diff --git a/service/src/main/inse/background_jobs/model.py b/service/src/main/inse/background_jobs/model.py index 0cc7d37e..2a19fbef 100644 --- a/service/src/main/inse/background_jobs/model.py +++ b/service/src/main/inse/background_jobs/model.py @@ -135,6 +135,12 @@ class DockerHealth(BaseModel): detail: str +class RegistryHealth(BaseModel): + reachable: bool + detail: str + host: 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 4a3b7d41..57b3704b 100644 --- a/service/src/main/inse/background_jobs/router.py +++ b/service/src/main/inse/background_jobs/router.py @@ -11,6 +11,7 @@ from .model import ( AvailableImages, BackgroundJobTask, DockerHealth, + RegistryHealth, JobDefinitionCreateRequest, JobDefinitionUpdateRequest, JobRun, @@ -147,3 +148,14 @@ async def docker_health( access_token: AccessTokenMetadata = auth_service.CurrentUserAccessTokenPayloadDep, ) -> DockerHealth: return service.docker_health(access_token) + + +@router.get( + "/registry-health", + operation_id="getBackgroundJobsRegistryHealth", + response_model=RegistryHealth, +) +async def registry_health( + access_token: AccessTokenMetadata = auth_service.CurrentUserAccessTokenPayloadDep, +) -> RegistryHealth: + return service.registry_health(access_token) diff --git a/service/src/main/inse/background_jobs/runner.py b/service/src/main/inse/background_jobs/runner.py index 89a1c8f8..288b9fb8 100644 --- a/service/src/main/inse/background_jobs/runner.py +++ b/service/src/main/inse/background_jobs/runner.py @@ -5,6 +5,7 @@ periodic schedule/reconcile loop. import asyncio import logging +import re from datetime import datetime from threading import RLock from typing import Optional @@ -45,6 +46,23 @@ def docker_reachable() -> tuple[bool, str]: return False, str(error) +def registry_reachable() -> tuple[bool, str]: + username = settings.background_jobs_registry_username + password = settings.background_jobs_registry_password + auth = (username, password) if username and password else None + host = registry_host() + try: + with httpx.Client(timeout=8.0, auth=auth) as client: + response = client.get(f"https://{host}/v2/") + if response.status_code == 200: + return True, "ok" + if response.status_code == 401: + return False, "authentication failed (401)" + return False, f"unexpected status {response.status_code}" + except Exception as error: # noqa: BLE001 + return False, str(error) + + def compute_next_run(schedule: str) -> datetime: return croniter(schedule, utcnow()).get_next(datetime) @@ -112,6 +130,18 @@ def is_registry_image(image: Optional[str]) -> bool: return bool(image) and image.split("/", 1)[0] == registry_host() +def container_name(definition: JobDefinition, run: JobRun) -> str: + slug = definition.name.lower() + slug = ( + slug.replace("ä", "ae") + .replace("ö", "oe") + .replace("ü", "ue") + .replace("ß", "ss") + ) + slug = re.sub(r"[^a-z0-9]+", "-", slug).strip("-")[:40].strip("-") + return f"{slug or 'job'}-run-{run.id}" + + def resolve_command(definition: JobDefinition): return definition.command or None @@ -134,15 +164,8 @@ def registry_auth() -> Optional[dict[str, str]]: def pull_image(image: str) -> None: - try: - get_docker_client().images.pull(image, auth_config=registry_auth()) - logger.info("Pulled image '%s' from the registry.", image) - except Exception: - logger.warning( - "Could not pull image '%s'; using the local copy if present.", - image, - exc_info=True, - ) + get_docker_client().images.pull(image, auth_config=registry_auth()) + logger.info("Pulled image '%s' from the registry.", image) def start_run( @@ -163,15 +186,25 @@ def start_run( session.refresh(run) return run - try: - if settings.background_jobs_pull_before_run: + if settings.background_jobs_pull_before_run and is_registry_image(image): + try: pull_image(image) + except Exception as error: # noqa: BLE001 + run.status = JobRunStatus.FAILED + run.finished_at = utcnow() + run.logs = f"failed to pull image '{image}': {error}" + session.add(run) + session.commit() + session.refresh(run) + return run + + try: container = get_docker_client().containers.run( image=image, command=resolve_command(definition), environment=resolve_environment(definition), detach=True, - name=f"background-job-{definition.id}-run-{run.id}", + name=container_name(definition, run), remove=False, ) run.container_id = container.id diff --git a/service/src/main/inse/background_jobs/service.py b/service/src/main/inse/background_jobs/service.py index 581557d9..9f27b30e 100644 --- a/service/src/main/inse/background_jobs/service.py +++ b/service/src/main/inse/background_jobs/service.py @@ -17,6 +17,7 @@ from .model import ( AvailableImages, BackgroundJobTask, DockerHealth, + RegistryHealth, JobDefinition, JobDefinitionCreateRequest, JobDefinitionUpdateRequest, @@ -390,3 +391,11 @@ def docker_health(access_token: AccessTokenMetadata) -> DockerHealth: _require_super_admin(access_token) reachable, detail = runner.docker_reachable() return DockerHealth(reachable=reachable, detail=detail) + + +def registry_health(access_token: AccessTokenMetadata) -> RegistryHealth: + _require_super_admin(access_token) + reachable, detail = runner.registry_reachable() + return RegistryHealth( + reachable=reachable, detail=detail, host=runner.registry_host() + ) diff --git a/webapp/src/app/api/.openapi-generator/FILES b/webapp/src/app/api/.openapi-generator/FILES index ded62dd1..edff19a7 100644 --- a/webapp/src/app/api/.openapi-generator/FILES +++ b/webapp/src/app/api/.openapi-generator/FILES @@ -192,6 +192,7 @@ model/publicationIdsByAuthorPosition.ts model/publicationsByAuthorResponse.ts model/rankingResponse.ts model/rebuildResponse.ts +model/registryHealth.ts model/score.ts model/sortDirection.ts model/tokenType.ts diff --git a/webapp/src/app/api/api/backgroundJobs.service.ts b/webapp/src/app/api/api/backgroundJobs.service.ts index 2617efd6..8df591c2 100644 --- a/webapp/src/app/api/api/backgroundJobs.service.ts +++ b/webapp/src/app/api/api/backgroundJobs.service.ts @@ -38,6 +38,8 @@ import { JobDefinitionUpdateRequest } from '../model/jobDefinitionUpdateRequest' import { JobRun } from '../model/jobRun'; // @ts-ignore import { JobRunLogs } from '../model/jobRunLogs'; +// @ts-ignore +import { RegistryHealth } from '../model/registryHealth'; // @ts-ignore import { BASE_PATH, COLLECTION_FORMATS } from '../variables'; @@ -856,6 +858,110 @@ export class BackgroundJobsService extends BaseService { ); } + /** + * Registry Health + * @endpoint get /api/background-jobs/registry-health + * @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 getBackgroundJobsRegistryHealth( + secureFgpAcc?: string, + observe?: 'body', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable; + public getBackgroundJobsRegistryHealth( + secureFgpAcc?: string, + observe?: 'response', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable>; + public getBackgroundJobsRegistryHealth( + secureFgpAcc?: string, + observe?: 'events', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable>; + public getBackgroundJobsRegistryHealth( + 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/registry-health`; + 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, + }, + ); + } + /** * Run Task * @endpoint post /api/background-jobs/tasks/{task_id}/run diff --git a/webapp/src/app/api/model/models.ts b/webapp/src/app/api/model/models.ts index c07e9caa..9a5c1383 100644 --- a/webapp/src/app/api/model/models.ts +++ b/webapp/src/app/api/model/models.ts @@ -162,6 +162,7 @@ export * from './publicationIdsByAuthorPosition'; export * from './publicationsByAuthorResponse'; export * from './rankingResponse'; export * from './rebuildResponse'; +export * from './registryHealth'; export * from './score'; export * from './sortDirection'; export * from './tokenType'; diff --git a/webapp/src/app/api/model/registryHealth.ts b/webapp/src/app/api/model/registryHealth.ts new file mode 100644 index 00000000..dc9411bd --- /dev/null +++ b/webapp/src/app/api/model/registryHealth.ts @@ -0,0 +1,15 @@ +/** + * 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 RegistryHealth { + reachable: boolean; + detail: string; + host: string; +} diff --git a/webapp/src/app/modules/jobs/jobs.component.html b/webapp/src/app/modules/jobs/jobs.component.html index 429e494c..40e432be 100644 --- a/webapp/src/app/modules/jobs/jobs.component.html +++ b/webapp/src/app/modules/jobs/jobs.component.html @@ -18,37 +18,86 @@ - - -
- - -
- Docker-Daemon -
- {{ dockerHealth()?.reachable ? 'Erreichbar' : 'Nicht erreichbar' }} - @if (dockerHealth()?.detail) { - · {{ dockerHealth()?.detail }} - } +
+ + +
+ + +
+ Docker-Daemon +
+ {{ + dockerHealth()?.reachable ? 'Erreichbar' : 'Nicht erreichbar' + }} + @if (dockerHealth()?.detail) { + · {{ dockerHealth()?.detail }} + } +
-
- - - + + + + + + +
+ + +
+
+ Nexus-Registry + @if (registryHealth()?.host) { + {{ registryHealth()?.host }} + } +
+
+ @if (registryHealthLoading() && !registryHealth()) { + Wird geprüft … + } @else { + {{ + registryHealth()?.reachable + ? 'Erreichbar' + : 'Nicht erreichbar' + }} + @if (registryHealth()?.detail) { + · {{ registryHealth()?.detail }} + } + } +
+
+
+ +
+
+
diff --git a/webapp/src/app/modules/jobs/jobs.component.scss b/webapp/src/app/modules/jobs/jobs.component.scss index b131ba42..1777b492 100644 --- a/webapp/src/app/modules/jobs/jobs.component.scss +++ b/webapp/src/app/modules/jobs/jobs.component.scss @@ -37,23 +37,37 @@ mat-paginator { background-color: var(--sg-background); } -.docker-health-content { +.health-cards { display: flex; - align-items: center; - justify-content: space-between; - gap: 16px; -} - -.docker-health-info { - display: flex; - align-items: flex-start; gap: 12px; } -.docker-state-dot { - margin-top: 6px; - width: 10px; - height: 10px; +.health-card { + flex: 1 1 0; + min-width: 0; +} + +.health-content { + display: flex; + align-items: center; + justify-content: space-between; + gap: 12px; +} + +.health-info { + display: flex; + align-items: center; + gap: 12px; + min-width: 0; +} + +.health-text { + min-width: 0; +} + +.state-dot { + width: 12px; + height: 12px; border-radius: 50%; background: #94a3b8; flex-shrink: 0; @@ -67,11 +81,24 @@ mat-paginator { } } -.docker-health-detail { +.health-detail { font-size: 12px; color: #64748b; } +.health-title { + display: flex; + align-items: baseline; + gap: 8px; + flex-wrap: wrap; +} + +.health-host { + font-size: 11px; + color: #64748b; + word-break: break-all; +} + :host ::ng-deep .mat-mdc-row { height: 96px; } @@ -283,8 +310,7 @@ mat-paginator { flex-direction: column; } - .docker-health-content { + .health-cards { flex-direction: column; - align-items: flex-start; } } diff --git a/webapp/src/app/modules/jobs/jobs.component.ts b/webapp/src/app/modules/jobs/jobs.component.ts index f7bdb907..97a53644 100644 --- a/webapp/src/app/modules/jobs/jobs.component.ts +++ b/webapp/src/app/modules/jobs/jobs.component.ts @@ -30,6 +30,7 @@ import { BackgroundJobsService, BackgroundJobTask, DockerHealth, + RegistryHealth, } from '../../api'; import { DataTableComponent, @@ -89,6 +90,8 @@ export class JobsComponent implements OnInit { protected readonly tasks = signal([]); protected readonly dockerHealth = signal(null); protected readonly dockerHealthLoading = signal(false); + protected readonly registryHealth = signal(null); + protected readonly registryHealthLoading = signal(false); protected readonly deletingTaskIds = signal>(new Set()); protected readonly nowMs = signal(Date.now()); @@ -123,6 +126,7 @@ export class JobsComponent implements OnInit { ngOnInit(): void { this.tasks.set(this.tasksInput()); this.dockerHealth.set(this.dockerHealthInput()); + this.refreshRegistryHealth(); merge(this.pollNow, this.taskRefreshTrigger) .pipe( @@ -249,21 +253,62 @@ export class JobsComponent implements OnInit { }); } + protected refreshRegistryHealth(): void { + this.registryHealthLoading.set(true); + this.backgroundJobsService + .getBackgroundJobsRegistryHealth() + .pipe(takeUntilDestroyed(this.destroyRef)) + .subscribe({ + next: (health) => { + this.registryHealth.set(health); + this.registryHealthLoading.set(false); + }, + error: () => { + this.registryHealthLoading.set(false); + this.showError('Nexus-Status konnte nicht abgerufen werden.'); + }, + }); + } + + private notifyIfRegistryDown(): void { + this.backgroundJobsService + .getBackgroundJobsRegistryHealth() + .pipe(takeUntilDestroyed(this.destroyRef)) + .subscribe({ + next: (health) => { + this.registryHealth.set(health); + if (!health.reachable) { + this.showError( + `Nexus-Registry nicht erreichbar: ${health.detail}. Die Image-Auswahl bleibt leer.`, + ); + } + }, + }); + } + protected runNow(task: BackgroundJobTask): void { if (['running', 'stopping'].includes(task.status)) return; this.backgroundJobsService.runBackgroundJobTask(task.id).subscribe({ next: (run) => { + const status = run.status ?? 'running'; this.updateTask(task.id, (current) => ({ ...current, - status: 'running', + status, last_run: run, })); - this.snackBar.open(`„${task.name}“ wurde gestartet.`, 'OK', { - duration: 3000, - horizontalPosition: 'center', - verticalPosition: 'bottom', - }); + if (status === 'failed') { + this.showError( + `„${task.name}“ ist fehlgeschlagen — Details in den Logs.`, + ); + this.refreshRegistryHealth(); + } else { + this.snackBar.open(`„${task.name}“ wurde gestartet.`, 'OK', { + duration: 3000, + horizontalPosition: 'center', + verticalPosition: 'bottom', + }); + } this.refreshTasks(); }, error: (error) => @@ -334,6 +379,8 @@ export class JobsComponent implements OnInit { } protected openCreateDialog(): void { + this.notifyIfRegistryDown(); + const dialogRef = this.dialog.open< TaskCreateDialogComponent, void, @@ -359,6 +406,8 @@ export class JobsComponent implements OnInit { protected openEditDialog(task: BackgroundJobTask): void { if (['running', 'stopping'].includes(task.status)) return; + this.notifyIfRegistryDown(); + const dialogRef = this.dialog.open< TaskEditDialogComponent, TaskEditDialogData,