Aucune description

webui.go 7.8KB

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