/
pprof.go
117 lines (95 loc) · 1.84 KB
/
pprof.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
// Package pprof provides a pprof profiler which writes output to /tmp/[name].{cpu,mem}.pprof
package pprof
import (
"os"
"path/filepath"
"runtime"
"runtime/pprof"
"sync"
"time"
profile "github.com/unistack-org/micro/v3/profiler"
)
type profiler struct {
exit chan bool
cpuFile *os.File
memFile *os.File
opts profile.Options
sync.Mutex
running bool
}
func (p *profiler) writeHeap(f *os.File) {
defer f.Close()
t := time.NewTicker(time.Second * 30)
defer t.Stop()
for {
select {
case <-t.C:
runtime.GC()
_ = pprof.WriteHeapProfile(f)
case <-p.exit:
return
}
}
}
func (p *profiler) Start() error {
p.Lock()
defer p.Unlock()
if p.running {
return nil
}
// create exit channel
p.exit = make(chan bool)
cpuFile := filepath.Join("/tmp", "cpu.pprof")
memFile := filepath.Join("/tmp", "mem.pprof")
if len(p.opts.Name) > 0 {
cpuFile = filepath.Join("/tmp", p.opts.Name+".cpu.pprof")
memFile = filepath.Join("/tmp", p.opts.Name+".mem.pprof")
}
f1, err := os.Create(cpuFile)
if err != nil {
return err
}
f2, err := os.Create(memFile)
if err != nil {
return err
}
// start cpu profiling
if err := pprof.StartCPUProfile(f1); err != nil {
return err
}
// write the heap periodically
go p.writeHeap(f2)
// set cpu file
p.cpuFile = f1
// set mem file
p.memFile = f2
p.running = true
return nil
}
func (p *profiler) Stop() error {
p.Lock()
defer p.Unlock()
select {
case <-p.exit:
return nil
default:
close(p.exit)
pprof.StopCPUProfile()
p.cpuFile.Close()
p.running = false
p.cpuFile = nil
p.memFile = nil
return nil
}
}
func (p *profiler) String() string {
return "pprof"
}
// NewProfile create new profiler
func NewProfile(opts ...profile.Option) profile.Profiler {
options := profile.Options{}
for _, o := range opts {
o(&options)
}
return &profiler{opts: options}
}