From 564111ea20a5cea831879fefcff9d5a84de31663 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Mon, 29 Aug 2022 12:49:09 -0500 Subject: add Metrics options --- config/slskd.example.yml | 8 ++++- src/slskd/Core/Options.cs | 82 +++++++++++++++++++++++++++++++++++++++++------ 2 files changed, 80 insertions(+), 10 deletions(-) diff --git a/config/slskd.example.yml b/config/slskd.example.yml index 47404794..7038c576 100644 --- a/config/slskd.example.yml +++ b/config/slskd.example.yml @@ -76,8 +76,14 @@ # ttl: 604800000 # logger: # loki: ~ +# metrics: +# enabled: false +# url: /metrics +# authentication: +# disabled: false +# username: slskd +# password: slskd # feature: -# prometheus: false # swagger: false # soulseek: # username: ~ diff --git a/src/slskd/Core/Options.cs b/src/slskd/Core/Options.cs index bb525003..6a435db1 100644 --- a/src/slskd/Core/Options.cs +++ b/src/slskd/Core/Options.cs @@ -235,6 +235,13 @@ namespace slskd [RequiresRestart] public LoggerOptions Logger { get; init; } = new LoggerOptions(); + /// + /// Gets metrics options. + /// + [Validate] + [RequiresRestart] + public MetricsOptions Metrics { get; init; } = new MetricsOptions(); + /// /// Gets feature options. /// @@ -622,15 +629,6 @@ namespace slskd /// public class FeatureOptions { - /// - /// Gets a value indicating whether prometheus metrics should be collected and published. - /// - [Argument(default, "prometheus")] - [EnvironmentVariable("PROMETHEUS")] - [Description("enable collection and publishing of prometheus metrics")] - [RequiresRestart] - public bool Prometheus { get; init; } = false; - /// /// Gets a value indicating whether swagger documentation and UI should be enabled. /// @@ -730,6 +728,72 @@ namespace slskd public string Loki { get; init; } = null; } + /// + /// Metrics options. + /// + public class MetricsOptions + { + /// + /// Gets a value indicating whether the metrics endpoint should be enabled. + /// + [Argument(default, "metrics")] + [EnvironmentVariable("METRICS")] + [Description("enable metrics")] + [RequiresRestart] + public bool Enabled { get; init; } = false; + + /// + /// Gets the url for the metrics endpoint. + /// + [Argument(default, "metrics-url")] + [EnvironmentVariable("METRICS_URL")] + [Description("url for metrics")] + [RequiresRestart] + public string Url { get; init; } = "/metrics"; + + /// + /// Gets metrics endpoint authentication options. + /// + [Validate] + public AuthenticationOptions Authentication { get; init; } = new AuthenticationOptions(); + + /// + /// Metrics endpoint authentication options. + /// + public class AuthenticationOptions + { + /// + /// Gets a value indicating whether authentication should be disabled. + /// + [Argument(default, "metrics-no-auth")] + [EnvironmentVariable("METRICS_NO_AUTH")] + [Description("disable authentication for metrics requests")] + [RequiresRestart] + public bool Disabled { get; init; } = false; + + /// + /// Gets the username for the metrics endpoint. + /// + [Argument(default, "metrics-username")] + [EnvironmentVariable("METRICS_USERNAME")] + [Description("username for metrics")] + [StringLength(255, MinimumLength = 1)] + [RequiresRestart] + public string Username { get; init; } = Program.AppName; + + /// + /// Gets the password for the metrics endpoint. + /// + [Argument(default, "metrics-password")] + [EnvironmentVariable("METRICS_PASSWORD")] + [Description("password for metrics")] + [StringLength(255, MinimumLength = 1)] + [Secret] + [RequiresRestart] + public string Password { get; init; } = Program.AppName; + } + } + /// /// Soulseek client options. /// -- cgit v1.2.3 From 8e7b96c461795d5097c771684b1fe51feedb74e8 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Mon, 29 Aug 2022 12:49:22 -0500 Subject: add Metrics.BuildAsync() --- src/slskd/Core/Metrics.cs | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/src/slskd/Core/Metrics.cs b/src/slskd/Core/Metrics.cs index 83877500..3fc9a9b1 100644 --- a/src/slskd/Core/Metrics.cs +++ b/src/slskd/Core/Metrics.cs @@ -17,10 +17,27 @@ namespace slskd { + using System.IO; + using System.Threading.Tasks; using Prometheus; public static class Metrics { + /// + /// Builds metrics into a Prometheus-formatted string. + /// + /// A Prometheus-formatted string. + public static async Task BuildAsync() + { + using var stream = new MemoryStream(); + using var reader = new StreamReader(stream); + + await Prometheus.Metrics.DefaultRegistry.CollectAndExportAsTextAsync(stream); + stream.Position = 0; + + return await reader.ReadToEndAsync(); + } + public static class Search { /// -- cgit v1.2.3 From 558c550761bc30665af76c7b01d20f6606105a27 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Mon, 29 Aug 2022 12:49:43 -0500 Subject: use BuildAsync() in controller --- src/slskd/Core/API/Controllers/MetricsController.cs | 12 ++---------- 1 file changed, 2 insertions(+), 10 deletions(-) diff --git a/src/slskd/Core/API/Controllers/MetricsController.cs b/src/slskd/Core/API/Controllers/MetricsController.cs index aeccd97a..da2707c1 100644 --- a/src/slskd/Core/API/Controllers/MetricsController.cs +++ b/src/slskd/Core/API/Controllers/MetricsController.cs @@ -17,7 +17,6 @@ namespace slskd.Core.API { - using System.IO; using System.Threading.Tasks; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; @@ -38,16 +37,9 @@ namespace slskd.Core.API /// [HttpGet] [Authorize] - public async Task Metrics() + public async Task Get() { - using var stream = new MemoryStream(); - using var reader = new StreamReader(stream); - - await Prometheus.Metrics.DefaultRegistry.CollectAndExportAsTextAsync(stream); - stream.Position = 0; - - var response = await reader.ReadToEndAsync(); - + var response = await Metrics.BuildAsync(); return Content(response, "text/plain"); } } -- cgit v1.2.3 From 6d4a5106f918c474695a99aad3a4c2571e0905a4 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Mon, 29 Aug 2022 12:50:15 -0500 Subject: refactor Prometheus routing to support auth --- src/slskd/Program.cs | 53 ++++++++++++++++++++++++++++++++++------------------ 1 file changed, 35 insertions(+), 18 deletions(-) diff --git a/src/slskd/Program.cs b/src/slskd/Program.cs index 6357302b..4d109ee9 100644 --- a/src/slskd/Program.cs +++ b/src/slskd/Program.cs @@ -336,11 +336,6 @@ namespace slskd // bootstrap the ASP.NET application try { - if (OptionsAtStartup.Feature.Prometheus) - { - using var runtimeMetrics = DotNetRuntimeStatsBuilder.Default().StartCollecting(); - } - var builder = WebApplication.CreateBuilder(args); builder.Configuration @@ -513,6 +508,9 @@ namespace slskd .AllowCredentials() .WithExposedHeaders("X-URL-Base"))); + services.AddSystemMetrics(); + using var runtimeMetrics = DotNetRuntimeStatsBuilder.Default().StartCollecting(); + services.AddDataProtection() .PersistKeysToFileSystem(new DirectoryInfo(Path.Combine(AppDirectory, "data", ".DataProtection-Keys"))); @@ -614,11 +612,6 @@ namespace slskd }); } - if (OptionsAtStartup.Feature.Prometheus) - { - services.AddSystemMetrics(); - } - return services; } @@ -666,12 +659,6 @@ namespace slskd 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(); @@ -680,6 +667,7 @@ namespace slskd app.UseAuthentication(); app.UseRouting(); + app.UseHttpMetrics(); app.UseAuthorization(); app.UseEndpoints(endpoints => { @@ -690,9 +678,38 @@ namespace slskd endpoints.MapControllers(); endpoints.MapHealthChecks("/health"); - if (OptionsAtStartup.Feature.Prometheus) + if (OptionsAtStartup.Metrics.Enabled) { - endpoints.MapMetrics("/metrics"); + var options = OptionsAtStartup.Metrics; + var url = options.Url.StartsWith('/') ? options.Url : "/" + options.Url; + + Log.Information($"Publishing Prometheus metrics to {url}"); + + if (options.Authentication.Disabled) + { + Log.Warning("Authentication of metrics endpoint is DISABLED"); + } + + endpoints.MapGet(url, async context => + { + if (!options.Authentication.Disabled) + { + var auth = context.Request.Headers["Authorization"].FirstOrDefault(); + var providedCreds = auth?.Split(' ').Last(); + var validCreds = Convert.ToBase64String(Encoding.UTF8.GetBytes($"{options.Authentication.Username}:{options.Authentication.Password}")); + + if (string.IsNullOrEmpty(auth) || + !auth.StartsWith("Basic", StringComparison.InvariantCultureIgnoreCase) || + !string.Equals(providedCreds, validCreds, StringComparison.InvariantCultureIgnoreCase)) + { + context.Response.StatusCode = (int)HttpStatusCode.Unauthorized; + return; + } + } + + var response = await Metrics.BuildAsync(); + await context.Response.WriteAsync(response); + }); } }); -- cgit v1.2.3 From 2cbf74a09874278c3951dec7601c48af9d3d39f9 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Mon, 29 Aug 2022 15:28:15 -0500 Subject: update docs --- docs/config.md | 33 +++++++++++++++++++++++++++++---- 1 file changed, 29 insertions(+), 4 deletions(-) diff --git a/docs/config.md b/docs/config.md index 8403b76f..4e1f18dc 100644 --- a/docs/config.md +++ b/docs/config.md @@ -666,23 +666,48 @@ logger: loki: ~ ``` +## Metrics + +The application captures metrics internally and can optionally expose these metrics to be consumed by an instance of Prometheus. This is a good option for those wanting to tune performance characterisics of the application. + +Metrics are disabled by default, and enabling them will make them available at `/metrics`. Authentication is enabled by default, and the credentials are the same defaults as the web UI (`slskd`:`slskd`). + +If the application will be exposed to the internet, it's a good idea to leave this disabled or to set credentials other than the defaults. Elements of the system configuration, like operating system, architecture, and drive configuration are included and can this can make it easier for an attacker to exploit a vulnerability in your system. + + +| Command Line | Environment Variable | Description | +| -------------------- | -------------------- | --------------------------------------------------------- | +| `--metrics` | `METRICS` | Determines whether the metrics endpoint should be enabled | +| `--metrics-url` | `METRICS_URL` | The URL of the metrics endpoint | +| `--metrics-no-auth` | `METRICS_NO_AUTH` | Disables authentication for the metrics endpoint | +| `--metrics-username` | `METRICS_USERNAME` | The username for the metrics endpoint | +| `--metrics-password` | `METRICS_PASSWORD` | The password for the metrics endpoint | + +#### **YAML** + +```yaml +metrics: + enabled: false + url: /metrics + authentication: + disabled: false + username: slskd + password: slskd +``` + ## Features Several features have been added that aid in the development, debugging and operation of the application, but are generally not of much use to most users. -The application can publish Prometheus metrics to `/metrics` using [prometheus-net](https://github.com/prometheus-net/prometheus-net). This is especially useful for anyone attempting to tune performance characteristics. - The application can publish a Swagger (OpenAPI) definition and host SwaggerUI at `/swagger` using [Swashbuckle](https://github.com/domaindrivendev/Swashbuckle.AspNetCore). This is useful for anyone developing against the application API and/or creating a new web interface. | Command Line | Environment Variable | Description | | -------------- | -------------------- | ----------------------------------------------------------------------------------------- | -| `--prometheus` | `PROMETHEUS` | Determines whether Prometheus metrics are published to `/metrics` | | `--swagger` | `SWAGGER` | Determines whether Swagger (OpenAPI) definitions and UI should be available at `/swagger` | #### **YAML** ```yaml feature: - prometheus: false swagger: false ``` -- cgit v1.2.3 From e7cc66ec61dd6d6aeee2079d69afb257734a3df0 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Mon, 29 Aug 2022 15:28:31 -0500 Subject: don't expose HTTP metrics --- src/slskd/Program.cs | 2 -- 1 file changed, 2 deletions(-) diff --git a/src/slskd/Program.cs b/src/slskd/Program.cs index 4d109ee9..df9be4eb 100644 --- a/src/slskd/Program.cs +++ b/src/slskd/Program.cs @@ -665,9 +665,7 @@ namespace slskd } app.UseAuthentication(); - app.UseRouting(); - app.UseHttpMetrics(); app.UseAuthorization(); app.UseEndpoints(endpoints => { -- cgit v1.2.3 From d7520caa80629ea0821d936ebf2f236e14f89abe Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Mon, 29 Aug 2022 16:01:07 -0500 Subject: tweaks --- src/slskd/Program.cs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/slskd/Program.cs b/src/slskd/Program.cs index df9be4eb..8621a584 100644 --- a/src/slskd/Program.cs +++ b/src/slskd/Program.cs @@ -681,11 +681,11 @@ namespace slskd var options = OptionsAtStartup.Metrics; var url = options.Url.StartsWith('/') ? options.Url : "/" + options.Url; - Log.Information($"Publishing Prometheus metrics to {url}"); + Log.Information("Publishing Prometheus metrics to {URL}", url); if (options.Authentication.Disabled) { - Log.Warning("Authentication of metrics endpoint is DISABLED"); + Log.Warning("Authentication for the metrics endpoint is DISABLED"); } endpoints.MapGet(url, async context => @@ -729,7 +729,7 @@ namespace slskd 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"); + Log.Information("Publishing Swagger documentation to {URL}", "/swagger"); } // if we made it this far, the caller is either looking for a route that was synthesized with a SPA router, or is genuinely confused. -- cgit v1.2.3