forked from mtusi2026/mtusi2026lab6
208 lines
9.2 KiB
Python
208 lines
9.2 KiB
Python
#!/usr/bin/env python3
|
|
"""Controlled Level 4 incidents: (1) worker stop -> alert firing/resolved; (2) slow DB vs slow handler; (3) telemetry outage."""
|
|
from concurrent.futures import ThreadPoolExecutor
|
|
import json
|
|
import os
|
|
from pathlib import Path
|
|
import subprocess
|
|
import sys
|
|
import threading
|
|
import time
|
|
|
|
ROOT = Path(__file__).resolve().parents[1]
|
|
sys.path.insert(0, str(ROOT / 'tests'))
|
|
sys.path.insert(0, str(ROOT / 'student-tests'))
|
|
|
|
from client import Client, check
|
|
from grafana_helper import GrafanaClient
|
|
|
|
def compose(*args, env_extra=None):
|
|
env = os.environ.copy()
|
|
if env_extra:
|
|
env.update(env_extra)
|
|
subprocess.run(['docker', 'compose', *args], cwd=ROOT, env=env, check=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
|
|
|
|
def alert_state(g, name):
|
|
rules = g.prom_rules().get('data', {}).get('groups', [])
|
|
for grp in rules:
|
|
for r in grp.get('rules', []):
|
|
if r.get('name') == name:
|
|
return r.get('state')
|
|
return 'missing'
|
|
|
|
def prom_scalar(g, expr):
|
|
res = g.prom_query(expr).get('data', {}).get('result', [])
|
|
return float(res[0]['value'][1]) if res else 0.0
|
|
|
|
def wait_api_ready(c, timeout=45):
|
|
deadline = time.monotonic() + timeout
|
|
while time.monotonic() < deadline:
|
|
try:
|
|
c.call('GET', '/health/ready', schema='Health')
|
|
time.sleep(2)
|
|
return
|
|
except Exception:
|
|
time.sleep(0.5)
|
|
raise RuntimeError('API did not become ready')
|
|
|
|
def incident_1_worker_outage(g, c, alice, bob, chat):
|
|
print('Running Incident 1: Worker outage -> GrowingQueueLag firing & resolved...')
|
|
compose('stop', 'worker')
|
|
att, _ = c.attachment(alice, chat)
|
|
firing_seen = False
|
|
deadline = time.monotonic() + 75
|
|
try:
|
|
while time.monotonic() < deadline:
|
|
if alert_state(g, 'GrowingQueueLag') == 'firing':
|
|
firing_seen = True
|
|
break
|
|
time.sleep(2)
|
|
check(firing_seen, 'GrowingQueueLag alert did not reach firing state')
|
|
finally:
|
|
compose('up', '-d', 'worker')
|
|
c.wait_ready(bob, att, wait_seconds=60)
|
|
resolved_seen = False
|
|
deadline = time.monotonic() + 60
|
|
while time.monotonic() < deadline:
|
|
if alert_state(g, 'GrowingQueueLag') == 'inactive':
|
|
resolved_seen = True
|
|
break
|
|
time.sleep(2)
|
|
check(resolved_seen, 'GrowingQueueLag alert did not resolve after worker recovery')
|
|
return {'alert': 'GrowingQueueLag', 'firing_observed': firing_seen, 'resolved_observed': resolved_seen, 'attachment_status': 'ready'}
|
|
|
|
def incident_2_slow_db_vs_handler(g, c, alice, chat):
|
|
print('Running Incident 2: Slow DB (lock contention + 503) vs Slow HTTP handler...')
|
|
t0 = time.time()
|
|
def hold_lock():
|
|
subprocess.run(
|
|
['docker', 'compose', 'exec', '-T', 'postgres', 'psql', '-U', 'messenger', '-d', 'messenger', '-c',
|
|
'BEGIN; LOCK TABLE messages IN SHARE MODE; SELECT pg_sleep(1.3); COMMIT;'],
|
|
cwd=ROOT, check=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL,
|
|
)
|
|
th = threading.Thread(target=hold_lock)
|
|
th.start()
|
|
time.sleep(0.25)
|
|
r_db = c.message(alice, chat, 'slow-db-check')
|
|
th.join(timeout=10)
|
|
db_req_ms = round(r_db['elapsed'] * 1000, 1)
|
|
|
|
# Hold lock > 2s lock_timeout and send 3 parallel requests so all 3 hit real DB 503 timeouts
|
|
def hold_timeout_lock():
|
|
subprocess.run(
|
|
['docker', 'compose', 'exec', '-T', 'postgres', 'psql', '-U', 'messenger', '-d', 'messenger', '-c',
|
|
'BEGIN; LOCK TABLE messages IN SHARE MODE; SELECT pg_sleep(3.5); COMMIT;'],
|
|
cwd=ROOT, check=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL,
|
|
)
|
|
th2 = threading.Thread(target=hold_timeout_lock)
|
|
th2.start()
|
|
time.sleep(0.3)
|
|
def send_503(idx):
|
|
local = Client('http://localhost:8081', timeout=10)
|
|
return local.call('POST', f'/api/v1/chats/{chat["id"]}/messages', 503, actor=alice, body={'text': f'lock-timeout-{idx}'}, headers={'Idempotency-Key': f'lock-timeout-{int(t0)}-{idx}'})['status']
|
|
with ThreadPoolExecutor(max_workers=3) as ex:
|
|
statuses_503 = list(ex.map(send_503, range(3)))
|
|
th2.join(timeout=10)
|
|
|
|
error_firing = False
|
|
deadline = time.monotonic() + 60
|
|
while time.monotonic() < deadline:
|
|
if alert_state(g, 'HighApiErrorRatio') == 'firing':
|
|
error_firing = True
|
|
break
|
|
time.sleep(2)
|
|
check(error_firing, 'HighApiErrorRatio alert did not fire after 503 DB timeouts')
|
|
|
|
# Now induce slow HTTP handler (outside DB) on api replicas temporarily
|
|
compose('up', '-d', '--force-recreate', '--wait', '--scale', 'api=2', 'api', env_extra={'FAULT_HANDLER_DELAY_MS': '650'})
|
|
wait_api_ready(c)
|
|
r_handler = c.message(alice, chat, 'slow-handler-check')
|
|
handler_req_ms = round(r_handler['elapsed'] * 1000, 1)
|
|
compose('up', '-d', '--force-recreate', '--wait', '--scale', 'api=2', 'api', env_extra={'FAULT_HANDLER_DELAY_MS': '0'})
|
|
wait_api_ready(c)
|
|
|
|
time.sleep(8)
|
|
search = g.tempo_search('{ resource.service.name = "messenger-api" && duration > 500ms }', t0 - 5, time.time() + 5, limit=30)
|
|
slow_traces = search.get('traces', [])
|
|
db_dominant_trace = None
|
|
handler_dominant_trace = None
|
|
for item in slow_traces:
|
|
tr = g.tempo_trace(item['traceID'])
|
|
root_ms = 0.0
|
|
db_ms = 0.0
|
|
for b in tr.get('batches', []):
|
|
for ss in b.get('scopeSpans', []):
|
|
for sp in ss.get('spans', []):
|
|
dur_ms = (int(sp['endTimeUnixNano']) - int(sp['startTimeUnixNano'])) / 1e6
|
|
if sp.get('name', '').startswith('POST /api/v1/chats/{chat_id}/messages'):
|
|
root_ms = max(root_ms, dur_ms)
|
|
if sp.get('name') == 'db.query':
|
|
db_ms += dur_ms
|
|
if root_ms > 500:
|
|
if db_ms > root_ms * 0.6:
|
|
db_dominant_trace = {'trace_id': item['traceID'], 'root_ms': round(root_ms, 1), 'db_query_ms': round(db_ms, 1)}
|
|
elif db_ms < root_ms * 0.25:
|
|
handler_dominant_trace = {'trace_id': item['traceID'], 'root_ms': round(root_ms, 1), 'db_query_ms': round(db_ms, 1)}
|
|
|
|
check(db_dominant_trace is not None and handler_dominant_trace is not None, 'could not distinguish slow DB vs slow HTTP handler in Tempo traces')
|
|
return {
|
|
'slow_db_request_ms': db_req_ms,
|
|
'db_timeout_statuses': statuses_503,
|
|
'slow_handler_request_ms': handler_req_ms,
|
|
'high_api_error_ratio_fired': error_firing,
|
|
'db_dominant_trace': db_dominant_trace,
|
|
'handler_dominant_trace': handler_dominant_trace,
|
|
}
|
|
|
|
def incident_3_telemetry_outage(g, c, alice, bob, chat):
|
|
print('Running Incident 3: Telemetry backend outage (Tempo & Loki stopped) -> API works & bounded RAM...')
|
|
failed_spans_before = prom_scalar(g, 'sum(otelcol_exporter_send_failed_spans_total)')
|
|
failed_logs_before = prom_scalar(g, 'sum(otelcol_exporter_send_failed_log_records_total)')
|
|
compose('stop', 'tempo', 'loki')
|
|
try:
|
|
before_mem = subprocess.check_output(['docker', 'stats', '--no-stream', '--format', '{{.MemUsage}}', 'mtusi_lab6_solution-otel-collector-1'], text=True).strip()
|
|
for i in range(15):
|
|
r = c.message(alice, chat, f'outage-msg-{i}')
|
|
check(r['status'] == 201, 'API failed while telemetry backends were stopped')
|
|
att, _ = c.attachment(alice, chat)
|
|
ready = c.wait_ready(bob, att, wait_seconds=45)
|
|
check(ready['status'] == 'ready', 'worker failed while telemetry backends were stopped')
|
|
time.sleep(20)
|
|
after_mem = subprocess.check_output(['docker', 'stats', '--no-stream', '--format', '{{.MemUsage}}', 'mtusi_lab6_solution-otel-collector-1'], text=True).strip()
|
|
failed_spans_after = prom_scalar(g, 'sum(otelcol_exporter_send_failed_spans_total)')
|
|
failed_logs_after = prom_scalar(g, 'sum(otelcol_exporter_send_failed_log_records_total)')
|
|
finally:
|
|
compose('up', '-d', 'loki', 'tempo')
|
|
g.wait_ready(timeout=60)
|
|
return {
|
|
'messages_succeeded_during_outage': 15,
|
|
'attachment_ready_during_outage': True,
|
|
'collector_mem_before': before_mem,
|
|
'collector_mem_during_outage': after_mem,
|
|
'collector_send_failed_spans_delta': round(failed_spans_after - failed_spans_before),
|
|
'collector_send_failed_logs_delta': round(failed_logs_after - failed_logs_before),
|
|
'api_preserved': True,
|
|
}
|
|
|
|
def main():
|
|
g = GrafanaClient('http://localhost:3000')
|
|
g.wait_ready(timeout=90)
|
|
c = Client('http://localhost:8081')
|
|
alice, bob, _, chat = c.bootstrap()
|
|
|
|
res1 = incident_1_worker_outage(g, c, alice, bob, chat)
|
|
res2 = incident_2_slow_db_vs_handler(g, c, alice, chat)
|
|
res3 = incident_3_telemetry_outage(g, c, alice, bob, chat)
|
|
|
|
report = {
|
|
'incident_1_worker_outage': res1,
|
|
'incident_2_slow_db_vs_handler': res2,
|
|
'incident_3_telemetry_backend_outage': res3,
|
|
'result': 'PASS',
|
|
}
|
|
dest = ROOT / 'evidence/lab6-incidents.json'
|
|
dest.write_text(json.dumps(report, indent=2, ensure_ascii=False) + '\n', encoding='utf-8')
|
|
print(json.dumps(report, indent=2, ensure_ascii=False))
|
|
|
|
if __name__ == '__main__':
|
|
main() |