#!/usr/bin/env python3 """Lab4 failover evidence: upload, stop the serving API replica, read elsewhere. The public `make test-failover` checks writes and idempotency. This script adds the lab4-specific proof: the attachment is uploaded by a known replica, that replica is stopped with scripts/stop-one.sh, and the same original is downloaded through a different replica with an identical SHA-256. Python 3.9+, standard library only. Requires the running stand and Docker. """ import hashlib import json import os import subprocess import sys import time import uuid from pathlib import Path ROOT = Path(__file__).resolve().parents[1] sys.path.insert(0, str(ROOT / 'tests')) sys.path.insert(0, str(ROOT / 'scripts')) from client import Client, Failure, arguments, check # noqa: E402 import lab4_metrics as M # noqa: E402 EVIDENCE = ROOT / 'evidence' / 'resilience' def upload_with_instance(c, actor, chat, data): response = c.call('POST', '/api/v1/chats/' + chat['id'] + '/attachments?filename=failover.png', 201, actor=actor, raw=data, headers={'Content-Type': 'image/png'}, schema='Attachment') return response['json'], response['headers']['X-Instance-Id'] def main(): args = arguments('Lab4 upload/failover evidence; stops one API replica and restores it') EVIDENCE.mkdir(parents=True, exist_ok=True) c = Client(args.base_url, args.ca_file, timeout=20) alice, bob, eve, chat = c.bootstrap() data = M.png_random(1400, 1000, seed=42) attachment, uploader = upload_with_instance(c, alice, chat, data) observed = set() deadline = time.monotonic() + 30 while time.monotonic() < deadline: observed.add(c.call('GET', '/api/v1/users/me', actor=alice, schema='User')['headers']['X-Instance-Id']) if len(observed) >= 2: break time.sleep(0.3) check(len(observed) >= 2, 'expected at least two API replicas before failover') check(uploader in observed, 'upload was served by an unknown instance: ' + uploader) command = [str(ROOT / 'scripts/stop-one.sh')] environment = dict(os.environ) environment['TARGET_INSTANCE_ID'] = uploader started = M.now_iso() process = subprocess.run(command, cwd=str(ROOT), env=environment, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True) stopped = M.now_iso() check(process.returncode == 0, 'stop-one.sh failed: ' + process.stderr.strip()[-500:]) # The stopped replica must be the actual Docker container and stay stopped. target_ids = [] for container in M.compose('ps', '-a', '-q', 'api').stdout.split(): hostname = M.run(['docker', 'inspect', '-f', '{{.Config.Hostname}}', container]).stdout.strip() if hostname == uploader: target_ids.append(container) check(len(target_ids) == 1, 'could not map the upload instance to exactly one API container') state = M.inspect(target_ids[0])['State'] check(state['Status'] == 'exited', 'target container is not stopped: ' + state['Status']) M.wait_ready(60) replica_set = set() download = None restored_at = None restored_instances = set() try: deadline = time.monotonic() + 30 while time.monotonic() < deadline: download = c.call('GET', '/api/v1/attachments/' + attachment['id'] + '/content', actor=bob) replica_set.add(download['headers']['X-Instance-Id']) if download['headers']['X-Instance-Id'] != uploader and download['bytes'] == data: break time.sleep(0.3) check(download is not None and download['bytes'] == data, 'download after failover differs from the original') check(download['headers']['X-Instance-Id'] != uploader, 'download was served by the stopped replica') check(uploader not in replica_set, 'download hit the stopped replica') metadata = c.call('GET', '/api/v1/attachments/' + attachment['id'], actor=bob, schema='Attachment')['json'] check(metadata['sha256'] == hashlib.sha256(data).hexdigest(), 'metadata checksum changed after failover') check(metadata['size_bytes'] == len(data), 'metadata size changed after failover') finally: # Restore the replica explicitly; the failover hook itself must leave it # down, and this cleanup runs even when an assertion above fails. M.compose('up', '-d', '--no-deps', 'api') M.wait_ready(120) restored_at = M.now_iso() deadline = time.monotonic() + 30 while time.monotonic() < deadline: restored_instances.add( c.call('GET', '/api/v1/users/me', actor=alice, schema='User')['headers']['X-Instance-Id']) if len(restored_instances) >= 2: break time.sleep(0.3) check(len(restored_instances) >= 2, 'restored stand does not serve two API replicas') result = { 'checked_at': M.now_iso(), 'base_url': args.base_url, 'git_revision': M.run(['git', 'rev-parse', 'HEAD']).stdout.strip(), 'attachment_id': attachment['id'], 'content_bytes': len(data), 'sha256': hashlib.sha256(data).hexdigest(), 'instances_before': sorted(observed), 'upload_instance': uploader, 'stopped_container_id': target_ids[0], 'stopped_container_state': state['Status'], 'stop_started_at': started, 'stop_finished_at': stopped, 'download_instance': download['headers']['X-Instance-Id'] if download else None, 'download_instances_seen': sorted(replica_set), 'download_sha256': hashlib.sha256(download['bytes']).hexdigest() if download else None, 'restored_at': restored_at, 'restored_instances': sorted(restored_instances), 'result': 'PASS', 'notes': [ 'The upload response X-Instance-Id was mapped to the exact Docker hostname.', 'scripts/stop-one.sh left that container exited; the hook is not a restart helper.', 'The download was served by the remaining replica and matched the original bytes.', 'The stopped replica was restored explicitly with docker compose up -d api; Compose may recreate it with a new hostname.', ], } M.write_json(EVIDENCE / 'failover-upload.json', result) print(json.dumps({ 'upload_instance': uploader, 'download_instance': result['download_instance'], 'instances_seen': result['download_instances_seen'], 'sha256_matches': result['download_sha256'] == result['sha256'], 'stopped_container_state': result['stopped_container_state'], 'restored_at': result['restored_at'], }, ensure_ascii=False)) print('PASS: upload survived replica stop and downloaded with the same SHA-256 via another replica') if __name__ == '__main__': try: main() except (Failure, ValueError, OSError) as exc: print('FAIL:', str(exc)) raise SystemExit(1)