Nessuna descrizione

webui.go 13KB

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