|
| 1 | +package pprof |
| 2 | + |
| 3 | +import ( |
| 4 | + "net/http" |
| 5 | + "net/http/pprof" |
| 6 | + "strings" |
| 7 | + |
| 8 | + "github.com/yomorun/yomo/pkg/util" |
| 9 | + |
| 10 | + "github.com/yomorun/yomo/pkg/env" |
| 11 | +) |
| 12 | + |
| 13 | +type pprofConf struct { |
| 14 | + Enabled bool |
| 15 | + PathPrefix string |
| 16 | + Endpoint string |
| 17 | +} |
| 18 | + |
| 19 | +const ( |
| 20 | + pprofEnabled = "YOMO_PPROF_ENABLED" |
| 21 | + pathPrefix = "YOMO_PPROF_PATH_PREFIX" |
| 22 | + endpoint = "YOMO_PPROF_ENDPOINT" |
| 23 | +) |
| 24 | + |
| 25 | +func newEdgeConf() pprofConf { |
| 26 | + conf := pprofConf{} |
| 27 | + conf.Enabled = env.GetBool(pprofEnabled, false) |
| 28 | + conf.PathPrefix = env.GetString(pathPrefix, "/debug/pprof/") |
| 29 | + conf.Endpoint = env.GetString(endpoint, "0.0.0.0:6060") |
| 30 | + return conf |
| 31 | +} |
| 32 | + |
| 33 | +var logger = util.GetLogger("yomo::pprof") |
| 34 | + |
| 35 | +func Run() { |
| 36 | + conf := newEdgeConf() |
| 37 | + if conf.Enabled == false { |
| 38 | + return |
| 39 | + } |
| 40 | + |
| 41 | + mux := http.NewServeMux() |
| 42 | + pathPrefix := conf.PathPrefix |
| 43 | + mux.HandleFunc(pathPrefix, |
| 44 | + func(w http.ResponseWriter, r *http.Request) { |
| 45 | + name := strings.TrimPrefix(r.URL.Path, pathPrefix) |
| 46 | + if name != "" { |
| 47 | + pprof.Handler(name).ServeHTTP(w, r) |
| 48 | + return |
| 49 | + } |
| 50 | + pprof.Index(w, r) |
| 51 | + }) |
| 52 | + mux.HandleFunc(pathPrefix+"cmdline", pprof.Cmdline) |
| 53 | + mux.HandleFunc(pathPrefix+"profile", pprof.Profile) |
| 54 | + mux.HandleFunc(pathPrefix+"symbol", pprof.Symbol) |
| 55 | + mux.HandleFunc(pathPrefix+"trace", pprof.Trace) |
| 56 | + |
| 57 | + server := http.Server{ |
| 58 | + Addr: conf.Endpoint, |
| 59 | + Handler: mux, |
| 60 | + } |
| 61 | + |
| 62 | + logger.Infof("PProf server start... http://%s%s\n", conf.Endpoint, conf.PathPrefix) |
| 63 | + if err := server.ListenAndServe(); err != nil { |
| 64 | + if err == http.ErrServerClosed { |
| 65 | + logger.Errorf("PProf server closed.") |
| 66 | + } else { |
| 67 | + logger.Errorf("PProf server error: %v", err) |
| 68 | + } |
| 69 | + } |
| 70 | +} |
0 commit comments