diff options
| author | JP Dillingham <jp@dillingham.me> | 2022-10-15 15:55:29 -0500 |
|---|---|---|
| committer | JP Dillingham <jp@dillingham.me> | 2022-10-15 15:55:29 -0500 |
| commit | bfaef428f820a7a3ee7145e5c28007e09d90f4ba (patch) | |
| tree | 259f2407af751672f042a7a9980998edff77ce06 | |
| parent | 6981e3b3e3ae54f55e0319e0bdd1038506eae081 (diff) | |
| parent | cdf397d340a1a4c2b4c5077adce997854a0787b2 (diff) | |
| download | slskd-bfaef428f820a7a3ee7145e5c28007e09d90f4ba.tar.gz | |
Merge branch 'agent' of github.com:slskd/slskd into agent
| -rw-r--r-- | src/slskd/Core/Options.cs | 3 | ||||
| -rw-r--r-- | src/slskd/Network/API/Controllers/NetworkController.cs | 36 | ||||
| -rw-r--r-- | src/slskd/Network/API/Hubs/NetworkHub.cs | 8 | ||||
| -rw-r--r-- | src/slskd/Network/NetworkClient.cs | 30 | ||||
| -rw-r--r-- | src/slskd/Network/NetworkService.cs | 18 | ||||
| -rw-r--r-- | src/slskd/Shares/IShareService.cs | 20 | ||||
| -rw-r--r-- | src/slskd/Shares/ShareService.cs | 45 | ||||
| -rw-r--r-- | src/slskd/Shares/SqliteShareRepository.cs | 6 | ||||
| -rw-r--r-- | src/slskd/Shares/Types/Host.cs | 18 | ||||
| -rw-r--r-- | src/slskd/Shares/Types/HostState.cs | 35 | ||||
| -rw-r--r-- | src/slskd/Shares/Types/HostType.cs | 35 |
11 files changed, 114 insertions, 140 deletions
diff --git a/src/slskd/Core/Options.cs b/src/slskd/Core/Options.cs index c8ccbd69..b75f9356 100644 --- a/src/slskd/Core/Options.cs +++ b/src/slskd/Core/Options.cs @@ -401,6 +401,9 @@ namespace slskd public IEnumerable<ValidationResult> Validate(ValidationContext validationContext) { var results = new List<ValidationResult>(); + + // todo: can't run in agent mode if instancename is default + //var controllerResults = new List<ValidationResult>(); //var agentResults = new List<ValidationResult>(); diff --git a/src/slskd/Network/API/Controllers/NetworkController.cs b/src/slskd/Network/API/Controllers/NetworkController.cs index deeddc04..21373749 100644 --- a/src/slskd/Network/API/Controllers/NetworkController.cs +++ b/src/slskd/Network/API/Controllers/NetworkController.cs @@ -18,10 +18,12 @@ namespace slskd.Network { using System; + using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Authorization; + using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using Serilog; using slskd.Shares; @@ -86,36 +88,32 @@ namespace slskd.Network } } - [HttpDelete("files/{id}")] + [HttpPost("shares/{id}")] [Authorize] - public IActionResult NotifyUploadFailed(string id) + public async Task<IActionResult> UploadShares(string id) { if (!Guid.TryParse(id, out var guid)) { return BadRequest("Id is not a valid Guid"); } - if (Network.PendingFileUploads.TryGetValue(guid, out var record)) + if (!Network.TryGetShareUploadToken(guid, out var agent)) { - record.Stream.SetException(new NotFoundException($"The file could not be uploaded from the remote agent")); - return NoContent(); + return Unauthorized(); } - return NotFound(); - } + IEnumerable<Share> shares; + IFormFile database; - [HttpPost("shares/{id}")] - [Authorize] - public async Task<IActionResult> UploadShares(string id) - { - if (!Guid.TryParse(id, out var guid)) + try { - return BadRequest("Id is not a valid Guid"); + shares = Request.Form["shares"].ToString().FromJson<IEnumerable<Share>>(); + database = Request.Form.Files[0]; } - - if (!Network.TryGetShareUploadToken(guid, out var agent)) + catch (Exception ex) { - return Unauthorized(); + Log.Warning("Failed to handle share upload from agent {Agent}: {Message}", agent, ex.Message); + return BadRequest(); } var temp = Path.Combine(Path.GetTempPath(), $"slskd_share_{agent}_{Path.GetRandomFileName()}.db"); @@ -123,7 +121,7 @@ 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[0].OpenReadStream(); + using var inputStream = database.OpenReadStream(); await inputStream.CopyToAsync(outputStream); @@ -133,13 +131,15 @@ namespace slskd.Network if (!repository.TryValidate(out var problems)) { - return BadRequest(string.Join(", ", problems)); + return BadRequest("Invalid database: " + string.Join(", ", problems)); } var destinationRepository = ShareRepositoryFactory.CreateFromHost(agent); destinationRepository.RestoreFrom(repository); + Shares.AddOrUpdateHost(new Host(agent, shares)); + return Ok(); } } diff --git a/src/slskd/Network/API/Hubs/NetworkHub.cs b/src/slskd/Network/API/Hubs/NetworkHub.cs index 78a658d4..6d43e6da 100644 --- a/src/slskd/Network/API/Hubs/NetworkHub.cs +++ b/src/slskd/Network/API/Hubs/NetworkHub.cs @@ -99,5 +99,13 @@ namespace slskd.Network Log.Information("Agent connection {Id} requested a share upload token, but was not registered.", Context.ConnectionId); throw new UnauthorizedAccessException(); } + + public void NotifyUploadFailed(Guid id) + { + if (Network.PendingFileUploads.TryGetValue(id, out var record)) + { + record.Stream.SetException(new NotFoundException("The file could not be uploaded from the remote agent")); + } + } } }
\ No newline at end of file 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<Guid>(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); } } diff --git a/src/slskd/Network/NetworkService.cs b/src/slskd/Network/NetworkService.cs index 6c573da0..8753ae0a 100644 --- a/src/slskd/Network/NetworkService.cs +++ b/src/slskd/Network/NetworkService.cs @@ -23,6 +23,7 @@ namespace slskd.Network using System.Collections.Concurrent; using System.Collections.ObjectModel; using System.IO; + using System.Threading; using System.Threading.Tasks; using Microsoft.AspNetCore.SignalR; using Microsoft.Extensions.Caching.Memory; @@ -120,6 +121,9 @@ namespace slskd.Network NetworkHub = networkHub; OptionsMonitor = optionsMonitor; + OptionsMonitor.OnChange(options => Configure(options)); + + Configure(OptionsMonitor.CurrentValue); } /// <summary> @@ -138,6 +142,7 @@ namespace slskd.Network private IOptionsMonitor<Options> OptionsMonitor { get; } private IHubContext<NetworkHub> NetworkHub { get; set; } private ILogger Log { get; } = Serilog.Log.ForContext<NetworkService>(); + private SemaphoreSlim SyncRoot { get; } = new SemaphoreSlim(1, 1); /// <summary> /// Retrieves a new share upload token for the specified <paramref name="agent"/>. @@ -285,5 +290,18 @@ namespace slskd.Network private string GetAuthTokenCacheKey(string connectionId) => $"{connectionId}.auth"; private string GetShareTokenCacheKey(Guid token) => $"{token}.share"; + + private void Configure(Options options) + { + SyncRoot.Wait(); + + try + { + } + finally + { + SyncRoot.Release(); + } + } } } diff --git a/src/slskd/Shares/IShareService.cs b/src/slskd/Shares/IShareService.cs index b55db482..f0c474a1 100644 --- a/src/slskd/Shares/IShareService.cs +++ b/src/slskd/Shares/IShareService.cs @@ -32,6 +32,11 @@ namespace slskd.Shares IReadOnlyList<Host> Hosts { get; } /// <summary> + /// Gets the local share host. + /// </summary> + Host LocalHost { get; } + + /// <summary> /// Gets the state monitor for the service. /// </summary> IStateMonitor<ShareState> StateMonitor { get; } @@ -56,6 +61,14 @@ namespace slskd.Shares Task DumpAsync(string filename); /// <summary> + /// Returns the share host with the specified <paramref name="name"/>. + /// </summary> + /// <param name="name">The name of the host.</param> + /// <param name="host">The host, if found.</param> + /// <returns>A value indicating whether the host was found.</returns> + bool TryGetHost(string name, out Host host); + + /// <summary> /// Returns the contents of the specified <paramref name="directory"/>. /// </summary> /// <param name="directory">The directory for which the contents are to be listed.</param> @@ -63,6 +76,13 @@ namespace slskd.Shares Task<Directory> ListDirectoryAsync(string directory); /// <summary> + /// Removes the share host with the specified <paramref name="name"/>. + /// </summary> + /// <param name="name">The name of the host.</param> + /// <returns>A value indicating whether the host was removed.</returns> + bool TryRemoveHost(string name); + + /// <summary> /// Resolves the local filename of the specified <paramref name="remoteFilename"/>, if the mask is associated with a /// configured share. /// </summary> diff --git a/src/slskd/Shares/ShareService.cs b/src/slskd/Shares/ShareService.cs index cc35477e..03b0f2e1 100644 --- a/src/slskd/Shares/ShareService.cs +++ b/src/slskd/Shares/ShareService.cs @@ -51,8 +51,8 @@ namespace slskd.Shares ShareRepositoryFactory = shareRepositoryFactory; - var host = new Host(options.InstanceName, type: HostType.Local, state: HostState.Online); - var repository = ShareRepositoryFactory.CreateFromHost(options.InstanceName); + var host = new Host("local"); + var repository = ShareRepositoryFactory.CreateFromHost(host.Name); Local = (host, repository); @@ -94,6 +94,11 @@ namespace slskd.Shares public IReadOnlyList<Host> Hosts => HostDictionary.Values.Select(v => v.Host).Prepend(Local.Host).ToList().AsReadOnly(); /// <summary> + /// Gets the local share host. + /// </summary> + public Host LocalHost => Local.Host; + + /// <summary> /// Gets the state monitor for the service. /// </summary> public IStateMonitor<ShareState> StateMonitor { get; } @@ -124,7 +129,6 @@ namespace slskd.Shares updateValueFactory: (_, existing) => (host, existing.Repository)); AllRepositories = HostDictionary.Values - .Where(value => value.Host.State == HostState.Online) .Select(value => value.Repository) .Prepend(Local.Repository); } @@ -193,6 +197,32 @@ namespace slskd.Shares } /// <summary> + /// Returns the share host with the specified <paramref name="name"/>. + /// </summary> + /// <param name="name">The name of the host.</param> + /// <param name="host">The host, if found.</param> + /// <returns>A value indicating whether the host was found.</returns> + public bool TryGetHost(string name, out Host host) + { + if (HostDictionary.TryGetValue(name, out var record)) + { + host = record.Host; + return true; + } + + host = null; + return false; + } + + /// <summary> + /// Removes the share host with the specified <paramref name="name"/>. + /// </summary> + /// <param name="name">The name of the host.</param> + /// <returns>A value indicating whether the host was removed.</returns> + public bool TryRemoveHost(string name) + => HostDictionary.TryRemove(name, out _); + + /// <summary> /// Returns the contents of the specified <paramref name="directory"/>. /// </summary> /// <param name="directory">The directory for which the contents are to be listed.</param> @@ -264,7 +294,7 @@ namespace slskd.Shares await Scanner.ScanAsync(Local.Host.Shares, OptionsMonitor.CurrentValue.Shares); Log.Debug("Backing up shared file cache database..."); - Local.Repository.BackupTo(ShareRepositoryFactory.CreateFromHostBackup(OptionsMonitor.CurrentValue.InstanceName)); + Local.Repository.BackupTo(ShareRepositoryFactory.CreateFromHostBackup(Local.Host.Name)); Log.Debug("Shared file cache database backup complete"); } @@ -311,7 +341,7 @@ namespace slskd.Shares { Log.Information("Share cache StorageMode is 'Memory'. Attempting to load from backup..."); - var backupRepository = ShareRepositoryFactory.CreateFromHostBackup(OptionsMonitor.CurrentValue.InstanceName); + var backupRepository = ShareRepositoryFactory.CreateFromHostBackup(Local.Host.Name); if (backupRepository.TryValidate(out _)) { @@ -339,7 +369,7 @@ namespace slskd.Shares { Log.Warning("Share cache is missing, corrupt, or is out of date. Attempting to load from backup..."); - var backupRepository = ShareRepositoryFactory.CreateFromHostBackup(OptionsMonitor.CurrentValue.InstanceName); + var backupRepository = ShareRepositoryFactory.CreateFromHostBackup(Local.Host.Name); if (backupRepository.TryValidate(out _)) { @@ -413,9 +443,6 @@ namespace slskd.Shares Local = (Local.Host with { Shares = shares }, Local.Repository); - // todo: initialize agent hosts - // todo: don't destroy or overwrite existing hosts! - LastOptionsHash = optionsHash; } finally diff --git a/src/slskd/Shares/SqliteShareRepository.cs b/src/slskd/Shares/SqliteShareRepository.cs index 9b65794e..0a71280d 100644 --- a/src/slskd/Shares/SqliteShareRepository.cs +++ b/src/slskd/Shares/SqliteShareRepository.cs @@ -160,10 +160,10 @@ namespace slskd.Shares public void DumpTo(string filename) { using var sourceConn = GetConnection(ConnectionString); - using var backupConn = GetConnection($"Data Source={filename}"); - sourceConn.BackupDatabase(backupConn); - Sqlite. + // very important! don't use pooling for the backup connection or the file will remain locked + using var backupConn = GetConnection($"Data Source={filename};Pooling=False"); + sourceConn.BackupDatabase(backupConn); } /// <summary> diff --git a/src/slskd/Shares/Types/Host.cs b/src/slskd/Shares/Types/Host.cs index 3c5c9f9f..50302480 100644 --- a/src/slskd/Shares/Types/Host.cs +++ b/src/slskd/Shares/Types/Host.cs @@ -29,36 +29,22 @@ namespace slskd.Shares /// Initializes a new instance of the <see cref="Host"/> class. /// </summary> /// <param name="name">The name of the host.</param> - /// <param name="type">The type of the host.</param> /// <param name="shares">The collection of hosted shares.</param> - /// <param name="state">The initial state of the host.</param> - public Host(string name, HostType type, IEnumerable<Share> shares = null, HostState state = HostState.Offline) + public Host(string name, IEnumerable<Share> shares = null) { Name = name; - Type = type; Shares = shares ?? Enumerable.Empty<Share>(); - State = state; } /// <summary> /// Gets the name of the host. /// </summary> - /// <remarks>Corresponds to the configured <see cref="Options.InstanceName"/> of the host.</remarks> + /// <remarks>Corresponds to the configured <see cref="Options.InstanceName"/> of the host, or "local" for the local host.</remarks> public string Name { get; } /// <summary> /// Gets the collection of hosted shares. /// </summary> public IEnumerable<Share> Shares { get; init; } - - /// <summary> - /// Gets the host state. - /// </summary> - public HostState State { get; init; } - - /// <summary> - /// Gets the host type. - /// </summary> - public HostType Type { get; } } }
\ No newline at end of file diff --git a/src/slskd/Shares/Types/HostState.cs b/src/slskd/Shares/Types/HostState.cs deleted file mode 100644 index b10074d3..00000000 --- a/src/slskd/Shares/Types/HostState.cs +++ /dev/null @@ -1,35 +0,0 @@ -// <copyright file="HostState.cs" company="slskd Team"> -// Copyright (c) slskd Team. All rights reserved. -// -// This program is free software: you can redistribute it and/or modify -// it under the terms of the GNU Affero General Public License as published -// by the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU Affero General Public License for more details. -// -// You should have received a copy of the GNU Affero General Public License -// along with this program. If not, see https://www.gnu.org/licenses/. -// </copyright> - -namespace slskd.Shares -{ - /// <summary> - /// The state of a share host. - /// </summary> - public enum HostState - { - /// <summary> - /// Offline; unable to service requests. - /// </summary> - Offline = 0, - - /// <summary> - /// Online; able to service requests. - /// </summary> - Online = 1, - } -} diff --git a/src/slskd/Shares/Types/HostType.cs b/src/slskd/Shares/Types/HostType.cs deleted file mode 100644 index 6a892dff..00000000 --- a/src/slskd/Shares/Types/HostType.cs +++ /dev/null @@ -1,35 +0,0 @@ -// <copyright file="HostType.cs" company="slskd Team"> -// Copyright (c) slskd Team. All rights reserved. -// -// This program is free software: you can redistribute it and/or modify -// it under the terms of the GNU Affero General Public License as published -// by the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU Affero General Public License for more details. -// -// You should have received a copy of the GNU Affero General Public License -// along with this program. If not, see https://www.gnu.org/licenses/. -// </copyright> - -namespace slskd.Shares -{ - /// <summary> - /// The type of host. - /// </summary> - public enum HostType - { - /// <summary> - /// Local. - /// </summary> - Local = 0, - - /// <summary> - /// Remote; shares are hosted by an Agent. - /// </summary> - Remote = 1, - } -} |
