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 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