automatically cleanup participant redis data

This commit is contained in:
David Zhao
2021-01-18 17:56:48 -08:00
parent 834a4747ac
commit d83a1b1af3
15 changed files with 262 additions and 59 deletions
+4
View File
@@ -35,6 +35,10 @@ func NewLocalNode(conf *config.Config) (LocalNode, error) {
Id: fmt.Sprintf("%s%16.16X", utils.NodePrefix, macUint64()),
Ip: ip,
NumCpus: uint32(runtime.NumCPU()),
Stats: &livekit.NodeStats{
StartedAt: time.Now().Unix(),
UpdatedAt: time.Now().Unix(),
},
}, nil
}
+9 -4
View File
@@ -2,6 +2,7 @@ package routing
import (
"context"
"sync"
"github.com/go-redis/redis/v8"
"google.golang.org/protobuf/proto"
@@ -68,6 +69,7 @@ type RedisSink struct {
rc *redis.Client
nodeId string
participantId string
once sync.Once
onClose func()
}
@@ -75,6 +77,7 @@ func NewRedisSink(rc *redis.Client, nodeId, participantId string) *RedisSink {
return &RedisSink{
rc: rc,
nodeId: nodeId,
once: sync.Once{},
participantId: participantId,
}
}
@@ -84,10 +87,12 @@ func (s *RedisSink) WriteMessage(msg proto.Message) error {
}
func (s *RedisSink) Close() {
publishRouterMessage(s.rc, s.nodeId, s.participantId, &livekit.EndSession{})
if s.onClose != nil {
s.onClose()
}
s.once.Do(func() {
publishRouterMessage(s.rc, s.nodeId, s.participantId, &livekit.EndSession{})
if s.onClose != nil {
s.onClose()
}
})
}
func (s *RedisSink) OnClose(f func()) {
+28 -7
View File
@@ -2,6 +2,7 @@ package routing
import (
"context"
"sync"
"time"
"github.com/go-redis/redis/v8"
@@ -14,7 +15,8 @@ import (
)
const (
defaultCacheTTL = time.Minute
// expire participant mappings after a day
participantMappingTTL = 24 * time.Hour
)
// TODO: need to implement redis key cleanup, for when clients disconnect and such
@@ -25,6 +27,7 @@ type RedisRouter struct {
rc *redis.Client
cr *utils.CachedRedis
ctx context.Context
once sync.Once
redisSinks map[string]*RedisSink
cancel func()
@@ -35,6 +38,7 @@ func NewRedisRouter(currentNode LocalNode, rc *redis.Client, useLocal bool) *Red
LocalRouter: *NewLocalRouter(currentNode),
useLocal: useLocal,
rc: rc,
once: sync.Once{},
redisSinks: make(map[string]*RedisSink),
}
rr.ctx, rr.cancel = context.WithCancel(context.Background())
@@ -55,8 +59,8 @@ func (r *RedisRouter) RegisterNode() error {
}
func (r *RedisRouter) UnregisterNode() error {
r.rc.HDel(r.ctx, NodesKey, r.currentNode.Id)
return nil
// could be called after Stop(), so we'd want to use an unrelated context
return r.rc.HDel(context.Background(), NodesKey, r.currentNode.Id).Err()
}
func (r *RedisRouter) GetNodeForRoom(roomName string) (string, error) {
@@ -102,7 +106,7 @@ func (r *RedisRouter) ListNodes() ([]*livekit.Node, error) {
func (r *RedisRouter) SetParticipantRTCNode(participantId, nodeId string) error {
r.cr.Expire(participantRTCKey(participantId))
err := r.rc.Set(r.ctx, participantRTCKey(participantId), nodeId, 0).Err()
err := r.rc.Set(r.ctx, participantRTCKey(participantId), nodeId, participantMappingTTL).Err()
if err != nil {
err = errors.Wrap(err, "could not set rtc node")
}
@@ -173,18 +177,23 @@ func (r *RedisRouter) StartParticipant(roomName, participantId, participantName
if r.onNewParticipant == nil {
return ErrHandlerNotDefined
}
resSink := r.getOrCreateRedisSink(signalNode, participantId)
r.onNewParticipant(
roomName,
participantId,
participantName,
r.getOrCreateMessageChannel(r.requestChannels, participantId),
r.getOrCreateRedisSink(signalNode, participantId),
resSink,
)
return nil
}
func (r *RedisRouter) Start() error {
go r.subscribeWorker()
r.once.Do(func() {
go r.statsWorker()
go r.subscribeWorker()
})
return nil
}
@@ -194,7 +203,7 @@ func (r *RedisRouter) Stop() {
func (r *RedisRouter) setParticipantSignalNode(participantId, nodeId string) error {
r.cr.Expire(participantSignalKey(participantId))
if err := r.rc.Set(r.ctx, participantSignalKey(participantId), nodeId, 0).Err(); err != nil {
if err := r.rc.Set(r.ctx, participantSignalKey(participantId), nodeId, participantMappingTTL).Err(); err != nil {
return errors.Wrap(err, "could not set signal node")
}
return nil
@@ -229,6 +238,18 @@ func (r *RedisRouter) getParticipantSignalNode(participantId string) (nodeId str
return r.cr.CachedGet(participantSignalKey(participantId))
}
// update node stats and cleanup
func (r *RedisRouter) statsWorker() {
for r.ctx.Err() == nil {
// update every 10 seconds
<-time.After(10 * time.Second)
r.currentNode.Stats.UpdatedAt = time.Now().Unix()
if err := r.RegisterNode(); err != nil {
logger.Errorw("could not update node", "error", err)
}
}
}
func (r *RedisRouter) subscribeWorker() {
sub := r.rc.Subscribe(redisCtx, nodeChannel(r.currentNode.Id))
+7 -6
View File
@@ -3,10 +3,11 @@ package rtc
import "errors"
var (
ErrRoomIdMissing = errors.New("room is not passed in")
ErrInvalidRoomName = errors.New("room must have a unique name")
ErrRoomNotFound = errors.New("requested room does not exist")
ErrPermissionDenied = errors.New("no permissions to access the room")
ErrUnexpectedOffer = errors.New("expected answer SDP, received offer")
ErrUnexpectedNegotiation = errors.New("client negotiation has not been granted")
ErrInvalidRoomName = errors.New("room must have a unique name")
ErrRoomNotFound = errors.New("requested room does not exist")
ErrRoomClosed = errors.New("room has already closed")
ErrPermissionDenied = errors.New("no permissions to access the room")
ErrMaxParticipantsExceeded = errors.New("room has exceeded its max participants")
ErrUnexpectedOffer = errors.New("expected answer SDP, received offer")
ErrUnexpectedNegotiation = errors.New("client negotiation has not been granted")
)
+2
View File
@@ -172,9 +172,11 @@ func (p *ParticipantImpl) ToProto() *livekit.ParticipantInfo {
State: p.state,
}
p.lock.RLock()
for _, t := range p.publishedTracks {
info.Tracks = append(info.Tracks, ToProtoTrack(t))
}
p.lock.RUnlock()
return info
}
+44
View File
@@ -2,6 +2,7 @@ package rtc
import (
"sync"
"time"
"github.com/thoas/go-funk"
@@ -16,6 +17,9 @@ type Room struct {
lock sync.RWMutex
// map of participantId -> Participant
participants map[string]types.Participant
hasJoined bool
isClosed bool
onClose func()
}
func NewRoom(room *livekit.Room, config WebRTCConfig) *Room {
@@ -40,9 +44,19 @@ func (r *Room) GetParticipants() []types.Participant {
}
func (r *Room) Join(participant types.Participant) error {
if r.isClosed {
return ErrRoomClosed
}
r.lock.Lock()
defer r.lock.Unlock()
if r.MaxParticipants > 0 && int(r.MaxParticipants) == len(r.participants) {
return ErrMaxParticipantsExceeded
}
r.hasJoined = true
// it's important to set this before connection, we don't want to miss out on any publishedTracks
participant.OnTrackPublished(r.onTrackAdded)
participant.OnStateChange(func(p types.Participant, oldState livekit.ParticipantInfo_State) {
@@ -102,6 +116,36 @@ func (r *Room) RemoveParticipant(id string) {
}
delete(r.participants, id)
go r.CloseIfEmpty()
}
// Close the room if all participants had left, or it's still empty past timeout
func (r *Room) CloseIfEmpty() {
if r.isClosed {
return
}
r.lock.RLock()
numParticipants := len(r.participants)
r.lock.RUnlock()
if numParticipants > 0 {
return
}
elapsed := uint32(time.Now().Unix() - r.CreationTime)
logger.Infow("comparing elapsed", "elapsed", elapsed, "timeout", r.EmptyTimeout)
if r.hasJoined || (r.EmptyTimeout > 0 && elapsed >= r.EmptyTimeout) {
r.isClosed = true
if r.onClose != nil {
r.onClose()
}
}
}
func (r *Room) OnClose(f func()) {
r.onClose = f
}
// a ParticipantImpl in the room added a new remoteTrack, subscribe other participants to it
+54 -1
View File
@@ -13,6 +13,7 @@ import (
const (
numParticipants = 3
defaultDelay = 10 * time.Millisecond
)
func TestRoomJoin(t *testing.T) {
@@ -61,7 +62,7 @@ func TestRoomJoin(t *testing.T) {
rm.RemoveParticipant(p.ID())
p.OnStateChangeArgsForCall(0)(p, livekit.ParticipantInfo_ACTIVE)
time.Sleep(10 * time.Millisecond)
time.Sleep(defaultDelay)
for _, op := range participants {
if op == p {
@@ -72,6 +73,58 @@ func TestRoomJoin(t *testing.T) {
assert.Equal(t, 1, fakeP.SendParticipantUpdateCallCount())
}
})
t.Run("cannot exceed max participants", func(t *testing.T) {
rm := newRoomWithParticipants(t, 1)
rm.MaxParticipants = 1
p := newMockParticipant("second")
err := rm.Join(p)
assert.Equal(t, rtc.ErrMaxParticipantsExceeded, err)
})
}
func TestRoomClosure(t *testing.T) {
t.Run("room closes after participant leaves", func(t *testing.T) {
rm := newRoomWithParticipants(t, 1)
isClosed := false
rm.OnClose(func() {
isClosed = true
})
p := rm.GetParticipants()[0]
rm.RemoveParticipant(p.ID())
time.Sleep(defaultDelay)
assert.Len(t, rm.GetParticipants(), 0)
assert.True(t, isClosed)
assert.Equal(t, rtc.ErrRoomClosed, rm.Join(p))
})
t.Run("room does not close before empty timeout", func(t *testing.T) {
rm := newRoomWithParticipants(t, 0)
isClosed := false
rm.OnClose(func() {
isClosed = true
})
rm.CloseIfEmpty()
assert.False(t, isClosed)
})
t.Run("room closes after empty timeout", func(t *testing.T) {
rm := newRoomWithParticipants(t, 0)
isClosed := false
rm.OnClose(func() {
isClosed = true
})
rm.EmptyTimeout = 1
time.Sleep(1010 * time.Millisecond)
rm.CloseIfEmpty()
assert.True(t, isClosed)
})
}
func TestNewTrack(t *testing.T) {
+4
View File
@@ -2,6 +2,7 @@ package service
import (
"sync"
"time"
"github.com/thoas/go-funk"
@@ -26,6 +27,9 @@ func NewLocalRoomStore() *LocalRoomStore {
}
func (p *LocalRoomStore) CreateRoom(room *livekit.Room) error {
if room.CreationTime == 0 {
room.CreationTime = time.Now().Unix()
}
p.lock.Lock()
p.rooms[room.Sid] = room
p.roomIds[room.Name] = room.Sid
+5 -1
View File
@@ -2,6 +2,7 @@ package service
import (
"context"
"time"
"github.com/go-redis/redis/v8"
"github.com/pkg/errors"
@@ -31,9 +32,12 @@ func NewRedisRoomStore(rc *redis.Client) *RedisRoomStore {
}
func (p *RedisRoomStore) CreateRoom(room *livekit.Room) error {
if room.CreationTime == 0 {
room.CreationTime = time.Now().Unix()
}
err := p.rc.HSet(p.ctx, RoomIdMap, room.Sid, room.Name).Err()
if err != nil {
return err
return errors.Wrap(err, "could not create room")
}
data, err := proto.Marshal(room)
+9
View File
@@ -90,6 +90,15 @@ func (r *RTCRunner) getOrCreateRoom(roomName string) (*rtc.Room, error) {
}
room = rtc.NewRoom(ri, *r.config)
room.OnClose(func() {
r.lock.Lock()
delete(r.rooms, roomName)
r.lock.Unlock()
// also delete room from db
if err := r.roomProvider.DeleteRoom(roomName); err != nil {
logger.Errorw("could not delete room", "error", err)
}
})
r.lock.Lock()
r.rooms[roomName] = room
r.lock.Unlock()
+4
View File
@@ -103,6 +103,10 @@ func (s *LivekitServer) Start() error {
<-s.doneChan
if err := s.router.UnregisterNode(); err != nil {
logger.Errorw("could not unregister node", "error", err)
}
// wait for shutdown
ctx, _ := context.WithTimeout(context.Background(), time.Second*5)
s.httpServer.Shutdown(ctx)