carlos / platform Public

media: local runner and the provider boundary guard

Plan 3 Task 13. internal/medialocal is media.Engine on local processes:
each execution runs `<binary> codec` in a fresh 0700 scratch directory
under the runner's root, in its own process group, with only
CARLOS_MEDIA_JOB, PATH, CARLOS_MEDIA_SCRATCH and TMPDIR (plus test
extras, which cannot replace those four). The runner's timer stands in
for the deadline container (media.DeadlineSleep; SIGTERM to the group,
SIGKILL after Grace, default media.StopGrace). However the codec ends,
the rest of its group is killed before it is reaped, and its scratch is
removed once Describe reports it stopped. Linux only; runner_other.go
answers a Rejected elsewhere. Not wired into the console.

TestCoreLinksNoCloudSDK lists the deps of internal/media/...,
mediajobs, mediahandler, medialocal, storecfg and cmd/carlos-media on
linux amd64 and arm64: nothing under github.com/aws/ or
internal/console, and the root binary links none of them.

Preflight F29: the handler's Config takes FFmpeg and FFprobe from
CARLOS_MEDIA_FFMPEG and CARLOS_MEDIA_FFPROBE (absolute paths only).
Production cannot set them: the task definition gives the codec TMPDIR
alone and the console's RunTask overrides give it the payload alone,
both pinned by existing tests.

TestLocalEndToEndMinio runs a job through mediajobs on this runner with
the real carlos-media on a fake ffmpeg built from testdata, and
mediaaws grants on temporary credentials from MinIO's STS (F10). It
runs in a new 30-minio-contract block with a user scoped to its two
buckets.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev pushed by paul@keymail.dev 8f817127a5ca669fc34e7ac3496cf5758f1c02d8 parent 559ac3e
12 files changed, +1,471 −6
  • .amadan/ci.d/30-minio-contract +44 −0
  • internal/media/boundary_test.go +84 −0
  • internal/mediahandler/download_test.go +16 −2
  • internal/mediahandler/handler.go +24 −2
  • internal/mediahandler/realffmpeg_test.go +2 −2
  • internal/medialocal/e2e_test.go +200 −0
  • internal/medialocal/minio_test.go +104 −0
  • internal/medialocal/runner.go +371 −0
  • internal/medialocal/runner_linux.go +52 −0
  • internal/medialocal/runner_other.go +29 −0
  • internal/medialocal/runner_test.go +453 −0
  • internal/medialocal/testdata/fakeffmpeg/main.go +92 −0

CI failed — run details

