feat(jobs): select image from a Nexus autocomplete
This commit is contained in:
@@ -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 = ""
|
||||
|
||||
@@ -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",
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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()
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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<AvailableImages>;
|
||||
public getBackgroundJobAvailableImages(
|
||||
secureFgpAcc?: string,
|
||||
observe?: 'response',
|
||||
reportProgress?: boolean,
|
||||
options?: {
|
||||
httpHeaderAccept?: 'application/json';
|
||||
context?: HttpContext;
|
||||
transferCache?: boolean;
|
||||
},
|
||||
): Observable<HttpResponse<AvailableImages>>;
|
||||
public getBackgroundJobAvailableImages(
|
||||
secureFgpAcc?: string,
|
||||
observe?: 'events',
|
||||
reportProgress?: boolean,
|
||||
options?: {
|
||||
httpHeaderAccept?: 'application/json';
|
||||
context?: HttpContext;
|
||||
transferCache?: boolean;
|
||||
},
|
||||
): Observable<HttpEvent<AvailableImages>>;
|
||||
public getBackgroundJobAvailableImages(
|
||||
secureFgpAcc?: string,
|
||||
observe: any = 'body',
|
||||
reportProgress: boolean = false,
|
||||
options?: {
|
||||
httpHeaderAccept?: 'application/json';
|
||||
context?: HttpContext;
|
||||
transferCache?: boolean;
|
||||
},
|
||||
): Observable<any> {
|
||||
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<AvailableImages>(
|
||||
'get',
|
||||
`${basePath}${localVarPath}`,
|
||||
{
|
||||
context: localVarHttpContext,
|
||||
responseType: <any>responseType_,
|
||||
...(withCredentials ? { withCredentials } : {}),
|
||||
headers: localVarHeaders,
|
||||
observe: observe,
|
||||
...(localVarTransferCache !== undefined
|
||||
? { transferCache: localVarTransferCache }
|
||||
: {}),
|
||||
reportProgress: reportProgress,
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Docker Health
|
||||
* @endpoint get /api/background-jobs/docker-health
|
||||
|
||||
@@ -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<string>;
|
||||
detail?: string;
|
||||
}
|
||||
@@ -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;
|
||||
|
||||
@@ -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';
|
||||
|
||||
@@ -34,18 +34,26 @@
|
||||
|
||||
<mat-form-field appearance="outline">
|
||||
<mat-label>Image</mat-label>
|
||||
<textarea
|
||||
<input
|
||||
matInput
|
||||
class="image-input"
|
||||
rows="1"
|
||||
formControlName="image"></textarea>
|
||||
formControlName="image"
|
||||
[matAutocomplete]="imageAuto" />
|
||||
<mat-autocomplete #imageAuto="matAutocomplete">
|
||||
@for (image of filteredImages(); track image) {
|
||||
<mat-option [value]="image">{{ image }}</mat-option>
|
||||
}
|
||||
</mat-autocomplete>
|
||||
<mat-icon
|
||||
matSuffix
|
||||
class="field-info"
|
||||
matTooltip="Vorausgefüllt ist das Standard-Image mit allen Background-Job-Skripten — im Normalfall einfach so lassen. Nur ändern, wenn der Job ein eigenes Docker-Image nutzen soll; eigene Images erhalten die INSE-Zugangsdaten (Elasticsearch/LLM) nicht automatisch."
|
||||
matTooltip="Docker-Image für den Job. Tippen filtert die aus Nexus verfügbaren Images; du kannst auch einen eigenen Wert eingeben. Images aus unserer Registry (docker.nes.uni-due.de) erhalten die INSE-Zugangsdaten (Elasticsearch/LLM) automatisch, fremde Images nicht."
|
||||
>info_outline</mat-icon
|
||||
>
|
||||
<mat-hint>Im Normalfall unverändert lassen.</mat-hint>
|
||||
@if (form.controls.image.invalid && form.controls.image.touched) {
|
||||
<mat-error>Bitte ein Image auswählen oder eingeben.</mat-error>
|
||||
}
|
||||
<mat-hint>Aus Nexus wählen oder eigenes Image eingeben.</mat-hint>
|
||||
</mat-form-field>
|
||||
|
||||
<mat-form-field appearance="outline">
|
||||
|
||||
@@ -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<TaskCreateDialogComponent, BackgroundJobTask | undefined>
|
||||
@@ -43,6 +46,7 @@ export class TaskCreateDialogComponent {
|
||||
|
||||
protected readonly creating = signal(false);
|
||||
protected readonly serverError = signal('');
|
||||
protected readonly images = signal<string[]>([]);
|
||||
|
||||
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,
|
||||
})
|
||||
|
||||
@@ -34,18 +34,26 @@
|
||||
|
||||
<mat-form-field appearance="outline">
|
||||
<mat-label>Image</mat-label>
|
||||
<textarea
|
||||
<input
|
||||
matInput
|
||||
class="image-input"
|
||||
rows="1"
|
||||
formControlName="image"></textarea>
|
||||
formControlName="image"
|
||||
[matAutocomplete]="imageAuto" />
|
||||
<mat-autocomplete #imageAuto="matAutocomplete">
|
||||
@for (image of filteredImages(); track image) {
|
||||
<mat-option [value]="image">{{ image }}</mat-option>
|
||||
}
|
||||
</mat-autocomplete>
|
||||
<mat-icon
|
||||
matSuffix
|
||||
class="field-info"
|
||||
matTooltip="Vorausgefüllt ist das Standard-Image mit allen Background-Job-Skripten — im Normalfall einfach so lassen. Nur ändern, wenn der Job ein eigenes Docker-Image nutzen soll; eigene Images erhalten die INSE-Zugangsdaten (Elasticsearch/LLM) nicht automatisch."
|
||||
matTooltip="Docker-Image für den Job. Tippen filtert die aus Nexus verfügbaren Images; du kannst auch einen eigenen Wert eingeben. Images aus unserer Registry (docker.nes.uni-due.de) erhalten die INSE-Zugangsdaten (Elasticsearch/LLM) automatisch, fremde Images nicht."
|
||||
>info_outline</mat-icon
|
||||
>
|
||||
<mat-hint>Im Normalfall unverändert lassen.</mat-hint>
|
||||
@if (form.controls.image.invalid && form.controls.image.touched) {
|
||||
<mat-error>Bitte ein Image auswählen oder eingeben.</mat-error>
|
||||
}
|
||||
<mat-hint>Aus Nexus wählen oder eigenes Image eingeben.</mat-hint>
|
||||
</mat-form-field>
|
||||
|
||||
<mat-form-field appearance="outline">
|
||||
|
||||
@@ -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<TaskEditDialogComponent, BackgroundJobTask | undefined>
|
||||
@@ -52,6 +53,7 @@ export class TaskEditDialogComponent {
|
||||
|
||||
protected readonly saving = signal(false);
|
||||
protected readonly serverError = signal('');
|
||||
protected readonly images = signal<string[]>([]);
|
||||
|
||||
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,
|
||||
})
|
||||
|
||||
Reference in New Issue
Block a user