"""Проверки докера во временном контейнере""" import argparse from datetime import datetime, timezone import json import os import platform import socket import subprocess import time from urllib.error import URLError from urllib.request import urlopen from uuid import uuid4 from helpers import Client, ROOT def docker(*args): result = subprocess.run(["docker", *args], check=True, capture_output=True, text=True, timeout=60) return result.stdout.strip() def inspect(container): return json.loads(docker("inspect", container))[0] def wait_ready(container): subprocess.run([str(ROOT / "scripts/wait-ready.sh"), container], check=True, timeout=70) def check_shutdown(container, base_url, port): with socket.create_connection(("127.0.0.1", port), timeout=2) as pending: pending.sendall( b"POST /api/v1/users HTTP/1.1\r\nHost: localhost\r\n" b"Content-Type: application/json\r\nContent-Length: 1000\r\n" b"Expect: 100-continue\r\nConnection: close\r\n\r\n" ) assert b"100 Continue" in pending.recv(1024), "Сервер не начал читать тело запроса" pending.sendall(b'{"username":') started = time.monotonic() docker("kill", "--signal=TERM", container) first_refusal = None while inspect(container)["State"]["Running"]: assert time.monotonic() - started < 10, "SIGTERM: превышены 10 секунд" try: with urlopen(base_url + "/health/live", timeout=0.3): pass except (URLError, OSError): if first_refusal is None: first_refusal = time.monotonic() - started time.sleep(0.05) elapsed = time.monotonic() - started assert elapsed < 10, "SIGTERM: превышены 10 секунд" assert first_refusal is not None and first_refusal < elapsed, "Не показан отказ новых запросов при остановке" state = inspect(container)["State"] assert not state["OOMKilled"] and state["ExitCode"] in (0, 143), state result = subprocess.run(["docker", "logs", container], capture_output=True, text=True, check=True, timeout=10) logs = result.stdout + result.stderr assert "Application shutdown complete" in logs, "Нет подтверждения корректного завершения" try: with urlopen(base_url + "/health/live", timeout=0.5): raise AssertionError("Остановленный сервер отвечает") except (URLError, OSError): pass print(f"PASS: SIGTERM with unfinished request: {elapsed:.2f}s; new requests refused after {first_refusal:.2f}s; exit={state['ExitCode']}; OOM=false") def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--image", default="mtusi-messenger:lab2") args = parser.parse_args() container = "mtusi-messenger-lab2-check-" + uuid4().hex[:12] created = False print("UTC:", datetime.now(timezone.utc).isoformat()) print("Host:", platform.system(), platform.machine(), "Python", platform.python_version()) print("Docker:", docker("info", "--format", "{{.ServerVersion}} {{.Architecture}} CPUs={{.NCPU}} RAM={{.MemTotal}}")) revision = subprocess.run(["git", "rev-parse", "--short", "HEAD"], cwd=ROOT, capture_output=True, text=True) print("Base commit:", revision.stdout.strip() or "source snapshot", "(working tree may include final uncommitted changes)") print("Command: ./scripts/check-docker.sh") print("Container limits: 1 CPU, 256 MiB; no volumes; one API process") try: docker("run", "--detach", "--name", container, "--label", "mtusi.lab=2", "--cpus", "1", "--memory", "256m", "--publish", "127.0.0.1::8080", args.image) created = True wait_ready(container) before = inspect(container) port = int(before["NetworkSettings"]["Ports"]["8080/tcp"][0]["HostPort"]) base_url = f"http://127.0.0.1:{port}" print("Image:", before["Image"]) print("Python in image:", docker("exec", container, "python", "--version")) assert before["Mounts"] == [], "Обнаружены подключённые хранилища" assert before["HostConfig"]["Memory"] == 256 * 1024 * 1024 assert before["HostConfig"]["NanoCpus"] == 1_000_000_000 uid = docker("exec", container, "id", "-u") assert uid == "10001", "Сервер должен работать от непривилегированного пользователя" pid1 = docker("exec", container, "python", "-c", "from pathlib import Path; print(Path('/proc/1/cmdline').read_bytes().replace(b'\\0', b' ').decode().strip())") assert pid1 == "python -m src", pid1 print("PASS: UID=10001; PID 1=python -m src; Docker health=healthy") files = json.loads(docker("exec", container, "python", "-c", "import json; from pathlib import Path; print(json.dumps(sorted(p.name for p in Path('/app').iterdir())))")) assert files == ["requirements.txt", "src"], files failed_health = subprocess.run(["docker", "exec", "-e", "APP_PORT=1", container, "python", "-m", "src.healthcheck"], capture_output=True, timeout=10) assert failed_health.returncode == 1 print("PASS: image contains only sources and requirements; failed healthcheck returns 1") env = dict(os.environ, BASE_URL=base_url) subprocess.run([str(ROOT / "scripts/check.sh")], cwd=ROOT, env=env, check=True, timeout=120) client = Client(base_url) alice, bob, eve, chat = client.bootstrap() marker = "private-message-" + uuid4().hex first = client.message(alice, chat, marker)["json"] second = client.message(bob, chat, "Ответ второго участника")["json"] path = "/api/v1/chats/" + chat["id"] history = client.call("GET", path + "/messages", actor=alice, schema="MessagePage")["json"] assert {item["id"] for item in history["items"]} == {first["id"], second["id"]} client.call("GET", path, 404, actor=eve) result = subprocess.run(["docker", "logs", container], capture_output=True, text=True, check=True, timeout=10) logs = result.stdout + result.stderr assert marker not in logs and second["text"] not in logs assert "request_id=" in logs and "duration_ms=" in logs print("PASS: two members exchanged messages; outsider gets 404; logs contain no message text") docker("restart", "--time", "10", container) wait_ready(container) after = inspect(container) assert after["Image"] == before["Image"] assert after["State"]["StartedAt"] != before["State"]["StartedAt"] port = int(after["NetworkSettings"]["Ports"]["8080/tcp"][0]["HostPort"]) base_url = f"http://127.0.0.1:{port}" client = Client(base_url) client.call("GET", "/api/v1/users/me", 401, actor=alice) fresh = client.user("after_restart") client.call("GET", path, 404, actor=fresh) print("PASS: real restart with same image; old user gets 401; old chat gets 404") print("StartedAt before:", before["State"]["StartedAt"]) print("StartedAt after: ", after["State"]["StartedAt"]) check_shutdown(container, base_url, port) print("PASS: all Docker and API checks completed") finally: if created: docker("rm", "--force", container) print("Temporary test container removed") if __name__ == "__main__": main()