From 6cc182de0827ef71ce69bc2f4ad4e0fb89a54bfa Mon Sep 17 00:00:00 2001 From: James Elliott Date: Sun, 4 Sep 2022 22:26:03 +1000 Subject: [PATCH] fix(commands): potential nil ptr error on shutdown (#3947) --- internal/commands/root.go | 30 +++++++++++++++++++++--------- 1 file changed, 21 insertions(+), 9 deletions(-) diff --git a/internal/commands/root.go b/internal/commands/root.go index 45a262cb5..c532d562e 100644 --- a/internal/commands/root.go +++ b/internal/commands/root.go @@ -86,6 +86,7 @@ func cmdRootRun(_ *cobra.Command, _ []string) { runServers(config, providers, logger) } +//nolint:gocyclo // Complexity is required in this function. func runServers(config *schema.Configuration, providers middlewares.Providers, log *logrus.Logger) { ctx := context.Background() @@ -108,8 +109,8 @@ func runServers(config *schema.Configuration, providers middlewares.Providers, l g.Go(func() (err error) { defer func() { - if rec := recover(); rec != nil { - log.WithError(recoverErr(rec)).Errorf("Critical error in server caught (recovered)") + if r := recover(); r != nil { + log.WithError(recoverErr(r)).Errorf("Critical error in server caught (recovered)") } }() @@ -118,6 +119,8 @@ func runServers(config *schema.Configuration, providers middlewares.Providers, l } if err = mainServer.Serve(mainListener); err != nil { + log.WithError(err).Error("Server (main) returned error") + return err } @@ -130,8 +133,8 @@ func runServers(config *schema.Configuration, providers middlewares.Providers, l } defer func() { - if rec := recover(); rec != nil { - log.WithError(recoverErr(rec)).Errorf("Critical error in metrics server caught (recovered)") + if r := recover(); r != nil { + log.WithError(recoverErr(r)).Errorf("Critical error in metrics server caught (recovered)") } }() @@ -140,6 +143,8 @@ func runServers(config *schema.Configuration, providers middlewares.Providers, l } if err = metricsServer.Serve(metricsListener); err != nil { + log.WithError(err).Error("Server (metrics) returned error") + return err } @@ -147,10 +152,15 @@ func runServers(config *schema.Configuration, providers middlewares.Providers, l }) select { - case <-quit: - break + case s := <-quit: + switch s { + case syscall.SIGINT: + log.Debugf("Shutdown started due to SIGINT") + case syscall.SIGQUIT: + log.Debugf("Shutdown started due to SIGQUIT") + } case <-ctx.Done(): - break + log.Debugf("Shutdown started due to context completion") } cancel() @@ -159,8 +169,10 @@ func runServers(config *schema.Configuration, providers middlewares.Providers, l var err error - if err = mainServer.Shutdown(); err != nil { - log.WithError(err).Errorf("Error occurred shutting down the server") + if mainServer != nil { + if err = mainServer.Shutdown(); err != nil { + log.WithError(err).Errorf("Error occurred shutting down the server") + } } if metricsServer != nil {