sqlite3-Verbindungen werden ausdrücklich geschlossen (der Kontextmanager beendet nur die Transaktion). Die Kopie wird vor dem Komprimieren aus dem geerbten WAL-Modus in eine einzelne Datei überführt; -wal/-shm-Reste werden immer entfernt. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
168 lines
5.5 KiB
Python
168 lines
5.5 KiB
Python
"""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 contextlib import closing
|
|
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:
|
|
# closing(): sqlite3's own context manager only ends the transaction
|
|
with closing(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 _remove_snapshot(snapshot: Path) -> None:
|
|
for suffix in ("", "-wal", "-shm", "-journal"):
|
|
Path(f"{snapshot}{suffix}").unlink(missing_ok=True)
|
|
|
|
|
|
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:
|
|
_remove_snapshot(snapshot)
|
|
# sqlite3 backup API: consistent copy while the app keeps writing
|
|
with (
|
|
closing(sqlite3.connect(_database_path())) as source,
|
|
closing(sqlite3.connect(snapshot)) as target,
|
|
):
|
|
source.backup(target)
|
|
# The copy inherits WAL mode; switch back so everything is in one file
|
|
target.execute("PRAGMA journal_mode=DELETE")
|
|
_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:
|
|
_remove_snapshot(snapshot)
|
|
|
|
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()
|