-
-
Notifications
You must be signed in to change notification settings - Fork 3.8k
/
cpu_linux.go
156 lines (128 loc) · 2.49 KB
/
cpu_linux.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
148
149
150
151
152
153
154
155
156
package internal
import (
"errors"
"fmt"
"strings"
"sync"
"time"
"github.com/zeromicro/go-zero/core/iox"
"github.com/zeromicro/go-zero/core/logx"
)
const (
cpuTicks = 100
cpuFields = 8
)
var (
preSystem uint64
preTotal uint64
quota float64
cores uint64
initOnce sync.Once
)
// if /proc not present, ignore the cpu calculation, like wsl linux
func initialize() {
cpus, err := cpuSets()
if err != nil {
logx.Error(err)
return
}
cores = uint64(len(cpus))
quota = float64(len(cpus))
cq, err := cpuQuota()
if err == nil {
if cq != -1 {
period, err := cpuPeriod()
if err != nil {
logx.Error(err)
return
}
limit := float64(cq) / float64(period)
if limit < quota {
quota = limit
}
}
}
preSystem, err = systemCpuUsage()
if err != nil {
logx.Error(err)
return
}
preTotal, err = totalCpuUsage()
if err != nil {
logx.Error(err)
return
}
}
// RefreshCpu refreshes cpu usage and returns.
func RefreshCpu() uint64 {
initOnce.Do(initialize)
total, err := totalCpuUsage()
if err != nil {
return 0
}
system, err := systemCpuUsage()
if err != nil {
return 0
}
var usage uint64
cpuDelta := total - preTotal
systemDelta := system - preSystem
if cpuDelta > 0 && systemDelta > 0 {
usage = uint64(float64(cpuDelta*cores*1e3) / (float64(systemDelta) * quota))
}
preSystem = system
preTotal = total
return usage
}
func cpuQuota() (int64, error) {
cg, err := currentCgroup()
if err != nil {
return 0, err
}
return cg.cpuQuotaUs()
}
func cpuPeriod() (uint64, error) {
cg, err := currentCgroup()
if err != nil {
return 0, err
}
return cg.cpuPeriodUs()
}
func cpuSets() ([]uint64, error) {
cg, err := currentCgroup()
if err != nil {
return nil, err
}
return cg.cpus()
}
func systemCpuUsage() (uint64, error) {
lines, err := iox.ReadTextLines("/proc/stat", iox.WithoutBlank())
if err != nil {
return 0, err
}
for _, line := range lines {
fields := strings.Fields(line)
if fields[0] == "cpu" {
if len(fields) < cpuFields {
return 0, fmt.Errorf("bad format of cpu stats")
}
var totalClockTicks uint64
for _, i := range fields[1:cpuFields] {
v, err := parseUint(i)
if err != nil {
return 0, err
}
totalClockTicks += v
}
return (totalClockTicks * uint64(time.Second)) / cpuTicks, nil
}
}
return 0, errors.New("bad stats format")
}
func totalCpuUsage() (usage uint64, err error) {
var cg cgroup
if cg, err = currentCgroup(); err != nil {
return
}
return cg.usageAllCpus()
}