You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 

440 lines
12 KiB

  1. // Copyright 2017 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. "bytes"
  17. "fmt"
  18. "html/template"
  19. "net"
  20. "net/http"
  21. gourl "net/url"
  22. "os"
  23. "os/exec"
  24. "strconv"
  25. "strings"
  26. "time"
  27. "github.com/google/pprof/internal/graph"
  28. "github.com/google/pprof/internal/plugin"
  29. "github.com/google/pprof/internal/report"
  30. "github.com/google/pprof/profile"
  31. )
  32. // webInterface holds the state needed for serving a browser based interface.
  33. type webInterface struct {
  34. prof *profile.Profile
  35. options *plugin.Options
  36. help map[string]string
  37. templates *template.Template
  38. }
  39. func makeWebInterface(p *profile.Profile, opt *plugin.Options) *webInterface {
  40. templates := template.New("templategroup")
  41. addTemplates(templates)
  42. report.AddSourceTemplates(templates)
  43. return &webInterface{
  44. prof: p,
  45. options: opt,
  46. help: make(map[string]string),
  47. templates: templates,
  48. }
  49. }
  50. // maxEntries is the maximum number of entries to print for text interfaces.
  51. const maxEntries = 50
  52. // errorCatcher is a UI that captures errors for reporting to the browser.
  53. type errorCatcher struct {
  54. plugin.UI
  55. errors []string
  56. }
  57. func (ec *errorCatcher) PrintErr(args ...interface{}) {
  58. ec.errors = append(ec.errors, strings.TrimSuffix(fmt.Sprintln(args...), "\n"))
  59. ec.UI.PrintErr(args...)
  60. }
  61. // webArgs contains arguments passed to templates in webhtml.go.
  62. type webArgs struct {
  63. Title string
  64. Errors []string
  65. Total int64
  66. SampleTypes []string
  67. Legend []string
  68. Help map[string]string
  69. Nodes []string
  70. HTMLBody template.HTML
  71. TextBody string
  72. Top []report.TextItem
  73. FlameGraph template.JS
  74. }
  75. func serveWebInterface(hostport string, p *profile.Profile, o *plugin.Options, disableBrowser bool) error {
  76. host, port, err := getHostAndPort(hostport)
  77. if err != nil {
  78. return err
  79. }
  80. interactiveMode = true
  81. ui := makeWebInterface(p, o)
  82. for n, c := range pprofCommands {
  83. ui.help[n] = c.description
  84. }
  85. for n, v := range pprofVariables {
  86. ui.help[n] = v.help
  87. }
  88. ui.help["details"] = "Show information about the profile and this view"
  89. ui.help["graph"] = "Display profile as a directed graph"
  90. ui.help["reset"] = "Show the entire profile"
  91. server := o.HTTPServer
  92. if server == nil {
  93. server = defaultWebServer
  94. }
  95. args := &plugin.HTTPServerArgs{
  96. Hostport: net.JoinHostPort(host, strconv.Itoa(port)),
  97. Host: host,
  98. Port: port,
  99. Handlers: map[string]http.Handler{
  100. "/": http.HandlerFunc(ui.dot),
  101. "/top": http.HandlerFunc(ui.top),
  102. "/disasm": http.HandlerFunc(ui.disasm),
  103. "/source": http.HandlerFunc(ui.source),
  104. "/peek": http.HandlerFunc(ui.peek),
  105. "/flamegraph": http.HandlerFunc(ui.flamegraph),
  106. },
  107. }
  108. url := "http://" + args.Hostport
  109. o.UI.Print("Serving web UI on ", url)
  110. if o.UI.WantBrowser() && !disableBrowser {
  111. go openBrowser(url, o)
  112. }
  113. return server(args)
  114. }
  115. func getHostAndPort(hostport string) (string, int, error) {
  116. host, portStr, err := net.SplitHostPort(hostport)
  117. if err != nil {
  118. return "", 0, fmt.Errorf("could not split http address: %v", err)
  119. }
  120. if host == "" {
  121. host = "localhost"
  122. }
  123. var port int
  124. if portStr == "" {
  125. ln, err := net.Listen("tcp", net.JoinHostPort(host, "0"))
  126. if err != nil {
  127. return "", 0, fmt.Errorf("could not generate random port: %v", err)
  128. }
  129. port = ln.Addr().(*net.TCPAddr).Port
  130. err = ln.Close()
  131. if err != nil {
  132. return "", 0, fmt.Errorf("could not generate random port: %v", err)
  133. }
  134. } else {
  135. port, err = strconv.Atoi(portStr)
  136. if err != nil {
  137. return "", 0, fmt.Errorf("invalid port number: %v", err)
  138. }
  139. }
  140. return host, port, nil
  141. }
  142. func defaultWebServer(args *plugin.HTTPServerArgs) error {
  143. ln, err := net.Listen("tcp", args.Hostport)
  144. if err != nil {
  145. return err
  146. }
  147. isLocal := isLocalhost(args.Host)
  148. handler := http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
  149. if isLocal {
  150. // Only allow local clients
  151. host, _, err := net.SplitHostPort(req.RemoteAddr)
  152. if err != nil || !isLocalhost(host) {
  153. http.Error(w, "permission denied", http.StatusForbidden)
  154. return
  155. }
  156. }
  157. h := args.Handlers[req.URL.Path]
  158. if h == nil {
  159. // Fall back to default behavior
  160. h = http.DefaultServeMux
  161. }
  162. h.ServeHTTP(w, req)
  163. })
  164. // We serve the ui at /ui/ and redirect there from the root. This is done
  165. // to surface any problems with serving the ui at a non-root early. See:
  166. //
  167. // https://github.com/google/pprof/pull/348
  168. mux := http.NewServeMux()
  169. mux.Handle("/ui/", http.StripPrefix("/ui", handler))
  170. mux.Handle("/", redirectWithQuery("/ui"))
  171. s := &http.Server{Handler: mux}
  172. return s.Serve(ln)
  173. }
  174. func redirectWithQuery(path string) http.HandlerFunc {
  175. return func(w http.ResponseWriter, r *http.Request) {
  176. pathWithQuery := &gourl.URL{Path: path, RawQuery: r.URL.RawQuery}
  177. http.Redirect(w, r, pathWithQuery.String(), http.StatusTemporaryRedirect)
  178. }
  179. }
  180. func isLocalhost(host string) bool {
  181. for _, v := range []string{"localhost", "127.0.0.1", "[::1]", "::1"} {
  182. if host == v {
  183. return true
  184. }
  185. }
  186. return false
  187. }
  188. func openBrowser(url string, o *plugin.Options) {
  189. // Construct URL.
  190. u, _ := gourl.Parse(url)
  191. q := u.Query()
  192. for _, p := range []struct{ param, key string }{
  193. {"f", "focus"},
  194. {"s", "show"},
  195. {"sf", "show_from"},
  196. {"i", "ignore"},
  197. {"h", "hide"},
  198. {"si", "sample_index"},
  199. } {
  200. if v := pprofVariables[p.key].value; v != "" {
  201. q.Set(p.param, v)
  202. }
  203. }
  204. u.RawQuery = q.Encode()
  205. // Give server a little time to get ready.
  206. time.Sleep(time.Millisecond * 500)
  207. for _, b := range browsers() {
  208. args := strings.Split(b, " ")
  209. if len(args) == 0 {
  210. continue
  211. }
  212. viewer := exec.Command(args[0], append(args[1:], u.String())...)
  213. viewer.Stderr = os.Stderr
  214. if err := viewer.Start(); err == nil {
  215. return
  216. }
  217. }
  218. // No visualizer succeeded, so just print URL.
  219. o.UI.PrintErr(u.String())
  220. }
  221. func varsFromURL(u *gourl.URL) variables {
  222. vars := pprofVariables.makeCopy()
  223. vars["focus"].value = u.Query().Get("f")
  224. vars["show"].value = u.Query().Get("s")
  225. vars["show_from"].value = u.Query().Get("sf")
  226. vars["ignore"].value = u.Query().Get("i")
  227. vars["hide"].value = u.Query().Get("h")
  228. vars["sample_index"].value = u.Query().Get("si")
  229. return vars
  230. }
  231. // makeReport generates a report for the specified command.
  232. func (ui *webInterface) makeReport(w http.ResponseWriter, req *http.Request,
  233. cmd []string, vars ...string) (*report.Report, []string) {
  234. v := varsFromURL(req.URL)
  235. for i := 0; i+1 < len(vars); i += 2 {
  236. v[vars[i]].value = vars[i+1]
  237. }
  238. catcher := &errorCatcher{UI: ui.options.UI}
  239. options := *ui.options
  240. options.UI = catcher
  241. _, rpt, err := generateRawReport(ui.prof, cmd, v, &options)
  242. if err != nil {
  243. http.Error(w, err.Error(), http.StatusBadRequest)
  244. ui.options.UI.PrintErr(err)
  245. return nil, nil
  246. }
  247. return rpt, catcher.errors
  248. }
  249. // render generates html using the named template based on the contents of data.
  250. func (ui *webInterface) render(w http.ResponseWriter, tmpl string,
  251. rpt *report.Report, errList, legend []string, data webArgs) {
  252. file := getFromLegend(legend, "File: ", "unknown")
  253. profile := getFromLegend(legend, "Type: ", "unknown")
  254. data.Title = file + " " + profile
  255. data.Errors = errList
  256. data.Total = rpt.Total()
  257. data.SampleTypes = sampleTypes(ui.prof)
  258. data.Legend = legend
  259. data.Help = ui.help
  260. html := &bytes.Buffer{}
  261. if err := ui.templates.ExecuteTemplate(html, tmpl, data); err != nil {
  262. http.Error(w, "internal template error", http.StatusInternalServerError)
  263. ui.options.UI.PrintErr(err)
  264. return
  265. }
  266. w.Header().Set("Content-Type", "text/html")
  267. w.Write(html.Bytes())
  268. }
  269. // dot generates a web page containing an svg diagram.
  270. func (ui *webInterface) dot(w http.ResponseWriter, req *http.Request) {
  271. rpt, errList := ui.makeReport(w, req, []string{"svg"})
  272. if rpt == nil {
  273. return // error already reported
  274. }
  275. // Generate dot graph.
  276. g, config := report.GetDOT(rpt)
  277. legend := config.Labels
  278. config.Labels = nil
  279. dot := &bytes.Buffer{}
  280. graph.ComposeDot(dot, g, &graph.DotAttributes{}, config)
  281. // Convert to svg.
  282. svg, err := dotToSvg(dot.Bytes())
  283. if err != nil {
  284. http.Error(w, "Could not execute dot; may need to install graphviz.",
  285. http.StatusNotImplemented)
  286. ui.options.UI.PrintErr("Failed to execute dot. Is Graphviz installed?\n", err)
  287. return
  288. }
  289. // Get all node names into an array.
  290. nodes := []string{""} // dot starts with node numbered 1
  291. for _, n := range g.Nodes {
  292. nodes = append(nodes, n.Info.Name)
  293. }
  294. ui.render(w, "graph", rpt, errList, legend, webArgs{
  295. HTMLBody: template.HTML(string(svg)),
  296. Nodes: nodes,
  297. })
  298. }
  299. func dotToSvg(dot []byte) ([]byte, error) {
  300. cmd := exec.Command("dot", "-Tsvg")
  301. out := &bytes.Buffer{}
  302. cmd.Stdin, cmd.Stdout, cmd.Stderr = bytes.NewBuffer(dot), out, os.Stderr
  303. if err := cmd.Run(); err != nil {
  304. return nil, err
  305. }
  306. // Fix dot bug related to unquoted amperands.
  307. svg := bytes.Replace(out.Bytes(), []byte("&;"), []byte("&amp;;"), -1)
  308. // Cleanup for embedding by dropping stuff before the <svg> start.
  309. if pos := bytes.Index(svg, []byte("<svg")); pos >= 0 {
  310. svg = svg[pos:]
  311. }
  312. return svg, nil
  313. }
  314. func (ui *webInterface) top(w http.ResponseWriter, req *http.Request) {
  315. rpt, errList := ui.makeReport(w, req, []string{"top"}, "nodecount", "500")
  316. if rpt == nil {
  317. return // error already reported
  318. }
  319. top, legend := report.TextItems(rpt)
  320. var nodes []string
  321. for _, item := range top {
  322. nodes = append(nodes, item.Name)
  323. }
  324. ui.render(w, "top", rpt, errList, legend, webArgs{
  325. Top: top,
  326. Nodes: nodes,
  327. })
  328. }
  329. // disasm generates a web page containing disassembly.
  330. func (ui *webInterface) disasm(w http.ResponseWriter, req *http.Request) {
  331. args := []string{"disasm", req.URL.Query().Get("f")}
  332. rpt, errList := ui.makeReport(w, req, args)
  333. if rpt == nil {
  334. return // error already reported
  335. }
  336. out := &bytes.Buffer{}
  337. if err := report.PrintAssembly(out, rpt, ui.options.Obj, maxEntries); err != nil {
  338. http.Error(w, err.Error(), http.StatusBadRequest)
  339. ui.options.UI.PrintErr(err)
  340. return
  341. }
  342. legend := report.ProfileLabels(rpt)
  343. ui.render(w, "plaintext", rpt, errList, legend, webArgs{
  344. TextBody: out.String(),
  345. })
  346. }
  347. // source generates a web page containing source code annotated with profile
  348. // data.
  349. func (ui *webInterface) source(w http.ResponseWriter, req *http.Request) {
  350. args := []string{"weblist", req.URL.Query().Get("f")}
  351. rpt, errList := ui.makeReport(w, req, args)
  352. if rpt == nil {
  353. return // error already reported
  354. }
  355. // Generate source listing.
  356. var body bytes.Buffer
  357. if err := report.PrintWebList(&body, rpt, ui.options.Obj, maxEntries); err != nil {
  358. http.Error(w, err.Error(), http.StatusBadRequest)
  359. ui.options.UI.PrintErr(err)
  360. return
  361. }
  362. legend := report.ProfileLabels(rpt)
  363. ui.render(w, "sourcelisting", rpt, errList, legend, webArgs{
  364. HTMLBody: template.HTML(body.String()),
  365. })
  366. }
  367. // peek generates a web page listing callers/callers.
  368. func (ui *webInterface) peek(w http.ResponseWriter, req *http.Request) {
  369. args := []string{"peek", req.URL.Query().Get("f")}
  370. rpt, errList := ui.makeReport(w, req, args, "lines", "t")
  371. if rpt == nil {
  372. return // error already reported
  373. }
  374. out := &bytes.Buffer{}
  375. if err := report.Generate(out, rpt, ui.options.Obj); err != nil {
  376. http.Error(w, err.Error(), http.StatusBadRequest)
  377. ui.options.UI.PrintErr(err)
  378. return
  379. }
  380. legend := report.ProfileLabels(rpt)
  381. ui.render(w, "plaintext", rpt, errList, legend, webArgs{
  382. TextBody: out.String(),
  383. })
  384. }
  385. // getFromLegend returns the suffix of an entry in legend that starts
  386. // with param. It returns def if no such entry is found.
  387. func getFromLegend(legend []string, param, def string) string {
  388. for _, s := range legend {
  389. if strings.HasPrefix(s, param) {
  390. return s[len(param):]
  391. }
  392. }
  393. return def
  394. }