Replace sync/atomic usage with uber/atomic (#471)

This commit is contained in:
Raja Subramanian
2022-02-28 09:57:17 +05:30
committed by GitHub
parent 933b41e42a
commit 2706dc130f
9 changed files with 67 additions and 68 deletions
+7 -6
View File
@@ -2,7 +2,8 @@ package rtc
import ( import (
"math" "math"
"sync/atomic"
"go.uber.org/atomic"
) )
const ( const (
@@ -13,7 +14,7 @@ const (
// keeps track of audio level for a participant // keeps track of audio level for a participant
type AudioLevel struct { type AudioLevel struct {
levelThreshold uint8 levelThreshold uint8
currentLevel uint32 currentLevel *atomic.Uint32
// min duration to be considered active // min duration to be considered active
minActiveDuration uint32 minActiveDuration uint32
@@ -29,7 +30,7 @@ func NewAudioLevel(activeLevel uint8, minPercentile uint8, observeDuration uint3
l := &AudioLevel{ l := &AudioLevel{
levelThreshold: activeLevel, levelThreshold: activeLevel,
minActiveDuration: uint32(minPercentile) * observeDuration / 100, minActiveDuration: uint32(minPercentile) * observeDuration / 100,
currentLevel: SilentAudioLevel, currentLevel: atomic.NewUint32(SilentAudioLevel),
observeLevel: SilentAudioLevel, observeLevel: SilentAudioLevel,
durationToObserve: observeDuration, durationToObserve: observeDuration,
} }
@@ -51,9 +52,9 @@ func (l *AudioLevel) Observe(level uint8, durationMs uint32) {
// compute and reset // compute and reset
if l.activeDuration >= l.minActiveDuration { if l.activeDuration >= l.minActiveDuration {
level := uint32(l.observeLevel) - uint32(20*math.Log10(float64(l.activeDuration)/float64(l.durationToObserve))) level := uint32(l.observeLevel) - uint32(20*math.Log10(float64(l.activeDuration)/float64(l.durationToObserve)))
atomic.StoreUint32(&l.currentLevel, level) l.currentLevel.Store(level)
} else { } else {
atomic.StoreUint32(&l.currentLevel, SilentAudioLevel) l.currentLevel.Store(SilentAudioLevel)
} }
l.observeLevel = SilentAudioLevel l.observeLevel = SilentAudioLevel
l.activeDuration = 0 l.activeDuration = 0
@@ -63,7 +64,7 @@ func (l *AudioLevel) Observe(level uint8, durationMs uint32) {
// returns current audio level, 0 (loudest) to 127 (silent) // returns current audio level, 0 (loudest) to 127 (silent)
func (l *AudioLevel) GetLevel() (uint8, bool) { func (l *AudioLevel) GetLevel() (uint8, bool) {
level := uint8(atomic.LoadUint32(&l.currentLevel)) level := uint8(l.currentLevel.Load())
active := level != SilentAudioLevel active := level != SilentAudioLevel
return level, active return level, active
} }
+4 -4
View File
@@ -3,7 +3,6 @@ package rtc
import ( import (
"context" "context"
"sync" "sync"
"sync/atomic"
"github.com/livekit/protocol/livekit" "github.com/livekit/protocol/livekit"
"github.com/livekit/protocol/logger" "github.com/livekit/protocol/logger"
@@ -15,13 +14,15 @@ import (
"github.com/livekit/livekit-server/pkg/sfu/buffer" "github.com/livekit/livekit-server/pkg/sfu/buffer"
"github.com/livekit/livekit-server/pkg/sfu/twcc" "github.com/livekit/livekit-server/pkg/sfu/twcc"
"github.com/livekit/livekit-server/pkg/telemetry" "github.com/livekit/livekit-server/pkg/telemetry"
"go.uber.org/atomic"
) )
// MediaTrack represents a WebRTC track that needs to be forwarded // MediaTrack represents a WebRTC track that needs to be forwarded
// Implements MediaTrack and PublishedTrack interface // Implements MediaTrack and PublishedTrack interface
type MediaTrack struct { type MediaTrack struct {
params MediaTrackParams params MediaTrackParams
numUpTracks uint32 numUpTracks atomic.Uint32
buffer *buffer.Buffer buffer *buffer.Buffer
layerSSRCs [livekit.VideoQuality_HIGH + 1]uint32 layerSSRCs [livekit.VideoQuality_HIGH + 1]uint32
@@ -186,9 +187,8 @@ func (t *MediaTrack) AddReceiver(receiver *webrtc.RTPReceiver, track *webrtc.Tra
t.Receiver().(*sfu.WebRTCReceiver).AddUpTrack(track, buff) t.Receiver().(*sfu.WebRTCReceiver).AddUpTrack(track, buff)
atomic.AddUint32(&t.numUpTracks, 1)
// LK-TODO: can remove this completely when VideoLayers protocol becomes the default as it has info from client or if we decide to use TrackInfo.Simulcast // LK-TODO: can remove this completely when VideoLayers protocol becomes the default as it has info from client or if we decide to use TrackInfo.Simulcast
if atomic.LoadUint32(&t.numUpTracks) > 1 || track.RID() != "" { if t.numUpTracks.Inc() > 1 || track.RID() != "" {
// cannot only rely on numUpTracks since we fire metadata events immediately after the first layer // cannot only rely on numUpTracks since we fire metadata events immediately after the first layer
t.MediaTrackReceiver.SetSimulcast(true) t.MediaTrackReceiver.SetSimulcast(true)
} }
+1 -1
View File
@@ -1,13 +1,13 @@
package rtc package rtc
import ( import (
"sync/atomic"
"testing" "testing"
"time" "time"
"github.com/livekit/protocol/livekit" "github.com/livekit/protocol/livekit"
"github.com/pion/webrtc/v3" "github.com/pion/webrtc/v3"
"github.com/stretchr/testify/require" "github.com/stretchr/testify/require"
"go.uber.org/atomic"
"github.com/livekit/livekit-server/pkg/testutils" "github.com/livekit/livekit-server/pkg/testutils"
) )
+4 -4
View File
@@ -3,12 +3,12 @@ package service_test
import ( import (
"context" "context"
"sync" "sync"
"sync/atomic"
"testing" "testing"
"time" "time"
"github.com/livekit/protocol/livekit" "github.com/livekit/protocol/livekit"
"github.com/stretchr/testify/require" "github.com/stretchr/testify/require"
"go.uber.org/atomic"
"github.com/livekit/livekit-server/pkg/service" "github.com/livekit/livekit-server/pkg/service"
) )
@@ -77,7 +77,7 @@ func TestRoomLock(t *testing.T) {
token, err := rs.LockRoom(ctx, roomName, lockInterval) token, err := rs.LockRoom(ctx, roomName, lockInterval)
require.NoError(t, err) require.NoError(t, err)
require.NotEmpty(t, token) require.NotEmpty(t, token)
unlocked := uint32(0) unlocked := atomic.NewUint32(0)
wg := sync.WaitGroup{} wg := sync.WaitGroup{}
wg.Add(1) wg.Add(1)
@@ -87,12 +87,12 @@ func TestRoomLock(t *testing.T) {
token2, err := rs.LockRoom(ctx, roomName, lockInterval) token2, err := rs.LockRoom(ctx, roomName, lockInterval)
require.NoError(t, err) require.NoError(t, err)
defer rs.UnlockRoom(ctx, roomName, token2) defer rs.UnlockRoom(ctx, roomName, token2)
require.Equal(t, uint32(1), atomic.LoadUint32(&unlocked)) require.Equal(t, uint32(1), unlocked.Load())
}() }()
// release after 2 ms // release after 2 ms
time.Sleep(2 * time.Millisecond) time.Sleep(2 * time.Millisecond)
atomic.StoreUint32(&unlocked, 1) unlocked.Store(1)
_ = rs.UnlockRoom(ctx, roomName, token) _ = rs.UnlockRoom(ctx, roomName, token)
wg.Wait() wg.Wait()
+3 -3
View File
@@ -109,11 +109,11 @@ package sfu
import ( import (
"fmt" "fmt"
"sync" "sync"
"sync/atomic"
"time" "time"
"github.com/gammazero/deque" "github.com/gammazero/deque"
"github.com/livekit/protocol/logger" "github.com/livekit/protocol/logger"
"go.uber.org/atomic"
) )
type ProberParams struct { type ProberParams struct {
@@ -123,7 +123,7 @@ type ProberParams struct {
type Prober struct { type Prober struct {
logger logger.Logger logger logger.Logger
clusterId uint32 clusterId atomic.Uint32
clustersMu sync.RWMutex clustersMu sync.RWMutex
clusters deque.Deque clusters deque.Deque
@@ -179,7 +179,7 @@ func (p *Prober) AddCluster(desiredRateBps int, expectedRateBps int, minDuration
return ProbeClusterIdInvalid return ProbeClusterIdInvalid
} }
clusterId := ProbeClusterId(atomic.AddUint32(&p.clusterId, 1)) clusterId := ProbeClusterId(p.clusterId.Inc())
cluster := NewCluster(clusterId, desiredRateBps, expectedRateBps, minDuration, maxDuration) cluster := NewCluster(clusterId, desiredRateBps, expectedRateBps, minDuration, maxDuration)
p.logger.Debugw("cluster added", "cluster", cluster.String()) p.logger.Debugw("cluster added", "cluster", cluster.String())
+5 -5
View File
@@ -6,11 +6,11 @@ import (
"math/rand" "math/rand"
"runtime" "runtime"
"sync" "sync"
"sync/atomic"
"testing" "testing"
"github.com/gammazero/workerpool" "github.com/gammazero/workerpool"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
"go.uber.org/atomic"
) )
func TestWebRTCReceiver_OnCloseHandler(t *testing.T) { func TestWebRTCReceiver_OnCloseHandler(t *testing.T) {
@@ -137,7 +137,7 @@ func benchmarkGoroutine(b *testing.B, buckets []int) {
func benchmarkLoadBalanced(b *testing.B, numProcs, step, downTracks int) { func benchmarkLoadBalanced(b *testing.B, numProcs, step, downTracks int) {
for i := 0; i < b.N; i++ { for i := 0; i < b.N; i++ {
start := uint64(0) start := atomic.NewUint64(0)
step := uint64(step) step := uint64(step)
end := uint64(downTracks) end := uint64(downTracks)
@@ -147,7 +147,7 @@ func benchmarkLoadBalanced(b *testing.B, numProcs, step, downTracks int) {
go func() { go func() {
defer wg.Done() defer wg.Done()
for { for {
n := atomic.AddUint64(&start, step) n := start.Add(step)
if n >= end+step { if n >= end+step {
return return
} }
@@ -164,7 +164,7 @@ func benchmarkLoadBalanced(b *testing.B, numProcs, step, downTracks int) {
func benchmarkLoadBalancedPool(b *testing.B, wp *workerpool.WorkerPool, numProcs, step, downTracks int) { func benchmarkLoadBalancedPool(b *testing.B, wp *workerpool.WorkerPool, numProcs, step, downTracks int) {
for i := 0; i < b.N; i++ { for i := 0; i < b.N; i++ {
start := uint64(0) start := atomic.NewUint64(0)
step := uint64(step) step := uint64(step)
end := uint64(downTracks) end := uint64(downTracks)
@@ -174,7 +174,7 @@ func benchmarkLoadBalancedPool(b *testing.B, wp *workerpool.WorkerPool, numProcs
wp.Submit(func() { wp.Submit(func() {
defer wg.Done() defer wg.Done()
for { for {
n := atomic.AddUint64(&start, step) n := start.Add(step)
if n >= end+step { if n >= end+step {
return return
} }
+19 -20
View File
@@ -1,7 +1,6 @@
package prometheus package prometheus
import ( import (
"sync/atomic"
"time" "time"
"github.com/livekit/protocol/livekit" "github.com/livekit/protocol/livekit"
@@ -54,29 +53,29 @@ func GetUpdatedNodeStats(prev *livekit.NodeStats) (*livekit.NodeStats, error) {
updatedAt := time.Now().Unix() updatedAt := time.Now().Unix()
elapsed := updatedAt - prev.UpdatedAt elapsed := updatedAt - prev.UpdatedAt
bytesIn := atomic.LoadUint64(&atomicBytesIn) bytesInNow := bytesIn.Load()
bytesOut := atomic.LoadUint64(&atomicBytesOut) bytesOutNow := bytesOut.Load()
packetsIn := atomic.LoadUint64(&atomicPacketsIn) packetsInNow := packetsIn.Load()
packetsOut := atomic.LoadUint64(&atomicPacketsOut) packetsOutNow := packetsOut.Load()
nackTotal := atomic.LoadUint64(&atomicNackTotal) nackTotalNow := nackTotal.Load()
return &livekit.NodeStats{ return &livekit.NodeStats{
StartedAt: prev.StartedAt, StartedAt: prev.StartedAt,
UpdatedAt: updatedAt, UpdatedAt: updatedAt,
NumRooms: atomic.LoadInt32(&atomicRoomTotal), NumRooms: roomTotal.Load(),
NumClients: atomic.LoadInt32(&atomicParticipantTotal), NumClients: participantTotal.Load(),
NumTracksIn: atomic.LoadInt32(&atomicTrackPublishedTotal), NumTracksIn: trackPublishedTotal.Load(),
NumTracksOut: atomic.LoadInt32(&atomicTrackSubscribedTotal), NumTracksOut: trackSubscribedTotal.Load(),
BytesIn: bytesIn, BytesIn: bytesInNow,
BytesOut: bytesOut, BytesOut: bytesOutNow,
PacketsIn: packetsIn, PacketsIn: packetsInNow,
PacketsOut: packetsOut, PacketsOut: packetsOutNow,
NackTotal: nackTotal, NackTotal: nackTotalNow,
BytesInPerSec: perSec(prev.BytesIn, bytesIn, elapsed), BytesInPerSec: perSec(prev.BytesIn, bytesInNow, elapsed),
BytesOutPerSec: perSec(prev.BytesOut, bytesOut, elapsed), BytesOutPerSec: perSec(prev.BytesOut, bytesOutNow, elapsed),
PacketsInPerSec: perSec(prev.PacketsIn, packetsIn, elapsed), PacketsInPerSec: perSec(prev.PacketsIn, packetsInNow, elapsed),
PacketsOutPerSec: perSec(prev.PacketsOut, packetsOut, elapsed), PacketsOutPerSec: perSec(prev.PacketsOut, packetsOutNow, elapsed),
NackPerSec: perSec(prev.NackTotal, nackTotal, elapsed), NackPerSec: perSec(prev.NackTotal, nackTotalNow, elapsed),
NumCpus: numCPUs, NumCpus: numCPUs,
LoadAvgLast1Min: avg1Min, LoadAvgLast1Min: avg1Min,
LoadAvgLast5Min: avg5Min, LoadAvgLast5Min: avg5Min,
+11 -12
View File
@@ -1,9 +1,8 @@
package prometheus package prometheus
import ( import (
"sync/atomic"
"github.com/prometheus/client_golang/prometheus" "github.com/prometheus/client_golang/prometheus"
"go.uber.org/atomic"
) )
type Direction string type Direction string
@@ -14,11 +13,11 @@ const (
) )
var ( var (
atomicBytesIn uint64 bytesIn atomic.Uint64
atomicBytesOut uint64 bytesOut atomic.Uint64
atomicPacketsIn uint64 packetsIn atomic.Uint64
atomicPacketsOut uint64 packetsOut atomic.Uint64
atomicNackTotal uint64 nackTotal atomic.Uint64
promPacketLabels = []string{"direction"} promPacketLabels = []string{"direction"}
@@ -71,25 +70,25 @@ func initPacketStats(nodeID string) {
func IncrementPackets(direction Direction, count uint64) { func IncrementPackets(direction Direction, count uint64) {
promPacketTotal.WithLabelValues(string(direction)).Add(float64(count)) promPacketTotal.WithLabelValues(string(direction)).Add(float64(count))
if direction == Incoming { if direction == Incoming {
atomic.AddUint64(&atomicPacketsIn, count) packetsIn.Add(count)
} else { } else {
atomic.AddUint64(&atomicPacketsOut, count) packetsOut.Add(count)
} }
} }
func IncrementBytes(direction Direction, count uint64) { func IncrementBytes(direction Direction, count uint64) {
promPacketBytes.WithLabelValues(string(direction)).Add(float64(count)) promPacketBytes.WithLabelValues(string(direction)).Add(float64(count))
if direction == Incoming { if direction == Incoming {
atomic.AddUint64(&atomicBytesIn, count) bytesIn.Add(count)
} else { } else {
atomic.AddUint64(&atomicBytesOut, count) bytesOut.Add(count)
} }
} }
func IncrementRTCP(direction Direction, nack, pli, fir uint32) { func IncrementRTCP(direction Direction, nack, pli, fir uint32) {
if nack > 0 { if nack > 0 {
promNackTotal.WithLabelValues(string(direction)).Add(float64(nack)) promNackTotal.WithLabelValues(string(direction)).Add(float64(nack))
atomic.AddUint64(&atomicNackTotal, uint64(nack)) nackTotal.Add(uint64(nack))
} }
if pli > 0 { if pli > 0 {
promPliTotal.WithLabelValues(string(direction)).Add(float64(pli)) promPliTotal.WithLabelValues(string(direction)).Add(float64(pli))
+13 -13
View File
@@ -1,17 +1,17 @@
package prometheus package prometheus
import ( import (
"sync/atomic"
"time" "time"
"github.com/prometheus/client_golang/prometheus" "github.com/prometheus/client_golang/prometheus"
"go.uber.org/atomic"
) )
var ( var (
atomicRoomTotal int32 roomTotal atomic.Int32
atomicParticipantTotal int32 participantTotal atomic.Int32
atomicTrackPublishedTotal int32 trackPublishedTotal atomic.Int32
atomicTrackSubscribedTotal int32 trackSubscribedTotal atomic.Int32
promRoomTotal prometheus.Gauge promRoomTotal prometheus.Gauge
promRoomDuration prometheus.Histogram promRoomDuration prometheus.Histogram
@@ -63,7 +63,7 @@ func initRoomStats(nodeID string) {
func RoomStarted() { func RoomStarted() {
promRoomTotal.Add(1) promRoomTotal.Add(1)
atomic.AddInt32(&atomicRoomTotal, 1) roomTotal.Inc()
} }
func RoomEnded(startedAt time.Time) { func RoomEnded(startedAt time.Time) {
@@ -71,35 +71,35 @@ func RoomEnded(startedAt time.Time) {
promRoomDuration.Observe(float64(time.Since(startedAt)) / float64(time.Second)) promRoomDuration.Observe(float64(time.Since(startedAt)) / float64(time.Second))
} }
promRoomTotal.Sub(1) promRoomTotal.Sub(1)
atomic.AddInt32(&atomicRoomTotal, -1) roomTotal.Dec()
} }
func AddParticipant() { func AddParticipant() {
promParticipantTotal.Add(1) promParticipantTotal.Add(1)
atomic.AddInt32(&atomicParticipantTotal, 1) participantTotal.Inc()
} }
func SubParticipant() { func SubParticipant() {
promParticipantTotal.Sub(1) promParticipantTotal.Sub(1)
atomic.AddInt32(&atomicParticipantTotal, -1) participantTotal.Dec()
} }
func AddPublishedTrack(kind string) { func AddPublishedTrack(kind string) {
promTrackPublishedTotal.WithLabelValues(kind).Add(1) promTrackPublishedTotal.WithLabelValues(kind).Add(1)
atomic.AddInt32(&atomicTrackPublishedTotal, 1) trackPublishedTotal.Inc()
} }
func SubPublishedTrack(kind string) { func SubPublishedTrack(kind string) {
promTrackPublishedTotal.WithLabelValues(kind).Sub(1) promTrackPublishedTotal.WithLabelValues(kind).Sub(1)
atomic.AddInt32(&atomicTrackPublishedTotal, -1) trackPublishedTotal.Dec()
} }
func AddSubscribedTrack(kind string) { func AddSubscribedTrack(kind string) {
promTrackSubscribedTotal.WithLabelValues(kind).Add(1) promTrackSubscribedTotal.WithLabelValues(kind).Add(1)
atomic.AddInt32(&atomicTrackSubscribedTotal, 1) trackSubscribedTotal.Inc()
} }
func SubSubscribedTrack(kind string) { func SubSubscribedTrack(kind string) {
promTrackSubscribedTotal.WithLabelValues(kind).Sub(1) promTrackSubscribedTotal.WithLabelValues(kind).Sub(1)
atomic.AddInt32(&atomicTrackSubscribedTotal, -1) trackSubscribedTotal.Dec()
} }