Skip to content

Lightweight server monitoring with historical data, docker stats, and alerts.

feat(agent): support opt-in cgroup CPU and memory accounting (#2505)

Haven Madrayef840e0e6d8f
diff --git a/agent/agent.go b/agent/agent.go
index 6e876b577..0ba042a0a 100644
--- a/agent/agent.go
+++ b/agent/agent.go
@@ -27,6 +27,7 @@ type Agent struct {
debug bool // true if LOG_LEVEL is set to debug
zfs bool // true if system has arcstats
memCalc string // Memory calculation formula
+ forceUseCgroup bool // Explicitly use the cgroup mount root for CPU accounting
fsNames []string // List of filesystem device names being monitored
fsStats map[string]*system.FsStats // Keeps track of disk stats for each filesystem
diskPrev map[uint16]map[string]prevDisk // Previous disk I/O counters per cache interval
@@ -79,6 +80,11 @@ func NewAgent(dataDir ...string) (agent *Agent, err error) {
}
agent.memCalc, _ = utils.GetEnv("MEM_CALC")
+
+ if useCgroup, exists := utils.GetEnv("USE_CGROUP"); exists {
+ agent.forceUseCgroup = useCgroup == "true"
+ }
+ agent.initializeCpu()
agent.sensorConfig = agent.newSensorConfig()
// Parse disk usage cache duration (e.g., "15m", "1h") to avoid waking sleeping disks
@@ -106,6 +112,8 @@ func NewAgent(dataDir ...string) (agent *Agent, err error) {
slog.Debug(beszel.Version)
+ agent.warnIfRootCgroup()
+
// initialize docker manager
agent.dockerManager = newDockerManager(agent)
diff --git a/agent/cpu.go b/agent/cpu.go
index ce7fb39f4..f99f8ca40 100644
--- a/agent/cpu.go
+++ b/agent/cpu.go
@@ -30,17 +30,17 @@ type CpuMetrics struct {
Iowait float64
Steal float64
Idle float64
- // fromCgroup is set when Total comes from cgroup accounting (LXC) rather
- // than /proc/stat, so per-core /proc/stat usage would not match it.
+ // fromCgroup is set when Total comes from cgroup accounting rather than
+ // /proc/stat, so per-core /proc/stat usage would not match it.
fromCgroup bool
}
// getCpuMetrics calculates detailed CPU usage metrics using cached previous measurements.
// It returns percentages for total, user, system, iowait, and steal time.
-func getCpuMetrics(cacheTimeMs uint16) (CpuMetrics, error) {
+func getCpuMetrics(cacheTimeMs uint16, forceUseCgroup bool) (CpuMetrics, error) {
// Inside LXC, lxcfs serves /proc/stat with the host cores' counters, not
- // the guest's own usage. Prefer the cgroup's CPU accounting there. (#2332)
- if metrics, ok := containerCpuMetrics(cacheTimeMs); ok {
+ // the guest's own usage. Prefer cgroup accounting there or when requested. (#2332)
+ if metrics, ok := containerCpuMetrics(cacheTimeMs, forceUseCgroup); ok {
metrics.fromCgroup = true
return metrics, nil
}
diff --git a/agent/cpu_linux.go b/agent/cpu_linux.go
index a50d5059b..18bc6acee 100644
--- a/agent/cpu_linux.go
+++ b/agent/cpu_linux.go
@@ -3,6 +3,7 @@
package agent
import (
+ "log/slog"
"os"
"path/filepath"
"runtime"
@@ -23,9 +24,9 @@ import (
// reflects only the guest's processes, so inside LXC we derive CPU% from that
// instead.
//
-// Other runtimes (Docker, Podman, k8s) are deliberately left alone: the agent
-// is normally deployed there to monitor the host, and the host's /proc/stat is
-// exactly what it should report.
+// Other runtimes (Docker, Podman, k8s) use /proc/stat by default: the agent
+// is normally deployed there to monitor the host. BESZEL_AGENT_USE_CGROUP=true
+// explicitly opts into cgroup-root CPU accounting outside LXC.
// File paths and hooks are variables so tests can point them at fixtures.
var (
@@ -65,6 +66,12 @@ func detectLxc() bool {
return false
}
+// useCgroup enables cgroup-root accounting automatically in LXC or
+// explicitly when requested by the agent configuration.
+func useCgroup(forceUse bool) bool {
+ return forceUse || inLxc()
+}
+
// procStatFromLxcfs reports whether mountinfo shows lxcfs mounted on /proc/stat.
func procStatFromLxcfs(mountinfo []byte) bool {
for line := range strings.SplitSeq(string(mountinfo), "\n") {
@@ -91,10 +98,10 @@ type cgroupCpuSample struct {
var lastCgroupCpuSamples = make(map[uint16]cgroupCpuSample)
-// init seeds the LXC CPU baseline so the first reported value is a real
-// delta since startup rather than zero.
-func init() {
- if !inLxc() {
+// initializeCpu seeds the cgroup baseline after Agent configuration is read,
+// so the first reported CPU value is a delta instead of zero.
+func (a *Agent) initializeCpu() {
+ if !useCgroup(a.forceUseCgroup) {
return
}
if s, ok := readContainerCpuSample(); ok {
@@ -103,12 +110,38 @@ func init() {
}
}
-// containerCpuMetrics derives CPU metrics from the guest's own cgroup
-// accounting when running inside LXC. It returns ok=false everywhere else and
-// whenever cgroup accounting is unreadable, so callers keep the /proc/stat
-// path.
-func containerCpuMetrics(cacheTimeMs uint16) (CpuMetrics, bool) {
- if !inLxc() {
+// warnIfRootCgroup logs at startup when USE_CGROUP would read the host's root
+// cgroup (e.g. a container run with --cgroupns=host), whose accounting covers
+// the whole machine rather than the container.
+func (a *Agent) warnIfRootCgroup() {
+ if a.forceUseCgroup && inRootCgroupV2() {
+ slog.Warn("USE_CGROUP is reading the host's root cgroup; use --cgroupns=private to monitor the container")
+ }
+}
+
+// inRootCgroupV2 reports whether the visible cgroup v2 mount is the root
+// cgroup. Every cgroup except the root has a cgroup.type file.
+func inRootCgroupV2() bool {
+ if !utils.InCgroupV2(cpuProcSelfCgroup) {
+ return false
+ }
+ dir := cpuCgroupRoot
+ if mount := utils.CgroupMountPoint(cpuCgroupMountinfo, "cgroup2", ""); mount != "" {
+ dir = mount
+ }
+ if _, err := os.Stat(filepath.Join(dir, "cgroup.controllers")); err != nil {
+ return false // no cgroup v2 mount here
+ }
+ _, err := os.Stat(filepath.Join(dir, "cgroup.type"))
+ return os.IsNotExist(err)
+}
+
+// containerCpuMetrics derives CPU metrics from the cgroup mount root's
+// accounting when running inside LXC or explicitly enabled. It returns
+// ok=false when disabled or whenever cgroup accounting is unreadable, so
+// callers keep the /proc/stat path.
+func containerCpuMetrics(cacheTimeMs uint16, forceUseCgroup bool) (CpuMetrics, bool) {
+ if !useCgroup(forceUseCgroup) {
return CpuMetrics{}, false
}
cur, ok := readContainerCpuSample()
@@ -164,21 +197,24 @@ func readContainerCpuSample() (cgroupCpuSample, bool) {
// in /proc/self/cgroup (its service cgroup, or the ".lxc" leaf when started
// from an attached shell) only covers a subset and must not be descended into.
func readCgroupV2CpuSample() (cgroupCpuSample, bool) {
- if !inCgroupV2() {
+ if !utils.InCgroupV2(cpuProcSelfCgroup) {
return cgroupCpuSample{}, false // no v2 membership; try v1
}
dir := cpuCgroupRoot
- if mount := cgroupMountPoint("cgroup2", ""); mount != "" {
+ if mount := utils.CgroupMountPoint(cpuCgroupMountinfo, "cgroup2", ""); mount != "" {
dir = mount
}
- stat := filepath.Join(dir, "cpu.stat")
- usage, ok := cgroupStatValue(stat, "usage_usec")
+ stat, err := utils.ReadCgroupStat(filepath.Join(dir, "cpu.stat"))
+ if err != nil {
+ return cgroupCpuSample{}, false
+ }
+ usage, ok := stat["usage_usec"]
if !ok {
return cgroupCpuSample{}, false
}
s := cgroupCpuSample{usageUsec: usage, cores: cpuCgroupCores(dir)}
- s.userUsec, _ = cgroupStatValue(stat, "user_usec")
- s.systemUsec, _ = cgroupStatValue(stat, "system_usec")
+ s.userUsec = stat["user_usec"]
+ s.systemUsec = stat["system_usec"]
return s, true
}
@@ -187,7 +223,7 @@ func readCgroupV2CpuSample() (cgroupCpuSample, bool) {
// accounting includes every child cgroup, so it is read directly rather than
// the agent's own sub-cgroup.
func readCgroupV1CpuSample() (cgroupCpuSample, bool) {
- dir := cgroupMountPoint("cgroup", "cpuacct")
+ dir := utils.CgroupMountPoint(cpuCgroupMountinfo, "cgroup", "cpuacct")
if dir == "" {
return cgroupCpuSample{}, false
}
@@ -197,78 +233,13 @@ func readCgroupV1CpuSample() (cgroupCpuSample, bool) {
}
s := cgroupCpuSample{usageUsec: usageNs / 1000, cores: cpuCgroupCores(dir)}
// cpuacct.stat reports user/system in USER_HZ jiffies.
- if v, ok := cgroupStatValue(filepath.Join(dir, "cpuacct.stat"), "user"); ok {
- s.userUsec = v * 1e6 / cpuUserHZ
- }
- if v, ok := cgroupStatValue(filepath.Join(dir, "cpuacct.stat"), "system"); ok {
- s.systemUsec = v * 1e6 / cpuUserHZ
+ if stat, err := utils.ReadCgroupStat(filepath.Join(dir, "cpuacct.stat")); err == nil {
+ s.userUsec = stat["user"] * 1e6 / cpuUserHZ
+ s.systemUsec = stat["system"] * 1e6 / cpuUserHZ
}
return s, true
}
-// inCgroupV2 reports whether /proc/self/cgroup lists the v2 unified hierarchy
-// (a "0::<path>" entry).
-func inCgroupV2() bool {
- data, err := os.ReadFile(cpuProcSelfCgroup)
- if err != nil {
- return false
- }
- for line := range strings.SplitSeq(string(data), "\n") {
- if strings.HasPrefix(line, "0::") {
- return true
- }
- }
- return false
-}
-
-// cgroupMountPoint returns the mount point of a cgroup hierarchy from
-// /proc/self/mountinfo: the cgroup2 mount for v2, or the cgroup mount whose
-// super options list the wanted v1 controller.
-func cgroupMountPoint(fstype, v1ctrl string) string {
- data, err := os.ReadFile(cpuCgroupMountinfo)
- if err != nil {
- return ""
- }
- for _, line := range strings.Split(string(data), "\n") {
- left, right, found := strings.Cut(line, " - ")
- if !found {
- continue
- }
- post := strings.Fields(right)
- if len(post) == 0 || post[0] != fstype {
- continue
- }
- if v1ctrl != "" && !mountOptHas(post, v1ctrl) {
- continue
- }
- fields := strings.Fields(left)
- if len(fields) >= 5 {
- return unescapeMountPoint(fields[4])
- }
- }
- return ""
-}
-
-// mountOptHas reports whether the comma-separated super options (field 3 after
-// the " - " separator) contain opt.
-func mountOptHas(post []string, opt string) bool {
- if len(post) < 3 {
- return false
- }
- for _, o := range strings.Split(post[2], ",") {
- if o == opt {
- return true
- }
- }
- return false
-}
-
-// unescapeMountPoint decodes octal escapes (e.g. \040 for space) used in
-// mountinfo paths.
-func unescapeMountPoint(s string) string {
- return strings.NewReplacer(`\040`, " ", `\011`, "\t", `\012`, "\n", `\134`, `\`).Replace(s)
-}
-
// cpuCgroupCores returns how many CPU cores the cgroup at dir may use: the
// smallest of the process affinity mask, the cgroup cpuset, and the CPU quota.
func cpuCgroupCores(dir string) float64 {
@@ -335,38 +306,10 @@ func cpuQuotaCores(dir string) (float64, bool) {
}
}
}
- if quota, ok := readCgroupInt(filepath.Join(dir, "cpu.cfs_quota_us")); ok && quota > 0 {
- if period, ok := readCgroupInt(filepath.Join(dir, "cpu.cfs_period_us")); ok && period > 0 {
+ if quota, ok := utils.ReadIntFile(filepath.Join(dir, "cpu.cfs_quota_us")); ok && quota > 0 {
+ if period, ok := utils.ReadIntFile(filepath.Join(dir, "cpu.cfs_period_us")); ok && period > 0 {
return float64(quota) / float64(period), true
}
}
return 0, false
}
-
-// cgroupStatValue returns the value of key in a cgroup "key value" stat file.
-func cgroupStatValue(path, key string) (uint64, bool) {
- data, err := os.ReadFile(path)
- if err != nil {
- return 0, false
- }
- for line := range strings.SplitSeq(string(data), "\n") {
- name, value, found := strings.Cut(line, " ")
- if !found || name != key {
- continue
- }
- v, err := strconv.ParseUint(strings.TrimSpace(value), 10, 64)
- return v, err == nil
- }
- return 0, false
-}
-
-// readCgroupInt reads a file containing a single signed integer
-// (cpu.cfs_quota_us is -1 when no quota is set).
-func readCgroupInt(path string) (int64, bool) {
- data, err := os.ReadFile(path)
- if err != nil {
- return 0, false
- }
- v, err := strconv.ParseInt(strings.TrimSpace(string(data)), 10, 64)
- return v, err == nil
-}
diff --git a/agent/cpu_linux_test.go b/agent/cpu_linux_test.go
index 337ad76b1..3d03650f6 100644
--- a/agent/cpu_linux_test.go
+++ b/agent/cpu_linux_test.go
@@ -40,6 +40,8 @@ func swapCpuContainerSeams(t *testing.T) {
inLxc = sync.OnceValue(detectLxc)
lastCgroupCpuSamples = make(map[uint16]cgroupCpuSample)
os.Unsetenv("container")
+ t.Setenv("BESZEL_AGENT_USE_CGROUP", "")
+ t.Setenv("USE_CGROUP", "")
tmp := t.TempDir()
cpuCgroupRoot = filepath.Join(tmp, "cgroup")
@@ -184,7 +186,7 @@ func TestContainerCpuMetricsMath(t *testing.T) {
writeCpuFixture(t, filepath.Join(cpuCgroupRoot, "cpu.stat"),
"usage_usec 1000000\nuser_usec 600000\nsystem_usec 400000\n")
- m, ok := containerCpuMetrics(60000)
+ m, ok := containerCpuMetrics(60000, false)
require.True(t, ok)
assert.Zero(t, m.Total) // first call only seeds the baseline
@@ -192,7 +194,7 @@ func TestContainerCpuMetricsMath(t *testing.T) {
advance(time.Second)
writeCpuFixture(t, filepath.Join(cpuCgroupRoot, "cpu.stat"),
"usage_usec 3000000\nuser_usec 1600000\nsystem_usec 900000\n")
- m, ok = containerCpuMetrics(60000)
+ m, ok = containerCpuMetrics(60000, false)
require.True(t, ok)
assert.InDelta(t, 50, m.Total, 0.01)
assert.InDelta(t, 25, m.User, 0.01)
@@ -213,10 +215,10 @@ func TestContainerCpuMetricsHonorsQuota(t *testing.T) {
advance := fakeNow(t)
writeCpuFixture(t, filepath.Join(cpuCgroupRoot, "cpu.stat"), "usage_usec 1000000\n")
- containerCpuMetrics(60000)
+ containerCpuMetrics(60000, false)
advance(time.Second)
writeCpuFixture(t, filepath.Join(cpuCgroupRoot, "cpu.stat"), "usage_usec 2000000\n")
- m, ok := containerCpuMetrics(60000)
+ m, ok := containerCpuMetrics(60000, false)
require.True(t, ok)
assert.InDelta(t, 50, m.Total, 0.01) // 1 core-second against a 2-core quota
}
@@ -232,22 +234,22 @@ func TestContainerCpuMetricsZeroAndBackwardDelta(t *testing.T) {
advance := fakeNow(t)
// seed the baseline, then do not advance the clock: elapsed <= 0
- containerCpuMetrics(60000)
- m, ok := containerCpuMetrics(60000)
+ containerCpuMetrics(60000, false)
+ m, ok := containerCpuMetrics(60000, false)
require.True(t, ok)
assert.Zero(t, m.Total)
// counter goes backwards (cgroup recreated): report zero and re-baseline
advance(time.Second)
writeCpuFixture(t, filepath.Join(cpuCgroupRoot, "cpu.stat"), "usage_usec 100000\n")
- m, ok = containerCpuMetrics(60000)
+ m, ok = containerCpuMetrics(60000, false)
require.True(t, ok)
assert.Zero(t, m.Total)
// next tick measures from the new baseline, not the stale one
advance(time.Second)
writeCpuFixture(t, filepath.Join(cpuCgroupRoot, "cpu.stat"), "usage_usec 1100000\n")
- m, ok = containerCpuMetrics(60000)
+ m, ok = containerCpuMetrics(60000, false)
require.True(t, ok)
assert.InDelta(t, 25, m.Total, 0.01) // 1e6 usec / (1s * 4 cores)
}
@@ -255,7 +257,7 @@ func TestContainerCpuMetricsZeroAndBackwardDelta(t *testing.T) {
func TestContainerCpuMetricsFallbacks(t *testing.T) {
t.Run("not in lxc", func(t *testing.T) {
swapCpuContainerSeams(t)
- _, ok := containerCpuMetrics(60000)
+ _, ok := containerCpuMetrics(60000, false)
assert.False(t, ok)
})
// Docker agents monitor the host, so cgroup accounting must not kick in
@@ -265,7 +267,7 @@ func TestContainerCpuMetricsFallbacks(t *testing.T) {
writeCpuFixture(t, cpuProcSelfCgroup, "0::/\n")
writeCpuFixture(t, cpuCgroupMountinfo, "")
writeCpuFixture(t, filepath.Join(cpuCgroupRoot, "cpu.stat"), "usage_usec 5000000\n")
- _, ok := containerCpuMetrics(60000)
+ _, ok := containerCpuMetrics(60000, false)
assert.False(t, ok)
})
t.Run("in lxc without cgroup accounting", func(t *testing.T) {
@@ -274,15 +276,99 @@ func TestContainerCpuMetricsFallbacks(t *testing.T) {
writeCpuFixture(t, cpuProcSelfCgroup, "0::/\n")
writeCpuFixture(t, cpuCgroupMountinfo, "")
// cpuCgroupRoot has no cpu.stat
- _, ok := containerCpuMetrics(60000)
+ _, ok := containerCpuMetrics(60000, false)
assert.False(t, ok)
})
}
+func TestContainerCpuMetricsExplicitOptIn(t *testing.T) {
+ swapCpuContainerSeams(t)
+ writeCpuFixture(t, cpuProcSelfCgroup, "0::/system.slice/beszel-agent.service\n")
+ writeCpuFixture(t, cpuCgroupMountinfo, "")
+ writeCpuFixture(t, filepath.Join(cpuCgroupRoot, "cpu.stat"), "usage_usec 1000000\n")
+ cpuNumCPU = func() int { return 4 }
+ advance := fakeNow(t)
+
+ a := &Agent{forceUseCgroup: true}
+ a.initializeCpu()
+ require.False(t, lastCgroupCpuSamples[60000].at.IsZero())
+ advance(time.Second)
+ writeCpuFixture(t, filepath.Join(cpuCgroupRoot, "cpu.stat"), "usage_usec 3000000\n")
+ m, err := getCpuMetrics(60000, a.forceUseCgroup)
+ require.NoError(t, err)
+ assert.InDelta(t, 50, m.Total, 0.01)
+ assert.True(t, m.fromCgroup)
+}
+
+func TestContainerCpuMetricsExplicitOptInUnreadable(t *testing.T) {
+ swapCpuContainerSeams(t)
+ writeCpuFixture(t, cpuProcSelfCgroup, "0::/\n")
+ _, ok := containerCpuMetrics(60000, true)
+ assert.False(t, ok)
+}
+
+func TestInRootCgroupV2(t *testing.T) {
+ swapCpuContainerSeams(t)
+ writeCpuFixture(t, cpuCgroupMountinfo, "")
+
+ // no cgroup v2 membership
+ writeCpuFixture(t, cpuProcSelfCgroup, "4:cpu,cpuacct:/docker/abc\n")
+ writeCpuFixture(t, filepath.Join(cpuCgroupRoot, "cgroup.controllers"), "cpu memory\n")
+ assert.False(t, inRootCgroupV2())
+
+ // --cgroupns=host: the mount is the host root, which has no cgroup.type
+ writeCpuFixture(t, cpuProcSelfCgroup, "0::/system.slice/docker-abc.scope\n")
+ assert.True(t, inRootCgroupV2())
+
+ // --cgroupns=private: the mount is the container's own (non-root) cgroup
+ writeCpuFixture(t, filepath.Join(cpuCgroupRoot, "cgroup.type"), "domain\n")
+ assert.False(t, inRootCgroupV2())
+
+ // no cgroup v2 mount at all
+ require.NoError(t, os.RemoveAll(cpuCgroupRoot))
+ assert.False(t, inRootCgroupV2())
+}
+
+func TestInitializeCpuDetectsLxc(t *testing.T) {
+ swapCpuContainerSeams(t)
+ markLxc(t)
+ writeCpuFixture(t, cpuProcSelfCgroup, "0::/\n")
+ writeCpuFixture(t, cpuCgroupMountinfo, "")
+ writeCpuFixture(t, filepath.Join(cpuCgroupRoot, "cpu.stat"), "usage_usec 1000000\n")
+
+ a := &Agent{}
+ a.initializeCpu()
+ assert.EqualValues(t, 1000000, lastCgroupCpuSamples[60000].usageUsec)
+}
+
+func TestNewAgentInitializesCgroupCpuFromEnv(t *testing.T) {
+ swapCpuContainerSeams(t)
+ t.Setenv("BESZEL_AGENT_USE_CGROUP", "true")
+ writeCpuFixture(t, cpuProcSelfCgroup, "0::/system.slice/beszel-agent.service\n")
+ writeCpuFixture(t, cpuCgroupMountinfo, "")
+ writeCpuFixture(t, filepath.Join(cpuCgroupRoot, "cpu.stat"), "usage_usec 1000000\n")
+ cpuNumCPU = func() int { return 4 }
+ advance := fakeNow(t)
+
+ a, err := NewAgent(t.TempDir())
+ require.NoError(t, err)
+ require.True(t, a.forceUseCgroup)
+ assert.EqualValues(t, 1000000, lastCgroupCpuSamples[60000].usageUsec)
+
+ // Changing the environment later must not change this agent's CPU source.
+ t.Setenv("BESZEL_AGENT_USE_CGROUP", "false")
+ advance(time.Second)
+ writeCpuFixture(t, filepath.Join(cpuCgroupRoot, "cpu.stat"), "usage_usec 3000000\n")
+ m, err := getCpuMetrics(60000, a.forceUseCgroup)
+ require.NoError(t, err)
+ assert.InDelta(t, 50, m.Total, 0.01)
+ assert.True(t, m.fromCgroup)
+}
+
// The host path must keep reporting through gopsutil untouched.
func TestGetCpuMetricsHostFallback(t *testing.T) {
swapCpuContainerSeams(t)
- m, err := getCpuMetrics(60000)
+ m, err := getCpuMetrics(60000, false)
require.NoError(t, err)
assert.False(t, m.fromCgroup)
assert.GreaterOrEqual(t, m.Total, 0.0)
@@ -301,13 +387,13 @@ func TestGetCpuMetricsPrefersCgroup(t *testing.T) {
advance := fakeNow(t)
writeCpuFixture(t, filepath.Join(cpuCgroupRoot, "cpu.stat"), "usage_usec 0\n")
- m, err := getCpuMetrics(60000)
+ m, err := getCpuMetrics(60000, false)
require.NoError(t, err)
assert.Zero(t, m.Total)
advance(time.Second)
writeCpuFixture(t, filepath.Join(cpuCgroupRoot, "cpu.stat"), "usage_usec 2000000\n")
- m, err = getCpuMetrics(60000)
+ m, err = getCpuMetrics(60000, false)
require.NoError(t, err)
assert.InDelta(t, 50, m.Total, 0.01)
assert.True(t, m.fromCgroup) // per-core usage is skipped for this source
diff --git a/agent/cpu_unsupported.go b/agent/cpu_unsupported.go
index 886941f82..24cc50872 100644
--- a/agent/cpu_unsupported.go
+++ b/agent/cpu_unsupported.go
@@ -4,6 +4,10 @@ package agent
// containerCpuMetrics is Linux-only (cgroup accounting). Other platforms keep
// the gopsutil /proc path.
-func containerCpuMetrics(uint16) (CpuMetrics, bool) {
+func containerCpuMetrics(uint16, bool) (CpuMetrics, bool) {
return CpuMetrics{}, false
}
+
+func (a *Agent) initializeCpu() {}
+
+func (a *Agent) warnIfRootCgroup() {}
diff --git a/agent/memory.go b/agent/memory.go
new file mode 100644
index 000000000..4d21b7041
--- /dev/null
+++ b/agent/memory.go
@@ -0,0 +1,55 @@
+package agent
+
+import (
+ "github.com/henrygd/beszel/agent/utils"
+ "github.com/henrygd/beszel/agent/zfs"
+ "github.com/henrygd/beszel/internal/entities/system"
+ "github.com/shirou/gopsutil/v4/mem"
+)
+
+// memoryMetrics holds byte counters. For cgroups, Used excludes file cache,
+// while retaining shared memory/tmpfs. BuffCache is the subtracted file cache.
+type memoryMetrics struct {
+ Total, Used, BuffCache uint64
+}
+
+var memoryVirtualMemory = mem.VirtualMemory
+
+func (a *Agent) updateMemoryStats(stats *system.Stats) {
+ v, err := memoryVirtualMemory()
+ var hostTotal uint64
+ if err == nil {
+ hostTotal = v.Total
+ // Swap retains its existing /proc/meminfo source in both memory paths.
+ stats.Swap = utils.BytesToGigabytes(v.SwapTotal)
+ stats.SwapUsed = utils.BytesToGigabytes(saturatingSub(v.SwapTotal, v.SwapFree))
+ }
+
+ metrics, fromCgroup := containerMemoryMetrics(hostTotal, a.forceUseCgroup)
+ if !fromCgroup {
+ if err != nil {
+ return
+ }
+ used, cacheBuff, _ := calculateHostMemoryUsage(v, a.memCalc == "htop")
+ metrics = memoryMetrics{Total: v.Total, Used: used, BuffCache: cacheBuff}
+ // Host ARC must not be subtracted from container-scoped accounting.
+ if a.zfs {
+ if arcSize, _ := zfs.ARCSize(); arcSize > 0 && arcSize < metrics.Used {
+ metrics.Used -= arcSize
+ stats.MemZfsArc = utils.BytesToGigabytes(arcSize)
+ }
+ }
+ }
+
+ stats.Mem = utils.BytesToGigabytes(metrics.Total)
+ stats.MemUsed = utils.BytesToGigabytes(metrics.Used)
+ stats.MemBuffCache = utils.BytesToGigabytes(metrics.BuffCache)
+ if metrics.Total > 0 {
+ stats.MemPct = utils.TwoDecimals(float64(metrics.Used) / float64(metrics.Total) * 100)
+ }
+ if a.systemDetails.MemoryTotal != metrics.Total {
+ a.updateSystemDetails(func(details *system.Details) {
+ details.MemoryTotal = metrics.Total
+ })
+ }
+}
diff --git a/agent/memory_linux.go b/agent/memory_linux.go
new file mode 100644
index 000000000..3eff76c64
--- /dev/null
+++ b/agent/memory_linux.go
@@ -0,0 +1,86 @@
+//go:build linux
+
+package agent
+
+import (
+ "path/filepath"
+ "strconv"
+
+ "github.com/henrygd/beszel/agent/utils"
+)
+
+// containerMemoryMetrics is only used when USE_CGROUP is explicitly enabled.
+// Unlike /proc/stat, lxcfs already serves a container-scoped /proc/meminfo,
+// so LXC keeps the existing memory path by default.
+func containerMemoryMetrics(hostTotal uint64, forceUseCgroup bool) (memoryMetrics, bool) {
+ if !forceUseCgroup {
+ return memoryMetrics{}, false
+ }
+ if utils.InCgroupV2(cpuProcSelfCgroup) {
+ dir := cpuCgroupRoot
+ if mount := utils.CgroupMountPoint(cpuCgroupMountinfo, "cgroup2", ""); mount != "" {
+ dir = mount
+ }
+ if metrics, ok := readCgroupMemoryMetrics(dir, hostTotal, true); ok {
+ return metrics, true
+ }
+ }
+ if dir := utils.CgroupMountPoint(cpuCgroupMountinfo, "cgroup", "memory"); dir != "" {
+ return readCgroupMemoryMetrics(dir, hostTotal, false)
+ }
+ return memoryMetrics{}, false
+}
+
+// Read the hierarchy mount root to include sibling services and descendants,
+// rather than the agent's own service cgroup. A v1 unlimited limit is a
+// page-aligned LONG_MAX sentinel; the threshold also covers 32-bit kernels.
+func readCgroupMemoryMetrics(dir string, hostTotal uint64, v2 bool) (memoryMetrics, bool) {
+ usageFile, limitFile, cacheKey, shmemKey := "memory.usage_in_bytes", "memory.limit_in_bytes", "total_cache", "total_shmem"
+ if v2 {
+ usageFile, limitFile, cacheKey, shmemKey = "memory.current", "memory.max", "file", "shmem"
+ }
+ usage, ok := utils.ReadUintFile(filepath.Join(dir, usageFile))
+ if !ok {
+ return memoryMetrics{}, false
+ }
+ rawLimit, ok := utils.ReadStringFileOK(filepath.Join(dir, limitFile))
+ if !ok {
+ return memoryMetrics{}, false
+ }
+ var limit uint64
+ if !(v2 && rawLimit == "max") {
+ var err error
+ limit, err = strconv.ParseUint(rawLimit, 10, 64)
+ if err != nil {
+ return memoryMetrics{}, false
+ }
+ if !v2 && (limit >= (uint64(1)<<63)-(1<<20) || limit == 2147479552) {
+ limit = 0 // v1 unlimited sentinel
+ } else if limit == 0 {
+ return memoryMetrics{}, false
+ }
+ }
+ total := limit
+ if hostTotal > 0 && (total == 0 || hostTotal < total) {
+ total = hostTotal
+ }
+ if total == 0 {
+ return memoryMetrics{}, false // unlimited and no usable host total
+ }
+ stat, err := utils.ReadCgroupStat(filepath.Join(dir, "memory.stat"))
+ if err != nil {
+ return memoryMetrics{}, false
+ }
+ cache, ok := stat[cacheKey]
+ if !ok {
+ return memoryMetrics{}, false
+ }
+ shmem, ok := stat[shmemKey]
+ if !ok {
+ return memoryMetrics{}, false
+ }
+ // Both cache (v1) and file (v2) include shmem/tmpfs, which must remain
+ // charged as used memory rather than being classified as file cache.
+ cache = min(saturatingSub(cache, shmem), usage)
+ return memoryMetrics{Total: total, Used: usage - cache, BuffCache: cache}, true
+}
diff --git a/agent/memory_linux_test.go b/agent/memory_linux_test.go
new file mode 100644
index 000000000..586dbcb61
--- /dev/null
+++ b/agent/memory_linux_test.go
@@ -0,0 +1,221 @@
+//go:build testing && linux
+
+package agent
+
+import (
+ "errors"
+ "os"
+ "path/filepath"
+ "strconv"
+ "sync"
+ "testing"
+
+ "github.com/henrygd/beszel/internal/entities/system"
+ "github.com/shirou/gopsutil/v4/mem"
+ "github.com/stretchr/testify/assert"
+ "github.com/stretchr/testify/require"
+)
+
+func setupMemoryCgroup(t *testing.T, v2 bool) string {
+ t.Helper()
+ swapCpuContainerSeams(t)
+ if v2 {
+ writeCpuFixture(t, cpuProcSelfCgroup, "0::/system.slice/agent.service\n")
+ writeCpuFixture(t, cpuCgroupMountinfo, "")
+ return cpuCgroupRoot
+ }
+ dir := filepath.Join(filepath.Dir(cpuCgroupRoot), "memory")
+ writeCpuFixture(t, cpuProcSelfCgroup, "2:memory:/system.slice/agent.service\n")
+ writeCpuFixture(t, cpuCgroupMountinfo,
+ "30 25 0:26 / "+dir+" rw - cgroup cgroup rw,memory\n")
+ return dir
+}
+
+func writeMemoryFixture(t *testing.T, dir string, v2 bool, usage, limit, stat string) {
+ t.Helper()
+ usageName, limitName := "memory.usage_in_bytes", "memory.limit_in_bytes"
+ if v2 {
+ usageName, limitName = "memory.current", "memory.max"
+ }
+ writeCpuFixture(t, filepath.Join(dir, usageName), usage)
+ writeCpuFixture(t, filepath.Join(dir, limitName), limit)
+ writeCpuFixture(t, filepath.Join(dir, "memory.stat"), stat)
+}
+
+func TestContainerMemoryMetrics(t *testing.T) {
+ for _, v2 := range []bool{true, false} {
+ t.Run(strconv.FormatBool(v2), func(t *testing.T) {
+ dir := setupMemoryCgroup(t, v2)
+ key, shmemKey := "total_cache", "total_shmem"
+ if v2 {
+ key, shmemKey = "file", "shmem"
+ }
+ stat := func(cache, shmem string) string {
+ return key + " " + cache + "\n" + shmemKey + " " + shmem + "\n"
+ }
+ for _, tt := range []struct {
+ name, usage, limit, stat string
+ host uint64
+ want memoryMetrics
+ ok bool
+ }{
+ {"file cache excluded", "600", "1000", stat("200", "0"), 2000, memoryMetrics{1000, 400, 200}, true},
+ {"shared memory retained", "600", "1000", stat("200", "50"), 2000, memoryMetrics{1000, 450, 150}, true},
+ {"shared memory larger than cache", "600", "1000", stat("200", "300"), 2000, memoryMetrics{1000, 600, 0}, true},
+ {"zero usage", "0", "1000", stat("0", "0"), 2000, memoryMetrics{1000, 0, 0}, true},
+ {"cache larger than charge", "100", "1000", stat("200", "0"), 2000, memoryMetrics{1000, 0, 100}, true},
+ {"host caps limit", "600", "3000", stat("200", "0"), 2000, memoryMetrics{2000, 400, 200}, true},
+ {"finite without host", "600", "1000", stat("200", "0"), 0, memoryMetrics{1000, 400, 200}, true},
+ {"missing cache key", "600", "1000", shmemKey + " 0\n", 2000, memoryMetrics{}, false},
+ {"missing shared memory key", "600", "1000", key + " 200\n", 2000, memoryMetrics{}, false},
+ {"invalid cache", "600", "1000", stat("-1", "0"), 2000, memoryMetrics{}, false},
+ {"invalid shared memory", "600", "1000", stat("200", "-1"), 2000, memoryMetrics{}, false},
+ {"invalid usage", "bad", "1000", stat("200", "0"), 2000, memoryMetrics{}, false},
+ {"invalid limit", "600", "bad", stat("200", "0"), 2000, memoryMetrics{}, false},
+ {"zero limit", "600", "0", stat("200", "0"), 2000, memoryMetrics{}, false},
+ } {
+ t.Run(tt.name, func(t *testing.T) {
+ writeMemoryFixture(t, dir, v2, tt.usage, tt.limit, tt.stat)
+ metrics, ok := containerMemoryMetrics(tt.host, true)
+ assert.Equal(t, tt.ok, ok)
+ assert.Equal(t, tt.want, metrics)
+ })
+ }
+ limit := "9223372036854771712"
+ if v2 {
+ limit = "max"
+ }
+ writeMemoryFixture(t, dir, v2, "600", limit, stat("200", "0"))
+ writeMemoryFixture(t, filepath.Join(dir, "system.slice/agent.service"), v2, "1", "100", stat("0", "0"))
+ metrics, ok := containerMemoryMetrics(2000, true)
+ require.True(t, ok)
+ assert.Equal(t, memoryMetrics{2000, 400, 200}, metrics)
+ _, ok = containerMemoryMetrics(0, true)
+ assert.False(t, ok)
+ if !v2 {
+ writeMemoryFixture(t, dir, false, "600", "2147479552", stat("200", "0"))
+ metrics, ok = containerMemoryMetrics(2000, true)
+ require.True(t, ok)
+ assert.EqualValues(t, 2000, metrics.Total)
+ }
+ })
+ }
+}
+
+func TestContainerMemoryScopeAndEnablement(t *testing.T) {
+ dir := setupMemoryCgroup(t, true)
+ // A discovered non-default mount must win over the default root.
+ mount := filepath.Join(t.TempDir(), "unified")
+ writeCpuFixture(t, cpuCgroupMountinfo,
+ "30 25 0:26 /guest "+mount+" rw - cgroup2 cgroup2 rw\n")
+ writeMemoryFixture(t, dir, true, "1", "1000", "file 0\nshmem 0\n")
+ writeMemoryFixture(t, mount, true, "600", "1000", "file 200\nshmem 0\n")
+ writeMemoryFixture(t, filepath.Join(mount, "system.slice/agent.service"), true, "10", "100", "file 0\nshmem 0\n")
+ _, ok := containerMemoryMetrics(2000, false)
+ assert.False(t, ok) // Docker/host agents keep the existing path by default.
+ markLxc(t)
+ inLxc = sync.OnceValue(detectLxc) // Simulate a fresh process in LXC.
+ _, ok = containerMemoryMetrics(2000, false)
+ assert.False(t, ok) // lxcfs already serves container-scoped /proc/meminfo.
+ metrics, ok := containerMemoryMetrics(2000, true)
+ require.True(t, ok)
+ assert.Equal(t, memoryMetrics{1000, 400, 200}, metrics)
+ require.NoError(t, os.Remove(filepath.Join(mount, "memory.stat")))
+ _, ok = containerMemoryMetrics(2000, true)
+ assert.False(t, ok)
+}
+
+func TestUpdateMemoryStatsCgroupAndFallback(t *testing.T) {
+ dir := setupMemoryCgroup(t, true)
+ const gib = uint64(1 << 30)
+ writeMemoryFixture(t, dir, true, strconv.FormatUint(6*gib, 10), strconv.FormatUint(10*gib, 10),
+ "file "+strconv.FormatUint(2*gib, 10)+"\nshmem 0\n")
+ original := memoryVirtualMemory
+ t.Cleanup(func() { memoryVirtualMemory = original })
+ memoryVirtualMemory = func() (*mem.VirtualMemoryStat, error) {
+ return &mem.VirtualMemoryStat{Total: 20 * gib, Used: 12 * gib, Free: 4 * gib,
+ Cached: 4 * gib, SwapTotal: 2 * gib, SwapFree: gib}, nil
+ }
+ a := &Agent{forceUseCgroup: true, memCalc: "htop", zfs: true}
+ var stats system.Stats
+ a.updateMemoryStats(&stats)
+ assert.Equal(t, float64(10), stats.Mem)
+ assert.Equal(t, float64(4), stats.MemUsed)
+ assert.Equal(t, float64(2), stats.MemBuffCache)
+ assert.Equal(t, float64(40), stats.MemPct)
+ assert.Zero(t, stats.MemZfsArc)
+ assert.Equal(t, float64(2), stats.Swap)
+ assert.Equal(t, float64(1), stats.SwapUsed)
+ assert.Equal(t, 10*gib, a.systemDetails.MemoryTotal)
+ assert.True(t, a.detailsDirty)
+
+ a.detailsDirty = false
+ a.updateMemoryStats(&system.Stats{})
+ assert.False(t, a.detailsDirty)
+ writeCpuFixture(t, filepath.Join(dir, "memory.max"), strconv.FormatUint(8*gib, 10))
+ a.updateMemoryStats(&system.Stats{})
+ assert.Equal(t, 8*gib, a.systemDetails.MemoryTotal)
+ assert.True(t, a.detailsDirty)
+
+ // A missing required field falls back to the original htop calculation.
+ writeCpuFixture(t, filepath.Join(dir, "memory.stat"), "file 123\n")
+ a.zfs = false
+ stats = system.Stats{}
+ a.updateMemoryStats(&stats)
+ assert.Equal(t, float64(20), stats.Mem)
+ assert.Equal(t, float64(12), stats.MemUsed)
+ assert.Equal(t, float64(4), stats.MemBuffCache)
+ assert.Equal(t, float64(60), stats.MemPct)
+ assert.Equal(t, 20*gib, a.systemDetails.MemoryTotal)
+
+ // Finite cgroup limits still work if /proc/meminfo cannot be read.
+ memoryVirtualMemory = func() (*mem.VirtualMemoryStat, error) { return nil, errors.New("unreadable") }
+ writeCpuFixture(t, filepath.Join(dir, "memory.stat"), "file 0\nshmem 0\n")
+ stats = system.Stats{}
+ a.updateMemoryStats(&stats)
+ assert.Equal(t, float64(8), stats.Mem)
+ assert.Equal(t, float64(6), stats.MemUsed)
+ assert.Equal(t, float64(75), stats.MemPct)
+ assert.Zero(t, stats.Swap)
+}
+
+func TestMemoryDetailsInitiallyUseCgroupLimit(t *testing.T) {
+ dir := setupMemoryCgroup(t, true)
+ writeMemoryFixture(t, dir, true, "600", "1000", "file 200\nshmem 0\n")
+ original := memoryVirtualMemory
+ t.Cleanup(func() { memoryVirtualMemory = original })
+ memoryVirtualMemory = func() (*mem.VirtualMemoryStat, error) {
+ return &mem.VirtualMemoryStat{Total: 2000}, nil
+ }
+ a := &Agent{forceUseCgroup: true}
+ a.refreshSystemDetails()
+ assert.EqualValues(t, 1000, a.systemDetails.MemoryTotal)
+}
+
+// Captured from this container: active file cache made the working-set
+// calculation report ~80 GiB despite only ~17 GiB of anonymous RSS.
+func TestMemoryStatsExcludeActiveFileCache(t *testing.T) {
+ dir := setupMemoryCgroup(t, false)
+ const usage = uint64(135881601024)
+ const cache = uint64(116823166976)
+ const shmem = uint64(77180928)
+ writeMemoryFixture(t, dir, false, strconv.FormatUint(usage, 10), "137438953472",
+ "total_cache 116823166976\ntotal_shmem 77180928\n"+
+ "total_inactive_file 49902608384\ntotal_active_file 67684671488\n")
+ original := memoryVirtualMemory
+ t.Cleanup(func() { memoryVirtualMemory = original })
+ memoryVirtualMemory = func() (*mem.VirtualMemoryStat, error) {
+ return &mem.VirtualMemoryStat{Total: 1580621720 * 1024}, nil
+ }
+ metrics, ok := containerMemoryMetrics(1580621720*1024, true)
+ require.True(t, ok)
+ assert.Equal(t, usage-(cache-shmem), metrics.Used)
+ assert.Equal(t, cache-shmem, metrics.BuffCache)
+ assert.Equal(t, usage, metrics.Used+metrics.BuffCache)
+ var stats system.Stats
+ a := &Agent{forceUseCgroup: true}
+ a.updateMemoryStats(&stats)
+ assert.Equal(t, float64(17.82), stats.MemUsed)
+ assert.Equal(t, float64(108.73), stats.MemBuffCache)
+ assert.Equal(t, float64(13.92), stats.MemPct)
+}
diff --git a/agent/memory_unsupported.go b/agent/memory_unsupported.go
new file mode 100644
index 000000000..21e320d68
--- /dev/null
+++ b/agent/memory_unsupported.go
@@ -0,0 +1,7 @@
+//go:build !linux
+
+package agent
+
+func containerMemoryMetrics(uint64, bool) (memoryMetrics, bool) {
+ return memoryMetrics{}, false
+}
diff --git a/agent/system.go b/agent/system.go
index f567585f9..2aa302770 100644
--- a/agent/system.go
+++ b/agent/system.go
@@ -106,11 +106,16 @@ func (a *Agent) refreshSystemDetails() {
// total memory
a.systemDetails.MemoryTotal = hostInfo.MemTotal
- if a.systemDetails.MemoryTotal == 0 {
- if v, err := mem.VirtualMemory(); err == nil {
+ hostMemoryTotal := hostInfo.MemTotal
+ if v, err := memoryVirtualMemory(); err == nil {
+ hostMemoryTotal = v.Total
+ if a.systemDetails.MemoryTotal == 0 {
a.systemDetails.MemoryTotal = v.Total
}
}
+ if metrics, ok := containerMemoryMetrics(hostMemoryTotal, a.forceUseCgroup); ok {
+ a.systemDetails.MemoryTotal = metrics.Total
+ }
// zfs
if _, err := zfs.ARCSize(); err != nil {
@@ -156,7 +161,7 @@ func (a *Agent) getSystemStats(cacheTimeMs uint16) system.Stats {
}
// cpu metrics
- cpuMetrics, err := getCpuMetrics(cacheTimeMs)
+ cpuMetrics, err := getCpuMetrics(cacheTimeMs, a.forceUseCgroup)
if err == nil {
systemStats.Cpu = utils.TwoDecimals(cpuMetrics.Total)
systemStats.CpuBreakdown = []float64{
@@ -190,34 +195,7 @@ func (a *Agent) getSystemStats(cacheTimeMs uint16) system.Stats {
}
// memory
- if v, err := mem.VirtualMemory(); err == nil {
- used, cacheBuff, swapUsed := calculateHostMemoryUsage(v, a.memCalc == "htop")
- // swap
- systemStats.Swap = utils.BytesToGigabytes(v.SwapTotal)
- systemStats.SwapUsed = utils.BytesToGigabytes(swapUsed)
- v.Used = used
- // if a.memCalc == "legacy" {
- // v.Used = v.Total - v.Free - v.Buffers - v.Cached
- // cacheBuff = v.Total - v.Free - v.Used
- // v.UsedPercent = float64(v.Used) / float64(v.Total) * 100.0
- // }
- // subtract ZFS ARC size from used memory and add as its own category
- if a.zfs {
- if arcSize, _ := zfs.ARCSize(); arcSize > 0 && arcSize < v.Used {
- v.Used = v.Used - arcSize
- systemStats.MemZfsArc = utils.BytesToGigabytes(arcSize)
- }
- }
- if v.Total > 0 {
- v.UsedPercent = float64(v.Used) / float64(v.Total) * 100.0
- } else {
- v.UsedPercent = 0
- }
- systemStats.Mem = utils.BytesToGigabytes(v.Total)
- systemStats.MemBuffCache = utils.BytesToGigabytes(cacheBuff)
- systemStats.MemUsed = utils.BytesToGigabytes(v.Used)
- systemStats.MemPct = utils.TwoDecimals(v.UsedPercent)
- }
+ a.updateMemoryStats(&systemStats)
// disk usage
a.updateDiskUsage(&systemStats)
diff --git a/agent/utils/cgroup_linux.go b/agent/utils/cgroup_linux.go
new file mode 100644
index 000000000..eb3920638
--- /dev/null
+++ b/agent/utils/cgroup_linux.go
@@ -0,0 +1,100 @@
+//go:build linux
+
+package utils
+
+import (
+ "os"
+ "strconv"
+ "strings"
+)
+
+// InCgroupV2 reports whether the given /proc/self/cgroup file lists the
+// unified hierarchy (a "0::<path>" entry).
+func InCgroupV2(path string) bool {
+ data, err := os.ReadFile(path)
+ if err != nil {
+ return false
+ }
+ for line := range strings.SplitSeq(string(data), "\n") {
+ if strings.HasPrefix(line, "0::") {
+ return true
+ }
+ }
+ return false
+}
+
+// CgroupMountPoint finds a hierarchy's mount point in the given mountinfo file.
+// Use fstype "cgroup2" and an empty controller for v2, or "cgroup" and the
+// desired controller for v1. It returns the mount root, not a process's leaf.
+func CgroupMountPoint(path, fstype, controller string) string {
+ data, err := os.ReadFile(path)
+ if err != nil {
+ return ""
+ }
+ for line := range strings.SplitSeq(string(data), "\n") {
+ left, right, found := strings.Cut(line, " - ")
+ if !found {
+ continue
+ }
+ post := strings.Fields(right)
+ if len(post) == 0 || post[0] != fstype {
+ continue
+ }
+ if controller != "" && !mountOptHas(post, controller) {
+ continue
+ }
+ fields := strings.Fields(left)
+ if len(fields) >= 5 {
+ return unescapeMountPoint(fields[4])
+ }
+ }
+ return ""
+}
+
+// mountOptHas checks the comma-separated super options after the separator.
+func mountOptHas(post []string, opt string) bool {
+ if len(post) < 3 {
+ return false
+ }
+ for o := range strings.SplitSeq(post[2], ",") {
+ if o == opt {
+ return true
+ }
+ }
+ return false
+}
+
+func unescapeMountPoint(s string) string {
+ return strings.NewReplacer(`\040`, " ", `\011`, "\t", `\012`, "\n", `\134`, `\`).Replace(s)
+}
+
+// ReadCgroupStat reads all unsigned counters from a cgroup key/value stat file
+// in one read. Malformed entries are omitted; callers must check required keys.
+func ReadCgroupStat(path string) (map[string]uint64, error) {
+ data, err := os.ReadFile(path)
+ if err != nil {
+ return nil, err
+ }
+ values := make(map[string]uint64)
+ for line := range strings.SplitSeq(string(data), "\n") {
+ fields := strings.Fields(line)
+ if len(fields) != 2 {
+ continue
+ }
+ value, err := strconv.ParseUint(fields[1], 10, 64)
+ if err == nil {
+ values[fields[0]] = value
+ }
+ }
+ return values, nil
+}
+
+// ReadIntFile parses a signed decimal integer (e.g. a v1 CPU quota of -1).
+func ReadIntFile(path string) (int64, bool) {
+ raw, ok := ReadStringFileOK(path)
+ if !ok {
+ return 0, false
+ }
+ value, err := strconv.ParseInt(raw, 10, 64)
+ return value, err == nil
+}
diff --git a/agent/utils/cgroup_linux_test.go b/agent/utils/cgroup_linux_test.go
new file mode 100644
index 000000000..22664e233
--- /dev/null
+++ b/agent/utils/cgroup_linux_test.go
@@ -0,0 +1,88 @@
+//go:build linux
+
+package utils
+
+import (
+ "os"
+ "path/filepath"
+ "testing"
+
+ "github.com/stretchr/testify/assert"
+ "github.com/stretchr/testify/require"
+)
+
+func TestInCgroupV2(t *testing.T) {
+ path := filepath.Join(t.TempDir(), "cgroup")
+ assert.False(t, InCgroupV2(path))
+ for _, tt := range []struct {
+ name, contents string
+ want bool
+ }{
+ {"v1", "3:cpu,cpuacct:/system.slice/agent.service\n2:memory:/\n", false},
+ {"v2 service", "0::/system.slice/agent.service\n", true},
+ {"hybrid", "2:memory:/\n0::/\n", true},
+ {"empty", "", false},
+ } {
+ t.Run(tt.name, func(t *testing.T) {
+ require.NoError(t, os.WriteFile(path, []byte(tt.contents), 0o644))
+ assert.Equal(t, tt.want, InCgroupV2(path))
+ })
+ }
+}
+
+func TestCgroupMountPoint(t *testing.T) {
+ path := filepath.Join(t.TempDir(), "mountinfo")
+ assert.Empty(t, CgroupMountPoint(path, "cgroup2", ""))
+ contents := "malformed\n" +
+ "30 25 0:26 / /sys/fs/cgroup/cpu rw - cgroup cgroup rw,cpu,cpuacct\n" +
+ "31 25 0:27 / /sys/fs/cgroup/memory rw - cgroup cgroup rw,memory\n" +
+ `32 25 0:28 /guest /sys/fs/cgroup/unified\040root\134name rw - cgroup2 cgroup2 rw` + "\n"
+ require.NoError(t, os.WriteFile(path, []byte(contents), 0o644))
+ assert.Equal(t, "/sys/fs/cgroup/cpu", CgroupMountPoint(path, "cgroup", "cpuacct"))
+ assert.Equal(t, "/sys/fs/cgroup/memory", CgroupMountPoint(path, "cgroup", "memory"))
+ assert.Equal(t, `/sys/fs/cgroup/unified root\name`, CgroupMountPoint(path, "cgroup2", ""))
+ assert.Empty(t, CgroupMountPoint(path, "cgroup", "mem"))
+ assert.Empty(t, CgroupMountPoint(path, "cgroup", "cpuset"))
+}
+
+func TestReadCgroupStat(t *testing.T) {
+ path := filepath.Join(t.TempDir(), "memory.stat")
+ _, err := ReadCgroupStat(path)
+ require.Error(t, err)
+ contents := "anon 1024\nfile\t2048\ninactive_file 0\n" +
+ "negative -1\noverflow 18446744073709551616\ninvalid abc\nmissing\nextra 1 2\n"
+ require.NoError(t, os.WriteFile(path, []byte(contents), 0o644))
+ stat, err := ReadCgroupStat(path)
+ require.NoError(t, err)
+ assert.Equal(t, map[string]uint64{"anon": 1024, "file": 2048, "inactive_file": 0}, stat)
+ _, ok := stat["inactive_file"]
+ assert.True(t, ok)
+ _, ok = stat["usage_usec"]
+ assert.False(t, ok)
+}
+
+func TestReadIntFile(t *testing.T) {
+ path := filepath.Join(t.TempDir(), "quota")
+ _, ok := ReadIntFile(path)
+ assert.False(t, ok)
+ for _, tt := range []struct {
+ contents string
+ want int64
+ ok bool
+ }{
+ {" -1\n", -1, true},
+ {"100000\n", 100000, true},
+ {"0", 0, true},
+ {"max", 0, false},
+ {"9223372036854775808", 9223372036854775807, false},
+ } {
+ t.Run(tt.contents, func(t *testing.T) {
+ require.NoError(t, os.WriteFile(path, []byte(tt.contents), 0o644))
+ value, ok := ReadIntFile(path)
+ assert.Equal(t, tt.ok, ok)
+ if ok {
+ assert.Equal(t, tt.want, value)
+ }
+ })
+ }
+}