From 3246ca85aa5d4f040eb15e36e531955adea3d1b9 Mon Sep 17 00:00:00 2001 From: Patrick Date: Mon, 12 Aug 2024 13:44:19 +0200 Subject: [PATCH] (NOBIDS) gracefully shutdown frontend (#2929) --- cmd/explorer/main.go | 18 +++++++++++++++--- utils/utils.go | 3 ++- 2 files changed, 17 insertions(+), 4 deletions(-) diff --git a/cmd/explorer/main.go b/cmd/explorer/main.go index afe23b3e4b..d67bc8f1a2 100644 --- a/cmd/explorer/main.go +++ b/cmd/explorer/main.go @@ -4,6 +4,7 @@ import ( "context" "encoding/gob" "encoding/hex" + "errors" "flag" "fmt" "math/big" @@ -58,6 +59,8 @@ func init() { gob.Register(types.DataTableSaveState{}) } +var frontendHttpServer *http.Server + func main() { configPath := flag.String("config", "", "Path to the config file, if empty string defaults will be used") versionFlag := flag.Bool("version", false, "Show version and exit") @@ -639,7 +642,7 @@ func main() { if utils.Config.Frontend.HttpIdleTimeout == 0 { utils.Config.Frontend.HttpIdleTimeout = time.Minute } - srv := &http.Server{ + frontendHttpServer = &http.Server{ Addr: cfg.Frontend.Server.Host + ":" + cfg.Frontend.Server.Port, WriteTimeout: utils.Config.Frontend.HttpWriteTimeout, ReadTimeout: utils.Config.Frontend.HttpReadTimeout, @@ -647,9 +650,9 @@ func main() { Handler: n, } - logrus.Printf("http server listening on %v", srv.Addr) + logrus.Printf("http server listening on %v", frontendHttpServer.Addr) go func() { - if err := srv.ListenAndServe(); err != nil { + if err := frontendHttpServer.ListenAndServe(); err != nil && !errors.Is(err, http.ErrServerClosed) { logrus.WithError(err).Fatal("Error serving frontend") } }() @@ -670,5 +673,14 @@ func main() { utils.WaitForCtrlC() + if frontendHttpServer != nil { + logrus.Infof("shutting down frontendHttpServer") + ctx, cancel := context.WithTimeout(context.Background(), time.Second*10) + defer cancel() + if err := frontendHttpServer.Shutdown(ctx); err != nil { + logrus.WithError(err).Error("error shutting down frontend server") + } + } + logrus.Println("exiting...") } diff --git a/utils/utils.go b/utils/utils.go index fa3e9310c4..35313ff243 100644 --- a/utils/utils.go +++ b/utils/utils.go @@ -28,6 +28,7 @@ import ( "sort" "strconv" "strings" + "syscall" "time" "unicode/utf8" @@ -395,7 +396,7 @@ func GWeiBytesToEther(gwei []byte) decimal.Decimal { // WaitForCtrlC will block/wait until a control-c is pressed func WaitForCtrlC() { c := make(chan os.Signal, 1) - signal.Notify(c, os.Interrupt) + signal.Notify(c, os.Interrupt, syscall.SIGINT, syscall.SIGTERM) <-c }