"""Restore a Grimoire backup from the command line. python -m grimoire.restore /backups/grimoire-20261015T020000Z.tar python -m grimoire.restore /backups/grimoire-20261015T020000Z.tar --yes Run it inside the Grimoire container, which already has the database settings and has migrated the schema on start. It reads the scheduled backup's tar (services/backup_file.py) or the JSON the admin download produces, and nothing limits the file's size. It does what Settings → Restore does (services/backup.py replace_from_backup): - **A new, empty instance** takes the backup as it is. - **A live instance** rolls back to a backup of its own: everything goes back to the moment the backup was taken, for every user. - A backup from another instance, or one made before backups recorded their instance, only goes into an empty instance. Without --yes it only says what would change. With --yes it first saves the current state as a backup (to the backup destination, or DATA_DIR/pre-restore), then restores. Everyone is signed out afterwards. A backup in the oldest (v1) format is copied into an empty instance with new ids instead, as before. Afterwards, restart Grimoire: search indexes are not part of a backup and are rebuilt from the restored records at startup. """ from __future__ import annotations import argparse import asyncio import json import sys from pathlib import Path from sqlalchemy import func, select def load_backup(path: Path) -> dict: """The payload in `path`, whichever of the two backup formats it is.""" from grimoire.services.backup_file import is_archive, read_archive with open(path, "rb") as f: if is_archive(f): return read_archive(f) return json.load(f) async def _account_count() -> int: from grimoire.models import async_session from grimoire.models.user import User async with async_session() as session: return (await session.execute(select(func.count()).select_from(User))).scalar_one() async def _restore_v1(payload: dict) -> int: from grimoire.services.backup import restore_full_backup accounts = await _account_count() if accounts: print( f"This database already holds {accounts} account(s). A backup in the oldest " "format is copied in with new ids rather than replacing anything, so it only " "goes into an empty instance. Start Grimoire on an empty database and run " "this again.", file=sys.stderr, ) return 3 stats = await restore_full_backup(payload) print(json.dumps({"restored": stats}, indent=2, default=str)) return 0 def _print_preview(preview: dict) -> None: taken = preview.get("exported_at") or "an unknown date" if preview["mode"] == "rollback": print(f"This rolls the whole instance back to {taken}, for every user. Anything " "made since is removed, edits since are undone, records deleted since come back.") else: print(f"This instance has no records yet; it takes the backup from {taken} as it is.") for count in preview["counts"]: print(f" {count['kind']:<24} now {count['now']:>7} after {count['after']:>7}") async def run(path: Path, *, yes: bool = False) -> int: from grimoire.models import engine from grimoire.services import backup_job from grimoire.services.backup import RestoreRefused, replace_preview from grimoire.services.backup_file import ArchiveError try: try: payload = load_backup(path) except FileNotFoundError: print(f"There is no file at {path}.", file=sys.stderr) return 2 except (ArchiveError, ValueError) as exc: print(f"{path} isn't a backup this Grimoire can read: {exc}", file=sys.stderr) return 2 if (payload.get("version") or 1) < 2: code = await _restore_v1(payload) else: try: _print_preview(await replace_preview(payload)) if not yes: print("Nothing was changed. Run it again with --yes to restore.", file=sys.stderr) return 4 result = await backup_job.rollback_to_backup(payload) except RestoreRefused as exc: print(str(exc), file=sys.stderr) return 3 safety = result["safety_backup"] print(json.dumps({"restored": result["restored"], "safety_backup": safety}, indent=2, default=str)) print(f"The state it replaced is saved as {safety['file']} in {safety['where']}.", file=sys.stderr) code = 0 if code == 0: print("Restored. Restart Grimoire so the search indexes are rebuilt; " "everyone signs in again.", file=sys.stderr) return code finally: await engine.dispose() def main(argv: list[str] | None = None) -> int: parser = argparse.ArgumentParser( prog="python -m grimoire.restore", description=( "Restore a Grimoire backup (.tar or .json): into an empty instance, or " "roll this instance back to a backup of its own." ), ) parser.add_argument("file", type=Path, help="the backup file") parser.add_argument("--yes", action="store_true", help="restore; without it, only say what would change") args = parser.parse_args(argv) return asyncio.run(run(args.file, yes=args.yes)) if __name__ == "__main__": sys.exit(main())