fix: stable dump path so restic reuses a parent snapshot
ci / docker (push) Successful in 17s

Every run wrote its dump to <DB_DUMP_DIR>/<stamp>/, so the restic path set
changed nightly, no parent snapshot was ever found, and the whole 337 GiB
block store was re-hashed (~17 min per repository).

The dump now lives at <DB_DUMP_DIR>/current/seafile-databases.sql, written
to a .part file and renamed only after the 'Dump completed' trailer is
verified, so a failed dump never replaces the last good one. Rotated copies
are hardlinked into <DB_DUMP_DIR>/archive/<stamp>/, which is outside the
backed-up path set; DB_DUMP_KEEP now rotates those, and legacy per-run
directories are removed.
This commit is contained in:
trex Bot committed 2026-11-24 23:41:03 -06:00
1 parent 58e81b633a
commit 5c009974c8
2 files changed
+75 -30

No files matched your search

+54 -24
View File
@@ -548,9 +548,15 @@ def dump_databases(cfg: Config, stamp: str) -> dict:
if not password:
raise StepError("db-dump", f"no database password in {cfg.conf_env}")
outdir = Path(cfg.db_dump_dir) / stamp
# restic only reuses a parent snapshot when the path set matches the
# previous run exactly. A per-run directory (<DB_DUMP_DIR>/<stamp>) made
# every run a new path set, so restic re-hashed all 337 GiB of blocks each
# night. The dump therefore lives at a stable path; rotated copies go to
# archive/<stamp>/, which is deliberately outside the backed-up paths.
outdir = Path(cfg.db_dump_dir) / "current"
outdir.mkdir(parents=True, exist_ok=True)
target = outdir / "seafile-databases.sql"
partial = outdir / "seafile-databases.sql.part"
cmd = ["mariadb-dump", "-h", host, "-u", user]
if not cfg.db_ssl:
@@ -569,27 +575,42 @@ def dump_databases(cfg: Config, stamp: str) -> dict:
]
log(f"$ mariadb-dump -h {host} -u {user} ... --databases {' '.join(cfg.databases)} > {target}")
with target.open("wb") as handle:
result = subprocess.run(
cmd,
env={**os.environ, "MYSQL_PWD": password},
stdout=handle,
stderr=subprocess.PIPE,
)
if result.returncode != 0:
message = result.stderr.decode("utf-8", "replace").strip().splitlines()
raise StepError("db-dump", f"exit {result.returncode}: {message[-1] if message else ''}")
try:
with partial.open("wb") as handle:
result = subprocess.run(
cmd,
env={**os.environ, "MYSQL_PWD": password},
stdout=handle,
stderr=subprocess.PIPE,
)
if result.returncode != 0:
message = result.stderr.decode("utf-8", "replace").strip().splitlines()
raise StepError("db-dump", f"exit {result.returncode}: {message[-1] if message else ''}")
size = target.stat().st_size
if size < 1024:
raise StepError("db-dump", f"dump is only {size} bytes")
with target.open("rb") as handle:
handle.seek(max(0, size - 512))
tail = handle.read()
if b"Dump completed" not in tail:
raise StepError("db-dump", "dump is truncated (no 'Dump completed' trailer)")
size = partial.stat().st_size
if size < 1024:
raise StepError("db-dump", f"dump is only {size} bytes")
with partial.open("rb") as handle:
handle.seek(max(0, size - 512))
tail = handle.read()
if b"Dump completed" not in tail:
raise StepError("db-dump", "dump is truncated (no 'Dump completed' trailer)")
# Only replace the last good dump once the new one is complete.
os.replace(partial, target)
finally:
if partial.exists():
partial.unlink()
log(f"db dump ok: {target} ({human(size)})")
# Keep a rotated copy for local restore without putting it in the snapshot.
archive = Path(cfg.db_dump_dir) / "archive" / stamp
archive.mkdir(parents=True, exist_ok=True)
archived = archive / "seafile-databases.sql"
try:
os.link(target, archived)
except OSError:
shutil.copy2(target, archived)
log(f"db dump ok: {target} ({human(size)}), archived to {archived}")
return {"path": str(target), "bytes": size, "databases": list(cfg.databases)}
@@ -632,8 +653,8 @@ def latest_snapshot(cfg: Config, repository: str, password: str) -> dict | None:
}
def restic_backup(cfg: Config, repository: str, password: str, stamp: str) -> dict:
paths = [cfg.seafile_root, os.path.join(cfg.db_dump_dir, stamp)]
def restic_backup(cfg: Config, repository: str, password: str) -> dict:
paths = [cfg.seafile_root, os.path.join(cfg.db_dump_dir, "current")]
excludes = [
os.path.join(cfg.seafile_root, "logs"),
os.path.join(cfg.seafile_root, "tmpfiles"),
@@ -697,7 +718,16 @@ def cleanup_dumps(cfg: Config) -> None:
root = Path(cfg.db_dump_dir)
if not root.is_dir():
return
directories = sorted((p for p in root.iterdir() if p.is_dir()), reverse=True)
# Dumps from the old per-run layout (<DB_DUMP_DIR>/<stamp>/) are no longer
# part of the snapshot, so they would just sit there filling the volume.
for legacy in root.iterdir():
if legacy.is_dir() and legacy.name not in ("current", "archive"):
shutil.rmtree(legacy, ignore_errors=True)
log(f"removed legacy dump directory {legacy}")
archive = root / "archive"
if not archive.is_dir():
return
directories = sorted((p for p in archive.iterdir() if p.is_dir()), reverse=True)
for stale in directories[cfg.db_dump_keep:]:
shutil.rmtree(stale, ignore_errors=True)
log(f"removed old dump directory {stale}")
@@ -767,7 +797,7 @@ def main() -> int:
removed_locks.setdefault(name, []).extend(
cleanup_stale_locks(cfg, name, repository, password)
)
snapshots[name] = restic_backup(cfg, repository, password, stamp)
snapshots[name] = restic_backup(cfg, repository, password)
result["snapshots"] = snapshots
result["locks"] = removed_locks
retention(cfg, removed_locks)