diff options
| author | JP Dillingham <jp@dillingham.me> | 2022-11-08 07:46:30 -0600 |
|---|---|---|
| committer | GitHub <noreply@github.com> | 2022-11-08 07:46:30 -0600 |
| commit | 7850ce245d51c80b0b05f59523d866dae2303669 (patch) | |
| tree | 7658ca859d3563c1b4f773d7bd1d707662fcd015 /src/slskd/Network | |
| parent | f03520a84f7ce90339f0339bb4bd7e7d0d34a856 (diff) | |
| parent | 74dbb69973035a93e2eda532bd6afe7e2f89d741 (diff) | |
| download | slskd-7850ce245d51c80b0b05f59523d866dae2303669.tar.gz | |
Merge pull request #739 from slskd/network-state
Add network state to application state
Diffstat (limited to 'src/slskd/Network')
| -rw-r--r-- | src/slskd/Network/API/Hubs/NetworkHub.cs | 2 | ||||
| -rw-r--r-- | src/slskd/Network/DummyNetworkClient.cs | 35 | ||||
| -rw-r--r-- | src/slskd/Network/NetworkClient.cs | 72 | ||||
| -rw-r--r-- | src/slskd/Network/NetworkClientState.cs | 27 | ||||
| -rw-r--r-- | src/slskd/Network/NetworkService.cs | 102 | ||||
| -rw-r--r-- | src/slskd/Network/Types/Agent.cs | 3 |
6 files changed, 224 insertions, 17 deletions
diff --git a/src/slskd/Network/API/Hubs/NetworkHub.cs b/src/slskd/Network/API/Hubs/NetworkHub.cs index 6e46a78b..9a54dde5 100644 --- a/src/slskd/Network/API/Hubs/NetworkHub.cs +++ b/src/slskd/Network/API/Hubs/NetworkHub.cs @@ -116,7 +116,7 @@ namespace slskd.Network } var remoteIp = Context.Features.Get<IHttpConnectionFeature>().RemoteIpAddress.ToString(); - var record = new Agent { Name = agent, ConnectedAt = DateTime.UtcNow, IPAddress = remoteIp }; + var record = new Agent { Name = agent, IPAddress = remoteIp }; Log.Information("Agent connection {Id} ({IP}) authenticated as agent {Agent}", Context.ConnectionId, remoteIp, agent); Network.RegisterAgent(Context.ConnectionId, record); diff --git a/src/slskd/Network/DummyNetworkClient.cs b/src/slskd/Network/DummyNetworkClient.cs new file mode 100644 index 00000000..f592f492 --- /dev/null +++ b/src/slskd/Network/DummyNetworkClient.cs @@ -0,0 +1,35 @@ +// <copyright file="DummyNetworkClient.cs" company="slskd Team"> +// 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/. +// </copyright> + +namespace slskd.Network +{ + using System.Threading; + using System.Threading.Tasks; + + public class DummyNetworkClient : INetworkClient + { + public IStateMonitor<NetworkClientState> StateMonitor => new ManagedState<NetworkClientState>(); + + public void Dispose() { } + + public Task StartAsync(CancellationToken cancellationToken = default) => Task.CompletedTask; + + public Task StopAsync(CancellationToken cancellationToken = default) => Task.CompletedTask; + + public Task SynchronizeAsync(CancellationToken cancellationToken = default) => Task.CompletedTask; + } +} diff --git a/src/slskd/Network/NetworkClient.cs b/src/slskd/Network/NetworkClient.cs index bf79a790..207494ff 100644 --- a/src/slskd/Network/NetworkClient.cs +++ b/src/slskd/Network/NetworkClient.cs @@ -32,9 +32,14 @@ namespace slskd.Network /// <summary> /// Network client (agent). /// </summary> - public interface INetworkClient + public interface INetworkClient : IDisposable { /// <summary> + /// Gets the client state. + /// </summary> + IStateMonitor<NetworkClientState> StateMonitor { get; } + + /// <summary> /// Starts the client and connects to the controller. /// </summary> /// <param name="cancellationToken"></param> @@ -52,7 +57,7 @@ namespace slskd.Network /// Synchronizes state with the controller. /// </summary> /// <returns>The operation context.</returns> - Task SynchronizeAsync(); + Task SynchronizeAsync(CancellationToken cancellationToken = default); } /// <summary> @@ -75,12 +80,20 @@ namespace slskd.Network HttpClientFactory = httpClientFactory; + StateMonitor = State; + OptionsMonitor = optionsMonitor; OptionsMonitor.OnChange(options => Configure(options)); Configure(OptionsMonitor.CurrentValue); } + /// <summary> + /// Gets the client state. + /// </summary> + public IStateMonitor<NetworkClientState> StateMonitor { get; } + + private ManagedState<NetworkClientState> State { get; } = new(); private IShareService Shares { get; } private SemaphoreSlim SyncRoot { get; } = new SemaphoreSlim(1, 1); private string LastOptionsHash { get; set; } @@ -92,6 +105,7 @@ namespace slskd.Network private ILogger Log { get; } = Serilog.Log.ForContext<NetworkClient>(); private bool LoggedIn { get; set; } private TaskCompletionSource LoggedInTaskCompletionSource { get; set; } + private bool Disposed { get; set; } /// <summary> /// Starts the client and connects to the controller. @@ -100,7 +114,9 @@ namespace slskd.Network /// <returns></returns> public async Task StartAsync(CancellationToken cancellationToken = default) { - if (OptionsMonitor.CurrentValue.Network.Mode.ToEnum<OperationMode>() != OperationMode.Agent && !OptionsMonitor.CurrentValue.Flags.DualNetworkMode) + var mode = OptionsMonitor.CurrentValue.Network.Mode.ToEnum<OperationMode>(); + + if (mode != OperationMode.Agent && mode != OperationMode.Debug) { throw new InvalidOperationException($"Network client can only be started when operation mode is {OperationMode.Agent}"); } @@ -111,15 +127,22 @@ namespace slskd.Network Log.Information("Attempting to connect to the network controller {Address}", OptionsMonitor.CurrentValue.Network.Controller.Address); + State.SetValue(_ => TranslateState(HubConnectionState.Connecting)); + // retry indefinitely await Retry.Do( task: () => HubConnection.StartAsync(StartCancellationTokenSource.Token), isRetryable: (attempts, ex) => true, - onFailure: (attempts, ex) => Log.Warning("Failed attempt #{Attempts} to connect to network controller: {Message}", attempts, ex.Message), + onFailure: (attempts, ex) => + { + Log.Debug(ex, "Network hub connection failure"); + Log.Warning("Failed attempt #{Attempts} to connect to network controller: {Message}", attempts, ex.Message); + }, maxAttempts: int.MaxValue, maxDelayInMilliseconds: 30000, StartCancellationTokenSource.Token); + State.SetValue(_ => TranslateState(HubConnection.State)); Log.Information("Network controller connection established. Awaiting authentication..."); await LoggedInTaskCompletionSource.Task; @@ -166,12 +189,21 @@ namespace slskd.Network /// Synchronizes state with the controller. /// </summary> /// <returns>The operation context.</returns> - public Task SynchronizeAsync() + public Task SynchronizeAsync(CancellationToken cancellationToken = default) { return UploadSharesAsync(); } - private async Task UploadSharesAsync() + private NetworkClientState TranslateState(HubConnectionState hub) => hub switch + { + HubConnectionState.Disconnected => NetworkClientState.Disconnected, + HubConnectionState.Connected => NetworkClientState.Connected, + HubConnectionState.Connecting => NetworkClientState.Connecting, + HubConnectionState.Reconnecting => NetworkClientState.Reconnecting, + _ => throw new ArgumentException($"Unexpected HubConnectionState {hub}"), + }; + + private async Task UploadSharesAsync(CancellationToken cancellationToken = default) { if (!LoggedIn) { @@ -207,7 +239,7 @@ namespace slskd.Network request.Content = content; Log.Information("Beginning upload of shares"); - var response = await CreateHttpClient().SendAsync(request); + var response = await CreateHttpClient().SendAsync(request, cancellationToken); if (!response.IsSuccessStatusCode) { @@ -338,6 +370,7 @@ namespace slskd.Network { Log.Warning("Network controller connection closed: {Message}", arg.Message); LoggedIn = false; + State.SetValue(_ => TranslateState(HubConnection.State)); return Task.CompletedTask; } @@ -345,6 +378,7 @@ namespace slskd.Network { Log.Warning("Network controller connection reconnecting: {Message}", arg.Message); LoggedIn = false; + State.SetValue(_ => TranslateState(HubConnection.State)); return Task.CompletedTask; } @@ -353,6 +387,7 @@ namespace slskd.Network Log.Warning("Network controller connection reconnected"); // todo: does this need to log in again? does it retain the same connection id? LoggedIn = true; + State.SetValue(_ => TranslateState(HubConnection.State)); await UploadSharesAsync(); } @@ -381,7 +416,9 @@ namespace slskd.Network private void Configure(Options options) { - if (options.Network.Mode.ToEnum<OperationMode>() != OperationMode.Agent && !options.Flags.DualNetworkMode) + var mode = options.Network.Mode.ToEnum<OperationMode>(); + + if (mode != OperationMode.Agent && mode != OperationMode.Debug) { return; } @@ -461,5 +498,24 @@ namespace slskd.Network return TimeSpan.FromSeconds(Intervals[Math.Min(retryContext.PreviousRetryCount, Intervals.Length - 1)]); } } + + protected virtual void Dispose(bool disposing) + { + if (!Disposed) + { + if (disposing) + { + _ = HubConnection?.DisposeAsync(); + } + + Disposed = true; + } + } + + public void Dispose() + { + Dispose(disposing: true); + GC.SuppressFinalize(this); + } } } diff --git a/src/slskd/Network/NetworkClientState.cs b/src/slskd/Network/NetworkClientState.cs new file mode 100644 index 00000000..ba1c1369 --- /dev/null +++ b/src/slskd/Network/NetworkClientState.cs @@ -0,0 +1,27 @@ +// <copyright file="NetworkClientState.cs" company="slskd Team"> +// 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/. +// </copyright> + +namespace slskd.Network +{ + public enum NetworkClientState + { + Disconnected, + Connected, + Connecting, + Reconnecting, + } +} diff --git a/src/slskd/Network/NetworkService.cs b/src/slskd/Network/NetworkService.cs index 56777f61..a0bbe85f 100644 --- a/src/slskd/Network/NetworkService.cs +++ b/src/slskd/Network/NetworkService.cs @@ -25,6 +25,7 @@ namespace slskd.Network using System.Collections.ObjectModel; using System.IO; using System.Linq; + using System.Net.Http; using System.Threading; using System.Threading.Tasks; using Microsoft.AspNetCore.SignalR; @@ -39,11 +40,21 @@ namespace slskd.Network public interface INetworkService { /// <summary> + /// Gets the network client (agent). + /// </summary> + INetworkClient Client { get; } + + /// <summary> /// Gets the collection of registered Agents. /// </summary> ReadOnlyCollection<Agent> RegisteredAgents { get; } /// <summary> + /// Gets the state monitor for the service. + /// </summary> + IStateMonitor<NetworkState> StateMonitor { get; } + + /// <summary> /// Generates a random authentication challenge token for the specified <paramref name="connectionId"/>. /// </summary> /// <remarks>The token is cached internally, and is only valid while it remains in the cache.</remarks> @@ -243,21 +254,41 @@ namespace slskd.Network IShareService shareService, IShareRepositoryFactory shareRepositoryFactory, IOptionsMonitor<Options> optionsMonitor, - IHubContext<NetworkHub, INetworkHub> networkHub) + IHubContext<NetworkHub, INetworkHub> networkHub, + IHttpClientFactory httpClientFactory, + INetworkClient networkClient = null) { Shares = shareService; ShareRepositoryFactory = shareRepositoryFactory; Waiter = waiter; NetworkHub = networkHub; + // wire up a dummy client so callers don't need to handle nulls + Client = networkClient ?? new DummyNetworkClient(); + + StateMonitor = State; + OptionsMonitor = optionsMonitor; + OptionsMonitor.OnChange(options => Configure(options)); + Configure(OptionsMonitor.CurrentValue); } /// <summary> + /// Gets the network client (agent). + /// </summary> + public INetworkClient Client { get; private set; } + + /// <summary> /// Gets the collection of registered Agents. /// </summary> public ReadOnlyCollection<Agent> RegisteredAgents => RegisteredAgentDictionary.Values.Select(v => v.Agent).ToList().AsReadOnly(); + /// <summary> + /// Gets the state monitor for the service. + /// </summary> + public IStateMonitor<NetworkState> StateMonitor { get; } + + private IHttpClientFactory HttpClientFactory { get; } private ILogger Log { get; } = Serilog.Log.ForContext<NetworkService>(); private MemoryCache MemoryCache { get; } = new MemoryCache(new MemoryCacheOptions()); private IHubContext<NetworkHub, INetworkHub> NetworkHub { get; set; } @@ -267,7 +298,11 @@ namespace slskd.Network private IShareRepositoryFactory ShareRepositoryFactory { get; } private IShareService Shares { get; } private IWaiter Waiter { get; } + private IManagedState<NetworkState> State { get; } = new ManagedState<NetworkState>(); private ConcurrentDictionary<WaitKey, Guid> WaitIdDictionary { get; } = new(); + private SemaphoreSlim SyncRoot { get; } = new SemaphoreSlim(1, 1); + private string LastOptionsHash { get; set; } + private string LastControllerOptionsHash { get; set; } /// <summary> /// Generates a random authentication challenge token for the specified <paramref name="connectionId"/>. @@ -553,7 +588,10 @@ namespace slskd.Network /// <param name="connectionId">The ID of the connection.</param> /// <param name="agent">The agent.</param> public void RegisterAgent(string connectionId, Agent agent) - => RegisteredAgentDictionary.AddOrUpdate(agent.Name, addValue: (connectionId, agent), updateValueFactory: (k, v) => (connectionId, agent)); + { + RegisteredAgentDictionary.AddOrUpdate(agent.Name, addValue: (connectionId, agent), updateValueFactory: (k, v) => (connectionId, agent)); + State.SetValue(state => state with { Agents = RegisteredAgents }); + } /// <summary> /// Safely attempts to close a stream obtained with <see cref="GetFileStreamAsync"/>. @@ -582,14 +620,17 @@ namespace slskd.Network /// <returns>A value indicating whether a registration was removed.</returns> public bool TryDeregisterAgent(string connectionId, out (string ConnectionId, Agent Agent) record) { + record = default; + var removed = false; + if (TryGetAgentRegistration(connectionId, out var found)) { Shares.TryRemoveHost(found.Agent.Name); - return RegisteredAgentDictionary.TryRemove(found.Agent.Name, out record); + removed = RegisteredAgentDictionary.TryRemove(found.Agent.Name, out record); } - record = default; - return false; + State.SetValue(state => state with { Agents = RegisteredAgents }); + return removed; } /// <summary> @@ -659,6 +700,57 @@ namespace slskd.Network return TryValidateCredential(token.ToString(), agentName, credential, GetShareTokenCacheKey(token)); } + private void Configure(Options options) + { + SyncRoot.Wait(); + + try + { + var optionsHash = Compute.Sha1Hash(options.Network.ToJson()); + var controllerOptionsHash = Compute.Sha1Hash(options.Network.Controller.ToJson()); + + if (optionsHash == LastOptionsHash || controllerOptionsHash == LastControllerOptionsHash) + { + return; + } + + var mode = options.Network.Mode.ToEnum<OperationMode>(); + + if (mode == OperationMode.Controller) + { + State.SetValue(state => state with + { + Mode = mode, + Agents = RegisteredAgents, + }); + } + else + { + // the controller changed. disconnect and throw away the client and create a new one + Client = new NetworkClient(Shares, OptionsMonitor, HttpClientFactory); + Client.StateMonitor.OnChange(clientState + => State.SetValue(state => state with { Controller = state.Controller with { State = clientState.Current } })); + + State.SetValue(state => state with + { + Mode = mode, + Controller = new NetworkControllerState() + { + Address = options.Network.Controller.Address, + State = Client.StateMonitor.CurrentValue, + }, + }); + } + + LastOptionsHash = optionsHash; + LastControllerOptionsHash = controllerOptionsHash; + } + finally + { + SyncRoot.Release(); + } + } + private string GetAuthTokenCacheKey(string connectionId) => $"{connectionId}.auth"; private string GetFileTokenCacheKey(string filename, Guid token) => $"{filename}.{token}.file"; diff --git a/src/slskd/Network/Types/Agent.cs b/src/slskd/Network/Types/Agent.cs index 999243c6..8c392210 100644 --- a/src/slskd/Network/Types/Agent.cs +++ b/src/slskd/Network/Types/Agent.cs @@ -17,12 +17,9 @@ namespace slskd.Network { - using System; - public record Agent { public string Name { get; init; } public string IPAddress { get; init; } - public DateTime ConnectedAt { get; init; } = DateTime.UtcNow; } } |
