|
| 1 | +// Copyright Envoy AI Gateway Authors |
| 2 | +// SPDX-License-Identifier: Apache-2.0 |
| 3 | +// The full text of the Apache license is available in the LICENSE file at |
| 4 | +// the root of the repo. |
| 5 | + |
| 6 | +package pprof |
| 7 | + |
| 8 | +import ( |
| 9 | + "context" |
| 10 | + "errors" |
| 11 | + "log" |
| 12 | + "net/http" |
| 13 | + "net/http/pprof" |
| 14 | + "os" |
| 15 | + "time" |
| 16 | +) |
| 17 | + |
| 18 | +const ( |
| 19 | + pprofPort = "6060" // The same default port as in th Go pprof documentation. |
| 20 | + // DisableEnvVarKey is the environment variable name to disable the pprof server. |
| 21 | + // If this environment variable is set to any value, the pprof server will not be started. |
| 22 | + DisableEnvVarKey = "DISABLE_PPROF" |
| 23 | +) |
| 24 | + |
| 25 | +// Run the pprof server if the DISABLE_PPROF environment variable is not set. |
| 26 | +// This is non-blocking and will run the pprof server in a separate goroutine until the provided context is cancelled. |
| 27 | +// |
| 28 | +// Enabling the pprof server by default helps with debugging performance issues in production. |
| 29 | +// The impact should be negligible when the actual pprof endpoints are not being accessed. |
| 30 | +func Run(ctx context.Context) { |
| 31 | + if _, ok := os.LookupEnv(DisableEnvVarKey); !ok { |
| 32 | + mux := http.NewServeMux() |
| 33 | + mux.HandleFunc("/debug/pprof/", pprof.Index) |
| 34 | + mux.HandleFunc("/debug/pprof/cmdline", pprof.Cmdline) |
| 35 | + mux.HandleFunc("/debug/pprof/profile", pprof.Profile) |
| 36 | + mux.HandleFunc("/debug/pprof/symbol", pprof.Symbol) |
| 37 | + mux.HandleFunc("/debug/pprof/trace", pprof.Trace) |
| 38 | + server := &http.Server{Addr: ":" + pprofPort, Handler: mux, ReadHeaderTimeout: 5 * time.Second} |
| 39 | + go func() { |
| 40 | + log.Printf("starting pprof server on port %s", pprofPort) |
| 41 | + if err := server.ListenAndServe(); err != nil && !errors.Is(err, http.ErrServerClosed) { |
| 42 | + log.Printf("pprof server stopped: %v", err) |
| 43 | + } |
| 44 | + }() |
| 45 | + go func() { |
| 46 | + <-ctx.Done() |
| 47 | + log.Printf("shutting down pprof server...") |
| 48 | + shutdownCtx, cancel := context.WithTimeout(context.Background(), 5*time.Second) |
| 49 | + defer cancel() |
| 50 | + if err := server.Shutdown(shutdownCtx); err != nil { |
| 51 | + log.Printf("error shutting down pprof server: %v", err) |
| 52 | + } else { |
| 53 | + log.Print("pprof server shut down gracefully") |
| 54 | + } |
| 55 | + }() |
| 56 | + } |
| 57 | +} |
0 commit comments