carlos / platform Public

remote-metrics-nested: the sweep samples nested instances and tags them by the same rule

The sampler read only top-level carlos-*.service cgroups, so no nested
(isolated exec) instance had a reading on any box. It now reads each
route host's slice under carlos.slice/carlos-instances.slice, sums the
unit cgroups in it (fresh per start, unlike the slice) and publishes them
as carlos-exec@<host>, so the console's match and tenant filter are
unchanged. Tags follow the flat rule; a reading that includes a unit
present when the agent started is a leftover and never vouched. Tests: a
real activator over a nested cgroup tree, a reused hostname, an agent
restart, and a root-runner test under systemd (passed, run
20261026T194200-02064e). 8 mutants, all killed.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev dea5a7eda17f9d08db813be9b3c63adb46e6e514 parent 4dc5902
9 files changed, +647 −14
  • internal/host/agent.go +26 −1
  • internal/host/agentalerts_test.go +1 −1
  • internal/host/metrics_loop.go +56 −12
  • internal/host/metrics_nested.go +133 −0
  • internal/host/metrics_nested_linux.go +23 −0
  • internal/host/metrics_nested_other.go +7 −0
  • internal/host/metrics_nested_rootrunner_linux_test.go +86 −0
  • internal/host/metrics_nested_test.go +312 −0
  • internal/host/metrics_probes.go +3 −0
