"""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()