From 5a94ec0d6960210d9a8f8301308a56d59095bf70 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 9 Jul 2022 21:14:19 -0500 Subject: add ConnectionWatchdog --- src/slskd/Core/ConnectionWatchdog.cs | 113 +++++++++++++++++++++++++++++++++++ 1 file changed, 113 insertions(+) create mode 100644 src/slskd/Core/ConnectionWatchdog.cs (limited to 'src') diff --git a/src/slskd/Core/ConnectionWatchdog.cs b/src/slskd/Core/ConnectionWatchdog.cs new file mode 100644 index 00000000..633b1f70 --- /dev/null +++ b/src/slskd/Core/ConnectionWatchdog.cs @@ -0,0 +1,113 @@ +// +// Copyright (c) slskd Team. All rights reserved. +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Affero General Public License as published +// by the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Affero General Public License for more details. +// +// You should have received a copy of the GNU Affero General Public License +// along with this program. If not, see https://www.gnu.org/licenses/. +// + +using Microsoft.Extensions.Options; + +namespace slskd +{ + using System; + using System.Threading.Tasks; + using Serilog; + using Soulseek; + + public interface IConnectionWatchdog : IDisposable + { + } + + public class ConnectionWatchdog : IConnectionWatchdog + { + private static readonly int ReconnectMaxDelayMilliseconds = 300000; // 5 minutes + + public ConnectionWatchdog( + ISoulseekClient soulseekClient, + IOptionsMonitor optionsMonitor, + IStateMonitor state) + { + Client = soulseekClient; + Options = optionsMonitor; + State = state; + + WatchDogTimer = new System.Timers.Timer() + { + Interval = 250, + AutoReset = true, + Enabled = true, + }; + + WatchDogTimer.Elapsed += (sender, args) => _ = AttemptReconnect(); + } + + private int Attempts { get; set; } + private ISoulseekClient Client { get; } + private bool Disposed { get; set; } + private ILogger Log { get; } = Serilog.Log.ForContext(); + private IOptionsMonitor Options { get; set; } + private IStateMonitor State { get; } + private System.Timers.Timer WatchDogTimer { get; } + + public void Dispose() + { + Dispose(disposing: true); + GC.SuppressFinalize(this); + } + + protected virtual void Dispose(bool disposing) + { + if (!Disposed) + { + if (disposing) + { + WatchDogTimer?.Dispose(); + } + + Disposed = true; + } + } + + private async Task AttemptReconnect() + { + if (State.CurrentValue.Server.IsConnected || !State.CurrentValue.Server.AttemptingReconnect) + { + return; + } + + var (delay, jitter) = Compute.ExponentialBackoffDelay( + iteration: Attempts, + maxDelayInMilliseconds: ReconnectMaxDelayMilliseconds); + + var approximateDelay = (int)Math.Ceiling((double)(delay + jitter) / 1000); + Log.Information($"Waiting about {(approximateDelay == 1 ? "a second" : $"{approximateDelay} seconds")} before reconnecting"); + + await Task.Delay(delay + jitter); + + Log.Information("Attempting to reconnect (#{Attempts})...", Attempts); + + try + { + // reconnect with the latest configuration values we have for username and password, instead of the options that + // were captured at startup. if a user has updated these values prior to the disconnect, the changes will take + // effect now. + await Client.ConnectAsync(Options.CurrentValue.Soulseek.Username, Options.CurrentValue.Soulseek.Password); + } + catch (Exception ex) + { + Attempts++; + Log.Error("Failed to reconnect: {Message}", ex.Message); + } + } + } +} \ No newline at end of file -- cgit v1.2.3 From d95c02b1f086ba17811e7ef08d45a89e069f7e31 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 9 Jul 2022 21:14:32 -0500 Subject: add AttemptingReconnect --- src/slskd/Core/State.cs | 1 + 1 file changed, 1 insertion(+) (limited to 'src') diff --git a/src/slskd/Core/State.cs b/src/slskd/Core/State.cs index e009805a..7492a096 100644 --- a/src/slskd/Core/State.cs +++ b/src/slskd/Core/State.cs @@ -61,6 +61,7 @@ namespace slskd public bool IsConnected => State.HasFlag(SoulseekClientStates.Connected); public bool IsLoggedIn => State.HasFlag(SoulseekClientStates.LoggedIn); public bool IsTransitioning => State.HasFlag(SoulseekClientStates.Connecting) || State.HasFlag(SoulseekClientStates.Disconnecting) || State.HasFlag(SoulseekClientStates.LoggingIn); + public bool AttemptingReconnect { get; init; } } public record UserState -- cgit v1.2.3 From 9c4efa364072d86bff464905645c0663ecfd0406 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 9 Jul 2022 21:15:07 -0500 Subject: refactor reconnect logic --- src/slskd/Application.cs | 37 ++++++++++--------------------------- 1 file changed, 10 insertions(+), 27 deletions(-) (limited to 'src') diff --git a/src/slskd/Application.cs b/src/slskd/Application.cs index 598c0c5e..2c1a63af 100644 --- a/src/slskd/Application.cs +++ b/src/slskd/Application.cs @@ -381,7 +381,7 @@ namespace slskd logger.Write(TranslateLogLevel(args.Level), "{@Message}", args.Message); } - private async void Client_Disconnected(object sender, SoulseekClientDisconnectedEventArgs args) + private void Client_Disconnected(object sender, SoulseekClientDisconnectedEventArgs args) { if (State.CurrentValue.PendingReconnect) { @@ -414,34 +414,16 @@ namespace slskd return; } - var attempts = 1; - - while (true) + // none of the conditions that would prevent a reconnect attempt have been met + // update the state to set AttemptingReconnect to true, which will cause the IConnectionMonitor + // to begin the reconnect sequence + State.SetValue(state => state with { - var (delay, jitter) = Compute.ExponentialBackoffDelay( - iteration: attempts, - maxDelayInMilliseconds: ReconnectMaxDelayMilliseconds); - - var approximateDelay = (int)Math.Ceiling((double)(delay + jitter) / 1000); - Log.Information($"Waiting about {(approximateDelay == 1 ? "a second" : $"{approximateDelay} seconds")} before reconnecting"); - await Task.Delay(delay + jitter); - - Log.Information($"Attempting to reconnect (#{attempts})...", attempts); - - try + Server = state.Server with { - // reconnect with the latest configuration values we have for username and password, instead of the - // options that were captured at startup. if a user has updated these values prior to the disconnect, the - // changes will take effect now. - await Client.ConnectAsync(Options.Soulseek.Username, Options.Soulseek.Password); - break; - } - catch (Exception ex) - { - attempts++; - Log.Error("Failed to reconnect: {Message}", ex.Message); - } - } + AttemptingReconnect = true, + }, + }); } } @@ -521,6 +503,7 @@ namespace slskd Address = Client.Address, IPEndPoint = Client.IPEndPoint, State = Client.State, + AttemptingReconnect = Client.State.HasFlag(SoulseekClientStates.Connected) ? false : state.Server.AttemptingReconnect, }, User = state.User with { -- cgit v1.2.3 From 47f25751f42b75c156e82f84b67385291c3d7ef7 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 10 Jul 2022 12:21:46 -0500 Subject: remove AttemptingReconnect --- src/slskd/Core/State.cs | 1 - 1 file changed, 1 deletion(-) (limited to 'src') diff --git a/src/slskd/Core/State.cs b/src/slskd/Core/State.cs index 7492a096..e009805a 100644 --- a/src/slskd/Core/State.cs +++ b/src/slskd/Core/State.cs @@ -61,7 +61,6 @@ namespace slskd public bool IsConnected => State.HasFlag(SoulseekClientStates.Connected); public bool IsLoggedIn => State.HasFlag(SoulseekClientStates.LoggedIn); public bool IsTransitioning => State.HasFlag(SoulseekClientStates.Connecting) || State.HasFlag(SoulseekClientStates.Disconnecting) || State.HasFlag(SoulseekClientStates.LoggingIn); - public bool AttemptingReconnect { get; init; } } public record UserState -- cgit v1.2.3 From f22f333391f45e6d93c0df014fd06b543449e7f3 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 10 Jul 2022 12:22:05 -0500 Subject: add ConnectionWatchdog to DI --- src/slskd/Program.cs | 2 ++ 1 file changed, 2 insertions(+) (limited to 'src') diff --git a/src/slskd/Program.cs b/src/slskd/Program.cs index df1fb55c..ae4f2015 100644 --- a/src/slskd/Program.cs +++ b/src/slskd/Program.cs @@ -446,6 +446,8 @@ namespace slskd services.AddSingleton(); services.AddHostedService(p => p.GetRequiredService()); + services.AddSingleton(); + services.AddDbContext("search.db"); services.AddSingleton(); -- cgit v1.2.3 From 623702e58199131afe8ad58c19d0feabb066c211 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 10 Jul 2022 12:22:50 -0500 Subject: start connection watchdog on qualifying disconnect, stop on connect --- src/slskd/Application.cs | 26 +++++++------------------- 1 file changed, 7 insertions(+), 19 deletions(-) (limited to 'src') diff --git a/src/slskd/Application.cs b/src/slskd/Application.cs index 2c1a63af..af553475 100644 --- a/src/slskd/Application.cs +++ b/src/slskd/Application.cs @@ -76,6 +76,7 @@ namespace slskd IOptionsMonitor optionsMonitor, IManagedState state, ISoulseekClient soulseekClient, + IConnectionWatchdog connectionWatchdog, ITransferTracker transferTracker, ITransferService transferService, IBrowseTracker browseTracker, @@ -139,11 +140,14 @@ namespace slskd Client.DistributedNetworkStateChanged += Client_DistributedNetworkStateChanged; Client.DownloadDenied += (e, args) => Log.Information("Download of {Filename} from {Username} was denied: {Message}", args.Filename, args.Username, args.Message); Client.DownloadFailed += (e, args) => Log.Information("Download of {Filename} from {Username} failed", args.Filename, args.Username); + + ConnectionWatchdog = connectionWatchdog; } private ISoulseekClient Client { get; set; } private IRoomService RoomService { get; set; } private IBrowseTracker BrowseTracker { get; set; } + private IConnectionWatchdog ConnectionWatchdog { get; } private IConversationTracker ConversationTracker { get; set; } private ILogger Log { get; set; } = Serilog.Log.ForContext(); private ConcurrentDictionary Loggers { get; } = new ConcurrentDictionary(); @@ -355,6 +359,7 @@ namespace slskd private void Client_Connected(object sender, EventArgs e) { + ConnectionWatchdog.Stop(); Log.Information("Connected to the Soulseek server"); } @@ -402,28 +407,12 @@ namespace slskd } else if (args.Exception is KickedFromServerException) { - Log.Error("Disconnected from the Soulseek server: another client logged in using the username {Username}", Client.Username); + Log.Error("Disconnected from the Soulseek server: another client logged in using the same username"); } else { Log.Error("Disconnected from the Soulseek server: {Message}", args.Exception?.Message ?? args.Message); - - if (string.IsNullOrEmpty(Options.Soulseek.Username) || string.IsNullOrEmpty(Options.Soulseek.Password)) - { - Log.Warning($"Not reconnecting to the Soulseek server; username and/or password invalid. Specify valid credentials and manually connect, or update config and restart."); - return; - } - - // none of the conditions that would prevent a reconnect attempt have been met - // update the state to set AttemptingReconnect to true, which will cause the IConnectionMonitor - // to begin the reconnect sequence - State.SetValue(state => state with - { - Server = state.Server with - { - AttemptingReconnect = true, - }, - }); + ConnectionWatchdog.Start(); } } @@ -503,7 +492,6 @@ namespace slskd Address = Client.Address, IPEndPoint = Client.IPEndPoint, State = Client.State, - AttemptingReconnect = Client.State.HasFlag(SoulseekClientStates.Connected) ? false : state.Server.AttemptingReconnect, }, User = state.User with { -- cgit v1.2.3 From 55d3940da06c6e69a77ef51660cb7c00b568daf6 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 10 Jul 2022 12:23:37 -0500 Subject: synchronize retries, retry in a loop --- src/slskd/Core/ConnectionWatchdog.cs | 140 ++++++++++++++++++++++++++--------- 1 file changed, 107 insertions(+), 33 deletions(-) (limited to 'src') diff --git a/src/slskd/Core/ConnectionWatchdog.cs b/src/slskd/Core/ConnectionWatchdog.cs index 633b1f70..931155cf 100644 --- a/src/slskd/Core/ConnectionWatchdog.cs +++ b/src/slskd/Core/ConnectionWatchdog.cs @@ -20,18 +20,47 @@ using Microsoft.Extensions.Options; namespace slskd { using System; + using System.Threading; using System.Threading.Tasks; using Serilog; using Soulseek; + /// + /// Monitors the connection to the Soulseek server and reconnects with exponential backoff, if necessary. + /// public interface IConnectionWatchdog : IDisposable { + /// + /// Gets a value indicating whether the watchdog is monitoring the server connection. + /// + bool IsEnabled { get; } + + /// + /// Starts monitoring the server connection. + /// + /// This should be called when the connection is disconnected. + void Start(); + + /// + /// Stops monitoring the server connection. + /// + /// This should be called when the application is reasonably certain that the connection is connected. + void Stop(); } + /// + /// Monitors the connection to the Soulseek network and reconnects with exponential backoff, if necessary. + /// public class ConnectionWatchdog : IConnectionWatchdog { private static readonly int ReconnectMaxDelayMilliseconds = 300000; // 5 minutes + /// + /// Initializes a new instance of the class. + /// + /// + /// + /// public ConnectionWatchdog( ISoulseekClient soulseekClient, IOptionsMonitor optionsMonitor, @@ -41,37 +70,65 @@ namespace slskd Options = optionsMonitor; State = state; - WatchDogTimer = new System.Timers.Timer() + WatchdogTimer = new System.Timers.Timer() { - Interval = 250, + Interval = 100, AutoReset = true, - Enabled = true, + Enabled = false, }; - WatchDogTimer.Elapsed += (sender, args) => _ = AttemptReconnect(); + WatchdogTimer.Elapsed += (sender, args) => _ = AttemptReconnect(); } - private int Attempts { get; set; } + /// + /// Gets a value indicating whether the watchdog is monitoring the server connection. + /// + public bool IsEnabled => WatchdogTimer.Enabled; + private ISoulseekClient Client { get; } private bool Disposed { get; set; } private ILogger Log { get; } = Serilog.Log.ForContext(); private IOptionsMonitor Options { get; set; } private IStateMonitor State { get; } - private System.Timers.Timer WatchDogTimer { get; } + private SemaphoreSlim SyncRoot { get; } = new SemaphoreSlim(1, 1); + private System.Timers.Timer WatchdogTimer { get; } + /// + /// Disposes this instance. + /// public void Dispose() { Dispose(disposing: true); GC.SuppressFinalize(this); } + /// + /// Starts monitoring the server connection. + /// + /// This should be called when the connection is disconnected. + public void Start() + { + WatchdogTimer.Enabled = true; + _ = AttemptReconnect(); + } + + /// + /// Stops monitoring the server connection. + /// + /// This should be called when the application is reasonably certain that the connection is connected. + public void Stop() => WatchdogTimer.Enabled = false; + + /// + /// Disposes this instance. + /// + /// protected virtual void Dispose(bool disposing) { if (!Disposed) { if (disposing) { - WatchDogTimer?.Dispose(); + WatchdogTimer?.Dispose(); } Disposed = true; @@ -80,33 +137,50 @@ namespace slskd private async Task AttemptReconnect() { - if (State.CurrentValue.Server.IsConnected || !State.CurrentValue.Server.AttemptingReconnect) - { - return; - } - - var (delay, jitter) = Compute.ExponentialBackoffDelay( - iteration: Attempts, - maxDelayInMilliseconds: ReconnectMaxDelayMilliseconds); - - var approximateDelay = (int)Math.Ceiling((double)(delay + jitter) / 1000); - Log.Information($"Waiting about {(approximateDelay == 1 ? "a second" : $"{approximateDelay} seconds")} before reconnecting"); - - await Task.Delay(delay + jitter); - - Log.Information("Attempting to reconnect (#{Attempts})...", Attempts); - - try - { - // reconnect with the latest configuration values we have for username and password, instead of the options that - // were captured at startup. if a user has updated these values prior to the disconnect, the changes will take - // effect now. - await Client.ConnectAsync(Options.CurrentValue.Soulseek.Username, Options.CurrentValue.Soulseek.Password); - } - catch (Exception ex) + if (await SyncRoot.WaitAsync(0)) { - Attempts++; - Log.Error("Failed to reconnect: {Message}", ex.Message); + try + { + if (State.CurrentValue.Server.IsConnected) + { + return; + } + + var attempts = 1; + + while (true) + { + var (delay, jitter) = Compute.ExponentialBackoffDelay( + iteration: attempts, + maxDelayInMilliseconds: ReconnectMaxDelayMilliseconds); + + var approximateDelay = (int)Math.Ceiling((double)(delay + jitter) / 1000); + Log.Information($"Waiting about {(approximateDelay == 1 ? "a second" : $"{approximateDelay} seconds")} before reconnecting"); + await Task.Delay(delay + jitter); + + Log.Information("Attempting to reconnect (#{Attempts})...", attempts); + + try + { + // reconnect with the latest configuration values we have for username and password, instead of the + // options that were captured at startup. if a user has updated these values prior to the disconnect, + // the changes will take effect now. + await Client.ConnectAsync(Options.CurrentValue.Soulseek.Username, Options.CurrentValue.Soulseek.Password); + + Log.Information("Successfully reconnected after #{Attempts}", attempts); + break; + } + catch (Exception ex) + { + attempts++; + Log.Error("Failed to reconnect: {Message}", ex.Message); + } + } + } + finally + { + SyncRoot.Release(); + } } } } -- cgit v1.2.3 From 2c327ec95b55721959d9e521a1205e8deedf15bb Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Mon, 11 Jul 2022 10:14:30 -0500 Subject: remove log after reconnect --- src/slskd/Core/ConnectionWatchdog.cs | 2 -- 1 file changed, 2 deletions(-) (limited to 'src') diff --git a/src/slskd/Core/ConnectionWatchdog.cs b/src/slskd/Core/ConnectionWatchdog.cs index 931155cf..6a48c0e4 100644 --- a/src/slskd/Core/ConnectionWatchdog.cs +++ b/src/slskd/Core/ConnectionWatchdog.cs @@ -166,8 +166,6 @@ namespace slskd // options that were captured at startup. if a user has updated these values prior to the disconnect, // the changes will take effect now. await Client.ConnectAsync(Options.CurrentValue.Soulseek.Username, Options.CurrentValue.Soulseek.Password); - - Log.Information("Successfully reconnected after #{Attempts}", attempts); break; } catch (Exception ex) -- cgit v1.2.3