diff --git a/README.md b/README.md index aee92dc..102afed 100644 --- a/README.md +++ b/README.md @@ -20,13 +20,17 @@ pre-upgrade snapshots. It is off by default and needs `/var/run/docker.sock`. 3. Dumps `ccnet_db`, `seafile_db` and `seahub_db` into one consistent `--databases` dump under `/config/db//`, reading the credentials from the Seafile `conf/.env`. -4. Runs `restic backup` over the Seafile tree **and** that dump directory in a - single snapshot, tagged `seafile`, host `cygnus`. +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`, + host `cygnus`. 5. Repeats the backup into `LOCAL_RESTIC_REPOSITORY` when it is set. 6. Applies the retention policy, prunes weekly and runs a `--read-data-subset` - check weekly. + 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`. -8. Pings Kuma with the result and sends an Apprise notification. +8. Pings Kuma with the result and sends an Apprise notification. The body + names any lock that was removed. Any failure exits non-zero, pushes `?status=down` to Kuma and sends a failure notification. Kuma has no `/start` or `/fail` path — those forms answer 200 but @@ -50,6 +54,9 @@ record nothing, which is why the query string is the only form used here. | `LOCAL_RESTIC_PASSWORD` | `RESTIC_PASSWORD` | password for the local repository | | `RESTIC_CACHE_DIR` | `/config/restic-cache` | restic cache root | | `RESTIC_HOST` / `RESTIC_TAG` | `cygnus` / `seafile` | snapshot labels | +| `LOCK_STALE_AFTER` | `1800` | seconds before a lock counts as stale (restic's own window) | +| `LOCK_GRACE` | `600` | minimum age before a lock with a dead owner is removed | +| `RETRY_LOCK` | `30m` | `--retry-lock` passed to every restic call; empty disables it | | `KEEP_DAILY` / `KEEP_WEEKLY` / `KEEP_MONTHLY` / `KEEP_YEARLY` | `7` / `4` / `12` / `3` | retention | | `PRUNE_WEEKDAY` | `0` (Monday) | weekday to run `restic prune` | | `CHECK_WEEKDAY` | `6` (Sunday) | weekday to run `restic check` | @@ -65,6 +72,40 @@ record nothing, which is why the query string is the only form used here. `AWS_ACCESS_KEY_ID` / `AWS_SECRET_ACCESS_KEY` are read by restic itself for the `s3:` backend. +## Stale locks + +restic takes a lock in the repository for the duration of a run. If the +container is recreated mid-backup — a Komodo deploy, a `docker restart`, an +OOM kill — the process dies without releasing it, and restic will not treat +that lock as stale for **30 minutes**. The next run then either fails with +`repository is already locked` or blocks. + +Before each repository leg the script lists the locks, reads each one with +`restic cat lock` and classifies it: + +| Verdict | Condition | Action | +|---|---|---| +| `stale` | older than `LOCK_STALE_AFTER` | removed | +| `orphaned` | taken by this container, older than `LOCK_GRACE`, pid gone | removed | +| `live` | anything else | left alone | +| `unknown` | unparseable timestamp | removed | + +If nothing live is left, the removal is `restic unlock --remove-all`; if a live +lock is still there it falls back to plain `restic unlock`, which only drops the +ones past restic's own 30 minute window. Every lock is logged with its age, +host, pid and verdict, and the ids that were removed are re-checked with a +second `list locks` before being reported. + +The `orphaned` check compares the lock's `hostname` with the container's own, so +the compose file pins `hostname: seafile-backup` — without it the hostname is +the container id and changes on every recreate, which is exactly the case this +is meant to catch. A lock whose pid has been reused by a live process is +treated as live, so the failure mode is a lock that waits for the 30 minute +window rather than one that is removed while still in use. + +`RETRY_LOCK` is the backstop: every restic call carries `--retry-lock`, so a +lock that survives the cleanup makes the run wait instead of failing. + ## Restore ```sh diff --git a/seafile-backup.py b/seafile-backup.py index 64ece5c..54ecaba 100644 --- a/seafile-backup.py +++ b/seafile-backup.py @@ -24,18 +24,20 @@ import fcntl import hashlib import json import os +import re import shlex import shutil +import socket import subprocess import sys import time import urllib.error import urllib.parse import urllib.request -from datetime import datetime +from datetime import datetime, timezone from pathlib import Path -VERSION = "2.0.1" +VERSION = "2.1.0" LOG_MAX_BYTES = 10 * 1024 * 1024 @@ -128,6 +130,12 @@ class Config: self.restic_cache_dir = env("RESTIC_CACHE_DIR", "/config/restic-cache") self.restic_host = env("RESTIC_HOST", "cygnus") self.restic_tag = env("RESTIC_TAG", "seafile") + # restic calls a lock stale after 30 minutes; match that by default. + self.lock_stale_after = env_int("LOCK_STALE_AFTER", 1800) + # A lock this container took is only removed once it is this old, so a + # run that is just starting up is never mistaken for a dead one. + self.lock_grace = env_int("LOCK_GRACE", 600) + self.retry_lock = env("RETRY_LOCK", "30m") self.keep_daily = env_int("KEEP_DAILY", 7) self.keep_weekly = env_int("KEEP_WEEKLY", 4) @@ -221,8 +229,11 @@ def restic( step: str = "restic", ) -> subprocess.CompletedProcess: digest = hashlib.sha256(repository.encode()).hexdigest()[:12] + # --retry-lock makes a lock we could not clear wait instead of failing the + # run outright; restic drops it itself once it passes its stale window. + global_args = ["--retry-lock", cfg.retry_lock] if cfg.retry_lock else [] return run( - ["restic", *args], + ["restic", *global_args, *args], env_extra={ "RESTIC_REPOSITORY": repository, "RESTIC_PASSWORD": password, @@ -356,6 +367,130 @@ def acquire_lock(cfg: Config): return handle +def parse_restic_time(value: str | None) -> datetime | None: + """Parse a restic RFC3339 timestamp (nanosecond precision) as an aware datetime.""" + if not value: + return None + text = value.strip() + if text.endswith("Z"): + text = text[:-1] + "+00:00" + # restic writes nanoseconds; datetime.fromisoformat stops at microseconds + text = re.sub(r"(\.\d{6})\d+", r"\1", text) + try: + parsed = datetime.fromisoformat(text) + except ValueError: + return None + if parsed.tzinfo is None: + parsed = parsed.replace(tzinfo=timezone.utc) + return parsed + + +def pid_alive(pid: int) -> bool: + if pid <= 0: + return False + try: + os.kill(pid, 0) + except ProcessLookupError: + return False + except OSError: + # EPERM means the process exists but belongs to another user + return True + return True + + +def list_locks(cfg: Config, name: str, repository: str, password: str) -> list[dict]: + """Return every lock in the repository, with its id attached.""" + result = restic(cfg, repository, password, ["list", "locks"], capture=True, check=False) + if result.returncode != 0: + detail = (result.stderr or "").strip().splitlines() + log( + f"WARNING: cannot list locks in {name} (exit {result.returncode})" + + (f": {detail[-1]}" if detail else "") + ) + return [] + locks: list[dict] = [] + for lock_id in (result.stdout or "").split(): + info = restic( + cfg, repository, password, ["cat", "lock", lock_id], capture=True, check=False + ) + if info.returncode != 0: + log(f"WARNING: cannot read lock {lock_id[:8]} in {name}") + continue + try: + data = json.loads(info.stdout or "{}") + except json.JSONDecodeError: + log(f"WARNING: lock {lock_id[:8]} in {name} is not valid JSON") + continue + data["id"] = lock_id + locks.append(data) + return locks + + +def classify_lock( + cfg: Config, lock: dict, now: datetime, hostname: str +) -> tuple[str, float | None]: + """Decide whether a lock is stale, orphaned (dead owner) or still live.""" + created = parse_restic_time(lock.get("time")) + if created is None: + return "unknown", None + age = (now - created).total_seconds() + if age >= cfg.lock_stale_after: + return "stale", age + try: + pid = int(lock.get("pid") or 0) + except (TypeError, ValueError): + pid = 0 + if lock.get("hostname") == hostname and age >= cfg.lock_grace and not pid_alive(pid): + return "orphaned", age + return "live", age + + +def cleanup_stale_locks(cfg: Config, name: str, repository: str, password: str) -> list[str]: + """Remove restic locks left behind by a run that died. + + restic only calls a lock stale after 30 minutes, so a container recreated + mid-backup leaves a lock that blocks the next run for half an hour. A lock + is removed when it is older than LOCK_STALE_AFTER (restic's own rule) or + when this container took it and its pid is gone. Locks that still look live + are left alone: restic's own ``unlock`` only drops the ones past its window. + """ + locks = list_locks(cfg, name, repository, password) + if not locks: + return [] + now = datetime.now(timezone.utc) + hostname = socket.gethostname() + removable: list[dict] = [] + live = 0 + for lock in locks: + verdict, age = classify_lock(cfg, lock, now, hostname) + log( + f"lock {lock['id'][:8]} in {name}: {verdict} " + f"(age {duration(age) if age is not None else 'unknown'}, " + f"exclusive={lock.get('exclusive')}, host={lock.get('hostname')}, " + f"pid={lock.get('pid')})" + ) + if verdict == "live": + live += 1 + else: + removable.append(lock) + if not removable: + return [] + # --remove-all is only safe once nothing live is left; otherwise fall back + # to restic's own 30 minute rule. + args = ["unlock"] if live else ["unlock", "--remove-all"] + restic(cfg, repository, password, args, step=f"restic-unlock-{name}") + remaining = {lock["id"] for lock in list_locks(cfg, name, repository, password)} + removed = [lock["id"] for lock in removable if lock["id"] not in remaining] + if removed: + log( + f"removed {len(removed)} stale lock(s) from {name}: " + + ", ".join(lock_id[:8] for lock_id in removed) + ) + else: + log(f"WARNING: {len(removable)} stale lock(s) in {name} survived restic unlock") + return removed + + # -------------------------------------------------------------------------- # steps # -------------------------------------------------------------------------- @@ -514,9 +649,14 @@ def restic_backup(cfg: Config, repository: str, password: str, stamp: str) -> di return snapshot -def retention(cfg: Config) -> None: +def retention(cfg: Config, removed_locks: dict[str, list[str]]) -> None: today = datetime.now().weekday() for name, repository, password in cfg.repositories(): + # forget/prune/check want an exclusive lock, so clear anything a dead + # run left behind before asking for one. + removed_locks.setdefault(name, []).extend( + cleanup_stale_locks(cfg, name, repository, password) + ) restic( cfg, repository, password, [ @@ -568,6 +708,15 @@ def build_body(cfg: Config, ok: bool, result: dict, elapsed: float) -> str: lines.append(f"db dump: {human(dump['bytes'])} ({', '.join(dump['databases'])})") for name, snapshot in (result.get("snapshots") or {}).items(): lines.append(f"{name} snapshot: {snapshot['id']}") + locks = {name: ids for name, ids in (result.get("locks") or {}).items() if ids} + if locks: + lines.append( + "stale locks removed: " + + "; ".join( + f"{name} " + ", ".join(lock_id[:8] for lock_id in ids) + for name, ids in locks.items() + ) + ) if result.get("warnings"): lines.append("warnings: " + "; ".join(result["warnings"])) return "\n".join(lines) @@ -601,11 +750,16 @@ def main() -> int: stopped = True result["dump"] = dump_databases(cfg, stamp) snapshots = {} + removed_locks: dict[str, list[str]] = {} for name, repository, password in cfg.repositories(): ensure_repository(cfg, repository, password) + removed_locks.setdefault(name, []).extend( + cleanup_stale_locks(cfg, name, repository, password) + ) snapshots[name] = restic_backup(cfg, repository, password, stamp) result["snapshots"] = snapshots - retention(cfg) + result["locks"] = removed_locks + retention(cfg, removed_locks) cleanup_dumps(cfg) result["ok"] = True except Exception as exc: # noqa: BLE001 - top level guard, reported below