Ei kuvausta

webui.go 11KB

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