summaryrefslogtreecommitdiff
path: root/src/cmd/pprof/internal/driver/interactive.go
blob: 13009bf7e9f66a8b32bf8b2f4d52470e49d90d76 (plain)
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
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
// Copyright 2014 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

package driver

import (
	"fmt"
	"io"
	"regexp"
	"sort"
	"strconv"
	"strings"

	"cmd/pprof/internal/commands"
	"cmd/pprof/internal/plugin"
	"cmd/pprof/internal/profile"
)

var profileFunctionNames = []string{}

// functionCompleter replaces provided substring with a function
// name retrieved from a profile if a single match exists. Otherwise,
// it returns unchanged substring. It defaults to no-op if the profile
// is not specified.
func functionCompleter(substring string) string {
	found := ""
	for _, fName := range profileFunctionNames {
		if strings.Contains(fName, substring) {
			if found != "" {
				return substring
			}
			found = fName
		}
	}
	if found != "" {
		return found
	}
	return substring
}

// updateAutoComplete enhances autocompletion with information that can be
// retrieved from the profile
func updateAutoComplete(p *profile.Profile) {
	profileFunctionNames = nil // remove function names retrieved previously
	for _, fn := range p.Function {
		profileFunctionNames = append(profileFunctionNames, fn.Name)
	}
}

// splitCommand splits the command line input into tokens separated by
// spaces. Takes care to separate commands of the form 'top10' into
// two tokens: 'top' and '10'
func splitCommand(input string) []string {
	fields := strings.Fields(input)
	if num := strings.IndexAny(fields[0], "0123456789"); num != -1 {
		inputNumber := fields[0][num:]
		fields[0] = fields[0][:num]
		fields = append([]string{fields[0], inputNumber}, fields[1:]...)
	}
	return fields
}

// interactive displays a prompt and reads commands for profile
// manipulation/visualization.
func interactive(p *profile.Profile, obj plugin.ObjTool, ui plugin.UI, f *flags) error {
	updateAutoComplete(p)

	// Enter command processing loop.
	ui.Print("Entering interactive mode (type \"help\" for commands)")
	ui.SetAutoComplete(commands.NewCompleter(f.commands))

	for {
		input, err := readCommand(p, ui, f)
		if err != nil {
			if err != io.EOF {
				return err
			}
			if input == "" {
				return nil
			}
		}
		// Process simple commands.
		switch input {
		case "":
			continue
		case ":":
			f.flagFocus = newString("")
			f.flagIgnore = newString("")
			f.flagTagFocus = newString("")
			f.flagTagIgnore = newString("")
			f.flagHide = newString("")
			continue
		}

		fields := splitCommand(input)
		// Process report generation commands.
		if _, ok := f.commands[fields[0]]; ok {
			if err := generateReport(p, fields, obj, ui, f); err != nil {
				if err == io.EOF {
					return nil
				}
				ui.PrintErr(err)
			}
			continue
		}

		switch cmd := fields[0]; cmd {
		case "help":
			commandHelp(fields, ui, f)
			continue
		case "exit", "quit":
			return nil
		}

		// Process option settings.
		if of, err := optFlags(p, input, f); err == nil {
			f = of
		} else {
			ui.PrintErr("Error: ", err.Error())
		}
	}
}

func generateReport(p *profile.Profile, cmd []string, obj plugin.ObjTool, ui plugin.UI, f *flags) error {
	prof := p.Copy()

	cf, err := cmdFlags(prof, cmd, ui, f)
	if err != nil {
		return err
	}

	return generate(true, prof, obj, ui, cf)
}

// validateRegex checks if a string is a valid regular expression.
func validateRegex(v string) error {
	_, err := regexp.Compile(v)
	return err
}

// readCommand prompts for and reads the next command.
func readCommand(p *profile.Profile, ui plugin.UI, f *flags) (string, error) {
	//ui.Print("Options:\n", f.String(p))
	s, err := ui.ReadLine()
	return strings.TrimSpace(s), err
}

