Expand pk;stats functionality

This commit is contained in:
Ske
2019-12-22 12:50:47 +01:00
parent 93a52ff95a
commit b81eda47aa
5 changed files with 158 additions and 34 deletions

View File

@@ -0,0 +1,47 @@
using System.Diagnostics;
using System.Threading.Tasks;
using Serilog;
namespace PluralKit.Bot
{
public class CpuStatService
{
private ILogger _logger;
public double LastCpuMeasure { get; private set; }
public CpuStatService(ILogger logger)
{
_logger = logger;
}
/// <summary>
/// Gets the current CPU usage. Estimation takes ~5 seconds (of mostly sleeping).
/// </summary>
public async Task<double> EstimateCpuUsage()
{
// We get the current processor time, wait 5 seconds, then compare
// https://medium.com/@jackwild/getting-cpu-usage-in-net-core-7ef825831b8b
_logger.Information("Estimating CPU usage...");
var stopwatch = new Stopwatch();
stopwatch.Start();
var cpuTimeBefore = Process.GetCurrentProcess().TotalProcessorTime;
await Task.Delay(5000);
stopwatch.Stop();
var cpuTimeAfter = Process.GetCurrentProcess().TotalProcessorTime;
var cpuTimePassed = cpuTimeAfter - cpuTimeBefore;
var timePassed = stopwatch.Elapsed;
var percent = cpuTimePassed / timePassed;
_logger.Information("CPU usage measured as {Percent:P}", percent);
LastCpuMeasure = percent;
return percent;
}
}
}

View File

@@ -16,6 +16,7 @@ namespace PluralKit.Bot
{
private DiscordShardedClient _client;
private IMetrics _metrics;
private CpuStatService _cpu;
private IDataStore _data;
@@ -25,13 +26,14 @@ namespace PluralKit.Bot
private ILogger _logger;
public PeriodicStatCollector(IDiscordClient client, IMetrics metrics, ILogger logger, WebhookCacheService webhookCache, DbConnectionCountHolder countHolder, IDataStore data)
public PeriodicStatCollector(IDiscordClient client, IMetrics metrics, ILogger logger, WebhookCacheService webhookCache, DbConnectionCountHolder countHolder, IDataStore data, CpuStatService cpu)
{
_client = (DiscordShardedClient) client;
_metrics = metrics;
_webhookCache = webhookCache;
_countHolder = countHolder;
_data = data;
_cpu = cpu;
_logger = logger.ForContext<PeriodicStatCollector>();
}
@@ -71,7 +73,7 @@ namespace PluralKit.Bot
_metrics.Measure.Gauge.SetValue(CoreMetrics.ProcessPrivateMemory, process.PrivateMemorySize64);
_metrics.Measure.Gauge.SetValue(CoreMetrics.ProcessThreads, process.Threads.Count);
_metrics.Measure.Gauge.SetValue(CoreMetrics.ProcessHandles, process.HandleCount);
_metrics.Measure.Gauge.SetValue(CoreMetrics.CpuUsage, await EstimateCpuUsage());
_metrics.Measure.Gauge.SetValue(CoreMetrics.CpuUsage, await _cpu.EstimateCpuUsage());
// Database info
_metrics.Measure.Gauge.SetValue(CoreMetrics.DatabaseConnections, _countHolder.ConnectionCount);
@@ -82,29 +84,5 @@ namespace PluralKit.Bot
stopwatch.Stop();
_logger.Information("Updated metrics in {Time}", stopwatch.ElapsedDuration());
}
private async Task<double> EstimateCpuUsage()
{
// We get the current processor time, wait 5 seconds, then compare
// https://medium.com/@jackwild/getting-cpu-usage-in-net-core-7ef825831b8b
_logger.Information("Estimating CPU usage...");
var stopwatch = new Stopwatch();
stopwatch.Start();
var cpuTimeBefore = Process.GetCurrentProcess().TotalProcessorTime;
await Task.Delay(5000);
stopwatch.Stop();
var cpuTimeAfter = Process.GetCurrentProcess().TotalProcessorTime;
var cpuTimePassed = cpuTimeAfter - cpuTimeBefore;
var timePassed = stopwatch.Elapsed;
var percent = cpuTimePassed / timePassed;
_logger.Information("CPU usage measured as {Percent:P}", percent);
return percent;
}
}
}

View File

@@ -0,0 +1,58 @@
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Discord.WebSocket;
using NodaTime;
namespace PluralKit.Bot
{
public class ShardInfoService
{
public class ShardInfo
{
public Instant LastConnectionTime;
public int DisconnectionCount;
public int ShardLatency;
}
private Dictionary<int, ShardInfo> _shardInfo = new Dictionary<int, ShardInfo>();
public void Init(DiscordShardedClient client)
{
for (var i = 0; i < client.Shards.Count; i++)
_shardInfo[i] = new ShardInfo();
client.ShardConnected += ShardConnected;
client.ShardDisconnected += ShardDisconnected;
client.ShardReady += ShardReady;
client.ShardLatencyUpdated += ShardLatencyUpdated;
}
public ShardInfo GetShardInfo(DiscordSocketClient shard) => _shardInfo[shard.ShardId];
private Task ShardLatencyUpdated(int oldLatency, int newLatency, DiscordSocketClient shard)
{
_shardInfo[shard.ShardId].ShardLatency = newLatency;
return Task.CompletedTask;
}
private Task ShardReady(DiscordSocketClient shard)
{
return Task.CompletedTask;
}
private Task ShardDisconnected(Exception e, DiscordSocketClient shard)
{
_shardInfo[shard.ShardId].DisconnectionCount++;
return Task.CompletedTask;
}
private Task ShardConnected(DiscordSocketClient shard)
{
_shardInfo[shard.ShardId].LastConnectionTime = SystemClock.Instance.GetCurrentInstant();
return Task.CompletedTask;
}
}
}