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  	"io"
    22  	"maps"
    23  	"net"
    24  	"net/http"
    25  	gourl "net/url"
    26  	"os"
    27  	"os/exec"
    28  	"slices"
    29  	"strconv"
    30  	"strings"
    31  	"time"
    32  
    33  	"github.com/google/pprof/internal/graph"
    34  	"github.com/google/pprof/internal/measurement"
    35  	"github.com/google/pprof/internal/plugin"
    36  	"github.com/google/pprof/internal/report"
    37  	"github.com/google/pprof/profile"
    38  )
    39  
    40  // webInterface holds the state needed for serving a browser based interface.
    41  type webInterface struct {
    42  	prof         *profile.Profile
    43  	copier       profileCopier
    44  	options      *plugin.Options
    45  	help         map[string]string
    46  	settingsFile string
    47  }
    48  
    49  func makeWebInterface(p *profile.Profile, copier profileCopier, opt *plugin.Options) (*webInterface, error) {
    50  	settingsFile, err := settingsFileName()
    51  	if err != nil {
    52  		return nil, err
    53  	}
    54  	return &webInterface{
    55  		prof:         p,
    56  		copier:       copier,
    57  		options:      opt,
    58  		help:         make(map[string]string),
    59  		settingsFile: settingsFile,
    60  	}, nil
    61  }
    62  
    63  // maxEntries is the maximum number of entries to print for text interfaces.
    64  const maxEntries = 50
    65  
    66  // errorCatcher is a UI that captures errors for reporting to the browser.
    67  type errorCatcher struct {
    68  	plugin.UI
    69  	errors []string
    70  }
    71  
    72  func (ec *errorCatcher) PrintErr(args ...interface{}) {
    73  	ec.errors = append(ec.errors, strings.TrimSuffix(fmt.Sprintln(args...), "\n"))
    74  	ec.UI.PrintErr(args...)
    75  }
    76  
    77  // webArgs contains arguments passed to templates in webhtml.go.
    78  type webArgs struct {
    79  	Title       string
    80  	Errors      []string
    81  	Total       int64
    82  	SampleTypes []string
    83  	Legend      []string
    84  	DocURL      string
    85  	Standalone  bool // True for command-line generation of HTML
    86  	Help        map[string]string
    87  	Nodes       []string
    88  	HTMLBody    template.HTML
    89  	TextBody    string
    90  	Top         []report.TextItem
    91  	Listing     report.WebListData
    92  	FlameGraph  template.JS
    93  	Stacks      template.JS
    94  	Configs     []configMenuEntry
    95  	UnitDefs    []measurement.UnitType
    96  }
    97  
    98  func serveWebInterface(hostport string, p *profile.Profile, o *plugin.Options, disableBrowser bool) error {
    99  	host, port, err := getHostAndPort(hostport)
   100  	if err != nil {
   101  		return err
   102  	}
   103  	interactiveMode = true
   104  	copier := makeProfileCopier(p)
   105  	ui, err := makeWebInterface(p, copier, o)
   106  	if err != nil {
   107  		return err
   108  	}
   109  	for n, c := range pprofCommands {
   110  		ui.help[n] = c.description
   111  	}
   112  	maps.Copy(ui.help, configHelp)
   113  	ui.help["details"] = "Show information about the profile and this view"
   114  	ui.help["graph"] = "Display profile as a directed graph"
   115  	ui.help["flamegraph"] = "Display profile as a flame graph"
   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  			"/flamegraph":    http.HandlerFunc(ui.stackView),
   134  			"/flamegraph2":   redirectWithQuery("flamegraph", http.StatusMovedPermanently), // Keep legacy URL working.
   135  			"/flamegraphold": redirectWithQuery("flamegraph", http.StatusMovedPermanently), // Keep legacy URL working.
   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", http.StatusTemporaryRedirect))
   213  	s := &http.Server{Handler: mux}
   214  	return s.Serve(ln)
   215  }
   216  
   217  // redirectWithQuery responds with a given redirect code, preserving query
   218  // parameters in the redirect URL. It does not convert relative paths to
   219  // absolute paths like http.Redirect does, so that HTTPServerArgs.Handlers can
   220  // generate relative redirects that work with the external prefixing.
   221  func redirectWithQuery(path string, code int) http.HandlerFunc {
   222  	return func(w http.ResponseWriter, r *http.Request) {
   223  		pathWithQuery := &gourl.URL{Path: path, RawQuery: r.URL.RawQuery}
   224  		w.Header().Set("Location", pathWithQuery.String())
   225  		w.WriteHeader(code)
   226  	}
   227  }
   228  
   229  func isLocalhost(host string) bool {
   230  	return slices.Contains([]string{"localhost", "127.0.0.1", "[::1]", "::1"}, host)
   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  // renderHTML generates html using the named template based on the contents of data.
   283  func renderHTML(dst io.Writer, tmpl string, rpt *report.Report, errList, legend []string, data webArgs) error {
   284  	file := getFromLegend(legend, "File: ", "unknown")
   285  	profile := getFromLegend(legend, "Type: ", "unknown")
   286  	data.Title = file + " " + profile
   287  	data.Errors = errList
   288  	data.Total = rpt.Total()
   289  	data.DocURL = rpt.DocURL()
   290  	data.Legend = legend
   291  	return getHTMLTemplates().ExecuteTemplate(dst, tmpl, data)
   292  }
   293  
   294  // render responds with html generated by passing data to the named template.
   295  func (ui *webInterface) render(w http.ResponseWriter, req *http.Request, tmpl string,
   296  	rpt *report.Report, errList, legend []string, data webArgs) {
   297  	data.SampleTypes = sampleTypes(ui.prof)
   298  	data.Help = ui.help
   299  	data.Configs = configMenu(ui.settingsFile, *req.URL)
   300  	html := &bytes.Buffer{}
   301  	if err := renderHTML(html, tmpl, rpt, errList, legend, data); err != nil {
   302  		http.Error(w, "internal template error", http.StatusInternalServerError)
   303  		ui.options.UI.PrintErr(err)
   304  		return
   305  	}
   306  	w.Header().Set("Content-Type", "text/html")
   307  	w.Write(html.Bytes())
   308  }
   309  
   310  // dot generates a web page containing an svg diagram.
   311  func (ui *webInterface) dot(w http.ResponseWriter, req *http.Request) {
   312  	rpt, errList := ui.makeReport(w, req, []string{"svg"}, nil)
   313  	if rpt == nil {
   314  		return // error already reported
   315  	}
   316  
   317  	// Generate dot graph.
   318  	g, config := report.GetDOT(rpt)
   319  	legend := config.Labels
   320  	config.Labels = nil
   321  	dot := &bytes.Buffer{}
   322  	graph.ComposeDot(dot, g, &graph.DotAttributes{}, config)
   323  
   324  	// Convert to svg.
   325  	svg, err := dotToSvg(dot.Bytes())
   326  	if err != nil {
   327  		http.Error(w, "Could not execute dot; may need to install graphviz.",
   328  			http.StatusNotImplemented)
   329  		ui.options.UI.PrintErr("Failed to execute dot. Is Graphviz installed?\n", err)
   330  		return
   331  	}
   332  
   333  	// Get all node names into an array.
   334  	nodes := []string{""} // dot starts with node numbered 1
   335  	for _, n := range g.Nodes {
   336  		nodes = append(nodes, n.Info.Name)
   337  	}
   338  
   339  	ui.render(w, req, "graph", rpt, errList, legend, webArgs{
   340  		HTMLBody: template.HTML(string(svg)),
   341  		Nodes:    nodes,
   342  	})
   343  }
   344  
   345  func dotToSvg(dot []byte) ([]byte, error) {
   346  	cmd := exec.Command("dot", "-Tsvg")
   347  	out := &bytes.Buffer{}
   348  	cmd.Stdin, cmd.Stdout, cmd.Stderr = bytes.NewBuffer(dot), out, os.Stderr
   349  	if err := cmd.Run(); err != nil {
   350  		return nil, err
   351  	}
   352  
   353  	// Fix dot bug related to unquoted ampersands.
   354  	svg := bytes.Replace(out.Bytes(), []byte("&;"), []byte("&;"), -1)
   355  
   356  	// Cleanup for embedding by dropping stuff before the <svg> start.
   357  	if pos := bytes.Index(svg, []byte("<svg")); pos >= 0 {
   358  		svg = svg[pos:]
   359  	}
   360  	return svg, nil
   361  }
   362  
   363  func (ui *webInterface) top(w http.ResponseWriter, req *http.Request) {
   364  	rpt, errList := ui.makeReport(w, req, []string{"top"}, func(cfg *config) {
   365  		cfg.NodeCount = 500
   366  	})
   367  	if rpt == nil {
   368  		return // error already reported
   369  	}
   370  	top, legend := report.TextItems(rpt)
   371  	var nodes []string
   372  	for _, item := range top {
   373  		nodes = append(nodes, item.Name)
   374  	}
   375  
   376  	ui.render(w, req, "top", rpt, errList, legend, webArgs{
   377  		Top:   top,
   378  		Nodes: nodes,
   379  	})
   380  }
   381  
   382  // disasm generates a web page containing disassembly.
   383  func (ui *webInterface) disasm(w http.ResponseWriter, req *http.Request) {
   384  	args := []string{"disasm", req.URL.Query().Get("f")}
   385  	rpt, errList := ui.makeReport(w, req, args, nil)
   386  	if rpt == nil {
   387  		return // error already reported
   388  	}
   389  
   390  	out := &bytes.Buffer{}
   391  	if err := report.PrintAssembly(out, rpt, ui.options.Obj, maxEntries); err != nil {
   392  		http.Error(w, err.Error(), http.StatusBadRequest)
   393  		ui.options.UI.PrintErr(err)
   394  		return
   395  	}
   396  
   397  	legend := report.ProfileLabels(rpt)
   398  	ui.render(w, req, "plaintext", rpt, errList, legend, webArgs{
   399  		TextBody: out.String(),
   400  	})
   401  
   402  }
   403  
   404  // source generates a web page containing source code annotated with profile
   405  // data.
   406  func (ui *webInterface) source(w http.ResponseWriter, req *http.Request) {
   407  	args := []string{"weblist", req.URL.Query().Get("f")}
   408  	rpt, errList := ui.makeReport(w, req, args, nil)
   409  	if rpt == nil {
   410  		return // error already reported
   411  	}
   412  
   413  	// Generate source listing.
   414  	listing, err := report.MakeWebList(rpt, ui.options.Obj, maxEntries)
   415  	if err != nil {
   416  		http.Error(w, err.Error(), http.StatusBadRequest)
   417  		ui.options.UI.PrintErr(err)
   418  		return
   419  	}
   420  
   421  	legend := report.ProfileLabels(rpt)
   422  	ui.render(w, req, "sourcelisting", rpt, errList, legend, webArgs{
   423  		Listing: listing,
   424  	})
   425  }
   426  
   427  // peek generates a web page listing callers/callers.
   428  func (ui *webInterface) peek(w http.ResponseWriter, req *http.Request) {
   429  	args := []string{"peek", req.URL.Query().Get("f")}
   430  	rpt, errList := ui.makeReport(w, req, args, func(cfg *config) {
   431  		cfg.Granularity = "lines"
   432  	})
   433  	if rpt == nil {
   434  		return // error already reported
   435  	}
   436  
   437  	out := &bytes.Buffer{}
   438  	if err := report.Generate(out, rpt, ui.options.Obj); err != nil {
   439  		http.Error(w, err.Error(), http.StatusBadRequest)
   440  		ui.options.UI.PrintErr(err)
   441  		return
   442  	}
   443  
   444  	legend := report.ProfileLabels(rpt)
   445  	ui.render(w, req, "plaintext", rpt, errList, legend, webArgs{
   446  		TextBody: out.String(),
   447  	})
   448  }
   449  
   450  // saveConfig saves URL configuration.
   451  func (ui *webInterface) saveConfig(w http.ResponseWriter, req *http.Request) {
   452  	if err := setConfig(ui.settingsFile, *req.URL); err != nil {
   453  		http.Error(w, err.Error(), http.StatusBadRequest)
   454  		ui.options.UI.PrintErr(err)
   455  		return
   456  	}
   457  }
   458  
   459  // deleteConfig deletes a configuration.
   460  func (ui *webInterface) deleteConfig(w http.ResponseWriter, req *http.Request) {
   461  	name := req.URL.Query().Get("config")
   462  	if err := removeConfig(ui.settingsFile, name); err != nil {
   463  		http.Error(w, err.Error(), http.StatusBadRequest)
   464  		ui.options.UI.PrintErr(err)
   465  		return
   466  	}
   467  }
   468  
   469  // getFromLegend returns the suffix of an entry in legend that starts
   470  // with param.  It returns def if no such entry is found.
   471  func getFromLegend(legend []string, param, def string) string {
   472  	for _, s := range legend {
   473  		if strings.HasPrefix(s, param) {
   474  			return s[len(param):]
   475  		}
   476  	}
   477  	return def
   478  }
   479  

View as plain text