From 4e0afc12edb3bea76cbeb5d56e2f6994ec4a9d59 Mon Sep 17 00:00:00 2001 From: louis-19041904 Date: Thu, 23 Jul 2026 12:03:33 +0200 Subject: [PATCH] feat(jobs): select image from a Nexus autocomplete --- .../src/main/inse/background_jobs/model.py | 7 +- .../src/main/inse/background_jobs/router.py | 12 ++ .../src/main/inse/background_jobs/runner.py | 65 +++++++++-- .../src/main/inse/background_jobs/service.py | 26 ++++- webapp/src/app/api/.openapi-generator/FILES | 1 + .../src/app/api/api/backgroundJobs.service.ts | 106 ++++++++++++++++++ webapp/src/app/api/model/availableImages.ts | 14 +++ webapp/src/app/api/model/backgroundJobTask.ts | 2 +- webapp/src/app/api/model/models.ts | 1 + .../task-create-dialog.component.html | 18 ++- .../task-create-dialog.component.ts | 43 ++++++- .../task-edit-dialog.component.html | 18 ++- .../task-edit-dialog.component.ts | 45 ++++++-- 13 files changed, 323 insertions(+), 35 deletions(-) create mode 100644 webapp/src/app/api/model/availableImages.ts diff --git a/service/src/main/inse/background_jobs/model.py b/service/src/main/inse/background_jobs/model.py index 880218c1..0cc7d37e 100644 --- a/service/src/main/inse/background_jobs/model.py +++ b/service/src/main/inse/background_jobs/model.py @@ -114,7 +114,7 @@ class BackgroundJobTask(BaseModel): name: str description: str target_index: str - image: str + image: Optional[str] command: Optional[str] env: dict[str, str] schedule: Optional[str] @@ -133,3 +133,8 @@ class JobRunLogs(BaseModel): class DockerHealth(BaseModel): reachable: bool detail: str + + +class AvailableImages(BaseModel): + images: list[str] + detail: str = "" diff --git a/service/src/main/inse/background_jobs/router.py b/service/src/main/inse/background_jobs/router.py index e6d76bff..4a3b7d41 100644 --- a/service/src/main/inse/background_jobs/router.py +++ b/service/src/main/inse/background_jobs/router.py @@ -8,6 +8,7 @@ from inse.tags import Tags from . import service from .model import ( + AvailableImages, BackgroundJobTask, DockerHealth, JobDefinitionCreateRequest, @@ -126,6 +127,17 @@ async def stop_run( return service.stop_run(session, access_token, run_id) +@router.get( + "/available-images", + operation_id="getBackgroundJobAvailableImages", + response_model=AvailableImages, +) +async def get_available_images( + access_token: AccessTokenMetadata = auth_service.CurrentUserAccessTokenPayloadDep, +) -> AvailableImages: + return service.get_available_images(access_token) + + @router.get( "/docker-health", operation_id="getBackgroundJobsDockerHealth", diff --git a/service/src/main/inse/background_jobs/runner.py b/service/src/main/inse/background_jobs/runner.py index ff6d9c9a..89a1c8f8 100644 --- a/service/src/main/inse/background_jobs/runner.py +++ b/service/src/main/inse/background_jobs/runner.py @@ -10,6 +10,7 @@ from threading import RLock from typing import Optional import docker +import httpx from croniter import croniter from docker.errors import NotFound from sqlalchemy import update as sa_update @@ -62,8 +63,53 @@ def job_environment() -> dict[str, str]: return {key: value for key, value in environment.items() if value} -def resolve_image(definition: JobDefinition) -> str: - return definition.image or settings.background_jobs_image +def registry_host() -> str: + return settings.background_jobs_image.split("/", 1)[0] + + +REGISTRY_IMAGE_LIMIT = 500 + + +def list_registry_images() -> tuple[list[str], str]: + username = settings.background_jobs_registry_username + password = settings.background_jobs_registry_password + if not username or not password: + return [], "registry credentials are not configured" + + host = registry_host() + base = f"https://{host}" + try: + with httpx.Client(timeout=10.0, auth=(username, password)) as client: + catalog = client.get( + f"{base}/v2/_catalog", params={"n": REGISTRY_IMAGE_LIMIT} + ) + catalog.raise_for_status() + repositories = catalog.json().get("repositories", []) or [] + + images: list[str] = [] + for repository in repositories: + try: + response = client.get(f"{base}/v2/{repository}/tags/list") + response.raise_for_status() + tags = response.json().get("tags") or [] + except Exception: # noqa: BLE001 + tags = [] + if tags: + images.extend(f"{host}/{repository}:{tag}" for tag in tags) + else: + images.append(f"{host}/{repository}") + return sorted(images), "" + except Exception as error: # noqa: BLE001 + logger.warning("Could not list registry images.", exc_info=True) + return [], str(error) + + +def resolve_image(definition: JobDefinition) -> Optional[str]: + return definition.image or None + + +def is_registry_image(image: Optional[str]) -> bool: + return bool(image) and image.split("/", 1)[0] == registry_host() def resolve_command(definition: JobDefinition): @@ -71,11 +117,7 @@ def resolve_command(definition: JobDefinition): def resolve_environment(definition: JobDefinition) -> dict[str, str]: - base = ( - job_environment() - if resolve_image(definition) == settings.background_jobs_image - else {} - ) + base = job_environment() if is_registry_image(resolve_image(definition)) else {} return {**base, **(definition.env or {})} @@ -112,6 +154,15 @@ def start_run( session.refresh(run) image = resolve_image(definition) + if not image: + run.status = JobRunStatus.FAILED + run.finished_at = utcnow() + run.logs = "No image configured for this job." + session.add(run) + session.commit() + session.refresh(run) + return run + try: if settings.background_jobs_pull_before_run: pull_image(image) diff --git a/service/src/main/inse/background_jobs/service.py b/service/src/main/inse/background_jobs/service.py index 4522f19c..581557d9 100644 --- a/service/src/main/inse/background_jobs/service.py +++ b/service/src/main/inse/background_jobs/service.py @@ -14,6 +14,7 @@ from inse.auth.model import AccessTokenMetadata, UserRole from . import runner from .model import ( + AvailableImages, BackgroundJobTask, DockerHealth, JobDefinition, @@ -80,7 +81,7 @@ def _to_task(session: Session, definition: JobDefinition) -> BackgroundJobTask: name=definition.name, description=definition.description, target_index=definition.target_index, - image=runner.resolve_image(definition), + image=definition.image, command=definition.command, env=definition.env or {}, schedule=definition.schedule, @@ -113,6 +114,12 @@ def create_task( status_code=status.HTTP_422_UNPROCESSABLE_ENTITY, detail="Task name must not be empty.", ) + image = (payload.image or "").strip() + if not image: + raise HTTPException( + status_code=status.HTTP_422_UNPROCESSABLE_ENTITY, + detail="An image must be selected.", + ) if payload.schedule is not None and not croniter.is_valid(payload.schedule): raise HTTPException( status_code=status.HTTP_422_UNPROCESSABLE_ENTITY, @@ -126,7 +133,7 @@ def create_task( definition = JobDefinition( name=name, - image=payload.image, + image=image, command=payload.command, env=payload.env or {}, description=payload.description, @@ -203,6 +210,15 @@ def update_task( ) changes["name"] = name + if "image" in changes: + image = (changes["image"] or "").strip() + if not image: + raise HTTPException( + status_code=status.HTTP_422_UNPROCESSABLE_ENTITY, + detail="An image must be selected.", + ) + changes["image"] = image + definition = _get_definition(session, definition_id) for key, value in changes.items(): setattr(definition, key, value) @@ -364,6 +380,12 @@ def stop_run( return run +def get_available_images(access_token: AccessTokenMetadata) -> AvailableImages: + _require_super_admin(access_token) + images, detail = runner.list_registry_images() + return AvailableImages(images=images, detail=detail) + + def docker_health(access_token: AccessTokenMetadata) -> DockerHealth: _require_super_admin(access_token) reachable, detail = runner.docker_reachable() diff --git a/webapp/src/app/api/.openapi-generator/FILES b/webapp/src/app/api/.openapi-generator/FILES index b166b755..ded62dd1 100644 --- a/webapp/src/app/api/.openapi-generator/FILES +++ b/webapp/src/app/api/.openapi-generator/FILES @@ -47,6 +47,7 @@ model/autocompleteLocationItem.ts model/autocompleteResponse.ts model/autocompleteResponseMeta.ts model/autocompleteResponseResultsInner.ts +model/availableImages.ts model/award.ts model/backgroundJobTask.ts model/bodyChangePassword.ts diff --git a/webapp/src/app/api/api/backgroundJobs.service.ts b/webapp/src/app/api/api/backgroundJobs.service.ts index 7a838c18..2617efd6 100644 --- a/webapp/src/app/api/api/backgroundJobs.service.ts +++ b/webapp/src/app/api/api/backgroundJobs.service.ts @@ -22,6 +22,8 @@ import { import { CustomHttpParameterCodec } from '../encoder'; import { Observable } from 'rxjs'; +// @ts-ignore +import { AvailableImages } from '../model/availableImages'; // @ts-ignore import { BackgroundJobTask } from '../model/backgroundJobTask'; // @ts-ignore @@ -646,6 +648,110 @@ export class BackgroundJobsService extends BaseService { ); } + /** + * Get Available Images + * @endpoint get /api/background-jobs/available-images + * @param secureFgpAcc + * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. + * @param reportProgress flag to report request and response progress. + */ + public getBackgroundJobAvailableImages( + secureFgpAcc?: string, + observe?: 'body', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable; + public getBackgroundJobAvailableImages( + secureFgpAcc?: string, + observe?: 'response', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable>; + public getBackgroundJobAvailableImages( + secureFgpAcc?: string, + observe?: 'events', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable>; + public getBackgroundJobAvailableImages( + secureFgpAcc?: string, + observe: any = 'body', + reportProgress: boolean = false, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable { + let localVarHeaders = this.defaultHeaders; + + // authentication (HTTPBearer) required + localVarHeaders = this.configuration.addCredentialToHeaders( + 'HTTPBearer', + 'Authorization', + localVarHeaders, + 'Bearer ', + ); + + const localVarHttpHeaderAcceptSelected: string | undefined = + options?.httpHeaderAccept ?? + this.configuration.selectHeaderAccept(['application/json']); + if (localVarHttpHeaderAcceptSelected !== undefined) { + localVarHeaders = localVarHeaders.set( + 'Accept', + localVarHttpHeaderAcceptSelected, + ); + } + + const localVarHttpContext: HttpContext = + options?.context ?? new HttpContext(); + + const localVarTransferCache: boolean = options?.transferCache ?? true; + + let responseType_: 'text' | 'json' | 'blob' = 'json'; + if (localVarHttpHeaderAcceptSelected) { + if (localVarHttpHeaderAcceptSelected.startsWith('text')) { + responseType_ = 'text'; + } else if ( + this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected) + ) { + responseType_ = 'json'; + } else { + responseType_ = 'blob'; + } + } + + let localVarPath = `/api/background-jobs/available-images`; + const { basePath, withCredentials } = this.configuration; + return this.httpClient.request( + 'get', + `${basePath}${localVarPath}`, + { + context: localVarHttpContext, + responseType: responseType_, + ...(withCredentials ? { withCredentials } : {}), + headers: localVarHeaders, + observe: observe, + ...(localVarTransferCache !== undefined + ? { transferCache: localVarTransferCache } + : {}), + reportProgress: reportProgress, + }, + ); + } + /** * Docker Health * @endpoint get /api/background-jobs/docker-health diff --git a/webapp/src/app/api/model/availableImages.ts b/webapp/src/app/api/model/availableImages.ts new file mode 100644 index 00000000..06b9742e --- /dev/null +++ b/webapp/src/app/api/model/availableImages.ts @@ -0,0 +1,14 @@ +/** + * Innovation Search Engine API + * + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +export interface AvailableImages { + images: Array; + detail?: string; +} diff --git a/webapp/src/app/api/model/backgroundJobTask.ts b/webapp/src/app/api/model/backgroundJobTask.ts index e6072ba8..e3063969 100644 --- a/webapp/src/app/api/model/backgroundJobTask.ts +++ b/webapp/src/app/api/model/backgroundJobTask.ts @@ -14,7 +14,7 @@ export interface BackgroundJobTask { name: string; description: string; target_index: string; - image: string; + image: string | null; command: string | null; env: { [key: string]: string }; schedule: string | null; diff --git a/webapp/src/app/api/model/models.ts b/webapp/src/app/api/model/models.ts index 9134e614..c07e9caa 100644 --- a/webapp/src/app/api/model/models.ts +++ b/webapp/src/app/api/model/models.ts @@ -18,6 +18,7 @@ export * from './autocompleteLocationItem'; export * from './autocompleteResponse'; export * from './autocompleteResponseMeta'; export * from './autocompleteResponseResultsInner'; +export * from './availableImages'; export * from './award'; export * from './backgroundJobTask'; export * from './bodyChangePassword'; diff --git a/webapp/src/app/modules/jobs/task-create-dialog/task-create-dialog.component.html b/webapp/src/app/modules/jobs/task-create-dialog/task-create-dialog.component.html index c0d9b080..a41f8ed6 100644 --- a/webapp/src/app/modules/jobs/task-create-dialog/task-create-dialog.component.html +++ b/webapp/src/app/modules/jobs/task-create-dialog/task-create-dialog.component.html @@ -34,18 +34,26 @@ Image - + formControlName="image" + [matAutocomplete]="imageAuto" /> + + @for (image of filteredImages(); track image) { + {{ image }} + } + info_outline - Im Normalfall unverändert lassen. + @if (form.controls.image.invalid && form.controls.image.touched) { + Bitte ein Image auswählen oder eingeben. + } + Aus Nexus wählen oder eigenes Image eingeben. diff --git a/webapp/src/app/modules/jobs/task-create-dialog/task-create-dialog.component.ts b/webapp/src/app/modules/jobs/task-create-dialog/task-create-dialog.component.ts index 50858c76..ee841c3f 100644 --- a/webapp/src/app/modules/jobs/task-create-dialog/task-create-dialog.component.ts +++ b/webapp/src/app/modules/jobs/task-create-dialog/task-create-dialog.component.ts @@ -1,11 +1,13 @@ import { CommonModule } from '@angular/common'; -import { Component, inject, signal } from '@angular/core'; +import { Component, OnInit, computed, inject, signal } from '@angular/core'; +import { toSignal } from '@angular/core/rxjs-interop'; import { FormControl, FormGroup, ReactiveFormsModule, Validators, } from '@angular/forms'; +import { MatAutocompleteModule } from '@angular/material/autocomplete'; import { MatButtonModule } from '@angular/material/button'; import { MatDialogModule, MatDialogRef } from '@angular/material/dialog'; import { MatFormFieldModule } from '@angular/material/form-field'; @@ -23,6 +25,7 @@ const DEFAULT_JOB_IMAGE = 'docker.nes.uni-due.de/inse/background-jobs:latest'; imports: [ CommonModule, ReactiveFormsModule, + MatAutocompleteModule, MatButtonModule, MatDialogModule, MatFormFieldModule, @@ -34,7 +37,7 @@ const DEFAULT_JOB_IMAGE = 'docker.nes.uni-due.de/inse/background-jobs:latest'; styleUrl: './task-create-dialog.component.scss', standalone: true, }) -export class TaskCreateDialogComponent { +export class TaskCreateDialogComponent implements OnInit { private readonly dialogRef = inject< MatDialogRef @@ -43,6 +46,7 @@ export class TaskCreateDialogComponent { protected readonly creating = signal(false); protected readonly serverError = signal(''); + protected readonly images = signal([]); protected readonly form = new FormGroup({ name: new FormControl('', { @@ -52,10 +56,33 @@ export class TaskCreateDialogComponent { description: new FormControl('', { nonNullable: true }), targetIndex: new FormControl('', { nonNullable: true }), command: new FormControl('', { nonNullable: true }), - image: new FormControl(DEFAULT_JOB_IMAGE, { nonNullable: true }), + image: new FormControl(DEFAULT_JOB_IMAGE, { + nonNullable: true, + validators: [Validators.required], + }), env: new FormControl('', { nonNullable: true }), }); + private readonly imageQuery = toSignal( + this.form.controls.image.valueChanges, + { + initialValue: this.form.controls.image.value, + }, + ); + + protected readonly filteredImages = computed(() => { + const query = (this.imageQuery() ?? '').toLowerCase().trim(); + const all = this.images(); + if (!query) return all; + return all.filter((image) => image.toLowerCase().includes(query)); + }); + + ngOnInit(): void { + this.backgroundJobsService + .getBackgroundJobAvailableImages() + .subscribe({ next: (result) => this.images.set(result.images ?? []) }); + } + protected submit(): void { this.serverError.set(''); const value = this.form.getRawValue(); @@ -66,19 +93,23 @@ export class TaskCreateDialogComponent { return; } + const image = value.image.trim(); + if (!image) { + this.form.controls.image.markAsTouched(); + return; + } + const command = value.command.trim() || null; const env = this.parseEnv(value.env); if (env === undefined) return; - const image = value.image.trim(); - this.creating.set(true); this.backgroundJobsService .createBackgroundJobTask({ name, description: value.description.trim(), target_index: value.targetIndex.trim(), - image: !image || image === DEFAULT_JOB_IMAGE ? null : image, + image, command, env, }) diff --git a/webapp/src/app/modules/jobs/task-edit-dialog/task-edit-dialog.component.html b/webapp/src/app/modules/jobs/task-edit-dialog/task-edit-dialog.component.html index dc75d179..59f0b31f 100644 --- a/webapp/src/app/modules/jobs/task-edit-dialog/task-edit-dialog.component.html +++ b/webapp/src/app/modules/jobs/task-edit-dialog/task-edit-dialog.component.html @@ -34,18 +34,26 @@ Image - + formControlName="image" + [matAutocomplete]="imageAuto" /> + + @for (image of filteredImages(); track image) { + {{ image }} + } + info_outline - Im Normalfall unverändert lassen. + @if (form.controls.image.invalid && form.controls.image.touched) { + Bitte ein Image auswählen oder eingeben. + } + Aus Nexus wählen oder eigenes Image eingeben. diff --git a/webapp/src/app/modules/jobs/task-edit-dialog/task-edit-dialog.component.ts b/webapp/src/app/modules/jobs/task-edit-dialog/task-edit-dialog.component.ts index 776749a9..87f52cdd 100644 --- a/webapp/src/app/modules/jobs/task-edit-dialog/task-edit-dialog.component.ts +++ b/webapp/src/app/modules/jobs/task-edit-dialog/task-edit-dialog.component.ts @@ -1,11 +1,13 @@ import { CommonModule } from '@angular/common'; -import { Component, inject, signal } from '@angular/core'; +import { Component, OnInit, computed, inject, signal } from '@angular/core'; +import { toSignal } from '@angular/core/rxjs-interop'; import { FormControl, FormGroup, ReactiveFormsModule, Validators, } from '@angular/forms'; +import { MatAutocompleteModule } from '@angular/material/autocomplete'; import { MatButtonModule } from '@angular/material/button'; import { MAT_DIALOG_DATA, @@ -20,8 +22,6 @@ import { BackgroundJobTask, BackgroundJobsService } from '../../../api'; const ENV_LINE_PATTERN = /^[A-Za-z_][A-Za-z0-9_]*=.*$/; -const DEFAULT_JOB_IMAGE = 'docker.nes.uni-due.de/inse/background-jobs:latest'; - export interface TaskEditDialogData { task: BackgroundJobTask; } @@ -31,6 +31,7 @@ export interface TaskEditDialogData { imports: [ CommonModule, ReactiveFormsModule, + MatAutocompleteModule, MatButtonModule, MatDialogModule, MatFormFieldModule, @@ -42,7 +43,7 @@ export interface TaskEditDialogData { styleUrl: './task-edit-dialog.component.scss', standalone: true, }) -export class TaskEditDialogComponent { +export class TaskEditDialogComponent implements OnInit { private readonly dialogRef = inject< MatDialogRef @@ -52,6 +53,7 @@ export class TaskEditDialogComponent { protected readonly saving = signal(false); protected readonly serverError = signal(''); + protected readonly images = signal([]); protected readonly form = new FormGroup({ name: new FormControl(this.data.task.name, { @@ -67,12 +69,35 @@ export class TaskEditDialogComponent { command: new FormControl(this.data.task.command ?? '', { nonNullable: true, }), - image: new FormControl(this.data.task.image, { nonNullable: true }), + image: new FormControl(this.data.task.image ?? '', { + nonNullable: true, + validators: [Validators.required], + }), env: new FormControl(this.envToText(this.data.task.env), { nonNullable: true, }), }); + private readonly imageQuery = toSignal( + this.form.controls.image.valueChanges, + { + initialValue: this.form.controls.image.value, + }, + ); + + protected readonly filteredImages = computed(() => { + const query = (this.imageQuery() ?? '').toLowerCase().trim(); + const all = this.images(); + if (!query) return all; + return all.filter((image) => image.toLowerCase().includes(query)); + }); + + ngOnInit(): void { + this.backgroundJobsService + .getBackgroundJobAvailableImages() + .subscribe({ next: (result) => this.images.set(result.images ?? []) }); + } + protected submit(): void { this.serverError.set(''); const value = this.form.getRawValue(); @@ -83,18 +108,22 @@ export class TaskEditDialogComponent { return; } + const image = value.image.trim(); + if (!image) { + this.form.controls.image.markAsTouched(); + return; + } + const env = this.parseEnv(value.env); if (env === undefined) return; - const image = value.image.trim(); - this.saving.set(true); this.backgroundJobsService .updateBackgroundJobTask(this.data.task.id, { name, description: value.description.trim(), target_index: value.targetIndex.trim(), - image: !image || image === DEFAULT_JOB_IMAGE ? null : image, + image, command: value.command.trim() || null, env, })