activator: carlos run on a rootfs row runs in its image through the rootfs cmd unit; a named build is hashed off the lock and pinned before exec; a resident's lease watch stops its runs
StartCmd's body becomes startCmdUnit, shared by both runtimes: a binary row keeps its arm (nestedGate, CmdExe or Cmd, childEnv), a rootfs row takes rootfsCmdArm (every rootfs gate, a schema-2 launch file naming process cmd with rootfsLaunchEnv(rootfsCmdVars), CmdRootfs naming the image with the run's argv at b.tier(rt)). Root's pre-start refusals are marked refuseRootfs and hand back no unit. CmdSpec.Build resolves through BuildIdentity off a.mu (ErrCmdVersion), names the build to the start and the build state, and is in the generations file before exec until the run is proven settled. The resident lease watch stops attached runs at the drain and at the loss (Task 8's carry).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
12 files changed,
+1,204
−39
internal/activator/backend_rootfs.go+50 −0internal/activator/cmd.go+90 −3internal/activator/cmd_version_test.go+273 −0internal/activator/cmdunit.go+115 −28internal/activator/generations_file.go+5 −1internal/activator/rootfs_cmd_lease_test.go+137 −0internal/activator/rootfs_cmd_test.go+375 −0internal/activator/rootfs_ctl_harness_test.go+35 −0internal/activator/rootfs_invariants_test.go+73 −0internal/activator/rootfs_service.go+8 −1internal/activator/rootfs_test.go+8 −6internal/activator/rootfsenv_test.go+35 −0
diff --git a/internal/activator/backend_rootfs.go b/internal/activator/backend_rootfs.go| index 5375b26b1..8a7a28692 100644 |
| --- a/internal/activator/backend_rootfs.go |
| +++ b/internal/activator/backend_rootfs.go |
| @@ -10,6 +10,7 @@ import ( |
| "slices" |
| "strings" |
| + "github.com/carlosframework/platform/internal/instancectl" |
| "github.com/carlosframework/platform/internal/registry" |
| "github.com/carlosframework/platform/internal/release" |
| ) |
| @@ -125,3 +126,52 @@ func (a *Service) declaredProcesses(rt registry.Route, g Gen) (map[string]releas |
| } |
| return r.Processes(rt, id) |
| } |
| + |
| +// stagedImageOf is id as root's rootfs verbs name an image (A5), beside |
| +// stagedExeOf: the staged path, version and digest, with the process root |
| +// runs from it, or for a carlos run its argv (process ""). |
| +func stagedImageOf(id release.StagedIdentity, process string, argv []string) instancectl.StagedImage { |
| + return instancectl.StagedImage{Path: id.StagedPath, Version: id.Version, Digest: id.Digest, Process: process, Argv: argv} |
| +} |
| + |
| +// rootfsCmdArm is startCmdUnit's rootfs half [pf 1.6, 1.7, 1.8; A3, A5]: |
| +// every rootfs gate, then a schema-2 launch file naming launch.process |
| +// with rootfsLaunchEnv(rootfsCmdVars(...)) and no argv, and CmdRootfs |
| +// naming launch.image at the row's sized tier. The image is required: a |
| +// rootfs command always names the build it runs, and with none, or a |
| +// partial one, it is refused before anything is laid out. Root's |
| +// pre-start refusals (ErrStagedImage, ErrStartRefused) come back marked |
| +// refuseRootfs: nothing started. No egress step: #328 checks in root's |
| +// startRootfsCmd [pf 2.5]. |
| +func (b *ExecBackend) rootfsCmdArm(ctx context.Context, rt registry.Route, spec CmdSpec, launch cmdLaunch) (cmdArm, error) { |
| + if err := b.rootfsGates(ctx, rt); err != nil { |
| + return cmdArm{}, err |
| + } |
| + if launch.image == nil { |
| + return cmdArm{}, refuseRootfs(fmt.Errorf("%s: %w", rt.Host, errNoCmdExe)) |
| + } |
| + img := *launch.image |
| + if img.Version == "" || img.Path == "" || img.Digest == "" { |
| + return cmdArm{}, refuseRootfs(fmt.Errorf("%s: %w (build %q, path %q, digest %q)", rt.Host, errPartialStagedIdentity, img.Version, img.Path, img.Digest)) |
| + } |
| + rc, err := b.rootfsControl() |
| + if err != nil { |
| + return cmdArm{}, refuseRootfs(fmt.Errorf("%s: %w", rt.Host, err)) |
| + } |
| + return cmdArm{ |
| + unit: instancectl.RootfsUnitName(instancectl.RoleCmd, rt.Host), |
| + write: func(p instancePaths) error { |
| + env := rootfsLaunchEnv(b.rootfsCmdVars(rt, spec.genEnv, p.dbPath, spec.RunID, spec.RunDir)) |
| + return b.writeRootfsLaunchFor(p, instancectl.RoleCmd, 0, rt.Host, launch.process, env) |
| + }, |
| + start: func(ctx context.Context) (string, error) { |
| + inv, err := rc.CmdRootfs(ctx, rt.Host, b.tier(rt).MemoryMax, img) |
| + if errors.Is(err, instancectl.ErrStagedImage) || errors.Is(err, instancectl.ErrStartRefused) { |
| + // Answered before systemctl start (final review I1 for /cmd): |
| + // a refusal, never the build's failure. |
| + return "", refuseRootfs(err) |
| + } |
| + return inv, err |
| + }, |
| + }, nil |
| +} |
diff --git a/internal/activator/cmd.go b/internal/activator/cmd.go| index b1a82a5f5..07cda1d05 100644 |
| --- a/internal/activator/cmd.go |
| +++ b/internal/activator/cmd.go |
| @@ -3,6 +3,7 @@ package activator |
| import ( |
| "context" |
| "errors" |
| + "fmt" |
| "log" |
| "sync" |
| "time" |
| @@ -10,6 +11,7 @@ import ( |
| "github.com/carlosframework/platform/internal/instancectl" |
| "github.com/carlosframework/platform/internal/instancekey" |
| "github.com/carlosframework/platform/internal/registry" |
| + "github.com/carlosframework/platform/internal/release" |
| ) |
| // Why an instance stop interrupted a run (run spec §5.3). The text is what |
| @@ -116,6 +118,13 @@ type cmdHold struct { |
| // lastTry is when the last settle attempt ended, by h.now; the sweep's |
| // retry keeps actStopTimeout after it (retrySettle). Under mu. |
| lastTry time.Time |
| + // build is the build the run names (CmdSpec.Build), whole as |
| + // BuildIdentity hashed it, or zero for a run of gen's own build. RunCmd |
| + // sets it under a.mu with starting, and it is never written again. The |
| + // generations file names it until the run is proven settled |
| + // (entryGenerationsLocked), and it is on disk before the command execs |
| + // (publishBeforeExec). |
| + build release.StagedIdentity |
| // gen is the generation the run was admitted against (merge ruling |
| // M2): its number and its exe pin. RunCmd sets it under a.mu with |
| // starting, and it is never written again. The command execs gen's |
| @@ -389,6 +398,28 @@ func (a *Service) interruptCmdsLocked(e *actEntry, n uint64, why string) { |
| } |
| } |
| +// stopCmdsForLeaseLocked is a resident's lease watch reaching e's runs |
| +// (Plan 3 Task 12, C7): when the watch begins the lease's drain |
| +// (residentLeaseShort) and at the loss itself (residentLeaseLostLocked), |
| +// every run of e that may be running is stopped and proven settled now, |
| +// off a.mu, as its generations are killed, never only after the |
| +// generation's own drain (finishStop's settleCmds). A run whose start is in |
| +// flight is stopped once the start returns (cmdHold.stop waits for it). A |
| +// stop already in flight is joined, not repeated. A settle that fails |
| +// leaves the run unproven: the stop path's settleCmds keeps the lease |
| +// until one succeeds. The caller holds a.mu. |
| +func (a *Service) stopCmdsForLeaseLocked(e *actEntry) { |
| + for _, h := range cmdHoldsLocked(e) { |
| + go func(h *cmdHold) { |
| + ctx, cancel := context.WithTimeout(context.Background(), cmdStopBound) |
| + defer cancel() |
| + if err := h.stop(ctx, StopLeaseLost); err != nil { |
| + log.Printf("activator: %s: run %s is not proven stopped after its lease ran short: %v; the stop keeps the lease until it is", e.host, h.runID, err) |
| + } |
| + }(h) |
| + } |
| +} |
| + |
| // retryCmdSettlesLocked is the sweep's retry of every run of e whose stop |
| // was asked for and is not proven (re-review 6): a run interrupted when a |
| // swap retired its generation, a run whose own Stop failed, and a released |
| @@ -515,6 +546,15 @@ func (a *Service) RunCmd(ctx context.Context, rt registry.Route, spec CmdSpec) ( |
| if spec.Prepare != nil { |
| prepErr = spec.Prepare(pctx) |
| } |
| + // The build a run names is resolved here, once, off a.mu and before the |
| + // admission below takes it [Astra R1 8]: BuildIdentity hashes the whole |
| + // staged copy. Root checks the digest again at the start, so a file |
| + // replaced after this hash is refused there (ErrStagedImage or |
| + // ErrStagedExe), never run. |
| + build, buildErr := a.cmdBuildIdentity(rt, spec.Build) |
| + if prepErr == nil { |
| + prepErr = buildErr |
| + } |
| a.mu.Lock() |
| // waited: the run has waited for a switch since launch eligibility was |
| // last checked, by Prepare or by spec.Recheck. A wait can be long, so |
| @@ -578,11 +618,13 @@ func (a *Service) RunCmd(ctx context.Context, rt registry.Route, spec CmdSpec) ( |
| // (cmdStartInFlightLocked). |
| h.starting = true |
| h.gen = e.gen |
| + h.build = build |
| h.onProven = func() { |
| // The pin for h.gen is this run's alone once that generation is |
| - // no longer the entry's current one. |
| + // no longer the entry's current one, and a named build's is always |
| + // this run's alone. |
| a.mu.Lock() |
| - stale := a.entries[e.host] != e || e.gen.N != h.gen.N |
| + stale := a.entries[e.host] != e || e.gen.N != h.gen.N || h.build.Version != "" |
| a.mu.Unlock() |
| if stale { |
| _ = a.persistGenerations() |
| @@ -601,6 +643,11 @@ func (a *Service) RunCmd(ctx context.Context, rt registry.Route, spec CmdSpec) ( |
| if h.gen.StagedPath != "" { |
| spec.serving = &instancectl.StagedExe{Path: h.gen.StagedPath, Version: h.gen.Build, Digest: h.gen.Digest} |
| } |
| + // A run that names a build runs that build, whole as it was hashed |
| + // (a rootfs row's StartCmd names it to root as stagedImageOf does). |
| + if h.build.Version != "" { |
| + spec.serving = stagedExeOf(h.build) |
| + } |
| // And with the environment that generation launched with, from its |
| // handle: never the delivered files, which may hold a config revision |
| // it has not activated, a config swap queued or failed (merge ruling |
| @@ -633,9 +680,24 @@ func (a *Service) RunCmd(ctx context.Context, rt registry.Route, spec CmdSpec) ( |
| // one serving when the unit starts. The write takes time, so |
| // ownership and the run's own cancel and deadline are checked again |
| // after it, before anything starts. |
| - if err := a.recordBuild(sctx, rt.Host, h.gen.Build); err != nil { |
| + recorded := h.gen.Build |
| + if h.build.Version != "" { |
| + recorded = h.build.Version |
| + } |
| + if err := a.recordBuild(sctx, rt.Host, recorded); err != nil { |
| return abandon(err) |
| } |
| + // A named build is in the generations file on disk before it execs |
| + // [Astra R1 9]: root reads only what the file names, and could sweep |
| + // or restage a build it does not name under the command. The starting |
| + // hold names it from here (entryGenerationsLocked); a failed write |
| + // starts nothing (errStagedBuildNotPublished). A run of its |
| + // generation's own build is already named by that generation. |
| + if h.build.Version != "" { |
| + if err := a.publishBeforeExec(); err != nil { |
| + return abandon(err) |
| + } |
| + } |
| a.mu.Lock() |
| var refused error |
| switch { |
| @@ -682,3 +744,28 @@ func (a *Service) RunCmd(ctx context.Context, rt registry.Route, spec CmdSpec) ( |
| } |
| return run, nil |
| } |
| + |
| +// cmdBuildIdentity is build, the build a run names, as this box has it |
| +// staged for rt's app (zero for "", a run of its generation's own build): |
| +// whole (version, path and the digest of the bytes hashed now), through |
| +// the backend's BuildIdentity. A backend that cannot |
| +// name one, a build that is not staged here and a copy that cannot be read |
| +// are all ErrCmdVersion: nothing starts. Never call it with a.mu held: it |
| +// hashes the whole staged copy. |
| +func (a *Service) cmdBuildIdentity(rt registry.Route, build string) (release.StagedIdentity, error) { |
| + if build == "" { |
| + return release.StagedIdentity{}, nil |
| + } |
| + bi, ok := a.backend.(buildIdentifier) |
| + if !ok { |
| + return release.StagedIdentity{}, fmt.Errorf("%s: build %s: %w: this backend names no staged build", rt.Host, build, ErrCmdVersion) |
| + } |
| + id, err := bi.BuildIdentity(rt, build) |
| + if err != nil { |
| + return release.StagedIdentity{}, fmt.Errorf("%s: build %s: %w: %v", rt.Host, build, ErrCmdVersion, err) |
| + } |
| + if id.Version != build || id.StagedPath == "" || id.Digest == "" { |
| + return release.StagedIdentity{}, fmt.Errorf("%s: build %s: %w: the staged copy is named %q at %q (digest %q)", rt.Host, build, ErrCmdVersion, id.Version, id.StagedPath, id.Digest) |
| + } |
| + return id, nil |
| +} |
diff --git a/internal/activator/cmd_version_test.go b/internal/activator/cmd_version_test.go| new file mode 100644 |
| index 000000000..c3804dfc2 |
| --- /dev/null |
| +++ b/internal/activator/cmd_version_test.go |
| @@ -0,0 +1,273 @@ |
| +package activator |
| + |
| +// Plan 3 Task 12: carlos run --version. A run that names a build runs that |
| +// build as staged on this box, with the serving generation's environment; |
| +// the build is hashed off a.mu [Astra R1 8]; it is in the generations file |
| +// on disk before it execs and stays there until the run is proven settled |
| +// [Astra R1 9]; a build not staged here starts nothing (ErrCmdVersion). |
| + |
| +import ( |
| + "context" |
| + "errors" |
| + "fmt" |
| + "os" |
| + "path/filepath" |
| + "slices" |
| + "testing" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/registry" |
| + "github.com/carlosframework/platform/internal/release" |
| +) |
| + |
| +// RunCmd with Build "v2": StartCmd is handed v2's staged path and digest, |
| +// whole as BuildIdentity named it, and the serving generation's |
| +// environment; the build state names v2; the generations file lists v2 |
| +// from before the start until the run is proven settled. On a rootfs row |
| +// that identity reaches root through CmdRootfs (StartCmd's rootfs arm), |
| +// with the run's arguments as the image's argv. |
| +func TestRunVersionRunsTheNamedBuild(t *testing.T) { |
| + t.Run("RunCmd", func(t *testing.T) { |
| + a, cb, _ := testCmdActivator(t, Config{}) |
| + a.gens = true |
| + path := release.GenerationsPath(t.TempDir()) |
| + a.GenerationsFile = path |
| + var rec buildRecorder |
| + a.BeforeExec = rec.record |
| + rt := testRoute("c.example.com") |
| + arrangeAwake(t, a, rt) |
| + serving := map[string]string{"SHOP_MODE": "live"} |
| + cb.lastProc().launchEnv = serving |
| + want := fakeIdentity("v2") |
| + pinned := func() bool { return slices.Contains(readPinPaths(t, path, rt.Host), want.StagedPath) } |
| + var got CmdSpec |
| + var pinnedAtStart bool |
| + cb.startCmd = func(_ context.Context, _ registry.Route, spec CmdSpec) (CmdUnit, error) { |
| + got, pinnedAtStart = spec, pinned() |
| + return cb.unit, nil |
| + } |
| + h, err := a.RunCmd(context.Background(), rt, CmdSpec{RunID: "run_a", Build: "v2"}) |
| + if err != nil { |
| + t.Fatalf("RunCmd: %v", err) |
| + } |
| + if got.serving == nil || *got.serving != *stagedExeOf(want) { |
| + t.Fatalf("StartCmd was handed %v, want v2 whole: %+v", got.serving, want) |
| + } |
| + if got.genEnv["SHOP_MODE"] != "live" { |
| + t.Fatalf("the run's environment %v, want the serving generation's", got.genEnv) |
| + } |
| + if ids := cb.buildIdentities(); !slices.Equal(ids, []string{"v2"}) { |
| + t.Fatalf("BuildIdentity asked for %v, want v2 once", ids) |
| + } |
| + if rec.last() != "v2" { |
| + t.Fatalf("the build state names %q, want the build about to touch the data, v2", rec.last()) |
| + } |
| + if !pinnedAtStart { |
| + t.Fatal("the generations file did not name v2 when the command started") |
| + } |
| + if !pinned() { |
| + t.Fatal("v2 left the generations file while its run was unsettled") |
| + } |
| + if err := h.Stop(context.Background()); err != nil { |
| + t.Fatal(err) |
| + } |
| + waitFor(t, "v2's pin released once the run settled", func() bool { return !pinned() }) |
| + h.Release() |
| + }) |
| + t.Run("rootfs StartCmd", func(t *testing.T) { |
| + b, ctl := newRootfsBackend(t) |
| + ctl.cmdInv = "inv-r" |
| + rt := rootfsRoute(b) |
| + id := stagedRootfsIdentity(t, b, "v2") |
| + dir := filepath.Join(b.pathsFor(rt).dataDir, CmdRunDirName, "run_a") |
| + spec := CmdSpec{RunID: "run_a", RunDir: dir, Args: []string{"bin/rails", "db:migrate:status"}, Stdout: &syncBuffer{}, Stderr: &syncBuffer{}, |
| + serving: stagedExeOf(id), genEnv: map[string]string{"SHOP_MODE": "live"}} |
| + u, err := productionBackend(t, b).StartCmd(context.Background(), rt, spec) |
| + if err != nil { |
| + t.Fatalf("StartCmd: %v", err) |
| + } |
| + u.(*cmdUnit).out.Close() |
| + u.(*cmdUnit).errs.Close() |
| + img := ctl.lastRootfsImage() |
| + if want := stagedImageOf(id, "", spec.Args); img.Path != want.Path || img.Version != "v2" || img.Digest != id.Digest || img.Process != "" || !slices.Equal(img.Argv, spec.Args) { |
| + t.Fatalf("CmdRootfs named %+v, want %+v", img, want) |
| + } |
| + ctl.mustHaveCallPrefix(t, "cmd-rootfs "+rt.Host+" ") |
| + noCallStarts(t, ctl, "cmd "+rt.Host) |
| + }) |
| +} |
| + |
| +// A build that is not staged here: ErrCmdVersion, nothing recorded and no |
| +// unit started, and the instance takes the next run. |
| +func TestRunVersionNotStagedIsRefused(t *testing.T) { |
| + a, cb, _ := testCmdActivator(t, Config{}) |
| + var rec buildRecorder |
| + a.BeforeExec = rec.record |
| + rt := testRoute("c.example.com") |
| + arrangeAwake(t, a, rt) |
| + cb.mu.Lock() |
| + cb.ident.buildIDErr = fmt.Errorf("build v9: %w", os.ErrNotExist) |
| + cb.mu.Unlock() |
| + if _, err := a.RunCmd(context.Background(), rt, CmdSpec{RunID: "run_a", Build: "v9"}); !errors.Is(err, ErrCmdVersion) { |
| + t.Fatalf("RunCmd for an unstaged build = %v, want ErrCmdVersion", err) |
| + } |
| + if cb.cmdStarts != 0 || rec.last() != "" { |
| + t.Fatalf("the refused run started %d units and recorded %q", cb.cmdStarts, rec.last()) |
| + } |
| + cb.mu.Lock() |
| + cb.ident.buildIDErr = nil |
| + cb.mu.Unlock() |
| + a.BeforeExec = nil // the fake generation names no build to record |
| + h, err := a.RunCmd(context.Background(), rt, CmdSpec{RunID: "run_b"}) |
| + if err != nil { |
| + t.Fatalf("the next run: %v", err) |
| + } |
| + h.Release() |
| + |
| + // Production-wired: the backend's own BuildIdentity over the version |
| + // store, through the production composition. |
| + eb, _ := newRootfsBackend(t) |
| + s := &Service{backend: productionBackend(t, eb)} |
| + ert := rootfsRoute(eb) |
| + if _, err := s.cmdBuildIdentity(ert, "v9"); !errors.Is(err, ErrCmdVersion) { |
| + t.Fatalf("cmdBuildIdentity(v9) = %v, want ErrCmdVersion", err) |
| + } |
| + id, err := s.cmdBuildIdentity(ert, "v1") |
| + if err != nil || id.Version != "v1" || id.StagedPath != release.VersionPath(eb.OptDir, rootfsTestAcct, "v1", rootfsTestApp) || len(id.Digest) != 64 { |
| + t.Fatalf("cmdBuildIdentity(v1) = %+v, %v; want v1 whole", id, err) |
| + } |
| +} |
| + |
| +// blockingIdentityBackend is cmdFakeBackend whose BuildIdentity waits for |
| +// gate, as a hash of a large image would. |
| +type blockingIdentityBackend struct { |
| + *cmdFakeBackend |
| + entered, gate chan struct{} |
| +} |
| + |
| +func (b *blockingIdentityBackend) BuildIdentity(_ registry.Route, build string) (release.StagedIdentity, error) { |
| + close(b.entered) |
| + <-b.gate |
| + return fakeIdentity(build), nil |
| +} |
| + |
| +// [Astra R1 8] The named build is hashed off a.mu: while BuildIdentity |
| +// blocks, a request to another host wakes it and a sweep completes. |
| +func TestRunVersionHashesOffTheLock(t *testing.T) { |
| + fb := &fakeBackend{layoutFn: func(registry.Route) (Layout, string) { return LayoutNested, "" }} |
| + cb := &cmdFakeBackend{fakeBackend: fb, unit: &fakeCmdUnit{}} |
| + bb := &blockingIdentityBackend{cmdFakeBackend: cb, entered: make(chan struct{}), gate: make(chan struct{})} |
| + reg, err := registry.Open(filepath.Join(t.TempDir(), "registry.db")) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + a := New(Config{Bucket: "test-bucket", Idle: time.Hour}, bb, reg) |
| + clk := &fakeClock{t: time.Unix(1_700_000_000, 0)} |
| + a.now = clk.now |
| + t.Cleanup(func() { a.Shutdown(context.Background()) }) |
| + rt := testRoute("c.example.com") |
| + arrangeAwake(t, a, rt) |
| + type ran struct { |
| + h CmdHandle |
| + err error |
| + } |
| + done := make(chan ran, 1) |
| + go func() { |
| + h, err := a.RunCmd(context.Background(), rt, CmdSpec{RunID: "run_a", Build: "v2"}) |
| + done <- ran{h, err} |
| + }() |
| + <-bb.entered |
| + within := func(what string, f func()) { |
| + t.Helper() |
| + c := make(chan struct{}) |
| + go func() { f(); close(c) }() |
| + select { |
| + case <-c: |
| + case <-time.After(5 * time.Second): |
| + close(bb.gate) |
| + t.Fatalf("%s did not complete while the build was hashed: the hash holds a.mu", what) |
| + } |
| + } |
| + within("a request to another host", func() { |
| + end, err := a.beginRequest(context.Background(), testRoute("d.example.com")) |
| + if err != nil { |
| + t.Errorf("request to another host: %v", err) |
| + return |
| + } |
| + end() |
| + }) |
| + within("a sweep", a.sweepOnce) |
| + close(bb.gate) |
| + r := <-done |
| + if r.err != nil { |
| + t.Fatalf("RunCmd: %v", r.err) |
| + } |
| + if cb.cmdStarts != 1 { |
| + t.Fatalf("%d units started, want 1", cb.cmdStarts) |
| + } |
| + r.h.Release() |
| +} |
| + |
| +// [Astra R1 9] The persisted generations file names v2 before the /cmd |
| +// request, and still after the serving generation retires (an overlap |
| +// swap), until the run is proven settled. A failed write starts nothing. |
| +func TestRunVersionPinPublishedBeforeExec(t *testing.T) { |
| + want := fakeIdentity("v2") |
| + t.Run("pinned until settled", func(t *testing.T) { |
| + f, cb := newCmdSwapFixture(t) |
| + path := release.GenerationsPath(t.TempDir()) |
| + f.a.GenerationsFile = path |
| + pinned := func() bool { return slices.Contains(readPinPaths(t, path, f.host), want.StagedPath) } |
| + var pinnedAtStart bool |
| + cb.onStart = func() { pinnedAtStart = pinned() } |
| + cb.unit.setSettleErr(errors.New("processes remained")) |
| + h, err := f.a.RunCmd(context.Background(), testRoute(f.host), CmdSpec{RunID: "run_a", Build: "v2"}) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if !pinnedAtStart { |
| + t.Fatal("the generations file on disk did not name v2 when the command started") |
| + } |
| + if specs := cb.started(); len(specs) != 1 || specs[0].serving == nil || *specs[0].serving != *stagedExeOf(want) { |
| + t.Fatalf("the command was started on %+v, want v2", specs) |
| + } |
| + if res := f.a.Swap(context.Background(), f.attempt(ModeOverlap), f.newest); res.Outcome != SwapDone { |
| + t.Fatalf("Swap = %+v", res) |
| + } |
| + waitFor(t, "the interrupt's failed settle", func() bool { n, _ := cb.unit.stopped(); return n >= 1 }) |
| + if err := f.a.persistGenerations(); err != nil { |
| + t.Fatal(err) |
| + } |
| + if !pinned() { |
| + t.Fatal("v2 left the generations file after the serving generation retired, with its run unsettled") |
| + } |
| + cb.unit.setSettleErr(nil) |
| + if err := h.Stop(context.Background()); err != nil { |
| + t.Fatalf("Stop: %v", err) |
| + } |
| + waitFor(t, "v2's pin released", func() bool { return !pinned() }) |
| + h.Release() |
| + }) |
| + t.Run("a failed write starts nothing", func(t *testing.T) { |
| + f, cb := newCmdSwapFixture(t) |
| + notDir := filepath.Join(t.TempDir(), "file") |
| + if err := os.WriteFile(notDir, nil, 0o600); err != nil { |
| + t.Fatal(err) |
| + } |
| + f.a.GenerationsFile = filepath.Join(notDir, "generations.json") |
| + _, err := f.a.RunCmd(context.Background(), testRoute(f.host), CmdSpec{RunID: "run_a", Build: "v2"}) |
| + if !errors.Is(err, errStagedBuildNotPublished) { |
| + t.Fatalf("RunCmd with the generations file unwritable = %v, want errStagedBuildNotPublished", err) |
| + } |
| + if n := len(cb.started()); n != 0 { |
| + t.Fatalf("%d units started", n) |
| + } |
| + // The hold is gone: a run of the serving build, which needs no new |
| + // pin, is taken. |
| + h, err := f.a.RunCmd(context.Background(), testRoute(f.host), CmdSpec{RunID: "run_b"}) |
| + if err != nil { |
| + t.Fatalf("the next run: %v", err) |
| + } |
| + h.Release() |
| + }) |
| +} |
diff --git a/internal/activator/cmdunit.go b/internal/activator/cmdunit.go| index ead3f300e..b161061e8 100644 |
| --- a/internal/activator/cmdunit.go |
| +++ b/internal/activator/cmdunit.go |
| @@ -17,6 +17,7 @@ import ( |
| "github.com/carlosframework/platform/internal/instancectl" |
| "github.com/carlosframework/platform/internal/instancekey" |
| "github.com/carlosframework/platform/internal/registry" |
| + "github.com/carlosframework/platform/internal/release" |
| ) |
| // CmdRunDirName is the directory under an instance's own data directory |
| @@ -52,12 +53,19 @@ type CmdSpec struct { |
| // last check is that old by then. An error ends the run before launch, |
| // as Prepare's does. |
| Recheck func(ctx context.Context) error |
| + // Build is the build the command runs (carlos run --version): "" runs |
| + // the serving generation's build, as every run did before it; a |
| + // version runs that build as staged on this box, with the serving |
| + // generation's environment (merge ruling M3). A build not staged here |
| + // refuses the run before anything starts (ErrCmdVersion). |
| + Build string |
| // serving is the serving generation's staged build, set by RunCmd at its |
| // last awake check when that generation names one, generations on or |
| // off (zero-downtime spec §7.5 and settings ruling R-EXEC-SIDECAR: what |
| - // runs beside an instance is its serving artifact). Nil runs the live |
| - // link. Callers cannot set it. |
| + // runs beside an instance is its serving artifact), or the build Build |
| + // names. Nil runs the live link; a rootfs row refuses without one. |
| + // Callers cannot set it. |
| serving *instancectl.StagedExe |
| // genEnv is the file environment the run's generation launched with, |
| // from its handle (unitProc.LaunchEnv), set by RunCmd with serving |
| @@ -89,8 +97,14 @@ var _ cmdExeStarter = (*instancectl.Client)(nil) |
| // errNoCmdExe: a run names its serving generation's build and the control |
| // channel cannot carry it. The run is refused rather than run on the live |
| // link, which after a fallback names a build the instance is not serving. |
| +// A rootfs row's command always names its image, so a rootfs run with no |
| +// build to name is refused with it too. |
| var errNoCmdExe = errors.New("activator: the instance-control client cannot name a run's build") |
| +// ErrCmdVersion: the build a run names (CmdSpec.Build) is not staged on |
| +// this box, or cannot be read there. Nothing started. |
| +var ErrCmdVersion = errors.New("activator: the build named for a run is not staged on this box") |
| + |
| // CmdUnit is a started cmd unit. |
| type CmdUnit interface { |
| Invocation() string |
| @@ -158,35 +172,78 @@ func (b *ExecBackend) cmdLayout(rt registry.Route) (Layout, string) { |
| } |
| // StartCmd starts one run's cmd unit (run spec §5.4): the layout check, the |
| -// nested gate, the live link, the instance's directories, the environment |
| -// its generation launched with (spec.genEnv, merge ruling M3), the two |
| -// stream listeners, launch.cmd.json, then POST /cmd. It returns |
| +// runtime's gate (the nested gate and the live link for a binary row, every |
| +// rootfs gate for a rootfs row), the instance's directories, the |
| +// environment its generation launched with (spec.genEnv, merge ruling M3), |
| +// the two stream listeners, launch.cmd.json, then POST /cmd. It returns |
| // once the unit has an invocation. The environment is never logged. A |
| // failure after the POST was sent returns a unit with the error: the unit |
| // may be running, and the caller must stop and settle it. |
| // |
| -// A run that names its serving generation's staged build (spec.serving) |
| -// has root mount that build instead of the live link, and needs no live |
| -// link of its own. The argv is the same /opt/carlos/live/<host> inside the |
| -// namespace either way. |
| +// A binary run that names its serving generation's staged build |
| +// (spec.serving) has root mount that build instead of the live link, and |
| +// needs no live link of its own. The argv is the same |
| +// /opt/carlos/live/<host> inside the namespace either way. |
| +// |
| +// A rootfs run always names its image (spec.serving, as stagedImageOf |
| +// names it to root), with spec.Args as the image's argv exactly as given: |
| +// root runs it where and with what web runs, resolving its first word along |
| +// the image's PATH (A3, A5). Its launch file is schema 2 with process "cmd" |
| +// and no argv [pf 1.6]. |
| func (b *ExecBackend) StartCmd(ctx context.Context, rt registry.Route, spec CmdSpec) (CmdUnit, error) { |
| + if rt.Runtime == registry.RuntimeRootfsV1 { |
| + launch := cmdLaunch{process: string(instancectl.RoleCmd)} |
| + if x := spec.serving; x != nil { |
| + img := stagedImageOf(release.StagedIdentity{Version: x.Version, StagedPath: x.Path, Digest: x.Digest}, "", spec.Args) |
| + launch.image = &img |
| + } |
| + return b.startCmdUnit(ctx, rt, spec, launch) |
| + } |
| + return b.startCmdUnit(ctx, rt, spec, cmdLaunch{argv: append([]string{b.liveLink(rt.Host)}, spec.Args...)}) |
| +} |
| + |
| +// cmdLaunch is what a cmd unit runs, the one thing startCmdUnit's callers |
| +// vary: a binary row's argv, or a rootfs row's process (the tenant launch |
| +// file's name for it) and the image root starts it from, whose Argv is a |
| +// run's arguments or empty for a declared process. |
| +type cmdLaunch struct { |
| + argv []string |
| + process string |
| + image *instancectl.StagedImage |
| +} |
| + |
| +// cmdArm is one runtime's half of a cmd unit's start, after its gate has |
| +// passed: the unit it starts (for the log), the launch file it writes, and |
| +// the request that starts it. |
| +type cmdArm struct { |
| + unit string |
| + write func(p instancePaths) error |
| + start func(ctx context.Context) (string, error) |
| +} |
| + |
| +// startCmdUnit is StartCmd's body, shared by both runtimes (and by Group R's |
| +// release): the checks every cmd unit makes, the runtime's arm (binaryCmdArm |
| +// or rootfsCmdArm), the instance's directories, the listeners, the launch |
| +// file and the start. The unit it returns, on success and on a start that |
| +// may have begun alike, is the runtime-aware cmdUnit: a rootfs row's is |
| +// polled, stopped and proven gone as the rootfs cmd unit (A8). A start root |
| +// refused before it began anything (marked errRootfsRefused) returns no |
| +// unit: nothing can be running. |
| +func (b *ExecBackend) startCmdUnit(ctx context.Context, rt registry.Route, spec CmdSpec, launch cmdLaunch) (CmdUnit, error) { |
| if l, why := b.cmdLayout(rt); l != LayoutNested { |
| return nil, fmt.Errorf("%w: %s is %s (%s)", ErrCmdNotNested, rt.Host, l, why) |
| } |
| if err := checkCmdRunDir(b.pathsFor(rt).dataDir, spec); err != nil { |
| return nil, fmt.Errorf("%s: %w", rt.Host, err) |
| } |
| - if err := b.nestedGate(rt); err != nil { |
| - return nil, err |
| + var arm cmdArm |
| + var err error |
| + if rt.Runtime == registry.RuntimeRootfsV1 { |
| + arm, err = b.rootfsCmdArm(ctx, rt, spec, launch) |
| + } else { |
| + arm, err = b.binaryCmdArm(ctx, rt, spec, launch) |
| } |
| - var exeStart cmdExeStarter |
| - if spec.serving != nil { |
| - cs, ok := b.Control.(cmdExeStarter) |
| - if !ok { |
| - return nil, fmt.Errorf("%s: %w", rt.Host, errNoCmdExe) |
| - } |
| - exeStart = cs |
| - } else if err := b.ensureLiveLink(ctx, rt.Host); err != nil { |
| + if err != nil { |
| return nil, err |
| } |
| if spec.genEnv == nil { |
| @@ -220,16 +277,13 @@ func (b *ExecBackend) StartCmd(ctx context.Context, rt registry.Route, spec CmdS |
| errs.Close() |
| return nil, err |
| } |
| - argv := append([]string{b.liveLink(rt.Host)}, spec.Args...) |
| - env := childEnv(b.cmdVars(rt, spec.genEnv, p.dbPath, spec.RunID, spec.RunDir)) |
| - if err := b.writeLaunch(p, instancectl.RoleCmd, rt.Host, argv, env); err != nil { |
| + if err := arm.write(p); err != nil { |
| return fail(err) |
| } |
| - var inv string |
| - if exeStart != nil { |
| - inv, err = exeStart.CmdExe(ctx, rt.Host, b.tier(rt).MemoryMax, *spec.serving) |
| - } else { |
| - inv, err = b.Control.Cmd(ctx, rt.Host, b.tier(rt).MemoryMax) |
| + inv, err := arm.start(ctx) |
| + if errors.Is(err, errRootfsRefused) { |
| + // Root refused before systemctl start: nothing of the command ran. |
| + return fail(fmt.Errorf("%s: start cmd unit: %w", rt.Host, err)) |
| } |
| if err != nil { |
| // The request may have reached systemd before it failed (a timeout, |
| @@ -238,10 +292,43 @@ func (b *ExecBackend) StartCmd(ctx context.Context, rt registry.Route, spec CmdS |
| // and waits for its cgroup; it needs no invocation. |
| return &cmdUnit{b: b, rt: rt, out: out, errs: errs}, fmt.Errorf("%s: start cmd unit: %w", rt.Host, err) |
| } |
| - log.Printf("activator: %s: started %s for run %s", rt.Host, instancectl.UnitName(instancectl.RoleCmd, rt.Host), spec.RunID) |
| + log.Printf("activator: %s: started %s for run %s", rt.Host, arm.unit, spec.RunID) |
| return &cmdUnit{b: b, rt: rt, inv: inv, out: out, errs: errs}, nil |
| } |
| +// binaryCmdArm is startCmdUnit's binary half: the nested gate (which |
| +// refuses a rootfs row or an unknown runtime), then the staged build root |
| +// mounts (CmdExe) or the live link (Cmd), childEnv over cmdVars in the |
| +// launch file, launch.argv as its argv. |
| +func (b *ExecBackend) binaryCmdArm(ctx context.Context, rt registry.Route, spec CmdSpec, launch cmdLaunch) (cmdArm, error) { |
| + if err := b.nestedGate(rt); err != nil { |
| + return cmdArm{}, err |
| + } |
| + var exeStart cmdExeStarter |
| + if spec.serving != nil { |
| + cs, ok := b.Control.(cmdExeStarter) |
| + if !ok { |
| + return cmdArm{}, fmt.Errorf("%s: %w", rt.Host, errNoCmdExe) |
| + } |
| + exeStart = cs |
| + } else if err := b.ensureLiveLink(ctx, rt.Host); err != nil { |
| + return cmdArm{}, err |
| + } |
| + return cmdArm{ |
| + unit: instancectl.UnitName(instancectl.RoleCmd, rt.Host), |
| + write: func(p instancePaths) error { |
| + env := childEnv(b.cmdVars(rt, spec.genEnv, p.dbPath, spec.RunID, spec.RunDir)) |
| + return b.writeLaunch(p, instancectl.RoleCmd, rt.Host, launch.argv, env) |
| + }, |
| + start: func(ctx context.Context) (string, error) { |
| + if exeStart != nil { |
| + return exeStart.CmdExe(ctx, rt.Host, b.tier(rt).MemoryMax, *spec.serving) |
| + } |
| + return b.Control.Cmd(ctx, rt.Host, b.tier(rt).MemoryMax) |
| + }, |
| + }, nil |
| +} |
| + |
| type cmdUnit struct { |
| b *ExecBackend |
| rt registry.Route |
diff --git a/internal/activator/generations_file.go b/internal/activator/generations_file.go| index 11feb5c21..a84d6f75c 100644 |
| --- a/internal/activator/generations_file.go |
| +++ b/internal/activator/generations_file.go |
| @@ -169,7 +169,8 @@ func (a *Service) generationsSnapshotLocked() release.Generations { |
| // stored, so both are on disk before either execs; |
| // - a socketless attempt's build and fallback (Task 11); |
| // - the generation every run not yet proven settled was admitted |
| -// against (merge ruling M2). |
| +// against (merge ruling M2), and the build that run names |
| +// (CmdSpec.Build) when it names one [Astra R1 9]. |
| // |
| // The plan's builds stay listed while the entry lives, as e.plan does |
| // (afterWake reads it after the wake): a few more pins than the processes |
| @@ -208,6 +209,9 @@ func (a *Service) entryGenerationsLocked(e *actEntry, add func(release.StagedIde |
| // own process once a swap retires it. |
| for _, h := range cmdHoldsLocked(e) { |
| gen(h.gen) |
| + if h.build.Version != "" { |
| + add(h.build) |
| + } |
| } |
| } |
diff --git a/internal/activator/rootfs_cmd_lease_test.go b/internal/activator/rootfs_cmd_lease_test.go| new file mode 100644 |
| index 000000000..5d14d7a0d |
| --- /dev/null |
| +++ b/internal/activator/rootfs_cmd_lease_test.go |
| @@ -0,0 +1,137 @@ |
| +package activator |
| + |
| +// Plan 3 Task 12, Task 8's carry (C7): a carlos run attached to a resident |
| +// is under the resident's lease watch. When the watch begins the lease's |
| +// drain, and at the loss itself, the run's unit is stopped and proven at |
| +// once, beside the generation kills, never only after the generation's |
| +// own drain. Not parallel: residentPoll and residentDrainBudget are |
| +// package vars. |
| + |
| +import ( |
| + "context" |
| + "errors" |
| + "path/filepath" |
| + "sync" |
| + "testing" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/registry" |
| +) |
| + |
| +// killCmdBackend is killBackend with the run capability on the nested |
| +// layout: every run's unit is unit. |
| +type killCmdBackend struct { |
| + *killBackend |
| + unit *fakeCmdUnit |
| +} |
| + |
| +func (b *killCmdBackend) StartCmd(context.Context, registry.Route, CmdSpec) (CmdUnit, error) { |
| + return b.unit, nil |
| +} |
| + |
| +// residentRunService is residentKillService over a killCmdBackend. |
| +func residentRunService(t *testing.T, routes ...registry.Route) (*Service, *killCmdBackend) { |
| + t.Helper() |
| + kb := &killBackend{fakeBackend: &fakeBackend{layoutFn: func(registry.Route) (Layout, string) { return LayoutNested, "" }}} |
| + cb := &killCmdBackend{killBackend: kb, unit: &fakeCmdUnit{}} |
| + reg, err := registry.Open(filepath.Join(t.TempDir(), "registry.db")) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + a := New(Config{Bucket: "test-bucket", Idle: time.Hour}, cb, reg) |
| + clk := &fakeClock{t: time.Unix(1_700_000_000, 0)} |
| + a.now = clk.now |
| + a.gens = true |
| + armRootfsForTest(a) |
| + a.residentJitter = func() float64 { return 0 } |
| + a.residentLister = &fakeResidents{routes: routes} |
| + t.Cleanup(func() { a.Shutdown(context.Background()) }) |
| + return a, cb |
| +} |
| + |
| +// A renewal that fails outright with a run attached: the run's unit is |
| +// stopped at the loss, while the generation's SIGTERM drain is still |
| +// hanging, and the run reads as interrupted by the lost lease. |
| +func TestResidentRunStopsAtLeaseLoss(t *testing.T) { |
| + host := "shop.example.com" |
| + a, cb := residentRunService(t, residentRoute(host)) |
| + cb.unit.rep = cb.lastRep |
| + var rep *ownedRep |
| + cb.mu.Lock() |
| + cb.repWrap = func(r *fakeRep) Rep { rep = newOwnedRep(r, time.Now().Add(time.Hour)); return rep } |
| + cb.mu.Unlock() |
| + startResident(t, a, host) |
| + run, err := a.RunCmd(context.Background(), residentRoute(host), CmdSpec{RunID: "run_a"}) |
| + if err != nil { |
| + t.Fatalf("RunCmd: %v", err) |
| + } |
| + proc := cb.lastProc() |
| + drain := make(chan struct{}) |
| + proc.setStopGate(drain) |
| + var drained sync.Once |
| + endDrain := func() { drained.Do(func() { close(drain) }) } |
| + t.Cleanup(func() { proc.exit(); endDrain() }) |
| + cb.kmu.Lock() |
| + cb.onKill = func(uint64) { proc.exit() } |
| + cb.kmu.Unlock() |
| + |
| + rep.lose(errors.New("renew: the lock was taken")) |
| + waitFor(t, "the run's unit stopped at the loss", func() bool { n, _ := cb.unit.stopped(); return n >= 1 }) |
| + if proc.stopCalls() != 0 { |
| + t.Fatal("the generation's drain finished first: the run was not stopped at the loss") |
| + } |
| + if why, _ := run.Interrupted(); why != StopLeaseLost { |
| + t.Fatalf("the run was interrupted for %q, want %q", why, StopLeaseLost) |
| + } |
| + endDrain() |
| + waitFor(t, "the stop to finish", func() bool { return !a.hasEntry(host) }) |
| + if n, repClosed := cb.unit.stopped(); n != 1 || repClosed { |
| + t.Fatalf("the run's unit was stopped %d times, the last after the replica closed: %v; want once, before", n, repClosed) |
| + } |
| + run.Release() |
| +} |
| + |
| +// A renewal that hangs: the safety deadline the last renewal set is 1.5 s |
| +// off and the drain budget 1 s, so the watch begins the drain half a |
| +// second in. The run attached meanwhile is stopped then, before the |
| +// deadline, not after the generation's drain. |
| +func TestResidentRunStopsWhenTheLeaseRunsShort(t *testing.T) { |
| + shrinkResidentPoll(t, 10*time.Millisecond) |
| + shrinkDrainBudget(t, time.Second) |
| + host := "shop.example.com" |
| + a, cb := residentRunService(t, residentRoute(host)) |
| + cb.unit.rep = cb.lastRep |
| + deadline := time.Now().Add(1500 * time.Millisecond) |
| + cb.mu.Lock() |
| + cb.repWrap = func(r *fakeRep) Rep { return newOwnedRep(r, deadline) } |
| + cb.mu.Unlock() |
| + startResident(t, a, host) |
| + run, err := a.RunCmd(context.Background(), residentRoute(host), CmdSpec{RunID: "run_a"}) |
| + if err != nil { |
| + t.Fatalf("RunCmd: %v", err) |
| + } |
| + proc := cb.lastProc() |
| + drain := make(chan struct{}) |
| + proc.setStopGate(drain) |
| + var drained sync.Once |
| + endDrain := func() { drained.Do(func() { close(drain) }) } |
| + t.Cleanup(func() { proc.exit(); endDrain() }) |
| + cb.kmu.Lock() |
| + cb.onKill = func(uint64) { proc.exit(); endDrain() } // SIGKILL ends the drain |
| + cb.kmu.Unlock() |
| + waitFor(t, "the run's unit stopped while the drain fits", func() bool { n, _ := cb.unit.stopped(); return n >= 1 }) |
| + if !time.Now().Before(deadline) { |
| + t.Fatalf("the run was stopped %s after the safety deadline", time.Since(deadline)) |
| + } |
| + if proc.stopCalls() != 0 { |
| + t.Fatal("the generation's drain finished first: the run waited for it") |
| + } |
| + if why, _ := run.Interrupted(); why != StopLeaseLost { |
| + t.Fatalf("the run was interrupted for %q, want %q", why, StopLeaseLost) |
| + } |
| + waitFor(t, "the stop to finish", func() bool { return !a.hasEntry(host) }) |
| + if _, repClosed := cb.unit.stopped(); repClosed { |
| + t.Fatal("the run's unit was stopped after the replica closed") |
| + } |
| + run.Release() |
| +} |
diff --git a/internal/activator/rootfs_cmd_test.go b/internal/activator/rootfs_cmd_test.go| new file mode 100644 |
| index 000000000..9c0c242ba |
| --- /dev/null |
| +++ b/internal/activator/rootfs_cmd_test.go |
| @@ -0,0 +1,375 @@ |
| +//go:build linux |
| + |
| +package activator |
| + |
| +// Plan 3 Task 12: carlos run on a rootfs row, through the real control |
| +// handler (rootfsCtlHarness): the run's argv reaches root as the image's |
| +// argv, its launch file carries only the composed environment, and its |
| +// unit is polled, stopped and proven gone as the rootfs cmd unit |
| +// (Review Focus 7, A8). Not parallel: the tests set the agent's PATH or |
| +// shrink package bounds. |
| +// |
| +// The harness starts a real rootfs image only where the box platform is |
| +// linux-arm64 (release's manifest rule names rootfs-linux-arm64 alone, and |
| +// root resolves the image for its own platform). On another platform the |
| +// request is still sent and checked, and root's refusal of the image is |
| +// checked as a refusal; the tests that need a running unit say so and |
| +// skip. |
| + |
| +import ( |
| + "bytes" |
| + "context" |
| + "encoding/json" |
| + "errors" |
| + "net" |
| + "net/http" |
| + "os" |
| + "path/filepath" |
| + "slices" |
| + "strings" |
| + "sync" |
| + "testing" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/instancectl" |
| + "github.com/carlosframework/platform/internal/provision" |
| + "github.com/carlosframework/platform/internal/registry" |
| + "github.com/carlosframework/platform/internal/release" |
| +) |
| + |
| +// harnessStartsImages reports whether the harness's root can start a |
| +// rootfs image on this box. |
| +func harnessStartsImages() bool { return release.BoxPlatform() == "linux-arm64" } |
| + |
| +// runSpecIn is a run's spec on the harness's row: its run directory where |
| +// checkCmdRunDir wants it, and buffers for its streams. |
| +func (h *rootfsCtlHarness) runSpecIn(id string, args ...string) CmdSpec { |
| + dir := filepath.Join(h.eb.pathsFor(h.rt).dataDir, CmdRunDirName, id) |
| + return CmdSpec{RunID: id, RunDir: dir, Args: args, Stdout: &syncBuffer{}, Stderr: &syncBuffer{}} |
| +} |
| + |
| +// TestRootfsCmdRunsArgsInTheImage: StartCmd on a rootfs row sends root the |
| +// serving image and the member's arguments exactly as given (no live-link |
| +// prefix), as /cmd's argv; writes a schema-2 launch.cmd.json naming |
| +// process "cmd" with no argv and the composed environment only; and starts |
| +// the rootfs cmd unit, never the binary one. |
| +func TestRootfsCmdRunsArgsInTheImage(t *testing.T) { |
| + t.Setenv("PATH", "/agent/bin") |
| + h := newRootfsCtlHarness(t) |
| + h.runProbes() |
| + id, err := h.eb.BuildIdentity(h.rt, "v1") |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + spec := h.runSpecIn("run_a", "bin/rails", "db:seed", "--trace") |
| + spec.serving = stagedExeOf(id) |
| + spec.genEnv = map[string]string{"SHOP_MODE": "live", "CARLOS_SOCKET": "/tenant/elsewhere.sock"} |
| + u, err := h.eb.StartCmd(context.Background(), h.rt, spec) |
| + |
| + cmds := h.cmdRequests() |
| + if len(cmds) != 1 { |
| + t.Fatalf("%d /cmd requests, want one", len(cmds)) |
| + } |
| + q := cmds[0].query |
| + if q.Get("runtime") != "rootfs" || q.Get("image") != id.StagedPath || q.Get("version") != "v1" || q.Get("digest") != id.Digest || q.Has("process") { |
| + t.Fatalf("/cmd query %v, want the serving image %+v and no process", q, id) |
| + } |
| + if q.Get("memory_max") == "" || q.Get("memory_max") == "0" { |
| + t.Errorf("/cmd memory_max %q, want the row's sized tier", q.Get("memory_max")) |
| + } |
| + var body struct{ Argv []string } |
| + if err := json.Unmarshal(cmds[0].body, &body); err != nil || !slices.Equal(body.Argv, spec.Args) { |
| + t.Fatalf("/cmd argv %q (%v), want the member's arguments %q exactly", body.Argv, err, spec.Args) |
| + } |
| + |
| + l := readLaunchNamed(t, h.eb, h.rt, instancectl.LaunchFileName(instancectl.RoleCmd)) |
| + if l.Schema != instancectl.LaunchSchemaRootfs || l.Runtime != registry.RuntimeRootfsV1 || l.Process != "cmd" || len(l.Argv) != 0 { |
| + t.Fatalf("launch.cmd.json schema %d runtime %q process %q argv %q; want schema %d, rootfs, cmd, no argv", |
| + l.Schema, l.Runtime, l.Process, l.Argv, instancectl.LaunchSchemaRootfs) |
| + } |
| + for _, want := range []string{"CARLOS_SOCKET=" + h.rt.Socket, "CARLOS_RUN_ID=run_a", "CARLOS_RUN_DIR=" + spec.RunDir, "SHOP_MODE=live"} { |
| + if !slices.Contains(l.Env, want) { |
| + t.Errorf("launch env lacks %s:\n%s", want, strings.Join(l.Env, "\n")) |
| + } |
| + } |
| + for _, kv := range l.Env { |
| + if strings.HasPrefix(kv, "PATH=") || strings.HasPrefix(kv, "CARLOS_CONTROL_SOCKET=") || kv == "CARLOS_SOCKET=/tenant/elsewhere.sock" { |
| + t.Errorf("launch env carries %s", kv) |
| + } |
| + } |
| + if binary := h.callsLike("start --no-block " + instancectl.UnitName(instancectl.RoleCmd, h.rt.Host)); len(binary) != 0 { |
| + t.Fatalf("root started the binary cmd unit: %v", binary) |
| + } |
| + |
| + unit := instancectl.RootfsUnitName(instancectl.RoleCmd, h.rt.Host) |
| + if !harnessStartsImages() { |
| + // Root refuses the image itself here (see the file comment): a |
| + // refusal, nothing started, no unit handed back. |
| + if !errors.Is(err, instancectl.ErrStagedImage) || !errors.Is(err, errRootfsRefused) || u != nil { |
| + t.Fatalf("on %s: StartCmd = %v, %v; want root's staged-image refusal, marked, and no unit", release.BoxPlatform(), u, err) |
| + } |
| + if starts := h.callsLike("start --no-block " + unit); len(starts) != 0 { |
| + t.Fatalf("a refused /cmd started %v", starts) |
| + } |
| + return |
| + } |
| + if err != nil { |
| + t.Fatalf("StartCmd: %v", err) |
| + } |
| + if starts := h.callsLike("start --no-block " + unit); len(starts) != 1 { |
| + t.Fatalf("root's starts %v, want %s once", h.callsLike("start "), unit) |
| + } |
| + raw, err := os.ReadFile(filepath.Join(instancectl.RootfsExeDir(h.srv.ExeRoot, provision.InstanceID(h.rt.Host), instancectl.RoleCmd), "launch.json")) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + var rl instancectl.RootfsLaunch |
| + if err := json.Unmarshal(raw, &rl); err != nil { |
| + t.Fatal(err) |
| + } |
| + if rl.Process != "cmd" || !slices.Equal(rl.Argv, spec.Args) || rl.Version != "v1" || !strings.EqualFold(rl.Digest, id.Digest) { |
| + t.Fatalf("root's launch %+v, want process cmd, argv %q, build v1 at %s", rl, spec.Args, id.Digest) |
| + } |
| + h.release(unit) |
| + if err := u.StopAndSettle(context.Background()); err != nil { |
| + t.Fatalf("StopAndSettle once the unit ended: %v", err) |
| + } |
| +} |
| + |
| +// TestRootfsRunRefusedByRootIsARefusal: root answers /cmd 503 (its |
| +// readiness, a probe flipping): the run's start is a refusal, marked |
| +// errRootfsRefused, with no unit handed back and nothing started (INV-4). |
| +func TestRootfsRunRefusedByRootIsARefusal(t *testing.T) { |
| + h := newRootfsCtlHarness(t) |
| + h.runProbes() |
| + id, err := h.eb.BuildIdentity(h.rt, "v1") |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + h.mu.Lock() |
| + h.cmdStatus = http.StatusServiceUnavailable |
| + h.mu.Unlock() |
| + spec := h.runSpecIn("run_a", "true") |
| + spec.serving, spec.genEnv = stagedExeOf(id), map[string]string{} |
| + u, err := h.eb.StartCmd(context.Background(), h.rt, spec) |
| + if !errors.Is(err, errRootfsRefused) || !errors.Is(err, instancectl.ErrStartRefused) || u != nil { |
| + t.Fatalf("StartCmd = %v, %v; want a marked ErrStartRefused and no unit", u, err) |
| + } |
| + if v := verdictOf(err); v != gateNoOwnership { |
| + t.Fatalf("verdictOf = %d, want gateNoOwnership", v) |
| + } |
| + if starts := h.callsLike("start --no-block"); len(starts) != 0 { |
| + t.Fatalf("a refused /cmd started %v", starts) |
| + } |
| + // Without an image a rootfs run is refused before anything is laid out |
| + // or asked of root. |
| + spec = h.runSpecIn("run_b", "true") |
| + spec.genEnv = map[string]string{} |
| + if u, err := h.eb.StartCmd(context.Background(), h.rt, spec); !errors.Is(err, errNoCmdExe) || !errors.Is(err, errRootfsRefused) || u != nil { |
| + t.Fatalf("StartCmd with no image = %v, %v; want errNoCmdExe, marked", u, err) |
| + } |
| + if n := len(h.cmdRequests()); n != 1 { |
| + t.Fatalf("%d /cmd requests, want only the first run's", n) |
| + } |
| +} |
| + |
| +// heldRep is a replica that records its close. |
| +type heldRep struct { |
| + mu sync.Mutex |
| + closed bool |
| +} |
| + |
| +func (r *heldRep) Err() error { return nil } |
| +func (r *heldRep) Close(context.Context) error { |
| + r.mu.Lock() |
| + defer r.mu.Unlock() |
| + r.closed = true |
| + return nil |
| +} |
| +func (r *heldRep) isClosed() bool { |
| + r.mu.Lock() |
| + defer r.mu.Unlock() |
| + return r.closed |
| +} |
| + |
| +type heldLease struct{ rep *heldRep } |
| + |
| +func (l heldLease) Replicate(context.Context, string, time.Duration) (Rep, error) { return l.rep, nil } |
| +func (heldLease) Release(context.Context) error { return nil } |
| + |
| +// runHarnessBackend is harnessBackend whose lease's replica records its |
| +// close, so a test sees the replica held while a run is unproven. |
| +type runHarnessBackend struct { |
| + *harnessBackend |
| + rep *heldRep |
| +} |
| + |
| +func (b *runHarnessBackend) Acquire(ctx context.Context, rt registry.Route) (Lease, error) { |
| + _, _ = b.harnessBackend.Acquire(ctx, rt) |
| + return heldLease{rep: b.rep}, nil |
| +} |
| + |
| +// awakeHarnessRow is a Service over the harness (harnessService's, with a |
| +// replica that records its close), its startup sweep clean, and the row |
| +// awake through its rootfs generation unit. |
| +func awakeHarnessRow(t *testing.T, h *rootfsCtlHarness) (*Service, *runHarnessBackend, *fakeClock) { |
| + t.Helper() |
| + reg, err := registry.Open(filepath.Join(t.TempDir(), "registry.db")) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + t.Cleanup(func() { reg.Close() }) |
| + hb := &runHarnessBackend{harnessBackend: &harnessBackend{SplitBackend: productionBackend(t, h.eb)}, rep: &heldRep{}} |
| + a := New(Config{Bucket: "test-bucket", Idle: time.Hour}, hb, reg) |
| + clk := &fakeClock{t: time.Unix(1_700_000_000, 0)} |
| + a.now = clk.now |
| + a.gens = true |
| + a.ArmRootfs() |
| + t.Cleanup(func() { a.Shutdown(context.Background()) }) |
| + if err := reg.Upsert(h.rt); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := startupSweepFor(a, h); err != nil { |
| + t.Fatalf("startup sweep: %v", err) |
| + } |
| + h.serveGenerations() |
| + done, err := a.beginRequest(context.Background(), h.rt) |
| + if err != nil { |
| + t.Fatalf("wake: %v", err) |
| + } |
| + done() |
| + return a, hb, clk |
| +} |
| + |
| +// TestRootfsRunPollsAndStopsTheRootfsUnit (Review Focus 7, A8): a run |
| +// started through Service.RunCmd on an awake rootfs entry, through the |
| +// real control handler with no binary cmd unit anywhere. Its CARLOS_SOCKET |
| +// is the row's canonical socket, which reaches the serving generation |
| +// (Task 6's carry). Its Poll reads the rootfs cmd unit (running, then done |
| +// with its invocation once it ends). A Bounce during the run stops |
| +// carlos-instance-rootfs-cmd@ (never carlos-instance-cmd@), and while that |
| +// unit's cgroup stays populated the stop is unproven: the entry stays, |
| +// pending, with its replica open; the run's own Stop is unproven too. Once |
| +// the unit ends, the sweep proves it gone and only then does the replica |
| +// close. |
| +func TestRootfsRunPollsAndStopsTheRootfsUnit(t *testing.T) { |
| + if !harnessStartsImages() { |
| + t.Skipf("the harness's root starts a rootfs image only on linux-arm64, and this box is %s", release.BoxPlatform()) |
| + } |
| + old := roleEmptyBound |
| + roleEmptyBound = 300 * time.Millisecond |
| + t.Cleanup(func() { roleEmptyBound = old }) |
| + h := newRootfsCtlHarness(t) |
| + h.runProbes() |
| + h.eb.ObservePoll = 20 * time.Millisecond |
| + a, hb, clk := awakeHarnessRow(t, h) |
| + host := h.rt.Host |
| + |
| + run, err := a.RunCmd(context.Background(), h.rt, h.runSpecIn("run_a", "bin/rails", "runner", "Shop.sync")) |
| + if err != nil { |
| + t.Fatalf("RunCmd: %v", err) |
| + } |
| + unit := instancectl.RootfsUnitName(instancectl.RoleCmd, host) |
| + binary := instancectl.UnitName(instancectl.RoleCmd, host) |
| + if len(h.callsLike("start --no-block "+unit)) != 1 || len(h.callsLike("start --no-block "+binary)) != 0 { |
| + t.Fatalf("root's starts %v, want %s alone", h.callsLike("start"), unit) |
| + } |
| + |
| + // The run's socket is the canonical one, and it reaches the serving |
| + // generation (the cmd unit binds the instance's run directory at the |
| + // same path, so the link resolves the same way inside its namespace). |
| + l := readLaunchNamed(t, h.eb, h.rt, instancectl.LaunchFileName(instancectl.RoleCmd)) |
| + if !slices.Contains(l.Env, "CARLOS_SOCKET="+h.rt.Socket) { |
| + t.Fatalf("the run's CARLOS_SOCKET is not the canonical %s:\n%s", h.rt.Socket, strings.Join(l.Env, "\n")) |
| + } |
| + g, _ := a.genStateForTest(host) |
| + if target, err := os.Readlink(h.rt.Socket); err != nil || target != g.Socket { |
| + t.Fatalf("the canonical socket links to %q (%v), want the serving generation's %s", target, err, g.Socket) |
| + } |
| + if code := getOverUnix(t, h.rt.Socket); code != http.StatusOK { |
| + t.Fatalf("a request over the run's CARLOS_SOCKET answered %d", code) |
| + } |
| + |
| + type polled struct { |
| + st instancectl.CmdStatus |
| + err error |
| + } |
| + pollDone := make(chan polled, 1) |
| + go func() { |
| + st, err := run.Poll(context.Background()) |
| + pollDone <- polled{st, err} |
| + }() |
| + select { |
| + case p := <-pollDone: |
| + t.Fatalf("Poll answered %+v (%v) while the rootfs cmd unit runs; the binary unit would read as gone", p.st, p.err) |
| + case <-time.After(400 * time.Millisecond): |
| + } |
| + |
| + h.setStuck(unit, true) |
| + if !a.Bounce(host) { |
| + t.Fatal("Bounce found no awake entry") |
| + } |
| + waitFor(t, "the instance's stop to keep its unproven run", func() bool { |
| + a.mu.Lock() |
| + defer a.mu.Unlock() |
| + e := a.entries[host] |
| + return e != nil && e.pendingStop |
| + }) |
| + if len(h.callsLike("stop "+unit)) == 0 { |
| + t.Fatalf("the stop never reached %s; systemctl saw:\n%s", unit, strings.Join(h.callsLike(""), "\n")) |
| + } |
| + if stops := h.callsLike("stop " + binary); len(stops) != 0 { |
| + t.Fatalf("the stop reached the binary cmd unit: %v", stops) |
| + } |
| + if hb.rep.isClosed() { |
| + t.Fatal("the replica closed while the run's unit was unproven") |
| + } |
| + sctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) |
| + if err := run.Stop(sctx); err == nil { |
| + t.Fatal("the run's Stop proved the rootfs cmd unit gone while its cgroup is populated") |
| + } |
| + cancel() |
| + if hb.rep.isClosed() || !a.hasEntry(host) { |
| + t.Fatal("the entry or the replica went while the run's unit was unproven") |
| + } |
| + |
| + h.release(unit) |
| + select { |
| + case p := <-pollDone: |
| + if p.err != nil || p.st.State != instancectl.CmdDone || p.st.InvocationID != run.Invocation() { |
| + t.Fatalf("Poll after the unit ended = %+v, %v; want done for invocation %s", p.st, p.err, run.Invocation()) |
| + } |
| + case <-time.After(10 * time.Second): |
| + t.Fatal("Poll did not answer once the rootfs cmd unit ended") |
| + } |
| + waitFor(t, "the sweep to prove the run gone and finish the stop", func() bool { |
| + clk.advance(time.Minute) |
| + a.sweepOnce() |
| + return !a.hasEntry(host) |
| + }) |
| + if !hb.rep.isClosed() { |
| + t.Fatal("the stop finished without closing the replica") |
| + } |
| + run.Release() |
| + if why, _ := run.Interrupted(); why == "" { |
| + t.Error("the run does not say the instance's stop interrupted it") |
| + } |
| +} |
| + |
| +// getOverUnix sends GET / over the unix socket at path and returns the |
| +// status. |
| +func getOverUnix(t *testing.T, path string) int { |
| + t.Helper() |
| + c := &http.Client{Timeout: 5 * time.Second, Transport: &http.Transport{DialContext: func(ctx context.Context, _, _ string) (net.Conn, error) { |
| + var d net.Dialer |
| + return d.DialContext(ctx, "unix", path) |
| + }}} |
| + res, err := c.Get("http://instance/") |
| + if err != nil { |
| + t.Fatalf("GET over %s: %v", path, err) |
| + } |
| + defer res.Body.Close() |
| + var b bytes.Buffer |
| + _, _ = b.ReadFrom(res.Body) |
| + return res.StatusCode |
| +} |
diff --git a/internal/activator/rootfs_ctl_harness_test.go b/internal/activator/rootfs_ctl_harness_test.go| index c625db9e6..dcccd1268 100644 |
| --- a/internal/activator/rootfs_ctl_harness_test.go |
| +++ b/internal/activator/rootfs_ctl_harness_test.go |
| @@ -21,12 +21,14 @@ package activator |
| // and cmdStatus makes /cmd answer a chosen status before the handler. |
| import ( |
| + "bytes" |
| "context" |
| "crypto/sha256" |
| "encoding/hex" |
| "encoding/json" |
| "errors" |
| "fmt" |
| + "io" |
| "net" |
| "net/http" |
| "net/http/httputil" |
| @@ -69,6 +71,15 @@ type rootfsCtlHarness struct { |
| cmdStatus int |
| onStart func(unit string) |
| requests []string // "METHOD /path" of every request the agent sent |
| + // cmds is every POST /cmd the agent sent, its query and body, before |
| + // the front answered or handed it on (Task 12). |
| + cmds []harnessCmd |
| +} |
| + |
| +// harnessCmd is one POST /cmd as the agent sent it. |
| +type harnessCmd struct { |
| + query url.Values |
| + body []byte |
| } |
| // newRootfsCtlHarness builds the harness for acme/shop's |
| @@ -160,9 +171,18 @@ func newRootfsCtlHarness(t *testing.T) *rootfsCtlHarness { |
| }, DisableKeepAlives: true}, |
| } |
| fs := &http.Server{Handler: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| + isCmd := r.Method == http.MethodPost && r.URL.Path == "/cmd" |
| + var body []byte |
| + if isCmd { |
| + body, _ = io.ReadAll(r.Body) |
| + r.Body = io.NopCloser(bytes.NewReader(body)) |
| + } |
| h.mu.Lock() |
| status := h.cmdStatus |
| h.requests = append(h.requests, r.Method+" "+r.URL.Path) |
| + if isCmd { |
| + h.cmds = append(h.cmds, harnessCmd{query: r.URL.Query(), body: body}) |
| + } |
| h.mu.Unlock() |
| if status != 0 && r.Method == http.MethodPost && r.URL.Path == "/cmd" { |
| http.Error(w, "not starting the cmd unit: refused by the test", status) |
| @@ -492,3 +512,18 @@ func (h *rootfsCtlHarness) launchFiles() []string { |
| } |
| return out |
| } |
| + |
| +// cmdRequests is a copy of every POST /cmd the agent sent. |
| +func (h *rootfsCtlHarness) cmdRequests() []harnessCmd { |
| + h.mu.Lock() |
| + defer h.mu.Unlock() |
| + return append([]harnessCmd(nil), h.cmds...) |
| +} |
| + |
| +// setStuck makes unit's stop fail (stuck) or succeed, leaving its state |
| +// and invocation as they are. |
| +func (h *rootfsCtlHarness) setStuck(unit string, stuck bool) { |
| + h.mu.Lock() |
| + defer h.mu.Unlock() |
| + h.stuck[unit] = stuck |
| +} |
diff --git a/internal/activator/rootfs_invariants_test.go b/internal/activator/rootfs_invariants_test.go| index 43c85ef1a..20d498017 100644 |
| --- a/internal/activator/rootfs_invariants_test.go |
| +++ b/internal/activator/rootfs_invariants_test.go |
| @@ -664,6 +664,42 @@ var rootfsProofHandles = map[string]func(t *testing.T, r *rootfsProofRig){ |
| } |
| r.noBinaryVerb(t) |
| }, |
| + // Task 12: the unit a rootfs run's StartCmd hands back, through the |
| + // production composition (startCmdUnit's rootfs arm), is polled, |
| + // stopped and proven as the rootfs cmd unit. |
| + "rootfs run cmdUnit (StartCmd)": func(t *testing.T, r *rootfsProofRig) { |
| + old := roleEmptyBound |
| + roleEmptyBound = 100 * time.Millisecond |
| + t.Cleanup(func() { roleEmptyBound = old }) |
| + r.ctl.cmdInv = "inv-r" |
| + r.ctl.cmdStatusRootfs = instancectl.CmdStatus{InvocationID: "inv-r", State: instancectl.CmdRunning} |
| + r.ctl.cmdStatus = instancectl.CmdStatus{InvocationID: "inv-r", State: instancectl.CmdGone} // the binary unit's answer |
| + id := stagedRootfsIdentity(t, r.b, "v2") |
| + dir := filepath.Join(r.b.pathsFor(r.rt).dataDir, CmdRunDirName, "run_a") |
| + spec := CmdSpec{RunID: "run_a", RunDir: dir, Args: []string{"true"}, Stdout: &syncBuffer{}, Stderr: &syncBuffer{}, |
| + serving: stagedExeOf(id), genEnv: map[string]string{}} |
| + u, err := productionBackend(t, r.b).StartCmd(context.Background(), r.rt, spec) |
| + if err != nil { |
| + t.Fatalf("StartCmd: %v", err) |
| + } |
| + r.ctl.mustHaveCallPrefix(t, "cmd-rootfs "+r.rt.Host+" ") |
| + st, err := u.Poll(context.Background()) |
| + if err != nil || st.State != instancectl.CmdRunning { |
| + t.Fatalf("Poll = %+v, %v; want running, from the rootfs cmd unit", st, err) |
| + } |
| + r.ctl.mustHaveCallPrefix(t, "cmdstatus-rootfs "+r.rt.Host+" inv-r") |
| + unit := instancectl.RootfsUnitName(instancectl.RoleCmd, r.rt.Host) |
| + if err := u.StopAndSettle(context.Background()); err == nil { |
| + t.Fatalf("StopAndSettle proved the cmd unit gone while %s's group is populated", unit) |
| + } |
| + r.ctl.mustHaveCallPrefix(t, "stop-rootfs "+r.rt.Host+" role=cmd gen=0") |
| + r.noBinaryVerb(t) |
| + r.setPopulated(t, unit, false) |
| + if err := u.StopAndSettle(context.Background()); err != nil { |
| + t.Fatalf("StopAndSettle once %s's group is empty: %v", unit, err) |
| + } |
| + r.noBinaryVerb(t) |
| + }, |
| } |
| // stagedRootfsIdentity stages acme/shop at ver as root's staging leaves it |
| @@ -888,6 +924,11 @@ var rootfsRefusals = []struct { |
| {"a backend gate's refusal, as the early gate marks it", notAdmitted(refuseRootfs(errors.New("x")))}, |
| {"a served row with no replica (errRootfsReplicaMissing, marked)", refuseRootfs(fmt.Errorf("x: %w", errRootfsReplicaMissing))}, |
| {"no placeholder placer (errNoRootfsDB, marked)", refuseRootfs(fmt.Errorf("x: %w", errNoRootfsDB))}, |
| + // Task 12: a rootfs run with no image to name, as rootfsCmdArm marks |
| + // it; root's pre-start /cmd answers come through as N1's rows above |
| + // (TestRootfsRunRefusedByRootIsARefusal sends one through the real |
| + // client). |
| + {"a rootfs run with no image (errNoCmdExe, marked)", refuseRootfs(fmt.Errorf("x: %w", errNoCmdExe))}, |
| } |
| func TestRootfsRefusalsAreNotBuildFailures(t *testing.T) { |
| @@ -935,6 +976,38 @@ var rootfsLaunchRows = map[string]func(t *testing.T) (instancectl.Launch, map[st |
| } |
| return l, vars |
| }, |
| + // Task 12: a carlos run's launch file, written by the production |
| + // composition's StartCmd over the environment its generation launched |
| + // with. |
| + "run": func(t *testing.T) (instancectl.Launch, map[string]string) { |
| + b, ctl := newRootfsBackend(t) |
| + ctl.cmdInv = "inv-r" |
| + rt := rootfsRoute(b) |
| + up, _ := startRootfsGen7(t, b, ctl, rt, "SHOP_MODE=live\n") |
| + id, err := b.BuildIdentity(rt, "v2") |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + p := b.pathsFor(rt) |
| + dir := filepath.Join(p.dataDir, CmdRunDirName, "r1") |
| + spec := CmdSpec{RunID: "r1", RunDir: dir, Args: []string{"true"}, Stdout: &syncBuffer{}, Stderr: &syncBuffer{}, |
| + serving: stagedExeOf(id), genEnv: up.LaunchEnv()} |
| + u, err := productionBackend(t, b).StartCmd(context.Background(), rt, spec) |
| + if err != nil { |
| + t.Fatalf("StartCmd: %v", err) |
| + } |
| + u.(*cmdUnit).out.Close() |
| + u.(*cmdUnit).errs.Close() |
| + l := readLaunchNamed(t, b, rt, instancectl.LaunchFileName(instancectl.RoleCmd)) |
| + if l.Process != "cmd" { |
| + t.Fatalf("the run's launch names process %q, want cmd", l.Process) |
| + } |
| + vars := b.rootfsCmdVars(rt, up.LaunchEnv(), p.dbPath, "r1", dir) |
| + if vars["SHOP_MODE"] != "live" { |
| + t.Fatalf("the instance's file did not reach the composed variables: %v", vars) |
| + } |
| + return l, vars |
| + }, |
| } |
| // rootfsComposerRows: process -> its composer's variables, production-wired: |
diff --git a/internal/activator/rootfs_service.go b/internal/activator/rootfs_service.go| index e14b2932b..62913cbb3 100644 |
| --- a/internal/activator/rootfs_service.go |
| +++ b/internal/activator/rootfs_service.go |
| @@ -890,6 +890,9 @@ func (a *Service) residentLeaseShort(e *actEntry, left time.Duration) { |
| } |
| log.Printf("activator: %s: its lease is not renewing and is safe for %s more; stopping it while a drain still fits", e.host, left.Round(time.Millisecond)) |
| a.beginStopLocked(e, StopLeaseLost) |
| + // Its runs stop now too, inside the same budget, rather than after |
| + // the generation's drain (Plan 3 Task 12). |
| + a.stopCmdsForLeaseLocked(e) |
| } |
| // residentLeaseLost is the loss itself: e is stopped if it is still awake, |
| @@ -904,7 +907,8 @@ func (a *Service) residentLeaseLost(e *actEntry, err error) { |
| } |
| // residentLeaseLostLocked begins e's stop for a lost lease (if it is still |
| -// awake), cancels its generation attempts, and returns every generation |
| +// awake), stops its runs (stopCmdsForLeaseLocked), cancels its generation |
| +// attempts, and returns every generation |
| // number the entry has (the current one and each operation member's) for |
| // killResidentGens; nil when e is no longer the host's entry. The caller |
| // holds a.mu. |
| @@ -916,6 +920,9 @@ func (a *Service) residentLeaseLostLocked(e *actEntry, err error) []uint64 { |
| if e.state == actAwake { |
| a.beginStopLocked(e, StopLeaseLost) |
| } |
| + // An attached run is stopped at the loss, whatever the entry's state, |
| + // beside the generation kills (Plan 3 Task 12). |
| + a.stopCmdsForLeaseLocked(e) |
| gens := []uint64{} |
| if e.gen.N != 0 { |
| gens = append(gens, e.gen.N) |
diff --git a/internal/activator/rootfs_test.go b/internal/activator/rootfs_test.go| index 98b077de2..4a749e165 100644 |
| --- a/internal/activator/rootfs_test.go |
| +++ b/internal/activator/rootfs_test.go |
| @@ -1032,8 +1032,10 @@ func TestRootfsStartRefusesABinaryStagedUnderARootfsRow(t *testing.T) { |
| } |
| // A rootfs row never reaches a binary launch: the binary unit starts |
| -// (seed, sidecar, a swap's spawn, cmd) refuse it at nestedGate, and the |
| -// flat seam refuses it with RFS-2-C01. Nothing is asked of root. |
| +// (seed, sidecar, a swap's spawn) refuse it at nestedGate, and the flat |
| +// seam refuses it with RFS-2-C01. A run (StartCmd) takes its rootfs arm |
| +// since Plan 3 Task 12, never the binary one: with no image to name it is |
| +// refused (errNoCmdExe, marked). Nothing is asked of root. |
| func TestRootfsRowsNeverTakeABinaryLaunch(t *testing.T) { |
| t.Parallel() |
| b, ctl := newRootfsBackend(t) |
| @@ -1046,15 +1048,15 @@ func TestRootfsRowsNeverTakeABinaryLaunch(t *testing.T) { |
| _, _, err := b.spawnUnitFrom(context.Background(), rt, rt.Socket, 0, nil, cgroup.Limit{}) |
| return err |
| }, |
| - "cmd": func() error { |
| - _, err := b.StartCmd(context.Background(), rt, CmdSpec{RunID: "r1", RunDir: filepath.Join(provision.InstanceDir(b.DataDir, rt.Host), CmdRunDirName, "r1")}) |
| - return err |
| - }, |
| } { |
| if err := start(); !errors.Is(err, errRootfsBinaryLaunch) { |
| t.Errorf("%s: %v", name, err) |
| } |
| } |
| + _, err := b.StartCmd(context.Background(), rt, CmdSpec{RunID: "r1", RunDir: filepath.Join(provision.InstanceDir(b.DataDir, rt.Host), CmdRunDirName, "r1")}) |
| + if !errors.Is(err, errNoCmdExe) || !errors.Is(err, errRootfsRefused) || errors.Is(err, errRootfsBinaryLaunch) { |
| + t.Errorf("cmd: %v, want the rootfs arm's errNoCmdExe, marked", err) |
| + } |
| if len(ctl.callList()) != 0 { |
| t.Errorf("root was asked: %v", ctl.callList()) |
| } |
diff --git a/internal/activator/rootfsenv_test.go b/internal/activator/rootfsenv_test.go| index 501fd3434..0d8857a00 100644 |
| --- a/internal/activator/rootfsenv_test.go |
| +++ b/internal/activator/rootfsenv_test.go |
| @@ -5,6 +5,7 @@ import ( |
| "path/filepath" |
| "slices" |
| "sort" |
| + "strings" |
| "testing" |
| "github.com/carlosframework/platform/internal/instancectl" |
| @@ -187,3 +188,37 @@ func TestBinaryLaunchUnchanged(t *testing.T) { |
| t.Errorf("the tenant's variable is missing from the binary launch: %v", env) |
| } |
| } |
| + |
| +// Task 6's carry, checked by Task 12: a run's CARLOS_SOCKET is the row's |
| +// canonical socket while the serving generation listens on g<n>/app.sock. |
| +// On a box, the canonical path is a symlink (swapCanonicalLink) whose |
| +// target is the generation's absolute path, and both sit in the instance's |
| +// run directory, /run/carlos/instances/<instance id>, which the rootfs cmd |
| +// template binds at that same path (BindPaths=/run/carlos/instances/%I, |
| +// pinned by internal/host's TestRootfsTemplatesPerUnitLines) under the |
| +// unit named for that instance id. So the link resolves inside the run's |
| +// namespace exactly as outside it. TestRootfsRunPollsAndStopsTheRootfsUnit |
| +// dials it through the harness. |
| +func TestRunCanonicalSocketResolvesInsideTheCmdUnitsBinds(t *testing.T) { |
| + t.Parallel() |
| + host := "shop.example.com" |
| + iid := provision.InstanceID(host) |
| + runDir := provision.InstanceRunDir(host) |
| + if runDir != "/run/carlos/instances/"+iid { |
| + t.Fatalf("the instance's run directory is %s, not the path the cmd template binds", runDir) |
| + } |
| + if unit := instancectl.RootfsUnitName(instancectl.RoleCmd, host); unit != "carlos-instance-rootfs-cmd@"+iid+".service" { |
| + t.Fatalf("the rootfs cmd unit is %s, not the template instance %%I = %s", unit, iid) |
| + } |
| + rt := registry.Route{Host: host, Socket: provision.NestedSocket(host)} |
| + g := Gen{N: 3, Socket: nestedGenSocketIn(runDir, 3)} |
| + if !linksCanonical(rt, g) { |
| + t.Fatal("a nested generation's socket is not linked from the canonical path") |
| + } |
| + for name, p := range map[string]string{"canonical": rt.Socket, "generation": g.Socket} { |
| + rel, err := filepath.Rel(runDir, p) |
| + if err != nil || !filepath.IsAbs(p) || rel == ".." || strings.HasPrefix(rel, "../") { |
| + t.Errorf("the %s socket %s is not an absolute path inside %s", name, p, runDir) |
| + } |
| + } |
| +} |