Geen omschrijving

interactive.go 8.9KB

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