forked from mtusi2026/mtusi2026lab5
137 lines
6.6 KiB
Python
137 lines
6.6 KiB
Python
"""Explicit fault injection against this lab's disposable Compose project."""
|
|
import asyncio
|
|
import hashlib
|
|
from io import BytesIO
|
|
import json
|
|
from pathlib import Path
|
|
import subprocess
|
|
import sys
|
|
import time
|
|
from uuid import UUID
|
|
sys.path.insert(0,str(Path(__file__).resolve().parents[1]/'tests'))
|
|
from client import Client
|
|
from PIL import Image
|
|
import psycopg
|
|
from psycopg.rows import dict_row
|
|
from app.pipeline import broker
|
|
from app.attachments import client as s3client
|
|
|
|
ROOT=Path(__file__).resolve().parents[1]
|
|
results=[]
|
|
def dc(*args):
|
|
subprocess.run(['docker','compose','--env-file','.env',*args],cwd=ROOT,check=True,stdout=subprocess.DEVNULL)
|
|
def sql(query,params=(),one=True):
|
|
with psycopg.connect(Path('/run/secrets/database_url').read_text().strip(),row_factory=dict_row) as conn:
|
|
cur=conn.execute(query,params)
|
|
return cur.fetchone() if cur.description and one else cur.fetchall() if cur.description else None
|
|
def record(name,**data):
|
|
results.append(dict(test=name,result='PASS',**data))
|
|
(ROOT/'evidence/pipeline.json').write_text(json.dumps(results,indent=2))
|
|
print('PASS:',name,flush=True)
|
|
|
|
c=Client(); a,b,e,chat=c.bootstrap(); s3=s3client()
|
|
def meta(att):return c.call('GET','/api/v1/attachments/'+att['id'],actor=a,schema='Attachment')['json']
|
|
def upload():return c.attachment(a,chat)
|
|
def job(att):return sql('SELECT * FROM jobs WHERE attachment_id=%s',(UUID(att['id']),))
|
|
def wait_state(att,state,seconds=120):
|
|
end=time.monotonic()+seconds
|
|
while time.monotonic()<end:
|
|
current=meta(att)
|
|
if current['status']==state:return current
|
|
time.sleep(.3)
|
|
raise AssertionError('state timeout '+state)
|
|
def variants(att):
|
|
ready=c.wait_ready(a,att,120)
|
|
for v in ready['variants']:
|
|
data=c.call('GET','/api/v1/attachments/'+att['id']+'/content?variant='+v['name'],actor=b)['bytes']
|
|
assert hashlib.sha256(data).hexdigest()==v['sha256']
|
|
with Image.open(BytesIO(data)) as im:
|
|
assert im.size==(v['width'],v['height'])
|
|
assert im.format==('WEBP' if v['name']=='optimized' else 'JPEG')
|
|
assert not im.getexif()
|
|
return ready
|
|
try:
|
|
dc('stop','worker')
|
|
att,original=upload()
|
|
c.message(a,chat,'',attachments=[att['id']])
|
|
c.call('GET','/api/v1/attachments/'+att['id']+'/content',409,actor=a)
|
|
c.call('GET','/api/v1/attachments/'+att['id'],404,actor=e)
|
|
deadline=time.monotonic()+10
|
|
while job(att)['last_published'] is None and time.monotonic()<deadline:time.sleep(.2)
|
|
assert job(att)['last_published'] is not None
|
|
before=asyncio.run(broker().xlen('images.v1'))
|
|
assert before>0
|
|
dc('restart','api','broker')
|
|
dc('start','worker')
|
|
ready=variants(att)
|
|
assert c.call('GET','/api/v1/attachments/'+att['id']+'/content',actor=b)['bytes']==original
|
|
record('stopped worker and API broker restart',attachment_id=att['id'],queued_messages=before)
|
|
|
|
dc('stop','publisher')
|
|
att,_=upload()
|
|
assert job(att)['last_published'] is None
|
|
# API is killed after queued+job COMMIT, before any publisher can execute.
|
|
dc('kill','api'); dc('start','api'); dc('start','publisher')
|
|
variants(att)
|
|
record('crash between COMMIT and publish',attachment_id=att['id'])
|
|
|
|
dc('stop','worker')
|
|
# Start worker with one-shot marker inserted while it is running, before upload.
|
|
dc('start','worker');dc('exec','-T','worker','touch','/tmp/crash_after_object')
|
|
att,_=upload()
|
|
ready=variants(att)
|
|
assert job(att)['attempts']>=2
|
|
original_attempts=job(att)['attempts']
|
|
payload=dict(schema_version=1,job_id=str(job(att)['id']),type='attachment.process.v1',attachment_id=att['id'],pipeline_version=1,attempt=1,created_at=att['created_at'])
|
|
async def duplicate():
|
|
q=broker()
|
|
for _ in range(3):await q.xadd('images.v1',{'payload':json.dumps(payload)})
|
|
await q.aclose()
|
|
asyncio.run(duplicate());time.sleep(3)
|
|
assert meta(att)['variants']==ready['variants'] and job(att)['attempts']==original_attempts
|
|
listing=s3.list_objects_v2(Bucket='attachments',Prefix='variants/'+UUID(att['id']).hex+'/v1/')
|
|
assert listing['KeyCount']==3
|
|
record('crash after S3 write and duplicate delivery',attachment_id=att['id'],attempts=original_attempts,variant_objects=3)
|
|
|
|
dc('stop','worker'); att,_=upload()
|
|
# Trusted-storage corruption emulates permanent input failure after acceptance.
|
|
s3.put_object(Bucket='attachments',Key='staging/'+UUID(att['id']).hex,Body=b'broken')
|
|
dc('start','worker');failed=wait_state(att,'failed')
|
|
assert failed['error_code']=='invalid_image'
|
|
c.call('GET','/api/v1/attachments/'+att['id']+'/content',409,actor=a)
|
|
s3.put_object(Bucket='attachments',Key='staging/'+UUID(att['id']).hex,Body=original,ContentType='image/png')
|
|
dc('exec','-T','worker','python','-m','app.pipeline','replay',str(job(att)['id']),'restored staging for lab fault test')
|
|
variants(att)
|
|
assert sql('SELECT count(*) AS n FROM replay_audit WHERE job_id=%s',(job(att)['id'],))['n']==1
|
|
record('permanent failure registry and audited replay',attachment_id=att['id'])
|
|
|
|
dc('stop','worker'); att,_=upload()
|
|
worker_id=subprocess.check_output(['docker','compose','ps','-aq','worker'],cwd=ROOT,text=True).strip()
|
|
dc('stop','minio')
|
|
# docker start intentionally avoids Compose restarting the stopped dependency.
|
|
subprocess.run(['docker','start',worker_id],check=True,stdout=subprocess.DEVNULL)
|
|
# S3 outage intentionally makes API readiness fail, so HAProxy may return 503.
|
|
# Observe the durable job directly until storage and routing are restored.
|
|
deadline=time.monotonic()+150
|
|
while job(att)['state']!='failed' and time.monotonic()<deadline:time.sleep(.5)
|
|
failed=sql('SELECT error_code FROM attachments WHERE id=%s',(UUID(att['id']),))
|
|
assert failed['error_code']=='retry_exhausted' and job(att)['attempts']==5
|
|
dc('start','minio')
|
|
deadline=time.monotonic()+30
|
|
while time.monotonic()<deadline:
|
|
try:
|
|
if meta(att)['status']=='failed':break
|
|
except AssertionError:pass
|
|
time.sleep(.5)
|
|
assert meta(att)['status']=='failed'
|
|
record('temporary failure backoff and bounded retry',attachment_id=att['id'],attempts=5)
|
|
|
|
# Negative upload validation inherited from lab4.
|
|
path='/api/v1/chats/'+chat['id']+'/attachments?filename=bad.png'
|
|
for raw,mime,status in [(b'bad','image/png',415),(original,'image/jpeg',415),(b'x'*(10*1024*1024+1),'image/png',413)]:
|
|
c.call('POST',path,status,actor=a,raw=raw,headers={'Content-Type':mime})
|
|
c.call('POST',path.replace('bad.png','../bad.png'),400,actor=a,raw=original,headers={'Content-Type':'image/png'})
|
|
record('upload limits MIME filename')
|
|
finally:
|
|
dc('start','minio','worker','publisher','api')
|