Files
seafile-backup/seafile-backup.py
T
trex Bot 313db934e4 fix: Kuma has no /start or /fail path — push ?status=up|down instead
A request to /api/push/<token>/start or /fail answers 200 but records no
heartbeat, so a failed run left the push monitor green until its 24h
interval expired. Verified against Uptime Kuma 1.23.17: only the query
string form writes a heartbeat.
2026-11-24 15:05:03 -06:00

643 lines
23 KiB
Python

#!/usr/bin/env python3
"""Online backup of a Seafile CE stack (Seafile 12+) to restic.
Design
------
* No downtime. Seafile keeps serving. The database dump uses
``--single-transaction`` (a consistent InnoDB snapshot) and the block store
is content-addressed and immutable once written, so restic can read it while
Seafile writes. A cold mode exists for pre-upgrade snapshots but is off by
default.
* restic is the only backup engine. rclone is gone: it cannot write to the
RustFS buckets and ``sync`` is the wrong semantics for a backup.
* Every step is checked. Any failure exits non-zero, pushes `status=down` to
the Kuma push monitor and sends a failure notification. The 2023 prototype
discarded every exit code, which is why it reported success while doing
nothing.
Configuration is entirely environment driven; see README.md.
"""
from __future__ import annotations
import fcntl
import hashlib
import json
import os
import shlex
import shutil
import subprocess
import sys
import time
import urllib.error
import urllib.parse
import urllib.request
from datetime import datetime
from pathlib import Path
VERSION = "2.0.1"
LOG_MAX_BYTES = 10 * 1024 * 1024
# --------------------------------------------------------------------------
# logging
# --------------------------------------------------------------------------
class Log:
def __init__(self, path: str):
self.path = Path(path)
def __call__(self, message: str) -> None:
stamp = datetime.now().astimezone().strftime("%Y-%m-%d %H:%M:%S %Z")
line = f"{stamp} {message}"
print(line, flush=True)
try:
self.path.parent.mkdir(parents=True, exist_ok=True)
if self.path.exists() and self.path.stat().st_size > LOG_MAX_BYTES:
self.path.replace(self.path.with_suffix(self.path.suffix + ".1"))
with self.path.open("a", encoding="utf-8") as handle:
handle.write(line + "\n")
except OSError as exc: # never let logging kill a backup
print(f"log write failed: {exc}", file=sys.stderr, flush=True)
log = Log("/config/seafile-backup.log")
# --------------------------------------------------------------------------
# errors
# --------------------------------------------------------------------------
class StepError(RuntimeError):
def __init__(self, step: str, message: str):
super().__init__(f"{step}: {message}")
self.step = step
# --------------------------------------------------------------------------
# configuration
# --------------------------------------------------------------------------
def env(name: str, default: str | None = None) -> str | None:
value = os.environ.get(name)
if value is None or value.strip() == "":
return default
return value
def env_bool(name: str, default: bool = False) -> bool:
value = env(name)
if value is None:
return default
return value.strip().lower() in ("1", "true", "yes", "y", "on", "t")
def env_int(name: str, default: int) -> int:
value = env(name)
if value is None:
return default
try:
return int(value)
except ValueError:
raise SystemExit(f"{name} must be an integer, got {value!r}")
class Config:
def __init__(self) -> None:
self.seafile_root = env("SEAFILE_ROOT", "/shared/seafile")
self.conf_env = env("SEAFILE_CONF_ENV", "/shared/seafile/conf/.env")
self.db_dump_dir = env("DB_DUMP_DIR", "/config/db")
self.db_dump_keep = env_int("DB_DUMP_KEEP", 3)
self.databases = [
name.strip()
for name in env("DATABASES", "ccnet_db,seafile_db,seahub_db").split(",")
if name.strip()
]
self.db_host = env("DB_HOST")
self.db_user = env("DB_USER")
self.db_password = env("DB_PASSWORD")
self.db_ssl = env_bool("DB_SSL", False)
self.log_path = env("LOG_PATH", "/config/seafile-backup.log")
self.lock_path = env("LOCK_PATH", "/config/.seafile-backup.lock")
self.restic_repository = env("RESTIC_REPOSITORY")
self.restic_password = env("RESTIC_PASSWORD")
self.local_repository = env("LOCAL_RESTIC_REPOSITORY")
self.local_password = env("LOCAL_RESTIC_PASSWORD") or self.restic_password
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")
self.keep_daily = env_int("KEEP_DAILY", 7)
self.keep_weekly = env_int("KEEP_WEEKLY", 4)
self.keep_monthly = env_int("KEEP_MONTHLY", 12)
self.keep_yearly = env_int("KEEP_YEARLY", 3)
self.prune_weekday = env_int("PRUNE_WEEKDAY", 0) # Monday
self.check_weekday = env_int("CHECK_WEEKDAY", 6) # Sunday
self.check_read_data = env("CHECK_READ_DATA_SUBSET", "5%")
self.max_unused = env("PRUNE_MAX_UNUSED", "5%")
self.kuma_url = env("KUMA_PUSH_URL")
self.apprise_url = env("APPRISE_URL")
self.apprise_urls = env("APPRISE_URLS")
self.apprise_title = env("APPRISE_TITLE", "Seafile Backup")
self.cold_backup = env_bool("COLD_BACKUP", False)
self.seafile_container = env("SEAFILE_CONTAINER", "seafile")
self.fail_on_partial = env_bool("FAIL_ON_PARTIAL", False)
def validate(self) -> None:
missing = [
name
for name, value in (
("RESTIC_REPOSITORY", self.restic_repository),
("RESTIC_PASSWORD", self.restic_password),
)
if not value
]
if missing:
raise SystemExit("missing required environment: " + ", ".join(missing))
if self.local_repository and not self.local_password:
raise SystemExit("LOCAL_RESTIC_REPOSITORY is set but no password is available")
def repositories(self) -> list[tuple[str, str, str]]:
repos = [("primary", self.restic_repository, self.restic_password)]
if self.local_repository:
repos.append(("local", self.local_repository, self.local_password))
return repos
# --------------------------------------------------------------------------
# process helpers
# --------------------------------------------------------------------------
def run(
cmd: list[str],
*,
env_extra: dict[str, str] | None = None,
capture: bool = False,
log_output: bool = False,
check: bool = True,
step: str | None = None,
) -> subprocess.CompletedProcess:
step = step or cmd[0]
log("$ " + " ".join(shlex.quote(part) for part in cmd))
child_env = os.environ.copy()
if env_extra:
child_env.update(env_extra)
try:
result = subprocess.run(
cmd,
env=child_env,
text=True,
stdout=subprocess.PIPE if capture else None,
stderr=subprocess.PIPE if capture else None,
)
except FileNotFoundError:
raise StepError(step, f"{cmd[0]} not found in PATH")
if capture and log_output:
for stream in (result.stdout, result.stderr):
for line in (stream or "").splitlines():
log(" " + line)
if check and result.returncode != 0:
detail = ""
if capture:
tail = (result.stderr or result.stdout or "").strip().splitlines()
detail = tail[-1] if tail else ""
raise StepError(step, f"exit {result.returncode}" + (f": {detail}" if detail else ""))
return result
def restic(
cfg: Config,
repository: str,
password: str,
args: list[str],
*,
capture: bool = False,
log_output: bool = False,
check: bool = True,
step: str = "restic",
) -> subprocess.CompletedProcess:
digest = hashlib.sha256(repository.encode()).hexdigest()[:12]
return run(
["restic", *args],
env_extra={
"RESTIC_REPOSITORY": repository,
"RESTIC_PASSWORD": password,
"RESTIC_CACHE_DIR": os.path.join(cfg.restic_cache_dir, digest),
"RESTIC_PROGRESS_FPS": "0.0333",
},
capture=capture,
log_output=log_output,
check=check,
step=step,
)
# --------------------------------------------------------------------------
# notifications
# --------------------------------------------------------------------------
def http_get(url: str, timeout: int = 10) -> int:
request = urllib.request.Request(url, headers={"User-Agent": f"seafile-backup/{VERSION}"})
with urllib.request.urlopen(request, timeout=timeout) as response:
response.read(4096)
return response.status
def http_post_json(url: str, payload: dict, timeout: int = 20) -> int:
body = json.dumps(payload).encode("utf-8")
request = urllib.request.Request(
url,
data=body,
headers={
"Content-Type": "application/json",
"User-Agent": f"seafile-backup/{VERSION}",
},
method="POST",
)
with urllib.request.urlopen(request, timeout=timeout) as response:
response.read(4096)
return response.status
def kuma_ping(cfg: Config, params: dict) -> None:
"""Push one heartbeat to the Kuma push monitor.
Kuma only reads ``?status=up|down&msg=&ping=``. There is no ``/start`` or
``/fail`` path suffix: a request to one of those still answers 200 but
records nothing, so a failed run used to leave the monitor green until its
interval expired.
"""
if not cfg.kuma_url:
return
query = urllib.parse.urlencode(params)
url = f"{cfg.kuma_url.rstrip('/')}?{query}"
try:
status = http_get(url)
log(f"kuma ping {params.get('status', 'up')} -> {status}")
except (urllib.error.URLError, OSError) as exc:
log(f"WARNING: kuma ping failed: {exc}")
def notify(cfg: Config, ok: bool, body: str) -> None:
if not (cfg.apprise_url and cfg.apprise_urls):
return
title = f"{cfg.apprise_title}: {'OK' if ok else 'FAILED'}"
try:
status = http_post_json(
cfg.apprise_url,
{"urls": cfg.apprise_urls, "title": title, "body": body},
)
log(f"apprise notify -> {status}")
except (urllib.error.URLError, OSError) as exc:
log(f"WARNING: apprise notify failed: {exc}")
# --------------------------------------------------------------------------
# helpers
# --------------------------------------------------------------------------
def human(size: float) -> str:
for unit in ("B", "KB", "MB", "GB", "TB"):
if size < 1024 or unit == "TB":
return f"{size:.1f} {unit}" if unit != "B" else f"{int(size)} B"
size /= 1024
return f"{size:.1f} TB"
def duration(seconds: float) -> str:
seconds = int(seconds)
hours, rest = divmod(seconds, 3600)
minutes, secs = divmod(rest, 60)
if hours:
return f"{hours}h {minutes}m"
if minutes:
return f"{minutes}m {secs}s"
return f"{secs}s"
def read_env_file(path: str) -> dict[str, str]:
"""Parse a KEY=VALUE file the way docker compose does (quotes stripped)."""
values: dict[str, str] = {}
try:
text = Path(path).read_text(encoding="utf-8", errors="replace")
except OSError as exc:
raise StepError("config", f"cannot read {path}: {exc}")
for raw in text.splitlines():
line = raw.strip()
if not line or line.startswith("#"):
continue
if line.startswith("export "):
line = line[len("export "):]
if "=" not in line:
continue
key, value = line.split("=", 1)
value = value.strip()
if len(value) >= 2 and value[0] == value[-1] and value[0] in "\"'":
value = value[1:-1]
values[key.strip()] = value
return values
def acquire_lock(cfg: Config):
path = Path(cfg.lock_path)
path.parent.mkdir(parents=True, exist_ok=True)
handle = path.open("w")
try:
fcntl.flock(handle, fcntl.LOCK_EX | fcntl.LOCK_NB)
except BlockingIOError:
handle.close()
return None
handle.write(f"{os.getpid()}\n")
handle.flush()
return handle
# --------------------------------------------------------------------------
# steps
# --------------------------------------------------------------------------
def preflight(cfg: Config) -> None:
storage = os.path.join(cfg.seafile_root, "seafile-data", "storage")
if not os.path.isdir(storage):
raise StepError("preflight", f"{storage} is missing (is /shared mounted?)")
try:
with os.scandir(storage) as entries:
if next(entries, None) is None:
raise StepError("preflight", f"{storage} is empty")
except OSError as exc:
raise StepError("preflight", f"cannot read {storage}: {exc}")
if not os.path.isfile(cfg.conf_env):
raise StepError("preflight", f"{cfg.conf_env} is missing")
for binary in ("restic", "mariadb-dump"):
if not shutil.which(binary):
raise StepError("preflight", f"{binary} not found in PATH")
if cfg.cold_backup and not shutil.which("docker"):
raise StepError("preflight", "COLD_BACKUP is on but docker is not installed")
# restic writes temporary packs to $TMPDIR; the container rootfs is read-only
# and /tmp is a small tmpfs, so point it at the /config volume.
for directory in (os.environ.get("TMPDIR", "/tmp"), cfg.restic_cache_dir):
try:
os.makedirs(directory, exist_ok=True)
except OSError as exc:
raise StepError("preflight", f"cannot create {directory}: {exc}")
log(f"preflight ok: {cfg.seafile_root}, {len(cfg.databases)} databases")
def seafile_ctl(cfg: Config, action: str) -> None:
script = "/opt/seafile/seafile-server-latest"
for name in ("seahub.sh", "seafile.sh"):
run(
["docker", "exec", cfg.seafile_container, f"{script}/{name}", action],
step=f"seafile-{action}",
)
def dump_databases(cfg: Config, stamp: str) -> dict:
conf = read_env_file(cfg.conf_env)
host = cfg.db_host or conf.get("SEAFILE_MYSQL_DB_HOST") or "db"
user = cfg.db_user or conf.get("SEAFILE_MYSQL_DB_USER") or "seafile"
password = cfg.db_password or conf.get("SEAFILE_MYSQL_DB_PASSWORD")
if not password:
raise StepError("db-dump", f"no database password in {cfg.conf_env}")
outdir = Path(cfg.db_dump_dir) / stamp
outdir.mkdir(parents=True, exist_ok=True)
target = outdir / "seafile-databases.sql"
cmd = ["mariadb-dump", "-h", host, "-u", user]
if not cfg.db_ssl:
# MariaDB 11.x clients require TLS by default; the seafile-mysql
# container has no TLS configured and sits on a private bridge.
cmd.append("--skip-ssl")
cmd += [
"--single-transaction",
"--quick",
"--routines",
"--events",
"--triggers",
"--add-drop-table",
"--default-character-set=utf8mb4",
"--databases", *cfg.databases,
]
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 ''}")
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)")
log(f"db dump ok: {target} ({human(size)})")
return {"path": str(target), "bytes": size, "databases": list(cfg.databases)}
def ensure_repository(cfg: Config, repository: str, password: str) -> None:
result = restic(cfg, repository, password, ["cat", "config"], capture=True, check=False)
if result.returncode == 0:
return
if result.returncode == 10:
log(f"repository {repository} does not exist; initialising")
restic(cfg, repository, password, ["init"], step="restic-init")
return
detail = (result.stderr or "").strip().splitlines()
raise StepError(
"restic",
f"cannot open {repository} (exit {result.returncode}): {detail[-1] if detail else ''}",
)
def latest_snapshot(cfg: Config, repository: str, password: str) -> dict | None:
result = restic(
cfg, repository, password,
["snapshots", "--latest", "1", "--json"],
capture=True, check=False,
)
if result.returncode != 0:
return None
try:
data = json.loads(result.stdout or "[]")
except json.JSONDecodeError:
return None
if not data:
return None
snapshot = data[-1]
return {
"id": snapshot.get("short_id") or snapshot.get("id"),
"time": snapshot.get("time"),
"paths": snapshot.get("paths"),
}
def restic_backup(cfg: Config, repository: str, password: str, stamp: str) -> dict:
paths = [cfg.seafile_root, os.path.join(cfg.db_dump_dir, stamp)]
excludes = [
os.path.join(cfg.seafile_root, "logs"),
os.path.join(cfg.seafile_root, "tmpfiles"),
os.path.join(cfg.seafile_root, "seafile-data", "httptemp"),
os.path.join(cfg.seafile_root, "seafile-data", "tmp"),
"*.log",
]
args = ["backup", *paths, "--host", cfg.restic_host, "--tag", cfg.restic_tag]
for pattern in excludes:
args += ["--exclude", pattern]
result = restic(cfg, repository, password, args, check=False, step="restic-backup")
if result.returncode == 3:
log("WARNING: restic could not read some source files (exit 3)")
if cfg.fail_on_partial:
raise StepError("restic-backup", "partial backup (exit 3) and FAIL_ON_PARTIAL is set")
elif result.returncode != 0:
raise StepError("restic-backup", f"exit {result.returncode}")
snapshot = latest_snapshot(cfg, repository, password)
if not snapshot:
raise StepError("restic-backup", "no snapshot found after backup")
log(f"snapshot {snapshot['id']} saved to {repository}")
return snapshot
def retention(cfg: Config) -> None:
today = datetime.now().weekday()
for name, repository, password in cfg.repositories():
restic(
cfg, repository, password,
[
"forget",
f"--keep-daily={cfg.keep_daily}",
f"--keep-weekly={cfg.keep_weekly}",
f"--keep-monthly={cfg.keep_monthly}",
f"--keep-yearly={cfg.keep_yearly}",
],
step=f"restic-forget-{name}",
)
if today == cfg.prune_weekday:
restic(
cfg, repository, password,
["prune", f"--max-unused={cfg.max_unused}"],
step=f"restic-prune-{name}",
)
if today == cfg.check_weekday:
restic(
cfg, repository, password,
["check", f"--read-data-subset={cfg.check_read_data}"],
step=f"restic-check-{name}",
)
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)
for stale in directories[cfg.db_dump_keep:]:
shutil.rmtree(stale, ignore_errors=True)
log(f"removed old dump directory {stale}")
# --------------------------------------------------------------------------
# main
# --------------------------------------------------------------------------
def build_body(cfg: Config, ok: bool, result: dict, elapsed: float) -> str:
lines: list[str] = []
if ok:
lines.append(f"Seafile backup OK in {duration(elapsed)}")
else:
lines.append(f"Seafile backup FAILED after {duration(elapsed)}")
lines.append(f"error: {result.get('error', 'unknown')}")
dump = result.get("dump")
if dump:
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']}")
if result.get("warnings"):
lines.append("warnings: " + "; ".join(result["warnings"]))
return "\n".join(lines)
def main() -> int:
cfg = Config()
cfg.validate()
global log
log = Log(cfg.log_path)
lock = acquire_lock(cfg)
if lock is None:
log("another run holds the lock; skipping this one")
return 0
started = time.monotonic()
stamp = datetime.now().strftime("%Y%m%dT%H%M%S")
result: dict = {"ok": False, "warnings": []}
stopped = False
log(f"seafile-backup {VERSION} starting (run {stamp})")
# A mid-run up-ping keeps the push monitor green while the run is working.
kuma_ping(cfg, {"status": "up", "msg": "backup running"})
try:
preflight(cfg)
if cfg.cold_backup:
log("cold mode: stopping seahub and seafile")
seafile_ctl(cfg, "stop")
stopped = True
result["dump"] = dump_databases(cfg, stamp)
snapshots = {}
for name, repository, password in cfg.repositories():
ensure_repository(cfg, repository, password)
snapshots[name] = restic_backup(cfg, repository, password, stamp)
result["snapshots"] = snapshots
retention(cfg)
cleanup_dumps(cfg)
result["ok"] = True
except Exception as exc: # noqa: BLE001 - top level guard, reported below
result["error"] = str(exc)
log(f"FAILED: {exc}")
finally:
if stopped:
try:
log("cold mode: starting seafile and seahub")
seafile_ctl(cfg, "start")
except Exception as exc: # noqa: BLE001
result["ok"] = False
previous = result.get("error")
result["error"] = f"{previous}; " if previous else ""
result["error"] += f"failed to restart seafile: {exc}"
log(f"FAILED to restart seafile: {exc}")
elapsed = time.monotonic() - started
body = build_body(cfg, result["ok"], result, elapsed)
if result["ok"]:
kuma_ping(cfg, {"status": "up", "msg": "OK", "ping": int(elapsed * 1000)})
log(f"finished OK in {duration(elapsed)}")
notify(cfg, True, body)
return 0
kuma_ping(cfg, {"status": "down", "msg": (result.get("error") or "failed")[:200]})
log(f"finished FAILED in {duration(elapsed)}")
notify(cfg, False, body)
return 1
if __name__ == "__main__":
sys.exit(main())