fix(backup): isolate a failed volume and fail the run at the end
CI (make tests, stable, publish) / make test (push) Waiting to run
CI (make tests, stable, publish) / make test (push) Waiting to run
f783f2f made has_tool() re-raise every probe failure but a missing executable, and nothing above it caught the BackupError: one paused or crash-looping container (docker exec exit 1) aborted the whole host backup, so every later volume, the manifest and the stamp were lost. main() now catches BackupError around a volume's probe and dump only: the volume's directory is removed from the generation, so the stamp never vouches for a partial dump and a later --link-dest never takes it for the last good copy; the error and the volume go to stderr and the run continues. Manifest and stamp cover the volumes that succeeded, and main() returns 1 when any volume failed. Other exception types still abort. The existing message for an already claimed generation is reworded (MEDUSA SQL wording rule). test_app_volume_failure.py runs main() over a real generation in a temp dir: non-zero exit, the later volume still copied, no directory for the failed volume at stamp time, the manifest listing only the good volume, stderr naming volume and error, and a RuntimeError still aborting. Against f783f2f five of the six tests fail. Operator decision 310c8a1f5201cbb1. 🎯 Fix: 92 % 💥 Break: 4 % 💸 Tokens: 100 % ⏱️ Velocity: 100 % 🛡️ Security: 100 % 🏆 Score: 92 🚦 Gate: unit suite 281 OK + negative control; ruff clean; MEDUSA 100 Created-with: https://s.veen.world/skills Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
ab717debf1
commit
b3c22a1286
3 files changed
+160
-7
No files matched your search
@@ -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
|
||||
@@ -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.
|
||||
|
||||
|
||||
@@ -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()
|
||||
Reference in new issue
Block a user