Skip to content

armgit / Pulse

Public Imported from GitHub
0

Real-time monitoring dashboard for Proxmox VE, PBS, Docker, Kubernetes, TrueNAS and vSphere. Self-hosted, with alerts for failed backups, full disks, unhealthy containers and offline nodes.

Fix Docker container update recreation lifecycle

rcourtman8580b48abcb8
diff --git a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md b/docs/release-control/v6/internal/subsystems/agent-lifecycle.md
index 6471ad11fa..0a90459e2a 100644
--- a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md
+++ b/docs/release-control/v6/internal/subsystems/agent-lifecycle.md
@@ -30,8 +30,10 @@ that binary, not separate customer-facing agent products.
4. `internal/agentupdate/update.go`
5. `internal/hostagent/agent.go`
5a. `internal/dockeragent/agent.go`
- 5b. `internal/kubernetesagent/agent.go`
- 5c. `internal/agentexec/verifier_postconditions.go`
+ 5b. `internal/dockeragent/container_update.go`
+ 5c. `internal/dockeragent/container_update_typed.go`
+ 5d. `internal/kubernetesagent/agent.go`
+ 5e. `internal/agentexec/verifier_postconditions.go`
6. `cmd/pulse-agent/main.go`
7. `scripts/install.sh`
8. `scripts/install.ps1`
@@ -102,6 +104,22 @@ that binary, not separate customer-facing agent products.
## Shared Boundaries
+Docker container update recreation under `internal/dockeragent/` is lifecycle
+mutation authority, not monitoring collection. The module must translate
+daemon inspect output into a desired create plan before the original container
+is renamed: preserve operator configuration such as labels, mounts, binds,
+restart policy, explicit hostname, network aliases, IPAM, driver options,
+gateway priority, and network mode; remove daemon-generated observations and
+fields that conflict with `host` or shared `container:<id>` namespaces.
+`network_mode: service:<name>` reaches this boundary as the daemon-resolved
+`container:<id>` mode and follows the same rule. The create-time network must
+be deterministic, every additional attachment must be restored before start,
+and any create, connect, start, or verification failure after backup creation
+must report compensation truth and attempt rollback rather than declaring a
+partially connected replacement successful. The typed host-agent command path
+owns durable terminal receipts for that mutation: reconnect or server recovery
+may replay a persisted result, but may not execute the Docker mutation twice.
+
Automatic Patrol action admission wired through `internal/api/` is API/action-
lifecycle authority, not agent enrollment or command authority. Agent command
transport may run only after the lifecycle-owned policy lease has been
@@ -1974,9 +1992,33 @@ Agent` secondary handoff against the live setup wizard instead of relying
provider tools and in-memory tool results under settings-write authority;
it must not request `agent:exec`, dispatch an agent command, inspect agent
inventory, or turn a successful model probe into command authority.
+20. Keep Docker container-update proof on the production recreate path. Unit
+ coverage must include standalone and Compose-shaped host, shared-service,
+ shared-container, bridge, and custom-network plans, generated and explicit
+ hostnames, labels, dependencies, mounts, volumes, secondary-network
+ rollback, progress errors, and durable reconnect replay. The opt-in live
+ Docker Compose proof must exercise those network modes against a real
+ daemon; a fake-only sanitizer test is not sufficient lifecycle evidence.
## Current State
+### Docker updates recreate desired configuration and replay terminal truth
+
+The Docker module now builds an immutable recreate plan from inspect output
+before pulling or mutating. Generated container-ID hostnames and operational
+endpoint fields are not injected as explicit create configuration; explicit
+hostnames and configurable endpoint fields remain intact. Host and
+container/service namespace modes receive no conflicting endpoint or hostname
+configuration. Multi-network replacements connect the primary network
+deterministically and restore every remaining network before start; a failed
+attachment removes the replacement, restores the backup name, restarts the
+original when required, and returns rollback facts through the typed action
+result. The host agent persists that terminal result before delivery and
+replays it after reconnect without rerunning Docker. Agent Doctor hides the
+manual host-local update command only for a timestamped update attempt inside
+the bounded in-flight window; a missing timestamp or a stale attempt restores
+the manual recovery handoff.
+
### vSphere system members carry no agent semantics
ESXi host rows that now compose under their owning vCenter connection in the
diff --git a/docs/release-control/v6/internal/subsystems/registry.json b/docs/release-control/v6/internal/subsystems/registry.json
index 7cf1b8800a..e85d7c558f 100644
--- a/docs/release-control/v6/internal/subsystems/registry.json
+++ b/docs/release-control/v6/internal/subsystems/registry.json
@@ -1192,6 +1192,8 @@
"internal/api/setup_script_render.go",
"internal/api/unified_agent.go",
"internal/dockeragent/agent.go",
+ "internal/dockeragent/container_update.go",
+ "internal/dockeragent/container_update_typed.go",
"internal/kubernetesagent/agent.go",
"internal/remoteconfig/client.go",
"internal/securityutil/httpurl.go",
@@ -1320,6 +1322,24 @@
"internal/securityutil/httpurl_test.go"
]
},
+ {
+ "id": "docker-container-update-runtime",
+ "label": "Docker container recreate, rollback, durable result, and live network-mode proof",
+ "match_prefixes": [],
+ "match_files": [
+ "internal/dockeragent/container_update.go",
+ "internal/dockeragent/container_update_typed.go"
+ ],
+ "allow_same_subsystem_tests": false,
+ "test_prefixes": [],
+ "exact_files": [
+ "internal/dockeragent/container_update_contract_test.go",
+ "internal/dockeragent/container_update_integration_test.go",
+ "internal/dockeragent/container_update_test.go",
+ "internal/dockeragent/container_update_typed_test.go",
+ "internal/hostagent/docker_lifecycle_test.go"
+ ]
+ },
{
"id": "proxmox-unified-agent-setup-runtime",
"label": "proxmox unified agent setup runtime proof",
diff --git a/frontend-modern/src/components/Settings/__tests__/infrastructureAgentDoctorModel.test.ts b/frontend-modern/src/components/Settings/__tests__/infrastructureAgentDoctorModel.test.ts
index 6bd9d0c1a1..5188cbea11 100644
--- a/frontend-modern/src/components/Settings/__tests__/infrastructureAgentDoctorModel.test.ts
+++ b/frontend-modern/src/components/Settings/__tests__/infrastructureAgentDoctorModel.test.ts
@@ -238,6 +238,24 @@ describe('Agent Doctor model', () => {
expect(targets[0].commandBlockedReason).toBeUndefined();
});
+ it('keeps the manual command available when updating has no attempt timestamp', () => {
+ const agentUpdate = {
+ state: 'updating' as const,
+ autoUpdate: true,
+ };
+ const connection = connectionFixture({ agentUpdate });
+ const targets = collectInfrastructureAgentDoctorTargets({
+ rows: [rowFixture(connection)],
+ connections: [connection],
+ diagnostics: [diagnosticFixture({ agentUpdate })],
+ diagnosticsAvailable: true,
+ targetVersion: '6.2.0',
+ nowMs: Date.parse('2026-07-13T09:05:00Z'),
+ });
+
+ expect(targets[0].commandBlockedReason).toBeUndefined();
+ });
+
it('withholds FreeBSD and pfSense update commands until installer state is proven', () => {
const connection = connectionFixture({
agentIdentity: { hostname: 'firewall', platform: 'pfSense', architecture: 'amd64' },
diff --git a/frontend-modern/src/components/Settings/infrastructureAgentUpdateCommandsModel.ts b/frontend-modern/src/components/Settings/infrastructureAgentUpdateCommandsModel.ts
index 34fdf88792..230e176d88 100644
--- a/frontend-modern/src/components/Settings/infrastructureAgentUpdateCommandsModel.ts
+++ b/frontend-modern/src/components/Settings/infrastructureAgentUpdateCommandsModel.ts
@@ -403,7 +403,9 @@ const updaterApplyingNow = (
const update = connection.agentUpdate ?? diagnostic?.agentUpdate;
if (update?.state?.trim().toLowerCase() !== 'updating') return false;
const startedAt = Date.parse(update.lastAttemptAt || update.lastCheckedAt || '');
- if (Number.isNaN(startedAt)) return true;
+ // A bare/stale "updating" state is not enough evidence to hide the manual
+ // recovery path forever. Only a timestamped, recent attempt is in flight.
+ if (Number.isNaN(startedAt)) return false;
return nowMs - startedAt < UPDATER_IN_FLIGHT_STALL_MS;
};
diff --git a/internal/dockeragent/container_update.go b/internal/dockeragent/container_update.go
index b3d8e16720..aa4b27e73c 100644
--- a/internal/dockeragent/container_update.go
+++ b/internal/dockeragent/container_update.go
@@ -6,6 +6,7 @@ import (
"errors"
"fmt"
"io"
+ "sort"
"strings"
"time"
@@ -84,6 +85,108 @@ func sanitizeSharedNamespaceConfig(config *containertypes.Config, hostConfig *co
}
}
+type recreateNetworkAttachment struct {
+ name string
+ endpoint *network.EndpointSettings
+}
+
+type containerRecreatePlan struct {
+ config *containertypes.Config
+ hostConfig *containertypes.HostConfig
+ networkingConfig *network.NetworkingConfig
+ additionalNetworks []recreateNetworkAttachment
+}
+
+// buildContainerRecreatePlan turns inspect output into create input. Inspect
+// mixes desired configuration with daemon-generated runtime observations, so
+// it must not be passed back to ContainerCreate unchanged.
+func buildContainerRecreatePlan(inspect containertypes.InspectResponse) (containerRecreatePlan, error) {
+ if inspect.Config == nil {
+ return containerRecreatePlan{}, errors.New("inspect response is missing container configuration")
+ }
+ if inspect.HostConfig == nil {
+ return containerRecreatePlan{}, errors.New("inspect response is missing host configuration")
+ }
+
+ config := *inspect.Config
+ hostConfig := *inspect.HostConfig
+ if daemonGeneratedHostname(config.Hostname, inspect.ID) {
+ config.Hostname = ""
+ }
+ sanitizeSharedNamespaceConfig(&config, &hostConfig)
+
+ plan := containerRecreatePlan{
+ config: &config,
+ hostConfig: &hostConfig,
+ }
+ if hostConfig.NetworkMode.IsContainer() || hostConfig.NetworkMode.IsHost() ||
+ inspect.NetworkSettings == nil || len(inspect.NetworkSettings.Networks) == 0 {
+ return plan, nil
+ }
+
+ networkNames := make([]string, 0, len(inspect.NetworkSettings.Networks))
+ for name, endpoint := range inspect.NetworkSettings.Networks {
+ if strings.TrimSpace(name) == "" || endpoint == nil {
+ continue
+ }
+ networkNames = append(networkNames, name)
+ }
+ if len(networkNames) == 0 {
+ return plan, nil
+ }
+ sort.Strings(networkNames)
+
+ primaryNetwork := string(hostConfig.NetworkMode)
+ if primaryNetwork == "" || primaryNetwork == "default" {
+ primaryNetwork = "bridge"
+ }
+ if _, ok := inspect.NetworkSettings.Networks[primaryNetwork]; !ok {
+ primaryNetwork = networkNames[0]
+ }
+
+ plan.networkingConfig = &network.NetworkingConfig{
+ EndpointsConfig: map[string]*network.EndpointSettings{
+ primaryNetwork: desiredEndpointSettings(inspect.NetworkSettings.Networks[primaryNetwork]),
+ },
+ }
+ for _, name := range networkNames {
+ if name == primaryNetwork {
+ continue
+ }
+ plan.additionalNetworks = append(plan.additionalNetworks, recreateNetworkAttachment{
+ name: name,
+ endpoint: desiredEndpointSettings(inspect.NetworkSettings.Networks[name]),
+ })
+ }
+ return plan, nil
+}
+
+// desiredEndpointSettings preserves operator-configurable endpoint settings
+// and deliberately drops observed runtime fields such as endpoint IDs,
+// gateways, assigned addresses, prefix lengths, and generated DNS names.
+func desiredEndpointSettings(endpoint *network.EndpointSettings) *network.EndpointSettings {
+ if endpoint == nil {
+ return &network.EndpointSettings{}
+ }
+ return &network.EndpointSettings{
+ IPAMConfig: endpoint.IPAMConfig.Copy(),
+ Links: append([]string(nil), endpoint.Links...),
+ Aliases: append([]string(nil), endpoint.Aliases...),
+ DriverOpts: cloneStringMap(endpoint.DriverOpts),
+ GwPriority: endpoint.GwPriority,
+ MacAddress: append(network.HardwareAddr(nil), endpoint.MacAddress...),
+ }
+}
+
+func daemonGeneratedHostname(hostname, containerID string) bool {
+ hostname = strings.ToLower(strings.TrimSpace(hostname))
+ containerID = strings.TrimPrefix(strings.ToLower(strings.TrimSpace(containerID)), "sha256:")
+ if hostname == "" || containerID == "" {
+ return false
+ }
+ return hostname == containerID || (len(hostname) == 12 && strings.HasPrefix(containerID, hostname))
+}
+
// handleUpdateContainerCommand handles the update_container command from Pulse.
func (a *Agent) handleUpdateContainerCommand(ctx context.Context, target TargetConfig, command agentsdocker.Command) error {
commandPayload, err := decodeUpdateContainerPayload(command.Payload)
@@ -217,14 +320,21 @@ func (a *Agent) updateContainerWithProgress(ctx context.Context, containerID str
return result
}
+ recreatePlan, err := buildContainerRecreatePlan(inspect)
+ if err != nil {
+ result.Error = fmt.Sprintf("Failed to prepare container recreation: %v", err)
+ a.logger.Error().Err(err).Str("container", result.ContainerName).Msg("Invalid inspect response for container update")
+ return result
+ }
+
a.logger.Info().
Str("container", result.ContainerName).
- Str("image", inspect.Config.Image).
+ Str("image", recreatePlan.config.Image).
Bool("wasRunning", wasRunning).
Msg("Starting container update")
// 2. Pull the latest image
- imageName := inspect.Config.Image
+ imageName := recreatePlan.config.Image
reportProgress(fmt.Sprintf("Pulling image %s...", imageName))
a.logger.Info().Str("image", imageName).Msg("Pulling latest image")
@@ -287,35 +397,13 @@ func (a *Agent) updateContainerWithProgress(ctx context.Context, containerID str
reportProgress(fmt.Sprintf("Creating new container %s...", result.ContainerName))
- // 5. Prepare network configuration
- // We need to handle network settings carefully
- sanitizeSharedNamespaceConfig(inspect.Config, inspect.HostConfig)
- var networkingConfig *network.NetworkingConfig
- if len(inspect.NetworkSettings.Networks) > 0 {
- networkingConfig = &network.NetworkingConfig{
- EndpointsConfig: make(map[string]*network.EndpointSettings),
- }
- // Only set the first network here; we'll connect to others after creation
- for netName, netConfig := range inspect.NetworkSettings.Networks {
- networkingConfig.EndpointsConfig[netName] = &network.EndpointSettings{
- Aliases: netConfig.Aliases,
- IPAMConfig: netConfig.IPAMConfig,
- Links: netConfig.Links,
- NetworkID: netConfig.NetworkID,
- MacAddress: netConfig.MacAddress,
- DriverOpts: netConfig.DriverOpts,
- }
- break // Only set one network during creation
- }
- }
-
- // 6. Create a new container with the same configuration
+ // 5. Create a new container with the normalized desired configuration.
createResp, err := dockerCallWithRetry(ctx, dockerUpdateCallTimeout, func(callCtx context.Context) (containertypes.CreateResponse, error) {
return a.docker.ContainerCreate(
callCtx,
- inspect.Config,
- inspect.HostConfig,
- networkingConfig,
+ recreatePlan.config,
+ recreatePlan.hostConfig,
+ recreatePlan.networkingConfig,
nil, // Platform
result.ContainerName,
)
@@ -334,26 +422,23 @@ func (a *Agent) updateContainerWithProgress(ctx context.Context, containerID str
result.ContainerID = newContainerID
a.logger.Info().Str("newContainerId", newContainerID).Msg("New container created")
- // 7. Connect to additional networks (if more than one)
- networkCount := 0
- for netName, netConfig := range inspect.NetworkSettings.Networks {
- networkCount++
- if networkCount == 1 {
- continue // Skip the first one, already connected during creation
- }
- endpointConfig := &network.EndpointSettings{
- Aliases: netConfig.Aliases,
- IPAMConfig: netConfig.IPAMConfig,
- Links: netConfig.Links,
- MacAddress: netConfig.MacAddress,
- DriverOpts: netConfig.DriverOpts,
- }
- if err := a.docker.NetworkConnect(ctx, netName, newContainerID, endpointConfig); err != nil {
- a.logger.Warn().Err(err).Str("network", netName).Msg("Failed to connect to network, continuing anyway")
+ // 6. Restore every additional network before starting the replacement.
+ for _, attachment := range recreatePlan.additionalNetworks {
+ reportProgress(fmt.Sprintf("Connecting container %s to network %s...", result.ContainerName, attachment.name))
+ _, err := dockerCallWithRetry(ctx, dockerUpdateCallTimeout, func(callCtx context.Context) (struct{}, error) {
+ err := a.docker.NetworkConnect(callCtx, attachment.name, newContainerID, attachment.endpoint)
+ return struct{}{}, err
+ })
+ if err != nil {
+ result.Error = fmt.Sprintf("Failed to connect new container to network %s: %v", attachment.name, annotateDockerConnectionError(err))
+ a.logger.Error().Err(err).Str("network", attachment.name).Str("container", result.ContainerName).Msg("Failed to restore container network attachment")
+ result.RollbackAttempted = true
+ result.RolledBack = a.rollbackRemoveRenameAndRestart(ctx, newContainerID, backupName, result.ContainerName, containerID, wasRunning)
+ return result
}
}
- // 8. Start and verify the new container only if the original was running.
+ // 7. Start and verify the new container only if the original was running.
if wasRunning {
reportProgress(fmt.Sprintf("Starting container %s...", result.ContainerName))
_, err = dockerCallWithRetry(ctx, dockerUpdateCallTimeout, func(callCtx context.Context) (struct{}, error) {
@@ -371,7 +456,7 @@ func (a *Agent) updateContainerWithProgress(ctx context.Context, containerID str
a.logger.Info().Str("container", result.ContainerName).Msg("New container started, verifying stability...")
- // 9. Verify container stability
+ // 8. Verify container stability
reportProgress("Verifying container stability...")
// Wait a few seconds to ensure it doesn't crash immediately
sleepFn(5 * time.Second)
@@ -418,7 +503,7 @@ func (a *Agent) updateContainerWithProgress(ctx context.Context, containerID str
result.NewImageDigest = verifyInspect.Image
- // 10. Schedule cleanup of backup container after a delay.
+ // 9. Schedule cleanup of backup container after a delay.
// This gives time to verify the new container is working.
a.runAsync(func(asyncCtx context.Context) {
if !a.waitForAsyncDelay(5 * time.Minute) {
diff --git a/internal/dockeragent/container_update_contract_test.go b/internal/dockeragent/container_update_contract_test.go
new file mode 100644
index 0000000000..e6da16c6ab
--- /dev/null
+++ b/internal/dockeragent/container_update_contract_test.go
@@ -0,0 +1,310 @@
+package dockeragent
+
+import (
+ "context"
+ "errors"
+ "io"
+ "net/netip"
+ "reflect"
+ "strings"
+ "testing"
+
+ containertypes "github.com/moby/moby/api/types/container"
+ "github.com/moby/moby/api/types/mount"
+ "github.com/moby/moby/api/types/network"
+ v1 "github.com/opencontainers/image-spec/specs-go/v1"
+ "github.com/rs/zerolog"
+)
+
+func TestBuildContainerRecreatePlanNetworkModesAndDesiredConfiguration(t *testing.T) {
+ const containerID = "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef"
+
+ base := func() containertypes.InspectResponse {
+ inspect := baseInspect()
+ inspect.ID = containerID
+ inspect.Config.Hostname = containerID[:12]
+ inspect.Config.Domainname = "internal.example"
+ inspect.Config.Labels = map[string]string{
+ "com.docker.compose.project": "issue1564",
+ "com.docker.compose.service": "app",
+ "com.docker.compose.depends_on": `db:service_started:false`,
+ "pulse.test": "network-lifecycle",
+ }
+ inspect.Config.Volumes = map[string]struct{}{"/data": {}}
+ inspect.HostConfig.Binds = []string{"issue1564-data:/data", "/tmp/issue1564:/host"}
+ inspect.HostConfig.Mounts = []mount.Mount{{
+ Type: mount.TypeVolume,
+ Source: "issue1564-cache",
+ Target: "/cache",
+ }}
+ inspect.HostConfig.RestartPolicy = containertypes.RestartPolicy{Name: "unless-stopped"}
+ return inspect
+ }
+
+ t.Run("standalone bridge clears only a generated hostname", func(t *testing.T) {
+ inspect := base()
+ inspect.HostConfig.NetworkMode = "bridge"
+ inspect.NetworkSettings.Networks = map[string]*network.EndpointSettings{
+ "bridge": {Aliases: []string{"app"}},
+ }
+
+ plan, err := buildContainerRecreatePlan(inspect)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if plan.config.Hostname != "" {
+ t.Fatalf("generated hostname was retained as explicit: %q", plan.config.Hostname)
+ }
+ assertRecreatePlanPreservesNonNetworkConfiguration(t, inspect, plan)
+ assertPrimaryNetwork(t, plan, "bridge")
+ if inspect.Config.Hostname != containerID[:12] {
+ t.Fatal("building the recreate plan mutated inspect output")
+ }
+ })
+
+ t.Run("standalone custom networks preserve explicit configuration deterministically", func(t *testing.T) {
+ inspect := base()
+ inspect.Config.Hostname = "operator-hostname"
+ inspect.HostConfig.NetworkMode = "app-primary"
+ primaryEndpoint := &network.EndpointSettings{
+ IPAMConfig: &network.EndpointIPAMConfig{
+ IPv4Address: netip.MustParseAddr("172.30.0.20"),
+ LinkLocalIPs: []netip.Addr{netip.MustParseAddr("169.254.20.1")},
+ },
+ Links: []string{"db:database"},
+ Aliases: []string{"app", "api"},
+ DriverOpts: map[string]string{"com.example.mode": "isolated"},
+ GwPriority: 100,
+ NetworkID: "observed-network-id",
+ EndpointID: "observed-endpoint-id",
+ Gateway: netip.MustParseAddr("172.30.0.1"),
+ IPAddress: netip.MustParseAddr("172.30.0.20"),
+ MacAddress: network.HardwareAddr{0x02, 0x42, 0xac, 0x1e, 0x00, 0x14},
+ IPPrefixLen: 24,
+ DNSNames: []string{"observed-runtime-name"},
+ }
+ inspect.NetworkSettings.Networks = map[string]*network.EndpointSettings{
+ "z-observer": {Aliases: []string{"observer"}, GwPriority: 10},
+ "app-primary": primaryEndpoint,
+ "a-metrics": {Aliases: []string{"metrics"}, GwPriority: 20},
+ }
+
+ plan, err := buildContainerRecreatePlan(inspect)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if plan.config.Hostname != "operator-hostname" {
+ t.Fatalf("explicit hostname changed: %q", plan.config.Hostname)
+ }
+ assertRecreatePlanPreservesNonNetworkConfiguration(t, inspect, plan)
+ assertPrimaryNetwork(t, plan, "app-primary")
+ if got := []string{plan.additionalNetworks[0].name, plan.additionalNetworks[1].name}; !reflect.DeepEqual(got, []string{"a-metrics", "z-observer"}) {
+ t.Fatalf("additional network order = %v", got)
+ }
+
+ desired := plan.networkingConfig.EndpointsConfig["app-primary"]
+ if !reflect.DeepEqual(desired.IPAMConfig, primaryEndpoint.IPAMConfig) ||
+ !reflect.DeepEqual(desired.Links, primaryEndpoint.Links) ||
+ !reflect.DeepEqual(desired.Aliases, primaryEndpoint.Aliases) ||
+ !reflect.DeepEqual(desired.DriverOpts, primaryEndpoint.DriverOpts) ||
+ desired.GwPriority != primaryEndpoint.GwPriority ||
+ !reflect.DeepEqual(desired.MacAddress, primaryEndpoint.MacAddress) {
+ t.Fatalf("desired endpoint configuration was not preserved: %#v", desired)
+ }
+ if desired.NetworkID != "" || desired.EndpointID != "" || desired.Gateway.IsValid() ||
+ desired.IPAddress.IsValid() || desired.IPPrefixLen != 0 || len(desired.DNSNames) != 0 {
+ t.Fatalf("observed endpoint state leaked into create input: %#v", desired)
+ }
+ desired.Aliases[0] = "changed"
+ desired.DriverOpts["com.example.mode"] = "changed"
+ if primaryEndpoint.Aliases[0] != "app" || primaryEndpoint.DriverOpts["com.example.mode"] != "isolated" {
+ t.Fatal("desired endpoint aliases or driver options alias inspect output")
+ }
+ })
+
+ for _, tc := range []struct {
+ name string
+ networkMode containertypes.NetworkMode
+ }{
+ {name: "compose service shared namespace", networkMode: "container:compose-owner-id"},
+ {name: "standalone container shared namespace", networkMode: "container:standalone-owner-id"},
+ {name: "host namespace", networkMode: "host"},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ inspect := base()
+ inspect.Config.ExposedPorts = network.PortSet{network.MustParsePort("8080/tcp"): {}}
+ inspect.HostConfig.PortBindings = network.PortMap{
+ network.MustParsePort("8080/tcp"): {{HostPort: "8080"}},
+ }
+ inspect.HostConfig.NetworkMode = tc.networkMode
+ // Malformed/legacy inspect output must not cause an explicit
+ // endpoint attachment for namespace-sharing modes.
+ inspect.NetworkSettings.Networks = map[string]*network.EndpointSettings{
+ "bridge": {Aliases: []string{"stale"}},
+ }
+
+ plan, err := buildContainerRecreatePlan(inspect)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if plan.config.Hostname != "" || plan.config.Domainname != "" {
+ t.Fatalf("namespace-owned hostname/domain retained: %q/%q", plan.config.Hostname, plan.config.Domainname)
+ }
+ if plan.networkingConfig != nil || len(plan.additionalNetworks) != 0 {
+ t.Fatalf("shared namespace received endpoint configuration: %#v", plan)
+ }
+ assertRecreatePlanPreservesNonNetworkConfiguration(t, inspect, plan)
+ if tc.networkMode.IsContainer() {
+ if len(plan.config.ExposedPorts) != 0 || len(plan.hostConfig.PortBindings) != 0 {
+ t.Fatal("container namespace retained conflicting port configuration")
+ }
+ } else if len(plan.config.ExposedPorts) != 1 || len(plan.hostConfig.PortBindings) != 1 {
+ t.Fatal("host namespace lost otherwise-valid port configuration")
+ }
+ })
+ }
+}
+
+func TestBuildContainerRecreatePlanRejectsIncompleteInspectBeforeMutation(t *testing.T) {
+ for _, tc := range []struct {
+ name string
+ inspect containertypes.InspectResponse
+ }{
+ {name: "missing config", inspect: containertypes.InspectResponse{HostConfig: &containertypes.HostConfig{}}},
+ {name: "missing host config", inspect: containertypes.InspectResponse{Config: &containertypes.Config{Image: "busybox:1.36"}}},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ pullCalled := false
+ agent := &Agent{
+ docker: &fakeDockerClient{
+ containerInspectFn: func(context.Context, string) (containertypes.InspectResponse, error) {
+ inspect := tc.inspect
+ inspect.Name = "/app"
+ return inspect, nil
+ },
+ imagePullFn: func(context.Context, string, dockerImagePullOptions) (io.ReadCloser, error) {
+ pullCalled = true
+ return nil, errors.New("must not pull")
+ },
+ },
+ logger: zerolog.Nop(),
+ }
+ result := agent.updateContainerWithProgress(context.Background(), "container-id", nil)
+ if result.Success || !strings.Contains(result.Error, "Failed to prepare container recreation") {
+ t.Fatalf("result = %+v", result)
+ }
+ if pullCalled || result.BackupCreated || result.RollbackAttempted {
+ t.Fatalf("invalid inspect crossed mutation boundary: %+v", result)
+ }
+ })
+ }
+}
+
+func TestUpdateContainerRollsBackWhenAdditionalNetworkCannotBeRestored(t *testing.T) {
+ inspect := baseInspect()
+ inspect.ID = strings.Repeat("a", 64)
+ inspect.HostConfig.NetworkMode = "primary"
+ inspect.NetworkSettings.Networks = map[string]*network.EndpointSettings{
+ "secondary": {Aliases: []string{"secondary-alias"}, GwPriority: 10},
+ "primary": {Aliases: []string{"primary-alias"}, GwPriority: 100},
+ }
+
+ var (
+ createdPrimary string
+ removedID string
+ renameCalls [][2]string
+ startedIDs []string
+ progress []string
+ )
+ agent := &Agent{
+ docker: &fakeDockerClient{
+ containerInspectFn: func(context.Context, string) (containertypes.InspectResponse, error) {
+ return inspect, nil
+ },
+ imagePullFn: func(context.Context, string, dockerImagePullOptions) (io.ReadCloser, error) {
+ return io.NopCloser(strings.NewReader("{}")), nil
+ },
+ containerStopFn: func(context.Context, string, dockerContainerStopOptions) error {
+ return nil
+ },
+ containerRenameFn: func(_ context.Context, id, name string) error {
+ renameCalls = append(renameCalls, [2]string{id, name})
+ return nil
+ },
+ containerCreateFn: func(_ context.Context, _ *containertypes.Config, _ *containertypes.HostConfig, networkingConfig *network.NetworkingConfig, _ *v1.Platform, _ string) (containertypes.CreateResponse, error) {
+ for name := range networkingConfig.EndpointsConfig {
+ createdPrimary = name
+ }
+ return containertypes.CreateResponse{ID: "replacement-id"}, nil
+ },
+ networkConnectFn: func(_ context.Context, name, id string, endpoint *network.EndpointSettings) error {
+ if name != "secondary" || id != "replacement-id" || !reflect.DeepEqual(endpoint.Aliases, []string{"secondary-alias"}) {
+ t.Fatalf("unexpected NetworkConnect(%q, %q, %#v)", name, id, endpoint)
+ }
+ return errors.New("network unavailable")
+ },
+ containerRemoveFn: func(_ context.Context, id string, _ dockerContainerRemoveOptions) error {
+ removedID = id
+ return nil
+ },
+ containerStartFn: func(_ context.Context, id string, _ dockerContainerStartOptions) error {
+ startedIDs = append(startedIDs, id)
+ return nil
+ },
+ },
+ logger: zerolog.Nop(),
+ }
+
+ result := agent.updateContainerWithProgress(context.Background(), "original-id", func(step string) {
+ progress = append(progress, step)
+ })
+ if result.Success || !result.BackupCreated || !result.RollbackAttempted || !result.RolledBack {
+ t.Fatalf("network restoration failure did not report successful compensation: %+v", result)
+ }
+ if !strings.Contains(result.Error, "network secondary") {
+ t.Fatalf("network error was not surfaced: %q", result.Error)
+ }
+ if createdPrimary != "primary" || removedID != "replacement-id" {
+ t.Fatalf("primary=%q removed=%q", createdPrimary, removedID)
+ }
+ if len(renameCalls) != 2 || renameCalls[1][0] != result.BackupContainer || renameCalls[1][1] != "app" {
+ t.Fatalf("rollback rename calls = %#v", renameCalls)
+ }
+ if !reflect.DeepEqual(startedIDs, []string{"original-id"}) {
+ t.Fatalf("rollback starts = %v", startedIDs)
+ }
+ if !containsStringFragment(progress, "network secondary") {
+ t.Fatalf("network progress was not reported: %v", progress)
+ }
+}
+
+func assertRecreatePlanPreservesNonNetworkConfiguration(t *testing.T, inspect containertypes.InspectResponse, plan containerRecreatePlan) {
+ t.Helper()
+ if !reflect.DeepEqual(plan.config.Labels, inspect.Config.Labels) ||
+ !reflect.DeepEqual(plan.config.Volumes, inspect.Config.Volumes) ||
+ !reflect.DeepEqual(plan.hostConfig.Binds, inspect.HostConfig.Binds) ||
+ !reflect.DeepEqual(plan.hostConfig.Mounts, inspect.HostConfig.Mounts) ||
+ !reflect.DeepEqual(plan.hostConfig.RestartPolicy, inspect.HostConfig.RestartPolicy) ||
+ plan.hostConfig.NetworkMode != inspect.HostConfig.NetworkMode {
+ t.Fatalf("non-network desired configuration changed: plan=%#v inspect=%#v", plan, inspect)
+ }
+}
+
+func assertPrimaryNetwork(t *testing.T, plan containerRecreatePlan, want string) {
+ t.Helper()
+ if plan.networkingConfig == nil || len(plan.networkingConfig.EndpointsConfig) != 1 {
+ t.Fatalf("networking config = %#v", plan.networkingConfig)
+ }
+ if _, ok := plan.networkingConfig.EndpointsConfig[want]; !ok {
+ t.Fatalf("primary network = %#v, want %q", plan.networkingConfig.EndpointsConfig, want)
+ }
+}
+
+func containsStringFragment(values []string, fragment string) bool {
+ for _, value := range values {
+ if strings.Contains(value, fragment) {
+ return true
+ }
+ }
+ return false
+}
diff --git a/internal/dockeragent/container_update_integration_test.go b/internal/dockeragent/container_update_integration_test.go
new file mode 100644
index 0000000000..65fcfa8d8a
--- /dev/null
+++ b/internal/dockeragent/container_update_integration_test.go
@@ -0,0 +1,311 @@
+package dockeragent
+
+import (
+ "context"
+ "crypto/rand"
+ "encoding/hex"
+ "fmt"
+ "io"
+ "os"
+ "os/exec"
+ "path/filepath"
+ "strings"
+ "testing"
+ "time"
+
+ containertypes "github.com/moby/moby/api/types/container"
+ "github.com/moby/moby/client"
+ "github.com/rs/zerolog"
+)
+
+func TestIntegrationContainerUpdateComposeNetworkLifecycle(t *testing.T) {
+ if os.Getenv("PULSE_RUN_DOCKER_INTEGRATION") != "1" {
+ t.Skip("set PULSE_RUN_DOCKER_INTEGRATION=1 to run live Docker update lifecycle proof")
+ }
+ if _, err := exec.LookPath("docker"); err != nil {
+ t.Skip("docker CLI is unavailable")
+ }
+
+ ctx, cancel := context.WithTimeout(context.Background(), 5*time.Minute)
+ defer cancel()
+ suffix := updateIntegrationSuffix(t)
+ project := "pulseit1564" + suffix
+ testLabel := "pulse.integration.issue1564=" + suffix
+
+ if os.Getenv("DOCKER_HOST") == "" {
+ contextHost, contextErr := exec.CommandContext(ctx, "docker", "context", "inspect", "--format", "{{.Endpoints.docker.Host}}").Output()
+ if contextErr == nil {
+ if host := strings.TrimSpace(string(contextHost)); strings.HasPrefix(host, "unix://") {
+ t.Setenv("DOCKER_HOST", host)
+ }
+ }
+ }
+ rawClient, err := client.New(client.FromEnv, client.WithAPIVersionNegotiation())
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer rawClient.Close()
+ if _, err := rawClient.Info(ctx, client.InfoOptions{}); err != nil {
+ t.Skipf("Docker daemon is unavailable: %v", err)
+ }
+
+ pull, err := rawClient.ImagePull(ctx, "busybox:1.36", client.ImagePullOptions{})
+ if err != nil {
+ t.Fatalf("prepare integration image: %v", err)
+ }
+ _, _ = io.Copy(io.Discard, pull)
+ _ = pull.Close()
+
+ externalOwnerName := project + "-external-owner"
+ externalOwner, err := rawClient.ContainerCreate(ctx, client.ContainerCreateOptions{
+ Name: externalOwnerName,
+ Config: &containertypes.Config{
+ Image: "busybox:1.36",
+ Cmd: []string{"sleep", "300"},
+ Labels: map[string]string{"pulse.integration.issue1564": suffix},
+ },
+ HostConfig: &containertypes.HostConfig{},
+ })
+ if err != nil {
+ t.Fatalf("create external namespace owner: %v", err)
+ }
+ if _, err := rawClient.ContainerStart(ctx, externalOwner.ID, client.ContainerStartOptions{}); err != nil {
+ t.Fatalf("start external namespace owner: %v", err)
+ }
+
+ t.Cleanup(func() {
+ cleanupCtx, cleanupCancel := context.WithTimeout(context.Background(), time.Minute)
+ defer cleanupCancel()
+ result, listErr := rawClient.ContainerList(cleanupCtx, client.ContainerListOptions{
+ All: true,
+ Filters: client.Filters{
+ "label": {testLabel: true},
+ },
+ })
+ if listErr == nil {
+ for _, item := range result.Items {
+ _, _ = rawClient.ContainerRemove(cleanupCtx, item.ID, client.ContainerRemoveOptions{Force: true, RemoveVolumes: true})
+ }
+ }
+ _, _ = rawClient.ContainerRemove(cleanupCtx, externalOwnerName, client.ContainerRemoveOptions{Force: true, RemoveVolumes: true})
+ })
+
+ composeFile := filepath.Join(t.TempDir(), "compose.yaml")
+ composeYAML := fmt.Sprintf(`services:
+ owner:
+ image: busybox:1.36
+ command: ["sleep", "300"]
+ labels:
+ pulse.integration.issue1564: %q
+ networks:
+ - primary
+ bridge:
+ image: busybox:1.36
+ command: ["sleep", "300"]
+ network_mode: bridge
+ labels:
+ pulse.integration.issue1564: %q
+ volumes:
+ - data:/data
+ service_shared:
+ image: busybox:1.36
+ command: ["sleep", "300"]
+ network_mode: service:owner
+ depends_on:
+ owner:
+ condition: service_started
+ labels:
+ pulse.integration.issue1564: %q
+ volumes:
+ - data:/data
+ container_shared:
+ image: busybox:1.36
+ command: ["sleep", "300"]
+ network_mode: container:%s
+ labels:
+ pulse.integration.issue1564: %q
+ volumes:
+ - data:/data
+ host:
+ image: busybox:1.36
+ command: ["sleep", "300"]
+ network_mode: host
+ labels:
+ pulse.integration.issue1564: %q
+ volumes:
+ - data:/data
+ custom:
+ image: busybox:1.36
+ command: ["sleep", "300"]
+ hostname: explicit-custom-host
+ depends_on:
+ owner:
+ condition: service_started
+ labels:
+ pulse.integration.issue1564: %q
+ volumes:
+ - data:/data
+ networks:
+ primary:
+ aliases:
+ - application
+ gw_priority: 100
+ secondary:
+ aliases:
+ - metrics
+ gw_priority: 10
+volumes:
+ data:
+networks:
+ primary:
+ secondary:
+`, suffix, suffix, suffix, externalOwner.ID, suffix, suffix, suffix)
+ if err := os.WriteFile(composeFile, []byte(composeYAML), 0o600); err != nil {
+ t.Fatal(err)
+ }
+ runCompose := func(args ...string) ([]byte, error) {
+ commandArgs := append([]string{"compose", "-f", composeFile, "-p", project}, args...)
+ command := exec.CommandContext(ctx, "docker", commandArgs...)
+ return command.CombinedOutput()
+ }
+ if output, err := runCompose("up", "-d"); err != nil {
+ t.Fatalf("docker compose up: %v\n%s", err, output)
+ }
+ t.Cleanup(func() {
+ cleanupCtx, cleanupCancel := context.WithTimeout(context.Background(), time.Minute)
+ defer cleanupCancel()
+ command := exec.CommandContext(cleanupCtx, "docker", "compose", "-f", composeFile, "-p", project, "down", "--volumes", "--remove-orphans")
+ _ = command.Run()
+ })
+
+ moduleClient, err := newMobyDockerClient(client.FromEnv, client.WithAPIVersionNegotiation())
+ if err != nil {
+ t.Fatal(err)
+ }
+ agent := &Agent{docker: moduleClient, logger: zerolog.Nop()}
+ t.Cleanup(func() { _ = agent.Close() })
+ swap(t, &sleepFn, func(time.Duration) {})
+
+ serviceID := func(service string) string {
+ t.Helper()
+ output, psErr := runCompose("ps", "-q", service)
+ if psErr != nil {
+ t.Fatalf("docker compose ps %s: %v\n%s", service, psErr, output)
+ }
+ id := strings.TrimSpace(string(output))
+ if id == "" {
+ t.Fatalf("docker compose service %s has no container", service)
+ }
+ return id
+ }
+ ownerID := serviceID("owner")
+
+ for _, tc := range []struct {
+ service string
+ wantMode string
+ wantHostname string
+ wantNetworks []string
+ wantDependency bool
+ }{
+ {service: "bridge", wantMode: "bridge", wantNetworks: []string{"bridge"}},
+ {service: "service_shared", wantMode: "container:" + ownerID, wantHostname: ownerID[:12], wantDependency: true},
+ {service: "container_shared", wantMode: "container:" + externalOwner.ID, wantHostname: externalOwner.ID[:12]},
+ {service: "host", wantMode: "host"},
+ {
+ service: "custom", wantMode: project + "_primary", wantHostname: "explicit-custom-host",
+ wantNetworks: []string{project + "_primary", project + "_secondary"}, wantDependency: true,
+ },
+ } {
+ t.Run(tc.service, func(t *testing.T) {
+ oldID := serviceID(tc.service)
+ beforeResult, inspectErr := rawClient.ContainerInspect(ctx, oldID, client.ContainerInspectOptions{})
+ if inspectErr != nil {
+ t.Fatal(inspectErr)
+ }
+ before := beforeResult.Container
+
+ var progress []string
+ result := agent.updateContainerWithProgress(ctx, oldID, func(step string) {
+ progress = append(progress, step)
+ })
+ if !result.Success {
+ t.Fatalf("update failed: %+v (progress=%v)", result, progress)
+ }
+ if result.NewContainerID == "" || result.NewContainerID == oldID || !result.BackupCreated {
+ t.Fatalf("update did not recreate with a backup: %+v", result)
+ }
+
+ afterResult, inspectErr := rawClient.ContainerInspect(ctx, result.NewContainerID, client.ContainerInspectOptions{})
+ if inspectErr != nil {
+ t.Fatal(inspectErr)
+ }
+ after := afterResult.Container
+ if after.State == nil || !after.State.Running {
+ t.Fatalf("replacement is not running: %#v", after.State)
+ }
+ if after.HostConfig == nil || string(after.HostConfig.NetworkMode) != tc.wantMode {
+ t.Fatalf("network mode = %#v, want %q", after.HostConfig, tc.wantMode)
+ }
+ if after.Config == nil || after.Config.Labels["pulse.integration.issue1564"] != suffix ||
+ after.Config.Labels["com.docker.compose.project"] != project ||
+ after.Config.Labels["com.docker.compose.service"] != tc.service {
+ t.Fatalf("Compose and integration labels were not preserved: %#v", after.Config)
+ }
+ if tc.wantDependency && after.Config.Labels["com.docker.compose.depends_on"] == "" {
+ t.Fatalf("Compose dependency metadata was not preserved: %#v", after.Config.Labels)
+ }
+ if !hasMountTarget(after.Mounts, "/data") {
+ t.Fatalf("named volume mount was not preserved: %#v", after.Mounts)
+ }
+ if tc.wantHostname != "" && after.Config.Hostname != tc.wantHostname {
+ t.Fatalf("hostname = %q, want %q", after.Config.Hostname, tc.wantHostname)
+ }
+ if tc.service == "bridge" {
+ if before.Config == nil || before.Config.Hostname != oldID[:12] {
+ t.Fatalf("bridge fixture did not start with a generated hostname: %#v", before.Config)
+ }
+ if after.Config.Hostname != result.NewContainerID[:12] || after.Config.Hostname == before.Config.Hostname {
+ t.Fatalf("generated hostname was not regenerated: before=%q after=%q", before.Config.Hostname, after.Config.Hostname)
+ }
+ }
+ for _, networkName := range tc.wantNetworks {
+ if after.NetworkSettings == nil || after.NetworkSettings.Networks[networkName] == nil {
+ t.Fatalf("network %q was not restored: %#v", networkName, after.NetworkSettings)
+ }
+ }
+ if tc.service == "custom" {
+ if !containsString(after.NetworkSettings.Networks[project+"_primary"].Aliases, "application") ||
+ !containsString(after.NetworkSettings.Networks[project+"_secondary"].Aliases, "metrics") {
+ t.Fatalf("custom network aliases were not preserved: %#v", after.NetworkSettings.Networks)
+ }
+ }
+ })
+ }
+}
+
+func updateIntegrationSuffix(t *testing.T) string {
+ t.Helper()
+ var value [4]byte
+ if _, err := rand.Read(value[:]); err != nil {
+ t.Fatal(err)
+ }
+ return hex.EncodeToString(value[:])
+}
+
+func hasMountTarget(mounts []containertypes.MountPoint, target string) bool {
+ for _, item := range mounts {
+ if item.Destination == target {
+ return true
+ }
+ }
+ return false
+}
+
+func containsString(values []string, want string) bool {
+ for _, value := range values {
+ if value == want {
+ return true
+ }
+ }
+ return false
+}
diff --git a/internal/dockeragent/container_update_test.go b/internal/dockeragent/container_update_test.go
index a9c1958e25..6d208a507a 100644
--- a/internal/dockeragent/container_update_test.go
+++ b/internal/dockeragent/container_update_test.go
@@ -37,7 +37,6 @@ func baseInspect() containertypes.InspectResponse {
NetworkSettings: &containertypes.NetworkSettings{
Networks: map[string]*network.EndpointSettings{
"net1": {Aliases: []string{"app"}},
- "net2": {Aliases: []string{"app2"}},
},
},
}
@@ -260,9 +259,6 @@ func TestUpdateContainer_Success(t *testing.T) {
containerCreateFn: func(context.Context, *containertypes.Config, *containertypes.HostConfig, *network.NetworkingConfig, *v1.Platform, string) (containertypes.CreateResponse, error) {
return containertypes.CreateResponse{ID: "new123"}, nil
},
- networkConnectFn: func(context.Context, string, string, *network.EndpointSettings) error {
- return errors.New("network connect failed")
- },
containerStartFn: func(context.Context, string, dockerContainerStartOptions) error {
return nil
},
diff --git a/internal/dockeragent/container_update_typed_test.go b/internal/dockeragent/container_update_typed_test.go
new file mode 100644
index 0000000000..a6c1fde4cd
--- /dev/null
+++ b/internal/dockeragent/container_update_typed_test.go
@@ -0,0 +1,121 @@
+package dockeragent
+
+import (
+ "context"
+ "io"
+ "strings"
+ "testing"
+ "time"
+
+ containertypes "github.com/moby/moby/api/types/container"
+ "github.com/moby/moby/api/types/network"
+ v1 "github.com/opencontainers/image-spec/specs-go/v1"
+ "github.com/rs/zerolog"
+)
+
+func TestTypedContainerUpdatePreflightRefusesRuntimeAndDigestDrift(t *testing.T) {
+ t.Run("runtime mismatch", func(t *testing.T) {
+ inspectCalled := false
+ agent := &Agent{
+ runtime: RuntimeDocker,
+ docker: &fakeDockerClient{
+ containerInspectFn: func(context.Context, string) (containertypes.InspectResponse, error) {
+ inspectCalled = true
+ return baseInspect(), nil
+ },
+ },
+ }
+ if _, err := agent.TypedContainerUpdate(context.Background(), "podman", "container-id", "", nil); err == nil ||
+ !strings.Contains(err.Error(), "runtime mismatch") {
+ t.Fatalf("runtime mismatch error = %v", err)
+ }
+ if inspectCalled {
+ t.Fatal("runtime mismatch reached the daemon")
+ }
+ })
+
+ t.Run("digest drift", func(t *testing.T) {
+ pullCalled := false
+ agent := &Agent{
+ runtime: RuntimeDocker,
+ docker: &fakeDockerClient{
+ containerInspectFn: func(context.Context, string) (containertypes.InspectResponse, error) {
+ return baseInspect(), nil
+ },
+ imagePullFn: func(context.Context, string, dockerImagePullOptions) (io.ReadCloser, error) {
+ pullCalled = true
+ return io.NopCloser(strings.NewReader("{}")), nil
+ },
+ },
+ }
+ if _, err := agent.TypedContainerUpdate(context.Background(), "docker", "container-id", "sha256:planned", nil); err == nil ||
+ !strings.Contains(err.Error(), "digest no longer matches") {
+ t.Fatalf("digest drift error = %v", err)
+ }
+ if pullCalled {
+ t.Fatal("digest drift crossed the mutation preflight")
+ }
+ })
+}
+
+func TestTypedContainerUpdateDelegatesToProductionRecreatePath(t *testing.T) {
+ swap(t, &sleepFn, func(time.Duration) {})
+ swap(t, &newTimerFn, func(time.Duration) *time.Timer { return time.NewTimer(0) })
+
+ cleanupDone := make(chan struct{})
+ agent := &Agent{
+ runtime: RuntimeDocker,
+ docker: &fakeDockerClient{
+ containerInspectFn: func(_ context.Context, id string) (containertypes.InspectResponse, error) {
+ inspect := baseInspect()
+ if id == "replacement-id" {
+ inspect.Image = "sha256:new"
+ }
+ return inspect, nil
+ },
+ imagePullFn: func(context.Context, string, dockerImagePullOptions) (io.ReadCloser, error) {
+ return io.NopCloser(strings.NewReader("{}")), nil
+ },
+ containerStopFn: func(context.Context, string, dockerContainerStopOptions) error {
+ return nil
+ },
+ containerRenameFn: func(context.Context, string, string) error {
+ return nil
+ },
+ containerCreateFn: func(context.Context, *containertypes.Config, *containertypes.HostConfig, *network.NetworkingConfig, *v1.Platform, string) (containertypes.CreateResponse, error) {
+ return containertypes.CreateResponse{ID: "replacement-id"}, nil
+ },
+ containerStartFn: func(context.Context, string, dockerContainerStartOptions) error {
+ return nil
+ },
+ containerRemoveFn: func(context.Context, string, dockerContainerRemoveOptions) error {
+ close(cleanupDone)
+ return nil
+ },
+ },
+ logger: zerolog.Nop(),
+ }
+
+ var progress []string
+ outcome, err := agent.TypedContainerUpdate(
+ context.Background(),
+ "docker",
+ "container-id",
+ "sha256:old0000000000",
+ func(step string) { progress = append(progress, step) },
+ )
+ if err != nil {
+ t.Fatal(err)
+ }
+ if !outcome.Success || outcome.OldContainerID != "container-id" ||
+ outcome.NewContainerID != "replacement-id" || !outcome.BackupCreated ||
+ outcome.NewImageDigest != "sha256:new" {
+ t.Fatalf("typed outcome = %+v", outcome)
+ }
+ if !containsStringFragment(progress, "Pulling image") ||
+ !containsStringFragment(progress, "Creating new container") ||
+ !containsStringFragment(progress, "Verifying container stability") {
+ t.Fatalf("typed production-path progress = %v", progress)
+ }
+ <-cleanupDone
+}
diff --git a/internal/hostagent/docker_lifecycle_test.go b/internal/hostagent/docker_lifecycle_test.go
index c59f5e6ebb..bc23bb7e81 100644
--- a/internal/hostagent/docker_lifecycle_test.go
+++ b/internal/hostagent/docker_lifecycle_test.go
@@ -4,11 +4,17 @@ import (
"context"
"encoding/json"
"fmt"
+ "net/http"
+ "net/http/httptest"
+ "path/filepath"
"strings"
"testing"
"time"
+ "github.com/gorilla/websocket"
"github.com/rcourtman/pulse-go-rewrite/internal/agentexec"
+ "github.com/rcourtman/pulse-go-rewrite/internal/operationreceipt"
+ "github.com/rs/zerolog"
)
const dockerLifecycleTestContainerID = "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef"
@@ -93,9 +99,13 @@ func dockerLifecycleTestRequest(t *testing.T, startedAt time.Time) agentexec.Doc
type stubDockerUpdater struct {
outcome agentexec.DockerContainerUpdateOutcome
err error
+ calls *int
}
func (s stubDockerUpdater) TypedContainerUpdate(_ context.Context, _, _, _ string, _ func(string)) (agentexec.DockerContainerUpdateOutcome, error) {
+ if s.calls != nil {
+ *s.calls++
+ }
return s.outcome, s.err
}
@@ -205,3 +215,70 @@ func TestHostOperationReceiptConfigAcceptsDockerUpdateReceipts(t *testing.T) {
t.Fatalf("terminal receipt for a successful update was rejected: %v", err)
}
}
+
+func TestDockerContainerUpdateTerminalReceiptReplaysAfterAgentReconnect(t *testing.T) {
+ payload := boundUpdatePayload(t)
+ newID := strings.Repeat("b", 12)
+ updateCalls := 0
+ client := newUpdateTestClient(stubDockerUpdater{
+ outcome: agentexec.DockerContainerUpdateOutcome{
+ Success: true, ContainerName: "app", OldContainerID: payload.ContainerID, NewContainerID: newID,
+ OldImageDigest: "sha256:" + strings.Repeat("1", 64), NewImageDigest: "sha256:" + strings.Repeat("2", 64),
+ BackupCreated: true, BackupContainer: "app_pulse_backup_20260714_120000",
+ },
+ calls: &updateCalls,
+ })
+ client.logger = zerolog.Nop()
+ receipts, err := operationreceipt.Open(filepath.Join(t.TempDir(), "receipts.db"), hostOperationReceiptConfig())
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer receipts.Close()
+ client.operationReceipts = receipts
+
+ upgrader := websocket.Upgrader{CheckOrigin: func(*http.Request) bool { return true }}
+ serverConnections := make(chan *websocket.Conn)
+ releaseConnections := make(chan struct{})
+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ conn, upgradeErr := upgrader.Upgrade(w, r, nil)
+ if upgradeErr != nil {
+ t.Errorf("upgrade: %v", upgradeErr)
+ return
+ }
+ serverConnections <- conn
+ <-releaseConnections
+ _ = conn.Close()
+ }))
+ defer server.Close()
+
+ wsURL := "ws" + strings.TrimPrefix(server.URL, "http")
+ for attempt := 0; attempt < 2; attempt++ {
+ remote, _, dialErr := websocket.DefaultDialer.Dial(wsURL, nil)
+ if dialErr != nil {
+ t.Fatal(dialErr)
+ }
+ serverConn := <-serverConnections
+
+ client.handleDockerContainerUpdate(context.Background(), serverConn, payload)
+ var message wsMessage
+ if readErr := remote.ReadJSON(&message); readErr != nil {
+ t.Fatalf("attempt %d read result: %v", attempt+1, readErr)
+ }
+ if message.Type != msgTypeDockerContainerUpdateResult {
+ t.Fatalf("attempt %d message type = %q", attempt+1, message.Type)
+ }
+ var result agentexec.DockerContainerUpdateResultPayload
+ if decodeErr := json.Unmarshal(message.Payload, &result); decodeErr != nil {
+ t.Fatal(decodeErr)
+ }
+ if result.NewContainerID != newID || result.RequestID != payload.RequestID || !result.MutationCompleted {
+ t.Fatalf("attempt %d result = %+v", attempt+1, result)
+ }
+
+ _ = remote.Close()
+ releaseConnections <- struct{}{}
+ }
+ if updateCalls != 1 {
+ t.Fatalf("docker update executed %d times across reconnect, want 1", updateCalls)
+ }
+}