#!/usr/bin/env python3 """Index study, pg_dump, restore into a new database, full message checksum.""" import json import os from pathlib import Path import subprocess import time import uuid ROOT = Path(__file__).resolve().parents[1] os.chdir(ROOT) COMPOSE = ['docker', 'compose'] RUN = COMPOSE + ['run', '--rm', '--no-deps', '-T', '-v', str(ROOT / 'student-tests') + ':/app/student-tests:ro'] result = json.loads(subprocess.check_output(RUN + ['api', 'python', 'student-tests/index_study.py'], text=True)) source = result['database'] restore = 'restore_' + uuid.uuid4().hex[:12] restore_container = 'mtusi-lab2-' + restore restore_volume = restore_container + '-data' directory = ROOT / 'backups' directory.mkdir(exist_ok=True, mode=0o700) backup = directory / (source + '.dump') started = time.perf_counter() with backup.open('wb') as output: subprocess.run(COMPOSE + ['exec', '-T', 'postgres', 'pg_dump', '-U', 'messenger', '-Fc', source], stdout=output, check=True) backup.chmod(0o600) dump_seconds = time.perf_counter() - started source_id = subprocess.check_output(COMPOSE + ['ps', '-q', 'postgres'], text=True).strip() source_info = json.loads(subprocess.check_output(['docker', 'inspect', source_id], text=True))[0] network = next(iter(source_info['NetworkSettings']['Networks'])) image = source_info['Config']['Image'] subprocess.run(['docker', 'volume', 'create', restore_volume], check=True, stdout=subprocess.DEVNULL) started_bootstrap = time.perf_counter() restore_id = subprocess.check_output(['docker', 'run', '-d', '--name', restore_container, '--network', network, '--cpus=1', '--memory=512m', '-e', 'POSTGRES_USER=messenger', '-e', 'POSTGRES_DB=' + restore, '-e', 'POSTGRES_PASSWORD_FILE=/run/secrets/postgres_password', '--mount', 'type=volume,src=' + restore_volume + ',dst=/var/lib/postgresql/data', '--mount', 'type=bind,src=' + str(ROOT / 'secrets/postgres_password') + ',dst=/run/secrets/postgres_password,readonly', image], text=True).strip() try: deadline = time.monotonic() + 45 while subprocess.run(['docker', 'exec', restore_container, 'pg_isready', '-U', 'messenger', '-d', restore], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL).returncode: assert time.monotonic() < deadline, 'new PostgreSQL did not become ready' time.sleep(0.3) bootstrap_seconds = time.perf_counter() - started_bootstrap started = time.perf_counter() with backup.open('rb') as data: subprocess.run(['docker', 'exec', '-i', restore_container, 'pg_restore', '-U', 'messenger', '--no-owner', '--exit-on-error', '-d', restore], stdin=data, check=True) restore_seconds = time.perf_counter() - started verified = json.loads(subprocess.check_output(RUN + ['-e', 'RESEARCH_DATABASE=' + restore, '-e', 'RESEARCH_HOST=' + restore_container, 'api', 'python', 'student-tests/index_study.py', '--verify'], text=True)) finally: subprocess.run(['docker', 'stop', '-t', '10', restore_container], check=True, stdout=subprocess.DEVNULL) assert result['snapshot'] == verified, 'restored contents differ' result['backup'] = dict(format='pg_dump custom', bytes=backup.stat().st_size, dump_seconds=dump_seconds, bootstrap_seconds=bootstrap_seconds, restore_seconds=restore_seconds, restored_database=restore, source_container_id=source_id[:12], restore_container_id=restore_id[:12], fresh_restore_volume=restore_volume, source_volume=[m['Name'] for m in source_info['Mounts'] if m['Type'] == 'volume'], matching_counts=True, matching_all_messages_sha256=True, matching_selected_messages=True, restored_snapshot=verified) (ROOT / 'evidence/index-study.json').write_text(json.dumps(result, indent=2)) print('PASS: 100000 messages; two indexes; write costs; backup/restore counts, samples and full checksum match.') print('Backup seconds:', round(dump_seconds, 3), 'Restore seconds:', round(restore_seconds, 3))