Sin descripción

webui.go 8.5KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323
  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. "io"
  20. "net"
  21. "net/http"
  22. gourl "net/url"
  23. "os"
  24. "os/exec"
  25. "regexp"
  26. "strings"
  27. "time"
  28. "github.com/google/pprof/internal/graph"
  29. "github.com/google/pprof/internal/plugin"
  30. "github.com/google/pprof/internal/report"
  31. "github.com/google/pprof/profile"
  32. )
  33. // webInterface holds the state needed for serving a browser based interface.
  34. type webInterface struct {
  35. prof *profile.Profile
  36. options *plugin.Options
  37. help map[string]string
  38. }
  39. // errorCatcher is a UI that captures errors for reporting to the browser.
  40. type errorCatcher struct {
  41. plugin.UI
  42. errors []string
  43. }
  44. func (ec *errorCatcher) PrintErr(args ...interface{}) {
  45. ec.errors = append(ec.errors, strings.TrimSuffix(fmt.Sprintln(args...), "\n"))
  46. ec.UI.PrintErr(args...)
  47. }
  48. func serveWebInterface(hostport string, p *profile.Profile, o *plugin.Options) error {
  49. interactiveMode = true
  50. ui := &webInterface{
  51. prof: p,
  52. options: o,
  53. help: make(map[string]string),
  54. }
  55. for n, c := range pprofCommands {
  56. ui.help[n] = c.description
  57. }
  58. for n, v := range pprofVariables {
  59. ui.help[n] = v.help
  60. }
  61. ln, url, isLocal, err := newListenerAndURL(hostport)
  62. if err != nil {
  63. return err
  64. }
  65. // authorization wrapper
  66. wrap := o.HTTPWrapper
  67. if wrap == nil {
  68. if isLocal {
  69. // Only allow requests from local host.
  70. wrap = checkLocalHost
  71. } else {
  72. wrap = func(h http.Handler) http.Handler { return h }
  73. }
  74. }
  75. mux := http.NewServeMux()
  76. mux.Handle("/", wrap(http.HandlerFunc(ui.dot)))
  77. mux.Handle("/disasm", wrap(http.HandlerFunc(ui.disasm)))
  78. mux.Handle("/weblist", wrap(http.HandlerFunc(ui.weblist)))
  79. mux.Handle("/peek", wrap(http.HandlerFunc(ui.peek)))
  80. s := &http.Server{Handler: mux}
  81. go openBrowser(url, o)
  82. return s.Serve(ln)
  83. }
  84. func newListenerAndURL(hostport string) (ln net.Listener, url string, isLocal bool, err error) {
  85. host, _, err := net.SplitHostPort(hostport)
  86. if err != nil {
  87. return nil, "", false, err
  88. }
  89. if host == "" {
  90. host = "localhost"
  91. }
  92. if ln, err = net.Listen("tcp", hostport); err != nil {
  93. return nil, "", false, err
  94. }
  95. url = fmt.Sprint("http://", net.JoinHostPort(host, fmt.Sprint(ln.Addr().(*net.TCPAddr).Port)))
  96. return ln, url, isLocalhost(host), nil
  97. }
  98. func isLocalhost(host string) bool {
  99. for _, v := range []string{"localhost", "127.0.0.1", "[::1]", "::1"} {
  100. if host == v {
  101. return true
  102. }
  103. }
  104. return false
  105. }
  106. func openBrowser(url string, o *plugin.Options) {
  107. // Construct URL.
  108. u, _ := gourl.Parse(url)
  109. q := u.Query()
  110. for _, p := range []struct{ param, key string }{
  111. {"f", "focus"},
  112. {"s", "show"},
  113. {"i", "ignore"},
  114. {"h", "hide"},
  115. } {
  116. if v := pprofVariables[p.key].value; v != "" {
  117. q.Set(p.param, v)
  118. }
  119. }
  120. u.RawQuery = q.Encode()
  121. // Give server a little time to get ready.
  122. time.Sleep(time.Millisecond * 500)
  123. for _, b := range browsers() {
  124. args := strings.Split(b, " ")
  125. if len(args) == 0 {
  126. continue
  127. }
  128. viewer := exec.Command(args[0], append(args[1:], u.String())...)
  129. viewer.Stderr = os.Stderr
  130. if err := viewer.Start(); err == nil {
  131. return
  132. }
  133. }
  134. // No visualizer succeeded, so just print URL.
  135. o.UI.PrintErr(u.String())
  136. }
  137. func checkLocalHost(h http.Handler) http.Handler {
  138. return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
  139. host, _, err := net.SplitHostPort(req.RemoteAddr)
  140. if err != nil || !isLocalhost(host) {
  141. http.Error(w, "permission denied", http.StatusForbidden)
  142. return
  143. }
  144. h.ServeHTTP(w, req)
  145. })
  146. }
  147. // dot generates a web page containing an svg diagram.
  148. func (ui *webInterface) dot(w http.ResponseWriter, req *http.Request) {
  149. if req.URL.Path != "/" {
  150. http.NotFound(w, req)
  151. return
  152. }
  153. // Capture any error messages generated while generating a report.
  154. catcher := &errorCatcher{UI: ui.options.UI}
  155. options := *ui.options
  156. options.UI = catcher
  157. // Generate dot graph.
  158. args := []string{"svg"}
  159. vars := pprofVariables.makeCopy()
  160. vars["focus"].value = req.URL.Query().Get("f")
  161. vars["show"].value = req.URL.Query().Get("s")
  162. vars["ignore"].value = req.URL.Query().Get("i")
  163. vars["hide"].value = req.URL.Query().Get("h")
  164. _, rpt, err := generateRawReport(ui.prof, args, vars, &options)
  165. if err != nil {
  166. http.Error(w, err.Error(), http.StatusBadRequest)
  167. ui.options.UI.PrintErr(err)
  168. return
  169. }
  170. g, config := report.GetDOT(rpt)
  171. legend := config.Labels
  172. config.Labels = nil
  173. dot := &bytes.Buffer{}
  174. graph.ComposeDot(dot, g, &graph.DotAttributes{}, config)
  175. // Convert to svg.
  176. svg, err := dotToSvg(dot.Bytes())
  177. if err != nil {
  178. http.Error(w, "Could not execute dot; may need to install graphviz.",
  179. http.StatusNotImplemented)
  180. ui.options.UI.PrintErr("Failed to execute dot. Is Graphviz installed?\n", err)
  181. return
  182. }
  183. // Get regular expression for each node.
  184. nodes := []string{""}
  185. for _, n := range g.Nodes {
  186. nodes = append(nodes, regexp.QuoteMeta(n.Info.Name))
  187. }
  188. // Embed in html.
  189. file := getFromLegend(legend, "File: ", "unknown")
  190. profile := getFromLegend(legend, "Type: ", "unknown")
  191. data := struct {
  192. Title string
  193. Errors []string
  194. Svg template.HTML
  195. Legend []string
  196. Nodes []string
  197. Help map[string]string
  198. }{
  199. Title: file + " " + profile,
  200. Errors: catcher.errors,
  201. Svg: template.HTML(string(svg)),
  202. Legend: legend,
  203. Nodes: nodes,
  204. Help: ui.help,
  205. }
  206. html := &bytes.Buffer{}
  207. if err := graphTemplate.Execute(html, data); err != nil {
  208. http.Error(w, "internal template error", http.StatusInternalServerError)
  209. ui.options.UI.PrintErr(err)
  210. return
  211. }
  212. w.Header().Set("Content-Type", "text/html")
  213. w.Write(html.Bytes())
  214. }
  215. func dotToSvg(dot []byte) ([]byte, error) {
  216. cmd := exec.Command("dot", "-Tsvg")
  217. out := &bytes.Buffer{}
  218. cmd.Stdin, cmd.Stdout, cmd.Stderr = bytes.NewBuffer(dot), out, os.Stderr
  219. if err := cmd.Run(); err != nil {
  220. return nil, err
  221. }
  222. // Fix dot bug related to unquoted amperands.
  223. svg := bytes.Replace(out.Bytes(), []byte("&;"), []byte("&;"), -1)
  224. // Cleanup for embedding by dropping stuff before the <svg> start.
  225. if pos := bytes.Index(svg, []byte("<svg")); pos >= 0 {
  226. svg = svg[pos:]
  227. }
  228. return svg, nil
  229. }
  230. // disasm generates a web page containing disassembly.
  231. func (ui *webInterface) disasm(w http.ResponseWriter, req *http.Request) {
  232. ui.output(w, req, "disasm", "text/plain", pprofVariables.makeCopy())
  233. }
  234. // weblist generates a web page containing disassembly.
  235. func (ui *webInterface) weblist(w http.ResponseWriter, req *http.Request) {
  236. ui.output(w, req, "weblist", "text/html", pprofVariables.makeCopy())
  237. }
  238. // peek generates a web page listing callers/callers.
  239. func (ui *webInterface) peek(w http.ResponseWriter, req *http.Request) {
  240. vars := pprofVariables.makeCopy()
  241. vars.set("lines", "t") // Switch to line granularity
  242. ui.output(w, req, "peek", "text/plain", vars)
  243. }
  244. // output generates a webpage that contains the output of the specified pprof cmd.
  245. func (ui *webInterface) output(w http.ResponseWriter, req *http.Request, cmd, ctype string, vars variables) {
  246. focus := req.URL.Query().Get("f")
  247. if focus == "" {
  248. fmt.Fprintln(w, "no argument supplied for "+cmd)
  249. return
  250. }
  251. // Capture any error messages generated while generating a report.
  252. catcher := &errorCatcher{UI: ui.options.UI}
  253. options := *ui.options
  254. options.UI = catcher
  255. args := []string{cmd, focus}
  256. _, rpt, err := generateRawReport(ui.prof, args, vars, &options)
  257. if err != nil {
  258. http.Error(w, err.Error(), http.StatusBadRequest)
  259. ui.options.UI.PrintErr(err)
  260. return
  261. }
  262. out := &bytes.Buffer{}
  263. if err := report.Generate(out, rpt, ui.options.Obj); err != nil {
  264. http.Error(w, err.Error(), http.StatusBadRequest)
  265. ui.options.UI.PrintErr(err)
  266. return
  267. }
  268. if len(catcher.errors) > 0 {
  269. w.Header().Set("Content-Type", "text/plain")
  270. for _, msg := range catcher.errors {
  271. fmt.Println(w, msg)
  272. }
  273. return
  274. }
  275. w.Header().Set("Content-Type", ctype)
  276. io.Copy(w, out)
  277. }
  278. // getFromLegend returns the suffix of an entry in legend that starts
  279. // with param. It returns def if no such entry is found.
  280. func getFromLegend(legend []string, param, def string) string {
  281. for _, s := range legend {
  282. if strings.HasPrefix(s, param) {
  283. return s[len(param):]
  284. }
  285. }
  286. return def
  287. }