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

+21 -6
View File
@@ -18,8 +18,10 @@ pre-upgrade snapshots. It is off by default and needs `/var/run/docker.sock`.
2. Pings the Uptime Kuma push monitor with `?status=up` so the monitor stays
green while the run is in progress.
3. Dumps `ccnet_db`, `seafile_db` and `seahub_db` into one consistent
`--databases` dump under `/config/db/<timestamp>/`, reading the credentials
from the Seafile `conf/.env`.
`--databases` dump at the stable path
`/config/db/current/seafile-databases.sql`, reading the credentials from the
Seafile `conf/.env`. A rotated copy is hardlinked into
`/config/db/archive/<timestamp>/`.
4. Clears any stale restic lock left behind by a run that died (see
[Stale locks](#stale-locks)), then runs `restic backup` over the Seafile
tree **and** that dump directory in a single snapshot, tagged `seafile`,
@@ -28,7 +30,7 @@ pre-upgrade snapshots. It is off by default and needs `/var/run/docker.sock`.
6. Applies the retention policy, prunes weekly and runs a `--read-data-subset`
check weekly — clearing stale locks again first, because `forget`, `prune`
and `check` want an exclusive lock.
7. Deletes dump directories older than `DB_DUMP_KEEP`.
7. Deletes archived dumps older than `DB_DUMP_KEEP`.
8. Pings Kuma with the result and sends an Apprise notification. The body
names any lock that was removed.
@@ -45,8 +47,8 @@ record nothing, which is why the query string is the only form used here.
| `DB_HOST` / `DB_USER` / `DB_PASSWORD` | from `conf/.env` | override the DB target |
| `DB_SSL` | `false` | pass TLS to `mariadb-dump` (the bundled server has none) |
| `DATABASES` | `ccnet_db,seafile_db,seahub_db` | databases to dump |
| `DB_DUMP_DIR` | `/config/db` | where dumps are written |
| `DB_DUMP_KEEP` | `3` | dump directories to keep |
| `DB_DUMP_DIR` | `/config/db` | dump root: `current/` is backed up, `archive/` is rotated |
| `DB_DUMP_KEEP` | `3` | archived dumps to keep |
| `LOG_PATH` | `/config/seafile-backup.log` | log file (rotated at 10 MB) |
| `RESTIC_REPOSITORY` | *required* | primary restic repository |
| `RESTIC_PASSWORD` | *required* | primary repository password |
@@ -76,6 +78,19 @@ restart of the job.
`AWS_ACCESS_KEY_ID` / `AWS_SECRET_ACCESS_KEY` are read by restic itself for the
`s3:` backend.
## Why the dump path is stable
restic only reuses a parent snapshot when the host and the path set match the
previous run exactly. Writing each dump to its own `<DB_DUMP_DIR>/<stamp>/`
directory changed the path set every night, so restic found no parent and
re-hashed the whole 337 GiB block store — about 17 minutes per repository, for
nothing. The dump now lives at `/config/db/current/`, which is the only dump
path in the snapshot; the rotated copies in `archive/` are outside it.
The dump is written to `seafile-databases.sql.part` and renamed into place only
after the `Dump completed` trailer is verified, so a failed dump never replaces
the last good one.
## Stale locks
restic takes a lock in the repository for the duration of a run. If the
@@ -126,7 +141,7 @@ minutes old.
```sh
restic restore latest --target /restore
# then, against an empty MariaDB 10.11:
mariadb -h <host> -u root -p < /restore/config/db/<stamp>/seafile-databases.sql
mariadb -h <host> -u root -p < /restore/config/db/current/seafile-databases.sql
```
The dump is written with `--add-drop-table`, so it can also be replayed over an
+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)