#!/usr/bin/env python3 """Create a verified, read-only backup of the complete shared PostgreSQL DB.""" from __future__ import annotations import argparse import getpass import hashlib import os from pathlib import Path import shutil import subprocess import tempfile from urllib.parse import unquote, urlparse, parse_qs from datetime import datetime, timezone ROOT = Path(__file__).resolve().parents[1] DEFAULT_OUTPUT = ROOT.parent / "backups" / "postgres" def executable(name: str, override: str | None = None) -> Path: if override: path = Path(override).expanduser().resolve() if path.is_file() and os.access(path, os.X_OK): return path raise SystemExit(f"Executable is unavailable: {path}") # Prefer the current client-only Homebrew libpq package. A newer pg_dump # can dump older servers; an older-major pg_dump refuses newer servers. brew = shutil.which("brew") if brew: result = subprocess.run( [brew, "--prefix", "libpq"], text=True, capture_output=True, check=False, ) candidate = Path(result.stdout.strip()) / "bin" / name if result.returncode == 0 and candidate.is_file(): return candidate found = shutil.which(name) if not found: raise SystemExit(f"Missing required command: {name}") return Path(found) def unique_base(directory: Path) -> Path: stamp = datetime.now(timezone.utc).strftime("%Y%m%dT%H%M%SZ") base = directory / f"full-db-{stamp}" suffix = 0 while any((base.with_suffix(ext)).exists() for ext in (".dump", ".sha256")): suffix += 1 base = directory / f"full-db-{stamp}-{suffix}" return base def service_config(database_url: str) -> str: parsed = urlparse(database_url) if parsed.scheme not in {"postgres", "postgresql"}: raise SystemExit("DATABASE_URL must be a PostgreSQL URL") if not parsed.hostname or not parsed.username or not parsed.path.strip("/"): raise SystemExit("DATABASE_URL is missing host, user, or database") query = parse_qs(parsed.query) values = { "host": parsed.hostname, "port": str(parsed.port or 5432), "dbname": unquote(parsed.path.lstrip("/")), "user": unquote(parsed.username), "password": unquote(parsed.password or ""), "sslmode": query.get("sslmode", ["prefer"])[0], "connect_timeout": query.get("connect_timeout", ["30"])[0], } for key, value in values.items(): if not value or "\n" in value or "\r" in value: raise SystemExit(f"DATABASE_URL contains an invalid {key}") escaped = {key: value.replace("\\", "\\\\") for key, value in values.items()} return "[vaa_readonly_backup]\n" + "\n".join( f"{key}={value}" for key, value in escaped.items() ) + "\n" def sha256(path: Path) -> str: digest = hashlib.sha256() with path.open("rb") as source: for chunk in iter(lambda: source.read(1024 * 1024), b""): digest.update(chunk) return digest.hexdigest() def main() -> None: parser = argparse.ArgumentParser(description=__doc__) parser.add_argument( "output_dir", nargs="?", type=Path, default=DEFAULT_OUTPUT, help=f"backup directory (default: {DEFAULT_OUTPUT})", ) args = parser.parse_args() output = args.output_dir.expanduser().resolve() if output == Path("/"): raise SystemExit("Refusing to use the filesystem root as backup directory") output.mkdir(parents=True, exist_ok=True, mode=0o700) output.chmod(0o700) database_url = os.environ.get("DATABASE_URL") or getpass.getpass( "PostgreSQL DATABASE_URL (hidden): " ) config = service_config(database_url) del database_url pg_dump = executable("pg_dump", os.environ.get("PG_DUMP_BIN")) pg_restore = executable( "pg_restore", os.environ.get("PG_RESTORE_BIN") or str(pg_dump.with_name("pg_restore")), ) base = unique_base(output) archive = base.with_suffix(".dump") partial = base.with_suffix(".dump.partial") contents = base.with_suffix(".contents.txt") checksum = base.with_suffix(".sha256") print("Creating a read-only snapshot of the complete database...") print(f"Destination: {archive}") version = subprocess.run( [str(pg_dump), "--version"], text=True, capture_output=True, check=True ).stdout.strip() print(f"Client: {version}") try: with tempfile.TemporaryDirectory(prefix="vaa-pg-backup-") as temporary: service_file = Path(temporary) / "pg_service.conf" service_file.write_text(config, encoding="utf-8") service_file.chmod(0o600) del config environment = { **os.environ, "PGSERVICEFILE": str(service_file), "PGSERVICE": "vaa_readonly_backup", "PGAPPNAME": "voice-acting-arena-readonly-backup", # This makes the server reject writes even if this script were # accidentally changed to invoke a different SQL-aware tool. "PGOPTIONS": "-c default_transaction_read_only=on -c lock_timeout=10000", } subprocess.run( [ str(pg_dump), "--format=custom", "--compress=6", "--serializable-deferrable", "--lock-wait-timeout=10s", f"--file={partial}", ], env=environment, check=True, ) if not partial.is_file() or partial.stat().st_size == 0: raise RuntimeError("pg_dump produced an empty archive") listing = subprocess.run( [str(pg_restore), "--list", str(partial)], text=True, capture_output=True, check=True, ).stdout if "voice_acting_arena" not in listing: raise RuntimeError("Speech Performance Arena schema is absent") if " public " not in listing and "SCHEMA - public" not in listing: raise RuntimeError("public schema objects are absent") # Hard-link promotion is atomic and fails rather than overwriting an # existing archive. Both paths are guaranteed to be on the same disk. os.link(partial, archive) partial.unlink() contents.write_text(listing, encoding="utf-8") checksum.write_text(f"{sha256(archive)} {archive}\n", encoding="utf-8") for path in (archive, contents, checksum): path.chmod(0o600) finally: partial.unlink(missing_ok=True) print("Backup verified successfully.") print(f"Size: {archive.stat().st_size / 1024 / 1024:.1f} MiB") print(f"Archive: {archive}") print(f"Contents: {contents}") print(f"Checksum: {checksum}") if __name__ == "__main__": main()