feat(inventory): add metric history dashboards
Heimdall Gitea / Build and tests (pull_request) Failing after 3m28s
Heimdall Gitea / Build and scan server image (pull_request) Skipped
Heimdall Gitea / Build and scan agent image (pull_request) Skipped
Heimdall Gitea / Publish Docker Hub latest tags (pull_request) Skipped
Heimdall Gitea / Publish versioned release (pull_request) Skipped
Heimdall Gitea / Build and tests (pull_request) Failing after 3m28s
Heimdall Gitea / Build and scan server image (pull_request) Skipped
Heimdall Gitea / Build and scan agent image (pull_request) Skipped
Heimdall Gitea / Publish Docker Hub latest tags (pull_request) Skipped
Heimdall Gitea / Publish versioned release (pull_request) Skipped
This commit is contained in:
1 parent
9cf995383f
commit
c8c84f0e2c
24 files changed
+841
-1
No files matched your search
@@ -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,79 @@
|
||||
using Heimdall.Domain.Entities;
|
||||
using Heimdall.Infrastructure.Data;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.Extensions.Logging;
|
||||
|
||||
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);
|
||||
|
||||
// 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);
|
||||
}
|
||||
}
|
||||
@@ -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")
|
||||
|
||||
Reference in new issue
Block a user