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:
1 parent
58e81b633a
commit
5c009974c8
2 files changed
+60
-15
No files matched your search
@@ -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
|
2. Pings the Uptime Kuma push monitor with `?status=up` so the monitor stays
|
||||||
green while the run is in progress.
|
green while the run is in progress.
|
||||||
3. Dumps `ccnet_db`, `seafile_db` and `seahub_db` into one consistent
|
3. Dumps `ccnet_db`, `seafile_db` and `seahub_db` into one consistent
|
||||||
`--databases` dump under `/config/db/<timestamp>/`, reading the credentials
|
`--databases` dump at the stable path
|
||||||
from the Seafile `conf/.env`.
|
`/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
|
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
|
[Stale locks](#stale-locks)), then runs `restic backup` over the Seafile
|
||||||
tree **and** that dump directory in a single snapshot, tagged `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`
|
6. Applies the retention policy, prunes weekly and runs a `--read-data-subset`
|
||||||
check weekly — clearing stale locks again first, because `forget`, `prune`
|
check weekly — clearing stale locks again first, because `forget`, `prune`
|
||||||
and `check` want an exclusive lock.
|
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
|
8. Pings Kuma with the result and sends an Apprise notification. The body
|
||||||
names any lock that was removed.
|
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_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) |
|
| `DB_SSL` | `false` | pass TLS to `mariadb-dump` (the bundled server has none) |
|
||||||
| `DATABASES` | `ccnet_db,seafile_db,seahub_db` | databases to dump |
|
| `DATABASES` | `ccnet_db,seafile_db,seahub_db` | databases to dump |
|
||||||
| `DB_DUMP_DIR` | `/config/db` | where dumps are written |
|
| `DB_DUMP_DIR` | `/config/db` | dump root: `current/` is backed up, `archive/` is rotated |
|
||||||
| `DB_DUMP_KEEP` | `3` | dump directories to keep |
|
| `DB_DUMP_KEEP` | `3` | archived dumps to keep |
|
||||||
| `LOG_PATH` | `/config/seafile-backup.log` | log file (rotated at 10 MB) |
|
| `LOG_PATH` | `/config/seafile-backup.log` | log file (rotated at 10 MB) |
|
||||||
| `RESTIC_REPOSITORY` | *required* | primary restic repository |
|
| `RESTIC_REPOSITORY` | *required* | primary restic repository |
|
||||||
| `RESTIC_PASSWORD` | *required* | primary repository password |
|
| `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
|
`AWS_ACCESS_KEY_ID` / `AWS_SECRET_ACCESS_KEY` are read by restic itself for the
|
||||||
`s3:` backend.
|
`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
|
## Stale locks
|
||||||
|
|
||||||
restic takes a lock in the repository for the duration of a run. If the
|
restic takes a lock in the repository for the duration of a run. If the
|
||||||
@@ -126,7 +141,7 @@ minutes old.
|
|||||||
```sh
|
```sh
|
||||||
restic restore latest --target /restore
|
restic restore latest --target /restore
|
||||||
# then, against an empty MariaDB 10.11:
|
# 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
|
The dump is written with `--add-drop-table`, so it can also be replayed over an
|
||||||
|
|||||||
+39
-9
@@ -548,9 +548,15 @@ def dump_databases(cfg: Config, stamp: str) -> dict:
|
|||||||
if not password:
|
if not password:
|
||||||
raise StepError("db-dump", f"no database password in {cfg.conf_env}")
|
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)
|
outdir.mkdir(parents=True, exist_ok=True)
|
||||||
target = outdir / "seafile-databases.sql"
|
target = outdir / "seafile-databases.sql"
|
||||||
|
partial = outdir / "seafile-databases.sql.part"
|
||||||
|
|
||||||
cmd = ["mariadb-dump", "-h", host, "-u", user]
|
cmd = ["mariadb-dump", "-h", host, "-u", user]
|
||||||
if not cfg.db_ssl:
|
if not cfg.db_ssl:
|
||||||
@@ -569,7 +575,8 @@ def dump_databases(cfg: Config, stamp: str) -> dict:
|
|||||||
]
|
]
|
||||||
|
|
||||||
log(f"$ mariadb-dump -h {host} -u {user} ... --databases {' '.join(cfg.databases)} > {target}")
|
log(f"$ mariadb-dump -h {host} -u {user} ... --databases {' '.join(cfg.databases)} > {target}")
|
||||||
with target.open("wb") as handle:
|
try:
|
||||||
|
with partial.open("wb") as handle:
|
||||||
result = subprocess.run(
|
result = subprocess.run(
|
||||||
cmd,
|
cmd,
|
||||||
env={**os.environ, "MYSQL_PWD": password},
|
env={**os.environ, "MYSQL_PWD": password},
|
||||||
@@ -580,16 +587,30 @@ def dump_databases(cfg: Config, stamp: str) -> dict:
|
|||||||
message = result.stderr.decode("utf-8", "replace").strip().splitlines()
|
message = result.stderr.decode("utf-8", "replace").strip().splitlines()
|
||||||
raise StepError("db-dump", f"exit {result.returncode}: {message[-1] if message else ''}")
|
raise StepError("db-dump", f"exit {result.returncode}: {message[-1] if message else ''}")
|
||||||
|
|
||||||
size = target.stat().st_size
|
size = partial.stat().st_size
|
||||||
if size < 1024:
|
if size < 1024:
|
||||||
raise StepError("db-dump", f"dump is only {size} bytes")
|
raise StepError("db-dump", f"dump is only {size} bytes")
|
||||||
with target.open("rb") as handle:
|
with partial.open("rb") as handle:
|
||||||
handle.seek(max(0, size - 512))
|
handle.seek(max(0, size - 512))
|
||||||
tail = handle.read()
|
tail = handle.read()
|
||||||
if b"Dump completed" not in tail:
|
if b"Dump completed" not in tail:
|
||||||
raise StepError("db-dump", "dump is truncated (no 'Dump completed' trailer)")
|
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)}
|
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:
|
def restic_backup(cfg: Config, repository: str, password: str) -> dict:
|
||||||
paths = [cfg.seafile_root, os.path.join(cfg.db_dump_dir, stamp)]
|
paths = [cfg.seafile_root, os.path.join(cfg.db_dump_dir, "current")]
|
||||||
excludes = [
|
excludes = [
|
||||||
os.path.join(cfg.seafile_root, "logs"),
|
os.path.join(cfg.seafile_root, "logs"),
|
||||||
os.path.join(cfg.seafile_root, "tmpfiles"),
|
os.path.join(cfg.seafile_root, "tmpfiles"),
|
||||||
@@ -697,7 +718,16 @@ def cleanup_dumps(cfg: Config) -> None:
|
|||||||
root = Path(cfg.db_dump_dir)
|
root = Path(cfg.db_dump_dir)
|
||||||
if not root.is_dir():
|
if not root.is_dir():
|
||||||
return
|
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:]:
|
for stale in directories[cfg.db_dump_keep:]:
|
||||||
shutil.rmtree(stale, ignore_errors=True)
|
shutil.rmtree(stale, ignore_errors=True)
|
||||||
log(f"removed old dump directory {stale}")
|
log(f"removed old dump directory {stale}")
|
||||||
@@ -767,7 +797,7 @@ def main() -> int:
|
|||||||
removed_locks.setdefault(name, []).extend(
|
removed_locks.setdefault(name, []).extend(
|
||||||
cleanup_stale_locks(cfg, name, repository, password)
|
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["snapshots"] = snapshots
|
||||||
result["locks"] = removed_locks
|
result["locks"] = removed_locks
|
||||||
retention(cfg, removed_locks)
|
retention(cfg, removed_locks)
|
||||||
|
|||||||
Reference in new issue
Block a user