feat(agent): télémétrie inventaire matériel — CPU/mémoire/disque/GPU/OS/réseau (Fixes #82 #83 #84 #85) (#137)

## Contexte

Implémentation des tickets #82, #83, #84, #85 — télémétrie inventaire matériel agent. L'objectif est de fournir au central un maximum d'informations sur les machines des agents (CPU, mémoire, disques, GPU, OS, réseau, conteneur) sans SSH.

## Changements

### Nouveaux collecteurs (src/Heimdall.Agent/Services/)
- **CpuInfoProvider** : parse `/proc/cpuinfo` (vendor, modèle, cœurs physiques/logiques, fréquence, flags AVX/AVX2/FMA/AVX512, cache), topologie, détection cgroup CPU (`/sys/fs/cgroup/cpu.max` v2)
- **DiskInventoryProvider** : énumère les montages (`/proc/mounts`), capacité/libre/type SSD/HDD via `/sys/block/*/queue/rotation`
- **GpuInventoryProvider** : nvidia-smi, sysfs DRM, vainfo, rocm-smi avec fallback silencieux, multi-GPU
- **HostInfoProvider** : os-release, uname, `/proc/uptime` (uptime machine ≠ process), températures sysfs
- **ContainerInfoProvider** : détection Docker (/.dockerenv, cgroup), ID conteneur, limites CPU/mémoire

### Refonte SystemMetricsProvider
- Séparation host vs process (RAM machine ≠ RAM conteneur ≠ WorkingSet64)
- Uptime machine (`/proc/uptime`) distinct de l'uptime process
- Mémoire swap

### Entité Agent + Migration
- Champs structurés CPU/mémoire/disque/GPU/OS/réseau (tous nullable, rétrocompatible)
- Migration EF `AddAgentTelemetryInventory`

### Transport heartbeat
- Inventaire au register + refresh périodique (5 min, pas à chaque tick)
- Champs JSON pour listes (disques, GPU, interfaces réseau, températures)

### UI Admin (AgentDetail.razor)
- Sections CPU, Mémoire/Disques, GPU, Machine/Conteneur avec barres de progression et badges

### Tests
- 40+ tests unitaires : providers, handlers, entité Agent
- Total : 999 tests verts (Domain 149, Application 397, Agent 210, Web 243)

## Tickets liés
- Fixes #82 — CPU inventory
- Fixes #83 — Mémoire & disque
- Fixes #84 — GPU inventory
- Fixes #85 — OS, conteneur, réseau

## Résultats des tests
- `dotnet build` : 0 erreur, 0 warning
- Domain.Tests : 149 passed
- Application.Tests : 397 passed
- Agent.Tests : 210 passed
- Web.Tests : 243 passed
- Total : 999 tests ✅

## Checklist
- [x] `dotnet build` vert (TreatWarningsAsErrors)
- [x] Tests unitaires verts
- [x] Migration EF créée
- [x] Champs nullable (rétrocompatible)
- [x] Pas de référence Infrastructure dans les contrôleurs
- [x] Collecteurs avec fallback silencieux (pas de crash sans GPU/Docker/sysfs)

Reviewed-on: https://forgejo.tordais.cc/nonobis/Heimdall/pulls/137
This commit is contained in:
Arnaud Dartois authored and Arnaud Dartois committed 2026-08-20 14:13:06 +02:00
1 parent f7e6b0cec3
commit 4792b69e46
63 files changed
+8711 -563

No files matched your search

@@ -36,9 +36,7 @@ public class DatabaseMaintenanceJob
// REINDEX de la base (CONCURRENTLY impossible dans une transaction
// EF — exécution directe sur la connexion). On reindexe la table
// events et ses index (coût borné).
var reindexSql = isFirstSunday
? "REINDEX TABLE camera_events;"
: "REINDEX TABLE camera_events;";
const string reindexSql = "REINDEX TABLE camera_events;";
await db.Database.ExecuteSqlRawAsync(reindexSql, ct).ConfigureAwait(false);
_logger.LogInformation("Database maintenance: {Reindex}", reindexSql.Trim());
}
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,268 @@
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace Heimdall.Infrastructure.Migrations
{
/// <inheritdoc />
public partial class AddAgentTelemetryInventory : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.AddColumn<string>(
name: "Arch",
table: "agents",
type: "text",
nullable: true);
migrationBuilder.AddColumn<long>(
name: "ContainerCpuLimit",
table: "agents",
type: "bigint",
nullable: true);
migrationBuilder.AddColumn<string>(
name: "ContainerId",
table: "agents",
type: "text",
nullable: true);
migrationBuilder.AddColumn<string>(
name: "ContainerImage",
table: "agents",
type: "text",
nullable: true);
migrationBuilder.AddColumn<long>(
name: "ContainerMemoryLimitBytes",
table: "agents",
type: "bigint",
nullable: true);
migrationBuilder.AddColumn<string>(
name: "CpuArchitecture",
table: "agents",
type: "text",
nullable: true);
migrationBuilder.AddColumn<long>(
name: "CpuCacheBytes",
table: "agents",
type: "bigint",
nullable: true);
migrationBuilder.AddColumn<string>(
name: "CpuFlags",
table: "agents",
type: "text",
nullable: true);
migrationBuilder.AddColumn<double>(
name: "CpuFrequencyMhz",
table: "agents",
type: "double precision",
nullable: true);
migrationBuilder.AddColumn<string>(
name: "CpuModel",
table: "agents",
type: "text",
nullable: true);
migrationBuilder.AddColumn<string>(
name: "CpuVendor",
table: "agents",
type: "text",
nullable: true);
migrationBuilder.AddColumn<string>(
name: "DiskInventoryJson",
table: "agents",
type: "text",
nullable: true);
migrationBuilder.AddColumn<string>(
name: "GpuInventoryJson",
table: "agents",
type: "text",
nullable: true);
migrationBuilder.AddColumn<string>(
name: "KernelVersion",
table: "agents",
type: "text",
nullable: true);
migrationBuilder.AddColumn<int>(
name: "LogicalCores",
table: "agents",
type: "integer",
nullable: true);
migrationBuilder.AddColumn<long>(
name: "MemAvailableBytes",
table: "agents",
type: "bigint",
nullable: true);
migrationBuilder.AddColumn<long>(
name: "MemTotalBytes",
table: "agents",
type: "bigint",
nullable: true);
migrationBuilder.AddColumn<string>(
name: "NetworkInterfacesJson",
table: "agents",
type: "text",
nullable: true);
migrationBuilder.AddColumn<string>(
name: "OsName",
table: "agents",
type: "text",
nullable: true);
migrationBuilder.AddColumn<int>(
name: "PhysicalCores",
table: "agents",
type: "integer",
nullable: true);
migrationBuilder.AddColumn<long>(
name: "SwapFreeBytes",
table: "agents",
type: "bigint",
nullable: true);
migrationBuilder.AddColumn<long>(
name: "SwapTotalBytes",
table: "agents",
type: "bigint",
nullable: true);
migrationBuilder.AddColumn<string>(
name: "TemperatureJson",
table: "agents",
type: "text",
nullable: true);
migrationBuilder.AddColumn<int>(
name: "ThreadsPerCore",
table: "agents",
type: "integer",
nullable: true);
migrationBuilder.AddColumn<long>(
name: "UptimeMachineSeconds",
table: "agents",
type: "bigint",
nullable: true);
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropColumn(
name: "Arch",
table: "agents");
migrationBuilder.DropColumn(
name: "ContainerCpuLimit",
table: "agents");
migrationBuilder.DropColumn(
name: "ContainerId",
table: "agents");
migrationBuilder.DropColumn(
name: "ContainerImage",
table: "agents");
migrationBuilder.DropColumn(
name: "ContainerMemoryLimitBytes",
table: "agents");
migrationBuilder.DropColumn(
name: "CpuArchitecture",
table: "agents");
migrationBuilder.DropColumn(
name: "CpuCacheBytes",
table: "agents");
migrationBuilder.DropColumn(
name: "CpuFlags",
table: "agents");
migrationBuilder.DropColumn(
name: "CpuFrequencyMhz",
table: "agents");
migrationBuilder.DropColumn(
name: "CpuModel",
table: "agents");
migrationBuilder.DropColumn(
name: "CpuVendor",
table: "agents");
migrationBuilder.DropColumn(
name: "DiskInventoryJson",
table: "agents");
migrationBuilder.DropColumn(
name: "GpuInventoryJson",
table: "agents");
migrationBuilder.DropColumn(
name: "KernelVersion",
table: "agents");
migrationBuilder.DropColumn(
name: "LogicalCores",
table: "agents");
migrationBuilder.DropColumn(
name: "MemAvailableBytes",
table: "agents");
migrationBuilder.DropColumn(
name: "MemTotalBytes",
table: "agents");
migrationBuilder.DropColumn(
name: "NetworkInterfacesJson",
table: "agents");
migrationBuilder.DropColumn(
name: "OsName",
table: "agents");
migrationBuilder.DropColumn(
name: "PhysicalCores",
table: "agents");
migrationBuilder.DropColumn(
name: "SwapFreeBytes",
table: "agents");
migrationBuilder.DropColumn(
name: "SwapTotalBytes",
table: "agents");
migrationBuilder.DropColumn(
name: "TemperatureJson",
table: "agents");
migrationBuilder.DropColumn(
name: "ThreadsPerCore",
table: "agents");
migrationBuilder.DropColumn(
name: "UptimeMachineSeconds",
table: "agents");
}
}
}
@@ -38,12 +38,45 @@ namespace Heimdall.Infrastructure.Migrations
.IsUnicode(false)
.HasColumnType("character varying(8)");
b.Property<string>("Arch")
.HasColumnType("text");
b.Property<long?>("ContainerCpuLimit")
.HasColumnType("bigint");
b.Property<string>("ContainerId")
.HasColumnType("text");
b.Property<string>("ContainerImage")
.HasColumnType("text");
b.Property<long?>("ContainerMemoryLimitBytes")
.HasColumnType("bigint");
b.Property<string>("CpuArchitecture")
.HasColumnType("text");
b.Property<long?>("CpuCacheBytes")
.HasColumnType("bigint");
b.Property<int>("CpuCores")
.HasColumnType("integer");
b.Property<string>("CpuFlags")
.HasColumnType("text");
b.Property<double?>("CpuFrequencyMhz")
.HasColumnType("double precision");
b.Property<string>("CpuModel")
.HasColumnType("text");
b.Property<double?>("CpuUsagePercent")
.HasColumnType("double precision");
b.Property<string>("CpuVendor")
.HasColumnType("text");
b.Property<DateTime>("CreatedAt")
.ValueGeneratedOnAdd()
.HasColumnType("timestamp with time zone")
@@ -52,9 +85,15 @@ namespace Heimdall.Infrastructure.Migrations
b.Property<DateTime?>("DeletedAt")
.HasColumnType("timestamp with time zone");
b.Property<string>("DiskInventoryJson")
.HasColumnType("text");
b.Property<double?>("DiskUsagePercent")
.HasColumnType("double precision");
b.Property<string>("GpuInventoryJson")
.HasColumnType("text");
b.Property<string>("GpuType")
.IsRequired()
.HasMaxLength(20)
@@ -73,9 +112,21 @@ namespace Heimdall.Infrastructure.Migrations
b.Property<bool>("IsDeleted")
.HasColumnType("boolean");
b.Property<string>("KernelVersion")
.HasColumnType("text");
b.Property<DateTime?>("LastHeartbeat")
.HasColumnType("timestamp with time zone");
b.Property<int?>("LogicalCores")
.HasColumnType("integer");
b.Property<long?>("MemAvailableBytes")
.HasColumnType("bigint");
b.Property<long?>("MemTotalBytes")
.HasColumnType("bigint");
b.Property<long>("MemoryMb")
.HasColumnType("bigint");
@@ -88,6 +139,15 @@ namespace Heimdall.Infrastructure.Migrations
.IsUnicode(false)
.HasColumnType("character varying(200)");
b.Property<string>("NetworkInterfacesJson")
.HasColumnType("text");
b.Property<string>("OsName")
.HasColumnType("text");
b.Property<int?>("PhysicalCores")
.HasColumnType("integer");
b.Property<string>("PublicIp")
.HasMaxLength(45)
.IsUnicode(false)
@@ -102,11 +162,26 @@ namespace Heimdall.Infrastructure.Migrations
.IsUnicode(false)
.HasColumnType("character varying(20)");
b.Property<long?>("SwapFreeBytes")
.HasColumnType("bigint");
b.Property<long?>("SwapTotalBytes")
.HasColumnType("bigint");
b.Property<string>("TemperatureJson")
.HasColumnType("text");
b.Property<int?>("ThreadsPerCore")
.HasColumnType("integer");
b.Property<DateTime>("UpdatedAt")
.ValueGeneratedOnAdd()
.HasColumnType("timestamp with time zone")
.HasDefaultValueSql("NOW()");
b.Property<long?>("UptimeMachineSeconds")
.HasColumnType("bigint");
b.Property<long?>("UptimeSeconds")
.HasColumnType("bigint");
@@ -213,9 +213,9 @@ public sealed class CameraDiscoveryService : ICameraDiscoveryService
{
await Task.WhenAll(tasks).WaitAsync(timeoutCts.Token).ConfigureAwait(false);
}
catch (OperationCanceledException) when (!ct.IsCancellationRequested)
catch (OperationCanceledException ex) when (!ct.IsCancellationRequested)
{
_logger.LogWarning("Subnet scan timed out after {TimeoutMs}ms", request.TimeoutMs);
_logger.LogWarning(ex, "Subnet scan timed out after {TimeoutMs}ms", request.TimeoutMs);
}
_logger.LogInformation(
@@ -496,67 +496,9 @@ public sealed class CameraDiscoveryService : ICameraDiscoveryService
foreach (var device in devices)
{
if (string.IsNullOrWhiteSpace(device.Ip) || !IPAddress.TryParse(device.Ip, out _))
continue;
// Defense: ignore devices with no camera evidence (older agents that
// still report web servers / gateways).
if (ClassifyAgentDevice(device).type == DetectedCameraType.Unknown)
continue;
// Upsert: reuse an existing unprocessed result for site+IP.
var result = await db.CameraDiscoveryResults
.Include(r => r.DiscoveredStreams)
.FirstOrDefaultAsync(r => r.SiteId == siteId && r.IpAddress == device.Ip && !r.IsProcessed, ct)
.ConfigureAwait(false);
if (result is null)
{
result = new CameraDiscoveryResult(siteId, device.Ip);
db.CameraDiscoveryResults.Add(result);
newCount++;
}
else
{
updatedCount++;
}
ApplyAgentProbeData(result, device);
// Screenshot (agent-captured JPEG, base64) → in-memory cache keyed
// by the discovery result id. Never persisted.
if (!string.IsNullOrEmpty(device.ScreenshotBase64))
{
try
{
var bytes = Convert.FromBase64String(device.ScreenshotBase64);
_screenshots[result.Id] = new ScreenshotEntry(bytes, DateTime.UtcNow.AddMinutes(10));
}
catch (FormatException)
{
_logger.LogDebug("Invalid screenshot base64 for {Ip}, ignoring", device.Ip);
}
}
// The agent performs the authenticated ONVIF enrichment itself
// (it is on the camera network and holds the site's credential
// pool via the encrypted agent config). When it reports the label
// of the credential that succeeded, mark it as used.
if (!string.IsNullOrEmpty(device.CredentialLabel))
{
var used = pool.FirstOrDefault(p =>
string.Equals(p.Credential.Label, device.CredentialLabel, StringComparison.Ordinal));
if (used.Credential is not null)
{
used.Credential.MarkUsed();
_logger.LogInformation(
"Agent discovery {Ip} authenticated with credential '{Label}' (reported by agent)",
device.Ip, device.CredentialLabel);
}
}
// ── Build candidate stream URLs ─────────────────────────────
await BuildCandidateStreamUrlsAsync(db, result, device, pool, ct).ConfigureAwait(false);
var processed = await ProcessDiscoveredDeviceAsync(db, siteId, device, pool, ct).ConfigureAwait(false);
if (processed == 1) newCount++;
else if (processed == 2) updatedCount++;
}
await db.SaveChangesWithRetryAsync(ct: ct).ConfigureAwait(false);
@@ -569,6 +511,74 @@ public sealed class CameraDiscoveryService : ICameraDiscoveryService
new AgentDiscoverySubmitResponse(devices.Count, newCount, updatedCount));
}
/// <summary>Process a single discovered device from an agent submission.</summary>
/// <returns>0 = skipped, 1 = new, 2 = updated.</returns>
private async Task<int> ProcessDiscoveredDeviceAsync(
AppDbContext db, Guid? siteId, AgentDiscoveredDevice device,
List<(SiteCredential Credential, string Password)> pool, CancellationToken ct)
{
if (string.IsNullOrWhiteSpace(device.Ip) || !IPAddress.TryParse(device.Ip, out _))
return 0;
if (ClassifyAgentDevice(device).type == DetectedCameraType.Unknown)
return 0;
var result = await db.CameraDiscoveryResults
.Include(r => r.DiscoveredStreams)
.FirstOrDefaultAsync(r => r.SiteId == siteId && r.IpAddress == device.Ip && !r.IsProcessed, ct)
.ConfigureAwait(false);
int outcome;
if (result is null)
{
result = new CameraDiscoveryResult(siteId!.Value, device.Ip);
db.CameraDiscoveryResults.Add(result);
outcome = 1;
}
else
{
outcome = 2;
}
ApplyAgentProbeData(result, device);
CacheScreenshot(result, device);
MarkCredentialUsed(device, pool);
await BuildCandidateStreamUrlsAsync(db, result, device, pool, ct).ConfigureAwait(false);
return outcome;
}
private void CacheScreenshot(CameraDiscoveryResult result, AgentDiscoveredDevice device)
{
if (string.IsNullOrEmpty(device.ScreenshotBase64))
return;
try
{
var bytes = Convert.FromBase64String(device.ScreenshotBase64);
_screenshots[result.Id] = new ScreenshotEntry(bytes, DateTime.UtcNow.AddMinutes(10));
}
catch (FormatException ex)
{
_logger.LogDebug(ex, "Invalid screenshot base64 for {Ip}, ignoring", device.Ip);
}
}
private void MarkCredentialUsed(AgentDiscoveredDevice device, List<(SiteCredential Credential, string Password)> pool)
{
if (string.IsNullOrEmpty(device.CredentialLabel))
return;
var used = pool.FirstOrDefault(p =>
string.Equals(p.Credential.Label, device.CredentialLabel, StringComparison.Ordinal));
if (used.Credential is not null)
{
used.Credential.MarkUsed();
_logger.LogInformation(
"Agent discovery {Ip} authenticated with credential '{Label}' (reported by agent)",
device.Ip, device.CredentialLabel);
}
}
private void ApplyAgentProbeData(CameraDiscoveryResult result, AgentDiscoveredDevice device)
{
var mac = device.MacAddress ?? result.MacAddress;
@@ -237,7 +237,7 @@ public sealed partial class StreamTesterService
using var ms = new MemoryStream();
var copyTask = process.StandardOutput.BaseStream.CopyToAsync(ms, cts.Token);
var stderrTask = process.StandardError.ReadToEndAsync(cts.Token);
_ = process.StandardError.ReadToEndAsync(cts.Token); // drain stderr to prevent deadlock
var completed = await Task.WhenAny(copyTask, Task.Delay(TimeSpan.FromSeconds(8), ct)).ConfigureAwait(false);
if (completed != copyTask)
@@ -302,7 +302,7 @@ public sealed partial class StreamTesterService
{
var n = await stream.ReadAsync(buffer, cts.Token).ConfigureAwait(false);
if (n == 0) break;
ms.Write(buffer, 0, n);
await ms.WriteAsync(buffer.AsMemory(0, n), cts.Token).ConfigureAwait(false);
total += n;
var data = ms.GetBuffer();