forked from mtusi2026/mtusi2026lab2
Завершить PostgreSQL, Redis-сессии, миграции, таймауты и диагностику. Зафиксировать собственные тесты и доказательства финального прогона: 43 PASS, 0 FAIL, 0 SKIP; 768 HTTP-запросов без ошибок. Добавить официальный отчёт с запуском, архитектурой, SQL-планами и ограничениями. PR отложен до завершения уровня 5.
116 lines
5.6 KiB
Python
116 lines
5.6 KiB
Python
#!/usr/bin/env python3
|
|
"""Compare real WAITAOF waits on a new Redis/volume using current Compose settings."""
|
|
import argparse
|
|
import hashlib
|
|
import json
|
|
import os
|
|
from pathlib import Path
|
|
import secrets
|
|
import socket
|
|
import subprocess
|
|
import tempfile
|
|
import time
|
|
|
|
ROOT = Path(__file__).resolve().parents[2]
|
|
|
|
|
|
def command(args, timeout=60):
|
|
process = subprocess.run(args, cwd=ROOT, capture_output=True, text=True, timeout=timeout)
|
|
if process.returncode:
|
|
raise RuntimeError("diagnostic command failed: " + " ".join(args[:3]))
|
|
return process.stdout
|
|
|
|
|
|
def sources():
|
|
paths = [*ROOT.glob("internal/**/*.go"), *ROOT.glob("cmd/**/*.go"),
|
|
*ROOT.glob("db/**/*.sql"), ROOT / "compose.yaml", ROOT / "go.mod", ROOT / "go.sum"]
|
|
return {str(p.relative_to(ROOT)): hashlib.sha256(p.read_bytes()).hexdigest()
|
|
for p in paths if p.is_file() and not p.name.endswith("_test.go")}
|
|
|
|
|
|
def main():
|
|
parser = argparse.ArgumentParser(description=__doc__)
|
|
parser.add_argument("--output", required=True, type=Path)
|
|
args = parser.parse_args()
|
|
output = args.output.resolve()
|
|
output.mkdir(parents=True, exist_ok=False)
|
|
project = "lab2-test-waitaof-" + secrets.token_hex(6)
|
|
container, volume = project + "-redis", project + "-data"
|
|
label = "com.docker.compose.project=" + project
|
|
before = sources()
|
|
summary = {"project": project, "status": "FAIL", "source_before": before}
|
|
volume_created = False
|
|
try:
|
|
# Read the Compose model in memory. Only the Redis profile is saved;
|
|
# application environment/credentials never enter diagnostic artifacts.
|
|
config = json.loads(command(["docker", "compose", "--project-directory", str(ROOT),
|
|
"-p", project, "-f", str(ROOT / "compose.yaml"),
|
|
"config", "--format", "json"]))
|
|
redis = config["services"]["redis"]
|
|
profile = {"image": redis["image"], "command": redis["command"]}
|
|
if not isinstance(profile["command"], list):
|
|
raise RuntimeError("Redis command must be an argv list")
|
|
image = json.loads(command(["docker", "image", "inspect", profile["image"]]))[0]
|
|
summary.update(redis_profile=profile, image_id=image["Id"], image_digests=image.get("RepoDigests", []))
|
|
# Run the inspected image ID, so a mutable tag cannot change mid-run.
|
|
with socket.socket() as reservation:
|
|
reservation.bind(("127.0.0.1", 0))
|
|
port = reservation.getsockname()[1]
|
|
command(["docker", "volume", "create", "--label", label, volume])
|
|
volume_created = True
|
|
command(["docker", "run", "-d", "--name", container, "--label", label,
|
|
"-p", f"127.0.0.1:{port}:6379", "--mount", f"type=volume,src={volume},dst=/data",
|
|
image["Id"], *profile["command"]])
|
|
for _ in range(60):
|
|
ping = subprocess.run(["docker", "exec", container, "redis-cli", "ping"],
|
|
capture_output=True, text=True, timeout=5)
|
|
if ping.returncode == 0 and ping.stdout.strip() == "PONG":
|
|
break
|
|
time.sleep(.2)
|
|
else:
|
|
raise RuntimeError("test Redis is not ready")
|
|
with tempfile.TemporaryDirectory(prefix=project + "-") as directory:
|
|
binary = Path(directory) / "compare-waitaof"
|
|
command(["go", "build", "-o", str(binary), "./student-tests/diagnostics/waitaof"], timeout=120)
|
|
env = dict(os.environ, WAITAOF_TEST_REDIS_ADDR=f"127.0.0.1:{port}")
|
|
process = subprocess.Popen([str(binary), "-output", str(output)], cwd=ROOT, env=env,
|
|
stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True)
|
|
# Per-command deadlines bound the client; 36 sequential samples.
|
|
try:
|
|
with (output / "client.log").open("w") as log:
|
|
for line in process.stdout:
|
|
log.write(line)
|
|
log.flush()
|
|
print(line, end="", flush=True)
|
|
code = process.wait(timeout=10)
|
|
finally:
|
|
if process.poll() is None:
|
|
process.terminate()
|
|
process.wait(timeout=10)
|
|
summary["client_exit"] = code
|
|
summary["status"] = "COMPLETE" if code == 0 else "FAIL"
|
|
except (OSError, RuntimeError, KeyError, ValueError, subprocess.SubprocessError) as error:
|
|
summary["failure"] = str(error)
|
|
finally:
|
|
after = sources()
|
|
summary["source_after"] = after
|
|
summary["production_source_changes"] = sorted(k for k in set(before) | set(after) if before.get(k) != after.get(k))
|
|
inspected = subprocess.run(["docker", "inspect", container], capture_output=True, text=True)
|
|
if inspected.returncode == 0:
|
|
owned = json.loads(inspected.stdout)[0]["Config"]["Labels"].get("com.docker.compose.project") == project
|
|
summary["container_cleanup"] = owned and subprocess.run(
|
|
["docker", "rm", "-f", container], capture_output=True).returncode == 0
|
|
else:
|
|
summary["container_cleanup"] = True
|
|
summary["volume_cleanup"] = not volume_created or subprocess.run(
|
|
["docker", "volume", "rm", volume], capture_output=True).returncode == 0
|
|
if not summary["container_cleanup"] or not summary["volume_cleanup"]:
|
|
summary["status"] = "FAIL"
|
|
(output / "runner-summary.json").write_text(json.dumps(summary, indent=2, ensure_ascii=False) + "\n")
|
|
print(summary["status"] + ": " + str(output), flush=True)
|
|
return 0 if summary["status"] == "COMPLETE" else 1
|
|
|
|
|
|
if __name__ == "__main__":
|
|
raise SystemExit(main())
|