forked from mtusi2026/mtusi2026lab7
117 lines
4.8 KiB
Python
117 lines
4.8 KiB
Python
"""Run isolated worker, database and telemetry incidents and always restore the services."""
|
|
import json
|
|
from pathlib import Path
|
|
import re
|
|
import subprocess
|
|
import sys
|
|
import time
|
|
|
|
ROOT = Path(__file__).resolve().parents[1]
|
|
sys.path.insert(0, str(ROOT / "tests"))
|
|
from client import Client, check
|
|
|
|
DC = ["docker", "compose"]
|
|
AUDIT = DC + ["run", "--rm", "--no-deps", "-T", "audit", "python", "/app/student-tests/telemetry_probe.py"]
|
|
|
|
|
|
def run(args, capture=False, **kwargs):
|
|
return subprocess.run(args, check=True, text=True, capture_output=capture, **kwargs)
|
|
|
|
|
|
def metric(expression):
|
|
result = run(AUDIT + [expression], capture=True)
|
|
return [float(x) for x in json.loads(result.stdout.splitlines()[-1])["values"]]
|
|
|
|
|
|
def await_condition(predicate, seconds):
|
|
end = time.monotonic() + seconds
|
|
while time.monotonic() < end:
|
|
if predicate():
|
|
return round(seconds - (end - time.monotonic()), 3)
|
|
time.sleep(3)
|
|
raise AssertionError("timeout waiting for incident signal")
|
|
|
|
|
|
def worker(c, actor, chat):
|
|
run(DC + ["stop", "-t", "1", "worker"])
|
|
started = time.monotonic()
|
|
try:
|
|
att, _ = c.attachment(actor, chat)
|
|
alert = 'ALERTS{alertname="QueueLagGrowing",alertstate="firing"}'
|
|
firing = await_condition(lambda: metric(alert) == [1], 70)
|
|
age = max(metric("max(queue_oldest_age_seconds)"))
|
|
depth = max(metric("max(queue_depth)"))
|
|
check(age > 15 and depth >= 1, "unexpected queue measurement")
|
|
finally:
|
|
run(DC + ["start", "worker"])
|
|
resumed = time.monotonic()
|
|
c.wait_ready(actor, att)
|
|
ready = time.monotonic() - resumed
|
|
resolved = await_condition(lambda: not metric(alert) and metric("max(queue_depth)") == [0], 40)
|
|
print(json.dumps({"incident": "worker_stop", "age_seconds": age, "depth": depth,
|
|
"alert_firing_seconds": firing, "ready_after_restart_seconds": round(ready, 3),
|
|
"alert_resolved_seconds": resolved, "total_seconds": round(time.monotonic() - started, 3)}))
|
|
|
|
|
|
def database(c, actor, chat):
|
|
psql = DC + ["exec", "-T", "-u", "postgres", "db", "psql", "-qAt", "-d", "messenger", "-c"]
|
|
lock = subprocess.Popen(psql + [
|
|
"BEGIN; LOCK TABLE messages IN ACCESS EXCLUSIVE MODE; SELECT pg_sleep(24); ROLLBACK;"
|
|
], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
|
|
try:
|
|
def acquired():
|
|
return run(psql + ["SELECT count(*) FROM pg_locks WHERE relation='messages'::regclass "
|
|
"AND mode='AccessExclusiveLock' AND granted"], capture=True).stdout.strip() == "1"
|
|
await_condition(acquired, 10)
|
|
c.call("GET", "/health/ready", schema="Health")
|
|
start = time.monotonic()
|
|
results = []
|
|
for _ in range(5):
|
|
from uuid import uuid4
|
|
res = c.call("POST", f"/api/v1/chats/{chat['id']}/messages", 503, actor=actor,
|
|
body={"text": "lock probe"}, headers={"Idempotency-Key": uuid4().hex})
|
|
results.append(res)
|
|
run(AUDIT + ["--trace-error", results[0]["headers"]["X-Trace-Id"]])
|
|
finally:
|
|
lock.wait(timeout=30)
|
|
after = c.message(actor, chat, "database recovered")
|
|
print(json.dumps({"incident": "database_lock", "blocked_requests": len(results),
|
|
"failure_ms": [round(r["elapsed"] * 1000, 2) for r in results],
|
|
"first_success_ms": round(after["elapsed"] * 1000, 2),
|
|
"since_locked_requests_seconds": round(time.monotonic() - start, 3)}))
|
|
|
|
|
|
def telemetry(c, actor, chat):
|
|
start = time.time()
|
|
run(DC + ["stop", "-t", "1", "traces"])
|
|
try:
|
|
requests = 0
|
|
until = time.monotonic() + 17
|
|
att, _ = c.attachment(actor, chat)
|
|
c.wait_ready(actor, att)
|
|
while time.monotonic() < until:
|
|
c.message(actor, chat, "backend outage")
|
|
requests += 1
|
|
time.sleep(1)
|
|
otel = run(DC + ["ps", "-q", "otel"], capture=True).stdout.strip()
|
|
stats = run(["docker", "stats", "--no-stream", "--format", "{{.MemUsage}}", otel], capture=True)
|
|
logs = run(DC + ["logs", "--since", str(int(start)), "otel"], capture=True).stdout
|
|
dropped = sum(int(x) for x in re.findall(r'"dropped_items":\s*(\d+)', logs))
|
|
check(dropped > 0, "bounded telemetry loss not observed")
|
|
finally:
|
|
run(DC + ["start", "traces"])
|
|
print(json.dumps({"incident": "tempo_backend_stop", "successful_writes": requests,
|
|
"upload_ready": True, "collector_memory": stats.stdout.strip(),
|
|
"dropped_spans_reported": dropped, "outage_seconds": round(time.time() - start, 3)}))
|
|
|
|
|
|
def main():
|
|
c = Client(ca_file=str(ROOT / "secrets/authority/ca.crt"))
|
|
actor, _, _, chat = c.bootstrap()
|
|
for scenario in (worker, database, telemetry):
|
|
scenario(c, actor, chat)
|
|
|
|
|
|
if __name__ == "__main__":
|
|
main()
|