暫無描述

webui.go 10KB

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