Compare commits
6
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
b3c22a1286 | ||
|
|
ab717debf1 | ||
|
|
2a36d01f95 | ||
|
|
bbebf12710 | ||
|
|
fa73136e64 | ||
|
|
4a350b5198 |
No files matched your search
+1
-1
@@ -1,5 +1,5 @@
|
|||||||
# syntax=docker/dockerfile:1
|
# syntax=docker/dockerfile:1
|
||||||
FROM python:3.14-slim
|
FROM python:3.15-slim
|
||||||
|
|
||||||
WORKDIR /app
|
WORKDIR /app
|
||||||
|
|
||||||
|
|||||||
+1
-1
@@ -19,7 +19,7 @@ dependencies = [
|
|||||||
[project.optional-dependencies]
|
[project.optional-dependencies]
|
||||||
# Pinned: a ruff minor bump changes which rules fire, and `make test` gates on
|
# 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.
|
# 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]
|
[project.scripts]
|
||||||
baudolo = "baudolo.backup.__main__:main"
|
baudolo = "baudolo.backup.__main__:main"
|
||||||
|
|||||||
@@ -2,6 +2,7 @@
|
|||||||
|
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import sys
|
||||||
from contextlib import ExitStack
|
from contextlib import ExitStack
|
||||||
from datetime import datetime
|
from datetime import datetime
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
@@ -18,6 +19,7 @@ from .dumps import VolumeOutcome, backup_dumps_for_volume, load_databases_df
|
|||||||
from .layout import (
|
from .layout import (
|
||||||
create_version_directory,
|
create_version_directory,
|
||||||
create_volume_directory,
|
create_volume_directory,
|
||||||
|
discard_volume_directory,
|
||||||
get_machine_id,
|
get_machine_id,
|
||||||
stamp_directory,
|
stamp_directory,
|
||||||
write_manifest,
|
write_manifest,
|
||||||
@@ -44,6 +46,7 @@ def main() -> int:
|
|||||||
print("💾 Start volume backups...", flush=True)
|
print("💾 Start volume backups...", flush=True)
|
||||||
|
|
||||||
outcomes: dict[str, VolumeOutcome] = {}
|
outcomes: dict[str, VolumeOutcome] = {}
|
||||||
|
failed: list[str] = []
|
||||||
|
|
||||||
with ExitStack() as stack:
|
with ExitStack() as stack:
|
||||||
resolve_source = None
|
resolve_source = None
|
||||||
@@ -75,12 +78,23 @@ def main() -> int:
|
|||||||
|
|
||||||
outcome = VolumeOutcome(database=False, dumped=False)
|
outcome = VolumeOutcome(database=False, dumped=False)
|
||||||
if not args.only_files:
|
if not args.only_files:
|
||||||
outcome = backup_dumps_for_volume(
|
try:
|
||||||
containers=containers,
|
outcome = backup_dumps_for_volume(
|
||||||
vol_dir=vol_dir,
|
containers=containers,
|
||||||
databases_df=databases_df,
|
vol_dir=vol_dir,
|
||||||
database_containers=args.database_containers,
|
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
|
outcomes[volume_name] = outcome
|
||||||
|
|
||||||
if args.only_sql and outcome.database:
|
if args.only_sql and outcome.database:
|
||||||
@@ -151,4 +165,12 @@ def main() -> int:
|
|||||||
print("Handling Docker Compose services...", flush=True)
|
print("Handling Docker Compose services...", flush=True)
|
||||||
handle_docker_compose_services(args.compose_dir, args.hard_restart_projects)
|
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
|
return 0
|
||||||
@@ -7,6 +7,8 @@ from .shell import BackupError, execute_shell_command
|
|||||||
if TYPE_CHECKING:
|
if TYPE_CHECKING:
|
||||||
from collections.abc import Sequence
|
from collections.abc import Sequence
|
||||||
|
|
||||||
|
EXEC_NOT_FOUND = 127
|
||||||
|
|
||||||
|
|
||||||
def docker_exec_argv(
|
def docker_exec_argv(
|
||||||
container: str,
|
container: str,
|
||||||
@@ -59,11 +61,23 @@ def has_tool(container: str, tool: str) -> bool:
|
|||||||
Executes the binary rather than asking a shell for it: a distroless image
|
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
|
has no shell, and `sh -c 'command -v'` would answer "absent" for every
|
||||||
tool it ships.
|
tool it ships.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
False only on exit code 127, which dockerd sets when the runtime
|
||||||
|
reports the executable missing from the image.
|
||||||
|
|
||||||
|
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:
|
try:
|
||||||
execute_shell_command(docker_exec_argv(container, [tool, "--version"]))
|
execute_shell_command(docker_exec_argv(container, [tool, "--version"]))
|
||||||
except BackupError:
|
except BackupError as error:
|
||||||
return False
|
if error.returncode == EXEC_NOT_FOUND:
|
||||||
|
return False
|
||||||
|
raise
|
||||||
return True
|
return True
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -4,6 +4,7 @@ from __future__ import annotations
|
|||||||
|
|
||||||
import json
|
import json
|
||||||
import pathlib
|
import pathlib
|
||||||
|
import shutil
|
||||||
|
|
||||||
from dirval import create_stamp_file
|
from dirval import create_stamp_file
|
||||||
|
|
||||||
@@ -31,7 +32,7 @@ def create_version_directory(versions_dir: str, backup_time: str) -> str:
|
|||||||
raise BackupError(
|
raise BackupError(
|
||||||
f"generation {backup_time} already exists at {version_dir}; "
|
f"generation {backup_time} already exists at {version_dir}; "
|
||||||
"another run claimed this second - refusing to write into it, "
|
"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
|
) from None
|
||||||
return version_dir
|
return version_dir
|
||||||
|
|
||||||
@@ -42,6 +43,17 @@ def create_volume_directory(version_dir: str, volume_name: str) -> str:
|
|||||||
return str(path)
|
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:
|
def write_manifest(version_dir: str, volumes: dict[str, dict[str, bool]]) -> str:
|
||||||
"""Record the generation's layout and per-volume outcome.
|
"""Record the generation's layout and per-volume outcome.
|
||||||
|
|
||||||
|
|||||||
@@ -25,7 +25,17 @@ SYNC_BYTES = 1 << 16
|
|||||||
|
|
||||||
|
|
||||||
class BackupError(Exception):
|
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.
|
||||||
|
"""
|
||||||
|
|
||||||
|
def __init__(self, message: str, returncode: int | None = None) -> None:
|
||||||
|
super().__init__(message)
|
||||||
|
self.returncode = returncode
|
||||||
|
|
||||||
|
|
||||||
def _child_env(env: Mapping[str, str] | None) -> dict[str, str] | None:
|
def _child_env(env: Mapping[str, str] | None) -> dict[str, str] | None:
|
||||||
@@ -36,7 +46,8 @@ def _fail(command: Sequence[str], returncode: int, out: bytes, err: bytes) -> No
|
|||||||
raise BackupError(
|
raise BackupError(
|
||||||
f"Error in command: {' '.join(command)}\n"
|
f"Error in command: {' '.join(command)}\n"
|
||||||
f"Output: {out}\nError: {err}\n"
|
f"Output: {out}\nError: {err}\n"
|
||||||
f"Exit code: {returncode}"
|
f"Exit code: {returncode}",
|
||||||
|
returncode,
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -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,3 +1,6 @@
|
|||||||
|
import contextlib
|
||||||
|
import io
|
||||||
|
import sys
|
||||||
import unittest
|
import unittest
|
||||||
from unittest.mock import patch
|
from unittest.mock import patch
|
||||||
|
|
||||||
@@ -18,11 +21,24 @@ class TestHasTool(unittest.TestCase):
|
|||||||
with patch.object(docker_mod, "execute_shell_command", return_value=[]):
|
with patch.object(docker_mod, "execute_shell_command", return_value=[]):
|
||||||
self.assertTrue(docker_mod.has_tool("c1", "pg_dumpall"))
|
self.assertTrue(docker_mod.has_tool("c1", "pg_dumpall"))
|
||||||
|
|
||||||
def test_a_tool_that_exits_non_zero_is_absent(self) -> None:
|
def test_a_tool_missing_from_the_image_is_absent(self) -> None:
|
||||||
with patch.object(
|
not_found = BackupError(
|
||||||
docker_mod, "execute_shell_command", side_effect=BackupError("127")
|
'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_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."""
|
||||||
|
transient = BackupError(
|
||||||
|
"DeadlineExceeded: failed to start io pipe copy: unable to copy pipes",
|
||||||
|
126,
|
||||||
|
)
|
||||||
|
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:
|
def test_the_probe_needs_no_shell_in_the_image(self) -> None:
|
||||||
"""A distroless database ships no shell; `sh -c` would deny every tool."""
|
"""A distroless database ships no shell; `sh -c` would deny every tool."""
|
||||||
@@ -40,5 +56,23 @@ class TestHasTool(unittest.TestCase):
|
|||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
|
class TestProbeExitCode(unittest.TestCase):
|
||||||
|
def _probe_exiting(self, code: int) -> bool:
|
||||||
|
argv = [sys.executable, "-c", f"import sys; 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)
|
||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
unittest.main()
|
unittest.main()
|
||||||
@@ -4,6 +4,7 @@ from unittest.mock import patch
|
|||||||
import pandas as pd
|
import pandas as pd
|
||||||
|
|
||||||
from baudolo.backup import dumps as dumps_mod
|
from baudolo.backup import dumps as dumps_mod
|
||||||
|
from baudolo.backup.shell import BackupError
|
||||||
|
|
||||||
|
|
||||||
def _df(rows):
|
def _df(rows):
|
||||||
@@ -73,6 +74,29 @@ class TestProbeCache(unittest.TestCase):
|
|||||||
self.assertEqual(first, second)
|
self.assertEqual(first, second)
|
||||||
self.assertEqual(len(probe.calls), 1)
|
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):
|
def test_a_second_image_is_probed_separately(self):
|
||||||
probe = _Probe(["pg_dumpall"], image={"pg": "sha256:aaa", "app": "sha256:bbb"})
|
probe = _Probe(["pg_dumpall"], image={"pg": "sha256:aaa", "app": "sha256:bbb"})
|
||||||
dumps_mod._ENGINE_BY_IMAGE.clear()
|
dumps_mod._ENGINE_BY_IMAGE.clear()
|
||||||
|
|||||||
Reference in new issue
Block a user