Files
Heimdall/tests/Heimdall.Application.Tests/Handlers/Agents/HeartbeatHandlerInventoryTests.cs
T
Arnaud Dartois 4792b69e46 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
2026-08-20 14:13:06 +02:00

172 lines
7.2 KiB
C#

using Heimdall.Application.Agents.Commands.Heartbeat;
using Heimdall.Application.Common;
using Heimdall.Application.Tests.Common;
using Heimdall.Domain.Entities;
using Heimdall.Domain.Enums;
using NSubstitute;
using Microsoft.EntityFrameworkCore;
namespace Heimdall.Application.Tests.Handlers.Agents;
public class HeartbeatHandlerInventoryTests
{
private readonly Agent _existingAgent = new(Guid.NewGuid(), "agent-1", "agent-1", "1.0.0");
[Fact]
public async Task Heartbeat_with_cpu_inventory_should_update_fields()
{
_existingAgent.Register("hash", "pref");
var context = Substitute.For<IApplicationDbContext>();
context.Agents.Returns(MockDbSetHelper.CreateFor<Agent>([_existingAgent]));
var handler = new HeartbeatHandler(context);
var command = new HeartbeatCommand(
_existingAgent.Id, null, null, null, null, null,
CpuVendor: "GenuineIntel",
CpuModel: "Intel Core i7-12700K",
CpuArchitecture: "x86_64",
PhysicalCores: 12,
LogicalCores: 20,
ThreadsPerCore: 2,
CpuFrequencyMhz: 3600.0,
CpuFlags: "avx,avx2,fma",
CpuCacheBytes: 25_165_824,
ContainerCpuLimit: 200);
var result = await handler.Handle(command, CancellationToken.None);
result.IsSuccess.ShouldBeTrue();
_existingAgent.CpuVendor.ShouldBe("GenuineIntel");
_existingAgent.CpuModel.ShouldBe("Intel Core i7-12700K");
_existingAgent.CpuArchitecture.ShouldBe("x86_64");
_existingAgent.PhysicalCores.ShouldBe(12);
_existingAgent.LogicalCores.ShouldBe(20);
_existingAgent.ThreadsPerCore.ShouldBe(2);
_existingAgent.CpuFrequencyMhz.ShouldBe(3600.0);
_existingAgent.CpuFlags.ShouldBe("avx,avx2,fma");
_existingAgent.CpuCacheBytes.ShouldBe(25_165_824);
_existingAgent.ContainerCpuLimit.ShouldBe(200);
}
[Fact]
public async Task Heartbeat_with_memory_inventory_should_update_fields()
{
_existingAgent.Register("hash", "pref");
var context = Substitute.For<IApplicationDbContext>();
context.Agents.Returns(MockDbSetHelper.CreateFor<Agent>([_existingAgent]));
var handler = new HeartbeatHandler(context);
var command = new HeartbeatCommand(
_existingAgent.Id, null, null, null, null, null,
MemTotalBytes: 17_179_869_184,
MemAvailableBytes: 8_589_934_592,
SwapTotalBytes: 2_147_483_648,
SwapFreeBytes: 1_073_741_824,
ContainerMemoryLimitBytes: 4_294_967_296,
DiskInventoryJson: """[{"MountPoint":"/","FileSystem":"ext4","TotalBytes":107374182400}]""");
var result = await handler.Handle(command, CancellationToken.None);
result.IsSuccess.ShouldBeTrue();
_existingAgent.MemTotalBytes.ShouldBe(17_179_869_184);
_existingAgent.MemAvailableBytes.ShouldBe(8_589_934_592);
_existingAgent.SwapTotalBytes.ShouldBe(2_147_483_648);
_existingAgent.SwapFreeBytes.ShouldBe(1_073_741_824);
_existingAgent.ContainerMemoryLimitBytes.ShouldBe(4_294_967_296);
_existingAgent.DiskInventoryJson.ShouldNotBeNull();
_existingAgent.DiskInventoryJson.ShouldContain("ext4");
}
[Fact]
public async Task Heartbeat_with_gpu_inventory_should_update_field()
{
_existingAgent.Register("hash", "pref");
var context = Substitute.For<IApplicationDbContext>();
context.Agents.Returns(MockDbSetHelper.CreateFor<Agent>([_existingAgent]));
var handler = new HeartbeatHandler(context);
var gpuJson = """[{"Vendor":"Nvidia","Model":"RTX 3090","VramBytes":25769803776}]""";
var command = new HeartbeatCommand(
_existingAgent.Id, null, null, null, null, null,
GpuInventoryJson: gpuJson);
var result = await handler.Handle(command, CancellationToken.None);
result.IsSuccess.ShouldBeTrue();
_existingAgent.GpuInventoryJson.ShouldBe(gpuJson);
}
[Fact]
public async Task Heartbeat_with_host_inventory_should_update_fields()
{
_existingAgent.Register("hash", "pref");
var context = Substitute.For<IApplicationDbContext>();
context.Agents.Returns(MockDbSetHelper.CreateFor<Agent>([_existingAgent]));
var handler = new HeartbeatHandler(context);
var command = new HeartbeatCommand(
_existingAgent.Id, null, null, null, null, null,
OsName: "Ubuntu 22.04 LTS",
KernelVersion: "5.15.0-76-generic",
Arch: "x86_64",
UptimeMachineSeconds: 86400,
ContainerId: "abc123",
ContainerImage: "heimdall/agent:latest",
NetworkInterfacesJson: """[{"Name":"eth0","IpAddress":"192.168.1.100"}]""",
TemperatureJson: """[{"Zone":"coretemp","TemperatureCelsius":45.0}]""");
var result = await handler.Handle(command, CancellationToken.None);
result.IsSuccess.ShouldBeTrue();
_existingAgent.OsName.ShouldBe("Ubuntu 22.04 LTS");
_existingAgent.KernelVersion.ShouldBe("5.15.0-76-generic");
_existingAgent.Arch.ShouldBe("x86_64");
_existingAgent.UptimeMachineSeconds.ShouldBe(86400);
_existingAgent.ContainerId.ShouldBe("abc123");
_existingAgent.ContainerImage.ShouldBe("heimdall/agent:latest");
_existingAgent.NetworkInterfacesJson.ShouldNotBeNull();
_existingAgent.NetworkInterfacesJson.ShouldContain("eth0");
_existingAgent.TemperatureJson.ShouldNotBeNull();
_existingAgent.TemperatureJson.ShouldContain("coretemp");
}
[Fact]
public async Task Heartbeat_without_inventory_should_not_change_inventory_fields()
{
_existingAgent.Register("hash", "pref");
// Set some inventory data first
_existingAgent.UpdateCpuInventory(new CpuInventoryData("Intel", "i7", "x86_64", 8, 16, 2, 3600.0, "avx", 12345, null));
var context = Substitute.For<IApplicationDbContext>();
context.Agents.Returns(MockDbSetHelper.CreateFor<Agent>([_existingAgent]));
var handler = new HeartbeatHandler(context);
// Heartbeat without inventory fields
var command = new HeartbeatCommand(
_existingAgent.Id, "10.0.0.1", null, null, null, null,
CpuUsagePercent: 50.0);
var result = await handler.Handle(command, CancellationToken.None);
result.IsSuccess.ShouldBeTrue();
// Inventory should be preserved
_existingAgent.CpuVendor.ShouldBe("Intel");
_existingAgent.CpuModel.ShouldBe("i7");
}
[Fact]
public async Task Heartbeat_isOffline_should_not_update_inventory()
{
_existingAgent.Register("hash", "pref");
var context = Substitute.For<IApplicationDbContext>();
context.Agents.Returns(MockDbSetHelper.CreateFor<Agent>([_existingAgent]));
var handler = new HeartbeatHandler(context);
var command = new HeartbeatCommand(
_existingAgent.Id, null, null, null, null, null,
IsOffline: true,
CpuVendor: "Intel",
OsName: "Linux");
var result = await handler.Handle(command, CancellationToken.None);
result.IsSuccess.ShouldBeTrue();
_existingAgent.CpuVendor.ShouldBeNull();
_existingAgent.OsName.ShouldBeNull();
}
}