You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 

567 lines
22 KiB

  1. // Copyright 2014 Google Inc. All Rights Reserved.
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package driver
  15. import (
  16. "bytes"
  17. "fmt"
  18. "io"
  19. "os"
  20. "os/exec"
  21. "runtime"
  22. "sort"
  23. "strconv"
  24. "strings"
  25. "time"
  26. "github.com/google/pprof/internal/plugin"
  27. "github.com/google/pprof/internal/report"
  28. )
  29. // commands describes the commands accepted by pprof.
  30. type commands map[string]*command
  31. // command describes the actions for a pprof command. Includes a
  32. // function for command-line completion, the report format to use
  33. // during report generation, any postprocessing functions, and whether
  34. // the command expects a regexp parameter (typically a function name).
  35. type command struct {
  36. format int // report format to generate
  37. postProcess PostProcessor // postprocessing to run on report
  38. visualizer PostProcessor // display output using some callback
  39. hasParam bool // collect a parameter from the CLI
  40. description string // single-line description text saying what the command does
  41. usage string // multi-line help text saying how the command is used
  42. }
  43. // help returns a help string for a command.
  44. func (c *command) help(name string) string {
  45. message := c.description + "\n"
  46. if c.usage != "" {
  47. message += " Usage:\n"
  48. lines := strings.Split(c.usage, "\n")
  49. for _, line := range lines {
  50. message += fmt.Sprintf(" %s\n", line)
  51. }
  52. }
  53. return message + "\n"
  54. }
  55. // AddCommand adds an additional command to the set of commands
  56. // accepted by pprof. This enables extensions to add new commands for
  57. // specialized visualization formats. If the command specified already
  58. // exists, it is overwritten.
  59. func AddCommand(cmd string, format int, post PostProcessor, desc, usage string) {
  60. pprofCommands[cmd] = &command{format, post, nil, false, desc, usage}
  61. }
  62. // SetVariableDefault sets the default value for a pprof
  63. // variable. This enables extensions to set their own defaults.
  64. func SetVariableDefault(variable, value string) {
  65. if v := pprofVariables[variable]; v != nil {
  66. v.value = value
  67. }
  68. }
  69. // PostProcessor is a function that applies post-processing to the report output
  70. type PostProcessor func(input io.Reader, output io.Writer, ui plugin.UI) error
  71. // interactiveMode is true if pprof is running on interactive mode, reading
  72. // commands from its shell.
  73. var interactiveMode = false
  74. // pprofCommands are the report generation commands recognized by pprof.
  75. var pprofCommands = commands{
  76. // Commands that require no post-processing.
  77. "comments": {report.Comments, nil, nil, false, "Output all profile comments", ""},
  78. "disasm": {report.Dis, nil, nil, true, "Output assembly listings annotated with samples", listHelp("disasm", true)},
  79. "dot": {report.Dot, nil, nil, false, "Outputs a graph in DOT format", reportHelp("dot", false, true)},
  80. "list": {report.List, nil, nil, true, "Output annotated source for functions matching regexp", listHelp("list", false)},
  81. "peek": {report.Tree, nil, nil, true, "Output callers/callees of functions matching regexp", "peek func_regex\nDisplay callers and callees of functions matching func_regex."},
  82. "raw": {report.Raw, nil, nil, false, "Outputs a text representation of the raw profile", ""},
  83. "tags": {report.Tags, nil, nil, false, "Outputs all tags in the profile", "tags [tag_regex]* [-ignore_regex]* [>file]\nList tags with key:value matching tag_regex and exclude ignore_regex."},
  84. "text": {report.Text, nil, nil, false, "Outputs top entries in text form", reportHelp("text", true, true)},
  85. "top": {report.Text, nil, nil, false, "Outputs top entries in text form", reportHelp("top", true, true)},
  86. "traces": {report.Traces, nil, nil, false, "Outputs all profile samples in text form", ""},
  87. "tree": {report.Tree, nil, nil, false, "Outputs a text rendering of call graph", reportHelp("tree", true, true)},
  88. // Save binary formats to a file
  89. "callgrind": {report.Callgrind, nil, awayFromTTY("callgraph.out"), false, "Outputs a graph in callgrind format", reportHelp("callgrind", false, true)},
  90. "proto": {report.Proto, nil, awayFromTTY("pb.gz"), false, "Outputs the profile in compressed protobuf format", ""},
  91. "topproto": {report.TopProto, nil, awayFromTTY("pb.gz"), false, "Outputs top entries in compressed protobuf format", ""},
  92. // Generate report in DOT format and postprocess with dot
  93. "gif": {report.Dot, invokeDot("gif"), awayFromTTY("gif"), false, "Outputs a graph image in GIF format", reportHelp("gif", false, true)},
  94. "pdf": {report.Dot, invokeDot("pdf"), awayFromTTY("pdf"), false, "Outputs a graph in PDF format", reportHelp("pdf", false, true)},
  95. "png": {report.Dot, invokeDot("png"), awayFromTTY("png"), false, "Outputs a graph image in PNG format", reportHelp("png", false, true)},
  96. "ps": {report.Dot, invokeDot("ps"), awayFromTTY("ps"), false, "Outputs a graph in PS format", reportHelp("ps", false, true)},
  97. // Save SVG output into a file
  98. "svg": {report.Dot, massageDotSVG(), awayFromTTY("svg"), false, "Outputs a graph in SVG format", reportHelp("svg", false, true)},
  99. // Visualize postprocessed dot output
  100. "eog": {report.Dot, invokeDot("svg"), invokeVisualizer("svg", []string{"eog"}), false, "Visualize graph through eog", reportHelp("eog", false, false)},
  101. "evince": {report.Dot, invokeDot("pdf"), invokeVisualizer("pdf", []string{"evince"}), false, "Visualize graph through evince", reportHelp("evince", false, false)},
  102. "gv": {report.Dot, invokeDot("ps"), invokeVisualizer("ps", []string{"gv --noantialias"}), false, "Visualize graph through gv", reportHelp("gv", false, false)},
  103. "web": {report.Dot, massageDotSVG(), invokeVisualizer("svg", browsers()), false, "Visualize graph through web browser", reportHelp("web", false, false)},
  104. // Visualize callgrind output
  105. "kcachegrind": {report.Callgrind, nil, invokeVisualizer("grind", kcachegrind), false, "Visualize report in KCachegrind", reportHelp("kcachegrind", false, false)},
  106. // Visualize HTML directly generated by report.
  107. "weblist": {report.WebList, nil, invokeVisualizer("html", browsers()), true, "Display annotated source in a web browser", listHelp("weblist", false)},
  108. }
  109. // pprofVariables are the configuration parameters that affect the
  110. // reported generated by pprof.
  111. var pprofVariables = variables{
  112. // Filename for file-based output formats, stdout by default.
  113. "output": &variable{stringKind, "", "", helpText("Output filename for file-based outputs")},
  114. // Comparisons.
  115. "drop_negative": &variable{boolKind, "f", "", helpText(
  116. "Ignore negative differences",
  117. "Do not show any locations with values <0.")},
  118. // Graph handling options.
  119. "call_tree": &variable{boolKind, "f", "", helpText(
  120. "Create a context-sensitive call tree",
  121. "Treat locations reached through different paths as separate.")},
  122. // Display options.
  123. "relative_percentages": &variable{boolKind, "f", "", helpText(
  124. "Show percentages relative to focused subgraph",
  125. "If unset, percentages are relative to full graph before focusing",
  126. "to facilitate comparison with original graph.")},
  127. "unit": &variable{stringKind, "minimum", "", helpText(
  128. "Measurement units to display",
  129. "Scale the sample values to this unit.",
  130. "For time-based profiles, use seconds, milliseconds, nanoseconds, etc.",
  131. "For memory profiles, use megabytes, kilobytes, bytes, etc.",
  132. "Using auto will scale each value independently to the most natural unit.")},
  133. "compact_labels": &variable{boolKind, "f", "", "Show minimal headers"},
  134. "source_path": &variable{stringKind, "", "", "Search path for source files"},
  135. "trim_path": &variable{stringKind, "", "", "Path to trim from source paths before search"},
  136. // Filtering options
  137. "nodecount": &variable{intKind, "-1", "", helpText(
  138. "Max number of nodes to show",
  139. "Uses heuristics to limit the number of locations to be displayed.",
  140. "On graphs, dotted edges represent paths through nodes that have been removed.")},
  141. "nodefraction": &variable{floatKind, "0.005", "", "Hide nodes below <f>*total"},
  142. "edgefraction": &variable{floatKind, "0.001", "", "Hide edges below <f>*total"},
  143. "trim": &variable{boolKind, "t", "", helpText(
  144. "Honor nodefraction/edgefraction/nodecount defaults",
  145. "Set to false to get the full profile, without any trimming.")},
  146. "focus": &variable{stringKind, "", "", helpText(
  147. "Restricts to samples going through a node matching regexp",
  148. "Discard samples that do not include a node matching this regexp.",
  149. "Matching includes the function name, filename or object name.")},
  150. "ignore": &variable{stringKind, "", "", helpText(
  151. "Skips paths going through any nodes matching regexp",
  152. "If set, discard samples that include a node matching this regexp.",
  153. "Matching includes the function name, filename or object name.")},
  154. "prune_from": &variable{stringKind, "", "", helpText(
  155. "Drops any functions below the matched frame.",
  156. "If set, any frames matching the specified regexp and any frames",
  157. "below it will be dropped from each sample.")},
  158. "hide": &variable{stringKind, "", "", helpText(
  159. "Skips nodes matching regexp",
  160. "Discard nodes that match this location.",
  161. "Other nodes from samples that include this location will be shown.",
  162. "Matching includes the function name, filename or object name.")},
  163. "show": &variable{stringKind, "", "", helpText(
  164. "Only show nodes matching regexp",
  165. "If set, only show nodes that match this location.",
  166. "Matching includes the function name, filename or object name.")},
  167. "show_from": &variable{stringKind, "", "", helpText(
  168. "Drops functions above the highest matched frame.",
  169. "If set, all frames above the highest match are dropped from every sample.",
  170. "Matching includes the function name, filename or object name.")},
  171. "tagfocus": &variable{stringKind, "", "", helpText(
  172. "Restricts to samples with tags in range or matched by regexp",
  173. "Use name=value syntax to limit the matching to a specific tag.",
  174. "Numeric tag filter examples: 1kb, 1kb:10kb, memory=32mb:",
  175. "String tag filter examples: foo, foo.*bar, mytag=foo.*bar")},
  176. "tagignore": &variable{stringKind, "", "", helpText(
  177. "Discard samples with tags in range or matched by regexp",
  178. "Use name=value syntax to limit the matching to a specific tag.",
  179. "Numeric tag filter examples: 1kb, 1kb:10kb, memory=32mb:",
  180. "String tag filter examples: foo, foo.*bar, mytag=foo.*bar")},
  181. "tagshow": &variable{stringKind, "", "", helpText(
  182. "Only consider tags matching this regexp",
  183. "Discard tags that do not match this regexp")},
  184. "taghide": &variable{stringKind, "", "", helpText(
  185. "Skip tags matching this regexp",
  186. "Discard tags that match this regexp")},
  187. // Heap profile options
  188. "divide_by": &variable{floatKind, "1", "", helpText(
  189. "Ratio to divide all samples before visualization",
  190. "Divide all samples values by a constant, eg the number of processors or jobs.")},
  191. "mean": &variable{boolKind, "f", "", helpText(
  192. "Average sample value over first value (count)",
  193. "For memory profiles, report average memory per allocation.",
  194. "For time-based profiles, report average time per event.")},
  195. "sample_index": &variable{stringKind, "", "", helpText(
  196. "Sample value to report (0-based index or name)",
  197. "Profiles contain multiple values per sample.",
  198. "Use sample_index=i to select the ith value (starting at 0).")},
  199. "normalize": &variable{boolKind, "f", "", helpText(
  200. "Scales profile based on the base profile.")},
  201. // Data sorting criteria
  202. "flat": &variable{boolKind, "t", "cumulative", helpText("Sort entries based on own weight")},
  203. "cum": &variable{boolKind, "f", "cumulative", helpText("Sort entries based on cumulative weight")},
  204. // Output granularity
  205. "functions": &variable{boolKind, "t", "granularity", helpText(
  206. "Aggregate at the function level.",
  207. "Ignores the filename where the function was defined.")},
  208. "filefunctions": &variable{boolKind, "t", "granularity", helpText(
  209. "Aggregate at the function level.",
  210. "Takes into account the filename where the function was defined.")},
  211. "files": &variable{boolKind, "f", "granularity", "Aggregate at the file level."},
  212. "lines": &variable{boolKind, "f", "granularity", "Aggregate at the source code line level."},
  213. "addresses": &variable{boolKind, "f", "granularity", helpText(
  214. "Aggregate at the address level.",
  215. "Includes functions' addresses in the output.")},
  216. "noinlines": &variable{boolKind, "f", "", helpText(
  217. "Ignore inlines.",
  218. "Attributes inlined functions to their first out-of-line caller.")},
  219. }
  220. func helpText(s ...string) string {
  221. return strings.Join(s, "\n") + "\n"
  222. }
  223. // usage returns a string describing the pprof commands and variables.
  224. // if commandLine is set, the output reflect cli usage.
  225. func usage(commandLine bool) string {
  226. var prefix string
  227. if commandLine {
  228. prefix = "-"
  229. }
  230. fmtHelp := func(c, d string) string {
  231. return fmt.Sprintf(" %-16s %s", c, strings.SplitN(d, "\n", 2)[0])
  232. }
  233. var commands []string
  234. for name, cmd := range pprofCommands {
  235. commands = append(commands, fmtHelp(prefix+name, cmd.description))
  236. }
  237. sort.Strings(commands)
  238. var help string
  239. if commandLine {
  240. help = " Output formats (select at most one):\n"
  241. } else {
  242. help = " Commands:\n"
  243. commands = append(commands, fmtHelp("o/options", "List options and their current values"))
  244. commands = append(commands, fmtHelp("quit/exit/^D", "Exit pprof"))
  245. }
  246. help = help + strings.Join(commands, "\n") + "\n\n" +
  247. " Options:\n"
  248. // Print help for variables after sorting them.
  249. // Collect radio variables by their group name to print them together.
  250. radioOptions := make(map[string][]string)
  251. var variables []string
  252. for name, vr := range pprofVariables {
  253. if vr.group != "" {
  254. radioOptions[vr.group] = append(radioOptions[vr.group], name)
  255. continue
  256. }
  257. variables = append(variables, fmtHelp(prefix+name, vr.help))
  258. }
  259. sort.Strings(variables)
  260. help = help + strings.Join(variables, "\n") + "\n\n" +
  261. " Option groups (only set one per group):\n"
  262. var radioStrings []string
  263. for radio, ops := range radioOptions {
  264. sort.Strings(ops)
  265. s := []string{fmtHelp(radio, "")}
  266. for _, op := range ops {
  267. s = append(s, " "+fmtHelp(prefix+op, pprofVariables[op].help))
  268. }
  269. radioStrings = append(radioStrings, strings.Join(s, "\n"))
  270. }
  271. sort.Strings(radioStrings)
  272. return help + strings.Join(radioStrings, "\n")
  273. }
  274. func reportHelp(c string, cum, redirect bool) string {
  275. h := []string{
  276. c + " [n] [focus_regex]* [-ignore_regex]*",
  277. "Include up to n samples",
  278. "Include samples matching focus_regex, and exclude ignore_regex.",
  279. }
  280. if cum {
  281. h[0] += " [-cum]"
  282. h = append(h, "-cum sorts the output by cumulative weight")
  283. }
  284. if redirect {
  285. h[0] += " >f"
  286. h = append(h, "Optionally save the report on the file f")
  287. }
  288. return strings.Join(h, "\n")
  289. }
  290. func listHelp(c string, redirect bool) string {
  291. h := []string{
  292. c + "<func_regex|address> [-focus_regex]* [-ignore_regex]*",
  293. "Include functions matching func_regex, or including the address specified.",
  294. "Include samples matching focus_regex, and exclude ignore_regex.",
  295. }
  296. if redirect {
  297. h[0] += " >f"
  298. h = append(h, "Optionally save the report on the file f")
  299. }
  300. return strings.Join(h, "\n")
  301. }
  302. // browsers returns a list of commands to attempt for web visualization.
  303. func browsers() []string {
  304. var cmds []string
  305. if userBrowser := os.Getenv("BROWSER"); userBrowser != "" {
  306. cmds = append(cmds, userBrowser)
  307. }
  308. switch runtime.GOOS {
  309. case "darwin":
  310. cmds = append(cmds, "/usr/bin/open")
  311. case "windows":
  312. cmds = append(cmds, "cmd /c start")
  313. default:
  314. // Commands opening browsers are prioritized over xdg-open, so browser()
  315. // command can be used on linux to open the .svg file generated by the -web
  316. // command (the .svg file includes embedded javascript so is best viewed in
  317. // a browser).
  318. cmds = append(cmds, []string{"chrome", "google-chrome", "chromium", "firefox", "sensible-browser"}...)
  319. if os.Getenv("DISPLAY") != "" {
  320. // xdg-open is only for use in a desktop environment.
  321. cmds = append(cmds, "xdg-open")
  322. }
  323. }
  324. return cmds
  325. }
  326. var kcachegrind = []string{"kcachegrind"}
  327. // awayFromTTY saves the output in a file if it would otherwise go to
  328. // the terminal screen. This is used to avoid dumping binary data on
  329. // the screen.
  330. func awayFromTTY(format string) PostProcessor {
  331. return func(input io.Reader, output io.Writer, ui plugin.UI) error {
  332. if output == os.Stdout && (ui.IsTerminal() || interactiveMode) {
  333. tempFile, err := newTempFile("", "profile", "."+format)
  334. if err != nil {
  335. return err
  336. }
  337. ui.PrintErr("Generating report in ", tempFile.Name())
  338. output = tempFile
  339. }
  340. _, err := io.Copy(output, input)
  341. return err
  342. }
  343. }
  344. func invokeDot(format string) PostProcessor {
  345. return func(input io.Reader, output io.Writer, ui plugin.UI) error {
  346. cmd := exec.Command("dot", "-T"+format)
  347. cmd.Stdin, cmd.Stdout, cmd.Stderr = input, output, os.Stderr
  348. if err := cmd.Run(); err != nil {
  349. return fmt.Errorf("failed to execute dot. Is Graphviz installed? Error: %v", err)
  350. }
  351. return nil
  352. }
  353. }
  354. // massageDotSVG invokes the dot tool to generate an SVG image and alters
  355. // the image to have panning capabilities when viewed in a browser.
  356. func massageDotSVG() PostProcessor {
  357. generateSVG := invokeDot("svg")
  358. return func(input io.Reader, output io.Writer, ui plugin.UI) error {
  359. baseSVG := new(bytes.Buffer)
  360. if err := generateSVG(input, baseSVG, ui); err != nil {
  361. return err
  362. }
  363. _, err := output.Write([]byte(massageSVG(baseSVG.String())))
  364. return err
  365. }
  366. }
  367. func invokeVisualizer(suffix string, visualizers []string) PostProcessor {
  368. return func(input io.Reader, output io.Writer, ui plugin.UI) error {
  369. tempFile, err := newTempFile(os.TempDir(), "pprof", "."+suffix)
  370. if err != nil {
  371. return err
  372. }
  373. deferDeleteTempFile(tempFile.Name())
  374. if _, err := io.Copy(tempFile, input); err != nil {
  375. return err
  376. }
  377. tempFile.Close()
  378. // Try visualizers until one is successful
  379. for _, v := range visualizers {
  380. // Separate command and arguments for exec.Command.
  381. args := strings.Split(v, " ")
  382. if len(args) == 0 {
  383. continue
  384. }
  385. viewer := exec.Command(args[0], append(args[1:], tempFile.Name())...)
  386. viewer.Stderr = os.Stderr
  387. if err = viewer.Start(); err == nil {
  388. // Wait for a second so that the visualizer has a chance to
  389. // open the input file. This needs to be done even if we're
  390. // waiting for the visualizer as it can be just a wrapper that
  391. // spawns a browser tab and returns right away.
  392. defer func(t <-chan time.Time) {
  393. <-t
  394. }(time.After(time.Second))
  395. // On interactive mode, let the visualizer run in the background
  396. // so other commands can be issued.
  397. if !interactiveMode {
  398. return viewer.Wait()
  399. }
  400. return nil
  401. }
  402. }
  403. return err
  404. }
  405. }
  406. // variables describe the configuration parameters recognized by pprof.
  407. type variables map[string]*variable
  408. // variable is a single configuration parameter.
  409. type variable struct {
  410. kind int // How to interpret the value, must be one of the enums below.
  411. value string // Effective value. Only values appropriate for the Kind should be set.
  412. group string // boolKind variables with the same Group != "" cannot be set simultaneously.
  413. help string // Text describing the variable, in multiple lines separated by newline.
  414. }
  415. const (
  416. // variable.kind must be one of these variables.
  417. boolKind = iota
  418. intKind
  419. floatKind
  420. stringKind
  421. )
  422. // set updates the value of a variable, checking that the value is
  423. // suitable for the variable Kind.
  424. func (vars variables) set(name, value string) error {
  425. v := vars[name]
  426. if v == nil {
  427. return fmt.Errorf("no variable %s", name)
  428. }
  429. var err error
  430. switch v.kind {
  431. case boolKind:
  432. var b bool
  433. if b, err = stringToBool(value); err == nil {
  434. if v.group != "" && !b {
  435. err = fmt.Errorf("%q can only be set to true", name)
  436. }
  437. }
  438. case intKind:
  439. _, err = strconv.Atoi(value)
  440. case floatKind:
  441. _, err = strconv.ParseFloat(value, 64)
  442. case stringKind:
  443. // Remove quotes, particularly useful for empty values.
  444. if len(value) > 1 && strings.HasPrefix(value, `"`) && strings.HasSuffix(value, `"`) {
  445. value = value[1 : len(value)-1]
  446. }
  447. }
  448. if err != nil {
  449. return err
  450. }
  451. vars[name].value = value
  452. if group := vars[name].group; group != "" {
  453. for vname, vvar := range vars {
  454. if vvar.group == group && vname != name {
  455. vvar.value = "f"
  456. }
  457. }
  458. }
  459. return err
  460. }
  461. // boolValue returns the value of a boolean variable.
  462. func (v *variable) boolValue() bool {
  463. b, err := stringToBool(v.value)
  464. if err != nil {
  465. panic("unexpected value " + v.value + " for bool ")
  466. }
  467. return b
  468. }
  469. // intValue returns the value of an intKind variable.
  470. func (v *variable) intValue() int {
  471. i, err := strconv.Atoi(v.value)
  472. if err != nil {
  473. panic("unexpected value " + v.value + " for int ")
  474. }
  475. return i
  476. }
  477. // floatValue returns the value of a Float variable.
  478. func (v *variable) floatValue() float64 {
  479. f, err := strconv.ParseFloat(v.value, 64)
  480. if err != nil {
  481. panic("unexpected value " + v.value + " for float ")
  482. }
  483. return f
  484. }
  485. // stringValue returns a canonical representation for a variable.
  486. func (v *variable) stringValue() string {
  487. switch v.kind {
  488. case boolKind:
  489. return fmt.Sprint(v.boolValue())
  490. case intKind:
  491. return fmt.Sprint(v.intValue())
  492. case floatKind:
  493. return fmt.Sprint(v.floatValue())
  494. }
  495. return v.value
  496. }
  497. func stringToBool(s string) (bool, error) {
  498. switch strings.ToLower(s) {
  499. case "true", "t", "yes", "y", "1", "":
  500. return true, nil
  501. case "false", "f", "no", "n", "0":
  502. return false, nil
  503. default:
  504. return false, fmt.Errorf(`illegal value "%s" for bool variable`, s)
  505. }
  506. }
  507. // makeCopy returns a duplicate of a set of shell variables.
  508. func (vars variables) makeCopy() variables {
  509. varscopy := make(variables, len(vars))
  510. for n, v := range vars {
  511. vcopy := *v
  512. varscopy[n] = &vcopy
  513. }
  514. return varscopy
  515. }