/
profile.go
122 lines (96 loc) · 2.17 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
package main
import (
"fmt"
"net/http"
"strconv"
"sync"
"time"
"github.com/google/pprof/profile"
)
var profileNodes = map[string]*node{}
var profilesMutex sync.Mutex
func loadProfile(name, sample, url string, duration time.Duration) error {
// get seconds
seconds := int(duration / time.Second)
if seconds < 1 {
seconds = 1
}
// get profile
res, err := http.Get(url + "?seconds=" + strconv.Itoa(seconds))
if err != nil {
return err
}
// ensure close
defer res.Body.Close()
// parse profile
prf, err := profile.Parse(res.Body)
if err != nil {
return err
}
// prepare root
root := &node{
name: "root",
}
// get sample index
sampleIndex := -1
for i, st := range prf.SampleType {
if st.Type == sample {
sampleIndex = i
}
}
if sampleIndex < 0 {
return fmt.Errorf("sample not found")
}
// convert samples
for _, sample := range prf.Sample {
// prepare node
node := root
// reverse iterate locations
for i := len(sample.Location) - 1; i >= 0; i-- {
// get location
location := sample.Location[i]
// iterate lines
for _, line := range location.Line {
node = node.push(line.Function.Name)
}
}
// set self
node.self += sample.Value[sampleIndex]
// increment total
for node != nil {
node.total += sample.Value[sampleIndex]
node = node.parent
}
}
// sort nodes
root.sort()
// set profile
profilesMutex.Lock()
profileNodes[name] = root
profilesMutex.Unlock()
return nil
}
func getProfile(name string) *node {
// acquire mutex
profilesMutex.Lock()
defer profilesMutex.Unlock()
return profileNodes[name]
}
type walkProfileFunc func(level int, offset, length float32, name string, self, total int64)
func walkProfile(node *node, fn walkProfileFunc) {
// get divisor
divisor := float32(node.total)
// walk node
walkProfileNode(node, 0, 0, divisor, fn)
}
func walkProfileNode(nd *node, level int, offset, divisor float32, fn walkProfileFunc) float32 {
// get length
length := float32(nd.total) / divisor
// emit node
fn(level, offset, length, nd.name, nd.self, nd.total)
// walk children
for _, node := range nd.nodes {
offset += walkProfileNode(node, level+1, offset, divisor, fn)
}
return length
}