123 lines
3.8 KiB
Python
123 lines
3.8 KiB
Python
"""Worker process: job queue consumer plus the scheduler.
|
|
|
|
Scheduling lives here rather than in systemd timers. SPEC 3.4 makes the backup
|
|
schedule and the retention policy UI-editable server settings, and a
|
|
UI-editable timer would mean the app writing unit files and calling
|
|
``daemon-reload`` behind a polkit rule. In-app, a schedule is a settings row.
|
|
(TODO Phase 1.2.)
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import logging
|
|
import signal
|
|
import threading
|
|
from typing import Any
|
|
|
|
from apscheduler.schedulers.background import BackgroundScheduler
|
|
|
|
from ..config import get_settings
|
|
from ..db import SessionLocal
|
|
from ..logging_setup import configure_logging
|
|
from . import queue
|
|
from .handlers import HANDLERS
|
|
|
|
log = logging.getLogger(__name__)
|
|
|
|
_stop = threading.Event()
|
|
|
|
|
|
def _run_one(job: dict[str, Any]) -> None:
|
|
kind = job["kind"]
|
|
fn = HANDLERS.get(kind)
|
|
with SessionLocal() as session:
|
|
if fn is None:
|
|
queue.fail(session, job["id"], f"no handler registered for {kind!r}")
|
|
log.error("unknown job kind", extra={"kind": kind, "job_id": job["id"]})
|
|
return
|
|
try:
|
|
fn(session, job["payload"] or {})
|
|
except Exception as exc: # noqa: BLE001 - a handler must not kill the worker
|
|
session.rollback()
|
|
log.exception("job failed", extra={"kind": kind, "job_id": job["id"]})
|
|
queue.fail(session, job["id"], f"{type(exc).__name__}: {exc}")
|
|
else:
|
|
queue.complete(session, job["id"])
|
|
log.info("job done", extra={"kind": kind, "job_id": job["id"]})
|
|
|
|
|
|
def _build_scheduler() -> BackgroundScheduler:
|
|
"""Periodic work, enqueued rather than executed inline.
|
|
|
|
The scheduler only ever *enqueues*. That keeps every unit of work in one
|
|
place -- the queue -- where it is visible, retried and auditable, instead
|
|
of some jobs running inside a timer callback where a failure disappears.
|
|
"""
|
|
scheduler = BackgroundScheduler(timezone="UTC")
|
|
|
|
def _enqueue(kind: str) -> None:
|
|
with SessionLocal() as session:
|
|
queue.enqueue(session, kind)
|
|
session.commit()
|
|
|
|
scheduler.add_job(
|
|
lambda: _enqueue("prune_expired_commands"),
|
|
"interval",
|
|
minutes=15,
|
|
id="prune_expired_commands",
|
|
max_instances=1,
|
|
coalesce=True,
|
|
)
|
|
|
|
def _reclaim() -> None:
|
|
with SessionLocal() as session:
|
|
queue.requeue_stale(session)
|
|
|
|
scheduler.add_job(
|
|
_reclaim, "interval", minutes=5, id="requeue_stale", max_instances=1, coalesce=True
|
|
)
|
|
|
|
# Phase 5 adds: backup (schedule from the settings table), retention,
|
|
# restore_test (monthly).
|
|
return scheduler
|
|
|
|
|
|
def run() -> int:
|
|
settings = get_settings()
|
|
configure_logging(settings.log_level, settings.log_format)
|
|
|
|
def _handle_signal(signum: int, _frame: Any) -> None:
|
|
log.info("shutdown requested", extra={"signal": signum})
|
|
_stop.set()
|
|
|
|
signal.signal(signal.SIGTERM, _handle_signal)
|
|
signal.signal(signal.SIGINT, _handle_signal)
|
|
|
|
scheduler = _build_scheduler()
|
|
scheduler.start()
|
|
log.info(
|
|
"poorbird worker started",
|
|
extra={"worker": queue.WORKER_ID, "handlers": sorted(HANDLERS)},
|
|
)
|
|
|
|
try:
|
|
while not _stop.is_set():
|
|
try:
|
|
with SessionLocal() as session:
|
|
job = queue.claim(session)
|
|
except Exception: # noqa: BLE001 - a DB blip must not end the worker
|
|
log.exception("could not reach the database; backing off")
|
|
_stop.wait(5.0)
|
|
continue
|
|
|
|
if job is None:
|
|
_stop.wait(settings.worker_poll_interval_s)
|
|
continue
|
|
|
|
_run_one(job)
|
|
finally:
|
|
scheduler.shutdown(wait=False)
|
|
log.info("poorbird worker stopped")
|
|
|
|
return 0
|