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 (
"math"
"sync/atomic"
"go.uber.org/atomic"
)
const (
@@ -13,7 +14,7 @@ const (
// keeps track of audio level for a participant
type AudioLevel struct {
levelThreshold uint8
currentLevel uint32
currentLevel *atomic.Uint32
// min duration to be considered active
minActiveDuration uint32
@@ -29,7 +30,7 @@ func NewAudioLevel(activeLevel uint8, minPercentile uint8, observeDuration uint3
l := &AudioLevel{
levelThreshold: activeLevel,
minActiveDuration: uint32(minPercentile) * observeDuration / 100,
currentLevel: SilentAudioLevel,
currentLevel: atomic.NewUint32(SilentAudioLevel),
observeLevel: SilentAudioLevel,
durationToObserve: observeDuration,
}
@@ -51,9 +52,9 @@ func (l *AudioLevel) Observe(level uint8, durationMs uint32) {
// compute and reset
if l.activeDuration >= l.minActiveDuration {
level := uint32(l.observeLevel) - uint32(20*math.Log10(float64(l.activeDuration)/float64(l.durationToObserve)))
atomic.StoreUint32(&l.currentLevel, level)
l.currentLevel.Store(level)
} else {
atomic.StoreUint32(&l.currentLevel, SilentAudioLevel)
l.currentLevel.Store(SilentAudioLevel)
}
l.observeLevel = SilentAudioLevel
l.activeDuration = 0
@@ -63,7 +64,7 @@ func (l *AudioLevel) Observe(level uint8, durationMs uint32) {
// returns current audio level, 0 (loudest) to 127 (silent)
func (l *AudioLevel) GetLevel() (uint8, bool) {
level := uint8(atomic.LoadUint32(&l.currentLevel))
level := uint8(l.currentLevel.Load())
active := level != SilentAudioLevel
return level, active
}
+4 -4
View File
@@ -3,7 +3,6 @@ package rtc
import (
"context"
"sync"
"sync/atomic"
"github.com/livekit/protocol/livekit"
"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/twcc"
"github.com/livekit/livekit-server/pkg/telemetry"
"go.uber.org/atomic"
)
// MediaTrack represents a WebRTC track that needs to be forwarded
// Implements MediaTrack and PublishedTrack interface
type MediaTrack struct {
params MediaTrackParams
numUpTracks uint32
numUpTracks atomic.Uint32
buffer *buffer.Buffer
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)
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
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
t.MediaTrackReceiver.SetSimulcast(true)
}
+1 -1
View File
@@ -1,13 +1,13 @@
package rtc
import (
"sync/atomic"
"testing"
"time"
"github.com/livekit/protocol/livekit"
"github.com/pion/webrtc/v3"
"github.com/stretchr/testify/require"
"go.uber.org/atomic"
"github.com/livekit/livekit-server/pkg/testutils"
)
+4 -4
View File
@@ -3,12 +3,12 @@ package service_test
import (
"context"
"sync"
"sync/atomic"
"testing"
"time"
"github.com/livekit/protocol/livekit"
"github.com/stretchr/testify/require"
"go.uber.org/atomic"
"github.com/livekit/livekit-server/pkg/service"
)
@@ -77,7 +77,7 @@ func TestRoomLock(t *testing.T) {
token, err := rs.LockRoom(ctx, roomName, lockInterval)
require.NoError(t, err)
require.NotEmpty(t, token)
unlocked := uint32(0)
unlocked := atomic.NewUint32(0)
wg := sync.WaitGroup{}
wg.Add(1)
@@ -87,12 +87,12 @@ func TestRoomLock(t *testing.T) {
token2, err := rs.LockRoom(ctx, roomName, lockInterval)
require.NoError(t, err)
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
time.Sleep(2 * time.Millisecond)
atomic.StoreUint32(&unlocked, 1)
unlocked.Store(1)
_ = rs.UnlockRoom(ctx, roomName, token)
wg.Wait()
+3 -3
View File
@@ -109,11 +109,11 @@ package sfu
import (
"fmt"
"sync"
"sync/atomic"
"time"
"github.com/gammazero/deque"
"github.com/livekit/protocol/logger"
"go.uber.org/atomic"
)
type ProberParams struct {
@@ -123,7 +123,7 @@ type ProberParams struct {
type Prober struct {
logger logger.Logger
clusterId uint32
clusterId atomic.Uint32
clustersMu sync.RWMutex
clusters deque.Deque
@@ -179,7 +179,7 @@ func (p *Prober) AddCluster(desiredRateBps int, expectedRateBps int, minDuration
return ProbeClusterIdInvalid
}
clusterId := ProbeClusterId(atomic.AddUint32(&p.clusterId, 1))
clusterId := ProbeClusterId(p.clusterId.Inc())
cluster := NewCluster(clusterId, desiredRateBps, expectedRateBps, minDuration, maxDuration)
p.logger.Debugw("cluster added", "cluster", cluster.String())
+5 -5
View File
@@ -6,11 +6,11 @@ import (
"math/rand"
"runtime"
"sync"
"sync/atomic"
"testing"
"github.com/gammazero/workerpool"
"github.com/stretchr/testify/assert"
"go.uber.org/atomic"
)
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) {
for i := 0; i < b.N; i++ {
start := uint64(0)
start := atomic.NewUint64(0)
step := uint64(step)
end := uint64(downTracks)
@@ -147,7 +147,7 @@ func benchmarkLoadBalanced(b *testing.B, numProcs, step, downTracks int) {
go func() {
defer wg.Done()
for {
n := atomic.AddUint64(&start, step)
n := start.Add(step)
if n >= end+step {
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) {
for i := 0; i < b.N; i++ {
start := uint64(0)
start := atomic.NewUint64(0)
step := uint64(step)
end := uint64(downTracks)
@@ -174,7 +174,7 @@ func benchmarkLoadBalancedPool(b *testing.B, wp *workerpool.WorkerPool, numProcs
wp.Submit(func() {
defer wg.Done()
for {
n := atomic.AddUint64(&start, step)
n := start.Add(step)
if n >= end+step {
return
}
+19 -20
View File
@@ -1,7 +1,6 @@
package prometheus
import (
"sync/atomic"
"time"
"github.com/livekit/protocol/livekit"
@@ -54,29 +53,29 @@ func GetUpdatedNodeStats(prev *livekit.NodeStats) (*livekit.NodeStats, error) {
updatedAt := time.Now().Unix()
elapsed := updatedAt - prev.UpdatedAt
bytesIn := atomic.LoadUint64(&atomicBytesIn)
bytesOut := atomic.LoadUint64(&atomicBytesOut)
packetsIn := atomic.LoadUint64(&atomicPacketsIn)
packetsOut := atomic.LoadUint64(&atomicPacketsOut)
nackTotal := atomic.LoadUint64(&atomicNackTotal)
bytesInNow := bytesIn.Load()
bytesOutNow := bytesOut.Load()
packetsInNow := packetsIn.Load()
packetsOutNow := packetsOut.Load()
nackTotalNow := nackTotal.Load()
return &livekit.NodeStats{
StartedAt: prev.StartedAt,
UpdatedAt: updatedAt,
NumRooms: atomic.LoadInt32(&atomicRoomTotal),
NumClients: atomic.LoadInt32(&atomicParticipantTotal),
NumTracksIn: atomic.LoadInt32(&atomicTrackPublishedTotal),
NumTracksOut: atomic.LoadInt32(&atomicTrackSubscribedTotal),
BytesIn: bytesIn,
BytesOut: bytesOut,
PacketsIn: packetsIn,
PacketsOut: packetsOut,
NackTotal: nackTotal,
BytesInPerSec: perSec(prev.BytesIn, bytesIn, elapsed),
BytesOutPerSec: perSec(prev.BytesOut, bytesOut, elapsed),
PacketsInPerSec: perSec(prev.PacketsIn, packetsIn, elapsed),
PacketsOutPerSec: perSec(prev.PacketsOut, packetsOut, elapsed),
NackPerSec: perSec(prev.NackTotal, nackTotal, elapsed),
NumRooms: roomTotal.Load(),
NumClients: participantTotal.Load(),
NumTracksIn: trackPublishedTotal.Load(),
NumTracksOut: trackSubscribedTotal.Load(),
BytesIn: bytesInNow,
BytesOut: bytesOutNow,
PacketsIn: packetsInNow,
PacketsOut: packetsOutNow,
NackTotal: nackTotalNow,
BytesInPerSec: perSec(prev.BytesIn, bytesInNow, elapsed),
BytesOutPerSec: perSec(prev.BytesOut, bytesOutNow, elapsed),
PacketsInPerSec: perSec(prev.PacketsIn, packetsInNow, elapsed),
PacketsOutPerSec: perSec(prev.PacketsOut, packetsOutNow, elapsed),
NackPerSec: perSec(prev.NackTotal, nackTotalNow, elapsed),
NumCpus: numCPUs,
LoadAvgLast1Min: avg1Min,
LoadAvgLast5Min: avg5Min,
+11 -12
View File
@@ -1,9 +1,8 @@
package prometheus
import (
"sync/atomic"
"github.com/prometheus/client_golang/prometheus"
"go.uber.org/atomic"
)
type Direction string
@@ -14,11 +13,11 @@ const (
)
var (
atomicBytesIn uint64
atomicBytesOut uint64
atomicPacketsIn uint64
atomicPacketsOut uint64
atomicNackTotal uint64
bytesIn atomic.Uint64
bytesOut atomic.Uint64
packetsIn atomic.Uint64
packetsOut atomic.Uint64
nackTotal atomic.Uint64
promPacketLabels = []string{"direction"}
@@ -71,25 +70,25 @@ func initPacketStats(nodeID string) {
func IncrementPackets(direction Direction, count uint64) {
promPacketTotal.WithLabelValues(string(direction)).Add(float64(count))
if direction == Incoming {
atomic.AddUint64(&atomicPacketsIn, count)
packetsIn.Add(count)
} else {
atomic.AddUint64(&atomicPacketsOut, count)
packetsOut.Add(count)
}
}
func IncrementBytes(direction Direction, count uint64) {
promPacketBytes.WithLabelValues(string(direction)).Add(float64(count))
if direction == Incoming {
atomic.AddUint64(&atomicBytesIn, count)
bytesIn.Add(count)
} else {
atomic.AddUint64(&atomicBytesOut, count)
bytesOut.Add(count)
}
}
func IncrementRTCP(direction Direction, nack, pli, fir uint32) {
if nack > 0 {
promNackTotal.WithLabelValues(string(direction)).Add(float64(nack))
atomic.AddUint64(&atomicNackTotal, uint64(nack))
nackTotal.Add(uint64(nack))
}
if pli > 0 {
promPliTotal.WithLabelValues(string(direction)).Add(float64(pli))
+13 -13
View File
@@ -1,17 +1,17 @@
package prometheus
import (
"sync/atomic"
"time"
"github.com/prometheus/client_golang/prometheus"
"go.uber.org/atomic"
)
var (
atomicRoomTotal int32
atomicParticipantTotal int32
atomicTrackPublishedTotal int32
atomicTrackSubscribedTotal int32
roomTotal atomic.Int32
participantTotal atomic.Int32
trackPublishedTotal atomic.Int32
trackSubscribedTotal atomic.Int32
promRoomTotal prometheus.Gauge
promRoomDuration prometheus.Histogram
@@ -63,7 +63,7 @@ func initRoomStats(nodeID string) {
func RoomStarted() {
promRoomTotal.Add(1)
atomic.AddInt32(&atomicRoomTotal, 1)
roomTotal.Inc()
}
func RoomEnded(startedAt time.Time) {
@@ -71,35 +71,35 @@ func RoomEnded(startedAt time.Time) {
promRoomDuration.Observe(float64(time.Since(startedAt)) / float64(time.Second))
}
promRoomTotal.Sub(1)
atomic.AddInt32(&atomicRoomTotal, -1)
roomTotal.Dec()
}
func AddParticipant() {
promParticipantTotal.Add(1)
atomic.AddInt32(&atomicParticipantTotal, 1)
participantTotal.Inc()
}
func SubParticipant() {
promParticipantTotal.Sub(1)
atomic.AddInt32(&atomicParticipantTotal, -1)
participantTotal.Dec()
}
func AddPublishedTrack(kind string) {
promTrackPublishedTotal.WithLabelValues(kind).Add(1)
atomic.AddInt32(&atomicTrackPublishedTotal, 1)
trackPublishedTotal.Inc()
}
func SubPublishedTrack(kind string) {
promTrackPublishedTotal.WithLabelValues(kind).Sub(1)
atomic.AddInt32(&atomicTrackPublishedTotal, -1)
trackPublishedTotal.Dec()
}
func AddSubscribedTrack(kind string) {
promTrackSubscribedTotal.WithLabelValues(kind).Add(1)
atomic.AddInt32(&atomicTrackSubscribedTotal, 1)
trackSubscribedTotal.Inc()
}
func SubSubscribedTrack(kind string) {
promTrackSubscribedTotal.WithLabelValues(kind).Sub(1)
atomic.AddInt32(&atomicTrackSubscribedTotal, -1)
trackSubscribedTotal.Dec()
}