From 9bc54bc17c4bbb6146c416b84748492efde40754 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 23 Apr 2022 17:27:33 -0500 Subject: refactor Program to use .NET 6 conventions --- src/slskd/Program.cs | 583 +++++++++++++++++++++++++++++++++++++++++---------- 1 file changed, 474 insertions(+), 109 deletions(-) (limited to 'src/slskd/Program.cs') diff --git a/src/slskd/Program.cs b/src/slskd/Program.cs index a5c35dca..1e51cc5b 100644 --- a/src/slskd/Program.cs +++ b/src/slskd/Program.cs @@ -26,19 +26,42 @@ namespace slskd using System.Net; using System.Reflection; using System.Security.Cryptography.X509Certificates; - using Microsoft.AspNetCore; + using System.Text; + using System.Text.Json.Serialization; + using System.Threading.Tasks; + using Microsoft.AspNetCore.Authentication.JwtBearer; + using Microsoft.AspNetCore.Builder; + using Microsoft.AspNetCore.Diagnostics; using Microsoft.AspNetCore.Hosting; + using Microsoft.AspNetCore.Http; + using Microsoft.AspNetCore.Mvc.ApiExplorer; + using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.FileProviders; using Microsoft.Extensions.FileProviders.Physical; + using Microsoft.IdentityModel.Tokens; + using Microsoft.OpenApi.Models; + using Prometheus; using Prometheus.DotNetRuntime; + using Prometheus.SystemMetrics; using Serilog; using Serilog.Events; using Serilog.Sinks.Grafana.Loki; + using slskd.Authentication; using slskd.Configuration; + using slskd.Core.API; using slskd.Cryptography; + using slskd.Integrations.FTP; + using slskd.Integrations.Pushbullet; + using slskd.Messaging; + using slskd.Search; + using slskd.Search.API; + using slskd.Shares; + using slskd.Transfers; + using slskd.Users; using slskd.Validation; + using Soulseek; using Utility.CommandLine; using Utility.EnvironmentVariables; using IOFile = System.IO.File; @@ -154,6 +177,7 @@ namespace slskd private static IConfigurationRoot Configuration { get; set; } private static OptionsAtStartup OptionsAtStartup { get; } = new OptionsAtStartup(); + private static ILogger Log { get; set; } = new ConsoleWriteLineLogger(); [Argument('g', "generate-cert", "generate X509 certificate and password for HTTPs")] private static bool GenerateCertificate { get; set; } @@ -181,9 +205,10 @@ namespace slskd EnvironmentVariables.Populate(prefix: EnvironmentVariablePrefix); Arguments.Populate(clearExistingValues: false); + // if a user has used one of the arguments above, perform the requested task, then quit if (ShowVersion) { - Console.WriteLine(FullVersion); + Log.Information(FullVersion); return; } @@ -225,9 +250,8 @@ namespace slskd // if not, set it to the default. ConfigurationFile ??= DefaultConfigurationFile; - // verify(create if needed) default application - // directories. if the downloads or complete directories are overridden in config, those will be - // validated after the config is loaded. + // verify(create if needed) default application directories. if the downloads or complete + // directories are overridden in config, those will be validated after the config is loaded. try { VerifyDirectory(AppDirectory, createIfMissing: true, verifyWriteable: true); @@ -237,7 +261,7 @@ namespace slskd } catch (Exception ex) { - Console.WriteLine($"Filesystem exception: {ex.Message}"); + Log.Information($"Filesystem exception: {ex.Message}"); return; } @@ -253,114 +277,58 @@ namespace slskd if (OptionsAtStartup.Debug) { - Console.WriteLine($"Configuration:\n{Configuration.GetDebugView()}"); + Log.Information($"Configuration:\n{Configuration.GetDebugView()}"); } if (!OptionsAtStartup.TryValidate(out var result)) { - Console.WriteLine(result.GetResultView()); + Log.Information(result.GetResultView()); return; } } catch (Exception ex) { - Console.WriteLine($"Invalid configuration: {(!OptionsAtStartup.Debug ? ex : ex.Message)}"); + Log.Information($"Invalid configuration: {(!OptionsAtStartup.Debug ? ex : ex.Message)}"); return; } - Log.Logger = (OptionsAtStartup.Debug ? new LoggerConfiguration().MinimumLevel.Debug() : new LoggerConfiguration().MinimumLevel.Information()) - .MinimumLevel.Override("Microsoft", LogEventLevel.Warning) - .MinimumLevel.Override("System.Net.Http.HttpClient", OptionsAtStartup.Debug ? LogEventLevel.Warning : LogEventLevel.Fatal) - .MinimumLevel.Override("slskd.Authentication.PassthroughAuthenticationHandler", LogEventLevel.Warning) - .Enrich.WithProperty("InstanceName", OptionsAtStartup.InstanceName) - .Enrich.WithProperty("InvocationId", InvocationId) - .Enrich.WithProperty("ProcessId", ProcessId) - .Enrich.FromLogContext() - .WriteTo.Console( - outputTemplate: (OptionsAtStartup.Debug ? "[{SubContext}] " : string.Empty) + "[{Timestamp:HH:mm:ss} {Level:u3}] {Message:lj}{NewLine}{Exception}") - .WriteTo.Async(config => - config.File( - Path.Combine(AppDirectory, "logs", $"{AppName}-.log"), - outputTemplate: (OptionsAtStartup.Debug ? "[{SubContext}] " : string.Empty) + "[{Timestamp:HH:mm:ss} {Level:u3}] {Message:lj}{NewLine}{Exception}", - rollingInterval: RollingInterval.Day)) - .WriteTo.Conditional( - e => !string.IsNullOrEmpty(OptionsAtStartup.Logger.Loki), - config => config.GrafanaLoki( - OptionsAtStartup.Logger.Loki ?? string.Empty, - outputTemplate: "[{Timestamp:HH:mm:ss} {Level:u3}] {Message:lj}{NewLine}{Exception}")) - .WriteTo.Sink(new DelegatingSink(logEvent => - { - try - { - var record = new LogRecord() - { - Timestamp = logEvent.Timestamp.LocalDateTime, - Context = logEvent.Properties["SourceContext"].ToString().TrimStart('"').TrimEnd('"'), - SubContext = logEvent.Properties.ContainsKey("SubContext") ? logEvent.Properties["SubContext"].ToString().TrimStart('"').TrimEnd('"') : null, - Level = logEvent.Level.ToString(), - Message = logEvent.RenderMessage().TrimStart('"').TrimEnd('"'), - }; - - LogBuffer.Enqueue(record); - LogEmitted?.Invoke(null, record); - } - catch (Exception ex) - { - Console.WriteLine($"Misconfigured delegating logger: {ex.Message}"); - } - })) - .CreateLogger(); - - var logger = Log.ForContext(typeof(Program)); + ConfigureGlobalLogger(); + Log = Serilog.Log.ForContext(typeof(Program)); if (!OptionsAtStartup.NoLogo) { PrintLogo(FullVersion); } - logger.Information("Version: {Version}", FullVersion); + Log.Information("Version: {Version}", FullVersion); if (IsDevelopment) { - logger.Warning("This is a Development build; YMMV"); + Log.Warning("This is a Development build; YMMV"); } if (IsCanary) { - logger.Warning("This is a canary build"); - logger.Warning("Canary builds are considered UNSTABLE and may be completely BROKEN"); - logger.Warning($"Please report any issues here: {IssuesUrl}"); + Log.Warning("This is a canary build"); + Log.Warning("Canary builds are considered UNSTABLE and may be completely BROKEN"); + Log.Warning($"Please report any issues here: {IssuesUrl}"); } - logger.Information("Invocation ID: {InvocationId}", InvocationId); - logger.Information("Process ID: {ProcessId}", ProcessId); - logger.Information("Instance Name: {InstanceName}", OptionsAtStartup.InstanceName); + Log.Information("Invocation ID: {InvocationId}", InvocationId); + Log.Information("Process ID: {ProcessId}", ProcessId); + Log.Information("Instance Name: {InstanceName}", OptionsAtStartup.InstanceName); - logger.Information("Using application directory {AppDirectory}", AppDirectory); - logger.Information("Using configuration file {ConfigurationFile}", ConfigurationFile); + Log.Information("Using application directory {AppDirectory}", AppDirectory); + Log.Information("Using configuration file {ConfigurationFile}", ConfigurationFile); - // for convenience, try to copy the example configuration file to the application directory if no configuration - // file exists. if any part fails, just move on silently. - if (!IOFile.Exists(ConfigurationFile)) - { - try - { - logger.Warning("Configuration file {ConfigurationFile} does not exist; creating from example", ConfigurationFile); - var source = Path.Combine(AppContext.BaseDirectory, "config", $"{AppName}.example.yml"); - var destination = ConfigurationFile; - IOFile.Copy(source, destination); - } - catch (Exception ex) - { - logger.Error("Failed to create configuration file {ConfigurationFile}: {Message}", ConfigurationFile, ex.Message); - } - } + RecreateConfigurationFileIfMissing(ConfigurationFile); if (!string.IsNullOrEmpty(OptionsAtStartup.Logger.Loki)) { - logger.Information("Forwarding logs to Grafana Loki instance at {LoggerLokiUrl}", OptionsAtStartup.Logger.Loki); + Log.Information("Forwarding logs to Grafana Loki instance at {LoggerLokiUrl}", OptionsAtStartup.Logger.Loki); } + // bootstrap the ASP.NET application try { if (OptionsAtStartup.Feature.Prometheus) @@ -368,59 +336,419 @@ namespace slskd using var runtimeMetrics = DotNetRuntimeStatsBuilder.Default().StartCollecting(); } - var webHost = WebHost.CreateDefaultBuilder(args) - .SuppressStatusMessages(true) - .ConfigureAppConfiguration((hostingContext, builder) => - { - builder.Sources.Clear(); - builder.AddConfigurationProviders(EnvironmentVariablePrefix, ConfigurationFile); - }) - .UseSerilog() + var builder = WebApplication.CreateBuilder(args); + + builder.Configuration + .AddConfigurationProviders(EnvironmentVariablePrefix, ConfigurationFile); + + builder.Host + .UseSerilog(); + + builder.WebHost .UseUrls() .UseKestrel(options => { - logger.Information($"Listening for HTTP requests at http://{IPAddress.Any}:{OptionsAtStartup.Web.Port}/"); + Log.Information($"Listening for HTTP requests at http://{IPAddress.Any}:{OptionsAtStartup.Web.Port}/"); options.Listen(IPAddress.Any, OptionsAtStartup.Web.Port); if (!OptionsAtStartup.Web.Https.Disabled) { - logger.Information($"Listening for HTTPS requests at https://{IPAddress.Any}:{OptionsAtStartup.Web.Https.Port}/"); + Log.Information($"Listening for HTTPS requests at https://{IPAddress.Any}:{OptionsAtStartup.Web.Https.Port}/"); options.Listen(IPAddress.Any, OptionsAtStartup.Web.Https.Port, listenOptions => { var cert = OptionsAtStartup.Web.Https.Certificate; if (!string.IsNullOrEmpty(cert.Pfx)) { - logger.Information($"Using certificate from {cert.Pfx}"); + Log.Information($"Using certificate from {cert.Pfx}"); listenOptions.UseHttps(cert.Pfx, cert.Password); } else { - logger.Information($"Using randomly generated self-signed certificate"); + Log.Information($"Using randomly generated self-signed certificate"); listenOptions.UseHttps(X509.Generate(subject: AppName)); } }); } - }) - .UseStartup() - .Build(); + }); + + var services = builder.Services; + + ConfigureAspDotNetServices(services); + ConfigureDependencyInjectionContainer(services); + + var app = builder.Build(); + + ConfigureAspDotNetPipeline(app); if (OptionsAtStartup.NoStart) { - logger.Information("Qutting because 'no-start' option is enabled"); + Log.Information("Qutting because 'no-start' option is enabled"); return; } - webHost.Run(); + app.Run(); } catch (Exception ex) { - logger.Fatal(ex, "Application terminated unexpectedly"); + Log.Fatal(ex, "Application terminated unexpectedly"); } finally { - Log.CloseAndFlush(); + Serilog.Log.CloseAndFlush(); + } + } + + private static void ConfigureDependencyInjectionContainer(IServiceCollection services) + { + // add the instance of OptionsAtStartup to DI as they were at startup. use when Options might change, but + // the values at startup are to be used (generally anything marked RequiresRestart). + services.AddSingleton(OptionsAtStartup); + + // add IOptionsMonitor and IOptionsSnapshot to DI. + // use when the current Options are to be used (generally anything not marked RequiresRestart) + // the monitor should be used for services with Singleton lifetime, snapshots for everything else + services.AddOptions() + .Bind(Configuration.GetSection(AppName), o => { o.BindNonPublicProperties = true; }) + .Validate(options => + { + if (!options.TryValidate(out var result)) + { + Log.Warning("Options (re)configuration rejected."); + Log.Warning(result.GetResultView()); + return false; + } + + return true; + }); + + // add IManagedState, IStateMutator, IStateMonitor, and IStateSnapshot state to DI. + // the mutator should be used any time application state needs to be mutated (as the name implies) + // as with options, the monitor should be used for services with Singleton lifetime, snapshots for everything else + // IManagedState should be used where state is being mutated and accessed in the same context + services.AddManagedState(); + + // add IHttpClientFactory + // use through 'using var http = HttpClientFactory.CreateClient()' wherever HTTP calls will be made + // this is important to prevent memory leaks + services.AddHttpClient(); + + // add a partially configured instance of SoulseekClient. the Application instance will + // complete configuration at startup. + services.AddSingleton(_ => + new SoulseekClient(options: new SoulseekClientOptions( + maximumConcurrentUploads: OptionsAtStartup.Global.Upload.Slots, + maximumConcurrentDownloads: OptionsAtStartup.Global.Download.Slots, + minimumDiagnosticLevel: OptionsAtStartup.Soulseek.DiagnosticLevel))); + + // add the core application service to DI as well as a hosted service so that other services can + // access instance methods + services.AddSingleton(); + services.AddHostedService(p => p.GetRequiredService()); + + services.AddSingleton(); + services.AddSingleton(); + services.AddSingleton(); + services.AddSingleton(_ => new RoomTracker(messageLimit: 250)); + + services.AddSingleton(); + + services.AddSingleton(); + services.AddSingleton(); + services.AddSingleton(); + services.AddSingleton(); + + services.AddSingleton(); + services.AddSingleton(); + + services.AddSingleton(); + + // initialize DbContext instances to avoid race conditions when a db needs to be created from scratch. + // important: do this last + services.AddDbContextFactory(options => + { + options.UseSqlite($"Data Source={Path.Combine(AppDirectory, "data", "search.db")}"); + }); + + services.InitializeDbContext(); + } + + private static void ConfigureAspDotNetServices(IServiceCollection services) + { + services.AddCors(options => options.AddPolicy("AllowAll", builder => builder + .AllowAnyHeader() + .AllowAnyMethod() + .SetIsOriginAllowed((host) => true) + .AllowCredentials())); + + var jwtSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(OptionsAtStartup.Web.Authentication.Jwt.Key)); + + services.AddSingleton(jwtSigningKey); + + if (!OptionsAtStartup.Web.Authentication.Disabled) + { + services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme) + .AddJwtBearer(options => + { + options.TokenValidationParameters = new TokenValidationParameters + { + ClockSkew = TimeSpan.FromMinutes(5), + RequireSignedTokens = true, + RequireExpirationTime = true, + ValidateLifetime = true, + ValidIssuer = AppName, + ValidateIssuer = true, + ValidateAudience = false, + IssuerSigningKey = jwtSigningKey, + ValidateIssuerSigningKey = true, + }; + + options.Events = new JwtBearerEvents + { + OnMessageReceived = context => + { + // assign the request token from the access_token query parameter + // but only if the destination is a SignalR hub + // https://docs.microsoft.com/en-us/aspnet/core/signalr/authn-and-authz?view=aspnetcore-5.0 + if (context.HttpContext.Request.Path.StartsWithSegments("/hub")) + { + context.Token = context.Request.Query["access_token"]; + } + + return Task.CompletedTask; + }, + }; + }); + } + else + { + Log.Warning("Authentication of web requests is DISABLED"); + + services.AddAuthentication(PassthroughAuthentication.AuthenticationScheme) + .AddScheme(PassthroughAuthentication.AuthenticationScheme, options => + { + options.Username = "Anonymous"; + options.Role = Role.Administrator; + }); + } + + services.AddRouting(options => options.LowercaseUrls = true); + services.AddControllers().AddJsonOptions(options => + { + options.JsonSerializerOptions.Converters.Add(new IPAddressConverter()); + options.JsonSerializerOptions.Converters.Add(new JsonStringEnumConverter()); + options.JsonSerializerOptions.DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull; + }); + + services.AddSignalR().AddJsonProtocol(options => + { + options.PayloadSerializerOptions.Converters.Add(new IPAddressConverter()); + options.PayloadSerializerOptions.Converters.Add(new JsonStringEnumConverter()); + }); + + services.AddHealthChecks(); + + services.AddApiVersioning(options => options.ReportApiVersions = true); + services.AddVersionedApiExplorer(options => + { + options.GroupNameFormat = "'v'VVV"; + options.SubstituteApiVersionInUrl = true; + }); + + if (OptionsAtStartup.Feature.Swagger) + { + services.AddSwaggerGen(options => + { + options.DescribeAllParametersInCamelCase(); + options.SwaggerDoc( + "v0", + new OpenApiInfo + { + Title = AppName, + Version = "v0", + }); + + if (System.IO.File.Exists(XmlDocumentationFile)) + { + options.IncludeXmlComments(XmlDocumentationFile); + } + else + { + Log.Warning($"Unable to find XML documentation in {XmlDocumentationFile}, Swagger will not include metadata"); + } + }); + } + + if (OptionsAtStartup.Feature.Prometheus) + { + services.AddSystemMetrics(); + } + } + + private static void ConfigureAspDotNetPipeline(WebApplication app) + { + app.UseExceptionHandler(a => a.Run(async context => + { + await context.Response.WriteAsJsonAsync(context.Features.Get().Error.Message); + })); + + app.UseCors("AllowAll"); + + if (OptionsAtStartup.Web.Https.Force) + { + app.UseHttpsRedirection(); + app.UseHsts(); + + Log.Information($"Forcing HTTP requests to HTTPS"); } + + // allow users to specify a custom path base, for use behind a reverse proxy + var urlBase = OptionsAtStartup.Web.UrlBase; + urlBase = urlBase.StartsWith("/") ? urlBase : "/" + urlBase; + + app.UsePathBase(urlBase); + Log.Information("Using base url {UrlBase}", urlBase); + + // remove any errant double forward slashes which may have been introduced by manipulating the path base + app.Use(async (context, next) => + { + var path = context.Request.Path.ToString(); + + if (path.StartsWith("//")) + { + context.Request.Path = new string(path.Skip(1).ToArray()); + } + + await next(); + }); + + // serve static content from the configured path + FileServerOptions fileServerOptions = default; + + var contentPath = Path.GetFullPath(OptionsAtStartup.Web.ContentPath); + + if (!System.IO.Directory.Exists(contentPath)) + { + Log.Warning($"Static content disabled; cannot find content path '{contentPath}'"); + } + else + { + fileServerOptions = new FileServerOptions + { + FileProvider = new PhysicalFileProvider(contentPath), + RequestPath = string.Empty, + EnableDirectoryBrowsing = false, + EnableDefaultFiles = true, + }; + + app.UseFileServer(fileServerOptions); + Log.Information("Serving static content from {ContentPath}", contentPath); + } + + if (OptionsAtStartup.Feature.Prometheus) + { + app.UseHttpMetrics(); + Log.Information("Publishing Prometheus metrics to /metrics"); + } + + if (OptionsAtStartup.Web.Logging) + { + app.UseSerilogRequestLogging(); + } + + app.UseAuthentication(); + + app.UseRouting(); + app.UseAuthorization(); + app.UseEndpoints(endpoints => + { + endpoints.MapHub("/hub/application"); + endpoints.MapHub("/hub/logs"); + endpoints.MapHub("/hub/search"); + + endpoints.MapControllers(); + endpoints.MapHealthChecks("/health"); + + if (OptionsAtStartup.Feature.Prometheus) + { + endpoints.MapMetrics("/metrics"); + } + }); + + if (OptionsAtStartup.Feature.Swagger) + { + app.UseSwagger(); + app.UseSwaggerUI(options => app.Services.GetRequiredService().ApiVersionDescriptions.ToList() + .ForEach(description => options.SwaggerEndpoint($"{(urlBase == "/" ? string.Empty : urlBase)}/swagger/{description.GroupName}/swagger.json", description.GroupName))); + + Log.Information("Publishing Swagger documentation to /swagger"); + } + + // if we made it this far and the route still wasn't matched, return the index unless it's an api route. this is + // required so that SPA routing (React Router, etc) can work properly + app.Use(async (context, next) => + { + // exclude API routes which are not matched or return a 404 + if (!context.Request.Path.StartsWithSegments("/api")) + { + context.Request.Path = "/"; + } + + await next(); + }); + + // 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(contentPath)) + { + app.UseFileServer(fileServerOptions); + } + } + + private static void ConfigureGlobalLogger() + { + Serilog.Log.Logger = (OptionsAtStartup.Debug ? new LoggerConfiguration().MinimumLevel.Debug() : new LoggerConfiguration().MinimumLevel.Information()) + .MinimumLevel.Override("Microsoft", LogEventLevel.Warning) + .MinimumLevel.Override("System.Net.Http.HttpClient", OptionsAtStartup.Debug ? LogEventLevel.Warning : LogEventLevel.Fatal) + .MinimumLevel.Override("slskd.Authentication.PassthroughAuthenticationHandler", LogEventLevel.Warning) + .Enrich.WithProperty("InstanceName", OptionsAtStartup.InstanceName) + .Enrich.WithProperty("InvocationId", InvocationId) + .Enrich.WithProperty("ProcessId", ProcessId) + .Enrich.FromLogContext() + .WriteTo.Console( + outputTemplate: (OptionsAtStartup.Debug ? "[{SubContext}] " : string.Empty) + "[{Timestamp:HH:mm:ss} {Level:u3}] {Message:lj}{NewLine}{Exception}") + .WriteTo.Async(config => + config.File( + Path.Combine(AppDirectory, "logs", $"{AppName}-.log"), + outputTemplate: (OptionsAtStartup.Debug ? "[{SubContext}] " : string.Empty) + "[{Timestamp:HH:mm:ss} {Level:u3}] {Message:lj}{NewLine}{Exception}", + rollingInterval: RollingInterval.Day)) + .WriteTo.Conditional( + e => !string.IsNullOrEmpty(OptionsAtStartup.Logger.Loki), + config => config.GrafanaLoki( + OptionsAtStartup.Logger.Loki ?? string.Empty, + outputTemplate: "[{Timestamp:HH:mm:ss} {Level:u3}] {Message:lj}{NewLine}{Exception}")) + .WriteTo.Sink(new DelegatingSink(logEvent => + { + try + { + var record = new LogRecord() + { + Timestamp = logEvent.Timestamp.LocalDateTime, + Context = logEvent.Properties["SourceContext"].ToString().TrimStart('"').TrimEnd('"'), + SubContext = logEvent.Properties.ContainsKey("SubContext") ? logEvent.Properties["SubContext"].ToString().TrimStart('"').TrimEnd('"') : null, + Level = logEvent.Level.ToString(), + Message = logEvent.RenderMessage().TrimStart('"').TrimEnd('"'), + }; + + LogBuffer.Enqueue(record); + LogEmitted?.Invoke(null, record); + } + catch (Exception ex) + { + Log.Information($"Misconfigured delegating logger: {ex.Message}"); + } + })) + .CreateLogger(); } private static IConfigurationBuilder AddConfigurationProviders(this IConfigurationBuilder builder, string environmentVariablePrefix, string configurationFile) @@ -457,16 +785,53 @@ namespace slskd commandLine: Environment.CommandLine); } + private static void InitializeDbContext(this IServiceCollection services) + where TContext : DbContext + { + Log.Debug($"Initializing database context {typeof(TContext).Name}"); + + try + { + using var ctx = services + .BuildServiceProvider() + .GetRequiredService>() + .CreateDbContext(); + } + catch (Exception ex) + { + Log.Error(ex, $"Failed to initialize database context {typeof(TContext).Name}: ${ex.Message}"); + throw; + } + } + + private static void RecreateConfigurationFileIfMissing(string configurationFile) + { + if (!IOFile.Exists(configurationFile)) + { + try + { + Log.Warning("Configuration file {ConfigurationFile} does not exist; creating from example", configurationFile); + var source = Path.Combine(AppContext.BaseDirectory, "config", $"{AppName}.example.yml"); + var destination = configurationFile; + IOFile.Copy(source, destination); + } + catch (Exception ex) + { + Log.Error("Failed to create configuration file {ConfigurationFile}: {Message}", configurationFile, ex.Message); + } + } + } + private static void GenerateX509Certificate(string password, string filename) { - Console.WriteLine("Generating X509 certificate..."); + Log.Information("Generating X509 certificate..."); filename = Path.Combine(AppContext.BaseDirectory, filename); var cert = X509.Generate(subject: AppName, password, X509KeyStorageFlags.Exportable); IOFile.WriteAllBytes(filename, cert.Export(X509ContentType.Pkcs12, password)); - Console.WriteLine($"Password: {password}"); - Console.WriteLine($"Certificate exported to {filename}"); + Log.Information($"Password: {password}"); + Log.Information($"Certificate exported to {filename}"); } private static void PrintCommandLineArguments(Type targetType) @@ -516,12 +881,12 @@ namespace slskd var longestItem = lines.Max(l => l.Item.Length); - Console.WriteLine("\nusage: slskd [arguments]\n"); - Console.WriteLine("arguments:\n"); + Log.Information("\nusage: slskd [arguments]\n"); + Log.Information("arguments:\n"); foreach (var line in lines) { - Console.WriteLine($" {line.Item.PadRight(longestItem)} {line.Description}"); + Log.Information($" {line.Item.PadRight(longestItem)} {line.Description}"); } } @@ -570,11 +935,11 @@ namespace slskd var longestItem = lines.Max(l => l.Item.Length); - Console.WriteLine("\nenvironment variables (arguments and config file have precedence):\n"); + Log.Information("\nenvironment variables (arguments and config file have precedence):\n"); foreach (var line in lines) { - Console.WriteLine($" {line.Item.PadRight(longestItem)} {line.Description}"); + Log.Information($" {line.Item.PadRight(longestItem)} {line.Description}"); } } @@ -627,13 +992,13 @@ namespace slskd private static void VerifyDirectory(string directory, bool createIfMissing = true, bool verifyWriteable = true) { - if (!Directory.Exists(directory)) + if (!System.IO.Directory.Exists(directory)) { if (createIfMissing) { try { - Directory.CreateDirectory(directory); + System.IO.Directory.CreateDirectory(directory); } catch (Exception ex) { -- cgit v1.2.3