feat(backup): write database dumps gzip-compressed

Dumps stream through gzip into <db>.backup.sql.gz; no uncompressed copy touches the disk. Restore reads gzip and plain dumps by their magic bytes, verifies a gzip dump to its end before anything is dropped, and still finds the uncompressed names of older generations. The manifest names the compression.

🎯 Fix: 92 %
💥 Break: 20 %
💸 Cost: –
⏱️ Time: –
🛡️ Security: ~100 %
🏆 Score: 74
🚦 Gate: ⛔ break 20 % > 5

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Kevin Veen-BirkenbachandClaude Opus 5.5 committed 2026-11-05 18:37:04 +00:00
1 parent 328520169b
commit b30344d494
34 files changed
+833 -110

No files matched your search

+4 -4
View File
@@ -9,7 +9,7 @@ from baudolo.databases import CLUSTER_ROW, validate_database
from baudolo.generation import CLUSTER_SUFFIX, DUMP_SUFFIX, SQL_DIR
from .docker import docker_exec_argv
from .shell import BackupError, execute_to_file
from .shell import BackupError, execute_to_gzip
if TYPE_CHECKING:
import pandas as pd
@@ -53,7 +53,7 @@ def fallback_pg_dumpall(
"""
Perform a full Postgres cluster dump using pg_dumpall.
"""
execute_to_file(
execute_to_gzip(
docker_exec_argv(
container,
["pg_dumpall", "-U", username, "-h", "localhost"],
@@ -122,7 +122,7 @@ def backup_database(
if db_type == "mariadb":
# Force TCP so auth matches '<user>'@'%' instead of socket -> 'localhost'.
execute_to_file(
execute_to_gzip(
docker_exec_argv(
container,
[
@@ -144,7 +144,7 @@ def backup_database(
if db_type == "postgres":
try:
execute_to_file(
execute_to_gzip(
docker_exec_argv(
container,
[
+65 -9
View File
@@ -7,14 +7,22 @@ string handed to ``shell=True`` allowed.
from __future__ import annotations
import gzip
import os
import subprocess
import tempfile
import zlib
from functools import partial
from pathlib import Path
from typing import TYPE_CHECKING
if TYPE_CHECKING:
from collections.abc import Mapping, Sequence
GZIP_LEVEL = 6
READ_BYTES = 1 << 20
SYNC_BYTES = 1 << 16
class BackupError(Exception):
"""Generic exception for backup errors."""
@@ -53,23 +61,71 @@ def execute_shell_command(
return [line.decode("utf-8") for line in out.splitlines()]
def execute_to_file(
def is_sync_point(piece: bytes) -> bool:
"""
Args:
piece: a line of the dump, or a READ_BYTES slice of a longer one.
Returns:
True when a full flush follows *piece*, decided by its bytes alone, on
average once per SYNC_BYTES of input.
"""
return zlib.crc32(piece) % max(1, SYNC_BYTES // len(piece)) == 0
def _abort(process: subprocess.Popen, tmp: Path) -> None:
process.kill()
process.wait()
tmp.unlink(missing_ok=True)
def execute_to_gzip(
command: Sequence[str], out_file: str, *, env: Mapping[str, str] | None = None
) -> None:
"""Run *command*, writing its stdout to *out_file* only once it succeeded.
"""
Args:
command: argv, the program first; its stdout is the dump.
out_file: the final gzip path. The stream is written to
``<out_file>.tmp`` and renamed only after the command exited 0.
env: variables added to the child's environment.
The output goes to a sibling temporary file first, so a partial or empty
stream from a failing dump never takes the place of a valid backup.
Raises:
BackupError: the command failed, or the file could not be written.
"""
command = list(command)
print(" ".join(command), flush=True)
tmp = Path(f"{out_file}.tmp")
with tmp.open("wb") as handle:
with tempfile.TemporaryFile() as err_sink:
process = subprocess.Popen(
command, stdout=handle, stderr=subprocess.PIPE, env=_child_env(env)
command, stdout=subprocess.PIPE, stderr=err_sink, env=_child_env(env)
)
_, err = process.communicate()
if process.returncode != 0:
try:
with (
tmp.open("wb") as raw,
gzip.GzipFile(
filename="",
mode="wb",
fileobj=raw,
compresslevel=GZIP_LEVEL,
mtime=0,
) as packed,
):
for piece in iter(partial(process.stdout.readline, READ_BYTES), b""):
packed.write(piece)
if is_sync_point(piece):
packed.flush(zlib.Z_FULL_FLUSH)
except OSError as error:
_abort(process, tmp)
raise BackupError(f"Error writing {out_file}: {error}") from error
except BaseException:
_abort(process, tmp)
raise
finally:
process.stdout.close()
returncode = process.wait()
err_sink.seek(0)
err = err_sink.read()
if returncode != 0:
tmp.unlink()
_fail(command, process.returncode, b"", err)
_fail(command, returncode, b"", err)
tmp.replace(out_file)
+7 -2
View File
@@ -18,8 +18,12 @@ from __future__ import annotations
FILES_DIR = "files"
SQL_DIR = "sql"
DUMP_SUFFIX = ".backup.sql"
CLUSTER_SUFFIX = ".cluster.backup.sql"
LEGACY_DUMP_SUFFIX = ".backup.sql"
LEGACY_CLUSTER_SUFFIX = ".cluster.backup.sql"
COMPRESSED_SUFFIX = ".gz"
DUMP_COMPRESSION = "gzip"
DUMP_SUFFIX = LEGACY_DUMP_SUFFIX + COMPRESSED_SUFFIX
CLUSTER_SUFFIX = LEGACY_CLUSTER_SUFFIX + COMPRESSED_SUFFIX
MANIFEST_FILE = "manifest.json"
MANIFEST_SCHEMA = 1
@@ -42,6 +46,7 @@ def manifest_document(volumes: dict[str, object]) -> dict[str, object]:
"sql_dir": SQL_DIR,
"dump_suffix": DUMP_SUFFIX,
"cluster_suffix": CLUSTER_SUFFIX,
"dump_compression": DUMP_COMPRESSION,
},
"volumes": {
name: {
+29 -22
View File
@@ -6,6 +6,7 @@ import sys
from .db.cluster import restore_cluster_sql
from .db.mariadb import restore_mariadb_sql
from .db.postgres import restore_postgres_sql
from .dumpfile import locate
from .files import restore_volume_files
from .paths import BackupPaths
@@ -106,7 +107,7 @@ def main(argv: list[str] | None = None) -> int:
p_cluster.add_argument(
"--instance",
required=True,
help="Instance the dump was taken from; names <instance>.cluster.backup.sql",
help="Instance the dump was taken from; names <instance>.cluster.backup.sql.gz",
)
p_cluster.add_argument(
"--db-user",
@@ -149,13 +150,15 @@ def main(argv: list[str] | None = None) -> int:
db_name=args.db_name,
user=user,
password=password,
sql_path=BackupPaths(
args.volume_name,
args.backup_hash,
args.version,
repo_name=args.repo_name,
backups_dir=args.backups_dir,
).sql_file(args.db_name),
sql_path=locate(
BackupPaths(
args.volume_name,
args.backup_hash,
args.version,
repo_name=args.repo_name,
backups_dir=args.backups_dir,
).sql_file(args.db_name)
),
empty=args.empty,
check_version=not args.no_version_check,
)
@@ -166,13 +169,15 @@ def main(argv: list[str] | None = None) -> int:
container=args.container,
user=args.db_user,
password=password,
sql_path=BackupPaths(
args.volume_name,
args.backup_hash,
args.version,
repo_name=args.repo_name,
backups_dir=args.backups_dir,
).cluster_file(args.instance),
sql_path=locate(
BackupPaths(
args.volume_name,
args.backup_hash,
args.version,
repo_name=args.repo_name,
backups_dir=args.backups_dir,
).cluster_file(args.instance)
),
empty=args.empty,
check_version=not args.no_version_check,
)
@@ -185,13 +190,15 @@ def main(argv: list[str] | None = None) -> int:
db_name=args.db_name,
user=user,
password=password,
sql_path=BackupPaths(
args.volume_name,
args.backup_hash,
args.version,
repo_name=args.repo_name,
backups_dir=args.backups_dir,
).sql_file(args.db_name),
sql_path=locate(
BackupPaths(
args.volume_name,
args.backup_hash,
args.version,
repo_name=args.repo_name,
backups_dir=args.backups_dir,
).sql_file(args.db_name)
),
empty=args.empty,
check_version=not args.no_version_check,
)
+5 -3
View File
@@ -24,6 +24,7 @@ import tempfile
from pathlib import Path
from typing import TYPE_CHECKING
from baudolo.restore.dumpfile import open_dump
from baudolo.restore.run import docker_exec
from .version import guard
@@ -96,7 +97,7 @@ def dump_inventory(sql_path: str) -> tuple[list[str], list[str]]:
"""
databases: list[str] = []
roles: list[str] = []
with Path(sql_path).open("rb") as handle:
with open_dump(sql_path) as handle:
for raw in handle:
line = raw.decode("utf-8", "replace")
for pattern, sink, read in (
@@ -212,7 +213,8 @@ def restore_cluster_sql(
user: a superuser of that instance; the dump creates roles and
databases, which an application role may not do.
password: its password, handed to psql through the container's env.
sql_path: the ``<instance>.cluster.backup.sql`` of a generation.
sql_path: the ``<instance>.cluster.backup.sql.gz`` of a generation, or
the uncompressed ``<instance>.cluster.backup.sql`` of an older one.
empty: drop the cluster's databases and roles first. Without it the
replay stops at the first object that already exists, which is the
honest outcome: recreating a cluster over a populated one is a
@@ -243,7 +245,7 @@ def restore_cluster_sql(
docker_env=docker_env,
)
with Path(sql_path).open("rb") as src, tempfile.TemporaryFile() as filtered:
with open_dump(sql_path) as src, tempfile.TemporaryFile() as filtered:
for line in filter_own_role_creation(src, user):
filtered.write(line)
filtered.seek(0)
+9 -4
View File
@@ -3,7 +3,8 @@ from __future__ import annotations
import sys
from pathlib import Path
from baudolo.restore.run import docker_exec, docker_exec_sh
from baudolo.restore.dumpfile import open_dump, verify
from baudolo.restore.run import docker_exec, docker_exec_sh, docker_exec_stream
from .version import guard
@@ -47,6 +48,7 @@ def restore_mariadb_sql(
if not Path(sql_path).is_file():
raise FileNotFoundError(sql_path)
verify(sql_path)
docker_env = {"MYSQL_PWD": password}
if check_version:
@@ -98,9 +100,12 @@ def restore_mariadb_sql(
docker_env=docker_env,
)
with Path(sql_path).open("rb") as f:
docker_exec(
container, [client, "-u", user, db_name], stdin=f, docker_env=docker_env
with open_dump(sql_path) as source:
docker_exec_stream(
container,
[client, "-u", user, db_name],
source=source,
docker_env=docker_env,
)
print(f"MariaDB/MySQL restore complete for db '{db_name}'.")
+11 -11
View File
@@ -4,6 +4,7 @@ import tempfile
from pathlib import Path
from typing import TYPE_CHECKING
from baudolo.restore.dumpfile import open_dump
from baudolo.restore.run import docker_exec
from .version import guard
@@ -67,23 +68,22 @@ def restore_postgres_sql(
docker_env = {"PGPASSWORD": password}
if empty:
with _EMPTY_PRECLEAN_SQL.open(encoding="utf-8") as preclean:
drop_sql = preclean.read()
docker_exec(
container,
["psql", "-v", "ON_ERROR_STOP=1", "-U", user, "-d", db_name],
stdin=drop_sql.encode(),
docker_env=docker_env,
)
# Filter into a spooled temp file instead of building the whole dump in
# memory: production dumps reach many GB and the previous read/splitlines/
# join needed roughly three times the dump size in RSS.
with Path(sql_path).open("rb") as src, tempfile.TemporaryFile() as filtered:
with open_dump(sql_path) as src, tempfile.TemporaryFile() as filtered:
for line in filter_superuser_only_lines(src):
filtered.write(line)
filtered.seek(0)
if empty:
with _EMPTY_PRECLEAN_SQL.open(encoding="utf-8") as preclean:
drop_sql = preclean.read()
docker_exec(
container,
["psql", "-v", "ON_ERROR_STOP=1", "-U", user, "-d", db_name],
stdin=drop_sql.encode(),
docker_env=docker_env,
)
docker_exec(
container,
[
+5 -2
View File
@@ -23,9 +23,10 @@ with the cluster banner and the roles section, and the first
from __future__ import annotations
import io
import re
from pathlib import Path
from baudolo.restore.dumpfile import open_dump
from baudolo.restore.run import docker_exec, stdout_of
SCAN_LINES = 2000
@@ -69,7 +70,9 @@ def dump_version(sql_path: str, engine: str) -> str:
VersionMismatchError: no version line within the first ``SCAN_LINES``.
"""
pattern = DUMP_VERSION[engine]
with Path(sql_path).open(encoding="utf-8", errors="replace") as handle:
with io.TextIOWrapper(
open_dump(sql_path), encoding="utf-8", errors="replace"
) as handle:
for _ in range(SCAN_LINES):
line = handle.readline()
if not line:
+81
View File
@@ -0,0 +1,81 @@
from __future__ import annotations
import gzip
from pathlib import Path
from typing import BinaryIO
from baudolo.generation import COMPRESSED_SUFFIX
GZIP_MAGIC = b"\x1f\x8b"
VERIFY_BYTES = 1 << 20
def is_gzip(path: str) -> bool:
"""
Args:
path: a dump file.
Returns:
True when its first bytes are the gzip magic, whatever its name says.
"""
with Path(path).open("rb") as handle:
return handle.read(len(GZIP_MAGIC)) == GZIP_MAGIC
def open_dump(path: str) -> BinaryIO:
"""
Args:
path: a dump, gzip-compressed or plain.
Returns:
A binary reader yielding the SQL text either way.
"""
if is_gzip(path):
return gzip.open(path, "rb")
return Path(path).open("rb")
def verify(path: str) -> None:
"""
Args:
path: a dump; a gzip one is decompressed to its end, a plain one is
left alone.
Raises:
EOFError: the gzip stream is truncated.
gzip.BadGzipFile: its header, CRC or length is wrong.
zlib.error: its deflate data is corrupt.
"""
if not is_gzip(path):
return
with gzip.open(path, "rb") as handle:
while handle.read(VERIFY_BYTES):
pass
def locate(path: str) -> str:
"""
Args:
path: where this version writes the dump, ending in COMPRESSED_SUFFIX.
Returns:
*path*, or the uncompressed name earlier versions wrote, whichever
exists.
Raises:
FileNotFoundError: neither exists.
FileExistsError: both exist.
"""
legacy = path.removesuffix(COMPRESSED_SUFFIX)
found = [
candidate
for candidate in dict.fromkeys((path, legacy))
if Path(candidate).is_file()
]
if len(found) > 1:
raise FileExistsError(
f"both {path} and {legacy} exist; remove the one that must not be replayed"
)
if not found:
raise FileNotFoundError(f"neither {path} nor {legacy} exists")
return found[0]
+42
View File
@@ -1,8 +1,13 @@
from __future__ import annotations
import contextlib
import os
import shutil
import subprocess
import sys
from typing import BinaryIO
STREAM_BYTES = 1 << 20
def run(
@@ -96,6 +101,43 @@ def docker_exec(
)
def docker_exec_stream(
container: str,
argv: list[str],
*,
source: BinaryIO,
docker_env: dict[str, str] | None = None,
) -> None:
"""
Args:
container: the container to run in.
argv: the command, fed *source* on stdin.
source: a binary reader, copied in STREAM_BYTES chunks, so a reader
without a file descriptor of its own, such as a gzip one, works.
docker_env: as for :func:`docker_exec`.
Raises:
subprocess.CalledProcessError: the command exited non-zero.
"""
cmd = docker_exec_cmd(container, argv, docker_env)
process = subprocess.Popen(
cmd, stdin=subprocess.PIPE, env=child_env(None, docker_env)
)
try:
with contextlib.suppress(BrokenPipeError):
shutil.copyfileobj(source, process.stdin, STREAM_BYTES)
with contextlib.suppress(BrokenPipeError):
process.stdin.close()
except BaseException:
process.kill()
process.wait()
raise
returncode = process.wait()
if returncode != 0:
print(f"ERROR: command failed ({returncode}): {' '.join(cmd)}", file=sys.stderr)
raise subprocess.CalledProcessError(returncode, cmd)
def docker_exec_sh(
container: str,
script: str,