Telemetry refactor (#172)

* telemetry refactor

* fix imports

* update protocol
This commit is contained in:
David Colburn
2021-11-08 20:00:34 -06:00
committed by GitHub
parent 8344466629
commit 289ebd32ff
25 changed files with 597 additions and 511 deletions
+139
View File
@@ -0,0 +1,139 @@
package telemetry
import (
"context"
"time"
"github.com/livekit/protocol/logger"
livekit "github.com/livekit/protocol/proto"
"github.com/livekit/protocol/webhook"
"github.com/livekit/livekit-server/pkg/telemetry/prometheus"
)
func (s *TelemetryService) RoomStarted(ctx context.Context, room *livekit.Room) {
s.pool.Submit(prometheus.RoomStarted)
s.notifyEvent(ctx, &livekit.WebhookEvent{
Event: webhook.EventRoomStarted,
Room: room,
})
// TODO: analytics service
}
func (s *TelemetryService) RoomEnded(ctx context.Context, room *livekit.Room) {
s.pool.Submit(func() {
prometheus.RoomEnded(time.Unix(room.CreationTime, 0))
})
s.notifyEvent(ctx, &livekit.WebhookEvent{
Event: webhook.EventRoomFinished,
Room: room,
})
// TODO: analytics service
}
func (s *TelemetryService) ParticipantJoined(ctx context.Context, room *livekit.Room, participant *livekit.ParticipantInfo) {
s.pool.Submit(prometheus.AddParticipant)
s.notifyEvent(ctx, &livekit.WebhookEvent{
Event: webhook.EventParticipantJoined,
Room: room,
Participant: participant,
})
// TODO: analytics service
}
func (s *TelemetryService) ParticipantLeft(ctx context.Context, room *livekit.Room, participant *livekit.ParticipantInfo) {
s.pool.Submit(prometheus.SubParticipant)
s.notifyEvent(ctx, &livekit.WebhookEvent{
Event: webhook.EventParticipantLeft,
Room: room,
Participant: participant,
})
// TODO: analytics service
}
func (s *TelemetryService) PublishedTrack(SID, identity string, track *livekit.TrackInfo) {
s.pool.Submit(func() {
prometheus.AddPublishedTrack(track.Type.String())
})
// TODO: analytics service
}
func (s *TelemetryService) UnpublishedTrack(SID, identity string, track *livekit.TrackInfo) {
s.pool.Submit(func() {
prometheus.SubPublishedTrack(track.Type.String())
})
// TODO: analytics service
}
func (s *TelemetryService) SubscribedTrack(SID, identity string, track *livekit.TrackInfo) {
s.pool.Submit(func() {
prometheus.AddSubscribedTrack(track.Type.String())
})
// TODO: analytics service
}
func (s *TelemetryService) UnsubscribedTrack(SID, identity string, track *livekit.TrackInfo) {
s.pool.Submit(func() {
prometheus.SubSubscribedTrack(track.Type.String())
})
// TODO: analytics service
}
func (s *TelemetryService) RecordingStarted(ctx context.Context, recordingID string, req *livekit.StartRecordingRequest) {
logger.Debugw("recording started", "recordingID", recordingID)
s.notifyEvent(ctx, &livekit.WebhookEvent{
Event: webhook.EventRecordingStarted,
RecordingInfo: &livekit.RecordingInfo{
Id: recordingID,
Request: req,
},
})
// TODO: analytics service
}
func (s *TelemetryService) RecordingEnded(res *livekit.RecordingResult) {
// log results
values := []interface{}{"recordingID", res.Id}
if res.Error != "" {
values = append(values, "error", res.Error)
} else {
values = append(values, "duration", time.Duration(res.Duration*1e9))
if res.DownloadUrl != "" {
values = append(values, "url", res.DownloadUrl)
}
}
logger.Debugw("recording ended", values...)
s.notifyEvent(context.Background(), &livekit.WebhookEvent{
Event: webhook.EventRecordingFinished,
RecordingResult: res,
})
// TODO: analytics service
}
func (s *TelemetryService) notifyEvent(ctx context.Context, event *livekit.WebhookEvent) {
if s.notifier == nil {
return
}
s.pool.Submit(func() {
if err := s.notifier.Notify(ctx, event); err != nil {
logger.Warnw("failed to notify webhook", err, "event", event.Event)
}
})
}
+86
View File
@@ -0,0 +1,86 @@
package prometheus
import (
"sync/atomic"
"time"
livekit "github.com/livekit/protocol/proto"
"github.com/prometheus/client_golang/prometheus"
)
const livekitNamespace = "livekit"
var (
MessageCounter = prometheus.NewCounterVec(
prometheus.CounterOpts{
Namespace: livekitNamespace,
Subsystem: "node",
Name: "messages",
},
[]string{"type", "status"},
)
ServiceOperationCounter = prometheus.NewCounterVec(
prometheus.CounterOpts{
Namespace: livekitNamespace,
Subsystem: "node",
Name: "service_operation",
},
[]string{"type", "status", "error_type"},
)
)
func init() {
prometheus.MustRegister(MessageCounter)
prometheus.MustRegister(ServiceOperationCounter)
initPacketStats()
initRoomStats()
}
func UpdateCurrentNodeStats(nodeStats *livekit.NodeStats) error {
updatedAtPrevious := nodeStats.UpdatedAt
nodeStats.UpdatedAt = time.Now().Unix()
secondsSinceLastUpdate := nodeStats.UpdatedAt - updatedAtPrevious
err := updateCurrentNodeSystemStats(nodeStats)
updateCurrentNodeRoomStats(nodeStats)
updateCurrentNodePacketStats(nodeStats, secondsSinceLastUpdate)
return err
}
func updateCurrentNodeRoomStats(nodeStats *livekit.NodeStats) {
nodeStats.NumClients = atomic.LoadInt32(&atomicParticipantTotal)
nodeStats.NumRooms = atomic.LoadInt32(&atomicRoomTotal)
nodeStats.NumTracksIn = atomic.LoadInt32(&atomicTrackPublishedTotal)
nodeStats.NumTracksOut = atomic.LoadInt32(&atomicTrackSubscribedTotal)
}
func updateCurrentNodePacketStats(nodeStats *livekit.NodeStats, secondsSinceLastUpdate int64) {
if secondsSinceLastUpdate == 0 {
return
}
bytesInPrevious := nodeStats.BytesIn
bytesOutPrevious := nodeStats.BytesOut
packetsInPrevious := nodeStats.PacketsIn
packetsOutPrevious := nodeStats.PacketsOut
nackTotalPrevious := nodeStats.NackTotal
nodeStats.BytesIn = atomic.LoadUint64(&atomicBytesIn)
nodeStats.BytesOut = atomic.LoadUint64(&atomicBytesOut)
nodeStats.PacketsIn = atomic.LoadUint64(&atomicPacketsIn)
nodeStats.PacketsOut = atomic.LoadUint64(&atomicPacketsOut)
nodeStats.NackTotal = atomic.LoadUint64(&atomicNackTotal)
nodeStats.BytesInPerSec = perSec(bytesInPrevious, nodeStats.BytesIn, secondsSinceLastUpdate)
nodeStats.BytesOutPerSec = perSec(bytesOutPrevious, nodeStats.BytesOut, secondsSinceLastUpdate)
nodeStats.PacketsInPerSec = perSec(packetsInPrevious, nodeStats.PacketsIn, secondsSinceLastUpdate)
nodeStats.PacketsOutPerSec = perSec(packetsOutPrevious, nodeStats.PacketsOut, secondsSinceLastUpdate)
nodeStats.NackPerSec = perSec(nackTotalPrevious, nodeStats.NackTotal, secondsSinceLastUpdate)
}
func perSec(prev, curr uint64, secs int64) float32 {
return float32(curr-prev) / float32(secs)
}
+28
View File
@@ -0,0 +1,28 @@
//go:build linux
// +build linux
package prometheus
import (
linuxproc "github.com/c9s/goprocinfo/linux"
livekit "github.com/livekit/protocol/proto"
)
func updateCurrentNodeSystemStats(nodeStats *livekit.NodeStats) error {
cpuInfo, err := linuxproc.ReadCPUInfo("/proc/cpuinfo")
if err != nil {
return err
}
loadAvg, err := linuxproc.ReadLoadAvg("/proc/loadavg")
if err != nil {
return err
}
nodeStats.NumCpus = uint32(cpuInfo.NumCPU())
nodeStats.LoadAvgLast1Min = float32(loadAvg.Last1Min)
nodeStats.LoadAvgLast5Min = float32(loadAvg.Last5Min)
nodeStats.LoadAvgLast15Min = float32(loadAvg.Last15Min)
return nil
}
+10
View File
@@ -0,0 +1,10 @@
//go:build !linux
// +build !linux
package prometheus
import livekit "github.com/livekit/protocol/proto"
func updateCurrentNodeSystemStats(nodeStats *livekit.NodeStats) error {
return nil
}
+83
View File
@@ -0,0 +1,83 @@
package prometheus
import (
"sync/atomic"
"github.com/prometheus/client_golang/prometheus"
)
type Direction string
const (
Incoming Direction = "incoming"
Outgoing Direction = "outgoing"
)
var (
atomicBytesIn uint64
atomicBytesOut uint64
atomicPacketsIn uint64
atomicPacketsOut uint64
atomicNackTotal uint64
promPacketLabels = []string{"direction"}
promPacketTotal = prometheus.NewCounterVec(prometheus.CounterOpts{
Namespace: livekitNamespace,
Subsystem: "packet",
Name: "total",
}, promPacketLabels)
promPacketBytes = prometheus.NewCounterVec(prometheus.CounterOpts{
Namespace: livekitNamespace,
Subsystem: "packet",
Name: "bytes",
}, promPacketLabels)
promNackTotal = prometheus.NewCounterVec(prometheus.CounterOpts{
Namespace: livekitNamespace,
Subsystem: "nack",
Name: "total",
}, promPacketLabels)
promPliTotal = prometheus.NewCounterVec(prometheus.CounterOpts{
Namespace: livekitNamespace,
Subsystem: "pli",
Name: "total",
}, promPacketLabels)
promFirTotal = prometheus.NewCounterVec(prometheus.CounterOpts{
Namespace: livekitNamespace,
Subsystem: "fir",
Name: "total",
}, promPacketLabels)
)
func initPacketStats() {
prometheus.MustRegister(promPacketTotal)
prometheus.MustRegister(promPacketBytes)
prometheus.MustRegister(promNackTotal)
prometheus.MustRegister(promPliTotal)
prometheus.MustRegister(promFirTotal)
}
func IncrementPackets(direction Direction, pktLen uint64) {
promPacketTotal.WithLabelValues(string(direction)).Add(1)
promPacketBytes.WithLabelValues(string(direction)).Add(float64(pktLen))
if direction == Incoming {
atomic.AddUint64(&atomicPacketsIn, 1)
atomic.AddUint64(&atomicBytesIn, pktLen)
} else {
atomic.AddUint64(&atomicPacketsOut, 1)
atomic.AddUint64(&atomicBytesOut, pktLen)
}
}
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)
}
+95
View File
@@ -0,0 +1,95 @@
package prometheus
import (
"sync/atomic"
"time"
"github.com/prometheus/client_golang/prometheus"
)
var (
atomicRoomTotal int32
atomicParticipantTotal int32
atomicTrackPublishedTotal int32
atomicTrackSubscribedTotal int32
promRoomTotal = prometheus.NewGauge(prometheus.GaugeOpts{
Namespace: livekitNamespace,
Subsystem: "room",
Name: "total",
})
promRoomDuration = prometheus.NewHistogram(prometheus.HistogramOpts{
Namespace: livekitNamespace,
Subsystem: "room",
Name: "duration_seconds",
Buckets: []float64{
5, 10, 60, 5 * 60, 10 * 60, 30 * 60, 60 * 60, 2 * 60 * 60, 5 * 60 * 60, 10 * 60 * 60,
},
})
promParticipantTotal = prometheus.NewGauge(prometheus.GaugeOpts{
Namespace: livekitNamespace,
Subsystem: "participant",
Name: "total",
})
promTrackPublishedTotal = prometheus.NewGaugeVec(prometheus.GaugeOpts{
Namespace: livekitNamespace,
Subsystem: "track",
Name: "published_total",
}, []string{"kind"})
promTrackSubscribedTotal = prometheus.NewGaugeVec(prometheus.GaugeOpts{
Namespace: livekitNamespace,
Subsystem: "track",
Name: "subscribed_total",
}, []string{"kind"})
)
func initRoomStats() {
prometheus.MustRegister(promRoomTotal)
prometheus.MustRegister(promRoomDuration)
prometheus.MustRegister(promParticipantTotal)
prometheus.MustRegister(promTrackPublishedTotal)
prometheus.MustRegister(promTrackSubscribedTotal)
}
func RoomStarted() {
promRoomTotal.Add(1)
atomic.AddInt32(&atomicRoomTotal, 1)
}
func RoomEnded(startedAt time.Time) {
if !startedAt.IsZero() {
promRoomDuration.Observe(float64(time.Now().Sub(startedAt)) / float64(time.Second))
}
promRoomTotal.Sub(1)
atomic.AddInt32(&atomicRoomTotal, -1)
}
func AddParticipant() {
promParticipantTotal.Add(1)
atomic.AddInt32(&atomicParticipantTotal, 1)
}
func SubParticipant() {
promParticipantTotal.Sub(1)
atomic.AddInt32(&atomicParticipantTotal, -1)
}
func AddPublishedTrack(kind string) {
promTrackPublishedTotal.WithLabelValues(kind).Add(1)
atomic.AddInt32(&atomicTrackPublishedTotal, 1)
}
func SubPublishedTrack(kind string) {
promTrackPublishedTotal.WithLabelValues(kind).Sub(1)
atomic.AddInt32(&atomicTrackPublishedTotal, -1)
}
func AddSubscribedTrack(kind string) {
promTrackSubscribedTotal.WithLabelValues(kind).Add(1)
atomic.AddInt32(&atomicTrackSubscribedTotal, 1)
}
func SubSubscribedTrack(kind string) {
promTrackSubscribedTotal.WithLabelValues(kind).Sub(1)
atomic.AddInt32(&atomicTrackSubscribedTotal, -1)
}
+91
View File
@@ -0,0 +1,91 @@
package telemetry
import (
"github.com/gammazero/workerpool"
"github.com/livekit/protocol/webhook"
"github.com/pion/interceptor"
"github.com/pion/rtcp"
"github.com/pion/rtp"
)
type TelemetryService struct {
notifier webhook.Notifier
pool *workerpool.WorkerPool
}
func NewTelemetryService(notifier webhook.Notifier) *TelemetryService {
return &TelemetryService{
notifier: notifier,
pool: workerpool.New(10),
}
}
type StatsInterceptorFactory struct {
t *TelemetryService
participantID string
identity string
}
func (s *TelemetryService) NewStatsInterceptorFactory(participantID, identity string) *StatsInterceptorFactory {
return &StatsInterceptorFactory{
t: s,
participantID: participantID,
identity: identity,
}
}
func (f *StatsInterceptorFactory) NewInterceptor(id string) (interceptor.Interceptor, error) {
return &StatsInterceptor{
t: f.t,
participantID: f.participantID,
identity: f.identity,
}, nil
}
type StatsInterceptor struct {
interceptor.NoOp
t *TelemetryService
participantID string
identity string
}
// --- Incoming ---
// 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)
})
}
// BindRemoteStream lets you modify any incoming RTP packets. It is called once for per RemoteStream. The returned method
// will be called once per rtp packet.
func (s *StatsInterceptor) BindRemoteStream(_ *interceptor.StreamInfo, reader interceptor.RTPReader) interceptor.RTPReader {
return interceptor.RTPReaderFunc(func(payload []byte, attributes interceptor.Attributes) (int, interceptor.Attributes, error) {
s.t.HandleIncomingRTP(s.participantID, s.identity, uint64(len(payload)))
return reader.Read(payload, attributes)
})
}
// --- Outgoing ---
// 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)
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)
})
}
+64
View File
@@ -0,0 +1,64 @@
package telemetry
import (
"github.com/livekit/protocol/logger"
"github.com/pion/rtcp"
"github.com/livekit/livekit-server/pkg/telemetry/prometheus"
)
func (s *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
}
s.pool.Submit(func() {
for _, pkt := range pkts {
switch pkt.(type) {
case *rtcp.TransportLayerNack:
prometheus.IncrementNack(prometheus.Incoming)
case *rtcp.PictureLossIndication:
prometheus.IncrementPLI(prometheus.Incoming)
case *rtcp.FullIntraRequest:
prometheus.IncrementFIR(prometheus.Incoming)
}
}
})
// TODO: analytics service
}
func (s *TelemetryService) HandleIncomingRTP(participantID, identity string, pktLen uint64) {
s.pool.Submit(func() {
prometheus.IncrementPackets(prometheus.Incoming, pktLen)
})
// TODO: analytics service
}
func (s *TelemetryService) HandleOutgoingRTCP(participantID, identity string, pkts []rtcp.Packet) {
s.pool.Submit(func() {
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)
}
}
})
// TODO: analytics service
}
func (s *TelemetryService) HandleOutgoingRTP(participantID, identity string, pktLen uint64) {
s.pool.Submit(func() {
prometheus.IncrementPackets(prometheus.Outgoing, pktLen)
})
// TODO: analytics service
}