"""Running backup jobs.
:class:`JobRunner` contains the logic; :mod:`s365b.jobs.tasks` only wraps it
in Procrastinate tasks. Keeping them apart lets tests run jobs directly.
"""
from __future__ import annotations
import asyncio
import contextlib
from dataclasses import replace
from datetime import UTC, datetime
from typing import Any
from croniter import croniter
from sqlalchemy import select
from s365b.core import runlog
from s365b.core.catalog import Catalog, VersionStats
from s365b.core.concurrency import all_or_cancel
from s365b.core.engine import BackupEngine, ObjectResult
from s365b.core.events import JOB_FAILED, JOB_STOPPED, JOB_SUCCEEDED, JOB_WARNING, emit
from s365b.core.logging import get_logger
from s365b.core.services import Services
from s365b.db.models import (
AppPurpose,
AppRegistration,
BackupJob,
JobRun,
ModuleState,
ProtectedObjectRow,
RepositoryConfig,
RunKind,
RunStatus,
Tenant,
)
from s365b.jobs.liveness import live_run
from s365b.jobs.locks import repository_lock
from s365b.jobs.progress import ProgressTracker
from s365b.modules.sdk import BackupModule, ModuleContext, ProtectedObject, Severity
[docs]
log = get_logger(__name__)
[docs]
class JobSetupError(Exception):
"""A job cannot start (no tenant connected, repository missing…)."""
[docs]
def selected(
rows: list[ProtectedObjectRow], rules: dict[str, Any] | None
) -> list[ProtectedObjectRow]:
"""Apply a job's include/exclude rules for one module.
Rules: ``{"include": "all" | [external_id, ...], "exclude": [external_id, ...]}``.
No rules means everything.
Args:
rows: Discovered objects.
rules: The module's selection rules from the job.
Returns:
The objects to back up.
"""
rules = rules or {}
include = rules.get("include", "all")
exclude = set(rules.get("exclude", []))
return [
r
for r in rows
if (include == "all" or r.external_id in include) and r.external_id not in exclude
]
[docs]
def is_due(schedule: str, at: datetime) -> bool:
"""Return whether a cron schedule fires at the given minute.
Args:
schedule: Cron expression, e.g. ``"0 22 * * *"``.
at: The minute to test.
Returns:
True if the schedule matches.
"""
return bool(croniter.match(schedule, at.replace(second=0, microsecond=0)))
[docs]
def copies_warning(missing: int, error: str | None) -> str:
"""The warning for items without a restore copy (an extra copy).
Args:
missing: Current items without the copy.
error: Why the last attempt stopped, if it failed.
Returns:
A sentence for the run details and the alert email.
"""
text = (
f"{missing} item{'s have' if missing != 1 else ' has'} no restore copy yet, so"
f" {'they' if missing != 1 else 'it'} cannot be restored into Microsoft 365 from"
" here (the backup itself is complete). The next backup tries again."
)
return f"{text} {error}" if error else text
[docs]
class JobRunner:
"""Executes backup jobs.
Args:
services: Process services.
"""
# Seconds between progress saves (which is also how quickly a stop
# request is noticed).
[docs]
progress_interval = 3.0
def __init__(self, services: Services) -> None:
[docs]
self.services = services
[docs]
async def run_backup_job(self, job_id: int, *, requested_by: str = "scheduler") -> int:
"""Run one backup job to completion.
Never raises for problems inside the job: they are recorded on the
job run and as events.
Args:
job_id: Backup job ID.
requested_by: Who started it (``scheduler`` or a username).
Returns:
The job run ID.
"""
db = self.services.db
async with db.session() as s:
# Lock the job row so two runs starting together see each other.
await s.execute(select(BackupJob.id).where(BackupJob.id == job_id).with_for_update())
other = await live_run(s, job_id)
now = datetime.now(UTC)
run = JobRun(
job_fk=job_id,
kind=RunKind.BACKUP,
status=RunStatus.CANCELLED if other else RunStatus.RUNNING,
requested_by=requested_by,
started_at=now,
finished_at=now if other else None,
error=(
f"Skipped: run {other.id} of this job was still running." if other else None
),
progress={"phase": "done"} if other else {},
)
s.add(run)
await s.flush()
run_id = run.id
runlog.for_run(run_id)
bound = log.bind(job_id=job_id, run_id=run_id)
if other:
bound.info("job.skipped_overlap", running_run=other.id)
return run_id
stop = asyncio.Event()
stopped_by: str | None = None
total = VersionStats()
per_object: list[dict[str, Any]] = []
error: str | None = None
job_name = f"job {job_id}"
locks = contextlib.AsyncExitStack()
try:
job, tenant, app, repo_row, enabled = await self._load(job_id)
job_name = job.name
self.check_permissions(job, app, enabled)
# Shared: other backups may write too, but retention may not
# reclaim space meanwhile. Opened after locking, so the index is
# current.
await locks.enter_async_context(repository_lock(db, repo_row.id, exclusive=False))
repo = await self.services.open_repository(repo_row)
engine = BackupEngine(db, repo, repo_row.id)
graph = self.services.graph_for(tenant, app)
try:
async with ProgressTracker(
db, run_id, len(job.modules), interval=self.progress_interval, stop=stop
) as tracker:
for module_id in job.modules:
if stop.is_set():
break
if module_id not in self.services.registry or module_id not in enabled:
per_object.append({"module": module_id, "error": "module not enabled"})
continue
module = self.services.registry.get(module_id)
config = self.services.registry.parse_config(module_id, enabled[module_id])
ctx = ModuleContext(
tenant.tenant_id,
config,
graph,
bound.bind(module=module_id),
cancel=stop,
)
results = await self._run_module(
module, ctx, tenant.id, job, engine, run_id, tracker
)
found: dict[str, list[dict[str, str]]] = {}
for row, res in results:
total.add(res.stats)
for change, version in res.changes:
event_id = module.change_event(version.item_type, change, version)
if event_id:
found.setdefault(event_id, []).append(
{
"change": change,
"name": version.name,
"path": version.path,
"area": row.display_name,
}
)
entry: dict[str, Any] = {
"module": module_id,
"object": row.display_name,
"error": res.error,
} | res.stats.as_dict()
if res.extras_missing and not res.error:
entry["copies_missing"] = res.extras_missing
entry["warning"] = copies_warning(
res.extras_missing, res.extras_error
)
per_object.append(entry)
await self._emit_changes(module, found, run_id)
tracker.finish_module()
tracker.set_phase("finishing")
stopped_by = tracker.stopped_by
finally:
await graph.aclose()
except JobSetupError as exc:
error = str(exc)
except Exception as exc:
bound.exception("job.crashed")
error = f"{type(exc).__name__}: {exc}"
finally:
await locks.aclose()
failures = [o for o in per_object if o.get("error")]
warnings = [o for o in per_object if o.get("warning")]
if stop.is_set():
status = RunStatus.CANCELLED
error = f"Stopped by {stopped_by or 'a user'}. What was stored is kept."
elif error or (per_object and len(failures) == len(per_object)):
status = RunStatus.FAILED
elif failures or warnings:
status = RunStatus.WARNING
else:
status = RunStatus.SUCCESS
async with db.session() as s:
run_row = await s.get(JobRun, run_id)
assert run_row is not None # noqa: S101 - created above
run_row.status = status
run_row.finished_at = datetime.now(UTC)
run_row.error = error
run_row.stats = {"totals": total.as_dict(), "objects": per_object}
await self._emit_result(
s, job_id, job_name, run_id, status, error, failures + warnings, total
)
bound.info("job.finished", status=status.value, **total.as_dict())
return run_id
async def _run_module(
self,
module: BackupModule,
ctx: ModuleContext,
tenant_fk: int,
job: BackupJob,
engine: BackupEngine,
run_id: int,
tracker: ProgressTracker,
) -> list[tuple[ProtectedObjectRow, ObjectResult]]:
"""Discover, estimate and back up one module's selected objects.
Up to ``module.parallel_objects`` objects run at the same time.
"""
db = self.services.db
tracker.set_phase("discovering")
tracker.module, tracker.module_name = module.id, module.display_name
objects = [o async for o in module.discover(ctx)]
async with db.session() as s:
rows = await Catalog(s).sync_objects(tenant_fk, module.id, objects, datetime.now(UTC))
chosen = selected(rows, job.selection.get(module.id))
tracker.start_module(module.id, module.display_name, module.object_noun, len(chosen))
limit = asyncio.Semaphore(max(1, module.parallel_objects))
def for_object(row: ProtectedObjectRow) -> ModuleContext:
return replace(
ctx,
log=ctx.log.bind(object=row.display_name),
progress=lambda **kw: tracker.object_progress(row.id, **kw),
)
tracker.set_phase("estimating")
async def estimate(row: ProtectedObjectRow) -> int | None:
async with limit:
async with db.session() as s:
state = await Catalog(s).state_for(row.id, engine.repository_fk, module)
obj = ProtectedObject(row.kind, row.external_id, row.display_name, dict(row.meta))
try:
return await module.estimate(for_object(row), obj, state)
except Exception as exc:
ctx.log.info("job.estimate_failed", object=row.display_name, error=str(exc))
return None
if ctx.cancel.is_set():
return []
counts = await all_or_cancel(estimate(r) for r in chosen)
tracker.set_estimates({r.id: c for r, c in zip(chosen, counts, strict=True)})
tracker.set_phase("backing_up")
async def one(row: ProtectedObjectRow) -> tuple[ProtectedObjectRow, ObjectResult] | None:
async with limit:
if ctx.cancel.is_set():
return None # stopped before this object started
tracker.object_started(row.id, row.display_name)
res = await engine.backup_object(
module,
for_object(row),
row,
run_fk=run_id,
on_stats=lambda st: tracker.object_stats(row.id, st),
)
tracker.object_finished(row.id, bool(res.error))
return row, res
done = await all_or_cancel(one(r) for r in chosen)
return [d for d in done if d is not None]
[docs]
def check_permissions(
self, job: BackupJob, app: AppRegistration, enabled: dict[str, dict[str, Any]]
) -> None:
"""Fail early if the Backup app lacks permissions the job's modules need.
Without this every protected object fails with the same 403.
Args:
job: The job.
app: The Backup app registration.
enabled: Raw configs of the enabled modules.
Raises:
JobSetupError: Naming the missing permissions and the fix.
"""
reg = self.services.registry
configs = {
m: reg.parse_config(m, enabled[m]) for m in job.modules if m in reg and m in enabled
}
optional = {p for m, c in configs.items() for p in reg.get(m).optional_permissions(c)}
missing = sorted(
set(reg.required_permissions(configs, restore=False))
- set(app.granted_permissions)
- optional
)
if missing:
raise JobSetupError(
f"The Backup app has not been granted {', '.join(missing)}. Open Microsoft 365"
" tenant and click 'Update permissions and renew certificates' (a Global"
" Administrator signs in once)."
)
async def _load(
self, job_id: int
) -> tuple[BackupJob, Tenant, AppRegistration, RepositoryConfig, dict[str, dict[str, Any]]]:
async with self.services.db.session() as s:
job = await s.get(BackupJob, job_id)
if job is None:
raise JobSetupError(f"backup job {job_id} does not exist")
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")
app = (
await s.execute(
select(AppRegistration).where(
AppRegistration.tenant_fk == tenant.id,
AppRegistration.purpose == AppPurpose.BACKUP,
)
)
).scalar_one_or_none()
if app is None:
raise JobSetupError("the Backup app registration is missing; re-run tenant setup")
repo_row = await s.get(RepositoryConfig, job.repository_fk)
if repo_row is None:
raise JobSetupError(f"repository {job.repository_fk} does not exist")
enabled = {
m.module_id: dict(m.config)
for m in (await s.execute(select(ModuleState).where(ModuleState.enabled))).scalars()
}
return job, tenant, app, repo_row, enabled
async def _emit_changes(
self, module: BackupModule, found: dict[str, list[dict[str, str]]], run_id: int
) -> None:
"""Record one alert per module event type, listing the changed items."""
if not found:
return
types = {t.id: t for t in module.event_types()}
async with self.services.db.session() as s:
for event_id, items in found.items():
et = types.get(event_id)
if et is None:
log.warning("module.unknown_event", module=module.id, event_id=event_id)
continue
count = len(items)
await emit(
s,
f"{module.id}.{event_id}",
et.default_severity,
f"{module.display_name}: {et.label} ({count} item{'' if count == 1 else 's'})",
body={"items": items[:500]},
run_fk=run_id,
)
@staticmethod
async def _emit_result(
s: Any,
job_id: int,
job_name: str,
run_id: int,
status: RunStatus,
error: str | None,
failures: list[dict[str, Any]],
total: VersionStats,
) -> None:
body = {"job": job_name, "run_id": run_id, "error": error, "failures": failures[:50]} | {
"totals": total.as_dict()
}
if status is RunStatus.CANCELLED:
await emit(
s,
JOB_STOPPED,
Severity.INFO,
f"Backup stopped: {job_name}",
body=body,
run_fk=run_id,
)
elif status is RunStatus.FAILED:
await emit(
s,
JOB_FAILED,
Severity.ERROR,
f"Backup failed: {job_name}",
body=body,
dedup_key=f"job_failed:{job_id}",
run_fk=run_id,
)
elif status is RunStatus.WARNING:
await emit(
s,
JOB_WARNING,
Severity.WARNING,
f"Backup finished with warnings: {job_name}"
+ (f" ({n} failed)" if (n := sum(1 for f in failures if f.get("error"))) else ""),
body=body,
dedup_key=f"job_warning:{job_id}",
run_fk=run_id,
)
else:
await emit(
s,
JOB_SUCCEEDED,
Severity.INFO,
f"Backup succeeded: {job_name}",
body=body,
run_fk=run_id,
)
[docs]
async def due_jobs(self, at: datetime) -> list[int]:
"""Return the IDs of enabled jobs whose schedule fires at ``at``.
Args:
at: The minute being scheduled (server time zone).
Returns:
Job IDs.
"""
async with self.services.db.session() as s:
jobs = (await s.execute(select(BackupJob).where(BackupJob.enabled))).scalars().all()
due = []
for job in jobs:
try:
if is_due(job.schedule, at):
due.append(job.id)
except (ValueError, KeyError):
log.error("job.bad_schedule", job_id=job.id, schedule=job.schedule)
return due
[docs]
async def discover_objects(services: Services, module_id: str) -> list[ProtectedObjectRow]:
"""Discover a module's objects in the tenant now and update the catalog.
Args:
services: Process services.
module_id: The module.
Returns:
The discovered objects.
Raises:
JobSetupError: If no tenant or Backup app is set up.
"""
async with 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")
app = (
await s.execute(
select(AppRegistration).where(
AppRegistration.tenant_fk == tenant.id,
AppRegistration.purpose == AppPurpose.BACKUP,
)
)
).scalar_one_or_none()
if app is None:
raise JobSetupError("the Backup app registration is missing; re-run tenant setup")
state = await s.get(ModuleState, module_id)
module = services.registry.get(module_id)
config = services.registry.parse_config(module_id, dict(state.config) if state else None)
graph = services.graph_for(tenant, app)
try:
ctx = ModuleContext(tenant.tenant_id, config, graph, log.bind(module=module_id))
objects = [o async for o in module.discover(ctx)]
finally:
await graph.aclose()
async with services.db.session() as s:
return await Catalog(s).sync_objects(tenant.id, module_id, objects, datetime.now(UTC))