media: contain the local codec, keep the runner test-only
Astra T13 round 1, on 8f817127. The runner stays a test harness: it now contains the codec itself, and the package doc names what it does not contain. A descendant that leaves the codec's process group or session outlives Stop, the deadline and the runner. Production containment is the ECS task, or the systemd unit's cgroup (spec section 8). - Every SIGTERM and SIGKILL goes to the codec pid as well as its group, so a codec that joins another group still ends (TestRunnerDeadlineEndsACodecThatMovedGroup). - The codec has Pdeathsig SIGKILL. It is started on a thread the runner locks and holds until the reap, never on Run's caller's (TestRunnerCodecDiesWithTheRunner, TestRunnerCodecOutlivesItsCallersThread). - TestMedialocalIsTestOnly fails any non-test package that imports internal/medialocal, on linux, darwin and windows. - The handler's comment on CARLOS_MEDIA_FFMPEG/FFPROBE says the console never sets them, but the gate does not read container environment.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
6 files changed,
+329
−54
internal/mediahandler/handler.go+10 −6internal/medialocal/runner.go+59 −25internal/medialocal/runner_linux.go+11 −6internal/medialocal/runner_other.go+1 −1internal/medialocal/runner_test.go+190 −16internal/medialocal/testonly_test.go+58 −0
diff --git a/internal/mediahandler/handler.go b/internal/mediahandler/handler.go| index 904b6b4c2..4e51a1b4a 100644 |
| --- a/internal/mediahandler/handler.go |
| +++ b/internal/mediahandler/handler.go |
| @@ -33,12 +33,16 @@ const ScratchEnv = "CARLOS_MEDIA_SCRATCH" |
| // FFmpegEnv and FFprobeEnv name the ffmpeg and ffprobe binaries; unset, |
| // or not an absolute path, they are DefaultFFmpeg and DefaultFFprobe. |
| -// Only tests set them: the local runner's end-to-end test (plan 3 |
| -// Task 13) points them at a fake. In production nothing can: the task |
| -// definition gives the codec TMPDIR alone, the console's RunTask |
| -// overrides give it media.PayloadEnv alone (both pinned by their tests, |
| -// media_engine.tftest.hcl and TestRunTaskInput), and the image's |
| -// environment is its base image's. |
| +// Only tests are meant to set them: the local runner's end-to-end test |
| +// (plan 3 Task 13) points them at a fake. The console never does: the |
| +// media-engine module's task definitions give the codec TMPDIR alone, |
| +// the console's RunTask overrides give it media.PayloadEnv alone (both |
| +// pinned by their tests, media_engine.tftest.hcl and TestRunTaskInput), |
| +// and the image's environment is its base image's. That is convention, |
| +// not enforcement: a revision registered by hand could set them, since |
| +// the refusal gate (media.CheckTaskDefinition) does not read container |
| +// environment. Refusing them there is deferred hardening (plan 3 Task 13 |
| +// report). |
| const ( |
| FFmpegEnv = "CARLOS_MEDIA_FFMPEG" |
| FFprobeEnv = "CARLOS_MEDIA_FFPROBE" |
diff --git a/internal/medialocal/runner.go b/internal/medialocal/runner.go| index 77783c78f..0f362655a 100644 |
| --- a/internal/medialocal/runner.go |
| +++ b/internal/medialocal/runner.go |
| @@ -6,15 +6,28 @@ |
| // scratch directory of its own under the runner's scratch root, in its |
| // own process group, with only the environment the codec needs. The |
| // runner's own timer stands in for the deadline container: at |
| -// media.DeadlineSleep it sends SIGTERM to the codec's process group and, |
| -// Grace later, SIGKILL. When the codec ends for any reason, whatever is |
| -// left of its process group is killed, as a container's processes die |
| -// with it, and the codec is reaped. |
| +// media.DeadlineSleep it sends SIGTERM to the codec and its process |
| +// group and, Grace later, SIGKILL to both. When the codec ends for any |
| +// reason, whatever is left of its process group is killed, as a |
| +// container's processes die with it, and the codec is reaped. The codec |
| +// gets SIGKILL from the kernel if the runner dies first (Pdeathsig, on a |
| +// thread held from its start to its reap). |
| // |
| -// It is not wired into the console. A deployment on a MinIO-compatible |
| -// store would run the engine image as a one-shot container under |
| -// systemd, with RuntimeMaxSec as its deadline (spec §8); this runner is |
| -// that shape, for tests. |
| +// # Test-only, and what it does not contain |
| +// |
| +// This is a test harness, not a production engine, and |
| +// TestMedialocalIsTestOnly fails any non-test package that imports it. |
| +// It contains the codec itself: the codec cannot leave the signals by |
| +// moving to another process group, and cannot outlive the runner. It |
| +// does not contain the codec's descendants the way a container does. A |
| +// descendant that leaves the codec's process group or session (setpgid |
| +// into another group, setsid) is not signalled by Stop, the deadline or |
| +// Close, and one alive when the runner dies is not killed. Production |
| +// containment is not this package's: on AWS the ECS task ends every |
| +// process of the task, and a deployment without AWS runs the engine |
| +// image as a one-shot container under systemd, whose cgroup ends the |
| +// whole tree at RuntimeMaxSec (spec §8). This runner is that shape, for |
| +// tests of the codec and the job table. |
| package medialocal |
| import ( |
| @@ -24,6 +37,7 @@ import ( |
| "os" |
| "os/exec" |
| "path/filepath" |
| + "runtime" |
| "sort" |
| "sync" |
| "time" |
| @@ -138,21 +152,41 @@ func (r *Runner) Run(ctx context.Context, req media.RunRequest) (string, error) |
| Stderr: r.Log, |
| WaitDelay: waitDelay, |
| } |
| - if err := startCodec(cmd); err != nil { |
| - os.RemoveAll(scratch) |
| - return "", &media.Rejected{Reason: "the codec did not start: " + err.Error()} |
| - } |
| t := &task{ |
| arn: arnOf(req.Execution), execution: req.Execution, scratch: scratch, cmd: cmd, |
| - startedAt: time.Now(), |
| - stop: make(chan struct{}), kill: make(chan struct{}), done: make(chan struct{}), |
| + stop: make(chan struct{}), kill: make(chan struct{}), done: make(chan struct{}), |
| + } |
| + started := make(chan error, 1) |
| + go r.supervise(t, req, started) |
| + if err := <-started; err != nil { |
| + os.RemoveAll(scratch) |
| + return "", &media.Rejected{Reason: "the codec did not start: " + err.Error()} |
| } |
| + // watch's end takes r.mu, which this holds: the task is in the maps |
| + // before it can be described stopped. |
| r.tasks[t.arn], r.byExec[t.execution] = t, t |
| - sleep := media.DeadlineSleep(t.startedAt, time.Duration(req.DeadlineS)*time.Second, req.GrantExpiry) |
| - go r.watch(t, sleep) |
| return t.arn, nil |
| } |
| +// supervise starts the codec and watches it on one OS thread, held from |
| +// the start to the reap. The kernel sends the codec's parent-death |
| +// signal when the thread that started it exits, not the process (Go |
| +// ends a thread when a goroutine locked to it returns), so the codec is |
| +// started from a thread nothing else can end: it then gets SIGKILL only |
| +// when the runner's process dies. started answers the start. |
| +func (r *Runner) supervise(t *task, req media.RunRequest, started chan<- error) { |
| + runtime.LockOSThread() |
| + defer runtime.UnlockOSThread() |
| + if err := startCodec(t.cmd); err != nil { |
| + started <- err |
| + return |
| + } |
| + t.startedAt = time.Now() |
| + sleep := media.DeadlineSleep(t.startedAt, time.Duration(req.DeadlineS)*time.Second, req.GrantExpiry) |
| + started <- nil |
| + r.watch(t, sleep) |
| +} |
| + |
| // newScratch makes a fresh 0700 directory under root, with tmp in it |
| // (the codec's TMPDIR). |
| func newScratch(root string) (string, error) { |
| @@ -189,8 +223,8 @@ func codecEnv(extra []string, payload, scratch string) []string { |
| // watch is the task's deadline container and its end: the timer, Stop |
| // or Close end the codec; however it ends, the rest of its process |
| // group is killed, the codec reaped and the task described stopped. |
| -// Every signal to the group is sent from here, before the reap, so the |
| -// group's id cannot have been reused. |
| +// Every signal is sent from here, to the codec and to its group, before |
| +// the reap, so neither id can have been reused. |
| func (r *Runner) watch(t *task, sleep time.Duration) { |
| exited := make(chan struct{}) |
| pid := t.cmd.Process.Pid |
| @@ -211,10 +245,10 @@ func (r *Runner) watch(t *task, sleep time.Duration) { |
| r.end(t, exited) |
| case <-t.kill: |
| stopCode = StopUserInitiated |
| - signalGroup(pid, sigKill) |
| + signalCodec(pid, sigKill) |
| <-exited |
| } |
| - signalGroup(pid, sigKill) |
| + signalCodec(pid, sigKill) |
| _ = t.cmd.Wait() // the exit is read from ProcessState |
| code := exitCode(t.cmd.ProcessState) |
| r.mu.Lock() |
| @@ -224,11 +258,11 @@ func (r *Runner) watch(t *task, sleep time.Duration) { |
| close(t.done) |
| } |
| -// end is SIGTERM to the codec's process group, then SIGKILL after the |
| -// grace (at once on Close), and the codec's exit. |
| +// end is SIGTERM to the codec and its process group, then SIGKILL after |
| +// the grace (at once on Close), and the codec's exit. |
| func (r *Runner) end(t *task, exited <-chan struct{}) { |
| pid := t.cmd.Process.Pid |
| - signalGroup(pid, sigTerm) |
| + signalCodec(pid, sigTerm) |
| grace := time.NewTimer(r.grace()) |
| defer grace.Stop() |
| select { |
| @@ -237,7 +271,7 @@ func (r *Runner) end(t *task, exited <-chan struct{}) { |
| case <-grace.C: |
| case <-t.kill: |
| } |
| - signalGroup(pid, sigKill) |
| + signalCodec(pid, sigKill) |
| <-exited |
| } |
| @@ -343,7 +377,7 @@ func (r *Runner) Wait(ctx context.Context, arn string) error { |
| } |
| } |
| -// Close kills every task still running (SIGKILL to its process group, no |
| +// Close kills every task still running (SIGKILL to the codec and its process group, no |
| // grace), waits for each to be reaped and removes every scratch |
| // directory. Run refuses afterwards. |
| func (r *Runner) Close() error { |
diff --git a/internal/medialocal/runner_linux.go b/internal/medialocal/runner_linux.go| index c4d185ce2..2bcfe0c57 100644 |
| --- a/internal/medialocal/runner_linux.go |
| +++ b/internal/medialocal/runner_linux.go |
| @@ -17,17 +17,22 @@ const ( |
| ) |
| // startCodec starts cmd as the leader of a process group of its own, so |
| -// the runner can signal everything the codec starts in it. |
| +// the runner can signal everything the codec starts in it, with SIGKILL |
| +// as its parent-death signal: the kernel kills the codec when the |
| +// starting thread exits, which supervise holds until the reap, so only |
| +// the runner's death ends it that way. The caller holds the thread. |
| func startCodec(cmd *exec.Cmd) error { |
| - cmd.SysProcAttr = &syscall.SysProcAttr{Setpgid: true} |
| + cmd.SysProcAttr = &syscall.SysProcAttr{Setpgid: true, Pdeathsig: syscall.SIGKILL} |
| return cmd.Start() |
| } |
| -// signalGroup sends sig to the process group whose leader is pid. The |
| -// codec is not reaped yet when this is called, so the group's id is |
| -// still its own. |
| -func signalGroup(pid int, sig unix.Signal) { |
| +// signalCodec sends sig to the codec itself and to the process group it |
| +// leads: a codec that moved to another group is still signalled, and |
| +// what it left in its own group too. The codec is not reaped yet when |
| +// this is called, so neither id can have been reused. |
| +func signalCodec(pid int, sig unix.Signal) { |
| _ = unix.Kill(-pid, sig) |
| + _ = unix.Kill(pid, sig) |
| } |
| // waitExited blocks until pid has exited, without reaping it: the |
diff --git a/internal/medialocal/runner_other.go b/internal/medialocal/runner_other.go| index 96e7c3a4a..79d41df98 100644 |
| --- a/internal/medialocal/runner_other.go |
| +++ b/internal/medialocal/runner_other.go |
| @@ -22,7 +22,7 @@ func startCodec(*exec.Cmd) error { |
| return errors.New("the local media runner runs only on Linux") |
| } |
| -func signalGroup(int, signal) {} |
| +func signalCodec(int, signal) {} |
| func waitExited(int) {} |
diff --git a/internal/medialocal/runner_test.go b/internal/medialocal/runner_test.go| index b83a0a426..149ffd9fe 100644 |
| --- a/internal/medialocal/runner_test.go |
| +++ b/internal/medialocal/runner_test.go |
| @@ -13,6 +13,7 @@ import ( |
| "os/exec" |
| "os/signal" |
| "path/filepath" |
| + "runtime" |
| "slices" |
| "strconv" |
| "strings" |
| @@ -32,6 +33,9 @@ import ( |
| // place of the tests. |
| const fakeEnv = "MEDIALOCAL_FAKE" |
| +// runnerRootEnv is the runner scenario's scratch root. |
| +const runnerRootEnv = "MEDIALOCAL_RUNNER_ROOT" |
| + |
| func TestMain(m *testing.M) { |
| if scenario := os.Getenv(fakeEnv); scenario != "" { |
| os.Exit(fakeCodec(scenario)) |
| @@ -44,7 +48,15 @@ func TestMain(m *testing.M) { |
| // - ignore-term: starts a grandchild in its own process group that |
| // ignores SIGTERM too, prints "codec <pid>" and "grandchild <pid>" |
| // on stdout, which both hold open, and blocks ignoring SIGTERM. |
| -// - grandchild: ignore-term's child: blocks ignoring SIGTERM. |
| +// - grandchild: ignore-term's and move-group's child: blocks ignoring |
| +// SIGTERM. |
| +// - move-group: starts a grandchild leading a process group of its |
| +// own, with nothing of the codec's stdout, moves itself into that |
| +// group, prints both pids and blocks ignoring SIGTERM: the runner's |
| +// group signal no longer reaches it. |
| +// - alone: prints "codec <pid>" and blocks ignoring SIGTERM. |
| +// - runner: the test binary as a runner of one alone execution, the |
| +// codec's output on its own stdout; it waits to be killed. |
| // - scratch: writes a file named after its payload in its scratch |
| // directory and in TMPDIR, each created, never replaced, then exits 0. |
| // - env: prints its arguments, then its environment, one a line. |
| @@ -66,6 +78,50 @@ func fakeCodec(scenario string) int { |
| return blockIgnoringTerm() |
| case "grandchild": |
| return blockIgnoringTerm() |
| + case "move-group": |
| + // A grandchild leads a group of its own and holds nothing of the |
| + // codec's; the codec then joins that group, leaving the one the |
| + // runner made for it, and blocks ignoring SIGTERM. |
| + exe, err := os.Executable() |
| + if err != nil { |
| + return 1 |
| + } |
| + g := exec.Command(exe) |
| + g.Env = append(os.Environ(), fakeEnv+"=grandchild") |
| + g.SysProcAttr = &syscall.SysProcAttr{Setpgid: true} |
| + if err := g.Start(); err != nil { |
| + return 1 |
| + } |
| + fmt.Printf("grandchild %d\n", g.Process.Pid) |
| + if err := unix.Setpgid(0, g.Process.Pid); err != nil { |
| + fmt.Fprintln(os.Stderr, "fake: setpgid:", err) |
| + return 4 |
| + } |
| + if pgid, _ := unix.Getpgid(0); pgid != g.Process.Pid { |
| + return 5 |
| + } |
| + fmt.Printf("codec %d\n", os.Getpid()) |
| + return blockIgnoringTerm() |
| + case "alone": |
| + fmt.Printf("codec %d\n", os.Getpid()) |
| + return blockIgnoringTerm() |
| + case "runner": |
| + // The test binary as a runner: one execution of the alone codec, |
| + // its output on this process's stdout, then it waits to be killed. |
| + exe, err := os.Executable() |
| + if err != nil { |
| + return 1 |
| + } |
| + r := New(exe, os.Getenv(runnerRootEnv)) |
| + r.Env = []string{fakeEnv + "=alone"} |
| + r.Log = os.Stdout |
| + if _, err := r.Run(context.Background(), media.RunRequest{ |
| + Execution: "exec-orphan", Payload: []byte("job"), DeadlineS: 600, GrantExpiry: time.Now().Add(time.Hour), |
| + }); err != nil { |
| + fmt.Fprintln(os.Stderr, "fake runner:", err) |
| + return 1 |
| + } |
| + return blockIgnoringTerm() |
| case "scratch": |
| name := os.Getenv(media.PayloadEnv) |
| // The handler's own rule: the scratch is CARLOS_MEDIA_SCRATCH, |
| @@ -124,16 +180,16 @@ func newTestRunner(t *testing.T, scenario string) *Runner { |
| return r |
| } |
| -// ignoring is a running ignore-term codec: the pids it printed, and a |
| -// channel closed once every process holding its stdout has exited. |
| +// ignoring is a running fake codec: the pids it printed (grandchild 0 |
| +// when it has none), and a channel closed once every process holding |
| +// its stdout has exited. |
| type ignoring struct { |
| codec, grandchild int |
| gone chan struct{} |
| } |
| -// runIgnoring starts an ignore-term execution with deadlineS and reads |
| -// its two pids. Either process still alive when the test ends gets |
| -// SIGKILL. |
| +// runIgnoring starts an execution of r's scenario with deadlineS and |
| +// reads its pids (watchOutput). |
| func runIgnoring(t *testing.T, r *Runner, execution string, deadlineS int64) (string, ignoring) { |
| t.Helper() |
| pr, pw, err := os.Pipe() |
| @@ -144,11 +200,20 @@ func runIgnoring(t *testing.T, r *Runner, execution string, deadlineS int64) (st |
| arn, err := r.Run(context.Background(), media.RunRequest{ |
| Execution: execution, Payload: []byte("job"), DeadlineS: deadlineS, GrantExpiry: time.Now().Add(time.Hour), |
| }) |
| - pw.Close() // the codec and its grandchild hold their own copies |
| + pw.Close() // the codec and its descendants hold their own copies |
| if err != nil { |
| pr.Close() |
| t.Fatalf("Run: %v", err) |
| } |
| + return arn, watchOutput(t, pr) |
| +} |
| + |
| +// watchOutput reads a fake codec's pids from pr, up to its "codec <pid>" |
| +// line, then drains pr: gone closes at its EOF, once every process |
| +// holding the write end has exited. The codec and any grandchild still |
| +// alive when the test ends get SIGKILL. |
| +func watchOutput(t *testing.T, pr *os.File) ignoring { |
| + t.Helper() |
| ig := ignoring{gone: make(chan struct{})} |
| pids := make(chan [2]int, 1) |
| go func() { |
| @@ -156,13 +221,17 @@ func runIgnoring(t *testing.T, r *Runner, execution string, deadlineS int64) (st |
| defer pr.Close() |
| var got [2]int |
| sc := bufio.NewScanner(pr) |
| - for n := 0; n < 2 && sc.Scan(); n++ { |
| + for sc.Scan() { |
| role, pid, _ := strings.Cut(sc.Text(), " ") |
| - i := 0 |
| + n, _ := strconv.Atoi(pid) |
| if role == "grandchild" { |
| - i = 1 |
| + got[1] = n |
| + continue |
| + } |
| + if role == "codec" { |
| + got[0] = n |
| + break |
| } |
| - got[i], _ = strconv.Atoi(pid) |
| } |
| pids <- got |
| io.Copy(io.Discard, pr) |
| @@ -171,16 +240,18 @@ func runIgnoring(t *testing.T, r *Runner, execution string, deadlineS int64) (st |
| case got := <-pids: |
| ig.codec, ig.grandchild = got[0], got[1] |
| case <-time.After(10 * time.Second): |
| - t.Fatal("the fake codec did not report its pids") |
| + t.Fatal("the fake codec did not report its pid") |
| } |
| - if ig.codec <= 0 || ig.grandchild <= 0 { |
| - t.Fatalf("pids %+v", ig) |
| + if ig.codec <= 0 { |
| + t.Fatalf("the fake codec ended before it reported its pid (grandchild %d)", ig.grandchild) |
| } |
| t.Cleanup(func() { |
| - _ = unix.Kill(ig.grandchild, unix.SIGKILL) |
| + if ig.grandchild > 0 { |
| + _ = unix.Kill(ig.grandchild, unix.SIGKILL) |
| + } |
| _ = unix.Kill(ig.codec, unix.SIGKILL) |
| }) |
| - return arn, ig |
| + return ig |
| } |
| // waitGone answers how long after since every process of ig exited, or |
| @@ -287,6 +358,109 @@ func TestRunnerStopEndsLikeTheTimer(t *testing.T) { |
| } |
| } |
| +// TestRunnerDeadlineEndsACodecThatMovedGroup: a codec that leaves the |
| +// process group the runner made for it, joining another, and ignores |
| +// SIGTERM is still gone within the deadline plus the grace plus 1 s: |
| +// the runner signals the codec itself as well as its group (Astra T13 |
| +// P1). Its grandchild, which left the group, is outside the runner's |
| +// scope (package doc) and is killed by the test. |
| +func TestRunnerDeadlineEndsACodecThatMovedGroup(t *testing.T) { |
| + r := newTestRunner(t, "move-group") |
| + r.Grace = time.Second |
| + const deadline = time.Second |
| + start := time.Now() |
| + arn, ig := runIgnoring(t, r, "exec-moved", int64(deadline/time.Second)) |
| + if ig.grandchild <= 0 { |
| + t.Fatalf("the fake reported no grandchild: %+v", ig) |
| + } |
| + waitGone(t, ig, start, deadline+r.Grace+time.Second, "moved group") |
| + waitTask(t, r, arn) |
| + task := describeOne(t, r, arn) |
| + if !task.Stopped || exitOf(task.DeadlineExit) != "0" || exitOf(task.CodecExit) != "137" { |
| + t.Fatalf("described %+v (codec %s, deadline %s)", task, exitOf(task.CodecExit), exitOf(task.DeadlineExit)) |
| + } |
| + reaped(t, ig.codec) |
| +} |
| + |
| +// TestRunnerCodecDiesWithTheRunner: a process running a runner is |
| +// killed with SIGKILL, so nothing of the runner's own runs; the codec it |
| +// started is gone within 5 s, as its parent-death signal (SIGKILL) |
| +// promises (Astra T13 P1). The codec's stdout is the test's pipe, whose |
| +// EOF is the codec's exit. |
| +func TestRunnerCodecDiesWithTheRunner(t *testing.T) { |
| + exe, err := os.Executable() |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + pr, pw, err := os.Pipe() |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + runner := exec.Command(exe) |
| + runner.Env = append(os.Environ(), fakeEnv+"=runner", runnerRootEnv+"="+t.TempDir()) |
| + runner.Stdout = pw |
| + if err := runner.Start(); err != nil { |
| + t.Fatal(err) |
| + } |
| + pw.Close() |
| + reapRunner := sync.OnceFunc(func() { _ = runner.Wait() }) |
| + t.Cleanup(func() { |
| + _ = runner.Process.Kill() |
| + reapRunner() |
| + }) |
| + ig := watchOutput(t, pr) |
| + if err := runner.Process.Signal(syscall.SIGKILL); err != nil { |
| + t.Fatal(err) |
| + } |
| + reapRunner() |
| + killed := time.Now() |
| + waitGone(t, ig, killed, 5*time.Second, "runner killed") |
| +} |
| + |
| +// TestRunnerCodecOutlivesItsCallersThread: a parent-death signal |
| +// follows the thread that started the child, and Go ends a thread when |
| +// a goroutine locked to it returns. Run is called from such goroutines, |
| +// which then return: every codec is still running a second later, since |
| +// the runner starts each on a thread of its own, held until the reap, |
| +// never on its caller's. There are four callers because Go parks the |
| +// main thread rather than end it, and at most one can have run there. |
| +func TestRunnerCodecOutlivesItsCallersThread(t *testing.T) { |
| + r := newTestRunner(t, "alone") |
| + var codecs []ignoring |
| + for i := range 4 { |
| + pr, pw, err := os.Pipe() |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + r.Log = pw |
| + called := make(chan error, 1) |
| + go func() { |
| + runtime.LockOSThread() // never unlocked: the thread ends with the goroutine |
| + _, err := r.Run(context.Background(), media.RunRequest{ |
| + Execution: fmt.Sprintf("exec-threads-%d", i), Payload: []byte("job"), DeadlineS: 600, GrantExpiry: time.Now().Add(time.Hour), |
| + }) |
| + called <- err |
| + }() |
| + err = <-called |
| + pw.Close() |
| + if err != nil { |
| + pr.Close() |
| + t.Fatalf("Run: %v", err) |
| + } |
| + codecs = append(codecs, watchOutput(t, pr)) |
| + } |
| + alive := time.NewTimer(time.Second) |
| + defer alive.Stop() |
| + <-alive.C |
| + for _, ig := range codecs { |
| + select { |
| + case <-ig.gone: |
| + t.Errorf("the codec %d died when the thread that called Run ended", ig.codec) |
| + default: // still running; Close kills it |
| + } |
| + } |
| +} |
| + |
| // entries lists dir's names, sorted; none when it does not exist. |
| func entries(t *testing.T, dir string) []string { |
| t.Helper() |
diff --git a/internal/medialocal/testonly_test.go b/internal/medialocal/testonly_test.go| new file mode 100644 |
| index 000000000..2d2d5c3e9 |
| --- /dev/null |
| +++ b/internal/medialocal/testonly_test.go |
| @@ -0,0 +1,58 @@ |
| +package medialocal |
| + |
| +import ( |
| + "os" |
| + "os/exec" |
| + "path/filepath" |
| + "runtime" |
| + "slices" |
| + "strings" |
| + "testing" |
| +) |
| + |
| +const ( |
| + modulePath = "github.com/carlosframework/platform" |
| + selfPath = modulePath + "/internal/medialocal" |
| +) |
| + |
| +// TestMedialocalIsTestOnly: no non-test package of the module imports |
| +// this one, on Linux, macOS or Windows. The runner contains the codec, |
| +// not its descendants (package doc): a descendant that leaves the |
| +// codec's process group or session outlives Stop, the deadline and the |
| +// runner. Production containment is the ECS task, or the systemd unit's |
| +// cgroup with RuntimeMaxSec on a deployment without AWS (spec §8), so |
| +// using the runner as a production engine needs that containment first, |
| +// and this guard removed on purpose. |
| +func TestMedialocalIsTestOnly(t *testing.T) { |
| + gobin := filepath.Join(runtime.GOROOT(), "bin", "go") |
| + if _, err := os.Stat(gobin); err != nil { |
| + if gobin, err = exec.LookPath("go"); err != nil { |
| + t.Skip("no go toolchain to list imports with") |
| + } |
| + } |
| + for _, target := range []string{"linux/amd64", "darwin/arm64", "windows/amd64"} { |
| + goos, goarch, _ := strings.Cut(target, "/") |
| + cmd := exec.Command(gobin, "list", "-e", "-f", "{{.ImportPath}} {{join .Imports \" \"}}", modulePath+"/...") |
| + cmd.Env = append(os.Environ(), "GOOS="+goos, "GOARCH="+goarch, "CGO_ENABLED=0") |
| + out, err := cmd.Output() |
| + if err != nil { |
| + t.Fatalf("go list (%s): %v", target, err) |
| + } |
| + lines := strings.Split(strings.TrimSpace(string(out)), "\n") |
| + if len(lines) < 10 { |
| + t.Fatalf("go list (%s) answered %d packages", target, len(lines)) |
| + } |
| + for _, line := range lines { |
| + fields := strings.Fields(line) |
| + if len(fields) == 0 || fields[0] == selfPath { |
| + continue |
| + } |
| + if slices.Contains(fields[1:], selfPath) { |
| + t.Errorf("%s: %s imports internal/medialocal. The local runner is a test harness: a "+ |
| + "codec's descendant that leaves its process group or session outlives Stop, the "+ |
| + "deadline and the runner itself. Production containment is the ECS task or a systemd "+ |
| + "unit's cgroup (spec §8). Use it only from tests.", target, fields[0]) |
| + } |
| + } |
| + } |
| +} |