pprof.go 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302
  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. // See Go's net/http/pprof for docs.
  8. //
  9. // This is a fork of net/http/pprof that doesn't use init side effects
  10. // and doesn't use html/template (which ends up calling
  11. // reflect.Value.MethodByName, which disables some linker deadcode
  12. // optimizations).
  13. package pprof
  14. import (
  15. "bufio"
  16. "bytes"
  17. "fmt"
  18. "html"
  19. "io"
  20. "net/http"
  21. "os"
  22. "runtime"
  23. "runtime/pprof"
  24. "runtime/trace"
  25. "sort"
  26. "strconv"
  27. "strings"
  28. "time"
  29. )
  30. func AddHandlers(mux *http.ServeMux) {
  31. mux.HandleFunc("/debug/pprof/", Index)
  32. mux.HandleFunc("/debug/pprof/cmdline", Cmdline)
  33. mux.HandleFunc("/debug/pprof/profile", Profile)
  34. mux.HandleFunc("/debug/pprof/symbol", Symbol)
  35. mux.HandleFunc("/debug/pprof/trace", Trace)
  36. }
  37. // Cmdline responds with the running program's
  38. // command line, with arguments separated by NUL bytes.
  39. // The package initialization registers it as /debug/pprof/cmdline.
  40. func Cmdline(w http.ResponseWriter, r *http.Request) {
  41. w.Header().Set("X-Content-Type-Options", "nosniff")
  42. w.Header().Set("Content-Type", "text/plain; charset=utf-8")
  43. fmt.Fprint(w, strings.Join(os.Args, "\x00"))
  44. }
  45. func sleep(w http.ResponseWriter, d time.Duration) {
  46. var clientGone <-chan bool
  47. //lint:ignore SA1019 CloseNotifier is deprecated but it functions and this is a temporary fork
  48. if cn, ok := w.(http.CloseNotifier); ok {
  49. clientGone = cn.CloseNotify()
  50. }
  51. select {
  52. case <-time.After(d):
  53. case <-clientGone:
  54. }
  55. }
  56. func durationExceedsWriteTimeout(r *http.Request, seconds float64) bool {
  57. srv, ok := r.Context().Value(http.ServerContextKey).(*http.Server)
  58. return ok && srv.WriteTimeout != 0 && seconds >= srv.WriteTimeout.Seconds()
  59. }
  60. func serveError(w http.ResponseWriter, status int, txt string) {
  61. w.Header().Set("Content-Type", "text/plain; charset=utf-8")
  62. w.Header().Set("X-Go-Pprof", "1")
  63. w.Header().Del("Content-Disposition")
  64. w.WriteHeader(status)
  65. fmt.Fprintln(w, txt)
  66. }
  67. // Profile responds with the pprof-formatted cpu profile.
  68. // Profiling lasts for duration specified in seconds GET parameter, or for 30 seconds if not specified.
  69. // The package initialization registers it as /debug/pprof/profile.
  70. func Profile(w http.ResponseWriter, r *http.Request) {
  71. w.Header().Set("X-Content-Type-Options", "nosniff")
  72. sec, err := strconv.ParseInt(r.FormValue("seconds"), 10, 64)
  73. if sec <= 0 || err != nil {
  74. sec = 30
  75. }
  76. if durationExceedsWriteTimeout(r, float64(sec)) {
  77. serveError(w, http.StatusBadRequest, "profile duration exceeds server's WriteTimeout")
  78. return
  79. }
  80. // Set Content Type assuming StartCPUProfile will work,
  81. // because if it does it starts writing.
  82. w.Header().Set("Content-Type", "application/octet-stream")
  83. w.Header().Set("Content-Disposition", `attachment; filename="profile"`)
  84. if err := pprof.StartCPUProfile(w); err != nil {
  85. // StartCPUProfile failed, so no writes yet.
  86. serveError(w, http.StatusInternalServerError,
  87. fmt.Sprintf("Could not enable CPU profiling: %s", err))
  88. return
  89. }
  90. sleep(w, time.Duration(sec)*time.Second)
  91. pprof.StopCPUProfile()
  92. }
  93. // Trace responds with the execution trace in binary form.
  94. // Tracing lasts for duration specified in seconds GET parameter, or for 1 second if not specified.
  95. // The package initialization registers it as /debug/pprof/trace.
  96. func Trace(w http.ResponseWriter, r *http.Request) {
  97. w.Header().Set("X-Content-Type-Options", "nosniff")
  98. sec, err := strconv.ParseFloat(r.FormValue("seconds"), 64)
  99. if sec <= 0 || err != nil {
  100. sec = 1
  101. }
  102. if durationExceedsWriteTimeout(r, sec) {
  103. serveError(w, http.StatusBadRequest, "profile duration exceeds server's WriteTimeout")
  104. return
  105. }
  106. // Set Content Type assuming trace.Start will work,
  107. // because if it does it starts writing.
  108. w.Header().Set("Content-Type", "application/octet-stream")
  109. w.Header().Set("Content-Disposition", `attachment; filename="trace"`)
  110. if err := trace.Start(w); err != nil {
  111. // trace.Start failed, so no writes yet.
  112. serveError(w, http.StatusInternalServerError,
  113. fmt.Sprintf("Could not enable tracing: %s", err))
  114. return
  115. }
  116. sleep(w, time.Duration(sec*float64(time.Second)))
  117. trace.Stop()
  118. }
  119. // Symbol looks up the program counters listed in the request,
  120. // responding with a table mapping program counters to function names.
  121. // The package initialization registers it as /debug/pprof/symbol.
  122. func Symbol(w http.ResponseWriter, r *http.Request) {
  123. w.Header().Set("X-Content-Type-Options", "nosniff")
  124. w.Header().Set("Content-Type", "text/plain; charset=utf-8")
  125. // We have to read the whole POST body before
  126. // writing any output. Buffer the output here.
  127. var buf bytes.Buffer
  128. // We don't know how many symbols we have, but we
  129. // do have symbol information. Pprof only cares whether
  130. // this number is 0 (no symbols available) or > 0.
  131. fmt.Fprintf(&buf, "num_symbols: 1\n")
  132. var b *bufio.Reader
  133. if r.Method == "POST" {
  134. b = bufio.NewReader(r.Body)
  135. } else {
  136. b = bufio.NewReader(strings.NewReader(r.URL.RawQuery))
  137. }
  138. for {
  139. word, err := b.ReadSlice('+')
  140. if err == nil {
  141. word = word[0 : len(word)-1] // trim +
  142. }
  143. pc, _ := strconv.ParseUint(string(word), 0, 64)
  144. if pc != 0 {
  145. f := runtime.FuncForPC(uintptr(pc))
  146. if f != nil {
  147. fmt.Fprintf(&buf, "%#x %s\n", pc, f.Name())
  148. }
  149. }
  150. // Wait until here to check for err; the last
  151. // symbol will have an err because it doesn't end in +.
  152. if err != nil {
  153. if err != io.EOF {
  154. fmt.Fprintf(&buf, "reading request: %v\n", err)
  155. }
  156. break
  157. }
  158. }
  159. w.Write(buf.Bytes())
  160. }
  161. // Handler returns an HTTP handler that serves the named profile.
  162. func Handler(name string) http.Handler {
  163. return handler(name)
  164. }
  165. type handler string
  166. func (name handler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
  167. w.Header().Set("X-Content-Type-Options", "nosniff")
  168. p := pprof.Lookup(string(name))
  169. if p == nil {
  170. serveError(w, http.StatusNotFound, "Unknown profile")
  171. return
  172. }
  173. gc, _ := strconv.Atoi(r.FormValue("gc"))
  174. if name == "heap" && gc > 0 {
  175. runtime.GC()
  176. }
  177. debug, _ := strconv.Atoi(r.FormValue("debug"))
  178. if debug != 0 {
  179. w.Header().Set("Content-Type", "text/plain; charset=utf-8")
  180. } else {
  181. w.Header().Set("Content-Type", "application/octet-stream")
  182. w.Header().Set("Content-Disposition", fmt.Sprintf(`attachment; filename="%s"`, name))
  183. }
  184. p.WriteTo(w, debug)
  185. }
  186. var profileDescriptions = map[string]string{
  187. "allocs": "A sampling of all past memory allocations",
  188. "block": "Stack traces that led to blocking on synchronization primitives",
  189. "cmdline": "The command line invocation of the current program",
  190. "goroutine": "Stack traces of all current goroutines",
  191. "heap": "A sampling of memory allocations of live objects. You can specify the gc GET parameter to run GC before taking the heap sample.",
  192. "mutex": "Stack traces of holders of contended mutexes",
  193. "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.",
  194. "threadcreate": "Stack traces that led to the creation of new OS threads",
  195. "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.",
  196. }
  197. // Index responds with the pprof-formatted profile named by the request.
  198. // For example, "/debug/pprof/heap" serves the "heap" profile.
  199. // Index responds to a request for "/debug/pprof/" with an HTML page
  200. // listing the available profiles.
  201. func Index(w http.ResponseWriter, r *http.Request) {
  202. if strings.HasPrefix(r.URL.Path, "/debug/pprof/") {
  203. name := strings.TrimPrefix(r.URL.Path, "/debug/pprof/")
  204. if name != "" {
  205. handler(name).ServeHTTP(w, r)
  206. return
  207. }
  208. }
  209. type profile struct {
  210. Name string
  211. Href string
  212. Desc string
  213. Count int
  214. }
  215. var profiles []profile
  216. for _, p := range pprof.Profiles() {
  217. profiles = append(profiles, profile{
  218. Name: p.Name(),
  219. Href: p.Name() + "?debug=1",
  220. Desc: profileDescriptions[p.Name()],
  221. Count: p.Count(),
  222. })
  223. }
  224. // Adding other profiles exposed from within this package
  225. for _, p := range []string{"cmdline", "profile", "trace"} {
  226. profiles = append(profiles, profile{
  227. Name: p,
  228. Href: p,
  229. Desc: profileDescriptions[p],
  230. })
  231. }
  232. sort.Slice(profiles, func(i, j int) bool {
  233. return profiles[i].Name < profiles[j].Name
  234. })
  235. io.WriteString(w, `<html>
  236. <head>
  237. <title>/debug/pprof/</title>
  238. <style>
  239. .profile-name{
  240. display:inline-block;
  241. width:6rem;
  242. }
  243. </style>
  244. </head>
  245. <body>
  246. /debug/pprof/<br>
  247. <br>
  248. Types of profiles available:
  249. <table>
  250. <thead><td>Count</td><td>Profile</td></thead>
  251. `)
  252. for _, p := range profiles {
  253. fmt.Fprintf(w, "<tr><td>%d</td><td><a href=%v>%v</td></tr>\n",
  254. p.Count, html.EscapeString(p.Href), html.EscapeString(p.Name))
  255. }
  256. io.WriteString(w, `</table>
  257. <a href="goroutine?debug=2">full goroutine stack dump</a>
  258. <br/>
  259. <p>
  260. Profile Descriptions:
  261. <ul>
  262. `)
  263. for _, p := range profiles {
  264. fmt.Fprintf(w, "<li><div class=profile-name>%s:</div> %s</li>\n",
  265. html.EscapeString(p.Name), html.EscapeString(p.Desc))
  266. }
  267. io.WriteString(w, `
  268. </ul>
  269. </p>
  270. </body>
  271. </html>
  272. `)
  273. }