carlos / platform Public

activator: rootfsCtlHarness (the real control handler behind an ExecBackend) and the startup proof through it

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev 8a63adfd3d71e98cac3d11cabab423a1ab5987cd parent 2fb7e96
2 files changed, +662 −0
  • internal/activator/rootfs_admission_test.go +168 −0
  • internal/activator/rootfs_ctl_harness_test.go +494 −0
diff --git a/internal/activator/rootfs_admission_test.go b/internal/activator/rootfs_admission_test.go
new file mode 100644
index 000000000..90f6e8159
--- /dev/null
+++ b/internal/activator/rootfs_admission_test.go
@@ -0,0 +1,168 @@
+//go:build linux
+
+package activator
+
+// The startup proof [Astra R3 3], through the real control handler
+// (rootfsCtlHarness): rootfs admission opens only on a startup sweep that
+// proved every leftover unit gone, and after a failed one it stays closed
+// for the Service's life.
+
+import (
+ "context"
+ "errors"
+ "path/filepath"
+ "sync"
+ "testing"
+ "time"
+
+ "github.com/carlosframework/platform/internal/instancectl"
+ "github.com/carlosframework/platform/internal/registry"
+ "github.com/carlosframework/platform/internal/release"
+)
+
+// harnessBackend is the production composition over the harness's
+// ExecBackend, with the lease and the restore counted and kept off S3:
+// Acquire hands out a lease whose replica is a no-op, and Restore finds
+// the warm database a first boot would have.
+type harnessBackend struct {
+ *SplitBackend
+ mu sync.Mutex
+ acquires, restores int
+}
+
+func (b *harnessBackend) Acquire(context.Context, registry.Route) (Lease, error) {
+ b.mu.Lock()
+ defer b.mu.Unlock()
+ b.acquires++
+ return bucketLease{rig: &bucketRig{}}, nil
+}
+
+func (b *harnessBackend) Restore(context.Context, registry.Route) (bool, error) {
+ b.mu.Lock()
+ defer b.mu.Unlock()
+ b.restores++
+ return false, nil
+}
+
+func (b *harnessBackend) counts() (int, int) {
+ b.mu.Lock()
+ defer b.mu.Unlock()
+ return b.acquires, b.restores
+}
+
+func harnessService(t *testing.T, h *rootfsCtlHarness) (*Service, *harnessBackend, *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 := &harnessBackend{SplitBackend: productionBackend(t, h.eb)}
+ 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() // the scheduler armed on this boot; the sweep is the question
+ t.Cleanup(func() { a.Shutdown(context.Background()) })
+ return a, hb, clk
+}
+
+// startupSweep is what internal/host's startup sweep wrapper does with the
+// answer (TestStartupSweepMarksOnlyWhenClean holds the wrapper itself):
+// MarkRootfsSwept on a clean sweep and never otherwise.
+func startupSweepFor(a *Service, h *rootfsCtlHarness) error {
+ _, err := h.client.Sweep(context.Background())
+ if err == nil {
+ a.MarkRootfsSwept()
+ }
+ return err
+}
+
+// TestRootfsAdmissionWaitsForTheStartupProof: a replaced Service over the
+// real control handler whose startup sweep answers Failed for a leftover
+// rootfs cmd unit (its cgroup populated, its stop refused). The readiness
+// probes pass, yet a request, a wake that did not come through begin and
+// a RunCmd cause no Acquire, no Restore and no launch (errRootfsUnswept).
+// Admission stays closed for the Service's life: after the leftover ends,
+// an hour of fake time and many sweeps later, still no Acquire and no
+// second sweep. A new Service whose startup sweep is clean wakes the
+// instance on the next request, through the rootfs generation unit. Task 8
+// adds the resident tick's row.
+func TestRootfsAdmissionWaitsForTheStartupProof(t *testing.T) {
+ h := newRootfsCtlHarness(t)
+ leftover := instancectl.RootfsUnitName(instancectl.RoleCmd, h.rt.Host)
+ h.leave(leftover, true)
+ h.runProbes()
+
+ a, hb, clk := harnessService(t, h)
+ if err := startupSweepFor(a, h); err == nil {
+ t.Fatal("the sweep proved a unit whose stop failed gone")
+ }
+ refused := func(when string) {
+ t.Helper()
+ if _, err := a.beginRequest(context.Background(), h.rt); !errors.Is(err, errRootfsUnswept) {
+ t.Fatalf("%s: request = %v, want errRootfsUnswept", when, err)
+ }
+ if err := dueWake(a, h.rt); !errors.Is(err, errRootfsUnswept) {
+ t.Fatalf("%s: wake = %v, want errRootfsUnswept", when, err)
+ }
+ _, err := a.RunCmd(context.Background(), h.rt, CmdSpec{RunID: "r1", Args: []string{"true"}})
+ var we *CmdWakeError
+ if !errors.As(err, &we) || !errors.Is(err, errRootfsUnswept) {
+ t.Fatalf("%s: RunCmd = %v, want a wake error carrying errRootfsUnswept", when, err)
+ }
+ if acq, res := hb.counts(); acq != 0 || res != 0 {
+ t.Fatalf("%s: acquires %d, restores %d", when, acq, res)
+ }
+ if starts := h.rootfsStarts(); len(starts) != 0 {
+ t.Fatalf("%s: root started %v", when, starts)
+ }
+ if files := h.launchFiles(); len(files) != 0 {
+ t.Fatalf("%s: launch files written: %v", when, files)
+ }
+ }
+ refused("after the failed sweep")
+
+ h.release(leftover)
+ for i := 0; i < 60; i++ {
+ clk.advance(time.Minute)
+ a.sweepOnce()
+ }
+ refused("an hour after the leftover ended")
+ if sweeps := h.callsLike("list-units"); len(sweeps) != 1 {
+ t.Fatalf("the box swept %d times; a sweep after Start would stop this agent's own units", len(sweeps))
+ }
+
+ // The agent restarts and its startup sweep is clean.
+ b, hb2, _ := harnessService(t, h)
+ if err := startupSweepFor(b, h); err != nil {
+ t.Fatalf("the second startup sweep: %v", err)
+ }
+ h.serveGenerations()
+ done, err := b.beginRequest(context.Background(), h.rt)
+ if release.BoxPlatform() != "linux-arm64" {
+ // Root stages rootfs images for linux-arm64 alone (a rootfs
+ // manifest carries only release.RootfsArtifactKey), so on this
+ // box root refuses the image itself (ErrStagedImage): after the
+ // admission, the lease and the restore, at root's /start of the
+ // generation. On a linux-arm64 box the wake serves (below).
+ if !errors.Is(err, instancectl.ErrStagedImage) {
+ t.Fatalf("after a clean sweep on %s: %v, want root's staged-image refusal", release.BoxPlatform(), err)
+ }
+ if acq, res := hb2.counts(); acq != 1 || res != 1 || h.requested("POST /start") != 1 {
+ t.Fatalf("acquires %d, restores %d, /start asked %d times: the admission did not open", acq, res, h.requested("POST /start"))
+ }
+ return
+ }
+ if err != nil {
+ t.Fatalf("after a clean sweep: %v", err)
+ }
+ done()
+ starts := h.rootfsStarts()
+ if acq, _ := hb2.counts(); acq != 1 || len(starts) != 1 {
+ t.Fatalf("acquires %d, root starts %v: want one wake through one unit", acq, starts)
+ }
+ if g, _ := b.genStateForTest(h.rt.Host); instancectl.RootfsGenUnitName(h.rt.Host, g.N) != starts[0] {
+ t.Fatalf("serving generation %d, but root started %s", g.N, starts[0])
+ }
+}
diff --git a/internal/activator/rootfs_ctl_harness_test.go b/internal/activator/rootfs_ctl_harness_test.go
new file mode 100644
index 000000000..c625db9e6
--- /dev/null
+++ b/internal/activator/rootfs_ctl_harness_test.go
@@ -0,0 +1,494 @@
+//go:build linux
+
+package activator
+
+// rootfsCtlHarness (Plan 3 Task 7; Task 12 and Group R reuse it) is the
+// real control handler behind an ExecBackend [Astra R1 1]: a real
+// instancectl.Server on a unix socket under the short TMPDIR, PeerOK
+// answering nil, its probes run for real (RunProbe) over fakes that pass;
+// systemctl a fake keyed by unit name (each unit's show answer read from
+// its state and the drop-ins root wrote, start and stop recorded in order
+// and changing that unit's state); CgroupRoot a fixture tree whose
+// cgroup.events per unit follows the unit; the version store holding
+// build v1 of acme/shop staged with its root-written manifest; HostApp
+// and HostRuntime answering the row. The ExecBackend is nestedBackend's
+// with Control the real client and its unit, cgroup and control-group
+// reads on the same fakes. No binary unit exists in any answer: a binary
+// carlos-instance-cmd@ or carlos-instance-run@ unit reads inactive with no
+// invocation and has no cgroup, so a test passes only if every poll, stop
+// 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.
+
+import (
+ "context"
+ "crypto/sha256"
+ "encoding/hex"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "net"
+ "net/http"
+ "net/http/httputil"
+ "net/netip"
+ "net/url"
+ "os"
+ "path/filepath"
+ "sort"
+ "strconv"
+ "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"
+ "github.com/carlosframework/platform/internal/version"
+)
+
+type harnessUnit struct {
+ active bool
+ inv string
+}
+
+type rootfsCtlHarness struct {
+ t *testing.T
+ srv *instancectl.Server
+ client *instancectl.Client
+ eb *ExecBackend
+ rt registry.Route
+ cgroup string // CgroupRoot: the fixture tree root and agent read
+
+ mu sync.Mutex
+ seq int
+ units map[string]*harnessUnit
+ calls []string
+ stuck map[string]bool
+ cmdStatus int
+ onStart func(unit string)
+ requests []string // "METHOD /path" of every request the agent sent
+}
+
+// newRootfsCtlHarness builds the harness for acme/shop's
+// shop.example.com, build v1 staged and the live link on it.
+func newRootfsCtlHarness(t *testing.T) *rootfsCtlHarness {
+ t.Helper()
+ root, err := os.MkdirTemp("", "rh")
+ if err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(func() { os.RemoveAll(root) })
+ h := &rootfsCtlHarness{t: t, units: map[string]*harnessUnit{}, stuck: map[string]bool{}, cgroup: filepath.Join(root, "cgroup")}
+ for _, d := range []string{h.cgroup, filepath.Join(root, "exe"), filepath.Join(root, "dropins"), filepath.Join(root, "probe")} {
+ if err := os.MkdirAll(d, 0o755); err != nil {
+ t.Fatal(err)
+ }
+ }
+ resolv := filepath.Join(root, "resolv.conf")
+ probeOut := filepath.Join(root, "probe.out")
+ rootfsProbeOut := filepath.Join(root, "rootfs-probe.out")
+ for path, body := range map[string]string{
+ resolv: "nameserver 10.0.0.2\n",
+ probeOut: `{"ready":true,"lines":[{"check":"pid1","verdict":"ok"}]}`,
+ rootfsProbeOut: `{"ready":true,"lines":[{"check":"root-image","verdict":"ok"}]}`,
+ } {
+ if err := os.WriteFile(path, []byte(body), 0o644); err != nil {
+ t.Fatal(err)
+ }
+ }
+
+ // The agent's side: nestedBackend, build v1 staged as root stages a
+ // rootfs image, with the manifest naming it for this box's platform.
+ unit := &fakeUnit{}
+ eb, _ := nestedBackend(t, &fakeControl{}, unit)
+ stageRootfsForBox(t, eb, "v1")
+ pointLive(t, eb, rootfsTestHost, release.VersionPath(eb.OptDir, rootfsTestAcct, "v1", rootfsTestApp))
+ h.rt = rootfsRoute(eb)
+
+ h.srv = &instancectl.Server{
+ Systemctl: h.systemctl,
+ PeerOK: func(net.Conn) error { return nil },
+ CgroupRoot: h.cgroup,
+ ProbeOut: probeOut,
+ ProbeImage: func(dst string) error { return os.WriteFile(dst, []byte("probe image"), 0o644) },
+ ProbeImageFile: filepath.Join(root, "probe", "rootfs.squashfs"),
+ RootfsProbeOut: rootfsProbeOut,
+ FixtureOK: func() error { return nil },
+ ProbeEvery: time.Hour,
+ Logf: t.Logf,
+ Build: version.Build,
+ ExeRoot: filepath.Join(root, "exe"),
+ OptDir: eb.OptDir,
+ DropInDir: filepath.Join(root, "dropins"),
+ ResolvedConf: resolv,
+ HostApp: func(host string) (string, string, error) {
+ if host != rootfsTestHost {
+ return "", "", errors.New("no such route")
+ }
+ return rootfsTestAcct, rootfsTestApp, nil
+ },
+ HostRuntime: func(host string) (string, error) {
+ if host != rootfsTestHost {
+ return "", errors.New("no such route")
+ }
+ return registry.RuntimeRootfsV1, nil
+ },
+ LocalAddrs: func() ([]netip.Prefix, error) { return []netip.Prefix{netip.MustParsePrefix("172.31.7.19/32")}, nil },
+ }
+ // The real handler on its own socket, behind a front socket that can
+ // answer /cmd itself (cmdStatus) and hands everything else on.
+ inner := filepath.Join(root, "ctl.sock")
+ ln, err := net.Listen("unix", inner)
+ if err != nil {
+ t.Fatal(err)
+ }
+ ctx, cancel := context.WithCancel(context.Background())
+ served := make(chan struct{})
+ go func() { defer close(served); _ = h.srv.Serve(ctx, ln) }()
+ front := filepath.Join(root, "front.sock")
+ fln, err := net.Listen("unix", front)
+ if err != nil {
+ t.Fatal(err)
+ }
+ proxy := &httputil.ReverseProxy{
+ Rewrite: func(r *httputil.ProxyRequest) { r.SetURL(&url.URL{Scheme: "http", Host: "instance-control"}) },
+ Transport: &http.Transport{DialContext: func(ctx context.Context, _, _ string) (net.Conn, error) {
+ var d net.Dialer
+ return d.DialContext(ctx, "unix", inner)
+ }, DisableKeepAlives: true},
+ }
+ fs := &http.Server{Handler: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ h.mu.Lock()
+ status := h.cmdStatus
+ h.requests = append(h.requests, r.Method+" "+r.URL.Path)
+ 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)
+ return
+ }
+ proxy.ServeHTTP(w, r)
+ })}
+ go func() { _ = fs.Serve(fln) }()
+ t.Cleanup(func() {
+ fs.Close()
+ cancel()
+ <-served
+ })
+ h.client = instancectl.NewClient(front)
+
+ eb.Control = h.client
+ eb.GenContainment = true
+ eb.RootfsOK = func(ctx context.Context) error { return h.client.ReadyRootfs(ctx) }
+ eb.RootfsPlacement = func(context.Context, registry.Route) error { return nil }
+ eb.UnitState = h.unitState
+ eb.CgroupRoot = h.cgroup
+ eb.CgroupEvents = cgroupEventsUnder(h.cgroup)
+ eb.ControlGroup = h.controlGroup
+ h.eb = eb
+ return h
+}
+
+// stageRootfsForBox stages acme/shop ver as root's staging leaves a rootfs
+// 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()
+ body := []byte("squashfs image of shop " + ver)
+ if err := release.StageArtifact(b.OptDir, rootfsTestAcct, ver, rootfsTestApp, body); err != nil {
+ t.Fatal(err)
+ }
+ 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"}}}
+ raw, err := json.Marshal(m)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if err := release.StageManifest(b.OptDir, rootfsTestAcct, ver, rootfsTestApp, raw); err != nil {
+ t.Fatal(err)
+ }
+}
+
+// runProbes runs the control service's probes, as its probe loop does at
+// start; with the harness's fakes both pass.
+func (h *rootfsCtlHarness) runProbes() {
+ h.t.Helper()
+ h.srv.RunProbe(context.Background())
+ if err := h.client.ReadyRootfs(context.Background()); err != nil {
+ h.t.Fatalf("the probes did not pass: %v", err)
+ }
+}
+
+// leave makes unit a leftover of a previous agent: active, its cgroup
+// populated, and, when stuck, a unit whose stop fails.
+func (h *rootfsCtlHarness) leave(unit string, stuck bool) {
+ h.mu.Lock()
+ defer h.mu.Unlock()
+ h.seq++
+ h.units[unit] = &harnessUnit{active: true, inv: fmt.Sprintf("%032x", h.seq)}
+ h.stuck[unit] = stuck
+ h.setPopulatedLocked(unit, true)
+}
+
+// release lets unit go: its stop succeeds from now on, and it ends.
+func (h *rootfsCtlHarness) release(unit string) {
+ h.mu.Lock()
+ defer h.mu.Unlock()
+ delete(h.stuck, unit)
+ if u := h.units[unit]; u != nil {
+ u.active = false
+ }
+ h.setPopulatedLocked(unit, false)
+}
+
+func (h *rootfsCtlHarness) setOnStart(f func(unit string)) {
+ h.mu.Lock()
+ h.onStart = f
+ h.mu.Unlock()
+}
+
+// callsLike is every systemctl call whose joined arguments start with
+// prefix.
+func (h *rootfsCtlHarness) callsLike(prefix string) []string {
+ h.mu.Lock()
+ defer h.mu.Unlock()
+ var out []string
+ for _, c := range h.calls {
+ if strings.HasPrefix(c, prefix) {
+ out = append(out, c)
+ }
+ }
+ return out
+}
+
+// startsOf is every started unit that is one of the row's rootfs units.
+func (h *rootfsCtlHarness) rootfsStarts() []string {
+ var out []string
+ for _, c := range h.callsLike("start ") {
+ if u := strings.TrimPrefix(c, "start "); instancectl.IsRootfsUnit(u) {
+ out = append(out, u)
+ }
+ }
+ return out
+}
+
+func (h *rootfsCtlHarness) slice() string { return instancectl.SliceName(h.rt.Host) }
+
+func (h *rootfsCtlHarness) cgroupDir(unit string) string {
+ return filepath.Join(h.cgroup, "carlos.slice", "carlos-instances.slice", h.slice(), unit)
+}
+
+func (h *rootfsCtlHarness) setPopulatedLocked(unit string, populated bool) {
+ dir := h.cgroupDir(unit)
+ if err := os.MkdirAll(dir, 0o755); err != nil {
+ h.t.Error(err)
+ return
+ }
+ body := "populated 0\nfrozen 0\n"
+ if populated {
+ body = "populated 1\nfrozen 0\n"
+ }
+ if err := os.WriteFile(filepath.Join(dir, "cgroup.events"), []byte(body), 0o644); err != nil {
+ h.t.Error(err)
+ }
+}
+
+func (h *rootfsCtlHarness) unitState(_ context.Context, unit string) (string, string, error) {
+ h.mu.Lock()
+ defer h.mu.Unlock()
+ u := h.units[unit]
+ if u == nil {
+ return "inactive", "", nil
+ }
+ if u.active {
+ return "active", u.inv, nil
+ }
+ return "inactive", u.inv, nil
+}
+
+func (h *rootfsCtlHarness) controlGroup(_ context.Context, unit string) (string, error) {
+ h.mu.Lock()
+ defer h.mu.Unlock()
+ return h.controlGroupLocked(unit), nil
+}
+
+func (h *rootfsCtlHarness) controlGroupLocked(unit string) string {
+ if u := h.units[unit]; u != nil && u.active {
+ return "/carlos.slice/carlos-instances.slice/" + h.slice() + "/" + unit
+ }
+ return ""
+}
+
+// dropIns is every Key=Value line of the drop-ins root wrote for unit.
+func (h *rootfsCtlHarness) dropIns(unit string) map[string]string {
+ m := map[string]string{}
+ dir := filepath.Join(h.srv.DropInDir, unit+".d")
+ ents, _ := os.ReadDir(dir)
+ for _, e := range ents {
+ raw, err := os.ReadFile(filepath.Join(dir, e.Name()))
+ if err != nil {
+ continue
+ }
+ for _, line := range strings.Split(string(raw), "\n") {
+ if k, v, ok := strings.Cut(line, "="); ok && !strings.HasPrefix(line, "#") {
+ m[k] = v
+ }
+ }
+ }
+ return m
+}
+
+// systemctl is the fake systemd root drives.
+func (h *rootfsCtlHarness) systemctl(_ context.Context, args ...string) (string, error) {
+ h.mu.Lock()
+ h.calls = append(h.calls, strings.Join(args, " "))
+ var hook func()
+ defer func() {
+ h.mu.Unlock()
+ if hook != nil {
+ hook()
+ }
+ }()
+ if len(args) == 0 {
+ return "", errors.New("no verb")
+ }
+ last := args[len(args)-1]
+ switch args[0] {
+ case "start":
+ h.seq++
+ h.units[last] = &harnessUnit{active: true, inv: fmt.Sprintf("%032x", h.seq)}
+ h.setPopulatedLocked(last, true)
+ if f := h.onStart; f != nil {
+ hook = func() { f(last) }
+ }
+ return "", nil
+ case "stop", "kill":
+ if h.stuck[last] {
+ return "Job for " + last + " canceled.", errors.New("exit status 1")
+ }
+ if u := h.units[last]; u != nil {
+ u.active = false
+ h.setPopulatedLocked(last, false)
+ }
+ return "", nil
+ case "daemon-reload", "set-property", "reset-failed":
+ return "", nil
+ case "list-units":
+ var names []string
+ for n := range h.units {
+ names = append(names, n)
+ }
+ sort.Strings(names)
+ var b strings.Builder
+ for _, n := range names {
+ state := "inactive"
+ if h.units[n].active {
+ state = "active"
+ }
+ fmt.Fprintf(&b, "%s loaded %s running x\n", n, state)
+ }
+ return b.String(), nil
+ case "list-jobs":
+ return "", nil
+ case "show":
+ return h.showLocked(args[1:])
+ }
+ return "", fmt.Errorf("the harness's systemctl does not know %q", strings.Join(args, " "))
+}
+
+func (h *rootfsCtlHarness) showLocked(args []string) (string, error) {
+ var props, units []string
+ value := false
+ for i := 0; i < len(args); i++ {
+ switch a := args[i]; {
+ case a == "-p" && i+1 < len(args):
+ props = append(props, strings.Split(args[i+1], ",")...)
+ i++
+ case a == "--value":
+ value = true
+ case strings.HasPrefix(a, "-"):
+ default:
+ units = append(units, a)
+ }
+ }
+ var blocks []string
+ for _, unit := range units {
+ answer := h.propsLocked(unit)
+ if value {
+ return answer[props[0]] + "\n", nil
+ }
+ var b strings.Builder
+ for _, p := range props {
+ b.WriteString(p + "=" + answer[p] + "\n")
+ }
+ blocks = append(blocks, b.String())
+ }
+ return strings.Join(blocks, "\n"), nil
+}
+
+func (h *rootfsCtlHarness) propsLocked(unit string) map[string]string {
+ m := map[string]string{"NeedDaemonReload": "no", "MemoryDenyWriteExecute": "yes"}
+ if strings.HasSuffix(unit, ".slice") {
+ return m
+ }
+ m["Slice"] = h.slice()
+ for k, v := range h.dropIns(unit) {
+ m[k] = v
+ }
+ if _, err := os.Stat(filepath.Join(h.srv.DropInDir, unit+".d", instancectl.JITDropInName)); err == nil {
+ m["MemoryDenyWriteExecute"] = "no"
+ }
+ m["ActiveState"] = "inactive"
+ if u := h.units[unit]; u != nil {
+ m["InvocationID"] = u.inv
+ if u.active {
+ m["ActiveState"] = "active"
+ }
+ }
+ m["ControlGroup"] = h.controlGroupLocked(unit)
+ return m
+}
+
+// serveGenerations binds each started rootfs generation's socket and
+// answers 200 there, where the web process would.
+func (h *rootfsCtlHarness) serveGenerations() {
+ h.setOnStart(func(unit string) {
+ i := strings.LastIndex(unit, ":")
+ if i < 0 {
+ return
+ }
+ n, err := strconv.ParseUint(strings.TrimSuffix(unit[i+1:], ".service"), 10, 64)
+ if err != nil || instancectl.RootfsGenUnitName(h.rt.Host, n) != unit {
+ return
+ }
+ h.t.Cleanup(serveOK(h.t, nestedGenSocketIn(h.eb.pathsFor(h.rt).runDir, n)))
+ })
+}
+
+// requested reports how many requests the agent sent as "METHOD /path".
+func (h *rootfsCtlHarness) requested(req string) int {
+ h.mu.Lock()
+ defer h.mu.Unlock()
+ n := 0
+ for _, r := range h.requests {
+ if r == req {
+ n++
+ }
+ }
+ return n
+}
+
+// launchFiles is every launch file in the row's instance directory.
+func (h *rootfsCtlHarness) launchFiles() []string {
+ ents, _ := os.ReadDir(provision.InstanceDir(h.eb.DataDir, h.rt.Host))
+ var out []string
+ for _, e := range ents {
+ if strings.HasPrefix(e.Name(), "launch") {
+ out = append(out, e.Name())
+ }
+ }
+ return out
+}