From 0323a5b8cf5e51464a1f8777adf729036d093551 Mon Sep 17 00:00:00 2001 From: Justin Li Date: Fri, 26 Jun 2015 14:05:55 -0400 Subject: [PATCH] Add pprof debug HTTP endpoint --- chihaya.go | 20 ++------------------ debug.go | 52 ++++++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 54 insertions(+), 18 deletions(-) create mode 100644 debug.go diff --git a/chihaya.go b/chihaya.go index 50336cb..c594ba1 100644 --- a/chihaya.go +++ b/chihaya.go @@ -9,7 +9,6 @@ import ( "os" "os/signal" "runtime" - "runtime/pprof" "sync" "syscall" @@ -27,13 +26,11 @@ import ( var ( maxProcs int - profile string configPath string ) func init() { flag.IntVar(&maxProcs, "maxprocs", runtime.NumCPU(), "maximum parallel threads") - flag.StringVar(&profile, "profile", "", "if non-empty, path to write profiling data") flag.StringVar(&configPath, "config", "", "path to the configuration file") } @@ -47,21 +44,8 @@ func Boot() { runtime.GOMAXPROCS(maxProcs) glog.V(1).Info("Set max threads to ", maxProcs) - if profile != "" { - f, err := os.Create(profile) - if err != nil { - glog.Fatalf("Failed to create profile file: %s\n", err) - } - defer f.Close() - - pprof.StartCPUProfile(f) - glog.Info("Started profiling") - - defer func() { - pprof.StopCPUProfile() - glog.Info("Stopped profiling") - }() - } + debugBoot() + defer debugShutdown() cfg, err := config.Open(configPath) if err != nil { diff --git a/debug.go b/debug.go new file mode 100644 index 0000000..9781e48 --- /dev/null +++ b/debug.go @@ -0,0 +1,52 @@ +package chihaya + +import ( + "flag" + "net/http" + "os" + "runtime/pprof" + + _ "net/http/pprof" + + "github.com/golang/glog" +) + +var ( + profile string + debugAddr string + profileFile *os.File +) + +func init() { + flag.StringVar(&profile, "profile", "", "if non-empty, path to write CPU profiling data") + flag.StringVar(&debugAddr, "debug", "", "if non-empty, address to serve debug data") +} + +func debugBoot() { + var err error + + if debugAddr != "" { + go func() { + glog.Info("Starting debug HTTP on ", debugAddr) + glog.Fatal(http.ListenAndServe(debugAddr, nil)) + }() + } + + if profile != "" { + profileFile, err = os.Create(profile) + if err != nil { + glog.Fatalf("Failed to create profile file: %s\n", err) + } + + pprof.StartCPUProfile(profileFile) + glog.Info("Started profiling") + } +} + +func debugShutdown() { + if profileFile != nil { + profileFile.Close() + pprof.StopCPUProfile() + glog.Info("Stopped profiling") + } +}