forked from mtusi2026/mtusi2026lab3
Grade 4
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) # Docker DNS validity 2s, plus resolver budget 1s.
|
||||
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
|
||||
Reference in New Issue
Block a user