-
Notifications
You must be signed in to change notification settings - Fork 622
/
tree.go
444 lines (396 loc) · 9.83 KB
/
tree.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
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
package model
import (
"bytes"
"fmt"
"io"
"sort"
"strings"
dvarint "github.com/dennwc/varint"
"github.com/xlab/treeprint"
"github.com/grafana/pyroscope/pkg/og/util/varint"
"github.com/grafana/pyroscope/pkg/slices"
"github.com/grafana/pyroscope/pkg/util/minheap"
)
type Tree struct {
root []*node
}
type node struct {
parent *node
children []*node
self, total int64
name string
}
func (t *Tree) String() string {
type branch struct {
nodes []*node
treeprint.Tree
}
tree := treeprint.New()
for _, n := range t.root {
b := tree.AddBranch(fmt.Sprintf("%s: self %d total %d", n.name, n.self, n.total))
remaining := append([]*branch{}, &branch{nodes: n.children, Tree: b})
for len(remaining) > 0 {
current := remaining[0]
remaining = remaining[1:]
for _, n := range current.nodes {
if len(n.children) > 0 {
remaining = append(remaining, &branch{nodes: n.children, Tree: current.Tree.AddBranch(fmt.Sprintf("%s: self %d total %d", n.name, n.self, n.total))})
} else {
current.Tree.AddNode(fmt.Sprintf("%s: self %d total %d", n.name, n.self, n.total))
}
}
}
}
return tree.String()
}
func (t *Tree) Total() (v int64) {
for _, n := range t.root {
v += n.total
}
return v
}
func (t *Tree) InsertStack(v int64, stack ...string) {
if v <= 0 {
return
}
r := &node{children: t.root}
n := r
for s := range stack {
name := stack[s]
n.total += v
// Inlined node.insert
i, j := 0, len(n.children)
for i < j {
h := int(uint(i+j) >> 1)
if n.children[h].name < name {
i = h + 1
} else {
j = h
}
}
if i < len(n.children) && n.children[i].name == name {
n = n.children[i]
} else {
child := &node{parent: n, name: name}
n.children = append(n.children, child)
copy(n.children[i+1:], n.children[i:])
n.children[i] = child
n = child
}
}
// Leaf.
n.total += v
n.self += v
t.root = r.children
}
func (t *Tree) WriteCollapsed(dst io.Writer) {
t.IterateStacks(func(_ string, self int64, stack []string) {
slices.Reverse(stack)
_, _ = fmt.Fprintf(dst, "%s %d\n", strings.Join(stack, ";"), self)
})
}
func (t *Tree) IterateStacks(cb func(name string, self int64, stack []string)) {
nodes := make([]*node, len(t.root), 1024)
stack := make([]string, 0, 64)
copy(nodes, t.root)
for len(nodes) > 0 {
n := nodes[0]
self := n.self
label := n.name
if self > 0 {
current := n
stack = stack[:0]
for current != nil && current.parent != nil {
stack = append(stack, current.name)
current = current.parent
}
cb(label, self, stack)
}
nodes = nodes[1:]
nodes = append(nodes, n.children...)
}
}
// Default Depth First Search slice capacity. The value should be equal
// to the number of all the siblings of the tree leaf ascendants.
//
// Chosen empirically. For very deep stacks (>128), it's likely that the
// slice will grow to 1-4K nodes, depending on the trace branching.
const defaultDFSSize = 128
func (t *Tree) Merge(src *Tree) {
if t.Total() == 0 && src.Total() > 0 {
*t = *src
return
}
if src.Total() == 0 {
return
}
srcNodes := make([]*node, 0, defaultDFSSize)
srcRoot := &node{children: src.root}
srcNodes = append(srcNodes, srcRoot)
dstNodes := make([]*node, 0, defaultDFSSize)
dstRoot := &node{children: t.root}
dstNodes = append(dstNodes, dstRoot)
var st, dt *node
for len(srcNodes) > 0 {
st, srcNodes = srcNodes[len(srcNodes)-1], srcNodes[:len(srcNodes)-1]
dt, dstNodes = dstNodes[len(dstNodes)-1], dstNodes[:len(dstNodes)-1]
dt.self += st.self
dt.total += st.total
for _, srcChildNode := range st.children {
// Note that we don't copy the name, but reference it.
dstChildNode := dt.insert(srcChildNode.name)
srcNodes = append(srcNodes, srcChildNode)
dstNodes = append(dstNodes, dstChildNode)
}
}
t.root = dstRoot.children
}
func (t *Tree) FormatNodeNames(fn func(string) string) {
nodes := make([]*node, 0, defaultDFSSize)
nodes = append(nodes, &node{children: t.root})
var n *node
var fix bool
for len(nodes) > 0 {
n, nodes = nodes[len(nodes)-1], nodes[:len(nodes)-1]
m := n.name
n.name = fn(m)
if m != n.name {
fix = true
}
nodes = append(nodes, n.children...)
}
if !fix {
return
}
t.Fix()
}
// Fix re-establishes order of nodes and merges duplicates.
func (t *Tree) Fix() {
if len(t.root) == 0 {
return
}
r := &node{children: t.root}
for _, n := range r.children {
n.parent = r
}
nodes := make([][]*node, 0, defaultDFSSize)
nodes = append(nodes, r.children)
var n []*node
for len(nodes) > 0 {
n, nodes = nodes[len(nodes)-1], nodes[:len(nodes)-1]
if len(n) == 0 {
continue
}
sort.Slice(n, func(i, j int) bool {
return n[i].name < n[j].name
})
p := n[0]
j := 1
for _, c := range n[1:] {
if p.name == c.name {
for _, x := range c.children {
x.parent = p
}
p.children = append(p.children, c.children...)
p.total += c.total
p.self += c.self
continue
}
p = c
n[j] = c
j++
}
n = n[:j]
for _, c := range n {
c.parent.children = n
nodes = append(nodes, c.children)
}
}
t.root = r.children
}
func (n *node) String() string {
return fmt.Sprintf("{%s: self %d total %d}", n.name, n.self, n.total)
}
func (n *node) insert(name string) *node {
i := sort.Search(len(n.children), func(i int) bool {
return n.children[i].name >= name
})
if i < len(n.children) && n.children[i].name == name {
return n.children[i]
}
// We don't clone the name: it is caller responsibility
// to maintain the memory ownership.
child := &node{parent: n, name: name}
n.children = append(n.children, child)
copy(n.children[i+1:], n.children[i:])
n.children[i] = child
return child
}
// minValue returns the minimum "total" value a node in a tree has to have to show up in
// the resulting flamegraph
func (t *Tree) minValue(maxNodes int64) int64 {
if maxNodes < 1 {
return 0
}
nodes := make([]*node, 0, max(int64(len(t.root)), defaultDFSSize))
treeSize := t.size(nodes)
if treeSize <= maxNodes {
return 0
}
h := make([]int64, 0, maxNodes)
nodes = append(nodes[:0], t.root...)
var n *node
for len(nodes) > 0 {
last := len(nodes) - 1
n, nodes = nodes[last], nodes[:last]
if len(h) >= int(maxNodes) {
if n.total > h[0] {
h = minheap.Pop(h)
} else {
continue
}
}
h = minheap.Push(h, n.total)
nodes = append(nodes, n.children...)
}
if len(h) < int(maxNodes) {
return 0
}
return h[0]
}
// size reports number of nodes the tree consists of.
// Provided buffer used for DFS traversal.
func (t *Tree) size(buf []*node) int64 {
nodes := append(buf, t.root...)
var s int64
var n *node
for len(nodes) > 0 {
last := len(nodes) - 1
n, nodes = nodes[last], nodes[:last]
nodes = append(nodes, n.children...)
s++
}
return s
}
const truncatedNodeName = "other"
var truncatedNodeNameBytes = []byte(truncatedNodeName)
// Bytes returns marshaled tree byte representation; the number of nodes
// is limited to maxNodes. The function modifies the tree: truncated nodes
// are removed from the tree in place.
func (t *Tree) Bytes(maxNodes int64) []byte {
var buf bytes.Buffer
_ = t.MarshalTruncate(&buf, maxNodes)
return buf.Bytes()
}
// MarshalTruncate writes tree byte representation to the writer provider,
// the number of nodes is limited to maxNodes. The function modifies
// the tree: truncated nodes are removed from the tree.
func (t *Tree) MarshalTruncate(w io.Writer, maxNodes int64) (err error) {
if len(t.root) == 0 {
return nil
}
vw := varint.NewWriter()
minVal := t.minValue(maxNodes)
nodes := make([]*node, 1, defaultDFSSize)
nodes[0] = &node{children: t.root} // Virtual root node.
var n *node
for len(nodes) > 0 {
last := len(nodes) - 1
n, nodes = nodes[last], nodes[:last]
if _, _ = vw.Write(w, uint64(len(n.name))); err != nil {
return err
}
if _, _ = w.Write(unsafeStringBytes(n.name)); err != nil {
return err
}
if _, err = vw.Write(w, uint64(n.self)); err != nil {
return err
}
var other int64
var j int
for _, cn := range n.children {
if cn.total >= minVal || cn.name == truncatedNodeName {
n.children[j] = cn
j++
} else {
other += cn.total
}
}
n.children = n.children[:j]
if other > 0 {
o := n.insert(truncatedNodeName)
o.total += other
o.self += other
}
if len(n.children) > 0 {
nodes = append(nodes, n.children...)
}
if _, err = vw.Write(w, uint64(len(n.children))); err != nil {
return err
}
}
return nil
}
var errMalformedTreeBytes = fmt.Errorf("malformed tree bytes")
const estimateBytesPerNode = 16 // Chosen empirically.
func MustUnmarshalTree(b []byte) *Tree {
if len(b) == 0 {
return new(Tree)
}
t, err := UnmarshalTree(b)
if err != nil {
panic(err)
}
return t
}
func UnmarshalTree(b []byte) (*Tree, error) {
t := new(Tree)
if len(b) < 2 {
return t, nil
}
size := estimateBytesPerNode
if e := len(b) / estimateBytesPerNode; e > estimateBytesPerNode {
size = e
}
parents := make([]*node, 1, size)
// Virtual root node.
root := new(node)
parents[0] = root
var parent *node
var offset int
for len(parents) > 0 {
parent, parents = parents[len(parents)-1], parents[:len(parents)-1]
nameLen, o := dvarint.Uvarint(b[offset:])
if o < 0 {
return nil, errMalformedTreeBytes
}
offset += o
// Note that we allocate a string, instead of referencing b's capacity.
name := string(b[offset : offset+int(nameLen)])
offset += int(nameLen)
value, o := dvarint.Uvarint(b[offset:])
if o < 0 {
return nil, errMalformedTreeBytes
}
offset += o
childrenLen, o := dvarint.Uvarint(b[offset:])
if o < 0 {
return nil, errMalformedTreeBytes
}
offset += o
n := parent.insert(name)
n.children = make([]*node, 0, childrenLen)
n.self = int64(value)
pn := n
for pn.parent != nil {
pn.total += n.self
pn = pn.parent
}
for i := uint64(0); i < childrenLen; i++ {
parents = append(parents, n)
}
}
// Remove the virtual root.
t.root = root.children[0].children
return t, nil
}