feat: implement persistent messenger with PostgreSQL and Redis
Skeleton contracts / contracts (pull_request) Canceled after 0s
Skeleton contracts / contracts (pull_request) Canceled after 0s
This commit is contained in:
@@ -0,0 +1,81 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Backup/restore в новый изолированный контейнер и новый volume.
|
||||
|
||||
Запускать без параллельных писателей. Backup остаётся в backups/ (игнорируется
|
||||
Git), контейнер после проверки останавливается, volume сохраняется.
|
||||
"""
|
||||
from datetime import datetime, timezone
|
||||
from pathlib import Path
|
||||
import json
|
||||
import subprocess
|
||||
import time
|
||||
from uuid import uuid4
|
||||
|
||||
|
||||
def run(args, **kwargs):
|
||||
return subprocess.run(args, check=True, **kwargs)
|
||||
|
||||
|
||||
def main():
|
||||
suffix = datetime.now(timezone.utc).strftime('%Y%m%dT%H%M%SZ') + '-' + uuid4().hex[:6]
|
||||
container = 'lab2-audit-restore-' + suffix.lower()
|
||||
volume = container + '-data'
|
||||
source = ['docker', 'compose', 'exec', '-T', 'postgres']
|
||||
target = ['docker', 'exec', '-i', container]
|
||||
query = """SELECT 'users', count(*) FROM users
|
||||
UNION ALL SELECT 'chats', count(*) FROM chats
|
||||
UNION ALL SELECT 'chat_members', count(*) FROM chat_members
|
||||
UNION ALL SELECT 'messages', count(*) FROM messages
|
||||
UNION ALL SELECT 'sessions', count(*) FROM sessions ORDER BY 1;
|
||||
SELECT id, md5(text) FROM messages ORDER BY id LIMIT 5;"""
|
||||
|
||||
def summary(prefix):
|
||||
return run(prefix + ['psql', '-X', '-v', 'ON_ERROR_STOP=1', '-U', 'messenger',
|
||||
'-d', 'messenger', '-Atc', query],
|
||||
capture_output=True, text=True).stdout
|
||||
|
||||
before = summary(source)
|
||||
Path('backups').mkdir(exist_ok=True)
|
||||
backup = Path('backups') / (suffix + '.dump')
|
||||
with backup.open('xb') as out:
|
||||
backup.chmod(0o600)
|
||||
run(source + ['pg_dump', '-U', 'messenger', '-d', 'messenger', '-Fc'], stdout=out)
|
||||
run(['docker', 'run', '-d', '--name', container, '--network', 'none',
|
||||
'--mount', 'type=volume,src=' + volume + ',dst=/var/lib/postgresql/data',
|
||||
'-e', 'POSTGRES_HOST_AUTH_METHOD=trust', '-e', 'POSTGRES_USER=messenger',
|
||||
'-e', 'POSTGRES_DB=messenger', 'postgres:16.8-bookworm'], capture_output=True)
|
||||
try:
|
||||
for _ in range(60):
|
||||
ready = subprocess.run(target + ['pg_isready', '-U', 'messenger', '-d', 'messenger'],
|
||||
capture_output=True)
|
||||
if ready.returncode == 0:
|
||||
break
|
||||
time.sleep(1)
|
||||
else:
|
||||
raise AssertionError('restore PostgreSQL did not start')
|
||||
start = time.monotonic()
|
||||
with backup.open('rb') as src:
|
||||
run(target + ['pg_restore', '--exit-on-error', '-U', 'messenger',
|
||||
'-d', 'messenger'], stdin=src)
|
||||
elapsed = time.monotonic() - start
|
||||
restored = summary(target)
|
||||
after = summary(source)
|
||||
assert before == after, 'source changed during backup; retry without writers'
|
||||
assert before == restored, 'restored counts or samples differ'
|
||||
evidence = {
|
||||
'date_utc': suffix, 'container': container, 'volume': volume,
|
||||
'network': 'none', 'backup': str(backup),
|
||||
'pg_restore_seconds': round(elapsed, 3),
|
||||
'source_counts_and_sample_md5': before.splitlines(),
|
||||
'restored_counts_and_sample_md5': restored.splitlines(),
|
||||
'result': 'PASS',
|
||||
'limitation': 'counts for all five tables and five message id/text hashes; not full RTO or full DB checksum',
|
||||
}
|
||||
Path('evidence/backup_restore.json').write_text(json.dumps(evidence, indent=2) + '\n')
|
||||
print(json.dumps(evidence, indent=2))
|
||||
finally:
|
||||
run(['docker', 'stop', container], capture_output=True)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
Reference in New Issue
Block a user