net/http/pprof

最後更新


net/http/pprof 把 Go 執行時的效能剖析資料(CPU、記憶體、goroutine 等)開成 HTTP 端點,讓你對執行中的服務做剖析。

這個套件做什麼


程式變慢、記憶體一直漲、goroutine 越開越多時,你需要「剖析(profiling)」:看時間花在哪些函式、記憶體由誰配置。runtime/pprof 能把剖析資料寫成檔案,但長時間執行的伺服器不方便停下來改程式。net/http/pprof 直接在 HTTP 伺服器上開一組 /debug/pprof/ 端點,需要時用瀏覽器或 go tool pprof 連上去抓資料即可。
端點內容
/debug/pprof/索引頁,列出所有剖析類型
/debug/pprof/profile?seconds=NCPU 剖析,取樣 N 秒(預設 30)
/debug/pprof/heap記憶體(目前存活的配置)
/debug/pprof/allocs所有記憶體配置
/debug/pprof/goroutine所有 goroutine 的呼叫堆疊
/debug/pprof/block、/debug/pprof/mutex阻塞與鎖競爭(需先開啟取樣率)
/debug/pprof/trace?seconds=N執行追蹤,給 go tool trace 用

拿到資料後的分析方法(go tool pprof、火焰圖)見 pprof 效能剖析。
注意:這些端點會洩漏程式內部資訊,CPU 剖析還會增加負載。不要對外公開,只聽 localhost 或放在需要驗證的內部 port。

匯入


  1. import _ "net/http/pprof"

只需要它「註冊端點」的副作用時,用空白識別字 _ 匯入。要自己掛到其他路由器上,則正常匯入 "net/http/pprof"。

常用 API


匿名匯入:註冊到 DefaultServeMux


import _ "net/http/pprof" 會在 init 時把端點註冊到 http.DefaultServeMux。只要你的程式用 http.ListenAndServe(addr, nil)(nil 代表使用 DefaultServeMux)啟動伺服器,端點就自動存在。常見寫法是另外開一個只聽本機的 goroutine:
  1. go func() {
  2. log.Println(http.ListenAndServe("localhost:6060", nil))
  3. }()

Go 1.22 起,這些端點只接受 GET(以及 HEAD),其他方法會得到 405。
簽名:
  1. import _ "net/http/pprof"

範例用 httptest 把 DefaultServeMux 開在本機隨機 port,檢查索引頁列出的剖析類型。
範例:
  1. package main
  2. import (
  3. "fmt"
  4. "io"
  5. "net/http"
  6. "net/http/httptest"
  7. _ "net/http/pprof"
  8. "strings"
  9. )
  10. func main() {
  11. srv := httptest.NewServer(http.DefaultServeMux)
  12. defer srv.Close()
  13. resp, err := http.Get(srv.URL + "/debug/pprof/")
  14. if err != nil {
  15. fmt.Println(err)
  16. return
  17. }
  18. body, _ := io.ReadAll(resp.Body)
  19. resp.Body.Close()
  20. fmt.Println(resp.StatusCode, resp.Header.Get("Content-Type"))
  21. for _, name := range []string{"allocs", "goroutine", "heap", "profile", "trace"} {
  22. fmt.Printf("%s listed: %v\n", name, strings.Contains(string(body), name))
  23. }
  24. resp, err = http.Post(srv.URL+"/debug/pprof/heap", "text/plain", nil)
  25. if err != nil {
  26. fmt.Println(err)
  27. return
  28. }
  29. resp.Body.Close()
  30. fmt.Println("POST:", resp.StatusCode)
  31. }

輸出:
  1. 200 text/html; charset=utf-8
  2. allocs listed: true
  3. goroutine listed: true
  4. heap listed: true
  5. profile listed: true
  6. trace listed: true
  7. POST: 405

掛到自己的 ServeMux:Index、Cmdline、Profile、Symbol、Trace


