#!/usr/bin/env python3 """Run Lab 5 checks against an isolated Compose stand and write JSONL evidence.""" import argparse import os from pathlib import Path import platform import subprocess import sys import time from urllib.parse import urlsplit sys.dont_write_bytecode = True from checks import ROOT, Evidence, Failure, Pending, Probe, check, health, idempotency from pipeline import Pipeline, make_decoder, upload_rejects, variants from stand import Stand HERE = Path(__file__).resolve().parent TEST_HOOK = HERE / "compose_action.py" def arguments(): cases = ("http", "idempotency-lb", "resources", "persistence", "failover", "unready", "rolling", "migrations", "pipeline-http", "pipeline-faults", "pipeline-versioned", "public", "all") p = argparse.ArgumentParser(description=__doc__) p.add_argument("--scenario", choices=cases, action="append", required=True) p.add_argument("--case", action="append", help="run only the named case within the selected scenario(s)") p.add_argument("--base-url", default=os.environ.get("BASE_URL")) p.add_argument("--ca-file", default=os.environ.get("CA_FILE")) p.add_argument("--output", required=True, help="new JSONL file; no overwrite") p.add_argument("--project", help="explicit disposable Compose project required for fault scenarios") p.add_argument("--exercise", action="store_true", help="allow fault actions on this isolated project") p.add_argument("--compose-file", action="append", default=[]) for k, default in (("api", "api"), ("lb", "lb"), ("db", "postgres"), ("migrate", "migrate"), ("db-user", "messenger"), ("db-name", "messenger")): p.add_argument("--" + k, default=default) p.add_argument("--store", action="append", help="additional persistence stores; repeat per service") p.add_argument("--api-port", type=int, default=8080) p.add_argument("--network", help="shared API/LB Docker network for diagnostics") p.add_argument("--probe-image", default="rustfs/rustfs:1.0.4", help="local image with curl, for direct health diagnostics from the LB namespace") p.add_argument("--workers", type=int, default=6) p.add_argument("--timeout", type=float, default=2) p.add_argument("--window", type=float, default=3) p.add_argument("--warmup", type=float, default=2) p.add_argument("--pipeline-timeout", type=int, default=120) p.add_argument("--repetitions", type=int, default=3, help="number of complete versioned experiment series") p.add_argument("--magick", help="optional path to ImageMagick 7 for full image decode") for k in ("restart", "stop", "unready", "ready", "roll", "pipeline"): p.add_argument("--" + k + "-hook", type=str) a = p.parse_args() if not a.base_url: p.error("--base-url (or BASE_URL) is required") url = urlsplit(a.base_url) if (url.scheme not in ("http", "https") or not url.hostname or url.username or url.password or url.query or url.fragment or url.path not in ("", "/")): p.error("use an HTTP(S) origin without credentials, query, path, or fragment") if not 2 <= a.workers <= 64 or not 0 < a.timeout <= 5 or not 2 <= a.window <= 30 or not 0 < a.warmup <= 30: p.error("workers=2..64, timeout=(0,5], window=2..30, warmup=(0,30]") if not 1 <= a.pipeline_timeout <= 600: p.error("pipeline timeout must be 1..600 s") if not 1 <= a.repetitions <= 10: p.error("repetitions must be 1..10") if a.store is None: a.store = ["redis", "s3", "rabbitmq"] if a.exercise and (not a.project or a.project == "highload-lab5"): p.error("--exercise requires --project for a disposable stand (not highload-lab5)") return a def control_env(a): import json return dict(os.environ, COMPOSE_PROJECT_NAME=a.project or "", LAB5_TEST_COMPOSE_FILES=json.dumps([str(Path(f).resolve()) for f in a.compose_file]), LAB5_TEST_API=a.api, LAB5_TEST_DB=a.db, LAB5_TEST_LB=a.lb, LAB5_TEST_DB_USER=a.db_user, LAB5_TEST_DB_NAME=a.db_name, LAB5_TEST_STORES=" ".join(a.store), PYTHONDONTWRITEBYTECODE="1") def safe_to_exercise(args): if not args.exercise: raise Pending("requires --exercise and a dedicated --project") def public_case(stand, mode, out): a, e = stand.a, stand.e if mode != "test": safe_to_exercise(a) apis = stand.public_topology() env = control_env(a) cmd = ["make", mode, "BASE_URL=" + stand.c.base, "PYTHON=" + sys.executable] if a.ca_file: cmd.append("CA_FILE=" + a.ca_file) if mode != "test": hook = a.restart_hook if mode == "test-persistence" else a.stop_hook # The default test-only hook is scoped to the explicit project and uses # the same scope passed to the student scenarios. hook = hook or str(TEST_HOOK) check(Path(hook).is_file() and os.access(hook, os.X_OK), "public action hook is not executable") cmd.append("ACTION_SCRIPT=" + str(Path(hook).resolve())) env["LAB5_HOOK_MODE"] = "restart" if mode == "test-persistence" else "stop-one" path = Path(out).with_suffix(f".{mode}.log") start = time.monotonic() try: with path.open("xb") as log: result = subprocess.run(cmd, cwd=ROOT, env=env, stdout=log, stderr=subprocess.STDOUT, timeout=300) e.event("public_run", command=mode, exit_code=result.returncode, log=path.name, elapsed_s=time.monotonic() - start) check(result.returncode == 0, f"make {mode} returned {result.returncode}; see {path.name}") except subprocess.TimeoutExpired: raise Failure(f"make {mode} exceeded its timeout; see {path.name}") from None finally: if mode == "test-failover": before = {r["id"] for r in apis} rows = [r for r in stand.containers(a.api) if r["id"] in before and r["state"] == "exited"] if rows: stand.command("restore after teacher failover", ["docker", "start", *[r["id"] for r in rows]]) def main(): a = arguments() e = Evidence(a.output) e.event("environment", base=a.base_url, project=a.project, workers=a.workers, timeout=a.timeout, fault_window=a.window, warmup=a.warmup, python=platform.python_version(), host=platform.machine(), os=platform.system(), logical_cpus=os.cpu_count()) c = Probe(a.base_url, a.ca_file, a.timeout, e) s = Stand(a, c) decoder = make_decoder(s, a.magick) if not a.pipeline_hook and "compose.fault.test.yaml" in [Path(f).name for f in a.compose_file]: a.pipeline_hook = str(HERE / "pipeline_action.py") pipeline = Pipeline(s, decoder) def exercise(f): def wrapper(): safe_to_exercise(a) f() return wrapper def idem_lb(): s.public_topology() idempotency(c, a.workers, known_instances=s.a_ids) def readiness(): # Use the bundled hook only with its explicit edge network override. explicit = [Path(f).name for f in a.compose_file] if "compose.readiness.test.yaml" in explicit: a.unready_hook = a.unready_hook or str(TEST_HOOK) a.ready_hook = a.ready_hook or str(TEST_HOOK) s.unready() def persist(): previous = a.restart_hook a.restart_hook = previous or str(TEST_HOOK) try: s.persistence() finally: a.restart_hook = previous def versioned(): from versioned import series series(pipeline, a.repetitions) # The test-only restart hook uses the same Compose file/service selection. os.environ.update(control_env(a)) os.environ["LAB5_HOOK_MODE"] = "restart" groups = { "http": [("health", lambda: health(c)), ("idempotency", lambda: idempotency(c, a.workers))], "idempotency-lb": [("idempotency-across-LB", idem_lb)], "resources": [("CPU-RAM-ports", s.resources)], "migrations": [("single-migration-start", lambda: (s.public_topology(), s.migration_snapshot()))], "persistence": [("persistent-idempotency", exercise(persist))], "failover": [("each-SIGTERM-read-write-with-load", exercise(s.failover))], "unready": [("LB-excludes-unready-API", exercise(readiness))], "rolling": [("one-API-at-a-time-under-load", exercise(s.rolling))], "pipeline-http": [("upload-byte-pixel-media-limits", lambda: upload_rejects(c)), ("async-output-variants", lambda: variants(c, min(60, a.pipeline_timeout), decoder))], "pipeline-faults": [ ("durable-broker-worker-stop-and-redelivery", exercise(pipeline.durable)), ("crash-COMMIT-before-publish", exercise(lambda: pipeline.crash("commit-before-publish"))), ("crash-relay-after-confirm-before-mark", exercise(lambda: pipeline.crash("publish-before-mark"))), ("crash-object-before-ack-lease", exercise(lambda: pipeline.crash("object-before-ack"))), ("crash-ready-before-ack", exercise(lambda: pipeline.crash("ready-before-ack"))), ("bounded-processing-timeout-and-prefetch", exercise(pipeline.bounded_processing)), ("mismatched-broker-envelope-DLQ", exercise(pipeline.malformed_job)), ("backoff-jitter-permanent-failed-replay", exercise(pipeline.retry_replay)), ], "pipeline-versioned": [("pipeline-versioned-series", exercise(versioned))], "public": [(f"make-{m}", lambda m=m: public_case(s, m, a.output)) for m in ("test", "test-persistence", "test-failover")], } if "all" in a.scenario: selectors = [name for name in groups if name != "pipeline-versioned" or name in a.scenario] # The LB case covers HTTP idempotency as well; avoid a duplicate run. groups["http"] = groups["http"][:1] else: selectors = list(dict.fromkeys(a.scenario)) if "idempotency-lb" in selectors and "http" in selectors: groups["http"] = groups["http"][:1] selected = [(label, fn) for group in selectors for label, fn in groups[group]] if a.case: check(set(a.case) <= {label for label, _ in selected}, "--case is outside the selected scenarios") selected = [(label, fn) for label, fn in selected if label in a.case] results = [] try: for label, fn in selected: results.append(e.case(label, fn)) e.event("summary", **{k: results.count(k) for k in ("PASS", "FAIL", "PENDING")}) return 1 if "FAIL" in results else (2 if "PENDING" in results else 0) finally: e.file.close() if __name__ == "__main__": try: raise SystemExit(main()) except (Failure, OSError) as exc: print("FAIL:", exc if isinstance(exc, Failure) else type(exc).__name__, file=sys.stderr) raise SystemExit(1) from None