Source code for s365b.jobs.restore

"""Restoring backed-up items into Microsoft 365.

A restore is asked for in Browse: some items, or everything in a folder (or
a whole mailbox) matching what was shown, as it was at a point in time. The
API records it as a queued job run (:func:`queue_restore`); a worker runs it
(:func:`run_restore`) with the Restore app, and the module writes the items
back. Like a backup, it shows live progress, can be stopped, is audited and
ends with a notification.

An item that was deleted by the chosen time is restored from its last
version before the deletion.
"""

from __future__ import annotations

import asyncio
import contextlib
from collections.abc import AsyncIterator, Callable
from dataclasses import dataclass
from datetime import UTC, datetime
from typing import Any, Literal

from pydantic import BaseModel, Field
from sqlalchemy import select
from sqlalchemy.dialects.postgresql import distinct_on
from sqlalchemy.ext.asyncio import AsyncSession

from s365b.core import runlog
from s365b.core.audit import audit
from s365b.core.events import emit
from s365b.core.logging import get_logger
from s365b.core.selection import at_time, in_folder, matches
from s365b.core.services import Services
from s365b.db.models import (
    AppPurpose,
    AppRegistration,
    Item,
    ItemVersionRow,
    JobRun,
    ModuleState,
    ProtectedObjectRow,
    RepositoryConfig,
    RunKind,
    RunStatus,
    Tenant,
)
from s365b.jobs.locks import repository_lock
from s365b.jobs.progress import ProgressTracker
from s365b.jobs.runner import JobSetupError
from s365b.modules.sdk import (
    BackupModule,
    ItemVersion,
    ModuleContext,
    ModuleError,
    ProtectedObject,
    RestoreRequest,
    RestoreResult,
    Severity,
    StoredItem,
)
from s365b.storage.repository import ContentRef, Repository, extra_ref

