feat: tägliche datenbanksicherung

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 <noreply@anthropic.com>
This commit is contained in:
dbildhauerandClaude Opus 5.5 committed 2026-10-25 15:32:13 +01:00
1 parent 4aebac5336
commit 7fd699c6af
6 files changed
+444 -2

No files matched your search

+38
View File
@@ -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,
)
+12
View File
@@ -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
+7
View File
@@ -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
+25 -2
View File
@@ -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
+155
View File
@@ -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()