pgbackup-r2 0.4.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- pgbackup_r2/__init__.py +3 -0
- pgbackup_r2/__main__.py +5 -0
- pgbackup_r2/agecrypt.py +183 -0
- pgbackup_r2/checks.py +118 -0
- pgbackup_r2/cli.py +354 -0
- pgbackup_r2/commands.py +979 -0
- pgbackup_r2/config.py +251 -0
- pgbackup_r2/errors.py +23 -0
- pgbackup_r2/heartbeat.py +42 -0
- pgbackup_r2/pg.py +184 -0
- pgbackup_r2/pgurl.py +140 -0
- pgbackup_r2/retention.py +21 -0
- pgbackup_r2/scheduling.py +69 -0
- pgbackup_r2/stamps.py +58 -0
- pgbackup_r2/storage.py +334 -0
- pgbackup_r2/tiers.py +205 -0
- pgbackup_r2/ui.py +329 -0
- pgbackup_r2/util.py +89 -0
- pgbackup_r2-0.4.0.dist-info/METADATA +113 -0
- pgbackup_r2-0.4.0.dist-info/RECORD +23 -0
- pgbackup_r2-0.4.0.dist-info/WHEEL +4 -0
- pgbackup_r2-0.4.0.dist-info/entry_points.txt +2 -0
- pgbackup_r2-0.4.0.dist-info/licenses/LICENSE +21 -0
pgbackup_r2/__init__.py
ADDED
pgbackup_r2/__main__.py
ADDED
pgbackup_r2/agecrypt.py
ADDED
|
@@ -0,0 +1,183 @@
|
|
|
1
|
+
"""Everything that touches `age`.
|
|
2
|
+
|
|
3
|
+
The private key is never logged and never put in a process argument. When it comes from
|
|
4
|
+
AGE_IDENTITY, it is written to a 0600 file in a private temp directory just for the one
|
|
5
|
+
`age -d` call, and deleted as soon as that call returns, even if it fails.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import contextlib
|
|
11
|
+
import os
|
|
12
|
+
import tempfile
|
|
13
|
+
from collections.abc import Iterator, Sequence
|
|
14
|
+
|
|
15
|
+
from .config import Settings
|
|
16
|
+
from .errors import CommandError, ConfigError
|
|
17
|
+
from .util import run
|
|
18
|
+
|
|
19
|
+
SECRET_PREFIX = "AGE-SECRET-KEY-1"
|
|
20
|
+
PUBLIC_PREFIX = "age1"
|
|
21
|
+
AGE_MAGIC = b"age-encryption.org/v1"
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def check_recipients(recipients: Sequence[str]) -> tuple[str, ...]:
|
|
25
|
+
"""Refuse to continue without at least one public key: no unencrypted backups, ever."""
|
|
26
|
+
if not recipients:
|
|
27
|
+
raise ConfigError(
|
|
28
|
+
"AGE_RECIPIENTS is empty, so the backup can't be encrypted and won't run",
|
|
29
|
+
hint="Make a key pair with `keygen` and put the age1... public key in AGE_RECIPIENTS",
|
|
30
|
+
)
|
|
31
|
+
for r in recipients:
|
|
32
|
+
if r.upper().startswith("AGE-SECRET-KEY-"):
|
|
33
|
+
raise ConfigError(
|
|
34
|
+
"AGE_RECIPIENTS contains a private key (AGE-SECRET-KEY-...). Only the age1... "
|
|
35
|
+
"public key belongs on the server; keep the private key off it",
|
|
36
|
+
hint="Put the age1... public key in AGE_RECIPIENTS, and the private key in "
|
|
37
|
+
"AGE_IDENTITY on your laptop only",
|
|
38
|
+
)
|
|
39
|
+
if not (r.startswith(PUBLIC_PREFIX) or r.startswith("ssh-")):
|
|
40
|
+
raise ConfigError(
|
|
41
|
+
f"AGE_RECIPIENTS entry starting {r[:8]!r}... isn't an age public key "
|
|
42
|
+
"(they start with age1)",
|
|
43
|
+
hint="Copy the AGE_RECIPIENTS=age1... line from `pgb keygen --plain`",
|
|
44
|
+
)
|
|
45
|
+
return tuple(recipients)
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def recipient_args(recipients: Sequence[str]) -> list[str]:
|
|
49
|
+
args: list[str] = []
|
|
50
|
+
for r in check_recipients(recipients):
|
|
51
|
+
args += ["-r", r]
|
|
52
|
+
return args
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def validate_identity(value: str) -> str:
|
|
56
|
+
"""Check AGE_IDENTITY looks like a private key. Returns the key text to write to a file."""
|
|
57
|
+
lines = [ln.strip() for ln in value.strip().splitlines()]
|
|
58
|
+
keys = [ln for ln in lines if ln and not ln.startswith("#")]
|
|
59
|
+
if keys and all(k.startswith(SECRET_PREFIX) for k in keys):
|
|
60
|
+
return "\n".join(keys) + "\n"
|
|
61
|
+
first = keys[0] if keys else ""
|
|
62
|
+
if first.startswith(PUBLIC_PREFIX):
|
|
63
|
+
raise ConfigError(
|
|
64
|
+
"AGE_IDENTITY looks like a public key (age1...), not a private key",
|
|
65
|
+
hint="Use the private key, the line starting AGE-SECRET-KEY-1",
|
|
66
|
+
)
|
|
67
|
+
raise ConfigError(
|
|
68
|
+
"AGE_IDENTITY doesn't start with AGE-SECRET-KEY-1; this looks like a typo or a "
|
|
69
|
+
"truncated paste",
|
|
70
|
+
hint="Copy the whole private key line into your .env, without quotes",
|
|
71
|
+
)
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def require_identity(settings: Settings) -> None:
|
|
75
|
+
"""Fail early, before downloading anything, if no usable private key is configured."""
|
|
76
|
+
if settings.age_identity:
|
|
77
|
+
validate_identity(settings.age_identity)
|
|
78
|
+
return
|
|
79
|
+
if settings.age_identity_file:
|
|
80
|
+
_check_identity_file(settings.age_identity_file)
|
|
81
|
+
return
|
|
82
|
+
raise ConfigError(
|
|
83
|
+
"no private key, so the backup can't be decrypted",
|
|
84
|
+
hint="Set AGE_IDENTITY in your .env (the AGE-SECRET-KEY-1... line), "
|
|
85
|
+
"or AGE_IDENTITY_FILE to a key file",
|
|
86
|
+
)
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
def _check_identity_file(path: str) -> None:
|
|
90
|
+
try:
|
|
91
|
+
with open(path, encoding="utf-8", errors="replace") as f:
|
|
92
|
+
text = f.read()
|
|
93
|
+
except OSError as exc:
|
|
94
|
+
raise ConfigError(
|
|
95
|
+
f"can't read AGE_IDENTITY_FILE {path}: {exc.strerror}",
|
|
96
|
+
hint="Point AGE_IDENTITY_FILE at a readable key file, or use AGE_IDENTITY instead",
|
|
97
|
+
) from None
|
|
98
|
+
if SECRET_PREFIX not in text and "PRIVATE KEY" not in text:
|
|
99
|
+
raise ConfigError(
|
|
100
|
+
f"AGE_IDENTITY_FILE {path} doesn't contain an AGE-SECRET-KEY-1... private key",
|
|
101
|
+
hint="Point AGE_IDENTITY_FILE at the file with the AGE-SECRET-KEY-1... line",
|
|
102
|
+
)
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
@contextlib.contextmanager
|
|
106
|
+
def identity_path(settings: Settings) -> Iterator[str]:
|
|
107
|
+
"""Yield a path to the private key file, removing any temporary copy afterwards."""
|
|
108
|
+
require_identity(settings)
|
|
109
|
+
if settings.age_identity_file:
|
|
110
|
+
yield settings.age_identity_file
|
|
111
|
+
return
|
|
112
|
+
assert settings.age_identity is not None
|
|
113
|
+
content = validate_identity(settings.age_identity)
|
|
114
|
+
directory = tempfile.mkdtemp(prefix="pgbackup-r2-key-") # mode 0700
|
|
115
|
+
path = os.path.join(directory, "identity.txt")
|
|
116
|
+
try:
|
|
117
|
+
fd = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)
|
|
118
|
+
with os.fdopen(fd, "w", encoding="utf-8") as f:
|
|
119
|
+
f.write(content)
|
|
120
|
+
yield path
|
|
121
|
+
finally:
|
|
122
|
+
with contextlib.suppress(FileNotFoundError):
|
|
123
|
+
os.remove(path)
|
|
124
|
+
with contextlib.suppress(OSError):
|
|
125
|
+
os.rmdir(directory)
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
def _decrypt_error(exc: CommandError) -> CommandError:
|
|
129
|
+
text = str(exc)
|
|
130
|
+
if "no identity matched" in text:
|
|
131
|
+
return CommandError(
|
|
132
|
+
"the private key doesn't match this backup: it was encrypted for a different "
|
|
133
|
+
"public key",
|
|
134
|
+
hint="Check AGE_IDENTITY is the partner of the AGE_RECIPIENTS key on the server",
|
|
135
|
+
)
|
|
136
|
+
if "header" in text or "not an age file" in text or "introduction" in text:
|
|
137
|
+
return CommandError(f"this file isn't an age-encrypted backup ({text})")
|
|
138
|
+
return exc
|
|
139
|
+
|
|
140
|
+
|
|
141
|
+
def encrypt_bytes(data: bytes, recipients: Sequence[str]) -> bytes:
|
|
142
|
+
return run(["age", *recipient_args(recipients)], input=data, what="age").stdout
|
|
143
|
+
|
|
144
|
+
|
|
145
|
+
def decrypt_bytes(data: bytes, settings: Settings) -> bytes:
|
|
146
|
+
with identity_path(settings) as key:
|
|
147
|
+
try:
|
|
148
|
+
return run(["age", "-d", "-i", key], input=data, what="age").stdout
|
|
149
|
+
except CommandError as exc:
|
|
150
|
+
raise _decrypt_error(exc) from None
|
|
151
|
+
|
|
152
|
+
|
|
153
|
+
def decrypt_file(src: str, dst: str, settings: Settings) -> None:
|
|
154
|
+
with identity_path(settings) as key:
|
|
155
|
+
try:
|
|
156
|
+
run(["age", "-d", "-i", key, "-o", dst, src], what="age")
|
|
157
|
+
except CommandError as exc:
|
|
158
|
+
with contextlib.suppress(FileNotFoundError):
|
|
159
|
+
os.remove(dst)
|
|
160
|
+
raise _decrypt_error(exc) from None
|
|
161
|
+
|
|
162
|
+
|
|
163
|
+
def keygen() -> tuple[str, str]:
|
|
164
|
+
"""A fresh (public, private) key pair, generated in memory. Nothing is written to disk."""
|
|
165
|
+
out = run(["age-keygen"], what="age-keygen").stdout.decode()
|
|
166
|
+
secret = next((ln.strip() for ln in out.splitlines() if ln.startswith(SECRET_PREFIX)), None)
|
|
167
|
+
if not secret:
|
|
168
|
+
raise CommandError(
|
|
169
|
+
"age-keygen didn't print a private key",
|
|
170
|
+
hint="This is a bug in the image: please report it at "
|
|
171
|
+
"https://github.com/iotabyt/pgbackup-r2/issues",
|
|
172
|
+
)
|
|
173
|
+
public = next(
|
|
174
|
+
(
|
|
175
|
+
ln.split(":", 1)[1].strip()
|
|
176
|
+
for ln in out.splitlines()
|
|
177
|
+
if ln.lower().startswith("# public key:")
|
|
178
|
+
),
|
|
179
|
+
None,
|
|
180
|
+
)
|
|
181
|
+
if not public:
|
|
182
|
+
public = run(["age-keygen", "-y"], input=secret.encode() + b"\n").stdout.decode().strip()
|
|
183
|
+
return public, secret
|
pgbackup_r2/checks.py
ADDED
|
@@ -0,0 +1,118 @@
|
|
|
1
|
+
"""Pure checks: comparing row counts, reading pg_restore --list output."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import re
|
|
6
|
+
from collections.abc import Mapping
|
|
7
|
+
|
|
8
|
+
_PLAIN_IDENT = re.compile(r"^[a-z_][a-z0-9_$]*$")
|
|
9
|
+
_TOC_LINE = re.compile(r"^\d+; \d+ \d+ (.*)$")
|
|
10
|
+
_DUMPED_FROM = re.compile(r"^;\s+Dumped from database version:\s*(.+)$", re.MULTILINE)
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
def allowed_drift(expected: int, tolerance: float) -> int:
|
|
14
|
+
"""Exact match for empty tables, otherwise max(1, expected * tolerance)."""
|
|
15
|
+
if expected == 0:
|
|
16
|
+
return 0
|
|
17
|
+
return max(1, int(expected * tolerance))
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def compare_counts(
|
|
21
|
+
expected: Mapping[str, int], actual: Mapping[str, int], tolerance: float
|
|
22
|
+
) -> list[str]:
|
|
23
|
+
"""One human-readable line per problem; empty means everything matches."""
|
|
24
|
+
problems: list[str] = []
|
|
25
|
+
for table in sorted(expected.keys() - actual.keys()):
|
|
26
|
+
problems.append(f"missing table {table} (manifest has {expected[table]:,} rows)")
|
|
27
|
+
for table in sorted(actual.keys() - expected.keys()):
|
|
28
|
+
problems.append(
|
|
29
|
+
f"extra table {table} ({actual[table]:,} rows) isn't in the manifest; "
|
|
30
|
+
"the scratch database should start empty"
|
|
31
|
+
)
|
|
32
|
+
for table in sorted(expected.keys() & actual.keys()):
|
|
33
|
+
want, got = expected[table], actual[table]
|
|
34
|
+
allowed = allowed_drift(want, tolerance)
|
|
35
|
+
if abs(got - want) > allowed:
|
|
36
|
+
problems.append(
|
|
37
|
+
f"{table}: expected {want:,} rows, restored {got:,} "
|
|
38
|
+
f"(off by {abs(got - want):,}, allowed {allowed:,})"
|
|
39
|
+
)
|
|
40
|
+
return problems
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def count_report(
|
|
44
|
+
expected: Mapping[str, int], actual: Mapping[str, int], tolerance: float
|
|
45
|
+
) -> list[tuple[str, int | None, int | None, bool]]:
|
|
46
|
+
"""(table, expected, restored, ok) for every table on either side, sorted by name."""
|
|
47
|
+
rows = []
|
|
48
|
+
for table in sorted(expected.keys() | actual.keys()):
|
|
49
|
+
want, got = expected.get(table), actual.get(table)
|
|
50
|
+
ok = (
|
|
51
|
+
want is not None
|
|
52
|
+
and got is not None
|
|
53
|
+
and abs(got - want) <= allowed_drift(want, tolerance)
|
|
54
|
+
)
|
|
55
|
+
rows.append((table, want, got, ok))
|
|
56
|
+
return rows
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def quote_ident(name: str) -> str:
|
|
60
|
+
"""Close to Postgres quote_ident (keywords aside, which we only use for display)."""
|
|
61
|
+
if _PLAIN_IDENT.match(name):
|
|
62
|
+
return name
|
|
63
|
+
return '"' + name.replace('"', '""') + '"'
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def split_qualified(key: str) -> tuple[str, str]:
|
|
67
|
+
"""'public."Readings"' -> ('public', 'Readings'). Inverse of quote_ident(s).quote_ident(t)."""
|
|
68
|
+
parts: list[str] = []
|
|
69
|
+
i, n = 0, len(key)
|
|
70
|
+
while i <= n:
|
|
71
|
+
if i < n and key[i] == '"':
|
|
72
|
+
i += 1
|
|
73
|
+
buf = []
|
|
74
|
+
while i < n:
|
|
75
|
+
if key[i] == '"':
|
|
76
|
+
if i + 1 < n and key[i + 1] == '"':
|
|
77
|
+
buf.append('"')
|
|
78
|
+
i += 2
|
|
79
|
+
continue
|
|
80
|
+
i += 1
|
|
81
|
+
break
|
|
82
|
+
buf.append(key[i])
|
|
83
|
+
i += 1
|
|
84
|
+
parts.append("".join(buf))
|
|
85
|
+
else:
|
|
86
|
+
end = key.find(".", i)
|
|
87
|
+
end = n if end == -1 else end
|
|
88
|
+
parts.append(key[i:end])
|
|
89
|
+
i = end
|
|
90
|
+
if i < n and key[i] == ".":
|
|
91
|
+
i += 1
|
|
92
|
+
continue
|
|
93
|
+
break
|
|
94
|
+
if len(parts) != 2:
|
|
95
|
+
return "", key
|
|
96
|
+
return parts[0], parts[1]
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
def toc_tables(toc: str) -> list[tuple[str, str]]:
|
|
100
|
+
"""(schema, table) for every TABLE entry in pg_restore --list output."""
|
|
101
|
+
tables = []
|
|
102
|
+
for line in toc.splitlines():
|
|
103
|
+
m = _TOC_LINE.match(line.strip())
|
|
104
|
+
if not m:
|
|
105
|
+
continue
|
|
106
|
+
rest = m.group(1)
|
|
107
|
+
if not rest.startswith("TABLE ") or rest.startswith("TABLE DATA "):
|
|
108
|
+
continue
|
|
109
|
+
body = rest[len("TABLE ") :]
|
|
110
|
+
schema, _, remainder = body.partition(" ")
|
|
111
|
+
name = remainder.rsplit(" ", 1)[0] if " " in remainder else remainder
|
|
112
|
+
tables.append((schema, name))
|
|
113
|
+
return sorted(tables)
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
def dumped_from(toc: str) -> str | None:
|
|
117
|
+
m = _DUMPED_FROM.search(toc)
|
|
118
|
+
return m.group(1).strip() if m else None
|
pgbackup_r2/cli.py
ADDED
|
@@ -0,0 +1,354 @@
|
|
|
1
|
+
"""pgbackup-r2 command line."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import argparse
|
|
6
|
+
import os
|
|
7
|
+
import signal
|
|
8
|
+
import sys
|
|
9
|
+
from collections.abc import Sequence
|
|
10
|
+
|
|
11
|
+
from botocore.exceptions import (
|
|
12
|
+
BotoCoreError,
|
|
13
|
+
ClientError,
|
|
14
|
+
EndpointConnectionError,
|
|
15
|
+
NoCredentialsError,
|
|
16
|
+
)
|
|
17
|
+
from rich_argparse import RawDescriptionRichHelpFormatter
|
|
18
|
+
|
|
19
|
+
from . import __version__, commands, heartbeat, pg, ui
|
|
20
|
+
from .config import DEFAULTS, Settings
|
|
21
|
+
from .errors import CommandError, PgBackupError
|
|
22
|
+
|
|
23
|
+
PINGS_ON_FAILURE = ("backup", "drill")
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
class _HelpParser(argparse.ArgumentParser):
|
|
27
|
+
"""Help in the order people read it: what the command does, how to call it, examples."""
|
|
28
|
+
|
|
29
|
+
def format_help(self) -> str:
|
|
30
|
+
formatter = self._get_formatter()
|
|
31
|
+
formatter.add_text(self.description)
|
|
32
|
+
formatter.add_usage(self.usage, self._actions, self._mutually_exclusive_groups)
|
|
33
|
+
for group in self._action_groups:
|
|
34
|
+
formatter.start_section(group.title)
|
|
35
|
+
formatter.add_text(group.description)
|
|
36
|
+
formatter.add_arguments(group._group_actions)
|
|
37
|
+
formatter.end_section()
|
|
38
|
+
formatter.add_text(self.epilog)
|
|
39
|
+
return formatter.format_help()
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def _prog() -> str:
|
|
43
|
+
"""'pgb' when run through the pgb wrapper (it sets PGB_VERSION), else 'pgbackup-r2'."""
|
|
44
|
+
return "pgb" if os.environ.get("PGB_VERSION") else "pgbackup-r2"
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def _examples(*lines: tuple[str, str]) -> str:
|
|
48
|
+
width = max(len(cmd) for cmd, _ in lines) + 2
|
|
49
|
+
body = "\n".join(
|
|
50
|
+
f" {cmd:<{width}}{('# ' + note) if note else ''}".rstrip() for cmd, note in lines
|
|
51
|
+
)
|
|
52
|
+
return "Examples:\n" + body
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def build_parser() -> argparse.ArgumentParser:
|
|
56
|
+
prog = _prog()
|
|
57
|
+
d = DEFAULTS
|
|
58
|
+
common = argparse.ArgumentParser(add_help=False)
|
|
59
|
+
common.add_argument(
|
|
60
|
+
"-q", "--quiet", action="store_true", default=argparse.SUPPRESS, help="warnings only"
|
|
61
|
+
)
|
|
62
|
+
common.add_argument(
|
|
63
|
+
"--plain",
|
|
64
|
+
action="store_true",
|
|
65
|
+
default=argparse.SUPPRESS,
|
|
66
|
+
help="plain log lines: no colour, spinners or tables (automatic when not a terminal)",
|
|
67
|
+
)
|
|
68
|
+
|
|
69
|
+
fmt = RawDescriptionRichHelpFormatter
|
|
70
|
+
parser = _HelpParser(
|
|
71
|
+
prog=prog,
|
|
72
|
+
description="Encrypted Postgres backups to R2 or any S3, with restore drills that prove "
|
|
73
|
+
"they work.\nSettings come from environment variables, usually a .env file.",
|
|
74
|
+
epilog=_examples(
|
|
75
|
+
(f"{prog} doctor", "check everything is set up"),
|
|
76
|
+
(f"{prog} backup", "back up now"),
|
|
77
|
+
(f"{prog} drill", "prove the latest backup restores"),
|
|
78
|
+
)
|
|
79
|
+
+ "\n\nDocs: https://pgbackup-r2.iotabyt.com",
|
|
80
|
+
parents=[common],
|
|
81
|
+
formatter_class=fmt,
|
|
82
|
+
)
|
|
83
|
+
parser.add_argument("--version", action="version", version=f"pgbackup-r2 {__version__}")
|
|
84
|
+
sub = parser.add_subparsers(
|
|
85
|
+
dest="command", metavar="COMMAND", required=True, parser_class=_HelpParser
|
|
86
|
+
)
|
|
87
|
+
|
|
88
|
+
def add(name: str, summary: str, *examples: tuple[str, str]) -> argparse.ArgumentParser:
|
|
89
|
+
return sub.add_parser(
|
|
90
|
+
name,
|
|
91
|
+
parents=[common],
|
|
92
|
+
help=(first := summary.split(". ")[0].rstrip("."))[0].lower() + first[1:],
|
|
93
|
+
description=summary,
|
|
94
|
+
epilog=_examples(*((f"{prog} {cmd}", note) for cmd, note in examples)),
|
|
95
|
+
formatter_class=fmt,
|
|
96
|
+
)
|
|
97
|
+
|
|
98
|
+
p = add(
|
|
99
|
+
"backup",
|
|
100
|
+
"Take one encrypted backup now.",
|
|
101
|
+
("backup", ""),
|
|
102
|
+
("backup --no-prune", "keep old backups this time"),
|
|
103
|
+
)
|
|
104
|
+
p.add_argument("--no-prune", action="store_true", help="don't prune old backups afterwards")
|
|
105
|
+
|
|
106
|
+
add(
|
|
107
|
+
"list",
|
|
108
|
+
"List the backups, oldest first, and when the last drill ran.",
|
|
109
|
+
("list", ""),
|
|
110
|
+
("list --plain", "one line per backup, for scripts"),
|
|
111
|
+
)
|
|
112
|
+
|
|
113
|
+
p = add(
|
|
114
|
+
"prune",
|
|
115
|
+
f"Delete backups older than RETENTION_DAYS ({d['RETENTION_DAYS']}), always keeping the "
|
|
116
|
+
f"newest MIN_KEEP ({d['MIN_KEEP']}).",
|
|
117
|
+
("prune --dry-run", "show what would go"),
|
|
118
|
+
("prune", ""),
|
|
119
|
+
)
|
|
120
|
+
p.add_argument("--dry-run", action="store_true", help="show what would be deleted")
|
|
121
|
+
|
|
122
|
+
p = add(
|
|
123
|
+
"restore",
|
|
124
|
+
"Restore a backup into RESTORE_DATABASE_URL.",
|
|
125
|
+
("restore", "the latest backup"),
|
|
126
|
+
("restore 2026-11-18T020000Z", "a specific one"),
|
|
127
|
+
("restore latest --to-production", "over the live database; asks you to confirm"),
|
|
128
|
+
)
|
|
129
|
+
p.add_argument(
|
|
130
|
+
"stamp",
|
|
131
|
+
nargs="?",
|
|
132
|
+
default="latest",
|
|
133
|
+
metavar="STAMP|latest",
|
|
134
|
+
help="latest (the default), a stamp like 2026-11-18T020000Z, or <tier>/<stamp>",
|
|
135
|
+
)
|
|
136
|
+
p.add_argument(
|
|
137
|
+
"--target",
|
|
138
|
+
metavar="URL",
|
|
139
|
+
help="postgres:// URL to restore into (default: $RESTORE_DATABASE_URL, which keeps "
|
|
140
|
+
"the password out of the process list)",
|
|
141
|
+
)
|
|
142
|
+
p.add_argument(
|
|
143
|
+
"--to-production",
|
|
144
|
+
action="store_true",
|
|
145
|
+
help="allow restoring over DATABASE_URL (asks you to type the database name)",
|
|
146
|
+
)
|
|
147
|
+
|
|
148
|
+
p = add(
|
|
149
|
+
"drill",
|
|
150
|
+
"Restore a backup into a throwaway database and check every table.",
|
|
151
|
+
("drill", "the latest backup"),
|
|
152
|
+
("drill 2026-11-18T020000Z", "a specific one"),
|
|
153
|
+
("drill monthly/2026-11-01T020000Z", "with TIERS: one in a given tier"),
|
|
154
|
+
)
|
|
155
|
+
p.add_argument(
|
|
156
|
+
"stamp",
|
|
157
|
+
nargs="?",
|
|
158
|
+
default="latest",
|
|
159
|
+
metavar="STAMP|latest",
|
|
160
|
+
help="latest (the default), a stamp like 2026-11-18T020000Z, or <tier>/<stamp>",
|
|
161
|
+
)
|
|
162
|
+
p.add_argument(
|
|
163
|
+
"--preflight",
|
|
164
|
+
action="store_true",
|
|
165
|
+
help="only check the private key, the bucket and that the backup exists; restores "
|
|
166
|
+
"nothing and needs no database (pgb drill runs this before starting Postgres)",
|
|
167
|
+
)
|
|
168
|
+
|
|
169
|
+
add(
|
|
170
|
+
"keygen",
|
|
171
|
+
"Print a new key pair. Nothing is written to disk.",
|
|
172
|
+
("keygen", ""),
|
|
173
|
+
("keygen --plain", "exactly as the lines go in .env"),
|
|
174
|
+
)
|
|
175
|
+
|
|
176
|
+
add(
|
|
177
|
+
"doctor",
|
|
178
|
+
"Check the settings, the database, the bucket, the keys and the last drill.",
|
|
179
|
+
("doctor", ""),
|
|
180
|
+
)
|
|
181
|
+
|
|
182
|
+
p = add(
|
|
183
|
+
"detect",
|
|
184
|
+
"Look at the bucket's folders and lifecycle rules, and suggest TIERS.",
|
|
185
|
+
("detect", ""),
|
|
186
|
+
("detect --env-lines", "only the suggested .env lines, for scripts"),
|
|
187
|
+
)
|
|
188
|
+
p.add_argument(
|
|
189
|
+
"--env-lines",
|
|
190
|
+
action="store_true",
|
|
191
|
+
help="print only the suggested .env lines on stdout (the explanation goes to stderr)",
|
|
192
|
+
)
|
|
193
|
+
|
|
194
|
+
p = add(
|
|
195
|
+
"decrypt",
|
|
196
|
+
"Write a backup out as a plain pg_dump file.",
|
|
197
|
+
("decrypt latest --out /out/backup.dump", ""),
|
|
198
|
+
("decrypt --file /out/x.dump.age --out /out/x.dump", "a file you downloaded"),
|
|
199
|
+
)
|
|
200
|
+
p.add_argument(
|
|
201
|
+
"stamp",
|
|
202
|
+
nargs="?",
|
|
203
|
+
default=None,
|
|
204
|
+
metavar="STAMP|latest",
|
|
205
|
+
help="latest (the default), a stamp like 2026-11-18T020000Z, or <tier>/<stamp>",
|
|
206
|
+
)
|
|
207
|
+
p.add_argument("--file", metavar="PATH", help="decrypt a .dump.age on disk instead (no S3)")
|
|
208
|
+
p.add_argument("--out", required=True, metavar="PATH", help="where to write the dump")
|
|
209
|
+
p.add_argument("--force", action="store_true", help="overwrite --out if it exists")
|
|
210
|
+
|
|
211
|
+
p = add(
|
|
212
|
+
"verify",
|
|
213
|
+
"Check a backup downloads, decrypts and is a real dump. No database needed.",
|
|
214
|
+
("verify", "the latest backup"),
|
|
215
|
+
("verify 2026-11-18T020000Z", "a specific one"),
|
|
216
|
+
("verify --file /out/2026-11-18T020000Z.dump.age", "a file you downloaded"),
|
|
217
|
+
)
|
|
218
|
+
p.add_argument(
|
|
219
|
+
"stamp",
|
|
220
|
+
nargs="?",
|
|
221
|
+
default=None,
|
|
222
|
+
metavar="STAMP|latest",
|
|
223
|
+
help="latest (the default), a stamp like 2026-11-18T020000Z, or <tier>/<stamp>",
|
|
224
|
+
)
|
|
225
|
+
p.add_argument("--file", metavar="PATH", help="verify a .dump.age on disk instead (no S3)")
|
|
226
|
+
|
|
227
|
+
p = add(
|
|
228
|
+
"schedule",
|
|
229
|
+
f"Stay running and back up every day at BACKUP_AT ({d['BACKUP_AT']} UTC). "
|
|
230
|
+
"The container's default command.",
|
|
231
|
+
("schedule", ""),
|
|
232
|
+
("schedule --at 02:00,14:00 --run-now", "twice a day, and once right now"),
|
|
233
|
+
)
|
|
234
|
+
p.add_argument(
|
|
235
|
+
"--at",
|
|
236
|
+
metavar="HH:MM[,HH:MM]",
|
|
237
|
+
help=f"UTC times (default: $BACKUP_AT or {d['BACKUP_AT']})",
|
|
238
|
+
)
|
|
239
|
+
p.add_argument("--run-now", action="store_true", help="also take a backup straight away")
|
|
240
|
+
return parser
|
|
241
|
+
|
|
242
|
+
|
|
243
|
+
def _dispatch(args: argparse.Namespace) -> int:
|
|
244
|
+
cmd = args.command
|
|
245
|
+
if cmd == "keygen":
|
|
246
|
+
return commands.keygen()
|
|
247
|
+
if cmd == "doctor":
|
|
248
|
+
return commands.doctor()
|
|
249
|
+
|
|
250
|
+
file_mode = cmd in ("decrypt", "verify") and bool(args.file)
|
|
251
|
+
if file_mode and args.stamp:
|
|
252
|
+
raise PgBackupError(
|
|
253
|
+
"give either a STAMP or --file, not both",
|
|
254
|
+
hint=f"`{cmd} STAMP` reads from the bucket; `{cmd} --file PATH` reads a local file",
|
|
255
|
+
)
|
|
256
|
+
settings = Settings.from_env(require_bucket=not file_mode)
|
|
257
|
+
|
|
258
|
+
if cmd == "detect":
|
|
259
|
+
return commands.detect(settings, suggest_only=args.env_lines)
|
|
260
|
+
if cmd == "backup":
|
|
261
|
+
commands.backup(settings, prune=False if args.no_prune else None)
|
|
262
|
+
return 0
|
|
263
|
+
if cmd == "list":
|
|
264
|
+
return commands.list_backups(settings)
|
|
265
|
+
if cmd == "prune":
|
|
266
|
+
return commands.prune_backups(settings, dry_run=args.dry_run)
|
|
267
|
+
if cmd == "restore":
|
|
268
|
+
target = settings.restore_target(args.target)
|
|
269
|
+
return commands.restore(settings, args.stamp, target, to_production=args.to_production)
|
|
270
|
+
if cmd == "drill":
|
|
271
|
+
if args.preflight:
|
|
272
|
+
return commands.drill_preflight(settings, args.stamp)
|
|
273
|
+
return commands.drill(settings, args.stamp)
|
|
274
|
+
if cmd == "decrypt":
|
|
275
|
+
return commands.decrypt(
|
|
276
|
+
settings, args.stamp or "latest", file=args.file, out=args.out, force=args.force
|
|
277
|
+
)
|
|
278
|
+
if cmd == "verify":
|
|
279
|
+
return commands.verify(settings, args.stamp or "latest", file=args.file)
|
|
280
|
+
if cmd == "schedule":
|
|
281
|
+
return commands.schedule(settings, args.at, run_now=args.run_now)
|
|
282
|
+
raise AssertionError(cmd)
|
|
283
|
+
|
|
284
|
+
|
|
285
|
+
def _one_line(exc: BaseException) -> str:
|
|
286
|
+
return " ".join(str(exc).split()) or type(exc).__name__
|
|
287
|
+
|
|
288
|
+
|
|
289
|
+
DOCTOR_HINT = "Run `pgb doctor`: it checks the settings, the database, the bucket and the keys"
|
|
290
|
+
|
|
291
|
+
|
|
292
|
+
def _hint(exc: BaseException) -> str | None:
|
|
293
|
+
"""A short fix for the error, if we know one."""
|
|
294
|
+
if isinstance(exc, PgBackupError):
|
|
295
|
+
if exc.hint is None and isinstance(exc, CommandError):
|
|
296
|
+
return pg.connection_hint(str(exc), os.environ.get("DATABASE_URL")) or DOCTOR_HINT
|
|
297
|
+
return exc.hint or DOCTOR_HINT
|
|
298
|
+
if isinstance(exc, NoCredentialsError):
|
|
299
|
+
return "Set AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY in your .env"
|
|
300
|
+
if isinstance(exc, EndpointConnectionError):
|
|
301
|
+
return "Check S3_ENDPOINT (for R2: https://<account-id>.r2.cloudflarestorage.com)"
|
|
302
|
+
if isinstance(exc, ClientError):
|
|
303
|
+
code = str(exc.response.get("Error", {}).get("Code", ""))
|
|
304
|
+
if code == "NoSuchBucket":
|
|
305
|
+
return "Check S3_BUCKET, and that S3_ENDPOINT is the right account"
|
|
306
|
+
if code in ("InvalidAccessKeyId", "SignatureDoesNotMatch", "AccessDenied", "403"):
|
|
307
|
+
return (
|
|
308
|
+
"Check AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY, and that the token has "
|
|
309
|
+
"Object Read & Write on this bucket"
|
|
310
|
+
)
|
|
311
|
+
# Every error ends with something to do next.
|
|
312
|
+
return DOCTOR_HINT
|
|
313
|
+
|
|
314
|
+
|
|
315
|
+
def _on_sigterm(signum, frame) -> None:
|
|
316
|
+
raise KeyboardInterrupt
|
|
317
|
+
|
|
318
|
+
|
|
319
|
+
def main(argv: Sequence[str] | None = None) -> int:
|
|
320
|
+
args = build_parser().parse_args(argv)
|
|
321
|
+
ui.configure(
|
|
322
|
+
plain=getattr(args, "plain", False),
|
|
323
|
+
quiet=getattr(args, "quiet", False),
|
|
324
|
+
command=args.command,
|
|
325
|
+
)
|
|
326
|
+
# As PID 1 in a container, SIGTERM is ignored unless we handle it.
|
|
327
|
+
if os.getpid() == 1:
|
|
328
|
+
signal.signal(signal.SIGTERM, _on_sigterm)
|
|
329
|
+
|
|
330
|
+
def report_failure(message: str) -> None:
|
|
331
|
+
if args.command in PINGS_ON_FAILURE:
|
|
332
|
+
heartbeat.ping(
|
|
333
|
+
os.environ.get("HEARTBEAT_FAIL_URL"),
|
|
334
|
+
failure=f"pgbackup-r2 {args.command} failed: {message}",
|
|
335
|
+
)
|
|
336
|
+
|
|
337
|
+
try:
|
|
338
|
+
return _dispatch(args)
|
|
339
|
+
except (PgBackupError, BotoCoreError, ClientError) as exc:
|
|
340
|
+
message = _one_line(exc)
|
|
341
|
+
ui.error(message, _hint(exc))
|
|
342
|
+
report_failure(message)
|
|
343
|
+
return 1
|
|
344
|
+
except KeyboardInterrupt:
|
|
345
|
+
ui.info("stopped")
|
|
346
|
+
return 0 if args.command == "schedule" else 130
|
|
347
|
+
except Exception as exc:
|
|
348
|
+
ui.exception("unexpected error (this is a bug, please report it)")
|
|
349
|
+
report_failure(_one_line(exc))
|
|
350
|
+
return 1
|
|
351
|
+
|
|
352
|
+
|
|
353
|
+
if __name__ == "__main__":
|
|
354
|
+
sys.exit(main())
|