Files
mtusi2026lab6/student-tests/incidents.py
T

318 lines
11 KiB
Python

import os
import subprocess
import threading
import time
from concurrent.futures import ThreadPoolExecutor
from contextlib import contextmanager
from urllib.error import HTTPError, URLError
from client import Client, check, run
from observe import trace_for, upload
from pipeline_support import COMPOSE, compose, ready_api, sql, wait_ready
from telemetry_support import logs, save, spans, states, value, wait_until
API_ALERTS = ["ApiHighErrorRate", "ApiBurnFast", "ApiBurnSlow"]
READY_ALERTS = ["ReadyBurnFast", "ReadyBurnSlow"]
class Traffic:
def __init__(self, actor):
self.actor = actor
self.stop = threading.Event()
self.lock = threading.Lock()
self.counts = {}
self.error = None
self.slowest_ok = 0
def run(self):
client = Client(timeout=12)
while not self.stop.is_set():
started = time.monotonic()
try:
response = client.call(
"GET", "/api/v1/users/me", actor=self.actor, expected=[200, 503]
)
status = response["status"]
elapsed = time.monotonic() - started
with self.lock:
self.counts[status] = self.counts.get(status, 0) + 1
if status == 200:
self.slowest_ok = max(self.slowest_ok, elapsed)
else:
self.error = response["headers"]["X-Request-Id"]
except Exception as error:
with self.lock:
name = type(error).__name__
self.counts[name] = self.counts.get(name, 0) + 1
self.stop.wait(0.2)
@contextmanager
def start(self, clients=6):
with ThreadPoolExecutor(max_workers=clients) as pool:
workers = [pool.submit(self.run) for _ in range(clients)]
try:
yield self
finally:
self.stop.set()
for worker in workers:
worker.result()
def snapshot(self):
with self.lock:
return dict(self.counts)
@contextmanager
def session_lock(seconds):
command = (
'psql -v ON_ERROR_STOP=1 -U "$(cat /run/secrets/postgres_user)"'
' -d "$(cat /run/secrets/postgres_db)" -At'
)
with subprocess.Popen(
COMPOSE + ["exec", "-T", "db", "sh", "-c", command],
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
text=True,
) as process:
process.stdin.write(
f"SET application_name='lab6-incident'; BEGIN; LOCK TABLE sessions IN ACCESS EXCLUSIVE MODE; "
f"SELECT pg_sleep({seconds}); ROLLBACK;\n"
)
process.stdin.close()
try:
wait_until(
lambda: sql(
"SELECT count(*) FROM pg_stat_activity WHERE application_name='lab6-incident'"
" AND wait_event='PgSleep';"
)
== "1",
15,
"database lock not acquired",
)
yield time.monotonic()
finally:
sql(
"SELECT pg_cancel_backend(pid) FROM pg_stat_activity"
" WHERE application_name='lab6-incident' AND state='active';"
)
process.wait(timeout=15)
def monitor(names, firing, timeout, started):
samples = []
reached = set()
target = "firing" if firing else "inactive"
def check_state():
snapshot = states()
samples.append(
{
"seconds": round(time.monotonic() - started, 2),
"states": {name: snapshot[name] for name in names},
}
)
reached.update(name for name in names if snapshot[name] == target)
return (
len(reached) == len(names)
if firing
else all(snapshot[name] == target for name in names)
)
wait_until(check_state, timeout, "unexpected alert states: " + str(names))
return samples
def find_failed_dependency(request_id, since):
trace_id = wait_until(lambda: trace_for(request_id, since), 35, "DB incident log missing")
def dependency():
try:
rows = spans(trace_id)
except HTTPError as error:
if error.code == 404:
return None
raise
for row in rows:
if row["name"] == "postgres.session.lookup":
duration = (int(row["endTimeUnixNano"]) - int(row["startTimeUnixNano"])) / 1e9
if duration >= 3:
return {
"trace_id": trace_id,
"request_id": request_id,
"dependency": row["name"],
"duration_seconds": duration,
"status": row.get("status"),
}
return None
return wait_until(dependency, 35, "slow PostgreSQL span missing")
def database_incidents(actor):
with Traffic(actor).start() as traffic:
time.sleep(15)
wait_until(lambda: traffic.snapshot().get(200, 0) >= 35, 15, "no warm traffic")
before = traffic.snapshot().get(503, 0)
with session_lock(3) as started:
canceled = sql(
"SELECT pg_cancel_backend(pid) FROM (SELECT pid FROM pg_stat_activity"
" WHERE wait_event_type='Lock' AND query LIKE '%sessions%' LIMIT 1) AS blocked;"
)
check(canceled == "t", "short incident did not cancel a DB read")
brief = []
for _ in range(17):
brief.append({"seconds": round(time.monotonic() - started, 2), "states": states()})
time.sleep(1)
short_errors = traffic.snapshot().get(503, 0) - before
check(short_errors > 0, "short fault produced no observed errors")
check(
not any(sample["states"][name] == "firing" for sample in brief for name in API_ALERTS),
"short burst fired an API alert",
)
since = time.time() - 2
with session_lock(85) as started:
detection = monitor(API_ALERTS, True, 75, started)
request_id = traffic.error
released = time.monotonic()
recovery = monitor(API_ALERTS, False, 95, released)
check(
traffic.snapshot().get(200, 0) > 30 and traffic.snapshot().get(503, 0) > short_errors,
"sustained incident did not affect HTTP",
)
sample = find_failed_dependency(request_id, since)
return {
"traffic_clients": 6,
"short": {"503_count": short_errors, "samples": brief, "alert_firings": 0},
"sustained": {
"firing": detection,
"resolved": recovery,
"bounded_lock_seconds": 85,
"traffic_statuses": traffic.snapshot(),
"cause": sample,
},
}
def queue_incident(client, actor, chat):
compose("stop", "worker")
started = time.monotonic()
attachments = []
try:
for index in range(16):
attachments.append(upload(client, actor, chat, "lag-" + str(index))["json"])
provisional = monitor(["AttachmentQueueLag"], True, 45, started)
peak = {
"age_seconds": value("max(lab_queue_oldest_seconds)"),
"backlog": value("max(lab_queue_depth)"),
"reported_capacity": value("sum(lab_worker_capacity)"),
}
check(peak["backlog"] >= 16, "observability reported no backlog")
finally:
compose("start", "worker")
released = time.monotonic()
for attachment in attachments:
wait_ready(client, actor, attachment)
drain = round(time.monotonic() - released, 2)
ready_firing = monitor(READY_ALERTS, True, 45, released)
resolved = monitor(["AttachmentQueueLag"], False, 30, released)
ready_resolved = monitor(READY_ALERTS, False, 90, released)
return {
"accepted": len(attachments),
"queue_firing": provisional,
"peak": peak,
"drained_seconds": drain,
"ready_burn_firing": ready_firing,
"queue_resolved": resolved,
"ready_burn_resolved": ready_resolved,
"all_ready": True,
}
def collector_snapshot():
metric = "otelcol_exporter_send_failed_log_records_total"
return {
"send_failed_logs": value("sum(" + metric + '{exporter="otlphttp/loki"})'),
"queue_size": value('max(otelcol_exporter_queue_size{exporter="otlphttp/loki"})'),
"queue_capacity": value('max(otelcol_exporter_queue_capacity{exporter="otlphttp/loki"})'),
"rss_bytes": value("otelcol_process_memory_rss_bytes"),
}
def backend_incident(client, actor, chat):
before = collector_snapshot()
acknowledged = []
samples = []
compose("stop", "loki")
started = time.monotonic()
try:
for index in range(30):
acknowledged.append(
client.message(actor, chat, "backend proof " + str(index))["json"]["id"]
)
if index % 3 == 0:
samples.append(collector_snapshot())
time.sleep(0.7)
samples.append(collector_snapshot())
finally:
compose("start", "loki")
page = client.call(
"GET", f"/api/v1/chats/{chat['id']}/messages?limit=100", actor=actor, schema="MessagePage"
)["json"]
check(
set(acknowledged) <= {item["id"] for item in page["items"]},
"message loss during telemetry outage",
)
after = collector_snapshot()
failed = (
max([after["send_failed_logs"], *[s["send_failed_logs"] for s in samples]])
- before["send_failed_logs"]
)
check(failed > 0, "Collector exporter drops were not observed")
wait_until(loki_ready, 75, "Loki failed to recover")
since = time.time() - 2
response = client.message(actor, chat, "telemetry restored")
restored_trace = wait_until(
lambda: trace_for(response["headers"]["X-Request-Id"], since),
45,
"new business log not exported after Loki recovery",
)
return {
"confirmed_and_read": len(acknowledged),
"seconds": round(time.monotonic() - started, 2),
"collector_before": before,
"collector_samples": samples,
"collector_after": after,
"failed_export_log_records_delta": failed,
"restored_trace_id": restored_trace,
}
def loki_ready():
try:
logs('{service_name="messenger-api"}', limit=1)
return True
except (HTTPError, URLError, TimeoutError):
return False
def main():
ready_api()
client = Client(timeout=12)
actor, _, _, chat = client.bootstrap()
mode = os.getenv("INCIDENT", "all")
if mode in ("all", "db"):
save("database-incident.json", database_incidents(actor))
print("PASS short DB burst and sustained slowdown: real alerts and DB trace", flush=True)
if mode in ("all", "queue"):
save("queue-incident.json", queue_incident(client, actor, chat))
print("PASS stopped worker: backlog, firing/resolved and slow READY burn", flush=True)
if mode in ("all", "backend"):
save("backend-incident.json", backend_incident(client, actor, chat))
print("PASS stopped Loki: bounded telemetry failure and saved business writes", flush=True)
if __name__ == "__main__":
run(main)