Files
FabledGrimoire/src/grimoire/services/backup_job.py
T
bvandeusenandClaude Opus 5.5 1f5e963c35
CI & Build / Plugin hooks (push) Successful in 10s
CI & Build / Python lint (push) Successful in 1s
CI & Build / TypeScript typecheck (push) Successful in 32s
CI & Build / Python tests (push) Successful in 1m42s
CI & Build / integration (push) Successful in 1m48s
CI & Build / Build & push image (push) Canceled after 22s
feat(6848): Settings restore rolls back, from the destination or a file, after a preview
The web restore no longer copies a backup in beside the live data.

- GET /api/admin/restore/sources lists the backups at the backup destination,
  newest first.
- POST /api/admin/restore/preview says what a restore would do, changing
  nothing: fresh or rollback, when the backup was taken, and counts now and
  after per kind. A backup that cannot apply here gets a 409 with the reason.
- POST /api/admin/restore?confirm=rollback runs backup_job.rollback_to_backup:
  safety backup, replace, then search rebuilt in the background.

Each takes ?source=<name> (a backup at the destination) or an upload. The
destination path exists because uploads are held to the request-size limit,
and a real instance's backup is far over it. backup_s3.get_file downloads
from a bucket. backup_destination.list_backups/open_backup only accept names
the scheduled backup writes, so a request cannot reach any other file.

Settings -> Data -> Restore from Backup opens RestoreBackupDialog. The dialog:
1. Pick a backup at the destination or a file.
2. Read the preview.
3. Type "roll back".
4. Run it. The dialog then says where the replaced state was saved, and sends
   the user to sign in again.

Closes #6840. Milestone 582, step 4.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-04 20:06:07 -05:00

255 lines
9.8 KiB
Python

