-
Notifications
You must be signed in to change notification settings - Fork 134
/
holmes.go
887 lines (732 loc) · 22.7 KB
/
holmes.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
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 holmes
import (
"bytes"
"fmt"
"io/ioutil"
"runtime"
"runtime/pprof"
"sync"
"sync/atomic"
"time"
)
// Holmes is a self-aware profile dumper.
type Holmes struct {
opts *options
// stats
collectCount int
gcCycleCount int
threadTriggerCount int
cpuTriggerCount int
memTriggerCount int
grTriggerCount int
gcHeapTriggerCount int
shrinkThreadTriggerCount int
// cooldown
threadCoolDownTime time.Time
cpuCoolDownTime time.Time
memCoolDownTime time.Time
gcHeapCoolDownTime time.Time
grCoolDownTime time.Time
shrinkThrCoolDownTime time.Time
// GC heap triggered, need to dump next time.
gcHeapTriggered bool
// stats ring
memStats ring
cpuStats ring
grNumStats ring
threadStats ring
gcHeapStats ring
// switch
stopped int64
// lock Protect the following
sync.Mutex
// channel for GC sweep finalizer event
gcEventsCh chan struct{}
// profiler reporter channels
rptEventsCh chan rptEvent
}
// New creates a holmes dumper.
func New(opts ...Option) (*Holmes, error) {
holmes := &Holmes{
opts: newOptions(),
stopped: 1, // Initialization should be off
}
for _, opt := range opts {
if err := opt.apply(holmes.opts); err != nil {
return nil, err
}
}
return holmes, nil
}
// EnableThreadDump enables the goroutine dump.
func (h *Holmes) EnableThreadDump() *Holmes {
h.opts.threadOpts.Enable = true
return h
}
// DisableThreadDump disables the goroutine dump.
func (h *Holmes) DisableThreadDump() *Holmes {
h.opts.threadOpts.Enable = false
return h
}
// EnableGoroutineDump enables the goroutine dump.
func (h *Holmes) EnableGoroutineDump() *Holmes {
h.opts.grOpts.Enable = true
return h
}
// DisableGoroutineDump disables the goroutine dump.
func (h *Holmes) DisableGoroutineDump() *Holmes {
h.opts.grOpts.Enable = false
return h
}
// EnableCPUDump enables the CPU dump.
func (h *Holmes) EnableCPUDump() *Holmes {
h.opts.cpuOpts.Enable = true
return h
}
// DisableCPUDump disables the CPU dump.
func (h *Holmes) DisableCPUDump() *Holmes {
h.opts.cpuOpts.Enable = false
return h
}
// EnableMemDump enables the mem dump.
func (h *Holmes) EnableMemDump() *Holmes {
h.opts.memOpts.Enable = true
return h
}
// DisableMemDump disables the mem dump.
func (h *Holmes) DisableMemDump() *Holmes {
h.opts.memOpts.Enable = false
return h
}
// EnableGCHeapDump enables the GC heap dump.
func (h *Holmes) EnableGCHeapDump() *Holmes {
h.opts.gCHeapOpts.Enable = true
return h
}
// DisableGCHeapDump disables the gc heap dump.
func (h *Holmes) DisableGCHeapDump() *Holmes {
h.opts.gCHeapOpts.Enable = false
return h
}
// EnableShrinkThread enables shrink thread
func (h *Holmes) EnableShrinkThread() *Holmes {
h.opts.ShrinkThrOptions.Enable = true
return h
}
// DisableShrinkThread disables shrink thread
func (h *Holmes) DisableShrinkThread() *Holmes {
h.opts.ShrinkThrOptions.Enable = false
return h
}
func finalizerCallback(gc *gcHeapFinalizer) {
defer func() {
if r := recover(); r != nil {
gc.h.Errorf("Panic in finalizer callback: %v", r)
}
}()
// disable or stop gc clean up normally
if atomic.LoadInt64(&gc.h.stopped) == 1 {
return
}
// register the finalizer again
runtime.SetFinalizer(gc, finalizerCallback)
// read channel should be atomic.
ch := gc.h.gcEventsCh
if ch == nil {
return
}
// Notice: here may be a litte race, will panic when ch is closed now.
// we just leave it since it is very small and there is a recover.
select {
case ch <- struct{}{}:
default:
gc.h.Errorf("can not send event to finalizer channel immediately, may be analyzer blocked?")
}
}
// it won't fit into tiny span since this struct contains point.
type gcHeapFinalizer struct {
h *Holmes
}
func (h *Holmes) startGCCycleLoop(ch chan struct{}) {
h.gcHeapStats = newRing(minCollectCyclesBeforeDumpStart)
gc := &gcHeapFinalizer{
h,
}
runtime.SetFinalizer(gc, finalizerCallback)
go gc.h.gcHeapCheckLoop(ch)
}
// Start starts the dump loop of holmes.
func (h *Holmes) Start() {
h.Lock()
defer h.Unlock()
if !atomic.CompareAndSwapInt64(&h.stopped, 1, 0) {
//nolint
h.Errorf("Holmes has started, please don't start it again.")
return
}
gcEventsCh := make(chan struct{}, 1)
rptCh := make(chan rptEvent, 32)
h.gcEventsCh = gcEventsCh
h.rptEventsCh = rptCh
h.initEnvironment()
go h.startDumpLoop()
go h.startReporter(rptCh)
h.startGCCycleLoop(gcEventsCh)
}
// Stop the dump loop.
func (h *Holmes) Stop() {
h.Lock()
defer h.Unlock()
if !atomic.CompareAndSwapInt64(&h.stopped, 0, 1) {
//nolint
fmt.Println("Holmes has stop, please don't stop it again.")
return
}
if gcEventsCh := h.gcEventsCh; gcEventsCh != nil {
h.gcEventsCh = nil
close(gcEventsCh)
}
if rptEventsCh := h.rptEventsCh; rptEventsCh != nil {
h.rptEventsCh = nil
close(rptEventsCh)
}
}
func (h *Holmes) startDumpLoop() {
// init previous cool down time
now := time.Now()
h.cpuCoolDownTime = now
h.memCoolDownTime = now
h.grCoolDownTime = now
// init stats ring
h.cpuStats = newRing(minCollectCyclesBeforeDumpStart)
h.memStats = newRing(minCollectCyclesBeforeDumpStart)
h.grNumStats = newRing(minCollectCyclesBeforeDumpStart)
h.threadStats = newRing(minCollectCyclesBeforeDumpStart)
// dump loop
ticker := time.NewTicker(h.opts.CollectInterval)
defer ticker.Stop()
for {
select {
case <-h.opts.intervalResetting:
// wait for go version update to 1.15
// can use Reset API directly here. pkg.go.dev/time#Ticker.Reset
// we can't use the `for-range` here, because the range loop
// caches the variable to be lopped and then it can't be overwritten
itv := h.opts.CollectInterval
h.Infof("[Holmes] collect interval is resetting to [%v]\n", itv) //nolint:forbidigo
ticker = time.NewTicker(itv)
default:
// bug fix: https://github.com/mosn/holmes/issues/63
// make sure that the message inside intervalResetting channel
// would be consumed before ticker.C.
<-ticker.C
if atomic.LoadInt64(&h.stopped) == 1 {
h.Infof("[Holmes] dump loop stopped") //nolint:forbidigo
return
}
cpuCore, err := h.getCPUCore()
if cpuCore == 0 || err != nil {
h.Errorf("[Holmes] get CPU core failed, CPU core: %v, error: %v", cpuCore, err)
return
}
memoryLimit, err := h.getMemoryLimit()
if memoryLimit == 0 || err != nil {
h.Errorf("[Holmes] get memory limit failed, memory limit: %v, error: %v", memoryLimit, err)
return
}
cpu, mem, gNum, tNum, err := collect(cpuCore, memoryLimit)
if err != nil {
h.Errorf("failed to collect resource usage: %v", err.Error())
continue
}
h.cpuStats.push(cpu)
h.memStats.push(mem)
h.grNumStats.push(gNum)
h.threadStats.push(tNum)
h.collectCount++
if h.collectCount < minCollectCyclesBeforeDumpStart {
// at least collect some cycles
// before start to judge and dump
h.Debugf("[Holmes] warming up cycle : %d", h.collectCount)
continue
}
if err := h.EnableDump(cpu); err != nil {
h.Infof("[Holmes] unable to dump: %v", err)
continue
}
h.memCheckAndDump(mem)
h.cpuCheckAndDump(cpu)
h.threadCheckAndDump(tNum)
h.threadCheckAndShrink(tNum)
h.goroutineCheckAndDump(gNum)
}
}
}
// goroutine start.
func (h *Holmes) goroutineCheckAndDump(gNum int) {
// get a copy instead of locking it
grOpts := h.opts.GetGrOpts()
if !grOpts.Enable {
return
}
if h.grCoolDownTime.After(time.Now()) {
h.Debugf("[Holmes] goroutine dump is in cooldown")
return
}
// grOpts is a struct, no escape.
if triggered := h.goroutineProfile(gNum, grOpts); triggered {
h.grCoolDownTime = time.Now().Add(grOpts.CoolDown)
h.grTriggerCount++
}
}
func (h *Holmes) goroutineProfile(gNum int, c grOptions) bool {
match, reason := matchRule(h.grNumStats, gNum, c.TriggerMin, c.TriggerAbs, c.TriggerDiff, c.GoroutineTriggerNumMax)
if !match {
h.Infof(UniformLogFormat, "NODUMP", check2name[goroutine],
c.TriggerMin, c.TriggerDiff, c.TriggerAbs,
c.GoroutineTriggerNumMax, h.grNumStats.sequentialData(), gNum)
return false
}
h.Alertf("holmes.goroutine", UniformLogFormat, "pprof ", check2name[goroutine],
c.TriggerMin, c.TriggerDiff, c.TriggerAbs,
c.GoroutineTriggerNumMax,
h.grNumStats.sequentialData(), gNum)
var buf bytes.Buffer
_ = pprof.Lookup("goroutine").WriteTo(&buf, int(h.opts.DumpProfileType)) // nolint: errcheck
scene := Scene{
typeOption: *c.typeOption,
CurVal: gNum,
Avg: h.grNumStats.avg(),
}
h.ReportProfile(type2name[goroutine], h.writeProfileDataToFile(buf, goroutine, ""),
reason, "", time.Now(), buf.Bytes(), scene)
return true
}
// memory start.
func (h *Holmes) memCheckAndDump(mem int) {
// get a copy instead of locking it
memOpts := h.opts.GetMemOpts()
if !memOpts.Enable {
return
}
if h.memCoolDownTime.After(time.Now()) {
h.Debugf("[Holmes] mem dump is in cooldown")
return
}
// memOpts is a struct, no escape.
if triggered := h.memProfile(mem, memOpts); triggered {
h.memCoolDownTime = time.Now().Add(memOpts.CoolDown)
h.memTriggerCount++
}
}
func (h *Holmes) memProfile(rss int, c typeOption) bool {
match, reason := matchRule(h.memStats, rss, c.TriggerMin, c.TriggerAbs, c.TriggerDiff, NotSupportTypeMaxConfig)
if !match {
// let user know why this should not dump
h.Infof(UniformLogFormat, "NODUMP", check2name[mem],
c.TriggerMin, c.TriggerDiff, c.TriggerAbs, NotSupportTypeMaxConfig,
h.memStats.sequentialData(), rss)
return false
}
h.Alertf("holmes.memory", UniformLogFormat, "pprof", check2name[mem],
c.TriggerMin, c.TriggerDiff, c.TriggerAbs,
NotSupportTypeMaxConfig, h.memStats, rss)
var buf bytes.Buffer
_ = pprof.Lookup("heap").WriteTo(&buf, int(h.opts.DumpProfileType)) // nolint: errcheck
scene := Scene{
typeOption: c,
CurVal: rss,
Avg: h.memStats.avg(),
}
h.ReportProfile(type2name[mem], h.writeProfileDataToFile(buf, mem, ""), reason, "", time.Now(), buf.Bytes(), scene)
return true
}
func (h *Holmes) threadCheckAndShrink(threadNum int) {
opts := h.opts.GetShrinkThreadOpts()
if !opts.Enable {
return
}
if h.shrinkThrCoolDownTime.After(time.Now()) {
return
}
if threadNum > opts.Threshold {
// 100x Delay time a cooldown time as default
delay := opts.Delay * 100
// one hour at least
if delay < time.Hour {
delay = time.Hour
}
if delay > time.Hour*24 {
delay = time.Hour * 24
}
h.shrinkThrCoolDownTime = time.Now().Add(delay)
h.Alertf("holmes.thread", "current thread number(%v) larger than threshold(%v), will start to shrink thread after %v", threadNum, opts.Threshold, opts.Delay)
// do not shrink thread immediately
time.AfterFunc(opts.Delay, func() {
h.startShrinkThread()
})
}
}
// thread start.
func (h *Holmes) threadCheckAndDump(threadNum int) {
threadOpts := h.opts.GetThreadOpts()
if !threadOpts.Enable {
return
}
if h.threadCoolDownTime.After(time.Now()) {
h.Debugf("[Holmes] thread dump is in cooldown")
return
}
// threadOpts is a struct, no escape.
if triggered := h.threadProfile(threadNum, threadOpts); triggered {
h.threadCoolDownTime = time.Now().Add(threadOpts.CoolDown)
h.threadTriggerCount++
// optimize: https://github.com/mosn/holmes/issues/84
// Thread dump information contains goroutine information
// skip goroutine dump
h.goroutineCoolDownByThread()
}
}
// The thread dump is triggered while operating goroutine dump CoolDown .
// Thread dump information contains goroutine information .
func (h *Holmes) goroutineCoolDownByThread() {
grOpts := h.opts.GetGrOpts()
if !grOpts.Enable {
return
}
h.grCoolDownTime = time.Now().Add(grOpts.CoolDown)
}
// TODO: better only shrink the threads that are idle.
func (h *Holmes) startShrinkThread() {
curThreadNum := getThreadNum()
opts := h.opts.GetShrinkThreadOpts()
n := curThreadNum - opts.Threshold
// check again after the timer triggered
if opts.Enable && n > 0 {
h.shrinkThreadTriggerCount++
h.Infof("[holmes] start to shrink %v threads, now: %v", n, curThreadNum)
var wg sync.WaitGroup
wg.Add(n)
for i := 0; i < n; i++ {
// avoid close too much thread in batch.
time.Sleep(time.Millisecond * 100)
go func() {
defer wg.Done()
runtime.LockOSThread()
}()
}
wg.Wait()
h.Infof("[holmes] finished shrink threads, now: %v", getThreadNum())
}
}
func (h *Holmes) threadProfile(curThreadNum int, c typeOption) bool {
match, reason := matchRule(h.threadStats, curThreadNum, c.TriggerMin, c.TriggerAbs, c.TriggerDiff, NotSupportTypeMaxConfig)
if !match {
// let user know why this should not dump
h.Infof(UniformLogFormat, "NODUMP", check2name[thread],
c.TriggerMin, c.TriggerDiff, c.TriggerAbs, NotSupportTypeMaxConfig,
h.threadStats.sequentialData(), curThreadNum)
return false
}
h.Alertf("holmes.thread", UniformLogFormat, "pprof", check2name[thread],
c.TriggerMin, c.TriggerDiff, c.TriggerAbs,
NotSupportTypeMaxConfig, h.threadStats, curThreadNum)
eventID := fmt.Sprintf("thr-%d", h.threadTriggerCount)
var buf bytes.Buffer
_ = pprof.Lookup("threadcreate").WriteTo(&buf, int(h.opts.DumpProfileType)) // nolint: errcheck
scene := Scene{
typeOption: c,
CurVal: curThreadNum,
Avg: h.threadStats.avg(),
}
h.ReportProfile(type2name[thread], h.writeProfileDataToFile(buf, thread, eventID),
reason, eventID, time.Now(), buf.Bytes(), scene)
buf.Reset()
_ = pprof.Lookup("goroutine").WriteTo(&buf, int(h.opts.DumpProfileType)) // nolint: errcheck
h.ReportProfile(type2name[goroutine], h.writeProfileDataToFile(buf, goroutine, eventID),
reason, eventID, time.Now(), buf.Bytes(), scene)
return true
}
// thread end.
// cpu start.
func (h *Holmes) cpuCheckAndDump(cpu int) {
cpuOpts := h.opts.GetCPUOpts()
if !cpuOpts.Enable {
return
}
if h.cpuCoolDownTime.After(time.Now()) {
h.Debugf("[Holmes] cpu dump is in cooldown")
return
}
// cpuOpts is a struct, no escape.
if triggered := h.cpuProfile(cpu, cpuOpts); triggered {
h.cpuCoolDownTime = time.Now().Add(cpuOpts.CoolDown)
h.cpuTriggerCount++
}
}
func (h *Holmes) cpuProfile(curCPUUsage int, c typeOption) bool {
match, reason := matchRule(h.cpuStats, curCPUUsage, c.TriggerMin, c.TriggerAbs, c.TriggerDiff, NotSupportTypeMaxConfig)
if !match {
// let user know why this should not dump
h.Infof(UniformLogFormat, "NODUMP", check2name[cpu],
c.TriggerMin, c.TriggerDiff, c.TriggerAbs, NotSupportTypeMaxConfig,
h.cpuStats.sequentialData(), curCPUUsage)
return false
}
h.Alertf("holmes.cpu", UniformLogFormat, "pprof dump", check2name[cpu],
c.TriggerMin, c.TriggerDiff, c.TriggerAbs, NotSupportTypeMaxConfig,
h.cpuStats.sequentialData(), curCPUUsage)
bf, binFileName, err := getBinaryFileNameAndCreate(h.opts.DumpPath, cpu, "")
if err != nil {
h.Errorf("[Holmes] failed to create cpu profile file: %v", err.Error())
return false
}
defer bf.Close() // nolint: errcheck
err = pprof.StartCPUProfile(bf)
if err != nil {
h.Errorf("[Holmes] failed to profile cpu: %v", err.Error())
return false
}
time.Sleep(defaultCPUSamplingTime)
pprof.StopCPUProfile()
rptOpts, bfCpy := h.opts.GetReporterOpts(), []byte{}
if h.opts.DumpToLogger || rptOpts.active == 1 {
bfCpy, err = ioutil.ReadFile(binFileName)
if err != nil {
h.Errorf("encounter error when dumping profile to logger, failed to read cpu profile file: %v", err)
return true
}
}
if h.opts.DumpToLogger {
h.Infof("[Holmes] CPU profile name : " + "::" + binFileName + " \n" + string(bfCpy))
}
scene := Scene{
typeOption: c,
CurVal: curCPUUsage,
Avg: h.cpuStats.avg(),
}
if rptOpts.active == 1 {
h.ReportProfile(type2name[cpu], binFileName,
reason, "", time.Now(), bfCpy, scene)
}
return true
}
func (h *Holmes) gcHeapCheckLoop(ch chan struct{}) {
for range ch {
h.gcHeapCheckAndDump()
}
}
func (h *Holmes) gcHeapCheckAndDump() {
gcHeapOpts := h.opts.GetGcHeapOpts()
if !gcHeapOpts.Enable || atomic.LoadInt64(&h.stopped) == 1 {
return
}
memStats := new(runtime.MemStats)
runtime.ReadMemStats(memStats)
// TODO: we can only use NextGC for now since runtime haven't expose heapmarked yet
// and we hard code the gcPercent is 100 here.
// may introduce a new API debug.GCHeapMarked? it can also has better performance(no STW).
nextGC := memStats.NextGC
prevGC := nextGC / 2 //nolint:gomnd
memoryLimit, err := h.getMemoryLimit()
if memoryLimit == 0 || err != nil {
h.Errorf("[Holmes] get memory limit failed, memory limit: %v, error: %v", memoryLimit, err)
return
}
ratio := int(100 * float64(prevGC) / float64(memoryLimit))
h.gcHeapStats.push(ratio)
h.gcCycleCount++
if h.gcCycleCount < minCollectCyclesBeforeDumpStart {
// at least collect some cycles
// before start to judge and dump
h.Debugf("[Holmes] GC cycle warming up : %d", h.gcCycleCount)
return
}
if h.gcHeapCoolDownTime.After(time.Now()) {
h.Debugf("[Holmes] GC heap dump is in cooldown")
return
}
if triggered := h.gcHeapProfile(ratio, h.gcHeapTriggered, gcHeapOpts); triggered {
if h.gcHeapTriggered {
// already dump twice, mark it false
h.gcHeapTriggered = false
h.gcHeapCoolDownTime = time.Now().Add(gcHeapOpts.CoolDown)
h.gcHeapTriggerCount++
} else {
// force dump next time
h.gcHeapTriggered = true
}
}
}
func (h *Holmes) getCPUCore() (float64, error) {
if h.opts.cpuCore > 0 {
return h.opts.cpuCore, nil
}
if h.opts.UseGoProcAsCPUCore {
return float64(runtime.GOMAXPROCS(-1)), nil
}
if h.opts.UseCGroup {
return getCGroupCPUCore()
}
return float64(runtime.NumCPU()), nil
}
func (h *Holmes) getMemoryLimit() (uint64, error) {
if h.opts.memoryLimit > 0 {
return h.opts.memoryLimit, nil
}
if h.opts.UseCGroup {
return getCGroupMemoryLimit()
}
return getNormalMemoryLimit()
}
// gcHeapProfile will dump profile twice when triggered once.
// since the current memory profile will be merged after next GC cycle.
// And we assume the finalizer will be called before next GC cycle(it will be usually).
func (h *Holmes) gcHeapProfile(gc int, force bool, c typeOption) bool {
match, reason := matchRule(h.gcHeapStats, gc, c.TriggerMin, c.TriggerAbs, c.TriggerDiff, NotSupportTypeMaxConfig)
if !force && !match {
// let user know why this should not dump
h.Infof(UniformLogFormat, "NODUMP", check2name[gcHeap],
c.TriggerMin, c.TriggerDiff, c.TriggerAbs,
NotSupportTypeMaxConfig,
h.gcHeapStats.sequentialData(), gc)
return false
}
h.Alertf("holmes.gcheap", UniformLogFormat, "pprof", check2name[gcHeap],
c.TriggerMin, c.TriggerDiff, c.TriggerAbs,
NotSupportTypeMaxConfig, h.gcHeapStats, gc)
// gcHeapTriggerCount only increased after got both two profiles
eventID := fmt.Sprintf("heap-%d", h.gcHeapTriggerCount)
var buf bytes.Buffer
_ = pprof.Lookup("heap").WriteTo(&buf, int(h.opts.DumpProfileType)) // nolint: errcheck
scene := Scene{
typeOption: c,
CurVal: gc,
Avg: h.gcHeapStats.avg(),
}
h.ReportProfile(type2name[gcHeap], h.writeProfileDataToFile(buf, gcHeap, eventID),
reason, eventID, time.Now(), buf.Bytes(), scene)
return true
}
func (h *Holmes) writeProfileDataToFile(data bytes.Buffer, dumpType configureType, eventID string) string {
fileName, err := writeFile(data, dumpType, h.opts.DumpOptions, eventID)
if err != nil {
h.Errorf("failed to write profile to file(%v), err: %s", fileName, err.Error())
return ""
}
if h.opts.DumpOptions.DumpToLogger {
h.Infof(fmt.Sprintf("[Holmes] %v profile: \n", check2name[dumpType]) + data.String())
}
h.Infof("[Holmes] pprof %v profile write to file %v successfully", check2name[dumpType], fileName)
return fileName
}
func (h *Holmes) initEnvironment() {
// whether the max memory is limited by cgroup
if h.opts.UseCGroup {
h.Infof("[Holmes] use cgroup to limit memory")
} else {
h.Infof("[Holmes] use the default memory percent calculated by gopsutil")
}
}
func (h *Holmes) EnableDump(curCPU int) (err error) {
if h.opts.CPUMaxPercent != 0 && curCPU >= h.opts.CPUMaxPercent {
return fmt.Errorf("current cpu percent [%v] is greater than the CPUMaxPercent [%v]", curCPU, h.opts.CPUMaxPercent)
}
return nil
}
// Set sets holmes's optional after initialing.
func (h *Holmes) Set(opts ...Option) error {
h.opts.L.Lock()
defer h.opts.L.Unlock()
for _, opt := range opts {
if err := opt.apply(h.opts); err != nil {
return err
}
}
return nil
}
func (h *Holmes) DisableProfileReporter() {
atomic.StoreInt32(&h.opts.rptOpts.active, 0)
}
func (h *Holmes) EnableProfileReporter() {
opt := h.opts.GetReporterOpts()
if opt.reporter == nil {
h.Infof("failed to enable profile reporter since reporter is empty")
return
}
atomic.StoreInt32(&h.opts.rptOpts.active, 1)
}
func (h *Holmes) ReportProfile(pType string, filename string, reason ReasonType, eventID string, sampleTime time.Time, pprofBytes []byte, scene Scene) {
if filename == "" {
h.Errorf("dump name is empty, type:%s, reason:%s, eventID:%s", pType, reason.String(), eventID)
return
}
defer func() {
if r := recover(); r != nil {
h.Errorf("Panic during report profile: %v", r)
}
}()
if atomic.LoadInt64(&h.stopped) == 1 {
return
}
opts := h.opts.GetReporterOpts()
if opts.active == 0 {
return
}
msg := rptEvent{
PType: pType,
FileName: filename,
Reason: reason,
EventID: eventID,
SampleTime: sampleTime,
PprofBytes: pprofBytes,
Scene: scene,
}
// read channel should be atomic.
ch := h.rptEventsCh
if ch == nil {
return
}
// Notice: here may be a litte race, will panic when ch is closed now.
// we just leave it since it is very small and there is a recover.
select {
case ch <- msg:
default:
h.Warnf("reporter channel is full, will ignore it")
}
}
// startReporter starts a background goroutine to consume event channel,
// and finish it at after receive from cancel channel.
func (h *Holmes) startReporter(ch chan rptEvent) {
go func() {
for evt := range ch {
opts := h.opts.GetReporterOpts()
if opts.reporter == nil {
h.Infof("reporter is nil, please initial it before startReporter")
// drop the event
continue
}
// It's supposed to be sending judgment, isn't it?
err := opts.reporter.Report(evt.PType, evt.FileName, evt.Reason, evt.EventID, evt.SampleTime, evt.PprofBytes, evt.Scene) // nolint: errcheck
if err != nil {
h.Infof("reporter err:%v", err)
}
}
}()
}