feat: detect and remove stale restic locks
ci / docker (push) Successful in 17s

A container recreated mid-backup leaves a restic lock behind, and restic
will not call it stale for 30 minutes, so the next run fails or blocks.

Before each repository leg (and again before retention, which needs an
exclusive lock) list the locks, read each with 'restic cat lock' and
classify it: stale past LOCK_STALE_AFTER, orphaned when this container
took it and its pid is gone, live otherwise. Remove with
'unlock --remove-all' only when nothing live is left, otherwise fall back
to plain 'unlock' so a running backup is never disturbed. Removed ids are
re-checked with a second list and reported in the notification body.

Every restic call now carries --retry-lock (RETRY_LOCK, default 30m) as a
backstop, so a lock that survives cleanup makes the run wait instead of
failing.
This commit is contained in:
trex Bot committed 2026-11-24 23:26:24 -06:00
1 parent cbf0cbd963
commit 1d8f49980c
2 files changed
+204 -9

No files matched your search

+159 -5
View File
@@ -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