From 7fd699c6af87592ad00b5d5dfb07501af63a22fe Mon Sep 17 00:00:00 2001 From: dbildhauer Date: Sun, 25 Oct 2026 15:32:13 +0100 Subject: [PATCH] =?UTF-8?q?feat:=20t=C3=A4gliche=20datenbanksicherung?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Konsistente Momentaufnahme per SQLite-Backup-API nach data/backups, geprüft mit PRAGMA integrity_check und komprimiert; erst eine geprüfte Datei bekommt den endgültigen Namen. Aufbewahrung 7 täglich + 4 wöchentlich, verpasste Sicherungen werden nach dem Start nachgeholt. lc-admin backup für manuelle Sicherungen, Status für Admins unter /api/admin/backup. Co-Authored-By: Claude Opus 5.5 --- backend/app/api/admin.py | 38 ++++++ backend/app/cli.py | 12 ++ backend/app/config.py | 7 ++ backend/app/main.py | 27 ++++- backend/app/services/backup.py | 155 ++++++++++++++++++++++++ backend/tests/test_backup.py | 207 +++++++++++++++++++++++++++++++++ 6 files changed, 444 insertions(+), 2 deletions(-) create mode 100644 backend/app/services/backup.py create mode 100644 backend/tests/test_backup.py diff --git a/backend/app/api/admin.py b/backend/app/api/admin.py index 67d003d..fab6c73 100644 --- a/backend/app/api/admin.py +++ b/backend/app/api/admin.py @@ -1,9 +1,14 @@ +from datetime import datetime + from fastapi import APIRouter, BackgroundTasks, HTTPException, status +from pydantic import BaseModel from app.api.deps import AdminUser, DbSession +from app.config import get_settings from app.models import User from app.schemas.auth import UserOut from app.schemas.users import UserCreate, UserUpdate +from app.services import backup as backup_service from app.services import users as user_service from app.ws.hub import hub @@ -49,3 +54,36 @@ def update_user( def delete_user(user_id: int, admin: AdminUser, db: DbSession, background: BackgroundTasks) -> None: user_service.delete_user(db, admin, _get_user_or_404(db, user_id)) background.add_task(hub.close_user, user_id) + + +class BackupFile(BaseModel): + name: str + size: int + created_at: datetime + + +class BackupStatus(BaseModel): + enabled: bool + hour: int + latest: BackupFile | None + count: int + # No backup within the last day: something is wrong (or the job is disabled) + stale: bool + last_error: str | None + + +@router.get("/backup", response_model=BackupStatus) +def backup_status(_admin: AdminUser) -> BackupStatus: + settings = get_settings() + backups = backup_service.list_backups() + latest = backups[0] if backups else None + return BackupStatus( + enabled=settings.backup_enabled, + hour=settings.backup_hour, + latest=None + if latest is None + else BackupFile(name=latest.path.name, size=latest.size, created_at=latest.created_at), + count=len(backups), + stale=backup_service.needs_catch_up(), + last_error=backup_service.last_error, + ) diff --git a/backend/app/cli.py b/backend/app/cli.py index a191554..399988b 100644 --- a/backend/app/cli.py +++ b/backend/app/cli.py @@ -7,6 +7,7 @@ import sys from app.db import _session_factory from app.models import Role +from app.services import backup as backup_service from app.services.users import UserError, create_user, get_by_username, set_password @@ -33,6 +34,14 @@ def _reset_password(args: argparse.Namespace) -> None: print(f"Passwort für '{user.username}' gesetzt, alle Sitzungen wurden beendet.") +def _backup(_args: argparse.Namespace) -> None: + try: + info = backup_service.create_backup() + except backup_service.BackupError as exc: + raise UserError(f"Sicherung fehlgeschlagen: {exc}") from exc + print(f"Sicherung geschrieben: {info.path} ({info.size:,} Bytes)".replace(",", ".")) + + def build_parser() -> argparse.ArgumentParser: parser = argparse.ArgumentParser(prog="lc-admin", description="LAN-Clipboard Verwaltung") sub = parser.add_subparsers(dest="command", required=True) @@ -49,6 +58,9 @@ def build_parser() -> argparse.ArgumentParser: p.add_argument("username") p.set_defaults(func=_reset_password) + p = sub.add_parser("backup", help="Datenbank jetzt sichern (nach /data/backups)") + p.set_defaults(func=_backup) + return parser diff --git a/backend/app/config.py b/backend/app/config.py index a9d14e6..41fd9a0 100644 --- a/backend/app/config.py +++ b/backend/app/config.py @@ -1,6 +1,7 @@ from functools import lru_cache from pathlib import Path +from pydantic import Field from pydantic_settings import BaseSettings, SettingsConfigDict @@ -35,6 +36,12 @@ class Settings(BaseSettings): # Uploads are refused when the disk would drop below this; the server is shared file_min_free_bytes: int = 2 * 1024 * 1024 * 1024 + # Daily consistent database snapshot to /data/backups (local time, see TZ) + backup_enabled: bool = True + backup_hour: int = Field(default=3, ge=0, le=23) + backup_keep_daily: int = Field(default=7, ge=1) + backup_keep_weekly: int = Field(default=4, ge=0) + initial_admin_username: str | None = None initial_admin_password: str | None = None diff --git a/backend/app/main.py b/backend/app/main.py index 182c508..e7fd4cd 100644 --- a/backend/app/main.py +++ b/backend/app/main.py @@ -1,4 +1,5 @@ import asyncio +import contextlib import logging from collections.abc import AsyncIterator from contextlib import asynccontextmanager @@ -17,6 +18,7 @@ from app.middleware import ( OriginCheckMiddleware, SecurityHeadersMiddleware, ) +from app.services import backup as backup_service from app.services import files as file_service from app.services.access import ProjectNotFound, ReadOnly from app.services.auth import delete_old_login_attempts @@ -27,6 +29,8 @@ from app.ws.hub import hub logger = logging.getLogger(__name__) CLEANUP_INTERVAL_SECONDS = 3600 +# Give the app time to start before a missed backup is caught up +BACKUP_CATCH_UP_DELAY_SECONDS = 60 def _cleanup() -> list[tuple[int, set[int]]]: @@ -79,14 +83,33 @@ def _bootstrap_admin() -> None: logger.info("INITIAL_ADMIN_* ignored: users already exist; remove them from .env.") +async def _run_backup() -> None: + # Failures are logged with traceback and shown in the admin area + with contextlib.suppress(backup_service.BackupError): + await run_in_threadpool(backup_service.create_backup) + + +async def _backup_loop() -> None: + """Daily at BACKUP_HOUR; a backup missed while the container was down is caught up.""" + await asyncio.sleep(BACKUP_CATCH_UP_DELAY_SECONDS) + if await run_in_threadpool(backup_service.needs_catch_up): + await _run_backup() + while True: + await asyncio.sleep(backup_service.seconds_until_next_run()) + await _run_backup() + + @asynccontextmanager async def lifespan(_app: FastAPI) -> AsyncIterator[None]: await run_in_threadpool(_bootstrap_admin) - task = asyncio.create_task(_cleanup_loop()) + tasks = [asyncio.create_task(_cleanup_loop())] + if get_settings().backup_enabled: + tasks.append(asyncio.create_task(_backup_loop())) try: yield finally: - task.cancel() + for task in tasks: + task.cancel() # Hashed build output never changes; everything else must be revalidated so updates arrive diff --git a/backend/app/services/backup.py b/backend/app/services/backup.py new file mode 100644 index 0000000..b81df50 --- /dev/null +++ b/backend/app/services/backup.py @@ -0,0 +1,155 @@ +"""Daily consistent snapshot of the SQLite database. + +The Proxmox Backup Server copies the host's files; a live SQLite file in WAL mode may be +caught mid-write. This job writes a consistent, verified, compressed copy to +/data/backups that the host backup then picks up. Uploaded files are write-once and are +left to the host backup (see README). +""" + +import gzip +import logging +import os +import re +import shutil +import sqlite3 +from dataclasses import dataclass +from datetime import date, datetime, timedelta +from pathlib import Path + +from app.config import get_settings + +logger = logging.getLogger(__name__) + +_NAME = re.compile(r"^app-(\d{4}-\d{2}-\d{2})\.db\.gz$") +# A backup is "due" again after this long, e.g. when the container was down at night +MAX_AGE = timedelta(hours=24) + + +class BackupError(Exception): + """The snapshot could not be created or failed verification.""" + + +@dataclass +class BackupInfo: + path: Path + day: date + size: int + created_at: datetime + + +# Result of the most recent attempt in this process, shown in the admin area +last_error: str | None = None + + +def backup_dir() -> Path: + return get_settings().data_dir / "backups" + + +def _database_path() -> Path: + return get_settings().data_dir / "app.db" + + +def list_backups() -> list[BackupInfo]: + """All backups, newest first; unrelated or temporary files are ignored.""" + directory = backup_dir() + if not directory.is_dir(): + return [] + backups = [] + for path in directory.iterdir(): + match = _NAME.match(path.name) + if match and path.is_file(): + stat = path.stat() + backups.append( + BackupInfo( + path=path, + day=date.fromisoformat(match.group(1)), + size=stat.st_size, + created_at=datetime.fromtimestamp(stat.st_mtime).astimezone(), + ) + ) + return sorted(backups, key=lambda b: b.day, reverse=True) + + +def latest_backup() -> BackupInfo | None: + backups = list_backups() + return backups[0] if backups else None + + +def _verify(path: Path) -> None: + with sqlite3.connect(path) as conn: + result = conn.execute("PRAGMA integrity_check").fetchone()[0] + if result != "ok": + raise BackupError(f"Integritätsprüfung fehlgeschlagen: {result}") + + +def create_backup(now: datetime | None = None) -> BackupInfo: + """Snapshot, verify and compress the database; a second run on the same day replaces + that day's backup. Only a verified, complete file ever gets the final name.""" + global last_error + now = now or datetime.now().astimezone() + directory = backup_dir() + directory.mkdir(parents=True, exist_ok=True) + day = now.date().isoformat() + snapshot = directory / f".app-{day}.db.tmp" + compressed = directory / f".app-{day}.db.gz.tmp" + final = directory / f"app-{day}.db.gz" + try: + snapshot.unlink(missing_ok=True) + # sqlite3 backup API: consistent copy while the app keeps writing + with sqlite3.connect(_database_path()) as source, sqlite3.connect(snapshot) as target: + source.backup(target) + _verify(snapshot) + with snapshot.open("rb") as raw, gzip.open(compressed, "wb", compresslevel=6) as out: + shutil.copyfileobj(raw, out) + os.replace(compressed, final) + except Exception as exc: + last_error = f"{now:%d.%m.%Y %H:%M}: {exc}" + compressed.unlink(missing_ok=True) + logger.exception("Backup failed") + raise BackupError(str(exc)) from exc + finally: + snapshot.unlink(missing_ok=True) + + last_error = None + removed = prune() + info = next(b for b in list_backups() if b.path == final) + logger.info( + "Backup %s written (%d bytes), %d old backups removed", final.name, info.size, removed + ) + return info + + +def prune() -> int: + """Keep the newest KEEP_DAILY backups plus the newest one of each of the KEEP_WEEKLY + calendar weeks before them; delete the rest. Returns the number deleted.""" + settings = get_settings() + backups = list_backups() + keep = {b.path for b in backups[: settings.backup_keep_daily]} + weeks: set[tuple[int, int]] = set() + for backup in backups[settings.backup_keep_daily :]: + week = backup.day.isocalendar()[:2] + if week not in weeks and len(weeks) < settings.backup_keep_weekly: + weeks.add(week) + keep.add(backup.path) + removed = 0 + for backup in backups: + if backup.path not in keep: + backup.path.unlink(missing_ok=True) + removed += 1 + return removed + + +def needs_catch_up(now: datetime | None = None) -> bool: + """True when the newest backup is missing or older than a day.""" + now = now or datetime.now().astimezone() + latest = latest_backup() + return latest is None or now - latest.created_at > MAX_AGE + + +def seconds_until_next_run(now: datetime | None = None) -> float: + """Seconds until the next BACKUP_HOUR:00 local time.""" + now = now or datetime.now().astimezone() + run = now.replace(hour=get_settings().backup_hour, minute=0, second=0, microsecond=0) + if run <= now: + run += timedelta(days=1) + return (run - now).total_seconds() diff --git a/backend/tests/test_backup.py b/backend/tests/test_backup.py new file mode 100644 index 0000000..899c344 --- /dev/null +++ b/backend/tests/test_backup.py @@ -0,0 +1,207 @@ +import gzip +import os +import sqlite3 +from datetime import date, datetime, timedelta + +import pytest + +from app import cli +from app.config import get_settings +from app.models import Role +from app.services import backup +from tests.conftest import login + + +def restore(info, tmp_path): + """Decompress a backup the way the README describes and open it.""" + target = tmp_path / "restored.db" + target.write_bytes(gzip.decompress(info.path.read_bytes())) + return sqlite3.connect(target) + + +def at(day: str, hour: int = 3) -> datetime: + return datetime.fromisoformat(f"{day}T{hour:02d}:00:00").astimezone() + + +def fake_backup(day: date, age_days: float = 0) -> None: + directory = backup.backup_dir() + directory.mkdir(parents=True, exist_ok=True) + path = directory / f"app-{day.isoformat()}.db.gz" + path.write_bytes(b"x") + stamp = datetime.now().timestamp() - age_days * 86400 + os.utime(path, (stamp, stamp)) + + +@pytest.fixture(autouse=True) +def no_last_error(): + backup.last_error = None + yield + backup.last_error = None + + +def test_backup_can_be_restored(app_env, make_user, tmp_path): + make_user("anna") + + info = backup.create_backup(at("2026-10-25")) + + assert info.path.name == "app-2026-10-25.db.gz" + assert info.size > 0 + with restore(info, tmp_path) as conn: + assert conn.execute("PRAGMA integrity_check").fetchone()[0] == "ok" + assert conn.execute("SELECT username FROM users").fetchall() == [("anna",)] + assert conn.execute("SELECT version_num FROM alembic_version").fetchone() is not None + + +def test_backup_is_a_snapshot(app_env, make_user, tmp_path): + make_user("anna") + info = backup.create_backup(at("2026-10-25")) + make_user("bert") + + with restore(info, tmp_path) as conn: + assert conn.execute("SELECT count(*) FROM users").fetchone()[0] == 1 + + +def test_second_backup_of_a_day_replaces_the_first(app_env, make_user, tmp_path): + backup.create_backup(at("2026-10-25", 3)) + make_user("anna") + info = backup.create_backup(at("2026-10-25", 14)) + + assert [b.path.name for b in backup.list_backups()] == ["app-2026-10-25.db.gz"] + with restore(info, tmp_path) as conn: + assert conn.execute("SELECT count(*) FROM users").fetchone()[0] == 1 + + +def test_failed_verification_leaves_no_backup(app_env, monkeypatch): + def broken(_path): + raise backup.BackupError("Integritätsprüfung fehlgeschlagen: page 3 corrupt") + + monkeypatch.setattr(backup, "_verify", broken) + + with pytest.raises(backup.BackupError): + backup.create_backup(at("2026-10-25")) + assert list(backup.backup_dir().iterdir()) == [] + assert "page 3 corrupt" in backup.last_error + + +def test_success_clears_last_error(app_env): + backup.last_error = "earlier failure" + backup.create_backup(at("2026-10-25")) + assert backup.last_error is None + + +def test_retention_keeps_daily_and_weekly(app_env, monkeypatch): + monkeypatch.setenv("BACKUP_KEEP_DAILY", "7") + monkeypatch.setenv("BACKUP_KEEP_WEEKLY", "4") + get_settings.cache_clear() + first = date(2026, 9, 1) + for offset in range(55): + fake_backup(first + timedelta(days=offset)) + (backup.backup_dir() / "notes.txt").write_text("not a backup") + + removed = backup.prune() + + kept = [b.day for b in backup.list_backups()] + newest = first + timedelta(days=54) # 2026-10-25, a Sunday + daily = [newest - timedelta(days=i) for i in range(7)] + assert kept[:7] == daily + # Then the newest backup of each of the 4 calendar weeks before + assert kept[7:] == [ + date(2026, 10, 18), + date(2026, 10, 11), + date(2026, 10, 4), + date(2026, 9, 27), + ] + assert removed == 55 - 11 + assert (backup.backup_dir() / "notes.txt").exists() + + +def test_needs_catch_up(app_env): + assert backup.needs_catch_up() is True + fake_backup(date.today(), age_days=0.5) + assert backup.needs_catch_up() is False + for path in backup.backup_dir().iterdir(): + path.unlink() + fake_backup(date.today() - timedelta(days=2), age_days=1.5) + assert backup.needs_catch_up() is True + + +@pytest.mark.parametrize( + ("now", "expected_hours"), + [("02:00", 1), ("03:00", 24), ("04:30", 22.5), ("23:00", 4)], +) +def test_next_run(app_env, now, expected_hours): + current = datetime.fromisoformat(f"2026-10-20T{now}:00").astimezone() + assert backup.seconds_until_next_run(current) == expected_hours * 3600 + + +def test_backup_hour_is_validated(app_env, monkeypatch): + monkeypatch.setenv("BACKUP_HOUR", "24") + get_settings.cache_clear() + with pytest.raises(ValueError): + get_settings() + + +def test_cli_backup(app_env, monkeypatch, capsys): + monkeypatch.setenv("LC_ALLOW_ROOT", "1") + assert cli.main(["backup"]) == 0 + assert "Sicherung geschrieben" in capsys.readouterr().out + assert len(backup.list_backups()) == 1 + + +def test_admin_sees_backup_status(client, make_user): + make_user("root", role=Role.ADMIN) + login(client, "root") + + status = client.get("/api/admin/backup").json() + assert status["latest"] is None + assert status["stale"] is True + assert (status["enabled"], status["hour"]) == (True, 3) + + info = backup.create_backup() + status = client.get("/api/admin/backup").json() + assert status["latest"]["name"] == info.path.name + assert status["latest"]["size"] == info.size + assert status["count"] == 1 + assert status["stale"] is False + assert status["last_error"] is None + + +def test_backup_status_is_admin_only(client, make_user): + make_user("anna") + login(client, "anna") + assert client.get("/api/admin/backup").status_code == 403 + + +def test_loop_catches_up_and_survives_failures(app_env, monkeypatch): + import asyncio + + from app import main + + calls = [] + real = backup.create_backup + loop = asyncio.new_event_loop() + done = asyncio.Event() + + def flaky(): + calls.append(len(calls)) + if len(calls) == 3: + # Runs in the thread pool; wake the test on the event loop + loop.call_soon_threadsafe(done.set) + if len(calls) == 2: + raise backup.BackupError("disk full") + return real() + + monkeypatch.setattr(main, "BACKUP_CATCH_UP_DELAY_SECONDS", 0) + monkeypatch.setattr(backup, "create_backup", flaky) + monkeypatch.setattr(backup, "seconds_until_next_run", lambda: 0.01) + + async def run_briefly(): + task = asyncio.create_task(main._backup_loop()) + await asyncio.wait_for(done.wait(), timeout=10) + task.cancel() + + loop.run_until_complete(run_briefly()) + loop.close() + # Catch-up at start, then scheduled runs; the failed second run did not stop the loop + assert len(calls) >= 3 + assert len(backup.list_backups()) == 1