"""Explicit fault-injection campaign, scoped to the mtusi-lab5 Compose project.""" import datetime as dt import hashlib import json import os from pathlib import Path import subprocess import sys import time os.environ['PYTHONDONTWRITEBYTECODE']='1' ROOT = Path(__file__).resolve().parents[1] sys.path.insert(0,str(ROOT/'tests')) from client import Client,Failure,check EVIDENCE = ROOT/'evidence' BASE = os.getenv('BASE_URL','http://127.0.0.1:8085') DC = ['docker','compose','--env-file','.env','-f','compose.yaml','-f','compose.test.yaml'] results = [] def command(args,filename=None,allow_failure=False): proc = subprocess.run(args,cwd=ROOT,encoding='utf-8',errors='replace',capture_output=True,timeout=180) if filename: (EVIDENCE/filename).write_text(proc.stdout+proc.stderr,encoding='utf-8') if proc.returncode and not allow_failure: raise RuntimeError('Command failed: '+' '.join(args)+'\n'+proc.stdout+proc.stderr) return proc def compose(*args): return command(DC+list(args)) def dbtool(*args,allow_failure=False): proc = command(DC+['run','--rm','--no-deps','test-runner','python','student-tests/dbtool.py',*map(str,args)],allow_failure=allow_failure) if allow_failure: return proc.returncode return json.loads(proc.stdout) def save(name,value): (EVIDENCE/name).write_text(json.dumps(value,ensure_ascii=False,indent=2),encoding='utf-8') def wait_health(c): deadline = time.monotonic()+90 while time.monotonic()0: break check(time.monotonic()0,'broker lost unconsumed job') c.call('GET','/api/v1/users/me',actor=alice,schema='User') compose('start','worker') _,info = ready(c,bob,att,data) record('worker_off_api_broker_restart',started,{'queue_before':queue_before,'queue_after':queue_after,'before':before,'after':after,'job':info}) started = time.monotonic() baseline = info dbtool('duplicate',att['id'],1,12) time.sleep(2) repeated = dbtool('inspect',att['id']) check(repeated['objects']==baseline['objects'],'successful duplicate rewrote objects') check(repeated['jobs']==baseline['jobs'],'successful duplicate changed job') check(any(e['event']=='duplicate_ignored' for e in repeated['events']),'duplicates not consumed') record('12_duplicate_deliveries',started,{'job':repeated}) for point in ('before_publish','after_publish','before_effect','after_object','before_result_commit','after_result_commit'): started = time.monotonic() compose('stop','-t','1','worker','publisher') att,data = c.attachment(alice,chat) dbtool('fault',att['id'],point) compose('start','publisher','worker') _,info = ready(c,bob,att,data) check(any(e['event']=='fault' and e['detail']==point for e in info['events']),'fault not triggered') if point in ('before_effect','after_object','before_result_commit'): check(any(e['event']=='lease_recovered' for e in info['events']),'dead worker lease not recovered') check(info['jobs'][0]['attempts']==2,'crash attempt accounting') if point=='after_result_commit': deadline = time.monotonic()+40 while not any(e['event']=='duplicate_ignored' for e in info['events']): check(time.monotonic()=1,'invalid envelope registry') stages = dbtool('staging') check('staging/'+att['id'] not in stages['keys'],'ready staging not cleaned') record('invalid_envelope_and_staging_cleanup',started,{'queue':queue,'staging_count':len(stages['keys'])}) finally: compose('start','api1','api2','broker','s3','postgres','publisher','worker') save('before-restart.json',snapshot()) suffix = '.cmd' if os.name=='nt' else '.sh' command([sys.executable,'-X','utf8','tests/resilience.py','--base-url',BASE,'--mode','persistence','--action-script',str(ROOT/'scripts'/('restart'+suffix))],'persistence.txt') save('after-restart.json',snapshot()) print('PASS: public persistence',flush=True) command([sys.executable,'-X','utf8','tests/resilience.py','--base-url',BASE,'--mode','failover','--action-script',str(ROOT/'scripts'/('stop-one'+suffix))],'failover.txt') print('PASS: public failover',flush=True) compose('start','api1','api2') wait_health(c) command([sys.executable,'-X','utf8','tests/smoke.py','--base-url',BASE],'final-smoke.txt') save('final-containers.json',snapshot()) save('verification.json',{'result':'PASS','pipeline_scenarios':len(results),'public_smoke':True,'public_persistence':True,'public_failover':True,'image_acceptance':True,'base_url':BASE}) print('PASS: all lab5 verification',flush=True) if __name__=='__main__': main()