feat(agent): add system metrics (CPU, memory, disk, uptime) to heartbeat
Introduce SystemMetricsProvider that reads /proc on Linux (with safe fallbacks on other platforms) and includes CPU usage, memory usage, disk usage, and uptime in every heartbeat payload. Allows Central to monitor agent health proactively.
This commit is contained in:
1 parent
4b6e4ce27a
commit
f03ed91695
2 files changed
+182
-4
No files matched your search
@@ -12,6 +12,7 @@ public class AgentRegistrationService : BackgroundService
|
||||
private readonly IHttpClientFactory _httpClientFactory;
|
||||
private readonly ILogger<AgentRegistrationService> _logger;
|
||||
private readonly AgentState _state;
|
||||
private readonly SystemMetricsProvider _metrics = new();
|
||||
private HttpClient? _client;
|
||||
|
||||
public AgentRegistrationService(
|
||||
@@ -34,7 +35,12 @@ public class AgentRegistrationService : BackgroundService
|
||||
_logger.LogInformation("Agent stopping, sending final heartbeat...");
|
||||
try
|
||||
{
|
||||
var request = new HeartbeatRequest(_state.PublicIp, IsOffline: true);
|
||||
var metrics = _metrics.Collect();
|
||||
var request = new HeartbeatRequest(_state.PublicIp, IsOffline: true,
|
||||
CpuUsagePercent: metrics.CpuUsagePercent,
|
||||
MemoryUsageBytes: metrics.MemoryUsageBytes,
|
||||
DiskUsagePercent: metrics.DiskUsagePercent,
|
||||
UptimeSeconds: metrics.UptimeSeconds);
|
||||
await _client.PostAsJsonAsync(
|
||||
$"api/agents/{_state.AgentId}/heartbeat",
|
||||
request, CancellationToken.None);
|
||||
@@ -148,7 +154,13 @@ public class AgentRegistrationService : BackgroundService
|
||||
{
|
||||
try
|
||||
{
|
||||
var heartbeatRequest = new HeartbeatRequest(_state.PublicIp);
|
||||
var metrics = _metrics.Collect();
|
||||
var heartbeatRequest = new HeartbeatRequest(
|
||||
_state.PublicIp,
|
||||
CpuUsagePercent: metrics.CpuUsagePercent,
|
||||
MemoryUsageBytes: metrics.MemoryUsageBytes,
|
||||
DiskUsagePercent: metrics.DiskUsagePercent,
|
||||
UptimeSeconds: metrics.UptimeSeconds);
|
||||
var heartbeatResponse = await client.PostAsJsonAsync(
|
||||
$"api/agents/{_state.AgentId}/heartbeat",
|
||||
heartbeatRequest, stoppingToken);
|
||||
@@ -191,5 +203,9 @@ internal sealed record RegisterResponse(
|
||||
[property: JsonPropertyName("apiKeyPrefix")] string ApiKeyPrefix);
|
||||
|
||||
internal sealed record HeartbeatRequest(
|
||||
string? PublicIp,
|
||||
[property: JsonPropertyName("isOffline")] bool IsOffline = false);
|
||||
[property: JsonPropertyName("publicIp")] string? PublicIp,
|
||||
[property: JsonPropertyName("isOffline")] bool IsOffline = false,
|
||||
[property: JsonPropertyName("cpuUsagePercent")] double? CpuUsagePercent = null,
|
||||
[property: JsonPropertyName("memoryUsageBytes")] long? MemoryUsageBytes = null,
|
||||
[property: JsonPropertyName("diskUsagePercent")] double? DiskUsagePercent = null,
|
||||
[property: JsonPropertyName("uptimeSeconds")] long? UptimeSeconds = null);
|
||||
@@ -0,0 +1,162 @@
|
||||
using System.Diagnostics;
|
||||
using System.Runtime.InteropServices;
|
||||
|
||||
namespace Heimdall.Agent.Services;
|
||||
|
||||
/// <summary>
|
||||
/// Collects basic system metrics (CPU, memory, uptime, disk) without external dependencies.
|
||||
/// Uses /proc on Linux, falls back to safe defaults on other platforms.
|
||||
/// </summary>
|
||||
public sealed class SystemMetricsProvider
|
||||
{
|
||||
private static readonly DateTime ProcessStart = Process.GetCurrentProcess().StartTime.ToUniversalTime();
|
||||
private long _lastCpuTicks;
|
||||
private DateTime _lastCpuSample = DateTime.UtcNow;
|
||||
|
||||
/// <summary>
|
||||
/// Returns a snapshot of current system metrics.
|
||||
/// </summary>
|
||||
public SystemMetrics Collect()
|
||||
{
|
||||
return new SystemMetrics
|
||||
{
|
||||
CpuUsagePercent = GetCpuUsage(),
|
||||
MemoryUsageBytes = Process.GetCurrentProcess().WorkingSet64,
|
||||
TotalMemoryBytes = GetTotalMemory(),
|
||||
DiskUsagePercent = GetDiskUsage(),
|
||||
UptimeSeconds = (long)(DateTime.UtcNow - ProcessStart).TotalSeconds
|
||||
};
|
||||
}
|
||||
|
||||
private double? GetCpuUsage()
|
||||
{
|
||||
try
|
||||
{
|
||||
if (!OperatingSystem.IsLinux())
|
||||
return null;
|
||||
|
||||
var now = DateTime.UtcNow;
|
||||
var cpuTicks = GetTotalCpuTicks();
|
||||
if (cpuTicks is null)
|
||||
return null;
|
||||
|
||||
var elapsedMs = (now - _lastCpuSample).TotalMilliseconds;
|
||||
if (elapsedMs < 500)
|
||||
return null; // too soon for a meaningful delta
|
||||
|
||||
var deltaTicks = cpuTicks.Value - _lastCpuTicks;
|
||||
_lastCpuTicks = cpuTicks.Value;
|
||||
_lastCpuSample = now;
|
||||
|
||||
// /proc/stat reports ticks at CLK_TCK (usually 100 Hz)
|
||||
var usage = deltaTicks / (elapsedMs * 4.0); // 4 logical CPUs approximation
|
||||
return Math.Round(Math.Clamp(usage * 100.0, 0, 100), 1);
|
||||
}
|
||||
catch
|
||||
{
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private static long? GetTotalCpuTicks()
|
||||
{
|
||||
var line = File.ReadLines("/proc/stat").FirstOrDefault();
|
||||
if (line is null || !line.StartsWith("cpu ", StringComparison.Ordinal))
|
||||
return null;
|
||||
|
||||
// cpu user nice system idle iowait irq softirq steal
|
||||
var parts = line.Split(' ', StringSplitOptions.RemoveEmptyEntries);
|
||||
if (parts.Length < 5)
|
||||
return null;
|
||||
|
||||
return parts.Skip(1).Take(4).Sum(p => long.TryParse(p, out var v) ? v : 0);
|
||||
}
|
||||
|
||||
private static long? GetTotalMemory()
|
||||
{
|
||||
try
|
||||
{
|
||||
if (OperatingSystem.IsLinux())
|
||||
{
|
||||
var memTotal = File.ReadLines("/proc/meminfo")
|
||||
.FirstOrDefault(l => l.StartsWith("MemTotal:", StringComparison.Ordinal));
|
||||
if (memTotal is not null)
|
||||
{
|
||||
var value = memTotal.Split(' ', StringSplitOptions.RemoveEmptyEntries)
|
||||
.Skip(1).FirstOrDefault();
|
||||
if (long.TryParse(value, out var kb))
|
||||
return kb * 1024;
|
||||
}
|
||||
}
|
||||
|
||||
return RuntimeInformation.IsOSPlatform(OSPlatform.OSX)
|
||||
? (long?)SystemInfo.GetPhysicalMemory()
|
||||
: null;
|
||||
}
|
||||
catch
|
||||
{
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private static double? GetDiskUsage()
|
||||
{
|
||||
try
|
||||
{
|
||||
if (OperatingSystem.IsLinux())
|
||||
{
|
||||
var drive = new DriveInfo(Directory.GetDirectoryRoot(AppContext.BaseDirectory));
|
||||
if (drive.IsReady && drive.TotalSize > 0)
|
||||
{
|
||||
return Math.Round((double)(drive.TotalSize - drive.AvailableFreeSpace) / drive.TotalSize * 100, 1);
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
catch
|
||||
{
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public sealed record SystemMetrics
|
||||
{
|
||||
public double? CpuUsagePercent { get; init; }
|
||||
public long? MemoryUsageBytes { get; init; }
|
||||
public long? TotalMemoryBytes { get; init; }
|
||||
public double? DiskUsagePercent { get; init; }
|
||||
public long? UptimeSeconds { get; init; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Minimal Mono.Posix.NETStandard substitute for OSX memory info.
|
||||
/// </summary>
|
||||
internal static class SystemInfo
|
||||
{
|
||||
// macOS: sysctl hw.memsize via process invocation
|
||||
public static long GetPhysicalMemory()
|
||||
{
|
||||
try
|
||||
{
|
||||
using var proc = Process.Start(new ProcessStartInfo
|
||||
{
|
||||
FileName = "sysctl",
|
||||
Arguments = "-n hw.memsize",
|
||||
RedirectStandardOutput = true,
|
||||
UseShellExecute = false,
|
||||
CreateNoWindow = true
|
||||
});
|
||||
|
||||
if (proc is null) return 0;
|
||||
var output = proc.StandardOutput.ReadToEnd();
|
||||
proc.WaitForExit(1000);
|
||||
return long.TryParse(output?.Trim(), out var mem) ? mem : 0;
|
||||
}
|
||||
catch
|
||||
{
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user