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.
5 // Package pprof serves via its HTTP server runtime profiling data
6 // in the format expected by the pprof visualization tool.
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/.
12 // To use pprof, link this package into your program:
13 // import _ "net/http/pprof"
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:
20 // log.Println(http.ListenAndServe("localhost:6060", nil))
23 // If you are not using DefaultServeMux, you will have to register handlers
24 // with the mux you are using.
26 // Then use the pprof tool to look at the heap profile:
28 // go tool pprof http://localhost:6060/debug/pprof/heap
30 // Or to look at a 30-second CPU profile:
32 // go tool pprof http://localhost:6060/debug/pprof/profile?seconds=30
34 // Or to look at the goroutine blocking profile, after calling
35 // runtime.SetBlockProfileRate in your program:
37 // go tool pprof http://localhost:6060/debug/pprof/block
39 // Or to collect a 5-second execution trace:
41 // wget http://localhost:6060/debug/pprof/trace?seconds=5
43 // Or to look at the holders of contended mutexes, after calling
44 // runtime.SetMutexProfileFraction in your program:
46 // go tool pprof http://localhost:6060/debug/pprof/mutex
48 // To view all available profiles, open http://localhost:6060/debug/pprof/
51 // For a study of the facility in action, visit
53 // https://blog.golang.org/2011/06/profiling-go-programs.html
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)
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"))
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()
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()
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)
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 {
126 if durationExceedsWriteTimeout(r, float64(sec)) {
127 serveError(w, http.StatusBadRequest, "profile duration exceeds server's WriteTimeout")
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))
141 sleep(w, time.Duration(sec)*time.Second)
142 pprof.StopCPUProfile()
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 {
155 if durationExceedsWriteTimeout(r, sec) {
156 serveError(w, http.StatusBadRequest, "profile duration exceeds server's WriteTimeout")
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))
170 sleep(w, time.Duration(sec*float64(time.Second)))
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")
181 // We have to read the whole POST body before
182 // writing any output. Buffer the output here.
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")
191 if r.Method == "POST" {
192 b = bufio.NewReader(r.Body)
194 b = bufio.NewReader(strings.NewReader(r.URL.RawQuery))
198 word, err := b.ReadSlice('+')
200 word = word[0 : len(word)-1] // trim +
202 pc, _ := strconv.ParseUint(string(word), 0, 64)
204 f := runtime.FuncForPC(uintptr(pc))
206 fmt.Fprintf(&buf, "%#x %s\n", pc, f.Name())
210 // Wait until here to check for err; the last
211 // symbol will have an err because it doesn't end in +.
214 fmt.Fprintf(&buf, "reading request: %v\n", err)
223 // Handler returns an HTTP handler that serves the named profile.
224 func Handler(name string) http.Handler {
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))
234 serveError(w, http.StatusNotFound, "Unknown profile")
237 gc, _ := strconv.Atoi(r.FormValue("gc"))
238 if name == "heap" && gc > 0 {
241 debug, _ := strconv.Atoi(r.FormValue("debug"))
243 w.Header().Set("Content-Type", "text/plain; charset=utf-8")
245 w.Header().Set("Content-Type", "application/octet-stream")
246 w.Header().Set("Content-Disposition", fmt.Sprintf(`attachment; filename="%s"`, name))
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.",
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/")
271 handler(name).ServeHTTP(w, r)
276 type profile struct {
282 var profiles []profile
283 for _, p := range pprof.Profiles() {
284 profiles = append(profiles, profile{
286 Href: p.Name() + "?debug=1",
287 Desc: profileDescriptions[p.Name()],
292 // Adding other profiles exposed from within this package
293 for _, p := range []string{"cmdline", "profile", "trace"} {
294 profiles = append(profiles, profile{
297 Desc: profileDescriptions[p],
301 sort.Slice(profiles, func(i, j int) bool {
302 return profiles[i].Name < profiles[j].Name
305 if err := indexTmpl.Execute(w, profiles); err != nil {
310 var indexTmpl = template.Must(template.New("index").Parse(`<html>
312 <title>/debug/pprof/</title>
315 display:inline-block;
323 Types of profiles available:
325 <thead><td>Count</td><td>Profile</td></thead>
328 <td>{{.Count}}</td><td><a href={{.Href}}>{{.Name}}</a></td>
332 <a href="goroutine?debug=2">full goroutine stack dump</a>
335 Profile Descriptions:
338 <li><div class=profile-name>{{.Name}}:</div> {{.Desc}}</li>