Analytics events + stats (#187)
* events * bump * update incoming stats * publisher stats * outgoing rtcp * stats * remove unnecessary struct * merge mediaTrack * put comment back
This commit is contained in:
+13
-5
@@ -240,6 +240,12 @@ func (t *MediaTrack) AddSubscriber(sub types.Participant) error {
|
||||
downTrack.OnBind(func() {
|
||||
go t.sendDownTrackBindingReports(sub)
|
||||
})
|
||||
downTrack.OnPacketSent(func(_ *sfu.DownTrack, size int) {
|
||||
t.params.Telemetry.OnDownstreamPacket(sub.ID(), size)
|
||||
})
|
||||
downTrack.OnRTCP(func(pkts []rtcp.Packet) {
|
||||
t.params.Telemetry.HandleRTCP(livekit.StreamType_DOWNSTREAM, sub.ID(), pkts)
|
||||
})
|
||||
|
||||
downTrack.OnCloseHandler(func() {
|
||||
go func() {
|
||||
@@ -247,7 +253,7 @@ func (t *MediaTrack) AddSubscriber(sub types.Participant) error {
|
||||
delete(t.subscribedTracks, sub.ID())
|
||||
t.lock.Unlock()
|
||||
|
||||
t.params.Telemetry.TrackUnsubscribed(sub.ID(), sub.Identity(), t.ToProto())
|
||||
t.params.Telemetry.TrackUnsubscribed(sub.ID(), t.ToProto())
|
||||
|
||||
// ignore if the subscribing sub is not connected
|
||||
if sub.SubscriberPC().ConnectionState() == webrtc.PeerConnectionStateClosed {
|
||||
@@ -297,7 +303,7 @@ func (t *MediaTrack) AddSubscriber(sub types.Participant) error {
|
||||
sub.Negotiate()
|
||||
}()
|
||||
|
||||
t.params.Telemetry.TrackSubscribed(sub.ID(), sub.Identity(), t.ToProto())
|
||||
t.params.Telemetry.TrackSubscribed(sub.ID(), t.ToProto())
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -378,18 +384,20 @@ func (t *MediaTrack) AddReceiver(receiver *webrtc.RTPReceiver, track *webrtc.Tra
|
||||
onclose := t.onClose
|
||||
t.lock.Unlock()
|
||||
t.RemoveAllSubscribers()
|
||||
t.params.Telemetry.TrackUnpublished(t.params.ParticipantID, t.params.ParticipantIdentity, t.ToProto(), uint32(track.SSRC()))
|
||||
t.params.Telemetry.TrackUnpublished(t.params.ParticipantID, t.ToProto(), uint32(track.SSRC()))
|
||||
if onclose != nil {
|
||||
onclose()
|
||||
}
|
||||
})
|
||||
t.params.Telemetry.TrackPublished(t.params.ParticipantID, t.params.ParticipantIdentity, t.ToProto(), buff)
|
||||
|
||||
t.params.Telemetry.TrackPublished(t.params.ParticipantID, t.ToProto())
|
||||
if t.Kind() == livekit.TrackType_AUDIO {
|
||||
t.buffer = buff
|
||||
}
|
||||
}
|
||||
|
||||
t.receiver.AddUpTrack(track, buff, t.shouldStartWithBestQuality())
|
||||
t.params.Telemetry.AddUpTrack(t.params.ParticipantID, buff)
|
||||
|
||||
atomic.AddUint32(&t.numUpTracks, 1)
|
||||
if atomic.LoadUint32(&t.numUpTracks) > 1 {
|
||||
t.simulcasted.TrySet(true)
|
||||
|
||||
@@ -65,7 +65,8 @@ func newPeerConnection(params TransportParams) (*webrtc.PeerConnection, *webrtc.
|
||||
se.DisableMediaEngineCopy(true)
|
||||
|
||||
ir := &interceptor.Registry{}
|
||||
if params.Telemetry != nil {
|
||||
// intercept pub -> SFU rtcp for analytics
|
||||
if params.Telemetry != nil && params.Target == livekit.SignalTarget_PUBLISHER {
|
||||
f := params.Telemetry.NewStatsInterceptorFactory(params.ParticipantID, params.ParticipantIdentity)
|
||||
ir.Add(f)
|
||||
}
|
||||
|
||||
@@ -1,8 +1,7 @@
|
||||
// Code generated by Wire. DO NOT EDIT.
|
||||
|
||||
//go:generate go run github.com/google/wire/cmd/wire
|
||||
//go:build !wireinject
|
||||
// +build !wireinject
|
||||
//+build !wireinject
|
||||
|
||||
package service
|
||||
|
||||
|
||||
@@ -489,12 +489,11 @@ func (b *Buffer) buildReceptionReport() rtcp.ReceptionReport {
|
||||
fracLost = uint8((lostInterval << 8) / expectedInterval)
|
||||
}
|
||||
if b.lastFractionLostToReport > fracLost {
|
||||
// If fractionlost from subscriber is bigger than sfu received, use it.
|
||||
// If fraction lost from subscriber is bigger than sfu received, use it.
|
||||
fracLost = b.lastFractionLostToReport
|
||||
}
|
||||
|
||||
var dlsr uint32
|
||||
|
||||
if b.lastSRRecv != 0 {
|
||||
delayMS := uint32((time.Now().UnixNano() - b.lastSRRecv) / 1e6)
|
||||
dlsr = (delayMS / 1e3) << 16
|
||||
|
||||
+24
-8
@@ -124,6 +124,7 @@ type DownTrack struct {
|
||||
bandwidthConstrainedMuted atomicBool
|
||||
|
||||
// RTCP callbacks
|
||||
onRTCP func([]rtcp.Packet)
|
||||
onREMB func(dt *DownTrack, remb *rtcp.ReceiverEstimatedMaximumBitrate)
|
||||
|
||||
// simulcast layer availability change callback
|
||||
@@ -133,7 +134,7 @@ type DownTrack struct {
|
||||
onSubscriptionChanged func(dt *DownTrack)
|
||||
|
||||
// packet sent callback
|
||||
onPacketSent func(dt *DownTrack, size int)
|
||||
onPacketSent []func(dt *DownTrack, size int)
|
||||
}
|
||||
|
||||
// NewDownTrack returns a DownTrack.
|
||||
@@ -588,6 +589,10 @@ func (d *DownTrack) OnBind(fn func()) {
|
||||
d.onBind = fn
|
||||
}
|
||||
|
||||
func (d *DownTrack) OnRTCP(fn func([]rtcp.Packet)) {
|
||||
d.onRTCP = fn
|
||||
}
|
||||
|
||||
func (d *DownTrack) OnREMB(fn func(dt *DownTrack, remb *rtcp.ReceiverEstimatedMaximumBitrate)) {
|
||||
d.onREMB = fn
|
||||
}
|
||||
@@ -611,7 +616,7 @@ func (d *DownTrack) OnSubscriptionChanged(fn func(dt *DownTrack)) {
|
||||
}
|
||||
|
||||
func (d *DownTrack) OnPacketSent(fn func(dt *DownTrack, size int)) {
|
||||
d.onPacketSent = fn
|
||||
d.onPacketSent = append(d.onPacketSent, fn)
|
||||
}
|
||||
|
||||
func (d *DownTrack) AdjustAllocation(availableChannelCapacity uint64) (uint64, uint64) {
|
||||
@@ -769,7 +774,6 @@ func (d *DownTrack) CreateSenderReport() *rtcp.SenderReport {
|
||||
diff = 0
|
||||
}
|
||||
octets, packets := d.getSRStats()
|
||||
|
||||
return &rtcp.SenderReport{
|
||||
SSRC: d.ssrc,
|
||||
NTPTime: uint64(nowNTP),
|
||||
@@ -898,8 +902,10 @@ func (d *DownTrack) writeSimpleRTP(extPkt *buffer.ExtPacket) error {
|
||||
}
|
||||
|
||||
_, err = d.writeStream.WriteRTP(&hdr, payload)
|
||||
if err == nil && d.onPacketSent != nil {
|
||||
d.onPacketSent(d, hdr.MarshalSize()+len(payload))
|
||||
if err == nil {
|
||||
for _, f := range d.onPacketSent {
|
||||
f(d, hdr.MarshalSize()+len(payload))
|
||||
}
|
||||
}
|
||||
|
||||
return err
|
||||
@@ -1052,8 +1058,10 @@ func (d *DownTrack) writeSimulcastRTP(extPkt *buffer.ExtPacket, layer int32) err
|
||||
}
|
||||
|
||||
_, err = d.writeStream.WriteRTP(&hdr, payload)
|
||||
if err == nil && d.onPacketSent != nil {
|
||||
d.onPacketSent(d, hdr.MarshalSize()+len(payload))
|
||||
if err == nil {
|
||||
for _, f := range d.onPacketSent {
|
||||
f(d, hdr.MarshalSize()+len(payload))
|
||||
}
|
||||
}
|
||||
|
||||
return err
|
||||
@@ -1142,7 +1150,8 @@ func (d *DownTrack) writeBlankFrameRTP() error {
|
||||
|
||||
func (d *DownTrack) handleRTCP(bytes []byte) {
|
||||
// LK-TODO - should probably handle RTCP even if muted
|
||||
if !d.enabled.get() {
|
||||
enabled := d.enabled.get()
|
||||
if !enabled && d.onRTCP == nil {
|
||||
return
|
||||
}
|
||||
|
||||
@@ -1151,6 +1160,13 @@ func (d *DownTrack) handleRTCP(bytes []byte) {
|
||||
Logger.Error(err, "Unmarshal rtcp receiver packets err")
|
||||
}
|
||||
|
||||
if d.onRTCP != nil {
|
||||
d.onRTCP(pkts)
|
||||
if !enabled {
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
var fwdPkts []rtcp.Packet
|
||||
pliOnce := true
|
||||
firOnce := true
|
||||
|
||||
+85
-25
@@ -7,6 +7,7 @@ import (
|
||||
"github.com/livekit/protocol/logger"
|
||||
livekit "github.com/livekit/protocol/proto"
|
||||
"github.com/livekit/protocol/webhook"
|
||||
"google.golang.org/protobuf/types/known/timestamppb"
|
||||
|
||||
"github.com/livekit/livekit-server/pkg/sfu/buffer"
|
||||
"github.com/livekit/livekit-server/pkg/telemetry/prometheus"
|
||||
@@ -20,7 +21,11 @@ func (t *TelemetryService) RoomStarted(ctx context.Context, room *livekit.Room)
|
||||
Room: room,
|
||||
})
|
||||
|
||||
// TODO: analytics service
|
||||
t.sendEvent(&livekit.AnalyticsEvent{
|
||||
Type: livekit.AnalyticsEventType_ROOM_CREATED,
|
||||
Timestamp: ×tamppb.Timestamp{Seconds: room.CreationTime},
|
||||
Room: room,
|
||||
})
|
||||
}
|
||||
|
||||
func (t *TelemetryService) RoomEnded(ctx context.Context, room *livekit.Room) {
|
||||
@@ -31,10 +36,18 @@ func (t *TelemetryService) RoomEnded(ctx context.Context, room *livekit.Room) {
|
||||
Room: room,
|
||||
})
|
||||
|
||||
// TODO: analytics service
|
||||
t.sendEvent(&livekit.AnalyticsEvent{
|
||||
Type: livekit.AnalyticsEventType_ROOM_ENDED,
|
||||
Timestamp: timestamppb.Now(),
|
||||
RoomSid: room.Sid,
|
||||
})
|
||||
}
|
||||
|
||||
func (t *TelemetryService) ParticipantJoined(ctx context.Context, room *livekit.Room, participant *livekit.ParticipantInfo) {
|
||||
t.Lock()
|
||||
t.workers[participant.Sid] = NewStatsWorker(t, room.Sid, participant.Sid)
|
||||
t.Unlock()
|
||||
|
||||
prometheus.AddParticipant()
|
||||
|
||||
t.notifyEvent(ctx, &livekit.WebhookEvent{
|
||||
@@ -43,7 +56,11 @@ func (t *TelemetryService) ParticipantJoined(ctx context.Context, room *livekit.
|
||||
Participant: participant,
|
||||
})
|
||||
|
||||
// TODO: analytics service
|
||||
t.sendEvent(&livekit.AnalyticsEvent{
|
||||
Type: livekit.AnalyticsEventType_PARTICIPANT_JOINED,
|
||||
Timestamp: timestamppb.Now(),
|
||||
Participant: participant,
|
||||
})
|
||||
}
|
||||
|
||||
func (t *TelemetryService) ParticipantLeft(ctx context.Context, room *livekit.Room, participant *livekit.ParticipantInfo) {
|
||||
@@ -62,46 +79,71 @@ func (t *TelemetryService) ParticipantLeft(ctx context.Context, room *livekit.Ro
|
||||
Participant: participant,
|
||||
})
|
||||
|
||||
// TODO: analytics service
|
||||
t.sendEvent(&livekit.AnalyticsEvent{
|
||||
Type: livekit.AnalyticsEventType_PARTICIPANT_LEFT,
|
||||
Timestamp: timestamppb.Now(),
|
||||
ParticipantId: participant.Sid,
|
||||
})
|
||||
}
|
||||
|
||||
func (t *TelemetryService) TrackPublished(participantID, identity string, track *livekit.TrackInfo, buff *buffer.Buffer) {
|
||||
t.Lock()
|
||||
if t.workers[participantID] == nil {
|
||||
t.workers[participantID] = NewStatsWorker(func(diff *buffer.Stats) {
|
||||
t.HandleIncomingRTP(participantID, identity, diff)
|
||||
})
|
||||
}
|
||||
t.workers[participantID].AddBuffer(buff)
|
||||
t.Unlock()
|
||||
|
||||
func (t *TelemetryService) TrackPublished(participantID string, track *livekit.TrackInfo) {
|
||||
prometheus.AddPublishedTrack(track.Type.String())
|
||||
|
||||
// TODO: analytics service
|
||||
t.sendEvent(&livekit.AnalyticsEvent{
|
||||
Type: livekit.AnalyticsEventType_TRACK_PUBLISHED,
|
||||
Timestamp: timestamppb.Now(),
|
||||
ParticipantId: participantID,
|
||||
Track: track,
|
||||
})
|
||||
}
|
||||
|
||||
func (t *TelemetryService) TrackUnpublished(participantID, identity string, track *livekit.TrackInfo, ssrc uint32) {
|
||||
func (t *TelemetryService) AddUpTrack(participantID string, buff *buffer.Buffer) {
|
||||
t.RLock()
|
||||
if w := t.workers[participantID]; w != nil {
|
||||
w := t.workers[participantID]
|
||||
t.RUnlock()
|
||||
if w != nil {
|
||||
w.AddBuffer(buff)
|
||||
}
|
||||
}
|
||||
|
||||
func (t *TelemetryService) TrackUnpublished(participantID string, track *livekit.TrackInfo, ssrc uint32) {
|
||||
t.RLock()
|
||||
w := t.workers[participantID]
|
||||
t.RUnlock()
|
||||
if w != nil {
|
||||
w.RemoveBuffer(ssrc)
|
||||
}
|
||||
t.RUnlock()
|
||||
|
||||
prometheus.SubPublishedTrack(track.Type.String())
|
||||
|
||||
// TODO: analytics service
|
||||
t.sendEvent(&livekit.AnalyticsEvent{
|
||||
Type: livekit.AnalyticsEventType_TRACK_UNPUBLISHED,
|
||||
Timestamp: timestamppb.Now(),
|
||||
ParticipantId: participantID,
|
||||
TrackId: track.Sid,
|
||||
})
|
||||
}
|
||||
|
||||
func (t *TelemetryService) TrackSubscribed(participantID, identity string, track *livekit.TrackInfo) {
|
||||
func (t *TelemetryService) TrackSubscribed(participantID string, track *livekit.TrackInfo) {
|
||||
prometheus.AddSubscribedTrack(track.Type.String())
|
||||
|
||||
// TODO: analytics service
|
||||
t.sendEvent(&livekit.AnalyticsEvent{
|
||||
Type: livekit.AnalyticsEventType_TRACK_SUBSCRIBED,
|
||||
Timestamp: timestamppb.Now(),
|
||||
ParticipantId: participantID,
|
||||
TrackId: track.Sid,
|
||||
})
|
||||
}
|
||||
|
||||
func (t *TelemetryService) TrackUnsubscribed(participantID, identity string, track *livekit.TrackInfo) {
|
||||
func (t *TelemetryService) TrackUnsubscribed(participantID string, track *livekit.TrackInfo) {
|
||||
prometheus.SubSubscribedTrack(track.Type.String())
|
||||
|
||||
// TODO: analytics service
|
||||
t.sendEvent(&livekit.AnalyticsEvent{
|
||||
Type: livekit.AnalyticsEventType_TRACK_UNSUBSCRIBED,
|
||||
Timestamp: timestamppb.Now(),
|
||||
ParticipantId: participantID,
|
||||
TrackId: track.Sid,
|
||||
})
|
||||
}
|
||||
|
||||
func (t *TelemetryService) RecordingStarted(ctx context.Context, recordingID string, req *livekit.StartRecordingRequest) {
|
||||
@@ -113,7 +155,11 @@ func (t *TelemetryService) RecordingStarted(ctx context.Context, recordingID str
|
||||
},
|
||||
})
|
||||
|
||||
// TODO: analytics service
|
||||
t.sendEvent(&livekit.AnalyticsEvent{
|
||||
Type: livekit.AnalyticsEventType_RECORDING_STARTED,
|
||||
Timestamp: timestamppb.Now(),
|
||||
RecordingId: recordingID,
|
||||
})
|
||||
}
|
||||
|
||||
func (t *TelemetryService) RecordingEnded(res *livekit.RecordingResult) {
|
||||
@@ -122,7 +168,11 @@ func (t *TelemetryService) RecordingEnded(res *livekit.RecordingResult) {
|
||||
RecordingResult: res,
|
||||
})
|
||||
|
||||
// TODO: analytics service
|
||||
t.sendEvent(&livekit.AnalyticsEvent{
|
||||
Type: livekit.AnalyticsEventType_RECORDING_ENDED,
|
||||
Timestamp: timestamppb.Now(),
|
||||
RecordingId: res.Id,
|
||||
})
|
||||
}
|
||||
|
||||
func (t *TelemetryService) notifyEvent(ctx context.Context, event *livekit.WebhookEvent) {
|
||||
@@ -136,3 +186,13 @@ func (t *TelemetryService) notifyEvent(ctx context.Context, event *livekit.Webho
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func (t *TelemetryService) sendEvent(event *livekit.AnalyticsEvent) {
|
||||
if t.analyticsEnabled {
|
||||
if err := t.events.Send(&livekit.AnalyticsEvents{
|
||||
Events: []*livekit.AnalyticsEvent{event},
|
||||
}); err != nil {
|
||||
logger.Errorw("failed to send event", err, "eventType", event.Type.String())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
package telemetry
|
||||
|
||||
import (
|
||||
livekit "github.com/livekit/protocol/proto"
|
||||
"github.com/pion/interceptor"
|
||||
"github.com/pion/rtcp"
|
||||
"github.com/pion/rtp"
|
||||
)
|
||||
|
||||
type StatsInterceptorFactory struct {
|
||||
@@ -28,29 +28,11 @@ type StatsInterceptor struct {
|
||||
identity string
|
||||
}
|
||||
|
||||
// BindRTCPReader lets you modify any incoming RTCP packets. It is called once per sender/receiver, however this might
|
||||
// change in the future. The returned method will be called once per packet batch.
|
||||
func (s *StatsInterceptor) BindRTCPReader(reader interceptor.RTCPReader) interceptor.RTCPReader {
|
||||
return interceptor.RTCPReaderFunc(func(bytes []byte, attributes interceptor.Attributes) (int, interceptor.Attributes, error) {
|
||||
s.t.HandleIncomingRTCP(s.participantID, s.identity, bytes)
|
||||
return reader.Read(bytes, attributes)
|
||||
})
|
||||
}
|
||||
|
||||
// BindRTCPWriter lets you modify any outgoing RTCP packets. It is called once per PeerConnection. The returned method
|
||||
// will be called once per packet batch.
|
||||
func (s *StatsInterceptor) BindRTCPWriter(writer interceptor.RTCPWriter) interceptor.RTCPWriter {
|
||||
return interceptor.RTCPWriterFunc(func(pkts []rtcp.Packet, attributes interceptor.Attributes) (int, error) {
|
||||
s.t.HandleOutgoingRTCP(s.participantID, s.identity, pkts)
|
||||
s.t.HandleRTCP(livekit.StreamType_UPSTREAM, s.participantID, pkts)
|
||||
return writer.Write(pkts, attributes)
|
||||
})
|
||||
}
|
||||
|
||||
// BindLocalStream lets you modify any outgoing RTP packets. It is called once for per LocalStream. The returned method
|
||||
// will be called once per rtp packet.
|
||||
func (s *StatsInterceptor) BindLocalStream(_ *interceptor.StreamInfo, writer interceptor.RTPWriter) interceptor.RTPWriter {
|
||||
return interceptor.RTPWriterFunc(func(header *rtp.Header, payload []byte, attributes interceptor.Attributes) (int, error) {
|
||||
s.t.HandleOutgoingRTP(s.participantID, s.identity, uint64(len(payload)))
|
||||
return writer.Write(header, payload, attributes)
|
||||
})
|
||||
}
|
||||
|
||||
@@ -75,15 +75,15 @@ func IncrementBytes(direction Direction, count uint64) {
|
||||
}
|
||||
}
|
||||
|
||||
func IncrementNack(direction Direction) {
|
||||
promNackTotal.WithLabelValues(string(direction)).Add(1)
|
||||
atomic.AddUint64(&atomicNackTotal, 1)
|
||||
}
|
||||
|
||||
func IncrementPLI(direction Direction) {
|
||||
promPliTotal.WithLabelValues(string(direction)).Add(1)
|
||||
}
|
||||
|
||||
func IncrementFIR(direction Direction) {
|
||||
promFirTotal.WithLabelValues(string(direction)).Add(1)
|
||||
func IncrementRTCP(direction Direction, nack, pli, fir int32) {
|
||||
if nack > 0 {
|
||||
promNackTotal.WithLabelValues(string(direction)).Add(float64(nack))
|
||||
atomic.AddUint64(&atomicNackTotal, uint64(nack))
|
||||
}
|
||||
if pli > 0 {
|
||||
promPliTotal.WithLabelValues(string(direction)).Add(float64(pli))
|
||||
}
|
||||
if fir > 0 {
|
||||
promFirTotal.WithLabelValues(string(direction)).Add(float64(fir))
|
||||
}
|
||||
}
|
||||
|
||||
+72
-39
@@ -5,10 +5,10 @@ import (
|
||||
|
||||
"github.com/gammazero/workerpool"
|
||||
"github.com/livekit/protocol/logger"
|
||||
livekit "github.com/livekit/protocol/proto"
|
||||
"github.com/livekit/protocol/webhook"
|
||||
"github.com/pion/rtcp"
|
||||
|
||||
"github.com/livekit/livekit-server/pkg/sfu/buffer"
|
||||
"github.com/livekit/livekit-server/pkg/telemetry/prometheus"
|
||||
)
|
||||
|
||||
@@ -19,6 +19,12 @@ type TelemetryService struct {
|
||||
sync.RWMutex
|
||||
// one worker per participant
|
||||
workers map[string]*StatsWorker
|
||||
|
||||
analyticsEnabled bool
|
||||
authToken string
|
||||
nodeID string
|
||||
events livekit.AnalyticsRecorderService_IngestEventsClient
|
||||
stats livekit.AnalyticsRecorderService_IngestStatsClient
|
||||
}
|
||||
|
||||
func NewTelemetryService(notifier webhook.Notifier) *TelemetryService {
|
||||
@@ -26,6 +32,10 @@ func NewTelemetryService(notifier webhook.Notifier) *TelemetryService {
|
||||
notifier: notifier,
|
||||
webhookPool: workerpool.New(1),
|
||||
workers: make(map[string]*StatsWorker),
|
||||
|
||||
analyticsEnabled: false, // TODO
|
||||
authToken: "",
|
||||
nodeID: "",
|
||||
}
|
||||
}
|
||||
|
||||
@@ -37,53 +47,76 @@ func (t *TelemetryService) NewStatsInterceptorFactory(participantID, identity st
|
||||
}
|
||||
}
|
||||
|
||||
func (t *TelemetryService) HandleIncomingRTP(participantID, identity string, diff *buffer.Stats) {
|
||||
prometheus.IncrementPackets(prometheus.Incoming, uint64(diff.PacketCount))
|
||||
prometheus.IncrementBytes(prometheus.Incoming, diff.TotalByte)
|
||||
|
||||
// TODO: analytics service
|
||||
// diff.LastExpected, diff.LastReceived, diff.Jitter, diff.LostRate
|
||||
func (t *TelemetryService) OnDownstreamPacket(participantID string, bytes int) {
|
||||
t.RLock()
|
||||
w := t.workers[participantID]
|
||||
t.RUnlock()
|
||||
if w != nil {
|
||||
w.OnDownstreamPacket(bytes)
|
||||
}
|
||||
}
|
||||
|
||||
func (t *TelemetryService) HandleIncomingRTCP(participantID, identity string, bytes []byte) {
|
||||
pkts, err := rtcp.Unmarshal(bytes)
|
||||
if err != nil {
|
||||
logger.Errorw("Interceptor failed to unmarshal rtcp packets", err)
|
||||
return
|
||||
}
|
||||
|
||||
func (t *TelemetryService) HandleRTCP(streamType livekit.StreamType, participantID string, pkts []rtcp.Packet) {
|
||||
stats := &livekit.AnalyticsStat{}
|
||||
for _, pkt := range pkts {
|
||||
switch pkt.(type) {
|
||||
switch pkt := pkt.(type) {
|
||||
case *rtcp.TransportLayerNack:
|
||||
prometheus.IncrementNack(prometheus.Incoming)
|
||||
stats.NackCount++
|
||||
case *rtcp.PictureLossIndication:
|
||||
prometheus.IncrementPLI(prometheus.Incoming)
|
||||
stats.PliCount++
|
||||
case *rtcp.FullIntraRequest:
|
||||
prometheus.IncrementFIR(prometheus.Incoming)
|
||||
stats.FirCount++
|
||||
case *rtcp.ReceiverReport:
|
||||
for _, rr := range pkt.Reports {
|
||||
if delay := uint64(rr.Delay); delay > stats.Delay {
|
||||
stats.Delay = delay
|
||||
}
|
||||
if jitter := float64(rr.Jitter); jitter > stats.Jitter {
|
||||
stats.Jitter = jitter
|
||||
}
|
||||
stats.PacketLost += uint64(rr.TotalLost)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// TODO: analytics service
|
||||
}
|
||||
|
||||
func (t *TelemetryService) HandleOutgoingRTP(participantID, identity string, pktLen uint64) {
|
||||
prometheus.IncrementPackets(prometheus.Outgoing, 1)
|
||||
prometheus.IncrementBytes(prometheus.Outgoing, pktLen)
|
||||
|
||||
// TODO: analytics service
|
||||
}
|
||||
|
||||
func (t *TelemetryService) HandleOutgoingRTCP(participantID, identity string, pkts []rtcp.Packet) {
|
||||
for _, pkt := range pkts {
|
||||
switch pkt.(type) {
|
||||
case *rtcp.TransportLayerNack:
|
||||
prometheus.IncrementNack(prometheus.Outgoing)
|
||||
case *rtcp.PictureLossIndication:
|
||||
prometheus.IncrementPLI(prometheus.Outgoing)
|
||||
case *rtcp.FullIntraRequest:
|
||||
prometheus.IncrementFIR(prometheus.Outgoing)
|
||||
}
|
||||
direction := prometheus.Incoming
|
||||
if streamType == livekit.StreamType_DOWNSTREAM {
|
||||
direction = prometheus.Outgoing
|
||||
}
|
||||
|
||||
// TODO: analytics service
|
||||
prometheus.IncrementRTCP(direction, stats.NackCount, stats.PliCount, stats.FirCount)
|
||||
|
||||
t.RLock()
|
||||
w := t.workers[participantID]
|
||||
t.RUnlock()
|
||||
if w != nil {
|
||||
w.OnRTCP(streamType, stats)
|
||||
}
|
||||
}
|
||||
|
||||
func (t *TelemetryService) Report(stats []*livekit.AnalyticsStat) {
|
||||
for _, stat := range stats {
|
||||
direction := prometheus.Incoming
|
||||
if stat.Kind == livekit.StreamType_DOWNSTREAM {
|
||||
direction = prometheus.Outgoing
|
||||
}
|
||||
|
||||
prometheus.IncrementPackets(direction, stat.TotalPackets)
|
||||
prometheus.IncrementBytes(direction, stat.TotalBytes)
|
||||
}
|
||||
|
||||
t.sendStats(stats)
|
||||
}
|
||||
|
||||
func (t *TelemetryService) sendStats(stats []*livekit.AnalyticsStat) {
|
||||
if t.analyticsEnabled {
|
||||
for _, stat := range stats {
|
||||
stat.AuthToken = t.authToken
|
||||
stat.Node = t.nodeID
|
||||
}
|
||||
|
||||
if err := t.stats.Send(&livekit.AnalyticsStats{Stats: stats}); err != nil {
|
||||
logger.Errorw("failed to send stats", err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+141
-44
@@ -4,25 +4,60 @@ import (
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
livekit "github.com/livekit/protocol/proto"
|
||||
"google.golang.org/protobuf/types/known/timestamppb"
|
||||
|
||||
"github.com/livekit/livekit-server/pkg/sfu/buffer"
|
||||
)
|
||||
|
||||
const updateFrequency = time.Second * 10
|
||||
|
||||
// StatsWorker handles incoming RTP statistics instead of the stream interceptor
|
||||
// StatsWorker handles participant stats
|
||||
type StatsWorker struct {
|
||||
t *TelemetryService
|
||||
roomID string
|
||||
participantID string
|
||||
|
||||
sync.RWMutex
|
||||
buffers map[uint32]*buffer.Buffer
|
||||
lastStats *buffer.Stats
|
||||
onUpdate func(diff *buffer.Stats)
|
||||
close chan struct{}
|
||||
buffers map[uint32]*buffer.Buffer
|
||||
drain map[uint32]bool
|
||||
|
||||
incoming *Stats
|
||||
outgoing *Stats
|
||||
|
||||
close chan struct{}
|
||||
}
|
||||
|
||||
func NewStatsWorker(onUpdate func(*buffer.Stats)) *StatsWorker {
|
||||
type Stats struct {
|
||||
sync.Mutex
|
||||
next *livekit.AnalyticsStat
|
||||
totalPackets uint32
|
||||
prevPackets uint32
|
||||
totalBytes uint64
|
||||
prevBytes uint64
|
||||
}
|
||||
|
||||
func NewStatsWorker(t *TelemetryService, roomID, participantID string) *StatsWorker {
|
||||
s := &StatsWorker{
|
||||
buffers: make(map[uint32]*buffer.Buffer),
|
||||
onUpdate: onUpdate,
|
||||
close: make(chan struct{}, 1),
|
||||
t: t,
|
||||
roomID: roomID,
|
||||
participantID: participantID,
|
||||
|
||||
buffers: make(map[uint32]*buffer.Buffer),
|
||||
drain: make(map[uint32]bool),
|
||||
|
||||
incoming: &Stats{next: &livekit.AnalyticsStat{
|
||||
Kind: livekit.StreamType_UPSTREAM,
|
||||
RoomId: roomID,
|
||||
ParticipantId: participantID,
|
||||
}},
|
||||
outgoing: &Stats{next: &livekit.AnalyticsStat{
|
||||
Kind: livekit.StreamType_DOWNSTREAM,
|
||||
RoomId: roomID,
|
||||
ParticipantId: participantID,
|
||||
}},
|
||||
|
||||
close: make(chan struct{}, 1),
|
||||
}
|
||||
go s.run()
|
||||
return s
|
||||
@@ -32,58 +67,120 @@ func (s *StatsWorker) run() {
|
||||
for {
|
||||
select {
|
||||
case <-s.close:
|
||||
// drain
|
||||
s.Update()
|
||||
return
|
||||
case <-time.After(updateFrequency):
|
||||
s.onUpdate(s.Calc())
|
||||
s.Update()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (s *StatsWorker) AddBuffer(buffer *buffer.Buffer) {
|
||||
s.Lock()
|
||||
defer s.Unlock()
|
||||
|
||||
s.buffers[buffer.GetMediaSSRC()] = buffer
|
||||
}
|
||||
|
||||
func (s *StatsWorker) OnDownstreamPacket(bytes int) {
|
||||
s.outgoing.Lock()
|
||||
defer s.outgoing.Unlock()
|
||||
|
||||
s.outgoing.totalPackets++
|
||||
s.outgoing.totalBytes += uint64(bytes)
|
||||
}
|
||||
|
||||
func (s *StatsWorker) OnRTCP(direction livekit.StreamType, stats *livekit.AnalyticsStat) {
|
||||
ds := s.incoming
|
||||
if direction == livekit.StreamType_DOWNSTREAM {
|
||||
ds = s.outgoing
|
||||
}
|
||||
|
||||
ds.Lock()
|
||||
defer ds.Unlock()
|
||||
|
||||
if stats.Delay > ds.next.Delay {
|
||||
ds.next.Delay = stats.Delay
|
||||
}
|
||||
if stats.Jitter > ds.next.Jitter {
|
||||
ds.next.Jitter = stats.Jitter
|
||||
}
|
||||
ds.next.PacketLost += stats.PacketLost
|
||||
ds.next.NackCount += stats.NackCount
|
||||
ds.next.PliCount += stats.PliCount
|
||||
ds.next.FirCount += stats.FirCount
|
||||
}
|
||||
|
||||
func (s *StatsWorker) Update() {
|
||||
var packetsIn uint32
|
||||
var bytesIn uint64
|
||||
|
||||
s.Lock()
|
||||
ts := timestamppb.Now()
|
||||
for _, buff := range s.buffers {
|
||||
stats := buff.GetStats()
|
||||
packetsIn += stats.PacketCount
|
||||
bytesIn += stats.TotalByte
|
||||
}
|
||||
|
||||
if len(s.drain) > 0 {
|
||||
for ssrc := range s.drain {
|
||||
delete(s.buffers, ssrc)
|
||||
}
|
||||
s.drain = make(map[uint32]bool)
|
||||
}
|
||||
s.Unlock()
|
||||
|
||||
s.incoming.Lock()
|
||||
s.incoming.totalPackets = packetsIn
|
||||
s.incoming.totalBytes = bytesIn
|
||||
s.incoming.Unlock()
|
||||
|
||||
stats := make([]*livekit.AnalyticsStat, 0, 2)
|
||||
upstream := s.update(s.incoming, ts)
|
||||
if upstream != nil {
|
||||
stats = append(stats, upstream)
|
||||
}
|
||||
downstream := s.update(s.outgoing, ts)
|
||||
if downstream != nil {
|
||||
stats = append(stats, downstream)
|
||||
}
|
||||
|
||||
s.t.Report(stats)
|
||||
}
|
||||
|
||||
func (s *StatsWorker) update(stats *Stats, ts *timestamppb.Timestamp) *livekit.AnalyticsStat {
|
||||
if stats.totalBytes == 0 {
|
||||
return nil
|
||||
}
|
||||
|
||||
stats.Lock()
|
||||
defer stats.Unlock()
|
||||
|
||||
next := stats.next
|
||||
stats.next = &livekit.AnalyticsStat{
|
||||
Kind: next.Kind,
|
||||
RoomId: s.roomID,
|
||||
ParticipantId: s.participantID,
|
||||
}
|
||||
|
||||
next.TimeStamp = ts
|
||||
next.TotalPackets = uint64(stats.totalPackets - stats.prevPackets)
|
||||
next.TotalBytes = stats.totalBytes - stats.prevBytes
|
||||
|
||||
stats.prevPackets = stats.totalPackets
|
||||
stats.prevBytes = stats.totalBytes
|
||||
|
||||
return next
|
||||
}
|
||||
|
||||
func (s *StatsWorker) RemoveBuffer(ssrc uint32) {
|
||||
s.Lock()
|
||||
delete(s.buffers, ssrc)
|
||||
s.drain[ssrc] = true
|
||||
s.Unlock()
|
||||
}
|
||||
|
||||
func (s *StatsWorker) Calc() *buffer.Stats {
|
||||
s.RLock()
|
||||
total := &buffer.Stats{}
|
||||
for _, buff := range s.buffers {
|
||||
stats := buff.GetStats()
|
||||
total.PacketCount += stats.PacketCount
|
||||
total.TotalByte += stats.TotalByte
|
||||
total.LastExpected += stats.LastExpected
|
||||
total.LastReceived += stats.LastReceived
|
||||
if stats.Jitter > total.Jitter {
|
||||
total.Jitter = stats.Jitter
|
||||
}
|
||||
}
|
||||
s.RUnlock()
|
||||
|
||||
var diff *buffer.Stats
|
||||
if s.lastStats != nil {
|
||||
diff = &buffer.Stats{
|
||||
LastExpected: total.LastExpected - s.lastStats.LastExpected,
|
||||
LastReceived: total.LastReceived - s.lastStats.LastReceived,
|
||||
PacketCount: total.PacketCount - s.lastStats.PacketCount,
|
||||
TotalByte: total.TotalByte - s.lastStats.TotalByte,
|
||||
Jitter: total.Jitter,
|
||||
}
|
||||
} else {
|
||||
diff = total
|
||||
}
|
||||
diff.LostRate = float32(diff.LastExpected-diff.LastReceived) / float32(diff.LastExpected)
|
||||
|
||||
s.lastStats = diff
|
||||
return diff
|
||||
}
|
||||
|
||||
func (s *StatsWorker) Close() {
|
||||
close(s.close)
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user