func commandHelp(_ []string, ui plugin.UI, f *flags) error {
	help := `
 Commands:
   cmd [n] [--cum] [focus_regex]* [-ignore_regex]*
       Produce a text report with the top n entries.
       Include samples matching focus_regex, and exclude ignore_regex.
       Add --cum to sort using cumulative data.
       Available commands:
`
	var commands []string
	for name, cmd := range f.commands {
		commands = append(commands, fmt.Sprintf("         %-12s %s", name, cmd.Usage))
	}
	sort.Strings(commands)

	help = help + strings.Join(commands, "\n") + `
   peek func_regex
       Display callers and callees of functions matching func_regex.

   dot [n] [focus_regex]* [-ignore_regex]* [>file]
       Produce an annotated callgraph with the top n entries.
       Include samples matching focus_regex, and exclude ignore_regex.
       For other outputs, replace dot with:
       - Graphic formats: dot, svg, pdf, ps, gif, png (use > to name output file)
       - Graph viewer:    gv, web, evince, eog

   callgrind [n] [focus_regex]* [-ignore_regex]* [>file]
       Produce a file in callgrind-compatible format.
       Include samples matching focus_regex, and exclude ignore_regex.

   weblist func_regex [-ignore_regex]*
       Show annotated source with interspersed assembly in a web browser.

   list func_regex [-ignore_regex]*
       Print source for routines matching func_regex, and exclude ignore_regex.

   disasm func_regex [-ignore_regex]*
       Disassemble routines matching func_regex, and exclude ignore_regex.

   tags tag_regex [-ignore_regex]*
       List tags with key:value matching tag_regex and exclude ignore_regex.

   quit/exit/^D
 	     Exit pprof.

   option=value
       The following options can be set individually:
           cum/flat:           Sort entries based on cumulative or flat data
           call_tree:          Build context-sensitive call trees
           nodecount:          Max number of entries to display
           nodefraction:       Min frequency ratio of nodes to display
           edgefraction:       Min frequency ratio of edges to display
           focus/ignore:       Regexp to include/exclude samples by name/file
           tagfocus/tagignore: Regexp or value range to filter samples by tag
                               eg "1mb", "1mb:2mb", ":64kb"

           functions:          Level of aggregation for sample data
           files:
           lines:
           addresses:

           unit:               Measurement unit to use on reports

           Sample value selection by index:
            sample_index:      Index of sample value to display
            mean:              Average sample value over first value

           Sample value selection by name:
            alloc_space        for heap profiles
            alloc_objects
            inuse_space
            inuse_objects

            total_delay        for contention profiles
            mean_delay
            contentions

   :   Clear focus/ignore/hide/tagfocus/tagignore`

	ui.Print(help)
	return nil
}

// cmdFlags parses the options of an interactive command and returns
// an updated flags object.
func cmdFlags(prof *profile.Profile, input []string, ui plugin.UI, f *flags) (*flags, error) {
	cf := *f

	var focus, ignore string
	output := *cf.flagOutput
	nodeCount := *cf.flagNodeCount
	cmd := input[0]

	// Update output flags based on parameters.
	tokens := input[1:]
	for p := 0; p < len(tokens); p++ {
		t := tokens[p]
		if t == "" {
			continue
		}
		if c, err := strconv.ParseInt(t, 10, 32); err == nil {
			nodeCount = int(c)
			continue
		}
		switch t[0] {
		case '>':
			if len(t) > 1 {
				output = t[1:]
				continue
			}
			// find next token
			for p++; p < len(tokens); p++ {
				if tokens[p] != "" {
					output = tokens[p]
					break
				}
			}
		case '-':
			if t == "--cum" || t == "-cum" {
				cf.flagCum = newBool(true)
				continue
			}
			ignore = catRegex(ignore, t[1:])
		default:
			focus = catRegex(focus, t)
		}
	}

	pcmd, ok := f.commands[cmd]
	if !ok {
		return nil, fmt.Errorf("Unexpected parse failure: %v", input)
	}
	// Reset flags
	cf.flagCommands = make(map[string]*bool)
	cf.flagParamCommands = make(map[string]*string)

	if !pcmd.HasParam {
		cf.flagCommands[cmd] = newBool(true)

		switch cmd {
		case "tags":
			cf.flagTagFocus = newString(focus)
			cf.flagTagIgnore = newString(ignore)
		default:
			cf.flagFocus = newString(catRegex(*cf.flagFocus, focus))
			cf.flagIgnore = newString(catRegex(*cf.flagIgnore, ignore))
		}
	} else {
		if focus == "" {
			focus = "."
		}
		cf.flagParamCommands[cmd] = newString(focus)
		cf.flagIgnore = newString(catRegex(*cf.flagIgnore, ignore))
	}

	if nodeCount < 0 {
		switch cmd {
		case "text", "top":
			// Default text/top to 10 nodes on interactive mode
			nodeCount = 10
		default:
			nodeCount = 80
		}
	}

	cf.flagNodeCount = newInt(nodeCount)
	cf.flagOutput = newString(output)

	// Do regular flags processing
	if err := processFlags(prof, ui, &cf); err != nil {
		cf.usage(ui)
		return nil, err
	}

	return &cf, nil
}

func catRegex(a, b string) string {
	if a == "" {
		return b
	}
	if b == "" {
		return a
	}
	return a + "|" + b
}

