-
Notifications
You must be signed in to change notification settings - Fork 12
Expand file tree
/
Copy pathprofile.go
More file actions
87 lines (76 loc) · 1.96 KB
/
Copy pathprofile.go
File metadata and controls
87 lines (76 loc) · 1.96 KB
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
package autopprof
import (
"bufio"
"bytes"
"runtime/pprof"
"sync"
"time"
)
//go:generate mockgen -source=profile.go -destination=profile_mock.go -package=autopprof
type profiler interface {
// profileCPU profiles the CPU usage for a specific duration.
profileCPU() ([]byte, error)
// profileHeap profiles the heap usage.
profileHeap() ([]byte, error)
// profileGoroutine profiles the goroutine usage.
profileGoroutine() ([]byte, error)
}
type defaultProfiler struct {
// cpuProfilingDuration is the duration to wait until collect
// the enough cpu profiling data.
// Default: 10s.
cpuProfilingDuration time.Duration
// cpuMu serializes profileCPU calls. pprof.StartCPUProfile is a
// process-wide singleton — concurrent invocations would make the
// second one fail immediately. With ReportAll a cascade path can
// land on CPU at the same tick as its own watcher, so we gate it.
cpuMu sync.Mutex
}
func newDefaultProfiler(duration time.Duration) *defaultProfiler {
return &defaultProfiler{
cpuProfilingDuration: duration,
}
}
func (p *defaultProfiler) profileCPU() ([]byte, error) {
p.cpuMu.Lock()
defer p.cpuMu.Unlock()
var (
buf bytes.Buffer
w = bufio.NewWriter(&buf)
)
if err := pprof.StartCPUProfile(w); err != nil {
return nil, err
}
<-time.After(p.cpuProfilingDuration)
pprof.StopCPUProfile()
if err := w.Flush(); err != nil {
return nil, err
}
return buf.Bytes(), nil
}
func (p *defaultProfiler) profileHeap() ([]byte, error) {
var (
buf bytes.Buffer
w = bufio.NewWriter(&buf)
)
if err := pprof.Lookup("heap").WriteTo(w, 0); err != nil {
return nil, err
}
if err := w.Flush(); err != nil {
return nil, err
}
return buf.Bytes(), nil
}
func (p *defaultProfiler) profileGoroutine() ([]byte, error) {
var (
buf bytes.Buffer
w = bufio.NewWriter(&buf)
)
if err := pprof.Lookup("goroutine").WriteTo(w, 0); err != nil {
return nil, err
}
if err := w.Flush(); err != nil {
return nil, err
}
return buf.Bytes(), nil
}