package cgroup import ( "errors" "os" "os/exec" "path/filepath" "strconv" "testing" ) func TestExecNameAndIsExecName(t *testing.T) { if got := ExecName("keymail.dev"); got != "carlos-exec@keymail.dev" { t.Fatalf("ExecName = %q, want %q", got, "carlos-exec@keymail.dev") } for name, want := range map[string]bool{ "carlos-exec@keymail.dev": true, "carlos-exec@": false, // no host — not one of ours "supervise": false, // the agent's own leaf "carlos-app@x.service": false, "cgroup.procs": false, } { if got := IsExecName(name); got != want { t.Errorf("IsExecName(%q) = %v, want %v", name, got, want) } } } // TestParseSelfCgroup pins the /proc/self/cgroup v2 line format: the "0::" // line carries the unified-hierarchy path. v1-only content (no 0:: line) // and the root cgroup ("0::/") both report not-ok — neither is a subtree // systemd could have delegated to us. func TestParseSelfCgroup(t *testing.T) { cases := []struct { name, data, want string ok bool }{ {"systemd service", "0::/system.slice/carlos-edge.service\n", "system.slice/carlos-edge.service", true}, {"hybrid box, v2 line among v1", "12:pids:/system.slice\n0::/system.slice/carlos-edge.service\n", "system.slice/carlos-edge.service", true}, {"v1 only", "12:pids:/system.slice\n11:cpu:/system.slice\n", "", false}, {"root cgroup", "0::/\n", "", false}, {"empty", "", "", false}, } for _, c := range cases { got, ok := ParseSelfCgroup(c.data) if got != c.want || ok != c.ok { t.Errorf("%s: ParseSelfCgroup = (%q, %v), want (%q, %v)", c.name, got, ok, c.want, c.ok) } } } // newDelegatedRoot builds the temp-dir shape of a delegated cgroup: the two // control files systemd chowns to the unit's user when Delegate= is set. // Everything the dance does is plain file I/O, so a temp dir is a faithful // fixture — the same seam listCarlosUnits uses in internal/host. // forgetKills clears the process-wide kill marks (Linux builds set it). The // marks are keyed by (device, inode), so a mark an earlier test left would // name a fresh test directory on a filesystem that reuses inodes (ext4, // xfs), and the start would remove a cgroup that never took a kill. // cgroupfs does not reuse cgroup inode ids; a temp dir can. var forgetKills = func() {} func newDelegatedRoot(t *testing.T) string { t.Helper() forgetKills() root := t.TempDir() for _, f := range []string{"cgroup.procs", "cgroup.subtree_control"} { if err := os.WriteFile(filepath.Join(root, f), nil, 0o644); err != nil { t.Fatal(err) } } return root } // TestSetupAtRefusesUndelegatedRoot: without Delegate= the control files are // root-owned (here: absent) — SetupAt must error so Setup degrades to the // nil manager instead of half-arming. func TestSetupAtRefusesUndelegatedRoot(t *testing.T) { if _, err := SetupAt(t.TempDir(), t.Logf); err == nil { t.Fatal("SetupAt on an undelegated root succeeded, want error") } } // TestSetupAtDance pins the dance's observable results: the agent's own PID // moved into the supervise/ leaf (cgroup v2 forbids enabling controllers on // a cgroup with member processes), then the four controllers enabled in // subtree_control, and Root reporting the subtree. func TestSetupAtDance(t *testing.T) { root := newDelegatedRoot(t) m, err := SetupAt(root, t.Logf) if err != nil { t.Fatal(err) } if m.Root() != root { t.Errorf("Root = %q, want %q", m.Root(), root) } pid, err := os.ReadFile(filepath.Join(root, "supervise", "cgroup.procs")) if err != nil { t.Fatalf("supervise leaf not populated: %v", err) } if string(pid) != strconv.Itoa(os.Getpid()) { t.Errorf("supervise/cgroup.procs = %q, want our own pid %d", pid, os.Getpid()) } ctrl, err := os.ReadFile(filepath.Join(root, "cgroup.subtree_control")) if err != nil { t.Fatal(err) } if string(ctrl) != "+cpu +memory +io +pids" { t.Errorf("subtree_control = %q, want %q", ctrl, "+cpu +memory +io +pids") } } // TestSetupAtSweepsStaleExecDirs: a previous agent's per-host dirs are empty // after its children died with the service; the dance removes them. A // non-empty one (something still alive in it — shouldn't happen, but rmdir // would fail anyway) and a foreign name are left alone. func TestSetupAtSweepsStaleExecDirs(t *testing.T) { root := newDelegatedRoot(t) stale := filepath.Join(root, "carlos-exec@old.example.com") if err := os.Mkdir(stale, 0o755); err != nil { t.Fatal(err) } occupied := filepath.Join(root, "carlos-exec@busy.example.com") if err := os.MkdirAll(filepath.Join(occupied, "child"), 0o755); err != nil { t.Fatal(err) } foreign := filepath.Join(root, "not-ours") if err := os.Mkdir(foreign, 0o755); err != nil { t.Fatal(err) } if _, err := SetupAt(root, t.Logf); err != nil { t.Fatal(err) } if _, err := os.Stat(stale); !os.IsNotExist(err) { t.Errorf("stale exec dir survived the sweep: %v", err) } if _, err := os.Stat(occupied); err != nil { t.Errorf("non-empty exec dir must be tolerated, not force-removed: %v", err) } if _, err := os.Stat(foreign); err != nil { t.Errorf("foreign dir must be untouched: %v", err) } } func TestNilManagerRoot(t *testing.T) { var m *Manager if got := m.Root(); got != "" { t.Fatalf("nil Root = %q, want \"\"", got) } } // fakeStart swaps the package's spawn seam for a recorder, restoring it on // cleanup. The fake never spawns anything: "success" fabricates cmd.Process // from our own PID so the PID-move path has a real number to write. func fakeStart(t *testing.T, fail func(cmd *exec.Cmd) error) *[]*exec.Cmd { t.Helper() var calls []*exec.Cmd orig := startCmd startCmd = func(cmd *exec.Cmd) error { calls = append(calls, cmd) if err := fail(cmd); err != nil { return err } cmd.Process, _ = os.FindProcess(os.Getpid()) return nil } t.Cleanup(func() { startCmd = orig }) return &calls } func buildTrue() *exec.Cmd { return exec.Command("/bin/true") } // TestStartNilManagerSpawnsPlainly: the nil manager is the no-delegation // state — one plain start, no SysProcAttr, no filesystem writes. func TestStartNilManagerSpawnsPlainly(t *testing.T) { calls := fakeStart(t, func(*exec.Cmd) error { return nil }) var m *Manager cmd, err := m.Start("h.example.com", Limit{}, buildTrue) if err != nil || cmd == nil { t.Fatalf("Start = (%v, %v), want started cmd", cmd, err) } if len(*calls) != 1 || (*calls)[0].SysProcAttr != nil { t.Fatalf("nil manager must start exactly once with no SysProcAttr: %d calls", len(*calls)) } } // TestStartGenuineSpawnFailureIsReturned: when the start itself fails (here // the PID-move start a temp dir's placement failure falls back to), the // error propagates and the host dir this spawn made does not survive it. func TestStartGenuineSpawnFailureIsReturned(t *testing.T) { root := newDelegatedRoot(t) m, err := SetupAt(root, t.Logf) if err != nil { t.Fatal(err) } fakeStart(t, func(*exec.Cmd) error { return errors.New("no such binary") }) if _, err := m.Start("h.example.com", Limit{}, buildTrue); err == nil { t.Fatal("Start with a failing spawn succeeded, want error") } if _, err := os.Stat(m.hostDir("h.example.com")); !os.IsNotExist(err) { t.Errorf("ghost host dir survived a failed spawn: %v", err) } } // TestCleanupHost: removes an empty per-host dir, tolerates a non-empty // one, and is nil-safe. func TestCleanupHost(t *testing.T) { root := newDelegatedRoot(t) m, err := SetupAt(root, t.Logf) if err != nil { t.Fatal(err) } empty := filepath.Join(root, ExecName("gone.example.com")) if err := os.Mkdir(empty, 0o755); err != nil { t.Fatal(err) } m.CleanupHost("gone.example.com") if _, err := os.Stat(empty); !os.IsNotExist(err) { t.Errorf("empty host dir not removed: %v", err) } busy := filepath.Join(root, ExecName("busy.example.com")) if err := os.MkdirAll(filepath.Join(busy, "child"), 0o755); err != nil { t.Fatal(err) } m.CleanupHost("busy.example.com") // must not panic or force-remove if _, err := os.Stat(busy); err != nil { t.Errorf("non-empty host dir must survive: %v", err) } var nilM *Manager nilM.CleanupHost("h.example.com") // must not panic } // TestStartAndMoveRemovesGhostDirOnSpawnFailure: when the spawn itself // never happens, the host cgroup dir must not survive it — a ghost dir // would make the sampler report permanent zeros for a host with nothing // running. func TestStartAndMoveRemovesGhostDirOnSpawnFailure(t *testing.T) { root := newDelegatedRoot(t) m, err := SetupAt(root, t.Logf) if err != nil { t.Fatal(err) } dir := m.hostDir("h.example.com") if err := os.MkdirAll(dir, 0o755); err != nil { t.Fatal(err) } fakeStart(t, func(*exec.Cmd) error { return errors.New("no such binary") }) if _, err := m.startAndMove("h.example.com", buildTrue); err == nil { t.Fatal("startAndMove with a failing spawn succeeded, want error") } if _, err := os.Stat(dir); !os.IsNotExist(err) { t.Errorf("ghost host dir survived a failed spawn: %v", err) } } // TestStartAndMoveToleratesBrokenSeam: a startCmd seam that reports success // without ever setting cmd.Process must not panic while writing the PID — // this package must never panic the agent over a broken seam. func TestStartAndMoveToleratesBrokenSeam(t *testing.T) { root := newDelegatedRoot(t) m, err := SetupAt(root, t.Logf) if err != nil { t.Fatal(err) } if err := os.MkdirAll(m.hostDir("h.example.com"), 0o755); err != nil { t.Fatal(err) } orig := startCmd startCmd = func(cmd *exec.Cmd) error { return nil } // never sets cmd.Process t.Cleanup(func() { startCmd = orig }) if _, err := m.startAndMove("h.example.com", buildTrue); err != nil { t.Fatal(err) } } // TestStartWritesMemoryLimit: a non-zero Limit lands in the host cgroup as // memory.max and memory.high (high = 90% of max, so a tenant is throttled // and reclaimed before it is killed). The temp-dir fixture has no kernel // behind it, so the assertion is on the bytes written. func TestStartWritesMemoryLimit(t *testing.T) { root := newDelegatedRoot(t) m, err := SetupAt(root, t.Logf) if err != nil { t.Fatal(err) } fakeStart(t, func(*exec.Cmd) error { return nil }) if _, err := m.Start("h.example.com", Limit{MemoryMax: 1 << 30}, buildTrue); err != nil { t.Fatal(err) } dir := m.hostDir("h.example.com") for file, want := range map[string]string{ "memory.max": "1073741824", "memory.high": "966367638", // max/10*9, integer arithmetic "memory.oom.group": "1", "memory.swap.max": "1073741824", // = max: the cap is total, not RAM-only } { got, err := os.ReadFile(filepath.Join(dir, file)) if err != nil { t.Fatalf("%s not written: %v", file, err) } if string(got) != want { t.Errorf("%s = %q, want %q", file, got, want) } } } // TestStartZeroLimitWritesNothing: the zero Limit is "no cap" — the // pre-spec behaviour, byte for byte, for any caller that has no tier. func TestStartZeroLimitWritesNothing(t *testing.T) { root := newDelegatedRoot(t) m, err := SetupAt(root, t.Logf) if err != nil { t.Fatal(err) } fakeStart(t, func(*exec.Cmd) error { return nil }) if _, err := m.Start("h.example.com", Limit{}, buildTrue); err != nil { t.Fatal(err) } for _, file := range []string{"memory.max", "memory.high"} { if _, err := os.Stat(filepath.Join(m.hostDir("h.example.com"), file)); !os.IsNotExist(err) { t.Errorf("%s exists for a zero limit", file) } } } // TestStartLimitWriteFailureStillSpawns: a cgroup that refuses the limit // (read-only control file, an old kernel) costs one log line and an // uncapped child — never a failed spawn. Same discipline as every other // accounting failure in this package. func TestStartLimitWriteFailureStillSpawns(t *testing.T) { root := newDelegatedRoot(t) m, err := SetupAt(root, t.Logf) if err != nil { t.Fatal(err) } dir := m.hostDir("h.example.com") if err := os.MkdirAll(dir, 0o755); err != nil { t.Fatal(err) } // A directory where the file should go: WriteFile fails with EISDIR. if err := os.Mkdir(filepath.Join(dir, "memory.max"), 0o755); err != nil { t.Fatal(err) } fakeStart(t, func(*exec.Cmd) error { return nil }) cmd, err := m.Start("h.example.com", TierDefault, buildTrue) if err != nil || cmd == nil { t.Fatalf("Start = (%v, %v), want a started cmd despite the limit failure", cmd, err) } // max failed, so high must NOT have been written: a high with no max // is a throttle with no wall, and the doc comment promises the short // circuit. if _, err := os.Stat(filepath.Join(dir, "memory.high")); !os.IsNotExist(err) { t.Errorf("memory.high written after memory.max failed: %v", err) } } // TestStartBiasesChildOOMScore: a started child gets ExecOOMScoreAdj // written to its oom_score_adj (redirected into a temp dir here), on both // spawn paths. Without it the agent — the largest process in the edge // tree — is the memcg OOM killer's first pick when the outer wall fires. func TestStartBiasesChildOOMScore(t *testing.T) { root := newDelegatedRoot(t) m, err := SetupAt(root, t.Logf) if err != nil { t.Fatal(err) } adj := t.TempDir() orig := oomScoreAdjPath oomScoreAdjPath = func(pid int) string { return filepath.Join(adj, strconv.Itoa(pid)) } t.Cleanup(func() { oomScoreAdjPath = orig }) // A real start: /bin/true gives the child a pid to write for. cmd, err := m.startAndMove("h.example.com", buildTrue) if err != nil { t.Fatal(err) } _ = cmd.Wait() got, err := os.ReadFile(filepath.Join(adj, strconv.Itoa(cmd.Process.Pid))) if err != nil { t.Fatalf("oom_score_adj not written: %v", err) } if string(got) != ExecOOMScoreAdj { t.Errorf("oom_score_adj = %q, want %q", got, ExecOOMScoreAdj) } } func TestTiers(t *testing.T) { if TierDefault.MemoryMax != 512<<20 { t.Errorf("TierDefault = %d, want 512M — the carlos-app@ template's number", TierDefault.MemoryMax) } if TierChildren.MemoryMax != 1<<30 { t.Errorf("TierChildren = %d, want 1G — caps/render.go's children tier", TierChildren.MemoryMax) } } func TestSetupAtRetainingPreservesClaimEvidence(t *testing.T) { root := newDelegatedRoot(t) retained := filepath.Join(root, "carlos-exec@claim-old.local") if err := os.Mkdir(retained, 0755); err != nil { t.Fatal(err) } if _, err := SetupAtRetaining(root, t.Logf); err != nil { t.Fatal(err) } if _, err := os.Stat(retained); err != nil { t.Fatalf("retained claim tree removed: %v", err) } }