forked from mtusi2026/mtusi2026lab7
41 lines
2.5 KiB
Python
41 lines
2.5 KiB
Python
"""Stop each actual API replica in turn; preserve a session, message and image."""
|
|
import json,os,subprocess,sys,time
|
|
from pathlib import Path
|
|
ROOT=Path(__file__).resolve().parents[1]
|
|
sys.path.insert(0,str(ROOT/'tests'))
|
|
from client import Client,Failure,check
|
|
c=Client('https://localhost:8443',str(ROOT/'secrets/ca/ca.crt'),timeout=2)
|
|
def run(*args):return subprocess.check_output(args,cwd=ROOT,text=True)
|
|
results={}
|
|
for service in ('api-a','api-b'):
|
|
run(sys.executable,'scripts/manage.py','restore')
|
|
a,b,_,chat=c.bootstrap()
|
|
msg=c.message(a,chat,'preserve across '+service)['json']
|
|
att,content=c.attachment(a,chat);c.wait_ready(a,att)
|
|
container=run('docker','compose','ps','-q',service).strip()
|
|
alias=json.loads(run('docker','inspect',container))[0]['Config']['Hostname']
|
|
started=time.monotonic();errors=0;instances=set()
|
|
try:
|
|
subprocess.run([sys.executable,'scripts/manage.py','stop-one'],cwd=ROOT,env=dict(os.environ,TARGET_INSTANCE_ID=alias),check=True,stdout=subprocess.DEVNULL)
|
|
first=None
|
|
for i in range(20):
|
|
try:
|
|
reply=c.message(a,chat,'after-stop-'+service+'-'+str(i))
|
|
instances.add(reply['headers']['X-Instance-Id'])
|
|
if first is None:first=round(time.monotonic()-started,3)
|
|
except Failure:errors+=1
|
|
time.sleep(.1)
|
|
check(first is not None and first<10,'writes failed to recover in 10 seconds')
|
|
check(alias not in instances and len(instances)==1,'stopped API still serving or no survivor')
|
|
state=json.loads(run('docker','inspect',container))[0]['State']
|
|
check(not state['Running'],'replica was not actually stopped')
|
|
messages=c.call('GET','/api/v1/chats/'+chat['id']+'/messages?limit=100',actor=b,schema='MessagePage')['json']['items']
|
|
check(msg in messages,'confirmed message lost')
|
|
actual=c.call('GET','/api/v1/attachments/'+att['id']+'/content',actor=b)['bytes']
|
|
check(actual==content,'original image changed')
|
|
c.call('GET','/api/v1/users/me',actor=a,schema='User')
|
|
results[service]={'actual_container_stopped':True,'existing_session_and_message_preserved':True,'original_image_identical':True,'surviving_instances':len(instances),'first_success_seconds':first,'failed_attempts':errors,'successful_writes':20-errors}
|
|
finally:run(sys.executable,'scripts/manage.py','restore')
|
|
(ROOT/'evidence/failover-each.json').write_text(json.dumps(results,indent=2)+'\n')
|
|
print('PASS: each API stopped in turn; messages, session and image preserved')
|