如果你的應用程式用的是自己建立的 http.NewServeMux(),匿名匯入註冊在 DefaultServeMux 上的端點不會出現在你的路由裡。這其實是好事:可以把剖析端點放在另一個只聽本機的伺服器,和對外的應用程式分開。
手動註冊時要掛五個函式。Index 註冊在 /debug/pprof/ 子樹,它除了顯示索引頁,也負責 heap、goroutine 等具名剖析。
簽名:
  1. func Index(w http.ResponseWriter, r *http.Request)
  2. func Cmdline(w http.ResponseWriter, r *http.Request)
  3. func Profile(w http.ResponseWriter, r *http.Request)
  4. func Symbol(w http.ResponseWriter, r *http.Request)
  5. func Trace(w http.ResponseWriter, r *http.Request)

範例中對外的 app 沒有剖析端點,回 404;debug 伺服器才有。
範例:
  1. package main
  2. import (
  3. "fmt"
  4. "io"
  5. "net/http"
  6. "net/http/httptest"
  7. "net/http/pprof"
  8. )
  9. func main() {
  10. debug := http.NewServeMux()
  11. debug.HandleFunc("GET /debug/pprof/", pprof.Index)
  12. debug.HandleFunc("GET /debug/pprof/cmdline", pprof.Cmdline)
  13. debug.HandleFunc("GET /debug/pprof/profile", pprof.Profile)
  14. debug.HandleFunc("GET /debug/pprof/symbol", pprof.Symbol)
  15. debug.HandleFunc("GET /debug/pprof/trace", pprof.Trace)
  16. app := http.NewServeMux()
  17. app.HandleFunc("GET /{$}", func(w http.ResponseWriter, r *http.Request) {
  18. fmt.Fprint(w, "app")
  19. })
  20. appSrv := httptest.NewServer(app)
  21. defer appSrv.Close()
  22. debugSrv := httptest.NewServer(debug)
  23. defer debugSrv.Close()
  24. for _, u := range []string{appSrv.URL + "/debug/pprof/", debugSrv.URL + "/debug/pprof/"} {
  25. resp, err := http.Get(u)
  26. if err != nil {
  27. fmt.Println(err)
  28. continue
  29. }
  30. io.Copy(io.Discard, resp.Body)
  31. resp.Body.Close()
  32. fmt.Println(resp.StatusCode)
  33. }
  34. }

輸出:
  1. 404
  2. 200

pprof.Handler:只開放特定剖析


Handler(name) 回傳單一剖析類型的 Handler,名稱就是 runtime/pprof 的剖析名稱,例如 "goroutine"、"heap"、"allocs"、"block"、"mutex"。適合只想開放其中幾項,或想掛在自訂路徑時。
查詢參數 debug=1 回傳人類可讀的文字格式;不加則是 go tool pprof 使用的二進位格式(gzip 壓縮的 protobuf)。
簽名:
  1. func Handler(name string) http.Handler

範例只檢查第一行開頭,因為 goroutine 數量每次執行可能不同。
範例:
  1. package main
  2. import (
  3. "bufio"
  4. "fmt"
  5. "net/http"
  6. "net/http/httptest"
  7. "net/http/pprof"
  8. "strings"
  9. )
  10. func main() {
  11. mux := http.NewServeMux()
  12. mux.Handle("GET /debug/goroutines", pprof.Handler("goroutine"))
  13. mux.Handle("GET /debug/heap", pprof.Handler("heap"))
  14. srv := httptest.NewServer(mux)
  15. defer srv.Close()
  16. resp, err := http.Get(srv.URL + "/debug/goroutines?debug=1")
  17. if err != nil {
  18. fmt.Println(err)
  19. return
  20. }
  21. first, _ := bufio.NewReader(resp.Body).ReadString('\n')
  22. resp.Body.Close()
  23. fmt.Println(resp.StatusCode, strings.HasPrefix(first, "goroutine profile: total"))
  24. resp, err = http.Get(srv.URL + "/debug/heap")
  25. if err != nil {
  26. fmt.Println(err)
  27. return
  28. }
  29. resp.Body.Close()
  30. fmt.Println(resp.StatusCode, resp.Header.Get("Content-Type"))
  31. }

