"""Explicit lab3-only lifecycle hooks. Never delete volumes or print credentials.""" import json import os from pathlib import Path import subprocess import sys ROOT = Path(__file__).resolve().parents[1] os.chdir(ROOT) def docker(*args): return subprocess.check_output(['docker', *args], text=True).strip() def compose(*args): return docker('compose', *args) def snapshot(): result = [] containers = compose('ps', '-a', '-q').splitlines() if not containers: return result # One bulk inspect keeps the stop hook well below its 10-second budget. # Only these selected fields are written; Config/Env are never logged. for container in json.loads(docker('inspect', *containers)): service = container['Config']['Labels']['com.docker.compose.service'] if service not in ('lb', 'api1', 'api2', 'db'): continue state, mounts = container['State'], container['Mounts'] result.append({'service': service, 'container': container['Id'], 'running': state['Running'], 'started_at': state['StartedAt'], 'finished_at': state['FinishedAt'], 'volumes': [m['Name'] for m in mounts if m['Type'] == 'volume']}) return result def save(name, value): (ROOT / 'evidence').mkdir(exist_ok=True) (ROOT / 'evidence' / name).write_text(json.dumps(value, indent=2) + '\n', encoding='utf-8') def main(): action = sys.argv[1] if action == 'restart': before = snapshot() compose('stop', 'lb', 'api1', 'api2', 'db') compose('up', '-d', '--wait', '--wait-timeout', '30', 'db') compose('run', '--rm', '--no-deps', 'migrate') compose('up', '-d', '--no-deps', '--wait', '--wait-timeout', '30', 'api1', 'api2') compose('up', '-d', '--no-deps', 'lb') save('restart-scope.json', {'before': before, 'after': snapshot()}) elif action == 'stop-one': target = os.environ.get('TARGET_INSTANCE_ID') if not target: raise RuntimeError('TARGET_INSTANCE_ID required') before = snapshot() selected = None for service in ('api1', 'api2'): code = "fetch('http://127.0.0.1:8080/health/live').then(r=>console.log(r.headers.get('x-instance-id'))).catch(()=>process.exit(1))" instance = compose('exec', '-T', service, 'node', '-e', code) if instance == target: selected = service break if selected is None: raise RuntimeError('Target is not a running API in this lab') compose('stop', '-t', '2', selected) after = snapshot() assert not next(s for s in after if s['service'] == selected)['running'] assert all(s['running'] for s in after if s['service'] != selected) save('stop-' + selected + '.json', {'target_instance': target, 'selected_service': selected, 'before': before, 'after': after}) elif action == 'restore': compose('up', '-d', '--no-deps', '--wait', '--wait-timeout', '30', 'api1', 'api2') else: raise RuntimeError('Unknown action') print('PASS: ' + action + ' completed for mtusi-lab3') if __name__ == '__main__': main()