mirror of
https://github.com/kevinveenbirkenbach/computer-playbook.git
synced 2026-11-28 13:57:43 +00:00
Merge pull request #1418 from infinito-nexus/dependabot/pip/backup-docker-to-local-8.0.0
build(deps): Bump backup-docker-to-local from 7.1.1 to 8.0.0
This commit is contained in:
20 files changed
+647
-79
No files matched your search
@@ -59,11 +59,11 @@ def plan(root: Path) -> tuple[list[tuple[str, str]], list[str]]:
|
||||
except ValueError as error:
|
||||
unreadable.append(f"{repo}: {error}")
|
||||
continue
|
||||
files_glob, dump_glob = manifest.globs_of(names)
|
||||
files_glob, dump_globs = manifest.globs_of(names)
|
||||
files_dir = names["files_dir"]
|
||||
if rtype == "volume":
|
||||
steps += [(rtype, str(vol)) for vol in sorted(generation.glob(files_glob))]
|
||||
if any(generation.glob(dump_glob)):
|
||||
if any(hit for glob in dump_globs for hit in generation.glob(glob)):
|
||||
steps.append(("database", str(generation)))
|
||||
elif (generation / files_dir).is_dir():
|
||||
steps.append((rtype, str(generation / files_dir)))
|
||||
|
||||
+1
-1
@@ -13,7 +13,7 @@ license = { file = "LICENSE.md" }
|
||||
dependencies = [
|
||||
# Pinned: utils/recovery reads the generation layout from baudolo's own
|
||||
# BackupPaths, so the version here and in svc-bkp-volume-2-local must match.
|
||||
"backup-docker-to-local==7.1.1",
|
||||
"backup-docker-to-local==8.0.0",
|
||||
"Babel",
|
||||
"bcrypt",
|
||||
"cryptography",
|
||||
|
||||
@@ -10,6 +10,7 @@ File payloads are captured with rsync hard-link snapshots; databases register th
|
||||
This role installs the `baudolo` CLI, lays out the on-host backup tree, deploys the systemd service that drives the periodic run, and wires the cleanup-of-failed-backups dependency so partial snapshots are not retained.
|
||||
Database seeding for individual apps is contributed by the consumer roles via `tasks/03_seed-database-to-backup.yml`, which they include conditionally once `svc-bkp-volume-2-local` is in `group_names`.
|
||||
The first seed of a play reads `databases.csv` once through `tasks/05_read-seeded-databases.yml`; a consumer whose row already holds its credentials skips `baudolo-seed`, every other consumer still calls it at its own point in the play.
|
||||
`baudolo-seed` gets the password on stdin (`--password-stdin`), so it never shows in the host's process list.
|
||||
|
||||
## Schema
|
||||
|
||||
@@ -181,7 +182,12 @@ the order is: deploy the stack, stop the consumers, replay, start them again.
|
||||
The step names which of the two states is missing — a stopped container that
|
||||
only needs starting, or no container at all.
|
||||
|
||||
It replays every single-database dump with `baudolo-restore <engine> --empty`.
|
||||
It replays every single-database dump with `baudolo-restore <engine> --empty`,
|
||||
the password on stdin (`--db-password-stdin`) rather than on the command line.
|
||||
Since baudolo 8 a dump is gzip-compressed and named `<db>.backup.sql.gz`; a
|
||||
generation written before holds `<db>.backup.sql` and is found and replayed the
|
||||
same way. A dump present under both names stops the replay before anything is
|
||||
dropped, because nothing can tell which of the two is the one to restore.
|
||||
Two rules make it safe rather than convenient:
|
||||
|
||||
1. **The consumers must be down.** `--empty` pre-cleans the schema in one psql
|
||||
@@ -204,9 +210,12 @@ Two rules make it safe rather than convenient:
|
||||
generation copied to another host carries its header along, a csv row does
|
||||
not.
|
||||
|
||||
Cluster dumps (`database = '*'`) are reported and skipped: `baudolo-restore`
|
||||
has no subcommand that replays them. Database mode is local-only — the
|
||||
credentials live in the target host's own `databases.csv`.
|
||||
Cluster dumps (`database = '*'`) go through `baudolo-restore cluster` with the
|
||||
superuser of the instance's cluster row in `databases.csv`, before the
|
||||
single-database dumps. A cluster dump without that row, or with a consumer of
|
||||
any database it recreates still running, aborts the run before anything is
|
||||
replayed. Database mode is local-only — the credentials live in the target
|
||||
host's own `databases.csv`.
|
||||
|
||||
### A single volume
|
||||
|
||||
|
||||
@@ -95,7 +95,9 @@ matrix reports `SKIP` unless they are created first (`mknod /dev/loop0 b 7 0`,
|
||||
## `verify/backup.sh`
|
||||
|
||||
Requires the newest generation to hold real payload — a volume counts when it has
|
||||
a `files/` tree or a non-empty `sql` dump. In the async pass it additionally
|
||||
a `files/` tree or a non-empty `sql` dump. A dump is `*.backup.sql.gz` since
|
||||
baudolo 8 and `*.backup.sql` before; the gzip one counts by what it decompresses
|
||||
to, because an empty gzip file is still some twenty bytes. In the async pass it additionally
|
||||
requires `PREVIOUS_GENERATION` to be a distinct, older generation, which is what
|
||||
proves the differential `--link-dest` chain advanced.
|
||||
|
||||
@@ -153,9 +155,10 @@ database and its role, which the deploy creates and the container does not, so
|
||||
wiping it would leave `baudolo-restore --empty -d <db>` with nothing to connect
|
||||
to and the drill would fail at itself instead of at a defect.
|
||||
|
||||
**A generation holding a cluster dump fails the drill.** `baudolo-restore` has
|
||||
no subcommand that replays one, so that database cannot be proven restorable —
|
||||
the honest verdict is a red, not a silent skip.
|
||||
**A cluster dump is replayed, not skipped.** The recover chain sends it through
|
||||
`baudolo-restore cluster` with the superuser of its cluster row, so a
|
||||
generation holding one proves that instance restorable like any other dump; a
|
||||
missing cluster row is a red, not a silent skip.
|
||||
|
||||
**Not every subject is a compose project.** Discourse is built by its own
|
||||
`./launcher rebuild` ([handlers/stack_host.yml](../../../web-app-discourse/handlers/stack_host.yml))
|
||||
|
||||
@@ -142,7 +142,7 @@ while IFS= read -r sql_file; do
|
||||
if [[ " ${DB_PROJECTS[*]-} " != *" ${owner} "* ]]; then
|
||||
DB_PROJECTS+=("${owner}")
|
||||
fi
|
||||
done < <(find "${GEN_DIR}" -mindepth 3 -maxdepth 3 -type f -path '*/sql/*.backup.sql' | sort)
|
||||
done < <(find "${GEN_DIR}" -mindepth 3 -maxdepth 3 -type f \( -path '*/sql/*.backup.sql' -o -path '*/sql/*.backup.sql.gz' \) | sort)
|
||||
echo "OK: ${#DB_PROJECTS[@]} database project(s) hold the dumps: ${DB_PROJECTS[*]-none}"
|
||||
for project in "${DB_PROJECTS[@]}"; do
|
||||
echo "OK: only service '${DB_SERVICE[${project}]}' of project ${project} comes up for the replay"
|
||||
|
||||
@@ -22,11 +22,14 @@ Usage:
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import io
|
||||
import os
|
||||
import re
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
from baudolo.restore.dumpfile import open_dump
|
||||
|
||||
sys.path.insert(0, os.environ["BKP_TEST_REPO_ROOT"])
|
||||
|
||||
from utils.paths import FILE_DATABASE_SECRETS
|
||||
@@ -98,7 +101,7 @@ def volume_mountpoint(volume: str) -> Path:
|
||||
|
||||
def file_volumes(generation_dir: Path) -> list[str]:
|
||||
"""The volumes this generation stores as a file tree."""
|
||||
files_glob, _dump_glob = manifest.globs_of(manifest.layout_of(generation_dir))
|
||||
files_glob, _dump_globs = manifest.globs_of(manifest.layout_of(generation_dir))
|
||||
return sorted(path.parent.name for path in generation_dir.glob(files_glob))
|
||||
|
||||
|
||||
@@ -157,7 +160,9 @@ def each_database(generation_dir: Path):
|
||||
|
||||
def in_file(path: Path, token: str) -> bool:
|
||||
"""Whether a token appears anywhere in a file, without holding it in memory."""
|
||||
with path.open(encoding="utf-8", errors="replace") as handle:
|
||||
with io.TextIOWrapper(
|
||||
open_dump(str(path)), encoding="utf-8", errors="replace"
|
||||
) as handle:
|
||||
return any(token in line for line in handle)
|
||||
|
||||
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
#!/usr/bin/env bash
|
||||
# Verify the newest backup generation is stored, non-empty, and dumped where a
|
||||
# dump was owed: a volume counts as payload with a files/ tree or a non-empty
|
||||
# sql dump, and a volume the run recorded as a database must carry the dump
|
||||
# unless its provider has no consumer on this host.
|
||||
# dump was owed: a volume counts as payload with a files/ tree or a sql dump
|
||||
# that holds data once decompressed, and a volume the run recorded as a
|
||||
# database must carry the dump unless its provider has no consumer on this host.
|
||||
# The generation's own manifest is the authority; a generation written before
|
||||
# baudolo wrote one is judged by the engine's on-disk footprint instead.
|
||||
# Requires REPO_DIR/NEWEST_GENERATION/BKP_TEST_REPO_ROOT from test.sh.
|
||||
@@ -41,6 +41,20 @@ engine_of() {
|
||||
return 1
|
||||
}
|
||||
|
||||
has_dump() {
|
||||
local dump
|
||||
while IFS= read -r -d '' dump; do
|
||||
if [[ "${dump}" == *.gz ]]; then
|
||||
if (( $(gzip -cd -- "${dump}" 2>/dev/null | head -c 1 | wc -c) > 0 )); then
|
||||
return 0
|
||||
fi
|
||||
elif [[ -s "${dump}" ]]; then
|
||||
return 0
|
||||
fi
|
||||
done < <(find "$1" -mindepth 1 -type f \( -name '*.backup.sql' -o -name '*.backup.sql.gz' \) -print0 2>/dev/null)
|
||||
return 1
|
||||
}
|
||||
|
||||
IFS=',' read -r -a CONSUMERLESS <<< "${BKP_TEST_CONSUMERLESS_DB_VOLUMES}"
|
||||
|
||||
owe_dump() {
|
||||
@@ -67,7 +81,10 @@ EMPTY=0
|
||||
UNDUMPED=()
|
||||
for vol_dir in "${VOLUME_DIRS[@]}"; do
|
||||
has_files="$(find "${vol_dir}/files" -mindepth 1 -print -quit 2>/dev/null || true)"
|
||||
has_sql="$(find "${vol_dir}/sql" -mindepth 1 -type f -name '*.backup.sql' -size +0 -print -quit 2>/dev/null || true)"
|
||||
has_sql=""
|
||||
if has_dump "${vol_dir}/sql"; then
|
||||
has_sql=1
|
||||
fi
|
||||
if [[ -z "${has_files}" ]] && [[ -z "${has_sql}" ]]; then
|
||||
echo "WARN: ${vol_dir##*/} backed up empty"
|
||||
EMPTY=$((EMPTY + 1))
|
||||
|
||||
@@ -50,15 +50,16 @@
|
||||
|
||||
- name: "🧮 Compare the database definition with the seeded one"
|
||||
ansible.builtin.set_fact:
|
||||
svc_bkp_volume_2_local_seed_argv: "{{ svc_bkp_volume_2_local_seed_command }}"
|
||||
svc_bkp_volume_2_local_seed_argv: >-
|
||||
{{ ['baudolo-seed', FILE_DATABASE_SECRETS | string]
|
||||
+ svc_bkp_volume_2_local_seed_row[:3]
|
||||
+ ['--password-stdin'] }}
|
||||
svc_bkp_volume_2_local_seed_current: >-
|
||||
{{ svc_bkp_volume_2_local_seeded | baudolo_seed_current(*svc_bkp_volume_2_local_seed_command[2:]) }}
|
||||
{{ svc_bkp_volume_2_local_seeded | baudolo_seed_current(*svc_bkp_volume_2_local_seed_row) }}
|
||||
svc_bkp_volume_2_local_seeded: >-
|
||||
{{ svc_bkp_volume_2_local_seeded | baudolo_seed_apply(*svc_bkp_volume_2_local_seed_command[2:]) }}
|
||||
{{ svc_bkp_volume_2_local_seeded | baudolo_seed_apply(*svc_bkp_volume_2_local_seed_row) }}
|
||||
vars:
|
||||
svc_bkp_volume_2_local_seed_command:
|
||||
- baudolo-seed
|
||||
- "{{ FILE_DATABASE_SECRETS | string }}"
|
||||
svc_bkp_volume_2_local_seed_row:
|
||||
- "{{ database_instance | string }}"
|
||||
- "{{ '*' if (database_name | string | length) == 0 else (database_name | string) }}"
|
||||
- "{{ database_username | string }}"
|
||||
@@ -68,6 +69,7 @@
|
||||
- name: 🌱 Seed database definition via baudolo-seed (system binary)
|
||||
ansible.builtin.command:
|
||||
argv: "{{ svc_bkp_volume_2_local_seed_argv }}"
|
||||
stdin: "{{ database_password | string }}"
|
||||
when: not (svc_bkp_volume_2_local_seed_current | bool)
|
||||
no_log: "{{ MASK_CREDENTIALS_IN_LOGS | bool }}"
|
||||
# todo: add flock to baudolo-seed upstream, then async seeding becomes safe again.
|
||||
|
||||
@@ -79,11 +79,17 @@ class TestBaudoloPin(unittest.TestCase):
|
||||
self.assertEqual(layout.MANIFEST_SCHEMA, generation.MANIFEST_SCHEMA)
|
||||
|
||||
def test_the_layout_literals_match_baudolo(self) -> None:
|
||||
from baudolo import generation
|
||||
from baudolo.restore.paths import BackupPaths
|
||||
|
||||
installed = version(_PACKAGE)
|
||||
paths = BackupPaths("", "", "", repo_name="", backups_dir="")
|
||||
for name, ours, theirs in (
|
||||
(
|
||||
"COMPRESSED_SUFFIX",
|
||||
layout.COMPRESSED_SUFFIX,
|
||||
generation.COMPRESSED_SUFFIX,
|
||||
),
|
||||
("SQL_DIR", layout.SQL_DIR, PurePath(paths.sql_file("")).parent.name),
|
||||
("FILES_DIR", layout.FILES_DIR, PurePath(paths.files_dir()).name),
|
||||
("DUMP_SUFFIX", layout.DUMP_SUFFIX, PurePath(paths.sql_file("")).name),
|
||||
|
||||
@@ -40,6 +40,30 @@ class PlanTest(unittest.TestCase):
|
||||
self.assertTrue(any(s.endswith("pg_data/files") for _, s in steps))
|
||||
self.assertTrue(any(s.endswith("redis/files") for _, s in steps))
|
||||
|
||||
def test_a_dump_compressed_or_plain_adds_the_database_step(self):
|
||||
for name in ("zammad.backup.sql.gz", "zammad.backup.sql"):
|
||||
with self.subTest(dump=name), tempfile.TemporaryDirectory() as td:
|
||||
root = Path(td)
|
||||
self._tree(root)
|
||||
generation = root / "HASH/backup-docker-to-local/20260101000000"
|
||||
(generation / "pg_data/sql").mkdir()
|
||||
(generation / "pg_data/sql" / name).write_bytes(b"")
|
||||
steps, _unreadable = full.plan(root)
|
||||
self.assertEqual(
|
||||
[t for t, _ in steps],
|
||||
["nfs", "volume", "volume", "database", "secrets"],
|
||||
)
|
||||
|
||||
def test_negative_control_a_file_that_is_no_dump_adds_no_database_step(self):
|
||||
with tempfile.TemporaryDirectory() as td:
|
||||
root = Path(td)
|
||||
self._tree(root)
|
||||
generation = root / "HASH/backup-docker-to-local/20260101000000"
|
||||
(generation / "pg_data/sql").mkdir()
|
||||
(generation / "pg_data/sql/zammad.backup.sql.tmp").write_bytes(b"")
|
||||
steps, _unreadable = full.plan(root)
|
||||
self.assertNotIn("database", [t for t, _ in steps])
|
||||
|
||||
def test_plan_picks_newest_generation(self):
|
||||
with tempfile.TemporaryDirectory() as td:
|
||||
root = Path(td)
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
#!/usr/bin/env python3
|
||||
import gzip
|
||||
import importlib.util
|
||||
import os
|
||||
import tempfile
|
||||
@@ -65,13 +66,17 @@ class TestFileVolumes(TestCase):
|
||||
class TestCaptured(TestCase):
|
||||
"""The half of the proof that runs in both deploy modes."""
|
||||
|
||||
def generation(self, marker_token, dump_body):
|
||||
def generation(self, marker_token, dump_body, *, compressed=False):
|
||||
root = Path(tempfile.mkdtemp()) / "gen"
|
||||
(root / "openldap_data/files").mkdir(parents=True)
|
||||
(root / "postgres/sql").mkdir(parents=True)
|
||||
if marker_token is not None:
|
||||
(root / "openldap_data/files" / SCRIPT.MARKER_FILE).write_text(marker_token)
|
||||
(root / "postgres/sql/zammad.backup.sql").write_text(dump_body)
|
||||
if compressed:
|
||||
with gzip.open(root / "postgres/sql/zammad.backup.sql.gz", "wt") as out:
|
||||
out.write(dump_body)
|
||||
else:
|
||||
(root / "postgres/sql/zammad.backup.sql").write_text(dump_body)
|
||||
return root
|
||||
|
||||
def test_a_generation_carrying_both_passes(self):
|
||||
@@ -80,6 +85,20 @@ class TestCaptured(TestCase):
|
||||
)
|
||||
self.assertEqual(SCRIPT.captured(root, "dr-1-2"), 0)
|
||||
|
||||
def test_a_compressed_dump_carrying_the_row_passes(self):
|
||||
root = self.generation(
|
||||
"dr-1-2",
|
||||
"INSERT INTO infinito_dr_marker VALUES ('dr-1-2');\n",
|
||||
compressed=True,
|
||||
)
|
||||
self.assertEqual(SCRIPT.captured(root, "dr-1-2"), 0)
|
||||
|
||||
def test_negative_control_a_compressed_dump_without_the_row_fails(self):
|
||||
root = self.generation("dr-1-2", "-- empty dump\n", compressed=True)
|
||||
with self.assertRaises(SCRIPT.databases.RecoveryError) as raised:
|
||||
SCRIPT.captured(root, "dr-1-2")
|
||||
self.assertIn("zammad.backup.sql.gz", str(raised.exception))
|
||||
|
||||
def test_a_volume_whose_tree_missed_the_marker_fails(self):
|
||||
root = self.generation(
|
||||
None, "INSERT INTO infinito_dr_marker VALUES ('dr-1-2');\n"
|
||||
|
||||
@@ -9,6 +9,7 @@ seed its row, stays a failure.
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import gzip
|
||||
import json
|
||||
import os
|
||||
import subprocess
|
||||
@@ -53,17 +54,45 @@ def _verify(
|
||||
),
|
||||
encoding="utf-8",
|
||||
)
|
||||
env = {
|
||||
**os.environ,
|
||||
"REPO_DIR": repo,
|
||||
"NEWEST_GENERATION": GENERATION,
|
||||
"BKP_TEST_REPO_ROOT": str(PROJECT_ROOT),
|
||||
"BKP_TEST_PYTHON": sys.executable,
|
||||
"BKP_TEST_CONSUMERLESS_DB_VOLUMES": consumerless,
|
||||
}
|
||||
return subprocess.run(
|
||||
["bash", str(SCRIPT)], capture_output=True, text=True, env=env, check=False
|
||||
return _run(repo, consumerless)
|
||||
|
||||
|
||||
def _verify_dump(name: str, body: bytes) -> subprocess.CompletedProcess[str]:
|
||||
with tempfile.TemporaryDirectory() as repo:
|
||||
generation = Path(repo) / GENERATION
|
||||
sql = generation / "postgres_data" / SQL_DIR
|
||||
sql.mkdir(parents=True)
|
||||
(sql / name).write_bytes(body)
|
||||
(generation / MANIFEST_FILE).write_text(
|
||||
json.dumps(
|
||||
{
|
||||
"schema": MANIFEST_SCHEMA,
|
||||
"volumes": {
|
||||
"postgres_data": {
|
||||
"database": True,
|
||||
"dumped": True,
|
||||
"engine": "postgres",
|
||||
}
|
||||
},
|
||||
}
|
||||
),
|
||||
encoding="utf-8",
|
||||
)
|
||||
return _run(repo, "")
|
||||
|
||||
|
||||
def _run(repo: str, consumerless: str) -> subprocess.CompletedProcess[str]:
|
||||
env = {
|
||||
**os.environ,
|
||||
"REPO_DIR": repo,
|
||||
"NEWEST_GENERATION": GENERATION,
|
||||
"BKP_TEST_REPO_ROOT": str(PROJECT_ROOT),
|
||||
"BKP_TEST_PYTHON": sys.executable,
|
||||
"BKP_TEST_CONSUMERLESS_DB_VOLUMES": consumerless,
|
||||
}
|
||||
return subprocess.run(
|
||||
["bash", str(SCRIPT)], capture_output=True, text=True, env=env, check=False
|
||||
)
|
||||
|
||||
|
||||
class TestVerifyBackup(unittest.TestCase):
|
||||
@@ -93,5 +122,34 @@ class TestVerifyBackup(unittest.TestCase):
|
||||
)
|
||||
|
||||
|
||||
class TestDumpPayload(unittest.TestCase):
|
||||
def assert_payload(self, result: subprocess.CompletedProcess[str]) -> None:
|
||||
self.assertEqual(result.returncode, 0, result.stdout + result.stderr)
|
||||
self.assertIn("OK: backup payload present", result.stdout)
|
||||
|
||||
def assert_empty(self, result: subprocess.CompletedProcess[str]) -> None:
|
||||
self.assertEqual(result.returncode, 1, result.stdout + result.stderr)
|
||||
self.assertIn("every backed-up volume", result.stdout)
|
||||
|
||||
def test_a_compressed_dump_counts(self) -> None:
|
||||
self.assert_payload(
|
||||
_verify_dump("zammad.backup.sql.gz", gzip.compress(b"SELECT 1;\n"))
|
||||
)
|
||||
|
||||
def test_negative_control_a_compressed_empty_dump_is_empty(self) -> None:
|
||||
empty = gzip.compress(b"")
|
||||
self.assertGreater(len(empty), 0)
|
||||
self.assert_empty(_verify_dump("zammad.backup.sql.gz", empty))
|
||||
|
||||
def test_a_plain_dump_from_before_baudolo_8_counts(self) -> None:
|
||||
self.assert_payload(_verify_dump("zammad.backup.sql", b"SELECT 1;\n"))
|
||||
|
||||
def test_negative_control_a_plain_empty_dump_is_empty(self) -> None:
|
||||
self.assert_empty(_verify_dump("zammad.backup.sql", b""))
|
||||
|
||||
def test_negative_control_a_file_that_is_no_dump_does_not_count(self) -> None:
|
||||
self.assert_empty(_verify_dump("zammad.sql.tmp", b"SELECT 1;\n"))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
Whitespace-only changes.
+127
@@ -0,0 +1,127 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import io
|
||||
import sys
|
||||
import tempfile
|
||||
import unittest
|
||||
from contextlib import redirect_stderr, redirect_stdout
|
||||
from pathlib import Path
|
||||
from unittest.mock import patch
|
||||
|
||||
from baudolo.databases import read_rows
|
||||
from baudolo.seed import __main__ as seed_cli
|
||||
from jinja2 import Environment, StrictUndefined, select_autoescape
|
||||
from jinja2.nativetypes import NativeEnvironment
|
||||
|
||||
from plugins.filter.baudolo_seed import FilterModule, baudolo_seeded
|
||||
from utils import PROJECT_ROOT
|
||||
from utils.cache.yaml import load_yaml_any
|
||||
|
||||
TASKS = (
|
||||
PROJECT_ROOT / "roles/svc-bkp-volume-2-local/tasks/03_seed-database-to-backup.yml"
|
||||
)
|
||||
COMPARE = "🧮 Compare the database definition with the seeded one"
|
||||
SEED = "🌱 Seed database definition via baudolo-seed (system binary)"
|
||||
PASSWORDS = ("S3cr3t with space", "pa;ss\"q'uote", "ends in a newline\n")
|
||||
|
||||
|
||||
def _task(name: str) -> dict:
|
||||
for task in load_yaml_any(str(TASKS)) or []:
|
||||
if task.get("name") == name:
|
||||
return task
|
||||
raise AssertionError(f"{TASKS} has no task '{name}'")
|
||||
|
||||
|
||||
def _render(password: str, csv: Path) -> tuple[list[str], str, dict]:
|
||||
"""
|
||||
Args:
|
||||
password: the consumer's ``database_password``.
|
||||
csv: stands in for ``FILE_DATABASE_SECRETS``.
|
||||
|
||||
Returns:
|
||||
The command module's argv, the stdin it writes (with the newline
|
||||
``stdin_add_newline`` appends), and the facts the compare task sets.
|
||||
"""
|
||||
context = {
|
||||
"FILE_DATABASE_SECRETS": str(csv),
|
||||
"database_instance": "central-postgres",
|
||||
"database_name": "zammad",
|
||||
"database_username": "zammad",
|
||||
"database_password": password,
|
||||
"svc_bkp_volume_2_local_seeded": baudolo_seeded(""),
|
||||
}
|
||||
text = Environment(
|
||||
undefined=StrictUndefined,
|
||||
autoescape=select_autoescape(default_for_string=False),
|
||||
)
|
||||
native = NativeEnvironment(undefined=StrictUndefined)
|
||||
native.filters.update(FilterModule().filters())
|
||||
compare = _task(COMPARE)
|
||||
for key, values in compare["vars"].items():
|
||||
context[key] = [text.from_string(value).render(context) for value in values]
|
||||
facts = {
|
||||
key: native.from_string(value).render(context)
|
||||
for key, value in compare["ansible.builtin.set_fact"].items()
|
||||
}
|
||||
context.update(facts)
|
||||
command = _task(SEED)["ansible.builtin.command"]
|
||||
argv = native.from_string(command["argv"]).render(context)
|
||||
stdin = text.from_string(command["stdin"]).render(context)
|
||||
if command.get("stdin_add_newline", True):
|
||||
stdin += "\n"
|
||||
return argv, stdin, facts
|
||||
|
||||
|
||||
def _seed(argv: list[str], stdin: str) -> str:
|
||||
"""
|
||||
Args:
|
||||
argv: the baudolo-seed call.
|
||||
stdin: text the call reads from stdin.
|
||||
|
||||
Returns:
|
||||
The call's stderr.
|
||||
"""
|
||||
with (
|
||||
patch.object(sys, "argv", argv),
|
||||
patch.object(sys, "stdin", io.StringIO(stdin)),
|
||||
redirect_stdout(io.StringIO()),
|
||||
redirect_stderr(io.StringIO()) as stderr,
|
||||
):
|
||||
seed_cli.main()
|
||||
return stderr.getvalue()
|
||||
|
||||
|
||||
class TestSeedPasswordTransport(unittest.TestCase):
|
||||
def test_the_password_is_on_no_argv(self) -> None:
|
||||
for password in PASSWORDS:
|
||||
with self.subTest(password=password):
|
||||
argv, _stdin, _facts = _render(password, Path("/x/databases.csv"))
|
||||
self.assertEqual(argv[0], "baudolo-seed")
|
||||
self.assertEqual(argv[-1], "--password-stdin")
|
||||
self.assertFalse(any(password.strip() in part for part in argv))
|
||||
|
||||
def test_baudolo_seed_stores_the_password_from_stdin(self) -> None:
|
||||
for password in PASSWORDS:
|
||||
with self.subTest(password=password), tempfile.TemporaryDirectory() as tmp:
|
||||
csv = Path(tmp) / "databases.csv"
|
||||
argv, stdin, facts = _render(password, csv)
|
||||
self.assertNotIn("WARNING", _seed(argv, stdin))
|
||||
rows = read_rows(str(csv))
|
||||
self.assertEqual([row.password for row in rows], [password])
|
||||
self.assertFalse(facts["svc_bkp_volume_2_local_seed_current"])
|
||||
self.assertEqual(
|
||||
facts["svc_bkp_volume_2_local_seeded"]["rows"],
|
||||
[list(row) for row in rows],
|
||||
"the play's view of databases.csv must match what baudolo wrote",
|
||||
)
|
||||
|
||||
def test_negative_control_without_stdin_the_row_holds_no_password(self) -> None:
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
csv = Path(tmp) / "databases.csv"
|
||||
argv, _stdin, _facts = _render(PASSWORDS[0], csv)
|
||||
_seed(argv, "")
|
||||
self.assertEqual([row.password for row in read_rows(str(csv))], [""])
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -1,9 +1,14 @@
|
||||
#!/usr/bin/env python3
|
||||
import gzip
|
||||
import io
|
||||
import json
|
||||
import tempfile
|
||||
from contextlib import redirect_stderr
|
||||
from pathlib import Path
|
||||
from unittest import TestCase, main, mock
|
||||
|
||||
from baudolo.restore import __main__ as restore_cli
|
||||
from baudolo.restore.dumpfile import locate
|
||||
from baudolo.restore.paths import BackupPaths
|
||||
|
||||
from utils.recovery import databases
|
||||
@@ -89,6 +94,40 @@ class TestLayoutFollowsBaudolo(TestCase):
|
||||
[(c.volume, c.instance) for c in clusters], [("postgres", "all")]
|
||||
)
|
||||
|
||||
def test_backup_paths_names_the_compressed_dump(self):
|
||||
self.assertTrue(self.paths.sql_file("zammad").endswith(".backup.sql.gz"))
|
||||
self.assertTrue(
|
||||
self.paths.cluster_file("all").endswith(".cluster.backup.sql.gz")
|
||||
)
|
||||
|
||||
def assert_core_finds_what_baudolo_replays(self):
|
||||
dumps, clusters = databases.dumps_of(self.generation)
|
||||
self.assertEqual(len(dumps), 1)
|
||||
self.assertEqual(len(clusters), 1)
|
||||
for dump in dumps:
|
||||
self.assertEqual(locate(self.paths.sql_file(dump.database)), str(dump.path))
|
||||
for cluster in clusters:
|
||||
self.assertEqual(
|
||||
locate(self.paths.cluster_file(cluster.instance)), str(cluster.path)
|
||||
)
|
||||
|
||||
def test_a_compressed_dump_is_the_one_baudolo_restore_replays(self):
|
||||
self.assert_core_finds_what_baudolo_replays()
|
||||
|
||||
def test_a_dump_from_before_baudolo_8_is_the_one_baudolo_restore_replays(self):
|
||||
for written in (self.paths.sql_file("zammad"), self.paths.cluster_file("all")):
|
||||
Path(written).rename(written.removesuffix(".gz"))
|
||||
self.assert_core_finds_what_baudolo_replays()
|
||||
|
||||
def test_negative_control_a_dump_held_twice_is_refused_like_baudolo_does(self):
|
||||
legacy = self.paths.sql_file("zammad").removesuffix(".gz")
|
||||
Path(legacy).write_text("")
|
||||
with self.assertRaises(FileExistsError):
|
||||
locate(self.paths.sql_file("zammad"))
|
||||
with self.assertRaises(databases.RecoveryError) as raised:
|
||||
databases.dumps_of(self.generation)
|
||||
self.assertIn("zammad.backup.sql", str(raised.exception))
|
||||
|
||||
|
||||
class TestGenerationLayout(TestCase):
|
||||
def setUp(self):
|
||||
@@ -115,6 +154,27 @@ class TestGenerationLayout(TestCase):
|
||||
[(c.volume, c.instance) for c in clusters], [("postgres", "all")]
|
||||
)
|
||||
|
||||
def test_compressed_and_plain_dumps_of_one_generation_are_both_found(self):
|
||||
(self.generation / "mariadb/sql").mkdir(parents=True)
|
||||
(self.generation / "mariadb/sql/nextcloud.backup.sql.gz").write_bytes(b"")
|
||||
(self.generation / "mariadb/sql/central.cluster.backup.sql.gz").write_bytes(b"")
|
||||
dumps, clusters = databases.dumps_of(self.generation)
|
||||
self.assertEqual(
|
||||
[(d.volume, d.database) for d in dumps],
|
||||
[("mariadb", "nextcloud"), ("postgres", "zammad")],
|
||||
)
|
||||
self.assertEqual(
|
||||
[(c.volume, c.instance) for c in clusters],
|
||||
[("mariadb", "central"), ("postgres", "all")],
|
||||
)
|
||||
|
||||
def test_negative_control_a_file_that_is_no_dump_is_not_replayed(self):
|
||||
for stray in ("zammad.backup.sql.tmp", "zammad.sql.gz", "notes.gz"):
|
||||
(self.generation / "postgres/sql" / stray).write_bytes(b"")
|
||||
dumps, clusters = databases.dumps_of(self.generation)
|
||||
self.assertEqual([d.path.name for d in dumps], ["zammad.backup.sql"])
|
||||
self.assertEqual([c.path.name for c in clusters], ["all.cluster.backup.sql"])
|
||||
|
||||
def test_cluster_argv_matches_the_baudolo_contract(self):
|
||||
cluster = databases.Cluster("postgres", "central-postgres", Path("/x"))
|
||||
argv = databases.cluster_argv(
|
||||
@@ -122,7 +182,6 @@ class TestGenerationLayout(TestCase):
|
||||
databases.generation_of(self.generation),
|
||||
"postgres-1",
|
||||
"postgres",
|
||||
"s3cret",
|
||||
)
|
||||
self.assertEqual(
|
||||
argv[:5],
|
||||
@@ -143,7 +202,6 @@ class TestGenerationLayout(TestCase):
|
||||
"postgres",
|
||||
"postgres-1",
|
||||
"zammad",
|
||||
"s3cret",
|
||||
)
|
||||
self.assertEqual(
|
||||
argv[:5],
|
||||
@@ -159,6 +217,92 @@ class TestGenerationLayout(TestCase):
|
||||
self.assertEqual(argv[argv.index("--container") + 1], "postgres-1")
|
||||
self.assertEqual(argv[argv.index("--db-name") + 1], "zammad")
|
||||
|
||||
def test_neither_argv_takes_a_password(self):
|
||||
generation_parts = databases.generation_of(self.generation)
|
||||
for argv in (
|
||||
databases.restore_argv(
|
||||
databases.Dump("postgres", "zammad", Path("/x")),
|
||||
generation_parts,
|
||||
"postgres",
|
||||
"postgres-1",
|
||||
"zammad",
|
||||
),
|
||||
databases.cluster_argv(
|
||||
databases.Cluster("postgres", "all", Path("/x")),
|
||||
generation_parts,
|
||||
"postgres-1",
|
||||
"postgres",
|
||||
),
|
||||
):
|
||||
with self.subTest(subcommand=argv[1]):
|
||||
self.assertIn("--db-password-stdin", argv)
|
||||
self.assertNotIn("--db-password", argv)
|
||||
|
||||
|
||||
class TestPasswordTransport(TestCase):
|
||||
PASSWORD = "s3 cr'et\n"
|
||||
|
||||
def setUp(self):
|
||||
self.generation = generation(Path(tempfile.mkdtemp()))
|
||||
self.parts = databases.generation_of(self.generation)
|
||||
|
||||
def argvs(self):
|
||||
return {
|
||||
"postgres": databases.restore_argv(
|
||||
databases.Dump("postgres", "zammad", Path("/x")),
|
||||
self.parts,
|
||||
"postgres",
|
||||
"postgres-1",
|
||||
"zammad",
|
||||
),
|
||||
"cluster": databases.cluster_argv(
|
||||
databases.Cluster("postgres", "all", Path("/x")),
|
||||
self.parts,
|
||||
"postgres-1",
|
||||
"postgres",
|
||||
),
|
||||
}
|
||||
|
||||
def baudolo_receives(self, argv, stdin):
|
||||
seen = {}
|
||||
|
||||
def restore(**kwargs):
|
||||
seen.update(kwargs)
|
||||
|
||||
with (
|
||||
mock.patch.object(restore_cli, "restore_postgres_sql", restore),
|
||||
mock.patch.object(restore_cli, "restore_cluster_sql", restore),
|
||||
mock.patch.object(restore_cli, "locate", lambda path: path),
|
||||
mock.patch("sys.stdin", io.StringIO(stdin)),
|
||||
redirect_stderr(io.StringIO()) as stderr,
|
||||
):
|
||||
self.assertEqual(restore_cli.main(argv[1:]), 0)
|
||||
self.assertNotIn("WARNING", stderr.getvalue())
|
||||
return seen["password"]
|
||||
|
||||
def test_the_password_reaches_baudolo_through_stdin_only(self):
|
||||
for subcommand, argv in self.argvs().items():
|
||||
with self.subTest(subcommand=subcommand):
|
||||
self.assertFalse(any(self.PASSWORD.strip() in part for part in argv))
|
||||
sent = {}
|
||||
|
||||
def fake_run(argv, secret="", stdin=None, sent=sent):
|
||||
sent["stdin"] = stdin
|
||||
sent["secret"] = secret
|
||||
return ""
|
||||
|
||||
with mock.patch.object(recovery_docker, "_run", fake_run):
|
||||
databases._restore(argv, self.PASSWORD)
|
||||
self.assertEqual(sent["secret"], self.PASSWORD)
|
||||
self.assertEqual(
|
||||
self.baudolo_receives(argv, sent["stdin"]), self.PASSWORD
|
||||
)
|
||||
|
||||
def test_negative_control_without_stdin_baudolo_gets_no_password(self):
|
||||
for subcommand, argv in self.argvs().items():
|
||||
with self.subTest(subcommand=subcommand):
|
||||
self.assertEqual(self.baudolo_receives(argv, ""), "")
|
||||
|
||||
|
||||
POSTGRES_HEADER = """--
|
||||
-- PostgreSQL database dump
|
||||
@@ -310,9 +454,11 @@ class TestReplay(TestCase):
|
||||
|
||||
def replay(self, running):
|
||||
calls = []
|
||||
self.stdins = []
|
||||
|
||||
def fake_run(argv, secret=""):
|
||||
def fake_run(argv, secret="", stdin=None):
|
||||
calls.append(argv)
|
||||
self.stdins.append(stdin)
|
||||
return ""
|
||||
|
||||
with (
|
||||
@@ -349,6 +495,42 @@ class TestReplay(TestCase):
|
||||
self.assertEqual(len(restores), 1)
|
||||
self.assertEqual(restores[0][:2], ["baudolo-restore", "postgres"])
|
||||
|
||||
def test_the_password_goes_in_on_stdin_and_on_no_argv(self):
|
||||
_, calls = self.replay([])
|
||||
self.assertEqual(
|
||||
[argv for argv in calls if any("s3cret" in part for part in argv)], []
|
||||
)
|
||||
self.assertEqual([stdin for stdin in self.stdins if stdin], ["s3cret\n"])
|
||||
|
||||
def test_a_compressed_dump_is_replayed(self):
|
||||
(self.generation / "postgres/sql/zammad.backup.sql").unlink()
|
||||
with gzip.open(
|
||||
self.generation / "postgres/sql/zammad.backup.sql.gz", "wt"
|
||||
) as out:
|
||||
out.write(POSTGRES_HEADER)
|
||||
replayed, calls = self.replay([])
|
||||
self.assertEqual(replayed, 1)
|
||||
restore = next(argv for argv in calls if argv[0] == "baudolo-restore")
|
||||
self.assertEqual(restore[restore.index("--db-name") + 1], "zammad")
|
||||
|
||||
def test_negative_control_a_dump_held_twice_replays_nothing(self):
|
||||
with gzip.open(
|
||||
self.generation / "postgres/sql/zammad.backup.sql.gz", "wt"
|
||||
) as out:
|
||||
out.write(POSTGRES_HEADER)
|
||||
calls = []
|
||||
with (
|
||||
mock.patch.object(
|
||||
recovery_docker,
|
||||
"_run",
|
||||
lambda argv, secret="", stdin=None: calls.append(argv) or "",
|
||||
),
|
||||
self.assertRaises(databases.RecoveryError) as raised,
|
||||
):
|
||||
databases.replay(self.generation, self.csv, engines=self.engines)
|
||||
self.assertIn("same dump twice", str(raised.exception))
|
||||
self.assertEqual(calls, [])
|
||||
|
||||
def test_the_version_check_is_left_to_baudolo(self):
|
||||
_, calls = self.replay([])
|
||||
self.assertEqual(
|
||||
@@ -385,7 +567,9 @@ class TestReplay(TestCase):
|
||||
|
||||
def test_no_container_at_all_says_to_deploy_first(self):
|
||||
with (
|
||||
mock.patch.object(recovery_docker, "_run", lambda argv, secret="": ""),
|
||||
mock.patch.object(
|
||||
recovery_docker, "_run", lambda argv, secret="", stdin=None: ""
|
||||
),
|
||||
self.assertRaises(databases.RecoveryError) as raised,
|
||||
):
|
||||
recovery_docker.container_of_volume("postgres")
|
||||
@@ -430,7 +614,9 @@ class TestReplay(TestCase):
|
||||
encoding="utf-8",
|
||||
)
|
||||
with (
|
||||
mock.patch.object(recovery_docker, "_run", lambda argv, secret="": ""),
|
||||
mock.patch.object(
|
||||
recovery_docker, "_run", lambda argv, secret="", stdin=None: ""
|
||||
),
|
||||
mock.patch.object(
|
||||
recovery_docker,
|
||||
"consumers_running",
|
||||
@@ -460,7 +646,9 @@ class TestReplay(TestCase):
|
||||
mock.patch.object(
|
||||
recovery_docker,
|
||||
"_run",
|
||||
lambda argv, secret="": "bigbluebutton\n" if "inspect" in argv else "",
|
||||
lambda argv, secret="", stdin=None: (
|
||||
"bigbluebutton\n" if "inspect" in argv else ""
|
||||
),
|
||||
),
|
||||
mock.patch.object(
|
||||
recovery_docker,
|
||||
@@ -518,7 +706,9 @@ class TestReplay(TestCase):
|
||||
encoding="utf-8",
|
||||
)
|
||||
with (
|
||||
mock.patch.object(recovery_docker, "_run", lambda argv, secret="": ""),
|
||||
mock.patch.object(
|
||||
recovery_docker, "_run", lambda argv, secret="", stdin=None: ""
|
||||
),
|
||||
mock.patch.object(recovery_docker, "consumers_running", lambda *a, **k: []),
|
||||
mock.patch.object(
|
||||
recovery_docker, "container_of_volume", lambda *a, **k: "postgres-1"
|
||||
@@ -532,6 +722,22 @@ class TestReplay(TestCase):
|
||||
self.assertNotIn("s3cret", str(raised.exception))
|
||||
self.assertIn("***", str(raised.exception))
|
||||
|
||||
def test_a_password_echoed_on_stderr_is_redacted_too(self):
|
||||
with self.assertRaises(databases.RecoveryError) as raised:
|
||||
recovery_docker._run(
|
||||
["sh", "-c", "cat >&2; exit 1"], secret="s3cret", stdin="s3cret\n"
|
||||
)
|
||||
self.assertNotIn("s3cret", str(raised.exception))
|
||||
self.assertIn("***", str(raised.exception))
|
||||
|
||||
def test_negative_control_unredacted_stderr_is_shown(self):
|
||||
with self.assertRaises(databases.RecoveryError) as raised:
|
||||
recovery_docker._run(["sh", "-c", "cat >&2; exit 1"], stdin="s3cret\n")
|
||||
self.assertIn("s3cret", str(raised.exception))
|
||||
|
||||
def test_stdin_reaches_the_command(self):
|
||||
self.assertEqual(recovery_docker._run(["cat"], stdin="s3cret\n"), "s3cret\n")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -99,7 +99,7 @@ class TestLayoutOf(unittest.TestCase):
|
||||
self.assertEqual(manifest.layout_of(directory)["files_dir"], "payload")
|
||||
self.assertEqual(
|
||||
manifest.globs_of(manifest.layout_of(directory)),
|
||||
("*/payload", "*/dumps/*.sql.gz"),
|
||||
("*/payload", ("*/dumps/*.sql.gz", "*/dumps/*.sql")),
|
||||
)
|
||||
|
||||
def test_a_generation_without_a_manifest_falls_back_to_the_literals(self) -> None:
|
||||
@@ -108,11 +108,42 @@ class TestLayoutOf(unittest.TestCase):
|
||||
self.assertEqual(names["sql_dir"], layout.SQL_DIR)
|
||||
|
||||
def test_the_fallback_globs_match_the_literal_layout(self) -> None:
|
||||
files_glob, dump_glob = manifest.globs_of(
|
||||
files_glob, dump_globs = manifest.globs_of(
|
||||
manifest.layout_of(tempfile.mkdtemp())
|
||||
)
|
||||
self.assertEqual(files_glob, f"*/{layout.FILES_DIR}")
|
||||
self.assertEqual(dump_glob, f"*/{layout.SQL_DIR}/*{layout.DUMP_SUFFIX}")
|
||||
self.assertEqual(
|
||||
dump_globs,
|
||||
(
|
||||
f"*/{layout.SQL_DIR}/*.backup.sql.gz",
|
||||
f"*/{layout.SQL_DIR}/*.backup.sql",
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
class TestDumpSuffixes(unittest.TestCase):
|
||||
def test_a_compressed_name_also_finds_the_plain_one(self) -> None:
|
||||
self.assertEqual(
|
||||
manifest.dump_suffixes(".backup.sql.gz"), (".backup.sql.gz", ".backup.sql")
|
||||
)
|
||||
|
||||
def test_negative_control_a_plain_name_finds_only_itself(self) -> None:
|
||||
self.assertEqual(manifest.dump_suffixes(".backup.sql"), (".backup.sql",))
|
||||
|
||||
def test_a_generation_stating_the_plain_names_is_walked_with_those(self) -> None:
|
||||
directory = generation(
|
||||
{},
|
||||
layout_names={
|
||||
"files_dir": "files",
|
||||
"sql_dir": "sql",
|
||||
"dump_suffix": ".backup.sql",
|
||||
"cluster_suffix": ".cluster.backup.sql",
|
||||
},
|
||||
)
|
||||
self.assertEqual(
|
||||
manifest.globs_of(manifest.layout_of(directory))[1],
|
||||
("*/sql/*.backup.sql",),
|
||||
)
|
||||
|
||||
|
||||
class TestSchemaGuard(unittest.TestCase):
|
||||
|
||||
+57
-19
@@ -32,6 +32,7 @@ from utils.cache.applications import get_application_defaults
|
||||
from utils.recovery import docker as recovery_docker
|
||||
from utils.recovery import manifest
|
||||
from utils.recovery.docker import RecoveryError
|
||||
from utils.recovery.layout import COMPRESSED_SUFFIX
|
||||
from utils.roles.applications.services.database import (
|
||||
RDBMS_SERVICE_KEYS,
|
||||
resolve_database_service_key,
|
||||
@@ -127,22 +128,52 @@ def dumps_of(generation_dir: Path) -> tuple[list[Dump], list[Cluster]]:
|
||||
Returns:
|
||||
The single-database dumps, and the cluster dumps, which name their
|
||||
instance in the file name and go through ``baudolo-restore cluster``.
|
||||
|
||||
Raises:
|
||||
RecoveryError: one dump is there both compressed and plain.
|
||||
``baudolo-restore`` refuses to pick either, so the replay stops
|
||||
here, before the first dump goes in.
|
||||
"""
|
||||
dumps: list[Dump] = []
|
||||
clusters: list[Cluster] = []
|
||||
names = manifest.layout_of(generation_dir)
|
||||
cluster_suffix = names["cluster_suffix"]
|
||||
dump_suffix = names["dump_suffix"]
|
||||
_files_glob, dump_glob = manifest.globs_of(names)
|
||||
for path in sorted(generation_dir.glob(dump_glob)):
|
||||
cluster_suffixes = manifest.dump_suffixes(names["cluster_suffix"])
|
||||
dump_suffixes = manifest.dump_suffixes(names["dump_suffix"])
|
||||
_files_glob, dump_globs = manifest.globs_of(names)
|
||||
hits = {hit for glob in dump_globs for hit in generation_dir.glob(glob)}
|
||||
found: dict[Path, Path] = {}
|
||||
for path in sorted(hits):
|
||||
plain = path.with_name(path.name.removesuffix(COMPRESSED_SUFFIX))
|
||||
if plain in found:
|
||||
raise RecoveryError(
|
||||
f"{found[plain].name} and {path.name} in {path.parent} are the "
|
||||
"same dump twice; remove the one that must not be replayed"
|
||||
)
|
||||
found[plain] = path
|
||||
volume = path.parent.parent.name
|
||||
if path.name.endswith(cluster_suffix):
|
||||
clusters.append(Cluster(volume, path.name[: -len(cluster_suffix)], path))
|
||||
instance = _stem(path.name, cluster_suffixes)
|
||||
if instance is not None:
|
||||
clusters.append(Cluster(volume, instance, path))
|
||||
continue
|
||||
dumps.append(Dump(volume, path.name[: -len(dump_suffix)], path))
|
||||
dumps.append(Dump(volume, _stem(path.name, dump_suffixes), path))
|
||||
return dumps, clusters
|
||||
|
||||
|
||||
def _stem(name: str, suffixes: tuple[str, ...]) -> str | None:
|
||||
"""
|
||||
Args:
|
||||
name: a dump file name.
|
||||
suffixes: the suffixes a dump of that kind may carry, first match wins.
|
||||
|
||||
Returns:
|
||||
*name* without the first of *suffixes* it ends in, None for none.
|
||||
"""
|
||||
for suffix in suffixes:
|
||||
if name.endswith(suffix):
|
||||
return name[: -len(suffix)]
|
||||
return None
|
||||
|
||||
|
||||
def _rows_of(csv_path: Path) -> list[Row]:
|
||||
"""The host's databases.csv, read through baudolo's own reader."""
|
||||
if not csv_path.is_file():
|
||||
@@ -230,7 +261,6 @@ def restore_argv(
|
||||
engine: str,
|
||||
container: str,
|
||||
user: str,
|
||||
password: str,
|
||||
) -> list[str]:
|
||||
"""Build the baudolo-restore call that replays one dump."""
|
||||
return [
|
||||
@@ -249,8 +279,7 @@ def restore_argv(
|
||||
dump.database,
|
||||
"--db-user",
|
||||
user,
|
||||
"--db-password",
|
||||
password,
|
||||
"--db-password-stdin",
|
||||
"--empty",
|
||||
]
|
||||
|
||||
@@ -260,7 +289,6 @@ def cluster_argv(
|
||||
generation: Generation,
|
||||
container: str,
|
||||
user: str,
|
||||
password: str,
|
||||
) -> list[str]:
|
||||
"""Build the baudolo-restore call that replays one instance as a whole.
|
||||
|
||||
@@ -283,12 +311,24 @@ def cluster_argv(
|
||||
cluster.instance,
|
||||
"--db-user",
|
||||
user,
|
||||
"--db-password",
|
||||
password,
|
||||
"--db-password-stdin",
|
||||
"--empty",
|
||||
]
|
||||
|
||||
|
||||
def _restore(argv: list[str], password: str) -> str:
|
||||
"""
|
||||
Args:
|
||||
argv: one baudolo-restore call carrying ``--db-password-stdin``.
|
||||
password: sent on stdin followed by one newline, which
|
||||
``--db-password-stdin`` strips again.
|
||||
|
||||
Returns:
|
||||
The call's output.
|
||||
"""
|
||||
return recovery_docker._run(argv, secret=password, stdin=f"{password}\n")
|
||||
|
||||
|
||||
def replay(
|
||||
generation_dir: Path,
|
||||
csv_path: Path,
|
||||
@@ -358,9 +398,8 @@ def replay(
|
||||
container = engine_of_cluster[cluster.path]
|
||||
user, password = cluster_credentials[cluster.instance]
|
||||
print(
|
||||
recovery_docker._run(
|
||||
cluster_argv(cluster, generation, container, user, password),
|
||||
secret=password,
|
||||
_restore(
|
||||
cluster_argv(cluster, generation, container, user), password
|
||||
).strip()
|
||||
)
|
||||
print(f"OK: replayed cluster dump '{cluster.instance}' into {container}")
|
||||
@@ -370,9 +409,8 @@ def replay(
|
||||
container = recovery_docker.container_of_volume(dump.volume, docker_host)
|
||||
user, password = credentials[dump.database]
|
||||
print(
|
||||
recovery_docker._run(
|
||||
restore_argv(dump, generation, engine, container, user, password),
|
||||
secret=password,
|
||||
_restore(
|
||||
restore_argv(dump, generation, engine, container, user), password
|
||||
).strip()
|
||||
)
|
||||
print(f"OK: replayed {engine} dump '{dump.database}' into {container}")
|
||||
|
||||
@@ -21,24 +21,29 @@ def _docker(argv: list[str], docker_host: str | None) -> list[str]:
|
||||
return [DOCKER_BIN, *(["-H", docker_host] if docker_host else []), *argv]
|
||||
|
||||
|
||||
def _run(argv: list[str], secret: str = "") -> str:
|
||||
def _run(argv: list[str], secret: str = "", stdin: str | None = None) -> str:
|
||||
"""Run a command, aborting the replay when it fails.
|
||||
|
||||
Args:
|
||||
argv: the command.
|
||||
secret: a value to redact from the error message.
|
||||
secret: a value to redact from the error message, which quotes both
|
||||
the command and its stderr.
|
||||
stdin: text fed to the command's stdin, None for none.
|
||||
"""
|
||||
try:
|
||||
result = subprocess.run(argv, capture_output=True, text=True, check=False)
|
||||
result = subprocess.run(
|
||||
argv, capture_output=True, text=True, check=False, input=stdin
|
||||
)
|
||||
except FileNotFoundError as missing:
|
||||
raise RecoveryError(f"{argv[0]} is not on PATH") from missing
|
||||
if result.returncode != 0:
|
||||
shown = " ".join(argv)
|
||||
shown = (
|
||||
f"command failed ({result.returncode}): {' '.join(argv)}\n"
|
||||
f"{result.stderr.strip()}"
|
||||
)
|
||||
if secret:
|
||||
shown = shown.replace(secret, "***")
|
||||
raise RecoveryError(
|
||||
f"command failed ({result.returncode}): {shown}\n{result.stderr.strip()}"
|
||||
)
|
||||
raise RecoveryError(shown)
|
||||
return result.stdout
|
||||
|
||||
|
||||
|
||||
@@ -16,8 +16,9 @@ from __future__ import annotations
|
||||
|
||||
SQL_DIR = "sql"
|
||||
FILES_DIR = "files"
|
||||
DUMP_SUFFIX = ".backup.sql"
|
||||
CLUSTER_SUFFIX = ".cluster.backup.sql"
|
||||
DUMP_SUFFIX = ".backup.sql.gz"
|
||||
CLUSTER_SUFFIX = ".cluster.backup.sql.gz"
|
||||
COMPRESSED_SUFFIX = ".gz"
|
||||
|
||||
MANIFEST_FILE = "manifest.json"
|
||||
MANIFEST_SCHEMA = 1
|
||||
@@ -66,15 +66,32 @@ def layout_of(generation_dir: Path | str) -> dict[str, str]:
|
||||
}
|
||||
|
||||
|
||||
def globs_of(names: dict[str, str]) -> tuple[str, str]:
|
||||
"""``(files_glob, dump_glob)`` for the layout *names* describe.
|
||||
def dump_suffixes(suffix: str) -> tuple[str, ...]:
|
||||
"""
|
||||
Args:
|
||||
suffix: a ``dump_suffix`` or ``cluster_suffix`` of a layout.
|
||||
|
||||
Takes the names rather than the directory so a caller that needs both
|
||||
reads the manifest once.
|
||||
Returns:
|
||||
*suffix*, then the plain name it compresses when it ends in
|
||||
``COMPRESSED_SUFFIX``, the pair ``baudolo-restore`` tries.
|
||||
"""
|
||||
return tuple(
|
||||
dict.fromkeys((suffix, suffix.removesuffix(fallback.COMPRESSED_SUFFIX)))
|
||||
)
|
||||
|
||||
|
||||
def globs_of(names: dict[str, str]) -> tuple[str, tuple[str, ...]]:
|
||||
"""``(files_glob, dump_globs)`` for the layout *names* describe.
|
||||
|
||||
One dump glob per name in :func:`dump_suffixes`. Takes the names rather
|
||||
than the directory so a caller that needs both reads the manifest once.
|
||||
"""
|
||||
return (
|
||||
f"*/{names['files_dir']}",
|
||||
f"*/{names['sql_dir']}/*{names['dump_suffix']}",
|
||||
tuple(
|
||||
f"*/{names['sql_dir']}/*{suffix}"
|
||||
for suffix in dump_suffixes(names["dump_suffix"])
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
|
||||
Reference in new issue
Block a user