Files
mtusi2026lab3/scripts/benchmark_scale.py
T

81 lines
2.9 KiB
Python

#!/usr/bin/env python3
"""Repeatable closed-loop scaling experiment for lab3 grade 5."""
import argparse
import json
import subprocess
import sys
import time
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
OUTPUT = ROOT / "evidence" / "scale"
def run(command):
return subprocess.run(command, cwd=ROOT, check=True)
def wait_ready():
deadline = time.monotonic() + 60
while time.monotonic() < deadline:
result = subprocess.run(
["python", "-c", "import urllib.request; print(urllib.request.urlopen('http://localhost:8080/health/ready', timeout=2).status)"],
cwd=ROOT,
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL,
)
if result.returncode == 0:
return
time.sleep(1)
raise RuntimeError("API did not become ready")
def main():
parser = argparse.ArgumentParser()
parser.add_argument("--duration", type=float, default=15)
parser.add_argument("--concurrency", type=int, default=8)
args = parser.parse_args()
OUTPUT.mkdir(parents=True, exist_ok=True)
metadata = {
"hypothesis": "With a fixed API budget, two replicas should improve tail and throughput versus one; four replicas will converge toward PostgreSQL/LB limits.",
"duration_seconds": args.duration,
"concurrency": args.concurrency,
"fixed_budget": {"cpu": 2.0, "memory_mb": 1024},
}
(OUTPUT / "experiment.json").write_text(json.dumps(metadata, ensure_ascii=False, indent=2) + "\n")
fixed_runs = []
for count in (1, 2, 4):
run([sys.executable, str(ROOT / "scripts" / "scale_topology.py"), str(count),
"--total-cpus", "2", "--total-memory-mb", "1024"])
wait_ready()
dest = OUTPUT / f"fixed-{count}-replicas.json"
run([sys.executable, str(ROOT / "tests" / "load.py"),
"--duration", str(args.duration), "--concurrency", str(args.concurrency),
"--output", str(dest)])
fixed_runs.append(dest.name)
resource_runs = []
for total_cpus, memory_mb in ((1.0, 512), (2.0, 1024), (4.0, 2048)):
run([sys.executable, str(ROOT / "scripts" / "scale_topology.py"), "2",
"--total-cpus", str(total_cpus), "--total-memory-mb", str(memory_mb)])
wait_ready()
dest = OUTPUT / f"resources-{int(total_cpus)}cpu-{memory_mb}mb.json"
run([sys.executable, str(ROOT / "tests" / "load.py"),
"--duration", str(args.duration), "--concurrency", str(args.concurrency),
"--output", str(dest)])
resource_runs.append(dest.name)
summary = {
"fixed_budget_runs": fixed_runs,
"resource_growth_runs": resource_runs,
"raw_outputs": "Each JSON is the public load-test summary.",
}
(OUTPUT / "runs.json").write_text(json.dumps(summary, ensure_ascii=False, indent=2) + "\n")
print("Benchmark complete:", OUTPUT)
if __name__ == "__main__":
main()