github.com/guyezi/gofrontend@v0.0.0-20200228202240-7a62a49e62c0/libgo/go/net/http/pprof/pprof.go (about)

     1  // Copyright 2010 The Go Authors. All rights reserved.
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  
     5  // Package pprof serves via its HTTP server runtime profiling data
     6  // in the format expected by the pprof visualization tool.
     7  //
     8  // The package is typically only imported for the side effect of
     9  // registering its HTTP handlers.
    10  // The handled paths all begin with /debug/pprof/.
    11  //
    12  // To use pprof, link this package into your program:
    13  //	import _ "net/http/pprof"
    14  //
    15  // If your application is not already running an http server, you
    16  // need to start one. Add "net/http" and "log" to your imports and
    17  // the following code to your main function:
    18  //
    19  // 	go func() {
    20  // 		log.Println(http.ListenAndServe("localhost:6060", nil))
    21  // 	}()
    22  //
    23  // If you are not using DefaultServeMux, you will have to register handlers
    24  // with the mux you are using.
    25  //
    26  // Then use the pprof tool to look at the heap profile:
    27  //
    28  //	go tool pprof http://localhost:6060/debug/pprof/heap
    29  //
    30  // Or to look at a 30-second CPU profile:
    31  //
    32  //	go tool pprof http://localhost:6060/debug/pprof/profile?seconds=30
    33  //
    34  // Or to look at the goroutine blocking profile, after calling
    35  // runtime.SetBlockProfileRate in your program:
    36  //
    37  //	go tool pprof http://localhost:6060/debug/pprof/block
    38  //
    39  // Or to collect a 5-second execution trace:
    40  //
    41  //	wget http://localhost:6060/debug/pprof/trace?seconds=5
    42  //
    43  // Or to look at the holders of contended mutexes, after calling
    44  // runtime.SetMutexProfileFraction in your program:
    45  //
    46  //	go tool pprof http://localhost:6060/debug/pprof/mutex
    47  //
    48  // To view all available profiles, open http://localhost:6060/debug/pprof/
    49  // in your browser.
    50  //
    51  // For a study of the facility in action, visit
    52  //
    53  //	https://blog.golang.org/2011/06/profiling-go-programs.html
    54  //
    55  package pprof
    56  
    57  import (
    58  	"bufio"
    59  	"bytes"
    60  	"fmt"
    61  	"html/template"
    62  	"io"
    63  	"log"
    64  	"net/http"
    65  	"os"
    66  	"runtime"
    67  	"runtime/pprof"
    68  	"runtime/trace"
    69  	"sort"
    70  	"strconv"
    71  	"strings"
    72  	"time"
    73  )
    74  
    75  func init() {
    76  	http.HandleFunc("/debug/pprof/", Index)
    77  	http.HandleFunc("/debug/pprof/cmdline", Cmdline)
    78  	http.HandleFunc("/debug/pprof/profile", Profile)
    79  	http.HandleFunc("/debug/pprof/symbol", Symbol)
    80  	http.HandleFunc("/debug/pprof/trace", Trace)
    81  }
    82  
    83  // Cmdline responds with the running program's
    84  // command line, with arguments separated by NUL bytes.
    85  // The package initialization registers it as /debug/pprof/cmdline.
    86  func Cmdline(w http.ResponseWriter, r *http.Request) {
    87  	w.Header().Set("X-Content-Type-Options", "nosniff")
    88  	w.Header().Set("Content-Type", "text/plain; charset=utf-8")
    89  	fmt.Fprintf(w, strings.Join(os.Args, "\x00"))
    90  }
    91  
    92  func sleep(w http.ResponseWriter, d time.Duration) {
    93  	var clientGone <-chan bool
    94  	if cn, ok := w.(http.CloseNotifier); ok {
    95  		clientGone = cn.CloseNotify()
    96  	}
    97  	select {
    98  	case <-time.After(d):
    99  	case <-clientGone:
   100  	}
   101  }
   102  
   103  func durationExceedsWriteTimeout(r *http.Request, seconds float64) bool {
   104  	srv, ok := r.Context().Value(http.ServerContextKey).(*http.Server)
   105  	return ok && srv.WriteTimeout != 0 && seconds >= srv.WriteTimeout.Seconds()
   106  }
   107  
   108  func serveError(w http.ResponseWriter, status int, txt string) {
   109  	w.Header().Set("Content-Type", "text/plain; charset=utf-8")
   110  	w.Header().Set("X-Go-Pprof", "1")
   111  	w.Header().Del("Content-Disposition")
   112  	w.WriteHeader(status)
   113  	fmt.Fprintln(w, txt)
   114  }
   115  
   116  // Profile responds with the pprof-formatted cpu profile.
   117  // Profiling lasts for duration specified in seconds GET parameter, or for 30 seconds if not specified.
   118  // The package initialization registers it as /debug/pprof/profile.
   119  func Profile(w http.ResponseWriter, r *http.Request) {
   120  	w.Header().Set("X-Content-Type-Options", "nosniff")
   121  	sec, err := strconv.ParseInt(r.FormValue("seconds"), 10, 64)
   122  	if sec <= 0 || err != nil {
   123  		sec = 30
   124  	}
   125  
   126  	if durationExceedsWriteTimeout(r, float64(sec)) {
   127  		serveError(w, http.StatusBadRequest, "profile duration exceeds server's WriteTimeout")
   128  		return
   129  	}
   130  
   131  	// Set Content Type assuming StartCPUProfile will work,
   132  	// because if it does it starts writing.
   133  	w.Header().Set("Content-Type", "application/octet-stream")
   134  	w.Header().Set("Content-Disposition", `attachment; filename="profile"`)
   135  	if err := pprof.StartCPUProfile(w); err != nil {
   136  		// StartCPUProfile failed, so no writes yet.
   137  		serveError(w, http.StatusInternalServerError,
   138  			fmt.Sprintf("Could not enable CPU profiling: %s", err))
   139  		return
   140  	}
   141  	sleep(w, time.Duration(sec)*time.Second)
   142  	pprof.StopCPUProfile()
   143  }
   144  
   145  // Trace responds with the execution trace in binary form.
   146  // Tracing lasts for duration specified in seconds GET parameter, or for 1 second if not specified.
   147  // The package initialization registers it as /debug/pprof/trace.
   148  func Trace(w http.ResponseWriter, r *http.Request) {
   149  	w.Header().Set("X-Content-Type-Options", "nosniff")
   150  	sec, err := strconv.ParseFloat(r.FormValue("seconds"), 64)
   151  	if sec <= 0 || err != nil {
   152  		sec = 1
   153  	}
   154  
   155  	if durationExceedsWriteTimeout(r, sec) {
   156  		serveError(w, http.StatusBadRequest, "profile duration exceeds server's WriteTimeout")
   157  		return
   158  	}
   159  
   160  	// Set Content Type assuming trace.Start will work,
   161  	// because if it does it starts writing.
   162  	w.Header().Set("Content-Type", "application/octet-stream")
   163  	w.Header().Set("Content-Disposition", `attachment; filename="trace"`)
   164  	if err := trace.Start(w); err != nil {
   165  		// trace.Start failed, so no writes yet.
   166  		serveError(w, http.StatusInternalServerError,
   167  			fmt.Sprintf("Could not enable tracing: %s", err))
   168  		return
   169  	}
   170  	sleep(w, time.Duration(sec*float64(time.Second)))
   171  	trace.Stop()
   172  }
   173  
   174  // Symbol looks up the program counters listed in the request,
   175  // responding with a table mapping program counters to function names.
   176  // The package initialization registers it as /debug/pprof/symbol.
   177  func Symbol(w http.ResponseWriter, r *http.Request) {
   178  	w.Header().Set("X-Content-Type-Options", "nosniff")
   179  	w.Header().Set("Content-Type", "text/plain; charset=utf-8")
   180  
   181  	// We have to read the whole POST body before
   182  	// writing any output. Buffer the output here.
   183  	var buf bytes.Buffer
   184  
   185  	// We don't know how many symbols we have, but we
   186  	// do have symbol information. Pprof only cares whether
   187  	// this number is 0 (no symbols available) or > 0.
   188  	fmt.Fprintf(&buf, "num_symbols: 1\n")
   189  
   190  	var b *bufio.Reader
   191  	if r.Method == "POST" {
   192  		b = bufio.NewReader(r.Body)
   193  	} else {
   194  		b = bufio.NewReader(strings.NewReader(r.URL.RawQuery))
   195  	}
   196  
   197  	for {
   198  		word, err := b.ReadSlice('+')
   199  		if err == nil {
   200  			word = word[0 : len(word)-1] // trim +
   201  		}
   202  		pc, _ := strconv.ParseUint(string(word), 0, 64)
   203  		if pc != 0 {
   204  			f := runtime.FuncForPC(uintptr(pc))
   205  			if f != nil {
   206  				fmt.Fprintf(&buf, "%#x %s\n", pc, f.Name())
   207  			}
   208  		}
   209  
   210  		// Wait until here to check for err; the last
   211  		// symbol will have an err because it doesn't end in +.
   212  		if err != nil {
   213  			if err != io.EOF {
   214  				fmt.Fprintf(&buf, "reading request: %v\n", err)
   215  			}
   216  			break
   217  		}
   218  	}
   219  
   220  	w.Write(buf.Bytes())
   221  }
   222  
   223  // Handler returns an HTTP handler that serves the named profile.
   224  func Handler(name string) http.Handler {
   225  	return handler(name)
   226  }
   227  
   228  type handler string
   229  
   230  func (name handler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
   231  	w.Header().Set("X-Content-Type-Options", "nosniff")
   232  	p := pprof.Lookup(string(name))
   233  	if p == nil {
   234  		serveError(w, http.StatusNotFound, "Unknown profile")
   235  		return
   236  	}
   237  	gc, _ := strconv.Atoi(r.FormValue("gc"))
   238  	if name == "heap" && gc > 0 {
   239  		runtime.GC()
   240  	}
   241  	debug, _ := strconv.Atoi(r.FormValue("debug"))
   242  	if debug != 0 {
   243  		w.Header().Set("Content-Type", "text/plain; charset=utf-8")
   244  	} else {
   245  		w.Header().Set("Content-Type", "application/octet-stream")
   246  		w.Header().Set("Content-Disposition", fmt.Sprintf(`attachment; filename="%s"`, name))
   247  	}
   248  	p.WriteTo(w, debug)
   249  }
   250  
   251  var profileDescriptions = map[string]string{
   252  	"allocs":       "A sampling of all past memory allocations",
   253  	"block":        "Stack traces that led to blocking on synchronization primitives",
   254  	"cmdline":      "The command line invocation of the current program",
   255  	"goroutine":    "Stack traces of all current goroutines",
   256  	"heap":         "A sampling of memory allocations of live objects. You can specify the gc GET parameter to run GC before taking the heap sample.",
   257  	"mutex":        "Stack traces of holders of contended mutexes",
   258  	"profile":      "CPU profile. You can specify the duration in the seconds GET parameter. After you get the profile file, use the go tool pprof command to investigate the profile.",
   259  	"threadcreate": "Stack traces that led to the creation of new OS threads",
   260  	"trace":        "A trace of execution of the current program. You can specify the duration in the seconds GET parameter. After you get the trace file, use the go tool trace command to investigate the trace.",
   261  }
   262  
   263  // Index responds with the pprof-formatted profile named by the request.
   264  // For example, "/debug/pprof/heap" serves the "heap" profile.
   265  // Index responds to a request for "/debug/pprof/" with an HTML page
   266  // listing the available profiles.
   267  func Index(w http.ResponseWriter, r *http.Request) {
   268  	if strings.HasPrefix(r.URL.Path, "/debug/pprof/") {
   269  		name := strings.TrimPrefix(r.URL.Path, "/debug/pprof/")
   270  		if name != "" {
   271  			handler(name).ServeHTTP(w, r)
   272  			return
   273  		}
   274  	}
   275  
   276  	type profile struct {
   277  		Name  string
   278  		Href  string
   279  		Desc  string
   280  		Count int
   281  	}
   282  	var profiles []profile
   283  	for _, p := range pprof.Profiles() {
   284  		profiles = append(profiles, profile{
   285  			Name:  p.Name(),
   286  			Href:  p.Name() + "?debug=1",
   287  			Desc:  profileDescriptions[p.Name()],
   288  			Count: p.Count(),
   289  		})
   290  	}
   291  
   292  	// Adding other profiles exposed from within this package
   293  	for _, p := range []string{"cmdline", "profile", "trace"} {
   294  		profiles = append(profiles, profile{
   295  			Name: p,
   296  			Href: p,
   297  			Desc: profileDescriptions[p],
   298  		})
   299  	}
   300  
   301  	sort.Slice(profiles, func(i, j int) bool {
   302  		return profiles[i].Name < profiles[j].Name
   303  	})
   304  
   305  	if err := indexTmpl.Execute(w, profiles); err != nil {
   306  		log.Print(err)
   307  	}
   308  }
   309  
   310  var indexTmpl = template.Must(template.New("index").Parse(`<html>
   311  <head>
   312  <title>/debug/pprof/</title>
   313  <style>
   314  .profile-name{
   315  	display:inline-block;
   316  	width:6rem;
   317  }
   318  </style>
   319  </head>
   320  <body>
   321  /debug/pprof/<br>
   322  <br>
   323  Types of profiles available:
   324  <table>
   325  <thead><td>Count</td><td>Profile</td></thead>
   326  {{range .}}
   327  	<tr>
   328  	<td>{{.Count}}</td><td><a href={{.Href}}>{{.Name}}</a></td>
   329  	</tr>
   330  {{end}}
   331  </table>
   332  <a href="goroutine?debug=2">full goroutine stack dump</a>
   333  <br/>
   334  <p>
   335  Profile Descriptions:
   336  <ul>
   337  {{range .}}
   338  <li><div class=profile-name>{{.Name}}:</div> {{.Desc}}</li>
   339  {{end}}
   340  </ul>
   341  </p>
   342  </body>
   343  </html>
   344  `))