github.com/slayercat/go@v0.0.0-20170428012452-c51559813f61/src/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  // Then use the pprof tool to look at the heap profile:
    24  //
    25  //	go tool pprof http://localhost:6060/debug/pprof/heap
    26  //
    27  // Or to look at a 30-second CPU profile:
    28  //
    29  //	go tool pprof http://localhost:6060/debug/pprof/profile
    30  //
    31  // Or to look at the goroutine blocking profile, after calling
    32  // runtime.SetBlockProfileRate in your program:
    33  //
    34  //	go tool pprof http://localhost:6060/debug/pprof/block
    35  //
    36  // Or to collect a 5-second execution trace:
    37  //
    38  //	wget http://localhost:6060/debug/pprof/trace?seconds=5
    39  //
    40  // To view all available profiles, open http://localhost:6060/debug/pprof/
    41  // in your browser.
    42  //
    43  // For a study of the facility in action, visit
    44  //
    45  //	https://blog.golang.org/2011/06/profiling-go-programs.html
    46  //
    47  package pprof
    48  
    49  import (
    50  	"bufio"
    51  	"bytes"
    52  	"fmt"
    53  	"html/template"
    54  	"io"
    55  	"log"
    56  	"net/http"
    57  	"os"
    58  	"runtime"
    59  	"runtime/pprof"
    60  	"runtime/trace"
    61  	"strconv"
    62  	"strings"
    63  	"time"
    64  )
    65  
    66  func init() {
    67  	http.Handle("/debug/pprof/", http.HandlerFunc(Index))
    68  	http.Handle("/debug/pprof/cmdline", http.HandlerFunc(Cmdline))
    69  	http.Handle("/debug/pprof/profile", http.HandlerFunc(Profile))
    70  	http.Handle("/debug/pprof/symbol", http.HandlerFunc(Symbol))
    71  	http.Handle("/debug/pprof/trace", http.HandlerFunc(Trace))
    72  }
    73  
    74  // Cmdline responds with the running program's
    75  // command line, with arguments separated by NUL bytes.
    76  // The package initialization registers it as /debug/pprof/cmdline.
    77  func Cmdline(w http.ResponseWriter, r *http.Request) {
    78  	w.Header().Set("Content-Type", "text/plain; charset=utf-8")
    79  	fmt.Fprintf(w, strings.Join(os.Args, "\x00"))
    80  }
    81  
    82  func sleep(w http.ResponseWriter, d time.Duration) {
    83  	var clientGone <-chan bool
    84  	if cn, ok := w.(http.CloseNotifier); ok {
    85  		clientGone = cn.CloseNotify()
    86  	}
    87  	select {
    88  	case <-time.After(d):
    89  	case <-clientGone:
    90  	}
    91  }
    92  
    93  func durationExceedsWriteTimeout(r *http.Request, seconds float64) bool {
    94  	srv, ok := r.Context().Value(http.ServerContextKey).(*http.Server)
    95  	return ok && srv.WriteTimeout != 0 && seconds >= srv.WriteTimeout.Seconds()
    96  }
    97  
    98  // Profile responds with the pprof-formatted cpu profile.
    99  // The package initialization registers it as /debug/pprof/profile.
   100  func Profile(w http.ResponseWriter, r *http.Request) {
   101  	sec, _ := strconv.ParseInt(r.FormValue("seconds"), 10, 64)
   102  	if sec == 0 {
   103  		sec = 30
   104  	}
   105  
   106  	if durationExceedsWriteTimeout(r, float64(sec)) {
   107  		w.Header().Set("Content-Type", "text/plain; charset=utf-8")
   108  		w.Header().Set("X-Go-Pprof", "1")
   109  		w.WriteHeader(http.StatusBadRequest)
   110  		fmt.Fprintln(w, "profile duration exceeds server's WriteTimeout")
   111  		return
   112  	}
   113  
   114  	// Set Content Type assuming StartCPUProfile will work,
   115  	// because if it does it starts writing.
   116  	w.Header().Set("Content-Type", "application/octet-stream")
   117  	if err := pprof.StartCPUProfile(w); err != nil {
   118  		// StartCPUProfile failed, so no writes yet.
   119  		// Can change header back to text content
   120  		// and send error code.
   121  		w.Header().Set("Content-Type", "text/plain; charset=utf-8")
   122  		w.Header().Set("X-Go-Pprof", "1")
   123  		w.WriteHeader(http.StatusInternalServerError)
   124  		fmt.Fprintf(w, "Could not enable CPU profiling: %s\n", err)
   125  		return
   126  	}
   127  	sleep(w, time.Duration(sec)*time.Second)
   128  	pprof.StopCPUProfile()
   129  }
   130  
   131  // Trace responds with the execution trace in binary form.
   132  // Tracing lasts for duration specified in seconds GET parameter, or for 1 second if not specified.
   133  // The package initialization registers it as /debug/pprof/trace.
   134  func Trace(w http.ResponseWriter, r *http.Request) {
   135  	sec, err := strconv.ParseFloat(r.FormValue("seconds"), 64)
   136  	if sec <= 0 || err != nil {
   137  		sec = 1
   138  	}
   139  
   140  	if durationExceedsWriteTimeout(r, sec) {
   141  		w.Header().Set("Content-Type", "text/plain; charset=utf-8")
   142  		w.Header().Set("X-Go-Pprof", "1")
   143  		w.WriteHeader(http.StatusBadRequest)
   144  		fmt.Fprintln(w, "profile duration exceeds server's WriteTimeout")
   145  		return
   146  	}
   147  
   148  	// Set Content Type assuming trace.Start will work,
   149  	// because if it does it starts writing.
   150  	w.Header().Set("Content-Type", "application/octet-stream")
   151  	if err := trace.Start(w); err != nil {
   152  		// trace.Start failed, so no writes yet.
   153  		// Can change header back to text content and send error code.
   154  		w.Header().Set("Content-Type", "text/plain; charset=utf-8")
   155  		w.Header().Set("X-Go-Pprof", "1")
   156  		w.WriteHeader(http.StatusInternalServerError)
   157  		fmt.Fprintf(w, "Could not enable tracing: %s\n", err)
   158  		return
   159  	}
   160  	sleep(w, time.Duration(sec*float64(time.Second)))
   161  	trace.Stop()
   162  }
   163  
   164  // Symbol looks up the program counters listed in the request,
   165  // responding with a table mapping program counters to function names.
   166  // The package initialization registers it as /debug/pprof/symbol.
   167  func Symbol(w http.ResponseWriter, r *http.Request) {
   168  	w.Header().Set("Content-Type", "text/plain; charset=utf-8")
   169  
   170  	// We have to read the whole POST body before
   171  	// writing any output. Buffer the output here.
   172  	var buf bytes.Buffer
   173  
   174  	// We don't know how many symbols we have, but we
   175  	// do have symbol information. Pprof only cares whether
   176  	// this number is 0 (no symbols available) or > 0.
   177  	fmt.Fprintf(&buf, "num_symbols: 1\n")
   178  
   179  	var b *bufio.Reader
   180  	if r.Method == "POST" {
   181  		b = bufio.NewReader(r.Body)
   182  	} else {
   183  		b = bufio.NewReader(strings.NewReader(r.URL.RawQuery))
   184  	}
   185  
   186  	for {
   187  		word, err := b.ReadSlice('+')
   188  		if err == nil {
   189  			word = word[0 : len(word)-1] // trim +
   190  		}
   191  		pc, _ := strconv.ParseUint(string(word), 0, 64)
   192  		if pc != 0 {
   193  			f := runtime.FuncForPC(uintptr(pc))
   194  			if f != nil {
   195  				fmt.Fprintf(&buf, "%#x %s\n", pc, f.Name())
   196  			}
   197  		}
   198  
   199  		// Wait until here to check for err; the last
   200  		// symbol will have an err because it doesn't end in +.
   201  		if err != nil {
   202  			if err != io.EOF {
   203  				fmt.Fprintf(&buf, "reading request: %v\n", err)
   204  			}
   205  			break
   206  		}
   207  	}
   208  
   209  	w.Write(buf.Bytes())
   210  }
   211  
   212  // Handler returns an HTTP handler that serves the named profile.
   213  func Handler(name string) http.Handler {
   214  	return handler(name)
   215  }
   216  
   217  type handler string
   218  
   219  func (name handler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
   220  	w.Header().Set("Content-Type", "text/plain; charset=utf-8")
   221  	debug, _ := strconv.Atoi(r.FormValue("debug"))
   222  	p := pprof.Lookup(string(name))
   223  	if p == nil {
   224  		w.WriteHeader(404)
   225  		fmt.Fprintf(w, "Unknown profile: %s\n", name)
   226  		return
   227  	}
   228  	gc, _ := strconv.Atoi(r.FormValue("gc"))
   229  	if name == "heap" && gc > 0 {
   230  		runtime.GC()
   231  	}
   232  	p.WriteTo(w, debug)
   233  }
   234  
   235  // Index responds with the pprof-formatted profile named by the request.
   236  // For example, "/debug/pprof/heap" serves the "heap" profile.
   237  // Index responds to a request for "/debug/pprof/" with an HTML page
   238  // listing the available profiles.
   239  func Index(w http.ResponseWriter, r *http.Request) {
   240  	if strings.HasPrefix(r.URL.Path, "/debug/pprof/") {
   241  		name := strings.TrimPrefix(r.URL.Path, "/debug/pprof/")
   242  		if name != "" {
   243  			handler(name).ServeHTTP(w, r)
   244  			return
   245  		}
   246  	}
   247  
   248  	profiles := pprof.Profiles()
   249  	if err := indexTmpl.Execute(w, profiles); err != nil {
   250  		log.Print(err)
   251  	}
   252  }
   253  
   254  var indexTmpl = template.Must(template.New("index").Parse(`<html>
   255  <head>
   256  <title>/debug/pprof/</title>
   257  </head>
   258  <body>
   259  /debug/pprof/<br>
   260  <br>
   261  profiles:<br>
   262  <table>
   263  {{range .}}
   264  <tr><td align=right>{{.Count}}<td><a href="{{.Name}}?debug=1">{{.Name}}</a>
   265  {{end}}
   266  </table>
   267  <br>
   268  <a href="goroutine?debug=2">full goroutine stack dump</a><br>
   269  </body>
   270  </html>
   271  `))