This repository has been archived by the owner on Oct 23, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 183
/
cpu.go
283 lines (241 loc) · 8.14 KB
/
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
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
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
package cpu
import (
"context"
"fmt"
"strings"
"time"
"github.com/shirou/gopsutil/cpu"
"github.com/signalfx/golib/v3/datapoint"
"github.com/signalfx/golib/v3/sfxclient"
"github.com/signalfx/signalfx-agent/pkg/core/config"
"github.com/signalfx/signalfx-agent/pkg/monitors"
"github.com/signalfx/signalfx-agent/pkg/monitors/types"
"github.com/signalfx/signalfx-agent/pkg/utils"
"github.com/sirupsen/logrus"
log "github.com/sirupsen/logrus"
)
const cpuUtilName = "cpu.utilization"
const percoreMetricName = "cpu.utilization_per_core"
var errorUsedDiffLessThanZero = fmt.Errorf("usedDiff < 0")
var errorTotalDiffLessThanZero = fmt.Errorf("totalDiff < 0")
func init() {
monitors.Register(&monitorMetadata, func() interface{} { return &Monitor{} }, &Config{})
}
// Config for this monitor
type Config struct {
config.MonitorConfig `singleInstance:"true" acceptsEndpoints:"false"`
// If `true`, stats will be generated for the system as a whole _as well
// as_ for each individual CPU/core in the system and will be distinguished
// by the `cpu` dimension. If `false`, stats will only be generated for
// the system as a whole that will not include a `cpu` dimension.
ReportPerCPU bool `yaml:"reportPerCPU"`
}
type totalUsed struct {
Total float64
Used float64
}
// Monitor for Utilization
type Monitor struct {
Output types.FilteringOutput
cancel func()
conf *Config
previousPerCore map[string]*totalUsed
previousTotal *totalUsed
logger logrus.FieldLogger
}
func (m *Monitor) generatePerCoreDatapoints() []*datapoint.Datapoint {
totals, err := times(true)
if err != nil {
if err == context.DeadlineExceeded {
m.logger.WithField("debug", err).Debugf("unable to get per core cpu times will try again in the next reporting cycle")
} else {
m.logger.WithField("warning", err).Warningf("unable to get per core cpu times will try again in the next reporting cycle")
}
}
out := make([]*datapoint.Datapoint, 0, len(totals))
// for each core
for i := range totals {
core := totals[i]
// get current times as totalUsed
current := cpuTimeStatTototalUsed(&core)
dps := makeSecondaryDatapoints(&core)
// calculate utilization
if prev, ok := m.previousPerCore[core.CPU]; ok && prev != nil {
utilization, err := getUtilization(prev, current)
if err != nil {
m.logger.WithError(err).Errorf("failed to calculate utilization for cpu core %s", core.CPU)
} else {
dps = append(dps,
datapoint.New(
percoreMetricName,
nil,
datapoint.NewFloatValue(utilization),
datapoint.Gauge,
time.Time{},
))
}
}
for i := range dps {
dps[i].Dimensions = utils.MergeStringMaps(dps[i].Dimensions,
map[string]string{"cpu": strings.ReplaceAll(core.CPU, "cpu", "")},
)
}
// store current as previous value for next time
m.previousPerCore[core.CPU] = current
out = append(out, dps...)
}
return out
}
func (m *Monitor) generateDatapoints() []*datapoint.Datapoint {
total, err := times(false)
if err != nil || len(total) == 0 {
if err == context.DeadlineExceeded {
m.logger.WithField("debug", err).Debugf("unable to get cpu times will try again in the next reporting cycle")
} else {
m.logger.WithError(err).Errorf("unable to get cpu times will try again in the next reporting cycle")
}
return nil
}
// get current times as totalUsed
current := cpuTimeStatTototalUsed(&total[0])
dps := makeSecondaryDatapoints(&total[0])
// calculate utilization
if m.previousTotal != nil {
utilization, err := getUtilization(m.previousTotal, current)
// append errors
if err != nil {
if err == errorTotalDiffLessThanZero || err == errorUsedDiffLessThanZero {
m.logger.WithField("debug", err).Debugf("failed to calculate utilization for cpu")
} else {
m.logger.WithError(err).Errorf("failed to calculate utilization for cpu")
}
return nil
}
// add datapoint to be returned
dps = append(dps, datapoint.New(
cpuUtilName,
map[string]string{},
datapoint.NewFloatValue(utilization),
datapoint.Gauge,
time.Time{},
))
}
if cpuCount, err := cpu.Counts(true); err == nil {
dps = append(dps, sfxclient.Gauge(cpuNumProcessors, nil, int64(cpuCount)))
}
// store current as previous value for next time
m.previousTotal = current
return dps
}
func makeSecondaryDatapoints(stat *cpu.TimesStat) []*datapoint.Datapoint {
return []*datapoint.Datapoint{
sfxclient.CumulativeF(cpuIdle, nil, stat.Idle),
sfxclient.CumulativeF(cpuNice, nil, stat.Nice),
sfxclient.CumulativeF(cpuSoftirq, nil, stat.Softirq),
sfxclient.CumulativeF(cpuInterrupt, nil, stat.Irq),
sfxclient.CumulativeF(cpuSteal, nil, stat.Steal),
sfxclient.CumulativeF(cpuSystem, nil, stat.System),
sfxclient.CumulativeF(cpuUser, nil, stat.User),
sfxclient.CumulativeF(cpuWait, nil, stat.Iowait),
}
}
func getUtilization(prev *totalUsed, current *totalUsed) (utilization float64, err error) {
if prev.Total == 0 {
err = fmt.Errorf("prev.Total == 0 will skip until previous Total is > 0")
return
}
usedDiff := current.Used - prev.Used
totalDiff := current.Total - prev.Total
switch {
case usedDiff < 0.0:
err = errorUsedDiffLessThanZero
case totalDiff < 0.0:
err = errorTotalDiffLessThanZero
case (usedDiff == 0.0 && totalDiff == 0.0) || totalDiff == 0.0:
utilization = 0
default:
// calculate utilization
utilization = usedDiff / totalDiff * 100.0
if utilization < 0.0 {
err = fmt.Errorf("percent %v < 0 total: %v used: %v", utilization, usedDiff, totalDiff)
}
if utilization > 100.0 {
err = fmt.Errorf("percent %v > 100 total: %v used: %v ", utilization, usedDiff, totalDiff)
}
}
return
}
func (m *Monitor) initializeCPUTimes() {
// initialize previous values
var total []cpu.TimesStat
var err error
if total, err = times(false); err != nil {
m.logger.WithField("debug", err).Debugf("unable to initialize cpu times will try again in the next reporting cycle")
}
if len(total) > 0 {
m.previousTotal = cpuTimeStatTototalUsed(&total[0])
}
}
func (m *Monitor) initializePerCoreCPUTimes() {
// initialize per core cpu times
var totals []cpu.TimesStat
var err error
if totals, err = times(true); err != nil {
m.logger.WithField("debug", err).Debugf("unable to initialize per core cpu times will try again in the next reporting cycle")
}
m.previousPerCore = make(map[string]*totalUsed, len(totals))
for i := range totals {
m.previousPerCore[totals[i].CPU] = cpuTimeStatTototalUsed(&totals[i])
}
}
// Configure is the main function of the monitor, it will report host metadata
// on a varied interval
func (m *Monitor) Configure(conf *Config) error {
m.logger = logrus.WithFields(log.Fields{"monitorType": monitorType})
// create contexts for managing the the plugin loop
var ctx context.Context
ctx, m.cancel = context.WithCancel(context.Background())
// save config to monitor for convenience
m.conf = conf
// initialize cpu times and per core cpu times so that we don't have to wait an entire reporting interval to report utilization
m.initializeCPUTimes()
m.initializePerCoreCPUTimes()
hasPerCPUMetric := utils.StringSliceToMap(m.Output.EnabledMetrics())[cpuUtilizationPerCore]
// gather metrics on the specified interval
utils.RunOnInterval(ctx, func() {
dps := m.generateDatapoints()
if hasPerCPUMetric || conf.ReportPerCPU {
// NOTE: If this monitor ever fails to complete in a reporting interval
// maybe run this on a separate go routine
perCoreDPs := m.generatePerCoreDatapoints()
dps = append(dps, perCoreDPs...)
}
m.Output.SendDatapoints(dps...)
}, time.Duration(conf.IntervalSeconds)*time.Second)
return nil
}
// Shutdown stops the metric sync
func (m *Monitor) Shutdown() {
if m.cancel != nil {
m.cancel()
}
}
// cpuTimeStatTototalUsed converts a cpu.TimesStat to a totalUsed with Total and Used values
func cpuTimeStatTototalUsed(t *cpu.TimesStat) *totalUsed {
// add up all times if a value doesn't apply then the struct field
// will be 0 and shouldn't affect anything
// Guest and GuestNice are already included in User and Nice so don't
// double count them.
total := t.User +
t.System +
t.Idle +
t.Nice +
t.Iowait +
t.Irq +
t.Softirq +
t.Steal
return &totalUsed{
Total: total,
Used: total - t.Idle,
}
}