forked from mtusi2026/mtusi2026lab3
102 lines
4.4 KiB
Python
Executable File
102 lines
4.4 KiB
Python
Executable File
#!/usr/bin/env python3
|
|
"""One reproducible point for Lab 3, Level 5, Track 1."""
|
|
import argparse
|
|
import json
|
|
import os
|
|
from pathlib import Path
|
|
import subprocess
|
|
import sys
|
|
import threading
|
|
import time
|
|
|
|
|
|
ROOT = Path(__file__).resolve().parents[1]
|
|
COMPOSE = ["docker", "compose", "-p", "mtusi2026lab3bench", "-f", "compose.benchmark.yaml"]
|
|
|
|
|
|
def command(arguments: list[str], environment: dict[str, str] | None = None) -> subprocess.CompletedProcess:
|
|
return subprocess.run(arguments, cwd=ROOT, env=environment, check=True, text=True)
|
|
|
|
|
|
def compose(arguments: list[str], environment: dict[str, str] | None = None) -> subprocess.CompletedProcess:
|
|
return command(COMPOSE + arguments, environment)
|
|
|
|
|
|
def stats(container_ids: list[str]) -> list[dict]:
|
|
if not container_ids:
|
|
return []
|
|
output = subprocess.check_output(
|
|
["docker", "stats", "--no-stream", "--format", "{{json .}}", *container_ids],
|
|
cwd=ROOT,
|
|
text=True,
|
|
)
|
|
return [json.loads(line) for line in output.splitlines() if line.strip()]
|
|
|
|
|
|
def main() -> None:
|
|
parser = argparse.ArgumentParser(description=__doc__)
|
|
parser.add_argument("--label", required=True)
|
|
parser.add_argument("--replicas", type=int, required=True)
|
|
parser.add_argument("--api-cpus", required=True)
|
|
parser.add_argument("--api-memory", required=True)
|
|
parser.add_argument("--duration", type=float, default=15)
|
|
parser.add_argument("--concurrency", type=int, default=32)
|
|
parser.add_argument("--keep", action="store_true", help="Do not remove the isolated benchmark stack")
|
|
args = parser.parse_args()
|
|
if args.replicas < 1 or args.duration < 1 or args.concurrency < 1:
|
|
parser.error("replicas, duration and concurrency must be positive")
|
|
|
|
output = ROOT / "evidence" / "track1" / "raw" / f"{args.label}.json"
|
|
output.parent.mkdir(parents=True, exist_ok=True)
|
|
environment = os.environ.copy()
|
|
environment.update({"BENCH_API_CPUS": args.api_cpus, "BENCH_API_MEMORY": args.api_memory})
|
|
compose(["down", "--volumes", "--remove-orphans"], environment)
|
|
try:
|
|
compose(["up", "--build", "--detach", "--wait", "--scale", f"api={args.replicas}"], environment)
|
|
container_ids = subprocess.check_output(
|
|
COMPOSE + ["ps", "-q"], cwd=ROOT, env=environment, text=True
|
|
).split()
|
|
samples: list[dict] = []
|
|
loading = subprocess.Popen(
|
|
[
|
|
sys.executable, "tests/load.py", "--base-url", "http://localhost:8081",
|
|
"--duration", str(args.duration), "--concurrency", str(args.concurrency),
|
|
"--output", str(output.with_suffix(".load.json")),
|
|
],
|
|
cwd=ROOT,
|
|
)
|
|
while loading.poll() is None:
|
|
samples.append({"at_seconds": round(time.monotonic(), 3), "containers": stats(container_ids)})
|
|
time.sleep(1)
|
|
if loading.wait() != 0:
|
|
raise SystemExit("load generator failed")
|
|
load = json.loads(output.with_suffix(".load.json").read_text(encoding="utf-8"))
|
|
report = {
|
|
"label": args.label,
|
|
"topology": {
|
|
"load_balancer_image": "haproxy:3.0.11-alpine",
|
|
"api_replicas": args.replicas,
|
|
"api_cpu_per_replica": args.api_cpus,
|
|
"api_memory_per_replica": args.api_memory,
|
|
"api_cpu_total": round(args.replicas * float(args.api_cpus), 3),
|
|
"api_memory_total_mib": args.replicas * int(args.api_memory.removesuffix("M")),
|
|
"database_cpu": environment.get("BENCH_DB_CPUS", "0.75"),
|
|
"database_memory": environment.get("BENCH_DB_MEMORY", "512M"),
|
|
"load_balancer_cpu": environment.get("BENCH_LB_CPUS", "0.25"),
|
|
"load_balancer_memory": environment.get("BENCH_LB_MEMORY", "128M"),
|
|
},
|
|
"load": load,
|
|
"docker_stats_samples": samples,
|
|
"method": "Fresh PostgreSQL volume for this point; closed-loop POST messages, no automatic retries; Docker stats sampled about once a second.",
|
|
}
|
|
output.write_text(json.dumps(report, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
|
|
output.with_suffix(".load.json").unlink(missing_ok=True)
|
|
print(json.dumps({"saved": str(output.relative_to(ROOT)), "load": load}, ensure_ascii=False, indent=2))
|
|
finally:
|
|
if not args.keep:
|
|
compose(["down", "--volumes", "--remove-orphans"], environment)
|
|
|
|
|
|
if __name__ == "__main__":
|
|
main()
|