Files
mtusi2026lab6/student-tests/incidents.py
T

57 lines
2.8 KiB
Python

#!/usr/bin/env python3
"""Two bounded local faults. Always restore every service in finally blocks."""
import json
import subprocess
import time
from pathlib import Path
from observability import Client, check, logs, eventually, get, ROOT, trace_exists
report = []
def compose(*args):
subprocess.run(['docker','compose',*args], cwd=ROOT, check=True, stdout=subprocess.DEVNULL)
def main():
c = Client('http://localhost:18086')
alice, bob, eve, chat = c.bootstrap()
start = time.time()
compose('stop','worker')
try:
att, _ = c.attachment(alice,chat)
time.sleep(5)
queued = c.call('GET','/api/v1/attachments/'+att['id'],actor=alice,schema='Attachment')['json']
check(queued['status']=='queued','job processed while worker stopped')
accepted_logs = eventually(lambda: logs('messenger-api',' | status="202"'))
report.append({'incident':'worker stopped','started_unix':start,'accepted_status':202,'after_5s':queued['status'],'api_observations':accepted_logs})
finally:
compose('up','-d','--no-deps','worker')
c.wait_ready(alice,att)
report[-1]['recovery_seconds'] = round(time.time()-start,3)
report[-1]['recovered_status'] = 'ready'
# Accept durable work before disabling S3; the worker then experiences real S3 errors.
compose('stop','worker')
att, _ = c.attachment(alice,chat)
start = time.time()
try:
compose('stop','s3')
compose('up','-d','--no-deps','worker')
error_logs = eventually(lambda: [r for r in logs('messenger-worker',' | event="s3.error"') if int(r['values'][0][0])/1e9 >= start], seconds=70)
tid = error_logs[0]['stream']['trace_id']
error_trace = eventually(lambda: trace_exists(tid))
report.append({'incident':'S3 stopped during background processing','started_unix':start,'observations':error_logs, 'error_trace':error_trace})
finally:
compose('up','-d','--no-deps','s3','worker')
# Wait for S3 health before issuing the control upload.
eventually(lambda: subprocess.run(['docker','compose','exec','-T','s3','wget','--quiet','--spider','http://127.0.0.1:9000/healthz'],cwd=ROOT,stdout=subprocess.DEVNULL,stderr=subprocess.DEVNULL).returncode==0)
time.sleep(5)
att2, _ = c.attachment(alice,chat)
c.wait_ready(alice,att2)
report[-1]['recovery_seconds'] = round(time.time()-start,3)
report[-1]['control_upload_status'] = 'ready'
report[-1]['worker_errors'] = get('http://localhost:19091','/api/v1/query',{'query':'worker_jobs_total{outcome=~"retry|failed|error"}'})
(ROOT/'evidence'/'incidents.json').write_text(json.dumps(report,ensure_ascii=False,indent=2)+'\n')
print('PASS: stopped worker retained queued job, S3 outage produced worker errors, both recovered; evidence/incidents.json')
if __name__ == '__main__':
main()