forked from mtusi2026/mtusi2026lab4
Add third lab code
This commit is contained in:
@@ -0,0 +1,79 @@
|
||||
"""Project-scoped Docker operations; never read/export container environments."""
|
||||
import json
|
||||
import subprocess
|
||||
import time
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
|
||||
|
||||
def docker(*args):
|
||||
return subprocess.check_output(['docker', *args], cwd=ROOT, text=True, timeout=120).strip()
|
||||
|
||||
|
||||
def compose(*args):
|
||||
return docker('compose', *args)
|
||||
|
||||
|
||||
def snapshot(service=None):
|
||||
ids = compose('ps', '-a', '-q', *([service] if service else [])).split()
|
||||
if not ids:
|
||||
return []
|
||||
# Select fields before returning; no secrets in evidence.
|
||||
template = ('{"id":{{json .Id}},"name":{{json .Name}},"instance":{{json .Config.Hostname}},'
|
||||
'"image":{{json .Image}},"state":{{json .State.Status}},'
|
||||
'"started":{{json .State.StartedAt}},'
|
||||
'"health":{{with index .State "Health"}}{{json .Status}}{{else}}null{{end}},'
|
||||
'"cpu":{{.HostConfig.NanoCpus}},"memory":{{.HostConfig.Memory}},'
|
||||
'"ports":{{json .HostConfig.PortBindings}}}')
|
||||
return [json.loads(line) for line in docker('inspect', '--format', template, *ids).splitlines()]
|
||||
|
||||
|
||||
def wait_api(count=2, timeout=60):
|
||||
deadline = time.monotonic() + timeout
|
||||
while time.monotonic() < deadline:
|
||||
rows = snapshot('api')
|
||||
if len(rows) == count and all(r['health'] == 'healthy' and r['state'] == 'running' for r in rows):
|
||||
time.sleep(3) # Allow the nginx readiness poll (2s) and reload.
|
||||
return rows
|
||||
time.sleep(0.5)
|
||||
raise RuntimeError('API replicas did not become healthy')
|
||||
|
||||
|
||||
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 stop_instance(instance):
|
||||
before = snapshot('api')
|
||||
matches = [r for r in before if r['instance'] == instance and r['state'] == 'running']
|
||||
if len(matches) != 1 or sum(r['state'] == 'running' for r in before) < 2:
|
||||
raise RuntimeError('Target must identify one running API with a running peer')
|
||||
docker('stop', '--time', '8', matches[0]['id'])
|
||||
result = {'target': instance, 'before': before, 'after': snapshot('api')}
|
||||
if next(r for r in result['after'] if r['instance'] == instance)['state'] != 'exited':
|
||||
raise RuntimeError('Target was not stopped')
|
||||
return result
|
||||
|
||||
|
||||
def restore():
|
||||
compose('up', '-d', '--no-deps', '--no-recreate', 'api')
|
||||
return wait_api()
|
||||
|
||||
|
||||
def rolling():
|
||||
before = wait_api()
|
||||
if len(before) != 2:
|
||||
raise RuntimeError('This rolling scenario requires exactly two replicas')
|
||||
steps = []
|
||||
for old in before:
|
||||
stop_instance(old['instance'])
|
||||
# Only remove the selected, already stopped API; never remove a volume.
|
||||
docker('rm', old['id'])
|
||||
compose('up', '-d', '--no-deps', '--no-recreate', '--scale', 'api=2', 'api')
|
||||
steps.append({'replaced': old['id'], 'ready': wait_api()})
|
||||
result = {'before': before, 'steps': steps, 'after': snapshot('api')}
|
||||
if {r['id'] for r in before} & {r['id'] for r in result['after']}:
|
||||
raise RuntimeError('Not all original API containers were replaced')
|
||||
return result
|
||||
@@ -0,0 +1,3 @@
|
||||
@echo off
|
||||
cd /d "%~dp0.."
|
||||
python scripts\restart.py
|
||||
@@ -0,0 +1,28 @@
|
||||
"""Restart the whole lab stack, retaining volumes and recording actual start times."""
|
||||
import subprocess
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
|
||||
|
||||
def snapshot():
|
||||
ids = subprocess.check_output(['docker', 'compose', 'ps', '-q'], cwd=ROOT, text=True).split()
|
||||
return subprocess.check_output(
|
||||
['docker', 'inspect', '--format', '{{.Name}} {{.State.StartedAt}}', *ids],
|
||||
cwd=ROOT, text=True,
|
||||
)
|
||||
|
||||
|
||||
def main():
|
||||
before = snapshot()
|
||||
subprocess.run(['docker', 'compose', 'restart', 'api', 'postgres', 'redis', 'nginx'],
|
||||
cwd=ROOT, check=True, timeout=60)
|
||||
after = snapshot()
|
||||
(ROOT / 'evidence').mkdir(exist_ok=True)
|
||||
(ROOT / 'evidence' / 'restart.txt').write_text(
|
||||
'Command: docker compose restart api postgres redis nginx\nBefore (UTC):\n' + before
|
||||
+ 'After (UTC):\n' + after, encoding='utf-8')
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@@ -0,0 +1,4 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
cd "$(dirname "$0")/.."
|
||||
python3 scripts/restart.py
|
||||
@@ -0,0 +1,3 @@
|
||||
@echo off
|
||||
cd /d "%~dp0.."
|
||||
python scripts\stop-one.py
|
||||
@@ -0,0 +1,5 @@
|
||||
import os
|
||||
from ops import stop_instance
|
||||
|
||||
if __name__ == '__main__':
|
||||
stop_instance(os.environ['TARGET_INSTANCE_ID'])
|
||||
@@ -0,0 +1,4 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
cd "$(dirname "$0")/.."
|
||||
exec python3 scripts/stop-one.py
|
||||
Reference in New Issue
Block a user