#!/usr/bin/env python3 """Create one recoverable legacy FUC database dump after the write freeze.""" import datetime import gzip import hashlib import json import os from pathlib import Path import re import shutil import stat import subprocess import sys PRIVATE = Path("/var/www/wwwroot/fuc-xb-test/private") SOCKET = "/run/mysqld/mysqld.sock" SOURCE = Path("/www/wwwroot/fuuuu.cloud") CLIENT = ["mariadb", "--protocol=socket", "--socket=" + SOCKET, "--batch", "--skip-column-names"] DUMP = [ "mariadb-dump", "--protocol=socket", "--socket=" + SOCKET, "--quick", "--lock-tables", "--routines", "--events", "--triggers", "--hex-blob", "--default-character-set=utf8mb4", "--skip-add-locks", ] def database_inventory(database): result = subprocess.run(CLIENT + [database], input=( "SELECT TABLE_NAME, TABLE_TYPE, COALESCE(ENGINE,'') FROM information_schema.TABLES " "WHERE TABLE_SCHEMA = DATABASE() ORDER BY TABLE_NAME;" ), text=True, capture_output=True, check=True, timeout=30) return result.stdout.splitlines() def database_programs(database): result = subprocess.run(CLIENT + [database], input=( "SELECT (SELECT COUNT(*) FROM information_schema.TRIGGERS WHERE TRIGGER_SCHEMA=DATABASE())," "(SELECT COUNT(*) FROM information_schema.ROUTINES WHERE ROUTINE_SCHEMA=DATABASE())," "(SELECT COUNT(*) FROM information_schema.EVENTS WHERE EVENT_SCHEMA=DATABASE());" ), text=True, capture_output=True, check=True, timeout=30) return dict(zip(("triggers", "routines", "events"), map(int, result.stdout.split()), strict=True)) def validate_dump(path): digest = hashlib.sha256() with path.open("rb") as compressed: for block in iter(lambda: compressed.read(1024 * 1024), b""): digest.update(block) tail = b"" with gzip.open(path, "rb") as dump: for block in iter(lambda: dump.read(1024 * 1024), b""): tail = (tail + block)[-256:] if b"-- Dump completed on " not in tail: raise RuntimeError("MariaDB dump completion footer is missing") return digest.hexdigest() def backup(database, directory): if not re.fullmatch(r"[A-Za-z0-9_]+", database) or database.startswith("fuc_xb"): raise RuntimeError("Expected a legacy source database") inventory = database_inventory(database) programs = database_programs(database) if not inventory: raise RuntimeError("Empty legacy database inventory") destination = directory / "old-fuc-full.sql.gz" manifest = directory / "old-fuc-full.json" temporary = directory / "old-fuc-full.sql.gz.part" if any(os.path.lexists(path) for path in (destination, manifest, temporary)): raise RuntimeError("A legacy backup or partial attempt already exists") if shutil.disk_usage(directory).free < 256 * 1024 * 1024: raise RuntimeError("Insufficient space for the legacy backup") try: with temporary.open("xb") as output: with subprocess.Popen(DUMP + [database], stdout=subprocess.PIPE, stderr=subprocess.DEVNULL) as proc: try: with gzip.GzipFile(filename="", mode="wb", fileobj=output, mtime=0) as zipped: shutil.copyfileobj(proc.stdout, zipped) if proc.wait() != 0: raise RuntimeError("MariaDB legacy backup failed") finally: if proc.poll() is None: proc.kill() output.flush() os.fsync(output.fileno()) digest = validate_dump(temporary) if database_inventory(database) != inventory or database_programs(database) != programs: raise RuntimeError("Legacy database schema changed during the backup") receipt = { "created_utc": datetime.datetime.now(datetime.timezone.utc).isoformat(), "database_sha256": hashlib.sha256(database.encode()).hexdigest(), "inventory": inventory, "programs": programs, "bytes": temporary.stat().st_size, "sha256": digest, } os.rename(temporary, destination) with manifest.open("x") as handle: json.dump(receipt, handle, indent=2) handle.write("\n") handle.flush() os.fsync(handle.fileno()) return receipt finally: temporary.unlink(missing_ok=True) def main(): if len(sys.argv) != 2 or not re.fullmatch(r"cutover-[0-9]{8}T[0-9]{6}Z", sys.argv[1]): raise RuntimeError("An exact cutover window directory is required") directory = PRIVATE / sys.argv[1] gate = directory / "freeze-verified.json" if directory.resolve() != directory or gate.resolve() != gate: raise RuntimeError("A private cutover directory and freeze receipt are required") for path in (directory, gate): info = path.stat() if info.st_uid != os.geteuid() or stat.S_IMODE(info.st_mode) & 0o077: raise RuntimeError("Cutover evidence must be private") with gate.open() as handle: freeze = json.load(handle) stopped = ("old_ingress_maintenance", "old_business_writers_stopped", "old_nodes_drained") verified = datetime.datetime.fromisoformat(freeze["verified_utc"]) age = datetime.datetime.now(datetime.timezone.utc) - verified if any(freeze.get(key) is not True for key in stopped) or not 0 <= age.total_seconds() <= 900: raise RuntimeError("A current verified write freeze is required") database = subprocess.run( ["php", "-r", "require 'config/.config.php'; echo $_ENV['db_database'];"], cwd=SOURCE, capture_output=True, text=True, check=True, timeout=10, ).stdout if hashlib.sha256(database.encode()).hexdigest() != freeze["database_sha256"]: raise RuntimeError("Freeze receipt does not identify the legacy database") receipt = backup(database, directory) print(json.dumps({key: receipt[key] for key in ("created_utc", "bytes", "sha256")})) if __name__ == "__main__": os.umask(0o077) try: main() except (OSError, ValueError, KeyError, RuntimeError, subprocess.SubprocessError) as exc: sys.exit(str(exc) if isinstance(exc, RuntimeError) else type(exc).__name__)