Files
mtusi2026lab6/student-tests/test_slo_alerts.py
T

139 lines
5.2 KiB
Python

#!/usr/bin/env python3
"""Reproduce a DB outage and capture Prometheus burn-rate transitions."""
import argparse
import json
import subprocess
import sys
import threading
import time
from datetime import datetime, timezone
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
COMPOSE_FILES = ["-f", "compose.yaml"]
if (ROOT / "compose.local.yaml").exists():
COMPOSE_FILES += ["-f", "compose.local.yaml"]
COMPOSE_FILES += ["-f", "compose.telemetry.yaml"]
sys.path.insert(0, str(ROOT / "scripts"))
from slo_watch import snapshot # noqa: E402
PROBE = r'''
import base64, json, sys, time
from concurrent.futures import ThreadPoolExecutor
from datetime import datetime, timezone
from urllib.error import HTTPError
from urllib.request import Request, urlopen
end = time.monotonic() + int(sys.argv[1])
events = []
headers = {"Authorization": "Basic " + base64.b64encode(b"lab6_probe:synthetic-invalid-password").decode()}
def run_one(_):
result = []
while time.monotonic() < end:
req = Request("http://127.0.0.1:8080/api/v1/auth/sessions", data=b"", headers=headers, method="POST")
try:
with urlopen(req, timeout=30) as response:
code = response.status
except HTTPError as exc:
code = exc.code
except OSError:
code = 0
result.append([datetime.now(timezone.utc).isoformat(timespec="seconds"), code])
time.sleep(0.4)
return result
with ThreadPoolExecutor(max_workers=1) as pool:
for batch in pool.map(run_one, range(1)):
events.extend(batch)
print(json.dumps({"events": sorted(events)}))
'''
def utc_now():
return datetime.now(timezone.utc).isoformat(timespec="seconds")
def compose(*args):
subprocess.run(
["docker", "compose", *COMPOSE_FILES, "--env-file", ".env", *args],
cwd=ROOT, check=True, stdout=subprocess.DEVNULL,
)
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--case", choices=("short", "long"), required=True)
parser.add_argument("--output", required=True)
args = parser.parse_args()
pre, outage, post = (15, 50, 90) if args.case == "short" else (15, 180, 130)
duration = pre + outage + post + 10
samples, watch_errors, times = [], [], {"started": utc_now()}
stop_watching = threading.Event()
def watch():
while not stop_watching.is_set():
try:
samples.append(snapshot("http://127.0.0.1:9090"))
except (OSError, ValueError, KeyError) as exc:
watch_errors.append({"timestamp": utc_now(), "type": type(exc).__name__})
stop_watching.wait(5)
watcher = threading.Thread(target=watch, daemon=True)
watcher.start()
command = [
"docker", "compose", *COMPOSE_FILES, "--env-file", ".env", "exec", "-T",
"api", "python", "-u", "-", str(duration),
]
probe = subprocess.Popen(command, cwd=ROOT, stdin=subprocess.PIPE,
stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
probe.stdin.write(PROBE)
probe.stdin.close()
db_stopped = False
try:
time.sleep(pre)
times["stop_requested"] = utc_now()
compose("stop", "postgres")
db_stopped = True
times["db_stopped"] = utc_now()
time.sleep(outage)
times["restart_requested"] = utc_now()
compose("up", "-d", "--wait", "postgres")
db_stopped = False
times["db_healthy"] = utc_now()
time.sleep(post)
finally:
if db_stopped:
compose("up", "-d", "--wait", "postgres")
times["db_healthy_after_cleanup"] = utc_now()
stop_watching.set()
watcher.join(timeout=6)
output = probe.stdout.read()
error = probe.stderr.read()
probe.wait(timeout=15)
result = json.loads(output) if probe.returncode == 0 else {"error": error[-500:]}
result.update({"case": args.case, "planned_seconds": {"pre": pre, "outage": outage, "post": post},
"times": times, "prometheus_samples": samples, "watch_errors": watch_errors})
path = Path(args.output)
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text(json.dumps(result, indent=2, sort_keys=True) + "\n", encoding="utf-8")
states = {name: {sample["alerts"].get(name) for sample in samples}
for name in ("Lab6HighHttpErrorRate", "Lab6ApiBurnShort", "Lab6ApiBurnLong")}
codes = {event[1] for event in result.get("events", [])}
print(json.dumps({"case": args.case, "codes": sorted(codes),
"states": {name: sorted(values) for name, values in states.items()},
"samples": len(samples), "output": str(path)}, sort_keys=True))
expected = {"Lab6HighHttpErrorRate", "Lab6ApiBurnShort"}
if args.case == "long":
expected.add("Lab6ApiBurnLong")
if probe.returncode or not {401, 503} <= codes or any("firing" not in states[name] for name in expected):
raise SystemExit("incident did not demonstrate the expected HTTP SLO transitions")
if any(sample["alerts"].get(name) != "inactive" for name in expected for sample in samples[-3:]):
raise SystemExit("alerts did not resolve after database recovery")
if __name__ == "__main__":
main()