StreamAllocator (congestion controller) refactor (#3180)

* refactor WIP

* WIP

* compiling

* runlock

* fixes

* fmt

* stringer and unlikely logger

* clean up
This commit is contained in:
Raja Subramanian
2024-11-16 03:06:37 +05:30
committed by GitHub
parent eceada8b31
commit 6509cdb5ea
21 changed files with 832 additions and 514 deletions
+175
View File
@@ -0,0 +1,175 @@
// Copyright 2023 LiveKit, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package remotebwe
import (
"fmt"
"time"
"github.com/livekit/livekit-server/pkg/sfu/bwe"
"github.com/livekit/livekit-server/pkg/sfu/ccutils"
"github.com/livekit/protocol/logger"
)
// ------------------------------------------------
type channelCongestionReason int
const (
channelCongestionReasonNone channelCongestionReason = iota
channelCongestionReasonEstimate
channelCongestionReasonLoss
)
func (c channelCongestionReason) String() string {
switch c {
case channelCongestionReasonNone:
return "NONE"
case channelCongestionReasonEstimate:
return "ESTIMATE"
case channelCongestionReasonLoss:
return "LOSS"
default:
return fmt.Sprintf("%d", int(c))
}
}
// ------------------------------------------------
type ChannelObserverConfig struct {
Estimate ccutils.TrendDetectorConfig `yaml:"estimate,omitempty"`
Nack NackTrackerConfig `yaml:"nack,omitempty"`
}
var (
defaultTrendDetectorConfigProbe = ccutils.TrendDetectorConfig{
RequiredSamples: 3,
RequiredSamplesMin: 3,
DownwardTrendThreshold: 0.0,
DownwardTrendMaxWait: 5 * time.Second,
CollapseThreshold: 0,
ValidityWindow: 10 * time.Second,
}
defaultChannelObserverConfigProbe = ChannelObserverConfig{
Estimate: defaultTrendDetectorConfigProbe,
Nack: defaultNackTrackerConfigProbe,
}
defaultTrendDetectorConfigNonProbe = ccutils.TrendDetectorConfig{
RequiredSamples: 12,
RequiredSamplesMin: 8,
DownwardTrendThreshold: -0.6,
DownwardTrendMaxWait: 5 * time.Second,
CollapseThreshold: 500 * time.Millisecond,
ValidityWindow: 10 * time.Second,
}
defaultChannelObserverConfigNonProbe = ChannelObserverConfig{
Estimate: defaultTrendDetectorConfigNonProbe,
Nack: defaultNackTrackerConfigNonProbe,
}
)
// ------------------------------------------------
type channelObserverParams struct {
Name string
Config ChannelObserverConfig
}
type channelObserver struct {
params channelObserverParams
logger logger.Logger
estimateTrend *ccutils.TrendDetector[int64]
nackTracker *nackTracker
}
func newChannelObserver(params channelObserverParams, logger logger.Logger) *channelObserver {
return &channelObserver{
params: params,
logger: logger,
estimateTrend: ccutils.NewTrendDetector[int64](ccutils.TrendDetectorParams{
Name: params.Name + "-estimate",
Logger: logger,
Config: params.Config.Estimate,
}),
nackTracker: newNackTracker(nackTrackerParams{
Name: params.Name + "-nack",
Logger: logger,
Config: params.Config.Nack,
}),
}
}
func (c *channelObserver) SeedEstimate(estimate int64) {
c.estimateTrend.Seed(estimate)
}
func (c *channelObserver) AddEstimate(estimate int64) {
c.estimateTrend.AddValue(estimate)
}
func (c *channelObserver) AddNack(packets uint32, repeatedNacks uint32) {
c.nackTracker.Add(packets, repeatedNacks)
}
func (c *channelObserver) GetLowestEstimate() int64 {
return c.estimateTrend.GetLowest()
}
func (c *channelObserver) GetHighestEstimate() int64 {
return c.estimateTrend.GetHighest()
}
func (c *channelObserver) HasEnoughEstimateSamples() bool {
return c.estimateTrend.HasEnoughSamples()
}
func (c *channelObserver) GetNackRatio() float64 {
return c.nackTracker.GetRatio()
}
/* REMOTE-BWE-DATA
func (c *channelObserver) GetNackHistory() []string {
return c.nackTracker.GetHistory()
}
*/
func (c *channelObserver) GetTrend() (bwe.ChannelTrend, channelCongestionReason) {
estimateDirection := c.estimateTrend.GetDirection()
switch {
case estimateDirection == ccutils.TrendDirectionDownward:
c.logger.Debugw("stream allocator: channel observer: estimate is trending downward", "channel", c)
return bwe.ChannelTrendCongesting, channelCongestionReasonEstimate
case c.nackTracker.IsTriggered():
c.logger.Debugw("stream allocator: channel observer: high rate of repeated NACKs", "channel", c)
return bwe.ChannelTrendCongesting, channelCongestionReasonLoss
case estimateDirection == ccutils.TrendDirectionUpward:
return bwe.ChannelTrendClearing, channelCongestionReasonNone
}
return bwe.ChannelTrendNeutral, channelCongestionReasonNone
}
func (c *channelObserver) String() string {
return fmt.Sprintf("name: %s, estimate: {%v}, nack {%v}", c.params.Name, c.estimateTrend, c.nackTracker)
}
// ------------------------------------------------
+143
View File
@@ -0,0 +1,143 @@
// Copyright 2023 LiveKit, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package remotebwe
import (
"fmt"
"time"
"github.com/livekit/protocol/logger"
)
// ------------------------------------------------
type NackTrackerConfig struct {
WindowMinDuration time.Duration `yaml:"window_min_duration,omitempty"`
WindowMaxDuration time.Duration `yaml:"window_max_duration,omitempty"`
RatioThreshold float64 `yaml:"ratio_threshold,omitempty"`
}
var (
defaultNackTrackerConfigProbe = NackTrackerConfig{
WindowMinDuration: 500 * time.Millisecond,
WindowMaxDuration: 1 * time.Second,
RatioThreshold: 0.04,
}
defaultNackTrackerConfigNonProbe = NackTrackerConfig{
WindowMinDuration: 2 * time.Second,
WindowMaxDuration: 3 * time.Second,
RatioThreshold: 0.08,
}
)
// ------------------------------------------------
type nackTrackerParams struct {
Name string
Logger logger.Logger
Config NackTrackerConfig
}
type nackTracker struct {
params nackTrackerParams
windowStartTime time.Time
packets uint32
repeatedNacks uint32
/* REMOTE-BWE-DATA
// REMOTE-BWE-EXPERIMENTAL-TODO: remove when cleaning up experimental stuff
history []string
*/
}
func newNackTracker(params nackTrackerParams) *nackTracker {
return &nackTracker{
params: params,
// REMOTE-BWE-DATA history: make([]string, 0, 10),
}
}
func (n *nackTracker) Add(packets uint32, repeatedNacks uint32) {
if n.params.Config.WindowMaxDuration != 0 && !n.windowStartTime.IsZero() && time.Since(n.windowStartTime) > n.params.Config.WindowMaxDuration {
// REMOTE-BWE-DATA n.updateHistory()
n.windowStartTime = time.Time{}
n.packets = 0
n.repeatedNacks = 0
}
//
// Start NACK monitoring window only when a repeated NACK happens.
// This allows locking tightly to when NACKs start happening and
// check if the NACKs keep adding up (potentially a sign of congestion)
// or isolated losses
//
if n.repeatedNacks == 0 && repeatedNacks != 0 {
n.windowStartTime = time.Now()
}
if !n.windowStartTime.IsZero() {
n.packets += packets
n.repeatedNacks += repeatedNacks
}
}
func (n *nackTracker) GetRatio() float64 {
ratio := 0.0
if n.packets != 0 {
ratio = float64(n.repeatedNacks) / float64(n.packets)
if ratio > 1.0 {
ratio = 1.0
}
}
return ratio
}
func (n *nackTracker) IsTriggered() bool {
if n.params.Config.WindowMinDuration != 0 && !n.windowStartTime.IsZero() && time.Since(n.windowStartTime) > n.params.Config.WindowMinDuration {
return n.GetRatio() > n.params.Config.RatioThreshold
}
return false
}
func (n *nackTracker) ToString() string {
window := ""
if !n.windowStartTime.IsZero() {
now := time.Now()
elapsed := now.Sub(n.windowStartTime).Seconds()
window = fmt.Sprintf("t: %+v|%+v|%.2fs", n.windowStartTime.Format(time.UnixDate), now.Format(time.UnixDate), elapsed)
}
return fmt.Sprintf("n: %s, %s, p: %d, rn: %d, rn/p: %.2f", n.params.Name, window, n.packets, n.repeatedNacks, n.GetRatio())
}
/* REMOTE-BWE-DATA
func (n *nackTracker) GetHistory() []string {
return n.history
}
func (n *nackTracker) updateHistory() {
if len(n.history) >= 10 {
n.history = n.history[1:]
}
n.history = append(n.history, n.ToString())
}
*/
// ------------------------------------------------
+369
View File
@@ -0,0 +1,369 @@
// Copyright 2023 LiveKit, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package remotebwe
import (
"sync"
"time"
"github.com/frostbyte73/core"
"github.com/livekit/livekit-server/pkg/sfu/bwe"
"github.com/livekit/protocol/logger"
"github.com/livekit/protocol/utils/mono"
)
const (
ChannelCapacityInfinity = 100 * 1000 * 1000 // 100 Mbps
)
// ---------------------------------------------------------------------------
type RemoteBWEConfig struct {
NackRatioAttenuator float64 `yaml:"nack_ratio_attenuator,omitempty"`
ExpectedUsageThreshold float64 `yaml:"expected_usage_threshold,omitempty"`
ChannelObserverProbe ChannelObserverConfig `yaml:"channel_observer_probe,omitempty"`
ChannelObserverNonProbe ChannelObserverConfig `yaml:"channel_observer_non_probe,omitempty"`
CongestedMinDuration time.Duration `yaml:"congested_min_duration,omitempty"`
PeriodicCheckInterval time.Duration `yaml:"periodic_check_interval,omitempty"`
PeriodicCheckIntervalCongested time.Duration `yaml:"periodic_check_interval_congested,omitempty"`
}
var (
DefaultRemoteBWEConfig = RemoteBWEConfig{
NackRatioAttenuator: 0.4,
ExpectedUsageThreshold: 0.95,
ChannelObserverProbe: defaultChannelObserverConfigProbe,
ChannelObserverNonProbe: defaultChannelObserverConfigNonProbe,
CongestedMinDuration: 3 * time.Second,
PeriodicCheckInterval: 2 * time.Second,
PeriodicCheckIntervalCongested: 200 * time.Millisecond,
}
)
// ---------------------------------------------------------------------------
type RemoteBWEParams struct {
Config RemoteBWEConfig
Logger logger.Logger
}
type RemoteBWE struct {
bwe.NullBWE
params RemoteBWEParams
lock sync.RWMutex
lastReceivedEstimate int64
lastExpectedBandwidthUsage int64
isInProbe bool
committedChannelCapacity int64
channelObserver *channelObserver
congestionState bwe.CongestionState
congestionStateSwitchedAt time.Time
wake chan struct{}
stop core.Fuse
bweListener bwe.BWEListener
}
func NewRemoteBWE(params RemoteBWEParams) *RemoteBWE {
r := &RemoteBWE{
params: params,
}
r.channelObserver = r.newChannelObserverNonProbe()
return r
}
func (r *RemoteBWE) SetBWEListener(bweListener bwe.BWEListener) {
r.lock.Lock()
defer r.lock.Unlock()
r.bweListener = bweListener
}
func (r *RemoteBWE) getBWEListener() bwe.BWEListener {
r.lock.RLock()
defer r.lock.RUnlock()
return r.bweListener
}
func (r *RemoteBWE) Reset() {
r.lock.Lock()
defer r.lock.Unlock()
r.channelObserver = r.newChannelObserverNonProbe()
}
func (r *RemoteBWE) Stop() {
r.stop.Break()
}
func (r *RemoteBWE) HandleREMB(
receivedEstimate int64,
isProbeFinalizing bool,
expectedBandwidthUsage int64,
sentPackets uint32,
repeatedNacks uint32,
) {
r.lock.Lock()
r.lastReceivedEstimate = receivedEstimate
r.lastExpectedBandwidthUsage = expectedBandwidthUsage
if !isProbeFinalizing {
r.channelObserver.AddEstimate(r.lastReceivedEstimate)
r.channelObserver.AddNack(sentPackets, repeatedNacks)
}
var (
shouldNotify bool
state bwe.CongestionState
committedChannelCapacity int64
)
if !r.isInProbe {
shouldNotify, state, committedChannelCapacity = r.congestionDetectionStateMachine()
}
r.lock.Unlock()
if shouldNotify {
if bweListener := r.getBWEListener(); bweListener != nil {
bweListener.OnCongestionStateChange(state, committedChannelCapacity)
}
}
}
func (r *RemoteBWE) congestionDetectionStateMachine() (bool, bwe.CongestionState, int64) {
newState := r.congestionState
update := false
trend, reason := r.channelObserver.GetTrend()
switch r.congestionState {
case bwe.CongestionStateNone:
if trend == bwe.ChannelTrendCongesting {
if r.estimateAvailableChannelCapacity(reason) {
newState = bwe.CongestionStateCongested
}
}
case bwe.CongestionStateCongested:
if trend == bwe.ChannelTrendCongesting {
if r.estimateAvailableChannelCapacity(reason) {
// update state sa this needs to reset switch time to wait for congestion min duration again
update = true
}
} else if time.Since(r.congestionStateSwitchedAt) >= r.params.Config.CongestedMinDuration {
newState = bwe.CongestionStateNone
}
}
shouldNotify := false
if newState != r.congestionState || update {
r.updateCongestionState(newState, reason)
shouldNotify = true
}
return shouldNotify, r.congestionState, r.committedChannelCapacity
}
func (r *RemoteBWE) estimateAvailableChannelCapacity(reason channelCongestionReason) bool {
var estimateToCommit int64
switch reason {
case channelCongestionReasonLoss:
estimateToCommit = int64(float64(r.lastExpectedBandwidthUsage) * (1.0 - r.params.Config.NackRatioAttenuator*r.channelObserver.GetNackRatio()))
default:
estimateToCommit = r.lastReceivedEstimate
}
if estimateToCommit > r.lastReceivedEstimate {
estimateToCommit = r.lastReceivedEstimate
}
commitThreshold := int64(r.params.Config.ExpectedUsageThreshold * float64(r.lastExpectedBandwidthUsage))
ulgr := r.params.Logger.WithUnlikelyValues(
"reason", reason,
"old(bps)", r.committedChannelCapacity,
"new(bps)", estimateToCommit,
"lastReceived(bps)", r.lastReceivedEstimate,
"expectedUsage(bps)", r.lastExpectedBandwidthUsage,
"commitThreshold(bps)", commitThreshold,
"channel", r.channelObserver,
)
if estimateToCommit > commitThreshold {
ulgr.Debugw("remote bwe: channel congestion detected, skipping above commit threshold channel capacity update")
return false
}
ulgr.Infow("remote bwe: channel congestion detected, applying channel capacity update")
/* REMOTE-BWE-DATA
r.params.Logger.Debugw(
fmt.Sprintf("remote bwe: channel congestion detected, %s channel capacity: experimental", action),
"nackHistory", r.channelObserver.GetNackHistory(),
)
*/
r.committedChannelCapacity = estimateToCommit
// reset to get new set of samples for next trend
r.channelObserver = r.newChannelObserverNonProbe()
return true
}
func (r *RemoteBWE) updateCongestionState(state bwe.CongestionState, reason channelCongestionReason) {
r.params.Logger.Infow(
"remote bwe: congestion state change",
"from", r.congestionState,
"to", state,
"reason", reason,
"committedChannelCapacity", r.committedChannelCapacity,
)
if state != r.congestionState {
// notify worker for ticker interval management based on state
select {
case r.wake <- struct{}{}:
default:
}
}
r.congestionState = state
r.congestionStateSwitchedAt = mono.Now()
}
func (r *RemoteBWE) newChannelObserverNonProbe() *channelObserver {
return newChannelObserver(
channelObserverParams{
Name: "non-probe",
Config: r.params.Config.ChannelObserverNonProbe,
},
r.params.Logger,
)
}
func (r *RemoteBWE) ProbingStart(expectedBandwidthUsage int64) {
r.lock.Lock()
defer r.lock.Unlock()
r.isInProbe = true
r.lastExpectedBandwidthUsage = expectedBandwidthUsage
r.params.Logger.Debugw(
"stream allocator: starting probe",
"lastReceived", r.lastReceivedEstimate,
"expectedBandwidthUsage", expectedBandwidthUsage,
"channel", r.channelObserver,
)
r.channelObserver = newChannelObserver(
channelObserverParams{
Name: "probe",
Config: r.params.Config.ChannelObserverProbe,
},
r.params.Logger,
)
r.channelObserver.SeedEstimate(r.lastReceivedEstimate)
}
func (r *RemoteBWE) ProbingEnd(isNotFailing bool, isGoalReached bool) {
r.lock.Lock()
defer r.lock.Unlock()
highestEstimateInProbe := r.channelObserver.GetHighestEstimate()
//
// Reset estimator at the end of a probe irrespective of probe result to get fresh readings.
// With a failed probe, the latest estimate could be lower than committed estimate.
// As bandwidth estimator (remote in REMB case, local in TWCC case) holds state,
// subsequent estimates could start from the lower point. That should not trigger a
// downward trend and get latched to committed estimate as that would trigger a re-allocation.
// With fresh readings, as long as the trend is not going downward, it will not get latched.
//
// BWE-TODO: clean up this comment after implementing probing in TWCC case
// NOTE: With TWCC, it is possible to reset bandwidth estimation to clean state as
// the send side is in full control of bandwidth estimation.
//
r.params.Logger.Debugw(
"probe done",
"isNotFailing", isNotFailing,
"isGoalReached", isGoalReached,
"committedEstimate", r.committedChannelCapacity,
"highestEstimate", highestEstimateInProbe,
"channel", r.channelObserver,
)
r.channelObserver = r.newChannelObserverNonProbe()
if !isNotFailing {
return
}
if highestEstimateInProbe > r.committedChannelCapacity {
r.committedChannelCapacity = highestEstimateInProbe
}
}
func (r *RemoteBWE) GetProbeStatus() (bool, bwe.ChannelTrend, int64, int64) {
r.lock.RLock()
defer r.lock.RUnlock()
if !r.isInProbe {
return false, bwe.ChannelTrendNeutral, 0, 0
}
trend, _ := r.channelObserver.GetTrend()
return r.channelObserver.HasEnoughEstimateSamples(),
trend,
r.channelObserver.GetLowestEstimate(),
r.channelObserver.GetHighestEstimate()
}
func (r *RemoteBWE) worker() {
ticker := time.NewTicker(r.params.Config.PeriodicCheckInterval)
defer ticker.Stop()
for {
select {
case <-r.wake:
r.lock.RLock()
state := r.congestionState
r.lock.RUnlock()
if state == bwe.CongestionStateCongested {
ticker.Reset(r.params.Config.PeriodicCheckIntervalCongested)
} else {
ticker.Reset(r.params.Config.PeriodicCheckInterval)
}
case <-ticker.C:
var (
shouldNotify bool
state bwe.CongestionState
committedChannelCapacity int64
)
r.lock.Lock()
shouldNotify, state, committedChannelCapacity = r.congestionDetectionStateMachine()
r.lock.Unlock()
if shouldNotify {
if bweListener := r.getBWEListener(); bweListener != nil {
bweListener.OnCongestionStateChange(state, committedChannelCapacity)
}
}
case <-r.stop.Watch():
return
}
}
}