Bez popisu

webui.go 11KB

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