Skip to content

Modern Docker Management, Designed for Everyone

feat: prune idle volume browser helper containers (#2767)

Dimitri Dolgovd3b2795a631f
diff --git a/backend/internal/bootstrap/jobs_bootstrap.go b/backend/internal/bootstrap/jobs_bootstrap.go
index 429a1c3ce..56752020c 100644
--- a/backend/internal/bootstrap/jobs_bootstrap.go
+++ b/backend/internal/bootstrap/jobs_bootstrap.go
@@ -34,6 +34,9 @@ func registerJobs(appCtx context.Context, newScheduler *pkg_scheduler.JobSchedul
eventCleanupJob := pkg_scheduler.NewEventCleanupJob(appServices.Event, appServices.Settings)
newScheduler.RegisterJob(eventCleanupJob)
+ pruningVolumeHelperJob := pkg_scheduler.NewPruningVolumeHelperJob(appServices.Volume, appServices.Settings)
+ newScheduler.RegisterJob(pruningVolumeHelperJob)
+
expiredSessionsCleanupJob := pkg_scheduler.NewExpiredSessionsCleanupJob(appServices.Session, appServices.Settings)
newScheduler.RegisterJob(expiredSessionsCleanupJob)
diff --git a/backend/internal/configschema/schema_test.go b/backend/internal/configschema/schema_test.go
index 617b7df3f..e2c057487 100644
--- a/backend/internal/configschema/schema_test.go
+++ b/backend/internal/configschema/schema_test.go
@@ -367,6 +367,7 @@ var expectedSettingOverrideKeys = []string{
"trivyResourceLimitsEnabled",
"trivyScanTimeout",
"trivySecurityOpts",
+ "volumeBrowserHelperIdleTimeout",
"vulnerabilityScanEnabled",
"vulnerabilityScanInterval",
}
diff --git a/backend/internal/models/settings.go b/backend/internal/models/settings.go
index 8e5be4809..f2a98c519 100644
--- a/backend/internal/models/settings.go
+++ b/backend/internal/models/settings.go
@@ -107,31 +107,32 @@ type Settings struct {
// Deprecated: Use pruneNetworkMode instead.
ScheduledPruneNetworks SettingVariable `key:"scheduledPruneNetworks,deprecated" meta:"label=Legacy Scheduled Prune Networks;type=boolean;keywords=prune,networks,cleanup,maintenance,legacy;category=internal;description=Legacy boolean network prune flag retained for migration compatibility"`
// Deprecated: Use pruneBuildCacheMode instead.
- ScheduledPruneBuildCache SettingVariable `key:"scheduledPruneBuildCache,deprecated" meta:"label=Legacy Scheduled Prune Build Cache;type=boolean;keywords=prune,build cache,cleanup,maintenance,legacy;category=internal;description=Legacy boolean build cache prune flag retained for migration compatibility"`
- PruneContainerMode SettingVariable `key:"pruneContainerMode" meta:"label=Prune Containers;type=select;keywords=prune,containers,cleanup,maintenance,mode,older,stopped;category=internal;description=Select how containers should be pruned when the scheduled prune job runs"`
- PruneContainerUntil SettingVariable `key:"pruneContainerUntil" meta:"label=Container Age Filter;type=text;keywords=prune,containers,cleanup,maintenance,until,older,duration;category=internal;description=Duration threshold for scheduled container prune when mode is olderThan"`
- PruneImageMode SettingVariable `key:"pruneImageMode" meta:"label=Prune Images;type=select;keywords=prune,images,cleanup,maintenance,mode,dangling,all,older;category=internal;description=Select how images should be pruned when the scheduled prune job runs"`
- PruneImageUntil SettingVariable `key:"pruneImageUntil" meta:"label=Image Age Filter;type=text;keywords=prune,images,cleanup,maintenance,until,older,duration;category=internal;description=Duration threshold for scheduled image prune when mode is olderThan"`
- PruneVolumeMode SettingVariable `key:"pruneVolumeMode" meta:"label=Prune Volumes;type=select;keywords=prune,volumes,cleanup,maintenance,mode,anonymous,named;category=internal;description=Select how volumes should be pruned when the scheduled prune job runs"`
- PruneNetworkMode SettingVariable `key:"pruneNetworkMode" meta:"label=Prune Networks;type=select;keywords=prune,networks,cleanup,maintenance,mode,unused,older;category=internal;description=Select how networks should be pruned when the scheduled prune job runs"`
- PruneNetworkUntil SettingVariable `key:"pruneNetworkUntil" meta:"label=Network Age Filter;type=text;keywords=prune,networks,cleanup,maintenance,until,older,duration;category=internal;description=Duration threshold for scheduled network prune when mode is olderThan"`
- PruneBuildCacheMode SettingVariable `key:"pruneBuildCacheMode" meta:"label=Prune Build Cache;type=select;keywords=prune,build cache,cleanup,maintenance,mode,unused,all,older;category=internal;description=Select how build cache should be pruned when the scheduled prune job runs"`
- PruneBuildCacheUntil SettingVariable `key:"pruneBuildCacheUntil" meta:"label=Build Cache Age Filter;type=text;keywords=prune,build cache,cleanup,maintenance,until,older,duration;category=internal;description=Duration threshold for scheduled build cache prune when mode is olderThan"`
- AutoHealEnabled SettingVariable `key:"autoHealEnabled" meta:"label=Auto Heal;type=boolean;keywords=auto,heal,health,restart,unhealthy,recovery,container,healthcheck;category=internal;description=Automatically restart containers that become unhealthy"`
- AutoHealInterval SettingVariable `key:"autoHealInterval" meta:"label=Auto Heal Interval;type=cron;keywords=auto,heal,interval,frequency,schedule,health,jobs;description=How often to check container health (cron expression)" catmeta:"id=jobschedule"`
- AutoHealExcludedContainers SettingVariable `key:"autoHealExcludedContainers" meta:"label=Auto Heal Excluded Containers;type=text;keywords=auto,heal,exclude,containers,ignore,skip,health;category=internal;description=Comma-separated list of containers to exclude from auto-heal"`
- AutoHealMaxRestarts SettingVariable `key:"autoHealMaxRestarts" meta:"label=Auto Heal Max Restarts;type=number;keywords=auto,heal,max,restarts,limit,loop,protection;category=internal;description=Maximum auto-heal restarts per container within the restart window (default: 5)"`
- AutoHealRestartWindow SettingVariable `key:"autoHealRestartWindow" meta:"label=Auto Heal Restart Window;type=number;keywords=auto,heal,restart,window,minutes,cooldown,protection;category=internal;description=Time window in minutes for counting auto-heal restarts (default: 30)"`
- MaxImageUploadSize SettingVariable `key:"maxImageUploadSize" meta:"label=Max Image Upload Size;type=number;keywords=upload,size,limit,maximum,image,tar,file,megabytes,mb,storage;category=internal;description=Maximum size in MB for image archive uploads (default: 500)"`
- GitSyncMaxFiles SettingVariable `key:"gitSyncMaxFiles,envOverride" meta:"label=Git Sync Max Files;type=number;keywords=git,sync,files,limit,repository,compose,gitops;category=general;description=Maximum number of repository files copied during a Git sync. Set 0 to disable the environment cap (default: 500)"`
- GitSyncMaxTotalSizeMb SettingVariable `key:"gitSyncMaxTotalSizeMb,envOverride" meta:"label=Git Sync Max Total Size (MB);type=number;keywords=git,sync,size,limit,repository,compose,gitops,mb;category=general;description=Maximum combined size in MB for files copied during a Git sync. Set 0 to disable the environment cap (default: 50)"`
- GitSyncMaxBinarySizeMb SettingVariable `key:"gitSyncMaxBinarySizeMb,envOverride" meta:"label=Git Sync Max Binary Size (MB);type=number;keywords=git,sync,binary,size,limit,repository,compose,gitops,mb;category=general;description=Maximum size in MB for a single binary file copied during a Git sync. Set 0 to disable the environment cap (default: 10)"`
- DockerHost SettingVariable `key:"dockerHost,authrequired,envOverride" meta:"label=Docker Host;type=text;keywords=docker,host,daemon,socket,unix,remote;category=internal;description=URI for Docker daemon"`
- BuildProvider SettingVariable `key:"buildProvider,envOverride" meta:"label=Build Provider;type=select;keywords=build,buildkit,depot,provider,remote,local;category=build;description=Default build provider (local or depot)" catmeta:"id=build;title=Build;icon=code;url=/settings/builds;description=Configure BuildKit and Depot build settings"`
- BuildsDirectory SettingVariable `key:"buildsDirectory,envOverride" meta:"label=Builds Directory;type=text;keywords=builds,directory,path,workspace,context;category=build;description=Root directory for manual build workspaces"`
- BuildTimeout SettingVariable `key:"buildTimeout,envOverride" meta:"label=Build Timeout;type=number;keywords=build,timeout,seconds,buildkit;category=build;description=Timeout for BuildKit builds in seconds (default: 1800 = 30 minutes)"`
- DepotProjectId SettingVariable `key:"depotProjectId,envOverride" meta:"label=Depot Project ID;type=text;keywords=depot,project,id,build,provider;category=build;description=Depot project identifier"`
- DepotToken SettingVariable `key:"depotToken,envOverride,sensitive" meta:"label=Depot Token;type=password;keywords=depot,token,api,secret,build,provider;category=build;description=Depot API token"`
+ ScheduledPruneBuildCache SettingVariable `key:"scheduledPruneBuildCache,deprecated" meta:"label=Legacy Scheduled Prune Build Cache;type=boolean;keywords=prune,build cache,cleanup,maintenance,legacy;category=internal;description=Legacy boolean build cache prune flag retained for migration compatibility"`
+ PruneContainerMode SettingVariable `key:"pruneContainerMode" meta:"label=Prune Containers;type=select;keywords=prune,containers,cleanup,maintenance,mode,older,stopped;category=internal;description=Select how containers should be pruned when the scheduled prune job runs"`
+ PruneContainerUntil SettingVariable `key:"pruneContainerUntil" meta:"label=Container Age Filter;type=text;keywords=prune,containers,cleanup,maintenance,until,older,duration;category=internal;description=Duration threshold for scheduled container prune when mode is olderThan"`
+ PruneImageMode SettingVariable `key:"pruneImageMode" meta:"label=Prune Images;type=select;keywords=prune,images,cleanup,maintenance,mode,dangling,all,older;category=internal;description=Select how images should be pruned when the scheduled prune job runs"`
+ PruneImageUntil SettingVariable `key:"pruneImageUntil" meta:"label=Image Age Filter;type=text;keywords=prune,images,cleanup,maintenance,until,older,duration;category=internal;description=Duration threshold for scheduled image prune when mode is olderThan"`
+ PruneVolumeMode SettingVariable `key:"pruneVolumeMode" meta:"label=Prune Volumes;type=select;keywords=prune,volumes,cleanup,maintenance,mode,anonymous,named;category=internal;description=Select how volumes should be pruned when the scheduled prune job runs"`
+ PruneNetworkMode SettingVariable `key:"pruneNetworkMode" meta:"label=Prune Networks;type=select;keywords=prune,networks,cleanup,maintenance,mode,unused,older;category=internal;description=Select how networks should be pruned when the scheduled prune job runs"`
+ PruneNetworkUntil SettingVariable `key:"pruneNetworkUntil" meta:"label=Network Age Filter;type=text;keywords=prune,networks,cleanup,maintenance,until,older,duration;category=internal;description=Duration threshold for scheduled network prune when mode is olderThan"`
+ PruneBuildCacheMode SettingVariable `key:"pruneBuildCacheMode" meta:"label=Prune Build Cache;type=select;keywords=prune,build cache,cleanup,maintenance,mode,unused,all,older;category=internal;description=Select how build cache should be pruned when the scheduled prune job runs"`
+ PruneBuildCacheUntil SettingVariable `key:"pruneBuildCacheUntil" meta:"label=Build Cache Age Filter;type=text;keywords=prune,build cache,cleanup,maintenance,until,older,duration;category=internal;description=Duration threshold for scheduled build cache prune when mode is olderThan"`
+ AutoHealEnabled SettingVariable `key:"autoHealEnabled" meta:"label=Auto Heal;type=boolean;keywords=auto,heal,health,restart,unhealthy,recovery,container,healthcheck;category=internal;description=Automatically restart containers that become unhealthy"`
+ AutoHealInterval SettingVariable `key:"autoHealInterval" meta:"label=Auto Heal Interval;type=cron;keywords=auto,heal,interval,frequency,schedule,health,jobs;description=How often to check container health (cron expression)" catmeta:"id=jobschedule"`
+ AutoHealExcludedContainers SettingVariable `key:"autoHealExcludedContainers" meta:"label=Auto Heal Excluded Containers;type=text;keywords=auto,heal,exclude,containers,ignore,skip,health;category=internal;description=Comma-separated list of containers to exclude from auto-heal"`
+ AutoHealMaxRestarts SettingVariable `key:"autoHealMaxRestarts" meta:"label=Auto Heal Max Restarts;type=number;keywords=auto,heal,max,restarts,limit,loop,protection;category=internal;description=Maximum auto-heal restarts per container within the restart window (default: 5)"`
+ AutoHealRestartWindow SettingVariable `key:"autoHealRestartWindow" meta:"label=Auto Heal Restart Window;type=number;keywords=auto,heal,restart,window,minutes,cooldown,protection;category=internal;description=Time window in minutes for counting auto-heal restarts (default: 30)"`
+ VolumeBrowserHelperIdleTimeout SettingVariable `key:"volumeBrowserHelperIdleTimeout" meta:"label=Volume Browser Idle Timeout;type=number;keywords=volume,browser,helper,idle,timeout,cleanup,reaper,minutes;category=internal;description=Minutes a volume-browser helper container may sit idle before automatic removal (default: 10; 0 disables)"`
+ MaxImageUploadSize SettingVariable `key:"maxImageUploadSize" meta:"label=Max Image Upload Size;type=number;keywords=upload,size,limit,maximum,image,tar,file,megabytes,mb,storage;category=internal;description=Maximum size in MB for image archive uploads (default: 500)"`
+ GitSyncMaxFiles SettingVariable `key:"gitSyncMaxFiles,envOverride" meta:"label=Git Sync Max Files;type=number;keywords=git,sync,files,limit,repository,compose,gitops;category=general;description=Maximum number of repository files copied during a Git sync. Set 0 to disable the environment cap (default: 500)"`
+ GitSyncMaxTotalSizeMb SettingVariable `key:"gitSyncMaxTotalSizeMb,envOverride" meta:"label=Git Sync Max Total Size (MB);type=number;keywords=git,sync,size,limit,repository,compose,gitops,mb;category=general;description=Maximum combined size in MB for files copied during a Git sync. Set 0 to disable the environment cap (default: 50)"`
+ GitSyncMaxBinarySizeMb SettingVariable `key:"gitSyncMaxBinarySizeMb,envOverride" meta:"label=Git Sync Max Binary Size (MB);type=number;keywords=git,sync,binary,size,limit,repository,compose,gitops,mb;category=general;description=Maximum size in MB for a single binary file copied during a Git sync. Set 0 to disable the environment cap (default: 10)"`
+ DockerHost SettingVariable `key:"dockerHost,authrequired,envOverride" meta:"label=Docker Host;type=text;keywords=docker,host,daemon,socket,unix,remote;category=internal;description=URI for Docker daemon"`
+ BuildProvider SettingVariable `key:"buildProvider,envOverride" meta:"label=Build Provider;type=select;keywords=build,buildkit,depot,provider,remote,local;category=build;description=Default build provider (local or depot)" catmeta:"id=build;title=Build;icon=code;url=/settings/builds;description=Configure BuildKit and Depot build settings"`
+ BuildsDirectory SettingVariable `key:"buildsDirectory,envOverride" meta:"label=Builds Directory;type=text;keywords=builds,directory,path,workspace,context;category=build;description=Root directory for manual build workspaces"`
+ BuildTimeout SettingVariable `key:"buildTimeout,envOverride" meta:"label=Build Timeout;type=number;keywords=build,timeout,seconds,buildkit;category=build;description=Timeout for BuildKit builds in seconds (default: 1800 = 30 minutes)"`
+ DepotProjectId SettingVariable `key:"depotProjectId,envOverride" meta:"label=Depot Project ID;type=text;keywords=depot,project,id,build,provider;category=build;description=Depot project identifier"`
+ DepotToken SettingVariable `key:"depotToken,envOverride,sensitive" meta:"label=Depot Token;type=password;keywords=depot,token,api,secret,build,provider;category=build;description=Depot API token"`
// Authentication and security categories
AuthLocalEnabled SettingVariable `key:"authLocalEnabled,public" meta:"label=Local Authentication;type=boolean;keywords=local,auth,authentication,username,password,login,credentials;category=authentication;description=Enable local username/password authentication" catmeta:"id=authentication;title=Authentication;icon=lock;url=/settings/authentication;description=Manage authentication providers, password policy, and session behavior"`
diff --git a/backend/internal/services/settings_service.go b/backend/internal/services/settings_service.go
index cc0a3b1b5..50f6d95ce 100644
--- a/backend/internal/services/settings_service.go
+++ b/backend/internal/services/settings_service.go
@@ -145,6 +145,7 @@ func DefaultSettingsConfig() *models.Settings {
AutoHealExcludedContainers: models.SettingVariable{Value: ""},
AutoHealMaxRestarts: models.SettingVariable{Value: "5"},
AutoHealRestartWindow: models.SettingVariable{Value: "30"},
+ VolumeBrowserHelperIdleTimeout: models.SettingVariable{Value: "10"},
GitopsSyncInterval: models.SettingVariable{Value: "0 */1 * * * *"},
BaseServerURL: models.SettingVariable{Value: "http://localhost"},
EnableGravatar: models.SettingVariable{Value: "true"},
diff --git a/backend/internal/services/volume_service.go b/backend/internal/services/volume_service.go
index de7940122..77be9ccf4 100644
--- a/backend/internal/services/volume_service.go
+++ b/backend/internal/services/volume_service.go
@@ -41,7 +41,14 @@ type VolumeService struct {
imageService *ImageService
backupVolumeName string
helperMu sync.Mutex
- helperByVolume map[string]string
+ helperByVolume map[string]*volumeHelper
+}
+
+// volumeHelper tracks a reused read-only browse helper container and the last
+// time it serviced a request, so idle helpers can be reaped.
+type volumeHelper struct {
+ id string
+ lastUsedAt time.Time
}
const volumeHelperImage = DefaultArcaneToolsImage
@@ -80,7 +87,7 @@ func NewVolumeService(db *database.DB, dockerService *DockerClientService, event
containerService: containerService,
imageService: imageService,
backupVolumeName: backupVolumeName,
- helperByVolume: make(map[string]string),
+ helperByVolume: make(map[string]*volumeHelper),
}
}
@@ -166,6 +173,12 @@ func (s *VolumeService) DeleteVolume(ctx context.Context, name string, force boo
return fmt.Errorf("failed to connect to Docker: %w", err)
}
+ // Stop any read-only browse helper first; a helper mounting the volume would
+ // otherwise block a non-forced VolumeRemove with "volume is in use".
+ if stopErr := s.StopHelper(ctx, name); stopErr != nil {
+ slog.WarnContext(ctx, "could not stop volume browse helper before delete", "volume", name, "error", stopErr.Error())
+ }
+
if _, err := dockerClient.VolumeRemove(ctx, name, client.VolumeRemoveOptions{
Force: force,
}); err != nil {
@@ -197,6 +210,11 @@ func (s *VolumeService) PruneVolumesWithOptions(ctx context.Context, all bool) (
return nil, fmt.Errorf("failed to connect to Docker: %w", err)
}
+ // Stop all read-only browse helpers first; a helper mounting a volume marks it
+ // "in use" and would prevent VolumePrune from reclaiming an otherwise-unused
+ // volume. Helpers are re-created on demand on the next browse request.
+ s.CleanupHelperContainers(ctx)
+
preserveTrivyCache := s.preserveTrivyCacheOnVolumePruneInternal()
// Docker's VolumesPrune behavior (API v1.42+):
@@ -783,7 +801,7 @@ func (s *VolumeService) createTempContainerInternal(ctx context.Context, volumeN
if readOnly {
s.helperMu.Lock()
- s.helperByVolume[volumeName] = resp.ID
+ s.helperByVolume[volumeName] = &volumeHelper{id: resp.ID, lastUsedAt: time.Now()}
s.helperMu.Unlock()
return resp.ID, func() {}, nil
}
@@ -793,13 +811,13 @@ func (s *VolumeService) createTempContainerInternal(ctx context.Context, volumeN
func (s *VolumeService) getReusableReadOnlyContainerInternal(ctx context.Context, dockerClient *client.Client, volumeName string) (string, bool) {
s.helperMu.Lock()
- containerID := s.helperByVolume[volumeName]
+ helper := s.helperByVolume[volumeName]
s.helperMu.Unlock()
- if containerID == "" {
+ if helper == nil || helper.id == "" {
return "", false
}
- inspect, err := libarcane.ContainerInspectWithCompatibility(ctx, dockerClient, containerID, client.ContainerInspectOptions{})
+ inspect, err := libarcane.ContainerInspectWithCompatibility(ctx, dockerClient, helper.id, client.ContainerInspectOptions{})
if err != nil || inspect.Container.State == nil || !inspect.Container.State.Running {
s.helperMu.Lock()
delete(s.helperByVolume, volumeName)
@@ -807,7 +825,19 @@ func (s *VolumeService) getReusableReadOnlyContainerInternal(ctx context.Context
return "", false
}
- return containerID, true
+ s.touchHelperInternal(volumeName)
+
+ return helper.id, true
+}
+
+// touchHelperInternal records that the helper for volumeName just serviced a
+// request, resetting its idle clock. No-op if the entry is gone.
+func (s *VolumeService) touchHelperInternal(volumeName string) {
+ s.helperMu.Lock()
+ defer s.helperMu.Unlock()
+ if helper := s.helperByVolume[volumeName]; helper != nil {
+ helper.lastUsedAt = time.Now()
+ }
}
func (s *VolumeService) CleanupHelperContainers(ctx context.Context) {
@@ -819,12 +849,12 @@ func (s *VolumeService) CleanupHelperContainers(ctx context.Context) {
s.helperMu.Lock()
helperIDs := make([]string, 0, len(s.helperByVolume))
- for _, containerID := range s.helperByVolume {
- if containerID != "" {
- helperIDs = append(helperIDs, containerID)
+ for _, helper := range s.helperByVolume {
+ if helper != nil && helper.id != "" {
+ helperIDs = append(helperIDs, helper.id)
}
}
- s.helperByVolume = make(map[string]string)
+ s.helperByVolume = make(map[string]*volumeHelper)
s.helperMu.Unlock()
for _, containerID := range helperIDs {
@@ -834,6 +864,95 @@ func (s *VolumeService) CleanupHelperContainers(ctx context.Context) {
}
}
+// ReapIdleHelpers removes reused read-only browse helper containers that have
+// not serviced a request within idleTimeout. It is map-driven (orphaned helpers
+// not tracked in helperByVolume are left to the startup orphan sweep). Entries
+// are removed from the map before the container is removed, so a concurrent
+// request simply gets a cache miss and re-creates a fresh helper.
+func (s *VolumeService) ReapIdleHelpers(ctx context.Context, idleTimeout time.Duration) (int, error) {
+ if idleTimeout <= 0 {
+ return 0, nil
+ }
+
+ dockerClient, err := s.dockerService.GetClient(ctx)
+ if err != nil {
+ return 0, fmt.Errorf("failed to get docker client for idle helper reap: %w", err)
+ }
+
+ staleIDs := s.collectStaleHelperIDsInternal(time.Now(), idleTimeout)
+
+ removed := 0
+ for _, containerID := range staleIDs {
+ if _, err := dockerClient.ContainerRemove(ctx, containerID, volumeHelperRemoveOptionsInternal()); err != nil {
+ slog.WarnContext(ctx, "failed to remove idle helper container", "container_id", containerID, "error", err.Error())
+ continue
+ }
+ removed++
+ }
+
+ return removed, nil
+}
+
+// collectStaleHelperIDsInternal removes idle (and any nil) entries from the helper
+// map and returns the container IDs that should be removed. Pure map/mutex
+// bookkeeping with no Docker calls, so it can be unit-tested directly. Entries are
+// dropped before their containers are removed so a concurrent request gets a clean
+// cache miss and re-creates a fresh helper.
+func (s *VolumeService) collectStaleHelperIDsInternal(now time.Time, idleTimeout time.Duration) []string {
+ staleIDs := make([]string, 0)
+ s.helperMu.Lock()
+ defer s.helperMu.Unlock()
+ for volumeName, helper := range s.helperByVolume {
+ if helper == nil {
+ delete(s.helperByVolume, volumeName)
+ continue
+ }
+ if now.Sub(helper.lastUsedAt) >= idleTimeout {
+ staleIDs = append(staleIDs, helper.id)
+ delete(s.helperByVolume, volumeName)
+ }
+ }
+ return staleIDs
+}
+
+// StopHelper removes the reused read-only browse helper for a single volume, if
+// one exists. It is idempotent: stopping a volume with no active helper returns
+// nil.
+func (s *VolumeService) StopHelper(ctx context.Context, volumeName string) error {
+ if strings.TrimSpace(volumeName) == "" {
+ return nil
+ }
+
+ dockerClient, err := s.dockerService.GetClient(ctx)
+ if err != nil {
+ return fmt.Errorf("failed to get docker client for helper stop: %w", err)
+ }
+
+ containerID := s.takeHelperIDInternal(volumeName)
+ if containerID == "" {
+ return nil
+ }
+
+ if _, err := dockerClient.ContainerRemove(ctx, containerID, volumeHelperRemoveOptionsInternal()); err != nil {
+ return fmt.Errorf("failed to remove helper container: %w", err)
+ }
+
+ return nil
+}
+
+// takeHelperIDInternal removes the helper entry for volumeName and returns its
+// container ID, or "" if there was none. Pure map/mutex bookkeeping.
+func (s *VolumeService) takeHelperIDInternal(volumeName string) string {
+ s.helperMu.Lock()
+ defer s.helperMu.Unlock()
+ helper := s.helperByVolume[volumeName]
+ delete(s.helperByVolume, volumeName)
+ if helper == nil {
+ return ""
+ }
+ return helper.id
+}
+
func (s *VolumeService) CleanupOrphanedVolumeHelpers(ctx context.Context) error {
dockerClient, err := s.dockerService.GetClient(ctx)
if err != nil {
diff --git a/backend/internal/services/volume_service_test.go b/backend/internal/services/volume_service_test.go
index 7749162af..8085ee0c9 100644
--- a/backend/internal/services/volume_service_test.go
+++ b/backend/internal/services/volume_service_test.go
@@ -3,6 +3,7 @@ package services
import (
"context"
"testing"
+ "time"
"github.com/getarcaneapp/arcane/backend/pkg/libarcane"
volumetypes "github.com/getarcaneapp/arcane/types/volume"
@@ -366,3 +367,57 @@ func TestBackupArchiveFilenameInternal(t *testing.T) {
})
}
}
+
+func TestCollectStaleHelperIDsInternal(t *testing.T) {
+ now := time.Now()
+ s := &VolumeService{
+ helperByVolume: map[string]*volumeHelper{
+ "fresh": {id: "c-fresh", lastUsedAt: now.Add(-1 * time.Minute)},
+ "stale": {id: "c-stale", lastUsedAt: now.Add(-11 * time.Minute)},
+ "atedge": {id: "c-atedge", lastUsedAt: now.Add(-10 * time.Minute)},
+ "nilent": nil,
+ },
+ }
+
+ stale := s.collectStaleHelperIDsInternal(now, 10*time.Minute)
+
+ require.ElementsMatch(t, []string{"c-stale", "c-atedge"}, stale,
+ "helpers idle >= timeout (and exactly at the edge) should be collected")
+
+ // Only the fresh entry survives; stale, at-edge, and nil entries are dropped.
+ require.Len(t, s.helperByVolume, 1)
+ require.Contains(t, s.helperByVolume, "fresh")
+}
+
+func TestTakeHelperIDInternal(t *testing.T) {
+ s := &VolumeService{
+ helperByVolume: map[string]*volumeHelper{
+ "vol-a": {id: "c-a", lastUsedAt: time.Now()},
+ },
+ }
+
+ // Present: returns id and removes the entry.
+ require.Equal(t, "c-a", s.takeHelperIDInternal("vol-a"))
+ require.NotContains(t, s.helperByVolume, "vol-a")
+
+ // Absent (idempotent): returns "" without panicking.
+ require.Equal(t, "", s.takeHelperIDInternal("vol-a"))
+ require.Equal(t, "", s.takeHelperIDInternal("never-existed"))
+}
+
+func TestTouchHelperInternal(t *testing.T) {
+ old := time.Now().Add(-30 * time.Minute)
+ s := &VolumeService{
+ helperByVolume: map[string]*volumeHelper{
+ "vol-a": {id: "c-a", lastUsedAt: old},
+ },
+ }
+
+ s.touchHelperInternal("vol-a")
+ require.True(t, s.helperByVolume["vol-a"].lastUsedAt.After(old),
+ "touch should reset the idle clock forward")
+
+ // Missing volume is a no-op (must not panic or create an entry).
+ s.touchHelperInternal("missing")
+ require.NotContains(t, s.helperByVolume, "missing")
+}
diff --git a/backend/pkg/scheduler/volume_helper_reaper_job.go b/backend/pkg/scheduler/volume_helper_reaper_job.go
new file mode 100644
index 000000000..a9e2b0e50
--- /dev/null
+++ b/backend/pkg/scheduler/volume_helper_reaper_job.go
@@ -0,0 +1,76 @@
+package scheduler
+
+import (
+ "context"
+ "log/slog"
+ "time"
+
+ "github.com/getarcaneapp/arcane/backend/internal/services"
+)
+
+const (
+ PruningVolumeHelperJobName = "pruning-volume-helper"
+
+ // volumeHelperIdleTimeoutSetting is the settings key (in minutes) controlling how
+ // long a volume-browser helper container may sit idle before it is reaped.
+ volumeHelperIdleTimeoutSetting = "volumeBrowserHelperIdleTimeout"
+ defaultVolumeHelperIdleTimeoutMinutes = 10
+ volumeHelperPruningSchedule = "0 */5 * * * *"
+)
+
+// PruningVolumeHelperJob periodically removes idle volume-browser helper
+// containers. The run frequency is fixed (every 5 minutes); how stale a helper must
+// be to be pruned is driven by the volumeBrowserHelperIdleTimeout setting.
+type PruningVolumeHelperJob struct {
+ volumeService *services.VolumeService
+ settingsService *services.SettingsService
+}
+
+func NewPruningVolumeHelperJob(volumeService *services.VolumeService, settingsService *services.SettingsService) *PruningVolumeHelperJob {
+ return &PruningVolumeHelperJob{
+ volumeService: volumeService,
+ settingsService: settingsService,
+ }
+}
+
+func (j *PruningVolumeHelperJob) Name() string {
+ return PruningVolumeHelperJobName
+}
+
+// Schedule runs the pruning job every 5 minutes. This is intentionally not
+// configurable; the idle timeout (read in Run) is the user-facing knob.
+func (j *PruningVolumeHelperJob) Schedule(ctx context.Context) string {
+ return volumeHelperPruningSchedule
+}
+
+func (j *PruningVolumeHelperJob) Run(ctx context.Context) {
+ if j.volumeService == nil {
+ return
+ }
+
+ minutes := defaultVolumeHelperIdleTimeoutMinutes
+ if j.settingsService != nil {
+ minutes = j.settingsService.GetIntSetting(ctx, volumeHelperIdleTimeoutSetting, defaultVolumeHelperIdleTimeoutMinutes)
+ }
+ if minutes <= 0 {
+ // 0 (or negative) disables idle pruning.
+ return
+ }
+
+ removed, err := j.volumeService.ReapIdleHelpers(ctx, time.Duration(minutes)*time.Minute)
+ if err != nil {
+ slog.ErrorContext(ctx, "volume helper pruning failed", "jobName", PruningVolumeHelperJobName, "error", err)
+ return
+ }
+ if removed > 0 {
+ slog.InfoContext(ctx, "volume helper pruning completed",
+ "jobName", PruningVolumeHelperJobName,
+ "removed", removed,
+ "idleTimeoutMinutes", minutes)
+ }
+}
+
+func (j *PruningVolumeHelperJob) Reschedule(ctx context.Context) error {
+ // Fixed schedule; the idle-timeout setting only affects Run behavior.
+ return nil
+}
diff --git a/backend/pkg/scheduler/volume_helper_reaper_job_test.go b/backend/pkg/scheduler/volume_helper_reaper_job_test.go
new file mode 100644
index 000000000..6e81bcc42
--- /dev/null
+++ b/backend/pkg/scheduler/volume_helper_reaper_job_test.go
@@ -0,0 +1,30 @@
+package scheduler
+
+import (
+ "context"
+ "testing"
+
+ "github.com/stretchr/testify/require"
+)
+
+func TestPruningVolumeHelperJob_Name(t *testing.T) {
+ job := NewPruningVolumeHelperJob(nil, nil)
+ require.Equal(t, PruningVolumeHelperJobName, job.Name())
+}
+
+func TestPruningVolumeHelperJob_Schedule(t *testing.T) {
+ job := NewPruningVolumeHelperJob(nil, nil)
+ // Fixed every-5-minute schedule; the idle timeout (read in Run) is the knob.
+ require.Equal(t, "0 */5 * * * *", job.Schedule(context.Background()))
+}
+
+func TestPruningVolumeHelperJob_Reschedule(t *testing.T) {
+ job := NewPruningVolumeHelperJob(nil, nil)
+ require.NoError(t, job.Reschedule(context.Background()))
+}
+
+func TestPruningVolumeHelperJob_Run_NilVolumeServiceNoPanic(t *testing.T) {
+ job := NewPruningVolumeHelperJob(nil, nil)
+ // With no volume service the run must return without panicking (defensive guard).
+ require.NotPanics(t, func() { job.Run(context.Background()) })
+}
diff --git a/frontend/src/lib/types/settings.type.ts b/frontend/src/lib/types/settings.type.ts
index 10d1c4590..5e92367eb 100644
--- a/frontend/src/lib/types/settings.type.ts
+++ b/frontend/src/lib/types/settings.type.ts
@@ -38,6 +38,7 @@ export type Settings = {
autoHealExcludedContainers?: string;
autoHealMaxRestarts?: number;
autoHealRestartWindow?: number;
+ volumeBrowserHelperIdleTimeout?: number;
maxImageUploadSize: number;
gitSyncMaxFiles: number;
gitSyncMaxTotalSizeMb: number;
diff --git a/types/settings/settings.go b/types/settings/settings.go
index 50d3edbd1..096d5cf7b 100644
--- a/types/settings/settings.go
+++ b/types/settings/settings.go
@@ -474,6 +474,12 @@ type Update struct {
// Required: false
AutoHealRestartWindow *string `json:"autoHealRestartWindow,omitempty"`
+ // VolumeBrowserHelperIdleTimeout is the number of minutes a volume-browser helper
+ // container may sit idle before it is automatically removed (0 disables).
+ //
+ // Required: false
+ VolumeBrowserHelperIdleTimeout *string `json:"volumeBrowserHelperIdleTimeout,omitempty"`
+
// BuildProvider is the default build provider (local|depot).
//
// Required: false