From c8c84f0e2cc0a4a8d025da4f7196987456badecf Mon Sep 17 00:00:00 2001 From: Arnaud Dartois Date: Sun, 25 Oct 2026 02:19:01 +0200 Subject: [PATCH 1/6] feat(inventory): add metric history dashboards --- .../Agents/AgentTelemetryMapping.cs | 5 + .../Common/IApplicationDbContext.cs | 1 + .../Inventory/MetricHistoryRange.cs | 30 ++++++ .../GetAgentMetricHistoryHandler.cs | 80 ++++++++++++++ .../GetAgentMetricHistoryQuery.cs | 19 ++++ .../GetSiteCapacityHistoryHandler.cs | 102 ++++++++++++++++++ .../GetSiteCapacityHistoryQuery.cs | 18 ++++ src/Heimdall.Domain/Entities/Agent.cs | 8 ++ .../Entities/AgentMetricSample.cs | 22 ++++ .../BackgroundJobs/DependencyInjection.cs | 1 + .../BackgroundJobs/JobSetup.cs | 5 + .../Data/AppDbContext.cs | 1 + .../AgentMetricSampleConfiguration.cs | 23 ++++ .../Jobs/AgentMetricSampleJob.cs | 79 ++++++++++++++ .../20261025080000_AddAgentMetricSamples.cs | 71 ++++++++++++ .../Migrations/AppDbContextModelSnapshot.cs | 70 ++++++++++++ .../Components/Pages/AgentDetail.razor | 63 +++++++++++ .../Components/Pages/SiteDetail.razor | 97 +++++++++++++++++ .../Shared/MetricHistoryChart.razor | 79 ++++++++++++++ .../Controllers/AgentsController.cs | 13 +++ .../Controllers/SitesController.cs | 13 +++ .../Services/HeimdallApiClient.cs | 37 +++++++ src/Heimdall.Web/Services/MetricChartPoint.cs | 3 + todo.md | 2 +- 24 files changed, 841 insertions(+), 1 deletion(-) create mode 100644 src/Heimdall.Application/Inventory/MetricHistoryRange.cs create mode 100644 src/Heimdall.Application/Inventory/Queries/GetAgentMetricHistory/GetAgentMetricHistoryHandler.cs create mode 100644 src/Heimdall.Application/Inventory/Queries/GetAgentMetricHistory/GetAgentMetricHistoryQuery.cs create mode 100644 src/Heimdall.Application/Inventory/Queries/GetSiteCapacityHistory/GetSiteCapacityHistoryHandler.cs create mode 100644 src/Heimdall.Application/Inventory/Queries/GetSiteCapacityHistory/GetSiteCapacityHistoryQuery.cs create mode 100644 src/Heimdall.Domain/Entities/AgentMetricSample.cs create mode 100644 src/Heimdall.Infrastructure/Data/Configurations/AgentMetricSampleConfiguration.cs create mode 100644 src/Heimdall.Infrastructure/Jobs/AgentMetricSampleJob.cs create mode 100644 src/Heimdall.Infrastructure/Migrations/20261025080000_AddAgentMetricSamples.cs create mode 100644 src/Heimdall.Web/Components/Shared/MetricHistoryChart.razor create mode 100644 src/Heimdall.Web/Services/MetricChartPoint.cs diff --git a/src/Heimdall.Application/Agents/AgentTelemetryMapping.cs b/src/Heimdall.Application/Agents/AgentTelemetryMapping.cs index 07e2a9e..e6160eb 100644 --- a/src/Heimdall.Application/Agents/AgentTelemetryMapping.cs +++ b/src/Heimdall.Application/Agents/AgentTelemetryMapping.cs @@ -32,6 +32,11 @@ public static class AgentTelemetryMapping /// public static void ApplyTo(this AgentTelemetryFields fields, Agent agent) { + if (fields.CpuVendor is not null || fields.CpuModel is not null || + fields.MemTotalBytes.HasValue || fields.DiskInventoryJson is not null || + fields.GpuInventoryJson is not null || fields.TemperatureJson is not null) + agent.MarkInventoryObserved(DateTime.UtcNow); + // Live metrics — always update agent.UpdateLiveMetrics( fields.CpuUsagePercent, diff --git a/src/Heimdall.Application/Common/IApplicationDbContext.cs b/src/Heimdall.Application/Common/IApplicationDbContext.cs index 01f4146..3d585a1 100644 --- a/src/Heimdall.Application/Common/IApplicationDbContext.cs +++ b/src/Heimdall.Application/Common/IApplicationDbContext.cs @@ -6,6 +6,7 @@ namespace Heimdall.Application.Common; public interface IApplicationDbContext { DbSet Agents { get; } + DbSet AgentMetricSamples { get; } DbSet AgentLogEntries { get; } DbSet AgentSettings { get; } DbSet AnalysisJobs { get; } diff --git a/src/Heimdall.Application/Inventory/MetricHistoryRange.cs b/src/Heimdall.Application/Inventory/MetricHistoryRange.cs new file mode 100644 index 0000000..c1f5c91 --- /dev/null +++ b/src/Heimdall.Application/Inventory/MetricHistoryRange.cs @@ -0,0 +1,30 @@ +namespace Heimdall.Application.Inventory; + +internal static class MetricHistoryRange +{ + public static bool TryParse(string? value, DateTime nowUtc, out DateTime fromUtc, out int bucketMinutes) + { + bucketMinutes = value switch + { + "24h" => 5, + "7d" => 30, + _ => 0 + }; + fromUtc = value switch + { + "24h" => nowUtc.AddHours(-24), + "7d" => nowUtc.AddDays(-7), + _ => default + }; + return bucketMinutes != 0; + } + + public static DateTime ToBucketUtc(int year, int month, int day, int hour, int slot, int bucketMinutes) + => new(year, month, day, hour, slot * bucketMinutes, 0, DateTimeKind.Utc); + + public static DateTime FloorToBucketUtc(DateTime valueUtc, int bucketMinutes) + { + var bucketTicks = TimeSpan.FromMinutes(bucketMinutes).Ticks; + return new DateTime(valueUtc.Ticks - valueUtc.Ticks % bucketTicks, DateTimeKind.Utc); + } +} diff --git a/src/Heimdall.Application/Inventory/Queries/GetAgentMetricHistory/GetAgentMetricHistoryHandler.cs b/src/Heimdall.Application/Inventory/Queries/GetAgentMetricHistory/GetAgentMetricHistoryHandler.cs new file mode 100644 index 0000000..5269fed --- /dev/null +++ b/src/Heimdall.Application/Inventory/Queries/GetAgentMetricHistory/GetAgentMetricHistoryHandler.cs @@ -0,0 +1,80 @@ +using Heimdall.Application.Common; +using MediatR; +using Microsoft.EntityFrameworkCore; + +namespace Heimdall.Application.Inventory.Queries.GetAgentMetricHistory; + +public sealed class GetAgentMetricHistoryHandler(IApplicationDbContext db) + : IRequestHandler>> +{ + public async Task>> Handle( + GetAgentMetricHistoryQuery query, CancellationToken ct) + { + var now = DateTime.UtcNow; + if (!MetricHistoryRange.TryParse(query.Range, now, out var fromUtc, out var bucketMinutes)) + return ServiceResult>.Failure("Range must be 24h or 7d."); + + if (!await db.Agents.AnyAsync(agent => agent.Id == query.AgentId, ct).ConfigureAwait(false)) + return ServiceResult>.NotFound("Agent not found."); + + var buckets = await db.AgentMetricSamples.AsNoTracking() + .Where(sample => sample.AgentId == query.AgentId && sample.CapturedAtUtc >= fromUtc && sample.CapturedAtUtc <= now) + .GroupBy(sample => new + { + sample.CapturedAtUtc.Year, + sample.CapturedAtUtc.Month, + sample.CapturedAtUtc.Day, + sample.CapturedAtUtc.Hour, + Slot = sample.CapturedAtUtc.Minute / bucketMinutes + }) + .Select(group => new + { + group.Key.Year, + group.Key.Month, + group.Key.Day, + group.Key.Hour, + group.Key.Slot, + InventoryObservedAtUtc = group.Max(sample => sample.InventoryObservedAtUtc), + LogicalCores = group.Max(sample => sample.LogicalCores), + CpuUsagePercent = group.Average(sample => sample.CpuUsagePercent), + ProcessMemoryBytes = group.Average(sample => (double?)sample.MemoryUsageBytes), + MemoryTotalBytes = group.Max(sample => sample.MemTotalBytes), + MemoryUsedBytes = group.Average(sample => sample.MemTotalBytes.HasValue && sample.MemAvailableBytes.HasValue + ? (double?)(sample.MemTotalBytes.Value - sample.MemAvailableBytes.Value) + : null), + DiskUsagePercent = group.Average(sample => sample.DiskUsagePercent), + GpuTemperatureCelsius = group.Average(sample => sample.GpuTemperatureCelsius), + GpuUtilizationPercent = group.Average(sample => sample.GpuUtilizationPercent) + }) + .OrderBy(bucket => bucket.Year).ThenBy(bucket => bucket.Month).ThenBy(bucket => bucket.Day) + .ThenBy(bucket => bucket.Hour).ThenBy(bucket => bucket.Slot) + .ToListAsync(ct).ConfigureAwait(false); + + var byTimestamp = buckets.ToDictionary( + bucket => MetricHistoryRange.ToBucketUtc(bucket.Year, bucket.Month, bucket.Day, bucket.Hour, bucket.Slot, bucketMinutes), + bucket => new AgentMetricHistoryPoint( + MetricHistoryRange.ToBucketUtc(bucket.Year, bucket.Month, bucket.Day, bucket.Hour, bucket.Slot, bucketMinutes), + bucket.InventoryObservedAtUtc, + bucket.LogicalCores, + bucket.CpuUsagePercent, + ToLong(bucket.ProcessMemoryBytes), + bucket.MemoryTotalBytes, + ToLong(bucket.MemoryUsedBytes), + bucket.DiskUsagePercent, + bucket.GpuTemperatureCelsius, + bucket.GpuUtilizationPercent)); + var firstBucket = MetricHistoryRange.FloorToBucketUtc(fromUtc, bucketMinutes); + var lastBucket = MetricHistoryRange.FloorToBucketUtc(now, bucketMinutes); + var result = new List(); + for (var timestamp = firstBucket; timestamp <= lastBucket; timestamp = timestamp.AddMinutes(bucketMinutes)) + { + result.Add(byTimestamp.TryGetValue(timestamp, out var point) + ? point + : new AgentMetricHistoryPoint(timestamp, null, null, null, null, null, null, null, null, null)); + } + + return ServiceResult>.Success(result); + } + + private static long? ToLong(double? value) => value is null ? null : (long)Math.Round(value.Value); +} diff --git a/src/Heimdall.Application/Inventory/Queries/GetAgentMetricHistory/GetAgentMetricHistoryQuery.cs b/src/Heimdall.Application/Inventory/Queries/GetAgentMetricHistory/GetAgentMetricHistoryQuery.cs new file mode 100644 index 0000000..fa098bd --- /dev/null +++ b/src/Heimdall.Application/Inventory/Queries/GetAgentMetricHistory/GetAgentMetricHistoryQuery.cs @@ -0,0 +1,19 @@ +using Heimdall.Application.Common; +using MediatR; + +namespace Heimdall.Application.Inventory.Queries.GetAgentMetricHistory; + +public sealed record GetAgentMetricHistoryQuery(Guid AgentId, string Range) + : IRequest>>; + +public sealed record AgentMetricHistoryPoint( + DateTime TimestampUtc, + DateTime? InventoryObservedAtUtc, + int? LogicalCores, + double? CpuUsagePercent, + long? ProcessMemoryBytes, + long? MemoryTotalBytes, + long? MemoryUsedBytes, + double? DiskUsagePercent, + double? GpuTemperatureCelsius, + double? GpuUtilizationPercent); diff --git a/src/Heimdall.Application/Inventory/Queries/GetSiteCapacityHistory/GetSiteCapacityHistoryHandler.cs b/src/Heimdall.Application/Inventory/Queries/GetSiteCapacityHistory/GetSiteCapacityHistoryHandler.cs new file mode 100644 index 0000000..33d67c7 --- /dev/null +++ b/src/Heimdall.Application/Inventory/Queries/GetSiteCapacityHistory/GetSiteCapacityHistoryHandler.cs @@ -0,0 +1,102 @@ +using Heimdall.Application.Common; +using MediatR; +using Microsoft.EntityFrameworkCore; + +namespace Heimdall.Application.Inventory.Queries.GetSiteCapacityHistory; + +public sealed class GetSiteCapacityHistoryHandler(IApplicationDbContext db) + : IRequestHandler>> +{ + public async Task>> Handle( + GetSiteCapacityHistoryQuery query, CancellationToken ct) + { + var now = DateTime.UtcNow; + if (!MetricHistoryRange.TryParse(query.Range, now, out var fromUtc, out var bucketMinutes)) + return ServiceResult>.Failure("Range must be 24h or 7d."); + + if (!await db.Sites.AnyAsync(site => site.Id == query.SiteId, ct).ConfigureAwait(false)) + return ServiceResult>.NotFound("Site not found."); + + var perAgentBuckets = db.AgentMetricSamples.AsNoTracking() + .Where(sample => sample.SiteId == query.SiteId && sample.CapturedAtUtc >= fromUtc && sample.CapturedAtUtc <= now) + .GroupBy(sample => new + { + sample.AgentId, + sample.CapturedAtUtc.Year, + sample.CapturedAtUtc.Month, + sample.CapturedAtUtc.Day, + sample.CapturedAtUtc.Hour, + Slot = sample.CapturedAtUtc.Minute / bucketMinutes + }) + .Select(group => new + { + group.Key.Year, + group.Key.Month, + group.Key.Day, + group.Key.Hour, + group.Key.Slot, + InventoryObservedAtUtc = group.Max(sample => sample.InventoryObservedAtUtc), + LogicalCores = group.Max(sample => sample.LogicalCores), + MemoryCapacityBytes = group.Max(sample => sample.MemTotalBytes), + MemoryAvailableBytes = group.Average(sample => (double?)sample.MemAvailableBytes), + AverageCpuUsagePercent = group.Average(sample => sample.CpuUsagePercent), + AverageDiskUsagePercent = group.Average(sample => sample.DiskUsagePercent), + AverageGpuTemperatureCelsius = group.Average(sample => sample.GpuTemperatureCelsius) + }) + .ToListAsync(ct).ConfigureAwait(false); + + var buckets = perAgentBuckets + .GroupBy(agent => new { agent.Year, agent.Month, agent.Day, agent.Hour, agent.Slot }) + .Select(group => new + { + group.Key.Year, + group.Key.Month, + group.Key.Day, + group.Key.Hour, + group.Key.Slot, + InventoryObservedAtUtc = group.Max(agent => agent.InventoryObservedAtUtc), + ReportingAgents = group.Count(), + LogicalCores = group.Any(agent => agent.LogicalCores.HasValue) + ? group.Sum(agent => (int?)agent.LogicalCores) + : null, + MemoryCapacityBytes = group.Any(agent => agent.MemoryCapacityBytes.HasValue) + ? group.Sum(agent => agent.MemoryCapacityBytes) + : null, + MemoryUsedBytes = group.Any(agent => agent.MemoryCapacityBytes.HasValue && agent.MemoryAvailableBytes.HasValue) + ? group.Sum(agent => agent.MemoryCapacityBytes.HasValue && agent.MemoryAvailableBytes.HasValue + ? agent.MemoryCapacityBytes.Value - agent.MemoryAvailableBytes.Value + : (double?)null) + : null, + AverageCpuUsagePercent = group.Average(agent => agent.AverageCpuUsagePercent), + AverageDiskUsagePercent = group.Average(agent => agent.AverageDiskUsagePercent), + AverageGpuTemperatureCelsius = group.Average(agent => agent.AverageGpuTemperatureCelsius) + }) + .OrderBy(bucket => bucket.Year).ThenBy(bucket => bucket.Month).ThenBy(bucket => bucket.Day) + .ThenBy(bucket => bucket.Hour).ThenBy(bucket => bucket.Slot) + .ToArray(); + + var byTimestamp = buckets.ToDictionary( + bucket => MetricHistoryRange.ToBucketUtc(bucket.Year, bucket.Month, bucket.Day, bucket.Hour, bucket.Slot, bucketMinutes), + bucket => new SiteCapacityHistoryPoint( + MetricHistoryRange.ToBucketUtc(bucket.Year, bucket.Month, bucket.Day, bucket.Hour, bucket.Slot, bucketMinutes), + bucket.InventoryObservedAtUtc, + bucket.ReportingAgents, + bucket.LogicalCores, + bucket.MemoryCapacityBytes, + bucket.MemoryUsedBytes is { } memoryUsed ? (long?)Math.Round(memoryUsed) : null, + bucket.AverageCpuUsagePercent, + bucket.AverageDiskUsagePercent, + bucket.AverageGpuTemperatureCelsius)); + var firstBucket = MetricHistoryRange.FloorToBucketUtc(fromUtc, bucketMinutes); + var lastBucket = MetricHistoryRange.FloorToBucketUtc(now, bucketMinutes); + var result = new List(); + for (var timestamp = firstBucket; timestamp <= lastBucket; timestamp = timestamp.AddMinutes(bucketMinutes)) + { + result.Add(byTimestamp.TryGetValue(timestamp, out var point) + ? point + : new SiteCapacityHistoryPoint(timestamp, null, 0, null, null, null, null, null, null)); + } + + return ServiceResult>.Success(result); + } +} diff --git a/src/Heimdall.Application/Inventory/Queries/GetSiteCapacityHistory/GetSiteCapacityHistoryQuery.cs b/src/Heimdall.Application/Inventory/Queries/GetSiteCapacityHistory/GetSiteCapacityHistoryQuery.cs new file mode 100644 index 0000000..1005dd1 --- /dev/null +++ b/src/Heimdall.Application/Inventory/Queries/GetSiteCapacityHistory/GetSiteCapacityHistoryQuery.cs @@ -0,0 +1,18 @@ +using Heimdall.Application.Common; +using MediatR; + +namespace Heimdall.Application.Inventory.Queries.GetSiteCapacityHistory; + +public sealed record GetSiteCapacityHistoryQuery(Guid SiteId, string Range) + : IRequest>>; + +public sealed record SiteCapacityHistoryPoint( + DateTime TimestampUtc, + DateTime? InventoryObservedAtUtc, + int ReportingAgents, + int? LogicalCores, + long? MemoryCapacityBytes, + long? MemoryUsedBytes, + double? AverageCpuUsagePercent, + double? AverageDiskUsagePercent, + double? AverageGpuTemperatureCelsius); diff --git a/src/Heimdall.Domain/Entities/Agent.cs b/src/Heimdall.Domain/Entities/Agent.cs index 88dd0b6..a9cae1e 100644 --- a/src/Heimdall.Domain/Entities/Agent.cs +++ b/src/Heimdall.Domain/Entities/Agent.cs @@ -77,6 +77,7 @@ public class Agent : Entity, IAuditableEntity, ISoftDeletable // ─── Network & Temperature (JSON) ───────────────────────────── public string? NetworkInterfacesJson { get; private set; } public string? TemperatureJson { get; private set; } + public DateTime? InventoryObservedAtUtc { get; private set; } // Audit public DateTime CreatedAt { get; set; } @@ -207,6 +208,13 @@ public class Agent : Entity, IAuditableEntity, ISoftDeletable GpuInventoryJson = gpuInventoryJson; } + public void MarkInventoryObserved(DateTime observedAtUtc) + { + if (observedAtUtc.Kind != DateTimeKind.Utc) + throw new ArgumentException("Inventory observation time must be UTC", nameof(observedAtUtc)); + InventoryObservedAtUtc = observedAtUtc; + } + public void UpdateHostInventory(HostInventoryData data) { OsName = data.OsName; diff --git a/src/Heimdall.Domain/Entities/AgentMetricSample.cs b/src/Heimdall.Domain/Entities/AgentMetricSample.cs new file mode 100644 index 0000000..5e8a1b1 --- /dev/null +++ b/src/Heimdall.Domain/Entities/AgentMetricSample.cs @@ -0,0 +1,22 @@ +namespace Heimdall.Domain.Entities; + +/// A bounded, time-stamped sample of an Agent's live resource metrics. +public sealed class AgentMetricSample +{ + public Guid Id { get; private set; } + public Guid AgentId { get; private set; } + public Guid SiteId { get; private set; } + public DateTime CapturedAtUtc { get; private set; } + public int? LogicalCores { get; private set; } + public double? CpuUsagePercent { get; private set; } + public long? MemoryUsageBytes { get; private set; } + public long? MemTotalBytes { get; private set; } + public long? MemAvailableBytes { get; private set; } + public double? DiskUsagePercent { get; private set; } + public double? GpuTemperatureCelsius { get; private set; } + public double? GpuUtilizationPercent { get; private set; } + public string? TemperatureJson { get; private set; } + public DateTime? InventoryObservedAtUtc { get; private set; } + + private AgentMetricSample() { } +} diff --git a/src/Heimdall.Infrastructure/BackgroundJobs/DependencyInjection.cs b/src/Heimdall.Infrastructure/BackgroundJobs/DependencyInjection.cs index ccbb721..f94b36b 100644 --- a/src/Heimdall.Infrastructure/BackgroundJobs/DependencyInjection.cs +++ b/src/Heimdall.Infrastructure/BackgroundJobs/DependencyInjection.cs @@ -42,6 +42,7 @@ public static class DependencyInjection services.AddScoped(); services.AddScoped(); services.AddScoped(); + services.AddScoped(); services.AddScoped(); services.AddScoped(); services.AddScoped(); diff --git a/src/Heimdall.Infrastructure/BackgroundJobs/JobSetup.cs b/src/Heimdall.Infrastructure/BackgroundJobs/JobSetup.cs index aae1f8e..3344bb7 100644 --- a/src/Heimdall.Infrastructure/BackgroundJobs/JobSetup.cs +++ b/src/Heimdall.Infrastructure/BackgroundJobs/JobSetup.cs @@ -32,6 +32,11 @@ public static class JobSetup job => job.ExecuteAsync(CancellationToken.None), "0 4 * * *"); // Daily at 4:00 — purge logs > retention (7 j par défaut) + manager.AddOrUpdate( + "agent-metric-sample", + job => job.ExecuteAsync(CancellationToken.None), + "*/5 * * * *"); // Every 5 minutes; samples are retained for 8 days. + manager.AddOrUpdate( "storage-staging-cleanup", job => job.ExecuteAsync(CancellationToken.None), diff --git a/src/Heimdall.Infrastructure/Data/AppDbContext.cs b/src/Heimdall.Infrastructure/Data/AppDbContext.cs index 78f4c02..9fcd36b 100644 --- a/src/Heimdall.Infrastructure/Data/AppDbContext.cs +++ b/src/Heimdall.Infrastructure/Data/AppDbContext.cs @@ -26,6 +26,7 @@ public class AppDbContext : IdentityDbContext, IApplicat public DbSet Sites => Set(); public DbSet SiteCredentials => Set(); public DbSet Agents => Set(); + public DbSet AgentMetricSamples => Set(); public DbSet AgentLogEntries => Set(); public DbSet Cameras => Set(); public DbSet CameraCredentials => Set(); diff --git a/src/Heimdall.Infrastructure/Data/Configurations/AgentMetricSampleConfiguration.cs b/src/Heimdall.Infrastructure/Data/Configurations/AgentMetricSampleConfiguration.cs new file mode 100644 index 0000000..a32281c --- /dev/null +++ b/src/Heimdall.Infrastructure/Data/Configurations/AgentMetricSampleConfiguration.cs @@ -0,0 +1,23 @@ +using Heimdall.Domain.Entities; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Metadata.Builders; + +namespace Heimdall.Infrastructure.Data.Configurations; + +public sealed class AgentMetricSampleConfiguration : IEntityTypeConfiguration +{ + public void Configure(EntityTypeBuilder builder) + { + builder.ToTable("agent_metric_samples"); + builder.HasKey(sample => sample.Id); + builder.Property(sample => sample.Id).HasDefaultValueSql("gen_random_uuid()"); + builder.Property(sample => sample.CapturedAtUtc).IsRequired(); + builder.Property(sample => sample.TemperatureJson).HasColumnType("text"); + + builder.HasIndex(sample => new { sample.AgentId, sample.CapturedAtUtc }).IsUnique(); + builder.HasIndex(sample => new { sample.SiteId, sample.CapturedAtUtc }); + builder.HasIndex(sample => sample.CapturedAtUtc); + builder.HasOne().WithMany().HasForeignKey(sample => sample.AgentId) + .OnDelete(DeleteBehavior.Cascade); + } +} diff --git a/src/Heimdall.Infrastructure/Jobs/AgentMetricSampleJob.cs b/src/Heimdall.Infrastructure/Jobs/AgentMetricSampleJob.cs new file mode 100644 index 0000000..ab67621 --- /dev/null +++ b/src/Heimdall.Infrastructure/Jobs/AgentMetricSampleJob.cs @@ -0,0 +1,79 @@ +using Heimdall.Domain.Entities; +using Heimdall.Infrastructure.Data; +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.Logging; + +namespace Heimdall.Infrastructure.Jobs; + +/// +/// Records one idempotent five-minute sample for Agents with a recent heartbeat, +/// then removes samples outside the eight-day chart window in bounded batches. +/// +public sealed class AgentMetricSampleJob +{ + private static readonly TimeSpan SampleInterval = TimeSpan.FromMinutes(5); + private static readonly TimeSpan Retention = TimeSpan.FromDays(8); + private readonly IDbContextFactory _dbFactory; + private readonly ILogger _logger; + + public AgentMetricSampleJob(IDbContextFactory dbFactory, ILogger logger) + { + _dbFactory = dbFactory; + _logger = logger; + } + + public async Task ExecuteAsync(CancellationToken ct) + { + await using var db = await _dbFactory.CreateDbContextAsync(ct).ConfigureAwait(false); + var now = DateTime.UtcNow; + 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); + + var cutoff = now - Retention; + var deleted = 0; + while (true) + { + var batchIds = await db.AgentMetricSamples + .Where(sample => sample.CapturedAtUtc < cutoff) + .OrderBy(sample => sample.CapturedAtUtc) + .Take(5000) + .Select(sample => sample.Id) + .ToListAsync(ct) + .ConfigureAwait(false); + if (batchIds.Count == 0) break; + + deleted += await db.AgentMetricSamples + .Where(sample => batchIds.Contains(sample.Id)) + .ExecuteDeleteAsync(ct) + .ConfigureAwait(false); + await Task.Delay(100, ct).ConfigureAwait(false); + } + + _logger.LogDebug("Agent metric sampling stored {SampleCount} samples and deleted {DeletedCount} expired samples", + sampled, deleted); + } +} diff --git a/src/Heimdall.Infrastructure/Migrations/20261025080000_AddAgentMetricSamples.cs b/src/Heimdall.Infrastructure/Migrations/20261025080000_AddAgentMetricSamples.cs new file mode 100644 index 0000000..0ca69b5 --- /dev/null +++ b/src/Heimdall.Infrastructure/Migrations/20261025080000_AddAgentMetricSamples.cs @@ -0,0 +1,71 @@ +using Heimdall.Infrastructure.Data; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Migrations; + +namespace Heimdall.Infrastructure.Migrations; + +[DbContext(typeof(AppDbContext))] +[Migration("20261025080000_AddAgentMetricSamples")] +public sealed class AddAgentMetricSamples : Migration +{ + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.AddColumn( + name: "InventoryObservedAtUtc", + table: "agents", + type: "timestamp with time zone", + nullable: true); + + migrationBuilder.CreateTable( + name: "agent_metric_samples", + columns: table => new + { + Id = table.Column(type: "uuid", nullable: false, defaultValueSql: "gen_random_uuid()"), + AgentId = table.Column(type: "uuid", nullable: false), + SiteId = table.Column(type: "uuid", nullable: false), + CapturedAtUtc = table.Column(type: "timestamp with time zone", nullable: false), + LogicalCores = table.Column(type: "integer", nullable: true), + CpuUsagePercent = table.Column(type: "double precision", nullable: true), + MemoryUsageBytes = table.Column(type: "bigint", nullable: true), + MemTotalBytes = table.Column(type: "bigint", nullable: true), + MemAvailableBytes = table.Column(type: "bigint", nullable: true), + DiskUsagePercent = table.Column(type: "double precision", nullable: true), + GpuTemperatureCelsius = table.Column(type: "double precision", nullable: true), + GpuUtilizationPercent = table.Column(type: "double precision", nullable: true), + TemperatureJson = table.Column(type: "text", nullable: true), + InventoryObservedAtUtc = table.Column(type: "timestamp with time zone", nullable: true) + }, + constraints: table => + { + table.PrimaryKey("PK_agent_metric_samples", x => x.Id); + table.ForeignKey( + name: "FK_agent_metric_samples_agents_AgentId", + column: x => x.AgentId, + principalTable: "agents", + principalColumn: "Id", + onDelete: ReferentialAction.Cascade); + }); + + migrationBuilder.CreateIndex( + name: "IX_agent_metric_samples_AgentId_CapturedAtUtc", + table: "agent_metric_samples", + columns: new[] { "AgentId", "CapturedAtUtc" }, + unique: true); + + migrationBuilder.CreateIndex( + name: "IX_agent_metric_samples_CapturedAtUtc", + table: "agent_metric_samples", + column: "CapturedAtUtc"); + + migrationBuilder.CreateIndex( + name: "IX_agent_metric_samples_SiteId_CapturedAtUtc", + table: "agent_metric_samples", + columns: new[] { "SiteId", "CapturedAtUtc" }); + } + + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropTable(name: "agent_metric_samples"); + migrationBuilder.DropColumn(name: "InventoryObservedAtUtc", table: "agents"); + } +} diff --git a/src/Heimdall.Infrastructure/Migrations/AppDbContextModelSnapshot.cs b/src/Heimdall.Infrastructure/Migrations/AppDbContextModelSnapshot.cs index 29f1a0d..e3381d3 100644 --- a/src/Heimdall.Infrastructure/Migrations/AppDbContextModelSnapshot.cs +++ b/src/Heimdall.Infrastructure/Migrations/AppDbContextModelSnapshot.cs @@ -187,6 +187,9 @@ namespace Heimdall.Infrastructure.Migrations b.Property("TemperatureJson") .HasColumnType("text"); + b.Property("InventoryObservedAtUtc") + .HasColumnType("timestamp with time zone"); + b.Property("ThreadsPerCore") .HasColumnType("integer"); @@ -262,6 +265,64 @@ namespace Heimdall.Infrastructure.Migrations b.ToTable("agent_log_entries", (string)null); }); + modelBuilder.Entity("Heimdall.Domain.Entities.AgentMetricSample", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid") + .HasDefaultValueSql("gen_random_uuid()"); + + b.Property("AgentId") + .HasColumnType("uuid"); + + b.Property("CapturedAtUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("CpuUsagePercent") + .HasColumnType("double precision"); + + b.Property("DiskUsagePercent") + .HasColumnType("double precision"); + + b.Property("GpuTemperatureCelsius") + .HasColumnType("double precision"); + + b.Property("GpuUtilizationPercent") + .HasColumnType("double precision"); + + b.Property("LogicalCores") + .HasColumnType("integer"); + + b.Property("MemTotalBytes") + .HasColumnType("bigint"); + + b.Property("MemAvailableBytes") + .HasColumnType("bigint"); + + b.Property("MemoryUsageBytes") + .HasColumnType("bigint"); + + b.Property("SiteId") + .HasColumnType("uuid"); + + b.Property("TemperatureJson") + .HasColumnType("text"); + + b.Property("InventoryObservedAtUtc") + .HasColumnType("timestamp with time zone"); + + b.HasKey("Id"); + + b.HasIndex("AgentId", "CapturedAtUtc") + .IsUnique(); + + b.HasIndex("CapturedAtUtc"); + + b.HasIndex("SiteId", "CapturedAtUtc"); + + b.ToTable("agent_metric_samples", (string)null); + }); + modelBuilder.Entity("Heimdall.Domain.Entities.AgentSetting", b => { b.Property("Id") @@ -2401,6 +2462,15 @@ namespace Heimdall.Infrastructure.Migrations b.Navigation("Agent"); }); + modelBuilder.Entity("Heimdall.Domain.Entities.AgentMetricSample", b => + { + b.HasOne("Heimdall.Domain.Entities.Agent", null) + .WithMany() + .HasForeignKey("AgentId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + modelBuilder.Entity("Heimdall.Domain.Entities.AgentSetting", b => { b.HasOne("Heimdall.Domain.Entities.Agent", "Agent") diff --git a/src/Heimdall.Web/Components/Pages/AgentDetail.razor b/src/Heimdall.Web/Components/Pages/AgentDetail.razor index 7a804ce..8d48518 100644 --- a/src/Heimdall.Web/Components/Pages/AgentDetail.razor +++ b/src/Heimdall.Web/Components/Pages/AgentDetail.razor @@ -585,6 +585,39 @@ else } + +
+ Historique des ressources + + 24 h + 7 jours + +
+ @if (_metricHistoryLoading) + { + + } + else if (_metricHistoryError) + { + Impossible de charger l’historique des ressources. + } + else + { + @if (_metricHistory.LastOrDefault(point => point.InventoryObservedAtUtc.HasValue) is { } inventoryPoint) + { + + Dernier inventaire GPU/température reçu : @inventoryPoint.InventoryObservedAtUtc!.Value.ToLocalTime().ToString("g"). + + } + + + + + + + } +
+ @* ─── Agent Logs ─── *@ _metricHistory = []; + private bool _metricHistoryLoading; + private bool _metricHistoryError; + private string _metricRange = "24h"; // Updates private LatestReleaseInfo? _updateInfo; @@ -856,6 +893,7 @@ else _agent = await Api.GetAgentAsync(Id); if (_agent is not null) { + await LoadMetricHistoryAsync(_metricRange); await LoadSettingsAsync(); await LoadLogsAsync(keepPage: false); _ = LoadUpdateInfoAsync(); @@ -865,6 +903,31 @@ else finally { _loading = false; } } + private async Task LoadMetricHistoryAsync(string range) + { + _metricRange = range; + _metricHistoryLoading = true; + _metricHistoryError = false; + try + { + _metricHistory = await Api.GetAgentMetricHistoryAsync(Id, range) ?? []; + } + catch + { + _metricHistoryError = true; + _metricHistory = []; + } + finally { _metricHistoryLoading = false; } + } + + private List MetricSeries(Func selector) + => _metricHistory.Select(point => new MetricChartPoint(point.TimestampUtc, selector(point))).ToList(); + + private static double? MemoryUsedPercent(AgentMetricHistoryPoint point) + => point.MemoryUsedBytes is { } used && point.MemoryTotalBytes is > 0 + ? Math.Clamp(100d * used / point.MemoryTotalBytes.Value, 0, 100) + : null; + private async Task LoadSettingsAsync() { _settingsError = false; diff --git a/src/Heimdall.Web/Components/Pages/SiteDetail.razor b/src/Heimdall.Web/Components/Pages/SiteDetail.razor index a1863e7..d824e3b 100644 --- a/src/Heimdall.Web/Components/Pages/SiteDetail.razor +++ b/src/Heimdall.Web/Components/Pages/SiteDetail.razor @@ -45,6 +45,56 @@ else + +
+ Capacité et ressources du site + + 24 h + 7 jours + +
+ @if (_capacityHistoryLoading) + { + + } + else if (_capacityHistoryError) + { + Impossible de charger l’historique de capacité. + } + else if (_capacityHistory.Count == 0 || !_capacityHistory.Any(point => point.ReportingAgents > 0)) + { + Les données historiques apparaîtront après le premier échantillon d’agent. + } + else + { + var latestCapacity = _capacityHistory.LastOrDefault(point => point.ReportingAgents > 0); + @if (latestCapacity is not null) + { + @if (latestCapacity.InventoryObservedAtUtc.HasValue) + { + + Dernier inventaire GPU/température reçu : @latestCapacity.InventoryObservedAtUtc.Value.ToLocalTime().ToString("g"). + + } + + Agents échantillonnés@latestCapacity.ReportingAgents + Cœurs logiques@(latestCapacity.LogicalCores?.ToString() ?? "—") + RAM totale@FormatCapacity(latestCapacity.MemoryCapacityBytes) + RAM utilisée@FormatCapacity(latestCapacity.MemoryUsedBytes) + + } + + + + + + + + Les trous représentent des périodes sans échantillon en ligne; ils ne comptent pas comme une utilisation nulle. + + } +
+ @* Token d'enregistrement *@ @@ -196,6 +246,10 @@ else private SiteItem? _site; private bool _loading = true; + private List _capacityHistory = []; + private bool _capacityHistoryLoading; + private bool _capacityHistoryError; + private string _capacityRange = "24h"; private bool _generating; private string? _generatedToken; private DateTime _tokenExpiresAt; @@ -216,6 +270,8 @@ else try { _site = await Api.GetSiteAsync(Id); + if (_site is not null) + await LoadCapacityHistoryAsync(_capacityRange); } catch { Snackbar.Add(UiErrors.OperationFailed(), Severity.Error); } finally { _loading = false; } @@ -223,6 +279,47 @@ else await LoadCredentials(); } + private async Task LoadCapacityHistoryAsync(string range) + { + _capacityRange = range; + _capacityHistoryLoading = true; + _capacityHistoryError = false; + try + { + _capacityHistory = await Api.GetSiteCapacityHistoryAsync(Id, range) ?? []; + } + catch + { + _capacityHistoryError = true; + _capacityHistory = []; + } + finally { _capacityHistoryLoading = false; } + } + + private List CapacitySeries(Func selector) + => _capacityHistory.Select(point => new MetricChartPoint(point.TimestampUtc, selector(point))).ToList(); + + private static double? MemoryCapacityUsedPercent(SiteCapacityHistoryPoint point) + => point.MemoryUsedBytes is { } used && point.MemoryCapacityBytes is > 0 + ? Math.Clamp(100d * used / point.MemoryCapacityBytes.Value, 0, 100) + : null; + + private static string FormatCapacity(long? bytes) + => bytes is { } value ? FormatBytes(value) : "—"; + + private static string FormatBytes(long bytes) + { + string[] units = ["B", "KB", "MB", "GB", "TB"]; + var size = (double)bytes; + var unit = 0; + while (size >= 1024 && unit < units.Length - 1) + { + size /= 1024; + unit++; + } + return $"{size:0.#} {units[unit]}"; + } + private async Task LoadCredentials() { _credentialsLoading = true; diff --git a/src/Heimdall.Web/Components/Shared/MetricHistoryChart.razor b/src/Heimdall.Web/Components/Shared/MetricHistoryChart.razor new file mode 100644 index 0000000..c081182 --- /dev/null +++ b/src/Heimdall.Web/Components/Shared/MetricHistoryChart.razor @@ -0,0 +1,79 @@ + + @Title + @if (Points.Count == 0 || !Points.Any(point => point.Value.HasValue)) + { + Aucune donnée sur cette période. + } + else + { + + + + @FormatValue(UpperBound) + @FormatValue(LowerBound) + @foreach (var segment in GetSegments()) + { + + } + +
+ @Points[0].TimestampUtc.ToLocalTime().ToString("g") + @Points[^1].TimestampUtc.ToLocalTime().ToString("g") +
+ } +
+ +@code { + [Parameter, EditorRequired] public string Title { get; set; } = ""; + [Parameter, EditorRequired] public IReadOnlyList Points { get; set; } = []; + [Parameter] public string Unit { get; set; } = "%"; + [Parameter] public double? Minimum { get; set; } + [Parameter] public double? Maximum { get; set; } + + private double LowerBound + { + get + { + if (Minimum.HasValue) return Minimum.Value; + var values = Points.Where(point => point.Value.HasValue).Select(point => point.Value!.Value).ToArray(); + return values.Length == 0 ? 0 : Math.Floor(values.Min()); + } + } + + private double UpperBound + { + get + { + if (Maximum.HasValue) return Maximum.Value; + var values = Points.Where(point => point.Value.HasValue).Select(point => point.Value!.Value).ToArray(); + if (values.Length == 0) return 1; + var max = Math.Ceiling(values.Max()); + return max <= LowerBound ? LowerBound + 1 : max; + } + } + + private IEnumerable GetSegments() + { + const double left = 40; + const double right = 710; + const double top = 14; + const double bottom = 130; + var span = Math.Max(UpperBound - LowerBound, double.Epsilon); + var segment = new List(); + for (var index = 0; index < Points.Count; index++) + { + if (Points[index].Value is not { } value) + { + if (segment.Count > 0) { yield return string.Join(" ", segment); segment.Clear(); } + continue; + } + + var x = Points.Count <= 1 ? left : left + (right - left) * index / (Points.Count - 1); + var y = bottom - (bottom - top) * (value - LowerBound) / span; + segment.Add($"{x.ToString("0.##", System.Globalization.CultureInfo.InvariantCulture)},{y.ToString("0.##", System.Globalization.CultureInfo.InvariantCulture)}"); + } + if (segment.Count > 0) yield return string.Join(" ", segment); + } + + private string FormatValue(double value) => $"{value:0.##}{Unit}"; +} diff --git a/src/Heimdall.Web/Controllers/AgentsController.cs b/src/Heimdall.Web/Controllers/AgentsController.cs index aaec7f6..7e734c2 100644 --- a/src/Heimdall.Web/Controllers/AgentsController.cs +++ b/src/Heimdall.Web/Controllers/AgentsController.cs @@ -7,6 +7,7 @@ using Heimdall.Application.Agents.Queries.GetAgentsBySite; using Heimdall.Application.Agents.Queries.GetAllAgents; using Heimdall.Application.AgentLogs.Commands.SubmitAgentLogs; using Heimdall.Application.AgentLogs.Queries.GetAgentLogs; +using Heimdall.Application.Inventory.Queries.GetAgentMetricHistory; using Heimdall.Application.Cameras.Commands.ReportCameraStatus; using Heimdall.Application.DTOs; using Heimdall.Domain.Enums; @@ -218,6 +219,18 @@ public class AgentsController : ControllerBase return Ok(result.Data); } + /// Get bounded historical metrics for an Agent. + [Authorize(AuthenticationSchemes = "JwtBearer,Cookies", Policy = AppPermissions.SiteRead)] + [HttpGet("{id:guid}/metrics/history")] + [ProducesResponseType(typeof(IReadOnlyList), StatusCodes.Status200OK)] + public async Task GetMetricHistory(Guid id, [FromQuery] string range = "24h", CancellationToken ct = default) + { + var result = await _mediator.Send(new GetAgentMetricHistoryQuery(id, range), ct); + if (!result.IsSuccess) + return StatusCode(result.StatusCode ?? 400, new { error = result.Error }); + return Ok(result.Data); + } + /// List all agents across all sites. [Authorize(AuthenticationSchemes = "JwtBearer,Cookies", Policy = AppPermissions.SiteRead)] [HttpGet] diff --git a/src/Heimdall.Web/Controllers/SitesController.cs b/src/Heimdall.Web/Controllers/SitesController.cs index 39f317b..6a6413b 100644 --- a/src/Heimdall.Web/Controllers/SitesController.cs +++ b/src/Heimdall.Web/Controllers/SitesController.cs @@ -14,6 +14,7 @@ using Heimdall.Application.Sites.Queries.GetSite; using Heimdall.Application.Sites.Queries.GetSiteCascadeInfo; using Heimdall.Application.Sites.Queries.GetSitesByUser; using Heimdall.Application.Inventory.Queries.GetInventoryStats; +using Heimdall.Application.Inventory.Queries.GetSiteCapacityHistory; using Heimdall.Infrastructure.Security; using MediatR; using Microsoft.AspNetCore.Authorization; @@ -146,6 +147,18 @@ public class SitesController : ControllerBase return Ok(result.Data); } + /// Get bounded historical resource capacity for a site. + [Authorize(AuthenticationSchemes = "JwtBearer,Cookies", Policy = AppPermissions.SiteRead)] + [HttpGet("{id:guid}/capacity/history")] + [ProducesResponseType(typeof(IReadOnlyList), StatusCodes.Status200OK)] + public async Task GetCapacityHistory(Guid id, [FromQuery] string range = "24h", CancellationToken ct = default) + { + var result = await _mediator.Send(new GetSiteCapacityHistoryQuery(id, range), ct); + if (!result.IsSuccess) + return StatusCode(result.StatusCode ?? 400, new { error = result.Error }); + return Ok(result.Data); + } + /// Delete a site (Admin only). [Authorize(AuthenticationSchemes = "JwtBearer,Cookies", Policy = AppPermissions.SiteDelete)] [HttpDelete("{id:guid}")] diff --git a/src/Heimdall.Web/Services/HeimdallApiClient.cs b/src/Heimdall.Web/Services/HeimdallApiClient.cs index 7a5e7d9..3039d0e 100644 --- a/src/Heimdall.Web/Services/HeimdallApiClient.cs +++ b/src/Heimdall.Web/Services/HeimdallApiClient.cs @@ -385,6 +385,13 @@ public class HeimdallApiClient : IDisposable return await client.GetFromJsonAsync($"api/sites/{id}", Json); } + public async Task?> GetSiteCapacityHistoryAsync(Guid id, string range) + { + var client = CreateClient(); + return await client.GetFromJsonAsync>( + $"api/sites/{id}/capacity/history?range={Uri.EscapeDataString(range)}", Json); + } + public async Task> CreateSiteAsync(string name, string? address, string? timezone, string? ntfyTopic = null) { var client = CreateClient(); @@ -622,6 +629,13 @@ public class HeimdallApiClient : IDisposable return await client.GetFromJsonAsync($"api/agents/{id}", Json); } + public async Task?> GetAgentMetricHistoryAsync(Guid id, string range) + { + var client = CreateClient(); + return await client.GetFromJsonAsync>( + $"api/agents/{id}/metrics/history?range={Uri.EscapeDataString(range)}", Json); + } + public async Task?> GetAgentsBySiteAsync(Guid siteId, int page = 1, int pageSize = 20) { var client = CreateClient(); @@ -1039,6 +1053,29 @@ public record StatsEnvelope(StatsResult Data, DateTime Timestamp); public record AgentStatItem(string StatType, string Label, int Value, string Color); +public record AgentMetricHistoryPoint( + [property: JsonPropertyName("timestampUtc")] DateTime TimestampUtc, + [property: JsonPropertyName("inventoryObservedAtUtc")] DateTime? InventoryObservedAtUtc, + [property: JsonPropertyName("logicalCores")] int? LogicalCores, + [property: JsonPropertyName("cpuUsagePercent")] double? CpuUsagePercent, + [property: JsonPropertyName("processMemoryBytes")] long? ProcessMemoryBytes, + [property: JsonPropertyName("memoryTotalBytes")] long? MemoryTotalBytes, + [property: JsonPropertyName("memoryUsedBytes")] long? MemoryUsedBytes, + [property: JsonPropertyName("diskUsagePercent")] double? DiskUsagePercent, + [property: JsonPropertyName("gpuTemperatureCelsius")] double? GpuTemperatureCelsius, + [property: JsonPropertyName("gpuUtilizationPercent")] double? GpuUtilizationPercent); + +public record SiteCapacityHistoryPoint( + [property: JsonPropertyName("timestampUtc")] DateTime TimestampUtc, + [property: JsonPropertyName("inventoryObservedAtUtc")] DateTime? InventoryObservedAtUtc, + [property: JsonPropertyName("reportingAgents")] int ReportingAgents, + [property: JsonPropertyName("logicalCores")] int? LogicalCores, + [property: JsonPropertyName("memoryCapacityBytes")] long? MemoryCapacityBytes, + [property: JsonPropertyName("memoryUsedBytes")] long? MemoryUsedBytes, + [property: JsonPropertyName("averageCpuUsagePercent")] double? AverageCpuUsagePercent, + [property: JsonPropertyName("averageDiskUsagePercent")] double? AverageDiskUsagePercent, + [property: JsonPropertyName("averageGpuTemperatureCelsius")] double? AverageGpuTemperatureCelsius); + public class AuditLogItem { public Guid Id { get; set; } diff --git a/src/Heimdall.Web/Services/MetricChartPoint.cs b/src/Heimdall.Web/Services/MetricChartPoint.cs new file mode 100644 index 0000000..47d8d3d --- /dev/null +++ b/src/Heimdall.Web/Services/MetricChartPoint.cs @@ -0,0 +1,3 @@ +namespace Heimdall.Web.Services; + +public sealed record MetricChartPoint(DateTime TimestampUtc, double? Value); diff --git a/todo.md b/todo.md index 4203034..2d6e36d 100644 --- a/todo.md +++ b/todo.md @@ -39,7 +39,7 @@ Ce fichier remplace les rapports de `docs/audits/` et constitue le suivi courant - [ ] **FEAT-02** Implémenter enregistrement continu/événement, segments et index temporel, upload repris, replay/range/export autorisés, quotas et purge complète. - [ ] **FEAT-03 / UI-02** Évaluer modèles/licences visage et plaques, persister `PersonId`/`VehicleId` et lier les événements ; vérifier historique paginé sans confusion d'identité, conservation et suppression des données biométriques. - [ ] **GPU #77** Les Compose CPU n'exigent plus NVIDIA et n'annoncent plus un `ORT_PROVIDER=CUDA` ignoré. Des overlays optionnels exposent NVIDIA/AMD/Intel à l'inventaire; l'inférence ONNX de l'image Agent reste CPU. Restent une image/runtime GPU, la détection du fournisseur réellement attaché à la session, et les validations GPU réel + fallback CPU. -- [ ] **Inventaire #86** Historiser CPU/RAM/disque/température GPU, fournir courbes 24 h/7 j et capacité par site, avec index et purge bornée. +- [ ] **Inventaire #86** En cours : échantillons Central idempotents toutes les 5 min, horodatage séparé de réception des inventaires, agrégats API bornés (5 min/30 min) avec trous conservés, historique agent et capacité par site, graphiques 24 h/7 j, index et purge en lots à 8 jours. La migration et la CI restent à valider; les températures GPU ne sont présentes que si l’agent remonte un inventaire GPU. - [ ] **mDNS #81** La PR #78 fait de l'Agent la source unique des probes HomeKit sur le LAN caméra ; Central persiste et restitue catégorie, appairage et port, et la fusion conserve l'annonce mDNS même si le scan TCP a vu l'IP d'abord. Le client partagé assemble PTR/SRV/TXT/A, décode `ci` et `sf`, et filtre les catégories 17/18. La CI #246 a passé build, tests et scans d'images ; reste une validation sur LAN avec caméra/sonnette réelles. - [ ] **UI groupes #138 / accès #134** Finaliser maquette et validation produit, puis vérifier l'union accès direct/groupe et les priorités dans l'interface. - [ ] **Localisation #142** Extraire tous les textes UI, erreurs, notifications et emails ; persister FR/EN par utilisateur, basculer sans rechargement, garder français par défaut et vérifier les clés des deux ressources. -- 2.54.1 From 5edaba16ca353961d2943eccc75415d6a143219b Mon Sep 17 00:00:00 2001 From: Arnaud Dartois Date: Sun, 25 Oct 2026 02:23:31 +0200 Subject: [PATCH 2/6] fix(inventory): await site metric buckets --- .../GetSiteCapacityHistory/GetSiteCapacityHistoryHandler.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Heimdall.Application/Inventory/Queries/GetSiteCapacityHistory/GetSiteCapacityHistoryHandler.cs b/src/Heimdall.Application/Inventory/Queries/GetSiteCapacityHistory/GetSiteCapacityHistoryHandler.cs index 33d67c7..ba01132 100644 --- a/src/Heimdall.Application/Inventory/Queries/GetSiteCapacityHistory/GetSiteCapacityHistoryHandler.cs +++ b/src/Heimdall.Application/Inventory/Queries/GetSiteCapacityHistory/GetSiteCapacityHistoryHandler.cs @@ -17,7 +17,7 @@ public sealed class GetSiteCapacityHistoryHandler(IApplicationDbContext db) if (!await db.Sites.AnyAsync(site => site.Id == query.SiteId, ct).ConfigureAwait(false)) return ServiceResult>.NotFound("Site not found."); - var perAgentBuckets = db.AgentMetricSamples.AsNoTracking() + var perAgentBuckets = await db.AgentMetricSamples.AsNoTracking() .Where(sample => sample.SiteId == query.SiteId && sample.CapturedAtUtc >= fromUtc && sample.CapturedAtUtc <= now) .GroupBy(sample => new { -- 2.54.1 From e86c0e159a27ee550f2beb95927415a15ecc169d Mon Sep 17 00:00:00 2001 From: Arnaud Dartois Date: Sun, 25 Oct 2026 02:51:19 +0200 Subject: [PATCH 3/6] fix(inventory): isolate invalid GPU inventory samples --- .../Jobs/AgentMetricSampleJob.cs | 100 ++++++++++++++---- 1 file changed, 77 insertions(+), 23 deletions(-) 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(); } -- 2.54.1 From 6abde35475e2947a7c499df58b2695b322b4cb36 Mon Sep 17 00:00:00 2001 From: Arnaud Dartois Date: Sun, 25 Oct 2026 02:59:38 +0200 Subject: [PATCH 4/6] perf(inventory): batch metric sample inserts --- .../Jobs/AgentMetricSampleJob.cs | 46 ++++++++++++++++--- 1 file changed, 39 insertions(+), 7 deletions(-) diff --git a/src/Heimdall.Infrastructure/Jobs/AgentMetricSampleJob.cs b/src/Heimdall.Infrastructure/Jobs/AgentMetricSampleJob.cs index 612b7bd..445a80c 100644 --- a/src/Heimdall.Infrastructure/Jobs/AgentMetricSampleJob.cs +++ b/src/Heimdall.Infrastructure/Jobs/AgentMetricSampleJob.cs @@ -46,21 +46,38 @@ public sealed class AgentMetricSampleJob .ToListAsync(ct) .ConfigureAwait(false); - var sampled = 0; + var samples = new List(agents.Count); 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. + samples.Add(new MetricSamplePayload( + agent.Id, agent.SiteId, capturedAt, agent.LogicalCores, agent.CpuUsagePercent, + agent.MemoryUsageBytes, agent.MemTotalBytes, agent.MemAvailableBytes, agent.DiskUsagePercent, + gpuTemperature, gpuUtilization, agent.TemperatureJson, agent.InventoryObservedAtUtc)); + } + + // The unique (AgentId, CapturedAtUtc) index makes retries and duplicate + // executions safe. Only typed, server-serialized values reach PostgreSQL. + const int batchSize = 500; + var sampled = 0; + for (var offset = 0; offset < samples.Count; offset += batchSize) + { + var payload = JsonSerializer.Serialize(samples.Skip(offset).Take(batchSize)); 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}}) + SELECT gen_random_uuid(), sample."AgentId", sample."SiteId", sample."CapturedAtUtc", sample."LogicalCores", + sample."CpuUsagePercent", sample."MemoryUsageBytes", sample."MemTotalBytes", sample."MemAvailableBytes", + sample."DiskUsagePercent", sample."GpuTemperatureCelsius", sample."GpuUtilizationPercent", + sample."TemperatureJson", sample."InventoryObservedAtUtc" + FROM jsonb_to_recordset({{payload}}::jsonb) AS sample( + "AgentId" uuid, "SiteId" uuid, "CapturedAtUtc" timestamp with time zone, + "LogicalCores" integer, "CpuUsagePercent" double precision, "MemoryUsageBytes" bigint, + "MemTotalBytes" bigint, "MemAvailableBytes" bigint, "DiskUsagePercent" double precision, + "GpuTemperatureCelsius" double precision, "GpuUtilizationPercent" double precision, + "TemperatureJson" text, "InventoryObservedAtUtc" timestamp with time zone) ON CONFLICT ("AgentId", "CapturedAtUtc") DO NOTHING """, ct).ConfigureAwait(false); } @@ -130,4 +147,19 @@ public sealed class AgentMetricSampleJob } private static double? Average(IReadOnlyCollection values) => values.Count == 0 ? null : values.Average(); + + private sealed record MetricSamplePayload( + Guid AgentId, + Guid SiteId, + DateTime CapturedAtUtc, + int? LogicalCores, + double? CpuUsagePercent, + long? MemoryUsageBytes, + long? MemTotalBytes, + long? MemAvailableBytes, + double? DiskUsagePercent, + double? GpuTemperatureCelsius, + double? GpuUtilizationPercent, + string? TemperatureJson, + DateTime? InventoryObservedAtUtc); } -- 2.54.1 From d3aa74496bb3bff79bd9fdea533f2dfd6f18ad24 Mon Sep 17 00:00:00 2001 From: Arnaud Dartois Date: Sun, 25 Oct 2026 02:11:28 +0100 Subject: [PATCH 5/6] fix(inventory): satisfy metric parser analyzers --- src/Heimdall.Infrastructure/Jobs/AgentMetricSampleJob.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/Heimdall.Infrastructure/Jobs/AgentMetricSampleJob.cs b/src/Heimdall.Infrastructure/Jobs/AgentMetricSampleJob.cs index 445a80c..95c5415 100644 --- a/src/Heimdall.Infrastructure/Jobs/AgentMetricSampleJob.cs +++ b/src/Heimdall.Infrastructure/Jobs/AgentMetricSampleJob.cs @@ -138,7 +138,7 @@ public sealed class AgentMetricSampleJob } private static void AddMetric(JsonElement device, string property, string camelCaseProperty, - ICollection values, double minimum, double maximum) + List 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) && @@ -146,7 +146,7 @@ public sealed class AgentMetricSampleJob values.Add(number); } - private static double? Average(IReadOnlyCollection values) => values.Count == 0 ? null : values.Average(); + private static double? Average(List values) => values.Count == 0 ? null : values.Average(); private sealed record MetricSamplePayload( Guid AgentId, -- 2.54.1 From d890e0c0d555182109843a5885fc33f2a5b1e0f1 Mon Sep 17 00:00:00 2001 From: Arnaud Dartois Date: Sun, 25 Oct 2026 03:10:39 +0100 Subject: [PATCH 6/6] docs(inventory): record metric history validation --- todo.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/todo.md b/todo.md index 2d6e36d..696f711 100644 --- a/todo.md +++ b/todo.md @@ -39,7 +39,7 @@ Ce fichier remplace les rapports de `docs/audits/` et constitue le suivi courant - [ ] **FEAT-02** Implémenter enregistrement continu/événement, segments et index temporel, upload repris, replay/range/export autorisés, quotas et purge complète. - [ ] **FEAT-03 / UI-02** Évaluer modèles/licences visage et plaques, persister `PersonId`/`VehicleId` et lier les événements ; vérifier historique paginé sans confusion d'identité, conservation et suppression des données biométriques. - [ ] **GPU #77** Les Compose CPU n'exigent plus NVIDIA et n'annoncent plus un `ORT_PROVIDER=CUDA` ignoré. Des overlays optionnels exposent NVIDIA/AMD/Intel à l'inventaire; l'inférence ONNX de l'image Agent reste CPU. Restent une image/runtime GPU, la détection du fournisseur réellement attaché à la session, et les validations GPU réel + fallback CPU. -- [ ] **Inventaire #86** En cours : échantillons Central idempotents toutes les 5 min, horodatage séparé de réception des inventaires, agrégats API bornés (5 min/30 min) avec trous conservés, historique agent et capacité par site, graphiques 24 h/7 j, index et purge en lots à 8 jours. La migration et la CI restent à valider; les températures GPU ne sont présentes que si l’agent remonte un inventaire GPU. +- [x] **Inventaire #86** La PR #84 livre les échantillons Central idempotents toutes les 5 min, l’horodatage distinct de réception, les agrégats API bornés (5 min/30 min) avec trous conservés, l’historique agent, la capacité par site, les graphiques 24 h/7 j, l’index et la purge en lots à 8 jours. La migration, les tests et scans d’images ont passé dans le run PR #273. Les températures GPU sont disponibles lorsque l’Agent remonte un inventaire GPU. - [ ] **mDNS #81** La PR #78 fait de l'Agent la source unique des probes HomeKit sur le LAN caméra ; Central persiste et restitue catégorie, appairage et port, et la fusion conserve l'annonce mDNS même si le scan TCP a vu l'IP d'abord. Le client partagé assemble PTR/SRV/TXT/A, décode `ci` et `sf`, et filtre les catégories 17/18. La CI #246 a passé build, tests et scans d'images ; reste une validation sur LAN avec caméra/sonnette réelles. - [ ] **UI groupes #138 / accès #134** Finaliser maquette et validation produit, puis vérifier l'union accès direct/groupe et les priorités dans l'interface. - [ ] **Localisation #142** Extraire tous les textes UI, erreurs, notifications et emails ; persister FR/EN par utilisateur, basculer sans rechargement, garder français par défaut et vérifier les clés des deux ressources. -- 2.54.1