shutdown gracefully without os.Exit (#7480)

* shutdown gracefully without os.Exit

* Update server/util.go

Co-authored-by: Alessio Treglia <quadrispro@ubuntu.com>
Co-authored-by: Alessio Treglia <alessio@tendermint.com>
This commit is contained in:
yihuang
2020-10-14 15:13:48 +00:00
committed by GitHub
co-authored by Alessio Treglia Alessio Treglia
parent 652d5d93bb
commit f260ca4319
3 changed files with 33 additions and 9 deletions
+8 -8
View File
@@ -179,14 +179,14 @@ func startStandAlone(ctx *Context, appCreator types.AppCreator) error {
tmos.Exit(err.Error())
}
TrapSignal(func() {
defer func() {
if err = svr.Stop(); err != nil {
tmos.Exit(err.Error())
}
})
}()
// run forever (the node will not be returned)
select {}
// Wait for SIGINT or SIGTERM signal
return WaitForQuitSignals()
}
// legacyAminoCdc is used for the legacy REST API
@@ -290,7 +290,7 @@ func startInProcess(ctx *Context, clientCtx client.Context, appCreator types.App
}
}
TrapSignal(func() {
defer func() {
if tmNode.IsRunning() {
_ = tmNode.Stop()
}
@@ -308,8 +308,8 @@ func startInProcess(ctx *Context, clientCtx client.Context, appCreator types.App
}
ctx.Logger.Info("exiting...")
})
}()
// run forever (the node will not be returned)
select {}
// Wait for SIGINT or SIGTERM signal
return WaitForQuitSignals()
}
+18
View File
@@ -8,6 +8,7 @@ import (
"os"
"os/signal"
"path/filepath"
"strconv"
"syscall"
"time"
@@ -39,6 +40,15 @@ type Context struct {
Logger log.Logger
}
// ErrorCode contains the exit code for server exit.
type ErrorCode struct {
Code int
}
func (e ErrorCode) Error() string {
return strconv.Itoa(e.Code)
}
func NewDefaultContext() *Context {
return NewContext(viper.New(), tmcfg.DefaultConfig(), log.NewTMLogger(log.NewSyncWriter(os.Stdout)))
}
@@ -245,6 +255,14 @@ func TrapSignal(cleanupFunc func()) {
}()
}
// WaitForQuitSignals waits for SIGINT and SIGTERM and returns.
func WaitForQuitSignals() ErrorCode {
sigs := make(chan os.Signal, 1)
signal.Notify(sigs, syscall.SIGINT, syscall.SIGTERM)
sig := <-sigs
return ErrorCode{Code: int(sig.(syscall.Signal)) + 128}
}
func skipInterface(iface net.Interface) bool {
if iface.Flags&net.FlagUp == 0 {
return true // interface down