Skip to content

Modern Docker Management, Designed for Everyone

feat: automated docker api re-negotiation (#2471)

Kyle Mendell8adaebeb5471
diff --git a/backend/internal/bootstrap/jobs_bootstrap.go b/backend/internal/bootstrap/jobs_bootstrap.go
index a23d44ac8..e76d544e6 100644
--- a/backend/internal/bootstrap/jobs_bootstrap.go
+++ b/backend/internal/bootstrap/jobs_bootstrap.go
@@ -23,6 +23,9 @@ func registerJobs(appCtx context.Context, newScheduler *pkg_scheduler.JobSchedul
newScheduler.RegisterJob(environmentHealthJob)
}
+ dockerClientRefreshJob := pkg_scheduler.NewDockerClientRefreshJob(appServices.Docker, appServices.Settings)
+ newScheduler.RegisterJob(dockerClientRefreshJob)
+
analyticsJob := pkg_scheduler.NewAnalyticsJob(appServices.Settings, appServices.KV, nil, appConfig)
newScheduler.RegisterJob(analyticsJob)
// Send initial heartbeat on startup without blocking bootstrap.
@@ -55,6 +58,7 @@ func registerJobs(appCtx context.Context, newScheduler *pkg_scheduler.JobSchedul
newScheduler,
imagePollingJob,
autoUpdateJob,
+ dockerClientRefreshJob,
environmentHealthJob,
eventCleanupJob,
scheduledPruneJob,
@@ -72,6 +76,7 @@ func setupJobScheduleCallbacks(
newScheduler *pkg_scheduler.JobScheduler,
imagePollingJob *pkg_scheduler.ImagePollingJob,
autoUpdateJob *pkg_scheduler.AutoUpdateJob,
+ dockerClientRefreshJob *pkg_scheduler.DockerClientRefreshJob,
environmentHealthJob *pkg_scheduler.EnvironmentHealthJob,
eventCleanupJob *pkg_scheduler.EventCleanupJob,
scheduledPruneJob *pkg_scheduler.ScheduledPruneJob,
@@ -93,6 +98,7 @@ func setupJobScheduleCallbacks(
newScheduler,
imagePollingJob,
autoUpdateJob,
+ dockerClientRefreshJob,
environmentHealthJob,
eventCleanupJob,
scheduledPruneJob,
@@ -111,6 +117,7 @@ func handleJobScheduleChangeInternal(
newScheduler *pkg_scheduler.JobScheduler,
imagePollingJob *pkg_scheduler.ImagePollingJob,
autoUpdateJob *pkg_scheduler.AutoUpdateJob,
+ dockerClientRefreshJob *pkg_scheduler.DockerClientRefreshJob,
environmentHealthJob *pkg_scheduler.EnvironmentHealthJob,
eventCleanupJob *pkg_scheduler.EventCleanupJob,
scheduledPruneJob *pkg_scheduler.ScheduledPruneJob,
@@ -127,6 +134,10 @@ func handleJobScheduleChangeInternal(
if err := newScheduler.RescheduleJob(ctx, autoUpdateJob); err != nil {
slog.WarnContext(ctx, "Failed to reschedule auto-update job", "error", err)
}
+ case "dockerClientRefreshInterval":
+ if err := newScheduler.RescheduleJob(ctx, dockerClientRefreshJob); err != nil {
+ slog.WarnContext(ctx, "Failed to reschedule docker-client-refresh job", "error", err)
+ }
case "environmentHealthInterval":
if appConfig.AgentMode {
return
diff --git a/backend/internal/configschema/schema_test.go b/backend/internal/configschema/schema_test.go
index 5986e9608..3c26ca650 100644
--- a/backend/internal/configschema/schema_test.go
+++ b/backend/internal/configschema/schema_test.go
@@ -269,6 +269,7 @@ var expectedSettingOverrideKeys = []string{
"depotToken",
"diskUsagePath",
"dockerApiTimeout",
+ "dockerClientRefreshInterval",
"dockerHost",
"dockerImagePullTimeout",
"enableGravatar",
diff --git a/backend/internal/models/settings.go b/backend/internal/models/settings.go
index c3ca1ae91..2d8face74 100644
--- a/backend/internal/models/settings.go
+++ b/backend/internal/models/settings.go
@@ -87,6 +87,7 @@ type Settings struct {
AutoUpdateExcludedContainers SettingVariable `key:"autoUpdateExcludedContainers" meta:"label=Excluded Containers;type=text;keywords=exclude,containers,ignore,skip;category=internal;description=Comma-separated list of containers to exclude from auto-update"`
PollingEnabled SettingVariable `key:"pollingEnabled" meta:"label=Enable Polling;type=boolean;keywords=polling,check,monitor,watch,scan,detection,automatic;category=internal;description=Enable automatic checking for image updates"`
PollingInterval SettingVariable `key:"pollingInterval" meta:"label=Polling Interval;type=cron;keywords=interval,frequency,schedule,time,minutes,period,delay;category=internal;description=How often to check for image updates (cron expression)"`
+ DockerClientRefreshInterval SettingVariable `key:"dockerClientRefreshInterval" meta:"label=Docker Client Refresh Interval;type=cron;keywords=docker,client,refresh,daemon,api,version,reconnect,renegotiate,schedule;category=internal;description=How often to refresh the cached Docker client API version (cron expression)"`
EventCleanupInterval SettingVariable `key:"eventCleanupInterval" meta:"label=Event Cleanup Interval;type=cron;keywords=events,cleanup,retention,interval,frequency,schedule,history,logs,jobs;description=How often to delete old events (cron expression)"`
AutoInjectEnv SettingVariable `key:"autoInjectEnv" meta:"label=Auto Inject Env Variables;type=boolean;keywords=auto,inject,env,environment,variables,interpolation;category=internal;description=Automatically inject project .env variables into all containers (default: false)"`
// Deprecated: Use the granular prune mode settings instead.
diff --git a/backend/internal/services/docker_client_service.go b/backend/internal/services/docker_client_service.go
index 4042ea20e..d551246cc 100644
--- a/backend/internal/services/docker_client_service.go
+++ b/backend/internal/services/docker_client_service.go
@@ -28,6 +28,8 @@ type DockerClientService struct {
config *config.Config
settingsService *SettingsService
client *client.Client
+ clientVersion string
+ clientLastProbe time.Time
mu sync.Mutex
}
@@ -40,31 +42,46 @@ func NewDockerClientService(db *database.DB, cfg *config.Config, settingsService
}
func newDockerClientInternal(ctx context.Context, host string) (*client.Client, error) {
+ apiVersion, err := detectDockerAPIVersionInternal(ctx, host)
+ if err != nil {
+ return nil, err
+ }
+
+ configuredClient, err := newDockerClientWithAPIVersionInternal(host, apiVersion)
+ if err != nil {
+ return nil, err
+ }
+
+ return configuredClient, nil
+}
+
+func detectDockerAPIVersionInternal(ctx context.Context, host string) (string, error) {
probeClient, err := client.New(
client.WithHost(host),
)
if err != nil {
- return nil, fmt.Errorf("failed to create Docker probe client: %w", err)
+ return "", fmt.Errorf("failed to create Docker probe client: %w", err)
}
+ defer closeDockerClientInternal(probeClient, "failed to close probe Docker client")
ctx, cancel := context.WithTimeout(ctx, dockerClientNegotiationTimeout)
defer cancel()
pingResult, err := probeClient.Ping(ctx, client.PingOptions{})
if err != nil {
- if closeErr := probeClient.Close(); closeErr != nil {
- slog.Warn("failed to close probe Docker client after ping failure", "error", closeErr)
- }
- return nil, fmt.Errorf("failed to negotiate Docker API version: %w", err)
+ return "", fmt.Errorf("failed to negotiate Docker API version: %w", err)
}
apiVersion := strings.TrimSpace(pingResult.APIVersion)
if apiVersion == "" {
- return probeClient, nil
+ slog.WarnContext(ctx, "Docker ping did not report an API version, using minimum supported client API version", "api_version", client.MinAPIVersion)
+ return client.MinAPIVersion, nil
}
- _ = probeClient.Close()
+ return apiVersion, nil
+}
+func newDockerClientWithAPIVersionInternal(host string, apiVersion string) (*client.Client, error) {
configuredClient, err := client.New(
client.WithHost(host),
client.WithAPIVersion(apiVersion),
@@ -76,23 +93,86 @@ func newDockerClientInternal(ctx context.Context, host string) (*client.Client,
return configuredClient, nil
}
+func closeDockerClientInternal(cli *client.Client, message string) {
+ if cli == nil {
+ return
+ }
+
+ if err := cli.Close(); err != nil {
+ slog.Warn(message, "error", err)
+ }
+}
+
// GetClient returns a singleton Docker client instance.
// It initializes the client on the first call.
func (s *DockerClientService) GetClient(ctx context.Context) (*client.Client, error) {
s.mu.Lock()
- defer s.mu.Unlock()
-
if s.client != nil {
- return s.client, nil
+ cli := s.client
+ s.mu.Unlock()
+ return cli, nil
}
+ s.mu.Unlock()
cli, err := newDockerClientInternal(ctx, s.config.DockerHost)
if err != nil {
return nil, fmt.Errorf("failed to create Docker client: %w", err)
}
+ s.mu.Lock()
+ if s.client != nil {
+ existingClient := s.client
+ s.mu.Unlock()
+ closeDockerClientInternal(cli, "failed to close unused Docker client after concurrent initialization")
+ return existingClient, nil
+ }
+
s.client = cli
- return s.client, nil
+ s.clientVersion = cli.ClientVersion()
+ s.clientLastProbe = time.Now()
+ s.mu.Unlock()
+
+ return cli, nil
+}
+
+// RefreshClient probes the Docker daemon and recreates the cached client when
+// the daemon's effective API version changed.
+func (s *DockerClientService) RefreshClient(ctx context.Context) error {
+ apiVersion, err := detectDockerAPIVersionInternal(ctx, s.config.DockerHost)
+ if err != nil {
+ return fmt.Errorf("failed to refresh Docker client: %w", err)
+ }
+
+ s.mu.Lock()
+ if s.client != nil && apiVersion == s.clientVersion {
+ s.clientLastProbe = time.Now()
+ s.mu.Unlock()
+ return nil
+ }
+ s.mu.Unlock()
+
+ cli, err := newDockerClientWithAPIVersionInternal(s.config.DockerHost, apiVersion)
+ if err != nil {
+ return fmt.Errorf("failed to refresh Docker client: %w", err)
+ }
+
+ s.mu.Lock()
+ if s.client != nil && apiVersion == s.clientVersion {
+ s.clientLastProbe = time.Now()
+ s.mu.Unlock()
+ closeDockerClientInternal(cli, "failed to close unused Docker client after concurrent refresh")
+ return nil
+ }
+
+ oldClient := s.client
+ s.client = cli
+ s.clientVersion = apiVersion
+ s.clientLastProbe = time.Now()
+ s.mu.Unlock()
+
+ closeDockerClientInternal(oldClient, "failed to close replaced Docker client")
+
+ return nil
}
// DockerHost returns the configured DOCKER_HOST value.
diff --git a/backend/internal/services/docker_client_service_test.go b/backend/internal/services/docker_client_service_test.go
index be3266803..6f8dafb07 100644
--- a/backend/internal/services/docker_client_service_test.go
+++ b/backend/internal/services/docker_client_service_test.go
@@ -2,39 +2,169 @@ package services
import (
"context"
+ "net"
"net/http"
"net/http/httptest"
+ "sync/atomic"
"testing"
+ "time"
+ "github.com/getarcaneapp/arcane/backend/internal/config"
"github.com/moby/moby/api/types/container"
"github.com/moby/moby/api/types/image"
+ "github.com/moby/moby/client"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
-func TestNewDockerClient_UsesConfiguredHostAndPinsServerAPIVersion(t *testing.T) {
+func TestNewDockerClient_PinsEffectiveAPIVersion(t *testing.T) {
t.Setenv("DOCKER_API_VERSION", "1.54")
t.Setenv("DOCKER_HOST", "tcp://docker-from-env:2375")
- server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ tests := []struct {
+ name string
+ pingAPIVersion string
+ expectedVersion string
+ }{
+ {
+ name: "uses server API version",
+ pingAPIVersion: "1.41",
+ expectedVersion: "1.41",
+ },
+ {
+ name: "falls back to minimum API version when ping version is empty",
+ pingAPIVersion: "",
+ expectedVersion: client.MinAPIVersion,
+ },
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ server := newDockerPingTestServerInternal(t, tt.pingAPIVersion)
+
+ cli, err := newDockerClientInternal(context.Background(), server.URL)
+ require.NoError(t, err)
+ t.Cleanup(func() {
+ _ = cli.Close()
+ })
+
+ assert.Equal(t, server.URL, cli.DaemonHost())
+ assert.Equal(t, tt.expectedVersion, cli.ClientVersion())
+ assert.NotEqual(t, client.MaxAPIVersion, cli.ClientVersion())
+ })
+ }
+}
+
+func TestDockerClientService_GetClientReturnsCachedClientUntilRefresh(t *testing.T) {
+ server := newDockerPingTestServerInternal(t, "1.41")
+ svc := newDockerClientServiceForTestInternal(server.URL)
+
+ firstClient, err := svc.GetClient(context.Background())
+ require.NoError(t, err)
+ t.Cleanup(func() {
+ _ = firstClient.Close()
+ })
+
+ secondClient, err := svc.GetClient(context.Background())
+ require.NoError(t, err)
+
+ assert.Same(t, firstClient, secondClient)
+ assert.Equal(t, "1.41", secondClient.ClientVersion())
+}
+
+func TestDockerClientService_RefreshClientRecreatesCachedClientAfterAPIVersionChange(t *testing.T) {
+ apiVersion := atomic.Value{}
+ apiVersion.Store("1.41")
+ server := newDockerPingTestServerWithVersionInternal(t, func() string {
+ return apiVersion.Load().(string)
+ })
+ svc := newDockerClientServiceForTestInternal(server.URL)
+
+ firstClient, err := svc.GetClient(context.Background())
+ require.NoError(t, err)
+ t.Cleanup(func() {
+ _ = firstClient.Close()
+ })
+ assert.Equal(t, "1.41", firstClient.ClientVersion())
+
+ apiVersion.Store("1.42")
+
+ err = svc.RefreshClient(context.Background())
+ require.NoError(t, err)
+ secondClient := svc.client
+ t.Cleanup(func() {
+ _ = secondClient.Close()
+ })
+
+ assert.NotSame(t, firstClient, secondClient)
+ assert.Equal(t, "1.42", secondClient.ClientVersion())
+}
+
+func TestDockerClientService_RefreshClientClosesOldCachedClientWhenReplaced(t *testing.T) {
+ var oldServerClosedConnections atomic.Int32
+ oldServer := newDockerPingTestServerWithConnStateInternal(t, "1.41", func(_ net.Conn, state http.ConnState) {
+ if state == http.StateClosed {
+ oldServerClosedConnections.Add(1)
+ }
+ })
+ newServer := newDockerPingTestServerInternal(t, "1.42")
+ svc := newDockerClientServiceForTestInternal(oldServer.URL)
+
+ firstClient, err := svc.GetClient(context.Background())
+ require.NoError(t, err)
+ t.Cleanup(func() {
+ _ = firstClient.Close()
+ })
+
+ _, err = firstClient.Ping(context.Background(), client.PingOptions{})
+ require.NoError(t, err)
+ closedBeforeReplace := oldServerClosedConnections.Load()
+
+ svc.config.DockerHost = newServer.URL
+
+ err = svc.RefreshClient(context.Background())
+ require.NoError(t, err)
+ secondClient := svc.client
+ t.Cleanup(func() {
+ _ = secondClient.Close()
+ })
+
+ require.Eventually(t, func() bool {
+ return oldServerClosedConnections.Load() > closedBeforeReplace
+ }, time.Second, 10*time.Millisecond)
+ assert.NotSame(t, firstClient, secondClient)
+ assert.Equal(t, "1.42", secondClient.ClientVersion())
+}
+
+func TestDockerClientService_RefreshClientProbeFailureKeepsCachedClient(t *testing.T) {
+ var failProbe atomic.Bool
+ server := newDockerPingTestServerWithHandlerInternal(t, func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path != "/_ping" {
http.NotFound(w, r)
return
}
-
+ if failProbe.Load() {
+ w.WriteHeader(http.StatusForbidden)
+ return
+ }
w.Header().Set("Api-Version", "1.41")
w.WriteHeader(http.StatusOK)
- }))
- t.Cleanup(server.Close)
+ })
+ svc := newDockerClientServiceForTestInternal(server.URL)
- cli, err := newDockerClientInternal(context.Background(), server.URL)
+ firstClient, err := svc.GetClient(context.Background())
require.NoError(t, err)
t.Cleanup(func() {
- _ = cli.Close()
+ _ = firstClient.Close()
})
- assert.Equal(t, server.URL, cli.DaemonHost())
- assert.Equal(t, "1.41", cli.ClientVersion())
+ failProbe.Store(true)
+
+ err = svc.RefreshClient(context.Background())
+ require.Error(t, err)
+ assert.Same(t, firstClient, svc.client)
+ assert.Equal(t, "1.41", svc.clientVersion)
+ assert.False(t, svc.clientLastProbe.IsZero())
}
func TestCountImageUsage_UsesContainerImageIDs(t *testing.T) {
@@ -65,3 +195,59 @@ func TestCountImageUsage_NoImages(t *testing.T) {
assert.Equal(t, 0, unused)
assert.Equal(t, 0, total)
}
+
+func newDockerClientServiceForTestInternal(host string) *DockerClientService {
+ return NewDockerClientService(nil, &config.Config{DockerHost: host}, nil)
+}
+
+func newDockerPingTestServerInternal(t *testing.T, apiVersion string) *httptest.Server {
+ t.Helper()
+
+ return newDockerPingTestServerWithVersionInternal(t, func() string {
+ return apiVersion
+ })
+}
+
+func newDockerPingTestServerWithVersionInternal(t *testing.T, apiVersion func() string) *httptest.Server {
+ t.Helper()
+
+ return newDockerPingTestServerWithHandlerInternal(t, func(w http.ResponseWriter, r *http.Request) {
+ if r.URL.Path != "/_ping" {
+ http.NotFound(w, r)
+ return
+ }
+
+ if version := apiVersion(); version != "" {
+ w.Header().Set("Api-Version", version)
+ }
+ w.WriteHeader(http.StatusOK)
+ })
+}
+
+func newDockerPingTestServerWithConnStateInternal(t *testing.T, apiVersion string, connState func(net.Conn, http.ConnState)) *httptest.Server {
+ t.Helper()
+
+ server := httptest.NewUnstartedServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ if r.URL.Path != "/_ping" {
+ http.NotFound(w, r)
+ return
+ }
+
+ w.Header().Set("Api-Version", apiVersion)
+ w.WriteHeader(http.StatusOK)
+ }))
+ server.Config.ConnState = connState
+ server.Start()
+ t.Cleanup(server.Close)
+
+ return server
+}
+
+func newDockerPingTestServerWithHandlerInternal(t *testing.T, handler http.HandlerFunc) *httptest.Server {
+ t.Helper()
+
+ server := httptest.NewServer(handler)
+ t.Cleanup(server.Close)
+
+ return server
+}
diff --git a/backend/internal/services/job_service.go b/backend/internal/services/job_service.go
index f95dc1919..f7e589d34 100644
--- a/backend/internal/services/job_service.go
+++ b/backend/internal/services/job_service.go
@@ -54,14 +54,15 @@ func (s *JobService) SetScheduler(scheduler JobRunner) {
func (s *JobService) GetJobSchedules(ctx context.Context) jobschedule.Config {
// Use SettingsService cache for fast reads.
return jobschedule.Config{
- EnvironmentHealthInterval: s.settings.GetStringSetting(ctx, "environmentHealthInterval", "0 */2 * * * *"),
- EventCleanupInterval: s.settings.GetStringSetting(ctx, "eventCleanupInterval", "0 0 */6 * * *"),
- 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 */1 * * * *"),
- VulnerabilityScanInterval: s.settings.GetStringSetting(ctx, "vulnerabilityScanInterval", "0 0 0 * * *"),
- AutoHealInterval: s.settings.GetStringSetting(ctx, "autoHealInterval", "*/30 * * * * *"),
+ EnvironmentHealthInterval: s.settings.GetStringSetting(ctx, "environmentHealthInterval", "0 */2 * * * *"),
+ EventCleanupInterval: s.settings.GetStringSetting(ctx, "eventCleanupInterval", "0 0 */6 * * *"),
+ AutoUpdateInterval: s.settings.GetStringSetting(ctx, "autoUpdateInterval", "0 0 0 * * *"),
+ DockerClientRefreshInterval: s.settings.GetStringSetting(ctx, "dockerClientRefreshInterval", "*/30 * * * * *"),
+ PollingInterval: s.settings.GetStringSetting(ctx, "pollingInterval", "0 */15 * * * *"),
+ ScheduledPruneInterval: s.settings.GetStringSetting(ctx, "scheduledPruneInterval", "0 0 0 * * *"),
+ GitopsSyncInterval: s.settings.GetStringSetting(ctx, "gitopsSyncInterval", "0 */1 * * * *"),
+ VulnerabilityScanInterval: s.settings.GetStringSetting(ctx, "vulnerabilityScanInterval", "0 0 0 * * *"),
+ AutoHealInterval: s.settings.GetStringSetting(ctx, "autoHealInterval", "*/30 * * * * *"),
}
}
@@ -83,6 +84,7 @@ func (s *JobService) UpdateJobSchedules(ctx context.Context, updates jobschedule
{key: "environmentHealthInterval", current: current.EnvironmentHealthInterval, update: updates.EnvironmentHealthInterval},
{key: "eventCleanupInterval", current: current.EventCleanupInterval, update: updates.EventCleanupInterval},
{key: "autoUpdateInterval", current: current.AutoUpdateInterval, update: updates.AutoUpdateInterval},
+ {key: "dockerClientRefreshInterval", current: current.DockerClientRefreshInterval, update: updates.DockerClientRefreshInterval},
{key: "pollingInterval", current: current.PollingInterval, update: updates.PollingInterval},
{key: "scheduledPruneInterval", current: current.ScheduledPruneInterval, update: updates.ScheduledPruneInterval},
{key: "gitopsSyncInterval", current: current.GitopsSyncInterval, update: updates.GitopsSyncInterval},
@@ -102,7 +104,7 @@ func (s *JobService) UpdateJobSchedules(ctx context.Context, updates jobschedule
}
changed := false
- changedKeys := make([]string, 0, 7)
+ changedKeys := make([]string, 0, len(fields))
upsert := func(tx *gorm.DB, key string, v *string, currentVal string) error {
if v == nil {
return nil
@@ -224,14 +226,15 @@ func (s *JobService) getJobScheduleInternal(ctx context.Context, meta meta.JobMe
}
defaultSchedules := map[string]string{
- "environmentHealthInterval": "0 */2 * * * *",
- "eventCleanupInterval": "0 0 */6 * * *",
- "autoUpdateInterval": "0 0 0 * * *",
- "pollingInterval": "0 */15 * * * *",
- "scheduledPruneInterval": "0 0 0 * * *",
- "gitopsSyncInterval": "0 */1 * * * *",
- "vulnerabilityScanInterval": "0 0 0 * * *",
- "autoHealInterval": "*/30 * * * * *",
+ "environmentHealthInterval": "0 */2 * * * *",
+ "eventCleanupInterval": "0 0 */6 * * *",
+ "autoUpdateInterval": "0 0 0 * * *",
+ "dockerClientRefreshInterval": "*/30 * * * * *",
+ "pollingInterval": "0 */15 * * * *",
+ "scheduledPruneInterval": "0 0 0 * * *",
+ "gitopsSyncInterval": "0 */1 * * * *",
+ "vulnerabilityScanInterval": "0 0 0 * * *",
+ "autoHealInterval": "*/30 * * * * *",
}
defaultSchedule := defaultSchedules[meta.SettingsKey]
diff --git a/backend/internal/services/job_service_test.go b/backend/internal/services/job_service_test.go
index fabb7cfc3..10c2aa243 100644
--- a/backend/internal/services/job_service_test.go
+++ b/backend/internal/services/job_service_test.go
@@ -22,6 +22,19 @@ func TestJobService_GetJobSchedules_DefaultGitOpsInterval(t *testing.T) {
require.Equal(t, "0 */1 * * * *", cfg.GitopsSyncInterval)
}
+func TestJobService_GetJobSchedules_DefaultDockerClientRefreshInterval(t *testing.T) {
+ ctx := context.Background()
+ db := setupSettingsTestDB(t)
+
+ settingsSvc, err := NewSettingsService(ctx, db)
+ require.NoError(t, err)
+
+ jobSvc := NewJobService(db, settingsSvc, &config.Config{})
+ cfg := jobSvc.GetJobSchedules(ctx)
+
+ require.Equal(t, "*/30 * * * * *", cfg.DockerClientRefreshInterval)
+}
+
func TestJobService_ListJobs_AnalyticsHeartbeatIsManagedInternally(t *testing.T) {
ctx := context.Background()
db := setupSettingsTestDB(t)
@@ -58,6 +71,25 @@ func TestJobService_ListJobs_IncludesDisabledAutoHealJob(t *testing.T) {
require.Equal(t, "autoHealInterval", autoHealJob.SettingsKey)
}
+func TestJobService_ListJobs_IncludesDockerClientRefreshJob(t *testing.T) {
+ ctx := context.Background()
+ db := setupSettingsTestDB(t)
+
+ settingsSvc, err := NewSettingsService(ctx, db)
+ require.NoError(t, err)
+
+ jobSvc := NewJobService(db, settingsSvc, &config.Config{})
+ jobs, err := jobSvc.ListJobs(ctx)
+ require.NoError(t, err)
+
+ refreshJob := findJobStatusByIDInternal(t, jobs.Jobs, "docker-client-refresh")
+ require.True(t, refreshJob.Enabled)
+ require.True(t, refreshJob.CanRunManually)
+ require.Equal(t, "monitoring", refreshJob.Category)
+ require.Equal(t, "dockerClientRefreshInterval", refreshJob.SettingsKey)
+ require.Equal(t, "*/30 * * * * *", refreshJob.Schedule)
+}
+
func findJobStatusByIDInternal(t *testing.T, jobs []jobschedule.JobStatus, id string) jobschedule.JobStatus {
t.Helper()
diff --git a/backend/internal/services/settings_service.go b/backend/internal/services/settings_service.go
index 6b9555977..46a46a425 100644
--- a/backend/internal/services/settings_service.go
+++ b/backend/internal/services/settings_service.go
@@ -104,6 +104,7 @@ func DefaultSettingsConfig() *models.Settings {
AutoUpdateExcludedContainers: models.SettingVariable{Value: ""},
PollingEnabled: models.SettingVariable{Value: "true"},
PollingInterval: models.SettingVariable{Value: "0 0 * * * *"},
+ DockerClientRefreshInterval: models.SettingVariable{Value: "*/30 * * * * *"},
EventCleanupInterval: models.SettingVariable{Value: "0 0 */6 * * *"},
AutoInjectEnv: models.SettingVariable{Value: "false"},
PruneMode: models.SettingVariable{Value: "dangling"}, //nolint:staticcheck // Legacy prune setting is still seeded for migration compatibility.
diff --git a/backend/pkg/scheduler/docker_client_refresh_job.go b/backend/pkg/scheduler/docker_client_refresh_job.go
new file mode 100644
index 000000000..4fb1ec331
--- /dev/null
+++ b/backend/pkg/scheduler/docker_client_refresh_job.go
@@ -0,0 +1,55 @@
+package scheduler
+
+import (
+ "context"
+ "log/slog"
+
+ "github.com/getarcaneapp/arcane/backend/internal/services"
+ "github.com/robfig/cron/v3"
+)
+
+const DockerClientRefreshJobName = "docker-client-refresh"
+const dockerClientRefreshDefaultSchedule = "*/30 * * * * *"
+
+// DockerClientRefreshJob keeps the cached Docker client aligned with the daemon
+// API version after daemon restarts or upgrades.
+type DockerClientRefreshJob struct {
+ dockerClientService *services.DockerClientService
+ settingsService *services.SettingsService
+}
+
+// NewDockerClientRefreshJob creates the scheduled Docker client refresh job.
+func NewDockerClientRefreshJob(dockerClientService *services.DockerClientService, settingsService *services.SettingsService) *DockerClientRefreshJob {
+ return &DockerClientRefreshJob{
+ dockerClientService: dockerClientService,
+ settingsService: settingsService,
+ }
+}
+
+func (j *DockerClientRefreshJob) Name() string {
+ return DockerClientRefreshJobName
+}
+
+func (j *DockerClientRefreshJob) Schedule(ctx context.Context) string {
+ schedule := j.settingsService.GetStringSetting(ctx, "dockerClientRefreshInterval", dockerClientRefreshDefaultSchedule)
+ if schedule == "" {
+ schedule = dockerClientRefreshDefaultSchedule
+ }
+
+ parser := cron.NewParser(cron.Second | cron.Minute | cron.Hour | cron.Dom | cron.Month | cron.Dow)
+ if _, err := parser.Parse(schedule); err != nil {
+ slog.WarnContext(ctx, "Invalid cron expression for Docker client refresh, using default", "invalid_schedule", schedule, "error", err)
+ return dockerClientRefreshDefaultSchedule
+ }
+
+ return schedule
+}
+
+func (j *DockerClientRefreshJob) Run(ctx context.Context) {
+ if err := j.dockerClientService.RefreshClient(ctx); err != nil {
+ slog.WarnContext(ctx, "Docker client refresh failed", "error", err)
+ return
+ }
+
+ slog.DebugContext(ctx, "Docker client refresh completed")
+}
diff --git a/frontend/src/lib/types/job-schedule.type.ts b/frontend/src/lib/types/job-schedule.type.ts
index 14358b1d5..234624694 100644
--- a/frontend/src/lib/types/job-schedule.type.ts
+++ b/frontend/src/lib/types/job-schedule.type.ts
@@ -2,6 +2,7 @@ export type JobSchedules = {
environmentHealthInterval: string;
eventCleanupInterval: string;
autoUpdateInterval: string;
+ dockerClientRefreshInterval: string;
pollingInterval: string;
scheduledPruneInterval: string;
gitopsSyncInterval: string;
diff --git a/frontend/src/lib/types/settings.type.ts b/frontend/src/lib/types/settings.type.ts
index 5c59d7b36..8f03d803f 100644
--- a/frontend/src/lib/types/settings.type.ts
+++ b/frontend/src/lib/types/settings.type.ts
@@ -12,6 +12,7 @@ export type Settings = {
autoUpdateExcludedContainers?: string;
pollingEnabled: boolean;
pollingInterval: number;
+ dockerClientRefreshInterval?: string;
environmentHealthInterval: number;
defaultDeployPullPolicy: 'missing' | 'always' | 'never';
scheduledPruneEnabled?: boolean;
diff --git a/types/jobschedule/jobschedule.go b/types/jobschedule/jobschedule.go
index 2dd1fcdc5..26be0d808 100644
--- a/types/jobschedule/jobschedule.go
+++ b/types/jobschedule/jobschedule.go
@@ -7,28 +7,30 @@ import "time"
// All fields are in minutes.
// This makes conversion to time.Duration straightforward in the backend.
type Config struct {
- EnvironmentHealthInterval string `json:"environmentHealthInterval"`
- EventCleanupInterval string `json:"eventCleanupInterval"`
- AutoUpdateInterval string `json:"autoUpdateInterval"`
- PollingInterval string `json:"pollingInterval"`
- ScheduledPruneInterval string `json:"scheduledPruneInterval"`
- GitopsSyncInterval string `json:"gitopsSyncInterval"`
- VulnerabilityScanInterval string `json:"vulnerabilityScanInterval"`
- AutoHealInterval string `json:"autoHealInterval"`
+ EnvironmentHealthInterval string `json:"environmentHealthInterval"`
+ EventCleanupInterval string `json:"eventCleanupInterval"`
+ AutoUpdateInterval string `json:"autoUpdateInterval"`
+ DockerClientRefreshInterval string `json:"dockerClientRefreshInterval"`
+ PollingInterval string `json:"pollingInterval"`
+ ScheduledPruneInterval string `json:"scheduledPruneInterval"`
+ GitopsSyncInterval string `json:"gitopsSyncInterval"`
+ VulnerabilityScanInterval string `json:"vulnerabilityScanInterval"`
+ AutoHealInterval string `json:"autoHealInterval"`
}
// Update is used to update job schedule intervals (in minutes).
//
// Any nil field is ignored.
type Update struct {
- EnvironmentHealthInterval *string `json:"environmentHealthInterval,omitempty"`
- EventCleanupInterval *string `json:"eventCleanupInterval,omitempty"`
- AutoUpdateInterval *string `json:"autoUpdateInterval,omitempty"`
- PollingInterval *string `json:"pollingInterval,omitempty"`
- ScheduledPruneInterval *string `json:"scheduledPruneInterval,omitempty"`
- GitopsSyncInterval *string `json:"gitopsSyncInterval,omitempty"`
- VulnerabilityScanInterval *string `json:"vulnerabilityScanInterval,omitempty"`
- AutoHealInterval *string `json:"autoHealInterval,omitempty"`
+ EnvironmentHealthInterval *string `json:"environmentHealthInterval,omitempty"`
+ EventCleanupInterval *string `json:"eventCleanupInterval,omitempty"`
+ AutoUpdateInterval *string `json:"autoUpdateInterval,omitempty"`
+ DockerClientRefreshInterval *string `json:"dockerClientRefreshInterval,omitempty"`
+ PollingInterval *string `json:"pollingInterval,omitempty"`
+ ScheduledPruneInterval *string `json:"scheduledPruneInterval,omitempty"`
+ GitopsSyncInterval *string `json:"gitopsSyncInterval,omitempty"`
+ VulnerabilityScanInterval *string `json:"vulnerabilityScanInterval,omitempty"`
+ AutoHealInterval *string `json:"autoHealInterval,omitempty"`
}
// JobStatus represents the current status and metadata for a background job.
diff --git a/types/meta/job_metadata.go b/types/meta/job_metadata.go
index ec70e292a..67e278670 100644
--- a/types/meta/job_metadata.go
+++ b/types/meta/job_metadata.go
@@ -37,6 +37,17 @@ var jobMetadataRegistry = map[string]JobMetadata{
CanRunManually: true,
Prerequisites: []JobPrerequisiteMetadata{},
},
+ "docker-client-refresh": {
+ ID: "docker-client-refresh",
+ Name: "Docker Client Refresh",
+ Description: "Refreshes the cached Docker client API version after daemon restarts or upgrades",
+ Category: "monitoring",
+ SettingsKey: "dockerClientRefreshInterval",
+ ManagerOnly: false,
+ IsContinuous: false,
+ CanRunManually: true,
+ Prerequisites: []JobPrerequisiteMetadata{},
+ },
"event-cleanup": {
ID: "event-cleanup",
Name: "Event Cleanup",
diff --git a/types/settings/settings.go b/types/settings/settings.go
index f6851843d..64b6fd899 100644
--- a/types/settings/settings.go
+++ b/types/settings/settings.go
@@ -73,6 +73,11 @@ type Update struct {
// Required: false
PollingInterval *string `json:"pollingInterval,omitempty"`
+ // DockerClientRefreshInterval is the cron expression for refreshing the cached Docker client.
+ //
+ // Required: false
+ DockerClientRefreshInterval *string `json:"dockerClientRefreshInterval,omitempty"`
+
// AutoInjectEnv indicates if project .env variables should be automatically injected into all containers.
//
// Required: false