暂无描述

interactive.go 12KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467
  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. "fmt"
  17. "io"
  18. "regexp"
  19. "sort"
  20. "strconv"
  21. "strings"
  22. "github.com/google/pprof/internal/plugin"
  23. "github.com/google/pprof/internal/report"
  24. "github.com/google/pprof/profile"
  25. )
  26. var commentStart = "//:" // Sentinel for comments on options
  27. var tailDigitsRE = regexp.MustCompile("[0-9]+$")
  28. // interactive starts a shell to read pprof commands.
  29. func interactive(p *profile.Profile, o *plugin.Options) error {
  30. // Enter command processing loop.
  31. o.UI.SetAutoComplete(newCompleter(functionNames(p)))
  32. pprofVariables.set("compact_labels", "true")
  33. pprofVariables["sample_index"].help += fmt.Sprintf("Or use sample_index=name, with name in %v.\n", sampleTypes(p))
  34. // Do not wait for the visualizer to complete, to allow multiple
  35. // graphs to be visualized simultaneously.
  36. interactiveMode = true
  37. shortcuts := profileShortcuts(p)
  38. // Get all groups in pprofVariables to allow for clearer error messages.
  39. groups := groupOptions(pprofVariables)
  40. greetings(p, o.UI)
  41. for {
  42. input, err := o.UI.ReadLine("(pprof) ")
  43. if err != nil {
  44. if err != io.EOF {
  45. return err
  46. }
  47. if input == "" {
  48. return nil
  49. }
  50. }
  51. for _, input := range shortcuts.expand(input) {
  52. // Process assignments of the form variable=value
  53. if s := strings.SplitN(input, "=", 2); len(s) > 0 {
  54. name := strings.TrimSpace(s[0])
  55. var value string
  56. if len(s) == 2 {
  57. value = s[1]
  58. if comment := strings.LastIndex(value, commentStart); comment != -1 {
  59. value = value[:comment]
  60. }
  61. value = strings.TrimSpace(value)
  62. }
  63. if v := pprofVariables[name]; v != nil {
  64. // All non-bool options require inputs
  65. if v.kind != boolKind && value == "" {
  66. o.UI.PrintErr(fmt.Errorf("please specify a value, e.g. %s=<val>", name))
  67. continue
  68. }
  69. if name == "sample_index" {
  70. // Error check sample_index=xxx to ensure xxx is a valid sample type.
  71. index, err := p.SampleIndexByName(value)
  72. if err != nil {
  73. o.UI.PrintErr(err)
  74. continue
  75. }
  76. value = p.SampleType[index].Type
  77. }
  78. if err := pprofVariables.set(name, value); err != nil {
  79. o.UI.PrintErr(err)
  80. }
  81. continue
  82. }
  83. // Allow group=variable syntax by converting into variable="".
  84. if v := pprofVariables[value]; v != nil && v.group == name {
  85. if err := pprofVariables.set(value, ""); err != nil {
  86. o.UI.PrintErr(err)
  87. }
  88. continue
  89. } else if okValues := groups[name]; okValues != nil {
  90. o.UI.PrintErr(fmt.Errorf("unrecognized value for %s: %q. Use one of %s", name, value, strings.Join(okValues, ", ")))
  91. continue
  92. }
  93. }
  94. tokens := strings.Fields(input)
  95. if len(tokens) == 0 {
  96. continue
  97. }
  98. switch tokens[0] {
  99. case "o", "options":
  100. printCurrentOptions(p, o.UI)
  101. continue
  102. case "exit", "quit", "q":
  103. return nil
  104. case "help":
  105. commandHelp(strings.Join(tokens[1:], " "), o.UI)
  106. continue
  107. }
  108. args, vars, err := parseCommandLine(tokens)
  109. if err == nil {
  110. err = generateReportWrapper(p, args, vars, o)
  111. }
  112. if err != nil {
  113. o.UI.PrintErr(err)
  114. }
  115. }
  116. }
  117. }
  118. // groupOptions returns a map containing all non-empty groups
  119. // mapped to an array of the option names in that group in
  120. // sorted order.
  121. func groupOptions(vars variables) map[string][]string {
  122. groups := make(map[string][]string)
  123. for name, option := range vars {
  124. group := option.group
  125. if group != "" {
  126. groups[group] = append(groups[group], name)
  127. }
  128. }
  129. for _, names := range groups {
  130. sort.Strings(names)
  131. }
  132. return groups
  133. }
  134. var generateReportWrapper = generateReport // For testing purposes.
  135. // greetings prints a brief welcome and some overall profile
  136. // information before accepting interactive commands.
  137. func greetings(p *profile.Profile, ui plugin.UI) {
  138. numLabelUnits := identifyNumLabelUnits(p, ui)
  139. ropt, err := reportOptions(p, numLabelUnits, pprofVariables)
  140. if err == nil {
  141. rpt := report.New(p, ropt)
  142. ui.Print(strings.Join(report.ProfileLabels(rpt), "\n"))
  143. if rpt.Total() == 0 && len(p.SampleType) > 1 {
  144. ui.Print(`No samples were found with the default sample value type.`)
  145. ui.Print(`Try "sample_index" command to analyze different sample values.`, "\n")
  146. }
  147. }
  148. ui.Print(`Entering interactive mode (type "help" for commands, "o" for options)`)
  149. }
  150. // shortcuts represents composite commands that expand into a sequence
  151. // of other commands.
  152. type shortcuts map[string][]string
  153. func (a shortcuts) expand(input string) []string {
  154. input = strings.TrimSpace(input)
  155. if a != nil {
  156. if r, ok := a[input]; ok {
  157. return r
  158. }
  159. }
  160. return []string{input}
  161. }
  162. var pprofShortcuts = shortcuts{
  163. ":": []string{"focus=", "ignore=", "hide=", "tagfocus=", "tagignore="},
  164. }
  165. // profileShortcuts creates macros for convenience and backward compatibility.
  166. func profileShortcuts(p *profile.Profile) shortcuts {
  167. s := pprofShortcuts
  168. // Add shortcuts for sample types
  169. for _, st := range p.SampleType {
  170. command := fmt.Sprintf("sample_index=%s", st.Type)
  171. s[st.Type] = []string{command}
  172. s["total_"+st.Type] = []string{"mean=0", command}
  173. s["mean_"+st.Type] = []string{"mean=1", command}
  174. }
  175. return s
  176. }
  177. func sampleTypes(p *profile.Profile) []string {
  178. types := make([]string, len(p.SampleType))
  179. for i, t := range p.SampleType {
  180. types[i] = t.Type
  181. }
  182. return types
  183. }
  184. func printCurrentOptions(p *profile.Profile, ui plugin.UI) {
  185. var args []string
  186. type groupInfo struct {
  187. set string
  188. values []string
  189. }
  190. groups := make(map[string]*groupInfo)
  191. for n, o := range pprofVariables {
  192. v := o.stringValue()
  193. comment := ""
  194. if g := o.group; g != "" {
  195. gi, ok := groups[g]
  196. if !ok {
  197. gi = &groupInfo{}
  198. groups[g] = gi
  199. }
  200. if o.boolValue() {
  201. gi.set = n
  202. }
  203. gi.values = append(gi.values, n)
  204. continue
  205. }
  206. switch {
  207. case n == "sample_index":
  208. st := sampleTypes(p)
  209. if v == "" {
  210. // Apply default (last sample index).
  211. v = st[len(st)-1]
  212. }
  213. // Add comments for all sample types in profile.
  214. comment = "[" + strings.Join(st, " | ") + "]"
  215. case n == "source_path":
  216. continue
  217. case n == "nodecount" && v == "-1":
  218. comment = "default"
  219. case v == "":
  220. // Add quotes for empty values.
  221. v = `""`
  222. }
  223. if comment != "" {
  224. comment = commentStart + " " + comment
  225. }
  226. args = append(args, fmt.Sprintf(" %-25s = %-20s %s", n, v, comment))
  227. }
  228. for g, vars := range groups {
  229. sort.Strings(vars.values)
  230. comment := commentStart + " [" + strings.Join(vars.values, " | ") + "]"
  231. args = append(args, fmt.Sprintf(" %-25s = %-20s %s", g, vars.set, comment))
  232. }
  233. sort.Strings(args)
  234. ui.Print(strings.Join(args, "\n"))
  235. }
  236. // parseCommandLine parses a command and returns the pprof command to
  237. // execute and a set of variables for the report.
  238. func parseCommandLine(input []string) ([]string, variables, error) {
  239. cmd, args := input[:1], input[1:]
  240. name := cmd[0]
  241. c := pprofCommands[name]
  242. if c == nil {
  243. // Attempt splitting digits on abbreviated commands (eg top10)
  244. if d := tailDigitsRE.FindString(name); d != "" && d != name {
  245. name = name[:len(name)-len(d)]
  246. cmd[0], args = name, append([]string{d}, args...)
  247. c = pprofCommands[name]
  248. }
  249. }
  250. if c == nil {
  251. if v := pprofVariables[name]; v != nil {
  252. return nil, nil, fmt.Errorf("did you mean: %s=%s", name, args[0])
  253. }
  254. return nil, nil, fmt.Errorf("unrecognized command: %q", name)
  255. }
  256. if c.hasParam {
  257. if len(args) == 0 {
  258. return nil, nil, fmt.Errorf("command %s requires an argument", name)
  259. }
  260. cmd = append(cmd, args[0])
  261. args = args[1:]
  262. }
  263. // Copy the variables as options set in the command line are not persistent.
  264. vcopy := pprofVariables.makeCopy()
  265. var focus, ignore string
  266. for i := 0; i < len(args); i++ {
  267. t := args[i]
  268. if _, err := strconv.ParseInt(t, 10, 32); err == nil {
  269. vcopy.set("nodecount", t)
  270. continue
  271. }
  272. switch t[0] {
  273. case '>':
  274. outputFile := t[1:]
  275. if outputFile == "" {
  276. i++
  277. if i >= len(args) {
  278. return nil, nil, fmt.Errorf("unexpected end of line after >")
  279. }
  280. outputFile = args[i]
  281. }
  282. vcopy.set("output", outputFile)
  283. case '-':
  284. if t == "--cum" || t == "-cum" {
  285. vcopy.set("cum", "t")
  286. continue
  287. }
  288. ignore = catRegex(ignore, t[1:])
  289. default:
  290. focus = catRegex(focus, t)
  291. }
  292. }
  293. if name == "tags" {
  294. updateFocusIgnore(vcopy, "tag", focus, ignore)
  295. } else {
  296. updateFocusIgnore(vcopy, "", focus, ignore)
  297. }
  298. if vcopy["nodecount"].intValue() == -1 && (name == "text" || name == "top") {
  299. vcopy.set("nodecount", "10")
  300. }
  301. return cmd, vcopy, nil
  302. }
  303. func updateFocusIgnore(v variables, prefix, f, i string) {
  304. if f != "" {
  305. focus := prefix + "focus"
  306. v.set(focus, catRegex(v[focus].value, f))
  307. }
  308. if i != "" {
  309. ignore := prefix + "ignore"
  310. v.set(ignore, catRegex(v[ignore].value, i))
  311. }
  312. }
  313. func catRegex(a, b string) string {
  314. if a != "" && b != "" {
  315. return a + "|" + b
  316. }
  317. return a + b
  318. }
  319. // commandHelp displays help and usage information for all Commands
  320. // and Variables or a specific Command or Variable.
  321. func commandHelp(args string, ui plugin.UI) {
  322. if args == "" {
  323. help := usage(false)
  324. help = help + `
  325. : Clear focus/ignore/hide/tagfocus/tagignore
  326. type "help <cmd|option>" for more information
  327. `
  328. ui.Print(help)
  329. return
  330. }
  331. if c := pprofCommands[args]; c != nil {
  332. ui.Print(c.help(args))
  333. return
  334. }
  335. if v := pprofVariables[args]; v != nil {
  336. ui.Print(v.help + "\n")
  337. return
  338. }
  339. ui.PrintErr("Unknown command: " + args)
  340. }
  341. // newCompleter creates an autocompletion function for a set of commands.
  342. func newCompleter(fns []string) func(string) string {
  343. return func(line string) string {
  344. v := pprofVariables
  345. switch tokens := strings.Fields(line); len(tokens) {
  346. case 0:
  347. // Nothing to complete
  348. case 1:
  349. // Single token -- complete command name
  350. if match := matchVariableOrCommand(v, tokens[0]); match != "" {
  351. return match
  352. }
  353. case 2:
  354. if tokens[0] == "help" {
  355. if match := matchVariableOrCommand(v, tokens[1]); match != "" {
  356. return tokens[0] + " " + match
  357. }
  358. return line
  359. }
  360. fallthrough
  361. default:
  362. // Multiple tokens -- complete using functions, except for tags
  363. if cmd := pprofCommands[tokens[0]]; cmd != nil && tokens[0] != "tags" {
  364. lastTokenIdx := len(tokens) - 1
  365. lastToken := tokens[lastTokenIdx]
  366. if strings.HasPrefix(lastToken, "-") {
  367. lastToken = "-" + functionCompleter(lastToken[1:], fns)
  368. } else {
  369. lastToken = functionCompleter(lastToken, fns)
  370. }
  371. return strings.Join(append(tokens[:lastTokenIdx], lastToken), " ")
  372. }
  373. }
  374. return line
  375. }
  376. }
  377. // matchVariableOrCommand attempts to match a string token to the prefix of a Command.
  378. func matchVariableOrCommand(v variables, token string) string {
  379. token = strings.ToLower(token)
  380. found := ""
  381. for cmd := range pprofCommands {
  382. if strings.HasPrefix(cmd, token) {
  383. if found != "" {
  384. return ""
  385. }
  386. found = cmd
  387. }
  388. }
  389. for variable := range v {
  390. if strings.HasPrefix(variable, token) {
  391. if found != "" {
  392. return ""
  393. }
  394. found = variable
  395. }
  396. }
  397. return found
  398. }
  399. // functionCompleter replaces provided substring with a function
  400. // name retrieved from a profile if a single match exists. Otherwise,
  401. // it returns unchanged substring. It defaults to no-op if the profile
  402. // is not specified.
  403. func functionCompleter(substring string, fns []string) string {
  404. found := ""
  405. for _, fName := range fns {
  406. if strings.Contains(fName, substring) {
  407. if found != "" {
  408. return substring
  409. }
  410. found = fName
  411. }
  412. }
  413. if found != "" {
  414. return found
  415. }
  416. return substring
  417. }
  418. func functionNames(p *profile.Profile) []string {
  419. var fns []string
  420. for _, fn := range p.Function {
  421. fns = append(fns, fn.Name)
  422. }
  423. return fns
  424. }