carlos / platform Public

activator: the rootfs release's backend: StartRelease in the rootfs cmd unit from the staged image, ReleaseEnv, execLease's lease signal

Rootfs apps Plan 3 Group R, pass R1a. ExecBackend gains ReleaseBackend:
StartRelease runs startRootfsCmd (every rootfs gate, a whole identity, the
rootfs control half, the cmd role's directories, both stream listeners, a
schema-2 launch file from rootfsLaunchEnv alone, the caller's exec gate,
then CmdRootfs naming the staged image's release process at b.tier).
Root's pre-start answers are marked refusals with no unit; any other
error after the POST hands back an invocation-less cmdUnit to settle.
Both streams write whole lines into one capped, mutex-guarded sink.
ReleaseEnv mints the admin token and instance key as the run role does
(nested rows only), applies the replica key gate and composes
rootfsReleaseVars (no CARLOS_RUN_ID or CARLOS_RUN_DIR). SplitBackend
forwards both for exec rows and refuses unit rows. execLease gains
SafeUntil and Lost; leaseWatch, watchOf, releaseDue and releaseTimeout
land in rootfsrelease.go. Harness: unit SubState/Result/ExecMain*,
finish, POST /cmd capture, stageRootfsWithProcesses. Group R is started;
the inventory fixture is judged as Group A alone. No copy is built.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev b9d63dc4a33ce005075d5b424dc9d045512dc089 parent 080ce59
13 files changed, +1,284 −12
  • internal/activator/backend_exec.go +9 −0
  • internal/activator/backend_rootfs.go +217 −0
  • internal/activator/backend_unit.go +24 −0
  • internal/activator/cmdunit.go +10 −0
  • internal/activator/production_backend_test.go +20 −0
  • internal/activator/rootfs_ctl_harness_test.go +86 −3
  • internal/activator/rootfs_invariants_test.go +77 −0
  • internal/activator/rootfs_release_backend_test.go +347 −0
  • internal/activator/rootfsenv.go +9 −0
  • internal/activator/rootfsenv_test.go +17 −0
  • internal/activator/rootfsrelease.go +68 −0
  • internal/activator/rootfsrelease_test.go +387 −0
  • plan3_groups_test.go +13 −9
diff --git a/internal/activator/backend_exec.go b/internal/activator/backend_exec.go
index ff1a777b4..3c75bd141 100644
--- a/internal/activator/backend_exec.go
+++ b/internal/activator/backend_exec.go
@@ -824,6 +824,15 @@ func (l *execLease) RetryRelease(ctx context.Context) error { return l.held.Retr
// spent handle or a poisoned one.
func (l *execLease) Err() error { return l.held.Err() }
+// SafeUntil is the held lease's safety deadline while ownership holds, and
+// the loss once a renewal has failed (lease.Held.SafeUntil). A release run
+// under a wake's lease (Group R, leaseWatch) is stopped ahead of it.
+func (l *execLease) SafeUntil() (time.Time, error) { return l.held.SafeUntil() }
+
+// Lost closes when the held lease's renewal fails or its safety deadline
+// passes (lease.Held.Lost).
+func (l *execLease) Lost() <-chan struct{} { return l.held.Lost() }
+
// Restore puts the row's database in place for a wake. A row whose seed is
// placeable (ready, swapped or placed) or committed goes through the seed
// fallback (seedplace.go), which never reports fresh; every other row
diff --git a/internal/activator/backend_rootfs.go b/internal/activator/backend_rootfs.go
index 5375b26b1..27ba1255e 100644
--- a/internal/activator/backend_rootfs.go
+++ b/internal/activator/backend_rootfs.go
@@ -6,12 +6,18 @@ import (
"context"
"errors"
"fmt"
+ "io"
"log"
+ "os"
"slices"
"strings"
+ "sync"
+ "github.com/carlosframework/platform/internal/applog"
+ "github.com/carlosframework/platform/internal/instancectl"
"github.com/carlosframework/platform/internal/registry"
"github.com/carlosframework/platform/internal/release"
+ "github.com/carlosframework/platform/internal/runs"
)
// ProcessReader is the one read of a rootfs build's declared processes
@@ -125,3 +131,214 @@ func (a *Service) declaredProcesses(rt registry.Route, g Gen) (map[string]releas
}
return r.Processes(rt, id)
}
+
+// ReleaseBackend is the backend half of a rootfs build's release process
+// (Group R): the environment it launches with and its start in the rootfs
+// cmd unit. ExecBackend has it; SplitBackend forwards it for an exec row.
+type ReleaseBackend interface {
+ // ReleaseEnv is the environment a release of rt launches with [pf
+ // R1.3]: the run role's admin token, instance key and file environment
+ // (minted if absent, as a web start mints them), the replica key gate,
+ // then rootfsReleaseVars. File I/O: never under a.mu.
+ ReleaseEnv(ctx context.Context, rt registry.Route) (map[string]string, error)
+ // StartRelease starts id's release process in the rootfs cmd unit (see
+ // startRootfsCmd), its output written to out a line at a time. It may
+ // return a unit together with an error: the start may have begun, and
+ // the unit must still be stopped and settled. A refusal before root ran
+ // anything returns no unit and an error marked refuseRootfs or
+ // launchRefused.
+ StartRelease(ctx context.Context, rt registry.Route, id release.StagedIdentity, env map[string]string, out io.Writer) (CmdUnit, error)
+}
+
+var (
+ _ ReleaseBackend = (*ExecBackend)(nil)
+ _ ReleaseBackend = (*SplitBackend)(nil)
+)
+
+// stagedImageOf is id as root's rootfs verbs name an image, beside
+// stagedExeOf: the staged path, version and digest, with the declared
+// process root runs from it, or an operator's 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}
+}
+
+// ReleaseEnv implements ReleaseBackend [pf R1.3]. It takes the three
+// steps a web start's prepare takes for the run role (prepare.go), so a
+// first boot's release has the admin token and the instance key, and the
+// web start after it finds the same ones; then the replica gate a cmd
+// start asks; then the release's composition over the file environment.
+// The environment is never logged.
+func (b *ExecBackend) ReleaseEnv(ctx context.Context, rt registry.Route) (map[string]string, error) {
+ if !rt.Rootfs() {
+ return nil, refuseRootfs(fmt.Errorf("%s: a release command runs only on a rootfs instance", rt.Host))
+ }
+ // Nothing is minted on a row that is not nested: a fenced or
+ // conflicting row's paths name the box's flat directory, which may be
+ // a host mid-migration (ensureInstanceKeyAt).
+ p := b.pathsFor(rt)
+ switch p.layout {
+ case LayoutNested:
+ case LayoutFenced, LayoutConflict:
+ return nil, refuseRootfs(fmt.Errorf("%s: refusing a release command: %s", rt.Host, p.reason))
+ default:
+ return nil, refuseRootfs(fmt.Errorf("%s: %s", rt.Host, rootfsNotNestedText))
+ }
+ if err := os.MkdirAll(p.dataDir, 0o700); err != nil {
+ return nil, err
+ }
+ hctx, cancel := context.WithTimeout(ctx, haSecretsBudget)
+ defer cancel()
+ if err := b.ensureAdminTokenFor(hctx, rt, p); err != nil {
+ return nil, fmt.Errorf("admin token for %s: %w", rt.Host, err)
+ }
+ if _, err := b.ensureInstanceKeyFor(hctx, rt, p); err != nil {
+ return nil, fmt.Errorf("instance key for %s: %w", rt.Host, err)
+ }
+ env, layer, err := b.launchEnvLayer(hctx, rt)
+ if err != nil {
+ return nil, err
+ }
+ if err := b.replicaKeyGate(rt, env, layer, false); err != nil {
+ return nil, err
+ }
+ return b.rootfsReleaseVars(rt, env, p.dbPath), nil
+}
+
+// StartRelease implements ReleaseBackend: startRootfsCmd naming id's
+// release process, both streams written into out through one capped line
+// writer (releaseOutput) [pf R1.5].
+func (b *ExecBackend) StartRelease(ctx context.Context, rt registry.Route, id release.StagedIdentity, env map[string]string, out io.Writer) (CmdUnit, error) {
+ o := newReleaseOutput(rt.Host, out, runs.MaxOutputBytes)
+ return b.startRootfsCmd(ctx, rt, id, release.ProcessRelease, env, o.stream(), o.stream())
+}
+
+// startRootfsCmd starts process, a declared process of id, in rt's rootfs
+// cmd unit [pf R0.1, R1.4], in this order: every rootfs gate; a whole
+// identity and a control channel with a rootfs half; the instance's
+// directories; the two stream listeners the unit writes stdout and stderr
+// to; a schema-2 launch file with env alone (rootfsLaunchEnv, never the
+// agent's own environment); the caller's exec gate, the last thing before
+// root is asked; then CmdRootfs at the row's tier. Root's answers given
+// before systemctl start are refusals (marked, no unit): nothing of the
+// build ran. Any other error after the POST hands back a unit with the
+// error, since the unit may be running and must still be stopped and
+// settled. StartCmd, the binary path, is a separate function and stays as
+// it is (INV-6).
+func (b *ExecBackend) startRootfsCmd(ctx context.Context, rt registry.Route, id release.StagedIdentity, process string, env map[string]string, stdout, stderr io.Writer) (CmdUnit, error) {
+ if !rt.Rootfs() {
+ return nil, refuseRootfs(fmt.Errorf("%s: a rootfs command runs only on a rootfs instance", rt.Host))
+ }
+ if err := b.rootfsGates(ctx, rt); err != nil {
+ return nil, err
+ }
+ if id.Version == "" || id.StagedPath == "" || id.Digest == "" {
+ return nil, refuseRootfs(fmt.Errorf("%s: %w (build %q, path %q, digest %q)", rt.Host, errPartialStagedIdentity, id.Version, id.StagedPath, id.Digest))
+ }
+ rc, err := b.rootfsControl()
+ if err != nil {
+ return nil, refuseRootfs(fmt.Errorf("%s: %w", rt.Host, err))
+ }
+ p, _, _, _, err := b.prepare(rt, instancectl.RoleCmd)
+ if err != nil {
+ return nil, err
+ }
+ out, err := listenCmdStream(b.logSocketNamed(rt.Host, string(instancectl.RoleCmd)), stdout)
+ if err != nil {
+ return nil, fmt.Errorf("stdout listener for %s: %w", rt.Host, err)
+ }
+ errs, err := listenCmdStream(b.logSocketNamed(rt.Host, cmdErrSocket), stderr)
+ if err != nil {
+ out.Close()
+ return nil, fmt.Errorf("stderr listener for %s: %w", rt.Host, err)
+ }
+ fail := func(err error) (CmdUnit, error) {
+ out.Close()
+ errs.Close()
+ return nil, err
+ }
+ if err := b.writeRootfsLaunchFor(p, instancectl.RoleCmd, 0, rt.Host, process, rootfsLaunchEnv(env)); err != nil {
+ return fail(err)
+ }
+ // The caller's exec gate (withExecGate), right before root is asked;
+ // runExecGate also writes ctx's pending wake record between two asks
+ // of the gate (runPendingRecord). A refusal is launchRefused: no /cmd
+ // is sent.
+ if err := runExecGate(ctx); err != nil {
+ return fail(err)
+ }
+ unit := instancectl.RootfsUnitName(instancectl.RoleCmd, rt.Host)
+ inv, err := rc.CmdRootfs(ctx, rt.Host, b.tier(rt).MemoryMax, stagedImageOf(id, process, nil))
+ if errors.Is(err, instancectl.ErrStagedImage) || errors.Is(err, instancectl.ErrStartRefused) {
+ // Answered before systemctl start: a refusal, never the build's
+ // failure (INV-4).
+ return fail(refuseRootfs(fmt.Errorf("%s: start %s: %w", rt.Host, process, err)))
+ }
+ if err != nil {
+ // The request may have reached systemd before it failed, so the
+ // unit may be running: a unit with no invocation still stops the
+ // host's rootfs cmd unit and waits for its cgroup.
+ log.Printf("activator: %s: start of %s (%s of build %s) failed, it may have begun: %v", rt.Host, unit, process, id.Version, err)
+ return &cmdUnit{b: b, rt: rt, out: out, errs: errs}, fmt.Errorf("%s: start %s: %w", rt.Host, process, err)
+ }
+ log.Printf("activator: %s: started %s (%s of build %s) memory.max=%d", rt.Host, unit, process, id.Version, b.tier(rt).MemoryMax)
+ return &cmdUnit{b: b, rt: rt, inv: inv, out: out, errs: errs}, nil
+}
+
+// releaseOutput is where both streams of a release command go [pf R1.5]:
+// one sink for both, guarded by a mutex (each stream's copy runs in its own
+// goroutine), fed whole lines by a line splitter per stream so the two
+// never interleave inside a line, and capped at max bytes, after which the
+// rest is dropped with one diagnostic in the journal. A nil out discards.
+type releaseOutput struct {
+ host string
+ max int64
+
+ mu sync.Mutex
+ out io.Writer
+ n int64
+ capped bool
+}
+
+func newReleaseOutput(host string, out io.Writer, max int64) *releaseOutput {
+ return &releaseOutput{host: host, max: max, out: out}
+}
+
+// stream is one stream's writer into o: its own line splitter, at most
+// execLogLineMax bytes a line as the app log's tee cuts them.
+func (o *releaseOutput) stream() io.Writer {
+ return &releaseStream{lines: applog.NewLineWriter(execLogLineMax, o.line)}
+}
+
+// line writes one whole line to out, while the total stays within max.
+func (o *releaseOutput) line(s string) {
+ o.mu.Lock()
+ defer o.mu.Unlock()
+ if o.out == nil || o.capped {
+ return
+ }
+ if o.n+int64(len(s)) > o.max {
+ o.capped = true
+ log.Printf("activator: %s: the release command's output passed %d bytes; the rest is not in the app log", o.host, o.max)
+ return
+ }
+ o.n += int64(len(s))
+ _, _ = o.out.Write([]byte(s))
+}
+
+// releaseStream is one stream's line splitter. endStream (cmdStream's
+// hook at the stream's end) writes a last line that had no newline.
+type releaseStream struct{ lines *applog.LineWriter }
+
+func (s *releaseStream) Write(p []byte) (int, error) { return s.lines.Write(p) }
+func (s *releaseStream) endStream() { _ = s.lines.Close() }
+
+// lineEmitter is a writer handing each Write to emit as one line, for a
+// releaseOutput's out; a nil emit discards.
+type lineEmitter func(string)
+
+func (e lineEmitter) Write(p []byte) (int, error) {
+ if e != nil {
+ e(string(p))
+ }
+ return len(p), nil
+}
diff --git a/internal/activator/backend_unit.go b/internal/activator/backend_unit.go
index 78969a6da..c027f207e 100644
--- a/internal/activator/backend_unit.go
+++ b/internal/activator/backend_unit.go
@@ -50,6 +50,7 @@ import (
"context"
"errors"
"fmt"
+ "io"
"net/http"
"os/exec"
"strings"
@@ -371,6 +372,29 @@ func (b *SplitBackend) Processes(rt registry.Route, id release.StagedIdentity) (
return nil, refuseRootfs(fmt.Errorf("%s: %w", rt.Host, errNoRootfsControl))
}
+// ReleaseEnv forwards a release's environment (Group R) to the exec side.
+// A unit-backed row, or an exec side without the release, is refused as
+// Processes refuses it.
+func (b *SplitBackend) ReleaseEnv(ctx context.Context, rt registry.Route) (map[string]string, error) {
+ if rt.Backing != registry.BackingUnit {
+ if r, ok := b.Exec.(ReleaseBackend); ok {
+ return r.ReleaseEnv(ctx, rt)
+ }
+ }
+ return nil, refuseRootfs(fmt.Errorf("%s: %w", rt.Host, errNoRootfsControl))
+}
+
+// StartRelease forwards a release's start (Group R) to the exec side,
+// refused like ReleaseEnv: no unit is returned, so nothing ran.
+func (b *SplitBackend) StartRelease(ctx context.Context, rt registry.Route, id release.StagedIdentity, env map[string]string, out io.Writer) (CmdUnit, error) {
+ if rt.Backing != registry.BackingUnit {
+ if r, ok := b.Exec.(ReleaseBackend); ok {
+ return r.StartRelease(ctx, rt, id, env, out)
+ }
+ }
+ return nil, refuseRootfs(fmt.Errorf("%s: %w", rt.Host, errNoRootfsControl))
+}
+
func (b *SplitBackend) Restore(ctx context.Context, rt registry.Route) (bool, error) {
return b.pick(rt).Restore(ctx, rt)
}
diff --git a/internal/activator/cmdunit.go b/internal/activator/cmdunit.go
index ead3f300e..ac604ee75 100644
--- a/internal/activator/cmdunit.go
+++ b/internal/activator/cmdunit.go
@@ -360,8 +360,18 @@ func (s *cmdStream) copy(c net.Conn) {
defer close(s.copied)
defer c.Close()
_, _ = io.Copy(s.w, c)
+ // A writer that splits lines (a release's, releaseStream) is told the
+ // stream has ended, so a last line with no newline still reaches it.
+ // A run's writers have no such method and are as they were.
+ if e, ok := s.w.(streamEnder); ok {
+ e.endStream()
+ }
}
+// streamEnder is a cmd stream's writer that wants to know its stream has
+// ended (releaseStream).
+type streamEnder interface{ endStream() }
+
// cmdAcceptGrace is how long Drain waits for a connection still queued in
// the listener's backlog. A var so tests can shrink it.
var cmdAcceptGrace = time.Second
diff --git a/internal/activator/production_backend_test.go b/internal/activator/production_backend_test.go
index 4ecab1210..cbd6fc1ef 100644
--- a/internal/activator/production_backend_test.go
+++ b/internal/activator/production_backend_test.go
@@ -7,6 +7,7 @@ package activator
import (
"context"
"errors"
+ "io"
"sync"
"testing"
"time"
@@ -67,6 +68,22 @@ func TestProductionBackendImplementsRootfsSeams(t *testing.T) {
}
return err
},
+ // R1a: both release methods refuse, and StartRelease hands back no
+ // unit, so nothing ran.
+ "ReleaseBackend": func() error {
+ r, ok := b.(ReleaseBackend)
+ if !ok {
+ t.Fatal("SplitBackend is not a ReleaseBackend")
+ }
+ if env, err := r.ReleaseEnv(context.Background(), unit); env != nil || !errors.Is(err, errNoRootfsControl) || !errors.Is(err, errRootfsRefused) {
+ t.Errorf("ReleaseEnv on a unit row = %v, %v; want a marked errNoRootfsControl", env, err)
+ }
+ u, err := r.StartRelease(context.Background(), unit, stagedRootfsIdentity(t, eb, "v2"), nil, io.Discard)
+ if u != nil {
+ t.Errorf("StartRelease on a unit row returned a unit")
+ }
+ return err
+ },
}
for name, refusal := range rows {
if err := refusal(); err == nil {
@@ -85,6 +102,9 @@ func TestProductionBackendImplementsRootfsSeams(t *testing.T) {
if err := rows["ProcessReader"](); !errors.Is(err, errNoRootfsControl) || !errors.Is(err, errRootfsRefused) {
t.Errorf("Processes on a unit row = %v, want a marked errNoRootfsControl", err)
}
+ if err := rows["ReleaseBackend"](); !errors.Is(err, errNoRootfsControl) || !errors.Is(err, errRootfsRefused) {
+ t.Errorf("StartRelease on a unit row = %v, want a marked errNoRootfsControl", err)
+ }
// An exec row is forwarded: the exec side's own answers.
if err := b.(rootfsStartable).rootfsStartable(context.Background(), rootfsRoute(eb)); err != nil {
t.Errorf("rootfsStartable on the exec side's passing row = %v", err)
diff --git a/internal/activator/rootfs_ctl_harness_test.go b/internal/activator/rootfs_ctl_harness_test.go
index c625db9e6..64e3c5600 100644
--- a/internal/activator/rootfs_ctl_harness_test.go
+++ b/internal/activator/rootfs_ctl_harness_test.go
@@ -19,14 +19,19 @@ package activator
// and proof names the rootfs unit. /sweep is the real handler over the
// same fake; stuck makes a unit's stop fail (a unit that will not stop),
// and cmdStatus makes /cmd answer a chosen status before the handler.
+// Group R (R1a) adds a unit's SubState, Result, ExecMainStatus and
+// ExecMainCode (a started unit reads active/running until finish), the
+// capture of every POST /cmd, and a stager declaring chosen processes.
import (
+ "bytes"
"context"
"crypto/sha256"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
+ "io"
"net"
"net/http"
"net/http/httputil"
@@ -51,6 +56,15 @@ import (
type harnessUnit struct {
active bool
inv string
+ // sub, result, status and code are SubState, Result, ExecMainStatus
+ // and ExecMainCode (R1a): "running" from a start, set by finish.
+ sub, result, status, code string
+}
+
+// harnessCmd is one POST /cmd as the agent sent it (R1a, after 6c6f8607's).
+type harnessCmd struct {
+ query url.Values
+ body []byte
}
type rootfsCtlHarness struct {
@@ -69,6 +83,9 @@ 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.
+ cmds []harnessCmd
}
// newRootfsCtlHarness builds the harness for acme/shop's
@@ -160,9 +177,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)
@@ -194,6 +220,13 @@ func newRootfsCtlHarness(t *testing.T) *rootfsCtlHarness {
// release for this box's platform: the image at its version path and the
// manifest sibling naming it.
func stageRootfsForBox(t *testing.T, b *ExecBackend, ver string) {
+ t.Helper()
+ stageRootfsWithProcesses(t, b, ver, map[string]release.Process{release.ProcessWeb: {Command: []string{"/app/serve"}, WorkingDir: "/app"}})
+}
+
+// stageRootfsWithProcesses is stageRootfsForBox with the manifest declaring
+// procs (R1a: a release process beside web), and names the staged build.
+func stageRootfsWithProcesses(t *testing.T, b *ExecBackend, ver string, procs map[string]release.Process) release.StagedIdentity {
t.Helper()
body := []byte("squashfs image of shop " + ver)
if err := release.StageArtifact(b.OptDir, rootfsTestAcct, ver, rootfsTestApp, body); err != nil {
@@ -202,7 +235,7 @@ func stageRootfsForBox(t *testing.T, b *ExecBackend, ver string) {
sum := sha256.Sum256(body)
m := release.Manifest{Schema: 1, App: rootfsTestApp, Version: ver, Kind: release.KindRootfs,
Artifacts: map[string]release.Artifact{"rootfs-" + release.BoxPlatform(): {File: release.RootfsArtifactFile, SHA256: hex.EncodeToString(sum[:]), Size: int64(len(body))}},
- Processes: map[string]release.Process{release.ProcessWeb: {Command: []string{"/app/serve"}, WorkingDir: "/app"}}}
+ Processes: procs}
raw, err := json.Marshal(m)
if err != nil {
t.Fatal(err)
@@ -210,6 +243,7 @@ func stageRootfsForBox(t *testing.T, b *ExecBackend, ver string) {
if err := release.StageManifest(b.OptDir, rootfsTestAcct, ver, rootfsTestApp, raw); err != nil {
t.Fatal(err)
}
+ return release.StagedIdentity{Version: ver, StagedPath: release.VersionPath(b.OptDir, rootfsTestAcct, ver, rootfsTestApp), Digest: hex.EncodeToString(sum[:])}
}
// runProbes runs the control service's probes, as its probe loop does at
@@ -359,7 +393,7 @@ func (h *rootfsCtlHarness) systemctl(_ context.Context, args ...string) (string,
switch args[0] {
case "start":
h.seq++
- h.units[last] = &harnessUnit{active: true, inv: fmt.Sprintf("%032x", h.seq)}
+ h.units[last] = &harnessUnit{active: true, inv: fmt.Sprintf("%032x", h.seq), sub: "running"}
h.setPopulatedLocked(last, true)
if f := h.onStart; f != nil {
hook = func() { f(last) }
@@ -371,6 +405,7 @@ func (h *rootfsCtlHarness) systemctl(_ context.Context, args ...string) (string,
}
if u := h.units[last]; u != nil {
u.active = false
+ u.sub = "dead"
h.setPopulatedLocked(last, false)
}
return "", nil
@@ -444,8 +479,12 @@ func (h *rootfsCtlHarness) propsLocked(unit string) map[string]string {
m["ActiveState"] = "inactive"
if u := h.units[unit]; u != nil {
m["InvocationID"] = u.inv
- if u.active {
+ m["SubState"], m["Result"], m["ExecMainStatus"], m["ExecMainCode"] = u.sub, u.result, u.status, u.code
+ switch {
+ case u.active:
m["ActiveState"] = "active"
+ case u.result != "" && u.result != "success":
+ m["ActiveState"] = "failed"
}
}
m["ControlGroup"] = h.controlGroupLocked(unit)
@@ -492,3 +531,47 @@ func (h *rootfsCtlHarness) launchFiles() []string {
}
return out
}
+
+// finish makes unit's main process exit with ExecMainCode code and
+// ExecMainStatus status, as the oneshot rootfs cmd unit (RemainAfterExit)
+// reads after it: a clean exit is active/exited with Result success; any
+// other is failed with Result exit-code, signal or core-dump. Its cgroup
+// is left as it is (setPopulatedLocked).
+func (h *rootfsCtlHarness) finish(unit, code, status string) {
+ h.mu.Lock()
+ defer h.mu.Unlock()
+ u := h.units[unit]
+ if u == nil {
+ h.t.Errorf("finish: %s was never started", unit)
+ return
+ }
+ u.code, u.status = code, status
+ if code == "1" && status == "0" {
+ u.active, u.sub, u.result = true, "exited", "success"
+ return
+ }
+ u.active, u.sub = false, "failed"
+ switch code {
+ case "2":
+ u.result = "signal"
+ case "3":
+ u.result = "core-dump"
+ default:
+ u.result = "exit-code"
+ }
+}
+
+// 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 abdf8bcfc..d4c6c13d1 100644
--- a/internal/activator/rootfs_invariants_test.go
+++ b/internal/activator/rootfs_invariants_test.go
@@ -29,6 +29,7 @@ import (
"go/parser"
"go/token"
"go/types"
+ "io"
"os"
"path/filepath"
"regexp"
@@ -664,6 +665,46 @@ var rootfsProofHandles = map[string]func(t *testing.T, r *rootfsProofRig){
}
r.noBinaryVerb(t)
},
+ // R1a: the unit StartRelease hands back is the rootfs cmd unit's: its
+ // start, poll and stop name it, and its settle stays unproven while
+ // that unit's group is populated, whatever the binary unit answers.
+ "release cmdUnit (StartRelease)": func(t *testing.T, r *rootfsProofRig) {
+ oldEmpty, oldGrace := roleEmptyBound, cmdAcceptGrace
+ roleEmptyBound, cmdAcceptGrace = 100*time.Millisecond, 20*time.Millisecond
+ t.Cleanup(func() { roleEmptyBound, cmdAcceptGrace = oldEmpty, oldGrace })
+ id := stagedRootfsIdentity(t, r.b, "v2")
+ r.ctl.cmdInv = "inv-rel"
+ r.ctl.cmdStatusRootfs = instancectl.CmdStatus{InvocationID: "inv-rel", State: instancectl.CmdRunning}
+ r.ctl.cmdStatus = instancectl.CmdStatus{InvocationID: "inv-rel", State: instancectl.CmdGone} // the binary unit's answer
+ env, err := r.b.ReleaseEnv(context.Background(), r.rt)
+ if err != nil {
+ t.Fatalf("ReleaseEnv: %v", err)
+ }
+ u, err := r.b.StartRelease(context.Background(), r.rt, id, env, io.Discard)
+ if err != nil || u == nil || u.Invocation() != "inv-rel" {
+ t.Fatalf("StartRelease = %v, %v", u, err)
+ }
+ r.ctl.mustHaveCallPrefix(t, "cmd-rootfs "+r.rt.Host+" memory_max=")
+ if img := r.ctl.lastRootfsImage(); img.Process != release.ProcessRelease || img.Version != "v2" || img.Path != id.StagedPath || img.Digest != id.Digest || img.Argv != nil {
+ t.Fatalf("the release named image %+v, want B's release process", img)
+ }
+ 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-rel")
+ unit := instancectl.RootfsUnitName(instancectl.RoleCmd, r.rt.Host)
+ if err := u.StopAndSettle(context.Background()); err == nil {
+ t.Fatalf("StopAndSettle proved the release 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
@@ -944,6 +985,30 @@ var rootfsLaunchRows = map[string]func(t *testing.T) (instancectl.Launch, map[st
}
return l, vars
},
+ // R1a: the release's launch file, written by StartRelease from the
+ // environment ReleaseEnv composed, through the production backend.
+ "release": func(t *testing.T) (instancectl.Launch, map[string]string) {
+ eb, ctl := newRootfsBackend(t)
+ var b Backend = productionBackend(t, eb)
+ rb := b.(ReleaseBackend)
+ rt := rootfsRoute(eb)
+ writeInstanceEnv(t, eb, rt, "SHOP_MODE=live\n")
+ id := stagedRootfsIdentity(t, eb, "v2")
+ ctl.cmdInv = "inv-rel"
+ vars, err := rb.ReleaseEnv(context.Background(), rt)
+ if err != nil {
+ t.Fatalf("ReleaseEnv: %v", err)
+ }
+ if vars["SHOP_MODE"] != "live" {
+ t.Fatalf("the instance's file did not reach the composed variables: %v", vars)
+ }
+ u, err := rb.StartRelease(context.Background(), rt, id, vars, io.Discard)
+ if err != nil || u == nil {
+ t.Fatalf("StartRelease: %v, %v", u, err)
+ }
+ t.Cleanup(func() { u.(*cmdUnit).out.Close(); u.(*cmdUnit).errs.Close() })
+ return readLaunchFile(t, eb, rt, instancectl.RoleCmd), vars
+ },
}
// rootfsComposerRows: process -> its composer's variables, production-wired:
@@ -959,6 +1024,18 @@ var rootfsComposerRows = map[string]func(t *testing.T, envFile string) map[strin
p := b.pathsFor(rt)
return b.rootfsCmdVars(rt, up.LaunchEnv(), p.dbPath, "r1", filepath.Join(p.dataDir, CmdRunDirName, "r1"))
},
+ // R1a: the release's composer, over the instance's files as ReleaseEnv
+ // reads them for the run role.
+ "release": func(t *testing.T, envFile string) map[string]string {
+ b, _ := newRootfsBackend(t)
+ rt := rootfsRoute(b)
+ writeInstanceEnv(t, b, rt, envFile)
+ vars, err := b.ReleaseEnv(context.Background(), rt)
+ if err != nil {
+ t.Fatalf("ReleaseEnv: %v", err)
+ }
+ return vars
+ },
}
// rootfsAgentOnlyEnv is the agent's own environment for the INV-5 test:
diff --git a/internal/activator/rootfs_release_backend_test.go b/internal/activator/rootfs_release_backend_test.go
new file mode 100644
index 000000000..b2a9aaa1f
--- /dev/null
+++ b/internal/activator/rootfs_release_backend_test.go
@@ -0,0 +1,347 @@
+//go:build linux
+
+package activator
+
+// Group R, R1a: the release's backend half through the real control
+// handler (rootfsCtlHarness). StartRelease starts the build's release
+// process in the rootfs cmd unit from the staged image, and the cmdUnit it
+// hands back polls and proves that unit gone, never the binary cmd unit.
+// Root starts a rootfs image only on linux-arm64 [pf R0.4], so the tests
+// that need the unit running skip elsewhere (needRootfsStart); what the
+// agent sends and root's refusals are checked on every platform.
+
+import (
+ "context"
+ "encoding/json"
+ "errors"
+ "io"
+ "os"
+ "path/filepath"
+ "slices"
+ "strconv"
+ "strings"
+ "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"
+)
+
+// releaseProcs is a build declaring web and a release process.
+func releaseProcs() map[string]release.Process {
+ return map[string]release.Process{
+ release.ProcessWeb: {Command: []string{"/app/serve"}, WorkingDir: "/app"},
+ release.ProcessRelease: {Command: []string{"/app/bin/rails", "db:migrate"}, WorkingDir: "/app", TimeoutSec: 120},
+ }
+}
+
+// releaseHarness is the harness with its probes passed, live on v1, and
+// build v2 staged declaring a release process; it answers v2's identity
+// and the environment ReleaseEnv composes for the row.
+func releaseHarness(t *testing.T) (*rootfsCtlHarness, release.StagedIdentity, map[string]string) {
+ t.Helper()
+ h := newRootfsCtlHarness(t)
+ h.runProbes()
+ id := stageRootfsWithProcesses(t, h.eb, "v2", releaseProcs())
+ env, err := h.eb.ReleaseEnv(context.Background(), h.rt)
+ if err != nil {
+ t.Fatalf("ReleaseEnv: %v", err)
+ }
+ return h, id, env
+}
+
+// needRootfsStart skips t where root cannot start a rootfs image [pf R0.4].
+func needRootfsStart(t *testing.T) {
+ t.Helper()
+ if p := release.BoxPlatform(); p != "linux-arm64" {
+ t.Skipf("root starts a rootfs image only on linux-arm64 (a rootfs manifest names %s alone); this box is %s", release.RootfsArtifactKey, p)
+ }
+}
+
+// shrinkCmdBounds shrinks the cgroup wait and the streams' accept grace for
+// a test that settles a cmd unit. Not parallel: both are package vars.
+func shrinkCmdBounds(t *testing.T) {
+ t.Helper()
+ oldEmpty, oldGrace := roleEmptyBound, cmdAcceptGrace
+ roleEmptyBound, cmdAcceptGrace = 200*time.Millisecond, 50*time.Millisecond
+ t.Cleanup(func() { roleEmptyBound, cmdAcceptGrace = oldEmpty, oldGrace })
+}
+
+// settleAtEnd stops and proves u gone when the test ends.
+func settleAtEnd(t *testing.T, h *rootfsCtlHarness, u CmdUnit) {
+ t.Cleanup(func() {
+ h.release(instancectl.RootfsUnitName(instancectl.RoleCmd, h.rt.Host))
+ if err := u.StopAndSettle(context.Background()); err != nil {
+ t.Errorf("settling the release unit at the end: %v", err)
+ }
+ })
+}
+
+// noBinaryCmdUnit fails t if any systemctl call named the binary cmd unit.
+func noBinaryCmdUnit(t *testing.T, h *rootfsCtlHarness) {
+ t.Helper()
+ bin := instancectl.UnitName(instancectl.RoleCmd, h.rt.Host)
+ for _, c := range h.callsLike("") {
+ if strings.Contains(c, bin) || strings.Contains(c, "carlos-instance-cmd@") {
+ t.Errorf("systemctl was asked about the binary cmd unit: %q", c)
+ }
+ }
+}
+
+func TestReleaseRunsInTheCmdUnitFromTheNewImage(t *testing.T) {
+ shrinkCmdBounds(t)
+ t.Setenv("PATH", "/agent/bin")
+ h, id, env := releaseHarness(t)
+ live := release.VersionPath(h.eb.OptDir, rootfsTestAcct, "v1", rootfsTestApp)
+ u, err := h.eb.StartRelease(context.Background(), h.rt, id, env, io.Discard)
+
+ // What the agent sent and wrote, on every platform: the POST /cmd names
+ // B's image with the release process at the row's tier, and the launch
+ // file is schema 2 with the composed environment alone.
+ cmds := h.cmdRequests()
+ if len(cmds) != 1 {
+ t.Fatalf("POST /cmd sent %d times, want once", len(cmds))
+ }
+ q := cmds[0].query
+ if q.Get("runtime") != "rootfs" || q.Get("image") != id.StagedPath || q.Get("version") != "v2" || q.Get("digest") != id.Digest || q.Get("process") != release.ProcessRelease {
+ t.Errorf("POST /cmd query %v, want B's image, version, digest and process release", q)
+ }
+ if q.Get("image") == live {
+ t.Errorf("POST /cmd names the live link's build %s", live)
+ }
+ if want := strconv.FormatInt(h.eb.tier(h.rt).MemoryMax, 10); q.Get("memory_max") != want {
+ t.Errorf("POST /cmd memory_max %q, want the row's tier %s", q.Get("memory_max"), want)
+ }
+ if len(cmds[0].body) != 0 {
+ t.Errorf("POST /cmd carries a body %q: a declared process has no argv", cmds[0].body)
+ }
+ l := readLaunchFile(t, h.eb, h.rt, instancectl.RoleCmd)
+ if l.Schema != instancectl.LaunchSchemaRootfs || l.Process != release.ProcessRelease || len(l.Argv) != 0 || l.Runtime != registry.RuntimeRootfsV1 {
+ t.Errorf("launch.cmd.json schema %d process %q argv %q runtime %q, want schema %d, release, no argv", l.Schema, l.Process, l.Argv, l.Runtime, instancectl.LaunchSchemaRootfs)
+ }
+ lenv := envMap(t, l.Env)
+ if lenv["CARLOS_DB"] != provision.NestedDBPath(h.eb.DataDir, h.rt.Host) || lenv["CARLOS_SOCKET"] != h.rt.Socket {
+ t.Errorf("CARLOS_DB %q CARLOS_SOCKET %q, want the nested database and the row's socket %q", lenv["CARLOS_DB"], lenv["CARLOS_SOCKET"], h.rt.Socket)
+ }
+ for _, k := range []string{"CARLOS_CONTROL_SOCKET", "CARLOS_PURGE", "CARLOS_RUN_ID", "CARLOS_RUN_DIR", "PATH"} {
+ if v, ok := lenv[k]; ok {
+ t.Errorf("the release's launch file carries %s=%q", k, v)
+ }
+ }
+ if !slices.Equal(l.Env, rootfsLaunchEnv(env)) {
+ t.Errorf("launch env %q, want rootfsLaunchEnv of ReleaseEnv's", l.Env)
+ }
+
+ needRootfsStart(t)
+ if err != nil || u == nil {
+ t.Fatalf("StartRelease = %v, %v", u, err)
+ }
+ settleAtEnd(t, h, u)
+ unit := instancectl.RootfsUnitName(instancectl.RoleCmd, h.rt.Host)
+ if starts := h.callsLike("start "); !slices.Contains(starts, "start --no-block "+unit) {
+ t.Errorf("systemctl starts %q, want %s", starts, unit)
+ }
+ noBinaryCmdUnit(t, h)
+ // Root's resolved launch, in the unit's exe layout: B's image, B's
+ // version and digest, the release process's own command.
+ dir := instancectl.RootfsExeDir(h.srv.ExeRoot, provision.InstanceID(h.rt.Host), instancectl.RoleCmd)
+ if target, err := os.Readlink(filepath.Join(dir, instancectl.RootfsExeImage)); err != nil || target != id.StagedPath {
+ t.Errorf("the cmd unit's image is %q (%v), want B's %s", target, err, id.StagedPath)
+ }
+ raw, err := os.ReadFile(filepath.Join(dir, instancectl.RootfsExeLaunch))
+ if err != nil {
+ t.Fatal(err)
+ }
+ var rl instancectl.RootfsLaunch
+ if err := json.Unmarshal(raw, &rl); err != nil {
+ t.Fatal(err)
+ }
+ if rl.Process != release.ProcessRelease || rl.Version != "v2" || !strings.EqualFold(rl.Digest, id.Digest) || !slices.Equal(rl.Argv, releaseProcs()[release.ProcessRelease].Command) {
+ t.Errorf("root's launch %+v, want B's release process", rl)
+ }
+}
+
+func TestReleasePollsTheRootfsCmdUnit(t *testing.T) {
+ shrinkCmdBounds(t)
+ h, id, env := releaseHarness(t)
+ needRootfsStart(t)
+ u, err := h.eb.StartRelease(context.Background(), h.rt, id, env, io.Discard)
+ if err != nil || u == nil {
+ t.Fatalf("StartRelease = %v, %v", u, err)
+ }
+ settleAtEnd(t, h, u)
+ unit := instancectl.RootfsUnitName(instancectl.RoleCmd, h.rt.Host)
+ type answer struct {
+ st instancectl.CmdStatus
+ err error
+ }
+ done := make(chan answer, 1)
+ go func() {
+ st, err := u.Poll(context.Background())
+ done <- answer{st, err}
+ }()
+ // A poll of the binary unit would answer CmdGone at once: the running
+ // rootfs unit keeps root's long poll open.
+ select {
+ case a := <-done:
+ t.Fatalf("the poll of the running release answered at once: %+v, %v", a.st, a.err)
+ case <-time.After(400 * time.Millisecond):
+ }
+ if shows := h.callsLike("show -p InvocationID,ActiveState,SubState,Result,ExecMainStatus,ExecMainCode " + unit); len(shows) == 0 {
+ t.Errorf("root never read %s's state; calls %q", unit, h.callsLike("show"))
+ }
+ noBinaryCmdUnit(t, h)
+ h.finish(unit, "1", "3")
+ select {
+ case a := <-done:
+ if a.err != nil || a.st.State != instancectl.CmdDone || a.st.Status != "3" || a.st.InvocationID != u.Invocation() {
+ t.Errorf("the poll answered %+v, %v; want CmdDone with status 3 for %s", a.st, a.err, u.Invocation())
+ }
+ case <-time.After(10 * time.Second):
+ t.Fatal("the open poll did not answer once the release exited")
+ }
+}
+
+func TestReleaseStopProvesTheRootfsCmdUnitGone(t *testing.T) {
+ shrinkCmdBounds(t)
+ h, id, env := releaseHarness(t)
+ needRootfsStart(t)
+ u, err := h.eb.StartRelease(context.Background(), h.rt, id, env, io.Discard)
+ if err != nil || u == nil {
+ t.Fatalf("StartRelease = %v, %v", u, err)
+ }
+ settleAtEnd(t, h, u)
+ unit := instancectl.RootfsUnitName(instancectl.RoleCmd, h.rt.Host)
+ bin := instancectl.UnitName(instancectl.RoleCmd, h.rt.Host)
+ // A unit that will not stop: its group stays populated 1. The binary
+ // unit's group is absent, which would read as proven.
+ h.setStuck(unit, true)
+ err = u.StopAndSettle(context.Background())
+ if err == nil {
+ t.Fatalf("StopAndSettle proved %s gone while its group is populated", unit)
+ }
+ if !strings.Contains(err.Error(), "processes remained") {
+ t.Errorf("the failed settle %v did not wait on %s's cgroup", err, unit)
+ }
+ if _, serr := os.Stat(h.cgroupDir(bin)); !errors.Is(serr, os.ErrNotExist) {
+ t.Fatalf("the binary cmd unit's cgroup exists (%v): the test proves nothing", serr)
+ }
+ if stops := h.callsLike("stop "); !slices.Contains(stops, "stop "+unit) {
+ t.Errorf("systemctl stops %q, want %s", stops, unit)
+ }
+ noBinaryCmdUnit(t, h)
+ // It lets go: the next attempt proves it.
+ h.release(unit)
+ if err := u.StopAndSettle(context.Background()); err != nil {
+ t.Fatalf("StopAndSettle once %s's group is empty: %v", unit, err)
+ }
+ noBinaryCmdUnit(t, h)
+}
+
+// Root's answers given before systemctl start (/cmd's 503, then its 403)
+// are refusals: no unit, never the build's failure, nothing started.
+func TestReleaseRefusedByRootIsNotABuildFailure(t *testing.T) {
+ h, id, env := releaseHarness(t)
+ sockets := []string{h.eb.logSocketNamed(h.rt.Host, string(instancectl.RoleCmd)), h.eb.logSocketNamed(h.rt.Host, cmdErrSocket)}
+ for _, status := range []int{503, 403} {
+ h.mu.Lock()
+ h.cmdStatus = status
+ h.mu.Unlock()
+ u, err := h.eb.StartRelease(context.Background(), h.rt, id, env, io.Discard)
+ if u != nil {
+ t.Errorf("/cmd %d: StartRelease returned a unit", status)
+ }
+ if !errors.Is(err, errRootfsRefused) || verdictOf(err) != gateNoOwnership {
+ t.Errorf("/cmd %d: StartRelease = %v (verdict %d), want a marked refusal (gateNoOwnership)", status, err, verdictOf(err))
+ }
+ if status == 403 && !errors.Is(err, instancectl.ErrStagedImage) || status == 503 && !errors.Is(err, instancectl.ErrStartRefused) {
+ t.Errorf("/cmd %d: %v, not typed as root's answer", status, err)
+ }
+ // The agent's own launch file stays as root's refusal left it, and
+ // both stream listeners are closed.
+ if files := h.launchFiles(); !slices.Equal(files, []string{instancectl.LaunchFileName(instancectl.RoleCmd)}) {
+ t.Errorf("/cmd %d: launch files %q", status, files)
+ }
+ for _, s := range sockets {
+ if _, serr := os.Stat(s); !errors.Is(serr, os.ErrNotExist) {
+ t.Errorf("/cmd %d: the stream listener %s is still bound (%v)", status, s, serr)
+ }
+ }
+ }
+ if h.requested("POST /cmd") != 2 {
+ t.Errorf("POST /cmd sent %d times, want 2", h.requested("POST /cmd"))
+ }
+ for _, c := range h.callsLike("start ") {
+ if strings.Contains(c, "cmd@") {
+ t.Errorf("systemctl started a cmd unit after root refused: %q", c)
+ }
+ }
+}
+
+// The caller's exec gate is asked last, before root: a refusal sends no
+// /cmd and returns no unit.
+func TestReleaseExecGateRefusesAtTheLastMoment(t *testing.T) {
+ h, id, env := releaseHarness(t)
+ asked := 0
+ gate := func() error { asked++; return errSwapLeaseLost }
+ u, err := h.eb.StartRelease(withExecGate(context.Background(), gate), h.rt, id, env, io.Discard)
+ var refused launchRefused
+ if u != nil || !errors.As(err, &refused) || !errors.Is(err, errSwapLeaseLost) {
+ t.Fatalf("StartRelease = %v, %v; want launchRefused over the gate's error and no unit", u, err)
+ }
+ if asked == 0 {
+ t.Error("the exec gate was never asked")
+ }
+ if n := h.requested("POST /cmd"); n != 0 || len(h.cmdRequests()) != 0 {
+ t.Errorf("POST /cmd sent %d times after the gate refused", n)
+ }
+ if _, err := os.Stat(filepath.Join(provision.InstanceDir(h.eb.DataDir, h.rt.Host), instancectl.LaunchFileName(instancectl.RoleCmd))); err != nil {
+ t.Errorf("the gate was not the last step: no launch file before it (%v)", err)
+ }
+}
+
+// Through the production composition (SplitBackend over the harness's
+// ExecBackend): the release seam is found and reaches the exec half; a
+// unit-backed row is refused by both methods, marked, before root.
+func TestReleaseThroughTheProductionBackend(t *testing.T) {
+ shrinkCmdBounds(t)
+ h, id, _ := releaseHarness(t)
+ var b Backend = productionBackend(t, h.eb)
+ rb, ok := b.(ReleaseBackend)
+ if !ok {
+ t.Fatal("the production backend is not a ReleaseBackend")
+ }
+ env, err := rb.ReleaseEnv(context.Background(), h.rt)
+ if err != nil || env["CARLOS_SOCKET"] != h.rt.Socket || env["CARLOS_ADMIN_TOKEN"] == "" {
+ t.Fatalf("ReleaseEnv through SplitBackend = %v (socket %q), %v", sortedKeys(env), env["CARLOS_SOCKET"], err)
+ }
+ unitRow := h.rt
+ unitRow.Backing = registry.BackingUnit
+ if env, err := rb.ReleaseEnv(context.Background(), unitRow); env != nil || !errors.Is(err, errNoRootfsControl) || !errors.Is(err, errRootfsRefused) {
+ t.Errorf("ReleaseEnv on a unit row = %v, %v; want a marked errNoRootfsControl", env, err)
+ }
+ if u, err := rb.StartRelease(context.Background(), unitRow, id, env, io.Discard); u != nil || !errors.Is(err, errNoRootfsControl) || !errors.Is(err, errRootfsRefused) {
+ t.Errorf("StartRelease on a unit row = %v, %v; want a marked errNoRootfsControl", u, err)
+ }
+ if n := h.requested("POST /cmd"); n != 0 {
+ t.Fatalf("a unit row's release reached root (%d POST /cmd)", n)
+ }
+ u, err := rb.StartRelease(context.Background(), h.rt, id, env, io.Discard)
+ if n := h.requested("POST /cmd"); n != 1 {
+ t.Fatalf("POST /cmd sent %d times through SplitBackend, want once", n)
+ }
+ if release.BoxPlatform() != "linux-arm64" {
+ // Root refuses the image itself here (needRootfsStart): the exec
+ // half was reached, and the refusal is marked.
+ if u != nil || !errors.Is(err, instancectl.ErrStagedImage) || !errors.Is(err, errRootfsRefused) {
+ t.Fatalf("StartRelease through SplitBackend on %s = %v, %v; want root's marked refusal", release.BoxPlatform(), u, err)
+ }
+ needRootfsStart(t)
+ }
+ if err != nil || u == nil {
+ t.Fatalf("StartRelease through SplitBackend = %v, %v", u, err)
+ }
+ settleAtEnd(t, h, u)
+}
diff --git a/internal/activator/rootfsenv.go b/internal/activator/rootfsenv.go
index 73b25cccd..f51cac0d2 100644
--- a/internal/activator/rootfsenv.go
+++ b/internal/activator/rootfsenv.go
@@ -20,3 +20,12 @@ import "github.com/carlosframework/platform/internal/registry"
func (b *ExecBackend) rootfsCmdVars(rt registry.Route, fileEnv map[string]string, dbPath, runID, runDir string) map[string]string {
return rootfsVars(b.cmdVars(rt, fileEnv, dbPath, runID, runDir), rt.Socket, dbPath)
}
+
+// rootfsReleaseVars is a release command's environment on a rootfs row
+// (Group R, D1): rootfsCmdVars over fileEnv, the environment the run role
+// would launch with now (ReleaseEnv), without a run's id or directory: a
+// release is no carlos run. The row's canonical socket and dbPath are set
+// after the file environment, as for a run.
+func (b *ExecBackend) rootfsReleaseVars(rt registry.Route, fileEnv map[string]string, dbPath string) map[string]string {
+ return withoutVars(b.rootfsCmdVars(rt, fileEnv, dbPath, "", ""), "CARLOS_RUN_ID", "CARLOS_RUN_DIR")
+}
diff --git a/internal/activator/rootfsenv_test.go b/internal/activator/rootfsenv_test.go
index 501fd3434..b3b02992a 100644
--- a/internal/activator/rootfsenv_test.go
+++ b/internal/activator/rootfsenv_test.go
@@ -154,6 +154,23 @@ func TestRootfsCmdVarsFollowTheRunRule(t *testing.T) {
if m := envMap(t, env); len(m) != len(vars) || m["PATH"] != "" {
t.Errorf("launch env %v", env)
}
+ // Group R (R1a): a release is no run. The same composition without a
+ // run's id or directory, a tenant's own CARLOS_RUN_ID included.
+ rel := b.rootfsReleaseVars(rt, withVar(genEnv, "CARLOS_RUN_ID", "tenant"), p.dbPath)
+ for _, k := range []string{"CARLOS_RUN_ID", "CARLOS_RUN_DIR", "CARLOS_CONTROL_SOCKET", "CARLOS_PURGE"} {
+ if v, ok := rel[k]; ok {
+ t.Errorf("a release carries %s=%q", k, v)
+ }
+ }
+ for k, v := range want {
+ if k != "CARLOS_RUN_ID" && k != "CARLOS_RUN_DIR" && rel[k] != v {
+ t.Errorf("release %s = %q, want %q", k, rel[k], v)
+ }
+ }
+ wantRel := []string{"CARLOS_ADMIN_TOKEN", "CARLOS_DB", "CARLOS_HOST", "CARLOS_INSTANCE_KEY", "CARLOS_REGION", "CARLOS_SOCKET", "SHOP_MODE"}
+ if got := sortedKeys(rel); !slices.Equal(got, wantRel) {
+ t.Errorf("release variables %v, want %v", got, wantRel)
+ }
}
// Binary rows take no composer of this file: the socket and database stay
diff --git a/internal/activator/rootfsrelease.go b/internal/activator/rootfsrelease.go
new file mode 100644
index 000000000..4280d469d
--- /dev/null
+++ b/internal/activator/rootfsrelease.go
@@ -0,0 +1,68 @@
+package activator
+
+// The release process of a rootfs build (rootfs apps Plan 3, Group R): a
+// build may declare `release` (a Rails db:migrate), which this box runs
+// from the new image in the rootfs cmd unit, under the instance's lease,
+// before an overlap swap is admitted (R2) and inside a wake (R3). This
+// file holds what decides that a release is due and how long it may run,
+// and the lease signal it runs under. The backend half (StartRelease,
+// ReleaseEnv) is in backend_rootfs.go.
+
+import (
+ "strings"
+ "time"
+
+ "github.com/carlosframework/platform/internal/lease"
+ "github.com/carlosframework/platform/internal/registry"
+ "github.com/carlosframework/platform/internal/release"
+ "github.com/carlosframework/platform/internal/runs"
+)
+
+// leaseWatch is the held lease a release runs under [pf R1.1]: a wake's
+// Lease (*execLease, R3) or an awake incumbent's replica (*lease.Replicator,
+// R2). Err is its liveness, SafeUntil the deadline before which the
+// release's unit must be proven gone, and Lost closes once ownership ends.
+type leaseWatch interface {
+ residentOwnership
+ Err() error
+}
+
+var (
+ _ leaseWatch = (*execLease)(nil)
+ _ leaseWatch = (*lease.Replicator)(nil)
+)
+
+// watchOf is x as a leaseWatch, or nil when x cannot report the lease's
+// signal (a lease or replica with no deadline to stop ahead of).
+func watchOf(x any) leaseWatch {
+ if w, ok := x.(leaseWatch); ok {
+ return w
+ }
+ return nil
+}
+
+// releaseDue reports whether a start of build id on rt runs id's release
+// process first: rt is a rootfs row, the build declares release, and id is
+// not rt's good build (the build whose release has already run here, by
+// version and digest). A build that is already good is not migrated again.
+func releaseDue(rt registry.Route, id release.StagedIdentity, procs map[string]release.Process) bool {
+ if !rt.Rootfs() {
+ return false
+ }
+ if _, ok := procs[release.ProcessRelease]; !ok {
+ return false
+ }
+ return !(id.Version == rt.GoodVersion && strings.EqualFold(id.Digest, rt.GoodDigest))
+}
+
+// releaseTimeout is how long p, a release process, may run [pf R1.6]: its
+// timeout_sec, or release.DefaultReleaseTimeoutSec when it sets none. The
+// manifest check already refuses a timeout_sec above
+// release.MaxReleaseTimeoutSec; runs.MaxTimeout caps it again here.
+func releaseTimeout(p release.Process) time.Duration {
+ d := time.Duration(release.DefaultReleaseTimeoutSec) * time.Second
+ if p.TimeoutSec > 0 {
+ d = time.Duration(p.TimeoutSec) * time.Second
+ }
+ return min(d, runs.MaxTimeout)
+}
diff --git a/internal/activator/rootfsrelease_test.go b/internal/activator/rootfsrelease_test.go
new file mode 100644
index 000000000..2db9c4b1f
--- /dev/null
+++ b/internal/activator/rootfsrelease_test.go
@@ -0,0 +1,387 @@
+package activator
+
+// Group R, R1a: what decides a release is due and its bound, the lease
+// signal it runs under, the writer its output goes through, and its
+// environment on a first boot. The harness half is
+// rootfs_release_backend_test.go.
+
+import (
+ "bytes"
+ "context"
+ "errors"
+ "fmt"
+ "net"
+ "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"
+)
+
+func TestReleaseDue(t *testing.T) {
+ t.Parallel()
+ good := release.StagedIdentity{Version: "v1", StagedPath: "/opt/v1", Digest: "aa11"}
+ rootfs := registry.Route{Host: "shop.example.com", Runtime: registry.RuntimeRootfsV1, GoodVersion: "v1", GoodDigest: "aa11"}
+ binary := rootfs
+ binary.Runtime = ""
+ withRelease := map[string]release.Process{release.ProcessWeb: {Command: []string{"/app/serve"}}, release.ProcessRelease: {Command: []string{"/app/migrate"}}}
+ webOnly := map[string]release.Process{release.ProcessWeb: {Command: []string{"/app/serve"}}}
+ for _, c := range []struct {
+ name string
+ rt registry.Route
+ id release.StagedIdentity
+ procs map[string]release.Process
+ want bool
+ }{
+ {"rootfs, B is not the good build", rootfs, release.StagedIdentity{Version: "v2", StagedPath: "/opt/v2", Digest: "bb22"}, withRelease, true},
+ {"B is the good build, version and digest", rootfs, good, withRelease, false},
+ {"B is the good build, digest in upper case", rootfs, release.StagedIdentity{Version: "v1", StagedPath: "/opt/v1", Digest: "AA11"}, withRelease, false},
+ {"same version, another digest", rootfs, release.StagedIdentity{Version: "v1", StagedPath: "/opt/v1", Digest: "cc33"}, withRelease, true},
+ {"no good build yet", func() registry.Route { r := rootfs; r.GoodVersion, r.GoodDigest = "", ""; return r }(), good, withRelease, true},
+ {"no release process", rootfs, release.StagedIdentity{Version: "v2", StagedPath: "/opt/v2", Digest: "bb22"}, webOnly, false},
+ {"no processes", rootfs, release.StagedIdentity{Version: "v2", StagedPath: "/opt/v2", Digest: "bb22"}, nil, false},
+ {"a binary row", binary, release.StagedIdentity{Version: "v2", StagedPath: "/opt/v2", Digest: "bb22"}, withRelease, false},
+ } {
+ if got := releaseDue(c.rt, c.id, c.procs); got != c.want {
+ t.Errorf("%s: releaseDue = %v, want %v", c.name, got, c.want)
+ }
+ }
+}
+
+func TestReleaseTimeoutBounds(t *testing.T) {
+ t.Parallel()
+ for _, c := range []struct {
+ sec int
+ want time.Duration
+ }{
+ {0, 600 * time.Second},
+ {-5, 600 * time.Second},
+ {120, 120 * time.Second},
+ {7 * 60 * 60, 6 * time.Hour},
+ } {
+ if got := releaseTimeout(release.Process{Command: []string{"/app/migrate"}, TimeoutSec: c.sec}); got != c.want {
+ t.Errorf("timeout_sec %d: releaseTimeout = %s, want %s", c.sec, got, c.want)
+ }
+ }
+}
+
+// The lease signal: a wake's lease and an incumbent's replica each read as
+// a leaseWatch; a lease or replica without the signal reads as none.
+func TestReleaseLeaseWatchOf(t *testing.T) {
+ t.Parallel()
+ if w := watchOf(noopLeaseForWatch{}); w != nil {
+ t.Errorf("watchOf(a lease with no deadline) = %T, want nil", w)
+ }
+ if w := watchOf(nil); w != nil {
+ t.Errorf("watchOf(nil) = %T, want nil", w)
+ }
+ rep := newOwnedRep(&fakeRep{}, time.Now().Add(time.Hour))
+ t.Cleanup(func() { rep.timer.Stop() })
+ w := watchOf(rep)
+ if w == nil {
+ t.Fatal("watchOf(a replica with the lease's signal) = nil")
+ }
+ if until, err := w.SafeUntil(); err != nil || time.Until(until) < 50*time.Minute {
+ t.Errorf("SafeUntil = %v, %v", until, err)
+ }
+ rep.lose(fmt.Errorf("renewal failed"))
+ select {
+ case <-w.Lost():
+ default:
+ t.Error("Lost did not close on the loss")
+ }
+ if _, err := w.SafeUntil(); err == nil {
+ t.Error("SafeUntil answered a deadline after the loss")
+ }
+ if w.Err() == nil {
+ t.Error("Err is nil after the loss")
+ }
+}
+
+// noopLeaseForWatch is a Lease with no signal of its own.
+type noopLeaseForWatch struct{}
+
+func (noopLeaseForWatch) Replicate(context.Context, string, time.Duration) (Rep, error) {
+ return nil, nil
+}
+func (noopLeaseForWatch) Release(context.Context) error { return nil }
+
+// releaseLines collects what a releaseOutput writes, one Write a line.
+type releaseLines struct {
+ mu sync.Mutex
+ lines []string
+}
+
+func (c *releaseLines) emit(s string) {
+ c.mu.Lock()
+ c.lines = append(c.lines, s)
+ c.mu.Unlock()
+}
+
+func (c *releaseLines) got() []string {
+ c.mu.Lock()
+ defer c.mu.Unlock()
+ return slices.Clone(c.lines)
+}
+
+// The release's output writer alone [pf R1.5]: two streams copying at once
+// reach the emitter in whole lines, a last line with no newline included;
+// past the cap the lines stop, with one diagnostic in the journal.
+func TestReleaseOutputReachesTheAppLog(t *testing.T) {
+ var c releaseLines
+ o := newReleaseOutput("shop.example.com", lineEmitter(c.emit), 1<<20)
+ want := map[string]bool{}
+ var wg sync.WaitGroup
+ for _, name := range []string{"out", "err"} {
+ w := o.stream()
+ var all bytes.Buffer
+ for i := range 300 {
+ line := fmt.Sprintf("%s line %03d of the migration", name, i)
+ want[line] = true
+ all.WriteString(line + "\n")
+ }
+ all.WriteString(name + " tail")
+ want[name+" tail"] = true
+ wg.Add(1)
+ go func() {
+ defer wg.Done()
+ // Small chunks that end mid-line, as a socket read does.
+ raw := all.Bytes()
+ for len(raw) > 0 {
+ n := min(7, len(raw))
+ _, _ = w.Write(raw[:n])
+ raw = raw[n:]
+ }
+ w.(streamEnder).endStream()
+ }()
+ }
+ wg.Wait()
+ got := c.got()
+ if len(got) != len(want) {
+ t.Fatalf("%d lines reached the emitter, want %d", len(got), len(want))
+ }
+ for _, l := range got {
+ if !want[l] {
+ t.Errorf("a line arrived broken or interleaved: %q", l)
+ }
+ }
+
+ // The cap: three 30-byte lines fit in 100, the fourth does not, and
+ // nothing after it is written, a short line included.
+ logs := captureLog(t)
+ var capped releaseLines
+ o = newReleaseOutput("shop.example.com", lineEmitter(capped.emit), 100)
+ w := o.stream()
+ for i := range 6 {
+ fmt.Fprintf(w, "%029d\n", i)
+ }
+ fmt.Fprintf(w, "x\n")
+ if got := capped.got(); len(got) != 3 {
+ t.Errorf("%d lines past a 100-byte cap, want 3: %q", len(got), got)
+ }
+ if n := strings.Count(logs.String(), "the release command's output passed 100 bytes"); n != 1 {
+ t.Errorf("the cap logged %d diagnostics, want 1: %q", n, logs.String())
+ }
+ if strings.Contains(logs.String(), "00000000000000000000000000004") {
+ t.Errorf("a dropped line was logged: %q", logs.String())
+ }
+
+ // A nil writer, and a nil emitter, discard.
+ o = newReleaseOutput("shop.example.com", nil, 100)
+ if _, err := o.stream().Write([]byte("dropped\n")); err != nil {
+ t.Errorf("a nil writer: %v", err)
+ }
+ if n, err := lineEmitter(nil).Write([]byte("dropped")); n != 7 || err != nil {
+ t.Errorf("a nil emitter: %d, %v", n, err)
+ }
+}
+
+// The writer behind a real cmd stream: the unit's last line, with no
+// newline, reaches the emitter once the stream ends (cmdStream's endStream).
+func TestReleaseOutputLastLineThroughACmdStream(t *testing.T) {
+ t.Parallel()
+ dir, err := os.MkdirTemp("", "rl")
+ if err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(func() { os.RemoveAll(dir) })
+ var c releaseLines
+ o := newReleaseOutput("shop.example.com", lineEmitter(c.emit), 1<<20)
+ sock := filepath.Join(dir, "cmd.sock")
+ s, err := listenCmdStream(sock, o.stream())
+ if err != nil {
+ t.Skipf("cannot bind here (%v)", err)
+ }
+ conn, err := net.Dial("unix", sock)
+ if err != nil {
+ t.Fatal(err)
+ }
+ _, _ = conn.Write([]byte("migrating\ndone, no newline"))
+ conn.Close()
+ if err := s.Drain(5 * time.Second); err != nil {
+ t.Fatal(err)
+ }
+ if got := c.got(); !slices.Equal(got, []string{"migrating", "done, no newline"}) {
+ t.Errorf("lines %q", got)
+ }
+}
+
+// [pf R1.3] On a first boot nothing is on disk: ReleaseEnv mints the admin
+// token and the instance key as the run role would, and the web start's
+// prepare after it finds the same ones (one mint).
+func TestReleaseEnvOnAFirstBoot(t *testing.T) {
+ t.Parallel()
+ b, _ := newRootfsBackend(t)
+ b.Region = "eu-west-2"
+ rt := rootfsRoute(b)
+ p := b.pathsFor(rt)
+ if _, err := os.Stat(p.envFile); !os.IsNotExist(err) {
+ t.Fatalf("the instance's env file exists before the first boot: %v", err)
+ }
+ env, err := b.ReleaseEnv(context.Background(), rt)
+ if err != nil {
+ t.Fatalf("ReleaseEnv on a first boot: %v", err)
+ }
+ token, key := env["CARLOS_ADMIN_TOKEN"], env[InstanceKeyVar]
+ if len(token) < 20 || len(key) < 20 {
+ t.Fatalf("ReleaseEnv did not mint: token %d bytes, key %d bytes", len(token), len(key))
+ }
+ want := map[string]string{
+ "CARLOS_SOCKET": rt.Socket,
+ "CARLOS_DB": provision.NestedDBPath(b.DataDir, rt.Host),
+ "CARLOS_HOST": rt.Host,
+ "CARLOS_REGION": "eu-west-2",
+ }
+ for k, v := range want {
+ if env[k] != v {
+ t.Errorf("%s = %q, want %q", k, env[k], v)
+ }
+ }
+ for _, k := range []string{"CARLOS_CONTROL_SOCKET", "CARLOS_PURGE", "CARLOS_RUN_ID", "CARLOS_RUN_DIR"} {
+ if v, ok := env[k]; ok {
+ t.Errorf("a release carries %s=%q", k, v)
+ }
+ }
+ // The web start's prepare reads the same token and key.
+ sock := nestedGenSocketIn(p.runDir, 7)
+ _, ctl, logs, fileEnv, _, err := b.prepareKeyedAt(rt, instancectl.RoleRun, sock, 7, nil)
+ if err != nil {
+ t.Fatalf("the web start's prepare: %v", err)
+ }
+ if ctl != nil {
+ ctl.Close()
+ }
+ if logs != nil {
+ logs.Close()
+ }
+ if fileEnv["CARLOS_ADMIN_TOKEN"] != token || fileEnv[InstanceKeyVar] != key {
+ t.Errorf("the web start minted again: its token or key differs from the release's")
+ }
+ again, err := b.ReleaseEnv(context.Background(), rt)
+ if err != nil || again["CARLOS_ADMIN_TOKEN"] != token || again[InstanceKeyVar] != key {
+ t.Errorf("a second ReleaseEnv minted again (%v)", err)
+ }
+ raw, err := os.ReadFile(p.envFile)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if n := strings.Count(string(raw), InstanceKeyVar+"="); n != 1 {
+ t.Errorf("the env file holds %d instance keys, want 1", n)
+ }
+}
+
+// StartRelease gives each of the unit's two streams its own line splitter
+// over the one capped sink: lines written to stdout and stderr in
+// interleaved pieces, as systemd's two connections deliver them, still
+// reach out whole.
+func TestReleaseStartSplitsEachStreamApart(t *testing.T) {
+ t.Parallel()
+ b, ctl := newRootfsBackend(t)
+ rt := rootfsRoute(b)
+ id := stagedRootfsIdentity(t, b, "v2")
+ ctl.cmdInv = "inv-rel"
+ env, err := b.ReleaseEnv(context.Background(), rt)
+ if err != nil {
+ t.Fatal(err)
+ }
+ var c releaseLines
+ u, err := b.StartRelease(context.Background(), rt, id, env, lineEmitter(c.emit))
+ if err != nil || u == nil {
+ t.Fatalf("StartRelease = %v, %v", u, err)
+ }
+ cu := u.(*cmdUnit)
+ var conns []net.Conn
+ for _, name := range []string{string(instancectl.RoleCmd), cmdErrSocket} {
+ conn, err := net.Dial("unix", b.logSocketNamed(rt.Host, name))
+ if err != nil {
+ t.Fatal(err)
+ }
+ conns = append(conns, conn)
+ }
+ for _, piece := range []struct {
+ stream int
+ text string
+ }{{0, "stdout o"}, {1, "stderr o"}, {0, "ne\nstdout tw"}, {1, "ne\nstderr tw"}, {0, "o\n"}, {1, "o\n"}} {
+ if _, err := conns[piece.stream].Write([]byte(piece.text)); err != nil {
+ t.Fatal(err)
+ }
+ time.Sleep(20 * time.Millisecond)
+ }
+ for _, conn := range conns {
+ conn.Close()
+ }
+ if err := errors.Join(cu.out.Drain(5*time.Second), cu.errs.Drain(5*time.Second)); err != nil {
+ t.Fatal(err)
+ }
+ got := c.got()
+ slices.Sort(got)
+ if want := []string{"stderr one", "stderr two", "stdout one", "stdout two"}; !slices.Equal(got, want) {
+ t.Errorf("lines %q, want %q", got, want)
+ }
+}
+
+// ReleaseEnv mints nothing on a row that is not nested: a conflicting
+// row's paths, and those of one not on the nested defaults, are the box's
+// flat directory.
+func TestReleaseEnvRefusesARowThatIsNotNested(t *testing.T) {
+ t.Parallel()
+ b, _ := newRootfsBackend(t)
+ conflict := rootfsRoute(b)
+ flat := conflict
+ flat.DBPath = provision.DefaultDBPath(b.DataDir, flat.Host)
+ b.LayoutFacts.SameID = func(a, b string) bool { return true }
+ b.LayoutFacts.Peers = func() ([]registry.Route, error) {
+ return []registry.Route{{Host: "other.example.com", Kind: "instance", Hibernate: true, Socket: "/nonexistent/other.sock"}}, nil
+ }
+ if p := b.pathsFor(conflict); p.layout != LayoutConflict {
+ t.Fatalf("the row is %s, want conflict", p.layout)
+ }
+ check := func(name string, rt registry.Route) {
+ t.Helper()
+ env, err := b.ReleaseEnv(context.Background(), rt)
+ if env != nil || !errors.Is(err, errRootfsRefused) {
+ t.Errorf("ReleaseEnv on a %s row = %v, %v; want a marked refusal", name, sortedKeys(env), err)
+ }
+ for _, f := range []string{filepath.Join(b.DataDir, rt.Host+".env"), filepath.Join(provision.InstanceDir(b.DataDir, rt.Host), rt.Host+".env")} {
+ if _, err := os.Stat(f); !os.IsNotExist(err) {
+ t.Errorf("%s was written for a %s row (%v)", f, name, err)
+ }
+ }
+ }
+ check("conflicting", conflict)
+ b.LayoutFacts.Peers = nil
+ if p := b.pathsFor(flat); p.layout == LayoutNested {
+ t.Fatal("the row on the flat database reads as nested")
+ }
+ check("not nested", flat)
+ binary := conflict
+ binary.Runtime = ""
+ check("binary", binary)
+}
diff --git a/plan3_groups_test.go b/plan3_groups_test.go
index 81ec79cc1..b0cdc15a7 100644
--- a/plan3_groups_test.go
+++ b/plan3_groups_test.go
@@ -50,7 +50,7 @@ var (
// plan3GroupsStarted and plan3GroupsLanded: "R" and "W" (and "A" in
// landed), each added by the task the file comment names.
var (
- plan3GroupsStarted = []string{}
+ plan3GroupsStarted = []string{"R"}
plan3GroupsLanded = []string{"A"}
)
@@ -206,7 +206,7 @@ func TestPlan3MachineryInventory(t *testing.T) {
if len(sources) < 50 {
t.Fatalf("found %d sources in internal/activator: the inventory reads the wrong directory", len(sources))
}
- problems, seen := plan3InventoryProblems(t, sources)
+ problems, seen := plan3InventoryProblems(t, sources, plan3GroupStarted)
for _, p := range problems {
t.Error(p)
}
@@ -220,9 +220,12 @@ func TestPlan3MachineryInventory(t *testing.T) {
}
// The fixture's comment lists what the inventory must refuse and what it
-// must pass: exactly the five refusals below.
+// must pass: exactly the five refusals below. It is judged as on main
+// before R or W started (Group A alone), so a group starting never takes
+// a refusal away from the check.
func TestPlan3MachineryInventoryFixture(t *testing.T) {
- problems, _ := plan3InventoryProblems(t, []string{filepath.Join("testdata", "plan3_inventory", "added.go")})
+ onlyA := func(g string) bool { return g == "A" }
+ problems, _ := plan3InventoryProblems(t, []string{filepath.Join("testdata", "plan3_inventory", "added.go")}, onlyA)
want := []string{"func runRelease: release machinery before group R has started",
"type rootfsWorkerState: worker machinery before group W has started",
"method Service.StartRootfsWorker: worker machinery before group W has started",
@@ -238,9 +241,10 @@ func TestPlan3MachineryInventoryFixture(t *testing.T) {
}
}
-// plan3InventoryProblems judges every declaration in sources, and reports
-// which baseline keys it saw.
-func plan3InventoryProblems(t *testing.T, sources []string) (problems []string, seen map[string]bool) {
+// plan3InventoryProblems judges every declaration in sources, with started
+// answering which groups have started, and reports which baseline keys it
+// saw.
+func plan3InventoryProblems(t *testing.T, sources []string, started func(string) bool) (problems []string, seen map[string]bool) {
t.Helper()
seen = map[string]bool{}
fset := token.NewFileSet()
@@ -256,10 +260,10 @@ func plan3InventoryProblems(t *testing.T, sources []string) (problems []string,
continue
}
at := fset.Position(d.pos).String() + ": " + key + ": "
- if plan3Match(plan3ReleaseInventory, d.name) != "" && !plan3GroupStarted("R") {
+ if plan3Match(plan3ReleaseInventory, d.name) != "" && !started("R") {
problems = append(problems, at+"release machinery before group R has started")
}
- if plan3Match(plan3WorkerInventory, d.name) != "" && !plan3GroupStarted("W") {
+ if plan3Match(plan3WorkerInventory, d.name) != "" && !started("W") {
problems = append(problems, at+"worker machinery before group W has started")
}
}