-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathprofile.go
126 lines (108 loc) · 2.25 KB
/
profile.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
package cpuprofile
import (
"bytes"
"context"
"runtime/pprof"
"sync"
"time"
)
var globalCPUProfiler = newCPUProfiler()
var profileWindow = time.Second
type ProfileData struct {
Data *bytes.Buffer
Error error
}
type ProfileConsumer = chan *ProfileData
type cpuProfiler struct {
consumers map[ProfileConsumer]struct{}
profileData *ProfileData
lastDataSize int
sync.Mutex
}
func newCPUProfiler() *cpuProfiler {
return &cpuProfiler{
consumers: make(map[ProfileConsumer]struct{}),
}
}
func (p *cpuProfiler) register(ch ProfileConsumer) {
if ch == nil {
return
}
p.Lock()
p.consumers[ch] = struct{}{}
p.Unlock()
}
func (p *cpuProfiler) unregister(ch ProfileConsumer) {
if ch == nil {
return
}
p.Lock()
delete(p.consumers, ch)
p.Unlock()
}
// StartProfiler uses to start to run the global cpuProfiler and global aggregater
func StartCPUProfiler(ctx context.Context, window time.Duration) error {
profileWindow = window
err := globalCPUProfiler.start(ctx)
if err != nil {
return err
}
return globalAggregator.start(ctx)
}
func (p *cpuProfiler) start(ctx context.Context) error {
go p.profilingLoop(ctx)
// log.Println("cpu profiler started")
return nil
}
func (p *cpuProfiler) profilingLoop(ctx context.Context) {
checkTicker := time.NewTicker(profileWindow)
defer func() {
checkTicker.Stop()
pprof.StopCPUProfile()
}()
for {
select {
case <-ctx.Done():
// log.Println("cpu profiler stopped")
return
case <-checkTicker.C:
p.doProfiling()
}
}
}
func (p *cpuProfiler) doProfiling() {
if p.profileData != nil {
pprof.StopCPUProfile()
p.lastDataSize = p.profileData.Data.Len()
p.sendToConsumers()
}
if len(p.consumers) == 0 {
return
}
capacity := (p.lastDataSize/4096 + 1) * 4096
p.profileData = &ProfileData{Data: bytes.NewBuffer(make([]byte, 0, capacity))}
err := pprof.StartCPUProfile(p.profileData.Data)
if err != nil {
p.profileData.Error = err
// notify error as soon as possible
p.sendToConsumers()
return
}
}
func (p *cpuProfiler) sendToConsumers() {
p.Lock()
defer func() {
p.Unlock()
if r := recover(); r != nil {
// log.Printf("cpu profiler panic: %v", r)
}
}()
for c := range p.consumers {
select {
case c <- p.profileData:
default:
// ignore
}
}
p.profileData = nil
}