Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
65 changes: 65 additions & 0 deletions procstats/linux/cgroup.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package linux

import (
"fmt"
"strings"
"time"
)
Expand Down Expand Up @@ -30,6 +31,18 @@ func (pcg ProcCGroup) Lookup(name string) (cgroup CGroup, ok bool) {
return cgroup, ok
}

// Unified returns the cgroup v2 (unified hierarchy) entry, which
// /proc/<pid>/cgroup reports as "0::<path>", 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) {
Expand All @@ -50,6 +63,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, ',')
Expand Down Expand Up @@ -90,13 +108,60 @@ 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(readSmallFile(cgroupPath("", cgroup, "cpu.max")))
}

// parseCPUMax parses the cgroup v2 cpu.max format, "<quota> [<period>]", 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, 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 = 100 * time.Millisecond
if hasPeriod {
period = time.Duration(parseInt(p)) * time.Microsecond
}
return quota, period
}

// 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 weight * 1024 / 100
}
32 changes: 32 additions & 0 deletions procstats/linux/cgroup_bench_test.go
Original file line number Diff line number Diff line change
@@ -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 b.Loop() {
if _, err := ParseProcCGroup(text); err != nil {
b.Fatal(err)
}
}
})
}
}
40 changes: 40 additions & 0 deletions procstats/linux/cgroup_linux_bench_test.go
Original file line number Diff line number Diff line change
@@ -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 b.Loop() {
ReadCPUPeriod("")
}
}

func BenchmarkReadCPUQuota(b *testing.B) {
b.ReportAllocs()
for b.Loop() {
ReadCPUQuota("")
}
}

func BenchmarkReadCPUShares(b *testing.B) {
b.ReportAllocs()
for b.Loop() {
ReadCPUShares("")
}
}

func BenchmarkReadMemoryLimit(b *testing.B) {
pid := os.Getpid()
b.ReportAllocs()
for b.Loop() {
ReadMemoryLimit(pid)
}
}
65 changes: 65 additions & 0 deletions procstats/linux/cgroup_v2_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
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},
{"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 {
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: 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 b.Loop() {
parseCPUMax("150000 100000\n")
}
}
10 changes: 9 additions & 1 deletion procstats/linux/io.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import (
"path/filepath"
"strconv"
"strings"
"sync"
"time"
)

Expand All @@ -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 {
Expand All @@ -40,3 +41,10 @@ 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.
// 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
})
21 changes: 21 additions & 0 deletions procstats/linux/io_linux.go
Original file line number Diff line number Diff line change
@@ -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])
}
7 changes: 7 additions & 0 deletions procstats/linux/io_other.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
//go:build !linux

package linux

func readSmallFile(path string) string {
return readFile(path)
}
22 changes: 22 additions & 0 deletions procstats/linux/memory_linux.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,13 +17,21 @@ 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)
}
return limit
}

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)
}
return limit
}
if memory, ok := cgroups.Lookup("memory"); ok {
limit = readMemoryCGroupMemoryLimit(memory)
}
Expand All @@ -42,6 +50,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(cgroupPath("", 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"

Expand Down
10 changes: 8 additions & 2 deletions procstats/proc_linux.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
Loading