Implemented node system statistics
This commit is contained in:
59
MoonlightServers.Daemon/Helpers/SystemMetrics.Memory.cs
Normal file
59
MoonlightServers.Daemon/Helpers/SystemMetrics.Memory.cs
Normal file
@@ -0,0 +1,59 @@
|
||||
namespace MoonlightServers.Daemon.Helpers;
|
||||
|
||||
public partial class SystemMetrics
|
||||
{
|
||||
/// <summary>Memory figures derived from <c>/proc/meminfo</c>.</summary>
|
||||
/// <param name="TotalBytes">Physical RAM installed.</param>
|
||||
/// <param name="UsedBytes">RAM actively in use (<c>Total - Available</c>).</param>
|
||||
/// <param name="FreeBytes">Completely unallocated RAM.</param>
|
||||
/// <param name="CachedBytes">Page cache + reclaimable slab — matches the <c>cached</c> column in <c>free -h</c>.</param>
|
||||
/// <param name="BuffersBytes">Kernel I/O buffer memory.</param>
|
||||
/// <param name="AvailableBytes">Estimated RAM available for new allocations without swapping.</param>
|
||||
/// <param name="UsedPercent">UsedBytes / TotalBytes as a percentage (0–100).</param>
|
||||
public record MemoryInfo(
|
||||
long TotalBytes,
|
||||
long UsedBytes,
|
||||
long FreeBytes,
|
||||
long CachedBytes,
|
||||
long BuffersBytes,
|
||||
long AvailableBytes,
|
||||
double UsedPercent
|
||||
);
|
||||
|
||||
// Memory — /proc/meminfo
|
||||
|
||||
/// <summary>
|
||||
/// Parses <c>/proc/meminfo</c> into a <see cref="MemoryInfo"/> record.
|
||||
/// The <c>CachedBytes</c> field is computed as
|
||||
/// <c>Cached + SReclaimable - Shmem</c> to match the value shown by <c>free -h</c>.
|
||||
/// </summary>
|
||||
private static async Task<MemoryInfo> ReadMemoryAsync()
|
||||
{
|
||||
var lines = await File.ReadAllLinesAsync("/proc/meminfo");
|
||||
var map = new Dictionary<string, long>(StringComparer.Ordinal);
|
||||
|
||||
foreach (var line in lines)
|
||||
{
|
||||
var colon = line.IndexOf(':');
|
||||
if (colon < 0)
|
||||
continue;
|
||||
|
||||
var key = line[..colon].Trim();
|
||||
var val = line[(colon + 1)..].Trim().Split(' ')[0]; // Strip "kB" suffix.
|
||||
if (long.TryParse(val, out var kb))
|
||||
map[key] = kb * 1024L;
|
||||
}
|
||||
|
||||
var total = map.GetValueOrDefault("MemTotal");
|
||||
var available = map.GetValueOrDefault("MemAvailable");
|
||||
var free = map.GetValueOrDefault("MemFree");
|
||||
var buffers = map.GetValueOrDefault("Buffers");
|
||||
var cached = map.GetValueOrDefault("Cached")
|
||||
+ map.GetValueOrDefault("SReclaimable")
|
||||
- map.GetValueOrDefault("Shmem");
|
||||
var used = total - available;
|
||||
var usedPct = total > 0 ? Math.Round((double)used / total * 100.0, 2) : 0.0;
|
||||
|
||||
return new MemoryInfo(total, used, free, cached, buffers, available, usedPct);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user