diff --git a/.amadan/ci.d/30-minio-contract b/.amadan/ci.d/30-minio-contract
index 028e53d47..7e11eb447 100755
--- a/.amadan/ci.d/30-minio-contract
+++ b/.amadan/ci.d/30-minio-contract
@@ -590,6 +590,50 @@ if ! grep -q '^--- PASS: TestMediaTransfersMinio (' "$out_media"; then
exit 1
fi
+# A whole media job on the local runner (media conversion plan 3, Task 13):
+# mediajobs with internal/medialocal as its engine, the real carlos-media
+# (built by the test, on a fake ffmpeg) as the codec, and mediaaws's grants
+# on temporary credentials from this server's STS, as above. The user gets
+# what the console and the narrowed sessions need and no more: list, read,
+# write and delete objects in its own store and results buckets.
+"$mc" --quiet mb local/media-local-store local/media-local-results
+cat >"$rundir/media-local.json" <<'EOF'
+{"Version": "2012-10-17", "Statement": [
+ {"Effect": "Allow", "Action": ["s3:ListBucket"], "Resource": [
+ "arn:aws:s3:::media-local-store", "arn:aws:s3:::media-local-results"
+ ]},
+ {"Effect": "Allow", "Action": ["s3:GetObject", "s3:PutObject", "s3:DeleteObject"], "Resource": [
+ "arn:aws:s3:::media-local-store/*", "arn:aws:s3:::media-local-results/*"
+ ]}
+]}
+EOF
+"$mc" --quiet admin policy create local media-local "$rundir/media-local.json"
+"$mc" --quiet admin user add local medialocal medialocalsecret1
+"$mc" --quiet admin policy attach local media-local --user medialocal
+
+out_local=$rundir/test-media-local.log
+set +e
+CARLOS_MINIO_TEST=1 \
+ MINIO_ENDPOINT="http://127.0.0.1:$port" \
+ MEDIA_LOCAL_KEY=medialocal \
+ MEDIA_LOCAL_SECRET=medialocalsecret1 \
+ MEDIA_LOCAL_BUCKET=media-local-store \
+ MEDIA_LOCAL_RESULTS=media-local-results \
+ go test ./internal/medialocal/ -run 'TestLocalEndToEndMinio' -count=1 -v >"$out_local" 2>&1
+test_status=$?
+set -e
+cat "$out_local"
+if [ "$test_status" -ne 0 ]; then
+ exit "$test_status"
+fi
+if ! grep -q '^--- PASS: TestLocalEndToEndMinio (' "$out_local"; then
+ echo >&2
+ echo "the local runner's MinIO test did not PASS: it was skipped, filtered out, or renamed." >&2
+ echo "It skips unless CARLOS_MINIO_TEST=1. Check the env block above and that" >&2
+ echo "TestLocalEndToEndMinio still exists in internal/medialocal." >&2
+ exit 1
+fi
+
# The planned handover witnesses (region HA §25.10, held-requests Task 8):
# two real activators and three real edges in one process, the HA lease,
# litestream replication and the files store against this MinIO, as the
diff --git a/internal/media/boundary_test.go b/internal/media/boundary_test.go
new file mode 100644
index 000000000..f82a9ab4a
--- /dev/null
+++ b/internal/media/boundary_test.go
@@ -0,0 +1,84 @@
+package media
+
+import (
+ "os"
+ "os/exec"
+ "path/filepath"
+ "runtime"
+ "strings"
+ "testing"
+)
+
+const modulePath = "github.com/carlosframework/platform"
+
+// corePackages are the provider-neutral core (spec §8, plan 3 Task 13):
+// none may link a cloud SDK or the console. internal/mediaaws is the
+// AWS adapter and is not among them.
+var corePackages = []string{
+ modulePath + "/internal/media/...",
+ modulePath + "/internal/mediajobs/...",
+ modulePath + "/internal/mediahandler/...",
+ modulePath + "/internal/medialocal/...",
+ modulePath + "/internal/storecfg/...",
+ modulePath + "/cmd/carlos-media",
+}
+
+// goList answers `go list -deps` of patterns for linux/arch with cgo
+// off: one import path a line.
+func goList(t *testing.T, arch string, patterns ...string) []string {
+ t.Helper()
+ 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 dependencies with")
+ }
+ }
+ cmd := exec.Command(gobin, append([]string{"list", "-deps"}, patterns...)...)
+ cmd.Env = append(os.Environ(), "GOOS=linux", "GOARCH="+arch, "CGO_ENABLED=0")
+ out, err := cmd.CombinedOutput()
+ if err != nil {
+ t.Fatalf("go list (%s): %v\n%s", arch, err, out)
+ }
+ return strings.Split(strings.TrimSpace(string(out)), "\n")
+}
+
+// coreMatch reports whether path is one of corePackages.
+func coreMatch(path string) bool {
+ for _, p := range corePackages {
+ if dir, ok := strings.CutSuffix(p, "/..."); ok {
+ if path == dir || strings.HasPrefix(path, dir+"/") {
+ return true
+ }
+ } else if path == p {
+ return true
+ }
+ }
+ return false
+}
+
+// TestCoreLinksNoCloudSDK: the core links no package under
+// github.com/aws/ and nothing of internal/console, on both
+// architectures the engine and the console run on; and the root binary
+// links none of the core (its census scope stays as it was).
+func TestCoreLinksNoCloudSDK(t *testing.T) {
+ console := modulePath + "/internal/console"
+ for _, arch := range []string{"amd64", "arm64"} {
+ deps := goList(t, arch, corePackages...)
+ if len(deps) < len(corePackages) {
+ t.Fatalf("linux/%s: go list answered %d packages", arch, len(deps))
+ }
+ for _, path := range deps {
+ if strings.HasPrefix(path, "github.com/aws/") {
+ t.Errorf("linux/%s: the media core links %s", arch, path)
+ }
+ if path == console || strings.HasPrefix(path, console+"/") {
+ t.Errorf("linux/%s: the media core links %s", arch, path)
+ }
+ }
+ for _, path := range goList(t, arch, modulePath) {
+ if coreMatch(path) {
+ t.Errorf("linux/%s: the root binary links %s", arch, path)
+ }
+ }
+ }
+}
diff --git a/internal/mediahandler/download_test.go b/internal/mediahandler/download_test.go
index 45d18042c..0dfafed5a 100644
--- a/internal/mediahandler/download_test.go
+++ b/internal/mediahandler/download_test.go
@@ -1137,10 +1137,13 @@ func TestHandlerNeverLogsTransfers(t *testing.T) {
}
}
-// TestConfigDefaults: the paths default to Debian's ffmpeg and
+// TestConfigDefaults: the paths default to CARLOS_MEDIA_FFMPEG and
+// CARLOS_MEDIA_FFPROBE when absolute, else Debian's ffmpeg, and to
// CARLOS_MEDIA_SCRATCH, else /scratch; a set field is kept.
func TestConfigDefaults(t *testing.T) {
t.Setenv(ScratchEnv, "")
+ t.Setenv(FFmpegEnv, "")
+ t.Setenv(FFprobeEnv, "")
c := Config{}.withDefaults()
if c.FFmpeg != "/usr/bin/ffmpeg" || c.FFprobe != "/usr/bin/ffprobe" || c.Scratch != "/scratch" || c.Now == nil || c.Logf == nil || c.wait == nil || c.idle == nil || c.HTTP == nil {
t.Fatalf("defaults %+v", c)
@@ -1152,9 +1155,20 @@ func TestConfigDefaults(t *testing.T) {
if got := (Config{}).withDefaults().Scratch; got != "/var/media/x1" {
t.Fatalf("Scratch = %q, want the environment's", got)
}
- if got := (Config{Scratch: "/s", FFmpeg: "/f"}).withDefaults(); got.Scratch != "/s" || got.FFmpeg != "/f" {
+ t.Setenv(FFmpegEnv, "/opt/fake/ffmpeg")
+ t.Setenv(FFprobeEnv, "/opt/fake/ffprobe")
+ if got := (Config{}).withDefaults(); got.FFmpeg != "/opt/fake/ffmpeg" || got.FFprobe != "/opt/fake/ffprobe" {
+ t.Fatalf("FFmpeg, FFprobe = %q, %q, want the environment's", got.FFmpeg, got.FFprobe)
+ }
+ if got := (Config{Scratch: "/s", FFmpeg: "/f"}).withDefaults(); got.Scratch != "/s" || got.FFmpeg != "/f" || got.FFprobe != "/opt/fake/ffprobe" {
t.Fatalf("set fields replaced: %+v", got)
}
+ // A relative path is not taken: children start by absolute path.
+ t.Setenv(FFmpegEnv, "bin/ffmpeg")
+ t.Setenv(FFprobeEnv, "ffprobe")
+ if got := (Config{}).withDefaults(); got.FFmpeg != DefaultFFmpeg || got.FFprobe != DefaultFFprobe {
+ t.Fatalf("FFmpeg, FFprobe = %q, %q, want the defaults for relative paths", got.FFmpeg, got.FFprobe)
+ }
}
// TestDownloadStarTotalAfterAKnownSize: once the first answer gave the
diff --git a/internal/mediahandler/handler.go b/internal/mediahandler/handler.go
index 0ba1d81f6..904b6b4c2 100644
--- a/internal/mediahandler/handler.go
+++ b/internal/mediahandler/handler.go
@@ -31,6 +31,19 @@ import (
// execution.
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.
+const (
+ FFmpegEnv = "CARLOS_MEDIA_FFMPEG"
+ FFprobeEnv = "CARLOS_MEDIA_FFPROBE"
+)
+
// Defaults for Config's paths.
const (
DefaultFFmpeg = "/usr/bin/ffmpeg"
@@ -70,10 +83,10 @@ type Config struct {
// withDefaults fills every unset field.
func (c Config) withDefaults() Config {
if c.FFmpeg == "" {
- c.FFmpeg = DefaultFFmpeg
+ c.FFmpeg = binaryFromEnv(FFmpegEnv, DefaultFFmpeg)
}
if c.FFprobe == "" {
- c.FFprobe = DefaultFFprobe
+ c.FFprobe = binaryFromEnv(FFprobeEnv, DefaultFFprobe)
}
if c.Scratch == "" {
c.Scratch = os.Getenv(ScratchEnv)
@@ -104,6 +117,15 @@ func (c Config) withDefaults() Config {
return c
}
+// binaryFromEnv is the named environment variable's value when it is an
+// absolute path, else def: runChild starts every child by absolute path.
+func binaryFromEnv(name, def string) string {
+ if v := os.Getenv(name); filepath.IsAbs(v) {
+ return v
+ }
+ return def
+}
+
// jobError is a named failure: its code is one of media.HandlerCodes,
// and the result object carries it (run.go's finish).
type jobError struct{ code string }
diff --git a/internal/mediahandler/realffmpeg_test.go b/internal/mediahandler/realffmpeg_test.go
index 99e64931e..d444480e3 100644
--- a/internal/mediahandler/realffmpeg_test.go
+++ b/internal/mediahandler/realffmpeg_test.go
@@ -27,8 +27,8 @@ import (
// CARLOS_MEDIA_REGEN_FIXTURES=1, TestRegenerateProbeFixtures rewrites
// testdata/probe from them.
const (
- realFFmpegEnv = "CARLOS_MEDIA_FFMPEG"
- realFFprobeEnv = "CARLOS_MEDIA_FFPROBE"
+ realFFmpegEnv = FFmpegEnv
+ realFFprobeEnv = FFprobeEnv
regenEnv = "CARLOS_MEDIA_REGEN_FIXTURES"
)
diff --git a/internal/medialocal/e2e_test.go b/internal/medialocal/e2e_test.go
new file mode 100644
index 000000000..479383a28
--- /dev/null
+++ b/internal/medialocal/e2e_test.go
@@ -0,0 +1,200 @@
+//go:build linux
+
+package medialocal
+
+import (
+ "context"
+ "crypto/md5"
+ "database/sql"
+ "encoding/hex"
+ "errors"
+ "fmt"
+ "os"
+ "os/exec"
+ "path/filepath"
+ "runtime"
+ "slices"
+ "sync"
+ "sync/atomic"
+ "testing"
+ "time"
+
+ _ "modernc.org/sqlite"
+
+ "github.com/carlosframework/platform/internal/media"
+ "github.com/carlosframework/platform/internal/mediahandler"
+ "github.com/carlosframework/platform/internal/mediajobs"
+)
+
+// e2eStore is the object store an end-to-end run converts in: grants on
+// it, and the test's own access to seed the source and look at what the
+// job left.
+type e2eStore struct {
+ grants media.Grants
+ bucket string
+ put func(t *testing.T, key string, body []byte)
+ // list answers the names of the objects under prefix, sorted.
+ list func(t *testing.T, prefix string) []string
+ del func(t *testing.T, keys ...string)
+}
+
+// The fixtures the fake ffmpeg answers with (internal/mediahandler's
+// ok-video): its probe answer and its encode, also the source.
+var e2eFixtures = map[string]string{
+ "ok-av.json": "../mediahandler/testdata/probe/ok-av.json",
+ "video.mp4": "../mediahandler/testdata/fmp4/video.mp4",
+}
+
+// goTool is the go command that built this test.
+func goTool(t *testing.T) string {
+ t.Helper()
+ gobin := filepath.Join(runtime.GOROOT(), "bin", "go")
+ if _, err := os.Stat(gobin); err != nil {
+ if gobin, err = exec.LookPath("go"); err != nil {
+ t.Fatal("no go toolchain to build carlos-media with")
+ }
+ }
+ return gobin
+}
+
+// buildE2E builds carlos-media and the fake ffmpeg into a directory of
+// their own, with the fake's fixtures beside it.
+func buildE2E(t *testing.T) (carlosMedia, ffmpeg string) {
+ t.Helper()
+ dir := t.TempDir()
+ carlosMedia, ffmpeg = filepath.Join(dir, "carlos-media"), filepath.Join(dir, "ffmpeg")
+ for _, b := range [][2]string{
+ {carlosMedia, "github.com/carlosframework/platform/cmd/carlos-media"},
+ {ffmpeg, "./testdata/fakeffmpeg"},
+ } {
+ cmd := exec.Command(goTool(t), "build", "-o", b[0], b[1])
+ cmd.Env = append(os.Environ(), "CGO_ENABLED=0")
+ if out, err := cmd.CombinedOutput(); err != nil {
+ t.Fatalf("go build %s: %v\n%s", b[1], err, out)
+ }
+ }
+ for name, src := range e2eFixtures {
+ b, err := os.ReadFile(src)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if err := os.WriteFile(filepath.Join(dir, name), b, 0o600); err != nil {
+ t.Fatal(err)
+ }
+ }
+ return carlosMedia, ffmpeg
+}
+
+// oneStore is the StoreGuard of a deployment with one app and its store.
+type oneStore struct {
+ mu sync.Mutex
+ facts mediajobs.StoreFacts
+}
+
+func (s *oneStore) Lock(string, string) func() {
+ s.mu.Lock()
+ return s.mu.Unlock
+}
+
+func (s *oneStore) Current(context.Context, string, string) (mediajobs.StoreFacts, error) {
+ return s.facts, nil
+}
+
+var e2eSeq atomic.Int64
+
+// runEndToEnd submits one video-720p job on s through mediajobs with this
+// runner as its engine, the codec being the real carlos-media on the fake
+// ffmpeg: the job goes to done, its three outputs are in the bucket under
+// its execution's prefix, the result object is deleted by the cleanup,
+// and the execution's scratch is gone.
+func runEndToEnd(t *testing.T, s e2eStore) {
+ ctx, cancel := context.WithTimeout(context.Background(), 3*time.Minute)
+ defer cancel()
+ carlosMedia, ffmpeg := buildE2E(t)
+ source, err := os.ReadFile(e2eFixtures["video.mp4"])
+ if err != nil {
+ t.Fatal(err)
+ }
+ execRand, err := media.NewExecutionID()
+ if err != nil {
+ t.Fatal(err)
+ }
+ key := "uploads/" + execRand + "/clip.mp4"
+ s.put(t, key, source)
+ sum := md5.Sum(source)
+ etag := hex.EncodeToString(sum[:])
+
+ r := New(carlosMedia, t.TempDir())
+ r.Env = []string{mediahandler.FFmpegEnv + "=" + ffmpeg, mediahandler.FFprobeEnv + "=" + ffmpeg}
+ var log syncBuffer
+ r.Log = &log
+ t.Cleanup(func() {
+ if err := r.Close(); err != nil {
+ t.Errorf("Close: %v", err)
+ }
+ if t.Failed() {
+ t.Logf("the codec's log:\n%s", log.String())
+ }
+ })
+
+ db, err := sql.Open("sqlite", fmt.Sprintf("file:medialocal-e2e-%d?mode=memory&cache=shared", e2eSeq.Add(1)))
+ if err != nil {
+ t.Fatal(err)
+ }
+ db.SetMaxOpenConns(1)
+ t.Cleanup(func() { db.Close() })
+ for _, stmt := range mediajobs.Schema {
+ if _, err := db.ExecContext(ctx, stmt); err != nil {
+ t.Fatal(err)
+ }
+ }
+ const account, app, incarnation = "acct", "shop", "0123456789abcdef0123456789abcdef"
+ stores := &oneStore{facts: mediajobs.StoreFacts{Exists: true, Incarnation: incarnation, Bucket: s.bucket, Region: "us-east-1"}}
+ jobs := mediajobs.New(db, mediajobs.Deps{
+ Engine: r, Grants: s.grants, Stores: stores, Limits: media.DefaultLimits(), Logf: t.Logf,
+ })
+ job, created, err := jobs.Submit(ctx, mediajobs.SubmitRequest{
+ Account: account, App: app, Incarnation: incarnation, Bucket: s.bucket, Key: key, ETag: etag,
+ Preset: media.PresetVideo720p, Class: media.PickClass(media.PresetVideo720p, "", int64(len(source))),
+ Bytes: int64(len(source)), Now: time.Now(),
+ })
+ if err != nil || !created {
+ t.Fatalf("Submit: created %v, %v", created, err)
+ }
+ if err := jobs.Pass(ctx, time.Now()); err != nil {
+ t.Fatalf("the dispatching pass: %v", err)
+ }
+ row, ok, err := jobs.Lookup(ctx, account, app, incarnation, job.ID)
+ if err != nil || !ok || row.State != "running" || row.TaskARN == "" {
+ t.Fatalf("after dispatch: %+v, %v, %v", row, ok, err)
+ }
+ prefix := media.OutputPrefix(key, etag, media.PresetVideo720p, row.Execution)
+ t.Cleanup(func() {
+ var keys []string
+ for _, n := range media.OutputNames(media.PresetVideo720p) {
+ keys = append(keys, prefix+n)
+ }
+ s.del(t, append(keys, key)...)
+ })
+ if err := r.Wait(ctx, row.TaskARN); err != nil {
+ t.Fatalf("waiting for the codec: %v", err)
+ }
+ if err := jobs.Pass(ctx, time.Now()); err != nil {
+ t.Fatalf("the tracking pass: %v", err)
+ }
+ row, ok, err = jobs.Lookup(ctx, account, app, incarnation, job.ID)
+ if err != nil || !ok || row.State != "done" || row.ErrorCode != "" || row.Result == nil {
+ t.Fatalf("after the codec stopped: %+v, %v, %v", row, ok, err)
+ }
+ want := slices.Clone(media.OutputNames(media.PresetVideo720p))
+ slices.Sort(want)
+ if got := s.list(t, prefix); !slices.Equal(got, want) {
+ t.Fatalf("under %s: %v, want %v", prefix, got, want)
+ }
+ if _, err := s.grants.ReadResult(ctx, row.Execution); !errors.Is(err, media.ErrNotFound) {
+ t.Fatalf("the result object after the cleanup: %v", err)
+ }
+ if left, err := os.ReadDir(r.ScratchRoot); err != nil || len(left) != 0 {
+ t.Fatalf("scratch root holds %v, %v", left, err)
+ }
+}
diff --git a/internal/medialocal/minio_test.go b/internal/medialocal/minio_test.go
new file mode 100644
index 000000000..5e298fb70
--- /dev/null
+++ b/internal/medialocal/minio_test.go
@@ -0,0 +1,104 @@
+//go:build linux
+
+package medialocal
+
+import (
+ "bytes"
+ "context"
+ "errors"
+ "os"
+ "slices"
+ "strings"
+ "testing"
+
+ "github.com/aws/aws-sdk-go-v2/aws"
+ "github.com/aws/aws-sdk-go-v2/credentials"
+ "github.com/aws/aws-sdk-go-v2/service/s3"
+ "github.com/aws/aws-sdk-go-v2/service/sts"
+
+ "github.com/carlosframework/platform/internal/media"
+ "github.com/carlosframework/platform/internal/mediaaws"
+)
+
+// minioRegion is the region MinIO answers for when none is configured.
+const minioRegion = "us-east-1"
+
+// minioAssume is the grants' assume function on MinIO's STS: a session
+// of the test's user narrowed by the grant's policy. Its credentials
+// carry a session token, as production's always do (preflight F10).
+func minioAssume(api *sts.Client) func(ctx context.Context, sessionName, policy string) (aws.Credentials, error) {
+ return func(ctx context.Context, sessionName, policy string) (aws.Credentials, error) {
+ out, err := api.AssumeRole(ctx, &sts.AssumeRoleInput{
+ RoleArn: aws.String("arn:minio:iam:::role/media-conversion"),
+ RoleSessionName: aws.String(sessionName),
+ DurationSeconds: aws.Int32(int32(media.GrantLifetime.Seconds())),
+ Policy: aws.String(policy),
+ })
+ if err != nil {
+ return aws.Credentials{}, err
+ }
+ c := out.Credentials
+ if c == nil || c.AccessKeyId == nil || c.SecretAccessKey == nil || c.SessionToken == nil || c.Expiration == nil {
+ return aws.Credentials{}, errors.New("MinIO's AssumeRole answered no complete credentials")
+ }
+ return aws.Credentials{
+ AccessKeyID: *c.AccessKeyId, SecretAccessKey: *c.SecretAccessKey, SessionToken: *c.SessionToken,
+ CanExpire: true, Expires: *c.Expiration, Source: "medialocal-minio",
+ }, nil
+ }
+}
+
+// TestLocalEndToEndMinio is a whole job with no cloud API but the store:
+// mediajobs with this runner as its engine, the real carlos-media built
+// here on a fake ffmpeg (scenario ok-video), and mediaaws's grants on
+// temporary credentials from MinIO's STS. The job goes to done, its three
+// outputs are under its execution's prefix and the cleanup deletes its
+// result object. .amadan/ci.d/30-minio-contract stands the server up.
+func TestLocalEndToEndMinio(t *testing.T) {
+ if os.Getenv("CARLOS_MINIO_TEST") != "1" {
+ t.Skip("set CARLOS_MINIO_TEST=1 (with a running MinIO and the MINIO_* and MEDIA_LOCAL_* env vars) to run a local media job against MinIO; see .amadan/ci.d/30-minio-contract")
+ }
+ env := map[string]string{}
+ for _, name := range []string{"MINIO_ENDPOINT", "MEDIA_LOCAL_KEY", "MEDIA_LOCAL_SECRET", "MEDIA_LOCAL_BUCKET", "MEDIA_LOCAL_RESULTS"} {
+ if env[name] = os.Getenv(name); env[name] == "" {
+ t.Fatalf("%s is not set (required when CARLOS_MINIO_TEST=1)", name)
+ }
+ }
+ endpoint, bucket := env["MINIO_ENDPOINT"], env["MEDIA_LOCAL_BUCKET"]
+ user := credentials.NewStaticCredentialsProvider(env["MEDIA_LOCAL_KEY"], env["MEDIA_LOCAL_SECRET"], "")
+ console := s3.New(s3.Options{Region: minioRegion, BaseEndpoint: aws.String(endpoint), UsePathStyle: true, Credentials: user})
+ stsClient := sts.New(sts.Options{Region: minioRegion, BaseEndpoint: aws.String(endpoint), Credentials: user})
+ c := mediaaws.Config{V: 1, Region: minioRegion, ResultsBucket: env["MEDIA_LOCAL_RESULTS"], StorePrefix: bucket, AccountID: "123456789012"}
+ g := mediaaws.NewGrants(c, minioAssume(stsClient), console, mediaaws.WithS3Endpoint(endpoint))
+
+ runEndToEnd(t, e2eStore{
+ grants: g,
+ bucket: bucket,
+ put: func(t *testing.T, key string, body []byte) {
+ t.Helper()
+ if _, err := console.PutObject(context.Background(), &s3.PutObjectInput{Bucket: aws.String(bucket), Key: aws.String(key), Body: bytes.NewReader(body)}); err != nil {
+ t.Fatalf("seed %s: %v", key, err)
+ }
+ },
+ list: func(t *testing.T, prefix string) []string {
+ t.Helper()
+ out, err := console.ListObjectsV2(context.Background(), &s3.ListObjectsV2Input{Bucket: aws.String(bucket), Prefix: aws.String(prefix)})
+ if err != nil {
+ t.Fatalf("list %s: %v", prefix, err)
+ }
+ var names []string
+ for _, o := range out.Contents {
+ names = append(names, strings.TrimPrefix(aws.ToString(o.Key), prefix))
+ }
+ slices.Sort(names)
+ return names
+ },
+ del: func(t *testing.T, keys ...string) {
+ for _, k := range keys {
+ if _, err := console.DeleteObject(context.Background(), &s3.DeleteObjectInput{Bucket: aws.String(bucket), Key: aws.String(k)}); err != nil {
+ t.Errorf("remove %s: %v", k, err)
+ }
+ }
+ },
+ })
+}
diff --git a/internal/medialocal/runner.go b/internal/medialocal/runner.go
new file mode 100644
index 000000000..77783c78f
--- /dev/null
+++ b/internal/medialocal/runner.go
@@ -0,0 +1,371 @@
+// Package medialocal runs media conversion executions as local
+// processes: media.Engine without any cloud API (spec §8, plan 3
+// Task 13).
+//
+// Each execution is one process, `<binary> codec`, in a fresh 0700
+// 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.
+//
+// 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.
+package medialocal
+
+import (
+ "context"
+ "errors"
+ "io"
+ "os"
+ "os/exec"
+ "path/filepath"
+ "sort"
+ "sync"
+ "time"
+
+ "github.com/carlosframework/platform/internal/media"
+ "github.com/carlosframework/platform/internal/mediahandler"
+)
+
+// codecPath is the codec's PATH: the image's, never the runner's.
+const codecPath = "PATH=/usr/local/bin:/usr/bin:/bin"
+
+// The stop codes Describe reports, ECS's names for the same ends.
+const (
+ // StopEssentialExited: the codec exited, or the timer ended it (the
+ // deadline container is essential too).
+ StopEssentialExited = "EssentialContainerExited"
+ // StopUserInitiated: Stop ended it.
+ StopUserInitiated = "UserInitiated"
+)
+
+// waitDelay bounds cmd.Wait's copy of the codec's output once the codec
+// has exited: a descendant still holding the pipe cannot hold the
+// reaper.
+const waitDelay = 5 * time.Second
+
+// Runner is a media.Engine on local processes.
+type Runner struct {
+ // Binary is the carlos-media binary; ScratchRoot holds one scratch
+ // directory per execution. Both are absolute paths.
+ Binary, ScratchRoot string
+ // Env is appended to every codec's environment ahead of the
+ // runner's own variables, which win. Tests only.
+ Env []string
+ // Grace is the time from the SIGTERM to the SIGKILL; zero is
+ // media.StopGrace.
+ Grace time.Duration
+ // Log receives the codec's stdout and stderr; nil discards them.
+ Log io.Writer
+
+ mu sync.Mutex
+ tasks map[string]*task // by ARN
+ byExec map[string]*task
+ closed bool
+}
+
+// task is one execution's process and what Describe reports of it.
+type task struct {
+ arn, execution, scratch string
+ cmd *exec.Cmd
+ startedAt time.Time
+
+ stopOnce, killOnce sync.Once
+ stop, kill chan struct{} // closed by Stop, by Close
+ done chan struct{} // closed once stopped and reaped
+
+ // Under Runner.mu.
+ stopped bool
+ stoppedAt time.Time
+ stopCode string
+ codecExit, deadlineExit *int
+ scratchRemoved bool
+}
+
+// New is a runner of binary with scratch directories under scratchRoot.
+func New(binary, scratchRoot string) *Runner {
+ return &Runner{Binary: binary, ScratchRoot: scratchRoot}
+}
+
+var _ media.Engine = (*Runner)(nil)
+
+func (r *Runner) grace() time.Duration {
+ if r.Grace > 0 {
+ return r.Grace
+ }
+ return media.StopGrace
+}
+
+// arnOf is an execution's task ARN.
+func arnOf(execution string) string { return "medialocal:task/" + execution }
+
+// Run starts the execution's codec. As ECS with the execution as its
+// client token, a second Run of the same execution answers the first
+// one's task. A codec that cannot start is a *media.Rejected: no task.
+func (r *Runner) Run(ctx context.Context, req media.RunRequest) (string, error) {
+ if err := ctx.Err(); err != nil {
+ return "", err
+ }
+ if req.Execution == "" || len(req.Payload) == 0 {
+ return "", &media.Rejected{Reason: "the run request has no execution or no payload"}
+ }
+ r.mu.Lock()
+ defer r.mu.Unlock()
+ if r.closed {
+ return "", &media.Rejected{Reason: "the local runner is closed"}
+ }
+ if t := r.byExec[req.Execution]; t != nil {
+ return t.arn, nil
+ }
+ if r.tasks == nil {
+ r.tasks, r.byExec = map[string]*task{}, map[string]*task{}
+ }
+ scratch, err := newScratch(r.ScratchRoot)
+ if err != nil {
+ return "", &media.Rejected{Retryable: true, Reason: "no scratch directory: " + err.Error()}
+ }
+ cmd := &exec.Cmd{
+ Path: r.Binary,
+ Args: []string{r.Binary, media.CodecCommand},
+ Dir: scratch,
+ Env: codecEnv(r.Env, string(req.Payload), scratch),
+ Stdout: r.Log,
+ 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{}),
+ }
+ 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
+}
+
+// newScratch makes a fresh 0700 directory under root, with tmp in it
+// (the codec's TMPDIR).
+func newScratch(root string) (string, error) {
+ dir, err := os.MkdirTemp(root, "exec-")
+ if err != nil {
+ return "", err
+ }
+ // MkdirTemp makes it 0700 less the umask; say so whatever the umask.
+ if err := os.Chmod(dir, 0o700); err != nil {
+ os.RemoveAll(dir)
+ return "", err
+ }
+ if err := os.Mkdir(filepath.Join(dir, "tmp"), 0o700); err != nil {
+ os.RemoveAll(dir)
+ return "", err
+ }
+ return dir, nil
+}
+
+// codecEnv is the codec's whole environment: extra (tests only), then
+// the payload, PATH, the scratch and TMPDIR in it. Nothing of the
+// runner's own environment is passed on, and where extra names one of
+// the four, exec keeps the last value, the runner's.
+func codecEnv(extra []string, payload, scratch string) []string {
+ env := append([]string(nil), extra...)
+ return append(env,
+ media.PayloadEnv+"="+payload,
+ codecPath,
+ mediahandler.ScratchEnv+"="+scratch,
+ "TMPDIR="+filepath.Join(scratch, "tmp"),
+ )
+}
+
+// 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.
+func (r *Runner) watch(t *task, sleep time.Duration) {
+ exited := make(chan struct{})
+ pid := t.cmd.Process.Pid
+ go func() {
+ waitExited(pid)
+ close(exited)
+ }()
+ timer := time.NewTimer(max(sleep, 0))
+ defer timer.Stop()
+ deadlineExit, stopCode := media.DeadlineExitStopped, StopEssentialExited
+ select {
+ case <-exited:
+ case <-timer.C:
+ deadlineExit = media.DeadlineExitReached
+ r.end(t, exited)
+ case <-t.stop:
+ stopCode = StopUserInitiated
+ r.end(t, exited)
+ case <-t.kill:
+ stopCode = StopUserInitiated
+ signalGroup(pid, sigKill)
+ <-exited
+ }
+ signalGroup(pid, sigKill)
+ _ = t.cmd.Wait() // the exit is read from ProcessState
+ code := exitCode(t.cmd.ProcessState)
+ r.mu.Lock()
+ t.stopped, t.stoppedAt, t.stopCode = true, time.Now(), stopCode
+ t.codecExit, t.deadlineExit = &code, &deadlineExit
+ r.mu.Unlock()
+ 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.
+func (r *Runner) end(t *task, exited <-chan struct{}) {
+ pid := t.cmd.Process.Pid
+ signalGroup(pid, sigTerm)
+ grace := time.NewTimer(r.grace())
+ defer grace.Stop()
+ select {
+ case <-exited:
+ return
+ case <-grace.C:
+ case <-t.kill:
+ }
+ signalGroup(pid, sigKill)
+ <-exited
+}
+
+// describe is what Describe reports of t, under r.mu.
+func (t *task) describe() media.Task {
+ return media.Task{
+ ARN: t.arn, StartedBy: t.execution, StopCode: t.stopCode, Stopped: t.stopped,
+ StartedAt: t.startedAt, StoppedAt: t.stoppedAt,
+ CodecExit: t.codecExit, DeadlineExit: t.deadlineExit,
+ }
+}
+
+// removeScratch removes a stopped task's scratch once, under r.mu.
+func (t *task) removeScratch() error {
+ if !t.stopped || t.scratchRemoved {
+ return nil
+ }
+ if err := os.RemoveAll(t.scratch); err != nil {
+ return err
+ }
+ t.scratchRemoved = true
+ return nil
+}
+
+// Describe reports each task it knows and names the rest missing. A task
+// described stopped has its scratch directory removed.
+func (r *Runner) Describe(ctx context.Context, arns []string) ([]media.Task, []string, error) {
+ if err := ctx.Err(); err != nil {
+ return nil, nil, err
+ }
+ r.mu.Lock()
+ defer r.mu.Unlock()
+ var found []media.Task
+ var missing []string
+ var errs []error
+ for _, arn := range arns {
+ t := r.tasks[arn]
+ if t == nil {
+ missing = append(missing, arn)
+ continue
+ }
+ errs = append(errs, t.removeScratch())
+ found = append(found, t.describe())
+ }
+ if err := errors.Join(errs...); err != nil {
+ return nil, nil, err
+ }
+ return found, missing, nil
+}
+
+// ListByStartedBy answers the execution's task, described as Describe
+// does.
+func (r *Runner) ListByStartedBy(ctx context.Context, execution string) (media.Task, bool, error) {
+ if err := ctx.Err(); err != nil {
+ return media.Task{}, false, err
+ }
+ r.mu.Lock()
+ defer r.mu.Unlock()
+ t := r.byExec[execution]
+ if t == nil {
+ return media.Task{}, false, nil
+ }
+ if err := t.removeScratch(); err != nil {
+ return media.Task{}, false, err
+ }
+ return t.describe(), true, nil
+}
+
+// Stop ends the task as the timer does, without waiting for it: SIGTERM,
+// then SIGKILL after the grace. A task it does not know, or one already
+// stopped, is success, as for ECS.
+func (r *Runner) Stop(ctx context.Context, arn, reason string) error {
+ if err := ctx.Err(); err != nil {
+ return err
+ }
+ r.mu.Lock()
+ t := r.tasks[arn]
+ r.mu.Unlock()
+ if t != nil {
+ t.stopOnce.Do(func() { close(t.stop) })
+ }
+ return nil
+}
+
+// CheckRevision has no task definition to check: the runner runs the
+// binary it was given.
+func (r *Runner) CheckRevision(context.Context, media.ClassKey) error { return nil }
+
+// Wait blocks until the task is stopped and its codec reaped, or ctx
+// ends.
+func (r *Runner) Wait(ctx context.Context, arn string) error {
+ r.mu.Lock()
+ t := r.tasks[arn]
+ r.mu.Unlock()
+ if t == nil {
+ return errors.New("medialocal: no such task")
+ }
+ select {
+ case <-t.done:
+ return nil
+ case <-ctx.Done():
+ return ctx.Err()
+ }
+}
+
+// Close kills every task still running (SIGKILL to its process group, no
+// grace), waits for each to be reaped and removes every scratch
+// directory. Run refuses afterwards.
+func (r *Runner) Close() error {
+ r.mu.Lock()
+ r.closed = true
+ var ts []*task
+ for _, t := range r.tasks {
+ ts = append(ts, t)
+ }
+ r.mu.Unlock()
+ sort.Slice(ts, func(i, j int) bool { return ts[i].arn < ts[j].arn })
+ for _, t := range ts {
+ t.killOnce.Do(func() { close(t.kill) })
+ }
+ for _, t := range ts {
+ <-t.done
+ }
+ r.mu.Lock()
+ defer r.mu.Unlock()
+ var errs []error
+ for _, t := range ts {
+ errs = append(errs, t.removeScratch())
+ }
+ return errors.Join(errs...)
+}
diff --git a/internal/medialocal/runner_linux.go b/internal/medialocal/runner_linux.go
new file mode 100644
index 000000000..c4d185ce2
--- /dev/null
+++ b/internal/medialocal/runner_linux.go
@@ -0,0 +1,52 @@
+//go:build linux
+
+package medialocal
+
+import (
+ "errors"
+ "os"
+ "os/exec"
+ "syscall"
+
+ "golang.org/x/sys/unix"
+)
+
+const (
+ sigTerm = unix.SIGTERM
+ sigKill = unix.SIGKILL
+)
+
+// startCodec starts cmd as the leader of a process group of its own, so
+// the runner can signal everything the codec starts in it.
+func startCodec(cmd *exec.Cmd) error {
+ cmd.SysProcAttr = &syscall.SysProcAttr{Setpgid: true}
+ 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) {
+ _ = unix.Kill(-pid, sig)
+}
+
+// waitExited blocks until pid has exited, without reaping it: the
+// caller signals its group, then reaps it with cmd.Wait.
+func waitExited(pid int) {
+ for {
+ var info unix.Siginfo
+ err := unix.Waitid(unix.P_PID, pid, &info, unix.WEXITED|unix.WNOWAIT, nil)
+ if !errors.Is(err, unix.EINTR) {
+ return
+ }
+ }
+}
+
+// exitCode is the codec's exit as ECS reports a container's: its exit
+// status, or 128 plus the signal that killed it.
+func exitCode(ps *os.ProcessState) int {
+ if ws, ok := ps.Sys().(syscall.WaitStatus); ok && ws.Signaled() {
+ return 128 + int(ws.Signal())
+ }
+ return ps.ExitCode()
+}
diff --git a/internal/medialocal/runner_other.go b/internal/medialocal/runner_other.go
new file mode 100644
index 000000000..96e7c3a4a
--- /dev/null
+++ b/internal/medialocal/runner_other.go
@@ -0,0 +1,29 @@
+//go:build !linux
+
+package medialocal
+
+import (
+ "errors"
+ "os"
+ "os/exec"
+)
+
+// signal stands in for unix.Signal where the runner does not run.
+type signal int
+
+const (
+ sigTerm signal = 15
+ sigKill signal = 9
+)
+
+// startCodec refuses: the runner relies on Linux process groups and
+// waitid, so Run answers a *media.Rejected and nothing else is reached.
+func startCodec(*exec.Cmd) error {
+ return errors.New("the local media runner runs only on Linux")
+}
+
+func signalGroup(int, signal) {}
+
+func waitExited(int) {}
+
+func exitCode(ps *os.ProcessState) int { return ps.ExitCode() }
diff --git a/internal/medialocal/runner_test.go b/internal/medialocal/runner_test.go
new file mode 100644
index 000000000..b83a0a426
--- /dev/null
+++ b/internal/medialocal/runner_test.go
@@ -0,0 +1,453 @@
+//go:build linux
+
+package medialocal
+
+import (
+ "bufio"
+ "bytes"
+ "context"
+ "errors"
+ "fmt"
+ "io"
+ "os"
+ "os/exec"
+ "os/signal"
+ "path/filepath"
+ "slices"
+ "strconv"
+ "strings"
+ "sync"
+ "syscall"
+ "testing"
+ "time"
+
+ "golang.org/x/sys/unix"
+
+ "github.com/carlosframework/platform/internal/media"
+ "github.com/carlosframework/platform/internal/mediahandler"
+)
+
+// The fake codec is the test binary re-executed with fakeEnv naming a
+// scenario, passed through Runner.Env: TestMain runs the scenario in
+// place of the tests.
+const fakeEnv = "MEDIALOCAL_FAKE"
+
+func TestMain(m *testing.M) {
+ if scenario := os.Getenv(fakeEnv); scenario != "" {
+ os.Exit(fakeCodec(scenario))
+ }
+ os.Exit(m.Run())
+}
+
+// fakeCodec runs one scenario and answers its exit code.
+//
+// - 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.
+// - 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.
+func fakeCodec(scenario string) int {
+ switch scenario {
+ case "ignore-term":
+ exe, err := os.Executable()
+ if err != nil {
+ return 1
+ }
+ g := exec.Command(exe)
+ g.Env = append(os.Environ(), fakeEnv+"=grandchild")
+ g.Stdout = os.Stdout
+ if err := g.Start(); err != nil {
+ return 1
+ }
+ fmt.Printf("grandchild %d\n", g.Process.Pid)
+ fmt.Printf("codec %d\n", os.Getpid())
+ return blockIgnoringTerm()
+ case "grandchild":
+ return blockIgnoringTerm()
+ case "scratch":
+ name := os.Getenv(media.PayloadEnv)
+ // The handler's own rule: the scratch is CARLOS_MEDIA_SCRATCH,
+ // else /scratch.
+ scratch := os.Getenv(mediahandler.ScratchEnv)
+ if scratch == "" {
+ scratch = mediahandler.DefaultScratch
+ }
+ tmp := os.Getenv("TMPDIR")
+ if name == "" || tmp == "" {
+ return 2
+ }
+ for _, dir := range []string{scratch, tmp} {
+ f, err := os.OpenFile(filepath.Join(dir, name), os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0o600)
+ if err != nil {
+ fmt.Fprintln(os.Stderr, "fake:", err)
+ return 3
+ }
+ f.Close()
+ }
+ return 0
+ case "env":
+ fmt.Println(strings.Join(os.Args, " "))
+ for _, kv := range os.Environ() {
+ fmt.Println(kv)
+ }
+ return 0
+ }
+ return 98
+}
+
+// blockIgnoringTerm waits on SIGTERM forever: only SIGKILL ends it.
+func blockIgnoringTerm() int {
+ c := make(chan os.Signal, 1)
+ signal.Notify(c, syscall.SIGTERM)
+ for range c {
+ }
+ return 0
+}
+
+// newTestRunner is a runner of the test binary as the fake codec running
+// scenario, with a scratch root of its own, closed when the test ends.
+func newTestRunner(t *testing.T, scenario string) *Runner {
+ t.Helper()
+ exe, err := os.Executable()
+ if err != nil {
+ t.Fatal(err)
+ }
+ r := New(exe, t.TempDir())
+ r.Env = []string{fakeEnv + "=" + scenario}
+ t.Cleanup(func() {
+ if err := r.Close(); err != nil {
+ t.Errorf("Close: %v", err)
+ }
+ })
+ 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.
+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.
+func runIgnoring(t *testing.T, r *Runner, execution string, deadlineS int64) (string, ignoring) {
+ t.Helper()
+ pr, pw, err := os.Pipe()
+ if err != nil {
+ t.Fatal(err)
+ }
+ r.Log = pw
+ 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
+ if err != nil {
+ pr.Close()
+ t.Fatalf("Run: %v", err)
+ }
+ ig := ignoring{gone: make(chan struct{})}
+ pids := make(chan [2]int, 1)
+ go func() {
+ defer close(ig.gone)
+ defer pr.Close()
+ var got [2]int
+ sc := bufio.NewScanner(pr)
+ for n := 0; n < 2 && sc.Scan(); n++ {
+ role, pid, _ := strings.Cut(sc.Text(), " ")
+ i := 0
+ if role == "grandchild" {
+ i = 1
+ }
+ got[i], _ = strconv.Atoi(pid)
+ }
+ pids <- got
+ io.Copy(io.Discard, pr)
+ }()
+ select {
+ 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")
+ }
+ if ig.codec <= 0 || ig.grandchild <= 0 {
+ t.Fatalf("pids %+v", ig)
+ }
+ t.Cleanup(func() {
+ _ = unix.Kill(ig.grandchild, unix.SIGKILL)
+ _ = unix.Kill(ig.codec, unix.SIGKILL)
+ })
+ return arn, ig
+}
+
+// waitGone answers how long after since every process of ig exited, or
+// fails the test when that is not by limit.
+func waitGone(t *testing.T, ig ignoring, since time.Time, limit time.Duration, what string) time.Duration {
+ t.Helper()
+ timer := time.NewTimer(time.Until(since.Add(limit)))
+ defer timer.Stop()
+ select {
+ case <-ig.gone:
+ return time.Since(since)
+ case <-timer.C:
+ t.Fatalf("%s: the codec or its grandchild still runs %s after the start", what, limit)
+ return 0
+ }
+}
+
+// describeOne describes arn, which must be found.
+func describeOne(t *testing.T, r *Runner, arn string) media.Task {
+ t.Helper()
+ found, missing, err := r.Describe(context.Background(), []string{arn})
+ if err != nil || len(missing) != 0 || len(found) != 1 {
+ t.Fatalf("Describe(%s) = %+v, missing %v, %v", arn, found, missing, err)
+ }
+ return found[0]
+}
+
+func waitTask(t *testing.T, r *Runner, arn string) {
+ t.Helper()
+ ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
+ defer cancel()
+ if err := r.Wait(ctx, arn); err != nil {
+ t.Fatalf("Wait(%s): %v", arn, err)
+ }
+}
+
+func exitOf(p *int) string {
+ if p == nil {
+ return "none"
+ }
+ return strconv.Itoa(*p)
+}
+
+// reaped fails the test when pid is still a process, a zombie included:
+// the runner reaps its codec.
+func reaped(t *testing.T, pid int) {
+ t.Helper()
+ if err := unix.Kill(pid, 0); !errors.Is(err, unix.ESRCH) {
+ t.Fatalf("the codec %d is still a process (kill 0: %v): not reaped", pid, err)
+ }
+}
+
+// TestRunnerDeadlineEndsAnIgnoringChild: a codec that ignores SIGTERM,
+// with a grandchild in its process group that ignores it too, is gone,
+// both of them, within the deadline plus the grace plus 1 s, and not
+// before the deadline plus the grace: SIGTERM to the group at the
+// deadline, SIGKILL to the group once the grace has passed. The deadline
+// is described reached (0) and the codec killed (137), and it is reaped.
+func TestRunnerDeadlineEndsAnIgnoringChild(t *testing.T) {
+ r := newTestRunner(t, "ignore-term")
+ r.Grace = time.Second
+ const deadline = time.Second
+ start := time.Now()
+ arn, ig := runIgnoring(t, r, "exec-deadline", int64(deadline/time.Second))
+ took := waitGone(t, ig, start, deadline+r.Grace+time.Second, "deadline")
+ if took < deadline+r.Grace {
+ t.Fatalf("gone %s after the start, before the deadline plus the grace", took)
+ }
+ waitTask(t, r, arn)
+ task := describeOne(t, r, arn)
+ if !task.Stopped || exitOf(task.DeadlineExit) != "0" || exitOf(task.CodecExit) != "137" || task.StopCode != StopEssentialExited || task.StartedBy != "exec-deadline" {
+ t.Fatalf("described %+v (codec %s, deadline %s)", task, exitOf(task.CodecExit), exitOf(task.DeadlineExit))
+ }
+ if ran := task.StoppedAt.Sub(task.StartedAt); ran < deadline+r.Grace || ran > deadline+r.Grace+time.Second {
+ t.Fatalf("ran %s", ran)
+ }
+ reaped(t, ig.codec)
+}
+
+// TestRunnerStopEndsLikeTheTimer: Stop is the timer's SIGTERM, grace and
+// SIGKILL to the group, described stopped by the console (143).
+func TestRunnerStopEndsLikeTheTimer(t *testing.T) {
+ r := newTestRunner(t, "ignore-term")
+ r.Grace = time.Second
+ arn, ig := runIgnoring(t, r, "exec-stop", 600)
+ stopped := time.Now()
+ if err := r.Stop(context.Background(), arn, "test"); err != nil {
+ t.Fatal(err)
+ }
+ if took := waitGone(t, ig, stopped, r.Grace+time.Second, "stop"); took < r.Grace {
+ t.Fatalf("gone %s after Stop, before the grace", took)
+ }
+ waitTask(t, r, arn)
+ task := describeOne(t, r, arn)
+ if !task.Stopped || exitOf(task.DeadlineExit) != "143" || exitOf(task.CodecExit) != "137" || task.StopCode != StopUserInitiated {
+ t.Fatalf("described %+v (codec %s, deadline %s)", task, exitOf(task.CodecExit), exitOf(task.DeadlineExit))
+ }
+ reaped(t, ig.codec)
+ // Stopping a stopped task, or one the runner never ran, is success.
+ for _, a := range []string{arn, arnOf("never")} {
+ if err := r.Stop(context.Background(), a, "again"); err != nil {
+ t.Fatalf("Stop(%s): %v", a, err)
+ }
+ }
+}
+
+// entries lists dir's names, sorted; none when it does not exist.
+func entries(t *testing.T, dir string) []string {
+ t.Helper()
+ des, err := os.ReadDir(dir)
+ if errors.Is(err, os.ErrNotExist) {
+ return nil
+ }
+ if err != nil {
+ t.Fatal(err)
+ }
+ var out []string
+ for _, d := range des {
+ out = append(out, d.Name())
+ }
+ return out
+}
+
+// TestRunnerScratchIsPerExecution: two executions each get a fresh 0700
+// directory under the scratch root, write only there (their TMPDIR is
+// inside it) and nothing under /scratch; Describe of a stopped task
+// removes its directory.
+func TestRunnerScratchIsPerExecution(t *testing.T) {
+ r := newTestRunner(t, "scratch")
+ before := entries(t, mediahandler.DefaultScratch)
+ jobs := map[string]string{} // ARN → payload
+ for _, job := range []string{"job-a", "job-b"} {
+ arn, err := r.Run(context.Background(), media.RunRequest{
+ Execution: "exec-" + job, Payload: []byte(job), DeadlineS: 600, GrantExpiry: time.Now().Add(time.Hour),
+ })
+ if err != nil {
+ t.Fatal(err)
+ }
+ jobs[arn] = job
+ }
+ for arn := range jobs {
+ waitTask(t, r, arn)
+ }
+ dirs := entries(t, r.ScratchRoot)
+ if len(dirs) != 2 {
+ t.Fatalf("scratch root holds %v, want one directory per execution", dirs)
+ }
+ seen := map[string]bool{}
+ for _, d := range dirs {
+ path := filepath.Join(r.ScratchRoot, d)
+ fi, err := os.Lstat(path)
+ if err != nil || !fi.IsDir() || fi.Mode().Perm() != 0o700 {
+ t.Fatalf("%s: %v, %v", d, fi.Mode(), err)
+ }
+ got := entries(t, path)
+ if len(got) != 2 || got[1] != "tmp" {
+ t.Fatalf("%s holds %v, want its own job file and tmp", d, got)
+ }
+ if tmp := entries(t, filepath.Join(path, "tmp")); !slices.Equal(tmp, got[:1]) {
+ t.Fatalf("%s/tmp holds %v, want %v", d, tmp, got[:1])
+ }
+ seen[got[0]] = true
+ }
+ if !seen["job-a"] || !seen["job-b"] {
+ t.Fatalf("job files %v", seen)
+ }
+ if after := entries(t, mediahandler.DefaultScratch); !slices.Equal(after, before) {
+ t.Fatalf("%s held %v and now %v", mediahandler.DefaultScratch, before, after)
+ }
+ for arn := range jobs {
+ task := describeOne(t, r, arn)
+ if !task.Stopped || exitOf(task.CodecExit) != "0" || exitOf(task.DeadlineExit) != "143" || task.StopCode != StopEssentialExited {
+ t.Fatalf("described %+v (codec %s, deadline %s)", task, exitOf(task.CodecExit), exitOf(task.DeadlineExit))
+ }
+ }
+ if left := entries(t, r.ScratchRoot); len(left) != 0 {
+ t.Fatalf("scratch root holds %v after both were described stopped", left)
+ }
+}
+
+// syncBuffer is a bytes.Buffer safe for the copy goroutine and a reader.
+type syncBuffer struct {
+ mu sync.Mutex
+ b bytes.Buffer
+}
+
+func (s *syncBuffer) Write(p []byte) (int, error) {
+ s.mu.Lock()
+ defer s.mu.Unlock()
+ return s.b.Write(p)
+}
+
+func (s *syncBuffer) String() string {
+ s.mu.Lock()
+ defer s.mu.Unlock()
+ return s.b.String()
+}
+
+// TestRunnerCodecEnvironment: the codec runs as `<binary> codec` with
+// the payload, PATH, its scratch and TMPDIR in it, the test's extras,
+// and nothing of the runner's own environment; an extra cannot replace
+// one of the runner's variables.
+func TestRunnerCodecEnvironment(t *testing.T) {
+ t.Setenv("MEDIALOCAL_CANARY", "the runner's own environment")
+ r := newTestRunner(t, "env")
+ r.Env = append(r.Env, "TMPDIR=/elsewhere", media.PayloadEnv+"=not the payload")
+ var out syncBuffer
+ r.Log = &out
+ arn, err := r.Run(context.Background(), media.RunRequest{Execution: "exec-env", Payload: []byte(`{"v":1}`), DeadlineS: 600, GrantExpiry: time.Now().Add(time.Hour)})
+ if err != nil {
+ t.Fatal(err)
+ }
+ waitTask(t, r, arn)
+ lines := strings.Split(strings.TrimSpace(out.String()), "\n")
+ if len(lines) == 0 || lines[0] != r.Binary+" codec" {
+ t.Fatalf("arguments %q", lines)
+ }
+ env := lines[1:]
+ slices.Sort(env)
+ dirs := entries(t, r.ScratchRoot)
+ if len(dirs) != 1 {
+ t.Fatalf("scratch root holds %v", dirs)
+ }
+ scratch := filepath.Join(r.ScratchRoot, dirs[0])
+ want := []string{
+ media.PayloadEnv + `={"v":1}`,
+ mediahandler.ScratchEnv + "=" + scratch,
+ fakeEnv + "=env",
+ "PATH=/usr/local/bin:/usr/bin:/bin",
+ "TMPDIR=" + filepath.Join(scratch, "tmp"),
+ }
+ slices.Sort(want)
+ if !slices.Equal(env, want) {
+ t.Fatalf("the codec's environment is\n%s\nwant\n%s", strings.Join(env, "\n"), strings.Join(want, "\n"))
+ }
+}
+
+// TestRunnerRunIsIdempotent: a second Run of an execution answers its
+// task and starts nothing; an ARN the runner never made is missing.
+func TestRunnerRunIsIdempotent(t *testing.T) {
+ r := newTestRunner(t, "scratch")
+ req := media.RunRequest{Execution: "exec-once", Payload: []byte("job-once"), DeadlineS: 600, GrantExpiry: time.Now().Add(time.Hour)}
+ arn, err := r.Run(context.Background(), req)
+ if err != nil {
+ t.Fatal(err)
+ }
+ again, err := r.Run(context.Background(), req)
+ if err != nil || again != arn {
+ t.Fatalf("second Run = %q, %v; want %q", again, err, arn)
+ }
+ waitTask(t, r, arn)
+ if dirs := entries(t, r.ScratchRoot); len(dirs) != 1 {
+ t.Fatalf("scratch root holds %v, want one execution's", dirs)
+ }
+ found, missing, err := r.Describe(context.Background(), []string{arn, arnOf("never")})
+ if err != nil || len(found) != 1 || !slices.Equal(missing, []string{arnOf("never")}) {
+ t.Fatalf("Describe = %+v, %v, %v", found, missing, err)
+ }
+ task, ok, err := r.ListByStartedBy(context.Background(), "exec-once")
+ if err != nil || !ok || task.ARN != arn || !task.Stopped {
+ t.Fatalf("ListByStartedBy = %+v, %v, %v", task, ok, err)
+ }
+ if _, ok, err := r.ListByStartedBy(context.Background(), "never"); ok || err != nil {
+ t.Fatalf("ListByStartedBy(never) = %v, %v", ok, err)
+ }
+ var rej *media.Rejected
+ if _, err := r.Run(context.Background(), media.RunRequest{Execution: "exec-empty"}); !errors.As(err, &rej) {
+ t.Fatalf("Run with no payload: %v", err)
+ }
+}
diff --git a/internal/medialocal/testdata/fakeffmpeg/main.go b/internal/medialocal/testdata/fakeffmpeg/main.go
new file mode 100644
index 000000000..d3216f3ea
--- /dev/null
+++ b/internal/medialocal/testdata/fakeffmpeg/main.go
@@ -0,0 +1,92 @@
+// Command fakeffmpeg is ffmpeg and ffprobe for TestLocalEndToEndMinio:
+// the handler's ok-video scenario (internal/mediahandler/run_test.go) as
+// a program the codec can run, since a built carlos-media cannot reach
+// a test binary's helper (plan 3 preflight F29). The codec gives its
+// children a fixed environment, so the fixtures sit beside this binary:
+// ok-av.json (ffprobe's answer) and video.mp4 (Task 4's encode).
+//
+// - -version: an ffmpeg version line;
+// - -of: ffprobe's answer for the source;
+// - otherwise an encode: its last argument, which must not exist,
+// gets video.mp4's bytes or a minimal JPEG for poster.jpg.
+package main
+
+import (
+ "errors"
+ "fmt"
+ "os"
+ "path/filepath"
+ "slices"
+ "strings"
+)
+
+const versionLine = "ffmpeg version 7.1.5-0+deb13u1 Copyright (c) 2000-2025 the FFmpeg developers\nbuilt with gcc 14\n"
+
+// jpeg is a JPEG's start and end markers around a few bytes.
+var jpeg = []byte{0xff, 0xd8, 0xff, 0xe0, 0, 0x10, 'J', 'F', 'I', 'F', 0, 0xff, 0xd9}
+
+func main() {
+ os.Exit(run(os.Args[1:]))
+}
+
+func run(args []string) int {
+ exe, err := os.Executable()
+ if err != nil {
+ fmt.Fprintln(os.Stderr, "fakeffmpeg:", err)
+ return 1
+ }
+ dir := filepath.Dir(exe)
+ switch {
+ case slices.Contains(args, "-version"):
+ fmt.Print(versionLine)
+ return 0
+ case slices.Contains(args, "-of"):
+ for i, a := range args {
+ if a == "-show_entries" && i+1 < len(args) && strings.HasPrefix(args[i+1], "packet=") {
+ fmt.Fprintln(os.Stderr, "fakeffmpeg: no packet pass for ok-video")
+ return 1
+ }
+ }
+ return copyOut(filepath.Join(dir, "ok-av.json"))
+ case len(args) == 0:
+ fmt.Fprintln(os.Stderr, "fakeffmpeg: no arguments")
+ return 1
+ }
+ out := args[len(args)-1]
+ var data []byte
+ switch filepath.Base(out) {
+ case "video.mp4":
+ if data, err = os.ReadFile(filepath.Join(dir, "video.mp4")); err != nil {
+ fmt.Fprintln(os.Stderr, "fakeffmpeg:", err)
+ return 1
+ }
+ case "poster.jpg":
+ data = jpeg
+ default:
+ fmt.Fprintln(os.Stderr, "fakeffmpeg: an unexpected output")
+ return 1
+ }
+ f, err := os.OpenFile(out, os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0o600)
+ if err == nil {
+ _, err = f.Write(data)
+ err = errors.Join(err, f.Close())
+ }
+ if err != nil {
+ fmt.Fprintln(os.Stderr, "fakeffmpeg:", err)
+ return 1
+ }
+ return 0
+}
+
+// copyOut writes the file at path to stdout.
+func copyOut(path string) int {
+ b, err := os.ReadFile(path)
+ if err == nil {
+ _, err = os.Stdout.Write(b)
+ }
+ if err != nil {
+ fmt.Fprintln(os.Stderr, "fakeffmpeg:", err)
+ return 1
+ }
+ return 0
+}