설명 없음

interactive.go 10KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422
  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. waitForVisualizer = false
  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 := locateSampleIndex(p, 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 printCurrentOptions(p *profile.Profile, ui plugin.UI) {
  146. var args []string
  147. type groupInfo struct {
  148. set string
  149. values []string
  150. }
  151. groups := make(map[string]*groupInfo)
  152. for n, o := range pprofVariables {
  153. v := o.stringValue()
  154. comment := ""
  155. if g := o.group; g != "" {
  156. gi, ok := groups[g]
  157. if !ok {
  158. gi = &groupInfo{}
  159. groups[g] = gi
  160. }
  161. if o.boolValue() {
  162. gi.set = n
  163. }
  164. gi.values = append(gi.values, n)
  165. continue
  166. }
  167. switch {
  168. case n == "sample_index":
  169. st := sampleTypes(p)
  170. if v == "" {
  171. // Apply default (last sample index).
  172. v = st[len(st)-1]
  173. }
  174. // Add comments for all sample types in profile.
  175. comment = "[" + strings.Join(st, " | ") + "]"
  176. case n == "source_path":
  177. continue
  178. case n == "nodecount" && v == "-1":
  179. comment = "default"
  180. case v == "":
  181. // Add quotes for empty values.
  182. v = `""`
  183. }
  184. if comment != "" {
  185. comment = commentStart + " " + comment
  186. }
  187. args = append(args, fmt.Sprintf(" %-25s = %-20s %s", n, v, comment))
  188. }
  189. for g, vars := range groups {
  190. sort.Strings(vars.values)
  191. comment := commentStart + " [" + strings.Join(vars.values, " | ") + "]"
  192. args = append(args, fmt.Sprintf(" %-25s = %-20s %s", g, vars.set, comment))
  193. }
  194. sort.Strings(args)
  195. ui.Print(strings.Join(args, "\n"))
  196. }
  197. // parseCommandLine parses a command and returns the pprof command to
  198. // execute and a set of variables for the report.
  199. func parseCommandLine(input []string) ([]string, variables, error) {
  200. cmd, args := input[:1], input[1:]
  201. name := cmd[0]
  202. c := pprofCommands[name]
  203. if c == nil {
  204. // Attempt splitting digits on abbreviated commands (eg top10)
  205. if d := tailDigitsRE.FindString(name); d != "" && d != name {
  206. name = name[:len(name)-len(d)]
  207. cmd[0], args = name, append([]string{d}, args...)
  208. c = pprofCommands[name]
  209. }
  210. }
  211. if c == nil {
  212. return nil, nil, fmt.Errorf("Unrecognized command: %q", name)
  213. }
  214. if c.hasParam {
  215. if len(args) == 0 {
  216. return nil, nil, fmt.Errorf("command %s requires an argument", name)
  217. }
  218. cmd = append(cmd, args[0])
  219. args = args[1:]
  220. }
  221. // Copy the variables as options set in the command line are not persistent.
  222. vcopy := pprofVariables.makeCopy()
  223. var focus, ignore string
  224. for i := 0; i < len(args); i++ {
  225. t := args[i]
  226. if _, err := strconv.ParseInt(t, 10, 32); err == nil {
  227. vcopy.set("nodecount", t)
  228. continue
  229. }
  230. switch t[0] {
  231. case '>':
  232. outputFile := t[1:]
  233. if outputFile == "" {
  234. i++
  235. if i >= len(args) {
  236. return nil, nil, fmt.Errorf("Unexpected end of line after >")
  237. }
  238. outputFile = args[i]
  239. }
  240. vcopy.set("output", outputFile)
  241. case '-':
  242. if t == "--cum" || t == "-cum" {
  243. vcopy.set("cum", "t")
  244. continue
  245. }
  246. ignore = catRegex(ignore, t[1:])
  247. default:
  248. focus = catRegex(focus, t)
  249. }
  250. }
  251. if name == "tags" {
  252. updateFocusIgnore(vcopy, "tag", focus, ignore)
  253. } else {
  254. updateFocusIgnore(vcopy, "", focus, ignore)
  255. }
  256. if vcopy["nodecount"].intValue() == -1 && (name == "text" || name == "top") {
  257. vcopy.set("nodecount", "10")
  258. }
  259. return cmd, vcopy, nil
  260. }
  261. func updateFocusIgnore(v variables, prefix, f, i string) {
  262. if f != "" {
  263. focus := prefix + "focus"
  264. v.set(focus, catRegex(v[focus].value, f))
  265. }
  266. if i != "" {
  267. ignore := prefix + "ignore"
  268. v.set(ignore, catRegex(v[ignore].value, i))
  269. }
  270. }
  271. func catRegex(a, b string) string {
  272. if a != "" && b != "" {
  273. return a + "|" + b
  274. }
  275. return a + b
  276. }
  277. // commandHelp displays help and usage information for all Commands
  278. // and Variables or a specific Command or Variable.
  279. func commandHelp(args string, ui plugin.UI) {
  280. if args == "" {
  281. help := usage(false)
  282. help = help + `
  283. : Clear focus/ignore/hide/tagfocus/tagignore
  284. type "help <cmd|option>" for more information
  285. `
  286. ui.Print(help)
  287. return
  288. }
  289. if c := pprofCommands[args]; c != nil {
  290. ui.Print(c.help(args))
  291. return
  292. }
  293. if v := pprofVariables[args]; v != nil {
  294. ui.Print(v.help + "\n")
  295. return
  296. }
  297. ui.PrintErr("Unknown command: " + args)
  298. }
  299. // newCompleter creates an autocompletion function for a set of commands.
  300. func newCompleter(fns []string) func(string) string {
  301. return func(line string) string {
  302. v := pprofVariables
  303. switch tokens := strings.Fields(line); len(tokens) {
  304. case 0:
  305. // Nothing to complete
  306. case 1:
  307. // Single token -- complete command name
  308. if match := matchVariableOrCommand(v, tokens[0]); match != "" {
  309. return match
  310. }
  311. case 2:
  312. if tokens[0] == "help" {
  313. if match := matchVariableOrCommand(v, tokens[1]); match != "" {
  314. return tokens[0] + " " + match
  315. }
  316. return line
  317. }
  318. fallthrough
  319. default:
  320. // Multiple tokens -- complete using functions, except for tags
  321. if cmd := pprofCommands[tokens[0]]; cmd != nil && tokens[0] != "tags" {
  322. lastTokenIdx := len(tokens) - 1
  323. lastToken := tokens[lastTokenIdx]
  324. if strings.HasPrefix(lastToken, "-") {
  325. lastToken = "-" + functionCompleter(lastToken[1:], fns)
  326. } else {
  327. lastToken = functionCompleter(lastToken, fns)
  328. }
  329. return strings.Join(append(tokens[:lastTokenIdx], lastToken), " ")
  330. }
  331. }
  332. return line
  333. }
  334. }
  335. // matchCommand attempts to match a string token to the prefix of a Command.
  336. func matchVariableOrCommand(v variables, token string) string {
  337. token = strings.ToLower(token)
  338. found := ""
  339. for cmd := range pprofCommands {
  340. if strings.HasPrefix(cmd, token) {
  341. if found != "" {
  342. return ""
  343. }
  344. found = cmd
  345. }
  346. }
  347. for variable := range v {
  348. if strings.HasPrefix(variable, token) {
  349. if found != "" {
  350. return ""
  351. }
  352. found = variable
  353. }
  354. }
  355. return found
  356. }
  357. // functionCompleter replaces provided substring with a function
  358. // name retrieved from a profile if a single match exists. Otherwise,
  359. // it returns unchanged substring. It defaults to no-op if the profile
  360. // is not specified.
  361. func functionCompleter(substring string, fns []string) string {
  362. found := ""
  363. for _, fName := range fns {
  364. if strings.Contains(fName, substring) {
  365. if found != "" {
  366. return substring
  367. }
  368. found = fName
  369. }
  370. }
  371. if found != "" {
  372. return found
  373. }
  374. return substring
  375. }
  376. func functionNames(p *profile.Profile) []string {
  377. var fns []string
  378. for _, fn := range p.Function {
  379. fns = append(fns, fn.Name)
  380. }
  381. return fns
  382. }