forked from mtusi2026/mtusi2026lab6
179 lines
8.6 KiB
Python
179 lines
8.6 KiB
Python
#!/usr/bin/env python3
|
|
"""Controlled lab6 failures, with unconditional service recovery and sanitized evidence."""
|
|
import argparse
|
|
from datetime import datetime, timezone
|
|
import json
|
|
import os
|
|
from pathlib import Path
|
|
import shlex
|
|
import subprocess
|
|
import sys
|
|
import time
|
|
import urllib.error
|
|
import urllib.parse
|
|
import urllib.request
|
|
|
|
ROOT = Path(__file__).resolve().parents[1]
|
|
sys.path.insert(0, str(ROOT / 'tests'))
|
|
from client import Client, check
|
|
sys.path.insert(0, str(ROOT / 'student-tests'))
|
|
from observability import get, eventually
|
|
|
|
|
|
def main():
|
|
parser = argparse.ArgumentParser()
|
|
parser.add_argument('--base-url', default='http://localhost:8080')
|
|
parser.add_argument('--prometheus-url', default='http://localhost:9090')
|
|
parser.add_argument('--only', choices=['all', 'retry', 'backend'], default='all')
|
|
args = parser.parse_args()
|
|
compose = shlex.split(os.environ.get('COMPOSE', 'docker compose'))
|
|
def command(*cmd):
|
|
subprocess.run(compose + list(cmd), cwd=ROOT, check=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
|
|
def query(expr):
|
|
return get(args.prometheus_url + '/api/v1/query?' + urllib.parse.urlencode({'query': expr}))['data']['result']
|
|
def value(expr):
|
|
rows = query(expr)
|
|
return float(rows[0]['value'][1]) if rows else 0
|
|
def firing(name):
|
|
alerts = get(args.prometheus_url + '/api/v1/alerts')['data']['alerts']
|
|
return any(a['labels']['alertname'] == name and a['state'] == 'firing' for a in alerts)
|
|
c = Client(args.base_url)
|
|
alice, bob, _, chat = c.bootstrap()
|
|
events = json.loads((ROOT / "evidence/incidents.json").read_text()) if args.only != "all" else []
|
|
def record(name, **fields):
|
|
events.append({'event': name, 'timestamp': datetime.now(timezone.utc).isoformat(), **fields})
|
|
(ROOT / 'evidence/incidents.json').write_text(json.dumps(events, indent=2) + '\n')
|
|
print(name, flush=True)
|
|
if args.only == "all":
|
|
# 1. Durable queue ages while worker is stopped; resume drains the same job.
|
|
command('stop', 'worker')
|
|
try:
|
|
att, _ = c.attachment(alice, chat)
|
|
record('worker_stopped_upload_accepted')
|
|
eventually(lambda: firing('QueueLagGrowing'), timeout=120)
|
|
record('QueueLagGrowing_firing', depth=value('max(queue_depth)'), oldest_seconds=value('max(queue_oldest_age)'))
|
|
finally:
|
|
command('start', 'worker')
|
|
c.wait_ready(bob, att)
|
|
eventually(lambda: not firing('QueueLagGrowing') and value('max(queue_depth)') == 0, timeout=90)
|
|
record('QueueLagGrowing_resolved_backlog_drained')
|
|
# 2. PostgreSQL unavailable: valid authenticated reads must yield 5xx, never successful phantom writes.
|
|
command('stop', 'db')
|
|
statuses = {}
|
|
try:
|
|
record('database_stopped')
|
|
deadline = time.monotonic() + 100
|
|
while time.monotonic() < deadline:
|
|
request = urllib.request.Request(args.base_url + '/api/v1/chats/' + chat['id'] + '/messages',
|
|
headers={'Authorization': 'Bearer ' + alice['token']})
|
|
try:
|
|
response = urllib.request.urlopen(request, timeout=12)
|
|
except urllib.error.HTTPError as error:
|
|
response = error
|
|
with response:
|
|
code = response.status
|
|
statuses[str(code)] = statuses.get(str(code), 0) + 1
|
|
if firing('ApiHighErrorRate'):
|
|
break
|
|
time.sleep(0.5)
|
|
check(firing('ApiHighErrorRate'), 'API error alert did not fire')
|
|
check(any(int(code) >= 500 for code in statuses), 'No server errors observed')
|
|
record('ApiHighErrorRate_firing', response_counts=statuses)
|
|
finally:
|
|
command('start', 'db')
|
|
def recovered():
|
|
return c.call('GET', '/health/ready', schema='Health')['status'] == 200
|
|
eventually(recovered, timeout=90)
|
|
# New traffic moves the one-minute failure window out of the rate calculation.
|
|
deadline = time.monotonic() + 100
|
|
while time.monotonic() < deadline:
|
|
c.call('GET', '/api/v1/chats/' + chat['id'] + '/messages', actor=alice, schema='MessagePage')
|
|
if not firing('ApiHighErrorRate'):
|
|
break
|
|
time.sleep(1)
|
|
check(not firing('ApiHighErrorRate'), 'API alert did not resolve')
|
|
record('ApiHighErrorRate_resolved_database_recovered')
|
|
if args.only != "backend":
|
|
# A retriable S3 failure must preserve the upload trace across the next outbox row.
|
|
import base64
|
|
import uuid
|
|
trace = uuid.uuid4().hex
|
|
command('pause', 'worker')
|
|
paused = True
|
|
try:
|
|
content = (ROOT / 'tests/fixtures/sample.png').read_bytes()
|
|
att = c.call('POST', '/api/v1/chats/' + chat['id'] + '/attachments?filename=sample.png', 202,
|
|
actor=alice, raw=content, headers={'Content-Type': 'image/png',
|
|
'traceparent': '00-' + trace + '-0123456789abcdef-01'}, schema='Attachment')['json']
|
|
auth = os.environ.get('GRAFANA_ADMIN_USER', 'admin') + ':' + (ROOT / 'secrets/grafana_admin_password').read_text().strip()
|
|
grafana = os.environ.get('GRAFANA_URL', 'http://localhost:3000')
|
|
def retry_observed():
|
|
data = get(grafana + '/api/datasources/proxy/uid/tempo/api/traces/' + trace, auth)
|
|
def contains(obj):
|
|
if isinstance(obj, dict):
|
|
if obj.get('key') == 'job.outcome' and obj.get('value', {}).get('stringValue') == 'retry':
|
|
return True
|
|
return any(contains(v) for v in obj.values())
|
|
return isinstance(obj, list) and any(contains(v) for v in obj)
|
|
return contains(data)
|
|
command('stop', 'minio')
|
|
command('unpause', 'worker')
|
|
paused = False
|
|
eventually(retry_observed, timeout=45)
|
|
record('s3_failure_scheduled_retry', trace_id=trace)
|
|
finally:
|
|
command('start', 'minio')
|
|
if paused:
|
|
command('unpause', 'worker')
|
|
c.wait_ready(bob, att)
|
|
auth = os.environ.get('GRAFANA_ADMIN_USER', 'admin') + ':' + (ROOT / 'secrets/grafana_admin_password').read_text().strip()
|
|
grafana = os.environ.get('GRAFANA_URL', 'http://localhost:3000')
|
|
def retry_trace():
|
|
data = get(grafana + '/api/datasources/proxy/uid/tempo/api/traces/' + trace, auth)
|
|
spans = []
|
|
def walk(obj):
|
|
if isinstance(obj, dict):
|
|
if 'spanId' in obj and 'name' in obj:
|
|
spans.append(obj)
|
|
for value_ in obj.values():
|
|
walk(value_)
|
|
elif isinstance(obj, list):
|
|
for value_ in obj:
|
|
walk(value_)
|
|
walk(data)
|
|
by_id = {s['spanId']: s for s in spans}
|
|
# consumer -> enqueue -> publish -> next consumer (all inside the same trace)
|
|
for child in spans:
|
|
if child['name'] != 'attachment.process':
|
|
continue
|
|
producer = by_id.get(child.get('parentSpanId'), {})
|
|
enqueue = by_id.get(producer.get('parentSpanId'), {})
|
|
prior = by_id.get(enqueue.get('parentSpanId'), {})
|
|
if producer.get('name') == 'jobs:attachments publish' and enqueue.get('name') == 'attachment.enqueue' and prior.get('name') == 'attachment.process':
|
|
return True
|
|
return False
|
|
eventually(retry_trace)
|
|
record('retry_same_trace_ready_verified', trace_id=trace)
|
|
# 3. Broken telemetry storage must not break either application process.
|
|
before = value('sum(otelcol_exporter_send_failed_spans)')
|
|
command('stop', 'tempo', 'loki')
|
|
try:
|
|
record('tempo_loki_stopped')
|
|
att, _ = c.attachment(alice, chat)
|
|
c.wait_ready(bob, att)
|
|
for _ in range(20):
|
|
c.message(alice, chat, 'Synthetic telemetry outage probe')
|
|
time.sleep(1)
|
|
eventually(lambda: value('sum(otelcol_exporter_send_failed_spans)') > before, timeout=45)
|
|
record('telemetry_outage_api_worker_healthy',
|
|
failed_span_exports=value('sum(otelcol_exporter_send_failed_spans)')-before,
|
|
collector_rss_bytes=value('max(otelcol_process_memory_rss)'))
|
|
finally:
|
|
command('start', 'tempo', 'loki')
|
|
record('tempo_loki_restarted')
|
|
print('PASS: worker lag and DB error alerts fired/resolved; API and worker survived telemetry backend outage.')
|
|
|
|
|
|
if __name__ == '__main__':
|
|
main()
|