Açıklama Yok

interactive.go 11KB

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