Modern Docker Management, Designed for Everyone
Go composecontainer-managementcontainersdockerdocker-composedocker-managementgoself-hostedsveltekittypescriptweb-ui
refactor: use getarcaneapp/updater module (#2788)
Kyle Mendell35a0f2bf7d4c
diff --git a/backend/cli/upgrade/upgrade.go b/backend/cli/upgrade/upgrade.goindex 0cad3aa63..6edc3231e 100644--- a/backend/cli/upgrade/upgrade.go+++ b/backend/cli/upgrade/upgrade.go@@ -10,7 +10,8 @@ import (docker "github.com/getarcaneapp/arcane/backend/pkg/dockerutil""github.com/getarcaneapp/arcane/backend/pkg/libarcane"- libupdater "github.com/getarcaneapp/arcane/backend/pkg/libarcane/imageupdate"+ updaterlabels "github.com/getarcaneapp/updater/pkg/labels"+ updaterlogs "github.com/getarcaneapp/updater/pkg/logs""github.com/moby/moby/api/types/container""github.com/moby/moby/api/types/network""github.com/moby/moby/client"@@ -54,7 +55,7 @@ func runUpgrade(cmd *cobra.Command, args []string) error {// This prevents interruption when stopping the target containerctx := context.Background()- logFile, err := libupdater.SetupMessageOnlyLogFile("/app/data", "arcane-upgrade", slog.LevelInfo)+ logFile, err := updaterlogs.SetupMessageOnlyLogFile("/app/data", "arcane-upgrade", slog.LevelInfo)if err != nil {slog.Warn("Failed to setup file logging", "error", err)} else if logFile != nil {@@ -152,7 +153,7 @@ func findArcaneContainer(ctx context.Context, dockerClient *client.Client) (cont}// New label: com.getarcaneapp.arcane=true- if libupdater.IsArcaneContainer(labels) {+ if updaterlabels.IsArcaneContainer(labels) {slog.Info("Found Arcane container by label", "id", c.ID[:12], "image", c.Image, "names", c.Names)return inspect, nil}diff --git a/backend/go.mod b/backend/go.modindex d8dd91cb4..80988e5b8 100644--- a/backend/go.mod+++ b/backend/go.mod@@ -22,8 +22,9 @@ require (github.com/docker/compose/v5 v5.1.4github.com/docker/go-units v0.5.0github.com/fsnotify/fsnotify v1.10.1- github.com/getarcaneapp/arcane/cli v1.19.1+ github.com/getarcaneapp/arcane/cli v1.19.5github.com/getarcaneapp/arcane/types v1.19.5+ github.com/getarcaneapp/updater v0.3.2github.com/glebarez/sqlite v1.11.0github.com/go-git/go-git/v5 v5.19.1github.com/goccy/go-yaml v1.19.2diff --git a/backend/go.sum b/backend/go.sumindex 76b8e55ca..a647eb21a 100644--- a/backend/go.sum+++ b/backend/go.sum@@ -173,6 +173,8 @@ github.com/fvbommel/sortorder v1.1.0 h1:fUmoe+HLsBTctBDoaBwpQo5N+nrCp8g/BjKb/6ZQgithub.com/fvbommel/sortorder v1.1.0/go.mod h1:uk88iVf1ovNn1iLfgUVU2F9o5eO30ui720w+kxuqRs0=github.com/fxamacker/cbor/v2 v2.9.1 h1:2rWm8B193Ll4VdjsJY28jxs70IdDsHRWgQYAI80+rMQ=github.com/fxamacker/cbor/v2 v2.9.1/go.mod h1:vM4b+DJCtHn+zz7h3FFp/hDAI9WNWCsZj23V5ytsSxQ=+github.com/getarcaneapp/updater v0.3.2 h1:mSyMlb7q+EyLjGKrcMg64b+D+wVwMBkq8ZduC8PQawE=+github.com/getarcaneapp/updater v0.3.2/go.mod h1:0o8qpysU0YdEuEyCq6FtQPyuTTPDEV5Epwx7ctROAKM=github.com/glebarez/go-sqlite v1.22.0 h1:uAcMJhaA6r3LHMTFgP0SifzgXg46yJkgxqyuyec+ruQ=github.com/glebarez/go-sqlite v1.22.0/go.mod h1:PlBIdHe0+aUEFn+r2/uthrWq4FxbzugL0L8Li6yQJbc=github.com/glebarez/sqlite v1.11.0 h1:wSG0irqzP6VurnMEpFGer5Li19RpIRi2qvQz++w0GMw=diff --git a/backend/internal/common/errors.go b/backend/internal/common/errors.goindex fd0fce289..482e52d7b 100644--- a/backend/internal/common/errors.go+++ b/backend/internal/common/errors.go@@ -1244,6 +1244,42 @@ func (e *UpdaterHistoryError) Error() string {return fmt.Sprintf("Failed to get updater history: %v", e.Err)}+type UpdaterDockerServiceUnavailableError struct{}++func (e *UpdaterDockerServiceUnavailableError) Error() string {+ return "docker service unavailable"+}++type UpdaterDockerClientUnavailableError struct{}++func (e *UpdaterDockerClientUnavailableError) Error() string {+ return "docker client unavailable"+}++type UpdaterImageServiceUnavailableError struct{}++func (e *UpdaterImageServiceUnavailableError) Error() string {+ return "image service unavailable"+}++type UpdaterDatabaseUnavailableError struct{}++func (e *UpdaterDatabaseUnavailableError) Error() string {+ return "database unavailable"+}++type UpdaterServiceUnavailableError struct{}++func (e *UpdaterServiceUnavailableError) Error() string {+ return "updater service unavailable"+}++type UpdaterProjectServiceUnavailableError struct{}++func (e *UpdaterProjectServiceUnavailableError) Error() string {+ return "project service unavailable"+}+type UserListError struct {Err error}diff --git a/backend/internal/configschema/schema_test.go b/backend/internal/configschema/schema_test.goindex fd78576c7..5528af07c 100644--- a/backend/internal/configschema/schema_test.go+++ b/backend/internal/configschema/schema_test.go@@ -276,6 +276,7 @@ var expectedSettingOverrideKeys = []string{"autoHealRestartWindow","autoInjectEnv","autoUpdate",+ "autoUpdateComposeStandaloneFallback","autoUpdateExcludedContainers","autoUpdateInterval","baseServerUrl",diff --git a/backend/internal/models/settings.go b/backend/internal/models/settings.goindex e5a5fd873..ede6e7e3c 100644--- a/backend/internal/models/settings.go+++ b/backend/internal/models/settings.go@@ -81,46 +81,47 @@ type Settings struct {OledMode SettingVariable `key:"oledMode,public,local" meta:"label=OLED Mode;type=boolean;keywords=oled,dark,theme,black,amoled,appearance,display;category=general;description=Use true-black backgrounds for OLED displays (only active in dark mode)"`// Docker category- AutoUpdate SettingVariable `key:"autoUpdate" meta:"label=Auto Update;type=boolean;keywords=auto,update,automatic,upgrade,refresh,restart,deploy;category=internal;description=Automatically update containers when new images are available"`- AutoUpdateInterval SettingVariable `key:"autoUpdateInterval" meta:"label=Auto Update Interval;type=cron;keywords=auto,update,interval,frequency,schedule,automatic,timing;category=internal;description=How often to check for automatic updates (cron expression)"`- 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)"`- ExpiredSessionsCleanupInterval SettingVariable `key:"expiredSessionsCleanupInterval" meta:"label=Expired Sessions Cleanup Interval;type=cron;keywords=sessions,cleanup,retention,expired,revoked,interval,frequency,schedule,auth,jobs;description=How often to delete expired and old revoked sessions (cron expression)"`- ActivityHistoryRetentionDays SettingVariable `key:"activityHistoryRetentionDays" meta:"label=Activity History Retention;type=number;keywords=activity,history,retention,days,cleanup,background,tasks;category=activity;description=Delete completed Activity Center entries older than this many days. Set 0 to disable age-based cleanup." catmeta:"id=activity;title=Activity;icon=activity;url=/settings/activity;description=Configure Activity Center history and cleanup"`- ActivityHistoryMaxEntries SettingVariable `key:"activityHistoryMaxEntries" meta:"label=Activity History Limit;type=number;keywords=activity,history,limit,entries,count,cleanup,background,tasks;category=activity;description=Maximum completed Activity Center entries to keep per environment. Set 0 to disable count-based cleanup."`- 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)"`- DefaultDeployPullPolicy SettingVariable `key:"defaultDeployPullPolicy" meta:"label=Default Deploy Pull Policy;type=select;keywords=deploy,pull,policy,compose,up,missing,always;category=internal;description=Default image pull policy when deploying projects"`- ScheduledPruneEnabled SettingVariable `key:"scheduledPruneEnabled" meta:"label=Scheduled Prune Enabled;type=boolean;keywords=prune,cleanup,maintenance,schedule,automatic;category=internal;description=Enable scheduled pruning of unused Docker resources"`- ScheduledPruneInterval SettingVariable `key:"scheduledPruneInterval" meta:"label=Scheduled Prune Interval;type=cron;keywords=prune,cleanup,interval,minutes,schedule;category=internal;description=How often to run scheduled prunes (cron expression)"`- GitopsSyncInterval SettingVariable `key:"gitopsSyncInterval" meta:"label=GitOps Sync Interval;type=cron;keywords=gitops,sync,interval,frequency,schedule,repository;category=internal;description=How often to run GitOps synchronization checks (cron expression)"`- 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"`+ AutoUpdate SettingVariable `key:"autoUpdate" meta:"label=Auto Update;type=boolean;keywords=auto,update,automatic,upgrade,refresh,restart,deploy;category=internal;description=Automatically update containers when new images are available"`+ AutoUpdateInterval SettingVariable `key:"autoUpdateInterval" meta:"label=Auto Update Interval;type=cron;keywords=auto,update,interval,frequency,schedule,automatic,timing;category=internal;description=How often to check for automatic updates (cron expression)"`+ 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"`+ AutoUpdateComposeStandaloneFallback SettingVariable `key:"autoUpdateComposeStandaloneFallback" meta:"label=Compose Standalone Fallback;type=boolean;keywords=auto,update,compose,standalone,fallback,containers;category=internal;description=Allow auto-update to recreate Compose-managed containers directly when Arcane cannot resolve the owning project. Restart Arcane after changing this setting."`+ 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)"`+ ExpiredSessionsCleanupInterval SettingVariable `key:"expiredSessionsCleanupInterval" meta:"label=Expired Sessions Cleanup Interval;type=cron;keywords=sessions,cleanup,retention,expired,revoked,interval,frequency,schedule,auth,jobs;description=How often to delete expired and old revoked sessions (cron expression)"`+ ActivityHistoryRetentionDays SettingVariable `key:"activityHistoryRetentionDays" meta:"label=Activity History Retention;type=number;keywords=activity,history,retention,days,cleanup,background,tasks;category=activity;description=Delete completed Activity Center entries older than this many days. Set 0 to disable age-based cleanup." catmeta:"id=activity;title=Activity;icon=activity;url=/settings/activity;description=Configure Activity Center history and cleanup"`+ ActivityHistoryMaxEntries SettingVariable `key:"activityHistoryMaxEntries" meta:"label=Activity History Limit;type=number;keywords=activity,history,limit,entries,count,cleanup,background,tasks;category=activity;description=Maximum completed Activity Center entries to keep per environment. Set 0 to disable count-based cleanup."`+ 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)"`+ DefaultDeployPullPolicy SettingVariable `key:"defaultDeployPullPolicy" meta:"label=Default Deploy Pull Policy;type=select;keywords=deploy,pull,policy,compose,up,missing,always;category=internal;description=Default image pull policy when deploying projects"`+ ScheduledPruneEnabled SettingVariable `key:"scheduledPruneEnabled" meta:"label=Scheduled Prune Enabled;type=boolean;keywords=prune,cleanup,maintenance,schedule,automatic;category=internal;description=Enable scheduled pruning of unused Docker resources"`+ ScheduledPruneInterval SettingVariable `key:"scheduledPruneInterval" meta:"label=Scheduled Prune Interval;type=cron;keywords=prune,cleanup,interval,minutes,schedule;category=internal;description=How often to run scheduled prunes (cron expression)"`+ GitopsSyncInterval SettingVariable `key:"gitopsSyncInterval" meta:"label=GitOps Sync Interval;type=cron;keywords=gitops,sync,interval,frequency,schedule,repository;category=internal;description=How often to run GitOps synchronization checks (cron expression)"`+ 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 categoriesAuthLocalEnabled 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/container_registry_service.go b/backend/internal/services/container_registry_service.goindex 7e8a8c2af..fae2f31a5 100644--- a/backend/internal/services/container_registry_service.go+++ b/backend/internal/services/container_registry_service.go@@ -18,12 +18,14 @@ import ("github.com/getarcaneapp/arcane/backend/internal/database""github.com/getarcaneapp/arcane/backend/internal/models""github.com/getarcaneapp/arcane/backend/pkg/libarcane/crypto"- imageupdatecore "github.com/getarcaneapp/arcane/backend/pkg/libarcane/imageupdate"utilsregistry "github.com/getarcaneapp/arcane/backend/pkg/libarcane/registryauth""github.com/getarcaneapp/arcane/backend/pkg/pagination""github.com/getarcaneapp/arcane/backend/pkg/utils""github.com/getarcaneapp/arcane/backend/pkg/utils/cache""github.com/getarcaneapp/arcane/types/containerregistry"+ updaterdigest "github.com/getarcaneapp/updater/pkg/digest"+ updaterrefs "github.com/getarcaneapp/updater/pkg/refs"+ updaterregistry "github.com/getarcaneapp/updater/pkg/registry"dockerregistry "github.com/moby/moby/api/types/registry""github.com/moby/moby/client")@@ -60,10 +62,16 @@ type resolvedRegistryCredential struct {}type registryRateLimitCacheEntryInternal struct {- RateLimit imageupdatecore.RateLimitInfo `json:"rateLimit"`+ RateLimit updaterregistry.RateLimitInfo `json:"rateLimit"`CheckedAt time.Time `json:"checkedAt"`}+type rateLimitRoundTripFuncInternal func(*http.Request) (*http.Response, error)++func (f rateLimitRoundTripFuncInternal) RoundTrip(req *http.Request) (*http.Response, error) {+ return f(req)+}+type ContainerRegistryService struct {db *database.DBdockerClient registryDaemonGetter@@ -80,7 +88,7 @@ func NewContainerRegistryService(db *database.DB, dockerClient registryDaemonGetreturn &ContainerRegistryService{db: db,dockerClient: dockerClient,- distributionHTTPClient: imageupdatecore.NewRegistryHTTPClient(),+ distributionHTTPClient: updaterregistry.NewRegistryHTTPClient(),cache: make(map[string]*cache.Cache[string]),kvService: kvService,}@@ -466,6 +474,7 @@ func (s *ContainerRegistryService) buildRegistryPullUsageInternal(ctx context.Co}if cachedRateLimit, checkedAt, ok := s.getCachedRateLimitInternal(ctx, reg.ID); ok {+ ensureRateLimitUsedInternal(cachedRateLimit)usage.Limit = cachedRateLimit.Limitusage.Remaining = cachedRateLimit.Remainingusage.Used = cachedRateLimit.Used@@ -481,6 +490,7 @@ func (s *ContainerRegistryService) buildRegistryPullUsageInternal(ctx context.Cousage.Error = err.Error()return usage}+ ensureRateLimitUsedInternal(rateLimit)usage.Limit = rateLimit.Limitusage.Remaining = rateLimit.Remaining@@ -492,6 +502,14 @@ func (s *ContainerRegistryService) buildRegistryPullUsageInternal(ctx context.Coreturn usage}+func ensureRateLimitUsedInternal(rateLimit *updaterregistry.RateLimitInfo) {+ if rateLimit == nil || rateLimit.Used != nil || rateLimit.Limit == nil || rateLimit.Remaining == nil {+ return+ }+ used := max(*rateLimit.Limit-*rateLimit.Remaining, 0)+ rateLimit.Used = &used+}+func (s *ContainerRegistryService) getObservedPullsInternal(ctx context.Context, registryHost string) int64 {if s.kvService == nil || registryHost == "" {return 0@@ -506,7 +524,7 @@ func (s *ContainerRegistryService) getObservedPullsInternal(ctx context.Context,return value}-func (s *ContainerRegistryService) dockerHubCredentialForRegistryInternal(reg models.ContainerRegistry) (*imageupdatecore.Credentials, string, string, error) {+func (s *ContainerRegistryService) dockerHubCredentialForRegistryInternal(reg models.ContainerRegistry) (*updaterregistry.Credentials, string, string, error) {if reg.RegistryType != registryTypeGeneric {return nil, "anonymous", "", nil}@@ -526,17 +544,42 @@ func (s *ContainerRegistryService) dockerHubCredentialForRegistryInternal(reg moreturn nil, "anonymous", "", nil}- return &imageupdatecore.Credentials{+ return &updaterregistry.Credentials{Username: username,Token: token,}, "credential", username, nil}-func (s *ContainerRegistryService) fetchDockerHubRateLimitInternal(ctx context.Context, credential *imageupdatecore.Credentials) (*imageupdatecore.RateLimitInfo, error) {- return imageupdatecore.FetchRegistryRateLimit(ctx, "docker.io", dockerHubRateLimitRepository, dockerHubRateLimitTag, credential, s.distributionHTTPClient)+func (s *ContainerRegistryService) fetchDockerHubRateLimitInternal(ctx context.Context, credential *updaterregistry.Credentials) (*updaterregistry.RateLimitInfo, error) {+ return updaterregistry.FetchRegistryRateLimit(ctx, "docker.io", dockerHubRateLimitRepository, dockerHubRateLimitTag, credential, dockerHubRateLimitHTTPClientInternal(s.distributionHTTPClient))+}++func dockerHubRateLimitHTTPClientInternal(httpClient *http.Client) *http.Client {+ if httpClient == nil {+ return nil+ }++ cloned := *httpClient+ baseTransport := cloned.Transport+ if baseTransport == nil {+ baseTransport = http.DefaultTransport+ }++ cloned.Transport = rateLimitRoundTripFuncInternal(func(req *http.Request) (*http.Response, error) {+ if req.Method == http.MethodGet &&+ req.URL.Host == "registry-1.docker.io" &&+ req.URL.Path == "/v2/"+dockerHubRateLimitRepository+"/manifests/"+dockerHubRateLimitTag {+ rewritten := req.Clone(req.Context())+ rewritten.Method = http.MethodHead+ req = rewritten+ }+ return baseTransport.RoundTrip(req)+ })++ return &cloned}-func (s *ContainerRegistryService) getCachedRateLimitInternal(ctx context.Context, registryID string) (*imageupdatecore.RateLimitInfo, time.Time, bool) {+func (s *ContainerRegistryService) getCachedRateLimitInternal(ctx context.Context, registryID string) (*updaterregistry.RateLimitInfo, time.Time, bool) {if s.kvService == nil || registryID == "" {return nil, time.Time{}, false}@@ -562,7 +605,7 @@ func (s *ContainerRegistryService) getCachedRateLimitInternal(ctx context.Contexreturn &entry.RateLimit, entry.CheckedAt, true}-func (s *ContainerRegistryService) setCachedRateLimitInternal(ctx context.Context, registryID string, rateLimit *imageupdatecore.RateLimitInfo, checkedAt time.Time) {+func (s *ContainerRegistryService) setCachedRateLimitInternal(ctx context.Context, registryID string, rateLimit *updaterregistry.RateLimitInfo, checkedAt time.Time) {if s.kvService == nil || registryID == "" || rateLimit == nil {return}@@ -717,7 +760,7 @@ func (s *ContainerRegistryService) GetImageDigest(ctx context.Context, imageRef}func (s *ContainerRegistryService) inspectImageDigestInternal(ctx context.Context, imageRef string, externalCreds []containerregistry.Credential) (*registryDigestResult, error) {- parts, err := imageupdatecore.NormalizeReference(imageRef)+ parts, err := updaterrefs.NormalizeReference(imageRef)if err != nil {return nil, err}@@ -806,7 +849,7 @@ func (s *ContainerRegistryService) inspectImageDigestViaDaemonInternal(ctx conteinspectResult, err := dockerClient.DistributionInspect(ctx, normalizedRef, client.DistributionInspectOptions{})if err == nil {- digest, normalizeErr := imageupdatecore.NormalizeDigest(inspectResult.Descriptor.Digest.String())+ digest, normalizeErr := updaterdigest.Normalize(inspectResult.Descriptor.Digest.String())if normalizeErr != nil {return nil, fmt.Errorf("distribution inspect returned invalid digest for %s: %w", normalizedRef, normalizeErr)}@@ -844,7 +887,7 @@ func (s *ContainerRegistryService) inspectImageDigestWithCredentialsInternal(ctxEncodedRegistryAuth: authHeader,})if err == nil {- digest, normalizeErr := imageupdatecore.NormalizeDigest(inspectResult.Descriptor.Digest.String())+ digest, normalizeErr := updaterdigest.Normalize(inspectResult.Descriptor.Digest.String())if normalizeErr != nil {return nil, fmt.Errorf("distribution inspect returned invalid digest for %s: %w", normalizedRef, normalizeErr)}@@ -1213,7 +1256,7 @@ func (s *ContainerRegistryService) deleteUnsyncedInternal(ctx context.Context, e}func normalizeImageReferenceForDistributionInternal(imageRef string) (string, string, error) {- parts, err := imageupdatecore.NormalizeReference(imageRef)+ parts, err := updaterrefs.NormalizeReference(imageRef)if err != nil {return "", "", err}@@ -1299,19 +1342,19 @@ func isDistributionFallbackEligibleInternal(err error) bool {return false}- return imageupdatecore.IsFallbackEligibleDaemonError(err)+ return updaterregistry.IsFallbackEligibleDaemonError(err)}func (s *ContainerRegistryService) fetchDigestFromRegistryInternal(ctx context.Context, registryHost, repository, tag string, credential *resolvedRegistryCredential) (string, error) {- var distributionCredential *imageupdatecore.Credentials+ var distributionCredential *updaterregistry.Credentialsif credential != nil {- distributionCredential = &imageupdatecore.Credentials{+ distributionCredential = &updaterregistry.Credentials{Username: strings.TrimSpace(credential.Username),Token: strings.TrimSpace(credential.Token),}}- return imageupdatecore.FetchDigest(+ return updaterregistry.FetchDigest(ctx,registryHost,repository,diff --git a/backend/internal/services/container_service.go b/backend/internal/services/container_service.goindex fe1c86c05..da524c408 100644--- a/backend/internal/services/container_service.go+++ b/backend/internal/services/container_service.go@@ -18,7 +18,6 @@ import (dockerutils "github.com/getarcaneapp/arcane/backend/pkg/dockerutil""github.com/getarcaneapp/arcane/backend/pkg/libarcane""github.com/getarcaneapp/arcane/backend/pkg/libarcane/containerstats"- libupdater "github.com/getarcaneapp/arcane/backend/pkg/libarcane/imageupdate""github.com/getarcaneapp/arcane/backend/pkg/libarcane/timeouts""github.com/getarcaneapp/arcane/backend/pkg/pagination""github.com/getarcaneapp/arcane/backend/pkg/projects"@@ -26,6 +25,7 @@ import (containertypes "github.com/getarcaneapp/arcane/types/container""github.com/getarcaneapp/arcane/types/containerregistry"imagetypes "github.com/getarcaneapp/arcane/types/image"+ libupdater "github.com/getarcaneapp/updater/pkg/labels""github.com/moby/moby/api/types/container""github.com/moby/moby/api/types/events""github.com/moby/moby/api/types/network"diff --git a/backend/internal/services/dashboard_service.go b/backend/internal/services/dashboard_service.goindex 33d15305e..6212f33fe 100644--- a/backend/internal/services/dashboard_service.go+++ b/backend/internal/services/dashboard_service.go@@ -10,12 +10,12 @@ import ("github.com/getarcaneapp/arcane/backend/internal/database""github.com/getarcaneapp/arcane/backend/internal/models"dockerutils "github.com/getarcaneapp/arcane/backend/pkg/dockerutil"- libupdater "github.com/getarcaneapp/arcane/backend/pkg/libarcane/imageupdate""github.com/getarcaneapp/arcane/types/base"containertypes "github.com/getarcaneapp/arcane/types/container"dashboardtypes "github.com/getarcaneapp/arcane/types/dashboard"imagetypes "github.com/getarcaneapp/arcane/types/image"versiontypes "github.com/getarcaneapp/arcane/types/version"+ libupdater "github.com/getarcaneapp/updater/pkg/labels"dockercontainer "github.com/moby/moby/api/types/container""golang.org/x/sync/errgroup")diff --git a/backend/internal/services/image_update_service.go b/backend/internal/services/image_update_service.goindex b7f677c11..5845d5040 100644--- a/backend/internal/services/image_update_service.go+++ b/backend/internal/services/image_update_service.go@@ -15,12 +15,12 @@ import ("github.com/getarcaneapp/arcane/backend/internal/models"activitylib "github.com/getarcaneapp/arcane/backend/pkg/libarcane/activity""github.com/getarcaneapp/arcane/backend/pkg/libarcane/crypto"- imageupdatecore "github.com/getarcaneapp/arcane/backend/pkg/libarcane/imageupdate""github.com/getarcaneapp/arcane/backend/pkg/libarcane/ratelimit"registry "github.com/getarcaneapp/arcane/backend/pkg/libarcane/registryauth""github.com/getarcaneapp/arcane/backend/pkg/utils""github.com/getarcaneapp/arcane/types/containerregistry""github.com/getarcaneapp/arcane/types/imageupdate"+ updaterdigest "github.com/getarcaneapp/updater/pkg/digest""github.com/moby/moby/api/types/image""github.com/moby/moby/client""golang.org/x/sync/errgroup"@@ -301,7 +301,7 @@ func (s *ImageUpdateService) parseImageReference(imageRef string) *ImageParts {// Fallback parser for cases where the official parser failsfunc (s *ImageUpdateService) parseImageReferenceFallback(imageRef string) *ImageParts {var registryHost, repository, tag string- if _, ok := imageupdatecore.DigestFromReferenceSuffix(imageRef); ok {+ if _, ok := updaterdigest.FromReferenceSuffix(imageRef); ok {digestParts := strings.Split(imageRef, "@")if len(digestParts) != 2 {return nil@@ -467,7 +467,7 @@ func (s *ImageUpdateService) inspectLocalImageSnapshotInternal(ctx context.Conte// Extract all digests from RepoDigestsif len(inspectResponse.RepoDigests) > 0 {for _, repoDigest := range inspectResponse.RepoDigests {- digest, ok := imageupdatecore.DigestFromReferenceSuffix(repoDigest)+ digest, ok := updaterdigest.FromReferenceSuffix(repoDigest)if !ok {continue}diff --git a/backend/internal/services/project_service.go b/backend/internal/services/project_service.goindex a91e472a5..20de3d662 100644--- a/backend/internal/services/project_service.go+++ b/backend/internal/services/project_service.go@@ -25,7 +25,6 @@ import ("github.com/getarcaneapp/arcane/backend/internal/database""github.com/getarcaneapp/arcane/backend/internal/models"dockerutil "github.com/getarcaneapp/arcane/backend/pkg/dockerutil"- libupdater "github.com/getarcaneapp/arcane/backend/pkg/libarcane/imageupdate""github.com/getarcaneapp/arcane/backend/pkg/libarcane/libbuild""github.com/getarcaneapp/arcane/backend/pkg/libarcane/timeouts""github.com/getarcaneapp/arcane/backend/pkg/pagination"@@ -37,6 +36,7 @@ import ("github.com/getarcaneapp/arcane/types/containerregistry"imagetypes "github.com/getarcaneapp/arcane/types/image""github.com/getarcaneapp/arcane/types/project"+ libupdater "github.com/getarcaneapp/updater/pkg/labels""github.com/moby/moby/api/types/container""gorm.io/gorm")diff --git a/backend/internal/services/project_service_test.go b/backend/internal/services/project_service_test.goindex 623a63b6b..ea5ff2267 100644--- a/backend/internal/services/project_service_test.go+++ b/backend/internal/services/project_service_test.go@@ -22,12 +22,12 @@ import (composeapi "github.com/docker/compose/v5/pkg/api""github.com/getarcaneapp/arcane/backend/internal/common""github.com/getarcaneapp/arcane/backend/internal/config"- libupdater "github.com/getarcaneapp/arcane/backend/pkg/libarcane/imageupdate""github.com/getarcaneapp/arcane/backend/pkg/pagination""github.com/getarcaneapp/arcane/backend/pkg/projects"buildtypes "github.com/getarcaneapp/arcane/types/builds"imagetypes "github.com/getarcaneapp/arcane/types/image"projecttypes "github.com/getarcaneapp/arcane/types/project"+ libupdater "github.com/getarcaneapp/updater/pkg/labels"glsqlite "github.com/glebarez/sqlite""github.com/moby/moby/api/types/container"dockertypesimage "github.com/moby/moby/api/types/image"diff --git a/backend/internal/services/settings_service.go b/backend/internal/services/settings_service.goindex 044a8fa8a..e59baa699 100644--- a/backend/internal/services/settings_service.go+++ b/backend/internal/services/settings_service.go@@ -107,88 +107,89 @@ func (s *SettingsService) getDefaultSettings() *models.Settings {// DefaultSettingsConfig returns the canonical default settings model used by Arcane.func DefaultSettingsConfig() *models.Settings {return &models.Settings{- ProjectsDirectory: models.SettingVariable{Value: "/app/data/projects"},- TemplatesDirectory: models.SettingVariable{Value: "/app/data/templates"},- FollowProjectSymlinks: models.SettingVariable{Value: "false"},- SwarmStackSourcesDirectory: models.SettingVariable{Value: "/app/data/swarm/sources"},- DiskUsagePath: models.SettingVariable{Value: "/app/data/projects"},- AutoUpdate: models.SettingVariable{Value: "false"},- AutoUpdateInterval: models.SettingVariable{Value: "0 0 0 * * *"},- 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 * * *"},- ExpiredSessionsCleanupInterval: models.SettingVariable{Value: "0 0 0 * * *"},- ActivityHistoryRetentionDays: models.SettingVariable{Value: "30"},- ActivityHistoryMaxEntries: models.SettingVariable{Value: "1000"},- AutoInjectEnv: models.SettingVariable{Value: "false"},- DefaultDeployPullPolicy: models.SettingVariable{Value: "missing"},- ScheduledPruneEnabled: models.SettingVariable{Value: "false"},- ScheduledPruneInterval: models.SettingVariable{Value: "0 0 0 * * *"},- PruneContainerMode: models.SettingVariable{Value: "stopped"},- PruneContainerUntil: models.SettingVariable{Value: ""},- PruneImageMode: models.SettingVariable{Value: "dangling"},- PruneImageUntil: models.SettingVariable{Value: ""},- PruneVolumeMode: models.SettingVariable{Value: "none"},- PruneNetworkMode: models.SettingVariable{Value: "unused"},- PruneNetworkUntil: models.SettingVariable{Value: ""},- PruneBuildCacheMode: models.SettingVariable{Value: "none"},- PruneBuildCacheUntil: models.SettingVariable{Value: ""},- AutoHealEnabled: models.SettingVariable{Value: "false"},- AutoHealInterval: models.SettingVariable{Value: "*/30 * * * * *"},- 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"},- DefaultShell: models.SettingVariable{Value: "/bin/sh"},- DockerHost: models.SettingVariable{Value: "unix:///var/run/docker.sock"},- BuildsDirectory: models.SettingVariable{Value: "/builds"},- AuthLocalEnabled: models.SettingVariable{Value: "true"},- AuthSessionTimeout: models.SettingVariable{Value: "1440"},- AuthPasswordPolicy: models.SettingVariable{Value: "strong"},- VulnerabilityScanEnabled: models.SettingVariable{Value: "false"},- VulnerabilityScanInterval: models.SettingVariable{Value: "0 0 0 * * *"},- TrivyImage: models.SettingVariable{Value: DefaultTrivyImage},- TrivyNetwork: models.SettingVariable{Value: ""},- TrivySecurityOpts: models.SettingVariable{Value: ""},- TrivyPrivileged: models.SettingVariable{Value: "false"},- TrivyPreserveCacheOnVolumePrune: models.SettingVariable{Value: "true"},- TrivyResourceLimitsEnabled: models.SettingVariable{Value: "true"},- TrivyCpuLimit: models.SettingVariable{Value: "1"},- TrivyMemoryLimitMb: models.SettingVariable{Value: "0"},- TrivyConcurrentScanContainers: models.SettingVariable{Value: "1"},- OidcEnabled: models.SettingVariable{Value: "false"},- OidcClientId: models.SettingVariable{Value: ""},- OidcClientSecret: models.SettingVariable{Value: ""},- OidcIssuerUrl: models.SettingVariable{Value: ""},- OidcAuthorizationEndpoint: models.SettingVariable{Value: ""},- OidcTokenEndpoint: models.SettingVariable{Value: ""},- OidcUserinfoEndpoint: models.SettingVariable{Value: ""},- OidcJwksEndpoint: models.SettingVariable{Value: ""},- OidcScopes: models.SettingVariable{Value: "openid email profile"},- OidcGroupsClaim: models.SettingVariable{Value: "groups"},- OidcSkipTlsVerify: models.SettingVariable{Value: "false"},- OidcAutoRedirectToProvider: models.SettingVariable{Value: "false"},- OidcMergeAccounts: models.SettingVariable{Value: "false"},- OidcProviderName: models.SettingVariable{Value: ""},- OidcProviderLogoUrl: models.SettingVariable{Value: ""},- OidcMobileRedirectUris: models.SettingVariable{Value: "arcane-mobile://oidc-callback"},- MobileNavigationMode: models.SettingVariable{Value: "floating"},- MobileNavigationShowLabels: models.SettingVariable{Value: "true"},- SidebarHoverExpansion: models.SettingVariable{Value: "true"},- KeyboardShortcutsEnabled: models.SettingVariable{Value: "true"},- ApplicationTheme: models.SettingVariable{Value: "default"},- AccentColor: models.SettingVariable{Value: "oklch(0.606 0.25 292.717)"},- OledMode: models.SettingVariable{Value: "false"},- MaxImageUploadSize: models.SettingVariable{Value: "500"},- GitSyncMaxFiles: models.SettingVariable{Value: "500"},- GitSyncMaxTotalSizeMb: models.SettingVariable{Value: "50"},- GitSyncMaxBinarySizeMb: models.SettingVariable{Value: "10"},- EnvironmentHealthInterval: models.SettingVariable{Value: "0 */2 * * * *"},+ ProjectsDirectory: models.SettingVariable{Value: "/app/data/projects"},+ TemplatesDirectory: models.SettingVariable{Value: "/app/data/templates"},+ FollowProjectSymlinks: models.SettingVariable{Value: "false"},+ SwarmStackSourcesDirectory: models.SettingVariable{Value: "/app/data/swarm/sources"},+ DiskUsagePath: models.SettingVariable{Value: "/app/data/projects"},+ AutoUpdate: models.SettingVariable{Value: "false"},+ AutoUpdateInterval: models.SettingVariable{Value: "0 0 0 * * *"},+ AutoUpdateExcludedContainers: models.SettingVariable{Value: ""},+ AutoUpdateComposeStandaloneFallback: models.SettingVariable{Value: "false"},+ PollingEnabled: models.SettingVariable{Value: "true"},+ PollingInterval: models.SettingVariable{Value: "0 0 * * * *"},+ DockerClientRefreshInterval: models.SettingVariable{Value: "*/30 * * * * *"},+ EventCleanupInterval: models.SettingVariable{Value: "0 0 */6 * * *"},+ ExpiredSessionsCleanupInterval: models.SettingVariable{Value: "0 0 0 * * *"},+ ActivityHistoryRetentionDays: models.SettingVariable{Value: "30"},+ ActivityHistoryMaxEntries: models.SettingVariable{Value: "1000"},+ AutoInjectEnv: models.SettingVariable{Value: "false"},+ DefaultDeployPullPolicy: models.SettingVariable{Value: "missing"},+ ScheduledPruneEnabled: models.SettingVariable{Value: "false"},+ ScheduledPruneInterval: models.SettingVariable{Value: "0 0 0 * * *"},+ PruneContainerMode: models.SettingVariable{Value: "stopped"},+ PruneContainerUntil: models.SettingVariable{Value: ""},+ PruneImageMode: models.SettingVariable{Value: "dangling"},+ PruneImageUntil: models.SettingVariable{Value: ""},+ PruneVolumeMode: models.SettingVariable{Value: "none"},+ PruneNetworkMode: models.SettingVariable{Value: "unused"},+ PruneNetworkUntil: models.SettingVariable{Value: ""},+ PruneBuildCacheMode: models.SettingVariable{Value: "none"},+ PruneBuildCacheUntil: models.SettingVariable{Value: ""},+ AutoHealEnabled: models.SettingVariable{Value: "false"},+ AutoHealInterval: models.SettingVariable{Value: "*/30 * * * * *"},+ 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"},+ DefaultShell: models.SettingVariable{Value: "/bin/sh"},+ DockerHost: models.SettingVariable{Value: "unix:///var/run/docker.sock"},+ BuildsDirectory: models.SettingVariable{Value: "/builds"},+ AuthLocalEnabled: models.SettingVariable{Value: "true"},+ AuthSessionTimeout: models.SettingVariable{Value: "1440"},+ AuthPasswordPolicy: models.SettingVariable{Value: "strong"},+ VulnerabilityScanEnabled: models.SettingVariable{Value: "false"},+ VulnerabilityScanInterval: models.SettingVariable{Value: "0 0 0 * * *"},+ TrivyImage: models.SettingVariable{Value: DefaultTrivyImage},+ TrivyNetwork: models.SettingVariable{Value: ""},+ TrivySecurityOpts: models.SettingVariable{Value: ""},+ TrivyPrivileged: models.SettingVariable{Value: "false"},+ TrivyPreserveCacheOnVolumePrune: models.SettingVariable{Value: "true"},+ TrivyResourceLimitsEnabled: models.SettingVariable{Value: "true"},+ TrivyCpuLimit: models.SettingVariable{Value: "1"},+ TrivyMemoryLimitMb: models.SettingVariable{Value: "0"},+ TrivyConcurrentScanContainers: models.SettingVariable{Value: "1"},+ OidcEnabled: models.SettingVariable{Value: "false"},+ OidcClientId: models.SettingVariable{Value: ""},+ OidcClientSecret: models.SettingVariable{Value: ""},+ OidcIssuerUrl: models.SettingVariable{Value: ""},+ OidcAuthorizationEndpoint: models.SettingVariable{Value: ""},+ OidcTokenEndpoint: models.SettingVariable{Value: ""},+ OidcUserinfoEndpoint: models.SettingVariable{Value: ""},+ OidcJwksEndpoint: models.SettingVariable{Value: ""},+ OidcScopes: models.SettingVariable{Value: "openid email profile"},+ OidcGroupsClaim: models.SettingVariable{Value: "groups"},+ OidcSkipTlsVerify: models.SettingVariable{Value: "false"},+ OidcAutoRedirectToProvider: models.SettingVariable{Value: "false"},+ OidcMergeAccounts: models.SettingVariable{Value: "false"},+ OidcProviderName: models.SettingVariable{Value: ""},+ OidcProviderLogoUrl: models.SettingVariable{Value: ""},+ OidcMobileRedirectUris: models.SettingVariable{Value: "arcane-mobile://oidc-callback"},+ MobileNavigationMode: models.SettingVariable{Value: "floating"},+ MobileNavigationShowLabels: models.SettingVariable{Value: "true"},+ SidebarHoverExpansion: models.SettingVariable{Value: "true"},+ KeyboardShortcutsEnabled: models.SettingVariable{Value: "true"},+ ApplicationTheme: models.SettingVariable{Value: "default"},+ AccentColor: models.SettingVariable{Value: "oklch(0.606 0.25 292.717)"},+ OledMode: models.SettingVariable{Value: "false"},+ MaxImageUploadSize: models.SettingVariable{Value: "500"},+ GitSyncMaxFiles: models.SettingVariable{Value: "500"},+ GitSyncMaxTotalSizeMb: models.SettingVariable{Value: "50"},+ GitSyncMaxBinarySizeMb: models.SettingVariable{Value: "10"},+ EnvironmentHealthInterval: models.SettingVariable{Value: "0 */2 * * * *"},DockerAPITimeout: models.SettingVariable{Value: "30"},DockerImagePullTimeout: models.SettingVariable{Value: "600"},diff --git a/backend/internal/services/settings_service_test.go b/backend/internal/services/settings_service_test.goindex 13d81fc2e..8ebd97a45 100644--- a/backend/internal/services/settings_service_test.go+++ b/backend/internal/services/settings_service_test.go@@ -43,7 +43,7 @@ func TestSettingsService_EnsureDefaultSettings_Idempotent(t *testing.T) {require.Equal(t, count1, count2)// Spot-check core and automation defaults exist with correct values- for _, key := range []string{"authLocalEnabled", "projectsDirectory", "followProjectSymlinks", "autoUpdateExcludedContainers", "vulnerabilityScanEnabled", "vulnerabilityScanInterval", "trivyImage", "trivyNetwork", "trivySecurityOpts", "trivyPrivileged", "trivyPreserveCacheOnVolumePrune", "trivyResourceLimitsEnabled", "trivyCpuLimit", "trivyMemoryLimitMb", "trivyConcurrentScanContainers", "gitSyncMaxFiles", "gitSyncMaxTotalSizeMb", "gitSyncMaxBinarySizeMb"} {+ for _, key := range []string{"authLocalEnabled", "projectsDirectory", "followProjectSymlinks", "autoUpdateExcludedContainers", "autoUpdateComposeStandaloneFallback", "vulnerabilityScanEnabled", "vulnerabilityScanInterval", "trivyImage", "trivyNetwork", "trivySecurityOpts", "trivyPrivileged", "trivyPreserveCacheOnVolumePrune", "trivyResourceLimitsEnabled", "trivyCpuLimit", "trivyMemoryLimitMb", "trivyConcurrentScanContainers", "gitSyncMaxFiles", "gitSyncMaxTotalSizeMb", "gitSyncMaxBinarySizeMb"} {var sv models.SettingVariableerr := svc.db.WithContext(ctx).Where("key = ?", key).First(&sv).Errorrequire.NoErrorf(t, err, "missing default key %s", key)@@ -53,6 +53,8 @@ func TestSettingsService_EnsureDefaultSettings_Idempotent(t *testing.T) {require.Equal(t, "false", sv.Value)case "autoUpdateExcludedContainers":require.Equal(t, "", sv.Value)+ case "autoUpdateComposeStandaloneFallback":+ require.Equal(t, "false", sv.Value)case "vulnerabilityScanEnabled":require.Equal(t, "false", sv.Value)case "vulnerabilityScanInterval":diff --git a/backend/internal/services/system_service.go b/backend/internal/services/system_service.goindex bbf0874e5..8a72b48a5 100644--- a/backend/internal/services/system_service.go+++ b/backend/internal/services/system_service.go@@ -13,10 +13,10 @@ import ("github.com/getarcaneapp/arcane/backend/internal/models"activitylib "github.com/getarcaneapp/arcane/backend/pkg/libarcane/activity""github.com/getarcaneapp/arcane/backend/pkg/libarcane/dockerrun"- libupdater "github.com/getarcaneapp/arcane/backend/pkg/libarcane/imageupdate""github.com/getarcaneapp/arcane/backend/pkg/utils"containertypes "github.com/getarcaneapp/arcane/types/container""github.com/getarcaneapp/arcane/types/system"+ libupdater "github.com/getarcaneapp/updater/pkg/labels""github.com/goccy/go-yaml""github.com/moby/moby/api/types/container""github.com/moby/moby/client"diff --git a/backend/internal/services/system_upgrade_service.go b/backend/internal/services/system_upgrade_service.goindex cf0a59f69..9349f4e39 100644--- a/backend/internal/services/system_upgrade_service.go+++ b/backend/internal/services/system_upgrade_service.go@@ -14,8 +14,8 @@ import ("github.com/getarcaneapp/arcane/backend/internal/models"dockerutils "github.com/getarcaneapp/arcane/backend/pkg/dockerutil""github.com/getarcaneapp/arcane/backend/pkg/libarcane"- libupdater "github.com/getarcaneapp/arcane/backend/pkg/libarcane/imageupdate""github.com/getarcaneapp/arcane/backend/pkg/libarcane/timeouts"+ libupdater "github.com/getarcaneapp/updater/pkg/labels"containertypes "github.com/moby/moby/api/types/container"mounttypes "github.com/moby/moby/api/types/mount""github.com/moby/moby/client"diff --git a/backend/internal/services/system_upgrade_service_test.go b/backend/internal/services/system_upgrade_service_test.goindex f76ace096..3bf4a30a2 100644--- a/backend/internal/services/system_upgrade_service_test.go+++ b/backend/internal/services/system_upgrade_service_test.go@@ -6,7 +6,7 @@ import ("testing""github.com/getarcaneapp/arcane/backend/internal/common"- libupdater "github.com/getarcaneapp/arcane/backend/pkg/libarcane/imageupdate"+ libupdater "github.com/getarcaneapp/updater/pkg/labels"containertypes "github.com/moby/moby/api/types/container"mounttypes "github.com/moby/moby/api/types/mount"networktypes "github.com/moby/moby/api/types/network"diff --git a/backend/internal/services/updater_service.go b/backend/internal/services/updater_service.goindex cc564358c..e82f8daaf 100644--- a/backend/internal/services/updater_service.go+++ b/backend/internal/services/updater_service.go@@ -7,55 +7,58 @@ import ("io""log/slog""maps"- "net"- "net/url""slices""strings"- "sync""time""github.com/compose-spec/compose-go/v2/loader"- "github.com/moby/moby/api/types/container"- "github.com/moby/moby/api/types/network"- "github.com/moby/moby/client"-+ "github.com/getarcaneapp/arcane/backend/internal/common""github.com/getarcaneapp/arcane/backend/internal/database""github.com/getarcaneapp/arcane/backend/internal/models"dockerutil "github.com/getarcaneapp/arcane/backend/pkg/dockerutil""github.com/getarcaneapp/arcane/backend/pkg/libarcane"activitylib "github.com/getarcaneapp/arcane/backend/pkg/libarcane/activity"- libupdater "github.com/getarcaneapp/arcane/backend/pkg/libarcane/imageupdate"projectspkg "github.com/getarcaneapp/arcane/backend/pkg/projects""github.com/getarcaneapp/arcane/backend/pkg/utils""github.com/getarcaneapp/arcane/types/updater"+ moduleapi "github.com/getarcaneapp/updater/api"+ updaterdigest "github.com/getarcaneapp/updater/pkg/digest"+ "github.com/getarcaneapp/updater/pkg/labels"+ "github.com/getarcaneapp/updater/pkg/refs"+ moduletypes "github.com/getarcaneapp/updater/types"+ "github.com/moby/moby/api/types/container"+ "github.com/moby/moby/client")-// UpdaterService coordinates image update checks, container recreation, and-// project redeploy flows for Arcane's auto-update system.-type UpdaterService struct {- db *database.DB- settingsService *SettingsService- dockerService *DockerClientService- projectService *ProjectService- imageUpdateService *ImageUpdateService- registryService *ContainerRegistryService- eventService *EventService- imageService *ImageService- notificationService *NotificationService- upgradeService selfUpgradeService- activityService *ActivityService-- statusMu sync.RWMutex- updatingContainers map[string]bool- updatingProjects map[string]bool-}+const autoUpdateComposeStandaloneFallbackSettingKeyInternal = "autoUpdateComposeStandaloneFallback"-type selfUpgradeService interface {+// UpdaterService is Arcane's handler-facing service for the standalone updater engine.+type UpdaterService struct {+ deps updaterDependenciesInternal+ engine *moduleapi.Service+}++type updaterDependenciesInternal struct {+ DB *database.DB+ Docker *DockerClientService+ Settings *SettingsService+ Projects *ProjectService+ ImagePuller *ImageService+ ImageUpdates *ImageUpdateService+ RegistryDigestResolver *ContainerRegistryService+ Events *EventService+ Notifications *NotificationService+ SelfUpgrade selfUpgradeServiceInternal+ Activity *ActivityService+ SystemUser models.User+ Logger *slog.Logger+}++type selfUpgradeServiceInternal interface {TriggerUpgradeViaCLI(ctx context.Context, user models.User) error}-// NewUpdaterService constructs an UpdaterService with the dependencies needed-// to plan, execute, and record container and project updates.+// NewUpdaterService constructs the Arcane updater facade.func NewUpdaterService(db *database.DB,settings *SettingsService,@@ -66,360 +69,494 @@ func NewUpdaterService(events *EventService,imageSvc *ImageService,notifications *NotificationService,- upgrade selfUpgradeService,+ upgrade selfUpgradeServiceInternal,activityService *ActivityService,) *UpdaterService {- return &UpdaterService{- db: db,- settingsService: settings,- dockerService: docker,- projectService: projects,- imageUpdateService: imageUpdates,- registryService: registries,- eventService: events,- imageService: imageSvc,- notificationService: notifications,- upgradeService: upgrade,- activityService: activityService,- updatingContainers: map[string]bool{},- updatingProjects: map[string]bool{},+ service := &UpdaterService{+ deps: updaterDependenciesInternal{+ DB: db,+ Docker: docker,+ Settings: settings,+ Projects: projects,+ ImagePuller: imageSvc,+ ImageUpdates: imageUpdates,+ RegistryDigestResolver: registries,+ Events: events,+ Notifications: notifications,+ SelfUpgrade: upgrade,+ Activity: activityService,+ SystemUser: systemUser,+ },+ }+ service.engine = moduleapi.NewService(service.configInternal(context.Background()))+ return service+}++func (s *UpdaterService) configInternal(ctx context.Context) moduleapi.Config {+ return moduleapi.Config{+ DockerClientProvider: s,+ ImagePuller: s,+ PendingStore: s,+ RunRecorder: s,+ Settings: s,+ RegistryDigestResolver: s.registryDigestResolverInternal(),+ ProjectUpdater: s,+ SelfUpdater: s,+ Notifier: s,+ EventRecorder: s,+ UsedImageCollector: moduleapi.UsedImageCollectorFunc(s.CollectUsedImages),+ LabelPolicy: labels.DefaultLabelPolicy(),+ AllowComposeStandaloneFallback: s.allowComposeStandaloneFallbackInternal(ctx),+ Logger: s.loggerInternal(),+ }+}++func (s *UpdaterService) engineInternal() *moduleapi.Service {+ return s.engine+}++func (s *UpdaterService) loggerInternal() *slog.Logger {+ if s.deps.Logger != nil {+ return s.deps.Logger+ }+ return slog.Default()+}++func (s *UpdaterService) allowComposeStandaloneFallbackInternal(ctx context.Context) bool {+ if s == nil || s.deps.Settings == nil {+ return false+ }+ return s.deps.Settings.GetBoolSetting(ctx, autoUpdateComposeStandaloneFallbackSettingKeyInternal, false)+}++func (s *UpdaterService) registryDigestResolverInternal() updaterdigest.RemoteResolver {+ if s == nil || s.deps.RegistryDigestResolver == nil {+ return nil}+ return s.deps.RegistryDigestResolver}-// ApplyPending executes the currently pending image updates and returns a-// per-resource result summary. When dryRun is true, it reports the planned-// actions without mutating containers or projects.-//-//nolint:gocognit,gocyclo,maintidx // large but sequential update-orchestration flow; refactor tracked separately+// ApplyPending executes pending image updates.func (s *UpdaterService) ApplyPending(ctx context.Context, dryRun bool) (out *updater.Result, err error) {start := time.Now()- out = &updater.Result{Items: []updater.ResourceResult{}}activityID := s.startAutoUpdateActivityInternal(ctx, dryRun)- out.ActivityID = utils.StringPtrFromTrimmed(activityID)- ctx = s.activityService.Track(ctx, activityID)+ out = &updater.Result{Items: []updater.ResourceResult{}, ActivityID: utils.StringPtrFromTrimmed(activityID)}+ ctx = s.trackActivityInternal(ctx, activityID)+ ctx = contextWithActivityIDInternal(ctx, activityID)+defer func() {- if out != nil {- out.ActivityID = utils.StringPtrFromTrimmed(activityID)+ if out == nil {+ out = &updater.Result{Items: []updater.ResourceResult{}}+ }+ if out.Duration == "" {+ out.Duration = time.Since(start).String()}+ out.ActivityID = utils.StringPtrFromTrimmed(activityID)s.completeAutoUpdateActivityInternal(ctx, activityID, out, err)}()- var records []models.ImageUpdateRecord- if err := s.db.WithContext(ctx).Where("has_update = ?", true).Find(&records).Error; err != nil {- return nil, fmt.Errorf("query pending image updates: %w", err)- }- // debug: how many pending records and dryRun flag- slog.DebugContext(ctx, "ApplyPending: found pending image update records", "records", len(records), "dryRun", dryRun)- s.appendAutoUpdateActivityMessageInternal(ctx, activityID, fmt.Sprintf("Found %d pending image update records", len(records)), "Planning updates", 10)-- if len(records) == 0 {- out.Duration = time.Since(start).String()- return out, nil- }+ s.recordAutoUpdateEventInternal(ctx, models.EventSeverityInfo, models.JSON{+ "phase": "start",+ "dryRun": dryRun,+ "time": time.Now().UTC().Format(time.RFC3339),+ })+ s.appendAutoUpdateActivityMessageInternal(ctx, activityID, "Planning pending updates", "Planning updates", 5)- // Only update images that are actually used by running resources- usedImages, err := s.collectUsedImages(ctx)- if err != nil {- slog.WarnContext(ctx, "ApplyPending: failed to collect actively used images; skipping update run", "error", err)- out.Duration = time.Since(start).String()- return out, nil+ moduleResult, engineErr := s.engineInternal().ApplyPending(ctx, moduletypes.Options{DryRun: dryRun})+ if moduleResult != nil {+ out = resultFromModuleInternal(moduleResult)+ out.ActivityID = utils.StringPtrFromTrimmed(activityID)+ s.logResultItemsInternal(ctx, out)}- if len(usedImages) == 0 {- slog.DebugContext(ctx, "ApplyPending: no actively used images found; nothing to update")- out.Duration = time.Since(start).String()- return out, nil+ if engineErr != nil {+ err = engineErr+ return out, err}- // Plan updates and capture OLD image digests before pull- type updatePlan struct {- oldRef string- newRef string- oldIDs []string // sha256:... image IDs that currently back oldRef- pulled bool+ if !dryRun && s.deps.ImageUpdates != nil {+ s.appendAutoUpdateActivityMessageInternal(ctx, activityID, "Cleaning up update records", "Cleaning up", 95)+ if cleanupErr := s.deps.ImageUpdates.CleanupOrphanedRecords(ctx); cleanupErr != nil {+ s.loggerInternal().WarnContext(ctx, "cleanup orphaned update records failed", "error", cleanupErr)+ }}- var plans []updatePlan- for _, r := range records {- if r.Repository == "" || r.Tag == "" {- continue- }- oldRef := fmt.Sprintf("%s:%s", r.Repository, r.Tag)- oldNorm := libupdater.NormalizeImageUpdateRef(oldRef)- if oldNorm == "" {- slog.DebugContext(ctx, "ApplyPending: skipping invalid pending image reference", "imageRef", oldRef)- continue- }+ s.recordAutoUpdateEventInternal(ctx, models.EventSeverityInfo, models.JSON{+ "phase": "complete",+ "checked": out.Checked,+ "updated": out.Updated,+ "skipped": out.Skipped,+ "failed": out.Failed,+ "duration": out.Duration,+ "time": time.Now().UTC().Format(time.RFC3339),+ })+ return out, nil+}- if _, ok := usedImages[oldNorm]; !ok {- continue- }+// UpdateSingleContainer updates a single container by ID to the latest available image.+func (s *UpdaterService) UpdateSingleContainer(ctx context.Context, containerID string) (out *updater.Result, err error) {+ start := time.Now()+ activityID := s.startSingleContainerUpdateActivityInternal(ctx, containerID)+ out = &updater.Result{Items: []updater.ResourceResult{}, ActivityID: utils.StringPtrFromTrimmed(activityID)}+ ctx = s.trackActivityInternal(ctx, activityID)+ ctx = contextWithActivityIDInternal(ctx, activityID)- newRef := oldRef- if r.IsTagUpdate() && r.LatestVersion != nil && *r.LatestVersion != "" {- newRef = fmt.Sprintf("%s:%s", r.Repository, *r.LatestVersion)+ defer func() {+ if out == nil {+ out = &updater.Result{Items: []updater.ResourceResult{}}}+ if out.Duration == "" {+ out.Duration = time.Since(start).String()+ }+ out.ActivityID = utils.StringPtrFromTrimmed(activityID)+ s.completeAutoUpdateActivityInternal(ctx, activityID, out, err)+ }()- oldIDs, _ := s.resolveLocalImageIDsForRef(ctx, oldRef)- oldIDs = libupdater.AppendImageUpdateRecordIDToOldIDs(oldIDs, r.ID)- plans = append(plans, updatePlan{oldRef: oldRef, newRef: newRef, oldIDs: oldIDs})+ moduleResult, engineErr := s.engineInternal().UpdateContainer(ctx, containerID, moduletypes.Options{})+ if moduleResult != nil {+ out = resultFromModuleInternal(moduleResult)+ out.ActivityID = utils.StringPtrFromTrimmed(activityID)+ s.logResultItemsInternal(ctx, out)}+ if engineErr != nil {+ err = engineErr+ return out, err+ }+ return out, nil+}++// GetStatus returns the current in-memory update activity snapshot.+func (s *UpdaterService) GetStatus() updater.Status {+ return statusFromModuleInternal(s.engineInternal().Status())+}- if len(plans) == 0 {- s.appendAutoUpdateActivityMessageInternal(ctx, activityID, "No active resources need updates", "Planning updates", 100)- out.Duration = time.Since(start).String()- return out, nil+// GetHistory returns the most recent auto-update history records, newest first.+func (s *UpdaterService) GetHistory(ctx context.Context, limit int) ([]models.AutoUpdateRecord, error) {+ var records []models.AutoUpdateRecord+ query := s.deps.DB.WithContext(ctx).Order("start_time DESC")+ if limit > 0 {+ query = query.Limit(limit)+ }+ if err := query.Find(&records).Error; err != nil {+ return nil, fmt.Errorf("get history: %w", err)}+ return records, nil+}- // Log run start- s.logAutoUpdate(ctx, models.EventSeverityInfo, models.JSON{- "phase": "start",- "dryRun": dryRun,- "planned": len(plans),- "time": time.Now().UTC().Format(time.RFC3339),+// RestartContainersUsingOldIDs restarts containers matching old image IDs or refs.+func (s *UpdaterService) RestartContainersUsingOldIDs(ctx context.Context, oldIDToNewRef map[string]string, oldRefToNewRef map[string]string) ([]updater.ResourceResult, error) {+ results, err := s.engineInternal().RestartContainersUsingOldImages(ctx, oldIDToNewRef, oldRefToNewRef)+ return resourceResultsFromModuleInternal(results), err+}++// TriggerSelfUpdateViaCLI triggers Arcane's detached CLI self-update path.+func (s *UpdaterService) TriggerSelfUpdateViaCLI(ctx context.Context, source, containerID, containerName string, labelMap map[string]string) error {+ if !labels.IsArcaneContainer(labelMap) {+ return fmt.Errorf("%s: container is not an Arcane self-update target", source)+ }+ return s.TriggerSelfUpdate(ctx, moduletypes.SelfUpdateTarget{+ ContainerID: containerID,+ ContainerName: containerName,+ InstanceType: instanceTypeFromLabelsInternal(labelMap),+ Labels: labelMap,})+}++// BeginContainerUpdate marks a container as updating.+func (s *UpdaterService) BeginContainerUpdate(containerID string) func() {+ return s.engineInternal().BeginContainerUpdate(containerID)+}++// BeginProjectUpdate marks a project as updating.+func (s *UpdaterService) BeginProjectUpdate(projectID string) func() {+ return s.engineInternal().BeginProjectUpdate(projectID)+}- // Pull images with ImageService (waits for completion)- // Only containers using the OLD image IDs will be restarted after pulls succeed.- // This prevents restarts when pulls fail or when the image digest didn't change.- dcli, err := s.dockerService.GetClient(ctx)+func (s *UpdaterService) recordAutoUpdateEventInternal(ctx context.Context, severity models.EventSeverity, metadata models.JSON) {+ if s.deps.Events == nil {+ return+ }+ phase, _ := metadata["phase"].(string)+ _, err := s.deps.Events.CreateEvent(ctx, CreateEventRequest{+ Type: models.EventTypeSystemAutoUpdate,+ Severity: severity,+ Title: autoUpdateEventTitleInternal(phase, metadata),+ ResourceType: utils.StringPtrFromTrimmed("system"),+ ResourceName: utils.StringPtrFromTrimmed("auto_updater"),+ EnvironmentID: utils.StringPtrFromTrimmed("0"),+ Metadata: metadata,+ })if err != nil {- return nil, fmt.Errorf("docker connect: %w", err)- }- digestChecker := libupdater.NewDigestChecker(dcli, s.registryService)-- // track all old image IDs we saw for pulled updates so we can prune them after restart- oldIDSet := map[string]struct{}{}-- for i := range plans {- p := plans[i]- s.appendAutoUpdateActivityMessageInternal(ctx, activityID, "Checking update for "+p.oldRef, "Checking image", 20)- item := updater.ResourceResult{- ResourceID: p.oldRef,- ResourceType: "image",- ResourceName: p.oldRef,- Status: "checked",- OldImages: map[string]string{"main": p.oldRef},- NewImages: map[string]string{"main": p.newRef},+ s.loggerInternal().DebugContext(ctx, "failed to record auto-update event", "error", err)+ }+}++func instanceTypeFromLabelsInternal(labelMap map[string]string) string {+ if labels.IsArcaneAgentContainer(labelMap) {+ return "agent"+ }+ return "server"+}++func autoUpdateEventTitleInternal(phase string, metadata models.JSON) string {+ switch phase {+ case "start":+ return "Auto-update run started"+ case "image_pull", "image":+ image := strings.TrimSpace(fmt.Sprint(metadata["imageNew"]))+ if image == "" {+ image = strings.TrimSpace(fmt.Sprint(metadata["imageOld"]))}- out.Checked++-- if dryRun {- item.Status = "skipped"- out.Skipped++- out.Items = append(out.Items, item)- _ = s.recordRun(ctx, item)-- s.logAutoUpdate(ctx, s.severityFromStatus(item.Status), models.JSON{- "phase": "image_pull",- "imageOld": p.oldRef,- "imageNew": p.newRef,- "status": item.Status,- "dryRun": true,- })- continue+ if image != "" {+ return "Auto-update: image pull " + image}-- // Digest pre-check: if registry supports it and digests match, avoid pulling entirely.- // This also prevents unnecessary restarts when the update record is stale.- normNew := libupdater.NormalizeImageUpdateRef(p.newRef)- check := digestChecker.CheckImageNeedsUpdate(ctx, normNew)- skipPull := false-- if check.CheckedViaAPI && check.Error == nil && !check.NeedsUpdate {- item.Status = "skipped"- item.Error = "image already up to date"- out.Skipped++- // Image is already up to date — do NOT mark as pulled so that- // containers using this image are not scheduled for recreation.- skipPull = true-- s.logAutoUpdate(ctx, s.severityFromStatus(item.Status), models.JSON{- "phase": "image_pull",- "imageOld": p.oldRef,- "imageNew": p.newRef,- "status": item.Status,- "digestLocal": check.LocalDigest,- "digestRemote": check.RemoteDigest,- "checkedViaApi": true,- "error": item.Error,- })+ return "Auto-update: image pull"+ case "image_prune":+ imageID := strings.TrimSpace(fmt.Sprint(metadata["imageId"]))+ if imageID != "" {+ return "Auto-update: image prune " + imageID}-- if !skipPull {- progressWriter := activitylib.NewWriter(ctx, s.activityService, activityID, io.Discard, "Pulling updated images")- err := s.imageService.PullImage(ctx, p.newRef, progressWriter, systemUser, nil)- activitylib.FlushWriter(progressWriter)- if err != nil {- item.Status = "failed"- item.Error = err.Error()- out.Failed++- } else {- item.Status = "updated"- item.UpdateApplied = true- out.Updated++- plans[i].pulled = true- for _, id := range p.oldIDs {- if id != "" {- oldIDSet[id] = struct{}{}- }- }- }- s.logAutoUpdate(ctx, s.severityFromStatus(item.Status), models.JSON{- "phase": "image_pull",- "imageOld": p.oldRef,- "imageNew": p.newRef,- "status": item.Status,- "error": item.Error,- })+ return "Auto-update: image prune"+ case "container":+ name := strings.TrimSpace(fmt.Sprint(metadata["resourceName"]))+ if name == "" {+ name = strings.TrimSpace(fmt.Sprint(metadata["container"]))+ }+ if name == "" {+ name = strings.TrimSpace(fmt.Sprint(metadata["containerId"]))+ }+ if name != "" {+ return "Auto-update: container " + name}+ return "Auto-update: container"+ case "project":+ name := strings.TrimSpace(fmt.Sprint(metadata["projectName"]))+ if name == "" {+ name = strings.TrimSpace(fmt.Sprint(metadata["projectId"]))+ }+ if name != "" {+ return "Auto-update: project " + name+ }+ return "Auto-update: project"+ case "complete":+ return "Auto-update run completed"+ default:+ if phase != "" {+ return "Auto-update: " + phase+ }+ return "Auto-update"+ }+}- out.Items = append(out.Items, item)- _ = s.recordRun(ctx, item)+// DockerClient returns Arcane's configured Docker client for the updater engine.+func (s *UpdaterService) DockerClient(ctx context.Context) (*client.Client, error) {+ if s == nil || s.deps.Docker == nil {+ return nil, &common.UpdaterDockerServiceUnavailableError{}}+ return s.deps.Docker.GetClient(ctx)+}- // Build maps for fast matching later (only for successfully pulled updates)- oldRefToNewRef := map[string]string{}- oldIDToNewRef := map[string]string{} // sha256 -> newRef- for _, p := range plans {- if !p.pulled {- continue- }- oldRefToNewRef[p.oldRef] = p.newRef- for _, id := range p.oldIDs {- if id != "" {- oldIDToNewRef[id] = p.newRef- }- }+// PullImage pulls an image through Arcane's image service.+func (s *UpdaterService) PullImage(ctx context.Context, imageRef string, progress io.Writer) error {+ if s == nil || s.deps.ImagePuller == nil {+ return &common.UpdaterImageServiceUnavailableError{}}+ activityID := activityIDFromContextInternal(ctx)+ writer := activitylib.NewWriter(ctx, s.deps.Activity, activityID, progress, "Pulling updated images")+ err := s.deps.ImagePuller.PullImage(ctx, imageRef, writer, s.deps.SystemUser, nil)+ activitylib.FlushWriter(writer)+ return err+}- if !dryRun && (len(oldIDToNewRef) > 0 || len(oldRefToNewRef) > 0) {- s.appendAutoUpdateActivityMessageInternal(ctx, activityID, "Restarting containers that use updated images", "Restarting containers", 75)- results, err := s.restartContainersUsingOldIDs(ctx, oldIDToNewRef, oldRefToNewRef)- if err != nil {- slog.Warn("container restarts had errors", "err", err)- }- for _, r := range results {- item := updater.ResourceResult{- ResourceID: r.ResourceID,- ResourceType: "container",- ResourceName: r.ResourceName,- Status: r.Status,- Error: r.Error,- OldImages: r.OldImages,- NewImages: r.NewImages,- UpdateApplied: r.UpdateApplied,- }- out.Items = append(out.Items, item)- out.Checked++- switch {- case r.UpdateApplied:- out.Updated++- case r.Error != "":- out.Failed++- default:- out.Skipped++- }- _ = s.recordRun(ctx, item)-- s.logAutoUpdate(ctx, s.severityFromStatus(item.Status), models.JSON{- "phase": "container",- "containerId": r.ResourceID,- "container": r.ResourceName,- "status": r.Status,- "oldImageMain": r.OldImages["main"],- "newImageMain": r.NewImages["main"],- "error": r.Error,- })- }+// PendingImageUpdates returns pending image update records from Arcane's database.+func (s *UpdaterService) PendingImageUpdates(ctx context.Context) ([]moduletypes.ImageUpdateRecord, error) {+ if s == nil || s.deps.DB == nil {+ return nil, &common.UpdaterDatabaseUnavailableError{}}- // Prune old images that are no longer used (only for images that were actually updated)- var runningImageIDs map[string]struct{}- if !dryRun {- if inUseSet, inUseErr := s.buildRunningImageIDSetInternal(ctx); inUseErr != nil {- slog.Warn("failed to build running image id set; falling back to compatibility checks", "err", inUseErr)- } else {- runningImageIDs = inUseSet- }+ var records []models.ImageUpdateRecord+ if err := s.deps.DB.WithContext(ctx).Where("has_update = ?", true).Find(&records).Error; err != nil {+ return nil, fmt.Errorf("query pending image updates: %w", err)}+ s.appendAutoUpdateActivityMessageInternal(+ ctx,+ activityIDFromContextInternal(ctx),+ fmt.Sprintf("Found %d pending image update records", len(records)),+ "Planning updates",+ 10,+ )- if !dryRun && len(oldIDSet) > 0 {- s.appendAutoUpdateActivityMessageInternal(ctx, activityID, "Pruning old image IDs", "Pruning images", 90)- ids := make([]string, 0, len(oldIDSet))- for id := range oldIDSet {- ids = append(ids, id)- }- if err := s.pruneImageIDsWithInUseSetInternal(ctx, ids, runningImageIDs); err != nil {- slog.Warn("image prune failed", "err", err)- }+ out := make([]moduletypes.ImageUpdateRecord, 0, len(records))+ for _, record := range records {+ out = append(out, imageUpdateRecordToModuleInternal(record))}+ return out, nil+}- // After applying updates, clear has_update locally if no containers still use old image IDs.- if !dryRun {- for _, p := range plans {- if len(p.oldIDs) == 0 {- continue- }- stillUsed, usageErr := s.anyImageIDsStillInUseWithSetInternal(ctx, p.oldIDs, runningImageIDs)- if usageErr != nil {- slog.Warn("check image usage failed for update record clear", "err", usageErr, "image", p.oldRef)- continue- }- if stillUsed {- continue- }+// ClearImageUpdateRecord clears a pending image update record after it is handled.+func (s *UpdaterService) ClearImageUpdateRecord(ctx context.Context, record moduletypes.ImageUpdateRecord) error {+ if s == nil {+ return &common.UpdaterServiceUnavailableError{}+ }+ return s.clearImageUpdateRecordForModuleInternal(ctx, record)+}- clearedAny := false- for _, oldID := range p.oldIDs {- if oldID == "" {- continue- }- if err := s.clearImageUpdateRecordByID(ctx, oldID); err != nil {- slog.WarnContext(ctx, "failed to clear update record by image id", "imageID", oldID, "image", p.oldRef, "err", err)- continue- }- clearedAny = true- }+// RecordUpdateRun persists one updater resource result into Arcane history.+func (s *UpdaterService) RecordUpdateRun(ctx context.Context, result moduletypes.ResourceResult) error {+ if s == nil || s.deps.DB == nil {+ return nil+ }+ return s.recordRunInternal(ctx, resourceResultFromModuleInternal(result))+}- if clearedAny {- s.logAutoUpdate(ctx, models.EventSeverityInfo, models.JSON{- "phase": "record_clear",- "imageOld": p.oldRef,- "status": "cleared",- })- }- }+// ExcludedContainers returns auto-update exclusions from Arcane settings.+func (s *UpdaterService) ExcludedContainers(ctx context.Context) ([]string, error) {+ if s == nil {+ return nil, nil+ }+ excluded := s.buildExcludedContainerSetInternal(ctx)+ if len(excluded) == 0 {+ return nil, nil+ }+ out := make([]string, 0, len(excluded))+ for name := range excluded {+ out = append(out, name)+ }+ return out, nil+}- if err := s.imageUpdateService.CleanupOrphanedRecords(ctx); err != nil {- slog.Warn("cleanup orphaned update records failed", "err", err)+// ProjectByComposeName resolves an Arcane project from a Docker Compose project name.+func (s *UpdaterService) ProjectByComposeName(ctx context.Context, composeName string) (moduletypes.ComposeProject, error) {+ if s == nil || s.deps.Projects == nil {+ return moduletypes.ComposeProject{}, &common.UpdaterProjectServiceUnavailableError{}+ }+ project, err := s.deps.Projects.GetProjectByComposeName(ctx, composeName)+ if err != nil {+ return moduletypes.ComposeProject{}, err+ }+ if project == nil {+ return moduletypes.ComposeProject{}, fmt.Errorf("compose project not found: %s", composeName)+ }+ return moduletypes.ComposeProject{ID: project.ID, Name: project.Name}, nil+}++// UpdateServices redeploys selected services through Arcane's project service.+func (s *UpdaterService) UpdateServices(ctx context.Context, projectID string, services []string) error {+ if s == nil || s.deps.Projects == nil {+ return &common.UpdaterProjectServiceUnavailableError{}+ }+ return s.deps.Projects.UpdateProjectServices(ctx, projectID, services, s.deps.SystemUser)+}++// TriggerSelfUpdate runs Arcane's CLI-backed self-update hook.+func (s *UpdaterService) TriggerSelfUpdate(ctx context.Context, target moduletypes.SelfUpdateTarget) error {+ if s == nil || s.deps.SelfUpgrade == nil {+ instanceType := strings.TrimSpace(target.InstanceType)+ if instanceType == "" {+ instanceType = "server"}+ return fmt.Errorf("%s self-update requires CLI upgrade service", instanceType)+ }+ if err := s.deps.SelfUpgrade.TriggerUpgradeViaCLI(ctx, s.deps.SystemUser); err != nil {+ return fmt.Errorf("CLI upgrade failed: %w", err)}+ return nil+}- // Log run complete- duration := time.Since(start).String()- out.Duration = duration- s.logAutoUpdate(ctx, models.EventSeverityInfo, models.JSON{- "phase": "complete",- "checked": out.Checked,- "updated": out.Updated,- "skipped": out.Skipped,- "failed": out.Failed,- "duration": duration,- "time": time.Now().UTC().Format(time.RFC3339),+// Notify sends Arcane's container update notification.+func (s *UpdaterService) Notify(ctx context.Context, notification moduletypes.Notification) error {+ if s == nil || s.deps.Notifications == nil {+ return nil+ }+ return s.deps.Notifications.SendContainerUpdateNotification(+ ctx,+ notification.ContainerName,+ notification.ImageRef,+ notification.OldImage,+ notification.NewImage,+ )+}++// RecordEvent records updater lifecycle events in Arcane's event stream.+func (s *UpdaterService) RecordEvent(ctx context.Context, event moduletypes.Event) error {+ if s == nil {+ return nil+ }++ eventType, ok := containerEventTypeInternal(event.Phase)+ if ok {+ if s.deps.Events == nil {+ return nil+ }+ return s.deps.Events.LogContainerEvent(+ ctx,+ eventType,+ event.ResourceID,+ event.ResourceName,+ s.deps.SystemUser.ID,+ s.deps.SystemUser.Username,+ "0",+ models.JSON(event.Metadata),+ )+ }++ severity := models.EventSeverityInfo+ if strings.EqualFold(event.Severity, "error") {+ severity = models.EventSeverityError+ }+ s.recordAutoUpdateEventInternal(ctx, severity, models.JSON{+ "phase": event.Phase,+ "resourceId": event.ResourceID,+ "resourceName": event.ResourceName,+ "resourceType": event.ResourceType,+ "time": time.Now().UTC().Format(time.RFC3339),})+ return nil+}- return out, nil+func containerEventTypeInternal(phase string) (models.EventType, bool) {+ switch phase {+ case "container_stop":+ return models.EventTypeContainerStop, true+ case "container_delete":+ return models.EventTypeContainerDelete, true+ case "container_create":+ return models.EventTypeContainerCreate, true+ case "container_start":+ return models.EventTypeContainerStart, true+ case "container_update":+ return models.EventTypeContainerUpdate, true+ default:+ return "", false+ }+}++type activityIDContextKeyInternal struct{}++func contextWithActivityIDInternal(ctx context.Context, activityID string) context.Context {+ activityID = strings.TrimSpace(activityID)+ if activityID == "" {+ return ctx+ }+ return context.WithValue(ctx, activityIDContextKeyInternal{}, activityID)+}++func activityIDFromContextInternal(ctx context.Context) string {+ if ctx == nil {+ return ""+ }+ activityID, _ := ctx.Value(activityIDContextKeyInternal{}).(string)+ return strings.TrimSpace(activityID)}func (s *UpdaterService) startAutoUpdateActivityInternal(ctx context.Context, dryRun bool) string {- if s.activityService == nil {+ if s.deps.Activity == nil {return ""}- activity, err := s.activityService.StartActivity(ctx, StartActivityRequest{+ activity, err := s.deps.Activity.StartActivity(ctx, activitylib.StartRequest{EnvironmentID: "0",Type: models.ActivityTypeAutoUpdate,- ResourceType: new("system"),- ResourceName: new("Auto update"),+ ResourceType: utils.StringPtrFromTrimmed("system"),+ ResourceName: utils.StringPtrFromTrimmed("Auto update"),Step: "Planning updates",LatestMessage: "Auto-update run started",Metadata: models.JSON{"dryRun": dryRun},@@ -432,15 +569,15 @@ func (s *UpdaterService) startAutoUpdateActivityInternal(ctx context.Context, dr}func (s *UpdaterService) startSingleContainerUpdateActivityInternal(ctx context.Context, containerID string) string {- if s.activityService == nil {+ if s.deps.Activity == nil {return ""}- activity, err := s.activityService.StartActivity(ctx, StartActivityRequest{+ activity, err := s.deps.Activity.StartActivity(ctx, activitylib.StartRequest{EnvironmentID: "0",Type: models.ActivityTypeAutoUpdate,- ResourceType: new("container"),+ ResourceType: utils.StringPtrFromTrimmed("container"),ResourceID: &containerID,- ResourceName: new(containerID),+ ResourceName: utils.StringPtrFromTrimmed(containerID),Step: "Updating container",LatestMessage: "Container update started",Metadata: models.JSON{"containerID": containerID},@@ -453,13 +590,13 @@ func (s *UpdaterService) startSingleContainerUpdateActivityInternal(ctx context.}func (s *UpdaterService) appendAutoUpdateActivityMessageInternal(ctx context.Context, activityID, message, step string, progress int) {- if s.activityService == nil || activityID == "" {+ if s.deps.Activity == nil || strings.TrimSpace(activityID) == "" {return}- if step == "" {+ if strings.TrimSpace(step) == "" {step = message}- if _, err := s.activityService.AppendMessage(ctx, activityID, AppendActivityMessageRequest{+ if _, err := s.deps.Activity.AppendMessage(ctx, activityID, activitylib.AppendMessageRequest{Level: models.ActivityMessageLevelInfo,Message: message,Progress: &progress,@@ -470,7 +607,7 @@ func (s *UpdaterService) appendAutoUpdateActivityMessageInternal(ctx context.Con}func (s *UpdaterService) completeAutoUpdateActivityInternal(ctx context.Context, activityID string, result *updater.Result, applyErr error) {- if s.activityService == nil || activityID == "" {+ if s.deps.Activity == nil || strings.TrimSpace(activityID) == "" {return}@@ -494,1653 +631,380 @@ func (s *UpdaterService) completeAutoUpdateActivityInternal(ctx context.Context,errMessage = nil}- if _, err := s.activityService.CompleteActivity(utils.ActivityRuntimeContext(ctx, nil), activityID, status, message, errMessage); err != nil {+ if _, err := s.deps.Activity.CompleteActivity(utils.ActivityRuntimeContext(ctx, nil), activityID, status, message, errMessage); err != nil {slog.DebugContext(ctx, "failed to complete auto-update activity", "activityId", activityID, "error", err)}}-// UpdateSingleContainer updates a single container by ID to the latest available image.-// It pulls the new image, stops the container, removes it, and recreates it with the new image.-//-//nolint:gocognit,gocyclo,maintidx // single-container update flow is intentionally linear with explicit early exits for failure reporting-func (s *UpdaterService) UpdateSingleContainer(ctx context.Context, containerID string) (out *updater.Result, err error) {- start := time.Now()- out = &updater.Result{Items: []updater.ResourceResult{}}- activityID := s.startSingleContainerUpdateActivityInternal(ctx, containerID)- out.ActivityID = utils.StringPtrFromTrimmed(activityID)- ctx = s.activityService.Track(ctx, activityID)- defer func() {- if out != nil {- out.ActivityID = utils.StringPtrFromTrimmed(activityID)- }- s.completeAutoUpdateActivityInternal(ctx, activityID, out, err)- }()- slog.InfoContext(ctx, "UpdateSingleContainer: starting", "containerID", containerID)- dcli, err := s.dockerService.GetClient(ctx)- if err != nil {- return nil, fmt.Errorf("docker connect: %w", err)+func (s *UpdaterService) trackActivityInternal(ctx context.Context, activityID string) context.Context {+ if s.deps.Activity == nil || strings.TrimSpace(activityID) == "" {+ return ctx}+ return s.deps.Activity.Track(ctx, activityID)+}- // Get container info- containerFilters := make(client.Filters)- containerFilters = containerFilters.Add("id", containerID)- containerList, err := dcli.ContainerList(ctx, client.ContainerListOptions{All: true, Filters: containerFilters})- if err != nil {- return nil, fmt.Errorf("list containers: %w", err)+func imageUpdateRecordToModuleInternal(record models.ImageUpdateRecord) moduletypes.ImageUpdateRecord {+ return moduletypes.ImageUpdateRecord{+ ID: record.ID,+ Repository: record.Repository,+ Tag: record.Tag,+ HasUpdate: record.HasUpdate,+ UpdateType: record.UpdateType,+ CurrentVersion: record.CurrentVersion,+ LatestVersion: record.LatestVersion,+ CurrentDigest: record.CurrentDigest,+ LatestDigest: record.LatestDigest,+ CheckTime: record.CheckTime,+ LastError: record.LastError,}- containers := containerList.Items+}- var targetContainer *container.Summary- if len(containers) > 0 {- targetContainer = &containers[0]+func resultFromModuleInternal(result *moduletypes.Result) *updater.Result {+ if result == nil {+ return &updater.Result{Items: []updater.ResourceResult{}}}-- if targetContainer == nil {- return nil, fmt.Errorf("container not found: %s", containerID)+ return &updater.Result{+ Success: result.Success,+ Checked: result.Checked,+ Updated: result.Updated,+ Skipped: result.Skipped,+ Failed: result.Failed,+ StartTime: result.StartTime,+ EndTime: result.EndTime,+ Duration: result.Duration,+ Items: resourceResultsFromModuleInternal(result.Items),+ ActivityID: result.ActivityID,}+}- containerName := dockerutil.ContainerSummaryName(*targetContainer)- slog.InfoContext(ctx, "UpdateSingleContainer: found container", "containerID", containerID, "name", containerName, "image", targetContainer.Image)-- // Inspect container to get full config (needed for label-based controls)- inspectBeforeResult, err := libarcane.ContainerInspectWithCompatibility(ctx, dcli, targetContainer.ID, client.ContainerInspectOptions{})- if err != nil {- out.Items = append(out.Items, updater.ResourceResult{- ResourceID: targetContainer.ID,- ResourceType: "container",- ResourceName: containerName,- Status: "failed",- Error: fmt.Sprintf("inspect failed: %v", err),- })- out.Failed++- out.Duration = time.Since(start).String()- return out, nil- }- inspectBefore := inspectBeforeResult.Container-- labels := map[string]string{}- if inspectBefore.Config != nil && inspectBefore.Config.Labels != nil {- labels = inspectBefore.Config.Labels- }-- isArcaneContainer := libupdater.IsArcaneContainer(labels)- slog.InfoContext(ctx, "UpdateSingleContainer: inspected container",- "containerID", containerID,- "imageID", inspectBefore.Image,- "isArcane", isArcaneContainer,- "hasArcaneLabel", labels["com.getarcaneapp.arcane"])-- endContainerStatus := s.beginContainerUpdateInternal(targetContainer.ID)- defer endContainerStatus()- endProjectStatus := s.beginProjectUpdateInternal(composeProjectNameFromLabelsInternal(labels))- defer endProjectStatus()-- if libupdater.IsUpdateDisabled(labels) {- slog.InfoContext(ctx, "UpdateSingleContainer: updates disabled by label", "containerID", containerID)- out.Items = append(out.Items, updater.ResourceResult{- ResourceID: targetContainer.ID,- ResourceType: "container",- ResourceName: containerName,- Status: "skipped",- Error: "updates disabled by label",- })- out.Skipped++- out.Checked = 1- out.Duration = time.Since(start).String()- return out, nil- }-- if libupdater.IsSwarmTask(labels) && !isArcaneContainer {- slog.InfoContext(ctx, "UpdateSingleContainer: skipping swarm task container", "containerID", containerID)- out.Items = append(out.Items, updater.ResourceResult{- ResourceID: targetContainer.ID,- ResourceType: "container",- ResourceName: containerName,- Status: "skipped",- Error: "swarm service; update at the service level",- })- out.Skipped++- out.Checked = 1- out.Duration = time.Since(start).String()- return out, nil+func resourceResultsFromModuleInternal(results []moduletypes.ResourceResult) []updater.ResourceResult {+ out := make([]updater.ResourceResult, 0, len(results))+ for _, result := range results {+ out = append(out, resourceResultFromModuleInternal(result))}+ return out+}- // Resolve the best pullable image reference for this container.- configImageRef := ""- if inspectBefore.Config != nil {- configImageRef = strings.TrimSpace(inspectBefore.Config.Image)+func resourceResultFromModuleInternal(result moduletypes.ResourceResult) updater.ResourceResult {+ return updater.ResourceResult{+ ResourceID: result.ResourceID,+ ResourceName: result.ResourceName,+ ResourceType: result.ResourceType,+ Status: result.Status,+ UpdateAvailable: result.UpdateAvailable,+ UpdateApplied: result.UpdateApplied,+ OldImages: result.OldImages,+ NewImages: result.NewImages,+ Error: result.Error,+ Details: result.Details,}- imageRef, imageRefSource := resolvePullableImageRefInternal(targetContainer.Image, configImageRef, nil)- if imageRef == "" && inspectBefore.Image != "" {- if imageInspect, inspectErr := dcli.ImageInspect(ctx, inspectBefore.Image); inspectErr == nil {- imageRef, imageRefSource = resolvePullableImageRefInternal(targetContainer.Image, configImageRef, imageInspect.RepoTags)- } else {- slog.DebugContext(ctx, "UpdateSingleContainer: failed to inspect container image for fallback refs", "containerID", containerID, "imageID", inspectBefore.Image, "error", inspectErr)- }+}++func statusFromModuleInternal(status moduletypes.Status) updater.Status {+ return updater.Status{+ UpdatingContainers: status.UpdatingContainers,+ UpdatingProjects: status.UpdatingProjects,+ ContainerIds: status.ContainerIDs,+ ProjectIds: status.ProjectIDs,+ }+}++func (s *UpdaterService) recordRunInternal(ctx context.Context, item updater.ResourceResult) error {+ now := time.Now()+ record := &models.AutoUpdateRecord{+ ResourceID: item.ResourceID,+ ResourceType: item.ResourceType,+ ResourceName: item.ResourceName,+ Status: models.AutoUpdateStatus(item.Status),+ StartTime: now,+ EndTime: &now,+ UpdateAvailable: item.UpdateAvailable || item.Status == moduletypes.StatusUpdated || item.Status == moduletypes.StatusUpdateAvailable,+ UpdateApplied: item.UpdateApplied,+ OldImageVersions: mapToJSONInternal(item.OldImages),+ NewImageVersions: mapToJSONInternal(item.NewImages),+ Details: detailsToJSONInternal(item.Details),}- if imageRef == "" || libupdater.IsImageIDLikeReference(imageRef) {- out.Items = append(out.Items, updater.ResourceResult{- ResourceID: targetContainer.ID,- ResourceType: "container",- ResourceName: containerName,- Status: "skipped",- Error: "unable to resolve a pullable image reference for container",- })- out.Skipped++- out.Duration = time.Since(start).String()- return out, nil+ if item.Error != "" {+ record.Error = &item.Error}+ return s.deps.DB.WithContext(ctx).Create(record).Error+}- normalizedRef := libupdater.NormalizeImageUpdateRef(imageRef)- repo, tag := s.parseRepoAndTag(normalizedRef)+func (s *UpdaterService) clearImageUpdateRecordForModuleInternal(ctx context.Context, record moduletypes.ImageUpdateRecord) error {+ if s.deps.DB == nil {+ return nil+ }- if repo == "" || tag == "" {- out.Items = append(out.Items, updater.ResourceResult{- ResourceID: targetContainer.ID,- ResourceType: "container",- ResourceName: containerName,- Status: "skipped",- Error: "invalid image reference",- })- out.Skipped++- out.Duration = time.Since(start).String()- return out, nil+ query := s.deps.DB.WithContext(ctx).Model(&models.ImageUpdateRecord{})+ if strings.TrimSpace(record.ID) != "" {+ return query.Where("id = ?", record.ID).Update("has_update", false).Error}+ return query.Where("repository = ? AND tag = ?", record.Repository, record.Tag).Update("has_update", false).Error+}- slog.InfoContext(ctx, "UpdateSingleContainer: pulling new image", "containerID", containerID, "image", normalizedRef, "imageRefSource", imageRefSource)+func mapToJSONInternal(values map[string]string) models.JSON {+ if len(values) == 0 {+ return nil+ }+ out := make(models.JSON, len(values))+ for key, value := range values {+ out[key] = value+ }+ return out+}- // Pull the latest image using the image service- if err := s.imageService.PullImage(ctx, normalizedRef, io.Discard, systemUser, nil); err != nil {- out.Items = append(out.Items, updater.ResourceResult{- ResourceID: targetContainer.ID,- ResourceType: "container",- ResourceName: containerName,- Status: "failed",- Error: fmt.Sprintf("pull failed: %v", err),- })- out.Failed++- out.Duration = time.Since(start).String()- return out, nil- }-- // Compare with pulled image to avoid unnecessary restart.- // digestResolver is intentionally nil: CompareWithPulled only inspects local- // images and does not need remote registry access.- checker := libupdater.NewDigestChecker(dcli, nil)- changed, cmpErr := checker.CompareWithPulled(ctx, inspectBefore.Image, normalizedRef)- slog.InfoContext(ctx, "UpdateSingleContainer: digest comparison",- "containerID", containerID,- "changed", changed,- "compareError", cmpErr,- "oldImageID", inspectBefore.Image,- "normalizedRef", normalizedRef)-- if cmpErr == nil && !changed {- slog.InfoContext(ctx, "UpdateSingleContainer: no update needed - digest unchanged",- "containerID", containerID,- "imageID", inspectBefore.Image)- out.Items = append(out.Items, updater.ResourceResult{- ResourceID: targetContainer.ID,- ResourceType: "container",- ResourceName: containerName,- Status: "skipped",- Error: "image digest unchanged after pull",- })- out.Skipped++- out.Checked = 1- out.Duration = time.Since(start).String()- return out, nil- }-- inspect := inspectBefore-- // Check if this is Arcane self-update - use CLI upgrade instead- containerLabels := map[string]string{}- if inspect.Config != nil && inspect.Config.Labels != nil {- containerLabels = inspect.Config.Labels- }-- if libupdater.IsArcaneContainer(containerLabels) {- if err := s.triggerSelfUpdateViaCLIInternal(ctx, "UpdateSingleContainer", containerID, containerName, containerLabels); err != nil {- out.Items = append(out.Items, updater.ResourceResult{- ResourceID: targetContainer.ID,- ResourceType: "container",- ResourceName: containerName,- Status: "failed",- Error: err.Error(),- })- out.Failed++- out.Duration = time.Since(start).String()- return out, nil- }+func detailsToJSONInternal(values map[string]any) models.JSON {+ if len(values) == 0 {+ return nil+ }+ out := make(models.JSON, len(values))+ maps.Copy(out, values)+ return out+}- out.Items = append(out.Items, updater.ResourceResult{- ResourceID: targetContainer.ID,- ResourceType: "container",- ResourceName: containerName,- Status: "updated",+func (s *UpdaterService) logResultItemsInternal(ctx context.Context, result *updater.Result) {+ if result == nil {+ return+ }+ for _, item := range result.Items {+ severity := models.EventSeverityInfo+ switch item.Status {+ case moduletypes.StatusFailed:+ severity = models.EventSeverityError+ case moduletypes.StatusUpdated:+ severity = models.EventSeveritySuccess+ }+ s.recordAutoUpdateEventInternal(ctx, severity, models.JSON{+ "phase": item.ResourceType,+ "resourceId": item.ResourceID,+ "resourceName": item.ResourceName,+ "status": item.Status,+ "error": item.Error,+ "oldImages": item.OldImages,+ "newImages": item.NewImages,})- out.Updated++- out.Checked = 1- out.Duration = time.Since(start).String()-- slog.InfoContext(ctx, "UpdateSingleContainer: CLI upgrade triggered successfully", "containerID", containerID)- return out, nil- }-- // Update the container- projectName := dockerutil.ComposeProjectLabel(inspect.Config.Labels)- serviceName := dockerutil.ComposeServiceLabel(inspect.Config.Labels)-- if projectName != "" && serviceName != "" {- slog.InfoContext(ctx, "UpdateSingleContainer: detected compose container, using project-based update", "containerID", containerID, "project", projectName, "service", serviceName)-- proj, err := s.projectService.GetProjectByComposeName(ctx, projectName)- if err == nil {- // The direct image pull above is still required to compare digests and- // skip no-op updates. Compose project updates intentionally pull again- // inside UpdateProjectServices to keep project redeploy behavior unified.- if err := s.projectService.UpdateProjectServices(ctx, proj.ID, []string{serviceName}, systemUser); err != nil {- out.Items = append(out.Items, updater.ResourceResult{- ResourceID: targetContainer.ID,- ResourceType: "container",- ResourceName: containerName,- Status: "failed",- Error: fmt.Sprintf("project update failed: %v", err),- })- out.Failed++- out.Duration = time.Since(start).String()- return out, nil- }-- out.Items = append(out.Items, updater.ResourceResult{- ResourceID: targetContainer.ID,- ResourceType: "container",- ResourceName: containerName,- Status: "updated",- })- out.Updated++- out.Checked = 1- out.Duration = time.Since(start).String()+ }+}- if s.notificationService != nil {- if notifErr := s.notificationService.SendContainerUpdateNotification(ctx, containerName, imageRef, inspectBefore.Image, normalizedRef); notifErr != nil {- slog.WarnContext(ctx, "Failed to send container update notification", "containerID", containerID, "containerName", containerName, "imageRef", normalizedRef, "error", notifErr.Error())- }- }+// CollectUsedImages returns normalized image references used by running Arcane resources.+func (s *UpdaterService) CollectUsedImages(ctx context.Context) (map[string]struct{}, error) {+ out := map[string]struct{}{}+ var errs []error+ successfulSources := 0- // Prune old image if no longer in use- if inspectBefore.Image != "" {- _ = s.pruneImageIDsWithInUseSetInternal(ctx, []string{inspectBefore.Image}, nil)+ if s.deps.Docker == nil {+ errs = append(errs, &common.UpdaterDockerServiceUnavailableError{})+ } else {+ dcli, err := s.deps.Docker.GetClient(ctx)+ if err != nil || dcli == nil {+ if err == nil {+ err = &common.UpdaterDockerClientUnavailableError{}}+ errs = append(errs, err)+ s.loggerInternal().DebugContext(ctx, "collectUsedImages: docker connection unavailable", "error", err)+ } else if err := s.collectUsedImagesFromContainersInternal(ctx, dcli, out); err != nil {+ errs = append(errs, err)+ s.loggerInternal().DebugContext(ctx, "collectUsedImages: failed collecting from containers", "error", err)+ } else {+ successfulSources+++ }+ }- return out, nil+ if s.deps.Projects != nil {+ if err := s.collectUsedImagesFromProjectsInternal(ctx, out); err != nil {+ errs = append(errs, err)+ s.loggerInternal().DebugContext(ctx, "collectUsedImages: failed collecting from projects", "error", err)+ } else {+ successfulSources++}- slog.WarnContext(ctx, "UpdateSingleContainer: compose labels found but project not found in DB, falling back to standalone update", "project", projectName, "err", err)}- if err := s.updateContainer(ctx, *targetContainer, inspect, normalizedRef); err != nil {- out.Items = append(out.Items, updater.ResourceResult{- ResourceID: targetContainer.ID,- ResourceType: "container",- ResourceName: containerName,- Status: "failed",- Error: err.Error(),- })- out.Failed++- } else {- out.Items = append(out.Items, updater.ResourceResult{- ResourceID: targetContainer.ID,- ResourceType: "container",- ResourceName: containerName,- Status: "updated",- })- out.Updated++-- if s.notificationService != nil {- if notifErr := s.notificationService.SendContainerUpdateNotification(ctx, containerName, imageRef, inspectBefore.Image, normalizedRef); notifErr != nil {- slog.WarnContext(ctx, "Failed to send container update notification", "containerID", containerID, "containerName", containerName, "imageRef", normalizedRef, "error", notifErr.Error())- }- }-- // Clear the update record for this exact image ID when no running container still uses it.- // This avoids repo-name canonicalization mismatches (e.g. "nginx" vs "docker.io/library/nginx").- if inspectBefore.Image != "" {- stillUsed, usageErr := s.anyImageIDsStillInUse(ctx, []string{inspectBefore.Image})- if usageErr != nil {- slog.WarnContext(ctx, "failed to check image usage before clearing update record", "imageID", inspectBefore.Image, "err", usageErr)- } else if !stillUsed {- if err := s.clearImageUpdateRecordByID(ctx, inspectBefore.Image); err != nil {- slog.WarnContext(ctx, "failed to clear update record by image id", "imageID", inspectBefore.Image, "err", err)- }- }- } else if err := s.clearImageUpdateRecord(ctx, repo, tag); err != nil {- // Fallback for unexpected cases where the old image ID is unavailable.- slog.WarnContext(ctx, "failed to clear update record", "repo", repo, "tag", tag, "err", err)- }+ if successfulSources == 0 {+ return nil, errors.Join(errs...)}- out.Checked = 1- out.Duration = time.Since(start).String()-- slog.InfoContext(ctx, "UpdateSingleContainer: complete", "containerID", containerID, "updated", out.Updated, "failed", out.Failed)-+ s.loggerInternal().DebugContext(ctx, "collectUsedImages: collected used images", "count", len(out))return out, nil}-func (s *UpdaterService) pruneImageIDsWithInUseSetInternal(ctx context.Context, ids []string, inUseSet map[string]struct{}) error {- if len(ids) == 0 {- return nil- }-- slog.DebugContext(ctx, "pruneImageIDs: attempting to prune image ids", "count", len(ids))-- dcli, err := s.dockerService.GetClient(ctx)- if err != nil {- return fmt.Errorf("docker connect: %w", err)- }-- for _, id := range ids {- if id == "" {- continue- }-- slog.DebugContext(ctx, "pruneImageIDs: checking image id", "imageId", id)-- inUse, err := s.anyImageIDsStillInUseWithSetInternal(ctx, []string{id}, inUseSet)- if err != nil {- slog.Warn("check image usage failed", "imageId", id, "err", err)- continue- }- if inUse {- slog.DebugContext(ctx, "pruneImageIDs: image still in use, skipping", "imageId", id)- // still referenced by a container; skip- continue- }-- if _, err := dcli.ImageRemove(ctx, id, client.ImageRemoveOptions{PruneChildren: true}); err != nil {- slog.Warn("image remove failed", "imageId", id, "err", err)- continue- }-- s.logAutoUpdate(ctx, models.EventSeverityInfo, models.JSON{- "phase": "image_prune",- "imageId": id,- "status": "removed",- })- slog.DebugContext(ctx, "pruneImageIDs: image removed", "imageId", id)- }-- return nil-}--// GetStatus returns the current in-memory update activity snapshot.-func (s *UpdaterService) GetStatus() updater.Status { return s.statusSnapshotInternal() }--// GetHistory returns the most recent auto-update history records, newest first.-func (s *UpdaterService) GetHistory(ctx context.Context, limit int) ([]models.AutoUpdateRecord, error) {- var rec []models.AutoUpdateRecord- q := s.db.WithContext(ctx).Order("start_time DESC")- if limit > 0 {- q = q.Limit(limit)- }- if err := q.Find(&rec).Error; err != nil {- return nil, fmt.Errorf("get history: %w", err)- }- return rec, nil-}--// --- internals -----func (s *UpdaterService) updateContainer(ctx context.Context, cnt container.Summary, inspect container.InspectResponse, newRef string) error {- dcli, err := s.dockerService.GetClient(ctx)- if err != nil {- return fmt.Errorf("docker connect: %w", err)- }-- name := dockerutil.ContainerSummaryName(cnt)- labels := inspect.Config.Labels- isArcane := libupdater.IsArcaneContainer(labels)-- // Arcane containers should always use CLI upgrade, not inline update- // This method should not be called for Arcane containers- if isArcane {- slog.ErrorContext(ctx, "updateContainer: called for Arcane container - should use CLI upgrade instead", "containerId", cnt.ID, "containerName", name)- return errors.New("arcane containers must use CLI upgrade method (TriggerUpgradeViaCLI), not inline update")- }-- slog.DebugContext(ctx, "updateContainer: starting update", "containerId", cnt.ID, "containerName", name, "newRef", newRef, "isArcane", isArcane)-- originalName := inspect.Name-- // Get custom stop signal if configured- stopSignal := libupdater.GetStopSignal(labels)- stopOpts := client.ContainerStopOptions{}- if stopSignal != "" {- stopOpts.Signal = stopSignal- slog.DebugContext(ctx, "updateContainer: using custom stop signal", "signal", stopSignal)- }-- // Stop the container- if _, err := dcli.ContainerStop(ctx, cnt.ID, stopOpts); err != nil {- slog.DebugContext(ctx, "updateContainer: stop failed", "containerId", cnt.ID, "err", err)- return fmt.Errorf("stop: %w", err)- }- _ = s.eventService.LogContainerEvent(ctx, models.EventTypeContainerStop, cnt.ID, name, systemUser.ID, systemUser.Username, "0", models.JSON{"action": "updater_stop"})-- // Remove the container- if _, err := dcli.ContainerRemove(ctx, cnt.ID, client.ContainerRemoveOptions{}); err != nil {- slog.DebugContext(ctx, "updateContainer: remove failed", "containerId", cnt.ID, "err", err)- return fmt.Errorf("remove: %w", err)- }- _ = s.eventService.LogContainerEvent(ctx, models.EventTypeContainerDelete, cnt.ID, name, systemUser.ID, systemUser.Username, "0", models.JSON{"action": "updater_delete"})-- // recreate with new image ref- cfg := inspect.Config- cfg.Image = newRef-- // Update the com.docker.compose.image label so that `docker compose up -d`- // recognises the container as up-to-date and does not recreate it.- if cfg.Labels != nil {- if _, ok := cfg.Labels["com.docker.compose.image"]; ok {- if imgInspect, err := dcli.ImageInspect(ctx, newRef); err == nil {- cfg.Labels["com.docker.compose.image"] = imgInspect.ID- } else {- slog.WarnContext(ctx, "updateContainer: could not inspect new image to update compose label",- "newRef", newRef, "err", err)- }- }- }-- hostConfig, sanitizedMemorySwappiness, engineInfo, err := libarcane.PrepareRecreateHostConfigForEngine(ctx, dcli, inspect.HostConfig)- if err != nil {- return fmt.Errorf("prepare host config: %w", err)- }- if sanitizedMemorySwappiness {- slog.InfoContext(ctx,- "updateContainer: stripped unsupported host config field for recreate",- "containerId", cnt.ID,- "containerName", name,- "engine", engineInfo.Name,- "cgroupVersion", engineInfo.CgroupVersion,- "field", "memorySwappiness",- )- }-- // Fix for "conflicting options: hostname and the network mode"- // When network mode is "host" or "container:...", Hostname must be empty- var nm container.NetworkMode- if hostConfig != nil {- nm = hostConfig.NetworkMode- }- if nm.IsHost() || nm.IsContainer() {- cfg.Hostname = ""- cfg.Domainname = ""- }-- // Fix for "conflicting options: port exposing and the container type network mode"- // When network mode is "container:...", port mappings are not allowed- if nm.IsContainer() {- cfg.ExposedPorts = nil- if hostConfig != nil {- hostConfig.PortBindings = nil- hostConfig.PublishAllPorts = false- }- }-- apiVersion := libarcane.DetectDockerAPIVersion(ctx, dcli)- networkingConfig := buildUpdaterRecreateNetworkingConfigInternal(nm, inspect.NetworkSettings, apiVersion)- if networkingConfig != nil && apiVersion != "" && !libarcane.SupportsDockerCreatePerNetworkMACAddress(apiVersion) {- slog.InfoContext(ctx,- "updateContainer: daemon API does not support per-network mac-address on create; stripping endpoint mac addresses",- "containerId", cnt.ID,- "containerName", name,- "dockerAPIVersion", apiVersion,- "minimumRequiredAPIVersion", libarcane.NetworkScopedMacAddressMinAPIVersion,- )- }-- // Use original name for new container- containerName := strings.TrimPrefix(originalName, "/")-- resp, err := libarcane.ContainerCreateWithCompatibilityForAPIVersion(ctx, dcli, client.ContainerCreateOptions{- Config: cfg,- HostConfig: hostConfig,- NetworkingConfig: networkingConfig,- Name: containerName,- }, apiVersion)- if err != nil {- slog.DebugContext(ctx, "updateContainer: create failed", "containerName", containerName, "err", err)- return fmt.Errorf("create: %w", err)- }- _ = s.eventService.LogContainerEvent(ctx, models.EventTypeContainerCreate, resp.ID, name, systemUser.ID, systemUser.Username, "0", models.JSON{"action": "updater_create", "newImageId": resp.ID})-- if _, err := dcli.ContainerStart(ctx, resp.ID, client.ContainerStartOptions{}); err != nil {- slog.DebugContext(ctx, "updateContainer: start failed", "newContainerId", resp.ID, "err", err)- return fmt.Errorf("start: %w", err)- }- _ = s.eventService.LogContainerEvent(ctx, models.EventTypeContainerStart, resp.ID, name, systemUser.ID, systemUser.Username, "0", models.JSON{"action": "updater_start"})-- _ = s.eventService.LogContainerEvent(ctx, models.EventTypeContainerUpdate, resp.ID, name, systemUser.ID, systemUser.Username, "0", models.JSON{- "oldContainerId": cnt.ID,- "newContainerId": resp.ID,- "newImage": newRef,- })-- slog.DebugContext(ctx, "updateContainer: update complete", "oldContainerId", cnt.ID, "newContainerId", resp.ID)- return nil-}--func buildUpdaterRecreateNetworkingConfigInternal(networkMode container.NetworkMode, settings *container.NetworkSettings, apiVersion string) *network.NetworkingConfig {- if networkMode.IsContainer() || settings == nil || len(settings.Networks) == 0 {- return nil- }-- rawEndpointsConfig := make(map[string]*network.EndpointSettings, len(settings.Networks))- for networkName, endpoint := range settings.Networks {- if endpoint == nil {- rawEndpointsConfig[networkName] = &network.EndpointSettings{}- continue- }-- rawEndpointsConfig[networkName] = &network.EndpointSettings{- IPAMConfig: endpoint.IPAMConfig.Copy(),- Links: slices.Clone(endpoint.Links),- Aliases: slices.Clone(endpoint.Aliases),- DriverOpts: maps.Clone(endpoint.DriverOpts),- GwPriority: endpoint.GwPriority,- MacAddress: endpoint.MacAddress,- }- }-- sanitizedEndpointsConfig := libarcane.SanitizeContainerCreateEndpointSettingsForDockerAPI(rawEndpointsConfig, apiVersion)- if len(sanitizedEndpointsConfig) == 0 {- return nil- }-- return &network.NetworkingConfig{EndpointsConfig: sanitizedEndpointsConfig}-}--func addNormalizedImageUpdateRefInternal(ctx context.Context, out map[string]struct{}, imageRef, logMessage string, attrs ...any) {- normalizedRef := libupdater.NormalizeImageUpdateRef(imageRef)- if normalizedRef != "" {- out[normalizedRef] = struct{}{}- return- }-- args := slices.Clone(attrs)- args = append(args, "imageRef", imageRef)- if ctx != nil {- slog.DebugContext(ctx, logMessage, args...)- } else {- slog.Debug(logMessage, args...)- }-}--func (s *UpdaterService) stripDigest(ref string) string {- if before, _, ok := strings.Cut(ref, "@"); ok {- return before- }- return ref-}--// collectUsedImagesFromContainersInternal adds normalized image tags from non-opted-out running containers.func (s *UpdaterService) collectUsedImagesFromContainersInternal(ctx context.Context, dcli *client.Client, out map[string]struct{}) error {if dcli == nil {return nil}excludedContainers := s.buildExcludedContainerSetInternal(ctx)-listResult, err := dcli.ContainerList(ctx, client.ContainerListOptions{All: false})if err != nil {return err}- list := listResult.Items- slog.DebugContext(ctx, "collectUsedImagesFromContainersInternal: container list fetched", "count", len(list))- for _, c := range list {- if libupdater.IsUpdateDisabled(c.Labels) {- slog.DebugContext(ctx, "collectUsedImagesFromContainersInternal: container opted out by labels", "containerId", c.ID)++ for _, summary := range listResult.Items {+ if labels.IsUpdateDisabled(summary.Labels) {+ s.loggerInternal().DebugContext(ctx, "collectUsedImagesFromContainers: container opted out by labels", "containerId", summary.ID)continue}- if len(excludedContainers) > 0 {- isExcluded := false- for _, name := range c.Names {- if excludedContainers[strings.TrimPrefix(name, "/")] {- isExcluded = true- break- }- }- if isExcluded {- slog.DebugContext(ctx, "collectUsedImagesFromContainersInternal: skipping excluded container", "containerId", c.ID, "names", c.Names)- continue- }+ if containerSummaryExcludedInternal(summary, excludedContainers) {+ s.loggerInternal().DebugContext(ctx, "collectUsedImagesFromContainers: skipping excluded container", "containerId", summary.ID, "names", summary.Names)+ continue}- imageRef := strings.TrimSpace(c.Image)- if imageRef != "" && !libupdater.IsImageIDLikeReference(imageRef) {- addNormalizedImageUpdateRefInternal(ctx, out, imageRef, "collectUsedImagesFromContainersInternal: skipping invalid image reference", "containerId", c.ID)+ imageRef := strings.TrimSpace(summary.Image)+ if imageRef != "" && !refs.IsImageIDLikeReference(imageRef) {+ addNormalizedImageUpdateRefInternal(ctx, out, imageRef, "collectUsedImagesFromContainers: skipping invalid image reference", "containerId", summary.ID)continue}- inspectResult, err := libarcane.ContainerInspectWithCompatibility(ctx, dcli, c.ID, client.ContainerInspectOptions{})- if err != nil {- slog.DebugContext(ctx, "collectUsedImagesFromContainersInternal: container inspect failed", "containerId", c.ID, "err", err)+ inspectResult, inspectErr := libarcane.ContainerInspectWithCompatibility(ctx, dcli, summary.ID, client.ContainerInspectOptions{})+ if inspectErr != nil {+ s.loggerInternal().DebugContext(ctx, "collectUsedImagesFromContainers: container inspect failed", "containerId", summary.ID, "error", inspectErr)continue}inspect := inspectResult.Container- if inspect.Config != nil && libupdater.IsUpdateDisabled(inspect.Config.Labels) {- slog.DebugContext(ctx, "collectUsedImagesFromContainersInternal: container inspect labels opted out", "containerId", c.ID)+ if inspect.Config != nil && labels.IsUpdateDisabled(inspect.Config.Labels) {+ s.loggerInternal().DebugContext(ctx, "collectUsedImagesFromContainers: container inspect labels opted out", "containerId", summary.ID)continue}- for _, t := range s.getNormalizedTagsForContainer(ctx, dcli, inspect) {- out[t] = struct{}{}+ for _, tag := range s.normalizedTagsForContainerInternal(ctx, dcli, inspect) {+ out[tag] = struct{}{}}}return nil}-// buildExcludedContainerSetInternal returns the set of container names from the-// autoUpdateExcludedContainers setting. An empty map means no exclusions.-func (s *UpdaterService) buildExcludedContainerSetInternal(ctx context.Context) map[string]bool {- raw := s.settingsService.GetStringSetting(ctx, "autoUpdateExcludedContainers", "")- if raw == "" {- return nil- }- excluded := make(map[string]bool)- for p := range strings.SplitSeq(raw, ",") {- if name := strings.TrimSpace(p); name != "" {- excluded[name] = true- }- }- return excluded-}--// Aggregate images in use across containers and compose projects-func (s *UpdaterService) collectUsedImages(ctx context.Context) (map[string]struct{}, error) {- out := map[string]struct{}{}- var errs []error- successfulSources := 0-- if s.dockerService == nil {- errs = append(errs, errors.New("docker service unavailable"))- } else {- dcli, err := s.dockerService.GetClient(ctx)- if err != nil || dcli == nil {- if err == nil {- err = errors.New("docker client unavailable")- }- errs = append(errs, fmt.Errorf("docker client: %w", err))- slog.DebugContext(ctx, "collectUsedImages: docker connection unavailable", "err", err)- } else if err := s.collectUsedImagesFromContainersInternal(ctx, dcli, out); err != nil {- errs = append(errs, fmt.Errorf("containers source: %w", err))- slog.DebugContext(ctx, "collectUsedImages: failed collecting from containers", "err", err)- } else {- successfulSources++- }- }-- if s.projectService != nil {- if err := s.collectUsedImagesFromProjects(ctx, out); err != nil {- errs = append(errs, fmt.Errorf("projects source: %w", err))- slog.DebugContext(ctx, "collectUsedImages: failed collecting from projects", "err", err)- } else {- successfulSources++- }- }-- if successfulSources == 0 {- return nil, errors.Join(errs...)- }-- slog.DebugContext(ctx, "collectUsedImages: collected used images", "count", len(out))- return out, nil-}--func (s *UpdaterService) collectUsedImagesFromProjects(ctx context.Context, out map[string]struct{}) error {- if s.projectService == nil {- return nil- }-- projs, err := s.projectService.ListAllProjects(ctx)- if err != nil {- return err- }-- activeProjectNames := activeComposeProjectNameSetInternal(projs)- if len(activeProjectNames) == 0 {- return nil- }-- composeContainers, err := projectspkg.ListGlobalComposeContainers(ctx)- if err != nil {- return err- }-- s.collectUsedImagesFromComposeContainersInternal(ctx, composeContainers, activeProjectNames, out)- return nil-}--func activeComposeProjectNameSetInternal(projects []models.Project) map[string]struct{} {- active := make(map[string]struct{})- for _, p := range projects {- if p.IsArchived {- continue- }- // consider running and partially running projects- if p.Status != models.ProjectStatusRunning && p.Status != models.ProjectStatusPartiallyRunning {- continue- }-- name := strings.TrimSpace(p.Name)- if name == "" {- continue- }-- active[name] = struct{}{}-- if normalized := loader.NormalizeProjectName(name); normalized != "" {- active[normalized] = struct{}{}- }- }- return active-}-func (s *UpdaterService) collectUsedImagesFromComposeContainersInternal(ctx context.Context, composeContainers []container.Summary, activeProjectNames map[string]struct{}, out map[string]struct{}) {- for _, c := range composeContainers {- projectName := dockerutil.ComposeProjectLabel(c.Labels)+ for _, summary := range composeContainers {+ projectName := dockerutil.ComposeProjectLabel(summary.Labels)if projectName == "" {continue}if _, isActive := activeProjectNames[projectName]; !isActive {continue}- if libupdater.IsUpdateDisabled(c.Labels) {+ if labels.IsUpdateDisabled(summary.Labels) {continue}- imageRef := strings.TrimSpace(c.Image)- if imageRef == "" || libupdater.IsImageIDLikeReference(imageRef) {+ imageRef := strings.TrimSpace(summary.Image)+ if imageRef == "" || refs.IsImageIDLikeReference(imageRef) {continue}- addNormalizedImageUpdateRefInternal(ctx, out, imageRef, "collectUsedImagesFromComposeContainersInternal: skipping invalid image reference", "containerId", c.ID)+ addNormalizedImageUpdateRefInternal(ctx, out, imageRef, "collectUsedImagesFromComposeContainers: skipping invalid image reference", "containerId", summary.ID)}}-func (s *UpdaterService) getNormalizedTagsForContainer(ctx context.Context, dcli *client.Client, inspect container.InspectResponse) []string {+func (s *UpdaterService) normalizedTagsForContainerInternal(ctx context.Context, dcli *client.Client, inspect container.InspectResponse) []string {seen := map[string]struct{}{}- // Prefer tags from the image object (handles sha256 IDs)if dcli != nil {- if ii, err := dcli.ImageInspect(ctx, inspect.Image); err == nil {- slog.DebugContext(ctx, "getNormalizedTagsForContainer: image inspect success", "imageId", inspect.Image, "repoTags", len(ii.RepoTags))- for _, tag := range ii.RepoTags {- if tag == "<none>:<none>" || tag == "" {+ if imageInspect, err := dcli.ImageInspect(ctx, inspect.Image); err == nil {+ for _, tag := range imageInspect.RepoTags {+ if strings.TrimSpace(tag) == "" || tag == "<none>:<none>" {continue}- addNormalizedImageUpdateRefInternal(ctx, seen, tag, "getNormalizedTagsForContainer: skipping invalid repo tag", "imageId", inspect.Image)+ addNormalizedImageUpdateRefInternal(ctx, seen, tag, "normalizedTagsForContainer: skipping invalid repo tag", "imageId", inspect.Image)}- } else {- slog.DebugContext(ctx, "getNormalizedTagsForContainer: image inspect failed", "imageId", inspect.Image, "err", err)}}if inspect.Config != nil && inspect.Config.Image != "" {- addNormalizedImageUpdateRefInternal(ctx, seen, inspect.Config.Image, "getNormalizedTagsForContainer: skipping invalid config image reference", "imageId", inspect.Image)+ addNormalizedImageUpdateRefInternal(ctx, seen, inspect.Config.Image, "normalizedTagsForContainer: skipping invalid config image reference", "imageId", inspect.Image)}out := make([]string, 0, len(seen))- for k := range seen {- out = append(out, k)+ for tag := range seen {+ out = append(out, tag)}- slog.DebugContext(ctx, "getNormalizedTagsForContainer: normalized tags", "count", len(out))return out}-func (s *UpdaterService) recordRun(ctx context.Context, item updater.ResourceResult) error {- rec := &models.AutoUpdateRecord{- ResourceID: item.ResourceID,- ResourceType: item.ResourceType,- ResourceName: item.ResourceName,- Status: models.AutoUpdateStatus(item.Status),- StartTime: time.Now(),- UpdateAvailable: item.Status == "updated" || item.Status == "update_available",- UpdateApplied: item.UpdateApplied,- }-- if item.Error != "" {- rec.Error = &item.Error+func (s *UpdaterService) buildExcludedContainerSetInternal(ctx context.Context) map[string]bool {+ if s.deps.Settings == nil {+ return nil}-- if len(item.OldImages) > 0 {- old := make(models.JSON)- for k, v := range item.OldImages {- old[k] = v- }- rec.OldImageVersions = old+ raw := s.deps.Settings.GetStringSetting(ctx, "autoUpdateExcludedContainers", "")+ if raw == "" {+ return nil}- if len(item.NewImages) > 0 {- newv := make(models.JSON)- for k, v := range item.NewImages {- newv[k] = v+ excluded := make(map[string]bool)+ for part := range strings.SplitSeq(raw, ",") {+ if name := strings.TrimSpace(part); name != "" {+ excluded[name] = true}- rec.NewImageVersions = newv}-- rec.EndTime = new(time.Now())-- return s.db.WithContext(ctx).Create(rec).Error+ return excluded}-// Resolve the local image ID(s) currently referenced by ref (repo:tag) before we pull.-// Returns IDs like "sha256:...".-func (s *UpdaterService) resolveLocalImageIDsForRef(ctx context.Context, ref string) ([]string, error) {- slog.DebugContext(ctx, "resolveLocalImageIDsForRef: resolving local image ids for ref", "ref", ref)-- dcli, err := s.dockerService.GetClient(ctx)- if err != nil {- return nil, err+func (s *UpdaterService) collectUsedImagesFromProjectsInternal(ctx context.Context, out map[string]struct{}) error {+ if s.deps.Projects == nil {+ return nil}- // digestResolver is intentionally nil: GetImageIDsForRef only inspects local images.- checker := libupdater.NewDigestChecker(dcli, nil)- ids, err := checker.GetImageIDsForRef(ctx, ref)+ projects, err := s.deps.Projects.ListAllProjects(ctx)if err != nil {- return nil, err+ return err}- slog.DebugContext(ctx, "resolveLocalImageIDsForRef: resolved ids", "ref", ref, "ids", ids)- return ids, nil-}-type restartPlan struct {- cnt container.Summary- inspect *container.InspectResponse- newRef string- match string- explicit bool- implicit bool-}--//nolint:gocognit,gocyclo,maintidx // restart-orchestration flow remaps old/new container IDs in one pass; refactor tracked separately-func (s *UpdaterService) restartContainersUsingOldIDs(ctx context.Context, oldIDToNewRef map[string]string, oldRefToNewRef map[string]string) ([]updater.ResourceResult, error) {- dcli, err := s.dockerService.GetClient(ctx)- if err != nil {- return nil, fmt.Errorf("docker connect: %w", err)+ activeProjectNames := activeComposeProjectNameSetInternal(projects)+ if len(activeProjectNames) == 0 {+ return nil}- listResult, err := dcli.ContainerList(ctx, client.ContainerListOptions{All: false})+ composeContainers, err := projectspkg.ListGlobalComposeContainers(ctx)if err != nil {- return nil, fmt.Errorf("list containers: %w", err)- }- list := listResult.Items- slog.DebugContext(ctx, "restartContainersUsingOldIDs: scanning containers for matching images", "containers", len(list), "oldIDMatches", len(oldIDToNewRef), "oldRefMatches", len(oldRefToNewRef))-- excludedContainers := s.buildExcludedContainerSetInternal(ctx)-- // Detect the Docker socket proxy container (if DOCKER_HOST is TCP) so we- // can skip it during auto-update. Updating it would sever Arcane's own- // Docker connectivity mid-operation. See #1881.- dockerProxyName := dockerProxyContainerNameInternal(s.dockerService.DockerHost())- if dockerProxyName != "" {- slog.InfoContext(ctx, "restartContainersUsingOldIDs: detected Docker socket proxy container; excluding from auto-update", "proxyContainer", dockerProxyName)- }-- updatedNorm := map[string]string{}- for oldRef, nr := range oldRefToNewRef {- if normalizedRef := libupdater.NormalizeImageUpdateRef(oldRef); normalizedRef != "" {- updatedNorm[normalizedRef] = nr- } else {- slog.DebugContext(ctx, "restartContainersUsingOldIDs: skipping invalid old image reference", "imageRef", oldRef)- }- }-- plansByName := map[string]*restartPlan{}- markedForRestart := map[string]bool{}- containersWithDeps := make([]libupdater.ContainerWithDeps, 0, len(list))-- // Cache resolved IDs for newRefs to avoid repeated API calls- targetImageIDs := map[string][]string{}-- for _, c := range list {- // Check exclusions first by container name(s)- isExcluded := false- for _, name := range c.Names {- cleanName := strings.TrimPrefix(name, "/")- if excludedContainers[cleanName] {- isExcluded = true- break- }- }- if isExcluded {- slog.DebugContext(ctx, "restartContainersUsingOldIDs: skipping excluded container", "containerId", c.ID, "names", c.Names)- continue- }-- // Skip containers with opt-out label- if libupdater.IsUpdateDisabled(c.Labels) {- continue- }-- if libupdater.IsSwarmTask(c.Labels) && !libupdater.IsArcaneContainer(c.Labels) {- slog.DebugContext(ctx, "restartContainersUsingOldIDs: skipping swarm task container", "containerId", c.ID, "names", c.Names)- continue- }-- // Skip the Docker socket proxy container to preserve Arcane's Docker connectivity (#1881)- if dockerProxyName != "" {- isProxy := false- for _, cname := range c.Names {- if strings.TrimPrefix(cname, "/") == dockerProxyName {- isProxy = true- break- }- }- if isProxy {- slog.WarnContext(ctx, "restartContainersUsingOldIDs: skipping Docker socket proxy container to preserve connectivity",- "containerId", c.ID, "containerName", dockerProxyName)- continue- }- }-- // Ensure labels map exists to avoid nil panics in implicit restart marking- if c.Labels == nil {- c.Labels = map[string]string{}- }-- name := dockerutil.ContainerSummaryName(c)- containersWithDeps = append(containersWithDeps, libupdater.ContainerWithDeps{- Container: c,- Name: name,- })-- var inspected *container.InspectResponse- newRef, match := libupdater.ResolveContainerImageMatch(c, nil, oldIDToNewRef, updatedNorm)- if newRef == "" && libupdater.ShouldInspectUnmatchedContainerForImageMatch(c) {- inspectResult, ierr := libarcane.ContainerInspectWithCompatibility(ctx, dcli, c.ID, client.ContainerInspectOptions{})- if ierr != nil {- slog.DebugContext(ctx, "restartContainersUsingOldIDs: inspect for image match failed", "containerId", c.ID, "err", ierr)- } else {- inspected = &inspectResult.Container- newRef, match = libupdater.ResolveContainerImageMatch(c, inspected, oldIDToNewRef, updatedNorm)- }- }-- if newRef != "" {- // Check if container is already on the target image- tids, cached := targetImageIDs[newRef]- if !cached {- tids, _ = s.resolveLocalImageIDsForRef(ctx, newRef)- targetImageIDs[newRef] = tids- }-- currentImageID := libupdater.CurrentContainerImageID(c, inspected)- if currentImageID != "" && slices.Contains(tids, currentImageID) {- // Already on target image- slog.InfoContext(ctx, "restartContainersUsingOldIDs: container already on target image; skipping restart",- "containerId", c.ID, "containerName", name, "imageID", currentImageID, "newRef", newRef)- newRef = ""- }- }-- p := &restartPlan{cnt: c, inspect: inspected, newRef: newRef, match: match, explicit: newRef != ""}- plansByName[name] = p- if p.explicit {- markedForRestart[name] = true- }- }-- // Only fetch full container inspect details if there are explicit restart candidates.- // This avoids one inspect call per running container on runs with no matching updates.- if len(markedForRestart) > 0 {- for i := range containersWithDeps {- cwd := containersWithDeps[i]- if p, ok := plansByName[cwd.Name]; ok && p.inspect != nil {- containersWithDeps[i] = libupdater.ExtractContainerDeps(ctx, dcli, cwd.Container, *p.inspect)- continue- }-- inspectResult, ierr := libarcane.ContainerInspectWithCompatibility(ctx, dcli, cwd.Container.ID, client.ContainerInspectOptions{})- if ierr != nil {- continue- }- inspect := inspectResult.Container- containersWithDeps[i] = libupdater.ExtractContainerDeps(ctx, dcli, cwd.Container, inspect)-- if p, ok := plansByName[containersWithDeps[i].Name]; ok {- p.inspect = new(inspect)- }- }- }-- // Propagate implicit restarts: if a dependency is restarting, restart dependents too.- for {- added := libupdater.UpdateImplicitRestart(containersWithDeps, markedForRestart)- if len(added) == 0 {- break- }- for _, name := range added {- if p, ok := plansByName[name]; ok {- if p.newRef == "" {- if p.inspect != nil && p.inspect.Config != nil {- p.newRef = strings.TrimSpace(p.inspect.Config.Image)- }- if p.newRef == "" {- p.newRef = p.cnt.Image- }- p.match = "dependency_restart"- p.implicit = true- }- }- }- }-- // Build the set of containers that will be restarted and sort them by dependency order.- candidates := make([]libupdater.ContainerWithDeps, 0, len(containersWithDeps))- for _, cd := range containersWithDeps {- if markedForRestart[cd.Name] {- candidates = append(candidates, cd)- }- }-- sorter := libupdater.NewContainerSorter(candidates)- sorted, sortErr := sorter.Sort()- _, _ = sorter.SortReverse() // keep method used; reverse order may be useful for future stop-first flows- if sortErr != nil {- slog.WarnContext(ctx, "restartContainersUsingOldIDs: dependency sort failed, falling back to unsorted order", "error", sortErr.Error())- sorted = candidates- }-- // Pre-scan sorted containers to group compose project services that need updates.- // We only group containers that are explicitly marked for restart (p.newRef != "").- projectToServices := make(map[string][]string) // projectID -> []serviceName- projectToSeenServices := make(map[string]map[string]struct{}) // projectID -> set(serviceName)- projectIDToObj := make(map[string]*models.Project)- projectNameToID := make(map[string]string)-- for _, cd := range sorted {- p := plansByName[cd.Name]- if p == nil || p.newRef == "" || p.inspect == nil || p.inspect.Config == nil {- continue- }- projectName := dockerutil.ComposeProjectLabel(p.inspect.Config.Labels)- serviceName := dockerutil.ComposeServiceLabel(p.inspect.Config.Labels)- if projectName != "" && serviceName != "" {- projectID, ok := lookupComposeProjectIDInternal(projectName, projectNameToID)- if !ok {- proj, err := s.projectService.GetProjectByComposeName(ctx, projectName)- if err != nil {- continue- }- projectID = proj.ID- projectIDToObj[proj.ID] = proj- projectNameToID[proj.Name] = proj.ID- projectNameToID[loader.NormalizeProjectName(proj.Name)] = proj.ID- }- if _, ok := projectToSeenServices[projectID]; !ok {- projectToSeenServices[projectID] = make(map[string]struct{})- }- if _, seen := projectToSeenServices[projectID][serviceName]; !seen {- projectToServices[projectID] = append(projectToServices[projectID], serviceName)- projectToSeenServices[projectID][serviceName] = struct{}{}- }- }- }-- processedProjectServices := make(map[string]map[string]struct{})- projectResults := make(map[string]error) // stores error from the project-level update run-- var results []updater.ResourceResult- for _, cd := range sorted {- p := plansByName[cd.Name]- if p == nil {- continue- }-- name := cd.Name- labels := map[string]string{}- if p.inspect == nil {- inspectResult, ierr := libarcane.ContainerInspectWithCompatibility(ctx, dcli, p.cnt.ID, client.ContainerInspectOptions{})- if ierr != nil {- res := updater.ResourceResult{- ResourceID: p.cnt.ID,- ResourceName: name,- ResourceType: "container",- Status: "failed",- Error: fmt.Sprintf("inspect failed: %v", ierr),- }- results = append(results, res)- continue- }- inspect := inspectResult.Container- p.inspect = new(inspect)-- // If this container belongs to a compose project that was missed during the- // pre-scan (inspect was nil), register it now so the main loop routes it- // through the compose-aware update path instead of standalone stop/rm/run.- s.lazyRegisterComposeProjectInternal(ctx, p, projectNameToID, projectIDToObj, projectToServices, projectToSeenServices)- }- if p.inspect.Config != nil && p.inspect.Config.Labels != nil {- labels = p.inspect.Config.Labels- }-- res := updater.ResourceResult{- ResourceID: p.cnt.ID,- ResourceName: name,- ResourceType: "container",- Status: "checked",- OldImages: map[string]string{"main": p.match},- NewImages: map[string]string{"main": libupdater.NormalizeImageUpdateRef(p.newRef)},- }-- if p.newRef == "" {- res.Status = "skipped"- res.Error = "no matching updated image"- results = append(results, res)- continue- }-- slog.DebugContext(ctx, "restartContainersUsingOldIDs: processing container", "containerId", p.cnt.ID, "container", name, "match", p.match, "newRef", p.newRef, "implicit", p.implicit)-- func() {- endContainerStatus := s.beginContainerUpdateInternal(p.cnt.ID)- defer endContainerStatus()- endProjectStatus := s.beginProjectUpdateInternal(composeProjectNameFromLabelsInternal(labels))- defer endProjectStatus()-- projectName := dockerutil.ComposeProjectLabel(labels)- serviceName := dockerutil.ComposeServiceLabel(labels)- var proj *models.Project- if projectName != "" {- if projectID, ok := lookupComposeProjectIDInternal(projectName, projectNameToID); ok {- proj = projectIDToObj[projectID]- }- }-- if proj != nil && serviceName != "" && !libupdater.IsArcaneContainer(labels) {- if pErr, failed := projectResults[proj.ID]; failed {- res.Status = "failed"- res.Error = fmt.Sprintf("project-level update failed: %v", pErr)- } else {- pendingServices := pendingComposeProjectServicesInternal(processedProjectServices, proj.ID, projectToServices[proj.ID])- if len(pendingServices) > 0 {- slog.InfoContext(ctx, "restartContainersUsingOldIDs: executing project-level update", "project", proj.Name, "services", pendingServices)- err := s.projectService.UpdateProjectServices(ctx, proj.ID, pendingServices, systemUser)- markComposeProjectServicesProcessedInternal(processedProjectServices, proj.ID, pendingServices)- if err != nil {- slog.ErrorContext(ctx, "restartContainersUsingOldIDs: project update failed", "project", proj.Name, "err", err)- projectResults[proj.ID] = err- }- }-- if pErr, failed := projectResults[proj.ID]; failed {- res.Status = "failed"- res.Error = fmt.Sprintf("project-level update failed: %v", pErr)- } else if verifyErr := libupdater.VerifyComposeServiceUpdatedImage(ctx, dcli, projectName, serviceName, libupdater.CurrentContainerImageID(p.cnt, p.inspect)); verifyErr != nil {- // A per-service verification failure is specific to this service. The- // project-level update already ran for every pending service, so we must- // not poison projectResults here: sibling services that are already- // running the new image would otherwise be reported as failures.- res.Status = "failed"- res.Error = fmt.Sprintf("service update verification failed: %v", verifyErr)- } else {- res.Status = "updated"- res.UpdateAvailable = true- res.UpdateApplied = true- // Send notification- if s.notificationService != nil {- if notifErr := s.notificationService.SendContainerUpdateNotification(ctx, name, p.newRef, p.match, libupdater.NormalizeImageUpdateRef(p.newRef)); notifErr != nil {- slog.WarnContext(ctx, "Failed to send container update notification", "containerId", p.cnt.ID, "containerName", name, "imageRef", p.newRef, "error", notifErr.Error())- }- }- }- }- } else // Arcane self-updates must go through the detached CLI upgrader.- if libupdater.IsArcaneContainer(labels) {- if err := s.triggerSelfUpdateViaCLIInternal(ctx, "restartContainersUsingOldIDs", p.cnt.ID, name, labels); err != nil {- res.Status = "failed"- res.Error = err.Error()- } else {- res.Status = "updated"- res.UpdateAvailable = true- res.UpdateApplied = true- slog.InfoContext(ctx, "restartContainersUsingOldIDs: CLI upgrade triggered successfully", "containerId", p.cnt.ID)- }- } else if err := s.updateContainer(ctx, p.cnt, *p.inspect, p.newRef); err != nil {- res.Status = "failed"- res.Error = err.Error()- slog.DebugContext(ctx, "restartContainersUsingOldIDs: update failed", "containerId", p.cnt.ID, "err", err)- } else {- res.Status = "updated"- res.UpdateAvailable = true- res.UpdateApplied = true- slog.DebugContext(ctx, "restartContainersUsingOldIDs: update succeeded", "containerId", p.cnt.ID)-- // Send notification after successful container update- if s.notificationService != nil {- if notifErr := s.notificationService.SendContainerUpdateNotification(ctx, name, p.newRef, p.match, libupdater.NormalizeImageUpdateRef(p.newRef)); notifErr != nil {- slog.WarnContext(ctx, "Failed to send container update notification", "containerId", p.cnt.ID, "containerName", name, "imageRef", p.newRef, "error", notifErr.Error())- }- }- }- }()- results = append(results, res)- }- slog.DebugContext(ctx, "restartContainersUsingOldIDs: completed scanning", "results", len(results))- return results, nil-}--func (s *UpdaterService) triggerSelfUpdateViaCLIInternal(ctx context.Context, source, containerID, containerName string, labels map[string]string) error {- if !libupdater.IsArcaneContainer(labels) {- return fmt.Errorf("%s: container is not an Arcane self-update target", source)- }-- instanceType := "server"- if libupdater.IsArcaneAgentContainer(labels) {- instanceType = "agent"- }-- if s.upgradeService == nil {- err := fmt.Errorf("%s self-update requires CLI upgrade service", instanceType)- slog.ErrorContext(ctx, source+": missing CLI upgrade service for Arcane self-update",- "containerId", containerID,- "container", containerName,- "instanceType", instanceType,- "err", err)return err}- slog.InfoContext(ctx, source+": detected Arcane self-update, using CLI upgrade method",- "containerId", containerID,- "container", containerName,- "instanceType", instanceType)-- if err := s.upgradeService.TriggerUpgradeViaCLI(ctx, systemUser); err != nil {- wrappedErr := fmt.Errorf("CLI upgrade failed: %w", err)- slog.WarnContext(ctx, source+": CLI upgrade failed",- "containerId", containerID,- "container", containerName,- "instanceType", instanceType,- "err", err)- return wrappedErr- }-+ s.collectUsedImagesFromComposeContainersInternal(ctx, composeContainers, activeProjectNames, out)return nil}-func pendingComposeProjectServicesInternal(processedProjectServices map[string]map[string]struct{}, projectID string, services []string) []string {- if len(services) == 0 {- return nil- }-- processed := processedProjectServices[projectID]- pending := make([]string, 0, len(services))- for _, service := range services {- if processed == nil {- pending = append(pending, service)+func activeComposeProjectNameSetInternal(projects []models.Project) map[string]struct{} {+ active := make(map[string]struct{})+ for _, project := range projects {+ if project.IsArchived {continue}- if _, alreadyProcessed := processed[service]; !alreadyProcessed {- pending = append(pending, service)- }- }-- return pending-}--func markComposeProjectServicesProcessedInternal(processedProjectServices map[string]map[string]struct{}, projectID string, services []string) {- if len(services) == 0 {- return- }-- if _, exists := processedProjectServices[projectID]; !exists {- processedProjectServices[projectID] = make(map[string]struct{}, len(services))- }- for _, service := range services {- processedProjectServices[projectID][service] = struct{}{}- }-}--// lazyRegisterComposeProjectInternal registers a compose project into the pre-scan lookup maps when the-// container's inspect data was unavailable during the pre-scan (inspect was nil at that point).-// Without this, the main loop's lookupComposeProjectIDInternal call would miss the project and-// fall through to the destructive standalone stop/rm/run path.-func (s *UpdaterService) lazyRegisterComposeProjectInternal(- ctx context.Context,- p *restartPlan,- projectNameToID map[string]string,- projectIDToObj map[string]*models.Project,- projectToServices map[string][]string,- projectToSeenServices map[string]map[string]struct{},-) {- if p.newRef == "" || p.inspect == nil || p.inspect.Config == nil {- return- }- projectName := dockerutil.ComposeProjectLabel(p.inspect.Config.Labels)- serviceName := dockerutil.ComposeServiceLabel(p.inspect.Config.Labels)- if projectName == "" || serviceName == "" {- return- }-- projectID, registered := lookupComposeProjectIDInternal(projectName, projectNameToID)- if !registered {- proj, err := s.projectService.GetProjectByComposeName(ctx, projectName)- if err != nil {- return- }- projectID = proj.ID- projectIDToObj[proj.ID] = proj- projectNameToID[proj.Name] = proj.ID- projectNameToID[loader.NormalizeProjectName(proj.Name)] = proj.ID- }- if _, ok := projectToSeenServices[projectID]; !ok {- projectToSeenServices[projectID] = make(map[string]struct{})- }- if _, seen := projectToSeenServices[projectID][serviceName]; !seen {- projectToServices[projectID] = append(projectToServices[projectID], serviceName)- projectToSeenServices[projectID][serviceName] = struct{}{}- }-}--func (s *UpdaterService) beginContainerUpdateInternal(containerID string) func() {- containerID = strings.TrimSpace(containerID)- if containerID == "" {- return func() {}- }-- s.statusMu.Lock()- s.updatingContainers[containerID] = true- s.statusMu.Unlock()-- return func() {- s.statusMu.Lock()- delete(s.updatingContainers, containerID)- s.statusMu.Unlock()- }-}--func (s *UpdaterService) beginProjectUpdateInternal(projectID string) func() {- projectID = strings.TrimSpace(projectID)- if projectID == "" {- return func() {}- }-- s.statusMu.Lock()- s.updatingProjects[projectID] = true- s.statusMu.Unlock()-- return func() {- s.statusMu.Lock()- delete(s.updatingProjects, projectID)- s.statusMu.Unlock()- }-}--func composeProjectNameFromLabelsInternal(labels map[string]string) string {- if len(labels) == 0 {- return ""- }- return dockerutil.ComposeProjectLabel(labels)-}--func lookupComposeProjectIDInternal(projectName string, projectNameToID map[string]string) (string, bool) {- if projectName == "" || len(projectNameToID) == 0 {- return "", false- }- if projectID, ok := projectNameToID[projectName]; ok {- return projectID, true- }- projectID, ok := projectNameToID[loader.NormalizeProjectName(projectName)]- return projectID, ok-}--func (s *UpdaterService) statusSnapshotInternal() updater.Status {- s.statusMu.RLock()- defer s.statusMu.RUnlock()-- containerIDs := make([]string, 0, len(s.updatingContainers))- for id := range s.updatingContainers {- containerIDs = append(containerIDs, id)- }- projectIDs := make([]string, 0, len(s.updatingProjects))- for id := range s.updatingProjects {- projectIDs = append(projectIDs, id)- }-- return updater.Status{- UpdatingContainers: len(s.updatingContainers),- UpdatingProjects: len(s.updatingProjects),- ContainerIds: containerIDs,- ProjectIds: projectIDs,- }-}--func resolvePullableImageRefInternal(summaryImage, inspectConfigImage string, repoTags []string) (ref, source string) {- if image := strings.TrimSpace(inspectConfigImage); image != "" && !libupdater.IsImageIDLikeReference(image) {- return image, "container_inspect_config"- }-- if image := strings.TrimSpace(summaryImage); image != "" && !libupdater.IsImageIDLikeReference(image) {- return image, "container_summary"- }-- for _, tag := range repoTags {- trimmed := strings.TrimSpace(tag)- if trimmed == "" || trimmed == "<none>:<none>" || libupdater.IsImageIDLikeReference(trimmed) {+ if project.Status != models.ProjectStatusRunning && project.Status != models.ProjectStatusPartiallyRunning {continue}- return trimmed, "image_repo_tag"- }-- return "", ""-}--func (s *UpdaterService) logAutoUpdate(ctx context.Context, sev models.EventSeverity, metadata models.JSON) {- phase, _ := metadata["phase"].(string)- title := "Auto-update"- switch phase {- case "start":- title = "Auto-update run started"- case "image_pull":- img := fmt.Sprint(metadata["imageNew"])- if img == "" {- img = fmt.Sprint(metadata["imageOld"])- }- if img != "" {- title = "Auto-update: image pull " + img- } else {- title = "Auto-update: image pull"- }- case "image_prune":- imageID := fmt.Sprint(metadata["imageId"])- if imageID != "" {- title = "Auto-update: image prune " + imageID- } else {- title = "Auto-update: image prune"- }- case "container":- name := fmt.Sprint(metadata["container"])+ name := strings.TrimSpace(project.Name)if name == "" {- name = fmt.Sprint(metadata["containerId"])- }- if name != "" {- title = "Auto-update: container " + name- } else {- title = "Auto-update: container"- }- case "project":- name := fmt.Sprint(metadata["projectName"])- if name == "" {- name = fmt.Sprint(metadata["projectId"])+ continue}- if name != "" {- title = "Auto-update: project " + name- } else {- title = "Auto-update: project"+ active[name] = struct{}{}+ if normalized := loader.NormalizeProjectName(name); normalized != "" {+ active[normalized] = struct{}{}}- case "complete":- title = "Auto-update run completed"- }-- _, _ = s.eventService.CreateEvent(ctx, CreateEventRequest{- Type: models.EventTypeSystemAutoUpdate,- Severity: sev,- Title: title,- ResourceType: new("system"),- ResourceName: new("auto_updater"),- EnvironmentID: new("0"),- Metadata: metadata,- })-}--func (s *UpdaterService) severityFromStatus(status string) models.EventSeverity {- switch status {- case "failed":- return models.EventSeverityError- case "updated":- return models.EventSeveritySuccess- default:- return models.EventSeverityInfo}+ return active}-func (s *UpdaterService) anyImageIDsStillInUse(ctx context.Context, ids []string) (bool, error) {- if len(ids) == 0 {- return false, nil- }- set := make(map[string]struct{}, len(ids))- for _, id := range ids {- if id != "" {- set[id] = struct{}{}- }- }-- slog.DebugContext(ctx, "anyImageIDsStillInUse: checking ids", "ids", ids)-- dcli, err := s.dockerService.GetClient(ctx)- if err != nil {- return false, fmt.Errorf("docker connect: %w", err)- }-- listResult, err := dcli.ContainerList(ctx, client.ContainerListOptions{All: false})- if err != nil {- return false, fmt.Errorf("list containers: %w", err)- }- list := listResult.Items- for _, c := range list {- inspectResult, ierr := libarcane.ContainerInspectWithCompatibility(ctx, dcli, c.ID, client.ContainerInspectOptions{})- if ierr != nil {- continue- }- inspect := inspectResult.Container- if _, ok := set[inspect.Image]; ok {- slog.DebugContext(ctx, "anyImageIDsStillInUse: image still used by container", "imageId", inspect.Image, "containerId", c.ID)- return true, nil- }+func addNormalizedImageUpdateRefInternal(ctx context.Context, out map[string]struct{}, imageRef, logMessage string, attrs ...any) {+ normalizedRef := refs.NormalizeImageUpdateRef(imageRef)+ if normalizedRef != "" {+ out[normalizedRef] = struct{}{}+ return}- slog.DebugContext(ctx, "anyImageIDsStillInUse: no matching usage found")- return false, nil-}-func (s *UpdaterService) anyImageIDsStillInUseWithSetInternal(ctx context.Context, ids []string, inUseSet map[string]struct{}) (bool, error) {- if inUseSet != nil {- return anyImageIDsInUseSetInternal(ids, inUseSet), nil+ args := slices.Clone(attrs)+ args = append(args, "imageRef", imageRef)+ if ctx != nil {+ slog.DebugContext(ctx, logMessage, args...)+ return}- return s.anyImageIDsStillInUse(ctx, ids)+ slog.Debug(logMessage, args...)}-func anyImageIDsInUseSetInternal(ids []string, inUseSet map[string]struct{}) bool {- if len(ids) == 0 || len(inUseSet) == 0 {+func containerSummaryExcludedInternal(summary container.Summary, excludedContainers map[string]bool) bool {+ if len(excludedContainers) == 0 {return false}-- for _, id := range ids {- if id == "" {- continue- }- if _, ok := inUseSet[id]; ok {+ for _, name := range summary.Names {+ if excludedContainers[strings.TrimPrefix(name, "/")] {return true}}return false}--func (s *UpdaterService) buildRunningImageIDSetInternal(ctx context.Context) (map[string]struct{}, error) {- dcli, err := s.dockerService.GetClient(ctx)- if err != nil {- return nil, fmt.Errorf("docker connect: %w", err)- }-- listResult, err := dcli.ContainerList(ctx, client.ContainerListOptions{All: false})- if err != nil {- return nil, fmt.Errorf("list containers: %w", err)- }- list := listResult.Items-- inUseSet := make(map[string]struct{}, len(list))- for _, c := range list {- if c.ImageID != "" {- inUseSet[c.ImageID] = struct{}{}- continue- }-- inspectResult, ierr := libarcane.ContainerInspectWithCompatibility(ctx, dcli, c.ID, client.ContainerInspectOptions{})- inspect := inspectResult.Container- if ierr == nil && inspect.Image != "" {- inUseSet[inspect.Image] = struct{}{}- }- }-- return inUseSet, nil-}--func (s *UpdaterService) clearImageUpdateRecord(ctx context.Context, repository, tag string) error {- return s.db.WithContext(ctx).- Model(&models.ImageUpdateRecord{}).- Where("repository = ? AND tag = ?", repository, tag).- Update("has_update", false).Error-}--func (s *UpdaterService) clearImageUpdateRecordByID(ctx context.Context, imageID string) error {- return s.db.WithContext(ctx).- Model(&models.ImageUpdateRecord{}).- Where("id = ?", imageID).- Update("has_update", false).Error-}--// parseRepoAndTag extracts repository and tag from a reference like "registry/repo:tag".-// Uses the last ":" occurring after the last "/" as the tag separator. Defaults tag to "latest".-func (s *UpdaterService) parseRepoAndTag(ref string) (string, string) {- // strip digest if present- ref = s.stripDigest(ref)-- tag := "latest"- slash := strings.LastIndex(ref, "/")- colon := strings.LastIndex(ref, ":")- if colon > slash && colon != -1 {- tag = ref[colon+1:]- ref = ref[:colon]- }- // Keep registry in repository as stored in records (they store Repository without tag)- return ref, tag-}--// dockerProxyContainerNameInternal extracts the container hostname from a TCP-// DOCKER_HOST value (e.g. "tcp://my-proxy:2375" → "my-proxy"). Returns empty-// string when DOCKER_HOST is not a TCP address, is an IP, or cannot be parsed.-func dockerProxyContainerNameInternal(dockerHost string) string {- dockerHost = strings.TrimSpace(dockerHost)- if dockerHost == "" {- return ""- }- u, err := url.Parse(dockerHost)- if err != nil || strings.ToLower(u.Scheme) != "tcp" {- return ""- }- host := u.Hostname() // strips brackets from IPv6, strips port- if host == "" || host == "localhost" || strings.Contains(host, ".") || net.ParseIP(host) != nil {- return ""- }- return host-}diff --git a/backend/internal/services/updater_service_test.go b/backend/internal/services/updater_service_test.goindex 3e91e7a4a..2797c074b 100644--- a/backend/internal/services/updater_service_test.go+++ b/backend/internal/services/updater_service_test.go@@ -1,1153 +1,336 @@package servicesimport (+ "bytes""context"- "encoding/json""errors"- "net"- "net/http"- "net/http/httptest"- "net/netip"- "net/url"- "os"- "path/filepath"- "strings""testing""time"- "github.com/compose-spec/compose-go/v2/loader"- composetypes "github.com/compose-spec/compose-go/v2/types"- "github.com/getarcaneapp/arcane/backend/internal/config"- "github.com/getarcaneapp/arcane/backend/internal/database"- glsqlite "github.com/glebarez/sqlite"- "github.com/moby/moby/api/types/container"- dockertypesimage "github.com/moby/moby/api/types/image"- "github.com/moby/moby/api/types/network"- dockerclient "github.com/moby/moby/client"+ "github.com/getarcaneapp/arcane/backend/internal/models"+ moduleapi "github.com/getarcaneapp/updater/api"+ updaterlabels "github.com/getarcaneapp/updater/pkg/labels"+ moduletypes "github.com/getarcaneapp/updater/types""github.com/stretchr/testify/assert""github.com/stretchr/testify/require"- "gorm.io/gorm"-- "github.com/getarcaneapp/arcane/backend/internal/models"- libupdater "github.com/getarcaneapp/arcane/backend/pkg/libarcane/imageupdate")-// mockSystemUpgradeService is a simple mock implementation for testing-type mockSystemUpgradeService struct {+type mockSystemUpgradeServiceInternal struct {triggerCalled booltriggerError errorcapturedUser *models.User- canUpgrade bool}-func (m *mockSystemUpgradeService) TriggerUpgradeViaCLI(ctx context.Context, user models.User) error {+func (m *mockSystemUpgradeServiceInternal) TriggerUpgradeViaCLI(_ context.Context, user models.User) error {m.triggerCalled = truem.capturedUser = &userreturn m.triggerError}-func (m *mockSystemUpgradeService) CanUpgrade(ctx context.Context) (bool, error) {- return m.canUpgrade, nil-}--// TestUpdaterService_ArcaneLabel_TriggersCLIUpgrade verifies that when the-// com.getarcaneapp.arcane label is set to "true", the IsArcaneContainer check-// returns true, indicating that CLI upgrade should be triggered-func TestUpdaterService_ArcaneLabel_TriggersCLIUpgrade(t *testing.T) {+func TestUpdaterService_ApplyPendingNoRecordsInternal(t *testing.T) {ctx := context.Background()+ db := setupProjectTestDB(t)+ svc := NewUpdaterService(db, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil)- // Create mock upgrade service- mockUpgrade := &mockSystemUpgradeService{}-- // Test with Arcane label set to "true"- labels := map[string]string{- "com.getarcaneapp.arcane": "true",- }-- // Verify that IsArcaneContainer correctly identifies the label- isArcane := libupdater.IsArcaneContainer(labels)- assert.True(t, isArcane, "IsArcaneContainer should return true for Arcane label")-- // Simulate the logic from restartContainersUsingOldIDs:- // When upgradeService is not nil and isArcane is true, CLI should be called- if isArcane {- _ = mockUpgrade.TriggerUpgradeViaCLI(ctx, systemUser)- }-- // Verify CLI upgrade was called- assert.True(t, mockUpgrade.triggerCalled, "TriggerUpgradeViaCLI should have been called for Arcane container")-}--func TestUpdaterService_ArcaneAgentLabel_TriggersCLIUpgrade(t *testing.T) {- ctx := context.Background()- mockUpgrade := &mockSystemUpgradeService{}- service := &UpdaterService{upgradeService: mockUpgrade}-- labels := map[string]string{- libupdater.LabelArcaneAgent: "true",- }-- err := service.triggerSelfUpdateViaCLIInternal(ctx, "test", "container-1", "arcane-agent", labels)+ result, err := svc.ApplyPending(ctx, true)require.NoError(t, err)- assert.True(t, mockUpgrade.triggerCalled, "TriggerUpgradeViaCLI should have been called for Arcane agent container")- assert.NotNil(t, mockUpgrade.capturedUser)- assert.Equal(t, systemUser.ID, mockUpgrade.capturedUser.ID)+ require.NotNil(t, result)+ assert.Zero(t, result.Checked)+ assert.Zero(t, result.Updated)+ assert.Zero(t, result.Skipped)+ assert.Zero(t, result.Failed)+ assert.Empty(t, result.Items)}-// TestUpdaterService_NonArcaneLabel_DoesNotTriggerCLI verifies that containers without-// the Arcane label do not trigger CLI upgrade-func TestUpdaterService_NonArcaneLabel_DoesNotTriggerCLI(t *testing.T) {+func TestUpdaterService_ConfigUsesComposeStandaloneFallbackSettingInternal(t *testing.T) {ctx := context.Background()- // Create mock upgrade service- mockUpgrade := &mockSystemUpgradeService{}-- // Test with no Arcane label- labels := map[string]string{- "some.other.label": "true",- }-- // Verify that IsArcaneContainer returns false- isArcane := libupdater.IsArcaneContainer(labels)- assert.False(t, isArcane, "IsArcaneContainer should return false for non-Arcane container")-- // Simulate the logic from restartContainersUsingOldIDs- if isArcane {- _ = mockUpgrade.TriggerUpgradeViaCLI(ctx, systemUser)- }-- // Verify CLI upgrade was NOT called- assert.False(t, mockUpgrade.triggerCalled, "TriggerUpgradeViaCLI should not have been called for non-Arcane container")-}--func TestUpdaterService_TriggerSelfUpdateViaCLI_NonArcaneContainer(t *testing.T) {- ctx := context.Background()- mockUpgrade := &mockSystemUpgradeService{}- service := &UpdaterService{upgradeService: mockUpgrade}-- labels := map[string]string{- "some.other.label": "true",- }-- err := service.triggerSelfUpdateViaCLIInternal(ctx, "test", "container-1", "not-arcane", labels)-- require.Error(t, err)- assert.Contains(t, err.Error(), "container is not an Arcane self-update target")- assert.False(t, mockUpgrade.triggerCalled, "non-Arcane containers must not trigger the CLI upgrade path")-}--// TestUpdaterService_ArcaneLabelWithError_PropagatesError verifies that CLI upgrade errors-// are properly propagated-func TestUpdaterService_ArcaneLabelWithError_PropagatesError(t *testing.T) {- ctx := context.Background()-- // Create mock that returns an error- expectedErr := errors.New("upgrade already in progress")- mockUpgrade := &mockSystemUpgradeService{- triggerError: expectedErr,- }-- labels := map[string]string{- "com.getarcaneapp.arcane": "true",- }-- isArcane := libupdater.IsArcaneContainer(labels)- assert.True(t, isArcane, "Should detect Arcane container")+ t.Run("defaults disabled without settings service", func(t *testing.T) {+ svc := NewUpdaterService(nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil)- // Call the upgrade method- var err error- if isArcane {- err = mockUpgrade.TriggerUpgradeViaCLI(ctx, systemUser)- }-- // Verify error is propagated- require.Error(t, err, "Error should be propagated from TriggerUpgradeViaCLI")- assert.Equal(t, expectedErr, err, "Should return the same error")- assert.True(t, mockUpgrade.triggerCalled, "TriggerUpgradeViaCLI should have been attempted")-}+ cfg := svc.configInternal(ctx)-// TestUpdaterService_NilUpgradeService_GracefulHandling verifies graceful handling-// when upgrade service is nil-func TestUpdaterService_NilUpgradeService_GracefulHandling(t *testing.T) {- ctx := context.Background()- service := &UpdaterService{}+ assert.False(t, cfg.AllowComposeStandaloneFallback)+ })- labels := map[string]string{- libupdater.LabelArcane: "true",- }+ t.Run("reads settings service", func(t *testing.T) {+ db := setupProjectTestDB(t)+ settingsSvc, err := NewSettingsService(ctx, db)+ require.NoError(t, err)+ require.NoError(t, settingsSvc.SetBoolSetting(ctx, autoUpdateComposeStandaloneFallbackSettingKeyInternal, true))+ svc := NewUpdaterService(db, settingsSvc, nil, nil, nil, nil, nil, nil, nil, nil, nil)- err := service.triggerSelfUpdateViaCLIInternal(ctx, "test", "container-1", "arcane", labels)+ cfg := svc.configInternal(ctx)- require.Error(t, err)- assert.Contains(t, err.Error(), "server self-update requires CLI upgrade service")+ assert.True(t, cfg.AllowComposeStandaloneFallback)+ })}-func TestUpdaterService_ArcaneAgentLabel_MissingUpgradeServiceReturnsError(t *testing.T) {+func TestUpdaterService_TriggerSelfUpdateViaCLIInternal(t *testing.T) {ctx := context.Background()- service := &UpdaterService{}- labels := map[string]string{- libupdater.LabelArcaneAgent: "true",- }+ t.Run("server label triggers upgrade with system user", func(t *testing.T) {+ mockUpgrade := &mockSystemUpgradeServiceInternal{}+ svc := NewUpdaterService(nil, nil, nil, nil, nil, nil, nil, nil, nil, mockUpgrade, nil)- err := service.triggerSelfUpdateViaCLIInternal(ctx, "test", "container-1", "arcane-agent", labels)-- require.Error(t, err)- assert.Contains(t, err.Error(), "agent self-update requires CLI upgrade service")-}--// TestUpdaterService_ArcaneLabelVariations tests various label formats-func TestUpdaterService_ArcaneLabelVariations(t *testing.T) {- tests := []struct {- name string- labels map[string]string- expectedArcane bool- description string- }{- {- name: "standard arcane label",- labels: map[string]string{- "com.getarcaneapp.arcane": "true",- },- expectedArcane: true,- description: "Standard Arcane label should be detected",- },- {- name: "empty labels",- labels: map[string]string{},- expectedArcane: false,- description: "Empty labels should not be detected as Arcane",- },- {- name: "nil labels",- labels: nil,- expectedArcane: false,- description: "Nil labels should not be detected as Arcane",- },- {- name: "other labels only",- labels: map[string]string{- "some.other.label": "true",- },- expectedArcane: false,- description: "Non-Arcane labels should not be detected as Arcane",- },- {- name: "arcane label false",- labels: map[string]string{- "com.getarcaneapp.arcane": "false",- },- expectedArcane: false,- description: "Arcane label set to false should not be detected as Arcane",- },- }-- for _, tt := range tests {- t.Run(tt.name, func(t *testing.T) {- isArcane := libupdater.IsArcaneContainer(tt.labels)- assert.Equal(t, tt.expectedArcane, isArcane, tt.description)+ err := svc.TriggerSelfUpdateViaCLI(ctx, "test", "container-1", "arcane", map[string]string{+ updaterlabels.LabelArcane: "true",})- }-}--// TestUpdaterService_CLICalledWithSystemUser verifies that systemUser is passed-func TestUpdaterService_CLICalledWithSystemUser(t *testing.T) {- ctx := context.Background()-- mockUpgrade := &mockSystemUpgradeService{}-- labels := map[string]string{- "com.getarcaneapp.arcane": "true",- }- isArcane := libupdater.IsArcaneContainer(labels)- assert.True(t, isArcane)-- if isArcane {- _ = mockUpgrade.TriggerUpgradeViaCLI(ctx, systemUser)- }-- // Verify systemUser was passed- assert.True(t, mockUpgrade.triggerCalled)- assert.NotNil(t, mockUpgrade.capturedUser)- assert.Equal(t, systemUser.ID, mockUpgrade.capturedUser.ID)- assert.Equal(t, systemUser.Username, mockUpgrade.capturedUser.Username)-}--func TestUpdaterService_UpdateSingleContainerSkipsSwarmTaskInternal(t *testing.T) {- ctx := context.Background()- const containerID = "swarm-task-1"- labels := map[string]string{- libupdater.LabelSwarmServiceID: "service-1",- libupdater.LabelSwarmServiceName: "web",- }- pullCalled := false-- srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {- switch {- case strings.HasSuffix(r.URL.Path, "/containers/json"):- w.Header().Set("Content-Type", "application/json")- require.NoError(t, json.NewEncoder(w).Encode([]container.Summary{- {- ID: containerID,- Names: []string{"/web.1.task"},- Image: "nginx:latest",- ImageID: "sha256:old-image",- Labels: labels,- },- }))- case strings.Contains(r.URL.Path, "/containers/") && strings.HasSuffix(r.URL.Path, "/json"):- w.Header().Set("Content-Type", "application/json")- require.NoError(t, json.NewEncoder(w).Encode(container.InspectResponse{- ID: containerID,- Image: "sha256:old-image",- Config: &container.Config{- Image: "nginx:latest",- Labels: labels,- },- }))- case strings.HasSuffix(r.URL.Path, "/images/create"):- pullCalled = true- http.Error(w, "unexpected pull", http.StatusInternalServerError)- default:- http.NotFound(w, r)- }- }))- defer srv.Close()-- dcli, err := dockerclient.NewClientWithOpts(- dockerclient.WithHost("tcp://"+srv.Listener.Addr().String()),- dockerclient.WithVersion("1.46"),- )- require.NoError(t, err)-- db := setupActivityServiceTestDBInternal(t)- svc := NewUpdaterService(nil, nil, &DockerClientService{client: dcli, config: &config.Config{}}, nil, nil, nil, nil, nil, nil, nil, NewActivityService(db))-- out, err := svc.UpdateSingleContainer(ctx, containerID)- require.NoError(t, err)- require.NotNil(t, out)- require.Len(t, out.Items, 1)- assert.Equal(t, "skipped", out.Items[0].Status)- assert.Contains(t, out.Items[0].Error, "swarm service")- assert.False(t, pullCalled, "swarm task update must not pull or recreate the task container")-}--func TestUpdaterService_RestartContainersUsingOldIDsSkipsSwarmTaskInternal(t *testing.T) {- ctx := context.Background()- const containerID = "swarm-task-1"- labels := map[string]string{- libupdater.LabelSwarmServiceID: "service-1",- libupdater.LabelSwarmServiceName: "web",- }- stopCalled := false-- srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {- switch {- case strings.HasSuffix(r.URL.Path, "/containers/json"):- w.Header().Set("Content-Type", "application/json")- require.NoError(t, json.NewEncoder(w).Encode([]container.Summary{- {- ID: containerID,- Names: []string{"/web.1.task"},- Image: "nginx:latest",- ImageID: "sha256:old-image",- Labels: labels,- },- }))- case strings.Contains(r.URL.Path, "/containers/") && strings.HasSuffix(r.URL.Path, "/json"):- w.Header().Set("Content-Type", "application/json")- require.NoError(t, json.NewEncoder(w).Encode(container.InspectResponse{- ID: containerID,- Name: "/web.1.task",- Image: "sha256:old-image",- Config: &container.Config{- Image: "nginx:latest",- Labels: labels,- },- }))- case strings.Contains(r.URL.Path, "/containers/") && strings.HasSuffix(r.URL.Path, "/stop"):- stopCalled = true- http.Error(w, "unexpected stop", http.StatusInternalServerError)- default:- http.NotFound(w, r)- }- }))- defer srv.Close()-- dcli, err := dockerclient.NewClientWithOpts(- dockerclient.WithHost("tcp://"+srv.Listener.Addr().String()),- dockerclient.WithVersion("1.46"),- )- require.NoError(t, err)+ require.NoError(t, err)+ assert.True(t, mockUpgrade.triggerCalled)+ require.NotNil(t, mockUpgrade.capturedUser)+ assert.Equal(t, systemUser.ID, mockUpgrade.capturedUser.ID)+ assert.Equal(t, systemUser.Username, mockUpgrade.capturedUser.Username)+ })- settingsDB := setupUpdaterServiceSettingsDB(t)- settings, err := NewSettingsService(ctx, settingsDB)- require.NoError(t, err)- svc := NewUpdaterService(nil, settings, &DockerClientService{client: dcli, config: &config.Config{}}, nil, nil, nil, nil, nil, nil, nil, nil)+ t.Run("agent label triggers upgrade", func(t *testing.T) {+ mockUpgrade := &mockSystemUpgradeServiceInternal{}+ svc := NewUpdaterService(nil, nil, nil, nil, nil, nil, nil, nil, nil, mockUpgrade, nil)- results, err := svc.restartContainersUsingOldIDs(ctx, map[string]string{"sha256:old-image": "nginx:latest"}, nil)- require.NoError(t, err)- assert.Empty(t, results)- assert.False(t, stopCalled, "swarm task update must not stop the orchestrator-owned task container")-}+ err := svc.TriggerSelfUpdateViaCLI(ctx, "test", "container-1", "arcane-agent", map[string]string{+ updaterlabels.LabelArcaneAgent: "true",+ })-// TestUpdaterService_UpgradeServiceNotNilCheck verifies the nil check logic-func TestUpdaterService_UpgradeServiceNotNilCheck(t *testing.T) {- ctx := context.Background()+ require.NoError(t, err)+ assert.True(t, mockUpgrade.triggerCalled)+ })- labels := map[string]string{- "com.getarcaneapp.arcane": "true",- }+ t.Run("non Arcane labels fail without triggering upgrade", func(t *testing.T) {+ mockUpgrade := &mockSystemUpgradeServiceInternal{}+ svc := NewUpdaterService(nil, nil, nil, nil, nil, nil, nil, nil, nil, mockUpgrade, nil)- // Test with non-nil upgrade service- mockUpgrade := &mockSystemUpgradeService{}- isArcane := libupdater.IsArcaneContainer(labels)+ err := svc.TriggerSelfUpdateViaCLI(ctx, "test", "container-1", "demo", map[string]string{+ "com.example.app": "demo",+ })- // This is the actual logic from restartContainersUsingOldIDs- if isArcane {- _ = mockUpgrade.TriggerUpgradeViaCLI(ctx, systemUser)- }+ require.Error(t, err)+ assert.Contains(t, err.Error(), "not an Arcane self-update target")+ assert.False(t, mockUpgrade.triggerCalled)+ })- assert.True(t, mockUpgrade.triggerCalled, "Should call CLI upgrade when service is not nil")-}+ t.Run("missing upgrade service reports required hook", func(t *testing.T) {+ svc := NewUpdaterService(nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil)-func TestLookupComposeProjectIDInternal(t *testing.T) {- t.Run("exact match", func(t *testing.T) {- projectID, ok := lookupComposeProjectIDInternal("myproject", map[string]string{- "myproject": "p1",+ err := svc.TriggerSelfUpdateViaCLI(ctx, "test", "container-1", "arcane", map[string]string{+ updaterlabels.LabelArcane: "true",})- require.True(t, ok)- assert.Equal(t, "p1", projectID)- })- t.Run("normalized fallback", func(t *testing.T) {- projectID, ok := lookupComposeProjectIDInternal("My Project", map[string]string{- loader.NormalizeProjectName("myproject"): "p1",- })- require.True(t, ok)- assert.Equal(t, "p1", projectID)+ require.Error(t, err)+ assert.Contains(t, err.Error(), "self-update requires CLI upgrade service")})- t.Run("missing project", func(t *testing.T) {- projectID, ok := lookupComposeProjectIDInternal("missing", map[string]string{- "other": "p1",+ t.Run("upgrade errors are wrapped", func(t *testing.T) {+ mockUpgrade := &mockSystemUpgradeServiceInternal{triggerError: errors.New("upgrade failed")}+ svc := NewUpdaterService(nil, nil, nil, nil, nil, nil, nil, nil, nil, mockUpgrade, nil)++ err := svc.TriggerSelfUpdateViaCLI(ctx, "test", "container-1", "arcane", map[string]string{+ updaterlabels.LabelArcane: "true",})- require.False(t, ok)- assert.Empty(t, projectID)++ require.Error(t, err)+ assert.Contains(t, err.Error(), "CLI upgrade failed")})}-func TestUpdaterService_LazyRegisterComposeProjectInternal_AddsServicesForRegisteredProject(t *testing.T) {- db := setupProjectTestDB(t)- ctx := context.Background()-- project := &models.Project{- BaseModel: models.BaseModel{ID: "p1"},- Name: "My Project!",- Path: "/tmp/my-project",- }- require.NoError(t, db.Create(project).Error)-- projectService := NewProjectService(db, nil, nil, nil, nil, nil, config.Load())- svc := &UpdaterService{projectService: projectService}+func TestUpdaterService_StatusTrackingInternal(t *testing.T) {+ svc := NewUpdaterService(nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil)- projectNameToID := map[string]string{}- projectIDToObj := map[string]*models.Project{}- projectToServices := map[string][]string{}- projectToSeenServices := map[string]map[string]struct{}{}+ stopContainer := svc.BeginContainerUpdate("container-1")+ stopProject := svc.BeginProjectUpdate("project-a")- firstPlan := &restartPlan{- newRef: "nginx:latest",- inspect: &container.InspectResponse{- Config: &container.Config{- Labels: map[string]string{- "com.docker.compose.project": "myproject",- "com.docker.compose.service": "web",- },- },- },- }- secondPlan := &restartPlan{- newRef: "nginx:latest",- inspect: &container.InspectResponse{- Config: &container.Config{- Labels: map[string]string{- "com.docker.compose.project": "myproject",- "com.docker.compose.service": "worker",- },- },- },- }+ status := svc.GetStatus()+ assert.Equal(t, 1, status.UpdatingContainers)+ assert.Equal(t, 1, status.UpdatingProjects)+ assert.Equal(t, []string{"container-1"}, status.ContainerIds)+ assert.Equal(t, []string{"project-a"}, status.ProjectIds)- svc.lazyRegisterComposeProjectInternal(ctx, firstPlan, projectNameToID, projectIDToObj, projectToServices, projectToSeenServices)- svc.lazyRegisterComposeProjectInternal(ctx, secondPlan, projectNameToID, projectIDToObj, projectToServices, projectToSeenServices)+ stopContainer()+ stopProject()- require.Contains(t, projectToServices, project.ID)- assert.Equal(t, []string{"web", "worker"}, projectToServices[project.ID])- assert.Equal(t, project.ID, projectNameToID[project.Name])- assert.Equal(t, project.ID, projectNameToID[loader.NormalizeProjectName(project.Name)])+ status = svc.GetStatus()+ assert.Zero(t, status.UpdatingContainers)+ assert.Zero(t, status.UpdatingProjects)+ assert.Empty(t, status.ContainerIds)+ assert.Empty(t, status.ProjectIds)}-func TestUpdaterService_RestartContainersUsingOldIDsMatchesComposeConfigImageInternal(t *testing.T) {+func TestUpdaterService_DockerClientAdapterInternal(t *testing.T) {ctx := context.Background()- db := setupProjectTestDB(t)- projectsDir := t.TempDir()- t.Setenv("PROJECTS_DIRECTORY", projectsDir)- settings, err := NewSettingsService(ctx, db)- require.NoError(t, err)- require.NoError(t, settings.SetStringSetting(ctx, "projectsDirectory", projectsDir))+ t.Run("missing docker service returns unavailable error", func(t *testing.T) {+ svc := NewUpdaterService(nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil)- projectPath := createComposeProjectDir(t, projectsDir, "compose-update-config-image")- imageRef := "registry.example.com/team/app:latest"- require.NoError(t, os.WriteFile(filepath.Join(projectPath, "compose.yaml"), []byte("services:\n app:\n image: "+imageRef+"\n"), 0o644))+ cli, err := svc.DockerClient(ctx)- projectRecord := &models.Project{- BaseModel: models.BaseModel{ID: "project-update-config-image"},- Name: "compose-update-config-image",- DirName: ptr("compose-update-config-image"),- Path: projectPath,- Status: models.ProjectStatusRunning,- }- require.NoError(t, db.Create(projectRecord).Error)-- originalComposePull := composePullProjectServicesInternal- originalComposeStop := composeStopProjectServicesInternal- originalComposeUp := composeUpProjectServicesInternal- t.Cleanup(func() {- composePullProjectServicesInternal = originalComposePull- composeStopProjectServicesInternal = originalComposeStop- composeUpProjectServicesInternal = originalComposeUp+ require.Error(t, err)+ assert.Nil(t, cli)+ assert.Contains(t, err.Error(), "docker service unavailable")})- var pulledServices []string- composePullProjectServicesInternal = func(_ context.Context, _ *composetypes.Project, services []string) error {- pulledServices = append([]string(nil), services...)- return nil- }- composeStopProjectServicesInternal = func(context.Context, *composetypes.Project, []string) error {- return nil- }- upCalled := false- composeUpProjectServicesInternal = func(_ context.Context, _ *composetypes.Project, services []string, removeOrphans bool, force bool) error {- upCalled = true- assert.Equal(t, []string{"app"}, services)- assert.False(t, removeOrphans)- assert.True(t, force)- return nil- }-- labels := map[string]string{- "com.docker.compose.project": "compose-update-config-image",- "com.docker.compose.service": "app",- }- containerID := "compose-app-1"- srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {- switch {- case strings.HasSuffix(r.URL.Path, "/containers/json"):- w.Header().Set("Content-Type", "application/json")- require.NoError(t, json.NewEncoder(w).Encode([]container.Summary{- {- ID: containerID,- Names: []string{"/compose-update-config-image-app-1"},- Image: "sha256:old-untagged",- ImageID: "sha256:old-untagged",- Labels: labels,- },- }))- case strings.Contains(r.URL.Path, "/containers/") && strings.HasSuffix(r.URL.Path, "/json"):- w.Header().Set("Content-Type", "application/json")- require.NoError(t, json.NewEncoder(w).Encode(container.InspectResponse{- ID: containerID,- Name: "/compose-update-config-image-app-1",- Image: "sha256:old-untagged",- Config: &container.Config{- Image: imageRef,- Labels: labels,- },- }))- case strings.Contains(r.URL.Path, "/images/") && strings.HasSuffix(r.URL.Path, "/json"):- encodedRef := strings.TrimSuffix(r.URL.Path[strings.LastIndex(r.URL.Path, "/images/")+len("/images/"):], "/json")- decodedRef, decodeErr := url.PathUnescape(encodedRef)- require.NoError(t, decodeErr)- require.Equal(t, imageRef, decodedRef)- w.Header().Set("Content-Type", "application/json")- require.NoError(t, json.NewEncoder(w).Encode(dockertypesimage.InspectResponse{- ID: "sha256:new-image",- RepoTags: []string{imageRef},- }))- default:- http.NotFound(w, r)- }- }))- defer srv.Close()-- dcli, err := dockerclient.NewClientWithOpts(- dockerclient.WithHost("tcp://"+srv.Listener.Addr().String()),- dockerclient.WithVersion("1.46"),- )- require.NoError(t, err)-- projectService := NewProjectService(db, settings, NewEventService(db, config.Load(), nil), nil, nil, nil, config.Load())- svc := NewUpdaterService(db, settings, &DockerClientService{client: dcli, config: &config.Config{}}, projectService, nil, nil, nil, nil, nil, nil, nil)-- results, err := svc.restartContainersUsingOldIDs(ctx, nil, map[string]string{imageRef: imageRef})-- require.NoError(t, err)- require.Len(t, results, 1)- assert.True(t, upCalled, "compose services matched by inspected config image must be recreated")- assert.Equal(t, []string{"app"}, pulledServices)- assert.Equal(t, "failed", results[0].Status)- assert.Contains(t, results[0].Error, "still running old image")- assert.NotContains(t, results[0].Error, "no matching updated image")-}--func TestPendingComposeProjectServicesInternal(t *testing.T) {- processedProjectServices := map[string]map[string]struct{}{}-- assert.Equal(t, []string{"A"}, pendingComposeProjectServicesInternal(processedProjectServices, "project-1", []string{"A"}))+ t.Run("delegates to configured docker service", func(t *testing.T) {+ server := newProjectImagePullServer(t, nil)+ wantClient := newTestDockerClient(t, server)+ dockerSvc := &DockerClientService{client: wantClient}+ svc := NewUpdaterService(nil, nil, dockerSvc, nil, nil, nil, nil, nil, nil, nil, nil)- markComposeProjectServicesProcessedInternal(processedProjectServices, "project-1", []string{"A"})- assert.Empty(t, pendingComposeProjectServicesInternal(processedProjectServices, "project-1", []string{"A"}))- assert.Equal(t, []string{"B"}, pendingComposeProjectServicesInternal(processedProjectServices, "project-1", []string{"A", "B"}))+ gotClient, err := svc.DockerClient(ctx)- markComposeProjectServicesProcessedInternal(processedProjectServices, "project-1", []string{"B"})- assert.Empty(t, pendingComposeProjectServicesInternal(processedProjectServices, "project-1", []string{"A", "B"}))-}--func TestAnyImageIDsInUseSet(t *testing.T) {- inUseSet := map[string]struct{}{- "sha256:one": {},- "sha256:two": {},- }-- assert.True(t, anyImageIDsInUseSetInternal([]string{"sha256:one"}, inUseSet))- assert.True(t, anyImageIDsInUseSetInternal([]string{"sha256:three", "sha256:two"}, inUseSet))- assert.False(t, anyImageIDsInUseSetInternal([]string{"sha256:three"}, inUseSet))- assert.False(t, anyImageIDsInUseSetInternal(nil, inUseSet))- assert.False(t, anyImageIDsInUseSetInternal([]string{"sha256:one"}, nil))-}--func TestCollectUsedImagesFromContainers_FastPathSkipsInspectLikeRefs(t *testing.T) {- out := map[string]struct{}{}-- // Simulate fast-path behavior expectations without Docker client dependency.- containers := []container.Summary{- {Image: "nginx:latest"},- {Image: "sha256:abcdef"},- {Image: "redis:7"},- {Image: "Bad/Image:latest"},- }-- for _, c := range containers {- if c.Image != "" && !libupdater.IsImageIDLikeReference(c.Image) {- addNormalizedImageUpdateRefInternal(context.Background(), out, c.Image, "test skip invalid image reference")- }- }-- assert.Contains(t, out, libupdater.NormalizeImageUpdateRef("nginx:latest"))- assert.Contains(t, out, libupdater.NormalizeImageUpdateRef("redis:7"))- assert.NotContains(t, out, libupdater.NormalizeImageUpdateRef("sha256:abcdef"))- assert.NotContains(t, out, "")-}--func mustHardwareAddr(t *testing.T, value string) network.HardwareAddr {- t.Helper()-- hw, err := net.ParseMAC(value)- require.NoError(t, err)-- return network.HardwareAddr(hw)-}--func TestBuildUpdaterRecreateNetworkingConfig(t *testing.T) {- tests := []struct {- name string- networkMode container.NetworkMode- settings *container.NetworkSettings- apiVersion string- assertions func(t *testing.T, got *network.NetworkingConfig)- }{- {- name: "skips container network mode",- networkMode: container.NetworkMode("container:db"),- apiVersion: "1.44",- settings: &container.NetworkSettings{- Networks: map[string]*network.EndpointSettings{- "custom": {Aliases: []string{"app"}},- },- },- assertions: func(t *testing.T, got *network.NetworkingConfig) {- require.Nil(t, got)- },- },- {- name: "returns nil for empty settings",- networkMode: container.NetworkMode("bridge"),- apiVersion: "1.44",- settings: &container.NetworkSettings{},- assertions: func(t *testing.T, got *network.NetworkingConfig) {- require.Nil(t, got)- },- },- {- name: "preserves recreate-safe endpoint config and strips runtime fields",- networkMode: container.NetworkMode("bridge"),- apiVersion: "1.43",- settings: &container.NetworkSettings{- Networks: map[string]*network.EndpointSettings{- "bridge": {- IPAMConfig: &network.EndpointIPAMConfig{- IPv4Address: netip.MustParseAddr("172.18.0.50"),- LinkLocalIPs: []netip.Addr{netip.MustParseAddr("169.254.10.10")},- },- Links: []string{"db:db"},- Aliases: []string{"app", "app-1"},- DriverOpts: map[string]string{"l2proxy": "true"},- GwPriority: 42,- MacAddress: mustHardwareAddr(t, "02:42:ac:11:00:02"),- IPAddress: netip.MustParseAddr("172.18.0.20"),- Gateway: netip.MustParseAddr("172.18.0.1"),- IPPrefixLen: 16,- },- "synobridge": nil,- },- },- assertions: func(t *testing.T, got *network.NetworkingConfig) {- require.NotNil(t, got)- require.Len(t, got.EndpointsConfig, 2)-- bridge := got.EndpointsConfig["bridge"]- require.NotNil(t, bridge)- require.NotNil(t, bridge.IPAMConfig)- assert.Equal(t, netip.MustParseAddr("172.18.0.50"), bridge.IPAMConfig.IPv4Address)- assert.Equal(t, []netip.Addr{netip.MustParseAddr("169.254.10.10")}, bridge.IPAMConfig.LinkLocalIPs)- assert.Equal(t, []string{"db:db"}, bridge.Links)- assert.Equal(t, []string{"app", "app-1"}, bridge.Aliases)- assert.Equal(t, map[string]string{"l2proxy": "true"}, bridge.DriverOpts)- assert.Equal(t, 42, bridge.GwPriority)- assert.Empty(t, bridge.MacAddress)- assert.False(t, bridge.IPAddress.IsValid())- assert.False(t, bridge.Gateway.IsValid())- assert.Zero(t, bridge.IPPrefixLen)-- synobridge := got.EndpointsConfig["synobridge"]- require.NotNil(t, synobridge)- assert.Empty(t, synobridge.Aliases)- },- },- {- name: "preserves network mac address when docker api supports it",- networkMode: container.NetworkMode("bridge"),- apiVersion: "1.44",- settings: &container.NetworkSettings{- Networks: map[string]*network.EndpointSettings{- "custom": {- Aliases: []string{"app"},- MacAddress: mustHardwareAddr(t, "02:42:ac:11:00:03"),- },- },- },- assertions: func(t *testing.T, got *network.NetworkingConfig) {- require.NotNil(t, got)- require.Len(t, got.EndpointsConfig, 1)-- endpoint := got.EndpointsConfig["custom"]- require.NotNil(t, endpoint)- assert.Equal(t, []string{"app"}, endpoint.Aliases)- assert.Equal(t, "02:42:ac:11:00:03", endpoint.MacAddress.String())- },- },- }-- for _, tt := range tests {- t.Run(tt.name, func(t *testing.T) {- got := buildUpdaterRecreateNetworkingConfigInternal(tt.networkMode, tt.settings, tt.apiVersion)- tt.assertions(t, got)- })- }-- t.Run("clones aliases slice", func(t *testing.T) {- settings := &container.NetworkSettings{- Networks: map[string]*network.EndpointSettings{- "custom": {- IPAMConfig: &network.EndpointIPAMConfig{- IPv4Address: netip.MustParseAddr("10.10.0.5"),- },- Links: []string{"db:db"},- Aliases: []string{"app"},- DriverOpts: map[string]string{"mode": "l2"},- },- },- }-- got := buildUpdaterRecreateNetworkingConfigInternal(container.NetworkMode("bridge"), settings, "1.44")- require.NotNil(t, got)-- got.EndpointsConfig["custom"].IPAMConfig.IPv4Address = netip.MustParseAddr("10.10.0.99")- got.EndpointsConfig["custom"].Links[0] = "cache:cache"- got.EndpointsConfig["custom"].Aliases[0] = "changed"- got.EndpointsConfig["custom"].DriverOpts["mode"] = "l3"-- require.NotNil(t, settings.Networks["custom"].IPAMConfig)- assert.Equal(t, netip.MustParseAddr("10.10.0.5"), settings.Networks["custom"].IPAMConfig.IPv4Address)- assert.Equal(t, []string{"db:db"}, settings.Networks["custom"].Links)- assert.Equal(t, []string{"app"}, settings.Networks["custom"].Aliases)- assert.Equal(t, map[string]string{"mode": "l2"}, settings.Networks["custom"].DriverOpts)+ require.NoError(t, err)+ assert.Same(t, wantClient, gotClient)})}-func setupUpdaterServiceTestDB(t *testing.T) *database.DB {- t.Helper()-- db, err := gorm.Open(glsqlite.Open(":memory:"), &gorm.Config{})- require.NoError(t, err)- require.NoError(t, db.AutoMigrate(&models.ImageUpdateRecord{}))-- return &database.DB{DB: db}-}--func TestUpdaterService_AppendAutoUpdateActivityMessageUsesExplicitStepInternal(t *testing.T) {+func TestUpdaterService_PullImageAdapterInternal(t *testing.T) {ctx := context.Background()- db := setupActivityServiceTestDBInternal(t)- activityService := NewActivityService(db)- svc := &UpdaterService{activityService: activityService}- activityID := svc.startAutoUpdateActivityInternal(ctx, false)- require.NotEmpty(t, activityID)- svc.appendAutoUpdateActivityMessageInternal(ctx, activityID, "Found 5 pending image update records", "Planning updates", 10)+ t.Run("missing image service returns unavailable error", func(t *testing.T) {+ svc := NewUpdaterService(nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil)- var activity models.Activity- require.NoError(t, db.WithContext(ctx).First(&activity, "id = ?", activityID).Error)- require.NotNil(t, activity.Progress)- assert.Equal(t, 10, *activity.Progress)- assert.Equal(t, "Found 5 pending image update records", activity.LatestMessage)- assert.Equal(t, "Planning updates", activity.Step)-}+ err := svc.PullImage(ctx, "registry.example.com/app:1.2.3", nil)-func TestUpdaterService_ClearImageUpdateRecordByID_AvoidsRepoCanonicalMismatch(t *testing.T) {- ctx := context.Background()- db := setupUpdaterServiceTestDB(t)-- record := models.ImageUpdateRecord{- ID: "sha256:old-image",- Repository: "nginx",- Tag: "latest",- HasUpdate: true,- UpdateType: models.UpdateTypeDigest,- CurrentVersion: "latest",- CheckTime: time.Now(),- }- require.NoError(t, db.WithContext(ctx).Create(&record).Error)-- svc := &UpdaterService{db: db}-- // Simulate the previous clear path that used normalized repo/tag.- require.NoError(t, svc.clearImageUpdateRecord(ctx, "docker.io/library/nginx", "latest"))-- var unchanged models.ImageUpdateRecord- require.NoError(t, db.WithContext(ctx).Where("id = ?", record.ID).First(&unchanged).Error)- assert.True(t, unchanged.HasUpdate, "repo/tag clear should not match when repository canonicalization differs")+ require.Error(t, err)+ assert.Contains(t, err.Error(), "image service unavailable")+ })- require.NoError(t, svc.clearImageUpdateRecordByID(ctx, record.ID))+ t.Run("delegates to Arcane image puller", func(t *testing.T) {+ db := setupProjectTestDB(t)+ server := newProjectImagePullServer(t, nil)+ dockerSvc := &DockerClientService{client: newTestDockerClient(t, server)}+ imageSvc := NewImageService(db, dockerSvc, nil, nil, nil, NewEventService(db, nil, nil))+ svc := NewUpdaterService(db, nil, dockerSvc, nil, nil, nil, nil, imageSvc, nil, nil, nil)+ var progress bytes.Buffer- var cleared models.ImageUpdateRecord- require.NoError(t, db.WithContext(ctx).Where("id = ?", record.ID).First(&cleared).Error)- assert.False(t, cleared.HasUpdate, "clear by image ID should always match the intended record")-}+ err := svc.PullImage(ctx, "nginx:latest", &progress)-func TestUpdaterService_CollectUsedImages_NoSourcesReturnsError(t *testing.T) {- svc := &UpdaterService{}-- used, err := svc.collectUsedImages(context.Background())- require.Error(t, err)- assert.Nil(t, used)+ require.NoError(t, err)+ assert.Contains(t, progress.String(), "Pulled")+ })}-func TestUpdaterService_ApplyPending_SkipsWhenUsedImageDiscoveryFails(t *testing.T) {+func TestUpdaterService_PendingImageUpdatesAdapterInternal(t *testing.T) {ctx := context.Background()- db := setupUpdaterServiceTestDB(t)-- record := models.ImageUpdateRecord{- ID: "sha256:pending-image",- Repository: "nginx",- Tag: "latest",+ db := setupProjectTestDB(t)+ latest := "1.2.4"+ currentDigest := "sha256:1111111111111111111111111111111111111111111111111111111111111111"+ latestDigest := "sha256:2222222222222222222222222222222222222222222222222222222222222222"+ lastError := "previous check failed"+ checkTime := time.Now().Add(-time.Hour).UTC()+ require.NoError(t, db.Create(&models.ImageUpdateRecord{+ ID: "pending",+ Repository: "registry.example.com/team/app",+ Tag: "1.2.3",HasUpdate: true,- UpdateType: models.UpdateTypeDigest,- CurrentVersion: "latest",- CheckTime: time.Now(),- }- require.NoError(t, db.WithContext(ctx).Create(&record).Error)+ UpdateType: models.UpdateTypeTag,+ CurrentVersion: "1.2.3",+ LatestVersion: &latest,+ CurrentDigest: ¤tDigest,+ LatestDigest: &latestDigest,+ CheckTime: checkTime,+ LastError: &lastError,+ }).Error)+ require.NoError(t, db.Create(&models.ImageUpdateRecord{+ ID: "not-pending",+ Repository: "registry.example.com/team/old",+ Tag: "1.0.0",+ HasUpdate: false,+ UpdateType: models.UpdateTypeDigest,+ CheckTime: checkTime,+ }).Error)+ svc := NewUpdaterService(db, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil)++ records, err := svc.PendingImageUpdates(ctx)- svc := &UpdaterService{- db: db,- dockerService: &DockerClientService{- config: &config.Config{DockerHost: "://bad-host"},- },- }-- out, err := svc.ApplyPending(ctx, false)require.NoError(t, err)- require.NotNil(t, out)- assert.Empty(t, out.Items)- assert.Zero(t, out.Checked)- assert.Zero(t, out.Updated)- assert.NotEmpty(t, out.Duration)-- var persisted models.ImageUpdateRecord- require.NoError(t, db.WithContext(ctx).Where("id = ?", record.ID).First(&persisted).Error)- assert.True(t, persisted.HasUpdate, "record should remain pending when used-image discovery fails")-}--func TestActiveComposeProjectNameSetInternal(t *testing.T) {- projects := []models.Project{- {Name: "My-App", Status: models.ProjectStatusRunning},- {Name: "skip-me", Status: models.ProjectStatusStopped},- {Name: "another_app", Status: models.ProjectStatusPartiallyRunning},- {Name: "archived-app", Status: models.ProjectStatusRunning, IsArchived: true},- {Name: "", Status: models.ProjectStatusRunning},- }-- got := activeComposeProjectNameSetInternal(projects)-- assert.Contains(t, got, "My-App")- assert.Contains(t, got, "my-app")- assert.Contains(t, got, "another_app")- assert.NotContains(t, got, "skip-me")- assert.NotContains(t, got, "archived-app")-}--func TestCollectUsedImagesFromComposeContainersInternal(t *testing.T) {- svc := &UpdaterService{}- out := map[string]struct{}{}- activeProjects := map[string]struct{}{- "myapp": {},- }-- composeContainers := []container.Summary{- {- Image: "nginx:latest",- Labels: map[string]string{- "com.docker.compose.project": "myapp",- },- },- {- Image: "redis:7",- Labels: map[string]string{- "com.docker.compose.project": "myapp",- libupdater.LabelUpdater: "false",- },- },- {- Image: "postgres:16",- Labels: map[string]string{- "com.docker.compose.project": "otherapp",- },- },- {- Image: "sha256:abcdef",- Labels: map[string]string{- "com.docker.compose.project": "myapp",- },- },- {- Image: "Bad/Image:latest",- Labels: map[string]string{- "com.docker.compose.project": "myapp",- },- },- }-- svc.collectUsedImagesFromComposeContainersInternal(context.Background(), composeContainers, activeProjects, out)+ require.Len(t, records, 1)+ assert.Equal(t, "pending", records[0].ID)+ assert.Equal(t, "registry.example.com/team/app", records[0].Repository)+ assert.Equal(t, "1.2.3", records[0].Tag)+ assert.True(t, records[0].HasUpdate)+ assert.Equal(t, moduletypes.UpdateTypeTag, records[0].UpdateType)+ assert.Equal(t, "1.2.3", records[0].CurrentVersion)+ assert.Equal(t, &latest, records[0].LatestVersion)+ assert.Equal(t, ¤tDigest, records[0].CurrentDigest)+ assert.Equal(t, &latestDigest, records[0].LatestDigest)+ assert.Equal(t, &lastError, records[0].LastError)+}++func TestUpdaterService_RecordUpdateRunAdapterInternal(t *testing.T) {+ ctx := context.Background()+ db := setupProjectTestDB(t)+ require.NoError(t, db.AutoMigrate(&models.AutoUpdateRecord{}))+ svc := NewUpdaterService(db, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil)++ err := svc.RecordUpdateRun(ctx, moduletypes.ResourceResult{+ ResourceID: "container-1",+ ResourceName: "web",+ ResourceType: moduletypes.ResourceTypeContainer,+ Status: moduletypes.StatusUpdated,+ UpdateAvailable: true,+ UpdateApplied: true,+ OldImages: map[string]string{"main": "nginx:1.2.3"},+ NewImages: map[string]string{"main": "nginx:1.2.4"},+ Details: map[string]any{"source": "test"},+ })- assert.Contains(t, out, libupdater.NormalizeImageUpdateRef("nginx:latest"))- assert.NotContains(t, out, libupdater.NormalizeImageUpdateRef("redis:7"))- assert.NotContains(t, out, libupdater.NormalizeImageUpdateRef("postgres:16"))- assert.NotContains(t, out, libupdater.NormalizeImageUpdateRef("sha256:abcdef"))- assert.NotContains(t, out, "")+ require.NoError(t, err)+ var record models.AutoUpdateRecord+ require.NoError(t, db.First(&record, "resource_id = ?", "container-1").Error)+ assert.Equal(t, "web", record.ResourceName)+ assert.Equal(t, "container", record.ResourceType)+ assert.Equal(t, models.AutoUpdateStatus(moduletypes.StatusUpdated), record.Status)+ assert.True(t, record.UpdateAvailable)+ assert.True(t, record.UpdateApplied)+ assert.Equal(t, "nginx:1.2.3", record.OldImageVersions["main"])+ assert.Equal(t, "nginx:1.2.4", record.NewImageVersions["main"])+ assert.Equal(t, "test", record.Details["source"])}func TestResolvePullableImageRefInternal(t *testing.T) {tests := []struct {- name string- summaryImage string- inspectImage string- repoTags []string- wantRef string- wantSource string+ name string+ summaryImage string+ inspectImage string+ repoTags []string+ expectedRef string+ expectedSource string}{{- name: "prefers inspect config image",- summaryImage: "portainer/portainer.ce:latest",- inspectImage: "ghcr.io/example/app:1.2.3",- wantRef: "ghcr.io/example/app:1.2.3",- wantSource: "container_inspect_config",+ name: "inspect config image wins",+ summaryImage: "nginx:latest",+ inspectImage: "registry.example.com/nginx:stable",+ expectedRef: "registry.example.com/nginx:stable",+ expectedSource: "container_inspect_config",},{- name: "falls back to summary image when inspect image is id-like",- summaryImage: "portainer/portainer.ce:latest",- inspectImage: "sha256:abcdef",- wantRef: "portainer/portainer.ce:latest",- wantSource: "container_summary",+ name: "summary image used when inspect is image ID",+ summaryImage: "redis:7",+ inspectImage: "sha256:abcdef",+ expectedRef: "redis:7",+ expectedSource: "container_summary",},{- name: "falls back to repo tag when summary and inspect are id-like",- summaryImage: "sha256:abc123",- inspectImage: "sha256:def456",- repoTags: []string{"<none>:<none>", "docker.io/library/portainer/portainer.ce:latest"},- wantRef: "docker.io/library/portainer/portainer.ce:latest",- wantSource: "image_repo_tag",+ name: "repo tag fallback skips none tag",+ summaryImage: "sha256:abcdef",+ inspectImage: "sha256:abcdef",+ repoTags: []string{"<none>:<none>", "postgres:16"},+ expectedRef: "postgres:16",+ expectedSource: "image_repo_tag",},{- name: "returns empty when only id-like candidates exist",- summaryImage: "sha256:abc123",- inspectImage: "sha256:def456",- repoTags: []string{"<none>:<none>", "sha256:fff"},- wantRef: "",- wantSource: "",+ name: "no pullable ref",+ summaryImage: "sha256:abcdef",+ inspectImage: "sha256:abcdef",+ repoTags: []string{"<none>:<none>"},},}for _, tt := range tests {t.Run(tt.name, func(t *testing.T) {- gotRef, gotSource := resolvePullableImageRefInternal(tt.summaryImage, tt.inspectImage, tt.repoTags)- assert.Equal(t, tt.wantRef, gotRef)- assert.Equal(t, tt.wantSource, gotSource)- })- }-}--func TestUpdaterService_StatusTrackingInternal(t *testing.T) {- svc := &UpdaterService{- updatingContainers: map[string]bool{},- updatingProjects: map[string]bool{},- }-- stopContainer := svc.beginContainerUpdateInternal("container-1")- stopProject := svc.beginProjectUpdateInternal("project-a")-- status := svc.GetStatus()- assert.Equal(t, 1, status.UpdatingContainers)- assert.Equal(t, 1, status.UpdatingProjects)- assert.ElementsMatch(t, []string{"container-1"}, status.ContainerIds)- assert.ElementsMatch(t, []string{"project-a"}, status.ProjectIds)-- stopContainer()- stopProject()-- status = svc.GetStatus()- assert.Zero(t, status.UpdatingContainers)- assert.Zero(t, status.UpdatingProjects)- assert.Empty(t, status.ContainerIds)- assert.Empty(t, status.ProjectIds)-}--func TestComposeProjectNameFromLabelsInternal(t *testing.T) {- assert.Equal(t, "", composeProjectNameFromLabelsInternal(nil))- assert.Equal(t, "", composeProjectNameFromLabelsInternal(map[string]string{}))- assert.Equal(t, "my-project", composeProjectNameFromLabelsInternal(map[string]string{- "com.docker.compose.project": " my-project ",- }))-}--func TestDockerProxyContainerNameInternal(t *testing.T) {- tests := []struct {- name string- dockerHost string- expected string- }{- {"empty", "", ""},- {"unix socket", "unix:///var/run/docker.sock", ""},- {"tcp with container hostname", "tcp://arcane-docker-socket-proxy:2375", "arcane-docker-socket-proxy"},- {"tcp with container hostname no port", "tcp://my-proxy", "my-proxy"},- {"tcp with ip address", "tcp://192.168.1.100:2375", ""},- {"tcp with localhost", "tcp://localhost:2375", ""},- {"tcp with fqdn", "tcp://docker.example.com:2375", ""},- {"tcp with ipv6 address", "tcp://[::1]:2375", ""},- {"tcp with ipv6 no port", "tcp://[::1]", ""},- {"tcp with spaces", " tcp://my-proxy:2375 ", "my-proxy"},- }-- for _, tt := range tests {- t.Run(tt.name, func(t *testing.T) {- assert.Equal(t, tt.expected, dockerProxyContainerNameInternal(tt.dockerHost))+ gotRef, gotSource := moduleapi.ResolvePullableImageRef(tt.summaryImage, tt.inspectImage, tt.repoTags)+ assert.Equal(t, tt.expectedRef, gotRef)+ assert.Equal(t, tt.expectedSource, gotSource)})}}--func setupUpdaterServiceSettingsDB(t *testing.T) *database.DB {- t.Helper()- db, err := gorm.Open(glsqlite.Open(":memory:"), &gorm.Config{})- require.NoError(t, err)- require.NoError(t, db.AutoMigrate(&models.SettingVariable{}))- return &database.DB{DB: db}-}--func TestUpdaterService_BuildExcludedContainerSetInternal_Empty(t *testing.T) {- ctx := context.Background()- db := setupUpdaterServiceSettingsDB(t)- settings, err := NewSettingsService(ctx, db)- require.NoError(t, err)- svc := &UpdaterService{settingsService: settings}-- excluded := svc.buildExcludedContainerSetInternal(ctx)- assert.Nil(t, excluded, "empty exclusion setting should return nil map")-}--func TestUpdaterService_BuildExcludedContainerSetInternal_ParsesList(t *testing.T) {- ctx := context.Background()- db := setupUpdaterServiceSettingsDB(t)- settings, err := NewSettingsService(ctx, db)- require.NoError(t, err)- require.NoError(t, settings.UpdateSetting(ctx, "autoUpdateExcludedContainers", "container-a, container-b , container-c"))-- svc := &UpdaterService{settingsService: settings}- excluded := svc.buildExcludedContainerSetInternal(ctx)-- assert.True(t, excluded["container-a"])- assert.True(t, excluded["container-b"])- assert.True(t, excluded["container-c"])- assert.False(t, excluded["container-d"])-}--// TestUpdaterService_CollectUsedImages_SkipsExcludedContainers verifies that images-// used ONLY by excluded containers are not included in the used-images set, so the-// auto-update job does not pull images for those containers.-func TestUpdaterService_CollectUsedImages_SkipsExcludedContainers(t *testing.T) {- ctx := context.Background()- db := setupUpdaterServiceSettingsDB(t)- settings, err := NewSettingsService(ctx, db)- require.NoError(t, err)- require.NoError(t, settings.UpdateSetting(ctx, "autoUpdateExcludedContainers", "excluded-container"))-- // Serve a fake Docker daemon that returns two containers: one excluded, one not.- fakeContainers := []container.Summary{- {ID: "c1", Names: []string{"/excluded-container"}, Image: "nginx:latest"},- {ID: "c2", Names: []string{"/active-container"}, Image: "redis:7"},- }- srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {- if strings.HasSuffix(r.URL.Path, "/containers/json") {- w.Header().Set("Content-Type", "application/json")- json.NewEncoder(w).Encode(fakeContainers)- return- }- http.NotFound(w, r)- }))- defer srv.Close()-- dcli, err := dockerclient.NewClientWithOpts(- dockerclient.WithHost("tcp://"+srv.Listener.Addr().String()),- dockerclient.WithVersion("1.46"),- )- require.NoError(t, err)-- svc := &UpdaterService{settingsService: settings}- out := map[string]struct{}{}-- require.NoError(t, svc.collectUsedImagesFromContainersInternal(ctx, dcli, out))-- assert.NotContains(t, out, libupdater.NormalizeImageUpdateRef("nginx:latest"), "excluded container image must not be collected")- assert.Contains(t, out, libupdater.NormalizeImageUpdateRef("redis:7"), "non-excluded container image must be collected")-}diff --git a/backend/internal/services/version_service.go b/backend/internal/services/version_service.goindex e164803a4..5661786d7 100644--- a/backend/internal/services/version_service.go+++ b/backend/internal/services/version_service.go@@ -15,9 +15,9 @@ import ("github.com/getarcaneapp/arcane/backend/internal/config"docker "github.com/getarcaneapp/arcane/backend/pkg/dockerutil""github.com/getarcaneapp/arcane/backend/pkg/libarcane"- libupdater "github.com/getarcaneapp/arcane/backend/pkg/libarcane/imageupdate""github.com/getarcaneapp/arcane/backend/pkg/utils/cache""github.com/getarcaneapp/arcane/types/version"+ libupdater "github.com/getarcaneapp/updater/pkg/labels"containertypes "github.com/moby/moby/api/types/container""github.com/moby/moby/client""golang.org/x/mod/semver"diff --git a/backend/internal/services/version_service_test.go b/backend/internal/services/version_service_test.goindex f80bcd858..3a767f418 100644--- a/backend/internal/services/version_service_test.go+++ b/backend/internal/services/version_service_test.go@@ -12,7 +12,7 @@ import ("time""github.com/getarcaneapp/arcane/backend/internal/models"- libupdater "github.com/getarcaneapp/arcane/backend/pkg/libarcane/imageupdate"+ libupdater "github.com/getarcaneapp/updater/pkg/labels""github.com/moby/moby/api/types/container"dockertypesimage "github.com/moby/moby/api/types/image""github.com/opencontainers/go-digest"diff --git a/backend/internal/services/vulnerability_service.go b/backend/internal/services/vulnerability_service.goindex 45fe897ef..fc59ca09e 100644--- a/backend/internal/services/vulnerability_service.go+++ b/backend/internal/services/vulnerability_service.go@@ -28,11 +28,11 @@ import (dockerutils "github.com/getarcaneapp/arcane/backend/pkg/dockerutil""github.com/getarcaneapp/arcane/backend/pkg/libarcane"activitylib "github.com/getarcaneapp/arcane/backend/pkg/libarcane/activity"- libupdater "github.com/getarcaneapp/arcane/backend/pkg/libarcane/imageupdate""github.com/getarcaneapp/arcane/backend/pkg/libarcane/timeouts""github.com/getarcaneapp/arcane/backend/pkg/pagination""github.com/getarcaneapp/arcane/backend/pkg/utils""github.com/getarcaneapp/arcane/types/vulnerability"+ libupdater "github.com/getarcaneapp/updater/pkg/labels""github.com/moby/moby/api/pkg/stdcopy"containertypes "github.com/moby/moby/api/types/container"imagetypes "github.com/moby/moby/api/types/image"diff --git a/backend/pkg/dockerutil/container_names.go b/backend/pkg/dockerutil/container_names.goindex 464b59d3d..0c344fb2d 100644--- a/backend/pkg/dockerutil/container_names.go+++ b/backend/pkg/dockerutil/container_names.go@@ -2,8 +2,6 @@ package dockerimport ("strings"-- "github.com/moby/moby/api/types/container")// ContainerNameFromNames returns Docker's first container name without the@@ -15,16 +13,3 @@ func ContainerNameFromNames(names []string) string {return strings.TrimPrefix(names[0], "/")}--// ContainerSummaryName returns a displayable container name from a Docker-// summary, falling back to the short container ID when Docker has no name.-func ContainerSummaryName(cnt container.Summary) string {- if name := ContainerNameFromNames(cnt.Names); name != "" {- return name- }-- if len(cnt.ID) >= 12 {- return cnt.ID[:12]- }- return cnt.ID-}diff --git a/backend/pkg/dockerutil/container_names_test.go b/backend/pkg/dockerutil/container_names_test.goindex 8e1ddd466..b6e854c75 100644--- a/backend/pkg/dockerutil/container_names_test.go+++ b/backend/pkg/dockerutil/container_names_test.go@@ -1,10 +1,6 @@package docker-import (- "testing"-- "github.com/moby/moby/api/types/container"-)+import "testing"func TestContainerNameFromNames(t *testing.T) {tests := []struct {@@ -42,30 +38,3 @@ func TestContainerNameFromNames(t *testing.T) {})}}--func TestContainerSummaryName(t *testing.T) {- tests := []struct {- name string- cnt container.Summary- want string- }{- {- name: "uses Docker name",- cnt: container.Summary{Names: []string{"/myapp"}, ID: "abc123456789"},- want: "myapp",- },- {- name: "falls back to short ID",- cnt: container.Summary{Names: []string{}, ID: "abc123456789"},- want: "abc123456789",- },- }-- for _, tt := range tests {- t.Run(tt.name, func(t *testing.T) {- if got := ContainerSummaryName(tt.cnt); got != tt.want {- t.Errorf("ContainerSummaryName() = %v, want %v", got, tt.want)- }- })- }-}diff --git a/backend/pkg/libarcane/imageupdate/digest.go b/backend/pkg/libarcane/imageupdate/digest.godeleted file mode 100644index 46d3cfb6d..000000000--- a/backend/pkg/libarcane/imageupdate/digest.go+++ /dev/null@@ -1,185 +0,0 @@-package imageupdate--import (- "context"- "errors"- "fmt"- "log/slog"- "strings"-- "github.com/moby/moby/client"- "github.com/opencontainers/go-digest"-)--type remoteDigestResolver interface {- GetImageDigest(ctx context.Context, imageRef string) (string, error)-}--// DigestChecker provides methods to check if an image needs updating by comparing digests-type DigestChecker struct {- dcli *client.Client- digestResolver remoteDigestResolver-}--// NewDigestChecker creates a new DigestChecker-func NewDigestChecker(dcli *client.Client, digestResolver remoteDigestResolver) *DigestChecker {- return &DigestChecker{- dcli: dcli,- digestResolver: digestResolver,- }-}--// CheckResult contains the result of a digest check-type CheckResult struct {- NeedsUpdate bool- LocalDigest string- RemoteDigest string- Error error- CheckedViaAPI bool // True if we checked via registry API, false if we had to pull-}--func NormalizeDigest(value string) (string, error) {- parsed, err := digest.Parse(strings.TrimSpace(value))- if err != nil {- return "", fmt.Errorf("invalid OCI digest %q: %w", value, err)- }-- return parsed.String(), nil-}--func DigestFromReferenceSuffix(ref string) (string, bool) {- _, digestValue, ok := strings.Cut(strings.TrimSpace(ref), "@")- if !ok {- return "", false- }-- normalized, err := NormalizeDigest(digestValue)- if err != nil {- return "", false- }-- return normalized, true-}--// CheckImageNeedsUpdate checks if an image has a newer version available without pulling-// Returns true if the remote digest differs from the local digest-func (c *DigestChecker) CheckImageNeedsUpdate(ctx context.Context, imageRef string) CheckResult {- result := CheckResult{}-- slog.DebugContext(ctx, "CheckImageNeedsUpdate: checking image",- "imageRef", imageRef,- "normalizedRef", normalizedReferenceStringInternal(imageRef))-- // Get local digest- localDigest, err := c.getLocalDigestInternal(ctx, imageRef)- if err != nil {- slog.DebugContext(ctx, "CheckImageNeedsUpdate: failed to get local digest",- "imageRef", imageRef,- "error", err)- // Image not present locally - definitely needs update- result.NeedsUpdate = true- result.Error = err- return result- }- result.LocalDigest = localDigest-- if c.digestResolver == nil {- result.Error = errors.New("remote digest resolver unavailable")- return result- }-- // Get remote digest via the Docker daemon-backed registry path.- remoteDigest, err := c.digestResolver.GetImageDigest(ctx, imageRef)- if err != nil {- slog.DebugContext(ctx, "CheckImageNeedsUpdate: failed to get remote digest",- "imageRef", imageRef,- "error", err)- // Can't determine remotely - caller should fall back to pull- result.Error = err- return result- }-- result.RemoteDigest = remoteDigest- result.CheckedViaAPI = true- result.NeedsUpdate = localDigest != remoteDigest-- slog.DebugContext(ctx, "CheckImageNeedsUpdate: digest comparison complete",- "imageRef", imageRef,- "localDigest", localDigest,- "remoteDigest", remoteDigest,- "needsUpdate", result.NeedsUpdate)-- return result-}--// getLocalDigestInternal retrieves the digest of a locally stored image-func (c *DigestChecker) getLocalDigestInternal(ctx context.Context, imageRef string) (string, error) {- inspect, err := c.dcli.ImageInspect(ctx, imageRef)- if err != nil {- return "", fmt.Errorf("image not found locally: %w", err)- }-- // Try to get digest from RepoDigests- for _, rd := range inspect.RepoDigests {- if normalized, ok := DigestFromReferenceSuffix(rd); ok {- return normalized, nil- }- }-- // Fall back to image ID (which is a content-addressed hash)- if inspect.ID != "" {- return inspect.ID, nil- }-- return "", errors.New("no digest available for image")-}--// CompareWithPulled compares the current container's image with a freshly pulled image-// This is the fallback when HEAD request doesn't work-func (c *DigestChecker) CompareWithPulled(ctx context.Context, containerImageID string, newImageRef string) (bool, error) {- // Get the new image info after pull- newInspect, err := c.dcli.ImageInspect(ctx, newImageRef)- if err != nil {- return false, fmt.Errorf("failed to inspect new image: %w", err)- }-- // Compare image IDs- return containerImageID != newInspect.ID, nil-}--// GetImageIDsForRef returns the image IDs associated with a reference-func (c *DigestChecker) GetImageIDsForRef(ctx context.Context, ref string) ([]string, error) {- // First try direct inspect- inspect, err := c.dcli.ImageInspect(ctx, ref)- if err == nil && inspect.ID != "" {- return []string{inspect.ID}, nil- }-- // Fall back to listing and filtering- imageList, err := c.dcli.ImageList(ctx, client.ImageListOptions{})- if err != nil {- return nil, err- }- images := imageList.Items-- normalizedRef := normalizedReferenceStringInternal(ref)- var ids []string- for _, img := range images {- for _, tag := range img.RepoTags {- if normalizedReferenceStringInternal(tag) == normalizedRef {- ids = append(ids, img.ID)- break- }- }- }-- return ids, nil-}--func normalizedReferenceStringInternal(imageRef string) string {- parts, err := NormalizeReference(imageRef)- if err != nil {- return ""- }- return parts.NormalizedRef-}diff --git a/backend/pkg/libarcane/imageupdate/digest_test.go b/backend/pkg/libarcane/imageupdate/digest_test.godeleted file mode 100644index f2d3a0fbf..000000000--- a/backend/pkg/libarcane/imageupdate/digest_test.go+++ /dev/null@@ -1,100 +0,0 @@-package imageupdate--import (- "testing"-- "github.com/opencontainers/go-digest"- "github.com/stretchr/testify/assert"- "github.com/stretchr/testify/require"-)--func TestNormalizeDigest(t *testing.T) {- want := digest.FromString("arcane").String()-- got, err := NormalizeDigest(" " + want + " ")- require.NoError(t, err)- assert.Equal(t, want, got)-}--func TestNormalizeDigest_InvalidDigest(t *testing.T) {- _, err := NormalizeDigest("sha256:not-a-valid-digest")- require.Error(t, err)-}--func TestDigestFromReferenceSuffix(t *testing.T) {- want := digest.FromString("arcane-reference").String()-- got, ok := DigestFromReferenceSuffix("docker.io/library/nginx@" + want)- require.True(t, ok)- assert.Equal(t, want, got)-}--func TestDigestFromReferenceSuffix_InvalidDigest(t *testing.T) {- _, ok := DigestFromReferenceSuffix("docker.io/library/nginx@sha256:bad")- assert.False(t, ok)-}--func TestParseImageRef(t *testing.T) {- redisDigest := digest.FromString("redis").String()-- tests := []struct {- name string- imageRef string- wantHost string- wantRepo string- wantTag string- }{- {- name: "docker hub official image",- imageRef: "nginx:latest",- wantHost: "docker.io",- wantRepo: "library/nginx",- wantTag: "latest",- },- {- name: "custom registry image",- imageRef: "ghcr.io/getarcaneapp/arcane:v1.2.3",- wantHost: "ghcr.io",- wantRepo: "getarcaneapp/arcane",- wantTag: "v1.2.3",- },- {- name: "digest reference defaults to latest tag",- imageRef: "docker.io/library/redis@" + redisDigest,- wantHost: "docker.io",- wantRepo: "library/redis",- wantTag: "latest",- },- {- name: "docker registry variant is normalized",- imageRef: "registry-1.docker.io/library/busybox:1.36",- wantHost: "docker.io",- wantRepo: "library/busybox",- wantTag: "1.36",- },- }-- for _, tt := range tests {- t.Run(tt.name, func(t *testing.T) {- parts, err := NormalizeReference(tt.imageRef)- assert.NoError(t, err)- assert.Equal(t, tt.wantHost, parts.RegistryHost)- assert.Equal(t, tt.wantRepo, parts.Repository)- assert.Equal(t, tt.wantTag, parts.Tag)- })- }-}--func TestNormalizeRef(t *testing.T) {- parts, err := NormalizeReference("nginx")- assert.NoError(t, err)- assert.Equal(t, "docker.io/library/nginx:latest", parts.NormalizedRef)-- parts, err = NormalizeReference("index.docker.io/library/nginx:latest")- assert.NoError(t, err)- assert.Equal(t, "docker.io/library/nginx:latest", parts.NormalizedRef)-- parts, err = NormalizeReference("ghcr.io/getarcaneapp/arcane:v1")- assert.NoError(t, err)- assert.Equal(t, "ghcr.io/getarcaneapp/arcane:v1", parts.NormalizedRef)-}diff --git a/backend/pkg/libarcane/imageupdate/labels.go b/backend/pkg/libarcane/imageupdate/labels.godeleted file mode 100644index c9e2d5609..000000000--- a/backend/pkg/libarcane/imageupdate/labels.go+++ /dev/null@@ -1,132 +0,0 @@-package imageupdate--import "strings"--const (- // LabelArcane and the constants below are the core Arcane container labels.- LabelArcane = "com.getarcaneapp.arcane" // Identifies the Arcane container itself- LabelArcaneAgent = "com.getarcaneapp.arcane.agent" // Identifies an Arcane agent container- LabelUpdater = "com.getarcaneapp.arcane.updater" // Enable/disable updates (true/false)-- // LabelSwarmServiceID and LabelSwarmServiceName identify Docker Swarm task containers.- LabelSwarmServiceID = "com.docker.swarm.service.id"- LabelSwarmServiceName = "com.docker.swarm.service.name"-- // LabelDependsOn and the constants below are update-dependency labels.- LabelDependsOn = "com.getarcaneapp.arcane.depends-on" // Comma-separated list of container names this depends on- LabelStopSignal = "com.getarcaneapp.arcane.stop-signal" // Custom stop signal (e.g., SIGINT)-)--// IsArcaneContainer checks if the container is the Arcane application itself-func IsArcaneContainer(labels map[string]string) bool {- return hasTruthyLabelInternal(labels, LabelArcane) || IsArcaneAgentContainer(labels)-}--// IsArcaneServerContainer checks if the container is the Arcane server, excluding agents.-func IsArcaneServerContainer(labels map[string]string) bool {- return hasTruthyLabelInternal(labels, LabelArcane) && !IsArcaneAgentContainer(labels)-}--// ShouldDisableArcaneServerRedeploy reports whether redeploy should be blocked for the given container.-func ShouldDisableArcaneServerRedeploy(labels map[string]string, containerID, currentContainerID string, currentErr error) bool {- if !IsArcaneServerContainer(labels) {- return false- }-- if currentErr != nil || strings.TrimSpace(currentContainerID) == "" {- // Without a runtime container ID, non-agent Arcane server labels are treated as protected.- // This prevents accidental self-redeploy, but native/CI runs can mark other Arcane servers disabled.- return true- }-- return containerIDsMatchInternal(containerID, currentContainerID)-}--// IsArcaneAgentContainer checks if the container is an Arcane agent container.-func IsArcaneAgentContainer(labels map[string]string) bool {- return hasTruthyLabelInternal(labels, LabelArcaneAgent)-}--// IsUpdateDisabled returns true if the special label is present and evaluates to false.-// Accepts false/0/no/off (case-insensitive) as "disabled". Default is enabled.-func IsUpdateDisabled(labels map[string]string) bool {- if labels == nil {- return false- }- for k, v := range labels {- if strings.EqualFold(k, LabelUpdater) {- switch strings.TrimSpace(strings.ToLower(v)) {- case "false", "0", "no", "off":- return true- default:- return false- }- }- }- return false-}--// IsSwarmTask checks if the labels identify a Docker Swarm task container.-func IsSwarmTask(labels map[string]string) bool {- return hasNonEmptyLabelInternal(labels, LabelSwarmServiceID) || hasNonEmptyLabelInternal(labels, LabelSwarmServiceName)-}--// GetStopSignal returns the custom stop signal if set, otherwise empty string-func GetStopSignal(labels map[string]string) string {- if labels == nil {- return ""- }- for k, v := range labels {- if strings.EqualFold(k, LabelStopSignal) {- return strings.TrimSpace(strings.ToUpper(v))- }- }- return ""-}--func hasTruthyLabelInternal(labels map[string]string, target string) bool {- if labels == nil {- return false- }-- for k, v := range labels {- if strings.EqualFold(k, target) && isTruthyLabelValueInternal(v) {- return true- }- }-- return false-}--func hasNonEmptyLabelInternal(labels map[string]string, target string) bool {- if labels == nil {- return false- }-- for k, v := range labels {- if strings.EqualFold(k, target) && strings.TrimSpace(v) != "" {- return true- }- }-- return false-}--func isTruthyLabelValueInternal(v string) bool {- switch strings.TrimSpace(strings.ToLower(v)) {- case "true", "1", "yes", "on":- return true- default:- return false- }-}--func containerIDsMatchInternal(a, b string) bool {- a = strings.TrimSpace(a)- b = strings.TrimSpace(b)- if a == "" || b == "" {- return false- }-- return a == b || strings.HasPrefix(a, b) || strings.HasPrefix(b, a)-}diff --git a/backend/pkg/libarcane/imageupdate/labels_test.go b/backend/pkg/libarcane/imageupdate/labels_test.godeleted file mode 100644index 2757b36e6..000000000--- a/backend/pkg/libarcane/imageupdate/labels_test.go+++ /dev/null@@ -1,447 +0,0 @@-package imageupdate--import (- "errors"- "testing"-)--func TestIsArcaneContainer(t *testing.T) {- tests := []struct {- name string- labels map[string]string- want bool- }{- {- name: "nil labels",- labels: nil,- want: false,- },- {- name: "empty labels",- labels: map[string]string{},- want: false,- },- {- name: "arcane label true",- labels: map[string]string{LabelArcane: "true"},- want: true,- },- {- name: "arcane label 1",- labels: map[string]string{LabelArcane: "1"},- want: true,- },- {- name: "arcane label yes",- labels: map[string]string{LabelArcane: "yes"},- want: true,- },- {- name: "arcane label on",- labels: map[string]string{LabelArcane: "on"},- want: true,- },- {- name: "arcane label false",- labels: map[string]string{LabelArcane: "false"},- want: false,- },- {- name: "arcane label TRUE uppercase",- labels: map[string]string{LabelArcane: "TRUE"},- want: true,- },- {- name: "arcane label with whitespace",- labels: map[string]string{LabelArcane: " true "},- want: true,- },- {- name: "case insensitive label key",- labels: map[string]string{"COM.GETARCANEAPP.ARCANE": "true"},- want: true,- },- {- name: "agent label true",- labels: map[string]string{LabelArcaneAgent: "true"},- want: true,- },- {- name: "agent label with whitespace",- labels: map[string]string{LabelArcaneAgent: " yes "},- want: true,- },- {- name: "agent label false",- labels: map[string]string{LabelArcaneAgent: "false"},- want: false,- },- }-- for _, tt := range tests {- t.Run(tt.name, func(t *testing.T) {- if got := IsArcaneContainer(tt.labels); got != tt.want {- t.Errorf("IsArcaneContainer() = %v, want %v", got, tt.want)- }- })- }-}--func TestIsArcaneAgentContainer(t *testing.T) {- tests := []struct {- name string- labels map[string]string- want bool- }{- {- name: "nil labels",- labels: nil,- want: false,- },- {- name: "agent label true",- labels: map[string]string{LabelArcaneAgent: "true"},- want: true,- },- {- name: "agent label case insensitive key",- labels: map[string]string{"COM.GETARCANEAPP.ARCANE.AGENT": "on"},- want: true,- },- {- name: "core arcane label only",- labels: map[string]string{LabelArcane: "true"},- want: false,- },- {- name: "agent label false",- labels: map[string]string{LabelArcaneAgent: "off"},- want: false,- },- }-- for _, tt := range tests {- t.Run(tt.name, func(t *testing.T) {- if got := IsArcaneAgentContainer(tt.labels); got != tt.want {- t.Errorf("IsArcaneAgentContainer() = %v, want %v", got, tt.want)- }- })- }-}--func TestIsArcaneServerContainer(t *testing.T) {- tests := []struct {- name string- labels map[string]string- want bool- }{- {- name: "nil labels",- labels: nil,- want: false,- },- {- name: "server label true",- labels: map[string]string{LabelArcane: "true"},- want: true,- },- {- name: "server label case insensitive key",- labels: map[string]string{"COM.GETARCANEAPP.ARCANE": "on"},- want: true,- },- {- name: "server label false",- labels: map[string]string{LabelArcane: "off"},- want: false,- },- {- name: "agent label only",- labels: map[string]string{LabelArcaneAgent: "true"},- want: false,- },- {- name: "agent label wins over server label",- labels: map[string]string{- LabelArcane: "true",- LabelArcaneAgent: "true",- },- want: false,- },- {- name: "false agent label does not exclude server",- labels: map[string]string{- LabelArcane: "true",- LabelArcaneAgent: "false",- },- want: true,- },- }-- for _, tt := range tests {- t.Run(tt.name, func(t *testing.T) {- if got := IsArcaneServerContainer(tt.labels); got != tt.want {- t.Errorf("IsArcaneServerContainer() = %v, want %v", got, tt.want)- }- })- }-}--func TestIsUpdateDisabled(t *testing.T) {- tests := []struct {- name string- labels map[string]string- want bool- }{- {- name: "nil labels - default enabled",- labels: nil,- want: false,- },- {- name: "empty labels - default enabled",- labels: map[string]string{},- want: false,- },- {- name: "no updater label - default enabled",- labels: map[string]string{"other": "value"},- want: false,- },- {- name: "updater label false",- labels: map[string]string{LabelUpdater: "false"},- want: true,- },- {- name: "updater label 0",- labels: map[string]string{LabelUpdater: "0"},- want: true,- },- {- name: "updater label no",- labels: map[string]string{LabelUpdater: "no"},- want: true,- },- {- name: "updater label off",- labels: map[string]string{LabelUpdater: "off"},- want: true,- },- {- name: "updater label true - enabled",- labels: map[string]string{LabelUpdater: "true"},- want: false,- },- {- name: "updater label FALSE uppercase",- labels: map[string]string{LabelUpdater: "FALSE"},- want: true,- },- {- name: "updater label with whitespace",- labels: map[string]string{LabelUpdater: " false "},- want: true,- },- {- name: "case insensitive label key",- labels: map[string]string{"COM.GETARCANEAPP.ARCANE.UPDATER": "false"},- want: true,- },- }-- for _, tt := range tests {- t.Run(tt.name, func(t *testing.T) {- if got := IsUpdateDisabled(tt.labels); got != tt.want {- t.Errorf("IsUpdateDisabled() = %v, want %v", got, tt.want)- }- })- }-}--func TestIsSwarmTask(t *testing.T) {- tests := []struct {- name string- labels map[string]string- want bool- }{- {- name: "nil labels",- labels: nil,- want: false,- },- {- name: "empty labels",- labels: map[string]string{},- want: false,- },- {- name: "unrelated labels",- labels: map[string]string{"com.example.service": "api"},- want: false,- },- {- name: "swarm service id",- labels: map[string]string{LabelSwarmServiceID: "service-id"},- want: true,- },- {- name: "swarm service name",- labels: map[string]string{LabelSwarmServiceName: "web"},- want: true,- },- {- name: "case insensitive label key",- labels: map[string]string{"COM.DOCKER.SWARM.SERVICE.ID": "service-id"},- want: true,- },- {- name: "empty swarm label value",- labels: map[string]string{LabelSwarmServiceID: " "},- want: false,- },- }-- for _, tt := range tests {- t.Run(tt.name, func(t *testing.T) {- if got := IsSwarmTask(tt.labels); got != tt.want {- t.Errorf("IsSwarmTask() = %v, want %v", got, tt.want)- }- })- }-}--func TestShouldDisableArcaneServerRedeploy(t *testing.T) {- tests := []struct {- name string- labels map[string]string- containerID string- currentContainerID string- currentErr error- want bool- }{- {- name: "current Arcane server container",- labels: map[string]string{LabelArcane: "true"},- containerID: "abcdef1234567890",- currentContainerID: "abcdef1234567890",- want: true,- },- {- name: "current Arcane server container with short detected ID",- labels: map[string]string{LabelArcane: "true"},- containerID: "abcdef1234567890",- currentContainerID: "abcdef123456",- want: true,- },- {- name: "different Arcane server container",- labels: map[string]string{LabelArcane: "true"},- containerID: "abcdef1234567890",- currentContainerID: "123456abcdef7890",- want: false,- },- {- name: "fail closed when current container cannot be detected",- labels: map[string]string{LabelArcane: "true"},- containerID: "abcdef1234567890",- currentErr: errors.New("not in docker"),- want: true,- },- {- name: "agent container remains redeployable",- labels: map[string]string{LabelArcaneAgent: "true"},- containerID: "abcdef1234567890",- currentContainerID: "abcdef1234567890",- want: false,- },- {- name: "agent label excludes Arcane server label",- labels: map[string]string{- LabelArcane: "true",- LabelArcaneAgent: "true",- },- containerID: "abcdef1234567890",- currentContainerID: "abcdef1234567890",- want: false,- },- {- name: "non-Arcane container",- labels: map[string]string{"app": "demo"},- containerID: "abcdef1234567890",- currentContainerID: "abcdef1234567890",- want: false,- },- }-- for _, tt := range tests {- t.Run(tt.name, func(t *testing.T) {- got := ShouldDisableArcaneServerRedeploy(tt.labels, tt.containerID, tt.currentContainerID, tt.currentErr)- if got != tt.want {- t.Errorf("ShouldDisableArcaneServerRedeploy() = %v, want %v", got, tt.want)- }- })- }-}--func TestGetStopSignal(t *testing.T) {- tests := []struct {- name string- labels map[string]string- want string- }{- {- name: "nil labels",- labels: nil,- want: "",- },- {- name: "empty labels",- labels: map[string]string{},- want: "",- },- {- name: "no stop signal label",- labels: map[string]string{"other": "value"},- want: "",- },- {- name: "SIGTERM",- labels: map[string]string{LabelStopSignal: "SIGTERM"},- want: "SIGTERM",- },- {- name: "SIGINT",- labels: map[string]string{LabelStopSignal: "SIGINT"},- want: "SIGINT",- },- {- name: "SIGKILL",- labels: map[string]string{LabelStopSignal: "SIGKILL"},- want: "SIGKILL",- },- {- name: "lowercase signal",- labels: map[string]string{LabelStopSignal: "sigterm"},- want: "SIGTERM",- },- {- name: "signal with whitespace",- labels: map[string]string{LabelStopSignal: " SIGTERM "},- want: "SIGTERM",- },- {- name: "case insensitive label key",- labels: map[string]string{"COM.GETARCANEAPP.ARCANE.STOP-SIGNAL": "SIGINT"},- want: "SIGINT",- },- }-- for _, tt := range tests {- t.Run(tt.name, func(t *testing.T) {- if got := GetStopSignal(tt.labels); got != tt.want {- t.Errorf("GetStopSignal() = %v, want %v", got, tt.want)- }- })- }-}diff --git a/backend/pkg/libarcane/imageupdate/logfile.go b/backend/pkg/libarcane/imageupdate/logfile.godeleted file mode 100644index 7d322f58a..000000000--- a/backend/pkg/libarcane/imageupdate/logfile.go+++ /dev/null@@ -1,165 +0,0 @@-package imageupdate--import (- "context"- "errors"- "fmt"- "io"- "log/slog"- "os"- "path/filepath"- "strconv"- "strings"- "sync"- "time"-)--type messageOnlyHandler struct {- mu *sync.Mutex- w io.Writer- minLevel slog.Level- attrs []slog.Attr- groups []string-}--func newMessageOnlyHandlerInternal(w io.Writer, minLevel slog.Level) *messageOnlyHandler {- return &messageOnlyHandler{mu: &sync.Mutex{}, w: w, minLevel: minLevel}-}--func (h *messageOnlyHandler) Enabled(_ context.Context, level slog.Level) bool {- return level >= h.minLevel-}--func (h *messageOnlyHandler) Handle(_ context.Context, r slog.Record) error {- if h.mu != nil {- h.mu.Lock()- defer h.mu.Unlock()- }-- line := r.Message- appendAttr := func(a slog.Attr) {- if a.Equal(slog.Attr{}) {- return- }- key := a.Key- if len(h.groups) > 0 {- key = strings.Join(h.groups, ".") + "." + key- }- line += " " + key + "=" + formatSlogValueInternal(a.Value)- }-- for _, a := range h.attrs {- appendAttr(a)- }-- r.Attrs(func(a slog.Attr) bool {- if a.Value.Kind() == slog.KindGroup {- g := a.Value.Group()- prev := h.groups- if a.Key != "" {- h.groups = append(h.groups, a.Key)- }- for _, ga := range g {- appendAttr(ga)- }- h.groups = prev- return true- }- appendAttr(a)- return true- })-- _, err := fmt.Fprintln(h.w, strings.TrimSpace(line))- return err-}--func (h *messageOnlyHandler) WithAttrs(attrs []slog.Attr) slog.Handler {- return &messageOnlyHandler{- mu: h.mu,- w: h.w,- minLevel: h.minLevel,- attrs: append(append([]slog.Attr{}, h.attrs...), attrs...),- groups: append([]string{}, h.groups...),- }-}--func (h *messageOnlyHandler) WithGroup(name string) slog.Handler {- groups := append([]string{}, h.groups...)- if strings.TrimSpace(name) != "" {- groups = append(groups, name)- }- return &messageOnlyHandler{- mu: h.mu,- w: h.w,- minLevel: h.minLevel,- attrs: append([]slog.Attr{}, h.attrs...),- groups: groups,- }-}--func formatSlogValueInternal(v slog.Value) string {- switch v.Kind() {- case slog.KindAny:- return strconv.Quote(fmt.Sprint(v.Any()))- case slog.KindString:- return strconv.Quote(v.String())- case slog.KindInt64:- return strconv.FormatInt(v.Int64(), 10)- case slog.KindUint64:- return strconv.FormatUint(v.Uint64(), 10)- case slog.KindFloat64:- return strconv.FormatFloat(v.Float64(), 'f', -1, 64)- case slog.KindTime:- return strconv.Quote(v.Time().Format(time.RFC3339Nano))- case slog.KindDuration:- return strconv.Quote(v.Duration().String())- case slog.KindBool:- if v.Bool() {- return "true"- }- return "false"- case slog.KindGroup:- // Groups are typically flattened earlier in Handle(), but handle defensively.- return strconv.Quote(fmt.Sprint(v.Group()))- case slog.KindLogValuer:- return formatSlogValueInternal(v.Resolve())- default:- return strconv.Quote(fmt.Sprint(v.Any()))- }-}--// SetupMessageOnlyLogFile configures slog to write structured logs to stdout and a-// message-only format to a file under dataDir.-//-// The file format is: <msg> key=value ... (no time/level/source) to keep-// upgrade logs concise for end users.-func SetupMessageOnlyLogFile(dataDir string, filePrefix string, minLevel slog.Level) (*os.File, error) {- if strings.TrimSpace(dataDir) == "" {- return nil, errors.New("dataDir is required")- }- if strings.TrimSpace(filePrefix) == "" {- filePrefix = "arcane-upgrade"- }-- if err := os.MkdirAll(dataDir, 0o755); err != nil {- return nil, fmt.Errorf("failed to create data directory: %w", err)- }-- logFileName := fmt.Sprintf("%s-%d.log", filePrefix, time.Now().Unix())- logFilePath := filepath.Join(dataDir, logFileName)-- logFile, err := os.OpenFile(logFilePath, os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0o644)- if err != nil {- return nil, fmt.Errorf("failed to open log file: %w", err)- }-- stdoutHandler := slog.NewTextHandler(os.Stdout, &slog.HandlerOptions{- Level: minLevel,- AddSource: true,- })- fileHandler := newMessageOnlyHandlerInternal(logFile, minLevel)-- slog.SetDefault(slog.New(slog.NewMultiHandler(stdoutHandler, fileHandler)))-- return logFile, nil-}diff --git a/backend/pkg/libarcane/imageupdate/logfile_test.go b/backend/pkg/libarcane/imageupdate/logfile_test.godeleted file mode 100644index dc60f472b..000000000--- a/backend/pkg/libarcane/imageupdate/logfile_test.go+++ /dev/null@@ -1,403 +0,0 @@-package imageupdate--import (- "bytes"- "context"- "log/slog"- "strings"- "testing"- "time"-)--func TestMessageOnlyHandler_Handle(t *testing.T) {- tests := []struct {- name string- level slog.Level- message string- attrs []slog.Attr- want string- }{- {- name: "info message only",- level: slog.LevelInfo,- message: "Test message",- attrs: []slog.Attr{},- want: "Test message",- },- {- name: "debug message",- level: slog.LevelDebug,- message: "Debug info",- attrs: []slog.Attr{},- want: "Debug info",- },- {- name: "error message",- level: slog.LevelError,- message: "Error occurred",- attrs: []slog.Attr{},- want: "Error occurred",- },- {- name: "message with string attribute",- level: slog.LevelInfo,- message: "Processing",- attrs: []slog.Attr{slog.String("key", "value")},- want: "Processing key=\"value\"",- },- {- name: "message with int attribute",- level: slog.LevelInfo,- message: "Count",- attrs: []slog.Attr{slog.Int("count", 42)},- want: "Count count=42",- },- }-- for _, tt := range tests {- t.Run(tt.name, func(t *testing.T) {- var buf bytes.Buffer- handler := newMessageOnlyHandlerInternal(&buf, slog.LevelDebug)-- record := slog.NewRecord(time.Now(), tt.level, tt.message, 0)- for _, attr := range tt.attrs {- record.AddAttrs(attr)- }-- if err := handler.Handle(context.Background(), record); err != nil {- t.Errorf("Handle() error = %v", err)- return- }-- got := strings.TrimSpace(buf.String())- if got != tt.want {- t.Errorf("Handle() output = %q, want %q", got, tt.want)- }- })- }-}--func TestMessageOnlyHandler_Enabled(t *testing.T) {- tests := []struct {- name string- minLevel slog.Level- level slog.Level- want bool- }{- {- name: "info enabled at debug level",- minLevel: slog.LevelDebug,- level: slog.LevelInfo,- want: true,- },- {- name: "debug disabled at info level",- minLevel: slog.LevelInfo,- level: slog.LevelDebug,- want: false,- },- {- name: "error enabled at info level",- minLevel: slog.LevelInfo,- level: slog.LevelError,- want: true,- },- {- name: "warn enabled at warn level",- minLevel: slog.LevelWarn,- level: slog.LevelWarn,- want: true,- },- }-- for _, tt := range tests {- t.Run(tt.name, func(t *testing.T) {- var buf bytes.Buffer- handler := newMessageOnlyHandlerInternal(&buf, tt.minLevel)-- if got := handler.Enabled(context.Background(), tt.level); got != tt.want {- t.Errorf("Enabled() = %v, want %v", got, tt.want)- }- })- }-}--func TestMessageOnlyHandler_WithAttrs(t *testing.T) {- var buf bytes.Buffer- handler := newMessageOnlyHandlerInternal(&buf, slog.LevelInfo)-- attrs := []slog.Attr{- slog.String("key1", "value1"),- slog.Int("key2", 42),- }-- newHandler := handler.WithAttrs(attrs)- if newHandler == nil {- t.Error("WithAttrs() returned nil")- }-- // Should return same handler type- if _, ok := newHandler.(*messageOnlyHandler); !ok {- t.Error("WithAttrs() did not return messageOnlyHandler")- }-- // Test that attrs are included in output- record := slog.NewRecord(time.Now(), slog.LevelInfo, "Test", 0)- if err := newHandler.Handle(context.Background(), record); err != nil {- t.Errorf("Handle() error = %v", err)- }-- output := buf.String()- if !strings.Contains(output, "key1") || !strings.Contains(output, "key2") {- t.Errorf("WithAttrs() output missing attributes: %q", output)- }-}--func TestMessageOnlyHandler_WithGroup(t *testing.T) {- var buf bytes.Buffer- handler := newMessageOnlyHandlerInternal(&buf, slog.LevelInfo)-- newHandler := handler.WithGroup("testgroup")- if newHandler == nil {- t.Error("WithGroup() returned nil")- }-- // Should return same handler type- if _, ok := newHandler.(*messageOnlyHandler); !ok {- t.Error("WithGroup() did not return messageOnlyHandler")- }-- // Test that group is used in output- record := slog.NewRecord(time.Now(), slog.LevelInfo, "Test", 0)- record.AddAttrs(slog.String("key", "value"))- if err := newHandler.Handle(context.Background(), record); err != nil {- t.Errorf("Handle() error = %v", err)- }-- output := buf.String()- if !strings.Contains(output, "testgroup") {- t.Errorf("WithGroup() output missing group name: %q", output)- }-}--func TestFormatSlogValue(t *testing.T) {- tests := []struct {- name string- value slog.Value- want string- }{- {- name: "string value",- value: slog.StringValue("test"),- want: "\"test\"",- },- {- name: "int value",- value: slog.Int64Value(42),- want: "42",- },- {- name: "bool value true",- value: slog.BoolValue(true),- want: "true",- },- {- name: "bool value false",- value: slog.BoolValue(false),- want: "false",- },- {- name: "float value",- value: slog.Float64Value(3.14),- want: "3.14",- },- {- name: "uint value",- value: slog.Uint64Value(100),- want: "100",- },- }-- for _, tt := range tests {- t.Run(tt.name, func(t *testing.T) {- got := formatSlogValueInternal(tt.value)- if got != tt.want {- t.Errorf("formatSlogValueInternal() = %v, want %v", got, tt.want)- }- })- }-}--func TestFormatSlogValue_Time(t *testing.T) {- now := time.Date(2024, 1, 1, 12, 0, 0, 0, time.UTC)- value := slog.TimeValue(now)-- got := formatSlogValueInternal(value)-- // Should be quoted and contain the date- if !strings.HasPrefix(got, "\"") || !strings.HasSuffix(got, "\"") {- t.Errorf("formatSlogValueInternal(time) should be quoted, got %q", got)- }- if !strings.Contains(got, "2024") {- t.Errorf("formatSlogValueInternal(time) should contain year, got %q", got)- }-}--func TestFormatSlogValue_Duration(t *testing.T) {- value := slog.DurationValue(5 * time.Second)- got := formatSlogValueInternal(value)-- // Should be quoted and contain duration string- if !strings.HasPrefix(got, "\"") || !strings.HasSuffix(got, "\"") {- t.Errorf("formatSlogValueInternal(duration) should be quoted, got %q", got)- }- if !strings.Contains(got, "5s") {- t.Errorf("formatSlogValueInternal(duration) should contain duration, got %q", got)- }-}--func TestMultiHandler_Enabled(t *testing.T) {- var buf1, buf2 bytes.Buffer- handler1 := newMessageOnlyHandlerInternal(&buf1, slog.LevelInfo)- handler2 := newMessageOnlyHandlerInternal(&buf2, slog.LevelWarn)-- multi := slog.NewMultiHandler(handler1, handler2)-- tests := []struct {- name string- level slog.Level- want bool- }{- {- name: "debug - neither enabled",- level: slog.LevelDebug,- want: false,- },- {- name: "info - first enabled",- level: slog.LevelInfo,- want: true,- },- {- name: "warn - both enabled",- level: slog.LevelWarn,- want: true,- },- {- name: "error - both enabled",- level: slog.LevelError,- want: true,- },- }-- for _, tt := range tests {- t.Run(tt.name, func(t *testing.T) {- if got := multi.Enabled(context.Background(), tt.level); got != tt.want {- t.Errorf("Enabled() = %v, want %v", got, tt.want)- }- })- }-}--func TestMultiHandler_Handle(t *testing.T) {- var buf1, buf2 bytes.Buffer- handler1 := newMessageOnlyHandlerInternal(&buf1, slog.LevelInfo)- handler2 := newMessageOnlyHandlerInternal(&buf2, slog.LevelInfo)-- multi := slog.NewMultiHandler(handler1, handler2)-- record := slog.NewRecord(time.Now(), slog.LevelInfo, "Test message", 0)- if err := multi.Handle(context.Background(), record); err != nil {- t.Errorf("Handle() error = %v", err)- }-- // Both handlers should have received the message- if !strings.Contains(buf1.String(), "Test message") {- t.Error("multi handler did not write to first handler")- }- if !strings.Contains(buf2.String(), "Test message") {- t.Error("multi handler did not write to second handler")- }-}--func TestMultiHandler_WithAttrs(t *testing.T) {- var buf1, buf2 bytes.Buffer- handler1 := newMessageOnlyHandlerInternal(&buf1, slog.LevelInfo)- handler2 := newMessageOnlyHandlerInternal(&buf2, slog.LevelInfo)-- multi := slog.NewMultiHandler(handler1, handler2)-- attrs := []slog.Attr{slog.String("key", "value")}- withAttrs := multi.WithAttrs(attrs)-- record := slog.NewRecord(time.Now(), slog.LevelInfo, "Test", 0)- if err := withAttrs.Handle(context.Background(), record); err != nil {- t.Errorf("Handle() error = %v", err)- }- if !strings.Contains(buf1.String(), "key=\"value\"") {- t.Errorf("WithAttrs() missing attr in first handler output: %q", buf1.String())- }- if !strings.Contains(buf2.String(), "key=\"value\"") {- t.Errorf("WithAttrs() missing attr in second handler output: %q", buf2.String())- }-}--func TestMultiHandler_WithGroup(t *testing.T) {- var buf1, buf2 bytes.Buffer- handler1 := newMessageOnlyHandlerInternal(&buf1, slog.LevelInfo)- handler2 := newMessageOnlyHandlerInternal(&buf2, slog.LevelInfo)-- multi := slog.NewMultiHandler(handler1, handler2)-- withGroup := multi.WithGroup("testgroup")-- record := slog.NewRecord(time.Now(), slog.LevelInfo, "Test", 0)- record.AddAttrs(slog.String("key", "value"))- if err := withGroup.Handle(context.Background(), record); err != nil {- t.Errorf("Handle() error = %v", err)- }- if !strings.Contains(buf1.String(), "testgroup.key=\"value\"") {- t.Errorf("WithGroup() missing grouped attr in first handler output: %q", buf1.String())- }- if !strings.Contains(buf2.String(), "testgroup.key=\"value\"") {- t.Errorf("WithGroup() missing grouped attr in second handler output: %q", buf2.String())- }-}--func TestNewMessageOnlyHandler(t *testing.T) {- var buf bytes.Buffer- handler := newMessageOnlyHandlerInternal(&buf, slog.LevelInfo)-- if handler.minLevel != slog.LevelInfo {- t.Errorf("newMessageOnlyHandlerInternal() minLevel = %v, want %v", handler.minLevel, slog.LevelInfo)- }-- if handler.mu == nil {- t.Error("newMessageOnlyHandlerInternal() did not initialize mutex")- }-}--func TestMessageOnlyHandler_MultipleMessages(t *testing.T) {- var buf bytes.Buffer- handler := newMessageOnlyHandlerInternal(&buf, slog.LevelInfo)-- messages := []string{- "First message",- "Second message",- "Third message",- }-- for _, msg := range messages {- record := slog.NewRecord(time.Now(), slog.LevelInfo, msg, 0)- if err := handler.Handle(context.Background(), record); err != nil {- t.Errorf("Handle() error = %v", err)- }- }-- output := buf.String()- for _, msg := range messages {- if !strings.Contains(output, msg) {- t.Errorf("Output missing message %q", msg)- }- }-}diff --git a/backend/pkg/libarcane/imageupdate/matching.go b/backend/pkg/libarcane/imageupdate/matching.godeleted file mode 100644index 0a7eb19ff..000000000--- a/backend/pkg/libarcane/imageupdate/matching.go+++ /dev/null@@ -1,158 +0,0 @@-package imageupdate--import (- "context"- "fmt"- "slices"- "strings"-- "github.com/moby/moby/api/types/container"- "github.com/moby/moby/client"-- dockerutil "github.com/getarcaneapp/arcane/backend/pkg/dockerutil"- "github.com/getarcaneapp/arcane/backend/pkg/libarcane"-)--// NormalizeImageUpdateRef returns the canonical image reference key used for update matching.-func NormalizeImageUpdateRef(imageRef string) string {- parts, err := NormalizeReference(imageRef)- if err != nil {- return ""- }- return parts.NormalizedRef-}--// IsImageIDLikeReference reports whether ref is a Docker image ID rather than a pullable tag.-func IsImageIDLikeReference(ref string) bool {- ref = strings.ToLower(strings.TrimSpace(ref))- return strings.HasPrefix(ref, "sha256:")-}--// AppendImageUpdateRecordIDToOldIDs includes SHA-like update record IDs in the old-image match set.-func AppendImageUpdateRecordIDToOldIDs(oldIDs []string, recordID string) []string {- recordID = strings.TrimSpace(recordID)- if !IsImageIDLikeReference(recordID) {- return oldIDs- }- if slices.Contains(oldIDs, recordID) {- return oldIDs- }- return append(oldIDs, recordID)-}--// ResolveContainerImageMatch finds the new image reference for a running container.-func ResolveContainerImageMatch(c container.Summary, inspect *container.InspectResponse, oldIDToNewRef map[string]string, updatedNorm map[string]string) (newRef, match string) {- if c.ImageID != "" {- if nr, ok := oldIDToNewRef[c.ImageID]; ok {- return nr, c.ImageID- }- }- if inspect != nil && inspect.Image != "" {- if nr, ok := oldIDToNewRef[inspect.Image]; ok {- return nr, inspect.Image- }- }-- if newRef, match := resolveImageRefMatchInternal(c.Image, updatedNorm); newRef != "" {- return newRef, match- }-- if inspect != nil && inspect.Config != nil {- if newRef, match := resolveImageRefMatchInternal(inspect.Config.Image, updatedNorm); newRef != "" {- return newRef, match- }- }-- if inspect != nil {- if newRef, match := resolveImageRefMatchInternal(inspect.Image, updatedNorm); newRef != "" {- return newRef, match- }- }-- return "", ""-}--// ShouldInspectUnmatchedContainerForImageMatch reports whether inspect may recover a tag match.-func ShouldInspectUnmatchedContainerForImageMatch(c container.Summary) bool {- imageRef := strings.TrimSpace(c.Image)- if imageRef == "" || IsImageIDLikeReference(imageRef) {- return true- }-- // A plain named reference (e.g. nginx:1.25) is already matchable, so inspect- // cannot recover anything new. Only when the summary image is digest-pinned- // (name@sha256:...) is the tag lost; for compose-managed containers the- // original tag often survives in the container config, so fall back to an- // inspect in that case alone instead of for every compose container.- if _, isDigestRef := DigestFromReferenceSuffix(imageRef); !isDigestRef {- return false- }-- return dockerutil.ComposeProjectLabel(c.Labels) != "" || dockerutil.ComposeServiceLabel(c.Labels) != ""-}--// CurrentContainerImageID returns the best available image ID for a container summary and optional inspect.-func CurrentContainerImageID(c container.Summary, inspect *container.InspectResponse) string {- if imageID := strings.TrimSpace(c.ImageID); imageID != "" {- return imageID- }- if inspect != nil {- return strings.TrimSpace(inspect.Image)- }- return ""-}--// VerifyComposeServiceUpdatedImage verifies that a compose service is no longer running oldImageID.-func VerifyComposeServiceUpdatedImage(ctx context.Context, dcli *client.Client, projectName, serviceName, oldImageID string) error {- projectName = strings.TrimSpace(projectName)- serviceName = strings.TrimSpace(serviceName)- oldImageID = strings.TrimSpace(oldImageID)- if dcli == nil || projectName == "" || serviceName == "" || oldImageID == "" {- return nil- }-- filters := make(client.Filters)- filters = filters.Add("label", dockerutil.ComposeProjectLabelKey+"="+projectName)- filters = filters.Add("label", dockerutil.ComposeServiceLabelKey+"="+serviceName)-- listResult, err := dcli.ContainerList(ctx, client.ContainerListOptions{All: false, Filters: filters})- if err != nil {- return fmt.Errorf("verify compose service image: list containers: %w", err)- }- if len(listResult.Items) == 0 {- return fmt.Errorf("compose service %s/%s has no running container after update", projectName, serviceName)- }-- for _, c := range listResult.Items {- currentImageID := strings.TrimSpace(c.ImageID)- if currentImageID == "" {- inspectResult, inspectErr := libarcane.ContainerInspectWithCompatibility(ctx, dcli, c.ID, client.ContainerInspectOptions{})- if inspectErr != nil {- return fmt.Errorf("verify compose service image: inspect container %s: %w", c.ID, inspectErr)- }- currentImageID = strings.TrimSpace(inspectResult.Container.Image)- }- if currentImageID == oldImageID {- return fmt.Errorf("compose service %s/%s still running old image %s after update", projectName, serviceName, oldImageID)- }- }-- return nil-}--func resolveImageRefMatchInternal(imageRef string, updatedNorm map[string]string) (newRef, match string) {- imageRef = strings.TrimSpace(imageRef)- if imageRef == "" || IsImageIDLikeReference(imageRef) {- return "", ""- }-- norm := NormalizeImageUpdateRef(imageRef)- if norm == "" {- return "", ""- }- if nr, ok := updatedNorm[norm]; ok {- return nr, norm- }-- return "", ""-}diff --git a/backend/pkg/libarcane/imageupdate/matching_test.go b/backend/pkg/libarcane/imageupdate/matching_test.godeleted file mode 100644index 71f709a0f..000000000--- a/backend/pkg/libarcane/imageupdate/matching_test.go+++ /dev/null@@ -1,163 +0,0 @@-package imageupdate--import (- "strings"- "testing"-- "github.com/moby/moby/api/types/container"- "github.com/stretchr/testify/assert"-- dockerutil "github.com/getarcaneapp/arcane/backend/pkg/dockerutil"-)--func TestAppendImageUpdateRecordIDToOldIDs(t *testing.T) {- tests := []struct {- name string- oldIDs []string- recordID string- want []string- }{- {- name: "appends image update record id when it is an image id",- oldIDs: nil,- recordID: "sha256:old-image",- want: []string{"sha256:old-image"},- },- {- name: "does not duplicate existing image id",- oldIDs: []string{"sha256:old-image"},- recordID: "sha256:old-image",- want: []string{"sha256:old-image"},- },- {- name: "ignores synthetic ref record ids",- oldIDs: []string{"sha256:old-image"},- recordID: "ref::registry.example.com/team/app@latest",- want: []string{"sha256:old-image"},- },- {- name: "ignores empty record ids",- oldIDs: []string{"sha256:old-image"},- recordID: " ",- want: []string{"sha256:old-image"},- },- }-- for _, tt := range tests {- t.Run(tt.name, func(t *testing.T) {- got := AppendImageUpdateRecordIDToOldIDs(tt.oldIDs, tt.recordID)- assert.Equal(t, tt.want, got)- })- }-}--func TestIsImageIDLikeReference(t *testing.T) {- assert.True(t, IsImageIDLikeReference("sha256:abcdef"))- assert.True(t, IsImageIDLikeReference("SHA256:ABCDEF"))- assert.False(t, IsImageIDLikeReference("nginx:latest"))- assert.False(t, IsImageIDLikeReference("docker.io/library/nginx:latest"))-}--func TestShouldInspectUnmatchedContainerForImageMatch(t *testing.T) {- composeLabels := map[string]string{- dockerutil.ComposeProjectLabelKey: "myproj",- dockerutil.ComposeServiceLabelKey: "web",- }-- // Empty or image-ID-like summary values always need an inspect to recover a tag.- assert.True(t, ShouldInspectUnmatchedContainerForImageMatch(container.Summary{Image: ""}))- assert.True(t, ShouldInspectUnmatchedContainerForImageMatch(container.Summary{Image: "sha256:abcdef"}))-- // A plain named reference is already matchable: no inspect even with compose labels.- assert.False(t, ShouldInspectUnmatchedContainerForImageMatch(container.Summary{Image: "nginx:1.25", Labels: composeLabels}))-- // A digest-pinned compose container loses its tag, so fall back to an inspect.- digestRef := "nginx@sha256:" + strings.Repeat("a", 64)- assert.True(t, ShouldInspectUnmatchedContainerForImageMatch(container.Summary{Image: digestRef, Labels: composeLabels}))-- // A digest-pinned container without compose labels has no tag to recover.- assert.False(t, ShouldInspectUnmatchedContainerForImageMatch(container.Summary{Image: digestRef}))-}--func TestResolveContainerImageMatch(t *testing.T) {- updatedNorm := map[string]string{- NormalizeImageUpdateRef("nginx:latest"): "nginx:latest",- }- oldIDToNewRef := map[string]string{- "sha256:img1": "redis:7",- }-- tests := []struct {- name string- container container.Summary- inspect *container.InspectResponse- updatedNorm map[string]string- wantRef string- wantMatchID string- }{- {- name: "match by image id",- container: container.Summary{- ImageID: "sha256:img1",- Image: "some/other:tag",- },- wantRef: "redis:7",- wantMatchID: "sha256:img1",- },- {- name: "match by normalized image tag from summary",- container: container.Summary{- ImageID: "sha256:unknown",- Image: "docker.io/library/nginx:latest",- },- wantRef: "nginx:latest",- wantMatchID: NormalizeImageUpdateRef("nginx:latest"),- },- {- name: "match by inspected config image when summary is image id-like",- container: container.Summary{- ImageID: "sha256:unknown",- Image: "sha256:abcdef",- },- inspect: &container.InspectResponse{- Image: "sha256:unknown",- Config: &container.Config{- Image: "docker.io/library/nginx:latest",- },- },- wantRef: "nginx:latest",- wantMatchID: NormalizeImageUpdateRef("nginx:latest"),- },- {- name: "image id-like summary value cannot be tag matched",- container: container.Summary{- ImageID: "sha256:unknown",- Image: "sha256:abcdef",- },- wantRef: "",- wantMatchID: "",- },- {- name: "invalid image reference does not match empty normalized key",- container: container.Summary{- ImageID: "sha256:unknown",- Image: "Bad/Image:latest",- },- updatedNorm: map[string]string{"": "wrong:latest"},- wantRef: "",- wantMatchID: "",- },- }-- for _, tt := range tests {- t.Run(tt.name, func(t *testing.T) {- localUpdatedNorm := updatedNorm- if tt.updatedNorm != nil {- localUpdatedNorm = tt.updatedNorm- }- gotRef, gotMatch := ResolveContainerImageMatch(tt.container, tt.inspect, oldIDToNewRef, localUpdatedNorm)- assert.Equal(t, tt.wantRef, gotRef)- assert.Equal(t, tt.wantMatchID, gotMatch)- })- }-}diff --git a/backend/pkg/libarcane/imageupdate/registry_http.go b/backend/pkg/libarcane/imageupdate/registry_http.godeleted file mode 100644index 8414c2587..000000000--- a/backend/pkg/libarcane/imageupdate/registry_http.go+++ /dev/null@@ -1,623 +0,0 @@-package imageupdate--import (- "context"- "encoding/base64"- "encoding/json"- "errors"- "fmt"- "net"- "net/http"- "net/url"- "strconv"- "strings"- "time"-- ref "github.com/distribution/reference"- "github.com/getarcaneapp/arcane/backend/pkg/libarcane/registryauth"-)--const defaultRegistryHost = "registry-1.docker.io"--// trustedAuthDelegations maps registry hosts to their trusted external auth realm hosts.-// Some registries serve images under their own domain but delegate token auth to a-// separate host (e.g. lscr.io delegates to ghcr.io).-var trustedAuthDelegations = map[string]string{- "docker.io": "auth.docker.io",- "lscr.io": "ghcr.io",- "registry.gitlab.com": "gitlab.com",-}--type Credentials struct {- Username string- Token string-}--// RateLimitInfo contains pull quota information returned by registry headers.-type RateLimitInfo struct {- Limit *int `json:"limit,omitempty"`- Remaining *int `json:"remaining,omitempty"`- Used *int `json:"used,omitempty"`- WindowSeconds *int `json:"windowSeconds,omitempty"`- Source string `json:"source,omitempty"`-}--type Reference struct {- NormalizedRef string- RegistryHost string- Repository string- Tag string-}--func NormalizeReference(imageRef string) (*Reference, error) {- trimmed := strings.TrimSpace(imageRef)- if before, _, ok := strings.Cut(trimmed, "@"); ok {- trimmed = before- }-- named, err := ref.ParseNormalizedNamed(trimmed)- if err != nil {- return nil, fmt.Errorf("invalid image reference %q: %w", imageRef, err)- }-- registryHost := normalizeRegistryForComparisonInternal(ref.Domain(named))- repository := ref.Path(named)-- tag := "latest"- if tagged, ok := named.(ref.NamedTagged); ok {- tag = tagged.Tag()- }-- return &Reference{- NormalizedRef: registryHost + "/" + repository + ":" + tag,- RegistryHost: registryHost,- Repository: repository,- Tag: tag,- }, nil-}--func IsFallbackEligibleDaemonError(err error) bool {- if err == nil {- return false- }-- errLower := strings.ToLower(err.Error())- if strings.Contains(errLower, "unauthorized") ||- strings.Contains(errLower, "authentication required") ||- strings.Contains(errLower, "no basic auth credentials") ||- strings.Contains(errLower, "access denied") ||- strings.Contains(errLower, "incorrect username or password") ||- strings.Contains(errLower, "status: 401") ||- strings.Contains(errLower, "status 401") {- return false- }-- if strings.Contains(errLower, "x509") || strings.Contains(errLower, "certificate") || strings.Contains(errLower, "tls") {- return false- }-- // Most network-level daemon errors are not fallback-eligible: if the daemon- // cannot reach the registry, the backend's direct HTTP client is also unlikely- // to succeed. Only registry/API capability failures trigger fallback.- //- // Exception: "proxyconnect" errors indicate the daemon's HTTP transport has a- // broken proxy configured at the OS level (e.g. Synology NAS with Docker 20.10).- // The Arcane backend container does not inherit that proxy, so the direct HTTP- // client can still reach the registry successfully.- indicators := []string{- "not found",- " 404 ",- "status: 404",- "status 404",- "403 forbidden",- "status: 403",- "status 403",- "administrative rules",- "not implemented",- "unsupported",- "distribution disabled",- "distribution api",- "proxyconnect",- }-- for _, indicator := range indicators {- if strings.Contains(errLower, indicator) {- return true- }- }-- return false-}--// FetchRegistryRateLimit fetches pull rate limit information from an OCI-// registry manifest response.-func FetchRegistryRateLimit(ctx context.Context, registryHost, repository, tag string, credential *Credentials, httpClient *http.Client) (*RateLimitInfo, error) {- if httpClient == nil {- httpClient = NewRegistryHTTPClient()- }-- requestCtx, cancel := context.WithTimeout(ctx, 30*time.Second)- defer cancel()-- authHeader := ""- if credential != nil && strings.TrimSpace(credential.Username) != "" && strings.TrimSpace(credential.Token) != "" {- authHeader = basicAuthHeaderInternal(credential.Username, credential.Token)- }-- resp, err := manifestRequestInternal(requestCtx, httpClient, registryHost, repository, tag, authHeader)- if err != nil {- return nil, err- }- defer func() { _ = resp.Body.Close() }()-- if resp.StatusCode == http.StatusUnauthorized {- challenge := resp.Header.Get("WWW-Authenticate")- if challenge == "" {- return nil, fmt.Errorf("manifest request failed with status: %d", resp.StatusCode)- }- return fetchRateLimitWithTokenAuthInternal(requestCtx, httpClient, registryHost, repository, tag, challenge, credential)- }-- if resp.StatusCode != http.StatusOK {- return nil, fmt.Errorf("manifest request failed with status: %d", resp.StatusCode)- }-- return extractRateLimitFromHeadersInternal(resp.Header)-}--func FetchDigest(ctx context.Context, registryHost, repository, tag string, credential *Credentials, httpClient *http.Client) (string, error) {- if httpClient == nil {- httpClient = NewRegistryHTTPClient()- }-- requestCtx, cancel := context.WithTimeout(ctx, 30*time.Second)- defer cancel()-- authHeader := ""- if credential != nil && strings.TrimSpace(credential.Username) != "" && strings.TrimSpace(credential.Token) != "" {- authHeader = basicAuthHeaderInternal(credential.Username, credential.Token)- }-- resp, err := manifestRequestInternal(requestCtx, httpClient, registryHost, repository, tag, authHeader)- if err != nil {- return "", err- }- defer func() { _ = resp.Body.Close() }()-- if resp.StatusCode == http.StatusUnauthorized {- challenge := resp.Header.Get("WWW-Authenticate")- if challenge == "" {- return "", fmt.Errorf("manifest request failed with status: %d", resp.StatusCode)- }- return fetchWithTokenAuthInternal(requestCtx, httpClient, registryHost, repository, tag, challenge, credential)- }-- if resp.StatusCode != http.StatusOK {- return "", fmt.Errorf("manifest request failed with status: %d", resp.StatusCode)- }-- digest := extractDigestFromHeadersInternal(resp.Header)- if digest == "" {- return "", errors.New("no digest header found in response")- }-- return digest, nil-}--func fetchRateLimitWithTokenAuthInternal(ctx context.Context, httpClient *http.Client, registryHost, repository, tag, challenge string, credential *Credentials) (*RateLimitInfo, error) {- realm, service := parseWWWAuthInternal(challenge)- if realm == "" {- return nil, errors.New("no auth realm found")- }- if err := validateAuthRealmInternal(registryHost, realm); err != nil {- return nil, err- }-- token, err := fetchRegistryTokenInternal(ctx, httpClient, realm, service, repository, credential)- if err != nil {- return nil, err- }-- resp, err := manifestRequestInternal(ctx, httpClient, registryHost, repository, tag, token)- if err != nil {- return nil, err- }- defer func() { _ = resp.Body.Close() }()-- if resp.StatusCode != http.StatusOK {- return nil, fmt.Errorf("authenticated manifest request failed with status: %d", resp.StatusCode)- }-- return extractRateLimitFromHeadersInternal(resp.Header)-}--func fetchWithTokenAuthInternal(ctx context.Context, httpClient *http.Client, registryHost, repository, tag, challenge string, credential *Credentials) (string, error) {- realm, service := parseWWWAuthInternal(challenge)- if realm == "" {- return "", errors.New("no auth realm found")- }- if err := validateAuthRealmInternal(registryHost, realm); err != nil {- return "", err- }-- token, err := fetchRegistryTokenInternal(ctx, httpClient, realm, service, repository, credential)- if err != nil {- return "", err- }-- resp, err := manifestRequestInternal(ctx, httpClient, registryHost, repository, tag, token)- if err != nil {- return "", err- }- defer func() { _ = resp.Body.Close() }()-- if resp.StatusCode != http.StatusOK {- return "", fmt.Errorf("authenticated manifest request failed with status: %d", resp.StatusCode)- }-- digest := extractDigestFromHeadersInternal(resp.Header)- if digest == "" {- return "", errors.New("no digest header found in authenticated response")- }-- return digest, nil-}--func fetchRegistryTokenInternal(ctx context.Context, httpClient *http.Client, authURL, service, repository string, credential *Credentials) (string, error) {- parsed, err := url.Parse(authURL)- if err != nil {- return "", fmt.Errorf("invalid auth url: %w", err)- }-- query := parsed.Query()- if query.Get("service") == "" {- if strings.TrimSpace(service) != "" {- query.Set("service", strings.TrimSpace(service))- } else {- query.Set("service", serviceNameFromAuthURLInternal(authURL))- }- }- query.Add("scope", fmt.Sprintf("repository:%s:pull", repository))- parsed.RawQuery = query.Encode()-- req, err := http.NewRequestWithContext(ctx, http.MethodGet, parsed.String(), nil)- if err != nil {- return "", fmt.Errorf("create token request: %w", err)- }- if credential != nil && strings.TrimSpace(credential.Username) != "" && strings.TrimSpace(credential.Token) != "" {- req.SetBasicAuth(strings.TrimSpace(credential.Username), strings.TrimSpace(credential.Token))- }-- resp, err := httpClient.Do(req)- if err != nil {- return "", fmt.Errorf("token request failed: %w", err)- }- defer func() { _ = resp.Body.Close() }()-- if resp.StatusCode != http.StatusOK {- return "", fmt.Errorf("token request failed with status: %d", resp.StatusCode)- }-- var tokenResponse struct {- Token string `json:"token"`- Legacy string `json:"access_token"`- }- if err := json.NewDecoder(resp.Body).Decode(&tokenResponse); err != nil {- return "", fmt.Errorf("decode token response: %w", err)- }-- token := strings.TrimSpace(tokenResponse.Token)- if token == "" {- token = strings.TrimSpace(tokenResponse.Legacy)- }- if token == "" {- return "", errors.New("no token in response")- }-- return token, nil-}--func manifestRequestInternal(ctx context.Context, httpClient *http.Client, registryHost, repository, tag, authHeader string) (*http.Response, error) {- manifestURL := fmt.Sprintf("%s/v2/%s/manifests/%s", registryBaseURLInternal(registryHost), repository, tag)-- req, err := http.NewRequestWithContext(ctx, http.MethodHead, manifestURL, nil)- if err != nil {- return nil, fmt.Errorf("create manifest request: %w", err)- }- addManifestRequestHeadersInternal(req, authHeader)-- resp, err := httpClient.Do(req)- if err != nil {- return nil, fmt.Errorf("manifest request failed: %w", err)- }-- switch resp.StatusCode {- case http.StatusMethodNotAllowed:- // Retry with GET only when the registry rejects HEAD as an unsupported method.- _ = resp.Body.Close()-- getReq, err := http.NewRequestWithContext(ctx, http.MethodGet, manifestURL, nil)- if err != nil {- return nil, fmt.Errorf("create manifest fallback request: %w", err)- }- addManifestRequestHeadersInternal(getReq, authHeader)-- getResp, err := httpClient.Do(getReq)- if err != nil {- return nil, fmt.Errorf("manifest fallback request failed: %w", err)- }-- return getResp, nil- default:- return resp, nil- }-}--// NewRegistryHTTPClient returns the shared transport configuration used for-// direct registry digest lookups.-func NewRegistryHTTPClient() *http.Client {- var transport *http.Transport- if defaultTransport, ok := http.DefaultTransport.(*http.Transport); ok {- transport = defaultTransport.Clone()- } else {- transport = &http.Transport{}- }- transport.Proxy = http.ProxyFromEnvironment-- return &http.Client{Transport: transport}-}--func registryBaseURLInternal(registryHost string) string {- trimmed := strings.TrimSpace(registryHost)- if strings.HasPrefix(trimmed, "http://") || strings.HasPrefix(trimmed, "https://") {- if parsed, err := url.Parse(trimmed); err == nil && parsed.Host != "" && normalizeRegistryForComparisonInternal(parsed.Host) == "docker.io" {- return "https://" + defaultRegistryHost- }- return strings.TrimSuffix(trimmed, "/")- }-- normalizedHost := normalizeRegistryForComparisonInternal(trimmed)- if normalizedHost == "docker.io" {- return "https://" + defaultRegistryHost- }-- return "https://" + normalizedHost-}--func addManifestRequestHeadersInternal(req *http.Request, authHeader string) {- req.Header.Set("Accept", "application/vnd.docker.distribution.manifest.v2+json, application/vnd.oci.image.manifest.v1+json, application/vnd.docker.distribution.manifest.list.v2+json, application/vnd.oci.image.index.v1+json")- req.Header.Set("User-Agent", "Arcane")- if strings.TrimSpace(authHeader) != "" {- req.Header.Set("Authorization", buildAuthHeaderInternal(authHeader))- }-}--func buildAuthHeaderInternal(authHeader string) string {- trimmed := strings.TrimSpace(authHeader)- if trimmed == "" {- return ""- }-- lower := strings.ToLower(trimmed)- if strings.HasPrefix(lower, "bearer ") || strings.HasPrefix(lower, "basic ") {- return trimmed- }-- return "Bearer " + trimmed-}--func basicAuthHeaderInternal(username, token string) string {- raw := strings.TrimSpace(username) + ":" + strings.TrimSpace(token)- return "Basic " + base64.StdEncoding.EncodeToString([]byte(raw))-}--func extractDigestFromHeadersInternal(headers http.Header) string {- if normalized, err := NormalizeDigest(headers.Get("Docker-Content-Digest")); err == nil {- return normalized- }-- etag := strings.Trim(headers.Get("ETag"), `"`)- if normalized, err := NormalizeDigest(etag); err == nil {- return normalized- }-- return ""-}--func extractRateLimitFromHeadersInternal(headers http.Header) (*RateLimitInfo, error) {- limit, limitWindow, limitErr := parseRateLimitHeaderInternal(headers.Get("Ratelimit-Limit"))- if limitErr != nil {- return nil, fmt.Errorf("parse RateLimit-Limit: %w", limitErr)- }-- remaining, remainingWindow, remainingErr := parseRateLimitHeaderInternal(headers.Get("Ratelimit-Remaining"))- if remainingErr != nil {- return nil, fmt.Errorf("parse RateLimit-Remaining: %w", remainingErr)- }-- if limit == nil && remaining == nil {- return nil, errors.New("rate limit headers not returned")- }-- windowSeconds := limitWindow- if windowSeconds == nil {- windowSeconds = remainingWindow- }-- var used *int- if limit != nil && remaining != nil {- used = new(*limit - *remaining)- }-- return &RateLimitInfo{- Limit: limit,- Remaining: remaining,- Used: used,- WindowSeconds: windowSeconds,- Source: strings.TrimSpace(headers.Get("Docker-Ratelimit-Source")),- }, nil-}--func parseRateLimitHeaderInternal(value string) (*int, *int, error) {- value = strings.TrimSpace(value)- if value == "" {- return nil, nil, nil- }-- if beforeComma, _, ok := strings.Cut(value, ","); ok {- value = strings.TrimSpace(beforeComma)- }-- parts := strings.Split(value, ";")- quota, err := parsePositiveIntInternal(strings.TrimSpace(parts[0]))- if err != nil {- return nil, nil, err- }-- var window *int- for _, part := range parts[1:] {- key, raw, ok := strings.Cut(strings.TrimSpace(part), "=")- if !ok || strings.TrimSpace(key) != "w" {- continue- }-- parsedWindow, parseErr := parsePositiveIntInternal(strings.TrimSpace(raw))- if parseErr != nil {- return nil, nil, fmt.Errorf("invalid window: %w", parseErr)- }- window = parsedWindow- break- }-- return quota, window, nil-}--func parsePositiveIntInternal(value string) (*int, error) {- if value == "" {- return nil, errors.New("empty integer value")- }-- parsed, err := strconv.Atoi(value)- if err != nil || parsed < 0 {- return nil, fmt.Errorf("invalid integer value %q", value)- }-- return &parsed, nil-}--func parseWWWAuthInternal(header string) (string, string) {- lower := strings.ToLower(header)- if !strings.HasPrefix(lower, "bearer ") {- return "", ""- }-- _, after, ok := strings.Cut(header, " ")- if !ok {- return "", ""- }-- var realm string- var service string- for _, part := range splitBearerDirectivesInternal(after) {- part = strings.TrimSpace(part)- lowerPart := strings.ToLower(part)-- switch {- case strings.HasPrefix(lowerPart, "realm="):- realm = strings.Trim(part[len("realm="):], `"`)- case strings.HasPrefix(lowerPart, "service="):- service = strings.Trim(part[len("service="):], `"`)- }- }-- return realm, service-}--func splitBearerDirectivesInternal(value string) []string {- var parts []string- var current strings.Builder- inQuote := false-- for _, r := range value {- switch {- case r == '"':- inQuote = !inQuote- current.WriteRune(r)- case r == ',' && !inQuote:- parts = append(parts, current.String())- current.Reset()- default:- current.WriteRune(r)- }- }-- if current.Len() > 0 {- parts = append(parts, current.String())- }-- return parts-}--func serviceNameFromAuthURLInternal(authURL string) string {- if strings.Contains(authURL, "auth.docker.io") {- return "registry.docker.io"- }-- trimmed := strings.TrimPrefix(authURL, "https://")- trimmed = strings.TrimPrefix(trimmed, "http://")- host, _, _ := strings.Cut(trimmed, "/")- if host == "" {- return "registry"- }-- return host-}--func validateAuthRealmInternal(registryHost, realm string) error {- parsedRealm, err := url.Parse(strings.TrimSpace(realm))- if err != nil {- return fmt.Errorf("invalid auth realm: %w", err)- }-- if !strings.EqualFold(parsedRealm.Scheme, "https") {- return fmt.Errorf("auth realm must use HTTPS, got %q", parsedRealm.Scheme)- }-- realmHost := normalizeAuthRealmHostInternal(parsedRealm.Host)- registry := normalizeAuthRealmHostInternal(registryHost)-- if realmHost == "" {- return errors.New("invalid auth realm host")- }- if realmHost == registry {- return nil- }-- if trustedRealm, ok := trustedAuthDelegations[registry]; ok && realmHost == trustedRealm {- return nil- }-- return fmt.Errorf("untrusted auth realm host %q for registry %q", realmHost, registry)-}--func normalizeAuthRealmHostInternal(raw string) string {- normalized := normalizeRegistryForComparisonInternal(raw)- if normalized == "" {- return ""- }-- host, port, err := net.SplitHostPort(normalized)- if err != nil {- return normalized- }-- if port == "443" {- return host- }-- return net.JoinHostPort(host, port)-}--func normalizeRegistryForComparisonInternal(raw string) string {- return registryauth.NormalizeRegistryForComparison(raw)-}diff --git a/backend/pkg/libarcane/imageupdate/registry_http_test.go b/backend/pkg/libarcane/imageupdate/registry_http_test.godeleted file mode 100644index db6ea3959..000000000--- a/backend/pkg/libarcane/imageupdate/registry_http_test.go+++ /dev/null@@ -1,390 +0,0 @@-package imageupdate--import (- "context"- "fmt"- "net/http"- "net/http/httptest"- "testing"-- "github.com/opencontainers/go-digest"- "github.com/stretchr/testify/assert"- "github.com/stretchr/testify/require"-)--func serverURLFromRequestInternal(r *http.Request) string {- return "https://" + r.Host-}--func TestIsFallbackEligibleDaemonError(t *testing.T) {- eligible := []string{- "not found",- "status: 404",- "status 404",- " 404 ",- "403 forbidden",- "status: 403",- "status 403",- "not implemented",- "unsupported",- "distribution disabled",- "distribution api",- "administrative rules",- "proxyconnect tcp: dial tcp :0: connect: connection refused",- }- for _, msg := range eligible {- t.Run("eligible/"+msg, func(t *testing.T) {- assert.True(t, IsFallbackEligibleDaemonError(fmt.Errorf("%s", msg)))- })- }-- notEligible := []string{- "unauthorized",- "authentication required",- "no basic auth credentials",- "access denied",- "status: 401",- "x509: certificate signed by unknown authority",- "tls handshake timeout",- "connection refused",- "no such host",- }- for _, msg := range notEligible {- t.Run("not-eligible/"+msg, func(t *testing.T) {- assert.False(t, IsFallbackEligibleDaemonError(fmt.Errorf("%s", msg)))- })- }-- assert.False(t, IsFallbackEligibleDaemonError(nil))-}--func TestFetchDigest_FallsBackToGetOnMethodNotAllowed(t *testing.T) {- var headCalls int- var getCalls int- wantDigest := digest.FromString("method-not-allowed").String()-- server := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {- switch r.Method {- case http.MethodHead:- headCalls++- w.WriteHeader(http.StatusMethodNotAllowed)- case http.MethodGet:- getCalls++- w.Header().Set("Docker-Content-Digest", wantDigest)- w.WriteHeader(http.StatusOK)- default:- t.Fatalf("unexpected method %s", r.Method)- }- }))- defer server.Close()-- digest, err := FetchDigest(- context.Background(),- server.URL,- "team/app",- "1.2.3",- nil,- server.Client(),- )- require.NoError(t, err)- assert.Equal(t, wantDigest, digest)- assert.Equal(t, 1, headCalls)- assert.Equal(t, 1, getCalls)-}--func TestFetchDigest_DoesNotFallbackToGetOnResourceErrors(t *testing.T) {- testCases := []struct {- name string- status int- }{- {name: "not found", status: http.StatusNotFound},- {name: "forbidden", status: http.StatusForbidden},- }-- for _, tc := range testCases {- t.Run(tc.name, func(t *testing.T) {- var headCalls int- var getCalls int-- server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {- switch r.Method {- case http.MethodHead:- headCalls++- w.WriteHeader(tc.status)- case http.MethodGet:- getCalls++- w.Header().Set("Docker-Content-Digest", "sha256:unexpected-get")- w.WriteHeader(http.StatusOK)- default:- t.Fatalf("unexpected method %s", r.Method)- }- }))- defer server.Close()-- digest, err := FetchDigest(- context.Background(),- server.URL,- "team/app",- "1.2.3",- nil,- server.Client(),- )- require.Error(t, err)- assert.Empty(t, digest)- assert.Equal(t, fmt.Sprintf("manifest request failed with status: %d", tc.status), err.Error())- assert.Equal(t, 1, headCalls)- assert.Equal(t, 0, getCalls)- })- }-}--func TestFetchRegistryRateLimit_AnonymousTokenFlow(t *testing.T) {- var tokenCalls int- var manifestCalls int-- server := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {- switch {- case r.URL.Path == "/token":- tokenCalls++- assert.Empty(t, r.Header.Get("Authorization"))- assert.Equal(t, "registry.example.com", r.URL.Query().Get("service"))- assert.Equal(t, "repository:team/app:pull", r.URL.Query().Get("scope"))- _, _ = w.Write([]byte(`{"token":"test-token"}`))- case r.Method == http.MethodHead && r.URL.Path == "/v2/team/app/manifests/latest":- manifestCalls++- if r.Header.Get("Authorization") != "Bearer test-token" {- w.Header().Set("WWW-Authenticate", fmt.Sprintf(`Bearer realm="%s/token",service="registry.example.com"`, serverURLFromRequestInternal(r)))- w.WriteHeader(http.StatusUnauthorized)- return- }- w.Header().Set("RateLimit-Limit", "100;w=21600")- w.Header().Set("RateLimit-Remaining", "76;w=21600")- w.Header().Set("Docker-RateLimit-Source", "203.0.113.10")- w.WriteHeader(http.StatusOK)- default:- t.Fatalf("unexpected request %s %s", r.Method, r.URL.Path)- }- }))- defer server.Close()-- info, err := FetchRegistryRateLimit(- context.Background(),- server.URL,- "team/app",- "latest",- nil,- server.Client(),- )-- require.NoError(t, err)- require.NotNil(t, info.Limit)- require.NotNil(t, info.Remaining)- require.NotNil(t, info.Used)- require.NotNil(t, info.WindowSeconds)- assert.Equal(t, 100, *info.Limit)- assert.Equal(t, 76, *info.Remaining)- assert.Equal(t, 24, *info.Used)- assert.Equal(t, 21600, *info.WindowSeconds)- assert.Equal(t, "203.0.113.10", info.Source)- assert.Equal(t, 1, tokenCalls)- assert.Equal(t, 2, manifestCalls)-}--func TestFetchRegistryRateLimit_CredentialBackedTokenFlow(t *testing.T) {- var tokenAuth string- var initialManifestAuth string-- server := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {- switch {- case r.URL.Path == "/token":- tokenAuth = r.Header.Get("Authorization")- _, _ = w.Write([]byte(`{"access_token":"credential-token"}`))- case r.Method == http.MethodHead && r.URL.Path == "/v2/team/app/manifests/latest":- if r.Header.Get("Authorization") != "Bearer credential-token" {- initialManifestAuth = r.Header.Get("Authorization")- w.Header().Set("WWW-Authenticate", fmt.Sprintf(`Bearer realm="%s/token",service="registry.example.com"`, serverURLFromRequestInternal(r)))- w.WriteHeader(http.StatusUnauthorized)- return- }- w.Header().Set("RateLimit-Limit", "200;w=21600")- w.Header().Set("RateLimit-Remaining", "199;w=21600")- w.WriteHeader(http.StatusOK)- default:- t.Fatalf("unexpected request %s %s", r.Method, r.URL.Path)- }- }))- defer server.Close()-- info, err := FetchRegistryRateLimit(- context.Background(),- server.URL,- "team/app",- "latest",- &Credentials{Username: "docker-user", Token: "docker-token"},- server.Client(),- )-- require.NoError(t, err)- require.NotNil(t, info.Limit)- require.NotNil(t, info.Remaining)- assert.Equal(t, 200, *info.Limit)- assert.Equal(t, 199, *info.Remaining)- assert.Contains(t, initialManifestAuth, "Basic ")- assert.Contains(t, tokenAuth, "Basic ")-}--func TestFetchRegistryRateLimit_MissingHeaders(t *testing.T) {- server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {- w.WriteHeader(http.StatusOK)- }))- defer server.Close()-- info, err := FetchRegistryRateLimit(context.Background(), server.URL, "team/app", "latest", nil, server.Client())-- require.Error(t, err)- assert.Nil(t, info)- assert.Contains(t, err.Error(), "rate limit headers not returned")-}--func TestFetchRegistryRateLimit_MalformedHeader(t *testing.T) {- server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {- w.Header().Set("RateLimit-Limit", "bad;w=21600")- w.WriteHeader(http.StatusOK)- }))- defer server.Close()-- info, err := FetchRegistryRateLimit(context.Background(), server.URL, "team/app", "latest", nil, server.Client())-- require.Error(t, err)- assert.Nil(t, info)- assert.Contains(t, err.Error(), "parse RateLimit-Limit")-}--func TestFetchRegistryRateLimit_NonOKResponse(t *testing.T) {- server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {- w.WriteHeader(http.StatusTooManyRequests)- }))- defer server.Close()-- info, err := FetchRegistryRateLimit(context.Background(), server.URL, "team/app", "latest", nil, server.Client())-- require.Error(t, err)- assert.Nil(t, info)- assert.Contains(t, err.Error(), "manifest request failed with status: 429")-}--func TestParseWWWAuthInternal_AllowsCommasInsideQuotedRealm(t *testing.T) {- realm, service := parseWWWAuthInternal(`Bearer realm="https://auth.example.com/token?a=1,b=2",service="registry.example.com"`)- assert.Equal(t, "https://auth.example.com/token?a=1,b=2", realm)- assert.Equal(t, "registry.example.com", service)-}--func TestFetchDigest_RejectsUntrustedTokenRealm(t *testing.T) {- registry := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {- w.Header().Set("WWW-Authenticate", `Bearer realm="https://169.254.169.254/token",service="registry.example.com"`)- w.WriteHeader(http.StatusUnauthorized)- }))- defer registry.Close()-- digest, err := FetchDigest(- context.Background(),- registry.URL,- "team/app",- "latest",- nil,- registry.Client(),- )-- require.Error(t, err)- assert.Empty(t, digest)- assert.Contains(t, err.Error(), "untrusted auth realm host")-}--func TestValidateAuthRealmInternal(t *testing.T) {- tests := []struct {- name string- registryHost string- realm string- wantErr bool- errContains string- }{- {- name: "same host allowed",- registryHost: "registry.example.com",- realm: "https://registry.example.com/token",- },- {- name: "same host with explicit default https port allowed",- registryHost: "registry.example.com",- realm: "https://registry.example.com:443/token",- },- {- name: "same host with matching non-default port allowed",- registryHost: "127.0.0.1:5000",- realm: "https://127.0.0.1:5000/token",- },- {- name: "docker hub auth host allowed",- registryHost: "registry-1.docker.io",- realm: "https://auth.docker.io/token",- },- {- name: "lscr.io delegates auth to ghcr.io",- registryHost: "lscr.io",- realm: "https://ghcr.io/token",- },- {- name: "registry.gitlab.com delegates auth to gitlab.com",- registryHost: "registry.gitlab.com",- realm: "https://gitlab.com/jwt/auth",- },- {- name: "non https realm rejected",- registryHost: "registry.example.com",- realm: "http://registry.example.com/token",- wantErr: true,- errContains: "auth realm must use HTTPS",- },- {- name: "empty realm rejected",- registryHost: "registry.example.com",- realm: "",- wantErr: true,- errContains: "auth realm must use HTTPS",- },- {- name: "malformed realm rejected",- registryHost: "registry.example.com",- realm: "https://%zz",- wantErr: true,- errContains: "invalid auth realm",- },- {- name: "relative realm rejected",- registryHost: "registry.example.com",- realm: "/token",- wantErr: true,- errContains: "auth realm must use HTTPS",- },- {- name: "untrusted realm rejected",- registryHost: "registry.example.com",- realm: "https://evil.com/token",- wantErr: true,- errContains: "untrusted auth realm host",- },- }-- for _, tc := range tests {- t.Run(tc.name, func(t *testing.T) {- err := validateAuthRealmInternal(tc.registryHost, tc.realm)- if tc.wantErr {- require.Error(t, err)- assert.Contains(t, err.Error(), tc.errContains)- return- }-- require.NoError(t, err)- })- }-}diff --git a/backend/pkg/libarcane/imageupdate/sorter.go b/backend/pkg/libarcane/imageupdate/sorter.godeleted file mode 100644index 187a4a72a..000000000--- a/backend/pkg/libarcane/imageupdate/sorter.go+++ /dev/null@@ -1,215 +0,0 @@-package imageupdate--import (- "context"- "fmt"- "log/slog"- "slices"- "strings"-- dockerutil "github.com/getarcaneapp/arcane/backend/pkg/dockerutil"- "github.com/moby/moby/api/types/container"- "github.com/moby/moby/client"-)--// ContainerWithDeps represents a container with its dependency information for sorting-type ContainerWithDeps struct {- Container container.Summary- Inspect container.InspectResponse- Name string- Links []string // Container names this one links to- DependsOn []string // Explicit dependencies from label- NetworkDeps []string // Implicit dependencies from container network mode-}--// ContainerSorter handles topological sorting of containers based on dependencies-type ContainerSorter struct {- containers []ContainerWithDeps- nameToIndex map[string]int- visited map[string]bool- marked map[string]bool // For cycle detection- sorted []ContainerWithDeps-}--// NewContainerSorter creates a new sorter for the given containers-func NewContainerSorter(containers []ContainerWithDeps) *ContainerSorter {- nameToIndex := make(map[string]int, len(containers))- for i, c := range containers {- nameToIndex[c.Name] = i- }- return &ContainerSorter{- containers: containers,- nameToIndex: nameToIndex,- visited: make(map[string]bool),- marked: make(map[string]bool),- sorted: make([]ContainerWithDeps, 0, len(containers)),- }-}--// Sort performs topological sort and returns containers in dependency order-// Dependencies come first, dependents come later-func (s *ContainerSorter) Sort() ([]ContainerWithDeps, error) {- for _, c := range s.containers {- if !s.visited[c.Name] {- if err := s.visitInternal(c); err != nil {- return nil, err- }- }- }- return s.sorted, nil-}--// SortReverse returns containers in reverse dependency order-// Dependents come first, dependencies come later (for stopping)-func (s *ContainerSorter) SortReverse() ([]ContainerWithDeps, error) {- sorted, err := s.Sort()- if err != nil {- return nil, err- }-- slices.Reverse(sorted)- return sorted, nil-}--func (s *ContainerSorter) visitInternal(c ContainerWithDeps) error {- if s.marked[c.Name] {- return fmt.Errorf("circular dependency detected: %s", c.Name)- }- if s.visited[c.Name] {- return nil- }-- s.marked[c.Name] = true- defer delete(s.marked, c.Name)-- // Visit all dependencies first- allDeps := s.getAllDependenciesInternal(c)- for _, depName := range allDeps {- if idx, ok := s.nameToIndex[depName]; ok {- if err := s.visitInternal(s.containers[idx]); err != nil {- return err- }- }- }-- s.visited[c.Name] = true- s.sorted = append(s.sorted, c)- return nil-}--func (s *ContainerSorter) getAllDependenciesInternal(c ContainerWithDeps) []string {- seen := make(map[string]struct{})- var deps []string-- for _, d := range c.Links {- if _, ok := seen[d]; !ok {- seen[d] = struct{}{}- deps = append(deps, d)- }- }- for _, d := range c.DependsOn {- if _, ok := seen[d]; !ok {- seen[d] = struct{}{}- deps = append(deps, d)- }- }- for _, d := range c.NetworkDeps {- if _, ok := seen[d]; !ok {- seen[d] = struct{}{}- deps = append(deps, d)- }- }-- return deps-}--// ExtractContainerDeps extracts dependency information from a container-func ExtractContainerDeps(ctx context.Context, dcli *client.Client, cnt container.Summary, inspect container.InspectResponse) ContainerWithDeps {- c := ContainerWithDeps{- Container: cnt,- Inspect: inspect,- Name: dockerutil.ContainerSummaryName(cnt),- }-- // Extract Docker links- if inspect.HostConfig != nil {- for _, link := range inspect.HostConfig.Links {- // Links are in format "container:/alias"- parts := strings.SplitN(link, ":", 2)- if len(parts) > 0 {- linkName := strings.TrimPrefix(parts[0], "/")- c.Links = append(c.Links, linkName)- }- }- }-- // Extract explicit depends-on from label- if inspect.Config != nil && inspect.Config.Labels != nil {- if deps, ok := inspect.Config.Labels[LabelDependsOn]; ok {- for dep := range strings.SplitSeq(deps, ",") {- dep = strings.TrimSpace(dep)- if dep != "" {- c.DependsOn = append(c.DependsOn, dep)- }- }- }- }-- // Extract implicit dependencies from network mode (container:xxx)- if inspect.HostConfig != nil {- nm := inspect.HostConfig.NetworkMode- if nm.IsContainer() {- // NetworkMode is "container:<name_or_id>"- containerRef := strings.TrimPrefix(string(nm), "container:")- c.NetworkDeps = append(c.NetworkDeps, containerRef)- }- }-- slog.DebugContext(ctx, "ExtractContainerDeps: extracted dependencies",- "container", c.Name,- "links", c.Links,- "dependsOn", c.DependsOn,- "networkDeps", c.NetworkDeps)-- return c-}--// UpdateImplicitRestart marks containers that need to restart because their dependencies are restarting.-// Returns the names of containers that were marked for implicit restart.-// Note: This function mutates the containers slice by adding "_arcane_implicit_restart" labels.-func UpdateImplicitRestart(containers []ContainerWithDeps, markedForRestart map[string]bool) []string {- var implicitRestarts []string-- for i, c := range containers {- if markedForRestart[c.Name] {- continue // Already marked- }-- // Check if any dependency is marked for restart- if !hasMarkedDependencyInternal(markedForRestart, c.Links) &&- !hasMarkedDependencyInternal(markedForRestart, c.DependsOn) &&- !hasMarkedDependencyInternal(markedForRestart, c.NetworkDeps) {- continue- }-- // This container's dependency is restarting, so it needs to restart too- markedForRestart[c.Name] = true- if containers[i].Container.Labels == nil {- containers[i].Container.Labels = map[string]string{}- }- containers[i].Container.Labels["_arcane_implicit_restart"] = "true"- implicitRestarts = append(implicitRestarts, c.Name)- }-- return implicitRestarts-}--func hasMarkedDependencyInternal(markedForRestart map[string]bool, deps []string) bool {- for _, dep := range deps {- if markedForRestart[dep] {- return true- }- }-- return false-}diff --git a/backend/pkg/libarcane/imageupdate/sorter_test.go b/backend/pkg/libarcane/imageupdate/sorter_test.godeleted file mode 100644index 2c4b85b6c..000000000--- a/backend/pkg/libarcane/imageupdate/sorter_test.go+++ /dev/null@@ -1,353 +0,0 @@-package imageupdate--import (- "testing"-- "github.com/moby/moby/api/types/container"-)--func TestContainerSorter_Sort(t *testing.T) {- tests := []struct {- name string- containers []ContainerWithDeps- want []string // Expected order by name- wantErr bool- }{- {- name: "empty containers",- containers: []ContainerWithDeps{},- want: []string{},- wantErr: false,- },- {- name: "single container no deps",- containers: []ContainerWithDeps{- {Name: "app", Container: container.Summary{ID: "app1"}},- },- want: []string{"app"},- wantErr: false,- },- {- name: "two containers no deps",- containers: []ContainerWithDeps{- {Name: "app", Container: container.Summary{ID: "app1"}},- {Name: "db", Container: container.Summary{ID: "db1"}},- },- want: []string{"app", "db"},- wantErr: false,- },- {- name: "simple dependency - app depends on db",- containers: []ContainerWithDeps{- {Name: "app", DependsOn: []string{"db"}, Container: container.Summary{ID: "app1"}},- {Name: "db", Container: container.Summary{ID: "db1"}},- },- want: []string{"db", "app"},- wantErr: false,- },- {- name: "link dependency - app links to db",- containers: []ContainerWithDeps{- {Name: "app", Links: []string{"db"}, Container: container.Summary{ID: "app1"}},- {Name: "db", Container: container.Summary{ID: "db1"}},- },- want: []string{"db", "app"},- wantErr: false,- },- {- name: "network dependency - app uses db network",- containers: []ContainerWithDeps{- {Name: "app", NetworkDeps: []string{"db"}, Container: container.Summary{ID: "app1"}},- {Name: "db", Container: container.Summary{ID: "db1"}},- },- want: []string{"db", "app"},- wantErr: false,- },- {- name: "chain dependency - app -> db -> cache",- containers: []ContainerWithDeps{- {Name: "app", DependsOn: []string{"db"}, Container: container.Summary{ID: "app1"}},- {Name: "db", DependsOn: []string{"cache"}, Container: container.Summary{ID: "db1"}},- {Name: "cache", Container: container.Summary{ID: "cache1"}},- },- want: []string{"cache", "db", "app"},- wantErr: false,- },- {- name: "multiple dependencies - app depends on db and cache",- containers: []ContainerWithDeps{- {Name: "app", DependsOn: []string{"db", "cache"}, Container: container.Summary{ID: "app1"}},- {Name: "db", Container: container.Summary{ID: "db1"}},- {Name: "cache", Container: container.Summary{ID: "cache1"}},- },- want: []string{"db", "cache", "app"},- wantErr: false,- },- {- name: "diamond dependency - app and worker depend on db, both depend on cache",- containers: []ContainerWithDeps{- {Name: "app", DependsOn: []string{"db"}, Container: container.Summary{ID: "app1"}},- {Name: "worker", DependsOn: []string{"db"}, Container: container.Summary{ID: "worker1"}},- {Name: "db", DependsOn: []string{"cache"}, Container: container.Summary{ID: "db1"}},- {Name: "cache", Container: container.Summary{ID: "cache1"}},- },- want: []string{"cache", "db", "app", "worker"},- wantErr: false,- },- {- name: "circular dependency - app -> db -> app",- containers: []ContainerWithDeps{- {Name: "app", DependsOn: []string{"db"}, Container: container.Summary{ID: "app1"}},- {Name: "db", DependsOn: []string{"app"}, Container: container.Summary{ID: "db1"}},- },- want: nil,- wantErr: true,- },- {- name: "circular dependency chain - app -> db -> cache -> app",- containers: []ContainerWithDeps{- {Name: "app", DependsOn: []string{"db"}, Container: container.Summary{ID: "app1"}},- {Name: "db", DependsOn: []string{"cache"}, Container: container.Summary{ID: "db1"}},- {Name: "cache", DependsOn: []string{"app"}, Container: container.Summary{ID: "cache1"}},- },- want: nil,- wantErr: true,- },- {- name: "missing dependency - app depends on nonexistent db",- containers: []ContainerWithDeps{- {Name: "app", DependsOn: []string{"db"}, Container: container.Summary{ID: "app1"}},- },- want: []string{"app"},- wantErr: false,- },- {- name: "mixed dependency types - links, depends-on, network",- containers: []ContainerWithDeps{- {Name: "app", Links: []string{"db"}, NetworkDeps: []string{"proxy"}, Container: container.Summary{ID: "app1"}},- {Name: "worker", DependsOn: []string{"db"}, Container: container.Summary{ID: "worker1"}},- {Name: "db", Container: container.Summary{ID: "db1"}},- {Name: "proxy", Container: container.Summary{ID: "proxy1"}},- },- want: []string{"db", "proxy", "app", "worker"},- wantErr: false,- },- }-- for _, tt := range tests {- t.Run(tt.name, func(t *testing.T) {- s := NewContainerSorter(tt.containers)- got, err := s.Sort()-- if (err != nil) != tt.wantErr {- t.Errorf("Sort() error = %v, wantErr %v", err, tt.wantErr)- return- }-- if tt.wantErr {- return- }-- if len(got) != len(tt.want) {- t.Errorf("Sort() returned %d containers, want %d", len(got), len(tt.want))- return- }-- for i, c := range got {- if c.Name != tt.want[i] {- t.Errorf("Sort()[%d].Name = %v, want %v", i, c.Name, tt.want[i])- }- }- })- }-}--func TestContainerSorter_SortReverse(t *testing.T) {- tests := []struct {- name string- containers []ContainerWithDeps- want []string // Expected reverse order by name- wantErr bool- }{- {- name: "empty containers",- containers: []ContainerWithDeps{},- want: []string{},- wantErr: false,- },- {- name: "simple dependency - reverse should be app then db",- containers: []ContainerWithDeps{- {Name: "app", DependsOn: []string{"db"}, Container: container.Summary{ID: "app1"}},- {Name: "db", Container: container.Summary{ID: "db1"}},- },- want: []string{"app", "db"},- wantErr: false,- },- {- name: "chain dependency - reverse should be app -> db -> cache",- containers: []ContainerWithDeps{- {Name: "app", DependsOn: []string{"db"}, Container: container.Summary{ID: "app1"}},- {Name: "db", DependsOn: []string{"cache"}, Container: container.Summary{ID: "db1"}},- {Name: "cache", Container: container.Summary{ID: "cache1"}},- },- want: []string{"app", "db", "cache"},- wantErr: false,- },- {- name: "circular dependency",- containers: []ContainerWithDeps{- {Name: "app", DependsOn: []string{"db"}, Container: container.Summary{ID: "app1"}},- {Name: "db", DependsOn: []string{"app"}, Container: container.Summary{ID: "db1"}},- },- want: nil,- wantErr: true,- },- }-- for _, tt := range tests {- t.Run(tt.name, func(t *testing.T) {- s := NewContainerSorter(tt.containers)- got, err := s.SortReverse()-- if (err != nil) != tt.wantErr {- t.Errorf("SortReverse() error = %v, wantErr %v", err, tt.wantErr)- return- }-- if tt.wantErr {- return- }-- if len(got) != len(tt.want) {- t.Errorf("SortReverse() returned %d containers, want %d", len(got), len(tt.want))- return- }-- for i, c := range got {- if c.Name != tt.want[i] {- t.Errorf("SortReverse()[%d].Name = %v, want %v", i, c.Name, tt.want[i])- }- }- })- }-}--func TestUpdateImplicitRestart(t *testing.T) {- tests := []struct {- name string- containers []ContainerWithDeps- markedForRestart map[string]bool- wantImplicit []string- wantMarkedAfter map[string]bool- }{- {- name: "no containers",- containers: []ContainerWithDeps{},- markedForRestart: map[string]bool{},- wantImplicit: []string{},- wantMarkedAfter: map[string]bool{},- },- {- name: "no dependencies, no restarts",- containers: []ContainerWithDeps{- {Name: "app", Container: container.Summary{ID: "app1"}},- {Name: "db", Container: container.Summary{ID: "db1"}},- },- markedForRestart: map[string]bool{},- wantImplicit: []string{},- wantMarkedAfter: map[string]bool{},- },- {- name: "db marked for restart, app depends on db",- containers: []ContainerWithDeps{- {Name: "app", DependsOn: []string{"db"}, Container: container.Summary{ID: "app1", Labels: map[string]string{}}},- {Name: "db", Container: container.Summary{ID: "db1"}},- },- markedForRestart: map[string]bool{"db": true},- wantImplicit: []string{"app"},- wantMarkedAfter: map[string]bool{"db": true, "app": true},- },- {- name: "chain reaction - cache restart triggers db (not app in single pass)",- containers: []ContainerWithDeps{- {Name: "app", DependsOn: []string{"db"}, Container: container.Summary{ID: "app1", Labels: map[string]string{}}},- {Name: "db", DependsOn: []string{"cache"}, Container: container.Summary{ID: "db1", Labels: map[string]string{}}},- {Name: "cache", Container: container.Summary{ID: "cache1"}},- },- markedForRestart: map[string]bool{"cache": true},- wantImplicit: []string{"db"}, // Only direct dependencies in single pass- wantMarkedAfter: map[string]bool{"cache": true, "db": true},- },- {- name: "app already marked, should not be in implicit list",- containers: []ContainerWithDeps{- {Name: "app", DependsOn: []string{"db"}, Container: container.Summary{ID: "app1"}},- {Name: "db", Container: container.Summary{ID: "db1"}},- },- markedForRestart: map[string]bool{"db": true, "app": true},- wantImplicit: []string{},- wantMarkedAfter: map[string]bool{"db": true, "app": true},- },- {- name: "link dependency triggers restart",- containers: []ContainerWithDeps{- {Name: "app", Links: []string{"db"}, Container: container.Summary{ID: "app1", Labels: map[string]string{}}},- {Name: "db", Container: container.Summary{ID: "db1"}},- },- markedForRestart: map[string]bool{"db": true},- wantImplicit: []string{"app"},- wantMarkedAfter: map[string]bool{"db": true, "app": true},- },- {- name: "network dependency triggers restart",- containers: []ContainerWithDeps{- {Name: "app", NetworkDeps: []string{"db"}, Container: container.Summary{ID: "app1", Labels: map[string]string{}}},- {Name: "db", Container: container.Summary{ID: "db1"}},- },- markedForRestart: map[string]bool{"db": true},- wantImplicit: []string{"app"},- wantMarkedAfter: map[string]bool{"db": true, "app": true},- },- {- name: "multiple dependencies - one triggers restart",- containers: []ContainerWithDeps{- {Name: "app", DependsOn: []string{"db", "cache"}, Container: container.Summary{ID: "app1", Labels: map[string]string{}}},- {Name: "db", Container: container.Summary{ID: "db1"}},- {Name: "cache", Container: container.Summary{ID: "cache1"}},- },- markedForRestart: map[string]bool{"db": true},- wantImplicit: []string{"app"},- wantMarkedAfter: map[string]bool{"db": true, "app": true},- },- }-- for _, tt := range tests {- t.Run(tt.name, func(t *testing.T) {- got := UpdateImplicitRestart(tt.containers, tt.markedForRestart)-- if len(got) != len(tt.wantImplicit) {- t.Errorf("UpdateImplicitRestart() returned %d implicit restarts, want %d", len(got), len(tt.wantImplicit))- t.Errorf("Got: %v, Want: %v", got, tt.wantImplicit)- }-- // Check implicit restart list- implicitMap := make(map[string]bool)- for _, name := range got {- implicitMap[name] = true- }- for _, want := range tt.wantImplicit {- if !implicitMap[want] {- t.Errorf("UpdateImplicitRestart() missing implicit restart for %v", want)- }- }-- // Check markedForRestart map after update- for name, want := range tt.wantMarkedAfter {- if got := tt.markedForRestart[name]; got != want {- t.Errorf("After UpdateImplicitRestart(), markedForRestart[%v] = %v, want %v", name, got, want)- }- }- })- }-}diff --git a/go.work.sum b/go.work.sumindex 87dc8f5c0..f2be75149 100644--- a/go.work.sum+++ b/go.work.sum@@ -463,6 +463,8 @@ github.com/fsouza/fake-gcs-server v1.17.0/go.mod h1:D1rTE4YCyHFNa99oyJJ5HyclvN/0github.com/gabriel-vasile/mimetype v1.4.13 h1:46nXokslUBsAJE/wMsp5gtO500a4F3Nkz9Ufpk2AcUM=github.com/gabriel-vasile/mimetype v1.4.13/go.mod h1:d+9Oxyo1wTzWdyVUPMmXFvp4F9tea18J8ufA774AB3s=github.com/getarcaneapp/arcane/types v0.0.0-20251219045603-8a9960a2bf04/go.mod h1:7Wj+0JnpYq4RQS+otyM6e4zkyJKDC01wxkWPyFCHwZA=+github.com/getarcaneapp/updater v0.3.2 h1:mSyMlb7q+EyLjGKrcMg64b+D+wVwMBkq8ZduC8PQawE=+github.com/getarcaneapp/updater v0.3.2/go.mod h1:0o8qpysU0YdEuEyCq6FtQPyuTTPDEV5Epwx7ctROAKM=github.com/getsentry/raven-go v0.2.0 h1:no+xWJRb5ZI7eE8TWgIq1jLulQiIoLG0IfYxv5JYMGs=github.com/getsentry/raven-go v0.2.0/go.mod h1:KungGk8q33+aIAZUIVWZDr2OfAEBsO49PX4NzFV5kcQ=github.com/gin-contrib/cors v1.7.7/go.mod h1:K5tW0RkzJtWSiOdikXloy8VEZlgdVNpHNw8FpjUPNrE=@@ -604,13 +606,10 @@ github.com/google/pprof v0.0.0-20211214055906-6f57359322fd/go.mod h1:KgnwoLYCZ8Igithub.com/google/pprof v0.0.0-20250820193118-f64d9cf942d6/go.mod h1:I6V7YzU0XDpsHqbsyrghnFZLO1gwK6NPTNvmetQIk9U=github.com/google/s2a-go v0.1.9 h1:LGD7gtMgezd8a/Xak7mEWL0PjoTQFvpRudN895yqKW0=github.com/google/s2a-go v0.1.9/go.mod h1:YA0Ei2ZQL3acow2O62kdp9UlnvMmU7kA6Eutn0dXayM=-github.com/google/subcommands v1.2.0/go.mod h1:ZjhPrFU+Olkh9WazFPsl27BQ4UPiG37m3yTrtFlrHVk=github.com/google/trillian v1.7.2 h1:EPBxc4YWY4Ak8tcuhyFleY+zYlbCDCa4Sn24e1Ka8Js=github.com/google/trillian v1.7.2/go.mod h1:mfQJW4qRH6/ilABtPYNBerVJAJ/upxHLX81zxNQw05s=github.com/google/uuid v1.1.2/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=github.com/google/uuid v1.2.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=-github.com/google/wire v0.7.0 h1:JxUKI6+CVBgCO2WToKy/nQk0sS+amI9z9EjVmdaocj4=-github.com/google/wire v0.7.0/go.mod h1:n6YbUQD9cPKTnHXEBN2DXlOp/mVADhVErcMFb0v3J18=github.com/googleapis/enterprise-certificate-proxy v0.3.6 h1:GW/XbdyBFQ8Qe+YAmFU9uHLo7OnF5tL52HFAgMmyrf4=github.com/googleapis/enterprise-certificate-proxy v0.3.6/go.mod h1:MkHOF77EYAE7qfSuSS9PU6g4Nt4e11cnsDUowfwewLA=github.com/googleapis/gax-go/v2 v2.15.0 h1:SyjDc1mGgZU5LncH8gimWo9lW1DtIfPibOG81vgd/bo=@@ -1154,12 +1153,9 @@ go.opentelemetry.io/otel/metric v1.35.0/go.mod h1:nKVFgxBZ2fReX6IlyW28MgZojkoAkJgo.opentelemetry.io/otel/metric v1.36.0/go.mod h1:zC7Ks+yeyJt4xig9DEw9kuUFe5C3zLbVjV2PzT6qzbs=go.opentelemetry.io/otel/metric v1.37.0/go.mod h1:04wGrZurHYKOc+RKeye86GwKiTb9FKm1WHtO+4EVr2E=go.opentelemetry.io/otel/metric v1.38.0/go.mod h1:kB5n/QoRM8YwmUahxvI3bO34eVtQf2i4utNVLr9gEmI=-go.opentelemetry.io/otel/metric/x v0.66.0/go.mod h1:d1+BDj9t96do0/1LoU1ayfCv79ZgNE41qbhBvnMOBZk=go.opentelemetry.io/otel/sdk v1.37.0/go.mod h1:VredYzxUvuo2q3WRcDnKDjbdvmO0sCzOvVAiY+yUkAg=go.opentelemetry.io/otel/sdk v1.38.0/go.mod h1:ghmNdGlVemJI3+ZB5iDEuk4bWA3GkTpW+DOoZMYBVVg=-go.opentelemetry.io/otel/sdk v1.44.0/go.mod h1:Osuydd3Se74nqjAKxid74N5eC+jfEqfTegHRnq58oK0=go.opentelemetry.io/otel/sdk/metric v1.38.0/go.mod h1:dg9PBnW9XdQ1Hd6ZnRz689CbtrUp0wMMs9iPcgT9EZA=-go.opentelemetry.io/otel/sdk/metric v1.44.0/go.mod h1:5B5pMARnXxKhltooO4xUuCBorl65a4EpnTalObqOigA=go.opentelemetry.io/otel/trace v1.35.0/go.mod h1:WUk7DtFp1Aw2MkvqGdwiXYDZZNvA/1J8o6xRXLrIkyc=go.opentelemetry.io/otel/trace v1.36.0/go.mod h1:gQ+OnDZzrybY4k4seLzPAWNwVBBVlF2szhehOBB/tGA=go.opentelemetry.io/otel/trace v1.37.0/go.mod h1:TlgrlQ+PtQO5XFerSPUYG0JSgGyryXewPGyayAWSBS0=