From 700a879c0b5568a1687a89d9aa5f9f960f4cb320 Mon Sep 17 00:00:00 2001 From: Mathew Kamkar <578302+matkam@users.noreply.github.com> Date: Wed, 15 Sep 2021 13:07:44 -0700 Subject: [PATCH] Redis Router graceful stop (#116) * prestop and hasparticipants in interface * add prestop function to existing routers * fakerouter prestop * update protocol version * read lock * redis router graceful stop * test fix * force stop --- cmd/server/main.go | 2 +- go.mod | 2 +- go.sum | 4 ++-- pkg/routing/interfaces.go | 1 + pkg/routing/localrouter.go | 4 ++++ pkg/routing/node.go | 1 + pkg/routing/redisrouter.go | 5 +++++ pkg/routing/routingfakes/fake_router.go | 2 ++ pkg/routing/selectorsystemload_test.go | 2 ++ pkg/routing/utils.go | 2 +- pkg/service/interfaces.go | 1 + pkg/service/roommanager.go | 12 ++++++++++++ pkg/service/server.go | 21 +++++++++++++++------ pkg/service/wire_gen.go | 3 ++- test/integration_helpers.go | 6 +++--- test/multinode_test.go | 2 +- test/turn_test.go | 2 +- test/webhook_test.go | 2 +- 18 files changed, 56 insertions(+), 18 deletions(-) diff --git a/cmd/server/main.go b/cmd/server/main.go index 5939fd66..d528d85e 100644 --- a/cmd/server/main.go +++ b/cmd/server/main.go @@ -202,7 +202,7 @@ func startServer(c *cli.Context) error { go func() { sig := <-sigChan logger.Infow("exit requested, shutting down", "signal", sig) - server.Stop() + server.Stop(false) }() return server.Start() diff --git a/go.mod b/go.mod index 8b56c2a6..d8bce4dc 100644 --- a/go.mod +++ b/go.mod @@ -14,7 +14,7 @@ require ( github.com/google/wire v0.5.0 github.com/gorilla/websocket v1.4.2 github.com/jxskiss/base62 v0.0.0-20191017122030-4f11678b909b - github.com/livekit/protocol v0.8.8 + github.com/livekit/protocol v0.8.9 github.com/magefile/mage v1.11.0 github.com/maxbrunsfeld/counterfeiter/v6 v6.3.0 github.com/mitchellh/go-homedir v1.1.0 diff --git a/go.sum b/go.sum index 2f230f0d..25b27a1d 100644 --- a/go.sum +++ b/go.sum @@ -246,8 +246,8 @@ github.com/lithammer/shortuuid/v3 v3.0.6 h1:pr15YQyvhiSX/qPxncFtqk+v4xLEpOZObbsY github.com/lithammer/shortuuid/v3 v3.0.6/go.mod h1:vMk8ke37EmiewwolSO1NLW8vP4ZaKlRuDIi8tWWmAts= github.com/livekit/ion-sfu v1.20.9 h1:Ih+tE5CXqdL1o6iXfZn+uBoddBXWceaOKVIun6aVuZM= github.com/livekit/ion-sfu v1.20.9/go.mod h1:g8hwobZI5fvX1RXvayf4ZXkgP7spV5YGE4yTSsumpB4= -github.com/livekit/protocol v0.8.8 h1:YXK+CNa3iMg+2P/RoBc2+buPV1ihdTlFqxaYxDb53KU= -github.com/livekit/protocol v0.8.8/go.mod h1:MEKn847Iu/2U8ClZyUmEm2oHn8k9fnSHy81Wv8kkSDo= +github.com/livekit/protocol v0.8.9 h1:oZNXehaeuV906sbnKtc4SvOld0Bj7lTF0AerenwvP70= +github.com/livekit/protocol v0.8.9/go.mod h1:MEKn847Iu/2U8ClZyUmEm2oHn8k9fnSHy81Wv8kkSDo= github.com/lucsky/cuid v1.0.2 h1:z4XlExeoderxoPj2/dxKOyPxe9RCOu7yNq9/XWxIUMQ= github.com/lucsky/cuid v1.0.2/go.mod h1:QaaJqckboimOmhRSJXSx/+IT+VTfxfPGSo/6mfgUfmE= github.com/lyft/protoc-gen-validate v0.0.13/go.mod h1:XbGvPuh87YZc5TdIa2/I4pLk0QoUACkjt2znoq26NVQ= diff --git a/pkg/routing/interfaces.go b/pkg/routing/interfaces.go index bfbaf57a..7ff580cf 100644 --- a/pkg/routing/interfaces.go +++ b/pkg/routing/interfaces.go @@ -62,6 +62,7 @@ type Router interface { OnRTCMessage(callback RTCMessageCallback) Start() error + PreStop() Stop() } diff --git a/pkg/routing/localrouter.go b/pkg/routing/localrouter.go index ed29f93f..718aa925 100644 --- a/pkg/routing/localrouter.go +++ b/pkg/routing/localrouter.go @@ -132,6 +132,10 @@ func (r *LocalRouter) Start() error { return nil } +func (r *LocalRouter) PreStop() { + r.currentNode.State = livekit.NodeState_SHUTTING_DOWN +} + func (r *LocalRouter) Stop() { r.rtcMessageChan.Close() } diff --git a/pkg/routing/node.go b/pkg/routing/node.go index 4681e860..b0251282 100644 --- a/pkg/routing/node.go +++ b/pkg/routing/node.go @@ -28,6 +28,7 @@ func NewLocalNode(conf *config.Config) (LocalNode, error) { Id: fmt.Sprintf("%s%s", utils.NodePrefix, HashedID(hostname)[:8]), Ip: conf.RTC.NodeIP, NumCpus: uint32(runtime.NumCPU()), + State: livekit.NodeState_SERVING, Stats: &livekit.NodeStats{ StartedAt: time.Now().Unix(), UpdatedAt: time.Now().Unix(), diff --git a/pkg/routing/redisrouter.go b/pkg/routing/redisrouter.go index 72a78e19..ed7c74c8 100644 --- a/pkg/routing/redisrouter.go +++ b/pkg/routing/redisrouter.go @@ -258,6 +258,11 @@ func (r *RedisRouter) Start() error { } } +func (r *RedisRouter) PreStop() { + r.currentNode.State = livekit.NodeState_SHUTTING_DOWN + r.RegisterNode() +} + func (r *RedisRouter) Stop() { if !r.isStarted.TrySet(false) { return diff --git a/pkg/routing/routingfakes/fake_router.go b/pkg/routing/routingfakes/fake_router.go index 80ff6dc7..18716d13 100644 --- a/pkg/routing/routingfakes/fake_router.go +++ b/pkg/routing/routingfakes/fake_router.go @@ -782,6 +782,8 @@ func (fake *FakeRouter) Stop() { } } +func (fake *FakeRouter) PreStop() {} + func (fake *FakeRouter) StopCallCount() int { fake.stopMutex.RLock() defer fake.stopMutex.RUnlock() diff --git a/pkg/routing/selectorsystemload_test.go b/pkg/routing/selectorsystemload_test.go index 41aaa7f7..4c3b9000 100644 --- a/pkg/routing/selectorsystemload_test.go +++ b/pkg/routing/selectorsystemload_test.go @@ -12,6 +12,7 @@ import ( var ( nodeLoadLow = &livekit.Node{ + State: livekit.NodeState_SERVING, Stats: &livekit.NodeStats{ UpdatedAt: time.Now().Unix(), NumCpus: 1, @@ -20,6 +21,7 @@ var ( } nodeLoadHigh = &livekit.Node{ + State: livekit.NodeState_SERVING, Stats: &livekit.NodeStats{ UpdatedAt: time.Now().Unix(), NumCpus: 1, diff --git a/pkg/routing/utils.go b/pkg/routing/utils.go index da47f9e1..b3011251 100644 --- a/pkg/routing/utils.go +++ b/pkg/routing/utils.go @@ -18,7 +18,7 @@ func IsAvailable(node *livekit.Node) bool { func GetAvailableNodes(nodes []*livekit.Node) []*livekit.Node { return funk.Filter(nodes, func(node *livekit.Node) bool { - return IsAvailable(node) + return IsAvailable(node) && node.State == livekit.NodeState_SERVING }).([]*livekit.Node) } diff --git a/pkg/service/interfaces.go b/pkg/service/interfaces.go index 57b1a957..242efcf1 100644 --- a/pkg/service/interfaces.go +++ b/pkg/service/interfaces.go @@ -41,5 +41,6 @@ type RoomManager interface { StartSession(ctx context.Context, roomName string, pi routing.ParticipantInit, requestSource routing.MessageSource, responseSink routing.MessageSink) CleanupRooms() error CloseIdleRooms() + HasParticipants() bool Stop() } diff --git a/pkg/service/roommanager.go b/pkg/service/roommanager.go index d88c5f4a..3054232f 100644 --- a/pkg/service/roommanager.go +++ b/pkg/service/roommanager.go @@ -202,6 +202,18 @@ func (r *LocalRoomManager) CloseIdleRooms() { } } +func (r *LocalRoomManager) HasParticipants() bool { + r.lock.RLock() + defer r.lock.RUnlock() + + for _, room := range r.rooms { + if len(room.GetParticipants()) != 0 { + return true + } + } + return false +} + func (r *LocalRoomManager) Stop() { // disconnect all clients r.lock.RLock() diff --git a/pkg/service/server.go b/pkg/service/server.go index 25720e9b..cd213caf 100644 --- a/pkg/service/server.go +++ b/pkg/service/server.go @@ -171,7 +171,7 @@ func (s *LivekitServer) Start() error { logger.Infow("starting LiveKit server", values...) if err := s.httpServer.Serve(ln); err != http.ErrServerClosed { logger.Errorw("could not start server", err) - s.Stop() + s.Stop(true) } }() @@ -184,10 +184,6 @@ func (s *LivekitServer) Start() error { <-s.doneChan - if err := s.router.UnregisterNode(); err != nil { - logger.Errorw("could not unregister node", err) - } - // wait for shutdown ctx, cancel := context.WithTimeout(context.Background(), time.Second*5) defer cancel() @@ -203,7 +199,20 @@ func (s *LivekitServer) Start() error { return nil } -func (s *LivekitServer) Stop() { +func (s *LivekitServer) Stop(force bool) { + // wait for all participants to exit + s.router.PreStop() + partTicker := time.NewTicker(5 * time.Second) + waitingForParticipants := !force && s.roomManager.HasParticipants() + for waitingForParticipants { + select { + case <-partTicker.C: + logger.Infow("waiting for participants to exit") + waitingForParticipants = s.roomManager.HasParticipants() + } + } + partTicker.Stop() + if !s.running.TrySet(false) { return } diff --git a/pkg/service/wire_gen.go b/pkg/service/wire_gen.go index eb36a39d..1a9cf9fc 100644 --- a/pkg/service/wire_gen.go +++ b/pkg/service/wire_gen.go @@ -1,7 +1,8 @@ // Code generated by Wire. DO NOT EDIT. //go:generate go run github.com/google/wire/cmd/wire -//+build !wireinject +//go:build !wireinject +// +build !wireinject package service diff --git a/test/integration_helpers.go b/test/integration_helpers.go index 5c42883b..9c2f9232 100644 --- a/test/integration_helpers.go +++ b/test/integration_helpers.go @@ -63,7 +63,7 @@ func setupSingleNodeTest(name string, roomName string) (*service.LivekitServer, panic(err) } return s, func() { - s.Stop() + s.Stop(true) logger.Infow("----------------FINISHING TEST----------------", "test", name) } } @@ -79,8 +79,8 @@ func setupMultiNodeTest(name string) (*service.LivekitServer, *service.LivekitSe waitForServerToStart(s2) return s1, s2, func() { - s1.Stop() - s2.Stop() + s1.Stop(true) + s2.Stop(true) redisClient().FlushAll(context.Background()) logger.Infow("----------------FINISHING TEST----------------", "test", name) } diff --git a/test/multinode_test.go b/test/multinode_test.go index 97d95f41..cd1d5476 100644 --- a/test/multinode_test.go +++ b/test/multinode_test.go @@ -117,7 +117,7 @@ func TestMultinodeReconnectAfterNodeShutdown(t *testing.T) { stopClients(c1, c2) // stop s2, and connect to room again - s2.Stop() + s2.Stop(true) time.Sleep(syncDelay) diff --git a/test/turn_test.go b/test/turn_test.go index f299ac56..24795674 100644 --- a/test/turn_test.go +++ b/test/turn_test.go @@ -32,7 +32,7 @@ func testTurnServer(t *testing.T) { require.NoError(t, err) go s.Start() waitForServerToStart(s) - defer s.Stop() + defer s.Stop(true) time.Sleep(syncDelay) diff --git a/test/webhook_test.go b/test/webhook_test.go index fa4baf0b..cbbf6f46 100644 --- a/test/webhook_test.go +++ b/test/webhook_test.go @@ -119,7 +119,7 @@ func setupServerWithWebhook() (server *service.LivekitServer, testServer *webook waitForServerToStart(server) finishFunc = func() { - server.Stop() + server.Stop(true) testServer.Stop() } return