Fix missing participant updates race (#163)

* Fix faulty participant update buffering.

* Fix bug with broadcasting out of order

* dedicated participant update worker, without locks

* use tracker to drop duplicate/out of date messages

* additional lock around filter logic
This commit is contained in:
David Zhao
2021-10-31 15:20:46 -07:00
committed by GitHub
parent f3e916e2fe
commit 7442551ae5
12 changed files with 134 additions and 148 deletions
+1
View File
@@ -13,6 +13,7 @@ require (
github.com/google/subcommands v1.2.0 // indirect
github.com/google/wire v0.5.0
github.com/gorilla/websocket v1.4.2
github.com/hashicorp/golang-lru v0.5.4
github.com/jxskiss/base62 v0.0.0-20191017122030-4f11678b909b
github.com/livekit/protocol v0.9.11
github.com/magefile/mage v1.11.0
+2
View File
@@ -209,6 +209,8 @@ github.com/hashicorp/go-version v1.2.0/go.mod h1:fltr4n8CU8Ke44wwGCBoEymUuxUHl09
github.com/hashicorp/go.net v0.0.1/go.mod h1:hjKkEWcCURg++eb33jQU7oqQcI9XDCnUzHA0oac0k90=
github.com/hashicorp/golang-lru v0.5.0/go.mod h1:/m3WP610KZHVQ1SGc6re/UDhFvYD7pJ4Ao+sR/qLZy8=
github.com/hashicorp/golang-lru v0.5.1/go.mod h1:/m3WP610KZHVQ1SGc6re/UDhFvYD7pJ4Ao+sR/qLZy8=
github.com/hashicorp/golang-lru v0.5.4 h1:YDjusn29QI/Das2iO9M0BHnIbxPeyuCHsjMW+lJfyTc=
github.com/hashicorp/golang-lru v0.5.4/go.mod h1:iADmTwqILo4mZ8BN3D2Q6+9jd8WM5uGBxy+E8yxSoD4=
github.com/hashicorp/hcl v1.0.0/go.mod h1:E5yfLk+7swimpb2L/Alb/PJmXilQ/rhwaUYs4T20WEQ=
github.com/hashicorp/logutils v1.0.0/go.mod h1:QIAnNjmIWmVIIkWDTG1z5v++HQmx9WQRO+LraFDTW64=
github.com/hashicorp/mdns v1.0.0/go.mod h1:tL+uN++7HEJ6SQLQ2/p+z2pH24WQKWjBPkE0mNTz8vQ=
+1 -1
View File
@@ -135,7 +135,7 @@ func Test() error {
func TestAll() error {
mg.Deps(generateWire)
// "-v", "-race",
cmd := exec.Command("go", "test", "./...", "-count=1", "-timeout=3m")
cmd := exec.Command("go", "test", "./...", "-count=1", "-timeout=4m")
connectStd(cmd)
return cmd.Run()
}
+3 -3
View File
@@ -37,7 +37,7 @@ type MediaTrack struct {
codec webrtc.RTPCodecParameters
muted utils.AtomicFlag
numUpTracks uint32
simulcasted bool
simulcasted utils.AtomicFlag
// channel to send RTCP packets to the source
lock sync.RWMutex
@@ -349,7 +349,7 @@ func (t *MediaTrack) AddReceiver(receiver *webrtc.RTPReceiver, track *webrtc.Tra
t.receiver.AddUpTrack(track, buff, t.shouldStartWithBestQuality())
// when RID is set, track is simulcasted
// TODO: how does this work with FF, SSRC based simulcast?
t.simulcasted = track.RID() != ""
t.simulcasted.TrySet(track.RID() != "")
atomic.AddUint32(&t.numUpTracks, 1)
buff.Bind(receiver.GetParameters(), buffer.Options{
@@ -381,7 +381,7 @@ func (t *MediaTrack) RemoveAllSubscribers() {
func (t *MediaTrack) ToProto() *livekit.TrackInfo {
info := t.params.TrackInfo
info.Muted = t.IsMuted()
info.Simulcast = t.simulcasted
info.Simulcast = t.simulcasted.Get()
return info
}
+1 -1
View File
@@ -38,7 +38,7 @@ func TestTrackInfo(t *testing.T) {
require.Equal(t, ti.Simulcast, outInfo.Simulcast)
// make it simulcasted
mt.simulcasted = true
mt.simulcasted.TrySet(true)
require.True(t, mt.ToProto().Simulcast)
}
+35 -27
View File
@@ -8,6 +8,7 @@ import (
"sync/atomic"
"time"
lru "github.com/hashicorp/golang-lru"
"github.com/livekit/protocol/logger"
livekit "github.com/livekit/protocol/proto"
"github.com/livekit/protocol/utils"
@@ -44,16 +45,16 @@ type ParticipantParams struct {
}
type ParticipantImpl struct {
params ParticipantParams
id string
publisher *PCTransport
subscriber *PCTransport
isClosed utils.AtomicFlag
permission *livekit.ParticipantPermission
state atomic.Value // livekit.ParticipantInfo_State
updateAfterActive atomic.Value // bool
rtcpCh chan []rtcp.Packet
pliThrottle *pliThrottle
params ParticipantParams
id string
publisher *PCTransport
subscriber *PCTransport
isClosed utils.AtomicFlag
permission *livekit.ParticipantPermission
state atomic.Value // livekit.ParticipantInfo_State
rtcpCh chan []rtcp.Packet
pliThrottle *pliThrottle
updateCache *lru.Cache
// reliable and unreliable data channels
reliableDC *webrtc.DataChannel
@@ -77,8 +78,9 @@ type ParticipantImpl struct {
// client intended to publish, yet to be reconciled
pendingTracks map[string]*livekit.TrackInfo
lock sync.RWMutex
once sync.Once
lock sync.RWMutex
once sync.Once
updateLock sync.Mutex
// callbacks & handlers
onTrackPublished func(types.Participant, types.PublishedTrack)
@@ -103,9 +105,12 @@ func NewParticipant(params ParticipantParams) (*ParticipantImpl, error) {
connectedAt: time.Now(),
}
p.state.Store(livekit.ParticipantInfo_JOINING)
p.updateAfterActive.Store(false)
var err error
// keep last participants and when updates were sent
if p.updateCache, err = lru.New(32); err != nil {
return nil, err
}
p.publisher, err = NewPCTransport(TransportParams{
Target: livekit.SignalTarget_PUBLISHER,
Config: params.Config,
@@ -179,10 +184,6 @@ func (p *ParticipantImpl) State() livekit.ParticipantInfo_State {
return p.state.Load().(livekit.ParticipantInfo_State)
}
func (p *ParticipantImpl) UpdateAfterActive() bool {
return p.updateAfterActive.Load().(bool)
}
func (p *ParticipantImpl) ProtocolVersion() types.ProtocolVersion {
return p.params.ProtocolVersion
}
@@ -515,16 +516,22 @@ func (p *ParticipantImpl) SendJoinResponse(roomInfo *livekit.Room, otherParticip
})
}
func (p *ParticipantImpl) SendParticipantUpdate(participants []*livekit.ParticipantInfo) error {
participantsToUpdate := participants
if p.State() == livekit.ParticipantInfo_JOINING {
// have not fully joined, it will not know how to handle updates
// make a note so that Room could resend updates once fully joined
p.updateAfterActive.Store(true)
return nil
func (p *ParticipantImpl) SendParticipantUpdate(participantsToUpdate []*livekit.ParticipantInfo, updatedAt time.Time) error {
if len(participantsToUpdate) == 1 {
p.updateLock.Lock()
defer p.updateLock.Unlock()
pi := participantsToUpdate[0]
if val, ok := p.updateCache.Get(pi.Sid); ok {
if lastUpdatedAt, ok := val.(time.Time); ok {
// this is a message delivered out of order, a more recent version of the message had already been
// sent.
if lastUpdatedAt.After(updatedAt) {
return nil
}
}
}
p.updateCache.Add(pi.Sid, updatedAt)
}
p.updateAfterActive.Store(false)
return p.writeMessage(&livekit.SignalResponse{
Message: &livekit.SignalResponse_Update{
Update: &livekit.ParticipantUpdate{
@@ -854,7 +861,6 @@ func (p *ParticipantImpl) onMediaTrack(track *webrtc.TrackRemote, rtpReceiver *w
newTrack = true
}
p.lock.Unlock()
ssrc := uint32(track.SSRC())
p.pliThrottle.addTrack(ssrc, track.RID())
@@ -864,6 +870,8 @@ func (p *ParticipantImpl) onMediaTrack(track *webrtc.TrackRemote, rtpReceiver *w
_ = p.publisher.pc.WriteRTCP([]rtcp.Packet{&pkt})
})
}
p.lock.Unlock()
mt.AddReceiver(rtpReceiver, track, p.twcc)
if newTrack {
+25
View File
@@ -167,6 +167,31 @@ func TestTrackPublishing(t *testing.T) {
})
}
func TestOutOfOrderUpdates(t *testing.T) {
p := newParticipantForTest("test")
sink := p.GetResponseSink().(*routingfakes.FakeMessageSink)
pi := &livekit.ParticipantInfo{
Sid: "PA_test2",
Identity: "test2",
Metadata: "123",
}
earlierTs := time.Now()
laterTs := time.Now()
require.NoError(t, p.SendParticipantUpdate([]*livekit.ParticipantInfo{pi}, laterTs))
pi = &livekit.ParticipantInfo{
Sid: "PA_test2",
Identity: "test2",
Metadata: "456",
}
require.NoError(t, p.SendParticipantUpdate([]*livekit.ParticipantInfo{pi}, earlierTs))
// only sent once, and it's the earlier message
require.Equal(t, 1, sink.WriteMessageCallCount())
sent := sink.WriteMessageArgsForCall(0).(*livekit.SignalResponse)
require.Equal(t, "123", sent.GetUpdate().Participants[0].Metadata)
}
// after disconnection, things should continue to function and not panic
func TestDisconnectTiming(t *testing.T) {
t.Run("Negotiate doesn't panic after channel closed", func(t *testing.T) {
+52 -26
View File
@@ -8,9 +8,9 @@ import (
"time"
"github.com/go-logr/logr"
"github.com/livekit/livekit-server/pkg/routing"
"github.com/livekit/protocol/logger"
livekit "github.com/livekit/protocol/proto"
"github.com/livekit/protocol/utils"
"github.com/pion/ion-sfu/pkg/buffer"
"google.golang.org/protobuf/proto"
@@ -26,9 +26,9 @@ const (
)
type Room struct {
Room *livekit.Room
config WebRTCConfig
lock sync.RWMutex
Room *livekit.Room
config WebRTCConfig
lock sync.RWMutex
// map of identity -> Participant
participants map[string]types.Participant
participantOpts map[string]*ParticipantOptions
@@ -37,8 +37,9 @@ type Room struct {
// time the first participant joined the room
joinedAt atomic.Value
// time that the last participant left the room
leftAt atomic.Value
isClosed utils.AtomicFlag
leftAt atomic.Value
closed chan struct{}
closeOnce sync.Once
// for active speaker updates
audioConfig *config.AudioConfig
@@ -63,6 +64,7 @@ func NewRoom(room *livekit.Room, config WebRTCConfig, audioConfig *config.AudioC
participants: make(map[string]types.Participant),
participantOpts: make(map[string]*ParticipantOptions),
bufferFactory: buffer.NewBufferFactory(config.Receiver.packetBufferSize, logr.Logger{}),
closed: make(chan struct{}),
}
if r.Room.EmptyTimeout == 0 {
r.Room.EmptyTimeout = DefaultEmptyTimeout
@@ -138,7 +140,7 @@ func (r *Room) LastLeftAt() int64 {
}
func (r *Room) Join(participant types.Participant, opts *ParticipantOptions, iceServers []*livekit.ICEServer) error {
if r.isClosed.Get() {
if r.IsClosed() {
stats.PromServiceOperationCounter.WithLabelValues("participant_join", "error", "room_closed").Add(1)
return ErrRoomClosed
}
@@ -174,10 +176,6 @@ func (r *Room) Join(participant types.Participant, opts *ParticipantOptions, ice
state := p.State()
if state == livekit.ParticipantInfo_ACTIVE {
if p.UpdateAfterActive() {
_ = p.SendParticipantUpdate(ToProtoParticipants(r.GetParticipants()))
}
// subscribe participant to existing publishedTracks
r.subscribeToExistingTracks(p)
@@ -236,6 +234,24 @@ func (r *Room) Join(participant types.Participant, opts *ParticipantOptions, ice
return nil
}
func (r *Room) ResumeParticipant(p types.Participant, responseSink routing.MessageSink) error {
// close previous sink, and link to new one
if prevSink := p.GetResponseSink(); prevSink != nil {
prevSink.Close()
}
p.SetResponseSink(responseSink)
updates := ToProtoParticipants(r.GetParticipants())
if err := p.SendParticipantUpdate(updates, time.Now()); err != nil {
return err
}
if err := p.ICERestart(); err != nil {
return err
}
return nil
}
func (r *Room) RemoveParticipant(identity string) {
r.lock.Lock()
p, ok := r.participants[identity]
@@ -306,9 +322,18 @@ func (r *Room) UpdateSubscriptions(participant types.Participant, trackIds []str
return nil
}
func (r *Room) IsClosed() bool {
select {
case <-r.closed:
return true
default:
return false
}
}
// CloseIfEmpty closes the room if all participants had left, or it's still empty past timeout
func (r *Room) CloseIfEmpty() {
if r.isClosed.Get() {
if r.IsClosed() {
return
}
@@ -343,15 +368,15 @@ func (r *Room) CloseIfEmpty() {
}
func (r *Room) Close() {
if !r.isClosed.TrySet(true) {
return
}
logger.Infow("closing room", "roomID", r.Room.Sid, "room", r.Room.Name)
r.closeOnce.Do(func() {
close(r.closed)
logger.Infow("closing room", "roomID", r.Room.Sid, "room", r.Room.Name)
r.statsReporter.RoomEnded()
if r.onClose != nil {
r.onClose()
}
r.statsReporter.RoomEnded()
if r.onClose != nil {
r.onClose()
}
})
}
func (r *Room) GetIncomingStats() stats.PacketStats {
@@ -427,7 +452,6 @@ func (r *Room) onTrackPublished(participant types.Participant, track types.Publi
defer r.lock.RUnlock()
// subscribe all existing participants to this PublishedTrack
// this is the default behavior. in the future this could be more selective
for _, existingParticipant := range r.participants {
if existingParticipant == participant {
// skip publishing participant
@@ -533,11 +557,14 @@ func (r *Room) subscribeToExistingTracks(p types.Participant) {
// broadcast an update about participant p
func (r *Room) broadcastParticipantState(p types.Participant, skipSource bool) {
r.lock.Lock()
updatedAt := time.Now()
updates := ToProtoParticipants([]types.Participant{p})
r.lock.Unlock()
if p.Hidden() {
if !skipSource {
// send update only to hidden participant
updates := ToProtoParticipants([]types.Participant{p})
err := p.SendParticipantUpdate(updates)
err := p.SendParticipantUpdate(updates, updatedAt)
if err != nil {
logger.Errorw("could not send update to participant", err,
"participant", p.Identity(), "pID", p.ID())
@@ -546,7 +573,6 @@ func (r *Room) broadcastParticipantState(p types.Participant, skipSource bool) {
return
}
updates := ToProtoParticipants([]types.Participant{p})
participants := r.GetParticipants()
for _, op := range participants {
// skip itself && closed participants
@@ -554,7 +580,7 @@ func (r *Room) broadcastParticipantState(p types.Participant, skipSource bool) {
continue
}
err := op.SendParticipantUpdate(updates)
err := op.SendParticipantUpdate(updates, updatedAt)
if err != nil {
logger.Errorw("could not send update to participant", err,
"participant", p.Identity(), "pID", p.ID())
@@ -602,7 +628,7 @@ func (r *Room) audioUpdateWorker() {
lastActiveMap := make(map[string]*livekit.SpeakerInfo)
for {
if r.isClosed.Get() {
if r.IsClosed() {
return
}
+1 -2
View File
@@ -49,7 +49,7 @@ type Participant interface {
AddSubscriber(op Participant) (int, error)
RemoveSubscriber(peerId string)
SendJoinResponse(info *livekit.Room, otherParticipants []Participant, iceServers []*livekit.ICEServer) error
SendParticipantUpdate(participants []*livekit.ParticipantInfo) error
SendParticipantUpdate(participants []*livekit.ParticipantInfo, updatedAt time.Time) error
SendSpeakerUpdate(speakers []*livekit.SpeakerInfo) error
SendDataPacket(packet *livekit.DataPacket) error
SendRoomUpdate(room *livekit.Room) error
@@ -82,7 +82,6 @@ type Participant interface {
AddSubscribedTrack(participantId string, st SubscribedTrack)
RemoveSubscribedTrack(participantId string, st SubscribedTrack)
SubscriberPC() *webrtc.PeerConnection
UpdateAfterActive() bool
DebugInfo() map[string]interface{}
}
+10 -73
View File
@@ -336,10 +336,11 @@ type FakeParticipant struct {
sendJoinResponseReturnsOnCall map[int]struct {
result1 error
}
SendParticipantUpdateStub func([]*livekit.ParticipantInfo) error
SendParticipantUpdateStub func([]*livekit.ParticipantInfo, time.Time) error
sendParticipantUpdateMutex sync.RWMutex
sendParticipantUpdateArgsForCall []struct {
arg1 []*livekit.ParticipantInfo
arg2 time.Time
}
sendParticipantUpdateReturns struct {
result1 error
@@ -435,16 +436,6 @@ type FakeParticipant struct {
toProtoReturnsOnCall map[int]struct {
result1 *livekit.ParticipantInfo
}
UpdateAfterActiveStub func() bool
updateAfterActiveMutex sync.RWMutex
updateAfterActiveArgsForCall []struct {
}
updateAfterActiveReturns struct {
result1 bool
}
updateAfterActiveReturnsOnCall map[int]struct {
result1 bool
}
invocations map[string][][]interface{}
invocationsMutex sync.RWMutex
}
@@ -2206,7 +2197,7 @@ func (fake *FakeParticipant) SendJoinResponseReturnsOnCall(i int, result1 error)
}{result1}
}
func (fake *FakeParticipant) SendParticipantUpdate(arg1 []*livekit.ParticipantInfo) error {
func (fake *FakeParticipant) SendParticipantUpdate(arg1 []*livekit.ParticipantInfo, arg2 time.Time) error {
var arg1Copy []*livekit.ParticipantInfo
if arg1 != nil {
arg1Copy = make([]*livekit.ParticipantInfo, len(arg1))
@@ -2216,13 +2207,14 @@ func (fake *FakeParticipant) SendParticipantUpdate(arg1 []*livekit.ParticipantIn
ret, specificReturn := fake.sendParticipantUpdateReturnsOnCall[len(fake.sendParticipantUpdateArgsForCall)]
fake.sendParticipantUpdateArgsForCall = append(fake.sendParticipantUpdateArgsForCall, struct {
arg1 []*livekit.ParticipantInfo
}{arg1Copy})
arg2 time.Time
}{arg1Copy, arg2})
stub := fake.SendParticipantUpdateStub
fakeReturns := fake.sendParticipantUpdateReturns
fake.recordInvocation("SendParticipantUpdate", []interface{}{arg1Copy})
fake.recordInvocation("SendParticipantUpdate", []interface{}{arg1Copy, arg2})
fake.sendParticipantUpdateMutex.Unlock()
if stub != nil {
return stub(arg1)
return stub(arg1, arg2)
}
if specificReturn {
return ret.result1
@@ -2236,17 +2228,17 @@ func (fake *FakeParticipant) SendParticipantUpdateCallCount() int {
return len(fake.sendParticipantUpdateArgsForCall)
}
func (fake *FakeParticipant) SendParticipantUpdateCalls(stub func([]*livekit.ParticipantInfo) error) {
func (fake *FakeParticipant) SendParticipantUpdateCalls(stub func([]*livekit.ParticipantInfo, time.Time) error) {
fake.sendParticipantUpdateMutex.Lock()
defer fake.sendParticipantUpdateMutex.Unlock()
fake.SendParticipantUpdateStub = stub
}
func (fake *FakeParticipant) SendParticipantUpdateArgsForCall(i int) []*livekit.ParticipantInfo {
func (fake *FakeParticipant) SendParticipantUpdateArgsForCall(i int) ([]*livekit.ParticipantInfo, time.Time) {
fake.sendParticipantUpdateMutex.RLock()
defer fake.sendParticipantUpdateMutex.RUnlock()
argsForCall := fake.sendParticipantUpdateArgsForCall[i]
return argsForCall.arg1
return argsForCall.arg1, argsForCall.arg2
}
func (fake *FakeParticipant) SendParticipantUpdateReturns(result1 error) {
@@ -2765,59 +2757,6 @@ func (fake *FakeParticipant) ToProtoReturnsOnCall(i int, result1 *livekit.Partic
}{result1}
}
func (fake *FakeParticipant) UpdateAfterActive() bool {
fake.updateAfterActiveMutex.Lock()
ret, specificReturn := fake.updateAfterActiveReturnsOnCall[len(fake.updateAfterActiveArgsForCall)]
fake.updateAfterActiveArgsForCall = append(fake.updateAfterActiveArgsForCall, struct {
}{})
stub := fake.UpdateAfterActiveStub
fakeReturns := fake.updateAfterActiveReturns
fake.recordInvocation("UpdateAfterActive", []interface{}{})
fake.updateAfterActiveMutex.Unlock()
if stub != nil {
return stub()
}
if specificReturn {
return ret.result1
}
return fakeReturns.result1
}
func (fake *FakeParticipant) UpdateAfterActiveCallCount() int {
fake.updateAfterActiveMutex.RLock()
defer fake.updateAfterActiveMutex.RUnlock()
return len(fake.updateAfterActiveArgsForCall)
}
func (fake *FakeParticipant) UpdateAfterActiveCalls(stub func() bool) {
fake.updateAfterActiveMutex.Lock()
defer fake.updateAfterActiveMutex.Unlock()
fake.UpdateAfterActiveStub = stub
}
func (fake *FakeParticipant) UpdateAfterActiveReturns(result1 bool) {
fake.updateAfterActiveMutex.Lock()
defer fake.updateAfterActiveMutex.Unlock()
fake.UpdateAfterActiveStub = nil
fake.updateAfterActiveReturns = struct {
result1 bool
}{result1}
}
func (fake *FakeParticipant) UpdateAfterActiveReturnsOnCall(i int, result1 bool) {
fake.updateAfterActiveMutex.Lock()
defer fake.updateAfterActiveMutex.Unlock()
fake.UpdateAfterActiveStub = nil
if fake.updateAfterActiveReturnsOnCall == nil {
fake.updateAfterActiveReturnsOnCall = make(map[int]struct {
result1 bool
})
}
fake.updateAfterActiveReturnsOnCall[i] = struct {
result1 bool
}{result1}
}
func (fake *FakeParticipant) Invocations() map[string][][]interface{} {
fake.invocationsMutex.RLock()
defer fake.invocationsMutex.RUnlock()
@@ -2917,8 +2856,6 @@ func (fake *FakeParticipant) Invocations() map[string][][]interface{} {
defer fake.subscriberPCMutex.RUnlock()
fake.toProtoMutex.RLock()
defer fake.toProtoMutex.RUnlock()
fake.updateAfterActiveMutex.RLock()
defer fake.updateAfterActiveMutex.RUnlock()
copiedInvocations := map[string][][]interface{}{}
for key, value := range fake.invocations {
copiedInvocations[key] = value
+2 -14
View File
@@ -186,20 +186,8 @@ func (r *LocalRoomManager) StartSession(ctx context.Context, roomName string, pi
"nodeID", r.currentNode.Id,
"participant", pi.Identity,
)
// close previous sink, and link to new one
prevSink := participant.GetResponseSink()
if prevSink != nil {
prevSink.Close()
}
participant.SetResponseSink(responseSink)
if err := participant.SendParticipantUpdate(rtc.ToProtoParticipants(room.GetParticipants())); err != nil {
logger.Warnw("failed to send participant update", err,
"participant", pi.Identity)
}
if err := participant.ICERestart(); err != nil {
logger.Warnw("could not restart ICE", err,
if err = room.ResumeParticipant(participant, responseSink); err != nil {
logger.Warnw("could not resume participant", err,
"participant", pi.Identity)
}
return
+1 -1
View File
@@ -1,3 +1,3 @@
package version
const Version = "0.13.6"
const Version = "0.13.7-SNAPSHOT"