rsc.io/go@v0.0.0-20150416155037-e040fd465409/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  //	http://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  	"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  // Profile responds with the pprof-formatted cpu profile.
    83  // The package initialization registers it as /debug/pprof/profile.
    84  func Profile(w http.ResponseWriter, r *http.Request) {
    85  	sec, _ := strconv.ParseInt(r.FormValue("seconds"), 10, 64)
    86  	if sec == 0 {
    87  		sec = 30
    88  	}
    89  
    90  	// Set Content Type assuming StartCPUProfile will work,
    91  	// because if it does it starts writing.
    92  	w.Header().Set("Content-Type", "application/octet-stream")
    93  	if err := pprof.StartCPUProfile(w); err != nil {
    94  		// StartCPUProfile failed, so no writes yet.
    95  		// Can change header back to text content
    96  		// and send error code.
    97  		w.Header().Set("Content-Type", "text/plain; charset=utf-8")
    98  		w.WriteHeader(http.StatusInternalServerError)
    99  		fmt.Fprintf(w, "Could not enable CPU profiling: %s\n", err)
   100  		return
   101  	}
   102  	time.Sleep(time.Duration(sec) * time.Second)
   103  	pprof.StopCPUProfile()
   104  }
   105  
   106  // Trace responds with the execution trace in binary form.
   107  // Tracing lasts for duration specified in seconds GET parameter, or for 1 second if not specified.
   108  // The package initialization registers it as /debug/pprof/trace.
   109  func Trace(w http.ResponseWriter, r *http.Request) {
   110  	sec, _ := strconv.ParseInt(r.FormValue("seconds"), 10, 64)
   111  	if sec == 0 {
   112  		sec = 1
   113  	}
   114  
   115  	// Set Content Type assuming StartTrace will work,
   116  	// because if it does it starts writing.
   117  	w.Header().Set("Content-Type", "application/octet-stream")
   118  	if err := pprof.StartTrace(w); err != nil {
   119  		// StartTrace failed, so no writes yet.
   120  		// Can change header back to text content and send error code.
   121  		w.Header().Set("Content-Type", "text/plain; charset=utf-8")
   122  		w.WriteHeader(http.StatusInternalServerError)
   123  		fmt.Fprintf(w, "Could not enable tracing: %s\n", err)
   124  		return
   125  	}
   126  	time.Sleep(time.Duration(sec) * time.Second)
   127  	pprof.StopTrace()
   128  }
   129  
   130  // Symbol looks up the program counters listed in the request,
   131  // responding with a table mapping program counters to function names.
   132  // The package initialization registers it as /debug/pprof/symbol.
   133  func Symbol(w http.ResponseWriter, r *http.Request) {
   134  	w.Header().Set("Content-Type", "text/plain; charset=utf-8")
   135  
   136  	// We have to read the whole POST body before
   137  	// writing any output.  Buffer the output here.
   138  	var buf bytes.Buffer
   139  
   140  	// We don't know how many symbols we have, but we
   141  	// do have symbol information.  Pprof only cares whether
   142  	// this number is 0 (no symbols available) or > 0.
   143  	fmt.Fprintf(&buf, "num_symbols: 1\n")
   144  
   145  	var b *bufio.Reader
   146  	if r.Method == "POST" {
   147  		b = bufio.NewReader(r.Body)
   148  	} else {
   149  		b = bufio.NewReader(strings.NewReader(r.URL.RawQuery))
   150  	}
   151  
   152  	for {
   153  		word, err := b.ReadSlice('+')
   154  		if err == nil {
   155  			word = word[0 : len(word)-1] // trim +
   156  		}
   157  		pc, _ := strconv.ParseUint(string(word), 0, 64)
   158  		if pc != 0 {
   159  			f := runtime.FuncForPC(uintptr(pc))
   160  			if f != nil {
   161  				fmt.Fprintf(&buf, "%#x %s\n", pc, f.Name())
   162  			}
   163  		}
   164  
   165  		// Wait until here to check for err; the last
   166  		// symbol will have an err because it doesn't end in +.
   167  		if err != nil {
   168  			if err != io.EOF {
   169  				fmt.Fprintf(&buf, "reading request: %v\n", err)
   170  			}
   171  			break
   172  		}
   173  	}
   174  
   175  	w.Write(buf.Bytes())
   176  }
   177  
   178  // Handler returns an HTTP handler that serves the named profile.
   179  func Handler(name string) http.Handler {
   180  	return handler(name)
   181  }
   182  
   183  type handler string
   184  
   185  func (name handler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
   186  	w.Header().Set("Content-Type", "text/plain; charset=utf-8")
   187  	debug, _ := strconv.Atoi(r.FormValue("debug"))
   188  	p := pprof.Lookup(string(name))
   189  	if p == nil {
   190  		w.WriteHeader(404)
   191  		fmt.Fprintf(w, "Unknown profile: %s\n", name)
   192  		return
   193  	}
   194  	gc, _ := strconv.Atoi(r.FormValue("gc"))
   195  	if name == "heap" && gc > 0 {
   196  		runtime.GC()
   197  	}
   198  	p.WriteTo(w, debug)
   199  	return
   200  }
   201  
   202  // Index responds with the pprof-formatted profile named by the request.
   203  // For example, "/debug/pprof/heap" serves the "heap" profile.
   204  // Index responds to a request for "/debug/pprof/" with an HTML page
   205  // listing the available profiles.
   206  func Index(w http.ResponseWriter, r *http.Request) {
   207  	if strings.HasPrefix(r.URL.Path, "/debug/pprof/") {
   208  		name := strings.TrimPrefix(r.URL.Path, "/debug/pprof/")
   209  		if name != "" {
   210  			handler(name).ServeHTTP(w, r)
   211  			return
   212  		}
   213  	}
   214  
   215  	profiles := pprof.Profiles()
   216  	if err := indexTmpl.Execute(w, profiles); err != nil {
   217  		log.Print(err)
   218  	}
   219  }
   220  
   221  var indexTmpl = template.Must(template.New("index").Parse(`<html>
   222  <head>
   223  <title>/debug/pprof/</title>
   224  </head>
   225  <body>
   226  /debug/pprof/<br>
   227  <br>
   228  profiles:<br>
   229  <table>
   230  {{range .}}
   231  <tr><td align=right>{{.Count}}<td><a href="{{.Name}}?debug=1">{{.Name}}</a>
   232  {{end}}
   233  </table>
   234  <br>
   235  <a href="goroutine?debug=2">full goroutine stack dump</a><br>
   236  </body>
   237  </html>
   238  `))