#!/usr/bin/env python3 """Lab 1, track 1: isolated matrix, integrity checks and paired comparison. Requires Python 3.9+, Docker, Go 1.27.1+. Standard libraries only; macOS/Linux. Does not edit the application or perform Git mutations. """ import argparse import csv import datetime as dt import hashlib import itertools import json import os from pathlib import Path import platform import shutil import statistics import subprocess import sys import tempfile import threading import time import urllib.error import urllib.request import uuid ROOT = Path(__file__).resolve().parents[1] GENERATOR = ROOT / "student-tests/track1_load.go" def command(args, timeout=60, required=True, **kwargs): result = subprocess.run(args, cwd=ROOT, capture_output=True, text=True, timeout=timeout, **kwargs) if required and result.returncode: raise RuntimeError("command failed: %s (exit %d)" % (args[0], result.returncode)) return result def docker(*args): return command(["docker", *args]).stdout.strip() def inspect(name): return json.loads(docker("inspect", name))[0] def digest(paths): h = hashlib.sha256() for path in sorted(paths): h.update(str(path.relative_to(ROOT)).encode() + b"\0" + path.read_bytes() + b"\0") return h.hexdigest() def save(path, value): path.parent.mkdir(parents=True, exist_ok=True) temporary = path.with_suffix(path.suffix + ".tmp") temporary.write_text(json.dumps(value, ensure_ascii=False, indent=2) + "\n") temporary.replace(path) def numbers(value): result = [int(x) for x in value.split(",")] if len(set(result)) != len(result) or any(x <= 0 for x in result): raise argparse.ArgumentTypeError("expected distinct positive integers") return result def compile_generator(directory): target = Path(directory) / "track1-load" environment = dict(os.environ, GOCACHE=str(Path(directory) / "go-cache")) result = command(["go", "build", "-o", str(target), str(GENERATOR)], timeout=180, required=False, env=environment) if result.returncode: raise RuntimeError("generator compilation failed: " + result.stderr.strip()) return target def build_image(args, output): if not args.build: return {"performed": False, "source_image_mapping": "unverified: existing image"} with tempfile.TemporaryDirectory(prefix="highload-track1-context-") as directory: for relative in filter(None, command(["git", "ls-files", "-z"]).stdout.split("\0")): source = ROOT / relative if source.is_file(): target = Path(directory) / relative target.parent.mkdir(parents=True, exist_ok=True) shutil.copy2(source, target) result = command(["docker", "build", "--progress=plain", "-t", args.image, directory], timeout=300, required=False) log = output.with_name(output.stem + "-build.txt") log.write_text(result.stdout + result.stderr) if result.returncode: raise RuntimeError("application Docker build failed; see " + str(log)) return {"performed": True, "exit_code": result.returncode, "log": str(log.relative_to(ROOT)) if log.is_relative_to(ROOT) else str(log), "context": "current tracked working files; not a committed clone"} def start_container(image, args): name = "highload-track1-" + uuid.uuid4().hex[:12] try: docker("run", "-d", "--name", name, "--cpus=" + str(args.cpus), "--memory=" + str(args.memory_mib) + "m", "--memory-swap=" + str(args.memory_mib) + "m", "--log-opt", "max-size=10m", "--log-opt", "max-file=1", "-p", "127.0.0.1::8080", "-e", "APP_HOST=0.0.0.0", "-e", "APP_PORT=8080", image) port = inspect(name)["NetworkSettings"]["Ports"]["8080/tcp"][0]["HostPort"] base = "http://127.0.0.1:" + port deadline = time.monotonic() + 20 while time.monotonic() < deadline: try: with urllib.request.urlopen(base + "/health/ready", timeout=1) as response: if response.status == 200: return name, base except (urllib.error.URLError, OSError): pass time.sleep(0.1) raise RuntimeError("API did not become ready") except BaseException: command(["docker", "rm", "--force", name], required=False) raise class Sampler: """PID 1 RSS and cgroup-v2 CPU/memory. Only samples inside the phase are used.""" files = ("/proc/1/status", "/sys/fs/cgroup/cpu.stat", "/sys/fs/cgroup/memory.current", "/sys/fs/cgroup/memory.events") def __init__(self, name, interval): self.name, self.interval = name, interval self.stop_event = threading.Event() self.samples, self.errors = [], [] self.thread = threading.Thread(target=self.loop, daemon=True) def loop(self): while not self.stop_event.is_set(): started = time.monotonic() try: result = command(["docker", "exec", self.name, "awk", 'FNR == 1 {print "FILE " FILENAME} {print}', *self.files], timeout=4, required=False) if result.returncode: raise RuntimeError("resource sampling failed (container stopped or cgroup v2 unavailable)") sections, current = {}, None for line in result.stdout.splitlines(): if line.startswith("FILE "): current = line[5:] sections[current] = [] elif current: sections[current].append(line) status = dict(line.split(":", 1) for line in sections[self.files[0]] if ":" in line) cpu = dict(line.split() for line in sections[self.files[1]]) events = dict(line.split() for line in sections[self.files[3]]) self.samples.append({"started": started, "finished": time.monotonic(), "rss_bytes": int(status["VmRSS"].split()[0]) * 1024, "cgroup_memory_bytes": int(sections[self.files[2]][0]), "cpu_usage_usec": int(cpu["usage_usec"]), "oom_kill_count": int(events.get("oom_kill", 0))}) except (RuntimeError, ValueError, KeyError, subprocess.SubprocessError) as exc: self.errors.append(str(exc)) self.stop_event.wait(max(0, self.interval - (time.monotonic() - started))) def finish(self, started, ended, cpus): self.stop_event.set() self.thread.join(timeout=5) samples = [s for s in self.samples if s["started"] >= started and s["finished"] <= ended] if self.errors or len(samples) < 2: raise RuntimeError(self.errors[0] if self.errors else "fewer than two resource samples; increase duration") first, last = samples[0], samples[-1] window = last["finished"] - first["finished"] cores = (last["cpu_usage_usec"] - first["cpu_usage_usec"]) / 1e6 / window rows = [{"seconds": round(s["finished"] - started, 4), "rss_bytes": s["rss_bytes"], "cgroup_memory_bytes": s["cgroup_memory_bytes"], "cpu_usage_usec": s["cpu_usage_usec"], "oom_kill_count": s["oom_kill_count"]} for s in samples] return {"sample_interval_seconds": self.interval, "sample_count": len(rows), "sample_window_seconds": window, "mean_cpu_cores": cores, "mean_cpu_percent_of_limit": 100 * cores / cpus, "rss_first_bytes": first["rss_bytes"], "rss_peak_observed_bytes": max(s["rss_bytes"] for s in samples), "cgroup_memory_peak_observed_bytes": max(s["cgroup_memory_bytes"] for s in samples), "oom_kill_count": max(s["oom_kill_count"] for s in samples), "samples": rows, "method": "RSS: /proc/1/status VmRSS. CPU: delta cgroup-v2 usage_usec / sample window. cgroup memory includes cache and sampling processes; it is not RSS. Peaks are sampled, not exact maxima."} def invoke(binary, name, base, args, history=203, concurrency=10, workload="read", mode="load"): invocation = [str(binary), "-base-url", base, "-mode", mode, "-history", str(history), "-concurrency", str(concurrency), "-duration", str(args.duration), "-warmup", str(args.warmup), "-timeout", str(args.timeout), "-page-size", str(args.page_size), "-payload-bytes", str(args.payload_bytes), "-workload", workload] child = subprocess.Popen(invocation, cwd=ROOT, text=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) sampler, measurement_start, metrics, resources = None, None, None, None failure = None # Generators should not hang in setup or verification; no shell process is spawned. timer = threading.Timer(max(120, history * args.timeout / 10 + args.duration + args.warmup + 30), child.kill) timer.start() try: for line in child.stdout: event = json.loads(line) kind = event["event"] if kind == "measurement_start": measurement_start = time.monotonic() sampler = Sampler(name, args.sample_interval) sampler.thread.start() elif kind == "measurement_complete": resources = sampler.finish(measurement_start, time.monotonic(), args.cpus) elif kind == "result": metrics = event["data"] elif kind == "failure": failure = event["data"]["reason"] code = child.wait(timeout=10) if code or metrics is None: raise RuntimeError(failure or "generator failed (exit %d)" % code) if mode == "load" and resources is None: raise RuntimeError("generator omitted resource measurement phase") return {"generator": metrics, "resources": resources, "exit_code": code} finally: timer.cancel() if child.poll() is None: child.kill() child.wait() if sampler: sampler.stop_event.set() sampler.thread.join(timeout=5) child.stdout.close() child.stderr.close() def preflight(binary, image, args): name, base = start_container(image, args) try: results = [] for invocation in (["make", "check"], ["make", "test", "BASE_URL=" + base], [sys.executable, "student-tests/level4.py", "--base-url", base]): result = command(invocation, required=False) results.append({"command": " ".join(invocation), "exit_code": result.returncode, "output": (result.stdout + result.stderr).strip()}) if result.returncode: raise RuntimeError("preflight failed: " + invocation[0]) return {"status": "PASS", "contract_checks": results, "track1_correctness": invoke(binary, name, base, args, mode="check")} finally: command(["docker", "rm", "--force", name], required=False) def write_csv(output, cases): path = output.with_suffix(".csv") fields = ["workload", "history", "concurrency", "repeat", "status", "read_rps", "read_p50_ms", "read_p95_ms", "read_p99_ms", "write_rps", "write_p95_ms", "errors", "rss_peak_mib", "cpu_percent_of_limit", "client_cpu_cores"] with path.open("w", newline="") as stream: writer = csv.DictWriter(stream, fieldnames=fields) writer.writeheader() for case in cases: row = {k: case.get(k) for k in fields[:5]} if case.get("result"): result = case["result"] metrics = result["generator"]["metrics"] read, write, resources = metrics["read"], metrics["write"], result["resources"] row.update(read_rps=read["successful_rps"], write_rps=write["successful_rps"], write_p95_ms=write["successful_latency_ms"]["p95"], errors=read["failed_requests"] + write["failed_requests"], rss_peak_mib=resources["rss_peak_observed_bytes"] / 1048576, cpu_percent_of_limit=resources["mean_cpu_percent_of_limit"], client_cpu_cores=metrics["client_cpu_cores"]) for p in ("p50", "p95", "p99"): row["read_" + p + "_ms"] = read["successful_latency_ms"][p] writer.writerow(row) def run_experiment(args): output = (ROOT / args.output).resolve() if output.exists(): raise RuntimeError("output already exists; choose a new path to preserve earlier measurements") if args.command == "run" and (len(args.histories) < 3 or len(args.concurrency) < 3): raise RuntimeError("track 1 requires at least three history sizes and three concurrency levels") if any(h < 2 * args.page_size for h in args.histories) or args.duration < max(2, args.sample_interval * 4): raise RuntimeError("history must fit two full pages; duration must allow at least four samples") output.parent.mkdir(parents=True, exist_ok=True) paths = [ROOT / p for p in ("Dockerfile", ".dockerignore", "go.mod", "go.sum")] paths += list((ROOT / "cmd").rglob("*.go")) + list((ROOT / "internal").rglob("*.go")) environment = {"system": platform.system(), "architecture": platform.machine(), "logical_cpus": os.cpu_count()} if platform.system() == "Darwin": hardware = command(["sysctl", "-n", "machdep.cpu.brand_string", "hw.memsize"]).stdout.splitlines() environment.update(cpu=hardware[0], memory_bytes=int(hardware[1])) info = json.loads(docker("info", "--format", "{{json .}}")) if str(info.get("CgroupVersion")) != "2": raise RuntimeError("resource collector currently requires Linux cgroup v2") report = {"schema": 1, "status": "RUNNING", "label": args.label, "started_at_utc": dt.datetime.now(dt.timezone.utc).isoformat(), "invocation": ["python3", "student-tests/track1.py", *sys.argv[1:]], "git_head": command(["git", "rev-parse", "HEAD"]).stdout.strip(), "uncommitted_working_files": bool(command(["git", "status", "--porcelain"]).stdout), "working_source_sha256": digest(paths), "generator_sha256": digest([GENERATOR, Path(__file__).resolve()]), "host": environment, "docker": {k: info.get(k) for k in ("ServerVersion", "Architecture", "NCPU", "MemTotal", "CgroupVersion")}, "limits": {"cpus": args.cpus, "memory_bytes": args.memory_mib * 1048576, "memory_swap_bytes": args.memory_mib * 1048576}, "method": {"histories": args.histories, "concurrency": args.concurrency, "workloads": args.workloads, "duration_seconds": args.duration, "warmup_seconds": args.warmup, "repeats": args.repeats, "page_size": args.page_size, "payload_bytes": args.payload_bytes, "timeout_seconds": args.timeout, "sample_interval_seconds": args.sample_interval, "seed_clients": 10, "read_pages": "first, middle, last full page; round robin", "fresh_container_per_case": True, "order": "repeat, history, concurrency, workload"}, "cases": [], "limitations": ["PASS validates the experiment and data integrity, not grade 5 or improvement.", "Closed-loop generator has coordinated omission; successes and errors are separate.", "Generator and API share one host; Docker sampling consumes a small part of container CPU.", "RSS is process residency, not heap size. Sampled peaks can miss short spikes."]} save(output, report) try: print("BUILD: application image and standalone generator", flush=True) report["build"] = build_image(args, output) image = json.loads(docker("image", "inspect", args.image))[0] report["image"] = {"tag": args.image, "id": image["Id"]} with tempfile.TemporaryDirectory(prefix="highload-track1-generator-") as directory: binary = compile_generator(directory) report["go_version"] = command(["go", "version"]).stdout.strip() print("PREFLIGHT: public API, level 4 HTTP checks, track 1 integrity", flush=True) report["preflight"] = preflight(binary, image["Id"], args) save(output, report) if args.command == "run": profiles = list(itertools.product(range(1, args.repeats + 1), args.histories, args.concurrency, args.workloads)) for index, (repeat, history, concurrency, workload) in enumerate(profiles, 1): case = {"repeat": repeat, "history": history, "concurrency": concurrency, "workload": workload, "status": "RUNNING"} report["cases"].append(case) print("CASE %d/%d: %s, N=%d, C=%d, repeat=%d" % (index, len(profiles), workload, history, concurrency, repeat), flush=True) name = None try: name, base = start_container(image["Id"], args) case["result"] = invoke(binary, name, base, args, history, concurrency, workload) state = inspect(name)["State"] case["container_state"] = {k: state[k] for k in ("Running", "OOMKilled", "ExitCode")} if not state["Running"] or state["OOMKilled"] or case["result"]["resources"]["oom_kill_count"]: raise RuntimeError("container stopped or OOM occurred") case["status"] = "PASS" metrics = case["result"]["generator"]["metrics"]["read"] print(" PASS: %.1f read RPS, p95=%s ms, p99=%s ms, RSS=%.1f MiB, errors=%d" % (metrics["successful_rps"], metrics["successful_latency_ms"]["p95"], metrics["successful_latency_ms"]["p99"], case["result"]["resources"]["rss_peak_observed_bytes"] / 1048576, metrics["failed_requests"]), flush=True) except (RuntimeError, OSError, ValueError, subprocess.SubprocessError) as exc: case.update(status="FAIL", reason=str(exc)) if name: state = inspect(name)["State"] case["container_state"] = {k: state[k] for k in ("Running", "OOMKilled", "ExitCode")} print(" FAIL: " + str(exc), flush=True) finally: if name: command(["docker", "rm", "--force", name], required=False) save(output, report) write_csv(output, report["cases"]) report["status"] = "PASS" if all(c["status"] == "PASS" for c in report["cases"]) else "FAIL" except (RuntimeError, OSError, ValueError, subprocess.SubprocessError) as exc: report.update(status="FAIL", reason=str(exc)) print("FAIL: " + str(exc), flush=True) finally: report["finished_at_utc"] = dt.datetime.now(dt.timezone.utc).isoformat() save(output, report) write_csv(output, report["cases"]) print("SUMMARY: %s; %s" % (report["status"], args.output), flush=True) return 0 if report["status"] == "PASS" else 1 def compare(args): before, after = [json.loads((ROOT / p).read_text()) for p in (args.before, args.after)] for report in (before, after): if report["status"] != "PASS" or not report["cases"]: raise RuntimeError("comparison requires two complete PASS matrices") for field in ("schema", "method", "limits", "host", "docker", "generator_sha256", "go_version"): if before[field] != after[field]: raise RuntimeError("incomparable experiments: different " + field) if before["image"]["id"] == after["image"]["id"]: raise RuntimeError("before and after use the same image; no application change demonstrated") def group(report): groups = {} for case in report["cases"]: key = (case["workload"], case["history"], case["concurrency"]) groups.setdefault(key, []).append(case) return groups a, b = group(before), group(after) if set(a) != set(b): raise RuntimeError("different matrix profiles") rows = [] print("workload N C | read RPS before -> after | p95 ms before -> after | RSS MiB before -> after") for key in sorted(a): def aggregate(cases): values = {"read_rps": [], "read_p95_ms": [], "read_p99_ms": [], "rss_peak_mib": [], "errors": []} for case in cases: result = case["result"] read, write = (result["generator"]["metrics"][op] for op in ("read", "write")) values["read_rps"].append(read["successful_rps"]) values["read_p95_ms"].append(read["successful_latency_ms"]["p95"]) values["read_p99_ms"].append(read["successful_latency_ms"]["p99"]) values["rss_peak_mib"].append(result["resources"]["rss_peak_observed_bytes"] / 1048576) values["errors"].append(read["failed_requests"] + write["failed_requests"]) if any(v is None for series in values.values() for v in series): raise RuntimeError("a profile has no successful reads") return {name: {"median": statistics.median(series), "min": min(series), "max": max(series)} for name, series in values.items()} first, second = aggregate(a[key]), aggregate(b[key]) row = {"workload": key[0], "history": key[1], "concurrency": key[2], "before": first, "after": second} row["read_rps_ratio"] = second["read_rps"]["median"] / first["read_rps"]["median"] rows.append(row) print("%s %d %d | %.1f -> %.1f | %.3f -> %.3f | %.1f -> %.1f" % (*key, first["read_rps"]["median"], second["read_rps"]["median"], first["read_p95_ms"]["median"], second["read_p95_ms"]["median"], first["rss_peak_mib"]["median"], second["rss_peak_mib"]["median"])) output = (ROOT / args.output).resolve() if output.exists(): raise RuntimeError("comparison output already exists; choose a new path") save(output, {"schema": 1, "before": args.before, "after": args.after, "before_image": before["image"], "after_image": after["image"], "rows": rows, "note": "Medians and min/max across repetitions; latency percentiles cover successful requests. A ratio is not proof of causality or a universal passing RPS."}) return 0 def main(): parser = argparse.ArgumentParser(description=__doc__) sub = parser.add_subparsers(dest="command", required=True) for name in ("run", "check"): p = sub.add_parser(name) p.add_argument("--build", action="store_true") p.add_argument("--image", required=True) p.add_argument("--label", default="before") p.add_argument("--output", required=True) p.add_argument("--histories", type=numbers, default=[100, 1000, 10000]) p.add_argument("--concurrency", type=numbers, default=[1, 5, 10]) p.add_argument("--workloads", default="read", type=lambda s: s.split(","), choices=None) p.add_argument("--duration", type=float, default=30) p.add_argument("--warmup", type=float, default=5) p.add_argument("--repeats", type=int, default=3) p.add_argument("--cpus", type=float, default=1) p.add_argument("--memory-mib", type=int, default=128) p.add_argument("--page-size", type=int, default=50) p.add_argument("--payload-bytes", type=int, default=128) p.add_argument("--timeout", type=float, default=5) p.add_argument("--sample-interval", type=float, default=0.5) p = sub.add_parser("compare") p.add_argument("--before", required=True) p.add_argument("--after", required=True) p.add_argument("--output", required=True) args = parser.parse_args() if args.command != "compare": if args.repeats < 1 or args.cpus <= 0 or args.memory_mib < 32 or args.warmup < 0 or args.timeout <= 0 or args.sample_interval < 0.1 or not 1 <= args.page_size <= 100 or not 32 <= args.payload_bytes <= 4000 or any(c > 256 for c in args.concurrency) or not args.workloads or set(args.workloads) - {"read", "mixed"} or len(args.workloads) != len(set(args.workloads)): parser.error("invalid limits, durations or workload parameters") try: return compare(args) if args.command == "compare" else run_experiment(args) except (RuntimeError, OSError, ValueError, subprocess.SubprocessError) as exc: print("FAIL: " + str(exc), flush=True) return 1 if __name__ == "__main__": raise SystemExit(main())