diff options
| author | JP Dillingham <jp@dillingham.me> | 2023-01-08 13:30:10 -0600 |
|---|---|---|
| committer | GitHub <noreply@github.com> | 2023-01-08 13:30:10 -0600 |
| commit | bbbde98f571dc7cd7a0ed35ef7846cc177372920 (patch) | |
| tree | d711d033bf604444519f98d9854b67d412efcacf /src/slskd/Relay | |
| parent | 9bb9c17312742adb65b37fe84bd64e7267defcd8 (diff) | |
| parent | 5133ac9eabc1ddf195002807f97a95ad0ab8d9a0 (diff) | |
| download | slskd-bbbde98f571dc7cd7a0ed35ef7846cc177372920.tar.gz | |
Merge branch 'master' into relay-docs
Diffstat (limited to 'src/slskd/Relay')
| -rw-r--r-- | src/slskd/Relay/API/Controllers/RelayController.cs | 34 | ||||
| -rw-r--r-- | src/slskd/Relay/DummyRelayClient.cs | 18 | ||||
| -rw-r--r-- | src/slskd/Relay/RelayClient.cs | 461 | ||||
| -rw-r--r-- | src/slskd/Relay/RelayService.cs | 10 |
4 files changed, 289 insertions, 234 deletions
diff --git a/src/slskd/Relay/API/Controllers/RelayController.cs b/src/slskd/Relay/API/Controllers/RelayController.cs index d4fb4810..f6c6d778 100644 --- a/src/slskd/Relay/API/Controllers/RelayController.cs +++ b/src/slskd/Relay/API/Controllers/RelayController.cs @@ -21,6 +21,7 @@ namespace slskd.Relay { using System; using System.Collections.Generic; + using System.Diagnostics; using System.IO; using System.Linq; using System.Threading.Tasks; @@ -115,7 +116,7 @@ namespace slskd.Relay return BadRequest(); } - Log.Information("Handling file download for token {Token} from a caller claiming to be agent {Agent}", token, agentName); + Log.Information("Handling file download of {Filename} ({Token}) from a caller claiming to be agent {Agent}", filename, token, agentName); // note: the token remains valid after the validation attempt, unlike most other endpoints. // this is done to support retries @@ -127,9 +128,9 @@ namespace slskd.Relay var sourceFile = Path.Combine(OptionsMonitor.CurrentValue.Directories.Downloads, filename); - Log.Information("Agent {Agent} authenticated. Sending file {File}", agentName, filename); + Log.Information("Agent {Agent} authenticated for token {Token}. Sending file {Filename}", agentName, guid, filename); - var stream = new FileStream(Path.Combine(OptionsMonitor.CurrentValue.Directories.Downloads, filename), FileMode.Open); + var stream = new FileStream(sourceFile, FileMode.Open); return File(stream, "application/octet-stream"); } @@ -185,6 +186,16 @@ namespace slskd.Relay var contentDisposition = ContentDispositionHeaderValue.Parse(fileSection.ContentDisposition); filename = contentDisposition.FileName.Value; stream = fileSection.Body; + + if (string.IsNullOrEmpty(filename)) + { + throw new ArgumentException("Upload filename is null or empty"); + } + + if (stream == null || !stream.CanRead) + { + throw new ArgumentException("Unable to obtain stream from request"); + } } catch (Exception ex) { @@ -194,19 +205,19 @@ namespace slskd.Relay return BadRequest(); } - Log.Information("Handling file upload for token {Token} from a caller claiming to be agent {Agent}", token, agentName); + Log.Information("Handling file upload of {Filename} ({Token}) from a caller claiming to be agent {Agent}", filename, token, agentName); // agents must encrypt the Id they were given in the request with the secret they share with the controller, and // provide the encrypted value as the credential with the request. the validation below verifies a bunch of // things, including that the encrypted value matches the expected value. the goal here is to ensure that the // caller is the same caller that received the request, and that the caller knows the shared secret. - if (!Relay.TryValidateFileStreamResponseCredential(token: guid, agentName, filename, credential)) + if (!Relay.TryValidateFileStreamResponseCredential(token: guid, agentName: agentName, filename: filename, credential: credential)) { Log.Warning("Failed to authenticate file upload token {Token} from a caller claiming to be agent {Agent}", guid, agentName); return Unauthorized(); } - Log.Information("File upload of {Filename} ({Token}) from agent {Agent} validated and authenticated. Forwarding file stream.", filename, token, agentName); + Log.Information("Agent {Agent} authenticated for token {Token}. Forwarding file stream for {Filename}", agentName, guid, filename); // pass the stream back to the relay service, which will in turn pass it to the upload service, and use it to // feed data into the remote upload. await this call, it will complete when the upload is complete, one way or the other. @@ -269,6 +280,8 @@ namespace slskd.Relay return BadRequest(); } + Log.Information("Handling share upload ({Token}) from a caller claiming to be agent {Agent}", token, agentName); + if (!Relay.TryValidateShareUploadCredential(token: guid, agentName, credential)) { Log.Warning("Failed to authenticate share upload from caller claiming to be agent {Agent} using token {Token}", agentName, guid); @@ -280,14 +293,19 @@ namespace slskd.Relay try { - Log.Debug("Uploading share from {Agent} to {Filename}", agentName, temp); + Log.Information("Agent {Agent} authenticated for token {Token}. Beginning download of shares to {Filename}", agentName, guid, temp); + + var sw = new Stopwatch(); + sw.Start(); using var outputStream = new FileStream(temp, FileMode.CreateNew, FileAccess.Write); using var inputStream = database.OpenReadStream(); await inputStream.CopyToAsync(outputStream); - Log.Debug("Upload of share from {Agent} to {Filename} complete", agentName, temp); + sw.Stop(); + + Log.Information("Download of shares from {Agent} ({Token}) complete ({Size} in {Duration}ms)", agentName, guid, ((double)inputStream.Length).SizeSuffix(), sw.ElapsedMilliseconds); await Relay.HandleShareUpload(agentName, id: guid, shares, temp); diff --git a/src/slskd/Relay/DummyRelayClient.cs b/src/slskd/Relay/DummyRelayClient.cs index dca4f808..c5bd477c 100644 --- a/src/slskd/Relay/DummyRelayClient.cs +++ b/src/slskd/Relay/DummyRelayClient.cs @@ -24,12 +24,26 @@ namespace slskd.Relay { public IStateMonitor<RelayClientState> StateMonitor => new ManagedState<RelayClientState>(); - public void Dispose() { } + private bool Disposed { get; set; } + + public void Dispose() + { + Dispose(disposing: true); + System.GC.SuppressFinalize(this); + } public Task StartAsync(CancellationToken cancellationToken = default) => Task.CompletedTask; public Task StopAsync(CancellationToken cancellationToken = default) => Task.CompletedTask; public Task SynchronizeAsync(CancellationToken cancellationToken = default) => Task.CompletedTask; + + protected virtual void Dispose(bool disposing) + { + if (!Disposed) + { + Disposed = true; + } + } } -} +}
\ No newline at end of file diff --git a/src/slskd/Relay/RelayClient.cs b/src/slskd/Relay/RelayClient.cs index d6bde1d7..5865c6f6 100644 --- a/src/slskd/Relay/RelayClient.cs +++ b/src/slskd/Relay/RelayClient.cs @@ -94,20 +94,29 @@ namespace slskd.Relay /// </summary> public IStateMonitor<RelayClientState> StateMonitor { get; } - private ManagedState<RelayClientState> State { get; } = new(); - private IShareService Shares { get; } private SemaphoreSlim ConfigurationSyncRoot { get; } = new SemaphoreSlim(1, 1); - private SemaphoreSlim StateSyncRoot { get; } = new SemaphoreSlim(1, 1); - private string LastOptionsHash { get; set; } - private IOptionsMonitor<Options> OptionsMonitor { get; } + private bool Disposed { get; set; } private IHttpClientFactory HttpClientFactory { get; } private HubConnection HubConnection { get; set; } - private bool StartRequested { get; set; } - private CancellationTokenSource StartCancellationTokenSource { get; set; } + private string LastOptionsHash { get; set; } private ILogger Log { get; } = Serilog.Log.ForContext<RelayClient>(); private bool LoggedIn { get; set; } private TaskCompletionSource LoggedInTaskCompletionSource { get; set; } - private bool Disposed { get; set; } + private IOptionsMonitor<Options> OptionsMonitor { get; } + private IShareService Shares { get; } + private CancellationTokenSource StartCancellationTokenSource { get; set; } + private bool StartRequested { get; set; } + private ManagedState<RelayClientState> State { get; } = new(); + private SemaphoreSlim StateSyncRoot { get; } = new SemaphoreSlim(1, 1); + + /// <summary> + /// Disposes this instance. + /// </summary> + public void Dispose() + { + Dispose(disposing: true); + GC.SuppressFinalize(this); + } /// <summary> /// Starts the client and connects to the controller. @@ -141,7 +150,37 @@ namespace slskd.Relay // retry indefinitely await Retry.Do( - task: () => HubConnection.StartAsync(StartCancellationTokenSource.Token), + task: async () => + { + await HubConnection.StartAsync(StartCancellationTokenSource.Token); + + State.SetValue(_ => TranslateState(HubConnection.State)); + Log.Information("Relay controller connection established. Awaiting authentication..."); + + await LoggedInTaskCompletionSource.Task; + + LoggedIn = true; + + Log.Information("Authenticated. Uploading shares..."); + + try + { + // give the controller time to register the login; there's a race condition here + // that should be extremely unlikely, but i've seen it when debugging. + await Task.Delay(500); + + await UploadSharesAsync(); + } + catch (Exception ex) + { + Log.Error(ex, ex.Message); + Log.Error("Disconnecting from the relay controller"); + await StopAsync(); + throw; + } + + Log.Information("Shares uploaded. Ready to upload files."); + }, isRetryable: (attempts, ex) => true, onFailure: (attempts, ex) => { @@ -151,29 +190,6 @@ namespace slskd.Relay maxAttempts: int.MaxValue, maxDelayInMilliseconds: 30000, StartCancellationTokenSource.Token); - - State.SetValue(_ => TranslateState(HubConnection.State)); - Log.Information("Relay controller connection established. Awaiting authentication..."); - - await LoggedInTaskCompletionSource.Task; - - LoggedIn = true; - - Log.Information("Authenticated. Uploading shares..."); - - try - { - await UploadSharesAsync(); - } - catch (Exception ex) - { - Log.Error(ex, ex.Message); - Log.Error("Disconnecting from the relay controller"); - await StopAsync(); - throw; - } - - Log.Information("Shares uploaded. Ready to upload files."); } finally { @@ -211,85 +227,172 @@ namespace slskd.Relay return UploadSharesAsync(cancellationToken); } - private RelayClientState TranslateState(HubConnectionState hub) => hub switch + /// <summary> + /// Disposes this instance. + /// </summary> + /// <param name="disposing"></param> + protected virtual void Dispose(bool disposing) { - HubConnectionState.Disconnected => RelayClientState.Disconnected, - HubConnectionState.Connected => RelayClientState.Connected, - HubConnectionState.Connecting => RelayClientState.Connecting, - HubConnectionState.Reconnecting => RelayClientState.Reconnecting, - _ => throw new ArgumentException($"Unexpected HubConnectionState {hub}"), - }; + if (!Disposed) + { + if (disposing) + { + _ = HubConnection?.DisposeAsync(); + } - private async Task UploadSharesAsync(CancellationToken cancellationToken = default) + Disposed = true; + } + } + + private string ComputeCredential(string token) { - if (!LoggedIn) + var options = OptionsMonitor.CurrentValue; + + var key = Pbkdf2.GetKey(options.Relay.Controller.Secret, options.InstanceName, 48); + var tokenBytes = System.Text.Encoding.UTF8.GetBytes(token); + + return Aes.Encrypt(tokenBytes, key).ToBase62(); + } + + private string ComputeCredential(Guid token) => ComputeCredential(token.ToString()); + + private void Configure(Options options) + { + var mode = options.Relay.Mode.ToEnum<RelayMode>(); + + if (mode != RelayMode.Agent && mode != RelayMode.Debug) { return; } - var temp = Path.Combine(Path.GetTempPath(), Program.AppName, $"share_backup_{Path.GetRandomFileName()}.db"); - - Directory.CreateDirectory(Path.Combine(Path.GetTempPath(), Program.AppName)); + ConfigurationSyncRoot.Wait(); try { - Log.Debug("Backing up shares to {Filename}", temp); - await Shares.DumpAsync(temp); - Log.Debug("Share backup successful"); + var optionsHash = Compute.Sha1Hash(options.Relay.Controller.ToJson()); - Log.Debug("Requesting share upload token..."); - var token = await HubConnection.InvokeAsync<Guid>(nameof(RelayHub.BeginShareUpload)); - Log.Debug("Share upload token {Token}", token); + if (optionsHash == LastOptionsHash) + { + return; + } - var stream = new FileStream(temp, FileMode.Open, FileAccess.Read); + Log.Debug("Relay options changed. Reconfiguring..."); - using var request = new HttpRequestMessage(HttpMethod.Post, $"api/v0/relay/shares/{token}"); + // if the client is attempting a connection, cancel it it's going to be dropped when we create a new instance, but + // we need the retry loop around connection to stop. + StartCancellationTokenSource?.Cancel(); - request.Headers.Add("X-API-Key", OptionsMonitor.CurrentValue.Relay.Controller.ApiKey); - request.Headers.Add("X-Relay-Agent", OptionsMonitor.CurrentValue.InstanceName); - request.Headers.Add("X-Relay-Credential", ComputeCredential(token)); + HubConnection = new HubConnectionBuilder() + .WithUrl($"{options.Relay.Controller.Address}/hub/relay", builder => + { + builder.AccessTokenProvider = () => Task.FromResult(options.Relay.Controller.ApiKey); + builder.HttpMessageHandlerFactory = (message) => + { + if (message is HttpClientHandler clientHandler && options.Relay.Controller.IgnoreCertificateErrors) + { + clientHandler.ServerCertificateCustomValidationCallback += (_, _, _, _) => true; + } - using var content = new MultipartFormDataContent - { - { new StringContent(Shares.LocalHost.Shares.ToJson()), "shares" }, - { new StreamContent(stream), "database", "shares" }, - }; + return message; + }; + }) + .WithAutomaticReconnect(new ControllerRetryPolicy(0, 1, 3, 10, 30, 60)) + .Build(); - request.Content = content; + HubConnection.Reconnected += HubConnection_Reconnected; + HubConnection.Reconnecting += HubConnection_Reconnecting; + HubConnection.Closed += HubConnection_Closed; - var size = ((double)stream.Length).SizeSuffix(); - var sw = new Stopwatch(); - sw.Start(); + HubConnection.On<string, long, Guid>(nameof(IRelayHub.RequestFileUpload), HandleFileUploadRequest); + HubConnection.On<string, Guid>(nameof(IRelayHub.RequestFileInfo), HandleFileInfoRequest); + HubConnection.On<string>(nameof(IRelayHub.Challenge), HandleAuthenticationChallenge); + HubConnection.On<string, Guid>(nameof(IRelayHub.NotifyFileDownloadCompleted), HandleNotifyFileDownloadCompleted); - Log.Information("Beginning upload of shares ({Size})", size); - Log.Debug("Shares: {Shares}", Shares.LocalHost.Shares.ToJson()); - var response = await CreateHttpClient().SendAsync(request, cancellationToken); + LastOptionsHash = optionsHash; - if (!response.IsSuccessStatusCode) + Log.Debug("Relay options reconfigured"); + + // if start was requested (if StartAsync() was called externally), restart after re-configuration + if (StartRequested) { - throw new RelayException($"Failed to upload shares to relay controller: {response.StatusCode}"); + Log.Information("Reconnecting the relay controller connection..."); + _ = StartAsync(); } - - sw.Stop(); - Log.Information("Upload of shares succeeded ({Size} in {Duration}ms)", size, sw.ElapsedMilliseconds); } finally { - File.Delete(temp); + ConfigurationSyncRoot.Release(); } } - private string ComputeCredential(string token) + private HttpClient CreateHttpClient() { - var options = OptionsMonitor.CurrentValue; + var options = OptionsMonitor.CurrentValue.Relay.Controller; + HttpClient client; - var key = Pbkdf2.GetKey(options.Relay.Controller.Secret, options.InstanceName, 48); - var tokenBytes = System.Text.Encoding.UTF8.GetBytes(token); + if (options.IgnoreCertificateErrors) + { + client = new HttpClient(new HttpClientHandler() + { + ClientCertificateOptions = ClientCertificateOption.Manual, + ServerCertificateCustomValidationCallback = (_, _, _, _) => true, + }); + } + else + { + client = new HttpClient(); + } - return Aes.Encrypt(tokenBytes, key).ToBase62(); + client.Timeout = TimeSpan.FromMilliseconds(int.MaxValue); + client.BaseAddress = new(options.Address); + return client; } - private string ComputeCredential(Guid token) => ComputeCredential(token.ToString()); + private async Task HandleAuthenticationChallenge(string challengeToken) + { + try + { + Log.Debug("Relay controller sent an authentication challenge"); + + var options = OptionsMonitor.CurrentValue; + + var agent = options.InstanceName; + var response = ComputeCredential(challengeToken); + + Log.Debug("Logging in..."); + await HubConnection.InvokeAsync(nameof(RelayHub.Login), agent, response); + Log.Debug("Login succeeded."); + LoggedInTaskCompletionSource?.TrySetResult(); + } + catch (UnauthorizedAccessException) + { + await HubConnection.StopAsync(); + Log.Error("Relay controller authentication failed. Check configuration."); + } + catch (Exception ex) + { + Log.Error(ex, "Failed to handle authentication challenge: {Message}", ex.Message); + } + } + + private async Task HandleFileInfoRequest(string filename, Guid id) + { + Log.Information("Relay controller requested file info for {Filename} with ID {Id}", filename, id); + + try + { + var (_, localFilename) = await Shares.ResolveFileAsync(filename); + + var localFileInfo = new FileInfo(localFilename); + + await HubConnection.InvokeAsync(nameof(RelayHub.ReturnFileInfo), id, localFileInfo.Exists, localFileInfo.Length); + } + catch (Exception ex) + { + Log.Error(ex, "Failed to handle file info request: {Message}", ex.Message); + await HubConnection.InvokeAsync(nameof(RelayHub.ReturnFileInfo), id, false, 0); + } + } private Task HandleFileUploadRequest(string filename, long startOffset, Guid token) { @@ -321,8 +424,6 @@ namespace slskd.Relay using var content = new MultipartFormDataContent { - { new StringContent(OptionsMonitor.CurrentValue.InstanceName), "name" }, - { new StringContent(ComputeCredential(token)), "credential" }, { new StreamContent(stream), "file", filename }, }; @@ -352,52 +453,6 @@ namespace slskd.Relay return Task.CompletedTask; } - private async Task HandleFileInfoRequest(string filename, Guid id) - { - Log.Information("Relay controller requested file info for {Filename} with ID {Id}", filename, id); - - try - { - var (_, localFilename) = await Shares.ResolveFileAsync(filename); - - var localFileInfo = new FileInfo(localFilename); - - await HubConnection.InvokeAsync(nameof(RelayHub.ReturnFileInfo), id, localFileInfo.Exists, localFileInfo.Length); - } - catch (Exception ex) - { - Log.Error(ex, "Failed to handle file info request: {Message}", ex.Message); - await HubConnection.InvokeAsync(nameof(RelayHub.ReturnFileInfo), id, false, 0); - } - } - - private async Task HandleAuthenticationChallenge(string challengeToken) - { - try - { - Log.Debug("Relay controller sent an authentication challenge"); - - var options = OptionsMonitor.CurrentValue; - - var agent = options.InstanceName; - var response = ComputeCredential(challengeToken); - - Log.Debug("Logging in..."); - await HubConnection.InvokeAsync(nameof(RelayHub.Login), agent, response); - Log.Debug("Login succeeded."); - LoggedInTaskCompletionSource?.TrySetResult(); - } - catch (UnauthorizedAccessException) - { - await HubConnection.StopAsync(); - Log.Error("Relay controller authentication failed. Check configuration."); - } - catch (Exception ex) - { - Log.Error(ex, "Failed to handle authentication challenge: {Message}", ex.Message); - } - } - private Task HandleNotifyFileDownloadCompleted(string filename, Guid token) { if (!OptionsMonitor.CurrentValue.Relay.Controller.Downloads) @@ -413,11 +468,15 @@ namespace slskd.Relay if (OptionsMonitor.CurrentValue.Relay.Mode.ToEnum<RelayMode>() == RelayMode.Debug) { - // if we're debugging, we're referencing the same file for both the controller and agent - // which will lead to an access violation. prefix the destination file to avoid this. + // if we're debugging, we're referencing the same file for both the controller and agent which will lead to an + // access violation. prefix the destination file to avoid this. destinationFile = Path.Combine(OptionsMonitor.CurrentValue.Directories.Downloads, $"{filename}.relayed"); } + // if the controller is Windows and the agent is Linux or vice versa, we need to translate the filename to the + // local OS or we're going to get funny results when we go to write the file + destinationFile = destinationFile.LocalizePath(); + await Retry.Do(task: async () => { using var request = new HttpRequestMessage(HttpMethod.Get, $"api/v0/relay/downloads/{token}"); @@ -457,118 +516,93 @@ namespace slskd.Relay return Task.CompletedTask; } - private Task HubConnection_Reconnecting(Exception arg) - { - Log.Warning("Relay controller connection reconnecting: {Message}", arg.Message); - LoggedIn = false; - State.SetValue(_ => TranslateState(HubConnection.State)); - return Task.CompletedTask; - } - private async Task HubConnection_Reconnected(string arg) { Log.Warning("Relay 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(); } - private HttpClient CreateHttpClient() + private Task HubConnection_Reconnecting(Exception arg) { - var options = OptionsMonitor.CurrentValue.Relay.Controller; - HttpClient client; - - if (options.IgnoreCertificateErrors) - { - client = new HttpClient(new HttpClientHandler() - { - ClientCertificateOptions = ClientCertificateOption.Manual, - ServerCertificateCustomValidationCallback = (_, _, _, _) => true, - }); - } - else - { - client = new HttpClient(); - } - - client.Timeout = TimeSpan.FromMilliseconds(int.MaxValue); - client.BaseAddress = new(options.Address); - return client; + Log.Warning("Relay controller connection reconnecting: {Message}", arg.Message); + LoggedIn = false; + State.SetValue(_ => TranslateState(HubConnection.State)); + return Task.CompletedTask; } - private void Configure(Options options) + private RelayClientState TranslateState(HubConnectionState hub) => hub switch { - var mode = options.Relay.Mode.ToEnum<RelayMode>(); + HubConnectionState.Disconnected => RelayClientState.Disconnected, + HubConnectionState.Connected => RelayClientState.Connected, + HubConnectionState.Connecting => RelayClientState.Connecting, + HubConnectionState.Reconnecting => RelayClientState.Reconnecting, + _ => throw new ArgumentException($"Unexpected HubConnectionState {hub}"), + }; - if (mode != RelayMode.Agent && mode != RelayMode.Debug) + private async Task UploadSharesAsync(CancellationToken cancellationToken = default) + { + if (!LoggedIn) { return; } - ConfigurationSyncRoot.Wait(); + var temp = Path.Combine(Path.GetTempPath(), Program.AppName, $"share_backup_{Path.GetRandomFileName()}.db"); + + Directory.CreateDirectory(Path.Combine(Path.GetTempPath(), Program.AppName)); try { - var optionsHash = Compute.Sha1Hash(options.Relay.Controller.ToJson()); - - if (optionsHash == LastOptionsHash) - { - return; - } + Log.Debug("Backing up shares to {Filename}", temp); + await Shares.DumpAsync(temp); + Log.Debug("Share backup successful"); - Log.Debug("Relay options changed. Reconfiguring..."); + Log.Debug("Requesting share upload token..."); + var token = await HubConnection.InvokeAsync<Guid>(nameof(RelayHub.BeginShareUpload)); + Log.Debug("Share upload token {Token}", token); - // if the client is attempting a connection, cancel it - // it's going to be dropped when we create a new instance, but we need - // the retry loop around connection to stop. - StartCancellationTokenSource?.Cancel(); + var stream = new FileStream(temp, FileMode.Open, FileAccess.Read); - HubConnection = new HubConnectionBuilder() - .WithUrl($"{options.Relay.Controller.Address}/hub/relay", builder => - { - builder.AccessTokenProvider = () => Task.FromResult(options.Relay.Controller.ApiKey); - builder.HttpMessageHandlerFactory = (message) => - { - if (message is HttpClientHandler clientHandler && options.Relay.Controller.IgnoreCertificateErrors) - { - clientHandler.ServerCertificateCustomValidationCallback += (_, _, _, _) => true; - } + using var request = new HttpRequestMessage(HttpMethod.Post, $"api/v0/relay/shares/{token}"); - return message; - }; - }) - .WithAutomaticReconnect(new ControllerRetryPolicy(0, 1, 3, 10, 30, 60)) - .Build(); + request.Headers.Add("X-API-Key", OptionsMonitor.CurrentValue.Relay.Controller.ApiKey); + request.Headers.Add("X-Relay-Agent", OptionsMonitor.CurrentValue.InstanceName); + request.Headers.Add("X-Relay-Credential", ComputeCredential(token)); - HubConnection.Reconnected += HubConnection_Reconnected; - HubConnection.Reconnecting += HubConnection_Reconnecting; - HubConnection.Closed += HubConnection_Closed; + using var content = new MultipartFormDataContent + { + { new StringContent(Shares.LocalHost.Shares.ToJson()), "shares" }, + { new StreamContent(stream), "database", "shares" }, + }; - HubConnection.On<string, long, Guid>(nameof(IRelayHub.RequestFileUpload), HandleFileUploadRequest); - HubConnection.On<string, Guid>(nameof(IRelayHub.RequestFileInfo), HandleFileInfoRequest); - HubConnection.On<string>(nameof(IRelayHub.Challenge), HandleAuthenticationChallenge); - HubConnection.On<string, Guid>(nameof(IRelayHub.NotifyFileDownloadCompleted), HandleNotifyFileDownloadCompleted); + request.Content = content; - LastOptionsHash = optionsHash; + var size = ((double)stream.Length).SizeSuffix(); + var sw = new Stopwatch(); + sw.Start(); - Log.Debug("Relay options reconfigured"); + Log.Information("Beginning upload of shares ({Size})", size); + Log.Debug("Shares: {Shares}", Shares.LocalHost.Shares.ToJson()); + var response = await CreateHttpClient().SendAsync(request, cancellationToken); - // if start was requested (if StartAsync() was called externally), restart - // after re-configuration - if (StartRequested) + if (!response.IsSuccessStatusCode) { - Log.Information("Reconnecting the relay controller connection..."); - _ = StartAsync(); + throw new RelayException($"Failed to upload shares to relay controller: {response.StatusCode}"); } + + sw.Stop(); + Log.Information("Upload of shares succeeded ({Size} in {Duration}ms)", size, sw.ElapsedMilliseconds); } finally { - ConfigurationSyncRoot.Release(); + File.Delete(temp); } } - private class ControllerRetryPolicy : IRetryPolicy + private sealed class ControllerRetryPolicy : IRetryPolicy { public ControllerRetryPolicy(params int[] intervals) { @@ -582,24 +616,5 @@ namespace slskd.Relay 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); - } } -} +}
\ No newline at end of file diff --git a/src/slskd/Relay/RelayService.cs b/src/slskd/Relay/RelayService.cs index 47879b19..1dda50c2 100644 --- a/src/slskd/Relay/RelayService.cs +++ b/src/slskd/Relay/RelayService.cs @@ -456,7 +456,7 @@ namespace slskd.Relay var key = new WaitKey(nameof(GetFileInfoAsync), agentName, id); var wait = Waiter.Wait<(bool Exists, long Length)>(key, timeout); - Log.Information("Created wait {Key}", key); + Log.Debug("Created wait {Key}", key); try { @@ -624,6 +624,8 @@ namespace slskd.Relay /// <returns>The operation context.</returns> public Task HandleShareUpload(string agentName, Guid id, IEnumerable<Share> shares, string filename) { + Log.Information("Loading shares from agent {Agent}", agentName); + using var repository = ShareRepositoryFactory.CreateFromFile(filename); if (!repository.TryValidate(out var problems)) @@ -637,6 +639,8 @@ namespace slskd.Relay Shares.AddOrUpdateHost(new Host(agentName, shares)); + Log.Information("Shares from agent {Agent} ready.", agentName); + return Task.CompletedTask; } @@ -694,8 +698,12 @@ namespace slskd.Relay if (TryGetAgentRegistration(connectionId, out var found)) { + Log.Information("Unloading shares for agent {Agent}", found.Agent.Name); + Shares.TryRemoveHost(found.Agent.Name); removed = RegisteredAgentDictionary.TryRemove(found.Agent.Name, out record); + + Log.Information("Shares for agent {Agent} unloaded", found.Agent.Name); } State.SetValue(state => state with { Agents = RegisteredAgents }); |
