Files
dpl/scripts/fuc-xb-launch/prepare-final-import.py
T

162 lines
7.1 KiB
Python

#!/usr/bin/env python3
"""Validate and restore a frozen FUC backup, then seal the final import input."""
from datetime import datetime, timezone
import gzip
import hashlib
import importlib.util
import json
import os
from pathlib import Path
import re
import secrets
import shutil
import subprocess
import sys
HERE = Path(__file__).resolve().parent
PRIVATE = Path("/var/www/wwwroot/fuc-xb-test/private")
BASELINE = PRIVATE / "refresh-20261105"
TARGET = "fuc_xb_test"
def load_tool(name, path):
spec = importlib.util.spec_from_file_location(name, path)
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
return module
def checked(condition, reason):
if not condition:
raise RuntimeError(reason)
def private(path):
checked(path.resolve() == path and path.stat().st_uid == 0
and path.stat().st_mode & 0o077 == 0, "Private root-owned input required")
return path
def read(path):
return json.loads(private(path).read_text())
def sha(path):
with private(path).open("rb") as handle:
return hashlib.file_digest(handle, "sha256").hexdigest()
def write(path, value):
with path.open("x") as handle:
json.dump(value, handle, indent=2)
handle.write("\n")
handle.flush()
os.fsync(handle.fileno())
def validate_snapshot(path, identity):
counts = {}
with gzip.open(path, "rt", encoding="utf-8") as stream:
header = json.loads(next(stream))
checked(header["kind"] == "header" and header["database_identity_sha256"] == identity,
"Wrong source identity in snapshot")
counts = dict.fromkeys(header["counts"], 0)
for line in stream:
entry = json.loads(line)
if entry["kind"] == "footer":
checked(not stream.readline() and counts == entry["counts"] == header["counts"]
and entry["source_business_writes"] == 0, "Snapshot counts do not reconcile")
return {"complete": True, "sha256": sha(path), "counts": counts,
"snapshot_utc": header["snapshot_utc"], "source_business_writes": 0}
checked(entry["kind"] == "row", "Unrecognized snapshot record")
counts[entry["table"]] += 1
raise RuntimeError("Incomplete snapshot")
def prepare(directory, backup, manifest):
source = "fuc_legacy_restore_" + secrets.token_hex(6)
client = backup.CLIENT
def run_sql(sql):
subprocess.run(client, input=sql, text=True, capture_output=True, check=True, timeout=30)
snapshot = directory / "snapshot.jsonl.gz"
partial = directory / "snapshot.jsonl.gz.part"
checked(not snapshot.exists() and not partial.exists(), "An earlier snapshot exists")
run_sql("CREATE DATABASE " + source + " CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci")
try:
with gzip.open(directory / "old-fuc-full.sql.gz", "rb") as dump:
with subprocess.Popen(client + [source], stdin=subprocess.PIPE,
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) as loader:
try:
shutil.copyfileobj(dump, loader.stdin)
loader.stdin.close()
checked(loader.wait(timeout=60) == 0, "Legacy backup restore failed")
finally:
if loader.poll() is None:
loader.kill()
checked(backup.database_inventory(source) == manifest["inventory"], "Restored table inventory differs")
with partial.open("xb") as compressed:
with subprocess.Popen(["php", str(HERE / "export-final-snapshot.php"), source],
stdout=subprocess.PIPE, stderr=subprocess.DEVNULL) as exporter:
try:
with gzip.GzipFile(filename="", fileobj=compressed, mode="wb", mtime=0) as stream:
shutil.copyfileobj(exporter.stdout, stream)
checked(exporter.wait(timeout=60) == 0, "Restored snapshot export failed")
finally:
if exporter.poll() is None:
exporter.kill()
result = validate_snapshot(partial, manifest["database_sha256"])
partial.rename(snapshot)
write(directory / "snapshot-manifest.json", result)
finally:
partial.unlink(missing_ok=True)
run_sql("DROP DATABASE " + source)
def main():
checked(os.geteuid() == 0 and len(sys.argv) == 2
and re.fullmatch(r"cutover-[0-9]{8}T[0-9]{6}Z", sys.argv[1]), "Expected a cutover window")
directory = private(PRIVATE / sys.argv[1])
freeze = read(directory / "freeze-verified.json")
manifest = read(directory / "old-fuc-full.json")
target = read(directory / "target-verified.json")
now = datetime.now(timezone.utc)
frozen_at = datetime.fromisoformat(freeze["verified_utc"])
backed_up = datetime.fromisoformat(manifest["created_utc"])
checked(frozen_at <= backed_up <= now and (now - frozen_at).total_seconds() <= 1800
and all(freeze.get(key) is True for key in
("old_ingress_maintenance", "old_business_writers_stopped", "old_nodes_drained", "payments_drained"))
and freeze["database_sha256"] == manifest["database_sha256"], "Verified source freeze and backup required")
checked(target["database"] == TARGET and target["public_writes_blocked"] is True
and target["writers_stopped"] is True and re.fullmatch(r"[0-9a-f]{40}", target["release"]),
"Verified XB target gate required")
backup = load_tool("fuc_legacy_backup", HERE / "backup-legacy.py")
dump = private(directory / "old-fuc-full.sql.gz")
checked(dump.stat().st_size == manifest["bytes"] and backup.validate_dump(dump) == manifest["sha256"],
"Frozen full backup fails verification")
checked(not any(manifest["programs"].values()) and all(
"\tBASE TABLE\t" in table for table in manifest["inventory"]), "Legacy stored programs or views require reviewed restore")
checked(not any((directory / file).exists() for file in
("import-ready.json", "snapshot-manifest.json", "projection.json", "identity-overrides.json")),
"Existing cutover inputs require inspection")
prepare(directory, backup, manifest)
write(directory / "identity-overrides.json", read(BASELINE / "identity-overrides.json"))
project = load_tool("fuc_final_projection", HERE.parent / "fuc-xb-refresh" / "project.py")
project.main(directory, BASELINE)
write(directory / "import-ready.json", {
"target": TARGET, "release": target["release"], "freeze_sha256": sha(directory / "freeze-verified.json"),
"target_gate_sha256": sha(directory / "target-verified.json"),
"backup_sha256": manifest["sha256"], "snapshot_sha256": sha(directory / "snapshot.jsonl.gz"),
"projection_sha256": sha(directory / "projection.json"),
})
if __name__ == "__main__":
os.umask(0o077)
try:
main()
except (OSError, ValueError, KeyError, RuntimeError, AssertionError, subprocess.SubprocessError) as failure:
sys.exit(str(failure) if isinstance(failure, RuntimeError) else type(failure).__name__)