[docs] log = get_logger(__name__)
[docs] RESTORE_SUCCEEDED = "restore_succeeded"
[docs] RESTORE_WARNING = "restore_warning"
[docs] RESTORE_FAILED = "restore_failed"
[docs] RESTORE_STOPPED = "restore_stopped"
[docs] MAX_ITEMS = 10_000 # items picked one by one
[docs] class RestoreScope(BaseModel): """Which items: picked ones, or everything shown in Browse."""
[docs] object_id: int
[docs] at: datetime | None = Field(None, description="Point in time; now if not given")
[docs] item_ids: list[int] = Field( default_factory=list, max_length=MAX_ITEMS, description="Items picked one by one; when given, the filters below are ignored", )
[docs] path: str | None = Field(None, max_length=2000, description="A folder; null for all")
[docs] subfolders: bool = True
[docs] q: str = Field("", max_length=200, description="Browse's search text")
[docs] include_deleted: bool = False
[docs] class RestoreSpec(RestoreScope): """A restore: which items, into which object, where in it."""
[docs] target_object_id: int | None = Field(None, description="Another object; null for the original")
[docs] destination: Literal["original", "folder"]
[docs] folder_name: str = Field("", max_length=200)
[docs] notify: bool = Field( True, description="Email when it finishes, whatever the minimum severity for alerts" )
@dataclass(frozen=True, slots=True)
[docs] class Chosen: """An item to restore, with the version to restore."""
[docs] item: Item
[docs] version: ItemVersionRow
[docs] async def choose( s: AsyncSession, scope: RestoreScope, at: datetime, *, item_types: set[str] | None = None, limit: int | None = None, ) -> list[Chosen]: """Find the item versions a restore covers. Args: s: Session. scope: What to restore. at: The point in time. item_types: Only items of these types. limit: Read at most this many items (to refuse too many cheaply). Returns: One version per item; for items deleted by then, the last version before the deletion. """ stmt = ( select(ItemVersionRow, Item) .join(Item, Item.id == ItemVersionRow.item_fk) .where(Item.protected_object_fk == scope.object_id, at_time(at)) ) if item_types is not None: stmt = stmt.where(Item.item_type.in_(item_types)) if scope.item_ids: stmt = stmt.where(Item.id.in_(scope.item_ids)) else: if not scope.include_deleted: stmt = stmt.where(~ItemVersionRow.deleted) if scope.q.strip(): stmt = stmt.where(matches(scope.q.strip())) if scope.path is not None: stmt = stmt.where(in_folder(scope.path, subfolders=scope.subfolders)) if limit is not None: stmt = stmt.limit(limit) rows = (await s.execute(stmt)).all() chosen = {item.id: Chosen(item, v) for v, item in rows} # A deletion marker has no content: take the version it replaced. deleted = [c.item.id for c in chosen.values() if c.version.deleted] for start in range(0, len(deleted), 1000): batch = deleted[start : start + 1000] before = ( await s.execute( select(ItemVersionRow) .where( ItemVersionRow.item_fk.in_(batch), ~ItemVersionRow.deleted, ItemVersionRow.valid_from < at, ) .order_by(ItemVersionRow.item_fk, ItemVersionRow.valid_from.desc()) .ext(distinct_on(ItemVersionRow.item_fk)) ) ).scalars() for v in before: chosen[v.item_fk] = Chosen(chosen[v.item_fk].item, v) return [c for c in chosen.values() if not c.version.deleted and c.version.content]
[docs] def has_copies(version: ItemVersionRow, names: tuple[str, ...]) -> bool: """Whether a version has all the extra copies a module restores from.""" return all(extra_ref(dict(version.content or {}), n) is not None for n in names)
[docs] class Preview(BaseModel): """What a restore would do."""
[docs] items: int
[docs] bytes: int
[docs] without_copy: int = Field(description="Items backed up before restore copies were kept")
[docs] folders: int
[docs] async def preview(services: Services, scope: RestoreScope) -> Preview: """Count what a restore covers, before starting it. Args: services: Services. scope: What to restore. Returns: Counts. """ at = scope.at or datetime.now(UTC) async with services.db.session() as s: obj = await s.get(ProtectedObjectRow, scope.object_id) if obj is None: raise LookupError("no such protected object") chosen = await choose(s, scope, at) state = await s.get(ModuleState, obj.module_id) names = _copies(services, obj.module_id, state) size = 0 without = 0 for c in chosen: content = dict(c.version.content or {}) refs = [extra_ref(content, n) for n in names] if names and any(r is None for r in refs): without += 1 size += sum(r.size for r in refs if r is not None) if names else c.version.size return Preview( items=len(chosen), bytes=size, without_copy=without, folders=len({c.version.path for c in chosen}), )
def _copies(services: Services, module_id: str, state: ModuleState | None) -> tuple[str, ...]: reg = services.registry if module_id not in reg: return () config = reg.parse_config(module_id, dict(state.config) if state else None) return reg.get(module_id).extra_copies(config)
[docs] async def queue_restore( services: Services, spec: RestoreSpec, requested_by: str, *, ip: str | None = None ) -> JobRun: """Record a restore as a queued run and hand it to a worker. Args: services: Services. spec: The restore. requested_by: Username. ip: The requester's address, for the audit log. Returns: The queued run. Raises: LookupError: If an object does not exist. ValueError: If the restore is not possible as asked. """ at = spec.at or datetime.now(UTC) spec = spec.model_copy(update={"at": at, "folder_name": spec.folder_name.strip()}) async with services.db.session() as s: source = await s.get(ProtectedObjectRow, spec.object_id) if source is None: raise LookupError("no such protected object") reg = services.registry if source.module_id not in reg or not reg.get(source.module_id).supports_restore(): raise ValueError("This kind of item cannot be restored yet.") target = source if spec.target_object_id not in (None, source.id): other = await s.get(ProtectedObjectRow, spec.target_object_id) if other is None: raise LookupError("no such target") if (other.module_id, other.kind) != (source.module_id, source.kind): raise ValueError("Restore into an object of the same kind.") target = other if spec.destination == "folder" and not spec.folder_name: raise ValueError("Name the folder to restore into.") count = len(await choose(s, spec, at)) if not count: raise ValueError("Nothing to restore: no items match.") run = JobRun( kind=RunKind.RESTORE, status=RunStatus.QUEUED, requested_by=requested_by, stats={ "request": spec.model_dump(mode="json"), "source": source.display_name, "target": target.display_name, "module": source.module_id, "items": count, }, ) s.add(run) await s.flush() await audit( s, requested_by, "restore.queue", target=target.display_name, details={ "run_id": run.id, "source": source.display_name, "items": count, "at": at.isoformat(), "destination": spec.destination, "folder_name": spec.folder_name or None, }, ip=ip, ) run_id = run.id try: await services.enqueue_restore(run_id) except Exception: async with services.db.session() as s: row = await s.get(JobRun, run_id) if row is not None: row.status, row.finished_at = RunStatus.FAILED, datetime.now(UTC) row.error = "Could not hand the restore to a worker." raise async with services.db.session() as s: row = await s.get(JobRun, run_id) assert row is not None # noqa: S101 - created above return row
[docs] class Restorer: """Runs queued restores. Args: services: Process services. """
[docs] progress_interval = 3.0
def __init__(self, services: Services) -> None:
[docs] self.services = services
[docs] async def run(self, run_id: int) -> None: """Run a queued restore to the end. Never raises for problems inside it. Args: run_id: The queued run. """ db = self.services.db async with db.session() as s: run = await s.get(JobRun, run_id, with_for_update=True) if run is None or run.kind is not RunKind.RESTORE or run.status != RunStatus.QUEUED: return run.status, run.started_at = RunStatus.RUNNING, datetime.now(UTC) stats: dict[str, Any] = dict(run.stats or {}) requested_by = run.requested_by spec = RestoreSpec.model_validate(stats["request"]) runlog.for_run(run_id) bound = log.bind(run_id=run_id) stop = asyncio.Event() stopped_by: str | None = None result = RestoreResult() error: str | None = None locks = contextlib.AsyncExitStack() clients: list[Any] = [] try: tenant, restore_app, backup_app = await self._apps() source, target, module, config = await self._objects(spec) missing = sorted( module.required_permissions(config, restore=True) - set(restore_app.granted_permissions) ) if missing: raise JobSetupError( f"The Restore app has not been granted {', '.join(missing)}. Open Microsoft" " 365 tenant and click 'Update permissions and renew certificates'." ) assert spec.at is not None # noqa: S101 - set when queued async with db.session() as s: chosen = await choose(s, spec, spec.at) repo_rows = { r.id: r for r in ( await s.execute( select(RepositoryConfig).where( RepositoryConfig.id.in_({c.version.repository_fk for c in chosen}) ) ) ).scalars() } repos: dict[int, Repository] = {} for repo_id, repo_row in repo_rows.items(): # Retention may not reclaim space while the restore reads. await locks.enter_async_context(repository_lock(db, repo_id, exclusive=False)) repos[repo_id] = await self.services.open_repository(repo_row) source_obj = protected_object(source) items = [stored_item(c, source_obj, repos[c.version.repository_fk]) for c in chosen] graph = self.services.graph_for(tenant, restore_app) clients.append(graph) reader = self.services.graph_for(tenant, backup_app) if backup_app else None if reader is not None: clients.append(reader) async with ProgressTracker( db, run_id, 1, interval=self.progress_interval, stop=stop ) as tracker: tracker.start_module(module.id, module.display_name, module.object_noun, 1) tracker.set_phase("restoring") tracker.object_started(target.id, target.display_name) ctx = ModuleContext( tenant.tenant_id, config, graph, bound.bind(module=module.id, target=target.display_name), cancel=stop, progress=lambda **kw: tracker.object_progress(target.id, **kw), reader=reader, ) request = RestoreRequest( items, target=None if target.id == source.id else protected_object(target), options={"destination": spec.destination, "folder_name": spec.folder_name}, ) try: result = await module.restore(ctx, request) finally: tracker.object_finished(target.id, False) tracker.set_phase("finishing") stopped_by = tracker.stopped_by except asyncio.CancelledError: if not stop.is_set(): raise # the worker itself is shutting down # A module that stops by raising: the run is still finished below. except (JobSetupError, ModuleError, LookupError) as exc: error = str(exc) except Exception as exc: bound.exception("restore.crashed") error = f"{type(exc).__name__}: {exc}" finally: for c in clients: await c.aclose() await locks.aclose() if stop.is_set(): status = RunStatus.CANCELLED error = f"Stopped by {stopped_by or 'a user'}. What was restored before stays restored." elif error or (result.failed and not result.restored and not result.skipped): status = RunStatus.FAILED elif result.failed: status = RunStatus.WARNING else: status = RunStatus.SUCCESS stats |= { "restored": result.restored, "skipped": result.skipped, "failed": result.failed, "errors": result.errors, "folders_created": result.folders_created, } async with db.session() as s: row = await s.get(JobRun, run_id) assert row is not None # noqa: S101 - created above row.status, row.error, row.stats = status, error, stats row.finished_at = datetime.now(UTC) await audit( s, requested_by, "restore.finish", target=str(stats.get("target")), details={ "run_id": run_id, "status": status.value, "restored": result.restored, "skipped": result.skipped, "failed": result.failed, }, ) await _notify(s, run_id, status, stats, error) bound.info( "restore.finished", status=status.value, restored=result.restored, skipped=result.skipped, failed=result.failed, )
async def _apps(self) -> tuple[Tenant, AppRegistration, AppRegistration | None]: async with self.services.db.session() as s: tenant = (await s.execute(select(Tenant).order_by(Tenant.id))).scalars().first() if tenant is None: raise JobSetupError("no Microsoft 365 tenant is connected; finish setup first") apps = { a.purpose: a for a in ( await s.execute( select(AppRegistration).where(AppRegistration.tenant_fk == tenant.id) ) ).scalars() } restore_app = apps.get(AppPurpose.RESTORE) if restore_app is None: raise JobSetupError("the Restore app registration is missing; re-run tenant setup") return tenant, restore_app, apps.get(AppPurpose.BACKUP) async def _objects( self, spec: RestoreSpec ) -> tuple[ProtectedObjectRow, ProtectedObjectRow, BackupModule, BaseModel]: async with self.services.db.session() as s: source = await s.get(ProtectedObjectRow, spec.object_id) target = ( await s.get(ProtectedObjectRow, spec.target_object_id) if spec.target_object_id else source ) if source is None or target is None: raise JobSetupError("the mailbox (or other object) no longer exists in the catalog") state = await s.get(ModuleState, source.module_id) reg = self.services.registry if source.module_id not in reg: raise JobSetupError(f"the {source.module_id} module is not installed") module = reg.get(source.module_id) # A disabled module's backups stay restorable. config = reg.parse_config(source.module_id, dict(state.config) if state else None) return source, target, module, config
[docs] def protected_object(row: ProtectedObjectRow) -> ProtectedObject: """The SDK's view of a catalog object.""" return ProtectedObject(row.kind, row.external_id, row.display_name, dict(row.meta or {}))
[docs] def stored_item(c: Chosen, obj: ProtectedObject, repo: Repository) -> StoredItem: """A chosen version as the SDK's stored item, read from its repository.""" v = c.version content = dict(v.content or {}) main = ContentRef.from_json(content) extras = frozenset((content.get("extra") or {}).keys()) def read_extra(name: str) -> AsyncIterator[bytes]: ref = extra_ref(content, name) if ref is None: raise KeyError(name) return repo.get_content(ref) read: Callable[[], AsyncIterator[bytes]] = lambda: repo.get_content(main) # noqa: E731 return StoredItem( object=obj, version=ItemVersion( item_key=c.item.item_key, item_type=c.item.item_type, name=v.name, path=v.path, modified_at=v.modified_at, metadata=dict(v.meta or {}), ), read=read, extras=extras, read_extra=read_extra, size=main.size, )
async def _notify( s: AsyncSession, run_id: int, status: RunStatus, stats: dict[str, Any], error: str | None ) -> None: target = stats.get("target") body = { "source": stats.get("source"), "target": target, "restored": stats.get("restored"), "skipped": stats.get("skipped"), "failed": stats.get("failed"), "error": error, "run_id": run_id, # Asked for when the restore was started: sent even below the minimum severity. "always": bool((stats.get("request") or {}).get("notify", True)), } n = stats.get("restored", 0) if status is RunStatus.CANCELLED: kind, sev, subject = RESTORE_STOPPED, Severity.INFO, f"Restore stopped: {target}" elif status is RunStatus.FAILED: kind, sev, subject = RESTORE_FAILED, Severity.ERROR, f"Restore failed: {target}" elif status is RunStatus.WARNING: kind, sev = RESTORE_WARNING, Severity.WARNING subject = f"Restore finished with problems: {target} ({stats.get('failed')} failed)" else: kind, sev = RESTORE_SUCCEEDED, Severity.INFO subject = f"Restore finished: {n} item{'' if n == 1 else 's'} into {target}" await emit(s, kind, sev, subject, body=body, run_fk=run_id)
[docs] async def run_restore(services: Services, run_id: int) -> None: """Run a queued restore (the worker task's body). Args: services: Services. run_id: The queued run. """ await Restorer(services).run(run_id)