#!/usr/bin/env python3 """Operator evidence for lab4 persistence: real containers restarted, volumes kept. The public `make test-persistence` proves the contract result. This script adds the missing infrastructure evidence: every API/PostgreSQL/Valkey/S3 container has the same id but a new StartedAt, the named volumes are unchanged, and the same token, message and original attachment still work afterwards. Python 3.9+, standard library only. Requires the running stand and Docker. """ import json 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 snapshot(): state = {'services': {}, 'volumes': [], 'captured_at': M.now_iso()} for service in ('api', 'postgres', 'valkey', 's3'): state['services'][service] = [] for item in M.containers(service): data = M.inspect(item['container_id']) state['services'][service].append({ 'container_id': item['container_id'], 'name': item['name'], 'started_at': data['State'].get('StartedAt'), 'restart_count': data['RestartCount'], 'image_id': item['image_id'], 'volumes': [mount.get('Name') for mount in data.get('Mounts', []) if mount.get('Type') == 'volume'], }) volumes = M.run(['docker', 'volume', 'ls', '--format', '{{.Name}}']).stdout.splitlines() state['volumes'] = sorted(name for name in volumes if name.startswith(M.PROJECT + '-')) return state def main(): args = arguments('Lab4 persistence infrastructure evidence; restarts the stand') EVIDENCE.mkdir(parents=True, exist_ok=True) c = Client(args.base_url, args.ca_file) alice, bob, chat = None, None, None alice, bob, eve, chat = c.bootstrap() message = c.message(alice, chat, 'persistence evidence ' + uuid.uuid4().hex)['json'] attachment, content = c.attachment(alice, chat) before = snapshot() check(len(before['services']['api']) >= 2, 'need at least two API replicas') check(len(before['volumes']) >= 3, 'expected pgdata, valkeydata and s3data volumes') started = M.now_iso() print('running scripts/restart.sh (all API replicas and used stores, volumes kept)') process = subprocess.run([str(ROOT / 'scripts/restart.sh')], cwd=str(ROOT), stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True) check(process.returncode == 0, 'restart.sh failed: ' + process.stderr.strip()[-500:]) finished = M.now_iso() M.wait_ready(120) after = snapshot() checks = {} checks['same_container_ids'] = all( before['services'][service][index]['container_id'] == after['services'][service][index]['container_id'] for service in before['services'] for index in range(len(before['services'][service]))) checks['started_at_changed'] = all( before['services'][service][index]['started_at'] != after['services'][service][index]['started_at'] for service in before['services'] for index in range(len(before['services'][service]))) checks['all_services_restarted'] = all( len(before['services'][service]) == len(after['services'][service]) for service in before['services']) checks['volumes_unchanged'] = before['volumes'] == after['volumes'] # Same token, no re-login. The session lives in the restarted Valkey with # an absolute deadline; the original attachment lives in the restarted S3 # with its metadata in PostgreSQL. me = c.call('GET', '/api/v1/users/me', actor=alice, schema='User')['json'] checks['same_token_still_valid'] = me['id'] == alice['id'] page = c.call('GET', '/api/v1/chats/' + chat['id'] + '/messages?limit=100', actor=bob, schema='MessagePage')['json'] checks['message_survived'] = any(item == message for item in page['items']) metadata = c.call('GET', '/api/v1/attachments/' + attachment['id'], actor=bob, schema='Attachment')['json'] checks['attachment_metadata_survived'] = metadata['sha256'] == attachment['sha256'] download = c.call('GET', '/api/v1/attachments/' + attachment['id'] + '/content', actor=bob) checks['attachment_bytes_survived'] = download['bytes'] == content failed = [key for key, value in checks.items() if not value] result = { 'checked_at': M.now_iso(), 'base_url': args.base_url, 'git_revision': M.run(['git', 'rev-parse', 'HEAD']).stdout.strip(), 'restart_started_at': started, 'restart_finished_at': finished, 'hook_exit_code': process.returncode, 'hook_stdout': process.stdout, 'hook_stderr': process.stderr, 'before': before, 'after': after, 'checks': checks, 'result': 'PASS' if not failed else 'FAIL', 'failed': failed, 'notes': [ 'Container ids are unchanged: compose restarted real containers, it did not recreate them.', 'StartedAt changed for every API/PostgreSQL/Valkey/S3 container.', 'Named volumes were preserved; no volume was removed or re-created.', 'The public make test-persistence additionally checks the contract with the old token.', ], } M.write_json(EVIDENCE / 'persistence.json', result) print(json.dumps({'result': result['result'], 'checks': checks}, ensure_ascii=False)) if failed: raise SystemExit('FAILED checks: ' + ', '.join(failed)) print('PASS: real containers restarted, volumes and data preserved') if __name__ == '__main__': try: main() except (Failure, ValueError, OSError) as exc: print('FAIL:', str(exc)) raise SystemExit(1)