Нема описа

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