From 4876d4a5f024e2223312e95999f9be12bd8511fc Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Wed, 20 Jan 2021 22:26:31 -0600 Subject: wip --- src/slskd/Options.cs | 52 ++++++++++++++++++++++++++++++++++++++++++++++++++ src/slskd/Program.cs | 15 ++++++++------- src/slskd/Roles.cs | 9 +++++++++ src/slskd/Startup.cs | 34 +++++++++++++++++++++++++++++---- src/slskd/config.yml | 25 ++++++++++++++++++++++++ src/slskd/slskd.csproj | 10 ++++++++++ 6 files changed, 134 insertions(+), 11 deletions(-) create mode 100644 src/slskd/Options.cs create mode 100644 src/slskd/Roles.cs create mode 100644 src/slskd/config.yml (limited to 'src') diff --git a/src/slskd/Options.cs b/src/slskd/Options.cs new file mode 100644 index 00000000..f02f4d49 --- /dev/null +++ b/src/slskd/Options.cs @@ -0,0 +1,52 @@ +using System; +using System.Collections.Generic; +using System.ComponentModel.DataAnnotations; +using System.Linq; +using System.Threading.Tasks; + +namespace slskd +{ + public class Options + { + public class slskd + { + public Soulseek Soulseek { get; set; } + public IEnumerable Users { get; set; } + public IEnumerable ApiKeys { get; set; } + } + + public class Soulseek + { + public SoulseekCredentials Credentials { get; set; } + public SoulseekDistributedNetwork DistributedNetwork { get; set; } + + [Range(1024, 65535)] + public int ListenPort { get; set; } + + public class SoulseekCredentials + { + public string Username { get; set; } + public string Password { get; set; } + } + + public class SoulseekDistributedNetwork + { + public bool Enable { get; set; } + public int ChildLimit { get; set; } + } + } + + public class User + { + public string Username { get; set; } + public string PasswordHash { get; set; } + public Roles Role { get; set; } + } + + public class ApiKey + { + public string Key { get; set; } + public Roles Role { get; set; } + } + } +} diff --git a/src/slskd/Program.cs b/src/slskd/Program.cs index dc3b7c05..1b08b918 100644 --- a/src/slskd/Program.cs +++ b/src/slskd/Program.cs @@ -13,6 +13,7 @@ using System.Reflection; using Utility.CommandLine; using Utility.EnvironmentVariables; + using Utility.Extensions.Configuration.Yaml; public class Program { @@ -93,7 +94,7 @@ { if (!DisableLogo) { - PrintBanner(Version); + PrintLogo(Version); } PrintHelp(); @@ -155,7 +156,7 @@ if (!DisableLogo) { - PrintBanner(Version); + PrintLogo(Version); } var logger = Log.ForContext(); @@ -209,12 +210,12 @@ .ConfigureAppConfiguration((hostingContext, config) => { config.AddEnvironmentVariables(prefix: "SLSK_"); - config.AddJsonFile("config.json", optional: true, reloadOnChange: false); + config.AddYamlFile("config.yml", optional: true, reloadOnChange: true); }) .UseSerilog() .UseStartup(); - public static void PrintBanner(string version) + private static void PrintLogo(string version) { var padding = 56 - version.Length; var paddingLeft = padding / 2; @@ -237,13 +238,13 @@ Console.WriteLine(banner); } - public static void PrintHelp() + private static void PrintHelp() { PrintArguments(); PrintEnvironmentVariables(); } - public static void PrintArguments() + private static void PrintArguments() { static string GetLongName(ArgumentInfo info) => info.Property.PropertyType == typeof(bool) ? info.LongName : $"{info.LongName} <{info.Property.PropertyType.Name.ToLowerInvariant()}>"; @@ -267,7 +268,7 @@ } } - public static void PrintEnvironmentVariables() + private static void PrintEnvironmentVariables() { static string GetEnvironmentVariableName(ArgumentInfo info, bool includeType = false) => info.Property.CustomAttributes diff --git a/src/slskd/Roles.cs b/src/slskd/Roles.cs new file mode 100644 index 00000000..5ddee6d8 --- /dev/null +++ b/src/slskd/Roles.cs @@ -0,0 +1,9 @@ +namespace slskd +{ + public enum Roles + { + ReadOnly = 0, + User = 1, + Administrator = 2 + } +} diff --git a/src/slskd/Startup.cs b/src/slskd/Startup.cs index 37a3c7cd..9dd9f52d 100644 --- a/src/slskd/Startup.cs +++ b/src/slskd/Startup.cs @@ -32,6 +32,7 @@ using Microsoft.Extensions.Logging; using Prometheus; using Prometheus.SystemMetrics; + using Microsoft.Extensions.Options; public class Startup { @@ -101,6 +102,20 @@ public void ConfigureServices(IServiceCollection services) { + services.AddOptions() + .Bind(Configuration.GetSection("soulseek")); + + services.PostConfigure>(slskd => + { + Console.WriteLine($"config updated"); + Console.WriteLine(JsonSerializer.Serialize(slskd)); + }); + + services.AddOptions>().Bind(Configuration.GetSection("sparse")); + services.PostConfigure>(s => Console.WriteLine(JsonSerializer.Serialize(s))); + + services.AddOptions>().Bind(Configuration.GetSection("users")); + services.AddCors(options => options.AddPolicy("AllowAll", builder => builder.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader())); if (!Program.DisableAuthentication) @@ -184,6 +199,9 @@ ITransferTracker tracker, IBrowseTracker browseTracker, IConversationTracker conversationTracker, + IOptionsMonitor optionsAccessor, + IOptionsMonitor> users, + IOptionsMonitor> sparse, IRoomTracker roomTracker) { if (!env.IsDevelopment()) @@ -191,6 +209,14 @@ app.UseHsts(); } + optionsAccessor.OnChange(options => + { + Console.WriteLine(JsonSerializer.Serialize(optionsAccessor)); + }); + + sparse.OnChange(v => Console.WriteLine(JsonSerializer.Serialize(v))); + users.OnChange(users => Console.WriteLine(JsonSerializer.Serialize(users))); + app.UseCors("AllowAll"); app.UsePathBase(BasePath); @@ -395,10 +421,10 @@ } }; - Task.Run(async () => - { - await Client.ConnectAsync(Username, Password); - }).GetAwaiter().GetResult(); + //Task.Run(async () => + //{ + // await Client.ConnectAsync(Username, Password); + //}).GetAwaiter().GetResult(); logger.LogInformation("Connected and logged in as {Username}", Username); } diff --git a/src/slskd/config.yml b/src/slskd/config.yml new file mode 100644 index 00000000..266ab9da --- /dev/null +++ b/src/slskd/config.yml @@ -0,0 +1,25 @@ +soulseek: + credentials: + username: foo + password: bar + listenPort: 500 + distributedNetwork: + enable: true + childLimit: 100 +users: +- username: admin + passwordHash: abc + role: Administrators +- username: user + passwordHash: xyz + role: User +apiKeys: +- key: '1234567890' + role: ReadOnly +sparse: + - ~ + - 2nd entry + - + - 4th entry + - Null + - tests \ No newline at end of file diff --git a/src/slskd/slskd.csproj b/src/slskd/slskd.csproj index 7377ea60..4e1d9994 100644 --- a/src/slskd/slskd.csproj +++ b/src/slskd/slskd.csproj @@ -22,6 +22,14 @@ + + + + + + + + @@ -43,6 +51,8 @@ + + -- cgit v1.2.3 From 4afc5f54c37a1bcc7b2593e4a04d4cdf9c5f8b12 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Thu, 21 Jan 2021 18:00:40 -0600 Subject: more wip --- src/slskd/Configuration.cs | 153 +++++++++++++++++++++++++++++++++++++++++ src/slskd/Options.cs | 46 +++---------- src/slskd/Program.cs | 168 +++++++++++++++++++++++++++------------------ src/slskd/Startup.cs | 38 +++++----- src/slskd/config.yml | 32 ++------- 5 files changed, 291 insertions(+), 146 deletions(-) create mode 100644 src/slskd/Configuration.cs (limited to 'src') diff --git a/src/slskd/Configuration.cs b/src/slskd/Configuration.cs new file mode 100644 index 00000000..8f11bd07 --- /dev/null +++ b/src/slskd/Configuration.cs @@ -0,0 +1,153 @@ +namespace slskd +{ + using Microsoft.Extensions.Configuration; + using System; + using System.Collections; + using System.Collections.Generic; + using System.Diagnostics; + using System.Globalization; + using System.Linq; + using System.Reflection; + using System.Runtime.CompilerServices; + + public class ConfigurationAttribute : Attribute + { + public ConfigurationAttribute(string key) + { + Key = key; + } + + public string Key { get; set; } + } + + public static class Configuration + { + public static void Populate(this IConfiguration configuration, [CallerMemberName] string caller = default(string)) + { + var type = GetCallingType(caller); + var targetProperties = GetTargetProperties(type); + + foreach (var property in targetProperties) + { + var propertyType = property.Value.PropertyType; + + string value = configuration.GetValue(property.Key); + Console.WriteLine($"key {property.Key} value {value}"); + + if (string.IsNullOrEmpty(value)) + { + Console.WriteLine("skip"); + continue; + } + + object convertedValue; + + if (propertyType == typeof(bool)) + { + convertedValue = value?.Equals("true", StringComparison.InvariantCultureIgnoreCase) ?? false; + } + else if (propertyType.IsArray || (propertyType.IsGenericType && propertyType.GetGenericTypeDefinition() == typeof(List<>))) + { + Type valueType; + + if (propertyType.IsArray) + { + valueType = propertyType.GetElementType(); + } + else + { + valueType = propertyType.GetGenericArguments()[0]; + } + + // create a list to store converted values + Type valueListType = typeof(List<>).MakeGenericType(valueType); + var valueList = (IList)Activator.CreateInstance(valueListType); + + // populate the list + foreach (object v in value.Split(',').Select(s => s.Trim())) + { + valueList.Add(ChangeType(v, property.Key, valueType)); + } + + if (propertyType.IsArray) + { + var valueArray = Array.CreateInstance(propertyType.GetElementType(), valueList.Count); + + for (int i = 0; i < valueArray.Length; i++) + { + valueArray.SetValue(valueList[i], i); + } + + convertedValue = valueArray; + } + else + { + convertedValue = valueList; + } + } + else + { + convertedValue = ChangeType(value, property.Key, property.Value.PropertyType); + } + + property.Value.SetValue(null, convertedValue); + } + } + + private static Type GetCallingType(string caller) + { + var callingMethod = new StackTrace().GetFrames() + .Select(f => f.GetMethod()) + .FirstOrDefault(m => m.Name == caller); + + if (callingMethod == default(MethodBase)) + { + throw new InvalidOperationException($"Unable to determine the containing type of the calling method '{caller}'. Explicitly specify the originating Type."); + } + + return callingMethod.DeclaringType; + } + + private static Dictionary GetTargetProperties(Type type) + { + Dictionary properties = new Dictionary(); + + foreach (PropertyInfo property in type.GetProperties(BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Static)) + { + // attempt to fetch the ArgumentAttribute of the property + CustomAttributeData attribute = property.CustomAttributes.FirstOrDefault(a => a.AttributeType.Name == typeof(ConfigurationAttribute).Name); + + // if found, extract the Name property and add it to the dictionary + if (attribute != default(CustomAttributeData)) + { + string name = (string)attribute.ConstructorArguments[0].Value; + + if (!properties.ContainsKey(name)) + { + properties.Add(name, property); + } + } + } + + return properties; + } + + private static object ChangeType(object value, string name, Type type) + { + try + { + if (type.IsEnum) + { + return Enum.Parse(type, (string)value, true); + } + + return Convert.ChangeType(value, type, CultureInfo.InvariantCulture); + } + catch (Exception ex) when (ex is InvalidCastException || ex is FormatException || ex is OverflowException || ex is ArgumentNullException) + { + string message = $"Failed to convert value '{value}' to target type {type}"; + throw new ArgumentException(message, name, ex); + } + } + } +} diff --git a/src/slskd/Options.cs b/src/slskd/Options.cs index f02f4d49..0dbc9409 100644 --- a/src/slskd/Options.cs +++ b/src/slskd/Options.cs @@ -8,45 +8,17 @@ namespace slskd { public class Options { - public class slskd - { - public Soulseek Soulseek { get; set; } - public IEnumerable Users { get; set; } - public IEnumerable ApiKeys { get; set; } - } - - public class Soulseek - { - public SoulseekCredentials Credentials { get; set; } - public SoulseekDistributedNetwork DistributedNetwork { get; set; } - - [Range(1024, 65535)] - public int ListenPort { get; set; } - - public class SoulseekCredentials - { - public string Username { get; set; } - public string Password { get; set; } - } - - public class SoulseekDistributedNetwork - { - public bool Enable { get; set; } - public int ChildLimit { get; set; } - } - } - - public class User - { - public string Username { get; set; } - public string PasswordHash { get; set; } - public Roles Role { get; set; } - } + public slskdOptions slskd { get; set; } - public class ApiKey + public class slskdOptions { - public string Key { get; set; } - public Roles Role { get; set; } + public bool? Debug { get; set; } + public bool? NoLogo { get; set; } + public bool? NoAuth { get; set; } + public string InstanceName { get; set; } + public bool? Prometheus { get; set; } + public bool? Swagger { get; set; } + public string Loki { get; set; } } } } diff --git a/src/slskd/Program.cs b/src/slskd/Program.cs index 1b08b918..af181cfe 100644 --- a/src/slskd/Program.cs +++ b/src/slskd/Program.cs @@ -9,6 +9,7 @@ using Serilog.Sinks.Grafana.Loki; using System; using System.Diagnostics; + using System.IO; using System.Linq; using System.Reflection; using Utility.CommandLine; @@ -23,32 +24,39 @@ [Argument('v', "version", "display version information")] public static bool ShowVersion { get; private set; } - [Argument('d', "debug", "run in debug mode")] [EnvironmentVariable("SLSKD_DEBUG")] + [Configuration("slskd:debug")] + [Argument('d', "debug", "run in debug mode")] public static bool Debug { get; private set; } - [Argument('n', "no-logo", "suppress logo on startup")] [EnvironmentVariable("SLSKD_NO_LOGO")] + [Configuration("slskd:noLogo")] + [Argument('n', "no-logo", "suppress logo on startup")] public static bool DisableLogo { get; private set; } - [Argument('x', "no-auth", "disable authentication for web requests")] [EnvironmentVariable("SLSKD_NO_AUTH")] + [Configuration("slskd:noAuth")] + [Argument('x', "no-auth", "disable authentication for web requests")] public static bool DisableAuthentication { get; private set; } - [Argument('i', "instance-name", "optional; a unique name for this instance")] [EnvironmentVariable("SLSKD_INSTANCE_NAME")] + [Configuration("slskd:instanceName")] + [Argument('i', "instance-name", "optional; a unique name for this instance")] public static string InstanceName { get; private set; } = "default"; - [Argument('p', "prometheus", "enable collection and publish of prometheus metrics")] [EnvironmentVariable("SLSKD_PROMETHEUS")] + [Configuration("slskd:prometheus")] + [Argument('p', "prometheus", "enable collection and publish of prometheus metrics")] public static bool EnablePrometheus { get; private set; } - [Argument('s', "swagger", "enable swagger documentation")] [EnvironmentVariable("SLSKD_SWAGGER")] + [Configuration("slskd:swagger")] + [Argument('s', "swagger", "enable swagger documentation")] public static bool EnableSwagger { get; private set; } - [Argument(default, "loki", "the url to a Grafana Loki instance to which to log")] [EnvironmentVariable("SLSKD_LOKI")] + [Configuration("slskd:loki")] + [Argument(default, "loki", "the url to a Grafana Loki instance to which to log")] public static string LokiUrl { get; private set; } public static bool EnableLoki { get; private set; } @@ -56,6 +64,8 @@ public static Guid InvocationId { get; private set; } public static int ProcessId { get; private set; } + public static readonly string ConfigurationFile = "config.yml"; + public static void Main(string[] args) { try @@ -65,6 +75,22 @@ catch (Exception ex) { Console.WriteLine($"Error parsing environment variables: {ex.Message}"); + return; + } + + try + { + var config = new ConfigurationBuilder() + .SetBasePath(Directory.GetCurrentDirectory()) + .AddYamlFile(ConfigurationFile, optional: true, reloadOnChange: false) + .Build(); + + config.Populate(); + } + catch (Exception ex) + { + Console.WriteLine($"Error parsing configuration file '{ConfigurationFile}': {ex.Message}"); + return; } try @@ -73,16 +99,13 @@ } catch (Exception ex) { - Console.WriteLine($"Error parsing input: {ex.Message}"); + Console.WriteLine($"Error parsing command line input: {ex.Message}"); + return; } - InvocationId = Guid.NewGuid(); - ProcessId = Environment.ProcessId; + Console.WriteLine(LokiUrl); - var assembly = Assembly.GetExecutingAssembly(); - var assemblyVersion = assembly.GetName().Version; - var informationVersion = assembly.GetCustomAttribute().InformationalVersion; - Version = $"{assemblyVersion} ({informationVersion})"; + Version = ComputeVersion(); if (ShowVersion) { @@ -101,58 +124,12 @@ return; } + InvocationId = Guid.NewGuid(); + ProcessId = Environment.ProcessId; Debug = Debugger.IsAttached || Debug; EnableLoki = !string.IsNullOrEmpty(LokiUrl); - - if (Debug) - { - Log.Logger = new LoggerConfiguration() - .MinimumLevel.Debug() - .MinimumLevel.Override("Microsoft", LogEventLevel.Information) - .Enrich.WithProperty("Version", Version) - .Enrich.WithProperty("InstanceName", InstanceName) - .Enrich.WithProperty("InvocationId", InvocationId) - .Enrich.WithProperty("ProcessId", ProcessId) - .Enrich.FromLogContext() - .WriteTo.Console( - outputTemplate: "[{SourceContext}] [{Timestamp:HH:mm:ss} {Level:u3}] {Message:lj}{NewLine}{Exception}") - .WriteTo.Async(config => - config.File( - "logs/slskd-.log", - outputTemplate: "[{SourceContext}] [{Timestamp:HH:mm:ss} {Level:u3}] {Message:lj}{NewLine}{Exception}", - rollingInterval: RollingInterval.Day)) - .WriteTo.Conditional( - e => EnableLoki, - config => config.GrafanaLoki( - LokiUrl ?? string.Empty, - outputTemplate: "[{Timestamp:HH:mm:ss} {Level:u3}] {Message:lj}{NewLine}{Exception}")) - .CreateLogger(); - } - else - { - Log.Logger = new LoggerConfiguration() - .MinimumLevel.Information() - .MinimumLevel.Override("Microsoft", LogEventLevel.Warning) - .MinimumLevel.Override("slskd.Security.PassthroughAuthenticationHandler", LogEventLevel.Information) - .Enrich.WithProperty("Version", Version) - .Enrich.WithProperty("InstanceName", InstanceName) - .Enrich.WithProperty("InvocationId", InvocationId) - .Enrich.WithProperty("ProcessId", ProcessId) - .Enrich.FromLogContext() - .WriteTo.Console( - outputTemplate: "[{Timestamp:HH:mm:ss} {Level:u3}] {Message:lj}{NewLine}{Exception}") - .WriteTo.Async(config => - config.File( - "logs/slskd-.log", - outputTemplate: "[{Timestamp:HH:mm:ss} {Level:u3}] {Message:lj}{NewLine}{Exception}", - rollingInterval: RollingInterval.Day)) - .WriteTo.Conditional( - e => EnableLoki, - config => config.GrafanaLoki( - LokiUrl ?? string.Empty, - outputTemplate: "[{Timestamp:HH:mm:ss} {Level:u3}] {Message:lj}{NewLine}{Exception}")) - .CreateLogger(); - } + + ConfigureLogger(); if (!DisableLogo) { @@ -210,11 +187,72 @@ .ConfigureAppConfiguration((hostingContext, config) => { config.AddEnvironmentVariables(prefix: "SLSK_"); - config.AddYamlFile("config.yml", optional: true, reloadOnChange: true); + config.AddYamlFile(ConfigurationFile, optional: true, reloadOnChange: true); }) .UseSerilog() .UseStartup(); + private static string ComputeVersion() + { + var assembly = Assembly.GetExecutingAssembly(); + var assemblyVersion = assembly.GetName().Version; + var informationVersion = assembly.GetCustomAttribute().InformationalVersion; + return $"{assemblyVersion} ({informationVersion})"; + } + + private static void ConfigureLogger() + { + if (Debug) + { + Log.Logger = new LoggerConfiguration() + .MinimumLevel.Debug() + .MinimumLevel.Override("Microsoft", LogEventLevel.Information) + .Enrich.WithProperty("Version", Version) + .Enrich.WithProperty("InstanceName", InstanceName) + .Enrich.WithProperty("InvocationId", InvocationId) + .Enrich.WithProperty("ProcessId", ProcessId) + .Enrich.FromLogContext() + .WriteTo.Console( + outputTemplate: "[{SourceContext}] [{Timestamp:HH:mm:ss} {Level:u3}] {Message:lj}{NewLine}{Exception}") + .WriteTo.Async(config => + config.File( + "logs/slskd-.log", + outputTemplate: "[{SourceContext}] [{Timestamp:HH:mm:ss} {Level:u3}] {Message:lj}{NewLine}{Exception}", + rollingInterval: RollingInterval.Day)) + .WriteTo.Conditional( + e => EnableLoki, + config => config.GrafanaLoki( + LokiUrl ?? string.Empty, + outputTemplate: "[{Timestamp:HH:mm:ss} {Level:u3}] {Message:lj}{NewLine}{Exception}")) + .CreateLogger(); + } + else + { + Log.Logger = new LoggerConfiguration() + .MinimumLevel.Information() + .MinimumLevel.Override("Microsoft", LogEventLevel.Warning) + .MinimumLevel.Override("slskd.Security.PassthroughAuthenticationHandler", LogEventLevel.Information) + .Enrich.WithProperty("Version", Version) + .Enrich.WithProperty("InstanceName", InstanceName) + .Enrich.WithProperty("InvocationId", InvocationId) + .Enrich.WithProperty("ProcessId", ProcessId) + .Enrich.FromLogContext() + .WriteTo.Console( + outputTemplate: "[{Timestamp:HH:mm:ss} {Level:u3}] {Message:lj}{NewLine}{Exception}") + .WriteTo.Async(config => + config.File( + "logs/slskd-.log", + outputTemplate: "[{Timestamp:HH:mm:ss} {Level:u3}] {Message:lj}{NewLine}{Exception}", + rollingInterval: RollingInterval.Day)) + .WriteTo.Conditional( + e => EnableLoki, + config => config.GrafanaLoki( + LokiUrl ?? string.Empty, + outputTemplate: "[{Timestamp:HH:mm:ss} {Level:u3}] {Message:lj}{NewLine}{Exception}")) + .CreateLogger(); + } + } + private static void PrintLogo(string version) { var padding = 56 - version.Length; diff --git a/src/slskd/Startup.cs b/src/slskd/Startup.cs index 9dd9f52d..cfa59550 100644 --- a/src/slskd/Startup.cs +++ b/src/slskd/Startup.cs @@ -102,19 +102,19 @@ public void ConfigureServices(IServiceCollection services) { - services.AddOptions() - .Bind(Configuration.GetSection("soulseek")); + //services.AddOptions() + // .Bind(Configuration.GetSection("soulseek")); - services.PostConfigure>(slskd => - { - Console.WriteLine($"config updated"); - Console.WriteLine(JsonSerializer.Serialize(slskd)); - }); + //services.PostConfigure>(slskd => + //{ + // Console.WriteLine($"config updated"); + // Console.WriteLine(JsonSerializer.Serialize(slskd)); + //}); - services.AddOptions>().Bind(Configuration.GetSection("sparse")); - services.PostConfigure>(s => Console.WriteLine(JsonSerializer.Serialize(s))); + //services.AddOptions>().Bind(Configuration.GetSection("sparse")); + //services.PostConfigure>(s => Console.WriteLine(JsonSerializer.Serialize(s))); - services.AddOptions>().Bind(Configuration.GetSection("users")); + //services.AddOptions>().Bind(Configuration.GetSection("users")); services.AddCors(options => options.AddPolicy("AllowAll", builder => builder.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader())); @@ -199,9 +199,9 @@ ITransferTracker tracker, IBrowseTracker browseTracker, IConversationTracker conversationTracker, - IOptionsMonitor optionsAccessor, - IOptionsMonitor> users, - IOptionsMonitor> sparse, + //IOptionsMonitor optionsAccessor, + //IOptionsMonitor> users, + //IOptionsMonitor> sparse, IRoomTracker roomTracker) { if (!env.IsDevelopment()) @@ -209,13 +209,13 @@ app.UseHsts(); } - optionsAccessor.OnChange(options => - { - Console.WriteLine(JsonSerializer.Serialize(optionsAccessor)); - }); + //optionsAccessor.OnChange(options => + //{ + // Console.WriteLine(JsonSerializer.Serialize(optionsAccessor)); + //}); - sparse.OnChange(v => Console.WriteLine(JsonSerializer.Serialize(v))); - users.OnChange(users => Console.WriteLine(JsonSerializer.Serialize(users))); + //sparse.OnChange(v => Console.WriteLine(JsonSerializer.Serialize(v))); + //users.OnChange(users => Console.WriteLine(JsonSerializer.Serialize(users))); app.UseCors("AllowAll"); app.UsePathBase(BasePath); diff --git a/src/slskd/config.yml b/src/slskd/config.yml index 266ab9da..2a6642f6 100644 --- a/src/slskd/config.yml +++ b/src/slskd/config.yml @@ -1,25 +1,7 @@ -soulseek: - credentials: - username: foo - password: bar - listenPort: 500 - distributedNetwork: - enable: true - childLimit: 100 -users: -- username: admin - passwordHash: abc - role: Administrators -- username: user - passwordHash: xyz - role: User -apiKeys: -- key: '1234567890' - role: ReadOnly -sparse: - - ~ - - 2nd entry - - - - 4th entry - - Null - - tests \ No newline at end of file +slskd: + debug: false + noLogo: false + noAuth: false + instanceName: FromYAML + prometheus: true + loki1: http://192.168.1.60:3101 \ No newline at end of file -- cgit v1.2.3 From e52ca241f55e47e1e707134097ad5c4f8a641b07 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Thu, 21 Jan 2021 23:04:02 -0600 Subject: move stuff to common --- src/slskd/Common/Configuration.cs | 153 ++++++++++++++++++++ src/slskd/Common/YamlConfigurationSource.cs | 209 ++++++++++++++++++++++++++++ 2 files changed, 362 insertions(+) create mode 100644 src/slskd/Common/Configuration.cs create mode 100644 src/slskd/Common/YamlConfigurationSource.cs (limited to 'src') diff --git a/src/slskd/Common/Configuration.cs b/src/slskd/Common/Configuration.cs new file mode 100644 index 00000000..621c150e --- /dev/null +++ b/src/slskd/Common/Configuration.cs @@ -0,0 +1,153 @@ +namespace slskd +{ + using Microsoft.Extensions.Configuration; + using System; + using System.Collections; + using System.Collections.Generic; + using System.Diagnostics; + using System.Globalization; + using System.Linq; + using System.Reflection; + using System.Runtime.CompilerServices; + + public class ConfigurationAttribute : Attribute + { + public ConfigurationAttribute(string key) + { + Key = key; + } + + public string Key { get; set; } + } + + public static class Configuration + { + public static void Populate(this IConfiguration configuration, [CallerMemberName] string caller = default(string)) + { + var type = GetCallingType(caller); + var targetProperties = GetTargetProperties(type); + + foreach (var property in targetProperties) + { + var propertyType = property.Value.PropertyType; + + string value = configuration.GetValue(property.Key); + Console.WriteLine($"key {property.Key} value {value}"); + + if (string.IsNullOrEmpty(value)) + { + Console.WriteLine("skip"); + continue; + } + + object convertedValue; + + if (propertyType == typeof(bool)) + { + convertedValue = value?.Equals("true", StringComparison.InvariantCultureIgnoreCase) ?? false; + } + else if (propertyType.IsArray || (propertyType.IsGenericType && propertyType.GetGenericTypeDefinition() == typeof(List<>))) + { + Type valueType; + + if (propertyType.IsArray) + { + valueType = propertyType.GetElementType(); + } + else + { + valueType = propertyType.GetGenericArguments()[0]; + } + + // create a list to store converted values + Type valueListType = typeof(List<>).MakeGenericType(valueType); + var valueList = (IList)Activator.CreateInstance(valueListType); + + // populate the list + foreach (object v in value.Split(',').Select(s => s.Trim())) + { + valueList.Add(ChangeType(v, property.Key, valueType)); + } + + if (propertyType.IsArray) + { + var valueArray = Array.CreateInstance(propertyType.GetElementType(), valueList.Count); + + for (int i = 0; i < valueArray.Length; i++) + { + valueArray.SetValue(valueList[i], i); + } + + convertedValue = valueArray; + } + else + { + convertedValue = valueList; + } + } + else + { + convertedValue = ChangeType(value, property.Key, property.Value.PropertyType); + } + + property.Value.SetValue(null, convertedValue); + } + } + + private static Type GetCallingType(string caller) + { + var callingMethod = new StackTrace().GetFrames() + .Select(f => f.GetMethod()) + .FirstOrDefault(m => m.Name == caller); + + if (callingMethod == default(MethodBase)) + { + throw new InvalidOperationException($"Unable to determine the containing type of the calling method '{caller}'. Explicitly specify the originating Type."); + } + + return callingMethod.DeclaringType; + } + + private static Dictionary GetTargetProperties(Type type) + { + Dictionary properties = new Dictionary(); + + foreach (PropertyInfo property in type.GetProperties(BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Static)) + { + // attempt to fetch the ArgumentAttribute of the property + CustomAttributeData attribute = property.CustomAttributes.FirstOrDefault(a => a.AttributeType.Name == typeof(ConfigurationAttribute).Name); + + // if found, extract the Name property and add it to the dictionary + if (attribute != default(CustomAttributeData)) + { + string name = ((string)attribute.ConstructorArguments[0].Value)?.Replace("_", string.Empty).Replace("-", string.Empty); + + if (!properties.ContainsKey(name)) + { + properties.Add(name, property); + } + } + } + + return properties; + } + + private static object ChangeType(object value, string name, Type type) + { + try + { + if (type.IsEnum) + { + return Enum.Parse(type, (string)value, true); + } + + return Convert.ChangeType(value, type, CultureInfo.InvariantCulture); + } + catch (Exception ex) when (ex is InvalidCastException || ex is FormatException || ex is OverflowException || ex is ArgumentNullException) + { + string message = $"Failed to convert value '{value}' to target type {type}"; + throw new ArgumentException(message, name, ex); + } + } + } +} diff --git a/src/slskd/Common/YamlConfigurationSource.cs b/src/slskd/Common/YamlConfigurationSource.cs new file mode 100644 index 00000000..9dde3179 --- /dev/null +++ b/src/slskd/Common/YamlConfigurationSource.cs @@ -0,0 +1,209 @@ +/* + █▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀ ▀▀▀▀▀▀▀▀▀▀▀▀▀▀ ▀▀▀ ▀ ▀ ▀▀ + █ The MIT License (MIT) + █ + █ Copyright (c) 2021 JP Dillingham (jp@dillingham.ws) + █ + █ Permission is hereby granted, free of charge, to any person obtaining a copy + █ of this software and associated documentation files (the "Software"), to deal + █ in the Software without restriction, including without limitation the rights + █ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + █ copies of the Software, and to permit persons to whom the Software is + █ furnished to do so, subject to the following conditions: + █ + █ The above copyright notice and this permission notice shall be included in all + █ copies or substantial portions of the Software. + █ + █ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + █ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + █ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + █ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + █ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + █ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + █ SOFTWARE. + █ + ▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀ ▀▀ ▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀██ + ██ + ▀█▄ ██ ▄█▀ + ▀████▀ + ▀▀ */ + +namespace slskd +{ + using Microsoft.Extensions.Configuration; + using Microsoft.Extensions.FileProviders; + using System; + using System.IO; + using System.Linq; + using YamlDotNet.Core; + using YamlDotNet.RepresentationModel; + + /// + /// Extension methods for adding . + /// + public static class YamlConfigurationExtensions + { + /// + /// Adds the YAML configuration provider at to . + /// + /// The to add to. + /// Path relative to the base path stored in + /// of . + /// The . + public static IConfigurationBuilder AddYamlFile(this IConfigurationBuilder builder, string path) + { + return AddYamlFile(builder, provider: null, path: path, optional: false, reloadOnChange: false); + } + + /// + /// Adds the YAML configuration provider at to . + /// + /// The to add to. + /// Path relative to the base path stored in + /// of . + /// Whether the file is optional. + /// The . + public static IConfigurationBuilder AddYamlFile(this IConfigurationBuilder builder, string path, bool optional) + { + return AddYamlFile(builder, provider: null, path: path, optional: optional, reloadOnChange: false); + } + + /// + /// Adds the YAML configuration provider at to . + /// + /// The to add to. + /// Path relative to the base path stored in + /// of . + /// Whether the file is optional. + /// Whether the configuration should be reloaded if the file changes. + /// The . + public static IConfigurationBuilder AddYamlFile(this IConfigurationBuilder builder, string path, bool optional, bool reloadOnChange) + { + return AddYamlFile(builder, provider: null, path: path, optional: optional, reloadOnChange: reloadOnChange); + } + + /// + /// Adds a YAML configuration source to . + /// + /// The to add to. + /// The to use to access the file. + /// Path relative to the base path stored in + /// of . + /// Whether the file is optional. + /// Whether the configuration should be reloaded if the file changes. + /// The . + public static IConfigurationBuilder AddYamlFile(this IConfigurationBuilder builder, IFileProvider provider, string path, bool optional, bool reloadOnChange) + { + if (builder == null) + { + throw new ArgumentNullException(nameof(builder)); + } + if (string.IsNullOrEmpty(path)) + { + throw new ArgumentException("File path must be a non-empty string.", nameof(path)); + } + + return builder.AddYamlFile(s => + { + s.FileProvider = provider; + s.Path = path; + s.Optional = optional; + s.ReloadOnChange = reloadOnChange; + s.ResolveFileProvider(); + }); + } + + /// + /// Adds a YAML configuration source to . + /// + /// The to add to. + /// Configures the source. + /// The . + public static IConfigurationBuilder AddYamlFile(this IConfigurationBuilder builder, Action configureSource) + => builder.Add(configureSource); + } + + /// + /// Represents a YAML file as an . + /// + public class YamlConfigurationSource : FileConfigurationSource + { + /// + /// Builds the for this source. + /// + /// The . + /// A + public override IConfigurationProvider Build(IConfigurationBuilder builder) + { + EnsureDefaults(builder); + return new YamlConfigurationProvider(this); + } + } + + /// + /// A YAML file based . + /// + public class YamlConfigurationProvider : FileConfigurationProvider + { + /// + /// Initializes a new instance with the specified source. + /// + /// The source settings. + public YamlConfigurationProvider(YamlConfigurationSource source) : base(source) { } + + private string[] NullValues { get; } = new[] { "~", "null", "" }; + + /// + /// Loads the YAML data from a stream. + /// + /// The stream to read. + public override void Load(Stream stream) + { + try + { + using var reader = new StreamReader(stream); + + var yaml = new YamlStream(); + yaml.Load(reader); + + var rootNode = (YamlMappingNode)yaml.Documents[0].RootNode; + + Traverse(rootNode); + } + catch (YamlException e) + { + throw new FormatException("Could not parse the YAML file.", e); + } + } + + private void Traverse(YamlNode root, string path = null) + { + static string Clean(string str) => str?.Replace("_", string.Empty).Replace("-", string.Empty); + + if (root is YamlScalarNode scalar) + { + if (Data.ContainsKey(Clean(path))) + { + throw new FormatException($"A duplicate key '{Clean(path)}' was found."); + } + + Data[Clean(path)] = NullValues.Contains(scalar.Value.ToLower()) ? null : scalar.Value; + } + else if (root is YamlMappingNode map) + { + foreach (var node in map.Children) + { + var key = Clean(((YamlScalarNode)node.Key).Value); + Traverse(node.Value, path == null ? key : ConfigurationPath.Combine(path, key)); + } + } + else if (root is YamlSequenceNode sequence) + { + for (int i = 0; i < sequence.Children.Count(); i++) + { + Traverse(sequence.Children[i], ConfigurationPath.Combine(path, i.ToString())); + } + } + } + } +} -- cgit v1.2.3 From 8d7a5d770f8a88784d89c7f2178313e7ba6022a6 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Thu, 21 Jan 2021 23:04:12 -0600 Subject: move and rename Role --- src/slskd/Security/Role.cs | 9 +++++++++ 1 file changed, 9 insertions(+) create mode 100644 src/slskd/Security/Role.cs (limited to 'src') diff --git a/src/slskd/Security/Role.cs b/src/slskd/Security/Role.cs new file mode 100644 index 00000000..91c9e83c --- /dev/null +++ b/src/slskd/Security/Role.cs @@ -0,0 +1,9 @@ +namespace slskd +{ + public enum Role + { + ReadOnly = 0, + User = 1, + Administrator = 2 + } +} -- cgit v1.2.3 From 25169560d44344e970f14fec24c4f68413e64187 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Thu, 21 Jan 2021 23:04:25 -0600 Subject: flesh out config --- src/slskd/config.yml | 46 ++++++++++++++++++++++++++++++++++++++++------ 1 file changed, 40 insertions(+), 6 deletions(-) (limited to 'src') diff --git a/src/slskd/config.yml b/src/slskd/config.yml index 2a6642f6..a7840141 100644 --- a/src/slskd/config.yml +++ b/src/slskd/config.yml @@ -1,7 +1,41 @@ slskd: - debug: false - noLogo: false - noAuth: false - instanceName: FromYAML - prometheus: true - loki1: http://192.168.1.60:3101 \ No newline at end of file + options: + debug: false + no_logo: false + no_auth: false + instance_name: FromYAML + prometheus: true + swagger: true + logger: + loki: http://192.168.1.60:3101 + web: + url_base: / + content_path: wwwroot + jwt: + ttl: 604800000 + key: ~ +soulseek: + username: ~ + password: ~ + listen_port: 50000 + distributed_network: + enabled: true + child_limit: 10 + connection: + timeout: + connect: 5000 + inactivity: 15000 + buffer: + read: 16384 + write: 16384 +authentication: + users: + - name: admin + password: admin + role: Administrator + - name: user + password: user + role: User + api_keys: + - key: 1234567890 + role: ReadOnly \ No newline at end of file -- cgit v1.2.3 From 3f8af2e3ba6f9f1df35f5c0d213c1609b28cfb95 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Thu, 21 Jan 2021 23:05:11 -0600 Subject: move a bunch of settings to config --- src/slskd/Configuration.cs | 153 --------------------------------------------- src/slskd/Roles.cs | 9 --- src/slskd/Startup.cs | 141 +++++++++++++++++------------------------ src/slskd/slskd.csproj | 1 - 4 files changed, 57 insertions(+), 247 deletions(-) delete mode 100644 src/slskd/Configuration.cs delete mode 100644 src/slskd/Roles.cs (limited to 'src') diff --git a/src/slskd/Configuration.cs b/src/slskd/Configuration.cs deleted file mode 100644 index 8f11bd07..00000000 --- a/src/slskd/Configuration.cs +++ /dev/null @@ -1,153 +0,0 @@ -namespace slskd -{ - using Microsoft.Extensions.Configuration; - using System; - using System.Collections; - using System.Collections.Generic; - using System.Diagnostics; - using System.Globalization; - using System.Linq; - using System.Reflection; - using System.Runtime.CompilerServices; - - public class ConfigurationAttribute : Attribute - { - public ConfigurationAttribute(string key) - { - Key = key; - } - - public string Key { get; set; } - } - - public static class Configuration - { - public static void Populate(this IConfiguration configuration, [CallerMemberName] string caller = default(string)) - { - var type = GetCallingType(caller); - var targetProperties = GetTargetProperties(type); - - foreach (var property in targetProperties) - { - var propertyType = property.Value.PropertyType; - - string value = configuration.GetValue(property.Key); - Console.WriteLine($"key {property.Key} value {value}"); - - if (string.IsNullOrEmpty(value)) - { - Console.WriteLine("skip"); - continue; - } - - object convertedValue; - - if (propertyType == typeof(bool)) - { - convertedValue = value?.Equals("true", StringComparison.InvariantCultureIgnoreCase) ?? false; - } - else if (propertyType.IsArray || (propertyType.IsGenericType && propertyType.GetGenericTypeDefinition() == typeof(List<>))) - { - Type valueType; - - if (propertyType.IsArray) - { - valueType = propertyType.GetElementType(); - } - else - { - valueType = propertyType.GetGenericArguments()[0]; - } - - // create a list to store converted values - Type valueListType = typeof(List<>).MakeGenericType(valueType); - var valueList = (IList)Activator.CreateInstance(valueListType); - - // populate the list - foreach (object v in value.Split(',').Select(s => s.Trim())) - { - valueList.Add(ChangeType(v, property.Key, valueType)); - } - - if (propertyType.IsArray) - { - var valueArray = Array.CreateInstance(propertyType.GetElementType(), valueList.Count); - - for (int i = 0; i < valueArray.Length; i++) - { - valueArray.SetValue(valueList[i], i); - } - - convertedValue = valueArray; - } - else - { - convertedValue = valueList; - } - } - else - { - convertedValue = ChangeType(value, property.Key, property.Value.PropertyType); - } - - property.Value.SetValue(null, convertedValue); - } - } - - private static Type GetCallingType(string caller) - { - var callingMethod = new StackTrace().GetFrames() - .Select(f => f.GetMethod()) - .FirstOrDefault(m => m.Name == caller); - - if (callingMethod == default(MethodBase)) - { - throw new InvalidOperationException($"Unable to determine the containing type of the calling method '{caller}'. Explicitly specify the originating Type."); - } - - return callingMethod.DeclaringType; - } - - private static Dictionary GetTargetProperties(Type type) - { - Dictionary properties = new Dictionary(); - - foreach (PropertyInfo property in type.GetProperties(BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Static)) - { - // attempt to fetch the ArgumentAttribute of the property - CustomAttributeData attribute = property.CustomAttributes.FirstOrDefault(a => a.AttributeType.Name == typeof(ConfigurationAttribute).Name); - - // if found, extract the Name property and add it to the dictionary - if (attribute != default(CustomAttributeData)) - { - string name = (string)attribute.ConstructorArguments[0].Value; - - if (!properties.ContainsKey(name)) - { - properties.Add(name, property); - } - } - } - - return properties; - } - - private static object ChangeType(object value, string name, Type type) - { - try - { - if (type.IsEnum) - { - return Enum.Parse(type, (string)value, true); - } - - return Convert.ChangeType(value, type, CultureInfo.InvariantCulture); - } - catch (Exception ex) when (ex is InvalidCastException || ex is FormatException || ex is OverflowException || ex is ArgumentNullException) - { - string message = $"Failed to convert value '{value}' to target type {type}"; - throw new ArgumentException(message, name, ex); - } - } - } -} diff --git a/src/slskd/Roles.cs b/src/slskd/Roles.cs deleted file mode 100644 index 5ddee6d8..00000000 --- a/src/slskd/Roles.cs +++ /dev/null @@ -1,9 +0,0 @@ -namespace slskd -{ - public enum Roles - { - ReadOnly = 0, - User = 1, - Administrator = 2 - } -} diff --git a/src/slskd/Startup.cs b/src/slskd/Startup.cs index cfa59550..a29e1ffa 100644 --- a/src/slskd/Startup.cs +++ b/src/slskd/Startup.cs @@ -29,33 +29,19 @@ using System.Collections.Concurrent; using Serilog; using Serilog.Events; - using Microsoft.Extensions.Logging; using Prometheus; using Prometheus.SystemMetrics; using Microsoft.Extensions.Options; public class Startup { - internal static string Username { get; set; } - internal static string Password { get; set; } - internal static string BasePath { get; set; } - internal static string WebRoot { get; set; } - internal static int ListenPort { get; set; } internal static string OutputDirectory { get; set; } internal static string SharedDirectory { get; set; } internal static long SharedCacheTTL { get; set; } - internal static bool EnableDistributedNetwork { get; set; } - internal static int DistributedChildLimit { get; set; } internal static DiagnosticLevel DiagnosticLevel { get; set; } - internal static int ConnectTimeout { get; set; } - internal static int InactivityTimeout { get; set; } - internal static int SecurityTokenTTL { get; set; } internal static int RoomMessageLimit { get; set; } - internal static int ReadBufferSize { get; set; } - internal static int WriteBufferSize { get; set; } internal static string XmlDocFile { get; set; } - internal static SymmetricSecurityKey JwtSigningKey { get; set; } private SoulseekClient Client { get; set; } private object ConsoleSyncRoot { get; } = new object(); @@ -65,36 +51,15 @@ { Configuration = configuration; - Username = Configuration.GetValue("USERNAME"); - Password = Configuration.GetValue("PASSWORD"); - BasePath = Configuration.GetValue("BASE_PATH"); - WebRoot = Configuration.GetValue("WEB_ROOT", Path.Combine(Path.GetDirectoryName(new Uri(AppContext.BaseDirectory).AbsolutePath), "wwwroot")); - ListenPort = Configuration.GetValue("LISTEN_PORT", 50000); OutputDirectory = Configuration.GetValue("OUTPUT_DIR"); SharedDirectory = Configuration.GetValue("SHARED_DIR"); SharedCacheTTL = Configuration.GetValue("SHARED_CACHE_TTL", 3600000); // 1 hour - EnableDistributedNetwork = Configuration.GetValue("ENABLE_DNET", true); - DistributedChildLimit = Configuration.GetValue("DNET_CHILD_LIMIT", 10); DiagnosticLevel = Configuration.GetValue("DIAGNOSTIC", DiagnosticLevel.Info); - ConnectTimeout = Configuration.GetValue("CONNECT_TIMEOUT", 5000); - InactivityTimeout = Configuration.GetValue("INACTIVITY_TIMEOUT", 15000); - SecurityTokenTTL = Configuration.GetValue("SECURITY_TOKEN_TTL", 604800000); // 7 days RoomMessageLimit = Configuration.GetValue("ROOM_MESSAGE_LIMIT", 250); - ReadBufferSize = Configuration.GetValue("READ_BUFFER_SIZE", 16384); - WriteBufferSize = Configuration.GetValue("WRITE_BUFFER_SIZE", 16384); XmlDocFile = Configuration.GetValue("XML_DOC_FILE", Path.Combine(AppContext.BaseDirectory, typeof(Startup).GetTypeInfo().Assembly.GetName().Name + ".xml")); - JwtSigningKey = new SymmetricSecurityKey(PBKDF2.GetKey(Password)); - + SharedFileCache = new SharedFileCache(SharedDirectory, SharedCacheTTL); - - BasePath ??= "/"; - BasePath = BasePath.StartsWith("/") ? BasePath : $"/{BasePath}"; - - var logger = Log.ForContext(); - - logger.Information("Serving static content from {WebRoot}", WebRoot); - logger.Information("Using base request path {BasePath}", BasePath); } public IConfiguration Configuration { get; } @@ -102,24 +67,20 @@ public void ConfigureServices(IServiceCollection services) { - //services.AddOptions() - // .Bind(Configuration.GetSection("soulseek")); - - //services.PostConfigure>(slskd => - //{ - // Console.WriteLine($"config updated"); - // Console.WriteLine(JsonSerializer.Serialize(slskd)); - //}); - - //services.AddOptions>().Bind(Configuration.GetSection("sparse")); - //services.PostConfigure>(s => Console.WriteLine(JsonSerializer.Serialize(s))); + services.AddOptions() + .Bind(Configuration.GetSection("soulseek")); - //services.AddOptions>().Bind(Configuration.GetSection("users")); + services.AddOptions() + .Bind(Configuration.GetSection("authentication")); services.AddCors(options => options.AddPolicy("AllowAll", builder => builder.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader())); if (!Program.DisableAuthentication) { + var jwtSigningKey = new SymmetricSecurityKey(PBKDF2.GetKey(Program.JwtKey)); + + services.AddSingleton(jwtSigningKey); + services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme) .AddJwtBearer(options => { @@ -132,7 +93,7 @@ ValidIssuer = "slskd", ValidateIssuer = true, ValidateAudience = false, - IssuerSigningKey = JwtSigningKey, + IssuerSigningKey = jwtSigningKey, ValidateIssuerSigningKey = true, }; }); @@ -142,7 +103,7 @@ services.AddAuthentication(PassthroughAuthentication.AuthenticationScheme) .AddScheme(PassthroughAuthentication.AuthenticationScheme, options => { - options.Username = Username; + options.Username = "n/a"; }); } @@ -194,31 +155,29 @@ public void Configure( IApplicationBuilder app, IWebHostEnvironment env, - ILoggerFactory loggerFactory, IApiVersionDescriptionProvider provider, ITransferTracker tracker, IBrowseTracker browseTracker, IConversationTracker conversationTracker, - //IOptionsMonitor optionsAccessor, - //IOptionsMonitor> users, - //IOptionsMonitor> sparse, + IOptionsMonitor soulseekOptions, + IOptionsMonitor authenticationOptions, IRoomTracker roomTracker) { + var logger = Log.ForContext(); + if (!env.IsDevelopment()) { app.UseHsts(); } - //optionsAccessor.OnChange(options => - //{ - // Console.WriteLine(JsonSerializer.Serialize(optionsAccessor)); - //}); + Console.WriteLine(JsonSerializer.Serialize(authenticationOptions.CurrentValue)); - //sparse.OnChange(v => Console.WriteLine(JsonSerializer.Serialize(v))); - //users.OnChange(users => Console.WriteLine(JsonSerializer.Serialize(users))); + authenticationOptions.OnChange(o => Console.WriteLine(JsonSerializer.Serialize(o))); app.UseCors("AllowAll"); - app.UsePathBase(BasePath); + + app.UsePathBase(Program.UrlBase); + logger.Information("Using base url {UrlBase}", Program.UrlBase); // remove any errant double forward slashes which may have been introduced // by a reverse proxy or having the base path removed @@ -234,15 +193,25 @@ await next(); }); - var fileServerOptions = new FileServerOptions + FileServerOptions fileServerOptions = default; + + if (!System.IO.Directory.Exists(Program.ContentPath)) { - FileProvider = new PhysicalFileProvider(WebRoot), - RequestPath = "", - EnableDirectoryBrowsing = false, - EnableDefaultFiles = true - }; + logger.Warning($"Static content disabled; cannot find content path '{Program.ContentPath}'"); + } + else + { + fileServerOptions = new FileServerOptions + { + FileProvider = new PhysicalFileProvider(Program.ContentPath), + RequestPath = "", + EnableDirectoryBrowsing = false, + EnableDefaultFiles = true + }; - app.UseFileServer(fileServerOptions); + app.UseFileServer(fileServerOptions); + logger.Information("Serving static content from {ContentPath}", Program.ContentPath); + } app.UseSerilogRequestLogging(); @@ -287,27 +256,28 @@ // finally, hit the fileserver again. if the path was modified to return the index above, the index document will be returned // otherwise it will throw a final 404 back to the client. - app.UseFileServer(fileServerOptions); + if (System.IO.Directory.Exists(Program.ContentPath)) + { + app.UseFileServer(fileServerOptions); + } // --------------------------------------------------------------------------------------------------------------------------------------------- // begin SoulseekClient implementation // --------------------------------------------------------------------------------------------------------------------------------------------- - var logger = loggerFactory.CreateLogger(); - var connectionOptions = new ConnectionOptions( - readBufferSize: ReadBufferSize, - writeBufferSize: WriteBufferSize, - connectTimeout: ConnectTimeout, - inactivityTimeout: InactivityTimeout); + readBufferSize: soulseekOptions.CurrentValue.Connection.Buffer.Read, + writeBufferSize: soulseekOptions.CurrentValue.Connection.Buffer.Write, + connectTimeout: soulseekOptions.CurrentValue.Connection.Timeout.Connect, + inactivityTimeout: soulseekOptions.CurrentValue.Connection.Timeout.Inactivity); // create options for the client. // see the implementation of Func<> and Action<> options for detailed info. var clientOptions = new SoulseekClientOptions( - listenPort: ListenPort, + listenPort: soulseekOptions.CurrentValue.ListenPort, userEndPointCache: new UserEndPointCache(), - distributedChildLimit: DistributedChildLimit, - enableDistributedNetwork: EnableDistributedNetwork, + distributedChildLimit: soulseekOptions.CurrentValue.DistributedNetwork.ChildLimit, + enableDistributedNetwork: soulseekOptions.CurrentValue.DistributedNetwork.Enabled, minimumDiagnosticLevel: DiagnosticLevel, autoAcknowledgePrivateMessages: false, acceptPrivateRoomInvitations: true, @@ -320,6 +290,9 @@ enqueueDownloadAction: (username, endpoint, filename) => EnqueueDownloadAction(username, endpoint, filename, tracker), searchResponseResolver: SearchResponseResolver); + var username = soulseekOptions.CurrentValue.Username ?? Program.Username; + var password = soulseekOptions.CurrentValue.Password ?? Program.Password; + Client = new SoulseekClient(options: clientOptions); // bind the DiagnosticGenerated event so we can trap and display diagnostic messages. this is optional, and if the event @@ -396,7 +369,7 @@ Client.RoomJoined += (e, args) => { - if (args.Username != Username) // this will fire when we join a room; track that through the join operation. + if (args.Username != username) // this will fire when we join a room; track that through the join operation. { roomTracker.TryAddUser(args.RoomName, args.UserData); } @@ -409,15 +382,15 @@ Client.Disconnected += async (e, args) => { - logger.LogWarning("Disconnected from Soulseek server: {Message}", args.Message, args.Exception); + logger.Warning("Disconnected from Soulseek server: {Message}", args.Message, args.Exception); // don't reconnect if the disconnecting Exception is either of these types. // if KickedFromServerException, another client was most likely signed in, and retrying will cause a connect loop. // if ObjectDisposedException, the client is shutting down. if (!(args.Exception is KickedFromServerException || args.Exception is ObjectDisposedException)) { - logger.LogWarning("Attepting to reconnect..."); - await Client.ConnectAsync(Username, Password); + logger.Warning("Attepting to reconnect..."); + await Client.ConnectAsync(username, password); } }; @@ -426,7 +399,7 @@ // await Client.ConnectAsync(Username, Password); //}).GetAwaiter().GetResult(); - logger.LogInformation("Connected and logged in as {Username}", Username); + logger.Information("Connected and logged in as {Username}", username); } /// @@ -559,7 +532,7 @@ Console.WriteLine($"[SENDING SEARCH RESULTS]: {results.Count()} records to {username} for query {query.SearchText}"); return Task.FromResult(new SearchResponse( - Username, + username, token, freeUploadSlots: 1, uploadSpeed: 0, diff --git a/src/slskd/slskd.csproj b/src/slskd/slskd.csproj index 4e1d9994..285a18c7 100644 --- a/src/slskd/slskd.csproj +++ b/src/slskd/slskd.csproj @@ -51,7 +51,6 @@ - -- cgit v1.2.3 From 7ad098358e23e7de7e6d11f9c4feb122e013d2c8 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Thu, 21 Jan 2021 23:05:26 -0600 Subject: implement options --- src/slskd/Options.cs | 70 +++++++++++++++++++++++++++++++++++++++------------- 1 file changed, 53 insertions(+), 17 deletions(-) (limited to 'src') diff --git a/src/slskd/Options.cs b/src/slskd/Options.cs index 0dbc9409..ef2759f5 100644 --- a/src/slskd/Options.cs +++ b/src/slskd/Options.cs @@ -1,24 +1,60 @@ -using System; -using System.Collections.Generic; -using System.ComponentModel.DataAnnotations; -using System.Linq; -using System.Threading.Tasks; - -namespace slskd +namespace slskd { - public class Options + using System.Collections.Generic; + using System.Linq; + + public class RuntimeOptions { - public slskdOptions slskd { get; set; } + public class Soulseek + { + public string Username { get; set; } = Program.Username; + public string Password { get; set; } = Program.Password; + public int ListenPort { get; set; } = 50000; + public DistributedNetworkOptions DistributedNetwork { get; set; } + public ConnectionOptions Connection { get; set; } + + public class DistributedNetworkOptions + { + public bool Enabled { get; set; } = true; + public int ChildLimit { get; set; } = 10; + } + + public class ConnectionOptions + { + public TimeoutOptions Timeout { get; set; } + public BufferOptions Buffer { get; set; } - public class slskdOptions + public class TimeoutOptions + { + public int Connect { get; set; } = 5000; + public int Inactivity { get; set; } = 15000; + } + + public class BufferOptions + { + public int Read { get; set; } = 16384; + public int Write { get; set; } = 16384; + } + } + } + + public class Authentication { - public bool? Debug { get; set; } - public bool? NoLogo { get; set; } - public bool? NoAuth { get; set; } - public string InstanceName { get; set; } - public bool? Prometheus { get; set; } - public bool? Swagger { get; set; } - public string Loki { get; set; } + public IEnumerable Users { get; set; } + public IEnumerable ApiKeys { get; set; } + + public class User + { + public string Name { get; set; } + public string Password { get; set; } + public Role Role { get; set; } + } + + public class ApiKey + { + public string Key { get; set; } + public Role Role { get; set; } + } } } } -- cgit v1.2.3 From 0f1a0138eee284122e6fda5544437bf80f8e69d9 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Thu, 21 Jan 2021 23:06:08 -0600 Subject: tweak config paths, add more static options --- src/slskd/Program.cs | 56 +++++++++++++++++++++++++++++++++++++++------------- 1 file changed, 42 insertions(+), 14 deletions(-) (limited to 'src') diff --git a/src/slskd/Program.cs b/src/slskd/Program.cs index af181cfe..06f0ff02 100644 --- a/src/slskd/Program.cs +++ b/src/slskd/Program.cs @@ -14,7 +14,6 @@ using System.Reflection; using Utility.CommandLine; using Utility.EnvironmentVariables; - using Utility.Extensions.Configuration.Yaml; public class Program { @@ -25,40 +24,70 @@ public static bool ShowVersion { get; private set; } [EnvironmentVariable("SLSKD_DEBUG")] - [Configuration("slskd:debug")] + [Configuration("slskd:options:debug")] [Argument('d', "debug", "run in debug mode")] public static bool Debug { get; private set; } [EnvironmentVariable("SLSKD_NO_LOGO")] - [Configuration("slskd:noLogo")] + [Configuration("slskd:options:no_logo")] [Argument('n', "no-logo", "suppress logo on startup")] public static bool DisableLogo { get; private set; } [EnvironmentVariable("SLSKD_NO_AUTH")] - [Configuration("slskd:noAuth")] + [Configuration("slskd:options:no_auth")] [Argument('x', "no-auth", "disable authentication for web requests")] public static bool DisableAuthentication { get; private set; } [EnvironmentVariable("SLSKD_INSTANCE_NAME")] - [Configuration("slskd:instanceName")] + [Configuration("slskd:options:instance_name")] [Argument('i', "instance-name", "optional; a unique name for this instance")] public static string InstanceName { get; private set; } = "default"; [EnvironmentVariable("SLSKD_PROMETHEUS")] - [Configuration("slskd:prometheus")] - [Argument('p', "prometheus", "enable collection and publish of prometheus metrics")] + [Configuration("slskd:options:prometheus")] + [Argument('m', "prometheus", "enable collection and publish of prometheus metrics")] public static bool EnablePrometheus { get; private set; } [EnvironmentVariable("SLSKD_SWAGGER")] - [Configuration("slskd:swagger")] + [Configuration("slskd:options:swagger")] [Argument('s', "swagger", "enable swagger documentation")] public static bool EnableSwagger { get; private set; } [EnvironmentVariable("SLSKD_LOKI")] - [Configuration("slskd:loki")] - [Argument(default, "loki", "the url to a Grafana Loki instance to which to log")] + [Configuration("slskd:logger:loki")] + [Argument(default, "loki", "optional; the url to a Grafana Loki instance to which to log")] public static string LokiUrl { get; private set; } + [EnvironmentVariable("SLSKD_URL_BASE")] + [Configuration("slskd:web:url_base")] + [Argument('b', "url-base", "base url for web requests")] + public static string UrlBase { get; private set; } = "/"; + + [EnvironmentVariable("SLSKD_CONTENT_PATH")] + [Configuration("slskd:web:content_path")] + [Argument('c', "content-path", "path to static web content")] + public static string ContentPath { get; private set; } = Path.Combine(Path.GetDirectoryName(new Uri(AppContext.BaseDirectory).AbsolutePath), "wwwroot"); + + [EnvironmentVariable("SLSKD_JWT_KEY")] + [Configuration("slskd:web:jwt:key")] + [Argument(default, "jwt-key", "optional; the key with which to sign JWTs")] + public static string JwtKey { get; private set; } = Guid.NewGuid().ToString(); + + [EnvironmentVariable("SLSKD_JWT_TTL")] + [Configuration("slskd:web:jwt:ttl")] + [Argument(default, "jwt-ttl", "optional; the TTL for JWTs")] + public static int JwtTTL { get; private set; } = 604800000; + + [EnvironmentVariable("SLSKD_USERNAME")] + [Configuration("soulseek:username")] + [Argument('u', "username", "the username for the Soulseek network")] + public static string Username { get; private set; } + + [EnvironmentVariable("SLSKD_PASSWORD")] + [Configuration("soulseek:password")] + [Argument('p', "password", "the password for the Soulseek network")] + public static string Password { get; private set; } + public static bool EnableLoki { get; private set; } public static string Version { get; private set; } public static Guid InvocationId { get; private set; } @@ -103,8 +132,6 @@ return; } - Console.WriteLine(LokiUrl); - Version = ComputeVersion(); if (ShowVersion) @@ -128,14 +155,15 @@ ProcessId = Environment.ProcessId; Debug = Debugger.IsAttached || Debug; EnableLoki = !string.IsNullOrEmpty(LokiUrl); - - ConfigureLogger(); + UrlBase = UrlBase.StartsWith("/") ? UrlBase : "/" + UrlBase; + ContentPath = Path.GetFullPath(ContentPath); if (!DisableLogo) { PrintLogo(Version); } + ConfigureLogger(); var logger = Log.ForContext(); logger.Information("Version: {Version}", Version); -- cgit v1.2.3 From 0210ab449f7546a90982a8cb28403f3d6af02230 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Thu, 21 Jan 2021 23:07:53 -0600 Subject: refactor login to use configured users --- src/slskd/Controllers/SessionController.cs | 39 +++++++++++++++++++++++------- 1 file changed, 30 insertions(+), 9 deletions(-) (limited to 'src') diff --git a/src/slskd/Controllers/SessionController.cs b/src/slskd/Controllers/SessionController.cs index 5c162708..df523b75 100644 --- a/src/slskd/Controllers/SessionController.cs +++ b/src/slskd/Controllers/SessionController.cs @@ -8,6 +8,8 @@ using System.IdentityModel.Tokens.Jwt; using System.Security.Claims; using slskd.DTO; + using Microsoft.Extensions.Options; + using System.Linq; /// /// Session @@ -19,8 +21,18 @@ [Consumes("application/json")] public class SessionController : ControllerBase { - public SessionController() + private IOptionsSnapshot SoulseekOptions { get; set; } + private IOptionsSnapshot AuthenticationOptions { get; set; } + private SymmetricSecurityKey JwtSigningKey { get; set; } + + public SessionController( + IOptionsSnapshot soulseekOptions, + IOptionsSnapshot authenticationOptions, + SymmetricSecurityKey jwtSigningKey) { + SoulseekOptions = soulseekOptions; + AuthenticationOptions = authenticationOptions; + JwtSigningKey = jwtSigningKey; } /// @@ -83,29 +95,38 @@ return BadRequest("Username and/or Password missing or invalid"); } - if (login.Username == Startup.Username && login.Password == Startup.Password) + var user = AuthenticationOptions.Value.Users + .Where(u => u.Name == login.Username) + .FirstOrDefault(); + + if (user == default) + { + return Unauthorized(); + } + + if (login.Password == user.Password) { - return Ok(new TokenResponse(GetJwtSecurityToken())); + return Ok(new TokenResponse(GetJwtSecurityToken(user.Name, user.Role))); } return Unauthorized(); } - private JwtSecurityToken GetJwtSecurityToken() + private JwtSecurityToken GetJwtSecurityToken(string username, Role role) { var issuedUtc = DateTime.UtcNow; - var expiresUtc = DateTime.UtcNow.AddMilliseconds(Startup.SecurityTokenTTL); + var expiresUtc = DateTime.UtcNow.AddMilliseconds(Program.JwtTTL); var claims = new List() { - new Claim(ClaimTypes.Name, Startup.Username), + new Claim(ClaimTypes.Name, username), new Claim(ClaimTypes.NameIdentifier, Guid.NewGuid().ToString()), - new Claim(ClaimTypes.Role, "User"), - new Claim("name", Startup.Username), + new Claim(ClaimTypes.Role, role.ToString()), + new Claim("name", username), new Claim("iat", ((DateTimeOffset)issuedUtc).ToUnixTimeSeconds().ToString()) }; - var credentials = new SigningCredentials(Startup.JwtSigningKey, SecurityAlgorithms.HmacSha256); + var credentials = new SigningCredentials(JwtSigningKey, SecurityAlgorithms.HmacSha256); var token = new JwtSecurityToken( issuer: "slskd", -- cgit v1.2.3 From fc9a1aacfb9c4e005fd482ba37394840865e9e61 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Fri, 22 Jan 2021 16:48:26 -0600 Subject: wip --- src/slskd/Common/Configuration.cs | 6 +- src/slskd/Common/Options/InstanceOptions.cs | 184 ++++++++++++++++ src/slskd/Common/Options/RuntimeOptions.cs | 59 ++++++ src/slskd/Common/YamlConfigurationSource.cs | 209 ------------------- src/slskd/Controllers/SessionController.cs | 6 +- src/slskd/Options.cs | 60 ------ src/slskd/Program.cs | 311 +++++++--------------------- src/slskd/Startup.cs | 54 +++-- src/slskd/slskd.csproj | 3 +- 9 files changed, 346 insertions(+), 546 deletions(-) create mode 100644 src/slskd/Common/Options/InstanceOptions.cs create mode 100644 src/slskd/Common/Options/RuntimeOptions.cs delete mode 100644 src/slskd/Common/YamlConfigurationSource.cs delete mode 100644 src/slskd/Options.cs (limited to 'src') diff --git a/src/slskd/Common/Configuration.cs b/src/slskd/Common/Configuration.cs index 621c150e..fca57299 100644 --- a/src/slskd/Common/Configuration.cs +++ b/src/slskd/Common/Configuration.cs @@ -22,9 +22,9 @@ public static class Configuration { - public static void Populate(this IConfiguration configuration, [CallerMemberName] string caller = default(string)) + public static void Populate(this IConfiguration configuration, Type targetType = null, [CallerMemberName] string caller = default(string)) { - var type = GetCallingType(caller); + var type = targetType ?? GetCallingType(caller); var targetProperties = GetTargetProperties(type); foreach (var property in targetProperties) @@ -32,11 +32,9 @@ var propertyType = property.Value.PropertyType; string value = configuration.GetValue(property.Key); - Console.WriteLine($"key {property.Key} value {value}"); if (string.IsNullOrEmpty(value)) { - Console.WriteLine("skip"); continue; } diff --git a/src/slskd/Common/Options/InstanceOptions.cs b/src/slskd/Common/Options/InstanceOptions.cs new file mode 100644 index 00000000..09431956 --- /dev/null +++ b/src/slskd/Common/Options/InstanceOptions.cs @@ -0,0 +1,184 @@ +namespace slskd +{ + using Microsoft.Extensions.Configuration; + using System; + using System.IO; + using System.Linq; + using Utility.CommandLine; + using Utility.EnvironmentVariables; + using Utility.Extensions.Configuration.Yaml; + + public class InstanceOptions + { + [Argument('h', "help", "print usage")] + public static bool ShowHelp { get; private set; } + + [Argument('v', "version", "display version information")] + public static bool ShowVersion { get; private set; } + + [EnvironmentVariable("SLSKD_DEBUG")] + [Configuration("slskd:options:debug")] + [Argument('d', "debug", "run in debug mode")] + public static bool Debug { get; private set; } + + [EnvironmentVariable("SLSKD_NO_LOGO")] + [Configuration("slskd:options:no_logo")] + [Argument('n', "no-logo", "suppress logo on startup")] + public static bool DisableLogo { get; private set; } + + [EnvironmentVariable("SLSKD_NO_AUTH")] + [Configuration("slskd:options:no_auth")] + [Argument('x', "no-auth", "disable authentication for web requests")] + public static bool DisableAuthentication { get; private set; } + + [EnvironmentVariable("SLSKD_INSTANCE_NAME")] + [Configuration("slskd:options:instance_name")] + [Argument('i', "instance-name", "optional; a unique name for this instance")] + public static string InstanceName { get; private set; } = "default"; + + [EnvironmentVariable("SLSKD_PROMETHEUS")] + [Configuration("slskd:options:prometheus")] + [Argument('m', "prometheus", "enable collection and publish of prometheus metrics")] + public static bool EnablePrometheus { get; private set; } + + [EnvironmentVariable("SLSKD_SWAGGER")] + [Configuration("slskd:options:swagger")] + [Argument('s', "swagger", "enable swagger documentation")] + public static bool EnableSwagger { get; private set; } + + [EnvironmentVariable("SLSKD_LOKI")] + [Configuration("slskd:logger:loki")] + [Argument('l', "loki", "optional; the url to a Grafana Loki instance to which to log")] + public static string LokiUrl { get; private set; } + + [EnvironmentVariable("SLSKD_URL_BASE")] + [Configuration("slskd:web:url_base")] + [Argument('b', "url-base", "base url for web requests")] + public static string UrlBase { get; private set; } = "/"; + + [EnvironmentVariable("SLSKD_CONTENT_PATH")] + [Configuration("slskd:web:content_path")] + [Argument('c', "content-path", "path to static web content")] + public static string ContentPath { get; private set; } = Path.Combine(Path.GetDirectoryName(new Uri(AppContext.BaseDirectory).AbsolutePath), "wwwroot"); + + [EnvironmentVariable("SLSKD_JWT_KEY")] + [Configuration("slskd:web:jwt:key")] + [Argument('k', "jwt-key", "optional; the key with which to sign JWTs")] + public static string JwtKey { get; private set; } = Guid.NewGuid().ToString(); + + [EnvironmentVariable("SLSKD_JWT_TTL")] + [Configuration("slskd:web:jwt:ttl")] + [Argument('t', "jwt-ttl", "optional; the TTL for JWTs")] + public static int JwtTTL { get; private set; } = 604800000; + + [EnvironmentVariable("SLSKD_USERNAME")] + [Configuration("soulseek:username")] + [Argument('u', "username", "the username for the Soulseek network")] + public static string Username { get; private set; } + + [EnvironmentVariable("SLSKD_PASSWORD")] + [Configuration("soulseek:password")] + [Argument('p', "password", "the password for the Soulseek network")] + public static string Password { get; private set; } + + public static bool EnableLoki { get; private set; } + + public static void Populate(string configurationFile = null, bool argumentsOnly = false) + { + if (!argumentsOnly) + { + try + { + EnvironmentVariables.Populate(typeof(InstanceOptions)); + } + catch (Exception ex) + { + Console.WriteLine($"Error parsing environment variables: {ex.Message}"); + return; + } + + try + { + var config = new ConfigurationBuilder() + .SetBasePath(Directory.GetCurrentDirectory()) + .AddYamlFile(configurationFile, optional: true, reloadOnChange: false) + .Build(); + + Console.WriteLine(config.GetDebugView()); + + config.Populate(typeof(InstanceOptions)); + } + catch (Exception ex) + { + Console.WriteLine($"Error parsing configuration file '{configurationFile}': {ex.Message}"); + return; + } + } + + try + { + Arguments.Populate(typeof(InstanceOptions), clearExistingValues: false); + } + catch (Exception ex) + { + Console.WriteLine($"Error parsing command line input: {ex.Message}"); + return; + } + + EnableLoki = !string.IsNullOrEmpty(LokiUrl); + UrlBase = UrlBase.StartsWith("/") ? UrlBase : "/" + UrlBase; + ContentPath = Path.GetFullPath(ContentPath); + } + + public static void PrintHelp() + { + PrintArguments(); + } + + public static void PrintArguments() + { + static string GetLongName(ArgumentInfo info) + => info.Property.PropertyType == typeof(bool) ? info.LongName : $"{info.LongName} <{info.Property.PropertyType.Name.ToLowerInvariant()}>"; + + static string GetShortName(ArgumentInfo info) + => info.ShortName > 0 ? $"-{info.ShortName}|" : " "; + + var arguments = Arguments.GetArgumentInfo(typeof(InstanceOptions)); + var longestName = arguments.Select(a => GetLongName(a)).Max(n => n.Length); + + Console.WriteLine("\nusage: slskd [arguments]\n"); + Console.WriteLine("arguments:\n"); + foreach (var info in arguments) + { + var envar = info.Property.CustomAttributes + ?.Where(a => a.AttributeType == typeof(EnvironmentVariableAttribute)).FirstOrDefault() + ?.ConstructorArguments.FirstOrDefault().Value; + + var result = $" {GetShortName(info)}--{GetLongName(info).PadRight(longestName + 3)}{info.HelpText}"; + Console.WriteLine(result); + } + } + + public static void PrintEnvironmentVariables() + { + static string GetEnvironmentVariableName(ArgumentInfo info, bool includeType = false) + => info.Property.CustomAttributes + ?.Where(a => a.AttributeType == typeof(EnvironmentVariableAttribute)).FirstOrDefault() + ?.ConstructorArguments.FirstOrDefault().Value?.ToString() + (includeType ? $" <{info.Property.PropertyType.Name.ToLowerInvariant()}>" : ""); + + var arguments = Arguments.GetArgumentInfo(typeof(InstanceOptions)); + var longestName = arguments.Select(a => GetEnvironmentVariableName(a, includeType: true)).Where(a => a != null).Max(n => n.Length); + + Console.WriteLine("\nenvironment variables (arguments have precedence):\n"); + foreach (var info in arguments) + { + var envar = GetEnvironmentVariableName(info, includeType: false); + + if (string.IsNullOrEmpty(envar)) continue; + + var result = $" {GetEnvironmentVariableName(info, includeType: true).PadRight(longestName + 3)}{info.HelpText}"; + Console.WriteLine(result); + } + } + } +} diff --git a/src/slskd/Common/Options/RuntimeOptions.cs b/src/slskd/Common/Options/RuntimeOptions.cs new file mode 100644 index 00000000..d0c28e75 --- /dev/null +++ b/src/slskd/Common/Options/RuntimeOptions.cs @@ -0,0 +1,59 @@ +namespace slskd +{ + using System.Collections.Generic; + + public class RuntimeOptions + { + public class Soulseek + { + public string Username { get; set; } = InstanceOptions.Username; + public string Password { get; set; } = InstanceOptions.Password; + public int ListenPort { get; set; } = 50000; + public DistributedNetworkOptions DistributedNetwork { get; set; } + public ConnectionOptions Connection { get; set; } + + public class DistributedNetworkOptions + { + public bool Enabled { get; set; } = true; + public int ChildLimit { get; set; } = 10; + } + + public class ConnectionOptions + { + public TimeoutOptions Timeout { get; set; } + public BufferOptions Buffer { get; set; } + + public class TimeoutOptions + { + public int Connect { get; set; } = 5000; + public int Inactivity { get; set; } = 15000; + } + + public class BufferOptions + { + public int Read { get; set; } = 16384; + public int Write { get; set; } = 16384; + } + } + } + + public class Authentication + { + public IEnumerable Users { get; set; } + public IEnumerable ApiKeys { get; set; } + + public class User + { + public string Name { get; set; } + public string Password { get; set; } + public Role Role { get; set; } + } + + public class ApiKey + { + public string Key { get; set; } + public Role Role { get; set; } + } + } + } +} diff --git a/src/slskd/Common/YamlConfigurationSource.cs b/src/slskd/Common/YamlConfigurationSource.cs deleted file mode 100644 index 9dde3179..00000000 --- a/src/slskd/Common/YamlConfigurationSource.cs +++ /dev/null @@ -1,209 +0,0 @@ -/* - █▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀ ▀▀▀▀▀▀▀▀▀▀▀▀▀▀ ▀▀▀ ▀ ▀ ▀▀ - █ The MIT License (MIT) - █ - █ Copyright (c) 2021 JP Dillingham (jp@dillingham.ws) - █ - █ Permission is hereby granted, free of charge, to any person obtaining a copy - █ of this software and associated documentation files (the "Software"), to deal - █ in the Software without restriction, including without limitation the rights - █ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - █ copies of the Software, and to permit persons to whom the Software is - █ furnished to do so, subject to the following conditions: - █ - █ The above copyright notice and this permission notice shall be included in all - █ copies or substantial portions of the Software. - █ - █ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - █ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - █ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - █ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - █ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - █ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - █ SOFTWARE. - █ - ▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀ ▀▀ ▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀██ - ██ - ▀█▄ ██ ▄█▀ - ▀████▀ - ▀▀ */ - -namespace slskd -{ - using Microsoft.Extensions.Configuration; - using Microsoft.Extensions.FileProviders; - using System; - using System.IO; - using System.Linq; - using YamlDotNet.Core; - using YamlDotNet.RepresentationModel; - - /// - /// Extension methods for adding . - /// - public static class YamlConfigurationExtensions - { - /// - /// Adds the YAML configuration provider at to . - /// - /// The to add to. - /// Path relative to the base path stored in - /// of . - /// The . - public static IConfigurationBuilder AddYamlFile(this IConfigurationBuilder builder, string path) - { - return AddYamlFile(builder, provider: null, path: path, optional: false, reloadOnChange: false); - } - - /// - /// Adds the YAML configuration provider at to . - /// - /// The to add to. - /// Path relative to the base path stored in - /// of . - /// Whether the file is optional. - /// The . - public static IConfigurationBuilder AddYamlFile(this IConfigurationBuilder builder, string path, bool optional) - { - return AddYamlFile(builder, provider: null, path: path, optional: optional, reloadOnChange: false); - } - - /// - /// Adds the YAML configuration provider at to . - /// - /// The to add to. - /// Path relative to the base path stored in - /// of . - /// Whether the file is optional. - /// Whether the configuration should be reloaded if the file changes. - /// The . - public static IConfigurationBuilder AddYamlFile(this IConfigurationBuilder builder, string path, bool optional, bool reloadOnChange) - { - return AddYamlFile(builder, provider: null, path: path, optional: optional, reloadOnChange: reloadOnChange); - } - - /// - /// Adds a YAML configuration source to . - /// - /// The to add to. - /// The to use to access the file. - /// Path relative to the base path stored in - /// of . - /// Whether the file is optional. - /// Whether the configuration should be reloaded if the file changes. - /// The . - public static IConfigurationBuilder AddYamlFile(this IConfigurationBuilder builder, IFileProvider provider, string path, bool optional, bool reloadOnChange) - { - if (builder == null) - { - throw new ArgumentNullException(nameof(builder)); - } - if (string.IsNullOrEmpty(path)) - { - throw new ArgumentException("File path must be a non-empty string.", nameof(path)); - } - - return builder.AddYamlFile(s => - { - s.FileProvider = provider; - s.Path = path; - s.Optional = optional; - s.ReloadOnChange = reloadOnChange; - s.ResolveFileProvider(); - }); - } - - /// - /// Adds a YAML configuration source to . - /// - /// The to add to. - /// Configures the source. - /// The . - public static IConfigurationBuilder AddYamlFile(this IConfigurationBuilder builder, Action configureSource) - => builder.Add(configureSource); - } - - /// - /// Represents a YAML file as an . - /// - public class YamlConfigurationSource : FileConfigurationSource - { - /// - /// Builds the for this source. - /// - /// The . - /// A - public override IConfigurationProvider Build(IConfigurationBuilder builder) - { - EnsureDefaults(builder); - return new YamlConfigurationProvider(this); - } - } - - /// - /// A YAML file based . - /// - public class YamlConfigurationProvider : FileConfigurationProvider - { - /// - /// Initializes a new instance with the specified source. - /// - /// The source settings. - public YamlConfigurationProvider(YamlConfigurationSource source) : base(source) { } - - private string[] NullValues { get; } = new[] { "~", "null", "" }; - - /// - /// Loads the YAML data from a stream. - /// - /// The stream to read. - public override void Load(Stream stream) - { - try - { - using var reader = new StreamReader(stream); - - var yaml = new YamlStream(); - yaml.Load(reader); - - var rootNode = (YamlMappingNode)yaml.Documents[0].RootNode; - - Traverse(rootNode); - } - catch (YamlException e) - { - throw new FormatException("Could not parse the YAML file.", e); - } - } - - private void Traverse(YamlNode root, string path = null) - { - static string Clean(string str) => str?.Replace("_", string.Empty).Replace("-", string.Empty); - - if (root is YamlScalarNode scalar) - { - if (Data.ContainsKey(Clean(path))) - { - throw new FormatException($"A duplicate key '{Clean(path)}' was found."); - } - - Data[Clean(path)] = NullValues.Contains(scalar.Value.ToLower()) ? null : scalar.Value; - } - else if (root is YamlMappingNode map) - { - foreach (var node in map.Children) - { - var key = Clean(((YamlScalarNode)node.Key).Value); - Traverse(node.Value, path == null ? key : ConfigurationPath.Combine(path, key)); - } - } - else if (root is YamlSequenceNode sequence) - { - for (int i = 0; i < sequence.Children.Count(); i++) - { - Traverse(sequence.Children[i], ConfigurationPath.Combine(path, i.ToString())); - } - } - } - } -} diff --git a/src/slskd/Controllers/SessionController.cs b/src/slskd/Controllers/SessionController.cs index df523b75..d41a9295 100644 --- a/src/slskd/Controllers/SessionController.cs +++ b/src/slskd/Controllers/SessionController.cs @@ -46,7 +46,7 @@ [ProducesResponseType(typeof(bool), 200)] public IActionResult Enabled() { - return Ok(!Program.DisableAuthentication); + return Ok(!InstanceOptions.DisableAuthentication); } /// @@ -83,7 +83,7 @@ [ProducesResponseType(400)] [ProducesResponseType(401)] [ProducesResponseType(typeof(string), 500)] - public IActionResult Login([FromBody]LoginRequest login) + public IActionResult Login([FromBody] LoginRequest login) { if (login == default) { @@ -115,7 +115,7 @@ private JwtSecurityToken GetJwtSecurityToken(string username, Role role) { var issuedUtc = DateTime.UtcNow; - var expiresUtc = DateTime.UtcNow.AddMilliseconds(Program.JwtTTL); + var expiresUtc = DateTime.UtcNow.AddMilliseconds(InstanceOptions.JwtTTL); var claims = new List() { diff --git a/src/slskd/Options.cs b/src/slskd/Options.cs deleted file mode 100644 index ef2759f5..00000000 --- a/src/slskd/Options.cs +++ /dev/null @@ -1,60 +0,0 @@ -namespace slskd -{ - using System.Collections.Generic; - using System.Linq; - - public class RuntimeOptions - { - public class Soulseek - { - public string Username { get; set; } = Program.Username; - public string Password { get; set; } = Program.Password; - public int ListenPort { get; set; } = 50000; - public DistributedNetworkOptions DistributedNetwork { get; set; } - public ConnectionOptions Connection { get; set; } - - public class DistributedNetworkOptions - { - public bool Enabled { get; set; } = true; - public int ChildLimit { get; set; } = 10; - } - - public class ConnectionOptions - { - public TimeoutOptions Timeout { get; set; } - public BufferOptions Buffer { get; set; } - - public class TimeoutOptions - { - public int Connect { get; set; } = 5000; - public int Inactivity { get; set; } = 15000; - } - - public class BufferOptions - { - public int Read { get; set; } = 16384; - public int Write { get; set; } = 16384; - } - } - } - - public class Authentication - { - public IEnumerable Users { get; set; } - public IEnumerable ApiKeys { get; set; } - - public class User - { - public string Name { get; set; } - public string Password { get; set; } - public Role Role { get; set; } - } - - public class ApiKey - { - public string Key { get; set; } - public Role Role { get; set; } - } - } - } -} diff --git a/src/slskd/Program.cs b/src/slskd/Program.cs index 06f0ff02..e366e62f 100644 --- a/src/slskd/Program.cs +++ b/src/slskd/Program.cs @@ -9,86 +9,11 @@ using Serilog.Sinks.Grafana.Loki; using System; using System.Diagnostics; - using System.IO; - using System.Linq; using System.Reflection; - using Utility.CommandLine; - using Utility.EnvironmentVariables; + using Utility.Extensions.Configuration.Yaml; public class Program { - [Argument('h', "help", "print usage")] - public static bool ShowHelp { get; private set; } - - [Argument('v', "version", "display version information")] - public static bool ShowVersion { get; private set; } - - [EnvironmentVariable("SLSKD_DEBUG")] - [Configuration("slskd:options:debug")] - [Argument('d', "debug", "run in debug mode")] - public static bool Debug { get; private set; } - - [EnvironmentVariable("SLSKD_NO_LOGO")] - [Configuration("slskd:options:no_logo")] - [Argument('n', "no-logo", "suppress logo on startup")] - public static bool DisableLogo { get; private set; } - - [EnvironmentVariable("SLSKD_NO_AUTH")] - [Configuration("slskd:options:no_auth")] - [Argument('x', "no-auth", "disable authentication for web requests")] - public static bool DisableAuthentication { get; private set; } - - [EnvironmentVariable("SLSKD_INSTANCE_NAME")] - [Configuration("slskd:options:instance_name")] - [Argument('i', "instance-name", "optional; a unique name for this instance")] - public static string InstanceName { get; private set; } = "default"; - - [EnvironmentVariable("SLSKD_PROMETHEUS")] - [Configuration("slskd:options:prometheus")] - [Argument('m', "prometheus", "enable collection and publish of prometheus metrics")] - public static bool EnablePrometheus { get; private set; } - - [EnvironmentVariable("SLSKD_SWAGGER")] - [Configuration("slskd:options:swagger")] - [Argument('s', "swagger", "enable swagger documentation")] - public static bool EnableSwagger { get; private set; } - - [EnvironmentVariable("SLSKD_LOKI")] - [Configuration("slskd:logger:loki")] - [Argument(default, "loki", "optional; the url to a Grafana Loki instance to which to log")] - public static string LokiUrl { get; private set; } - - [EnvironmentVariable("SLSKD_URL_BASE")] - [Configuration("slskd:web:url_base")] - [Argument('b', "url-base", "base url for web requests")] - public static string UrlBase { get; private set; } = "/"; - - [EnvironmentVariable("SLSKD_CONTENT_PATH")] - [Configuration("slskd:web:content_path")] - [Argument('c', "content-path", "path to static web content")] - public static string ContentPath { get; private set; } = Path.Combine(Path.GetDirectoryName(new Uri(AppContext.BaseDirectory).AbsolutePath), "wwwroot"); - - [EnvironmentVariable("SLSKD_JWT_KEY")] - [Configuration("slskd:web:jwt:key")] - [Argument(default, "jwt-key", "optional; the key with which to sign JWTs")] - public static string JwtKey { get; private set; } = Guid.NewGuid().ToString(); - - [EnvironmentVariable("SLSKD_JWT_TTL")] - [Configuration("slskd:web:jwt:ttl")] - [Argument(default, "jwt-ttl", "optional; the TTL for JWTs")] - public static int JwtTTL { get; private set; } = 604800000; - - [EnvironmentVariable("SLSKD_USERNAME")] - [Configuration("soulseek:username")] - [Argument('u', "username", "the username for the Soulseek network")] - public static string Username { get; private set; } - - [EnvironmentVariable("SLSKD_PASSWORD")] - [Configuration("soulseek:password")] - [Argument('p', "password", "the password for the Soulseek network")] - public static string Password { get; private set; } - - public static bool EnableLoki { get; private set; } public static string Version { get; private set; } public static Guid InvocationId { get; private set; } public static int ProcessId { get; private set; } @@ -97,103 +22,120 @@ public static void Main(string[] args) { - try - { - EnvironmentVariables.Populate(); - } - catch (Exception ex) - { - Console.WriteLine($"Error parsing environment variables: {ex.Message}"); - return; - } + InstanceOptions.Populate(argumentsOnly: true); - try - { - var config = new ConfigurationBuilder() - .SetBasePath(Directory.GetCurrentDirectory()) - .AddYamlFile(ConfigurationFile, optional: true, reloadOnChange: false) - .Build(); - - config.Populate(); - } - catch (Exception ex) - { - Console.WriteLine($"Error parsing configuration file '{ConfigurationFile}': {ex.Message}"); - return; - } - - try - { - Arguments.Populate(clearExistingValues: false); - } - catch (Exception ex) - { - Console.WriteLine($"Error parsing command line input: {ex.Message}"); - return; - } - - Version = ComputeVersion(); + var assembly = Assembly.GetExecutingAssembly(); + var assemblyVersion = assembly.GetName().Version; + var informationVersion = assembly.GetCustomAttribute().InformationalVersion; + Version = $"{assemblyVersion} ({informationVersion})"; - if (ShowVersion) + if (InstanceOptions.ShowVersion) { Console.WriteLine(Version); return; } - if (ShowHelp) + if (InstanceOptions.ShowHelp) { - if (!DisableLogo) + if (!InstanceOptions.DisableLogo) { PrintLogo(Version); } - PrintHelp(); + InstanceOptions.PrintHelp(); return; } + InstanceOptions.Populate(ConfigurationFile, argumentsOnly: false); + InvocationId = Guid.NewGuid(); ProcessId = Environment.ProcessId; - Debug = Debugger.IsAttached || Debug; - EnableLoki = !string.IsNullOrEmpty(LokiUrl); - UrlBase = UrlBase.StartsWith("/") ? UrlBase : "/" + UrlBase; - ContentPath = Path.GetFullPath(ContentPath); - if (!DisableLogo) + if (!InstanceOptions.DisableLogo) { PrintLogo(Version); } - ConfigureLogger(); + if (InstanceOptions.Debug || Debugger.IsAttached) + { + Log.Logger = new LoggerConfiguration() + .MinimumLevel.Debug() + .MinimumLevel.Override("Microsoft", LogEventLevel.Information) + .Enrich.WithProperty("Version", Version) + .Enrich.WithProperty("InstanceName", InstanceOptions.InstanceName) + .Enrich.WithProperty("InvocationId", InvocationId) + .Enrich.WithProperty("ProcessId", ProcessId) + .Enrich.FromLogContext() + .WriteTo.Console( + outputTemplate: "[{SourceContext}] [{Timestamp:HH:mm:ss} {Level:u3}] {Message:lj}{NewLine}{Exception}") + .WriteTo.Async(config => + config.File( + "logs/slskd-.log", + outputTemplate: "[{SourceContext}] [{Timestamp:HH:mm:ss} {Level:u3}] {Message:lj}{NewLine}{Exception}", + rollingInterval: RollingInterval.Day)) + .WriteTo.Conditional( + e => InstanceOptions.EnableLoki, + config => config.GrafanaLoki( + InstanceOptions.LokiUrl ?? string.Empty, + outputTemplate: "[{Timestamp:HH:mm:ss} {Level:u3}] {Message:lj}{NewLine}{Exception}")) + .CreateLogger(); + } + else + { + Log.Logger = new LoggerConfiguration() + .MinimumLevel.Information() + .MinimumLevel.Override("Microsoft", LogEventLevel.Warning) + .MinimumLevel.Override("slskd.Security.PassthroughAuthenticationHandler", LogEventLevel.Information) + .Enrich.WithProperty("Version", Version) + .Enrich.WithProperty("InstanceName", InstanceOptions.InstanceName) + .Enrich.WithProperty("InvocationId", InvocationId) + .Enrich.WithProperty("ProcessId", ProcessId) + .Enrich.FromLogContext() + .WriteTo.Console( + outputTemplate: "[{Timestamp:HH:mm:ss} {Level:u3}] {Message:lj}{NewLine}{Exception}") + .WriteTo.Async(config => + config.File( + "logs/slskd-.log", + outputTemplate: "[{Timestamp:HH:mm:ss} {Level:u3}] {Message:lj}{NewLine}{Exception}", + rollingInterval: RollingInterval.Day)) + .WriteTo.Conditional( + e => InstanceOptions.EnableLoki, + config => config.GrafanaLoki( + InstanceOptions.LokiUrl ?? string.Empty, + outputTemplate: "[{Timestamp:HH:mm:ss} {Level:u3}] {Message:lj}{NewLine}{Exception}")) + .CreateLogger(); + } + var logger = Log.ForContext(); logger.Information("Version: {Version}", Version); - logger.Information("Instance Name: {InstanceName}", InstanceName); + logger.Information("Instance Name: {InstanceName}", InstanceOptions.InstanceName); logger.Information("Invocation ID: {InvocationId}", InvocationId); logger.Information("Process ID: {ProcessId}", ProcessId); - if (DisableAuthentication) + if (InstanceOptions.DisableAuthentication) { logger.Warning("Authentication of web requests is DISABLED"); } - if (EnablePrometheus) + if (InstanceOptions.EnablePrometheus) { logger.Information("Publishing Prometheus metrics to /metrics"); } - if (EnableSwagger) + if (InstanceOptions.EnableSwagger) { logger.Information("Publishing Swagger documentation to /swagger"); } - if (EnableLoki) + if (InstanceOptions.EnableLoki) { - logger.Information("Logging to Loki instance at {LoggerLokiUrl}", LokiUrl); + logger.Information("Logging to Loki instance at {LoggerLokiUrl}", InstanceOptions.LokiUrl); } try { - if (EnablePrometheus) + if (InstanceOptions.EnablePrometheus) { using var runtimeMetrics = DotNetRuntimeStatsBuilder.Default().StartCollecting(); } @@ -220,67 +162,6 @@ .UseSerilog() .UseStartup(); - private static string ComputeVersion() - { - var assembly = Assembly.GetExecutingAssembly(); - var assemblyVersion = assembly.GetName().Version; - var informationVersion = assembly.GetCustomAttribute().InformationalVersion; - return $"{assemblyVersion} ({informationVersion})"; - } - - private static void ConfigureLogger() - { - if (Debug) - { - Log.Logger = new LoggerConfiguration() - .MinimumLevel.Debug() - .MinimumLevel.Override("Microsoft", LogEventLevel.Information) - .Enrich.WithProperty("Version", Version) - .Enrich.WithProperty("InstanceName", InstanceName) - .Enrich.WithProperty("InvocationId", InvocationId) - .Enrich.WithProperty("ProcessId", ProcessId) - .Enrich.FromLogContext() - .WriteTo.Console( - outputTemplate: "[{SourceContext}] [{Timestamp:HH:mm:ss} {Level:u3}] {Message:lj}{NewLine}{Exception}") - .WriteTo.Async(config => - config.File( - "logs/slskd-.log", - outputTemplate: "[{SourceContext}] [{Timestamp:HH:mm:ss} {Level:u3}] {Message:lj}{NewLine}{Exception}", - rollingInterval: RollingInterval.Day)) - .WriteTo.Conditional( - e => EnableLoki, - config => config.GrafanaLoki( - LokiUrl ?? string.Empty, - outputTemplate: "[{Timestamp:HH:mm:ss} {Level:u3}] {Message:lj}{NewLine}{Exception}")) - .CreateLogger(); - } - else - { - Log.Logger = new LoggerConfiguration() - .MinimumLevel.Information() - .MinimumLevel.Override("Microsoft", LogEventLevel.Warning) - .MinimumLevel.Override("slskd.Security.PassthroughAuthenticationHandler", LogEventLevel.Information) - .Enrich.WithProperty("Version", Version) - .Enrich.WithProperty("InstanceName", InstanceName) - .Enrich.WithProperty("InvocationId", InvocationId) - .Enrich.WithProperty("ProcessId", ProcessId) - .Enrich.FromLogContext() - .WriteTo.Console( - outputTemplate: "[{Timestamp:HH:mm:ss} {Level:u3}] {Message:lj}{NewLine}{Exception}") - .WriteTo.Async(config => - config.File( - "logs/slskd-.log", - outputTemplate: "[{Timestamp:HH:mm:ss} {Level:u3}] {Message:lj}{NewLine}{Exception}", - rollingInterval: RollingInterval.Day)) - .WriteTo.Conditional( - e => EnableLoki, - config => config.GrafanaLoki( - LokiUrl ?? string.Empty, - outputTemplate: "[{Timestamp:HH:mm:ss} {Level:u3}] {Message:lj}{NewLine}{Exception}")) - .CreateLogger(); - } - } - private static void PrintLogo(string version) { var padding = 56 - version.Length; @@ -303,57 +184,5 @@ Console.WriteLine(banner); } - - private static void PrintHelp() - { - PrintArguments(); - PrintEnvironmentVariables(); - } - - private static void PrintArguments() - { - static string GetLongName(ArgumentInfo info) - => info.Property.PropertyType == typeof(bool) ? info.LongName : $"{info.LongName} <{info.Property.PropertyType.Name.ToLowerInvariant()}>"; - - static string GetShortName(ArgumentInfo info) - => info.ShortName > 0 ? $"-{info.ShortName}|" : " "; - - var arguments = Arguments.GetArgumentInfo(typeof(Program)); - var longestName = arguments.Select(a => GetLongName(a)).Max(n => n.Length); - - Console.WriteLine("\nusage: slskd [arguments]\n"); - Console.WriteLine("arguments:\n"); - foreach (var info in arguments) - { - var envar = info.Property.CustomAttributes - ?.Where(a => a.AttributeType == typeof(EnvironmentVariableAttribute)).FirstOrDefault() - ?.ConstructorArguments.FirstOrDefault().Value; - - var result = $" {GetShortName(info)}--{GetLongName(info).PadRight(longestName + 3)}{info.HelpText}"; - Console.WriteLine(result); - } - } - - private static void PrintEnvironmentVariables() - { - static string GetEnvironmentVariableName(ArgumentInfo info, bool includeType = false) - => info.Property.CustomAttributes - ?.Where(a => a.AttributeType == typeof(EnvironmentVariableAttribute)).FirstOrDefault() - ?.ConstructorArguments.FirstOrDefault().Value?.ToString() + (includeType ? $" <{info.Property.PropertyType.Name.ToLowerInvariant()}>" : ""); - - var arguments = Arguments.GetArgumentInfo(typeof(Program)); - var longestName = arguments.Select(a => GetEnvironmentVariableName(a, includeType: true)).Where(a => a !=null).Max(n => n.Length); - - Console.WriteLine("\nenvironment variables (arguments have precedence):\n"); - foreach (var info in arguments) - { - var envar = GetEnvironmentVariableName(info, includeType: false); - - if (string.IsNullOrEmpty(envar)) continue; - - var result = $" {GetEnvironmentVariableName(info, includeType: true).PadRight(longestName + 3)}{info.HelpText}"; - Console.WriteLine(result); - } - } } } diff --git a/src/slskd/Startup.cs b/src/slskd/Startup.cs index a29e1ffa..1e28deed 100644 --- a/src/slskd/Startup.cs +++ b/src/slskd/Startup.cs @@ -10,28 +10,28 @@ using System.Text.Json.Serialization; using System.Threading; using System.Threading.Tasks; - using Microsoft.AspNetCore.Authentication.JwtBearer; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Mvc.ApiExplorer; using Microsoft.Extensions.Caching.Memory; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; - using Microsoft.Extensions.FileProviders; - using Microsoft.Extensions.Hosting; - using Microsoft.IdentityModel.Tokens; using Microsoft.OpenApi.Models; using Soulseek; using Soulseek.Diagnostics; - using slskd.Entities; - using slskd.Security; using slskd.Trackers; using System.Collections.Concurrent; - using Serilog; - using Serilog.Events; - using Prometheus; + using Microsoft.IdentityModel.Tokens; + using slskd.Security; + using Microsoft.AspNetCore.Authentication.JwtBearer; using Prometheus.SystemMetrics; using Microsoft.Extensions.Options; + using Serilog; + using Microsoft.Extensions.Hosting; + using Prometheus; + using Microsoft.Extensions.FileProviders; + using Serilog.Events; + using slskd.Entities; public class Startup { @@ -42,7 +42,6 @@ internal static int RoomMessageLimit { get; set; } internal static string XmlDocFile { get; set; } - private SoulseekClient Client { get; set; } private object ConsoleSyncRoot { get; } = new object(); private ISharedFileCache SharedFileCache { get; set; } @@ -57,7 +56,6 @@ DiagnosticLevel = Configuration.GetValue("DIAGNOSTIC", DiagnosticLevel.Info); RoomMessageLimit = Configuration.GetValue("ROOM_MESSAGE_LIMIT", 250); XmlDocFile = Configuration.GetValue("XML_DOC_FILE", Path.Combine(AppContext.BaseDirectory, typeof(Startup).GetTypeInfo().Assembly.GetName().Name + ".xml")); - SharedFileCache = new SharedFileCache(SharedDirectory, SharedCacheTTL); } @@ -75,9 +73,9 @@ services.AddCors(options => options.AddPolicy("AllowAll", builder => builder.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader())); - if (!Program.DisableAuthentication) + if (!InstanceOptions.DisableAuthentication) { - var jwtSigningKey = new SymmetricSecurityKey(PBKDF2.GetKey(Program.JwtKey)); + var jwtSigningKey = new SymmetricSecurityKey(PBKDF2.GetKey(InstanceOptions.JwtKey)); services.AddSingleton(jwtSigningKey); @@ -139,7 +137,7 @@ } }); - if (Program.EnablePrometheus) + if (InstanceOptions.EnablePrometheus) { services.AddSystemMetrics(); } @@ -176,8 +174,8 @@ app.UseCors("AllowAll"); - app.UsePathBase(Program.UrlBase); - logger.Information("Using base url {UrlBase}", Program.UrlBase); + app.UsePathBase(InstanceOptions.UrlBase); + logger.Information("Using base url {UrlBase}", InstanceOptions.UrlBase); // remove any errant double forward slashes which may have been introduced // by a reverse proxy or having the base path removed @@ -195,31 +193,31 @@ FileServerOptions fileServerOptions = default; - if (!System.IO.Directory.Exists(Program.ContentPath)) + if (!System.IO.Directory.Exists(InstanceOptions.ContentPath)) { - logger.Warning($"Static content disabled; cannot find content path '{Program.ContentPath}'"); + logger.Warning($"Static content disabled; cannot find content path '{InstanceOptions.ContentPath}'"); } else { fileServerOptions = new FileServerOptions { - FileProvider = new PhysicalFileProvider(Program.ContentPath), + FileProvider = new PhysicalFileProvider(InstanceOptions.ContentPath), RequestPath = "", EnableDirectoryBrowsing = false, EnableDefaultFiles = true }; app.UseFileServer(fileServerOptions); - logger.Information("Serving static content from {ContentPath}", Program.ContentPath); + logger.Information("Serving static content from {ContentPath}", InstanceOptions.ContentPath); } app.UseSerilogRequestLogging(); - if (Program.EnablePrometheus) + if (InstanceOptions.EnablePrometheus) { app.UseHttpMetrics(); } - + app.UseAuthentication(); app.UseRouting(); @@ -228,13 +226,13 @@ { endpoints.MapControllers(); - if (Program.EnablePrometheus) + if (InstanceOptions.EnablePrometheus) { endpoints.MapMetrics(); } }); - if (Program.EnableSwagger) + if (InstanceOptions.EnableSwagger) { app.UseSwagger(); app.UseSwaggerUI(options => provider.ApiVersionDescriptions.ToList() @@ -256,7 +254,7 @@ // finally, hit the fileserver again. if the path was modified to return the index above, the index document will be returned // otherwise it will throw a final 404 back to the client. - if (System.IO.Directory.Exists(Program.ContentPath)) + if (System.IO.Directory.Exists(InstanceOptions.ContentPath)) { app.UseFileServer(fileServerOptions); } @@ -290,8 +288,8 @@ enqueueDownloadAction: (username, endpoint, filename) => EnqueueDownloadAction(username, endpoint, filename, tracker), searchResponseResolver: SearchResponseResolver); - var username = soulseekOptions.CurrentValue.Username ?? Program.Username; - var password = soulseekOptions.CurrentValue.Password ?? Program.Password; + var username = soulseekOptions.CurrentValue.Username ?? InstanceOptions.Username; + var password = soulseekOptions.CurrentValue.Password ?? InstanceOptions.Password; Client = new SoulseekClient(options: clientOptions); @@ -309,7 +307,7 @@ }; var logger = Loggers.GetOrAdd(e.GetType().FullName, Log.ForContext("SourceContext", "Soulseek").ForContext("SoulseekContext", e.GetType().FullName)); - + logger.Write(TranslateLogLevel(args.Level), "{@Message}", args.Message); }; diff --git a/src/slskd/slskd.csproj b/src/slskd/slskd.csproj index 285a18c7..d67e6eb8 100644 --- a/src/slskd/slskd.csproj +++ b/src/slskd/slskd.csproj @@ -50,7 +50,8 @@ - + + -- cgit v1.2.3 From ff3b1fe36885442a6e40cac23ec8b186ef416e77 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 23 Jan 2021 00:39:50 -0600 Subject: broken wip --- .../CommandLineArgumentConfigurationSource.cs | 93 +++++++++ src/slskd/Common/Configuration.cs | 151 --------------- .../EnvironmentVariableConfigurationSource.cs | 76 ++++++++ src/slskd/Common/Options/InstanceOptions.cs | 125 ++++++------ src/slskd/Common/Options/RuntimeOptions.cs | 97 ++++++++++ src/slskd/Common/YamlConfigurationSource.cs | 214 +++++++++++++++++++++ src/slskd/Program.cs | 30 ++- src/slskd/config.yml | 10 +- src/slskd/slskd.csproj | 1 - 9 files changed, 580 insertions(+), 217 deletions(-) create mode 100644 src/slskd/Common/CommandLineArgumentConfigurationSource.cs delete mode 100644 src/slskd/Common/Configuration.cs create mode 100644 src/slskd/Common/EnvironmentVariableConfigurationSource.cs create mode 100644 src/slskd/Common/YamlConfigurationSource.cs (limited to 'src') diff --git a/src/slskd/Common/CommandLineArgumentConfigurationSource.cs b/src/slskd/Common/CommandLineArgumentConfigurationSource.cs new file mode 100644 index 00000000..1762228d --- /dev/null +++ b/src/slskd/Common/CommandLineArgumentConfigurationSource.cs @@ -0,0 +1,93 @@ +namespace slskd +{ + using Microsoft.Extensions.Configuration; + using System; + using System.Collections.Generic; + using System.Linq; + using Utility.CommandLine; + + public class Argument + { + public string Description { get; set; } + public char ShortName { get; set; } + public string LongName { get; set; } + public string Key { get; set; } + } + + public static class CommandLineArgumentExtensions + { + public static IConfigurationBuilder MapCommandLineArguments(this IConfigurationBuilder builder, IEnumerable map, string commandLine) + { + if (builder == null) + { + throw new ArgumentNullException(nameof(builder)); + } + + return builder.MapCommandLineArguments(s => + { + s.Map = map; + s.CommandLine = commandLine; + }); + } + + public static IConfigurationBuilder MapCommandLineArguments(this IConfigurationBuilder builder, Action configureSource) + => builder.Add(configureSource); + } + + public class CommandLineArgumentConfigurationSource : IConfigurationSource + { + public IEnumerable Map { get; set; } + public string CommandLine { get; set; } + + public IConfigurationProvider Build(IConfigurationBuilder builder) + { + return new CommandLineArgumentConfigurationProvider(this); + } + } + + public class CommandLineArgumentConfigurationProvider : ConfigurationProvider + { + public CommandLineArgumentConfigurationSource Source { get; set; } + + /// + /// Initializes a new instance with the specified source. + /// + /// The source settings. + public CommandLineArgumentConfigurationProvider(CommandLineArgumentConfigurationSource source) + { + Source = source; + } + + public override void Load() + { + var dictionary = Arguments.Parse(Source.CommandLine).ArgumentDictionary; + + foreach (var item in Source.Map) + { + Console.WriteLine($"Item: {item.Key}"); + + if (string.IsNullOrEmpty(item.Key)) + { + continue; + } + + var arguments = new[] { item.ShortName.ToString(), item.LongName }.Where(i => !string.IsNullOrEmpty(i)); + + foreach (var argument in arguments) + { + if (dictionary.ContainsKey(argument)) + { + var value = dictionary[argument].ToString(); + + if (string.IsNullOrEmpty(value)) + { + value = "true"; + } + + Data[item.Key] = value; + } + } + } + } + } +} diff --git a/src/slskd/Common/Configuration.cs b/src/slskd/Common/Configuration.cs deleted file mode 100644 index fca57299..00000000 --- a/src/slskd/Common/Configuration.cs +++ /dev/null @@ -1,151 +0,0 @@ -namespace slskd -{ - using Microsoft.Extensions.Configuration; - using System; - using System.Collections; - using System.Collections.Generic; - using System.Diagnostics; - using System.Globalization; - using System.Linq; - using System.Reflection; - using System.Runtime.CompilerServices; - - public class ConfigurationAttribute : Attribute - { - public ConfigurationAttribute(string key) - { - Key = key; - } - - public string Key { get; set; } - } - - public static class Configuration - { - public static void Populate(this IConfiguration configuration, Type targetType = null, [CallerMemberName] string caller = default(string)) - { - var type = targetType ?? GetCallingType(caller); - var targetProperties = GetTargetProperties(type); - - foreach (var property in targetProperties) - { - var propertyType = property.Value.PropertyType; - - string value = configuration.GetValue(property.Key); - - if (string.IsNullOrEmpty(value)) - { - continue; - } - - object convertedValue; - - if (propertyType == typeof(bool)) - { - convertedValue = value?.Equals("true", StringComparison.InvariantCultureIgnoreCase) ?? false; - } - else if (propertyType.IsArray || (propertyType.IsGenericType && propertyType.GetGenericTypeDefinition() == typeof(List<>))) - { - Type valueType; - - if (propertyType.IsArray) - { - valueType = propertyType.GetElementType(); - } - else - { - valueType = propertyType.GetGenericArguments()[0]; - } - - // create a list to store converted values - Type valueListType = typeof(List<>).MakeGenericType(valueType); - var valueList = (IList)Activator.CreateInstance(valueListType); - - // populate the list - foreach (object v in value.Split(',').Select(s => s.Trim())) - { - valueList.Add(ChangeType(v, property.Key, valueType)); - } - - if (propertyType.IsArray) - { - var valueArray = Array.CreateInstance(propertyType.GetElementType(), valueList.Count); - - for (int i = 0; i < valueArray.Length; i++) - { - valueArray.SetValue(valueList[i], i); - } - - convertedValue = valueArray; - } - else - { - convertedValue = valueList; - } - } - else - { - convertedValue = ChangeType(value, property.Key, property.Value.PropertyType); - } - - property.Value.SetValue(null, convertedValue); - } - } - - private static Type GetCallingType(string caller) - { - var callingMethod = new StackTrace().GetFrames() - .Select(f => f.GetMethod()) - .FirstOrDefault(m => m.Name == caller); - - if (callingMethod == default(MethodBase)) - { - throw new InvalidOperationException($"Unable to determine the containing type of the calling method '{caller}'. Explicitly specify the originating Type."); - } - - return callingMethod.DeclaringType; - } - - private static Dictionary GetTargetProperties(Type type) - { - Dictionary properties = new Dictionary(); - - foreach (PropertyInfo property in type.GetProperties(BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Static)) - { - // attempt to fetch the ArgumentAttribute of the property - CustomAttributeData attribute = property.CustomAttributes.FirstOrDefault(a => a.AttributeType.Name == typeof(ConfigurationAttribute).Name); - - // if found, extract the Name property and add it to the dictionary - if (attribute != default(CustomAttributeData)) - { - string name = ((string)attribute.ConstructorArguments[0].Value)?.Replace("_", string.Empty).Replace("-", string.Empty); - - if (!properties.ContainsKey(name)) - { - properties.Add(name, property); - } - } - } - - return properties; - } - - private static object ChangeType(object value, string name, Type type) - { - try - { - if (type.IsEnum) - { - return Enum.Parse(type, (string)value, true); - } - - return Convert.ChangeType(value, type, CultureInfo.InvariantCulture); - } - catch (Exception ex) when (ex is InvalidCastException || ex is FormatException || ex is OverflowException || ex is ArgumentNullException) - { - string message = $"Failed to convert value '{value}' to target type {type}"; - throw new ArgumentException(message, name, ex); - } - } - } -} diff --git a/src/slskd/Common/EnvironmentVariableConfigurationSource.cs b/src/slskd/Common/EnvironmentVariableConfigurationSource.cs new file mode 100644 index 00000000..36a8ddf1 --- /dev/null +++ b/src/slskd/Common/EnvironmentVariableConfigurationSource.cs @@ -0,0 +1,76 @@ +namespace slskd +{ + using Microsoft.Extensions.Configuration; + using System; + using System.Collections.Generic; + + public class EnvironmentVariable + { + public string Description { get; set; } + public string Name { get; set; } + public string Key { get; set; } + } + + public static class EnvironmentVariableConfigurationExtensions + { + public static IConfigurationBuilder MapEnvironmentVariables(this IConfigurationBuilder builder, IEnumerable map) + { + if (builder == null) + { + throw new ArgumentNullException(nameof(builder)); + } + + return builder.MapEnvironmentVariables(s => + { + s.Map = map; + }); + } + + public static IConfigurationBuilder MapEnvironmentVariables(this IConfigurationBuilder builder, Action configureSource) + => builder.Add(configureSource); + } + + public class EnvironmentVariableConfigurationSource : IConfigurationSource + { + public IConfigurationProvider Build(IConfigurationBuilder builder) + { + return new EnvironmentVariableConfigurationProvider(this); + } + + public IEnumerable Map { get; set; } + } + + public class EnvironmentVariableConfigurationProvider : ConfigurationProvider + { + public EnvironmentVariableConfigurationSource Source { get; set; } + /// + /// Initializes a new instance with the specified source. + /// + /// The source settings. + public EnvironmentVariableConfigurationProvider(EnvironmentVariableConfigurationSource source) + { + Source = source; + } + + public override void Load() + { + foreach (var item in Source.Map) + { + if (string.IsNullOrEmpty(item.Key)) + { + continue; + } + + if (!string.IsNullOrEmpty(item.Name)) + { + var value = Environment.GetEnvironmentVariable(item.Name); + + if (!string.IsNullOrEmpty(value)) + { + Data[item.Key] = value; + } + } + } + } + } +} diff --git a/src/slskd/Common/Options/InstanceOptions.cs b/src/slskd/Common/Options/InstanceOptions.cs index 09431956..52b46722 100644 --- a/src/slskd/Common/Options/InstanceOptions.cs +++ b/src/slskd/Common/Options/InstanceOptions.cs @@ -6,7 +6,6 @@ using System.Linq; using Utility.CommandLine; using Utility.EnvironmentVariables; - using Utility.Extensions.Configuration.Yaml; public class InstanceOptions { @@ -17,32 +16,32 @@ public static bool ShowVersion { get; private set; } [EnvironmentVariable("SLSKD_DEBUG")] - [Configuration("slskd:options:debug")] + [Configuration("slskd:debug")] [Argument('d', "debug", "run in debug mode")] public static bool Debug { get; private set; } [EnvironmentVariable("SLSKD_NO_LOGO")] - [Configuration("slskd:options:no_logo")] + [Configuration("slskd:no_logo")] [Argument('n', "no-logo", "suppress logo on startup")] public static bool DisableLogo { get; private set; } [EnvironmentVariable("SLSKD_NO_AUTH")] - [Configuration("slskd:options:no_auth")] + [Configuration("slskd:no_auth")] [Argument('x', "no-auth", "disable authentication for web requests")] public static bool DisableAuthentication { get; private set; } [EnvironmentVariable("SLSKD_INSTANCE_NAME")] - [Configuration("slskd:options:instance_name")] + [Configuration("slskd:instance_name")] [Argument('i', "instance-name", "optional; a unique name for this instance")] public static string InstanceName { get; private set; } = "default"; - [EnvironmentVariable("SLSKD_PROMETHEUS")] - [Configuration("slskd:options:prometheus")] + [EnvironmentVariable("SLSKD_FEATURE_PROMETHEUS")] + [Configuration("slskd:feature:prometheus")] [Argument('m', "prometheus", "enable collection and publish of prometheus metrics")] public static bool EnablePrometheus { get; private set; } - [EnvironmentVariable("SLSKD_SWAGGER")] - [Configuration("slskd:options:swagger")] + [EnvironmentVariable("SLSKD_FEATURE_SWAGGER")] + [Configuration("slskd:feature:swagger")] [Argument('s', "swagger", "enable swagger documentation")] public static bool EnableSwagger { get; private set; } @@ -83,52 +82,68 @@ public static bool EnableLoki { get; private set; } - public static void Populate(string configurationFile = null, bool argumentsOnly = false) - { - if (!argumentsOnly) - { - try - { - EnvironmentVariables.Populate(typeof(InstanceOptions)); - } - catch (Exception ex) - { - Console.WriteLine($"Error parsing environment variables: {ex.Message}"); - return; - } - - try - { - var config = new ConfigurationBuilder() - .SetBasePath(Directory.GetCurrentDirectory()) - .AddYamlFile(configurationFile, optional: true, reloadOnChange: false) - .Build(); - - Console.WriteLine(config.GetDebugView()); - - config.Populate(typeof(InstanceOptions)); - } - catch (Exception ex) - { - Console.WriteLine($"Error parsing configuration file '{configurationFile}': {ex.Message}"); - return; - } - } - - try - { - Arguments.Populate(typeof(InstanceOptions), clearExistingValues: false); - } - catch (Exception ex) - { - Console.WriteLine($"Error parsing command line input: {ex.Message}"); - return; - } - - EnableLoki = !string.IsNullOrEmpty(LokiUrl); - UrlBase = UrlBase.StartsWith("/") ? UrlBase : "/" + UrlBase; - ContentPath = Path.GetFullPath(ContentPath); - } + //public static void Populate(string configurationFile = null, bool argumentsOnly = false) + //{ + // if (!argumentsOnly) + // { + // try + // { + // EnvironmentVariables.Populate(typeof(InstanceOptions)); + // } + // catch (Exception ex) + // { + // Console.WriteLine($"Error parsing environment variables: {ex.Message}"); + // return; + // } + + // try + // { + // var config = new ConfigurationBuilder() + // .SetBasePath(Directory.GetCurrentDirectory()) + // .AddMapping(new[] + // { + // new OptionMap { + // Description = "run in debug mode", + // EnvironmentVariable = "SLSK_DEBUG", + // ShortName = 'd', + // LongName = "debug", + // Key = "slskd:debug" + // }, + // new OptionMap { + // Description = "optional; a unique name for this instance", + // EnvironmentVariable = "SLSK_INSTANCE_NAME", + // ShortName = 'i', + // LongName = "instance-name", + // Key = "slskd:instancename" + // } + // }, Environment.CommandLine, configurationFile, optional: true, reloadOnChange: false) + // .Build(); + + // Console.WriteLine(config.GetDebugView()); + + // config.Populate(typeof(InstanceOptions)); + // } + // catch (Exception ex) + // { + // Console.WriteLine($"Error parsing configuration file '{configurationFile}': {ex.Message}"); + // return; + // } + // } + + // try + // { + // Arguments.Populate(typeof(InstanceOptions), clearExistingValues: false); + // } + // catch (Exception ex) + // { + // Console.WriteLine($"Error parsing command line input: {ex.Message}"); + // return; + // } + + // EnableLoki = !string.IsNullOrEmpty(LokiUrl); + // UrlBase = UrlBase.StartsWith("/") ? UrlBase : "/" + UrlBase; + // ContentPath = Path.GetFullPath(ContentPath); + //} public static void PrintHelp() { diff --git a/src/slskd/Common/Options/RuntimeOptions.cs b/src/slskd/Common/Options/RuntimeOptions.cs index d0c28e75..cded2334 100644 --- a/src/slskd/Common/Options/RuntimeOptions.cs +++ b/src/slskd/Common/Options/RuntimeOptions.cs @@ -1,9 +1,106 @@ namespace slskd { + using System; using System.Collections.Generic; public class RuntimeOptions { + public static IEnumerable EnvironmentVariableMap => new[] + { + new EnvironmentVariable { + Description = "run in debug mode", + Name = "SLSK_DEBUG", + Key = "slskd:debug" + }, + new EnvironmentVariable { + Description = "optional; a unique name for this instance", + Name = "SLSK_INSTANCE_NAME", + Key = "slskd:instancename" + }, + new EnvironmentVariable { + Description = "enable collection and publish of prometheus metrics", + Name = "SLSK_PROMETHEUS", + Key = "slskd:feature:prometheus" + }, + new EnvironmentVariable { + Description = "enable swagger documentation", + Name = "SLSK_SWAGGER", + Key = "slskd:feature:swagger" + }, + new EnvironmentVariable { + Description = "jwt signing key", + Name = "SLSKD_JWT_KEY", + Key = "slskd:web:jwt:key" + } + }; + + public static IEnumerable ArgumentMap => new[] + { + new Argument + { + Description = "print usage", + ShortName = 'h', + LongName = "help", + Key = "slskd:showhelp" + }, + new Argument { + Description = "display version information", + ShortName = 'v', + LongName = "version", + Key = "slskd:showversion" + }, + new Argument { + Description = "run in debug mode", + ShortName = 'd', + LongName = "debug", + Key = "slskd:debug" + }, + new Argument + { + Description = "", + ShortName = 'i', + LongName = "instance-name", + Key = "slskd:instancename" + } + }; + + public class slskd + { + public bool ShowHelp { get; private set; } = false; + public bool ShowVersion { get; private set; } = false; + public bool Debug { get; private set; } = false; + public bool NoLogo { get; private set; } = false; + public bool NoAuth { get; private set; } = false; + public string InstanceName { get; private set; } = "default"; + public FeatureOptions Feature { get; private set; } = new FeatureOptions(); + public LoggerOptions Logger { get; private set; } = new LoggerOptions(); + public WebOptions Web { get; private set; } = new WebOptions(); + + public class FeatureOptions + { + public bool Prometheus { get; private set; } = false; + public bool Swagger { get; private set; } = false; + } + + public class LoggerOptions + { + public string Loki { get; private set; } = null; + } + + public class WebOptions + { + public string UrlBase { get; private set; } = "/"; + public string ContentPath { get; private set; } = "wwwroot"; + public JwtOptions Jwt { get; private set; } = new JwtOptions(); + + public class JwtOptions + { + public int TTL { get; private set; } = 1234567890; + public string Key { get; private set; } = Guid.NewGuid().ToString(); + } + } + } + public class Soulseek { public string Username { get; set; } = InstanceOptions.Username; diff --git a/src/slskd/Common/YamlConfigurationSource.cs b/src/slskd/Common/YamlConfigurationSource.cs new file mode 100644 index 00000000..a7c379e3 --- /dev/null +++ b/src/slskd/Common/YamlConfigurationSource.cs @@ -0,0 +1,214 @@ +/* + █▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀ ▀▀▀▀▀▀▀▀▀▀▀▀▀▀ ▀▀▀ ▀ ▀ ▀▀ + █ The MIT License (MIT) + █ + █ Copyright (c) 2021 JP Dillingham (jp@dillingham.ws) + █ + █ Permission is hereby granted, free of charge, to any person obtaining a copy + █ of this software and associated documentation files (the "Software"), to deal + █ in the Software without restriction, including without limitation the rights + █ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + █ copies of the Software, and to permit persons to whom the Software is + █ furnished to do so, subject to the following conditions: + █ + █ The above copyright notice and this permission notice shall be included in all + █ copies or substantial portions of the Software. + █ + █ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + █ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + █ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + █ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + █ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + █ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + █ SOFTWARE. + █ + ▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀ ▀▀ ▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀██ + ██ + ▀█▄ ██ ▄█▀ + ▀████▀ + ▀▀ */ + +namespace slskd +{ + using Microsoft.Extensions.Configuration; + using Microsoft.Extensions.FileProviders; + using System; + using System.IO; + using System.Linq; + using YamlDotNet.Core; + using YamlDotNet.RepresentationModel; + + /// + /// Extension methods for adding . + /// + public static class YamlConfigurationExtensions + { + /// + /// Adds the YAML configuration provider at to . + /// + /// The to add to. + /// Path relative to the base path stored in + /// of . + /// The . + public static IConfigurationBuilder AddYamlFile(this IConfigurationBuilder builder, string path) + { + return AddYamlFile(builder, provider: null, path: path, optional: false, reloadOnChange: false); + } + + /// + /// Adds the YAML configuration provider at to . + /// + /// The to add to. + /// Path relative to the base path stored in + /// of . + /// Whether the file is optional. + /// The . + public static IConfigurationBuilder AddYamlFile(this IConfigurationBuilder builder, string path, bool optional) + { + return AddYamlFile(builder, provider: null, path: path, optional: optional, reloadOnChange: false); + } + + /// + /// Adds the YAML configuration provider at to . + /// + /// The to add to. + /// Path relative to the base path stored in + /// of . + /// Whether the file is optional. + /// Whether the configuration should be reloaded if the file changes. + /// The . + public static IConfigurationBuilder AddYamlFile(this IConfigurationBuilder builder, string path, bool optional, bool reloadOnChange) + { + return AddYamlFile(builder, provider: null, path: path, optional: optional, reloadOnChange: reloadOnChange); + } + + /// + /// Adds a YAML configuration source to . + /// + /// The to add to. + /// The to use to access the file. + /// Path relative to the base path stored in + /// of . + /// Whether the file is optional. + /// Whether the configuration should be reloaded if the file changes. + /// The . + public static IConfigurationBuilder AddYamlFile(this IConfigurationBuilder builder, IFileProvider provider, string path, bool optional, bool reloadOnChange) + { + if (builder == null) + { + throw new ArgumentNullException(nameof(builder)); + } + if (string.IsNullOrEmpty(path)) + { + throw new ArgumentException("File path must be a non-empty string.", nameof(path)); + } + + return builder.AddYamlFile(s => + { + s.FileProvider = provider; + s.Path = path; + s.Optional = optional; + s.ReloadOnChange = reloadOnChange; + s.ResolveFileProvider(); + }); + } + + /// + /// Adds a YAML configuration source to . + /// + /// The to add to. + /// Configures the source. + /// The . + public static IConfigurationBuilder AddYamlFile(this IConfigurationBuilder builder, Action configureSource) + => builder.Add(configureSource); + } + + /// + /// Represents a YAML file as an . + /// + public class YamlConfigurationSource : FileConfigurationSource + { + /// + /// Builds the for this source. + /// + /// The . + /// A + public override IConfigurationProvider Build(IConfigurationBuilder builder) + { + EnsureDefaults(builder); + return new YamlConfigurationProvider(this); + } + } + + /// + /// A YAML file based . + /// + public class YamlConfigurationProvider : FileConfigurationProvider + { + /// + /// Initializes a new instance with the specified source. + /// + /// The source settings. + public YamlConfigurationProvider(YamlConfigurationSource source) : base(source) { } + + private string[] NullValues { get; } = new[] { "~", "null", "" }; + + /// + /// Loads the YAML data from a stream. + /// + /// The stream to read. + public override void Load(Stream stream) + { + try + { + using var reader = new StreamReader(stream); + + var yaml = new YamlStream(); + yaml.Load(reader); + + var rootNode = (YamlMappingNode)yaml.Documents[0].RootNode; + + Traverse(rootNode); + } + catch (YamlException e) + { + throw new FormatException("Could not parse the YAML file.", e); + } + } + + private void Traverse(YamlNode root, string path = null) + { + static string Clean(string str) => str?.Replace("_", string.Empty).Replace("-", string.Empty); + + if (root is YamlScalarNode scalar) + { + if (Data.ContainsKey(Clean(path))) + { + throw new FormatException($"A duplicate key '{Clean(path)}' was found."); + } + + var value = NullValues.Contains(scalar.Value.ToLower()) ? null : scalar.Value; + + if (value != null) + { + Data[Clean(path)] = NullValues.Contains(scalar.Value.ToLower()) ? null : scalar.Value; + } + } + else if (root is YamlMappingNode map) + { + foreach (var node in map.Children) + { + var key = Clean(((YamlScalarNode)node.Key).Value); + Traverse(node.Value, path == null ? key : ConfigurationPath.Combine(path, key)); + } + } + else if (root is YamlSequenceNode sequence) + { + for (int i = 0; i < sequence.Children.Count(); i++) + { + Traverse(sequence.Children[i], ConfigurationPath.Combine(path, i.ToString())); + } + } + } + } +} diff --git a/src/slskd/Program.cs b/src/slskd/Program.cs index e366e62f..5ea7c304 100644 --- a/src/slskd/Program.cs +++ b/src/slskd/Program.cs @@ -9,8 +9,9 @@ using Serilog.Sinks.Grafana.Loki; using System; using System.Diagnostics; + using System.IO; using System.Reflection; - using Utility.Extensions.Configuration.Yaml; + using System.Text.Json; public class Program { @@ -20,22 +21,30 @@ public static readonly string ConfigurationFile = "config.yml"; + private static Action BinderOptions = (o) => { o.BindNonPublicProperties = true; }; + public static RuntimeOptions.slskd Options { get; private set; } = new(); + + public static void Main(string[] args) { - InstanceOptions.Populate(argumentsOnly: true); + new ConfigurationBuilder() + .MapCommandLineArguments(RuntimeOptions.ArgumentMap, Environment.CommandLine) + .Build() + .GetSection("slskd") + .Bind(Options, BinderOptions); var assembly = Assembly.GetExecutingAssembly(); var assemblyVersion = assembly.GetName().Version; var informationVersion = assembly.GetCustomAttribute().InformationalVersion; Version = $"{assemblyVersion} ({informationVersion})"; - if (InstanceOptions.ShowVersion) + if (Options.ShowVersion) { Console.WriteLine(Version); return; } - if (InstanceOptions.ShowHelp) + if (Options.ShowHelp) { if (!InstanceOptions.DisableLogo) { @@ -46,7 +55,18 @@ return; } - InstanceOptions.Populate(ConfigurationFile, argumentsOnly: false); + new ConfigurationBuilder() + .MapEnvironmentVariables(RuntimeOptions.EnvironmentVariableMap) + .SetBasePath(Directory.GetCurrentDirectory()) + .AddYamlFile(ConfigurationFile, optional: true, reloadOnChange: false) + .MapCommandLineArguments(RuntimeOptions.ArgumentMap, Environment.CommandLine) + .Build() + .GetSection("slskd") + .Bind(Options, BinderOptions); + + Console.WriteLine(JsonSerializer.Serialize(Options)); + + return; InvocationId = Guid.NewGuid(); ProcessId = Environment.ProcessId; diff --git a/src/slskd/config.yml b/src/slskd/config.yml index a7840141..df1514d0 100644 --- a/src/slskd/config.yml +++ b/src/slskd/config.yml @@ -1,9 +1,9 @@ slskd: - options: - debug: false - no_logo: false - no_auth: false - instance_name: FromYAML + debug: false + no_logo: false + no_auth: false + instance_name: FromYAML + feature: prometheus: true swagger: true logger: diff --git a/src/slskd/slskd.csproj b/src/slskd/slskd.csproj index d67e6eb8..cae5d27c 100644 --- a/src/slskd/slskd.csproj +++ b/src/slskd/slskd.csproj @@ -51,7 +51,6 @@ - -- cgit v1.2.3 From 9b433eb9266f26f21c82def6b6c720974a8a0bde Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 23 Jan 2021 13:39:45 -0600 Subject: add configuration providers --- .../Common/Configuration/CommandLineArguments.cs | 666 +++++++++++++++++++++ .../CommandLineConfigurationSource.cs | 139 +++++ .../EnvironmentVariableConfigurationSource.cs | 135 +++++ .../Configuration/YamlConfigurationSource.cs | 158 +++++ 4 files changed, 1098 insertions(+) create mode 100644 src/slskd/Common/Configuration/CommandLineArguments.cs create mode 100644 src/slskd/Common/Configuration/CommandLineConfigurationSource.cs create mode 100644 src/slskd/Common/Configuration/EnvironmentVariableConfigurationSource.cs create mode 100644 src/slskd/Common/Configuration/YamlConfigurationSource.cs (limited to 'src') diff --git a/src/slskd/Common/Configuration/CommandLineArguments.cs b/src/slskd/Common/Configuration/CommandLineArguments.cs new file mode 100644 index 00000000..133fd334 --- /dev/null +++ b/src/slskd/Common/Configuration/CommandLineArguments.cs @@ -0,0 +1,666 @@ +namespace slskd +{ + using System; + using System.Collections; + using System.Collections.Concurrent; + using System.Collections.Generic; + using System.Diagnostics; + using System.Globalization; + using System.Linq; + using System.Reflection; + using System.Runtime.CompilerServices; + using System.Text.RegularExpressions; + + /// + /// Provides extension method(s) for the CommandLineArguments namespace. + /// + public static class CommandLineArgumentsExtensions + { + /// + /// Gets the DeclaringType of the first method on the stack whose name matches the specified . + /// + /// The name of the calling method for which the DeclaringType is to be fetched. + /// The DeclaringType of the first method on the stack whose name matches the specified . + internal static Type GetCallingType(string caller) + { + var callingMethod = new StackTrace().GetFrames() + .Select(f => f.GetMethod()) + .FirstOrDefault(m => m.Name == caller); + + if (callingMethod == default) + { + throw new InvalidOperationException($"Unable to determine the containing type of the calling method '{caller}'. Explicitly specify the originating Type."); + } + + return callingMethod.DeclaringType; + } + + /// + /// Removes the outermost pair of enclosing quotes. + /// + /// The string to trim. + /// The trimmed string. + internal static string TrimOuterQuotes(this string value) + { + if (value.StartsWith("\"", StringComparison.InvariantCultureIgnoreCase) && value.EndsWith("\"", StringComparison.InvariantCultureIgnoreCase)) + { + value = value.Trim('"'); + } + else if (value.StartsWith("'", StringComparison.InvariantCultureIgnoreCase) && value.EndsWith("'", StringComparison.InvariantCultureIgnoreCase)) + { + value = value.Trim('\''); + } + + return value; + } + } + + /// + /// Indicates that the property is to be used as a target for automatic population of values from command line arguments + /// when invoking the method. + /// + [AttributeUsage(AttributeTargets.Property, AllowMultiple = false)] + public class CommandLineArgumentAttribute : Attribute + { + /// + /// Initializes a new instance of the class. + /// + /// The short name of the argument, represented as a single character. + /// The long name of the argument. + /// The help text of the argument. + public CommandLineArgumentAttribute(char shortName, string longName, string helpText = null) + { + ShortName = shortName; + LongName = longName; + HelpText = helpText; + } + + /// + /// Gets or sets the help text of the argument. + /// + public string HelpText { get; set; } + + /// + /// Gets or sets the long name of the argument. + /// + public string LongName { get; set; } + + /// + /// Gets or sets the short name of the argument. + /// + public char ShortName { get; set; } + } + + /// + /// Encapsulates argument names and help text. + /// + public class ArgumentInfo + { + /// + /// Initializes a new instance of the class. + /// + /// The short name of the argument. + /// The long name of the argument. + /// The help text for the argument. + /// The property with which the argument is associated. + public ArgumentInfo(char shortName, string longName, string helpText, PropertyInfo property) + { + ShortName = shortName; + LongName = longName; + HelpText = helpText; + Property = property; + } + + /// + /// Gets the help text for the argument. + /// + public string HelpText { get; } + + /// + /// Gets a value indicating whether the argument backing Type is a collection. + /// + public bool IsCollection => Property.PropertyType.IsArray || (Property.PropertyType.IsGenericType && Property.PropertyType.GetGenericTypeDefinition() == typeof(List<>)); + + /// + /// Gets the long name of the argument. + /// + public string LongName { get; } + + /// + /// Gets the property with which the argument is associated. + /// + public PropertyInfo Property { get; } + + /// + /// Gets the short name of the argument. + /// + public char ShortName { get; } + } + + /// + /// Provides static methods used to retrieve the command line arguments and operands with which the application was + /// started, as well as a Type to contain them. + /// + public class CommandLineArguments + { + /// + /// The regular expression with which to parse the command line string. + /// + private const string ArgumentRegExWithoutForwardSlash = "(?:[-]{1,2})([^=: ]+)[=: ]?([^-'\"]\\S*|\\\"[^\"]*\\\"|\\\'[^']*\\\')?|([^ ([^'\\\"]+|\"[^\\\"]+\"|\\\'[^']+\\\')"; + + /// + /// The regular expression with which to parse the command line string, including the ability to specify forward slashes. + /// + private const string ArgumentRegExWithForwardSlash = "(?:[-]{1,2}|\\/)([^=: ]+)[=: ]?([^-'\"\\/]\\S*|\\\"[^\"]*\\\"|\\\'[^']*\\\')?|([^ ([^'\\\"]+|\"[^\\\"]+\"|\\\'[^']+\\\')"; + + /// + /// The regular expression with which to parse argument-value groups. + /// + private const string GroupRegEx = "^-[^-]+"; + + /// + /// The regular expression with which to parse strings strictly containing operands. + /// + private const string OperandRegEx = "([^ ([^'\\\"]+|\\\"[^\\\"]+\\\"|\\\'[^']+\\\')"; + + /// + /// The regular expression with which to split the command line string explicitly among argument/value pairs and + /// operands, and strictly operands. + /// + /// + /// This regular expression effectively splits a string into two parts; the part before the first "--", and the part + /// after. Instances of "--" not surrounded by a word boundary and those enclosed in quotes are ignored. + /// + private const string StrictOperandSplitRegEx = "(.*?[^\\\"\\\'])?(\\B-{2}\\B)[^\\\"\\\']?(.*)"; + + private CommandLineArguments(string commandLineString, List> argumentList, Dictionary argumentDictionary, List operandList, Type targetType = null) + { + CommandLineString = commandLineString; + ArgumentList = argumentList; + ArgumentDictionary = argumentDictionary; + OperandList = operandList; + TargetType = targetType; + } + + /// + /// Gets or sets a value indicating whether forward slashes are processed as argument delimiters. + /// + public static bool EnableForwardSlash { get; set; } = false; + + /// + /// Gets a dictionary containing the arguments and values specified in the command line arguments with which the + /// application was started. + /// + /// + /// This dictionary contains argument key/value pairs compiled from the and checked against + /// the to combine duplicated pairs into lists where the backing property is a collection, and + /// to overwrite where the backing property is not a collection. + /// + public Dictionary ArgumentDictionary { get; } + + /// + /// Gets the list of arguments specified in the command line arguments with which the application was started. + /// + /// + /// This list contains each argument key/value pair as supplied in the original string, preserving the original order + /// and any duplicated pairs. + /// + public List> ArgumentList { get; } + + /// + /// Gets the command line string from which the arguments were parsed. + /// + public string CommandLineString { get; } + + /// + /// Gets a list containing the operands specified in the command line arguments with which the application was started. + /// + public List OperandList { get; private set; } + + /// + /// Gets the target Type, if applicable. + /// + public Type TargetType { get; } + + private static string ArgumentRegEx => EnableForwardSlash ? ArgumentRegExWithForwardSlash : ArgumentRegExWithoutForwardSlash; + + /// + /// Gets the argument value corresponding to the specified . + /// + /// The index for which the value is to be retrieved. + /// The argument value corresponding to the specified index. + public object this[int index] + { + get + { + return ArgumentList[index].Value; + } + } + + /// + /// Gets the argument value corresponding to the specified from the + /// property. + /// + /// The key for which the value is to be retrieved. + /// The argument value corresponding to the specified key. + public object this[string key] + { + get + { + return ArgumentDictionary[key]; + } + } + + /// + /// Retrieves a collection of gathered from properties in the target + /// marked with the along with the short and long names and help text. + /// + /// The for which the matching properties are to be retrieived. + /// Internal parameter used to identify the calling method. + /// The retrieved collection of . + public static IEnumerable GetArgumentInfo(Type type = null, [CallerMemberName] string caller = default) + { + type ??= CommandLineArgumentsExtensions.GetCallingType(caller); + var retVal = new List(); + + foreach (PropertyInfo property in GetArgumentProperties(type).Values.Distinct()) + { + CustomAttributeData attribute = property.CustomAttributes.FirstOrDefault(a => a.AttributeType.Name == typeof(CommandLineArgumentAttribute).Name); + + if (attribute != default(CustomAttributeData)) + { + retVal.Add(new ArgumentInfo( + shortName: (char)attribute.ConstructorArguments[0].Value, + longName: (string)attribute.ConstructorArguments[1].Value, + helpText: (string)attribute.ConstructorArguments[2].Value, + property: property)); + } + } + + return retVal; + } + + /// + /// Returns a dictionary containing the values specified in the command line arguments with which the application was + /// started, keyed by argument name. + /// + /// The command line arguments with which the application was started. + /// The for which the command line string is to be parsed. + /// + /// The dictionary containing the arguments and values specified in the command line arguments with which the + /// application was started. + /// + public static CommandLineArguments Parse(string commandLineString = default, Type type = null) + { + commandLineString = commandLineString == default || string.IsNullOrEmpty(commandLineString) ? Environment.CommandLine : commandLineString; + + List> argumentList; + List operandList; + + // use the strict operand regular expression to test for/extract the two halves of the string, if the operator is used. + MatchCollection matches = Regex.Matches(commandLineString, StrictOperandSplitRegEx); + + // if there is a match, the string contains the strict operand delimiter. parse the first and second matches accordingly. + if (matches.Count > 0) + { + // the first group of the first match will contain everything in the string prior to the strict operand delimiter, + // so extract the argument key/value pairs and list of operands from that string. + argumentList = GetArgumentList(matches[0].Groups[1].Value); + operandList = GetOperandList(matches[0].Groups[1].Value); + + // the first group of the second match will contain everything in the string after the strict operand delimiter, so + // extract the operands from that string using the strict method. + if (!string.IsNullOrEmpty(matches[0].Groups[3].Value)) + { + List operandListStrict = GetOperandListStrict(matches[0].Groups[3].Value); + operandList.AddRange(operandListStrict); + } + } + else + { + argumentList = GetArgumentList(commandLineString); + operandList = GetOperandList(commandLineString); + } + + var argumentDictionary = GetArgumentDictionary(argumentList, type); + return new CommandLineArguments(commandLineString, argumentList, argumentDictionary, operandList, type); + } + + /// + /// Populates the properties in the invoking class marked with the + /// with the values specified in the list of command line + /// arguments, if present. + /// + /// The command line arguments with which the application was started. + /// Whether to clear the properties before populating them. Defaults to true. + /// Internal parameter used to identify the calling method. + public static void Populate(string commandLineString = default, bool clearExistingValues = true, [CallerMemberName] string caller = default) + { + var type = CommandLineArgumentsExtensions.GetCallingType(caller); + Populate(type, Parse(commandLineString, type), clearExistingValues); + } + + /// + /// Populates the properties in the specified Type marked with the + /// with the values specified in the list of command line + /// arguments, if present. + /// + /// + /// The Type for which the static properties matching the list of command line arguments are to be populated. + /// + /// The command line arguments with which the application was started. + /// Whether to clear the properties before populating them. Defaults to true. + public static void Populate(Type type, string commandLineString = default, bool clearExistingValues = true) + { + Populate(type, Parse(commandLineString, type), clearExistingValues); + } + + /// + /// Populates the properties in the specified Type marked with the + /// with the values specified in the specified argument + /// dictionary, if present. All property values are set to null at the start of the routine. + /// + /// + /// The Type for which the static properties matching the list of command line arguments are to be populated. + /// + /// + /// The Arguments object containing the dictionary containing the argument-value pairs with which the destination + /// properties should be populated and the list of operands. + /// + /// Whether to clear the properties before populating them. Defaults to true. + public static void Populate(Type type, CommandLineArguments arguments, bool clearExistingValues = true) + { + // fetch any properties in the specified type marked with the ArgumentAttribute attribute and clear them + Dictionary properties = GetArgumentProperties(type); + + if (clearExistingValues) + { + ClearProperties(properties); + } + + foreach (string propertyName in properties.Keys) + { + // if the argument dictionary contains a matching argument + if (arguments.ArgumentDictionary.ContainsKey(propertyName)) + { + // retrieve the property and type + PropertyInfo property = properties[propertyName]; + Type propertyType = property.PropertyType; + + // retrieve the value from the argument dictionary + object value = arguments.ArgumentDictionary[propertyName]; + + object convertedValue; + + // if the type of the property is bool and the argument value is empty set the property value to true, + // indicating the argument is present + if (propertyType == typeof(bool)) + { + convertedValue = true; + + // if a value is specified, a bool flag was followed by an operand and the parser interpreted this as key + // value pair because it wasn't aware the flag was backed by a bool. remove the argument from the original + // string and re-parse operands from it to preserve order. + if (!string.IsNullOrEmpty(value.ToString())) + { + var arg = Regex.Matches(arguments.CommandLineString, "(?:[-]{1,2}|\\/)" + propertyName)[0].Value; + arguments.OperandList = GetOperandList(arguments.CommandLineString.Replace(arg, string.Empty)); + } + } + else if (propertyType.IsArray || (propertyType.IsGenericType && propertyType.GetGenericTypeDefinition() == typeof(List<>))) + { + convertedValue = value; + + // next, create a list with the same type as the target property + Type valueType; + + if (propertyType.IsArray) + { + valueType = propertyType.GetElementType(); + } + else + { + valueType = propertyType.GetGenericArguments()[0]; + } + + // create a list to store converted values + Type valueListType = typeof(List<>).MakeGenericType(valueType); + var valueList = (IList)Activator.CreateInstance(valueListType); + + // populate the list + foreach (object v in (List)convertedValue) + { + valueList.Add(ChangeType(v, propertyName, valueType)); + } + + // if the target property is an array, create one and populate it from the list this is surprisingly + // difficult here because we created the source list with the Activator and ToArray() won't work easily. + if (propertyType.IsArray) + { + var valueArray = Array.CreateInstance(propertyType.GetElementType(), valueList.Count); + + for (int i = 0; i < valueArray.Length; i++) + { + valueArray.SetValue(valueList[i], i); + } + + convertedValue = valueArray; + } + else + { + convertedValue = valueList; + } + } + else + { + convertedValue = ChangeType(value, propertyName, propertyType); + } + + // set the target properties' value to the converted value from the argument string + property.SetValue(null, convertedValue); + } + } + + PropertyInfo operandsProperty = GetOperandsProperty(type); + + // check to ensure the target class has a property marked with the Operands attribute; if not GetOperandsProperty() + // will return null. + if (operandsProperty != default) + { + if (operandsProperty.PropertyType.IsAssignableFrom(typeof(List))) + { + operandsProperty.SetValue(null, arguments.OperandList); + } + else + { + operandsProperty.SetValue(null, arguments.OperandList.ToArray()); + } + } + } + + private static object ChangeType(object value, string argument, Type toType) + { + try + { + if (toType.IsEnum) + { + return Enum.Parse(toType, (string)value, true); + } + + return Convert.ChangeType(value, toType, CultureInfo.InvariantCulture); + } + catch (Exception ex) when (ex is InvalidCastException || ex is FormatException || ex is OverflowException || ex is ArgumentNullException) + { + string message = $"Specified value '{value}' for argument '{argument}' (expected type: {toType}). "; + message += "See inner exception for details."; + + throw new ArgumentException(message, ex); + } + } + + private static void ClearProperties(Dictionary properties) + { + foreach (string key in properties.Keys) + { + properties[key].SetValue(null, null); + } + } + + private static Dictionary GetArgumentDictionary(List> argumentList, Type targetType = null) + { + var dict = new ConcurrentDictionary(); + var argumentInfo = targetType == null ? new List() : GetArgumentInfo(targetType); + + foreach (var arg in argumentList) + { + var info = argumentInfo.SingleOrDefault(i => i.ShortName.ToString(CultureInfo.InvariantCulture) == arg.Key || i.LongName == arg.Key); + + if (info != default(ArgumentInfo)) + { + bool added = false; + + foreach (var k in new[] { info.ShortName.ToString(CultureInfo.InvariantCulture), info.LongName }) + { + if (dict.ContainsKey(k)) + { + dict.AddOrUpdate(k, arg.Value, (key, existingValue) => info.IsCollection ? ((List)existingValue).Concat(new[] { arg.Value }).ToList() : (object)arg.Value); + added = true; + break; + } + } + + if (!added) + { + dict.TryAdd(arg.Key, info.IsCollection ? new List(new[] { arg.Value }) : (object)arg.Value); + } + } + else + { + dict.AddOrUpdate(arg.Key, arg.Value, (key, existingValue) => arg.Value); + } + } + + return dict.ToDictionary(a => a.Key, a => a.Value); + } + + private static List> GetArgumentList(string commandLineString) + { + var argumentList = new List>(); + + foreach (Match match in Regex.Matches(commandLineString, ArgumentRegEx)) + { + // the first match of the regular expression used to parse the string will contain the argument name, if one was matched. + if (match.Groups[1].Value == default || string.IsNullOrEmpty(match.Groups[1].Value)) + { + continue; + } + + string fullMatch = match.Groups[0].Value; + string argument = match.Groups[1].Value; + string value = match.Groups[2].Value; + + value = value.TrimOuterQuotes(); + + // check to see if the argument uses a single dash. if so, split the argument name into a char array and add each + // to the list. if a value is specified, it belongs to the final character. + if (Regex.IsMatch(fullMatch, GroupRegEx)) + { + char[] charArray = argument.ToCharArray(); + + // iterate over the characters backwards to more easily assign the value + for (int i = 0; i < charArray.Length; i++) + { + argumentList.Add(new KeyValuePair(charArray[i].ToString(CultureInfo.InvariantCulture), i == charArray.Length - 1 ? value : string.Empty)); + } + } + else + { + argumentList.Add(new KeyValuePair(argument, value)); + } + } + + return argumentList; + } + + private static Dictionary GetArgumentProperties(Type type) + { + Dictionary properties = new Dictionary(); + + foreach (PropertyInfo property in type.GetProperties(BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Static)) + { + // attempt to fetch the ArgumentAttribute of the property + CustomAttributeData attribute = property.CustomAttributes.FirstOrDefault(a => a.AttributeType.Name == typeof(CommandLineArgumentAttribute).Name); + + // if found, extract the Name property and add it to the dictionary + if (attribute != default(CustomAttributeData)) + { + char shortName = (char)attribute.ConstructorArguments[0].Value; + string longName = (string)attribute.ConstructorArguments[1].Value; + + if (!properties.ContainsKey(shortName.ToString(CultureInfo.InvariantCulture)) && !properties.ContainsKey(longName)) + { + properties.Add(shortName.ToString(CultureInfo.InvariantCulture), property); + properties.Add(longName, property); + } + } + } + + return properties; + } + + private static List GetOperandList(string commandLineString) + { + List operands = new List(); + + foreach (Match match in Regex.Matches(commandLineString, ArgumentRegEx)) + { + // the 3rd match of the regular expression used to parse the string will contain the operand, if one was matched. + if (match.Groups[3].Value == default || string.IsNullOrEmpty(match.Groups[3].Value)) + { + continue; + } + + string operand = match.Groups[3].Value; + + operands.Add(operand.TrimOuterQuotes()); + } + + return operands; + } + + private static List GetOperandListStrict(string operandListString) + { + List operands = new List(); + + foreach (Match match in Regex.Matches(operandListString, OperandRegEx)) + { + operands.Add(match.Groups[0].Value); + } + + return operands; + } + + private static PropertyInfo GetOperandsProperty(Type type) + { + PropertyInfo property = type.GetProperties(BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Static) + .FirstOrDefault(p => p.CustomAttributes + .Any(a => a.AttributeType.Name == typeof(OperandsAttribute).Name)); + + if (property != default && property.PropertyType != typeof(string[]) && property.PropertyType != typeof(List)) + { + throw new InvalidCastException("The target for the Operands attribute must be of string[] or List."); + } + + return property; + } + } + + /// + /// Indicates that the property is to be used as the target for automatic population of command line operands when invoking + /// the method. + /// + [AttributeUsage(AttributeTargets.Property, AllowMultiple = false)] + public class OperandsAttribute : Attribute + { + } +} \ No newline at end of file diff --git a/src/slskd/Common/Configuration/CommandLineConfigurationSource.cs b/src/slskd/Common/Configuration/CommandLineConfigurationSource.cs new file mode 100644 index 00000000..a6b46496 --- /dev/null +++ b/src/slskd/Common/Configuration/CommandLineConfigurationSource.cs @@ -0,0 +1,139 @@ +namespace slskd +{ + using Microsoft.Extensions.Configuration; + using System; + using System.Collections.Generic; + using System.Linq; + + /// + /// Defines a command line argument mapping. + /// + public record CommandLineArgument(char ShortName, string LongName, Type Type, string Key, string Description = null); + + /// + /// Extension methods for adding . + /// + public static class CommandLineExtensions + { + /// + /// Adds a command line argument configuration soruce to . + /// + /// The . + /// A list of command line argument mappings. + /// The command line string from which to parse arguments. + /// A value indicating whether configuration keys should be normalized (_, - removed, changed to lowercase). + /// + public static IConfigurationBuilder AddCommandLine(this IConfigurationBuilder builder, IEnumerable map, string commandLine = null, bool normalizeKey = true) + { + if (builder == null) + { + throw new ArgumentNullException(nameof(builder)); + } + + return builder.AddCommandLine(s => + { + s.Map = map; + s.CommandLine = commandLine ?? Environment.CommandLine; + s.NormalizeKey = normalizeKey; + }); + } + + /// + /// Adds a command line argument configuration source to . + /// + /// The . + /// Configures the source. + /// The . + public static IConfigurationBuilder AddCommandLine(this IConfigurationBuilder builder, Action configureSource) + => builder.Add(configureSource); + } + + /// + /// Represents command line arguments as an . + /// + public class CommandLineConfigurationSource : IConfigurationSource + { + /// + /// Builds the for this source. + /// + /// The . + /// A . + public IConfigurationProvider Build(IConfigurationBuilder builder) => new CommandLineConfigurationProvider(this); + + /// + /// Gets or sets a list of command line argument mappings. + /// + public IEnumerable Map { get; set; } + + /// + /// Gets or sets the command line string from which to parse arguments. + /// + public string CommandLine { get; set; } + + /// + /// Gets or sets a value indicating whether configuration keys should be normalized (_, - removed, changed to lowercase). + /// + public bool NormalizeKey { get; set; } + } + + /// + /// A command line argument . + /// + public class CommandLineConfigurationProvider : ConfigurationProvider + { + private IEnumerable Map { get; set; } + private string CommandLine { get; set; } + private bool NormalizeKey { get; set; } + + /// + /// Initializes a new instance with the specified source. + /// + /// The source settings. + public CommandLineConfigurationProvider(CommandLineConfigurationSource source) + { + Map = source.Map; + CommandLine = source.CommandLine; + NormalizeKey = source.NormalizeKey; + } + + /// + /// Parses command line arguments from the specified string and maps them to the specified keys. + /// + public override void Load() + { + var dictionary = CommandLineArguments.Parse(CommandLine).ArgumentDictionary; + + foreach (CommandLineArgument item in Map) + { + var (shortName, longName, type, key, _) = item; + + if (NormalizeKey) + { + key = key.Replace("-", string.Empty).Replace("_", string.Empty).ToLowerInvariant(); + } + + if (string.IsNullOrEmpty(key)) + { + continue; + } + + var arguments = new[] { shortName.ToString(), longName }.Where(i => !string.IsNullOrEmpty(i)); + + foreach (var argument in arguments) + { + if (dictionary.ContainsKey(argument)) + { + var value = dictionary[argument].ToString(); + + if (type == typeof(bool) && string.IsNullOrEmpty(value)) + { + value = "true"; + } + + Data[item.Key] = value; + } + } + } + } + } +} diff --git a/src/slskd/Common/Configuration/EnvironmentVariableConfigurationSource.cs b/src/slskd/Common/Configuration/EnvironmentVariableConfigurationSource.cs new file mode 100644 index 00000000..fe470be6 --- /dev/null +++ b/src/slskd/Common/Configuration/EnvironmentVariableConfigurationSource.cs @@ -0,0 +1,135 @@ +namespace slskd +{ + using Microsoft.Extensions.Configuration; + using System; + using System.Collections.Generic; + using System.Linq; + + /// + /// Defines an environment variable mapping. + /// + public record EnvironmentVariable(string Name, Type Type, string Key, string Description = null); + + /// + /// Extension methods for adding . + /// + public static class EnvironmentVariableConfigurationExtensions + { + /// + /// Adds an environment variable configuration source to . + /// + /// The to add to. + /// A list of environment variable mappings. + /// A prefix to prepend to all variable names. + /// A value indicating whether configuration keys should be normalized (_, - removed, changed to lowercase). + /// The . + public static IConfigurationBuilder AddEnvironmentVariables(this IConfigurationBuilder builder, IEnumerable map, string prefix = null, bool normalizeKey = true) + { + if (builder == null) + { + throw new ArgumentNullException(nameof(builder)); + } + + return builder.AddEnvironmentVariables(s => + { + s.Map = map ?? Enumerable.Empty(); + s.Prefix = prefix ?? string.Empty; + s.NormalizeKey = normalizeKey; + }); + } + + /// + /// Adds an enviroment variable configuration source to . + /// + /// The to add to. + /// Configures the source. + /// The . + public static IConfigurationBuilder AddEnvironmentVariables(this IConfigurationBuilder builder, Action configureSource) + => builder.Add(configureSource); + } + + /// + /// Represents environment variables as an . + /// + public class EnvironmentVariableConfigurationSource : IConfigurationSource + { + /// + /// Builds the for this source. + /// + /// The . + /// A . + public IConfigurationProvider Build(IConfigurationBuilder builder) + { + return new EnvironmentVariableConfigurationProvider(this); + } + + /// + /// Gets or sets a list of enviroment variable mappings. + /// + public IEnumerable Map { get; set; } + + /// + /// Gets or sets a prefix to prepend to all variable names. + /// + public string Prefix { get; set; } + + /// + /// Gets or sets a value indicating whether configuration keys should be normalized (_, - removed, changed to lowercase). + /// + public bool NormalizeKey { get; set; } + } + + /// + /// An enviroment variable . + /// + public class EnvironmentVariableConfigurationProvider : ConfigurationProvider + { + /// + /// Initializes a new instance with the specified source. + /// + /// The source settings. + public EnvironmentVariableConfigurationProvider(EnvironmentVariableConfigurationSource source) + { + Map = source.Map; + NormalizeKey = source.NormalizeKey; + } + + private IEnumerable Map { get; set; } + private bool NormalizeKey { get; set; } + + /// + /// Loads environment variables and maps them to the specified keys. + /// + public override void Load() + { + foreach (var item in Map) + { + var (name, type, key, _) = item; + + if (NormalizeKey) + { + key = key.Replace("_", string.Empty).Replace("-", string.Empty).ToLowerInvariant(); + } + + if (string.IsNullOrEmpty(key) || string.IsNullOrEmpty(name)) + { + continue; + } + + var value = Environment.GetEnvironmentVariable(name); + + if (string.IsNullOrEmpty(value)) + { + continue; + } + + if (type == typeof(bool)) + { + value = value.Equals("true", StringComparison.InvariantCultureIgnoreCase) ? value : "false"; + } + + Data[item.Key] = value; + } + } + } +} diff --git a/src/slskd/Common/Configuration/YamlConfigurationSource.cs b/src/slskd/Common/Configuration/YamlConfigurationSource.cs new file mode 100644 index 00000000..220cc00b --- /dev/null +++ b/src/slskd/Common/Configuration/YamlConfigurationSource.cs @@ -0,0 +1,158 @@ +namespace slskd +{ + using Microsoft.Extensions.Configuration; + using Microsoft.Extensions.FileProviders; + using System; + using System.IO; + using System.Linq; + using YamlDotNet.Core; + using YamlDotNet.RepresentationModel; + + /// + /// Extension methods for adding . + /// + public static class YamlConfigurationExtensions + { + /// + /// Adds a YAML configuration source to . + /// + /// The to add to. + /// Path relative to the base path stored in + /// of . + /// Whether the file is optional. + /// Whether the configuration should be reloaded if the file changes. + /// A value indicating whether configuration keys should be normalized (_, - removed, changed to lowercase). + /// The to use to access the file. + /// The . + public static IConfigurationBuilder AddYamlFile(this IConfigurationBuilder builder, string path, bool optional = true, bool reloadOnChange = false, bool normalizeKeys = true, IFileProvider provider = null) + { + if (builder == null) + { + throw new ArgumentNullException(nameof(builder)); + } + + if (string.IsNullOrEmpty(path)) + { + throw new ArgumentException("File path must be a non-empty string.", nameof(path)); + } + + return builder.AddYamlFile(s => + { + s.Path = path; + s.Optional = optional; + s.ReloadOnChange = reloadOnChange; + s.NormalizeKeys = normalizeKeys; + s.FileProvider = provider; + s.ResolveFileProvider(); + }); + } + + /// + /// Adds a YAML configuration source to . + /// + /// The to add to. + /// Configures the source. + /// The . + public static IConfigurationBuilder AddYamlFile(this IConfigurationBuilder builder, Action configureSource) + => builder.Add(configureSource); + } + + /// + /// Represents a YAML file as an . + /// + public class YamlConfigurationSource : FileConfigurationSource + { + /// + /// Builds the for this source. + /// + /// The . + /// A + public override IConfigurationProvider Build(IConfigurationBuilder builder) + { + EnsureDefaults(builder); + return new YamlConfigurationProvider(this); + } + + /// + /// Gets or sets a value indicating whether configuration keys should be normalized (_, - removed, changed to lowercase). + /// + public bool NormalizeKeys { get; set; } + } + + /// + /// A YAML file based . + /// + public class YamlConfigurationProvider : FileConfigurationProvider + { + /// + /// Initializes a new instance with the specified source. + /// + /// The source settings. + public YamlConfigurationProvider(YamlConfigurationSource source) + : base(source) + { + NormalizeKeys = source.NormalizeKeys; + } + + private bool NormalizeKeys { get; set; } + private string[] NullValues { get; } = new[] { "~", "null", "" }; + + /// + /// Loads the YAML data from a stream. + /// + /// The stream to read. + public override void Load(Stream stream) + { + try + { + using var reader = new StreamReader(stream); + + var yaml = new YamlStream(); + yaml.Load(reader); + + var rootNode = (YamlMappingNode)yaml.Documents[0].RootNode; + + Traverse(rootNode); + } + catch (YamlException e) + { + throw new FormatException("Could not parse the YAML file.", e); + } + } + + private void Traverse(YamlNode root, string path = null) + { + string Normalize(string str) => NormalizeKeys ? str?.Replace("_", string.Empty).Replace("-", string.Empty).ToLowerInvariant() : str; + + if (root is YamlScalarNode scalar) + { + if (Data.ContainsKey(Normalize(path))) + { + throw new FormatException($"A duplicate key '{Normalize(path)}' was found."); + } + + var value = NullValues.Contains(scalar.Value.ToLower()) ? null : scalar.Value; + + if (value != null) + { + Data[Normalize(path)] = NullValues.Contains(scalar.Value.ToLower()) ? null : scalar.Value; + } + } + else if (root is YamlMappingNode map) + { + foreach (var node in map.Children) + { + var key = Normalize(((YamlScalarNode)node.Key).Value); + Traverse(node.Value, path == null ? key : ConfigurationPath.Combine(path, key)); + } + } + else if (root is YamlSequenceNode sequence) + { + for (int i = 0; i < sequence.Children.Count(); i++) + { + Traverse(sequence.Children[i], ConfigurationPath.Combine(path, i.ToString())); + } + } + } + } +} -- cgit v1.2.3 From e9108aa3e747cd5798a4768e7cf9c5aa65d53395 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 23 Jan 2021 13:40:07 -0600 Subject: move Configuration --- .../CommandLineArgumentConfigurationSource.cs | 93 --------- .../EnvironmentVariableConfigurationSource.cs | 76 -------- src/slskd/Common/Options/InstanceOptions.cs | 199 ------------------- src/slskd/Common/Options/RuntimeOptions.cs | 156 --------------- src/slskd/Common/YamlConfigurationSource.cs | 214 --------------------- src/slskd/Configuration.cs | 214 +++++++++++++++++++++ 6 files changed, 214 insertions(+), 738 deletions(-) delete mode 100644 src/slskd/Common/CommandLineArgumentConfigurationSource.cs delete mode 100644 src/slskd/Common/EnvironmentVariableConfigurationSource.cs delete mode 100644 src/slskd/Common/Options/InstanceOptions.cs delete mode 100644 src/slskd/Common/Options/RuntimeOptions.cs delete mode 100644 src/slskd/Common/YamlConfigurationSource.cs create mode 100644 src/slskd/Configuration.cs (limited to 'src') diff --git a/src/slskd/Common/CommandLineArgumentConfigurationSource.cs b/src/slskd/Common/CommandLineArgumentConfigurationSource.cs deleted file mode 100644 index 1762228d..00000000 --- a/src/slskd/Common/CommandLineArgumentConfigurationSource.cs +++ /dev/null @@ -1,93 +0,0 @@ -namespace slskd -{ - using Microsoft.Extensions.Configuration; - using System; - using System.Collections.Generic; - using System.Linq; - using Utility.CommandLine; - - public class Argument - { - public string Description { get; set; } - public char ShortName { get; set; } - public string LongName { get; set; } - public string Key { get; set; } - } - - public static class CommandLineArgumentExtensions - { - public static IConfigurationBuilder MapCommandLineArguments(this IConfigurationBuilder builder, IEnumerable map, string commandLine) - { - if (builder == null) - { - throw new ArgumentNullException(nameof(builder)); - } - - return builder.MapCommandLineArguments(s => - { - s.Map = map; - s.CommandLine = commandLine; - }); - } - - public static IConfigurationBuilder MapCommandLineArguments(this IConfigurationBuilder builder, Action configureSource) - => builder.Add(configureSource); - } - - public class CommandLineArgumentConfigurationSource : IConfigurationSource - { - public IEnumerable Map { get; set; } - public string CommandLine { get; set; } - - public IConfigurationProvider Build(IConfigurationBuilder builder) - { - return new CommandLineArgumentConfigurationProvider(this); - } - } - - public class CommandLineArgumentConfigurationProvider : ConfigurationProvider - { - public CommandLineArgumentConfigurationSource Source { get; set; } - - /// - /// Initializes a new instance with the specified source. - /// - /// The source settings. - public CommandLineArgumentConfigurationProvider(CommandLineArgumentConfigurationSource source) - { - Source = source; - } - - public override void Load() - { - var dictionary = Arguments.Parse(Source.CommandLine).ArgumentDictionary; - - foreach (var item in Source.Map) - { - Console.WriteLine($"Item: {item.Key}"); - - if (string.IsNullOrEmpty(item.Key)) - { - continue; - } - - var arguments = new[] { item.ShortName.ToString(), item.LongName }.Where(i => !string.IsNullOrEmpty(i)); - - foreach (var argument in arguments) - { - if (dictionary.ContainsKey(argument)) - { - var value = dictionary[argument].ToString(); - - if (string.IsNullOrEmpty(value)) - { - value = "true"; - } - - Data[item.Key] = value; - } - } - } - } - } -} diff --git a/src/slskd/Common/EnvironmentVariableConfigurationSource.cs b/src/slskd/Common/EnvironmentVariableConfigurationSource.cs deleted file mode 100644 index 36a8ddf1..00000000 --- a/src/slskd/Common/EnvironmentVariableConfigurationSource.cs +++ /dev/null @@ -1,76 +0,0 @@ -namespace slskd -{ - using Microsoft.Extensions.Configuration; - using System; - using System.Collections.Generic; - - public class EnvironmentVariable - { - public string Description { get; set; } - public string Name { get; set; } - public string Key { get; set; } - } - - public static class EnvironmentVariableConfigurationExtensions - { - public static IConfigurationBuilder MapEnvironmentVariables(this IConfigurationBuilder builder, IEnumerable map) - { - if (builder == null) - { - throw new ArgumentNullException(nameof(builder)); - } - - return builder.MapEnvironmentVariables(s => - { - s.Map = map; - }); - } - - public static IConfigurationBuilder MapEnvironmentVariables(this IConfigurationBuilder builder, Action configureSource) - => builder.Add(configureSource); - } - - public class EnvironmentVariableConfigurationSource : IConfigurationSource - { - public IConfigurationProvider Build(IConfigurationBuilder builder) - { - return new EnvironmentVariableConfigurationProvider(this); - } - - public IEnumerable Map { get; set; } - } - - public class EnvironmentVariableConfigurationProvider : ConfigurationProvider - { - public EnvironmentVariableConfigurationSource Source { get; set; } - /// - /// Initializes a new instance with the specified source. - /// - /// The source settings. - public EnvironmentVariableConfigurationProvider(EnvironmentVariableConfigurationSource source) - { - Source = source; - } - - public override void Load() - { - foreach (var item in Source.Map) - { - if (string.IsNullOrEmpty(item.Key)) - { - continue; - } - - if (!string.IsNullOrEmpty(item.Name)) - { - var value = Environment.GetEnvironmentVariable(item.Name); - - if (!string.IsNullOrEmpty(value)) - { - Data[item.Key] = value; - } - } - } - } - } -} diff --git a/src/slskd/Common/Options/InstanceOptions.cs b/src/slskd/Common/Options/InstanceOptions.cs deleted file mode 100644 index 52b46722..00000000 --- a/src/slskd/Common/Options/InstanceOptions.cs +++ /dev/null @@ -1,199 +0,0 @@ -namespace slskd -{ - using Microsoft.Extensions.Configuration; - using System; - using System.IO; - using System.Linq; - using Utility.CommandLine; - using Utility.EnvironmentVariables; - - public class InstanceOptions - { - [Argument('h', "help", "print usage")] - public static bool ShowHelp { get; private set; } - - [Argument('v', "version", "display version information")] - public static bool ShowVersion { get; private set; } - - [EnvironmentVariable("SLSKD_DEBUG")] - [Configuration("slskd:debug")] - [Argument('d', "debug", "run in debug mode")] - public static bool Debug { get; private set; } - - [EnvironmentVariable("SLSKD_NO_LOGO")] - [Configuration("slskd:no_logo")] - [Argument('n', "no-logo", "suppress logo on startup")] - public static bool DisableLogo { get; private set; } - - [EnvironmentVariable("SLSKD_NO_AUTH")] - [Configuration("slskd:no_auth")] - [Argument('x', "no-auth", "disable authentication for web requests")] - public static bool DisableAuthentication { get; private set; } - - [EnvironmentVariable("SLSKD_INSTANCE_NAME")] - [Configuration("slskd:instance_name")] - [Argument('i', "instance-name", "optional; a unique name for this instance")] - public static string InstanceName { get; private set; } = "default"; - - [EnvironmentVariable("SLSKD_FEATURE_PROMETHEUS")] - [Configuration("slskd:feature:prometheus")] - [Argument('m', "prometheus", "enable collection and publish of prometheus metrics")] - public static bool EnablePrometheus { get; private set; } - - [EnvironmentVariable("SLSKD_FEATURE_SWAGGER")] - [Configuration("slskd:feature:swagger")] - [Argument('s', "swagger", "enable swagger documentation")] - public static bool EnableSwagger { get; private set; } - - [EnvironmentVariable("SLSKD_LOKI")] - [Configuration("slskd:logger:loki")] - [Argument('l', "loki", "optional; the url to a Grafana Loki instance to which to log")] - public static string LokiUrl { get; private set; } - - [EnvironmentVariable("SLSKD_URL_BASE")] - [Configuration("slskd:web:url_base")] - [Argument('b', "url-base", "base url for web requests")] - public static string UrlBase { get; private set; } = "/"; - - [EnvironmentVariable("SLSKD_CONTENT_PATH")] - [Configuration("slskd:web:content_path")] - [Argument('c', "content-path", "path to static web content")] - public static string ContentPath { get; private set; } = Path.Combine(Path.GetDirectoryName(new Uri(AppContext.BaseDirectory).AbsolutePath), "wwwroot"); - - [EnvironmentVariable("SLSKD_JWT_KEY")] - [Configuration("slskd:web:jwt:key")] - [Argument('k', "jwt-key", "optional; the key with which to sign JWTs")] - public static string JwtKey { get; private set; } = Guid.NewGuid().ToString(); - - [EnvironmentVariable("SLSKD_JWT_TTL")] - [Configuration("slskd:web:jwt:ttl")] - [Argument('t', "jwt-ttl", "optional; the TTL for JWTs")] - public static int JwtTTL { get; private set; } = 604800000; - - [EnvironmentVariable("SLSKD_USERNAME")] - [Configuration("soulseek:username")] - [Argument('u', "username", "the username for the Soulseek network")] - public static string Username { get; private set; } - - [EnvironmentVariable("SLSKD_PASSWORD")] - [Configuration("soulseek:password")] - [Argument('p', "password", "the password for the Soulseek network")] - public static string Password { get; private set; } - - public static bool EnableLoki { get; private set; } - - //public static void Populate(string configurationFile = null, bool argumentsOnly = false) - //{ - // if (!argumentsOnly) - // { - // try - // { - // EnvironmentVariables.Populate(typeof(InstanceOptions)); - // } - // catch (Exception ex) - // { - // Console.WriteLine($"Error parsing environment variables: {ex.Message}"); - // return; - // } - - // try - // { - // var config = new ConfigurationBuilder() - // .SetBasePath(Directory.GetCurrentDirectory()) - // .AddMapping(new[] - // { - // new OptionMap { - // Description = "run in debug mode", - // EnvironmentVariable = "SLSK_DEBUG", - // ShortName = 'd', - // LongName = "debug", - // Key = "slskd:debug" - // }, - // new OptionMap { - // Description = "optional; a unique name for this instance", - // EnvironmentVariable = "SLSK_INSTANCE_NAME", - // ShortName = 'i', - // LongName = "instance-name", - // Key = "slskd:instancename" - // } - // }, Environment.CommandLine, configurationFile, optional: true, reloadOnChange: false) - // .Build(); - - // Console.WriteLine(config.GetDebugView()); - - // config.Populate(typeof(InstanceOptions)); - // } - // catch (Exception ex) - // { - // Console.WriteLine($"Error parsing configuration file '{configurationFile}': {ex.Message}"); - // return; - // } - // } - - // try - // { - // Arguments.Populate(typeof(InstanceOptions), clearExistingValues: false); - // } - // catch (Exception ex) - // { - // Console.WriteLine($"Error parsing command line input: {ex.Message}"); - // return; - // } - - // EnableLoki = !string.IsNullOrEmpty(LokiUrl); - // UrlBase = UrlBase.StartsWith("/") ? UrlBase : "/" + UrlBase; - // ContentPath = Path.GetFullPath(ContentPath); - //} - - public static void PrintHelp() - { - PrintArguments(); - } - - public static void PrintArguments() - { - static string GetLongName(ArgumentInfo info) - => info.Property.PropertyType == typeof(bool) ? info.LongName : $"{info.LongName} <{info.Property.PropertyType.Name.ToLowerInvariant()}>"; - - static string GetShortName(ArgumentInfo info) - => info.ShortName > 0 ? $"-{info.ShortName}|" : " "; - - var arguments = Arguments.GetArgumentInfo(typeof(InstanceOptions)); - var longestName = arguments.Select(a => GetLongName(a)).Max(n => n.Length); - - Console.WriteLine("\nusage: slskd [arguments]\n"); - Console.WriteLine("arguments:\n"); - foreach (var info in arguments) - { - var envar = info.Property.CustomAttributes - ?.Where(a => a.AttributeType == typeof(EnvironmentVariableAttribute)).FirstOrDefault() - ?.ConstructorArguments.FirstOrDefault().Value; - - var result = $" {GetShortName(info)}--{GetLongName(info).PadRight(longestName + 3)}{info.HelpText}"; - Console.WriteLine(result); - } - } - - public static void PrintEnvironmentVariables() - { - static string GetEnvironmentVariableName(ArgumentInfo info, bool includeType = false) - => info.Property.CustomAttributes - ?.Where(a => a.AttributeType == typeof(EnvironmentVariableAttribute)).FirstOrDefault() - ?.ConstructorArguments.FirstOrDefault().Value?.ToString() + (includeType ? $" <{info.Property.PropertyType.Name.ToLowerInvariant()}>" : ""); - - var arguments = Arguments.GetArgumentInfo(typeof(InstanceOptions)); - var longestName = arguments.Select(a => GetEnvironmentVariableName(a, includeType: true)).Where(a => a != null).Max(n => n.Length); - - Console.WriteLine("\nenvironment variables (arguments have precedence):\n"); - foreach (var info in arguments) - { - var envar = GetEnvironmentVariableName(info, includeType: false); - - if (string.IsNullOrEmpty(envar)) continue; - - var result = $" {GetEnvironmentVariableName(info, includeType: true).PadRight(longestName + 3)}{info.HelpText}"; - Console.WriteLine(result); - } - } - } -} diff --git a/src/slskd/Common/Options/RuntimeOptions.cs b/src/slskd/Common/Options/RuntimeOptions.cs deleted file mode 100644 index cded2334..00000000 --- a/src/slskd/Common/Options/RuntimeOptions.cs +++ /dev/null @@ -1,156 +0,0 @@ -namespace slskd -{ - using System; - using System.Collections.Generic; - - public class RuntimeOptions - { - public static IEnumerable EnvironmentVariableMap => new[] - { - new EnvironmentVariable { - Description = "run in debug mode", - Name = "SLSK_DEBUG", - Key = "slskd:debug" - }, - new EnvironmentVariable { - Description = "optional; a unique name for this instance", - Name = "SLSK_INSTANCE_NAME", - Key = "slskd:instancename" - }, - new EnvironmentVariable { - Description = "enable collection and publish of prometheus metrics", - Name = "SLSK_PROMETHEUS", - Key = "slskd:feature:prometheus" - }, - new EnvironmentVariable { - Description = "enable swagger documentation", - Name = "SLSK_SWAGGER", - Key = "slskd:feature:swagger" - }, - new EnvironmentVariable { - Description = "jwt signing key", - Name = "SLSKD_JWT_KEY", - Key = "slskd:web:jwt:key" - } - }; - - public static IEnumerable ArgumentMap => new[] - { - new Argument - { - Description = "print usage", - ShortName = 'h', - LongName = "help", - Key = "slskd:showhelp" - }, - new Argument { - Description = "display version information", - ShortName = 'v', - LongName = "version", - Key = "slskd:showversion" - }, - new Argument { - Description = "run in debug mode", - ShortName = 'd', - LongName = "debug", - Key = "slskd:debug" - }, - new Argument - { - Description = "", - ShortName = 'i', - LongName = "instance-name", - Key = "slskd:instancename" - } - }; - - public class slskd - { - public bool ShowHelp { get; private set; } = false; - public bool ShowVersion { get; private set; } = false; - public bool Debug { get; private set; } = false; - public bool NoLogo { get; private set; } = false; - public bool NoAuth { get; private set; } = false; - public string InstanceName { get; private set; } = "default"; - public FeatureOptions Feature { get; private set; } = new FeatureOptions(); - public LoggerOptions Logger { get; private set; } = new LoggerOptions(); - public WebOptions Web { get; private set; } = new WebOptions(); - - public class FeatureOptions - { - public bool Prometheus { get; private set; } = false; - public bool Swagger { get; private set; } = false; - } - - public class LoggerOptions - { - public string Loki { get; private set; } = null; - } - - public class WebOptions - { - public string UrlBase { get; private set; } = "/"; - public string ContentPath { get; private set; } = "wwwroot"; - public JwtOptions Jwt { get; private set; } = new JwtOptions(); - - public class JwtOptions - { - public int TTL { get; private set; } = 1234567890; - public string Key { get; private set; } = Guid.NewGuid().ToString(); - } - } - } - - public class Soulseek - { - public string Username { get; set; } = InstanceOptions.Username; - public string Password { get; set; } = InstanceOptions.Password; - public int ListenPort { get; set; } = 50000; - public DistributedNetworkOptions DistributedNetwork { get; set; } - public ConnectionOptions Connection { get; set; } - - public class DistributedNetworkOptions - { - public bool Enabled { get; set; } = true; - public int ChildLimit { get; set; } = 10; - } - - public class ConnectionOptions - { - public TimeoutOptions Timeout { get; set; } - public BufferOptions Buffer { get; set; } - - public class TimeoutOptions - { - public int Connect { get; set; } = 5000; - public int Inactivity { get; set; } = 15000; - } - - public class BufferOptions - { - public int Read { get; set; } = 16384; - public int Write { get; set; } = 16384; - } - } - } - - public class Authentication - { - public IEnumerable Users { get; set; } - public IEnumerable ApiKeys { get; set; } - - public class User - { - public string Name { get; set; } - public string Password { get; set; } - public Role Role { get; set; } - } - - public class ApiKey - { - public string Key { get; set; } - public Role Role { get; set; } - } - } - } -} diff --git a/src/slskd/Common/YamlConfigurationSource.cs b/src/slskd/Common/YamlConfigurationSource.cs deleted file mode 100644 index a7c379e3..00000000 --- a/src/slskd/Common/YamlConfigurationSource.cs +++ /dev/null @@ -1,214 +0,0 @@ -/* - █▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀ ▀▀▀▀▀▀▀▀▀▀▀▀▀▀ ▀▀▀ ▀ ▀ ▀▀ - █ The MIT License (MIT) - █ - █ Copyright (c) 2021 JP Dillingham (jp@dillingham.ws) - █ - █ Permission is hereby granted, free of charge, to any person obtaining a copy - █ of this software and associated documentation files (the "Software"), to deal - █ in the Software without restriction, including without limitation the rights - █ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - █ copies of the Software, and to permit persons to whom the Software is - █ furnished to do so, subject to the following conditions: - █ - █ The above copyright notice and this permission notice shall be included in all - █ copies or substantial portions of the Software. - █ - █ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - █ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - █ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - █ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - █ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - █ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - █ SOFTWARE. - █ - ▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀ ▀▀ ▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀██ - ██ - ▀█▄ ██ ▄█▀ - ▀████▀ - ▀▀ */ - -namespace slskd -{ - using Microsoft.Extensions.Configuration; - using Microsoft.Extensions.FileProviders; - using System; - using System.IO; - using System.Linq; - using YamlDotNet.Core; - using YamlDotNet.RepresentationModel; - - /// - /// Extension methods for adding . - /// - public static class YamlConfigurationExtensions - { - /// - /// Adds the YAML configuration provider at to . - /// - /// The to add to. - /// Path relative to the base path stored in - /// of . - /// The . - public static IConfigurationBuilder AddYamlFile(this IConfigurationBuilder builder, string path) - { - return AddYamlFile(builder, provider: null, path: path, optional: false, reloadOnChange: false); - } - - /// - /// Adds the YAML configuration provider at to . - /// - /// The to add to. - /// Path relative to the base path stored in - /// of . - /// Whether the file is optional. - /// The . - public static IConfigurationBuilder AddYamlFile(this IConfigurationBuilder builder, string path, bool optional) - { - return AddYamlFile(builder, provider: null, path: path, optional: optional, reloadOnChange: false); - } - - /// - /// Adds the YAML configuration provider at to . - /// - /// The to add to. - /// Path relative to the base path stored in - /// of . - /// Whether the file is optional. - /// Whether the configuration should be reloaded if the file changes. - /// The . - public static IConfigurationBuilder AddYamlFile(this IConfigurationBuilder builder, string path, bool optional, bool reloadOnChange) - { - return AddYamlFile(builder, provider: null, path: path, optional: optional, reloadOnChange: reloadOnChange); - } - - /// - /// Adds a YAML configuration source to . - /// - /// The to add to. - /// The to use to access the file. - /// Path relative to the base path stored in - /// of . - /// Whether the file is optional. - /// Whether the configuration should be reloaded if the file changes. - /// The . - public static IConfigurationBuilder AddYamlFile(this IConfigurationBuilder builder, IFileProvider provider, string path, bool optional, bool reloadOnChange) - { - if (builder == null) - { - throw new ArgumentNullException(nameof(builder)); - } - if (string.IsNullOrEmpty(path)) - { - throw new ArgumentException("File path must be a non-empty string.", nameof(path)); - } - - return builder.AddYamlFile(s => - { - s.FileProvider = provider; - s.Path = path; - s.Optional = optional; - s.ReloadOnChange = reloadOnChange; - s.ResolveFileProvider(); - }); - } - - /// - /// Adds a YAML configuration source to . - /// - /// The to add to. - /// Configures the source. - /// The . - public static IConfigurationBuilder AddYamlFile(this IConfigurationBuilder builder, Action configureSource) - => builder.Add(configureSource); - } - - /// - /// Represents a YAML file as an . - /// - public class YamlConfigurationSource : FileConfigurationSource - { - /// - /// Builds the for this source. - /// - /// The . - /// A - public override IConfigurationProvider Build(IConfigurationBuilder builder) - { - EnsureDefaults(builder); - return new YamlConfigurationProvider(this); - } - } - - /// - /// A YAML file based . - /// - public class YamlConfigurationProvider : FileConfigurationProvider - { - /// - /// Initializes a new instance with the specified source. - /// - /// The source settings. - public YamlConfigurationProvider(YamlConfigurationSource source) : base(source) { } - - private string[] NullValues { get; } = new[] { "~", "null", "" }; - - /// - /// Loads the YAML data from a stream. - /// - /// The stream to read. - public override void Load(Stream stream) - { - try - { - using var reader = new StreamReader(stream); - - var yaml = new YamlStream(); - yaml.Load(reader); - - var rootNode = (YamlMappingNode)yaml.Documents[0].RootNode; - - Traverse(rootNode); - } - catch (YamlException e) - { - throw new FormatException("Could not parse the YAML file.", e); - } - } - - private void Traverse(YamlNode root, string path = null) - { - static string Clean(string str) => str?.Replace("_", string.Empty).Replace("-", string.Empty); - - if (root is YamlScalarNode scalar) - { - if (Data.ContainsKey(Clean(path))) - { - throw new FormatException($"A duplicate key '{Clean(path)}' was found."); - } - - var value = NullValues.Contains(scalar.Value.ToLower()) ? null : scalar.Value; - - if (value != null) - { - Data[Clean(path)] = NullValues.Contains(scalar.Value.ToLower()) ? null : scalar.Value; - } - } - else if (root is YamlMappingNode map) - { - foreach (var node in map.Children) - { - var key = Clean(((YamlScalarNode)node.Key).Value); - Traverse(node.Value, path == null ? key : ConfigurationPath.Combine(path, key)); - } - } - else if (root is YamlSequenceNode sequence) - { - for (int i = 0; i < sequence.Children.Count(); i++) - { - Traverse(sequence.Children[i], ConfigurationPath.Combine(path, i.ToString())); - } - } - } - } -} diff --git a/src/slskd/Configuration.cs b/src/slskd/Configuration.cs new file mode 100644 index 00000000..da7ccf48 --- /dev/null +++ b/src/slskd/Configuration.cs @@ -0,0 +1,214 @@ +namespace slskd +{ + using System; + using System.Collections.Generic; + + public record Option(char ShortName, string LongName, string EnvironmentVariable, Type Type, string Key, string Description = null); + + public static class Configuration + { + public static EnvironmentVariable ToEnvironmentVariable(this Option option) + => new EnvironmentVariable(option.EnvironmentVariable, option.Type, option.Key, option.Description); + + public static CommandLineArgument ToCommandLineArgument(this Option option) + => new CommandLineArgument(option.ShortName, option.LongName, option.Type, option.Key, option.Description); + + public static IEnumerable