Debounce network monitor restarts (#2225)

This commit is contained in:
Viktor Liu 2024-07-02 17:09:00 +02:00 committed by GitHub
parent 29e5eceb6b
commit cea19de667
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194

View File

@ -1465,6 +1465,15 @@ func (e *Engine) probeTURNs() []relay.ProbeResult {
return relay.ProbeAll(e.ctx, relay.ProbeTURN, e.TURNs) return relay.ProbeAll(e.ctx, relay.ProbeTURN, e.TURNs)
} }
func (e *Engine) restartEngine() {
if err := e.Stop(); err != nil {
log.Errorf("Failed to stop engine: %v", err)
}
if err := e.Start(); err != nil {
log.Errorf("Failed to start engine: %v", err)
}
}
func (e *Engine) startNetworkMonitor() { func (e *Engine) startNetworkMonitor() {
if !e.config.NetworkMonitor { if !e.config.NetworkMonitor {
log.Infof("Network monitor is disabled, not starting") log.Infof("Network monitor is disabled, not starting")
@ -1473,14 +1482,29 @@ func (e *Engine) startNetworkMonitor() {
e.networkMonitor = networkmonitor.New() e.networkMonitor = networkmonitor.New()
go func() { go func() {
var mu sync.Mutex
var debounceTimer *time.Timer
// Start the network monitor with a callback, Start will block until the monitor is stopped,
// a network change is detected, or an error occurs on start up
err := e.networkMonitor.Start(e.ctx, func() { err := e.networkMonitor.Start(e.ctx, func() {
// This function is called when a network change is detected
mu.Lock()
defer mu.Unlock()
if debounceTimer != nil {
debounceTimer.Stop()
}
// Set a new timer to debounce rapid network changes
debounceTimer = time.AfterFunc(1*time.Second, func() {
// This function is called after the debounce period
mu.Lock()
defer mu.Unlock()
log.Infof("Network monitor detected network change, restarting engine") log.Infof("Network monitor detected network change, restarting engine")
if err := e.Stop(); err != nil { e.restartEngine()
log.Errorf("Failed to stop engine: %v", err) })
}
if err := e.Start(); err != nil {
log.Errorf("Failed to start engine: %v", err)
}
}) })
if err != nil && !errors.Is(err, networkmonitor.ErrStopped) { if err != nil && !errors.Is(err, networkmonitor.ErrStopped) {
log.Errorf("Network monitor: %v", err) log.Errorf("Network monitor: %v", err)