Açıklama Yok

interactive.go 11KB

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