Skip to content

Commit

Permalink
pkg server: graceful shutdown
Browse files Browse the repository at this point in the history
  • Loading branch information
rkonfj committed Dec 24, 2023
1 parent 2ec7bf0 commit 1b0fa99
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 14 deletions.
13 changes: 13 additions & 0 deletions cmd/serve/cmd.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,11 @@
package serve

import (
"context"
"os"
"os/signal"
"syscall"

"github.com/dustin/go-humanize"
"github.com/rkonfj/toh/server"
"github.com/spf13/cobra"
Expand Down Expand Up @@ -31,6 +36,14 @@ func runAction(cmd *cobra.Command, args []string) error {
if err != nil {
return err
}

sigs := make(chan os.Signal, 1)
defer close(sigs)
signal.Notify(sigs, syscall.SIGINT, syscall.SIGTERM)
go func() {
<-sigs
s.Shutdown(context.Background())
}()
s.Run()
return nil
}
Expand Down
17 changes: 3 additions & 14 deletions server/server.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,12 @@ package server

import (
"context"
"errors"
"io"
"net"
"net/http"
"net/http/pprof"
"os"
"os/signal"
"sync"
"syscall"

"github.com/gorilla/websocket"
"github.com/rkonfj/toh/server/acl"
Expand Down Expand Up @@ -66,16 +64,16 @@ func NewTohServer(options Options) (*TohServer, error) {

func (s *TohServer) Run() {
go s.runTrafficEventConsumeLoop()
go s.runShutdownListener()

logrus.Infof("server listen on %s now", s.httpServer.Addr)
err := s.httpServer.ListenAndServe()
if err != nil {
if err != nil && !errors.Is(err, http.ErrServerClosed) {
logrus.Error(err)
}
}

func (s *TohServer) Shutdown(ctx context.Context) error {
s.acl.Shutdown()
return s.httpServer.Shutdown(ctx)
}

Expand Down Expand Up @@ -161,12 +159,3 @@ func (s *TohServer) pipe(wsConn *spec.Conn, netConn net.Conn) (lbc, rbc int64) {
logrus.Debugf("remote conn(%s) closed, close ws conn now", netConn.RemoteAddr().String())
return
}

func (s *TohServer) runShutdownListener() {
sigs := make(chan os.Signal, 1)
defer close(sigs)
signal.Notify(sigs, syscall.SIGINT, syscall.SIGTERM)
<-sigs
s.acl.Shutdown()
os.Exit(0)
}

0 comments on commit 1b0fa99

Please sign in to comment.