/
sherlock.go
356 lines (293 loc) · 9.34 KB
/
sherlock.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
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
/*
Copyright 2022 Huawei Cloud Computing Technologies Co., Ltd.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package sherlock
import (
"bytes"
"fmt"
"runtime/pprof"
"sync"
"time"
"github.com/openGemini/openGemini/lib/cpu"
"github.com/shirou/gopsutil/v3/mem"
"go.uber.org/zap"
)
type Sherlock struct {
opts *options
// stats
collectCount int
cpuTriggerCount int
memTriggerCount int
grtTriggerCount int
cpuCoolDownTime time.Time
memCoolDownTime time.Time
grtCoolDownTime time.Time
// metrics stats
memStats *MetricCircle
cpuStats *MetricCircle
grtStats *MetricCircle
// collector
collectFn func(cpuCore int, memoryLimit uint64) (int, int, int, error)
stop chan struct{}
wg sync.WaitGroup
}
// New creates a sherlock dumper.
func New(opts ...Option) *Sherlock {
sherlock := &Sherlock{
opts: newOptions(),
collectFn: collectMetrics,
}
for _, opt := range opts {
opt(sherlock.opts)
}
return sherlock
}
// Set sets sherlock's optional after initialing.
func (s *Sherlock) Set(opts ...Option) {
for _, opt := range opts {
opt(s.opts)
}
}
// EnableCPUDump enables the cpu dump.
func (s *Sherlock) EnableCPUDump() {
s.opts.cpuOpts.Enable = true
}
// DisableCPUDump disables the cpu dump.
func (s *Sherlock) DisableCPUDump() {
s.opts.cpuOpts.Enable = false
}
// EnableMemDump enables the mem dump.
func (s *Sherlock) EnableMemDump() {
s.opts.memOpts.Enable = true
}
// DisableMemDump disables the mem dump.
func (s *Sherlock) DisableMemDump() {
s.opts.memOpts.Enable = false
}
// EnableGrtDump enables the goroutine dump.
func (s *Sherlock) EnableGrtDump() {
s.opts.grtOpts.Enable = true
}
// DisableGrtDump disables the goroutine dump.
func (s *Sherlock) DisableGrtDump() {
s.opts.grtOpts.Enable = false
}
// Start starts the dump loop of sherlock.
func (s *Sherlock) Start() {
s.opts.logger.Info("sherlock is starting")
s.stop = make(chan struct{})
s.wg.Add(1)
go s.startDumpLoop()
}
// Stop the dump loop of sherlock.
func (s *Sherlock) Stop() {
close(s.stop)
s.wg.Wait()
}
const minMetricsBeforeDump = 10
func (s *Sherlock) startDumpLoop() {
defer s.wg.Done()
// init previous cool down time
now := time.Now()
s.cpuCoolDownTime = now
s.memCoolDownTime = now
s.grtCoolDownTime = now
// init metrics Circle
s.cpuStats = newMetricCircle(minMetricsBeforeDump)
s.memStats = newMetricCircle(minMetricsBeforeDump)
s.grtStats = newMetricCircle(minMetricsBeforeDump)
// dump loop
ticker := time.NewTicker(s.opts.MonitorInterval)
defer ticker.Stop()
for {
select {
case <-s.stop:
s.opts.logger.Info("[Sherlock] dump loop stopped")
return
case <-ticker.C:
}
cpuCore := cpu.GetCpuNum()
if cpuCore == 0 {
s.opts.logger.Error("[Sherlock] get CPU core failed", zap.Int("core", cpuCore))
return
}
memoryLimit, err := s.getMemoryLimit()
if memoryLimit == 0 || err != nil {
s.opts.logger.Error("[Sherlock] get memory limit failed", zap.Uint64("memory", memoryLimit), zap.Error(err))
return
}
cpuN, memN, gNum, err := s.collectFn(cpuCore, memoryLimit)
if err != nil {
s.opts.logger.Error("[Sherlock] failed to collect metrics usage", zap.Error(err))
continue
}
s.cpuStats.push(cpuN)
s.memStats.push(memN)
s.grtStats.push(gNum)
s.collectCount++
if s.collectCount < minMetricsBeforeDump {
continue
}
if err = s.enableDump(cpuN); err != nil {
s.opts.logger.Info("[Sherlock] unable to dump", zap.Error(err))
continue
}
s.memCheckAndDump(memN)
s.cpuCheckAndDump(cpuN)
s.goroutineCheckAndDump(gNum)
}
}
// mem check start.
func (s *Sherlock) memCheckAndDump(mem int) {
memOpts := s.opts.GetMemOpts()
if !memOpts.Enable {
return
}
if s.memCoolDownTime.After(time.Now()) {
s.opts.logger.Debug("[Sherlock] mem dump is in cooldown")
return
}
if triggered := s.memProfile(mem, memOpts); triggered {
s.memCoolDownTime = time.Now().Add(memOpts.CoolDown)
s.memTriggerCount++
}
}
func (s *Sherlock) memProfile(rss int, c commonOption) bool {
match, _ := matchRule(s.memStats, rss, c.TriggerMin, c.TriggerDiff, c.TriggerAbs)
if !match {
s.opts.logger.Debug("[Sherlock] not match memory dump rule",
zap.Int("config_min", c.TriggerMin), zap.Int("config_diff", c.TriggerDiff), zap.Int("config_abs", c.TriggerAbs),
zap.Int("current", rss), zap.Ints("previous", s.memStats.sequentialData()))
return false
}
s.opts.logger.Info("[Sherlock] dump memory profile",
zap.Int("config_min", c.TriggerMin), zap.Int("config_diff", c.TriggerDiff), zap.Int("config_abs", c.TriggerAbs),
zap.Int("current", rss), zap.Ints("previous", s.memStats.sequentialData()))
var buf bytes.Buffer
// write to binary gz profile
err := pprof.Lookup("heap").WriteTo(&buf, 0) // nolint
if err != nil {
return false
}
s.writeProfileDataToFile(buf, Memory)
return true
}
// mem check end.
// cpu check start.
func (s *Sherlock) cpuCheckAndDump(cpu int) {
cpuOpts := s.opts.GetCPUOpts()
if !cpuOpts.Enable {
return
}
if s.cpuCoolDownTime.After(time.Now()) {
s.opts.logger.Debug("[Sherlock] cpu dump is in cooldown")
return
}
// cpuOpts is a struct, no escape.
if triggered := s.cpuProfile(cpu, cpuOpts); triggered {
s.cpuCoolDownTime = time.Now().Add(cpuOpts.CoolDown)
s.cpuTriggerCount++
}
}
func (s *Sherlock) cpuProfile(curCPUUsage int, c commonOption) bool {
match, _ := matchRule(s.cpuStats, curCPUUsage, c.TriggerMin, c.TriggerDiff, c.TriggerAbs)
if !match {
// let user know why this should not dump
s.opts.logger.Debug("[Sherlock] not match cpu dump rule",
zap.Int("config_min", c.TriggerMin), zap.Int("config_diff", c.TriggerDiff), zap.Int("config_abs", c.TriggerAbs),
zap.Int("current", curCPUUsage), zap.Ints("previous", s.cpuStats.sequentialData()))
return false
}
s.opts.logger.Info("[Sherlock] dump cpu profile",
zap.Int("config_min", c.TriggerMin), zap.Int("config_diff", c.TriggerDiff), zap.Int("config_abs", c.TriggerAbs),
zap.Int("current", curCPUUsage), zap.Ints("previous", s.cpuStats.sequentialData()))
bf, filename, err := createAndGetFileInfo(s.opts.dumpOptions, CPU)
if err != nil {
s.opts.logger.Error("[Sherlock] failed to create cpu profile file", zap.Error(err))
return false
}
defer bf.Close() // nolint
err = pprof.StartCPUProfile(bf)
if err != nil {
s.opts.logger.Error("[Sherlock] failed to profile cpu", zap.Error(err))
return false
}
time.Sleep(defaultCPUSamplingTime)
pprof.StopCPUProfile()
s.opts.logger.Info("[Sherlock] profile write to file successfully", zap.String("type", "cpu"), zap.String("filename", filename))
return true
}
// cpu check end.
// goroutine check start.
func (s *Sherlock) goroutineCheckAndDump(gNum int) {
// get a copy instead of locking it
grtOpts := s.opts.GetGrtOpts()
if !grtOpts.Enable {
return
}
if s.grtCoolDownTime.After(time.Now()) {
s.opts.logger.Debug("[Sherlock] goroutine dump is in cooldown")
return
}
if triggered := s.goroutineProfile(gNum, grtOpts); triggered {
s.grtCoolDownTime = time.Now().Add(grtOpts.CoolDown)
s.grtTriggerCount++
}
}
func (s *Sherlock) goroutineProfile(gNum int, c grtOptions) bool {
match, _ := matchRule(s.grtStats, gNum, c.TriggerMin, c.TriggerDiff, c.TriggerAbs)
if c.GoroutineTriggerMaxNum > 0 && gNum >= c.GoroutineTriggerMaxNum {
//gNum is too big, preventing system crashes
match = false
}
if !match {
// let user know why this should not dump
s.opts.logger.Debug("[Sherlock] not match goroutine dump rule",
zap.Int("config_min", c.TriggerMin), zap.Int("config_diff", c.TriggerDiff), zap.Int("config_abs", c.TriggerAbs),
zap.Int("current", gNum), zap.Ints("previous", s.cpuStats.sequentialData()))
return false
}
s.opts.logger.Info("[Sherlock] dump goroutine profile",
zap.Int("config_min", c.TriggerMin), zap.Int("config_diff", c.TriggerDiff), zap.Int("config_abs", c.TriggerAbs),
zap.Int("current", gNum), zap.Ints("previous", s.cpuStats.sequentialData()))
var buf bytes.Buffer
err := pprof.Lookup("goroutine").WriteTo(&buf, 0) // nolint
if err != nil {
return false
}
s.writeProfileDataToFile(buf, Goroutine)
return true
}
// goroutine check end.
func (s *Sherlock) writeProfileDataToFile(data bytes.Buffer, dumpType configureType) {
filename, err := writeFile(data, dumpType, s.opts.dumpOptions)
if err != nil {
s.opts.logger.Error("[Sherlock] failed to write profile to file", zap.String("filename", filename), zap.Error(err))
return
}
s.opts.logger.Info("[Sherlock] profile write to file successfully", zap.String("type", dumpType.string()), zap.String("filename", filename))
}
func (s *Sherlock) getMemoryLimit() (uint64, error) {
// vm
vm, err := mem.VirtualMemory()
if err != nil {
return 0, err
}
return vm.Total, nil
}
// enableDump disables the trigger dump when the cpu usage is too high.
func (s *Sherlock) enableDump(cpuUsed int) (err error) {
if s.opts.CPUMaxPercent != 0 && cpuUsed >= s.opts.CPUMaxPercent {
return fmt.Errorf("current cpu used percent [%v] is greater than the CPUMaxPercent [%v]", cpuUsed, s.opts.CPUMaxPercent)
}
return nil
}