/
cpu_posix.go
147 lines (124 loc) · 4.4 KB
/
cpu_posix.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
134
135
136
137
138
139
140
141
142
143
144
145
146
147
//go:build linux || darwin
// +build linux darwin
package checks
import (
"context"
"fmt"
"math"
"time"
"github.com/shirou/gopsutil/v3/cpu"
)
func saturatingSub(a, b float64) float64 {
if a > b {
return a - b
}
return 0
}
func calcuateBusy(t cpu.TimesStat) (float64, float64, float64) {
busy := t.User + t.Nice + t.System + t.Irq + t.Softirq + t.Steal
idle := t.Idle + t.Iowait
total := busy + idle
return busy, idle, total
}
func calculateUsagePercentage(prev, current cpu.TimesStat) float64 {
// This is highly inspired by
// https://github.com/shirou/gopsutil/blob/master/cpu/cpu.go#L107
// and htop
// https://github.com/htop-dev/htop/blob/main/linux/LinuxProcessList.c#L1948-L2006
// and yes - htop is reading /proc/stat as we do
prevBusy, _, prevTotal := calcuateBusy(prev)
currentBusy, _, currentTotal := calcuateBusy(current)
if currentBusy <= prevBusy {
return 0
}
if currentTotal <= prevTotal {
return 100
}
return math.Min(100, math.Max(0, (currentBusy-prevBusy)/(currentTotal-prevTotal)*100))
}
// Run the actual check
// if error != nil the check result will be nil
// ctx can be canceled and runs the timeout
// CheckResult will be serialized after the return and should not change until the next call to Run
func (c *CheckCpu) Run(ctx context.Context) (interface{}, error) {
result := &resultCpu{}
prevTimeStats, err := cpu.TimesWithContext(ctx, true)
if err != nil {
return nil, err
}
if err := c.SleepWithContext(ctx, 1*time.Second); err != nil {
return nil, err
}
timeStats, err := cpu.TimesWithContext(ctx, true)
if err != nil {
return nil, err
}
if len(prevTimeStats) != len(timeStats) {
return nil, fmt.Errorf("number of CPU cores has changed %v != %v", len(prevTimeStats), len(timeStats))
}
// Get CPU usage per core
var cpuPercentages []float64
for i := range prevTimeStats {
cpuPercentage := calculateUsagePercentage(prevTimeStats[i], timeStats[i])
cpuPercentages = append(cpuPercentages, cpuPercentage)
}
result.PercentagePerCore = cpuPercentages
// Get total CPU usage as percentage
var totalCpuPercentage float64
for i := range cpuPercentages {
totalCpuPercentage = totalCpuPercentage + cpuPercentages[i]
}
result.PercentageTotal = totalCpuPercentage / float64(len(cpuPercentages))
// Get CPU timing details per core
var timings []cpuDetails
var totalUser, totalNice, totalSystem, totalIoWait, totalIdle, totalTotal float64
for i := range prevTimeStats {
// Ignore t.Irq + t.Softirq + t.Steal to get 100% over all values we list in the json
prevTotal := prevTimeStats[i].User + prevTimeStats[i].Nice + prevTimeStats[i].System + prevTimeStats[i].Idle + prevTimeStats[i].Iowait
currentTotal := timeStats[i].User + timeStats[i].Nice + timeStats[i].System + timeStats[i].Idle + timeStats[i].Iowait
userDelta := saturatingSub(timeStats[i].User, prevTimeStats[i].User)
niceDelta := saturatingSub(timeStats[i].Nice, prevTimeStats[i].Nice)
systemDelta := saturatingSub(timeStats[i].System, prevTimeStats[i].System)
ioWaitDelta := saturatingSub(timeStats[i].Iowait, prevTimeStats[i].Iowait)
idleDelta := saturatingSub(timeStats[i].Idle, prevTimeStats[i].Idle)
totalDelta := saturatingSub(currentTotal, prevTotal)
if totalDelta == 0 {
timings = append(timings, cpuDetails{})
} else {
// Do not Division by zero (not sure if this could ever happen to be honest but better safe than sorry)
timings = append(timings, cpuDetails{
User: userDelta / totalDelta * 100,
Nice: niceDelta / totalDelta * 100,
System: systemDelta / totalDelta * 100,
Idle: idleDelta / totalDelta * 100,
Iowait: ioWaitDelta / totalDelta * 100,
})
}
totalUser = totalUser + userDelta
totalNice = totalNice + niceDelta
totalSystem = totalSystem + systemDelta
totalIoWait = totalIoWait + ioWaitDelta
totalIdle = totalIdle + idleDelta
totalTotal = totalTotal + totalDelta
}
result.DetailsPerCore = timings
// Get total CPU timing details
result.DetailsTotal = &cpuDetails{
User: totalUser / totalTotal * 100,
Nice: totalNice / totalTotal * 100,
System: totalSystem / totalTotal * 100,
Idle: totalIdle / totalTotal * 100,
Iowait: totalIoWait / totalTotal * 100,
}
return result, nil
}
// Like sleep but can be canceled by context
func (c *CheckCpu) SleepWithContext(ctx context.Context, interval time.Duration) error {
var timer = time.NewTimer(interval)
select {
case <-ctx.Done():
return ctx.Err()
case <-timer.C:
return nil
}
}