Merge pull request 'feat(inventory): add metric history dashboards' (#84) from feat/inventory-metric-history into main
Heimdall Gitea / Build and scan server image (push) Canceled after 0s
Heimdall Gitea / Build and scan agent image (push) Canceled after 0s
Heimdall Gitea / Publish Docker Hub latest tags (push) Canceled after 0s
Heimdall Gitea / Publish versioned release (push) Canceled after 0s
Heimdall Gitea / Build and tests (push) Canceled after 4m53s
Heimdall Gitea / Build and scan server image (push) Canceled after 0s
Heimdall Gitea / Build and scan agent image (push) Canceled after 0s
Heimdall Gitea / Publish Docker Hub latest tags (push) Canceled after 0s
Heimdall Gitea / Publish versioned release (push) Canceled after 0s
Heimdall Gitea / Build and tests (push) Canceled after 4m53s
feat(inventory): add metric history dashboards
This commit was merged in pull request #84.
This commit is contained in:
commit
e91706e05b
24 files changed
+927
-1
No files matched your search
@@ -32,6 +32,11 @@ public static class AgentTelemetryMapping
|
||||
/// </summary>
|
||||
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,
|
||||
|
||||
@@ -6,6 +6,7 @@ namespace Heimdall.Application.Common;
|
||||
public interface IApplicationDbContext
|
||||
{
|
||||
DbSet<Agent> Agents { get; }
|
||||
DbSet<AgentMetricSample> AgentMetricSamples { get; }
|
||||
DbSet<AgentLogEntry> AgentLogEntries { get; }
|
||||
DbSet<AgentSetting> AgentSettings { get; }
|
||||
DbSet<AnalysisJob> AnalysisJobs { get; }
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
+80
@@ -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<GetAgentMetricHistoryQuery, ServiceResult<IReadOnlyList<AgentMetricHistoryPoint>>>
|
||||
{
|
||||
public async Task<ServiceResult<IReadOnlyList<AgentMetricHistoryPoint>>> Handle(
|
||||
GetAgentMetricHistoryQuery query, CancellationToken ct)
|
||||
{
|
||||
var now = DateTime.UtcNow;
|
||||
if (!MetricHistoryRange.TryParse(query.Range, now, out var fromUtc, out var bucketMinutes))
|
||||
return ServiceResult<IReadOnlyList<AgentMetricHistoryPoint>>.Failure("Range must be 24h or 7d.");
|
||||
|
||||
if (!await db.Agents.AnyAsync(agent => agent.Id == query.AgentId, ct).ConfigureAwait(false))
|
||||
return ServiceResult<IReadOnlyList<AgentMetricHistoryPoint>>.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<AgentMetricHistoryPoint>();
|
||||
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<IReadOnlyList<AgentMetricHistoryPoint>>.Success(result);
|
||||
}
|
||||
|
||||
private static long? ToLong(double? value) => value is null ? null : (long)Math.Round(value.Value);
|
||||
}
|
||||
+19
@@ -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<ServiceResult<IReadOnlyList<AgentMetricHistoryPoint>>>;
|
||||
|
||||
public sealed record AgentMetricHistoryPoint(
|
||||
DateTime TimestampUtc,
|
||||
DateTime? InventoryObservedAtUtc,
|
||||
int? LogicalCores,
|
||||
double? CpuUsagePercent,
|
||||
long? ProcessMemoryBytes,
|
||||
long? MemoryTotalBytes,
|
||||
long? MemoryUsedBytes,
|
||||
double? DiskUsagePercent,
|
||||
double? GpuTemperatureCelsius,
|
||||
double? GpuUtilizationPercent);
|
||||
+102
@@ -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<GetSiteCapacityHistoryQuery, ServiceResult<IReadOnlyList<SiteCapacityHistoryPoint>>>
|
||||
{
|
||||
public async Task<ServiceResult<IReadOnlyList<SiteCapacityHistoryPoint>>> Handle(
|
||||
GetSiteCapacityHistoryQuery query, CancellationToken ct)
|
||||
{
|
||||
var now = DateTime.UtcNow;
|
||||
if (!MetricHistoryRange.TryParse(query.Range, now, out var fromUtc, out var bucketMinutes))
|
||||
return ServiceResult<IReadOnlyList<SiteCapacityHistoryPoint>>.Failure("Range must be 24h or 7d.");
|
||||
|
||||
if (!await db.Sites.AnyAsync(site => site.Id == query.SiteId, ct).ConfigureAwait(false))
|
||||
return ServiceResult<IReadOnlyList<SiteCapacityHistoryPoint>>.NotFound("Site not found.");
|
||||
|
||||
var perAgentBuckets = await 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<SiteCapacityHistoryPoint>();
|
||||
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<IReadOnlyList<SiteCapacityHistoryPoint>>.Success(result);
|
||||
}
|
||||
}
|
||||
+18
@@ -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<ServiceResult<IReadOnlyList<SiteCapacityHistoryPoint>>>;
|
||||
|
||||
public sealed record SiteCapacityHistoryPoint(
|
||||
DateTime TimestampUtc,
|
||||
DateTime? InventoryObservedAtUtc,
|
||||
int ReportingAgents,
|
||||
int? LogicalCores,
|
||||
long? MemoryCapacityBytes,
|
||||
long? MemoryUsedBytes,
|
||||
double? AverageCpuUsagePercent,
|
||||
double? AverageDiskUsagePercent,
|
||||
double? AverageGpuTemperatureCelsius);
|
||||
@@ -77,6 +77,7 @@ public class Agent : Entity<Guid>, 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<Guid>, 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;
|
||||
|
||||
@@ -0,0 +1,22 @@
|
||||
namespace Heimdall.Domain.Entities;
|
||||
|
||||
/// <summary>A bounded, time-stamped sample of an Agent's live resource metrics.</summary>
|
||||
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() { }
|
||||
}
|
||||
@@ -42,6 +42,7 @@ public static class DependencyInjection
|
||||
services.AddScoped<DailyDigestJob>();
|
||||
services.AddScoped<WeeklyDigestJob>();
|
||||
services.AddScoped<AgentLogCleanupJob>();
|
||||
services.AddScoped<AgentMetricSampleJob>();
|
||||
services.AddScoped<RetentionCheckJob>();
|
||||
services.AddScoped<CleanupUnknownFacesJob>();
|
||||
services.AddScoped<CleanupLicensePlatesJob>();
|
||||
|
||||
@@ -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<AgentMetricSampleJob>(
|
||||
"agent-metric-sample",
|
||||
job => job.ExecuteAsync(CancellationToken.None),
|
||||
"*/5 * * * *"); // Every 5 minutes; samples are retained for 8 days.
|
||||
|
||||
manager.AddOrUpdate<StorageStagingCleanupJob>(
|
||||
"storage-staging-cleanup",
|
||||
job => job.ExecuteAsync(CancellationToken.None),
|
||||
|
||||
@@ -26,6 +26,7 @@ public class AppDbContext : IdentityDbContext<AppUser, AppRole, Guid>, IApplicat
|
||||
public DbSet<Site> Sites => Set<Site>();
|
||||
public DbSet<SiteCredential> SiteCredentials => Set<SiteCredential>();
|
||||
public DbSet<Agent> Agents => Set<Agent>();
|
||||
public DbSet<AgentMetricSample> AgentMetricSamples => Set<AgentMetricSample>();
|
||||
public DbSet<AgentLogEntry> AgentLogEntries => Set<AgentLogEntry>();
|
||||
public DbSet<Camera> Cameras => Set<Camera>();
|
||||
public DbSet<CameraCredentials> CameraCredentials => Set<CameraCredentials>();
|
||||
|
||||
@@ -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<AgentMetricSample>
|
||||
{
|
||||
public void Configure(EntityTypeBuilder<AgentMetricSample> 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<Agent>().WithMany().HasForeignKey(sample => sample.AgentId)
|
||||
.OnDelete(DeleteBehavior.Cascade);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,165 @@
|
||||
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;
|
||||
|
||||
/// <summary>
|
||||
/// Records one idempotent five-minute sample for Agents with a recent heartbeat,
|
||||
/// then removes samples outside the eight-day chart window in bounded batches.
|
||||
/// </summary>
|
||||
public sealed class AgentMetricSampleJob
|
||||
{
|
||||
private static readonly TimeSpan SampleInterval = TimeSpan.FromMinutes(5);
|
||||
private static readonly TimeSpan Retention = TimeSpan.FromDays(8);
|
||||
private readonly IDbContextFactory<AppDbContext> _dbFactory;
|
||||
private readonly ILogger<AgentMetricSampleJob> _logger;
|
||||
|
||||
public AgentMetricSampleJob(IDbContextFactory<AppDbContext> dbFactory, ILogger<AgentMetricSampleJob> 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);
|
||||
|
||||
// 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 samples = new List<MetricSamplePayload>(agents.Count);
|
||||
foreach (var agent in agents)
|
||||
{
|
||||
var (gpuTemperature, gpuUtilization) = ReadGpuMetrics(agent.GpuInventoryJson, agent.Id);
|
||||
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")
|
||||
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);
|
||||
}
|
||||
|
||||
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);
|
||||
}
|
||||
|
||||
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<double>();
|
||||
var utilizations = new List<double>();
|
||||
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,
|
||||
List<double> 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(List<double> 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);
|
||||
}
|
||||
@@ -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<DateTime>(
|
||||
name: "InventoryObservedAtUtc",
|
||||
table: "agents",
|
||||
type: "timestamp with time zone",
|
||||
nullable: true);
|
||||
|
||||
migrationBuilder.CreateTable(
|
||||
name: "agent_metric_samples",
|
||||
columns: table => new
|
||||
{
|
||||
Id = table.Column<Guid>(type: "uuid", nullable: false, defaultValueSql: "gen_random_uuid()"),
|
||||
AgentId = table.Column<Guid>(type: "uuid", nullable: false),
|
||||
SiteId = table.Column<Guid>(type: "uuid", nullable: false),
|
||||
CapturedAtUtc = table.Column<DateTime>(type: "timestamp with time zone", nullable: false),
|
||||
LogicalCores = table.Column<int>(type: "integer", nullable: true),
|
||||
CpuUsagePercent = table.Column<double>(type: "double precision", nullable: true),
|
||||
MemoryUsageBytes = table.Column<long>(type: "bigint", nullable: true),
|
||||
MemTotalBytes = table.Column<long>(type: "bigint", nullable: true),
|
||||
MemAvailableBytes = table.Column<long>(type: "bigint", nullable: true),
|
||||
DiskUsagePercent = table.Column<double>(type: "double precision", nullable: true),
|
||||
GpuTemperatureCelsius = table.Column<double>(type: "double precision", nullable: true),
|
||||
GpuUtilizationPercent = table.Column<double>(type: "double precision", nullable: true),
|
||||
TemperatureJson = table.Column<string>(type: "text", nullable: true),
|
||||
InventoryObservedAtUtc = table.Column<DateTime>(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");
|
||||
}
|
||||
}
|
||||
@@ -187,6 +187,9 @@ namespace Heimdall.Infrastructure.Migrations
|
||||
b.Property<string>("TemperatureJson")
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<DateTime?>("InventoryObservedAtUtc")
|
||||
.HasColumnType("timestamp with time zone");
|
||||
|
||||
b.Property<int?>("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<Guid>("Id")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("uuid")
|
||||
.HasDefaultValueSql("gen_random_uuid()");
|
||||
|
||||
b.Property<Guid>("AgentId")
|
||||
.HasColumnType("uuid");
|
||||
|
||||
b.Property<DateTime>("CapturedAtUtc")
|
||||
.HasColumnType("timestamp with time zone");
|
||||
|
||||
b.Property<double?>("CpuUsagePercent")
|
||||
.HasColumnType("double precision");
|
||||
|
||||
b.Property<double?>("DiskUsagePercent")
|
||||
.HasColumnType("double precision");
|
||||
|
||||
b.Property<double?>("GpuTemperatureCelsius")
|
||||
.HasColumnType("double precision");
|
||||
|
||||
b.Property<double?>("GpuUtilizationPercent")
|
||||
.HasColumnType("double precision");
|
||||
|
||||
b.Property<int?>("LogicalCores")
|
||||
.HasColumnType("integer");
|
||||
|
||||
b.Property<long?>("MemTotalBytes")
|
||||
.HasColumnType("bigint");
|
||||
|
||||
b.Property<long?>("MemAvailableBytes")
|
||||
.HasColumnType("bigint");
|
||||
|
||||
b.Property<long?>("MemoryUsageBytes")
|
||||
.HasColumnType("bigint");
|
||||
|
||||
b.Property<Guid>("SiteId")
|
||||
.HasColumnType("uuid");
|
||||
|
||||
b.Property<string>("TemperatureJson")
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<DateTime?>("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<Guid>("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")
|
||||
|
||||
@@ -585,6 +585,39 @@ else
|
||||
}
|
||||
</SectionCard>
|
||||
|
||||
<MudPaper Elevation="2" Class="pa-6 mb-6" Style="border-radius: 12px;">
|
||||
<div class="d-flex flex-wrap justify-space-between align-center mb-4">
|
||||
<MudText Typo="Typo.h6">Historique des ressources</MudText>
|
||||
<MudButtonGroup Variant="Variant.Outlined" Color="Color.Primary">
|
||||
<MudButton OnClick="@(() => LoadMetricHistoryAsync("24h"))" Disabled="@(_metricHistoryLoading || _metricRange == "24h")">24 h</MudButton>
|
||||
<MudButton OnClick="@(() => LoadMetricHistoryAsync("7d"))" Disabled="@(_metricHistoryLoading || _metricRange == "7d")">7 jours</MudButton>
|
||||
</MudButtonGroup>
|
||||
</div>
|
||||
@if (_metricHistoryLoading)
|
||||
{
|
||||
<MudProgressLinear Indeterminate="true" />
|
||||
}
|
||||
else if (_metricHistoryError)
|
||||
{
|
||||
<MudAlert Severity="Severity.Error">Impossible de charger l’historique des ressources.</MudAlert>
|
||||
}
|
||||
else
|
||||
{
|
||||
@if (_metricHistory.LastOrDefault(point => point.InventoryObservedAtUtc.HasValue) is { } inventoryPoint)
|
||||
{
|
||||
<MudText Typo="Typo.caption" Color="Color.Secondary" Class="mb-3">
|
||||
Dernier inventaire GPU/température reçu : @inventoryPoint.InventoryObservedAtUtc!.Value.ToLocalTime().ToString("g").
|
||||
</MudText>
|
||||
}
|
||||
<MudGrid>
|
||||
<MudItem xs="12" md="6"><MetricHistoryChart Title="CPU utilisé" Points="@MetricSeries(point => point.CpuUsagePercent)" Minimum="0" Maximum="100" /></MudItem>
|
||||
<MudItem xs="12" md="6"><MetricHistoryChart Title="Mémoire système utilisée" Points="@MetricSeries(MemoryUsedPercent)" Minimum="0" Maximum="100" /></MudItem>
|
||||
<MudItem xs="12" md="6"><MetricHistoryChart Title="Disque utilisé" Points="@MetricSeries(point => point.DiskUsagePercent)" Minimum="0" Maximum="100" /></MudItem>
|
||||
<MudItem xs="12" md="6"><MetricHistoryChart Title="Température GPU moyenne" Points="@MetricSeries(point => point.GpuTemperatureCelsius)" Unit=" °C" /></MudItem>
|
||||
</MudGrid>
|
||||
}
|
||||
</MudPaper>
|
||||
|
||||
@* ─── Agent Logs ─── *@
|
||||
<SectionCard Title="Logs"
|
||||
Icon="@Icons.Material.Filled.ReceiptLong"
|
||||
@@ -808,6 +841,10 @@ else
|
||||
|
||||
private AgentItem? _agent;
|
||||
private bool _loading = true;
|
||||
private List<AgentMetricHistoryPoint> _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<MetricChartPoint> MetricSeries(Func<AgentMetricHistoryPoint, double?> 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;
|
||||
|
||||
@@ -45,6 +45,56 @@ else
|
||||
</MudGrid>
|
||||
</MudPaper>
|
||||
|
||||
<MudPaper Elevation="2" Class="pa-6 mb-6" Style="border-radius: 12px;">
|
||||
<div class="d-flex flex-wrap justify-space-between align-center mb-4">
|
||||
<MudText Typo="Typo.h6">Capacité et ressources du site</MudText>
|
||||
<MudButtonGroup Variant="Variant.Outlined" Color="Color.Primary">
|
||||
<MudButton OnClick="@(() => LoadCapacityHistoryAsync("24h"))" Disabled="@(_capacityHistoryLoading || _capacityRange == "24h")">24 h</MudButton>
|
||||
<MudButton OnClick="@(() => LoadCapacityHistoryAsync("7d"))" Disabled="@(_capacityHistoryLoading || _capacityRange == "7d")">7 jours</MudButton>
|
||||
</MudButtonGroup>
|
||||
</div>
|
||||
@if (_capacityHistoryLoading)
|
||||
{
|
||||
<MudProgressLinear Indeterminate="true" />
|
||||
}
|
||||
else if (_capacityHistoryError)
|
||||
{
|
||||
<MudAlert Severity="Severity.Error">Impossible de charger l’historique de capacité.</MudAlert>
|
||||
}
|
||||
else if (_capacityHistory.Count == 0 || !_capacityHistory.Any(point => point.ReportingAgents > 0))
|
||||
{
|
||||
<MudAlert Severity="Severity.Info" Variant="Variant.Outlined">Les données historiques apparaîtront après le premier échantillon d’agent.</MudAlert>
|
||||
}
|
||||
else
|
||||
{
|
||||
var latestCapacity = _capacityHistory.LastOrDefault(point => point.ReportingAgents > 0);
|
||||
@if (latestCapacity is not null)
|
||||
{
|
||||
@if (latestCapacity.InventoryObservedAtUtc.HasValue)
|
||||
{
|
||||
<MudText Typo="Typo.caption" Color="Color.Secondary" Class="mb-2">
|
||||
Dernier inventaire GPU/température reçu : @latestCapacity.InventoryObservedAtUtc.Value.ToLocalTime().ToString("g").
|
||||
</MudText>
|
||||
}
|
||||
<MudGrid Class="mb-3">
|
||||
<MudItem xs="6" sm="3"><MudText Typo="Typo.caption" Color="Color.Secondary">Agents échantillonnés</MudText><MudText Typo="Typo.h6">@latestCapacity.ReportingAgents</MudText></MudItem>
|
||||
<MudItem xs="6" sm="3"><MudText Typo="Typo.caption" Color="Color.Secondary">Cœurs logiques</MudText><MudText Typo="Typo.h6">@(latestCapacity.LogicalCores?.ToString() ?? "—")</MudText></MudItem>
|
||||
<MudItem xs="6" sm="3"><MudText Typo="Typo.caption" Color="Color.Secondary">RAM totale</MudText><MudText Typo="Typo.h6">@FormatCapacity(latestCapacity.MemoryCapacityBytes)</MudText></MudItem>
|
||||
<MudItem xs="6" sm="3"><MudText Typo="Typo.caption" Color="Color.Secondary">RAM utilisée</MudText><MudText Typo="Typo.h6">@FormatCapacity(latestCapacity.MemoryUsedBytes)</MudText></MudItem>
|
||||
</MudGrid>
|
||||
}
|
||||
<MudGrid>
|
||||
<MudItem xs="12" md="6"><MetricHistoryChart Title="CPU moyen utilisé" Points="@CapacitySeries(point => point.AverageCpuUsagePercent)" Minimum="0" Maximum="100" /></MudItem>
|
||||
<MudItem xs="12" md="6"><MetricHistoryChart Title="Mémoire système utilisée" Points="@CapacitySeries(MemoryCapacityUsedPercent)" Minimum="0" Maximum="100" /></MudItem>
|
||||
<MudItem xs="12" md="6"><MetricHistoryChart Title="Disque moyen utilisé" Points="@CapacitySeries(point => point.AverageDiskUsagePercent)" Minimum="0" Maximum="100" /></MudItem>
|
||||
<MudItem xs="12" md="6"><MetricHistoryChart Title="Température GPU moyenne" Points="@CapacitySeries(point => point.AverageGpuTemperatureCelsius)" Unit=" °C" /></MudItem>
|
||||
</MudGrid>
|
||||
<MudText Typo="Typo.caption" Color="Color.Secondary" Class="mt-2">
|
||||
Les trous représentent des périodes sans échantillon en ligne; ils ne comptent pas comme une utilisation nulle.
|
||||
</MudText>
|
||||
}
|
||||
</MudPaper>
|
||||
|
||||
@* Token d'enregistrement *@
|
||||
<MudPaper Elevation="2" Class="pa-6 mb-6" Style="border-radius: 12px;">
|
||||
<MudText Typo="Typo.h6" Class="mb-4">
|
||||
@@ -196,6 +246,10 @@ else
|
||||
|
||||
private SiteItem? _site;
|
||||
private bool _loading = true;
|
||||
private List<SiteCapacityHistoryPoint> _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<MetricChartPoint> CapacitySeries(Func<SiteCapacityHistoryPoint, double?> 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;
|
||||
|
||||
@@ -0,0 +1,79 @@
|
||||
<MudPaper Elevation="0" Class="pa-3" Style="border: 1px solid var(--mud-palette-lines-default); border-radius: 8px; height: 100%;">
|
||||
<MudText Typo="Typo.subtitle2">@Title</MudText>
|
||||
@if (Points.Count == 0 || !Points.Any(point => point.Value.HasValue))
|
||||
{
|
||||
<MudText Typo="Typo.caption" Color="Color.Secondary" Class="mt-4">Aucune donnée sur cette période.</MudText>
|
||||
}
|
||||
else
|
||||
{
|
||||
<svg viewBox="0 0 720 160" role="img" aria-label="@Title" style="width:100%;height:150px;overflow:visible;">
|
||||
<line x1="40" y1="14" x2="710" y2="14" stroke="var(--mud-palette-lines-default)" />
|
||||
<line x1="40" y1="130" x2="710" y2="130" stroke="var(--mud-palette-lines-default)" />
|
||||
<text x="2" y="18" fill="var(--mud-palette-text-secondary)" font-size="11">@FormatValue(UpperBound)</text>
|
||||
<text x="2" y="134" fill="var(--mud-palette-text-secondary)" font-size="11">@FormatValue(LowerBound)</text>
|
||||
@foreach (var segment in GetSegments())
|
||||
{
|
||||
<polyline points="@segment" fill="none" stroke="var(--mud-palette-primary)" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round" />
|
||||
}
|
||||
</svg>
|
||||
<div class="d-flex justify-space-between">
|
||||
<MudText Typo="Typo.caption" Color="Color.Secondary">@Points[0].TimestampUtc.ToLocalTime().ToString("g")</MudText>
|
||||
<MudText Typo="Typo.caption" Color="Color.Secondary">@Points[^1].TimestampUtc.ToLocalTime().ToString("g")</MudText>
|
||||
</div>
|
||||
}
|
||||
</MudPaper>
|
||||
|
||||
@code {
|
||||
[Parameter, EditorRequired] public string Title { get; set; } = "";
|
||||
[Parameter, EditorRequired] public IReadOnlyList<MetricChartPoint> 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<string> 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<string>();
|
||||
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}";
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
|
||||
/// <summary>Get bounded historical metrics for an Agent.</summary>
|
||||
[Authorize(AuthenticationSchemes = "JwtBearer,Cookies", Policy = AppPermissions.SiteRead)]
|
||||
[HttpGet("{id:guid}/metrics/history")]
|
||||
[ProducesResponseType(typeof(IReadOnlyList<AgentMetricHistoryPoint>), StatusCodes.Status200OK)]
|
||||
public async Task<IActionResult> 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);
|
||||
}
|
||||
|
||||
/// <summary>List all agents across all sites.</summary>
|
||||
[Authorize(AuthenticationSchemes = "JwtBearer,Cookies", Policy = AppPermissions.SiteRead)]
|
||||
[HttpGet]
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
|
||||
/// <summary>Get bounded historical resource capacity for a site.</summary>
|
||||
[Authorize(AuthenticationSchemes = "JwtBearer,Cookies", Policy = AppPermissions.SiteRead)]
|
||||
[HttpGet("{id:guid}/capacity/history")]
|
||||
[ProducesResponseType(typeof(IReadOnlyList<SiteCapacityHistoryPoint>), StatusCodes.Status200OK)]
|
||||
public async Task<IActionResult> 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);
|
||||
}
|
||||
|
||||
/// <summary>Delete a site (Admin only).</summary>
|
||||
[Authorize(AuthenticationSchemes = "JwtBearer,Cookies", Policy = AppPermissions.SiteDelete)]
|
||||
[HttpDelete("{id:guid}")]
|
||||
|
||||
@@ -385,6 +385,13 @@ public class HeimdallApiClient : IDisposable
|
||||
return await client.GetFromJsonAsync<SiteItem>($"api/sites/{id}", Json);
|
||||
}
|
||||
|
||||
public async Task<List<SiteCapacityHistoryPoint>?> GetSiteCapacityHistoryAsync(Guid id, string range)
|
||||
{
|
||||
var client = CreateClient();
|
||||
return await client.GetFromJsonAsync<List<SiteCapacityHistoryPoint>>(
|
||||
$"api/sites/{id}/capacity/history?range={Uri.EscapeDataString(range)}", Json);
|
||||
}
|
||||
|
||||
public async Task<ApiResult<SiteWithTokenResult>> 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<AgentItem>($"api/agents/{id}", Json);
|
||||
}
|
||||
|
||||
public async Task<List<AgentMetricHistoryPoint>?> GetAgentMetricHistoryAsync(Guid id, string range)
|
||||
{
|
||||
var client = CreateClient();
|
||||
return await client.GetFromJsonAsync<List<AgentMetricHistoryPoint>>(
|
||||
$"api/agents/{id}/metrics/history?range={Uri.EscapeDataString(range)}", Json);
|
||||
}
|
||||
|
||||
public async Task<PagedData<AgentItem>?> 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; }
|
||||
|
||||
@@ -0,0 +1,3 @@
|
||||
namespace Heimdall.Web.Services;
|
||||
|
||||
public sealed record MetricChartPoint(DateTime TimestampUtc, double? Value);
|
||||
@@ -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.
|
||||
- [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.
|
||||
|
||||
Reference in new issue
Block a user