diff --git a/pkg/container/docker/client.go b/pkg/container/docker/client.go index 2b3adf6a6d..40c95bb163 100644 --- a/pkg/container/docker/client.go +++ b/pkg/container/docker/client.go @@ -122,6 +122,9 @@ type deployOps interface { ) error getContainerNetworkIP(ctx context.Context, containerName, networkName string) (string, error) discoverBridgeGateways(ctx context.Context) ([]netip.Addr, error) + // cleanupFailedIsolation best-effort removes the auxiliary containers and + // the internal network created for a workload whose setup failed. + cleanupFailedIsolation(ctx context.Context, name, networkName string) } // Client implements the Deployer interface for Docker (and compatible runtimes) @@ -189,7 +192,7 @@ func (c *Client) DeployWorkload( transportType string, options *runtime.DeployWorkloadOptions, isolateNetwork bool, -) (int, error) { +) (_ int, retErr error) { // Get permission config from profile var ignoreConfig *ignore.Config if options != nil { @@ -253,6 +256,10 @@ func (c *Client) DeployWorkload( } networkIsolation := false + // mcpCreated is set once the MCP container exists. From then on `thv rm` + // can find the auxiliary containers and network through it, and removing + // them here would leave the MCP container without its network. + mcpCreated := false // pspec and egress are populated in the isolation block and reused by // SetupIngress after the MCP container is created. var ( @@ -262,12 +269,33 @@ func (c *Client) DeployWorkload( if effectiveIsolation { networkIsolation = true + // A restart reaches this point with the stopped MCP container still in + // place, so the network and sidecars below belong to an existing + // workload and must survive a failed attempt. If the lookup fails, + // assume the container exists: leaving resources behind beats removing + // ones a workload depends on. + existingMcpID, lookupErr := c.findExistingContainer(ctx, name) + mcpExisted := lookupErr != nil || existingMcpID != "" + internalNetworkLabels := map[string]string{} lb.AddNetworkLabels(internalNetworkLabels, networkName) err := c.ops.createNetwork(ctx, networkName, internalNetworkLabels, true) if err != nil { return 0, fmt.Errorf("failed to create internal network: %w", err) } + // The internal network and the dns/egress/ingress containers are not + // tied to the MCP container yet, so `thv rm` cannot find them if setup + // fails before the MCP container is created. Remove them in that case, + // but only for a new workload (see mcpExisted above). + defer func() { + if retErr != nil && !mcpCreated && !mcpExisted { + // Detach from the caller's cancellation so a cancelled request + // still cleans up, but bound the cleanup so it cannot hang. + cleanupCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), 30*time.Second) + defer cancel() + c.ops.cleanupFailedIsolation(cleanupCtx, name, networkName) + } + }() // Start or reuse DNS normally before reading Podman's generated hosts. dnsContainerName := fmt.Sprintf("%s-dns", name) @@ -344,6 +372,7 @@ func (c *Client) DeployWorkload( if err != nil { return 0, fmt.Errorf("failed to create mcp container: %w", err) } + mcpCreated = true // Don't try and set up an ingress proxy if the transport type is stdio. if transportType == "stdio" { @@ -1394,6 +1423,35 @@ func (c *Client) deleteNetwork(ctx context.Context, name string) error { return nil } +// cleanupFailedIsolation best-effort removes the egress, ingress and dns +// containers and the internal network of a workload whose setup failed. Every +// sidecar is attempted and the network is always deleted, even when an earlier +// step fails. Failures are logged: the original setup error is what the caller +// needs. +func (c *Client) cleanupFailedIsolation(ctx context.Context, name, networkName string) { + var errs []error + for _, suffix := range []string{"egress", "ingress", "dns"} { + sidecarName := fmt.Sprintf("%s-%s", name, suffix) + id, err := c.findExistingContainer(ctx, sidecarName) + if err != nil { + errs = append(errs, fmt.Errorf("find %s container: %w", suffix, err)) + continue + } + if id == "" { + continue + } + if err := c.removeContainer(ctx, id); err != nil { + errs = append(errs, fmt.Errorf("remove %s container: %w", suffix, err)) + } + } + if err := c.deleteNetwork(ctx, networkName); err != nil { + errs = append(errs, fmt.Errorf("remove internal network %s: %w", networkName, err)) + } + if err := errors.Join(errs...); err != nil { + slog.Warn("failed to fully clean up after failed setup", "name", name, "error", err) + } +} + // removeContainer removes a container by ID, without removing any associated networks or proxy containers. func (c *Client) removeContainer(ctx context.Context, containerID string) error { _, err := c.api.ContainerRemove(ctx, containerID, mobyclient.ContainerRemoveOptions{ diff --git a/pkg/container/docker/client_cleanup_test.go b/pkg/container/docker/client_cleanup_test.go new file mode 100644 index 0000000000..9d21fee6d5 --- /dev/null +++ b/pkg/container/docker/client_cleanup_test.go @@ -0,0 +1,121 @@ +// SPDX-FileCopyrightText: Copyright 2026 Stacklok, Inc. +// SPDX-License-Identifier: Apache-2.0 + +package docker + +import ( + "encoding/json" + "net/http" + "strings" + "sync" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +// fakeDaemon is a minimal Docker daemon that serves container and network +// lookups for the given names and records every removal request. +type fakeDaemon struct { + mu sync.Mutex + containers map[string]bool // container names that exist + networks map[string]bool // network names that exist + failRemove map[string]bool // container IDs whose removal returns 500 + removed []string // "container/" or "network/" +} + +func (d *fakeDaemon) handler(t *testing.T) http.HandlerFunc { + t.Helper() + // nameFilter extracts the single "name" filter value of a list request. + nameFilter := func(r *http.Request) string { + var filters map[string]map[string]bool + require.NoError(t, json.Unmarshal([]byte(r.URL.Query().Get("filters")), &filters)) + for name := range filters["name"] { + return name + } + return "" + } + return func(w http.ResponseWriter, r *http.Request) { + d.mu.Lock() + defer d.mu.Unlock() + path := strings.TrimPrefix(r.URL.Path, "/v1.44") + switch { + case r.Method == http.MethodGet && path == "/containers/json": + name := nameFilter(r) + list := []map[string]any{} + if d.containers[name] { + list = append(list, map[string]any{"Id": "id-" + name, "Names": []string{"/" + name}}) + } + assert.NoError(t, json.NewEncoder(w).Encode(list)) + case r.Method == http.MethodDelete && strings.HasPrefix(path, "/containers/"): + id := strings.TrimPrefix(path, "/containers/") + d.removed = append(d.removed, "container/"+id) + if d.failRemove[id] { + http.Error(w, `{"message":"cannot remove"}`, http.StatusInternalServerError) + return + } + w.WriteHeader(http.StatusNoContent) + case r.Method == http.MethodGet && path == "/networks": + name := nameFilter(r) + list := []map[string]any{} + if d.networks[name] { + list = append(list, map[string]any{"Name": name, "Id": "net-" + name}) + } + assert.NoError(t, json.NewEncoder(w).Encode(list)) + case r.Method == http.MethodDelete && strings.HasPrefix(path, "/networks/"): + d.removed = append(d.removed, "network/"+strings.TrimPrefix(path, "/networks/")) + w.WriteHeader(http.StatusNoContent) + default: + t.Errorf("unexpected request %s %s", r.Method, r.URL.Path) + http.Error(w, "unexpected", http.StatusNotImplemented) + } + } +} + +func TestCleanupFailedIsolation(t *testing.T) { + t.Parallel() + + const network = "toolhive-app-internal" + tests := []struct { + name string + daemon *fakeDaemon + wantRemoved []string + }{ + { + name: "removes all sidecars and the network", + daemon: &fakeDaemon{ + containers: map[string]bool{"app-egress": true, "app-ingress": true, "app-dns": true}, + networks: map[string]bool{network: true}, + }, + wantRemoved: []string{"container/id-app-egress", "container/id-app-ingress", "container/id-app-dns", "network/net-" + network}, + }, + { + name: "a sidecar that fails to remove does not stop the network deletion", + daemon: &fakeDaemon{ + containers: map[string]bool{"app-egress": true, "app-ingress": true, "app-dns": true}, + networks: map[string]bool{network: true}, + failRemove: map[string]bool{"id-app-egress": true}, + }, + wantRemoved: []string{"container/id-app-egress", "container/id-app-ingress", "container/id-app-dns", "network/net-" + network}, + }, + { + name: "absent network is not an error", + daemon: &fakeDaemon{ + containers: map[string]bool{"app-dns": true}, + networks: map[string]bool{}, + }, + wantRemoved: []string{"container/id-app-dns"}, + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + api := discoveryHTTPClient(t, tt.daemon.handler(t)) + client := &Client{client: api, api: api} + + client.cleanupFailedIsolation(t.Context(), "app", network) + + assert.Equal(t, tt.wantRemoved, tt.daemon.removed) + }) + } +} diff --git a/pkg/container/docker/client_deploy_test.go b/pkg/container/docker/client_deploy_test.go index 6cfb784f66..894fc1739c 100644 --- a/pkg/container/docker/client_deploy_test.go +++ b/pkg/container/docker/client_deploy_test.go @@ -13,8 +13,10 @@ import ( "io" "net/http" "net/netip" + "strconv" "testing" + "github.com/moby/moby/api/types/container" "github.com/moby/moby/api/types/network" mobyclient "github.com/moby/moby/client" "github.com/stretchr/testify/assert" @@ -65,11 +67,20 @@ type fakeDeployOps struct { // callOrder tracks the sequence of operation calls for ordering assertions. callOrder *[]string + // cleanupCalls records cleanupFailedIsolation invocations as "workload/network". + cleanupCalls []string + // cleanupCtxErr and cleanupHasDeadline describe the context cleanup ran with. + cleanupCtxErr error + cleanupHasDeadline bool + // error injection errExternalNetworks error errCreateNetwork error errDNS error errMcp error + + // onCreateDNS, when set, runs inside createDnsContainer before it returns. + onCreateDNS func() } func (f *fakeDeployOps) createExternalNetworks(_ context.Context) error { @@ -110,9 +121,18 @@ func (f *fakeDeployOps) createDnsContainer(_ context.Context, _ string, _ bool, *f.callOrder = append(*f.callOrder, "createDnsContainer") } f.dnsCalled = true + if f.onCreateDNS != nil { + f.onCreateDNS() + } return f.dnsID, f.dnsIP, f.errDNS } +func (f *fakeDeployOps) cleanupFailedIsolation(ctx context.Context, name, networkName string) { + f.cleanupCalls = append(f.cleanupCalls, name+"/"+networkName) + f.cleanupCtxErr = ctx.Err() + _, f.cleanupHasDeadline = ctx.Deadline() +} + func (f *fakeDeployOps) getContainerNetworkIP(_ context.Context, _, _ string) (string, error) { return f.mcpIP, f.errMcpIP } @@ -156,8 +176,9 @@ type fakeNetworkProxy struct { setupCalled bool // SetupEgress was called ingressCalled bool // SetupIngress was called capturedSpec proxySpec - ingressPort int // returned by SetupIngress - err error + ingressPort int // returned by SetupIngress + err error // returned by SetupEgress (and SetupIngress when errIngress is nil) + errIngress error // returned by SetupIngress only, when set // callOrder tracks cross-component ordering when shared with fakeDeployOps. callOrder *[]string } @@ -182,6 +203,9 @@ func (f *fakeNetworkProxy) SetupIngress(_ context.Context, spec proxySpec, _ egr } f.ingressCalled = true f.capturedSpec = spec + if f.errIngress != nil { + return 0, f.errIngress + } if f.err != nil { return 0, f.err } @@ -671,6 +695,119 @@ func TestDeployWorkload_GatewayDiscoveryFailsClosed(t *testing.T) { assert.False(t, fops.mcpCalled) } +var errBoom = errors.New("boom") + +// TestDeployWorkload_SetupFailureCleanup pins when a failed deploy removes the +// isolation resources (internal network, DNS, proxies): only for a new +// workload that failed before its MCP container exists. Once the MCP container +// exists, `thv rm` cleans up through RemoveWorkload; a restart keeps the +// resources that belong to the existing workload; without isolation there is +// nothing to clean up. +func TestDeployWorkload_SetupFailureCleanup(t *testing.T) { + t.Parallel() + + badPortBinding := func() *runtime.DeployWorkloadOptions { + opts := runtime.NewDeployWorkloadOptions() + opts.ExposedPorts = map[string]struct{}{"8080/tcp": {}} + opts.PortBindings = map[string][]runtime.PortBinding{"8080/tcp": {{HostIP: "127.0.0.1", HostPort: "not-a-port"}}} + return opts + } + ingressOpts := func() *runtime.DeployWorkloadOptions { + opts := runtime.NewDeployWorkloadOptions() + opts.ExposedPorts = map[string]struct{}{"8080/tcp": {}} + opts.PortBindings = map[string][]runtime.PortBinding{"8080/tcp": {{HostIP: "127.0.0.1", HostPort: ""}}} + return opts + } + existingMcp := &existingLookup{items: []container.Summary{{ID: "mcp-id", Names: []string{"/app"}}}} + failedLookup := &existingLookup{err: errors.New("daemon unavailable")} + + tests := []struct { + name string + fops *fakeDeployOps + fproxy *fakeNetworkProxy + transport string + isolate bool + opts func() *runtime.DeployWorkloadOptions // nil means defaults + existing *existingLookup // nil means no existing MCP container + wantErr error + wantCleanup bool + wantMcp bool + }{ + {name: "dns container creation fails", fops: &fakeDeployOps{errDNS: errBoom}, fproxy: &fakeNetworkProxy{}, transport: "stdio", isolate: true, wantErr: errBoom, wantCleanup: true}, + {name: "gateway discovery fails", fops: &fakeDeployOps{errGateways: errBoom}, fproxy: &fakeNetworkProxy{}, transport: "stdio", isolate: true, wantErr: errBoom, wantCleanup: true}, + {name: "egress setup fails", fops: &fakeDeployOps{}, fproxy: &fakeNetworkProxy{err: errBoom}, transport: "stdio", isolate: true, wantErr: errBoom, wantCleanup: true}, + {name: "port binding is invalid", fops: &fakeDeployOps{}, fproxy: &fakeNetworkProxy{}, transport: "stdio", isolate: true, opts: badPortBinding, wantErr: strconv.ErrSyntax, wantCleanup: true}, + {name: "mcp container creation fails", fops: &fakeDeployOps{errMcp: errBoom}, fproxy: &fakeNetworkProxy{}, transport: "stdio", isolate: true, wantErr: errBoom, wantCleanup: true, wantMcp: true}, + {name: "internal network creation fails", fops: &fakeDeployOps{errCreateNetwork: errBoom}, fproxy: &fakeNetworkProxy{}, transport: "stdio", isolate: true, wantErr: errBoom}, + {name: "success keeps resources", fops: &fakeDeployOps{}, fproxy: &fakeNetworkProxy{}, transport: "stdio", isolate: true, wantMcp: true}, + {name: "mcp ip lookup fails after mcp container exists", fops: &fakeDeployOps{errMcpIP: errBoom}, fproxy: &fakeNetworkProxy{}, transport: "sse", isolate: true, opts: ingressOpts, wantErr: errBoom, wantMcp: true}, + {name: "ingress setup fails after mcp container exists", fops: &fakeDeployOps{}, fproxy: &fakeNetworkProxy{errIngress: errBoom}, transport: "sse", isolate: true, opts: ingressOpts, wantErr: errBoom, wantMcp: true}, + {name: "no isolation, mcp container creation fails", fops: &fakeDeployOps{errMcp: errBoom}, fproxy: &fakeNetworkProxy{}, transport: "stdio", isolate: false, opts: ingressOpts, wantErr: errBoom, wantMcp: true}, + {name: "restart with stopped mcp container keeps resources", fops: &fakeDeployOps{errDNS: errBoom}, fproxy: &fakeNetworkProxy{}, transport: "stdio", isolate: true, existing: existingMcp, wantErr: errBoom}, + {name: "restart with failed existence lookup keeps resources", fops: &fakeDeployOps{errDNS: errBoom}, fproxy: &fakeNetworkProxy{}, transport: "stdio", isolate: true, existing: failedLookup, wantErr: errBoom}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + client := newClientWithOpsAndProxy(tt.fops, tt.fproxy) + if tt.existing != nil { + client.api = &fakeDockerAPI{listFunc: func(_ context.Context, _ mobyclient.ContainerListOptions) ([]container.Summary, error) { + return tt.existing.items, tt.existing.err + }} + } + opts := runtime.NewDeployWorkloadOptions() + if tt.opts != nil { + opts = tt.opts() + } + _, err := client.DeployWorkload( + t.Context(), "image", "app", nil, nil, map[string]string{}, + &permissions.Profile{}, tt.transport, opts, tt.isolate, + ) + if tt.wantErr != nil { + require.ErrorIs(t, err, tt.wantErr) + } else { + require.NoError(t, err) + } + assert.Equal(t, tt.wantMcp, tt.fops.mcpCalled) + if tt.wantCleanup { + assert.Equal(t, []string{"app/toolhive-app-internal"}, tt.fops.cleanupCalls) + } else { + assert.Empty(t, tt.fops.cleanupCalls) + } + }) + } +} + +// existingLookup is what the fake Docker API returns when DeployWorkload looks +// for an already existing MCP container by name. +type existingLookup struct { + items []container.Summary + err error +} + +// TestDeployWorkload_CleanupSurvivesCancelledContextWithDeadline pins that the +// cleanup is detached from the caller's cancellation (a cancelled request must +// still remove its leaked resources) and is bounded by its own timeout. +func TestDeployWorkload_CleanupSurvivesCancelledContextWithDeadline(t *testing.T) { + t.Parallel() + + ctx, cancel := context.WithCancel(t.Context()) + // Cancel from inside the failing step (after the existing-container lookup + // has run) so the deploy fails with a cancelled context, as when a request + // is aborted mid-setup. + fops := &fakeDeployOps{errDNS: context.Canceled, onCreateDNS: cancel} + client := newClientWithOpsAndProxy(fops, &fakeNetworkProxy{}) + + _, err := client.DeployWorkload( + ctx, "image", "app", nil, nil, map[string]string{}, + &permissions.Profile{}, "stdio", runtime.NewDeployWorkloadOptions(), true, + ) + require.ErrorIs(t, err, context.Canceled) + require.Equal(t, []string{"app/toolhive-app-internal"}, fops.cleanupCalls) + require.NoError(t, fops.cleanupCtxErr, "cleanup must not inherit the caller's cancellation") + require.True(t, fops.cleanupHasDeadline, "cleanup must be bounded by its own timeout") +} + // Both runtimes read their host-access alias from the running DNS sidecar and // fail closed when it is missing. On Docker this is the host-gateway address, // which on Docker Desktop is not any bridge network's gateway.