From ac8942470872a3966c1adc02354ad1aa277bd81c Mon Sep 17 00:00:00 2001 From: Sathvik Date: Fri, 30 Oct 2026 09:56:57 +0530 Subject: [PATCH 1/3] procstats: support cgroup v2 Read CPU quota/period from cpu.max, shares from cpu.weight, and the memory limit from memory.max when /sys/fs/cgroup is the unified hierarchy. Parse the "0::/path" entry in /proc//cgroup, which was previously dropped, so v2 pods no longer fall back to 1/NumCPU and total system memory. Co-Authored-By: Claude Sonnet 5.5 --- procstats/linux/cgroup.go | 56 +++++++++++++++++++++++++++++++ procstats/linux/cgroup_v2_test.go | 46 +++++++++++++++++++++++++ procstats/linux/io.go | 6 ++++ procstats/linux/memory_linux.go | 20 +++++++++++ procstats/proc_linux.go | 10 ++++-- 5 files changed, 136 insertions(+), 2 deletions(-) create mode 100644 procstats/linux/cgroup_v2_test.go diff --git a/procstats/linux/cgroup.go b/procstats/linux/cgroup.go index 42cc232..c87539c 100644 --- a/procstats/linux/cgroup.go +++ b/procstats/linux/cgroup.go @@ -30,6 +30,18 @@ func (pcg ProcCGroup) Lookup(name string) (cgroup CGroup, ok bool) { return cgroup, ok } +// Unified returns the cgroup v2 (unified hierarchy) entry, which +// /proc//cgroup reports as "0::", and a bool indicating whether or +// not it was found. +func (pcg ProcCGroup) Unified() (cgroup CGroup, ok bool) { + for _, cg := range pcg { + if cg.ID == 0 && cg.Name == "" { + return cg, true + } + } + return CGroup{}, false +} + // ReadProcCGroup takes an int argument representing a PID // and returns a ProcCGroup and error, if any is encountered. func ReadProcCGroup(pid int) (proc ProcCGroup, err error) { @@ -50,6 +62,11 @@ func parseProcCGroup(s string) (proc ProcCGroup) { id, line := split(line, ':') name, path := split(line, ':') + if id == "0" && name == "" { // cgroup v2 unified hierarchy + proc = append(proc, CGroup{ID: 0, Name: "", Path: path}) + return + } + for len(name) != 0 { var next string name, next = split(name, ',') @@ -90,13 +107,52 @@ func ReadCPUShares(cgroup string) (shares int64, err error) { } func readCPUPeriod(cgroup string) time.Duration { + if isCGroupV2() { + _, period := readCPUMax(cgroup) + return period + } return readMicrosecondFile(cgroupPath("cpu", cgroup, "cpu.cfs_period_us")) } func readCPUQuota(cgroup string) time.Duration { + if isCGroupV2() { + quota, _ := readCPUMax(cgroup) + return quota + } return readMicrosecondFile(cgroupPath("cpu", cgroup, "cpu.cfs_quota_us")) } func readCPUShares(cgroup string) int64 { + if isCGroupV2() { + return weightToShares(readIntFile(cgroupPath("", cgroup, "cpu.weight"))) + } return readIntFile(cgroupPath("cpu", cgroup, "cpu.shares")) } + +func readCPUMax(cgroup string) (quota, period time.Duration) { + return parseCPUMax(readFile(cgroupPath("", cgroup, "cpu.max"))) +} + +// parseCPUMax parses the cgroup v2 cpu.max format, " ", where +// quota is "max" when unlimited. An unlimited quota is reported as -1µs to +// match what cgroup v1 reports in cpu.cfs_quota_us. +func parseCPUMax(s string) (quota, period time.Duration) { + q, p := split(strings.TrimSpace(s), ' ') + if q == "max" { + quota = -1 * time.Microsecond + } else { + quota = time.Duration(parseInt(q)) * time.Microsecond + } + period = time.Duration(parseInt(p)) * time.Microsecond + return quota, period +} + +// weightToShares converts a cgroup v2 cpu.weight (1-10000) to the equivalent +// cgroup v1 cpu.shares (2-262144), using the inverse of the conversion runc and +// the kubelet apply when writing cpu.weight. +func weightToShares(weight int64) int64 { + if weight <= 0 { + return 0 + } + return 2 + (weight-1)*262142/9999 +} diff --git a/procstats/linux/cgroup_v2_test.go b/procstats/linux/cgroup_v2_test.go new file mode 100644 index 0000000..a9b6112 --- /dev/null +++ b/procstats/linux/cgroup_v2_test.go @@ -0,0 +1,46 @@ +package linux + +import ( + "reflect" + "testing" + "time" +) + +func TestParseProcCGroupUnified(t *testing.T) { + proc, err := ParseProcCGroup("0::/kubepods.slice/pod1\n") + if err != nil { + t.Fatal(err) + } + if !reflect.DeepEqual(proc, ProcCGroup{{0, "", "/kubepods.slice/pod1"}}) { + t.Error(proc) + } + if cg, ok := proc.Unified(); !ok || cg.Path != "/kubepods.slice/pod1" { + t.Error(cg, ok) + } + if _, ok := proc.Lookup("memory"); ok { + t.Error("v2 entry must not match v1 controller names") + } +} + +func TestParseCPUMax(t *testing.T) { + tests := []struct { + in string + quota, period time.Duration + }{ + {"200000 100000\n", 200 * time.Millisecond, 100 * time.Millisecond}, + {"max 100000\n", -1 * time.Microsecond, 100 * time.Millisecond}, + } + for _, test := range tests { + if q, p := parseCPUMax(test.in); q != test.quota || p != test.period { + t.Errorf("parseCPUMax(%q) = %v, %v", test.in, q, p) + } + } +} + +func TestWeightToShares(t *testing.T) { + for weight, shares := range map[int64]int64{0: 0, 1: 2, 40: 1024, 10000: 262144} { + if got := weightToShares(weight); got != shares { + t.Errorf("weightToShares(%d) = %d, want %d", weight, got, shares) + } + } +} diff --git a/procstats/linux/io.go b/procstats/linux/io.go index 0b69769..9ef0ecf 100644 --- a/procstats/linux/io.go +++ b/procstats/linux/io.go @@ -40,3 +40,9 @@ func procPath(who any, what string) string { func cgroupPath(dir, cgroup, file string) string { return filepath.Join("/sys/fs/cgroup", dir, cgroup, file) } + +// isCGroupV2 reports whether /sys/fs/cgroup is the cgroup v2 unified hierarchy. +func isCGroupV2() bool { + _, err := os.Stat("/sys/fs/cgroup/cgroup.controllers") + return err == nil +} diff --git a/procstats/linux/memory_linux.go b/procstats/linux/memory_linux.go index f5d167f..1a862c5 100644 --- a/procstats/linux/memory_linux.go +++ b/procstats/linux/memory_linux.go @@ -24,6 +24,12 @@ func readCGroupMemoryLimit(pid int) (limit uint64) { } func readProcCGroupMemoryLimit(cgroups ProcCGroup) (limit uint64) { + if isCGroupV2() { + if unified, ok := cgroups.Unified(); ok { + limit = readUnifiedCGroupMemoryLimit(unified) + } + return limit + } if memory, ok := cgroups.Lookup("memory"); ok { limit = readMemoryCGroupMemoryLimit(memory) } @@ -42,6 +48,20 @@ func readMemoryCGroupMemoryLimit(cgroup CGroup) (limit uint64) { return limit } +// readUnifiedCGroupMemoryLimit reads memory.max, which holds "max" when the +// cgroup has no limit. +func readUnifiedCGroupMemoryLimit(cgroup CGroup) (limit uint64) { + limit = unlimitedMemoryLimit + + if b, err := os.ReadFile(filepath.Join("/sys/fs/cgroup", cgroup.Path, "memory.max")); err == nil { + if v, err := strconv.ParseUint(strings.TrimSpace(string(b)), 10, 64); err == nil { + limit = v + } + } + + return limit +} + func readMemoryCGroupMemoryLimitFilePath(cgroupPath string) string { path := "/sys/fs/cgroup/memory" diff --git a/procstats/proc_linux.go b/procstats/proc_linux.go index fbc5abc..be641a0 100644 --- a/procstats/proc_linux.go +++ b/procstats/proc_linux.go @@ -105,8 +105,14 @@ func collectProcInfo(pid int) (info ProcInfo, err error) { selfCGroups, _ := linux.ReadProcCGroup(os.Getpid()) procCGroups, _ := linux.ReadProcCGroup(pid) - selfCPU, _ := selfCGroups.Lookup("cpu,cpuacct") - procCPU, _ := procCGroups.Lookup("cpu,cpuacct") + selfCPU, ok := selfCGroups.Lookup("cpu,cpuacct") + if !ok { // cgroup v2 + selfCPU, _ = selfCGroups.Unified() + } + procCPU, ok := procCGroups.Lookup("cpu,cpuacct") + if !ok { // cgroup v2 + procCPU, _ = procCGroups.Unified() + } var ( cpuPeriod time.Duration From ccf519263c2424504a397d1509e4bb650fe00463 Mon Sep 17 00:00:00 2001 From: Sathvik Date: Fri, 30 Oct 2026 10:22:39 +0530 Subject: [PATCH 2/3] procstats: add cgroup benchmarks and address review feedback Add benchmarks for parsing /proc//cgroup and cpu.max and for reading the live cgroup CPU and memory files. From review: - Check for cgroup v2 once instead of an os.Stat on every read. - Read small cgroup files with a single open/read/close on Linux. - Fall back to sysinfo when no memory cgroup is found, instead of reporting a limit of 0. - Map cpu.weight so the v2 default (100) matches the v1 default shares (1024). - Reject malformed cpu.max and default the period to 100ms when absent. Co-Authored-By: Claude Opus 5.5 --- procstats/linux/cgroup.go | 29 ++++++++++------ procstats/linux/cgroup_bench_test.go | 32 +++++++++++++++++ procstats/linux/cgroup_linux_bench_test.go | 40 ++++++++++++++++++++++ procstats/linux/cgroup_v2_test.go | 21 +++++++++++- procstats/linux/io.go | 8 +++-- procstats/linux/io_linux.go | 21 ++++++++++++ procstats/linux/io_other.go | 7 ++++ procstats/linux/memory_linux.go | 4 ++- 8 files changed, 147 insertions(+), 15 deletions(-) create mode 100644 procstats/linux/cgroup_bench_test.go create mode 100644 procstats/linux/cgroup_linux_bench_test.go create mode 100644 procstats/linux/io_linux.go create mode 100644 procstats/linux/io_other.go diff --git a/procstats/linux/cgroup.go b/procstats/linux/cgroup.go index c87539c..241a8bd 100644 --- a/procstats/linux/cgroup.go +++ b/procstats/linux/cgroup.go @@ -1,6 +1,7 @@ package linux import ( + "fmt" "strings" "time" ) @@ -130,29 +131,37 @@ func readCPUShares(cgroup string) int64 { } func readCPUMax(cgroup string) (quota, period time.Duration) { - return parseCPUMax(readFile(cgroupPath("", cgroup, "cpu.max"))) + return parseCPUMax(readSmallFile(cgroupPath("", cgroup, "cpu.max"))) } -// parseCPUMax parses the cgroup v2 cpu.max format, " ", where -// quota is "max" when unlimited. An unlimited quota is reported as -1µs to -// match what cgroup v1 reports in cpu.cfs_quota_us. +// parseCPUMax parses the cgroup v2 cpu.max format, " []", where +// quota is "max" when unlimited and period defaults to 100ms. An unlimited +// quota is reported as -1µs to match what cgroup v1 reports in +// cpu.cfs_quota_us. func parseCPUMax(s string) (quota, period time.Duration) { - q, p := split(strings.TrimSpace(s), ' ') + q, p, hasPeriod := strings.Cut(strings.TrimSpace(s), " ") + if q == "" || strings.Contains(p, " ") { + check(fmt.Errorf("malformed cpu.max: %q", s)) + } if q == "max" { quota = -1 * time.Microsecond } else { quota = time.Duration(parseInt(q)) * time.Microsecond } - period = time.Duration(parseInt(p)) * time.Microsecond + period = 100 * time.Millisecond + if hasPeriod { + period = time.Duration(parseInt(p)) * time.Microsecond + } return quota, period } -// weightToShares converts a cgroup v2 cpu.weight (1-10000) to the equivalent -// cgroup v1 cpu.shares (2-262144), using the inverse of the conversion runc and -// the kubelet apply when writing cpu.weight. +// weightToShares converts a cgroup v2 cpu.weight (1-10000, default 100) to an +// approximate cgroup v1 cpu.shares (default 1024), so that the default weight +// maps to the default shares. Container runtimes have used different +// conversions over time, so the result is only meaningful relative to 1024. func weightToShares(weight int64) int64 { if weight <= 0 { return 0 } - return 2 + (weight-1)*262142/9999 + return weight * 1024 / 100 } diff --git a/procstats/linux/cgroup_bench_test.go b/procstats/linux/cgroup_bench_test.go new file mode 100644 index 0000000..0e18349 --- /dev/null +++ b/procstats/linux/cgroup_bench_test.go @@ -0,0 +1,32 @@ +package linux + +import "testing" + +const ( + procCGroupV1 = `11:memory:/user.slice +10:pids:/user.slice/user-1000.slice +9:devices:/user.slice +8:net_cls,net_prio:/ +7:blkio:/user.slice +6:hugetlb:/ +5:cpu,cpuacct:/user.slice +4:perf_event:/ +3:freezer:/ +2:cpuset:/ +1:name=systemd:/user.slice/user-1000.slice/session-3925.scope +` + procCGroupV2 = "0::/kubepods.slice/kubepods-burstable.slice/kubepods-burstable-pod1.slice/cri-containerd-abc.scope\n" +) + +func BenchmarkParseProcCGroup(b *testing.B) { + for name, text := range map[string]string{"v1": procCGroupV1, "v2": procCGroupV2} { + b.Run(name, func(b *testing.B) { + b.ReportAllocs() + for i := 0; i < b.N; i++ { + if _, err := ParseProcCGroup(text); err != nil { + b.Fatal(err) + } + } + }) + } +} diff --git a/procstats/linux/cgroup_linux_bench_test.go b/procstats/linux/cgroup_linux_bench_test.go new file mode 100644 index 0000000..a844484 --- /dev/null +++ b/procstats/linux/cgroup_linux_bench_test.go @@ -0,0 +1,40 @@ +//go:build linux + +package linux + +import ( + "os" + "testing" +) + +// These read the live /sys/fs/cgroup files of the machine running the +// benchmark, so only the relative cost between runs is meaningful. + +func BenchmarkReadCPUPeriod(b *testing.B) { + b.ReportAllocs() + for i := 0; i < b.N; i++ { + ReadCPUPeriod("") + } +} + +func BenchmarkReadCPUQuota(b *testing.B) { + b.ReportAllocs() + for i := 0; i < b.N; i++ { + ReadCPUQuota("") + } +} + +func BenchmarkReadCPUShares(b *testing.B) { + b.ReportAllocs() + for i := 0; i < b.N; i++ { + ReadCPUShares("") + } +} + +func BenchmarkReadMemoryLimit(b *testing.B) { + pid := os.Getpid() + b.ReportAllocs() + for i := 0; i < b.N; i++ { + ReadMemoryLimit(pid) + } +} diff --git a/procstats/linux/cgroup_v2_test.go b/procstats/linux/cgroup_v2_test.go index a9b6112..a37b826 100644 --- a/procstats/linux/cgroup_v2_test.go +++ b/procstats/linux/cgroup_v2_test.go @@ -29,6 +29,18 @@ func TestParseCPUMax(t *testing.T) { }{ {"200000 100000\n", 200 * time.Millisecond, 100 * time.Millisecond}, {"max 100000\n", -1 * time.Microsecond, 100 * time.Millisecond}, + {"max", -1 * time.Microsecond, 100 * time.Millisecond}, + {"50000 20000", 50 * time.Millisecond, 20 * time.Millisecond}, + } + for _, in := range []string{"", "abc 100", "100 200 300"} { + func() { + defer func() { + if recover() == nil { + t.Errorf("parseCPUMax(%q) did not fail", in) + } + }() + parseCPUMax(in) + }() } for _, test := range tests { if q, p := parseCPUMax(test.in); q != test.quota || p != test.period { @@ -38,9 +50,16 @@ func TestParseCPUMax(t *testing.T) { } func TestWeightToShares(t *testing.T) { - for weight, shares := range map[int64]int64{0: 0, 1: 2, 40: 1024, 10000: 262144} { + for weight, shares := range map[int64]int64{0: 0, 1: 10, 100: 1024, 10000: 102400} { if got := weightToShares(weight); got != shares { t.Errorf("weightToShares(%d) = %d, want %d", weight, got, shares) } } } + +func BenchmarkParseCPUMax(b *testing.B) { + b.ReportAllocs() + for i := 0; i < b.N; i++ { + parseCPUMax("150000 100000\n") + } +} diff --git a/procstats/linux/io.go b/procstats/linux/io.go index 9ef0ecf..5e4a61b 100644 --- a/procstats/linux/io.go +++ b/procstats/linux/io.go @@ -6,6 +6,7 @@ import ( "path/filepath" "strconv" "strings" + "sync" "time" ) @@ -24,7 +25,7 @@ func readMicrosecondFile(path string) time.Duration { } func readIntFile(path string) int64 { - return parseInt(strings.TrimSpace(readFile(path))) + return parseInt(strings.TrimSpace(readSmallFile(path))) } func parseInt(s string) int64 { @@ -42,7 +43,8 @@ func cgroupPath(dir, cgroup, file string) string { } // isCGroupV2 reports whether /sys/fs/cgroup is the cgroup v2 unified hierarchy. -func isCGroupV2() bool { +// The hierarchy cannot change while the process runs, so it is checked once. +var isCGroupV2 = sync.OnceValue(func() bool { _, err := os.Stat("/sys/fs/cgroup/cgroup.controllers") return err == nil -} +}) diff --git a/procstats/linux/io_linux.go b/procstats/linux/io_linux.go new file mode 100644 index 0000000..9d24698 --- /dev/null +++ b/procstats/linux/io_linux.go @@ -0,0 +1,21 @@ +package linux + +import "golang.org/x/sys/unix" + +// readSmallFile reads a file that fits in a single small read, such as a +// cgroup or proc setting, with fewer syscalls and allocations than +// os.ReadFile. It falls back to readFile on any error or if the file may be +// larger than the buffer. +func readSmallFile(path string) string { + fd, err := unix.Open(path, unix.O_RDONLY|unix.O_CLOEXEC, 0) + if err != nil { + return readFile(path) // reports the error the same way as before + } + var buf [512]byte + n, err := unix.Read(fd, buf[:]) + unix.Close(fd) + if err != nil || n == len(buf) { + return readFile(path) + } + return string(buf[:n]) +} diff --git a/procstats/linux/io_other.go b/procstats/linux/io_other.go new file mode 100644 index 0000000..95214a6 --- /dev/null +++ b/procstats/linux/io_other.go @@ -0,0 +1,7 @@ +//go:build !linux + +package linux + +func readSmallFile(path string) string { + return readFile(path) +} diff --git a/procstats/linux/memory_linux.go b/procstats/linux/memory_linux.go index 1a862c5..91dec2b 100644 --- a/procstats/linux/memory_linux.go +++ b/procstats/linux/memory_linux.go @@ -17,6 +17,7 @@ func readMemoryLimit(pid int) (limit uint64, err error) { } func readCGroupMemoryLimit(pid int) (limit uint64) { + limit = unlimitedMemoryLimit // fall back to sysinfo if the cgroup can't be read if cgroups, err := ReadProcCGroup(pid); err == nil { limit = readProcCGroupMemoryLimit(cgroups) } @@ -24,6 +25,7 @@ func readCGroupMemoryLimit(pid int) (limit uint64) { } func readProcCGroupMemoryLimit(cgroups ProcCGroup) (limit uint64) { + limit = unlimitedMemoryLimit // fall back to sysinfo if no memory cgroup is found if isCGroupV2() { if unified, ok := cgroups.Unified(); ok { limit = readUnifiedCGroupMemoryLimit(unified) @@ -53,7 +55,7 @@ func readMemoryCGroupMemoryLimit(cgroup CGroup) (limit uint64) { func readUnifiedCGroupMemoryLimit(cgroup CGroup) (limit uint64) { limit = unlimitedMemoryLimit - if b, err := os.ReadFile(filepath.Join("/sys/fs/cgroup", cgroup.Path, "memory.max")); err == nil { + if b, err := os.ReadFile(cgroupPath("", cgroup.Path, "memory.max")); err == nil { if v, err := strconv.ParseUint(strings.TrimSpace(string(b)), 10, 64); err == nil { limit = v } From 115e7d2975b4c2ea40e7c688d4bee244f72d0688 Mon Sep 17 00:00:00 2001 From: Sathvik Date: Fri, 30 Oct 2026 10:37:42 +0530 Subject: [PATCH 3/3] procstats: use b.Loop in cgroup benchmarks b.Loop keeps the compiler from eliminating calls whose results are discarded, which matters for the pure parseCPUMax benchmark. Co-Authored-By: Claude Opus 5.5 --- procstats/linux/cgroup_bench_test.go | 2 +- procstats/linux/cgroup_linux_bench_test.go | 8 ++++---- procstats/linux/cgroup_v2_test.go | 2 +- 3 files changed, 6 insertions(+), 6 deletions(-) diff --git a/procstats/linux/cgroup_bench_test.go b/procstats/linux/cgroup_bench_test.go index 0e18349..a2129d2 100644 --- a/procstats/linux/cgroup_bench_test.go +++ b/procstats/linux/cgroup_bench_test.go @@ -22,7 +22,7 @@ func BenchmarkParseProcCGroup(b *testing.B) { for name, text := range map[string]string{"v1": procCGroupV1, "v2": procCGroupV2} { b.Run(name, func(b *testing.B) { b.ReportAllocs() - for i := 0; i < b.N; i++ { + for b.Loop() { if _, err := ParseProcCGroup(text); err != nil { b.Fatal(err) } diff --git a/procstats/linux/cgroup_linux_bench_test.go b/procstats/linux/cgroup_linux_bench_test.go index a844484..c90179d 100644 --- a/procstats/linux/cgroup_linux_bench_test.go +++ b/procstats/linux/cgroup_linux_bench_test.go @@ -12,21 +12,21 @@ import ( func BenchmarkReadCPUPeriod(b *testing.B) { b.ReportAllocs() - for i := 0; i < b.N; i++ { + for b.Loop() { ReadCPUPeriod("") } } func BenchmarkReadCPUQuota(b *testing.B) { b.ReportAllocs() - for i := 0; i < b.N; i++ { + for b.Loop() { ReadCPUQuota("") } } func BenchmarkReadCPUShares(b *testing.B) { b.ReportAllocs() - for i := 0; i < b.N; i++ { + for b.Loop() { ReadCPUShares("") } } @@ -34,7 +34,7 @@ func BenchmarkReadCPUShares(b *testing.B) { func BenchmarkReadMemoryLimit(b *testing.B) { pid := os.Getpid() b.ReportAllocs() - for i := 0; i < b.N; i++ { + for b.Loop() { ReadMemoryLimit(pid) } } diff --git a/procstats/linux/cgroup_v2_test.go b/procstats/linux/cgroup_v2_test.go index a37b826..86aace1 100644 --- a/procstats/linux/cgroup_v2_test.go +++ b/procstats/linux/cgroup_v2_test.go @@ -59,7 +59,7 @@ func TestWeightToShares(t *testing.T) { func BenchmarkParseCPUMax(b *testing.B) { b.ReportAllocs() - for i := 0; i < b.N; i++ { + for b.Loop() { parseCPUMax("150000 100000\n") } }