Compare commits
8
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
e2bdac0793 | ||
|
|
982862725e | ||
|
|
b3c22a1286 | ||
|
|
ab717debf1 | ||
|
|
2a36d01f95 | ||
|
|
bbebf12710 | ||
|
|
fa73136e64 | ||
|
|
4a350b5198 |
No files matched your search
+1
-1
@@ -1,5 +1,5 @@
|
||||
# syntax=docker/dockerfile:1
|
||||
FROM python:3.14-slim
|
||||
FROM python:3.15-slim
|
||||
|
||||
WORKDIR /app
|
||||
|
||||
|
||||
+1
-1
@@ -19,7 +19,7 @@ dependencies = [
|
||||
[project.optional-dependencies]
|
||||
# Pinned: a ruff minor bump changes which rules fire, and `make test` gates on
|
||||
# a clean run, so an unpinned lint would fail the suite on an unrelated day.
|
||||
lint = ["ruff==0.17.3"]
|
||||
lint = ["ruff==0.17.6"]
|
||||
|
||||
[project.scripts]
|
||||
baudolo = "baudolo.backup.__main__:main"
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import sys
|
||||
from contextlib import ExitStack
|
||||
from datetime import datetime
|
||||
from pathlib import Path
|
||||
@@ -18,6 +19,7 @@ from .dumps import VolumeOutcome, backup_dumps_for_volume, load_databases_df
|
||||
from .layout import (
|
||||
create_version_directory,
|
||||
create_volume_directory,
|
||||
discard_volume_directory,
|
||||
get_machine_id,
|
||||
stamp_directory,
|
||||
write_manifest,
|
||||
@@ -44,6 +46,7 @@ def main() -> int:
|
||||
print("💾 Start volume backups...", flush=True)
|
||||
|
||||
outcomes: dict[str, VolumeOutcome] = {}
|
||||
failed: list[str] = []
|
||||
|
||||
with ExitStack() as stack:
|
||||
resolve_source = None
|
||||
@@ -75,12 +78,23 @@ def main() -> int:
|
||||
|
||||
outcome = VolumeOutcome(database=False, dumped=False)
|
||||
if not args.only_files:
|
||||
outcome = backup_dumps_for_volume(
|
||||
containers=containers,
|
||||
vol_dir=vol_dir,
|
||||
databases_df=databases_df,
|
||||
database_containers=args.database_containers,
|
||||
)
|
||||
try:
|
||||
outcome = backup_dumps_for_volume(
|
||||
containers=containers,
|
||||
vol_dir=vol_dir,
|
||||
databases_df=databases_df,
|
||||
database_containers=args.database_containers,
|
||||
)
|
||||
except BackupError as error:
|
||||
discard_volume_directory(vol_dir)
|
||||
failed.append(volume_name)
|
||||
print(
|
||||
f"ERROR: backup of volume '{volume_name}' failed; it is "
|
||||
f"left out of this generation.\n{error}",
|
||||
file=sys.stderr,
|
||||
flush=True,
|
||||
)
|
||||
continue
|
||||
outcomes[volume_name] = outcome
|
||||
|
||||
if args.only_sql and outcome.database:
|
||||
@@ -151,4 +165,12 @@ def main() -> int:
|
||||
print("Handling Docker Compose services...", flush=True)
|
||||
handle_docker_compose_services(args.compose_dir, args.hard_restart_projects)
|
||||
|
||||
if failed:
|
||||
print(
|
||||
f"ERROR: {len(failed)} volume(s) failed and are missing from "
|
||||
f"{version_dir}: {', '.join(failed)}",
|
||||
file=sys.stderr,
|
||||
flush=True,
|
||||
)
|
||||
return 1
|
||||
return 0
|
||||
@@ -1,5 +1,6 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
from .shell import BackupError, execute_shell_command
|
||||
@@ -7,6 +8,10 @@ from .shell import BackupError, execute_shell_command
|
||||
if TYPE_CHECKING:
|
||||
from collections.abc import Sequence
|
||||
|
||||
EXEC_NOT_FOUND = 127
|
||||
EXEC_START_FAILED = 126
|
||||
MISSING_EXECUTABLE = re.compile(rb"executable file\b.*\bnot found")
|
||||
|
||||
|
||||
def docker_exec_argv(
|
||||
container: str,
|
||||
@@ -59,11 +64,31 @@ def has_tool(container: str, tool: str) -> bool:
|
||||
Executes the binary rather than asking a shell for it: a distroless image
|
||||
has no shell, and `sh -c 'command -v'` would answer "absent" for every
|
||||
tool it ships.
|
||||
|
||||
Returns:
|
||||
False only when the executable is missing from the image: exit code
|
||||
127, or 126 with the runtime's "executable file ... not found" on
|
||||
stderr. dockerd overwrites every failed exec start with 126
|
||||
(moby/moby#45795), so on daemons whose CLI does not map the missing
|
||||
executable to 127 the exit code alone cannot tell it from a
|
||||
transient failure.
|
||||
|
||||
Raises:
|
||||
BackupError: the probe failed for any reason but a missing executable,
|
||||
e.g. a containerd io-pipe timeout. Reading that as "absent" would
|
||||
cache the image as no database and copy its files live instead of
|
||||
dumping them.
|
||||
"""
|
||||
try:
|
||||
execute_shell_command(docker_exec_argv(container, [tool, "--version"]))
|
||||
except BackupError:
|
||||
return False
|
||||
except BackupError as error:
|
||||
if error.returncode == EXEC_NOT_FOUND:
|
||||
return False
|
||||
if error.returncode == EXEC_START_FAILED and MISSING_EXECUTABLE.search(
|
||||
error.stderr
|
||||
):
|
||||
return False
|
||||
raise
|
||||
return True
|
||||
|
||||
|
||||
|
||||
@@ -4,6 +4,7 @@ from __future__ import annotations
|
||||
|
||||
import json
|
||||
import pathlib
|
||||
import shutil
|
||||
|
||||
from dirval import create_stamp_file
|
||||
|
||||
@@ -31,7 +32,7 @@ def create_version_directory(versions_dir: str, backup_time: str) -> str:
|
||||
raise BackupError(
|
||||
f"generation {backup_time} already exists at {version_dir}; "
|
||||
"another run claimed this second - refusing to write into it, "
|
||||
"since rsync --delete would overwrite that generation"
|
||||
"since the mirroring copy would replace the files of that generation"
|
||||
) from None
|
||||
return version_dir
|
||||
|
||||
@@ -42,6 +43,17 @@ def create_volume_directory(version_dir: str, volume_name: str) -> str:
|
||||
return str(path)
|
||||
|
||||
|
||||
def discard_volume_directory(volume_dir: str) -> None:
|
||||
"""A volume whose backup failed must not sit inside the stamped generation,
|
||||
where the stamp would vouch for a partial dump, and where a later run's
|
||||
``--link-dest`` would pick it up as the last good copy.
|
||||
|
||||
Args:
|
||||
volume_dir: the directory ``create_volume_directory`` returned.
|
||||
"""
|
||||
shutil.rmtree(volume_dir)
|
||||
|
||||
|
||||
def write_manifest(version_dir: str, volumes: dict[str, dict[str, bool]]) -> str:
|
||||
"""Record the generation's layout and per-volume outcome.
|
||||
|
||||
|
||||
@@ -25,7 +25,22 @@ SYNC_BYTES = 1 << 16
|
||||
|
||||
|
||||
class BackupError(Exception):
|
||||
"""Generic exception for backup errors."""
|
||||
"""Generic exception for backup errors.
|
||||
|
||||
Args:
|
||||
message: what failed.
|
||||
returncode: the exit code of the command that failed, None when the
|
||||
error did not come from a command's exit.
|
||||
stderr: what the failed command wrote to stderr, empty when it wrote
|
||||
nothing or the error did not come from a command.
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
self, message: str, returncode: int | None = None, stderr: bytes = b""
|
||||
) -> None:
|
||||
super().__init__(message)
|
||||
self.returncode = returncode
|
||||
self.stderr = stderr
|
||||
|
||||
|
||||
def _child_env(env: Mapping[str, str] | None) -> dict[str, str] | None:
|
||||
@@ -36,7 +51,9 @@ def _fail(command: Sequence[str], returncode: int, out: bytes, err: bytes) -> No
|
||||
raise BackupError(
|
||||
f"Error in command: {' '.join(command)}\n"
|
||||
f"Output: {out}\nError: {err}\n"
|
||||
f"Exit code: {returncode}"
|
||||
f"Exit code: {returncode}",
|
||||
returncode,
|
||||
err,
|
||||
)
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,119 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import contextlib
|
||||
import io
|
||||
import json
|
||||
import tempfile
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
from unittest import mock
|
||||
|
||||
from baudolo.backup import app
|
||||
from baudolo.backup.dumps import VolumeOutcome
|
||||
from baudolo.backup.shell import BackupError
|
||||
from baudolo.backup.volume import Backing
|
||||
from baudolo.generation import MANIFEST_FILE
|
||||
|
||||
from . import REQUIRED_PAIRS
|
||||
|
||||
BROKEN = "broken"
|
||||
LATER = "later"
|
||||
PROBE_ERROR = "docker exec probe exited 1"
|
||||
|
||||
|
||||
def drive(backups_dir: str, dump_error: Exception) -> dict:
|
||||
"""Run main() over a failing volume followed by a healthy one.
|
||||
|
||||
Args:
|
||||
backups_dir: real directory the generation is written into.
|
||||
dump_error: what the dump step raises for the first volume, after
|
||||
leaving a partial file in its directory.
|
||||
|
||||
Returns:
|
||||
``rc`` main's return value, ``copied`` the volumes whose files were
|
||||
copied, ``stamped`` the generation's entries and manifest volumes at
|
||||
stamp time, ``stderr`` what main wrote there.
|
||||
"""
|
||||
argv = ["baudolo"]
|
||||
for flag, value in REQUIRED_PAIRS:
|
||||
argv += [flag, backups_dir if flag == "--backups-dir" else value]
|
||||
|
||||
copied: list[str] = []
|
||||
stamped: dict = {}
|
||||
|
||||
def dumps(*, containers, vol_dir, databases_df, database_containers):
|
||||
if Path(vol_dir).name == BROKEN:
|
||||
(Path(vol_dir) / "partial.sql.gz").write_bytes(b"half")
|
||||
raise dump_error
|
||||
return VolumeOutcome(database=False, dumped=False)
|
||||
|
||||
def copy(versions_dir, volume_name, volume_dir, *, authoritative, source):
|
||||
copied.append(volume_name)
|
||||
|
||||
def stamp(version_dir: str) -> None:
|
||||
stamped["entries"] = sorted(p.name for p in Path(version_dir).iterdir())
|
||||
manifest = json.loads((Path(version_dir) / MANIFEST_FILE).read_text())
|
||||
stamped["volumes"] = sorted(manifest["volumes"])
|
||||
|
||||
stderr = io.StringIO()
|
||||
with (
|
||||
mock.patch("sys.argv", argv),
|
||||
mock.patch.object(app, "get_machine_id", return_value="machine"),
|
||||
mock.patch.object(app, "load_databases_df", return_value=None),
|
||||
mock.patch.object(app, "docker_volume_names", return_value=[BROKEN, LATER]),
|
||||
mock.patch.object(app, "containers_using_volume", return_value=["c"]),
|
||||
mock.patch.object(app, "volume_is_fully_ignored", return_value=False),
|
||||
mock.patch.object(app, "backup_dumps_for_volume", side_effect=dumps),
|
||||
mock.patch.object(app, "inspect_backing", return_value=Backing("/data")),
|
||||
mock.patch.object(app, "requires_stop", return_value=False),
|
||||
mock.patch.object(app, "backup_volume", side_effect=copy),
|
||||
mock.patch.object(app, "stamp_directory", side_effect=stamp),
|
||||
mock.patch.object(app, "handle_docker_compose_services"),
|
||||
contextlib.redirect_stdout(io.StringIO()),
|
||||
contextlib.redirect_stderr(stderr),
|
||||
):
|
||||
rc = app.main()
|
||||
return {
|
||||
"rc": rc,
|
||||
"copied": copied,
|
||||
"stamped": stamped,
|
||||
"stderr": stderr.getvalue(),
|
||||
}
|
||||
|
||||
|
||||
class TestVolumeFailure(unittest.TestCase):
|
||||
def setUp(self) -> None:
|
||||
tmp = tempfile.TemporaryDirectory()
|
||||
self.addCleanup(tmp.cleanup)
|
||||
self.backups_dir = tmp.name
|
||||
|
||||
def run_with_probe_failure(self) -> dict:
|
||||
return drive(self.backups_dir, BackupError(PROBE_ERROR, returncode=1))
|
||||
|
||||
def test_the_run_exits_non_zero(self) -> None:
|
||||
self.assertNotEqual(self.run_with_probe_failure()["rc"], 0)
|
||||
|
||||
def test_a_later_volume_is_still_copied(self) -> None:
|
||||
self.assertEqual(self.run_with_probe_failure()["copied"], [LATER])
|
||||
|
||||
def test_the_stamp_covers_no_directory_of_the_failed_volume(self) -> None:
|
||||
entries = self.run_with_probe_failure()["stamped"]["entries"]
|
||||
self.assertNotIn(BROKEN, entries)
|
||||
self.assertIn(LATER, entries)
|
||||
|
||||
def test_the_manifest_lists_only_the_volume_that_succeeded(self) -> None:
|
||||
self.assertEqual(self.run_with_probe_failure()["stamped"]["volumes"], [LATER])
|
||||
|
||||
def test_the_failure_is_logged_with_volume_and_error(self) -> None:
|
||||
stderr = self.run_with_probe_failure()["stderr"]
|
||||
self.assertIn(BROKEN, stderr)
|
||||
self.assertIn(PROBE_ERROR, stderr)
|
||||
|
||||
def test_an_error_other_than_backup_error_still_aborts_the_run(self) -> None:
|
||||
with self.assertRaises(RuntimeError):
|
||||
drive(self.backups_dir, RuntimeError("bug"))
|
||||
self.assertEqual(list(Path(self.backups_dir).rglob(MANIFEST_FILE)), [])
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -1,9 +1,20 @@
|
||||
import contextlib
|
||||
import io
|
||||
import sys
|
||||
import unittest
|
||||
from unittest.mock import patch
|
||||
|
||||
from baudolo.backup import docker as docker_mod
|
||||
from baudolo.backup.shell import BackupError
|
||||
|
||||
RUNC_NOT_FOUND = (
|
||||
b"OCI runtime exec failed: exec failed: unable to start container process: "
|
||||
b'exec: "pg_dumpall": executable file not found in $PATH'
|
||||
)
|
||||
CRUN_NOT_FOUND = (
|
||||
b"crun: executable file `pg_dumpall` not found in $PATH: No such file or directory"
|
||||
)
|
||||
|
||||
|
||||
class TestImageId(unittest.TestCase):
|
||||
def test_the_id_is_returned_without_surrounding_whitespace(self) -> None:
|
||||
@@ -18,11 +29,33 @@ class TestHasTool(unittest.TestCase):
|
||||
with patch.object(docker_mod, "execute_shell_command", return_value=[]):
|
||||
self.assertTrue(docker_mod.has_tool("c1", "pg_dumpall"))
|
||||
|
||||
def test_a_tool_that_exits_non_zero_is_absent(self) -> None:
|
||||
with patch.object(
|
||||
docker_mod, "execute_shell_command", side_effect=BackupError("127")
|
||||
def test_a_tool_missing_from_the_image_is_absent(self) -> None:
|
||||
not_found = BackupError(
|
||||
'exec: "mysqldump": executable file not found in $PATH', 127
|
||||
)
|
||||
with patch.object(docker_mod, "execute_shell_command", side_effect=not_found):
|
||||
self.assertFalse(docker_mod.has_tool("c1", "mysqldump"))
|
||||
|
||||
def test_a_missing_tool_reported_as_126_is_absent(self) -> None:
|
||||
for runtime_message in (RUNC_NOT_FOUND, CRUN_NOT_FOUND):
|
||||
with self.subTest(runtime_message=runtime_message):
|
||||
not_found = BackupError("exec failed", 126, runtime_message)
|
||||
with patch.object(
|
||||
docker_mod, "execute_shell_command", side_effect=not_found
|
||||
):
|
||||
self.assertFalse(docker_mod.has_tool("c1", "pg_dumpall"))
|
||||
|
||||
def test_a_failed_exec_is_not_read_as_a_missing_tool(self) -> None:
|
||||
"""containerd timed out on the io pipes of a mariadb that ships the tool."""
|
||||
pipe_timeout = (
|
||||
b"DeadlineExceeded: failed to start io pipe copy: unable to copy pipes"
|
||||
)
|
||||
transient = BackupError(pipe_timeout.decode(), 126, pipe_timeout)
|
||||
with (
|
||||
patch.object(docker_mod, "execute_shell_command", side_effect=transient),
|
||||
self.assertRaises(BackupError),
|
||||
):
|
||||
self.assertFalse(docker_mod.has_tool("c1", "mariadb-dump"))
|
||||
docker_mod.has_tool("c1", "mariadb-dump")
|
||||
|
||||
def test_the_probe_needs_no_shell_in_the_image(self) -> None:
|
||||
"""A distroless database ships no shell; `sh -c` would deny every tool."""
|
||||
@@ -40,5 +73,36 @@ class TestHasTool(unittest.TestCase):
|
||||
)
|
||||
|
||||
|
||||
class TestProbeExitCode(unittest.TestCase):
|
||||
def _probe_exiting(self, code: int, stderr: str = "") -> bool:
|
||||
argv = [
|
||||
sys.executable,
|
||||
"-c",
|
||||
f"import sys; sys.stderr.write({stderr!r}); sys.exit({code})",
|
||||
]
|
||||
with (
|
||||
patch.object(docker_mod, "docker_exec_argv", return_value=argv),
|
||||
contextlib.redirect_stdout(io.StringIO()),
|
||||
):
|
||||
return docker_mod.has_tool("c1", "mariadb-dump")
|
||||
|
||||
def test_exit_127_of_the_real_command_reads_as_absent(self) -> None:
|
||||
self.assertFalse(self._probe_exiting(127))
|
||||
|
||||
def test_any_other_exit_of_the_real_command_raises(self) -> None:
|
||||
with self.assertRaises(BackupError) as caught:
|
||||
self._probe_exiting(126)
|
||||
self.assertEqual(caught.exception.returncode, 126)
|
||||
|
||||
def test_exit_126_with_the_runtime_not_found_message_reads_as_absent(
|
||||
self,
|
||||
) -> None:
|
||||
self.assertFalse(
|
||||
self._probe_exiting(
|
||||
126, 'exec: "mariadb-dump": executable file not found in $PATH'
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -4,6 +4,7 @@ from unittest.mock import patch
|
||||
import pandas as pd
|
||||
|
||||
from baudolo.backup import dumps as dumps_mod
|
||||
from baudolo.backup.shell import BackupError
|
||||
|
||||
|
||||
def _df(rows):
|
||||
@@ -73,6 +74,29 @@ class TestProbeCache(unittest.TestCase):
|
||||
self.assertEqual(first, second)
|
||||
self.assertEqual(len(probe.calls), 1)
|
||||
|
||||
def test_a_failed_probe_caches_nothing_for_the_image(self):
|
||||
probe = _Probe(["mariadb-dump"])
|
||||
dumps_mod._ENGINE_BY_IMAGE.clear()
|
||||
|
||||
def _timed_out(container, tool):
|
||||
raise BackupError("DeadlineExceeded", 126)
|
||||
|
||||
with (
|
||||
patch.object(dumps_mod, "has_tool", _timed_out),
|
||||
patch.object(dumps_mod, "image_id", probe.image_id),
|
||||
self.assertRaises(BackupError),
|
||||
):
|
||||
dumps_mod.container_engine("c1")
|
||||
self.assertEqual(dumps_mod._ENGINE_BY_IMAGE, {})
|
||||
|
||||
with (
|
||||
patch.object(dumps_mod, "has_tool", probe.has_tool),
|
||||
patch.object(dumps_mod, "image_id", probe.image_id),
|
||||
):
|
||||
self.assertEqual(
|
||||
dumps_mod.container_engine("c1"), ("mariadb", "mariadb-dump")
|
||||
)
|
||||
|
||||
def test_a_second_image_is_probed_separately(self):
|
||||
probe = _Probe(["pg_dumpall"], image={"pg": "sha256:aaa", "app": "sha256:bbb"})
|
||||
dumps_mod._ENGINE_BY_IMAGE.clear()
|
||||
|
||||
Reference in new issue
Block a user