輸出:
  1. 200 true
  2. 200 application/octet-stream

Profile:CPU 剖析


Profile 在收到請求後開始 CPU 取樣,持續 seconds 參數指定的秒數(預設 30 秒),結束後回傳 gzip 壓縮的剖析資料。取樣期間請求會一直等著,所以用戶端的逾時要比 seconds 長。實務上直接用指令抓:
  1. go tool pprof http://localhost:6060/debug/pprof/profile?seconds=30

簽名:
  1. func Profile(w http.ResponseWriter, r *http.Request)

範例讓一個 goroutine 忙碌地跑迴圈,抓 1 秒的 CPU 剖析,只檢查回應是否為 gzip 格式(開頭兩個位元組為 1f 8b)。
注意:同一時間只能進行一個 CPU 剖析,重複請求會失敗。
範例:
  1. package main
  2. import (
  3. "fmt"
  4. "io"
  5. "net/http"
  6. "net/http/httptest"
  7. "net/http/pprof"
  8. )
  9. func busy(stop <-chan struct{}) {
  10. x := 0
  11. for {
  12. select {
  13. case <-stop:
  14. return
  15. default:
  16. x++
  17. }
  18. }
  19. }
  20. func main() {
  21. mux := http.NewServeMux()
  22. mux.HandleFunc("/debug/pprof/profile", pprof.Profile)
  23. srv := httptest.NewServer(mux)
  24. defer srv.Close()
  25. stop := make(chan struct{})
  26. go busy(stop)
  27. resp, err := http.Get(srv.URL + "/debug/pprof/profile?seconds=1")
  28. close(stop)
  29. if err != nil {
  30. fmt.Println(err)
  31. return
  32. }
  33. data, _ := io.ReadAll(resp.Body)
  34. resp.Body.Close()
  35. fmt.Println(resp.StatusCode, resp.Header.Get("Content-Type"))
  36. fmt.Println("gzip magic:", len(data) > 2 && data[0] == 0x1f && data[1] == 0x8b)
  37. }

輸出:
  1. 200 application/octet-stream
  2. gzip magic: true

Trace:執行追蹤


Trace 記錄 seconds 秒內的排程、系統呼叫、GC 等事件,產生的檔案用 go tool trace 開啟,可以看到每個 goroutine 何時在哪個執行緒上執行。seconds 可以是小數。
  1. curl -o trace.out "http://localhost:6060/debug/pprof/trace?seconds=5"
  2. go tool trace trace.out

簽名:
  1. func Trace(w http.ResponseWriter, r *http.Request)

範例:
  1. package main
  2. import (
  3. "fmt"
  4. "io"
  5. "net/http"
  6. "net/http/httptest"
  7. "net/http/pprof"
  8. )
  9. func main() {
  10. mux := http.NewServeMux()
  11. mux.HandleFunc("/debug/pprof/trace", pprof.Trace)
  12. srv := httptest.NewServer(mux)
  13. defer srv.Close()
  14. resp, err := http.Get(srv.URL + "/debug/pprof/trace?seconds=0.2")
  15. if err != nil {
  16. fmt.Println(err)
  17. return
  18. }
  19. data, _ := io.ReadAll(resp.Body)
  20. resp.Body.Close()
  21. fmt.Println(resp.StatusCode, resp.Header.Get("Content-Type"), len(data) > 0)
  22. }

輸出:
  1. 200 application/octet-stream true

重點整理


  • import _ "net/http/pprof" 會把 /debug/pprof/ 端點註冊到 DefaultServeMux
  • 用自己的 ServeMux 時,手動掛 Index、Cmdline、Profile、Symbol、Trace
  • 剖析端點只開在本機或內部 port,不要對外公開
  • ?debug=1 取得文字格式;二進位格式交給 go tool pprof
  • CPU 剖析與 trace 會等待 seconds 秒,用戶端逾時要設得夠長

資料來源