From 5ce97e6854e4affeac37005376c7100574411342 Mon Sep 17 00:00:00 2001 From: louis-19041904 Date: Sun, 12 Jul 2026 20:02:45 +0200 Subject: [PATCH] add superadmin background job endpoints and scheduler --- .../src/main/inse/background_jobs/model.py | 34 ++- .../src/main/inse/background_jobs/router.py | 108 +++++++++ .../src/main/inse/background_jobs/service.py | 208 ++++++++++++++++++ service/src/main/inse/main.py | 14 ++ service/src/main/inse/tags.py | 1 + 5 files changed, 364 insertions(+), 1 deletion(-) create mode 100644 service/src/main/inse/background_jobs/router.py create mode 100644 service/src/main/inse/background_jobs/service.py diff --git a/service/src/main/inse/background_jobs/model.py b/service/src/main/inse/background_jobs/model.py index ffaaa066..fae504a0 100644 --- a/service/src/main/inse/background_jobs/model.py +++ b/service/src/main/inse/background_jobs/model.py @@ -1,11 +1,12 @@ """ -Database tables for the background job runner. +Database tables and API schemas for the background job runner. """ from datetime import datetime, timezone from enum import StrEnum from typing import Optional +from pydantic import BaseModel from sqlmodel import Field, SQLModel @@ -79,3 +80,34 @@ class JobRun(SQLModel, table=True): description="Captured stdout/stderr, filled in when the run finishes " "(the container itself is removed afterwards).", ) + + +class JobDefinitionUpdateRequest(BaseModel): + + schedule: Optional[str] = None + enabled: Optional[bool] = None + + +class BackgroundJobTask(BaseModel): + id: int + name: str + description: str + target_index: str + job: BackgroundJobName + image: str + schedule: Optional[str] + enabled: bool + next_run_at: Optional[datetime] + last_run: Optional[JobRun] + status: str + + +class JobRunLogs(BaseModel): + run_id: int + status: JobRunStatus + logs: str + + +class DockerHealth(BaseModel): + reachable: bool + detail: str diff --git a/service/src/main/inse/background_jobs/router.py b/service/src/main/inse/background_jobs/router.py new file mode 100644 index 00000000..046a09f2 --- /dev/null +++ b/service/src/main/inse/background_jobs/router.py @@ -0,0 +1,108 @@ +from fastapi import APIRouter, Depends, Query +from sqlmodel import Session + +from inse.auth import service as auth_service +from inse.auth.model import AccessTokenMetadata +from inse.database import get_session +from inse.tags import Tags + +from . import service +from .model import ( + BackgroundJobTask, + DockerHealth, + JobDefinitionUpdateRequest, + JobRun, + JobRunLogs, +) + +router = APIRouter(prefix="/api/background-jobs", tags=[Tags.BACKGROUND_JOBS]) + + +@router.get( + "/tasks", + operation_id="getBackgroundJobTasks", + response_model=list[BackgroundJobTask], +) +async def get_tasks( + session: Session = Depends(get_session), + access_token: AccessTokenMetadata = auth_service.CurrentUserAccessTokenPayloadDep, +) -> list[BackgroundJobTask]: + return service.get_tasks(session, access_token) + + +@router.patch( + "/tasks/{task_id}", + operation_id="updateBackgroundJobTask", + response_model=BackgroundJobTask, +) +async def update_task( + task_id: int, + payload: JobDefinitionUpdateRequest, + session: Session = Depends(get_session), + access_token: AccessTokenMetadata = auth_service.CurrentUserAccessTokenPayloadDep, +) -> BackgroundJobTask: + return service.update_task(session, access_token, task_id, payload) + + +@router.post( + "/tasks/{task_id}/run", + operation_id="runBackgroundJobTask", + response_model=JobRun, +) +async def run_task( + task_id: int, + session: Session = Depends(get_session), + access_token: AccessTokenMetadata = auth_service.CurrentUserAccessTokenPayloadDep, +) -> JobRun: + return service.trigger_run(session, access_token, task_id) + + +@router.get( + "/tasks/{task_id}/runs", + operation_id="getBackgroundJobTaskRuns", + response_model=list[JobRun], +) +async def get_task_runs( + task_id: int, + limit: int = Query(default=20, ge=1, le=100), + session: Session = Depends(get_session), + access_token: AccessTokenMetadata = auth_service.CurrentUserAccessTokenPayloadDep, +) -> list[JobRun]: + return service.get_task_runs(session, access_token, task_id, limit) + + +@router.get( + "/runs/{run_id}/logs", + operation_id="getBackgroundJobRunLogs", + response_model=JobRunLogs, +) +async def get_run_logs( + run_id: int, + session: Session = Depends(get_session), + access_token: AccessTokenMetadata = auth_service.CurrentUserAccessTokenPayloadDep, +) -> JobRunLogs: + return service.get_run_logs(session, access_token, run_id) + + +@router.post( + "/runs/{run_id}/stop", + operation_id="stopBackgroundJobRun", + response_model=JobRun, +) +async def stop_run( + run_id: int, + session: Session = Depends(get_session), + access_token: AccessTokenMetadata = auth_service.CurrentUserAccessTokenPayloadDep, +) -> JobRun: + return service.stop_run(session, access_token, run_id) + + +@router.get( + "/docker-health", + operation_id="getBackgroundJobsDockerHealth", + response_model=DockerHealth, +) +async def docker_health( + access_token: AccessTokenMetadata = auth_service.CurrentUserAccessTokenPayloadDep, +) -> DockerHealth: + return service.docker_health(access_token) diff --git a/service/src/main/inse/background_jobs/service.py b/service/src/main/inse/background_jobs/service.py new file mode 100644 index 00000000..a2b2180b --- /dev/null +++ b/service/src/main/inse/background_jobs/service.py @@ -0,0 +1,208 @@ +""" +Business logic for the background job endpoints. Every function checks the +caller's access token first: background jobs start containers on the host, +so nothing here may ever be reachable for non-superadmins. +""" + +import logging + +from croniter import croniter +from fastapi import HTTPException, status +from sqlmodel import Session, col, select + +from inse import config +from inse.auth.model import AccessTokenMetadata, UserRole + +from . import runner +from .model import ( + BackgroundJobTask, + DockerHealth, + JobDefinition, + JobDefinitionUpdateRequest, + JobRun, + JobRunLogs, + JobRunStatus, + JobTriggeredBy, +) + +logger = logging.getLogger(__name__) + +settings = config.get_settings() + + +def _require_super_admin(access_token: AccessTokenMetadata) -> None: + if access_token.effective_role != UserRole.SUPER_ADMIN: + raise HTTPException( + status_code=status.HTTP_403_FORBIDDEN, + detail="Only superadmins can manage background jobs.", + ) + + +def _get_definition(session: Session, definition_id: int) -> JobDefinition: + definition = session.get(JobDefinition, definition_id) + if not definition: + raise HTTPException( + status_code=status.HTTP_404_NOT_FOUND, + detail=f"Unknown background job task id {definition_id}.", + ) + return definition + + +def _get_run(session: Session, run_id: int) -> JobRun: + run = session.get(JobRun, run_id) + if not run: + raise HTTPException( + status_code=status.HTTP_404_NOT_FOUND, + detail=f"Unknown background job run id {run_id}.", + ) + return run + + +def _last_run(session: Session, definition_id: int) -> JobRun | None: + return session.exec( + select(JobRun) + .where(JobRun.definition_id == definition_id) + .order_by(col(JobRun.id).desc()) + ).first() + + +def _to_task(session: Session, definition: JobDefinition) -> BackgroundJobTask: + last_run = _last_run(session, definition.id) + if last_run is None: + derived_status = "idle" + elif last_run.status == JobRunStatus.RUNNING: + derived_status = "running" + else: + derived_status = last_run.status.value + return BackgroundJobTask( + id=definition.id, + name=definition.name, + description=definition.description, + target_index=definition.target_index, + job=definition.job, + image=settings.background_jobs_image, + schedule=definition.schedule, + enabled=definition.enabled, + next_run_at=definition.next_run_at, + last_run=last_run, + status=derived_status, + ) + + +def get_tasks( + session: Session, access_token: AccessTokenMetadata +) -> list[BackgroundJobTask]: + _require_super_admin(access_token) + definitions = session.exec( + select(JobDefinition).order_by(col(JobDefinition.id)) + ).all() + return [_to_task(session, definition) for definition in definitions] + + +def update_task( + session: Session, + access_token: AccessTokenMetadata, + definition_id: int, + payload: JobDefinitionUpdateRequest, +) -> BackgroundJobTask: + _require_super_admin(access_token) + changes = payload.model_dump(exclude_unset=True) + if changes.get("schedule") is not None and not croniter.is_valid( + changes["schedule"] + ): + raise HTTPException( + status_code=status.HTTP_422_UNPROCESSABLE_ENTITY, + detail=f"Invalid cron expression: '{changes['schedule']}'.", + ) + + definition = _get_definition(session, definition_id) + for key, value in changes.items(): + setattr(definition, key, value) + if "schedule" in changes or "enabled" in changes: + definition.next_run_at = ( + runner.compute_next_run(definition.schedule) + if definition.enabled and definition.schedule + else None + ) + session.add(definition) + session.commit() + session.refresh(definition) + return _to_task(session, definition) + + +def trigger_run( + session: Session, access_token: AccessTokenMetadata, definition_id: int +) -> JobRun: + _require_super_admin(access_token) + definition = _get_definition(session, definition_id) + if runner.has_running_run(session, definition.id): + raise HTTPException( + status_code=status.HTTP_409_CONFLICT, + detail=f"'{definition.name}' is already running.", + ) + return runner.start_run(session, definition, JobTriggeredBy.MANUAL) + + +def get_task_runs( + session: Session, + access_token: AccessTokenMetadata, + definition_id: int, + limit: int, +) -> list[JobRun]: + _require_super_admin(access_token) + _get_definition(session, definition_id) + return session.exec( + select(JobRun) + .where(JobRun.definition_id == definition_id) + .order_by(col(JobRun.id).desc()) + .limit(limit) + ).all() + + +def get_run_logs( + session: Session, access_token: AccessTokenMetadata, run_id: int +) -> JobRunLogs: + """Live from the container while running; from the database once finished.""" + _require_super_admin(access_token) + run = _get_run(session, run_id) + if run.status == JobRunStatus.RUNNING and run.container_id: + try: + container = runner.get_docker_client().containers.get(run.container_id) + return JobRunLogs( + run_id=run_id, + status=run.status, + logs=container.logs().decode("utf-8", errors="replace"), + ) + except Exception: # noqa: BLE001 + pass # container may have just exited; fall through to stored logs + return JobRunLogs(run_id=run_id, status=run.status, logs=run.logs or "") + + +def stop_run( + session: Session, access_token: AccessTokenMetadata, run_id: int +) -> JobRun: + """Stops the container; the scheduler's next reconcile pass records the + final status, logs, and exit code.""" + _require_super_admin(access_token) + run = _get_run(session, run_id) + if run.status != JobRunStatus.RUNNING or not run.container_id: + raise HTTPException( + status_code=status.HTTP_409_CONFLICT, + detail=f"Run {run_id} is not running.", + ) + try: + runner.get_docker_client().containers.get(run.container_id).stop() + except Exception as error: # noqa: BLE001 + raise HTTPException( + status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, + detail=f"Failed to stop container: {error}", + ) + # The run stays "running" here on purpose: the next reconcile pass sees + # the exited container, captures its logs + exit code and removes it. + return run + + +def docker_health(access_token: AccessTokenMetadata) -> DockerHealth: + _require_super_admin(access_token) + reachable, detail = runner.docker_reachable() + return DockerHealth(reachable=reachable, detail=detail) diff --git a/service/src/main/inse/main.py b/service/src/main/inse/main.py index b4d12eec..1b0eacea 100644 --- a/service/src/main/inse/main.py +++ b/service/src/main/inse/main.py @@ -6,6 +6,7 @@ for fastapi that loads the service and the webapp. """ +import asyncio from contextlib import asynccontextmanager, contextmanager import logging @@ -43,6 +44,8 @@ from inse.bookmarks.router import router as bookmarks_router from inse.institutions.router import router as institutions_router from inse.database import create_db_and_tables, get_session from inse.auth.service import create_predefined_accounts +from inse.background_jobs.router import router as background_jobs_router +from inse.background_jobs.runner import scheduler_loop as background_jobs_scheduler_loop from inse.background_jobs.seed import create_predefined_job_definitions from . import config @@ -71,7 +74,17 @@ async def lifespan(app: FastAPI): with contextmanager(get_session)() as session: create_predefined_accounts(session, "../data/predefined_accounts.json") create_predefined_job_definitions(session) + + background_jobs_scheduler_task = None + if settings.background_jobs_scheduler_enabled: + background_jobs_scheduler_task = asyncio.create_task( + background_jobs_scheduler_loop() + ) + yield + + if background_jobs_scheduler_task is not None: + background_jobs_scheduler_task.cancel() logger.info("Shutting down the application...") @@ -110,6 +123,7 @@ app.include_router(works_v2_router) app.include_router(dashboard_router) app.include_router(bookmarks_router) +app.include_router(background_jobs_router) app.add_middleware( ETagCacheMiddleware, diff --git a/service/src/main/inse/tags.py b/service/src/main/inse/tags.py index a5411f63..a7690f85 100644 --- a/service/src/main/inse/tags.py +++ b/service/src/main/inse/tags.py @@ -15,3 +15,4 @@ class Tags(StrEnum): ORGANIZATION = "Organization" UNIVERSITY_RANKINGS = "University Rankings" DASHBOARD = "Dashboard" + BACKGROUND_JOBS = "Background Jobs"