Initial plumbing for metrics. (#2950)

* Initial plumbing for metrics.

This implements
- metrics received from participant.
- callback to room.
- room distributes it to all other participants (excluding the sending
  participant).
- other participants forward to client.
- counting metrics bytes in data channel stats

TODO:
  - recording/processing/batching
  - should recording/processing/batching happen on publisher side or
    subscriber side?
  - should metrics be echoed back to publisher?
  - grants to publish/subscribe metrics.

* mage generate

* clear OnMetrics on close

* - CanSubscribeMetrics permission.
- Echo back to sender.

* update deps

* No destination identities for metrics

* WIP

* use normalized timestamp for server injected timestamps

* compile

* debug log metrics batch

* correct comment

* add baseTime to wire

* protocol dep

* Scope metrics forwarding to only participants that a participant is
subscribed to.

Also remove the participant_metrics.go file as it was not doing anything
useful.

* update comment

* utils.ErrorIsOneOf

* couple of more utils.CloneProto
This commit is contained in:
Raja Subramanian
2024-09-19 11:42:31 +05:30
committed by GitHub
parent 4deaac2f3f
commit 7df6f86693
23 changed files with 488 additions and 55 deletions
+107 -25
View File
@@ -17,7 +17,6 @@ package rtc
import (
"context"
"fmt"
"io"
"os"
"slices"
"strconv"
@@ -27,7 +26,6 @@ import (
lru "github.com/hashicorp/golang-lru/v2"
"github.com/pion/rtcp"
"github.com/pion/sctp"
"github.com/pion/sdp/v3"
"github.com/pion/webrtc/v3"
"github.com/pkg/errors"
@@ -42,6 +40,7 @@ import (
"github.com/livekit/protocol/utils/guid"
"github.com/livekit/livekit-server/pkg/config"
"github.com/livekit/livekit-server/pkg/metric"
"github.com/livekit/livekit-server/pkg/routing"
"github.com/livekit/livekit-server/pkg/rtc/supervisor"
"github.com/livekit/livekit-server/pkg/rtc/transport"
@@ -109,6 +108,7 @@ func (p participantUpdateInfo) String() string {
// ---------------------------------------------------------------
type ParticipantParams struct {
BaseTime time.Time
Identity livekit.ParticipantIdentity
Name livekit.ParticipantName
SID livekit.ParticipantID
@@ -157,6 +157,7 @@ type ParticipantParams struct {
SyncStreams bool
ForwardStats *sfu.ForwardStats
DisableSenderReportPassThrough bool
MetricConfig metric.MetricConfig
}
type ParticipantImpl struct {
@@ -234,6 +235,7 @@ type ParticipantImpl struct {
onMigrateStateChange func(p types.LocalParticipant, migrateState types.MigrateState)
onParticipantUpdate func(types.LocalParticipant)
onDataPacket func(types.LocalParticipant, livekit.DataPacket_Kind, *livekit.DataPacket)
onMetrics func(types.LocalParticipant, *livekit.DataPacket)
migrateState atomic.Value // types.MigrateState
@@ -248,6 +250,8 @@ type ParticipantImpl struct {
tracksQuality map[livekit.TrackID]livekit.ConnectionQuality
metricTimestamper *metric.MetricTimestamper
// loggers for publisher and subscriber
pubLogger logger.Logger
subLogger logger.Logger
@@ -279,10 +283,16 @@ func NewParticipant(params ParticipantParams) (*ParticipantImpl, error) {
dataChannelStats: telemetry.NewBytesTrackStats(
telemetry.BytesTrackIDForParticipantID(telemetry.BytesTrackTypeData, params.SID),
params.SID,
params.Telemetry),
params.Telemetry,
),
tracksQuality: make(map[livekit.TrackID]livekit.ConnectionQuality),
pubLogger: params.Logger.WithComponent(sutils.ComponentPub),
subLogger: params.Logger.WithComponent(sutils.ComponentSub),
metricTimestamper: metric.NewMetricTimestamper(metric.MetricTimestamperParams{
Config: params.MetricConfig.Timestamper,
BaseTime: params.BaseTime,
Logger: params.Logger,
}),
pubLogger: params.Logger.WithComponent(sutils.ComponentPub),
subLogger: params.Logger.WithComponent(sutils.ComponentSub),
}
if !params.DisableSupervisor {
p.supervisor = supervisor.NewParticipantSupervisor(supervisor.ParticipantSupervisorParams{Logger: params.Logger})
@@ -749,6 +759,24 @@ func (p *ParticipantImpl) OnDataPacket(callback func(types.LocalParticipant, liv
p.lock.Unlock()
}
func (p *ParticipantImpl) getOnDataPacket() func(types.LocalParticipant, livekit.DataPacket_Kind, *livekit.DataPacket) {
p.lock.RLock()
defer p.lock.RUnlock()
return p.onDataPacket
}
func (p *ParticipantImpl) OnMetrics(callback func(types.LocalParticipant, *livekit.DataPacket)) {
p.lock.Lock()
p.onMetrics = callback
p.lock.Unlock()
}
func (p *ParticipantImpl) getOnMetrics() func(types.LocalParticipant, *livekit.DataPacket) {
p.lock.RLock()
defer p.lock.RUnlock()
return p.onMetrics
}
func (p *ParticipantImpl) OnClose(callback func(types.LocalParticipant)) {
p.lock.Lock()
p.onClose = callback
@@ -1201,6 +1229,10 @@ func (p *ParticipantImpl) Hidden() bool {
return p.grants.Load().Video.Hidden
}
func (p *ParticipantImpl) CanSubscribeMetrics() bool {
return p.grants.Load().Video.GetCanSubscribeMetrics()
}
func (p *ParticipantImpl) VerifySubscribeParticipantInfo(pID livekit.ParticipantID, version uint32) {
if !p.IsReady() {
// we have not sent a JoinResponse yet. metadata would be covered in JoinResponse
@@ -1333,6 +1365,10 @@ func (h SubscriberTransportHandler) OnInitialConnected() {
h.p.onSubscriberInitialConnected()
}
func (h SubscriberTransportHandler) OnDataSendError(err error) {
h.p.onDataSendError(err)
}
// ----------------------------------------------------------
type PrimaryTransportHandler struct {
@@ -1391,6 +1427,7 @@ func (p *ParticipantImpl) setupTransportManager() error {
Logger: p.params.Logger.WithComponent(sutils.ComponentTransport),
PublisherHandler: pth,
SubscriberHandler: sth,
DataChannelStats: p.dataChannelStats,
}
if p.params.SyncStreams && p.params.PlayoutDelay.GetEnabled() && p.params.ClientInfo.isFirefox() {
// we will disable playout delay for Firefox if the user is expecting
@@ -1601,7 +1638,9 @@ func (p *ParticipantImpl) onDataMessage(kind livekit.DataPacket_Kind, data []byt
dp.ParticipantIdentity = string(p.params.Identity)
}
shouldForward := false
shouldForwardData := true
shouldForwardMetrics := false
isPublisher := true
// only forward on user payloads
switch payload := dp.Value.(type) {
case *livekit.DataPacket_User:
@@ -1623,28 +1662,42 @@ func (p *ParticipantImpl) onDataMessage(kind livekit.DataPacket_Kind, data []byt
} else {
dp.DestinationIdentities = u.DestinationIdentities
}
shouldForward = true
case *livekit.DataPacket_SipDtmf:
shouldForward = true
case *livekit.DataPacket_Transcription:
if p.Kind() == livekit.ParticipantInfo_AGENT {
shouldForward = true
shouldForwardData = false
}
case *livekit.DataPacket_ChatMessage:
shouldForward = true
shouldForwardData = true
case *livekit.DataPacket_Metrics:
shouldForwardData = false
shouldForwardMetrics = true
isPublisher = false
// METRICS-TODO-QUESTIONS:
// 1. Should this record (and do processing/batching) metrics (i. e. publisher side) rather
// than forwarding and recording/processing/batching at every subscriber (in this case
// subscriber is defined as the other participants pushing this to edge client).
// 2. If the above is done, there could be two cadences, publisher side recording/processing/batching
// and pushing it to all subscribers on some cadence and subscribers have their own cadence of
// processing/batching and sending to edge clients.
p.metricTimestamper.Process(payload.Metrics)
default:
p.pubLogger.Warnw("received unsupported data packet", nil, "payload", payload)
}
if shouldForward {
p.lock.RLock()
onDataPacket := p.onDataPacket
p.lock.RUnlock()
if onDataPacket != nil {
if shouldForwardData {
if onDataPacket := p.getOnDataPacket(); onDataPacket != nil {
onDataPacket(p, kind, dp)
}
}
if shouldForwardMetrics {
if onMetrics := p.getOnMetrics(); onMetrics != nil {
onMetrics(p, dp)
}
}
p.setIsPublisher(true)
if isPublisher {
p.setIsPublisher(true)
}
}
func (p *ParticipantImpl) onICECandidate(c *webrtc.ICECandidate, target livekit.SignalTarget) error {
@@ -2194,6 +2247,7 @@ func (p *ParticipantImpl) addMigratedTrack(cid string, ti *livekit.TrackInfo) *M
func (p *ParticipantImpl) addMediaTrack(signalCid string, sdpCid string, ti *livekit.TrackInfo) *MediaTrack {
mt := NewMediaTrack(MediaTrackParams{
BaseTime: p.params.BaseTime,
SignalCid: signalCid,
SdpCid: sdpCid,
ParticipantID: p.params.SID,
@@ -2651,16 +2705,14 @@ func (p *ParticipantImpl) SendDataPacket(kind livekit.DataPacket_Kind, encoded [
return ErrDataChannelUnavailable
}
err := p.TransportManager.SendDataPacket(kind, encoded)
if err != nil {
if (errors.Is(err, sctp.ErrStreamClosed) || errors.Is(err, io.ErrClosedPipe)) && p.params.ReconnectOnDataChannelError {
p.params.Logger.Infow("issuing full reconnect on data channel error", "error", err)
p.IssueFullReconnect(types.ParticipantCloseReasonDataChannelError)
}
} else {
p.dataChannelStats.AddBytes(uint64(len(encoded)), true)
return p.TransportManager.SendDataPacket(kind, encoded)
}
func (p *ParticipantImpl) onDataSendError(err error) {
if p.params.ReconnectOnDataChannelError {
p.params.Logger.Infow("issuing full reconnect on data channel error", "error", err)
p.IssueFullReconnect(types.ParticipantCloseReasonDataChannelError)
}
return err
}
func (p *ParticipantImpl) setupEnabledCodecs(publishEnabledCodecs []*livekit.Codec, subscribeEnabledCodecs []*livekit.Codec, disabledCodecs *livekit.DisabledCodecs) {
@@ -2769,3 +2821,33 @@ func (p *ParticipantImpl) UpdateVideoTrack(update *livekit.UpdateLocalVideoTrack
p.pubLogger.Debugw("could not locate track", "trackID", update.TrackSid)
return errors.New("could not find track")
}
func (p *ParticipantImpl) HandleMetrics(senderParticipantID livekit.ParticipantID, metrics *livekit.MetricsBatch) error {
if p.State() != livekit.ParticipantInfo_ACTIVE {
return ErrDataChannelUnavailable
}
if !p.CanSubscribeMetrics() {
return ErrNoSubscribeMetricsPermission
}
if !p.SubscriptionManager.IsSubscribedTo(senderParticipantID) {
return nil
}
// METRICS-TODO: This is just forwarding. Will have to do more, including but not limited to
// 1. Filtering: subscriber metrics from self only should be sent to that participant.
// 2. Batching: could include re-mapping labels to consolidate multiple batches.
// 3. (Maybe) Time stamps: this is done on receive, TBD if required here also
dpData, err := proto.Marshal(&livekit.DataPacket{
Value: &livekit.DataPacket_Metrics{
Metrics: metrics,
},
})
if err != nil {
p.params.Logger.Errorw("failed to marshal data packet", err)
return err
}
return p.TransportManager.SendDataPacket(livekit.DataPacket_RELIABLE, dpData)
}