diff --git a/go.mod b/go.mod index 83a2a60e..31a9debe 100644 --- a/go.mod +++ b/go.mod @@ -23,7 +23,7 @@ require ( github.com/jxskiss/base62 v1.1.0 github.com/livekit/mageutil v0.0.0-20250511045019-0f1ff63f7731 github.com/livekit/mediatransportutil v0.0.0-20250519131108-fb90f5acfded - github.com/livekit/protocol v1.39.1-0.20250608060133-a3f43340ecd2 + github.com/livekit/protocol v1.39.1-0.20250609143527-8af5761cacc6 github.com/livekit/psrpc v0.6.1-0.20250511053145-465289d72c3c github.com/mackerelio/go-osstat v0.2.5 github.com/magefile/mage v1.15.0 diff --git a/go.sum b/go.sum index f7bd6f60..9a0218ee 100644 --- a/go.sum +++ b/go.sum @@ -169,8 +169,8 @@ github.com/livekit/mageutil v0.0.0-20250511045019-0f1ff63f7731 h1:9x+U2HGLrSw5AT github.com/livekit/mageutil v0.0.0-20250511045019-0f1ff63f7731/go.mod h1:Rs3MhFwutWhGwmY1VQsygw28z5bWcnEYmS1OG9OxjOQ= github.com/livekit/mediatransportutil v0.0.0-20250519131108-fb90f5acfded h1:ylZPdnlX1RW9Z15SD4mp87vT2D2shsk0hpLJwSPcq3g= github.com/livekit/mediatransportutil v0.0.0-20250519131108-fb90f5acfded/go.mod h1:mSNtYzSf6iY9xM3UX42VEI+STHvMgHmrYzEHPcdhB8A= -github.com/livekit/protocol v1.39.1-0.20250608060133-a3f43340ecd2 h1:o8ReFWr6ycwr6TaGLOFFT/6zZg4j7XS0zgmr0VLI7o8= -github.com/livekit/protocol v1.39.1-0.20250608060133-a3f43340ecd2/go.mod h1:6HPISM0bkTXTk9RIaQTCe0IDbomBPz7Jwp+N3w5sqL0= +github.com/livekit/protocol v1.39.1-0.20250609143527-8af5761cacc6 h1:aibQ28Ewev0otGVQEj/WWcovh+lVgwLu1DDTs1F54oU= +github.com/livekit/protocol v1.39.1-0.20250609143527-8af5761cacc6/go.mod h1:6HPISM0bkTXTk9RIaQTCe0IDbomBPz7Jwp+N3w5sqL0= github.com/livekit/psrpc v0.6.1-0.20250511053145-465289d72c3c h1:WwEr0YBejYbKzk8LSaO9h8h0G9MnE7shyDu8yXQWmEc= github.com/livekit/psrpc v0.6.1-0.20250511053145-465289d72c3c/go.mod h1:kmD+AZPkWu0MaXIMv57jhNlbiSZZ/Jx4bzlxBDVmJes= github.com/mackerelio/go-osstat v0.2.5 h1:+MqTbZUhoIt4m8qzkVoXUJg1EuifwlAJSk4Yl2GXh+o= diff --git a/pkg/rtc/mediatrack.go b/pkg/rtc/mediatrack.go index ee659950..bc0dad74 100644 --- a/pkg/rtc/mediatrack.go +++ b/pkg/rtc/mediatrack.go @@ -26,6 +26,7 @@ import ( "github.com/livekit/protocol/livekit" "github.com/livekit/protocol/logger" + "github.com/livekit/protocol/observability/roomobs" "github.com/livekit/livekit-server/pkg/config" "github.com/livekit/livekit-server/pkg/rtc/dynacast" @@ -74,6 +75,7 @@ type MediaTrackParams struct { VideoConfig config.VideoConfig Telemetry telemetry.TelemetryService Logger logger.Logger + Reporter roomobs.TrackReporter SimTracks map[uint32]SimulcastTrackInfo OnRTCP func([]rtcp.Packet) ForwardStats *sfu.ForwardStats @@ -328,6 +330,23 @@ func (t *MediaTrack) AddReceiver(receiver *webrtc.RTPReceiver, track sfu.TrackRe if priority == 0 || regressionTargetCodecReceived { key := telemetry.StatsKeyForTrack(livekit.StreamType_UPSTREAM, t.PublisherID(), t.ID(), ti.Source, ti.Type) t.params.Telemetry.TrackStats(key, stat) + + if cs, ok := telemetry.CondenseStat(stat); ok { + t.params.Reporter.Tx(func(tx roomobs.TrackTx) { + tx.ReportName(ti.Name) + tx.ReportKind(roomobs.TrackKindSub) + tx.ReportType(roomobs.TrackTypeFromProto(ti.Type)) + tx.ReportSource(roomobs.TrackSourceFromProto(ti.Source)) + tx.ReportMime(mime.NormalizeMimeType(ti.MimeType).ReporterType()) + tx.ReportLayer(roomobs.PackTrackLayer(ti.Height, ti.Width)) + tx.ReportDuration(uint16(cs.EndTime.Sub(cs.StartTime).Milliseconds())) + tx.ReportFrames(uint16(cs.Frames)) + tx.ReportRecvBytes(uint32(cs.Bytes)) + tx.ReportRecvPackets(cs.Packets) + tx.ReportPacketsLost(cs.PacketsLost) + tx.ReportScore(stat.Score) + }) + } } }) diff --git a/pkg/rtc/mediatracksubscriptions.go b/pkg/rtc/mediatracksubscriptions.go index 90209c83..d79d483b 100644 --- a/pkg/rtc/mediatracksubscriptions.go +++ b/pkg/rtc/mediatracksubscriptions.go @@ -27,6 +27,7 @@ import ( sutils "github.com/livekit/livekit-server/pkg/utils" "github.com/livekit/protocol/livekit" "github.com/livekit/protocol/logger" + "github.com/livekit/protocol/observability/roomobs" "github.com/livekit/livekit-server/pkg/rtc/types" "github.com/livekit/livekit-server/pkg/sfu" @@ -209,9 +210,28 @@ func (t *MediaTrackSubscriptions) AddSubscriber(sub types.LocalParticipant, wr * subTrack.SetPublisherMuted(t.params.MediaTrack.IsMuted()) }) + reporter := sub.GetReporter().WithTrack(trackID.String()) downTrack.OnStatsUpdate(func(_ *sfu.DownTrack, stat *livekit.AnalyticsStat) { key := telemetry.StatsKeyForTrack(livekit.StreamType_DOWNSTREAM, subscriberID, trackID, t.params.MediaTrack.Source(), t.params.MediaTrack.Kind()) t.params.Telemetry.TrackStats(key, stat) + + if cs, ok := telemetry.CondenseStat(stat); ok { + reporter.Tx(func(tx roomobs.TrackTx) { + ti := wr.TrackInfo() + tx.ReportName(ti.Name) + tx.ReportKind(roomobs.TrackKindPub) + tx.ReportType(roomobs.TrackTypeFromProto(ti.Type)) + tx.ReportSource(roomobs.TrackSourceFromProto(ti.Source)) + tx.ReportMime(mime.NormalizeMimeType(ti.MimeType).ReporterType()) + tx.ReportLayer(roomobs.PackTrackLayer(ti.Height, ti.Width)) + tx.ReportDuration(uint16(cs.EndTime.Sub(cs.StartTime).Milliseconds())) + tx.ReportFrames(uint16(cs.Frames)) + tx.ReportSendBytes(uint32(cs.Bytes)) + tx.ReportSendPackets(cs.Packets) + tx.ReportPacketsLost(cs.PacketsLost) + tx.ReportScore(stat.Score) + }) + } }) downTrack.OnMaxLayerChanged(func(dt *sfu.DownTrack, layer int32) { diff --git a/pkg/rtc/participant.go b/pkg/rtc/participant.go index d69002d9..38a17cf2 100644 --- a/pkg/rtc/participant.go +++ b/pkg/rtc/participant.go @@ -37,6 +37,8 @@ import ( "github.com/livekit/protocol/auth" "github.com/livekit/protocol/livekit" "github.com/livekit/protocol/logger" + "github.com/livekit/protocol/observability" + "github.com/livekit/protocol/observability/roomobs" "github.com/livekit/protocol/utils" "github.com/livekit/protocol/utils/guid" "github.com/livekit/protocol/utils/pointer" @@ -130,6 +132,8 @@ type ParticipantParams struct { SubscribeEnabledCodecs []*livekit.Codec Logger logger.Logger LoggerResolver logger.DeferredFieldResolver + Reporter roomobs.ParticipantSessionReporter + ReporterResolver roomobs.ParticipantReporterResolver SimTracks map[uint32]SimulcastTrackInfo Grants *auth.ClaimGrants InitialVersion uint32 @@ -191,7 +195,8 @@ type ParticipantImpl struct { sessionStartRecorded atomic.Bool lastActiveAt atomic.Pointer[time.Time] // when first connected - connectedAt time.Time + connectedAt time.Time + disconnectedAt atomic.Pointer[time.Time] // timer that's set when disconnect is detected on primary PC disconnectTimer *time.Timer migrationTimer *time.Timer @@ -303,6 +308,7 @@ func NewParticipant(params ParticipantParams) (*ParticipantImpl, error) { telemetry.BytesTrackIDForParticipantID(telemetry.BytesTrackTypeData, p.ID()), p.ID(), params.Telemetry, + params.Reporter, ) p.participantHelper.Store(params.ParticipantHelper) if !params.DisableSupervisor { @@ -323,6 +329,20 @@ func NewParticipant(params ParticipantParams) (*ParticipantImpl, error) { p.supervisor.OnPublicationError(p.onPublicationError) } + sessionTimer := observability.NewSessionTimer(p.params.SessionStartTime) + params.Reporter.RegisterFunc(func(ts time.Time, tx roomobs.ParticipantSessionTx) bool { + if dts := p.disconnectedAt.Load(); dts != nil { + ts = *dts + tx.ReportEndTime(ts) + } + + millis, mins := sessionTimer.Advance(ts) + tx.ReportDuration(uint16(millis)) + tx.ReportDurationMinutes(uint8(mins)) + + return !p.IsDisconnected() + }) + var err error // keep last participants and when updates were sent if p.updateCache, err = lru.New[livekit.ParticipantID, participantUpdateInfo](128); err != nil { @@ -355,6 +375,14 @@ func (p *ParticipantImpl) GetLoggerResolver() logger.DeferredFieldResolver { return p.params.LoggerResolver } +func (p *ParticipantImpl) GetReporter() roomobs.ParticipantSessionReporter { + return p.params.Reporter +} + +func (p *ParticipantImpl) GetReporterResolver() roomobs.ParticipantReporterResolver { + return p.params.ReporterResolver +} + func (p *ParticipantImpl) GetAdaptiveStream() bool { return p.params.AdaptiveStream } @@ -1804,6 +1832,7 @@ func (p *ParticipantImpl) updateState(state livekit.ParticipantInfo_State) { } if state == livekit.ParticipantInfo_DISCONNECTED && oldState == livekit.ParticipantInfo_ACTIVE { + p.disconnectedAt.Store(pointer.To(time.Now())) prometheus.RecordSessionDuration(int(p.ProtocolVersion()), time.Since(*p.lastActiveAt.Load())) } } @@ -2708,6 +2737,7 @@ func (p *ParticipantImpl) addMediaTrack(signalCid string, sdpCid string, ti *liv VideoConfig: p.params.VideoConfig, Telemetry: p.params.Telemetry, Logger: LoggerWithTrack(p.pubLogger, livekit.TrackID(ti.Sid), false), + Reporter: p.params.Reporter.WithTrack(ti.Sid), SubscriberConfig: p.params.Config.Subscriber, PLIThrottleConfig: p.params.PLIThrottleConfig, SimTracks: p.params.SimTracks, @@ -3345,6 +3375,7 @@ func (p *ParticipantImpl) MoveToRoom(params types.MoveToRoomParams) { p.params.Logger.Infow("move participant to new room", "newRoomName", params.RoomName, "newID", params.ParticipantID) p.params.LoggerResolver.Reset() + p.params.ReporterResolver.Reset() p.participantHelper.Store(params.Helper) p.SubscriptionManager.ClearAllSubscriptions() p.id.Store(params.ParticipantID) diff --git a/pkg/rtc/participant_internal_test.go b/pkg/rtc/participant_internal_test.go index e71fcba8..b6d1a1e1 100644 --- a/pkg/rtc/participant_internal_test.go +++ b/pkg/rtc/participant_internal_test.go @@ -31,6 +31,7 @@ import ( "github.com/livekit/protocol/auth" "github.com/livekit/protocol/livekit" "github.com/livekit/protocol/logger" + "github.com/livekit/protocol/observability/roomobs" lksdp "github.com/livekit/protocol/sdp" "github.com/livekit/protocol/utils" "github.com/livekit/protocol/utils/guid" @@ -703,6 +704,7 @@ func newParticipantForTestWithOpts(identity livekit.ParticipantIdentity, opts *p ClientConf: opts.clientConf, ClientInfo: ClientInfo{ClientInfo: opts.clientInfo}, Logger: LoggerWithParticipant(logger.GetLogger(), identity, sid, false), + Reporter: roomobs.NewNoopParticipantSessionReporter(), Telemetry: &telemetryfakes.FakeTelemetryService{}, VersionGenerator: utils.NewDefaultTimedVersionGenerator(), ParticipantHelper: &typesfakes.FakeLocalParticipantHelper{}, diff --git a/pkg/rtc/room.go b/pkg/rtc/room.go index fbfede4b..5269fc48 100644 --- a/pkg/rtc/room.go +++ b/pkg/rtc/room.go @@ -30,6 +30,7 @@ import ( "github.com/livekit/protocol/livekit" "github.com/livekit/protocol/logger" + "github.com/livekit/protocol/observability/roomobs" "github.com/livekit/protocol/rpc" "github.com/livekit/protocol/utils" "github.com/livekit/protocol/utils/guid" @@ -456,13 +457,16 @@ func (r *Room) Join(participant types.LocalParticipant, requestSource routing.Me // subscribe participant to existing published tracks r.subscribeToExistingTracks(p) + connectTime := time.Since(p.ConnectedAt()) meta := &livekit.AnalyticsClientMeta{ - ClientConnectTime: uint32(time.Since(p.ConnectedAt()).Milliseconds()), + ClientConnectTime: uint32(connectTime.Milliseconds()), } infos := p.GetICEConnectionInfo() + var connectionType roomobs.ConnectionType for _, info := range infos { if info.Type != types.ICEConnectionTypeUnknown { meta.ConnectionType = info.Type.String() + connectionType = info.Type.ReporterType() break } } @@ -473,6 +477,12 @@ func (r *Room) Join(participant types.LocalParticipant, requestSource routing.Me false, ) + participant.GetReporter().Tx(func(tx roomobs.ParticipantSessionTx) { + tx.ReportClientConnectTime(uint16(connectTime.Milliseconds())) + tx.ReportConnectResult(roomobs.ConnectionResultSuccess) + tx.ReportConnectionType(connectionType) + }) + fields := append( connectionDetailsFields(infos), "clientInfo", logger.Proto(sutils.ClientInfoWithoutAddress(p.GetClientInfo())), diff --git a/pkg/rtc/testutils.go b/pkg/rtc/testutils.go index 8231f02f..88893f18 100644 --- a/pkg/rtc/testutils.go +++ b/pkg/rtc/testutils.go @@ -17,6 +17,7 @@ package rtc import ( "github.com/livekit/protocol/livekit" "github.com/livekit/protocol/logger" + "github.com/livekit/protocol/observability/roomobs" "github.com/livekit/protocol/utils" "github.com/livekit/protocol/utils/guid" @@ -75,6 +76,7 @@ func NewMockParticipant(identity livekit.ParticipantIdentity, protocol types.Pro updateTrack() }) p.GetLoggerReturns(logger.GetLogger()) + p.GetReporterReturns(roomobs.NewNoopParticipantSessionReporter()) return p } diff --git a/pkg/rtc/types/ice.go b/pkg/rtc/types/ice.go index 27ea3f1d..fbcbc5a4 100644 --- a/pkg/rtc/types/ice.go +++ b/pkg/rtc/types/ice.go @@ -27,6 +27,7 @@ import ( "github.com/livekit/protocol/livekit" "github.com/livekit/protocol/logger" + "github.com/livekit/protocol/observability/roomobs" ) type ICEConnectionType int @@ -44,21 +45,32 @@ func (i ICEConnectionType) String() string { switch i { case ICEConnectionTypeUnknown: return "unknown" - case ICEConnectionTypeUDP: return "udp" - case ICEConnectionTypeTCP: return "tcp" - case ICEConnectionTypeTURN: return "turn" - default: return "unknown" } } +func (i ICEConnectionType) ReporterType() roomobs.ConnectionType { + switch i { + case ICEConnectionTypeUnknown: + return roomobs.ConnectionTypeUndefined + case ICEConnectionTypeUDP: + return roomobs.ConnectionTypeUDP + case ICEConnectionTypeTCP: + return roomobs.ConnectionTypeTCP + case ICEConnectionTypeTURN: + return roomobs.ConnectionTypeTurn + default: + return roomobs.ConnectionTypeUndefined + } +} + // -------------------------------------------- type ICECandidateExtended struct { @@ -83,6 +95,15 @@ func (i *ICEConnectionInfo) HasCandidates() bool { return len(i.Local) > 0 || len(i.Remote) > 0 } +func ICEConnectionInfosType(infos []*ICEConnectionInfo) ICEConnectionType { + for _, info := range infos { + if info.Type != ICEConnectionTypeUnknown { + return info.Type + } + } + return ICEConnectionTypeUnknown +} + // -------------------------------------------- type ICEConnectionDetails struct { diff --git a/pkg/rtc/types/interfaces.go b/pkg/rtc/types/interfaces.go index 571dc3c8..c9b909e6 100644 --- a/pkg/rtc/types/interfaces.go +++ b/pkg/rtc/types/interfaces.go @@ -24,6 +24,7 @@ import ( "github.com/livekit/protocol/auth" "github.com/livekit/protocol/livekit" "github.com/livekit/protocol/logger" + "github.com/livekit/protocol/observability/roomobs" "github.com/livekit/protocol/utils" "github.com/livekit/livekit-server/pkg/routing" @@ -342,6 +343,8 @@ type LocalParticipant interface { GetTrailer() []byte GetLogger() logger.Logger GetLoggerResolver() logger.DeferredFieldResolver + GetReporter() roomobs.ParticipantSessionReporter + GetReporterResolver() roomobs.ParticipantReporterResolver GetAdaptiveStream() bool ProtocolVersion() ProtocolVersion SupportsSyncStreamID() bool diff --git a/pkg/rtc/types/typesfakes/fake_local_participant.go b/pkg/rtc/types/typesfakes/fake_local_participant.go index 7cc24d5f..3126dc4c 100644 --- a/pkg/rtc/types/typesfakes/fake_local_participant.go +++ b/pkg/rtc/types/typesfakes/fake_local_participant.go @@ -13,6 +13,7 @@ import ( "github.com/livekit/protocol/auth" "github.com/livekit/protocol/livekit" "github.com/livekit/protocol/logger" + "github.com/livekit/protocol/observability/roomobs" "github.com/livekit/protocol/utils" "github.com/pion/rtcp" webrtc "github.com/pion/webrtc/v4" @@ -412,6 +413,26 @@ type FakeLocalParticipant struct { result1 string result2 error } + GetReporterStub func() roomobs.ParticipantSessionReporter + getReporterMutex sync.RWMutex + getReporterArgsForCall []struct { + } + getReporterReturns struct { + result1 roomobs.ParticipantSessionReporter + } + getReporterReturnsOnCall map[int]struct { + result1 roomobs.ParticipantSessionReporter + } + GetReporterResolverStub func() roomobs.ParticipantReporterResolver + getReporterResolverMutex sync.RWMutex + getReporterResolverArgsForCall []struct { + } + getReporterResolverReturns struct { + result1 roomobs.ParticipantReporterResolver + } + getReporterResolverReturnsOnCall map[int]struct { + result1 roomobs.ParticipantReporterResolver + } GetSubscribedParticipantsStub func() []livekit.ParticipantID getSubscribedParticipantsMutex sync.RWMutex getSubscribedParticipantsArgsForCall []struct { @@ -3312,6 +3333,112 @@ func (fake *FakeLocalParticipant) GetPublisherICESessionUfragReturnsOnCall(i int }{result1, result2} } +func (fake *FakeLocalParticipant) GetReporter() roomobs.ParticipantSessionReporter { + fake.getReporterMutex.Lock() + ret, specificReturn := fake.getReporterReturnsOnCall[len(fake.getReporterArgsForCall)] + fake.getReporterArgsForCall = append(fake.getReporterArgsForCall, struct { + }{}) + stub := fake.GetReporterStub + fakeReturns := fake.getReporterReturns + fake.recordInvocation("GetReporter", []interface{}{}) + fake.getReporterMutex.Unlock() + if stub != nil { + return stub() + } + if specificReturn { + return ret.result1 + } + return fakeReturns.result1 +} + +func (fake *FakeLocalParticipant) GetReporterCallCount() int { + fake.getReporterMutex.RLock() + defer fake.getReporterMutex.RUnlock() + return len(fake.getReporterArgsForCall) +} + +func (fake *FakeLocalParticipant) GetReporterCalls(stub func() roomobs.ParticipantSessionReporter) { + fake.getReporterMutex.Lock() + defer fake.getReporterMutex.Unlock() + fake.GetReporterStub = stub +} + +func (fake *FakeLocalParticipant) GetReporterReturns(result1 roomobs.ParticipantSessionReporter) { + fake.getReporterMutex.Lock() + defer fake.getReporterMutex.Unlock() + fake.GetReporterStub = nil + fake.getReporterReturns = struct { + result1 roomobs.ParticipantSessionReporter + }{result1} +} + +func (fake *FakeLocalParticipant) GetReporterReturnsOnCall(i int, result1 roomobs.ParticipantSessionReporter) { + fake.getReporterMutex.Lock() + defer fake.getReporterMutex.Unlock() + fake.GetReporterStub = nil + if fake.getReporterReturnsOnCall == nil { + fake.getReporterReturnsOnCall = make(map[int]struct { + result1 roomobs.ParticipantSessionReporter + }) + } + fake.getReporterReturnsOnCall[i] = struct { + result1 roomobs.ParticipantSessionReporter + }{result1} +} + +func (fake *FakeLocalParticipant) GetReporterResolver() roomobs.ParticipantReporterResolver { + fake.getReporterResolverMutex.Lock() + ret, specificReturn := fake.getReporterResolverReturnsOnCall[len(fake.getReporterResolverArgsForCall)] + fake.getReporterResolverArgsForCall = append(fake.getReporterResolverArgsForCall, struct { + }{}) + stub := fake.GetReporterResolverStub + fakeReturns := fake.getReporterResolverReturns + fake.recordInvocation("GetReporterResolver", []interface{}{}) + fake.getReporterResolverMutex.Unlock() + if stub != nil { + return stub() + } + if specificReturn { + return ret.result1 + } + return fakeReturns.result1 +} + +func (fake *FakeLocalParticipant) GetReporterResolverCallCount() int { + fake.getReporterResolverMutex.RLock() + defer fake.getReporterResolverMutex.RUnlock() + return len(fake.getReporterResolverArgsForCall) +} + +func (fake *FakeLocalParticipant) GetReporterResolverCalls(stub func() roomobs.ParticipantReporterResolver) { + fake.getReporterResolverMutex.Lock() + defer fake.getReporterResolverMutex.Unlock() + fake.GetReporterResolverStub = stub +} + +func (fake *FakeLocalParticipant) GetReporterResolverReturns(result1 roomobs.ParticipantReporterResolver) { + fake.getReporterResolverMutex.Lock() + defer fake.getReporterResolverMutex.Unlock() + fake.GetReporterResolverStub = nil + fake.getReporterResolverReturns = struct { + result1 roomobs.ParticipantReporterResolver + }{result1} +} + +func (fake *FakeLocalParticipant) GetReporterResolverReturnsOnCall(i int, result1 roomobs.ParticipantReporterResolver) { + fake.getReporterResolverMutex.Lock() + defer fake.getReporterResolverMutex.Unlock() + fake.GetReporterResolverStub = nil + if fake.getReporterResolverReturnsOnCall == nil { + fake.getReporterResolverReturnsOnCall = make(map[int]struct { + result1 roomobs.ParticipantReporterResolver + }) + } + fake.getReporterResolverReturnsOnCall[i] = struct { + result1 roomobs.ParticipantReporterResolver + }{result1} +} + func (fake *FakeLocalParticipant) GetSubscribedParticipants() []livekit.ParticipantID { fake.getSubscribedParticipantsMutex.Lock() ret, specificReturn := fake.getSubscribedParticipantsReturnsOnCall[len(fake.getSubscribedParticipantsArgsForCall)] @@ -8199,6 +8326,10 @@ func (fake *FakeLocalParticipant) Invocations() map[string][][]interface{} { defer fake.getPublishedTracksMutex.RUnlock() fake.getPublisherICESessionUfragMutex.RLock() defer fake.getPublisherICESessionUfragMutex.RUnlock() + fake.getReporterMutex.RLock() + defer fake.getReporterMutex.RUnlock() + fake.getReporterResolverMutex.RLock() + defer fake.getReporterResolverMutex.RUnlock() fake.getSubscribedParticipantsMutex.RLock() defer fake.getSubscribedParticipantsMutex.RUnlock() fake.getSubscribedTracksMutex.RLock() diff --git a/pkg/service/roommanager.go b/pkg/service/roommanager.go index 761f486a..ad49c20b 100644 --- a/pkg/service/roommanager.go +++ b/pkg/service/roommanager.go @@ -31,6 +31,8 @@ import ( "github.com/livekit/protocol/auth" "github.com/livekit/protocol/livekit" "github.com/livekit/protocol/logger" + "github.com/livekit/protocol/observability" + "github.com/livekit/protocol/observability/roomobs" "github.com/livekit/protocol/rpc" "github.com/livekit/protocol/utils" "github.com/livekit/protocol/utils/guid" @@ -73,6 +75,7 @@ type RoomManager struct { rtcRestServer rpc.RTCRestServer[livekit.NodeID] roomStore ObjectStore telemetry telemetry.TelemetryService + recorder observability.Reporter clientConfManager clientconfiguration.ClientConfigurationManager agentClient agent.Client agentStore AgentStore @@ -450,6 +453,7 @@ func (r *RoomManager) StartSession( Grants: pi.Grants, Reconnect: pi.Reconnect, Logger: pLogger, + Reporter: roomobs.NewNoopParticipantSessionReporter(), ClientConf: clientConf, ClientInfo: rtc.ClientInfo{ClientInfo: pi.Client}, Region: pi.Region, diff --git a/pkg/service/rtcservice.go b/pkg/service/rtcservice.go index ca077664..909463ed 100644 --- a/pkg/service/rtcservice.go +++ b/pkg/service/rtcservice.go @@ -470,6 +470,7 @@ func (s *RTCService) ServeHTTP(w http.ResponseWriter, r *http.Request) { pLogger.Debugw("sending participant update", "participantUpdate", m) case *livekit.SignalResponse_RoomMoved: resetLogger() + signalStats.Reset() roomName = livekit.RoomName(m.RoomMoved.GetRoom().GetName()) moveRoomID := livekit.RoomID(m.RoomMoved.GetRoom().GetSid()) if moveRoomID != "" { @@ -478,6 +479,8 @@ func (s *RTCService) ServeHTTP(w http.ResponseWriter, r *http.Request) { participantIdentity = livekit.ParticipantIdentity(m.RoomMoved.GetParticipant().GetIdentity()) pID = livekit.ParticipantID(m.RoomMoved.GetParticipant().GetSid()) resolveLogger(false) + signalStats.ResolveRoom(m.RoomMoved.GetRoom()) + signalStats.ResolveParticipant(m.RoomMoved.GetParticipant()) pLogger.Debugw("sending room moved", "roomMoved", m) } diff --git a/pkg/sfu/mime/mimetype.go b/pkg/sfu/mime/mimetype.go index 118a7bad..78f4cece 100644 --- a/pkg/sfu/mime/mimetype.go +++ b/pkg/sfu/mime/mimetype.go @@ -18,6 +18,8 @@ import ( "strings" "github.com/pion/webrtc/v4" + + "github.com/livekit/protocol/observability/roomobs" ) const ( @@ -187,6 +189,41 @@ func (m MimeType) String() string { return "MimeTypeUnknown" } +func (m MimeType) ReporterType() roomobs.MimeType { + switch m { + case MimeTypeUnknown: + return roomobs.MimeTypeUndefined + case MimeTypeH264: + return roomobs.MimeTypeVideoH264 + case MimeTypeH265: + return roomobs.MimeTypeVideoH265 + case MimeTypeOpus: + return roomobs.MimeTypeAudioOpus + case MimeTypeRED: + return roomobs.MimeTypeAudioRed + case MimeTypeVP8: + return roomobs.MimeTypeVideoVp8 + case MimeTypeVP9: + return roomobs.MimeTypeVideoVp9 + case MimeTypeAV1: + return roomobs.MimeTypeVideoAv1 + case MimeTypeG722: + return roomobs.MimeTypeAudioG722 + case MimeTypePCMU: + return roomobs.MimeTypeAudioPcmu + case MimeTypePCMA: + return roomobs.MimeTypeAudioPcma + case MimeTypeRTX: + return roomobs.MimeTypeVideoRtx + case MimeTypeFlexFEC: + return roomobs.MimeTypeVideoFlexfec + case MimeTypeULPFEC: + return roomobs.MimeTypeVideoUlpfec + } + + return roomobs.MimeTypeUndefined +} + func NormalizeMimeType(mime string) MimeType { switch { case strings.EqualFold(mime, webrtc.MimeTypeH264): diff --git a/pkg/telemetry/analyticsservice.go b/pkg/telemetry/analyticsservice.go index 57873acb..98b912ec 100644 --- a/pkg/telemetry/analyticsservice.go +++ b/pkg/telemetry/analyticsservice.go @@ -22,6 +22,7 @@ import ( "github.com/livekit/protocol/livekit" "github.com/livekit/protocol/logger" + "github.com/livekit/protocol/observability/roomobs" "github.com/livekit/protocol/rpc" "github.com/livekit/protocol/utils/guid" @@ -34,6 +35,7 @@ type AnalyticsService interface { SendStats(ctx context.Context, stats []*livekit.AnalyticsStat) SendEvent(ctx context.Context, events *livekit.AnalyticsEvent) SendNodeRoomStates(ctx context.Context, nodeRooms *livekit.AnalyticsNodeRooms) + RoomProjectReporter(ctx context.Context) roomobs.ProjectReporter } type analyticsService struct { @@ -95,3 +97,7 @@ func (a *analyticsService) SendNodeRoomStates(_ context.Context, nodeRooms *live logger.Errorw("failed to send node room states", err) } } + +func (a *analyticsService) RoomProjectReporter(_ context.Context) roomobs.ProjectReporter { + return roomobs.NewNoopProjectReporter() +} diff --git a/pkg/telemetry/signalanddatastats.go b/pkg/telemetry/signalanddatastats.go index 935fa4d8..f098e97d 100644 --- a/pkg/telemetry/signalanddatastats.go +++ b/pkg/telemetry/signalanddatastats.go @@ -24,6 +24,7 @@ import ( "go.uber.org/atomic" "github.com/livekit/protocol/livekit" + "github.com/livekit/protocol/observability/roomobs" "github.com/livekit/protocol/utils" ) @@ -55,16 +56,23 @@ type BytesTrackStats struct { totalSendBytes, totalRecvBytes atomic.Uint64 totalSendMessages, totalRecvMessages atomic.Uint32 telemetry TelemetryService + reporter roomobs.TrackReporter done core.Fuse } -func NewBytesTrackStats(trackID livekit.TrackID, pID livekit.ParticipantID, telemetry TelemetryService) *BytesTrackStats { +func NewBytesTrackStats( + trackID livekit.TrackID, + pID livekit.ParticipantID, + telemetry TelemetryService, + participantReporter roomobs.ParticipantSessionReporter, +) *BytesTrackStats { s := &BytesTrackStats{ trackID: trackID, pID: pID, telemetry: telemetry, + reporter: participantReporter.WithTrack(trackID.String()), } - go s.reporter() + go s.worker() return s } @@ -74,11 +82,23 @@ func (s *BytesTrackStats) AddBytes(bytes uint64, isSend bool) { s.sendMessages.Inc() s.totalSendBytes.Add(bytes) s.totalSendMessages.Inc() + + s.reporter.Tx(func(tx roomobs.TrackTx) { + tx.ReportType(roomobs.TrackTypeData) + tx.ReportSendBytes(uint32(bytes)) + tx.ReportSendPackets(1) + }) } else { s.recv.Add(bytes) s.recvMessages.Inc() s.totalRecvBytes.Add(bytes) s.totalRecvMessages.Inc() + + s.reporter.Tx(func(tx roomobs.TrackTx) { + tx.ReportType(roomobs.TrackTypeData) + tx.ReportRecvBytes(uint32(bytes)) + tx.ReportRecvPackets(1) + }) } } @@ -98,29 +118,31 @@ func (s *BytesTrackStats) Stop() { func (s *BytesTrackStats) report() { if recv := s.recv.Swap(0); recv > 0 { + packets := s.recvMessages.Swap(0) s.telemetry.TrackStats(StatsKeyForData(livekit.StreamType_UPSTREAM, s.pID, s.trackID), &livekit.AnalyticsStat{ Streams: []*livekit.AnalyticsStream{ { PrimaryBytes: recv, - PrimaryPackets: s.recvMessages.Swap(0), + PrimaryPackets: packets, }, }, }) } if send := s.send.Swap(0); send > 0 { + packets := s.sendMessages.Swap(0) s.telemetry.TrackStats(StatsKeyForData(livekit.StreamType_DOWNSTREAM, s.pID, s.trackID), &livekit.AnalyticsStat{ Streams: []*livekit.AnalyticsStream{ { PrimaryBytes: send, - PrimaryPackets: s.sendMessages.Swap(0), + PrimaryPackets: packets, }, }, }) } } -func (s *BytesTrackStats) reporter() { +func (s *BytesTrackStats) worker() { ticker := time.NewTicker(5 * time.Second) defer func() { ticker.Stop() @@ -143,17 +165,30 @@ type BytesSignalStats struct { BytesTrackStats ctx context.Context - mu sync.Mutex - ri *livekit.Room - pi *livekit.ParticipantInfo + participantResolver roomobs.ParticipantReporterResolver + trackResolver roomobs.KeyResolver + + mu sync.Mutex + ri *livekit.Room + pi *livekit.ParticipantInfo + stopped chan struct{} } -func NewBytesSignalStats(ctx context.Context, telemetry TelemetryService) *BytesSignalStats { +func NewBytesSignalStats( + ctx context.Context, + telemetry TelemetryService, +) *BytesSignalStats { + projectReporter := telemetry.RoomProjectReporter(ctx) + participantReporter, participantReporterResolver := roomobs.DeferredParticipantReporter(projectReporter) + trackReporter, trackReporterResolver := participantReporter.WithDeferredTrack() return &BytesSignalStats{ BytesTrackStats: BytesTrackStats{ telemetry: telemetry, + reporter: trackReporter, }, - ctx: ctx, + ctx: ctx, + participantResolver: participantReporterResolver, + trackResolver: trackReporterResolver, } } @@ -181,6 +216,22 @@ func (s *BytesSignalStats) ResolveParticipant(pi *livekit.ParticipantInfo) { } } +func (s *BytesSignalStats) Reset() { + s.mu.Lock() + defer s.mu.Unlock() + if s.stopped != nil { + s.done.Break() + <-s.stopped + s.stopped = nil + s.done = core.Fuse{} + } + s.ri = nil + s.pi = nil + + s.participantResolver.Reset() + s.trackResolver.Reset() +} + func (s *BytesSignalStats) maybeStart() { if s.ri == nil || s.pi == nil { return @@ -189,17 +240,27 @@ func (s *BytesSignalStats) maybeStart() { s.pID = livekit.ParticipantID(s.pi.Sid) s.trackID = BytesTrackIDForParticipantID(BytesTrackTypeSignal, s.pID) + s.participantResolver.Resolve( + livekit.RoomName(s.ri.Name), + livekit.RoomID(s.ri.Sid), + livekit.ParticipantIdentity(s.pi.Identity), + livekit.ParticipantID(s.pi.Sid), + ) + s.trackResolver.Resolve(string(s.trackID)) + s.telemetry.ParticipantJoined(s.ctx, s.ri, s.pi, nil, nil, false) - go s.reporter() + s.stopped = make(chan struct{}) + go s.worker() } -func (s *BytesSignalStats) reporter() { - s.BytesTrackStats.reporter() +func (s *BytesSignalStats) worker() { + s.BytesTrackStats.worker() s.telemetry.ParticipantLeft(s.ctx, s.ri, s.pi, false) + close(s.stopped) } // ----------------------------------------------------------------------- func BytesTrackIDForParticipantID(typ BytesTrackType, participantID livekit.ParticipantID) livekit.TrackID { - return livekit.TrackID(fmt.Sprintf("%s_%s%s", utils.TrackPrefix, string(typ), participantID)) + return livekit.TrackID(fmt.Sprintf("%s%s%s", utils.TrackPrefix, typ, participantID)) } diff --git a/pkg/telemetry/statsworker.go b/pkg/telemetry/statsworker.go index 0dec2c5c..c5fcbe6e 100644 --- a/pkg/telemetry/statsworker.go +++ b/pkg/telemetry/statsworker.go @@ -264,6 +264,39 @@ func coalesce(stats []*livekit.AnalyticsStat) *livekit.AnalyticsStat { return stat } +type CondensedStat struct { + StartTime time.Time + EndTime time.Time + Bytes uint64 + Packets uint32 + PacketsLost uint32 + Frames uint32 +} + +func CondenseStat(stat *livekit.AnalyticsStat) (ps CondensedStat, ok bool) { + if ok = isValid(stat); !ok { + return + } + + for _, stream := range stat.Streams { + startTime := stream.StartTime.AsTime() + endTime := stream.EndTime.AsTime() + if ps.StartTime.IsZero() || startTime.Before(ps.StartTime) { + ps.StartTime = startTime + } + if endTime.After(ps.EndTime) { + ps.EndTime = endTime + } + + ps.Bytes += stream.PrimaryBytes + ps.Packets += stream.PrimaryPackets + ps.PacketsLost += stream.PacketsLost + ps.Frames += stream.Frames + } + + return +} + func isValid(stat *livekit.AnalyticsStat) bool { for _, analyticsStream := range stat.Streams { if int32(analyticsStream.PrimaryPackets) < 0 || diff --git a/pkg/telemetry/telemetryfakes/fake_analytics_service.go b/pkg/telemetry/telemetryfakes/fake_analytics_service.go index 21b2bb6a..e321ba46 100644 --- a/pkg/telemetry/telemetryfakes/fake_analytics_service.go +++ b/pkg/telemetry/telemetryfakes/fake_analytics_service.go @@ -7,9 +7,21 @@ import ( "github.com/livekit/livekit-server/pkg/telemetry" "github.com/livekit/protocol/livekit" + "github.com/livekit/protocol/observability/roomobs" ) type FakeAnalyticsService struct { + RoomProjectReporterStub func(context.Context) roomobs.ProjectReporter + roomProjectReporterMutex sync.RWMutex + roomProjectReporterArgsForCall []struct { + arg1 context.Context + } + roomProjectReporterReturns struct { + result1 roomobs.ProjectReporter + } + roomProjectReporterReturnsOnCall map[int]struct { + result1 roomobs.ProjectReporter + } SendEventStub func(context.Context, *livekit.AnalyticsEvent) sendEventMutex sync.RWMutex sendEventArgsForCall []struct { @@ -32,6 +44,67 @@ type FakeAnalyticsService struct { invocationsMutex sync.RWMutex } +func (fake *FakeAnalyticsService) RoomProjectReporter(arg1 context.Context) roomobs.ProjectReporter { + fake.roomProjectReporterMutex.Lock() + ret, specificReturn := fake.roomProjectReporterReturnsOnCall[len(fake.roomProjectReporterArgsForCall)] + fake.roomProjectReporterArgsForCall = append(fake.roomProjectReporterArgsForCall, struct { + arg1 context.Context + }{arg1}) + stub := fake.RoomProjectReporterStub + fakeReturns := fake.roomProjectReporterReturns + fake.recordInvocation("RoomProjectReporter", []interface{}{arg1}) + fake.roomProjectReporterMutex.Unlock() + if stub != nil { + return stub(arg1) + } + if specificReturn { + return ret.result1 + } + return fakeReturns.result1 +} + +func (fake *FakeAnalyticsService) RoomProjectReporterCallCount() int { + fake.roomProjectReporterMutex.RLock() + defer fake.roomProjectReporterMutex.RUnlock() + return len(fake.roomProjectReporterArgsForCall) +} + +func (fake *FakeAnalyticsService) RoomProjectReporterCalls(stub func(context.Context) roomobs.ProjectReporter) { + fake.roomProjectReporterMutex.Lock() + defer fake.roomProjectReporterMutex.Unlock() + fake.RoomProjectReporterStub = stub +} + +func (fake *FakeAnalyticsService) RoomProjectReporterArgsForCall(i int) context.Context { + fake.roomProjectReporterMutex.RLock() + defer fake.roomProjectReporterMutex.RUnlock() + argsForCall := fake.roomProjectReporterArgsForCall[i] + return argsForCall.arg1 +} + +func (fake *FakeAnalyticsService) RoomProjectReporterReturns(result1 roomobs.ProjectReporter) { + fake.roomProjectReporterMutex.Lock() + defer fake.roomProjectReporterMutex.Unlock() + fake.RoomProjectReporterStub = nil + fake.roomProjectReporterReturns = struct { + result1 roomobs.ProjectReporter + }{result1} +} + +func (fake *FakeAnalyticsService) RoomProjectReporterReturnsOnCall(i int, result1 roomobs.ProjectReporter) { + fake.roomProjectReporterMutex.Lock() + defer fake.roomProjectReporterMutex.Unlock() + fake.RoomProjectReporterStub = nil + if fake.roomProjectReporterReturnsOnCall == nil { + fake.roomProjectReporterReturnsOnCall = make(map[int]struct { + result1 roomobs.ProjectReporter + }) + } + fake.roomProjectReporterReturnsOnCall[i] = struct { + result1 roomobs.ProjectReporter + }{result1} +} + func (fake *FakeAnalyticsService) SendEvent(arg1 context.Context, arg2 *livekit.AnalyticsEvent) { fake.sendEventMutex.Lock() fake.sendEventArgsForCall = append(fake.sendEventArgsForCall, struct { @@ -139,6 +212,8 @@ func (fake *FakeAnalyticsService) SendStatsArgsForCall(i int) (context.Context, func (fake *FakeAnalyticsService) Invocations() map[string][][]interface{} { fake.invocationsMutex.RLock() defer fake.invocationsMutex.RUnlock() + fake.roomProjectReporterMutex.RLock() + defer fake.roomProjectReporterMutex.RUnlock() fake.sendEventMutex.RLock() defer fake.sendEventMutex.RUnlock() fake.sendNodeRoomStatesMutex.RLock() diff --git a/pkg/telemetry/telemetryfakes/fake_telemetry_service.go b/pkg/telemetry/telemetryfakes/fake_telemetry_service.go index 627fc6eb..40f577ab 100644 --- a/pkg/telemetry/telemetryfakes/fake_telemetry_service.go +++ b/pkg/telemetry/telemetryfakes/fake_telemetry_service.go @@ -8,6 +8,7 @@ import ( "github.com/livekit/livekit-server/pkg/sfu/mime" "github.com/livekit/livekit-server/pkg/telemetry" "github.com/livekit/protocol/livekit" + "github.com/livekit/protocol/observability/roomobs" ) type FakeTelemetryService struct { @@ -130,6 +131,17 @@ type FakeTelemetryService struct { arg1 context.Context arg2 *livekit.Room } + RoomProjectReporterStub func(context.Context) roomobs.ProjectReporter + roomProjectReporterMutex sync.RWMutex + roomProjectReporterArgsForCall []struct { + arg1 context.Context + } + roomProjectReporterReturns struct { + result1 roomobs.ProjectReporter + } + roomProjectReporterReturnsOnCall map[int]struct { + result1 roomobs.ProjectReporter + } RoomStartedStub func(context.Context, *livekit.Room) roomStartedMutex sync.RWMutex roomStartedArgsForCall []struct { @@ -875,6 +887,67 @@ func (fake *FakeTelemetryService) RoomEndedArgsForCall(i int) (context.Context, return argsForCall.arg1, argsForCall.arg2 } +func (fake *FakeTelemetryService) RoomProjectReporter(arg1 context.Context) roomobs.ProjectReporter { + fake.roomProjectReporterMutex.Lock() + ret, specificReturn := fake.roomProjectReporterReturnsOnCall[len(fake.roomProjectReporterArgsForCall)] + fake.roomProjectReporterArgsForCall = append(fake.roomProjectReporterArgsForCall, struct { + arg1 context.Context + }{arg1}) + stub := fake.RoomProjectReporterStub + fakeReturns := fake.roomProjectReporterReturns + fake.recordInvocation("RoomProjectReporter", []interface{}{arg1}) + fake.roomProjectReporterMutex.Unlock() + if stub != nil { + return stub(arg1) + } + if specificReturn { + return ret.result1 + } + return fakeReturns.result1 +} + +func (fake *FakeTelemetryService) RoomProjectReporterCallCount() int { + fake.roomProjectReporterMutex.RLock() + defer fake.roomProjectReporterMutex.RUnlock() + return len(fake.roomProjectReporterArgsForCall) +} + +func (fake *FakeTelemetryService) RoomProjectReporterCalls(stub func(context.Context) roomobs.ProjectReporter) { + fake.roomProjectReporterMutex.Lock() + defer fake.roomProjectReporterMutex.Unlock() + fake.RoomProjectReporterStub = stub +} + +func (fake *FakeTelemetryService) RoomProjectReporterArgsForCall(i int) context.Context { + fake.roomProjectReporterMutex.RLock() + defer fake.roomProjectReporterMutex.RUnlock() + argsForCall := fake.roomProjectReporterArgsForCall[i] + return argsForCall.arg1 +} + +func (fake *FakeTelemetryService) RoomProjectReporterReturns(result1 roomobs.ProjectReporter) { + fake.roomProjectReporterMutex.Lock() + defer fake.roomProjectReporterMutex.Unlock() + fake.RoomProjectReporterStub = nil + fake.roomProjectReporterReturns = struct { + result1 roomobs.ProjectReporter + }{result1} +} + +func (fake *FakeTelemetryService) RoomProjectReporterReturnsOnCall(i int, result1 roomobs.ProjectReporter) { + fake.roomProjectReporterMutex.Lock() + defer fake.roomProjectReporterMutex.Unlock() + fake.RoomProjectReporterStub = nil + if fake.roomProjectReporterReturnsOnCall == nil { + fake.roomProjectReporterReturnsOnCall = make(map[int]struct { + result1 roomobs.ProjectReporter + }) + } + fake.roomProjectReporterReturnsOnCall[i] = struct { + result1 roomobs.ProjectReporter + }{result1} +} + func (fake *FakeTelemetryService) RoomStarted(arg1 context.Context, arg2 *livekit.Room) { fake.roomStartedMutex.Lock() fake.roomStartedArgsForCall = append(fake.roomStartedArgsForCall, struct { @@ -1575,6 +1648,8 @@ func (fake *FakeTelemetryService) Invocations() map[string][][]interface{} { defer fake.reportMutex.RUnlock() fake.roomEndedMutex.RLock() defer fake.roomEndedMutex.RUnlock() + fake.roomProjectReporterMutex.RLock() + defer fake.roomProjectReporterMutex.RUnlock() fake.roomStartedMutex.RLock() defer fake.roomStartedMutex.RUnlock() fake.sendEventMutex.RLock()