#!/usr/bin/env python3 """Track 2: disposable PostgreSQL A/B experiment and verified backup/restore. Uses sqlprobe and the existing snapshot comparator. Credentials and the actual dump remain in an automatically removed private temporary directory. Only the two containers and volumes created by this invocation can be removed. """ import argparse from datetime import datetime, timezone import hashlib import json import os from pathlib import Path import platform import secrets import subprocess import sys import tempfile import time ROOT = Path(__file__).resolve().parents[2] sys.path.insert(0, str(Path(__file__).resolve().parent)) from resources import Sampler from run import compare_snapshots def command(argv, *, env=None, stdin=None, stdout=None, timeout=180): try: result = subprocess.run(argv, cwd=ROOT, env=env, stdin=stdin, stdout=stdout or subprocess.PIPE, stderr=subprocess.PIPE, timeout=timeout) except (OSError, subprocess.SubprocessError) as exc: raise RuntimeError('Command unavailable or timed out: ' + argv[0]) from exc if result.returncode: # Process arguments/output may contain connection details. Do not print them. safe = [s for s in result.stderr.decode(errors='replace').splitlines() if s.startswith(('research:', 'sqlstate:'))] raise RuntimeError('Command failed: ' + Path(argv[0]).name + ' (exit ' + str(result.returncode) + ')' + ('; ' + '; '.join(safe) if safe else '')) return result.stdout.decode() if stdout is None else '' def save(path, value): path.write_text(json.dumps(value, ensure_ascii=False, indent=2) + '\n') def wait_postgres(name): deadline = time.monotonic() + 75 while time.monotonic() < deadline: result = subprocess.run(['docker', 'exec', name, 'pg_isready', '-U', 'messenger', '-d', 'messenger'], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, timeout=5) if result.returncode == 0: return time.sleep(.3) raise RuntimeError('PostgreSQL did not become ready') def container_state(name): fields = '{{json .State}}\n{{json .Mounts}}\n{{.Id}}' state, mounts, identifier = command(['docker', 'inspect', '--format', fields, name]).splitlines() state, mounts = json.loads(state), json.loads(mounts) return {'id': identifier, 'started_at': state['StartedAt'], 'running': state['Running'], 'oom_killed': state['OOMKilled'], 'volumes': [m['Name'] for m in mounts if m['Type'] == 'volume']} def selected_messages(name, schema): if not schema.startswith('lab2_test_') or not schema.replace('_', '').isalnum(): raise RuntimeError('Unexpected fixture schema') # Values stay in process memory. Evidence retains IDs and content fingerprints. sql = f'''SELECT row_to_json(chosen)::text FROM ( SELECT id,chat_id,sender_id,text,created_at,rn,total FROM ( SELECT m.*,row_number() OVER (PARTITION BY chat_id ORDER BY created_at,id) rn, count(*) OVER (PARTITION BY chat_id) total FROM "{schema}".messages m ) ranked WHERE rn IN (1,(total+1)/2,total) ORDER BY chat_id,rn ) chosen''' raw = command(['docker', 'exec', name, 'psql', '-U', 'messenger', '-d', 'messenger', '-At', '-c', sql]) result = [] for line in raw.splitlines(): row = json.loads(line) result.append({'id': row['id'], 'chat_id': row['chat_id'], 'position': row['rn'], 'chat_rows': row['total'], 'sha256': hashlib.sha256( json.dumps(row, sort_keys=True, ensure_ascii=False).encode()).hexdigest()}) if len(result) != 15: raise RuntimeError('Expected first/middle/last samples from all five chats') return result def main(): p = argparse.ArgumentParser(description=__doc__) p.add_argument('--output', type=Path, required=True) p.add_argument('--postgres-image', default='postgres:18') p.add_argument('--rows', type=int, default=100000) p.add_argument('--repetitions', type=int, default=60) p.add_argument('--series', type=int, default=4) p.add_argument('--write-batches', type=int, default=20) args = p.parse_args() if args.rows < 100000 or args.rows % 100 or args.repetitions < 30 or args.series < 4 or args.series % 2 or args.write_batches < 10: p.error('need >=100k rows divisible by 100, >=30 reads, even >=4 series and >=10 write batches') output = args.output.resolve() output.mkdir(parents=True, exist_ok=False) run_id = 'lab2-research-' + secrets.token_hex(6) names = [run_id + '-source', run_id + '-target'] volumes = [run_id + '-source-data', run_id + '-target-data'] owned_containers, owned_volumes = [], [] summary = {'status': 'FAIL', 'run_id': run_id, 'rows': args.rows, 'started_at': datetime.now(timezone.utc).isoformat(), 'stages': []} sampler = None try: image_info = json.loads(command(['docker', 'image', 'inspect', args.postgres_image]))[0] # Run the immutable locally resolved image ID; the chosen digest is in evidence. image_id = image_info['Id'] hardware = {} if sys.platform == 'darwin': for key in ('hw.model', 'hw.ncpu', 'hw.memsize', 'machdep.cpu.brand_string'): hardware[key] = command(['sysctl', '-n', key]).strip() environment = {'platform': platform.platform(), 'hardware': hardware, 'go': command(['go', 'version']).strip(), 'docker': command(['docker', 'version', '--format', '{{.Server.Version}}']).strip(), 'image': {'id': image_id, 'digests': image_info.get('RepoDigests', []), 'architecture': image_info['Architecture']}, 'limits_per_postgres': {'cpus': 1, 'memory_mib': 512}, 'other_running_containers_at_start': command(['docker', 'ps', '--format', '{{.Names}}']).splitlines()} save(output / 'environment.json', environment) with tempfile.TemporaryDirectory(prefix=run_id + '-') as directory: tmp = Path(directory) env_file = tmp / 'postgres.env' password = secrets.token_hex(24) env_file.write_text('POSTGRES_USER=messenger\nPOSTGRES_DB=messenger\nPOSTGRES_PASSWORD=' + password + '\n') env_file.chmod(0o600) probe = tmp / 'sqlprobe' build_env = dict(os.environ, GOCACHE=os.environ.get('GOCACHE', '/tmp/highload-research-go-cache')) command(['go', 'build', '-mod=readonly', '-o', str(probe), './student-tests/lab2/sqlprobe'], env=build_env) def start(index): name, volume = names[index], volumes[index] command(['docker', 'volume', 'create', '--label', 'highload.research=' + run_id, volume]) owned_volumes.append(volume) command(['docker', 'run', '-d', '--name', name, '--label', 'highload.research=' + run_id, '--cpus', '1', '--memory', '512m', '--memory-swap', '512m', '--env-file', str(env_file), '-p', '127.0.0.1::5432', '-v', volume + ':/var/lib/postgresql', image_id]) owned_containers.append(name) wait_postgres(name) return connection_url(name) def connection_url(name): port = command(['docker', 'port', name, '5432/tcp']).strip().rsplit(':', 1)[1] return f'postgres://messenger:{password}@127.0.0.1:{port}/messenger?sslmode=disable' source_url = start(0) def sqlprobe(mode, url, extra=()): argv = [str(probe), '-mode', mode, '-rows', str(args.rows), '-repetitions', str(args.repetitions), '-series', str(args.series), '-write-batches', str(args.write_batches), '-timeout', '12m', *extra] env = dict(os.environ, LAB2_SQL_DATABASE_URL=url) started = time.monotonic() result = json.loads(command(argv, env=env, timeout=750)) summary['stages'].append({'stage': mode, 'status': 'PASS', 'seconds': time.monotonic() - started}) return result print('PostgreSQL source ready; preparing and comparing >=100k rows', flush=True) sampler = Sampler(names[0], .5) began = time.monotonic() sampler.thread.start() comparison = sqlprobe('research', source_url) ended = time.monotonic() comparison['resources'] = sampler.finish(began, ended, 1) sampler = None save(output / 'indexes.json', comparison) print('Index comparison PASS; preparing persistent backup fixture', flush=True) schema = 'lab2_test_backup_' + secrets.token_hex(5) seed = sqlprobe('seed', source_url, ('-schema', schema)) save(output / 'dataset.json', seed) before = sqlprobe('snapshot', source_url, ('-schema', schema)) selected_before = selected_messages(names[0], schema) save(output / 'source-snapshot.json', before) save(output / 'source-selected.json', selected_before) target_url = start(1) empty = sqlprobe('snapshot', target_url, ('-schema', schema)) if not empty['empty'] or before['identity_sha256'] == empty['identity_sha256']: raise RuntimeError('Restore target must be a distinct empty PostgreSQL instance') before_states = {n: container_state(n) for n in names} if set(before_states[names[0]]['volumes']) & set(before_states[names[1]]['volumes']): raise RuntimeError('Source and target share a volume') save(output / 'storage-before-restore.json', before_states) dump = tmp / 'backup.dump' began = time.monotonic() with dump.open('wb') as stream: dump.chmod(0o600) command(['docker', 'exec', names[0], 'pg_dump', '-U', 'messenger', '-d', 'messenger', '-n', schema, '-Fc', '--no-owner', '--no-acl'], stdout=stream) backup_seconds = time.monotonic() - began dump_hash = hashlib.sha256(dump.read_bytes()).hexdigest() began = time.monotonic() with dump.open('rb') as stream: command(['docker', 'exec', '-i', names[1], 'pg_restore', '-U', 'messenger', '-d', 'messenger', '--exit-on-error', '--no-owner', '--no-acl'], stdin=stream) restore_seconds = time.monotonic() - began restored = sqlprobe('snapshot', target_url, ('-schema', schema)) compare_snapshots(before, restored) selected_after = selected_messages(names[1], schema) if selected_before != selected_after or before != sqlprobe('snapshot', source_url, ('-schema', schema)): raise RuntimeError('Selected messages differ or source changed during backup/restore') save(output / 'restored-snapshot.json', restored) save(output / 'restored-selected.json', selected_after) # Start from disk again, retaining only the new target's own volume. began = time.monotonic() command(['docker', 'restart', '--time', '20', names[1]]) wait_postgres(names[1]) # Docker can allocate a different ephemeral host port after restart. target_url = connection_url(names[1]) restarted = sqlprobe('snapshot', target_url, ('-schema', schema)) compare_snapshots(before, restarted) restart_seconds = time.monotonic() - began save(output / 'storage-after-restart.json', {n: container_state(n) for n in names}) restore = {'status': 'PASS', 'backup_seconds': backup_seconds, 'restore_seconds': restore_seconds, 'target_restart_and_verification_seconds': restart_seconds, 'archive_bytes': dump.stat().st_size, 'archive_sha256': dump_hash, 'source_unchanged': True, 'selected_messages_equal': len(selected_before), 'all_four_table_counts_and_digests_equal': True, 'target_restart_pass': True, 'archive_retained': False, 'scope': 'quiescent synthetic PostgreSQL schema; Redis sessions and post-snapshot writes not included'} save(output / 'backup-restore.json', restore) summary['status'] = 'PASS' print('Backup/restore and target restart PASS', flush=True) except Exception as exc: summary['failure'] = str(exc) if isinstance(exc, RuntimeError) else type(exc).__name__ print('FAIL: ' + summary['failure'], flush=True) finally: if sampler is not None: sampler.stop_event.set() sampler.thread.join(timeout=5) cleanup_errors = [] for name in reversed(owned_containers): try: command(['docker', 'rm', '-f', name], timeout=45) except RuntimeError: cleanup_errors.append('container ' + name) for name in reversed(owned_volumes): try: command(['docker', 'volume', 'rm', name], timeout=30) except RuntimeError: cleanup_errors.append('volume ' + name) summary['cleanup_errors'] = cleanup_errors if cleanup_errors: summary['status'] = 'FAIL' summary['finished_at'] = datetime.now(timezone.utc).isoformat() save(output / 'summary.json', summary) return 0 if summary['status'] == 'PASS' else 1 if __name__ == '__main__': raise SystemExit(main())