Bez popisu

webui.go 11KB

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