-
Notifications
You must be signed in to change notification settings - Fork 136
/
Copy pathpprof.go
81 lines (67 loc) · 2.25 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
// Copyright 2022 PingCAP, Inc. Licensed under Apache-2.0.
package profiling
import (
"fmt"
"io/ioutil"
"strconv"
"github.com/pingcap/tidb-dashboard/pkg/apiserver/model"
)
type pprofOptions struct {
duration uint
fileNameWithoutExt string
target *model.RequestTargetNode
fetcher *profileFetcher
profilingType TaskProfilingType
}
func fetchPprof(op *pprofOptions) (string, TaskRawDataType, error) {
fetcher := &fetcher{profileFetcher: op.fetcher, target: op.target}
tmpPath, rawDataType, err := fetcher.FetchAndWriteToFile(op.duration, op.fileNameWithoutExt, op.profilingType)
if err != nil {
return "", "", fmt.Errorf("failed to fetch and write to temp file: %v", err)
}
return tmpPath, rawDataType, nil
}
type fetcher struct {
target *model.RequestTargetNode
profileFetcher *profileFetcher
}
func (f *fetcher) FetchAndWriteToFile(duration uint, fileNameWithoutExt string, profilingType TaskProfilingType) (string, TaskRawDataType, error) {
var profilingRawDataType TaskRawDataType
var fileExtenstion string
secs := strconv.Itoa(int(duration))
var url string
switch profilingType {
case ProfilingTypeCPU:
url = "/debug/pprof/profile?seconds=" + secs
profilingRawDataType = RawDataTypeProtobuf
fileExtenstion = "*.proto"
case ProfilingTypeHeap:
url = "/debug/pprof/heap"
profilingRawDataType = RawDataTypeProtobuf
fileExtenstion = "*.proto"
case ProfilingTypeGoroutine:
url = "/debug/pprof/goroutine?debug=1"
profilingRawDataType = RawDataTypeText
fileExtenstion = "*.txt"
case ProfilingTypeMutex:
url = "/debug/pprof/mutex?debug=1"
profilingRawDataType = RawDataTypeText
fileExtenstion = "*.txt"
}
tmpfile, err := ioutil.TempFile("", fileNameWithoutExt+"_"+fileExtenstion)
if err != nil {
return "", "", fmt.Errorf("failed to create tmpfile to write profile: %v", err)
}
defer func() {
_ = tmpfile.Close()
}()
resp, err := (*f.profileFetcher).fetch(&fetchOptions{ip: f.target.IP, port: f.target.Port, path: url})
if err != nil {
return "", "", fmt.Errorf("failed to fetch profile with %v format: %v", fileExtenstion, err)
}
_, err = tmpfile.Write(resp)
if err != nil {
return "", "", fmt.Errorf("failed to write profile: %v", err)
}
return tmpfile.Name(), profilingRawDataType, nil
}