forked from mtusi2026/mtusi2026lab2
130 lines
4.8 KiB
Python
130 lines
4.8 KiB
Python
#!/usr/bin/env python3
|
|
|
|
import concurrent.futures
|
|
import os
|
|
import socket
|
|
import subprocess
|
|
import sys
|
|
import time
|
|
import urllib.error
|
|
import urllib.request
|
|
import uuid
|
|
from pathlib import Path
|
|
|
|
ROOT = Path(__file__).resolve().parents[1]
|
|
IMAGE = os.environ.get("IMAGE", "mtusi-messenger:lab2")
|
|
NETWORK = os.environ.get("COMPOSE_NETWORK", "mtusi-lab2_default")
|
|
PORT = int(os.environ.get("SIGTERM_PORT", "18080"))
|
|
|
|
|
|
def run(*args, check=True, timeout=60):
|
|
return subprocess.run(
|
|
args, check=check, text=True, stdout=subprocess.PIPE,
|
|
stderr=subprocess.STDOUT, timeout=timeout,
|
|
)
|
|
|
|
def docker_run_args(name, port):
|
|
# Отдельный контейнер API в сети compose: те же PostgreSQL и Valkey, секрет только для чтения
|
|
return ["docker", "run", "-d", "--name", name, "--network", NETWORK,
|
|
"-p", f"127.0.0.1:{port}:8080",
|
|
"-v", f"{ROOT}/secrets/database_url:/run/secrets/database_url:ro",
|
|
"-e", "DATABASE_URL_FILE=/run/secrets/database_url",
|
|
"-e", "CACHE_URL=redis://valkey:6379/0",
|
|
IMAGE]
|
|
|
|
|
|
def wait_ready(base_url, timeout=60):
|
|
deadline = time.monotonic() + timeout
|
|
while time.monotonic() < deadline:
|
|
try:
|
|
with urllib.request.urlopen(base_url + "/health/ready", timeout=1) as response:
|
|
if response.status == 200:
|
|
return
|
|
except (urllib.error.URLError, ConnectionError, TimeoutError):
|
|
pass
|
|
time.sleep(0.2)
|
|
raise RuntimeError("Test container did not become ready")
|
|
|
|
|
|
def connection_rejected(base_url):
|
|
try:
|
|
with urllib.request.urlopen(base_url + "/health/ready", timeout=0.5):
|
|
return False
|
|
except urllib.error.HTTPError:
|
|
return False
|
|
except (urllib.error.URLError, ConnectionError, TimeoutError):
|
|
return True
|
|
|
|
|
|
def test_shutdown(incomplete_request):
|
|
name = "mtusi-messenger-sigterm-" + uuid.uuid4().hex[:8]
|
|
base_url = f"http://127.0.0.1:{PORT}"
|
|
scenario = "incomplete POST" if incomplete_request else "idle"
|
|
pending = None
|
|
try:
|
|
run(*docker_run_args(name, PORT))
|
|
wait_ready(base_url)
|
|
|
|
if incomplete_request:
|
|
pending = socket.create_connection(("127.0.0.1", PORT), timeout=3)
|
|
pending.sendall(
|
|
b"POST /api/v1/users HTTP/1.1\r\n"
|
|
b"Host: localhost\r\nContent-Type: application/json\r\n"
|
|
b"Content-Length: 100\r\nExpect: 100-continue\r\n\r\n"
|
|
)
|
|
response = b""
|
|
while b"\r\n\r\n" not in response:
|
|
part = pending.recv(1024)
|
|
if not part:
|
|
raise AssertionError("Connection closed before 100 Continue")
|
|
response += part
|
|
if b"100 Continue" not in response:
|
|
raise AssertionError(f"Expected 100 Continue, received {response!r}")
|
|
pending.sendall(b"{")
|
|
|
|
print(f"Scenario: {scenario}; docker stop --timeout 10 {name}", flush=True)
|
|
start = time.monotonic()
|
|
with concurrent.futures.ThreadPoolExecutor(max_workers=1) as executor:
|
|
stopped = executor.submit(run, "docker", "stop", "--timeout", "10", name)
|
|
deadline = start + 2
|
|
while not connection_rejected(base_url):
|
|
if time.monotonic() >= deadline:
|
|
raise AssertionError("New connections are still accepted during shutdown")
|
|
time.sleep(0.05)
|
|
rejected_after = time.monotonic() - start
|
|
stopped.result(timeout=12)
|
|
elapsed = time.monotonic() - start
|
|
|
|
exit_code = int(run("docker", "inspect", name, "--format", "{{.State.ExitCode}}").stdout)
|
|
if exit_code != 0:
|
|
raise AssertionError(f"Container exited with code {exit_code}, expected 0")
|
|
if elapsed > 10:
|
|
raise AssertionError(f"Shutdown exceeded 10 seconds: {elapsed:.3f}s")
|
|
if not connection_rejected(base_url):
|
|
raise AssertionError("API still accepts connections after shutdown")
|
|
|
|
logs = run("docker", "logs", name).stdout
|
|
if "Application shutdown complete" not in logs:
|
|
raise AssertionError("Application did not complete its shutdown handler")
|
|
print(f"PASS {scenario}: exit code 0; shutdown {elapsed:.3f}s; "
|
|
f"new connections rejected after {rejected_after:.3f}s")
|
|
finally:
|
|
if pending is not None:
|
|
pending.close()
|
|
run("docker", "rm", "-f", name, check=False)
|
|
|
|
|
|
def main():
|
|
print(f"Image: {IMAGE}")
|
|
test_shutdown(False)
|
|
test_shutdown(True)
|
|
print("PASS SIGTERM: both scenarios completed within 10 seconds")
|
|
|
|
|
|
if __name__ == "__main__":
|
|
try:
|
|
main()
|
|
except Exception as exc:
|
|
print(f"FAIL: {type(exc).__name__}: {exc}", file=sys.stderr)
|
|
sys.exit(1)
|