import argparse import json import os import re import statistics import subprocess import sys import tempfile import time import urllib.parse import urllib.request from pathlib import Path ROOT = Path(__file__).resolve().parents[1] os.chdir(ROOT) SERVICES = [ "api-1", "api-2", "dispatcher", "worker", ] MONITORED = SERVICES + [ "otel-collector", "prometheus", "loki", "tempo", ] MODES = { "baseline": ("0", "0.0"), "full": ("1", "1.0"), "optimized": ("1", "0.1"), "balanced": ("1", "1.0"), } METRICS = [ "otelcol_receiver_accepted_spans", "otelcol_receiver_refused_spans", "otelcol_exporter_sent_spans", "otelcol_exporter_send_failed_spans", "otelcol_receiver_accepted_log_records", "otelcol_receiver_refused_log_records", "otelcol_exporter_sent_log_records", "otelcol_exporter_send_failed_log_records", "otelcol_receiver_accepted_metric_points", "otelcol_receiver_refused_metric_points", ] def command(args, **kwargs): return subprocess.run(args, check=True, **kwargs) def prometheus(query): url = ( "http://localhost:9090/api/v1/query?" + urllib.parse.urlencode({"query": query}) ) with urllib.request.urlopen(url, timeout=10) as response: result = json.load(response) if result["status"] != "success": raise RuntimeError("Prometheus query failed") return result["data"]["result"] def snapshot(): result = {} for name in METRICS: rows = prometheus(f"sum({name})") result[name] = float(rows[0]["value"][1]) if rows else 0.0 return result def switch_mode(mode): enabled, ratio = MODES[mode] env = dict(os.environ) env["TELEMETRY_ENABLED"] = enabled env["TELEMETRY_TRACE_SAMPLE_RATIO"] = ratio env["TELEMETRY_BENCHMARK_ENABLED"] = "0" env["TELEMETRY_COLLECTOR_CONFIG"] = ( "config-balanced.yaml" if mode == "balanced" else "config.yaml" ) command( [ "docker", "compose", "up", "-d", "--no-deps", "otel-collector", ], env=env, ) time.sleep(20) command( [ "docker", "compose", "up", "-d", "--no-deps", *SERVICES, ], env=env, ) deadline = time.monotonic() + 120 while time.monotonic() < deadline: ready = True for service in ["api-1", "api-2"]: cid = subprocess.check_output( ["docker", "compose", "ps", "-q", service], text=True, ).strip() if not cid: ready = False break status = subprocess.check_output( [ "docker", "inspect", "--format", "{{.State.Health.Status}}", cid, ], text=True, ).strip() if status != "healthy": ready = False break if ready: break time.sleep(3) else: raise RuntimeError("API replicas are not healthy") command(["make", "test"]) time.sleep(15) def container_ids(): result = {} for service in MONITORED: cid = subprocess.check_output( ["docker", "compose", "ps", "-q", service], text=True, ).strip() if not cid: raise RuntimeError(f"Container missing: {service}") result[cid[:12]] = service return result def memory_mib(value): value = value.split("/")[0].strip() match = re.fullmatch(r"([\d.]+)\s*([A-Za-z]+)", value) if not match: raise ValueError(f"Unknown memory format: {value}") number, unit = match.groups() factors = { "B": 1 / 1048576, "KiB": 1 / 1024, "MiB": 1, "GiB": 1024, "kB": 1000 / 1048576, "MB": 1000000 / 1048576, "GB": 1000000000 / 1048576, } return float(number) * factors[unit] def docker_sample(ids): output = subprocess.check_output( [ "docker", "stats", "--no-stream", "--format", "{{json .}}", *ids, ], text=True, ) result = {"timestamp": time.time(), "services": {}} for line in output.splitlines(): row = json.loads(line) service = ids[row["ID"][:12]] result["services"][service] = { "cpu_percent": float(row["CPUPerc"].rstrip("%")), "memory_mib": memory_mib(row["MemUsage"]), } return result def summarize_resources(samples): result = {} groups = { **{service: [service] for service in MONITORED}, "application_total": SERVICES, "observability_total": [ "otel-collector", "prometheus", "loki", "tempo" ], } for name, services in groups.items(): cpu = [] ram = [] for sample in samples: rows = sample["services"] if all(service in rows for service in services): cpu.append(sum( rows[service]["cpu_percent"] for service in services )) ram.append(sum( rows[service]["memory_mib"] for service in services )) if cpu: result[name] = { "samples": len(cpu), "cpu_mean_percent": round(statistics.mean(cpu), 3), "cpu_peak_percent": round(max(cpu), 3), "ram_mean_mib": round(statistics.mean(ram), 3), "ram_peak_mib": round(max(ram), 3), } return result def experiment(mode, repeat, args): name = f"{mode}-{repeat}" output = ROOT / "evidence" / f"grade5-{name}.json" print(f"\n=== Experiment {name} ===", flush=True) switch_mode(mode) ids = container_ids() with tempfile.TemporaryDirectory() as directory: marker = Path(directory) / "start" process = subprocess.Popen([ sys.executable, "scripts/benchmark_telemetry.py", "--mode", name, "--requests", str(args.requests), "--rate", str(args.rate), "--workers", str(args.workers), "--warmup", str(args.warmup), "--start-marker", str(marker), "--output", str(output), ]) try: deadline = time.monotonic() + 180 while not marker.exists(): if process.poll() is not None: raise RuntimeError("Benchmark exited before measurement") if time.monotonic() > deadline: raise RuntimeError("Benchmark warmup timeout") time.sleep(0.1) before = snapshot() marker.unlink() samples = [] while process.poll() is None: samples.append(docker_sample(ids)) time.sleep(1) if process.wait() != 0: raise RuntimeError("Benchmark failed") finally: if process.poll() is None: process.terminate() process.wait() time.sleep(40 if mode == "balanced" else 15) after = snapshot() report = json.loads(output.read_text()) samples = [ sample for sample in samples if report["started_at_unix"] <= sample["timestamp"] <= report["finished_at_unix"] ] if not samples: raise RuntimeError("No resource samples") deltas = { name: round(after[name] - before[name], 3) for name in METRICS } if any(value < 0 for value in deltas.values()): raise RuntimeError("Collector counter reset detected") report["collector_before"] = before report["collector_after"] = after report["collector_deltas"] = deltas report["resources"] = summarize_resources(samples) report["resource_samples"] = samples output.write_text( json.dumps(report, indent=2, ensure_ascii=False) + "\n" ) print(f"Saved: {output}", flush=True) def main(): parser = argparse.ArgumentParser() parser.add_argument("--requests", type=int, default=1200) parser.add_argument("--rate", type=float, default=20) parser.add_argument("--workers", type=int, default=16) parser.add_argument("--warmup", type=int, default=100) parser.add_argument("--repeats", type=int, default=3) parser.add_argument("--mode", choices=list(MODES)) args = parser.parse_args() if min( args.requests, args.rate, args.workers, args.repeats ) <= 0 or args.warmup < 0: parser.error("Invalid experiment parameters") orders = [ ["baseline", "full", "optimized"], ["full", "optimized", "baseline"], ["optimized", "baseline", "full"], ] try: for repeat in range(1, args.repeats + 1): selected = ( [args.mode] if args.mode else orders[(repeat - 1) % len(orders)] ) for mode in selected: experiment(mode, repeat, args) finally: print("\nRestoring full telemetry", flush=True) switch_mode("full") if __name__ == "__main__": main()