diff options
| author | JP Dillingham <jp@dillingham.me> | 2026-06-21 10:41:53 -0500 |
|---|---|---|
| committer | GitHub <noreply@github.com> | 2026-06-21 10:41:53 -0500 |
| commit | 7497db57e8a44769d1a098ad189247ea4e980a1d (patch) | |
| tree | 189ff962d5125fe2526e4f79dccb009379725fdf /src/slskd | |
| parent | 8e152ed6eccd5650179f2875eef4aa21243c8c15 (diff) | |
| parent | 28fa7202724da10075dbddc3244d5d5528b4bdad (diff) | |
| download | slskd-7497db57e8a44769d1a098ad189247ea4e980a1d.tar.gz | |
Merge pull request #1769 from slskd/reports
Collect and broadcast real-time transfer metrics, add a footer to the UI to display them
Diffstat (limited to 'src/slskd')
| -rw-r--r-- | src/slskd/Application.cs | 4 | ||||
| -rw-r--r-- | src/slskd/Common/ExponentialMovingAverage.cs | 10 | ||||
| -rw-r--r-- | src/slskd/Core/Clock.cs | 42 | ||||
| -rw-r--r-- | src/slskd/Program.cs | 142 | ||||
| -rw-r--r-- | src/slskd/Relay/RelayClient.cs | 1 | ||||
| -rw-r--r-- | src/slskd/Shares/ShareScanner.cs | 3 | ||||
| -rw-r--r-- | src/slskd/Telemetry/API/MetricsHub.cs | 60 | ||||
| -rw-r--r-- | src/slskd/Telemetry/Metrics.cs | 316 | ||||
| -rw-r--r-- | src/slskd/Telemetry/MetricsService.cs | 96 | ||||
| -rw-r--r-- | src/slskd/Telemetry/TelemetryService.cs | 18 | ||||
| -rw-r--r-- | src/slskd/Transfers/API/Controllers/TransfersController.cs | 4 | ||||
| -rw-r--r-- | src/slskd/Transfers/Downloads/DownloadService.cs | 155 | ||||
| -rw-r--r-- | src/slskd/Transfers/TransferService.cs | 59 | ||||
| -rw-r--r-- | src/slskd/Transfers/Uploads/UploadQueue.cs | 43 | ||||
| -rw-r--r-- | src/slskd/Transfers/Uploads/UploadService.cs | 158 |
15 files changed, 1041 insertions, 70 deletions
diff --git a/src/slskd/Application.cs b/src/slskd/Application.cs index 2b9a1f93..475e4288 100644 --- a/src/slskd/Application.cs +++ b/src/slskd/Application.cs @@ -112,7 +112,7 @@ namespace slskd ISoulseekClient soulseekClient, FileService fileService, ConnectionWatchdog connectionWatchdog, - ITransferService transferService, + TransferService transferService, IBrowseTracker browseTracker, IRoomService roomService, IUserService userService, @@ -257,7 +257,7 @@ namespace slskd private IPushbulletService Pushbullet { get; } private DateTime SharesRefreshStarted { get; set; } private IManagedState<State> State { get; } - private ITransferService Transfers { get; init; } + private TransferService Transfers { get; init; } private IHubContext<ApplicationHub> ApplicationHub { get; set; } private IHubContext<LogsHub> LogHub { get; set; } private EventBus EventBus { get; } diff --git a/src/slskd/Common/ExponentialMovingAverage.cs b/src/slskd/Common/ExponentialMovingAverage.cs index aaa6e5ea..6bc773cb 100644 --- a/src/slskd/Common/ExponentialMovingAverage.cs +++ b/src/slskd/Common/ExponentialMovingAverage.cs @@ -73,6 +73,16 @@ namespace slskd private Action<double> OnUpdate { get; } /// <summary> + /// Resets the value. + /// </summary> + public void Reset() + { + Value = 0; + Initialized = false; + OnUpdate?.Invoke(Value); + } + + /// <summary> /// Updates the average with a new value. /// </summary> /// <param name="value"></param> diff --git a/src/slskd/Core/Clock.cs b/src/slskd/Core/Clock.cs index 9d1e8c75..6dabb7ac 100644 --- a/src/slskd/Core/Clock.cs +++ b/src/slskd/Core/Clock.cs @@ -45,9 +45,13 @@ namespace slskd { EveryMinuteTimer.Elapsed += (_, _) => Fire(EveryMinute); EveryThirtySecondsTimer.Elapsed += (_, _) => Fire(EveryThirtySeconds); + EveryFifteenSecondsTimer.Elapsed += (_, _) => Fire(EveryFifteenSeconds); EveryFiveMinutesTimer.Elapsed += (_, _) => Fire(EveryFiveMinutes); EveryThirtyMinutesTimer.Elapsed += (_, _) => Fire(EveryThirtyMinutes); EveryHourTimer.Elapsed += (_, _) => Fire(EveryHour); + EveryFiveSecondsTimer.Elapsed += (_, _) => Fire(EveryFiveSeconds); + EverySecondTimer.Elapsed += (_, _) => Fire(EverySecond); + EveryFiveHundredMillisecondsTimer.Elapsed += (_, _) => Fire(EveryFiveHundredMilliseconds); } /// <summary> @@ -71,6 +75,26 @@ namespace slskd public static event EventHandler<ClockEventArgs> EveryThirtySeconds; /// <summary> + /// Fires every 15 seconds. + /// </summary> + public static event EventHandler<ClockEventArgs> EveryFifteenSeconds; + + /// <summary> + /// Fires every 5 seconds. + /// </summary> + public static event EventHandler<ClockEventArgs> EveryFiveSeconds; + + /// <summary> + /// Fires every second. + /// </summary> + public static event EventHandler<ClockEventArgs> EverySecond; + + /// <summary> + /// Fires every 500 milliseconds. + /// </summary> + public static event EventHandler<ClockEventArgs> EveryFiveHundredMilliseconds; + + /// <summary> /// Fires every 30 minutes. /// </summary> public static event EventHandler<ClockEventArgs> EveryThirtyMinutes; @@ -79,7 +103,11 @@ namespace slskd private static Timer EveryHourTimer { get; } = CreateTimer(interval: 1000 * 60 * 60); private static Timer EveryMinuteTimer { get; } = CreateTimer(interval: 1000 * 60); private static Timer EveryThirtySecondsTimer { get; } = CreateTimer(interval: 1000 * 30); + private static Timer EveryFifteenSecondsTimer { get; } = CreateTimer(interval: 1000 * 15); private static Timer EveryThirtyMinutesTimer { get; } = CreateTimer(interval: 1000 * 60 * 30); + private static Timer EveryFiveSecondsTimer { get; } = CreateTimer(interval: 1000 * 5); + private static Timer EverySecondTimer { get; } = CreateTimer(interval: 1000); + private static Timer EveryFiveHundredMillisecondsTimer { get; } = CreateTimer(interval: 500); /// <summary> /// Starts the clock. @@ -89,18 +117,26 @@ namespace slskd { EveryMinuteTimer.Enabled = true; EveryThirtySecondsTimer.Enabled = true; + EveryFifteenSecondsTimer.Enabled = true; EveryFiveMinutesTimer.Enabled = true; EveryThirtyMinutesTimer.Enabled = true; EveryHourTimer.Enabled = true; + EveryFiveSecondsTimer.Enabled = true; + EverySecondTimer.Enabled = true; + EveryFiveHundredMillisecondsTimer.Enabled = true; var firstRunArgs = new ClockEventArgs(firstRun: true); return Task.WhenAll( Task.Run(() => Fire(EveryMinute, firstRunArgs)), Task.Run(() => Fire(EveryThirtySeconds, firstRunArgs)), + Task.Run(() => Fire(EveryFifteenSeconds, firstRunArgs)), Task.Run(() => Fire(EveryFiveMinutes, firstRunArgs)), Task.Run(() => Fire(EveryThirtyMinutes, firstRunArgs)), - Task.Run(() => Fire(EveryHour, firstRunArgs))); + Task.Run(() => Fire(EveryHour, firstRunArgs)), + Task.Run(() => Fire(EveryFiveSeconds, firstRunArgs)), + Task.Run(() => Fire(EverySecond, firstRunArgs)), + Task.Run(() => Fire(EveryFiveHundredMilliseconds, firstRunArgs))); } /// <summary> @@ -110,9 +146,13 @@ namespace slskd { EveryMinuteTimer.Stop(); EveryThirtySecondsTimer.Stop(); + EveryFifteenSecondsTimer.Stop(); EveryFiveMinutesTimer.Stop(); EveryThirtyMinutesTimer.Stop(); + EveryFiveSecondsTimer.Stop(); EveryHourTimer.Stop(); + EverySecondTimer.Stop(); + EveryFiveHundredMillisecondsTimer.Stop(); } private static Timer CreateTimer(double interval) => new() { AutoReset = true, Interval = interval, Enabled = false }; diff --git a/src/slskd/Program.cs b/src/slskd/Program.cs index 9a2914ea..0fc6b294 100644 --- a/src/slskd/Program.cs +++ b/src/slskd/Program.cs @@ -46,6 +46,7 @@ namespace slskd using System.Security.Cryptography.X509Certificates; using System.Text; using System.Text.Json.Serialization; + using System.Text.RegularExpressions; using System.Threading; using System.Threading.Tasks; using Asp.Versioning.ApiExplorer; @@ -63,11 +64,12 @@ namespace slskd using Microsoft.Extensions.FileProviders.Physical; using Microsoft.IdentityModel.Tokens; using Microsoft.OpenApi; + using Prometheus; using Prometheus.DotNetRuntime; using Prometheus.SystemMetrics; + using Prometheus.SystemMetrics.Collectors; using Serilog; using Serilog.Events; - using Serilog.Formatting.Display; using Serilog.Sinks.Grafana.Loki; using Serilog.Sinks.SystemConsole.Themes; using slskd.Authentication; @@ -627,6 +629,7 @@ namespace slskd _ = app.Services.GetService<ScriptService>(); _ = app.Services.GetService<WebhookService>(); _ = app.Services.GetService<VPNService>(); + _ = app.Services.GetService<TelemetryService>(); app.ConfigureAspDotNetPipeline(); @@ -757,6 +760,7 @@ namespace slskd services.AddSingleton<PrometheusService>(); services.AddSingleton<ReportsService>(); + services.AddSingleton<MetricsService>(); services.AddSingleton<TelemetryService>(); services.AddSingleton<VPNService>(); @@ -778,7 +782,7 @@ namespace slskd services.AddSingleton<IRoomService, RoomService>(); - services.AddSingleton<ITransferService, TransferService>(); + services.AddSingleton<TransferService>(); services.AddSingleton<IDownloadService, DownloadService>(); services.AddSingleton<IUploadService, UploadService>(); services.AddSingleton<IBatchService, BatchService>(); @@ -828,10 +832,7 @@ 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(); + services.ConfigureTelemetry(); services.AddDataProtection() .PersistKeysToFileSystem(new DirectoryInfo(Path.Combine(DataDirectory, "misc", ".DataProtection-Keys"))); @@ -1114,6 +1115,7 @@ namespace slskd endpoints.MapHub<LogsHub>("/hub/logs"); endpoints.MapHub<SearchHub>("/hub/search"); endpoints.MapHub<RelayHub>("/hub/relay"); + endpoints.MapHub<MetricsHub>("/hub/metrics"); endpoints.MapControllers(); endpoints.MapHealthChecks("/health"); @@ -1301,6 +1303,134 @@ namespace slskd }; } + private static IServiceCollection ConfigureTelemetry(this IServiceCollection services) + { + Prometheus.Metrics.SuppressDefaultMetrics(new SuppressDefaultMetricOptions + { + SuppressDebugMetrics = true, // prometheus_net_metric_families/instances/timeseries + SuppressProcessMetrics = false, // dotnet_collection_count_total, dotnet_total_memory_bytes, process_* + SuppressMeters = true, // system_ + SuppressEventCounters = true, // more system_ + }); + + Regex[] sources = + [ + new Regex("^System.*", RegexOptions.Compiled), + new Regex("^Microsoft-Windows-DotNETRuntime", RegexOptions.Compiled), + new Regex("^Microsoft-Diagnostics-DiagnosticSource", RegexOptions.Compiled), + new Regex("^Private.InternalDiagnostics.System.Net.Sockets$", RegexOptions.Compiled), + ]; + + /* + Meter bridge - uses new .NET Meters + + included: + + System.Runtime + + excluded: + + Microsoft.AspNetCore.MemoryPool + Microsoft.AspNetCore.Server.Kestrel + Microsoft.AspNetCore.Http.Connections + Microsoft.AspNetCore.Hosting + Microsoft.AspNetCore.Routing + Microsoft.AspNetCore.Diagnostics + Microsoft.AspNetCore.Authentication + Microsoft.EntityFrameworkCore + Private.InternalDiagnostics.System.Net.Quic.MsQuic + */ + Prometheus.Metrics.ConfigureMeterAdapter(options => + { + options.InstrumentFilterPredicate = instrument => sources.Any(s => instrument?.Meter?.Name is string name && s.IsMatch(name)); + }); + + /* + EventCounter bridge - uses 'legacy' EventSource counters + + included: + + System.Runtime + System.Data.DataCommonEventSource + System.Transactions.TransactionsEventSource + System.Diagnostics.Metrics + System.Buffers.ArrayPoolEventSource + System.Diagnostics.Eventing.FrameworkEventSource + System.Threading.Tasks.TplEventSource + System.Collections.Concurrent.ConcurrentCollectionsEventSource + System.Net.Sockets + Private.InternalDiagnostics.System.Net.Sockets + + excluded: + + Microsoft.AspNetCore.Hosting + Microsoft-AspNetCore-Server-Kestrel + Microsoft-Windows-DotNETRuntime + Microsoft-Diagnostics-DiagnosticSource + Microsoft-Extensions-Logging + Microsoft-Extensions-DependencyInjection + Microsoft.EntityFrameworkCore + Private.InternalDiagnostics.System.Net.Quic + */ + Prometheus.Metrics.ConfigureEventCounterAdapter(options => + { + options.EventSourceFilterPredicate = name => sources.Any(s => name is string n && s.IsMatch(n)); + }); + + /* + https://github.com/djluck/prometheus-net.DotNetRuntime + + this package overlaps nearly completely with the built in stats, but it offers a slightly different + calculation for memory, and a thread pool throughput stat that's fairly important to me. + + this has been enabled for many years and it should be included because it may break people's stuff. + i may make it optional in the future. it honestly might make more sense to disable the meters above + and keep this. + + included: + + dotnet_build_info + dotnet_collection + dotnet_contention + dotnet_exceptions + dotnet_jit + dotnet_gc + dotnet_sockets + dotnet_threadpool + */ + DotNetRuntimeStats = DotNetRuntimeStatsBuilder + .Customize() + .WithGcStats() + .WithThreadPoolStats() + .WithContentionStats() + .WithJitStats() + .WithExceptionStats() + .WithSocketStats() + .StartCollecting(); + + /* + https://github.com/Daniel15/prometheus-net.SystemMetrics + + this package adds information about the host machine slskd is running on, including CPU, RAM, disks, + and network interfaces. + + included: + + node_filesystem_avail/size + node_network_receive_ + node_network_transmit_ + node_cpu_seconds_total (detailed user/syste/irq/idle for ALL cores) + node_memory_ + */ + services.AddSystemMetrics(registerDefaultCollectors: true); + + // exclude tmpfs/overlay noise in containers + services.Configure<DiskCollectorConfig>(cfg => + cfg.DriveTypes = new HashSet<DriveType> { DriveType.Fixed }); + + return services; + } + private static IConfigurationBuilder AddConfigurationProviders(this IConfigurationBuilder builder, string environmentVariablePrefix, string configurationFile, bool reloadOnChange) { configurationFile = Path.GetFullPath(configurationFile); diff --git a/src/slskd/Relay/RelayClient.cs b/src/slskd/Relay/RelayClient.cs index 5c5f9d38..fef16573 100644 --- a/src/slskd/Relay/RelayClient.cs +++ b/src/slskd/Relay/RelayClient.cs @@ -228,6 +228,7 @@ namespace slskd.Relay if (disposing) { _ = HubConnection?.DisposeAsync(); + StartCancellationTokenSource?.Dispose(); } Disposed = true; diff --git a/src/slskd/Shares/ShareScanner.cs b/src/slskd/Shares/ShareScanner.cs index 5920b7ac..7c93d437 100644 --- a/src/slskd/Shares/ShareScanner.cs +++ b/src/slskd/Shares/ShareScanner.cs @@ -392,7 +392,10 @@ namespace slskd.Shares } finally { + var cts = CancellationTokenSource; CancellationTokenSource = null; + cts?.Dispose(); + SyncRoot.Release(); } } diff --git a/src/slskd/Telemetry/API/MetricsHub.cs b/src/slskd/Telemetry/API/MetricsHub.cs new file mode 100644 index 00000000..5dcd4ecc --- /dev/null +++ b/src/slskd/Telemetry/API/MetricsHub.cs @@ -0,0 +1,60 @@ +// <copyright file="MetricsHub.cs" company="JP Dillingham"> +// ▄▄▄▄ ▄▄▄▄ ▄▄▄▄ +// ▄▄▄▄▄▄█ █▄▄▄▄▄█ █▄▄▄▄▄█ █ +// █__ --█ █__ --█ ◄█ - █ +// █▄▄▄▄▄█▄▄█▄▄▄▄▄█▄▄█▄▄█▄▄▄▄▄█ +// ┍━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ ━━━━ ━ ━┉ ┉ ┉ +// │ Copyright (c) JP Dillingham. +// │ +// │ This program is free software: you can redistribute it and/or modify +// │ it under the terms of the GNU Affero General Public License as published +// │ by the Free Software Foundation, version 3. +// │ +// │ This program is distributed in the hope that it will be useful, +// │ but WITHOUT ANY WARRANTY; without even the implied warranty of +// │ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// │ GNU Affero General Public License for more details. +// │ +// │ You should have received a copy of the GNU Affero General Public License +// │ along with this program. If not, see https://www.gnu.org/licenses/. +// │ +// │ This program is distributed with Additional Terms pursuant to Section 7 +// │ of the AGPLv3. See the LICENSE file in the root directory of this +// │ project for the complete terms and conditions. +// │ +// │ https://slskd.org +// │ +// ├╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌ ╌ ╌╌╌╌ ╌ +// │ SPDX-FileCopyrightText: JP Dillingham +// │ SPDX-License-Identifier: AGPL-3.0-only +// ╰───────────────────────────────────────────╶──── ─ ─── ─ ── ──┈ ┈ +// </copyright> + +namespace slskd.Telemetry; + +using System.Threading.Tasks; +using Microsoft.AspNetCore.Authorization; +using Microsoft.AspNetCore.SignalR; +using Serilog; + +public interface IMetricsHub +{ + Task Update(object metrics); +} + +[Authorize] +public class MetricsHub : Hub<IMetricsHub> +{ + public MetricsHub(MetricsService metricsService) + { + Metrics = metricsService; + } + + private static ILogger Log { get; } = Serilog.Log.ForContext<MetricsHub>(); + private MetricsService Metrics { get; } + + public override async Task OnConnectedAsync() + { + await Clients.Caller.Update(Metrics.Current()); + } +}
\ No newline at end of file diff --git a/src/slskd/Telemetry/Metrics.cs b/src/slskd/Telemetry/Metrics.cs index 33e16873..822f6aeb 100644 --- a/src/slskd/Telemetry/Metrics.cs +++ b/src/slskd/Telemetry/Metrics.cs @@ -33,6 +33,7 @@ namespace slskd.Telemetry; using System; +using System.Threading; using Prometheus; /// <summary> @@ -45,6 +46,31 @@ using Prometheus; /// </remarks> public static class Metrics { + private static SemaphoreSlim SyncRoot { get; } = new SemaphoreSlim(1, 1); + + /// <summary> + /// Updates metrics under a mutex to prevent mismatches and under/overruns. + /// </summary> + /// <remarks> + /// This method uses a <see cref="SemaphoreSlim"/> for synchronization and it is therefore safe to do async work + /// inside of <paramref name="work"/>, though it is discouraged for causing un-needed contention. + /// </remarks> + /// <param name="work">Updates to execute.</param> + /// <param name="cancellationToken">The token to monitor for cancellation requests.</param> + public static void Update(Action work, CancellationToken cancellationToken = default) + { + SyncRoot.Wait(cancellationToken); + + try + { + work.Invoke(); + } + finally + { + SyncRoot.Release(); + } + } + /// <summary> /// Metrics related to search requests and responses. /// </summary> @@ -265,6 +291,296 @@ public static class Metrics } /// <summary> + /// Metrics related to transfers. + /// </summary> + public static class Transfers + { + /// <summary> + /// Metrics related to uploads. + /// </summary> + public static class Uploads + { + /// <summary> + /// Metrics related to in-progress uploads. + /// </summary> + public static class InProgress + { + /// <summary> + /// Gets a gauge representing the current number of unique users with in-progress uploads. + /// </summary> + public static Gauge Users { get; } = Prometheus.Metrics.CreateGauge( + name: "slskd_transfers_uploads_in_progress_users_current", + help: "Current number of unique users with in-progress uploads"); + + /// <summary> + /// Gets a gauge representing the current number of in-progress uploads. + /// </summary> + public static Gauge Files { get; } = Prometheus.Metrics.CreateGauge( + name: "slskd_transfers_uploads_in_progress_files_current", + help: "Current number of in-progress uploads"); + + /// <summary> + /// Gets a gauge representing the current total size, in bytes, of in-progress uploads. + /// </summary> + public static Gauge Bytes { get; } = Prometheus.Metrics.CreateGauge( + name: "slskd_transfers_uploads_in_progress_bytes_current", + help: "Current total size, in bytes, of in-progress uploads"); + + /// <summary> + /// Gets a gauge representing the current total speed, in bytes per second, of in-progress uploads. + /// </summary> + public static ExponentialMovingAverage CurrentTotalSpeed { get; } = new ExponentialMovingAverage(smoothingFactor: 0.5, onUpdate: value => CurrentTotalSpeedGauge.Set(value)); + public static Gauge CurrentTotalSpeedGauge { get; } = Prometheus.Metrics.CreateGauge( + name: "slskd_transfers_uploads_in_progress_speed_total_current", + help: "Current total speed, in bytes per second, of in-progress uploads"); + + /// <summary> + /// Gets a gauge representing the current average speed, in bytes per second, of in-progress uploads. + /// </summary> + public static ExponentialMovingAverage CurrentAverageSpeed { get; } = new ExponentialMovingAverage(smoothingFactor: 0.5, onUpdate: value => CurrentAverageSpeedGauge.Set(value)); + public static Gauge CurrentAverageSpeedGauge { get; } = Prometheus.Metrics.CreateGauge( + name: "slskd_transfers_uploads_in_progress_speed_average_current", + help: "Current average speed, in bytes per second, of in-progress uploads"); + } + + /// <summary> + /// Metrics related to queued uploads. + /// </summary> + public static class Queued + { + /// <summary> + /// Gets a gauge representing the current number of unique users with queued uploads. + /// </summary> + public static Gauge Users { get; } = Prometheus.Metrics.CreateGauge( + name: "slskd_transfers_uploads_queued_users_current", + help: "Current number of unique users with queued uploads"); + + /// <summary> + /// Gets a gauge representing the current number of queued uploads. + /// </summary> + public static Gauge Files { get; } = Prometheus.Metrics.CreateGauge( + name: "slskd_transfers_uploads_queued_files_current", + help: "Current number of queued uploads"); + + /// <summary> + /// Gets a gauge representing the current total size, in bytes, of queued uploads. + /// </summary> + public static Gauge Bytes { get; } = Prometheus.Metrics.CreateGauge( + name: "slskd_transfers_uploads_queued_bytes_current", + help: "Current total size, in bytes, of queued uploads"); + } + + /// <summary> + /// Metrics related to completed uploads. + /// </summary> + public static class Completed + { + /// <summary> + /// Gets a counter representing the total number of uploads that completed successfully. + /// </summary> + public static Counter Succeeded { get; } = Prometheus.Metrics.CreateCounter( + name: "slskd_transfers_uploads_completed_succeeded", + help: "Total number of uploads that completed successfully"); + + /// <summary> + /// Gets a counter representing the total number of bytes transferred by successfully completed uploads. + /// </summary> + public static Counter Bytes { get; } = Prometheus.Metrics.CreateCounter( + name: "slskd_transfers_uploads_completed_bytes", + help: "Total number of bytes transferred by successfully completed uploads"); + + /// <summary> + /// Gets a counter representing the total number of uploads that failed. + /// </summary> + public static Counter Failed { get; } = Prometheus.Metrics.CreateCounter( + name: "slskd_transfers_uploads_completed_failed", + help: "Total number of uploads that failed"); + + /// <summary> + /// Gets a gauge representing the current average speed, in bytes per second, of completed downloads. + /// </summary> + public static ExponentialMovingAverage CurrentAverageSpeed { get; } = new ExponentialMovingAverage(smoothingFactor: 0.5, onUpdate: value => CurrentAverageSpeedGauge.Set(value)); + public static Gauge CurrentAverageSpeedGauge { get; } = Prometheus.Metrics.CreateGauge( + name: "slskd_transfers_uploads_completed_speed_average_current", + help: "Current average speed, in bytes per second, of completed uploads"); + + /// <summary> + /// Gets a histogram representing the the average speed of completed uploads, in bytes per second. + /// </summary> + public static Histogram AverageSpeed { get; } = Prometheus.Metrics.CreateHistogram( + name: "slskd_transfers_uploads_completed_speed_average", + help: "The average speed of completed uploads, in bytes per second", + new HistogramConfiguration + { + Buckets = [ + 1_024, // 1 KB/s + 10_240, // 10 KB/s + 51_200, // 50 KB/s + 102_400, // 100 KB/s + 204_800, // 200 KB/s + 307_200, // 300 KB/s + 409_600, // 400 KB/s + 512_000, // 500 KB/s + 1_048_576, // 1 MB/s + 2_097_152, // 2 MB/s + 4_194_304, // 4 MB/s + 6_291_456, // 6 MB/s + 10_485_760, // 10 MB/s + 26_214_400, // 25 MB/s + 52_428_800, // 50 MB/s + 104_857_600, // 100 MB/s + 262_144_000, // 250 MB/s + 524_288_000, // 500 MB/s + 1_073_741_824, // 1 GB/s + ], + }); + } + } + + /// <summary> + /// Metrics related to downloads. + /// </summary> + public static class Downloads + { + /// <summary> + /// Metrics related to in-progress downloads. + /// </summary> + public static class InProgress + { + /// <summary> + /// Gets a gauge representing the current number of unique users with in-progress downloads. + /// </summary> + public static Gauge Users { get; } = Prometheus.Metrics.CreateGauge( + name: "slskd_transfers_downloads_in_progress_users_current", + help: "Current number of unique users with in-progress downloads"); + + /// <summary> + /// Gets a gauge representing the current number of in-progress downloads. + /// </summary> + public static Gauge Files { get; } = Prometheus.Metrics.CreateGauge( + name: "slskd_transfers_downloads_in_progress_files_current", + help: "Current number of in-progress downloads"); + + /// <summary> + /// Gets a gauge representing the current total size, in bytes, of in-progress downloads. + /// </summary> + public static Gauge Bytes { get; } = Prometheus.Metrics.CreateGauge( + name: "slskd_transfers_downloads_in_progress_bytes_current", + help: "Current total size, in bytes, of in-progress downloads"); + + /// <summary> + /// Gets a gauge representing the current total speed, in bytes per second, of in-progress downloads. + /// </summary> + public static ExponentialMovingAverage CurrentTotalSpeed { get; } = new ExponentialMovingAverage(smoothingFactor: 0.5, onUpdate: value => CurrentTotalSpeedGauge.Set(value)); + public static Gauge CurrentTotalSpeedGauge { get; } = Prometheus.Metrics.CreateGauge( + name: "slskd_transfers_downloads_in_progress_speed_total_current", + help: "Current total speed, in bytes per second, of in-progress downloads"); + + /// <summary> + /// Gets a gauge representing the current average speed, in bytes per second, of in-progress downloads. + /// </summary> + public static ExponentialMovingAverage CurrentAverageSpeed { get; } = new ExponentialMovingAverage(smoothingFactor: 0.5, onUpdate: value => CurrentAverageSpeedGauge.Set(value)); + public static Gauge CurrentAverageSpeedGauge { get; } = Prometheus.Metrics.CreateGauge( + name: "slskd_transfers_downloads_in_progress_speed_average_current", + help: "Current average speed, in bytes per second, of in-progress downloads"); + } + + /// <summary> + /// Metrics related to queued downloads. + /// </summary> + public static class Queued + { + /// <summary> + /// Gets a gauge representing the current number of unique users with queued downloads. + /// </summary> + public static Gauge Users { get; } = Prometheus.Metrics.CreateGauge( + name: "slskd_transfers_downloads_queued_users_current", + help: "Current number of unique users with queued downloads"); + + /// <summary> + /// Gets a gauge representing the current number of queued downloads. + /// </summary> + public static Gauge Files { get; } = Prometheus.Metrics.CreateGauge( + name: "slskd_transfers_downloads_queued_files_current", + help: "Current number of queued downloads"); + + /// <summary> + /// Gets a gauge representing the current total size, in bytes, of queued downloads. + /// </summary> + public static Gauge Bytes { get; } = Prometheus.Metrics.CreateGauge( + name: "slskd_transfers_downloads_queued_bytes_current", + help: "Current total size, in bytes, of queued downloads"); + } + + /// <summary> + /// Metrics related to completed downloads. + /// </summary> + public static class Completed + { + /// <summary> + /// Gets a counter representing the total number of downloads that completed successfully. + /// </summary> + public static Counter Succeeded { get; } = Prometheus.Metrics.CreateCounter( + name: "slskd_transfers_downloads_completed_succeeded", + help: "Total number of downloads that completed successfully"); + + /// <summary> + /// Gets a counter representing the total number of bytes transferred by successfully completed downloads. + /// </summary> + public static Counter Bytes { get; } = Prometheus.Metrics.CreateCounter( + name: "slskd_transfers_downloads_completed_bytes", + help: "Total number of bytes transferred by successfully completed downloads"); + + /// <summary> + /// Gets a counter representing the total number of downloads that failed. + /// </summary> + public static Counter Failed { get; } = Prometheus.Metrics.CreateCounter( + name: "slskd_transfers_downloads_completed_failed", + help: "Total number of downloads that failed"); + + /// <summary> + /// Gets a gauge representing the current average speed, in bytes per second, of completed downloads. + /// </summary> + public static ExponentialMovingAverage CurrentAverageSpeed { get; } = new ExponentialMovingAverage(smoothingFactor: 0.5, onUpdate: value => CurrentAverageSpeedGauge.Set(value)); + public static Gauge CurrentAverageSpeedGauge { get; } = Prometheus.Metrics.CreateGauge( + name: "slskd_transfers_downloads_completed_speed_average_current", + help: "Current average speed, in bytes per second, of completed downloads"); + + /// <summary> + /// Gets a histogram representing the the average speed of completed downloads, in bytes per second. + /// </summary> + public static Histogram AverageSpeed { get; } = Prometheus.Metrics.CreateHistogram( + name: "slskd_transfers_downloads_completed_speed_average", + help: "The average speed of completed downloads, in bytes per second", + new HistogramConfiguration + { + Buckets = [ + 1_024, // 1 KB/s + 10_240, // 10 KB/s + 51_200, // 50 KB/s + 102_400, // 100 KB/s + 204_800, // 200 KB/s + 307_200, // 300 KB/s + 409_600, // 400 KB/s + 512_000, // 500 KB/s + 1_048_576, // 1 MB/s + 2_097_152, // 2 MB/s + 4_194_304, // 4 MB/s + 6_291_456, // 6 MB/s + 10_485_760, // 10 MB/s + 26_214_400, // 25 MB/s + 52_428_800, // 50 MB/s + 104_857_600, // 100 MB/s + 262_144_000, // 250 MB/s + 524_288_000, // 500 MB/s + 1_073_741_824, // 1 GB/s + ], + }); + } + } + } + + /// <summary> /// Metrics related to the distributed network. /// </summary> public static class DistributedNetwork diff --git a/src/slskd/Telemetry/MetricsService.cs b/src/slskd/Telemetry/MetricsService.cs new file mode 100644 index 00000000..1c69ef85 --- /dev/null +++ b/src/slskd/Telemetry/MetricsService.cs @@ -0,0 +1,96 @@ +// <copyright file="MetricsService.cs" company="JP Dillingham"> +// ▄▄▄▄ ▄▄▄▄ ▄▄▄▄ +// ▄▄▄▄▄▄█ █▄▄▄▄▄█ █▄▄▄▄▄█ █ +// █__ --█ █__ --█ ◄█ - █ +// █▄▄▄▄▄█▄▄█▄▄▄▄▄█▄▄█▄▄█▄▄▄▄▄█ +// ┍━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ ━━━━ ━ ━┉ ┉ ┉ +// │ Copyright (c) JP Dillingham. +// │ +// │ This program is free software: you can redistribute it and/or modify +// │ it under the terms of the GNU Affero General Public License as published +// │ by the Free Software Foundation, version 3. +// │ +// │ This program is distributed in the hope that it will be useful, +// │ but WITHOUT ANY WARRANTY; without even the implied warranty of +// │ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// │ GNU Affero General Public License for more details. +// │ +// │ You should have received a copy of the GNU Affero General Public License +// │ along with this program. If not, see https://www.gnu.org/licenses/. +// │ +// │ This program is distributed with Additional Terms pursuant to Section 7 +// │ of the AGPLv3. See the LICENSE file in the root directory of this +// │ project for the complete terms and conditions. +// │ +// │ https://slskd.org +// │ +// ├╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌ ╌ ╌╌╌╌ ╌ +// │ SPDX-FileCopyrightText: JP Dillingham +// │ SPDX-License-Identifier: AGPL-3.0-only +// ╰───────────────────────────────────────────╶──── ─ ─── ─ ── ──┈ ┈ +// </copyright> + +namespace slskd.Telemetry; + +using Serilog; + +/// <summary> +/// Metrics. +/// </summary> +public class MetricsService +{ + private ILogger Log { get; } = Serilog.Log.ForContext<MetricsService>(); + + public object Current() + { + var metrics = new + { + Downloads = new + { + InProgress = new + { + Files = Metrics.Transfers.Downloads.InProgress.Files.Value, + Users = Metrics.Transfers.Downloads.InProgress.Users.Value, + AverageSpeed = Metrics.Transfers.Downloads.InProgress.CurrentAverageSpeed.Value, + TotalSpeed = Metrics.Transfers.Downloads.InProgress.CurrentTotalSpeed.Value, + }, + Queued = new + { + Files = Metrics.Transfers.Downloads.Queued.Files.Value, + Users = Metrics.Transfers.Downloads.Queued.Users.Value, + Bytes = Metrics.Transfers.Downloads.Queued.Bytes.Value, + }, + Completed = new + { + Succeeded = Metrics.Transfers.Downloads.Completed.Succeeded.Value, + Failed = Metrics.Transfers.Downloads.Completed.Failed.Value, + Bytes = Metrics.Transfers.Downloads.Completed.Bytes.Value, + }, + }, + Uploads = new + { + InProgress = new + { + Files = Metrics.Transfers.Uploads.InProgress.Files.Value, + Users = Metrics.Transfers.Uploads.InProgress.Users.Value, + AverageSpeed = Metrics.Transfers.Uploads.InProgress.CurrentAverageSpeed.Value, + TotalSpeed = Metrics.Transfers.Uploads.InProgress.CurrentTotalSpeed.Value, + }, + Queued = new + { + Files = Metrics.Transfers.Uploads.Queued.Files.Value, + Users = Metrics.Transfers.Uploads.Queued.Users.Value, + Bytes = Metrics.Transfers.Uploads.Queued.Bytes.Value, + }, + Completed = new + { + Succeeded = Metrics.Transfers.Uploads.Completed.Succeeded.Value, + Failed = Metrics.Transfers.Uploads.Completed.Failed.Value, + Bytes = Metrics.Transfers.Uploads.Completed.Bytes.Value, + }, + }, + }; + + return metrics; + } +}
\ No newline at end of file diff --git a/src/slskd/Telemetry/TelemetryService.cs b/src/slskd/Telemetry/TelemetryService.cs index 74800126..5085d6ed 100644 --- a/src/slskd/Telemetry/TelemetryService.cs +++ b/src/slskd/Telemetry/TelemetryService.cs @@ -30,16 +30,32 @@ // ╰───────────────────────────────────────────╶──── ─ ─── ─ ── ──┈ ┈ // </copyright> +using Microsoft.AspNetCore.SignalR; + namespace slskd.Telemetry; public class TelemetryService { - public TelemetryService(PrometheusService prometheusService, ReportsService reportsService) + public TelemetryService( + PrometheusService prometheusService, + ReportsService reportsService, + MetricsService metricsService, + IHubContext<MetricsHub, IMetricsHub> metricsHub) { Prometheus = prometheusService; Reports = reportsService; + Metrics = metricsService; + + MetricsHub = metricsHub; + + Clock.EverySecond += (_, _) => + { + MetricsHub.Clients.All.Update(Metrics.Current()); + }; } public PrometheusService Prometheus { get; } public ReportsService Reports { get; } + public MetricsService Metrics { get; } + private IHubContext<MetricsHub, IMetricsHub> MetricsHub { get; } }
\ No newline at end of file diff --git a/src/slskd/Transfers/API/Controllers/TransfersController.cs b/src/slskd/Transfers/API/Controllers/TransfersController.cs index 3191e3a8..147921ef 100644 --- a/src/slskd/Transfers/API/Controllers/TransfersController.cs +++ b/src/slskd/Transfers/API/Controllers/TransfersController.cs @@ -64,7 +64,7 @@ namespace slskd.Transfers.API /// <param name="userService"></param> /// <param name="transferService"></param> public TransfersController( - ITransferService transferService, + TransferService transferService, IUserService userService, IOptionsSnapshot<Options> optionsSnapshot) { @@ -74,7 +74,7 @@ namespace slskd.Transfers.API } private static SemaphoreSlim DownloadRequestLimiter { get; } = new SemaphoreSlim(2, 2); - private ITransferService Transfers { get; } + private TransferService Transfers { get; } private IUserService Users { get; } private IOptionsSnapshot<Options> OptionsSnapshot { get; } private ILogger Log { get; set; } = Serilog.Log.ForContext<TransfersController>(); diff --git a/src/slskd/Transfers/Downloads/DownloadService.cs b/src/slskd/Transfers/Downloads/DownloadService.cs index 7c794e55..a4d48279 100644 --- a/src/slskd/Transfers/Downloads/DownloadService.cs +++ b/src/slskd/Transfers/Downloads/DownloadService.cs @@ -208,6 +208,7 @@ namespace slskd.Transfers.Downloads EventBus = eventBus; Clock.EveryMinute += (_, _) => Task.Run(() => CleanupEnqueueSemaphoresAsync()); + Clock.EveryFiveSeconds += (_, _) => Task.Run(() => EmitMetrics()); } /// <summary> @@ -1091,6 +1092,57 @@ namespace slskd.Transfers.Downloads context.SaveChanges(); } + protected virtual void EmitMetrics() + { + void EmitQueuedMetrics() + { + var queued = Client.Downloads.Where(u => u.State.HasFlag(TransferStates.Queued)); + + Telemetry.Metrics.Transfers.Downloads.Queued.Users + .Set(queued.Select(u => u.Username).Distinct().Count()); + + Telemetry.Metrics.Transfers.Downloads.Queued.Files + .Set(queued.Count()); + + Telemetry.Metrics.Transfers.Downloads.Queued.Bytes + .Set(queued.Sum(q => q.Size)); + } + + void EmitInProgressMetrics() + { + var inProgress = Client.Downloads.Where(u => u.State == TransferStates.InProgress); + + Telemetry.Metrics.Transfers.Downloads.InProgress.Users + .Set(inProgress.Select(u => u.Username).Distinct().Count()); + + Telemetry.Metrics.Transfers.Downloads.InProgress.Files + .Set(inProgress.Count()); + + Telemetry.Metrics.Transfers.Downloads.InProgress.Bytes + .Set(inProgress.Sum(u => u.Size)); + + if (inProgress.Any()) + { + Telemetry.Metrics.Transfers.Downloads.InProgress.CurrentTotalSpeed + .Update(inProgress.Sum(u => u.AverageSpeed)); + + Telemetry.Metrics.Transfers.Downloads.InProgress.CurrentAverageSpeed + .Update(inProgress.Any() ? inProgress.Average(u => u.AverageSpeed) : 0); + } + else + { + Telemetry.Metrics.Transfers.Downloads.InProgress.CurrentTotalSpeed.Reset(); + Telemetry.Metrics.Transfers.Downloads.InProgress.CurrentAverageSpeed.Reset(); + } + } + + Telemetry.Metrics.Update(() => + { + EmitQueuedMetrics(); + EmitInProgressMetrics(); + }); + } + /// <summary> /// Downloads the specified enqueued <paramref name="transfer"/> from the remote user. /// </summary> @@ -1132,6 +1184,9 @@ namespace slskd.Transfers.Downloads var retryOptions = OptionsMonitor.CurrentValue.Transfers.Download.Retry; var updateSyncRoot = new SemaphoreSlim(1, 1); + var stateHistory = new List<TransferStates>(); + DateTime lastReportedAverageSpeed = default; + try { using var rateLimiter = new RateLimiter(250, concurrencyLimit: 1, flushOnDispose: true); @@ -1172,6 +1227,27 @@ namespace slskd.Transfers.Downloads transfer.State = TransferStates.Queued | TransferStates.Locally; } + transfer = transfer.WithSoulseekTransfer(args.Transfer); + + Telemetry.Metrics.Update(() => + { + if (!TransferStateCategories.Queued.Contains(args.PreviousState) && TransferStateCategories.Queued.Contains(transfer.State)) + { + Telemetry.Metrics.Transfers.Downloads.Queued.Files.Inc(1); + Telemetry.Metrics.Transfers.Downloads.Queued.Bytes.Inc(transfer.Size); + } + + if (!TransferStateCategories.InProgress.Contains(args.PreviousState) && TransferStateCategories.InProgress.Contains(transfer.State)) + { + Telemetry.Metrics.Transfers.Downloads.Queued.Files.Dec(1); + Telemetry.Metrics.Transfers.Downloads.Queued.Bytes.Dec(transfer.Size); + Telemetry.Metrics.Transfers.Downloads.InProgress.Files.Inc(1); + Telemetry.Metrics.Transfers.Downloads.InProgress.Bytes.Inc(transfer.Size); + } + }); + + stateHistory.Add(transfer.State); + // todo: broadcast SynchronizedUpdate(transfer, semaphore: updateSyncRoot, cancellationToken: cancellationToken); } @@ -1204,6 +1280,21 @@ namespace slskd.Transfers.Downloads context.Transfers.Where(t => t.Id == transfer.Id).ExecuteUpdate(setter => setter .SetProperty(t => t.BytesTransferred, transfer.BytesTransferred) .SetProperty(t => t.AverageSpeed, transfer.AverageSpeed)); + + // progress is reported at 4x the speed (250ms) that the transfer's average speed is calculated (1000ms) + // the transfer's speed is also zero until it has enough data to compute the EMA, so throw both + // repeated and zero values out + var now = DateTime.UtcNow; + + if (transfer.AverageSpeed > 0 && now >= lastReportedAverageSpeed.AddMilliseconds(1000)) + { + Telemetry.Metrics.Update(() => + { + Telemetry.Metrics.Transfers.Downloads.InProgress.CurrentAverageSpeed.Update(transfer.AverageSpeed); + }, cancellationToken); + + lastReportedAverageSpeed = now; + } } finally { @@ -1307,6 +1398,29 @@ namespace slskd.Transfers.Downloads && ex is not TransferSizeMismatchException, onRetry: (attempts, delay) => { + // an attempt failed and we have decided that we're going to retry instead of letting it throw + // we *MAY* have incremented queued/in progress metrics as part of the previous attempt + var mostRecentQueuedOrInProgressState = stateHistory + .LastOrDefault(s => TransferStateCategories.InProgress.Contains(s) || TransferStateCategories.Queued.Contains(s)); + + Telemetry.Metrics.Update(() => + { + if (TransferStateCategories.InProgress.Contains(mostRecentQueuedOrInProgressState)) + { + Telemetry.Metrics.Transfers.Downloads.InProgress.Files.Dec(1); + Telemetry.Metrics.Transfers.Downloads.InProgress.Bytes.Dec(transfer.Size); + } + else if (TransferStateCategories.Queued.Contains(mostRecentQueuedOrInProgressState)) + { + Telemetry.Metrics.Transfers.Downloads.Queued.Files.Dec(1); + Telemetry.Metrics.Transfers.Downloads.Queued.Bytes.Dec(transfer.Size); + } + }); + + // reset the history to make detection logic above easier and more accurate + Log.Debug("Previous attempt to download {Filename} from user {Username} completed with states: {@States}", FileSafety.GetFileNameSafely(transfer.Filename), transfer.Username, stateHistory); + stateHistory = []; + Log.Information("Waiting about {Delay} second(s) to retry attempt #{Attempt} to download {Filename} from user {Username} in {Delay}ms", (int)Math.Ceiling((double)delay / 1000), attempts, transfer.Filename, transfer.Username); transfer.Attempts = attempts; @@ -1335,6 +1449,13 @@ namespace slskd.Transfers.Downloads // todo: broadcast to signalr hub SynchronizedUpdate(transfer, semaphore: updateSyncRoot, cancellationToken: CancellationToken.None); + Telemetry.Metrics.Update(() => + { + Telemetry.Metrics.Transfers.Downloads.Completed.Succeeded.Inc(1); + Telemetry.Metrics.Transfers.Downloads.Completed.Bytes.Inc(transfer.BytesTransferred); + Telemetry.Metrics.Transfers.Downloads.Completed.AverageSpeed.Observe(transfer.AverageSpeed); + }, cancellationToken); + Log.Debug("Successfully updated Transfer for {Filename} from {Username} (state: {State}, progress: {Progress})", transfer.Filename, transfer.Username, transfer.State, transfer.PercentComplete); /* @@ -1431,6 +1552,11 @@ namespace slskd.Transfers.Downloads // todo: broadcast SynchronizedUpdate(transfer, semaphore: updateSyncRoot, cancellationToken: CancellationToken.None); + Telemetry.Metrics.Update(() => + { + Telemetry.Metrics.Transfers.Downloads.Completed.Failed.Inc(1); + }, cancellationToken); + throw; } catch (Exception ex) @@ -1442,10 +1568,39 @@ namespace slskd.Transfers.Downloads // todo: broadcast SynchronizedUpdate(transfer, semaphore: updateSyncRoot, cancellationToken: CancellationToken.None); + Telemetry.Metrics.Update(() => + { + Telemetry.Metrics.Transfers.Downloads.Completed.Failed.Inc(1); + }, cancellationToken); + throw; } finally { + Log.Debug("Download of {Filename} from user {Username} completed with states: {@States}", FileSafety.GetFileNameSafely(transfer.Filename), transfer.Username, stateHistory); + + // figure out the most recent state that was either InProgress or Queued so that we can decrement the count and bytes + // for transfers that succeed this will be InProgress, for transfers that never started this will be Queued (cancelled or something) + // state will almost certainly transition to errored or completed before we get here, so we can't just take the last state + var mostRecentQueuedOrInProgressState = stateHistory + .LastOrDefault(s => TransferStateCategories.InProgress.Contains(s) || TransferStateCategories.Queued.Contains(s)); + + Telemetry.Metrics.Update(() => + { + if (TransferStateCategories.InProgress.Contains(mostRecentQueuedOrInProgressState) && Telemetry.Metrics.Transfers.Downloads.InProgress.Files.Value > 0) + { + // if the transfer was ever in progress at any time, we decrement because we should have incremented on that transition + Telemetry.Metrics.Transfers.Downloads.InProgress.Files.Dec(1); + Telemetry.Metrics.Transfers.Downloads.InProgress.Bytes.Dec(transfer.Size); + } + else if (TransferStateCategories.Queued.Contains(mostRecentQueuedOrInProgressState) && Telemetry.Metrics.Transfers.Downloads.Queued.Files.Value > 0) + { + // if the transfer never transitioned to in progress but it was queued at any point, decrement queued + Telemetry.Metrics.Transfers.Downloads.Queued.Files.Dec(1); + Telemetry.Metrics.Transfers.Downloads.Queued.Bytes.Dec(transfer.Size); + } + }, cancellationToken); + if (CancellationTokens.TryRemove(transfer.Id, out var storedCancellationTokenSource)) { storedCancellationTokenSource?.Dispose(); diff --git a/src/slskd/Transfers/TransferService.cs b/src/slskd/Transfers/TransferService.cs index 6079dcd2..6dd852a0 100644 --- a/src/slskd/Transfers/TransferService.cs +++ b/src/slskd/Transfers/TransferService.cs @@ -30,51 +30,34 @@ // ╰───────────────────────────────────────────╶──── ─ ─── ─ ── ──┈ ┈ // </copyright> -namespace slskd.Transfers -{ - using slskd.Transfers.Downloads; - using slskd.Transfers.Uploads; +namespace slskd.Transfers; + +using slskd.Transfers.Downloads; +using slskd.Transfers.Uploads; +/// <summary> +/// Manages transfers. +/// </summary> +public class TransferService +{ /// <summary> - /// Manages transfers. + /// Initializes a new instance of the <see cref="TransferService"/> class. /// </summary> - public interface ITransferService + public TransferService( + IUploadService uploadService = null, + IDownloadService downloadService = null) { - /// <summary> - /// Gets the upload service. - /// </summary> - IUploadService Uploads { get; } - - /// <summary> - /// Gets the download service. - /// </summary> - IDownloadService Downloads { get; } + Uploads = uploadService; + Downloads = downloadService; } /// <summary> - /// Manages transfers. + /// Gets the upload service. /// </summary> - public class TransferService : ITransferService - { - /// <summary> - /// Initializes a new instance of the <see cref="TransferService"/> class. - /// </summary> - public TransferService( - IUploadService uploadService = null, - IDownloadService downloadService = null) - { - Uploads = uploadService; - Downloads = downloadService; - } + public virtual IUploadService Uploads { get; init; } - /// <summary> - /// Gets the upload service. - /// </summary> - public IUploadService Uploads { get; init; } - - /// <summary> - /// Gets the download service. - /// </summary> - public IDownloadService Downloads { get; init; } - } + /// <summary> + /// Gets the download service. + /// </summary> + public virtual IDownloadService Downloads { get; init; } }
\ No newline at end of file diff --git a/src/slskd/Transfers/Uploads/UploadQueue.cs b/src/slskd/Transfers/Uploads/UploadQueue.cs index 0929d761..2dca0d9e 100644 --- a/src/slskd/Transfers/Uploads/UploadQueue.cs +++ b/src/slskd/Transfers/Uploads/UploadQueue.cs @@ -32,7 +32,7 @@ using Microsoft.Extensions.Options; -namespace slskd.Transfers +namespace slskd.Transfers.Uploads { using System; using System.Collections.Concurrent; @@ -136,12 +136,18 @@ namespace slskd.Transfers private ILogger Log { get; } = Serilog.Log.ForContext<UploadQueue>(); private IOptionsMonitor<Options> OptionsMonitor { get; } private SemaphoreSlim SyncRoot { get; } = new SemaphoreSlim(1, 1); - private ConcurrentDictionary<string, List<Upload>> Uploads { get; set; } = new ConcurrentDictionary<string, List<Upload>>(); + private ConcurrentDictionary<string, List<Upload>> UploadDictionary { get; set; } = new ConcurrentDictionary<string, List<Upload>>(); private IUserService Users { get; } /// <summary> - /// Awaits the start of an upload. + /// Returns a <see cref="Task"/> that, when complete, signals the underlying Soulseek.NET logic that + /// the 'wait for a free slot' permissive has been obtained. When the <see cref="Process"/> method is + /// ready, it will complete the Task and the upload will start. /// </summary> + /// <remarks> + /// This is the mechanism we use to control the queue; the Task we return here is completed in the + /// <see cref="Process"/> method once we have determined that this transfer is next to go. + /// </remarks> /// <param name="username">The username of the remote user.</param> /// <param name="filename">The filename for which to await the start.</param> /// <returns>The operation context.</returns> @@ -151,7 +157,7 @@ namespace slskd.Transfers try { - if (!Uploads.TryGetValue(username, out var list)) + if (!UploadDictionary.TryGetValue(username, out var list)) { throw new SlskdException($"No enqueued uploads for user {username}"); } @@ -209,7 +215,7 @@ namespace slskd.Transfers try { - if (!Uploads.TryGetValue(username, out var list)) + if (!UploadDictionary.TryGetValue(username, out var list)) { throw new SlskdException($"No enqueued uploads for user {username}"); } @@ -234,10 +240,12 @@ namespace slskd.Transfers Log.Debug("Group {Group} slots: {Used}/{Available}", group.Name, group.UsedSlots, group.Slots); } - if (!list.Any() && Uploads.TryRemove(username, out _)) + if (list.Count == 0 && UploadDictionary.TryRemove(username, out _)) { Log.Debug("Cleaned up tracking list for {User}; no more queued uploads to track", username); } + + EmitMetrics(); } finally { @@ -259,7 +267,7 @@ namespace slskd.Transfers { var upload = new Upload() { Username = username, Filename = filename }; - Uploads.AddOrUpdate( + UploadDictionary.AddOrUpdate( key: username, addValue: new List<Upload>(new[] { upload }), updateValueFactory: (key, list) => @@ -268,6 +276,7 @@ namespace slskd.Transfers return list; }); + EmitMetrics(); Log.Debug("Enqueued: {File} for {User} at {Time}", Path.GetFileName(upload.Filename), upload.Username, upload.Enqueued); } finally @@ -305,7 +314,7 @@ namespace slskd.Transfers var groupRecord = Groups.GetValueOrDefault(groupName); // the Uploads dictionary is keyed by username; gather all of the users that belong to the same group as the requested user - var uploadsForGroup = Uploads.Where(kvp => Users.GetGroup(kvp.Key) == groupName); + var uploadsForGroup = UploadDictionary.Where(kvp => Users.GetGroup(kvp.Key) == groupName); // the RoundRobin queue implementation is not strictly fair to all users; only uploads that are ready are candidates // for selection. this means that if Bob downloads files twice as fast as Alice, Bob is going to advance through the @@ -314,7 +323,7 @@ namespace slskd.Transfers if (groupRecord.Strategy == QueueStrategy.RoundRobin) { // find this user's uploads - if (!Uploads.TryGetValue(username, out var uploadsForUser)) + if (!UploadDictionary.TryGetValue(username, out var uploadsForUser)) { throw new NotFoundException($"File {filename} is not enqueued for user {username}"); } @@ -393,7 +402,7 @@ namespace slskd.Transfers } // the Uploads dictionary is keyed by username; gather all of the users that belong to the same group as the requested user - var uploadsForGroup = Uploads.Where(kvp => Users.GetGroup(kvp.Key) == groupName); + var uploadsForGroup = UploadDictionary.Where(kvp => Users.GetGroup(kvp.Key) == groupName); // assuming that the queue will be processed in a true round-robin fashion and that the user will be the last in the // rotation (worst case), the user's start position will be equal to the number of users downloading or waiting, + 1. @@ -501,7 +510,7 @@ namespace slskd.Transfers // flip the uploads dictionary so that it is keyed by group instead of user. wait until just before we process the // queue to do this, and fetch each user's group as we do, to allow users to move between groups at run time. we // delay "pinning" an upload to a group (via UsedSlots, below) for the same reason. - var readyUploadsByGroup = Uploads.Aggregate( + var readyUploadsByGroup = UploadDictionary.Aggregate( seed: new ConcurrentDictionary<string, List<Upload>>(), func: (groups, user) => { @@ -544,6 +553,9 @@ namespace slskd.Transfers // release the upload upload.TaskCompletionSource.SetResult(); + + EmitMetrics(); + Log.Debug("Started: {File} for {User} at {Time}", Path.GetFileName(upload.Filename), upload.Username, upload.Enqueued); Log.Debug("Group {Group} slots: {Used}/{Available}", group.Name, group.UsedSlots, group.Slots); @@ -557,5 +569,14 @@ namespace slskd.Transfers SyncRoot.Release(); } } + + private void EmitMetrics() + { + Telemetry.Metrics.Update(() => + { + Telemetry.Metrics.Transfers.Uploads.Queued.Users.Set(UploadDictionary.Values.Count(u => u.Any(t => t.Started is null))); + Telemetry.Metrics.Transfers.Uploads.InProgress.Users.Set(UploadDictionary.Values.Count(u => u.Any(t => t.Started is not null))); + }); + } } }
\ No newline at end of file diff --git a/src/slskd/Transfers/Uploads/UploadService.cs b/src/slskd/Transfers/Uploads/UploadService.cs index 9bb09f66..5f98afac 100644 --- a/src/slskd/Transfers/Uploads/UploadService.cs +++ b/src/slskd/Transfers/Uploads/UploadService.cs @@ -69,7 +69,7 @@ namespace slskd.Transfers.Uploads /// <summary> /// Adds the specified <paramref name="transfer"/>. Supersedes any existing record for the same file and username. /// </summary> - /// <remarks>This should generally not be called; use <see cref="EnqueueAsync(string, string)"/> instead.</remarks> + /// <remarks>This should generally not be called; use <see cref="EnqueueAsync(string, string, CancellationToken)"/> instead.</remarks> /// <param name="transfer"></param> void AddOrSupersede(Transfer transfer); @@ -78,20 +78,22 @@ namespace slskd.Transfers.Uploads /// </summary> /// <param name="username">The username of the requesting user.</param> /// <param name="filename">The local filename of the requested file.</param> + /// <param name="cancellationToken">The token to monitor for cancellation.</param> /// <returns>The operation context.</returns> - Task<Transfer> EnqueueAsync(string username, string filename); + Task<Transfer> EnqueueAsync(string username, string filename, CancellationToken cancellationToken = default); /// <summary> /// Uploads the specified enqueued <paramref name="transfer"/> to the requesting user. /// </summary> /// <param name="transfer">The Transfer to upload.</param> + /// <param name="cancellationToken">The token to monitor for cancellation.</param> /// <returns>The operation context.</returns> /// <exception cref="ArgumentNullException">Thrown if the specified Transfer is null.</exception> /// <exception cref="TransferNotFoundException">Thrown if the specified Transfer ID can't be found in the database.</exception> /// <exception cref="InvalidOperationException">Thrown if the specified Transfer is not in the Queued | Locally state.</exception> /// <exception cref="DuplicateTransferException">Thrown if an upload matching the username and filename is already tracked by Soulseek.NET.</exception> /// <exception cref="NotFoundException">Thrown if the specified file can't be found on disk.</exception> - Task<Transfer> UploadAsync(Transfer transfer); + Task<Transfer> UploadAsync(Transfer transfer, CancellationToken cancellationToken = default); /// <summary> /// Finds a single upload matching the specified <paramref name="expression"/>. @@ -194,6 +196,8 @@ namespace slskd.Transfers.Uploads Governor = new UploadGovernor(userService, optionsMonitor); Queue = new UploadQueue(userService, optionsMonitor); + + Clock.EveryFiveSeconds += (_, _) => Task.Run(() => EmitMetrics()); } /// <summary> @@ -221,7 +225,7 @@ namespace slskd.Transfers.Uploads /// <summary> /// Adds the specified <paramref name="transfer"/>. Supersedes any existing record for the same file and username. /// </summary> - /// <remarks>This should generally not be called; use <see cref="EnqueueAsync(string, string)"/> instead.</remarks> + /// <remarks>This should generally not be called; use <see cref="EnqueueAsync(string, string, CancellationToken)"/> instead.</remarks> /// <param name="transfer"></param> public void AddOrSupersede(Transfer transfer) { @@ -248,20 +252,23 @@ namespace slskd.Transfers.Uploads /// Uploads the specified enqueued <paramref name="transfer"/> to the requesting user. /// </summary> /// <param name="transfer">The Transfer to upload.</param> + /// <param name="cancellationToken">The token to monitor for cancellation.</param> /// <returns>The operation context.</returns> /// <exception cref="ArgumentNullException">Thrown if the specified Transfer is null.</exception> /// <exception cref="TransferNotFoundException">Thrown if the specified Transfer ID can't be found in the database.</exception> /// <exception cref="InvalidOperationException">Thrown if the specified Transfer is not in the Queued | Locally state.</exception> /// <exception cref="DuplicateTransferException">Thrown if an upload matching the username and filename is already tracked by Soulseek.NET.</exception> /// <exception cref="NotFoundException">Thrown if the specified file can't be found on disk.</exception> - public async Task<Transfer> UploadAsync(Transfer transfer) + public async Task<Transfer> UploadAsync(Transfer transfer, CancellationToken cancellationToken = default) { - var cts = new CancellationTokenSource(); + var cts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken); var syncRoot = new SemaphoreSlim(1, 1); string host = default; string localFilename = default; long localFileLength = default; + var stateHistory = new List<TransferStates>(); + DateTime lastReportedAverageSpeed = default; var lockName = $"{nameof(UploadAsync)}:{transfer.Username}:{transfer.Filename}"; @@ -345,6 +352,25 @@ namespace slskd.Transfers.Uploads transfer = transfer.WithSoulseekTransfer(args.Transfer); + Telemetry.Metrics.Update(() => + { + if (!TransferStateCategories.Queued.Contains(args.PreviousState) && TransferStateCategories.Queued.Contains(transfer.State)) + { + Telemetry.Metrics.Transfers.Uploads.Queued.Files.Inc(1); + Telemetry.Metrics.Transfers.Uploads.Queued.Bytes.Inc(transfer.Size); + } + + if (!TransferStateCategories.InProgress.Contains(args.PreviousState) && TransferStateCategories.InProgress.Contains(transfer.State)) + { + Telemetry.Metrics.Transfers.Uploads.Queued.Files.Dec(1); + Telemetry.Metrics.Transfers.Uploads.Queued.Bytes.Dec(transfer.Size); + Telemetry.Metrics.Transfers.Uploads.InProgress.Files.Inc(1); + Telemetry.Metrics.Transfers.Uploads.InProgress.Bytes.Inc(transfer.Size); + } + }, cancellationToken); + + stateHistory.Add(transfer.State); + // todo: broadcast SynchronizedUpdate(transfer, semaphore: syncRoot, cancellationToken: cts.Token); }, @@ -372,6 +398,22 @@ namespace slskd.Transfers.Uploads context.Transfers.Where(t => t.Id == transfer.Id).ExecuteUpdate(setter => setter .SetProperty(t => t.BytesTransferred, transfer.BytesTransferred) .SetProperty(t => t.AverageSpeed, transfer.AverageSpeed)); + + // progress is reported at 4x the speed (250ms) that the transfer's average speed is calculated (1000ms) + // the transfer's speed is also zero until it has enough data to compute the EMA, so throw both + // repeated and zero values out + var now = DateTime.UtcNow; + + if (transfer.AverageSpeed > 0 && now >= lastReportedAverageSpeed.AddMilliseconds(1000)) + { + Telemetry.Metrics.Update(() => + { + Telemetry.Metrics.Transfers.Uploads.InProgress.CurrentAverageSpeed.Update(transfer.AverageSpeed); + }, cancellationToken); + + lastReportedAverageSpeed = now; + } + } finally { @@ -444,6 +486,13 @@ namespace slskd.Transfers.Uploads // todo: broadcast SynchronizedUpdate(transfer, semaphore: syncRoot, cancellationToken: CancellationToken.None); + Telemetry.Metrics.Update(() => + { + Telemetry.Metrics.Transfers.Uploads.Completed.Succeeded.Inc(1); + Telemetry.Metrics.Transfers.Uploads.Completed.Bytes.Inc(transfer.BytesTransferred); + Telemetry.Metrics.Transfers.Uploads.Completed.AverageSpeed.Observe(transfer.AverageSpeed); + }, cancellationToken); + EventBus.Raise(new UploadFileCompleteEvent { Timestamp = transfer.EndedAt.Value, @@ -463,6 +512,11 @@ namespace slskd.Transfers.Uploads // todo: broadcast SynchronizedUpdate(transfer, semaphore: syncRoot, cancellationToken: CancellationToken.None); + Telemetry.Metrics.Update(() => + { + Telemetry.Metrics.Transfers.Uploads.Completed.Failed.Inc(1); + }, cancellationToken); + throw; } catch (Exception ex) when (ex is OperationCanceledException || ex is TimeoutException) @@ -474,6 +528,11 @@ namespace slskd.Transfers.Uploads // todo: broadcast SynchronizedUpdate(transfer, semaphore: syncRoot, cancellationToken: CancellationToken.None); + Telemetry.Metrics.Update(() => + { + Telemetry.Metrics.Transfers.Uploads.Completed.Failed.Inc(1); + }, cancellationToken); + throw; } catch (Exception ex) @@ -485,10 +544,37 @@ namespace slskd.Transfers.Uploads // todo: broadcast SynchronizedUpdate(transfer, semaphore: syncRoot, cancellationToken: CancellationToken.None); + Telemetry.Metrics.Update(() => + { + Telemetry.Metrics.Transfers.Uploads.Completed.Failed.Inc(1); + }, cancellationToken); + throw; } finally { + Log.Debug("Upload of {Filename} to user {Username} completed with states: {@States}", FileSafety.GetFileNameSafely(transfer.Filename), transfer.Username, stateHistory); + + // figure out the most recent state that was either InProgress or Queued so that we can decrement the count and bytes + // for transfers that succeed this will be InProgress, for transfers that never started this will be Queued (cancelled or something) + // state will almost certainly transition to errored or completed before we get here, so we can't just take the last state + var mostRecentQueuedOrInProgressState = stateHistory + .LastOrDefault(s => TransferStateCategories.InProgress.Contains(s) || TransferStateCategories.Queued.Contains(s)); + + Telemetry.Metrics.Update(() => + { + if (TransferStateCategories.InProgress.Contains(mostRecentQueuedOrInProgressState) && Telemetry.Metrics.Transfers.Uploads.InProgress.Files.Value > 0) + { + Telemetry.Metrics.Transfers.Uploads.InProgress.Files.Dec(1); + Telemetry.Metrics.Transfers.Uploads.InProgress.Bytes.Dec(transfer.Size); + } + else if (TransferStateCategories.Queued.Contains(mostRecentQueuedOrInProgressState) && Telemetry.Metrics.Transfers.Uploads.Queued.Files.Value > 0) + { + Telemetry.Metrics.Transfers.Uploads.Queued.Files.Dec(1); + Telemetry.Metrics.Transfers.Uploads.Queued.Bytes.Dec(transfer.Size); + } + }, cancellationToken); + if (host != Program.LocalHostName) { try @@ -506,7 +592,9 @@ namespace slskd.Transfers.Uploads Locks.TryRemove(lockName, out _); Log.Debug("Released lock {LockName}", lockName); - CancellationTokens.TryRemove(transfer.Id, out _); + CancellationTokens.TryRemove(transfer.Id, out var registeredCts); + registeredCts?.TryDispose(); + cts?.TryDispose(); // if for some reason this logic exits without the slotReleased delegate and Complete() being invoked, // the file will get stuck in the queue and prevent any further uploads to the user. be extra cautious @@ -525,8 +613,9 @@ namespace slskd.Transfers.Uploads /// </summary> /// <param name="username">The username of the requesting user.</param> /// <param name="filename">The local filename of the requested file.</param> + /// <param name="cancellationToken">The token to monitor for cancellation.</param> /// <returns>The operation context.</returns> - public async Task<Transfer> EnqueueAsync(string username, string filename) + public async Task<Transfer> EnqueueAsync(string username, string filename, CancellationToken cancellationToken = default) { if (string.IsNullOrEmpty(username)) { @@ -681,7 +770,7 @@ namespace slskd.Transfers.Uploads { Log.Error(task.Exception, "Failed to clean up transfer {Id} after failed execution: {Message}", id, task.Exception.Message); } - }); + }, cancellationToken); return transfer; } @@ -940,6 +1029,57 @@ namespace slskd.Transfers.Uploads return stats ?? new UserUploadStatistics(); } + protected virtual void EmitMetrics() + { + void EmitQueuedMetrics() + { + var queued = Client.Uploads.Where(u => u.State.HasFlag(TransferStates.Queued)); + + Telemetry.Metrics.Transfers.Uploads.Queued.Users + .Set(queued.Select(u => u.Username).Distinct().Count()); + + Telemetry.Metrics.Transfers.Uploads.Queued.Files + .Set(queued.Count()); + + Telemetry.Metrics.Transfers.Uploads.Queued.Bytes + .Set(queued.Sum(q => q.Size)); + } + + void EmitInProgressMetrics() + { + var inProgress = Client.Uploads.Where(u => u.State == TransferStates.InProgress); + + Telemetry.Metrics.Transfers.Uploads.InProgress.Users + .Set(inProgress.Select(u => u.Username).Distinct().Count()); + + Telemetry.Metrics.Transfers.Uploads.InProgress.Files + .Set(inProgress.Count()); + + Telemetry.Metrics.Transfers.Uploads.InProgress.Bytes + .Set(inProgress.Sum(u => u.Size)); + + if (inProgress.Any()) + { + Telemetry.Metrics.Transfers.Uploads.InProgress.CurrentTotalSpeed + .Update(inProgress.Sum(u => u.AverageSpeed)); + + Telemetry.Metrics.Transfers.Uploads.InProgress.CurrentAverageSpeed + .Update(inProgress.Any() ? inProgress.Average(u => u.AverageSpeed) : 0); + } + else + { + Telemetry.Metrics.Transfers.Uploads.InProgress.CurrentTotalSpeed.Reset(); + Telemetry.Metrics.Transfers.Uploads.InProgress.CurrentAverageSpeed.Reset(); + } + } + + Telemetry.Metrics.Update(() => + { + EmitQueuedMetrics(); + EmitInProgressMetrics(); + }); + } + private bool TryFail(Guid id, string exception, TransferStates state) { var t = Find(t => t.Id == id); |
