Aucune description

webui.go 8.4KB

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