Sin descripción

webui.go 12KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428
  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) 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. if o.UI.WantBrowser() {
  109. go openBrowser("http://"+args.Hostport, o)
  110. }
  111. return server(args)
  112. }
  113. func getHostAndPort(hostport string) (string, int, error) {
  114. host, portStr, err := net.SplitHostPort(hostport)
  115. if err != nil {
  116. return "", 0, fmt.Errorf("could not split http address: %v", err)
  117. }
  118. if host == "" {
  119. host = "localhost"
  120. }
  121. var port int
  122. if portStr == "" {
  123. ln, err := net.Listen("tcp", net.JoinHostPort(host, "0"))
  124. if err != nil {
  125. return "", 0, fmt.Errorf("could not generate random port: %v", err)
  126. }
  127. port = ln.Addr().(*net.TCPAddr).Port
  128. err = ln.Close()
  129. if err != nil {
  130. return "", 0, fmt.Errorf("could not generate random port: %v", err)
  131. }
  132. } else {
  133. port, err = strconv.Atoi(portStr)
  134. if err != nil {
  135. return "", 0, fmt.Errorf("invalid port number: %v", err)
  136. }
  137. }
  138. return host, port, nil
  139. }
  140. func defaultWebServer(args *plugin.HTTPServerArgs) error {
  141. ln, err := net.Listen("tcp", args.Hostport)
  142. if err != nil {
  143. return err
  144. }
  145. isLocal := isLocalhost(args.Host)
  146. handler := http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
  147. if isLocal {
  148. // Only allow local clients
  149. host, _, err := net.SplitHostPort(req.RemoteAddr)
  150. if err != nil || !isLocalhost(host) {
  151. http.Error(w, "permission denied", http.StatusForbidden)
  152. return
  153. }
  154. }
  155. h := args.Handlers[req.URL.Path]
  156. if h == nil {
  157. // Fall back to default behavior
  158. h = http.DefaultServeMux
  159. }
  160. h.ServeHTTP(w, req)
  161. })
  162. // We serve the ui at /ui/ and redirect there from the root. This is done
  163. // to surface any problems with serving the ui at a non-root early. See:
  164. //
  165. // https://github.com/google/pprof/pull/348
  166. mux := http.NewServeMux()
  167. mux.Handle("/ui/", http.StripPrefix("/ui", handler))
  168. mux.Handle("/", http.RedirectHandler("/ui/", http.StatusTemporaryRedirect))
  169. s := &http.Server{Handler: mux}
  170. return s.Serve(ln)
  171. }
  172. func isLocalhost(host string) bool {
  173. for _, v := range []string{"localhost", "127.0.0.1", "[::1]", "::1"} {
  174. if host == v {
  175. return true
  176. }
  177. }
  178. return false
  179. }
  180. func openBrowser(url string, o *plugin.Options) {
  181. // Construct URL.
  182. u, _ := gourl.Parse(url)
  183. q := u.Query()
  184. for _, p := range []struct{ param, key string }{
  185. {"f", "focus"},
  186. {"s", "show"},
  187. {"sf", "show_from"},
  188. {"i", "ignore"},
  189. {"h", "hide"},
  190. {"si", "sample_index"},
  191. } {
  192. if v := pprofVariables[p.key].value; v != "" {
  193. q.Set(p.param, v)
  194. }
  195. }
  196. u.RawQuery = q.Encode()
  197. // Give server a little time to get ready.
  198. time.Sleep(time.Millisecond * 500)
  199. for _, b := range browsers() {
  200. args := strings.Split(b, " ")
  201. if len(args) == 0 {
  202. continue
  203. }
  204. viewer := exec.Command(args[0], append(args[1:], u.String())...)
  205. viewer.Stderr = os.Stderr
  206. if err := viewer.Start(); err == nil {
  207. return
  208. }
  209. }
  210. // No visualizer succeeded, so just print URL.
  211. o.UI.PrintErr(u.String())
  212. }
  213. func varsFromURL(u *gourl.URL) variables {
  214. vars := pprofVariables.makeCopy()
  215. vars["focus"].value = u.Query().Get("f")
  216. vars["show"].value = u.Query().Get("s")
  217. vars["show_from"].value = u.Query().Get("sf")
  218. vars["ignore"].value = u.Query().Get("i")
  219. vars["hide"].value = u.Query().Get("h")
  220. vars["sample_index"].value = u.Query().Get("si")
  221. return vars
  222. }
  223. // makeReport generates a report for the specified command.
  224. func (ui *webInterface) makeReport(w http.ResponseWriter, req *http.Request,
  225. cmd []string, vars ...string) (*report.Report, []string) {
  226. v := varsFromURL(req.URL)
  227. for i := 0; i+1 < len(vars); i += 2 {
  228. v[vars[i]].value = vars[i+1]
  229. }
  230. catcher := &errorCatcher{UI: ui.options.UI}
  231. options := *ui.options
  232. options.UI = catcher
  233. _, rpt, err := generateRawReport(ui.prof, cmd, v, &options)
  234. if err != nil {
  235. http.Error(w, err.Error(), http.StatusBadRequest)
  236. ui.options.UI.PrintErr(err)
  237. return nil, nil
  238. }
  239. return rpt, catcher.errors
  240. }
  241. // render generates html using the named template based on the contents of data.
  242. func (ui *webInterface) render(w http.ResponseWriter, tmpl string,
  243. rpt *report.Report, errList, legend []string, data webArgs) {
  244. file := getFromLegend(legend, "File: ", "unknown")
  245. profile := getFromLegend(legend, "Type: ", "unknown")
  246. data.Title = file + " " + profile
  247. data.Errors = errList
  248. data.Total = rpt.Total()
  249. data.SampleTypes = sampleTypes(ui.prof)
  250. data.Legend = legend
  251. data.Help = ui.help
  252. html := &bytes.Buffer{}
  253. if err := ui.templates.ExecuteTemplate(html, tmpl, data); err != nil {
  254. http.Error(w, "internal template error", http.StatusInternalServerError)
  255. ui.options.UI.PrintErr(err)
  256. return
  257. }
  258. w.Header().Set("Content-Type", "text/html")
  259. w.Write(html.Bytes())
  260. }
  261. // dot generates a web page containing an svg diagram.
  262. func (ui *webInterface) dot(w http.ResponseWriter, req *http.Request) {
  263. rpt, errList := ui.makeReport(w, req, []string{"svg"})
  264. if rpt == nil {
  265. return // error already reported
  266. }
  267. // Generate dot graph.
  268. g, config := report.GetDOT(rpt)
  269. legend := config.Labels
  270. config.Labels = nil
  271. dot := &bytes.Buffer{}
  272. graph.ComposeDot(dot, g, &graph.DotAttributes{}, config)
  273. // Convert to svg.
  274. svg, err := dotToSvg(dot.Bytes())
  275. if err != nil {
  276. http.Error(w, "Could not execute dot; may need to install graphviz.",
  277. http.StatusNotImplemented)
  278. ui.options.UI.PrintErr("Failed to execute dot. Is Graphviz installed?\n", err)
  279. return
  280. }
  281. // Get all node names into an array.
  282. nodes := []string{""} // dot starts with node numbered 1
  283. for _, n := range g.Nodes {
  284. nodes = append(nodes, n.Info.Name)
  285. }
  286. ui.render(w, "graph", rpt, errList, legend, webArgs{
  287. HTMLBody: template.HTML(string(svg)),
  288. Nodes: nodes,
  289. })
  290. }
  291. func dotToSvg(dot []byte) ([]byte, error) {
  292. cmd := exec.Command("dot", "-Tsvg")
  293. out := &bytes.Buffer{}
  294. cmd.Stdin, cmd.Stdout, cmd.Stderr = bytes.NewBuffer(dot), out, os.Stderr
  295. if err := cmd.Run(); err != nil {
  296. return nil, err
  297. }
  298. // Fix dot bug related to unquoted amperands.
  299. svg := bytes.Replace(out.Bytes(), []byte("&;"), []byte("&amp;;"), -1)
  300. // Cleanup for embedding by dropping stuff before the <svg> start.
  301. if pos := bytes.Index(svg, []byte("<svg")); pos >= 0 {
  302. svg = svg[pos:]
  303. }
  304. return svg, nil
  305. }
  306. func (ui *webInterface) top(w http.ResponseWriter, req *http.Request) {
  307. rpt, errList := ui.makeReport(w, req, []string{"top"}, "nodecount", "500")
  308. if rpt == nil {
  309. return // error already reported
  310. }
  311. top, legend := report.TextItems(rpt)
  312. var nodes []string
  313. for _, item := range top {
  314. nodes = append(nodes, item.Name)
  315. }
  316. ui.render(w, "top", rpt, errList, legend, webArgs{
  317. Top: top,
  318. Nodes: nodes,
  319. })
  320. }
  321. // disasm generates a web page containing disassembly.
  322. func (ui *webInterface) disasm(w http.ResponseWriter, req *http.Request) {
  323. args := []string{"disasm", req.URL.Query().Get("f")}
  324. rpt, errList := ui.makeReport(w, req, args)
  325. if rpt == nil {
  326. return // error already reported
  327. }
  328. out := &bytes.Buffer{}
  329. if err := report.PrintAssembly(out, rpt, ui.options.Obj, maxEntries); err != nil {
  330. http.Error(w, err.Error(), http.StatusBadRequest)
  331. ui.options.UI.PrintErr(err)
  332. return
  333. }
  334. legend := report.ProfileLabels(rpt)
  335. ui.render(w, "plaintext", rpt, errList, legend, webArgs{
  336. TextBody: out.String(),
  337. })
  338. }
  339. // source generates a web page containing source code annotated with profile
  340. // data.
  341. func (ui *webInterface) source(w http.ResponseWriter, req *http.Request) {
  342. args := []string{"weblist", req.URL.Query().Get("f")}
  343. rpt, errList := ui.makeReport(w, req, args)
  344. if rpt == nil {
  345. return // error already reported
  346. }
  347. // Generate source listing.
  348. var body bytes.Buffer
  349. if err := report.PrintWebList(&body, rpt, ui.options.Obj, maxEntries); err != nil {
  350. http.Error(w, err.Error(), http.StatusBadRequest)
  351. ui.options.UI.PrintErr(err)
  352. return
  353. }
  354. legend := report.ProfileLabels(rpt)
  355. ui.render(w, "sourcelisting", rpt, errList, legend, webArgs{
  356. HTMLBody: template.HTML(body.String()),
  357. })
  358. }
  359. // peek generates a web page listing callers/callers.
  360. func (ui *webInterface) peek(w http.ResponseWriter, req *http.Request) {
  361. args := []string{"peek", req.URL.Query().Get("f")}
  362. rpt, errList := ui.makeReport(w, req, args, "lines", "t")
  363. if rpt == nil {
  364. return // error already reported
  365. }
  366. out := &bytes.Buffer{}
  367. if err := report.Generate(out, rpt, ui.options.Obj); err != nil {
  368. http.Error(w, err.Error(), http.StatusBadRequest)
  369. ui.options.UI.PrintErr(err)
  370. return
  371. }
  372. legend := report.ProfileLabels(rpt)
  373. ui.render(w, "plaintext", rpt, errList, legend, webArgs{
  374. TextBody: out.String(),
  375. })
  376. }
  377. // getFromLegend returns the suffix of an entry in legend that starts
  378. // with param. It returns def if no such entry is found.
  379. func getFromLegend(legend []string, param, def string) string {
  380. for _, s := range legend {
  381. if strings.HasPrefix(s, param) {
  382. return s[len(param):]
  383. }
  384. }
  385. return def
  386. }