Files
mtusi2026lab3/student-tests/track1_benchmark.py
T

386 lines
14 KiB
Python

#!/usr/bin/env python3
"""Repeatable 1/2/4 replica throughput experiment with Docker resource samples."""
import argparse
import json
import math
import platform
from pathlib import Path
import re
import subprocess
import sys
import tempfile
import time
import hashlib
ROOT = Path(__file__).resolve().parents[1]
LOAD_TEST = ROOT / "tests" / "load.py"
OUTPUT_DIR = ROOT / "evidence" / "track1"
COMPOSE = ["docker", "compose", "--env-file", ".env"]
def run(command, *, env=None, capture=True):
return subprocess.run(
command,
cwd=ROOT,
env=env,
check=True,
text=True,
stdout=subprocess.PIPE if capture else None,
stderr=subprocess.PIPE if capture else None,
)
def compose_environment(cpu_limit, memory_limit):
import os
env = os.environ.copy()
env["API_CPU_LIMIT"] = cpu_limit
env["API_MEMORY_LIMIT"] = memory_limit
return env
def database_counts():
query = (
"SELECT json_build_object("
"'users', (SELECT count(*) FROM users), "
"'chats', (SELECT count(*) FROM chats), "
"'messages', (SELECT count(*) FROM messages), "
"'sessions', (SELECT count(*) FROM sessions), "
"'idempotency_records', (SELECT count(*) FROM idempotency_records)"
")::text"
)
result = run(
COMPOSE
+ [
"exec",
"-T",
"postgres",
"psql",
"-X",
"-qAt",
"-U",
"messenger",
"-d",
"messenger",
"-c",
query,
]
)
return json.loads(result.stdout)
def create_database_snapshot(destination):
with destination.open("wb") as dump:
result = subprocess.run(
COMPOSE + ["exec", "-T", "postgres", "pg_dump", "-Fc", "-U", "messenger", "-d", "messenger"],
cwd=ROOT,
check=False,
stdout=dump,
stderr=subprocess.PIPE,
)
if result.returncode:
raise RuntimeError("failed to create PostgreSQL baseline snapshot: " + result.stderr.decode(errors="replace"))
digest_builder = hashlib.sha256()
with destination.open("rb") as dump:
for chunk in iter(lambda: dump.read(1024 * 1024), b""):
digest_builder.update(chunk)
digest = digest_builder.hexdigest()
return digest, database_counts()
def restore_database_snapshot(snapshot, baseline_counts, api_replicas, cpu_limit, memory_limit):
env = compose_environment(cpu_limit, memory_limit)
run(COMPOSE + ["stop", "api"])
with snapshot.open("rb") as dump:
result = subprocess.run(
COMPOSE
+ [
"exec",
"-T",
"postgres",
"pg_restore",
"-U",
"messenger",
"--clean",
"--if-exists",
"--no-owner",
"--no-acl",
"--exit-on-error",
"--dbname=messenger",
],
cwd=ROOT,
check=False,
stdin=dump,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
)
if result.returncode:
raise RuntimeError("failed to restore PostgreSQL baseline snapshot: " + result.stderr.decode(errors="replace"))
restored_counts = database_counts()
if restored_counts != baseline_counts:
raise RuntimeError(
"restored PostgreSQL baseline has different row counts: "
+ json.dumps(restored_counts, sort_keys=True)
)
run(
COMPOSE
+ [
"up",
"-d",
"--no-deps",
"--build",
"--force-recreate",
"--scale",
f"api={api_replicas}",
"--wait",
"--wait-timeout",
"120",
"api",
],
env=env,
)
def docker_stats():
containers = run(
["docker", "compose", "--env-file", ".env", "ps", "-q"],
).stdout.splitlines()
if not containers:
return []
result = run(
[
"docker",
"stats",
"--no-stream",
"--format",
"{{.Name}}|{{.CPUPerc}}|{{.MemUsage}}",
*containers,
]
)
samples = []
for line in result.stdout.splitlines():
name, cpu, memory = line.split("|", 2)
used = memory.split("/", 1)[0].strip()
samples.append(
{
"container": name,
"service": "api" if "-api-" in name else "postgres" if "-postgres-" in name else "load_balancer",
"cpu_percent": float(cpu.rstrip("%")),
"memory_bytes": parse_bytes(used),
}
)
return samples
def parse_bytes(value):
match = re.fullmatch(r"([0-9.]+)\s*([KMG]i?B|B)", value)
if not match:
return None
amount = float(match.group(1))
unit = match.group(2)
power = {"B": 0, "KB": 1, "KiB": 1, "MB": 2, "MiB": 2, "GB": 3, "GiB": 3}[unit]
return round(amount * 1024**power)
def run_load(name, duration, concurrency, repetition, base_url):
output = OUTPUT_DIR / f"{name}-run-{repetition}.json"
command = [
sys.executable,
str(LOAD_TEST),
"--base-url",
base_url,
"--duration",
str(duration),
"--concurrency",
str(concurrency),
"--output",
str(output.relative_to(ROOT)),
]
process = subprocess.Popen(
command,
cwd=ROOT,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
text=True,
)
samples = []
while process.poll() is None:
samples.extend(docker_stats())
time.sleep(1)
stdout, stderr = process.communicate()
if process.returncode:
raise RuntimeError(f"load run failed:\n{stdout}\n{stderr}")
metrics = json.loads(output.read_text(encoding="utf-8"))
metrics["resource_samples"] = samples
return metrics
def system_info():
def command_output(command):
try:
return run(command).stdout.strip()
except (OSError, subprocess.CalledProcessError):
return "unavailable"
return {
"platform": platform.platform(),
"processor": platform.processor() or "unavailable",
"cpu_count": __import__("os").cpu_count(),
"host_memory_bytes": command_output(["sysctl", "-n", "hw.memsize"]),
"docker_server": command_output(["docker", "version", "--format", "{{.Server.Version}}"]),
"docker_compose": command_output(["docker", "compose", "version", "--short"]),
}
def configure_limits(count, phase):
if phase == "fixed":
return f"{1 / count:.4f}", f"{512 // count}M"
return "1.0", "512M"
def experiment_case(count, phase, args, snapshot, snapshot_hash, baseline_counts):
cpu_limit, memory_limit = configure_limits(count, phase)
restore_database_snapshot(snapshot, baseline_counts, count, cpu_limit, memory_limit)
run_load(f"{phase}-{count}-warmup", args.warmup, args.concurrency, 0, args.base_url)
warmup_counts = database_counts()
if warmup_counts == baseline_counts:
raise RuntimeError("warm-up did not create synthetic workload data")
repetitions = []
for repetition in range(1, args.repetitions + 1):
restore_database_snapshot(snapshot, baseline_counts, count, cpu_limit, memory_limit)
repetitions.append(run_load(f"{phase}-{count}", args.duration, args.concurrency, repetition, args.base_url))
if database_counts() == baseline_counts:
raise RuntimeError(f"{phase}-{count} repetition {repetition} did not write benchmark data")
return {
"phase": phase,
"api_replicas": count,
"per_replica_cpu_limit": cpu_limit,
"per_replica_memory_limit": memory_limit,
"total_api_cpu_limit": round(float(cpu_limit) * count, 4),
"total_api_memory_limit_mib": int(memory_limit[:-1]) * count,
"warmup_seconds": args.warmup,
"baseline_row_counts": baseline_counts,
"baseline_snapshot_sha256": snapshot_hash,
"each_repetition_restored_same_baseline": True,
"repetitions": repetitions,
}
def make_graph(cases):
width, height = 900, 420
margin = 60
values = [
(
f"{case['phase']} / {case['api_replicas']}",
sum(run["successful_rps"] for run in case["repetitions"]) / len(case["repetitions"]),
"#3572A5" if case["phase"] == "fixed" else "#E38B29",
)
for case in cases
]
top = max((value for _, value, _ in values), default=1) or 1
graph_height = height - 2 * margin
bar_width = 78
gap = (width - 2 * margin - bar_width * len(values)) / max(1, len(values) - 1)
parts = [
f'<svg xmlns="http://www.w3.org/2000/svg" width="{width}" height="{height}" viewBox="0 0 {width} {height}">',
'<rect width="100%" height="100%" fill="white"/>',
'<text x="450" y="28" text-anchor="middle" font-family="sans-serif" font-size="18">API scaling: average successful RPS</text>',
f'<line x1="{margin}" y1="{height-margin}" x2="{width-margin}" y2="{height-margin}" stroke="#333"/>',
]
for index, (label, value, color) in enumerate(values):
x = margin + index * (bar_width + gap)
bar_height = value / top * graph_height
y = height - margin - bar_height
parts.append(f'<rect x="{x:.1f}" y="{y:.1f}" width="{bar_width}" height="{bar_height:.1f}" fill="{color}"/>')
parts.append(f'<text x="{x+bar_width/2:.1f}" y="{max(48,y-8):.1f}" text-anchor="middle" font-family="sans-serif" font-size="12">{value:.1f}</text>')
parts.append(f'<text x="{x+bar_width/2:.1f}" y="{height-margin+20}" text-anchor="middle" font-family="sans-serif" font-size="12">{label}</text>')
parts.append("</svg>")
(OUTPUT_DIR / "throughput.svg").write_text("\n".join(parts) + "\n", encoding="utf-8")
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--duration", type=int, default=30)
parser.add_argument("--warmup", type=int, default=5)
parser.add_argument("--concurrency", type=int, default=16)
parser.add_argument("--repetitions", type=int, default=3)
parser.add_argument("--base-url", default="http://127.0.0.1:8080")
args = parser.parse_args()
if not 1 <= args.duration <= 3600 or not 1 <= args.warmup <= 600:
parser.error("duration and warmup must be positive and bounded")
if not 1 <= args.concurrency <= 128 or not 1 <= args.repetitions <= 10:
parser.error("concurrency or repetitions out of range")
OUTPUT_DIR.mkdir(parents=True, exist_ok=True)
results_file = OUTPUT_DIR / "results.json"
with tempfile.TemporaryDirectory(prefix="lab3-track1-") as temporary_directory:
snapshot = Path(temporary_directory) / "baseline.dump"
run(COMPOSE + ["stop", "api"])
baseline_counts = None
try:
snapshot_hash, baseline_counts = create_database_snapshot(snapshot)
cases = []
for phase, replica_counts in (("fixed", (1, 2, 4)), ("growth", (1, 2, 4, 8))):
for count in replica_counts:
cases.append(
experiment_case(count, phase, args, snapshot, snapshot_hash, baseline_counts)
)
summary = {
"method": (
"closed-loop POST message workload via HAProxy; same concurrency and per-run "
"restored PostgreSQL custom-format baseline snapshot"
),
"database_baseline": {
"snapshot_sha256": snapshot_hash,
"row_counts": baseline_counts,
"restore_before_each_warmup_and_measured_repetition": True,
"state_after_experiment": "baseline restored; all synthetic benchmark writes removed",
},
"system": system_info(),
"database_and_lb_limits": {"postgres": "1 CPU / 1 GiB", "HAProxy": "0.5 CPU / 128 MiB"},
"client_concurrency": args.concurrency,
"requested_duration_seconds": args.duration,
"repetitions_per_case": args.repetitions,
"cases": cases,
}
results_file.write_text(
json.dumps(summary, ensure_ascii=False, indent=2) + "\n",
encoding="utf-8",
)
make_graph(cases)
for case in cases:
values = [run["successful_rps"] for run in case["repetitions"]]
deviation = math.sqrt(sum((value - sum(values) / len(values)) ** 2 for value in values) / len(values))
print(
f"{case['phase']:6} replicas={case['api_replicas']} "
f"mean_rps={sum(values) / len(values):.2f} stdev={deviation:.2f}"
)
print(f"Evidence saved under {OUTPUT_DIR.relative_to(ROOT)}")
finally:
if baseline_counts is not None:
restore_database_snapshot(snapshot, baseline_counts, 2, "1.0", "512M")
else:
run(
COMPOSE
+ [
"up",
"-d",
"--no-deps",
"--build",
"--force-recreate",
"--scale",
"api=2",
"--wait",
"--wait-timeout",
"120",
"api",
],
env=compose_environment("1.0", "512M"),
)
if __name__ == "__main__":
main()