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 look at the holders of contended mutexes, after calling
40 // runtime.SetMutexProfileFraction in your program:
42 // go tool pprof http://localhost:6060/debug/pprof/mutex
44 // The package also exports a handler that serves execution trace data
45 // for the "go tool trace" command. To collect a 5-second execution trace:
47 // curl -o trace.out http://localhost:6060/debug/pprof/trace?seconds=5
48 // go tool trace trace.out
50 // To view all available profiles, open http://localhost:6060/debug/pprof/
53 // For a study of the facility in action, visit
55 // https://blog.golang.org/2011/06/profiling-go-programs.html
81 http
.HandleFunc("/debug/pprof/", Index
)
82 http
.HandleFunc("/debug/pprof/cmdline", Cmdline
)
83 http
.HandleFunc("/debug/pprof/profile", Profile
)
84 http
.HandleFunc("/debug/pprof/symbol", Symbol
)
85 http
.HandleFunc("/debug/pprof/trace", Trace
)
88 // Cmdline responds with the running program's
89 // command line, with arguments separated by NUL bytes.
90 // The package initialization registers it as /debug/pprof/cmdline.
91 func Cmdline(w http
.ResponseWriter
, r
*http
.Request
) {
92 w
.Header().Set("X-Content-Type-Options", "nosniff")
93 w
.Header().Set("Content-Type", "text/plain; charset=utf-8")
94 fmt
.Fprint(w
, strings
.Join(os
.Args
, "\x00"))
97 func sleep(r
*http
.Request
, d time
.Duration
) {
100 case <-r
.Context().Done():
104 func durationExceedsWriteTimeout(r
*http
.Request
, seconds
float64) bool {
105 srv
, ok
:= r
.Context().Value(http
.ServerContextKey
).(*http
.Server
)
106 return ok
&& srv
.WriteTimeout
!= 0 && seconds
>= srv
.WriteTimeout
.Seconds()
109 func serveError(w http
.ResponseWriter
, status
int, txt
string) {
110 w
.Header().Set("Content-Type", "text/plain; charset=utf-8")
111 w
.Header().Set("X-Go-Pprof", "1")
112 w
.Header().Del("Content-Disposition")
113 w
.WriteHeader(status
)
117 // Profile responds with the pprof-formatted cpu profile.
118 // Profiling lasts for duration specified in seconds GET parameter, or for 30 seconds if not specified.
119 // The package initialization registers it as /debug/pprof/profile.
120 func Profile(w http
.ResponseWriter
, r
*http
.Request
) {
121 w
.Header().Set("X-Content-Type-Options", "nosniff")
122 sec
, err
:= strconv
.ParseInt(r
.FormValue("seconds"), 10, 64)
123 if sec
<= 0 || err
!= nil {
127 if durationExceedsWriteTimeout(r
, float64(sec
)) {
128 serveError(w
, http
.StatusBadRequest
, "profile duration exceeds server's WriteTimeout")
132 // Set Content Type assuming StartCPUProfile will work,
133 // because if it does it starts writing.
134 w
.Header().Set("Content-Type", "application/octet-stream")
135 w
.Header().Set("Content-Disposition", `attachment; filename="profile"`)
136 if err
:= pprof
.StartCPUProfile(w
); err
!= nil {
137 // StartCPUProfile failed, so no writes yet.
138 serveError(w
, http
.StatusInternalServerError
,
139 fmt
.Sprintf("Could not enable CPU profiling: %s", err
))
142 sleep(r
, time
.Duration(sec
)*time
.Second
)
143 pprof
.StopCPUProfile()
146 // Trace responds with the execution trace in binary form.
147 // Tracing lasts for duration specified in seconds GET parameter, or for 1 second if not specified.
148 // The package initialization registers it as /debug/pprof/trace.
149 func Trace(w http
.ResponseWriter
, r
*http
.Request
) {
150 w
.Header().Set("X-Content-Type-Options", "nosniff")
151 sec
, err
:= strconv
.ParseFloat(r
.FormValue("seconds"), 64)
152 if sec
<= 0 || err
!= nil {
156 if durationExceedsWriteTimeout(r
, sec
) {
157 serveError(w
, http
.StatusBadRequest
, "profile duration exceeds server's WriteTimeout")
161 // Set Content Type assuming trace.Start will work,
162 // because if it does it starts writing.
163 w
.Header().Set("Content-Type", "application/octet-stream")
164 w
.Header().Set("Content-Disposition", `attachment; filename="trace"`)
165 if err
:= trace
.Start(w
); err
!= nil {
166 // trace.Start failed, so no writes yet.
167 serveError(w
, http
.StatusInternalServerError
,
168 fmt
.Sprintf("Could not enable tracing: %s", err
))
171 sleep(r
, time
.Duration(sec
*float64(time
.Second
)))
175 // Symbol looks up the program counters listed in the request,
176 // responding with a table mapping program counters to function names.
177 // The package initialization registers it as /debug/pprof/symbol.
178 func Symbol(w http
.ResponseWriter
, r
*http
.Request
) {
179 w
.Header().Set("X-Content-Type-Options", "nosniff")
180 w
.Header().Set("Content-Type", "text/plain; charset=utf-8")
182 // We have to read the whole POST body before
183 // writing any output. Buffer the output here.
186 // We don't know how many symbols we have, but we
187 // do have symbol information. Pprof only cares whether
188 // this number is 0 (no symbols available) or > 0.
189 fmt
.Fprintf(&buf
, "num_symbols: 1\n")
192 if r
.Method
== "POST" {
193 b
= bufio
.NewReader(r
.Body
)
195 b
= bufio
.NewReader(strings
.NewReader(r
.URL
.RawQuery
))
199 word
, err
:= b
.ReadSlice('+')
201 word
= word
[0 : len(word
)-1] // trim +
203 pc
, _
:= strconv
.ParseUint(string(word
), 0, 64)
205 f
:= runtime
.FuncForPC(uintptr(pc
))
207 fmt
.Fprintf(&buf
, "%#x %s\n", pc
, f
.Name())
211 // Wait until here to check for err; the last
212 // symbol will have an err because it doesn't end in +.
215 fmt
.Fprintf(&buf
, "reading request: %v\n", err
)
224 // Handler returns an HTTP handler that serves the named profile.
225 func Handler(name
string) http
.Handler
{
231 func (name handler
) ServeHTTP(w http
.ResponseWriter
, r
*http
.Request
) {
232 w
.Header().Set("X-Content-Type-Options", "nosniff")
233 p
:= pprof
.Lookup(string(name
))
235 serveError(w
, http
.StatusNotFound
, "Unknown profile")
238 if sec
:= r
.FormValue("seconds"); sec
!= "" {
239 name
.serveDeltaProfile(w
, r
, p
, sec
)
242 gc
, _
:= strconv
.Atoi(r
.FormValue("gc"))
243 if name
== "heap" && gc
> 0 {
246 debug
, _
:= strconv
.Atoi(r
.FormValue("debug"))
248 w
.Header().Set("Content-Type", "text/plain; charset=utf-8")
250 w
.Header().Set("Content-Type", "application/octet-stream")
251 w
.Header().Set("Content-Disposition", fmt
.Sprintf(`attachment; filename="%s"`, name
))
256 func (name handler
) serveDeltaProfile(w http
.ResponseWriter
, r
*http
.Request
, p
*pprof
.Profile
, secStr
string) {
257 sec
, err
:= strconv
.ParseInt(secStr
, 10, 64)
258 if err
!= nil || sec
<= 0 {
259 serveError(w
, http
.StatusBadRequest
, `invalid value for "seconds" - must be a positive integer`)
262 if !profileSupportsDelta
[name
] {
263 serveError(w
, http
.StatusBadRequest
, `"seconds" parameter is not supported for this profile type`)
266 // 'name' should be a key in profileSupportsDelta.
267 if durationExceedsWriteTimeout(r
, float64(sec
)) {
268 serveError(w
, http
.StatusBadRequest
, "profile duration exceeds server's WriteTimeout")
271 debug
, _
:= strconv
.Atoi(r
.FormValue("debug"))
273 serveError(w
, http
.StatusBadRequest
, "seconds and debug params are incompatible")
276 p0
, err
:= collectProfile(p
)
278 serveError(w
, http
.StatusInternalServerError
, "failed to collect profile")
282 t
:= time
.NewTimer(time
.Duration(sec
) * time
.Second
)
286 case <-r
.Context().Done():
287 err
:= r
.Context().Err()
288 if err
== context
.DeadlineExceeded
{
289 serveError(w
, http
.StatusRequestTimeout
, err
.Error())
290 } else { // TODO: what's a good status code for canceled requests? 400?
291 serveError(w
, http
.StatusInternalServerError
, err
.Error())
297 p1
, err
:= collectProfile(p
)
299 serveError(w
, http
.StatusInternalServerError
, "failed to collect profile")
303 dur
:= p1
.TimeNanos
- p0
.TimeNanos
307 p1
, err
= profile
.Merge([]*profile
.Profile
{p0
, p1
})
309 serveError(w
, http
.StatusInternalServerError
, "failed to compute delta")
313 p1
.TimeNanos
= ts
// set since we don't know what profile.Merge set for TimeNanos.
314 p1
.DurationNanos
= dur
316 w
.Header().Set("Content-Type", "application/octet-stream")
317 w
.Header().Set("Content-Disposition", fmt
.Sprintf(`attachment; filename="%s-delta"`, name
))
321 func collectProfile(p
*pprof
.Profile
) (*profile
.Profile
, error
) {
323 if err
:= p
.WriteTo(&buf
, 0); err
!= nil {
326 ts
:= time
.Now().UnixNano()
327 p0
, err
:= profile
.Parse(&buf
)
335 var profileSupportsDelta
= map[handler
]bool{
341 "threadcreate": true,
344 var profileDescriptions
= map[string]string{
345 "allocs": "A sampling of all past memory allocations",
346 "block": "Stack traces that led to blocking on synchronization primitives",
347 "cmdline": "The command line invocation of the current program",
348 "goroutine": "Stack traces of all current goroutines",
349 "heap": "A sampling of memory allocations of live objects. You can specify the gc GET parameter to run GC before taking the heap sample.",
350 "mutex": "Stack traces of holders of contended mutexes",
351 "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.",
352 "threadcreate": "Stack traces that led to the creation of new OS threads",
353 "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.",
356 type profileEntry
struct {
363 // Index responds with the pprof-formatted profile named by the request.
364 // For example, "/debug/pprof/heap" serves the "heap" profile.
365 // Index responds to a request for "/debug/pprof/" with an HTML page
366 // listing the available profiles.
367 func Index(w http
.ResponseWriter
, r
*http
.Request
) {
368 if strings
.HasPrefix(r
.URL
.Path
, "/debug/pprof/") {
369 name
:= strings
.TrimPrefix(r
.URL
.Path
, "/debug/pprof/")
371 handler(name
).ServeHTTP(w
, r
)
376 w
.Header().Set("X-Content-Type-Options", "nosniff")
377 w
.Header().Set("Content-Type", "text/html; charset=utf-8")
379 var profiles
[]profileEntry
380 for _
, p
:= range pprof
.Profiles() {
381 profiles
= append(profiles
, profileEntry
{
384 Desc
: profileDescriptions
[p
.Name()],
389 // Adding other profiles exposed from within this package
390 for _
, p
:= range []string{"cmdline", "profile", "trace"} {
391 profiles
= append(profiles
, profileEntry
{
394 Desc
: profileDescriptions
[p
],
398 sort
.Slice(profiles
, func(i
, j
int) bool {
399 return profiles
[i
].Name
< profiles
[j
].Name
402 if err
:= indexTmplExecute(w
, profiles
); err
!= nil {
407 func indexTmplExecute(w io
.Writer
, profiles
[]profileEntry
) error
{
409 b
.WriteString(`<html>
411 <title>/debug/pprof/</title>
414 display:inline-block;
422 Types of profiles available:
424 <thead><td>Count</td><td>Profile</td></thead>
427 for _
, profile
:= range profiles
{
428 link
:= &url
.URL
{Path
: profile
.Href
, RawQuery
: "debug=1"}
429 fmt
.Fprintf(&b
, "<tr><td>%d</td><td><a href='%s'>%s</a></td></tr>\n", profile
.Count
, link
, html
.EscapeString(profile
.Name
))
432 b
.WriteString(`</table>
433 <a href="goroutine?debug=2">full goroutine stack dump</a>
436 Profile Descriptions:
439 for _
, profile
:= range profiles
{
440 fmt
.Fprintf(&b
, "<li><div class=profile-name>%s: </div> %s</li>\n", html
.EscapeString(profile
.Name
), html
.EscapeString(profile
.Desc
))
447 _
, err
:= w
.Write(b
.Bytes())