Modern Docker Management, Designed for Everyone
Go composecontainer-managementcontainersdockerdocker-composedocker-managementgoself-hostedsveltekittypescriptweb-ui
fix: use built in cli to upgrade arcane (#1358)
Kyle Mendell6f1d3319ab9c
diff --git a/.goreleaser.yaml b/.goreleaser.yamlindex 1f1e05feb..58148587e 100644--- a/.goreleaser.yaml+++ b/.goreleaser.yaml@@ -177,7 +177,6 @@ dockers_v2:'org.opencontainers.image.licenses': 'BSD-3-Clause''org.opencontainers.image.title': 'Arcane''org.opencontainers.image.description': 'Modern Docker Management, Made for Everyone'- 'com.getarcaneapp.arcane.updater': 'false''com.getarcaneapp.arcane': 'true'disable: '{{ if not (index .Env "BUILD_NEXT") }}true{{ end }}'sbom: true@@ -205,7 +204,6 @@ dockers_v2:'org.opencontainers.image.licenses': 'BSD-3-Clause''org.opencontainers.image.title': 'Arcane Agent''org.opencontainers.image.description': 'Arcane Agent'- 'com.getarcaneapp.arcane.updater': 'false''com.getarcaneapp.arcane.agent': 'true'disable: '{{ if not (index .Env "BUILD_NEXT") }}true{{ end }}'sbom: true@@ -233,7 +231,6 @@ dockers_v2:'org.opencontainers.image.licenses': 'BSD-3-Clause''org.opencontainers.image.title': 'Arcane''org.opencontainers.image.description': 'Modern Docker Management, Made for Everyone'- 'com.getarcaneapp.arcane.updater': 'false''com.getarcaneapp.arcane': 'true'disable: '{{ if not (index .Env "BUILD_NEXT") }}true{{ end }}'sbom: true@@ -261,7 +258,6 @@ dockers_v2:'org.opencontainers.image.licenses': 'BSD-3-Clause''org.opencontainers.image.title': 'Arcane Agent''org.opencontainers.image.description': 'Arcane Agent'- 'com.getarcaneapp.arcane.updater': 'false''com.getarcaneapp.arcane.agent': 'true'disable: '{{ if not (index .Env "BUILD_NEXT") }}true{{ end }}'sbom: truediff --git a/backend/internal/bootstrap/services_bootstrap.go b/backend/internal/bootstrap/services_bootstrap.goindex a2cee2256..e5f5d973d 100644--- a/backend/internal/bootstrap/services_bootstrap.go+++ b/backend/internal/bootstrap/services_bootstrap.go@@ -71,10 +71,10 @@ func initializeServices(ctx context.Context, db *database.DB, cfg *config.Configsvcs.Auth = services.NewAuthService(svcs.User, svcs.Settings, svcs.Event, cfg.JWTSecret, cfg)svcs.Oidc = services.NewOidcService(svcs.Auth, cfg, httpClient)svcs.ApiKey = services.NewApiKeyService(db, svcs.User)- svcs.Updater = services.NewUpdaterService(db, svcs.Settings, svcs.Docker, svcs.Project, svcs.ImageUpdate, svcs.ContainerRegistry, svcs.Event, svcs.Image, svcs.Notification)svcs.System = services.NewSystemService(db, svcs.Docker, svcs.Container, svcs.Image, svcs.Volume, svcs.Network, svcs.Settings)svcs.Version = services.NewVersionService(httpClient, cfg.UpdateCheckDisabled, config.Version, config.Revision, svcs.ContainerRegistry, svcs.Docker)svcs.SystemUpgrade = services.NewSystemUpgradeService(svcs.Docker, svcs.Version, svcs.Event)+ svcs.Updater = services.NewUpdaterService(db, svcs.Settings, svcs.Docker, svcs.Project, svcs.ImageUpdate, svcs.ContainerRegistry, svcs.Event, svcs.Image, svcs.Notification, svcs.SystemUpgrade)return svcs, dockerClient, nil}diff --git a/backend/internal/services/updater_service.go b/backend/internal/services/updater_service.goindex 341745a9b..3661b98b5 100644--- a/backend/internal/services/updater_service.go+++ b/backend/internal/services/updater_service.go@@ -31,6 +31,7 @@ type UpdaterService struct {eventService *EventServiceimageService *ImageServicenotificationService *NotificationService+ upgradeService *SystemUpgradeServiceupdatingContainers map[string]boolupdatingProjects map[string]bool@@ -46,6 +47,7 @@ func NewUpdaterService(events *EventService,imageSvc *ImageService,notifications *NotificationService,+ upgrade *SystemUpgradeService,) *UpdaterService {return &UpdaterService{db: db,@@ -57,6 +59,7 @@ func NewUpdaterService(eventService: events,imageService: imageSvc,notificationService: notifications,+ upgradeService: upgrade,updatingContainers: map[string]bool{},updatingProjects: map[string]bool{},}@@ -347,6 +350,8 @@ func (s *UpdaterService) UpdateSingleContainer(ctx context.Context, containerIDstart := time.Now()out := &updater.Result{Items: []updater.ResourceResult{}}+ slog.InfoContext(ctx, "UpdateSingleContainer: starting", "containerID", containerID)+dcli, err := s.dockerService.GetClient()if err != nil {return nil, fmt.Errorf("docker connect: %w", err)@@ -368,6 +373,7 @@ func (s *UpdaterService) UpdateSingleContainer(ctx context.Context, containerID}containerName := s.getContainerName(*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)inspectBefore, err := dcli.ContainerInspect(ctx, targetContainer.ID)@@ -388,7 +394,16 @@ func (s *UpdaterService) UpdateSingleContainer(ctx context.Context, containerIDif inspectBefore.Config != nil && inspectBefore.Config.Labels != nil {labels = inspectBefore.Config.Labels}++ isArcaneContainer := arcaneupdater.IsArcaneContainer(labels)+ slog.InfoContext(ctx, "UpdateSingleContainer: inspected container",+ "containerID", containerID,+ "imageID", inspectBefore.Image,+ "isArcane", isArcaneContainer,+ "hasArcaneLabel", labels["com.getarcaneapp.arcane"])+if arcaneupdater.IsUpdateDisabled(labels) {+ slog.InfoContext(ctx, "UpdateSingleContainer: updates disabled by label", "containerID", containerID)out.Items = append(out.Items, updater.ResourceResult{ResourceID: targetContainer.ID,ResourceType: "container",@@ -439,7 +454,17 @@ func (s *UpdaterService) UpdateSingleContainer(ctx context.Context, containerID// Compare with pulled image to avoid unnecessary restartchecker := arcaneupdater.NewDigestChecker(dcli, arcRegistry.NewClient())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",@@ -455,6 +480,42 @@ func (s *UpdaterService) UpdateSingleContainer(ctx context.Context, containerIDinspect := 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 arcaneupdater.IsArcaneContainer(containerLabels) && s.upgradeService != nil {+ slog.InfoContext(ctx, "UpdateSingleContainer: detected Arcane self-update, using CLI upgrade method", "containerID", containerID)++ if err := s.upgradeService.TriggerUpgradeViaCLI(ctx, systemUser); err != nil {+ out.Items = append(out.Items, updater.ResourceResult{+ ResourceID: targetContainer.ID,+ ResourceType: "container",+ ResourceName: containerName,+ Status: "failed",+ Error: fmt.Sprintf("CLI upgrade 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()++ slog.InfoContext(ctx, "UpdateSingleContainer: CLI upgrade triggered successfully", "containerID", containerID)+ return out, nil+ }+// Update the containerif err := s.updateContainer(ctx, *targetContainer, inspect, normalizedRef); err != nil {out.Items = append(out.Items, updater.ResourceResult{@@ -576,44 +637,30 @@ func (s *UpdaterService) updateContainer(ctx context.Context, cnt container.Summname := s.getContainerName(cnt)labels := inspect.Config.LabelsisArcane := arcaneupdater.IsArcaneContainer(labels)- var selfUpdate *arcaneupdater.SelfUpdate++ // Arcane containers should always use CLI upgrade, not inline update+ // This method should not be called for Arcane containersif isArcane {- selfUpdate = arcaneupdater.NewSelfUpdate(dcli)- if ok, ierr := selfUpdate.IsArcaneContainerByID(ctx, cnt.ID); ierr != nil {- slog.WarnContext(ctx, "updateContainer: failed to verify Arcane container by ID", "containerId", cnt.ID, "error", ierr.Error())- } else if !ok {- // Keep behavior label-driven, but log the inconsistency.- slog.WarnContext(ctx, "updateContainer: label indicated Arcane container but ID verification did not", "containerId", cnt.ID, "containerName", name)- }+ slog.ErrorContext(ctx, "updateContainer: called for Arcane container - should use CLI upgrade instead", "containerId", cnt.ID, "containerName", name)+ return fmt.Errorf("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)- // Execute pre-update lifecycle hook (skip for Arcane self-update)- if !isArcane {- hookResult := arcaneupdater.ExecutePreUpdateCommand(ctx, dcli, cnt.ID, labels)- if hookResult.Executed {- if hookResult.SkipUpdate {- slog.InfoContext(ctx, "updateContainer: container requested skip via pre-update hook", "containerId", cnt.ID, "containerName", name)- return fmt.Errorf("container requested skip update via exit code %d", arcaneupdater.ExitCodeSkipUpdate)- }- if hookResult.Error != nil {- slog.WarnContext(ctx, "updateContainer: pre-update hook failed", "containerId", cnt.ID, "err", hookResult.Error)- // Continue with update despite hook failure (configurable in future)- }+ // Execute pre-update lifecycle hook+ hookResult := arcaneupdater.ExecutePreUpdateCommand(ctx, dcli, cnt.ID, labels)+ if hookResult.Executed {+ if hookResult.SkipUpdate {+ slog.InfoContext(ctx, "updateContainer: container requested skip via pre-update hook", "containerId", cnt.ID, "containerName", name)+ return fmt.Errorf("container requested skip update via exit code %d", arcaneupdater.ExitCodeSkipUpdate)+ }+ if hookResult.Error != nil {+ slog.WarnContext(ctx, "updateContainer: pre-update hook failed", "containerId", cnt.ID, "err", hookResult.Error)+ // Continue with update despite hook failure (configurable in future)}}- // For Arcane self-update: rename the old container so new one can use the same nameoriginalName := inspect.Name- if isArcane {- tempName, renameErr := selfUpdate.PrepareForSelfUpdate(ctx, cnt.ID, originalName)- if renameErr != nil {- slog.WarnContext(ctx, "updateContainer: failed to rename Arcane container for self-update", "err", renameErr)- return fmt.Errorf("cannot proceed with self-update without renaming old container: %w", renameErr)- }- slog.InfoContext(ctx, "updateContainer: renamed Arcane container for self-update", "oldName", originalName, "tempName", tempName)- }// Get custom stop signal if configuredstopSignal := arcaneupdater.GetStopSignal(labels)@@ -623,21 +670,19 @@ func (s *UpdaterService) updateContainer(ctx context.Context, cnt container.Summslog.DebugContext(ctx, "updateContainer: using custom stop signal", "signal", stopSignal)}- // stop (skip for Arcane - it will be stopped after new one starts)- if !isArcane {- 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"})+ // 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- if err := dcli.ContainerRemove(ctx, cnt.ID, container.RemoveOptions{}); 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"})+ // Remove the container+ if err := dcli.ContainerRemove(ctx, cnt.ID, container.RemoveOptions{}); 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 refcfg := inspect.Config@@ -680,33 +725,11 @@ func (s *UpdaterService) updateContainer(ctx context.Context, cnt container.Summ}_ = s.eventService.LogContainerEvent(ctx, models.EventTypeContainerStart, resp.ID, name, systemUser.ID, systemUser.Username, "0", models.JSON{"action": "updater_start"})- // For Arcane self-update: now stop and remove the old container- if isArcane {- slog.InfoContext(ctx, "updateContainer: Arcane self-update - stopping old container", "oldContainerId", cnt.ID)- _ = dcli.ContainerStop(ctx, cnt.ID, container.StopOptions{})- _ = dcli.ContainerRemove(ctx, cnt.ID, container.RemoveOptions{Force: true})-- // Best-effort cleanup of any leftover arcane-old-* containers from prior self-updates.- if selfUpdate != nil {- if removed, cerr := selfUpdate.CleanupOldArcaneInstances(ctx, false); cerr != nil {- slog.DebugContext(ctx, "updateContainer: CleanupOldArcaneInstances failed", "error", cerr.Error())- } else if len(removed) > 0 {- slog.InfoContext(ctx, "updateContainer: cleaned up old Arcane instances", "count", len(removed))- }-- if cur, gerr := selfUpdate.GetCurrentArcaneContainer(ctx); gerr == nil && cur != nil {- slog.InfoContext(ctx, "updateContainer: current Arcane container after self-update", "containerId", cur.ID, "name", arcaneupdater.ExtractContainerName(*cur))- }- }- }-// Execute post-update lifecycle hook on the new container- if !isArcane {- hookResult := arcaneupdater.ExecutePostUpdateCommand(ctx, dcli, resp.ID, labels)- if hookResult.Executed && hookResult.Error != nil {- slog.WarnContext(ctx, "updateContainer: post-update hook failed", "newContainerId", resp.ID, "err", hookResult.Error)- // Log but don't fail the update- }+ hookResult = arcaneupdater.ExecutePostUpdateCommand(ctx, dcli, resp.ID, labels)+ if hookResult.Executed && hookResult.Error != nil {+ slog.WarnContext(ctx, "updateContainer: post-update hook failed", "newContainerId", resp.ID, "err", hookResult.Error)+ // Log but don't fail the update}_ = s.eventService.LogContainerEvent(ctx, models.EventTypeContainerUpdate, resp.ID, name, systemUser.ID, systemUser.Username, "0", models.JSON{@@ -1113,7 +1136,21 @@ func (s *UpdaterService) restartContainersUsingOldIDs(ctx context.Context, oldIDslog.DebugContext(ctx, "restartContainersUsingOldIDs: restarting container", "containerId", p.cnt.ID, "container", name, "match", p.match, "newRef", p.newRef, "implicit", p.implicit)- if err := s.updateContainer(ctx, p.cnt, p.inspect, p.newRef); err != nil {+ // Check if this is Arcane self-update - use CLI upgrade instead+ if arcaneupdater.IsArcaneContainer(labels) && s.upgradeService != nil {+ slog.InfoContext(ctx, "restartContainersUsingOldIDs: detected Arcane self-update, using CLI upgrade method", "containerId", p.cnt.ID, "container", name)++ if err := s.upgradeService.TriggerUpgradeViaCLI(ctx, systemUser); err != nil {+ res.Status = "failed"+ res.Error = fmt.Sprintf("CLI upgrade failed: %v", err)+ slog.WarnContext(ctx, "restartContainersUsingOldIDs: CLI upgrade failed", "containerId", p.cnt.ID, "err", err)+ } 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)diff --git a/backend/internal/services/updater_service_test.go b/backend/internal/services/updater_service_test.gonew file mode 100644index 000000000..2c7610475--- /dev/null+++ b/backend/internal/services/updater_service_test.go@@ -0,0 +1,231 @@+package services++import (+ "context"+ "errors"+ "testing"++ "github.com/stretchr/testify/assert"+ "github.com/stretchr/testify/require"++ "github.com/getarcaneapp/arcane/backend/internal/models"+ "github.com/getarcaneapp/arcane/backend/internal/utils/arcaneupdater"+)++// mockSystemUpgradeService is a simple mock implementation for testing+type mockSystemUpgradeService struct {+ triggerCalled bool+ triggerError error+ capturedUser *models.User+ canUpgrade bool+}++func (m *mockSystemUpgradeService) TriggerUpgradeViaCLI(ctx context.Context, user models.User) error {+ m.triggerCalled = true+ m.capturedUser = &user+ return 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) {+ ctx := context.Background()++ // 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 := arcaneupdater.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")+}++// TestUpdaterService_NonArcaneLabel_DoesNotTriggerCLI verifies that containers without+// the Arcane label do not trigger CLI upgrade+func TestUpdaterService_NonArcaneLabel_DoesNotTriggerCLI(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 := arcaneupdater.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")+}++// 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 := arcaneupdater.IsArcaneContainer(labels)+ assert.True(t, isArcane, "Should detect Arcane container")++ // 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")+}++// TestUpdaterService_NilUpgradeService_GracefulHandling verifies graceful handling+// when upgrade service is nil+func TestUpdaterService_NilUpgradeService_GracefulHandling(t *testing.T) {+ var mockUpgrade *mockSystemUpgradeService = nil++ labels := map[string]string{+ "com.getarcaneapp.arcane": "true",+ }++ isArcane := arcaneupdater.IsArcaneContainer(labels)+ assert.True(t, isArcane, "Should detect Arcane container")++ // When upgradeService is nil, ensure we don't attempt to call it.+ assert.Nil(t, mockUpgrade, "Upgrade service should be nil; should not attempt to call it")++ // Test passes if no panic occurs+}++// 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 := arcaneupdater.IsArcaneContainer(tt.labels)+ assert.Equal(t, tt.expectedArcane, isArcane, tt.description)+ })+ }+}++// 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 := arcaneupdater.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)+}++// TestUpdaterService_UpgradeServiceNotNilCheck verifies the nil check logic+func TestUpdaterService_UpgradeServiceNotNilCheck(t *testing.T) {+ ctx := context.Background()++ labels := map[string]string{+ "com.getarcaneapp.arcane": "true",+ }++ // Test with non-nil upgrade service+ mockUpgrade := &mockSystemUpgradeService{}+ isArcane := arcaneupdater.IsArcaneContainer(labels)++ // This is the actual logic from restartContainersUsingOldIDs+ if isArcane {+ _ = mockUpgrade.TriggerUpgradeViaCLI(ctx, systemUser)+ }++ assert.True(t, mockUpgrade.triggerCalled, "Should call CLI upgrade when service is not nil")+}diff --git a/backend/internal/utils/arcaneupdater/selfupdate.go b/backend/internal/utils/arcaneupdater/selfupdate.godeleted file mode 100644index a8f3e8a38..000000000--- a/backend/internal/utils/arcaneupdater/selfupdate.go+++ /dev/null@@ -1,164 +0,0 @@-package arcaneupdater--import (- "context"- "crypto/rand"- "log/slog"- "strconv"- "strings"- "time"-- "github.com/docker/docker/api/types/container"- "github.com/docker/docker/api/types/filters"- "github.com/docker/docker/client"-)--// SelfUpdate handles the special case of updating the Arcane container itself-type SelfUpdate struct {- dcli *client.Client-}--// NewSelfUpdate creates a new SelfUpdate handler-func NewSelfUpdate(dcli *client.Client) *SelfUpdate {- return &SelfUpdate{dcli: dcli}-}--// IsArcaneContainerByID checks if a container ID belongs to an Arcane container-func (s *SelfUpdate) IsArcaneContainerByID(ctx context.Context, containerID string) (bool, error) {- inspect, err := s.dcli.ContainerInspect(ctx, containerID)- if err != nil {- return false, err- }-- if inspect.Config == nil {- return false, nil- }-- return IsArcaneContainer(inspect.Config.Labels), nil-}--// PrepareForSelfUpdate renames the current Arcane container so the new one can use its name-// Returns the new temporary name assigned to the old container-func (s *SelfUpdate) PrepareForSelfUpdate(ctx context.Context, containerID string, originalName string) (string, error) {- // Generate a random temporary name- tempName := generateTempName()-- slog.InfoContext(ctx, "PrepareForSelfUpdate: renaming Arcane container for self-update", "containerID", containerID, "originalName", originalName, "tempName", tempName)-- if err := s.dcli.ContainerRename(ctx, containerID, tempName); err != nil {- return "", err- }-- return tempName, nil-}--// CleanupOldArcaneInstances finds and removes old Arcane container instances-// This should be called on startup to clean up any leftover containers from previous updates-func (s *SelfUpdate) CleanupOldArcaneInstances(ctx context.Context, keepNewest bool) ([]string, error) {- // Find all containers with the Arcane label- filterArgs := filters.NewArgs()- filterArgs.Add("label", LabelArcane+"=true")-- containers, err := s.dcli.ContainerList(ctx, container.ListOptions{- All: true,- Filters: filterArgs,- })- if err != nil {- return nil, err- }-- // Only remove containers that were renamed by Arcane self-update.- // This avoids deleting legitimate multi-instance Arcane containers.- old := make([]container.Summary, 0, len(containers))- for _, c := range containers {- name := ExtractContainerName(c)- if strings.HasPrefix(name, "arcane-old-") {- old = append(old, c)- }- }-- if len(old) == 0 {- return nil, nil // Nothing to clean up- }-- // Sort by creation time (newest first)- sortByCreated(old)-- var removed []string- startIdx := 0- if keepNewest {- startIdx = 1 // Skip the newest container- }-- for _, c := range old[startIdx:] {- name := ExtractContainerName(c)-- slog.InfoContext(ctx, "CleanupOldArcaneInstances: removing old Arcane instance", "containerID", c.ID, "name", name, "created", c.Created)-- // Stop if running- if c.State == "running" {- timeout := 30 // seconds- if err := s.dcli.ContainerStop(ctx, c.ID, container.StopOptions{Timeout: &timeout}); err != nil {- slog.WarnContext(ctx, "CleanupOldArcaneInstances: failed to stop container", "containerID", c.ID, "error", err)- continue- }- }-- // Remove container- if err := s.dcli.ContainerRemove(ctx, c.ID, container.RemoveOptions{Force: true}); err != nil {- slog.WarnContext(ctx, "CleanupOldArcaneInstances: failed to remove container", "containerID", c.ID, "error", err)- continue- }-- removed = append(removed, c.ID)- }-- return removed, nil-}--// GetCurrentArcaneContainer returns the currently running Arcane container, if any-func (s *SelfUpdate) GetCurrentArcaneContainer(ctx context.Context) (*container.Summary, error) {- filterArgs := filters.NewArgs()- filterArgs.Add("label", LabelArcane+"=true")- filterArgs.Add("status", "running")-- containers, err := s.dcli.ContainerList(ctx, container.ListOptions{- Filters: filterArgs,- })- if err != nil {- return nil, err- }-- if len(containers) == 0 {- return nil, nil- }-- // Return the newest running instance- sortByCreated(containers)- return &containers[0], nil-}--// sortByCreated sorts containers by creation time, newest first-func sortByCreated(containers []container.Summary) {- for i := 0; i < len(containers)-1; i++ {- for j := i + 1; j < len(containers); j++ {- if containers[i].Created < containers[j].Created {- containers[i], containers[j] = containers[j], containers[i]- }- }- }-}--// generateTempName generates a random temporary name for the old container-func generateTempName() string {- const charset = "abcdefghijklmnopqrstuvwxyz0123456789"- b := make([]byte, 8)- if _, err := rand.Read(b); err != nil {- // Extremely unlikely, but avoid failing the update due to entropy issues.- return "arcane-old-fallback-" + strconv.FormatInt(time.Now().UnixNano(), 36)- }- for i := range b {- b[i] = charset[int(b[i])%len(charset)]- }- return "arcane-old-" + string(b)-}diff --git a/backend/internal/utils/arcaneupdater/selfupdate_test.go b/backend/internal/utils/arcaneupdater/selfupdate_test.godeleted file mode 100644index 7ea61ee9d..000000000--- a/backend/internal/utils/arcaneupdater/selfupdate_test.go+++ /dev/null@@ -1,142 +0,0 @@-package arcaneupdater--import (- "strings"- "testing"- "time"-- "github.com/docker/docker/api/types/container"-)--func TestGenerateTempName(t *testing.T) {- names := make(map[string]bool)-- for i := 0; i < 10; i++ {- name := generateTempName()-- if !strings.HasPrefix(name, "arcane-old-") {- t.Errorf("generateTempName() = %q, want prefix 'arcane-old-'", name)- }-- if len(name) != 19 {- t.Errorf("generateTempName() length = %d, want 19", len(name))- }-- // Check for valid alphanumeric chars- suffix := strings.TrimPrefix(name, "arcane-old-")- for _, c := range suffix {- if (c < 'a' || c > 'z') && (c < '0' || c > '9') {- t.Errorf("generateTempName() suffix contains invalid char: %c in %q", c, suffix)- }- }-- names[name] = true- }-- // Should have unique names- if len(names) < 9 {- t.Errorf("generateTempName() not unique enough: %d unique out of 10", len(names))- }-}--func TestSortByCreated(t *testing.T) {- now := time.Now()-- tests := []struct {- name string- containers []container.Summary- want []string // Expected order (newest first)- }{- {- name: "empty list",- containers: []container.Summary{},- want: []string{},- },- {- name: "single container",- containers: []container.Summary{- {ID: "abc", Created: now.Unix()},- },- want: []string{"abc"},- },- {- name: "two containers - newest first",- containers: []container.Summary{- {ID: "older", Created: now.Add(-1 * time.Hour).Unix()},- {ID: "newer", Created: now.Unix()},- },- want: []string{"newer", "older"},- },- {- name: "three containers - newest first",- containers: []container.Summary{- {ID: "oldest", Created: now.Add(-2 * time.Hour).Unix()},- {ID: "middle", Created: now.Add(-1 * time.Hour).Unix()},- {ID: "newest", Created: now.Unix()},- },- want: []string{"newest", "middle", "oldest"},- },- }-- for _, tt := range tests {- t.Run(tt.name, func(t *testing.T) {- containers := make([]container.Summary, len(tt.containers))- copy(containers, tt.containers)-- sortByCreated(containers)-- if len(containers) != len(tt.want) {- t.Errorf("sortByCreated() len = %d, want %d", len(containers), len(tt.want))- return- }-- for i, want := range tt.want {- if containers[i].ID != want {- t.Errorf("sortByCreated()[%d].ID = %q, want %q", i, containers[i].ID, want)- }- }- })- }-}--func TestNewSelfUpdate(t *testing.T) {- su := NewSelfUpdate(nil)-- // NewSelfUpdate always returns a valid instance- if su.dcli != nil {- t.Error("NewSelfUpdate(nil) should set dcli to nil")- }-}--func TestGenerateTempName_ValidDockerName(t *testing.T) {- name := generateTempName()-- // Docker container names must match [a-zA-Z0-9][a-zA-Z0-9_.-]*- for i, c := range name {- valid := (c >= 'a' && c <= 'z') ||- (c >= 'A' && c <= 'Z') ||- (c >= '0' && c <= '9') ||- c == '-' || c == '_' || c == '.'-- if !valid {- t.Errorf("generateTempName()[%d] = %c is not valid for Docker container name", i, c)- }- }-}--func TestSortByCreated_SameTimestamp(t *testing.T) {- now := time.Now().Unix()-- containers := []container.Summary{- {ID: "first", Created: now},- {ID: "second", Created: now},- {ID: "third", Created: now},- }-- sortByCreated(containers)-- // Order should be preserved since all have same timestamp- if containers[0].ID != "first" || containers[1].ID != "second" || containers[2].ID != "third" {- t.Errorf("sortByCreated() not stable for equal elements")- }-}diff --git a/docker/Dockerfile b/docker/Dockerfileindex bf6141525..e918a32e4 100644--- a/docker/Dockerfile+++ b/docker/Dockerfile@@ -95,7 +95,6 @@ org.opencontainers.image.licenses="BSD-3-Clause" \org.opencontainers.image.ref.name="arcane" \org.opencontainers.image.title="Arcane" \org.opencontainers.image.description="Modern Docker Management, Made for Everyone" \-com.getarcaneapp.arcane.updater="false" \com.getarcaneapp.arcane="true"CMD ["./arcane"]\ No newline at end of filediff --git a/docker/Dockerfile-agent b/docker/Dockerfile-agentindex 9d76c2fc1..c10f464ea 100644--- a/docker/Dockerfile-agent+++ b/docker/Dockerfile-agent@@ -73,7 +73,6 @@ LABEL org.opencontainers.image.ref.name="arcane-agent"LABEL org.opencontainers.image.title="Arcane Agent"LABEL org.opencontainers.image.description="Arcane Agent"-LABEL com.getarcaneapp.arcane.updater="false"LABEL com.getarcaneapp.arcane.agent="true"EXPOSE 3553diff --git a/frontend/src/routes/(app)/containers/container-table.svelte b/frontend/src/routes/(app)/containers/container-table.svelteindex ec603018a..d980eabb7 100644--- a/frontend/src/routes/(app)/containers/container-table.svelte+++ b/frontend/src/routes/(app)/containers/container-table.svelte@@ -196,6 +196,7 @@message: m.containers_update_confirm_message({ name: containerName }),confirm: {label: m.containers_update_container(),+ destructive: false,action: async () => {actionStatus[container.id] = 'updating';try {