From f03ed9169538245b3d2dbb8a7ee9b8301ed38a43 Mon Sep 17 00:00:00 2001 From: Arnaud Dartois Date: Sat, 18 Jul 2026 14:06:09 +0000 Subject: [PATCH] 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. --- .../Services/AgentRegistrationService.cs | 24 ++- .../Services/SystemMetricsProvider.cs | 162 ++++++++++++++++++ 2 files changed, 182 insertions(+), 4 deletions(-) create mode 100644 src/Heimdall.Agent/Services/SystemMetricsProvider.cs diff --git a/src/Heimdall.Agent/Services/AgentRegistrationService.cs b/src/Heimdall.Agent/Services/AgentRegistrationService.cs index 9936754..5f1d3aa 100644 --- a/src/Heimdall.Agent/Services/AgentRegistrationService.cs +++ b/src/Heimdall.Agent/Services/AgentRegistrationService.cs @@ -12,6 +12,7 @@ public class AgentRegistrationService : BackgroundService private readonly IHttpClientFactory _httpClientFactory; private readonly ILogger _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); diff --git a/src/Heimdall.Agent/Services/SystemMetricsProvider.cs b/src/Heimdall.Agent/Services/SystemMetricsProvider.cs new file mode 100644 index 0000000..502c721 --- /dev/null +++ b/src/Heimdall.Agent/Services/SystemMetricsProvider.cs @@ -0,0 +1,162 @@ +using System.Diagnostics; +using System.Runtime.InteropServices; + +namespace Heimdall.Agent.Services; + +/// +/// Collects basic system metrics (CPU, memory, uptime, disk) without external dependencies. +/// Uses /proc on Linux, falls back to safe defaults on other platforms. +/// +public sealed class SystemMetricsProvider +{ + private static readonly DateTime ProcessStart = Process.GetCurrentProcess().StartTime.ToUniversalTime(); + private long _lastCpuTicks; + private DateTime _lastCpuSample = DateTime.UtcNow; + + /// + /// Returns a snapshot of current system metrics. + /// + 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; } +} + +/// +/// Minimal Mono.Posix.NETStandard substitute for OSX memory info. +/// +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; + } + } +}