暫無描述

webui.go 11KB

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