forked from mtusi2026/mtusi2026lab2
128 lines
4.4 KiB
Python
128 lines
4.4 KiB
Python
#!/usr/bin/env python3
|
|
"""SIGTERM: процесс перестаёт принимать запросы и завершается не дольше чем за 10 секунд.
|
|
|
|
Во время проверки фоновый клиент непрерывно шлёт GET /health/live: до сигнала
|
|
ответы 200, после — отказ в соединении; ответов 5xx быть не должно.
|
|
"""
|
|
|
|
import argparse
|
|
import json
|
|
import os
|
|
import subprocess
|
|
import threading
|
|
import time
|
|
import urllib.error
|
|
import urllib.request
|
|
from pathlib import Path
|
|
|
|
ROOT = Path(__file__).resolve().parents[1]
|
|
DEFAULT_BASE_URL = json.loads((ROOT / "lab.json").read_text())["default_base_url"]
|
|
|
|
SHUTDOWN_LIMIT_SEC = 10
|
|
PROBE_INTERVAL_SEC = 0.02
|
|
|
|
|
|
class Prober(threading.Thread):
|
|
"""Фоновый клиент: каждое обращение — новое соединение"""
|
|
|
|
def __init__(self, url: str) -> None:
|
|
super().__init__(daemon=True)
|
|
self.url = url
|
|
self.stop = threading.Event()
|
|
self.ok: list[float] = []
|
|
self.refused: list[float] = []
|
|
self.server_errors = 0
|
|
|
|
def run(self) -> None:
|
|
while not self.stop.is_set():
|
|
try:
|
|
with urllib.request.urlopen(self.url, timeout=2) as response:
|
|
if response.status == 200:
|
|
self.ok.append(time.monotonic())
|
|
except urllib.error.HTTPError as error:
|
|
if error.code >= 500:
|
|
self.server_errors += 1
|
|
except OSError:
|
|
self.refused.append(time.monotonic())
|
|
time.sleep(PROBE_INTERVAL_SEC)
|
|
|
|
|
|
def main() -> None:
|
|
parser = argparse.ArgumentParser(description=__doc__)
|
|
parser.add_argument(
|
|
"--base-url", default=os.environ.get("BASE_URL") or DEFAULT_BASE_URL
|
|
)
|
|
parser.add_argument(
|
|
"--container", default=os.environ.get("CONTAINER", "messenger-lab2-api-1")
|
|
)
|
|
args = parser.parse_args()
|
|
|
|
logs = subprocess.Popen(
|
|
["docker", "logs", "--follow", "--since", "0s", args.container],
|
|
stdout=subprocess.PIPE,
|
|
stderr=subprocess.STDOUT,
|
|
text=True,
|
|
)
|
|
waiter = subprocess.Popen(
|
|
["docker", "wait", args.container], stdout=subprocess.PIPE, text=True
|
|
)
|
|
prober = Prober(args.base_url.rstrip("/") + "/health/live")
|
|
prober.start()
|
|
time.sleep(1)
|
|
if not prober.ok:
|
|
raise SystemExit("FAIL: API не отвечает до отправки SIGTERM")
|
|
|
|
sent_at = time.monotonic()
|
|
subprocess.run(
|
|
["docker", "kill", "--signal", "SIGTERM", args.container],
|
|
check=True,
|
|
capture_output=True,
|
|
)
|
|
exit_code = int(waiter.communicate(timeout=SHUTDOWN_LIMIT_SEC + 5)[0].strip())
|
|
exited_at = time.monotonic()
|
|
time.sleep(0.5)
|
|
prober.stop.set()
|
|
prober.join()
|
|
shutdown_log = logs.communicate(timeout=5)[0]
|
|
|
|
shutdown_sec = exited_at - sent_at
|
|
ok_after = [t for t in prober.ok if t > sent_at]
|
|
first_refused = min((t for t in prober.refused if t > sent_at), default=None)
|
|
print("Логи контейнера после SIGTERM:")
|
|
print(
|
|
"\n".join(line for line in shutdown_log.splitlines() if "/health/" not in line)
|
|
)
|
|
print(
|
|
json.dumps(
|
|
{
|
|
"container": args.container,
|
|
"exit_code": exit_code,
|
|
"shutdown_seconds": round(shutdown_sec, 3),
|
|
"limit_seconds": SHUTDOWN_LIMIT_SEC,
|
|
"probes_ok_before_sigterm": len(prober.ok) - len(ok_after),
|
|
"probes_ok_after_sigterm": len(ok_after),
|
|
"first_refused_after_sigterm_seconds": None
|
|
if first_refused is None
|
|
else round(first_refused - sent_at, 3),
|
|
"probes_refused_after_sigterm": len(prober.refused),
|
|
"server_errors_5xx": prober.server_errors,
|
|
},
|
|
indent=2,
|
|
)
|
|
)
|
|
if (
|
|
exit_code != 0
|
|
or shutdown_sec > SHUTDOWN_LIMIT_SEC
|
|
or prober.server_errors
|
|
or first_refused is None
|
|
):
|
|
raise SystemExit("FAIL: завершение по SIGTERM не соответствует требованиям")
|
|
print(
|
|
"PASS: SIGTERM завершил процесс за %.2f с, новые соединения отклоняются"
|
|
% shutdown_sec
|
|
)
|
|
|
|
|
|
if __name__ == "__main__":
|
|
main()
|