Modern Docker Management, Designed for Everyone
Go composecontainer-managementcontainersdockerdocker-composedocker-managementgoself-hostedsveltekittypescriptweb-ui
fix: allow job schedules to be changed per environment (#1577)
Kyle Mendell4b31fc52b494
diff --git a/backend/internal/huma/handlers/job_schedules.go b/backend/internal/huma/handlers/job_schedules.goindex cd71dd477..1fb0f7cd6 100644--- a/backend/internal/huma/handlers/job_schedules.go+++ b/backend/internal/huma/handlers/job_schedules.go@@ -2,6 +2,7 @@ package handlersimport ("context"+ "encoding/json""net/http""github.com/danielgtaylor/huma/v2"@@ -10,11 +11,16 @@ import ("github.com/getarcaneapp/arcane/types/jobschedule")+type GetJobSchedulesInput struct {+ ID string `path:"id" doc:"Environment ID"`+}+type GetJobSchedulesOutput struct {Body jobschedule.Config}type UpdateJobSchedulesInput struct {+ ID string `path:"id" doc:"Environment ID"`Body jobschedule.Update `doc:"Job schedule update data"`}@@ -22,11 +28,16 @@ type UpdateJobSchedulesOutput struct {Body base.ApiResponse[jobschedule.Config]}+type ListJobsInput struct {+ ID string `path:"id" doc:"Environment ID"`+}+type GetJobsOutput struct {Body jobschedule.JobListResponse}type RunJobInput struct {+ ID string `path:"id" doc:"Environment ID"`JobID string `path:"jobId" minLength:"1" doc:"Job ID to run"`}@@ -34,13 +45,16 @@ type RunJobOutput struct {Body jobschedule.JobRunResponse}-func RegisterJobSchedules(api huma.API, jobSvc *services.JobService) {- h := &JobSchedulesHandler{jobService: jobSvc}+func RegisterJobSchedules(api huma.API, jobSvc *services.JobService, envSvc *services.EnvironmentService) {+ h := &JobSchedulesHandler{+ jobService: jobSvc,+ environmentService: envSvc,+ }huma.Register(api, huma.Operation{OperationID: "get-job-schedules",Method: http.MethodGet,- Path: "/job-schedules",+ Path: "/environments/{id}/job-schedules",Summary: "Get job schedules",Description: "Get configured cron schedules for background jobs",Tags: []string{"JobSchedules"},@@ -53,7 +67,7 @@ func RegisterJobSchedules(api huma.API, jobSvc *services.JobService) {huma.Register(api, huma.Operation{OperationID: "update-job-schedules",Method: http.MethodPut,- Path: "/job-schedules",+ Path: "/environments/{id}/job-schedules",Summary: "Update job schedules",Description: "Update background job cron schedules and reschedule running jobs",Tags: []string{"JobSchedules"},@@ -66,7 +80,7 @@ func RegisterJobSchedules(api huma.API, jobSvc *services.JobService) {huma.Register(api, huma.Operation{OperationID: "list-jobs",Method: http.MethodGet,- Path: "/jobs",+ Path: "/environments/{id}/jobs",Summary: "List all background jobs",Description: "Get status, schedule, and metadata for all background jobs",Tags: []string{"JobSchedules"},@@ -79,7 +93,7 @@ func RegisterJobSchedules(api huma.API, jobSvc *services.JobService) {huma.Register(api, huma.Operation{OperationID: "run-job",Method: http.MethodPost,- Path: "/jobs/{jobId}/run",+ Path: "/environments/{id}/jobs/{jobId}/run",Summary: "Run a job now",Description: "Manually trigger a background job to run immediately",Tags: []string{"JobSchedules"},@@ -91,14 +105,33 @@ func RegisterJobSchedules(api huma.API, jobSvc *services.JobService) {}type JobSchedulesHandler struct {- jobService *services.JobService+ jobService *services.JobService+ environmentService *services.EnvironmentService}-func (h *JobSchedulesHandler) ListJobs(ctx context.Context, _ *struct{}) (*GetJobsOutput, error) {+func (h *JobSchedulesHandler) ListJobs(ctx context.Context, input *ListJobsInput) (*GetJobsOutput, error) {if h.jobService == nil {return nil, huma.Error500InternalServerError("service not available")}+ if input.ID != "0" {+ if h.environmentService == nil {+ return nil, huma.Error500InternalServerError("environment service not available")+ }+ respBody, statusCode, err := h.environmentService.ProxyRequest(ctx, input.ID, http.MethodGet, "/api/environments/0/jobs", nil)+ if err != nil {+ return nil, huma.Error502BadGateway("failed to proxy request to environment: " + err.Error())+ }+ if statusCode != http.StatusOK {+ return nil, huma.NewError(statusCode, "environment returned error: "+string(respBody), nil)+ }+ var jobs jobschedule.JobListResponse+ if err := json.Unmarshal(respBody, &jobs); err != nil {+ return nil, huma.Error500InternalServerError("failed to decode environment response: " + err.Error())+ }+ return &GetJobsOutput{Body: jobs}, nil+ }+jobs, err := h.jobService.ListJobs(ctx)if err != nil {return nil, huma.Error500InternalServerError(err.Error())@@ -112,6 +145,24 @@ func (h *JobSchedulesHandler) RunJob(ctx context.Context, input *RunJobInput) (*return nil, huma.Error500InternalServerError("service not available")}+ if input.ID != "0" {+ if h.environmentService == nil {+ return nil, huma.Error500InternalServerError("environment service not available")+ }+ respBody, statusCode, err := h.environmentService.ProxyRequest(ctx, input.ID, http.MethodPost, "/api/environments/0/jobs/"+input.JobID+"/run", nil)+ if err != nil {+ return nil, huma.Error502BadGateway("failed to proxy request to environment: " + err.Error())+ }+ if statusCode != http.StatusOK {+ return nil, huma.NewError(statusCode, "environment returned error: "+string(respBody), nil)+ }+ var runResp jobschedule.JobRunResponse+ if err := json.Unmarshal(respBody, &runResp); err != nil {+ return nil, huma.Error500InternalServerError("failed to decode environment response: " + err.Error())+ }+ return &RunJobOutput{Body: runResp}, nil+ }+err := h.jobService.RunJobNowInline(ctx, input.JobID)if err != nil {return nil, huma.Error400BadRequest(err.Error())@@ -125,10 +176,29 @@ func (h *JobSchedulesHandler) RunJob(ctx context.Context, input *RunJobInput) (*}, nil}-func (h *JobSchedulesHandler) Get(ctx context.Context, _ *struct{}) (*GetJobSchedulesOutput, error) {+func (h *JobSchedulesHandler) Get(ctx context.Context, input *GetJobSchedulesInput) (*GetJobSchedulesOutput, error) {if h.jobService == nil {return nil, huma.Error500InternalServerError("service not available")}++ if input.ID != "0" {+ if h.environmentService == nil {+ return nil, huma.Error500InternalServerError("environment service not available")+ }+ respBody, statusCode, err := h.environmentService.ProxyRequest(ctx, input.ID, http.MethodGet, "/api/environments/0/job-schedules", nil)+ if err != nil {+ return nil, huma.Error502BadGateway("failed to proxy request to environment: " + err.Error())+ }+ if statusCode != http.StatusOK {+ return nil, huma.NewError(statusCode, "environment returned error: "+string(respBody), nil)+ }+ var cfg jobschedule.Config+ if err := json.Unmarshal(respBody, &cfg); err != nil {+ return nil, huma.Error500InternalServerError("failed to decode environment response: " + err.Error())+ }+ return &GetJobSchedulesOutput{Body: cfg}, nil+ }+cfg := h.jobService.GetJobSchedules(ctx)return &GetJobSchedulesOutput{Body: cfg}, nil}@@ -138,6 +208,32 @@ func (h *JobSchedulesHandler) Update(ctx context.Context, input *UpdateJobSchedureturn nil, huma.Error500InternalServerError("service not available")}+ if input.ID != "0" {+ if h.environmentService == nil {+ return nil, huma.Error500InternalServerError("environment service not available")+ }++ body, err := json.Marshal(input.Body)+ if err != nil {+ return nil, huma.Error500InternalServerError("failed to marshal request body: " + err.Error())+ }++ respBody, statusCode, err := h.environmentService.ProxyRequest(ctx, input.ID, http.MethodPut, "/api/environments/0/job-schedules", body)+ if err != nil {+ return nil, huma.Error502BadGateway("failed to proxy request to environment: " + err.Error())+ }+ if statusCode != http.StatusOK {+ return nil, huma.NewError(statusCode, "environment returned error: "+string(respBody), nil)+ }++ var apiResp base.ApiResponse[jobschedule.Config]+ if err := json.Unmarshal(respBody, &apiResp); err != nil {+ return nil, huma.Error500InternalServerError("failed to decode environment response: " + err.Error())+ }++ return &UpdateJobSchedulesOutput{Body: apiResp}, nil+ }+cfg, err := h.jobService.UpdateJobSchedules(ctx, input.Body)if err != nil {return nil, huma.Error400BadRequest(err.Error())diff --git a/backend/internal/huma/huma.go b/backend/internal/huma/huma.goindex 1dbc1c135..1edc1a7bb 100644--- a/backend/internal/huma/huma.go+++ b/backend/internal/huma/huma.go@@ -351,7 +351,7 @@ func registerHandlers(api huma.API, svc *Services) {handlers.RegisterImages(api, dockerSvc, imageSvc, imageUpdateSvc, settingsSvc)handlers.RegisterImageUpdates(api, imageUpdateSvc)handlers.RegisterSettings(api, settingsSvc, settingsSearchSvc, environmentSvc, cfg)- handlers.RegisterJobSchedules(api, jobScheduleSvc)+ handlers.RegisterJobSchedules(api, jobScheduleSvc, environmentSvc)handlers.RegisterVolumes(api, dockerSvc, volumeSvc)handlers.RegisterContainers(api, containerSvc, dockerSvc)handlers.RegisterNetworks(api, networkSvc, dockerSvc)diff --git a/backend/internal/middleware/environment_middleware.go b/backend/internal/middleware/environment_middleware.goindex 44a0e9fd9..aa6bc99c9 100644--- a/backend/internal/middleware/environment_middleware.go+++ b/backend/internal/middleware/environment_middleware.go@@ -30,6 +30,8 @@ const (managementEndpointAgentPair = "/agent/pair"managementEndpointVersion = "/version"managementEndpointSettings = "/settings"+ managementEndpointJobSchedules = "/job-schedules"+ managementEndpointJobs = "/jobs"errEnvironmentNotFound = "Environment not found"errEnvironmentDisabled = "Environment is disabled"@@ -179,6 +181,8 @@ func (m *EnvironmentMiddleware) hasResourcePath(c *gin.Context, envID string) bomanagementEndpointAgentPair,managementEndpointVersion,managementEndpointSettings,+ managementEndpointJobSchedules,+ managementEndpointJobs,}for _, endpoint := range managementEndpoints {diff --git a/backend/internal/services/job_service.go b/backend/internal/services/job_service.goindex 964153f7d..9bd155cfc 100644--- a/backend/internal/services/job_service.go+++ b/backend/internal/services/job_service.go@@ -3,6 +3,7 @@ package servicesimport ("context""fmt"+ "sort""time""github.com/getarcaneapp/arcane/backend/internal/config"@@ -50,6 +51,10 @@ func (s *JobService) GetJobSchedules(ctx context.Context) jobschedule.Config {EnvironmentHealthInterval: s.settings.GetStringSetting(ctx, "environmentHealthInterval", "0 */2 * * * *"),EventCleanupInterval: s.settings.GetStringSetting(ctx, "eventCleanupInterval", "0 0 */6 * * *"),AnalyticsHeartbeatInterval: s.settings.GetStringSetting(ctx, "analyticsHeartbeatInterval", "0 0 0 * * *"),+ AutoUpdateInterval: s.settings.GetStringSetting(ctx, "autoUpdateInterval", "0 0 0 * * *"),+ PollingInterval: s.settings.GetStringSetting(ctx, "pollingInterval", "0 */15 * * * *"),+ ScheduledPruneInterval: s.settings.GetStringSetting(ctx, "scheduledPruneInterval", "0 0 0 * * *"),+ GitopsSyncInterval: s.settings.GetStringSetting(ctx, "gitopsSyncInterval", "0 */5 * * * *"),}}@@ -57,7 +62,7 @@ func (s *JobService) UpdateJobSchedules(ctx context.Context, updates jobscheduleif s == nil || s.db == nil || s.settings == nil {return jobschedule.Config{}, fmt.Errorf("job service not initialized")}- if s.cfg != nil && (s.cfg.UIConfigurationDisabled || s.cfg.AgentMode) {+ if s.cfg != nil && s.cfg.UIConfigurationDisabled {return jobschedule.Config{}, fmt.Errorf("job schedule updates are disabled")}@@ -83,9 +88,21 @@ func (s *JobService) UpdateJobSchedules(ctx context.Context, updates jobscheduleif err := validate("analyticsHeartbeatInterval", updates.AnalyticsHeartbeatInterval); err != nil {return jobschedule.Config{}, err}+ if err := validate("autoUpdateInterval", updates.AutoUpdateInterval); err != nil {+ return jobschedule.Config{}, err+ }+ if err := validate("pollingInterval", updates.PollingInterval); err != nil {+ return jobschedule.Config{}, err+ }+ if err := validate("scheduledPruneInterval", updates.ScheduledPruneInterval); err != nil {+ return jobschedule.Config{}, err+ }+ if err := validate("gitopsSyncInterval", updates.GitopsSyncInterval); err != nil {+ return jobschedule.Config{}, err+ }changed := false- changedKeys := make([]string, 0, 3)+ changedKeys := make([]string, 0, 7)upsert := func(tx *gorm.DB, key string, v *string, currentVal string) error {if v == nil {return nil@@ -108,6 +125,18 @@ func (s *JobService) UpdateJobSchedules(ctx context.Context, updates jobscheduleif err := upsert(tx, "analyticsHeartbeatInterval", updates.AnalyticsHeartbeatInterval, current.AnalyticsHeartbeatInterval); err != nil {return err}+ if err := upsert(tx, "autoUpdateInterval", updates.AutoUpdateInterval, current.AutoUpdateInterval); err != nil {+ return err+ }+ if err := upsert(tx, "pollingInterval", updates.PollingInterval, current.PollingInterval); err != nil {+ return err+ }+ if err := upsert(tx, "scheduledPruneInterval", updates.ScheduledPruneInterval, current.ScheduledPruneInterval); err != nil {+ return err+ }+ if err := upsert(tx, "gitopsSyncInterval", updates.GitopsSyncInterval, current.GitopsSyncInterval); err != nil {+ return err+ }return nil})if err != nil {@@ -146,6 +175,11 @@ func (s *JobService) ListJobs(ctx context.Context) (*jobschedule.JobListResponsejobs = append(jobs, jobStatus)}+ // Sort jobs by ID to ensure stable UI order+ sort.Slice(jobs, func(i, j int) bool {+ return jobs[i].ID < jobs[j].ID+ })+isAgent := s.cfg != nil && s.cfg.AgentModereturn &jobschedule.JobListResponse{diff --git a/frontend/src/lib/components/job-card/job-card.svelte b/frontend/src/lib/components/job-card/job-card.svelteindex a4ebca728..34cc4b3b5 100644--- a/frontend/src/lib/components/job-card/job-card.svelte+++ b/frontend/src/lib/components/job-card/job-card.svelte@@ -14,6 +14,7 @@let {job,+ environmentId = '0',isAgent = false,onScheduleUpdate,children,@@ -21,6 +22,7 @@headerAccessory}: {job: JobStatus;+ environmentId?: string;isAgent?: boolean;onScheduleUpdate?: () => void;children?: Snippet;@@ -47,7 +49,7 @@if (!canRun) return;isRunning = true;- const result = await tryCatch(jobScheduleService.runJob(job.id));+ const result = await tryCatch(jobScheduleService.runJob(job.id, environmentId));isRunning = false;if (result.error || !result.data?.success) {@@ -137,5 +139,5 @@</Card.Root>{#if showScheduleDialog}- <JobScheduleDialog {job} bind:open={showScheduleDialog} onUpdate={handleScheduleUpdated} />+ <JobScheduleDialog {job} {environmentId} bind:open={showScheduleDialog} onUpdate={handleScheduleUpdated} />{/if}diff --git a/frontend/src/lib/components/job-card/job-schedule-dialog.svelte b/frontend/src/lib/components/job-card/job-schedule-dialog.svelteindex fb303e869..8860a09f0 100644--- a/frontend/src/lib/components/job-card/job-schedule-dialog.svelte+++ b/frontend/src/lib/components/job-card/job-schedule-dialog.svelte@@ -11,10 +11,12 @@let {job,+ environmentId = '0',open = $bindable(false),onUpdate}: {job: JobStatus;+ environmentId?: string;open?: boolean;onUpdate?: () => void;} = $props();@@ -58,7 +60,7 @@isLoading = true;const update = { [job.settingsKey]: scheduleValue };- const result = await tryCatch(jobScheduleService.updateJobSchedules(update));+ const result = await tryCatch(jobScheduleService.updateJobSchedules(update, environmentId));isLoading = false;if (result.error) {diff --git a/frontend/src/lib/services/job-schedule-service.ts b/frontend/src/lib/services/job-schedule-service.tsindex c89fdb3b9..77a8dd361 100644--- a/frontend/src/lib/services/job-schedule-service.ts+++ b/frontend/src/lib/services/job-schedule-service.ts@@ -2,20 +2,20 @@ import BaseAPIService from './api-service';import type { JobSchedules, JobSchedulesUpdate, JobListResponse, JobRunResponse } from '$lib/types/job-schedule.type';class JobScheduleService extends BaseAPIService {- async getJobSchedules(): Promise<JobSchedules> {- return this.handleResponse(this.api.get('/job-schedules'));+ async getJobSchedules(environmentId: string = '0'): Promise<JobSchedules> {+ return this.handleResponse(this.api.get(`/environments/${environmentId}/job-schedules`));}- async updateJobSchedules(update: JobSchedulesUpdate): Promise<JobSchedules> {- return this.handleResponse(this.api.put('/job-schedules', update));+ async updateJobSchedules(update: JobSchedulesUpdate, environmentId: string = '0'): Promise<JobSchedules> {+ return this.handleResponse(this.api.put(`/environments/${environmentId}/job-schedules`, update));}- async listJobs(): Promise<JobListResponse> {- return this.handleResponse(this.api.get('/jobs'));+ async listJobs(environmentId: string = '0'): Promise<JobListResponse> {+ return this.handleResponse(this.api.get(`/environments/${environmentId}/jobs`));}- async runJob(jobId: string): Promise<JobRunResponse> {- return this.handleResponse(this.api.post(`/jobs/${jobId}/run`));+ async runJob(jobId: string, environmentId: string = '0'): Promise<JobRunResponse> {+ return this.handleResponse(this.api.post(`/environments/${environmentId}/jobs/${jobId}/run`));}}diff --git a/frontend/src/lib/types/job-schedule.type.ts b/frontend/src/lib/types/job-schedule.type.tsindex ed769508c..02b9697d5 100644--- a/frontend/src/lib/types/job-schedule.type.ts+++ b/frontend/src/lib/types/job-schedule.type.ts@@ -2,6 +2,10 @@ export type JobSchedules = {environmentHealthInterval: string;eventCleanupInterval: string;analyticsHeartbeatInterval: string;+ autoUpdateInterval: string;+ pollingInterval: string;+ scheduledPruneInterval: string;+ gitopsSyncInterval: string;};export type JobSchedulesUpdate = Partial<JobSchedules>;diff --git a/frontend/src/routes/(app)/environments/[id]/+page.svelte b/frontend/src/routes/(app)/environments/[id]/+page.svelteindex 014f7d190..aedddecf8 100644--- a/frontend/src/routes/(app)/environments/[id]/+page.svelte+++ b/frontend/src/routes/(app)/environments/[id]/+page.svelte@@ -38,40 +38,54 @@let activeTab = $state('details');- const tabItems: TabItem[] = [- {- value: 'details',- label: m.environments_overview_title(),- icon: EnvironmentsIcon- },- {- value: 'general',- label: m.general_title(),- icon: SettingsIcon- },- {- value: 'docker',- label: m.environments_docker_settings_title(),- icon: DockerBrandIcon- },- {- value: 'jobs',- label: m.jobs_title(),- icon: JobsIcon- },- {- value: 'agent',- label: m.environments_agent_config_title(),- icon: ApiKeyIcon- },- {+ const tabItems = $derived.by((): TabItem[] => {+ const items: TabItem[] = [+ {+ value: 'details',+ label: m.environments_overview_title(),+ icon: EnvironmentsIcon+ },+ {+ value: 'general',+ label: m.general_title(),+ icon: SettingsIcon+ },+ {+ value: 'docker',+ label: m.environments_docker_settings_title(),+ icon: DockerBrandIcon+ },+ {+ value: 'jobs',+ label: m.jobs_title(),+ icon: JobsIcon+ }+ ];++ if (environment.id !== '0') {+ items.push({+ value: 'agent',+ label: m.environments_agent_config_title(),+ icon: ApiKeyIcon+ });+ }++ items.push({value: 'gitops',label: m.git_syncs_title(),icon: GitBranchIcon- }- ];+ });++ return items;+ });++ const tabValues = $derived(new Set(tabItems.map((tab) => tab.value)));- const tabValues = new Set(tabItems.map((tab) => tab.value));+ $effect(() => {+ if (!tabValues.has(activeTab)) {+ activeTab = 'details';+ }+ });$effect(() => {const tabFromUrl = page.url.searchParams.get('tab');diff --git a/frontend/src/routes/(app)/environments/[id]/components/JobsTab.svelte b/frontend/src/routes/(app)/environments/[id]/components/JobsTab.svelteindex 688412f39..03c25b6cf 100644--- a/frontend/src/routes/(app)/environments/[id]/components/JobsTab.svelte+++ b/frontend/src/routes/(app)/environments/[id]/components/JobsTab.svelte@@ -14,6 +14,7 @@let jobsResponse = $state<JobListResponse | null>(null);let isLoading = $state(true);+ let isFirstLoad = $state(true);let error = $state<string | null>(null);function resolveSettingsUrl(job: JobStatus, prereq: JobPrerequisite): string | undefined {@@ -35,12 +36,18 @@}async function loadJobs() {- isLoading = true;- const result = await tryCatch(jobScheduleService.listJobs());+ if (isFirstLoad) {+ isLoading = true;+ }++ const result = await tryCatch(jobScheduleService.listJobs(environmentId));isLoading = false;+ isFirstLoad = false;if (result.error) {- error = result.error.message;+ if (!jobsResponse) {+ error = result.error.message;+ }return;}@@ -108,11 +115,11 @@</div></Card.Header><Card.Content class="p-4 sm:p-6">- {#if isLoading}+ {#if isLoading && !jobsResponse}<div class="flex h-32 items-center justify-center"><Spinner class="size-8" /></div>- {:else if error}+ {:else if error && !jobsResponse}<div class="border-destructive/50 bg-destructive/10 text-destructive rounded-lg border p-4">{error}</div>@@ -129,6 +136,7 @@{#each categoryJobs as job (job.id)}<JobCard{job}+ {environmentId}isAgent={jobsResponse.isAgent}onScheduleUpdate={loadJobs}enabledOverride={getEnabledOverride(job)}diff --git a/types/jobschedule/jobschedule.go b/types/jobschedule/jobschedule.goindex 9bf3cacc2..291d30a9d 100644--- a/types/jobschedule/jobschedule.go+++ b/types/jobschedule/jobschedule.go@@ -10,6 +10,10 @@ type Config struct {EnvironmentHealthInterval string `json:"environmentHealthInterval"`EventCleanupInterval string `json:"eventCleanupInterval"`AnalyticsHeartbeatInterval string `json:"analyticsHeartbeatInterval"`+ AutoUpdateInterval string `json:"autoUpdateInterval"`+ PollingInterval string `json:"pollingInterval"`+ ScheduledPruneInterval string `json:"scheduledPruneInterval"`+ GitopsSyncInterval string `json:"gitopsSyncInterval"`}// Update is used to update job schedule intervals (in minutes).@@ -19,6 +23,10 @@ type Update struct {EnvironmentHealthInterval *string `json:"environmentHealthInterval,omitempty"`EventCleanupInterval *string `json:"eventCleanupInterval,omitempty"`AnalyticsHeartbeatInterval *string `json:"analyticsHeartbeatInterval,omitempty"`+ AutoUpdateInterval *string `json:"autoUpdateInterval,omitempty"`+ PollingInterval *string `json:"pollingInterval,omitempty"`+ ScheduledPruneInterval *string `json:"scheduledPruneInterval,omitempty"`+ GitopsSyncInterval *string `json:"gitopsSyncInterval,omitempty"`}// JobStatus represents the current status and metadata for a background job.