Fix MessageChannel leaks (#646)

This commit is contained in:
David Zhao
2022-04-22 10:53:20 -07:00
committed by GitHub
parent 2e182afb61
commit b7d22c4f34
8 changed files with 161 additions and 117 deletions
+53 -3
View File
@@ -2,6 +2,7 @@ package routing
import (
"context"
"encoding/json"
"github.com/go-redis/redis/v8"
"google.golang.org/protobuf/proto"
@@ -19,13 +20,13 @@ import (
type MessageSink interface {
WriteMessage(msg proto.Message) error
Close()
OnClose(f func())
}
//counterfeiter:generate . MessageSource
type MessageSource interface {
// ReadChan exposes a one way channel to make it easier to use with select
ReadChan() <-chan proto.Message
Close()
}
type ParticipantInit struct {
@@ -39,8 +40,20 @@ type ParticipantInit struct {
AdaptiveStream bool
}
type NewParticipantCallback func(ctx context.Context, roomName livekit.RoomName, pi ParticipantInit, requestSource MessageSource, responseSink MessageSink)
type RTCMessageCallback func(ctx context.Context, roomName livekit.RoomName, identity livekit.ParticipantIdentity, msg *livekit.RTCNodeMessage)
type NewParticipantCallback func(
ctx context.Context,
roomName livekit.RoomName,
pi ParticipantInit,
requestSource MessageSource,
responseSink MessageSink,
) error
type RTCMessageCallback func(
ctx context.Context,
roomName livekit.RoomName,
identity livekit.ParticipantIdentity,
msg *livekit.RTCNodeMessage,
)
// Router allows multiple nodes to coordinate the participant session
//counterfeiter:generate . Router
@@ -88,3 +101,40 @@ func CreateRouter(rc *redis.Client, node LocalNode) Router {
logger.Infow("using single-node routing")
return NewLocalRouter(node)
}
func (pi *ParticipantInit) ToStartSession(roomName livekit.RoomName, connectionID livekit.ConnectionID) (*livekit.StartSession, error) {
claims, err := json.Marshal(pi.Grants)
if err != nil {
return nil, err
}
return &livekit.StartSession{
RoomName: string(roomName),
Identity: string(pi.Identity),
Name: string(pi.Name),
// connection id is to allow the RTC node to identify where to route the message back to
ConnectionId: string(connectionID),
Reconnect: pi.Reconnect,
AutoSubscribe: pi.AutoSubscribe,
Client: pi.Client,
GrantsJson: string(claims),
AdaptiveStream: pi.AdaptiveStream,
}, nil
}
func ParticipantInitFromStartSession(ss *livekit.StartSession) (*ParticipantInit, error) {
claims := &auth.ClaimGrants{}
if err := json.Unmarshal([]byte(ss.GrantsJson), claims); err != nil {
return nil, err
}
return &ParticipantInit{
Identity: livekit.ParticipantIdentity(ss.Identity),
Name: livekit.ParticipantName(ss.Name),
Reconnect: ss.Reconnect,
Client: ss.Client,
AutoSubscribe: ss.AutoSubscribe,
Grants: claims,
AdaptiveStream: ss.AdaptiveStream,
}, nil
}
+19 -9
View File
@@ -102,15 +102,25 @@ func (r *LocalRouter) StartParticipantSignal(ctx context.Context, roomName livek
reqChan = r.getOrCreateMessageChannel(r.requestChannels, string(key))
resChan = r.getOrCreateMessageChannel(r.responseChannels, string(key))
r.onNewParticipant(
ctx,
roomName,
pi,
// request source
reqChan,
// response sink
resChan,
)
go func() {
err := r.onNewParticipant(
ctx,
roomName,
pi,
// request source
reqChan,
// response sink
resChan,
)
if err != nil {
reqChan.Close()
resChan.Close()
logger.Errorw("could not handle new participant", err,
"room", roomName,
"participant", pi.Identity,
)
}
}()
return livekit.ConnectionID(pi.Identity), reqChan, resChan, nil
}
+18 -15
View File
@@ -1,22 +1,24 @@
package routing
import (
"sync"
"google.golang.org/protobuf/proto"
)
const DefaultMessageChannelSize = 200
type MessageChannel struct {
msgChan chan proto.Message
closed chan struct{}
onClose func()
msgChan chan proto.Message
onClose func()
isClosed bool
lock sync.RWMutex
}
func NewMessageChannel(size int) *MessageChannel {
return &MessageChannel{
// allow some buffer to avoid blocked writes
msgChan: make(chan proto.Message, size),
closed: make(chan struct{}),
}
}
@@ -25,22 +27,19 @@ func (m *MessageChannel) OnClose(f func()) {
}
func (m *MessageChannel) IsClosed() bool {
select {
case <-m.closed:
return true
default:
return false
}
m.lock.RLock()
defer m.lock.RUnlock()
return m.isClosed
}
func (m *MessageChannel) WriteMessage(msg proto.Message) error {
if m.IsClosed() {
m.lock.RLock()
defer m.lock.RUnlock()
if m.isClosed {
return ErrChannelClosed
}
select {
case <-m.closed:
return ErrChannelClosed
case m.msgChan <- msg:
// published
return nil
@@ -55,11 +54,15 @@ func (m *MessageChannel) ReadChan() <-chan proto.Message {
}
func (m *MessageChannel) Close() {
if m.IsClosed() {
m.lock.Lock()
if m.isClosed {
m.lock.Unlock()
return
}
close(m.closed)
m.isClosed = true
close(m.msgChan)
m.lock.Unlock()
if m.onClose != nil {
m.onClose()
}
+22 -34
View File
@@ -3,7 +3,6 @@ package routing
import (
"bytes"
"context"
"encoding/json"
"runtime/pprof"
"sync"
"time"
@@ -13,7 +12,6 @@ import (
"go.uber.org/atomic"
"google.golang.org/protobuf/proto"
"github.com/livekit/protocol/auth"
"github.com/livekit/protocol/livekit"
"github.com/livekit/protocol/logger"
"github.com/livekit/protocol/utils"
@@ -158,24 +156,13 @@ func (r *RedisRouter) StartParticipantSignal(ctx context.Context, roomName livek
sink := NewRTCNodeSink(r.rc, livekit.NodeID(rtcNode.Id), pKey)
// serialize claims
claims, err := json.Marshal(pi.Grants)
ss, err := pi.ToStartSession(roomName, connectionID)
if err != nil {
return
}
// sends a message to start session
err = sink.WriteMessage(&livekit.StartSession{
RoomName: string(roomName),
Identity: string(pi.Identity),
Name: string(pi.Name),
// connection id is to allow the RTC node to identify where to route the message back to
ConnectionId: string(connectionID),
Reconnect: pi.Reconnect,
AutoSubscribe: pi.AutoSubscribe,
Client: pi.Client,
GrantsJson: string(claims),
AdaptiveStream: pi.AdaptiveStream,
})
err = sink.WriteMessage(ss)
if err != nil {
return
}
@@ -253,30 +240,31 @@ func (r *RedisRouter) startParticipantRTC(ss *livekit.StartSession, participantK
}
}
claims := &auth.ClaimGrants{}
if err := json.Unmarshal([]byte(ss.GrantsJson), claims); err != nil {
pi, err := ParticipantInitFromStartSession(ss)
if err != nil {
return err
}
pi := ParticipantInit{
Identity: livekit.ParticipantIdentity(ss.Identity),
Name: livekit.ParticipantName(ss.Name),
Reconnect: ss.Reconnect,
Client: ss.Client,
AutoSubscribe: ss.AutoSubscribe,
Grants: claims,
AdaptiveStream: ss.AdaptiveStream,
}
reqChan := r.getOrCreateMessageChannel(r.requestChannels, string(participantKey))
resSink := NewSignalNodeSink(r.rc, livekit.NodeID(signalNode), livekit.ConnectionID(ss.ConnectionId))
go r.onNewParticipant(
r.ctx,
livekit.RoomName(ss.RoomName),
pi,
reqChan,
resSink,
)
go func() {
err := r.onNewParticipant(
r.ctx,
livekit.RoomName(ss.RoomName),
*pi,
reqChan,
resSink,
)
if err != nil {
logger.Errorw("could not handle new participant", err,
"room", ss.RoomName,
"participant", ss.Identity,
)
// cleanup request channels
reqChan.Close()
resSink.Close()
}
}()
return nil
}
@@ -13,11 +13,6 @@ type FakeMessageSink struct {
closeMutex sync.RWMutex
closeArgsForCall []struct {
}
OnCloseStub func(func())
onCloseMutex sync.RWMutex
onCloseArgsForCall []struct {
arg1 func()
}
WriteMessageStub func(protoreflect.ProtoMessage) error
writeMessageMutex sync.RWMutex
writeMessageArgsForCall []struct {
@@ -57,38 +52,6 @@ func (fake *FakeMessageSink) CloseCalls(stub func()) {
fake.CloseStub = stub
}
func (fake *FakeMessageSink) OnClose(arg1 func()) {
fake.onCloseMutex.Lock()
fake.onCloseArgsForCall = append(fake.onCloseArgsForCall, struct {
arg1 func()
}{arg1})
stub := fake.OnCloseStub
fake.recordInvocation("OnClose", []interface{}{arg1})
fake.onCloseMutex.Unlock()
if stub != nil {
fake.OnCloseStub(arg1)
}
}
func (fake *FakeMessageSink) OnCloseCallCount() int {
fake.onCloseMutex.RLock()
defer fake.onCloseMutex.RUnlock()
return len(fake.onCloseArgsForCall)
}
func (fake *FakeMessageSink) OnCloseCalls(stub func(func())) {
fake.onCloseMutex.Lock()
defer fake.onCloseMutex.Unlock()
fake.OnCloseStub = stub
}
func (fake *FakeMessageSink) OnCloseArgsForCall(i int) func() {
fake.onCloseMutex.RLock()
defer fake.onCloseMutex.RUnlock()
argsForCall := fake.onCloseArgsForCall[i]
return argsForCall.arg1
}
func (fake *FakeMessageSink) WriteMessage(arg1 protoreflect.ProtoMessage) error {
fake.writeMessageMutex.Lock()
ret, specificReturn := fake.writeMessageReturnsOnCall[len(fake.writeMessageArgsForCall)]
@@ -155,8 +118,6 @@ func (fake *FakeMessageSink) Invocations() map[string][][]interface{} {
defer fake.invocationsMutex.RUnlock()
fake.closeMutex.RLock()
defer fake.closeMutex.RUnlock()
fake.onCloseMutex.RLock()
defer fake.onCloseMutex.RUnlock()
fake.writeMessageMutex.RLock()
defer fake.writeMessageMutex.RUnlock()
copiedInvocations := map[string][][]interface{}{}
@@ -9,6 +9,10 @@ import (
)
type FakeMessageSource struct {
CloseStub func()
closeMutex sync.RWMutex
closeArgsForCall []struct {
}
ReadChanStub func() <-chan protoreflect.ProtoMessage
readChanMutex sync.RWMutex
readChanArgsForCall []struct {
@@ -23,6 +27,30 @@ type FakeMessageSource struct {
invocationsMutex sync.RWMutex
}
func (fake *FakeMessageSource) Close() {
fake.closeMutex.Lock()
fake.closeArgsForCall = append(fake.closeArgsForCall, struct {
}{})
stub := fake.CloseStub
fake.recordInvocation("Close", []interface{}{})
fake.closeMutex.Unlock()
if stub != nil {
fake.CloseStub()
}
}
func (fake *FakeMessageSource) CloseCallCount() int {
fake.closeMutex.RLock()
defer fake.closeMutex.RUnlock()
return len(fake.closeArgsForCall)
}
func (fake *FakeMessageSource) CloseCalls(stub func()) {
fake.closeMutex.Lock()
defer fake.closeMutex.Unlock()
fake.CloseStub = stub
}
func (fake *FakeMessageSource) ReadChan() <-chan protoreflect.ProtoMessage {
fake.readChanMutex.Lock()
ret, specificReturn := fake.readChanReturnsOnCall[len(fake.readChanArgsForCall)]
@@ -79,6 +107,8 @@ func (fake *FakeMessageSource) ReadChanReturnsOnCall(i int, result1 <-chan proto
func (fake *FakeMessageSource) Invocations() map[string][][]interface{} {
fake.invocationsMutex.RLock()
defer fake.invocationsMutex.RUnlock()
fake.closeMutex.RLock()
defer fake.closeMutex.RUnlock()
fake.readChanMutex.RLock()
defer fake.readChanMutex.RUnlock()
copiedInvocations := map[string][][]interface{}{}
+18 -17
View File
@@ -6,6 +6,8 @@ import (
"sync"
"time"
"github.com/pkg/errors"
"github.com/livekit/protocol/auth"
"github.com/livekit/protocol/livekit"
"github.com/livekit/protocol/logger"
@@ -180,11 +182,16 @@ func (r *RoomManager) Stop() {
}
// StartSession starts WebRTC session when a new participant is connected, takes place on RTC node
func (r *RoomManager) StartSession(ctx context.Context, roomName livekit.RoomName, pi routing.ParticipantInit, requestSource routing.MessageSource, responseSink routing.MessageSink) {
func (r *RoomManager) StartSession(
ctx context.Context,
roomName livekit.RoomName,
pi routing.ParticipantInit,
requestSource routing.MessageSource,
responseSink routing.MessageSink,
) error {
room, err := r.getOrCreateRoom(ctx, roomName)
if err != nil {
logger.Errorw("could not create room", err, "room", roomName)
return
return err
}
defer room.Release()
@@ -198,11 +205,7 @@ func (r *RoomManager) StartSession(ctx context.Context, roomName livekit.RoomNam
"nodeID", r.currentNode.Id,
"participant", pi.Identity,
)
if err = room.ResumeParticipant(participant, responseSink); err != nil {
logger.Warnw("could not resume participant", err,
"participant", pi.Identity)
}
return
return room.ResumeParticipant(participant, responseSink)
} else {
// we need to clean up the existing participant, so a new one can join
room.RemoveParticipant(participant.Identity())
@@ -210,17 +213,14 @@ func (r *RoomManager) StartSession(ctx context.Context, roomName livekit.RoomNam
} else if pi.Reconnect {
// send leave request if participant is trying to reconnect without keep subscribe state
// but missing from the room
if err = responseSink.WriteMessage(&livekit.SignalResponse{
_ = responseSink.WriteMessage(&livekit.SignalResponse{
Message: &livekit.SignalResponse_Leave{
Leave: &livekit.LeaveRequest{
CanReconnect: true,
},
},
}); err != nil {
logger.Warnw("could not restart participant", err,
"participant", pi.Identity)
}
return
})
return errors.New("could not restart participant")
}
logger.Debugw("starting RTC session",
@@ -259,8 +259,7 @@ func (r *RoomManager) StartSession(ctx context.Context, roomName livekit.RoomNam
AdaptiveStream: pi.AdaptiveStream,
})
if err != nil {
logger.Errorw("could not create participant", err)
return
return err
}
// join room
@@ -270,7 +269,7 @@ func (r *RoomManager) StartSession(ctx context.Context, roomName livekit.RoomNam
if err = room.Join(participant, &opts, r.iceServersForRoom(room.Room), r.currentNode.Region); err != nil {
pLogger.Errorw("could not join room", err)
_ = participant.Close(true)
return
return err
}
if err = r.roomStore.StoreParticipant(ctx, roomName, participant.ToProto()); err != nil {
pLogger.Errorw("could not store participant", err)
@@ -309,6 +308,7 @@ func (r *RoomManager) StartSession(ctx context.Context, roomName livekit.RoomNam
})
go r.rtcSessionWorker(room, participant, requestSource)
return nil
}
// create the actual room object, to be used on RTC node
@@ -388,6 +388,7 @@ func (r *RoomManager) rtcSessionWorker(room *rtc.Room, participant types.LocalPa
"roomID", room.Room.Sid,
)
_ = participant.Close(true)
requestSource.Close()
}()
defer rtc.Recover()
+1
View File
@@ -189,6 +189,7 @@ func (s *RTCService) ServeHTTP(w http.ResponseWriter, r *http.Request) {
// function exits when websocket terminates, it'll close the event reading off of response sink as well
defer func() {
pLogger.Infow("server closing WS connection", "connID", connId)
resSource.Close()
reqSink.Close()
close(done)
}()