From a8bbd074f79cebd3b02d32e38ae975b5be816db1 Mon Sep 17 00:00:00 2001 From: Lynn Date: Tue, 3 Jul 2018 14:19:59 +0800 Subject: [PATCH] tidb-server, terror: add cleanup when `createServer` exits abnormally (#6947) * tidb-server, terror: add cleanup in createServer --- terror/terror.go | 7 +++++-- tidb-server/main.go | 15 ++++++++++----- 2 files changed, 15 insertions(+), 7 deletions(-) diff --git a/terror/terror.go b/terror/terror.go index 19baae2bb2d3f..f778c87033fe2 100644 --- a/terror/terror.go +++ b/terror/terror.go @@ -319,9 +319,12 @@ func ErrorNotEqual(err1, err2 error) bool { return !ErrorEqual(err1, err2) } -// MustNil fatals if err is not nil. -func MustNil(err error) { +// MustNil cleans up and fatals if err is not nil. +func MustNil(err error, closeFuns ...func()) { if err != nil { + for _, f := range closeFuns { + f() + } log.Fatalf(errors.ErrorStack(err)) } } diff --git a/tidb-server/main.go b/tidb-server/main.go index 61a45e8062df5..edff6cd4acaec 100644 --- a/tidb-server/main.go +++ b/tidb-server/main.go @@ -414,7 +414,8 @@ func createServer() { driver = server.NewTiDBDriver(storage) var err error svr, err = server.NewServer(cfg, driver) - terror.MustNil(err) + // Both domain and storage have started, so we have to clean them before exiting. + terror.MustNil(err, closeDomainAndStorage) if cfg.XProtocol.XServer { xcfg := &xserver.Config{ Addr: fmt.Sprintf("%s:%d", cfg.XProtocol.XHost, cfg.XProtocol.XPort), @@ -422,7 +423,7 @@ func createServer() { TokenLimit: cfg.TokenLimit, } xsvr, err = xserver.NewServer(xcfg) - terror.MustNil(err) + terror.MustNil(err, closeDomainAndStorage) } } @@ -484,11 +485,15 @@ func runServer() { } } +func closeDomainAndStorage() { + dom.Close() + err := storage.Close() + terror.Log(errors.Trace(err)) +} + func cleanup() { if graceful { svr.GracefulDown() } - dom.Close() - err := storage.Close() - terror.Log(errors.Trace(err)) + closeDomainAndStorage() }