add level 5

This commit is contained in:
Матвей
2026-10-14 15:53:07 +03:00
parent 516bb095ac
commit f2c4395693
13 changed files with 2226 additions and 30 deletions
+52
View File
@@ -0,0 +1,52 @@
#!/usr/bin/env python3
"""Renders Track 1 raw JSON results into a small dependency-free SVG chart."""
import json
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
ORDER = ["fixed-1", "fixed-2", "fixed-4", "growth-2", "growth-4"]
COLORS = {"fixed": "#2563eb", "growth": "#16a34a"}
def main() -> None:
raw = ROOT / "evidence" / "track1" / "raw"
values = []
for label in ORDER:
data = json.loads((raw / f"{label}.json").read_text(encoding="utf-8"))
values.append((label, data["load"]["successful_rps"], data["load"]["successful_latency_ms"]["p95"]))
maximum = max(value for _, value, _ in values)
width, height, bottom, chart_height = 820, 430, 355, 270
bars = []
for index, (label, rps, p95) in enumerate(values):
x = 70 + index * 145
bar_height = round(rps / maximum * chart_height)
y = bottom - bar_height
color = COLORS["fixed" if label.startswith("fixed") else "growth"]
bars.append(
f'<rect x="{x}" y="{y}" width="90" height="{bar_height}" fill="{color}"/>'
f'<text x="{x + 45}" y="{y - 8}" text-anchor="middle">{rps:.1f}</text>'
f'<text x="{x + 45}" y="{bottom + 20}" text-anchor="middle">{label}</text>'
f'<text x="{x + 45}" y="{bottom + 39}" text-anchor="middle" class="small">p95 {p95:.1f} ms</text>'
)
ticks = []
for value in range(0, int(maximum) + 100, 200):
y = bottom - round(value / maximum * chart_height)
ticks.append(f'<line x1="55" y1="{y}" x2="790" y2="{y}" class="grid"/><text x="48" y="{y + 4}" text-anchor="end">{value}</text>')
svg = f'''<svg xmlns="http://www.w3.org/2000/svg" width="{width}" height="{height}" viewBox="0 0 {width} {height}">
<style>text{{font:14px sans-serif;fill:#111827}} .small{{font-size:11px;fill:#4b5563}} .grid{{stroke:#d1d5db;stroke-width:1}} .legend{{font-size:12px}}</style>
<rect width="100%" height="100%" fill="white"/>
<text x="55" y="28" font-size="20" font-weight="bold">Track 1: successful RPS (closed-loop POST, concurrency 32)</text>
<text x="55" y="50" class="small">Blue: fixed API total 2 CPU / 1024 MiB. Green: API total 4 CPU / 2048 MiB.</text>
{''.join(ticks)}
<line x1="55" y1="{bottom}" x2="790" y2="{bottom}" stroke="#111827"/>
{''.join(bars)}
<text x="55" y="405" class="small">Data: evidence/track1/raw/*.json. Each point uses a fresh database volume; DB limit 0.75 CPU / 512 MiB.</text>
</svg>'''
destination = ROOT / "evidence" / "track1" / "scale.svg"
destination.write_text(svg + "\n", encoding="utf-8")
print(destination.relative_to(ROOT))
if __name__ == "__main__":
main()
+100
View File
@@ -0,0 +1,100 @@
#!/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": {
"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()