add docker job runner and scheduler

This commit is contained in:
2026-07-14 19:02:40 +02:00
committed by kallweit
parent 19933d69b6
commit 8bb0cf18ad
3 changed files with 204 additions and 1 deletions
+3 -1
View File
@@ -19,7 +19,9 @@ RUN pip install --root-user-action=ignore --no-cache-dir --disable-pip-version-c
"partial-json-parser==0.2.1.1.post7" \
"sqlmodel~=0.0.33" \
"argon2-cffi~=25.1.0" \
"pypdf==6.14.2"
"pypdf==6.14.2" \
"docker~=7.1.0" \
"croniter~=6.0.0"
COPY [ "src/main", "/home" ]
COPY [ "src/data", "/data" ]
@@ -0,0 +1,196 @@
"""
Execution side of the background job runner: launches job containers as
siblings via the host's Docker daemon (mounted /var/run/docker.sock) and
runs the periodic schedule/reconcile loop.
"""
import asyncio
import logging
from datetime import datetime
from typing import Optional
import docker
from croniter import croniter
from docker.errors import NotFound
from sqlmodel import Session, select
from inse import config
from inse.database import engine
from .model import JobDefinition, JobRun, JobRunStatus, JobTriggeredBy, utcnow
logger = logging.getLogger(__name__)
settings = config.get_settings()
_client: Optional[docker.DockerClient] = None
def get_docker_client() -> docker.DockerClient:
"""Lazily create the Docker client so the service still boots (and all
other endpoints work) when no Docker daemon is reachable."""
global _client
if _client is None:
_client = docker.from_env()
return _client
def docker_reachable() -> tuple[bool, str]:
try:
get_docker_client().ping()
return True, "ok"
except Exception as error: # noqa: BLE001 - reported to the caller
return False, str(error)
def compute_next_run(schedule: str) -> datetime:
return croniter(schedule, utcnow()).get_next(datetime)
def job_environment() -> dict[str, str]:
"""Environment for the job container, mapped from the service settings.
Passed inline: sibling containers are created by the HOST daemon, so an
env *file* path would resolve on the host, not in this container."""
environment = {
"INSE_ELASTIC_URL": settings.elasticsearch_inse_url,
"INSE_ELASTIC_API_KEY": settings.elasticsearch_inse_api_key,
"INSE_LLM_BASE_URL": settings.llm_api_url,
"INSE_LLM_API_KEY": settings.llm_api_key,
"INSE_LLM_MODEL": settings.llm_model,
}
return {key: value for key, value in environment.items() if value}
def start_run(
session: Session, definition: JobDefinition, triggered_by: JobTriggeredBy
) -> JobRun:
"""Create a JobRun row and launch its container. Marks the run failed
immediately if the container can't be started (e.g. image missing)."""
run = JobRun(definition_id=definition.id, triggered_by=triggered_by)
session.add(run)
session.commit()
session.refresh(run) # need run.id for the container name
try:
container = get_docker_client().containers.run(
image=settings.background_jobs_image,
command=[definition.job.value],
environment=job_environment(),
detach=True,
name=f"background-job-{definition.job.value}-run-{run.id}",
remove=False, # reconciler reads logs + exit code, then removes it
)
run.container_id = container.id
except Exception as error: # noqa: BLE001 - incl. ImageNotFound/daemon down
run.status = JobRunStatus.FAILED
run.finished_at = utcnow()
run.logs = f"failed to start container: {error}"
session.add(run)
session.commit()
session.refresh(run)
return run
def has_running_run(session: Session, definition_id: int) -> bool:
return (
session.exec(
select(JobRun).where(
JobRun.definition_id == definition_id,
JobRun.status == JobRunStatus.RUNNING,
)
).first()
is not None
)
def schedule_due_jobs(session: Session) -> None:
now = utcnow()
scheduled = session.exec(
select(JobDefinition).where(
JobDefinition.enabled == True, # noqa: E712 - SQLModel expression
JobDefinition.schedule != None, # noqa: E711
)
).all()
for definition in scheduled:
if definition.next_run_at is None:
definition.next_run_at = compute_next_run(definition.schedule)
session.add(definition)
continue
if definition.next_run_at > now:
continue
# Simple overlap protection: skip this slot if the previous run of
# the same definition is still going.
if has_running_run(session, definition.id):
logger.info(
"Skipping '%s': previous run still running.", definition.name
)
else:
run = start_run(session, definition, JobTriggeredBy.SCHEDULE)
logger.info(
"Started scheduled run %s of '%s'.", run.id, definition.name
)
definition.next_run_at = compute_next_run(definition.schedule)
session.add(definition)
session.commit()
def reconcile_runs(session: Session) -> None:
"""Finalize runs whose container has exited: capture logs + exit code
into the JobRun row, then remove the container (the DB row is the
durable record, not the container)."""
running = session.exec(
select(JobRun).where(JobRun.status == JobRunStatus.RUNNING)
).all()
for run in running:
if not run.container_id:
continue
try:
container = get_docker_client().containers.get(run.container_id)
except NotFound:
run.status = JobRunStatus.FAILED
run.finished_at = utcnow()
run.logs = (run.logs or "") + "\n[container disappeared before reconciliation]"
session.add(run)
continue
container.reload()
if container.status in ("exited", "dead"):
exit_code = container.attrs["State"]["ExitCode"]
run.logs = container.logs().decode("utf-8", errors="replace")
run.exit_code = exit_code
run.status = (
JobRunStatus.SUCCEEDED if exit_code == 0 else JobRunStatus.FAILED
)
run.finished_at = utcnow()
session.add(run)
container.remove()
logger.info(
"Run %s finished: %s (exit %s).", run.id, run.status, exit_code
)
session.commit()
def tick() -> None:
with Session(engine) as session:
schedule_due_jobs(session)
reconcile_runs(session)
async def scheduler_loop() -> None:
logger.info(
"Background job scheduler started (tick every %ss).",
settings.background_jobs_tick_seconds,
)
while True:
try:
# Docker SDK calls are blocking -- keep them off the event loop.
await asyncio.to_thread(tick)
except Exception: # noqa: BLE001 - a failed tick must not kill the loop
logger.exception("Background job scheduler tick failed.")
await asyncio.sleep(settings.background_jobs_tick_seconds)
+5
View File
@@ -43,6 +43,11 @@ class Settings(BaseSettings):
llm_api_key: Optional[str] = None
llm_model: Optional[str] = None
# Background job runner config (Docker-out-of-Docker)
background_jobs_image: str = "docker.nes.uni-due.de/inse/background-jobs:latest"
background_jobs_scheduler_enabled: bool = True
background_jobs_tick_seconds: int = 5
# Sentence Transformers config
sentence_transformers_model_name: str = "intfloat/multilingual-e5-base"