From bccd6202d2d3d6e60b6a24423f0ab628b6d7dd39 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 9 Oct 2022 14:51:30 -0500 Subject: split network client from service --- src/slskd/Network/NetworkClient.cs | 243 +++++++++++++++++++++++++++++++++++++ 1 file changed, 243 insertions(+) create mode 100644 src/slskd/Network/NetworkClient.cs (limited to 'src/slskd/Network/NetworkClient.cs') diff --git a/src/slskd/Network/NetworkClient.cs b/src/slskd/Network/NetworkClient.cs new file mode 100644 index 00000000..be7b6a2c --- /dev/null +++ b/src/slskd/Network/NetworkClient.cs @@ -0,0 +1,243 @@ +// +// 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.Network +{ + using System; + using System.IO; + using System.Net.Http; + using System.Threading; + using System.Threading.Tasks; + using Microsoft.AspNetCore.SignalR.Client; + using Serilog; + using slskd.Cryptography; + + public interface INetworkClient + { + Task StartAsync(CancellationToken cancellationToken = default); + Task StopAsync(CancellationToken cancellationToken = default); + } + + public class NetworkClient : INetworkClient + { + public NetworkClient( + IOptionsMonitor optionsMonitor, + IHttpClientFactory httpClientFactory) + { + HttpClientFactory = httpClientFactory; + + OptionsMonitor = optionsMonitor; + OptionsMonitor.OnChange(options => Configure(options)); + + Configure(OptionsMonitor.CurrentValue); + } + + private SemaphoreSlim SyncRoot { get; } = new SemaphoreSlim(1, 1); + private string LastOptionsHash { get; set; } + private IOptionsMonitor OptionsMonitor { get; } + private IHttpClientFactory HttpClientFactory { get; } + private HttpClient HttpClient { get; set; } + private HubConnection HubConnection { get; set; } + private bool StartRequested { get; set; } + private CancellationTokenSource StartCancellationTokenSource { get; set; } + + public async Task StartAsync(CancellationToken cancellationToken = default) + { + if (OptionsMonitor.CurrentValue.Network.OperationMode.ToEnum() != NetworkOperationMode.Agent && !OptionsMonitor.CurrentValue.Flags.DualNetworkMode) + { + throw new InvalidOperationException($"Network client can only be started when operation mode is {NetworkOperationMode.Agent}"); + } + + StartCancellationTokenSource = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken); + StartRequested = true; + + Log.Information("Attempting to connect to the network controller {Address}", OptionsMonitor.CurrentValue.Network.Controller.Address); + + // 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), + maxAttempts: int.MaxValue, + maxDelayInMilliseconds: 30000, + StartCancellationTokenSource.Token); + + Log.Information("Network controller connection established"); + } + + public async Task StopAsync(CancellationToken cancellationToken = default) + { + StartRequested = false; + + if (HubConnection != null) + { + await HubConnection.StopAsync(cancellationToken); + + Log.Information("Network controller connection disconnected"); + } + } + + private async Task HandleFileRequest(Guid id, string filename) + { + Log.Information("Network controller requested file {Filename} with ID {Id}", filename, id); + + try + { + using var stream = new FileStream(Path.Combine(@"C:\slsk-downloads", "1.mp3"), FileMode.Open, FileAccess.Read); + using var request = new HttpRequestMessage(HttpMethod.Post, $"api/v0/agents/files/{id}"); + using var content = new MultipartFormDataContent + { + { new StreamContent(stream), "file", filename }, + }; + + request.Content = content; + + Log.Information("Beginning upload of file {Filename} with ID {Id}", filename, id); + var response = await HttpClient.SendAsync(request); + + if (!response.IsSuccessStatusCode) + { + Log.Error("Upload of file {Filename} with ID {Id} failed: {StatusCode}", response.StatusCode); + Console.WriteLine("Failed"); + Console.WriteLine(response.StatusCode); + } + else + { + Console.WriteLine($"{filename} sent!"); + } + } + catch (Exception ex) + { + Log.Error(ex, "Failed to handle file request: {Message}", ex.Message); + } + } + + private async Task HandleAuthenticationChallenge(string challengeToken) + { + Log.Information("Network controller sent an authentication challenge"); + + try + { + var options = OptionsMonitor.CurrentValue; + + var agent = options.InstanceName; + var key = options.Network.Controller.Secret.FromBase62(); + var tokenBytes = challengeToken.FromBase62(); + + var response = Aes.Encrypt(tokenBytes, key).ToBase62(); + + Log.Information("Logging in..."); + var success = await HubConnection.InvokeAsync("Login", agent, response); + + if (!success) + { + await HubConnection.StopAsync(); + Log.Error("Network controller authentication failed. Check configuration."); + } + } + catch (Exception ex) + { + Log.Error(ex, "Failed to handle authentication challenge: {Message}", ex.Message); + } + } + + private Task HubConnection_Closed(Exception arg) + { + Log.Warning("Network controller connection closed: {Message}", arg.Message); + return Task.CompletedTask; + } + + private Task HubConnection_Reconnecting(Exception arg) + { + Log.Warning("Network controller connection reconnecting: {Message}", arg.Message); + return Task.CompletedTask; + } + + private Task HubConnection_Reconnected(string arg) + { + Log.Warning("Network controller connection reconnected"); + return Task.CompletedTask; + } + + private void Configure(Options options) + { + if (options.Network.OperationMode.ToEnum() != NetworkOperationMode.Agent && !options.Flags.DualNetworkMode) + { + return; + } + + SyncRoot.Wait(); + + try + { + var optionsHash = Compute.Sha1Hash(options.Network.Controller.ToJson()); + + if (optionsHash == LastOptionsHash) + { + return; + } + + Log.Information("Network options changed. Reconfiguring..."); + + // 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(); + + HttpClient = HttpClientFactory.CreateClient(); + HttpClient.BaseAddress = new(options.Network.Controller.Address); + + HubConnection = new HubConnectionBuilder() + .WithUrl($"{options.Network.Controller.Address}/hub/agents") + .WithAutomaticReconnect(new[] + { + TimeSpan.FromSeconds(0), + TimeSpan.FromSeconds(1), + TimeSpan.FromSeconds(3), + TimeSpan.FromSeconds(10), + TimeSpan.FromSeconds(30), + }) + .Build(); + + HubConnection.Reconnected += HubConnection_Reconnected; + HubConnection.Reconnecting += HubConnection_Reconnecting; + HubConnection.Closed += HubConnection_Closed; + + HubConnection.On(NetworkHubMethods.RequestFile, HandleFileRequest); + HubConnection.On(NetworkHubMethods.AuthenticationChallenge, HandleAuthenticationChallenge); + + LastOptionsHash = optionsHash; + + Log.Information("Network options reconfigured"); + + // if start was requested (if StartAsync() was called externally), restart + // after re-configuration + if (StartRequested) + { + Log.Information("Reconnecting the network controller connection..."); + _ = StartAsync(); + } + } + finally + { + SyncRoot.Release(); + } + } + } +} -- cgit v1.2.3 From 208082c34935aa8fc91d910b86bae611a29392f7 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Mon, 10 Oct 2022 15:57:32 -0500 Subject: resolve requested files from share --- src/slskd/Network/NetworkClient.cs | 35 +++++++++++++++++++++++++++-------- 1 file changed, 27 insertions(+), 8 deletions(-) (limited to 'src/slskd/Network/NetworkClient.cs') diff --git a/src/slskd/Network/NetworkClient.cs b/src/slskd/Network/NetworkClient.cs index be7b6a2c..e37936d7 100644 --- a/src/slskd/Network/NetworkClient.cs +++ b/src/slskd/Network/NetworkClient.cs @@ -27,6 +27,7 @@ namespace slskd.Network using Microsoft.AspNetCore.SignalR.Client; using Serilog; using slskd.Cryptography; + using slskd.Shares; public interface INetworkClient { @@ -37,9 +38,12 @@ namespace slskd.Network public class NetworkClient : INetworkClient { public NetworkClient( + IShareService shareService, IOptionsMonitor optionsMonitor, IHttpClientFactory httpClientFactory) { + Shares = shareService; + HttpClientFactory = httpClientFactory; OptionsMonitor = optionsMonitor; @@ -48,6 +52,7 @@ namespace slskd.Network Configure(OptionsMonitor.CurrentValue); } + private IShareService Shares { get; } private SemaphoreSlim SyncRoot { get; } = new SemaphoreSlim(1, 1); private string LastOptionsHash { get; set; } private IOptionsMonitor OptionsMonitor { get; } @@ -56,6 +61,7 @@ namespace slskd.Network private HubConnection HubConnection { get; set; } private bool StartRequested { get; set; } private CancellationTokenSource StartCancellationTokenSource { get; set; } + private ILogger Log { get; } = Serilog.Log.ForContext(); public async Task StartAsync(CancellationToken cancellationToken = default) { @@ -99,7 +105,17 @@ namespace slskd.Network try { - using var stream = new FileStream(Path.Combine(@"C:\slsk-downloads", "1.mp3"), FileMode.Open, FileAccess.Read); + var localFilename = await Shares.ResolveFileAsync(filename); + + var localFileInfo = new FileInfo(filename); + + if (!localFileInfo.Exists) + { + Shares.RequestScan(); + throw new NotFoundException($"The file '{localFilename}' could not be located on disk. A share scan should be performed."); + } + + using var stream = new FileStream(localFileInfo.FullName, FileMode.Open, FileAccess.Read); using var request = new HttpRequestMessage(HttpMethod.Post, $"api/v0/agents/files/{id}"); using var content = new MultipartFormDataContent { @@ -114,23 +130,24 @@ namespace slskd.Network if (!response.IsSuccessStatusCode) { Log.Error("Upload of file {Filename} with ID {Id} failed: {StatusCode}", response.StatusCode); - Console.WriteLine("Failed"); - Console.WriteLine(response.StatusCode); } else { - Console.WriteLine($"{filename} sent!"); + Log.Information("Upload of file {Filename} with ID {Id} succeeded.", filename); } } catch (Exception ex) { Log.Error(ex, "Failed to handle file request: {Message}", ex.Message); + + // report the failure to the controller. this avoids a failure due to timeout. + _ = HttpClient.SendAsync(new HttpRequestMessage(HttpMethod.Delete, $"api/v0/agents/files/{id}")); } } private async Task HandleAuthenticationChallenge(string challengeToken) { - Log.Information("Network controller sent an authentication challenge"); + Log.Debug("Network controller sent an authentication challenge"); try { @@ -142,7 +159,7 @@ namespace slskd.Network var response = Aes.Encrypt(tokenBytes, key).ToBase62(); - Log.Information("Logging in..."); + Log.Debug("Logging in..."); var success = await HubConnection.InvokeAsync("Login", agent, response); if (!success) @@ -150,6 +167,8 @@ namespace slskd.Network await HubConnection.StopAsync(); Log.Error("Network controller authentication failed. Check configuration."); } + + Log.Information("Network controller authentication succeeded."); } catch (Exception ex) { @@ -193,7 +212,7 @@ namespace slskd.Network return; } - Log.Information("Network options changed. Reconfiguring..."); + Log.Debug("Network options changed. Reconfiguring..."); // if the client is attempting a connection, cancel it // it's going to be dropped when we create a new instance, but we need @@ -224,7 +243,7 @@ namespace slskd.Network LastOptionsHash = optionsHash; - Log.Information("Network options reconfigured"); + Log.Debug("Network options reconfigured"); // if start was requested (if StartAsync() was called externally), restart // after re-configuration -- cgit v1.2.3 From 345485ad861ad0b2e643a3dbfc21eac013cd755c Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Mon, 10 Oct 2022 17:21:47 -0500 Subject: stub logic to upload shares --- src/slskd/Network/NetworkClient.cs | 57 ++++++++++++++++++++++++++++++++++++-- 1 file changed, 54 insertions(+), 3 deletions(-) (limited to 'src/slskd/Network/NetworkClient.cs') diff --git a/src/slskd/Network/NetworkClient.cs b/src/slskd/Network/NetworkClient.cs index e37936d7..007ce80f 100644 --- a/src/slskd/Network/NetworkClient.cs +++ b/src/slskd/Network/NetworkClient.cs @@ -62,6 +62,7 @@ namespace slskd.Network private bool StartRequested { get; set; } private CancellationTokenSource StartCancellationTokenSource { get; set; } private ILogger Log { get; } = Serilog.Log.ForContext(); + private TaskCompletionSource LoggedIn { get; set; } public async Task StartAsync(CancellationToken cancellationToken = default) { @@ -71,6 +72,7 @@ namespace slskd.Network } StartCancellationTokenSource = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken); + LoggedIn = new TaskCompletionSource(); StartRequested = true; Log.Information("Attempting to connect to the network controller {Address}", OptionsMonitor.CurrentValue.Network.Controller.Address); @@ -84,7 +86,24 @@ namespace slskd.Network maxDelayInMilliseconds: 30000, StartCancellationTokenSource.Token); - Log.Information("Network controller connection established"); + Log.Information("Network controller connection established. Awaiting authentication..."); + + await LoggedIn.Task; + + Log.Information("Authenticated. Uploading shares..."); + + try + { + await UploadSharesAsync(); + } + catch (Exception ex) + { + Log.Error($"Failed to upload shares to the network controller: {ex.Message}"); + Log.Error("Disconnecting"); + await StopAsync(); + } + + Log.Information("Shares uploaded. Ready to upload files."); } public async Task StopAsync(CancellationToken cancellationToken = default) @@ -99,6 +118,37 @@ namespace slskd.Network } } + public async Task UploadSharesAsync() + { + Log.Debug("Requesting share upload token..."); + var token = await HubConnection.InvokeAsync(nameof(NetworkHub.GetShareUploadToken)); + Log.Debug("Share upload token {Token}", token); + + var temp = Path.Combine(Path.GetTempPath(), $"slskd_share_backup_{Path.GetRandomFileName()}.db"); + + // todo: back up shares database to temp location + // todo: upload shares database backup to controller + + using var stream = new FileStream(temp, FileMode.Open, FileAccess.Read); + using var request = new HttpRequestMessage(HttpMethod.Post, $"api/v0/agents/shares/{token}"); + using var content = new MultipartFormDataContent + { + { new StreamContent(stream), "shares" }, + }; + + request.Content = content; + + Log.Information("Beginning upload of shares"); + var response = await HttpClient.SendAsync(request); + + if (!response.IsSuccessStatusCode) + { + throw new NetworkException($"Failed to upload shares to network controller: {response.StatusCode}"); + } + + Log.Information("Upload shares succeeded"); + } + private async Task HandleFileRequest(Guid id, string filename) { Log.Information("Network controller requested file {Filename} with ID {Id}", filename, id); @@ -160,7 +210,7 @@ namespace slskd.Network var response = Aes.Encrypt(tokenBytes, key).ToBase62(); Log.Debug("Logging in..."); - var success = await HubConnection.InvokeAsync("Login", agent, response); + var success = await HubConnection.InvokeAsync(nameof(NetworkHub.Login), agent, response); if (!success) { @@ -168,7 +218,8 @@ namespace slskd.Network Log.Error("Network controller authentication failed. Check configuration."); } - Log.Information("Network controller authentication succeeded."); + Log.Debug("Login succeeded."); + LoggedIn?.TrySetResult(); } catch (Exception ex) { -- cgit v1.2.3 From 3c3cfe6f2c3c49c05aa4de1e86a81fcb2c8af590 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Mon, 10 Oct 2022 18:16:23 -0500 Subject: implement share upload --- src/slskd/Network/NetworkClient.cs | 35 ++++++++++++++++++++++++++++------- 1 file changed, 28 insertions(+), 7 deletions(-) (limited to 'src/slskd/Network/NetworkClient.cs') diff --git a/src/slskd/Network/NetworkClient.cs b/src/slskd/Network/NetworkClient.cs index 007ce80f..10e33118 100644 --- a/src/slskd/Network/NetworkClient.cs +++ b/src/slskd/Network/NetworkClient.cs @@ -25,6 +25,7 @@ namespace slskd.Network using System.Threading; using System.Threading.Tasks; using Microsoft.AspNetCore.SignalR.Client; + using Microsoft.Data.Sqlite; using Serilog; using slskd.Cryptography; using slskd.Shares; @@ -98,9 +99,10 @@ namespace slskd.Network } catch (Exception ex) { - Log.Error($"Failed to upload shares to the network controller: {ex.Message}"); - Log.Error("Disconnecting"); + Log.Error(ex, ex.Message); + Log.Error("Disconnecting from the network controller"); await StopAsync(); + throw; } Log.Information("Shares uploaded. Ready to upload files."); @@ -120,16 +122,34 @@ namespace slskd.Network public async Task UploadSharesAsync() { + var temp = Path.Combine(Path.GetTempPath(), Program.AppName, $"share_backup_{Path.GetRandomFileName()}.db"); + + Directory.CreateDirectory(Path.Combine(Path.GetTempPath(), Program.AppName)); + + Log.Debug("Backing up shares to {Filename}", temp); + Shares.BackupTo($"Data Source={temp};Pooling=False;"); // quite a leaky abstraction + Log.Debug("Share backup successful"); + Log.Debug("Requesting share upload token..."); var token = await HubConnection.InvokeAsync(nameof(NetworkHub.GetShareUploadToken)); Log.Debug("Share upload token {Token}", token); - var temp = Path.Combine(Path.GetTempPath(), $"slskd_share_backup_{Path.GetRandomFileName()}.db"); + FileStream stream = default; - // todo: back up shares database to temp location - // todo: upload shares database backup to controller + try + { + stream = new FileStream(temp, FileMode.Open, FileAccess.Read); + } + catch (Exception ex) + { + // this happens if SQLite hangs on to the connection for whatever reason, seemingly due to pooling + // Pooling=False should be included in the connection string and this shouldn't be an issue, but + // since i don't totally understand the behavior, i'll leave this for now. + Log.Debug(ex, "Failed open stream to backup. Clearing SQLite pools and trying again."); + SqliteConnection.ClearAllPools(); + stream = new FileStream(temp, FileMode.Open, FileAccess.Read); + } - using var stream = new FileStream(temp, FileMode.Open, FileAccess.Read); using var request = new HttpRequestMessage(HttpMethod.Post, $"api/v0/agents/shares/{token}"); using var content = new MultipartFormDataContent { @@ -191,7 +211,8 @@ namespace slskd.Network Log.Error(ex, "Failed to handle file request: {Message}", ex.Message); // report the failure to the controller. this avoids a failure due to timeout. - _ = HttpClient.SendAsync(new HttpRequestMessage(HttpMethod.Delete, $"api/v0/agents/files/{id}")); + using var request = new HttpRequestMessage(HttpMethod.Delete, $"api/v0/agents/files/{id}"); + _ = HttpClient.SendAsync(request); } } -- cgit v1.2.3 From 5281911a0634bd790adef13e7e0de28d40e9ee4d Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 15 Oct 2022 08:04:47 -0500 Subject: add ShareRepositoryFactory, consolidate a lot of OOP cruft --- .../Network/API/Controllers/NetworkController.cs | 25 ++- src/slskd/Network/NetworkClient.cs | 28 ++-- src/slskd/Program.cs | 5 +- src/slskd/Shares/IReadOnlyShareRepository.cs | 26 --- src/slskd/Shares/IReadWriteShareRepository.cs | 96 ----------- src/slskd/Shares/IShareRepository.cs | 89 +++++++++- src/slskd/Shares/IShareRepositoryFactory.cs | 46 ++++++ src/slskd/Shares/IShareService.cs | 13 +- src/slskd/Shares/ShareConnectionStringFactory.cs | 58 ------- src/slskd/Shares/ShareRepositoryFactory.cs | 74 +++++++++ src/slskd/Shares/ShareScanner.cs | 4 +- src/slskd/Shares/ShareService.cs | 64 ++++--- src/slskd/Shares/SqliteShareRepository.cs | 183 ++++++++++++--------- 13 files changed, 384 insertions(+), 327 deletions(-) delete mode 100644 src/slskd/Shares/IReadOnlyShareRepository.cs delete mode 100644 src/slskd/Shares/IReadWriteShareRepository.cs create mode 100644 src/slskd/Shares/IShareRepositoryFactory.cs delete mode 100644 src/slskd/Shares/ShareConnectionStringFactory.cs create mode 100644 src/slskd/Shares/ShareRepositoryFactory.cs (limited to 'src/slskd/Network/NetworkClient.cs') diff --git a/src/slskd/Network/API/Controllers/NetworkController.cs b/src/slskd/Network/API/Controllers/NetworkController.cs index 69e3d789..deeddc04 100644 --- a/src/slskd/Network/API/Controllers/NetworkController.cs +++ b/src/slskd/Network/API/Controllers/NetworkController.cs @@ -24,6 +24,7 @@ namespace slskd.Network using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using Serilog; + using slskd.Shares; /// /// Network. @@ -33,11 +34,19 @@ namespace slskd.Network [ApiController] public class NetworkController : ControllerBase { - public NetworkController(INetworkService networkService) + public NetworkController( + INetworkService networkService, + IShareService shareService, + IShareRepositoryFactory shareRepositoryFactory) { Network = networkService; + Shares = shareService; + + ShareRepositoryFactory = shareRepositoryFactory; } + private IShareRepositoryFactory ShareRepositoryFactory { get; } + private IShareService Shares { get; } private INetworkService Network { get; } private ILogger Log { get; } = Serilog.Log.ForContext(); @@ -114,14 +123,22 @@ namespace slskd.Network Log.Debug("Uploading share from {Agent} to {Filename}", agent, temp); using var outputStream = new FileStream(temp, FileMode.CreateNew, FileAccess.Write); - using var inputStream = Request.Form.Files.First().OpenReadStream(); + using var inputStream = Request.Form.Files[0].OpenReadStream(); await inputStream.CopyToAsync(outputStream); Log.Debug("Upload of share from {Agent} to {Filename} complete", agent, temp); - // todo: validate database - // todo: add contents of db to local db + var repository = ShareRepositoryFactory.CreateFromFile(temp); + + if (!repository.TryValidate(out var problems)) + { + return BadRequest(string.Join(", ", problems)); + } + + var destinationRepository = ShareRepositoryFactory.CreateFromHost(agent); + + destinationRepository.RestoreFrom(repository); return Ok(); } diff --git a/src/slskd/Network/NetworkClient.cs b/src/slskd/Network/NetworkClient.cs index 10e33118..15f114f9 100644 --- a/src/slskd/Network/NetworkClient.cs +++ b/src/slskd/Network/NetworkClient.cs @@ -127,7 +127,7 @@ namespace slskd.Network Directory.CreateDirectory(Path.Combine(Path.GetTempPath(), Program.AppName)); Log.Debug("Backing up shares to {Filename}", temp); - Shares.BackupTo($"Data Source={temp};Pooling=False;"); // quite a leaky abstraction + await Shares.DumpAsync(temp); Log.Debug("Share backup successful"); Log.Debug("Requesting share upload token..."); @@ -136,18 +136,22 @@ namespace slskd.Network FileStream stream = default; - try - { - stream = new FileStream(temp, FileMode.Open, FileAccess.Read); - } - catch (Exception ex) + while (true) { - // this happens if SQLite hangs on to the connection for whatever reason, seemingly due to pooling - // Pooling=False should be included in the connection string and this shouldn't be an issue, but - // since i don't totally understand the behavior, i'll leave this for now. - Log.Debug(ex, "Failed open stream to backup. Clearing SQLite pools and trying again."); - SqliteConnection.ClearAllPools(); - stream = new FileStream(temp, FileMode.Open, FileAccess.Read); + try + { + stream = new FileStream(temp, FileMode.Open, FileAccess.Read); + break; + } + catch (Exception ex) + { + // this happens if SQLite hangs on to the connection for whatever reason, seemingly due to pooling + // Pooling=False should be included in the connection string and this shouldn't be an issue, but + // since i don't totally understand the behavior, i'll leave this for now. + Log.Debug(ex, "Failed open stream to backup. Clearing SQLite pools and trying again."); + SqliteConnection.ClearAllPools(); + await Task.Delay(100); + } } using var request = new HttpRequestMessage(HttpMethod.Post, $"api/v0/agents/shares/{token}"); diff --git a/src/slskd/Program.cs b/src/slskd/Program.cs index c5d0f961..b9d43992 100644 --- a/src/slskd/Program.cs +++ b/src/slskd/Program.cs @@ -528,10 +528,7 @@ namespace slskd services.AddSingleton(_ => new RoomTracker(messageLimit: 250)); services.AddSingleton(); - services.AddSingleton(new ShareConnectionStringFactory( - createFromFile: (name) => $"Data Source={Path.Combine(DataDirectory, $"shares.{name}")}.db;Cache=shared", - createFromMemory: (name) => $"file:shares.{name}?mode=memory", - createBackupFromFile: (name) => $"Data Source={Path.Combine(DataDirectory, $"shares.{name}")}.db.bak;")); + services.AddTransient(); services.AddSingleton(); services.AddSingleton(); diff --git a/src/slskd/Shares/IReadOnlyShareRepository.cs b/src/slskd/Shares/IReadOnlyShareRepository.cs deleted file mode 100644 index fff587ad..00000000 --- a/src/slskd/Shares/IReadOnlyShareRepository.cs +++ /dev/null @@ -1,26 +0,0 @@ -// -// 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/. -// - -namespace slskd.Shares -{ - /// - /// Read-only persistent storage of shared files and metadata. - /// - public interface IReadOnlyShareRepository : IShareRepository - { - } -} diff --git a/src/slskd/Shares/IReadWriteShareRepository.cs b/src/slskd/Shares/IReadWriteShareRepository.cs deleted file mode 100644 index c6701753..00000000 --- a/src/slskd/Shares/IReadWriteShareRepository.cs +++ /dev/null @@ -1,96 +0,0 @@ -// -// 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/. -// - -namespace slskd.Shares -{ - using System; - using Soulseek; - - /// - /// Writeable persistent storage of shared files and metadata. - /// - public interface IReadWriteShareRepository : IShareRepository - { - - /// - /// Creates a new database. - /// - /// - /// Creates tables using 'IF NOT EXISTS', so this is idempotent unless 'discardExisting` is specified, in which case - /// tables are explicitly dropped prior to creation. - /// - /// An optional value that determines whether the existing database should be discarded. - void Create(bool discardExisting = false); - - /// - /// Inserts a directory. - /// - /// The fully qualified local name of the directory. - /// The timestamp to assign to the record. - void InsertDirectory(string name, long timestamp); - - /// - /// Inserts a file. - /// - /// The fully qualified remote path of the file. - /// The fully qualified local path of the file. - /// The timestamp at which the file was last modified, according to the host OS. - /// The Soulseek.File instance representing the file. - /// The timestamp to assign to the record. - void InsertFile(string maskedFilename, string originalFilename, DateTime touchedAt, File file, long timestamp); - - /// - /// Inserts a scan record at the specified . - /// - /// The timestamp associated with the scan. - /// The options snapshot at the start of the scan. - void InsertScan(long timestamp, Options.SharesOptions options); - - /// - /// Backs the current database up to the database at the specified . - /// - /// The connection string of the destination database. - void BackupTo(string connectionString); - - /// - /// Restores the current database from the database at the specified . - /// - /// The connection string of the source database. - void RestoreFrom(string connectionString); - - /// - /// Deletes directory records with a timestamp prior to the specified . - /// - /// The timestamp before which to delete directories. - /// The number of records deleted. - long PruneDirectories(long olderThanTimestamp); - - /// - /// Deletes file records with a timestamp prior to the specified . - /// - /// The timestamp before which to delete files. - /// The number of records deleted. - long PruneFiles(long olderThanTimestamp); - - /// - /// Updates the scan started at the specified to set the . - /// - /// The timestamp associated with the scan. - /// The timestamp at the conclusion of the scan. - void UpdateScan(long timestamp, long end); - } -} \ No newline at end of file diff --git a/src/slskd/Shares/IShareRepository.cs b/src/slskd/Shares/IShareRepository.cs index 87c2c386..0cf5cd80 100644 --- a/src/slskd/Shares/IShareRepository.cs +++ b/src/slskd/Shares/IShareRepository.cs @@ -17,6 +17,7 @@ namespace slskd.Shares { + using System; using System.Collections.Generic; using Soulseek; @@ -30,6 +31,12 @@ namespace slskd.Shares /// string ConnectionString { get; } + /// + /// Backs the current database up to the database at the specified . + /// + /// The destination repository. + void BackupTo(IShareRepository repository); + /// /// Counts the number of directories in the database. /// @@ -44,6 +51,22 @@ namespace slskd.Shares /// The number of files. int CountFiles(string parentDirectory = null); + /// + /// Creates a new database. + /// + /// + /// Creates tables using 'IF NOT EXISTS', so this is idempotent unless 'discardExisting` is specified, in which case + /// tables are explicitly dropped prior to creation. + /// + /// An optional value that determines whether the existing database should be discarded. + void Create(bool discardExisting = false); + + /// + /// Dumps the contents of the database to a file. + /// + /// The destination file. + void DumpTo(string filename); + /// /// Finds the filename of the file matching the specified . /// @@ -51,6 +74,30 @@ namespace slskd.Shares /// The filename, if found. string FindFilename(string maskedFilename); + /// + /// Inserts a directory. + /// + /// The fully qualified local name of the directory. + /// The timestamp to assign to the record. + void InsertDirectory(string name, long timestamp); + + /// + /// Inserts a file. + /// + /// The fully qualified remote path of the file. + /// The fully qualified local path of the file. + /// The timestamp at which the file was last modified, according to the host OS. + /// The Soulseek.File instance representing the file. + /// The timestamp to assign to the record. + void InsertFile(string maskedFilename, string originalFilename, DateTime touchedAt, File file, long timestamp); + + /// + /// Inserts a scan record at the specified . + /// + /// The timestamp associated with the scan. + /// The options snapshot at the start of the scan. + void InsertScan(long timestamp, Options.SharesOptions options); + /// /// Lists all directories. /// @@ -66,6 +113,26 @@ namespace slskd.Shares /// The list of files. IEnumerable ListFiles(string parentDirectory = null, bool includeFullPath = false); + /// + /// Deletes directory records with a timestamp prior to the specified . + /// + /// The timestamp before which to delete directories. + /// The number of records deleted. + long PruneDirectories(long olderThanTimestamp); + + /// + /// Deletes file records with a timestamp prior to the specified . + /// + /// The timestamp before which to delete files. + /// The number of records deleted. + long PruneFiles(long olderThanTimestamp); + + /// + /// Restores the current database from the database at the specified . + /// + /// The destination repository. + void RestoreFrom(IShareRepository repository); + /// /// Searches the database for files matching the specified . /// @@ -74,11 +141,23 @@ namespace slskd.Shares IEnumerable Search(SearchQuery query); /// - /// Attempts to validate the database at the specified , or the - /// default . + /// Attempts to validate the backing database. + /// + /// A value indicating whether the database is valid. + bool TryValidate(); + + /// + /// Attempts to validate the backing database. /// - /// The connection string of the database to validate. + /// The list of problems, if the database is invalid. /// A value indicating whether the database is valid. - bool TryValidate(string connectionString = null); + bool TryValidate(out IEnumerable problems); + + /// + /// Updates the scan started at the specified to set the . + /// + /// The timestamp associated with the scan. + /// The timestamp at the conclusion of the scan. + void UpdateScan(long timestamp, long end); } -} +} \ No newline at end of file diff --git a/src/slskd/Shares/IShareRepositoryFactory.cs b/src/slskd/Shares/IShareRepositoryFactory.cs new file mode 100644 index 00000000..a43f84d9 --- /dev/null +++ b/src/slskd/Shares/IShareRepositoryFactory.cs @@ -0,0 +1,46 @@ +// +// 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/. +// + +namespace slskd.Shares +{ + /// + /// Persistent storage of a shared file cache. + /// + public interface IShareRepositoryFactory + { + /// + /// Create a repository for the specified . + /// + /// The name of the agent. + /// The created repository. + IShareRepository CreateFromHost(string name); + + /// + /// Create a repository backup for the specified . + /// + /// The name of the agent. + /// The created repository. + IShareRepository CreateFromHostBackup(string name); + + /// + /// Create a repository for the specified . + /// + /// The fully qualified path of the filename. + /// The created repository. + IShareRepository CreateFromFile(string filename); + } +} diff --git a/src/slskd/Shares/IShareService.cs b/src/slskd/Shares/IShareService.cs index 90fa115d..b55db482 100644 --- a/src/slskd/Shares/IShareService.cs +++ b/src/slskd/Shares/IShareService.cs @@ -42,18 +42,19 @@ namespace slskd.Shares /// The host to add or update. void AddOrUpdateHost(Host host); - /// - /// Backs contents of the cache up to the specified file. - /// - /// The destination connection string. - void BackupTo(string connectionString); - /// /// Returns the entire contents of the share. /// /// The entire contents of the share. Task> BrowseAsync(Share share = null); + /// + /// Dumps the local share cache to a file. + /// + /// The destination file. + /// The operation context. + Task DumpAsync(string filename); + /// /// Returns the contents of the specified . /// diff --git a/src/slskd/Shares/ShareConnectionStringFactory.cs b/src/slskd/Shares/ShareConnectionStringFactory.cs deleted file mode 100644 index d9b7492b..00000000 --- a/src/slskd/Shares/ShareConnectionStringFactory.cs +++ /dev/null @@ -1,58 +0,0 @@ -// -// 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/. -// - -namespace slskd.Shares -{ - using System; - - /// - /// Creates connection strings for share cache databases. - /// - public class ShareConnectionStringFactory - { - /// - /// Initializes a new instance of the class. - /// - /// The function used to create a connection string for a share cache database. - /// The function used to create an in-memory connection string for a share cache database. - /// The function used to crate a connection string for a share cache backup database. - public ShareConnectionStringFactory( - Func createFromFile, - Func createFromMemory, - Func createBackupFromFile) - { - CreateFromFile = createFromFile; - CreateFromMemory = createFromMemory; - CreateBackupFromFile = createBackupFromFile; - } - - /// - /// Gets a function used to create a connection string for a share cache database. - /// - public Func CreateFromFile { get; } - - /// - /// Gets a function used to create an in-memory connection string for a share cache database. - /// - public Func CreateFromMemory { get; } - - /// - /// Gets a function used to create a connection string for a share cache backup database. - /// - public Func CreateBackupFromFile { get; } - } -} diff --git a/src/slskd/Shares/ShareRepositoryFactory.cs b/src/slskd/Shares/ShareRepositoryFactory.cs new file mode 100644 index 00000000..fc58c397 --- /dev/null +++ b/src/slskd/Shares/ShareRepositoryFactory.cs @@ -0,0 +1,74 @@ +// +// 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 System.IO; + +namespace slskd.Shares +{ + /// + /// Persistent storage of a shared file cache. + /// + public class SqliteShareRepositoryFactory : IShareRepositoryFactory + { + /// + /// Initializes a new instance of the class. + /// + /// + public SqliteShareRepositoryFactory( + OptionsAtStartup optionsAtStartup) + { + StorageMode = optionsAtStartup.Shares.Cache.StorageMode.ToEnum(); + } + + private StorageMode StorageMode { get; } + + /// + /// Create a repository for the specified . + /// + /// The name of the agent. + /// The created repository. + public IShareRepository CreateFromHost(string name) + { + if (StorageMode == StorageMode.Memory) + { + return new SqliteShareRepository($"Data Source=file:shares.{name}?mode=memory;Cache=shared"); + } + + var file = Path.Combine(Program.DataDirectory, $"shares.{name}.db"); + return new SqliteShareRepository($"Data Source={file};Cache=shared"); + } + + /// + /// Create a repository backup for the specified . + /// + /// The name of the agent. + /// The created repository. + public IShareRepository CreateFromHostBackup(string name) + { + var file = Path.Combine(Program.DataDirectory, $"shares.{name}.bak.db"); + return new SqliteShareRepository($"Data Source={file}"); + } + + /// + /// Create a repository for the specified . + /// + /// The fully qualified path of the filename. + /// The created repository. + public IShareRepository CreateFromFile(string filename) + => new SqliteShareRepository($"Data Source={filename}"); + } +} diff --git a/src/slskd/Shares/ShareScanner.cs b/src/slskd/Shares/ShareScanner.cs index f5e7e52d..7a174396 100644 --- a/src/slskd/Shares/ShareScanner.cs +++ b/src/slskd/Shares/ShareScanner.cs @@ -67,7 +67,7 @@ namespace slskd.Shares /// public ShareScanner( int workerCount, - IReadWriteShareRepository shareRepository, + IShareRepository shareRepository, ISoulseekFileFactory soulseekFileFactory = null) { WorkerCount = workerCount; @@ -87,7 +87,7 @@ namespace slskd.Shares private IManagedState State { get; } = new ManagedState(); private SemaphoreSlim SyncRoot { get; } = new SemaphoreSlim(1); private CancellationTokenSource CancellationTokenSource { get; set; } - private IReadWriteShareRepository Repository { get; } + private IShareRepository Repository { get; } /// /// Scans the configured shares and fills the cache. diff --git a/src/slskd/Shares/ShareService.cs b/src/slskd/Shares/ShareService.cs index a0aec286..cc35477e 100644 --- a/src/slskd/Shares/ShareService.cs +++ b/src/slskd/Shares/ShareService.cs @@ -37,32 +37,22 @@ namespace slskd.Shares /// /// Initializes a new instance of the class. /// - /// + /// /// /// public ShareService( - ShareConnectionStringFactory shareConnectionStringFactory, + IShareRepositoryFactory shareRepositoryFactory, IOptionsMonitor optionsMonitor, IShareScanner scanner = null) { var options = optionsMonitor.CurrentValue; - ConnectionStringFactory = shareConnectionStringFactory; CacheStorageMode = options.Shares.Cache.StorageMode.ToEnum(); - if (CacheStorageMode == StorageMode.Memory) - { - ConnectionString = ConnectionStringFactory.CreateFromMemory(options.InstanceName); - } - else - { - ConnectionString = ConnectionStringFactory.CreateFromFile(options.InstanceName); - } - - BackupConnectionString = ConnectionStringFactory.CreateBackupFromFile(options.InstanceName); + ShareRepositoryFactory = shareRepositoryFactory; var host = new Host(options.InstanceName, type: HostType.Local, state: HostState.Online); - var repository = new SqliteShareRepository(ConnectionString); + var repository = ShareRepositoryFactory.CreateFromHost(options.InstanceName); Local = (host, repository); @@ -108,9 +98,7 @@ namespace slskd.Shares /// public IStateMonitor StateMonitor { get; } - private string ConnectionString { get; } - private string BackupConnectionString { get; } - private ShareConnectionStringFactory ConnectionStringFactory { get; } + private IShareRepositoryFactory ShareRepositoryFactory { get; } private IShareScanner Scanner { get; } private string LastOptionsHash { get; set; } private IOptionsMonitor OptionsMonitor { get; } @@ -119,7 +107,7 @@ namespace slskd.Shares private SemaphoreSlim SyncRoot { get; } = new SemaphoreSlim(1, 1); private StorageMode CacheStorageMode { get; } private ILogger Log { get; } = Serilog.Log.ForContext(); - private (Host Host, IReadWriteShareRepository Repository) Local { get; set; } + private (Host Host, IShareRepository Repository) Local { get; set; } private IEnumerable AllRepositories { get; set; } /// @@ -128,9 +116,11 @@ namespace slskd.Shares /// The host to add or update. public void AddOrUpdateHost(Host host) { + // we assume that if this method is called that the caller has verified that the + // file for the host exists and is valid. HostDictionary.AddOrUpdate( key: host.Name, - addValueFactory: (key) => (host, new SqliteShareRepository(ConnectionStringFactory.CreateFromFile(host.Name))), + addValueFactory: (key) => (host, ShareRepositoryFactory.CreateFromHost(host.Name)), updateValueFactory: (_, existing) => (host, existing.Repository)); AllRepositories = HostDictionary.Values @@ -139,15 +129,6 @@ namespace slskd.Shares .Prepend(Local.Repository); } - /// - /// Backs contents of the cache up to the specified file. - /// - /// The destination connection string. - public void BackupTo(string connectionString) - { - Repository.BackupTo(connectionString); - } - /// /// Returns the entire contents of the share. /// @@ -200,6 +181,17 @@ namespace slskd.Shares return Task.FromResult(results); } + /// + /// Dumps the local share cache to a file. + /// + /// The destination file. + /// The operation context. + public Task DumpAsync(string filename) + { + Local.Repository.DumpTo(filename); + return Task.CompletedTask; + } + /// /// Returns the contents of the specified . /// @@ -272,7 +264,7 @@ namespace slskd.Shares await Scanner.ScanAsync(Local.Host.Shares, OptionsMonitor.CurrentValue.Shares); Log.Debug("Backing up shared file cache database..."); - Local.Repository.BackupTo(BackupConnectionString); + Local.Repository.BackupTo(ShareRepositoryFactory.CreateFromHostBackup(OptionsMonitor.CurrentValue.InstanceName)); Log.Debug("Shared file cache database backup complete"); } @@ -319,11 +311,13 @@ namespace slskd.Shares { Log.Information("Share cache StorageMode is 'Memory'. Attempting to load from backup..."); - if (Local.Repository.TryValidate(BackupConnectionString)) + var backupRepository = ShareRepositoryFactory.CreateFromHostBackup(OptionsMonitor.CurrentValue.InstanceName); + + if (backupRepository.TryValidate(out _)) { Log.Information("Share cache backup validated. Attempting to restore..."); - Local.Repository.RestoreFrom(connectionString: BackupConnectionString); + Local.Repository.RestoreFrom(backupRepository); Log.Information("Share cache successfully restored from backup"); } @@ -337,7 +331,7 @@ namespace slskd.Shares { Log.Information("Share cache StorageMode is 'Disk'. Attempting to validate..."); - if (Local.Repository.TryValidate(ConnectionString)) + if (Local.Repository.TryValidate(out _)) { // no-op } @@ -345,11 +339,13 @@ namespace slskd.Shares { Log.Warning("Share cache is missing, corrupt, or is out of date. Attempting to load from backup..."); - if (Local.Repository.TryValidate(BackupConnectionString)) + var backupRepository = ShareRepositoryFactory.CreateFromHostBackup(OptionsMonitor.CurrentValue.InstanceName); + + if (backupRepository.TryValidate(out _)) { Log.Information("Share cache backup validated. Attempting to restore..."); - Local.Repository.RestoreFrom(connectionString: BackupConnectionString); + Local.Repository.RestoreFrom(backupRepository); Log.Information("Share cache successfully restored from backup"); } diff --git a/src/slskd/Shares/SqliteShareRepository.cs b/src/slskd/Shares/SqliteShareRepository.cs index 28788c3f..9b65794e 100644 --- a/src/slskd/Shares/SqliteShareRepository.cs +++ b/src/slskd/Shares/SqliteShareRepository.cs @@ -28,7 +28,7 @@ namespace slskd.Shares /// /// Persistent storage of shared files and metadata. /// - public class SqliteShareRepository : IReadWriteShareRepository + public class SqliteShareRepository : IShareRepository { /// /// Initializes a new instance of the class. @@ -47,84 +47,13 @@ namespace slskd.Shares private ILogger Log { get; } = Serilog.Log.ForContext(); /// - /// Attempts to validate the database at the specified , or the - /// default . + /// Backs the current database up to the database at the specified . /// - /// The connection string of the database to validate. - /// A value indicating whether the database is valid. - public bool TryValidate(string connectionString = null) - { - connectionString ??= ConnectionString; - - // to update this schema map, run the following query against a valid, up-to-date database and paste the output below: - // select '{ "' || name || '", "' || sql || '" },' from sqlite_master where type = 'table' - var schema = new Dictionary() - { - { "scans", "CREATE TABLE scans (timestamp INTEGER PRIMARY KEY, options TEXT NOT NULL, end INTEGER DEFAULT NULL)" }, - { "directories", "CREATE TABLE directories (name TEXT PRIMARY KEY, timestamp INTEGER NOT NULL)" }, - { "filenames", "CREATE VIRTUAL TABLE filenames USING fts5(maskedFilename)" }, - { "filenames_data", "CREATE TABLE 'filenames_data'(id INTEGER PRIMARY KEY, block BLOB)" }, - { "filenames_idx", "CREATE TABLE 'filenames_idx'(segid, term, pgno, PRIMARY KEY(segid, term)) WITHOUT ROWID" }, - { "filenames_content", "CREATE TABLE 'filenames_content'(id INTEGER PRIMARY KEY, c0)" }, - { "filenames_docsize", "CREATE TABLE 'filenames_docsize'(id INTEGER PRIMARY KEY, sz BLOB)" }, - { "filenames_config", "CREATE TABLE 'filenames_config'(k PRIMARY KEY, v) WITHOUT ROWID" }, - { "files", "CREATE TABLE files (maskedFilename TEXT PRIMARY KEY, originalFilename TEXT NOT NULL, size BIGINT NOT NULL, touchedAt TEXT NOT NULL, code INTEGER DEFAULT 1 NOT NULL, extension TEXT, attributeJson TEXT NOT NULL, timestamp INTEGER NOT NULL)" }, - }; - - try - { - Log.Debug("Validating shares database with connection string {String}", connectionString); - - using var conn = new SqliteConnection(connectionString); - conn.Open(); - - using var cmd = new SqliteCommand("SELECT name, sql from sqlite_master WHERE type = 'table';", conn); - - var reader = cmd.ExecuteReader(); - var rows = 0; - - while (reader.Read()) - { - var table = reader.GetString(0); - var expectedSql = reader.GetString(1); - - if (schema.TryGetValue(table, out var actualSql)) - { - if (actualSql != expectedSql) - { - throw new MissingFieldException($"Expected {table} schema to be {expectedSql}, found {actualSql}"); - } - else - { - Log.Debug("Shares database table {Table} is valid: {Actual}", table, actualSql); - } - } - - rows++; - } - - if (rows != schema.Count) - { - throw new MissingMemberException($"Expected {schema.Count} tables, found {rows}"); - } - - return true; - } - catch (Exception ex) - { - Log.Debug(ex, $"Failed to validate shares database with connection string {connectionString}: {ex.Message}"); - return false; - } - } - - /// - /// Backs the current database up to the database at the specified . - /// - /// The connection string of the destination database. - public void BackupTo(string connectionString) + /// The destination repository. + public void BackupTo(IShareRepository repository) { using var sourceConn = GetConnection(ConnectionString); - using var backupConn = GetConnection(connectionString); + using var backupConn = GetConnection(repository.ConnectionString); sourceConn.BackupDatabase(backupConn); } @@ -224,6 +153,19 @@ namespace slskd.Shares "extension TEXT, attributeJson TEXT NOT NULL, timestamp INTEGER NOT NULL);"); } + /// + /// Dumps the contents of the database to a file. + /// + /// The destination file. + public void DumpTo(string filename) + { + using var sourceConn = GetConnection(ConnectionString); + using var backupConn = GetConnection($"Data Source={filename}"); + sourceConn.BackupDatabase(backupConn); + + Sqlite. + } + /// /// Finds the filename of the file matching the specified . /// @@ -442,12 +384,12 @@ namespace slskd.Shares } /// - /// Restores the current database from the database at the specified . + /// Restores the current database from the database at the specified . /// - /// The connection string of the source database. - public void RestoreFrom(string connectionString) + /// The destination repository. + public void RestoreFrom(IShareRepository repository) { - using var sourceConn = GetConnection(connectionString); + using var sourceConn = GetConnection(repository.ConnectionString); using var restoreConn = GetConnection(); sourceConn.BackupDatabase(restoreConn); } @@ -504,6 +446,87 @@ namespace slskd.Shares } } + /// + /// Attempts to validate the backing database. + /// + /// A value indicating whether the database is valid. + public bool TryValidate() + { + return TryValidate(out _); + } + + /// + /// Attempts to validate the backing database. + /// + /// The list of problems, if the database is invalid. + /// A value indicating whether the database is valid. + public bool TryValidate(out IEnumerable problems) + { + var list = new List(); + problems = list; + + // to update this schema map, run the following query against a valid, up-to-date database and paste the output below: + // select '{ "' || name || '", "' || sql || '" },' from sqlite_master where type = 'table' + var schema = new Dictionary() + { + { "scans", "CREATE TABLE scans (timestamp INTEGER PRIMARY KEY, options TEXT NOT NULL, end INTEGER DEFAULT NULL)" }, + { "directories", "CREATE TABLE directories (name TEXT PRIMARY KEY, timestamp INTEGER NOT NULL)" }, + { "filenames", "CREATE VIRTUAL TABLE filenames USING fts5(maskedFilename)" }, + { "filenames_data", "CREATE TABLE 'filenames_data'(id INTEGER PRIMARY KEY, block BLOB)" }, + { "filenames_idx", "CREATE TABLE 'filenames_idx'(segid, term, pgno, PRIMARY KEY(segid, term)) WITHOUT ROWID" }, + { "filenames_content", "CREATE TABLE 'filenames_content'(id INTEGER PRIMARY KEY, c0)" }, + { "filenames_docsize", "CREATE TABLE 'filenames_docsize'(id INTEGER PRIMARY KEY, sz BLOB)" }, + { "filenames_config", "CREATE TABLE 'filenames_config'(k PRIMARY KEY, v) WITHOUT ROWID" }, + { "files", "CREATE TABLE files (maskedFilename TEXT PRIMARY KEY, originalFilename TEXT NOT NULL, size BIGINT NOT NULL, touchedAt TEXT NOT NULL, code INTEGER DEFAULT 1 NOT NULL, extension TEXT, attributeJson TEXT NOT NULL, timestamp INTEGER NOT NULL)" }, + }; + + try + { + Log.Debug("Validating shares database with connection string {String}", ConnectionString); + + using var conn = new SqliteConnection(ConnectionString); + conn.Open(); + + using var cmd = new SqliteCommand("SELECT name, sql from sqlite_master WHERE type = 'table';", conn); + + var reader = cmd.ExecuteReader(); + var rows = 0; + + while (reader.Read()) + { + var table = reader.GetString(0); + var expectedSql = reader.GetString(1); + + if (schema.TryGetValue(table, out var actualSql)) + { + if (actualSql != expectedSql) + { + list.Add($"Expected {table} schema to be {expectedSql}, found {actualSql}"); + } + else + { + Log.Debug("Shares database table {Table} is valid: {Actual}", table, actualSql); + } + } + + rows++; + } + + if (rows != schema.Count) + { + list.Add($"Expected {schema.Count} tables, found {rows}"); + } + + return !problems.Any(); + } + catch (Exception ex) + { + Log.Debug(ex, $"Failed to validate database: {ex.Message}"); + list.Add($"Failed to validate database: {ex.Message}"); + return false; + } + } + /// /// Updates the scan started at the specified to set the . /// -- cgit v1.2.3 From 09348537947ff6a2a405754ead0904eaee848203 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 15 Oct 2022 15:46:30 -0500 Subject: simplify uploads --- src/slskd/Network/NetworkClient.cs | 30 ++++++------------------------ 1 file changed, 6 insertions(+), 24 deletions(-) (limited to 'src/slskd/Network/NetworkClient.cs') diff --git a/src/slskd/Network/NetworkClient.cs b/src/slskd/Network/NetworkClient.cs index 15f114f9..d171e9b9 100644 --- a/src/slskd/Network/NetworkClient.cs +++ b/src/slskd/Network/NetworkClient.cs @@ -134,30 +134,13 @@ namespace slskd.Network var token = await HubConnection.InvokeAsync(nameof(NetworkHub.GetShareUploadToken)); Log.Debug("Share upload token {Token}", token); - FileStream stream = default; + var stream = new FileStream(temp, FileMode.Open, FileAccess.Read); - while (true) - { - try - { - stream = new FileStream(temp, FileMode.Open, FileAccess.Read); - break; - } - catch (Exception ex) - { - // this happens if SQLite hangs on to the connection for whatever reason, seemingly due to pooling - // Pooling=False should be included in the connection string and this shouldn't be an issue, but - // since i don't totally understand the behavior, i'll leave this for now. - Log.Debug(ex, "Failed open stream to backup. Clearing SQLite pools and trying again."); - SqliteConnection.ClearAllPools(); - await Task.Delay(100); - } - } - - using var request = new HttpRequestMessage(HttpMethod.Post, $"api/v0/agents/shares/{token}"); + using var request = new HttpRequestMessage(HttpMethod.Post, $"api/v0/network/shares/{token}"); using var content = new MultipartFormDataContent { - { new StreamContent(stream), "shares" }, + { new StringContent(Shares.LocalHost.Shares.ToJson()), "shares" }, + { new StreamContent(stream), "database", "shares" }, }; request.Content = content; @@ -190,7 +173,7 @@ namespace slskd.Network } using var stream = new FileStream(localFileInfo.FullName, FileMode.Open, FileAccess.Read); - using var request = new HttpRequestMessage(HttpMethod.Post, $"api/v0/agents/files/{id}"); + using var request = new HttpRequestMessage(HttpMethod.Post, $"api/v0/network/files/{id}"); using var content = new MultipartFormDataContent { { new StreamContent(stream), "file", filename }, @@ -215,8 +198,7 @@ namespace slskd.Network Log.Error(ex, "Failed to handle file request: {Message}", ex.Message); // report the failure to the controller. this avoids a failure due to timeout. - using var request = new HttpRequestMessage(HttpMethod.Delete, $"api/v0/agents/files/{id}"); - _ = HttpClient.SendAsync(request); + await HubConnection.InvokeAsync(nameof(NetworkHub.NotifyUploadFailed), id); } } -- cgit v1.2.3 From 8663b3fac9597f7b0c6ffd8081b99c761a18b326 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 15 Oct 2022 19:09:41 -0500 Subject: add file info handling --- src/slskd/Network/API/Hubs/NetworkHub.cs | 16 +++- src/slskd/Network/NetworkClient.cs | 25 +++++- src/slskd/Network/NetworkService.cs | 141 ++++++++++++++++++++++--------- 3 files changed, 139 insertions(+), 43 deletions(-) (limited to 'src/slskd/Network/NetworkClient.cs') diff --git a/src/slskd/Network/API/Hubs/NetworkHub.cs b/src/slskd/Network/API/Hubs/NetworkHub.cs index 6d43e6da..f79fecf2 100644 --- a/src/slskd/Network/API/Hubs/NetworkHub.cs +++ b/src/slskd/Network/API/Hubs/NetworkHub.cs @@ -26,6 +26,7 @@ namespace slskd.Network public static class NetworkHubMethods { public static readonly string RequestFile = "REQUEST_FILE"; + public static readonly string RequestFileInfo = "REQUEST_FILE_INFO"; public static readonly string AuthenticationChallenge = "AUTHENTICATION_CHALLENGE"; public static readonly string AuthenticationChallengeAccepted = "AUTHENTICATION_CHALLENGE_ACCEPTED"; public static readonly string AuthenticationChallengeRejected = "AUTHENTICATION_CHALLENGE_REJECTED"; @@ -41,6 +42,11 @@ namespace slskd.Network // todo: how to send this to the specified agent? return hub.Clients.All.SendAsync(NetworkHubMethods.RequestFile, filename, id); } + + public static Task RequestFileInfoAsync(this IHubContext hub, string agent, string filename, Guid id) + { + return hub.Clients.All.SendAsync(NetworkHubMethods.RequestFileInfo, filename, id); + } } /// @@ -104,7 +110,15 @@ namespace slskd.Network { if (Network.PendingFileUploads.TryGetValue(id, out var record)) { - record.Stream.SetException(new NotFoundException("The file could not be uploaded from the remote agent")); + record.Stream.TrySetException(new NotFoundException("The file could not be uploaded from the remote agent")); + } + } + + public void ReturnFileInfo(Guid id, bool exists, long length) + { + if (Network.PendingFileInquiries.TryGetValue(id, out var record)) + { + record.TrySetResult((exists, length)); } } } diff --git a/src/slskd/Network/NetworkClient.cs b/src/slskd/Network/NetworkClient.cs index d171e9b9..6e4e4dca 100644 --- a/src/slskd/Network/NetworkClient.cs +++ b/src/slskd/Network/NetworkClient.cs @@ -156,7 +156,7 @@ namespace slskd.Network Log.Information("Upload shares succeeded"); } - private async Task HandleFileRequest(Guid id, string filename) + private async Task HandleFileRequest(string filename, Guid id) { Log.Information("Network controller requested file {Filename} with ID {Id}", filename, id); @@ -164,7 +164,7 @@ namespace slskd.Network { var localFilename = await Shares.ResolveFileAsync(filename); - var localFileInfo = new FileInfo(filename); + var localFileInfo = new FileInfo(localFilename); if (!localFileInfo.Exists) { @@ -202,6 +202,25 @@ namespace slskd.Network } } + private async Task HandleFileInfoRequest(string filename, Guid id) + { + Log.Information("Network 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(NetworkHub.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(NetworkHub.ReturnFileInfo), id, false, 0); + } + } + private async Task HandleAuthenticationChallenge(string challengeToken) { Log.Debug("Network controller sent an authentication challenge"); @@ -296,7 +315,7 @@ namespace slskd.Network HubConnection.Reconnecting += HubConnection_Reconnecting; HubConnection.Closed += HubConnection_Closed; - HubConnection.On(NetworkHubMethods.RequestFile, HandleFileRequest); + HubConnection.On(NetworkHubMethods.RequestFile, HandleFileRequest); HubConnection.On(NetworkHubMethods.AuthenticationChallenge, HandleAuthenticationChallenge); LastOptionsHash = optionsHash; diff --git a/src/slskd/Network/NetworkService.cs b/src/slskd/Network/NetworkService.cs index 8753ae0a..d857cac5 100644 --- a/src/slskd/Network/NetworkService.cs +++ b/src/slskd/Network/NetworkService.cs @@ -37,11 +37,25 @@ namespace slskd.Network /// ReadOnlyDictionary Stream, TaskCompletionSource Completion)> PendingFileUploads { get; } + /// + /// Gets the collection of pending Agent file inquiries. + /// + ReadOnlyDictionary> PendingFileInquiries { get; } + /// /// Gets the collection of registered Agents. /// ReadOnlyDictionary RegisteredAgents { get; } + /// + /// Retrieves information about the specified from the specified . + /// + /// The agent from which to retrieve the file information. + /// The file for which to retrieve information. + /// An optional timeout value. + /// A value indicating whether the file exists, and the length in bytes. + Task<(bool Exists, long Length)> GetFileInfo(string agent, string filename, int timeout = 3000); + /// /// Retrieves an upload of the specified from the specified . /// @@ -131,12 +145,18 @@ namespace slskd.Network /// public ReadOnlyDictionary Stream, TaskCompletionSource Completion)> PendingFileUploads => new(PendingFileUploadDictionary); + /// + /// Gets the collection of pending Agent file inquiries. + /// + public ReadOnlyDictionary> PendingFileInquiries => new(PendingFileInquiryDictionary); + /// /// Gets the collection of registered Agents. /// public ReadOnlyDictionary RegisteredAgents => new(RegisteredAgentDictionary); private ConcurrentDictionary Stream, TaskCompletionSource Completion)> PendingFileUploadDictionary { get; } = new(); + private ConcurrentDictionary> PendingFileInquiryDictionary { get; } = new(); private ConcurrentDictionary RegisteredAgentDictionary { get; } = new(); private MemoryCache MemoryCache { get; } = new MemoryCache(new MemoryCacheOptions()); private IOptionsMonitor OptionsMonitor { get; } @@ -144,6 +164,88 @@ namespace slskd.Network private ILogger Log { get; } = Serilog.Log.ForContext(); private SemaphoreSlim SyncRoot { get; } = new SemaphoreSlim(1, 1); + /// + /// Retrieves information about the specified from the specified . + /// + /// The agent from which to retrieve the file information. + /// The file for which to retrieve information. + /// An optional timeout value. + /// A value indicating whether the file exists, and the length in bytes. + public async Task<(bool Exists, long Length)> GetFileInfo(string agent, string filename, int timeout = 3000) + { + var id = Guid.NewGuid(); + var tcs = new TaskCompletionSource<(bool Exists, long Length)>(); + + PendingFileInquiryDictionary.TryAdd(id, tcs); + + try + { + await NetworkHub.RequestFileInfoAsync(agent, filename, id); + Log.Information("Requested file information for {Filename} from Agent {Agent} with ID {Id}. Waiting for response.", filename, agent, id); + + var task = await Task.WhenAny(tcs.Task, Task.Delay(timeout)); + + if (task == tcs.Task) + { + return await tcs.Task; + } + else + { + throw new TimeoutException($"Timed out attempting to retrieve file information for {filename} from Agent {agent}"); + } + } + finally + { + PendingFileInquiryDictionary.TryRemove(id, out _); + } + } + + /// + /// Retrieves an upload of the specified from the specified . + /// + /// The agent from which to retrieve the file. + /// The file to retrieve. + /// An optional timeout value. + /// The operation context, including a stream containing the requested file, and an upload TaskCompletionSource. + public async Task<(Stream Stream, TaskCompletionSource Completion)> GetFileUpload(string agent, string filename, int timeout = 3000) + { + var id = Guid.NewGuid(); + + // create a TCS for the upload stream. this is awaited below and completed in + // the API controller when the agent POSTs the file + var upload = new TaskCompletionSource(); + + // create a TCS for the upload itself. this is awaited by the API controller + // and completed by the transfer service when the upload to the remote user is complete + // the API controller needs to wait until the remote transfer is complete in order to + // keep the stream open for the duration + var completion = new TaskCompletionSource(); + + PendingFileUploadDictionary.TryAdd(id, (upload, completion)); + + try + { + await NetworkHub.RequestFileAsync(agent, filename, id); + Log.Information("Requested file {Filename} from Agent {Agent} with ID {Id}. Waiting for incoming connection.", filename, agent, id); + + var task = await Task.WhenAny(upload.Task, Task.Delay(timeout)); + + if (task == upload.Task) + { + var stream = await upload.Task; + return (stream, completion); + } + else + { + throw new TimeoutException($"Timed out attempting to retrieve the file {filename} from agent {agent}"); + } + } + finally + { + PendingFileUploadDictionary.TryRemove(id, out _); + } + } + /// /// Retrieves a new share upload token for the specified . /// @@ -249,45 +351,6 @@ namespace slskd.Network return expectedResponse == challengeResponse; } - /// - /// Retrieves an upload of the specified from the specified . - /// - /// The agent from which to retrieve the file. - /// The file to retrieve. - /// An optional timeout value. - /// The operation context, including a stream containing the requested file, and an upload TaskCompletionSource. - public async Task<(Stream Stream, TaskCompletionSource Completion)> GetFileUpload(string agent, string filename, int timeout = 3000) - { - var id = Guid.NewGuid(); - - // create a TCS for the upload stream. this is awaited below and completed in - // the API controller when the agent POSTs the file - var upload = new TaskCompletionSource(); - - // create a TCS for the upload itself. this is awaited by the API controller - // and completed by the transfer service when the upload to the remote user is complete - // the API controller needs to wait until the remote transfer is complete in order to - // keep the stream open for the duration - var completion = new TaskCompletionSource(); - - PendingFileUploadDictionary.TryAdd(id, (upload, completion)); - - await NetworkHub.RequestFileAsync(agent, filename, id); - Log.Information("Requested file {Filename} from Agent {Agent} with ID {Id}. Waiting for incoming connection.", filename, agent, id); - - var task = await Task.WhenAny(upload.Task, Task.Delay(timeout)); - - if (task == upload.Task) - { - var stream = await upload.Task; - return (stream, completion); - } - else - { - throw new TimeoutException($"Timed out attempting to retrieve the file {filename} from agent {agent}"); - } - } - private string GetAuthTokenCacheKey(string connectionId) => $"{connectionId}.auth"; private string GetShareTokenCacheKey(Guid token) => $"{token}.share"; -- cgit v1.2.3 From add16a356b84c838d1cc9f2d5821f77d2284de1a Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 15 Oct 2022 19:17:06 -0500 Subject: get length from agent --- src/slskd/Network/NetworkClient.cs | 4 ++-- src/slskd/Transfers/Uploads/UploadService.cs | 10 +++++++++- 2 files changed, 11 insertions(+), 3 deletions(-) (limited to 'src/slskd/Network/NetworkClient.cs') diff --git a/src/slskd/Network/NetworkClient.cs b/src/slskd/Network/NetworkClient.cs index 6e4e4dca..355e94d6 100644 --- a/src/slskd/Network/NetworkClient.cs +++ b/src/slskd/Network/NetworkClient.cs @@ -162,7 +162,7 @@ namespace slskd.Network try { - var localFilename = await Shares.ResolveFileAsync(filename); + var (_, localFilename) = await Shares.ResolveFileAsync(filename); var localFileInfo = new FileInfo(localFilename); @@ -208,7 +208,7 @@ namespace slskd.Network try { - var localFilename = await Shares.ResolveFileAsync(filename); + var (_, localFilename) = await Shares.ResolveFileAsync(filename); var localFileInfo = new FileInfo(localFilename); diff --git a/src/slskd/Transfers/Uploads/UploadService.cs b/src/slskd/Transfers/Uploads/UploadService.cs index 2d07e501..58d93e86 100644 --- a/src/slskd/Transfers/Uploads/UploadService.cs +++ b/src/slskd/Transfers/Uploads/UploadService.cs @@ -133,7 +133,15 @@ namespace slskd.Transfers.Uploads } else { - localFileLength = 9001; + var (exists, length) = await Network.GetFileInfo(agent: host, filename); + + if (!exists || length <= 0) + { + // todo: force a remote scan + throw new NotFoundException($"The file '{localFilename}' could not be located on Agent {host}. A share scan should be performed."); + } + + localFileLength = length; } } catch (NotFoundException) -- cgit v1.2.3 From ed0531fa2e2ec9f310e8932c39160d19f3e80609 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 15 Oct 2022 19:24:43 -0500 Subject: handle info requests --- src/slskd/Network/NetworkClient.cs | 1 + 1 file changed, 1 insertion(+) (limited to 'src/slskd/Network/NetworkClient.cs') diff --git a/src/slskd/Network/NetworkClient.cs b/src/slskd/Network/NetworkClient.cs index 355e94d6..baaa1250 100644 --- a/src/slskd/Network/NetworkClient.cs +++ b/src/slskd/Network/NetworkClient.cs @@ -316,6 +316,7 @@ namespace slskd.Network HubConnection.Closed += HubConnection_Closed; HubConnection.On(NetworkHubMethods.RequestFile, HandleFileRequest); + HubConnection.On(NetworkHubMethods.RequestFileInfo, HandleFileInfoRequest); HubConnection.On(NetworkHubMethods.AuthenticationChallenge, HandleAuthenticationChallenge); LastOptionsHash = optionsHash; -- cgit v1.2.3