diff --git a/src/Heimdall.Infrastructure/Jobs/AgentMetricSampleJob.cs b/src/Heimdall.Infrastructure/Jobs/AgentMetricSampleJob.cs index ab67621..612b7bd 100644 --- a/src/Heimdall.Infrastructure/Jobs/AgentMetricSampleJob.cs +++ b/src/Heimdall.Infrastructure/Jobs/AgentMetricSampleJob.cs @@ -1,7 +1,9 @@ using Heimdall.Domain.Entities; +using Heimdall.Domain.Enums; using Heimdall.Infrastructure.Data; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Logging; +using System.Text.Json; namespace Heimdall.Infrastructure.Jobs; @@ -29,29 +31,39 @@ public sealed class AgentMetricSampleJob var capturedAt = new DateTime(now.Ticks - now.Ticks % SampleInterval.Ticks, DateTimeKind.Utc); var activeSince = now.AddMinutes(-2); - // The unique (AgentId, CapturedAtUtc) index makes Hangfire retries and - // duplicate executions safe without dropping a whole batch on conflict. - var sampled = await db.Database.ExecuteSqlInterpolatedAsync($$""" - INSERT INTO "agent_metric_samples" - ("Id", "AgentId", "SiteId", "CapturedAtUtc", "LogicalCores", "CpuUsagePercent", - "MemoryUsageBytes", "MemTotalBytes", "MemAvailableBytes", "DiskUsagePercent", "GpuTemperatureCelsius", - "GpuUtilizationPercent", "TemperatureJson", "InventoryObservedAtUtc") - SELECT gen_random_uuid(), a."Id", a."SiteId", {{capturedAt}}, a."LogicalCores", a."CpuUsagePercent", - a."MemoryUsageBytes", a."MemTotalBytes", a."MemAvailableBytes", a."DiskUsagePercent", gpu."TemperatureCelsius", - gpu."UtilizationPercent", a."TemperatureJson", a."InventoryObservedAtUtc" - FROM "agents" AS a - LEFT JOIN LATERAL ( - SELECT AVG(COALESCE((device.value->>'TemperatureCelsius')::double precision, - (device.value->>'temperatureCelsius')::double precision)) AS "TemperatureCelsius", - AVG(COALESCE((device.value->>'UtilizationPercent')::double precision, - (device.value->>'utilizationPercent')::double precision)) AS "UtilizationPercent" - FROM jsonb_array_elements(COALESCE(NULLIF(a."GpuInventoryJson", '')::jsonb, '[]'::jsonb)) AS device(value) - ) AS gpu ON TRUE - WHERE a."Status" = 'Online' - AND a."IsDeleted" = FALSE - AND a."LastHeartbeat" >= {{activeSince}} - ON CONFLICT ("AgentId", "CapturedAtUtc") DO NOTHING - """, ct).ConfigureAwait(false); + // Parse this heartbeat field in .NET: it is agent-provided text and may + // contain malformed JSON. A bad GPU payload must not abort every sample. + var agents = await db.Agents + .AsNoTracking() + .Where(agent => agent.Status == AgentStatus.Online && !agent.IsDeleted && agent.LastHeartbeat >= activeSince) + .Select(agent => new + { + agent.Id, agent.SiteId, agent.LogicalCores, agent.CpuUsagePercent, + agent.MemoryUsageBytes, agent.MemTotalBytes, agent.MemAvailableBytes, + agent.DiskUsagePercent, agent.GpuInventoryJson, agent.TemperatureJson, + agent.InventoryObservedAtUtc + }) + .ToListAsync(ct) + .ConfigureAwait(false); + + var sampled = 0; + foreach (var agent in agents) + { + var (gpuTemperature, gpuUtilization) = ReadGpuMetrics(agent.GpuInventoryJson, agent.Id); + // The unique (AgentId, CapturedAtUtc) index makes retries and + // duplicate executions safe without dropping a whole batch. + sampled += await db.Database.ExecuteSqlInterpolatedAsync($$""" + INSERT INTO "agent_metric_samples" + ("Id", "AgentId", "SiteId", "CapturedAtUtc", "LogicalCores", "CpuUsagePercent", + "MemoryUsageBytes", "MemTotalBytes", "MemAvailableBytes", "DiskUsagePercent", "GpuTemperatureCelsius", + "GpuUtilizationPercent", "TemperatureJson", "InventoryObservedAtUtc") + VALUES (gen_random_uuid(), {{agent.Id}}, {{agent.SiteId}}, {{capturedAt}}, {{agent.LogicalCores}}, + {{agent.CpuUsagePercent}}, {{agent.MemoryUsageBytes}}, {{agent.MemTotalBytes}}, {{agent.MemAvailableBytes}}, + {{agent.DiskUsagePercent}}, {{gpuTemperature}}, {{gpuUtilization}}, {{agent.TemperatureJson}}, + {{agent.InventoryObservedAtUtc}}) + ON CONFLICT ("AgentId", "CapturedAtUtc") DO NOTHING + """, ct).ConfigureAwait(false); + } var cutoff = now - Retention; var deleted = 0; @@ -76,4 +88,46 @@ public sealed class AgentMetricSampleJob _logger.LogDebug("Agent metric sampling stored {SampleCount} samples and deleted {DeletedCount} expired samples", sampled, deleted); } + + private (double? TemperatureCelsius, double? UtilizationPercent) ReadGpuMetrics(string? json, Guid agentId) + { + if (string.IsNullOrWhiteSpace(json)) return (null, null); + + try + { + using var document = JsonDocument.Parse(json); + if (document.RootElement.ValueKind != JsonValueKind.Array) + { + _logger.LogWarning("Ignoring non-array GPU inventory for agent {AgentId}", agentId); + return (null, null); + } + + var temperatures = new List(); + var utilizations = new List(); + foreach (var device in document.RootElement.EnumerateArray()) + { + if (device.ValueKind != JsonValueKind.Object) continue; + AddMetric(device, "TemperatureCelsius", "temperatureCelsius", temperatures, -273.15, 2000); + AddMetric(device, "UtilizationPercent", "utilizationPercent", utilizations, 0, 100); + } + + return (Average(temperatures), Average(utilizations)); + } + catch (JsonException ex) + { + _logger.LogWarning(ex, "Ignoring malformed GPU inventory for agent {AgentId}", agentId); + return (null, null); + } + } + + private static void AddMetric(JsonElement device, string property, string camelCaseProperty, + ICollection values, double minimum, double maximum) + { + if (!device.TryGetProperty(property, out var value) && !device.TryGetProperty(camelCaseProperty, out value)) return; + if (value.ValueKind == JsonValueKind.Number && value.TryGetDouble(out var number) && + double.IsFinite(number) && number >= minimum && number <= maximum) + values.Add(number); + } + + private static double? Average(IReadOnlyCollection values) => values.Count == 0 ? null : values.Average(); }