File size: 6,993 Bytes
10a8395
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
#!/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()