-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtrace.go
More file actions
211 lines (189 loc) · 5.58 KB
/
trace.go
File metadata and controls
211 lines (189 loc) · 5.58 KB
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
package main
import (
"fmt"
"io"
"os"
"regexp"
"sort"
"strings"
"github.com/spf13/cobra"
)
func newTraceCmd() *cobra.Command {
var shared sharedFlags
var method string
var minPct float64
var fqn bool
var hide string
cmd := &cobra.Command{
Use: "trace <file>",
Short: "Hottest path from a method to leaf (-m required)",
Args: cobra.ExactArgs(1),
RunE: func(cmd *cobra.Command, args []string) error {
if method == "" {
return fmt.Errorf("-m/--method required")
}
pctx, err := preprocessProfile(shared.toOpts(args[0], "trace"))
if err != nil {
return err
}
sf := pctx.sf
if hide != "" {
re, err := regexp.Compile(hide)
if err != nil {
return fmt.Errorf("invalid --hide regex: %v", err)
}
sf = sf.hideFrames(re)
}
cmdTrace(sf, method, minPct, fqn)
return nil
},
}
shared.register(cmd)
cmd.Flags().StringVarP(&method, "method", "m", "", "Substring match on method name (required)")
cmd.Flags().Float64Var(&minPct, "min-pct", 0.5, "Hide nodes below this %")
cmd.Flags().BoolVar(&fqn, "fqn", false, "Show fully-qualified names")
cmd.Flags().StringVar(&hide, "hide", "", "Remove matching frames before analysis (regex)")
return cmd
}
func cmdTrace(sf *stackFile, method string, minPct float64, fqn bool) {
if sf.totalSamples == 0 {
fmt.Fprintln(os.Stdout, "no samples (empty profile or all filtered out)")
return
}
writeTrace(os.Stdout, sf, method, minPct, fqn)
}
func writeTrace(w io.Writer, sf *stackFile, method string, minPct float64, fqn bool) {
pt := aggregatePaths(sf, method, func(frames []string, j int) []string {
path := make([]string, len(frames)-j)
for k := j; k < len(frames); k++ {
if fqn {
path[k-j] = displayName(frames[k], true)
} else {
path[k-j] = shortName(frames[k])
}
}
return path
})
if len(pt.samples) == 0 {
noMatchMessage(w, sf, method)
return
}
if len(pt.matchedNames) > 1 {
names := make([]string, 0, len(pt.matchedNames))
for n := range pt.matchedNames {
names = append(names, n)
}
sort.Strings(names)
fmt.Fprintf(w, "# matched %d methods: %s\n", len(pt.matchedNames), strings.Join(names, ", "))
}
// Collect roots sorted by sample count descending, then name for stability.
type rootEntry struct {
name string
samples int
}
roots := make(map[string]bool)
for key := range pt.samples {
roots[strings.SplitN(key, ";", 2)[0]] = true
}
var sortedRoots []rootEntry
for r := range roots {
sortedRoots = append(sortedRoots, rootEntry{r, pt.samples[r]})
}
sort.Slice(sortedRoots, func(i, j int) bool {
if sortedRoots[i].samples != sortedRoots[j].samples {
return sortedRoots[i].samples > sortedRoots[j].samples
}
return sortedRoots[i].name < sortedRoots[j].name
})
for _, root := range sortedRoots {
ftraceHottestPath(w, pt, root.name, minPct)
}
}
type traceChild struct {
key string
name string
samples int
}
// childrenAboveMinPct returns direct children of prefix sorted by samples
// descending, with ties broken by name ascending.
func childrenAboveMinPct(pt *pathTree, prefix string, minPct float64) []traceChild {
var children []traceChild
pfx := prefix + ";"
depth := strings.Count(prefix, ";") + 1
for key, cnt := range pt.samples {
if strings.HasPrefix(key, pfx) && strings.Count(key, ";") == depth {
childPct := pctOf(cnt, pt.totalSamples)
if childPct >= minPct {
parts := strings.Split(key, ";")
children = append(children, traceChild{key, parts[len(parts)-1], cnt})
}
}
}
sort.Slice(children, func(i, j int) bool {
if children[i].samples != children[j].samples {
return children[i].samples > children[j].samples
}
return children[i].name < children[j].name
})
return children
}
// ftraceHottestPath walks from root following the hottest child at each level.
func ftraceHottestPath(w io.Writer, pt *pathTree, rootKey string, minPct float64) {
prefix := rootKey
indent := 0
// siblingAnnotation is computed when we pick a child, then printed
// on that child's line (the next iteration).
siblingAnnotation := ""
for {
samples := pt.samples[prefix]
pct := pctOf(samples, pt.totalSamples)
if pct < minPct {
break
}
parts := strings.Split(prefix, ";")
name := parts[len(parts)-1]
pad := strings.Repeat(" ", indent)
children := childrenAboveMinPct(pt, prefix, minPct)
isLeaf := len(children) == 0
// Build line.
line := fmt.Sprintf("%s[%.1f%%] %s", pad, pct, name)
// Append sibling annotation (carried from previous iteration).
line += siblingAnnotation
// Leaf: append self-time annotation.
if isLeaf {
selfCt := pt.selfSamples[prefix]
selfPct := pctOf(selfCt, pt.totalSamples)
if selfCt > 0 && selfPct >= minPct {
line += fmt.Sprintf(" ← self=%.1f%%", selfPct)
}
fmt.Fprintln(w, line)
fmt.Fprintf(w, "Hottest leaf: %s (self=%.1f%%)\n", name, selfPct)
break
}
fmt.Fprintln(w, line)
// Pick hottest child, compute sibling annotation for next iteration.
hottest := children[0]
siblingAnnotation = ""
if len(children) > 1 {
next := children[1]
nextPct := pctOf(next.samples, pt.totalSamples)
n := len(children) - 1
word := "siblings"
if n == 1 {
word = "sibling"
}
siblingAnnotation = fmt.Sprintf(" (+%d %s, next: %.1f%% %s)", n, word, nextPct, next.name)
}
prefix = hottest.key
indent++
}
}
// computeTraceString returns the hottest-path trace for the given method as a string.
func computeTraceString(sf *stackFile, method string, minPct float64, fqn bool) string {
if sf.totalSamples == 0 {
return ""
}
var buf strings.Builder
writeTrace(&buf, sf, method, minPct, fqn)
return strings.TrimRight(buf.String(), "\n")
}