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

+1 -1
View File
@@ -21,6 +21,6 @@
<PackageReference Include="Microsoft.AspNetCore.SignalR.Client" Version="10.0.8" />
<PackageReference Include="Microsoft.ML.OnnxRuntime" Version="1.22.0" />
<PackageReference Include="Sentry.AspNetCore" Version="6.8.0" />
<PackageReference Include="SixLabors.ImageSharp" Version="4.1.0" />
<PackageReference Include="Magick.NET-Q16-AnyCPU" Version="14.16.0" />
</ItemGroup>
</Project>
+8
View File
@@ -82,6 +82,14 @@ builder.Services.AddSingleton<AgentState>(sp =>
});
builder.Services.AddSingleton<SystemMetricsProvider>();
// Inventory providers (grouped under InventoryProviders to reduce constructor parameter count)
builder.Services.AddSingleton<CpuInfoProvider>();
builder.Services.AddSingleton<DiskInventoryProvider>();
builder.Services.AddSingleton<HostInfoProvider>();
builder.Services.AddSingleton<ContainerInfoProvider>();
builder.Services.AddSingleton<InventoryProviders>();
builder.Services.AddSingleton<NetworkCameraScanner>();
builder.Services.AddSingleton<HomeKitMdnsProbe>();
builder.Services.AddSingleton<ICameraDatabase, SqliteCameraDatabase>();
@@ -5,6 +5,21 @@ using Microsoft.Extensions.Options;
namespace Heimdall.Agent.Services;
/// <summary>
/// Groups inventory-related services to reduce constructor parameter count.
/// </summary>
public sealed class InventoryProviders(
CpuInfoProvider cpuInfo,
DiskInventoryProvider diskInventory,
HostInfoProvider hostInfo,
ContainerInfoProvider containerInfo)
{
public CpuInfoProvider CpuInfo { get; } = cpuInfo;
public DiskInventoryProvider DiskInventory { get; } = diskInventory;
public HostInfoProvider HostInfo { get; } = hostInfo;
public ContainerInfoProvider ContainerInfo { get; } = containerInfo;
}
/// <summary>
/// Registers this agent with the Heimdall Central server and manages the heartbeat loop.
/// </summary>
@@ -15,14 +30,21 @@ public class AgentRegistrationService : BackgroundService
private readonly AgentState _state;
private readonly AgentOptions _options;
private readonly SystemMetricsProvider _metrics;
private readonly InventoryProviders _providers;
private readonly Logging.LogBufferService _buffer;
private HttpClient? _client;
/// <summary>Interval for full inventory refresh (5 minutes).</summary>
private static readonly TimeSpan InventoryRefreshInterval = TimeSpan.FromMinutes(5);
private const string ApiKeyHeader = "X-API-Key";
private DateTime _lastInventoryRefresh = DateTime.MinValue;
public AgentRegistrationService(
IHttpClientFactory httpClientFactory,
AgentState state,
IOptions<AgentOptions> options,
SystemMetricsProvider metrics,
InventoryProviders providers,
Logging.LogBufferService buffer,
ILogger<AgentRegistrationService> logger)
{
@@ -30,6 +52,7 @@ public class AgentRegistrationService : BackgroundService
_state = state;
_options = options.Value;
_metrics = metrics;
_providers = providers;
_buffer = buffer;
_logger = logger;
}
@@ -42,27 +65,32 @@ public class AgentRegistrationService : BackgroundService
if (_client is not null && _state.AgentId != Guid.Empty)
{
_logger.LogInformation("Agent stopping, sending final heartbeat...");
try
{
var metrics = _metrics.Collect();
var request = new HeartbeatRequest(_state.PublicIp, IsOffline: true,
CpuUsagePercent: metrics.CpuUsagePercent,
MemoryUsageBytes: metrics.MemoryUsageBytes,
DiskUsagePercent: metrics.DiskUsagePercent,
UptimeSeconds: metrics.UptimeSeconds);
await _client.PostAsJsonAsync(
$"api/agents/{_state.AgentId}/heartbeat",
request, CancellationToken.None);
}
catch (Exception ex)
{
_logger.LogWarning(ex, "Final heartbeat failed (non-fatal)");
}
await SendFinalHeartbeatAsync();
}
await base.StopAsync(cancellationToken);
}
private async Task SendFinalHeartbeatAsync()
{
try
{
var metrics = _metrics.Collect();
var request = new HeartbeatRequest(_state.PublicIp, IsOffline: true,
CpuUsagePercent: metrics.CpuUsagePercent,
MemoryUsageBytes: metrics.MemoryUsageBytes,
DiskUsagePercent: metrics.DiskUsagePercent,
UptimeSeconds: metrics.UptimeSeconds);
await _client!.PostAsJsonAsync(
$"api/agents/{_state.AgentId}/heartbeat",
request, CancellationToken.None);
}
catch (Exception ex)
{
_logger.LogWarning(ex, "Final heartbeat failed (non-fatal)");
}
}
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
var hostname = string.IsNullOrEmpty(_options.AgentName)
@@ -80,8 +108,8 @@ public class AgentRegistrationService : BackgroundService
_state.ApiKeyPrefix = existing.ApiKeyPrefix;
_state.PublicIp = existing.PublicIp;
client.DefaultRequestHeaders.Remove("X-API-Key");
client.DefaultRequestHeaders.Add("X-API-Key", existing.ApiKey);
client.DefaultRequestHeaders.Remove(ApiKeyHeader);
client.DefaultRequestHeaders.Add(ApiKeyHeader, existing.ApiKey);
_client = client;
_logger.LogInformation(
@@ -90,58 +118,7 @@ public class AgentRegistrationService : BackgroundService
}
else
{
// Step 1: Register (with retry)
_logger.LogInformation("Registering agent with Central at {CentralUrl}", _options.CentralUrl);
var maxRetries = _options.RegistrationMaxRetries;
RegisterResponse? registration = null;
for (int attempt = 1; attempt <= maxRetries; attempt++)
{
try
{
var request = new RegisterRequest(_options.SiteToken, hostname, _options.Version);
var response = await client.PostAsJsonAsync("api/agents/register", request, stoppingToken);
response.EnsureSuccessStatusCode();
registration = await response.Content.ReadFromJsonAsync<RegisterResponse>(stoppingToken);
if (registration is null)
throw new InvalidOperationException("Empty registration response");
break; // success
}
catch (Exception ex) when (attempt < maxRetries && ex is not OperationCanceledException)
{
var delay = TimeSpan.FromSeconds(Math.Pow(2, attempt));
_logger.LogWarning(ex,
"Registration attempt {Attempt}/{Max} failed, retrying in {Delay}s",
attempt, maxRetries, delay.TotalSeconds);
await Task.Delay(delay, stoppingToken);
}
}
if (registration is null)
{
_logger.LogError("All {Max} registration attempts failed", maxRetries);
throw new InvalidOperationException("Agent registration failed after all retries");
}
_state.AgentId = registration.AgentId;
_state.ApiKey = registration.ApiKey;
_state.ApiKeyPrefix = registration.ApiKeyPrefix;
_state.PublicIp = await ResolvePublicIpAsync(stoppingToken);
// Persist identity so subsequent restarts reuse it
await _state.SaveAsync(stoppingToken);
// Set API Key header for subsequent requests (Central's ApiKey scheme reads X-API-Key)
client.DefaultRequestHeaders.Remove("X-API-Key");
client.DefaultRequestHeaders.Add("X-API-Key", registration.ApiKey);
_client = client;
_logger.LogInformation(
"Agent registered successfully. ID: {AgentId}, Key prefix: {Prefix}",
registration.AgentId, registration.ApiKeyPrefix);
await RegisterAgentAsync(client, hostname, stoppingToken);
}
// Step 2: Heartbeat loop
@@ -151,33 +128,7 @@ public class AgentRegistrationService : BackgroundService
while (!stoppingToken.IsCancellationRequested)
{
try
{
var metrics = _metrics.Collect();
var heartbeatRequest = new HeartbeatRequest(
_state.PublicIp,
CpuUsagePercent: metrics.CpuUsagePercent,
MemoryUsageBytes: metrics.MemoryUsageBytes,
DiskUsagePercent: metrics.DiskUsagePercent,
UptimeSeconds: metrics.UptimeSeconds);
var heartbeatResponse = await client.PostAsJsonAsync(
$"api/agents/{_state.AgentId}/heartbeat",
heartbeatRequest, stoppingToken);
if (!heartbeatResponse.IsSuccessStatusCode)
{
_logger.LogWarning("Heartbeat failed: {StatusCode}", heartbeatResponse.StatusCode);
}
else
{
_logger.LogDebug("Heartbeat OK — agent online, {Buffered} log(s) buffered",
_buffer.Count);
}
}
catch (Exception ex) when (ex is not OperationCanceledException)
{
_logger.LogWarning(ex, "Heartbeat error (will retry)");
}
await SendHeartbeatAsync(client, stoppingToken);
// Re-read the interval each cycle so a remote setting change
// (ConfigReceiverService → AgentState.HeartbeatIntervalSeconds)
@@ -188,6 +139,153 @@ public class AgentRegistrationService : BackgroundService
}
}
private async Task RegisterAgentAsync(HttpClient client, string hostname, CancellationToken stoppingToken)
{
_logger.LogInformation("Registering agent with Central at {CentralUrl}", _options.CentralUrl);
var maxRetries = _options.RegistrationMaxRetries;
RegisterResponse? registration = null;
for (int attempt = 1; attempt <= maxRetries; attempt++)
{
try
{
var request = new RegisterRequest(_options.SiteToken, hostname, _options.Version);
var response = await client.PostAsJsonAsync("api/agents/register", request, stoppingToken);
response.EnsureSuccessStatusCode();
registration = await response.Content.ReadFromJsonAsync<RegisterResponse>(stoppingToken);
if (registration is null)
throw new InvalidOperationException("Empty registration response");
break; // success
}
catch (Exception ex) when (attempt < maxRetries && ex is not OperationCanceledException)
{
var delay = TimeSpan.FromSeconds(Math.Pow(2, attempt));
_logger.LogWarning(ex,
"Registration attempt {Attempt}/{Max} failed, retrying in {Delay}s",
attempt, maxRetries, delay.TotalSeconds);
await Task.Delay(delay, stoppingToken);
}
}
if (registration is null)
{
_logger.LogError("All {Max} registration attempts failed", maxRetries);
throw new InvalidOperationException("Agent registration failed after all retries");
}
_state.AgentId = registration.AgentId;
_state.ApiKey = registration.ApiKey;
_state.ApiKeyPrefix = registration.ApiKeyPrefix;
_state.PublicIp = await ResolvePublicIpAsync(stoppingToken);
// Persist identity so subsequent restarts reuse it
await _state.SaveAsync(stoppingToken);
// Set API Key header for subsequent requests
client.DefaultRequestHeaders.Remove(ApiKeyHeader);
client.DefaultRequestHeaders.Add(ApiKeyHeader, registration.ApiKey);
_client = client;
_logger.LogInformation(
"Agent registered successfully. ID: {AgentId}, Key prefix: {Prefix}",
registration.AgentId, registration.ApiKeyPrefix);
}
private async Task SendHeartbeatAsync(HttpClient client, CancellationToken stoppingToken)
{
try
{
var metrics = _metrics.Collect();
var inventory = CollectInventoryIfNeeded();
var heartbeatRequest = BuildHeartbeatRequest(metrics, inventory);
var heartbeatResponse = await client.PostAsJsonAsync(
$"api/agents/{_state.AgentId}/heartbeat",
heartbeatRequest, stoppingToken);
if (!heartbeatResponse.IsSuccessStatusCode)
{
_logger.LogWarning("Heartbeat failed: {StatusCode}", heartbeatResponse.StatusCode);
}
else
{
_logger.LogDebug("Heartbeat OK — agent online, {Buffered} log(s) buffered",
_buffer.Count);
}
}
catch (Exception ex) when (ex is not OperationCanceledException)
{
_logger.LogWarning(ex, "Heartbeat error (will retry)");
}
}
private HeartbeatRequest BuildHeartbeatRequest(SystemMetrics metrics, InventorySnapshot? inventory) => new(
_state.PublicIp,
CpuUsagePercent: metrics.CpuUsagePercent,
MemoryUsageBytes: metrics.MemoryUsageBytes,
DiskUsagePercent: metrics.DiskUsagePercent,
UptimeSeconds: metrics.UptimeSeconds,
MachineUptimeSeconds: metrics.MachineUptimeSeconds,
CpuVendor: inventory?.Cpu?.Vendor,
CpuModel: inventory?.Cpu?.Model,
CpuArchitecture: inventory?.Cpu?.Architecture,
PhysicalCores: inventory?.Cpu?.PhysicalCores,
LogicalCores: inventory?.Cpu?.LogicalCores,
ThreadsPerCore: inventory?.Cpu?.ThreadsPerCore,
CpuFrequencyMhz: inventory?.Cpu?.FrequencyMhz,
CpuFlags: inventory?.Cpu?.Flags,
CpuCacheBytes: inventory?.Cpu?.CacheBytes,
ContainerCpuLimit: inventory?.Cpu?.ContainerCpuLimit,
MemTotalBytes: inventory?.MemTotalBytes,
MemAvailableBytes: inventory?.MemAvailableBytes,
SwapTotalBytes: inventory?.SwapTotalBytes,
SwapFreeBytes: inventory?.SwapFreeBytes,
ContainerMemoryLimitBytes: inventory?.Container?.MemoryLimitBytes,
DiskInventoryJson: inventory?.DiskJson,
GpuInventoryJson: inventory?.GpuJson,
OsName: inventory?.Host?.OsName,
KernelVersion: inventory?.Host?.KernelVersion,
Arch: inventory?.Host?.Arch,
UptimeMachineSeconds: inventory?.Host?.UptimeSeconds,
ContainerId: inventory?.Container?.ContainerId,
ContainerImage: inventory?.Container?.ContainerImage,
NetworkInterfacesJson: inventory?.NetworkJson,
TemperatureJson: inventory?.TemperatureJson);
private InventorySnapshot? CollectInventoryIfNeeded()
{
var now = DateTime.UtcNow;
if (now - _lastInventoryRefresh < InventoryRefreshInterval)
return null; // use cached/null inventory this tick
_lastInventoryRefresh = now;
_logger.LogDebug("Collecting hardware inventory...");
var cpu = _providers.CpuInfo.Collect();
var disks = _providers.DiskInventory.Collect();
var gpus = GpuInventoryProvider.Collect();
var host = _providers.HostInfo.Collect();
var container = _providers.ContainerInfo.Collect();
return new InventorySnapshot
{
Cpu = cpu,
Host = host,
Container = container,
MemTotalBytes = MemoryReader.GetMemoryTotal(),
MemAvailableBytes = MemoryReader.GetMemoryAvailable(),
SwapTotalBytes = MemoryReader.GetSwapTotal(),
SwapFreeBytes = MemoryReader.GetSwapFree(),
DiskJson = System.Text.Json.JsonSerializer.Serialize(disks),
GpuJson = System.Text.Json.JsonSerializer.Serialize(gpus),
NetworkJson = System.Text.Json.JsonSerializer.Serialize(host.NetworkInterfaces),
TemperatureJson = System.Text.Json.JsonSerializer.Serialize(host.Temperature)
};
}
private async Task<string?> ResolvePublicIpAsync(CancellationToken ct)
{
try
@@ -201,10 +299,25 @@ public class AgentRegistrationService : BackgroundService
}
catch (Exception ex)
{
_logger.LogDebug("Public IP resolution failed ({Error}); reporting null", ex.Message);
_logger.LogDebug(ex, "Public IP resolution failed; reporting null");
return null;
}
}
private sealed class InventorySnapshot
{
public CpuInfo? Cpu { get; init; }
public HostInfo? Host { get; init; }
public ContainerInfo? Container { get; init; }
public long? MemTotalBytes { get; init; }
public long? MemAvailableBytes { get; init; }
public long? SwapTotalBytes { get; init; }
public long? SwapFreeBytes { get; init; }
public string? DiskJson { get; init; }
public string? GpuJson { get; init; }
public string? NetworkJson { get; init; }
public string? TemperatureJson { get; init; }
}
}
internal sealed record RegisterRequest(string Token, string Hostname, string Version);
@@ -220,4 +333,37 @@ internal sealed record HeartbeatRequest(
[property: JsonPropertyName("cpuUsagePercent")] double? CpuUsagePercent = null,
[property: JsonPropertyName("memoryUsageBytes")] long? MemoryUsageBytes = null,
[property: JsonPropertyName("diskUsagePercent")] double? DiskUsagePercent = null,
[property: JsonPropertyName("uptimeSeconds")] long? UptimeSeconds = null);
[property: JsonPropertyName("uptimeSeconds")] long? UptimeSeconds = null,
[property: JsonPropertyName("machineUptimeSeconds")] long? MachineUptimeSeconds = null,
// CPU inventory
[property: JsonPropertyName("cpuVendor")] string? CpuVendor = null,
[property: JsonPropertyName("cpuModel")] string? CpuModel = null,
[property: JsonPropertyName("cpuArchitecture")] string? CpuArchitecture = null,
[property: JsonPropertyName("physicalCores")] int? PhysicalCores = null,
[property: JsonPropertyName("logicalCores")] int? LogicalCores = null,
[property: JsonPropertyName("threadsPerCore")] int? ThreadsPerCore = null,
[property: JsonPropertyName("cpuFrequencyMhz")] double? CpuFrequencyMhz = null,
[property: JsonPropertyName("cpuFlags")] string? CpuFlags = null,
[property: JsonPropertyName("cpuCacheBytes")] long? CpuCacheBytes = null,
[property: JsonPropertyName("containerCpuLimit")] long? ContainerCpuLimit = null,
// Memory inventory
[property: JsonPropertyName("memTotalBytes")] long? MemTotalBytes = null,
[property: JsonPropertyName("memAvailableBytes")] long? MemAvailableBytes = null,
[property: JsonPropertyName("swapTotalBytes")] long? SwapTotalBytes = null,
[property: JsonPropertyName("swapFreeBytes")] long? SwapFreeBytes = null,
[property: JsonPropertyName("containerMemoryLimitBytes")] long? ContainerMemoryLimitBytes = null,
// Disk inventory
[property: JsonPropertyName("diskInventoryJson")] string? DiskInventoryJson = null,
// GPU inventory
[property: JsonPropertyName("gpuInventoryJson")] string? GpuInventoryJson = null,
// Host info
[property: JsonPropertyName("osName")] string? OsName = null,
[property: JsonPropertyName("kernelVersion")] string? KernelVersion = null,
[property: JsonPropertyName("arch")] string? Arch = null,
[property: JsonPropertyName("uptimeMachineSeconds")] long? UptimeMachineSeconds = null,
// Container info
[property: JsonPropertyName("containerId")] string? ContainerId = null,
[property: JsonPropertyName("containerImage")] string? ContainerImage = null,
// Network & Temperature
[property: JsonPropertyName("networkInterfacesJson")] string? NetworkInterfacesJson = null,
[property: JsonPropertyName("temperatureJson")] string? TemperatureJson = null);
@@ -0,0 +1,88 @@
namespace Heimdall.Agent.Services;
/// <summary>
/// Shared cgroup limit readers. Eliminates duplication between
/// <see cref="CpuInfoProvider"/> and <see cref="ContainerInfoProvider"/>.
/// </summary>
internal static class CgroupReader
{
/// <summary>
/// Reads the CPU limit from cgroup v1/v2. Returns the limit as a
/// percentage-based value (e.g. 200 = 2 cores), or null if unlimited.
/// </summary>
public static long? GetCpuLimit()
{
try
{
if (!OperatingSystem.IsLinux()) return null;
// cgroup v2: /sys/fs/cgroup/cpu.max → "max 100000" or "200000 100000"
var cpuMaxPath = "/sys/fs/cgroup/cpu.max";
if (File.Exists(cpuMaxPath))
{
var content = File.ReadAllText(cpuMaxPath).Trim();
var parts = content.Split(' ', StringSplitOptions.RemoveEmptyEntries);
if (parts.Length == 2 && parts[0] != "max" &&
long.TryParse(parts[0], out var quota) &&
long.TryParse(parts[1], out var period) && period > 0)
{
return (long)Math.Ceiling((double)quota / period * 100);
}
}
// cgroup v1: /sys/fs/cgroup/cpu/cpu.cfs_quota_us and cpu.cfs_period_us
var quotaPath = "/sys/fs/cgroup/cpu/cpu.cfs_quota_us";
var periodPath = "/sys/fs/cgroup/cpu/cpu.cfs_period_us";
if (File.Exists(quotaPath) && File.Exists(periodPath))
{
var quotaStr = File.ReadAllText(quotaPath).Trim();
var periodStr = File.ReadAllText(periodPath).Trim();
if (long.TryParse(quotaStr, out var quota) && quota > 0 &&
long.TryParse(periodStr, out var period) && period > 0)
{
return (long)Math.Ceiling((double)quota / period * 100);
}
}
return null;
}
catch
{
return null;
}
}
/// <summary>
/// Reads the memory limit from cgroup v1/v2. Returns bytes, or null if unlimited.
/// </summary>
public static long? GetMemoryLimit()
{
try
{
if (!OperatingSystem.IsLinux()) return null;
// cgroup v2: /sys/fs/cgroup/memory.max
var memMaxPath = "/sys/fs/cgroup/memory.max";
if (File.Exists(memMaxPath))
{
var content = File.ReadAllText(memMaxPath).Trim();
if (content != "max" && long.TryParse(content, out var limit) && limit > 0)
return limit;
}
// cgroup v1: /sys/fs/cgroup/memory/memory.limit_in_bytes
var v1Path = "/sys/fs/cgroup/memory/memory.limit_in_bytes";
if (File.Exists(v1Path))
{
var content = File.ReadAllText(v1Path).Trim();
if (long.TryParse(content, out var limit) && limit > 0 &&
limit < long.MaxValue / 2) // sanity: ignore unlimited
{
return limit;
}
}
}
catch { /* best effort */ }
return null;
}
}
@@ -0,0 +1,46 @@
using System.Diagnostics;
namespace Heimdall.Agent.Services;
/// <summary>
/// Shared utility for running external commands. Eliminates duplication
/// across GpuInventoryProvider, HostInfoProvider, and other providers.
/// </summary>
internal static class CommandRunner
{
/// <summary>
/// Runs an external command and returns its standard output.
/// Returns null on failure or timeout.
/// </summary>
public static string? Run(string command, string arguments, int timeoutMs = 5000)
{
try
{
using var process = Process.Start(new ProcessStartInfo
{
FileName = command,
Arguments = arguments,
RedirectStandardOutput = true,
RedirectStandardError = true,
UseShellExecute = false,
CreateNoWindow = true
});
if (process is null) return null;
var outputTask = process.StandardOutput.ReadToEndAsync();
if (!process.WaitForExit(timeoutMs))
{
try { process.Kill(); } catch { /* best effort */ }
return null;
}
return outputTask.IsCompletedSuccessfully ? outputTask.Result : null;
}
catch
{
return null;
}
}
}
@@ -0,0 +1,136 @@
namespace Heimdall.Agent.Services;
/// <summary>
/// Detects container environment (Docker, Podman, etc.) and reads cgroup limits.
/// </summary>
public sealed class ContainerInfoProvider
{
private const string ProcEnvironPath = "/proc/1/environ";
private const string Proc1CgroupPath = "/proc/1/cgroup";
private const string ProcSelfCgroupPath = "/proc/self/cgroup";
public ContainerInfo Collect()
{
var isContainer = DetectContainer();
return new ContainerInfo
{
IsContainer = isContainer,
ContainerId = isContainer ? GetContainerId() : null,
ContainerImage = isContainer ? GetContainerImage() : null,
MemoryLimitBytes = CgroupReader.GetMemoryLimit(),
CpuLimit = CgroupReader.GetCpuLimit()
};
}
private static bool DetectContainer()
{
try
{
if (File.Exists("/.dockerenv") || File.Exists("/run/.containerenv"))
return true;
if (DetectFromCgroup() || DetectFromEnviron())
return true;
}
catch { /* best effort */ }
return false;
}
private static bool DetectFromCgroup()
{
if (!File.Exists(Proc1CgroupPath)) return false;
var cgroupContent = File.ReadAllText(Proc1CgroupPath);
return cgroupContent.Contains("docker", StringComparison.OrdinalIgnoreCase) ||
cgroupContent.Contains("containerd", StringComparison.OrdinalIgnoreCase) ||
cgroupContent.Contains("kubepods", StringComparison.OrdinalIgnoreCase) ||
cgroupContent.Contains("lxc", StringComparison.OrdinalIgnoreCase) ||
cgroupContent.Contains("podman", StringComparison.OrdinalIgnoreCase);
}
private static bool DetectFromEnviron()
{
if (!File.Exists(ProcEnvironPath)) return false;
var environ = File.ReadAllText(ProcEnvironPath);
return environ.Contains("container=docker", StringComparison.OrdinalIgnoreCase) ||
environ.Contains("container=podman", StringComparison.OrdinalIgnoreCase);
}
private static string? GetContainerId()
{
try
{
var id = GetContainerIdFromCgroup();
if (id is not null) return id;
// Try hostname (Docker sets container ID as hostname)
var hostname = Environment.MachineName;
if (hostname.Length >= 12 && hostname.All(c => "0123456789abcdef".Contains(c)))
return hostname[..12];
}
catch { /* best effort */ }
return null;
}
private static string? GetContainerIdFromCgroup()
{
if (!File.Exists(ProcSelfCgroupPath)) return null;
foreach (var line in File.ReadLines(ProcSelfCgroupPath))
{
var parts = line.Split(':', StringSplitOptions.RemoveEmptyEntries);
if (parts.Length < 3) continue;
var segments = parts[2].Split('/', StringSplitOptions.RemoveEmptyEntries);
var lastSegment = segments.LastOrDefault();
if (lastSegment is { Length: >= 12 } && lastSegment.All(c => "0123456789abcdef".Contains(c)))
return lastSegment[..Math.Min(12, lastSegment.Length)];
}
return null;
}
private static string? GetContainerImage()
{
try
{
var envImage = Environment.GetEnvironmentVariable("DOCKER_IMAGE")
?? Environment.GetEnvironmentVariable("CONTAINER_IMAGE");
if (!string.IsNullOrWhiteSpace(envImage))
return envImage;
return ReadImageFromEnviron();
}
catch { /* best effort */ }
return null;
}
private static string? ReadImageFromEnviron()
{
if (!File.Exists(ProcEnvironPath)) return null;
var environ = File.ReadAllText(ProcEnvironPath);
foreach (var pair in environ.Split('\0'))
{
if (pair.StartsWith("DOCKER_IMAGE=", StringComparison.OrdinalIgnoreCase))
return pair["DOCKER_IMAGE=".Length..];
if (pair.StartsWith("IMAGE_NAME=", StringComparison.OrdinalIgnoreCase))
return pair["IMAGE_NAME=".Length..];
}
return null;
}
}
/// <summary>
/// Container environment information.
/// </summary>
public sealed record ContainerInfo
{
public bool IsContainer { get; init; }
public string? ContainerId { get; init; }
public string? ContainerImage { get; init; }
public long? MemoryLimitBytes { get; init; }
public long? CpuLimit { get; init; }
}
@@ -0,0 +1,204 @@
using System.Runtime.InteropServices;
using System.Text.RegularExpressions;
namespace Heimdall.Agent.Services;
/// <summary>
/// Collects CPU inventory information from /proc/cpuinfo, topology, and cgroup limits.
/// </summary>
public sealed partial class CpuInfoProvider
{
public CpuInfo Collect()
{
var info = ParseProcCpuinfo();
var topology = GetTopology();
return new CpuInfo
{
Vendor = info.GetValueOrDefault("vendor_id"),
Model = info.GetValueOrDefault("model name"),
Architecture = GetArchitecture(),
PhysicalCores = topology.PhysicalCores,
LogicalCores = topology.LogicalCores,
ThreadsPerCore = topology.ThreadsPerCore,
FrequencyMhz = ParseFrequency(info.GetValueOrDefault("cpu MHz")),
Flags = FilterKeyFlags(info.GetValueOrDefault("flags") ?? info.GetValueOrDefault("Features") ?? ""),
CacheBytes = GetCacheSize(),
ContainerCpuLimit = CgroupReader.GetCpuLimit()
};
}
private static Dictionary<string, string> ParseProcCpuinfo()
{
var result = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
try
{
if (!File.Exists("/proc/cpuinfo"))
return result;
foreach (var line in File.ReadLines("/proc/cpuinfo"))
{
var idx = line.IndexOf(':');
if (idx <= 0) continue;
var key = line[..idx].Trim();
var value = line[(idx + 1)..].Trim();
if (!result.ContainsKey(key))
result[key] = value;
}
}
catch { /* best effort */ }
return result;
}
private static (int? PhysicalCores, int? LogicalCores, int? ThreadsPerCore) GetTopology()
{
try
{
if (!OperatingSystem.IsLinux())
return (null, Environment.ProcessorCount, null);
var logicalCount = Environment.ProcessorCount;
var physicalCores = CountPhysicalCores();
var threadsPerCore = physicalCores is > 0 ? (int?)(logicalCount / physicalCores.Value) : null;
return (physicalCores, logicalCount, threadsPerCore);
}
catch
{
return (null, Environment.ProcessorCount, null);
}
}
private static int? CountPhysicalCores()
{
var physicalEntries = new HashSet<string>();
var cpuDirs = Directory.GetDirectories("/sys/devices/system/cpu")
.Where(d => CoreDirPattern().IsMatch(Path.GetFileName(d)));
foreach (var cpuDir in cpuDirs)
{
var physicalIdPath = Path.Combine(cpuDir, "topology", "physical_package_id");
var coreIdPath = Path.Combine(cpuDir, "topology", "core_id");
if (File.Exists(physicalIdPath) && File.Exists(coreIdPath))
{
var physId = File.ReadAllText(physicalIdPath).Trim();
var coreId = File.ReadAllText(coreIdPath).Trim();
physicalEntries.Add($"{physId}:{coreId}");
}
}
return physicalEntries.Count > 0 ? physicalEntries.Count : null;
}
[GeneratedRegex(@"^cpu\d+$")]
private static partial Regex CoreDirPattern();
private static string? GetArchitecture()
{
try
{
if (File.Exists("/proc/version"))
{
var version = File.ReadAllText("/proc/version");
if (version.Contains("x86_64", StringComparison.OrdinalIgnoreCase) ||
version.Contains("amd64", StringComparison.OrdinalIgnoreCase))
return "x86_64";
if (version.Contains("aarch64", StringComparison.OrdinalIgnoreCase) ||
version.Contains("arm64", StringComparison.OrdinalIgnoreCase))
return "aarch64";
}
return RuntimeInformation.ProcessArchitecture switch
{
Architecture.X64 => "x86_64",
Architecture.Arm64 => "aarch64",
Architecture.Arm => "armv7l",
_ => null
};
}
catch
{
return null;
}
}
private static double? ParseFrequency(string? mhzStr)
{
if (string.IsNullOrWhiteSpace(mhzStr)) return null;
if (double.TryParse(mhzStr, System.Globalization.NumberStyles.Float,
System.Globalization.CultureInfo.InvariantCulture, out var mhz))
return Math.Round(mhz, 1);
return null;
}
/// <summary>
/// Filters CPU flags to only include key modern instruction set flags.
/// </summary>
private static string FilterKeyFlags(string allFlags)
{
if (string.IsNullOrWhiteSpace(allFlags)) return "";
string[] keyFlags = ["avx", "avx2", "fma", "avx512f", "avx512bw", "avx512dq",
"avx512vl", "sse4_1", "sse4_2", "ssse3", "aes", "pclmulqdq",
"sha_ni", "sse2"];
var flags = allFlags.Split(' ', StringSplitOptions.RemoveEmptyEntries);
var matched = flags.Where(f => keyFlags.Contains(f, StringComparer.OrdinalIgnoreCase));
return string.Join(',', matched);
}
private static long? GetCacheSize()
{
try
{
if (!OperatingSystem.IsLinux()) return null;
var cacheDir = "/sys/devices/system/cpu/cpu0/cache";
if (!Directory.Exists(cacheDir)) return null;
long totalBytes = 0;
foreach (var indexDir in Directory.GetDirectories(cacheDir))
{
var levelPath = Path.Combine(indexDir, "level");
var sizePath = Path.Combine(indexDir, "size");
var typePath = Path.Combine(indexDir, "type");
if (!File.Exists(levelPath) || !File.Exists(sizePath)) continue;
var level = File.ReadAllText(levelPath).Trim();
var sizeStr = File.ReadAllText(sizePath).Trim();
var type = File.Exists(typePath) ? File.ReadAllText(typePath).Trim() : "";
// Only sum unified or data caches per level to avoid double counting
if (type == "Instruction" && level == "1") continue;
if (long.TryParse(sizeStr.Replace("K", "").Replace("k", ""), out var kb))
totalBytes += kb * 1024;
}
return totalBytes > 0 ? totalBytes : null;
}
catch
{
return null;
}
}
}
/// <summary>
/// CPU inventory data collected from the system.
/// </summary>
public sealed record CpuInfo
{
public string? Vendor { get; init; }
public string? Model { get; init; }
public string? Architecture { get; init; }
public int? PhysicalCores { get; init; }
public int? LogicalCores { get; init; }
public int? ThreadsPerCore { get; init; }
public double? FrequencyMhz { get; init; }
public string? Flags { get; init; }
public long? CacheBytes { get; init; }
public long? ContainerCpuLimit { get; init; }
}
@@ -0,0 +1,160 @@
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";
}
@@ -3,9 +3,7 @@ using System.Threading.Channels;
using Microsoft.Extensions.Logging;
using Microsoft.ML.OnnxRuntime;
using Microsoft.ML.OnnxRuntime.Tensors;
using SixLabors.ImageSharp;
using SixLabors.ImageSharp.PixelFormats;
using SixLabors.ImageSharp.Processing;
using ImageMagick;
namespace Heimdall.Agent.Services;
@@ -94,7 +92,7 @@ public sealed class FrameAnalyzerService : IDisposable
// Determine number of classes from output shape [1, 4+C, 8400]
var outputMeta = _session.OutputMetadata.Values.ToArray()[0];
_numClasses = outputMeta.Dimensions.Length >= 2 ? (int)outputMeta.Dimensions[1] - 4 : 80;
_numClasses = outputMeta.Dimensions.Length >= 2 ? outputMeta.Dimensions[1] - 4 : 80;
_logger.LogInformation(
"FrameAnalyzer initialized with model: {ModelPath} (input: {InputName}, classes: {Classes})",
@@ -204,10 +202,11 @@ public sealed class FrameAnalyzerService : IDisposable
if (_session is null)
return [];
using var image = Image.Load<Rgb24>(jpegData);
using var image = new MagickImage(jpegData);
image.Format = MagickFormat.Jpeg;
// Resize to model input size (640×640)
image.Mutate(x => x.Resize(InputSize, InputSize));
// Resize to model input size (640×640), ignoring aspect ratio (like ImageSharp Resize(640,640))
image.Resize(new MagickGeometry(InputSize, InputSize) { IgnoreAspectRatio = true });
var inputTensor = PreprocessImage(image);
@@ -219,32 +218,29 @@ public sealed class FrameAnalyzerService : IDisposable
using var results = _session.Run(inputs);
var output = results[0].AsTensor<float>().ToArray();
return ParseYoloOutput(output, image.Width, image.Height);
return ParseYoloOutput(output, (int)image.Width, (int)image.Height);
}
/// <summary>
/// Convert ImageSharp image to a normalized NCHW tensor [1, 3, 640, 640].
/// Convert Magick.NET image to a normalized NCHW tensor [1, 3, 640, 640].
/// YOLOv8 expects RGB channels, each normalized to [0, 1].
/// </summary>
private static DenseTensor<float> PreprocessImage(Image<Rgb24> image)
private static DenseTensor<float> PreprocessImage(MagickImage image)
{
var tensor = new DenseTensor<float>([1, 3, InputSize, InputSize]);
var width = image.Width;
// GetPixels().ToArray() returns contiguous interleaved RGB channel values
// (Q16 build => ushort ranging 0..65535), row-major.
var rgb = image.GetPixels()?.ToArray() ?? [];
image.ProcessPixelRows(accessor =>
var idx = 0;
for (var y = 0; y < InputSize; y++)
{
for (var y = 0; y < accessor.Height; y++)
for (var x = 0; x < InputSize; x++)
{
var pixelRow = accessor.GetRowSpan(y);
for (var x = 0; x < pixelRow.Length; x++)
{
var pixel = pixelRow[x];
tensor[0, 0, y, x] = pixel.R / 255f;
tensor[0, 1, y, x] = pixel.G / 255f;
tensor[0, 2, y, x] = pixel.B / 255f;
}
for (var c = 0; c < 3; c++)
tensor[0, c, y, x] = rgb[idx++] / 65535f;
}
});
}
return tensor;
}
@@ -329,21 +325,30 @@ public sealed class FrameAnalyzerService : IDisposable
Height: best.Y2 - best.Y1,
ClassIndex: best.ClassIdx));
// Suppress overlapping boxes of the same class
for (var j = i + 1; j < candidates.Count; j++)
{
if (suppressed[j]) continue;
if (candidates[j].ClassIdx != best.ClassIdx) continue;
var iou = ComputeIoU(best, candidates[j]);
if (iou >= NmsIouThreshold)
suppressed[j] = true;
}
SuppressOverlapping(candidates, suppressed, i, best);
}
return results.ToArray();
}
/// <summary>
/// Mark overlapping candidates of the same class as suppressed.
/// Extracted from ApplyNms to reduce cognitive complexity (S3776).
/// </summary>
private static void SuppressOverlapping(
List<RawDetection> candidates, bool[] suppressed, int index, RawDetection best)
{
for (var j = index + 1; j < candidates.Count; j++)
{
if (suppressed[j]) continue;
if (candidates[j].ClassIdx != best.ClassIdx) continue;
var iou = ComputeIoU(best, candidates[j]);
if (iou >= NmsIouThreshold)
suppressed[j] = true;
}
}
private static float ComputeIoU(RawDetection a, RawDetection b)
{
var interX1 = Math.Max(a.X1, b.X1);
@@ -0,0 +1,296 @@
using System.Text.Json;
using System.Text.RegularExpressions;
namespace Heimdall.Agent.Services;
/// <summary>
/// Collects GPU inventory information via nvidia-smi, sysfs DRM, vainfo, and rocm-smi.
/// Supports multi-GPU configurations.
/// </summary>
public sealed partial class GpuInventoryProvider
{
// SonarQube S1118: prevent instantiation — all members are static.
private GpuInventoryProvider() { }
private const string DeviceDir = "device";
public static IReadOnlyList<GpuInfo> Collect()
{
var gpus = CollectNvidiaSmi();
if (gpus.Count == 0)
{
gpus = CollectDrmDevices();
}
EnrichWithVaapiInfo(gpus);
var rocmGpus = CollectRocmSmi();
foreach (var rocm in rocmGpus.Where(rocm => !gpus.Any(g => g.Model?.Contains(rocm.Model ?? "", StringComparison.OrdinalIgnoreCase) == true)))
{
gpus.Add(rocm);
}
return gpus;
}
private static List<GpuInfo> CollectNvidiaSmi()
{
var gpus = new List<GpuInfo>();
try
{
var output = CommandRunner.Run("nvidia-smi",
"--query-gpu=index,name,driver_version,memory.total,memory.used,temperature.gpu,utilization.gpu --format=csv,noheader,nounits");
if (string.IsNullOrWhiteSpace(output)) return gpus;
foreach (var line in output.Split('\n', StringSplitOptions.RemoveEmptyEntries))
{
var parts = line.Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries);
if (parts.Length < 7) continue;
if (!long.TryParse(parts[3], out var vramMb)) vramMb = 0;
double.TryParse(parts[5], System.Globalization.NumberStyles.Float,
System.Globalization.CultureInfo.InvariantCulture, out var temp);
double.TryParse(parts[6], System.Globalization.NumberStyles.Float,
System.Globalization.CultureInfo.InvariantCulture, out var util);
gpus.Add(new GpuInfo
{
Vendor = "Nvidia",
Model = parts[1],
VramBytes = vramMb * 1024 * 1024,
DriverVersion = parts[2],
TemperatureCelsius = temp,
UtilizationPercent = util,
Backend = "Cuda",
EncoderSupport = DetectNvidiaEncoder()
});
}
}
catch { /* best effort */ }
return gpus;
}
private static string? DetectNvidiaEncoder()
{
try
{
var output = CommandRunner.Run("nvidia-smi", "-q --format=csv,noheader");
if (output is null) return null;
if (output.Contains("NVENC", StringComparison.OrdinalIgnoreCase))
return output.Contains("NVJPG", StringComparison.OrdinalIgnoreCase) ? "NVENC+NVJPG" : "NVENC";
return null;
}
catch { return null; }
}
private static List<GpuInfo> CollectDrmDevices()
{
var gpus = new List<GpuInfo>();
try
{
if (!OperatingSystem.IsLinux() || !Directory.Exists("/sys/class/drm"))
return gpus;
foreach (var cardDir in Directory.GetDirectories("/sys/class/drm"))
{
var name = Path.GetFileName(cardDir);
if (!name.StartsWith("card", StringComparison.Ordinal) || name.Contains('-'))
continue;
var vendorPath = Path.Combine(cardDir, DeviceDir, "vendor");
if (!File.Exists(vendorPath)) continue;
var vendor = File.ReadAllText(vendorPath).Trim();
var model = GetDrmCardModel(cardDir);
gpus.Add(new GpuInfo
{
Vendor = MapVendor(vendor),
Model = model,
Backend = MapBackend(vendor)
});
}
}
catch { /* best effort */ }
return gpus;
}
private static string MapVendor(string vendor) => vendor switch
{
"0x10de" => "Nvidia",
"0x1002" => "AMD",
"0x8086" => "Intel",
_ => vendor
};
private static string MapBackend(string vendor) => vendor switch
{
"0x10de" => "Cuda",
"0x1002" => "ROCm",
"0x8086" => "VAAPI",
_ => "Unknown"
};
private static string? GetDrmCardModel(string cardDir)
{
try
{
var ueventPath = Path.Combine(cardDir, DeviceDir, "uevent");
if (!File.Exists(ueventPath)) return null;
return ReadPciModelFromUevent(ueventPath);
}
catch { /* best effort */ }
return null;
}
private static string? ReadPciModelFromUevent(string ueventPath)
{
foreach (var line in File.ReadLines(ueventPath))
{
if (!line.StartsWith("PCI_ID=", StringComparison.OrdinalIgnoreCase)) continue;
var pciId = line["PCI_ID=".Length..].Trim();
var output = CommandRunner.Run("lspci", $"-d {pciId} -mm");
if (!string.IsNullOrWhiteSpace(output))
{
var modelName = ParsePciLspciOutput(output);
if (!string.IsNullOrWhiteSpace(modelName))
return modelName;
}
}
return null;
}
private static void EnrichWithVaapiInfo(List<GpuInfo> gpus)
{
try
{
if (!OperatingSystem.IsLinux()) return;
var output = CommandRunner.Run("vainfo", "");
if (string.IsNullOrWhiteSpace(output)) return;
if (!output.Contains("VAProfile", StringComparison.OrdinalIgnoreCase)) return;
// Reject software renderers (llvmpipe, swrast) — these are Mesa fallbacks, not real GPUs
if (output.Contains("llvmpipe", StringComparison.OrdinalIgnoreCase) ||
output.Contains("swrast", StringComparison.OrdinalIgnoreCase))
return;
// If no GPU was found but vainfo works with a real driver, report it
if (gpus.Count == 0)
{
gpus.Add(new GpuInfo
{
Vendor = "Intel",
Model = "VAAPI Renderer",
Backend = "VAAPI"
});
}
}
catch { /* best effort */ }
}
private static List<GpuInfo> CollectRocmSmi()
{
var gpus = new List<GpuInfo>();
try
{
var output = CommandRunner.Run("rocm-smi",
"--showid --showtemp --showmemuse --showproductname --showuse --csv");
if (string.IsNullOrWhiteSpace(output)) return gpus;
var lines = output.Split('\n', StringSplitOptions.RemoveEmptyEntries);
if (lines.Length < 2) return gpus;
var headers = lines[0].Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries);
for (int i = 1; i < lines.Length; i++)
{
var values = lines[i].Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries);
if (values.Length < 2) continue;
var gpuInfo = ParseRocmLine(headers, values);
if (gpuInfo is not null) gpus.Add(gpuInfo);
}
}
catch { /* best effort */ }
return gpus;
}
private static GpuInfo? ParseRocmLine(string[] headers, string[] values)
{
string? gpuModel = null;
double? gpuTemp = null;
double? gpuUtil = null;
for (int j = 0; j < Math.Min(headers.Length, values.Length); j++)
{
var header = headers[j].ToLowerInvariant();
var value = values[j];
if (header.Contains("name") || header.Contains("card"))
gpuModel = value;
else if (header.Contains("temp"))
gpuTemp = TryParseTemperature(value);
else if (header.Contains("use"))
gpuUtil = TryParsePercent(value);
}
return gpuModel is not null ? new GpuInfo
{
Vendor = "AMD",
Model = gpuModel,
Backend = "ROCm",
TemperatureCelsius = gpuTemp,
UtilizationPercent = gpuUtil
} : null;
}
private static double? TryParseTemperature(string value)
{
double.TryParse(value.Replace("c", "").Replace("C", "").Trim(),
System.Globalization.NumberStyles.Float,
System.Globalization.CultureInfo.InvariantCulture, out var t);
return t > 0 ? t : null;
}
private static double? TryParsePercent(string value)
{
double.TryParse(value.Replace("%", "").Trim(),
System.Globalization.NumberStyles.Float,
System.Globalization.CultureInfo.InvariantCulture,
out var util);
return util;
}
private static string? ParsePciLspciOutput(string output)
{
// lspci -mm output format: "vendor" "device" "class" "rev"
var match = PciLspciPattern().Match(output);
if (match.Success)
return match.Groups[2].Value.Trim();
return output.Split('\n', StringSplitOptions.RemoveEmptyEntries).FirstOrDefault()?.Trim().Trim('"');
}
[GeneratedRegex(@"""([^""]+)""\s+""([^""]+)""")]
private static partial Regex PciLspciPattern();
}
/// <summary>
/// GPU inventory data for a single GPU device.
/// </summary>
public sealed record GpuInfo
{
public string? Vendor { get; init; }
public string? Model { get; init; }
public long? VramBytes { get; init; }
public string? DriverVersion { get; init; }
public double? TemperatureCelsius { get; init; }
public double? UtilizationPercent { get; init; }
public string? Backend { get; init; }
public string? EncoderSupport { get; init; }
}
@@ -0,0 +1,291 @@
using System.Diagnostics;
using System.Net.NetworkInformation;
namespace Heimdall.Agent.Services;
/// <summary>
/// Collects host information: OS, kernel, uptime, network interfaces, and temperature.
/// </summary>
public sealed class HostInfoProvider
{
public HostInfo Collect()
{
return new HostInfo
{
OsName = GetOsName(),
KernelVersion = GetKernelVersion(),
Arch = GetArchitecture(),
UptimeSeconds = ProcFs.GetMachineUptime(),
NetworkInterfaces = CollectNetworkInterfaces(),
Temperature = CollectTemperature()
};
}
private static string? GetOsName()
{
try
{
if (OperatingSystem.IsLinux())
return GetLinuxOsName();
if (OperatingSystem.IsWindows())
return Environment.OSVersion.VersionString;
if (OperatingSystem.IsMacOS())
return GetMacOsName();
}
catch { /* best effort */ }
return null;
}
private static string? GetLinuxOsName()
{
var prettyName = ReadPrettyNameFromOsRelease();
if (prettyName is not null)
return prettyName;
var output = CommandRunner.Run("uname", "-sro");
return !string.IsNullOrWhiteSpace(output) ? output.Trim() : null;
}
private static string? ReadPrettyNameFromOsRelease()
{
if (!File.Exists("/etc/os-release")) return null;
return File.ReadLines("/etc/os-release")
.Where(line => line.StartsWith("PRETTY_NAME=", StringComparison.OrdinalIgnoreCase))
.Select(line => line["PRETTY_NAME=".Length..].Trim().Trim('"'))
.FirstOrDefault();
}
private static string? GetMacOsName()
{
var output = CommandRunner.Run("sw_vers", "-productVersion");
return !string.IsNullOrWhiteSpace(output) ? $"macOS {output.Trim()}" : null;
}
private static string? GetKernelVersion()
{
try
{
if (OperatingSystem.IsLinux() || OperatingSystem.IsMacOS())
{
var output = CommandRunner.Run("uname", "-r");
if (!string.IsNullOrWhiteSpace(output))
return output.Trim();
}
else if (OperatingSystem.IsWindows())
{
return Environment.OSVersion.VersionString;
}
}
catch { /* best effort */ }
return null;
}
private static string? GetArchitecture()
{
try
{
return System.Runtime.InteropServices.RuntimeInformation.ProcessArchitecture switch
{
System.Runtime.InteropServices.Architecture.X64 => "x86_64",
System.Runtime.InteropServices.Architecture.Arm64 => "aarch64",
System.Runtime.InteropServices.Architecture.Arm => "armv7l",
_ => System.Runtime.InteropServices.RuntimeInformation.ProcessArchitecture.ToString()
};
}
catch { return null; }
}
private static List<NetworkInterfaceInfo> CollectNetworkInterfaces()
{
var interfaces = new List<NetworkInterfaceInfo>();
try
{
if (OperatingSystem.IsLinux() && File.Exists("/proc/net/dev"))
{
var lines = File.ReadAllLines("/proc/net/dev");
// Skip header lines
foreach (var line in lines.Skip(2))
{
var trimmed = line.Trim();
var colonIdx = trimmed.IndexOf(':');
if (colonIdx <= 0) continue;
var name = trimmed[..colonIdx].Trim();
if (name == "lo") continue; // skip loopback
interfaces.Add(new NetworkInterfaceInfo
{
Name = name,
IpAddress = GetInterfaceIp(name),
MacAddress = GetInterfaceMac(name),
SpeedMbps = GetInterfaceSpeed(name)
});
}
}
else
{
// Fallback: use NetworkInterface API
CollectFallbackInterfaces(interfaces);
}
}
catch { /* best effort */ }
return interfaces;
}
private static void CollectFallbackInterfaces(List<NetworkInterfaceInfo> interfaces)
{
foreach (var ni in NetworkInterface.GetAllNetworkInterfaces())
{
if (ni.OperationalStatus != OperationalStatus.Up) continue;
if (ni.NetworkInterfaceType == NetworkInterfaceType.Loopback) continue;
var ipProps = ni.GetIPProperties();
var ip = ipProps.UnicastAddresses
.FirstOrDefault(a => a.Address.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)
?.Address.ToString();
var mac = ni.GetPhysicalAddress().ToString();
if (!string.IsNullOrEmpty(mac) && mac.Length == 12)
mac = $"{mac[0..2]}:{mac[2..4]}:{mac[4..6]}:{mac[6..8]}:{mac[8..10]}:{mac[10..12]}";
interfaces.Add(new NetworkInterfaceInfo
{
Name = ni.Name,
IpAddress = ip,
MacAddress = string.IsNullOrEmpty(mac) ? null : mac,
SpeedMbps = ni.Speed > 0 ? (long?)ni.Speed / 1_000_000 : null
});
}
}
private static string? GetInterfaceIp(string interfaceName)
{
try
{
var output = CommandRunner.Run("ip", $"-4 addr show {interfaceName}");
if (string.IsNullOrWhiteSpace(output)) return null;
foreach (var line in output.Split('\n'))
{
var trimmed = line.Trim();
if (trimmed.StartsWith("inet ", StringComparison.Ordinal))
{
var parts = trimmed.Split(' ', StringSplitOptions.RemoveEmptyEntries);
if (parts.Length >= 2)
{
var addr = parts[1];
var slashIdx = addr.IndexOf('/');
return slashIdx > 0 ? addr[..slashIdx] : addr;
}
}
}
}
catch { /* best effort */ }
return null;
}
private static string? GetInterfaceMac(string interfaceName)
{
try
{
var path = $"/sys/class/net/{interfaceName}/address";
if (File.Exists(path))
return File.ReadAllText(path).Trim();
}
catch { /* best effort */ }
return null;
}
private static long? GetInterfaceSpeed(string interfaceName)
{
try
{
var path = $"/sys/class/net/{interfaceName}/speed";
if (File.Exists(path))
{
var content = File.ReadAllText(path).Trim();
if (long.TryParse(content, out var speed) && speed > 0)
return speed;
}
}
catch { /* best effort */ }
return null;
}
private static List<TemperatureInfo> CollectTemperature()
{
var temps = new List<TemperatureInfo>();
try
{
if (!OperatingSystem.IsLinux()) return temps;
var thermalDir = "/sys/class/thermal";
if (!Directory.Exists(thermalDir)) return temps;
foreach (var zoneDir in Directory.GetDirectories(thermalDir))
{
if (!Path.GetFileName(zoneDir).StartsWith("thermal_zone", StringComparison.Ordinal))
continue;
var tempPath = Path.Combine(zoneDir, "temp");
if (!File.Exists(tempPath)) continue;
var typePath = Path.Combine(zoneDir, "type");
var zoneName = File.Exists(typePath) ? File.ReadAllText(typePath).Trim() : Path.GetFileName(zoneDir);
var tempStr = File.ReadAllText(tempPath).Trim();
if (TryParseMillidegrees(tempStr, out var tempCelsius) && tempCelsius is > -40 and < 200)
{
temps.Add(new TemperatureInfo
{
Zone = zoneName,
TemperatureCelsius = Math.Round(tempCelsius, 1)
});
}
}
}
catch { /* best effort */ }
return temps;
}
private static bool TryParseMillidegrees(string tempStr, out double celsius)
{
celsius = 0;
if (!long.TryParse(tempStr, out var millidegrees)) return false;
celsius = millidegrees / 1000.0;
return true;
}
}
/// <summary>
/// Host information data.
/// </summary>
public sealed record HostInfo
{
public string? OsName { get; init; }
public string? KernelVersion { get; init; }
public string? Arch { get; init; }
public long? UptimeSeconds { get; init; }
public List<NetworkInterfaceInfo> NetworkInterfaces { get; init; } = [];
public List<TemperatureInfo> Temperature { get; init; } = [];
}
/// <summary>
/// Network interface information.
/// </summary>
public sealed record NetworkInterfaceInfo
{
public string Name { get; init; } = "";
public string? IpAddress { get; init; }
public string? MacAddress { get; init; }
public long? SpeedMbps { get; init; }
}
/// <summary>
/// Thermal zone temperature information.
/// </summary>
public sealed record TemperatureInfo
{
public string Zone { get; init; } = "";
public double TemperatureCelsius { get; init; }
}
@@ -110,7 +110,7 @@ public class LogUploadService : BackgroundService
}
catch (Exception ex)
{
_logger.LogDebug("Log upload failed (network): {Error}; {Count} entries re-queued", ex.Message, entries.Count);
_logger.LogDebug(ex, "Log upload failed (network): {Count} entries re-queued", entries.Count);
_buffer.Requeue(entries);
}
}
@@ -0,0 +1,39 @@
namespace Heimdall.Agent.Services;
/// <summary>
/// Shared memory info reader from /proc/meminfo. Eliminates duplication
/// in <see cref="AgentRegistrationService"/> (GetMemoryTotal, GetMemoryAvailable,
/// GetSwapTotal, GetSwapFree are all the same pattern).
/// </summary>
internal static class MemoryReader
{
private const string ProcMeminfoPath = "/proc/meminfo";
/// <summary>
/// Reads a named field from /proc/meminfo and returns its value in bytes.
/// Returns null if the field is not found or parsing fails.
/// </summary>
public static long? ReadFieldBytes(string fieldName)
{
try
{
if (!OperatingSystem.IsLinux()) return null;
var line = File.ReadLines(ProcMeminfoPath)
.FirstOrDefault(l => l.StartsWith($"{fieldName}:", StringComparison.Ordinal));
if (line is not null)
{
var parts = line.Split(' ', StringSplitOptions.RemoveEmptyEntries);
if (parts.Length >= 2 && long.TryParse(parts[1], out var kb))
return kb * 1024;
}
}
catch { /* best effort */ }
return null;
}
public static long? GetMemoryTotal() => ReadFieldBytes("MemTotal");
public static long? GetMemoryAvailable() => ReadFieldBytes("MemAvailable");
public static long? GetSwapTotal() => ReadFieldBytes("SwapTotal");
public static long? GetSwapFree() => ReadFieldBytes("SwapFree");
}
@@ -1484,7 +1484,7 @@ public sealed class NetworkCameraScanner
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(ScreenshotTimeout, ct)).ConfigureAwait(false);
if (completed != copyTask)
+33
View File
@@ -0,0 +1,33 @@
namespace Heimdall.Agent.Services;
/// <summary>
/// Shared utilities for reading Linux proc filesystem values.
/// </summary>
internal static class ProcFs
{
/// <summary>
/// Gets machine uptime in seconds from /proc/uptime.
/// </summary>
public static long? GetMachineUptime()
{
try
{
if (OperatingSystem.IsLinux() && File.Exists("/proc/uptime"))
{
var content = File.ReadAllText("/proc/uptime").Trim();
var spaceIdx = content.IndexOf(' ');
if (spaceIdx > 0)
{
var uptimeStr = content[..spaceIdx];
if (double.TryParse(uptimeStr, System.Globalization.NumberStyles.Float,
System.Globalization.CultureInfo.InvariantCulture, out var uptime))
{
return (long)uptime;
}
}
}
}
catch { /* best effort */ }
return null;
}
}
@@ -22,16 +22,12 @@ public sealed class RuntimeLogLevel
{
private readonly ILoggerFactory _loggerFactory;
private readonly LoggerFilterOptions _filterOptions;
private readonly IReadOnlyList<LoggerFilterRule> _originalRules;
private LoggerFilterRule? _currentRule;
public RuntimeLogLevel(ILoggerFactory loggerFactory, IOptions<LoggerFilterOptions> filterOptions)
{
_loggerFactory = loggerFactory;
_filterOptions = filterOptions.Value;
// Snapshot the rules configured at startup (appsettings "Logging:LogLevel")
// so they can be restored after the live global rule is removed.
_originalRules = _filterOptions.Rules.ToList();
}
/// <summary>Current minimum level applied to all loggers.</summary>
@@ -113,14 +113,14 @@ public sealed class SnapshotPipelineService : BackgroundService
.ToList();
// Stop streams for cameras no longer assigned/disabled.
foreach (var activeId in _streams.ActiveCameraIds)
var toStop = _streams.ActiveCameraIds
.Where(activeId => !desired.Any(c => c.CameraId == activeId))
.ToList();
foreach (var activeId in toStop)
{
if (!desired.Any(c => c.CameraId == activeId))
{
await _streams.StopStreamAsync(activeId);
// Camera removed/disabled → Disabled status at the Central.
await _statusReporter.ReportAsync(activeId, "Disabled", ct);
}
await _streams.StopStreamAsync(activeId);
// Camera removed/disabled → Disabled status at the Central.
await _statusReporter.ReportAsync(activeId, "Disabled", ct);
}
// Start streams for newly assigned cameras.
@@ -24,7 +24,8 @@ public sealed class SystemMetricsProvider
MemoryUsageBytes = Process.GetCurrentProcess().WorkingSet64,
TotalMemoryBytes = GetTotalMemory(),
DiskUsagePercent = GetDiskUsage(),
UptimeSeconds = (long)(DateTime.UtcNow - ProcessStart).TotalSeconds
UptimeSeconds = (long)(DateTime.UtcNow - ProcessStart).TotalSeconds,
MachineUptimeSeconds = ProcFs.GetMachineUptime()
};
}
@@ -151,6 +152,8 @@ public sealed class SystemMetricsProvider
return null;
}
}
}
public sealed record SystemMetrics
@@ -160,6 +163,7 @@ public sealed record SystemMetrics
public long? TotalMemoryBytes { get; init; }
public double? DiskUsagePercent { get; init; }
public long? UptimeSeconds { get; init; }
public long? MachineUptimeSeconds { get; init; }
}
/// <summary>
@@ -182,8 +186,9 @@ internal static class SystemInfo
});
if (proc is null) return 0;
var output = proc.StandardOutput.ReadToEnd();
var outputTask = proc.StandardOutput.ReadToEndAsync();
proc.WaitForExit(1000);
var output = outputTask.IsCompletedSuccessfully ? outputTask.Result : null;
return long.TryParse(output?.Trim(), out var mem) ? mem : 0;
}
catch
@@ -13,10 +13,10 @@ public class SubmitAgentLogsHandler : IRequestHandler<SubmitAgentLogsCommand, Se
public SubmitAgentLogsHandler(IApplicationDbContext db) => _db = db;
public async Task<ServiceResult> Handle(SubmitAgentLogsCommand request, CancellationToken ct)
public async Task<ServiceResult> Handle(SubmitAgentLogsCommand request, CancellationToken cancellationToken)
{
var agentExists = await _db.Agents
.AnyAsync(a => a.Id == request.AgentId, ct)
.AnyAsync(a => a.Id == request.AgentId, cancellationToken)
.ConfigureAwait(false);
if (!agentExists)
return ServiceResult.NotFound("Agent not found");
@@ -56,7 +56,7 @@ public class SubmitAgentLogsHandler : IRequestHandler<SubmitAgentLogsCommand, Se
foreach (var entry in entries)
_db.AgentLogEntries.Add(entry);
await _db.SaveChangesWithRetryAsync(ct: ct).ConfigureAwait(false);
await _db.SaveChangesWithRetryAsync(ct: cancellationToken).ConfigureAwait(false);
return ServiceResult.Success();
}
@@ -13,7 +13,7 @@ public class GetAgentLogsHandler : IRequestHandler<GetAgentLogsQuery, ServiceRes
public GetAgentLogsHandler(IApplicationDbContext db) => _db = db;
public async Task<ServiceResult<PagedResult<AgentLogEntryDto>>> Handle(GetAgentLogsQuery request, CancellationToken ct)
public async Task<ServiceResult<PagedResult<AgentLogEntryDto>>> Handle(GetAgentLogsQuery request, CancellationToken cancellationToken)
{
var query = _db.AgentLogEntries.Where(e => e.AgentId == request.AgentId);
@@ -37,7 +37,7 @@ public class GetAgentLogsHandler : IRequestHandler<GetAgentLogsQuery, ServiceRes
|| (e.Source != null && e.Source.Contains(search, StringComparison.OrdinalIgnoreCase)));
}
var total = await query.CountAsync(ct).ConfigureAwait(false);
var total = await query.CountAsync(cancellationToken).ConfigureAwait(false);
var items = await query
.OrderByDescending(e => e.TimestampUtc)
@@ -51,7 +51,7 @@ public class GetAgentLogsHandler : IRequestHandler<GetAgentLogsQuery, ServiceRes
e.Message,
e.Exception,
e.Source))
.ToListAsync(ct)
.ToListAsync(cancellationToken)
.ConfigureAwait(false);
return ServiceResult<PagedResult<AgentLogEntryDto>>.Success(
@@ -0,0 +1,33 @@
using Heimdall.Application.DTOs;
using Heimdall.Domain.Entities;
namespace Heimdall.Application.Agents;
/// <summary>
/// Extension methods to map <see cref="Agent"/> entity to <see cref="AgentResponse"/> DTO.
/// Centralizes the mapping used across GetAllAgents, GetAgentsBySite, and GetAgent queries.
/// </summary>
public static class AgentExtensions
{
public static AgentResponse ToResponse(this Agent a) => new(
a.Id, a.SiteId, a.Site?.Name ?? string.Empty, a.Name, a.Hostname, a.Version, a.Status,
a.LastHeartbeat, a.PublicIp, a.HasGpu, a.CpuCores, a.MemoryMb,
a.GpuType.ToString(), a.CreatedAt,
a.CpuUsagePercent, a.MemoryUsageBytes, a.DiskUsagePercent, a.UptimeSeconds,
// CPU inventory
a.CpuVendor, a.CpuModel, a.CpuArchitecture,
a.PhysicalCores, a.LogicalCores, a.ThreadsPerCore,
a.CpuFrequencyMhz, a.CpuFlags, a.CpuCacheBytes, a.ContainerCpuLimit,
// Memory inventory
a.MemTotalBytes, a.MemAvailableBytes, a.SwapTotalBytes, a.SwapFreeBytes,
a.ContainerMemoryLimitBytes,
// Disk inventory
a.DiskInventoryJson,
// GPU inventory
a.GpuInventoryJson,
// Host info
a.OsName, a.KernelVersion, a.Arch, a.UptimeMachineSeconds,
// Container info
a.ContainerId, a.ContainerImage,
// Network & Temperature
a.NetworkInterfacesJson, a.TemperatureJson);
}
@@ -0,0 +1,77 @@
using Heimdall.Application.DTOs;
using Heimdall.Domain.Entities;
namespace Heimdall.Application.Agents;
/// <summary>
/// Shared mapping between <see cref="Agent"/> entity and <see cref="AgentTelemetryFields"/>.
/// Eliminates field-by-field duplication across HeartbeatHandler and AgentExtensions.
/// </summary>
public static class AgentTelemetryMapping
{
/// <summary>
/// Reads all telemetry properties from an <see cref="Agent"/> entity
/// and returns them as an <see cref="AgentTelemetryFields"/> record.
/// </summary>
public static AgentTelemetryFields ToTelemetryFields(this Agent a) => new(
a.CpuUsagePercent, a.MemoryUsageBytes, a.DiskUsagePercent, a.UptimeSeconds,
a.CpuVendor, a.CpuModel, a.CpuArchitecture,
a.PhysicalCores, a.LogicalCores, a.ThreadsPerCore,
a.CpuFrequencyMhz, a.CpuFlags, a.CpuCacheBytes, a.ContainerCpuLimit,
a.MemTotalBytes, a.MemAvailableBytes, a.SwapTotalBytes, a.SwapFreeBytes,
a.ContainerMemoryLimitBytes,
a.DiskInventoryJson, a.GpuInventoryJson,
a.OsName, a.KernelVersion, a.Arch, a.UptimeMachineSeconds,
a.ContainerId, a.ContainerImage,
a.NetworkInterfacesJson, a.TemperatureJson);
/// <summary>
/// Applies all telemetry fields from a <see cref="AgentTelemetryFields"/> source
/// (HeartbeatCommand, AgentHeartbeatRequest, etc.) to an <see cref="Agent"/> entity.
/// Preserves existing inventory when no new data is present.
/// </summary>
public static void ApplyTo(this AgentTelemetryFields fields, Agent agent)
{
// Live metrics — always update
agent.UpdateLiveMetrics(
fields.CpuUsagePercent,
fields.MemoryUsageBytes,
fields.DiskUsagePercent,
fields.UptimeSeconds);
// CPU inventory — update only when new data is present
if (fields.CpuVendor is not null || fields.CpuModel is not null ||
fields.PhysicalCores.HasValue || fields.LogicalCores.HasValue)
{
agent.UpdateCpuInventory(new CpuInventoryData(
fields.CpuVendor, fields.CpuModel, fields.CpuArchitecture,
fields.PhysicalCores, fields.LogicalCores, fields.ThreadsPerCore,
fields.CpuFrequencyMhz, fields.CpuFlags, fields.CpuCacheBytes,
fields.ContainerCpuLimit));
}
// Memory/disk inventory — update only when new data is present
if (fields.MemTotalBytes.HasValue || fields.DiskInventoryJson is not null)
{
agent.UpdateMemoryDiskInventory(new MemoryDiskInventoryData(
fields.MemTotalBytes, fields.MemAvailableBytes,
fields.SwapTotalBytes, fields.SwapFreeBytes,
fields.ContainerMemoryLimitBytes, fields.DiskInventoryJson));
}
// GPU inventory — update only when present
if (fields.GpuInventoryJson is not null)
agent.UpdateGpuInventory(fields.GpuInventoryJson);
// Host inventory — update only when new data is present
if (fields.OsName is not null || fields.KernelVersion is not null ||
fields.ContainerId is not null || fields.NetworkInterfacesJson is not null)
{
agent.UpdateHostInventory(new HostInventoryData(
fields.OsName, fields.KernelVersion, fields.Arch,
fields.UptimeMachineSeconds, fields.ContainerId,
fields.ContainerImage, fields.NetworkInterfacesJson,
fields.TemperatureJson));
}
}
}
@@ -1,4 +1,6 @@
using Heimdall.Application.Common;
using Heimdall.Application.DTOs;
using Heimdall.Domain.Entities;
using Heimdall.Domain.Enums;
using MediatR;
@@ -15,4 +17,80 @@ public record HeartbeatCommand(
double? CpuUsagePercent = null,
long? MemoryUsageBytes = null,
double? DiskUsagePercent = null,
long? UptimeSeconds = null) : IRequest<ServiceResult>;
long? UptimeSeconds = null,
// CPU inventory
string? CpuVendor = null,
string? CpuModel = null,
string? CpuArchitecture = null,
int? PhysicalCores = null,
int? LogicalCores = null,
int? ThreadsPerCore = null,
double? CpuFrequencyMhz = null,
string? CpuFlags = null,
long? CpuCacheBytes = null,
long? ContainerCpuLimit = null,
// Memory inventory
long? MemTotalBytes = null,
long? MemAvailableBytes = null,
long? SwapTotalBytes = null,
long? SwapFreeBytes = null,
long? ContainerMemoryLimitBytes = null,
// Disk inventory (JSON)
string? DiskInventoryJson = null,
// GPU inventory (JSON)
string? GpuInventoryJson = null,
// Host info
string? OsName = null,
string? KernelVersion = null,
string? Arch = null,
long? UptimeMachineSeconds = null,
// Container info
string? ContainerId = null,
string? ContainerImage = null,
// Network & Temperature (JSON)
string? NetworkInterfacesJson = null,
string? TemperatureJson = null) : AgentTelemetryFields(
CpuUsagePercent, MemoryUsageBytes, DiskUsagePercent, UptimeSeconds,
CpuVendor, CpuModel, CpuArchitecture, PhysicalCores, LogicalCores,
ThreadsPerCore, CpuFrequencyMhz, CpuFlags, CpuCacheBytes, ContainerCpuLimit,
MemTotalBytes, MemAvailableBytes, SwapTotalBytes, SwapFreeBytes, ContainerMemoryLimitBytes,
DiskInventoryJson, GpuInventoryJson, OsName, KernelVersion, Arch, UptimeMachineSeconds,
ContainerId, ContainerImage, NetworkInterfacesJson, TemperatureJson),
IRequest<ServiceResult>
{
/// <summary>Returns true if any CPU inventory field is non-null.</summary>
public bool HasCpuInventory() =>
CpuVendor is not null || CpuModel is not null || CpuArchitecture is not null ||
PhysicalCores is not null || LogicalCores is not null || ThreadsPerCore is not null ||
CpuFrequencyMhz is not null || CpuFlags is not null || CpuCacheBytes is not null ||
ContainerCpuLimit is not null;
/// <summary>Returns true if any memory/disk inventory field is non-null.</summary>
public bool HasMemoryDiskInventory() =>
MemTotalBytes is not null || MemAvailableBytes is not null ||
SwapTotalBytes is not null || SwapFreeBytes is not null ||
ContainerMemoryLimitBytes is not null || DiskInventoryJson is not null;
/// <summary>Returns true if any host inventory field is non-null.</summary>
public bool HasHostInventory() =>
OsName is not null || KernelVersion is not null || Arch is not null ||
UptimeMachineSeconds is not null || ContainerId is not null ||
ContainerImage is not null || NetworkInterfacesJson is not null ||
TemperatureJson is not null;
/// <summary>Converts CPU inventory fields to <see cref="CpuInventoryData"/>.</summary>
public CpuInventoryData ToCpuInventoryData() => new(
CpuVendor, CpuModel, CpuArchitecture,
PhysicalCores, LogicalCores, ThreadsPerCore,
CpuFrequencyMhz, CpuFlags, CpuCacheBytes, ContainerCpuLimit);
/// <summary>Converts memory/disk inventory fields to <see cref="MemoryDiskInventoryData"/>.</summary>
public MemoryDiskInventoryData ToMemoryDiskInventoryData() => new(
MemTotalBytes, MemAvailableBytes, SwapTotalBytes, SwapFreeBytes,
ContainerMemoryLimitBytes, DiskInventoryJson);
/// <summary>Converts host inventory fields to <see cref="HostInventoryData"/>.</summary>
public HostInventoryData ToHostInventoryData() => new(
OsName, KernelVersion, Arch, UptimeMachineSeconds,
ContainerId, ContainerImage, NetworkInterfacesJson, TemperatureJson);
}
@@ -1,3 +1,4 @@
using Heimdall.Application.Agents;
using Heimdall.Application.Common;
using Heimdall.Domain.Enums;
using MediatR;
@@ -11,39 +12,39 @@ public class HeartbeatHandler : IRequestHandler<HeartbeatCommand, ServiceResult>
public HeartbeatHandler(IApplicationDbContext db) => _db = db;
public async Task<ServiceResult> Handle(HeartbeatCommand request, CancellationToken ct)
public async Task<ServiceResult> Handle(HeartbeatCommand request, CancellationToken cancellationToken)
{
var agent = await _db.Agents.FirstOrDefaultAsync(a => a.Id == request.AgentId, ct).ConfigureAwait(false);
var agent = await _db.Agents.FirstOrDefaultAsync(a => a.Id == request.AgentId, cancellationToken).ConfigureAwait(false);
if (agent is null)
return ServiceResult.NotFound("Agent not found");
if (request.IsOffline)
{
// Graceful shutdown: reflect it immediately instead of waiting for
// the 90s HeartbeatMonitorJob timeout.
agent.MarkOffline();
}
else
{
agent.UpdateHeartbeat(request.PublicIp);
if (request.HasGpu.HasValue || request.CpuCores.HasValue || request.MemoryMb.HasValue || request.GpuType.HasValue)
{
agent.UpdateCapabilities(
request.HasGpu ?? false,
request.CpuCores ?? 0,
request.MemoryMb ?? 0,
request.GpuType ?? GpuAcceleration.None);
}
agent.UpdateLiveMetrics(
request.CpuUsagePercent,
request.MemoryUsageBytes,
request.DiskUsagePercent,
request.UptimeSeconds);
UpdateAgentState(agent, request);
}
await _db.SaveChangesWithRetryAsync(ct: ct).ConfigureAwait(false);
await _db.SaveChangesWithRetryAsync(ct: cancellationToken).ConfigureAwait(false);
return ServiceResult.Success();
}
private static void UpdateAgentState(Domain.Entities.Agent agent, HeartbeatCommand request)
{
agent.UpdateHeartbeat(request.PublicIp);
if (request.HasGpu.HasValue || request.CpuCores.HasValue || request.MemoryMb.HasValue || request.GpuType.HasValue)
{
agent.UpdateCapabilities(
request.HasGpu ?? false,
request.CpuCores ?? 0,
request.MemoryMb ?? 0,
request.GpuType ?? GpuAcceleration.None);
}
// Apply all telemetry fields via shared helper
request.ApplyTo(agent);
}
}
@@ -21,12 +21,6 @@ public class GetAgentHandler : IRequestHandler<GetAgentQuery, ServiceResult<Agen
if (agent is null)
return ServiceResult<AgentResponse>.NotFound("Agent not found");
return ServiceResult<AgentResponse>.Success(MapResponse(agent));
return ServiceResult<AgentResponse>.Success(agent.ToResponse());
}
private static AgentResponse MapResponse(Domain.Entities.Agent a) => new(
a.Id, a.SiteId, a.Site?.Name ?? string.Empty, a.Name, a.Hostname, a.Version, a.Status,
a.LastHeartbeat, a.PublicIp, a.HasGpu, a.CpuCores, a.MemoryMb,
a.GpuType.ToString(), a.CreatedAt,
a.CpuUsagePercent, a.MemoryUsageBytes, a.DiskUsagePercent, a.UptimeSeconds);
}
@@ -27,16 +27,10 @@ public class GetAgentsBySiteHandler : IRequestHandler<GetAgentsBySiteQuery, Serv
var items = await query
.Skip((request.Page - 1) * request.PageSize)
.Take(request.PageSize)
.Select(a => MapResponse(a))
.Select(a => a.ToResponse())
.ToListAsync(ct);
return ServiceResult<PagedResult<AgentResponse>>.Success(
new PagedResult<AgentResponse>(items, total, request.Page, request.PageSize));
}
private static AgentResponse MapResponse(Domain.Entities.Agent a) => new(
a.Id, a.SiteId, a.Site?.Name ?? string.Empty, a.Name, a.Hostname, a.Version, a.Status,
a.LastHeartbeat, a.PublicIp, a.HasGpu, a.CpuCores, a.MemoryMb,
a.GpuType.ToString(), a.CreatedAt,
a.CpuUsagePercent, a.MemoryUsageBytes, a.DiskUsagePercent, a.UptimeSeconds);
}
@@ -23,16 +23,10 @@ public class GetAllAgentsHandler : IRequestHandler<GetAllAgentsQuery, ServiceRes
var items = await query
.Skip((request.Page - 1) * request.PageSize)
.Take(request.PageSize)
.Select(a => MapResponse(a))
.Select(a => a.ToResponse())
.ToListAsync(ct);
return ServiceResult<PagedResult<AgentResponse>>.Success(
new PagedResult<AgentResponse>(items, total, request.Page, request.PageSize));
}
private static AgentResponse MapResponse(Domain.Entities.Agent a) => new(
a.Id, a.SiteId, a.Site?.Name ?? string.Empty, a.Name, a.Hostname, a.Version, a.Status,
a.LastHeartbeat, a.PublicIp, a.HasGpu, a.CpuCores, a.MemoryMb,
a.GpuType.ToString(), a.CreatedAt,
a.CpuUsagePercent, a.MemoryUsageBytes, a.DiskUsagePercent, a.UptimeSeconds);
}
@@ -33,17 +33,17 @@ public class ReportCameraStatusCommandHandler : IRequestHandler<ReportCameraStat
_logger = logger;
}
public async Task<ServiceResult> Handle(ReportCameraStatusCommand request, CancellationToken ct)
public async Task<ServiceResult> Handle(ReportCameraStatusCommand request, CancellationToken cancellationToken)
{
// Resolve the agent → site, then verify the camera belongs to that site.
var agent = await _db.Agents.AsNoTracking()
.FirstOrDefaultAsync(a => a.Id == request.AgentId, ct)
.FirstOrDefaultAsync(a => a.Id == request.AgentId, cancellationToken)
.ConfigureAwait(false);
if (agent is null)
return ServiceResult.NotFound("Agent not found");
var camera = await _db.Cameras
.FirstOrDefaultAsync(c => c.Id == request.CameraId, ct)
.FirstOrDefaultAsync(c => c.Id == request.CameraId, cancellationToken)
.ConfigureAwait(false);
if (camera is null)
return ServiceResult.NotFound("Camera not found");
@@ -54,14 +54,14 @@ public class ReportCameraStatusCommandHandler : IRequestHandler<ReportCameraStat
if (camera.Status != request.Status)
{
camera.SetStatus(request.Status);
await _db.SaveChangesWithRetryAsync(ct: ct).ConfigureAwait(false);
await _db.SaveChangesWithRetryAsync(ct: cancellationToken).ConfigureAwait(false);
_logger.LogInformation(
"Agent {AgentId} reported camera {CameraId} status -> {Status}",
request.AgentId, request.CameraId, request.Status);
await _monitoring.NotifyCameraStatusChanged(
agent.SiteId, request.CameraId, request.Status.ToString(), ct).ConfigureAwait(false);
agent.SiteId, request.CameraId, request.Status.ToString(), cancellationToken).ConfigureAwait(false);
}
return ServiceResult.Success();
+78 -2
View File
@@ -18,7 +18,45 @@ public record AgentHeartbeatRequest(
double? CpuUsagePercent = null,
long? MemoryUsageBytes = null,
double? DiskUsagePercent = null,
long? UptimeSeconds = null);
long? UptimeSeconds = null,
// CPU inventory
string? CpuVendor = null,
string? CpuModel = null,
string? CpuArchitecture = null,
int? PhysicalCores = null,
int? LogicalCores = null,
int? ThreadsPerCore = null,
double? CpuFrequencyMhz = null,
string? CpuFlags = null,
long? CpuCacheBytes = null,
long? ContainerCpuLimit = null,
// Memory inventory
long? MemTotalBytes = null,
long? MemAvailableBytes = null,
long? SwapTotalBytes = null,
long? SwapFreeBytes = null,
long? ContainerMemoryLimitBytes = null,
// Disk inventory (JSON)
string? DiskInventoryJson = null,
// GPU inventory (JSON)
string? GpuInventoryJson = null,
// Host info
string? OsName = null,
string? KernelVersion = null,
string? Arch = null,
long? UptimeMachineSeconds = null,
// Container info
string? ContainerId = null,
string? ContainerImage = null,
// Network & Temperature (JSON)
string? NetworkInterfacesJson = null,
string? TemperatureJson = null) : AgentTelemetryFields(
CpuUsagePercent, MemoryUsageBytes, DiskUsagePercent, UptimeSeconds,
CpuVendor, CpuModel, CpuArchitecture, PhysicalCores, LogicalCores,
ThreadsPerCore, CpuFrequencyMhz, CpuFlags, CpuCacheBytes, ContainerCpuLimit,
MemTotalBytes, MemAvailableBytes, SwapTotalBytes, SwapFreeBytes, ContainerMemoryLimitBytes,
DiskInventoryJson, GpuInventoryJson, OsName, KernelVersion, Arch, UptimeMachineSeconds,
ContainerId, ContainerImage, NetworkInterfacesJson, TemperatureJson);
public record AgentResponse(
Guid Id,
@@ -38,7 +76,45 @@ public record AgentResponse(
double? CpuUsagePercent = null,
long? MemoryUsageBytes = null,
double? DiskUsagePercent = null,
long? UptimeSeconds = null);
long? UptimeSeconds = null,
// CPU inventory
string? CpuVendor = null,
string? CpuModel = null,
string? CpuArchitecture = null,
int? PhysicalCores = null,
int? LogicalCores = null,
int? ThreadsPerCore = null,
double? CpuFrequencyMhz = null,
string? CpuFlags = null,
long? CpuCacheBytes = null,
long? ContainerCpuLimit = null,
// Memory inventory
long? MemTotalBytes = null,
long? MemAvailableBytes = null,
long? SwapTotalBytes = null,
long? SwapFreeBytes = null,
long? ContainerMemoryLimitBytes = null,
// Disk inventory (JSON)
string? DiskInventoryJson = null,
// GPU inventory (JSON)
string? GpuInventoryJson = null,
// Host info
string? OsName = null,
string? KernelVersion = null,
string? Arch = null,
long? UptimeMachineSeconds = null,
// Container info
string? ContainerId = null,
string? ContainerImage = null,
// Network & Temperature (JSON)
string? NetworkInterfacesJson = null,
string? TemperatureJson = null) : AgentTelemetryFields(
CpuUsagePercent, MemoryUsageBytes, DiskUsagePercent, UptimeSeconds,
CpuVendor, CpuModel, CpuArchitecture, PhysicalCores, LogicalCores,
ThreadsPerCore, CpuFrequencyMhz, CpuFlags, CpuCacheBytes, ContainerCpuLimit,
MemTotalBytes, MemAvailableBytes, SwapTotalBytes, SwapFreeBytes, ContainerMemoryLimitBytes,
DiskInventoryJson, GpuInventoryJson, OsName, KernelVersion, Arch, UptimeMachineSeconds,
ContainerId, ContainerImage, NetworkInterfacesJson, TemperatureJson);
public record RegisterAgentResponse(
Guid AgentId,
@@ -0,0 +1,44 @@
namespace Heimdall.Application.DTOs;
/// <summary>
/// Common telemetry fields shared by AgentHeartbeatRequest, HeartbeatCommand, and AgentResponse.
/// Extracted to eliminate code duplication across these DTOs.
/// </summary>
public record AgentTelemetryFields(
// System metrics
double? CpuUsagePercent = null,
long? MemoryUsageBytes = null,
double? DiskUsagePercent = null,
long? UptimeSeconds = null,
// CPU inventory
string? CpuVendor = null,
string? CpuModel = null,
string? CpuArchitecture = null,
int? PhysicalCores = null,
int? LogicalCores = null,
int? ThreadsPerCore = null,
double? CpuFrequencyMhz = null,
string? CpuFlags = null,
long? CpuCacheBytes = null,
long? ContainerCpuLimit = null,
// Memory inventory
long? MemTotalBytes = null,
long? MemAvailableBytes = null,
long? SwapTotalBytes = null,
long? SwapFreeBytes = null,
long? ContainerMemoryLimitBytes = null,
// Disk inventory (JSON)
string? DiskInventoryJson = null,
// GPU inventory (JSON)
string? GpuInventoryJson = null,
// Host info
string? OsName = null,
string? KernelVersion = null,
string? Arch = null,
long? UptimeMachineSeconds = null,
// Container info
string? ContainerId = null,
string? ContainerImage = null,
// Network & Temperature (JSON)
string? NetworkInterfacesJson = null,
string? TemperatureJson = null);
@@ -142,7 +142,7 @@ public static class CameraStreamTemplates
if (urls.Count == 0)
{
var fallbackPort = filter?.Contains(554) == true ? 554 : 554;
const int fallbackPort = 554;
urls.Add($"rtsp://{ip}:{fallbackPort}/stream1");
}
+124 -1
View File
@@ -19,7 +19,7 @@ public class Agent : Entity<Guid>, IAuditableEntity, ISoftDeletable
/// <summary>First 8 characters of the API key for identification.</summary>
public string? ApiKeyPrefix { get; private set; }
// Capabilities
// Capabilities (legacy)
public bool HasGpu { get; private set; }
public int CpuCores { get; private set; }
public long MemoryMb { get; private set; }
@@ -31,6 +31,47 @@ public class Agent : Entity<Guid>, IAuditableEntity, ISoftDeletable
public double? DiskUsagePercent { get; private set; }
public long? UptimeSeconds { get; private set; }
// ─── CPU inventory ────────────────────────────────────────────
public string? CpuVendor { get; private set; }
public string? CpuModel { get; private set; }
public string? CpuArchitecture { get; private set; }
public int? PhysicalCores { get; private set; }
public int? LogicalCores { get; private set; }
public int? ThreadsPerCore { get; private set; }
public double? CpuFrequencyMhz { get; private set; }
public string? CpuFlags { get; private set; }
public long? CpuCacheBytes { get; private set; }
// ─── Memory inventory ─────────────────────────────────────────
public long? MemTotalBytes { get; private set; }
public long? MemAvailableBytes { get; private set; }
public long? SwapTotalBytes { get; private set; }
public long? SwapFreeBytes { get; private set; }
// ─── Container limits ─────────────────────────────────────────
public long? ContainerCpuLimit { get; private set; }
public long? ContainerMemoryLimitBytes { get; private set; }
// ─── Disk inventory (JSON) ────────────────────────────────────
public string? DiskInventoryJson { get; private set; }
// ─── GPU inventory (JSON) ─────────────────────────────────────
public string? GpuInventoryJson { get; private set; }
// ─── Host info ────────────────────────────────────────────────
public string? OsName { get; private set; }
public string? KernelVersion { get; private set; }
public string? Arch { get; private set; }
public long? UptimeMachineSeconds { get; private set; }
// ─── Container info ───────────────────────────────────────────
public string? ContainerId { get; private set; }
public string? ContainerImage { get; private set; }
// ─── Network & Temperature (JSON) ─────────────────────────────
public string? NetworkInterfacesJson { get; private set; }
public string? TemperatureJson { get; private set; }
// Audit
public DateTime CreatedAt { get; set; }
public DateTime UpdatedAt { get; set; }
@@ -106,4 +147,86 @@ public class Agent : Entity<Guid>, IAuditableEntity, ISoftDeletable
IsDeleted = true;
DeletedAt = DateTime.UtcNow;
}
// ─── Inventory update methods ─────────────────────────────────
public void UpdateCpuInventory(CpuInventoryData data)
{
CpuVendor = data.Vendor;
CpuModel = data.Model;
CpuArchitecture = data.Architecture;
PhysicalCores = data.PhysicalCores;
LogicalCores = data.LogicalCores;
ThreadsPerCore = data.ThreadsPerCore;
CpuFrequencyMhz = data.FrequencyMhz;
CpuFlags = data.Flags;
CpuCacheBytes = data.CacheBytes;
ContainerCpuLimit = data.ContainerCpuLimit;
}
public void UpdateMemoryDiskInventory(MemoryDiskInventoryData data)
{
MemTotalBytes = data.MemTotalBytes;
MemAvailableBytes = data.MemAvailableBytes;
SwapTotalBytes = data.SwapTotalBytes;
SwapFreeBytes = data.SwapFreeBytes;
ContainerMemoryLimitBytes = data.ContainerMemoryLimitBytes;
DiskInventoryJson = data.DiskInventoryJson;
}
public void UpdateGpuInventory(string? gpuInventoryJson)
{
GpuInventoryJson = gpuInventoryJson;
}
public void UpdateHostInventory(HostInventoryData data)
{
OsName = data.OsName;
KernelVersion = data.KernelVersion;
Arch = data.Arch;
UptimeMachineSeconds = data.UptimeMachineSeconds;
ContainerId = data.ContainerId;
ContainerImage = data.ContainerImage;
NetworkInterfacesJson = data.NetworkInterfacesJson;
TemperatureJson = data.TemperatureJson;
}
}
/// <summary>
/// Groups CPU inventory fields to keep the update method under the parameter limit.
/// </summary>
public sealed record CpuInventoryData(
string? Vendor,
string? Model,
string? Architecture,
int? PhysicalCores,
int? LogicalCores,
int? ThreadsPerCore,
double? FrequencyMhz,
string? Flags,
long? CacheBytes,
long? ContainerCpuLimit);
/// <summary>
/// Groups memory and disk inventory fields.
/// </summary>
public sealed record MemoryDiskInventoryData(
long? MemTotalBytes,
long? MemAvailableBytes,
long? SwapTotalBytes,
long? SwapFreeBytes,
long? ContainerMemoryLimitBytes,
string? DiskInventoryJson);
/// <summary>
/// Groups host/container/network/temperature inventory fields.
/// </summary>
public sealed record HostInventoryData(
string? OsName,
string? KernelVersion,
string? Arch,
long? UptimeMachineSeconds,
string? ContainerId,
string? ContainerImage,
string? NetworkInterfacesJson,
string? TemperatureJson);
@@ -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();
@@ -4,7 +4,7 @@
@inject HeimdallApiClient Api
@inject ISnackbar Snackbar
@inject NavigationManager Nav
@implements IDisposable
@implements IAsyncDisposable
<MudText Typo="Typo.h1" Class="mb-6">
<MudIcon Icon="@Icons.Material.Filled.Dns" Class="mr-2" />
@@ -99,6 +99,363 @@ else
</MudItem>
</MudGrid>
@* ─── Hardware Inventory ─── *@
<MudGrid Class="mt-4">
@* ─── CPU Inventory ─── *@
<MudItem xs="12" md="6">
<SectionCard Title="Processeur" Icon="@Icons.Material.Filled.Memory" Elevation="2">
<MudGrid>
@if (_agent.CpuModel is not null)
{
<MudItem xs="12">
<MudText Typo="Typo.body2" Color="Color.Secondary">Modèle</MudText>
<MudText Typo="Typo.body1" Class="font-weight-medium">@_agent.CpuModel</MudText>
</MudItem>
}
@if (_agent.CpuVendor is not null)
{
<MudItem xs="6">
<MudText Typo="Typo.body2" Color="Color.Secondary">Fabricant</MudText>
<MudText Typo="Typo.body1">@_agent.CpuVendor</MudText>
</MudItem>
}
@if (_agent.CpuArchitecture is not null)
{
<MudItem xs="6">
<MudText Typo="Typo.body2" Color="Color.Secondary">Architecture</MudText>
<MudText Typo="Typo.body1">@_agent.CpuArchitecture</MudText>
</MudItem>
}
@if (_agent.PhysicalCores.HasValue)
{
<MudItem xs="4">
<MudText Typo="Typo.body2" Color="Color.Secondary">Cœurs physiques</MudText>
<MudText Typo="Typo.body1">@_agent.PhysicalCores</MudText>
</MudItem>
}
@if (_agent.LogicalCores.HasValue)
{
<MudItem xs="4">
<MudText Typo="Typo.body2" Color="Color.Secondary">Cœurs logiques</MudText>
<MudText Typo="Typo.body1">@_agent.LogicalCores</MudText>
</MudItem>
}
@if (_agent.ThreadsPerCore.HasValue)
{
<MudItem xs="4">
<MudText Typo="Typo.body2" Color="Color.Secondary">Threads/noyau</MudText>
<MudText Typo="Typo.body1">@_agent.ThreadsPerCore</MudText>
</MudItem>
}
@if (_agent.CpuFrequencyMhz.HasValue)
{
<MudItem xs="6" Class="mt-2">
<MudText Typo="Typo.body2" Color="Color.Secondary">Fréquence</MudText>
<MudText Typo="Typo.body1">@($"{_agent.CpuFrequencyMhz:F0} MHz")</MudText>
</MudItem>
}
@if (_agent.CpuCacheBytes.HasValue && _agent.CpuCacheBytes > 0)
{
<MudItem xs="6" Class="mt-2">
<MudText Typo="Typo.body2" Color="Color.Secondary">Cache</MudText>
<MudText Typo="Typo.body1">@FormatBytes(_agent.CpuCacheBytes.Value)</MudText>
</MudItem>
}
@if (!string.IsNullOrEmpty(_agent.CpuFlags))
{
<MudItem xs="12" Class="mt-2">
<MudText Typo="Typo.body2" Color="Color.Secondary">Instructions clés</MudText>
<div class="d-flex flex-wrap gap-1 mt-1">
@foreach (var flag in _agent.CpuFlags.Split(',', StringSplitOptions.RemoveEmptyEntries))
{
<MudChip T="string" Size="Size.Small" Color="Color.Info" Variant="Variant.Outlined">@flag</MudChip>
}
</div>
</MudItem>
}
</MudGrid>
</SectionCard>
</MudItem>
@* ─── Memory & Disk Inventory ─── *@
<MudItem xs="12" md="6">
<SectionCard Title="Mémoire & Stockage" Icon="@Icons.Material.Filled.Storage" Elevation="2">
<MudGrid>
@if (_agent.MemTotalBytes.HasValue)
{
<MudItem xs="6">
<MudText Typo="Typo.body2" Color="Color.Secondary">Mémoire totale</MudText>
<MudText Typo="Typo.body1">@FormatBytes(_agent.MemTotalBytes.Value)</MudText>
</MudItem>
}
@if (_agent.MemAvailableBytes.HasValue)
{
<MudItem xs="6">
<MudText Typo="Typo.body2" Color="Color.Secondary">Mémoire dispo</MudText>
<MudText Typo="Typo.body1">@FormatBytes(_agent.MemAvailableBytes.Value)</MudText>
</MudItem>
}
@if (_agent.SwapTotalBytes.HasValue && _agent.SwapTotalBytes > 0)
{
<MudItem xs="6" Class="mt-2">
<MudText Typo="Typo.body2" Color="Color.Secondary">Swap total</MudText>
<MudText Typo="Typo.body1">@FormatBytes(_agent.SwapTotalBytes.Value)</MudText>
</MudItem>
}
@if (_agent.SwapFreeBytes.HasValue && _agent.SwapTotalBytes is > 0)
{
<MudItem xs="6" Class="mt-2">
<MudText Typo="Typo.body2" Color="Color.Secondary">Swap dispo</MudText>
<MudText Typo="Typo.body1">@FormatBytes(_agent.SwapFreeBytes.Value)</MudText>
</MudItem>
}
@if (_agent.ContainerMemoryLimitBytes.HasValue)
{
<MudItem xs="12" Class="mt-2">
<MudChip T="string" Size="Size.Small" Color="Color.Warning">
Limite conteneur : @FormatBytes(_agent.ContainerMemoryLimitBytes.Value)
</MudChip>
</MudItem>
}
@if (!string.IsNullOrEmpty(_agent.DiskInventoryJson))
{
<MudItem xs="12" Class="mt-2">
<MudText Typo="Typo.body2" Color="Color.Secondary">Disques</MudText>
@{
var disks = ParseDiskJson(_agent.DiskInventoryJson);
}
@if (disks.Count > 0)
{
<MudTable Items="@disks" Dense="true" Hover="true" Elevation="0" Class="mt-1">
<HeaderContent>
<MudTh>Point de montage</MudTh>
<MudTh>FS</MudTh>
<MudTh>Taille</MudTh>
<MudTh>Utilisé</MudTh>
<MudTh>Type</MudTh>
</HeaderContent>
<RowTemplate>
<MudTd DataLabel="Point de montage">
<MudText Typo="Typo.body2">@context.MountPoint</MudText>
</MudTd>
<MudTd DataLabel="FS">
<MudText Typo="Typo.body2">@context.FileSystem</MudText>
</MudTd>
<MudTd DataLabel="Taille">
<MudText Typo="Typo.body2">@(context.TotalBytes.HasValue ? FormatBytes(context.TotalBytes.Value) : "-")</MudText>
</MudTd>
<MudTd DataLabel="Utilisé">
<MudText Typo="Typo.body2">@(context.UsedBytes.HasValue ? FormatBytes(context.UsedBytes.Value) : "-")</MudText>
</MudTd>
<MudTd DataLabel="Type">
<MudChip T="string" Size="Size.Small"
Color="@(context.Type == "SSD" ? Color.Success : Color.Default)">
@context.Type
</MudChip>
</MudTd>
</RowTemplate>
</MudTable>
}
else
{
<MudText Typo="Typo.body2" Color="Color.Secondary" Class="mt-1">Aucun disque détecté</MudText>
}
</MudItem>
}
</MudGrid>
</SectionCard>
</MudItem>
</MudGrid>
<MudGrid Class="mt-4">
@* ─── GPU Inventory ─── *@
<MudItem xs="12" md="6">
<SectionCard Title="GPU" Icon="@Icons.Material.Filled.Videocam" Elevation="2">
@{
var gpus = ParseGpuJson(_agent.GpuInventoryJson);
}
@if (gpus.Count > 0)
{
<MudTable Items="@gpus" Dense="true" Hover="true" Elevation="0">
<HeaderContent>
<MudTh>Modèle</MudTh>
<MudTh>Backend</MudTh>
<MudTh>VRAM</MudTh>
<MudTh>Temp</MudTh>
<MudTh>Utilisation</MudTh>
<MudTh>Driver</MudTh>
<MudTh>Encoder</MudTh>
</HeaderContent>
<RowTemplate>
<MudTd DataLabel="Modèle">
<MudText Typo="Typo.body2" Class="font-weight-medium">@(context.Model ?? "-")</MudText>
</MudTd>
<MudTd DataLabel="Backend">
<MudChip T="string" Size="Size.Small" Color="Color.Info">@(context.Backend ?? "-")</MudChip>
</MudTd>
<MudTd DataLabel="VRAM">
<MudText Typo="Typo.body2">@(context.VramBytes.HasValue ? FormatBytes(context.VramBytes.Value) : "-")</MudText>
</MudTd>
<MudTd DataLabel="Temp">
<MudText Typo="Typo.body2">@(context.TemperatureCelsius.HasValue ? $"{context.TemperatureCelsius:F0}°C" : "-")</MudText>
</MudTd>
<MudTd DataLabel="Utilisation">
<MudText Typo="Typo.body2">@(context.UtilizationPercent.HasValue ? $"{context.UtilizationPercent:F0}%" : "-")</MudText>
</MudTd>
<MudTd DataLabel="Driver">
<MudText Typo="Typo.body2">@(context.DriverVersion ?? "-")</MudText>
</MudTd>
<MudTd DataLabel="Encoder">
<MudText Typo="Typo.body2">@(context.EncoderSupport ?? "-")</MudText>
</MudTd>
</RowTemplate>
</MudTable>
}
else
{
<MudText Typo="Typo.body2" Color="Color.Secondary">Aucun GPU détecté</MudText>
}
</SectionCard>
</MudItem>
@* ─── Host & Container ─── *@
<MudItem xs="12" md="6">
<SectionCard Title="Système & Conteneur" Icon="@Icons.Material.Filled.Computer" Elevation="2">
<MudGrid>
@if (_agent.OsName is not null)
{
<MudItem xs="6">
<MudText Typo="Typo.body2" Color="Color.Secondary">OS</MudText>
<MudText Typo="Typo.body1">@_agent.OsName</MudText>
</MudItem>
}
@if (_agent.KernelVersion is not null)
{
<MudItem xs="6">
<MudText Typo="Typo.body2" Color="Color.Secondary">Noyau</MudText>
<MudText Typo="Typo.body1">@_agent.KernelVersion</MudText>
</MudItem>
}
@if (_agent.Arch is not null)
{
<MudItem xs="6" Class="mt-2">
<MudText Typo="Typo.body2" Color="Color.Secondary">Architecture</MudText>
<MudText Typo="Typo.body1">@_agent.Arch</MudText>
</MudItem>
}
@if (_agent.UptimeMachineSeconds.HasValue)
{
<MudItem xs="6" Class="mt-2">
<MudText Typo="Typo.body2" Color="Color.Secondary">Uptime machine</MudText>
<MudText Typo="Typo.body1">@FormatUptime(_agent.UptimeMachineSeconds.Value)</MudText>
</MudItem>
}
@if (_agent.ContainerId is not null)
{
<MudItem xs="12" Class="mt-2">
<MudDivider Class="mb-2" />
<MudText Typo="Typo.body2" Color="Color.Secondary">Conteneur</MudText>
<MudText Typo="Typo.body1">
<MudIcon Icon="@Icons.Material.Filled.CheckCircle" Color="Color.Success" Size="Size.Small" Class="mr-1" />
@(_agent.ContainerImage ?? "Conteneur Docker")
</MudText>
<MudText Typo="Typo.caption" Color="Color.Secondary">ID: @_agent.ContainerId</MudText>
</MudItem>
}
@if (_agent.ContainerCpuLimit.HasValue)
{
<MudItem xs="6" Class="mt-2">
<MudChip T="string" Size="Size.Small" Color="Color.Warning">
CPU limite: @($"{_agent.ContainerCpuLimit.Value / 100.0:F1} cores")
</MudChip>
</MudItem>
}
</MudGrid>
</SectionCard>
</MudItem>
</MudGrid>
<MudGrid Class="mt-4">
@* ─── Network Interfaces ─── *@
<MudItem xs="12" md="6">
<SectionCard Title="Réseau" Icon="@Icons.Material.Filled.Wifi" Elevation="2">
@{
var interfaces = ParseNetworkJson(_agent.NetworkInterfacesJson);
}
@if (interfaces.Count > 0)
{
<MudTable Items="@interfaces" Dense="true" Hover="true" Elevation="0">
<HeaderContent>
<MudTh>Interface</MudTh>
<MudTh>Adresse IP</MudTh>
<MudTh>MAC</MudTh>
<MudTh>Débit</MudTh>
</HeaderContent>
<RowTemplate>
<MudTd DataLabel="Interface">
<MudText Typo="Typo.body2" Class="font-weight-medium">@context.Name</MudText>
</MudTd>
<MudTd DataLabel="Adresse IP">
<MudText Typo="Typo.body2">@(context.IpAddress ?? "-")</MudText>
</MudTd>
<MudTd DataLabel="MAC">
<MudText Typo="Typo.body2">@(context.MacAddress ?? "-")</MudText>
</MudTd>
<MudTd DataLabel="Débit">
<MudText Typo="Typo.body2">@(context.SpeedMbps.HasValue ? $"{context.SpeedMbps} Mbps" : "-")</MudText>
</MudTd>
</RowTemplate>
</MudTable>
}
else
{
<MudText Typo="Typo.body2" Color="Color.Secondary">Aucune interface réseau détectée</MudText>
}
</SectionCard>
</MudItem>
@* ─── Temperature ─── *@
<MudItem xs="12" md="6">
<SectionCard Title="Températures" Icon="@Icons.Material.Filled.Thermostat" Elevation="2">
@{
var temps = ParseTemperatureJson(_agent.TemperatureJson);
}
@if (temps.Count > 0)
{
<MudTable Items="@temps" Dense="true" Hover="true" Elevation="0">
<HeaderContent>
<MudTh>Zone</MudTh>
<MudTh>Température</MudTh>
</HeaderContent>
<RowTemplate>
<MudTd DataLabel="Zone">
<MudText Typo="Typo.body2">@context.Zone</MudText>
</MudTd>
<MudTd DataLabel="Température">
@{
Color tempColor;
if (context.TemperatureCelsius > 70)
tempColor = Color.Error;
else if (context.TemperatureCelsius > 50)
tempColor = Color.Warning;
else
tempColor = Color.Default;
}
<MudText Typo="Typo.body2" Color="@tempColor">
@($"{context.TemperatureCelsius:F1}°C")
</MudText>
</MudTd>
</RowTemplate>
</MudTable>
}
else
{
<MudText Typo="Typo.body2" Color="Color.Secondary">Aucune sonde de température détectée</MudText>
}
</SectionCard>
</MudItem>
</MudGrid>
@* ─── Agent Settings (globals hérités + overrides) ─── *@
<SectionCard Title="Configuration"
Icon="@Icons.Material.Filled.Tune"
@@ -648,9 +1005,12 @@ else
private async Task ToggleAutoRefresh(bool enabled)
{
_autoRefresh = enabled;
_refreshCts?.Cancel();
_refreshCts?.Dispose();
_refreshCts = null;
if (_refreshCts is not null)
{
await _refreshCts.CancelAsync();
_refreshCts.Dispose();
_refreshCts = null;
}
if (enabled)
{
@@ -681,12 +1041,15 @@ else
_ => Color.Default
};
public void Dispose()
public async ValueTask DisposeAsync()
{
_disposed = true;
_refreshCts?.Cancel();
_refreshCts?.Dispose();
_refreshCts = null;
if (_refreshCts is not null)
{
await _refreshCts.CancelAsync();
_refreshCts.Dispose();
_refreshCts = null;
}
}
private static Color GetStatusColor(string status) => status switch
@@ -749,4 +1112,111 @@ else
? p.ToUpperInvariant()
: char.ToUpperInvariant(p[0]) + p[1..]));
}
// ─── Inventory helpers ─────────────────────────────────────────
private static string FormatBytes(long bytes) => bytes switch
{
>= 1_073_741_824L => $"{bytes / 1_073_741_824.0:F1} Go",
>= 1_048_576L => $"{bytes / 1_048_576.0:F1} Mo",
>= 1024L => $"{bytes / 1024.0:F1} Ko",
_ => $"{bytes} o"
};
private static string FormatUptime(long seconds) => seconds switch
{
>= 86400 => $"{seconds / 86400}j {seconds % 86400 / 3600}h",
>= 3600 => $"{seconds / 3600}h {seconds % 3600 / 60}m",
>= 60 => $"{seconds / 60}m {seconds % 60}s",
_ => $"{seconds}s"
};
private static List<DiskDto> ParseDiskJson(string? json)
{
if (string.IsNullOrWhiteSpace(json)) return [];
try
{
return System.Text.Json.JsonSerializer.Deserialize<List<DiskDto>>(json) ?? [];
}
catch { return []; }
}
private static List<GpuDto> ParseGpuJson(string? json)
{
if (string.IsNullOrWhiteSpace(json)) return [];
try
{
return System.Text.Json.JsonSerializer.Deserialize<List<GpuDto>>(json) ?? [];
}
catch { return []; }
}
private static List<NetworkDto> ParseNetworkJson(string? json)
{
if (string.IsNullOrWhiteSpace(json)) return [];
try
{
return System.Text.Json.JsonSerializer.Deserialize<List<NetworkDto>>(json) ?? [];
}
catch { return []; }
}
private static List<TempDto> ParseTemperatureJson(string? json)
{
if (string.IsNullOrWhiteSpace(json)) return [];
try
{
return System.Text.Json.JsonSerializer.Deserialize<List<TempDto>>(json) ?? [];
}
catch { return []; }
}
// DTOs for JSON deserialization
private sealed class DiskDto
{
public string MountPoint { get; init; } = "";
public string FileSystem { get; init; } = "";
public long? TotalBytes { get; init; } = null;
public long? UsedBytes { get; init; } = null;
public string Type { get; init; } = "Unknown";
}
[Serializable]
private sealed class GpuDto
{
[JsonPropertyName("model")]
public string? Model { get; init; }
[JsonPropertyName("vramBytes")]
public long? VramBytes { get; init; }
[JsonPropertyName("driverVersion")]
public string? DriverVersion { get; init; }
[JsonPropertyName("temperatureCelsius")]
public double? TemperatureCelsius { get; init; }
[JsonPropertyName("utilizationPercent")]
public double? UtilizationPercent { get; init; }
[JsonPropertyName("backend")]
public string? Backend { get; init; }
[JsonPropertyName("encoderSupport")]
public string? EncoderSupport { get; init; }
}
[Serializable]
private sealed class NetworkDto
{
public string Name { get; init; } = "";
[JsonPropertyName("ipAddress")]
public string? IpAddress { get; init; }
[JsonPropertyName("macAddress")]
public string? MacAddress { get; init; }
[JsonPropertyName("speedMbps")]
public long? SpeedMbps { get; init; }
}
[Serializable]
private sealed class TempDto
{
public string Zone { get; init; } = "";
[JsonPropertyName("temperatureCelsius")]
public double TemperatureCelsius { get; init; }
}
}
@@ -71,7 +71,7 @@
{
<MudChip T="string" Size="Size.Small" Class="ml-3"
Color="@(_testResult.Healthy == true ? Color.Success : Color.Error)" Variant="Variant.Outlined">
@(_testResult.Healthy == true ? "Opérationnel" : _testResult.Configured == false ? "Non configuré" : "Injoignable")
@GetStorageTestStatus()
</MudChip>
}
</div>
@@ -83,6 +83,13 @@
private bool _testing;
private StorageTestResult? _testResult;
private string GetStorageTestStatus()
{
if (_testResult?.Healthy is true) return "Opérationnel";
if (_testResult?.Configured is false) return "Non configuré";
return "Injoignable";
}
protected override async Task OnInitializedAsync()
{
try
@@ -7,6 +7,7 @@
@using Microsoft.AspNetCore.Components.Web.Virtualization
@using Microsoft.JSInterop
@using MudBlazor
@using System.Text.Json.Serialization
@using Microsoft.AspNetCore.Authorization
@using Microsoft.AspNetCore.Components.Authorization
@using Heimdall.Web
@@ -23,6 +23,15 @@ namespace Heimdall.Api.Controllers;
[EnableRateLimiting("Api")]
public class AgentsController : ControllerBase
{
/// <summary>Query parameters for agent log retrieval.</summary>
public record AgentLogsQuery(
[FromQuery] int Page = 1,
[FromQuery] int PageSize = 50,
[FromQuery] string? Level = null,
[FromQuery] DateTime? From = null,
[FromQuery] DateTime? To = null,
[FromQuery] string? Search = null);
private readonly IMediator _mediator;
public AgentsController(IMediator mediator) => _mediator = mediator;
@@ -35,10 +44,6 @@ public class AgentsController : ControllerBase
public async Task<IActionResult> Register(
[FromBody] RegisterAgentRequest request, CancellationToken ct)
{
// Extract API key from header (may be empty for registration)
var apiKey = Request.Headers.Authorization.FirstOrDefault()
?.Replace("Bearer ", "", StringComparison.OrdinalIgnoreCase);
var command = new RegisterAgentCommand(request.Token, request.Hostname, request.Version, request.PublicIp);
var result = await _mediator.Send(command, ct);
return result.IsSuccess
@@ -66,7 +71,39 @@ public class AgentsController : ControllerBase
request.CpuUsagePercent,
request.MemoryUsageBytes,
request.DiskUsagePercent,
request.UptimeSeconds);
request.UptimeSeconds,
// CPU inventory
request.CpuVendor,
request.CpuModel,
request.CpuArchitecture,
request.PhysicalCores,
request.LogicalCores,
request.ThreadsPerCore,
request.CpuFrequencyMhz,
request.CpuFlags,
request.CpuCacheBytes,
request.ContainerCpuLimit,
// Memory inventory
request.MemTotalBytes,
request.MemAvailableBytes,
request.SwapTotalBytes,
request.SwapFreeBytes,
request.ContainerMemoryLimitBytes,
// Disk inventory
request.DiskInventoryJson,
// GPU inventory
request.GpuInventoryJson,
// Host info
request.OsName,
request.KernelVersion,
request.Arch,
request.UptimeMachineSeconds,
// Container info
request.ContainerId,
request.ContainerImage,
// Network & Temperature
request.NetworkInterfacesJson,
request.TemperatureJson);
var result = await _mediator.Send(command, ct);
return result.IsSuccess
? Ok()
@@ -167,16 +204,11 @@ public class AgentsController : ControllerBase
[ProducesResponseType(typeof(void), StatusCodes.Status400BadRequest)]
public async Task<IActionResult> GetLogs(
Guid id,
[FromQuery] int page = 1,
[FromQuery] int pageSize = 50,
[FromQuery] string? level = null,
[FromQuery] DateTime? from = null,
[FromQuery] DateTime? to = null,
[FromQuery] string? search = null,
CancellationToken ct = default)
AgentLogsQuery query,
CancellationToken ct)
{
var result = await _mediator.Send(
new GetAgentLogsQuery(id, page, pageSize, level, from, to, search), ct);
new GetAgentLogsQuery(id, query.Page, query.PageSize, query.Level, query.From, query.To, query.Search), ct);
if (!result.IsSuccess)
return StatusCode(result.StatusCode ?? 400, new { error = result.Error });
return Ok(result.Data);
+261 -248
View File
@@ -42,14 +42,14 @@ Program.ConfigureMiddleware(app);
// (appsettings.Testing.json sets Database:MigrateOnStartup=false; test
// factories opt back in explicitly when they need the schema).
var migrateOnStartup = builder.Configuration.GetValue<bool?>("Database:MigrateOnStartup")
?? !app.Environment.IsEnvironment("Testing");
?? !app.Environment.IsEnvironment(TestingEnvironment);
if (migrateOnStartup)
{
await Program.ApplyMigrationsAsync(app);
}
// ── Register recurring Hangfire jobs (heartbeat monitor, agent failover) ──
var isTesting = app.Environment.IsEnvironment("Testing");
var isTesting = app.Environment.IsEnvironment(TestingEnvironment);
var pgConnStr = Environment.GetEnvironmentVariable("DATABASE_URL") ?? app.Configuration.GetConnectionString("Default");
if (!isTesting && !string.IsNullOrEmpty(pgConnStr))
{
@@ -76,6 +76,30 @@ internal sealed record SignInRequest(
// works in integration tests.
public partial class Program
{
private const string TestingEnvironment = "Testing";
// SonarQube S1118: partial class used by WebApplicationFactory needs a constructor.
protected Program() { }
private static string ResolveCategory(string key)
{
if (key.StartsWith("ntfy.", StringComparison.Ordinal) || key.StartsWith("email.", StringComparison.Ordinal))
return "integrations";
if (key.StartsWith("ai.", StringComparison.Ordinal))
return "ai";
return "agent";
}
private static string FormatSentryStatus(bool enabled, string? dsn)
{
if (!enabled)
return "DISABLED (toggle sentry.enabled=false — redémarrage requis)";
if (string.IsNullOrEmpty(dsn))
return "NOT CONFIGURED — errors will NOT be reported to GlitchTip";
var atIndex = dsn.IndexOf('@');
return $"configured ({dsn[..atIndex]}@...)";
}
// Shared JWT validation parameters — single source of truth for auth.
internal static TokenValidationParameters GetJwtValidationParameters(string key, string issuer, string audience) => new()
{
@@ -141,7 +165,7 @@ public partial class Program
{
migrationCt.ThrowIfCancellationRequested();
logger.LogInformation("Applying database migrations (attempt {Attempt}/{MaxRetries})...", attempt, maxRetries);
db.Database.Migrate();
await db.Database.MigrateAsync(migrationCt);
logger.LogInformation("Database migrations applied successfully");
break;
}
@@ -178,7 +202,19 @@ public partial class Program
.GetRequiredService<Microsoft.AspNetCore.Identity.RoleManager<Heimdall.Domain.Entities.AppRole>>();
var userManager = seedScope.ServiceProvider
.GetRequiredService<Microsoft.AspNetCore.Identity.UserManager<Heimdall.Domain.Entities.AppUser>>();
var groupDb = seedScope.ServiceProvider.GetRequiredService<AppDbContext>();
await SeedRolesAsync(roleManager);
await SeedGroupsAsync(groupDb);
var existingKeys = await GetExistingSettingKeysAsync(groupDb);
await SeedStorageSettingsAsync(groupDb, existingKeys);
await SeedIntegrationSettingsAsync(groupDb, existingKeys);
await MigrateLegacySentryKeysAsync(groupDb);
await SeedDemoDataAsync(configuration, userManager, groupDb);
}
private static async Task SeedRolesAsync(Microsoft.AspNetCore.Identity.RoleManager<Heimdall.Domain.Entities.AppRole> roleManager)
{
foreach (var roleName in AppRoles.All)
{
if (!await roleManager.RoleExistsAsync(roleName))
@@ -186,9 +222,10 @@ public partial class Program
await roleManager.CreateAsync(new Heimdall.Domain.Entities.AppRole(roleName));
}
}
}
// Seed default groups (idempotent)
var groupDb = seedScope.ServiceProvider.GetRequiredService<AppDbContext>();
private static async Task SeedGroupsAsync(AppDbContext groupDb)
{
var defaultGroups = new[] { "Administrateurs", "Superviseurs", "Visiteurs", "Techniciens" };
foreach (var groupName in defaultGroups)
{
@@ -206,10 +243,16 @@ public partial class Program
}
}
await groupDb.SaveChangesWithRetryAsync();
}
// Seed des paramètres de stockage (idempotent) — source de vérité DB,
// valeur initiale depuis env pour migration douce (ticket #78/#80).
var storageDefaults = new Dictionary<string, string?>
private static async Task<HashSet<string>> GetExistingSettingKeysAsync(AppDbContext groupDb) =>
new(
await groupDb.AppSettings.Select(s => s.Key).ToListAsync(),
StringComparer.OrdinalIgnoreCase);
private static async Task SeedStorageSettingsAsync(AppDbContext groupDb, HashSet<string> existingKeys)
{
var defaults = new Dictionary<string, string?>
{
["storage.provider"] = Environment.GetEnvironmentVariable("STORAGE__PROVIDER") ?? "Local",
["storage.local.path"] = Environment.GetEnvironmentVariable("STORAGE__LOCAL__PATH") ?? "./data/storage",
@@ -220,17 +263,9 @@ public partial class Program
["storage.s3.secretKey"] = Environment.GetEnvironmentVariable("S3_SECRET_KEY"),
["storage.s3.region"] = Environment.GetEnvironmentVariable("S3_REGION") ?? "us-east-1",
};
// Clés existantes en mémoire (casse ignorée) — le constructeur
// AppSetting lower-case les clés (accessKey → accesskey), et
// string.Equals(OrdinalIgnoreCase) n'est pas traduisible par EF :
// le check idempotent se fait donc côté client sur un HashSet.
var existingAppSettingKeys = new HashSet<string>(
await groupDb.AppSettings.Select(s => s.Key).ToListAsync(),
StringComparer.OrdinalIgnoreCase);
foreach (var (key, value) in storageDefaults)
foreach (var (key, value) in defaults)
{
if (existingAppSettingKeys.Contains(key))
continue;
if (existingKeys.Contains(key)) continue;
groupDb.AppSettings.Add(new Heimdall.Domain.Entities.AppSetting(
key, value ?? string.Empty, "storage",
key switch
@@ -247,10 +282,11 @@ public partial class Program
agentScoped: false));
}
await groupDb.SaveChangesWithRetryAsync();
}
// Seed des paramètres d'intégration (idempotent) — source de vérité DB,
// valeur initiale depuis env pour migration douce (ticket #80).
var integrationDefaults = new Dictionary<string, string?>
private static async Task SeedIntegrationSettingsAsync(AppDbContext groupDb, HashSet<string> existingKeys)
{
var defaults = new Dictionary<string, string?>
{
["ntfy.baseUrl"] = Environment.GetEnvironmentVariable("NTFY__BASE_URL") ?? "https://ntfy.sh",
["ntfy.token"] = Environment.GetEnvironmentVariable("NTFY__TOKEN"),
@@ -269,19 +305,16 @@ public partial class Program
["heartbeat.interval.seconds"] = Environment.GetEnvironmentVariable("HEARTBEAT__INTERVAL_SECONDS") ?? "30",
["sentry.enabled"] = "true",
};
foreach (var (key, value) in integrationDefaults)
foreach (var (key, value) in defaults)
{
if (existingAppSettingKeys.Contains(key))
continue;
// SMTP/ntfy/Sentry = paramètres GLOBAUX (jamais poussés aux agents) ;
// ai.*, log.*, heartbeat.* restent des défauts applicables aux agents.
if (existingKeys.Contains(key)) continue;
var agentScoped = !(key.StartsWith("ntfy.", StringComparison.Ordinal)
|| key.StartsWith("email.", StringComparison.Ordinal)
|| key.StartsWith("sentry.", StringComparison.Ordinal));
var category = ResolveCategory(key);
groupDb.AppSettings.Add(new Heimdall.Domain.Entities.AppSetting(
key, value ?? string.Empty,
key.StartsWith("ntfy.", StringComparison.Ordinal) || key.StartsWith("email.", StringComparison.Ordinal)
? "integrations" : key.StartsWith("ai.", StringComparison.Ordinal) ? "ai" : "agent",
category,
key switch
{
"ntfy.baseUrl" => "Serveur ntfy (URL de base)",
@@ -305,11 +338,10 @@ public partial class Program
agentScoped));
}
await groupDb.SaveChangesWithRetryAsync();
}
// Migration douce (#106) : les clés d'intégration déjà présentes en base
// (créées avant ce changement avec agentScoped=true) doivent passer en
// GLOBAL — jamais exposées aux agents. sentry.dsn n'a plus de rôle
// (DSN fixes en appsettings) → suppression.
private static async Task MigrateLegacySentryKeysAsync(AppDbContext groupDb)
{
await groupDb.AppSettings
.Where(s => s.Key.StartsWith("ntfy.") || s.Key.StartsWith("email.")
|| s.Key.StartsWith("storage.") || s.Key.StartsWith("sentry."))
@@ -319,38 +351,43 @@ public partial class Program
if (legacySentryDsn is not null)
groupDb.AppSettings.Remove(legacySentryDsn);
await groupDb.SaveChangesWithRetryAsync();
}
// Seed demo admin + demo site when explicitly enabled (dev & E2E hosts)
if (configuration.GetValue<bool>("Seed:DemoOnStartup", false))
private static async Task SeedDemoDataAsync(
IConfiguration configuration,
Microsoft.AspNetCore.Identity.UserManager<Heimdall.Domain.Entities.AppUser> userManager,
AppDbContext groupDb)
{
if (!configuration.GetValue<bool>("Seed:DemoOnStartup", false))
return;
var adminLogin = configuration.GetValue<string>("Seed:AdminLogin")
?? Environment.GetEnvironmentVariable("SEED__ADMIN_LOGIN")
?? "admin@heimdall.test";
var testAdmin = await userManager.FindByEmailAsync(adminLogin);
if (testAdmin is null)
{
var adminLogin = configuration.GetValue<string>("Seed:AdminLogin")
?? Environment.GetEnvironmentVariable("SEED__ADMIN_LOGIN")
?? "admin@heimdall.test";
var testAdmin = await userManager.FindByEmailAsync(adminLogin);
if (testAdmin is null)
testAdmin = new Heimdall.Domain.Entities.AppUser
{
testAdmin = new Heimdall.Domain.Entities.AppUser
{
UserName = adminLogin,
Email = adminLogin,
DisplayName = configuration.GetValue<string>("Seed:AdminDisplayName")
?? Environment.GetEnvironmentVariable("SEED__ADMIN_DISPLAYNAME")
?? "Admin"
};
var adminPassword = configuration["Seed:AdminPassword"]
?? Environment.GetEnvironmentVariable("SEED__ADMIN_PASSWORD")
?? throw new InvalidOperationException("Seed:AdminPassword is required in config or SEED__ADMIN_PASSWORD env var. Set this env var to create the demo admin on startup.");
await userManager.CreateAsync(testAdmin, adminPassword);
await userManager.AddToRoleAsync(testAdmin, AppRoles.Admin);
}
UserName = adminLogin,
Email = adminLogin,
DisplayName = configuration.GetValue<string>("Seed:AdminDisplayName")
?? Environment.GetEnvironmentVariable("SEED__ADMIN_DISPLAYNAME")
?? "Admin"
};
var adminPassword = configuration["Seed:AdminPassword"]
?? Environment.GetEnvironmentVariable("SEED__ADMIN_PASSWORD")
?? throw new InvalidOperationException("Seed:AdminPassword is required in config or SEED__ADMIN_PASSWORD env var. Set this env var to create the demo admin on startup.");
await userManager.CreateAsync(testAdmin, adminPassword);
await userManager.AddToRoleAsync(testAdmin, AppRoles.Admin);
}
var demoSite = await groupDb.Sites.FirstOrDefaultAsync(s => s.Name == "Site Démo");
if (demoSite is null)
{
demoSite = new Heimdall.Domain.Entities.Site("Site Démo", "Paris", "Europe/Paris");
groupDb.Sites.Add(demoSite);
await groupDb.SaveChangesWithRetryAsync();
}
var demoSite = await groupDb.Sites.FirstOrDefaultAsync(s => s.Name == "Site Démo");
if (demoSite is null)
{
demoSite = new Heimdall.Domain.Entities.Site("Site Démo", "Paris", "Europe/Paris");
groupDb.Sites.Add(demoSite);
await groupDb.SaveChangesWithRetryAsync();
}
}
@@ -362,11 +399,128 @@ public partial class Program
builder.Services.AddRazorComponents()
.AddInteractiveServerComponents();
// In-memory cache — required by INotificationRateLimiter (singleton)
builder.Services.AddMemoryCache();
// ── Authentication ──────────────────────────────────────────────
ConfigureAuthentication(builder);
ConfigureMudAndRateLimiting(builder);
ConfigureControllers(builder);
ConfigureSignalR(builder);
builder.Services.AddApplication();
builder.Services.AddInfrastructure(builder.Configuration);
ConfigureSentry(builder);
ConfigureAuthScheme(builder);
ConfigureBackgroundJobs(builder);
ConfigureHttpClients(builder);
builder.Services.AddScoped<AuthState>();
}
private static void ConfigureMudAndRateLimiting(WebApplicationBuilder builder)
{
builder.Services.AddMudServices(config =>
{
config.SnackbarConfiguration.PositionClass = "mud-alert-center-top";
config.SnackbarConfiguration.PreventDuplicates = true;
config.SnackbarConfiguration.ShowCloseIcon = true;
config.SnackbarConfiguration.VisibleStateDuration = 4000;
});
builder.Services.AddRateLimiter(options =>
{
options.RejectionStatusCode = 429;
options.AddFixedWindowLimiter("Auth", opt => { opt.PermitLimit = 10; opt.Window = TimeSpan.FromMinutes(1); opt.QueueLimit = 0; });
options.AddFixedWindowLimiter("Api", opt => { opt.PermitLimit = 200; opt.Window = TimeSpan.FromMinutes(1); opt.QueueLimit = 0; });
options.AddFixedWindowLimiter("TwoFactor", opt => { opt.PermitLimit = 5; opt.Window = TimeSpan.FromMinutes(1); opt.QueueLimit = 0; });
});
}
private static void ConfigureControllers(WebApplicationBuilder builder)
{
builder.Services.AddControllers(options =>
options.Filters.Add<Heimdall.Api.Filters.ExceptionFilter>())
.AddJsonOptions(options =>
{
options.JsonSerializerOptions.Converters.Add(
new System.Text.Json.Serialization.JsonStringEnumConverter());
})
.AddApplicationPart(typeof(Program).Assembly);
builder.Services.AddFluentValidationAutoValidation();
builder.Services.Configure<Microsoft.AspNetCore.Http.Json.JsonOptions>(opts =>
opts.SerializerOptions.Converters.Add(new System.Text.Json.Serialization.JsonStringEnumConverter()));
builder.Services.AddOpenApi();
}
private static void ConfigureSignalR(WebApplicationBuilder builder)
{
builder.Services.AddSignalR();
builder.Services.AddScoped<IEventBroadcastService, EventBroadcastService>();
builder.Services.AddScoped<IConfigBroadcastService, ConfigBroadcastService>();
builder.Services.AddScoped<IMonitoringBroadcastService, MonitoringBroadcastService>();
builder.Services.AddScoped<INotificationBroadcastService, NotificationBroadcastService>();
builder.Services.AddScoped<IAdminBroadcastService, AdminBroadcastService>();
}
private static void ConfigureAuthScheme(WebApplicationBuilder builder)
{
builder.Services.Configure<Microsoft.AspNetCore.Authentication.AuthenticationOptions>(options =>
{
options.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = CookieAuthenticationDefaults.AuthenticationScheme;
options.DefaultSignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
});
builder.Services.ConfigureApplicationCookie(options =>
{
options.LoginPath = "/login";
options.LogoutPath = "/_auth/signout";
options.AccessDeniedPath = "/not-found";
options.Cookie.Name = ".Heimdall.Auth";
options.Cookie.HttpOnly = true;
options.Cookie.SameSite = SameSiteMode.Lax;
options.Cookie.SecurePolicy = CookieSecurePolicy.SameAsRequest;
options.ExpireTimeSpan = TimeSpan.FromDays(7);
options.SlidingExpiration = true;
});
}
private static void ConfigureBackgroundJobs(WebApplicationBuilder builder)
{
var isTesting = builder.Environment.IsEnvironment(TestingEnvironment);
var connectionString = Environment.GetEnvironmentVariable("DATABASE_URL")
?? builder.Configuration.GetConnectionString("Default");
if (!isTesting && !string.IsNullOrEmpty(connectionString))
builder.Services.AddBackgroundJobs(builder.Configuration);
}
private static void ConfigureHttpClients(WebApplicationBuilder builder)
{
builder.Services.AddHttpContextAccessor();
builder.Services.AddScoped<HeimdallApiClient>();
builder.Services.AddScoped<NotificationsHubClient>();
builder.Services.AddTransient<TokenRefreshHandler>();
builder.Services.AddTransient<SameOriginHttpMessageHandler>();
var apiBaseUrlConfigured = ApiBaseUrlResolver.IsConfigured(builder.Configuration);
var apiBaseUrl = apiBaseUrlConfigured
? ApiBaseUrlResolver.ResolveConfigured(builder.Configuration)!
: ApiBaseUrlResolver.PlaceholderBase;
builder.Services.AddHttpClient("HeimdallApi", client =>
{
var baseUrl = apiBaseUrl.EndsWith('/') ? apiBaseUrl : apiBaseUrl + "/";
client.BaseAddress = new Uri(baseUrl);
client.Timeout = TimeSpan.FromSeconds(30);
})
.AddHttpMessageHandler<TokenRefreshHandler>()
.AddHttpMessageHandler<SameOriginHttpMessageHandler>();
if (apiBaseUrlConfigured)
Console.WriteLine($"[DIAG] ApiBaseUrl: {apiBaseUrl} (explicit)");
else
Console.WriteLine("[DIAG] ApiBaseUrl: same-origin (no explicit config)");
}
private static void ConfigureAuthentication(WebApplicationBuilder builder)
{
var jwtKey = builder.Configuration["Jwt:Key"]
?? Environment.GetEnvironmentVariable("JWT__KEY")
?? throw new InvalidOperationException("JWT:Key is not configured");
@@ -460,201 +614,60 @@ public partial class Program
builder.Services.AddScoped<HeimdallAuthStateProvider>();
builder.Services.AddScoped<AuthenticationStateProvider>(
sp => sp.GetRequiredService<HeimdallAuthStateProvider>());
}
// ── MudBlazor ─────────────────────────────────────────────────────
builder.Services.AddMudServices(config =>
{
config.SnackbarConfiguration.PositionClass = "mud-alert-center-top";
config.SnackbarConfiguration.PreventDuplicates = true;
config.SnackbarConfiguration.ShowCloseIcon = true;
config.SnackbarConfiguration.VisibleStateDuration = 4000;
});
// ── Rate Limiting ───────────────────────────────────────────────
builder.Services.AddRateLimiter(options =>
{
options.RejectionStatusCode = 429;
options.AddFixedWindowLimiter("Auth", opt => { opt.PermitLimit = 10; opt.Window = TimeSpan.FromMinutes(1); opt.QueueLimit = 0; });
options.AddFixedWindowLimiter("Api", opt => { opt.PermitLimit = 200; opt.Window = TimeSpan.FromMinutes(1); opt.QueueLimit = 0; });
// 2FA codes are high-value, low-volume: tighter limit than the login endpoint.
options.AddFixedWindowLimiter("TwoFactor", opt => { opt.PermitLimit = 5; opt.Window = TimeSpan.FromMinutes(1); opt.QueueLimit = 0; });
});
// ── Controllers (REST API) ────────────────────────────────────────
builder.Services.AddControllers(options =>
options.Filters.Add<Heimdall.Api.Filters.ExceptionFilter>())
.AddJsonOptions(options =>
{
// Serialize enums as strings in API responses (e.g. Agent.Status,
// Camera.Status) — otherwise the Blazor client fails to parse
// numeric enum values into its string-typed models.
options.JsonSerializerOptions.Converters.Add(
new System.Text.Json.Serialization.JsonStringEnumConverter());
})
// Explicitly register the Web assembly as an application part.
// AddMvcCore only auto-discovers Assembly.GetEntryAssembly(), which is
// the test host ("testhost") when CreateTestApplication runs under
// xUnit — without this, no /api/* controller is ever mapped in E2E.
.AddApplicationPart(typeof(Program).Assembly);
builder.Services.AddFluentValidationAutoValidation();
builder.Services.Configure<Microsoft.AspNetCore.Http.Json.JsonOptions>(opts =>
opts.SerializerOptions.Converters.Add(new System.Text.Json.Serialization.JsonStringEnumConverter()));
builder.Services.AddSignalR();
builder.Services.AddScoped<IEventBroadcastService, EventBroadcastService>();
builder.Services.AddScoped<IConfigBroadcastService, ConfigBroadcastService>();
builder.Services.AddScoped<IMonitoringBroadcastService, MonitoringBroadcastService>();
builder.Services.AddScoped<INotificationBroadcastService, NotificationBroadcastService>();
builder.Services.AddScoped<IAdminBroadcastService, AdminBroadcastService>();
builder.Services.AddOpenApi();
// ── Application & Infrastructure layers ──────────────────────────
builder.Services.AddApplication();
builder.Services.AddInfrastructure(builder.Configuration);
// ── Sentry (GlitchTip) — DSN fixe (appsettings), toggle global ──
// Le toggle sentry.enabled est lu en base (après AddInfrastructure) :
// false -> SDK non initialisé (redémarrage requis pour changer).
// Table absente au 1er boot / DB indisponible -> défaut activé.
// SKIP en Testing : pas de table app_settings avant les migrations.
private static void ConfigureSentry(WebApplicationBuilder builder)
{
var sentryDsn = builder.Configuration["Sentry:Dsn"]
?? Environment.GetEnvironmentVariable("SENTRY_DSN");
var isTestingEnv = builder.Environment.IsEnvironment("Testing");
var isTestingEnv = builder.Environment.IsEnvironment(TestingEnvironment);
var sentryEnabled = !isTestingEnv && IsSentryEnabledFromDb(builder.Services);
if (sentryEnabled && !string.IsNullOrEmpty(sentryDsn))
{
builder.WebHost.UseSentry((SentryAspNetCoreOptions options) =>
{
options.Dsn = sentryDsn;
// ── Env & Release ────────────────────────────────────────
options.Release = builder.Configuration["Sentry:Release"]
?? Environment.GetEnvironmentVariable("SENTRY_RELEASE");
// ── Error sampling ──────────────────────────────────────
options.SampleRate = 1.0f;
options.AttachStacktrace = true;
options.MaxBreadcrumbs = 100;
options.MinimumBreadcrumbLevel = LogLevel.Debug;
options.MinimumEventLevel = LogLevel.Error;
// ── Tracing (Performance) ───────────────────────────────
options.TracesSampleRate = double.Parse(
builder.Configuration["Sentry:TracesSampleRate"] ?? "0.05",
System.Globalization.CultureInfo.InvariantCulture);
// ── Request body capture ────────────────────────────────
options.MaxRequestBodySize = Sentry.Extensibility.RequestSize.Small;
// ── Structured logs (v5.14+) ────────────────────────────
options.EnableLogs = true;
// ── GlitchTip-specific: disable unsupported features ────
options.AutoSessionTracking = false;
// ── PII & GDPR ──────────────────────────────────────────
options.SendDefaultPii = false;
options.ServerName = null;
// ── Enhanced diagnostics ────────────────────────────────
options.CaptureBlockingCalls = true;
options.CaptureFailedRequests = true;
options.IncludeActivityData = true;
// ── Stack traces ────────────────────────────────────────
options.StackTraceMode = Sentry.StackTraceMode.Enhanced;
// ── BeforeSend — scrub PII before it leaves the SDK ────
options.SetBeforeSend((sentryEvent, hint) =>
{
sentryEvent.ServerName = null;
if (sentryEvent.Extra?.ContainsKey("password") == true)
(sentryEvent.Extra as IDictionary<string, object?>)?.Remove("password");
if (sentryEvent.Extra?.ContainsKey("token") == true)
(sentryEvent.Extra as IDictionary<string, object?>)?.Remove("token");
if (sentryEvent.Extra?.ContainsKey("secret") == true)
(sentryEvent.Extra as IDictionary<string, object?>)?.Remove("secret");
return sentryEvent;
});
// ── BeforeBreadcrumb — filter noisy breadcrumbs ────────
options.SetBeforeBreadcrumb(breadcrumb
=> breadcrumb.Category == "Microsoft.AspNetCore.RateLimiting"
? null
: breadcrumb);
});
builder.WebHost.UseSentry((SentryAspNetCoreOptions options) => ConfigureSentryOptions(options, builder, sentryDsn));
}
var sentryStatus = !sentryEnabled
? "DISABLED (toggle sentry.enabled=false — redémarrage requis)"
: string.IsNullOrEmpty(sentryDsn)
? "NOT CONFIGURED — errors will NOT be reported to GlitchTip"
: "configured (" + sentryDsn[..sentryDsn.IndexOf('@')] + "@...)";
var sentryStatus = FormatSentryStatus(sentryEnabled, sentryDsn);
Console.WriteLine($"[DIAG] Sentry/GlitchTip DSN: {sentryStatus}");
}
// AddIdentity (inside AddInfrastructure) sets Identity.Application as the
// default authenticate/challenge scheme. But /_auth/signin signs the
// ".Heimdall.Auth" cookie with the "Cookies" scheme. If the default stays
// on Identity.Application, UseAuthentication tries to validate the ticket
// with a DIFFERENT Data Protection purpose -> the cookie is never accepted
// and full page reloads always bounce back to /login.
builder.Services.Configure<Microsoft.AspNetCore.Authentication.AuthenticationOptions>(options =>
private static void ConfigureSentryOptions(SentryAspNetCoreOptions options, WebApplicationBuilder builder, string sentryDsn)
{
options.Dsn = sentryDsn;
options.Release = builder.Configuration["Sentry:Release"]
?? Environment.GetEnvironmentVariable("SENTRY_RELEASE");
options.SampleRate = 1.0f;
options.AttachStacktrace = true;
options.MaxBreadcrumbs = 100;
options.MinimumBreadcrumbLevel = LogLevel.Debug;
options.MinimumEventLevel = LogLevel.Error;
options.TracesSampleRate = double.Parse(
builder.Configuration["Sentry:TracesSampleRate"] ?? "0.05",
System.Globalization.CultureInfo.InvariantCulture);
options.MaxRequestBodySize = Sentry.Extensibility.RequestSize.Small;
options.EnableLogs = true;
options.AutoSessionTracking = false;
options.SendDefaultPii = false;
options.ServerName = null;
options.CaptureBlockingCalls = true;
options.CaptureFailedRequests = true;
options.IncludeActivityData = true;
options.StackTraceMode = Sentry.StackTraceMode.Enhanced;
options.SetBeforeSend(static (sentryEvent, _) =>
{
options.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = CookieAuthenticationDefaults.AuthenticationScheme;
options.DefaultSignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
sentryEvent.ServerName = null;
if (sentryEvent.Extra?.ContainsKey("password") == true)
(sentryEvent.Extra as IDictionary<string, object?>)?.Remove("password");
if (sentryEvent.Extra?.ContainsKey("token") == true)
(sentryEvent.Extra as IDictionary<string, object?>)?.Remove("token");
if (sentryEvent.Extra?.ContainsKey("secret") == true)
(sentryEvent.Extra as IDictionary<string, object?>)?.Remove("secret");
return sentryEvent;
});
// Configure Identity cookie AFTER AddInfrastructure (which calls AddIdentity)
// AddIdentity sets default paths (/Account/Login) that must be overridden
builder.Services.ConfigureApplicationCookie(options =>
{
options.LoginPath = "/login";
options.LogoutPath = "/_auth/signout";
options.AccessDeniedPath = "/not-found";
options.Cookie.Name = ".Heimdall.Auth";
options.Cookie.HttpOnly = true;
options.Cookie.SameSite = SameSiteMode.Lax;
options.Cookie.SecurePolicy = CookieSecurePolicy.SameAsRequest;
options.ExpireTimeSpan = TimeSpan.FromDays(7);
options.SlidingExpiration = true;
});
// ── Background jobs (skipped in Testing) ────────────────────────
var isTesting = builder.Environment.IsEnvironment("Testing");
var connectionString = Environment.GetEnvironmentVariable("DATABASE_URL")
?? builder.Configuration.GetConnectionString("Default");
if (!isTesting && !string.IsNullOrEmpty(connectionString))
builder.Services.AddBackgroundJobs(builder.Configuration);
// ── HTTP client ──────────────────────────────────────────────────
// Blazor Server monolith: the UI and the API run in the same process,
// so requests target the SAME origin as the browser by default. An
// explicit ApiBaseUrl (config/env) overrides that for external APIs.
builder.Services.AddHttpContextAccessor();
builder.Services.AddScoped<HeimdallApiClient>();
builder.Services.AddScoped<NotificationsHubClient>();
builder.Services.AddTransient<TokenRefreshHandler>();
builder.Services.AddTransient<SameOriginHttpMessageHandler>();
var apiBaseUrlConfigured = ApiBaseUrlResolver.IsConfigured(builder.Configuration);
var apiBaseUrl = apiBaseUrlConfigured
? ApiBaseUrlResolver.ResolveConfigured(builder.Configuration)!
: ApiBaseUrlResolver.PlaceholderBase;
builder.Services.AddHttpClient("HeimdallApi", client =>
{
var baseUrl = apiBaseUrl.EndsWith('/') ? apiBaseUrl : apiBaseUrl + "/";
client.BaseAddress = new Uri(baseUrl);
client.Timeout = TimeSpan.FromSeconds(30);
})
.AddHttpMessageHandler<TokenRefreshHandler>()
.AddHttpMessageHandler<SameOriginHttpMessageHandler>();
if (apiBaseUrlConfigured)
Console.WriteLine($"[DIAG] ApiBaseUrl: {apiBaseUrl} (explicit)");
else
Console.WriteLine("[DIAG] ApiBaseUrl: same-origin (no explicit config)");
builder.Services.AddScoped<AuthState>();
options.SetBeforeBreadcrumb(breadcrumb
=> breadcrumb.Category == "Microsoft.AspNetCore.RateLimiting"
? null
: breadcrumb);
}
internal static void ConfigureMiddleware(WebApplication app)
@@ -685,7 +698,7 @@ public partial class Program
// MapHangfireDashboard est utilisé car UseHangfireDashboard avec
// DashboardOptions.Authorization n'existe pas pour les policies ASP.NET.
// Skip en Testing : Hangfire y est désactivé (pas de AddHangfire).
if (!app.Environment.IsEnvironment("Testing"))
if (!app.Environment.IsEnvironment(TestingEnvironment))
{
app.MapHangfireDashboard("/hangfire", new DashboardOptions
{
@@ -705,7 +718,7 @@ public partial class Program
app.MapHub<AdminHub>("/hubs/admin");
// Diagnostic: log all mapped endpoints so E2E host mapping issues are visible.
if (app.Environment.IsEnvironment("Testing"))
if (app.Environment.IsEnvironment(TestingEnvironment))
{
var dataSource = app.Services.GetRequiredService<Microsoft.AspNetCore.Routing.EndpointDataSource>();
var endpoints = dataSource.Endpoints
+43 -20
View File
@@ -82,33 +82,24 @@ public class HeimdallApiClient
if (errors.Value.ValueKind != JsonValueKind.Object)
return Array.Empty<string>();
var messages = new List<string>();
foreach (var field in errors.Value.EnumerateObject())
{
if (field.Value.ValueKind != JsonValueKind.Array) continue;
messages.AddRange(field.Value.EnumerateArray()
return errors.Value.EnumerateObject()
.Where(field => field.Value.ValueKind == JsonValueKind.Array)
.SelectMany(field => field.Value.EnumerateArray()
.Where(item => item.ValueKind == JsonValueKind.String
&& !string.IsNullOrWhiteSpace(item.GetString()))
.Select(item => item.GetString()!));
}
return messages.ToArray();
.Select(item => item.GetString()!))
.ToArray();
}
private static string FallbackErrorMessage(HttpResponseMessage response)
=> $"Erreur du serveur (HTTP {(int)response.StatusCode})";
private static string? FindStringProperty(JsonElement obj, string name)
{
foreach (var prop in obj.EnumerateObject())
{
if (string.Equals(prop.Name, name, StringComparison.OrdinalIgnoreCase)
&& prop.Value.ValueKind == JsonValueKind.String)
return prop.Value.GetString();
}
return null;
}
private static string? FindStringProperty(JsonElement obj, string name) =>
obj.EnumerateObject()
.Where(prop => string.Equals(prop.Name, name, StringComparison.OrdinalIgnoreCase)
&& prop.Value.ValueKind == JsonValueKind.String)
.Select(prop => prop.Value.GetString())
.FirstOrDefault();
// ─── Profile ──────────────────────────────────────────────────
@@ -860,6 +851,38 @@ public class AgentItem
public long? MemoryUsageBytes { get; set; }
public double? DiskUsagePercent { get; set; }
public long? UptimeSeconds { get; set; }
// CPU inventory
public string? CpuVendor { get; set; }
public string? CpuModel { get; set; }
public string? CpuArchitecture { get; set; }
public int? PhysicalCores { get; set; }
public int? LogicalCores { get; set; }
public int? ThreadsPerCore { get; set; }
public double? CpuFrequencyMhz { get; set; }
public string? CpuFlags { get; set; }
public long? CpuCacheBytes { get; set; }
public long? ContainerCpuLimit { get; set; }
// Memory inventory
public long? MemTotalBytes { get; set; }
public long? MemAvailableBytes { get; set; }
public long? SwapTotalBytes { get; set; }
public long? SwapFreeBytes { get; set; }
public long? ContainerMemoryLimitBytes { get; set; }
// Disk inventory
public string? DiskInventoryJson { get; set; }
// GPU inventory
public string? GpuInventoryJson { get; set; }
// Host info
public string? OsName { get; set; }
public string? KernelVersion { get; set; }
public string? Arch { get; set; }
public long? UptimeMachineSeconds { get; set; }
// Container info
public string? ContainerId { get; set; }
public string? ContainerImage { get; set; }
// Network & Temperature
public string? NetworkInterfacesJson { get; set; }
public string? TemperatureJson { get; set; }
}
public class AgentLogItem