implement graceful restart

This commit is contained in:
smallnest
2020-07-13 18:00:08 +08:00
parent ed08247be3
commit bd48ea556b
2 changed files with 42 additions and 1 deletions

View File

@@ -20,7 +20,7 @@ import (
func (s *Server) startGateway(network string, ln net.Listener) net.Listener { func (s *Server) startGateway(network string, ln net.Listener) net.Listener {
if network != "tcp" && network != "tcp4" && network != "tcp6" { if network != "tcp" && network != "tcp4" && network != "tcp6" {
log.Infof("network is not tcp/tcp4/tcp6 so can not start gateway") // log.Infof("network is not tcp/tcp4/tcp6 so can not start gateway")
return ln return ln
} }

View File

@@ -18,6 +18,7 @@ import (
"time" "time"
"os" "os"
"os/exec"
"os/signal" "os/signal"
"syscall" "syscall"
@@ -751,6 +752,46 @@ func (s *Server) Shutdown(ctx context.Context) error {
return err return err
} }
// Restart restarts this server gracefully.
// It starts a new rpcx server with the same port with SO_REUSEPORT socket option,
// and shutdown this rpcx server gracefully.
func (s *Server) Restart(ctx context.Context) error {
pid, err := s.startProcess()
if err != nil {
return err
}
log.Infof("restart a new rpcx server: %d", pid)
// TODO: is it necessary?
time.Sleep(3 * time.Second)
return s.Shutdown(ctx)
}
func (s *Server) startProcess() (int, error) {
argv0, err := exec.LookPath(os.Args[0])
if err != nil {
return 0, err
}
// Pass on the environment and replace the old count key with the new one.
var env []string
for _, v := range os.Environ() {
env = append(env, v)
}
var originalWD, _ = os.Getwd()
allFiles := append([]*os.File{os.Stdin, os.Stdout, os.Stderr})
process, err := os.StartProcess(argv0, os.Args, &os.ProcAttr{
Dir: originalWD,
Env: env,
Files: allFiles,
})
if err != nil {
return 0, err
}
return process.Pid, nil
}
func (s *Server) checkProcessMsg() bool { func (s *Server) checkProcessMsg() bool {
size := atomic.LoadInt32(&s.handlerMsgNum) size := atomic.LoadInt32(&s.handlerMsgNum)
log.Info("need handle in-processing msg size:", size) log.Info("need handle in-processing msg size:", size)