pprof_debug.go 1.1 KB

1234567891011121314151617181920212223242526272829303132333435
  1. //go:build debug
  2. package nebula
  3. import (
  4. "context"
  5. "errors"
  6. "log/slog"
  7. "net/http"
  8. _ "net/http/pprof" // registers pprof handlers on http.DefaultServeMux
  9. )
  10. // startPprofServer serves net/http/pprof on localhost:6060 for the life of
  11. // ctx. It is only compiled into debug builds (`-tags debug`, `make debug`),
  12. // so a debug build announces itself with the Info line below. Loopback only:
  13. // a wildcard bind would expose profiles (peer addresses, config-derived
  14. // state) to anything that can reach the host, the overlay included.
  15. func startPprofServer(ctx context.Context, l *slog.Logger) {
  16. server := &http.Server{Addr: "localhost:6060", Handler: nil}
  17. l.Info("Starting pprof debug server (debug build)", "addr", server.Addr)
  18. go func() {
  19. if err := server.ListenAndServe(); err != nil && !errors.Is(err, http.ErrServerClosed) {
  20. l.Error("pprof debug server stopped", "error", err)
  21. }
  22. }()
  23. // Shut down the server when the context is cancelled.
  24. go func() {
  25. <-ctx.Done()
  26. if err := server.Shutdown(context.Background()); err != nil {
  27. l.Debug("Error shutting down pprof debug server", "error", err)
  28. }
  29. }()
  30. }