add pprof performance profiling support

Add --pprof command line option to enable performance profiling

Signed-off-by: Jianhui Zhao <zhaojh329@gmail.com>
This commit is contained in:
Jianhui Zhao
2025-07-16 17:05:39 +08:00
parent 0ca0086bdd
commit d1703f44cd
3 changed files with 36 additions and 0 deletions
+2
View File
@@ -44,6 +44,7 @@ type Config struct {
LocalAuth bool LocalAuth bool
Password string Password string
AllowOrigins bool AllowOrigins bool
PprofAddr string
} }
func (cfg *Config) Parse(c *cli.Command) error { func (cfg *Config) Parse(c *cli.Command) error {
@@ -66,6 +67,7 @@ func (cfg *Config) Parse(c *cli.Command) error {
getFlagOpt(c, "token", &cfg.Token) getFlagOpt(c, "token", &cfg.Token)
getFlagOpt(c, "password", &cfg.Password) getFlagOpt(c, "password", &cfg.Password)
getFlagOpt(c, "allow-origins", &cfg.AllowOrigins) getFlagOpt(c, "allow-origins", &cfg.AllowOrigins)
getFlagOpt(c, "pprof", &cfg.PprofAddr)
return nil return nil
} }
+5
View File
@@ -26,6 +26,7 @@ package main
import ( import (
"context" "context"
_ "net/http/pprof"
"os" "os"
"runtime" "runtime"
"runtime/debug" "runtime/debug"
@@ -118,6 +119,10 @@ func main() {
Name: "allow-origins", Name: "allow-origins",
Usage: "allow all origins for cross-domain request", Usage: "allow all origins for cross-domain request",
}, },
&cli.StringFlag{
Name: "pprof",
Usage: "enable pprof and listen on specified address (e.g. localhost:6060)",
},
&cli.BoolFlag{ &cli.BoolFlag{
Name: "verbose", Name: "verbose",
Aliases: []string{"V"}, Aliases: []string{"V"},
+29
View File
@@ -25,6 +25,8 @@
package main package main
import ( import (
"net"
"net/http"
"sync" "sync"
"sync/atomic" "sync/atomic"
@@ -46,12 +48,39 @@ type DeviceGroup struct {
func (srv *RttyServer) Run() error { func (srv *RttyServer) Run() error {
log.Debug().Msgf("%+v", srv.cfg) log.Debug().Msgf("%+v", srv.cfg)
if srv.cfg.PprofAddr != "" {
go srv.ListenPprof()
}
go srv.ListenDevices() go srv.ListenDevices()
go srv.ListenHttpProxy() go srv.ListenHttpProxy()
return srv.ListenAPI() return srv.ListenAPI()
} }
func (srv *RttyServer) ListenPprof() {
ln, err := net.Listen("tcp", srv.cfg.PprofAddr)
if err != nil {
log.Error().Err(err).Msgf("Failed to start pprof server")
return
}
defer ln.Close()
addr := ln.Addr().(*net.TCPAddr)
log.Info().Msgf("Starting pprof server on: %s", addr)
host := addr.IP.String()
if host == "0.0.0.0" || host == "::" {
host = "localhost"
}
log.Info().Msgf("Access pprof at: http://%s:%d/debug/pprof/", host, addr.Port)
err = http.Serve(ln, nil)
if err != nil {
log.Error().Err(err).Msgf("pprof server failed")
}
}
func (srv *RttyServer) GetDevice(group, id string) *Device { func (srv *RttyServer) GetDevice(group, id string) *Device {
srv.mu.RLock() srv.mu.RLock()
defer srv.mu.RUnlock() defer srv.mu.RUnlock()