"""The scheduled backup: when it runs, running it, and what each run did.
ONE APScheduler job (services/scheduler.py) fires at the top of every hour and
reads the config at fire time: when backups are on and the hour is the chosen
one, it runs. Reading at fire time rather than scheduling the chosen hour
keeps the app's startup free of a database read (a lifespan hook that waits
on the database is a worker that never serves), and a changed hour
needs no reschedule.
A run exports the full backup, writes it as the dated tar
(services/backup_file.py) and delivers it (services/backup_destination.py).
Its outcome is kept as one entry in a bounded list — the newest
`KEEP_RUNS` — in the `backup_runs` admin setting, like DB maintenance keeps
its last run. A failure is logged as an error AND kept with its reason in
words, so the Settings page can say what went wrong without anyone reading
logs.
"""
from __future__ import annotations
import asyncio
import json
import logging
import os
import time
from datetime import datetime, timedelta, timezone
from pathlib import Path
from apscheduler.triggers.cron import CronTrigger
from grimoire.services.backup_destination import (
DestinationError, deliver, load_config, load_secret,
)
from grimoire.services.backup_file import write_archive
from grimoire.services.scheduler import ScheduledJob
from grimoire.services.settings import get_admin_setting, set_admin_setting
logger = logging.getLogger(__name__)
RUNS_SETTING = "backup_runs"
KEEP_RUNS = 30
# A daily backup that hasn't succeeded for this long is overdue: a day plus
# room for one slow run, so a backup that lands at 02:40 instead of 02:05
# does not flicker the page into a warning.
STALE_AFTER = timedelta(hours=26)
# The whole run's deadline, because a wait with no deadline is a bug. The
# S3 upload has its own 15-minute timeout, but a folder on a hung NFS mount
# has none, and a run that never returns holds the lock — every later backup
# would be skipped as "already running", silently, forever.
RUN_DEADLINE = timedelta(minutes=60)
# Under DATA_DIR: where a rollback keeps the backup of what it replaced when
# no backup destination takes it.
PRE_RESTORE_DIR = "pre-restore"
_LOCK = asyncio.Lock()
_TASKS: set[asyncio.Task] = set()
class BackupBusy(Exception):
"""A backup is already running."""
def is_running() -> bool:
return _LOCK.locked()
async def list_runs() -> list[dict]:
"""The kept runs, newest first."""
raw = await get_admin_setting(RUNS_SETTING, "")
try:
runs = json.loads(raw) if raw else []
except ValueError:
return []
return [r for r in runs if isinstance(r, dict)] if isinstance(runs, list) else []
async def _record(run: dict) -> None:
runs = [run, *await list_runs()][:KEEP_RUNS]
await set_admin_setting(RUNS_SETTING, json.dumps(runs))
def summarise(runs: list[dict], *, enabled: bool, now: datetime) -> dict:
"""What the page leads with: when the last good backup was, and whether
backups are overdue. Pure, so the stale rule is tested on its own."""
last_ok = next((r for r in runs if r.get("status") == "ok"), None)
last_ok_at = _parse(last_ok.get("finished_at")) if last_ok else None
if not enabled:
overdue = False
elif last_ok_at is None:
# On, and never succeeded: overdue once the first scheduled chance
# has passed. Before any run at all, there is nothing to be late for.
overdue = bool(runs)
else:
overdue = now - last_ok_at > STALE_AFTER
return {
"last_run": runs[0] if runs else None,
"last_success": last_ok,
"overdue": overdue,
}
def _parse(value) -> datetime | None:
try:
return datetime.fromisoformat(value)
except (TypeError, ValueError):
return None
async def run_backup(trigger: str) -> dict:
"""Run one backup now and keep its outcome. Raises BackupBusy when one is
already running; never raises for a failed backup — that is the outcome.
"""
if _LOCK.locked():
raise BackupBusy()
async with _LOCK:
started = datetime.now(timezone.utc)
clock = time.monotonic()
run: dict = {"started_at": started.isoformat(), "trigger": trigger}
try:
config = await load_config()
secret, _ = await load_secret()
run["destination"] = config.destination
delivered = await asyncio.wait_for(
_export_and_deliver(config, secret, started), RUN_DEADLINE.total_seconds(),
)
run.update(status="ok", file=delivered.name,
size_bytes=delivered.size_bytes, where=delivered.where)
except (TimeoutError, asyncio.TimeoutError):
run.update(status="failed", error=(
f"The backup didn't finish within {int(RUN_DEADLINE.total_seconds() // 60)} "
"minutes and was abandoned. The destination may be hanging."
))
except DestinationError as exc:
run.update(status="failed", error=str(exc))
except Exception as exc:
logger.exception("backup run failed")
run.update(status="failed", error=f"The backup failed: {exc}")
run["finished_at"] = datetime.now(timezone.utc).isoformat()
run["duration_s"] = round(time.monotonic() - clock, 1)
if run["status"] == "ok":
logger.info("backup: wrote %s (%d bytes) to %s in %.1fs",
run["file"], run["size_bytes"], run["where"], run["duration_s"])
else:
logger.error("backup: %s", run["error"])
try:
await _record(run)
except Exception:
# The backup itself is done (or failed) either way; losing its
# entry in the history must not turn into an unhandled error in a
# scheduler thread. The log line above still says what happened.
logger.exception("backup: could not keep this run in the history")
return run
async def _export_and_deliver(config, secret, started):
from grimoire.services.backup import export_full_backup
payload = await export_full_backup()
return await deliver(
payload, config, secret, started,
app_version=os.environ.get("APP_VERSION", "dev"),
)
async def save_state_before_restore() -> dict:
"""Back up the store as it is now, before a rollback replaces it, and say
where the file went: the backup destination when backups are on and it
takes the file, otherwise DATA_DIR/pre-restore. Raises when neither takes
it, so a rollback never runs without a way back."""
from grimoire.config import Config
from grimoire.services.backup import export_full_backup
at = datetime.now(timezone.utc)
app_version = os.environ.get("APP_VERSION", "dev")
payload = await export_full_backup()
note = None
config = await load_config()
if config.enabled:
secret, _ = await load_secret()
try:
delivered = await asyncio.wait_for(
deliver(payload, config, secret, at, app_version=app_version),
RUN_DEADLINE.total_seconds(),
)
return {"file": delivered.name, "size_bytes": delivered.size_bytes,
"where": delivered.where}
except (DestinationError, TimeoutError, asyncio.TimeoutError) as exc:
note = (f"The backup destination didn't take it ({exc or 'it timed out'}), "
"so it was kept on the instance instead.")
folder = Path(Config.DATA_DIR) / PRE_RESTORE_DIR
path = await asyncio.to_thread(write_archive, payload, folder, at, app_version=app_version)
saved = {"file": path.name, "size_bytes": path.stat().st_size, "where": str(folder)}
if note:
saved["note"] = note
return saved
async def rollback_to_backup(data: dict) -> dict:
"""Roll the store back to a full backup, after backing up what it
replaces. Refuses (RestoreRefused) before writing anything when the backup
can't be applied here, and raises BackupBusy while a backup is running:
a backup taken during a rollback would mix the two states."""
from grimoire.services.backup import check_replace, replace_from_backup
await check_replace(data)
if _LOCK.locked():
raise BackupBusy()
async with _LOCK:
safety = await save_state_before_restore()
result = await replace_from_backup(data)
result["safety_backup"] = safety
logger.info("rollback: the state it replaced is in %s/%s", safety["where"], safety["file"])
return result
def start_reindex_after_restore() -> None:
"""Rebuild the search vectors a rollback cleared, in the background."""
from grimoire.services.backup import reindex_after_restore
task = asyncio.get_running_loop().create_task(reindex_after_restore())
_TASKS.add(task)
task.add_done_callback(_TASKS.discard)
def start_backup_now() -> None:
"""Start a manual backup in the background (the request returns at once;
the page reads progress from `is_running` and the run list). Raises
BackupBusy rather than queueing a second run behind the first."""
if _LOCK.locked():
raise BackupBusy()
task = asyncio.get_running_loop().create_task(run_backup("manual"))
_TASKS.add(task)
task.add_done_callback(_TASKS.discard)
async def _hourly_check() -> None:
config = await load_config()
if not config.enabled or datetime.now(timezone.utc).hour != config.hour:
return
try:
await run_backup("scheduled")
except BackupBusy:
logger.info("backup: a run is already going; the scheduled one is skipped")
_JOB = ScheduledJob("backup_hourly_check", _hourly_check, label="Backup")
def start_backup_scheduler(loop: asyncio.AbstractEventLoop) -> None:
_JOB.start(loop, CronTrigger(minute=0, timezone="UTC"),
describe="hourly; runs at the configured UTC hour")
def stop_backup_scheduler() -> None:
_JOB.stop()