暂无描述

driver.go 8.7KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340
  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 implements the core pprof functionality. It can be
  15. // parameterized with a flag implementation, fetch and symbolize
  16. // mechanisms.
  17. package driver
  18. import (
  19. "bytes"
  20. "fmt"
  21. "os"
  22. "path/filepath"
  23. "regexp"
  24. "strings"
  25. "github.com/google/pprof/internal/plugin"
  26. "github.com/google/pprof/internal/report"
  27. "github.com/google/pprof/profile"
  28. )
  29. // PProf acquires a profile, and symbolizes it using a profile
  30. // manager. Then it generates a report formatted according to the
  31. // options selected through the flags package.
  32. func PProf(eo *plugin.Options) error {
  33. // Remove any temporary files created during pprof processing.
  34. defer cleanupTempFiles()
  35. o := setDefaults(eo)
  36. src, cmd, err := parseFlags(o)
  37. if err != nil {
  38. return err
  39. }
  40. p, err := fetchProfiles(src, o)
  41. if err != nil {
  42. return err
  43. }
  44. if cmd != nil {
  45. return generateReport(p, cmd, currentConfig(), o)
  46. }
  47. if src.HTTPHostport != "" {
  48. return serveWebInterface(src.HTTPHostport, p, o, src.HTTPDisableBrowser)
  49. }
  50. return interactive(p, o)
  51. }
  52. func generateRawReport(p *profile.Profile, cmd []string, cfg config, o *plugin.Options) (*command, *report.Report, error) {
  53. p = p.Copy() // Prevent modification to the incoming profile.
  54. // Identify units of numeric tags in profile.
  55. numLabelUnits := identifyNumLabelUnits(p, o.UI)
  56. // Get report output format
  57. c := pprofCommands[cmd[0]]
  58. if c == nil {
  59. panic("unexpected nil command")
  60. }
  61. cfg = applyCommandOverrides(cmd[0], c.format, cfg)
  62. // Delay focus after configuring report to get percentages on all samples.
  63. relative := cfg.RelativePercentages
  64. if relative {
  65. if err := applyFocus(p, numLabelUnits, cfg, o.UI); err != nil {
  66. return nil, nil, err
  67. }
  68. }
  69. ropt, err := reportOptions(p, numLabelUnits, cfg)
  70. if err != nil {
  71. return nil, nil, err
  72. }
  73. ropt.OutputFormat = c.format
  74. if len(cmd) == 2 {
  75. s, err := regexp.Compile(cmd[1])
  76. if err != nil {
  77. return nil, nil, fmt.Errorf("parsing argument regexp %s: %v", cmd[1], err)
  78. }
  79. ropt.Symbol = s
  80. }
  81. rpt := report.New(p, ropt)
  82. if !relative {
  83. if err := applyFocus(p, numLabelUnits, cfg, o.UI); err != nil {
  84. return nil, nil, err
  85. }
  86. }
  87. if err := aggregate(p, cfg); err != nil {
  88. return nil, nil, err
  89. }
  90. return c, rpt, nil
  91. }
  92. func generateReport(p *profile.Profile, cmd []string, cfg config, o *plugin.Options) error {
  93. c, rpt, err := generateRawReport(p, cmd, cfg, o)
  94. if err != nil {
  95. return err
  96. }
  97. // Generate the report.
  98. dst := new(bytes.Buffer)
  99. if err := report.Generate(dst, rpt, o.Obj); err != nil {
  100. return err
  101. }
  102. src := dst
  103. // If necessary, perform any data post-processing.
  104. if c.postProcess != nil {
  105. dst = new(bytes.Buffer)
  106. if err := c.postProcess(src, dst, o.UI); err != nil {
  107. return err
  108. }
  109. src = dst
  110. }
  111. // If no output is specified, use default visualizer.
  112. output := cfg.Output
  113. if output == "" {
  114. if c.visualizer != nil {
  115. return c.visualizer(src, os.Stdout, o.UI)
  116. }
  117. _, err := src.WriteTo(os.Stdout)
  118. return err
  119. }
  120. // Output to specified file.
  121. o.UI.PrintErr("Generating report in ", output)
  122. out, err := o.Writer.Open(output)
  123. if err != nil {
  124. return err
  125. }
  126. if _, err := src.WriteTo(out); err != nil {
  127. out.Close()
  128. return err
  129. }
  130. return out.Close()
  131. }
  132. func applyCommandOverrides(cmd string, outputFormat int, cfg config) config {
  133. // Some report types override the trim flag to false below. This is to make
  134. // sure the default heuristics of excluding insignificant nodes and edges
  135. // from the call graph do not apply. One example where it is important is
  136. // annotated source or disassembly listing. Those reports run on a specific
  137. // function (or functions), but the trimming is applied before the function
  138. // data is selected. So, with trimming enabled, the report could end up
  139. // showing no data if the specified function is "uninteresting" as far as the
  140. // trimming is concerned.
  141. trim := cfg.Trim
  142. switch cmd {
  143. case "disasm", "weblist":
  144. trim = false
  145. cfg.Granularity = "addresses"
  146. // Force the 'noinlines' mode so that source locations for a given address
  147. // collapse and there is only one for the given address. Without this
  148. // cumulative metrics would be double-counted when annotating the assembly.
  149. // This is because the merge is done by address and in case of an inlined
  150. // stack each of the inlined entries is a separate callgraph node.
  151. cfg.NoInlines = true
  152. case "peek":
  153. trim = false
  154. case "list":
  155. trim = false
  156. cfg.Granularity = "lines"
  157. // Do not force 'noinlines' to be false so that specifying
  158. // "-list foo -noinlines" is supported and works as expected.
  159. case "text", "top", "topproto":
  160. if cfg.NodeCount == -1 {
  161. cfg.NodeCount = 0
  162. }
  163. default:
  164. if cfg.NodeCount == -1 {
  165. cfg.NodeCount = 80
  166. }
  167. }
  168. switch outputFormat {
  169. case report.Proto, report.Raw, report.Callgrind:
  170. trim = false
  171. cfg.Granularity = "addresses"
  172. cfg.NoInlines = false
  173. }
  174. if !trim {
  175. cfg.NodeCount = 0
  176. cfg.NodeFraction = 0
  177. cfg.EdgeFraction = 0
  178. }
  179. return cfg
  180. }
  181. func aggregate(prof *profile.Profile, cfg config) error {
  182. var function, filename, linenumber, address bool
  183. inlines := !cfg.NoInlines
  184. switch cfg.Granularity {
  185. case "addresses":
  186. if inlines {
  187. return nil
  188. }
  189. function = true
  190. filename = true
  191. linenumber = true
  192. address = true
  193. case "lines":
  194. function = true
  195. filename = true
  196. linenumber = true
  197. case "files":
  198. filename = true
  199. case "functions":
  200. function = true
  201. case "filefunctions":
  202. function = true
  203. filename = true
  204. default:
  205. return fmt.Errorf("unexpected granularity")
  206. }
  207. return prof.Aggregate(inlines, function, filename, linenumber, address)
  208. }
  209. func reportOptions(p *profile.Profile, numLabelUnits map[string]string, cfg config) (*report.Options, error) {
  210. si, mean := cfg.SampleIndex, cfg.Mean
  211. value, meanDiv, sample, err := sampleFormat(p, si, mean)
  212. if err != nil {
  213. return nil, err
  214. }
  215. stype := sample.Type
  216. if mean {
  217. stype = "mean_" + stype
  218. }
  219. if cfg.DivideBy == 0 {
  220. return nil, fmt.Errorf("zero divisor specified")
  221. }
  222. var filters []string
  223. addFilter := func(k string, v string) {
  224. if v != "" {
  225. filters = append(filters, k+"="+v)
  226. }
  227. }
  228. addFilter("focus", cfg.Focus)
  229. addFilter("ignore", cfg.Ignore)
  230. addFilter("hide", cfg.Hide)
  231. addFilter("show", cfg.Show)
  232. addFilter("show_from", cfg.ShowFrom)
  233. addFilter("tagfocus", cfg.TagFocus)
  234. addFilter("tagignore", cfg.TagIgnore)
  235. addFilter("tagshow", cfg.TagShow)
  236. addFilter("taghide", cfg.TagHide)
  237. ropt := &report.Options{
  238. CumSort: cfg.Sort == "cum",
  239. CallTree: cfg.CallTree,
  240. DropNegative: cfg.DropNegative,
  241. CompactLabels: cfg.CompactLabels,
  242. Ratio: 1 / cfg.DivideBy,
  243. NodeCount: cfg.NodeCount,
  244. NodeFraction: cfg.NodeFraction,
  245. EdgeFraction: cfg.EdgeFraction,
  246. ActiveFilters: filters,
  247. NumLabelUnits: numLabelUnits,
  248. SampleValue: value,
  249. SampleMeanDivisor: meanDiv,
  250. SampleType: stype,
  251. SampleUnit: sample.Unit,
  252. OutputUnit: cfg.Unit,
  253. SourcePath: cfg.SourcePath,
  254. TrimPath: cfg.TrimPath,
  255. IntelSyntax: cfg.IntelSyntax,
  256. }
  257. if len(p.Mapping) > 0 && p.Mapping[0].File != "" {
  258. ropt.Title = filepath.Base(p.Mapping[0].File)
  259. }
  260. return ropt, nil
  261. }
  262. // identifyNumLabelUnits returns a map of numeric label keys to the units
  263. // associated with those keys.
  264. func identifyNumLabelUnits(p *profile.Profile, ui plugin.UI) map[string]string {
  265. numLabelUnits, ignoredUnits := p.NumLabelUnits()
  266. // Print errors for tags with multiple units associated with
  267. // a single key.
  268. for k, units := range ignoredUnits {
  269. ui.PrintErr(fmt.Sprintf("For tag %s used unit %s, also encountered unit(s) %s", k, numLabelUnits[k], strings.Join(units, ", ")))
  270. }
  271. return numLabelUnits
  272. }
  273. type sampleValueFunc func([]int64) int64
  274. // sampleFormat returns a function to extract values out of a profile.Sample,
  275. // and the type/units of those values.
  276. func sampleFormat(p *profile.Profile, sampleIndex string, mean bool) (value, meanDiv sampleValueFunc, v *profile.ValueType, err error) {
  277. if len(p.SampleType) == 0 {
  278. return nil, nil, nil, fmt.Errorf("profile has no samples")
  279. }
  280. index, err := p.SampleIndexByName(sampleIndex)
  281. if err != nil {
  282. return nil, nil, nil, err
  283. }
  284. value = valueExtractor(index)
  285. if mean {
  286. meanDiv = valueExtractor(0)
  287. }
  288. v = p.SampleType[index]
  289. return
  290. }
  291. func valueExtractor(ix int) sampleValueFunc {
  292. return func(v []int64) int64 {
  293. return v[ix]
  294. }
  295. }