-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathprofiler.go
227 lines (199 loc) · 5.09 KB
/
profiler.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
// Package profiler is a simple abstraction for easily running runtime
// profiles and storing the results to files.
package profiler
import (
"io"
"io/ioutil"
"log"
"os"
"os/signal"
"path"
"path/filepath"
"runtime"
"runtime/pprof"
"runtime/trace"
"sync/atomic"
)
const (
// Profiler modes.
Block = iota
Cpu
Goroutine
Mem
Mutex
ThreadCreate
Trace
)
type profile struct {
File string
Start func(f io.Writer)
Stop func(f io.Writer)
f io.Writer
}
// Conf contains the profiler config.
type Conf struct {
// Directory path to dump the profile output to. Default is current directory.
DirPath string
// Quiet disables info log output.
Quiet bool
// NoShutdownHook controls whether the profiling package should
// hook SIGINT to automatically Stop().
NoShutdownHook bool
// MemProfileRate is the rate for the memory profiler. Default is 4096.
// To include every allocated block in the profile, set MemProfileRate to 1.
MemProfileRate int
// MemProfileType = heap or alloc. Default is heap.
MemProfileType string
}
// Profiler represents an active profiling session.
type Profiler struct {
c Conf
oldMemProfileRate int
profiles []*profile
log *log.Logger
}
// Flag to block concurrent and multiple Start() and Stop() of the profiler.
var running, stopped uint32
// New returns a new Profiler. One or more modes can be provided.
// eg: `prof := New(profiler.Cpu, profiler.Mem ...)`
// Configuration can be directly applied once `prof` is initiailized.
// eg: `prof.Path = "./otuput"`
func New(c Conf, modes ...int) *Profiler {
if len(modes) == 0 {
modes = append(modes, Cpu)
}
if c.MemProfileRate < 1 {
c.MemProfileRate = 4096
}
if c.MemProfileType != "heap" && c.MemProfileType != "alloc" {
c.MemProfileType = "heap"
}
// Setup the output directory.
if c.DirPath != "" {
if err := os.MkdirAll(c.DirPath, 0777); err != nil {
log.Fatalf("error creating output directory '%s': %v", c.DirPath, err)
}
}
prof := &Profiler{c: c}
// Initialize the logger.
if prof.c.Quiet {
prof.log = log.New(ioutil.Discard, "", log.Ldate|log.Ltime)
} else {
prof.log = log.New(os.Stdout, "profiler: ", log.Ldate|log.Ltime)
}
// Initialize the requested profile modes.
all := prof.all()
for _, mode := range modes {
if p, ok := all[mode]; ok {
prof.profiles = append(prof.profiles, p)
}
}
return prof
}
func (prof *Profiler) Start() {
if !atomic.CompareAndSwapUint32(&running, 0, 1) {
log.Fatal("profiler is already running")
}
// If shutdown hooks are enabled, listen to SIGINT and automatically Stop().
if !prof.c.NoShutdownHook {
go func() {
c := make(chan os.Signal, 1)
signal.Notify(c, os.Interrupt)
<-c
prof.log.Println("caught SIGINT. stopping.")
prof.Stop()
os.Exit(0)
}()
}
// Start the profilers.
for _, pr := range prof.profiles {
path := filepath.Join(prof.c.DirPath, pr.File)
f, err := os.Create(path)
if err != nil {
log.Fatalf("error creating file %s: %v", path, err)
}
prof.log.Printf("will dump to %s", path)
pr.f = f
pr.Start(f)
}
atomic.StoreUint32(&running, 1)
}
// Stop runs all the profile stop functions.
func (pr *Profiler) Stop() {
if !atomic.CompareAndSwapUint32(&stopped, 0, 1) {
log.Printf("profiler has already been stopped")
return
}
for _, p := range pr.profiles {
pr.log.Printf("finishing %s", path.Join(pr.c.DirPath, p.File))
p.Stop(p.f)
// Close the file handler.
p.f.(*os.File).Close()
}
}
func (pr *Profiler) all() map[int]*profile {
return map[int]*profile{
Cpu: {
File: "cpu.pprof",
Start: func(f io.Writer) { pprof.StartCPUProfile(f) },
Stop: func(f io.Writer) { pprof.StopCPUProfile() },
},
Mem: {
File: "mem.pprof",
Start: func(f io.Writer) {
// Record the old rate to reset the profiler on Stop().
pr.oldMemProfileRate = runtime.MemProfileRate
runtime.MemProfileRate = pr.c.MemProfileRate
},
Stop: func(f io.Writer) {
pprof.Lookup(pr.c.MemProfileType).WriteTo(f, 0)
runtime.MemProfileRate = pr.oldMemProfileRate
},
},
Mutex: {
File: "mutex.pprof",
Start: func(f io.Writer) { runtime.SetMutexProfileFraction(1) },
Stop: func(f io.Writer) {
if mp := pprof.Lookup("mutex"); mp != nil {
mp.WriteTo(f, 0)
}
runtime.SetMutexProfileFraction(0)
},
},
Block: {
File: "block.pprof",
Start: func(f io.Writer) { runtime.SetBlockProfileRate(1) },
Stop: func(f io.Writer) {
pprof.Lookup("block").WriteTo(f, 0)
runtime.SetBlockProfileRate(0)
},
},
ThreadCreate: {
File: "threadcreate.pprof",
Start: func(f io.Writer) {},
Stop: func(f io.Writer) {
if mp := pprof.Lookup("threadcreate"); mp != nil {
mp.WriteTo(f, 0)
}
},
},
Trace: {
File: "trace.out",
Start: func(f io.Writer) {
if err := trace.Start(f); err != nil {
pr.log.Fatalf("profile: could not start trace: %v", err)
}
},
Stop: func(f io.Writer) { trace.Stop() },
},
Goroutine: {
File: "goroutine.pprof",
Start: func(f io.Writer) {},
Stop: func(f io.Writer) {
if mp := pprof.Lookup("goroutine"); mp != nil {
mp.WriteTo(f, 0)
}
},
},
}
}