diff --git a/.dockerignore b/.dockerignore index eacd59e..877cb3e 100644 --- a/.dockerignore +++ b/.dockerignore @@ -1,12 +1,8 @@ -.gitignore -Dockerfile -LICENSE -*.md -.drone.yml -.env -*.log -*.conf -*tests* -*dest* -*db* -*pycache* \ No newline at end of file +.git +.gitea +.github +*.md +.env +*.log +__pycache__ +*.pyc diff --git a/.drone.yml b/.drone.yml deleted file mode 100644 index 492d575..0000000 --- a/.drone.yml +++ /dev/null @@ -1,35 +0,0 @@ -kind: pipeline -name: default -steps: -- name: docker - image: plugins/docker - settings: - registry: git.jonb.io - dry_run: false - username: jblu - password: - from_secret: gittea_drone - repo: git.jonb.io/jblu/seafile-backup - tags: - - latest - when: - branch: - - main - event: - - push -- name: docker-test - image: plugins/docker - settings: - registry: git.jonb.io - dry_run: false - username: jblu - password: - from_secret: gittea_drone - repo: git.jonb.io/jblu/seafile-backup - tags: - - dev - when: - branch: - - dev* - event: - - push \ No newline at end of file diff --git a/.gitea/workflows/docker.yml b/.gitea/workflows/docker.yml new file mode 100644 index 0000000..09d4b96 --- /dev/null +++ b/.gitea/workflows/docker.yml @@ -0,0 +1,30 @@ +name: ci + +on: + push: + branches: + - main + workflow_dispatch: + +jobs: + docker: + runs-on: ubuntu-latest + steps: + - name: Checkout + uses: actions/checkout@v4 + - name: Login to the registry + uses: docker/login-action@v4 + with: + registry: git.jonb.io + username: '${{ gitea.actor }}' + password: '${{ secrets.JONBIO_CI }}' + - name: Set up Docker Buildx + uses: docker/setup-buildx-action@v4 + - name: Build and push + uses: docker/build-push-action@v7 + with: + context: . + push: true + tags: | + git.jonb.io/jblu/seafile-backup:latest + git.jonb.io/jblu/seafile-backup:${{ gitea.sha }} diff --git a/AppriseClient.py b/AppriseClient.py deleted file mode 100644 index 179a8d3..0000000 --- a/AppriseClient.py +++ /dev/null @@ -1,39 +0,0 @@ -import requests as r -from tomllib import load -import os - -def apprise_notify(req_obj, apprise_url, aurls, title, body): - payload = {'urls': aurls,'title': title,'body': body,} - apprise_response = req_obj.post(apprise_url, json = payload ,verify=False) - return apprise_response - -class AppriseClient: - def __init__(self): - self.config = '' - try: - if os.environ["DOCKER"]: - self.host = os.environ["host"] - self.port = os.environ["port"] - self.aurls = os.environ["aurls"] - self.title = os.environ["title"] - self.body = os.environ["body"] - if os.environ["toml_path"]: - config_file_path=os.environ["toml_path"] - with open(config_file_path, 'rb') as c: - self.config = load(c) - except: - KeyError - if os.path.exists('./config.toml'): - config_file_path = './config.toml' - with open(config_file_path, 'rb') as c: - self.config = load(c) - if self.config: - self.host = self.config["apprise"]["host"] - self.port = self.config["apprise"]["port"] - self.aurls = self.config["apprise"]["aurls"] - self.title = self.config["apprise"]["title"] - self.body = self.config["apprise"]["body"] - self.apprise_response = apprise_notify(r,self.host,self.port,self.aurls,self.title,self.body) - -if __name__ == "__main__": - AppriseClient() \ No newline at end of file diff --git a/Dockerfile b/Dockerfile index 7d393d2..876f3ff 100644 --- a/Dockerfile +++ b/Dockerfile @@ -1,7 +1,25 @@ -FROM python:alpine3.18 -RUN apk add --no-cache mariadb-client rclone supercronic docker restic zip -COPY . opt -RUN chmod +x /opt/entrypoint.sh -RUN chmod +x /opt/restic.sh -RUN pip install requests python-dotenv -CMD ["/opt/entrypoint.sh"] \ No newline at end of file +FROM python:3.13-alpine + +# mariadb-client -> mariadb-dump +# restic -> the backup engine +# docker-cli -> only used when COLD_BACKUP=true (docker exec into seafile) +# supercronic -> cron with passthrough logs +RUN apk add --no-cache \ + mariadb-client \ + restic \ + docker-cli \ + supercronic \ + tzdata \ + && adduser -u 99 -D -G users -h /config -s /sbin/nologin backup + +COPY seafile-backup.py /usr/local/bin/seafile-backup +COPY entrypoint.sh /usr/local/bin/entrypoint.sh +RUN chmod 0755 /usr/local/bin/seafile-backup /usr/local/bin/entrypoint.sh + +ENV HOME=/tmp \ + PYTHONUNBUFFERED=1 \ + PYTHONDONTWRITEBYTECODE=1 + +USER 99:100 + +ENTRYPOINT ["/usr/local/bin/entrypoint.sh"] diff --git a/HealthchecksIO.py b/HealthchecksIO.py deleted file mode 100644 index a0cd5cb..0000000 --- a/HealthchecksIO.py +++ /dev/null @@ -1,6 +0,0 @@ -def healthcheck_ping(req_obj, url): - try: - req_obj.get(url, timeout=5) - except req_obj.RequestException as e: - # Log ping failure here... - print("Ping failed: %s" % e) \ No newline at end of file diff --git a/README.md b/README.md index 2117b50..fa2cd37 100644 --- a/README.md +++ b/README.md @@ -1,12 +1,80 @@ -# seafile-backup - -backup seafile data and mariadb database - -for restic -need 'RESTIC_REPOSITORY' environmental variable -need 'AWS_ACCESS_KEY_ID' environmental variable -need 'AWS_SECRET_ACCESS_KEY' environmental variable - -[![Build Status](https://drone.jonb.io/api/badges/jblu/seafile-backup/status.svg)](https://drone.jonb.io/jblu/seafile-backup) - -![seafile-backup](https://thunder.jonb.io/b/3/9507d221-6b6f-4627-b211-45c3668221cb.svg) \ No newline at end of file +# seafile-backup + +Online backup of a Seafile CE stack (Seafile 12+) to [restic](https://restic.net/). + +Seafile keeps running for the whole backup: + +* the database dump uses `--single-transaction`, so it is a consistent InnoDB + snapshot taken while seahub is serving; +* the block store (`seafile-data/storage`) is content-addressed and immutable + once written, so restic can read it while Seafile writes new blocks. + +A cold mode (`COLD_BACKUP=true`) stops seahub/seafile around the run for +pre-upgrade snapshots. It is off by default and needs `/var/run/docker.sock`. + +## What a run does + +1. Takes an exclusive lock (a second run exits immediately). +2. Pings the Uptime Kuma push monitor with `/start`. +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`. +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. +7. Deletes dump directories older than `DB_DUMP_KEEP`. +8. Pings Kuma with the result and sends an Apprise notification. + +Any failure exits non-zero, pings `/fail` and sends a failure notification. + +## Environment + +| Variable | Default | Meaning | +|---|---|---| +| `SEAFILE_ROOT` | `/shared/seafile` | Seafile data root inside the container | +| `SEAFILE_CONF_ENV` | `/shared/seafile/conf/.env` | source of the DB credentials | +| `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 | +| `LOG_PATH` | `/config/seafile-backup.log` | log file (rotated at 10 MB) | +| `RESTIC_REPOSITORY` | *required* | primary restic repository | +| `RESTIC_PASSWORD` | *required* | primary repository password | +| `LOCAL_RESTIC_REPOSITORY` | unset | optional second (local) repository | +| `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 | +| `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` | +| `CHECK_READ_DATA_SUBSET` | `5%` | how much data `restic check` re-reads | +| `PRUNE_MAX_UNUSED` | `5%` | `restic prune --max-unused` | +| `KUMA_PUSH_URL` | unset | Uptime Kuma push URL | +| `APPRISE_URL` / `APPRISE_URLS` | unset | Apprise endpoint and targets | +| `COLD_BACKUP` | `false` | stop Seafile around the run | +| `SEAFILE_CONTAINER` | `seafile` | container to stop in cold mode | +| `FAIL_ON_PARTIAL` | `false` | treat restic exit 3 as a failure | +| `CRON` | `0 3 * * *` | supercronic schedule | + +`AWS_ACCESS_KEY_ID` / `AWS_SECRET_ACCESS_KEY` are read by restic itself for the +`s3:` backend. + +## Restore + +```sh +restic restore latest --target /restore +# then, against an empty MariaDB 10.11: +mariadb -h -u root -p < /restore/config/db//seafile-databases.sql +``` + +The dump is written with `--add-drop-table`, so it can also be replayed over an +existing database. + +## Build + +```sh +docker build -t git.jonb.io/jblu/seafile-backup:latest . +``` diff --git a/entrypoint.sh b/entrypoint.sh index 4d53e71..9918d14 100644 --- a/entrypoint.sh +++ b/entrypoint.sh @@ -1,7 +1,12 @@ #!/bin/sh +set -eu -CRON_CONFIG_FILE="/opt/crontab" +: "${CRON:=0 3 * * *}" -echo "${CRON} python /opt/seafile-backup.py" > $CRON_CONFIG_FILE +# /opt is read-only when the container runs with read_only: true, so the +# generated crontab lives on the tmpfs. +CRON_CONFIG_FILE=/tmp/crontab -exec supercronic -passthrough-logs -quiet $CRON_CONFIG_FILE \ No newline at end of file +printf '%s /usr/local/bin/seafile-backup\n' "$CRON" > "$CRON_CONFIG_FILE" + +exec supercronic -passthrough-logs -quiet "$CRON_CONFIG_FILE" diff --git a/restic.sh b/restic.sh deleted file mode 100644 index 1bdf9aa..0000000 --- a/restic.sh +++ /dev/null @@ -1,38 +0,0 @@ -#!/bin/ash -: "${RESTIC_REPOSITORY:?Need the restic repository}" -: "${AWS_ACCESS_KEY_ID:?Need the access key id}" -: "${AWS_SECRET_ACCESS_KEY:?Need the secret access key}" -: "${RESTIC_PASSWORD:?Need the restic password}" -: "${LOG_PATH:-./restic-backup.log}" -: "${seafile_data_local:-/seafile}" - -# need to securely provide password: https://restic.readthedocs.io/en/latest/faq.html#how-can-i-specify-encryption-passwords-automatically -restic snapshots > /dev/null || restic init - -#Define a timestamp function -timestamp() { -date "+%b %d %Y %T %Z" -} - -# insert timestamp into log -printf "\n\n" -echo "-------------------------------------------------------------------------------" | tee -a $LOG_PATH -echo "$(timestamp): restic-backup.sh started" | tee -a $LOG_PATH - -# Run Backups -restic backup $seafile_data_local | tee -a $LOG_PATH - -# Remove snapshots according to policy -# If run cron more frequently, might add --keep-hourly 24 -restic forget --keep-daily 7 --keep-weekly 4 --keep-monthly 12 --keep-yearly 7 | tee -a $LOG_PATH - -# Remove unneeded data from the repository -restic prune | tee -a $LOG_PATH - -# Check the repository for errors -restic check | tee -a $LOG_PATH - -# insert timestamp into log -printf "\n\n" -echo "-------------------------------------------------------------------------------" | tee -a $LOG_PATH -echo "$(timestamp): restic-backup.sh finished" | tee -a $LOG_PATH \ No newline at end of file diff --git a/seafile-backup.py b/seafile-backup.py index e5e5103..4157118 100644 --- a/seafile-backup.py +++ b/seafile-backup.py @@ -1,141 +1,636 @@ -import os -from datetime import datetime -from dotenv import load_dotenv -from AppriseClient import apprise_notify -from HealthchecksIO import healthcheck_ping -import requests as r -import subprocess -now = datetime.now() -r.packages.urllib3.disable_warnings() - -load_dotenv() - -def to_bool(value): - """ - Converts 'something' to boolean. Raises exception for invalid formats - Possible True values: 1, True, "1", "TRue", "yes", "y", "t" - Possible False values: 0, False, "0", "faLse", "no", "n", "f" - """ - if str(value).lower() in ("yes", "y", "true", "t", "1"): return True - if str(value).lower() in ("no", "n", "false", "f", "0"): return False - raise Exception('Invalid value for boolean conversion: ' + str(value) + \ - f'\nPossible True values: 1, True, "1", "TRue", "yes", "y", "t"\ - \nPossible False values: 0, False, "0", "faLse", "no", "n", "f"') - -# switches -docker_command = to_bool(os.getenv("docker_command")) -rclone_copy = to_bool(os.getenv("rclone_copy")) -rclone_config_create = to_bool(os.getenv("rclone_config_create")) -rclone_push = to_bool(os.getenv("rclone_push")) -restic_push = to_bool(os.getenv("restic_push")) -db_dump = to_bool(os.getenv("db_dump")) -zip_db_files = to_bool(os.getenv("zip_db_files")) -offload_db_files = to_bool(os.getenv("offload_db_files")) -cleanup = to_bool(os.getenv("cleanup")) -healthcheck = to_bool(os.getenv("healthcheck")) -notify = to_bool(os.getenv("notify")) - -LOG_PATH = os.getenv("LOG_PATH") - -# docker -container_name = os.getenv("container_name") - -# data folders -seafile_data_local = os.getenv("seafile_data_local") -seafile_data_backup = os.getenv("seafile_data_backup") - -# databases -databases = os.getenv("databases") -db_dump_host = os.getenv("db_dump_host") -db_dump_user = os.getenv("db_dump_user") -db_dump_password = os.getenv("db_dump_password") -db_dump_tmp_path = os.getenv("db_dump_tmp_path") - -# Rclone remote -rclone_config_path = os.getenv("rclone_config_path") -rclone_remote = os.getenv("rclone_remote") -rclone_backend = os.getenv("rclone_backend") -rclone_provider = os.getenv("rclone_provider") -rclone_endpoint = os.getenv("rclone_endpoint") -rclone_remote_path = os.getenv("rclone_remote_path") -rclone_remote_db_path = os.getenv("rclone_remote_db_path") -rclone_environment_auth = os.getenv("rclone_environment_auth") -rclone_db_retention = os.getenv("rclone_db_retention") - -# Restic remote -RESTIC_REPOSITORY = os.getenv("RESTIC_REPOSITORY") -AWS_ACCESS_KEY_ID = os.getenv("AWS_ACCESS_KEY_ID") -AWS_SECRET_ACCESS_KEY = os.getenv("AWS_SECRET_ACCESS_KEY") -RESTIC_PASSWORD = os.getenv("RESTIC_PASSWORD") - -# healthchecks -healthcheck_url = os.getenv("healthcheck_url") - -# notify -apprise_apprise_url = os.getenv("apprise_apprise_url") -apprise_aurls = os.getenv("apprise_aurls") -apprise_title = os.getenv("apprise_title") -apprise_body = os.getenv("apprise_body") - -# healthcheck - Tell healthchecks.io we are starting the backup -if healthcheck: - healthcheck_ping(r, healthcheck_url.rstrip("/") + "/start") - -# Stop seafile and seafile hub -if docker_command: - os.system(f'docker exec {container_name} /opt/seafile/seafile-serverlatest/seahub.sh stop') - os.system(f'docker exec {container_name} /opt/seafile/seafile-server-latest/seafile.sh stop') - -# Dump the databases -if db_dump: - if not os.path.exists(db_dump_tmp_path): - os.system(f"mkdir -p {db_dump_tmp_path}") - for database in databases.split(','): - os.system(f'mariadb-dump -h {db_dump_host} -u {db_dump_user} -p{db_dump_password} --skip-opt\ - {database} > {db_dump_tmp_path}{database}.{now.strftime("%m-%d-%Y_%H-%M-%S")}.sql') - -# Create the config -if rclone_config_create: - rclone_config_check = str(subprocess.check_output(["rclone", "config", "file"])) - if "doesn't exist" in rclone_config_check: - os.system(f"rclone config create {rclone_remote} {rclone_backend} provider={rclone_provider}\ - endpoint={rclone_endpoint} env_auth=true") - -# Local rclone backup -if rclone_copy: - os.system(f'rclone sync -P {seafile_data_local} {seafile_data_backup}') - -# Remote rclone backup -if rclone_push: - os.system(f'rclone sync -P {seafile_data_local} {rclone_remote}:{rclone_remote_path}') - -# Remote restic backup -if restic_push: - os.system("/opt/restic.sh") - -# Start seafile and seafile hub -if docker_command: - os.system(f'docker exec {container_name} /opt/seafile/seafile-server-latest/seafile.sh start') - os.system(f'docker exec {container_name} /opt/seafile/seafile-server-latest/seahub.sh start') - -# compress db files -if zip_db_files: - os.system(f'zip -r {db_dump_tmp_path}/sfdb_{now.strftime("%m-%d-%Y_%H-%M-%S")} {db_dump_tmp_path}') - os.system(f'rm {db_dump_tmp_path}*.sql') - -# offload db file -if offload_db_files: - os.system(f'rclone copy -P {db_dump_tmp_path} {rclone_remote}:{rclone_remote_db_path}') - -# cleanup -if cleanup: - os.system(f'rm {db_dump_tmp_path}*sfdb_*') - os.system(f'rclone delete -P {rclone_db_retention} {rclone_remote}:{rclone_remote_db_path}') - -# healthcheck -if healthcheck: - healthcheck_ping(r, healthcheck_url) - -# notification -if notify: - apprise_notify(r, apprise_apprise_url, apprise_aurls, apprise_title, apprise_body) \ No newline at end of file +#!/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, pings the Kuma push + monitor with ``/fail`` 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.0" +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, suffix: str = "", params: dict | None = None) -> None: + if not cfg.kuma_url: + return + url = cfg.kuma_url.rstrip("/") + suffix + if params: + query = urllib.parse.urlencode(params) + url = f"{url}?{query}" + try: + status = http_get(url) + log(f"kuma ping {url} -> {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})") + kuma_ping(cfg, "/start") + + 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, "/fail", {"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())