Brak opisu

interactive.go 9.9KB

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