/
profiling.go
79 lines (69 loc) · 2.47 KB
/
profiling.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
package profiling
import (
"fmt"
"net"
"net/http"
"os"
"path/filepath"
"time"
"github.com/BTCGhostdag/BTCD/infrastructure/logger"
// Required for profiling
_ "net/http/pprof"
"runtime"
"runtime/pprof"
"github.com/BTCGhostdag/BTCD/util/panics"
)
// heapDumpFileName is the name of the heap dump file. We want every run to have its own
// file, so we append the timestamp of the program launch time to the file name (note the
// custom format for compliance with file name rules on all OSes).
var heapDumpFileName = fmt.Sprintf("heap-%s.pprof", time.Now().Format("01-02-2006T15.04.05"))
// Start starts the profiling server
func Start(port string, log *logger.Logger) {
spawn := panics.GoroutineWrapperFunc(log)
spawn("profiling.Start", func() {
listenAddr := net.JoinHostPort("", port)
log.Infof("Profile server listening on %s", listenAddr)
profileRedirect := http.RedirectHandler("/debug/pprof", http.StatusSeeOther)
http.Handle("/", profileRedirect)
log.Error(http.ListenAndServe(listenAddr, nil))
})
}
// TrackHeap tracks the size of the heap and dumps a profile if it passes a limit
func TrackHeap(appDir string, log *logger.Logger) {
spawn := panics.GoroutineWrapperFunc(log)
spawn("profiling.TrackHeap", func() {
dumpFolder := filepath.Join(appDir, "dumps")
err := os.MkdirAll(dumpFolder, 0700)
if err != nil {
log.Errorf("Could not create heap dumps folder at %s", dumpFolder)
return
}
const limitInGigabytes = 7 // We want to support 8 GB RAM, so we profile at 7
trackHeapSize(limitInGigabytes*1024*1024*1024, dumpFolder, log)
})
}
func trackHeapSize(heapLimit uint64, dumpFolder string, log *logger.Logger) {
ticker := time.NewTicker(10 * time.Second)
defer ticker.Stop()
for range ticker.C {
memStats := &runtime.MemStats{}
runtime.ReadMemStats(memStats)
// If we passed the expected heap limit, dump the heap profile to a file
if memStats.HeapAlloc > heapLimit {
dumpHeapProfile(heapLimit, dumpFolder, memStats, log)
}
}
}
func dumpHeapProfile(heapLimit uint64, dumpFolder string, memStats *runtime.MemStats, log *logger.Logger) {
heapFile := filepath.Join(dumpFolder, heapDumpFileName)
log.Infof("Saving heap statistics into %s (HeapAlloc=%d > %d=heapLimit)", heapFile, memStats.HeapAlloc, heapLimit)
f, err := os.Create(heapFile)
defer f.Close()
if err != nil {
log.Infof("Could not create heap profile: %s", err)
return
}
if err := pprof.WriteHeapProfile(f); err != nil {
log.Infof("Could not write heap profile: %s", err)
}
}