Modern Docker Management, Designed for Everyone
Go composecontainer-managementcontainersdockerdocker-composedocker-managementgoself-hostedsveltekittypescriptweb-ui
fix: project auto update not updating container properly (#2787)
Kyle Mendella6a106a6ff97
diff --git a/backend/internal/services/updater_service.go b/backend/internal/services/updater_service.goindex b868b6310..cc564358c 100644--- a/backend/internal/services/updater_service.go+++ b/backend/internal/services/updater_service.go@@ -144,7 +144,7 @@ func (s *UpdaterService) ApplyPending(ctx context.Context, dryRun bool) (out *upcontinue}oldRef := fmt.Sprintf("%s:%s", r.Repository, r.Tag)- oldNorm := normalizeImageUpdateRefInternal(oldRef)+ oldNorm := libupdater.NormalizeImageUpdateRef(oldRef)if oldNorm == "" {slog.DebugContext(ctx, "ApplyPending: skipping invalid pending image reference", "imageRef", oldRef)continue@@ -160,6 +160,7 @@ func (s *UpdaterService) ApplyPending(ctx context.Context, dryRun bool) (out *up}oldIDs, _ := s.resolveLocalImageIDsForRef(ctx, oldRef)+ oldIDs = libupdater.AppendImageUpdateRecordIDToOldIDs(oldIDs, r.ID)plans = append(plans, updatePlan{oldRef: oldRef, newRef: newRef, oldIDs: oldIDs})}@@ -220,7 +221,7 @@ func (s *UpdaterService) ApplyPending(ctx context.Context, dryRun bool) (out *up// 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 := normalizeImageUpdateRefInternal(p.newRef)+ normNew := libupdater.NormalizeImageUpdateRef(p.newRef)check := digestChecker.CheckImageNeedsUpdate(ctx, normNew)skipPull := false@@ -617,7 +618,7 @@ func (s *UpdaterService) UpdateSingleContainer(ctx context.Context, containerIDslog.DebugContext(ctx, "UpdateSingleContainer: failed to inspect container image for fallback refs", "containerID", containerID, "imageID", inspectBefore.Image, "error", inspectErr)}}- if imageRef == "" || isImageIDLikeReferenceInternal(imageRef) {+ if imageRef == "" || libupdater.IsImageIDLikeReference(imageRef) {out.Items = append(out.Items, updater.ResourceResult{ResourceID: targetContainer.ID,ResourceType: "container",@@ -630,7 +631,7 @@ func (s *UpdaterService) UpdateSingleContainer(ctx context.Context, containerIDreturn out, nil}- normalizedRef := normalizeImageUpdateRefInternal(imageRef)+ normalizedRef := libupdater.NormalizeImageUpdateRef(imageRef)repo, tag := s.parseRepoAndTag(normalizedRef)if repo == "" || tag == "" {@@ -1060,16 +1061,8 @@ func buildUpdaterRecreateNetworkingConfigInternal(networkMode container.NetworkMreturn &network.NetworkingConfig{EndpointsConfig: sanitizedEndpointsConfig}}-func normalizeImageUpdateRefInternal(imageRef string) string {- parts, err := libupdater.NormalizeReference(imageRef)- if err != nil {- return ""- }- return parts.NormalizedRef-}-func addNormalizedImageUpdateRefInternal(ctx context.Context, out map[string]struct{}, imageRef, logMessage string, attrs ...any) {- normalizedRef := normalizeImageUpdateRefInternal(imageRef)+ normalizedRef := libupdater.NormalizeImageUpdateRef(imageRef)if normalizedRef != "" {out[normalizedRef] = struct{}{}return@@ -1126,7 +1119,7 @@ func (s *UpdaterService) collectUsedImagesFromContainersInternal(ctx context.Con}imageRef := strings.TrimSpace(c.Image)- if imageRef != "" && !isImageIDLikeReferenceInternal(imageRef) {+ if imageRef != "" && !libupdater.IsImageIDLikeReference(imageRef) {addNormalizedImageUpdateRefInternal(ctx, out, imageRef, "collectUsedImagesFromContainersInternal: skipping invalid image reference", "containerId", c.ID)continue}@@ -1164,11 +1157,6 @@ func (s *UpdaterService) buildExcludedContainerSetInternal(ctx context.Context)return excluded}-func isImageIDLikeReferenceInternal(ref string) bool {- ref = strings.ToLower(strings.TrimSpace(ref))- return strings.HasPrefix(ref, "sha256:")-}-// Aggregate images in use across containers and compose projectsfunc (s *UpdaterService) collectUsedImages(ctx context.Context) (map[string]struct{}, error) {out := map[string]struct{}{}@@ -1273,7 +1261,7 @@ func (s *UpdaterService) collectUsedImagesFromComposeContainersInternal(ctx cont}imageRef := strings.TrimSpace(c.Image)- if imageRef == "" || isImageIDLikeReferenceInternal(imageRef) {+ if imageRef == "" || libupdater.IsImageIDLikeReference(imageRef) {continue}addNormalizedImageUpdateRefInternal(ctx, out, imageRef, "collectUsedImagesFromComposeContainersInternal: skipping invalid image reference", "containerId", c.ID)@@ -1400,7 +1388,7 @@ func (s *UpdaterService) restartContainersUsingOldIDs(ctx context.Context, oldIDupdatedNorm := map[string]string{}for oldRef, nr := range oldRefToNewRef {- if normalizedRef := normalizeImageUpdateRefInternal(oldRef); normalizedRef != "" {+ if normalizedRef := libupdater.NormalizeImageUpdateRef(oldRef); normalizedRef != "" {updatedNorm[normalizedRef] = nr} else {slog.DebugContext(ctx, "restartContainersUsingOldIDs: skipping invalid old image reference", "imageRef", oldRef)@@ -1466,7 +1454,17 @@ func (s *UpdaterService) restartContainersUsingOldIDs(ctx context.Context, oldIDName: name,})- newRef, match := s.resolveContainerImageMatchInternal(c, oldIDToNewRef, updatedNorm)+ 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@@ -1476,15 +1474,16 @@ func (s *UpdaterService) restartContainersUsingOldIDs(ctx context.Context, oldIDtargetImageIDs[newRef] = tids}- if c.ImageID != "" && slices.Contains(tids, c.ImageID) {+ currentImageID := libupdater.CurrentContainerImageID(c, inspected)+ if currentImageID != "" && slices.Contains(tids, currentImageID) {// Already on target imageslog.InfoContext(ctx, "restartContainersUsingOldIDs: container already on target image; skipping restart",- "containerId", c.ID, "containerName", name, "imageID", c.ImageID, "newRef", newRef)+ "containerId", c.ID, "containerName", name, "imageID", currentImageID, "newRef", newRef)newRef = ""}}- p := &restartPlan{cnt: c, newRef: newRef, match: match, explicit: newRef != ""}+ p := &restartPlan{cnt: c, inspect: inspected, newRef: newRef, match: match, explicit: newRef != ""}plansByName[name] = pif p.explicit {markedForRestart[name] = true@@ -1496,6 +1495,11 @@ func (s *UpdaterService) restartContainersUsingOldIDs(ctx context.Context, oldIDif 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@@ -1626,7 +1630,7 @@ func (s *UpdaterService) restartContainersUsingOldIDs(ctx context.Context, oldIDResourceType: "container",Status: "checked",OldImages: map[string]string{"main": p.match},- NewImages: map[string]string{"main": normalizeImageUpdateRefInternal(p.newRef)},+ NewImages: map[string]string{"main": libupdater.NormalizeImageUpdateRef(p.newRef)},}if p.newRef == "" {@@ -1672,13 +1676,20 @@ func (s *UpdaterService) restartContainersUsingOldIDs(ctx context.Context, oldIDif 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 = trueres.UpdateApplied = true// Send notificationif s.notificationService != nil {- if notifErr := s.notificationService.SendContainerUpdateNotification(ctx, name, p.newRef, p.match, normalizeImageUpdateRefInternal(p.newRef)); notifErr != 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())}}@@ -1707,7 +1718,7 @@ func (s *UpdaterService) restartContainersUsingOldIDs(ctx context.Context, oldID// Send notification after successful container updateif s.notificationService != nil {- if notifErr := s.notificationService.SendContainerUpdateNotification(ctx, name, p.newRef, p.match, normalizeImageUpdateRefInternal(p.newRef)); notifErr != 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())}}@@ -1904,41 +1915,18 @@ func (s *UpdaterService) statusSnapshotInternal() updater.Status {}}-func (s *UpdaterService) resolveContainerImageMatchInternal(c container.Summary, 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- }- }-- imageRef := strings.TrimSpace(c.Image)- if imageRef == "" || isImageIDLikeReferenceInternal(imageRef) {- return "", ""- }-- norm := normalizeImageUpdateRefInternal(imageRef)- if norm == "" {- return "", ""- }- if nr, ok := updatedNorm[norm]; ok {- return nr, norm- }-- return "", ""-}-func resolvePullableImageRefInternal(summaryImage, inspectConfigImage string, repoTags []string) (ref, source string) {- if image := strings.TrimSpace(inspectConfigImage); image != "" && !isImageIDLikeReferenceInternal(image) {+ if image := strings.TrimSpace(inspectConfigImage); image != "" && !libupdater.IsImageIDLikeReference(image) {return image, "container_inspect_config"}- if image := strings.TrimSpace(summaryImage); image != "" && !isImageIDLikeReferenceInternal(image) {+ 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>" || isImageIDLikeReferenceInternal(trimmed) {+ if trimmed == "" || trimmed == "<none>:<none>" || libupdater.IsImageIDLikeReference(trimmed) {continue}return trimmed, "image_repo_tag"diff --git a/backend/internal/services/updater_service_test.go b/backend/internal/services/updater_service_test.goindex c1e63877c..3e91e7a4a 100644--- a/backend/internal/services/updater_service_test.go+++ b/backend/internal/services/updater_service_test.go@@ -8,15 +8,20 @@ import ("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/stretchr/testify/assert"@@ -485,6 +490,120 @@ func TestUpdaterService_LazyRegisterComposeProjectInternal_AddsServicesForRegistassert.Equal(t, project.ID, projectNameToID[loader.NormalizeProjectName(project.Name)])}+func TestUpdaterService_RestartContainersUsingOldIDsMatchesComposeConfigImageInternal(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))++ 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))++ 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+ })++ 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{}{}@@ -511,13 +630,6 @@ func TestAnyImageIDsInUseSet(t *testing.T) {assert.False(t, anyImageIDsInUseSetInternal([]string{"sha256:one"}, nil))}-func TestIsImageIDLikeReference(t *testing.T) {- assert.True(t, isImageIDLikeReferenceInternal("sha256:abcdef"))- assert.True(t, isImageIDLikeReferenceInternal("SHA256:ABCDEF"))- assert.False(t, isImageIDLikeReferenceInternal("nginx:latest"))- assert.False(t, isImageIDLikeReferenceInternal("docker.io/library/nginx:latest"))-}-func TestCollectUsedImagesFromContainers_FastPathSkipsInspectLikeRefs(t *testing.T) {out := map[string]struct{}{}@@ -530,14 +642,14 @@ func TestCollectUsedImagesFromContainers_FastPathSkipsInspectLikeRefs(t *testing}for _, c := range containers {- if c.Image != "" && !isImageIDLikeReferenceInternal(c.Image) {+ if c.Image != "" && !libupdater.IsImageIDLikeReference(c.Image) {addNormalizedImageUpdateRefInternal(context.Background(), out, c.Image, "test skip invalid image reference")}}- assert.Contains(t, out, normalizeImageUpdateRefInternal("nginx:latest"))- assert.Contains(t, out, normalizeImageUpdateRefInternal("redis:7"))- assert.NotContains(t, out, normalizeImageUpdateRefInternal("sha256:abcdef"))+ 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, "")}@@ -850,81 +962,13 @@ func TestCollectUsedImagesFromComposeContainersInternal(t *testing.T) {svc.collectUsedImagesFromComposeContainersInternal(context.Background(), composeContainers, activeProjects, out)- assert.Contains(t, out, normalizeImageUpdateRefInternal("nginx:latest"))- assert.NotContains(t, out, normalizeImageUpdateRefInternal("redis:7"))- assert.NotContains(t, out, normalizeImageUpdateRefInternal("postgres:16"))- assert.NotContains(t, out, normalizeImageUpdateRefInternal("sha256:abcdef"))+ 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, "")}-func TestResolveContainerImageMatchInternal(t *testing.T) {- svc := &UpdaterService{}- updatedNorm := map[string]string{- normalizeImageUpdateRefInternal("nginx:latest"): "nginx:latest",- }- oldIDToNewRef := map[string]string{- "sha256:img1": "redis:7",- }-- tests := []struct {- name string- container container.Summary- 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: normalizeImageUpdateRefInternal("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 := svc.resolveContainerImageMatchInternal(tt.container, oldIDToNewRef, localUpdatedNorm)- assert.Equal(t, tt.wantRef, gotRef)- assert.Equal(t, tt.wantMatchID, gotMatch)- })- }-}-func TestResolvePullableImageRefInternal(t *testing.T) {tests := []struct {name string@@ -1104,6 +1148,6 @@ func TestUpdaterService_CollectUsedImages_SkipsExcludedContainers(t *testing.T)require.NoError(t, svc.collectUsedImagesFromContainersInternal(ctx, dcli, out))- assert.NotContains(t, out, normalizeImageUpdateRefInternal("nginx:latest"), "excluded container image must not be collected")- assert.Contains(t, out, normalizeImageUpdateRefInternal("redis:7"), "non-excluded container image must be collected")+ 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/pkg/libarcane/imageupdate/matching.go b/backend/pkg/libarcane/imageupdate/matching.gonew file mode 100644index 000000000..0a7eb19ff--- /dev/null+++ b/backend/pkg/libarcane/imageupdate/matching.go@@ -0,0 +1,158 @@+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.gonew file mode 100644index 000000000..71f709a0f--- /dev/null+++ b/backend/pkg/libarcane/imageupdate/matching_test.go@@ -0,0 +1,163 @@+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)+ })+ }+}