diff --git a/internal/host/agent.go b/internal/host/agent.go
index 14a7a47f5..c4d728341 100644
--- a/internal/host/agent.go
+++ b/internal/host/agent.go
@@ -279,6 +279,10 @@ func runAgent(args []string, buildClaims ClaimFactory) {
} else {
cgm = cgroup.Setup(log.Printf)
}
+ // What the nested layout holds before this agent can start anything:
+ // the metrics sampler never vouches a reading that includes one of
+ // these units (remote instance metrics, nested follow-up).
+ nestedAtStart := snapshotNestedUnits(cgroupInstancesSliceDir)
// Alert sinks and the operator paging hook (moves spec §13), built from
// the sink env alone and armed here, before armMovesPass and before any
@@ -910,7 +914,12 @@ func runAgent(args []string, buildClaims ClaimFactory) {
if svc != nil {
owners = func() map[string]metrics.Vouch { return metricsOwners(reg, svc, cgm.Leftover) }
}
- go metricsLoop(cgm.Root(), func() []string { return stampedUnitNames(reg) }, owners, alerts)
+ go metricsLoop(cgm.Root(), unitSources{
+ stamped: func() []string { return stampedUnitNames(reg) },
+ nestedHosts: func() []string { return routeHostNames(reg) },
+ nestedRoot: cgroupInstancesSliceDir,
+ nestedAtStart: nestedAtStart,
+ }, owners, alerts)
go configSyncLoop(reg, svc, dd, claims.Writes)
go configGenLoop(reg, svc, dd, claims.Writes)
go socketAdvisoryLoop(reg, svc)
@@ -3924,6 +3933,22 @@ func retentionLoop(reg *registry.Registry, buildStates func() (map[string]status
// and the agent are not. The names are returned sorted so the slice handed
// down each tick is stable (nothing below depends on the order; a stable one
// just makes a log or a test diff mean something).
+// routeHostNames is every host the registry has a route for: the sampler
+// reads each one's nested slice, if it has one (nestedUnitReadings). A read
+// failure returns nil: this tick's nested readings are lost, nothing else.
+func routeHostNames(reg *registry.Registry) []string {
+ routes, err := reg.List()
+ if err != nil {
+ log.Printf("agent: metrics: read route hosts: %v", err)
+ return nil
+ }
+ out := make([]string, 0, len(routes))
+ for _, rt := range routes {
+ out = append(out, rt.Host)
+ }
+ return out
+}
+
func stampedUnitNames(reg *registry.Registry) []string {
routes, err := reg.List()
if err != nil {
diff --git a/internal/host/agentalerts_test.go b/internal/host/agentalerts_test.go
index d0debe5c2..8778b0f07 100644
--- a/internal/host/agentalerts_test.go
+++ b/internal/host/agentalerts_test.go
@@ -47,7 +47,7 @@ func TestStuckMarkBeforeMetricsReachesTheSink(t *testing.T) {
if _, _, err := openStatusStore(context.Background(), os.Getenv); err == nil {
t.Fatal("fixture: the metrics store opened")
}
- metricsLoop(t.TempDir(), nil, nil, sinks)
+ metricsLoop(t.TempDir(), unitSources{}, nil, sinks)
}
h := newRevertHarness(t)
diff --git a/internal/host/metrics_loop.go b/internal/host/metrics_loop.go
index b963933f8..0363f4369 100644
--- a/internal/host/metrics_loop.go
+++ b/internal/host/metrics_loop.go
@@ -115,6 +115,15 @@ func (sm *sampler) tick(p sampleProbes) {
newPrevUnit[name] = u.cpuUsec
}
metrics.TagUnits(unitSamples, before, after)
+ // A nested reading that includes a unit this agent did not start
+ // is not vouched, whoever the activator says holds the host now.
+ for name, u := range units {
+ if u.leftover {
+ s := unitSamples[name]
+ s.Owner = nil
+ unitSamples[name] = s
+ }
+ }
}
// The CPU fraction above is a delta from the previous tick's counter:
// a reading keeps its tag only if that tick vouched the same tenant.
@@ -619,18 +628,32 @@ func httpPostWebhook(url string, body []byte) error { return alerting.PostJSON(u
// start, and a route stamped this afternoon would go unsampled until the next
// restart. A nil func means "no stamped units" — the darwin/dev shape, and
// what every test double passes.
-func realSampleProbes(execRoot string, stampedUnits func() []string, owners func() map[string]metrics.Vouch) sampleProbes {
+// unitSources is the sampler's registry and layout inputs: the bespoke
+// units stamped on routes, the hosts whose nested slices to read, and what
+// the nested layout held when the agent started (nestedStart). nil funcs
+// are none.
+type unitSources struct {
+ stamped func() []string
+ nestedHosts func() []string
+ nestedRoot string
+ nestedAtStart nestedStart
+}
+
+func realSampleProbes(execRoot string, src unitSources, owners func() map[string]metrics.Vouch) sampleProbes {
return sampleProbes{
procStat: readProcStat,
loadavg: readLoadAvg,
memFrac: readMemFrac,
diskFrac: readDiskFrac,
units: func() map[string]unitRaw {
- var stamped []string
- if stampedUnits != nil {
- stamped = stampedUnits()
+ var stamped, nested []string
+ if src.stamped != nil {
+ stamped = src.stamped()
+ }
+ if src.nestedHosts != nil {
+ nested = src.nestedHosts()
}
- return realUnitReadings(execRoot, stamped)
+ return mergeNested(realUnitReadings(execRoot, stamped), nestedUnitReadings(src.nestedRoot, nested, src.nestedAtStart))
},
owners: owners,
now: time.Now,
@@ -761,11 +784,12 @@ func BoxLabel() string { return metricsBoxLabel(os.Getenv, readMachineID()) }
// at the 60s tick cadence); alertTick runs every tick, since a threshold
// breach deserves faster detection than a metrics flush does.
//
-// stampedUnits is the sweep's one registry seam (agent.go's
-// stampedUnitNames): the bespoke units to sample alongside the carlos- ones,
-// re-read once per tick so a freshly stamped route is picked up within a
-// minute. It is a func, not the registry handle, so this loop keeps its "no
-// state but a bucket and /proc" shape; nil = none.
+// src is the sweep's registry seams (agent.go): the bespoke units to sample
+// alongside the carlos- ones (stampedUnitNames) and the hosts whose nested
+// slices to read (routeHostNames), re-read once per tick so a freshly
+// stamped or minted route is picked up within a minute, plus the nested
+// layout as it was at agent start. Funcs, not the registry handle, so this
+// loop keeps its "no state but a bucket and /proc" shape; nil = none.
//
// owners tags each exec cgroup's reading with the tenant the box vouches
// for (metricsOwners, agent.go's wiring); nil tags nothing.
@@ -773,7 +797,7 @@ func BoxLabel() string { return metricsBoxLabel(os.Getenv, readMachineID()) }
// sinks are the agent's alert sinks, built and armed for paging by runAgent
// at startup (armAgentAlerts); the loop delivers its alerts on them and
// never builds or arms its own. nil delivers nowhere.
-func metricsLoop(execRoot string, stampedUnits func() []string, owners func() map[string]metrics.Vouch, sinks *alertSinks) {
+func metricsLoop(execRoot string, src unitSources, owners func() map[string]metrics.Vouch, sinks *alertSinks) {
// This loop is always on and shares a process with the agent that serves
// this box's traffic, so a panic in it — an unreadable cgroup shape, a
// nil no one expected — must not take the box down with it. Monitoring
@@ -821,7 +845,7 @@ func metricsLoop(execRoot string, stampedUnits func() []string, owners func() ma
log.Printf("agent: metrics loop armed (60s ticks, 5min flush), publishing to %s", target)
sm := &sampler{}
- probes := realSampleProbes(execRoot, stampedUnits, owners)
+ probes := realSampleProbes(execRoot, src, owners)
tick := 0
// One watch for the life of the loop: its memory of what it has already
// alerted is what keeps a standing refusal from paging every minute.
@@ -847,3 +871,23 @@ func metricsLoop(execRoot string, stampedUnits func() []string, owners func() ma
}
}
}
+
+// mergeNested adds nested hosts' readings to the flat scan's. A host with
+// both (a layout change in flight) is summed: both are its processes, under
+// the same activator entry rule.
+func mergeNested(flat, nested map[string]unitRaw) map[string]unitRaw {
+ if len(nested) == 0 {
+ return flat
+ }
+ if flat == nil {
+ flat = make(map[string]unitRaw, len(nested))
+ }
+ for name, n := range nested {
+ if f, ok := flat[name]; ok {
+ flat[name] = sumUnitRaw([]unitRaw{f, n})
+ continue
+ }
+ flat[name] = n
+ }
+ return flat
+}
diff --git a/internal/host/metrics_nested.go b/internal/host/metrics_nested.go
new file mode 100644
index 000000000..78f53ae3c
--- /dev/null
+++ b/internal/host/metrics_nested.go
@@ -0,0 +1,133 @@
+package host
+
+import (
+ "errors"
+ "io/fs"
+ "os"
+ "path/filepath"
+ "strings"
+
+ "github.com/carlosframework/platform/internal/cgroup"
+ "github.com/carlosframework/platform/internal/instancectl"
+)
+
+// cgroupInstancesSliceDir is the nested layout's parent slice
+// (instancectl's parentSlices under the cgroup root): every nested host has
+// its slice, carlos-instances-<id>.slice, below it, and its units (run,
+// generations, sidecar, seed, cmd, rootfs) below that. The sampler's unit
+// scans read only system.slice and carlos.slice's own children, so before
+// this no nested instance had a reading at all, on any box.
+const cgroupInstancesSliceDir = "/sys/fs/cgroup/carlos.slice/carlos-instances.slice"
+
+// nestedStart is what the nested layout held when this agent started,
+// taken before the activator can start anything: the cgroup ids of every
+// unit then under a host's slice. Nested units are bound to carlos-edge
+// (BindsTo=), so a previous agent's units stop with it, but a stop can
+// still be in flight when this agent starts. A reading that includes one
+// of them is never vouched (unitRaw.leftover). unswept says the layout
+// could not be listed, so nothing in it is known to be this agent's.
+type nestedStart struct {
+ ids map[uint64]bool
+ unswept bool
+}
+
+// snapshotNestedUnits records root's unit cgroups for nestedStart. A box
+// with no nested layout (root absent) holds none.
+func snapshotNestedUnits(root string) nestedStart {
+ slices, err := os.ReadDir(root)
+ if err != nil {
+ if errors.Is(err, fs.ErrNotExist) {
+ return nestedStart{}
+ }
+ return nestedStart{unswept: true}
+ }
+ st := nestedStart{ids: map[uint64]bool{}}
+ for _, s := range slices {
+ if !s.IsDir() || !strings.HasSuffix(s.Name(), ".slice") {
+ continue
+ }
+ units, err := os.ReadDir(filepath.Join(root, s.Name()))
+ if err != nil {
+ st.unswept = true
+ continue
+ }
+ for _, u := range units {
+ if !u.IsDir() || !strings.HasSuffix(u.Name(), ".service") {
+ continue
+ }
+ id, ok := cgroupID(filepath.Join(root, s.Name(), u.Name()))
+ if !ok {
+ st.unswept = true
+ continue
+ }
+ st.ids[id] = true
+ }
+ }
+ return st
+}
+
+// nestedUnitReadings reads each host's nested units and sums them into one
+// reading per host, keyed carlos-exec@<host>: the name a flat host's
+// processes report under, so the console's per-host match and its tenant
+// filter need no change. It reads the unit cgroups, never the host's
+// slice: a unit's cgroup is new at each start, while the slice keeps the
+// charges of units that stopped, an earlier tenant's included. A host with
+// no slice (not nested here) is skipped. The reading is a leftover when
+// any unit in it was there when the agent started, its id cannot be read,
+// or the start could not be swept.
+func nestedUnitReadings(root string, hosts []string, start nestedStart) map[string]unitRaw {
+ out := map[string]unitRaw{}
+ for _, host := range hosts {
+ dir := filepath.Join(root, instancectl.SliceName(host))
+ units, err := os.ReadDir(dir)
+ if err != nil {
+ continue
+ }
+ var parts []unitRaw
+ leftover := start.unswept
+ for _, u := range units {
+ if !u.IsDir() || !strings.HasSuffix(u.Name(), ".service") {
+ continue
+ }
+ ud := filepath.Join(dir, u.Name())
+ if id, ok := cgroupID(ud); !ok || start.ids[id] {
+ leftover = true
+ }
+ parts = append(parts, readUnitRaw(ud))
+ }
+ if len(parts) == 0 {
+ continue
+ }
+ sum := sumUnitRaw(parts)
+ sum.leftover = leftover
+ out[cgroup.ExecName(host)] = sum
+ }
+ return out
+}
+
+// sumUnitRaw adds readings of one host's cgroups. A field is summed only
+// when every part has it: a partial CPU sum would make a wrong delta. The
+// peak is left unset, since peaks of different cgroups do not add.
+func sumUnitRaw(parts []unitRaw) unitRaw {
+ add := func(get func(unitRaw) *int64) *int64 {
+ var total int64
+ for _, p := range parts {
+ v := get(p)
+ if v == nil {
+ return nil
+ }
+ total += *v
+ }
+ return &total
+ }
+ out := unitRaw{
+ cpuUsec: add(func(u unitRaw) *int64 { return u.cpuUsec }),
+ memBytes: add(func(u unitRaw) *int64 { return u.memBytes }),
+ readBytes: add(func(u unitRaw) *int64 { return u.readBytes }),
+ writeBytes: add(func(u unitRaw) *int64 { return u.writeBytes }),
+ }
+ for _, p := range parts {
+ out.leftover = out.leftover || p.leftover
+ }
+ return out
+}
diff --git a/internal/host/metrics_nested_linux.go b/internal/host/metrics_nested_linux.go
new file mode 100644
index 000000000..f601ea65c
--- /dev/null
+++ b/internal/host/metrics_nested_linux.go
@@ -0,0 +1,23 @@
+//go:build linux
+
+package host
+
+import (
+ "os"
+ "syscall"
+)
+
+// cgroupID is dir's inode, which on cgroup v2 is the cgroup's id: never
+// reused while the box is up, so a unit started again under the same name
+// is a new id. ok is false when it cannot be read.
+func cgroupID(dir string) (uint64, bool) {
+ fi, err := os.Stat(dir)
+ if err != nil {
+ return 0, false
+ }
+ st, ok := fi.Sys().(*syscall.Stat_t)
+ if !ok {
+ return 0, false
+ }
+ return st.Ino, true
+}
diff --git a/internal/host/metrics_nested_other.go b/internal/host/metrics_nested_other.go
new file mode 100644
index 000000000..d5ff512e4
--- /dev/null
+++ b/internal/host/metrics_nested_other.go
@@ -0,0 +1,7 @@
+//go:build !linux
+
+package host
+
+// cgroupID has no cgroup to name off Linux: nested instances are a Linux
+// layout, and nothing read here is ever vouched.
+func cgroupID(string) (uint64, bool) { return 0, false }
diff --git a/internal/host/metrics_nested_rootrunner_linux_test.go b/internal/host/metrics_nested_rootrunner_linux_test.go
new file mode 100644
index 000000000..8eb4948af
--- /dev/null
+++ b/internal/host/metrics_nested_rootrunner_linux_test.go
@@ -0,0 +1,86 @@
+//go:build linux && rootrunner
+
+package host
+
+import (
+ "context"
+ "os"
+ "os/exec"
+ "path/filepath"
+ "testing"
+ "time"
+
+ "github.com/carlosframework/platform/internal/cgroup"
+ "github.com/carlosframework/platform/internal/instancectl"
+)
+
+// TestRootRunnerNestedUnitsAreSampled runs a unit where instance-control
+// puts a nested host's run unit (systemd-run into its per-host slice, so
+// systemd makes carlos.slice/carlos-instances.slice/<host slice>/<unit>)
+// and reads it with the production reader from the production root. The
+// reading has CPU and memory; it is not a leftover when started after the
+// snapshot, and is one when the snapshot already held it.
+func TestRootRunnerNestedUnitsAreSampled(t *testing.T) {
+ if os.Geteuid() != 0 {
+ t.Fatal("needs root")
+ }
+ const host = "rr.nested.example.com"
+ unit := instancectl.UnitName(instancectl.RoleRun, host)
+ slice := instancectl.SliceName(host)
+ before := snapshotNestedUnits(cgroupInstancesSliceDir)
+ if before.unswept {
+ t.Fatalf("snapshot before the unit = %+v", before)
+ }
+ out, err := exec.Command("systemd-run", "--unit="+unit, "--slice="+slice, "--property=MemoryAccounting=yes",
+ "--property=CPUAccounting=yes", "/bin/sh", "-c", "i=0; while [ $i -lt 2000000 ]; do i=$((i+1)); done; sleep 120").CombinedOutput()
+ if err != nil {
+ t.Fatalf("systemd-run: %v %s", err, out)
+ }
+ t.Cleanup(func() { exec.Command("systemctl", "stop", unit).Run() }) //nolint:errcheck
+ dir := filepath.Join(cgroupInstancesSliceDir, slice, unit)
+ deadline := time.Now().Add(10 * time.Second)
+ for {
+ if _, err := os.Stat(filepath.Join(dir, "cpu.stat")); err == nil {
+ break
+ }
+ if time.Now().After(deadline) {
+ t.Fatalf("the unit's cgroup %s did not appear", dir)
+ }
+ time.Sleep(100 * time.Millisecond)
+ }
+ time.Sleep(time.Second)
+
+ got := nestedUnitReadings(cgroupInstancesSliceDir, []string{host, "flat.example.com"}, before)
+ r, ok := got[cgroup.ExecName(host)]
+ if !ok || len(got) != 1 {
+ t.Fatalf("readings = %+v, want one for %s", got, host)
+ }
+ if r.cpuUsec == nil || *r.cpuUsec <= 0 || r.memBytes == nil || *r.memBytes <= 0 {
+ t.Fatalf("reading = cpu %v mem %v, want both", r.cpuUsec, r.memBytes)
+ }
+ if r.leftover {
+ t.Fatal("a unit started after the snapshot is a leftover")
+ }
+ after := snapshotNestedUnits(cgroupInstancesSliceDir)
+ if !nestedUnitReadings(cgroupInstancesSliceDir, []string{host}, after)[cgroup.ExecName(host)].leftover {
+ t.Fatal("a unit the snapshot held is not a leftover")
+ }
+
+ // The unit stops and starts again under the same name: a new cgroup id,
+ // so no longer the snapshot's.
+ if out, err := exec.Command("systemctl", "stop", unit).CombinedOutput(); err != nil {
+ t.Fatalf("stop: %v %s", err, out)
+ }
+ if out, err := exec.Command("systemd-run", "--unit="+unit, "--slice="+slice, "/bin/sleep", "120").CombinedOutput(); err != nil {
+ t.Fatalf("systemd-run again: %v %s", err, out)
+ }
+ ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
+ defer cancel()
+ for ctx.Err() == nil {
+ if r, ok := nestedUnitReadings(cgroupInstancesSliceDir, []string{host}, after)[cgroup.ExecName(host)]; ok && !r.leftover {
+ return
+ }
+ time.Sleep(100 * time.Millisecond)
+ }
+ t.Fatal("a restarted unit kept the earlier cgroup's id")
+}
diff --git a/internal/host/metrics_nested_test.go b/internal/host/metrics_nested_test.go
new file mode 100644
index 000000000..9bef267e9
--- /dev/null
+++ b/internal/host/metrics_nested_test.go
@@ -0,0 +1,312 @@
+package host
+
+// Nested (isolated exec) instances in the metrics sweep, end to end on one
+// box: a real registry, a real activator waking and stopping through a
+// stand-in backend, the nested layout's cgroup tree as instance-control
+// lays it out (carlos-instances-<id>.slice/<unit>, written here into a temp
+// root), the sampler's tick and flush, and the chunk the console reads.
+// The real tree under systemd is TestRootRunnerNestedUnitsAreSampled.
+
+import (
+ "context"
+ "encoding/json"
+ "errors"
+ "net/http"
+ "net/http/httptest"
+ "os"
+ "path/filepath"
+ "strconv"
+ "testing"
+ "time"
+
+ "github.com/carlosframework/platform/internal/activator"
+ "github.com/carlosframework/platform/internal/cgroup"
+ "github.com/carlosframework/platform/internal/instancectl"
+ "github.com/carlosframework/platform/internal/metrics"
+ "github.com/carlosframework/platform/internal/registry"
+ "github.com/carlosframework/platform/internal/release"
+)
+
+// nestedBackend starts nothing real: the wake's process is a plannedProc,
+// and its units are whatever the test writes into the cgroup tree.
+type nestedBackend struct{}
+
+func (nestedBackend) Acquire(context.Context, registry.Route) (activator.Lease, error) {
+ return plannedLease{}, nil
+}
+func (nestedBackend) Restore(context.Context, registry.Route) (bool, error) { return false, nil }
+func (nestedBackend) Seed(context.Context, registry.Route) error { return nil }
+func (nestedBackend) Start(context.Context, registry.Route) (activator.Proc, string, error) {
+ return &plannedProc{}, "v1", nil
+}
+func (nestedBackend) NextDue(context.Context, registry.Route) (int64, error) { return 0, nil }
+func (nestedBackend) HasSidecar(registry.Route) bool { return false }
+func (nestedBackend) StartSidecar(context.Context, registry.Route) (activator.Proc, error) {
+ return nil, errors.New("no sidecar")
+}
+func (nestedBackend) StartWorker(context.Context, registry.Route, map[string]string) (activator.Proc, string, error) {
+ return nil, "", errors.New("no worker")
+}
+
+const nestedHost = "eu.shop.example.com"
+
+// nestedBox is one box: its registry, its activator and its nested root.
+type nestedBox struct {
+ reg *registry.Registry
+ svc *activator.Service
+ root string
+ socket string
+ start nestedStart
+ sm *sampler
+ at time.Time
+}
+
+func newNestedBox(t *testing.T) *nestedBox {
+ t.Helper()
+ reg, err := registry.Open(filepath.Join(t.TempDir(), "registry.db"))
+ if err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(func() { reg.Close() })
+ b := &nestedBox{reg: reg, root: t.TempDir(), socket: healthySocket(t), sm: &sampler{},
+ at: time.Date(2026, 10, 26, 20, 0, 0, 0, time.UTC)}
+ b.restartAgent(t)
+ return b
+}
+
+// restartAgent is a new agent on the box: a fresh activator, and the
+// nested layout snapshotted before it can start anything (runAgent's
+// order).
+func (b *nestedBox) restartAgent(t *testing.T) {
+ t.Helper()
+ b.start = snapshotNestedUnits(b.root)
+ b.svc = activator.New(activator.Config{Bucket: "hib", Idle: time.Hour}, nestedBackend{}, b.reg)
+ b.svc.Routes = b.reg
+ svc := b.svc
+ t.Cleanup(func() { svc.Shutdown(context.Background()) })
+ b.sm = &sampler{}
+}
+
+// mint is the provision pass minting host for acct's app on this box.
+func (b *nestedBox) mint(t *testing.T, acct string) {
+ t.Helper()
+ if err := b.reg.Upsert(registry.Route{Host: nestedHost, Kind: "instance", Account: acct, App: "shop",
+ Socket: b.socket, Hibernate: true, Provisioned: true, Status: "ready"}); err != nil {
+ t.Fatal(err)
+ }
+}
+
+// wake serves one request: the activator wakes the host for its row.
+func (b *nestedBox) wake(t *testing.T) {
+ t.Helper()
+ rt, err := b.reg.Get(nestedHost)
+ if err != nil || rt == nil {
+ t.Fatalf("route: %+v %v", rt, err)
+ }
+ rec := httptest.NewRecorder()
+ req := httptest.NewRequest(http.MethodGet, "http://"+nestedHost+"/", nil)
+ if !b.svc.ServeHTTP(rec, req, *rt, http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {})) || rec.Code != http.StatusOK {
+ t.Fatalf("wake = %d %s", rec.Code, rec.Body)
+ }
+}
+
+// stop puts every entry down, as a retirement or an idle sleep does.
+func (b *nestedBox) stop(t *testing.T) {
+ t.Helper()
+ b.svc.RetireExcept(map[string]bool{})
+ deadline := time.Now().Add(5 * time.Second)
+ for !b.svc.Quiesced(nestedHost) {
+ if time.Now().After(deadline) {
+ t.Fatal("the entry did not stop")
+ }
+ time.Sleep(10 * time.Millisecond)
+ }
+}
+
+// unit writes (or rewrites) one unit cgroup of host's slice, as systemd
+// does for a unit instance-control starts.
+func (b *nestedBox) unit(t *testing.T, unit string, usec, mem int64) string {
+ t.Helper()
+ dir := filepath.Join(b.root, instancectl.SliceName(nestedHost), unit)
+ if err := os.MkdirAll(dir, 0o755); err != nil {
+ t.Fatal(err)
+ }
+ for name, body := range map[string]string{
+ "cpu.stat": "usage_usec " + strconv.FormatInt(usec, 10) + "\n",
+ "memory.current": strconv.FormatInt(mem, 10) + "\n",
+ } {
+ if err := os.WriteFile(filepath.Join(dir, name), []byte(body), 0o644); err != nil {
+ t.Fatal(err)
+ }
+ }
+ return dir
+}
+
+// tick is one sampler tick and flush through production code; it returns
+// the host's reading as the chunk carries it.
+func (b *nestedBox) tick(t *testing.T) metrics.UnitSample {
+ t.Helper()
+ b.at = b.at.Add(time.Minute)
+ f := 0.4
+ src := unitSources{nestedHosts: func() []string { return routeHostNames(b.reg) }, nestedRoot: b.root, nestedAtStart: b.start}
+ p := realSampleProbes("", src, func() map[string]metrics.Vouch { return metricsOwners(b.reg, b.svc, nil) })
+ p.procStat = func() *metrics.CPUCounters { return nil }
+ p.loadavg = func() (*float64, *float64, *float64) { return nil, nil, nil }
+ p.memFrac = func() *float64 { return &f }
+ p.diskFrac = func() *float64 { return &f }
+ at := b.at
+ p.now = func() time.Time { return at }
+ // The real probe also scans the box's own system.slice; only the
+ // nested tree under test is read here.
+ units := p.units
+ p.units = func() map[string]unitRaw {
+ out := map[string]unitRaw{}
+ for k, v := range units() {
+ if k == cgroup.ExecName(nestedHost) {
+ out[k] = v
+ }
+ }
+ return out
+ }
+ b.sm.tick(p)
+ store := release.NewDirStore(t.TempDir())
+ if err := metricsFlush(context.Background(), store, "box-b", b.sm, at); err != nil {
+ t.Fatal(err)
+ }
+ body, _, err := store.Get(context.Background(), metrics.RawKey("box-b", metrics.HourOf(at)))
+ if err != nil {
+ t.Fatal(err)
+ }
+ var chunk metrics.RawChunk
+ if err := json.Unmarshal(body, &chunk); err != nil {
+ t.Fatal(err)
+ }
+ return chunk.Samples[len(chunk.Samples)-1].Units[cgroup.ExecName(nestedHost)]
+}
+
+func owner(u metrics.UnitSample) string {
+ if u.Owner == nil {
+ return ""
+ }
+ return u.Owner.Account + "/" + u.Owner.App
+}
+
+// TestNestedInstanceIsSampledAndTagged: a nested instance's units are
+// read from its slice, summed into one reading under carlos-exec@<host>,
+// and tagged with its tenant once two ticks of the same entry agree.
+func TestNestedInstanceIsSampledAndTagged(t *testing.T) {
+ b := newNestedBox(t)
+ b.mint(t, "bdn")
+ b.wake(t)
+ b.unit(t, instancectl.UnitName(instancectl.RoleRun, nestedHost), 1_000_000, 3<<20)
+ b.unit(t, instancectl.UnitName(instancectl.RoleSidecar, nestedHost), 500_000, 1<<20)
+ first := b.tick(t)
+ if first.MemBytes == nil || *first.MemBytes != 4<<20 {
+ t.Fatalf("nested reading = %+v, want the two units' memory summed (4 MB)", first)
+ }
+ if owner(first) != "bdn/shop" {
+ t.Fatalf("first reading owner = %q, want bdn/shop", owner(first))
+ }
+ b.unit(t, instancectl.UnitName(instancectl.RoleRun, nestedHost), 4_000_000, 3<<20)
+ second := b.tick(t)
+ if second.CPUFrac == nil || owner(second) != "bdn/shop" {
+ t.Fatalf("second reading = cpu %v owner %q, want a CPU fraction tagged bdn/shop", second.CPUFrac, owner(second))
+ }
+}
+
+// TestNestedReusedHostname: the hostname was the rival's on this box, then
+// this account's. Its units are new cgroups, but the host has had two
+// tenants in this agent's life, so nothing is vouched until the agent
+// restarts; after a restart, a unit still there from before the restart is
+// a leftover, and only a reading wholly of units this agent started is
+// tagged.
+func TestNestedReusedHostname(t *testing.T) {
+ b := newNestedBox(t)
+ b.mint(t, "rival")
+ b.wake(t)
+ old := b.unit(t, instancectl.UnitName(instancectl.RoleRun, nestedHost), 9_000_000, 11<<20)
+ if u := b.tick(t); owner(u) != "rival/shop" {
+ t.Fatalf("predecessor's reading owner = %q, want rival/shop", owner(u))
+ }
+ b.stop(t)
+ if err := os.RemoveAll(old); err != nil {
+ t.Fatal(err)
+ }
+ if err := b.reg.Delete(nestedHost); err != nil {
+ t.Fatal(err)
+ }
+ b.mint(t, "bdn")
+ b.wake(t)
+ b.unit(t, instancectl.UnitName(instancectl.RoleRun, nestedHost), 200_000, 2<<20)
+ for i := 0; i < 2; i++ {
+ if u := b.tick(t); u.Owner != nil {
+ t.Fatalf("tick %d after the hostname changed tenant: owner %q, want none", i, owner(u))
+ }
+ }
+
+ // The agent restarts while the unit is still there (its stop in
+ // flight): a leftover until it goes.
+ b.restartAgent(t)
+ b.wake(t)
+ if u := b.tick(t); u.Owner != nil || u.MemBytes == nil {
+ t.Fatalf("reading with a unit from before the restart = owner %q mem %v, want a reading, untagged", owner(u), u.MemBytes)
+ }
+ // The new generation's unit starts, then the old one goes. (Created
+ // first because a temp filesystem may hand a removed dir's inode to the
+ // next one; cgroupfs never reuses a cgroup id.)
+ b.unit(t, instancectl.GenUnitName(nestedHost, 1), 100_000, 2<<20)
+ if err := os.RemoveAll(filepath.Join(b.root, instancectl.SliceName(nestedHost), instancectl.UnitName(instancectl.RoleRun, nestedHost))); err != nil {
+ t.Fatal(err)
+ }
+ // Its first reading's CPU delta starts from the leftover's counter
+ // (CarryTags); the next is wholly this agent's units.
+ if u := b.tick(t); u.Owner != nil {
+ t.Fatalf("first reading after the leftover went = owner %q, want none", owner(u))
+ }
+ if u := b.tick(t); owner(u) != "bdn/shop" {
+ t.Fatalf("reading of a unit this agent started = owner %q, want bdn/shop", owner(u))
+ }
+}
+
+// TestNestedSnapshotUnreadable: when the nested layout cannot be listed at
+// agent start, nothing in it is known to be this agent's.
+func TestNestedSnapshotUnreadable(t *testing.T) {
+ if st := snapshotNestedUnits(filepath.Join(t.TempDir(), "absent")); st.unswept || len(st.ids) != 0 {
+ t.Fatalf("a box with no nested layout = %+v, want clean", st)
+ }
+ root := t.TempDir()
+ if err := os.MkdirAll(filepath.Join(root, "carlos-instances-x.slice"), 0o755); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.Chmod(root, 0o300); err != nil {
+ t.Fatal(err)
+ }
+ defer os.Chmod(root, 0o755) //nolint:errcheck
+ if _, err := os.ReadDir(root); err == nil {
+ t.Skip("listable without read permission (running as root?)")
+ }
+ if st := snapshotNestedUnits(root); !st.unswept {
+ t.Fatal("an unlistable nested layout counted as swept")
+ }
+ b := &nestedBox{root: t.TempDir()}
+ b.unit(t, instancectl.UnitName(instancectl.RoleRun, nestedHost), 1, 1)
+ got := nestedUnitReadings(b.root, []string{nestedHost}, nestedStart{unswept: true})
+ if r, ok := got[cgroup.ExecName(nestedHost)]; !ok || !r.leftover {
+ t.Fatalf("a reading after an unswept start = %+v, want a leftover", got)
+ }
+ if r := nestedUnitReadings(b.root, []string{nestedHost}, nestedStart{})[cgroup.ExecName(nestedHost)]; r.leftover {
+ t.Fatal("a reading after a clean start is a leftover")
+ }
+}
+
+// TestSumUnitRaw: a field is summed only when every unit has it.
+func TestSumUnitRaw(t *testing.T) {
+ one, two := int64(1), int64(2)
+ s := sumUnitRaw([]unitRaw{{cpuUsec: &one, memBytes: &one}, {cpuUsec: &two}})
+ if s.cpuUsec == nil || *s.cpuUsec != 3 || s.memBytes != nil || s.memPeakBytes != nil {
+ t.Fatalf("sum = %+v", s)
+ }
+ if !sumUnitRaw([]unitRaw{{}, {leftover: true}}).leftover {
+ t.Fatal("a leftover part did not make the sum a leftover")
+ }
+}
diff --git a/internal/host/metrics_probes.go b/internal/host/metrics_probes.go
index 6ebe91951..cf7ad3c70 100644
--- a/internal/host/metrics_probes.go
+++ b/internal/host/metrics_probes.go
@@ -205,6 +205,9 @@ type unitRaw struct {
memPeakBytes *int64
readBytes *int64
writeBytes *int64
+ // leftover marks a nested host's reading that includes a unit this
+ // agent did not start (nestedUnitReadings): never vouched.
+ leftover bool
}
// readUnitRaw reads a unit's resource usage from the cgroup v2 files in