aboutsummaryrefslogtreecommitdiffstats
path: root/src
diff options
context:
space:
mode:
authorJP Dillingham <jpdillingham@gmail.com>2021-01-21 18:00:40 -0600
committerJP Dillingham <jpdillingham@gmail.com>2021-01-21 18:00:40 -0600
commit4afc5f54c37a1bcc7b2593e4a04d4cdf9c5f8b12 (patch)
tree7a0591cd6d903eb017ff4b5cb8c88169abd37658 /src
parent4876d4a5f024e2223312e95999f9be12bd8511fc (diff)
downloadslskd-4afc5f54c37a1bcc7b2593e4a04d4cdf9c5f8b12.tar.gz
more wip
Diffstat (limited to 'src')
-rw-r--r--src/slskd/Configuration.cs153
-rw-r--r--src/slskd/Options.cs46
-rw-r--r--src/slskd/Program.cs168
-rw-r--r--src/slskd/Startup.cs38
-rw-r--r--src/slskd/config.yml32
5 files changed, 291 insertions, 146 deletions
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<string>(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<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(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<User> Users { get; set; }
- public IEnumerable<ApiKey> 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<AssemblyInformationalVersionAttribute>().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<Startup>();
+ private static string ComputeVersion()
+ {
+ var assembly = Assembly.GetExecutingAssembly();
+ var assemblyVersion = assembly.GetName().Version;
+ var informationVersion = assembly.GetCustomAttribute<AssemblyInformationalVersionAttribute>().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<Options.Soulseek>()
- .Bind(Configuration.GetSection("soulseek"));
+ //services.AddOptions<Options.Soulseek>()
+ // .Bind(Configuration.GetSection("soulseek"));
- services.PostConfigure<List<Options.User>>(slskd =>
- {
- Console.WriteLine($"config updated");
- Console.WriteLine(JsonSerializer.Serialize(slskd));
- });
+ //services.PostConfigure<List<Options.User>>(slskd =>
+ //{
+ // Console.WriteLine($"config updated");
+ // Console.WriteLine(JsonSerializer.Serialize(slskd));
+ //});
- services.AddOptions<List<string>>().Bind(Configuration.GetSection("sparse"));
- services.PostConfigure<List<string>>(s => Console.WriteLine(JsonSerializer.Serialize(s)));
+ //services.AddOptions<List<string>>().Bind(Configuration.GetSection("sparse"));
+ //services.PostConfigure<List<string>>(s => Console.WriteLine(JsonSerializer.Serialize(s)));
- services.AddOptions<List<Options.User>>().Bind(Configuration.GetSection("users"));
+ //services.AddOptions<List<Options.User>>().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<Options.Soulseek> optionsAccessor,
- IOptionsMonitor<List<Options.User>> users,
- IOptionsMonitor<List<string>> sparse,
+ //IOptionsMonitor<Options.Soulseek> optionsAccessor,
+ //IOptionsMonitor<List<Options.User>> users,
+ //IOptionsMonitor<List<string>> 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