-
Notifications
You must be signed in to change notification settings - Fork 47
/
profile.go
287 lines (248 loc) · 7 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
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
// This Source Code Form is subject to the terms of the MIT License.
// If a copy of the MIT License was not distributed with this
// file, you can obtain one at https://opensource.org/licenses/MIT.
//
// Copyright (c) DUSK NETWORK. All rights reserved.
package diagnostics
import (
"fmt"
"os"
"runtime"
"runtime/debug"
"runtime/pprof"
"strconv"
"time"
log "github.com/sirupsen/logrus"
)
const (
blockProfileRate = 1000000000
// TODO: Find the optimal fraction value for mutex profiling.
mutexProfileRate = 1
)
// Profile represents the cpu or memory profile sampled at regular intervals.
type Profile struct {
name string
n, d uint
start bool
quit chan struct{}
}
// NewProfile returns a new instance of a Profile.
func NewProfile(name string, n, d uint, start bool) Profile {
return Profile{
name: name,
n: n,
d: d,
start: start,
quit: make(chan struct{}),
}
}
// loop runs a loop for periodical (CPU, Heap etc .. ) samples fetching
// Each N seconds loop restarts a profiler and keep samples fetching for D seconds.
//
// Example use:
//
// name: "cpu", n: 1800, d: 30, s: 0
// Continuous profiling sutiable for profiling a node
// in production with less perf overhead:
// This restarts CPU profiling each half an hour and keep samples fetching for 30 seconds
// output: cpu_$timestamp.prof file
//
// name: "memstats", n: 1800, d: 1, s: 0
// Memory leaks detection with less perf overhead
// This restarts Memstats fetching each half an hour and records GC/Memory stats into logs
//
// name: "heap", n: 1800, d: 1800, s: 1
// Detailed memory inefficiency detection with highest perf overhead
// This records complete memory profile each 30 mins and stores it in mem_$timestamp.pprof file
// suitable in development
// output: heap_$timestamp.prof file
//
// name: "cpu", n: 1800, d: 1800, s: 1
// Detailed CPU inefficiency detection with highest perf overhead
// This records complete CPU profile each 30 mins.
// suitable in development
// output: cpu_$timestamp.prof file
//
// name: "block", n: 1800, d: 30, s: 1
// Measures time in which goroutines is on idle. This should help to find any bottlenecks or
// deadlocks.
// (suitable in development)
// output: block_$timestamp.prof file
//
// name: "mutex", n: 1800, d: 30, s: 1
// This starts contended mutex profile from node startup.
// Mutex profile allows you to capture a fraction of the stack traces of
// goroutines with contended mutexes. (find too wide protected regions)
// (suitable in development)
// output: mutex_$timestamp.prof file
func (p *Profile) loop() {
var err error
t := time.NewTicker(time.Duration(p.n) * time.Second)
// Trigger sampling at startup
var f *os.File
if p.start {
f, err = startProfiling(p.name)
if err != nil {
// not supported type
return
}
}
defer stopProfiling(f, p.name)
// Restart the sampling each #interval minutes
for {
select {
case <-t.C:
// Close previous sampling and start a new one
stopProfiling(f, p.name)
f, err = startProfiling(p.name)
if err != nil {
return
}
// Sampling lasts not more than Duration seconds
t2 := time.NewTicker(time.Duration(p.d) * time.Second)
select {
case <-t2.C:
stopProfiling(f, p.name)
f = nil
case <-p.quit:
return
}
case <-p.quit:
return
}
}
}
// startProfiling initializes the profile selected by name and starts samples
// fetching
//nolint:goconst
func startProfiling(name string) (*os.File, error) {
createFile := func(name string) *os.File {
pprofFile, err := os.Create(profFile(name))
if err != nil {
log.Errorf("Could not create file for profiling %s", name)
return nil
}
log.WithFields(log.Fields{
"process": "profile",
"file": pprofFile.Name(),
}).Infof("%s profile starting", name)
return pprofFile
}
// Perform different initializing methods according to the type of profile
switch name {
case "mutex":
runtime.SetMutexProfileFraction(mutexProfileRate)
return createFile(name), nil
case "block":
runtime.SetBlockProfileRate(blockProfileRate)
return createFile(name), nil
case "heap", "goroutine":
return createFile(name), nil
case "memstats":
// No file needed for custom sampling that records into logger
logMemstatsSample()
case "cpu":
f := createFile(name)
if err := pprof.StartCPUProfile(f); err != nil {
log.Error("Could not start CPU profile: ", err)
}
return f, nil
default:
err := fmt.Errorf("Unsupported profile name %s", name)
log.Error(err)
return nil, err
}
return nil, nil
}
// stopProfiling stores profile sampling and resets any profile-related state.
func stopProfiling(f *os.File, name string) {
saveFile := func(f *os.File, name string) {
p := pprof.Lookup(name)
if p != nil && f != nil {
if err := p.WriteTo(f, 0); err != nil {
log.Errorf("Error on writing profile name %s: %v", name, err)
} else {
log.WithFields(log.Fields{
"process": "profile",
"file": f.Name(),
}).Infof("%s profile saved", name)
}
}
}
defer func() {
if f != nil {
_ = f.Close()
f = nil
}
}()
// Perform different storing methods according to the type of profile
switch name {
case "heap":
runtime.GC() // get up-to-date statistics
saveFile(f, name)
case "mutex":
saveFile(f, name)
runtime.SetMutexProfileFraction(0)
case "block":
saveFile(f, name)
runtime.SetBlockProfileRate(0)
case "goroutine":
saveFile(f, name)
case "memstats":
case "cpu":
pprof.StopCPUProfile()
log.WithFields(log.Fields{
"process": "profile",
"file": f.Name,
}).Infof("%s profile saved", name)
default:
log.Errorf("Unsupported profile name %s", name)
return
}
}
func profFile(prefix string) string {
name := prefix
name += "_"
name += strconv.Itoa(int(time.Now().Unix()))
return name + ".prof"
}
// Custom profile samples
// logMemstatsSample records memory/GC statistics as log entries.
func logMemstatsSample() {
l := log.WithField("process", "memstats")
runtime.GC() // get up-to-date statistics
memStats := new(runtime.MemStats)
runtime.ReadMemStats(memStats)
var gcStats debug.GCStats
debug.ReadGCStats(&gcStats)
s := memStats
l.Infof("# runtime.MemStats")
l.Infof("# Alloc = %d\n", s.Alloc)
l.Infof("# TotalAlloc = %d\n", s.TotalAlloc)
l.Infof("# Sys = %d\n", s.Sys)
l.Infof("# Lookups = %d\n", s.Lookups)
l.Infof("# Mallocs = %d\n", s.Mallocs)
l.Infof("# Frees = %d\n", s.Frees)
l.Infof("# HeapAlloc = %d\n", s.HeapAlloc)
l.Infof("# HeapSys = %d\n", s.HeapSys)
l.Infof("# HeapIdle = %d\n", s.HeapIdle)
l.Infof("# HeapInuse = %d\n", s.HeapInuse)
l.Infof("# HeapReleased = %d\n", s.HeapReleased)
l.Infof("# HeapObjects = %d\n", s.HeapObjects)
l.Infof("# Stack = %d / %d\n", s.StackInuse, s.StackSys)
// Record GC pause history, most recent 5 entries
l.Infof("# Stop-the-world Pause time")
for i, v := range gcStats.Pause {
l.Infof("# gcStats.Pause[%d] = %d ns", i, v)
if i == 5 {
break
}
}
}
func isSupported(name string) error {
switch name {
case "mutex", "block", "heap", "goroutine", "memstats", "cpu":
return nil
}
return fmt.Errorf("unsupported profile name %s", name)
}