| index ecc23e780..0e8f376b5 100644 |
| --- a/cmd/carlos-media/deadline_test.go |
| +++ b/cmd/carlos-media/deadline_test.go |
| @@ -1,12 +1,17 @@ |
| package main |
| |
| import ( |
| + "bufio" |
| "bytes" |
| "go/ast" |
| "go/parser" |
| "go/token" |
| + "io" |
| "os" |
| + "os/exec" |
| + "runtime" |
| "strconv" |
| + "sync/atomic" |
| "syscall" |
| "testing" |
| "time" |
| @@ -61,8 +66,9 @@ func await(t *testing.T, limit time.Duration, getenv func(string) string, now fu |
| // TestDeadlineExitsAtOnceWhenExpired: when the expiry less the stop grace |
| // is at or before the start, the container exits 0 at once (spec §5.5, |
| // astra R7-1: a task that waited in PENDING past its grant never |
| -// converts). Repeated so that a version which reaches the wait with a |
| -// zero timer and a pending SIGTERM would answer 143 at least once. |
| +// converts). The stop channel already holds SIGTERM, so a version that |
| +// reached the wait could answer 143; repeated so that a zero timer racing |
| +// that SIGTERM would lose at least once. |
| func TestDeadlineExitsAtOnceWhenExpired(t *testing.T) { |
| for _, c := range []struct{ name, expiry string }{ |
| {"long past", "1"}, |
| @@ -71,22 +77,16 @@ func TestDeadlineExitsAtOnceWhenExpired(t *testing.T) { |
| {"inside the grace", unix(fakeStart.Add(media.StopGrace - time.Second))}, |
| } { |
| for range 20 { |
| - began := time.Now() |
| - code := runDeadline(env("3000", c.expiry), fixedNow, preStopped()) |
| - took := time.Since(began) |
| - if code != media.DeadlineExitReached { |
| + if code := runDeadline(env("3000", c.expiry), fixedNow, preStopped()); code != media.DeadlineExitReached { |
| t.Fatalf("%s: exit %d, want %d", c.name, code, media.DeadlineExitReached) |
| } |
| - if took > 10*time.Millisecond { |
| - t.Fatalf("%s: took %s, want at once", c.name, took) |
| - } |
| } |
| } |
| } |
| |
| // TestDeadlineBadInput: anything but a canonical decimal deadline in |
| -// 1..3000 and a canonical decimal expiry in 1..maxExpiryUnix exits 3 at |
| -// once, before any wait. |
| +// 1..3000 and a canonical decimal expiry in 1..maxExpiryUnix exits 3 |
| +// before any wait (the pending SIGTERM would otherwise answer 143). |
| func TestDeadlineBadInput(t *testing.T) { |
| future := unix(fakeStart.Add(time.Hour)) |
| for _, c := range []struct{ name, deadline, expiry string }{ |
| @@ -113,18 +113,64 @@ func TestDeadlineBadInput(t *testing.T) { |
| {"int64 max expiry", "900", "9223372036854775807"}, |
| {"both empty", "", ""}, |
| } { |
| - began := time.Now() |
| - code := runDeadline(env(c.deadline, c.expiry), fixedNow, preStopped()) |
| - took := time.Since(began) |
| - if code != media.DeadlineExitBadInput { |
| + if code := runDeadline(env(c.deadline, c.expiry), fixedNow, preStopped()); code != media.DeadlineExitBadInput { |
| t.Errorf("%s (%q, %q): exit %d, want %d", c.name, c.deadline, c.expiry, code, media.DeadlineExitBadInput) |
| } |
| - if took > 10*time.Millisecond { |
| - t.Errorf("%s: took %s, want at once", c.name, took) |
| + } |
| +} |
| + |
| +// TestDeadlinePlanExact pins both sides of the bound: the sleep is |
| +// exactly the earlier of the relative deadline and the expiry less the |
| +// 30 s grace, never more, and the wall end is exactly the expiry less |
| +// the grace. |
| +func TestDeadlinePlanExact(t *testing.T) { |
| + hour := fakeStart.Add(time.Hour) |
| + for _, c := range []struct { |
| + name, deadline, expiry string |
| + want deadlinePlan |
| + }{ |
| + {"deadline 1", "1", unix(hour), deadlinePlan{Wait: true, Sleep: time.Second, WallEnd: hour.Add(-media.StopGrace)}}, |
| + {"deadline 3000", "3000", unix(hour), deadlinePlan{Wait: true, Sleep: 3000 * time.Second, WallEnd: hour.Add(-media.StopGrace)}}, |
| + {"expiry start+31s", "3000", unix(fakeStart.Add(31 * time.Second)), deadlinePlan{Wait: true, Sleep: time.Second, WallEnd: fakeStart.Add(time.Second)}}, |
| + {"expiry start+30s", "3000", unix(fakeStart.Add(30 * time.Second)), deadlinePlan{Exit: media.DeadlineExitReached}}, |
| + {"negative sleep", "3000", unix(fakeStart.Add(-time.Hour)), deadlinePlan{Exit: media.DeadlineExitReached}}, |
| + {"bad input", "3001", unix(hour), deadlinePlan{Exit: media.DeadlineExitBadInput}}, |
| + } { |
| + got := planDeadline(env(c.deadline, c.expiry), fixedNow) |
| + if got.Wait != c.want.Wait || got.Exit != c.want.Exit { |
| + t.Errorf("%s: wait %v exit %d, want wait %v exit %d", c.name, got.Wait, got.Exit, c.want.Wait, c.want.Exit) |
| + continue |
| + } |
| + if !c.want.Wait { |
| + continue |
| + } |
| + if got.Sleep != c.want.Sleep { |
| + t.Errorf("%s: sleep %s, want exactly %s", c.name, got.Sleep, c.want.Sleep) |
| + } |
| + if !got.WallEnd.Equal(c.want.WallEnd) { |
| + t.Errorf("%s: wall end %s, want %s", c.name, got.WallEnd, c.want.WallEnd) |
| } |
| } |
| } |
| |
| +// TestDeadlinePlanReadsTheClockOnce: the plan reads the start once. |
| +// (The wait then reads the wall clock on each tick, see |
| +// TestDeadlineWallClockJumpsForward.) |
| +func TestDeadlinePlanReadsTheClockOnce(t *testing.T) { |
| + calls := 0 |
| + now := func() time.Time { |
| + calls++ |
| + return fakeStart.Add(time.Duration(calls-1) * time.Hour) |
| + } |
| + p := planDeadline(env("900", unix(fakeStart.Add(time.Hour))), now) |
| + if calls != 1 { |
| + t.Fatalf("now called %d times, want 1", calls) |
| + } |
| + if !p.Wait || p.Sleep != 900*time.Second { |
| + t.Fatalf("plan %+v, want a 900 s wait from the first reading", p) |
| + } |
| +} |
| + |
| // TestDeadlineAcceptsTheBounds: the edges of the valid ranges reach the |
| // wait (and so answer the pending SIGTERM with 143). |
| func TestDeadlineAcceptsTheBounds(t *testing.T) { |
| @@ -165,7 +211,8 @@ func TestDeadlineStopped(t *testing.T) { |
| func ptr(v int) *int { return &v } |
| |
| // TestDeadlineReached: a 1 s deadline from the fake start returns 0 after |
| -// the timer, not before, with no SIGTERM. |
| +// the timer, not before, with no SIGTERM. The fake wall clock never |
| +// moves, so only the monotonic leg can end it. |
| func TestDeadlineReached(t *testing.T) { |
| code, took := await(t, 5*time.Second, env("1", unix(fakeStart.Add(time.Hour))), fixedNow, nil) |
| if code != media.DeadlineExitReached { |
| @@ -179,34 +226,177 @@ func TestDeadlineReached(t *testing.T) { |
| } |
| } |
| |
| -// TestDeadlineReachedAtExpiry: with a 3000 s deadline and the grant |
| -// expiring 31 s after the start, the sleep is the expiry less the 30 s |
| -// stop grace, 1 s. Fails (by the 5 s limit) if the expiry or the grace is |
| -// ignored. |
| -func TestDeadlineReachedAtExpiry(t *testing.T) { |
| - expiry := unix(fakeStart.Add(media.StopGrace + time.Second)) |
| - code, took := await(t, 5*time.Second, env("3000", expiry), fixedNow, nil) |
| - if code != media.DeadlineExitReached { |
| +// handClock is a wall clock the test answers by hand: each now() call |
| +// blocks until the test hands it a reading, so the test knows exactly |
| +// which reading each tick saw. |
| +type handClock chan time.Time |
| + |
| +func (c handClock) now() time.Time { return <-c } |
| + |
| +// read hands the wait's pending now() call the reading v. |
| +func (c handClock) read(t *testing.T, v time.Time) { |
| + t.Helper() |
| + select { |
| + case c <- v: |
| + case <-time.After(5 * time.Second): |
| + t.Fatalf("the wait did not read the clock (reading %s)", v) |
| + } |
| +} |
| + |
| +// tickOnce hands the wait one tick. The tick channel is unbuffered, so a |
| +// send that completes means the wait was still waiting. |
| +func tickOnce(t *testing.T, tick chan<- time.Time, what string) { |
| + t.Helper() |
| + select { |
| + case tick <- time.Time{}: |
| + case <-time.After(5 * time.Second): |
| + t.Fatalf("the wait had already returned before the tick %s", what) |
| + } |
| +} |
| + |
| +// startWait runs waitDeadline in the background. |
| +func startWait(p deadlinePlan, now func() time.Time, tick <-chan time.Time) <-chan int { |
| + done := make(chan int, 1) |
| + go func() { done <- waitDeadline(p, now, tick, nil) }() |
| + return done |
| +} |
| + |
| +func awaitCode(t *testing.T, done <-chan int, limit time.Duration, what string) int { |
| + t.Helper() |
| + select { |
| + case code := <-done: |
| + return code |
| + case <-time.After(limit): |
| + t.Fatalf("the wait did not return %s within %s", what, limit) |
| + return 0 |
| + } |
| +} |
| + |
| +// TestDeadlineWallClockJumpsForward: the wall clock jumps past the wall |
| +// end mid-wait (a forward step, or a VM resumed after a pause); the wait |
| +// exits 0 on the next tick, long before its hour-long monotonic timer. |
| +// A tick 1 ns before the wall end does not end it. |
| +func TestDeadlineWallClockJumpsForward(t *testing.T) { |
| + end := fakeStart.Add(time.Hour) |
| + c := make(handClock) |
| + tick := make(chan time.Time) |
| + done := startWait(deadlinePlan{Wait: true, Sleep: time.Hour, WallEnd: end}, c.now, tick) |
| + |
| + tickOnce(t, tick, "1 ns before the wall end") |
| + c.read(t, end.Add(-time.Nanosecond)) |
| + tickOnce(t, tick, "at the wall end") // completing proves the first tick did not end it |
| + c.read(t, end) |
| + if code := awaitCode(t, done, 5*time.Second, "at the wall end"); code != media.DeadlineExitReached { |
| t.Fatalf("exit %d, want %d", code, media.DeadlineExitReached) |
| } |
| - if took < time.Second { |
| - t.Fatalf("returned after %s, before the expiry less the grace", took) |
| +} |
| + |
| +// TestDeadlineWallClockStepsBack: a backward step cannot extend the run; |
| +// the monotonic timer still ends it. |
| +func TestDeadlineWallClockStepsBack(t *testing.T) { |
| + c := make(handClock) |
| + tick := make(chan time.Time) |
| + began := time.Now() |
| + done := startWait(deadlinePlan{Wait: true, Sleep: 200 * time.Millisecond, WallEnd: fakeStart.Add(time.Hour)}, c.now, tick) |
| + tickOnce(t, tick, "after the backward step") |
| + c.read(t, fakeStart.Add(-24*time.Hour)) |
| + if code := awaitCode(t, done, 5*time.Second, "on the monotonic timer"); code != media.DeadlineExitReached { |
| + t.Fatalf("exit %d, want %d", code, media.DeadlineExitReached) |
| + } |
| + if took := time.Since(began); took < 200*time.Millisecond { |
| + t.Fatalf("returned after %s, before the timer", took) |
| } |
| } |
| |
| -// TestDeadlineReadsTheClockOnce: the start is read once, before the |
| -// wait; a clock that moves on later calls changes nothing. |
| -func TestDeadlineReadsTheClockOnce(t *testing.T) { |
| - calls := 0 |
| +// TestDeadlineWallLegThroughRun: runDeadline itself ticks. The fake wall |
| +// clock reads the start once and then two hours on; with a 3000 s |
| +// deadline and an hour's grant, only the wall leg can end the run |
| +// within the 5 s limit (it ends after one wallCheckEvery). |
| +func TestDeadlineWallLegThroughRun(t *testing.T) { |
| + var calls atomic.Int64 |
| now := func() time.Time { |
| - calls++ |
| - return fakeStart.Add(time.Duration(calls-1) * time.Hour) |
| + if calls.Add(1) == 1 { |
| + return fakeStart |
| + } |
| + return fakeStart.Add(2 * time.Hour) |
| } |
| - if code, _ := await(t, 5*time.Second, env("900", unix(fakeStart.Add(time.Hour))), now, preStopped()); code != media.DeadlineExitStopped { |
| - t.Fatalf("exit %d, want %d", code, media.DeadlineExitStopped) |
| + code, _ := await(t, 5*time.Second, env("3000", unix(fakeStart.Add(time.Hour))), now, nil) |
| + if code != media.DeadlineExitReached { |
| + t.Fatalf("exit %d, want %d", code, media.DeadlineExitReached) |
| } |
| - if calls != 1 { |
| - t.Fatalf("now called %d times, want 1", calls) |
| +} |
| + |
| +// childEnv marks the re-executed test binary as the deadline command. |
| +const childEnv = "CARLOS_MEDIA_TEST_DEADLINE_CHILD" |
| + |
| +// TestDeadlineHelperProcess is the child of TestDeadlineSIGTERMProcess. |
| +// Run normally, it does nothing. |
| +func TestDeadlineHelperProcess(t *testing.T) { |
| + if os.Getenv(childEnv) != "1" { |
| + return |
| + } |
| + signalsReady = func() { os.Stdout.WriteString("ready\n") } |
| + os.Exit(dispatch([]string{media.DeadlineCommand}, io.Discard, io.Discard)) |
| +} |
| + |
| +// TestDeadlineSIGTERMProcess re-executes the test binary as `deadline` |
| +// with a 3000 s deadline, sends a real SIGTERM once the child has caught |
| +// it, and expects the process to exit 143 by its own exit, not to die of |
| +// the signal. It fails if signal.Notify is removed or names another |
| +// signal, because the Go runtime then dies of the SIGTERM. |
| +func TestDeadlineSIGTERMProcess(t *testing.T) { |
| + if runtime.GOOS == "windows" { |
| + t.Skip("no SIGTERM on Windows") |
| + } |
| + cmd := exec.Command(os.Args[0], "-test.run=^TestDeadlineHelperProcess$", "-test.count=1") |
| + cmd.Env = append(os.Environ(), childEnv+"=1", |
| + media.DeadlineEnv+"=3000", |
| + media.ExpiryEnv+"="+strconv.FormatInt(time.Now().Add(time.Hour).Unix(), 10)) |
| + out, err := cmd.StdoutPipe() |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := cmd.Start(); err != nil { |
| + t.Fatal(err) |
| + } |
| + t.Cleanup(func() { _ = cmd.Process.Kill() }) |
| + |
| + ready := make(chan bool, 1) |
| + go func() { |
| + sc := bufio.NewScanner(out) |
| + for sc.Scan() { |
| + if sc.Text() == "ready" { |
| + ready <- true |
| + return |
| + } |
| + } |
| + ready <- false |
| + }() |
| + select { |
| + case ok := <-ready: |
| + if !ok { |
| + t.Fatal("the child closed its stdout without catching SIGTERM") |
| + } |
| + case <-time.After(10 * time.Second): |
| + t.Fatal("the child did not reach the wait within 10 s") |
| + } |
| + |
| + if err := cmd.Process.Signal(syscall.SIGTERM); err != nil { |
| + t.Fatal(err) |
| + } |
| + waited := make(chan error, 1) |
| + go func() { waited <- cmd.Wait() }() |
| + select { |
| + case <-waited: |
| + case <-time.After(10 * time.Second): |
| + t.Fatal("the child did not exit within 10 s of SIGTERM") |
| + } |
| + st := cmd.ProcessState |
| + if ws, ok := st.Sys().(syscall.WaitStatus); ok && ws.Signaled() { |
| + t.Fatalf("the child died of %s; want exit %d through signal.Notify", ws.Signal(), media.DeadlineExitStopped) |
| + } |
| + if st.ExitCode() != media.DeadlineExitStopped { |
| + t.Fatalf("the child exited %d, want %d", st.ExitCode(), media.DeadlineExitStopped) |
| } |
| } |
| |