forked from mtusi2026/mtusi2026lab7
lab7
This commit is contained in:
@@ -0,0 +1,84 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Operator hooks for unmodified public resilience tests. Never remove volumes/data."""
|
||||
import json,os,ssl,subprocess,sys,time,urllib.request
|
||||
from pathlib import Path
|
||||
ROOT=Path(__file__).resolve().parent.parent
|
||||
os.chdir(ROOT)
|
||||
DC=[str(ROOT/'scripts/dc.sh')]
|
||||
DOCKER=[str(ROOT/'scripts/docker.sh')]
|
||||
DATA={'db':'/var/lib/postgresql/data','cache':'/data','minio':'/data','openbao':'/bao/data','grafana':'/var/lib/grafana','prometheus':'/prometheus','loki':'/loki','tempo':'/var/tempo'}
|
||||
def command(argv,timeout=80):
|
||||
result=subprocess.run(argv,text=True,stdout=subprocess.PIPE,stderr=subprocess.PIPE,timeout=timeout)
|
||||
log=ROOT/'secrets/operator/resilience-hook.log';log.parent.mkdir(parents=True,exist_ok=True)
|
||||
fd=os.open(log,os.O_WRONLY|os.O_CREAT|os.O_APPEND,0o600)
|
||||
with os.fdopen(fd,'w') as stream:stream.write(result.stdout+result.stderr)
|
||||
if result.returncode:raise RuntimeError('Operator command failed; inspect private resilience-hook.log')
|
||||
return result.stdout
|
||||
|
||||
def snapshot():
|
||||
ids=command(DC+['ps','--all','--quiet']).split()
|
||||
if not ids:return {}
|
||||
result={}
|
||||
for c in json.loads(command(DOCKER+['inspect',*ids])):
|
||||
service=c['Config']['Labels']['com.docker.compose.service']
|
||||
instance=next((v.partition('=')[2] for v in c['Config'].get('Env',[]) if v.startswith('INSTANCE_ID=')),c['Config']['Hostname'])
|
||||
result[service]={'id':c['Id'],'instance_id':instance,'running':c['State']['Running'],'started_at':c['State']['StartedAt'],
|
||||
'data_mounts':[{'source':m['Source'],'destination':m['Destination'],'rw':m['RW']} for m in c.get('Mounts',[]) if m['Destination']==DATA.get(service)]}
|
||||
return result
|
||||
|
||||
def wait_ready(timeout=60):
|
||||
values={}
|
||||
envfile=ROOT/'.env'
|
||||
if envfile.exists():values=dict(x.split('=',1) for x in envfile.read_text().splitlines() if '=' in x and not x.startswith('#'))
|
||||
url=os.environ.get('BASE_URL','https://localhost:'+values.get('HTTPS_PORT','8443'))+'/health/ready'
|
||||
ctx=ssl.create_default_context(cafile=str(ROOT/'certs/ca.crt'))
|
||||
opener=urllib.request.build_opener(urllib.request.ProxyHandler({}),urllib.request.HTTPSHandler(context=ctx))
|
||||
end=time.monotonic()+timeout
|
||||
while time.monotonic()<end:
|
||||
try:
|
||||
with opener.open(url,timeout=2) as r:
|
||||
if r.status==200:return
|
||||
except OSError:pass
|
||||
time.sleep(.25)
|
||||
raise RuntimeError('Verified HTTPS readiness did not recover before timeout')
|
||||
|
||||
def main():
|
||||
mode=sys.argv[1]
|
||||
assert mode in ('persistence','failover')
|
||||
started=time.monotonic();before=snapshot()
|
||||
evidence={'status':'RUNNING','mode':mode,'before':before,'volumes_removed':False}
|
||||
out=ROOT/os.environ.get('HOOK_EVIDENCE_FILE','evidence/resilience-'+mode+'-hook.json')
|
||||
assert out.resolve().is_relative_to((ROOT/'evidence').resolve())
|
||||
try:
|
||||
if mode=='persistence':
|
||||
assert all(before.get(s,{}).get('running') for s in ('api','api2','worker','db','cache','minio','openbao','lb')),'Start the full stack before the persistence hook'
|
||||
# Full process replacement includes DB, sessions, broker and S3.
|
||||
command(DC+['down'],timeout=30)
|
||||
command([str(ROOT/'scripts/bootstrap-openbao.sh')],timeout=45)
|
||||
command(DC+['up','-d','--no-build','--wait','--wait-timeout','50'],timeout=55)
|
||||
wait_ready(10)
|
||||
after=snapshot()
|
||||
for service in ('api','api2','worker','db','cache','minio','openbao','lb'):
|
||||
assert after[service]['running'] and after[service]['id']!=before[service]['id'],service
|
||||
for service in DATA:
|
||||
mounts=before[service]['data_mounts']
|
||||
assert len(mounts)==1 and mounts==after[service]['data_mounts'],service
|
||||
evidence['recreated_services']=sorted(s for s in before if s in after and before[s]['id']!=after[s]['id'])
|
||||
else:
|
||||
target=os.environ.get('TARGET_INSTANCE_ID','')
|
||||
candidates=[s for s in ('api','api2') if before.get(s,{}).get('running') and before[s]['instance_id']==target]
|
||||
assert target and len(candidates)==1,'TARGET_INSTANCE_ID must identify exactly one API process'
|
||||
service=candidates[0]
|
||||
command(DC+['stop','--timeout','5',service],timeout=8)
|
||||
after=snapshot()
|
||||
assert not after[service]['running'],'Target API is still running'
|
||||
other='api2' if service=='api' else 'api'
|
||||
assert after[other]['running'],'Surviving replica is not running'
|
||||
for untouched in ('db','cache','minio','openbao','lb','api-tls','api2-tls',other):
|
||||
assert before[untouched]['id']==after[untouched]['id'] and before[untouched]['started_at']==after[untouched]['started_at'],untouched
|
||||
evidence['stopped_service']=service
|
||||
evidence.update(status='PASS',after=after,elapsed_seconds=round(time.monotonic()-started,3))
|
||||
except Exception as e:
|
||||
evidence.update(status='FAIL',error=str(e),elapsed_seconds=round(time.monotonic()-started,3));raise
|
||||
finally:out.write_text(json.dumps(evidence,indent=2)+'\n')
|
||||
if __name__=='__main__':main()
|
||||
Reference in New Issue
Block a user