diff options
| author | JP Dillingham <jp@dillingham.me> | 2025-11-23 18:38:02 -0600 |
|---|---|---|
| committer | JP Dillingham <jp@dillingham.me> | 2025-11-23 18:38:02 -0600 |
| commit | 3e69af61e6ab42d79b9ff86adf7729e8abc70eed (patch) | |
| tree | 41c799babd5509638bee59afe9bd995fc6e8c6c5 /src/slskd/Program.cs | |
| parent | 119a3925da7fdf5f659bfa4c8e61e39a7148ba3e (diff) | |
| parent | 318d1c16f80f6d48a408fb95b77c5a42402bf7df (diff) | |
| download | slskd-3e69af61e6ab42d79b9ff86adf7729e8abc70eed.tar.gz | |
Merge remote-tracking branch 'origin/master' into statistics
Diffstat (limited to 'src/slskd/Program.cs')
| -rw-r--r-- | src/slskd/Program.cs | 88 |
1 files changed, 84 insertions, 4 deletions
diff --git a/src/slskd/Program.cs b/src/slskd/Program.cs index bafab7f5..edfe06bc 100644 --- a/src/slskd/Program.cs +++ b/src/slskd/Program.cs @@ -23,6 +23,8 @@ namespace slskd using System.Collections.Generic; using System.ComponentModel; using System.ComponentModel.DataAnnotations; + using System.Diagnostics; + using System.IO; using System.Linq; using System.Net; @@ -237,6 +239,7 @@ namespace slskd private static OptionsAtStartup OptionsAtStartup { get; } = new OptionsAtStartup(); private static ILogger Log { get; set; } = new ConsoleWriteLineLogger(); private static Mutex Mutex { get; } = new Mutex(initiallyOwned: true, Compute.Sha256Hash(AppName)); + private static IDisposable DotNetRuntimeStats { get; set; } [Argument('g', "generate-cert", "generate X509 certificate and password for HTTPs")] private static bool GenerateCertificate { get; set; } @@ -475,6 +478,12 @@ namespace slskd Log.Information($"Listening for HTTP requests at http://{IPAddress.Any}:{OptionsAtStartup.Web.Port}/"); options.Listen(IPAddress.Any, OptionsAtStartup.Web.Port); + if (OptionsAtStartup.Web.Socket != null) + { + Log.Information($"Listening for HTTP requests on unix domain socket (UDS) {OptionsAtStartup.Web.Socket}"); + options.ListenUnixSocket(OptionsAtStartup.Web.Socket); + } + if (!OptionsAtStartup.Web.Https.Disabled) { Log.Information($"Listening for HTTPS requests at https://{IPAddress.Any}:{OptionsAtStartup.Web.Https.Port}/"); @@ -585,7 +594,9 @@ namespace slskd new SoulseekClient(options: new SoulseekClientOptions( maximumConcurrentUploads: OptionsAtStartup.Global.Upload.Slots, maximumConcurrentDownloads: OptionsAtStartup.Global.Download.Slots, - minimumDiagnosticLevel: OptionsAtStartup.Soulseek.DiagnosticLevel.ToEnum<Soulseek.Diagnostics.DiagnosticLevel>()))); + minimumDiagnosticLevel: OptionsAtStartup.Soulseek.DiagnosticLevel.ToEnum<Soulseek.Diagnostics.DiagnosticLevel>(), + maximumConcurrentSearches: 2, + raiseEventsAsynchronously: true))); // add the core application service to DI as well as a hosted service so that other services can // access instance methods @@ -600,9 +611,12 @@ namespace slskd var connectionStringDictionary = new ConnectionStringDictionary(Database.List .Select(database => { + var caching = OptionsAtStartup.Flags.NoSqliteCacheSharing ? "Private" : "Shared"; + var pooling = OptionsAtStartup.Flags.NoSqlitePooling ? "False" : "True"; // don't invert and ToString this it is confusing + var connStr = OptionsAtStartup.Flags.Volatile - ? $"Data Source=file:{database}?mode=memory;Cache=shared;Pooling=True;" - : $"Data Source={Path.Combine(DataDirectory, $"{database}.db")};Cache=shared;Pooling=True;"; + ? $"Data Source=file:{database}?mode=memory;Cache={caching};Pooling={pooling};" + : $"Data Source={Path.Combine(DataDirectory, $"{database}.db")};Cache={caching};Pooling={pooling}"; return new KeyValuePair<Database, ConnectionString>(database, connStr); }) @@ -698,8 +712,10 @@ namespace slskd .AllowCredentials() .WithExposedHeaders("X-URL-Base", "X-Total-Count"))); + // note: don't dispose this (or let it be disposed) or some of the stats, like those related + // to the thread pool won't work + DotNetRuntimeStats = DotNetRuntimeStatsBuilder.Default().StartCollecting(); services.AddSystemMetrics(); - using var runtimeMetrics = DotNetRuntimeStatsBuilder.Default().StartCollecting(); services.AddDataProtection() .PersistKeysToFileSystem(new DirectoryInfo(Path.Combine(DataDirectory, "misc", ".DataProtection-Keys"))); @@ -1128,6 +1144,30 @@ namespace slskd } })) .CreateLogger(); + + if (OptionsAtStartup.Flags.LogUnobservedExceptions) + { + // log Exceptions raised on fired-and-forgotten tasks, which adds very little value but might help debug someday + TaskScheduler.UnobservedTaskException += (sender, e) => + { + Serilog.Log.Logger.Error(e.Exception, "Unobserved exception: {Message}", e.Exception.Message); + e.SetObserved(); + }; + } + + AppDomain.CurrentDomain.UnhandledException += (sender, e) => + { + var exception = e.ExceptionObject as Exception; + + if (e.IsTerminating) + { + Serilog.Log.Logger.Fatal(exception, "Unhandled fatal exception: {Message}", e.IsTerminating); + } + else + { + Serilog.Log.Logger.Error(exception, "Unhandled exception: {Message}", exception.Message); + } + }; } private static IConfigurationBuilder AddConfigurationProviders(this IConfigurationBuilder builder, string environmentVariablePrefix, string configurationFile, bool reloadOnChange) @@ -1174,6 +1214,7 @@ namespace slskd services.AddDbContextFactory<T>(options => { options.UseSqlite(connectionString); + options.AddInterceptors(new SqliteConnectionOpenedInterceptor()); if (OptionsAtStartup.Debug && OptionsAtStartup.Flags.LogSQL) { @@ -1181,11 +1222,50 @@ namespace slskd } }); + /* + instantiate the DbContext and make sure it is created + */ using var ctx = services .BuildServiceProvider() .GetRequiredService<IDbContextFactory<T>>() .CreateDbContext(); + Log.Debug("Ensuring {Contex} is created", typeof(T).Name); + ctx.Database.EnsureCreated(); + + /* + set (and validate) our desired PRAGMAs + + synchronous mode is also set upon every connection via SqliteConnectionOpenedInterceptor. + */ + ctx.Database.OpenConnection(); + var conn = ctx.Database.GetDbConnection(); + + Log.Debug("Setting PRAGMAs for {Contex}", typeof(T).Name); + using var initCommand = conn.CreateCommand(); + initCommand.CommandText = "PRAGMA journal_mode=WAL; PRAGMA synchronous=1; PRAGMA optimize;"; + initCommand.ExecuteNonQuery(); + + using var journalCmd = conn.CreateCommand(); + journalCmd.CommandText = "PRAGMA journal_mode;"; + var journalMode = journalCmd.ExecuteScalar()?.ToString(); + + if (!journalMode.Equals("WAL", StringComparison.OrdinalIgnoreCase)) + { + Log.Warning("Failed to set database {Type} journal_mode PRAGMA to WAL; performance may be reduced", typeof(T).Name); + } + + using var syncCmd = conn.CreateCommand(); + syncCmd.CommandText = "PRAGMA synchronous;"; + var sync = syncCmd.ExecuteScalar()?.ToString(); + + if (!sync.Equals("1", StringComparison.OrdinalIgnoreCase)) + { + Log.Warning("Failed to set database {Type} synchronous PRAGMA to 1; performance may be reduced", typeof(T).Name); + } + + Log.Debug("PRAGMAs for {Context}: journal_mode={JournalMode}, synchronous={Synchronous}", typeof(T).Name, journalMode, sync); + return services; } catch (Exception ex) |
