diff options
| author | JP Dillingham <jpdillingham@gmail.com> | 2021-02-07 20:57:15 -0600 |
|---|---|---|
| committer | GitHub <noreply@github.com> | 2021-02-07 20:57:15 -0600 |
| commit | e4a68f8cf75fbe8d00f05b710b4830f9d756e6e2 (patch) | |
| tree | d7ef3880ab54910e8be81a4c57f7e4d37e89dcbd | |
| parent | 07d221c14889d2db99276a9a03c0e067f8365155 (diff) | |
| parent | 30322e2d2461e4839269b52f1138f22dd18c6305 (diff) | |
| download | slskd-e4a68f8cf75fbe8d00f05b710b4830f9d756e6e2.tar.gz | |
Merge pull request #37 from slskd/config-option
Add the ability to specify the config file location
| -rw-r--r-- | src/slskd/Common/Configuration/EnvironmentVariables.cs | 185 | ||||
| -rw-r--r-- | src/slskd/Common/Validation/FileExistsAttribute.cs | 11 | ||||
| -rw-r--r-- | src/slskd/Options.cs | 46 | ||||
| -rw-r--r-- | src/slskd/Program.cs | 33 |
4 files changed, 243 insertions, 32 deletions
diff --git a/src/slskd/Common/Configuration/EnvironmentVariables.cs b/src/slskd/Common/Configuration/EnvironmentVariables.cs new file mode 100644 index 00000000..0ccda3cb --- /dev/null +++ b/src/slskd/Common/Configuration/EnvironmentVariables.cs @@ -0,0 +1,185 @@ +namespace slskd.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; + + /// <summary> + /// Indicates that the property is to be used as a target for automatic population of values from environment variables + /// when invoking the <see cref="EnvironmentVariables.Populate(Type, string)"/> method. + /// </summary> + [AttributeUsage(AttributeTargets.Property, AllowMultiple = false)] + public class EnvironmentVariableAttribute : Attribute + { + /// <summary> + /// Initializes a new instance of the <see cref="EnvironmentVariableAttribute"/> class. + /// </summary> + /// <param name="name">The name of the environment variable</param> + public EnvironmentVariableAttribute(string name) + { + Name = name; + } + + /// <summary> + /// Gets or sets the name of the environment variable. + /// </summary> + public string Name { get; set; } + } + + /// <summary> + /// Provides static methods used to populate properties from environment variable values. + /// </summary> + public static class EnvironmentVariables + { + /// <summary> + /// Populates the properties in the invoking class marked with the + /// <see cref="EnvironmentVariableAttribute"/><see cref="Attribute"/> with the values specified in environment variables. + /// </summary> + /// <param name="caller">Internal parameter used to identify the calling method.</param> + /// <param name="prefix">The optional prefix for variable names.</param> + public static void Populate(string prefix = null, [CallerMemberName] string caller = default) + { + Populate(GetCallingType(caller), prefix); + } + + /// <summary> + /// Populates the properties in the invoking class marked with the + /// <see cref="EnvironmentVariableAttribute"/><see cref="Attribute"/> with the values specified in environment variables. + /// </summary> + /// <param name="type"> + /// The Type for which the static properties matching the list of environment variables are to be populated. + /// </param> + /// <param name="prefix">The optional prefix for variable names.</param> + public static void Populate(Type type, string prefix = "") + { + prefix ??= string.Empty; + + var targetProperties = GetTargetProperties(type); + + foreach (var property in targetProperties) + { + var propertyType = property.Value.PropertyType; + + string value = Environment.GetEnvironmentVariable(prefix + 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) + { + throw new InvalidOperationException($"Unable to determine the containing type of the calling method '{caller}'. Explicitly specify the originating Type."); + } + + return callingMethod.DeclaringType; + } + + 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); + } + } + + private static Dictionary<string, PropertyInfo> GetTargetProperties(Type type) + { + Dictionary<string, PropertyInfo> properties = new Dictionary<string, PropertyInfo>(); + + 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(EnvironmentVariableAttribute).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; + } + } +}
\ No newline at end of file diff --git a/src/slskd/Common/Validation/FileExistsAttribute.cs b/src/slskd/Common/Validation/FileExistsAttribute.cs index 5453c0ba..8493b783 100644 --- a/src/slskd/Common/Validation/FileExistsAttribute.cs +++ b/src/slskd/Common/Validation/FileExistsAttribute.cs @@ -7,11 +7,14 @@ { protected override ValidationResult IsValid(object value, ValidationContext validationContext) { - var file = Path.GetFullPath(value.ToString()); - - if (!string.IsNullOrEmpty(file) && !File.Exists(file)) + if (value != null) { - return new ValidationResult($"The {validationContext.DisplayName} field specifies a non-existent file '{file}'."); + var file = Path.GetFullPath(value?.ToString()); + + if (!string.IsNullOrEmpty(file) && !File.Exists(file)) + { + return new ValidationResult($"The {validationContext.DisplayName} field specifies a non-existent file '{file}'."); + } } return ValidationResult.Success; diff --git a/src/slskd/Options.cs b/src/slskd/Options.cs index c8fb197e..4ebc8bdc 100644 --- a/src/slskd/Options.cs +++ b/src/slskd/Options.cs @@ -15,7 +15,7 @@ public bool Debug { get; private set; } = Debugger.IsAttached; public bool NoLogo { get; private set; } = false; - public string InstanceName { get; private set; } = "default"; + public string InstanceName { get; private set; } = "default"; [Validate] public DirectoriesOptions Directories { get; private set; } = new DirectoriesOptions(); [Validate] @@ -205,6 +205,14 @@ Default: Defaults.NoLogo, Description: "suppress logo on startup"), new( + ShortName: 'c', + LongName: "config", + EnvironmentVariable: "CONFIG", + Key: null, + Type: typeof(string), + Default: Program.DefaultConfigurationFile, + Description: "path to configuration file"), + new( ShortName: 'i', LongName: "instance-name", EnvironmentVariable: "INSTANCE_NAME", @@ -219,7 +227,7 @@ Key: "slskd:directories:downloads", Type: typeof(string), Default: Defaults.Directories.Downloads, - Description: "the path where downloaded files are saved"), + Description: "path where downloaded files are saved"), new( ShortName: 's', LongName: "shared", @@ -227,7 +235,7 @@ Key: "slskd:directories:shared", Type: typeof(string), Default: Defaults.Directories.Shared, - Description: "the path to shared files"), + Description: "path to shared files"), new( ShortName: 'l', LongName: "http-port", @@ -258,7 +266,7 @@ EnvironmentVariable: "HTTPS_CERT_PFX", Key: "slskd:web:https:certificate:pfx", Type: typeof(string), - Default: null, + Default: Defaults.Web.Https.Certificate.Pfx, Description: "path to X509 certificate .pfx"), new( ShortName: default, @@ -266,7 +274,7 @@ EnvironmentVariable: "HTTPS_CERT_PASSWORD", Key: "slskd:web:https:certificate:password", Type: typeof(string), - Default: null, + Default: Defaults.Web.Https.Certificate.Password, Description: "X509 certificate password"), new( ShortName: default, @@ -299,7 +307,7 @@ Key: "slskd:web:authentication:username", Type: typeof(string), Default: Defaults.Web.Authentication.Username, - Description: "the username for the web UI"), + Description: "the username for web UI"), new( ShortName: 'p', LongName: "password", @@ -315,7 +323,7 @@ Key: "slskd:web:authentication:jwt:key", Type: typeof(string), Default: Defaults.Web.Authentication.Jwt.Key, - Description: "the key with which to sign JWTs"), + Description: "JWT signing key"), new( ShortName: default, LongName: "jwt-ttl", @@ -323,7 +331,7 @@ Key: "slskd:web:authentication:jwt:ttl", Type: typeof(int), Default: Defaults.Web.Authentication.Jwt.Ttl, - Description: "the TTL for JWTs"), + Description: "TTL for JWTs"), new( ShortName: default, LongName: "prometheus", @@ -347,7 +355,7 @@ Key: "slskd:logger:loki", Type: typeof(string), Default: Defaults.Logger.Loki, - Description: "optional; the url to a Grafana Loki instance to which to log"), + Description: "optional; url to a Grafana Loki instance to which to log"), new( ShortName: default, LongName: "slsk-username", @@ -355,7 +363,7 @@ Key: "slskd:soulseek:username", Type: typeof(string), Default: Defaults.Soulseek.Username, - Description: "the username for the Soulseek network"), + Description: "username for the Soulseek network"), new( ShortName: default, LongName: "slsk-password", @@ -363,7 +371,7 @@ Key: "slskd:soulseek:password", Type: typeof(string), Default: Defaults.Soulseek.Password, - Description: "the password for the Soulseek network"), + Description: "password for the Soulseek network"), new( ShortName: default, LongName: "slsk-listen-port", @@ -371,7 +379,7 @@ Key: "slskd:soulseek:listenport", Type: typeof(int), Default: Defaults.Soulseek.ListenPort, - Description: "the port on which to listen for incoming connections"), + Description: "port on which to listen for incoming connections"), new( ShortName: default, LongName: "slsk-diag-level", @@ -379,7 +387,7 @@ Key: "slskd:soulseek:diagnosticlevel", Type: typeof(DiagnosticLevel), Default: Defaults.Soulseek.DiagnosticLevel, - Description: "the minimum diagnostic level (None, Warning, Info, Debug)"), + Description: "minimum diagnostic level (None, Warning, Info, Debug)"), new( ShortName: default, LongName: "slsk-no-dnet", @@ -387,7 +395,7 @@ Key: "slskd:soulseek:distributednetwork:disabled", Type: typeof(bool), Default: Defaults.Soulseek.DistributedNetwork.Disabled, - Description: "disables the distributed network"), + Description: "disable the distributed network"), new( ShortName: default, LongName: "slsk-dnet-children", @@ -395,7 +403,7 @@ Key: "slskd:soulseek:distributednetwork:childlimit", Type: typeof(int), Default: Defaults.Soulseek.DistributedNetwork.ChildLimit, - Description: "the limit for the number of distributed children"), + Description: "max number of distributed children"), new( ShortName: default, LongName: "slsk-connection-timeout", @@ -403,7 +411,7 @@ Key: "slskd:soulseek:connection:timeout:connect", Type: typeof(int), Default: Defaults.Soulseek.Connection.Timeout.Connect, - Description: "the connection timeout, in miliseconds"), + Description: "connection timeout, in miliseconds"), new( ShortName: default, LongName: "slsk-inactivity-timeout", @@ -411,7 +419,7 @@ Key: "slskd:soulseek:connection:timeout:inactivity", Type: typeof(int), Default: Defaults.Soulseek.Connection.Timeout.Inactivity, - Description: "the connection inactivity timeout, in miliseconds"), + Description: "connection inactivity timeout, in miliseconds"), new( ShortName: default, LongName: "slsk-read-buffer", @@ -419,7 +427,7 @@ Key: "slskd:soulseek:connection:buffer:read", Type: typeof(int), Default: Defaults.Soulseek.Connection.Buffer.Read, - Description: "the read buffer size for connections"), + Description: "read buffer size for connections"), new( ShortName: default, LongName: "slsk-write-buffer", @@ -427,7 +435,7 @@ Key: "slskd:soulseek:connection:buffer:write", Type: typeof(int), Default: Defaults.Soulseek.Connection.Buffer.Write, - Description: "the write buffer size for connections"), + Description: "write buffer size for connections"), }; } }
\ No newline at end of file diff --git a/src/slskd/Program.cs b/src/slskd/Program.cs index 373cad67..7c6736a3 100644 --- a/src/slskd/Program.cs +++ b/src/slskd/Program.cs @@ -3,6 +3,8 @@ using Microsoft.AspNetCore; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; + using Microsoft.Extensions.FileProviders; + using Microsoft.Extensions.FileProviders.Physical; using Prometheus.DotNetRuntime; using Serilog; using Serilog.Events; @@ -22,6 +24,8 @@ { public static IConfigurationBuilder AddConfigurationProviders(this IConfigurationBuilder builder, string environmentVariablePrefix, string configurationFile) { + configurationFile = Path.GetFullPath(configurationFile); + return builder .AddDefaultValues( map: Options.Map.Select(o => o.ToDefaultValue())) @@ -29,9 +33,10 @@ prefix: environmentVariablePrefix, map: Options.Map.Select(o => o.ToEnvironmentVariable())) .AddYamlFile( - path: Path.Combine(AppContext.BaseDirectory, configurationFile), + path: Path.GetFileName(configurationFile), optional: true, - reloadOnChange: false) + reloadOnChange: false, + provider: new PhysicalFileProvider(Path.GetDirectoryName(configurationFile), ExclusionFilters.None)) .AddCommandLine( commandLine: Environment.CommandLine, map: Options.Map.Select(o => o.ToCommandLineArgument())); @@ -40,9 +45,9 @@ public class Program { - private static readonly string AppName = "slskd"; - private static readonly string ConfigurationFile = $"{AppName}.yml"; - private static readonly string EnvironmentVariablePrefix = $"{AppName.ToUpperInvariant()}_"; + public static readonly string AppName = "slskd"; + public static readonly string DefaultConfigurationFile = $"{AppName}.yml"; + public static readonly string EnvironmentVariablePrefix = $"{AppName.ToUpperInvariant()}_"; public static Guid InvocationId { get; } = Guid.NewGuid(); public static int ProcessId { get; } = Environment.ProcessId; @@ -65,12 +70,17 @@ [CommandLineArgument('g', "generate-cert", "generate X509 certificate and password for HTTPs")] private static bool GenerateCertificate { get; set; } + [EnvironmentVariable("CONFIG")] + [CommandLineArgument('c', "config", "path to configuration file")] + private static string ConfigurationFile { get; set; } = DefaultConfigurationFile; + private static Options Options { get; } = new Options(); - private static IConfigurationRoot Configuration { get; set; } + private static IConfigurationRoot Configuration { get; set; } public static void Main(string[] args) { - CommandLineArguments.Populate(); + EnvironmentVariables.Populate(prefix: EnvironmentVariablePrefix); + CommandLineArguments.Populate(clearExistingValues: false); if (ShowVersion) { @@ -117,7 +127,7 @@ } catch (Exception ex) { - Console.WriteLine($"Invalid configuration: {ex.Message}"); + Console.WriteLine($"Invalid configuration: {(Options.Debug ? ex : ex.Message)}"); return; } @@ -181,6 +191,11 @@ var logger = Log.ForContext<Program>(); + if (ConfigurationFile != DefaultConfigurationFile && !File.Exists(ConfigurationFile)) + { + logger.Warning($"Specified configuration file '{ConfigurationFile}' could not be found and was not loaded."); + } + logger.Information("Version: {Version}", Version); logger.Information("Instance Name: {InstanceName}", Options.InstanceName); logger.Information("Invocation ID: {InvocationId}", InvocationId); @@ -292,7 +307,7 @@ { var (_, _, environmentVariable, key, type, defaultValue, description) = item; - if (string.IsNullOrEmpty(environmentVariable) || string.IsNullOrEmpty(key)) + if (string.IsNullOrEmpty(environmentVariable)) { continue; } |
