@@ -4,6 +4,8 @@ package commands
44import (
55 "context"
66 "fmt"
7+ "net/http"
8+ "net/http/pprof"
79 "os"
810 "path/filepath"
911 "strings"
@@ -49,11 +51,13 @@ var (
4951 dmsgPort uint16
5052 dmsgServerType string
5153 geoipURL string
54+ pprofAddr string
5255)
5356
5457func init () {
5558 RootCmd .Flags ().StringVarP (& addr , "addr" , "a" , ":9098" , "address to bind to\033 [0m" )
5659 RootCmd .Flags ().StringVarP (& metricsAddr , "metrics" , "m" , "" , "address to bind metrics API to\033 [0m" )
60+ RootCmd .Flags ().StringVar (& pprofAddr , "pprof" , "" , "address to bind pprof debug server (e.g. localhost:6060)\033 [0m" )
5761 RootCmd .Flags ().StringVarP (& redisURL , "redis" , "r" , "redis://localhost:6379" , "connections string for a redis store\033 [0m" )
5862 RootCmd .Flags ().StringVarP (& pgHost , "pg-host" , "o" , "localhost" , "host of postgres\033 [0m" )
5963 RootCmd .Flags ().StringVarP (& pgPort , "pg-port" , "p" , "5432" , "port of postgres\033 [0m" )
@@ -94,6 +98,39 @@ PG_USER="postgres" PG_DATABASE="sd" PG_PASSWORD="" service-discovery --sk $(tail
9498 ctx , cancel := cmdutil .SignalContext (context .Background (), log )
9599 defer cancel ()
96100
101+ if pprofAddr != "" {
102+ pprofMux := http .NewServeMux ()
103+
104+ // Register the index (which links to everything else)
105+ pprofMux .HandleFunc ("/debug/pprof/" , pprof .Index )
106+ pprofMux .HandleFunc ("/debug/pprof/cmdline" , pprof .Cmdline )
107+ pprofMux .HandleFunc ("/debug/pprof/profile" , pprof .Profile )
108+ pprofMux .HandleFunc ("/debug/pprof/symbol" , pprof .Symbol )
109+ pprofMux .HandleFunc ("/debug/pprof/trace" , pprof .Trace )
110+
111+ // Register profile handlers using pprof.Handler
112+ for _ , profile := range []string {"heap" , "goroutine" , "threadcreate" , "block" , "mutex" , "allocs" } {
113+ pprofMux .Handle ("/debug/pprof/" + profile , pprof .Handler (profile ))
114+ }
115+
116+ go func () {
117+ log .Infof ("Starting pprof server on %s" , pprofAddr )
118+ server := & http.Server {
119+ Addr : pprofAddr ,
120+ Handler : pprofMux ,
121+ ReadHeaderTimeout : 10 * time .Second ,
122+ ReadTimeout : 30 * time .Second ,
123+ WriteTimeout : 30 * time .Second ,
124+ IdleTimeout : 60 * time .Second ,
125+ }
126+ if err := server .ListenAndServe (); err != nil && err != http .ErrServerClosed {
127+ log .Errorf ("pprof server failed: %v" , err )
128+ }
129+ }()
130+
131+ time .Sleep (100 * time .Millisecond )
132+ }
133+
97134 var gormDB * gorm.DB
98135
99136 pgUser , pgPassword , pgDatabase := storeconfig .PostgresCredential ()
0 commit comments