"""Procrastinate tasks and the worker app.
There is no separate scheduler process: Procrastinate workers run periodic
tasks themselves, and a database lock makes sure each tick runs once even
with several workers. Every minute, :func:`scheduler_tick` queues the backup
jobs whose cron schedule is due.
"""
from __future__ import annotations
from datetime import datetime
from zoneinfo import ZoneInfo
import procrastinate
from s365b.core import runlog
from s365b.core.config import Settings, get_settings
from s365b.core.logging import get_logger
from s365b.core.services import Services
from s365b.jobs.liveness import reap_stale_runs
from s365b.jobs.runner import JobRunner
[docs]
log = get_logger(__name__)
[docs]
tasks = procrastinate.Blueprint()
_services: Services | None = None
[docs]
def services() -> Services:
"""Return this worker's services, created on first use.
Returns:
The services.
"""
global _services
if _services is None:
_services = Services.from_settings(get_settings())
return _services
@tasks.task(name="run_backup_job", queue="backup", pass_context=False)
[docs]
async def run_backup_job(job_id: int, requested_by: str = "scheduler") -> int:
"""Run a backup job (queued by the scheduler or the UI).
Args:
job_id: Backup job ID.
requested_by: Who started it.
Returns:
The job run ID.
"""
try:
return await JobRunner(services()).run_backup_job(job_id, requested_by=requested_by)
finally:
await runlog.finish(services().db) # the whole log, ready to download
@tasks.task(name="run_restore", queue="restore", pass_context=False)
[docs]
async def run_restore(run_id: int) -> int:
"""Run a restore queued from Browse.
Args:
run_id: The queued job run.
Returns:
The job run ID.
"""
from s365b.jobs.restore import run_restore as restore
try:
await restore(services(), run_id)
finally:
await runlog.finish(services().db)
return run_id
@tasks.periodic(cron="* * * * *", periodic_id="scheduler_tick")
@tasks.task(name="scheduler_tick", queue="scheduler", pass_context=False)
[docs]
async def scheduler_tick(timestamp: int) -> list[int]:
"""Queue backup jobs whose schedule is due this minute.
A queueing lock per job prevents a second run from being queued while one
is still waiting.
Args:
timestamp: The scheduled minute (Unix time), from Procrastinate.
Returns:
IDs of jobs queued.
"""
svc = services()
for run_id in await reap_stale_runs(svc.db):
log.warning("job.run_interrupted", run_id=run_id)
at = datetime.fromtimestamp(timestamp, ZoneInfo(svc.settings.timezone))
queued = []
for job_id in await JobRunner(svc).due_jobs(at):
try:
await run_backup_job.configure(queueing_lock=f"backup-job-{job_id}").defer_async(
job_id=job_id
)
queued.append(job_id)
except procrastinate.exceptions.AlreadyEnqueued:
pass
return queued
[docs]
RETENTION_RETRY_MINUTES = 30
[docs]
RETENTION_MAX_ATTEMPTS = 12 # keep trying for six hours, then wait for tomorrow
@tasks.task(name="run_retention", queue="backup", pass_context=False)
[docs]
async def run_retention(
repository_id: int, requested_by: str = "scheduler", attempt: int = 1
) -> int:
"""Apply a repository's retention policy (nightly, or from the UI).
If a backup is writing to the repository, the run is recorded as
skipped and retried 30 minutes later.
Args:
repository_id: Repository row ID.
requested_by: Who started it.
attempt: Retry counter.
Returns:
The job run ID.
"""
from s365b.jobs.retention import run_retention as apply
try:
run_id, skipped = await apply(services(), repository_id, requested_by=requested_by)
finally:
await runlog.finish(services().db)
if skipped and attempt < RETENTION_MAX_ATTEMPTS:
await run_retention.configure(
schedule_in={"minutes": RETENTION_RETRY_MINUTES},
queueing_lock=f"retention-{repository_id}-retry",
).defer_async(repository_id=repository_id, requested_by=requested_by, attempt=attempt + 1)
return run_id
@tasks.periodic(cron="0 * * * *", periodic_id="retention_tick")
@tasks.task(name="retention_tick", queue="scheduler", pass_context=False)
[docs]
async def retention_tick(timestamp: int) -> list[int]:
"""At the configured hour, queue retention for every repository.
Also deletes audit log entries and alerts past their retention.
Args:
timestamp: The scheduled hour (Unix time), from Procrastinate.
Returns:
IDs of repositories queued.
"""
from sqlalchemy import select
from s365b.core import settings_store
from s365b.db.models import RepositoryConfig
from s365b.jobs.retention import HousekeepingSettings, purge_records
svc = services()
at = datetime.fromtimestamp(timestamp, ZoneInfo(svc.settings.timezone))
async with svc.db.session() as s:
cfg = await settings_store.load(s, HousekeepingSettings)
repo_ids = list((await s.execute(select(RepositoryConfig.id))).scalars())
if at.hour != cfg.run_hour:
return []
log.info("housekeeping.purged", **await purge_records(svc))
queued = []
for repo_id in repo_ids:
try:
await run_retention.configure(queueing_lock=f"retention-{repo_id}").defer_async(
repository_id=repo_id
)
queued.append(repo_id)
except procrastinate.exceptions.AlreadyEnqueued:
pass
return queued
_apps: dict[str, procrastinate.App] = {}
@tasks.periodic(cron="* * * * *", periodic_id="deliver_notifications")
@tasks.task(name="deliver_notifications", queue="scheduler", pass_context=False)
[docs]
async def deliver_notifications(timestamp: int) -> dict[str, int]:
"""Email the events that are due (every minute).
Args:
timestamp: The scheduled minute (Unix time), from Procrastinate.
Returns:
Count of events per outcome.
"""
from s365b.notify.delivery import deliver_pending
return await deliver_pending(services())
[docs]
def build_app(settings: Settings) -> procrastinate.App:
"""Return the Procrastinate app for this database (one per process).
``add_tasks_from`` renames the blueprint's tasks in place, so building a
second app would turn ``s365b:run_backup_job`` into
``s365b:s365b:run_backup_job``, a task no worker knows. The app is
therefore built once and reused.
Args:
settings: Process settings.
Returns:
The app (open it with ``open_async`` before use).
"""
conninfo = settings.libpq_url()
app = _apps.get(conninfo)
if app is None:
app = procrastinate.App(connector=procrastinate.PsycopgConnector(conninfo=conninfo))
app.add_tasks_from(tasks, namespace="s365b")
_apps[conninfo] = app
return app