|
| 1 | +/* |
| 2 | + * cgroup.go - Read CPU and memory limits from Linux cgroups v2. |
| 3 | + * |
| 4 | + * Copyright 2026 Google LLC |
| 5 | + * |
| 6 | + * Licensed under the Apache License, Version 2.0 (the "License"); you may not |
| 7 | + * use this file except in compliance with the License. You may obtain a copy of |
| 8 | + * the License at |
| 9 | + * |
| 10 | + * http://www.apache.org/licenses/LICENSE-2.0 |
| 11 | + * |
| 12 | + * Unless required by applicable law or agreed to in writing, software |
| 13 | + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT |
| 14 | + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the |
| 15 | + * License for the specific language governing permissions and limitations under |
| 16 | + * the License. |
| 17 | + */ |
| 18 | + |
| 19 | +// Package cgroup reads CPU and memory resource limits from Linux control |
| 20 | +// groups (cgroup v2). |
| 21 | +// |
| 22 | +// References: |
| 23 | +// - cgroups(7): https://man7.org/linux/man-pages/man7/cgroups.7.html |
| 24 | +// - cgroup v2 (cpu.max, memory.max): https://docs.kernel.org/admin-guide/cgroup-v2.html |
| 25 | +// - /proc/self/cgroup: https://man7.org/linux/man-pages/man7/cgroups.7.html (see "/proc files") |
| 26 | +package cgroup |
| 27 | + |
| 28 | +import ( |
| 29 | + "bufio" |
| 30 | + "errors" |
| 31 | + "fmt" |
| 32 | + "os" |
| 33 | + "path/filepath" |
| 34 | + "strconv" |
| 35 | + "strings" |
| 36 | +) |
| 37 | + |
| 38 | +// Errors. |
| 39 | +var ( |
| 40 | + // ErrNoLimit indicates that no cgroup limit is set. |
| 41 | + ErrNoLimit = errors.New("no cgroup limit set") |
| 42 | + |
| 43 | + // ErrV1Detected indicates that cgroup v1 controllers were found. Only v2 is |
| 44 | + // supported. |
| 45 | + ErrV1Detected = errors.New("cgroup v1 detected; only v2 is supported") |
| 46 | +) |
| 47 | + |
| 48 | +// Cgroup provides access to cgroup v2 resource limits. Create one with |
| 49 | +// New or NewFromRoot. |
| 50 | +type Cgroup struct { |
| 51 | + // cgroupDir is the resolved filesystem path to the cgroup directory |
| 52 | + // (e.g. /sys/fs/cgroup/user.slice/...). |
| 53 | + cgroupDir string |
| 54 | +} |
| 55 | + |
| 56 | +// New returns a Cgroup by reading /proc/self/cgroup on the live system. |
| 57 | +func New() (Cgroup, error) { |
| 58 | + return NewFromRoot("/") |
| 59 | +} |
| 60 | + |
| 61 | +// NewFromRoot is like New but resolves all filesystem paths relative to |
| 62 | +// root instead of "/". This is useful for testing with a mock filesystem. |
| 63 | +func NewFromRoot(root string) (Cgroup, error) { |
| 64 | + groupPath, err := parseProcCgroup(filepath.Join(root, "proc/self/cgroup")) |
| 65 | + if err != nil { |
| 66 | + return Cgroup{}, err |
| 67 | + } |
| 68 | + return Cgroup{ |
| 69 | + cgroupDir: filepath.Join(root, "sys/fs/cgroup", groupPath), |
| 70 | + }, nil |
| 71 | +} |
| 72 | + |
| 73 | +// CPUQuota returns the CPU quota as a fractional number of CPUs (e.g. 0.5 |
| 74 | +// means half a core). Returns ErrNoLimit if no CPU limit is configured. |
| 75 | +func (c Cgroup) CPUQuota() (float64, error) { |
| 76 | + data, err := c.readFile("cpu.max") |
| 77 | + if err != nil { |
| 78 | + return 0, err |
| 79 | + } |
| 80 | + return parseCPUMax(data) |
| 81 | +} |
| 82 | + |
| 83 | +// MemoryLimit returns the cgroup memory limit in bytes. Returns ErrNoLimit |
| 84 | +// if no memory limit is configured. |
| 85 | +func (c Cgroup) MemoryLimit() (int64, error) { |
| 86 | + data, err := c.readFile("memory.max") |
| 87 | + if err != nil { |
| 88 | + return 0, err |
| 89 | + } |
| 90 | + return parseMemoryMax(data) |
| 91 | +} |
| 92 | + |
| 93 | +func (c Cgroup) readFile(path string) (string, error) { |
| 94 | + data, err := os.ReadFile(filepath.Join(c.cgroupDir, path)) |
| 95 | + if err != nil { |
| 96 | + if os.IsNotExist(err) { |
| 97 | + return "", ErrNoLimit |
| 98 | + } |
| 99 | + return "", err |
| 100 | + } |
| 101 | + return strings.TrimSpace(string(data)), nil |
| 102 | +} |
| 103 | + |
| 104 | +// parseProcCgroup parses /proc/self/cgroup and returns the cgroup v2 group |
| 105 | +// path. The v2 entry is the line with hierarchy-ID "0" and an empty |
| 106 | +// controller list: "0::<path>". |
| 107 | +// |
| 108 | +// Returns an error if v1 controllers are detected or no v2 entry is found. |
| 109 | +// |
| 110 | +// https://man7.org/linux/man-pages/man7/cgroups.7.html |
| 111 | +func parseProcCgroup(path string) (string, error) { |
| 112 | + f, err := os.Open(path) |
| 113 | + if err != nil { |
| 114 | + return "", err |
| 115 | + } |
| 116 | + defer f.Close() |
| 117 | + |
| 118 | + var v2Path string |
| 119 | + |
| 120 | + scanner := bufio.NewScanner(f) |
| 121 | + for scanner.Scan() { |
| 122 | + parts := strings.SplitN(scanner.Text(), ":", 3) |
| 123 | + if len(parts) != 3 { |
| 124 | + continue |
| 125 | + } |
| 126 | + if parts[0] == "0" && parts[1] == "" { |
| 127 | + v2Path = parts[2] |
| 128 | + } else if parts[1] != "" { |
| 129 | + return "", ErrV1Detected |
| 130 | + } |
| 131 | + } |
| 132 | + if err := scanner.Err(); err != nil { |
| 133 | + return "", err |
| 134 | + } |
| 135 | + if v2Path == "" { |
| 136 | + return "", fmt.Errorf("no cgroup v2 entry found in %s", path) |
| 137 | + } |
| 138 | + return v2Path, nil |
| 139 | +} |
| 140 | + |
| 141 | +func parseCPUMax(content string) (float64, error) { |
| 142 | + fields := strings.Fields(content) |
| 143 | + if len(fields) == 0 || len(fields) > 2 { |
| 144 | + return 0, fmt.Errorf("unexpected cpu.max format: %q", content) |
| 145 | + } |
| 146 | + if fields[0] == "max" { |
| 147 | + return 0, ErrNoLimit |
| 148 | + } |
| 149 | + quota, err := strconv.ParseFloat(fields[0], 64) |
| 150 | + if err != nil { |
| 151 | + return 0, fmt.Errorf("parsing cpu.max quota: %w", err) |
| 152 | + } |
| 153 | + period := 100000.0 |
| 154 | + if len(fields) == 2 { |
| 155 | + period, err = strconv.ParseFloat(fields[1], 64) |
| 156 | + if err != nil { |
| 157 | + return 0, fmt.Errorf("parsing cpu.max period: %w", err) |
| 158 | + } |
| 159 | + if period == 0 { |
| 160 | + return 0, fmt.Errorf("cpu.max period is zero") |
| 161 | + } |
| 162 | + } |
| 163 | + return quota / period, nil |
| 164 | +} |
| 165 | + |
| 166 | +func parseMemoryMax(content string) (int64, error) { |
| 167 | + if content == "max" { |
| 168 | + return 0, ErrNoLimit |
| 169 | + } |
| 170 | + v, err := strconv.ParseInt(content, 10, 64) |
| 171 | + if err != nil { |
| 172 | + return 0, fmt.Errorf("parsing memory.max: %w", err) |
| 173 | + } |
| 174 | + return v, nil |
| 175 | +} |
0 commit comments