Nenhuma descrição

interactive.go 11KB

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