Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
60 changes: 59 additions & 1 deletion pkg/container/docker/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down Expand Up @@ -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 {
Expand Down Expand Up @@ -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 (
Expand All @@ -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)
}
}()
Comment on lines +286 to +298

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[MEDIUM] Failure cleanup removes the reused network and sidecars of a restarted workload

mcpCreated only says whether this call created the MCP container. thv restart stops the workload (StopWorkload leaves the MCP container and network in place) and then reaches DeployWorkload, where createNetwork, createDnsContainer and createContainer reuse what already exists. If a step before createMcpContainer fails (gateway discovery, egress setup, port bindings), this defer removes the network and the dns/egress/ingress containers of a workload whose MCP container is still there, so the comment above ("thv rm cannot find them") is not true on that path. Before this change the network survived and a retry could succeed. I could not confirm from the code whether Docker then refuses to start the old container against the recreated network, but createAndStartContainer already handles a start that fails because "its network vanished", so the failure mode is known.

Recommendation: only clean up what this call created. For example, check findExistingContainer(ctx, name) before createNetwork and skip the defer (or at least the network removal) when the MCP container already exists. If removing them is the intended trade-off, say so in a comment here. Either way, add a test with a pre-existing MCP container and a pre-MCP failure.

Raised by: correctness, scope discipline, tests. Verified: confirmed.


// Start or reuse DNS normally before reading Podman's generated hosts.
dnsContainerName := fmt.Sprintf("%s-dns", name)
Expand Down Expand Up @@ -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" {
Expand Down Expand Up @@ -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{
Expand Down
121 changes: 121 additions & 0 deletions pkg/container/docker/client_cleanup_test.go
Original file line number Diff line number Diff line change
@@ -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/<id>" or "network/<id>"
}

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)
})
}
}
Loading
Loading