-
Notifications
You must be signed in to change notification settings - Fork 8
/
cgroupv1.go
133 lines (116 loc) · 2.54 KB
/
cgroupv1.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
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
//go:build linux
// +build linux
package autopprof
import (
"bufio"
"os"
"path"
"strconv"
"time"
"github.com/containerd/cgroups"
v1 "github.com/containerd/cgroups/stats/v1"
)
const (
cgroupV1MountPoint = "/sys/fs/cgroup"
cgroupV1CPUSubsystem = "cpu"
cgroupV1CPUQuotaFile = "cpu.cfs_quota_us"
cgroupV1CPUPeriodFile = "cpu.cfs_period_us"
cgroupV1UsageUnit = time.Nanosecond
)
type cgroupV1 struct {
staticPath string
mountPoint string
cpuSubsystem string
cpuQuota float64
q cpuUsageSnapshotQueuer
}
func newCgroupsV1() *cgroupV1 {
q := newCPUUsageSnapshotQueue(
cpuUsageSnapshotQueueSize,
)
return &cgroupV1{
staticPath: "/",
mountPoint: cgroupV1MountPoint,
cpuSubsystem: cgroupV1CPUSubsystem,
q: q,
}
}
func (c *cgroupV1) setCPUQuota() error {
quota, err := c.parseCPU(cgroupV1CPUQuotaFile)
if err != nil {
return err
}
period, err := c.parseCPU(cgroupV1CPUPeriodFile)
if err != nil {
return err
}
c.cpuQuota = float64(quota) / float64(period)
return nil
}
func (c *cgroupV1) snapshotCPUUsage(usage uint64) {
c.q.enqueue(&cpuUsageSnapshot{
usage: usage,
timestamp: time.Now(),
})
}
func (c *cgroupV1) stat() (*v1.Metrics, error) {
var (
path = cgroups.StaticPath(c.staticPath)
cg, err = cgroups.Load(cgroups.V1, path)
)
if err != nil {
return nil, err
}
stat, err := cg.Stat()
if err != nil {
return nil, err
}
return stat, nil
}
func (c *cgroupV1) cpuUsage() (float64, error) {
stat, err := c.stat()
if err != nil {
return 0, err
}
c.snapshotCPUUsage(stat.CPU.Usage.Total) // In nanoseconds.
// Calculate the usage only if there are enough snapshots.
if !c.q.isFull() {
return 0, nil
}
s1, s2 := c.q.head(), c.q.tail()
delta := time.Duration(s2.usage-s1.usage) * cgroupV1UsageUnit
duration := s2.timestamp.Sub(s1.timestamp)
return (float64(delta) / float64(duration)) / c.cpuQuota, nil
}
func (c *cgroupV1) memUsage() (float64, error) {
stat, err := c.stat()
if err != nil {
return 0, err
}
var (
sm = stat.Memory
usage = sm.Usage.Usage - sm.InactiveFile
limit = sm.HierarchicalMemoryLimit
)
return float64(usage) / float64(limit), nil
}
func (c *cgroupV1) parseCPU(filename string) (int, error) {
f, err := os.Open(
path.Join(c.mountPoint, c.cpuSubsystem, filename),
)
if err != nil {
return 0, err
}
scanner := bufio.NewScanner(f)
if scanner.Scan() {
val, err := strconv.Atoi(scanner.Text())
if err != nil {
return 0, err
}
return val, nil
}
if err := scanner.Err(); err != nil {
return 0, err
}
return 0, ErrV1CPUSubsystemEmpty
}