aboutsummaryrefslogtreecommitdiffstats
path: root/src/slskd
diff options
context:
space:
mode:
authorJP Dillingham <jp@dillingham.me>2022-08-28 22:04:54 -0500
committerGitHub <noreply@github.com>2022-08-28 22:04:54 -0500
commitfd91051fbe04cd3db23b197f75dff8a566b2e007 (patch)
treec4d4016c210cf790215480017cd239703d61a546 /src/slskd
parentb82b84d955d403aab4e9da1ea1fc68e08c54dbbb (diff)
parenta746ccab1a31c9e97a32abc707250d645618fa4c (diff)
downloadslskd-fd91051fbe04cd3db23b197f75dff8a566b2e007.tar.gz
Merge pull request #617 from slskd/metrics
Add metrics tracking search and browse activity and distributed network state
Diffstat (limited to 'src/slskd')
-rw-r--r--src/slskd/Application.cs36
-rw-r--r--src/slskd/Common/ExponentialMovingAverage.cs71
-rw-r--r--src/slskd/Core/API/Controllers/MetricsController.cs54
-rw-r--r--src/slskd/Core/Clock.cs40
-rw-r--r--src/slskd/Core/Metrics.cs125
-rw-r--r--src/slskd/slskd.csproj2
6 files changed, 327 insertions, 1 deletions
diff --git a/src/slskd/Application.cs b/src/slskd/Application.cs
index ed3aec30..04dbab2e 100644
--- a/src/slskd/Application.cs
+++ b/src/slskd/Application.cs
@@ -160,6 +160,8 @@ namespace slskd
Client.DownloadFailed += (e, args) => Log.Information("Download of {Filename} from {Username} failed", args.Filename, args.Username);
ConnectionWatchdog = connectionWatchdog;
+
+ Clock.EveryMinute += Clock_EveryMinute;
}
/// <summary>
@@ -408,11 +410,22 @@ namespace slskd
/// <returns>A Task resolving an IEnumerable of Soulseek.Directory.</returns>
private async Task<BrowseResponse> BrowseResponseResolver(string username, IPEndPoint endpoint)
{
+ Metrics.Browse.RequestsReceived.Inc(1);
+
try
{
+ var sw = new Stopwatch();
+ sw.Start();
+
var directories = (await Shares.BrowseAsync())
.Select(d => new Soulseek.Directory(d.Name.Replace('/', '\\'), d.Files)); // Soulseek NS requires backslashes
+ sw.Stop();
+
+ Metrics.Browse.ResponseLatency.Observe(sw.ElapsedMilliseconds);
+ Metrics.Browse.CurrentResponseLatency.Update(sw.ElapsedMilliseconds);
+ Metrics.Browse.ResponsesSent.Inc(1);
+
return new BrowseResponse(directories);
}
catch (Exception ex)
@@ -623,6 +636,17 @@ namespace slskd
Parent = e.Parent.Username,
},
});
+
+ Metrics.DistributedNetwork.HasParent.Set(e.HasParent ? 1 : 0);
+ Metrics.DistributedNetwork.BranchLevel.Set(e.BranchLevel);
+ Metrics.DistributedNetwork.ChildLimit.Set(e.ChildLimit);
+ Metrics.DistributedNetwork.Children.Set(e.Children.Count);
+ }
+
+ private void Clock_EveryMinute(object sender, EventArgs e)
+ {
+ Metrics.DistributedNetwork.BroadcastLatency.Observe(Client.DistributedNetwork.AverageBroadcastLatency ?? 0);
+ Metrics.DistributedNetwork.CurrentBroadcastLatency.Set(Client.DistributedNetwork.AverageBroadcastLatency ?? 0);
}
private void Client_TransferProgressUpdated(object sender, TransferProgressUpdatedEventArgs args)
@@ -876,6 +900,8 @@ namespace slskd
/// <returns>A Task resolving a SearchResponse, or null.</returns>
private async Task<SearchResponse> SearchResponseResolver(string username, int token, SearchQuery query)
{
+ Metrics.Search.RequestsReceived.Inc(1);
+
if (CompiledSearchResponseFilters.Any(filter => filter.IsMatch(query.SearchText)))
{
return null;
@@ -890,8 +916,16 @@ namespace slskd
try
{
+ var sw = new Stopwatch();
+ sw.Start();
+
var results = await Shares.SearchAsync(query);
+ sw.Stop();
+
+ Metrics.Search.ResponseLatency.Observe(sw.ElapsedMilliseconds);
+ Metrics.Search.CurrentResponseLatency.Update(sw.ElapsedMilliseconds);
+
if (results.Any())
{
// make sure our average speed (as reported by the server) is reasonably up to date
@@ -901,6 +935,8 @@ namespace slskd
Log.Information("[{Context}]: Sending {Count} records to {Username} for query '{Query}'", "SEARCH RESULT SENT", results.Count(), username, query.SearchText);
+ Metrics.Search.ResponsesSent.Inc(1);
+
return new SearchResponse(
Client.Username,
token,
diff --git a/src/slskd/Common/ExponentialMovingAverage.cs b/src/slskd/Common/ExponentialMovingAverage.cs
new file mode 100644
index 00000000..76e39333
--- /dev/null
+++ b/src/slskd/Common/ExponentialMovingAverage.cs
@@ -0,0 +1,71 @@
+// <copyright file="ExponentialMovingAverage.cs" company="slskd Team">
+// Copyright (c) slskd Team. All rights reserved.
+//
+// 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, either version 3 of the License, or
+// (at your option) any later version.
+//
+// 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/.
+// </copyright>
+
+using System;
+
+namespace slskd
+{
+ /// <summary>
+ /// An exponential moving average.
+ /// </summary>
+ public class ExponentialMovingAverage
+ {
+ /// <summary>
+ /// Initializes a new instance of the <see cref="ExponentialMovingAverage"/> class.
+ /// </summary>
+ /// <param name="smoothingFactor"></param>
+ public ExponentialMovingAverage(double smoothingFactor)
+ {
+ SmoothingFactor = smoothingFactor;
+ }
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="ExponentialMovingAverage"/> class.
+ /// </summary>
+ /// <param name="smoothingFactor"></param>
+ /// <param name="onUpdate"></param>
+ public ExponentialMovingAverage(double smoothingFactor, Action<double> onUpdate = null)
+ : this(smoothingFactor)
+ {
+ OnUpdate = onUpdate;
+ }
+
+ /// <summary>
+ /// Gets the current value.
+ /// </summary>
+ public double Value { get; private set; } = 0;
+
+ /// <summary>
+ /// Gets a value indicating whether the average has been initialized.
+ /// </summary>
+ public bool Initialized { get; private set; } = false;
+
+ private double SmoothingFactor { get; }
+ private Action<double> OnUpdate { get; }
+
+ /// <summary>
+ /// Updates the average with a new value.
+ /// </summary>
+ /// <param name="value"></param>
+ public void Update(double value)
+ {
+ Value = !Initialized ? value : ((value - Value) * SmoothingFactor) + Value;
+ Initialized = true;
+ OnUpdate?.Invoke(Value);
+ }
+ }
+}
diff --git a/src/slskd/Core/API/Controllers/MetricsController.cs b/src/slskd/Core/API/Controllers/MetricsController.cs
new file mode 100644
index 00000000..aeccd97a
--- /dev/null
+++ b/src/slskd/Core/API/Controllers/MetricsController.cs
@@ -0,0 +1,54 @@
+// <copyright file="MetricsController.cs" company="slskd Team">
+// Copyright (c) slskd Team. All rights reserved.
+//
+// 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, either version 3 of the License, or
+// (at your option) any later version.
+//
+// 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/.
+// </copyright>
+
+namespace slskd.Core.API
+{
+ using System.IO;
+ using System.Threading.Tasks;
+ using Microsoft.AspNetCore.Authorization;
+ using Microsoft.AspNetCore.Mvc;
+
+ /// <summary>
+ /// Logs.
+ /// </summary>
+ [Route("api/v{version:apiVersion}/[controller]")]
+ [ApiVersion("0")]
+ [ApiController]
+ [Produces("text/plain")]
+ [Consumes("text/plain")]
+ public class MetricsController : ControllerBase
+ {
+ /// <summary>
+ /// Gets application metrics.
+ /// </summary>
+ /// <returns></returns>
+ [HttpGet]
+ [Authorize]
+ public async Task<IActionResult> Metrics()
+ {
+ 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();
+
+ return Content(response, "text/plain");
+ }
+ }
+}
diff --git a/src/slskd/Core/Clock.cs b/src/slskd/Core/Clock.cs
new file mode 100644
index 00000000..4d2e6c10
--- /dev/null
+++ b/src/slskd/Core/Clock.cs
@@ -0,0 +1,40 @@
+// <copyright file="Clock.cs" company="slskd Team">
+// Copyright (c) slskd Team. All rights reserved.
+//
+// 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, either version 3 of the License, or
+// (at your option) any later version.
+//
+// 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/.
+// </copyright>
+
+namespace slskd
+{
+ using System;
+ using System.Timers;
+
+ /// <summary>
+ /// The application clock, used for time based events.
+ /// </summary>
+ public static class Clock
+ {
+ static Clock()
+ {
+ EveryMinuteTimer.Elapsed += (_, _) => EveryMinute?.Invoke(null, EventArgs.Empty);
+ }
+
+ /// <summary>
+ /// Fires every 60 seconds.
+ /// </summary>
+ public static event EventHandler EveryMinute;
+
+ private static Timer EveryMinuteTimer { get; } = new Timer() { AutoReset = true, Interval = 60000, Enabled = true };
+ }
+} \ No newline at end of file
diff --git a/src/slskd/Core/Metrics.cs b/src/slskd/Core/Metrics.cs
new file mode 100644
index 00000000..83877500
--- /dev/null
+++ b/src/slskd/Core/Metrics.cs
@@ -0,0 +1,125 @@
+// <copyright file="Metrics.cs" company="slskd Team">
+// Copyright (c) slskd Team. All rights reserved.
+//
+// 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, either version 3 of the License, or
+// (at your option) any later version.
+//
+// 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/.
+// </copyright>
+
+namespace slskd
+{
+ using Prometheus;
+
+ public static class Metrics
+ {
+ public static class Search
+ {
+ /// <summary>
+ /// Gets a histogram representing the time taken to resolve a response to an incoming search request, in milliseconds.
+ /// </summary>
+ public static Histogram ResponseLatency { get; } = Prometheus.Metrics.CreateHistogram(
+ "slskd_search_response_latency",
+ "The time taken to resolve a response to an incoming search request, in milliseconds",
+ new HistogramConfiguration
+ {
+ Buckets = Histogram.ExponentialBuckets(1, 2, 10),
+ });
+
+ /// <summary>
+ /// Gets an EMA representing the average time taken to resolve a response to an incoming search request, in milliseconds.
+ /// </summary>
+ public static ExponentialMovingAverage CurrentResponseLatency { get; } = new ExponentialMovingAverage(smoothingFactor: 0.5, onUpdate: value => CurrentResponseLatencyGauge.Set(value));
+
+ /// <summary>
+ /// Gets a counter representing the total number of search requests received.
+ /// </summary>
+ public static Counter RequestsReceived { get; } = Prometheus.Metrics.CreateCounter("slskd_search_requests_received", "Total number of search requests received");
+
+ /// <summary>
+ /// Gets a counter representing the total number of search responses sent.
+ /// </summary>
+ public static Counter ResponsesSent { get; } = Prometheus.Metrics.CreateCounter("slskd_search_responses_sent", "Total number of search responses sent");
+
+ private static Gauge CurrentResponseLatencyGauge { get; } = Prometheus.Metrics.CreateGauge("slskd_search_response_latency_current", "The average time taken to resolve a response to an incoming search request, in milliseconds");
+ }
+
+ public static class Browse
+ {
+ /// <summary>
+ /// Gets a histogram representing the time taken to resolve a response to an incoming browse request, in milliseconds.
+ /// </summary>
+ public static Histogram ResponseLatency { get; } = Prometheus.Metrics.CreateHistogram(
+ "slskd_browse_response_latency",
+ "The time taken to resolve a response to an incoming browse request, in milliseconds",
+ new HistogramConfiguration
+ {
+ Buckets = Histogram.ExponentialBuckets(1, 2, 10),
+ });
+
+ /// <summary>
+ /// Gets an EMA representing the average time taken to resolve a response to an incoming search request, in milliseconds.
+ /// </summary>
+ public static ExponentialMovingAverage CurrentResponseLatency { get; } = new ExponentialMovingAverage(smoothingFactor: 0.5, onUpdate: value => CurrentResponseLatencyGauge.Set(value));
+
+ /// <summary>
+ /// Gets a counter representing the total number of browse requests received.
+ /// </summary>
+ public static Counter RequestsReceived { get; } = Prometheus.Metrics.CreateCounter("slskd_browse_requests_received", "Total number of browse requests received");
+
+ /// <summary>
+ /// Gets a counter representing the total number of browse responses sent.
+ /// </summary>
+ public static Counter ResponsesSent { get; } = Prometheus.Metrics.CreateCounter("slskd_browse_responses_sent", "Total number of browse responses sent");
+
+ private static Gauge CurrentResponseLatencyGauge { get; } = Prometheus.Metrics.CreateGauge("slskd_browse_response_latency_current", "The average time taken to resolve a response to an incoming browse request, in milliseconds");
+ }
+
+ public static class DistributedNetwork
+ {
+ /// <summary>
+ /// Gets a gauge representing the current number of connected distributed children.
+ /// </summary>
+ public static Gauge Children { get; } = Prometheus.Metrics.CreateGauge("slskd_dnet_children", "Current number of connected distributed children");
+
+ /// <summary>
+ /// Gets a gauge representing the current distributed child limit.
+ /// </summary>
+ public static Gauge ChildLimit { get; } = Prometheus.Metrics.CreateGauge("slskd_dnet_child_limit", "Current distributed child limit");
+
+ /// <summary>
+ /// Gets a gauge indicating whether a distributed parent connection is established.
+ /// </summary>
+ public static Gauge HasParent { get; } = Prometheus.Metrics.CreateGauge("slskd_dnet_has_parent", "A value indicating whether a distributed parent connection is established");
+
+ /// <summary>
+ /// Gets a gauge representing the current distributed branch level.
+ /// </summary>
+ public static Gauge BranchLevel { get; } = Prometheus.Metrics.CreateGauge("slskd_dnet_branch_level", "Current distributed branch level");
+
+ /// <summary>
+ /// Gets a gauge representing the most recent average time tekn to broadcast incoming search requests to connected children.
+ /// </summary>
+ public static Gauge CurrentBroadcastLatency { get; } = Prometheus.Metrics.CreateGauge("slskd_dnet_broadcast_latency_current", "The average time taken to broadcast incoming search requests to connected children");
+
+ /// <summary>
+ /// Gets a histogram representing the time taken to resolve a response to an incoming browse request, in milliseconds.
+ /// </summary>
+ public static Histogram BroadcastLatency { get; } = Prometheus.Metrics.CreateHistogram(
+ "slskd_dnet_broadcast_latency",
+ "The time taken to broadcast incoming search requests to connected children, in milliseconds",
+ new HistogramConfiguration
+ {
+ Buckets = Histogram.ExponentialBuckets(0.5, 2, 12),
+ });
+ }
+ }
+}
diff --git a/src/slskd/slskd.csproj b/src/slskd/slskd.csproj
index d2f0a9b7..8f0f99b2 100644
--- a/src/slskd/slskd.csproj
+++ b/src/slskd/slskd.csproj
@@ -68,7 +68,7 @@
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
- <PackageReference Include="Soulseek" Version="5.1.0" />
+ <PackageReference Include="Soulseek" Version="5.1.1" />
<PackageReference Include="StyleCop.Analyzers" Version="1.2.0-beta.354">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>