package runner
import (
"context"
"encoding/json"
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"runtime"
"strconv"
"strings"
"sync"
"testing"
"time"
"craftdesign.group/quarry/internal/cibridge"
)
// A TASK WHOSE RUN IS CANCELLED STOPS.
//
// jva measured a closed landing's merge job running its full four
// minutes after the run was cancelled, holding the runner. dagnats#737
// answers 409 to a heartbeat of such a task; the runner then kills the
// job, its children included, and reports nothing.
func TestATaskWhoseRunIsCancelledStops(t *testing.T) {
job, _ := json.Marshal(Job{Steps: []JobStep{{Run: "sleep 30; echo ran-to-$((40+2))"}}})
tk := task("doomed", "c1")
tk.Metadata = map[string]string{JobKey: string(job)}
br := &fakeBridge{queue: map[string][]polled{"t-job": {tk}}, resolved: map[string]map[string]any{}, logs: map[string]string{},
cancelled: map[string]bool{}}
srv := httptest.NewServer(br.handler())
defer srv.Close()
var logged []string
var logMu sync.Mutex
r, err := New(Config{
Bridge: srv.URL, Token: "WT", Tasks: []string{"t-job"}, MaxTasks: 1,
WorkDir: t.TempDir(), Checkout: appCheckout{}, Heartbeat: 100 * time.Millisecond,
Logf: func(f string, a ...any) { logMu.Lock(); logged = append(logged, f); logMu.Unlock() },
})
if err != nil {
t.Fatal(err)
}
ctx, cancel := context.WithCancel(context.Background())
done := make(chan struct{})
go func() { r.Run(ctx); close(done) }()
// Let it start, then cancel the run.
time.Sleep(500 * time.Millisecond)
br.mu.Lock()
br.cancelled["doomed"] = true
br.mu.Unlock()
cancelledAt := time.Now()
stopped := false
for deadline := time.Now().Add(15 * time.Second); time.Now().Before(deadline); time.Sleep(50 * time.Millisecond) {
br.mu.Lock()
l := br.logs["doomed"]
br.mu.Unlock()
if strings.Contains(l, "stopped: this task's run was cancelled") {
stopped = true
break
}
}
took := time.Since(cancelledAt)
cancel()
<-done
if !stopped {
t.Fatalf("FAIL: the task did not stop within 15s of its run being cancelled")
}
if took > 8*time.Second {
t.Errorf("FAIL: stopping took %s; want it within a few heartbeats", took)
}
br.mu.Lock()
defer br.mu.Unlock()
if strings.Contains(br.logs["doomed"], "ran-to-42") {
t.Error("FAIL: the job ran to its end")
}
for _, a := range br.actions {
if a == "doomed complete" || a == "doomed fail" {
t.Errorf("FAIL: the runner reported %q for a withdrawn task", a)
}
}
t.Logf("ok: stopped %s after its run was cancelled, reported nothing", took.Round(10*time.Millisecond))
}
// A LOG UPLOAD REFUSED FOR GOOD STOPS THE RUNNING TASK IMMEDIATELY.
//
// Heartbeat is set to an hour so only the log upload's 409 can stop the
// task. The slot must be freed quickly and the next task must run.
func TestALogUploadRefusalStopsTheTask(t *testing.T) {
job1, _ := json.Marshal(Job{Steps: []JobStep{{Run: "i=0; while [ $i -lt 60 ]; do echo tick-$i; sleep 0.2; i=$((i+1)); done"}}})
doomed := task("doomed", "c1")
doomed.Metadata = map[string]string{JobKey: string(job1)}
job2, _ := json.Marshal(Job{Steps: []JobStep{{Run: "true"}}})
next := task("next", "c2")
next.Metadata = map[string]string{JobKey: string(job2)}
br := &fakeBridge{
queue: map[string][]polled{"t-job": {doomed, next}},
resolved: map[string]map[string]any{},
logs: map[string]string{},
}
inner := br.handler()
var rejectLogs sync.Mutex
refuse := false
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
if req.URL.Path == "/v1/tasks/doomed/logs" {
rejectLogs.Lock()
r := refuse
rejectLogs.Unlock()
if r {
w.Header().Set(cibridge.ReasonHeader, cibridge.ReasonTaskResolved)
w.WriteHeader(http.StatusConflict)
return
}
}
inner.ServeHTTP(w, req)
}))
defer srv.Close()
r, err := New(Config{
Bridge: srv.URL, Token: "WT", Tasks: []string{"t-job"}, MaxTasks: 1,
WorkDir: t.TempDir(), Checkout: appCheckout{}, Heartbeat: time.Hour,
Logf: func(string, ...any) {},
})
if err != nil {
t.Fatal(err)
}
ctx, cancel := context.WithCancel(context.Background())
done := make(chan struct{})
go func() { r.Run(ctx); close(done) }()
time.Sleep(600 * time.Millisecond)
rejectLogs.Lock()
refuse = true
rejectLogs.Unlock()
start := time.Now()
nextDone := false
for deadline := time.Now().Add(10 * time.Second); time.Now().Before(deadline); time.Sleep(30 * time.Millisecond) {
br.mu.Lock()
_, nextDone = br.resolved["next"]
br.mu.Unlock()
if nextDone {
break
}
}
took := time.Since(start)
cancel()
<-done
if !nextDone {
t.Fatalf("FAIL: the runner never freed the slot for the next task after log 409")
}
if took > 6*time.Second {
t.Errorf("FAIL: slot took %s to free after log 409; want it on the next flush", took.Round(10*time.Millisecond))
}
br.mu.Lock()
defer br.mu.Unlock()
if got := br.resolved["next"]["action"]; got != "complete" {
t.Errorf("FAIL: next task resolved %v, want complete", got)
}
for _, a := range br.actions {
if a == "doomed complete" || a == "doomed fail" {
t.Errorf("FAIL: reported %q for a cancelled task", a)
}
}
t.Logf("ok: stopped via log 409 and finished next task in %s", took.Round(10*time.Millisecond))
}
// CANCELLING A TASK KILLS ITS WHOLE PROCESS GROUP, SIGTERM-IGNORING GRANDCHILDREN INCLUDED.
func TestCancelKillsProcessGroupGrandchildren(t *testing.T) {
if runtime.GOOS == "windows" {
t.Skip("unix process groups")
}
dir := t.TempDir()
pidTmp := filepath.Join(dir, "grandchild.tmp")
pidFile := filepath.Join(dir, "grandchild.pid")
script := `sh -c 'trap "" TERM; echo $$ > "` + pidTmp + `"; mv "` + pidTmp + `" "` + pidFile + `"; exec sleep 60' & wait`
job, _ := json.Marshal(Job{Steps: []JobStep{{Run: script}}})
tk := task("pgid-job", "c1")
tk.Metadata = map[string]string{JobKey: string(job)}
br := &fakeBridge{
queue: map[string][]polled{"t-job": {tk}},
resolved: map[string]map[string]any{},
logs: map[string]string{},
cancelled: map[string]bool{},
}
srv := httptest.NewServer(br.handler())
defer srv.Close()
r, err := New(Config{
Bridge: srv.URL, Token: "WT", Tasks: []string{"t-job"}, MaxTasks: 1,
WorkDir: t.TempDir(), Checkout: appCheckout{}, Heartbeat: 100 * time.Millisecond,
Logf: func(string, ...any) {},
})
if err != nil {
t.Fatal(err)
}
ctx, cancel := context.WithCancel(context.Background())
done := make(chan struct{})
go func() { r.Run(ctx); close(done) }()
var childPID int
for deadline := time.Now().Add(10 * time.Second); time.Now().Before(deadline); time.Sleep(30 * time.Millisecond) {
raw, err := os.ReadFile(pidFile)
if err == nil {
if n, perr := strconv.Atoi(strings.TrimSpace(string(raw))); perr == nil && n > 0 {
childPID = n
break
}
}
}
if childPID == 0 {
cancel()
<-done
t.Fatal("FAIL: grandchild never wrote its pid")
}
br.mu.Lock()
br.cancelled["pgid-job"] = true
br.mu.Unlock()
dead := false
for deadline := time.Now().Add(10 * time.Second); time.Now().Before(deadline); time.Sleep(50 * time.Millisecond) {
if !pidAlive(childPID) {
dead = true
break
}
}
cancel()
<-done
if !dead {
t.Fatalf("FAIL: SIGTERM-ignoring grandchild pid %d survived task cancellation", childPID)
}
t.Logf("ok: SIGTERM-ignoring grandchild pid %d killed with process group", childPID)
}