// optFlags parses an interactive option setting and returns
// an updated flags object.
func optFlags(p *profile.Profile, input string, f *flags) (*flags, error) {
	inputs := strings.SplitN(input, "=", 2)
	option := strings.ToLower(strings.TrimSpace(inputs[0]))
	var value string
	if len(inputs) == 2 {
		value = strings.TrimSpace(inputs[1])
	}

	of := *f

	var err error
	var bv bool
	var uv uint64
	var fv float64

	switch option {
	case "cum":
		if bv, err = parseBool(value); err != nil {
			return nil, err
		}
		of.flagCum = newBool(bv)
	case "flat":
		if bv, err = parseBool(value); err != nil {
			return nil, err
		}
		of.flagCum = newBool(!bv)
	case "call_tree":
		if bv, err = parseBool(value); err != nil {
			return nil, err
		}
		of.flagCallTree = newBool(bv)
	case "unit":
		of.flagDisplayUnit = newString(value)
	case "sample_index":
		if uv, err = strconv.ParseUint(value, 10, 32); err != nil {
			return nil, err
		}
		if ix := int(uv); ix < 0 || ix >= len(p.SampleType) {
			return nil, fmt.Errorf("sample_index out of range [0..%d]", len(p.SampleType)-1)
		}
		of.flagSampleIndex = newInt(int(uv))
	case "mean":
		if bv, err = parseBool(value); err != nil {
			return nil, err
		}
		of.flagMean = newBool(bv)
	case "nodecount":
		if uv, err = strconv.ParseUint(value, 10, 32); err != nil {
			return nil, err
		}
		of.flagNodeCount = newInt(int(uv))
	case "nodefraction":
		if fv, err = strconv.ParseFloat(value, 64); err != nil {
			return nil, err
		}
		of.flagNodeFraction = newFloat64(fv)
	case "edgefraction":
		if fv, err = strconv.ParseFloat(value, 64); err != nil {
			return nil, err
		}
		of.flagEdgeFraction = newFloat64(fv)
	case "focus":
		if err = validateRegex(value); err != nil {
			return nil, err
		}
		of.flagFocus = newString(value)
	case "ignore":
		if err = validateRegex(value); err != nil {
			return nil, err
		}
		of.flagIgnore = newString(value)
	case "tagfocus":
		if err = validateRegex(value); err != nil {
			return nil, err
		}
		of.flagTagFocus = newString(value)
	case "tagignore":
		if err = validateRegex(value); err != nil {
			return nil, err
		}
		of.flagTagIgnore = newString(value)
	case "hide":
		if err = validateRegex(value); err != nil {
			return nil, err
		}
		of.flagHide = newString(value)
	case "addresses", "files", "lines", "functions":
		if bv, err = parseBool(value); err != nil {
			return nil, err
		}
		if !bv {
			return nil, fmt.Errorf("select one of addresses/files/lines/functions")
		}
		setGranularityToggle(option, &of)
	default:
		if ix := findSampleIndex(p, "", option); ix >= 0 {
			of.flagSampleIndex = newInt(ix)
		} else if ix := findSampleIndex(p, "total_", option); ix >= 0 {
			of.flagSampleIndex = newInt(ix)
			of.flagMean = newBool(false)
		} else if ix := findSampleIndex(p, "mean_", option); ix >= 1 {
			of.flagSampleIndex = newInt(ix)
			of.flagMean = newBool(true)
		} else {
			return nil, fmt.Errorf("unrecognized command: %s", input)
		}
	}
	return &of, nil
}

// parseBool parses a string as a boolean value.
func parseBool(v string) (bool, error) {
	switch strings.ToLower(v) {
	case "true", "t", "yes", "y", "1", "":
		return true, nil
	case "false", "f", "no", "n", "0":
		return false, nil
	}
	return false, fmt.Errorf(`illegal input "%s" for bool value`, v)
}

func findSampleIndex(p *profile.Profile, prefix, sampleType string) int {
	if !strings.HasPrefix(sampleType, prefix) {
		return -1
	}
	sampleType = strings.TrimPrefix(sampleType, prefix)
	for i, r := range p.SampleType {
		if r.Type == sampleType {
			return i
		}
	}
	return -1
}

// setGranularityToggle manages the set of granularity options. These
// operate as a toggle; turning one on turns the others off.
func setGranularityToggle(o string, fl *flags) {
	t, f := newBool(true), newBool(false)
	fl.flagFunctions = f
	fl.flagFiles = f
	fl.flagLines = f
	fl.flagAddresses = f
	switch o {
	case "functions":
		fl.flagFunctions = t
	case "files":
		fl.flagFiles = t
	case "lines":
		fl.flagLines = t
	case "addresses":
		fl.flagAddresses = t
	default:
		panic(fmt.Errorf("unexpected option %s", o))
	}
}