Files
Heimdall/src/Heimdall.Agent/Services/DiskInventoryProvider.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

161 lines
4.7 KiB
C#

namespace Heimdall.Agent.Services;
/// <summary>
/// Enumerates disk mounts from /proc/mounts and detects disk type (SSD/HDD) from sysfs.
/// </summary>
public sealed class DiskInventoryProvider
{
private const string ProcMountsPath = "/proc/mounts";
private const string Unknown = "Unknown";
public IReadOnlyList<DiskInfo> Collect()
{
var disks = new List<DiskInfo>();
try
{
if (!OperatingSystem.IsLinux())
return disks;
var mounts = ParseProcMounts();
foreach (var mount in mounts)
{
var diskInfo = new DiskInfo
{
MountPoint = mount.MountPoint,
FileSystem = mount.FileSystem,
TotalBytes = GetDiskTotalBytes(mount.MountPoint),
UsedBytes = GetDiskUsedBytes(mount.MountPoint),
Type = DetectDiskType(mount.MountPoint)
};
if (diskInfo.TotalBytes is > 0)
disks.Add(diskInfo);
}
}
catch { /* best effort */ }
return disks;
}
private static List<MountEntry> ParseProcMounts()
{
var mounts = new List<MountEntry>();
try
{
if (!File.Exists(ProcMountsPath))
return mounts;
HashSet<string> skipFs =
[
"proc", "sysfs", "devpts", "tmpfs", "cgroup", "cgroup2",
"overlay", "squashfs", "devtmpfs", "securityfs", "pstore",
"debugfs", "hugetlbfs", "mqueue", "fusectl", "configfs",
"tracefs", "bpf", "rpc_pipefs", "nfsd", "autofs"
];
foreach (var line in File.ReadLines(ProcMountsPath))
{
var parts = line.Split(' ', StringSplitOptions.RemoveEmptyEntries);
if (parts.Length < 2) continue;
var device = parts[0];
var mountPoint = parts[1];
var fsType = parts[2];
if (skipFs.Contains(fsType, StringComparer.OrdinalIgnoreCase)) continue;
if (!device.StartsWith("/dev/", StringComparison.Ordinal)) continue;
mounts.Add(new MountEntry
{
Device = device,
MountPoint = mountPoint,
FileSystem = fsType
});
}
}
catch { /* best effort */ }
return mounts;
}
private static long? GetDiskTotalBytes(string mountPoint)
{
try
{
var drive = new DriveInfo(mountPoint);
if (drive.IsReady)
return drive.TotalSize;
}
catch { /* best effort */ }
return null;
}
private static long? GetDiskUsedBytes(string mountPoint)
{
try
{
var drive = new DriveInfo(mountPoint);
if (drive.IsReady)
return drive.TotalSize - drive.AvailableFreeSpace;
}
catch { /* best effort */ }
return null;
}
/// <summary>
/// Detects disk type (SSD/HDD) by checking /sys/block/*/queue/rotation.
/// rotation=0 means SSD, rotation=1 means HDD.
/// </summary>
private static string DetectDiskType(string mountPoint)
{
try
{
if (!File.Exists(ProcMountsPath))
return Unknown;
return FindDiskRotation(mountPoint) ?? Unknown;
}
catch
{
return Unknown;
}
}
private static string? FindDiskRotation(string mountPoint)
{
foreach (var line in File.ReadLines(ProcMountsPath))
{
var parts = line.Split(' ', StringSplitOptions.RemoveEmptyEntries);
if (parts.Length < 2 || parts[1] != mountPoint || !parts[0].StartsWith("/dev/", StringComparison.Ordinal))
continue;
var deviceName = Path.GetFileName(parts[0]);
var rotationPath = $"/sys/block/{deviceName}/queue/rotation";
if (!File.Exists(rotationPath)) return null;
var rotation = File.ReadAllText(rotationPath).Trim();
return rotation == "0" ? "SSD" : "HDD";
}
return null;
}
private sealed class MountEntry
{
public string Device { get; init; } = "";
public string MountPoint { get; init; } = "";
public string FileSystem { get; init; } = "";
}
}
/// <summary>
/// Disk inventory data for a single mount point.
/// </summary>
public sealed record DiskInfo
{
public string MountPoint { get; init; } = "";
public string FileSystem { get; init; } = "";
public long? TotalBytes { get; init; }
public long? UsedBytes { get; init; }
public string Type { get; init; } = "Unknown";
}