rename(547): the server is grimoire — package, image, DB defaults, backups
CI & Build / Python lint (push) Successful in 3s
CI & Build / Plugin hooks (push) Successful in 12s
CI & Build / TypeScript typecheck (push) Successful in 56s
CI & Build / integration (push) Successful in 1m4s
CI & Build / Python tests (push) Successful in 1m55s
CI & Build / Build & push image (push) Successful in 44s
CI & Build / Python lint (push) Successful in 3s
CI & Build / Plugin hooks (push) Successful in 12s
CI & Build / TypeScript typecheck (push) Successful in 56s
CI & Build / integration (push) Successful in 1m4s
CI & Build / Python tests (push) Successful in 1m55s
CI & Build / Build & push image (push) Successful in 44s
Step 2 of the Scribe -> Grimoire rename. - src/scribe -> src/grimoire, and every import, patch target, module path, hypercorn entry point and `python -m grimoire.restore` with it; pyproject, uv.lock and the frontend package are named grimoire. - Image git.fabledsword.com/bvandeusen/fabledgrimoire; CI's Postgres service runs as grimoire / grimoire_test. - Compose files default the DB user, database and (prod) volume to grimoire, each overridable from .env, so an install created as Scribe keeps its data by setting POSTGRES_USER, POSTGRES_DB and PGDATA_VOLUME. - Backups are written as grimoire-<ts>.tar with format grimoire-backup-tar. Archives named scribe-* with the scribe-backup-tar manifest still restore and are still counted at the destination (folder and S3), with tests. - Exports, the MCP auth realm, the ASGI scope key and the persistent logger carry the new name. Kept on purpose: the secret-sealing key label stays "scribe.secrets.v1", because every stored secret was derived under it. Plugin identity (plugin name, hooks, env vars, .scribe marker, skills) is step 3. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,188 @@
|
||||
"""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 apscheduler.triggers.cron import CronTrigger
|
||||
|
||||
from grimoire.services.backup_destination import (
|
||||
DestinationError, deliver, load_config, load_secret,
|
||||
)
|
||||
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)
|
||||
|
||||
_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"),
|
||||
)
|
||||
|
||||
|
||||
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()
|
||||
Reference in New Issue
Block a user