Coverage for scripts/backup_postgres.py: 100%

65 statements  

« prev     ^ index     » next       coverage.py v7.17.3, created at 2026-11-22 12:55 +0000

1"""Back up the Postgres database (V6.6.5, #352): `pg_dump --format=custom` into `state/backups/`, keeping the newest N, 

2and a `last_backup.json` marker the paper-to-live scorecard reads (a backup older than 7 days fails it). 

3 

4The DSN is the runtime one (`AETHER_POSTGRES_DSN`, its `_FILE`, a Docker secret or the keyring); it is passed to pg_dump 

5through the environment, never on the command line. With `--docker` the dump runs inside the compose `postgres` container, 

6for a host without the client tools. Restore: `pg_restore --clean --if-exists -d <dsn> state/backups/<file>.dump` 

7(RUNBOOK "Backups"). 

8 

9 python scripts/backup_postgres.py # local pg_dump 

10 python scripts/backup_postgres.py --docker # docker compose exec postgres pg_dump 

11 python scripts/backup_postgres.py --dry-run # print what would run 

12""" 

13 

14from __future__ import annotations 

15 

16import argparse 

17import json 

18import os 

19import shutil 

20import subprocess 

21import sys 

22from datetime import datetime, timezone 

23from pathlib import Path 

24 

25ROOT = Path(__file__).resolve().parents[1] 

26sys.path.insert(0, str(ROOT)) 

27 

28from execution.secrets_io import secret_env # noqa: E402 

29 

30BACKUP_DIR = ROOT / "state" / "backups" 

31 

32 

33def dump_command(*, docker: bool, target: Path) -> list[str]: 

34 """The pg_dump invocation; the DSN arrives through PG* environment variables (never argv).""" 

35 if docker: 

36 user = os.environ.get("POSTGRES_USER", "aether") 

37 database = os.environ.get("POSTGRES_DB", "aether_quant") 

38 return ["docker", "compose", "exec", "-T", "postgres", "pg_dump", "--format=custom", "-U", user, "-d", database] 

39 return ["pg_dump", "--format=custom", "--file", str(target)] 

40 

41 

42def prune(directory: Path, keep: int) -> list[Path]: 

43 dumps = sorted(directory.glob("aether_quant_*.dump")) 

44 removed = dumps[:-keep] if keep > 0 and len(dumps) > keep else [] 

45 for path in removed: 

46 path.unlink() 

47 return removed 

48 

49 

50def main(argv: list[str] | None = None) -> int: 

51 parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) 

52 parser.add_argument("--docker", action="store_true", help="Run pg_dump inside the compose postgres container") 

53 parser.add_argument("--keep", type=int, default=14, help="Dumps to keep (default 14)") 

54 parser.add_argument("--out-dir", default=str(BACKUP_DIR)) 

55 parser.add_argument("--dry-run", action="store_true") 

56 args = parser.parse_args(argv) 

57 

58 out_dir = Path(args.out_dir) 

59 stamp = datetime.now(timezone.utc).strftime("%Y%m%dT%H%M%SZ") 

60 target = out_dir / f"aether_quant_{stamp}.dump" 

61 command = dump_command(docker=args.docker, target=target) 

62 if args.dry_run: 

63 print(" ".join(command), f"> {target}" if args.docker else "") 

64 return 0 

65 dsn = secret_env("POSTGRES_DSN", "") 

66 if not args.docker and not dsn: 

67 print("error: no Postgres DSN (AETHER_POSTGRES_DSN, its _FILE, a Docker secret or the keyring)", file=sys.stderr) 

68 return 1 

69 if not args.docker and shutil.which("pg_dump") is None: 

70 print("error: pg_dump is not installed; use --docker", file=sys.stderr) 

71 return 1 

72 out_dir.mkdir(parents=True, exist_ok=True) 

73 env = {**os.environ} 

74 if dsn and not args.docker: 

75 env["PGDATABASE"] = dsn # libpq accepts a connection URI as the database name 

76 if args.docker: 

77 with target.open("wb") as handle: 

78 result = subprocess.run(command, cwd=ROOT, stdout=handle, env=env, check=False) 

79 else: 

80 result = subprocess.run(command, cwd=ROOT, env=env, check=False) 

81 if result.returncode != 0 or not target.exists() or target.stat().st_size == 0: 

82 target.unlink(missing_ok=True) 

83 print(f"error: pg_dump failed ({result.returncode})", file=sys.stderr) 

84 return 1 

85 removed = prune(out_dir, args.keep) 

86 marker = {"date": datetime.now(timezone.utc).date().isoformat(), "file": target.name, "bytes": target.stat().st_size, "pruned": [path.name for path in removed]} 

87 (out_dir / "last_backup.json").write_text(json.dumps(marker, indent=1) + "\n", encoding="utf-8") 

88 print(f"backed up to {target} ({marker['bytes']} bytes); kept the newest {args.keep}") 

89 return 0 

90 

91 

92if __name__ == "__main__": 

93 raise SystemExit(main())