lnd: properly shutdown the optional pprof server

This commit makes sure when lnd is shutting down, the optional pprof
server is also gracefully shutting down.
This commit is contained in:
yyforyongyu
2023-04-19 17:06:09 +08:00
parent f56c9e9c8a
commit 4243c5b95f

42
lnd.go
View File

@@ -180,14 +180,42 @@ func Main(cfg *Config, lisCfg ListenerCfg, implCfg *ImplementationCfg,
network, network,
) )
ctx := context.Background()
ctx, cancel := context.WithCancel(ctx)
defer cancel()
// Enable http profiling server if requested. // Enable http profiling server if requested.
if cfg.Profile != "" { if cfg.Profile != "" {
// Create the http handler.
profileRedirect := http.RedirectHandler(
"/debug/pprof", http.StatusSeeOther,
)
http.Handle("/", profileRedirect)
ltndLog.Infof("Pprof listening on %v", cfg.Profile)
// Create the pprof server.
pprofServer := &http.Server{
Addr: cfg.Profile,
Handler: profileRedirect,
ReadHeaderTimeout: 5 * time.Second,
}
// Shut the server down when lnd is shutting down.
defer func() {
ltndLog.Info("Stopping pprof server...")
err := pprofServer.Shutdown(ctx)
if err != nil {
ltndLog.Errorf("Stop pprof server got err: %v",
err)
}
}()
// Start the pprof server.
go func() { go func() {
profileRedirect := http.RedirectHandler("/debug/pprof", err := pprofServer.ListenAndServe()
http.StatusSeeOther) if err != nil && !errors.Is(err, http.ErrServerClosed) {
http.Handle("/", profileRedirect) ltndLog.Errorf("Serving pprof got err: %v", err)
ltndLog.Infof("Pprof listening on %v", cfg.Profile) }
fmt.Println(http.ListenAndServe(cfg.Profile, nil))
}() }()
} }
@@ -202,10 +230,6 @@ func Main(cfg *Config, lisCfg ListenerCfg, implCfg *ImplementationCfg,
defer pprof.StopCPUProfile() defer pprof.StopCPUProfile()
} }
ctx := context.Background()
ctx, cancel := context.WithCancel(ctx)
defer cancel()
// Run configuration dependent DB pre-initialization. Note that this // Run configuration dependent DB pre-initialization. Note that this
// needs to be done early and once during the startup process, before // needs to be done early and once during the startup process, before
// any DB access. // any DB access.