Files
mtusi2026lab4/student-tests/attachment-failover.py
T

66 lines
2.9 KiB
Python

"""Stop exactly the API that returned upload 201, download via survivor; repeat both."""
import hashlib
import json
import os
from pathlib import Path
import subprocess
import sys
import time
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / 'tests'))
from client import Client, check
from faults import compose, ready
def mappings():
result = {}
for container in compose('ps', '-q', 'api').split():
identity = subprocess.check_output(['docker', 'exec', container, 'python', '-c', 'import urllib.request;print(urllib.request.urlopen("http://localhost:8080/health/live").headers["X-Instance-Id"])'], text=True).strip()
result[identity] = container
return result
def main():
c = Client(os.getenv('BASE_URL', 'http://localhost:8084'), timeout=20)
alice,bob,eve,chat = c.bootstrap()
image=(Path(__file__).resolve().parents[1]/'tests/fixtures/sample.png').read_bytes()
results=[]
stopped=set()
try:
for _ in range(2):
mapping=mappings()
for attempt in range(20):
response=c.call('POST','/api/v1/chats/'+chat['id']+'/attachments?filename=failover.png',201,actor=alice,raw=image,headers={'Content-Type':'image/png'},schema='Attachment')
instance=response['headers']['X-Instance-Id']
container=mapping[instance]
if container not in stopped:
break
else:
raise RuntimeError('could not reach other uploader')
att=response['json']
env=dict(os.environ,TARGET_INSTANCE_ID=instance)
subprocess.run(['scripts/stop-one.sh'],env=env,check=True)
status=subprocess.check_output(['docker','inspect','--format','{{.State.Running}}',container],text=True).strip()
check(status=='false','uploader still running')
deadline=time.monotonic()+10
while True:
try:
download=c.call('GET','/api/v1/attachments/'+att['id']+'/content',actor=bob)
break
except AssertionError:
if time.monotonic()>deadline:
raise
time.sleep(.2)
check(download['headers']['X-Instance-Id']!=instance,'served by stopped uploader')
check(download['bytes']==image,'original changed after uploader stop')
results.append({'uploader_instance':instance,'stopped_container':container[:12],'survivor_instance':download['headers']['X-Instance-Id'],'sha256':hashlib.sha256(download['bytes']).hexdigest(),'original_identical':True})
stopped.add(container)
compose('start','api')
time.sleep(4)
ready(c)
print(json.dumps({'passed':True,'both_uploaders_tested':len(stopped),'scenarios':results},indent=2))
finally:
compose('start','api')
if __name__=='__main__':
main()