pprof.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449
  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. // Package pprof serves via its HTTP server runtime profiling data
  5. // in the format expected by the pprof visualization tool.
  6. //
  7. // The package is typically only imported for the side effect of
  8. // registering its HTTP handlers.
  9. // The handled paths all begin with /debug/pprof/.
  10. //
  11. // To use pprof, link this package into your program:
  12. // import _ "net/http/pprof"
  13. //
  14. // If your application is not already running an http server, you
  15. // need to start one. Add "net/http" and "log" to your imports and
  16. // the following code to your main function:
  17. //
  18. // go func() {
  19. // log.Println(http.ListenAndServe("localhost:6060", nil))
  20. // }()
  21. //
  22. // If you are not using DefaultServeMux, you will have to register handlers
  23. // with the mux you are using.
  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?seconds=30
  32. //
  33. // Or to look at the goroutine blocking profile, after calling
  34. // runtime.SetBlockProfileRate in your program:
  35. //
  36. // go tool pprof http://localhost:6060/debug/pprof/block
  37. //
  38. // Or to look at the holders of contended mutexes, after calling
  39. // runtime.SetMutexProfileFraction in your program:
  40. //
  41. // go tool pprof http://localhost:6060/debug/pprof/mutex
  42. //
  43. // The package also exports a handler that serves execution trace data
  44. // for the "go tool trace" command. To collect a 5-second execution trace:
  45. //
  46. // curl -o trace.out http://localhost:6060/debug/pprof/trace?seconds=5
  47. // go tool trace trace.out
  48. //
  49. // To view all available profiles, open http://localhost:6060/debug/pprof/
  50. // in your browser.
  51. //
  52. // For a study of the facility in action, visit
  53. //
  54. // https://blog.golang.org/2011/06/profiling-go-programs.html
  55. //
  56. package pprof
  57. import (
  58. "bufio"
  59. "bytes"
  60. "context"
  61. "fmt"
  62. "html"
  63. "internal/profile"
  64. "io"
  65. "log"
  66. "net/http"
  67. "net/url"
  68. "os"
  69. "runtime"
  70. "runtime/pprof"
  71. "runtime/trace"
  72. "sort"
  73. "strconv"
  74. "strings"
  75. "time"
  76. )
  77. func init() {
  78. http.HandleFunc("/debug/pprof/", Index)
  79. http.HandleFunc("/debug/pprof/cmdline", Cmdline)
  80. http.HandleFunc("/debug/pprof/profile", Profile)
  81. http.HandleFunc("/debug/pprof/symbol", Symbol)
  82. http.HandleFunc("/debug/pprof/trace", Trace)
  83. }
  84. // Cmdline responds with the running program's
  85. // command line, with arguments separated by NUL bytes.
  86. // The package initialization registers it as /debug/pprof/cmdline.
  87. func Cmdline(w http.ResponseWriter, r *http.Request) {
  88. w.Header().Set("X-Content-Type-Options", "nosniff")
  89. w.Header().Set("Content-Type", "text/plain; charset=utf-8")
  90. fmt.Fprint(w, strings.Join(os.Args, "\x00"))
  91. }
  92. func sleep(r *http.Request, d time.Duration) {
  93. select {
  94. case <-time.After(d):
  95. case <-r.Context().Done():
  96. }
  97. }
  98. func durationExceedsWriteTimeout(r *http.Request, seconds float64) bool {
  99. srv, ok := r.Context().Value(http.ServerContextKey).(*http.Server)
  100. return ok && srv.WriteTimeout != 0 && seconds >= srv.WriteTimeout.Seconds()
  101. }
  102. func serveError(w http.ResponseWriter, status int, txt string) {
  103. w.Header().Set("Content-Type", "text/plain; charset=utf-8")
  104. w.Header().Set("X-Go-Pprof", "1")
  105. w.Header().Del("Content-Disposition")
  106. w.WriteHeader(status)
  107. fmt.Fprintln(w, txt)
  108. }
  109. // Profile responds with the pprof-formatted cpu profile.
  110. // Profiling lasts for duration specified in seconds GET parameter, or for 30 seconds if not specified.
  111. // The package initialization registers it as /debug/pprof/profile.
  112. func Profile(w http.ResponseWriter, r *http.Request) {
  113. w.Header().Set("X-Content-Type-Options", "nosniff")
  114. sec, err := strconv.ParseInt(r.FormValue("seconds"), 10, 64)
  115. if sec <= 0 || err != nil {
  116. sec = 30
  117. }
  118. if durationExceedsWriteTimeout(r, float64(sec)) {
  119. serveError(w, http.StatusBadRequest, "profile duration exceeds server's WriteTimeout")
  120. return
  121. }
  122. // Set Content Type assuming StartCPUProfile will work,
  123. // because if it does it starts writing.
  124. w.Header().Set("Content-Type", "application/octet-stream")
  125. w.Header().Set("Content-Disposition", `attachment; filename="profile"`)
  126. if err := pprof.StartCPUProfile(w); err != nil {
  127. // StartCPUProfile failed, so no writes yet.
  128. serveError(w, http.StatusInternalServerError,
  129. fmt.Sprintf("Could not enable CPU profiling: %s", err))
  130. return
  131. }
  132. sleep(r, time.Duration(sec)*time.Second)
  133. pprof.StopCPUProfile()
  134. }
  135. // Trace responds with the execution trace in binary form.
  136. // Tracing lasts for duration specified in seconds GET parameter, or for 1 second if not specified.
  137. // The package initialization registers it as /debug/pprof/trace.
  138. func Trace(w http.ResponseWriter, r *http.Request) {
  139. w.Header().Set("X-Content-Type-Options", "nosniff")
  140. sec, err := strconv.ParseFloat(r.FormValue("seconds"), 64)
  141. if sec <= 0 || err != nil {
  142. sec = 1
  143. }
  144. if durationExceedsWriteTimeout(r, sec) {
  145. serveError(w, http.StatusBadRequest, "profile duration exceeds server's WriteTimeout")
  146. return
  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. w.Header().Set("Content-Disposition", `attachment; filename="trace"`)
  152. if err := trace.Start(w); err != nil {
  153. // trace.Start failed, so no writes yet.
  154. serveError(w, http.StatusInternalServerError,
  155. fmt.Sprintf("Could not enable tracing: %s", err))
  156. return
  157. }
  158. sleep(r, time.Duration(sec*float64(time.Second)))
  159. trace.Stop()
  160. }
  161. // Symbol looks up the program counters listed in the request,
  162. // responding with a table mapping program counters to function names.
  163. // The package initialization registers it as /debug/pprof/symbol.
  164. func Symbol(w http.ResponseWriter, r *http.Request) {
  165. w.Header().Set("X-Content-Type-Options", "nosniff")
  166. w.Header().Set("Content-Type", "text/plain; charset=utf-8")
  167. // We have to read the whole POST body before
  168. // writing any output. Buffer the output here.
  169. var buf bytes.Buffer
  170. // We don't know how many symbols we have, but we
  171. // do have symbol information. Pprof only cares whether
  172. // this number is 0 (no symbols available) or > 0.
  173. fmt.Fprintf(&buf, "num_symbols: 1\n")
  174. var b *bufio.Reader
  175. if r.Method == "POST" {
  176. b = bufio.NewReader(r.Body)
  177. } else {
  178. b = bufio.NewReader(strings.NewReader(r.URL.RawQuery))
  179. }
  180. for {
  181. word, err := b.ReadSlice('+')
  182. if err == nil {
  183. word = word[0 : len(word)-1] // trim +
  184. }
  185. pc, _ := strconv.ParseUint(string(word), 0, 64)
  186. if pc != 0 {
  187. f := runtime.FuncForPC(uintptr(pc))
  188. if f != nil {
  189. fmt.Fprintf(&buf, "%#x %s\n", pc, f.Name())
  190. }
  191. }
  192. // Wait until here to check for err; the last
  193. // symbol will have an err because it doesn't end in +.
  194. if err != nil {
  195. if err != io.EOF {
  196. fmt.Fprintf(&buf, "reading request: %v\n", err)
  197. }
  198. break
  199. }
  200. }
  201. w.Write(buf.Bytes())
  202. }
  203. // Handler returns an HTTP handler that serves the named profile.
  204. func Handler(name string) http.Handler {
  205. return handler(name)
  206. }
  207. type handler string
  208. func (name handler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
  209. w.Header().Set("X-Content-Type-Options", "nosniff")
  210. p := pprof.Lookup(string(name))
  211. if p == nil {
  212. serveError(w, http.StatusNotFound, "Unknown profile")
  213. return
  214. }
  215. if sec := r.FormValue("seconds"); sec != "" {
  216. name.serveDeltaProfile(w, r, p, sec)
  217. return
  218. }
  219. gc, _ := strconv.Atoi(r.FormValue("gc"))
  220. if name == "heap" && gc > 0 {
  221. runtime.GC()
  222. }
  223. debug, _ := strconv.Atoi(r.FormValue("debug"))
  224. if debug != 0 {
  225. w.Header().Set("Content-Type", "text/plain; charset=utf-8")
  226. } else {
  227. w.Header().Set("Content-Type", "application/octet-stream")
  228. w.Header().Set("Content-Disposition", fmt.Sprintf(`attachment; filename="%s"`, name))
  229. }
  230. p.WriteTo(w, debug)
  231. }
  232. func (name handler) serveDeltaProfile(w http.ResponseWriter, r *http.Request, p *pprof.Profile, secStr string) {
  233. sec, err := strconv.ParseInt(secStr, 10, 64)
  234. if err != nil || sec <= 0 {
  235. serveError(w, http.StatusBadRequest, `invalid value for "seconds" - must be a positive integer`)
  236. return
  237. }
  238. if !profileSupportsDelta[name] {
  239. serveError(w, http.StatusBadRequest, `"seconds" parameter is not supported for this profile type`)
  240. return
  241. }
  242. // 'name' should be a key in profileSupportsDelta.
  243. if durationExceedsWriteTimeout(r, float64(sec)) {
  244. serveError(w, http.StatusBadRequest, "profile duration exceeds server's WriteTimeout")
  245. return
  246. }
  247. debug, _ := strconv.Atoi(r.FormValue("debug"))
  248. if debug != 0 {
  249. serveError(w, http.StatusBadRequest, "seconds and debug params are incompatible")
  250. return
  251. }
  252. p0, err := collectProfile(p)
  253. if err != nil {
  254. serveError(w, http.StatusInternalServerError, "failed to collect profile")
  255. return
  256. }
  257. t := time.NewTimer(time.Duration(sec) * time.Second)
  258. defer t.Stop()
  259. select {
  260. case <-r.Context().Done():
  261. err := r.Context().Err()
  262. if err == context.DeadlineExceeded {
  263. serveError(w, http.StatusRequestTimeout, err.Error())
  264. } else { // TODO: what's a good status code for canceled requests? 400?
  265. serveError(w, http.StatusInternalServerError, err.Error())
  266. }
  267. return
  268. case <-t.C:
  269. }
  270. p1, err := collectProfile(p)
  271. if err != nil {
  272. serveError(w, http.StatusInternalServerError, "failed to collect profile")
  273. return
  274. }
  275. ts := p1.TimeNanos
  276. dur := p1.TimeNanos - p0.TimeNanos
  277. p0.Scale(-1)
  278. p1, err = profile.Merge([]*profile.Profile{p0, p1})
  279. if err != nil {
  280. serveError(w, http.StatusInternalServerError, "failed to compute delta")
  281. return
  282. }
  283. p1.TimeNanos = ts // set since we don't know what profile.Merge set for TimeNanos.
  284. p1.DurationNanos = dur
  285. w.Header().Set("Content-Type", "application/octet-stream")
  286. w.Header().Set("Content-Disposition", fmt.Sprintf(`attachment; filename="%s-delta"`, name))
  287. p1.Write(w)
  288. }
  289. func collectProfile(p *pprof.Profile) (*profile.Profile, error) {
  290. var buf bytes.Buffer
  291. if err := p.WriteTo(&buf, 0); err != nil {
  292. return nil, err
  293. }
  294. ts := time.Now().UnixNano()
  295. p0, err := profile.Parse(&buf)
  296. if err != nil {
  297. return nil, err
  298. }
  299. p0.TimeNanos = ts
  300. return p0, nil
  301. }
  302. var profileSupportsDelta = map[handler]bool{
  303. "allocs": true,
  304. "block": true,
  305. "goroutine": true,
  306. "heap": true,
  307. "mutex": true,
  308. "threadcreate": true,
  309. }
  310. var profileDescriptions = map[string]string{
  311. "allocs": "A sampling of all past memory allocations",
  312. "block": "Stack traces that led to blocking on synchronization primitives",
  313. "cmdline": "The command line invocation of the current program",
  314. "goroutine": "Stack traces of all current goroutines",
  315. "heap": "A sampling of memory allocations of live objects. You can specify the gc GET parameter to run GC before taking the heap sample.",
  316. "mutex": "Stack traces of holders of contended mutexes",
  317. "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.",
  318. "threadcreate": "Stack traces that led to the creation of new OS threads",
  319. "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.",
  320. }
  321. type profileEntry struct {
  322. Name string
  323. Href string
  324. Desc string
  325. Count int
  326. }
  327. // Index responds with the pprof-formatted profile named by the request.
  328. // For example, "/debug/pprof/heap" serves the "heap" profile.
  329. // Index responds to a request for "/debug/pprof/" with an HTML page
  330. // listing the available profiles.
  331. func Index(w http.ResponseWriter, r *http.Request) {
  332. if strings.HasPrefix(r.URL.Path, "/debug/pprof/") {
  333. name := strings.TrimPrefix(r.URL.Path, "/debug/pprof/")
  334. if name != "" {
  335. handler(name).ServeHTTP(w, r)
  336. return
  337. }
  338. }
  339. w.Header().Set("X-Content-Type-Options", "nosniff")
  340. w.Header().Set("Content-Type", "text/html; charset=utf-8")
  341. var profiles []profileEntry
  342. for _, p := range pprof.Profiles() {
  343. profiles = append(profiles, profileEntry{
  344. Name: p.Name(),
  345. Href: p.Name(),
  346. Desc: profileDescriptions[p.Name()],
  347. Count: p.Count(),
  348. })
  349. }
  350. // Adding other profiles exposed from within this package
  351. for _, p := range []string{"cmdline", "profile", "trace"} {
  352. profiles = append(profiles, profileEntry{
  353. Name: p,
  354. Href: p,
  355. Desc: profileDescriptions[p],
  356. })
  357. }
  358. sort.Slice(profiles, func(i, j int) bool {
  359. return profiles[i].Name < profiles[j].Name
  360. })
  361. if err := indexTmplExecute(w, profiles); err != nil {
  362. log.Print(err)
  363. }
  364. }
  365. func indexTmplExecute(w io.Writer, profiles []profileEntry) error {
  366. var b bytes.Buffer
  367. b.WriteString(`<html>
  368. <head>
  369. <title>/debug/pprof/</title>
  370. <style>
  371. .profile-name{
  372. display:inline-block;
  373. width:6rem;
  374. }
  375. </style>
  376. </head>
  377. <body>
  378. /debug/pprof/<br>
  379. <br>
  380. Types of profiles available:
  381. <table>
  382. <thead><td>Count</td><td>Profile</td></thead>
  383. `)
  384. for _, profile := range profiles {
  385. link := &url.URL{Path: profile.Href, RawQuery: "debug=1"}
  386. fmt.Fprintf(&b, "<tr><td>%d</td><td><a href='%s'>%s</a></td></tr>\n", profile.Count, link, html.EscapeString(profile.Name))
  387. }
  388. b.WriteString(`</table>
  389. <a href="goroutine?debug=2">full goroutine stack dump</a>
  390. <br>
  391. <p>
  392. Profile Descriptions:
  393. <ul>
  394. `)
  395. for _, profile := range profiles {
  396. fmt.Fprintf(&b, "<li><div class=profile-name>%s: </div> %s</li>\n", html.EscapeString(profile.Name), html.EscapeString(profile.Desc))
  397. }
  398. b.WriteString(`</ul>
  399. </p>
  400. </body>
  401. </html>`)
  402. _, err := w.Write(b.Bytes())
  403. return err
  404. }