| 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 |
| +} |