Skip to content
Draft
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
14 changes: 7 additions & 7 deletions internal/headless/headless.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ package headless

import (
"bytes"
"context"
"encoding/json"
"fmt"
"io"
Expand Down Expand Up @@ -219,20 +220,19 @@ func (t *trackingWriter) Write(p []byte) (n int, err error) {
// runCommandAndCapture shells out the given command and intercepts both standard streams.
// It kills the process if it produces no output for IdleTimeout.
func runCommandAndCapture(shell, command string) (string, string, error) {
cmd := exec.Command(shell, "-c", command)
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
cmd := exec.CommandContext(ctx, shell, "-c", command)
cmd.Env = os.Environ()

var stdoutBuf, stderrBuf bytes.Buffer

timer := time.AfterFunc(IdleTimeout, func() {
if cmd.Process != nil {
_ = cmd.Process.Kill()
}
})
timeout := IdleTimeout
timer := time.AfterFunc(timeout, cancel)
defer timer.Stop()

resetTimer := func() {
timer.Reset(IdleTimeout)
timer.Reset(timeout)
}

cmd.Stdout = &trackingWriter{w: &stdoutBuf, onWrite: resetTimer}
Expand Down
29 changes: 29 additions & 0 deletions internal/headless/idle_timeout_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
package headless

import (
"testing"
"time"
)

func TestCaptureIdleTimeout(t *testing.T) {
previous := IdleTimeout
IdleTimeout = 100 * time.Millisecond
t.Cleanup(func() { IdleTimeout = previous })

for _, tc := range []struct {
name, command, stdout string
}{
{"silent", "exec sleep 2", ""},
{"output before idle", "printf ready; exec sleep 2", "ready"},
} {
t.Run(tc.name, func(t *testing.T) {
stdout, stderr, err := runCommandAndCapture("sh", tc.command)
if err == nil {
t.Fatal("expected the idle command to be terminated")
}
if stdout != tc.stdout || stderr != "" {
t.Fatalf("captured stdout=%q stderr=%q, want stdout=%q and empty stderr", stdout, stderr, tc.stdout)
}
})
}
}