Record SLO and observability fault experiments
This commit is contained in:
@@ -0,0 +1,118 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Prove business API survives a bounded outage of all telemetry stores."""
|
||||
|
||||
import json
|
||||
import subprocess
|
||||
import time
|
||||
from datetime import datetime, timezone
|
||||
from pathlib import Path
|
||||
from urllib.parse import urlencode
|
||||
from urllib.request import urlopen
|
||||
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
FILES = ["-f", "compose.yaml"]
|
||||
if (ROOT / "compose.local.yaml").exists():
|
||||
FILES += ["-f", "compose.local.yaml"]
|
||||
FILES += ["-f", "compose.telemetry.yaml"]
|
||||
COMPOSE = ["docker", "compose", *FILES, "--env-file", ".env"]
|
||||
COUNTERS = (
|
||||
"otelcol_exporter_enqueue_failed_spans",
|
||||
"otelcol_exporter_send_failed_spans",
|
||||
"otelcol_exporter_send_failed_log_records",
|
||||
"otelcol_exporter_send_failed_metric_points",
|
||||
"otelcol_receiver_refused_spans",
|
||||
"otelcol_receiver_refused_log_records",
|
||||
"otelcol_receiver_refused_metric_points",
|
||||
)
|
||||
|
||||
|
||||
def run(*args):
|
||||
return subprocess.run(args, cwd=ROOT, capture_output=True, text=True)
|
||||
|
||||
|
||||
def stats():
|
||||
result = run("docker", "stats", "--no-stream", "--format", "{{json .}}",
|
||||
"mtusi2026lab6-otel-collector-1", "mtusi2026lab6-api-1", "mtusi2026lab6-worker-1")
|
||||
return [json.loads(line) for line in result.stdout.splitlines()] if result.returncode == 0 else []
|
||||
|
||||
|
||||
def metric(name):
|
||||
url = "http://127.0.0.1:9090/api/v1/query?" + urlencode({"query": f"sum({name})"})
|
||||
try:
|
||||
with urlopen(url, timeout=5) as response:
|
||||
rows = json.load(response)["data"]["result"]
|
||||
except (OSError, ValueError):
|
||||
return None
|
||||
return float(rows[0]["value"][1]) if rows else None
|
||||
|
||||
|
||||
def stores_up():
|
||||
url = "http://127.0.0.1:9090/api/v1/query?" + urlencode({"query": "up{job=~\"prometheus|loki|tempo\"}"})
|
||||
try:
|
||||
with urlopen(url, timeout=5) as response:
|
||||
rows = json.load(response)["data"]["result"]
|
||||
except (OSError, ValueError):
|
||||
return False
|
||||
return len(rows) == 3 and all(row["value"][1] == "1" for row in rows)
|
||||
|
||||
|
||||
def main():
|
||||
output = ROOT / "evidence/telemetry-backend-outage-2026-10-02.json"
|
||||
data = {"started": datetime.now(timezone.utc).isoformat(timespec="seconds"),
|
||||
"stores": ["prometheus", "loki", "tempo"], "stats_before": stats(),
|
||||
"collector_counters_before": {name: metric(name) for name in COUNTERS}}
|
||||
stopped = False
|
||||
try:
|
||||
result = run(*COMPOSE, "stop", "prometheus", "loki", "tempo")
|
||||
if result.returncode:
|
||||
raise RuntimeError(result.stderr[-500:])
|
||||
stopped = True
|
||||
data["stores_stopped"] = datetime.now(timezone.utc).isoformat(timespec="seconds")
|
||||
smoke = run("make", "test", "BASE_URL=http://127.0.0.1:8080")
|
||||
data["smoke_passed"] = smoke.returncode == 0
|
||||
data["smoke_tail"] = (smoke.stdout + smoke.stderr).splitlines()[-5:]
|
||||
load = run("python3", "tests/load.py", "--base-url", "http://127.0.0.1:8080",
|
||||
"--duration", "30", "--concurrency", "4",
|
||||
"--output", "evidence/telemetry-outage-http-load-2026-10-02.json")
|
||||
data["load_passed"] = load.returncode == 0
|
||||
data["stats_during"] = stats()
|
||||
# Longer than Collector's 30-second exporter retry horizon.
|
||||
time.sleep(35)
|
||||
data["stats_after_35s"] = stats()
|
||||
finally:
|
||||
if stopped:
|
||||
restored = run(*COMPOSE, "up", "-d", "prometheus", "loki", "tempo")
|
||||
data["stores_restored"] = restored.returncode == 0
|
||||
data["stores_restored_at"] = datetime.now(timezone.utc).isoformat(timespec="seconds")
|
||||
healthy_since = None
|
||||
deadline = time.monotonic() + 90
|
||||
while time.monotonic() < deadline:
|
||||
if stores_up():
|
||||
healthy_since = healthy_since or time.monotonic()
|
||||
if time.monotonic() - healthy_since >= 30:
|
||||
break
|
||||
else:
|
||||
healthy_since = None
|
||||
time.sleep(5)
|
||||
data["stores_healthy"] = (healthy_since is not None and
|
||||
time.monotonic() - healthy_since >= 30 and stores_up())
|
||||
data["collector_counters_after"] = {name: metric(name) for name in COUNTERS}
|
||||
data["collector_counter_delta"] = {
|
||||
name: (data["collector_counters_after"][name] - data["collector_counters_before"][name]
|
||||
if data["collector_counters_before"][name] is not None and
|
||||
data["collector_counters_after"][name] is not None else None)
|
||||
for name in COUNTERS
|
||||
}
|
||||
output.write_text(json.dumps(data, indent=2, sort_keys=True) + "\n", encoding="utf-8")
|
||||
print(json.dumps({"smoke_passed": data.get("smoke_passed"),
|
||||
"load_passed": data.get("load_passed"),
|
||||
"stores_restored": data.get("stores_restored"),
|
||||
"collector_counter_delta": data["collector_counter_delta"],
|
||||
"output": str(output)}, sort_keys=True))
|
||||
if not all(data.get(key) for key in ("smoke_passed", "load_passed", "stores_restored", "stores_healthy")):
|
||||
raise SystemExit("business path or telemetry recovery failed")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,89 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Stop worker, build a real durable backlog, then verify queue-lag recovery."""
|
||||
|
||||
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]
|
||||
sys.path.insert(0, str(ROOT / "tests"))
|
||||
sys.path.insert(0, str(ROOT / "scripts"))
|
||||
from client import Client # noqa: E402
|
||||
from slo_watch import snapshot # noqa: E402
|
||||
|
||||
|
||||
FILES = ["-f", "compose.yaml"]
|
||||
if (ROOT / "compose.local.yaml").exists():
|
||||
FILES += ["-f", "compose.local.yaml"]
|
||||
FILES += ["-f", "compose.telemetry.yaml"]
|
||||
|
||||
|
||||
def compose(*args):
|
||||
subprocess.run(["docker", "compose", *FILES, "--env-file", ".env", *args],
|
||||
cwd=ROOT, check=True, stdout=subprocess.DEVNULL)
|
||||
|
||||
|
||||
def now():
|
||||
return datetime.now(timezone.utc).isoformat(timespec="seconds")
|
||||
|
||||
|
||||
def main():
|
||||
client = Client("http://127.0.0.1:8080")
|
||||
alice, _bob, _eve, chat = client.bootstrap()
|
||||
image = (ROOT / "tests/fixtures/sample.png").read_bytes()
|
||||
samples = []
|
||||
stop = threading.Event()
|
||||
|
||||
def watch():
|
||||
while not stop.is_set():
|
||||
samples.append(snapshot("http://127.0.0.1:9090"))
|
||||
stop.wait(5)
|
||||
|
||||
watcher = threading.Thread(target=watch, daemon=True)
|
||||
watcher.start()
|
||||
times = {"started": now()}
|
||||
worker_stopped = False
|
||||
try:
|
||||
compose("stop", "worker")
|
||||
worker_stopped = True
|
||||
times["worker_stopped"] = now()
|
||||
attachments = []
|
||||
for _ in range(8):
|
||||
response = client.call(
|
||||
"POST", f"/api/v1/chats/{chat['id']}/attachments?filename=queue-probe.png",
|
||||
202, actor=alice, raw=image, headers={"Content-Type": "image/png"}, schema="Attachment",
|
||||
)
|
||||
attachments.append(response["json"])
|
||||
times["uploads_accepted"] = now()
|
||||
time.sleep(35)
|
||||
compose("up", "-d", "worker")
|
||||
worker_stopped = False
|
||||
times["worker_started"] = now()
|
||||
for item in attachments:
|
||||
client.wait_ready(alice, item, wait_seconds=120)
|
||||
times["all_ready"] = now()
|
||||
time.sleep(40)
|
||||
finally:
|
||||
if worker_stopped:
|
||||
compose("up", "-d", "worker")
|
||||
stop.set()
|
||||
watcher.join(timeout=6)
|
||||
states = [item["alerts"].get("Lab6QueueLag") for item in samples]
|
||||
data = {"times": times, "queued_uploads": len(attachments),
|
||||
"ready_uploads": len(attachments), "prometheus_samples": samples,
|
||||
"queue_alert_states": sorted(set(states))}
|
||||
path = ROOT / "evidence/queue-worker-stop-2026-10-02.json"
|
||||
path.write_text(json.dumps(data, indent=2, sort_keys=True) + "\n", encoding="utf-8")
|
||||
print(json.dumps({"queued_uploads": len(attachments), "states": data["queue_alert_states"],
|
||||
"times": times, "output": str(path)}, sort_keys=True))
|
||||
if "firing" not in states or states[-1] != "inactive":
|
||||
raise SystemExit("queue lag alert did not fire and resolve")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,138 @@
|
||||
#!/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()
|
||||
Reference in New Issue
Block a user