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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
107 changes: 92 additions & 15 deletions agent/agentproc/api.go
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,7 @@ func (api *API) Routes() http.Handler {
r.Get("/list", api.handleListProcesses)
r.Get("/{id}/output", api.handleProcessOutput)
r.Post("/{id}/signal", api.handleSignalProcess)
r.Post("/signal-by-idempotency-key", api.handleSignalProcessByIdempotencyKey)
return r
}

Expand Down Expand Up @@ -247,6 +248,96 @@ func (api *API) handleProcessOutput(rw http.ResponseWriter, r *http.Request) {
})
}

// handleSignalProcessByIdempotencyKey sends a signal to the process
// started under an idempotency key. It exists so a caller whose start
// response was lost can still stop the command it asked for: the key
// identifies the process even when its ID never arrived. The key
// travels in the body rather than the path so no key value needs URL
// escaping.
func (api *API) handleSignalProcessByIdempotencyKey(rw http.ResponseWriter, r *http.Request) {
ctx := r.Context()

var chatID string
if chatContext, ok := agentchat.FromContext(ctx); ok {
chatID = chatContext.ID.String()
}

var req workspacesdk.SignalProcessByIdempotencyKeyRequest
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
httpapi.Write(ctx, rw, http.StatusBadRequest, codersdk.Response{
Message: "Request body must be valid JSON.",
Detail: err.Error(),
})
return
}
if req.IdempotencyKey == "" {
httpapi.Write(ctx, rw, http.StatusBadRequest, codersdk.Response{
Message: "Idempotency key is required.",
})
return
}
if !validateSignal(ctx, rw, req.Signal) {
return
}

if err := api.manager.signalByKey(ctx, chatID, req.IdempotencyKey, req.Signal); err != nil {
switch {
case errors.Is(err, errProcessNotFound):
httpapi.Write(ctx, rw, http.StatusNotFound, workspacesdk.ProcessKeyNotFoundError{
Code: workspacesdk.ProcessKeyNotFoundCode,
Response: codersdk.Response{
Message: "No process was started with this idempotency key.",
},
})
case errors.Is(err, errProcessStartPending):
httpapi.Write(ctx, rw, http.StatusConflict, workspacesdk.ProcessConflictError{
Code: workspacesdk.ProcessConflictStartPending,
Response: codersdk.Response{
Message: "The start holding this idempotency key has not spawned its process yet.",
},
})
case errors.Is(err, errProcessNotRunning):
httpapi.Write(ctx, rw, http.StatusConflict, workspacesdk.ProcessConflictError{
Code: workspacesdk.ProcessConflictNotRunning,
Response: codersdk.Response{
Message: "The process started with this idempotency key is not running.",
},
})
default:
httpapi.Write(ctx, rw, http.StatusInternalServerError, codersdk.Response{
Message: "Failed to signal process.",
Detail: err.Error(),
})
}
return
}

httpapi.Write(ctx, rw, http.StatusOK, codersdk.Response{
Message: fmt.Sprintf("Signal %q sent.", req.Signal),
})
}

// validateSignal writes its own error response; false means the caller
// must stop.
func validateSignal(ctx context.Context, rw http.ResponseWriter, signal string) bool {
if signal == "" {
httpapi.Write(ctx, rw, http.StatusBadRequest, codersdk.Response{
Message: "Signal is required.",
})
return false
}
if signal != "kill" && signal != "terminate" {
httpapi.Write(ctx, rw, http.StatusBadRequest, codersdk.Response{
Message: fmt.Sprintf(
"Unsupported signal %q. Use \"kill\" or \"terminate\".",
signal,
),
})
return false
}
return true
}

// handleSignalProcess sends a signal to a running process.
func (api *API) handleSignalProcess(rw http.ResponseWriter, r *http.Request) {
ctx := r.Context()
Expand All @@ -272,21 +363,7 @@ func (api *API) handleSignalProcess(rw http.ResponseWriter, r *http.Request) {
})
return
}

