forked from mtusi2026/mtusi2026lab7
35 lines
2.2 KiB
Python
35 lines
2.2 KiB
Python
"""Explicit operator lifecycle hooks; volumes and secrets are preserved."""
|
|
from pathlib import Path
|
|
import subprocess,sys,os,json,time,urllib.error
|
|
import bao
|
|
ROOT=Path(__file__).resolve().parents[1];os.chdir(ROOT)
|
|
def dc(*args):return subprocess.check_output(['docker','compose',*args],text=True,stderr=subprocess.DEVNULL).strip()
|
|
def snapshot():
|
|
ids=dc('ps','-a','-q').splitlines()
|
|
data=json.loads(subprocess.check_output(['docker','inspect',*ids],text=True))
|
|
return [{'service':x['Config']['Labels']['com.docker.compose.service'],'container':x['Id'],'started_at':x['State']['StartedAt'],'running':x['State']['Running'],'volumes':[v['Name'] for v in x['Mounts'] if v['Type']=='volume']} for x in data if x['Config']['Labels']['com.docker.compose.service'] not in ['migrate','s3-init','checks']]
|
|
def main():
|
|
action=sys.argv[1];before=snapshot()
|
|
if action=='restart':
|
|
dc('stop');dc('up','-d','db','s3','broker','bao','otel-collector','prometheus','loki','tempo','grafana','otel-collector-tls','prometheus-tls','loki-tls','tempo-tls')
|
|
for i in range(40):
|
|
try:bao.call('sys/init');break
|
|
except urllib.error.URLError:time.sleep(1)
|
|
# This script runs on the operator host, never inside an application container.
|
|
saved=json.loads((ROOT/'operator/bao-init.json').read_text())
|
|
if bao.call('sys/seal-status')['sealed']:bao.call('sys/unseal',{'key':saved['keys_base64'][0]})
|
|
dc('up','-d','--wait','--wait-timeout','40','api1','api2','worker');dc('up','-d','lb')
|
|
elif action=='stop-one':
|
|
target=os.environ['TARGET_INSTANCE_ID'];selected=None
|
|
for service in ['api1','api2']:
|
|
value=dc('exec','-T',service,'node','-e',"fetch('http://127.0.0.1:9001/health/live').then(r=>console.log(r.headers.get('x-instance-id')))")
|
|
if value==target:selected=service;break
|
|
if not selected:raise RuntimeError('Unknown API instance')
|
|
dc('stop','-t','2',selected)
|
|
elif action=='restore':dc('up','-d','--wait','api1','api2')
|
|
else:raise RuntimeError('Unknown action')
|
|
after=snapshot()
|
|
(ROOT/'evidence'/('lifecycle-'+action+'.json')).write_text(json.dumps({'before':before,'after':after},indent=2)+'\n')
|
|
print('PASS: '+action+' complete for lab7; volumes preserved')
|
|
if __name__=='__main__':main()
|