Skip to content

Modern Docker Management, Designed for Everyone

fix: resolve docker.sock host path for self-upgrade when using network_mode service (#3565)

Kyle Mendell7435fd4f20fe
diff --git a/backend/internal/system/upgrade_service.go b/backend/internal/system/upgrade_service.go
index 06df9d792..30c88e1ed 100644
--- a/backend/internal/system/upgrade_service.go
+++ b/backend/internal/system/upgrade_service.go
@@ -76,7 +76,7 @@ func NewSystemUpgradeService(
// CanUpgrade checks if self-upgrade is possible
func (s *SystemUpgradeService) CanUpgrade(ctx context.Context) (bool, error) {
// Check if running in Docker
- containerId, err := s.getCurrentContainerIDInternal()
+ containerId, err := s.getCurrentContainerIDInternal(ctx)
if err != nil {
return false, err
}
@@ -123,7 +123,7 @@ func (s *SystemUpgradeService) TriggerUpgradeViaCLI(ctx context.Context, user mo
if containerId == "" {
// Fall back to the container this process runs in
var err error
- containerId, err = s.getCurrentContainerIDInternal()
+ containerId, err = s.getCurrentContainerIDInternal(ctx)
if err != nil {
return "", errors.WrapIf(err, "get current container")
}
@@ -367,12 +367,19 @@ func resolveSystemUpgraderRuntimeOptionsInternal(
}
// getCurrentContainerID detects if we're running in Docker and returns container ID
-func (s *SystemUpgradeService) getCurrentContainerIDInternal() (string, error) {
- id, err := cgroup.CurrentContainerID()
+func (s *SystemUpgradeService) getCurrentContainerIDInternal(ctx context.Context) (string, error) {
+ // cgroup detection fails on cgroupv2 with a private namespace, and with
+ // network_mode: service:<sidecar> the hostname identifies the sidecar —
+ // InspectCurrentArcaneContainer adds the Arcane-label fallback (#3544).
+ dockerClient, err := s.dockerService.GetClient(ctx)
+ if err != nil {
+ return "", err
+ }
+ inspect, err := libarcane.InspectCurrentArcaneContainer(ctx, dockerClient)
if err != nil {
return "", errors.New("arcane is not running in a Docker container")
}
- return id, nil
+ return inspect.ID, nil
}
// findArcaneContainer finds the container using the ID
diff --git a/backend/pkg/dockerutil/mount_utils.go b/backend/pkg/dockerutil/mount_utils.go
index 525a18b26..d13ecc583 100644
--- a/backend/pkg/dockerutil/mount_utils.go
+++ b/backend/pkg/dockerutil/mount_utils.go
@@ -23,7 +23,7 @@ func MountForCurrentContainerSubpath(ctx context.Context, dockerCli *client.Clie
if dockerCli == nil {
return nil, nil
}
- inspectTarget, err := libarcane.CurrentContainerInspectTarget(cgroup.CurrentContainerID, os.Hostname)
+ inspectTarget, _, err := libarcane.CurrentContainerInspectTarget(cgroup.CurrentContainerID, os.Hostname)
if err != nil {
return nil, err
}
diff --git a/backend/pkg/libarcane/internal_resource.go b/backend/pkg/libarcane/internal_resource.go
index 87944a39e..564250783 100644
--- a/backend/pkg/libarcane/internal_resource.go
+++ b/backend/pkg/libarcane/internal_resource.go
@@ -77,31 +77,69 @@ func InspectCurrentArcaneContainer(ctx context.Context, dockerClient *client.Cli
return nil, errors.New("docker client is not available")
}
- if target, err := CurrentContainerInspectTarget(cgroup.CurrentContainerID, os.Hostname); err == nil && target != "" {
+ // A cgroup-derived container ID is definitively the current container, so
+ // that inspect is trusted even without the Arcane label (custom images).
+ // With network_mode: service:<sidecar> the hostname belongs to the sidecar
+ // container, so a hostname-derived inspect is only trusted directly when it
+ // carries the Arcane label (#3544); an unlabeled hostname hit is kept as a
+ // last resort so the label lookup can't hijack detection either way.
+ var unlabeled *container.InspectResponse
+ if target, fromContainerID, err := CurrentContainerInspectTarget(cgroup.CurrentContainerID, os.Hostname); err == nil && target != "" {
if inspect, inspectErr := ContainerInspectWithCompatibility(ctx, dockerClient, target, client.ContainerInspectOptions{}); inspectErr == nil {
- return &inspect.Container, nil
+ if fromContainerID {
+ return &inspect.Container, nil
+ }
+ if inspect.Container.Config != nil && strings.EqualFold(strings.TrimSpace(inspect.Container.Config.Labels[labels.LabelArcane]), "true") {
+ return &inspect.Container, nil
+ }
+ unlabeled = &inspect.Container
}
}
- containerID := FindArcaneContainerIDByLabel(ctx, dockerClient)
- if containerID == "" {
- return nil, errors.New("could not detect Arcane container")
+ if containerID := FindArcaneContainerIDByLabel(ctx, dockerClient); containerID != "" {
+ inspect, err := ContainerInspectWithCompatibility(ctx, dockerClient, containerID, client.ContainerInspectOptions{})
+ if err != nil {
+ return nil, errors.WrapIf(err, "inspect Arcane container")
+ }
+ // An unlabeled hostname hit is only overridden by the labeled match when
+ // that match shares the hostname container's network namespace — i.e. the
+ // hostname really belonged to its sidecar (#3544). Otherwise the labeled
+ // container is a different Arcane instance and the hostname hit is us.
+ if unlabeled == nil || sharesNetworkNamespaceInternal(&inspect.Container, unlabeled) {
+ return &inspect.Container, nil
+ }
}
- inspect, err := ContainerInspectWithCompatibility(ctx, dockerClient, containerID, client.ContainerInspectOptions{})
- if err != nil {
- return nil, errors.WrapIf(err, "inspect Arcane container")
+ if unlabeled != nil {
+ return unlabeled, nil
}
- return &inspect.Container, nil
+ return nil, errors.New("could not detect Arcane container")
+}
+
+// sharesNetworkNamespaceInternal reports whether candidate runs with
+// network_mode "container:<owner>", i.e. it borrows owner's network namespace
+// (and therefore owner's hostname). The reference may be the owner's ID (any
+// prefix length) or its name.
+func sharesNetworkNamespaceInternal(candidate, owner *container.InspectResponse) bool {
+ if candidate.HostConfig == nil || !candidate.HostConfig.NetworkMode.IsContainer() {
+ return false
+ }
+ ref := strings.TrimSpace(candidate.HostConfig.NetworkMode.ConnectedContainer())
+ if ref == "" {
+ return false
+ }
+ return strings.HasPrefix(owner.ID, ref) || strings.EqualFold(ref, strings.TrimPrefix(owner.Name, "/"))
}
-// CurrentContainerInspectTarget resolves the identifier used to inspect Arcane's current container.
-func CurrentContainerInspectTarget(currentContainerID func() (string, error), hostname func() (string, error)) (string, error) {
+// CurrentContainerInspectTarget resolves the identifier used to inspect Arcane's
+// current container. The second return reports whether the target came from the
+// cgroup container ID (authoritative) rather than the hostname fallback.
+func CurrentContainerInspectTarget(currentContainerID func() (string, error), hostname func() (string, error)) (string, bool, error) {
if currentContainerID != nil {
if containerID, err := currentContainerID(); err == nil {
if containerID = strings.TrimSpace(containerID); containerID != "" {
- return containerID, nil
+ return containerID, true, nil
}
}
}
@@ -112,8 +150,8 @@ func CurrentContainerInspectTarget(currentContainerID func() (string, error), ho
value, err := hostname()
if err != nil {
- return "", err
+ return "", false, err
}
- return strings.TrimSpace(value), nil
+ return strings.TrimSpace(value), false, nil
}
diff --git a/backend/pkg/libarcane/internal_resource_test.go b/backend/pkg/libarcane/internal_resource_test.go
index 34302de73..9aaece853 100644
--- a/backend/pkg/libarcane/internal_resource_test.go
+++ b/backend/pkg/libarcane/internal_resource_test.go
@@ -1,45 +1,52 @@
package libarcane
import (
+ "context"
+ "net/http"
+ "strings"
"testing"
"emperror.dev/errors"
+ "github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestCurrentContainerInspectTarget(t *testing.T) {
t.Run("prefers detected container id over hostname", func(t *testing.T) {
- target, err := CurrentContainerInspectTarget(
+ target, fromContainerID, err := CurrentContainerInspectTarget(
func() (string, error) { return "0123456789ab", nil },
func() (string, error) { return "rpi4", nil },
)
require.NoError(t, err)
require.Equal(t, "0123456789ab", target)
+ require.True(t, fromContainerID)
})
t.Run("falls back to hostname when container id unavailable", func(t *testing.T) {
- target, err := CurrentContainerInspectTarget(
+ target, fromContainerID, err := CurrentContainerInspectTarget(
func() (string, error) { return "", errors.New("no container id found") },
func() (string, error) { return "rpi4", nil },
)
require.NoError(t, err)
require.Equal(t, "rpi4", target)
+ require.False(t, fromContainerID)
})
t.Run("trims whitespace from detected container id", func(t *testing.T) {
- target, err := CurrentContainerInspectTarget(
+ target, fromContainerID, err := CurrentContainerInspectTarget(
func() (string, error) { return " 0123456789ab ", nil },
func() (string, error) { return "rpi4", nil },
)
require.NoError(t, err)
require.Equal(t, "0123456789ab", target)
+ require.True(t, fromContainerID)
})
t.Run("returns hostname error when fallback fails", func(t *testing.T) {
- target, err := CurrentContainerInspectTarget(
+ target, fromContainerID, err := CurrentContainerInspectTarget(
func() (string, error) { return "", errors.New("no container id found") },
func() (string, error) { return "", errors.New("hostname unavailable") },
)
@@ -47,5 +54,53 @@ func TestCurrentContainerInspectTarget(t *testing.T) {
require.Error(t, err)
require.Contains(t, err.Error(), "hostname unavailable")
require.Empty(t, target)
+ require.False(t, fromContainerID)
})
}
+
+func TestInspectCurrentArcaneContainer_FallsBackToLabelWhenHostnameIsSidecar(t *testing.T) {
+ // With network_mode: service:<sidecar> the hostname inspect returns the
+ // sidecar container (no Arcane label); detection must fall back to the
+ // label lookup instead of trusting it (#3544).
+ dockerClient := newTestDockerClient(t, func(w http.ResponseWriter, r *http.Request) {
+ w.Header().Set("Content-Type", "application/json")
+ switch {
+ case strings.HasSuffix(r.URL.Path, "/containers/json"):
+ _, _ = w.Write([]byte(`[{"Id":"arcane123","Names":["/arcane"],"State":"running","Labels":{"com.getarcaneapp.arcane":"true"}}]`))
+ case strings.HasSuffix(r.URL.Path, "/containers/arcane123/json"):
+ _, _ = w.Write([]byte(`{"Id":"arcane123","Name":"/arcane","State":{"Running":true},"HostConfig":{"NetworkMode":"container:sidecar456"},"Config":{"Labels":{"com.getarcaneapp.arcane":"true"}}}`))
+ case strings.HasSuffix(r.URL.Path, "/json"):
+ _, _ = w.Write([]byte(`{"Id":"sidecar456","Name":"/ts-arcane","State":{"Running":true},"Config":{"Labels":{}}}`))
+ default:
+ w.WriteHeader(http.StatusOK)
+ }
+ })
+
+ got, err := InspectCurrentArcaneContainer(context.Background(), dockerClient)
+ require.NoError(t, err)
+ assert.Equal(t, "arcane123", got.ID)
+}
+
+func TestInspectCurrentArcaneContainer_KeepsUnlabeledHitOverUnrelatedLabeledInstance(t *testing.T) {
+ // The hostname resolves to the actual (unlabeled custom-image) Arcane
+ // container; a second, labeled Arcane instance also runs on the daemon but
+ // does not share the hostname container's network namespace, so it must not
+ // hijack detection.
+ dockerClient := newTestDockerClient(t, func(w http.ResponseWriter, r *http.Request) {
+ w.Header().Set("Content-Type", "application/json")
+ switch {
+ case strings.HasSuffix(r.URL.Path, "/containers/json"):
+ _, _ = w.Write([]byte(`[{"Id":"other789","Names":["/arcane-other"],"State":"running","Labels":{"com.getarcaneapp.arcane":"true"}}]`))
+ case strings.HasSuffix(r.URL.Path, "/containers/other789/json"):
+ _, _ = w.Write([]byte(`{"Id":"other789","Name":"/arcane-other","State":{"Running":true},"HostConfig":{"NetworkMode":"bridge"},"Config":{"Labels":{"com.getarcaneapp.arcane":"true"}}}`))
+ case strings.HasSuffix(r.URL.Path, "/json"):
+ _, _ = w.Write([]byte(`{"Id":"custom123","Name":"/arcane-custom","State":{"Running":true},"Config":{"Labels":{}}}`))
+ default:
+ w.WriteHeader(http.StatusOK)
+ }
+ })
+
+ got, err := InspectCurrentArcaneContainer(context.Background(), dockerClient)
+ require.NoError(t, err)
+ assert.Equal(t, "custom123", got.ID)
+}
diff --git a/backend/pkg/projects/container_mounts.go b/backend/pkg/projects/container_mounts.go
index c665f84d1..08da6b57a 100644
--- a/backend/pkg/projects/container_mounts.go
+++ b/backend/pkg/projects/container_mounts.go
@@ -2,14 +2,12 @@ package projects
import (
"context"
- "os"
"strings"
mounttypes "github.com/moby/moby/api/types/mount"
"github.com/moby/moby/client"
"github.com/getarcaneapp/arcane/backend/v2/pkg/libarcane"
- "go.getarcane.app/sys/cgroup"
)
// GetCurrentContainerMounts inspects Arcane's own container and returns its bind and
@@ -21,21 +19,18 @@ func GetCurrentContainerMounts(ctx context.Context, dockerCli *client.Client) ([
return nil, nil // No docker client, can't discover
}
- // Prefer robust current-container detection and fall back to hostname.
- inspectTarget, err := libarcane.CurrentContainerInspectTarget(cgroup.CurrentContainerID, os.Hostname)
- if err != nil {
- return nil, err
- }
-
- inspect, err := libarcane.ContainerInspectWithCompatibility(ctx, dockerCli, inspectTarget, client.ContainerInspectOptions{})
+ // Label-fallback detection matters here: with network_mode: service:<sidecar>
+ // the hostname identifies the sidecar, whose mounts do not include
+ // docker.sock — breaking host-path resolution for the self-upgrader (#3544).
+ inspect, err := libarcane.InspectCurrentArcaneContainer(ctx, dockerCli)
if err != nil {
// Not running in a container or can't reach docker daemon
return nil, err
}
- mounts := make([]HostMount, 0, len(inspect.Container.Mounts))
- for i := range inspect.Container.Mounts {
- m := &inspect.Container.Mounts[i]
+ mounts := make([]HostMount, 0, len(inspect.Mounts))
+ for i := range inspect.Mounts {
+ m := &inspect.Mounts[i]
if m.Type != mounttypes.TypeBind && m.Type != mounttypes.TypeVolume {
continue
}