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 23:13:48 +08:00 committed by GitHub
parent 652d5d93bb
commit f260ca4319
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 33 additions and 9 deletions

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()
}

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

View File

@ -3,12 +3,18 @@ package main
import (
"os"
"github.com/cosmos/cosmos-sdk/server"
"github.com/cosmos/cosmos-sdk/simapp/simd/cmd"
)
func main() {
rootCmd, _ := cmd.NewRootCmd()
if err := cmd.Execute(rootCmd); err != nil {
os.Exit(1)
switch e := err.(type) {
case server.ErrorCode:
os.Exit(e.Code)
default:
os.Exit(1)
}
}
}