if req.Signal == "" {
httpapi.Write(ctx, rw, http.StatusBadRequest, codersdk.Response{
Message: "Signal is required.",
})
return
}

if req.Signal != "kill" && req.Signal != "terminate" {
httpapi.Write(ctx, rw, http.StatusBadRequest, codersdk.Response{
Message: fmt.Sprintf(
"Unsupported signal %q. Use \"kill\" or \"terminate\".",
req.Signal,
),
})
if !validateSignal(ctx, rw, req.Signal) {
return
}

Expand Down
157 changes: 157 additions & 0 deletions agent/agentproc/api_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -116,6 +116,28 @@ func postSignal(t *testing.T, handler http.Handler, id string, req workspacesdk.
return w
}

func postSignalByKey(t *testing.T, handler http.Handler, req workspacesdk.SignalProcessByIdempotencyKeyRequest, headers ...http.Header) *httptest.ResponseRecorder {
t.Helper()

ctx, cancel := context.WithTimeout(context.Background(), testutil.WaitLong)
defer cancel()

body, err := json.Marshal(req)
require.NoError(t, err)

w := httptest.NewRecorder()
r := httptest.NewRequestWithContext(ctx, http.MethodPost, "/signal-by-idempotency-key", bytes.NewReader(body))
for _, header := range headers {
for key, values := range header {
for _, value := range values {
r.Header.Add(key, value)
}
}
}
handler.ServeHTTP(w, r)
return w
}

// newTestAPI creates a new API with a test logger and default
// execer, returning the handler and API.
func newTestAPI(t *testing.T) http.Handler {
Expand Down Expand Up @@ -1221,6 +1243,141 @@ func getOutputWithWaitCtx(ctx context.Context, t *testing.T, handler http.Handle
return w
}

func TestSignalProcessByIdempotencyKey(t *testing.T) {
t.Parallel()

t.Run("KillsProcessStartedUnderKey", func(t *testing.T) {
t.Parallel()

handler := newTestAPI(t)
id := startAndGetID(t, handler, workspacesdk.StartProcessRequest{
Command: "sleep 60",
IdempotencyKey: "key-1",
Background: true,
})

w := postSignalByKey(t, handler, workspacesdk.SignalProcessByIdempotencyKeyRequest{
IdempotencyKey: "key-1",
Signal: "kill",
})
require.Equal(t, http.StatusOK, w.Code)

resp := waitForExit(t, handler, id)
require.False(t, resp.Running)
})

// Keys carry provider-supplied tool call IDs, so the route must
// accept values that would need escaping in a URL path.
t.Run("AcceptsKeysNeedingURLEscaping", func(t *testing.T) {
t.Parallel()

for _, key := range []string{"7-a/b", "7-a b", "7-a%b", "7-a?b#c", "7-.."} {
t.Run(key, func(t *testing.T) {
t.Parallel()

handler := newTestAPI(t)
id := startAndGetID(t, handler, workspacesdk.StartProcessRequest{
Command: "sleep 60",
IdempotencyKey: key,
Background: true,
})

w := postSignalByKey(t, handler, workspacesdk.SignalProcessByIdempotencyKeyRequest{
IdempotencyKey: key,
Signal: "kill",
})
require.Equal(t, http.StatusOK, w.Code)
require.False(t, waitForExit(t, handler, id).Running)
})
}
})

t.Run("UnknownKeyNotFound", func(t *testing.T) {
t.Parallel()

handler := newTestAPI(t)
w := postSignalByKey(t, handler, workspacesdk.SignalProcessByIdempotencyKeyRequest{
IdempotencyKey: "key-missing",
Signal: "kill",
})
require.Equal(t, http.StatusNotFound, w.Code)
var notFound workspacesdk.ProcessKeyNotFoundError
require.NoError(t, json.NewDecoder(w.Body).Decode(&notFound))
require.Equal(t, workspacesdk.ProcessKeyNotFoundCode, notFound.Code)
})

t.Run("ForeignChatKeyNotFound", func(t *testing.T) {
t.Parallel()

// Reservations are chat-scoped, so another chat's key is
// simply absent rather than forbidden.
handler := newTestAPI(t)
headerA := http.Header{}
headerA.Set(workspacesdk.CoderChatIDHeader, uuid.New().String())
headerB := http.Header{}
headerB.Set(workspacesdk.CoderChatIDHeader, uuid.New().String())

id := startAndGetID(t, handler, workspacesdk.StartProcessRequest{
Command: "sleep 60",
IdempotencyKey: "key-1",
Background: true,
}, headerA)

w := postSignalByKey(t, handler, workspacesdk.SignalProcessByIdempotencyKeyRequest{
IdempotencyKey: "key-1",
Signal: "kill",
}, headerB)
require.Equal(t, http.StatusNotFound, w.Code)

// The process is untouched.
w = getOutputWithHeaders(t, handler, id, headerA)
require.Equal(t, http.StatusOK, w.Code)
var output workspacesdk.ProcessOutputResponse
require.NoError(t, json.NewDecoder(w.Body).Decode(&output))
require.True(t, output.Running)
})

t.Run("ExitedProcessConflicts", func(t *testing.T) {
t.Parallel()

handler := newTestAPI(t)
id := startAndGetID(t, handler, workspacesdk.StartProcessRequest{
Command: "echo hello",
IdempotencyKey: "key-1",
})
waitForExit(t, handler, id)

w := postSignalByKey(t, handler, workspacesdk.SignalProcessByIdempotencyKeyRequest{
IdempotencyKey: "key-1",
Signal: "kill",
})
// The code must distinguish this from a start conflict, since
// callers suppress the kill only for an exited process.
requireConflictCode(t, w, workspacesdk.ProcessConflictNotRunning)
})

t.Run("RejectsUnsupportedSignal", func(t *testing.T) {
t.Parallel()

handler := newTestAPI(t)
w := postSignalByKey(t, handler, workspacesdk.SignalProcessByIdempotencyKeyRequest{
IdempotencyKey: "key-1",
Signal: "hup",
})
require.Equal(t, http.StatusBadRequest, w.Code)
})

t.Run("RejectsMissingKey", func(t *testing.T) {
t.Parallel()

handler := newTestAPI(t)
w := postSignalByKey(t, handler, workspacesdk.SignalProcessByIdempotencyKeyRequest{
Signal: "kill",
})
require.Equal(t, http.StatusBadRequest, w.Code)
})
}

func TestSignalProcess(t *testing.T) {
t.Parallel()

Expand Down
23 changes: 23 additions & 0 deletions agent/agentproc/process.go
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,11 @@ var (
errProcessNotFound = xerrors.New("process not found")
errProcessNotRunning = xerrors.New("process is not running")

// errProcessStartPending reports a reservation that has not
// published its process yet, so the request reached nothing
// though the command may still run.
errProcessStartPending = xerrors.New("process start is still pending")

// exitedProcessReapAge is how long an exited process without
// an idempotency key is kept before being automatically
// removed from the map.
Expand Down Expand Up @@ -446,6 +451,24 @@ func (m *manager) signal(id string, sig string) error {
return nil
}

// signalByKey signals the process started under an idempotency key,
// so a caller that lost the start response can still act on it.
// Reservations are chat-scoped, so another chat's key is absent here.
//
// A reservation that has not spawned yet is the expected state on this
// path, since it is used precisely when the start response was lost.
// Waiting within ctx keeps that from reading as a missing process.
func (m *manager) signalByKey(ctx context.Context, chatID, idempotencyKey, sig string) error {
procID, err := m.runOnce.Await(ctx, runOnceKey{chatID: chatID, key: idempotencyKey})
if err != nil {
if errors.Is(err, agentrunonce.ErrPublicationPending) {
return errProcessStartPending
}
return errProcessNotFound
}
return m.signal(procID, sig)
}

// Close kills all running processes and prevents new ones from
// starting. It cancels each process's context, which causes
// CommandContext to kill the process and its pipe goroutines to
Expand Down
Loading
Loading