Implement lab3 grade 4: balanced API replicas, shared idempotency and failure tests

This commit is contained in:
2026-11-02 20:54:35 +03:00
parent 0ab3a341aa
commit 5332cda400
55 changed files with 102293 additions and 19 deletions
+24
View File
@@ -0,0 +1,24 @@
#!/usr/bin/env python3
"""Create local synthetic credentials once; never print them or replace existing files."""
from pathlib import Path
import secrets
root = Path(__file__).resolve().parents[1]
folder = root / 'secrets'
folder.mkdir(exist_ok=True)
password_file = folder / 'db_password'
if not password_file.exists():
password_file.write_text(secrets.token_hex(24), encoding='utf-8')
password = password_file.read_text(encoding='utf-8').strip()
values = {
'database_url': 'postgresql://messenger:' + password + '@db:5432/messenger',
'cache_url': 'redis://redis:6379/0',
'cursor_key': secrets.token_hex(32),
}
for name, value in values.items():
target = folder / name
if not target.exists():
target.write_text(value, encoding='utf-8')
if not (root / '.env').exists():
(root / '.env').write_text('APP_HOST=0.0.0.0\nAPP_PORT=8080\nAPP_ENV=lab\nSESSION_TTL_SECONDS=3600\nSESSION_STORE=redis\n', encoding='utf-8')
print('Local .env and secrets ready (existing values preserved).')
+40
View File
@@ -0,0 +1,40 @@
#!/usr/bin/env python3
"""Build committed sources with fresh secrets/volumes on a separate local test port."""
import os
from pathlib import Path
import subprocess
import sys
ROOT = Path(__file__).resolve().parents[1]
CLONE = ROOT / 'output' / 'clean-check'
ENV = dict(os.environ, PYTHONUTF8='1', PYTHONIOENCODING='utf-8', APP_PORT='8081', API_REPLICAS='2')
def run(args, cwd=CLONE):
result = subprocess.run(args, cwd=cwd, env=ENV, text=True, encoding='utf-8', errors='replace',
stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
print(result.stdout, end='', flush=True)
if result.returncode:
raise RuntimeError('Clean checkout check failed; see command output')
def main():
if CLONE.exists():
raise SystemExit('output/clean-check already exists; preserve it or move it before a fresh run')
CLONE.parent.mkdir(exist_ok=True)
run(['git', 'clone', '--no-hardlinks', str(ROOT), str(CLONE)], cwd=ROOT)
assert not (CLONE / '.env').exists() and not (CLONE / 'secrets').exists()
run([sys.executable, '-X', 'utf8', 'scripts/bootstrap.py'])
dc = ['docker', 'compose', '-p', 'mtusi-lab3-osokin-clean', '--env-file', '.env']
try:
run([*dc, 'up', '-d', '--build', '--wait'])
run([sys.executable, '-X', 'utf8', 'tests/smoke.py', '--base-url', 'http://127.0.0.1:8081'])
run([*dc, 'exec', '-T', 'api', 'python', 'student-tests/test_idempotency.py'])
run([*dc, 'ps', '--all'])
print('PASS: committed clean clone, new secrets, fresh project volumes, smoke and concurrent replay.')
finally:
run([*dc, 'down']) # Keep even the disposable test data; never down --volumes here.
if __name__ == '__main__':
main()
+27
View File
@@ -0,0 +1,27 @@
#!/usr/bin/env python3
"""Short defense demonstration, with tokens and credentials kept only in memory."""
from collections import Counter
from pathlib import Path
import os
import sys
import uuid
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / 'tests'))
from client import Client, check
c = Client(os.environ.get('BASE_URL', 'http://127.0.0.1:8080'))
alice, bob, eve, chat = c.bootstrap()
instances = Counter(c.call('GET', '/api/v1/users/me', actor=alice, schema='User')['headers']['X-Instance-Id']
for _ in range(12))
check(len(instances) == 2, 'Two API instances must serve the same session')
print('One login; 12 requests through LB:')
for instance, count in sorted(instances.items()):
print(' ', instance, ':', count, 'requests')
key = uuid.uuid4().hex
first = c.message(alice, chat, 'Одно сообщение при двух повторах', key=key)
second = c.message(alice, chat, 'Одно сообщение при двух повторах', key=key)
check(first['json'] == second['json'], 'Replay differs')
print('POST #1:', first['status'], first['headers']['X-Instance-Id'])
print('POST #2:', second['status'], second['headers']['X-Instance-Id'])
print('Same message ID:', first['json']['id'])
print('PASS: shared session, different processes, one message.')
+136
View File
@@ -0,0 +1,136 @@
#!/usr/bin/env python3
"""Operate only this Compose project; never remove a data volume or log secrets."""
import argparse
import json
import os
from pathlib import Path
import subprocess
import time
ROOT = Path(__file__).resolve().parents[1]
EVIDENCE = ROOT / 'evidence'
def command(*args):
return subprocess.check_output(list(args), cwd=ROOT, text=True, encoding='utf-8').strip()
def compose(*args):
return command('docker', 'compose', '--env-file', '.env', *args)
def containers(service=None, all_states=False):
args = ['ps', '-q'] + (['--all'] if all_states else []) + ([service] if service else [])
ids = compose(*args).split()
if not ids:
return []
raw = json.loads(command('docker', 'inspect', *ids))
result = []
for item in raw:
labels = item['Config']['Labels']
result.append(dict(id=item['Id'], name=item['Name'].lstrip('/'),
service=labels['com.docker.compose.service'],
number=int(labels.get('com.docker.compose.container-number', '1')),
hostname=item['Config']['Hostname'], pid=item['State']['Pid'],
started_at=item['State']['StartedAt'], status=item['State']['Status'],
health=item['State'].get('Health', {}).get('Status'),
image=item['Image'],
memory_limit=item['HostConfig']['Memory'],
cpu_limit=item['HostConfig']['NanoCpus'] / 1e9,
published_ports=item['NetworkSettings']['Ports'],
mounts=[dict(name=m.get('Name'), destination=m['Destination'])
for m in item['Mounts'] if m['Type'] == 'volume']))
return sorted(result, key=lambda x: (x['service'], x['number']))
def save(name, data):
EVIDENCE.mkdir(exist_ok=True)
(EVIDENCE / name).write_text(json.dumps(data, ensure_ascii=False, indent=2) + '\n', encoding='utf-8')
def wait_api(count=2, timeout=45):
deadline = time.monotonic() + timeout
while time.monotonic() < deadline:
items = containers('api')
if len(items) == count and all(x['health'] == 'healthy' for x in items):
# DNS + one successful active health check; LB recovery is verified by HTTP tests.
time.sleep(3)
return items
time.sleep(.5)
raise RuntimeError('API containers did not become healthy')
def stop_one():
target = os.environ.get('TARGET_INSTANCE_ID')
items = containers('api')
if len(items) < 2:
raise RuntimeError('Need at least two live API replicas')
selected = [x for x in items if target and target.startswith(x['hostname'] + '-')]
if len(selected) != 1:
raise RuntimeError('TARGET_INSTANCE_ID must identify one live API process')
started = time.monotonic()
command('docker', 'stop', '--time', '8', selected[0]['id'])
after = containers('api', all_states=True)
assert next(x for x in after if x['id'] == selected[0]['id'])['status'] == 'exited'
assert len([x for x in after if x['status'] == 'running']) >= 1
save('stop-one.json', dict(target_instance=target, stopped=selected[0], after=after,
hook_seconds=time.monotonic() - started))
print('Stopped selected API process; other API remains running. evidence/stop-one.json')
def restart():
before = containers()
compose('restart', 'api', 'db', 'redis', 'lb')
after = containers()
for old in before:
if old['service'] == 'migrate':
continue
new = next(x for x in after if x['id'] == old['id'])
assert old['started_at'] != new['started_at'], old['name'] + ' did not restart'
assert old['mounts'] == new['mounts'], 'Volumes changed'
save('restart.json', dict(before=before, after=after))
print('Restarted both API processes, PostgreSQL, Redis and LB; volumes unchanged.')
def replace_one(identifier):
# Pin exact Compose-owned ID before stopping/removing. No storage containers.
old = next(x for x in containers('api') if x['id'] == identifier)
command('docker', 'stop', '--time', '8', old['id'])
command('docker', 'rm', old['id'])
# Keep the other running replica, even if a newly built image is available.
compose('up', '-d', '--no-deps', '--no-recreate', 'api')
items = wait_api()
# Compose may assign a new replica number; verify a new process exists.
assert all(x['id'] != identifier for x in items)
return dict(old=old, after=items)
def rolling():
initial = containers('api')
assert len(initial) == 2, 'This grade 4 demonstration uses exactly two replicas'
changes = []
for old in initial:
changes.append(replace_one(old['id']))
save('rolling-processes.json', dict(before=initial, replacements=changes, after=containers('api')))
print('Replaced each API container in turn; both have new container IDs.')
def main():
parser = argparse.ArgumentParser()
parser.add_argument('action', choices=['restart', 'stop-one', 'rolling', 'restore', 'state'])
action = parser.parse_args().action
if action == 'restart':
restart()
elif action == 'stop-one':
stop_one()
elif action == 'rolling':
rolling()
elif action == 'restore':
compose('up', '-d', '--no-deps', '--no-recreate', 'api')
wait_api()
else:
print(json.dumps(containers(all_states=True), indent=2))
if __name__ == '__main__':
main()
+4
View File
@@ -0,0 +1,4 @@
@echo off
cd /d "%~dp0\.."
python -X utf8 scripts\labctl.py restart
exit /b %errorlevel%
+4
View File
@@ -0,0 +1,4 @@
#!/bin/sh
set -eu
cd "$(dirname "$0")/.."
exec python3 scripts/labctl.py restart
+4
View File
@@ -0,0 +1,4 @@
@echo off
cd /d "%~dp0\.."
python -X utf8 scripts\labctl.py stop-one
exit /b %errorlevel%
+4
View File
@@ -0,0 +1,4 @@
#!/bin/sh
set -eu
cd "$(dirname "$0")/.."
exec python3 scripts/labctl.py stop-one
+60
View File
@@ -0,0 +1,60 @@
#!/usr/bin/env python3
"""Run public checks and all grade 4 demonstrations, preserving sanitized evidence."""
import json
import os
from pathlib import Path
import platform
import subprocess
import sys
from datetime import datetime, timezone
ROOT = Path(__file__).resolve().parents[1]
EVIDENCE = ROOT / 'evidence'
ENV = dict(os.environ, PYTHONUTF8='1', PYTHONIOENCODING='utf-8')
BASE = os.environ.get('BASE_URL', 'http://127.0.0.1:8080')
ENV['BASE_URL'] = BASE
PYTHON = sys.executable
def run(name, args):
print('Running', name, flush=True)
proc = subprocess.run(args, cwd=ROOT, env=ENV, text=True, encoding='utf-8', errors='replace',
stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
output = '$ ' + ' '.join(args).replace(PYTHON, 'python') + '\n' + proc.stdout
output = '\n'.join(line.rstrip() for line in output.splitlines()).rstrip() + '\n'
(EVIDENCE / (name + '.txt')).write_text(output, encoding='utf-8')
print(proc.stdout, end='', flush=True)
if proc.returncode:
raise SystemExit('Check failed: ' + name)
def main():
EVIDENCE.mkdir(exist_ok=True)
run('check', [PYTHON, 'scripts/check_contract.py'])
run('compose', ['docker', 'compose', '--env-file', '.env', 'config', '--quiet'])
run('smoke', [PYTHON, 'tests/smoke.py', '--base-url', BASE])
run('idempotency', ['docker', 'compose', 'exec', '-T', 'api', 'python', 'student-tests/test_idempotency.py'])
run('migration-repeat', ['docker', 'compose', 'run', '--rm', '--no-deps', 'migrate'])
run('persistence', [PYTHON, 'tests/resilience.py', '--mode', 'persistence', '--base-url', BASE,
'--action-script', 'scripts/restart.cmd' if os.name == 'nt' else 'scripts/restart.sh'])
run('restore-before-failover', [PYTHON, 'scripts/labctl.py', 'restore'])
run('failover', [PYTHON, 'tests/resilience.py', '--mode', 'failover', '--base-url', BASE,
'--action-script', 'scripts/stop-one.cmd' if os.name == 'nt' else 'scripts/stop-one.sh'])
run('restore-after-failover', [PYTHON, 'scripts/labctl.py', 'restore'])
run('load-grade4', [PYTHON, 'student-tests/test_recovery.py'])
run('smoke-after', [PYTHON, 'tests/smoke.py', '--base-url', BASE])
run('processes', [PYTHON, 'scripts/labctl.py', 'state'])
info = json.loads(subprocess.check_output(['docker', 'info', '--format', '{{json .}}'], text=True))
environment = dict(verified_at_utc=datetime.now(timezone.utc).isoformat(), host_os=platform.platform(),
client_python=platform.python_version(),
docker={k: info[k] for k in ('ServerVersion', 'OperatingSystem', 'KernelVersion',
'NCPU', 'MemTotal', 'Architecture')}, images={})
for name in ('postgres:17.6-bookworm', 'redis:7.4.5-bookworm', 'haproxy:3.0.16-alpine'):
environment['images'][name] = json.loads(subprocess.check_output(
['docker', 'image', 'inspect', name, '--format', '{{json .RepoDigests}}'], text=True))
(EVIDENCE / 'environment.json').write_text(json.dumps(environment, indent=2) + '\n', encoding='utf-8')
print('PASS: public checks and every grade 4 scenario complete.')
if __name__ == '__main__':
main()