Files
ukmesh/scripts/lib/core-projection-backup.py

99 lines
4.2 KiB
Python

"""Capture/verify the dedicated CoreScope projection and its committed source cursors."""
import argparse
from contextlib import closing
import json
from pathlib import Path
import shutil
import sqlite3
import tarfile
import tempfile
def source_files(config):
if config.get('publicProjection') is not True or config.get('dbPath') != '/data/analyzer.db':
raise ValueError('expected the dedicated CoreScope public projection')
files = []
for source in [*config.get('postgresSources', []), *config.get('redisSources', [])]:
cursor = Path(source['statePath'])
if cursor.parent != Path('/data') or cursor.suffix != '.json' or cursor.name == 'config.json':
raise ValueError('expected an explicit projection cursor directly under /data')
files.append(cursor.name)
if len(set(files)) != len(files):
raise ValueError('projection cursors must be distinct')
return files
def readonly(path):
if not path.is_file() or path.is_symlink():
raise ValueError('missing regular projection database')
return sqlite3.connect(path.resolve().as_uri() + '?mode=ro', uri=True)
def state(db):
return [db.execute('SELECT count(*) FROM transmissions').fetchone()[0],
db.execute('SELECT count(*) FROM public_projection_state WHERE singleton=1').fetchone()[0]]
def capture(data, config_path, archive):
with tempfile.TemporaryDirectory(dir=archive.parent) as staging:
stage = Path(staging)
config_bytes = config_path.read_bytes()
cursors = source_files(json.loads(config_bytes))
(stage / 'config.json').write_bytes(config_bytes)
for cursor in cursors:
path = data / cursor
if path.is_symlink():
raise ValueError('projection cursor must be a regular file')
if path.exists():
body = path.read_bytes()
json.loads(body)
(stage / cursor).write_bytes(body)
# Both source adapters advance their durable cursor only after the
# SQLite batch commits. An older cursor safely repeats idempotent work.
with closing(readonly(data / 'analyzer.db')) as src, closing(sqlite3.connect(stage / 'analyzer.db')) as dst:
src.execute('BEGIN')
before = state(src)
src.backup(dst)
if before[1] != 1 or state(dst) != before:
raise ValueError('projection snapshot differs from its source')
with tarfile.open(archive, 'x:gz') as tar:
for path in sorted(stage.iterdir()):
tar.add(path, arcname=path.name, recursive=False)
def restore(archive, target):
target.mkdir(mode=0o700)
with tarfile.open(archive, 'r:gz') as tar:
files = {}
for item in tar:
if not item.isfile() or item.name != Path(item.name).name or item.name in files:
raise ValueError('invalid projection archive member')
files[item.name] = item
cfg = tar.extractfile(files['config.json']).read()
cursors = source_files(json.loads(cfg))
if set(files) - {'config.json', 'analyzer.db', *cursors} or 'analyzer.db' not in files:
raise ValueError('unexpected or missing projection archive member')
for name, member in files.items():
with tar.extractfile(member) as src, (target / name).open('xb') as dst:
shutil.copyfileobj(src, dst)
with closing(readonly(target / 'analyzer.db')) as db:
if db.execute('PRAGMA integrity_check').fetchall() != [('ok',)] or state(db)[1] != 1:
raise ValueError('restored projection database did not verify')
if __name__ == '__main__':
parser = argparse.ArgumentParser()
sub = parser.add_subparsers(dest='action', required=True)
for action, names in [('capture', ('data', 'config', 'archive')), ('restore', ('archive', 'target'))]:
cmd = sub.add_parser(action)
for name in names:
cmd.add_argument(name, type=Path)
args = parser.parse_args()
try:
if args.action == 'capture':
capture(args.data, args.config, args.archive)
else:
restore(args.archive, args.target)
except Exception:
parser.exit(1, 'CoreScope projection recovery failed\n')