aboutsummaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorJP Dillingham <jpdillingham@gmail.com>2021-07-24 14:39:40 -0500
committerGitHub <noreply@github.com>2021-07-24 14:39:40 -0500
commit58bc401dab5d7eb3bc6cb07a22e0ee9c97ddf4bd (patch)
tree64072f5eaa896335cc04de8ffe84fa79a50a2be7
parentfc7800409dfbe0cf26a72dd1de17cbae23d0cb35 (diff)
parent78b3b953d9c36c2cc2939ad00881b0cbf388865a (diff)
downloadslskd-58bc401dab5d7eb3bc6cb07a22e0ee9c97ddf4bd.tar.gz
Merge pull request #125 from slskd/options
Refactor configuration components to allow for run-time updates
-rw-r--r--src/slskd/Application/IStateMonitor.cs46
-rw-r--r--src/slskd/Application/Management/API/Controllers/ApplicationController.cs4
-rw-r--r--src/slskd/Application/Management/API/Controllers/OptionsController.cs71
-rw-r--r--src/slskd/Application/Management/API/Controllers/SessionController.cs17
-rw-r--r--src/slskd/Application/Management/IManagementService.cs14
-rw-r--r--src/slskd/Application/Management/ManagementService.cs25
-rw-r--r--src/slskd/Application/Service.cs215
-rw-r--r--src/slskd/Application/State.cs24
-rw-r--r--src/slskd/Application/StateMonitor.cs94
-rw-r--r--src/slskd/Application/Transfer/API/Controllers/TransfersController.cs4
-rw-r--r--src/slskd/Common/Configuration/RequiresReconnectAttribute.cs26
-rw-r--r--src/slskd/Common/Configuration/RequiresRestartAttribute.cs26
-rw-r--r--src/slskd/Common/Configuration/YamlConfigurationSource.cs15
-rw-r--r--src/slskd/Common/Extensions.cs60
-rw-r--r--src/slskd/Integrations/FTP/FTPClientFactory.cs38
-rw-r--r--src/slskd/Integrations/FTP/FTPService.cs10
-rw-r--r--src/slskd/Integrations/Pushbullet/IPushbulletService.cs3
-rw-r--r--src/slskd/Integrations/Pushbullet/PushbulletService.cs40
-rw-r--r--src/slskd/Options.cs126
-rw-r--r--src/slskd/Program.cs55
-rw-r--r--src/slskd/Properties/analysis.ruleset1
-rw-r--r--src/slskd/Properties/slskd.yml135
-rw-r--r--src/slskd/Startup.cs59
23 files changed, 889 insertions, 219 deletions
diff --git a/src/slskd/Application/IStateMonitor.cs b/src/slskd/Application/IStateMonitor.cs
new file mode 100644
index 00000000..e4c8fc26
--- /dev/null
+++ b/src/slskd/Application/IStateMonitor.cs
@@ -0,0 +1,46 @@
+// <copyright file="IStateMonitor.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
+{
+ using System;
+
+ /// <summary>
+ /// Used for notifications when <see cref="State"/> changes.
+ /// </summary>
+ public interface IStateMonitor
+ {
+ /// <summary>
+ /// Gets the current application state.
+ /// </summary>
+ State Current { get; }
+
+ /// <summary>
+ /// Registers a listener to be called whenever <see cref="State"/> changes.
+ /// </summary>
+ /// <param name="listener">Registers a listener to be called whenver state changes.</param>
+ /// <returns>An <see cref="IDisposable"/> which should be disposed to stop listening for changes.</returns>
+ IDisposable OnChange(Action<(State Previous, State Current)> listener);
+
+ /// <summary>
+ /// Replaces the current state with the value resolved by the <paramref name="setter"/>.
+ /// </summary>
+ /// <param name="setter">Given the current state, resolves a new state value.</param>
+ /// <returns>The updated state.</returns>
+ State Set(Func<State, State> setter);
+ }
+}
diff --git a/src/slskd/Application/Management/API/Controllers/ApplicationController.cs b/src/slskd/Application/Management/API/Controllers/ApplicationController.cs
index f0121af9..ddac832a 100644
--- a/src/slskd/Application/Management/API/Controllers/ApplicationController.cs
+++ b/src/slskd/Application/Management/API/Controllers/ApplicationController.cs
@@ -51,8 +51,6 @@ namespace slskd.Management.API
[Authorize]
public IActionResult Shutdown()
{
- Client.Disconnect("Shut down via API");
-
Lifetime.StopApplication();
return NoContent();
}
@@ -65,8 +63,6 @@ namespace slskd.Management.API
[Authorize]
public IActionResult Restart()
{
- Client.Disconnect("Restarted via API");
-
Process.Start(Process.GetCurrentProcess().MainModule.FileName, Environment.CommandLine);
Lifetime.StopApplication();
diff --git a/src/slskd/Application/Management/API/Controllers/OptionsController.cs b/src/slskd/Application/Management/API/Controllers/OptionsController.cs
new file mode 100644
index 00000000..6f6275d1
--- /dev/null
+++ b/src/slskd/Application/Management/API/Controllers/OptionsController.cs
@@ -0,0 +1,71 @@
+// <copyright file="OptionsController.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>
+
+using Microsoft.Extensions.Options;
+
+namespace slskd.Management.API
+{
+ using Microsoft.AspNetCore.Authorization;
+ using Microsoft.AspNetCore.Mvc;
+
+ /// <summary>
+ /// Options.
+ /// </summary>
+ [Route("api/v{version:apiVersion}/[controller]")]
+ [ApiVersion("0")]
+ [ApiController]
+ [Produces("application/json")]
+ [Consumes("application/json")]
+ public class OptionsController : ControllerBase
+ {
+ public OptionsController(
+ OptionsAtStartup optionsAtStartup,
+ IOptionsSnapshot<Options> optionsSnapshot)
+ {
+ OptionsAtStartup = optionsAtStartup;
+ OptionsSnapshot = optionsSnapshot;
+ }
+
+ private IOptionsSnapshot<Options> OptionsSnapshot { get; }
+ private OptionsAtStartup OptionsAtStartup { get; }
+
+ /// <summary>
+ /// Gets the current application options.
+ /// </summary>
+ /// <returns></returns>
+ [HttpGet]
+ [Authorize]
+ [ProducesResponseType(typeof(Options), 200)]
+ public IActionResult Current()
+ {
+ return Ok(OptionsSnapshot.Value);
+ }
+
+ /// <summary>
+ /// Gets the application options provided at startup.
+ /// </summary>
+ /// <returns></returns>
+ [HttpGet]
+ [Route("startup")]
+ [Authorize]
+ [ProducesResponseType(typeof(Options), 200)]
+ public IActionResult Startup()
+ {
+ return Ok(OptionsAtStartup);
+ }
+ }
+}
diff --git a/src/slskd/Application/Management/API/Controllers/SessionController.cs b/src/slskd/Application/Management/API/Controllers/SessionController.cs
index 09a95c24..02e8257e 100644
--- a/src/slskd/Application/Management/API/Controllers/SessionController.cs
+++ b/src/slskd/Application/Management/API/Controllers/SessionController.cs
@@ -15,6 +15,8 @@
// along with this program. If not, see https://www.gnu.org/licenses/.
// </copyright>
+using Microsoft.Extensions.Options;
+
namespace slskd.Management.API
{
using System;
@@ -37,15 +39,18 @@ namespace slskd.Management.API
public class SessionController : ControllerBase
{
public SessionController(
- Microsoft.Extensions.Options.IOptionsSnapshot<Options> optionsSnapshot,
+ IOptionsSnapshot<Options> optionsSnapshot,
+ OptionsAtStartup optionsAtStartup,
SymmetricSecurityKey jwtSigningKey)
{
- Options = optionsSnapshot.Value;
+ OptionsSnapshot = optionsSnapshot;
+ OptionsAtStartup = optionsAtStartup;
JwtSigningKey = jwtSigningKey;
}
private SymmetricSecurityKey JwtSigningKey { get; set; }
- private Options Options { get; set; }
+ private IOptionsSnapshot<Options> OptionsSnapshot { get; set; }
+ private OptionsAtStartup OptionsAtStartup { get; set; }
/// <summary>
/// Checks whether the provided authentication is valid.
@@ -75,7 +80,7 @@ namespace slskd.Management.API
[ProducesResponseType(typeof(bool), 200)]
public IActionResult Enabled()
{
- return Ok(!Options.Web.Authentication.Disable);
+ return Ok(!OptionsAtStartup.Web.Authentication.Disable);
}
/// <summary>
@@ -106,7 +111,7 @@ namespace slskd.Management.API
}
// only admin login for now
- if (Options.Web.Authentication.Username == login.Username && Options.Web.Authentication.Password == login.Password)
+ if (OptionsSnapshot.Value.Web.Authentication.Username == login.Username && OptionsSnapshot.Value.Web.Authentication.Password == login.Password)
{
return Ok(new TokenResponse(GetJwtSecurityToken(login.Username, Role.Administrator)));
}
@@ -117,7 +122,7 @@ namespace slskd.Management.API
private JwtSecurityToken GetJwtSecurityToken(string username, Role role)
{
var issuedUtc = DateTime.UtcNow;
- var expiresUtc = DateTime.UtcNow.AddMilliseconds(Options.Web.Authentication.Jwt.Ttl);
+ var expiresUtc = DateTime.UtcNow.AddMilliseconds(OptionsAtStartup.Web.Authentication.Jwt.Ttl);
var claims = new List<Claim>()
{
diff --git a/src/slskd/Application/Management/IManagementService.cs b/src/slskd/Application/Management/IManagementService.cs
index 4ee2185e..b3e13477 100644
--- a/src/slskd/Application/Management/IManagementService.cs
+++ b/src/slskd/Application/Management/IManagementService.cs
@@ -26,6 +26,12 @@ namespace slskd.Management
public interface IManagementService
{
/// <summary>
+ /// Connects the Soulseek client to the server using the configured username and password.
+ /// </summary>
+ /// <returns>The operation context.</returns>
+ Task ConnectServerAsync();
+
+ /// <summary>
/// Disconnects the Soulseek client from the server.
/// </summary>
/// <param name="message">An optional message containing the reason for the disconnect.</param>
@@ -33,15 +39,9 @@ namespace slskd.Management
void DisconnectServer(string message = null, Exception exception = null);
/// <summary>
- /// Connects the Soulseek client to the server using the configured username and password.
- /// </summary>
- /// <returns>The operation context.</returns>
- Task ConnectServerAsync();
-
- /// <summary>
/// Gets the current state of the connection to the Soulseek server.
/// </summary>
/// <returns>The current server state.</returns>
ServerState GetServerState();
}
-}
+} \ No newline at end of file
diff --git a/src/slskd/Application/Management/ManagementService.cs b/src/slskd/Application/Management/ManagementService.cs
index 84935879..66ed2b97 100644
--- a/src/slskd/Application/Management/ManagementService.cs
+++ b/src/slskd/Application/Management/ManagementService.cs
@@ -15,6 +15,8 @@
// along with this program. If not, see https://www.gnu.org/licenses/.
// </copyright>
+using Microsoft.Extensions.Options;
+
namespace slskd.Management
{
using System;
@@ -32,15 +34,23 @@ namespace slskd.Management
/// <param name="optionsMonitor">The options monitor used to derive application options.</param>
/// <param name="soulseekClient">The Soulseek client.</param>
public ManagementService(
- Microsoft.Extensions.Options.IOptionsMonitor<Options> optionsMonitor,
+ IOptionsMonitor<Options> optionsMonitor,
ISoulseekClient soulseekClient)
{
- Options = optionsMonitor.CurrentValue;
+ OptionsMonitor = optionsMonitor;
Client = soulseekClient;
}
private ISoulseekClient Client { get; }
- private Options Options { get; }
+ private Options Options => OptionsMonitor.CurrentValue;
+ private IOptionsMonitor<Options> OptionsMonitor { get; }
+
+ /// <summary>
+ /// Connects the Soulseek client to the server using the configured username and password.
+ /// </summary>
+ /// <returns>The operation context.</returns>
+ public Task ConnectServerAsync()
+ => Client.ConnectAsync(Options.Soulseek.Username, Options.Soulseek.Password);
/// <summary>
/// Disconnects the Soulseek client from the server.
@@ -51,13 +61,6 @@ namespace slskd.Management
=> Client.Disconnect(message, exception ?? new IntentionalDisconnectException(message));
/// <summary>
- /// Connects the Soulseek client to the server using the configured username and password.
- /// </summary>
- /// <returns>The operation context.</returns>
- public Task ConnectServerAsync()
- => Client.ConnectAsync(Options.Soulseek.Username, Options.Soulseek.Password);
-
- /// <summary>
/// Gets the current state of the connection to the Soulseek server.
/// </summary>
/// <returns>The current server state.</returns>
@@ -70,4 +73,4 @@ namespace slskd.Management
Username = Client.Username,
};
}
-}
+} \ No newline at end of file
diff --git a/src/slskd/Application/Service.cs b/src/slskd/Application/Service.cs
index b40c43c9..62f6eb32 100644
--- a/src/slskd/Application/Service.cs
+++ b/src/slskd/Application/Service.cs
@@ -22,13 +22,14 @@ namespace slskd
using System.IO;
using System.Linq;
using System.Net;
- using System.Text.Json;
+ using System.Reflection;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Options;
using Serilog;
using Serilog.Events;
+ using slskd.Configuration;
using slskd.Integrations.Pushbullet;
using slskd.Messaging;
using slskd.Peer;
@@ -44,7 +45,9 @@ namespace slskd
private (int Directories, int Files) sharedCounts = (0, 0);
public Service(
- IOptionsMonitor<Options> optionMonitor,
+ OptionsAtStartup optionsAtStartup,
+ IOptionsMonitor<Options> optionsMonitor,
+ IStateMonitor stateMonitor,
ITransferTracker transferTracker,
IBrowseTracker browseTracker,
IConversationTracker conversationTracker,
@@ -52,10 +55,15 @@ namespace slskd
ISharedFileCache sharedFileCache,
IPushbulletService pushbulletService)
{
- OptionsMonitor = optionMonitor;
- OptionsMonitor.OnChange(options => OptionsChanged(options));
+ OptionsAtStartup = optionsAtStartup;
- Options = OptionsMonitor.CurrentValue;
+ OptionsMonitor = optionsMonitor;
+ OptionsMonitor.OnChange(async options => await OptionsMonitor_OnChange(options));
+
+ PreviousOptions = OptionsMonitor.CurrentValue;
+
+ StateMonitor = stateMonitor;
+ StateMonitor.OnChange(state => StateMonitor_OnChange(state));
TransferTracker = transferTracker;
BrowseTracker = browseTracker;
@@ -66,29 +74,29 @@ namespace slskd
ProxyOptions proxyOptions = default;
- if (UsingProxy)
+ if (OptionsAtStartup.Soulseek.Connection.Proxy.Enabled)
{
proxyOptions = new ProxyOptions(
- address: Options.Soulseek.Connection.Proxy.Address,
- port: Options.Soulseek.Connection.Proxy.Port.Value,
- username: Options.Soulseek.Connection.Proxy.Username,
- password: Options.Soulseek.Connection.Proxy.Password);
+ address: OptionsAtStartup.Soulseek.Connection.Proxy.Address,
+ port: OptionsAtStartup.Soulseek.Connection.Proxy.Port.Value,
+ username: OptionsAtStartup.Soulseek.Connection.Proxy.Username,
+ password: OptionsAtStartup.Soulseek.Connection.Proxy.Password);
}
var connectionOptions = new ConnectionOptions(
- readBufferSize: Options.Soulseek.Connection.Buffer.Read,
- writeBufferSize: Options.Soulseek.Connection.Buffer.Write,
- connectTimeout: Options.Soulseek.Connection.Timeout.Connect,
- inactivityTimeout: Options.Soulseek.Connection.Timeout.Inactivity,
+ readBufferSize: OptionsAtStartup.Soulseek.Connection.Buffer.Read,
+ writeBufferSize: OptionsAtStartup.Soulseek.Connection.Buffer.Write,
+ connectTimeout: OptionsAtStartup.Soulseek.Connection.Timeout.Connect,
+ inactivityTimeout: OptionsAtStartup.Soulseek.Connection.Timeout.Inactivity,
proxyOptions: proxyOptions);
var clientOptions = new SoulseekClientOptions(
- listenPort: Options.Soulseek.ListenPort,
+ listenPort: OptionsAtStartup.Soulseek.ListenPort,
enableListener: true,
userEndPointCache: new UserEndPointCache(),
- distributedChildLimit: Options.Soulseek.DistributedNetwork.ChildLimit,
- enableDistributedNetwork: !Options.Soulseek.DistributedNetwork.Disabled,
- minimumDiagnosticLevel: Options.Soulseek.DiagnosticLevel,
+ distributedChildLimit: OptionsAtStartup.Soulseek.DistributedNetwork.ChildLimit,
+ enableDistributedNetwork: !OptionsAtStartup.Soulseek.DistributedNetwork.Disabled,
+ minimumDiagnosticLevel: OptionsAtStartup.Soulseek.DiagnosticLevel,
autoAcknowledgePrivateMessages: false,
acceptPrivateRoomInvitations: true,
serverConnectionOptions: connectionOptions,
@@ -132,36 +140,39 @@ namespace slskd
}
public static ISoulseekClient SoulseekClient { get; private set; }
+
private IBrowseTracker BrowseTracker { get; set; }
private ISoulseekClient Client { get; set; }
private IConversationTracker ConversationTracker { get; set; }
private ILogger Logger { get; set; } = Log.ForContext<Service>();
private ConcurrentDictionary<string, ILogger> Loggers { get; } = new ConcurrentDictionary<string, ILogger>();
private IOptionsMonitor<Options> OptionsMonitor { get; set; }
- private Options Options { get; set; }
+ private OptionsAtStartup OptionsAtStartup { get; set; }
+ private Options PreviousOptions { get; set; }
private IRoomTracker RoomTracker { get; set; }
+ private IStateMonitor StateMonitor { get; set; }
private ISharedFileCache SharedFileCache { get; set; }
private ITransferTracker TransferTracker { get; set; }
- private bool UsingProxy => !string.IsNullOrWhiteSpace(Options.Soulseek.Connection.Proxy.Address) && Options.Soulseek.Connection.Proxy.Port.HasValue;
private IPushbulletService Pushbullet { get; }
+ private ReaderWriterLockSlim OptionsSyncRoot { get; } = new ReaderWriterLockSlim();
public async Task StartAsync(CancellationToken cancellationToken)
{
- if (UsingProxy)
+ if (OptionsAtStartup.Soulseek.Connection.Proxy.Enabled)
{
- Logger.Information($"Using Proxy {Options.Soulseek.Connection.Proxy.Address}:{Options.Soulseek.Connection.Proxy.Port}");
+ Logger.Information($"Using Proxy {OptionsAtStartup.Soulseek.Connection.Proxy.Address}:{OptionsAtStartup.Soulseek.Connection.Proxy.Port}");
}
Logger.Information("Client started");
- Logger.Information("Listening on port {Port}", Options.Soulseek.ListenPort);
+ Logger.Information("Listening on port {Port}", OptionsAtStartup.Soulseek.ListenPort);
- if (string.IsNullOrEmpty(Options.Soulseek.Username) || string.IsNullOrEmpty(Options.Soulseek.Password))
+ if (string.IsNullOrEmpty(OptionsAtStartup.Soulseek.Username) || string.IsNullOrEmpty(OptionsAtStartup.Soulseek.Password))
{
Logger.Warning($"Not connecting to the Soulseek server; username and/or password invalid. Specify valid credentials and manually connect, or update config and restart.");
}
else
{
- await Client.ConnectAsync(Options.Soulseek.Username, Options.Soulseek.Password).ConfigureAwait(false);
+ await Client.ConnectAsync(OptionsAtStartup.Soulseek.Username, OptionsAtStartup.Soulseek.Password).ConfigureAwait(false);
}
}
@@ -173,15 +184,128 @@ namespace slskd
return Task.CompletedTask;
}
- private void OptionsChanged(Options options)
+ private async Task OptionsMonitor_OnChange(Options newOptions)
{
- Console.WriteLine($"Options changed. Old options:");
- Console.WriteLine(JsonSerializer.Serialize(Options));
- Console.WriteLine($"\tNew options:");
- Console.WriteLine(JsonSerializer.Serialize(options));
- // todo: did options really change?
- // todo: if options did change, create a patch and ReconfigureOptionsAsync
- // todo: if ReconfigureOptionsAsync = true, find some way to let the user know a reconnect is pending
+ // this code is known to fire more than once per update. i'm not sure
+ // whether these might be executed concurrently. lock to be safe, because
+ // we need to accurately track the last value of Options for diffing purposes.
+ // threading shenanigans here could lead to missed updates.
+ OptionsSyncRoot.EnterWriteLock();
+
+ try
+ {
+ var pendingRestart = false;
+ var pendingReconnect = false;
+ var soulseekRequiresReconnect = false;
+
+ var diff = PreviousOptions.DiffWith(newOptions);
+
+ // don't react to duplicate/no-change events
+ // https://github.com/slskd/slskd/issues/126
+ if (!diff.Any())
+ {
+ return;
+ }
+
+ foreach (var (property, fqn, left, right) in diff)
+ {
+ static bool HasAttribute<T>(PropertyInfo property) => property.CustomAttributes.Any(a => a.AttributeType == typeof(T));
+
+ var requiresRestart = HasAttribute<RequiresRestartAttribute>(property);
+ var requiresReconnect = HasAttribute<RequiresReconnectAttribute>(property);
+
+ Logger.Debug($"{fqn} changed from '{left ?? "<null>"}' to '{right ?? "<null>"}'{(requiresRestart ? "; Restart required to take effect." : string.Empty)}{(requiresReconnect ? "; Reconnect required to take effect." : string.Empty)}");
+
+ pendingRestart |= requiresRestart;
+ pendingReconnect |= requiresReconnect;
+ }
+
+ // determine whether any Soulseek options changed. if so, we need to construct a patch
+ // and invoke ReconfigureOptionsAsync().
+ var slskDiff = PreviousOptions.Soulseek.DiffWith(newOptions.Soulseek);
+
+ if (slskDiff.Any())
+ {
+ var old = PreviousOptions.Soulseek;
+ var update = newOptions.Soulseek;
+
+ Logger.Debug("Soulseek options changed from {Previous} to {Current}", old.ToJson(), update.ToJson());
+
+ // determine whether any Connection options changed. if so, replace the whole object.
+ // Soulseek.NET doesn't offer a way to patch parts of connection options. the updates only affect
+ // new connections, so a partial patch doesn't make a lot of sense anyway.
+ var connectionDiff = old.Connection.DiffWith(update.Connection);
+
+ ConnectionOptions connectionPatch = null;
+
+ if (connectionDiff.Any())
+ {
+ var connection = update.Connection;
+
+ ProxyOptions proxyPatch = null;
+
+ if (connection.Proxy.Enabled)
+ {
+ proxyPatch = new ProxyOptions(
+ connection.Proxy.Address,
+ connection.Proxy.Port.Value,
+ connection.Proxy.Username,
+ connection.Proxy.Password);
+ }
+
+ connectionPatch = new ConnectionOptions(
+ connection.Buffer.Read,
+ connection.Buffer.Write,
+ connection.Timeout.Connect,
+ connection.Timeout.Inactivity,
+ proxyOptions: proxyPatch);
+ }
+
+ var patch = new SoulseekClientOptionsPatch(
+ listenPort: old.ListenPort == update.ListenPort ? null : update.ListenPort,
+ enableDistributedNetwork: old.DistributedNetwork.Disabled == update.DistributedNetwork.Disabled ? null : !update.DistributedNetwork.Disabled,
+ distributedChildLimit: old.DistributedNetwork.ChildLimit == update.DistributedNetwork.ChildLimit ? null : update.DistributedNetwork.ChildLimit,
+ serverConnectionOptions: connectionPatch,
+ peerConnectionOptions: connectionPatch,
+ transferConnectionOptions: connectionPatch,
+ incomingConnectionOptions: connectionPatch,
+ distributedConnectionOptions: connectionPatch);
+
+ Logger.Debug("Patching Soulseek options with {Patch}", patch.ToJson());
+
+ soulseekRequiresReconnect = await SoulseekClient.ReconfigureOptionsAsync(patch);
+ }
+
+ // require a reconnect if the client is connected and any options marked [RequiresReconnect] changed,
+ // OR if the call to reconfigure the client requires a reconnect
+ if ((Client.State.HasFlag(SoulseekClientStates.Connected) && pendingReconnect) || soulseekRequiresReconnect)
+ {
+ StateMonitor.Set(state => state with { PendingReconnect = true });
+ Logger.Information("One or more updated Soulseek options requires the client to be disconnected, then reconnected to the network to take effect.");
+ }
+
+ if (pendingRestart)
+ {
+ StateMonitor.Set(state => state with { PendingRestart = true });
+ Logger.Information("One or more updated options requires an application restart to take effect.");
+ }
+
+ Logger.Information("Options updated successfully.");
+ }
+ catch (Exception ex)
+ {
+ Logger.Error(ex, "Failed to apply option update: {Message}", ex.Message);
+ }
+ finally
+ {
+ PreviousOptions = OptionsMonitor.CurrentValue;
+ OptionsSyncRoot.ExitWriteLock();
+ }
+ }
+
+ private void StateMonitor_OnChange((State Previous, State Current) state)
+ {
+ Logger.Debug("State changed from {Previous} to {Current}", state.Previous.ToJson(), state.Current.ToJson());
}
private void SharedFileCache_Refreshed(object sender, (int Directories, int Files) e)
@@ -202,7 +326,7 @@ namespace slskd
private Task<BrowseResponse> BrowseResponseResolver(string username, IPEndPoint endpoint)
{
var directories = System.IO.Directory
- .GetDirectories(Options.Directories.Shared, "*", SearchOption.AllDirectories)
+ .GetDirectories(OptionsMonitor.CurrentValue.Directories.Shared, "*", SearchOption.AllDirectories)
.Select(dir => new Soulseek.Directory(dir.Replace("/", @"\"), System.IO.Directory.GetFiles(dir)
.Select(f => new Soulseek.File(1, Path.GetFileName(f), new FileInfo(f).Length, Path.GetExtension(f)))));
@@ -237,11 +361,16 @@ namespace slskd
private void Client_LoggedIn(object sender, EventArgs e)
{
- Logger.Information("Logged in to the Soulseek server as {Username}", Options.Soulseek.Username);
+ Logger.Information("Logged in to the Soulseek server as {Username}", Client.Username);
}
private async void Client_Disconnected(object sender, SoulseekClientDisconnectedEventArgs args)
{
+ if (StateMonitor.Current.PendingReconnect)
+ {
+ StateMonitor.Set(state => state with { PendingReconnect = false });
+ }
+
if (args.Exception is ObjectDisposedException || args.Exception is ApplicationShutdownException)
{
Logger.Information("Disconnected from the Soulseek server: the client is shutting down");
@@ -256,13 +385,13 @@ namespace slskd
}
else if (args.Exception is KickedFromServerException)
{
- Logger.Error("Disconnected from the Soulseek server: another client logged in using the username {Username}", Options.Soulseek.Username);
+ Logger.Error("Disconnected from the Soulseek server: another client logged in using the username {Username}", Client.Username);
}
else
{
Logger.Error("Disconnected from the Soulseek server: {Message}", args.Exception?.Message ?? args.Message);
- if (string.IsNullOrEmpty(Options.Soulseek.Username) || string.IsNullOrEmpty(Options.Soulseek.Password))
+ if (string.IsNullOrEmpty(OptionsMonitor.CurrentValue.Soulseek.Username) || string.IsNullOrEmpty(OptionsMonitor.CurrentValue.Soulseek.Password))
{
Logger.Warning($"Not reconnecting to the Soulseek server; username and/or password invalid. Specify valid credentials and manually connect, or update config and restart.");
return;
@@ -284,7 +413,9 @@ namespace slskd
try
{
- await Client.ConnectAsync(Options.Soulseek.Username, Options.Soulseek.Password);
+ // reconnect with the latest configuration values we have for username and password, instead of the options that were
+ // captured at startup. if a user has updated these values prior to the disconnect, the changes will take effect now.
+ await Client.ConnectAsync(OptionsMonitor.CurrentValue.Soulseek.Username, OptionsMonitor.CurrentValue.Soulseek.Password);
break;
}
catch (Exception ex)
@@ -300,7 +431,7 @@ namespace slskd
{
ConversationTracker.AddOrUpdate(args.Username, PrivateMessage.FromEventArgs(args));
- if (Options.Integration.Pushbullet.Enabled && !args.Replayed)
+ if (OptionsMonitor.CurrentValue.Integration.Pushbullet.Enabled && !args.Replayed)
{
Console.WriteLine("Pushing...");
_ = Pushbullet.PushAsync($"Private Message from {args.Username}", args.Username, args.Message);
@@ -311,7 +442,7 @@ namespace slskd
{
Console.WriteLine($"[PUBLIC CHAT] [{args.RoomName}] [{args.Username}]: {args.Message}");
- if (Options.Integration.Pushbullet.Enabled && args.Message.Contains(Client.Username))
+ if (OptionsMonitor.CurrentValue.Integration.Pushbullet.Enabled && args.Message.Contains(Client.Username))
{
_ = Pushbullet.PushAsync($"Room Mention by {args.Username} in {args.RoomName}", args.RoomName, args.Message);
}
@@ -320,7 +451,7 @@ namespace slskd
private void Client_RoomJoined(object sender, RoomJoinedEventArgs args)
{
// this will fire when we join a room; track that through the join operation.
- if (args.Username != Options.Soulseek.Username)
+ if (args.Username != Client.Username)
{
RoomTracker.TryAddUser(args.RoomName, args.UserData);
}
@@ -336,7 +467,7 @@ namespace slskd
var message = RoomMessage.FromEventArgs(args, DateTime.UtcNow);
RoomTracker.AddOrUpdateMessage(args.RoomName, message);
- if (Options.Integration.Pushbullet.Enabled && message.Message.Contains(Client.Username))
+ if (OptionsMonitor.CurrentValue.Integration.Pushbullet.Enabled && message.Message.Contains(Client.Username))
{
_ = Pushbullet.PushAsync($"Room Mention by {message.Username} in {message.RoomName}", message.RoomName, message.Message);
}
diff --git a/src/slskd/Application/State.cs b/src/slskd/Application/State.cs
new file mode 100644
index 00000000..75d46dec
--- /dev/null
+++ b/src/slskd/Application/State.cs
@@ -0,0 +1,24 @@
+// <copyright file="State.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
+{
+ /// <summary>
+ /// Application state.
+ /// </summary>
+ public record State(bool PendingReconnect = false, bool PendingRestart = false);
+} \ No newline at end of file
diff --git a/src/slskd/Application/StateMonitor.cs b/src/slskd/Application/StateMonitor.cs
new file mode 100644
index 00000000..5c9d90e3
--- /dev/null
+++ b/src/slskd/Application/StateMonitor.cs
@@ -0,0 +1,94 @@
+// <copyright file="StateMonitor.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
+{
+ using System;
+
+ /// <summary>
+ /// Used for notifications when <see cref="State"/> changes.
+ /// </summary>
+ public class StateMonitor : IStateMonitor
+ {
+ private event Action<(State, State)> Changed;
+
+ /// <summary>
+ /// Gets the current application state.
+ /// </summary>
+ public State Current { get; private set; } = new State();
+
+ /// <summary>
+ /// Registers a listener to be called whenever <see cref="State"/> changes.
+ /// </summary>
+ /// <param name="listener">Registers a listener to be called whenver state changes.</param>
+ /// <returns>An <see cref="IDisposable"/> which should be disposed to stop listening for changes.</returns>
+ public IDisposable OnChange(Action<(State Previous, State Current)> listener)
+ {
+ var disposable = new StateTrackerDisposable(this, listener);
+ Changed += disposable.OnChange;
+ return disposable;
+ }
+
+ /// <summary>
+ /// Replaces the current state with the value resolved by the <paramref name="setter"/>.
+ /// </summary>
+ /// <param name="setter">Given the current state, resolves a new state value.</param>
+ /// <returns>The updated state.</returns>
+ public State Set(Func<State, State> setter)
+ {
+ var previous = Current.ToJson().ToObject<State>();
+ Current = setter(Current);
+
+ Changed?.Invoke((previous, Current));
+ return Current;
+ }
+
+ private class StateTrackerDisposable : IDisposable
+ {
+ public StateTrackerDisposable(StateMonitor stateMonitor, Action<(State Previous, State Current)> listener)
+ {
+ StateMonitor = stateMonitor;
+ Listener = listener;
+ }
+
+ private bool Disposed { get; set; }
+ private Action<(State Previous, State Current)> Listener { get; }
+ private StateMonitor StateMonitor { get; }
+
+ public void Dispose()
+ {
+ Dispose(disposing: true);
+ GC.SuppressFinalize(this);
+ }
+
+ public void OnChange((State Previous, State Current) args) => Listener.Invoke(args);
+
+ protected virtual void Dispose(bool disposing)
+ {
+ if (!Disposed)
+ {
+ if (disposing)
+ {
+ StateMonitor.Changed -= OnChange;
+ }
+
+ Disposed = true;
+ }
+ }
+ }
+ }
+}
diff --git a/src/slskd/Application/Transfer/API/Controllers/TransfersController.cs b/src/slskd/Application/Transfer/API/Controllers/TransfersController.cs
index 97b86689..9ed36d1b 100644
--- a/src/slskd/Application/Transfer/API/Controllers/TransfersController.cs
+++ b/src/slskd/Application/Transfer/API/Controllers/TransfersController.cs
@@ -15,6 +15,8 @@
// along with this program. If not, see https://www.gnu.org/licenses/.
// </copyright>
+using Microsoft.Extensions.Options;
+
namespace slskd.Transfer.API
{
using System;
@@ -46,7 +48,7 @@ namespace slskd.Transfer.API
/// <param name="tracker"></param>
/// <param name="ftpClient"></param>
public TransfersController(
- Microsoft.Extensions.Options.IOptionsSnapshot<Options> options,
+ IOptionsSnapshot<Options> options,
ISoulseekClient client,
ITransferTracker tracker,
IFTPService ftpClient)
diff --git a/src/slskd/Common/Configuration/RequiresReconnectAttribute.cs b/src/slskd/Common/Configuration/RequiresReconnectAttribute.cs
new file mode 100644
index 00000000..cd5edd14
--- /dev/null
+++ b/src/slskd/Common/Configuration/RequiresReconnectAttribute.cs
@@ -0,0 +1,26 @@
+// <copyright file="RequiresReconnectAttribute.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.Configuration
+{
+ using System;
+
+ [AttributeUsage(AttributeTargets.Property)]
+ public class RequiresReconnectAttribute : Attribute
+ {
+ }
+}
diff --git a/src/slskd/Common/Configuration/RequiresRestartAttribute.cs b/src/slskd/Common/Configuration/RequiresRestartAttribute.cs
new file mode 100644
index 00000000..9b90eabe
--- /dev/null
+++ b/src/slskd/Common/Configuration/RequiresRestartAttribute.cs
@@ -0,0 +1,26 @@
+// <copyright file="RequiresRestartAttribute.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.Configuration
+{
+ using System;
+
+ [AttributeUsage(AttributeTargets.Property)]
+ public class RequiresRestartAttribute : Attribute
+ {
+ }
+}
diff --git a/src/slskd/Common/Configuration/YamlConfigurationSource.cs b/src/slskd/Common/Configuration/YamlConfigurationSource.cs
index 332df647..82e2227d 100644
--- a/src/slskd/Common/Configuration/YamlConfigurationSource.cs
+++ b/src/slskd/Common/Configuration/YamlConfigurationSource.cs
@@ -37,6 +37,7 @@ namespace slskd.Configuration
/// <param name="path">
/// Path relative to the base path stored in <see cref="IConfigurationBuilder.Properties"/> of <paramref name="builder"/>.
/// </param>
+ /// <param name="targetType">The type from which to map properties.</param>
/// <param name="optional">Whether the file is optional.</param>
/// <param name="reloadOnChange">Whether the configuration should be reloaded if the file changes.</param>
/// <param name="normalizeKeys">
@@ -44,7 +45,7 @@ namespace slskd.Configuration
/// </param>
/// <param name="provider">The updated <see cref="IFileProvider"/> to use to access the file.</param>
/// <returns>The <see cref="IConfigurationBuilder"/>.</returns>
- public static IConfigurationBuilder AddYamlFile(this IConfigurationBuilder builder, string path, bool optional = true, bool reloadOnChange = false, bool normalizeKeys = true, IFileProvider provider = null)
+ public static IConfigurationBuilder AddYamlFile(this IConfigurationBuilder builder, string path, Type targetType, bool optional = true, bool reloadOnChange = false, bool normalizeKeys = true, IFileProvider provider = null)
{
if (builder == null)
{
@@ -59,6 +60,7 @@ namespace slskd.Configuration
return builder.AddYamlFile(s =>
{
s.Path = path;
+ s.TargetType = targetType;
s.Optional = optional;
s.ReloadOnChange = reloadOnChange;
s.NormalizeKeys = normalizeKeys;
@@ -89,9 +91,13 @@ namespace slskd.Configuration
public YamlConfigurationProvider(YamlConfigurationSource source)
: base(source)
{
+ TargetType = source.TargetType;
+ Namespace = TargetType.Namespace.Split('.').First();
NormalizeKeys = source.NormalizeKeys;
}
+ private Type TargetType { get; set; }
+ private string Namespace { get; set; }
private bool NormalizeKeys { get; set; }
private string[] NullValues { get; } = new[] { "~", "null", string.Empty };
@@ -111,7 +117,7 @@ namespace slskd.Configuration
if (yaml.Documents.Count > 0)
{
var rootNode = (YamlMappingNode)yaml.Documents[0].RootNode;
- Traverse(rootNode);
+ Traverse(rootNode, Namespace);
}
}
catch (YamlException e)
@@ -162,6 +168,11 @@ namespace slskd.Configuration
public class YamlConfigurationSource : FileConfigurationSource
{
/// <summary>
+ /// Gets or sets the type from which to map properties.
+ /// </summary>
+ public Type TargetType { get; set; }
+
+ /// <summary>
/// Gets or sets a value indicating whether configuration keys should be normalized (_, - removed, changed to lowercase).
/// </summary>
public bool NormalizeKeys { get; set; }
diff --git a/src/slskd/Common/Extensions.cs b/src/slskd/Common/Extensions.cs
index a7a89a71..3e4f6e68 100644
--- a/src/slskd/Common/Extensions.cs
+++ b/src/slskd/Common/Extensions.cs
@@ -19,12 +19,10 @@ namespace slskd
{
using System;
using System.Collections.Generic;
- using System.ComponentModel.DataAnnotations;
using System.IO;
using System.Linq;
- using System.Security.Cryptography;
- using System.Text;
- using slskd.Validation;
+ using System.Reflection;
+ using System.Text.Json;
/// <summary>
/// Extensions.
@@ -32,6 +30,60 @@ namespace slskd
public static class Extensions
{
/// <summary>
+ /// Serializes this object to json.
+ /// </summary>
+ /// <param name="obj">The object to serialize.</param>
+ /// <returns>A string containing the serialized object.</returns>
+ public static string ToJson(this object obj) => JsonSerializer.Serialize(obj);
+
+ /// <summary>
+ /// Deserializes this string from json to an object of type <typeparamref name="T"/>.
+ /// </summary>
+ /// <typeparam name="T">The type to which to deserialize the string.</typeparam>
+ /// <param name="str">The string to deserialize.</param>
+ /// <returns>The new object deserialzied from the string.</returns>
+ public static T ToObject<T>(this string str) => JsonSerializer.Deserialize<T>(str);
+
+ /// <summary>
+ /// Deeply compares this object with the specified object and returns a list of properties that are different.
+ /// </summary>
+ /// <param name="left">The left side of the comparison.</param>
+ /// <param name="right">The right side of the comparison.</param>
+ /// <param name="parentFqn">The root path for recursive calls.</param>
+ /// <returns>A list of differences between the two objects.</returns>
+ public static IEnumerable<(PropertyInfo Property, string FQN, object Left, object Right)> DiffWith(this object left, object right, string parentFqn = null)
+ {
+ if (left?.GetType() != right?.GetType())
+ {
+ throw new InvalidCastException($"Unable to diff types {left?.GetType()} and {right?.GetType()}");
+ }
+
+ var differences = new List<(PropertyInfo Property, string FQN, object Left, object Right)>();
+
+ foreach (var prop in left?.GetType().GetProperties())
+ {
+ var leftVal = prop.GetValue(left);
+ var rightVal = prop.GetValue(right);
+ var propType = prop.PropertyType;
+ var fqn = string.IsNullOrEmpty(parentFqn) ? prop.Name : string.Join(".", parentFqn, prop.Name);
+
+ if (propType.IsPrimitive || Nullable.GetUnderlyingType(propType) != null || new[] { typeof(string), typeof(decimal) }.Contains(propType))
+ {
+ if (!Equals(leftVal, rightVal))
+ {
+ differences.Add((prop, fqn, leftVal, rightVal));
+ }
+ }
+ else
+ {
+ differences.AddRange(DiffWith(leftVal, rightVal, fqn));
+ }
+ }
+
+ return differences;
+ }
+
+ /// <summary>
/// Returns the directory from the given path, regardless of separator format.
/// </summary>
/// <param name="path">The path.</param>
diff --git a/src/slskd/Integrations/FTP/FTPClientFactory.cs b/src/slskd/Integrations/FTP/FTPClientFactory.cs
index cc076ca1..e9ee0721 100644
--- a/src/slskd/Integrations/FTP/FTPClientFactory.cs
+++ b/src/slskd/Integrations/FTP/FTPClientFactory.cs
@@ -15,6 +15,8 @@
// along with this program. If not, see https://www.gnu.org/licenses/.
// </copyright>
+using Microsoft.Extensions.Options;
+
namespace slskd.Integrations.FTP
{
using System;
@@ -30,25 +32,13 @@ namespace slskd.Integrations.FTP
/// Initializes a new instance of the <see cref="FTPClientFactory"/> class.
/// </summary>
/// <param name="optionsMonitor">The options monitor used to derive application options.</param>
- public FTPClientFactory(Microsoft.Extensions.Options.IOptionsMonitor<Options> optionsMonitor)
+ public FTPClientFactory(IOptionsMonitor<Options> optionsMonitor)
{
- Options = optionsMonitor.CurrentValue;
-
- try
- {
- EncryptionMode = (FtpEncryptionMode)Enum.Parse(typeof(FtpEncryptionMode), FTPOptions.EncryptionMode, ignoreCase: true);
- }
- catch (Exception ex)
- {
- // Options should validate that the given string is parsable to FtpEncryptionMode through EnumAttribute; if this
- // throws there's a bug somewhere.
- throw new ArgumentException($"Failed to parse {typeof(FtpEncryptionMode).Name} from application Options. This is most likely a programming error; please file a GitHub issue and include your FTP configuration.", ex);
- }
+ OptionsMonitor = optionsMonitor;
}
- private FtpEncryptionMode EncryptionMode { get; set; }
- private FTPOptions FTPOptions => Options.Integration.FTP;
- private Options Options { get; set; }
+ private FTPOptions FTPOptions => OptionsMonitor.CurrentValue.Integration.FTP;
+ private IOptionsMonitor<Options> OptionsMonitor { get; set; }
/// <summary>
/// Creates an instance of <see cref="FtpClient"/>.
@@ -57,10 +47,24 @@ namespace slskd.Integrations.FTP
public FtpClient CreateFtpClient()
{
var client = new FtpClient(FTPOptions.Address, FTPOptions.Port, FTPOptions.Username, FTPOptions.Password);
- client.EncryptionMode = EncryptionMode;
+ client.EncryptionMode = ParseFtpEncryptionMode(FTPOptions.EncryptionMode);
client.ValidateAnyCertificate = FTPOptions.IgnoreCertificateErrors;
return client;
}
+
+ private FtpEncryptionMode ParseFtpEncryptionMode(string encryptionMode)
+ {
+ try
+ {
+ return (FtpEncryptionMode)Enum.Parse(typeof(FtpEncryptionMode), encryptionMode, ignoreCase: true);
+ }
+ catch (Exception ex)
+ {
+ // Options should validate that the given string is parsable to FtpEncryptionMode through EnumAttribute; if this
+ // throws there's a bug somewhere.
+ throw new ArgumentException($"Failed to parse {typeof(FtpEncryptionMode).Name} from application Options. This is most likely a programming error; please file a GitHub issue and include your FTP configuration.", ex);
+ }
+ }
}
} \ No newline at end of file
diff --git a/src/slskd/Integrations/FTP/FTPService.cs b/src/slskd/Integrations/FTP/FTPService.cs
index a5fe6a8f..becf1a12 100644
--- a/src/slskd/Integrations/FTP/FTPService.cs
+++ b/src/slskd/Integrations/FTP/FTPService.cs
@@ -15,6 +15,8 @@
// along with this program. If not, see https://www.gnu.org/licenses/.
// </copyright>
+using Microsoft.Extensions.Options;
+
namespace slskd.Integrations.FTP
{
using System;
@@ -38,18 +40,18 @@ namespace slskd.Integrations.FTP
/// <param name="log">The logger.</param>
public FTPService(
IFTPClientFactory ftpClientFactory,
- Microsoft.Extensions.Options.IOptionsMonitor<Options> optionsMonitor,
+ IOptionsMonitor<Options> optionsMonitor,
ILogger<FTPService> log)
{
Factory = ftpClientFactory;
- Options = optionsMonitor.CurrentValue;
+ OptionsMonitor = optionsMonitor;
Log = log;
}
private IFTPClientFactory Factory { get; set; }
- private FTPOptions FTPOptions => Options.Integration.FTP;
+ private FTPOptions FTPOptions => OptionsMonitor.CurrentValue.Integration.FTP;
private ILogger<FTPService> Log { get; set; }
- private Options Options { get; }
+ private IOptionsMonitor<Options> OptionsMonitor { get; }
/// <summary>
/// Uploads the specified <paramref name="filename"/> to the configured FTP server.
diff --git a/src/slskd/Integrations/Pushbullet/IPushbulletService.cs b/src/slskd/Integrations/Pushbullet/IPushbulletService.cs
index 6da42326..bad33903 100644
--- a/src/slskd/Integrations/Pushbullet/IPushbulletService.cs
+++ b/src/slskd/Integrations/Pushbullet/IPushbulletService.cs
@@ -17,12 +17,13 @@
namespace slskd.Integrations.Pushbullet
{
+ using System;
using System.Threading.Tasks;
/// <summary>
/// Pushbullet integration service.
/// </summary>
- public interface IPushbulletService
+ public interface IPushbulletService : IDisposable
{
/// <summary>
/// Sends a push notification to Pushbullet.
diff --git a/src/slskd/Integrations/Pushbullet/PushbulletService.cs b/src/slskd/Integrations/Pushbullet/PushbulletService.cs
index cb31e6dc..1a224321 100644
--- a/src/slskd/Integrations/Pushbullet/PushbulletService.cs
+++ b/src/slskd/Integrations/Pushbullet/PushbulletService.cs
@@ -15,6 +15,8 @@
// along with this program. If not, see https://www.gnu.org/licenses/.
// </copyright>
+using Microsoft.Extensions.Options;
+
namespace slskd.Integrations.Pushbullet
{
using System;
@@ -41,23 +43,33 @@ namespace slskd.Integrations.Pushbullet
/// <param name="log">The logger.</param>
public PushbulletService(
IHttpClientFactory httpClientFactory,
- Microsoft.Extensions.Options.IOptionsMonitor<Options> optionsMonitor,
+ IOptionsMonitor<Options> optionsMonitor,
ILogger<PushbulletService> log)
{
HttpClientFactory = httpClientFactory;
- Options = optionsMonitor.CurrentValue;
+ OptionsMonitor = optionsMonitor;
Log = log;
RecentlySent = new MemoryCache(new MemoryCacheOptions());
}
+ private bool Disposed { get; set; }
private IHttpClientFactory HttpClientFactory { get; }
- private Options Options { get; }
private ILogger<PushbulletService> Log { get; }
- private PushbulletOptions PushbulletOptions => Options.Integration.Pushbullet;
+ private IOptionsMonitor<Options> OptionsMonitor { get; }
+ private PushbulletOptions PushbulletOptions => OptionsMonitor.CurrentValue.Integration.Pushbullet;
private IMemoryCache RecentlySent { get; }
/// <summary>
+ /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
+ /// </summary>
+ public void Dispose()
+ {
+ Dispose(disposing: true);
+ GC.SuppressFinalize(this);
+ }
+
+ /// <summary>
/// Sends a push notification to Pushbullet.
/// </summary>
/// <param name="title">The notification title.</param>
@@ -66,6 +78,11 @@ namespace slskd.Integrations.Pushbullet
/// <returns>The operation context.</returns>
public Task PushAsync(string title, string cacheKey, string body)
{
+ if (!PushbulletOptions.Enabled)
+ {
+ return Task.CompletedTask;
+ }
+
if (string.IsNullOrWhiteSpace(title))
{
throw new ArgumentException("A notification title must be supplied", nameof(title));
@@ -91,6 +108,19 @@ namespace slskd.Integrations.Pushbullet
return PushInternalAsync(title, body);
}
+ protected virtual void Dispose(bool disposing)
+ {
+ if (!Disposed)
+ {
+ if (disposing)
+ {
+ RecentlySent.Dispose();
+ }
+
+ Disposed = true;
+ }
+ }
+
private async Task PushInternalAsync(string title, string body)
{
try
@@ -133,4 +163,4 @@ namespace slskd.Integrations.Pushbullet
}
}
}
-}
+} \ No newline at end of file
diff --git a/src/slskd/Options.cs b/src/slskd/Options.cs
index 7e4880c6..4a032c47 100644
--- a/src/slskd/Options.cs
+++ b/src/slskd/Options.cs
@@ -15,6 +15,8 @@
// along with this program. If not, see https://www.gnu.org/licenses/.
// </copyright>
+using Microsoft.Extensions.Options;
+
namespace slskd
{
using System;
@@ -23,14 +25,61 @@ namespace slskd
using System.ComponentModel.DataAnnotations;
using System.Diagnostics;
using FluentFTP;
+ using slskd.Configuration;
using slskd.Validation;
using Soulseek.Diagnostics;
using Utility.CommandLine;
using Utility.EnvironmentVariables;
/// <summary>
+ /// Disambiguates options derived at startup from options that may update at run time.
+ /// </summary>
+ /// <remarks>
+ /// This class is added directly to dependency injection, but <see cref="Options"/> is not, so consumers must inject <see cref="OptionsAtStartup"/>
+ /// instead of <see cref="Options"/> to make it clear that these options will not change. Options that may change should be accessed by injecting
+ /// <see cref="IOptionsMonitor{T}"/> or <see cref="IOptionsSnapshot{T}"/>, depending on the lifetime of the component.
+ /// </remarks>
+ public class OptionsAtStartup : Options
+ {
+ }
+
+ /// <summary>
/// Application options.
/// </summary>
+ /// <remarks>
+ /// <para>
+ /// This class contains all application options, which may be sourced from (in order of precedence):
+ /// <list type="bullet">
+ /// <item>
+ /// <term>Defaults</term>
+ /// <description>Default values, statically defined in this class.</description>
+ /// </item>
+ /// <item>
+ /// <term>Environment Variables</term>
+ /// <description>Environment variables set at either the system or user scope.</description>
+ /// </item>
+ /// <item>
+ /// <term>YAML Configuration File</term>
+ /// <description>A YAML file containing a mapping of this class.</description>
+ /// </item>
+ /// <item>
+ /// <term>Command Line</term>
+ /// <description>Options provided via the command line when starting the application.</description>
+ /// </item>
+ /// </list>
+ /// </para>
+ /// <para>
+ /// Only the YAML configuration source can change at runtime and consumers of this class must be aware of this, either injecting
+ /// <see cref="IOptionsMonitor{T}"/> in components with a singleton lifetime, or <see cref="IOptionsSnapshot{T}"/> for transient or scoped lifetimes.
+ /// </para>
+ /// <para>
+ /// To obtain the Options specified at startup (discarding any updates that may have been applied since), inject <see cref="OptionsAtStartup"/>.
+ /// </para>
+ /// <para>
+ /// Options specified via the command line can not be overwritten by changes to the YAML file. This is by design due to the immutable
+ /// nature of the command line string after the application is started.
+ /// </para>
+ /// </remarks>
public class Options
{
/// <summary>
@@ -38,6 +87,7 @@ namespace slskd
/// </summary>
[Argument('v', "version")]
[Description("display version information")]
+ [Obsolete("Used only for documentation; see Program for actual implementation")]
public bool ShowVersion { get; private set; } = false;
/// <summary>
@@ -45,6 +95,7 @@ namespace slskd
/// </summary>
[Argument('h', "help")]
[Description("display command line usage")]
+ [Obsolete("Used only for documentation; see Program for actual implementation")]
public bool ShowHelp { get; private set; } = false;
/// <summary>
@@ -52,6 +103,7 @@ namespace slskd
/// </summary>
[Argument('e', "envars")]
[Description("display environment variables")]
+ [Obsolete("Used only for documentation; see Program for actual implementation")]
public bool ShowEnvironmentVariables { get; private set; } = false;
/// <summary>
@@ -59,6 +111,7 @@ namespace slskd
/// </summary>
[Argument('g', "generate-cert")]
[Description("generate X509 certificate and password for HTTPs")]
+ [Obsolete("Used only for documentation; see Program for actual implementation")]
public bool GenerateCertificate { get; private set; } = false;
/// <summary>
@@ -67,6 +120,7 @@ namespace slskd
[Argument('c', "config")]
[EnvironmentVariable("CONFIG")]
[Description("path to configuration file")]
+ [Obsolete("Used only for documentation; see Program for actual implementation")]
public string ConfigurationFile { get; private set; } = Program.DefaultConfigurationFile;
/// <summary>
@@ -75,6 +129,7 @@ namespace slskd
[Argument('d', "debug")]
[EnvironmentVariable("DEBUG")]
[Description("run in debug mode")]
+ [RequiresRestart]
public bool Debug { get; private set; } = Debugger.IsAttached;
/// <summary>
@@ -83,6 +138,7 @@ namespace slskd
[Argument('n', "no-logo")]
[EnvironmentVariable("NO_LOGO")]
[Description("suppress logo on startup")]
+ [RequiresRestart]
public bool NoLogo { get; private set; } = false;
/// <summary>
@@ -91,6 +147,7 @@ namespace slskd
[Argument('x', "no-start")]
[EnvironmentVariable("NO_START")]
[Description("quit the application after initialization")]
+ [RequiresRestart]
public bool NoStart { get; private set; } = false;
/// <summary>
@@ -99,12 +156,14 @@ namespace slskd
[Argument('i', "instance-name")]
[EnvironmentVariable("INSTANCE_NAME")]
[Description("optional; a unique name for this instance")]
+ [RequiresRestart]
public string InstanceName { get; private set; } = "default";
/// <summary>
/// Gets directory options.
/// </summary>
[Validate]
+ [RequiresRestart]
public DirectoriesOptions Directories { get; private set; } = new DirectoriesOptions();
/// <summary>
@@ -117,12 +176,14 @@ namespace slskd
/// Gets logger options.
/// </summary>
[Validate]
+ [RequiresRestart]
public LoggerOptions Logger { get; private set; } = new LoggerOptions();
/// <summary>
/// Gets feature options.
/// </summary>
[Validate]
+ [RequiresRestart]
public FeatureOptions Feature { get; private set; } = new FeatureOptions();
/// <summary>
@@ -149,6 +210,7 @@ namespace slskd
[EnvironmentVariable("APP_DIR")]
[Description("path where application data is saved")]
[DirectoryExists]
+ [RequiresRestart]
public string App { get; private set; } = Program.DefaultAppDirectory;
/// <summary>
@@ -158,6 +220,7 @@ namespace slskd
[EnvironmentVariable("INCOMPLETE_DIR")]
[Description("path where incomplete downloads are saved")]
[DirectoryExists]
+ [RequiresRestart]
public string Incomplete { get; private set; } = Program.DefaultIncompleteDirectory;
/// <summary>
@@ -167,6 +230,7 @@ namespace slskd
[EnvironmentVariable("DOWNLOADS_DIR")]
[Description("path where downloaded files are saved")]
[DirectoryExists]
+ [RequiresRestart]
public string Downloads { get; private set; } = Program.DefaultDownloadsDirectory;
/// <summary>
@@ -176,6 +240,7 @@ namespace slskd
[EnvironmentVariable("SHARED_DIR")]
[Description("path to shared files")]
[DirectoryExists]
+ [RequiresRestart]
public string Shared { get; private set; } = Program.DefaultSharedDirectory;
}
@@ -190,6 +255,7 @@ namespace slskd
[Argument(default, "prometheus")]
[EnvironmentVariable("PROMETHEUS")]
[Description("enable collection and publishing of prometheus metrics")]
+ [RequiresRestart]
public bool Prometheus { get; private set; } = false;
/// <summary>
@@ -198,6 +264,7 @@ namespace slskd
[Argument(default, "swagger")]
[EnvironmentVariable("SWAGGER")]
[Description("enable swagger documentation and UI")]
+ [RequiresRestart]
public bool Swagger { get; private set; } = false;
}
@@ -212,6 +279,7 @@ namespace slskd
[Argument(default, "loki")]
[EnvironmentVariable("LOKI")]
[Description("optional; url to a Grafana Loki instance to which to log")]
+ [RequiresRestart]
public string Loki { get; private set; } = null;
}
@@ -226,6 +294,7 @@ namespace slskd
[Argument(default, "slsk-username")]
[EnvironmentVariable("SLSK_USERNAME")]
[Description("username for the Soulseek network")]
+ [RequiresReconnect]
public string Username { get; private set; } = null;
/// <summary>
@@ -234,6 +303,7 @@ namespace slskd
[Argument(default, "slsk-password")]
[EnvironmentVariable("SLSK_PASSWORD")]
[Description("password for the Soulseek network")]
+ [RequiresReconnect]
public string Password { get; private set; } = null;
/// <summary>
@@ -251,6 +321,7 @@ namespace slskd
[Argument(default, "slsk-diag-level")]
[EnvironmentVariable("SLSK_DIAG_LEVEL")]
[Description("minimum diagnostic level (None, Warning, Info, Debug)")]
+ [RequiresRestart]
public DiagnosticLevel DiagnosticLevel { get; private set; } = DiagnosticLevel.Info;
/// <summary>
@@ -339,9 +410,17 @@ namespace slskd
/// <summary>
/// Connection proxy options.
/// </summary>
- public class ProxyOptions
+ public class ProxyOptions : IValidatableObject
{
/// <summary>
+ /// Gets a value indicating whether the proxy is enabled.
+ /// </summary>
+ [Argument(default, "slsk-proxy")]
+ [EnvironmentVariable("SLSK_PROXY_ENABLED")]
+ [Description("enable connection proxy")]
+ public bool Enabled { get; private set; } = false;
+
+ /// <summary>
/// Gets the proxy address.
/// </summary>
[Argument(default, "slsk-proxy-address")]
@@ -376,6 +455,28 @@ namespace slskd
[Description("connection proxy password")]
[StringLength(255, MinimumLength = 1)]
public string Password { get; private set; }
+
+ /// <summary>
+ /// Extended validation.
+ /// </summary>
+ /// <param name="validationContext"></param>
+ /// <returns></returns>
+ public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
+ {
+ var results = new List<ValidationResult>();
+
+ if (Enabled && string.IsNullOrWhiteSpace(Address))
+ {
+ results.Add(new ValidationResult($"The Enabled field is true, but no Address has been specified."));
+ }
+
+ if (Enabled && !Port.HasValue)
+ {
+ results.Add(new ValidationResult($"The Enabled field is true, but no Port has been specified."));
+ }
+
+ return results;
+ }
}
}
@@ -415,12 +516,14 @@ namespace slskd
[EnvironmentVariable("HTTP_PORT")]
[Description("HTTP listen port for web UI")]
[Range(1, 65535)]
+ [RequiresRestart]
public int Port { get; private set; } = 5000;
/// <summary>
/// Gets HTTPS options.
/// </summary>
[Validate]
+ [RequiresRestart]
public HttpsOptions Https { get; private set; } = new HttpsOptions();
/// <summary>
@@ -429,6 +532,7 @@ namespace slskd
[Argument(default, "url-base")]
[EnvironmentVariable("URL_BASE")]
[Description("base url for web requests")]
+ [RequiresRestart]
public string UrlBase { get; private set; } = "/";
/// <summary>
@@ -438,6 +542,7 @@ namespace slskd
[EnvironmentVariable("CONTENT_PATH")]
[Description("path to static web content")]
[StringLength(255, MinimumLength = 1)]
+ [RequiresRestart]
public string ContentPath { get; private set; } = "wwwroot";
/// <summary>
@@ -457,6 +562,7 @@ namespace slskd
[Argument('x', "no-auth")]
[EnvironmentVariable("NO_AUTH")]
[Description("disable authentication for web requests")]
+ [RequiresRestart]
public bool Disable { get; private set; } = false;
/// <summary>
@@ -481,6 +587,7 @@ namespace slskd
/// Gets JWT options.
/// </summary>
[Validate]
+ [RequiresRestart]
public JwtOptions Jwt { get; private set; } = new JwtOptions();
/// <summary>
@@ -495,6 +602,7 @@ namespace slskd
[EnvironmentVariable("JWT_KEY")]
[Description("JWT signing key")]
[StringLength(255, MinimumLength = 1)]
+ [RequiresRestart]
public string Key { get; private set; } = Guid.NewGuid().ToString();
/// <summary>
@@ -504,6 +612,7 @@ namespace slskd
[EnvironmentVariable("JWT_TTL")]
[Description("TTL for JWTs")]
[Range(3600, int.MaxValue)]
+ [RequiresRestart]
public int Ttl { get; private set; } = 604800000;
}
}
@@ -520,6 +629,7 @@ namespace slskd
[EnvironmentVariable("HTTPS_PORT")]
[Description("HTTPS listen port for web UI")]
[Range(1, 65535)]
+ [RequiresRestart]
public int Port { get; private set; } = 5001;
/// <summary>
@@ -528,12 +638,14 @@ namespace slskd
[Argument('f', "force-https")]
[EnvironmentVariable("HTTPS_FORCE")]
[Description("redirect HTTP to HTTPS")]
+ [RequiresRestart]
public bool Force { get; private set; } = false;
/// <summary>
/// Gets certificate options.
/// </summary>
[Validate]
+ [RequiresRestart]
public CertificateOptions Certificate { get; private set; } = new CertificateOptions();
/// <summary>
@@ -549,6 +661,7 @@ namespace slskd
[EnvironmentVariable("HTTPS_CERT_PFX")]
[Description("path to X509 certificate .pfx")]
[FileExists]
+ [RequiresRestart]
public string Pfx { get; private set; }
/// <summary>
@@ -557,6 +670,7 @@ namespace slskd
[Argument(default, "https-cert-password")]
[EnvironmentVariable("HTTPS_CERT_PASSWORD")]
[Description("X509 certificate password")]
+ [RequiresRestart]
public string Password { get; private set; }
}
}
@@ -676,6 +790,11 @@ namespace slskd
[Range(0, 5)]
public int RetryAttempts { get; private set; } = 3;
+ /// <summary>
+ /// Extended validation.
+ /// </summary>
+ /// <param name="validationContext"></param>
+ /// <returns></returns>
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
var results = new List<ValidationResult>();
@@ -752,6 +871,11 @@ namespace slskd
[Description("cooldown time for Pushbullet notifications, in milliseconds")]
public int CooldownTime { get; private set; } = 900000; // 15 minutes
+ /// <summary>
+ /// Extended validation.
+ /// </summary>
+ /// <param name="validationContext"></param>
+ /// <returns></returns>
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
var results = new List<ValidationResult>();
diff --git a/src/slskd/Program.cs b/src/slskd/Program.cs
index 062d3a48..d22ab433 100644
--- a/src/slskd/Program.cs
+++ b/src/slskd/Program.cs
@@ -120,7 +120,7 @@ namespace slskd
public static string Version { get; } = $"{AssemblyVersion} ({InformationalVersion})";
private static IConfigurationRoot Configuration { get; set; }
- private static Options Options { get; } = new Options();
+ private static OptionsAtStartup OptionsAtStartup { get; } = new OptionsAtStartup();
[EnvironmentVariable("CONFIG")]
[Argument('c', "config", "path to configuration file")]
@@ -193,14 +193,14 @@ namespace slskd
.Build();
Configuration.GetSection(AppName)
- .Bind(Options, (o) => { o.BindNonPublicProperties = true; });
+ .Bind(OptionsAtStartup, (o) => { o.BindNonPublicProperties = true; });
- if (Options.Debug)
+ if (OptionsAtStartup.Debug)
{
Console.WriteLine($"Configuration:\n{Configuration.GetDebugView()}");
}
- if (!Options.TryValidate(out var result))
+ if (!OptionsAtStartup.TryValidate(out var result))
{
Console.WriteLine(result.GetResultView());
return;
@@ -208,16 +208,16 @@ namespace slskd
}
catch (Exception ex)
{
- Console.WriteLine($"Invalid configuration: {(!Options.Debug ? ex : ex.Message)}");
+ Console.WriteLine($"Invalid configuration: {(!OptionsAtStartup.Debug ? ex : ex.Message)}");
return;
}
try
{
- VerifyOrCreateDirectory(Options.Directories.App);
- VerifyOrCreateDirectory(Options.Directories.Incomplete);
- VerifyOrCreateDirectory(Options.Directories.Downloads);
- VerifyOrCreateDirectory(Options.Directories.Shared, verifyWriteable: false);
+ VerifyOrCreateDirectory(OptionsAtStartup.Directories.App);
+ VerifyOrCreateDirectory(OptionsAtStartup.Directories.Incomplete);
+ VerifyOrCreateDirectory(OptionsAtStartup.Directories.Downloads);
+ VerifyOrCreateDirectory(OptionsAtStartup.Directories.Shared, verifyWriteable: false);
}
catch (Exception ex)
{
@@ -225,31 +225,31 @@ namespace slskd
return;
}
- Log.Logger = (Options.Debug ? new LoggerConfiguration().MinimumLevel.Debug() : new LoggerConfiguration().MinimumLevel.Information())
+ Log.Logger = (OptionsAtStartup.Debug ? new LoggerConfiguration().MinimumLevel.Debug() : new LoggerConfiguration().MinimumLevel.Information())
.MinimumLevel.Override("Microsoft", LogEventLevel.Warning)
.MinimumLevel.Override("slskd.API.Authentication.PassthroughAuthenticationHandler", LogEventLevel.Information)
.Enrich.WithProperty("Version", Version)
- .Enrich.WithProperty("InstanceName", Options.InstanceName)
+ .Enrich.WithProperty("InstanceName", OptionsAtStartup.InstanceName)
.Enrich.WithProperty("InvocationId", InvocationId)
.Enrich.WithProperty("ProcessId", ProcessId)
.Enrich.FromLogContext()
.WriteTo.Console(
- outputTemplate: (Options.Debug ? "[{SourceContext}] [{SoulseekContext}] " : string.Empty) + "[{Timestamp:HH:mm:ss} {Level:u3}] {Message:lj}{NewLine}{Exception}")
+ outputTemplate: (OptionsAtStartup.Debug ? "[{SourceContext}] [{SoulseekContext}] " : string.Empty) + "[{Timestamp:HH:mm:ss} {Level:u3}] {Message:lj}{NewLine}{Exception}")
.WriteTo.Async(config =>
config.File(
Path.Combine(AppContext.BaseDirectory, "logs", $"{AppName}-.log"),
- outputTemplate: (Options.Debug ? "[{SourceContext}] " : string.Empty) + "[{Timestamp:HH:mm:ss} {Level:u3}] {Message:lj}{NewLine}{Exception}",
+ outputTemplate: (OptionsAtStartup.Debug ? "[{SourceContext}] " : string.Empty) + "[{Timestamp:HH:mm:ss} {Level:u3}] {Message:lj}{NewLine}{Exception}",
rollingInterval: RollingInterval.Day))
.WriteTo.Conditional(
- e => !string.IsNullOrEmpty(Options.Logger.Loki),
+ e => !string.IsNullOrEmpty(OptionsAtStartup.Logger.Loki),
config => config.GrafanaLoki(
- Options.Logger.Loki ?? string.Empty,
+ OptionsAtStartup.Logger.Loki ?? string.Empty,
outputTemplate: "[{Timestamp:HH:mm:ss} {Level:u3}] {Message:lj}{NewLine}{Exception}"))
.CreateLogger();
var logger = Log.ForContext(typeof(Program));
- if (!Options.NoLogo)
+ if (!OptionsAtStartup.NoLogo)
{
PrintLogo(Version);
}
@@ -260,18 +260,18 @@ namespace slskd
}
logger.Information("Version: {Version}", Version);
- logger.Information("Instance Name: {InstanceName}", Options.InstanceName);
+ logger.Information("Instance Name: {InstanceName}", OptionsAtStartup.InstanceName);
logger.Information("Invocation ID: {InvocationId}", InvocationId);
logger.Information("Process ID: {ProcessId}", ProcessId);
- if (!string.IsNullOrEmpty(Options.Logger.Loki))
+ if (!string.IsNullOrEmpty(OptionsAtStartup.Logger.Loki))
{
- logger.Information("Forwarding logs to Grafana Loki instance at {LoggerLokiUrl}", Options.Logger.Loki);
+ logger.Information("Forwarding logs to Grafana Loki instance at {LoggerLokiUrl}", OptionsAtStartup.Logger.Loki);
}
try
{
- if (Options.Feature.Prometheus)
+ if (OptionsAtStartup.Feature.Prometheus)
{
using var runtimeMetrics = DotNetRuntimeStatsBuilder.Default().StartCollecting();
}
@@ -287,13 +287,13 @@ namespace slskd
.UseUrls()
.UseKestrel(options =>
{
- logger.Information($"Listening for HTTP requests at http://{IPAddress.Any}:{Options.Web.Port}/");
- options.Listen(IPAddress.Any, Options.Web.Port);
+ logger.Information($"Listening for HTTP requests at http://{IPAddress.Any}:{OptionsAtStartup.Web.Port}/");
+ options.Listen(IPAddress.Any, OptionsAtStartup.Web.Port);
- logger.Information($"Listening for HTTPS requests at https://{IPAddress.Any}:{Options.Web.Https.Port}/");
- options.Listen(IPAddress.Any, Options.Web.Https.Port, listenOptions =>
+ logger.Information($"Listening for HTTPS requests at https://{IPAddress.Any}:{OptionsAtStartup.Web.Https.Port}/");
+ options.Listen(IPAddress.Any, OptionsAtStartup.Web.Https.Port, listenOptions =>
{
- var cert = Options.Web.Https.Certificate;
+ var cert = OptionsAtStartup.Web.Https.Certificate;
if (!string.IsNullOrEmpty(cert.Pfx))
{
@@ -310,7 +310,7 @@ namespace slskd
.UseStartup<Startup>()
.Build();
- if (Options.NoStart)
+ if (OptionsAtStartup.NoStart)
{
logger.Information("Qutting because 'no-start' option is enabled");
return;
@@ -340,8 +340,9 @@ namespace slskd
prefix: environmentVariablePrefix)
.AddYamlFile(
path: Path.GetFileName(configurationFile),
+ targetType: typeof(Options),
optional: true,
- reloadOnChange: false,
+ reloadOnChange: true,
provider: new PhysicalFileProvider(Path.GetDirectoryName(configurationFile), ExclusionFilters.None)) // required for locations outside of the app directory
.AddCommandLine(
targetType: typeof(Options),
diff --git a/src/slskd/Properties/analysis.ruleset b/src/slskd/Properties/analysis.ruleset
index 09e99d9e..4e4ae5cf 100644
--- a/src/slskd/Properties/analysis.ruleset
+++ b/src/slskd/Properties/analysis.ruleset
@@ -45,6 +45,7 @@
<Rule Id="SA1116" Action="None" />
<Rule Id="SA1117" Action="None" />
<Rule Id="SA1124" Action="None" />
+ <Rule Id="SA1200" Action="Info" />
<Rule Id="SA1300" Action="None" />
<Rule Id="SA1402" Action="None" />
<Rule Id="SA1516" Action="None" />
diff --git a/src/slskd/Properties/slskd.yml b/src/slskd/Properties/slskd.yml
index 43c87f90..938d2a70 100644
--- a/src/slskd/Properties/slskd.yml
+++ b/src/slskd/Properties/slskd.yml
@@ -1,72 +1,71 @@
-# slskd:
-# debug: false
-# no_logo: false
-# instance_name: default
-# web:
-# port: 5000
-# https:
-# port: 5001
-# force: false
-# certificate:
-# pfx: ~
-# password: ~
-# url_base: /
-# content_path: wwwroot
-# authentication:
-# disable: false
-# username: slskd
-# password: slskd
-# jwt:
-# key: ~
-# ttl: 604800000
-# directories:
-# app: ~
-# incomplete: ~
-# downloads: ~
-# shared: ~
-# logger:
-# loki: ~
-# feature:
-# prometheus: false
-# swagger: false
-# soulseek:
-# username: ~
-# password: ~
-# listen_port: 50000
-# diagnostic_level: Info
-# distributed_network:
-# disabled: false
-# child_limit: 25
-# connection:
-# timeout:
-# connect: 10000
-# inactivity: 15000
-# buffer:
-# read: 16384
-# write: 16384
-# proxy:
-# address: ~
-# port: ~
-# username: ~
-# password: ~
-# integration:
-# ftp:
-# enabled: false
+# debug: false
+# no_logo: false
+# instance_name: default
+# web:
+# port: 5000
+# https:
+# port: 5001
+# force: false
+# certificate:
+# pfx: ~
+# password: ~
+# url_base: /
+# content_path: wwwroot
+# authentication:
+# disable: false
+# username: slskd
+# password: slskd
+# jwt:
+# key: ~
+# ttl: 604800000
+# directories:
+# app: ~
+# incomplete: ~
+# downloads: ~
+# shared: ~
+# logger:
+# loki: ~
+# feature:
+# prometheus: false
+# swagger: false
+# soulseek:
+# username: ~
+# password: ~
+# listen_port: 50000
+# diagnostic_level: Info
+# distributed_network:
+# disabled: false
+# child_limit: 25
+# connection:
+# timeout:
+# connect: 10000
+# inactivity: 15000
+# buffer:
+# read: 16384
+# write: 16384
+# proxy:
# address: ~
# port: ~
-# encryption_mode: auto
-# ignore_certificate_errors: false
# username: ~
# password: ~
-# remote_path: /
-# overwrite_existing: true
-# connection_timeout: 5000
-# retry_attempts: 3
-# pushbullet:
-# enabled: false
-# access_token: ~
-# notification_prefix: "From slskd:"
-# notify_on_private_message: true
-# notify_on_room_mention: true
-# retry_attempts: 3
-# cooldown_time: 900000 \ No newline at end of file
+# integration:
+# ftp:
+# enabled: false
+# address: ~
+# port: ~
+# encryption_mode: auto
+# ignore_certificate_errors: false
+# username: ~
+# password: ~
+# remote_path: /
+# overwrite_existing: true
+# connection_timeout: 5000
+# retry_attempts: 3
+# pushbullet:
+# enabled: false
+# access_token: ~
+# notification_prefix: "From slskd:"
+# notify_on_private_message: true
+# notify_on_room_mention: true
+# retry_attempts: 3
+# cooldown_time: 900000 \ No newline at end of file
diff --git a/src/slskd/Startup.cs b/src/slskd/Startup.cs
index 635a6890..af0fd329 100644
--- a/src/slskd/Startup.cs
+++ b/src/slskd/Startup.cs
@@ -42,6 +42,7 @@ namespace slskd
using slskd.Peer;
using slskd.Search;
using slskd.Transfer;
+ using slskd.Validation;
/// <summary>
/// ASP.NET Startup.
@@ -51,29 +52,29 @@ namespace slskd
/// <summary>
/// Initializes a new instance of the <see cref="Startup"/> class.
/// </summary>
- /// <param name="configuration">The application configuration.</param>
+ /// <param name="configuration">The application configuration root.</param>
public Startup(IConfiguration configuration)
{
Configuration = configuration;
- Options = new Options();
- Configuration.GetSection(Program.AppName).Bind(Options, (o) =>
+ OptionsAtStartup = new OptionsAtStartup();
+ Configuration.GetSection(Program.AppName).Bind(OptionsAtStartup, (o) =>
{
o.BindNonPublicProperties = true;
});
- UrlBase = Options.Web.UrlBase;
+ UrlBase = OptionsAtStartup.Web.UrlBase;
UrlBase = UrlBase.StartsWith("/") ? UrlBase : "/" + UrlBase;
- ContentPath = Path.GetFullPath(Options.Web.ContentPath);
+ ContentPath = Path.GetFullPath(OptionsAtStartup.Web.ContentPath);
- JwtSigningKey = new SymmetricSecurityKey(Pbkdf2.GetKey(Options.Web.Authentication.Jwt.Key));
+ JwtSigningKey = new SymmetricSecurityKey(Pbkdf2.GetKey(OptionsAtStartup.Web.Authentication.Jwt.Key));
}
private IConfiguration Configuration { get; }
private string ContentPath { get; set; }
private SymmetricSecurityKey JwtSigningKey { get; set; }
- private Options Options { get; }
+ private OptionsAtStartup OptionsAtStartup { get; }
private string UrlBase { get; set; }
/// <summary>
@@ -84,14 +85,34 @@ namespace slskd
{
var logger = Log.ForContext<Startup>();
+ // add the instance of OptionsAtStartup to DI as they were at startup. use when Options might change, but
+ // the values at startup are to be used.
+ services.AddSingleton(OptionsAtStartup);
+
+ // add IOptionsMonitor and IOptionsSnapshot to DI. use when the current Options are to be used.
services.AddOptions<Options>()
- .Bind(Configuration.GetSection(Program.AppName), o => { o.BindNonPublicProperties = true; });
+ .Bind(Configuration.GetSection(Program.AppName), o => { o.BindNonPublicProperties = true; })
+ .Validate(options =>
+ {
+ if (!options.TryValidate(out var result))
+ {
+ logger.Warning("Options (re)configuration rejected.");
+ logger.Warning(result.GetResultView());
+ return false;
+ }
+
+ return true;
+ });
+
+ // add IStateMonitor to DI, to track application state in an observable way. similar to IOptionsMonitor,
+ // but state is managed by the application itself. Usage is roughly the same.
+ services.AddSingleton<IStateMonitor, StateMonitor>();
services.AddCors(options => options.AddPolicy("AllowAll", builder => builder.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader()));
services.AddSingleton(JwtSigningKey);
- if (!Options.Web.Authentication.Disable)
+ if (!OptionsAtStartup.Web.Authentication.Disable)
{
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(options =>
@@ -139,7 +160,7 @@ namespace slskd
options.SubstituteApiVersionInUrl = true;
});
- if (Options.Feature.Swagger)
+ if (OptionsAtStartup.Feature.Swagger)
{
services.AddSwaggerGen(options =>
{
@@ -163,19 +184,19 @@ namespace slskd
});
}
- if (Options.Feature.Prometheus)
+ if (OptionsAtStartup.Feature.Prometheus)
{
services.AddSystemMetrics();
}
services.AddDbContextFactory<SearchDbContext>(options =>
{
- options.UseSqlite($"Data Source={Path.Combine(Options.Directories.App, "search.db")}");
+ options.UseSqlite($"Data Source={Path.Combine(OptionsAtStartup.Directories.App, "search.db")}");
});
services.AddDbContextFactory<PeerDbContext>(options =>
{
- options.UseSqlite($"Data Source={Path.Combine(Options.Directories.App, "peer.db")}");
+ options.UseSqlite($"Data Source={Path.Combine(OptionsAtStartup.Directories.App, "peer.db")}");
});
services.AddHttpClient();
@@ -185,14 +206,14 @@ namespace slskd
services.AddSingleton<IConversationTracker, ConversationTracker>();
services.AddSingleton<IRoomTracker, RoomTracker>(_ => new RoomTracker(messageLimit: 250));
services.AddSingleton<ISharedFileCache>(_ =>
- new SharedFileCache(Options.Directories.Shared, 3600000));
+ new SharedFileCache(OptionsAtStartup.Directories.Shared, 3600000));
services.AddSingleton<ISearchService, SearchService>();
services.AddSingleton<IPeerService, PeerService>();
services.AddSingleton<IManagementService, ManagementService>();
services.AddSingleton<IFTPClientFactory, FTPClientFactory>();
- services.AddTransient<IFTPService, FTPService>();
+ services.AddSingleton<IFTPService, FTPService>();
services.AddSingleton<IPushbulletService, PushbulletService>();
@@ -213,7 +234,7 @@ namespace slskd
app.UseCors("AllowAll");
- if (Options.Web.Https.Force)
+ if (OptionsAtStartup.Web.Https.Force)
{
app.UseHttpsRedirection();
app.UseHsts();
@@ -258,7 +279,7 @@ namespace slskd
logger.Information("Serving static content from {ContentPath}", ContentPath);
}
- if (Options.Feature.Prometheus)
+ if (OptionsAtStartup.Feature.Prometheus)
{
app.UseHttpMetrics();
logger.Information("Publishing Prometheus metrics to /metrics");
@@ -275,13 +296,13 @@ namespace slskd
endpoints.MapControllers();
endpoints.MapHealthChecks("/health");
- if (Options.Feature.Prometheus)
+ if (OptionsAtStartup.Feature.Prometheus)
{
endpoints.MapMetrics();
}
});
- if (Options.Feature.Swagger)
+ if (OptionsAtStartup.Feature.Swagger)
{
app.UseSwagger();
app.UseSwaggerUI(options => apiVersionDescriptionProvider.ApiVersionDescriptions.ToList()