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