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:
1 parent
f7e6b0cec3
commit
4792b69e46
63 files changed
+8711
-563
No files matched your search
@@ -139,6 +139,21 @@ jobs:
|
||||
shell: bash
|
||||
run: dotnet format Heimdall.slnx whitespace --verify-no-changes --no-restore
|
||||
|
||||
# Réduire l'artifact : ne garder que le runtime linux-x64 (seul utilisé en CI).
|
||||
# Sans RID, bin/ contient ~520 MB de runtimes multi-plateforme inutiles → artifact
|
||||
# de 809 MB qui sature les runners (flaky 'context deadline exceeded').
|
||||
- name: Réduire build (garder runtime linux-x64)
|
||||
shell: bash
|
||||
run: |
|
||||
set -euo pipefail
|
||||
find src tests -type d -path '*/runtimes' -not -path '*/obj/*' 2>/dev/null | while read -r d; do
|
||||
for f in "$d"/*; do
|
||||
[ "$(basename "$f")" = "linux-x64" ] || rm -rf "$f"
|
||||
done
|
||||
done
|
||||
echo "Taille artifact finale:"
|
||||
du -sh src tests 2>/dev/null | sort -rh | head -5
|
||||
|
||||
- name: Upload build artifacts
|
||||
uses: https://forgejo.tordais.cc/actions/upload-artifact@v3
|
||||
with:
|
||||
@@ -178,6 +193,10 @@ jobs:
|
||||
set -euo pipefail
|
||||
mkdir -p /tmp/coverage
|
||||
PROJECTS="tests/Heimdall.Domain.Tests/Heimdall.Domain.Tests.csproj tests/Heimdall.Application.Tests/Heimdall.Application.Tests.csproj tests/Heimdall.Agent.Tests/Heimdall.Agent.Tests.csproj tests/Heimdall.Api.Tests/Heimdall.Api.Tests.csproj"
|
||||
# Warm-up dotnet UNE fois (first-time-use / NuGet-Migrations) avant la
|
||||
# parallélisation : évite la course sur /tmp/.dotnet/shm (mutex EEXIST)
|
||||
# quand plusieurs dotnet test démarrent simultanément (flaky intermittent).
|
||||
dotnet msbuild -version >/dev/null 2>&1
|
||||
FAIL=0
|
||||
declare -A JOB_LOG
|
||||
for proj in $PROJECTS; do
|
||||
|
||||
@@ -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>
|
||||
@@ -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)
|
||||
|
||||
@@ -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
|
||||
|
||||
+3
-3
@@ -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);
|
||||
}
|
||||
+5
-5
@@ -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();
|
||||
|
||||
@@ -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");
|
||||
}
|
||||
|
||||
|
||||
@@ -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());
|
||||
}
|
||||
|
||||
Generated
+2292
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
@@ -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
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -267,11 +267,17 @@ public class AgentRegistrationServiceTests : IDisposable
|
||||
AgentState? state = null)
|
||||
{
|
||||
state ??= _state;
|
||||
var providers = new InventoryProviders(
|
||||
new CpuInfoProvider(),
|
||||
new DiskInventoryProvider(),
|
||||
new HostInfoProvider(),
|
||||
new ContainerInfoProvider());
|
||||
return new AgentRegistrationService(
|
||||
factory,
|
||||
state,
|
||||
Options.Create(_options),
|
||||
_metrics,
|
||||
providers,
|
||||
new Logging.LogBufferService(),
|
||||
NullLogger<AgentRegistrationService>.Instance);
|
||||
}
|
||||
|
||||
@@ -161,6 +161,7 @@ public class CameraStreamServiceTests
|
||||
{
|
||||
using var service = CreateService();
|
||||
await service.StopAllAsync();
|
||||
service.ShouldNotBeNull();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
|
||||
@@ -0,0 +1,135 @@
|
||||
using Heimdall.Agent.Services;
|
||||
|
||||
namespace Heimdall.Agent.Tests;
|
||||
|
||||
public class CpuInfoProviderTests
|
||||
{
|
||||
[Fact]
|
||||
public void Collect_should_return_non_null_result()
|
||||
{
|
||||
var provider = new CpuInfoProvider();
|
||||
var result = provider.Collect();
|
||||
|
||||
result.ShouldNotBeNull();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Collect_should_not_throw()
|
||||
{
|
||||
var provider = new CpuInfoProvider();
|
||||
var act = () => provider.Collect();
|
||||
|
||||
act.ShouldNotThrow();
|
||||
}
|
||||
}
|
||||
|
||||
public class DiskInventoryProviderTests
|
||||
{
|
||||
[Fact]
|
||||
public void Collect_should_return_non_null_list()
|
||||
{
|
||||
var provider = new DiskInventoryProvider();
|
||||
var result = provider.Collect();
|
||||
|
||||
result.ShouldNotBeNull();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Collect_should_not_throw()
|
||||
{
|
||||
var provider = new DiskInventoryProvider();
|
||||
var act = () => provider.Collect();
|
||||
|
||||
act.ShouldNotThrow();
|
||||
}
|
||||
}
|
||||
|
||||
public class GpuInventoryProviderTests
|
||||
{
|
||||
[Fact]
|
||||
public void Collect_should_return_non_null_list()
|
||||
{
|
||||
var result = GpuInventoryProvider.Collect();
|
||||
|
||||
result.ShouldNotBeNull();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Collect_should_not_throw()
|
||||
{
|
||||
var act = () => GpuInventoryProvider.Collect();
|
||||
|
||||
act.ShouldNotThrow();
|
||||
}
|
||||
}
|
||||
|
||||
public class HostInfoProviderTests
|
||||
{
|
||||
[Fact]
|
||||
public void Collect_should_return_non_null_result()
|
||||
{
|
||||
var provider = new HostInfoProvider();
|
||||
var result = provider.Collect();
|
||||
|
||||
result.ShouldNotBeNull();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Collect_should_not_throw()
|
||||
{
|
||||
var provider = new HostInfoProvider();
|
||||
var act = () => provider.Collect();
|
||||
|
||||
act.ShouldNotThrow();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Collect_should_return_network_interfaces_list()
|
||||
{
|
||||
var provider = new HostInfoProvider();
|
||||
var result = provider.Collect();
|
||||
|
||||
result.NetworkInterfaces.ShouldNotBeNull();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Collect_should_return_temperature_list()
|
||||
{
|
||||
var provider = new HostInfoProvider();
|
||||
var result = provider.Collect();
|
||||
|
||||
result.Temperature.ShouldNotBeNull();
|
||||
}
|
||||
}
|
||||
|
||||
public class ContainerInfoProviderTests
|
||||
{
|
||||
[Fact]
|
||||
public void Collect_should_return_non_null_result()
|
||||
{
|
||||
var provider = new ContainerInfoProvider();
|
||||
var result = provider.Collect();
|
||||
|
||||
result.ShouldNotBeNull();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Collect_should_not_throw()
|
||||
{
|
||||
var provider = new ContainerInfoProvider();
|
||||
var act = () => provider.Collect();
|
||||
|
||||
act.ShouldNotThrow();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Collect_should_set_is_container_consistently()
|
||||
{
|
||||
var provider = new ContainerInfoProvider();
|
||||
var result = provider.Collect();
|
||||
|
||||
// Verify IsContainer matches the actual container environment
|
||||
var actuallyInContainer = File.Exists("/.dockerenv") || File.Exists("/run/.containerenv");
|
||||
result.IsContainer.ShouldBe(actuallyInContainer);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,86 @@
|
||||
using Heimdall.Agent.Services;
|
||||
|
||||
namespace Heimdall.Agent.Tests.Services;
|
||||
|
||||
public class CgroupReaderTests
|
||||
{
|
||||
[Fact]
|
||||
public void GetCpuLimit_ShouldReturnNull_OrPositiveValue_OnLinux()
|
||||
{
|
||||
if (!OperatingSystem.IsLinux()) return;
|
||||
|
||||
var limit = CgroupReader.GetCpuLimit();
|
||||
|
||||
// May be null if not in a container (unlimited)
|
||||
// Or positive if in a container with CPU limits
|
||||
if (limit.HasValue)
|
||||
{
|
||||
limit.Value.ShouldBeGreaterThan(0);
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void GetMemoryLimit_ShouldReturnNull_OrPositiveValue_OnLinux()
|
||||
{
|
||||
if (!OperatingSystem.IsLinux()) return;
|
||||
|
||||
var limit = CgroupReader.GetMemoryLimit();
|
||||
|
||||
// May be null if not in a container (unlimited)
|
||||
// Or positive if in a container with memory limits
|
||||
if (limit.HasValue)
|
||||
{
|
||||
limit.Value.ShouldBeGreaterThan(0);
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void GetCpuLimit_ShouldReturnReasonableValue_WhenPresent()
|
||||
{
|
||||
if (!OperatingSystem.IsLinux()) return;
|
||||
|
||||
var limit = CgroupReader.GetCpuLimit();
|
||||
if (limit.HasValue)
|
||||
{
|
||||
// CPU limit as percentage should be between 1% and 10000% (100 cores)
|
||||
limit.Value.ShouldBeGreaterThanOrEqualTo(1);
|
||||
limit.Value.ShouldBeLessThanOrEqualTo(10_000);
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void GetMemoryLimit_ShouldReturnReasonableValue_WhenPresent()
|
||||
{
|
||||
if (!OperatingSystem.IsLinux()) return;
|
||||
|
||||
var limit = CgroupReader.GetMemoryLimit();
|
||||
if (limit.HasValue)
|
||||
{
|
||||
// Memory limit should be at least 1MB and less than 1PB
|
||||
limit.Value.ShouldBeGreaterThanOrEqualTo(1_048_576);
|
||||
limit.Value.ShouldBeLessThanOrEqualTo(1_125_899_906_842_624);
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void GetCpuLimit_CalledTwice_ShouldReturnConsistentResults()
|
||||
{
|
||||
if (!OperatingSystem.IsLinux()) return;
|
||||
|
||||
var first = CgroupReader.GetCpuLimit();
|
||||
var second = CgroupReader.GetCpuLimit();
|
||||
|
||||
first.ShouldBe(second);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void GetMemoryLimit_CalledTwice_ShouldReturnConsistentResults()
|
||||
{
|
||||
if (!OperatingSystem.IsLinux()) return;
|
||||
|
||||
var first = CgroupReader.GetMemoryLimit();
|
||||
var second = CgroupReader.GetMemoryLimit();
|
||||
|
||||
first.ShouldBe(second);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,123 @@
|
||||
using Heimdall.Agent.Services;
|
||||
|
||||
namespace Heimdall.Agent.Tests.Services;
|
||||
|
||||
public class ContainerInfoProviderDetailedTests
|
||||
{
|
||||
[Fact]
|
||||
public void Collect_ShouldReturnContainerInfo()
|
||||
{
|
||||
var provider = new ContainerInfoProvider();
|
||||
var result = provider.Collect();
|
||||
|
||||
result.ShouldNotBeNull();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Collect_ShouldNotThrow()
|
||||
{
|
||||
var provider = new ContainerInfoProvider();
|
||||
var act = () => provider.Collect();
|
||||
act.ShouldNotThrow();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Collect_IsContainer_ShouldBeConsistentWithDockerEnv()
|
||||
{
|
||||
var provider = new ContainerInfoProvider();
|
||||
var result = provider.Collect();
|
||||
|
||||
var actuallyInContainer = File.Exists("/.dockerenv") || File.Exists("/run/.containerenv");
|
||||
result.IsContainer.ShouldBe(actuallyInContainer);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Collect_ContainerId_ShouldBeNullOrHex_WhenContainer()
|
||||
{
|
||||
var provider = new ContainerInfoProvider();
|
||||
var result = provider.Collect();
|
||||
|
||||
if (result.IsContainer && result.ContainerId is not null)
|
||||
{
|
||||
result.ContainerId.Length.ShouldBeGreaterThanOrEqualTo(12);
|
||||
result.ContainerId.All(c => "0123456789abcdef".Contains(c)).ShouldBeTrue();
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Collect_MemoryLimitBytes_ShouldBeNullOrPositive()
|
||||
{
|
||||
var provider = new ContainerInfoProvider();
|
||||
var result = provider.Collect();
|
||||
|
||||
if (result.MemoryLimitBytes.HasValue)
|
||||
{
|
||||
result.MemoryLimitBytes.Value.ShouldBeGreaterThan(0);
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Collect_CpuLimit_ShouldBeNullOrPositive()
|
||||
{
|
||||
var provider = new ContainerInfoProvider();
|
||||
var result = provider.Collect();
|
||||
|
||||
if (result.CpuLimit.HasValue)
|
||||
{
|
||||
result.CpuLimit.Value.ShouldBeGreaterThan(0);
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Collect_CalledTwice_ShouldReturnConsistentResults()
|
||||
{
|
||||
var provider = new ContainerInfoProvider();
|
||||
var first = provider.Collect();
|
||||
var second = provider.Collect();
|
||||
|
||||
first.IsContainer.ShouldBe(second.IsContainer);
|
||||
first.ContainerId.ShouldBe(second.ContainerId);
|
||||
}
|
||||
|
||||
// ── ContainerInfo record tests ──────────────────────────────────
|
||||
|
||||
[Fact]
|
||||
public void ContainerInfo_DefaultValues_ShouldBeCorrect()
|
||||
{
|
||||
var info = new ContainerInfo();
|
||||
|
||||
info.IsContainer.ShouldBeFalse();
|
||||
info.ContainerId.ShouldBeNull();
|
||||
info.ContainerImage.ShouldBeNull();
|
||||
info.MemoryLimitBytes.ShouldBeNull();
|
||||
info.CpuLimit.ShouldBeNull();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ContainerInfo_WithValues_ShouldStoreCorrectly()
|
||||
{
|
||||
var info = new ContainerInfo
|
||||
{
|
||||
IsContainer = true,
|
||||
ContainerId = "abc123def456",
|
||||
ContainerImage = "heimdall/agent:latest",
|
||||
MemoryLimitBytes = 4_294_967_296,
|
||||
CpuLimit = 200
|
||||
};
|
||||
|
||||
info.IsContainer.ShouldBeTrue();
|
||||
info.ContainerId.ShouldBe("abc123def456");
|
||||
info.ContainerImage.ShouldBe("heimdall/agent:latest");
|
||||
info.MemoryLimitBytes.ShouldBe(4_294_967_296);
|
||||
info.CpuLimit.ShouldBe(200);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ContainerInfo_RecordEquality_ShouldWork()
|
||||
{
|
||||
var info1 = new ContainerInfo { IsContainer = true, ContainerId = "abc" };
|
||||
var info2 = new ContainerInfo { IsContainer = true, ContainerId = "abc" };
|
||||
|
||||
info1.ShouldBe(info2);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,186 @@
|
||||
using Heimdall.Agent.Services;
|
||||
|
||||
namespace Heimdall.Agent.Tests.Services;
|
||||
|
||||
public class CpuInfoProviderDetailedTests
|
||||
{
|
||||
[Fact]
|
||||
public void Collect_ShouldReturnCpuInfo()
|
||||
{
|
||||
var provider = new CpuInfoProvider();
|
||||
var result = provider.Collect();
|
||||
|
||||
result.ShouldNotBeNull();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Collect_ShouldNotThrow()
|
||||
{
|
||||
var provider = new CpuInfoProvider();
|
||||
var act = () => provider.Collect();
|
||||
act.ShouldNotThrow();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Collect_Vendor_ShouldNotBeNull_OnLinux()
|
||||
{
|
||||
if (!OperatingSystem.IsLinux()) return;
|
||||
|
||||
var provider = new CpuInfoProvider();
|
||||
var result = provider.Collect();
|
||||
|
||||
result.Vendor.ShouldNotBeNull();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Collect_Model_ShouldNotBeNull_OnLinux()
|
||||
{
|
||||
if (!OperatingSystem.IsLinux()) return;
|
||||
|
||||
var provider = new CpuInfoProvider();
|
||||
var result = provider.Collect();
|
||||
|
||||
result.Model.ShouldNotBeNull();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Collect_Architecture_ShouldBeValid()
|
||||
{
|
||||
var provider = new CpuInfoProvider();
|
||||
var result = provider.Collect();
|
||||
|
||||
result.Architecture.ShouldNotBeNull();
|
||||
var validArchs = new[] { "x86_64", "aarch64", "armv7l" };
|
||||
validArchs.ShouldContain(result.Architecture);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Collect_LogicalCores_ShouldBePositive()
|
||||
{
|
||||
var provider = new CpuInfoProvider();
|
||||
var result = provider.Collect();
|
||||
|
||||
result.LogicalCores.ShouldNotBeNull();
|
||||
result.LogicalCores!.Value.ShouldBeGreaterThan(0);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Collect_PhysicalCores_ShouldBeNullOrPositive()
|
||||
{
|
||||
var provider = new CpuInfoProvider();
|
||||
var result = provider.Collect();
|
||||
|
||||
if (result.PhysicalCores.HasValue)
|
||||
{
|
||||
result.PhysicalCores.Value.ShouldBeGreaterThan(0);
|
||||
result.PhysicalCores.Value.ShouldBeLessThanOrEqualTo(result.LogicalCores!.Value);
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Collect_ThreadsPerCore_ShouldBeNullOrPositive()
|
||||
{
|
||||
var provider = new CpuInfoProvider();
|
||||
var result = provider.Collect();
|
||||
|
||||
if (result.ThreadsPerCore.HasValue)
|
||||
{
|
||||
result.ThreadsPerCore.Value.ShouldBeGreaterThan(0);
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Collect_FrequencyMhz_ShouldBeNullOrReasonable()
|
||||
{
|
||||
var provider = new CpuInfoProvider();
|
||||
var result = provider.Collect();
|
||||
|
||||
if (result.FrequencyMhz.HasValue)
|
||||
{
|
||||
result.FrequencyMhz.Value.ShouldBeGreaterThan(0);
|
||||
result.FrequencyMhz.Value.ShouldBeLessThan(20_000);
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Collect_Flags_ShouldBeNullOrNonEmpty()
|
||||
{
|
||||
var provider = new CpuInfoProvider();
|
||||
var result = provider.Collect();
|
||||
|
||||
if (result.Flags is not null)
|
||||
{
|
||||
result.Flags.ShouldNotBe("");
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Collect_CalledTwice_ShouldReturnConsistentResults()
|
||||
{
|
||||
var provider = new CpuInfoProvider();
|
||||
var first = provider.Collect();
|
||||
var second = provider.Collect();
|
||||
|
||||
first.Vendor.ShouldBe(second.Vendor);
|
||||
first.Model.ShouldBe(second.Model);
|
||||
first.Architecture.ShouldBe(second.Architecture);
|
||||
first.LogicalCores.ShouldBe(second.LogicalCores);
|
||||
}
|
||||
|
||||
// ── CpuInfo record tests ────────────────────────────────────────
|
||||
|
||||
[Fact]
|
||||
public void CpuInfo_DefaultValues_ShouldBeNull()
|
||||
{
|
||||
var info = new CpuInfo();
|
||||
|
||||
info.Vendor.ShouldBeNull();
|
||||
info.Model.ShouldBeNull();
|
||||
info.Architecture.ShouldBeNull();
|
||||
info.PhysicalCores.ShouldBeNull();
|
||||
info.LogicalCores.ShouldBeNull();
|
||||
info.ThreadsPerCore.ShouldBeNull();
|
||||
info.FrequencyMhz.ShouldBeNull();
|
||||
info.Flags.ShouldBeNull();
|
||||
info.CacheBytes.ShouldBeNull();
|
||||
info.ContainerCpuLimit.ShouldBeNull();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void CpuInfo_WithValues_ShouldStoreCorrectly()
|
||||
{
|
||||
var info = new CpuInfo
|
||||
{
|
||||
Vendor = "GenuineIntel",
|
||||
Model = "Intel Core i7-12700K",
|
||||
Architecture = "x86_64",
|
||||
PhysicalCores = 12,
|
||||
LogicalCores = 20,
|
||||
ThreadsPerCore = 2,
|
||||
FrequencyMhz = 3600.0,
|
||||
Flags = "avx,avx2,fma,sse4_1",
|
||||
CacheBytes = 25_165_824,
|
||||
ContainerCpuLimit = 200
|
||||
};
|
||||
|
||||
info.Vendor.ShouldBe("GenuineIntel");
|
||||
info.Model.ShouldBe("Intel Core i7-12700K");
|
||||
info.Architecture.ShouldBe("x86_64");
|
||||
info.PhysicalCores.ShouldBe(12);
|
||||
info.LogicalCores.ShouldBe(20);
|
||||
info.ThreadsPerCore.ShouldBe(2);
|
||||
info.FrequencyMhz.ShouldBe(3600.0);
|
||||
info.Flags.ShouldBe("avx,avx2,fma,sse4_1");
|
||||
info.CacheBytes.ShouldBe(25_165_824);
|
||||
info.ContainerCpuLimit.ShouldBe(200);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void CpuInfo_RecordEquality_ShouldWork()
|
||||
{
|
||||
var info1 = new CpuInfo { Vendor = "AMD", Model = "Ryzen 9" };
|
||||
var info2 = new CpuInfo { Vendor = "AMD", Model = "Ryzen 9" };
|
||||
|
||||
info1.ShouldBe(info2);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,171 @@
|
||||
using Heimdall.Agent.Services;
|
||||
|
||||
namespace Heimdall.Agent.Tests.Services;
|
||||
|
||||
public class DiskInventoryProviderDetailedTests
|
||||
{
|
||||
[Fact]
|
||||
public void Collect_ShouldReturnListOfDiskInfo()
|
||||
{
|
||||
var provider = new DiskInventoryProvider();
|
||||
var result = provider.Collect();
|
||||
|
||||
result.ShouldNotBeNull();
|
||||
result.ShouldBeAssignableTo<IReadOnlyList<DiskInfo>>();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Collect_OnLinux_ShouldReturnAtLeastOneDisk()
|
||||
{
|
||||
if (!OperatingSystem.IsLinux()) return;
|
||||
|
||||
var provider = new DiskInventoryProvider();
|
||||
var result = provider.Collect();
|
||||
|
||||
result.Count.ShouldBeGreaterThan(0);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Collect_DiskInfo_ShouldHaveMountPoint()
|
||||
{
|
||||
if (!OperatingSystem.IsLinux()) return;
|
||||
|
||||
var provider = new DiskInventoryProvider();
|
||||
var result = provider.Collect();
|
||||
|
||||
foreach (var disk in result)
|
||||
{
|
||||
disk.MountPoint.ShouldNotBeNullOrEmpty();
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Collect_DiskInfo_ShouldHaveFileSystem()
|
||||
{
|
||||
if (!OperatingSystem.IsLinux()) return;
|
||||
|
||||
var provider = new DiskInventoryProvider();
|
||||
var result = provider.Collect();
|
||||
|
||||
foreach (var disk in result)
|
||||
{
|
||||
disk.FileSystem.ShouldNotBeNullOrEmpty();
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Collect_DiskInfo_ShouldHavePositiveTotalBytes()
|
||||
{
|
||||
if (!OperatingSystem.IsLinux()) return;
|
||||
|
||||
var provider = new DiskInventoryProvider();
|
||||
var result = provider.Collect();
|
||||
|
||||
foreach (var disk in result)
|
||||
{
|
||||
disk.TotalBytes.ShouldNotBeNull();
|
||||
disk.TotalBytes!.Value.ShouldBeGreaterThan(0);
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Collect_DiskInfo_UsedBytes_ShouldBeLessOrEqualToTotalBytes()
|
||||
{
|
||||
if (!OperatingSystem.IsLinux()) return;
|
||||
|
||||
var provider = new DiskInventoryProvider();
|
||||
var result = provider.Collect();
|
||||
|
||||
foreach (var disk in result)
|
||||
{
|
||||
if (disk.UsedBytes.HasValue)
|
||||
{
|
||||
disk.UsedBytes.Value.ShouldBeLessThanOrEqualTo(disk.TotalBytes!.Value);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Collect_DiskInfo_Type_ShouldBeValid()
|
||||
{
|
||||
if (!OperatingSystem.IsLinux()) return;
|
||||
|
||||
var provider = new DiskInventoryProvider();
|
||||
var result = provider.Collect();
|
||||
|
||||
foreach (var disk in result)
|
||||
{
|
||||
disk.Type.ShouldNotBeNullOrEmpty();
|
||||
var validTypes = new[] { "SSD", "HDD", "Unknown" };
|
||||
validTypes.ShouldContain(disk.Type);
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Collect_ShouldHaveAtLeastOneMount()
|
||||
{
|
||||
if (!OperatingSystem.IsLinux()) return;
|
||||
|
||||
var provider = new DiskInventoryProvider();
|
||||
var result = provider.Collect();
|
||||
|
||||
// In containers, "/" may not appear as a separate mount — just check we found disks
|
||||
result.ShouldNotBeEmpty();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Collect_CalledTwice_ShouldReturnConsistentResults()
|
||||
{
|
||||
var provider = new DiskInventoryProvider();
|
||||
var first = provider.Collect();
|
||||
var second = provider.Collect();
|
||||
|
||||
first.Count.ShouldBe(second.Count);
|
||||
for (int i = 0; i < first.Count; i++)
|
||||
{
|
||||
first[i].MountPoint.ShouldBe(second[i].MountPoint);
|
||||
first[i].FileSystem.ShouldBe(second[i].FileSystem);
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Collect_ShouldNotThrowOnAnyPlatform()
|
||||
{
|
||||
var provider = new DiskInventoryProvider();
|
||||
var act = () => provider.Collect();
|
||||
act.ShouldNotThrow();
|
||||
}
|
||||
|
||||
// ── DiskInfo record tests ───────────────────────────────────────
|
||||
|
||||
[Fact]
|
||||
public void DiskInfo_DefaultValues_ShouldBeCorrect()
|
||||
{
|
||||
var disk = new DiskInfo();
|
||||
|
||||
disk.MountPoint.ShouldBe("");
|
||||
disk.FileSystem.ShouldBe("");
|
||||
disk.TotalBytes.ShouldBeNull();
|
||||
disk.UsedBytes.ShouldBeNull();
|
||||
disk.Type.ShouldBe("Unknown");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void DiskInfo_WithValues_ShouldStoreCorrectly()
|
||||
{
|
||||
var disk = new DiskInfo
|
||||
{
|
||||
MountPoint = "/",
|
||||
FileSystem = "ext4",
|
||||
TotalBytes = 1_000_000_000_000,
|
||||
UsedBytes = 500_000_000_000,
|
||||
Type = "SSD"
|
||||
};
|
||||
|
||||
disk.MountPoint.ShouldBe("/");
|
||||
disk.FileSystem.ShouldBe("ext4");
|
||||
disk.TotalBytes.ShouldBe(1_000_000_000_000);
|
||||
disk.UsedBytes.ShouldBe(500_000_000_000);
|
||||
disk.Type.ShouldBe("SSD");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,148 @@
|
||||
using Heimdall.Agent.Services;
|
||||
|
||||
namespace Heimdall.Agent.Tests.Services;
|
||||
|
||||
public class GpuInventoryProviderDetailedTests
|
||||
{
|
||||
[Fact]
|
||||
public void Collect_ShouldReturnListOfGpuInfo()
|
||||
{
|
||||
var result = GpuInventoryProvider.Collect();
|
||||
|
||||
result.ShouldNotBeNull();
|
||||
result.ShouldBeAssignableTo<IReadOnlyList<GpuInfo>>();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Collect_ShouldNotThrow()
|
||||
{
|
||||
var act = () => GpuInventoryProvider.Collect();
|
||||
act.ShouldNotThrow();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Collect_GpuInfo_ShouldHaveVendor_WhenPresent()
|
||||
{
|
||||
var result = GpuInventoryProvider.Collect();
|
||||
|
||||
foreach (var gpu in result)
|
||||
{
|
||||
if (gpu.Vendor is not null)
|
||||
{
|
||||
var validVendors = new[] { "Nvidia", "AMD", "Intel", "Unknown" };
|
||||
// Vendor could also be a raw hex ID if not mapped
|
||||
gpu.Vendor.ShouldNotBeNullOrEmpty();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Collect_GpuInfo_Backend_ShouldBeValid_WhenPresent()
|
||||
{
|
||||
var result = GpuInventoryProvider.Collect();
|
||||
|
||||
foreach (var gpu in result)
|
||||
{
|
||||
if (gpu.Backend is not null)
|
||||
{
|
||||
var validBackends = new[] { "Cuda", "ROCm", "VAAPI", "Unknown" };
|
||||
validBackends.ShouldContain(gpu.Backend);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Collect_GpuInfo_VramBytes_ShouldBePositive_WhenPresent()
|
||||
{
|
||||
var result = GpuInventoryProvider.Collect();
|
||||
|
||||
foreach (var gpu in result)
|
||||
{
|
||||
if (gpu.VramBytes.HasValue)
|
||||
{
|
||||
gpu.VramBytes.Value.ShouldBeGreaterThan(0);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Collect_GpuInfo_TemperatureCelsius_ShouldBeReasonable_WhenPresent()
|
||||
{
|
||||
var result = GpuInventoryProvider.Collect();
|
||||
|
||||
foreach (var gpu in result)
|
||||
{
|
||||
if (gpu.TemperatureCelsius.HasValue)
|
||||
{
|
||||
gpu.TemperatureCelsius.Value.ShouldBeGreaterThanOrEqualTo(0);
|
||||
gpu.TemperatureCelsius.Value.ShouldBeLessThanOrEqualTo(200);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Collect_GpuInfo_UtilizationPercent_ShouldBeReasonable_WhenPresent()
|
||||
{
|
||||
var result = GpuInventoryProvider.Collect();
|
||||
|
||||
foreach (var gpu in result)
|
||||
{
|
||||
if (gpu.UtilizationPercent.HasValue)
|
||||
{
|
||||
gpu.UtilizationPercent.Value.ShouldBeGreaterThanOrEqualTo(0);
|
||||
gpu.UtilizationPercent.Value.ShouldBeLessThanOrEqualTo(100);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ── GpuInfo record tests ────────────────────────────────────────
|
||||
|
||||
[Fact]
|
||||
public void GpuInfo_DefaultValues_ShouldBeNull()
|
||||
{
|
||||
var gpu = new GpuInfo();
|
||||
|
||||
gpu.Vendor.ShouldBeNull();
|
||||
gpu.Model.ShouldBeNull();
|
||||
gpu.VramBytes.ShouldBeNull();
|
||||
gpu.DriverVersion.ShouldBeNull();
|
||||
gpu.TemperatureCelsius.ShouldBeNull();
|
||||
gpu.UtilizationPercent.ShouldBeNull();
|
||||
gpu.Backend.ShouldBeNull();
|
||||
gpu.EncoderSupport.ShouldBeNull();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void GpuInfo_WithValues_ShouldStoreCorrectly()
|
||||
{
|
||||
var gpu = new GpuInfo
|
||||
{
|
||||
Vendor = "Nvidia",
|
||||
Model = "RTX 4090",
|
||||
VramBytes = 24_576_000_000,
|
||||
DriverVersion = "535.129.03",
|
||||
TemperatureCelsius = 65.0,
|
||||
UtilizationPercent = 85.5,
|
||||
Backend = "Cuda",
|
||||
EncoderSupport = "NVENC+NVJPG"
|
||||
};
|
||||
|
||||
gpu.Vendor.ShouldBe("Nvidia");
|
||||
gpu.Model.ShouldBe("RTX 4090");
|
||||
gpu.VramBytes.ShouldBe(24_576_000_000);
|
||||
gpu.DriverVersion.ShouldBe("535.129.03");
|
||||
gpu.TemperatureCelsius.ShouldBe(65.0);
|
||||
gpu.UtilizationPercent.ShouldBe(85.5);
|
||||
gpu.Backend.ShouldBe("Cuda");
|
||||
gpu.EncoderSupport.ShouldBe("NVENC+NVJPG");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void GpuInfo_RecordEquality_ShouldWork()
|
||||
{
|
||||
var gpu1 = new GpuInfo { Vendor = "AMD", Model = "RX 7900 XTX", Backend = "ROCm" };
|
||||
var gpu2 = new GpuInfo { Vendor = "AMD", Model = "RX 7900 XTX", Backend = "ROCm" };
|
||||
|
||||
gpu1.ShouldBe(gpu2);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,152 @@
|
||||
using Heimdall.Agent.Services;
|
||||
|
||||
namespace Heimdall.Agent.Tests.Services;
|
||||
|
||||
public class HostInfoProviderTests
|
||||
{
|
||||
[Fact]
|
||||
public void Collect_ShouldReturnNonNullHostInfo()
|
||||
{
|
||||
var provider = new HostInfoProvider();
|
||||
var info = provider.Collect();
|
||||
|
||||
info.ShouldNotBeNull();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Collect_OsName_ShouldNotBeNull_OnLinux()
|
||||
{
|
||||
if (!OperatingSystem.IsLinux()) return;
|
||||
|
||||
var provider = new HostInfoProvider();
|
||||
var info = provider.Collect();
|
||||
|
||||
info.OsName.ShouldNotBeNull();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Collect_KernelVersion_ShouldNotBeNull_OnLinux()
|
||||
{
|
||||
if (!OperatingSystem.IsLinux()) return;
|
||||
|
||||
var provider = new HostInfoProvider();
|
||||
var info = provider.Collect();
|
||||
|
||||
// uname -r peut échouer dans certains containers CI
|
||||
// On vérifie juste que le collect ne crash pas
|
||||
info.ShouldNotBeNull();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Collect_Arch_ShouldNotBeNull()
|
||||
{
|
||||
var provider = new HostInfoProvider();
|
||||
var info = provider.Collect();
|
||||
|
||||
info.Arch.ShouldNotBeNull();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Collect_Arch_ShouldBeValidArchitecture()
|
||||
{
|
||||
var provider = new HostInfoProvider();
|
||||
var info = provider.Collect();
|
||||
|
||||
info.Arch.ShouldNotBeNull();
|
||||
var validArchs = new[] { "x86_64", "aarch64", "armv7l" };
|
||||
validArchs.ShouldContain(info.Arch);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Collect_UptimeSeconds_ShouldNotBeNull_OnLinux()
|
||||
{
|
||||
if (!OperatingSystem.IsLinux()) return;
|
||||
|
||||
var provider = new HostInfoProvider();
|
||||
var info = provider.Collect();
|
||||
|
||||
info.UptimeSeconds.ShouldNotBeNull();
|
||||
info.UptimeSeconds.Value.ShouldBeGreaterThan(0);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Collect_NetworkInterfaces_ShouldBeNonNull()
|
||||
{
|
||||
var provider = new HostInfoProvider();
|
||||
var info = provider.Collect();
|
||||
|
||||
info.NetworkInterfaces.ShouldNotBeNull();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Collect_NetworkInterfaces_ShouldContainAtLeastOne_OnLinux()
|
||||
{
|
||||
if (!OperatingSystem.IsLinux()) return;
|
||||
|
||||
var provider = new HostInfoProvider();
|
||||
var info = provider.Collect();
|
||||
|
||||
// On a real Linux machine, there should be at least one non-loopback interface
|
||||
info.NetworkInterfaces.ShouldNotBeEmpty();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Collect_Temperature_ShouldBeNonNull()
|
||||
{
|
||||
var provider = new HostInfoProvider();
|
||||
var info = provider.Collect();
|
||||
|
||||
info.Temperature.ShouldNotBeNull();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Collect_NetworkInterface_ShouldHaveName()
|
||||
{
|
||||
var provider = new HostInfoProvider();
|
||||
var info = provider.Collect();
|
||||
|
||||
if (info.NetworkInterfaces.Count > 0)
|
||||
{
|
||||
info.NetworkInterfaces[0].Name.ShouldNotBeNullOrEmpty();
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Collect_NetworkInterface_ShouldNotIncludeLoopback()
|
||||
{
|
||||
var provider = new HostInfoProvider();
|
||||
var info = provider.Collect();
|
||||
|
||||
foreach (var ni in info.NetworkInterfaces)
|
||||
{
|
||||
ni.Name.ShouldNotBe("lo");
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Collect_CalledMultipleTimes_ShouldNotThrow()
|
||||
{
|
||||
var provider = new HostInfoProvider();
|
||||
|
||||
for (int i = 0; i < 3; i++)
|
||||
{
|
||||
var info = provider.Collect();
|
||||
info.ShouldNotBeNull();
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Collect_KernelVersion_ShouldContainDot_OnLinux()
|
||||
{
|
||||
if (!OperatingSystem.IsLinux()) return;
|
||||
|
||||
var provider = new HostInfoProvider();
|
||||
var info = provider.Collect();
|
||||
|
||||
// Kernel version peut être null dans containers CI
|
||||
if (info.KernelVersion is not null)
|
||||
{
|
||||
info.KernelVersion.ShouldContain(".");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,143 @@
|
||||
using Heimdall.Agent.Services;
|
||||
|
||||
namespace Heimdall.Agent.Tests.Services;
|
||||
|
||||
public class MemoryReaderTests
|
||||
{
|
||||
[Fact]
|
||||
public void ReadFieldBytes_MemTotal_ShouldReturnValue_OnLinux()
|
||||
{
|
||||
if (!OperatingSystem.IsLinux()) return;
|
||||
|
||||
var total = MemoryReader.ReadFieldBytes("MemTotal");
|
||||
|
||||
total.ShouldNotBeNull();
|
||||
total.Value.ShouldBeGreaterThan(0);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ReadFieldBytes_MemAvailable_ShouldReturnValue_OnLinux()
|
||||
{
|
||||
if (!OperatingSystem.IsLinux()) return;
|
||||
|
||||
var available = MemoryReader.ReadFieldBytes("MemAvailable");
|
||||
|
||||
available.ShouldNotBeNull();
|
||||
available.Value.ShouldBeGreaterThan(0);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ReadFieldBytes_SwapTotal_ShouldReturnValue_OnLinux()
|
||||
{
|
||||
if (!OperatingSystem.IsLinux()) return;
|
||||
|
||||
var swapTotal = MemoryReader.ReadFieldBytes("SwapTotal");
|
||||
|
||||
// Swap may or may not be present
|
||||
if (swapTotal.HasValue)
|
||||
{
|
||||
swapTotal.Value.ShouldBeGreaterThanOrEqualTo(0);
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ReadFieldBytes_SwapFree_ShouldReturnValue_OnLinux()
|
||||
{
|
||||
if (!OperatingSystem.IsLinux()) return;
|
||||
|
||||
var swapFree = MemoryReader.ReadFieldBytes("SwapFree");
|
||||
|
||||
// Swap may or may not be present
|
||||
if (swapFree.HasValue)
|
||||
{
|
||||
swapFree.Value.ShouldBeGreaterThanOrEqualTo(0);
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void GetMemoryTotal_ShouldReturnPositiveValue_OnLinux()
|
||||
{
|
||||
if (!OperatingSystem.IsLinux()) return;
|
||||
|
||||
var total = MemoryReader.GetMemoryTotal();
|
||||
|
||||
total.ShouldNotBeNull();
|
||||
total.Value.ShouldBeGreaterThan(0);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void GetMemoryAvailable_ShouldReturnPositiveValue_OnLinux()
|
||||
{
|
||||
if (!OperatingSystem.IsLinux()) return;
|
||||
|
||||
var available = MemoryReader.GetMemoryAvailable();
|
||||
|
||||
available.ShouldNotBeNull();
|
||||
available.Value.ShouldBeGreaterThan(0);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void GetMemoryAvailable_ShouldBeLessOrEqualToMemTotal_OnLinux()
|
||||
{
|
||||
if (!OperatingSystem.IsLinux()) return;
|
||||
|
||||
var total = MemoryReader.GetMemoryTotal();
|
||||
var available = MemoryReader.GetMemoryAvailable();
|
||||
|
||||
if (total.HasValue && available.HasValue)
|
||||
{
|
||||
available.Value.ShouldBeLessThanOrEqualTo(total.Value);
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ReadFieldBytes_NonExistentField_ShouldReturnNull_OnLinux()
|
||||
{
|
||||
if (!OperatingSystem.IsLinux()) return;
|
||||
|
||||
var result = MemoryReader.ReadFieldBytes("NonExistentField12345");
|
||||
|
||||
result.ShouldBeNull();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void GetSwapTotal_ShouldReturnNull_OrNonNegative_OnLinux()
|
||||
{
|
||||
if (!OperatingSystem.IsLinux()) return;
|
||||
|
||||
var swapTotal = MemoryReader.GetSwapTotal();
|
||||
|
||||
if (swapTotal.HasValue)
|
||||
{
|
||||
swapTotal.Value.ShouldBeGreaterThanOrEqualTo(0);
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void GetSwapFree_ShouldBeLessOrEqualToSwapTotal_OnLinux()
|
||||
{
|
||||
if (!OperatingSystem.IsLinux()) return;
|
||||
|
||||
var total = MemoryReader.GetSwapTotal();
|
||||
var free = MemoryReader.GetSwapFree();
|
||||
|
||||
if (total.HasValue && free.HasValue)
|
||||
{
|
||||
free.Value.ShouldBeLessThanOrEqualTo(total.Value);
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ReadFieldBytes_ShouldConvertKbToBytes_OnLinux()
|
||||
{
|
||||
if (!OperatingSystem.IsLinux()) return;
|
||||
|
||||
// MemTotal in /proc/meminfo is in kB, ReadFieldBytes should return bytes
|
||||
var total = MemoryReader.GetMemoryTotal();
|
||||
if (total.HasValue)
|
||||
{
|
||||
// At least 1 MB (1024 * 1024 bytes)
|
||||
total.Value.ShouldBeGreaterThanOrEqualTo(1_048_576);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
using Heimdall.Agent.Services;
|
||||
|
||||
namespace Heimdall.Agent.Tests.Services;
|
||||
|
||||
public class ProcFsTests
|
||||
{
|
||||
[Fact]
|
||||
public void GetMachineUptime_ShouldReturnPositiveValue_OnLinux()
|
||||
{
|
||||
if (!OperatingSystem.IsLinux()) return;
|
||||
|
||||
var uptime = ProcFs.GetMachineUptime();
|
||||
|
||||
uptime.ShouldNotBeNull();
|
||||
uptime.Value.ShouldBeGreaterThan(0);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void GetMachineUptime_ShouldReturnConsistentValue()
|
||||
{
|
||||
if (!OperatingSystem.IsLinux()) return;
|
||||
|
||||
var first = ProcFs.GetMachineUptime();
|
||||
var second = ProcFs.GetMachineUptime();
|
||||
|
||||
first.ShouldNotBeNull();
|
||||
second.ShouldNotBeNull();
|
||||
// Second should be >= first (monotonically increasing)
|
||||
second.Value.ShouldBeGreaterThanOrEqualTo(first.Value);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void GetMachineUptime_ShouldReturnNull_OnNonLinux()
|
||||
{
|
||||
// On non-Linux, should return null (we're on Linux, so just verify it returns a value)
|
||||
if (OperatingSystem.IsLinux())
|
||||
{
|
||||
ProcFs.GetMachineUptime().ShouldNotBeNull();
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void GetMachineUptime_ShouldReadFromProcUptime()
|
||||
{
|
||||
if (!OperatingSystem.IsLinux()) return;
|
||||
|
||||
// Verify the value is reasonable (machine is up at least 1 second)
|
||||
var uptime = ProcFs.GetMachineUptime();
|
||||
uptime.ShouldNotBeNull();
|
||||
uptime.Value.ShouldBeGreaterThanOrEqualTo(1);
|
||||
}
|
||||
}
|
||||
@@ -39,6 +39,7 @@ public class SnapshotPipelineServiceTests
|
||||
await service.StartAsync(CancellationToken.None);
|
||||
var cts = new CancellationTokenSource(TimeSpan.FromMilliseconds(300));
|
||||
await service.StopAsync(cts.Token);
|
||||
state.AgentId.ShouldBe(Guid.Empty);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
@@ -114,5 +115,6 @@ public class SnapshotPipelineServiceTests
|
||||
{
|
||||
var (service, _, _, _, _) = CreatePipeline();
|
||||
await service.StopAsync(CancellationToken.None);
|
||||
service.ShouldNotBeNull();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,202 @@
|
||||
using Heimdall.Application.Agents;
|
||||
using Heimdall.Application.DTOs;
|
||||
using Heimdall.Domain.Entities;
|
||||
using Heimdall.Domain.Enums;
|
||||
|
||||
namespace Heimdall.Application.Tests.Agents;
|
||||
|
||||
public class AgentExtensionsTests
|
||||
{
|
||||
[Fact]
|
||||
public void ToResponse_ShouldMapBasicFields()
|
||||
{
|
||||
var agent = CreateAgent();
|
||||
agent.UpdateCapabilities(true, 8, 16384, GpuAcceleration.NvidiaCuda);
|
||||
|
||||
var response = agent.ToResponse();
|
||||
|
||||
response.Name.ShouldBe("test-agent");
|
||||
response.Hostname.ShouldBe("test-host");
|
||||
response.Version.ShouldBe("1.0.0");
|
||||
response.HasGpu.ShouldBeTrue();
|
||||
response.CpuCores.ShouldBe(8);
|
||||
response.MemoryMb.ShouldBe(16384);
|
||||
response.GpuType.ShouldBe("NvidiaCuda");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToResponse_ShouldMapLiveMetrics()
|
||||
{
|
||||
var agent = CreateAgent();
|
||||
agent.UpdateLiveMetrics(42.5, 4_294_967_296, 73.1, 86400);
|
||||
|
||||
var response = agent.ToResponse();
|
||||
|
||||
response.CpuUsagePercent.ShouldBe(42.5);
|
||||
response.MemoryUsageBytes.ShouldBe(4_294_967_296);
|
||||
response.DiskUsagePercent.ShouldBe(73.1);
|
||||
response.UptimeSeconds.ShouldBe(86400);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToResponse_ShouldMapCpuInventory()
|
||||
{
|
||||
var agent = CreateAgent();
|
||||
agent.UpdateCpuInventory(new CpuInventoryData(
|
||||
"GenuineIntel", "Intel Core i7-12700K", "x86_64",
|
||||
12, 20, 2, 3600.0, "avx,avx2,fma", 25_165_824, 200));
|
||||
|
||||
var response = agent.ToResponse();
|
||||
|
||||
response.CpuVendor.ShouldBe("GenuineIntel");
|
||||
response.CpuModel.ShouldBe("Intel Core i7-12700K");
|
||||
response.CpuArchitecture.ShouldBe("x86_64");
|
||||
response.PhysicalCores.ShouldBe(12);
|
||||
response.LogicalCores.ShouldBe(20);
|
||||
response.ThreadsPerCore.ShouldBe(2);
|
||||
response.CpuFrequencyMhz.ShouldBe(3600.0);
|
||||
response.CpuFlags.ShouldBe("avx,avx2,fma");
|
||||
response.CpuCacheBytes.ShouldBe(25_165_824);
|
||||
response.ContainerCpuLimit.ShouldBe(200);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToResponse_ShouldMapMemoryInventory()
|
||||
{
|
||||
var agent = CreateAgent();
|
||||
agent.UpdateMemoryDiskInventory(new MemoryDiskInventoryData(
|
||||
17_179_869_184, 8_589_934_592, 2_147_483_648, 1_073_741_824,
|
||||
4_294_967_296, """[{"Mount":"/"}]"""));
|
||||
|
||||
var response = agent.ToResponse();
|
||||
|
||||
response.MemTotalBytes.ShouldBe(17_179_869_184);
|
||||
response.MemAvailableBytes.ShouldBe(8_589_934_592);
|
||||
response.SwapTotalBytes.ShouldBe(2_147_483_648);
|
||||
response.SwapFreeBytes.ShouldBe(1_073_741_824);
|
||||
response.ContainerMemoryLimitBytes.ShouldBe(4_294_967_296);
|
||||
response.DiskInventoryJson.ShouldBe("""[{"Mount":"/"}]""");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToResponse_ShouldMapGpuInventory()
|
||||
{
|
||||
var agent = CreateAgent();
|
||||
agent.UpdateGpuInventory("""[{"Name":"RTX 4090"}]""");
|
||||
|
||||
var response = agent.ToResponse();
|
||||
|
||||
response.GpuInventoryJson.ShouldBe("""[{"Name":"RTX 4090"}]""");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToResponse_ShouldMapHostInventory()
|
||||
{
|
||||
var agent = CreateAgent();
|
||||
agent.UpdateHostInventory(new HostInventoryData(
|
||||
"Ubuntu 22.04 LTS", "5.15.0-76-generic", "x86_64", 100000,
|
||||
"abc123", "heimdall/agent:latest", """[{"Name":"eth0"}]""", """[{"Zone":"coretemp"}]"""));
|
||||
|
||||
var response = agent.ToResponse();
|
||||
|
||||
response.OsName.ShouldBe("Ubuntu 22.04 LTS");
|
||||
response.KernelVersion.ShouldBe("5.15.0-76-generic");
|
||||
response.Arch.ShouldBe("x86_64");
|
||||
response.UptimeMachineSeconds.ShouldBe(100000);
|
||||
response.ContainerId.ShouldBe("abc123");
|
||||
response.ContainerImage.ShouldBe("heimdall/agent:latest");
|
||||
response.NetworkInterfacesJson.ShouldBe("""[{"Name":"eth0"}]""");
|
||||
response.TemperatureJson.ShouldBe("""[{"Zone":"coretemp"}]""");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToResponse_WithNullSite_ShouldReturnEmptySiteName()
|
||||
{
|
||||
var agent = CreateAgent();
|
||||
|
||||
var response = agent.ToResponse();
|
||||
|
||||
response.SiteName.ShouldBe(string.Empty);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToResponse_ShouldMapSiteName_WhenSiteIsSet()
|
||||
{
|
||||
var agent = CreateAgent();
|
||||
// Site navigation is set by EF Core; test with reflection
|
||||
var siteProperty = typeof(Agent).GetProperty("Site",
|
||||
System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance);
|
||||
var site = new Site("Test Site");
|
||||
siteProperty?.SetValue(agent, site);
|
||||
|
||||
var response = agent.ToResponse();
|
||||
|
||||
response.SiteName.ShouldBe("Test Site");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToResponse_AllTelemetryFields_ShouldBeMapped()
|
||||
{
|
||||
var agent = CreateAgent();
|
||||
agent.UpdateLiveMetrics(42.5, 4_294_967_296, 73.1, 86400);
|
||||
agent.UpdateCpuInventory(new CpuInventoryData(
|
||||
"AMD", "Ryzen 9", "x86_64", 8, 16, 2, 3400.0, "sse4", 16_777_216, null));
|
||||
agent.UpdateMemoryDiskInventory(new MemoryDiskInventoryData(
|
||||
8_000_000_000, 4_000_000_000, 2_000_000_000, 1_000_000_000, null, null));
|
||||
agent.UpdateGpuInventory("""[{"Name":"RX 7900"}]""");
|
||||
agent.UpdateHostInventory(new HostInventoryData(
|
||||
"Fedora", "6.5.0", "x86_64", 50000, "def", "img", "[]", "[]"));
|
||||
|
||||
var response = agent.ToResponse();
|
||||
|
||||
// Live metrics
|
||||
response.CpuUsagePercent.ShouldBe(42.5);
|
||||
response.MemoryUsageBytes.ShouldBe(4_294_967_296);
|
||||
response.DiskUsagePercent.ShouldBe(73.1);
|
||||
response.UptimeSeconds.ShouldBe(86400);
|
||||
|
||||
// CPU
|
||||
response.CpuVendor.ShouldBe("AMD");
|
||||
response.CpuModel.ShouldBe("Ryzen 9");
|
||||
|
||||
// Memory
|
||||
response.MemTotalBytes.ShouldBe(8_000_000_000);
|
||||
|
||||
// GPU
|
||||
response.GpuInventoryJson.ShouldBe("""[{"Name":"RX 7900"}]""");
|
||||
|
||||
// Host
|
||||
response.OsName.ShouldBe("Fedora");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToTelemetryFields_ShouldMapAllFields()
|
||||
{
|
||||
var agent = CreateAgent();
|
||||
agent.UpdateLiveMetrics(42.5, 4_294_967_296, 73.1, 86400);
|
||||
agent.UpdateCpuInventory(new CpuInventoryData(
|
||||
"Intel", "i7", "x86_64", 12, 20, 2, 3600.0, "avx", 25_165_824, 200));
|
||||
agent.UpdateMemoryDiskInventory(new MemoryDiskInventoryData(
|
||||
17_179_869_184, 8_589_934_592, 2_147_483_648, 1_073_741_824, 4_294_967_296, """[{"Mount":"/"}]"""));
|
||||
agent.UpdateGpuInventory("""[{"Name":"RTX 4090"}]""");
|
||||
agent.UpdateHostInventory(new HostInventoryData(
|
||||
"Ubuntu", "5.15.0", "x86_64", 86400, "abc", "img", "[]", "[]"));
|
||||
|
||||
var fields = agent.ToTelemetryFields();
|
||||
|
||||
fields.CpuUsagePercent.ShouldBe(42.5);
|
||||
fields.MemoryUsageBytes.ShouldBe(4_294_967_296);
|
||||
fields.DiskUsagePercent.ShouldBe(73.1);
|
||||
fields.UptimeSeconds.ShouldBe(86400);
|
||||
fields.CpuVendor.ShouldBe("Intel");
|
||||
fields.CpuModel.ShouldBe("i7");
|
||||
fields.MemTotalBytes.ShouldBe(17_179_869_184);
|
||||
fields.GpuInventoryJson.ShouldBe("""[{"Name":"RTX 4090"}]""");
|
||||
fields.OsName.ShouldBe("Ubuntu");
|
||||
}
|
||||
|
||||
private static Agent CreateAgent()
|
||||
{
|
||||
return new Agent(Guid.NewGuid(), "test-agent", "test-host", "1.0.0");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,213 @@
|
||||
using Heimdall.Application.Agents;
|
||||
using Heimdall.Application.Agents.Commands.Heartbeat;
|
||||
using Heimdall.Application.DTOs;
|
||||
using Heimdall.Domain.Entities;
|
||||
using Heimdall.Domain.Enums;
|
||||
|
||||
namespace Heimdall.Application.Tests.Agents;
|
||||
|
||||
public class AgentTelemetryMappingTests
|
||||
{
|
||||
[Fact]
|
||||
public void ApplyTo_ShouldSetLiveMetrics()
|
||||
{
|
||||
var agent = CreateAgent();
|
||||
var cmd = new HeartbeatCommand(agent.Id, null, null, null, null, null,
|
||||
CpuUsagePercent: 42.5,
|
||||
MemoryUsageBytes: 4_294_967_296,
|
||||
DiskUsagePercent: 73.1,
|
||||
UptimeSeconds: 86400);
|
||||
|
||||
cmd.ApplyTo(agent);
|
||||
|
||||
agent.CpuUsagePercent.ShouldBe(42.5);
|
||||
agent.MemoryUsageBytes.ShouldBe(4_294_967_296);
|
||||
agent.DiskUsagePercent.ShouldBe(73.1);
|
||||
agent.UptimeSeconds.ShouldBe(86400);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ApplyTo_ShouldSetCpuInventory_WhenPresent()
|
||||
{
|
||||
var agent = CreateAgent();
|
||||
var cmd = new HeartbeatCommand(agent.Id, null, null, null, null, null,
|
||||
CpuVendor: "GenuineIntel",
|
||||
CpuModel: "Intel Core i7-12700K",
|
||||
CpuArchitecture: "x86_64",
|
||||
PhysicalCores: 12,
|
||||
LogicalCores: 20,
|
||||
ThreadsPerCore: 2,
|
||||
CpuFrequencyMhz: 3600.0,
|
||||
CpuFlags: "avx,avx2,fma",
|
||||
CpuCacheBytes: 25_165_824,
|
||||
ContainerCpuLimit: 200);
|
||||
|
||||
cmd.ApplyTo(agent);
|
||||
|
||||
agent.CpuVendor.ShouldBe("GenuineIntel");
|
||||
agent.CpuModel.ShouldBe("Intel Core i7-12700K");
|
||||
agent.CpuArchitecture.ShouldBe("x86_64");
|
||||
agent.PhysicalCores.ShouldBe(12);
|
||||
agent.LogicalCores.ShouldBe(20);
|
||||
agent.ThreadsPerCore.ShouldBe(2);
|
||||
agent.CpuFrequencyMhz.ShouldBe(3600.0);
|
||||
agent.CpuFlags.ShouldBe("avx,avx2,fma");
|
||||
agent.CpuCacheBytes.ShouldBe(25_165_824);
|
||||
agent.ContainerCpuLimit.ShouldBe(200);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ApplyTo_ShouldPreserveExistingCpuInventory_WhenNull()
|
||||
{
|
||||
var agent = CreateAgent();
|
||||
agent.UpdateCpuInventory(new CpuInventoryData("AMD", "Ryzen", "x86_64", 8, 16, 2, 3400.0, "sse4", 16_777_216, null));
|
||||
|
||||
var cmd = new HeartbeatCommand(agent.Id, null, null, null, null, null,
|
||||
CpuUsagePercent: 50.0);
|
||||
|
||||
cmd.ApplyTo(agent);
|
||||
|
||||
// CPU inventory should be preserved since no CPU inventory fields were sent
|
||||
agent.CpuVendor.ShouldBe("AMD");
|
||||
agent.CpuModel.ShouldBe("Ryzen");
|
||||
agent.PhysicalCores.ShouldBe(8);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ApplyTo_ShouldSetMemoryDiskInventory_WhenPresent()
|
||||
{
|
||||
var agent = CreateAgent();
|
||||
var cmd = new HeartbeatCommand(agent.Id, null, null, null, null, null,
|
||||
MemTotalBytes: 17_179_869_184,
|
||||
MemAvailableBytes: 8_589_934_592,
|
||||
SwapTotalBytes: 2_147_483_648,
|
||||
SwapFreeBytes: 1_073_741_824,
|
||||
ContainerMemoryLimitBytes: 4_294_967_296,
|
||||
DiskInventoryJson: """[{"Mount":"/"}]""");
|
||||
|
||||
cmd.ApplyTo(agent);
|
||||
|
||||
agent.MemTotalBytes.ShouldBe(17_179_869_184);
|
||||
agent.MemAvailableBytes.ShouldBe(8_589_934_592);
|
||||
agent.SwapTotalBytes.ShouldBe(2_147_483_648);
|
||||
agent.SwapFreeBytes.ShouldBe(1_073_741_824);
|
||||
agent.ContainerMemoryLimitBytes.ShouldBe(4_294_967_296);
|
||||
agent.DiskInventoryJson.ShouldBe("""[{"Mount":"/"}]""");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ApplyTo_ShouldPreserveExistingMemoryDiskInventory_WhenNull()
|
||||
{
|
||||
var agent = CreateAgent();
|
||||
agent.UpdateMemoryDiskInventory(new MemoryDiskInventoryData(8_000_000_000, 4_000_000_000, 2_000_000_000, 1_000_000_000, null, null));
|
||||
|
||||
var cmd = new HeartbeatCommand(agent.Id, null, null, null, null, null,
|
||||
CpuUsagePercent: 50.0);
|
||||
|
||||
cmd.ApplyTo(agent);
|
||||
|
||||
agent.MemTotalBytes.ShouldBe(8_000_000_000);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ApplyTo_ShouldSetGpuInventory_WhenPresent()
|
||||
{
|
||||
var agent = CreateAgent();
|
||||
var cmd = new HeartbeatCommand(agent.Id, null, null, null, null, null,
|
||||
GpuInventoryJson: """[{"Name":"RTX 4090"}]""");
|
||||
|
||||
cmd.ApplyTo(agent);
|
||||
|
||||
agent.GpuInventoryJson.ShouldBe("""[{"Name":"RTX 4090"}]""");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ApplyTo_ShouldSetHostInventory_WhenPresent()
|
||||
{
|
||||
var agent = CreateAgent();
|
||||
var cmd = new HeartbeatCommand(agent.Id, null, null, null, null, null,
|
||||
OsName: "Ubuntu 22.04 LTS",
|
||||
KernelVersion: "5.15.0-76-generic",
|
||||
Arch: "x86_64",
|
||||
UptimeMachineSeconds: 86400,
|
||||
ContainerId: "abc123",
|
||||
ContainerImage: "heimdall/agent:latest",
|
||||
NetworkInterfacesJson: """[{"Name":"eth0"}]""",
|
||||
TemperatureJson: """[{"Zone":"coretemp"}]""");
|
||||
|
||||
cmd.ApplyTo(agent);
|
||||
|
||||
agent.OsName.ShouldBe("Ubuntu 22.04 LTS");
|
||||
agent.KernelVersion.ShouldBe("5.15.0-76-generic");
|
||||
agent.Arch.ShouldBe("x86_64");
|
||||
agent.UptimeMachineSeconds.ShouldBe(86400);
|
||||
agent.ContainerId.ShouldBe("abc123");
|
||||
agent.ContainerImage.ShouldBe("heimdall/agent:latest");
|
||||
agent.NetworkInterfacesJson.ShouldBe("""[{"Name":"eth0"}]""");
|
||||
agent.TemperatureJson.ShouldBe("""[{"Zone":"coretemp"}]""");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ApplyTo_ShouldPreserveExistingHostInventory_WhenNull()
|
||||
{
|
||||
var agent = CreateAgent();
|
||||
agent.UpdateHostInventory(new HostInventoryData("Fedora", "6.5.0", "x86_64", 100000, "def456", "agent:v2", null, null));
|
||||
|
||||
var cmd = new HeartbeatCommand(agent.Id, null, null, null, null, null,
|
||||
CpuUsagePercent: 50.0);
|
||||
|
||||
cmd.ApplyTo(agent);
|
||||
|
||||
agent.OsName.ShouldBe("Fedora");
|
||||
agent.KernelVersion.ShouldBe("6.5.0");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToTelemetryFields_ShouldReadAllFields()
|
||||
{
|
||||
var agent = CreateAgent();
|
||||
agent.UpdateLiveMetrics(42.5, 4_294_967_296, 73.1, 86400);
|
||||
agent.UpdateCpuInventory(new CpuInventoryData("Intel", "i7", "x86_64", 12, 20, 2, 3600.0, "avx", 25_165_824, 200));
|
||||
agent.UpdateMemoryDiskInventory(new MemoryDiskInventoryData(17_179_869_184, 8_589_934_592, 2_147_483_648, 1_073_741_824, 4_294_967_296, """[{"Mount":"/"}]"""));
|
||||
agent.UpdateGpuInventory("""[{"Name":"RTX 4090"}]""");
|
||||
agent.UpdateHostInventory(new HostInventoryData("Ubuntu", "5.15.0", "x86_64", 86400, "abc", "img", "[]", "[]"));
|
||||
|
||||
var fields = agent.ToTelemetryFields();
|
||||
|
||||
fields.CpuUsagePercent.ShouldBe(42.5);
|
||||
fields.MemoryUsageBytes.ShouldBe(4_294_967_296);
|
||||
fields.DiskUsagePercent.ShouldBe(73.1);
|
||||
fields.UptimeSeconds.ShouldBe(86400);
|
||||
fields.CpuVendor.ShouldBe("Intel");
|
||||
fields.MemTotalBytes.ShouldBe(17_179_869_184);
|
||||
fields.GpuInventoryJson.ShouldBe("""[{"Name":"RTX 4090"}]""");
|
||||
fields.OsName.ShouldBe("Ubuntu");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ApplyTo_RoundTrip_ShouldPreserveValues()
|
||||
{
|
||||
var agent = CreateAgent();
|
||||
var cmd = new HeartbeatCommand(agent.Id, null, null, null, null, null,
|
||||
CpuUsagePercent: 42.5,
|
||||
MemoryUsageBytes: 4_294_967_296,
|
||||
CpuVendor: "AMD",
|
||||
MemTotalBytes: 16_000_000_000,
|
||||
OsName: "Debian");
|
||||
|
||||
cmd.ApplyTo(agent);
|
||||
|
||||
var fields = agent.ToTelemetryFields();
|
||||
|
||||
fields.CpuUsagePercent.ShouldBe(42.5);
|
||||
fields.MemoryUsageBytes.ShouldBe(4_294_967_296);
|
||||
fields.CpuVendor.ShouldBe("AMD");
|
||||
fields.MemTotalBytes.ShouldBe(16_000_000_000);
|
||||
fields.OsName.ShouldBe("Debian");
|
||||
}
|
||||
|
||||
private static Agent CreateAgent()
|
||||
{
|
||||
return new Agent(Guid.NewGuid(), "test-agent", "test-host", "1.0.0");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,151 @@
|
||||
using Heimdall.Application.DTOs;
|
||||
|
||||
namespace Heimdall.Application.Tests.DTOs;
|
||||
|
||||
public class AgentTelemetryFieldsTests
|
||||
{
|
||||
[Fact]
|
||||
public void DefaultConstructor_ShouldHaveAllNulls()
|
||||
{
|
||||
var fields = new AgentTelemetryFields();
|
||||
|
||||
fields.CpuUsagePercent.ShouldBeNull();
|
||||
fields.MemoryUsageBytes.ShouldBeNull();
|
||||
fields.DiskUsagePercent.ShouldBeNull();
|
||||
fields.UptimeSeconds.ShouldBeNull();
|
||||
fields.CpuVendor.ShouldBeNull();
|
||||
fields.CpuModel.ShouldBeNull();
|
||||
fields.CpuArchitecture.ShouldBeNull();
|
||||
fields.PhysicalCores.ShouldBeNull();
|
||||
fields.LogicalCores.ShouldBeNull();
|
||||
fields.ThreadsPerCore.ShouldBeNull();
|
||||
fields.CpuFrequencyMhz.ShouldBeNull();
|
||||
fields.CpuFlags.ShouldBeNull();
|
||||
fields.CpuCacheBytes.ShouldBeNull();
|
||||
fields.ContainerCpuLimit.ShouldBeNull();
|
||||
fields.MemTotalBytes.ShouldBeNull();
|
||||
fields.MemAvailableBytes.ShouldBeNull();
|
||||
fields.SwapTotalBytes.ShouldBeNull();
|
||||
fields.SwapFreeBytes.ShouldBeNull();
|
||||
fields.ContainerMemoryLimitBytes.ShouldBeNull();
|
||||
fields.DiskInventoryJson.ShouldBeNull();
|
||||
fields.GpuInventoryJson.ShouldBeNull();
|
||||
fields.OsName.ShouldBeNull();
|
||||
fields.KernelVersion.ShouldBeNull();
|
||||
fields.Arch.ShouldBeNull();
|
||||
fields.UptimeMachineSeconds.ShouldBeNull();
|
||||
fields.ContainerId.ShouldBeNull();
|
||||
fields.ContainerImage.ShouldBeNull();
|
||||
fields.NetworkInterfacesJson.ShouldBeNull();
|
||||
fields.TemperatureJson.ShouldBeNull();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void WithAllValues_ShouldStoreCorrectly()
|
||||
{
|
||||
var fields = new AgentTelemetryFields(
|
||||
CpuUsagePercent: 42.5,
|
||||
MemoryUsageBytes: 4_294_967_296,
|
||||
DiskUsagePercent: 73.1,
|
||||
UptimeSeconds: 86400,
|
||||
CpuVendor: "GenuineIntel",
|
||||
CpuModel: "Intel Core i7-12700K",
|
||||
CpuArchitecture: "x86_64",
|
||||
PhysicalCores: 12,
|
||||
LogicalCores: 20,
|
||||
ThreadsPerCore: 2,
|
||||
CpuFrequencyMhz: 3600.0,
|
||||
CpuFlags: "avx,avx2,fma",
|
||||
CpuCacheBytes: 25_165_824,
|
||||
ContainerCpuLimit: 200,
|
||||
MemTotalBytes: 17_179_869_184,
|
||||
MemAvailableBytes: 8_589_934_592,
|
||||
SwapTotalBytes: 2_147_483_648,
|
||||
SwapFreeBytes: 1_073_741_824,
|
||||
ContainerMemoryLimitBytes: 4_294_967_296,
|
||||
DiskInventoryJson: """[{"Mount":"/"}]""",
|
||||
GpuInventoryJson: """[{"Name":"RTX 4090"}]""",
|
||||
OsName: "Ubuntu 22.04 LTS",
|
||||
KernelVersion: "5.15.0-76-generic",
|
||||
Arch: "x86_64",
|
||||
UptimeMachineSeconds: 100000,
|
||||
ContainerId: "abc123",
|
||||
ContainerImage: "heimdall/agent:latest",
|
||||
NetworkInterfacesJson: """[{"Name":"eth0"}]""",
|
||||
TemperatureJson: """[{"Zone":"coretemp"}]"""
|
||||
);
|
||||
|
||||
fields.CpuUsagePercent.ShouldBe(42.5);
|
||||
fields.MemoryUsageBytes.ShouldBe(4_294_967_296);
|
||||
fields.DiskUsagePercent.ShouldBe(73.1);
|
||||
fields.UptimeSeconds.ShouldBe(86400);
|
||||
fields.CpuVendor.ShouldBe("GenuineIntel");
|
||||
fields.CpuModel.ShouldBe("Intel Core i7-12700K");
|
||||
fields.CpuArchitecture.ShouldBe("x86_64");
|
||||
fields.PhysicalCores.ShouldBe(12);
|
||||
fields.LogicalCores.ShouldBe(20);
|
||||
fields.ThreadsPerCore.ShouldBe(2);
|
||||
fields.CpuFrequencyMhz.ShouldBe(3600.0);
|
||||
fields.CpuFlags.ShouldBe("avx,avx2,fma");
|
||||
fields.CpuCacheBytes.ShouldBe(25_165_824);
|
||||
fields.ContainerCpuLimit.ShouldBe(200);
|
||||
fields.MemTotalBytes.ShouldBe(17_179_869_184);
|
||||
fields.MemAvailableBytes.ShouldBe(8_589_934_592);
|
||||
fields.SwapTotalBytes.ShouldBe(2_147_483_648);
|
||||
fields.SwapFreeBytes.ShouldBe(1_073_741_824);
|
||||
fields.ContainerMemoryLimitBytes.ShouldBe(4_294_967_296);
|
||||
fields.DiskInventoryJson.ShouldBe("""[{"Mount":"/"}]""");
|
||||
fields.GpuInventoryJson.ShouldBe("""[{"Name":"RTX 4090"}]""");
|
||||
fields.OsName.ShouldBe("Ubuntu 22.04 LTS");
|
||||
fields.KernelVersion.ShouldBe("5.15.0-76-generic");
|
||||
fields.Arch.ShouldBe("x86_64");
|
||||
fields.UptimeMachineSeconds.ShouldBe(100000);
|
||||
fields.ContainerId.ShouldBe("abc123");
|
||||
fields.ContainerImage.ShouldBe("heimdall/agent:latest");
|
||||
fields.NetworkInterfacesJson.ShouldBe("""[{"Name":"eth0"}]""");
|
||||
fields.TemperatureJson.ShouldBe("""[{"Zone":"coretemp"}]""");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void WithPartialValues_ShouldStoreOnlyProvidedFields()
|
||||
{
|
||||
var fields = new AgentTelemetryFields(
|
||||
CpuUsagePercent: 50.0,
|
||||
CpuVendor: "AMD"
|
||||
);
|
||||
|
||||
fields.CpuUsagePercent.ShouldBe(50.0);
|
||||
fields.CpuVendor.ShouldBe("AMD");
|
||||
fields.MemoryUsageBytes.ShouldBeNull();
|
||||
fields.CpuModel.ShouldBeNull();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void RecordEquality_SameValues_ShouldBeEqual()
|
||||
{
|
||||
var f1 = new AgentTelemetryFields(CpuUsagePercent: 42.5, CpuVendor: "Intel");
|
||||
var f2 = new AgentTelemetryFields(CpuUsagePercent: 42.5, CpuVendor: "Intel");
|
||||
|
||||
f1.ShouldBe(f2);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void RecordEquality_DifferentValues_ShouldNotBeEqual()
|
||||
{
|
||||
var f1 = new AgentTelemetryFields(CpuUsagePercent: 42.5);
|
||||
var f2 = new AgentTelemetryFields(CpuUsagePercent: 50.0);
|
||||
|
||||
f1.ShouldNotBe(f2);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void RecordWith_ShouldCreateModifiedCopy()
|
||||
{
|
||||
var original = new AgentTelemetryFields(CpuUsagePercent: 42.5, CpuVendor: "Intel");
|
||||
var modified = original with { CpuUsagePercent = 99.0 };
|
||||
|
||||
modified.CpuUsagePercent.ShouldBe(99.0);
|
||||
modified.CpuVendor.ShouldBe("Intel");
|
||||
original.CpuUsagePercent.ShouldBe(42.5);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,171 @@
|
||||
using Heimdall.Application.Agents.Commands.Heartbeat;
|
||||
using Heimdall.Application.Common;
|
||||
using Heimdall.Application.Tests.Common;
|
||||
using Heimdall.Domain.Entities;
|
||||
using Heimdall.Domain.Enums;
|
||||
using NSubstitute;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
|
||||
namespace Heimdall.Application.Tests.Handlers.Agents;
|
||||
|
||||
public class HeartbeatHandlerInventoryTests
|
||||
{
|
||||
private readonly Agent _existingAgent = new(Guid.NewGuid(), "agent-1", "agent-1", "1.0.0");
|
||||
|
||||
[Fact]
|
||||
public async Task Heartbeat_with_cpu_inventory_should_update_fields()
|
||||
{
|
||||
_existingAgent.Register("hash", "pref");
|
||||
var context = Substitute.For<IApplicationDbContext>();
|
||||
context.Agents.Returns(MockDbSetHelper.CreateFor<Agent>([_existingAgent]));
|
||||
var handler = new HeartbeatHandler(context);
|
||||
var command = new HeartbeatCommand(
|
||||
_existingAgent.Id, null, null, null, null, null,
|
||||
CpuVendor: "GenuineIntel",
|
||||
CpuModel: "Intel Core i7-12700K",
|
||||
CpuArchitecture: "x86_64",
|
||||
PhysicalCores: 12,
|
||||
LogicalCores: 20,
|
||||
ThreadsPerCore: 2,
|
||||
CpuFrequencyMhz: 3600.0,
|
||||
CpuFlags: "avx,avx2,fma",
|
||||
CpuCacheBytes: 25_165_824,
|
||||
ContainerCpuLimit: 200);
|
||||
|
||||
var result = await handler.Handle(command, CancellationToken.None);
|
||||
|
||||
result.IsSuccess.ShouldBeTrue();
|
||||
_existingAgent.CpuVendor.ShouldBe("GenuineIntel");
|
||||
_existingAgent.CpuModel.ShouldBe("Intel Core i7-12700K");
|
||||
_existingAgent.CpuArchitecture.ShouldBe("x86_64");
|
||||
_existingAgent.PhysicalCores.ShouldBe(12);
|
||||
_existingAgent.LogicalCores.ShouldBe(20);
|
||||
_existingAgent.ThreadsPerCore.ShouldBe(2);
|
||||
_existingAgent.CpuFrequencyMhz.ShouldBe(3600.0);
|
||||
_existingAgent.CpuFlags.ShouldBe("avx,avx2,fma");
|
||||
_existingAgent.CpuCacheBytes.ShouldBe(25_165_824);
|
||||
_existingAgent.ContainerCpuLimit.ShouldBe(200);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Heartbeat_with_memory_inventory_should_update_fields()
|
||||
{
|
||||
_existingAgent.Register("hash", "pref");
|
||||
var context = Substitute.For<IApplicationDbContext>();
|
||||
context.Agents.Returns(MockDbSetHelper.CreateFor<Agent>([_existingAgent]));
|
||||
var handler = new HeartbeatHandler(context);
|
||||
var command = new HeartbeatCommand(
|
||||
_existingAgent.Id, null, null, null, null, null,
|
||||
MemTotalBytes: 17_179_869_184,
|
||||
MemAvailableBytes: 8_589_934_592,
|
||||
SwapTotalBytes: 2_147_483_648,
|
||||
SwapFreeBytes: 1_073_741_824,
|
||||
ContainerMemoryLimitBytes: 4_294_967_296,
|
||||
DiskInventoryJson: """[{"MountPoint":"/","FileSystem":"ext4","TotalBytes":107374182400}]""");
|
||||
|
||||
var result = await handler.Handle(command, CancellationToken.None);
|
||||
|
||||
result.IsSuccess.ShouldBeTrue();
|
||||
_existingAgent.MemTotalBytes.ShouldBe(17_179_869_184);
|
||||
_existingAgent.MemAvailableBytes.ShouldBe(8_589_934_592);
|
||||
_existingAgent.SwapTotalBytes.ShouldBe(2_147_483_648);
|
||||
_existingAgent.SwapFreeBytes.ShouldBe(1_073_741_824);
|
||||
_existingAgent.ContainerMemoryLimitBytes.ShouldBe(4_294_967_296);
|
||||
_existingAgent.DiskInventoryJson.ShouldNotBeNull();
|
||||
_existingAgent.DiskInventoryJson.ShouldContain("ext4");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Heartbeat_with_gpu_inventory_should_update_field()
|
||||
{
|
||||
_existingAgent.Register("hash", "pref");
|
||||
var context = Substitute.For<IApplicationDbContext>();
|
||||
context.Agents.Returns(MockDbSetHelper.CreateFor<Agent>([_existingAgent]));
|
||||
var handler = new HeartbeatHandler(context);
|
||||
var gpuJson = """[{"Vendor":"Nvidia","Model":"RTX 3090","VramBytes":25769803776}]""";
|
||||
var command = new HeartbeatCommand(
|
||||
_existingAgent.Id, null, null, null, null, null,
|
||||
GpuInventoryJson: gpuJson);
|
||||
|
||||
var result = await handler.Handle(command, CancellationToken.None);
|
||||
|
||||
result.IsSuccess.ShouldBeTrue();
|
||||
_existingAgent.GpuInventoryJson.ShouldBe(gpuJson);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Heartbeat_with_host_inventory_should_update_fields()
|
||||
{
|
||||
_existingAgent.Register("hash", "pref");
|
||||
var context = Substitute.For<IApplicationDbContext>();
|
||||
context.Agents.Returns(MockDbSetHelper.CreateFor<Agent>([_existingAgent]));
|
||||
var handler = new HeartbeatHandler(context);
|
||||
var command = new HeartbeatCommand(
|
||||
_existingAgent.Id, null, null, null, null, null,
|
||||
OsName: "Ubuntu 22.04 LTS",
|
||||
KernelVersion: "5.15.0-76-generic",
|
||||
Arch: "x86_64",
|
||||
UptimeMachineSeconds: 86400,
|
||||
ContainerId: "abc123",
|
||||
ContainerImage: "heimdall/agent:latest",
|
||||
NetworkInterfacesJson: """[{"Name":"eth0","IpAddress":"192.168.1.100"}]""",
|
||||
TemperatureJson: """[{"Zone":"coretemp","TemperatureCelsius":45.0}]""");
|
||||
|
||||
var result = await handler.Handle(command, CancellationToken.None);
|
||||
|
||||
result.IsSuccess.ShouldBeTrue();
|
||||
_existingAgent.OsName.ShouldBe("Ubuntu 22.04 LTS");
|
||||
_existingAgent.KernelVersion.ShouldBe("5.15.0-76-generic");
|
||||
_existingAgent.Arch.ShouldBe("x86_64");
|
||||
_existingAgent.UptimeMachineSeconds.ShouldBe(86400);
|
||||
_existingAgent.ContainerId.ShouldBe("abc123");
|
||||
_existingAgent.ContainerImage.ShouldBe("heimdall/agent:latest");
|
||||
_existingAgent.NetworkInterfacesJson.ShouldNotBeNull();
|
||||
_existingAgent.NetworkInterfacesJson.ShouldContain("eth0");
|
||||
_existingAgent.TemperatureJson.ShouldNotBeNull();
|
||||
_existingAgent.TemperatureJson.ShouldContain("coretemp");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Heartbeat_without_inventory_should_not_change_inventory_fields()
|
||||
{
|
||||
_existingAgent.Register("hash", "pref");
|
||||
// Set some inventory data first
|
||||
_existingAgent.UpdateCpuInventory(new CpuInventoryData("Intel", "i7", "x86_64", 8, 16, 2, 3600.0, "avx", 12345, null));
|
||||
var context = Substitute.For<IApplicationDbContext>();
|
||||
context.Agents.Returns(MockDbSetHelper.CreateFor<Agent>([_existingAgent]));
|
||||
var handler = new HeartbeatHandler(context);
|
||||
|
||||
// Heartbeat without inventory fields
|
||||
var command = new HeartbeatCommand(
|
||||
_existingAgent.Id, "10.0.0.1", null, null, null, null,
|
||||
CpuUsagePercent: 50.0);
|
||||
|
||||
var result = await handler.Handle(command, CancellationToken.None);
|
||||
|
||||
result.IsSuccess.ShouldBeTrue();
|
||||
// Inventory should be preserved
|
||||
_existingAgent.CpuVendor.ShouldBe("Intel");
|
||||
_existingAgent.CpuModel.ShouldBe("i7");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Heartbeat_isOffline_should_not_update_inventory()
|
||||
{
|
||||
_existingAgent.Register("hash", "pref");
|
||||
var context = Substitute.For<IApplicationDbContext>();
|
||||
context.Agents.Returns(MockDbSetHelper.CreateFor<Agent>([_existingAgent]));
|
||||
var handler = new HeartbeatHandler(context);
|
||||
var command = new HeartbeatCommand(
|
||||
_existingAgent.Id, null, null, null, null, null,
|
||||
IsOffline: true,
|
||||
CpuVendor: "Intel",
|
||||
OsName: "Linux");
|
||||
|
||||
var result = await handler.Handle(command, CancellationToken.None);
|
||||
|
||||
result.IsSuccess.ShouldBeTrue();
|
||||
_existingAgent.CpuVendor.ShouldBeNull();
|
||||
_existingAgent.OsName.ShouldBeNull();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,167 @@
|
||||
using Heimdall.Domain.Entities;
|
||||
using Heimdall.Domain.Enums;
|
||||
using Shouldly;
|
||||
|
||||
namespace Heimdall.Domain.Tests.Entities;
|
||||
|
||||
public class AgentInventoryTests
|
||||
{
|
||||
[Fact]
|
||||
public void UpdateCpuInventory_should_set_all_fields()
|
||||
{
|
||||
var agent = CreateAgent();
|
||||
|
||||
agent.UpdateCpuInventory(new CpuInventoryData(
|
||||
Vendor: "GenuineIntel",
|
||||
Model: "Intel(R) Core(TM) i7-12700K",
|
||||
Architecture: "x86_64",
|
||||
PhysicalCores: 12,
|
||||
LogicalCores: 20,
|
||||
ThreadsPerCore: 2,
|
||||
FrequencyMhz: 3600.0,
|
||||
Flags: "avx,avx2,fma,aes",
|
||||
CacheBytes: 25_165_824,
|
||||
ContainerCpuLimit: 200));
|
||||
|
||||
agent.CpuVendor.ShouldBe("GenuineIntel");
|
||||
agent.CpuModel.ShouldBe("Intel(R) Core(TM) i7-12700K");
|
||||
agent.CpuArchitecture.ShouldBe("x86_64");
|
||||
agent.PhysicalCores.ShouldBe(12);
|
||||
agent.LogicalCores.ShouldBe(20);
|
||||
agent.ThreadsPerCore.ShouldBe(2);
|
||||
agent.CpuFrequencyMhz.ShouldBe(3600.0);
|
||||
agent.CpuFlags.ShouldBe("avx,avx2,fma,aes");
|
||||
agent.CpuCacheBytes.ShouldBe(25_165_824);
|
||||
agent.ContainerCpuLimit.ShouldBe(200);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void UpdateCpuInventory_should_accept_nulls()
|
||||
{
|
||||
var agent = CreateAgent();
|
||||
|
||||
agent.UpdateCpuInventory(new CpuInventoryData(null, null, null, null, null, null, null, null, null, null));
|
||||
|
||||
agent.CpuVendor.ShouldBeNull();
|
||||
agent.CpuModel.ShouldBeNull();
|
||||
agent.PhysicalCores.ShouldBeNull();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void UpdateMemoryDiskInventory_should_set_all_fields()
|
||||
{
|
||||
var agent = CreateAgent();
|
||||
var diskJson = """[{"MountPoint":"/","FileSystem":"ext4","TotalBytes":107374182400,"UsedBytes":53687091200,"Type":"SSD"}]""";
|
||||
|
||||
agent.UpdateMemoryDiskInventory(new MemoryDiskInventoryData(
|
||||
MemTotalBytes: 17_179_869_184,
|
||||
MemAvailableBytes: 8_589_934_592,
|
||||
SwapTotalBytes: 2_147_483_648,
|
||||
SwapFreeBytes: 1_073_741_824,
|
||||
ContainerMemoryLimitBytes: 4_294_967_296,
|
||||
DiskInventoryJson: diskJson));
|
||||
|
||||
agent.MemTotalBytes.ShouldBe(17_179_869_184);
|
||||
agent.MemAvailableBytes.ShouldBe(8_589_934_592);
|
||||
agent.SwapTotalBytes.ShouldBe(2_147_483_648);
|
||||
agent.SwapFreeBytes.ShouldBe(1_073_741_824);
|
||||
agent.ContainerMemoryLimitBytes.ShouldBe(4_294_967_296);
|
||||
agent.DiskInventoryJson.ShouldBe(diskJson);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void UpdateGpuInventory_should_set_json()
|
||||
{
|
||||
var agent = CreateAgent();
|
||||
var gpuJson = """[{"Vendor":"Nvidia","Model":"RTX 3090","VramBytes":25769803776}]""";
|
||||
|
||||
agent.UpdateGpuInventory(gpuJson);
|
||||
|
||||
agent.GpuInventoryJson.ShouldBe(gpuJson);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void UpdateHostInventory_should_set_all_fields()
|
||||
{
|
||||
var agent = CreateAgent();
|
||||
var netJson = """[{"Name":"eth0","IpAddress":"192.168.1.100","MacAddress":"aa:bb:cc:dd:ee:ff"}]""";
|
||||
var tempJson = """[{"Zone":"coretemp","TemperatureCelsius":45.0}]""";
|
||||
|
||||
agent.UpdateHostInventory(new HostInventoryData(
|
||||
OsName: "Ubuntu 22.04 LTS",
|
||||
KernelVersion: "5.15.0-76-generic",
|
||||
Arch: "x86_64",
|
||||
UptimeMachineSeconds: 86400,
|
||||
ContainerId: "abc123def456",
|
||||
ContainerImage: "heimdall/agent:latest",
|
||||
NetworkInterfacesJson: netJson,
|
||||
TemperatureJson: tempJson));
|
||||
|
||||
agent.OsName.ShouldBe("Ubuntu 22.04 LTS");
|
||||
agent.KernelVersion.ShouldBe("5.15.0-76-generic");
|
||||
agent.Arch.ShouldBe("x86_64");
|
||||
agent.UptimeMachineSeconds.ShouldBe(86400);
|
||||
agent.ContainerId.ShouldBe("abc123def456");
|
||||
agent.ContainerImage.ShouldBe("heimdall/agent:latest");
|
||||
agent.NetworkInterfacesJson.ShouldBe(netJson);
|
||||
agent.TemperatureJson.ShouldBe(tempJson);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void UpdateHostInventory_should_accept_nulls()
|
||||
{
|
||||
var agent = CreateAgent();
|
||||
|
||||
agent.UpdateHostInventory(new HostInventoryData(null, null, null, null, null, null, null, null));
|
||||
|
||||
agent.OsName.ShouldBeNull();
|
||||
agent.KernelVersion.ShouldBeNull();
|
||||
agent.ContainerId.ShouldBeNull();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void All_new_fields_should_be_null_by_default()
|
||||
{
|
||||
var agent = CreateAgent();
|
||||
|
||||
// CPU
|
||||
agent.CpuVendor.ShouldBeNull();
|
||||
agent.CpuModel.ShouldBeNull();
|
||||
agent.CpuArchitecture.ShouldBeNull();
|
||||
agent.PhysicalCores.ShouldBeNull();
|
||||
agent.LogicalCores.ShouldBeNull();
|
||||
agent.ThreadsPerCore.ShouldBeNull();
|
||||
agent.CpuFrequencyMhz.ShouldBeNull();
|
||||
agent.CpuFlags.ShouldBeNull();
|
||||
agent.CpuCacheBytes.ShouldBeNull();
|
||||
agent.ContainerCpuLimit.ShouldBeNull();
|
||||
// Memory
|
||||
agent.MemTotalBytes.ShouldBeNull();
|
||||
agent.MemAvailableBytes.ShouldBeNull();
|
||||
agent.SwapTotalBytes.ShouldBeNull();
|
||||
agent.SwapFreeBytes.ShouldBeNull();
|
||||
agent.ContainerMemoryLimitBytes.ShouldBeNull();
|
||||
// Disk
|
||||
agent.DiskInventoryJson.ShouldBeNull();
|
||||
// GPU
|
||||
agent.GpuInventoryJson.ShouldBeNull();
|
||||
// Host
|
||||
agent.OsName.ShouldBeNull();
|
||||
agent.KernelVersion.ShouldBeNull();
|
||||
agent.Arch.ShouldBeNull();
|
||||
agent.UptimeMachineSeconds.ShouldBeNull();
|
||||
// Container
|
||||
agent.ContainerId.ShouldBeNull();
|
||||
agent.ContainerImage.ShouldBeNull();
|
||||
// Network & Temperature
|
||||
agent.NetworkInterfacesJson.ShouldBeNull();
|
||||
agent.TemperatureJson.ShouldBeNull();
|
||||
}
|
||||
|
||||
private static Agent CreateAgent()
|
||||
{
|
||||
var agent = new Agent(Guid.NewGuid(), "TestAgent", "test-host", "1.0.0");
|
||||
agent.Register("hash", "pref");
|
||||
return agent;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,964 @@
|
||||
using System.Net;
|
||||
using Heimdall.Web.Services;
|
||||
using NSubstitute;
|
||||
|
||||
namespace Heimdall.Web.Tests.Services;
|
||||
|
||||
/// <summary>
|
||||
/// Additional HeimdallApiClient tests to increase line coverage on
|
||||
/// Sites, Users, Cameras, Settings, Events, Notifications, AgentSettings, 2FA.
|
||||
/// </summary>
|
||||
public sealed class HeimdallApiClientCoverageTests : IDisposable
|
||||
{
|
||||
private readonly MockHttpMessageHandler _handler;
|
||||
private readonly HttpClient _httpClient;
|
||||
private readonly IHttpClientFactory _httpFactory;
|
||||
private readonly AuthState _authState;
|
||||
private readonly HeimdallApiClient _sut;
|
||||
|
||||
public HeimdallApiClientCoverageTests()
|
||||
{
|
||||
_handler = new MockHttpMessageHandler();
|
||||
_httpClient = new HttpClient(_handler) { BaseAddress = new Uri("http://localhost:8080/") };
|
||||
_httpFactory = Substitute.For<IHttpClientFactory>();
|
||||
_httpFactory.CreateClient("HeimdallApi").Returns(_httpClient);
|
||||
_authState = new AuthState();
|
||||
_sut = new HeimdallApiClient(_httpFactory, _authState);
|
||||
}
|
||||
|
||||
public void Dispose() => _httpClient.Dispose();
|
||||
|
||||
private void SetAuthToken() =>
|
||||
_authState.Login(new AuthResponse(
|
||||
"token", "refresh", DateTime.UtcNow.AddHours(1), false,
|
||||
new UserInfo(Guid.NewGuid(), "a@b.com", "Admin", ["Admin"])));
|
||||
|
||||
// ── Sites ───────────────────────────────────────────────────────
|
||||
|
||||
[Fact]
|
||||
public async Task GetSitesAsync_ReturnsPagedData()
|
||||
{
|
||||
SetAuthToken();
|
||||
var expected = new PagedData<SiteItem>(
|
||||
[new SiteItem(Guid.NewGuid(), "Site A", null, "UTC", null, true, DateTime.UtcNow)], 1, 1, 20);
|
||||
_handler.QueueResponse(HttpStatusCode.OK, expected);
|
||||
|
||||
var result = await _sut.GetSitesAsync();
|
||||
|
||||
Assert.NotNull(result);
|
||||
Assert.Single(result.Items);
|
||||
Assert.Equal("Site A", result.Items[0].Name);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetSiteAsync_ReturnsSite()
|
||||
{
|
||||
SetAuthToken();
|
||||
var id = Guid.NewGuid();
|
||||
var expected = new SiteItem(id, "My Site", null, "UTC", null, true, DateTime.UtcNow);
|
||||
_handler.QueueResponse(HttpStatusCode.OK, expected);
|
||||
|
||||
var result = await _sut.GetSiteAsync(id);
|
||||
|
||||
Assert.NotNull(result);
|
||||
Assert.Equal("My Site", result.Name);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task UpdateSiteAsync_WhenSuccess_ReturnsTrue()
|
||||
{
|
||||
SetAuthToken();
|
||||
_handler.QueueResponse(HttpStatusCode.OK);
|
||||
|
||||
var result = await _sut.UpdateSiteAsync(Guid.NewGuid(), "New Name", "Addr", "UTC");
|
||||
|
||||
Assert.True(result);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task UpdateSiteAsync_WhenFails_ReturnsFalse()
|
||||
{
|
||||
SetAuthToken();
|
||||
_handler.QueueResponse(HttpStatusCode.BadRequest);
|
||||
|
||||
var result = await _sut.UpdateSiteAsync(Guid.NewGuid(), "", null, null);
|
||||
|
||||
Assert.False(result);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task DeleteSiteAsync_WhenSuccess_ReturnsTrue()
|
||||
{
|
||||
SetAuthToken();
|
||||
_handler.QueueResponse(HttpStatusCode.OK);
|
||||
|
||||
var result = await _sut.DeleteSiteAsync(Guid.NewGuid());
|
||||
|
||||
Assert.True(result);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GenerateSiteTokenAsync_WhenSuccess_ReturnsToken()
|
||||
{
|
||||
SetAuthToken();
|
||||
var expected = new TokenResult("tok-123", DateTime.UtcNow.AddHours(1));
|
||||
_handler.QueueResponse(HttpStatusCode.OK, expected);
|
||||
|
||||
var result = await _sut.GenerateSiteTokenAsync(Guid.NewGuid());
|
||||
|
||||
Assert.NotNull(result);
|
||||
Assert.Equal("tok-123", result.Token);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GenerateSiteTokenAsync_WhenFails_ReturnsNull()
|
||||
{
|
||||
SetAuthToken();
|
||||
_handler.QueueResponse(HttpStatusCode.NotFound);
|
||||
|
||||
var result = await _sut.GenerateSiteTokenAsync(Guid.NewGuid());
|
||||
|
||||
Assert.Null(result);
|
||||
}
|
||||
|
||||
// ── Users ───────────────────────────────────────────────────────
|
||||
|
||||
[Fact]
|
||||
public async Task GetUsersAsync_ReturnsPagedData()
|
||||
{
|
||||
SetAuthToken();
|
||||
var expected = new PagedData<UserItem>(
|
||||
[new UserItem { Id = Guid.NewGuid(), Email = "u@t.com" }], 1, 1, 20);
|
||||
_handler.QueueResponse(HttpStatusCode.OK, expected);
|
||||
|
||||
var result = await _sut.GetUsersAsync();
|
||||
|
||||
Assert.NotNull(result);
|
||||
Assert.Single(result.Items);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetUserAsync_ReturnsUser()
|
||||
{
|
||||
SetAuthToken();
|
||||
var id = Guid.NewGuid();
|
||||
_handler.QueueResponse(HttpStatusCode.OK, new UserItem { Id = id, Email = "u@t.com" });
|
||||
|
||||
var result = await _sut.GetUserAsync(id);
|
||||
|
||||
Assert.NotNull(result);
|
||||
Assert.Equal(id, result.Id);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task CreateUserAsync_WhenSuccess_ReturnsUser()
|
||||
{
|
||||
SetAuthToken();
|
||||
var expected = new UserItem { Id = Guid.NewGuid(), Email = "new@t.com" };
|
||||
_handler.QueueResponse(HttpStatusCode.OK, expected);
|
||||
|
||||
var result = await _sut.CreateUserAsync("new@t.com", "pwd", "New", ["Admin"]);
|
||||
|
||||
Assert.NotNull(result);
|
||||
Assert.Equal("new@t.com", result.Email);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task CreateUserAsync_WhenFails_ReturnsNull()
|
||||
{
|
||||
SetAuthToken();
|
||||
_handler.QueueResponse(HttpStatusCode.BadRequest);
|
||||
|
||||
var result = await _sut.CreateUserAsync("bad", "", "", []);
|
||||
|
||||
Assert.Null(result);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task UpdateUserAsync_WhenSuccess_ReturnsTrue()
|
||||
{
|
||||
SetAuthToken();
|
||||
_handler.QueueResponse(HttpStatusCode.OK);
|
||||
|
||||
var result = await _sut.UpdateUserAsync(Guid.NewGuid(), "New Name", null, null);
|
||||
|
||||
Assert.True(result);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task AssignRolesAsync_WhenSuccess_ReturnsTrue()
|
||||
{
|
||||
SetAuthToken();
|
||||
_handler.QueueResponse(HttpStatusCode.OK);
|
||||
|
||||
var result = await _sut.AssignRolesAsync(Guid.NewGuid(), ["Admin"]);
|
||||
|
||||
Assert.True(result);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task AssignSitesAsync_WhenSuccess_ReturnsTrue()
|
||||
{
|
||||
SetAuthToken();
|
||||
_handler.QueueResponse(HttpStatusCode.OK);
|
||||
|
||||
var result = await _sut.AssignSitesAsync(Guid.NewGuid(), [Guid.NewGuid()]);
|
||||
|
||||
Assert.True(result);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ResetPasswordAsync_WhenSuccess_ReturnsResult()
|
||||
{
|
||||
SetAuthToken();
|
||||
var expected = new PasswordResetResult("new-pwd-123");
|
||||
_handler.QueueResponse(HttpStatusCode.OK, expected);
|
||||
|
||||
var result = await _sut.ResetPasswordAsync(Guid.NewGuid());
|
||||
|
||||
Assert.NotNull(result);
|
||||
Assert.Equal("new-pwd-123", result.TemporaryPassword);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ResetPasswordAsync_WhenFails_ReturnsNull()
|
||||
{
|
||||
SetAuthToken();
|
||||
_handler.QueueResponse(HttpStatusCode.NotFound);
|
||||
|
||||
var result = await _sut.ResetPasswordAsync(Guid.NewGuid());
|
||||
|
||||
Assert.Null(result);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task LockUserAsync_WhenSuccess_ReturnsTrue()
|
||||
{
|
||||
SetAuthToken();
|
||||
_handler.QueueResponse(HttpStatusCode.OK);
|
||||
|
||||
var result = await _sut.LockUserAsync(Guid.NewGuid());
|
||||
|
||||
Assert.True(result);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task UnlockUserAsync_WhenSuccess_ReturnsTrue()
|
||||
{
|
||||
SetAuthToken();
|
||||
_handler.QueueResponse(HttpStatusCode.OK);
|
||||
|
||||
var result = await _sut.UnlockUserAsync(Guid.NewGuid());
|
||||
|
||||
Assert.True(result);
|
||||
}
|
||||
|
||||
// ── Cameras ─────────────────────────────────────────────────────
|
||||
|
||||
[Fact]
|
||||
public async Task GetCamerasBySiteAsync_ReturnsPagedData()
|
||||
{
|
||||
SetAuthToken();
|
||||
var expected = new PagedData<CameraItem>(
|
||||
[new CameraItem { Id = Guid.NewGuid(), Name = "Cam 1" }], 1, 1, 20);
|
||||
_handler.QueueResponse(HttpStatusCode.OK, expected);
|
||||
|
||||
var result = await _sut.GetCamerasBySiteAsync(Guid.NewGuid());
|
||||
|
||||
Assert.NotNull(result);
|
||||
Assert.Single(result.Items);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetCameraAsync_ReturnsCamera()
|
||||
{
|
||||
SetAuthToken();
|
||||
var id = Guid.NewGuid();
|
||||
_handler.QueueResponse(HttpStatusCode.OK, new CameraItem { Id = id, Name = "Cam" });
|
||||
|
||||
var result = await _sut.GetCameraAsync(id);
|
||||
|
||||
Assert.NotNull(result);
|
||||
Assert.Equal("Cam", result.Name);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task UpdateCameraAsync_WhenSuccess_ReturnsTrue()
|
||||
{
|
||||
SetAuthToken();
|
||||
_handler.QueueResponse(HttpStatusCode.OK);
|
||||
|
||||
var result = await _sut.UpdateCameraAsync(Guid.NewGuid(), "Cam", "rtsp://cam", "Online");
|
||||
|
||||
Assert.True(result);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task DeleteCameraAsync_WhenSuccess_ReturnsTrue()
|
||||
{
|
||||
SetAuthToken();
|
||||
_handler.QueueResponse(HttpStatusCode.OK);
|
||||
|
||||
var result = await _sut.DeleteCameraAsync(Guid.NewGuid());
|
||||
|
||||
Assert.True(result);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task DeleteCameraAsync_WhenFails_ReturnsFalse()
|
||||
{
|
||||
SetAuthToken();
|
||||
_handler.QueueResponse(HttpStatusCode.NotFound);
|
||||
|
||||
var result = await _sut.DeleteCameraAsync(Guid.NewGuid());
|
||||
|
||||
Assert.False(result);
|
||||
}
|
||||
|
||||
// ── Settings ────────────────────────────────────────────────────
|
||||
|
||||
[Fact]
|
||||
public async Task GetSettingsAsync_ReturnsList()
|
||||
{
|
||||
SetAuthToken();
|
||||
_handler.QueueResponse(HttpStatusCode.OK, new List<AppSettingItem>());
|
||||
|
||||
var result = await _sut.GetSettingsAsync();
|
||||
|
||||
Assert.NotNull(result);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task CreateSettingAsync_ReturnsResponse()
|
||||
{
|
||||
SetAuthToken();
|
||||
_handler.QueueResponse(HttpStatusCode.OK);
|
||||
|
||||
var result = await _sut.CreateSettingAsync(new CreateAppSettingRequest("key", "val"));
|
||||
|
||||
Assert.Equal(HttpStatusCode.OK, result.StatusCode);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task UpdateSettingAsync_ReturnsResponse()
|
||||
{
|
||||
SetAuthToken();
|
||||
_handler.QueueResponse(HttpStatusCode.OK);
|
||||
|
||||
var result = await _sut.UpdateSettingAsync("key", new UpdateAppSettingRequest("new-val"));
|
||||
|
||||
Assert.Equal(HttpStatusCode.OK, result.StatusCode);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task DeleteSettingAsync_ReturnsResponse()
|
||||
{
|
||||
SetAuthToken();
|
||||
_handler.QueueResponse(HttpStatusCode.OK);
|
||||
|
||||
var result = await _sut.DeleteSettingAsync("key");
|
||||
|
||||
Assert.Equal(HttpStatusCode.OK, result.StatusCode);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task TestStorageAsync_WhenSuccess_ReturnsResult()
|
||||
{
|
||||
SetAuthToken();
|
||||
_handler.QueueResponse(HttpStatusCode.OK, new StorageTestResult("Minio", true, true));
|
||||
|
||||
var result = await _sut.TestStorageAsync();
|
||||
|
||||
Assert.NotNull(result);
|
||||
Assert.True(result.Healthy);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task TestStorageAsync_WhenFails_ReturnsNull()
|
||||
{
|
||||
SetAuthToken();
|
||||
_handler.QueueResponse(HttpStatusCode.InternalServerError);
|
||||
|
||||
var result = await _sut.TestStorageAsync();
|
||||
|
||||
Assert.Null(result);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task TestEmailAsync_WhenSuccess_ReturnsResult()
|
||||
{
|
||||
SetAuthToken();
|
||||
_handler.QueueResponse(HttpStatusCode.OK, new TestActionResult(true, "Sent"));
|
||||
|
||||
var result = await _sut.TestEmailAsync();
|
||||
|
||||
Assert.NotNull(result);
|
||||
Assert.True(result.Success);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task TestEmailAsync_WhenFails_ReturnsNull()
|
||||
{
|
||||
SetAuthToken();
|
||||
_handler.QueueResponse(HttpStatusCode.InternalServerError);
|
||||
|
||||
var result = await _sut.TestEmailAsync();
|
||||
|
||||
Assert.Null(result);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task TestNtfyAsync_WhenSuccess_ReturnsResult()
|
||||
{
|
||||
SetAuthToken();
|
||||
_handler.QueueResponse(HttpStatusCode.OK, new TestActionResult(true, "Sent"));
|
||||
|
||||
var result = await _sut.TestNtfyAsync();
|
||||
|
||||
Assert.NotNull(result);
|
||||
Assert.True(result.Success);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task TestAiAsync_WhenSuccess_ReturnsResult()
|
||||
{
|
||||
SetAuthToken();
|
||||
_handler.QueueResponse(HttpStatusCode.OK, new TestActionResult(true, "OK"));
|
||||
|
||||
var result = await _sut.TestAiAsync();
|
||||
|
||||
Assert.NotNull(result);
|
||||
Assert.True(result.Success);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ReloadAllConfigAsync_ReturnsResponse()
|
||||
{
|
||||
SetAuthToken();
|
||||
_handler.QueueResponse(HttpStatusCode.OK);
|
||||
|
||||
var result = await _sut.ReloadAllConfigAsync();
|
||||
|
||||
Assert.Equal(HttpStatusCode.OK, result.StatusCode);
|
||||
}
|
||||
|
||||
// ── Agent Settings ──────────────────────────────────────────────
|
||||
|
||||
[Fact]
|
||||
public async Task GetAgentSettingsAsync_ReturnsList()
|
||||
{
|
||||
SetAuthToken();
|
||||
_handler.QueueResponse(HttpStatusCode.OK, new List<AgentSettingItem>());
|
||||
|
||||
var result = await _sut.GetAgentSettingsAsync(Guid.NewGuid());
|
||||
|
||||
Assert.NotNull(result);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task SetAgentSettingAsync_ReturnsResponse()
|
||||
{
|
||||
SetAuthToken();
|
||||
_handler.QueueResponse(HttpStatusCode.OK);
|
||||
|
||||
var result = await _sut.SetAgentSettingAsync(
|
||||
Guid.NewGuid(), new SetAgentSettingRequest("key", "val"));
|
||||
|
||||
Assert.Equal(HttpStatusCode.OK, result.StatusCode);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task RemoveAgentSettingAsync_ReturnsResponse()
|
||||
{
|
||||
SetAuthToken();
|
||||
_handler.QueueResponse(HttpStatusCode.OK);
|
||||
|
||||
var result = await _sut.RemoveAgentSettingAsync(Guid.NewGuid(), "key");
|
||||
|
||||
Assert.Equal(HttpStatusCode.OK, result.StatusCode);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetEffectiveAgentConfigAsync_ReturnsDict()
|
||||
{
|
||||
SetAuthToken();
|
||||
_handler.QueueResponse(HttpStatusCode.OK, new Dictionary<string, string> { ["k"] = "v" });
|
||||
|
||||
var result = await _sut.GetEffectiveAgentConfigAsync(Guid.NewGuid());
|
||||
|
||||
Assert.NotNull(result);
|
||||
Assert.Equal("v", result["k"]);
|
||||
}
|
||||
|
||||
// ── Agents ──────────────────────────────────────────────────────
|
||||
|
||||
[Fact]
|
||||
public async Task GetAgentAsync_ReturnsAgent()
|
||||
{
|
||||
SetAuthToken();
|
||||
var id = Guid.NewGuid();
|
||||
_handler.QueueResponse(HttpStatusCode.OK, new AgentItem { Id = id, Name = "Agent 1" });
|
||||
|
||||
var result = await _sut.GetAgentAsync(id);
|
||||
|
||||
Assert.NotNull(result);
|
||||
Assert.Equal("Agent 1", result.Name);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetAgentsBySiteAsync_ReturnsPagedData()
|
||||
{
|
||||
SetAuthToken();
|
||||
var expected = new PagedData<AgentItem>(
|
||||
[new AgentItem { Id = Guid.NewGuid(), Name = "A1" }], 1, 1, 20);
|
||||
_handler.QueueResponse(HttpStatusCode.OK, expected);
|
||||
|
||||
var result = await _sut.GetAgentsBySiteAsync(Guid.NewGuid());
|
||||
|
||||
Assert.NotNull(result);
|
||||
Assert.Single(result.Items);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetAllAgentsAsync_ReturnsPagedData()
|
||||
{
|
||||
SetAuthToken();
|
||||
var expected = new PagedData<AgentItem>(
|
||||
[new AgentItem { Id = Guid.NewGuid(), Name = "All" }], 1, 1, 20);
|
||||
_handler.QueueResponse(HttpStatusCode.OK, expected);
|
||||
|
||||
var result = await _sut.GetAllAgentsAsync();
|
||||
|
||||
Assert.NotNull(result);
|
||||
Assert.Single(result.Items);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetAgentStatsAsync_ReturnsList()
|
||||
{
|
||||
SetAuthToken();
|
||||
_handler.QueueResponse(HttpStatusCode.OK, new List<AgentStatItem>());
|
||||
|
||||
var result = await _sut.GetAgentStatsAsync();
|
||||
|
||||
Assert.NotNull(result);
|
||||
}
|
||||
|
||||
// ── Events ──────────────────────────────────────────────────────
|
||||
|
||||
[Fact]
|
||||
public async Task GetEventsAsync_ReturnsPageResult()
|
||||
{
|
||||
SetAuthToken();
|
||||
var expected = new EventPageResult([], 0, 1, 50);
|
||||
_handler.QueueResponse(HttpStatusCode.OK, expected);
|
||||
|
||||
var result = await _sut.GetEventsAsync(null, null);
|
||||
|
||||
Assert.NotNull(result);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetRecentEventsAsync_ReturnsList()
|
||||
{
|
||||
SetAuthToken();
|
||||
_handler.QueueResponse(HttpStatusCode.OK, new List<EventItem>());
|
||||
|
||||
var result = await _sut.GetRecentEventsAsync(Guid.NewGuid());
|
||||
|
||||
Assert.NotNull(result);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetEventAsync_ReturnsEvent()
|
||||
{
|
||||
SetAuthToken();
|
||||
var id = Guid.NewGuid();
|
||||
_handler.QueueResponse(HttpStatusCode.OK, new EventItem(
|
||||
id, Guid.NewGuid(), "Motion", 0.95, "person", null, null,
|
||||
DateTime.UtcNow, DateTime.UtcNow));
|
||||
|
||||
var result = await _sut.GetEventAsync(id);
|
||||
|
||||
Assert.NotNull(result);
|
||||
Assert.Equal(id, result.Id);
|
||||
}
|
||||
|
||||
// ── Notification Config ─────────────────────────────────────────
|
||||
|
||||
[Fact]
|
||||
public async Task GetNotificationConfigAsync_ReturnsConfig()
|
||||
{
|
||||
SetAuthToken();
|
||||
_handler.QueueResponse(HttpStatusCode.OK, new NotificationConfigItem { EmailEnabled = true });
|
||||
|
||||
var result = await _sut.GetNotificationConfigAsync();
|
||||
|
||||
Assert.NotNull(result);
|
||||
Assert.True(result.EmailEnabled);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task UpdateNotificationConfigAsync_WhenSuccess_ReturnsTrue()
|
||||
{
|
||||
SetAuthToken();
|
||||
_handler.QueueResponse(HttpStatusCode.OK);
|
||||
|
||||
var result = await _sut.UpdateNotificationConfigAsync(
|
||||
new UpdateNotificationConfigRequest(true, "a@b.com", false, null, null, null, null));
|
||||
|
||||
Assert.True(result);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task UpdateNotificationConfigAsync_WhenFails_ReturnsFalse()
|
||||
{
|
||||
SetAuthToken();
|
||||
_handler.QueueResponse(HttpStatusCode.BadRequest);
|
||||
|
||||
var result = await _sut.UpdateNotificationConfigAsync(
|
||||
new UpdateNotificationConfigRequest(null, null, null, null, null, null, null));
|
||||
|
||||
Assert.False(result);
|
||||
}
|
||||
|
||||
// ── Site Credentials ────────────────────────────────────────────
|
||||
|
||||
[Fact]
|
||||
public async Task GetSiteCredentialsAsync_ReturnsList()
|
||||
{
|
||||
SetAuthToken();
|
||||
_handler.QueueResponse(HttpStatusCode.OK, new List<SiteCredentialItem>());
|
||||
|
||||
var result = await _sut.GetSiteCredentialsAsync(Guid.NewGuid());
|
||||
|
||||
Assert.NotNull(result);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task AddSiteCredentialAsync_WhenSuccess_ReturnsItem()
|
||||
{
|
||||
SetAuthToken();
|
||||
var expected = new SiteCredentialItem { Id = Guid.NewGuid(), Label = "cred" };
|
||||
_handler.QueueResponse(HttpStatusCode.OK, expected);
|
||||
|
||||
var result = await _sut.AddSiteCredentialAsync(Guid.NewGuid(), "cred", "user", "pass");
|
||||
|
||||
Assert.NotNull(result);
|
||||
Assert.Equal("cred", result.Label);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task AddSiteCredentialAsync_WhenFails_ReturnsNull()
|
||||
{
|
||||
SetAuthToken();
|
||||
_handler.QueueResponse(HttpStatusCode.BadRequest);
|
||||
|
||||
var result = await _sut.AddSiteCredentialAsync(Guid.NewGuid(), "", "", "");
|
||||
|
||||
Assert.Null(result);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task DeleteSiteCredentialAsync_WhenSuccess_ReturnsTrue()
|
||||
{
|
||||
SetAuthToken();
|
||||
_handler.QueueResponse(HttpStatusCode.OK);
|
||||
|
||||
var result = await _sut.DeleteSiteCredentialAsync(Guid.NewGuid(), Guid.NewGuid());
|
||||
|
||||
Assert.True(result);
|
||||
}
|
||||
|
||||
// ── Discovery ───────────────────────────────────────────────────
|
||||
|
||||
[Fact]
|
||||
public async Task GetPendingDiscoveriesAsync_ReturnsList()
|
||||
{
|
||||
SetAuthToken();
|
||||
_handler.QueueResponse(HttpStatusCode.OK, new List<PendingDiscoveryItem>());
|
||||
|
||||
var result = await _sut.GetPendingDiscoveriesAsync(Guid.NewGuid());
|
||||
|
||||
Assert.NotNull(result);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ScanNowAsync_WhenSuccess_ReturnsResult()
|
||||
{
|
||||
SetAuthToken();
|
||||
_handler.QueueResponse(HttpStatusCode.OK, new ScanNowResult(3));
|
||||
|
||||
var result = await _sut.ScanNowAsync(Guid.NewGuid());
|
||||
|
||||
Assert.NotNull(result);
|
||||
Assert.Equal(3, result.AgentsNotified);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ScanNowAsync_WhenFails_ReturnsNull()
|
||||
{
|
||||
SetAuthToken();
|
||||
_handler.QueueResponse(HttpStatusCode.NotFound);
|
||||
|
||||
var result = await _sut.ScanNowAsync(Guid.NewGuid());
|
||||
|
||||
Assert.Null(result);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task RejectDiscoveryAsync_WhenSuccess_ReturnsTrue()
|
||||
{
|
||||
SetAuthToken();
|
||||
_handler.QueueResponse(HttpStatusCode.OK);
|
||||
|
||||
var result = await _sut.RejectDiscoveryAsync(Guid.NewGuid());
|
||||
|
||||
Assert.True(result);
|
||||
}
|
||||
|
||||
// ── 2FA ─────────────────────────────────────────────────────────
|
||||
|
||||
[Fact]
|
||||
public async Task RegisterAsync_WhenSuccess_ReturnsAuthResponse()
|
||||
{
|
||||
var expected = new AuthResponse("access", "refresh", DateTime.UtcNow.AddHours(1), false,
|
||||
new UserInfo(Guid.NewGuid(), "a@b.com", "A", null));
|
||||
_handler.QueueResponse(HttpStatusCode.OK, expected);
|
||||
|
||||
var result = await _sut.RegisterAsync("a@b.com", "pwd", "Display");
|
||||
|
||||
Assert.NotNull(result);
|
||||
Assert.Equal("access", result.AccessToken);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task RegisterAsync_WhenFails_ReturnsNull()
|
||||
{
|
||||
_handler.QueueResponse(HttpStatusCode.BadRequest);
|
||||
|
||||
var result = await _sut.RegisterAsync("bad", "", "");
|
||||
|
||||
Assert.Null(result);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Verify2faAsync_WhenSuccess_ReturnsAuthResponse()
|
||||
{
|
||||
var expected = new AuthResponse("access", "refresh", DateTime.UtcNow.AddHours(1), false,
|
||||
new UserInfo(Guid.NewGuid(), "a@b.com", "A", null));
|
||||
_handler.QueueResponse(HttpStatusCode.OK, expected);
|
||||
|
||||
var result = await _sut.Verify2faAsync("a@b.com", "123456");
|
||||
|
||||
Assert.NotNull(result);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Verify2faAsync_WhenFails_ReturnsNull()
|
||||
{
|
||||
_handler.QueueResponse(HttpStatusCode.Unauthorized);
|
||||
|
||||
var result = await _sut.Verify2faAsync("a@b.com", "wrong");
|
||||
|
||||
Assert.Null(result);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Enable2faAsync_WhenSuccess_ReturnsResponse()
|
||||
{
|
||||
_handler.QueueResponse(HttpStatusCode.OK, new { secret = "abc", qrCode = "data" });
|
||||
|
||||
var result = await _sut.Enable2faAsync();
|
||||
|
||||
Assert.NotNull(result);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Enable2faAsync_WhenFails_ReturnsNull()
|
||||
{
|
||||
_handler.QueueResponse(HttpStatusCode.BadRequest);
|
||||
|
||||
var result = await _sut.Enable2faAsync();
|
||||
|
||||
Assert.Null(result);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Disable2faAsync_WhenSuccess_ReturnsTrue()
|
||||
{
|
||||
_handler.QueueResponse(HttpStatusCode.OK);
|
||||
|
||||
var result = await _sut.Disable2faAsync();
|
||||
|
||||
Assert.True(result);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Disable2faAsync_WhenFails_ReturnsFalse()
|
||||
{
|
||||
_handler.QueueResponse(HttpStatusCode.BadRequest);
|
||||
|
||||
var result = await _sut.Disable2faAsync();
|
||||
|
||||
Assert.False(result);
|
||||
}
|
||||
|
||||
// ── Profile ─────────────────────────────────────────────────────
|
||||
|
||||
[Fact]
|
||||
public async Task UpdateMyProfileAsync_WhenSuccess_ReturnsTrue()
|
||||
{
|
||||
SetAuthToken();
|
||||
_handler.QueueResponse(HttpStatusCode.OK);
|
||||
|
||||
var result = await _sut.UpdateMyProfileAsync("New Name", "dark", "fr");
|
||||
|
||||
Assert.True(result);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task UpdateMyProfileAsync_WhenFails_ReturnsFalse()
|
||||
{
|
||||
SetAuthToken();
|
||||
_handler.QueueResponse(HttpStatusCode.BadRequest);
|
||||
|
||||
var result = await _sut.UpdateMyProfileAsync("", null, null);
|
||||
|
||||
Assert.False(result);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ChangePasswordAsync_WhenSuccess_ReturnsTrue()
|
||||
{
|
||||
SetAuthToken();
|
||||
_handler.QueueResponse(HttpStatusCode.OK);
|
||||
|
||||
var result = await _sut.ChangePasswordAsync("old", "new");
|
||||
|
||||
Assert.True(result);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ChangePasswordAsync_WhenFails_ReturnsFalse()
|
||||
{
|
||||
SetAuthToken();
|
||||
_handler.QueueResponse(HttpStatusCode.BadRequest);
|
||||
|
||||
var result = await _sut.ChangePasswordAsync("wrong", "new");
|
||||
|
||||
Assert.False(result);
|
||||
}
|
||||
|
||||
// ── Agent Logs ──────────────────────────────────────────────────
|
||||
|
||||
[Fact]
|
||||
public async Task GetAgentLogsAsync_ReturnsPagedData()
|
||||
{
|
||||
SetAuthToken();
|
||||
var expected = new PagedData<AgentLogItem>(
|
||||
[new AgentLogItem { Id = Guid.NewGuid(), Message = "log" }], 1, 1, 50);
|
||||
_handler.QueueResponse(HttpStatusCode.OK, expected);
|
||||
|
||||
var result = await _sut.GetAgentLogsAsync(Guid.NewGuid());
|
||||
|
||||
Assert.NotNull(result);
|
||||
Assert.Single(result.Items);
|
||||
}
|
||||
|
||||
// ── SiteItem ────────────────────────────────────────────────────
|
||||
|
||||
[Fact]
|
||||
public async Task GetGroupAsync_ReturnsGroup()
|
||||
{
|
||||
SetAuthToken();
|
||||
var id = Guid.NewGuid();
|
||||
_handler.QueueResponse(HttpStatusCode.OK, new GroupItem { Id = id, Name = "G1" });
|
||||
|
||||
var result = await _sut.GetGroupAsync(id);
|
||||
|
||||
Assert.NotNull(result);
|
||||
Assert.Equal("G1", result.Name);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task UpdateGroupAsync_WhenSuccess_ReturnsTrue()
|
||||
{
|
||||
SetAuthToken();
|
||||
_handler.QueueResponse(HttpStatusCode.OK);
|
||||
|
||||
var result = await _sut.UpdateGroupAsync(Guid.NewGuid(), "New", "desc");
|
||||
|
||||
Assert.True(result);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task UpdateGroupAsync_WhenFails_ReturnsFalse()
|
||||
{
|
||||
SetAuthToken();
|
||||
_handler.QueueResponse(HttpStatusCode.BadRequest);
|
||||
|
||||
var result = await _sut.UpdateGroupAsync(Guid.NewGuid(), "", null);
|
||||
|
||||
Assert.False(result);
|
||||
}
|
||||
|
||||
// ── ReadErrorMessage edge cases ─────────────────────────────────
|
||||
|
||||
[Fact]
|
||||
public async Task CreateSiteAsync_WhenValidationErrors_ReturnsJoinedMessages()
|
||||
{
|
||||
SetAuthToken();
|
||||
_handler.QueueResponse(HttpStatusCode.BadRequest, new
|
||||
{
|
||||
errors = new
|
||||
{
|
||||
Name = new[] { "Le nom est requis" },
|
||||
Timezone = new[] { "Fuseau horaire invalide" }
|
||||
}
|
||||
});
|
||||
|
||||
var result = await _sut.CreateSiteAsync("", null, "bad");
|
||||
|
||||
Assert.False(result.Succeeded);
|
||||
Assert.NotNull(result.ErrorMessage);
|
||||
Assert.Contains("Le nom est requis", result.ErrorMessage);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task CreateSiteAsync_WhenNullBody_ReturnsInvalidResponse()
|
||||
{
|
||||
SetAuthToken();
|
||||
_handler.QueueRawResponse(HttpStatusCode.OK, "null");
|
||||
|
||||
var result = await _sut.CreateSiteAsync("Site", null, "UTC");
|
||||
|
||||
Assert.False(result.Succeeded);
|
||||
Assert.Equal("Réponse du serveur invalide.", result.ErrorMessage);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task CreateCameraAsync_WhenNullBody_ReturnsInvalidResponse()
|
||||
{
|
||||
SetAuthToken();
|
||||
_handler.QueueRawResponse(HttpStatusCode.OK, "null");
|
||||
|
||||
var result = await _sut.CreateCameraAsync(Guid.NewGuid(), "Cam", "rtsp://cam", null, null);
|
||||
|
||||
Assert.False(result.Succeeded);
|
||||
Assert.Equal("Réponse du serveur invalide.", result.ErrorMessage);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ConfirmDiscoveryAsync_WhenNullBody_ReturnsInvalidResponse()
|
||||
{
|
||||
SetAuthToken();
|
||||
_handler.QueueRawResponse(HttpStatusCode.OK, "null");
|
||||
|
||||
var result = await _sut.ConfirmDiscoveryAsync(
|
||||
Guid.NewGuid(), Guid.NewGuid(), "Cam", "rtsp://cam", null, null);
|
||||
|
||||
Assert.False(result.Succeeded);
|
||||
Assert.Equal("Réponse du serveur invalide.", result.ErrorMessage);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user