Source file src/cmd/vendor/github.com/google/pprof/internal/driver/webui.go

     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  
    15  package driver
    16  
    17  import (
    18  	"bytes"
    19  	"fmt"
    20  	"html/template"
    21  	"net"
    22  	"net/http"
    23  	gourl "net/url"
    24  	"os"
    25  	"os/exec"
    26  	"strconv"
    27  	"strings"
    28  	"time"
    29  
    30  	"github.com/google/pprof/internal/graph"
    31  	"github.com/google/pprof/internal/plugin"
    32  	"github.com/google/pprof/internal/report"
    33  	"github.com/google/pprof/profile"
    34  )
    35  
    36  // webInterface holds the state needed for serving a browser based interface.
    37  type webInterface struct {
    38  	prof         *profile.Profile
    39  	copier       profileCopier
    40  	options      *plugin.Options
    41  	help         map[string]string
    42  	templates    *template.Template
    43  	settingsFile string
    44  }
    45  
    46  func makeWebInterface(p *profile.Profile, copier profileCopier, opt *plugin.Options) (*webInterface, error) {
    47  	settingsFile, err := settingsFileName()
    48  	if err != nil {
    49  		return nil, err
    50  	}
    51  	templates := template.New("templategroup")
    52  	addTemplates(templates)
    53  	report.AddSourceTemplates(templates)
    54  	return &webInterface{
    55  		prof:         p,
    56  		copier:       copier,
    57  		options:      opt,
    58  		help:         make(map[string]string),
    59  		templates:    templates,
    60  		settingsFile: settingsFile,
    61  	}, nil
    62  }
    63  
    64  // maxEntries is the maximum number of entries to print for text interfaces.
    65  const maxEntries = 50
    66  
    67  // errorCatcher is a UI that captures errors for reporting to the browser.
    68  type errorCatcher struct {
    69  	plugin.UI
    70  	errors []string
    71  }
    72  
    73  func (ec *errorCatcher) PrintErr(args ...interface{}) {
    74  	ec.errors = append(ec.errors, strings.TrimSuffix(fmt.Sprintln(args...), "\n"))
    75  	ec.UI.PrintErr(args...)
    76  }
    77  
    78  // webArgs contains arguments passed to templates in webhtml.go.
    79  type webArgs struct {
    80  	Title       string
    81  	Errors      []string
    82  	Total       int64
    83  	SampleTypes []string
    84  	Legend      []string
    85  	Help        map[string]string
    86  	Nodes       []string
    87  	HTMLBody    template.HTML
    88  	TextBody    string
    89  	Top         []report.TextItem
    90  	FlameGraph  template.JS
    91  	Stacks      template.JS
    92  	Configs     []configMenuEntry
    93  }
    94  
    95  func serveWebInterface(hostport string, p *profile.Profile, o *plugin.Options, disableBrowser bool) error {
    96  	host, port, err := getHostAndPort(hostport)
    97  	if err != nil {
    98  		return err
    99  	}
   100  	interactiveMode = true
   101  	copier := makeProfileCopier(p)
   102  	ui, err := makeWebInterface(p, copier, o)
   103  	if err != nil {
   104  		return err
   105  	}
   106  	for n, c := range pprofCommands {
   107  		ui.help[n] = c.description
   108  	}
   109  	for n, help := range configHelp {
   110  		ui.help[n] = help
   111  	}
   112  	ui.help["details"] = "Show information about the profile and this view"
   113  	ui.help["graph"] = "Display profile as a directed graph"
   114  	ui.help["flamegraph"] = "Display profile as a flame graph"
   115  	ui.help["flamegraphold"] = "Display profile as a flame graph (old version; slated for removal)"
   116  	ui.help["reset"] = "Show the entire profile"
   117  	ui.help["save_config"] = "Save current settings"
   118  
   119  	server := o.HTTPServer
   120  	if server == nil {
   121  		server = defaultWebServer
   122  	}
   123  	args := &plugin.HTTPServerArgs{
   124  		Hostport: net.JoinHostPort(host, strconv.Itoa(port)),
   125  		Host:     host,
   126  		Port:     port,
   127  		Handlers: map[string]http.Handler{
   128  			"/":              http.HandlerFunc(ui.dot),
   129  			"/top":           http.HandlerFunc(ui.top),
   130  			"/disasm":        http.HandlerFunc(ui.disasm),
   131  			"/source":        http.HandlerFunc(ui.source),
   132  			"/peek":          http.HandlerFunc(ui.peek),
   133  			"/flamegraphold": http.HandlerFunc(ui.flamegraph),
   134  			"/flamegraph":    http.HandlerFunc(ui.stackView),
   135  			"/flamegraph2":   http.HandlerFunc(ui.stackView), // Support older URL
   136  			"/saveconfig":    http.HandlerFunc(ui.saveConfig),
   137  			"/deleteconfig":  http.HandlerFunc(ui.deleteConfig),
   138  			"/download": http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
   139  				w.Header().Set("Content-Type", "application/vnd.google.protobuf+gzip")
   140  				w.Header().Set("Content-Disposition", "attachment;filename=profile.pb.gz")
   141  				p.Write(w)
   142  			}),
   143  		},
   144  	}
   145  
   146  	url := "http://" + args.Hostport
   147  
   148  	o.UI.Print("Serving web UI on ", url)
   149  
   150  	if o.UI.WantBrowser() && !disableBrowser {
   151  		go openBrowser(url, o)
   152  	}
   153  	return server(args)
   154  }
   155  
   156  func getHostAndPort(hostport string) (string, int, error) {
   157  	host, portStr, err := net.SplitHostPort(hostport)
   158  	if err != nil {
   159  		return "", 0, fmt.Errorf("could not split http address: %v", err)
   160  	}
   161  	if host == "" {
   162  		host = "localhost"
   163  	}
   164  	var port int
   165  	if portStr == "" {
   166  		ln, err := net.Listen("tcp", net.JoinHostPort(host, "0"))
   167  		if err != nil {
   168  			return "", 0, fmt.Errorf("could not generate random port: %v", err)
   169  		}
   170  		port = ln.Addr().(*net.TCPAddr).Port
   171  		err = ln.Close()
   172  		if err != nil {
   173  			return "", 0, fmt.Errorf("could not generate random port: %v", err)
   174  		}
   175  	} else {
   176  		port, err = strconv.Atoi(portStr)
   177  		if err != nil {
   178  			return "", 0, fmt.Errorf("invalid port number: %v", err)
   179  		}
   180  	}
   181  	return host, port, nil
   182  }
   183  func defaultWebServer(args *plugin.HTTPServerArgs) error {
   184  	ln, err := net.Listen("tcp", args.Hostport)
   185  	if err != nil {
   186  		return err
   187  	}
   188  	isLocal := isLocalhost(args.Host)
   189  	handler := http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
   190  		if isLocal {
   191  			// Only allow local clients
   192  			host, _, err := net.SplitHostPort(req.RemoteAddr)
   193  			if err != nil || !isLocalhost(host) {
   194  				http.Error(w, "permission denied", http.StatusForbidden)
   195  				return
   196  			}
   197  		}
   198  		h := args.Handlers[req.URL.Path]
   199  		if h == nil {
   200  			// Fall back to default behavior
   201  			h = http.DefaultServeMux
   202  		}
   203  		h.ServeHTTP(w, req)
   204  	})
   205  
   206  	// We serve the ui at /ui/ and redirect there from the root. This is done
   207  	// to surface any problems with serving the ui at a non-root early. See:
   208  	//
   209  	// https://github.com/google/pprof/pull/348
   210  	mux := http.NewServeMux()
   211  	mux.Handle("/ui/", http.StripPrefix("/ui", handler))
   212  	mux.Handle("/", redirectWithQuery("/ui"))
   213  	s := &http.Server{Handler: mux}
   214  	return s.Serve(ln)
   215  }
   216  
   217  func redirectWithQuery(path string) http.HandlerFunc {
   218  	return func(w http.ResponseWriter, r *http.Request) {
   219  		pathWithQuery := &gourl.URL{Path: path, RawQuery: r.URL.RawQuery}
   220  		http.Redirect(w, r, pathWithQuery.String(), http.StatusTemporaryRedirect)
   221  	}
   222  }
   223  
   224  func isLocalhost(host string) bool {
   225  	for _, v := range []string{"localhost", "127.0.0.1", "[::1]", "::1"} {
   226  		if host == v {
   227  			return true
   228  		}
   229  	}
   230  	return false
   231  }
   232  
   233  func openBrowser(url string, o *plugin.Options) {
   234  	// Construct URL.
   235  	baseURL, _ := gourl.Parse(url)
   236  	current := currentConfig()
   237  	u, _ := current.makeURL(*baseURL)
   238  
   239  	// Give server a little time to get ready.
   240  	time.Sleep(time.Millisecond * 500)
   241  
   242  	for _, b := range browsers() {
   243  		args := strings.Split(b, " ")
   244  		if len(args) == 0 {
   245  			continue
   246  		}
   247  		viewer := exec.Command(args[0], append(args[1:], u.String())...)
   248  		viewer.Stderr = os.Stderr
   249  		if err := viewer.Start(); err == nil {
   250  			return
   251  		}
   252  	}
   253  	// No visualizer succeeded, so just print URL.
   254  	o.UI.PrintErr(u.String())
   255  }
   256  
   257  // makeReport generates a report for the specified command.
   258  // If configEditor is not null, it is used to edit the config used for the report.
   259  func (ui *webInterface) makeReport(w http.ResponseWriter, req *http.Request,
   260  	cmd []string, configEditor func(*config)) (*report.Report, []string) {
   261  	cfg := currentConfig()
   262  	if err := cfg.applyURL(req.URL.Query()); err != nil {
   263  		http.Error(w, err.Error(), http.StatusBadRequest)
   264  		ui.options.UI.PrintErr(err)
   265  		return nil, nil
   266  	}
   267  	if configEditor != nil {
   268  		configEditor(&cfg)
   269  	}
   270  	catcher := &errorCatcher{UI: ui.options.UI}
   271  	options := *ui.options
   272  	options.UI = catcher
   273  	_, rpt, err := generateRawReport(ui.copier.newCopy(), cmd, cfg, &options)
   274  	if err != nil {
   275  		http.Error(w, err.Error(), http.StatusBadRequest)
   276  		ui.options.UI.PrintErr(err)
   277  		return nil, nil
   278  	}
   279  	return rpt, catcher.errors
   280  }
   281  
   282  // render generates html using the named template based on the contents of data.
   283  func (ui *webInterface) render(w http.ResponseWriter, req *http.Request, tmpl string,
   284  	rpt *report.Report, errList, legend []string, data webArgs) {
   285  	file := getFromLegend(legend, "File: ", "unknown")
   286  	profile := getFromLegend(legend, "Type: ", "unknown")
   287  	data.Title = file + " " + profile
   288  	data.Errors = errList
   289  	data.Total = rpt.Total()
   290  	data.SampleTypes = sampleTypes(ui.prof)
   291  	data.Legend = legend
   292  	data.Help = ui.help
   293  	data.Configs = configMenu(ui.settingsFile, *req.URL)
   294  
   295  	html := &bytes.Buffer{}
   296  	if err := ui.templates.ExecuteTemplate(html, tmpl, data); err != nil {
   297  		http.Error(w, "internal template error", http.StatusInternalServerError)
   298  		ui.options.UI.PrintErr(err)
   299  		return
   300  	}
   301  	w.Header().Set("Content-Type", "text/html")
   302  	w.Write(html.Bytes())
   303  }
   304  
   305  // dot generates a web page containing an svg diagram.
   306  func (ui *webInterface) dot(w http.ResponseWriter, req *http.Request) {
   307  	rpt, errList := ui.makeReport(w, req, []string{"svg"}, nil)
   308  	if rpt == nil {
   309  		return // error already reported
   310  	}
   311  
   312  	// Generate dot graph.
   313  	g, config := report.GetDOT(rpt)
   314  	legend := config.Labels
   315  	config.Labels = nil
   316  	dot := &bytes.Buffer{}
   317  	graph.ComposeDot(dot, g, &graph.DotAttributes{}, config)
   318  
   319  	// Convert to svg.
   320  	svg, err := dotToSvg(dot.Bytes())
   321  	if err != nil {
   322  		http.Error(w, "Could not execute dot; may need to install graphviz.",
   323  			http.StatusNotImplemented)
   324  		ui.options.UI.PrintErr("Failed to execute dot. Is Graphviz installed?\n", err)
   325  		return
   326  	}
   327  
   328  	// Get all node names into an array.
   329  	nodes := []string{""} // dot starts with node numbered 1
   330  	for _, n := range g.Nodes {
   331  		nodes = append(nodes, n.Info.Name)
   332  	}
   333  
   334  	ui.render(w, req, "graph", rpt, errList, legend, webArgs{
   335  		HTMLBody: template.HTML(string(svg)),
   336  		Nodes:    nodes,
   337  	})
   338  }
   339  
   340  func dotToSvg(dot []byte) ([]byte, error) {
   341  	cmd := exec.Command("dot", "-Tsvg")
   342  	out := &bytes.Buffer{}
   343  	cmd.Stdin, cmd.Stdout, cmd.Stderr = bytes.NewBuffer(dot), out, os.Stderr
   344  	if err := cmd.Run(); err != nil {
   345  		return nil, err
   346  	}
   347  
   348  	// Fix dot bug related to unquoted ampersands.
   349  	svg := bytes.Replace(out.Bytes(), []byte("&;"), []byte("&;"), -1)
   350  
   351  	// Cleanup for embedding by dropping stuff before the <svg> start.
   352  	if pos := bytes.Index(svg, []byte("<svg")); pos >= 0 {
   353  		svg = svg[pos:]
   354  	}
   355  	return svg, nil
   356  }
   357  
   358  func (ui *webInterface) top(w http.ResponseWriter, req *http.Request) {
   359  	rpt, errList := ui.makeReport(w, req, []string{"top"}, func(cfg *config) {
   360  		cfg.NodeCount = 500
   361  	})
   362  	if rpt == nil {
   363  		return // error already reported
   364  	}
   365  	top, legend := report.TextItems(rpt)
   366  	var nodes []string
   367  	for _, item := range top {
   368  		nodes = append(nodes, item.Name)
   369  	}
   370  
   371  	ui.render(w, req, "top", rpt, errList, legend, webArgs{
   372  		Top:   top,
   373  		Nodes: nodes,
   374  	})
   375  }
   376  
   377  // disasm generates a web page containing disassembly.
   378  func (ui *webInterface) disasm(w http.ResponseWriter, req *http.Request) {
   379  	args := []string{"disasm", req.URL.Query().Get("f")}
   380  	rpt, errList := ui.makeReport(w, req, args, nil)
   381  	if rpt == nil {
   382  		return // error already reported
   383  	}
   384  
   385  	out := &bytes.Buffer{}
   386  	if err := report.PrintAssembly(out, rpt, ui.options.Obj, maxEntries); err != nil {
   387  		http.Error(w, err.Error(), http.StatusBadRequest)
   388  		ui.options.UI.PrintErr(err)
   389  		return
   390  	}
   391  
   392  	legend := report.ProfileLabels(rpt)
   393  	ui.render(w, req, "plaintext", rpt, errList, legend, webArgs{
   394  		TextBody: out.String(),
   395  	})
   396  
   397  }
   398  
   399  // source generates a web page containing source code annotated with profile
   400  // data.
   401  func (ui *webInterface) source(w http.ResponseWriter, req *http.Request) {
   402  	args := []string{"weblist", req.URL.Query().Get("f")}
   403  	rpt, errList := ui.makeReport(w, req, args, nil)
   404  	if rpt == nil {
   405  		return // error already reported
   406  	}
   407  
   408  	// Generate source listing.
   409  	var body bytes.Buffer
   410  	if err := report.PrintWebList(&body, rpt, ui.options.Obj, maxEntries); err != nil {
   411  		http.Error(w, err.Error(), http.StatusBadRequest)
   412  		ui.options.UI.PrintErr(err)
   413  		return
   414  	}
   415  
   416  	legend := report.ProfileLabels(rpt)
   417  	ui.render(w, req, "sourcelisting", rpt, errList, legend, webArgs{
   418  		HTMLBody: template.HTML(body.String()),
   419  	})
   420  }
   421  
   422  // peek generates a web page listing callers/callers.
   423  func (ui *webInterface) peek(w http.ResponseWriter, req *http.Request) {
   424  	args := []string{"peek", req.URL.Query().Get("f")}
   425  	rpt, errList := ui.makeReport(w, req, args, func(cfg *config) {
   426  		cfg.Granularity = "lines"
   427  	})
   428  	if rpt == nil {
   429  		return // error already reported
   430  	}
   431  
   432  	out := &bytes.Buffer{}
   433  	if err := report.Generate(out, rpt, ui.options.Obj); err != nil {
   434  		http.Error(w, err.Error(), http.StatusBadRequest)
   435  		ui.options.UI.PrintErr(err)
   436  		return
   437  	}
   438  
   439  	legend := report.ProfileLabels(rpt)
   440  	ui.render(w, req, "plaintext", rpt, errList, legend, webArgs{
   441  		TextBody: out.String(),
   442  	})
   443  }
   444  
   445  // saveConfig saves URL configuration.
   446  func (ui *webInterface) saveConfig(w http.ResponseWriter, req *http.Request) {
   447  	if err := setConfig(ui.settingsFile, *req.URL); err != nil {
   448  		http.Error(w, err.Error(), http.StatusBadRequest)
   449  		ui.options.UI.PrintErr(err)
   450  		return
   451  	}
   452  }
   453  
   454  // deleteConfig deletes a configuration.
   455  func (ui *webInterface) deleteConfig(w http.ResponseWriter, req *http.Request) {
   456  	name := req.URL.Query().Get("config")
   457  	if err := removeConfig(ui.settingsFile, name); err != nil {
   458  		http.Error(w, err.Error(), http.StatusBadRequest)
   459  		ui.options.UI.PrintErr(err)
   460  		return
   461  	}
   462  }
   463  
   464  // getFromLegend returns the suffix of an entry in legend that starts
   465  // with param.  It returns def if no such entry is found.
   466  func getFromLegend(legend []string, param, def string) string {
   467  	for _, s := range legend {
   468  		if strings.HasPrefix(s, param) {
   469  			return s[len(param):]
   470  		}
   471  	}
   472  	return def
   473  }
   474  

View as plain text