diff --git a/docs/arch/08-workloads-lifecycle.md b/docs/arch/08-workloads-lifecycle.md index e3288960e2..49dc03118f 100644 --- a/docs/arch/08-workloads-lifecycle.md +++ b/docs/arch/08-workloads-lifecycle.md @@ -19,7 +19,11 @@ stateDiagram-v2 Starting --> Running: Success Starting --> Error: Failed + Starting --> Stopping: Stop Running --> Stopping: Stop + Unhealthy --> Stopping: Stop + Unauthenticated --> Stopping: Stop + AuthRetrying --> Stopping: Stop Running --> Unhealthy: Health Failed Running --> Unauthenticated: Auth Failed Running --> AuthRetrying: Transient Token Refresh Failures @@ -81,8 +85,36 @@ thv stop my-server **Container workload**: Stops proxy process → stops container → preserves state +Stopping a workload by name always cleans up its proxy and asks the runtime to +stop the container, even when the container has exited or is gone. This stops a +supervisor that is waiting in restart backoff. Auxiliary workloads have no proxy +to clean up. + +Stop writes `Stopping` and then `Stopped`, and removes client configuration, +only when something was live: the container was running or the recorded PID is +the workload's running supervisor. Otherwise stop leaves the current status +alone, so an `Error` or `PolicyStopped` workload keeps its status and reason, +even if a stale PID is still recorded. If the recorded PID is alive but can't be +inspected, stop fails instead, because it can neither signal that process nor +know that it has stopped. See [Proxy termination](#proxy-termination). + +`thv stop --all` and `--group` skip `Starting` workloads, including supervisors +waiting in restart backoff. Stop them by name. + +Stop keeps the saved run configuration, but a foreground `run` deletes its +workload when it exits. Stop waits at most five seconds for the supervisor to +exit, so it can return before that cleanup finishes. Before it writes the final +status, stop checks that the saved configuration still exists, and skips the +write if it is gone. The check and the write are not atomic, so a concurrent +delete can still race with stop. Stop does not create status for a name it +doesn't know. + **Remote workload**: Stops proxy → preserves state +Stop moves a remote workload from `Running`, `Starting`, `AuthRetrying`, +`Unauthenticated`, or `Unhealthy` to `Stopped`, with the same saved +configuration check. Other statuses are left alone. + **Implementation**: `pkg/workloads/manager.go` ### Start @@ -104,6 +136,27 @@ thv rm my-server **Container workload**: Stops proxy → removes container → deletes state +Delete stops the supervisor before it removes the container. If the container +lookup finds nothing but a saved run configuration exists, delete still asks the +runtime to remove the workload, because a supervisor in backoff can create the +container again. If that removal fails and the container still can't be found, +delete logs the error and cleans up the saved state. If the container now +exists, delete returns the error and keeps the saved state so you can retry. A +name with no container and no saved run configuration skips runtime removal. + +Delete uses the container's runtime name when it finds one, then the saved +`ContainerName`, then the workload name. + +The Docker runtime only deletes networks that carry the `toolhive=true` and +workload name labels. It leaves unlabelled networks alone, even when their +names match ToolHive's naming scheme. + +Delete fails, sets the status to `Error`, and keeps the container and saved +state if the supervisor can't be confirmed gone: it is still running after +being killed, or its recorded PID is alive but can't be inspected. +Retry once the supervisor has exited. See +[Proxy termination](#proxy-termination). + **Remote workload**: Stops proxy → deletes state **Implementation**: `pkg/workloads/manager.go` @@ -136,9 +189,65 @@ The same `Applier` backs both the CLI (`thv upgrade apply`) and the API (`POST / ### Proxy termination -Stop and delete terminate the proxy using its recorded PID. When PID-based termination is unavailable or fails (for example, the status file is missing, records no PID, or the process is already gone), they fall back to port-based cleanup: the process holding the proxy port is terminated only after it is confirmed to be this workload's proxy. This prevents an orphaned proxy from continuing to hold the port after the container has been stopped or removed. - -**Implementation**: `pkg/workloads/manager.go` +Before signalling the PID in the status file, stop and delete check that it +belongs to this workload's ToolHive supervisor. A detached supervisor must have +the exact workload name on its command line. A foreground supervisor must be a +`thv` process whose subcommand, the first argument that is not a flag, is +`run`, `start`, or `restart`. Only the ToolHive arguments before `--` are +checked, because everything after `--` goes to the MCP server. + +- `start` and `restart` must have the workload name as a whole argument, unless + they select workloads with `--all`/`-a` or `--group`/`-g`. +- `run` must have `--name ` or `--name=`. A `run` without + `--name`, such as `thv run ` or `thv run --from-config `, is + accepted without a name, because its name comes from the image or the file. + +There is no process start-time check, so if the OS reuses the PID for another +matching `thv` command, ToolHive can't tell. A recorded PID is never signalled +unless it passes this check: + +- A process that was inspected and doesn't match, for example after the OS + reused the PID, is left alone and its PID stays recorded. Stop and delete + carry on as if no supervisor were running. +- A process that is alive but can't be inspected, for example because it + belongs to another user, makes stop, delete, start, and restart fail with an + error. It could still be the supervisor, and ToolHive won't report success + while it may be restarting the container. +- A PID whose process has exited is cleared. + +On Unix, ToolHive sends SIGTERM. On Windows, it uses TerminateProcess, which is +a hard stop. Either way it waits up to five seconds for the process to exit. +A supervisor's shutdown stops its containers one at a time with the runtime's +stop timeout, so it can take a minute when a container ignores SIGTERM. Stop +carries on and leaves it to finish. Delete, start, and restart can't overlap +with that shutdown, so they kill a supervisor that is still exiting (SIGKILL on +Unix), wait up to five more seconds, and fail if it is still running. Delete +then removes the containers itself, and start and restart replace them. + +If there is no PID to signal, or the process doesn't match, stop and delete +fall back to freeing the proxy port when the saved configuration allows +it. The port holder must match the workload exactly, and the fallback also +waits up to five seconds. This fallback is best-effort and can leave a proxy +running or its port in use. + +The supervisor owns its PID entry. It keeps the PID registered across container +restart attempts, including backoff, and shutdown cancels the backoff. When it +exits, it clears the PID only if the entry still holds its own PID. If it was +cancelled, by a signal or by reaching a deadline, it exits with status 0, and +under one status file lock clears its PID and changes `Starting` or `Running` to +`Stopped`. It writes nothing unless the recorded PID is its own, so a +replacement that has written `Starting` but not yet recorded its PID keeps its +status. + +Start and restart stop any other supervisor whose PID is recorded for the +workload before they spawn a new one, whatever the current status is. They +return an error, without spawning, unless that supervisor is confirmed gone. +They never signal their own PID. A foreground `thv run` is the exception: it +deletes its workload when it exits, so start and restart leave it in charge and +return success without doing anything, including while it waits in restart +backoff. These rules apply to container and remote workloads. + +**Implementation**: `pkg/workloads/manager.go`, `pkg/process/toolhive_proxy.go` ### List diff --git a/pkg/container/docker/client.go b/pkg/container/docker/client.go index 05482a6d4a..5e85886e4d 100644 --- a/pkg/container/docker/client.go +++ b/pkg/container/docker/client.go @@ -447,7 +447,7 @@ func (c *Client) StopWorkload(ctx context.Context, workloadName string) error { info, err := c.GetWorkloadInfo(ctx, workloadName) if err != nil { // If the container doesn't exist, that's fine - it's already "stopped" - if errors.Is(err, ErrContainerNotFound) { + if errors.Is(err, ErrContainerNotFound) || errors.Is(err, runtime.ErrWorkloadNotFound) { return nil } return err @@ -489,33 +489,36 @@ func (c *Client) StopWorkload(ctx context.Context, workloadName string) error { return nil } -// RemoveWorkload removes a workload -// If the workload doesn't exist, it returns success +// RemoveWorkload removes a workload and its associated helpers and networks. +// A missing primary does not prevent cleanup of resources derived from the +// supplied name. Other inspection errors are returned without attempting cleanup. func (c *Client) RemoveWorkload(ctx context.Context, workloadName string) error { - // get container name from ID + // Inspect again at removal time; the supervisor may have created or removed + // the primary container since the manager's initial inspection. containerResponse, err := c.inspectContainerByName(ctx, workloadName) if err != nil { - slog.Warn("failed to inspect container", "name", workloadName, "error", err) + if !errors.Is(err, runtime.ErrWorkloadNotFound) && !errors.Is(err, runtime.ErrContainerNotFound) && !errdefs.IsNotFound(err) { + return fmt.Errorf("failed to inspect workload %s for removal: %w", workloadName, err) + } } - // remove the / if it starts with it - containerName := containerResponse.Name - containerName = strings.TrimPrefix(containerName, "/") - - // remove the workload containers - var labels map[string]string - if containerResponse.Config != nil { - labels = containerResponse.Config.Labels - } else { - labels = make(map[string]string) - } - err = c.removeContainer(ctx, containerResponse.ID) - if err != nil { - return err // removeContainer already wraps the error with context. + containerName := workloadName + var workloadLabels map[string]string + if err == nil { + containerName = strings.TrimPrefix(containerResponse.Name, "/") + if containerResponse.Config != nil { + workloadLabels = containerResponse.Config.Labels + } + if err := c.removeContainer(ctx, containerResponse.ID); err != nil { + return err // removeContainer already wraps the error with context. + } } - // Clean up any proxy containers associated with this workload. - err = c.removeProxyContainers(ctx, containerName, labels) + // When the primary is absent, only its exact workload-name-derived helper + // names are available. Nil labels retain legacy network-isolation cleanup. + // Callers must supply the physical container name to clean up timestamped + // resources in that case; an unknown physical name cannot be reconstructed. + err = c.removeProxyContainers(ctx, containerName, workloadLabels) if err != nil { return err // removeProxyContainers already wraps the error with context. } @@ -1369,6 +1372,11 @@ func (c *Client) deleteNetwork(ctx context.Context, name string) error { return nil } + if !lb.IsToolHiveContainer(networkToRemove.Labels) || lb.GetContainerName(networkToRemove.Labels) == "" { + slog.Debug("network lacks ToolHive ownership labels, skipping deletion", "name", name) + return nil + } + if _, err := c.client.NetworkRemove(ctx, networkToRemove.ID, mobyclient.NetworkRemoveOptions{}); err != nil { return fmt.Errorf("failed to remove network %s: %w", name, err) } @@ -1391,7 +1399,7 @@ func (c *Client) removeContainer(ctx context.Context, containerID string) error return nil } -// removeProxyContainers removes the MCP server container and any proxy containers. +// removeProxyContainers removes only exact-name ToolHive auxiliary containers. func (c *Client) removeProxyContainers( ctx context.Context, containerName string, @@ -1414,11 +1422,28 @@ func (c *Client) removeProxyContainers( for _, suffix := range suffixes { containerName := fmt.Sprintf("%s-%s", containerName, suffix) - containerId, err := c.findExistingContainer(ctx, containerName) + result, err := c.api.ContainerList(ctx, mobyclient.ContainerListOptions{ + All: true, + Filters: mobyclient.Filters{}. + Add("name", containerName). + Add("label", fmt.Sprintf("%s=%s", lb.LabelToolHive, lb.LabelToolHiveValue)). + Add("label", fmt.Sprintf("%s=%s", ToolhiveAuxiliaryWorkloadLabel, LabelValueTrue)), + }) if err != nil { slog.Debug("failed to find container", "type", suffix, "name", containerName, "error", err) continue } + var containerId string + for _, candidate := range result.Items { + if candidate.Labels[lb.LabelToolHive] != lb.LabelToolHiveValue || + candidate.Labels[ToolhiveAuxiliaryWorkloadLabel] != LabelValueTrue { + continue + } + if slices.Contains(candidate.Names, containerName) || slices.Contains(candidate.Names, "/"+containerName) { + containerId = candidate.ID + break + } + } if containerId == "" { continue } diff --git a/pkg/container/docker/client_remove_test.go b/pkg/container/docker/client_remove_test.go new file mode 100644 index 0000000000..95fc74b0ed --- /dev/null +++ b/pkg/container/docker/client_remove_test.go @@ -0,0 +1,244 @@ +// SPDX-FileCopyrightText: Copyright 2025 Stacklok, Inc. +// SPDX-License-Identifier: Apache-2.0 + +package docker + +import ( + "context" + "encoding/json" + "errors" + "net/http" + "strings" + "sync" + "testing" + + "github.com/containerd/errdefs" + "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" + "github.com/stretchr/testify/require" + + "github.com/stacklok/toolhive/pkg/labels" +) + +func TestRemoveWorkload_AbsentPrimaryCleansOnlyItsOrphanResources(t *testing.T) { + t.Parallel() + for _, tt := range []struct { + name string + disappearsOnInspect bool + collisionLabels map[string]string + }{ + {name: "empty lookup preserves unlabeled helper-name collision"}, + { + name: "Docker inspect not found preserves nonauxiliary ToolHive collision", + disappearsOnInspect: true, + collisionLabels: map[string]string{"toolhive": "true", "toolhive-basename": "svc-ingress"}, + }, + } { + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + var mu sync.Mutex + remaining := map[string]bool{ + "/containers/helper-egress": true, + "/containers/helper-dns": true, + "/containers/other-dns": true, + "/containers/collision-ingress": true, + "/networks/internal-svc": true, + "/networks/internal-other": true, + "/networks/external": true, + } + client := discoveryHTTPClient(t, func(w http.ResponseWriter, r *http.Request) { + mu.Lock() + defer mu.Unlock() + path := strings.TrimPrefix(r.URL.Path, "/v1.44") + w.Header().Set("Content-Type", "application/json") + switch { + case r.Method == http.MethodDelete: + if !remaining[path] { + t.Errorf("unexpected or unsafe deletion: %s", path) + http.Error(w, `{"message":"not found"}`, http.StatusNotFound) + return + } + delete(remaining, path) + w.WriteHeader(http.StatusNoContent) + case path == "/containers/json": + // An unrelated workload must keep the shared external network alive. + _, _ = w.Write([]byte(`[{"Id":"other","Names":["/other"],"Labels":{"toolhive":"true"}}]`)) + case path == "/networks": + _, _ = w.Write([]byte(`[{"Id":"internal-svc","Name":"toolhive-svc-internal","Labels":{"toolhive":"true","toolhive-name":"toolhive-svc-internal"}},{"Id":"internal-other","Name":"toolhive-other-internal","Labels":{"toolhive":"true","toolhive-name":"toolhive-other-internal"}},{"Id":"external","Name":"toolhive-external","Labels":{"toolhive":"true","toolhive-name":"toolhive-external"}}]`)) + default: + t.Errorf("unexpected Docker request: %s %s", r.Method, path) + http.Error(w, `{"message":"unexpected request"}`, http.StatusInternalServerError) + } + }) + candidates := []container.Summary{ + { + ID: "helper-egress", Names: []string{"/svc-egress"}, + Labels: map[string]string{"toolhive": "true", "toolhive-basename": "svc-egress", ToolhiveAuxiliaryWorkloadLabel: "true"}, + }, + { + ID: "other-dns", Names: []string{"/mysvc-dns"}, + Labels: map[string]string{"toolhive": "true", "toolhive-basename": "mysvc-dns", ToolhiveAuxiliaryWorkloadLabel: "true"}, + }, + { + ID: "helper-dns", Names: []string{"/svc-dns"}, + Labels: map[string]string{"toolhive": "true", "toolhive-basename": "svc-dns", ToolhiveAuxiliaryWorkloadLabel: "true"}, + }, + {ID: "collision-ingress", Names: []string{"/svc-ingress"}, Labels: tt.collisionLabels}, + } + if tt.disappearsOnInspect { + candidates = append(candidates, container.Summary{ + ID: "missing-primary", Names: []string{"/svc"}, + Labels: map[string]string{"toolhive": "true", "toolhive-basename": "svc"}, + }) + } + api := &fakeDockerAPI{ + listFunc: func(_ context.Context, opts mobyclient.ContainerListOptions) ([]container.Summary, error) { + var found []container.Summary + candidateLoop: + for _, candidate := range candidates { + // Honor every requested label so a production ownership filter is exercised. + for _, filter := range filterValues(opts.Filters, "label") { + key, value, hasValue := strings.Cut(filter, "=") + actual, exists := candidate.Labels[key] + if !exists || (hasValue && actual != value) { + continue candidateLoop + } + } + names := filterValues(opts.Filters, "name") + matchesName := len(names) == 0 + for _, name := range names { + for _, actual := range candidate.Names { + matchesName = matchesName || strings.Contains(actual, name) + } + } + if matchesName { + found = append(found, candidate) + } + } + return found, nil + }, + inspectFunc: func(_ context.Context, id string) (container.InspectResponse, error) { + assert.True(t, tt.disappearsOnInspect, "empty lookup must not inspect an empty ID") + assert.Equal(t, "missing-primary", id) + return container.InspectResponse{}, errdefs.ErrNotFound + }, + removeFunc: func(_ context.Context, id string, _ mobyclient.ContainerRemoveOptions) error { + t.Errorf("absent primary must not be removed by empty or stale ID: %q", id) + return nil + }, + } + c := &Client{api: api, client: client} + + require.NoError(t, c.RemoveWorkload(t.Context(), "svc")) + mu.Lock() + defer mu.Unlock() + assert.Equal(t, map[string]bool{ + "/containers/collision-ingress": true, + "/containers/other-dns": true, + "/networks/internal-other": true, + "/networks/external": true, + }, remaining, "cleanup must remove owned helpers and private network without deleting helper-name collisions or unrelated networks") + }) + } +} + +func TestRemoveWorkload_AbsentPrimaryRequiresNetworkOwnership(t *testing.T) { + t.Parallel() + for _, tt := range []struct { + name string + networkLabels map[string]string + wantDeleted bool + }{ + {name: "unlabelled network"}, + {name: "missing name label", networkLabels: map[string]string{labels.LabelToolHive: labels.LabelToolHiveValue}}, + {name: "missing ownership label", networkLabels: map[string]string{labels.LabelName: "network"}}, + {name: "false ownership label", networkLabels: map[string]string{labels.LabelToolHive: "false", labels.LabelName: "network"}}, + {name: "empty name label", networkLabels: map[string]string{labels.LabelToolHive: labels.LabelToolHiveValue, labels.LabelName: ""}}, + {name: "owned network", wantDeleted: true}, + } { + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + var mu sync.Mutex + var deleted []string + client := discoveryHTTPClient(t, func(w http.ResponseWriter, r *http.Request) { + mu.Lock() + defer mu.Unlock() + path := strings.TrimPrefix(r.URL.Path, "/v1.44") + w.Header().Set("Content-Type", "application/json") + switch { + case r.Method == http.MethodDelete: + deleted = append(deleted, path) + w.WriteHeader(http.StatusNoContent) + case path == "/containers/json": + _, _ = w.Write([]byte(`[]`)) + case path == "/networks": + var networks []network.Summary + for _, name := range []string{"toolhive-foo-internal", "toolhive-external"} { + networkLabels := tt.networkLabels + if tt.wantDeleted { + networkLabels = make(map[string]string) + labels.AddNetworkLabels(networkLabels, name) + } + networks = append(networks, network.Summary{Network: network.Network{ + ID: name, Name: name, Labels: networkLabels, + }}) + } + assert.NoError(t, json.NewEncoder(w).Encode(networks)) + default: + t.Errorf("unexpected Docker request: %s %s", r.Method, path) + w.WriteHeader(http.StatusInternalServerError) + } + }) + api := &fakeDockerAPI{ + listFunc: func(context.Context, mobyclient.ContainerListOptions) ([]container.Summary, error) { + return nil, nil + }, + } + c := &Client{api: api, client: client} + + require.NoError(t, c.RemoveWorkload(t.Context(), "foo")) + mu.Lock() + defer mu.Unlock() + if tt.wantDeleted { + assert.Equal(t, []string{"/networks/toolhive-foo-internal", "/networks/toolhive-external"}, deleted) + } else { + assert.Empty(t, deleted, "networks without ToolHive ownership labels must survive removal") + } + }) + } +} + +func TestRemoveWorkload_InspectionFailureDoesNotDeleteResources(t *testing.T) { + t.Parallel() + for _, failureAt := range []string{"lookup", "inspect"} { + t.Run(failureAt, func(t *testing.T) { + t.Parallel() + inspectErr := errors.New("Docker daemon unavailable") + api := &fakeDockerAPI{ + listFunc: func(_ context.Context, _ mobyclient.ContainerListOptions) ([]container.Summary, error) { + if failureAt == "lookup" { + return nil, inspectErr + } + return []container.Summary{{ID: "primary", Names: []string{"/svc"}}}, nil + }, + inspectFunc: func(context.Context, string) (container.InspectResponse, error) { + return container.InspectResponse{}, inspectErr + }, + removeFunc: func(context.Context, string, mobyclient.ContainerRemoveOptions) error { + t.Error("failed inspection must not remove a primary container") + return nil + }, + } + client := discoveryHTTPClient(t, func(w http.ResponseWriter, r *http.Request) { + t.Errorf("failed inspection must not attempt helper or network cleanup: %s %s", r.Method, r.URL.Path) + w.WriteHeader(http.StatusInternalServerError) + _ = json.NewEncoder(w).Encode(map[string]string{"message": "unexpected cleanup"}) + }) + c := &Client{api: api, client: client} + + require.ErrorIs(t, c.RemoveWorkload(t.Context(), "svc"), inspectErr) + }) + } +} diff --git a/pkg/container/docker/client_stop_test.go b/pkg/container/docker/client_stop_test.go index 4bc00df183..f3f2dcccf5 100644 --- a/pkg/container/docker/client_stop_test.go +++ b/pkg/container/docker/client_stop_test.go @@ -139,6 +139,31 @@ func TestStopWorkload_NotFound_ReturnsNil(t *testing.T) { require.NoError(t, err) } +func TestStopWorkload_EmptyContainerListIsAlreadyStopped(t *testing.T) { + t.Parallel() + + stopCalls := 0 + inspectCalls := 0 + api := &fakeDockerAPI{ + listFunc: func(_ context.Context, _ mobyclient.ContainerListOptions) ([]container.Summary, error) { + return nil, nil + }, + inspectFunc: func(_ context.Context, _ string) (container.InspectResponse, error) { + inspectCalls++ + return container.InspectResponse{}, nil + }, + stopFunc: func(_ context.Context, _ string, _ mobyclient.ContainerStopOptions) error { + stopCalls++ + return nil + }, + } + c := &Client{api: api} + + require.NoError(t, c.StopWorkload(t.Context(), "already-removed")) + assert.Zero(t, inspectCalls, "a missing workload has no container to inspect") + assert.Zero(t, stopCalls, "missing workloads must not call the container stop API") +} + // TestStopProxyContainer_HandlesEnvoyAndSquidTopologies exercises the building // block of the shared cleanup path. StopWorkload iterates the fixed proxy // suffixes (-egress, -ingress, -dns) and calls stopProxyContainer for each; this diff --git a/pkg/process/find_windows.go b/pkg/process/find_windows.go index 1a0326066b..c875066d3e 100644 --- a/pkg/process/find_windows.go +++ b/pkg/process/find_windows.go @@ -6,6 +6,7 @@ package process import ( + "errors" "fmt" "syscall" "unsafe" @@ -13,8 +14,9 @@ import ( // Windows API constants const ( - processQueryInformation = 0x0400 - stillActive = 259 + processQueryInformation = 0x0400 + stillActive = 259 + errorInvalidParameter syscall.Errno = 87 ) // Windows API functions @@ -42,8 +44,12 @@ func FindProcess(pid int) (bool, error) { ) if handle == 0 { - // Process doesn't exist or cannot be opened - return false, nil + // With these valid access/inheritance arguments, ERROR_INVALID_PARAMETER + // means the PID does not exist. Access denial leaves its state unknown. + if errors.Is(err, errorInvalidParameter) { + return false, nil + } + return false, fmt.Errorf("failed to open process: %w", err) } // Don't forget to close the handle when we're done diff --git a/pkg/process/kill.go b/pkg/process/kill.go new file mode 100644 index 0000000000..322dc98ea7 --- /dev/null +++ b/pkg/process/kill.go @@ -0,0 +1,25 @@ +// SPDX-FileCopyrightText: Copyright 2025 Stacklok, Inc. +// SPDX-License-Identifier: Apache-2.0 + +package process + +import ( + "fmt" + "os" +) + +// ForceKillProcess kills a process without letting it clean up: SIGKILL on +// Unix and TerminateProcess on Windows. +func ForceKillProcess(pid int) error { + if pid <= 0 { + return fmt.Errorf("invalid PID: %d", pid) + } + process, err := os.FindProcess(pid) + if err != nil { + return fmt.Errorf("failed to find process: %w", err) + } + if err := process.Kill(); err != nil { + return fmt.Errorf("failed to kill process: %w", err) + } + return nil +} diff --git a/pkg/process/mocks/mock_process_metadata.go b/pkg/process/mocks/mock_process_metadata.go new file mode 100644 index 0000000000..e4f8a4e55b --- /dev/null +++ b/pkg/process/mocks/mock_process_metadata.go @@ -0,0 +1,100 @@ +// Code generated by MockGen. DO NOT EDIT. +// Source: toolhive_proxy.go +// +// Generated by this command: +// +// mockgen -destination=mocks/mock_process_metadata.go -package=mocks -source=toolhive_proxy.go -mock_names=processMetadata=MockProcessMetadata +// + +// Package mocks is a generated GoMock package. +package mocks + +import ( + reflect "reflect" + + gomock "go.uber.org/mock/gomock" +) + +// MockProcessMetadata is a mock of processMetadata interface. +type MockProcessMetadata struct { + ctrl *gomock.Controller + recorder *MockProcessMetadataMockRecorder + isgomock struct{} +} + +// MockProcessMetadataMockRecorder is the mock recorder for MockProcessMetadata. +type MockProcessMetadataMockRecorder struct { + mock *MockProcessMetadata +} + +// NewMockProcessMetadata creates a new mock instance. +func NewMockProcessMetadata(ctrl *gomock.Controller) *MockProcessMetadata { + mock := &MockProcessMetadata{ctrl: ctrl} + mock.recorder = &MockProcessMetadataMockRecorder{mock} + return mock +} + +// EXPECT returns an object that allows the caller to indicate expected use. +func (m *MockProcessMetadata) EXPECT() *MockProcessMetadataMockRecorder { + return m.recorder +} + +// Cmdline mocks base method. +func (m *MockProcessMetadata) Cmdline() (string, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "Cmdline") + ret0, _ := ret[0].(string) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// Cmdline indicates an expected call of Cmdline. +func (mr *MockProcessMetadataMockRecorder) Cmdline() *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Cmdline", reflect.TypeOf((*MockProcessMetadata)(nil).Cmdline)) +} + +// CmdlineSlice mocks base method. +func (m *MockProcessMetadata) CmdlineSlice() ([]string, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "CmdlineSlice") + ret0, _ := ret[0].([]string) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// CmdlineSlice indicates an expected call of CmdlineSlice. +func (mr *MockProcessMetadataMockRecorder) CmdlineSlice() *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "CmdlineSlice", reflect.TypeOf((*MockProcessMetadata)(nil).CmdlineSlice)) +} + +// Environ mocks base method. +func (m *MockProcessMetadata) Environ() ([]string, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "Environ") + ret0, _ := ret[0].([]string) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// Environ indicates an expected call of Environ. +func (mr *MockProcessMetadataMockRecorder) Environ() *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Environ", reflect.TypeOf((*MockProcessMetadata)(nil).Environ)) +} + +// Exe mocks base method. +func (m *MockProcessMetadata) Exe() (string, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "Exe") + ret0, _ := ret[0].(string) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// Exe indicates an expected call of Exe. +func (mr *MockProcessMetadataMockRecorder) Exe() *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Exe", reflect.TypeOf((*MockProcessMetadata)(nil).Exe)) +} diff --git a/pkg/process/toolhive_proxy.go b/pkg/process/toolhive_proxy.go index 837772add9..a0b7d3eeda 100644 --- a/pkg/process/toolhive_proxy.go +++ b/pkg/process/toolhive_proxy.go @@ -4,6 +4,7 @@ package process import ( + "slices" "strings" gopsutilprocess "github.com/shirou/gopsutil/v4/process" @@ -15,6 +16,15 @@ const ( toolHiveBinaryName = "thv" ) +//go:generate mockgen -destination=mocks/mock_process_metadata.go -package=mocks -source=toolhive_proxy.go -mock_names=processMetadata=MockProcessMetadata + +type processMetadata interface { + Environ() ([]string, error) + Cmdline() (string, error) + CmdlineSlice() ([]string, error) + Exe() (string, error) +} + // containsThvBinary returns true if s appears to reference the thv binary // (e.g. /usr/bin/thv, thv start, thv.exe), avoiding false positives like "toolhive". func containsThvBinary(s string) bool { @@ -66,9 +76,155 @@ func IsToolHiveProxyForWorkload(pid int, workloadName string) (bool, error) { return true, nil } +// IsTrackedToolHiveProxyForWorkload verifies a PID read from a workload's status. +// Detached supervisors must match the workload name. Non-detached ToolHive +// run/start/restart supervisors use recorded-PID binding without a process-birth-time check. +// Only the subcommand and its ToolHive arguments before "--" are checked. +// An unnamed or --from-config run may omit its derived workload name. Named +// runs must match; start/restart must include the name or select --all or --group. +// Port-discovered PIDs must use IsToolHiveProxyForWorkload instead. +func IsTrackedToolHiveProxyForWorkload(pid int, workloadName string) (bool, error) { + if pid <= 0 || workloadName == "" { + return false, nil + } + p, err := gopsutilprocess.NewProcess(int32(pid)) //nolint:gosec // G115: supported platform PIDs fit int32. + if err != nil { + return false, err + } + return isTrackedToolHiveProxyForWorkload(p, workloadName) +} + +func isTrackedToolHiveProxyForWorkload(p processMetadata, workloadName string) (bool, error) { + env, err := p.Environ() + if err != nil { + return false, err + } + if slices.Contains(env, ToolHiveDetachedEnv+"="+ToolHiveDetachedValue) { + cmdline, err := p.Cmdline() + if err != nil { + return false, err + } + return cmdlineContainsWorkload(cmdline, workloadName), nil + } + args, err := p.CmdlineSlice() + if err != nil { + return false, err + } + if !isToolHiveProcess(p) { + return false, nil + } + switch command, rest := supervisorSubcommand(args); command { + case "run": + return trackedRunMatchesWorkload(rest, workloadName), nil + case "start", "restart": + return trackedStartMatchesWorkload(rest, workloadName), nil + } + return false, nil +} + +// IsForegroundRunSupervisorForWorkload reports whether pid is a non-detached +// `thv run` supervising workloadName. Such a process deletes its workload when +// it exits, so it cannot be replaced by another supervisor. +func IsForegroundRunSupervisorForWorkload(pid int, workloadName string) (bool, error) { + if pid <= 0 || workloadName == "" { + return false, nil + } + p, err := gopsutilprocess.NewProcess(int32(pid)) //nolint:gosec // G115: supported platform PIDs fit int32. + if err != nil { + return false, err + } + return isForegroundRunSupervisorForWorkload(p, workloadName) +} + +func isForegroundRunSupervisorForWorkload(p processMetadata, workloadName string) (bool, error) { + env, err := p.Environ() + if err != nil { + return false, err + } + if slices.Contains(env, ToolHiveDetachedEnv+"="+ToolHiveDetachedValue) { + return false, nil + } + args, err := p.CmdlineSlice() + if err != nil { + return false, err + } + if !isToolHiveProcess(p) { + return false, nil + } + command, rest := supervisorSubcommand(args) + return command == "run" && trackedRunMatchesWorkload(rest, workloadName), nil +} + +// supervisorSubcommand returns the first non-flag argument after argv[0] and +// the arguments that follow it, up to "--". The only root flag, --debug, takes +// no value, so the first non-flag argument is the subcommand. Arguments after +// "--" belong to the MCP server, not ToolHive. +func supervisorSubcommand(argv []string) (string, []string) { + for i := 1; i < len(argv); i++ { + if argv[i] == "--" { + return "", nil + } + if strings.HasPrefix(argv[i], "-") { + continue + } + rest := argv[i+1:] + if end := slices.Index(rest, "--"); end >= 0 { + rest = rest[:end] + } + return argv[i], rest + } + return "", nil +} + +// trackedStartMatchesWorkload accepts start/restart arguments that name the +// workload or select it through --all/-a or --group/-g. +func trackedStartMatchesWorkload(args []string, workloadName string) bool { + return slices.ContainsFunc(args, func(arg string) bool { + switch { + case arg == workloadName, arg == "--all", arg == "--group", strings.HasPrefix(arg, "--group="): + return true + case strings.HasPrefix(arg, "--all="): + return strings.TrimPrefix(arg, "--all=") != "false" + case strings.HasPrefix(arg, "--"): + return false + case strings.HasPrefix(arg, "-"): + // Shorthand cluster such as -a, -af, -g, or -g=name. + shorthands, _, _ := strings.Cut(arg[1:], "=") + return strings.ContainsAny(shorthands, "ag") + } + return false + }) +} + +func trackedRunMatchesWorkload(args []string, workloadName string) bool { + named := false + fromConfig := false + for i := 0; i < len(args); i++ { + switch { + case args[i] == "--name": + named = true + i++ + if i >= len(args) || args[i] != workloadName { + return false + } + case strings.HasPrefix(args[i], "--name="): + named = true + if strings.TrimPrefix(args[i], "--name=") != workloadName { + return false + } + case args[i] == "--from-config", strings.HasPrefix(args[i], "--from-config="): + // The workload name comes from the config file, like an unnamed run. + fromConfig = true + } + } + return named || fromConfig || slices.ContainsFunc(args, func(arg string) bool { + return !strings.HasPrefix(arg, "-") + }) +} + // isToolHiveProcess returns true if p is a ToolHive process (TOOLHIVE_DETACHED // or thv binary in exe/cmdline). -func isToolHiveProcess(p *gopsutilprocess.Process) bool { +func isToolHiveProcess(p processMetadata) bool { if hasToolHiveDetachedEnv(p) { return true } @@ -81,7 +237,7 @@ func isToolHiveProcess(p *gopsutilprocess.Process) bool { return false } -func hasToolHiveDetachedEnv(p *gopsutilprocess.Process) bool { +func hasToolHiveDetachedEnv(p processMetadata) bool { env, err := p.Environ() if err != nil { return false @@ -105,12 +261,12 @@ func cmdlineContainsWorkload(cmdline, workloadName string) bool { if !strings.Contains(cmdline, pattern) { return false } - // Ensure workloadName is not a prefix of a longer word: next char must be space, -, or end + // A hyphen continues the workload name; it is not a token boundary. idx := strings.Index(cmdline, pattern) end := idx + len(pattern) if end >= len(cmdline) { return true } next := cmdline[end] - return next == ' ' || next == '-' + return next == ' ' } diff --git a/pkg/process/toolhive_proxy_test.go b/pkg/process/toolhive_proxy_test.go index 2f126ba6cc..138c043da1 100644 --- a/pkg/process/toolhive_proxy_test.go +++ b/pkg/process/toolhive_proxy_test.go @@ -4,10 +4,22 @@ package process import ( + "bufio" + "errors" + "fmt" + "os" + "os/exec" + "path/filepath" + "runtime" + "strings" "testing" + "time" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" + "go.uber.org/mock/gomock" + + "github.com/stacklok/toolhive/pkg/process/mocks" ) func TestIsToolHiveProxyForWorkload_InvalidPID(t *testing.T) { @@ -35,6 +47,282 @@ func TestIsToolHiveProxyForWorkload_NonToolHiveProcess(t *testing.T) { assert.False(t, isToolHive) } +func TestIsTrackedToolHiveProxyForWorkload_DetachedRequiresExactWorkload(t *testing.T) { + t.Parallel() + pid := startIdentityProcess(t, true, "start", "github-extra", "--foreground") + + matched, err := IsTrackedToolHiveProxyForWorkload(pid, "github-extra") + require.NoError(t, err) + assert.True(t, matched, "detached supervisor must match its complete workload name") + matched, err = IsTrackedToolHiveProxyForWorkload(pid, "github") + require.NoError(t, err) + assert.False(t, matched, "a hyphen continues the workload name, not a token boundary") +} + +func TestIsTrackedToolHiveProxyForWorkload_RejectsMissingIdentity(t *testing.T) { + t.Parallel() + for _, tt := range []struct { + name string + pid int + workload string + }{ + {name: "zero PID", pid: 0, workload: "github"}, + {name: "negative PID", pid: -1, workload: "github"}, + {name: "empty workload", pid: os.Getpid()}, + } { + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + matched, err := IsTrackedToolHiveProxyForWorkload(tt.pid, tt.workload) + require.NoError(t, err) + assert.False(t, matched, "both a valid PID and a workload name are required") + }) + } +} + +//nolint:tparallel // owned-child cleanup must finish before the parent looks up its reaped PID +func TestIsTrackedToolHiveProxyForWorkload_ReapedProcess(t *testing.T) { + t.Parallel() + if runtime.GOOS == "windows" { + t.Skip("process identity fixture requires Unix symlinks and process inspection") + } + var pid int + t.Run("owned child", func(t *testing.T) { + pid = startIdentityProcess(t, true, "start", "github", "--foreground") + }) + require.Positive(t, pid) + // The subtest's cleanup kills and reaps the child before looking up its PID. + matched, err := IsTrackedToolHiveProxyForWorkload(pid, "github") + require.Error(t, err) + assert.False(t, matched, "a stale PID must not identify a workload supervisor") +} + +func TestIsTrackedToolHiveProxyForWorkload_MetadataErrors(t *testing.T) { + t.Parallel() + for _, tt := range []struct { + name string + env []string + environErr bool + }{ + { + name: "environment unavailable", + env: []string{ToolHiveDetachedEnv + "=" + ToolHiveDetachedValue}, + environErr: true, + }, + { + name: "detached command line unavailable", + env: []string{ToolHiveDetachedEnv + "=" + ToolHiveDetachedValue}, + }, + {name: "foreground command line unavailable"}, + } { + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + metadata := mocks.NewMockProcessMetadata(gomock.NewController(t)) + metadataErr := errors.New("process metadata unavailable") + if tt.environErr { + metadata.EXPECT().Environ().Return(tt.env, metadataErr) + } else { + metadata.EXPECT().Environ().Return(tt.env, nil) + if len(tt.env) > 0 { + metadata.EXPECT().Cmdline().Return("/usr/bin/thv start github --foreground", metadataErr) + } else { + metadata.EXPECT().CmdlineSlice().Return(nil, metadataErr) + } + } + + matched, err := isTrackedToolHiveProxyForWorkload(metadata, "github") + require.ErrorIs(t, err, metadataErr) + assert.False(t, matched, "unreadable identity must not authorize stopping a process") + }) + } +} + +func TestIsTrackedToolHiveProxyForWorkload_ForegroundArguments(t *testing.T) { + t.Parallel() + for _, tt := range []struct { + name string + args []string + expected bool + }{ + {name: "start another workload", args: []string{"thv", "start", "other", "--foreground"}}, + {name: "root flag before run", args: []string{"thv", "--debug", "run", "img", "--name", "demo"}, expected: true}, + {name: "equals name", args: []string{"thv", "run", "img", "--name=demo"}, expected: true}, + {name: "different name", args: []string{"thv", "run", "img", "--name", "other"}}, + {name: "different equals name", args: []string{"thv", "run", "demo", "--name=other"}}, + {name: "missing name value", args: []string{"thv", "run", "img", "--name"}}, + {name: "empty name value", args: []string{"thv", "run", "img", "--name="}}, + {name: "unnamed run", args: []string{"thv", "run", "img"}, expected: true}, + {name: "positional workload", args: []string{"thv", "run", "demo"}, expected: true}, + {name: "run without image", args: []string{"thv", "run"}}, + {name: "start all", args: []string{"thv", "start", "--all", "--foreground"}, expected: true}, + {name: "start group", args: []string{"thv", "start", "--group", "servers"}, expected: true}, + {name: "restart equals group", args: []string{"thv", "restart", "--group=servers"}, expected: true}, + {name: "restart workload", args: []string{"thv", "restart", "demo", "--foreground"}, expected: true}, + {name: "reject partial workload", args: []string{"thv", "start", "demo-extra", "--foreground"}}, + {name: "reject subcommand substring", args: []string{"thv", "serve", "--description= run img"}}, + {name: "skip executable", args: []string{"run", "demo"}}, + {name: "first subcommand wins", args: []string{"thv", "start", "other", "run", "img"}}, + {name: "serve flag value is not a subcommand", args: []string{"thv", "serve", "--sentry-environment", "run", "--port", "8080"}}, + {name: "server name does not override workload", args: []string{"thv", "run", "--foreground", "--name", "demo", "img", "--", "--name", "backend"}, expected: true}, + {name: "server name does not select workload", args: []string{"thv", "run", "--foreground", "--name", "backend", "img", "--", "--name", "demo"}}, + {name: "unnamed run with server name", args: []string{"thv", "run", "img", "--", "--name", "other"}, expected: true}, + {name: "start shorthand all", args: []string{"thv", "start", "-a", "-f"}, expected: true}, + {name: "restart shorthand cluster", args: []string{"thv", "restart", "-af"}, expected: true}, + {name: "start shorthand group", args: []string{"thv", "start", "-g", "servers", "-f"}, expected: true}, + {name: "restart shorthand equals group", args: []string{"thv", "restart", "-g=servers"}, expected: true}, + {name: "start explicit all true", args: []string{"thv", "start", "--all=true"}, expected: true}, + {name: "start explicit all false", args: []string{"thv", "start", "--all=false", "other"}}, + {name: "run config equals", args: []string{"thv", "run", "--foreground", "--from-config=demo.json"}, expected: true}, + {name: "run config argument", args: []string{"thv", "run", "--foreground", "--from-config", "demo.json"}, expected: true}, + {name: "separator before command", args: []string{"thv", "--", "run", "img"}}, + {name: "empty argv"}, + } { + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + metadata := mocks.NewMockProcessMetadata(gomock.NewController(t)) + metadata.EXPECT().Environ().Return(nil, nil).Times(2) + metadata.EXPECT().CmdlineSlice().Return(tt.args, nil) + metadata.EXPECT().Exe().Return("/usr/bin/thv", nil) + + matched, err := isTrackedToolHiveProxyForWorkload(metadata, "demo") + require.NoError(t, err) + assert.Equal(t, tt.expected, matched) + }) + } +} + +func TestIsForegroundRunSupervisorForWorkload(t *testing.T) { + t.Parallel() + for _, tt := range []struct { + name string + detached bool + args []string + expected bool + }{ + {name: "detached run", detached: true, args: []string{"thv", "run", "--name", "demo", "img"}}, + {name: "foreground run", args: []string{"thv", "run", "--name", "demo", "img"}, expected: true}, + {name: "foreground start", args: []string{"thv", "start", "demo", "--foreground"}}, + {name: "different workload", args: []string{"thv", "run", "--name", "other", "img"}}, + } { + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + metadata := mocks.NewMockProcessMetadata(gomock.NewController(t)) + if tt.detached { + metadata.EXPECT().Environ().Return([]string{ToolHiveDetachedEnv + "=" + ToolHiveDetachedValue}, nil) + } else { + metadata.EXPECT().Environ().Return(nil, nil).Times(2) + metadata.EXPECT().CmdlineSlice().Return(tt.args, nil) + metadata.EXPECT().Exe().Return("/usr/bin/thv", nil) + } + matched, err := isForegroundRunSupervisorForWorkload(metadata, "demo") + require.NoError(t, err) + assert.Equal(t, tt.expected, matched) + }) + } +} + +func TestIsTrackedToolHiveProxyForWorkload_ForegroundDoesNotRelaxPortIdentity(t *testing.T) { + t.Parallel() + + for _, tt := range []struct { + name string + args []string + }{ + {name: "unnamed run", args: []string{"run", "--foreground", "example/server"}}, + {name: "named run", args: []string{"run", "--foreground", "--name", "derived-workload-name", "example/server"}}, + {name: "start", args: []string{"start", "derived-workload-name", "--foreground"}}, + {name: "restart", args: []string{"restart", "derived-workload-name", "--foreground"}}, + } { + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + pid := startIdentityProcess(t, false, tt.args...) + matched, err := IsTrackedToolHiveProxyForWorkload(pid, "derived-workload-name") + require.NoError(t, err) + assert.True(t, matched, "tracked foreground supervisors must remain stoppable") + if tt.args[0] != "start" { + matched, err = IsToolHiveProxyForWorkload(pid, "derived-workload-name") + require.NoError(t, err) + assert.False(t, matched, "port-discovered foreground supervisor still requires start-workload identity") + } + }) + } +} + +func TestIsTrackedToolHiveProxyForWorkload_RejectsForegroundServe(t *testing.T) { + t.Parallel() + pid := startIdentityProcess(t, false, "serve") + + toolHive, err := IsToolHiveProxyForWorkload(pid, "") + require.NoError(t, err) + require.True(t, toolHive, "fixture must have ToolHive binary identity without a detached marker") + matched, err := IsTrackedToolHiveProxyForWorkload(pid, "stale-workload") + require.NoError(t, err) + assert.False(t, matched, "a stale supervisor PID must not identify ToolHive serve as a workload supervisor") +} + +func TestToolHiveIdentityProcess(t *testing.T) { + t.Parallel() + if os.Getenv("TOOLHIVE_TEST_IDENTITY_HELPER") != "1" { + return + } + fmt.Println("ready") + <-time.After(time.Minute) + os.Exit(1) +} + +func startIdentityProcess(t *testing.T, detached bool, args ...string) int { + t.Helper() + if runtime.GOOS == "windows" { + t.Skip("process identity fixture requires Unix symlinks and process inspection") + } + executable, err := os.Executable() + require.NoError(t, err) + if !detached { + thv := filepath.Join(t.TempDir(), "thv") + require.NoError(t, os.Symlink(executable, thv)) + executable = thv + } + // Test flag parsing stops at the first non-flag argument, so the ToolHive + // subcommand can follow directly without a "--" that would hide it. + cmd := exec.Command(executable, append([]string{"-test.run=^TestToolHiveIdentityProcess$"}, args...)...) + for _, entry := range os.Environ() { + if !strings.HasPrefix(entry, ToolHiveDetachedEnv+"=") { + cmd.Env = append(cmd.Env, entry) + } + } + cmd.Env = append(cmd.Env, "TOOLHIVE_TEST_IDENTITY_HELPER=1") + if detached { + cmd.Env = append(cmd.Env, ToolHiveDetachedEnv+"="+ToolHiveDetachedValue) + } + stdout, err := cmd.StdoutPipe() + require.NoError(t, err) + require.NoError(t, cmd.Start()) + exited := make(chan struct{}) + go func() { + _ = cmd.Wait() + close(exited) + }() + t.Cleanup(func() { + _ = cmd.Process.Kill() + select { + case <-exited: + case <-time.After(5 * time.Second): + t.Error("identity helper was not reaped") + } + }) + ready := make(chan string, 1) + go func() { + line, _ := bufio.NewReader(stdout).ReadString('\n') + ready <- line + }() + select { + case line := <-ready: + require.Equal(t, "ready\n", line) + case <-time.After(5 * time.Second): + t.Fatal("identity helper did not start") + } + return cmd.Process.Pid +} + func TestContainsThvBinary(t *testing.T) { t.Parallel() tests := []struct { @@ -74,6 +362,7 @@ func TestCmdlineContainsWorkload(t *testing.T) { {"matches at end", "thv start myworkload", "myworkload", true}, {"rejects different workload", "/usr/bin/thv start slack --foreground", "github", false}, {"rejects partial match", "thv start github --foreground", "git", false}, + {"rejects hyphenated name prefix", "thv start github-extra --foreground", "github", false}, {"rejects suffix match", "thv start github --foreground", "hub", false}, {"empty workload", "thv start github --foreground", "", false}, } diff --git a/pkg/runner/runner.go b/pkg/runner/runner.go index 37d7cdbaf0..d1b0355c19 100644 --- a/pkg/runner/runner.go +++ b/pkg/runner/runner.go @@ -717,13 +717,6 @@ func (r *Runner) Run(ctx context.Context) error { slog.Warn("failed to cleanup telemetry", "error", err) } - // Remove the PID file if it exists. Use PID-guarded reset so that a - // dying process does not clobber the PID of a replacement process that - // started in the meantime (e.g. during thv rm + thv run). - if err := r.statusManager.ResetWorkloadPIDIfMatch(cleanupCtx, r.Config.BaseName, os.Getpid()); err != nil { - slog.Warn("failed to reset workload PID", "container", r.Config.ContainerName, "error", err) - } - slog.Debug("mcp server stopped", "container", r.Config.ContainerName) } @@ -798,12 +791,6 @@ func (r *Runner) Run(ctx context.Context) error { stopMCPServer("Context cancelled") case <-doneCh: // The transport has already been stopped (likely by the container exit) - // Remove the old PID from the state file. Use PID-guarded reset to - // avoid clobbering a replacement process's PID. - if err := r.statusManager.ResetWorkloadPIDIfMatch(ctx, r.Config.BaseName, os.Getpid()); err != nil { - slog.Warn("failed to reset workload PID", "workload", r.Config.BaseName, "error", err) - } - // Check if workload still exists (using status manager and runtime) // If it doesn't exist, it was removed - clean up client config // If it exists, it exited unexpectedly - signal restart needed @@ -833,7 +820,8 @@ func (r *Runner) Run(ctx context.Context) error { return nil // Exit gracefully, no restart } - // Workload still exists - signal restart needed + // Keep the PID: the same supervisor handles the restart and must remain + // stoppable even while its transport is down during retry backoff. slog.Debug("MCP server stopped, restart needed", "container", r.Config.ContainerName) return ErrContainerExitedRestartNeeded } diff --git a/pkg/workloads/main_test.go b/pkg/workloads/main_test.go new file mode 100644 index 0000000000..d470fec7cf --- /dev/null +++ b/pkg/workloads/main_test.go @@ -0,0 +1,34 @@ +// SPDX-FileCopyrightText: Copyright 2026 Stacklok, Inc. +// SPDX-License-Identifier: Apache-2.0 + +package workloads + +import ( + "fmt" + "os" + "testing" + + "github.com/stacklok/toolhive/pkg/process" +) + +const detachedReaperTestEnv = "TOOLHIVE_TEST_WORKLOADS_DETACHED_REAPER_79CBF5" + +func TestMain(m *testing.M) { + mode, fixture := os.LookupEnv(detachedReaperTestEnv) + if fixture { + if (mode == "clean" || mode == "error") && os.Getenv(process.ToolHiveDetachedEnv) == process.ToolHiveDetachedValue && + len(os.Args) == 4 && os.Args[1] == "start" && + os.Args[2] == "detached-reaper-79cbf5-"+mode && os.Args[3] == "--foreground" { + exitCode := 0 + if mode == "error" { + exitCode = 42 + } + fmt.Printf("detached reaper fixture exit %d\n", exitCode) + os.Exit(exitCode) + } + fmt.Fprintf(os.Stderr, "unexpected detached reaper invocation: mode=%q detached=%q args=%q\n", + mode, os.Getenv(process.ToolHiveDetachedEnv), os.Args) + os.Exit(2) + } + os.Exit(m.Run()) +} diff --git a/pkg/workloads/manager.go b/pkg/workloads/manager.go index 644abef2fb..9ab39141ab 100644 --- a/pkg/workloads/manager.go +++ b/pkg/workloads/manager.go @@ -6,10 +6,12 @@ package workloads import ( + "cmp" "context" "errors" "fmt" "log/slog" + "maps" "os" "os/exec" "path/filepath" @@ -98,10 +100,41 @@ type DefaultManager struct { statuses statuses.StatusManager configProvider config.Provider - retryConfig *retryConfig - newRunner mcpRunnerFactory - detachedSpawner detachedProcessSpawner - portFreer portFreer + retryConfig *retryConfig + newRunner mcpRunnerFactory + detachedSpawner detachedProcessSpawner + portFreer portFreer + proxyExitTimeout time.Duration + clientManagers clientManagerProvider + savedRunConfigs savedRunConfigChecker +} + +// clientManagerProvider creates the client manager used to update MCP client +// configurations when a workload stops, restarts, or is deleted. +type clientManagerProvider interface { + NewClientManager(ctx context.Context) (client.Manager, error) +} + +type defaultClientManagerProvider struct{} + +func (defaultClientManagerProvider) NewClientManager(ctx context.Context) (client.Manager, error) { + return client.NewManager(ctx) +} + +// savedRunConfigChecker reports whether a workload still has a saved run +// configuration. +type savedRunConfigChecker interface { + Exists(ctx context.Context, name string) (bool, error) +} + +type defaultSavedRunConfigChecker struct{} + +func (defaultSavedRunConfigChecker) Exists(ctx context.Context, name string) (bool, error) { + store, err := state.NewRunConfigStore(state.DefaultAppName) + if err != nil { + return false, fmt.Errorf("failed to open run configuration store: %w", err) + } + return store.Exists(ctx, name) } // mcpRunner is the subset of *runner.Runner that RunWorkload's retry loop @@ -172,6 +205,18 @@ func withPortFreer(f portFreer) managerOption { return func(d *DefaultManager) { d.portFreer = f } } +// withProxyExitTimeout bounds proxy-exit waits during stop and restart port cleanup. +func withProxyExitTimeout(timeout time.Duration) managerOption { + return func(d *DefaultManager) { d.proxyExitTimeout = timeout } +} + +func (d *DefaultManager) proxyExitTimeoutOrDefault() time.Duration { + if d.proxyExitTimeout > 0 { + return d.proxyExitTimeout + } + return defaultProxyExitTimeout +} + // retryConfigOrDefault returns the manager's retryConfig if set, otherwise defaults. func (d *DefaultManager) retryConfigOrDefault() retryConfig { if d.retryConfig == nil { @@ -212,6 +257,9 @@ func (d *DefaultManager) portFreerOrDefault() portFreer { var ErrWorkloadNotRunning = fmt.Errorf("workload not running") const ( + defaultProxyExitTimeout = 5 * time.Second + workloadPIDCleanupTimeout = 5 * time.Second + // AsyncOperationTimeout is the timeout for async workload operations AsyncOperationTimeout = 5 * time.Minute ) @@ -229,9 +277,11 @@ func NewManager(ctx context.Context) (*DefaultManager, error) { } return &DefaultManager{ - runtime: runtime, - statuses: statusManager, - configProvider: config.NewDefaultProvider(), + runtime: runtime, + statuses: statusManager, + configProvider: config.NewDefaultProvider(), + clientManagers: defaultClientManagerProvider{}, + savedRunConfigs: defaultSavedRunConfigChecker{}, }, nil } @@ -248,9 +298,11 @@ func NewManagerWithProvider(ctx context.Context, configProvider config.Provider) } return &DefaultManager{ - runtime: runtime, - statuses: statusManager, - configProvider: configProvider, + runtime: runtime, + statuses: statusManager, + configProvider: configProvider, + clientManagers: defaultClientManagerProvider{}, + savedRunConfigs: defaultSavedRunConfigChecker{}, }, nil } @@ -262,9 +314,11 @@ func NewManagerFromRuntime(runtime rt.Runtime) (Manager, error) { } return &DefaultManager{ - runtime: runtime, - statuses: statusManager, - configProvider: config.NewDefaultProvider(), + runtime: runtime, + statuses: statusManager, + configProvider: config.NewDefaultProvider(), + clientManagers: defaultClientManagerProvider{}, + savedRunConfigs: defaultSavedRunConfigChecker{}, }, nil } @@ -277,9 +331,11 @@ func NewManagerFromRuntimeWithProvider(runtime rt.Runtime, configProvider config } return &DefaultManager{ - runtime: runtime, - statuses: statusManager, - configProvider: configProvider, + runtime: runtime, + statuses: statusManager, + configProvider: configProvider, + clientManagers: defaultClientManagerProvider{}, + savedRunConfigs: defaultSavedRunConfigChecker{}, }, nil } @@ -458,22 +514,24 @@ func (d *DefaultManager) stopRemoteWorkload(ctx context.Context, name string, ru // A remote workload's proxy can outlive its recorded status (e.g. the status // file went missing), so we always try to free an orphaned proxy below — only // the status transitions and client-config cleanup are gated on the workload - // actually running. + // running, starting, retrying authentication, unauthenticated, or unhealthy. workload, err := d.statuses.GetWorkload(ctx, name) if err != nil && !errors.Is(err, rt.ErrWorkloadNotFound) { return fmt.Errorf("failed to find workload %s: %w", name, err) } - running := err == nil && workload.Status == rt.WorkloadStatusRunning + stoppable := err == nil && (workload.Status == rt.WorkloadStatusRunning || workload.Status == rt.WorkloadStatusStarting || + workload.Status == rt.WorkloadStatusAuthRetrying || workload.Status == rt.WorkloadStatusUnauthenticated || + workload.Status == rt.WorkloadStatusUnhealthy) switch { case err != nil: // Status is gone (e.g. a missing status file); don't fail the operation, // but still free an orphaned proxy below. slog.Warn("failed to stop workload", "workload", name, "error", err) - case !running: + case !stoppable: slog.Warn("Failed to stop workload", "workload", name, "error", ErrWorkloadNotRunning) } - if running { + if stoppable { if err := d.statuses.SetWorkloadStatus(ctx, name, rt.WorkloadStatusStopping, ""); err != nil { slog.Debug("failed to set workload status to stopping", "workload", name, "error", err) } @@ -481,58 +539,133 @@ func (d *DefaultManager) stopRemoteWorkload(ctx context.Context, name string, ru // Stop the proxy and free its port even when the status is missing or not // running — an orphaned proxy can still be holding the port. - if runConfig.BaseName != "" { - d.ensureProxyStopped(ctx, name, runConfig.BaseName, runConfig) + if err := d.stopRemoteProxy(ctx, name, runConfig, stoppable); err != nil { + return err } - if running { - // For remote workloads we only need to clean up client configurations; the - // saved state is preserved for restart capability. - if err := removeClientConfigurations(name, false); err != nil { - slog.Warn("failed to remove client configurations", "error", err) - } else { - slog.Debug("client configurations removed", "workload", name) - } - if err := d.statuses.SetWorkloadStatus(ctx, name, rt.WorkloadStatusStopped, ""); err != nil { - slog.Debug("failed to set workload status to stopped", "workload", name, "error", err) - } - slog.Debug("remote workload stopped", "workload", name) + if stoppable { + return d.finishRemoteWorkloadStop(ctx, name, runConfig) + } + return nil +} + +func (d *DefaultManager) stopRemoteProxy(ctx context.Context, name string, runConfig *runner.RunConfig, stoppable bool) error { + if runConfig.BaseName == "" { + return nil + } + result := d.ensureProxyStopped(ctx, name, runConfig.BaseName, runConfig, false) + err := supervisorStopError(name, result, false) + if err != nil && stoppable { + d.recordSupervisorStopError(ctx, name, err) + } + return err +} + +func (d *DefaultManager) finishRemoteWorkloadStop(ctx context.Context, name string, runConfig *runner.RunConfig) error { + exists, err := d.savedWorkloadStillExists(ctx, name, runConfig, false) + if err != nil { + return err + } + if !exists { + return nil } + if err := d.removeClientConfigurations(name, false); err != nil { + slog.Warn("failed to remove client configurations", "error", err) + } else { + slog.Debug("client configurations removed", "workload", name) + } + if err := d.statuses.SetWorkloadStatus(ctx, name, rt.WorkloadStatusStopped, ""); err != nil { + slog.Debug("failed to set workload status to stopped", "workload", name, "error", err) + } + slog.Debug("remote workload stopped", "workload", name) return nil } +// Foreground shutdown can delete saved state before the proxy process exits. +// Recheck after cleanup so stop does not recreate its status or repeat client +// cleanup for a deleted workload. Auxiliary/no-config paths retain +// their existing behavior because they need not have their own saved state. +func (d *DefaultManager) savedWorkloadStillExists( + ctx context.Context, name string, runConfig *runner.RunConfig, isAuxiliary bool, +) (bool, error) { + if runConfig == nil || isAuxiliary { + return true, nil + } + exists, err := d.savedRunConfigs.Exists(ctx, cmp.Or(runConfig.BaseName, name)) + if err != nil { + return false, fmt.Errorf("failed to check saved workload after stop: %w", err) + } + return exists, nil +} + // stopContainerWorkload stops a container-based workload. runConfig may be nil -// when the run config could not be loaded; it is used only for port-based proxy -// cleanup when the tracked PID is unavailable. +// when the run config could not be loaded; otherwise it provides saved labels +// if the container is missing and enables port-based proxy cleanup. func (d *DefaultManager) stopContainerWorkload(ctx context.Context, name string, runConfig *runner.RunConfig) error { container, err := d.runtime.GetWorkloadInfo(ctx, name) + found := err == nil if err != nil { - if errors.Is(err, rt.ErrWorkloadNotFound) { - // Log but don't fail the entire operation for not found containers - slog.Warn("failed to stop workload", "workload", name, "error", err) + if !errors.Is(err, rt.ErrWorkloadNotFound) && !errors.Is(err, rt.ErrContainerNotFound) { + return fmt.Errorf("failed to find workload %s: %w", name, err) + } + slog.Debug("container not found, proceeding with proxy cleanup", "workload", name) + if runConfig == nil { + // Without saved state, attempt cleanup by the requested name without + // creating a status entry or changing client configurations. + result := d.ensureProxyStopped(ctx, name, name, nil, false) + if err := supervisorStopError(name, result, false); err != nil { + return err + } + if err := d.runtime.StopWorkload(ctx, name); err != nil { + return fmt.Errorf("failed to stop container: %w", err) + } return nil } - return fmt.Errorf("failed to find workload %s: %w", name, err) - } - running := container.IsRunning() - if !running { - // Log but don't fail the entire operation for not running containers - slog.Warn("Failed to stop workload", "workload", name, "error", ErrWorkloadNotRunning) - return nil + container = rt.ContainerInfo{Name: cmp.Or(runConfig.ContainerName, name), Labels: maps.Clone(runConfig.ContainerLabels)} + if container.Labels == nil { + container.Labels = make(map[string]string) + } + if labels.GetContainerBaseName(container.Labels) == "" { + container.Labels[labels.LabelBaseName] = cmp.Or(runConfig.BaseName, name) + } } - // Transition workload to `stopping` state. - if err := d.statuses.SetWorkloadStatus(ctx, name, rt.WorkloadStatusStopping, ""); err != nil { - slog.Debug("failed to set workload status to stopping", "workload", name, "error", err) + // Only a running container or a live recorded supervisor gives stop + // something to report. Otherwise the existing status (for example error or + // policy_stopped) and client configuration stay as they are. Read the PID + // before cleanup, because a successful proxy stop clears it. + live := found && container.IsRunning() + if !live { + live, err = d.hasLiveSupervisorPID(ctx, labels.GetContainerBaseName(container.Labels)) + if err != nil { + return err + } + } + if live { + if err := d.statuses.SetWorkloadStatus(ctx, name, rt.WorkloadStatusStopping, ""); err != nil { + slog.Debug("failed to set workload status to stopping", "workload", name, "error", err) + } + } else { + slog.Warn("Failed to stop workload", "workload", name, "error", ErrWorkloadNotRunning) } - // Use the existing stopWorkloads method for container workloads - return d.stopSingleContainerWorkload(ctx, &container, runConfig) + // Clean up the proxy before stopping by name, even if the initial container + // was exited or missing: its supervisor may have recreated it since inspection. + return d.stopSingleContainerWorkload(ctx, &container, runConfig, live) } // RunWorkload runs a workload in the foreground with automatic restart on container exit. -func (d *DefaultManager) RunWorkload(ctx context.Context, runConfig *runner.RunConfig) error { +func (d *DefaultManager) RunWorkload(ctx context.Context, runConfig *runner.RunConfig) (runErr error) { + // The supervisor owns its PID across runner attempts, including backoff. + // Final cleanup must survive cancellation without clearing a replacement PID. + defer func() { + runErr = d.finishWorkloadRun(ctx, runConfig.BaseName, runErr) + }() + + if ctx.Err() != nil { + return nil + } // Ensure that the workload has a status entry before starting the process. if err := d.statuses.SetWorkloadStatus(ctx, runConfig.BaseName, rt.WorkloadStatusStarting, ""); err != nil { // Failure to create the initial state is a fatal error. @@ -549,19 +682,28 @@ func (d *DefaultManager) RunWorkload(ctx context.Context, runConfig *runner.RunC for attempt <= maxRetries { if attempt > 1 { slog.Info("restart attempt", "attempt", attempt, "maxRetries", maxRetries, "workload", runConfig.BaseName, "delay", retryDelay) - time.Sleep(retryDelay) + timer := time.NewTimer(retryDelay) + select { + case <-ctx.Done(): + timer.Stop() + return nil + case <-timer.C: + } // Exponential backoff: 5s, 10s, 20s, 40s, 60s (capped) - retryDelay *= 2 - if retryDelay > cfg.maxBackoff { - retryDelay = cfg.maxBackoff - } + retryDelay = min(retryDelay*2, cfg.maxBackoff) } + if ctx.Err() != nil { + return nil + } mcpRunner := newRunner(runConfig, d.statuses) runStartTime := time.Now() err := mcpRunner.Run(ctx) runDuration := time.Since(runStartTime) + if ctx.Err() != nil { + return nil + } if err != nil { // Check if this is a "container exited, restart needed" error @@ -570,33 +712,14 @@ func (d *DefaultManager) RunWorkload(ctx context.Context, runConfig *runner.RunC "workload", runConfig.BaseName, "attempt", attempt, "maxRetries", maxRetries, "runDuration", runDuration) - // Remove from client config so clients notice the restart - clientManager, clientErr := client.NewManager(ctx) - if clientErr == nil { - slog.Debug("removing from client configurations before restart", "workload", runConfig.BaseName) - if removeErr := clientManager.RemoveServerFromClients(ctx, runConfig.BaseName, runConfig.Group); removeErr != nil { - slog.Warn("failed to remove from client config", "error", removeErr) - } - } - // A "stable" run reached at least stableRunThreshold of runtime before // failing — long enough that we treat the next attempt as a fresh // failure rather than another tick of the current retry sequence. stable := runDuration >= cfg.stableRunThreshold - // Set status to starting (since we're restarting) - statusReason := "Container exited, restarting" - if stable { - statusReason = "Container exited after stable run, restarting" - } - statusErr := d.statuses.SetWorkloadStatus( - ctx, - runConfig.BaseName, - rt.WorkloadStatusStarting, - statusReason, - ) - if statusErr != nil { - slog.Warn("failed to set workload status to starting", "workload", runConfig.BaseName, "error", statusErr) + d.prepareWorkloadRestart(ctx, runConfig, stable) + if ctx.Err() != nil { + return nil } // Without this reset of the attempt count, sustained external @@ -620,23 +743,13 @@ func (d *DefaultManager) RunWorkload(ctx context.Context, runConfig *runner.RunC // Exhausted all retries slog.Error("failed to restart after max attempts, giving up", "workload", runConfig.BaseName, "maxRetries", maxRetries) - statusErr = d.statuses.SetWorkloadStatus( - ctx, - runConfig.BaseName, - rt.WorkloadStatusError, - "Failed to restart after container exit", - ) - if statusErr != nil { - slog.Warn("failed to set workload status to error", "workload", runConfig.BaseName, "error", statusErr) - } + d.recordWorkloadRunFailure(ctx, runConfig.BaseName, "Failed to restart after container exit") return fmt.Errorf("container restart failed after %d attempts", maxRetries) } // Some other error - don't retry slog.Error("workload failed with error", "workload", runConfig.BaseName, "error", err) - if statusErr := d.statuses.SetWorkloadStatus(ctx, runConfig.BaseName, rt.WorkloadStatusError, err.Error()); statusErr != nil { - slog.Warn("Failed to set workload status to error", "workload", runConfig.BaseName, "error", statusErr) - } + d.recordWorkloadRunFailure(ctx, runConfig.BaseName, err.Error()) return err } @@ -648,6 +761,57 @@ func (d *DefaultManager) RunWorkload(ctx context.Context, runConfig *runner.RunC return fmt.Errorf("unexpected end of retry loop for %s", runConfig.BaseName) } +func (d *DefaultManager) finishWorkloadRun(ctx context.Context, name string, runErr error) error { + cleanupCtx, cancel := context.WithTimeout(context.Background(), workloadPIDCleanupTimeout) + defer cancel() + if ctx.Err() == nil { + if err := d.statuses.ResetWorkloadPIDIfMatch(cleanupCtx, name, os.Getpid()); err != nil { + slog.Warn("failed to reset workload PID", "workload", name, "error", err) + } + return runErr + } + // A cancellation that does not come from stop or delete (for example + // SIGTERM or Ctrl-C) would otherwise leave the status at starting or + // running. The PID reset and status write happen together so a + // replacement that has written starting but no PID yet is left alone. + if err := d.statuses.SetWorkloadStoppedIfOwned(cleanupCtx, name, os.Getpid()); err != nil { + slog.Warn("failed to set workload status to stopped", "workload", name, "error", err) + } + return nil +} + +func (d *DefaultManager) recordWorkloadRunFailure(ctx context.Context, name, reason string) { + if ctx.Err() != nil { + return + } + if err := d.statuses.SetWorkloadStatus(ctx, name, rt.WorkloadStatusError, reason); err != nil { + slog.Warn("failed to set workload status to error", "workload", name, "error", err) + } +} + +// prepareWorkloadRestart removes stale client configuration and records that +// the workload is restarting, unless shutdown interrupted client cleanup. +func (d *DefaultManager) prepareWorkloadRestart(ctx context.Context, runConfig *runner.RunConfig, stable bool) { + clientManager, err := d.clientManagers.NewClientManager(ctx) + if err == nil { + slog.Debug("removing from client configurations before restart", "workload", runConfig.BaseName) + if err := clientManager.RemoveServerFromClients(ctx, runConfig.BaseName, runConfig.Group); err != nil { + slog.Warn("failed to remove from client config", "error", err) + } + } + if ctx.Err() != nil { + return + } + + statusReason := "Container exited, restarting" + if stable { + statusReason = "Container exited after stable run, restarting" + } + if err := d.statuses.SetWorkloadStatus(ctx, runConfig.BaseName, rt.WorkloadStatusStarting, statusReason); err != nil { + slog.Warn("failed to set workload status to starting", "workload", runConfig.BaseName, "error", err) + } +} + // validateSecretParameters validates the secret parameters for a workload. func (d *DefaultManager) validateSecretParameters(ctx context.Context, runConfig *runner.RunConfig) error { // If there are run secrets, validate them @@ -799,9 +963,18 @@ func (d *DefaultManager) spawnDetached(ctx context.Context, runConfig *runner.Ru return 0, err } + // A long-lived parent (thv serve) must reap its detached children too. + go reapDetachedProcess(detachedCmd) + return detachedCmd.Process.Pid, nil } +func reapDetachedProcess(cmd *exec.Cmd) { + if err := cmd.Wait(); err != nil { + slog.Debug("detached proxy exited with error", "pid", cmd.Process.Pid, "error", err) + } +} + // GetLogs retrieves the logs of a container. // The lines parameter specifies the maximum number of lines to return from the end of the logs. // If lines is 0, all logs are returned. @@ -905,7 +1078,10 @@ func (d *DefaultManager) deleteRemoteWorkload(ctx context.Context, name string, // Stop proxy if running if runConfig.BaseName != "" { - d.ensureProxyStopped(ctx, name, runConfig.BaseName, runConfig) + result := d.ensureProxyStopped(ctx, name, runConfig.BaseName, runConfig, true) + if err := d.failDeleteOnSupervisor(ctx, name, result); err != nil { + return err + } } // Clean up associated resources (remote workloads are not auxiliary) @@ -936,35 +1112,48 @@ func (d *DefaultManager) deleteContainerWorkload(ctx context.Context, name strin slog.Warn("failed to set workload status to removing", "workload", name, "error", err) } - // Determine baseName and isAuxiliary for cleanup (needed even if container doesn't exist) - var baseName string - var isAuxiliary bool - + // Use live labels when available, falling back to saved identity if startup + // has not created the container yet. + var containerLabels map[string]string if container != nil { - containerLabels := container.Labels - baseName = labels.GetContainerBaseName(containerLabels) - isAuxiliary = labels.IsAuxiliaryWorkload(containerLabels) - - // Remove the container first - if err := d.removeContainer(ctx, name); err != nil { - return err + containerLabels = container.Labels + } else if runConfig != nil { + containerLabels = runConfig.ContainerLabels + } + baseName := labels.GetContainerBaseName(containerLabels) + if baseName == "" { + if runConfig != nil && runConfig.BaseName != "" { + baseName = runConfig.BaseName + } else { + baseName = name } - } else { - // Container doesn't exist, but we still need to clean up state - // Use the workload name as baseName (they're typically the same) - baseName = name - isAuxiliary = false - slog.Debug("container not found for workload, proceeding with state cleanup", "workload", name) } + isAuxiliary := labels.IsAuxiliaryWorkload(containerLabels) - // Stop proxy-runner process AFTER container removal to prevent recreation - // Skip for auxiliary workloads like inspector that don't use proxy processes + // Stop the supervisor before removal, rather than letting removal itself + // trigger a restart. Delete fails while a signalled supervisor is still + // exiting or the recorded one cannot be verified, since either could + // still act on the workload. + // Auxiliary workloads like inspector do not use proxy processes. if !isAuxiliary { - d.ensureProxyStopped(ctx, name, baseName, runConfig) + proxyConfig := runConfig + if runConfig != nil { + configCopy := *runConfig + configCopy.BaseName = baseName + proxyConfig = &configCopy + } + result := d.ensureProxyStopped(ctx, name, baseName, proxyConfig, true) + if err := d.failDeleteOnSupervisor(ctx, name, result); err != nil { + return err + } } else { slog.Debug("skipping proxy-runner stop for auxiliary workload", "workload", name) } + if err := d.removeWorkloadContainer(ctx, name, container, runConfig); err != nil { + return err + } + // Clean up associated resources (must happen even if container doesn't exist) d.cleanupWorkloadResources(ctx, name, baseName, isAuxiliary) @@ -976,11 +1165,62 @@ func (d *DefaultManager) deleteContainerWorkload(ctx context.Context, name strin return nil } +// failDeleteOnSupervisor records an error status when delete cannot confirm +// that the supervisor has stopped. +func (d *DefaultManager) failDeleteOnSupervisor(ctx context.Context, name string, result proxyStopResult) error { + err := supervisorStopError(name, result, true) + if err != nil { + d.recordSupervisorStopError(ctx, name, err) + } + return err +} + +// recordSupervisorStopError replaces a stopping or removing status that would +// otherwise be left behind when the supervisor could not be stopped. +func (d *DefaultManager) recordSupervisorStopError(ctx context.Context, name string, err error) { + if statusErr := d.statuses.SetWorkloadStatus(ctx, name, rt.WorkloadStatusError, err.Error()); statusErr != nil { + slog.Warn("Failed to set workload status to error", "workload", name, "error", statusErr) + } +} + +// removeWorkloadContainer removes the workload's container during delete. +// container is the result of the initial lookup and may be nil. +func (d *DefaultManager) removeWorkloadContainer( + ctx context.Context, name string, container *rt.ContainerInfo, runConfig *runner.RunConfig, +) error { + if container == nil && runConfig == nil { + // Nothing identifies a container to remove; only the state cleanup applies. + slog.Debug("container not found for workload, proceeding with state cleanup", "workload", name) + return nil + } + + runtimeName := name + if container != nil { + runtimeName = cmp.Or(container.Name, name) + } else if runConfig.ContainerName != "" { + runtimeName = runConfig.ContainerName + } + + // Remove even when the saved container was absent during inspection: the + // supervisor may have created it in flight before it stopped. + err := d.removeContainer(ctx, name, runtimeName) + if err == nil || container != nil { + return err + } + if _, lookupErr := d.runtime.GetWorkloadInfo(ctx, runtimeName); errors.Is(lookupErr, rt.ErrWorkloadNotFound) || + errors.Is(lookupErr, rt.ErrContainerNotFound) { + slog.Warn("container removal failed but no container exists, continuing with state cleanup", + "workload", name, "container", runtimeName, "error", err) + return nil + } + return err +} + // getWorkloadContainer retrieves workload container info with error handling func (d *DefaultManager) getWorkloadContainer(ctx context.Context, name string) (*rt.ContainerInfo, error) { container, err := d.runtime.GetWorkloadInfo(ctx, name) if err != nil { - if errors.Is(err, rt.ErrWorkloadNotFound) { + if errors.Is(err, rt.ErrWorkloadNotFound) || errors.Is(err, rt.ErrContainerNotFound) { // Log but don't fail the entire operation for not found containers slog.Warn("failed to get workload", "workload", name, "error", err) return nil, nil @@ -1015,65 +1255,191 @@ func (d *DefaultManager) isSupervisorProcessAlive(ctx context.Context, name stri return true } -// stopProcess stops the proxy process associated with the container. It reports -// whether a tracked proxy process was actually stopped: true only when a valid -// PID was found and killed. A false return (no PID recorded, e.g. a missing -// status file, or the kill failed) signals callers to fall back to port-based -// cleanup so an orphaned proxy does not keep holding the workload's port. -func (d *DefaultManager) stopProcess(ctx context.Context, name string) bool { +// hasLiveSupervisorPID reports whether the workload records a PID that is its +// live supervisor. It fails when that PID is alive but cannot be inspected, +// because stop would neither signal it nor know that it is gone. +func (d *DefaultManager) hasLiveSupervisorPID(ctx context.Context, name string) (bool, error) { + if name == "" { + return false, nil + } + pid, err := d.statuses.GetWorkloadPID(ctx, name) + if err != nil || pid <= 0 { + return false, nil + } + switch identifySupervisor(pid, name) { + case supervisorVerified: + return true, nil + case supervisorUnverifiable: + return false, fmt.Errorf("workload %s: %w", name, errSupervisorUnverifiable) + case supervisorGone, supervisorForeign: + } + return false, nil +} + +type supervisorIdentity int + +const ( + supervisorGone supervisorIdentity = iota + supervisorVerified + // supervisorForeign is a live process that was inspected and is not this + // workload's supervisor, for example after PID reuse. + supervisorForeign + // supervisorUnverifiable is a live process (or one whose liveness is + // unknown) whose identity could not be inspected. + supervisorUnverifiable +) + +var ( + errSupervisorUnverifiable = errors.New( + "its recorded supervisor process is running but could not be verified, so it was not stopped") + errSupervisorExiting = errors.New("its supervisor process is still exiting; retry once it has stopped") +) + +func identifySupervisor(pid int, name string) supervisorIdentity { + verified, identityErr := process.IsTrackedToolHiveProxyForWorkload(pid, name) + if identityErr == nil && verified { + return supervisorVerified + } + alive, findErr := process.FindProcess(pid) + switch { + case findErr == nil && !alive: + return supervisorGone + case identityErr != nil || findErr != nil: + slog.Warn("could not verify tracked proxy identity", "workload", name, "pid", pid, + "identityError", identityErr, "error", findErr) + return supervisorUnverifiable + default: + return supervisorForeign + } +} + +// supervisorStopError reports a stop result that leaves the supervisor's +// state unknown. Delete and start also require a signalled supervisor to have +// exited, so it cannot tear down what they do next. +func supervisorStopError(name string, result proxyStopResult, requireExit bool) error { + switch { + case result == proxyUnverifiable: + return fmt.Errorf("workload %s: %w", name, errSupervisorUnverifiable) + case result == proxyExiting && requireExit: + return fmt.Errorf("workload %s: %w", name, errSupervisorExiting) + } + return nil +} + +// proxyStopResult describes the outcome of stopping a tracked proxy PID. +type proxyStopResult int + +const ( + // proxyNotStopped means no verified proxy was signalled, so callers may + // fall back to port-based cleanup. + proxyNotStopped proxyStopResult = iota + // proxyStopped means the verified proxy was signalled and has exited. + proxyStopped + // proxyExiting means the verified proxy was signalled but had not exited + // when the wait timed out. Signalling it again would not help. + proxyExiting + // proxyUnverifiable means the recorded PID is alive but its identity could + // not be inspected, so it was not signalled. + proxyUnverifiable +) + +// stopProcess stops the proxy process associated with the container. +// Unverified PIDs are cleared only if the process is confirmed gone; otherwise +// they remain available for a later retry. With requireExit, a verified +// supervisor that is still exiting after SIGTERM is killed. +func (d *DefaultManager) stopProcess(ctx context.Context, name string, requireExit bool) proxyStopResult { if name == "" { slog.Warn("could not find base container name in labels") - return false + return proxyNotStopped } - // Try to read the PID and kill the process pid, err := d.statuses.GetWorkloadPID(ctx, name) - if err != nil { + if err != nil || pid <= 0 { slog.Debug("no PID found, proxy may not be running in detached mode", "workload", name) - return false + return proxyNotStopped + } + + // Foreground runs rely on the status entry for workload binding; detached + // supervisors additionally have a verifiable workload name in their command. + switch identifySupervisor(pid, name) { + case supervisorVerified: + result := d.stopVerifiedProxy(ctx, name, pid, process.KillProcess) + if result == proxyExiting && requireExit { + // Its shutdown stops containers one by one with the runtime's stop + // timeout, which can take a minute. The caller takes over that + // cleanup, so it must not overlap with what the caller does next. + slog.Warn("supervisor is still exiting, killing it", "workload", name, "pid", pid) + result = d.stopVerifiedProxy(ctx, name, pid, process.ForceKillProcess) + } + return result + case supervisorUnverifiable: + return proxyUnverifiable + case supervisorForeign: + slog.Warn("tracked PID is not this workload's proxy, preserving it without signaling", "workload", name, "pid", pid) + case supervisorGone: + slog.Debug("tracked proxy is gone, clearing PID", "workload", name, "pid", pid) + if err := d.statuses.ResetWorkloadPIDIfMatch(ctx, name, pid); err != nil { + slog.Warn("failed to reset workload PID", "workload", name, "error", err) + } } + return proxyNotStopped +} - // PID found, try to kill the process - slog.Debug("stopping proxy process", "pid", pid) - stopped := false - if err := process.KillProcess(pid); err != nil { +// stopVerifiedProxy terminates a proxy whose identity the caller has verified. +func (d *DefaultManager) stopVerifiedProxy(ctx context.Context, name string, pid int, signal func(int) error) proxyStopResult { + slog.Debug("stopping proxy process", "workload", name, "pid", pid) + if err := signal(pid); err != nil { slog.Debug("failed to kill proxy process", "error", err) - } else { - slog.Debug("proxy process stopped") - stopped = true + return proxyNotStopped } - // Remove the PID of the terminated process - if err := d.statuses.ResetWorkloadPID(ctx, name); err != nil { + waitCtx, cancel := context.WithTimeout(ctx, d.proxyExitTimeoutOrDefault()) + defer cancel() + if err := process.WaitForExit(waitCtx, pid); err != nil { + slog.Warn("proxy process is still exiting after signal", "workload", name, "pid", pid, "error", err) + return proxyExiting + } + + slog.Debug("proxy process stopped", "workload", name, "pid", pid) + if err := d.statuses.ResetWorkloadPIDIfMatch(ctx, name, pid); err != nil { slog.Warn("failed to reset workload PID", "workload", name, "error", err) } - return stopped + return proxyStopped } -// stopProxyIfNeeded stops the proxy process if the workload has a base name. It -// reports whether a tracked proxy process was stopped (see stopProcess); false -// when there is no base name or no proxy was killed. -func (d *DefaultManager) stopProxyIfNeeded(ctx context.Context, name, baseName string) bool { +// stopProxyIfNeeded stops the proxy process if the workload has a base name +// (see stopProcess). +func (d *DefaultManager) stopProxyIfNeeded( + ctx context.Context, name, baseName string, requireExit bool, +) proxyStopResult { slog.Debug("removing proxy process", "workload", name) if baseName == "" { - return false + return proxyNotStopped } - return d.stopProcess(ctx, baseName) + return d.stopProcess(ctx, baseName, requireExit) } -// ensureProxyStopped stops the workload's proxy and guarantees its port is freed. -// It first stops the tracked PID (stopProxyIfNeeded); if that does not stop a -// proxy — no PID is recorded (e.g. the status file is missing) or the kill fails -// (e.g. a stale PID whose process is already gone) — it falls back to port-based -// cleanup, which only kills a process verified to be this workload's own proxy. +// ensureProxyStopped makes a best-effort attempt to stop the workload's proxy +// and free its port. +// It first stops the tracked PID (stopProxyIfNeeded). If no verified proxy was +// signalled — no PID is recorded, identity verification fails, or the signal +// fails — it falls back to port-based cleanup, which only kills a process +// verified to be this workload's own proxy. A proxy that was signalled but is +// still exiting is not signalled through the port again; with requireExit it +// is killed instead. // runConfig may be nil (no port fallback then). Used by the stop and delete // paths; the restart path instead frees the port itself, just before the child -// re-binds. -func (d *DefaultManager) ensureProxyStopped(ctx context.Context, name, baseName string, runConfig *runner.RunConfig) { - if !d.stopProxyIfNeeded(ctx, name, baseName) { +// re-binds. Callers fail with supervisorStopError rather than report success +// while the supervisor may still be managing the workload. +func (d *DefaultManager) ensureProxyStopped( + ctx context.Context, name, baseName string, runConfig *runner.RunConfig, requireExit bool, +) proxyStopResult { + result := d.stopProxyIfNeeded(ctx, name, baseName, requireExit) + if result == proxyNotStopped { d.portFreerOrDefault()(ctx, runConfig) } + return result } // freePortHolderIfNeeded kills the process holding the proxy port if it is in @@ -1083,7 +1449,7 @@ func (d *DefaultManager) ensureProxyStopped(ctx context.Context, name, baseName // "address already in use"), and // - stop/delete, as a fallback when PID-based termination is unavailable or // fails, so an orphaned proxy does not keep holding the port. -func (*DefaultManager) freePortHolderIfNeeded(ctx context.Context, runConfig *runner.RunConfig) { +func (d *DefaultManager) freePortHolderIfNeeded(ctx context.Context, runConfig *runner.RunConfig) { if runConfig == nil || runConfig.Port <= 0 { return } @@ -1126,21 +1492,22 @@ func (*DefaultManager) freePortHolderIfNeeded(ctx context.Context, runConfig *ru return } - waitCtx, cancel := context.WithTimeout(ctx, 5*time.Second) + waitCtx, cancel := context.WithTimeout(ctx, d.proxyExitTimeoutOrDefault()) defer cancel() if err := process.WaitForExit(waitCtx, portPID); err != nil { slog.Warn("timeout waiting for process to exit", "pid", portPID, "error", err) } } -// removeContainer removes the container from the runtime -func (d *DefaultManager) removeContainer(ctx context.Context, name string) error { +// removeContainer removes and verifies runtimeName while keeping status and +// diagnostics associated with the original workload name. +func (d *DefaultManager) removeContainer(ctx context.Context, name, runtimeName string) error { slog.Debug("removing container", "workload", name) - if err := d.runtime.RemoveWorkload(ctx, name); err != nil { + if err := d.runtime.RemoveWorkload(ctx, runtimeName); err != nil { if statusErr := d.statuses.SetWorkloadStatus(ctx, name, rt.WorkloadStatusError, err.Error()); statusErr != nil { slog.Warn("Failed to set workload status to error", "workload", name, "error", statusErr) } - return fmt.Errorf("failed to remove container: %w", err) + return fmt.Errorf("failed to remove container for workload %s: %w", name, err) } // Wait for the container to actually be removed from the runtime @@ -1148,21 +1515,21 @@ func (d *DefaultManager) removeContainer(ctx context.Context, name string) error const maxRetries = 30 const retryDelay = 100 * time.Millisecond for range maxRetries { - _, err := d.runtime.GetWorkloadInfo(ctx, name) + _, err := d.runtime.GetWorkloadInfo(ctx, runtimeName) if err != nil { - if errors.Is(err, rt.ErrWorkloadNotFound) { + if errors.Is(err, rt.ErrWorkloadNotFound) || errors.Is(err, rt.ErrContainerNotFound) { // Container is gone, deletion complete slog.Debug("container removed from runtime", "workload", name) return nil } // Some other error occurred slog.Warn("error checking container status during removal", "error", err) - return fmt.Errorf("failed to verify container removal: %w", err) + return fmt.Errorf("failed to verify container removal for workload %s: %w", name, err) } // Container still exists, wait and retry select { case <-ctx.Done(): - return fmt.Errorf("context cancelled while waiting for container removal: %w", ctx.Err()) + return fmt.Errorf("context cancelled while waiting for container removal for workload %s: %w", name, ctx.Err()) case <-time.After(retryDelay): continue } @@ -1183,7 +1550,7 @@ func (d *DefaultManager) cleanupWorkloadResources(ctx context.Context, name, bas } // Remove client configurations - if err := removeClientConfigurations(name, isAuxiliary); err != nil { + if err := d.removeClientConfigurations(name, isAuxiliary); err != nil { slog.Warn("failed to remove client configurations", "error", err) } else { slog.Debug("client configurations removed", "workload", name) @@ -1370,16 +1737,27 @@ func (d *DefaultManager) maybeSetupRemoteWorkload( slog.Debug("remote workload is running but supervisor is dead, cleaning up before restart", "workload", name) } - // Run cleanup (Stopping → stop proxy → remove client configs → Stopped) for all - // known workload states except Starting. Skip when workload not found (first-time start) + // Same handoff rules as container workloads: a foreground `thv run` stays + // in charge, and any other supervisor must be gone before a new one starts. + pid, stopErr := d.stopOtherSupervisor(ctx, runConfig.BaseName) + if stopErr != nil { + return nil, stopErr + } + if pid != 0 { + slog.Info("workload is supervised by a foreground thv run, leaving it in charge", + "workload", name, "pid", pid) + return nil, nil + } + + // Run cleanup (Stopping → remove client configs → Stopped) for all known + // workload states except Starting. Skip when workload not found (first-time start) // or status is Starting (parent set this before spawning the child process). needsCleanup := err == nil && workload.Status != rt.WorkloadStatusStarting if needsCleanup { if err := d.statuses.SetWorkloadStatus(ctx, name, rt.WorkloadStatusStopping, ""); err != nil { slog.Debug("failed to set workload status to stopping", "workload", name, "error", err) } - d.stopProxyIfNeeded(ctx, name, runConfig.BaseName) - if err := removeClientConfigurations(name, false); err != nil { + if err := d.removeClientConfigurations(name, false); err != nil { slog.Warn("failed to remove client configurations", "error", err) } if err := d.statuses.SetWorkloadStatus(ctx, name, rt.WorkloadStatusStopped, ""); err != nil { @@ -1469,6 +1847,21 @@ func (d *DefaultManager) maybeSetupContainerWorkload(ctx context.Context, name s slog.Debug("workload is running but supervisor is dead, cleaning up before restart", "workload", workloadName) } + // Stop any remaining supervisor, including one in restart backoff while + // the container has exited, so two supervisors never manage the same + // workload. + if !labels.IsAuxiliaryWorkload(container.Labels) { + pid, stopErr := d.stopOtherSupervisor(ctx, workloadName) + if stopErr != nil { + return "", nil, stopErr + } + if pid != 0 { + slog.Info("workload is supervised by a foreground thv run, leaving it in charge", + "workload", workloadName, "pid", pid) + return "", nil, nil + } + } + // Check if we need to stop the workload before restarting // This happens when: 1) container is running, or 2) inconsistent state shouldStop := false @@ -1489,12 +1882,6 @@ func (d *DefaultManager) maybeSetupContainerWorkload(ctx context.Context, name s slog.Debug("Failed to set workload status to stopping", "workload", workloadName, "error", err) } - // Stop the supervisor process (proxy) if it exists (may already be dead) - // This ensures we clean up any orphaned supervisor processes - if !labels.IsAuxiliaryWorkload(container.Labels) { - d.stopProcess(ctx, workloadName) - } - // Now stop the container if it's running if container.IsRunning() { if err := d.runtime.StopWorkload(ctx, containerName); err != nil { @@ -1507,7 +1894,7 @@ func (d *DefaultManager) maybeSetupContainerWorkload(ctx context.Context, name s } // Clean up client configurations - if err := removeClientConfigurations(workloadName, labels.IsAuxiliaryWorkload(container.Labels)); err != nil { + if err := d.removeClientConfigurations(workloadName, labels.IsAuxiliaryWorkload(container.Labels)); err != nil { slog.Warn("failed to remove client configurations", "error", err) } @@ -1542,6 +1929,28 @@ func (d *DefaultManager) maybeSetupContainerWorkload(ctx context.Context, name s return workloadName, mcpRunner, nil } +// stopOtherSupervisor stops the supervisor recorded for the workload before +// start or restart replaces it, unless it is this process, which happens when +// a detached `start --foreground` child sets up its own workload. +// +// A live non-detached `thv run` deletes the workload when it exits, so it is +// left in charge and its PID returned instead. Any other supervisor must be +// confirmed gone: one that is still exiting stops its container on the way +// out and would take down the replacement's, so it is killed. +func (d *DefaultManager) stopOtherSupervisor(ctx context.Context, name string) (foregroundRunPID int, err error) { + if name == "" { + return 0, nil + } + pid, err := d.statuses.GetWorkloadPID(ctx, name) + if err != nil || pid <= 0 || pid == os.Getpid() { + return 0, nil + } + if foreground, err := process.IsForegroundRunSupervisorForWorkload(pid, name); err == nil && foreground { + return pid, nil + } + return 0, supervisorStopError(name, d.stopProcess(ctx, name, true), true) +} + // startWorkload starts the workload in either foreground or background mode func (d *DefaultManager) startWorkload(ctx context.Context, name string, mcpRunner *runner.Runner, foreground bool) error { slog.Debug("starting tooling server", "workload", name) @@ -1567,8 +1976,8 @@ func (d *DefaultManager) startWorkload(ctx context.Context, name string, mcpRunn } // TODO: Move to dedicated config management interface. -// updateClientConfigurations updates client configuration files with the MCP server URL -func removeClientConfigurations(containerName string, isAuxiliary bool) error { +// removeClientConfigurations removes the server from client configuration files. +func (d *DefaultManager) removeClientConfigurations(containerName string, isAuxiliary bool) error { // Get the workload's group by loading its run config runConfig, err := runner.LoadState(context.Background(), containerName) var group string @@ -1582,7 +1991,7 @@ func removeClientConfigurations(containerName string, isAuxiliary bool) error { group = runConfig.Group } - clientManager, err := client.NewManager(context.Background()) + clientManager, err := d.clientManagers.NewClientManager(context.Background()) if err != nil { slog.Warn("failed to create client manager, skipping client config removal", "workload", containerName, "error", err) return nil @@ -1644,31 +2053,49 @@ func (*DefaultManager) cleanupTempPermissionProfile(ctx context.Context, baseNam // stopSingleContainerWorkload stops a single container workload. runConfig may // be nil; when present it lets stop fall back to port-based proxy cleanup if the -// tracked PID is unavailable (e.g. a missing status file). +// tracked PID is unavailable (e.g. a missing status file). The stopped status +// and client-configuration cleanup only apply when live is true. func (d *DefaultManager) stopSingleContainerWorkload( - ctx context.Context, workload *rt.ContainerInfo, runConfig *runner.RunConfig, + ctx context.Context, workload *rt.ContainerInfo, runConfig *runner.RunConfig, live bool, ) error { childCtx, cancel := context.WithTimeout(context.Background(), AsyncOperationTimeout) defer cancel() name := labels.GetContainerBaseName(workload.Labels) + isAuxiliary := labels.IsAuxiliaryWorkload(workload.Labels) // Stop the proxy process (skip for auxiliary workloads like inspector) - if labels.IsAuxiliaryWorkload(workload.Labels) { + if isAuxiliary { slog.Debug("skipping proxy stop for auxiliary workload", "workload", name) } else { - d.ensureProxyStopped(ctx, name, name, runConfig) + result := d.ensureProxyStopped(ctx, name, name, runConfig, false) + if err := supervisorStopError(name, result, false); err != nil { + if live { + d.recordSupervisorStopError(childCtx, name, err) + } + return err + } } slog.Debug("stopping containers", "workload", name) // Stop the container - if err := d.runtime.StopWorkload(childCtx, workload.Name); err != nil { - if statusErr := d.statuses.SetWorkloadStatus(childCtx, name, rt.WorkloadStatusError, err.Error()); statusErr != nil { - slog.Warn("Failed to set workload status to error", "workload", name, "error", statusErr) + stopErr := d.runtime.StopWorkload(childCtx, workload.Name) + exists, err := d.savedWorkloadStillExists(childCtx, name, runConfig, isAuxiliary) + if err != nil { + return errors.Join(err, stopErr) + } + if stopErr != nil { + if exists { + if statusErr := d.statuses.SetWorkloadStatus(childCtx, name, rt.WorkloadStatusError, stopErr.Error()); statusErr != nil { + slog.Warn("Failed to set workload status to error", "workload", name, "error", statusErr) + } } - return fmt.Errorf("failed to stop container: %w", err) + return fmt.Errorf("failed to stop container: %w", stopErr) + } + if !exists || !live { + return nil } - if err := removeClientConfigurations(name, labels.IsAuxiliaryWorkload(workload.Labels)); err != nil { + if err := d.removeClientConfigurations(name, isAuxiliary); err != nil { slog.Warn("failed to remove client configurations", "error", err) } else { slog.Debug("client configurations removed", "workload", name) diff --git a/pkg/workloads/manager_coverage_test.go b/pkg/workloads/manager_coverage_test.go new file mode 100644 index 0000000000..b52cea622c --- /dev/null +++ b/pkg/workloads/manager_coverage_test.go @@ -0,0 +1,268 @@ +// SPDX-FileCopyrightText: Copyright 2026 Stacklok, Inc. +// SPDX-License-Identifier: Apache-2.0 + +package workloads + +import ( + "context" + "errors" + "fmt" + "math" + "os" + "os/exec" + "path/filepath" + goruntime "runtime" + "strings" + "testing" + "time" + + "github.com/adrg/xdg" + "github.com/stretchr/testify/require" + "go.uber.org/mock/gomock" + + "github.com/stacklok/toolhive/pkg/client" + clientMocks "github.com/stacklok/toolhive/pkg/client/mocks" + "github.com/stacklok/toolhive/pkg/container/runtime" + runtimeMocks "github.com/stacklok/toolhive/pkg/container/runtime/mocks" + "github.com/stacklok/toolhive/pkg/labels" + "github.com/stacklok/toolhive/pkg/process" + "github.com/stacklok/toolhive/pkg/runner" + statusMocks "github.com/stacklok/toolhive/pkg/workloads/statuses/mocks" +) + +func TestDetachedReaperFixture_RejectsMismatchedInvocation(t *testing.T) { + t.Parallel() + executable, err := os.Executable() + require.NoError(t, err) + for _, tt := range []struct { + name string + mode string + }{ + {name: "marked malformed invocation", mode: "clean"}, + {name: "empty marker"}, + } { + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + t.Cleanup(cancel) + // If TestMain falls through, select no tests so a regression cannot recursively spawn fixtures. + cmd := exec.CommandContext(ctx, executable, "-test.run=^$") + for _, entry := range os.Environ() { + if !strings.HasPrefix(entry, detachedReaperTestEnv+"=") && + !strings.HasPrefix(entry, process.ToolHiveDetachedEnv+"=") { + cmd.Env = append(cmd.Env, entry) + } + } + cmd.Env = append(cmd.Env, detachedReaperTestEnv+"="+tt.mode, + process.ToolHiveDetachedEnv+"="+process.ToolHiveDetachedValue) + output, err := cmd.CombinedOutput() + require.NoError(t, ctx.Err(), "fixture must reject the invocation before the deadline") + var exitErr *exec.ExitError + require.ErrorAs(t, err, &exitErr) + require.Equal(t, 2, exitErr.ExitCode(), string(output)) + require.Contains(t, string(output), "unexpected detached reaper invocation") + }) + } +} + +func TestDefaultManager_prepareWorkloadRestart_ClientCleanup(t *testing.T) { + t.Parallel() + for _, tt := range []struct { + name string + stable bool + cancelCleanup bool + preCancelled bool + factoryError bool + }{ + {name: "cleanup error still restarts"}, + {name: "cleanup error still restarts stable workload", stable: true}, + {name: "cancellation during cleanup preserves status", cancelCleanup: true}, + {name: "pre-cancelled restart preserves status", preCancelled: true}, + {name: "factory failure still restarts", factoryError: true}, + } { + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + t.Cleanup(cancel) + if tt.preCancelled { + cancel() + } + ctrl := gomock.NewController(t) + sm := statusMocks.NewMockStatusManager(ctrl) + cm := clientMocks.NewMockManager(ctrl) + const name, group = "retry-client-cleanup", "test-group" + if !tt.factoryError { + cleanupCall := cm.EXPECT().RemoveServerFromClients(ctx, name, group).DoAndReturn(func(context.Context, string, string) error { + if !tt.preCancelled { + require.NoError(t, ctx.Err(), "cancellation must begin inside client cleanup") + } + if tt.cancelCleanup { + cancel() + } + return errors.New("client configuration is read-only") + }) + if tt.preCancelled { + cleanupCall.AnyTimes() + } + } + if !tt.cancelCleanup && !tt.preCancelled { + reason := "Container exited, restarting" + if tt.stable { + reason = "Container exited after stable run, restarting" + } + sm.EXPECT().SetWorkloadStatus(ctx, name, runtime.WorkloadStatusStarting, reason).Return(nil) + } + manager := &DefaultManager{statuses: sm} + manager.clientManagers = testClientManagerProvider(func(context.Context) (client.Manager, error) { + if tt.factoryError { + return nil, errors.New("client manager unavailable") + } + return cm, nil + }) + + manager.prepareWorkloadRestart(ctx, &runner.RunConfig{BaseName: name, Group: group}, tt.stable) + if tt.cancelCleanup || tt.preCancelled { + require.ErrorIs(t, ctx.Err(), context.Canceled) + } + }) + } +} + +//nolint:paralleltest // saved-workload fixtures use t.Setenv +func TestDefaultManager_StopCleanupErrorsDoNotPreventStopped(t *testing.T) { + isolateWorkloadStopState(t) + for _, remote := range []bool{false, true} { + for _, factoryError := range []bool{false, true} { + t.Run(fmt.Sprintf("remote=%t/factoryError=%t", remote, factoryError), func(t *testing.T) { + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + t.Cleanup(cancel) + const name, group = "stop-client-cleanup", "test-group" + rc := &runner.RunConfig{BaseName: name, Group: group} + persistStopRunConfig(t, name, rc) + ctrl := gomock.NewController(t) + sm := statusMocks.NewMockStatusManager(ctrl) + cm := clientMocks.NewMockManager(ctrl) + rm := runtimeMocks.NewMockRuntime(ctrl) + manager := &DefaultManager{ + savedRunConfigs: testSavedRunConfigChecker{exists: true}, + statuses: sm, runtime: rm, + } + manager.clientManagers = testClientManagerProvider(func(context.Context) (client.Manager, error) { + if factoryError { + return nil, errors.New("client manager unavailable") + } + return cm, nil + }) + var cleanupCall *gomock.Call + if !factoryError { + cleanupCall = cm.EXPECT().RemoveServerFromClients(gomock.Any(), name, group). + Return(errors.New("client configuration is read-only")) + } + stopped := sm.EXPECT().SetWorkloadStatus(gomock.Any(), name, runtime.WorkloadStatusStopped, "").Return(nil) + if cleanupCall != nil { + stopped.After(cleanupCall) + } + if remote { + require.NoError(t, manager.finishRemoteWorkloadStop(ctx, name, rc)) + return + } + sm.EXPECT().GetWorkloadPID(gomock.Any(), name).Return(0, nil) + withPortFreer(func(context.Context, *runner.RunConfig) {})(manager) + stop := rm.EXPECT().StopWorkload(gomock.Any(), name).Return(nil) + stopped.After(stop) + if cleanupCall != nil { + cleanupCall.After(stop) + } + require.NoError(t, manager.stopSingleContainerWorkload(ctx, &runtime.ContainerInfo{ + Name: name, Labels: map[string]string{labels.LabelBaseName: name}, + }, rc, true)) + }) + } + } +} + +func TestDefaultManager_stopVerifiedProxy_SignalErrorPreservesPID(t *testing.T) { + t.Parallel() + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + t.Cleanup(cancel) + const name = "signal-error-proxy" + pid := math.MaxInt32 + manager := &DefaultManager{statuses: statusMocks.NewMockStatusManager(gomock.NewController(t))} + signalled := false + signal := func(handle int) error { + signalled = true + require.Equal(t, pid, handle, "the injected signal must receive the saved PID") + return errors.New("process signal failed") + } + + require.Equal(t, proxyNotStopped, manager.stopVerifiedProxy(ctx, name, pid, signal), "a failed signal must not reset the saved PID") + require.True(t, signalled) +} + +func TestDefaultManager_stopVerifiedProxy_ExitTimeout(t *testing.T) { + t.Parallel() + const name = "signalled-but-exiting" + proxy := startProxyProcess(t, name, true) + sm := statusMocks.NewMockStatusManager(gomock.NewController(t)) + manager := &DefaultManager{statuses: sm} + withProxyExitTimeout(50 * time.Millisecond)(manager) + + result := manager.stopVerifiedProxy(context.Background(), name, proxy.pid, process.KillProcess) + require.Equal(t, proxyExiting, result) + select { + case <-proxy.exited: + t.Error("SIGTERM-ignoring proxy unexpectedly exited") + default: + } +} + +func TestDefaultManager_spawnDetached_ReapsOwnedChildren(t *testing.T) { + if goruntime.GOOS == "windows" { + t.Skip("detached fixture requires Unix process reaping") + } + isolateWorkloadStopState(t) + t.Setenv(process.ToolHiveDetachedEnv, "") + for _, mode := range []string{"clean", "error"} { + t.Run(mode, func(t *testing.T) { + t.Setenv(detachedReaperTestEnv, mode) + name := "detached-reaper-79cbf5-" + mode + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + t.Cleanup(cancel) + sm := statusMocks.NewMockStatusManager(gomock.NewController(t)) + sm.EXPECT().SetWorkloadStatus(ctx, name, runtime.WorkloadStatusStarting, "").Return(nil) + manager := &DefaultManager{statuses: sm} + + pid, err := manager.spawnDetached(ctx, &runner.RunConfig{BaseName: name}) + require.NoError(t, err) + require.Positive(t, pid) + reaped := false + t.Cleanup(func() { + if reaped { + return + } + alive, findErr := process.FindProcess(pid) + if findErr == nil && alive { + child, findErr := os.FindProcess(pid) + if findErr == nil { + _ = child.Kill() + } + } + cleanupCtx, cleanupCancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cleanupCancel() + require.NoError(t, process.WaitForExit(cleanupCtx, pid), "detached fixture must not outlive the test") + }) + require.NoError(t, process.WaitForExit(ctx, pid), "spawnDetached must reap even a failed child") + reaped = true + alive, err := process.FindProcess(pid) + require.NoError(t, err) + require.False(t, alive) + log, err := os.ReadFile(filepath.Join(xdg.DataHome, "toolhive", "logs", name+".log")) + require.NoError(t, err) + exitCode := 0 + if mode == "error" { + exitCode = 42 + } + require.Contains(t, string(log), fmt.Sprintf("detached reaper fixture exit %d", exitCode), "only the explicitly gated child fixture may run") + }) + } +} diff --git a/pkg/workloads/manager_delete_test.go b/pkg/workloads/manager_delete_test.go new file mode 100644 index 0000000000..faab53d207 --- /dev/null +++ b/pkg/workloads/manager_delete_test.go @@ -0,0 +1,237 @@ +// SPDX-FileCopyrightText: Copyright 2025 Stacklok, Inc. +// SPDX-License-Identifier: Apache-2.0 + +package workloads + +import ( + "context" + "errors" + "fmt" + "testing" + "time" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + "go.uber.org/mock/gomock" + + "github.com/stacklok/toolhive/pkg/container/runtime" + runtimeMocks "github.com/stacklok/toolhive/pkg/container/runtime/mocks" + "github.com/stacklok/toolhive/pkg/labels" + "github.com/stacklok/toolhive/pkg/process" + "github.com/stacklok/toolhive/pkg/runner" + statusMocks "github.com/stacklok/toolhive/pkg/workloads/statuses/mocks" +) + +//nolint:paralleltest // saved-workload fixtures use t.Setenv +func TestDefaultManager_deleteContainerWorkload_StopsSupervisorBeforeFreshRemoval(t *testing.T) { + isolateWorkloadStopState(t) + removeErr := errors.New("network teardown failed") + for _, tt := range []struct { + name string + missingErr error + removeErr error + verifiedErr error + }{ + {name: "existing primary", verifiedErr: runtime.ErrWorkloadNotFound}, + {name: "primary starts after empty lookup", missingErr: runtime.ErrWorkloadNotFound, verifiedErr: runtime.ErrWorkloadNotFound}, + {name: "primary starts after inspect not found", missingErr: runtime.ErrContainerNotFound, verifiedErr: runtime.ErrContainerNotFound}, + {name: "deletion failure preserves saved config", missingErr: runtime.ErrWorkloadNotFound, removeErr: removeErr}, + } { + t.Run(tt.name, func(t *testing.T) { + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + t.Cleanup(cancel) + const name = "deleting-workload" + const containerName = "deleting-workload-1730000000" + rc := &runner.RunConfig{BaseName: name, ContainerName: containerName} + persistStopRunConfig(t, name, rc) + saved, err := runner.LoadState(ctx, name) + require.NoError(t, err) + proxy := startVerifiedProxyProcess(t, name) + ctrl := gomock.NewController(t) + rtMock := runtimeMocks.NewMockRuntime(ctrl) + sm := statusMocks.NewMockStatusManager(ctrl) + primaryExists := tt.missingErr == nil + if tt.missingErr != nil { + rtMock.EXPECT().GetWorkloadInfo(gomock.Any(), name). + Return(runtime.ContainerInfo{}, fmt.Errorf("initial inspection: %w", tt.missingErr)) + } else { + rtMock.EXPECT().GetWorkloadInfo(gomock.Any(), name).Return(runtime.ContainerInfo{ + Name: containerName, Labels: map[string]string{labels.LabelBaseName: name}, + }, nil) + } + sm.EXPECT().SetWorkloadStatus(gomock.Any(), name, runtime.WorkloadStatusRemoving, "").Return(nil) + sm.EXPECT().GetWorkloadPID(gomock.Any(), name).DoAndReturn(func(context.Context, string) (int, error) { + // Model an in-flight supervisor startup finishing after the initial lookup. + primaryExists = true + return proxy.pid, nil + }) + sm.EXPECT().ResetWorkloadPIDIfMatch(gomock.Any(), name, proxy.pid).Return(nil) + removalName := containerName + rtMock.EXPECT().RemoveWorkload(gomock.Any(), removalName).DoAndReturn(func(context.Context, string) error { + alive, err := process.FindProcess(proxy.pid) + require.NoError(t, err) + require.False(t, alive, "runtime deletion began while the supervisor could still recreate the workload") + // Check liveness before waiting: waiting first could hide the original ordering regression. + select { + case <-proxy.exited: + assert.NoError(t, proxy.waitErr, "supervisor must finish graceful shutdown before runtime deletion") + case <-time.After(time.Second): + t.Fatal("supervisor helper was not reaped") + } + assert.True(t, primaryExists, "fresh removal must catch the workload created after the initial lookup") + if tt.removeErr == nil { + primaryExists = false + } + return tt.removeErr + }) + if tt.removeErr != nil { + rtMock.EXPECT().GetWorkloadInfo(gomock.Any(), removalName).Return(runtime.ContainerInfo{Name: containerName}, nil) + sm.EXPECT().SetWorkloadStatus(gomock.Any(), name, runtime.WorkloadStatusError, tt.removeErr.Error()).Return(nil) + } else { + rtMock.EXPECT().GetWorkloadInfo(gomock.Any(), removalName). + Return(runtime.ContainerInfo{}, fmt.Errorf("removal verification: %w", tt.verifiedErr)) + sm.EXPECT().DeleteWorkloadStatus(gomock.Any(), name).Return(nil) + } + manager := &DefaultManager{ + clientManagers: testClientManagerProvider(unavailableClientManager), + runtime: rtMock, + statuses: sm, + } + withPortFreer(func(context.Context, *runner.RunConfig) { + t.Error("verified supervisor exit must not need port fallback") + })(manager) + + err = manager.deleteContainerWorkload(ctx, name, rc) + if tt.removeErr != nil { + require.ErrorIs(t, err, tt.removeErr) + after, loadErr := runner.LoadState(ctx, name) + require.NoError(t, loadErr, "failed deletion must retain recovery state") + assert.Equal(t, saved, after) + } else { + require.NoError(t, err) + assert.False(t, primaryExists, "delete must not leave a newly created primary behind") + _, loadErr := runner.LoadState(ctx, name) + require.Error(t, loadErr, "successful deletion must remove saved config") + } + }) + } +} + +//nolint:paralleltest // saved-workload fixtures use t.Setenv +func TestDefaultManager_deleteContainerWorkload_AuxiliaryDoesNotStopSupervisorOrDeleteParentConfig(t *testing.T) { + isolateWorkloadStopState(t) + ctx := context.Background() + const parent = "parent-workload" + const auxiliary = "parent-workload-inspector" + parentConfig := &runner.RunConfig{BaseName: parent} + persistStopRunConfig(t, parent, parentConfig) + saved, err := runner.LoadState(ctx, parent) + require.NoError(t, err) + proxy := startVerifiedProxyProcess(t, parent) + auxLabels := map[string]string{labels.LabelBaseName: auxiliary, labels.LabelAuxiliary: "true"} + ctrl := gomock.NewController(t) + rtMock := runtimeMocks.NewMockRuntime(ctrl) + sm := statusMocks.NewMockStatusManager(ctrl) + rtMock.EXPECT().GetWorkloadInfo(gomock.Any(), auxiliary). + Return(runtime.ContainerInfo{Name: auxiliary, Labels: auxLabels}, nil) + sm.EXPECT().SetWorkloadStatus(gomock.Any(), auxiliary, runtime.WorkloadStatusRemoving, "").Return(nil) + rtMock.EXPECT().RemoveWorkload(gomock.Any(), auxiliary).Return(nil) + rtMock.EXPECT().GetWorkloadInfo(gomock.Any(), auxiliary).Return(runtime.ContainerInfo{}, runtime.ErrWorkloadNotFound) + sm.EXPECT().DeleteWorkloadStatus(gomock.Any(), auxiliary).Return(nil) + manager := &DefaultManager{ + clientManagers: testClientManagerProvider(unavailableClientManager), + runtime: rtMock, + statuses: sm, + } + withPortFreer(func(context.Context, *runner.RunConfig) { t.Error("auxiliary deletion must not clean up parent proxy") })(manager) + + require.NoError(t, manager.deleteContainerWorkload(ctx, auxiliary, nil)) + alive, err := process.FindProcess(proxy.pid) + require.NoError(t, err) + assert.True(t, alive, "auxiliary deletion must not stop the parent supervisor") + select { + case <-proxy.exited: + t.Error("auxiliary deletion stopped the parent supervisor") + default: + } + after, err := runner.LoadState(ctx, parent) + require.NoError(t, err) + assert.Equal(t, saved, after) +} + +//nolint:paralleltest // deletion reads and removes saved state +func TestDefaultManager_deleteContainerWorkload_MissingContainer(t *testing.T) { + isolateWorkloadStopState(t) + removeErr := errors.New("runtime removal failed") + verifyErr := errors.New("runtime inspection failed") + for _, tt := range []struct { + name string + saved bool + removeErr error + verifyErr error + appeared bool + }{ + {name: "no saved configuration skips runtime removal"}, + {name: "failed removal with no remaining container deletes saved state", saved: true, removeErr: removeErr}, + {name: "container appearing after failed removal preserves saved state", saved: true, removeErr: removeErr, appeared: true}, + {name: "failed verification with no remaining container deletes saved state", saved: true, verifyErr: verifyErr}, + {name: "container appearing after failed verification preserves saved state", saved: true, verifyErr: verifyErr, appeared: true}, + } { + t.Run(tt.name, func(t *testing.T) { + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + t.Cleanup(cancel) + const name = "missing-delete-workload" + const containerName = "missing-delete-workload-20260101" + var rc *runner.RunConfig + if tt.saved { + rc = &runner.RunConfig{BaseName: name, ContainerName: containerName} + persistStopRunConfig(t, name, rc) + } + ctrl := gomock.NewController(t) + rtMock := runtimeMocks.NewMockRuntime(ctrl) + sm := statusMocks.NewMockStatusManager(ctrl) + rtMock.EXPECT().GetWorkloadInfo(gomock.Any(), name).Return(runtime.ContainerInfo{}, runtime.ErrWorkloadNotFound) + sm.EXPECT().SetWorkloadStatus(gomock.Any(), name, runtime.WorkloadStatusRemoving, "").Return(nil) + sm.EXPECT().GetWorkloadPID(gomock.Any(), name).Return(0, nil) + if tt.saved { + rtMock.EXPECT().RemoveWorkload(gomock.Any(), containerName).Return(tt.removeErr) + if tt.removeErr != nil { + sm.EXPECT().SetWorkloadStatus(gomock.Any(), name, runtime.WorkloadStatusError, tt.removeErr.Error()).Return(nil) + } else { + rtMock.EXPECT().GetWorkloadInfo(gomock.Any(), containerName).Return(runtime.ContainerInfo{}, tt.verifyErr) + } + if tt.appeared { + rtMock.EXPECT().GetWorkloadInfo(gomock.Any(), containerName).Return(runtime.ContainerInfo{Name: containerName}, nil) + } else { + rtMock.EXPECT().GetWorkloadInfo(gomock.Any(), containerName).Return(runtime.ContainerInfo{}, runtime.ErrContainerNotFound) + } + } + if !tt.appeared { + sm.EXPECT().DeleteWorkloadStatus(gomock.Any(), name).Return(nil) + } + fallbackCalls := 0 + manager := &DefaultManager{ + runtime: rtMock, + statuses: sm, + clientManagers: testClientManagerProvider(unavailableClientManager), + } + withPortFreer(func(context.Context, *runner.RunConfig) { fallbackCalls++ })(manager) + + err := manager.deleteContainerWorkload(ctx, name, rc) + assert.Equal(t, 1, fallbackCalls, "missing containers must not suppress orphan proxy cleanup") + if tt.appeared { + if tt.removeErr != nil { + require.ErrorIs(t, err, tt.removeErr) + } else { + require.ErrorIs(t, err, tt.verifyErr) + } + _, loadErr := runner.LoadState(ctx, name) + require.NoError(t, loadErr, "failed deletion must retain recovery state") + } else { + require.NoError(t, err) + _, loadErr := runner.LoadState(ctx, name) + require.Error(t, loadErr, "successful deletion must remove saved state") + } + }) + } +} diff --git a/pkg/workloads/manager_supervisor_test.go b/pkg/workloads/manager_supervisor_test.go new file mode 100644 index 0000000000..e75c65f899 --- /dev/null +++ b/pkg/workloads/manager_supervisor_test.go @@ -0,0 +1,189 @@ +// SPDX-FileCopyrightText: Copyright 2025 Stacklok, Inc. +// SPDX-License-Identifier: Apache-2.0 + +package workloads + +import ( + "context" + "testing" + "time" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + "go.uber.org/mock/gomock" + + "github.com/stacklok/toolhive/pkg/container/runtime" + runtimeMocks "github.com/stacklok/toolhive/pkg/container/runtime/mocks" + "github.com/stacklok/toolhive/pkg/core" + "github.com/stacklok/toolhive/pkg/labels" + "github.com/stacklok/toolhive/pkg/runner" + statusMocks "github.com/stacklok/toolhive/pkg/workloads/statuses/mocks" +) + +// unverifiableSupervisorPID returns a live PID whose identity this test +// process cannot inspect. PID 1 belongs to another user unless tests run as +// root, in which case the scenario cannot be reproduced. +func unverifiableSupervisorPID(t *testing.T, name string) int { + t.Helper() + if identifySupervisor(1, name) != supervisorUnverifiable { + t.Skip("PID 1 can be inspected by this user") + } + return 1 +} + +func TestDefaultManager_UnverifiableSupervisorFailsStopDeleteAndStart(t *testing.T) { + t.Parallel() + const name = "unverifiable-supervisor" + pid := unverifiableSupervisorPID(t, name) + exited := runtime.ContainerInfo{Name: name, State: "exited", Labels: map[string]string{labels.LabelBaseName: name}} + + t.Run("stop", func(t *testing.T) { + t.Parallel() + ctrl := gomock.NewController(t) + rtMock := runtimeMocks.NewMockRuntime(ctrl) + sm := statusMocks.NewMockStatusManager(ctrl) + rtMock.EXPECT().GetWorkloadInfo(gomock.Any(), name).Return(exited, nil) + sm.EXPECT().GetWorkloadPID(gomock.Any(), name).Return(pid, nil) + // No status writes or runtime stop: stop must not report a supervisor + // it could neither signal nor rule out as stopped. + manager := &DefaultManager{runtime: rtMock, statuses: sm} + + err := manager.stopContainerWorkload(context.Background(), name, &runner.RunConfig{BaseName: name}) + require.ErrorIs(t, err, errSupervisorUnverifiable) + }) + + t.Run("delete", func(t *testing.T) { + t.Parallel() + ctrl := gomock.NewController(t) + rtMock := runtimeMocks.NewMockRuntime(ctrl) + sm := statusMocks.NewMockStatusManager(ctrl) + rtMock.EXPECT().GetWorkloadInfo(gomock.Any(), name).Return(exited, nil) + sm.EXPECT().SetWorkloadStatus(gomock.Any(), name, runtime.WorkloadStatusRemoving, "").Return(nil) + sm.EXPECT().GetWorkloadPID(gomock.Any(), name).Return(pid, nil) + sm.EXPECT().SetWorkloadStatus(gomock.Any(), name, runtime.WorkloadStatusError, gomock.Any()).Return(nil) + // No container removal or status deletion while the supervisor may live. + manager := &DefaultManager{runtime: rtMock, statuses: sm} + + err := manager.deleteContainerWorkload(context.Background(), name, nil) + require.ErrorIs(t, err, errSupervisorUnverifiable) + }) + + t.Run("start", func(t *testing.T) { + t.Parallel() + ctrl := gomock.NewController(t) + sm := statusMocks.NewMockStatusManager(ctrl) + sm.EXPECT().GetWorkloadPID(gomock.Any(), name).Return(pid, nil).Times(2) + manager := &DefaultManager{statuses: sm} + + foregroundPID, err := manager.stopOtherSupervisor(context.Background(), name) + require.ErrorIs(t, err, errSupervisorUnverifiable) + assert.Zero(t, foregroundPID) + }) +} + +// A supervisor's shutdown stops its containers one by one with the runtime's +// stop timeout, so it can outlast stop's wait. Delete and start must not +// overlap with it, but `thv stop` followed by `thv start` or `thv rm` must not +// fail either, so they kill a supervisor that is still exiting. +func TestDefaultManager_ExitingSupervisorIsKilledBeforeDeleteAndStart(t *testing.T) { + t.Parallel() + + t.Run("stop leaves it exiting", func(t *testing.T) { + t.Parallel() + const name = "exiting-supervisor-stop" + proxy := startProxyProcess(t, name, true) + ctrl := gomock.NewController(t) + sm := statusMocks.NewMockStatusManager(ctrl) + sm.EXPECT().GetWorkloadPID(gomock.Any(), name).Return(proxy.pid, nil) + manager := &DefaultManager{statuses: sm} + withProxyExitTimeout(50 * time.Millisecond)(manager) + + require.Equal(t, proxyExiting, manager.stopProcess(context.Background(), name, false)) + select { + case <-proxy.exited: + t.Error("stop must not kill a supervisor that is shutting down") + default: + } + }) + + t.Run("start", func(t *testing.T) { + t.Parallel() + const name = "exiting-supervisor-start" + proxy := startProxyProcess(t, name, true) + ctrl := gomock.NewController(t) + sm := statusMocks.NewMockStatusManager(ctrl) + sm.EXPECT().GetWorkloadPID(gomock.Any(), name).Return(proxy.pid, nil).Times(2) + sm.EXPECT().ResetWorkloadPIDIfMatch(gomock.Any(), name, proxy.pid).Return(nil) + manager := &DefaultManager{statuses: sm} + withProxyExitTimeout(50 * time.Millisecond)(manager) + + foregroundPID, err := manager.stopOtherSupervisor(context.Background(), name) + require.NoError(t, err) + assert.Zero(t, foregroundPID) + requireExited(t, proxy) + }) + + t.Run("delete", func(t *testing.T) { + t.Parallel() + const name = "exiting-supervisor-delete" + proxy := startProxyProcess(t, name, true) + ctrl := gomock.NewController(t) + rtMock := runtimeMocks.NewMockRuntime(ctrl) + sm := statusMocks.NewMockStatusManager(ctrl) + rtMock.EXPECT().GetWorkloadInfo(gomock.Any(), name).Return(runtime.ContainerInfo{ + Name: name, State: "running", Labels: map[string]string{labels.LabelBaseName: name}, + }, nil) + sm.EXPECT().SetWorkloadStatus(gomock.Any(), name, runtime.WorkloadStatusRemoving, "").Return(nil) + sm.EXPECT().GetWorkloadPID(gomock.Any(), name).Return(proxy.pid, nil) + sm.EXPECT().ResetWorkloadPIDIfMatch(gomock.Any(), name, proxy.pid).Return(nil) + rtMock.EXPECT().RemoveWorkload(gomock.Any(), name).DoAndReturn(func(context.Context, string) error { + requireExited(t, proxy) + return nil + }) + rtMock.EXPECT().GetWorkloadInfo(gomock.Any(), name).Return(runtime.ContainerInfo{}, runtime.ErrWorkloadNotFound) + sm.EXPECT().DeleteWorkloadStatus(gomock.Any(), name).Return(nil) + manager := &DefaultManager{ + runtime: rtMock, statuses: sm, + clientManagers: testClientManagerProvider(unavailableClientManager), + } + withProxyExitTimeout(50 * time.Millisecond)(manager) + withPortFreer(func(context.Context, *runner.RunConfig) { + t.Error("a signalled supervisor must not be signalled again through port cleanup") + })(manager) + + require.NoError(t, manager.deleteContainerWorkload(context.Background(), name, nil)) + }) +} + +func requireExited(t *testing.T, proxy *workloadProxyProcess) { + t.Helper() + // The helper's Wait goroutine closes exited just after reaping the process. + select { + case <-proxy.exited: + case <-time.After(time.Second): + t.Fatal("the old supervisor must be gone before the caller proceeds") + } +} + +func TestDefaultManager_maybeSetupRemoteWorkload_ForegroundRunKeepsOwnership(t *testing.T) { + t.Parallel() + const name = "foreground-remote" + proxy := startVerifiedProxyProcess(t, "", "run", "--name", name, "https://example.com/mcp") + ctrl := gomock.NewController(t) + sm := statusMocks.NewMockStatusManager(ctrl) + sm.EXPECT().GetWorkload(gomock.Any(), name).Return(core.Workload{Name: name, Status: runtime.WorkloadStatusUnhealthy}, nil) + sm.EXPECT().GetWorkloadPID(gomock.Any(), name).Return(proxy.pid, nil) + // No status writes: the foreground run would delete the workload if it + // were signalled during restart. + manager := &DefaultManager{statuses: sm} + + gotRunner, err := manager.maybeSetupRemoteWorkload(context.Background(), name, + &runner.RunConfig{BaseName: name, RemoteURL: "https://example.com/mcp"}) + require.NoError(t, err) + assert.Nil(t, gotRunner) + select { + case <-proxy.exited: + t.Error("foreground run must keep ownership of its remote workload") + case <-time.After(100 * time.Millisecond): + } +} diff --git a/pkg/workloads/manager_test.go b/pkg/workloads/manager_test.go index c828e0e6bb..273aeda2f0 100644 --- a/pkg/workloads/manager_test.go +++ b/pkg/workloads/manager_test.go @@ -4,11 +4,20 @@ package workloads import ( + "bufio" "context" "errors" "fmt" + "maps" + "net" + "os" "os/exec" + "os/signal" + "path/filepath" goruntime "runtime" + "strconv" + "strings" + "syscall" "testing" "time" @@ -17,18 +26,43 @@ import ( "github.com/stretchr/testify/require" "go.uber.org/mock/gomock" + "github.com/stacklok/toolhive/pkg/client" + clientMocks "github.com/stacklok/toolhive/pkg/client/mocks" "github.com/stacklok/toolhive/pkg/config" configMocks "github.com/stacklok/toolhive/pkg/config/mocks" "github.com/stacklok/toolhive/pkg/container/runtime" runtimeMocks "github.com/stacklok/toolhive/pkg/container/runtime/mocks" "github.com/stacklok/toolhive/pkg/core" + "github.com/stacklok/toolhive/pkg/labels" + "github.com/stacklok/toolhive/pkg/networking" + "github.com/stacklok/toolhive/pkg/process" "github.com/stacklok/toolhive/pkg/runner" + "github.com/stacklok/toolhive/pkg/state" "github.com/stacklok/toolhive/pkg/transport/types" "github.com/stacklok/toolhive/pkg/vmcp" "github.com/stacklok/toolhive/pkg/workloads/statuses" statusMocks "github.com/stacklok/toolhive/pkg/workloads/statuses/mocks" ) +type testClientManagerProvider func(context.Context) (client.Manager, error) + +func (f testClientManagerProvider) NewClientManager(ctx context.Context) (client.Manager, error) { + return f(ctx) +} + +func unavailableClientManager(context.Context) (client.Manager, error) { + return nil, errors.New("client manager unavailable") +} + +type testSavedRunConfigChecker struct { + exists bool + err error +} + +func (f testSavedRunConfigChecker) Exists(context.Context, string) (bool, error) { + return f.exists, f.err +} + func TestDefaultManager_ListWorkloadsInGroup(t *testing.T) { t.Parallel() @@ -740,7 +774,9 @@ func TestDefaultManager_restartRemoteWorkload(t *testing.T) { tt.setupMocks(statusMgr) manager := &DefaultManager{ - statuses: statusMgr, + savedRunConfigs: testSavedRunConfigChecker{exists: true}, + clientManagers: testClientManagerProvider(unavailableClientManager), + statuses: statusMgr, } err := manager.restartRemoteWorkload(context.Background(), tt.workloadName, tt.runConfig, tt.foreground) @@ -809,10 +845,9 @@ func TestDefaultManager_restartContainerWorkload(t *testing.T) { Status: runtime.WorkloadStatusRunning, }, nil) // Check if supervisor is alive - return error (supervisor is dead) - sm.EXPECT().GetWorkloadPID(gomock.Any(), "container-workload").Return(0, errors.New("no PID found")) + sm.EXPECT().GetWorkloadPID(gomock.Any(), "container-workload").Return(0, errors.New("no PID found")).Times(2) // With dead supervisor, restart proceeds with cleanup and restart sm.EXPECT().SetWorkloadStatus(gomock.Any(), "container-workload", runtime.WorkloadStatusStopping, "").Return(nil) - sm.EXPECT().GetWorkloadPID(gomock.Any(), "container-workload").Return(0, errors.New("no PID found")) rm.EXPECT().StopWorkload(gomock.Any(), "container-workload").Return(nil) // Allow any subsequent status updates sm.EXPECT().SetWorkloadStatus(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()).AnyTimes().Return(nil) @@ -855,8 +890,9 @@ func TestDefaultManager_restartContainerWorkload(t *testing.T) { tt.setupMocks(statusMgr, runtimeMgr) manager := &DefaultManager{ - statuses: statusMgr, - runtime: runtimeMgr, + clientManagers: testClientManagerProvider(unavailableClientManager), + statuses: statusMgr, + runtime: runtimeMgr, } err := manager.restartContainerWorkload(context.Background(), tt.workloadName, tt.foreground) @@ -893,7 +929,9 @@ func TestDefaultManager_restartLogicConsistency(t *testing.T) { statusMgr.EXPECT().GetWorkloadPID(gomock.Any(), "test-base").Return(12345, nil) manager := &DefaultManager{ - statuses: statusMgr, + savedRunConfigs: testSavedRunConfigChecker{exists: true}, + clientManagers: testClientManagerProvider(unavailableClientManager), + statuses: statusMgr, } runConfig := &runner.RunConfig{ @@ -925,7 +963,9 @@ func TestDefaultManager_restartLogicConsistency(t *testing.T) { statusMgr.EXPECT().SetWorkloadPID(gomock.Any(), gomock.Any(), gomock.Any()).AnyTimes().Return(nil) manager := &DefaultManager{ - statuses: statusMgr, + savedRunConfigs: testSavedRunConfigChecker{exists: true}, + clientManagers: testClientManagerProvider(unavailableClientManager), + statuses: statusMgr, } runConfig := &runner.RunConfig{ @@ -955,13 +995,14 @@ func TestDefaultManager_restartLogicConsistency(t *testing.T) { statusMgr.EXPECT().GetWorkloadPID(gomock.Any(), "test-base").Return(0, nil) // stopProxyIfNeeded also calls GetWorkloadPID (via stopProcess) statusMgr.EXPECT().GetWorkloadPID(gomock.Any(), "test-base").Return(0, nil) - statusMgr.EXPECT().ResetWorkloadPID(gomock.Any(), "test-base").Return(nil) statusMgr.EXPECT().SetWorkloadStatus(gomock.Any(), "test-workload", runtime.WorkloadStatusStopping, "").Return(nil) statusMgr.EXPECT().SetWorkloadStatus(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()).AnyTimes().Return(nil) statusMgr.EXPECT().SetWorkloadPID(gomock.Any(), gomock.Any(), gomock.Any()).AnyTimes().Return(nil) manager := &DefaultManager{ - statuses: statusMgr, + savedRunConfigs: testSavedRunConfigChecker{exists: true}, + clientManagers: testClientManagerProvider(unavailableClientManager), + statuses: statusMgr, } runConfig := &runner.RunConfig{ @@ -1000,8 +1041,10 @@ func TestDefaultManager_restartLogicConsistency(t *testing.T) { statusMgr.EXPECT().GetWorkloadPID(gomock.Any(), "test-workload").Return(12345, nil) manager := &DefaultManager{ - statuses: statusMgr, - runtime: runtimeMgr, + savedRunConfigs: testSavedRunConfigChecker{exists: true}, + clientManagers: testClientManagerProvider(unavailableClientManager), + statuses: statusMgr, + runtime: runtimeMgr, } err := manager.restartContainerWorkload(context.Background(), "test-workload", false) @@ -1033,11 +1076,10 @@ func TestDefaultManager_restartLogicConsistency(t *testing.T) { }, nil) // Check if supervisor is alive - return error (dead supervisor) - statusMgr.EXPECT().GetWorkloadPID(gomock.Any(), "test-workload").Return(0, errors.New("no PID found")) + statusMgr.EXPECT().GetWorkloadPID(gomock.Any(), "test-workload").Return(0, errors.New("no PID found")).Times(2) // When supervisor is dead, expect stop logic to be called statusMgr.EXPECT().SetWorkloadStatus(gomock.Any(), "test-workload", runtime.WorkloadStatusStopping, "").Return(nil) - statusMgr.EXPECT().GetWorkloadPID(gomock.Any(), "test-workload").Return(0, errors.New("no PID found")) runtimeMgr.EXPECT().StopWorkload(gomock.Any(), "test-workload").Return(nil) // Allow any subsequent status updates (starting, error, etc.) - we don't care about the exact sequence @@ -1045,8 +1087,10 @@ func TestDefaultManager_restartLogicConsistency(t *testing.T) { statusMgr.EXPECT().SetWorkloadPID(gomock.Any(), gomock.Any(), gomock.Any()).AnyTimes().Return(nil) manager := &DefaultManager{ - statuses: statusMgr, - runtime: runtimeMgr, + savedRunConfigs: testSavedRunConfigChecker{exists: true}, + clientManagers: testClientManagerProvider(unavailableClientManager), + statuses: statusMgr, + runtime: runtimeMgr, } _ = manager.restartContainerWorkload(context.Background(), "test-workload", false) @@ -1078,20 +1122,20 @@ func TestDefaultManager_restartLogicConsistency(t *testing.T) { }, nil) // PID 0 with nil error - simulates ResetWorkloadPID setting process_id to 0 - statusMgr.EXPECT().GetWorkloadPID(gomock.Any(), "test-workload").Return(0, nil) + statusMgr.EXPECT().GetWorkloadPID(gomock.Any(), "test-workload").Return(0, nil).Times(2) // When supervisor is treated as dead, expect stop logic statusMgr.EXPECT().SetWorkloadStatus(gomock.Any(), "test-workload", runtime.WorkloadStatusStopping, "").Return(nil) - statusMgr.EXPECT().GetWorkloadPID(gomock.Any(), "test-workload").Return(0, nil) - statusMgr.EXPECT().ResetWorkloadPID(gomock.Any(), "test-workload").Return(nil) runtimeMgr.EXPECT().StopWorkload(gomock.Any(), "test-workload").Return(nil) statusMgr.EXPECT().SetWorkloadStatus(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()).AnyTimes().Return(nil) statusMgr.EXPECT().SetWorkloadPID(gomock.Any(), gomock.Any(), gomock.Any()).AnyTimes().Return(nil) manager := &DefaultManager{ - statuses: statusMgr, - runtime: runtimeMgr, + savedRunConfigs: testSavedRunConfigChecker{exists: true}, + clientManagers: testClientManagerProvider(unavailableClientManager), + statuses: statusMgr, + runtime: runtimeMgr, } _ = manager.restartContainerWorkload(context.Background(), "test-workload", false) @@ -1144,6 +1188,7 @@ func TestDefaultManager_RunWorkload(t *testing.T) { mockStatusMgr := statusMocks.NewMockStatusManager(ctrl) tt.setupMocks(mockStatusMgr) + expectSupervisorPIDCleanup(t, mockStatusMgr, tt.runConfig.BaseName) manager := &DefaultManager{ statuses: mockStatusMgr, @@ -1207,6 +1252,213 @@ func (f *fakeRunnerFactory) factory() mcpRunnerFactory { } } +func expectSupervisorPIDCleanup(t *testing.T, sm *statusMocks.MockStatusManager, name string) { + t.Helper() + sm.EXPECT().ResetWorkloadPIDIfMatch(gomock.Any(), name, os.Getpid()). + DoAndReturn(func(ctx context.Context, _ string, _ int) error { + assert.NoError(t, ctx.Err(), "PID cleanup must survive supervisor cancellation") + _, bounded := ctx.Deadline() + assert.True(t, bounded, "PID cleanup must not wait indefinitely") + return nil + }) +} + +func expectSupervisorCancellationCleanup(t *testing.T, sm *statusMocks.MockStatusManager, name string) { + t.Helper() + // The PID reset happens inside the guarded write; a separate reset first + // would let the guard mistake a replacement's PID-less starting status. + sm.EXPECT().SetWorkloadStoppedIfOwned(gomock.Any(), name, os.Getpid()). + DoAndReturn(func(ctx context.Context, _ string, _ int) error { + assert.NoError(t, ctx.Err(), "status cleanup must survive supervisor cancellation") + _, bounded := ctx.Deadline() + assert.True(t, bounded, "status cleanup must not wait indefinitely") + return nil + }) +} + +func TestDefaultManager_RunWorkload_CancellationInterruptsBackoff(t *testing.T) { + t.Parallel() + + ctrl := gomock.NewController(t) + sm := statusMocks.NewMockStatusManager(ctrl) + const name = "cancel-retrying-supervisor" + restarting := make(chan struct{}) + sm.EXPECT().SetWorkloadStatus(gomock.Any(), name, runtime.WorkloadStatusStarting, "").Return(nil) + sm.EXPECT().SetWorkloadStatus(gomock.Any(), name, runtime.WorkloadStatusStarting, "Container exited, restarting"). + DoAndReturn(func(context.Context, string, runtime.WorkloadStatus, string) error { + close(restarting) + return nil + }) + // No Error status write is allowed after a user requests shutdown. + expectSupervisorCancellationCleanup(t, sm, name) + factory := &fakeRunnerFactory{outcomes: []fakeRunOutcome{{err: runner.ErrContainerExitedRestartNeeded}}} + manager := &DefaultManager{ + clientManagers: testClientManagerProvider(unavailableClientManager), + statuses: sm, + } + withRunnerFactory(factory.factory())(manager) + withRetryConfig(retryConfig{ + maxRetries: 3, initialDelay: 30 * time.Second, + maxBackoff: time.Minute, stableRunThreshold: time.Minute, + })(manager) + ctx, cancel := context.WithCancel(context.Background()) + t.Cleanup(cancel) + done := make(chan error, 1) + go func() { done <- manager.RunWorkload(ctx, &runner.RunConfig{BaseName: name}) }() + select { + case <-restarting: + case <-time.After(5 * time.Second): + t.Fatal("supervisor did not schedule its retry") + } + // The retry status is written just before entering backoff. Leave enough + // time to enter the wait rather than only testing cancellation before it. + select { + case err := <-done: + t.Fatalf("supervisor returned before cancellation: %v", err) + case <-time.After(100 * time.Millisecond): + } + cancel() + select { + case err := <-done: + require.NoError(t, err) + case <-time.After(2 * time.Second): + t.Fatal("cancellation did not interrupt retry backoff") + } + assert.Equal(t, 1, factory.callCount, "shutdown must not start another runner") +} + +func TestDefaultManager_RunWorkload_CancelledSupervisorClearsOnlyItsOwnPID(t *testing.T) { + t.Parallel() + + const name = "replaced-supervisor" + ctrl := gomock.NewController(t) + sm := statusMocks.NewMockStatusManager(ctrl) + // The guarded API must receive this supervisor's PID, never a replacement's + // PID read from storage or an unconditional reset. + expectSupervisorCancellationCleanup(t, sm, name) + manager := &DefaultManager{statuses: sm} + withRunnerFactory(func(*runner.RunConfig, statuses.StatusManager) mcpRunner { + t.Error("cancelled supervisor must not create a runner") + return &fakeRunner{} + })(manager) + ctx, cancel := context.WithCancel(context.Background()) + cancel() + require.NoError(t, manager.RunWorkload(ctx, &runner.RunConfig{BaseName: name})) +} + +func TestDefaultManager_RunWorkload_CancellationPreventsFurtherAttempts(t *testing.T) { + t.Parallel() + + for _, stage := range []string{"initial status", "runner", "restart status"} { + t.Run(stage, func(t *testing.T) { + t.Parallel() + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + t.Cleanup(cancel) + ctrl := gomock.NewController(t) + sm := statusMocks.NewMockStatusManager(ctrl) + const name = "cancel-at-boundary" + sm.EXPECT().SetWorkloadStatus(gomock.Any(), name, runtime.WorkloadStatusStarting, ""). + DoAndReturn(func(context.Context, string, runtime.WorkloadStatus, string) error { + if stage == "initial status" { + cancel() + } + return nil + }) + if stage == "restart status" { + sm.EXPECT().SetWorkloadStatus(gomock.Any(), name, runtime.WorkloadStatusStarting, "Container exited, restarting"). + DoAndReturn(func(context.Context, string, runtime.WorkloadStatus, string) error { + cancel() + return nil + }) + } + expectSupervisorCancellationCleanup(t, sm, name) + attempts := 0 + manager := &DefaultManager{statuses: sm} + manager.clientManagers = testClientManagerProvider(func(context.Context) (client.Manager, error) { + return nil, errors.New("client manager unavailable") + }) + withRunnerFactory(func(*runner.RunConfig, statuses.StatusManager) mcpRunner { + attempts++ + if stage == "runner" { + cancel() + } + return &fakeRunner{err: runner.ErrContainerExitedRestartNeeded} + })(manager) + + require.NoError(t, manager.RunWorkload(ctx, &runner.RunConfig{BaseName: name})) + require.ErrorIs(t, ctx.Err(), context.Canceled) + if stage == "initial status" { + assert.Zero(t, attempts, "shutdown must prevent runner creation") + } else { + assert.Equal(t, 1, attempts, "shutdown must not retry or record a terminal error") + } + }) + } +} + +func TestDefaultManager_RunWorkload_FailureSurvivesStatusAndPIDCleanupErrors(t *testing.T) { + t.Parallel() + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + t.Cleanup(cancel) + ctrl := gomock.NewController(t) + sm := statusMocks.NewMockStatusManager(ctrl) + const name = "failed-supervisor" + runErr := errors.New("runner failed") + storageErr := errors.New("status storage unavailable") + gomock.InOrder( + sm.EXPECT().SetWorkloadStatus(gomock.Any(), name, runtime.WorkloadStatusStarting, "").Return(nil), + sm.EXPECT().SetWorkloadStatus(gomock.Any(), name, runtime.WorkloadStatusError, runErr.Error()).Return(storageErr), + sm.EXPECT().ResetWorkloadPIDIfMatch(gomock.Any(), name, os.Getpid()). + DoAndReturn(func(cleanupCtx context.Context, _ string, _ int) error { + assert.NoError(t, cleanupCtx.Err()) + _, bounded := cleanupCtx.Deadline() + assert.True(t, bounded) + return storageErr + }), + ) + manager := &DefaultManager{statuses: sm} + withRunnerFactory(func(*runner.RunConfig, statuses.StatusManager) mcpRunner { + return &fakeRunner{err: runErr} + })(manager) + + require.ErrorIs(t, manager.RunWorkload(ctx, &runner.RunConfig{BaseName: name}), runErr) +} + +func TestDefaultManager_recordWorkloadRunFailure_CancellationDoesNotOverwriteStatus(t *testing.T) { + t.Parallel() + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + cancel() + manager := &DefaultManager{statuses: statusMocks.NewMockStatusManager(gomock.NewController(t))} + + manager.recordWorkloadRunFailure(ctx, "stopping-supervisor", "runner failed during shutdown") +} + +func TestDefaultManager_RunWorkload_RestartStatusFailureDoesNotConsumeExtraAttempts(t *testing.T) { + t.Parallel() + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + t.Cleanup(cancel) + ctrl := gomock.NewController(t) + sm := statusMocks.NewMockStatusManager(ctrl) + const name = "restart-status-failure" + gomock.InOrder( + sm.EXPECT().SetWorkloadStatus(gomock.Any(), name, runtime.WorkloadStatusStarting, "").Return(nil), + sm.EXPECT().SetWorkloadStatus(gomock.Any(), name, runtime.WorkloadStatusStarting, "Container exited, restarting"). + Return(errors.New("status storage unavailable")), + ) + expectSupervisorPIDCleanup(t, sm, name) + factory := &fakeRunnerFactory{outcomes: []fakeRunOutcome{{err: runner.ErrContainerExitedRestartNeeded}, {}}} + manager := &DefaultManager{statuses: sm} + manager.clientManagers = testClientManagerProvider(func(context.Context) (client.Manager, error) { + return nil, errors.New("client manager unavailable") + }) + withRunnerFactory(factory.factory())(manager) + withRetryConfig(retryConfig{maxRetries: 2, initialDelay: time.Millisecond, + maxBackoff: time.Millisecond, stableRunThreshold: time.Minute})(manager) + + require.NoError(t, manager.RunWorkload(ctx, &runner.RunConfig{BaseName: name})) + assert.Equal(t, 2, factory.callCount) +} + func TestDefaultManager_RunWorkload_RetryCounterReset(t *testing.T) { t.Parallel() @@ -1284,7 +1536,6 @@ func TestDefaultManager_RunWorkload_RetryCounterReset(t *testing.T) { for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { t.Parallel() - ctrl := gomock.NewController(t) defer ctrl.Finish() @@ -1294,8 +1545,12 @@ func TestDefaultManager_RunWorkload_RetryCounterReset(t *testing.T) { Return(nil). AnyTimes() + expectSupervisorPIDCleanup(t, mockStatusMgr, "retry-test") factory := &fakeRunnerFactory{outcomes: tt.outcomes} - manager := &DefaultManager{statuses: mockStatusMgr} + manager := &DefaultManager{ + clientManagers: testClientManagerProvider(unavailableClientManager), + statuses: mockStatusMgr, + } withRetryConfig(testCfg)(manager) withRunnerFactory(factory.factory())(manager) @@ -1505,7 +1760,7 @@ func TestDefaultManager_removeContainer(t *testing.T) { } ctx := context.Background() - err := manager.removeContainer(ctx, tt.workloadName) + err := manager.removeContainer(ctx, tt.workloadName, tt.workloadName) if tt.expectError { require.Error(t, err) @@ -1912,8 +2167,9 @@ func TestDefaultManager_UpdateWorkload(t *testing.T) { } } +//nolint:paralleltest // saved-workload fixtures use t.Setenv func TestDefaultManager_updateSingleWorkload(t *testing.T) { - t.Parallel() + isolateWorkloadStopState(t) // fakeSpawnerPID is the fake PID returned by the test-injected spawner. // It must be > 0 so SetWorkloadPID treats it as a real PID. @@ -1936,7 +2192,7 @@ func TestDefaultManager_updateSingleWorkload(t *testing.T) { name string workloadName string runConfig *runner.RunConfig - setupMocks func(*runtimeMocks.MockRuntime, *statusMocks.MockStatusManager) + setupMocks func(*testing.T, *runtimeMocks.MockRuntime, *statusMocks.MockStatusManager) expectError bool errorMsg string }{ @@ -1948,7 +2204,8 @@ func TestDefaultManager_updateSingleWorkload(t *testing.T) { BaseName: "test-workload", Group: "default", }, - setupMocks: func(rt *runtimeMocks.MockRuntime, sm *statusMocks.MockStatusManager) { + setupMocks: func(t *testing.T, rt *runtimeMocks.MockRuntime, sm *statusMocks.MockStatusManager) { + t.Helper() // Mock the stop operation - return error for GetWorkloadInfo rt.EXPECT().GetWorkloadInfo(gomock.Any(), "test-workload"). Return(runtime.ContainerInfo{}, errors.New("container lookup failed")).AnyTimes() @@ -1967,7 +2224,8 @@ func TestDefaultManager_updateSingleWorkload(t *testing.T) { BaseName: "test-workload", Group: "default", }, - setupMocks: func(rt *runtimeMocks.MockRuntime, sm *statusMocks.MockStatusManager) { + setupMocks: func(t *testing.T, rt *runtimeMocks.MockRuntime, sm *statusMocks.MockStatusManager) { + t.Helper() // Mock stop operation - workload exists and can be stopped rt.EXPECT().GetWorkloadInfo(gomock.Any(), "test-workload"). Return(runtime.ContainerInfo{ @@ -1975,10 +2233,14 @@ func TestDefaultManager_updateSingleWorkload(t *testing.T) { State: "running", Labels: map[string]string{"toolhive-basename": "test-workload"}, }, nil) - // Mock GetWorkloadPID call from stopProcess - sm.EXPECT().GetWorkloadPID(gomock.Any(), "test-workload").Return(1234, nil) + // Stop only an owned proxy child, never an arbitrary host PID. + pid := startVerifiedProxyProcess(t, "test-workload").pid + sm.EXPECT().GetWorkloadPID(gomock.Any(), "test-workload").Return(pid, nil) rt.EXPECT().StopWorkload(gomock.Any(), "test-workload").Return(nil) - sm.EXPECT().ResetWorkloadPID(gomock.Any(), "test-workload").Return(nil) + resetPID := sm.EXPECT().ResetWorkloadPIDIfMatch(gomock.Any(), "test-workload", pid).Return(nil) + // Delete observes the PID already cleared by stop. + sm.EXPECT().GetWorkloadPID(gomock.Any(), "test-workload"). + Return(0, nil).After(resetPID) // Mock delete operation - workload exists and can be deleted rt.EXPECT().GetWorkloadInfo(gomock.Any(), "test-workload"). @@ -2009,7 +2271,8 @@ func TestDefaultManager_updateSingleWorkload(t *testing.T) { BaseName: "test-workload", Group: "default", }, - setupMocks: func(rt *runtimeMocks.MockRuntime, sm *statusMocks.MockStatusManager) { + setupMocks: func(t *testing.T, rt *runtimeMocks.MockRuntime, sm *statusMocks.MockStatusManager) { + t.Helper() // Mock successful stop rt.EXPECT().GetWorkloadInfo(gomock.Any(), "test-workload"). Return(runtime.ContainerInfo{ @@ -2017,10 +2280,14 @@ func TestDefaultManager_updateSingleWorkload(t *testing.T) { State: "running", Labels: map[string]string{"toolhive-basename": "test-workload"}, }, nil) - // Mock GetWorkloadPID call from stopProcess - sm.EXPECT().GetWorkloadPID(gomock.Any(), "test-workload").Return(1234, nil) + // Stop only an owned proxy child, never an arbitrary host PID. + pid := startVerifiedProxyProcess(t, "test-workload").pid + sm.EXPECT().GetWorkloadPID(gomock.Any(), "test-workload").Return(pid, nil) rt.EXPECT().StopWorkload(gomock.Any(), "test-workload").Return(nil) - sm.EXPECT().ResetWorkloadPID(gomock.Any(), "test-workload").Return(nil) + resetPID := sm.EXPECT().ResetWorkloadPIDIfMatch(gomock.Any(), "test-workload", pid).Return(nil) + // Delete observes the PID already cleared by stop. + sm.EXPECT().GetWorkloadPID(gomock.Any(), "test-workload"). + Return(0, nil).After(resetPID) // Mock failed delete rt.EXPECT().GetWorkloadInfo(gomock.Any(), "test-workload"). @@ -2040,7 +2307,6 @@ func TestDefaultManager_updateSingleWorkload(t *testing.T) { for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - t.Parallel() ctx := context.Background() ctrl := gomock.NewController(t) @@ -2051,19 +2317,22 @@ func TestDefaultManager_updateSingleWorkload(t *testing.T) { mockConfigProvider := configMocks.NewMockProvider(ctrl) if tt.setupMocks != nil { - tt.setupMocks(mockRuntime, mockStatusManager) + tt.setupMocks(t, mockRuntime, mockStatusManager) } manager := &DefaultManager{ - runtime: mockRuntime, - statuses: mockStatusManager, - configProvider: mockConfigProvider, + savedRunConfigs: testSavedRunConfigChecker{exists: true}, + clientManagers: testClientManagerProvider(unavailableClientManager), + runtime: mockRuntime, + statuses: mockStatusManager, + configProvider: mockConfigProvider, } // Inject a no-op spawner so RunWorkloadDetached does not re-exec the // test binary. Without this, the real spawn would orphan a child // process that recursively reruns the entire test suite. See #5344. withDetachedSpawner(noopSpawnerFor(mockStatusManager))(manager) + persistStopRunConfig(t, tt.workloadName, tt.runConfig) err := manager.updateSingleWorkload(ctx, tt.workloadName, tt.runConfig) if tt.expectError { @@ -2113,6 +2382,8 @@ func TestDefaultManager_RunWorkload_ContainerExitHandling(t *testing.T) { Group: "default", } + expectSupervisorPIDCleanup(t, mockStatusMgr, runConfig.BaseName) + // RunWorkload will fail because the runner can't actually run // This tests that the status is properly set err := manager.RunWorkload(context.Background(), runConfig) @@ -2264,11 +2535,11 @@ func TestGetRemoteWorkloadsFromState_AuthRetryingVisibleWithoutAll(t *testing.T) } // startKillableProcess starts a real, long-lived child process and returns its -// PID. The process is killed and reaped on test cleanup. It is used to exercise -// the path where stopProcess finds a valid PID and KillProcess succeeds. The +// PID and an exit notification. The process is killed and reaped on test cleanup. It represents an +// unrelated process that must not be killed as a proxy. The // helper relies on the Unix `sleep` command, so it skips on Windows (the CI unit // test matrix is Linux-only) and if the process cannot be started. -func startKillableProcess(t *testing.T) int { +func startKillableProcess(t *testing.T) (int, <-chan struct{}) { t.Helper() if goruntime.GOOS == "windows" { t.Skip("startKillableProcess relies on the Unix sleep command") @@ -2277,18 +2548,825 @@ func startKillableProcess(t *testing.T) int { if err := cmd.Start(); err != nil { t.Skipf("could not start helper process: %v", err) } + exited := make(chan struct{}) + go func() { + _ = cmd.Wait() + close(exited) + }() t.Cleanup(func() { _ = cmd.Process.Kill() - _ = cmd.Wait() + select { + case <-exited: + case <-time.After(5 * time.Second): + t.Error("unrelated helper process was not reaped") + } + }) + return cmd.Process.Pid, exited +} + +func isolateWorkloadStopState(t *testing.T) { + t.Helper() + t.Cleanup(xdg.Reload) + t.Setenv("XDG_STATE_HOME", t.TempDir()) + t.Setenv("XDG_DATA_HOME", t.TempDir()) + t.Setenv("XDG_CONFIG_HOME", t.TempDir()) + xdg.Reload() +} + +func persistStopRunConfig(t *testing.T, name string, rc *runner.RunConfig) { + t.Helper() + copied := *rc + copied.SchemaVersion = runner.CurrentSchemaVersion + if copied.BaseName == "" { + copied.BaseName = name + } + require.NoError(t, copied.SaveState(context.Background())) +} + +type workloadProxyProcess struct { + pid int + port int + exited chan struct{} + waitErr error // Read only after exited is closed by the Wait goroutine. +} + +func TestWorkloadProxyProcess(t *testing.T) { + t.Parallel() + + mode := os.Getenv("TOOLHIVE_TEST_PROXY_HELPER") + if mode == "" { + return + } + terminated := make(chan os.Signal, 1) + if mode == "ignore-term" { + signal.Ignore(syscall.SIGTERM) + } else { + signal.Notify(terminated, syscall.SIGTERM) + } + var listener net.Listener + if mode == "listen" { + var err error + listener, err = net.Listen("tcp4", "127.0.0.1:0") + require.NoError(t, err) + fmt.Printf("ready %d\n", listener.Addr().(*net.TCPAddr).Port) + } else { + fmt.Println("ready") + } + exitCode := 0 + select { + case <-terminated: + case <-time.After(time.Minute): + exitCode = 1 + } + if listener != nil { + require.NoError(t, listener.Close()) + } + os.Exit(exitCode) +} + +func startVerifiedProxyProcess(t *testing.T, name string, args ...string) *workloadProxyProcess { + t.Helper() + return startProxyProcess(t, name, false, args...) +} + +func startProxyProcess(t *testing.T, name string, ignoreSIGTERM bool, args ...string) *workloadProxyProcess { + t.Helper() + return startProxyProcessFixture(t, name, ignoreSIGTERM, false, args...) +} + +func startProxyProcessFixture(t *testing.T, name string, ignoreSIGTERM, listen bool, args ...string) *workloadProxyProcess { + t.Helper() + if goruntime.GOOS == "windows" { + t.Skip("proxy helper requires SIGTERM") + } + executable, err := os.Executable() + require.NoError(t, err) + detached := len(args) == 0 + if detached { + args = []string{"start", name, "--foreground"} + } else { + thv := filepath.Join(t.TempDir(), "thv") + require.NoError(t, os.Symlink(executable, thv)) + executable = thv + } + cmd := exec.Command(executable, append([]string{"-test.run=^TestWorkloadProxyProcess$"}, args...)...) + for _, entry := range os.Environ() { + if !strings.HasPrefix(entry, "TOOLHIVE_DETACHED=") { + cmd.Env = append(cmd.Env, entry) + } + } + mode := "1" + if ignoreSIGTERM { + mode = "ignore-term" + } else if listen { + mode = "listen" + } + cmd.Env = append(cmd.Env, "TOOLHIVE_TEST_PROXY_HELPER="+mode) + if detached { + cmd.Env = append(cmd.Env, "TOOLHIVE_DETACHED=1") + } + stdout, err := cmd.StdoutPipe() + require.NoError(t, err) + require.NoError(t, cmd.Start()) + proxy := &workloadProxyProcess{pid: cmd.Process.Pid, exited: make(chan struct{})} + ready := make(chan string, 1) + go func() { + line, _ := bufio.NewReader(stdout).ReadString('\n') + ready <- line + }() + go func() { + proxy.waitErr = cmd.Wait() + close(proxy.exited) + }() + t.Cleanup(func() { + _ = cmd.Process.Kill() + select { + case <-proxy.exited: + case <-time.After(5 * time.Second): + t.Error("proxy helper was not reaped") + } + }) + select { + case line := <-ready: + if listen { + fields := strings.Fields(line) + require.Len(t, fields, 2) + require.Equal(t, "ready", fields[0]) + proxy.port, err = strconv.Atoi(fields[1]) + require.NoError(t, err) + require.Positive(t, proxy.port) + } else { + require.Equal(t, "ready\n", line) + } + case <-time.After(5 * time.Second): + t.Fatal("proxy helper did not start") + } + verified, err := process.IsToolHiveProxyForWorkload(proxy.pid, name) + require.NoError(t, err) + require.True(t, verified, "helper must satisfy production proxy identity checks") + return proxy +} + +//nolint:paralleltest // t.Setenv is incompatible with t.Parallel +func TestDefaultManager_stopContainerWorkload_ExitedContainerWaitsForTrackedProxy(t *testing.T) { + isolateWorkloadStopState(t) + + for _, tt := range []struct { + name string + startProxy func(*testing.T) *workloadProxyProcess + }{ + { + name: "detached start uses workload base name", + startProxy: func(t *testing.T) *workloadProxyProcess { + t.Helper() + return startVerifiedProxyProcess(t, "requested-container") + }, + }, + { + name: "foreground run without detached environment uses thv binary identity", + startProxy: func(t *testing.T) *workloadProxyProcess { + t.Helper() + return startVerifiedProxyProcess(t, "", "run", "--foreground", "example/server") + }, + }, + } { + t.Run(tt.name, func(t *testing.T) { + proxy := tt.startProxy(t) + ctrl := gomock.NewController(t) + sm := statusMocks.NewMockStatusManager(ctrl) + rtMock := runtimeMocks.NewMockRuntime(ctrl) + rtMock.EXPECT().GetWorkloadInfo(gomock.Any(), "requested-container").Return(runtime.ContainerInfo{ + Name: "requested-container-1730000000", State: "exited", + Labels: map[string]string{labels.LabelBaseName: "requested-container"}, + }, nil) + sm.EXPECT().SetWorkloadStatus(gomock.Any(), "requested-container", runtime.WorkloadStatusStopping, "").Return(nil) + sm.EXPECT().GetWorkloadPID(gomock.Any(), "requested-container").Return(proxy.pid, nil).Times(2) + sm.EXPECT().ResetWorkloadPIDIfMatch(gomock.Any(), "requested-container", proxy.pid).Return(nil) + rtMock.EXPECT().StopWorkload(gomock.Any(), "requested-container-1730000000").DoAndReturn(func(context.Context, string) error { + select { + case <-proxy.exited: + assert.NoError(t, proxy.waitErr, "proxy must handle SIGTERM before runtime stop") + default: + t.Error("runtime stop called before tracked proxy exited") + } + return nil + }) + sm.EXPECT().SetWorkloadStatus(gomock.Any(), "requested-container", runtime.WorkloadStatusStopped, "").Return(nil) + manager := &DefaultManager{ + savedRunConfigs: testSavedRunConfigChecker{exists: true}, + clientManagers: testClientManagerProvider(unavailableClientManager), + statuses: sm, runtime: rtMock, + } + withPortFreer(func(context.Context, *runner.RunConfig) { + t.Error("verified proxy exit must not require port fallback") + })(manager) + + rc := &runner.RunConfig{BaseName: "requested-container", ContainerName: "requested-container-1730000000"} + persistStopRunConfig(t, "requested-container", rc) + require.NoError(t, manager.stopContainerWorkload(context.Background(), "requested-container", rc)) + }) + } +} + +func TestDefaultManager_stopContainerWorkload_MissingContainerUsesSavedLabels(t *testing.T) { + t.Parallel() + + for _, tt := range []struct { + name string + inspectErr error + runConfig *runner.RunConfig + wantContainerName string + }{ + { + name: "saved base fills missing label without mutating config", + runConfig: &runner.RunConfig{ + BaseName: "requested-container", + ContainerName: "requested-container-1730000000", + ContainerLabels: map[string]string{"custom-label": "preserved"}, + }, + wantContainerName: "requested-container-1730000000", + }, + { + name: "saved base label is preserved without mutating config", + runConfig: &runner.RunConfig{ + BaseName: "requested-container", + ContainerName: "requested-container-1730000000", + ContainerLabels: map[string]string{labels.LabelBaseName: "requested-container"}, + }, + wantContainerName: "requested-container-1730000000", + }, + { + name: "wrapped container not found still stops saved container", + inspectErr: fmt.Errorf("inspect: %w", runtime.ErrContainerNotFound), + runConfig: &runner.RunConfig{BaseName: "requested-container", ContainerName: "requested-container-1730000000"}, + wantContainerName: "requested-container-1730000000", + }, + { + name: "missing saved container name falls back to workload base", + runConfig: &runner.RunConfig{BaseName: "requested-container"}, + wantContainerName: "requested-container", + }, + } { + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + + original := *tt.runConfig + original.ContainerLabels = maps.Clone(tt.runConfig.ContainerLabels) + ctrl := gomock.NewController(t) + sm := statusMocks.NewMockStatusManager(ctrl) + rtMock := runtimeMocks.NewMockRuntime(ctrl) + inspectErr := tt.inspectErr + if inspectErr == nil { + inspectErr = fmt.Errorf("inspect: %w", runtime.ErrWorkloadNotFound) + } + rtMock.EXPECT().GetWorkloadInfo(gomock.Any(), "requested-container").Return(runtime.ContainerInfo{}, inspectErr) + + sm.EXPECT().GetWorkloadPID(gomock.Any(), "requested-container").Return(0, runtime.ErrWorkloadNotFound).Times(2) + fallbackCalls := 0 + rtMock.EXPECT().StopWorkload(gomock.Any(), tt.wantContainerName).DoAndReturn(func(context.Context, string) error { + assert.Equal(t, 1, fallbackCalls, "proxy cleanup must precede the fresh runtime stop") + return nil + }) + + manager := &DefaultManager{ + savedRunConfigs: testSavedRunConfigChecker{exists: true}, + statuses: sm, runtime: rtMock, + } + withPortFreer(func(_ context.Context, rc *runner.RunConfig) { + assert.Same(t, tt.runConfig, rc) + fallbackCalls++ + })(manager) + + require.NoError(t, manager.stopContainerWorkload(context.Background(), "requested-container", tt.runConfig)) + assert.Equal(t, &original, tt.runConfig) + }) + } +} + +func TestDefaultManager_stopContainerWorkload_MissingConfigStopsTrackedProxyWithoutStatusWrites(t *testing.T) { + t.Parallel() + + const name = "missing-container" + proxy := startVerifiedProxyProcess(t, name) + ctrl := gomock.NewController(t) + sm := statusMocks.NewMockStatusManager(ctrl) + rtMock := runtimeMocks.NewMockRuntime(ctrl) + rtMock.EXPECT().GetWorkloadInfo(gomock.Any(), name).Return(runtime.ContainerInfo{}, runtime.ErrWorkloadNotFound) + sm.EXPECT().GetWorkloadPID(gomock.Any(), name).Return(proxy.pid, nil) + sm.EXPECT().ResetWorkloadPIDIfMatch(gomock.Any(), name, proxy.pid).Return(nil) + rtMock.EXPECT().StopWorkload(gomock.Any(), name).DoAndReturn(func(context.Context, string) error { + select { + case <-proxy.exited: + assert.NoError(t, proxy.waitErr) + default: + t.Error("runtime stop called before tracked proxy exited") + } + return nil }) - return cmd.Process.Pid + manager := &DefaultManager{statuses: sm, runtime: rtMock} + + require.NoError(t, manager.stopContainerWorkload(context.Background(), name, nil)) +} + +func TestDefaultManager_stopContainerWorkload_InspectionFailureDoesNotStopProxy(t *testing.T) { + t.Parallel() + + ctrl := gomock.NewController(t) + sm := statusMocks.NewMockStatusManager(ctrl) + rtMock := runtimeMocks.NewMockRuntime(ctrl) + inspectErr := errors.New("runtime inspection failed") + rtMock.EXPECT().GetWorkloadInfo(gomock.Any(), "container").Return(runtime.ContainerInfo{}, inspectErr) + manager := &DefaultManager{statuses: sm, runtime: rtMock} + + require.ErrorIs(t, manager.stopContainerWorkload(context.Background(), "container", + &runner.RunConfig{BaseName: "saved-base"}), inspectErr) +} + +func TestDefaultManager_stopContainerWorkload_RuntimeStopFailureRecordsErrorAfterProxyCleanup(t *testing.T) { + t.Parallel() + + ctrl := gomock.NewController(t) + sm := statusMocks.NewMockStatusManager(ctrl) + rtMock := runtimeMocks.NewMockRuntime(ctrl) + stopErr := errors.New("runtime stop failed") + rtMock.EXPECT().GetWorkloadInfo(gomock.Any(), "container").Return(runtime.ContainerInfo{}, runtime.ErrWorkloadNotFound) + + sm.EXPECT().GetWorkloadPID(gomock.Any(), "container").Return(0, runtime.ErrWorkloadNotFound).Times(2) + cleanupComplete := false + rtMock.EXPECT().StopWorkload(gomock.Any(), "container").DoAndReturn(func(context.Context, string) error { + assert.True(t, cleanupComplete, "runtime stop must follow proxy cleanup even on failure") + return stopErr + }) + sm.EXPECT().SetWorkloadStatus(gomock.Any(), "container", runtime.WorkloadStatusError, stopErr.Error()). + Return(errors.New("status storage unavailable")) + manager := &DefaultManager{ + savedRunConfigs: testSavedRunConfigChecker{exists: true}, + statuses: sm, runtime: rtMock, + } + withPortFreer(func(context.Context, *runner.RunConfig) { cleanupComplete = true })(manager) + + rc := &runner.RunConfig{BaseName: "container"} + + require.ErrorIs(t, manager.stopContainerWorkload(context.Background(), "container", rc), stopErr) +} + +func TestDefaultManager_stopContainerWorkload_MissingConfigPropagatesRuntimeStopFailure(t *testing.T) { + t.Parallel() + + ctrl := gomock.NewController(t) + sm := statusMocks.NewMockStatusManager(ctrl) + rtMock := runtimeMocks.NewMockRuntime(ctrl) + stopErr := errors.New("runtime stop failed") + rtMock.EXPECT().GetWorkloadInfo(gomock.Any(), "container").Return(runtime.ContainerInfo{}, runtime.ErrWorkloadNotFound) + sm.EXPECT().GetWorkloadPID(gomock.Any(), "container").Return(0, runtime.ErrWorkloadNotFound) + rtMock.EXPECT().StopWorkload(gomock.Any(), "container").Return(stopErr) + manager := &DefaultManager{statuses: sm, runtime: rtMock} + + require.ErrorIs(t, manager.stopContainerWorkload(context.Background(), "container", nil), stopErr) +} + +func TestDefaultManager_stopContainerWorkload_InactivePreservesStatusAndClients(t *testing.T) { + t.Parallel() + + for _, status := range []runtime.WorkloadStatus{runtime.WorkloadStatusError, runtime.WorkloadStatusPolicyStopped} { + for _, tt := range []struct { + name string + missing bool + stalePID bool + }{ + {name: "exited"}, + {name: "missing", missing: true}, + {name: "exited with reaped supervisor", stalePID: true}, + } { + t.Run(fmt.Sprintf("%s/%s", status, tt.name), func(t *testing.T) { + t.Parallel() + const name = "inactive-workload" + const containerName = "inactive-workload-20260101" + ctrl := gomock.NewController(t) + sm := statusMocks.NewMockStatusManager(ctrl) + rtMock := runtimeMocks.NewMockRuntime(ctrl) + cm := clientMocks.NewMockManager(ctrl) + previous := core.Workload{Name: name, Status: status, StatusContext: "original failure or policy decision"} + sm.EXPECT().GetWorkload(gomock.Any(), name).Return(previous, nil).AnyTimes() + pid := 0 + if tt.stalePID { + var exited <-chan struct{} + pid, exited = startKillableProcess(t) + child, err := os.FindProcess(pid) + require.NoError(t, err) + require.NoError(t, child.Kill()) + require.NoError(t, child.Release()) + select { + case <-exited: + case <-time.After(5 * time.Second): + t.Fatal("stale supervisor fixture was not reaped") + } + sm.EXPECT().ResetWorkloadPIDIfMatch(gomock.Any(), name, pid).Return(nil) + } + sm.EXPECT().GetWorkloadPID(gomock.Any(), name).Return(pid, nil).Times(2) + if tt.missing { + rtMock.EXPECT().GetWorkloadInfo(gomock.Any(), name).Return(runtime.ContainerInfo{}, runtime.ErrWorkloadNotFound) + } else { + rtMock.EXPECT().GetWorkloadInfo(gomock.Any(), name).Return(runtime.ContainerInfo{ + Name: containerName, State: "exited", Labels: map[string]string{labels.LabelBaseName: name}, + }, nil) + } + rc := &runner.RunConfig{BaseName: name, ContainerName: containerName} + manager := &DefaultManager{ + runtime: rtMock, + statuses: sm, + savedRunConfigs: testSavedRunConfigChecker{exists: true}, + clientManagers: testClientManagerProvider(func(context.Context) (client.Manager, error) { + return cm, nil + }), + } + fallbackCalls := 0 + withPortFreer(func(_ context.Context, got *runner.RunConfig) { + assert.Same(t, rc, got) + fallbackCalls++ + })(manager) + rtMock.EXPECT().StopWorkload(gomock.Any(), containerName).DoAndReturn(func(context.Context, string) error { + assert.Equal(t, 1, fallbackCalls, "orphan cleanup must precede the runtime stop") + return nil + }) + + require.NoError(t, manager.stopContainerWorkload(context.Background(), name, rc)) + assert.Equal(t, 1, fallbackCalls) + }) + } + } +} + +func TestDefaultManager_maybeSetupContainerWorkload_ForegroundRunKeepsOwnership(t *testing.T) { + t.Parallel() + const name = "foreground-restart-backoff" + proxy := startVerifiedProxyProcess(t, "", "run", "--foreground", "--name", name, "example/server") + ctrl := gomock.NewController(t) + rtMock := runtimeMocks.NewMockRuntime(ctrl) + sm := statusMocks.NewMockStatusManager(ctrl) + rtMock.EXPECT().GetWorkloadInfo(gomock.Any(), name).Return(runtime.ContainerInfo{ + Name: name, State: "exited", Labels: map[string]string{labels.LabelBaseName: name}, + }, nil) + sm.EXPECT().GetWorkload(gomock.Any(), name).Return(core.Workload{ + Name: name, Status: runtime.WorkloadStatusStarting, + }, nil) + sm.EXPECT().GetWorkloadPID(gomock.Any(), name).Return(proxy.pid, nil) + manager := &DefaultManager{runtime: rtMock, statuses: sm} + + gotName, gotRunner, err := manager.maybeSetupContainerWorkload(context.Background(), name) + require.NoError(t, err) + assert.Empty(t, gotName) + assert.Nil(t, gotRunner) + select { + case <-proxy.exited: + t.Error("foreground run must retain ownership during restart backoff") + default: + } +} + +//nolint:paralleltest // runner setup loads saved state +func TestDefaultManager_maybeSetupContainerWorkload_StartingSupervisor(t *testing.T) { + isolateWorkloadStopState(t) + for _, ownPID := range []bool{false, true} { + t.Run(fmt.Sprintf("ownPID=%t", ownPID), func(t *testing.T) { + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + t.Cleanup(cancel) + const name = "restart-backoff-workload" + rc := &runner.RunConfig{BaseName: name, ContainerName: name + "-20260101"} + persistStopRunConfig(t, name, rc) + pid := os.Getpid() + var proxy *workloadProxyProcess + if !ownPID { + proxy = startVerifiedProxyProcess(t, name) + pid = proxy.pid + } + ctrl := gomock.NewController(t) + rtMock := runtimeMocks.NewMockRuntime(ctrl) + sm := statusMocks.NewMockStatusManager(ctrl) + rtMock.EXPECT().GetWorkloadInfo(gomock.Any(), name).Return(runtime.ContainerInfo{ + Name: rc.ContainerName, State: "exited", Labels: map[string]string{labels.LabelBaseName: name}, + }, nil) + sm.EXPECT().GetWorkload(gomock.Any(), name).Return(core.Workload{Name: name, Status: runtime.WorkloadStatusStarting}, nil) + pidCall := sm.EXPECT().GetWorkloadPID(gomock.Any(), name).Return(pid, nil) + if !ownPID { + pidCall.Times(2) + sm.EXPECT().ResetWorkloadPIDIfMatch(gomock.Any(), name, pid).Return(nil) + } + sm.EXPECT().SetWorkloadStatus(gomock.Any(), name, runtime.WorkloadStatusStarting, ""). + DoAndReturn(func(context.Context, string, runtime.WorkloadStatus, string) error { + if proxy != nil { + select { + case <-proxy.exited: + assert.NoError(t, proxy.waitErr, "the previous supervisor must exit gracefully before restart") + default: + t.Error("restart became ready to spawn while its previous supervisor was alive") + } + } + return nil + }) + manager := &DefaultManager{runtime: rtMock, statuses: sm} + + gotName, gotRunner, err := manager.maybeSetupContainerWorkload(ctx, name) + require.NoError(t, err) + assert.Equal(t, name, gotName) + require.NotNil(t, gotRunner) + }) + } +} + +//nolint:paralleltest // t.Setenv is incompatible with t.Parallel +func TestDefaultManager_StopWorkloads_MissingContainerStopsSavedContainerNameAndPreservesConfig(t *testing.T) { + isolateWorkloadStopState(t) + + ctx := context.Background() + const name = "missing-container" + runConfig := &runner.RunConfig{ + SchemaVersion: runner.CurrentSchemaVersion, + Name: "saved-container-name", + ContainerName: "saved-container-name-1730000000", + BaseName: name, + ContainerLabels: map[string]string{"custom-label": "preserved"}, + Transport: types.TransportTypeStreamableHTTP, + Group: "default", + } + require.NoError(t, runConfig.SaveState(ctx)) + before, err := runner.LoadState(ctx, name) + require.NoError(t, err) + + ctrl := gomock.NewController(t) + sm := statusMocks.NewMockStatusManager(ctrl) + rtMock := runtimeMocks.NewMockRuntime(ctrl) + rtMock.EXPECT().GetWorkloadInfo(gomock.Any(), name).Return(runtime.ContainerInfo{}, runtime.ErrWorkloadNotFound) + + sm.EXPECT().GetWorkloadPID(gomock.Any(), name).Return(0, runtime.ErrWorkloadNotFound).Times(2) + + cleanupComplete := false + rtMock.EXPECT().StopWorkload(gomock.Any(), runConfig.ContainerName).DoAndReturn(func(context.Context, string) error { + assert.True(t, cleanupComplete) + return nil + }) + manager := &DefaultManager{ + savedRunConfigs: testSavedRunConfigChecker{exists: true}, + statuses: sm, runtime: rtMock, + } + withPortFreer(func(_ context.Context, rc *runner.RunConfig) { + assert.Equal(t, before, rc) + cleanupComplete = true + })(manager) + + complete, err := manager.StopWorkloads(ctx, []string{name}) + require.NoError(t, err) + require.NoError(t, complete()) + after, err := runner.LoadState(ctx, name) + require.NoError(t, err) + assert.Equal(t, before, after) +} + +//nolint:paralleltest // saved-workload fixtures use t.Setenv +func TestDefaultManager_StopWorkload_ForegroundDeletionIsNotResurrected(t *testing.T) { + isolateWorkloadStopState(t) + + for _, kind := range []string{"container", "remote"} { + remote := kind == "remote" + t.Run(kind, func(t *testing.T) { + ctx := context.Background() + name := "deleted-foreground-" + kind + rc := &runner.RunConfig{BaseName: name, ContainerName: name} + if remote { + rc.RemoteURL = "https://example.com/mcp" + } + persistStopRunConfig(t, name, rc) + store, err := state.NewRunConfigStore(state.DefaultAppName) + require.NoError(t, err) + ctrl := gomock.NewController(t) + rtMock := runtimeMocks.NewMockRuntime(ctrl) + fileStatuses, err := statuses.NewFileStatusManager(rtMock) + require.NoError(t, err) + require.NoError(t, fileStatuses.SetWorkloadStatus(ctx, name, runtime.WorkloadStatusRunning, "")) + proxy := startVerifiedProxyProcess(t, "", "run", "--foreground", "example/server") + require.NoError(t, fileStatuses.SetWorkloadPID(ctx, name, proxy.pid)) + statusPath := filepath.Join(xdg.DataHome, "toolhive", "statuses", name+".json") + sm := statusMocks.NewMockStatusManager(ctrl) + if remote { + sm.EXPECT().GetWorkload(gomock.Any(), name).Return(core.Workload{ + Name: name, Status: runtime.WorkloadStatusRunning, + }, nil) + } else { + sm.EXPECT().GetWorkloadPID(gomock.Any(), name).Return(proxy.pid, nil) + rtMock.EXPECT().GetWorkloadInfo(gomock.Any(), name).Return(runtime.ContainerInfo{ + Name: name, State: "exited", Labels: map[string]string{labels.LabelBaseName: name}, + }, nil) + rtMock.EXPECT().StopWorkload(gomock.Any(), name).DoAndReturn(func(context.Context, string) error { + select { + case <-proxy.exited: + assert.NoError(t, proxy.waitErr) + default: + t.Error("runtime stop preceded foreground supervisor exit") + } + return nil + }) + } + // Only Stopping is permitted: neither path may write Stopped after deletion. + sm.EXPECT().SetWorkloadStatus(gomock.Any(), name, runtime.WorkloadStatusStopping, ""). + DoAndReturn(fileStatuses.SetWorkloadStatus) + sm.EXPECT().GetWorkloadPID(gomock.Any(), name). + DoAndReturn(func(ctx context.Context, name string) (int, error) { + pid, err := fileStatuses.GetWorkloadPID(ctx, name) + require.NoError(t, err) + // Model the owner deleting both files before exit, not during the + // later runtime stop. PID reset must tolerate the deleted status. + require.NoError(t, store.Delete(ctx, name)) + require.NoError(t, fileStatuses.DeleteWorkloadStatus(ctx, name)) + return pid, nil + }) + sm.EXPECT().ResetWorkloadPIDIfMatch(gomock.Any(), name, proxy.pid). + DoAndReturn(func(ctx context.Context, name string, pid int) error { + _, err := os.Stat(statusPath) + require.ErrorIs(t, err, os.ErrNotExist, "owner deletion must precede guarded PID reset") + return fileStatuses.ResetWorkloadPIDIfMatch(ctx, name, pid) + }) + manager := &DefaultManager{ + clientManagers: testClientManagerProvider(unavailableClientManager), + savedRunConfigs: defaultSavedRunConfigChecker{}, + runtime: rtMock, + statuses: sm, + } + withPortFreer(func(context.Context, *runner.RunConfig) { + t.Error("foreground exit must not require port fallback") + })(manager) + + if remote { + require.NoError(t, manager.stopRemoteWorkload(ctx, name, rc)) + } else { + require.NoError(t, manager.stopContainerWorkload(ctx, name, rc)) + } + exists, err := store.Exists(ctx, name) + require.NoError(t, err) + assert.False(t, exists, "stop must not recreate a deleted foreground run config") + _, err = os.Stat(statusPath) + assert.ErrorIs(t, err, os.ErrNotExist, "stop must not recreate status after foreground deletion") + }) + } +} + +//nolint:paralleltest // client configuration cleanup loads saved state +func TestDefaultManager_stopRemoteWorkload_LiveProxyStatusesEndStopped(t *testing.T) { + isolateWorkloadStopState(t) + for _, status := range []runtime.WorkloadStatus{ + runtime.WorkloadStatusStarting, + runtime.WorkloadStatusAuthRetrying, + runtime.WorkloadStatusUnauthenticated, + runtime.WorkloadStatusUnhealthy, + } { + t.Run(string(status), func(t *testing.T) { + const name = "remote-retry-backoff" + rc := &runner.RunConfig{BaseName: name, RemoteURL: "https://example.com/mcp"} + + proxy := startVerifiedProxyProcess(t, name) + ctrl := gomock.NewController(t) + sm := statusMocks.NewMockStatusManager(ctrl) + gomock.InOrder( + sm.EXPECT().GetWorkload(gomock.Any(), name).Return(core.Workload{ + Name: name, Status: status, + }, nil), + sm.EXPECT().SetWorkloadStatus(gomock.Any(), name, runtime.WorkloadStatusStopping, "").Return(nil), + sm.EXPECT().GetWorkloadPID(gomock.Any(), name).Return(proxy.pid, nil), + sm.EXPECT().ResetWorkloadPIDIfMatch(gomock.Any(), name, proxy.pid).Return(nil), + sm.EXPECT().SetWorkloadStatus(gomock.Any(), name, runtime.WorkloadStatusStopped, "").Return(nil), + ) + manager := &DefaultManager{ + savedRunConfigs: testSavedRunConfigChecker{exists: true}, + clientManagers: testClientManagerProvider(unavailableClientManager), + statuses: sm, + } + withPortFreer(func(context.Context, *runner.RunConfig) { t.Error("tracked supervisor exit must not need fallback") })(manager) + + require.NoError(t, manager.stopRemoteWorkload(context.Background(), name, rc)) + select { + case <-proxy.exited: + assert.NoError(t, proxy.waitErr) + default: + t.Error("remote stop returned while supervisor was still alive") + } + }) + } +} + +//nolint:paralleltest // client configuration cleanup loads saved state +func TestDefaultManager_stopRemoteWorkload_StatusWriteFailuresDoNotSkipProxyCleanup(t *testing.T) { + isolateWorkloadStopState(t) + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + t.Cleanup(cancel) + const name = "remote-status-failure" + rc := &runner.RunConfig{BaseName: name, RemoteURL: "https://example.com/mcp"} + + ctrl := gomock.NewController(t) + sm := statusMocks.NewMockStatusManager(ctrl) + storageErr := errors.New("status storage unavailable") + fallbackCalls := 0 + gomock.InOrder( + sm.EXPECT().GetWorkload(gomock.Any(), name).Return(core.Workload{Status: runtime.WorkloadStatusRunning}, nil), + sm.EXPECT().SetWorkloadStatus(gomock.Any(), name, runtime.WorkloadStatusStopping, "").Return(storageErr), + sm.EXPECT().GetWorkloadPID(gomock.Any(), name).Return(0, nil), + sm.EXPECT().SetWorkloadStatus(gomock.Any(), name, runtime.WorkloadStatusStopped, ""). + DoAndReturn(func(context.Context, string, runtime.WorkloadStatus, string) error { + assert.Equal(t, 1, fallbackCalls, "proxy cleanup must precede the final status write") + return storageErr + }), + ) + manager := &DefaultManager{ + savedRunConfigs: testSavedRunConfigChecker{exists: true}, + clientManagers: testClientManagerProvider(unavailableClientManager), + statuses: sm, + } + withPortFreer(func(context.Context, *runner.RunConfig) { fallbackCalls++ })(manager) + + require.NoError(t, manager.stopRemoteWorkload(ctx, name, rc)) + assert.Equal(t, 1, fallbackCalls) +} + +func TestDefaultManager_stopRemoteWorkload_StoppedStatusStillCleansUpProxy(t *testing.T) { + t.Parallel() + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + t.Cleanup(cancel) + const name = "already-stopped-remote" + ctrl := gomock.NewController(t) + sm := statusMocks.NewMockStatusManager(ctrl) + sm.EXPECT().GetWorkload(gomock.Any(), name).Return(core.Workload{Status: runtime.WorkloadStatusStopped}, nil) + sm.EXPECT().GetWorkloadPID(gomock.Any(), name).Return(0, nil) + manager := &DefaultManager{statuses: sm} + rc := &runner.RunConfig{BaseName: name} + fallbackCalls := 0 + withPortFreer(func(_ context.Context, got *runner.RunConfig) { + assert.Same(t, rc, got) + fallbackCalls++ + })(manager) + + require.NoError(t, manager.stopRemoteWorkload(ctx, name, rc)) + assert.Equal(t, 1, fallbackCalls, "stale status must not suppress orphan cleanup or create new status") +} + +func TestDefaultManager_finishRemoteWorkloadStop_StateCheckFailureDoesNotWriteStopped(t *testing.T) { + t.Parallel() + checkErr := errors.New("state store unavailable") + manager := &DefaultManager{ + statuses: statusMocks.NewMockStatusManager(gomock.NewController(t)), + savedRunConfigs: testSavedRunConfigChecker{err: checkErr}, + } + err := manager.finishRemoteWorkloadStop(context.Background(), "remote", &runner.RunConfig{BaseName: "remote"}) + require.ErrorIs(t, err, checkErr) +} + +func TestDefaultManager_stopContainerWorkload_StateCheckFailurePreservesRuntimeError(t *testing.T) { + t.Parallel() + const name = "failed-state-check" + rc := &runner.RunConfig{BaseName: name} + ctrl := gomock.NewController(t) + rtMock := runtimeMocks.NewMockRuntime(ctrl) + sm := statusMocks.NewMockStatusManager(ctrl) + stopErr := errors.New("runtime stop failed") + checkErr := errors.New("state store unavailable") + rtMock.EXPECT().GetWorkloadInfo(gomock.Any(), name).Return(runtime.ContainerInfo{}, runtime.ErrWorkloadNotFound) + sm.EXPECT().GetWorkloadPID(gomock.Any(), name).Return(0, nil).Times(2) + rtMock.EXPECT().StopWorkload(gomock.Any(), name).Return(stopErr) + manager := &DefaultManager{ + statuses: sm, + runtime: rtMock, + savedRunConfigs: testSavedRunConfigChecker{err: checkErr}, + } + withPortFreer(func(context.Context, *runner.RunConfig) {})(manager) + err := manager.stopContainerWorkload(context.Background(), name, rc) + require.ErrorIs(t, err, stopErr) + require.ErrorIs(t, err, checkErr) + assert.Contains(t, err.Error(), "failed to check saved workload after stop") +} + +//nolint:paralleltest // client configuration cleanup loads saved state +func TestDefaultManager_stopSingleContainerWorkload_AuxiliaryNeedsNoSavedStateOrProxy(t *testing.T) { + isolateWorkloadStopState(t) + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + t.Cleanup(cancel) + const name = "inspector" + ctrl := gomock.NewController(t) + rtMock := runtimeMocks.NewMockRuntime(ctrl) + sm := statusMocks.NewMockStatusManager(ctrl) + gomock.InOrder( + rtMock.EXPECT().StopWorkload(gomock.Any(), name).Return(nil), + sm.EXPECT().SetWorkloadStatus(gomock.Any(), name, runtime.WorkloadStatusStopped, "").Return(nil), + ) + manager := &DefaultManager{ + clientManagers: testClientManagerProvider(unavailableClientManager), + runtime: rtMock, + statuses: sm, + } + withPortFreer(func(context.Context, *runner.RunConfig) { t.Error("auxiliary workload must not clean up a proxy") })(manager) + workload := &runtime.ContainerInfo{Name: name, Labels: map[string]string{ + labels.LabelBaseName: name, labels.LabelAuxiliary: "true", + }} + + require.NoError(t, manager.stopSingleContainerWorkload(ctx, workload, &runner.RunConfig{BaseName: name}, true)) } -// TestDefaultManager_stopProcess verifies the boolean contract that the -// stop/delete port-cleanup fallback relies on: stopProcess reports true only -// when it found a tracked PID and killed it. A false return (no PID recorded — -// e.g. a missing status file — or a failed kill) is what triggers the -// port-based cleanup fallback in stopSingleContainerWorkload/deleteContainerWorkload. func TestDefaultManager_stopProcess(t *testing.T) { t.Parallel() @@ -2296,45 +3374,56 @@ func TestDefaultManager_stopProcess(t *testing.T) { name string workload string setupMocks func(t *testing.T, sm *statusMocks.MockStatusManager) - want bool + want proxyStopResult }{ { - name: "empty name returns false", + name: "empty name returns not stopped", workload: "", setupMocks: func(_ *testing.T, _ *statusMocks.MockStatusManager) { // No status manager calls expected for an empty name. }, - want: false, + want: proxyNotStopped, }, { - name: "GetWorkloadPID error returns false", + name: "GetWorkloadPID error returns not stopped", workload: "test-workload", setupMocks: func(_ *testing.T, sm *statusMocks.MockStatusManager) { sm.EXPECT().GetWorkloadPID(gomock.Any(), "test-workload").Return(0, errors.New("boom")) }, - want: false, + want: proxyNotStopped, }, { - name: "missing status file (pid 0) returns false", + name: "missing status file (pid 0) returns not stopped", workload: "test-workload", setupMocks: func(_ *testing.T, sm *statusMocks.MockStatusManager) { - // A missing status file yields PID 0 with no error; KillProcess(0) fails, - // so no proxy is stopped. The PID is still reset. + // A missing status file yields PID 0 with no error; identity validation + // rejects it without a PID update. sm.EXPECT().GetWorkloadPID(gomock.Any(), "test-workload").Return(0, nil) - sm.EXPECT().ResetWorkloadPID(gomock.Any(), "test-workload").Return(nil) }, - want: false, + want: proxyNotStopped, }, { - name: "valid running PID returns true", + name: "verified proxy exit succeeds even when PID reset fails", workload: "test-workload", setupMocks: func(t *testing.T, sm *statusMocks.MockStatusManager) { t.Helper() - pid := startKillableProcess(t) + pid := startVerifiedProxyProcess(t, "test-workload").pid sm.EXPECT().GetWorkloadPID(gomock.Any(), "test-workload").Return(pid, nil) - sm.EXPECT().ResetWorkloadPID(gomock.Any(), "test-workload").Return(nil) + sm.EXPECT().ResetWorkloadPIDIfMatch(gomock.Any(), "test-workload", pid). + Return(errors.New("status storage unavailable")) }, - want: true, + want: proxyStopped, + }, + { + name: "live PID that cannot be inspected is reported, not ignored", + workload: "test-workload", + setupMocks: func(t *testing.T, sm *statusMocks.MockStatusManager) { + t.Helper() + pid := unverifiableSupervisorPID(t, "test-workload") + // No reset: the process may still be the supervisor. + sm.EXPECT().GetWorkloadPID(gomock.Any(), "test-workload").Return(pid, nil) + }, + want: proxyUnverifiable, }, } @@ -2350,20 +3439,169 @@ func TestDefaultManager_stopProcess(t *testing.T) { manager := &DefaultManager{statuses: sm} - got := manager.stopProcess(context.Background(), tt.workload) + got := manager.stopProcess(context.Background(), tt.workload, false) assert.Equal(t, tt.want, got) }) } } +func TestDefaultManager_ensureProxyStopped_ExitedPIDCleanupFailureStillFallsBack(t *testing.T) { + t.Parallel() + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + t.Cleanup(cancel) + pid, exited := startKillableProcess(t) + child, err := os.FindProcess(pid) + require.NoError(t, err) + require.NoError(t, child.Kill()) + select { + case <-exited: + case <-ctx.Done(): + t.Fatal("child was not reaped before stale PID cleanup") + } + ctrl := gomock.NewController(t) + sm := statusMocks.NewMockStatusManager(ctrl) + const name = "already-exited-proxy" + sm.EXPECT().GetWorkloadPID(gomock.Any(), name).Return(pid, nil) + sm.EXPECT().ResetWorkloadPIDIfMatch(gomock.Any(), name, pid). + Return(errors.New("status storage unavailable")) + manager := &DefaultManager{statuses: sm} + fallbackCalls := 0 + withPortFreer(func(context.Context, *runner.RunConfig) { fallbackCalls++ })(manager) + + manager.ensureProxyStopped(ctx, name, name, &runner.RunConfig{BaseName: name}, false) + assert.Equal(t, 1, fallbackCalls, "clearing a stale PID is not proof that the port is free") +} + +func TestDefaultManager_ensureProxyStopped_UnverifiedLivePIDIsPreservedWithoutSignaling(t *testing.T) { + t.Parallel() + + for _, tt := range []struct { + name string + start func(*testing.T) (int, <-chan struct{}) + }{ + {name: "unrelated executable", start: startKillableProcess}, + {name: "detached supervisor of hyphen-suffixed workload", start: func(t *testing.T) (int, <-chan struct{}) { + t.Helper() + proxy := startVerifiedProxyProcess(t, "github-extra") + return proxy.pid, proxy.exited + }}, + } { + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + const name = "github" + pid, exited := tt.start(t) + ctrl := gomock.NewController(t) + sm := statusMocks.NewMockStatusManager(ctrl) + sm.EXPECT().GetWorkloadPID(gomock.Any(), name).Return(pid, nil) + // No reset expectation: a live process that is not this workload's + // supervisor must remain tracked. + manager := &DefaultManager{statuses: sm} + rc := &runner.RunConfig{BaseName: name, Port: 54321} + fallbackCalls := 0 + withPortFreer(func(_ context.Context, got *runner.RunConfig) { + assert.Same(t, rc, got) + fallbackCalls++ + })(manager) + + result := manager.ensureProxyStopped(context.Background(), name, name, rc, false) + assert.Equal(t, proxyNotStopped, result, "an inspected foreign process must not block stop or delete") + assert.Equal(t, 1, fallbackCalls, "unverified PID must not suppress port cleanup") + select { + case <-exited: + t.Error("unverified live process was terminated") + case <-time.After(100 * time.Millisecond): + } + }) + } +} + +func TestDefaultManager_ensureProxyStopped_ExitTimeoutPreservesVerifiedPIDWithoutFallback(t *testing.T) { + t.Parallel() + + const name = "slow-shutdown-supervisor" + proxy := startProxyProcess(t, name, true) + ctrl := gomock.NewController(t) + sm := statusMocks.NewMockStatusManager(ctrl) + sm.EXPECT().GetWorkloadPID(gomock.Any(), name).Return(proxy.pid, nil) + // No reset expectation: timeout must not drop the only supervisor handle. + manager := &DefaultManager{statuses: sm} + withProxyExitTimeout(100 * time.Millisecond)(manager) + runConfig := &runner.RunConfig{BaseName: name, Port: 54321} + fallbackCalls := 0 + withPortFreer(func(_ context.Context, rc *runner.RunConfig) { + assert.Same(t, runConfig, rc) + fallbackCalls++ + })(manager) + + manager.ensureProxyStopped(context.Background(), name, name, runConfig, false) + assert.Zero(t, fallbackCalls, "a signalled proxy must not be signalled again through port cleanup") + select { + case <-proxy.exited: + t.Error("SIGTERM-ignoring proxy unexpectedly exited") + default: + } +} + +//nolint:paralleltest // saved-workload fixtures use t.Setenv +func TestDefaultManager_freePortHolderIfNeeded_WaitsForOwnedProxyExitAndReleasesListener(t *testing.T) { + isolateWorkloadStopState(t) + if goruntime.GOOS == "darwin" || goruntime.GOOS == "freebsd" { + if _, err := exec.LookPath("lsof"); err != nil { + t.Skipf("TCP owner discovery requires lsof: %v", err) + } + } + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + t.Cleanup(cancel) + name := fmt.Sprintf("port-cleanup-%d", time.Now().UnixNano()) + proxy := startProxyProcessFixture(t, name, false, true) + portPID, err := networking.GetProcessOnPort(proxy.port) + require.NoError(t, err) + require.Equal(t, proxy.pid, portPID, "port discovery must identify only the owned fixture") + rc := &runner.RunConfig{BaseName: name, Port: proxy.port} + persistStopRunConfig(t, name, rc) + saved, err := runner.LoadState(ctx, name) + require.NoError(t, err) + manager := &DefaultManager{} + withProxyExitTimeout(5 * time.Second)(manager) + + wrongWorkload := *saved + wrongWorkload.BaseName += "-other" + manager.freePortHolderIfNeeded(ctx, &wrongWorkload) + alive, err := process.FindProcess(proxy.pid) + require.NoError(t, err) + require.True(t, alive, "cleanup must not signal another workload's proxy") + portPID, err = networking.GetProcessOnPort(proxy.port) + require.NoError(t, err) + require.Equal(t, proxy.pid, portPID, "identity mismatch must leave the owned listener intact") + + manager.freePortHolderIfNeeded(ctx, saved) + listener, err := net.Listen("tcp4", fmt.Sprintf("127.0.0.1:%d", proxy.port)) + require.NoError(t, err, "cleanup must release the listener before returning") + t.Cleanup(func() { assert.NoError(t, listener.Close()) }) + select { + case <-proxy.exited: + require.NoError(t, proxy.waitErr, "owned proxy must complete its graceful shutdown") + case <-ctx.Done(): + t.Fatal("port cleanup did not terminate and reap the owned proxy") + } +} + // TestDefaultManager_orphanProxyPortCleanup verifies that stop and rm fall back // to port-based proxy cleanup when the tracked PID is unavailable (the missing // status-file scenario), and that the fallback does not run on the normal path // where the proxy was stopped by PID. +// +//nolint:paralleltest // saved-workload fixtures use t.Setenv func TestDefaultManager_orphanProxyPortCleanup(t *testing.T) { - t.Parallel() + isolateWorkloadStopState(t) const workloadName = "test-workload" + savedRunConfig := func(t *testing.T) *runner.RunConfig { + t.Helper() + rc := &runner.RunConfig{BaseName: workloadName, Port: 54321} + persistStopRunConfig(t, workloadName, rc) + return rc + } containerInfo := func() runtime.ContainerInfo { return runtime.ContainerInfo{ Name: workloadName, @@ -2373,7 +3611,6 @@ func TestDefaultManager_orphanProxyPortCleanup(t *testing.T) { } t.Run("stop frees orphan proxy port when status file missing", func(t *testing.T) { - t.Parallel() ctrl := gomock.NewController(t) defer ctrl.Finish() @@ -2383,19 +3620,23 @@ func TestDefaultManager_orphanProxyPortCleanup(t *testing.T) { // Missing status file: no tracked PID, so the proxy is not killed by PID. sm.EXPECT().GetWorkloadPID(gomock.Any(), workloadName).Return(0, nil) - sm.EXPECT().ResetWorkloadPID(gomock.Any(), workloadName).Return(nil) rtMock.EXPECT().StopWorkload(gomock.Any(), workloadName).Return(nil) sm.EXPECT().SetWorkloadStatus(gomock.Any(), workloadName, runtime.WorkloadStatusStopped, "").Return(nil) var freed []*runner.RunConfig runConfig := &runner.RunConfig{BaseName: workloadName, Port: 54321} - manager := &DefaultManager{statuses: sm, runtime: rtMock} + persistStopRunConfig(t, workloadName, runConfig) + manager := &DefaultManager{ + savedRunConfigs: testSavedRunConfigChecker{exists: true}, + clientManagers: testClientManagerProvider(unavailableClientManager), + statuses: sm, runtime: rtMock, + } withPortFreer(func(_ context.Context, rc *runner.RunConfig) { freed = append(freed, rc) })(manager) ci := containerInfo() - err := manager.stopSingleContainerWorkload(context.Background(), &ci, runConfig) + err := manager.stopSingleContainerWorkload(context.Background(), &ci, runConfig, true) require.NoError(t, err) require.Len(t, freed, 1, "port-cleanup fallback should run exactly once") @@ -2404,7 +3645,6 @@ func TestDefaultManager_orphanProxyPortCleanup(t *testing.T) { }) t.Run("stop does not free port on normal shutdown", func(t *testing.T) { - t.Parallel() ctrl := gomock.NewController(t) defer ctrl.Finish() @@ -2413,21 +3653,25 @@ func TestDefaultManager_orphanProxyPortCleanup(t *testing.T) { rtMock := runtimeMocks.NewMockRuntime(ctrl) // A valid, killable PID: the proxy is stopped by PID, so no fallback. - pid := startKillableProcess(t) + pid := startVerifiedProxyProcess(t, workloadName).pid sm.EXPECT().GetWorkloadPID(gomock.Any(), workloadName).Return(pid, nil) - sm.EXPECT().ResetWorkloadPID(gomock.Any(), workloadName).Return(nil) + sm.EXPECT().ResetWorkloadPIDIfMatch(gomock.Any(), workloadName, pid).Return(nil) rtMock.EXPECT().StopWorkload(gomock.Any(), workloadName).Return(nil) sm.EXPECT().SetWorkloadStatus(gomock.Any(), workloadName, runtime.WorkloadStatusStopped, "").Return(nil) freedCalls := 0 - manager := &DefaultManager{statuses: sm, runtime: rtMock} + manager := &DefaultManager{ + savedRunConfigs: testSavedRunConfigChecker{exists: true}, + clientManagers: testClientManagerProvider(unavailableClientManager), + statuses: sm, runtime: rtMock, + } withPortFreer(func(_ context.Context, _ *runner.RunConfig) { freedCalls++ })(manager) ci := containerInfo() err := manager.stopSingleContainerWorkload( - context.Background(), &ci, &runner.RunConfig{BaseName: workloadName, Port: 54321}, + context.Background(), &ci, savedRunConfig(t), true, ) require.NoError(t, err) @@ -2435,7 +3679,6 @@ func TestDefaultManager_orphanProxyPortCleanup(t *testing.T) { }) t.Run("delete frees orphan proxy port when status file missing", func(t *testing.T) { - t.Parallel() ctrl := gomock.NewController(t) defer ctrl.Finish() @@ -2451,12 +3694,16 @@ func TestDefaultManager_orphanProxyPortCleanup(t *testing.T) { rtMock.EXPECT().GetWorkloadInfo(gomock.Any(), workloadName).Return(runtime.ContainerInfo{}, runtime.ErrWorkloadNotFound) // Missing status file: no tracked PID, so the proxy is not killed by PID. sm.EXPECT().GetWorkloadPID(gomock.Any(), workloadName).Return(0, nil) - sm.EXPECT().ResetWorkloadPID(gomock.Any(), workloadName).Return(nil) sm.EXPECT().DeleteWorkloadStatus(gomock.Any(), workloadName).Return(nil) var freed []*runner.RunConfig runConfig := &runner.RunConfig{BaseName: workloadName, Port: 54321} - manager := &DefaultManager{statuses: sm, runtime: rtMock} + persistStopRunConfig(t, workloadName, runConfig) + manager := &DefaultManager{ + savedRunConfigs: testSavedRunConfigChecker{exists: true}, + clientManagers: testClientManagerProvider(unavailableClientManager), + statuses: sm, runtime: rtMock, + } withPortFreer(func(_ context.Context, rc *runner.RunConfig) { freed = append(freed, rc) })(manager) @@ -2470,7 +3717,6 @@ func TestDefaultManager_orphanProxyPortCleanup(t *testing.T) { }) t.Run("delete does not free port on normal shutdown", func(t *testing.T) { - t.Parallel() ctrl := gomock.NewController(t) defer ctrl.Finish() @@ -2483,19 +3729,23 @@ func TestDefaultManager_orphanProxyPortCleanup(t *testing.T) { rtMock.EXPECT().RemoveWorkload(gomock.Any(), workloadName).Return(nil) rtMock.EXPECT().GetWorkloadInfo(gomock.Any(), workloadName).Return(runtime.ContainerInfo{}, runtime.ErrWorkloadNotFound) // A valid, killable PID: the proxy is stopped by PID, so no fallback. - pid := startKillableProcess(t) + pid := startVerifiedProxyProcess(t, workloadName).pid sm.EXPECT().GetWorkloadPID(gomock.Any(), workloadName).Return(pid, nil) - sm.EXPECT().ResetWorkloadPID(gomock.Any(), workloadName).Return(nil) + sm.EXPECT().ResetWorkloadPIDIfMatch(gomock.Any(), workloadName, pid).Return(nil) sm.EXPECT().DeleteWorkloadStatus(gomock.Any(), workloadName).Return(nil) freedCalls := 0 - manager := &DefaultManager{statuses: sm, runtime: rtMock} + manager := &DefaultManager{ + savedRunConfigs: testSavedRunConfigChecker{exists: true}, + clientManagers: testClientManagerProvider(unavailableClientManager), + statuses: sm, runtime: rtMock, + } withPortFreer(func(_ context.Context, _ *runner.RunConfig) { freedCalls++ })(manager) err := manager.deleteContainerWorkload( - context.Background(), workloadName, &runner.RunConfig{BaseName: workloadName, Port: 54321}, + context.Background(), workloadName, savedRunConfig(t), ) require.NoError(t, err) @@ -2503,7 +3753,6 @@ func TestDefaultManager_orphanProxyPortCleanup(t *testing.T) { }) t.Run("remote stop frees orphan proxy port when status file missing", func(t *testing.T) { - t.Parallel() ctrl := gomock.NewController(t) defer ctrl.Finish() @@ -2517,11 +3766,15 @@ func TestDefaultManager_orphanProxyPortCleanup(t *testing.T) { sm.EXPECT().GetWorkload(gomock.Any(), workloadName).Return(core.Workload{}, runtime.ErrWorkloadNotFound) // No tracked PID, so the proxy is not killed by PID. sm.EXPECT().GetWorkloadPID(gomock.Any(), workloadName).Return(0, nil) - sm.EXPECT().ResetWorkloadPID(gomock.Any(), workloadName).Return(nil) var freed []*runner.RunConfig runConfig := &runner.RunConfig{BaseName: workloadName, Port: 54321} - manager := &DefaultManager{statuses: sm} + persistStopRunConfig(t, workloadName, runConfig) + manager := &DefaultManager{ + savedRunConfigs: testSavedRunConfigChecker{exists: true}, + clientManagers: testClientManagerProvider(unavailableClientManager), + statuses: sm, + } withPortFreer(func(_ context.Context, rc *runner.RunConfig) { freed = append(freed, rc) })(manager) @@ -2535,7 +3788,6 @@ func TestDefaultManager_orphanProxyPortCleanup(t *testing.T) { }) t.Run("remote delete frees orphan proxy port when status file missing", func(t *testing.T) { - t.Parallel() ctrl := gomock.NewController(t) defer ctrl.Finish() @@ -2545,12 +3797,16 @@ func TestDefaultManager_orphanProxyPortCleanup(t *testing.T) { sm.EXPECT().SetWorkloadStatus(gomock.Any(), workloadName, runtime.WorkloadStatusRemoving, "").Return(nil) // Missing status file: no tracked PID, so the proxy is not killed by PID. sm.EXPECT().GetWorkloadPID(gomock.Any(), workloadName).Return(0, nil) - sm.EXPECT().ResetWorkloadPID(gomock.Any(), workloadName).Return(nil) sm.EXPECT().DeleteWorkloadStatus(gomock.Any(), workloadName).Return(nil) var freed []*runner.RunConfig runConfig := &runner.RunConfig{BaseName: workloadName, Port: 54321} - manager := &DefaultManager{statuses: sm} + persistStopRunConfig(t, workloadName, runConfig) + manager := &DefaultManager{ + savedRunConfigs: testSavedRunConfigChecker{exists: true}, + clientManagers: testClientManagerProvider(unavailableClientManager), + statuses: sm, + } withPortFreer(func(_ context.Context, rc *runner.RunConfig) { freed = append(freed, rc) })(manager) @@ -2564,7 +3820,6 @@ func TestDefaultManager_orphanProxyPortCleanup(t *testing.T) { }) t.Run("remote stop does not free port on normal shutdown", func(t *testing.T) { - t.Parallel() ctrl := gomock.NewController(t) defer ctrl.Finish() @@ -2577,19 +3832,23 @@ func TestDefaultManager_orphanProxyPortCleanup(t *testing.T) { }, nil) sm.EXPECT().SetWorkloadStatus(gomock.Any(), workloadName, runtime.WorkloadStatusStopping, "").Return(nil) // A valid, killable PID: the proxy is stopped by PID, so no fallback. - pid := startKillableProcess(t) + pid := startVerifiedProxyProcess(t, workloadName).pid sm.EXPECT().GetWorkloadPID(gomock.Any(), workloadName).Return(pid, nil) - sm.EXPECT().ResetWorkloadPID(gomock.Any(), workloadName).Return(nil) + sm.EXPECT().ResetWorkloadPIDIfMatch(gomock.Any(), workloadName, pid).Return(nil) sm.EXPECT().SetWorkloadStatus(gomock.Any(), workloadName, runtime.WorkloadStatusStopped, "").Return(nil) freedCalls := 0 - manager := &DefaultManager{statuses: sm} + manager := &DefaultManager{ + savedRunConfigs: testSavedRunConfigChecker{exists: true}, + clientManagers: testClientManagerProvider(unavailableClientManager), + statuses: sm, + } withPortFreer(func(_ context.Context, _ *runner.RunConfig) { freedCalls++ })(manager) err := manager.stopRemoteWorkload( - context.Background(), workloadName, &runner.RunConfig{BaseName: workloadName, Port: 54321}, + context.Background(), workloadName, savedRunConfig(t), ) require.NoError(t, err) @@ -2597,7 +3856,6 @@ func TestDefaultManager_orphanProxyPortCleanup(t *testing.T) { }) t.Run("remote delete does not free port on normal shutdown", func(t *testing.T) { - t.Parallel() ctrl := gomock.NewController(t) defer ctrl.Finish() @@ -2606,19 +3864,23 @@ func TestDefaultManager_orphanProxyPortCleanup(t *testing.T) { sm.EXPECT().SetWorkloadStatus(gomock.Any(), workloadName, runtime.WorkloadStatusRemoving, "").Return(nil) // A valid, killable PID: the proxy is stopped by PID, so no fallback. - pid := startKillableProcess(t) + pid := startVerifiedProxyProcess(t, workloadName).pid sm.EXPECT().GetWorkloadPID(gomock.Any(), workloadName).Return(pid, nil) - sm.EXPECT().ResetWorkloadPID(gomock.Any(), workloadName).Return(nil) + sm.EXPECT().ResetWorkloadPIDIfMatch(gomock.Any(), workloadName, pid).Return(nil) sm.EXPECT().DeleteWorkloadStatus(gomock.Any(), workloadName).Return(nil) freedCalls := 0 - manager := &DefaultManager{statuses: sm} + manager := &DefaultManager{ + savedRunConfigs: testSavedRunConfigChecker{exists: true}, + clientManagers: testClientManagerProvider(unavailableClientManager), + statuses: sm, + } withPortFreer(func(_ context.Context, _ *runner.RunConfig) { freedCalls++ })(manager) err := manager.deleteRemoteWorkload( - context.Background(), workloadName, &runner.RunConfig{BaseName: workloadName, Port: 54321}, + context.Background(), workloadName, savedRunConfig(t), ) require.NoError(t, err) diff --git a/pkg/workloads/statuses/file_status.go b/pkg/workloads/statuses/file_status.go index d118476759..ceed2b4ebd 100644 --- a/pkg/workloads/statuses/file_status.go +++ b/pkg/workloads/statuses/file_status.go @@ -519,6 +519,42 @@ func (f *fileStatusManager) ResetWorkloadPIDIfMatch(ctx context.Context, workloa return err } +// SetWorkloadStoppedIfOwned clears the PID and marks the workload stopped in +// one locked write, only if its status file still exists and records ownerPID. +// The status changes only from starting or running. A supervisor cancelled by +// a signal uses it so it neither recreates a deleted workload's status nor +// overrides a replacement supervisor or a newer stopping/removing status. +func (f *fileStatusManager) SetWorkloadStoppedIfOwned(ctx context.Context, workloadName string, ownerPID int) error { + if err := removePIDFile(workloadName); err != nil { + slog.Debug("no PID for workload was removed", "workload", workloadName) + } + return f.withFileLock(ctx, workloadName, func(statusFilePath string) error { + if _, err := os.Stat(statusFilePath); os.IsNotExist(err) { + return nil + } else if err != nil { + return fmt.Errorf("failed to check status file for workload %s: %w", workloadName, err) + } + + statusFile, err := f.readStatusFile(statusFilePath) + if err != nil { + return fmt.Errorf("failed to read existing status for workload %s: %w", workloadName, err) + } + if statusFile.ProcessID != ownerPID { + slog.Debug("skipping stopped mark: workload owned by another process", + "workload", workloadName, "current_pid", statusFile.ProcessID, "owner_pid", ownerPID) + return nil + } + + statusFile.ProcessID = 0 + if statusFile.Status == rt.WorkloadStatusStarting || statusFile.Status == rt.WorkloadStatusRunning { + statusFile.Status = rt.WorkloadStatusStopped + statusFile.StatusContext = "" + } + statusFile.UpdatedAt = time.Now() + return f.writeStatusFile(statusFilePath, *statusFile) + }) +} + // GetWorkloadPID retrieves the PID of a workload from its status file. func (f *fileStatusManager) GetWorkloadPID(ctx context.Context, workloadName string) (int, error) { var pid int diff --git a/pkg/workloads/statuses/file_status_test.go b/pkg/workloads/statuses/file_status_test.go index d9546af162..b62be0e3cd 100644 --- a/pkg/workloads/statuses/file_status_test.go +++ b/pkg/workloads/statuses/file_status_test.go @@ -1910,6 +1910,62 @@ func TestFileStatusManager_ResetWorkloadPIDIfMatch_NonExistentWorkload(t *testin require.NoFileExists(t, statusFile) } +func TestFileStatusManager_SetWorkloadStoppedIfOwned(t *testing.T) { + t.Parallel() + const ownerPID = 12345 + + tests := []struct { + name string + status rt.WorkloadStatus + pid int + wantStatus rt.WorkloadStatus + wantContext string + wantPID int + }{ + {name: "running with owner PID", status: rt.WorkloadStatusRunning, pid: ownerPID, wantStatus: rt.WorkloadStatusStopped}, + {name: "starting with owner PID", status: rt.WorkloadStatusStarting, pid: ownerPID, wantStatus: rt.WorkloadStatusStopped}, + // A replacement supervisor writes starting before it records its PID. + {name: "replacement without PID yet", status: rt.WorkloadStatusStarting, + wantStatus: rt.WorkloadStatusStarting, wantContext: "original"}, + {name: "replacement PID", status: rt.WorkloadStatusStarting, pid: 99999, + wantStatus: rt.WorkloadStatusStarting, wantContext: "original", wantPID: 99999}, + {name: "removing with owner PID clears only PID", status: rt.WorkloadStatusRemoving, pid: ownerPID, + wantStatus: rt.WorkloadStatusRemoving, wantContext: "original"}, + {name: "error with another PID", status: rt.WorkloadStatusError, pid: 99999, + wantStatus: rt.WorkloadStatusError, wantContext: "original", wantPID: 99999}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + tempDir := t.TempDir() + manager := &fileStatusManager{baseDir: tempDir} + ctx := context.Background() + + require.NoError(t, manager.SetWorkloadStatus(ctx, "test-workload", tt.status, "original")) + require.NoError(t, manager.SetWorkloadPID(ctx, "test-workload", tt.pid)) + + require.NoError(t, manager.SetWorkloadStoppedIfOwned(ctx, "test-workload", ownerPID)) + + data, err := os.ReadFile(filepath.Join(tempDir, "test-workload.json")) + require.NoError(t, err) + var statusFileData workloadStatusFile + require.NoError(t, json.Unmarshal(data, &statusFileData)) + assert.Equal(t, tt.wantStatus, statusFileData.Status) + assert.Equal(t, tt.wantContext, statusFileData.StatusContext) + assert.Equal(t, tt.wantPID, statusFileData.ProcessID) + }) + } + + t.Run("missing status is not recreated", func(t *testing.T) { + t.Parallel() + tempDir := t.TempDir() + manager := &fileStatusManager{baseDir: tempDir} + + require.NoError(t, manager.SetWorkloadStoppedIfOwned(context.Background(), "test-workload", ownerPID)) + require.NoFileExists(t, filepath.Join(tempDir, "test-workload.json")) + }) +} + // TestFileStatusManager_GetWorkload_PIDMigration tests PID migration from legacy PID files to status files func TestFileStatusManager_GetWorkload_PIDMigration(t *testing.T) { t.Parallel() diff --git a/pkg/workloads/statuses/mocks/mock_status_manager.go b/pkg/workloads/statuses/mocks/mock_status_manager.go index 9ff073471f..9b300d2f88 100644 --- a/pkg/workloads/statuses/mocks/mock_status_manager.go +++ b/pkg/workloads/statuses/mocks/mock_status_manager.go @@ -156,3 +156,17 @@ func (mr *MockStatusManagerMockRecorder) SetWorkloadStatus(ctx, workloadName, st mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SetWorkloadStatus", reflect.TypeOf((*MockStatusManager)(nil).SetWorkloadStatus), ctx, workloadName, status, contextMsg) } + +// SetWorkloadStoppedIfOwned mocks base method. +func (m *MockStatusManager) SetWorkloadStoppedIfOwned(ctx context.Context, workloadName string, ownerPID int) error { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "SetWorkloadStoppedIfOwned", ctx, workloadName, ownerPID) + ret0, _ := ret[0].(error) + return ret0 +} + +// SetWorkloadStoppedIfOwned indicates an expected call of SetWorkloadStoppedIfOwned. +func (mr *MockStatusManagerMockRecorder) SetWorkloadStoppedIfOwned(ctx, workloadName, ownerPID any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SetWorkloadStoppedIfOwned", reflect.TypeOf((*MockStatusManager)(nil).SetWorkloadStoppedIfOwned), ctx, workloadName, ownerPID) +} diff --git a/pkg/workloads/statuses/noop.go b/pkg/workloads/statuses/noop.go index f24e710e29..c7c2145964 100644 --- a/pkg/workloads/statuses/noop.go +++ b/pkg/workloads/statuses/noop.go @@ -54,6 +54,11 @@ func (*NoopStatusManager) ResetWorkloadPIDIfMatch(_ context.Context, _ string, _ return nil } +// SetWorkloadStoppedIfOwned does nothing and returns nil. +func (*NoopStatusManager) SetWorkloadStoppedIfOwned(_ context.Context, _ string, _ int) error { + return nil +} + // GetWorkloadPID returns 0 and nil error. func (*NoopStatusManager) GetWorkloadPID(_ context.Context, _ string) (int, error) { return 0, nil diff --git a/pkg/workloads/statuses/status.go b/pkg/workloads/statuses/status.go index 776dc9c5cd..b2d2a3d0b2 100644 --- a/pkg/workloads/statuses/status.go +++ b/pkg/workloads/statuses/status.go @@ -42,6 +42,11 @@ type StatusManager interface { // dying process from clobbering the PID written by a replacement process // that started in the meantime. ResetWorkloadPIDIfMatch(ctx context.Context, workloadName string, expectedPID int) error + // SetWorkloadStoppedIfOwned atomically clears the PID and marks a workload + // stopped only if its status still exists and records ownerPID. Only a + // starting or running status becomes stopped. It never creates a status + // entry or overrides a newer status. + SetWorkloadStoppedIfOwned(ctx context.Context, workloadName string, ownerPID int) error // GetWorkloadPID retrieves the PID of a workload by its name. // Returns 0 if the workload does not exist or if PID is not available. GetWorkloadPID(ctx context.Context, workloadName string) (int, error) @@ -165,6 +170,13 @@ func (*runtimeStatusManager) ResetWorkloadPIDIfMatch(_ context.Context, workload return nil } +func (*runtimeStatusManager) SetWorkloadStoppedIfOwned(_ context.Context, workloadName string, ownerPID int) error { + // Noop for runtime status manager + slog.Debug("workload conditional stop (noop for runtime status manager)", + "workload", workloadName, "owner_pid", ownerPID) + return nil +} + func (*runtimeStatusManager) GetWorkloadPID(_ context.Context, workloadName string) (int, error) { // Noop for runtime status manager - always return 0 slog.Debug("workload PID requested (noop for runtime status manager, returning 0)", "workload", workloadName)