Bez popisu

driver.go 10.0KB

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