-
Notifications
You must be signed in to change notification settings - Fork 2
/
cgroup_cpu.go
86 lines (80 loc) · 2.26 KB
/
cgroup_cpu.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
package cgroup
import (
"fmt"
"os"
"path"
"strconv"
"strings"
)
// See https://github.com/opencontainers/runc/tree/main/libcontainer/cgroups for more examples.
type CPUStat struct {
UsageSeconds float64
ThrottledTimeSeconds float64
LimitCores float64
}
func (cg Cgroup) CpuStat() (*CPUStat, error) {
if cg.Version == V1 {
return cg.cpuStatV1()
}
return cg.cpuStatV2()
}
func (cg Cgroup) cpuStatV1() (*CPUStat, error) {
throttling, err := readVariablesFromFile(path.Join(cg.cgRoot, "cpu", cg.subsystems["cpu"], "cpu.stat"))
if err != nil {
return nil, err
}
usageNs, err := readIntFromFile(path.Join(cg.cgRoot, "cpuacct", cg.subsystems["cpuacct"], "cpuacct.usage"))
if err != nil {
return nil, err
}
periodUs, err := readIntFromFile(path.Join(cg.cgRoot, "cpu", cg.subsystems["cpu"], "cpu.cfs_period_us"))
if err != nil {
return nil, err
}
quotaUs, err := readIntFromFile(path.Join(cg.cgRoot, "cpu", cg.subsystems["cpu"], "cpu.cfs_quota_us"))
if err != nil {
return nil, err
}
res := &CPUStat{
UsageSeconds: float64(usageNs) / 1e9,
ThrottledTimeSeconds: float64(throttling["throttled_time"]) / 1e9,
}
if quotaUs > 0 {
res.LimitCores = float64(quotaUs) / float64(periodUs)
}
return res, nil
}
func (cg Cgroup) cpuStatV2() (*CPUStat, error) {
vars, err := readVariablesFromFile(path.Join(cg.cgRoot, cg.subsystems[""], "cpu.stat"))
if err != nil {
return nil, err
}
res := &CPUStat{
UsageSeconds: float64(vars["usage_usec"]) / 1e6,
ThrottledTimeSeconds: float64(vars["throttled_usec"]) / 1e6,
}
payload, err := os.ReadFile(path.Join(cg.cgRoot, cg.subsystems[""], "cpu.max"))
if err != nil {
return nil, err
}
data := strings.TrimSpace(string(payload))
parts := strings.Fields(data)
if len(parts) != 2 {
return nil, fmt.Errorf("invalid cpu.max payload: %s", data)
}
if parts[0] == "max" { //no limit
return res, nil
}
quotaUs, err := strconv.ParseUint(parts[0], 10, 64)
if err != nil {
return nil, fmt.Errorf("invalid quota value in cpu.max: %s", parts[0])
}
periodUs, err := strconv.ParseUint(parts[1], 10, 64)
if err != nil {
return nil, fmt.Errorf("invalid period value in cpu.max: %s", parts[1])
}
if periodUs > 0 {
res.LimitCores = float64(quotaUs) / float64(periodUs)
}
return res, nil
}