| new file mode 100644 |
| index 000000000..ecc23e780 |
| --- /dev/null |
| +++ b/cmd/carlos-media/deadline_test.go |
| @@ -0,0 +1,301 @@ |
| +package main |
| + |
| +import ( |
| + "bytes" |
| + "go/ast" |
| + "go/parser" |
| + "go/token" |
| + "os" |
| + "strconv" |
| + "syscall" |
| + "testing" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/media" |
| +) |
| + |
| +// fakeStart is the clock the tests hand runDeadline as its start. |
| +var fakeStart = time.Unix(1_800_000_000, 0) |
| + |
| +func fixedNow() time.Time { return fakeStart } |
| + |
| +func env(deadline, expiry string) func(string) string { |
| + return func(k string) string { |
| + switch k { |
| + case media.DeadlineEnv: |
| + return deadline |
| + case media.ExpiryEnv: |
| + return expiry |
| + } |
| + return "" |
| + } |
| +} |
| + |
| +func unix(t time.Time) string { return strconv.FormatInt(t.Unix(), 10) } |
| + |
| +// preStopped is a stop channel already holding SIGTERM. A call that |
| +// should return at once must not reach the wait: if it did, it would |
| +// answer DeadlineExitStopped instead. |
| +func preStopped() chan os.Signal { |
| + c := make(chan os.Signal, 1) |
| + c <- syscall.SIGTERM |
| + return c |
| +} |
| + |
| +// await runs runDeadline in the background and gives its answer, failing |
| +// the test if none comes within limit. |
| +func await(t *testing.T, limit time.Duration, getenv func(string) string, now func() time.Time, stop <-chan os.Signal) (int, time.Duration) { |
| + t.Helper() |
| + done := make(chan int, 1) |
| + began := time.Now() |
| + go func() { done <- runDeadline(getenv, now, stop) }() |
| + select { |
| + case code := <-done: |
| + return code, time.Since(began) |
| + case <-time.After(limit): |
| + t.Fatalf("runDeadline did not return within %s", limit) |
| + return 0, 0 |
| + } |
| +} |
| + |
| +// 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. |
| +func TestDeadlineExitsAtOnceWhenExpired(t *testing.T) { |
| + for _, c := range []struct{ name, expiry string }{ |
| + {"long past", "1"}, |
| + {"an hour ago", unix(fakeStart.Add(-time.Hour))}, |
| + {"exactly the grace away", unix(fakeStart.Add(media.StopGrace))}, |
| + {"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 { |
| + 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. |
| +func TestDeadlineBadInput(t *testing.T) { |
| + future := unix(fakeStart.Add(time.Hour)) |
| + for _, c := range []struct{ name, deadline, expiry string }{ |
| + {"empty deadline", "", future}, |
| + {"zero deadline", "0", future}, |
| + {"deadline over 3000", "3001", future}, |
| + {"negative deadline", "-5", future}, |
| + {"exponent deadline", "1e3", future}, |
| + {"signed deadline", "+5", future}, |
| + {"padded deadline", "05", future}, |
| + {"spaced deadline", " 5", future}, |
| + {"fractional deadline", "5.0", future}, |
| + {"huge deadline", "99999999999999999999", future}, |
| + {"unit deadline", "900s", future}, |
| + {"non-number expiry", "900", "soon"}, |
| + {"empty expiry", "900", ""}, |
| + {"zero expiry", "900", "0"}, |
| + {"negative expiry", "900", "-1"}, |
| + {"signed expiry", "900", "+" + future}, |
| + {"padded expiry", "900", "0" + future}, |
| + {"RFC 3339 expiry", "900", fakeStart.Add(time.Hour).UTC().Format(time.RFC3339)}, |
| + {"milliseconds expiry", "900", strconv.FormatInt(fakeStart.Add(time.Hour).UnixMilli(), 10)}, |
| + {"expiry past year 9999", "900", strconv.FormatInt(maxExpiryUnix+1, 10)}, |
| + {"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 { |
| + 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) |
| + } |
| + } |
| +} |
| + |
| +// TestDeadlineAcceptsTheBounds: the edges of the valid ranges reach the |
| +// wait (and so answer the pending SIGTERM with 143). |
| +func TestDeadlineAcceptsTheBounds(t *testing.T) { |
| + far := strconv.FormatInt(maxExpiryUnix, 10) |
| + for _, c := range []struct{ name, deadline, expiry string }{ |
| + {"deadline 1", "1", far}, |
| + {"deadline 3000", "3000", far}, |
| + {"expiry at year 9999", "900", far}, |
| + {"expiry an hour on", "900", unix(fakeStart.Add(time.Hour))}, |
| + } { |
| + if code, _ := await(t, 5*time.Second, env(c.deadline, c.expiry), fixedNow, preStopped()); code != media.DeadlineExitStopped { |
| + t.Errorf("%s: exit %d, want %d (the wait)", c.name, code, media.DeadlineExitStopped) |
| + } |
| + } |
| +} |
| + |
| +// TestDeadlineStopped: SIGTERM during the wait (ECS stopping the task |
| +// because codec finished) exits 143, which the console does not read as |
| +// deadline_exceeded. |
| +func TestDeadlineStopped(t *testing.T) { |
| + stop := make(chan os.Signal, 1) |
| + done := make(chan int, 1) |
| + go func() { done <- runDeadline(env("3000", unix(fakeStart.Add(time.Hour))), fixedNow, stop) }() |
| + stop <- syscall.SIGTERM |
| + select { |
| + case code := <-done: |
| + if code != media.DeadlineExitStopped { |
| + t.Fatalf("exit %d, want %d", code, media.DeadlineExitStopped) |
| + } |
| + case <-time.After(5 * time.Second): |
| + t.Fatal("runDeadline did not return on SIGTERM") |
| + } |
| + if got := media.ClassifyStop("", nil, ptr(media.DeadlineExitStopped)); got == media.CodeDeadlineExceeded { |
| + t.Fatalf("a stopped deadline classifies as %s", got) |
| + } |
| +} |
| + |
| +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. |
| +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 { |
| + t.Fatalf("exit %d, want %d", code, media.DeadlineExitReached) |
| + } |
| + if took < time.Second { |
| + t.Fatalf("returned after %s, before the 1 s deadline", took) |
| + } |
| + if got := media.ClassifyStop("", nil, ptr(code)); got != media.CodeDeadlineExceeded { |
| + t.Fatalf("a reached deadline classifies as %s, want %s", got, media.CodeDeadlineExceeded) |
| + } |
| +} |
| + |
| +// 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 { |
| + 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) |
| + } |
| +} |
| + |
| +// 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 |
| + now := func() time.Time { |
| + calls++ |
| + return fakeStart.Add(time.Duration(calls-1) * 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) |
| + } |
| + if calls != 1 { |
| + t.Fatalf("now called %d times, want 1", calls) |
| + } |
| +} |
| + |
| +// TestDeadlineDispatch: the binary's "deadline" command takes no |
| +// argument and reads only the environment, and prints nothing. Other |
| +// commands, and none, are refused with the usage line. |
| +func TestDeadlineDispatch(t *testing.T) { |
| + run := func(env1, env2 string, args ...string) (int, string, string) { |
| + t.Setenv(media.DeadlineEnv, env1) |
| + t.Setenv(media.ExpiryEnv, env2) |
| + var stdout, stderr bytes.Buffer |
| + done := make(chan int, 1) |
| + go func() { done <- dispatch(args, &stdout, &stderr) }() |
| + select { |
| + case code := <-done: |
| + return code, stdout.String(), stderr.String() |
| + case <-time.After(5 * time.Second): |
| + t.Fatalf("dispatch(%q) did not return within 5 s", args) |
| + return 0, "", "" |
| + } |
| + } |
| + for _, c := range []struct { |
| + name, deadline, expiry string |
| + args []string |
| + want int |
| + }{ |
| + // Neither variable set: bad input. |
| + {"unset", "", "", []string{media.DeadlineCommand}, media.DeadlineExitBadInput}, |
| + // An expired grant: os.Getenv reached runDeadline. |
| + {"expired", "900", "1", []string{media.DeadlineCommand}, media.DeadlineExitReached}, |
| + // The same values with an argument: refused before reading them. |
| + {"an argument", "900", "1", []string{media.DeadlineCommand, "900"}, media.DeadlineExitBadInput}, |
| + } { |
| + code, out, errOut := run(c.deadline, c.expiry, c.args...) |
| + if code != c.want { |
| + t.Errorf("%s: dispatch(%q) = %d, want %d", c.name, c.args, code, c.want) |
| + } |
| + if out != "" || errOut != "" { |
| + t.Errorf("%s: dispatch(%q) printed %q / %q, want nothing", c.name, c.args, out, errOut) |
| + } |
| + } |
| + for _, args := range [][]string{nil, {"sleep"}, {"Deadline"}, {""}} { |
| + code, out, errOut := run("900", "1", args...) |
| + if code != exitUsage || out != "" || errOut != usageLine+"\n" { |
| + t.Errorf("dispatch(%q) = %d, %q / %q; want %d and the usage line", args, code, out, errOut, exitUsage) |
| + } |
| + } |
| +} |
| + |
| +// TestDeadlineCommandMatchesTheGate: the command the binary answers to |
| +// is the one the refusal gate requires. |
| +func TestDeadlineCommandMatchesTheGate(t *testing.T) { |
| + if media.EngineEntryPoint != "/usr/local/bin/carlos-media" || media.DeadlineCommand != "deadline" { |
| + t.Fatalf("gate expects %s %s; this binary is carlos-media deadline", media.EngineEntryPoint, media.DeadlineCommand) |
| + } |
| +} |
| + |
| +// TestDeadlineFilePrintsAndListensOnNothing: deadline.go imports only |
| +// what a timer needs and never names stdout or stderr (spec §5.5: |
| +// deadline listens on nothing). |
| +func TestDeadlineFilePrintsAndListensOnNothing(t *testing.T) { |
| + f, err := parser.ParseFile(token.NewFileSet(), "deadline.go", nil, parser.ImportsOnly|parser.ParseComments) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + allowed := map[string]bool{ |
| + `"os"`: true, `"strconv"`: true, `"time"`: true, |
| + `"github.com/carlosframework/platform/internal/media"`: true, |
| + } |
| + for _, imp := range f.Imports { |
| + if !allowed[imp.Path.Value] { |
| + t.Errorf("deadline.go imports %s", imp.Path.Value) |
| + } |
| + } |
| + full, err := parser.ParseFile(token.NewFileSet(), "deadline.go", nil, 0) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + ast.Inspect(full, func(n ast.Node) bool { |
| + switch x := n.(type) { |
| + case *ast.SelectorExpr: |
| + if id, ok := x.X.(*ast.Ident); ok && id.Name == "os" && x.Sel.Name != "Signal" { |
| + t.Errorf("deadline.go uses os.%s", x.Sel.Name) |
| + } |
| + case *ast.Ident: |
| + if x.Name == "print" || x.Name == "println" { |
| + t.Errorf("deadline.go calls %s", x.Name) |
| + } |
| + } |
| + return true |
| + }) |
| +} |