-
Notifications
You must be signed in to change notification settings - Fork 38
/
allocation_sampler.go
122 lines (95 loc) · 2.36 KB
/
allocation_sampler.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 internal
import (
"bytes"
"errors"
"runtime/pprof"
profile "github.com/instana/go-sensor/autoprofile/internal/pprof/profile"
)
type AllocationSampler struct{}
func NewAllocationSampler() *AllocationSampler {
return &AllocationSampler{}
}
func (as *AllocationSampler) Reset() {
}
func (as *AllocationSampler) Start() error {
return nil
}
func (as *AllocationSampler) Stop() error {
return nil
}
func (as *AllocationSampler) Profile(duration int64, timespan int64) (*Profile, error) {
hp, err := as.readHeapProfile()
if err != nil {
return nil, err
}
if hp == nil {
return nil, errors.New("no profile returned")
}
top, err := as.createAllocationCallGraph(hp)
if err != nil {
return nil, err
}
roots := make([]*CallSite, 0)
for _, child := range top.children {
roots = append(roots, child)
}
return NewProfile(CategoryMemory, TypeMemoryAllocation, UnitByte, roots, duration, timespan), nil
}
func (as *AllocationSampler) createAllocationCallGraph(p *profile.Profile) (*CallSite, error) {
// find "inuse_space" type index
inuseSpaceTypeIndex := -1
for i, s := range p.SampleType {
if s.Type == "inuse_space" {
inuseSpaceTypeIndex = i
break
}
}
// find "inuse_objects" type index
inuseObjectsTypeIndex := -1
for i, s := range p.SampleType {
if s.Type == "inuse_objects" {
inuseObjectsTypeIndex = i
break
}
}
if inuseSpaceTypeIndex == -1 || inuseObjectsTypeIndex == -1 {
return nil, errors.New("unrecognized profile data")
}
// build call graph
top := NewCallSite("", "", 0)
for _, s := range p.Sample {
if shouldSkipStack(s) {
continue
}
value := s.Value[inuseSpaceTypeIndex]
if value == 0 {
continue
}
count := s.Value[inuseObjectsTypeIndex]
current := top
for i := len(s.Location) - 1; i >= 0; i-- {
l := s.Location[i]
funcName, fileName, fileLine := readFuncInfo(l)
current = current.FindOrAddChild(funcName, fileName, fileLine)
}
current.Increment(float64(value), int64(count))
}
return top, nil
}
func (as *AllocationSampler) readHeapProfile() (*profile.Profile, error) {
buf := bytes.NewBuffer(nil)
if err := pprof.WriteHeapProfile(buf); err != nil {
return nil, err
}
p, err := profile.Parse(buf)
if err != nil {
return nil, err
}
if err := symbolizeProfile(p); err != nil {
return nil, err
}
if err := p.CheckValid(); err != nil {
return nil, err
}
return p, nil
}