/
profiling.go
81 lines (65 loc) · 2.21 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
80
81
package framework
import (
"bytes"
"context"
"fmt"
"io"
"net/http"
"time"
)
const (
cpuProfilePrefix = "cpu_profile"
heapProfilePrefix = "heap_profile"
timeoutProfilingQuery = 1 * time.Minute
)
// Profiler profiles a node for metrics.
type Profiler struct {
pprofURI string
websocketURI string
// the name of the target of this profiler. used to determine the profile file names.
targetName string
http.Client
}
// TakeCPUProfile takes a CPU profile for the given duration and then saves it to the log directory.
func (n *Profiler) TakeCPUProfile(dur time.Duration) error {
profileBytes, err := n.query(fmt.Sprintf("/debug/pprof/profile?seconds=%d", dur.Truncate(time.Second)))
if err != nil {
return err
}
fileName := fmt.Sprintf("%s_%s_%d.profile", n.targetName, cpuProfilePrefix, time.Now().Unix())
return n.writeProfile(fileName, profileBytes)
}
// TakeHeapSnapshot takes a snapshot of the heap memory and then saves it to the log directory.
func (n *Profiler) TakeHeapSnapshot() error {
profileBytes, err := n.query("/debug/pprof/heap")
if err != nil {
return err
}
fileName := fmt.Sprintf("%s_%s_%d.profile", n.targetName, heapProfilePrefix, time.Now().Unix())
return n.writeProfile(fileName, profileBytes)
}
// queries the given pprof URI and returns the profile data.
func (n *Profiler) query(path string) ([]byte, error) {
target := fmt.Sprintf("%s%s", n.pprofURI, path)
ctx, cancel := context.WithTimeout(context.Background(), timeoutProfilingQuery)
defer cancel()
req, err := http.NewRequestWithContext(ctx, http.MethodGet, target, nil)
if err != nil {
return nil, fmt.Errorf("download failed: %w", err)
}
resp, err := n.Do(req)
if err != nil {
return nil, fmt.Errorf("unable to take profile: %w", err)
}
defer func() { _ = resp.Body.Close() }()
profileBytes, err := io.ReadAll(resp.Body)
if err != nil {
return nil, fmt.Errorf("unable to read profile from response: %w", err)
}
return profileBytes, err
}
// writeProfile writes the given profile data to the given file in the log directory.
func (n *Profiler) writeProfile(fileName string, profileBytes []byte) error {
profileReader := io.NopCloser(bytes.NewReader(profileBytes))
return writeFileInLogDir(fileName, profileReader)
}