diff --git a/.forgejo/workflows/ci.yml b/.forgejo/workflows/ci.yml index 8532077..7e75ebf 100644 --- a/.forgejo/workflows/ci.yml +++ b/.forgejo/workflows/ci.yml @@ -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 diff --git a/src/Heimdall.Agent/Heimdall.Agent.csproj b/src/Heimdall.Agent/Heimdall.Agent.csproj index 20b4527..de45962 100644 --- a/src/Heimdall.Agent/Heimdall.Agent.csproj +++ b/src/Heimdall.Agent/Heimdall.Agent.csproj @@ -21,6 +21,6 @@ - + diff --git a/src/Heimdall.Agent/Program.cs b/src/Heimdall.Agent/Program.cs index 208197c..0eb0b2a 100644 --- a/src/Heimdall.Agent/Program.cs +++ b/src/Heimdall.Agent/Program.cs @@ -82,6 +82,14 @@ builder.Services.AddSingleton(sp => }); builder.Services.AddSingleton(); + +// Inventory providers (grouped under InventoryProviders to reduce constructor parameter count) +builder.Services.AddSingleton(); +builder.Services.AddSingleton(); +builder.Services.AddSingleton(); +builder.Services.AddSingleton(); +builder.Services.AddSingleton(); + builder.Services.AddSingleton(); builder.Services.AddSingleton(); builder.Services.AddSingleton(); diff --git a/src/Heimdall.Agent/Services/AgentRegistrationService.cs b/src/Heimdall.Agent/Services/AgentRegistrationService.cs index 7580322..df59b6c 100644 --- a/src/Heimdall.Agent/Services/AgentRegistrationService.cs +++ b/src/Heimdall.Agent/Services/AgentRegistrationService.cs @@ -5,6 +5,21 @@ using Microsoft.Extensions.Options; namespace Heimdall.Agent.Services; +/// +/// Groups inventory-related services to reduce constructor parameter count. +/// +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; +} + /// /// Registers this agent with the Heimdall Central server and manages the heartbeat loop. /// @@ -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; + /// Interval for full inventory refresh (5 minutes). + 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 options, SystemMetricsProvider metrics, + InventoryProviders providers, Logging.LogBufferService buffer, ILogger 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(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(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 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); diff --git a/src/Heimdall.Agent/Services/CgroupReader.cs b/src/Heimdall.Agent/Services/CgroupReader.cs new file mode 100644 index 0000000..59ee734 --- /dev/null +++ b/src/Heimdall.Agent/Services/CgroupReader.cs @@ -0,0 +1,88 @@ +namespace Heimdall.Agent.Services; + +/// +/// Shared cgroup limit readers. Eliminates duplication between +/// and . +/// +internal static class CgroupReader +{ + /// + /// 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. + /// + 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; + } + } + + /// + /// Reads the memory limit from cgroup v1/v2. Returns bytes, or null if unlimited. + /// + 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; + } +} diff --git a/src/Heimdall.Agent/Services/CommandRunner.cs b/src/Heimdall.Agent/Services/CommandRunner.cs new file mode 100644 index 0000000..1516d71 --- /dev/null +++ b/src/Heimdall.Agent/Services/CommandRunner.cs @@ -0,0 +1,46 @@ +using System.Diagnostics; + +namespace Heimdall.Agent.Services; + +/// +/// Shared utility for running external commands. Eliminates duplication +/// across GpuInventoryProvider, HostInfoProvider, and other providers. +/// +internal static class CommandRunner +{ + /// + /// Runs an external command and returns its standard output. + /// Returns null on failure or timeout. + /// + 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; + } + } +} diff --git a/src/Heimdall.Agent/Services/ContainerInfoProvider.cs b/src/Heimdall.Agent/Services/ContainerInfoProvider.cs new file mode 100644 index 0000000..1c43167 --- /dev/null +++ b/src/Heimdall.Agent/Services/ContainerInfoProvider.cs @@ -0,0 +1,136 @@ +namespace Heimdall.Agent.Services; + +/// +/// Detects container environment (Docker, Podman, etc.) and reads cgroup limits. +/// +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; + } +} + +/// +/// Container environment information. +/// +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; } +} diff --git a/src/Heimdall.Agent/Services/CpuInfoProvider.cs b/src/Heimdall.Agent/Services/CpuInfoProvider.cs new file mode 100644 index 0000000..8057308 --- /dev/null +++ b/src/Heimdall.Agent/Services/CpuInfoProvider.cs @@ -0,0 +1,204 @@ +using System.Runtime.InteropServices; +using System.Text.RegularExpressions; + +namespace Heimdall.Agent.Services; + +/// +/// Collects CPU inventory information from /proc/cpuinfo, topology, and cgroup limits. +/// +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 ParseProcCpuinfo() + { + var result = new Dictionary(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(); + 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; + } + + /// + /// Filters CPU flags to only include key modern instruction set flags. + /// + 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; + } + } +} + +/// +/// CPU inventory data collected from the system. +/// +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; } +} diff --git a/src/Heimdall.Agent/Services/DiskInventoryProvider.cs b/src/Heimdall.Agent/Services/DiskInventoryProvider.cs new file mode 100644 index 0000000..8bade7d --- /dev/null +++ b/src/Heimdall.Agent/Services/DiskInventoryProvider.cs @@ -0,0 +1,160 @@ +namespace Heimdall.Agent.Services; + +/// +/// Enumerates disk mounts from /proc/mounts and detects disk type (SSD/HDD) from sysfs. +/// +public sealed class DiskInventoryProvider +{ + private const string ProcMountsPath = "/proc/mounts"; + private const string Unknown = "Unknown"; + + public IReadOnlyList Collect() + { + var disks = new List(); + 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 ParseProcMounts() + { + var mounts = new List(); + try + { + if (!File.Exists(ProcMountsPath)) + return mounts; + + HashSet 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; + } + + /// + /// Detects disk type (SSD/HDD) by checking /sys/block/*/queue/rotation. + /// rotation=0 means SSD, rotation=1 means HDD. + /// + 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; } = ""; + } +} + +/// +/// Disk inventory data for a single mount point. +/// +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"; +} diff --git a/src/Heimdall.Agent/Services/FrameAnalyzerService.cs b/src/Heimdall.Agent/Services/FrameAnalyzerService.cs index 4848f60..6a701a8 100644 --- a/src/Heimdall.Agent/Services/FrameAnalyzerService.cs +++ b/src/Heimdall.Agent/Services/FrameAnalyzerService.cs @@ -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(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().ToArray(); - return ParseYoloOutput(output, image.Width, image.Height); + return ParseYoloOutput(output, (int)image.Width, (int)image.Height); } /// - /// 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]. /// - private static DenseTensor PreprocessImage(Image image) + private static DenseTensor PreprocessImage(MagickImage image) { var tensor = new DenseTensor([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(); } + /// + /// Mark overlapping candidates of the same class as suppressed. + /// Extracted from ApplyNms to reduce cognitive complexity (S3776). + /// + private static void SuppressOverlapping( + List 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); diff --git a/src/Heimdall.Agent/Services/GpuInventoryProvider.cs b/src/Heimdall.Agent/Services/GpuInventoryProvider.cs new file mode 100644 index 0000000..ee24b79 --- /dev/null +++ b/src/Heimdall.Agent/Services/GpuInventoryProvider.cs @@ -0,0 +1,296 @@ +using System.Text.Json; +using System.Text.RegularExpressions; + +namespace Heimdall.Agent.Services; + +/// +/// Collects GPU inventory information via nvidia-smi, sysfs DRM, vainfo, and rocm-smi. +/// Supports multi-GPU configurations. +/// +public sealed partial class GpuInventoryProvider +{ + // SonarQube S1118: prevent instantiation — all members are static. + private GpuInventoryProvider() { } + + private const string DeviceDir = "device"; + + public static IReadOnlyList 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 CollectNvidiaSmi() + { + var gpus = new List(); + 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 CollectDrmDevices() + { + var gpus = new List(); + 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 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 CollectRocmSmi() + { + var gpus = new List(); + 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(); +} + +/// +/// GPU inventory data for a single GPU device. +/// +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; } +} diff --git a/src/Heimdall.Agent/Services/HostInfoProvider.cs b/src/Heimdall.Agent/Services/HostInfoProvider.cs new file mode 100644 index 0000000..8bb94ba --- /dev/null +++ b/src/Heimdall.Agent/Services/HostInfoProvider.cs @@ -0,0 +1,291 @@ +using System.Diagnostics; +using System.Net.NetworkInformation; + +namespace Heimdall.Agent.Services; + +/// +/// Collects host information: OS, kernel, uptime, network interfaces, and temperature. +/// +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 CollectNetworkInterfaces() + { + var interfaces = new List(); + 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 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 CollectTemperature() + { + var temps = new List(); + 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; + } +} + +/// +/// Host information data. +/// +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 NetworkInterfaces { get; init; } = []; + public List Temperature { get; init; } = []; +} + +/// +/// Network interface information. +/// +public sealed record NetworkInterfaceInfo +{ + public string Name { get; init; } = ""; + public string? IpAddress { get; init; } + public string? MacAddress { get; init; } + public long? SpeedMbps { get; init; } +} + +/// +/// Thermal zone temperature information. +/// +public sealed record TemperatureInfo +{ + public string Zone { get; init; } = ""; + public double TemperatureCelsius { get; init; } +} diff --git a/src/Heimdall.Agent/Services/LogUploadService.cs b/src/Heimdall.Agent/Services/LogUploadService.cs index b35d6a4..14b5394 100644 --- a/src/Heimdall.Agent/Services/LogUploadService.cs +++ b/src/Heimdall.Agent/Services/LogUploadService.cs @@ -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); } } diff --git a/src/Heimdall.Agent/Services/MemoryReader.cs b/src/Heimdall.Agent/Services/MemoryReader.cs new file mode 100644 index 0000000..a7c44f0 --- /dev/null +++ b/src/Heimdall.Agent/Services/MemoryReader.cs @@ -0,0 +1,39 @@ +namespace Heimdall.Agent.Services; + +/// +/// Shared memory info reader from /proc/meminfo. Eliminates duplication +/// in (GetMemoryTotal, GetMemoryAvailable, +/// GetSwapTotal, GetSwapFree are all the same pattern). +/// +internal static class MemoryReader +{ + private const string ProcMeminfoPath = "/proc/meminfo"; + + /// + /// Reads a named field from /proc/meminfo and returns its value in bytes. + /// Returns null if the field is not found or parsing fails. + /// + 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"); +} diff --git a/src/Heimdall.Agent/Services/NetworkCameraScanner.cs b/src/Heimdall.Agent/Services/NetworkCameraScanner.cs index 0168bee..80f7d13 100644 --- a/src/Heimdall.Agent/Services/NetworkCameraScanner.cs +++ b/src/Heimdall.Agent/Services/NetworkCameraScanner.cs @@ -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) diff --git a/src/Heimdall.Agent/Services/ProcFs.cs b/src/Heimdall.Agent/Services/ProcFs.cs new file mode 100644 index 0000000..d80cd6b --- /dev/null +++ b/src/Heimdall.Agent/Services/ProcFs.cs @@ -0,0 +1,33 @@ +namespace Heimdall.Agent.Services; + +/// +/// Shared utilities for reading Linux proc filesystem values. +/// +internal static class ProcFs +{ + /// + /// Gets machine uptime in seconds from /proc/uptime. + /// + 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; + } +} diff --git a/src/Heimdall.Agent/Services/RuntimeLogLevel.cs b/src/Heimdall.Agent/Services/RuntimeLogLevel.cs index d8f60ab..35307b5 100644 --- a/src/Heimdall.Agent/Services/RuntimeLogLevel.cs +++ b/src/Heimdall.Agent/Services/RuntimeLogLevel.cs @@ -22,16 +22,12 @@ public sealed class RuntimeLogLevel { private readonly ILoggerFactory _loggerFactory; private readonly LoggerFilterOptions _filterOptions; - private readonly IReadOnlyList _originalRules; private LoggerFilterRule? _currentRule; public RuntimeLogLevel(ILoggerFactory loggerFactory, IOptions 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(); } /// Current minimum level applied to all loggers. diff --git a/src/Heimdall.Agent/Services/SnapshotPipelineService.cs b/src/Heimdall.Agent/Services/SnapshotPipelineService.cs index e8beed2..7f7bc64 100644 --- a/src/Heimdall.Agent/Services/SnapshotPipelineService.cs +++ b/src/Heimdall.Agent/Services/SnapshotPipelineService.cs @@ -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. diff --git a/src/Heimdall.Agent/Services/SystemMetricsProvider.cs b/src/Heimdall.Agent/Services/SystemMetricsProvider.cs index a632e93..4b78ee8 100644 --- a/src/Heimdall.Agent/Services/SystemMetricsProvider.cs +++ b/src/Heimdall.Agent/Services/SystemMetricsProvider.cs @@ -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; } } /// @@ -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 diff --git a/src/Heimdall.Application/AgentLogs/Commands/SubmitAgentLogs/SubmitAgentLogsHandler.cs b/src/Heimdall.Application/AgentLogs/Commands/SubmitAgentLogs/SubmitAgentLogsHandler.cs index 2cc25a2..9598128 100644 --- a/src/Heimdall.Application/AgentLogs/Commands/SubmitAgentLogs/SubmitAgentLogsHandler.cs +++ b/src/Heimdall.Application/AgentLogs/Commands/SubmitAgentLogs/SubmitAgentLogsHandler.cs @@ -13,10 +13,10 @@ public class SubmitAgentLogsHandler : IRequestHandler _db = db; - public async Task Handle(SubmitAgentLogsCommand request, CancellationToken ct) + public async Task 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 _db = db; - public async Task>> Handle(GetAgentLogsQuery request, CancellationToken ct) + public async Task>> Handle(GetAgentLogsQuery request, CancellationToken cancellationToken) { var query = _db.AgentLogEntries.Where(e => e.AgentId == request.AgentId); @@ -37,7 +37,7 @@ public class GetAgentLogsHandler : IRequestHandler e.TimestampUtc) @@ -51,7 +51,7 @@ public class GetAgentLogsHandler : IRequestHandler>.Success( diff --git a/src/Heimdall.Application/Agents/AgentExtensions.cs b/src/Heimdall.Application/Agents/AgentExtensions.cs new file mode 100644 index 0000000..39b6bcb --- /dev/null +++ b/src/Heimdall.Application/Agents/AgentExtensions.cs @@ -0,0 +1,33 @@ +using Heimdall.Application.DTOs; +using Heimdall.Domain.Entities; + +namespace Heimdall.Application.Agents; +/// +/// Extension methods to map entity to DTO. +/// Centralizes the mapping used across GetAllAgents, GetAgentsBySite, and GetAgent queries. +/// +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); +} diff --git a/src/Heimdall.Application/Agents/AgentTelemetryMapping.cs b/src/Heimdall.Application/Agents/AgentTelemetryMapping.cs new file mode 100644 index 0000000..07e2a9e --- /dev/null +++ b/src/Heimdall.Application/Agents/AgentTelemetryMapping.cs @@ -0,0 +1,77 @@ +using Heimdall.Application.DTOs; +using Heimdall.Domain.Entities; + +namespace Heimdall.Application.Agents; + +/// +/// Shared mapping between entity and . +/// Eliminates field-by-field duplication across HeartbeatHandler and AgentExtensions. +/// +public static class AgentTelemetryMapping +{ + /// + /// Reads all telemetry properties from an entity + /// and returns them as an record. + /// + 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); + + /// + /// Applies all telemetry fields from a source + /// (HeartbeatCommand, AgentHeartbeatRequest, etc.) to an entity. + /// Preserves existing inventory when no new data is present. + /// + 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)); + } + } +} diff --git a/src/Heimdall.Application/Agents/Commands/Heartbeat/HeartbeatCommand.cs b/src/Heimdall.Application/Agents/Commands/Heartbeat/HeartbeatCommand.cs index eebb680..98ab5ef 100644 --- a/src/Heimdall.Application/Agents/Commands/Heartbeat/HeartbeatCommand.cs +++ b/src/Heimdall.Application/Agents/Commands/Heartbeat/HeartbeatCommand.cs @@ -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; + 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 +{ + /// Returns true if any CPU inventory field is non-null. + 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; + + /// Returns true if any memory/disk inventory field is non-null. + 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; + + /// Returns true if any host inventory field is non-null. + 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; + + /// Converts CPU inventory fields to . + public CpuInventoryData ToCpuInventoryData() => new( + CpuVendor, CpuModel, CpuArchitecture, + PhysicalCores, LogicalCores, ThreadsPerCore, + CpuFrequencyMhz, CpuFlags, CpuCacheBytes, ContainerCpuLimit); + + /// Converts memory/disk inventory fields to . + public MemoryDiskInventoryData ToMemoryDiskInventoryData() => new( + MemTotalBytes, MemAvailableBytes, SwapTotalBytes, SwapFreeBytes, + ContainerMemoryLimitBytes, DiskInventoryJson); + + /// Converts host inventory fields to . + public HostInventoryData ToHostInventoryData() => new( + OsName, KernelVersion, Arch, UptimeMachineSeconds, + ContainerId, ContainerImage, NetworkInterfacesJson, TemperatureJson); +} diff --git a/src/Heimdall.Application/Agents/Commands/Heartbeat/HeartbeatHandler.cs b/src/Heimdall.Application/Agents/Commands/Heartbeat/HeartbeatHandler.cs index b8a2314..e6e9dbe 100644 --- a/src/Heimdall.Application/Agents/Commands/Heartbeat/HeartbeatHandler.cs +++ b/src/Heimdall.Application/Agents/Commands/Heartbeat/HeartbeatHandler.cs @@ -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 public HeartbeatHandler(IApplicationDbContext db) => _db = db; - public async Task Handle(HeartbeatCommand request, CancellationToken ct) + public async Task 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); + } } diff --git a/src/Heimdall.Application/Agents/Queries/GetAgent/GetAgentQuery.cs b/src/Heimdall.Application/Agents/Queries/GetAgent/GetAgentQuery.cs index 8b97306..10a3dda 100644 --- a/src/Heimdall.Application/Agents/Queries/GetAgent/GetAgentQuery.cs +++ b/src/Heimdall.Application/Agents/Queries/GetAgent/GetAgentQuery.cs @@ -21,12 +21,6 @@ public class GetAgentHandler : IRequestHandler.NotFound("Agent not found"); - return ServiceResult.Success(MapResponse(agent)); + return ServiceResult.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); } diff --git a/src/Heimdall.Application/Agents/Queries/GetAgentsBySite/GetAgentsBySiteQuery.cs b/src/Heimdall.Application/Agents/Queries/GetAgentsBySite/GetAgentsBySiteQuery.cs index 00921b0..44d6abf 100644 --- a/src/Heimdall.Application/Agents/Queries/GetAgentsBySite/GetAgentsBySiteQuery.cs +++ b/src/Heimdall.Application/Agents/Queries/GetAgentsBySite/GetAgentsBySiteQuery.cs @@ -27,16 +27,10 @@ public class GetAgentsBySiteHandler : IRequestHandler MapResponse(a)) + .Select(a => a.ToResponse()) .ToListAsync(ct); return ServiceResult>.Success( new PagedResult(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); } diff --git a/src/Heimdall.Application/Agents/Queries/GetAllAgents/GetAllAgentsQuery.cs b/src/Heimdall.Application/Agents/Queries/GetAllAgents/GetAllAgentsQuery.cs index 0cd6faf..1935521 100644 --- a/src/Heimdall.Application/Agents/Queries/GetAllAgents/GetAllAgentsQuery.cs +++ b/src/Heimdall.Application/Agents/Queries/GetAllAgents/GetAllAgentsQuery.cs @@ -23,16 +23,10 @@ public class GetAllAgentsHandler : IRequestHandler MapResponse(a)) + .Select(a => a.ToResponse()) .ToListAsync(ct); return ServiceResult>.Success( new PagedResult(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); } diff --git a/src/Heimdall.Application/Cameras/Commands/ReportCameraStatus/ReportCameraStatusCommand.cs b/src/Heimdall.Application/Cameras/Commands/ReportCameraStatus/ReportCameraStatusCommand.cs index 39065aa..e8cb596 100644 --- a/src/Heimdall.Application/Cameras/Commands/ReportCameraStatus/ReportCameraStatusCommand.cs +++ b/src/Heimdall.Application/Cameras/Commands/ReportCameraStatus/ReportCameraStatusCommand.cs @@ -33,17 +33,17 @@ public class ReportCameraStatusCommandHandler : IRequestHandler Handle(ReportCameraStatusCommand request, CancellationToken ct) + public async Task 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 {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(); diff --git a/src/Heimdall.Application/DTOs/AgentDto.cs b/src/Heimdall.Application/DTOs/AgentDto.cs index 5f23ecc..78554d4 100644 --- a/src/Heimdall.Application/DTOs/AgentDto.cs +++ b/src/Heimdall.Application/DTOs/AgentDto.cs @@ -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, diff --git a/src/Heimdall.Application/DTOs/AgentTelemetryFields.cs b/src/Heimdall.Application/DTOs/AgentTelemetryFields.cs new file mode 100644 index 0000000..41fc8ac --- /dev/null +++ b/src/Heimdall.Application/DTOs/AgentTelemetryFields.cs @@ -0,0 +1,44 @@ +namespace Heimdall.Application.DTOs; + +/// +/// Common telemetry fields shared by AgentHeartbeatRequest, HeartbeatCommand, and AgentResponse. +/// Extracted to eliminate code duplication across these DTOs. +/// +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); diff --git a/src/Heimdall.Application/Discovery/CameraStreamTemplates.cs b/src/Heimdall.Application/Discovery/CameraStreamTemplates.cs index 055624a..9cef01c 100644 --- a/src/Heimdall.Application/Discovery/CameraStreamTemplates.cs +++ b/src/Heimdall.Application/Discovery/CameraStreamTemplates.cs @@ -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"); } diff --git a/src/Heimdall.Domain/Entities/Agent.cs b/src/Heimdall.Domain/Entities/Agent.cs index 35748b3..8876201 100644 --- a/src/Heimdall.Domain/Entities/Agent.cs +++ b/src/Heimdall.Domain/Entities/Agent.cs @@ -19,7 +19,7 @@ public class Agent : Entity, IAuditableEntity, ISoftDeletable /// First 8 characters of the API key for identification. 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, 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, 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; + } } + +/// +/// Groups CPU inventory fields to keep the update method under the parameter limit. +/// +public sealed record CpuInventoryData( + string? Vendor, + string? Model, + string? Architecture, + int? PhysicalCores, + int? LogicalCores, + int? ThreadsPerCore, + double? FrequencyMhz, + string? Flags, + long? CacheBytes, + long? ContainerCpuLimit); + +/// +/// Groups memory and disk inventory fields. +/// +public sealed record MemoryDiskInventoryData( + long? MemTotalBytes, + long? MemAvailableBytes, + long? SwapTotalBytes, + long? SwapFreeBytes, + long? ContainerMemoryLimitBytes, + string? DiskInventoryJson); + +/// +/// Groups host/container/network/temperature inventory fields. +/// +public sealed record HostInventoryData( + string? OsName, + string? KernelVersion, + string? Arch, + long? UptimeMachineSeconds, + string? ContainerId, + string? ContainerImage, + string? NetworkInterfacesJson, + string? TemperatureJson); diff --git a/src/Heimdall.Infrastructure/Jobs/DatabaseMaintenanceJob.cs b/src/Heimdall.Infrastructure/Jobs/DatabaseMaintenanceJob.cs index d075b5a..af16fef 100644 --- a/src/Heimdall.Infrastructure/Jobs/DatabaseMaintenanceJob.cs +++ b/src/Heimdall.Infrastructure/Jobs/DatabaseMaintenanceJob.cs @@ -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()); } diff --git a/src/Heimdall.Infrastructure/Migrations/20260818065253_AddAgentTelemetryInventory.Designer.cs b/src/Heimdall.Infrastructure/Migrations/20260818065253_AddAgentTelemetryInventory.Designer.cs new file mode 100644 index 0000000..ad477ff --- /dev/null +++ b/src/Heimdall.Infrastructure/Migrations/20260818065253_AddAgentTelemetryInventory.Designer.cs @@ -0,0 +1,2292 @@ +// +using System; +using Heimdall.Infrastructure.Data; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; +using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata; + +#nullable disable + +namespace Heimdall.Infrastructure.Migrations +{ + [DbContext(typeof(AppDbContext))] + [Migration("20260818065253_AddAgentTelemetryInventory")] + partial class AddAgentTelemetryInventory + { + /// + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder + .HasAnnotation("ProductVersion", "10.0.8") + .HasAnnotation("Relational:MaxIdentifierLength", 63); + + NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder); + + modelBuilder.Entity("Heimdall.Domain.Entities.Agent", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("ApiKeyHash") + .HasMaxLength(128) + .IsUnicode(false) + .HasColumnType("character varying(128)"); + + b.Property("ApiKeyPrefix") + .HasMaxLength(8) + .IsUnicode(false) + .HasColumnType("character varying(8)"); + + b.Property("Arch") + .HasColumnType("text"); + + b.Property("ContainerCpuLimit") + .HasColumnType("bigint"); + + b.Property("ContainerId") + .HasColumnType("text"); + + b.Property("ContainerImage") + .HasColumnType("text"); + + b.Property("ContainerMemoryLimitBytes") + .HasColumnType("bigint"); + + b.Property("CpuArchitecture") + .HasColumnType("text"); + + b.Property("CpuCacheBytes") + .HasColumnType("bigint"); + + b.Property("CpuCores") + .HasColumnType("integer"); + + b.Property("CpuFlags") + .HasColumnType("text"); + + b.Property("CpuFrequencyMhz") + .HasColumnType("double precision"); + + b.Property("CpuModel") + .HasColumnType("text"); + + b.Property("CpuUsagePercent") + .HasColumnType("double precision"); + + b.Property("CpuVendor") + .HasColumnType("text"); + + b.Property("CreatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("NOW()"); + + b.Property("DeletedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("DiskInventoryJson") + .HasColumnType("text"); + + b.Property("DiskUsagePercent") + .HasColumnType("double precision"); + + b.Property("GpuInventoryJson") + .HasColumnType("text"); + + b.Property("GpuType") + .IsRequired() + .HasMaxLength(20) + .IsUnicode(false) + .HasColumnType("character varying(20)"); + + b.Property("HasGpu") + .HasColumnType("boolean"); + + b.Property("Hostname") + .IsRequired() + .HasMaxLength(255) + .IsUnicode(false) + .HasColumnType("character varying(255)"); + + b.Property("IsDeleted") + .HasColumnType("boolean"); + + b.Property("KernelVersion") + .HasColumnType("text"); + + b.Property("LastHeartbeat") + .HasColumnType("timestamp with time zone"); + + b.Property("LogicalCores") + .HasColumnType("integer"); + + b.Property("MemAvailableBytes") + .HasColumnType("bigint"); + + b.Property("MemTotalBytes") + .HasColumnType("bigint"); + + b.Property("MemoryMb") + .HasColumnType("bigint"); + + b.Property("MemoryUsageBytes") + .HasColumnType("bigint"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(200) + .IsUnicode(false) + .HasColumnType("character varying(200)"); + + b.Property("NetworkInterfacesJson") + .HasColumnType("text"); + + b.Property("OsName") + .HasColumnType("text"); + + b.Property("PhysicalCores") + .HasColumnType("integer"); + + b.Property("PublicIp") + .HasMaxLength(45) + .IsUnicode(false) + .HasColumnType("character varying(45)"); + + b.Property("SiteId") + .HasColumnType("uuid"); + + b.Property("Status") + .IsRequired() + .HasMaxLength(20) + .IsUnicode(false) + .HasColumnType("character varying(20)"); + + b.Property("SwapFreeBytes") + .HasColumnType("bigint"); + + b.Property("SwapTotalBytes") + .HasColumnType("bigint"); + + b.Property("TemperatureJson") + .HasColumnType("text"); + + b.Property("ThreadsPerCore") + .HasColumnType("integer"); + + b.Property("UpdatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("NOW()"); + + b.Property("UptimeMachineSeconds") + .HasColumnType("bigint"); + + b.Property("UptimeSeconds") + .HasColumnType("bigint"); + + b.Property("Version") + .IsRequired() + .HasMaxLength(50) + .IsUnicode(false) + .HasColumnType("character varying(50)"); + + b.HasKey("Id"); + + b.HasIndex("LastHeartbeat") + .HasFilter("\"Status\" = 'Online'"); + + b.HasIndex("SiteId"); + + b.ToTable("agents", (string)null); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.AgentLogEntry", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("AgentId") + .HasColumnType("uuid"); + + b.Property("Exception") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.Property("Level") + .IsRequired() + .HasMaxLength(20) + .IsUnicode(false) + .HasColumnType("character varying(20)"); + + b.Property("Message") + .IsRequired() + .HasMaxLength(2000) + .HasColumnType("character varying(2000)"); + + b.Property("Source") + .HasMaxLength(200) + .IsUnicode(false) + .HasColumnType("character varying(200)"); + + b.Property("TimestampUtc") + .HasColumnType("timestamp with time zone"); + + b.HasKey("Id"); + + b.HasIndex("AgentId", "TimestampUtc"); + + b.ToTable("agent_log_entries", (string)null); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.AgentSetting", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("AgentId") + .HasColumnType("uuid") + .HasColumnName("agent_id"); + + b.Property("CreatedAt") + .HasColumnType("timestamp with time zone") + .HasColumnName("created_at"); + + b.Property("Key") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("character varying(200)") + .HasColumnName("key"); + + b.Property("UpdatedAt") + .HasColumnType("timestamp with time zone") + .HasColumnName("updated_at"); + + b.Property("Value") + .IsRequired() + .HasColumnType("text") + .HasColumnName("value"); + + b.HasKey("Id"); + + b.HasIndex("AgentId", "Key") + .IsUnique(); + + b.ToTable("agent_settings", (string)null); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.ApiKey", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("CreatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("NOW()"); + + b.Property("CreatedByUserId") + .HasColumnType("uuid"); + + b.Property("Enabled") + .HasColumnType("boolean"); + + b.Property("ExpiresAt") + .HasColumnType("timestamp with time zone"); + + b.Property("KeyHash") + .IsRequired() + .HasMaxLength(128) + .IsUnicode(false) + .HasColumnType("character varying(128)"); + + b.Property("KeyPrefix") + .IsRequired() + .HasMaxLength(8) + .IsUnicode(false) + .HasColumnType("character varying(8)"); + + b.Property("LastUsedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("SiteId") + .HasColumnType("uuid"); + + b.HasKey("Id"); + + b.HasIndex("KeyHash"); + + b.HasIndex("KeyPrefix"); + + b.HasIndex("SiteId"); + + b.ToTable("api_keys", (string)null); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.AppRole", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("ConcurrencyStamp") + .IsConcurrencyToken() + .HasColumnType("text"); + + b.Property("Name") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("NormalizedName") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.HasKey("Id"); + + b.HasIndex("NormalizedName") + .IsUnique() + .HasDatabaseName("RoleNameIndex"); + + b.ToTable("roles", (string)null); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.AppSetting", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("AgentScoped") + .HasColumnType("boolean"); + + b.Property("AllowedValues") + .HasMaxLength(2000) + .HasColumnType("character varying(2000)") + .HasColumnName("allowed_values"); + + b.Property("Category") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("character varying(100)") + .HasColumnName("category"); + + b.Property("CreatedAt") + .HasColumnType("timestamp with time zone") + .HasColumnName("created_at"); + + b.Property("Description") + .HasMaxLength(500) + .HasColumnType("character varying(500)") + .HasColumnName("description"); + + b.Property("Key") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("character varying(200)") + .HasColumnName("key"); + + b.Property("UpdatedAt") + .HasColumnType("timestamp with time zone") + .HasColumnName("updated_at"); + + b.Property("Value") + .IsRequired() + .HasColumnType("text") + .HasColumnName("value"); + + b.Property("ValueType") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("character varying(50)") + .HasColumnName("value_type"); + + b.HasKey("Id"); + + b.HasIndex("Key") + .IsUnique(); + + b.ToTable("app_settings", (string)null); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.AppUser", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("AccessFailedCount") + .HasColumnType("integer"); + + b.Property("ConcurrencyStamp") + .IsConcurrencyToken() + .HasColumnType("text"); + + b.Property("CreatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("NOW()"); + + b.Property("DisplayName") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("character varying(200)"); + + b.Property("Email") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("EmailConfirmed") + .HasColumnType("boolean"); + + b.Property("Language") + .IsRequired() + .ValueGeneratedOnAdd() + .HasMaxLength(10) + .IsUnicode(false) + .HasColumnType("character varying(10)") + .HasDefaultValue("fr"); + + b.Property("LockoutEnabled") + .HasColumnType("boolean"); + + b.Property("LockoutEnd") + .HasColumnType("timestamp with time zone"); + + b.Property("MustChangePassword") + .ValueGeneratedOnAdd() + .HasColumnType("boolean") + .HasDefaultValue(false); + + b.Property("NormalizedEmail") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("NormalizedUserName") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("PasswordHash") + .HasColumnType("text"); + + b.Property("PhoneNumber") + .HasColumnType("text"); + + b.Property("PhoneNumberConfirmed") + .HasColumnType("boolean"); + + b.Property("SecurityStamp") + .HasColumnType("text"); + + b.Property("Theme") + .ValueGeneratedOnAdd() + .HasMaxLength(20) + .IsUnicode(false) + .HasColumnType("character varying(20)") + .HasDefaultValue("Auto"); + + b.Property("TwoFactorEnabled") + .HasColumnType("boolean"); + + b.Property("UserName") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.HasKey("Id"); + + b.HasIndex("NormalizedEmail") + .HasDatabaseName("EmailIndex"); + + b.HasIndex("NormalizedUserName") + .IsUnique() + .HasDatabaseName("UserNameIndex"); + + b.ToTable("users", (string)null); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.AuditLog", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("Action") + .IsRequired() + .HasMaxLength(100) + .IsUnicode(false) + .HasColumnType("character varying(100)"); + + b.Property("IpAddress") + .HasMaxLength(45) + .IsUnicode(false) + .HasColumnType("character varying(45)"); + + b.Property("NewValue") + .HasColumnType("text"); + + b.Property("OldValue") + .HasColumnType("text"); + + b.Property("ResourceId") + .HasMaxLength(100) + .IsUnicode(false) + .HasColumnType("character varying(100)"); + + b.Property("ResourceType") + .IsRequired() + .HasMaxLength(100) + .IsUnicode(false) + .HasColumnType("character varying(100)"); + + b.Property("Timestamp") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("NOW()"); + + b.Property("UserId") + .HasColumnType("uuid"); + + b.HasKey("Id"); + + b.HasIndex("Timestamp") + .IsDescending(); + + b.HasIndex("UserId"); + + b.HasIndex("ResourceType", "ResourceId", "Timestamp") + .IsDescending(false, false, true); + + b.ToTable("audit_logs", (string)null); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.Camera", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("AgentId") + .HasColumnType("uuid"); + + b.Property("Capabilities") + .IsRequired() + .HasMaxLength(64) + .IsUnicode(false) + .HasColumnType("character varying(64)"); + + b.Property("CreatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("NOW()"); + + b.Property("DeletedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("DetectedType") + .IsRequired() + .HasMaxLength(20) + .IsUnicode(false) + .HasColumnType("character varying(20)"); + + b.Property("DiscoveryMethod") + .IsRequired() + .HasMaxLength(20) + .IsUnicode(false) + .HasColumnType("character varying(20)"); + + b.Property("HasAudio") + .HasColumnType("boolean"); + + b.Property("HasMotionDetection") + .HasColumnType("boolean"); + + b.Property("HasPtz") + .HasColumnType("boolean"); + + b.Property("HttpPort") + .HasColumnType("integer"); + + b.Property("IpAddress") + .HasMaxLength(45) + .HasColumnType("character varying(45)"); + + b.Property("IsDeleted") + .HasColumnType("boolean"); + + b.Property("LastDiscoveredAt") + .HasColumnType("timestamp with time zone"); + + b.Property("LastStreamTestAt") + .HasColumnType("timestamp with time zone"); + + b.Property("LastTestedCodecs") + .HasMaxLength(200) + .IsUnicode(false) + .HasColumnType("character varying(200)"); + + b.Property("LastTestedHeight") + .HasColumnType("integer"); + + b.Property("LastTestedLatencyMs") + .HasColumnType("bigint"); + + b.Property("LastTestedWidth") + .HasColumnType("integer"); + + b.Property("MacAddress") + .HasMaxLength(17) + .HasColumnType("character varying(17)"); + + b.Property("Manufacturer") + .HasMaxLength(100) + .HasColumnType("character varying(100)"); + + b.Property("Model") + .HasMaxLength(100) + .HasColumnType("character varying(100)"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(200) + .IsUnicode(false) + .HasColumnType("character varying(200)"); + + b.Property("OnvifPort") + .HasColumnType("integer"); + + b.Property("RtspPort") + .HasColumnType("integer"); + + b.Property("RtspUrl") + .HasMaxLength(1000) + .IsUnicode(false) + .HasColumnType("character varying(1000)"); + + b.Property("SiteId") + .HasColumnType("uuid"); + + b.Property("Status") + .IsRequired() + .HasMaxLength(20) + .IsUnicode(false) + .HasColumnType("character varying(20)"); + + b.Property("StoragePolicyId") + .HasColumnType("uuid"); + + b.Property("SubRtspUrl") + .HasMaxLength(1000) + .IsUnicode(false) + .HasColumnType("character varying(1000)"); + + b.Property("UpdatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("NOW()"); + + b.HasKey("Id"); + + b.HasIndex("AgentId"); + + b.HasIndex("IpAddress"); + + b.HasIndex("MacAddress"); + + b.HasIndex("SiteId"); + + b.HasIndex("StoragePolicyId"); + + b.ToTable("cameras", (string)null); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.CameraAssignment", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("AgentId") + .HasColumnType("uuid"); + + b.Property("AssignedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("CameraId") + .HasColumnType("uuid"); + + b.Property("Reason") + .IsRequired() + .HasMaxLength(50) + .IsUnicode(false) + .HasColumnType("character varying(50)"); + + b.Property("ReleasedAt") + .HasColumnType("timestamp with time zone"); + + b.HasKey("Id"); + + b.HasIndex("AssignedAt"); + + b.HasIndex("AgentId", "ReleasedAt") + .HasFilter("\"ReleasedAt\" IS NULL"); + + b.HasIndex("CameraId", "ReleasedAt") + .IsUnique() + .HasFilter("\"ReleasedAt\" IS NULL"); + + b.ToTable("camera_assignments", (string)null); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.CameraCredentials", b => + { + b.Property("CameraId") + .HasColumnType("uuid"); + + b.Property("CreatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("NOW()"); + + b.Property("OnvifPassword") + .IsRequired() + .HasMaxLength(500) + .IsUnicode(false) + .HasColumnType("character varying(500)"); + + b.Property("OnvifUsername") + .IsRequired() + .ValueGeneratedOnAdd() + .HasMaxLength(100) + .IsUnicode(false) + .HasColumnType("character varying(100)") + .HasDefaultValue("admin"); + + b.Property("RtspPassword") + .IsRequired() + .HasMaxLength(500) + .IsUnicode(false) + .HasColumnType("character varying(500)"); + + b.Property("RtspUsername") + .IsRequired() + .HasMaxLength(100) + .IsUnicode(false) + .HasColumnType("character varying(100)"); + + b.Property("UpdatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("NOW()"); + + b.HasKey("CameraId"); + + b.ToTable("camera_credentials", (string)null); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.CameraDetectionProfile", b => + { + b.Property("CameraId") + .HasColumnType("uuid"); + + b.Property("ActiveIntervalMs") + .HasColumnType("integer"); + + b.Property("AnimalCooldownSec") + .HasColumnType("integer"); + + b.Property("DetectAnimal") + .HasColumnType("boolean"); + + b.Property("DetectMotion") + .HasColumnType("boolean"); + + b.Property("DetectPackage") + .HasColumnType("boolean"); + + b.Property("DetectPerson") + .HasColumnType("boolean"); + + b.Property("DetectVehicle") + .HasColumnType("boolean"); + + b.Property("FaceRecognition") + .HasColumnType("boolean"); + + b.Property("IdleIntervalMs") + .HasColumnType("integer"); + + b.Property("IoUThreshold") + .HasColumnType("double precision"); + + b.Property("LicensePlateRecognition") + .HasColumnType("boolean"); + + b.Property("MaxEventsPerMinute") + .HasColumnType("integer"); + + b.Property("MinConfidence") + .ValueGeneratedOnAdd() + .HasColumnType("double precision") + .HasDefaultValue(0.40000000000000002); + + b.Property("MotionIntervalMs") + .HasColumnType("integer"); + + b.Property("MotionThreshold") + .HasColumnType("double precision"); + + b.Property("PersonCooldownSec") + .HasColumnType("integer"); + + b.Property("RequireMotionForAI") + .HasColumnType("boolean"); + + b.Property("VehicleCooldownSec") + .HasColumnType("integer"); + + b.Property("YoloModel") + .IsRequired() + .ValueGeneratedOnAdd() + .HasMaxLength(50) + .IsUnicode(false) + .HasColumnType("character varying(50)") + .HasDefaultValue("yolov8n"); + + b.HasKey("CameraId"); + + b.ToTable("camera_detection_profiles", (string)null); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.CameraDiscoveryResult", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("DetectedType") + .IsRequired() + .HasMaxLength(20) + .IsUnicode(false) + .HasColumnType("character varying(20)"); + + b.Property("DiscoveryMethod") + .IsRequired() + .HasMaxLength(20) + .IsUnicode(false) + .HasColumnType("character varying(20)"); + + b.Property("HomeKitDeviceId") + .HasMaxLength(50) + .IsUnicode(false) + .HasColumnType("character varying(50)"); + + b.Property("HomeKitModel") + .HasMaxLength(200) + .IsUnicode(false) + .HasColumnType("character varying(200)"); + + b.Property("HomeKitName") + .HasMaxLength(200) + .IsUnicode(false) + .HasColumnType("character varying(200)"); + + b.Property("Hostname") + .HasMaxLength(255) + .IsUnicode(false) + .HasColumnType("character varying(255)"); + + b.Property("HttpPort") + .HasColumnType("integer"); + + b.Property("HttpServerHeader") + .HasMaxLength(200) + .IsUnicode(false) + .HasColumnType("character varying(200)"); + + b.Property("HttpStatusCode") + .HasColumnType("integer"); + + b.Property("IpAddress") + .IsRequired() + .HasMaxLength(45) + .IsUnicode(false) + .HasColumnType("character varying(45)"); + + b.Property("IsHomeKitCamera") + .HasColumnType("boolean"); + + b.Property("IsProcessed") + .HasColumnType("boolean"); + + b.Property("IsReachable") + .HasColumnType("boolean"); + + b.Property("MacAddress") + .HasMaxLength(17) + .IsUnicode(false) + .HasColumnType("character varying(17)"); + + b.Property("OnvifDeviceServiceUrl") + .HasMaxLength(500) + .IsUnicode(false) + .HasColumnType("character varying(500)"); + + b.Property("OnvifHardware") + .HasMaxLength(200) + .IsUnicode(false) + .HasColumnType("character varying(200)"); + + b.Property("OnvifName") + .HasMaxLength(200) + .IsUnicode(false) + .HasColumnType("character varying(200)"); + + b.Property("OnvifPort") + .HasColumnType("integer"); + + b.PrimitiveCollection("OpenPorts") + .IsRequired() + .IsUnicode(false) + .HasColumnType("integer[]"); + + b.Property("ProbedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("NOW()"); + + b.Property("SiteId") + .HasColumnType("uuid"); + + b.Property("Vendor") + .HasMaxLength(100) + .IsUnicode(false) + .HasColumnType("character varying(100)"); + + b.HasKey("Id"); + + b.HasIndex("IpAddress"); + + b.HasIndex("IsProcessed"); + + b.HasIndex("SiteId"); + + b.ToTable("camera_discovery_results", (string)null); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.CameraEvent", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("AgentId") + .HasColumnType("uuid"); + + b.Property("CameraId") + .HasColumnType("uuid"); + + b.Property("Confidence") + .ValueGeneratedOnAdd() + .HasColumnType("double precision") + .HasDefaultValue(0.0); + + b.Property("CreatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("NOW()"); + + b.Property("DetectionHash") + .HasMaxLength(128) + .IsUnicode(false) + .HasColumnType("character varying(128)"); + + b.Property("IsSuppressed") + .ValueGeneratedOnAdd() + .HasColumnType("boolean") + .HasDefaultValue(false); + + b.Property("Label") + .HasMaxLength(200) + .IsUnicode(false) + .HasColumnType("character varying(200)"); + + b.Property("MetadataJson") + .HasColumnType("jsonb"); + + b.Property("OccurredAt") + .HasColumnType("timestamp with time zone"); + + b.Property("ParentEventId") + .HasColumnType("uuid"); + + b.Property("RecordingId") + .HasColumnType("uuid"); + + b.Property("SnapshotThumbUrl") + .HasMaxLength(2000) + .IsUnicode(false) + .HasColumnType("character varying(2000)"); + + b.Property("SnapshotUrl") + .HasMaxLength(2000) + .IsUnicode(false) + .HasColumnType("character varying(2000)"); + + b.Property("TrackId") + .HasMaxLength(100) + .IsUnicode(false) + .HasColumnType("character varying(100)"); + + b.Property("Type") + .HasColumnType("integer"); + + b.Property("UpdatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("NOW()"); + + b.Property("VehicleId") + .HasColumnType("uuid"); + + b.HasKey("Id"); + + b.HasIndex("DetectionHash"); + + b.HasIndex("OccurredAt"); + + b.HasIndex("ParentEventId"); + + b.HasIndex("RecordingId"); + + b.HasIndex("TrackId"); + + b.HasIndex("VehicleId"); + + b.HasIndex("CameraId", "OccurredAt") + .IsDescending(false, true); + + b.HasIndex("CameraId", "Type"); + + b.ToTable("camera_events", (string)null); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.DiscoveredStreamUrl", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.PrimitiveCollection("Codecs") + .IsRequired() + .IsUnicode(false) + .HasColumnType("text[]"); + + b.Property("DiscoveryResultId") + .HasColumnType("uuid"); + + b.Property("Height") + .HasColumnType("integer"); + + b.Property("IsAlive") + .HasColumnType("boolean"); + + b.Property("IsMainStream") + .HasColumnType("boolean"); + + b.Property("LatencyMs") + .HasColumnType("bigint"); + + b.Property("Protocol") + .IsRequired() + .HasMaxLength(20) + .IsUnicode(false) + .HasColumnType("character varying(20)"); + + b.Property("Url") + .IsRequired() + .HasMaxLength(2000) + .IsUnicode(false) + .HasColumnType("character varying(2000)"); + + b.Property("Width") + .HasColumnType("integer"); + + b.HasKey("Id"); + + b.HasIndex("DiscoveryResultId"); + + b.HasIndex("IsAlive"); + + b.HasIndex("IsMainStream"); + + b.ToTable("discovered_streams", (string)null); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.Group", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("CreatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("NOW()"); + + b.Property("DeletedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("Description") + .HasMaxLength(1000) + .HasColumnType("character varying(1000)"); + + b.Property("IsDeleted") + .HasColumnType("boolean"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("character varying(200)"); + + b.Property("UpdatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("NOW()"); + + b.HasKey("Id"); + + b.HasIndex("IsDeleted") + .HasFilter("\"IsDeleted\" = false"); + + b.HasIndex("Name"); + + b.ToTable("groups", (string)null); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.KnownFace", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("Embedding") + .IsRequired() + .HasColumnType("jsonb"); + + b.Property("PersonId") + .HasColumnType("uuid"); + + b.Property("SourceEventId") + .HasMaxLength(100) + .IsUnicode(false) + .HasColumnType("character varying(100)"); + + b.Property("ThumbnailUrl") + .HasMaxLength(2000) + .IsUnicode(false) + .HasColumnType("character varying(2000)"); + + b.HasKey("Id"); + + b.HasIndex("PersonId"); + + b.ToTable("known_faces", (string)null); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.LicensePlate", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("Confidence") + .ValueGeneratedOnAdd() + .HasColumnType("double precision") + .HasDefaultValue(0.0); + + b.Property("CreatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("NOW()"); + + b.Property("PersonId") + .HasColumnType("uuid"); + + b.Property("PlateText") + .IsRequired() + .HasMaxLength(20) + .IsUnicode(false) + .HasColumnType("character varying(20)"); + + b.Property("UpdatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("NOW()"); + + b.Property("VehicleId") + .HasColumnType("uuid"); + + b.HasKey("Id"); + + b.HasIndex("PersonId"); + + b.HasIndex("PlateText"); + + NpgsqlIndexBuilderExtensions.HasMethod(b.HasIndex("PlateText"), "gin"); + NpgsqlIndexBuilderExtensions.HasOperators(b.HasIndex("PlateText"), new[] { "gin_trgm_ops" }); + + b.HasIndex("VehicleId"); + + b.ToTable("license_plates", (string)null); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.Notification", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("CameraId") + .HasColumnType("uuid"); + + b.Property("CreatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("NOW()"); + + b.Property("EventType") + .HasMaxLength(50) + .HasColumnType("character varying(50)"); + + b.Property("IsRead") + .HasColumnType("boolean"); + + b.Property("Link") + .HasMaxLength(500) + .HasColumnType("character varying(500)"); + + b.Property("Message") + .IsRequired() + .HasMaxLength(2000) + .HasColumnType("character varying(2000)"); + + b.Property("ReadAt") + .HasColumnType("timestamp with time zone"); + + b.Property("SiteId") + .HasColumnType("uuid"); + + b.Property("SnapshotUrl") + .HasMaxLength(500) + .HasColumnType("character varying(500)"); + + b.Property("Title") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("character varying(200)"); + + b.Property("Type") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("character varying(50)"); + + b.Property("UpdatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("NOW()"); + + b.Property("UserId") + .HasColumnType("uuid"); + + b.HasKey("Id"); + + b.HasIndex("CreatedAt"); + + b.HasIndex("UserId"); + + b.HasIndex("UserId", "IsRead"); + + b.ToTable("notifications", (string)null); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.NotificationTemplate", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("BodyMarkdown") + .IsRequired() + .HasColumnType("text"); + + b.Property("Channel") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("character varying(50)"); + + b.Property("CreatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("NOW()"); + + b.Property("EventType") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("character varying(50)"); + + b.Property("IsDefault") + .HasColumnType("boolean"); + + b.Property("Language") + .IsRequired() + .ValueGeneratedOnAdd() + .HasMaxLength(10) + .HasColumnType("character varying(10)") + .HasDefaultValue("fr"); + + b.Property("Subject") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("character varying(200)"); + + b.Property("UpdatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("NOW()"); + + b.HasKey("Id"); + + b.HasIndex("EventType", "Channel", "Language") + .IsUnique(); + + b.ToTable("notification_templates", (string)null); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.Person", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("Category") + .HasMaxLength(50) + .IsUnicode(false) + .HasColumnType("character varying(50)"); + + b.Property("CreatedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("DisplayName") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("character varying(200)"); + + b.Property("IsWatchlisted") + .HasColumnType("boolean"); + + b.Property("Notes") + .HasMaxLength(2000) + .HasColumnType("character varying(2000)"); + + b.Property("PhotoUrl") + .HasMaxLength(2000) + .IsUnicode(false) + .HasColumnType("character varying(2000)"); + + b.Property("UpdatedAt") + .HasColumnType("timestamp with time zone"); + + b.HasKey("Id"); + + b.HasIndex("Category"); + + b.HasIndex("DisplayName"); + + b.HasIndex("IsWatchlisted"); + + b.ToTable("persons", (string)null); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.Recording", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("CameraId") + .HasColumnType("uuid"); + + b.Property("CreatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("NOW()"); + + b.Property("DurationSeconds") + .ValueGeneratedOnAdd() + .HasColumnType("double precision") + .HasDefaultValue(0.0); + + b.Property("SizeBytes") + .HasColumnType("bigint"); + + b.Property("StoragePath") + .IsRequired() + .HasMaxLength(2000) + .IsUnicode(false) + .HasColumnType("character varying(2000)"); + + b.Property("StoragePolicyId") + .HasColumnType("uuid"); + + b.Property("StorageProvider") + .IsRequired() + .HasMaxLength(20) + .IsUnicode(false) + .HasColumnType("character varying(20)"); + + b.Property("Timestamp") + .HasColumnType("timestamp with time zone"); + + b.Property("UpdatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("NOW()"); + + b.HasKey("Id"); + + b.HasIndex("StoragePath") + .IsUnique(); + + b.HasIndex("StoragePolicyId"); + + b.HasIndex("CameraId", "Timestamp"); + + b.ToTable("recordings", (string)null); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.RevokedRefreshToken", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("ExpiresAt") + .HasColumnType("timestamp with time zone"); + + b.Property("RevokedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("NOW()"); + + b.Property("TokenHash") + .IsRequired() + .HasMaxLength(128) + .IsUnicode(false) + .HasColumnType("character varying(128)"); + + b.Property("UserId") + .HasColumnType("uuid"); + + b.HasKey("Id"); + + b.HasIndex("ExpiresAt"); + + b.HasIndex("TokenHash") + .IsUnique(); + + b.ToTable("revoked_refresh_tokens", (string)null); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.Site", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("Address") + .HasMaxLength(500) + .HasColumnType("character varying(500)"); + + b.Property("CreatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("NOW()"); + + b.Property("DeletedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("Enabled") + .HasColumnType("boolean"); + + b.Property("IsDeleted") + .HasColumnType("boolean"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("character varying(200)"); + + b.Property("NtfyTopic") + .HasColumnType("text"); + + b.Property("RegistrationTokenHash") + .HasMaxLength(128) + .IsUnicode(false) + .HasColumnType("character varying(128)"); + + b.Property("Timezone") + .IsRequired() + .ValueGeneratedOnAdd() + .HasMaxLength(100) + .IsUnicode(false) + .HasColumnType("character varying(100)") + .HasDefaultValue("UTC"); + + b.Property("TokenExpiresAt") + .HasColumnType("timestamp with time zone"); + + b.Property("UpdatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("NOW()"); + + b.HasKey("Id"); + + b.HasIndex("IsDeleted") + .HasFilter("\"IsDeleted\" = false"); + + b.HasIndex("Name"); + + b.ToTable("sites", (string)null); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.SiteCredential", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("CreatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("NOW()"); + + b.Property("Label") + .IsRequired() + .HasMaxLength(100) + .IsUnicode(false) + .HasColumnType("character varying(100)"); + + b.Property("LastUsedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("Password") + .IsRequired() + .HasMaxLength(2000) + .IsUnicode(false) + .HasColumnType("character varying(2000)"); + + b.Property("SiteId") + .HasColumnType("uuid"); + + b.Property("Username") + .IsRequired() + .HasMaxLength(200) + .IsUnicode(false) + .HasColumnType("character varying(200)"); + + b.HasKey("Id"); + + b.HasIndex("SiteId"); + + b.ToTable("site_credentials", (string)null); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.StoragePolicy", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("CreatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("NOW()"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(100) + .IsUnicode(false) + .HasColumnType("character varying(100)"); + + b.Property("RetentionDays") + .HasColumnType("integer"); + + b.Property("StorageProvider") + .IsRequired() + .HasMaxLength(20) + .IsUnicode(false) + .HasColumnType("character varying(20)"); + + b.Property("UpdatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("NOW()"); + + b.HasKey("Id"); + + b.ToTable("storage_policies", (string)null); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.UserGroup", b => + { + b.Property("UserId") + .HasColumnType("uuid"); + + b.Property("GroupId") + .HasColumnType("uuid"); + + b.HasKey("UserId", "GroupId"); + + b.HasIndex("GroupId"); + + b.ToTable("user_groups", (string)null); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.UserNotificationConfig", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("CreatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("NOW()"); + + b.Property("DailyDigest") + .HasColumnType("boolean"); + + b.Property("EmailAddress") + .HasMaxLength(200) + .HasColumnType("character varying(200)"); + + b.Property("EmailEnabled") + .HasColumnType("boolean"); + + b.Property("Language") + .IsRequired() + .ValueGeneratedOnAdd() + .HasMaxLength(10) + .HasColumnType("character varying(10)") + .HasDefaultValue("fr"); + + b.Property("NtfyEnabled") + .HasColumnType("boolean"); + + b.Property("NtfyUrl") + .HasMaxLength(500) + .HasColumnType("character varying(500)"); + + b.Property("SubscribedEventsJson") + .HasColumnType("jsonb") + .HasColumnName("subscribed_events"); + + b.Property("UpdatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("NOW()"); + + b.Property("UserId") + .HasColumnType("uuid"); + + b.Property("WeeklyDigest") + .HasColumnType("boolean"); + + b.HasKey("Id"); + + b.HasIndex("UserId") + .IsUnique(); + + b.ToTable("user_notification_configs", (string)null); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.UserRecoveryCode", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("CodeHash") + .IsRequired() + .HasMaxLength(64) + .IsUnicode(false) + .HasColumnType("character varying(64)"); + + b.Property("CreatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("NOW()"); + + b.Property("UsedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("UserId") + .HasColumnType("uuid"); + + b.HasKey("Id"); + + b.HasIndex("UserId"); + + b.HasIndex("UserId", "CodeHash") + .IsUnique(); + + b.ToTable("user_recovery_codes", (string)null); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.UserSite", b => + { + b.Property("UserId") + .HasColumnType("uuid"); + + b.Property("SiteId") + .HasColumnType("uuid"); + + b.HasKey("UserId", "SiteId"); + + b.HasIndex("SiteId"); + + b.ToTable("user_sites", (string)null); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.Vehicle", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("Color") + .HasMaxLength(50) + .IsUnicode(false) + .HasColumnType("character varying(50)"); + + b.Property("CreatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("NOW()"); + + b.Property("LicensePlate") + .HasMaxLength(20) + .IsUnicode(false) + .HasColumnType("character varying(20)"); + + b.Property("Make") + .HasMaxLength(100) + .IsUnicode(false) + .HasColumnType("character varying(100)"); + + b.Property("Model") + .HasMaxLength(100) + .IsUnicode(false) + .HasColumnType("character varying(100)"); + + b.Property("PersonId") + .HasColumnType("uuid"); + + b.Property("UpdatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("NOW()"); + + b.HasKey("Id"); + + b.HasIndex("LicensePlate"); + + b.HasIndex("PersonId"); + + b.ToTable("vehicles", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("ClaimType") + .HasColumnType("text"); + + b.Property("ClaimValue") + .HasColumnType("text"); + + b.Property("RoleId") + .HasColumnType("uuid"); + + b.HasKey("Id"); + + b.HasIndex("RoleId"); + + b.ToTable("role_claims", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("ClaimType") + .HasColumnType("text"); + + b.Property("ClaimValue") + .HasColumnType("text"); + + b.Property("UserId") + .HasColumnType("uuid"); + + b.HasKey("Id"); + + b.HasIndex("UserId"); + + b.ToTable("user_claims", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin", b => + { + b.Property("LoginProvider") + .HasColumnType("text"); + + b.Property("ProviderKey") + .HasColumnType("text"); + + b.Property("ProviderDisplayName") + .HasColumnType("text"); + + b.Property("UserId") + .HasColumnType("uuid"); + + b.HasKey("LoginProvider", "ProviderKey"); + + b.HasIndex("UserId"); + + b.ToTable("user_logins", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole", b => + { + b.Property("UserId") + .HasColumnType("uuid"); + + b.Property("RoleId") + .HasColumnType("uuid"); + + b.HasKey("UserId", "RoleId"); + + b.HasIndex("RoleId"); + + b.ToTable("user_roles", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken", b => + { + b.Property("UserId") + .HasColumnType("uuid"); + + b.Property("LoginProvider") + .HasColumnType("text"); + + b.Property("Name") + .HasColumnType("text"); + + b.Property("Value") + .HasColumnType("text"); + + b.HasKey("UserId", "LoginProvider", "Name"); + + b.ToTable("user_tokens", (string)null); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.Agent", b => + { + b.HasOne("Heimdall.Domain.Entities.Site", "Site") + .WithMany("Agents") + .HasForeignKey("SiteId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.Navigation("Site"); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.AgentLogEntry", b => + { + b.HasOne("Heimdall.Domain.Entities.Agent", "Agent") + .WithMany() + .HasForeignKey("AgentId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Agent"); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.AgentSetting", b => + { + b.HasOne("Heimdall.Domain.Entities.Agent", "Agent") + .WithMany() + .HasForeignKey("AgentId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Agent"); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.ApiKey", b => + { + b.HasOne("Heimdall.Domain.Entities.Site", "Site") + .WithMany() + .HasForeignKey("SiteId") + .OnDelete(DeleteBehavior.Restrict); + + b.Navigation("Site"); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.AuditLog", b => + { + b.HasOne("Heimdall.Domain.Entities.AppUser", "User") + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.SetNull); + + b.Navigation("User"); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.Camera", b => + { + b.HasOne("Heimdall.Domain.Entities.Agent", "Agent") + .WithMany("Cameras") + .HasForeignKey("AgentId") + .OnDelete(DeleteBehavior.SetNull); + + b.HasOne("Heimdall.Domain.Entities.Site", "Site") + .WithMany("Cameras") + .HasForeignKey("SiteId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("Heimdall.Domain.Entities.StoragePolicy", "StoragePolicy") + .WithMany() + .HasForeignKey("StoragePolicyId") + .OnDelete(DeleteBehavior.SetNull); + + b.Navigation("Agent"); + + b.Navigation("Site"); + + b.Navigation("StoragePolicy"); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.CameraAssignment", b => + { + b.HasOne("Heimdall.Domain.Entities.Agent", "Agent") + .WithMany() + .HasForeignKey("AgentId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("Heimdall.Domain.Entities.Camera", "Camera") + .WithMany() + .HasForeignKey("CameraId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.Navigation("Agent"); + + b.Navigation("Camera"); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.CameraCredentials", b => + { + b.HasOne("Heimdall.Domain.Entities.Camera", "Camera") + .WithOne("Credentials") + .HasForeignKey("Heimdall.Domain.Entities.CameraCredentials", "CameraId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Camera"); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.CameraDetectionProfile", b => + { + b.HasOne("Heimdall.Domain.Entities.Camera", "Camera") + .WithOne("DetectionProfile") + .HasForeignKey("Heimdall.Domain.Entities.CameraDetectionProfile", "CameraId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Camera"); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.CameraDiscoveryResult", b => + { + b.HasOne("Heimdall.Domain.Entities.Site", "Site") + .WithMany() + .HasForeignKey("SiteId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Site"); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.CameraEvent", b => + { + b.HasOne("Heimdall.Domain.Entities.Camera", "Camera") + .WithMany() + .HasForeignKey("CameraId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Heimdall.Domain.Entities.CameraEvent", "ParentEvent") + .WithMany() + .HasForeignKey("ParentEventId") + .OnDelete(DeleteBehavior.SetNull); + + b.HasOne("Heimdall.Domain.Entities.Recording", "Recording") + .WithMany() + .HasForeignKey("RecordingId") + .OnDelete(DeleteBehavior.SetNull); + + b.HasOne("Heimdall.Domain.Entities.Vehicle", "Vehicle") + .WithMany() + .HasForeignKey("VehicleId") + .OnDelete(DeleteBehavior.SetNull); + + b.Navigation("Camera"); + + b.Navigation("ParentEvent"); + + b.Navigation("Recording"); + + b.Navigation("Vehicle"); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.DiscoveredStreamUrl", b => + { + b.HasOne("Heimdall.Domain.Entities.CameraDiscoveryResult", "DiscoveryResult") + .WithMany("DiscoveredStreams") + .HasForeignKey("DiscoveryResultId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("DiscoveryResult"); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.KnownFace", b => + { + b.HasOne("Heimdall.Domain.Entities.Person", "Person") + .WithMany("Faces") + .HasForeignKey("PersonId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Person"); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.LicensePlate", b => + { + b.HasOne("Heimdall.Domain.Entities.Person", "Person") + .WithMany() + .HasForeignKey("PersonId") + .OnDelete(DeleteBehavior.SetNull); + + b.HasOne("Heimdall.Domain.Entities.Vehicle", "Vehicle") + .WithMany() + .HasForeignKey("VehicleId") + .OnDelete(DeleteBehavior.SetNull); + + b.Navigation("Person"); + + b.Navigation("Vehicle"); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.Recording", b => + { + b.HasOne("Heimdall.Domain.Entities.Camera", "Camera") + .WithMany() + .HasForeignKey("CameraId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Heimdall.Domain.Entities.StoragePolicy", "StoragePolicy") + .WithMany() + .HasForeignKey("StoragePolicyId") + .OnDelete(DeleteBehavior.SetNull); + + b.Navigation("Camera"); + + b.Navigation("StoragePolicy"); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.SiteCredential", b => + { + b.HasOne("Heimdall.Domain.Entities.Site", "Site") + .WithMany("Credentials") + .HasForeignKey("SiteId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Site"); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.UserGroup", b => + { + b.HasOne("Heimdall.Domain.Entities.Group", "Group") + .WithMany("UserGroups") + .HasForeignKey("GroupId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Heimdall.Domain.Entities.AppUser", "User") + .WithMany("UserGroups") + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Group"); + + b.Navigation("User"); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.UserSite", b => + { + b.HasOne("Heimdall.Domain.Entities.Site", "Site") + .WithMany() + .HasForeignKey("SiteId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("Heimdall.Domain.Entities.AppUser", "User") + .WithMany("UserSites") + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Site"); + + b.Navigation("User"); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.Vehicle", b => + { + b.HasOne("Heimdall.Domain.Entities.Person", "Person") + .WithMany() + .HasForeignKey("PersonId") + .OnDelete(DeleteBehavior.SetNull); + + b.Navigation("Person"); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim", b => + { + b.HasOne("Heimdall.Domain.Entities.AppRole", null) + .WithMany() + .HasForeignKey("RoleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim", b => + { + b.HasOne("Heimdall.Domain.Entities.AppUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin", b => + { + b.HasOne("Heimdall.Domain.Entities.AppUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole", b => + { + b.HasOne("Heimdall.Domain.Entities.AppRole", null) + .WithMany() + .HasForeignKey("RoleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Heimdall.Domain.Entities.AppUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken", b => + { + b.HasOne("Heimdall.Domain.Entities.AppUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.Agent", b => + { + b.Navigation("Cameras"); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.AppUser", b => + { + b.Navigation("UserGroups"); + + b.Navigation("UserSites"); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.Camera", b => + { + b.Navigation("Credentials"); + + b.Navigation("DetectionProfile"); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.CameraDiscoveryResult", b => + { + b.Navigation("DiscoveredStreams"); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.Group", b => + { + b.Navigation("UserGroups"); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.Person", b => + { + b.Navigation("Faces"); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.Site", b => + { + b.Navigation("Agents"); + + b.Navigation("Cameras"); + + b.Navigation("Credentials"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/src/Heimdall.Infrastructure/Migrations/20260818065253_AddAgentTelemetryInventory.cs b/src/Heimdall.Infrastructure/Migrations/20260818065253_AddAgentTelemetryInventory.cs new file mode 100644 index 0000000..aacdada --- /dev/null +++ b/src/Heimdall.Infrastructure/Migrations/20260818065253_AddAgentTelemetryInventory.cs @@ -0,0 +1,268 @@ +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace Heimdall.Infrastructure.Migrations +{ + /// + public partial class AddAgentTelemetryInventory : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.AddColumn( + name: "Arch", + table: "agents", + type: "text", + nullable: true); + + migrationBuilder.AddColumn( + name: "ContainerCpuLimit", + table: "agents", + type: "bigint", + nullable: true); + + migrationBuilder.AddColumn( + name: "ContainerId", + table: "agents", + type: "text", + nullable: true); + + migrationBuilder.AddColumn( + name: "ContainerImage", + table: "agents", + type: "text", + nullable: true); + + migrationBuilder.AddColumn( + name: "ContainerMemoryLimitBytes", + table: "agents", + type: "bigint", + nullable: true); + + migrationBuilder.AddColumn( + name: "CpuArchitecture", + table: "agents", + type: "text", + nullable: true); + + migrationBuilder.AddColumn( + name: "CpuCacheBytes", + table: "agents", + type: "bigint", + nullable: true); + + migrationBuilder.AddColumn( + name: "CpuFlags", + table: "agents", + type: "text", + nullable: true); + + migrationBuilder.AddColumn( + name: "CpuFrequencyMhz", + table: "agents", + type: "double precision", + nullable: true); + + migrationBuilder.AddColumn( + name: "CpuModel", + table: "agents", + type: "text", + nullable: true); + + migrationBuilder.AddColumn( + name: "CpuVendor", + table: "agents", + type: "text", + nullable: true); + + migrationBuilder.AddColumn( + name: "DiskInventoryJson", + table: "agents", + type: "text", + nullable: true); + + migrationBuilder.AddColumn( + name: "GpuInventoryJson", + table: "agents", + type: "text", + nullable: true); + + migrationBuilder.AddColumn( + name: "KernelVersion", + table: "agents", + type: "text", + nullable: true); + + migrationBuilder.AddColumn( + name: "LogicalCores", + table: "agents", + type: "integer", + nullable: true); + + migrationBuilder.AddColumn( + name: "MemAvailableBytes", + table: "agents", + type: "bigint", + nullable: true); + + migrationBuilder.AddColumn( + name: "MemTotalBytes", + table: "agents", + type: "bigint", + nullable: true); + + migrationBuilder.AddColumn( + name: "NetworkInterfacesJson", + table: "agents", + type: "text", + nullable: true); + + migrationBuilder.AddColumn( + name: "OsName", + table: "agents", + type: "text", + nullable: true); + + migrationBuilder.AddColumn( + name: "PhysicalCores", + table: "agents", + type: "integer", + nullable: true); + + migrationBuilder.AddColumn( + name: "SwapFreeBytes", + table: "agents", + type: "bigint", + nullable: true); + + migrationBuilder.AddColumn( + name: "SwapTotalBytes", + table: "agents", + type: "bigint", + nullable: true); + + migrationBuilder.AddColumn( + name: "TemperatureJson", + table: "agents", + type: "text", + nullable: true); + + migrationBuilder.AddColumn( + name: "ThreadsPerCore", + table: "agents", + type: "integer", + nullable: true); + + migrationBuilder.AddColumn( + name: "UptimeMachineSeconds", + table: "agents", + type: "bigint", + nullable: true); + } + + /// + 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"); + } + } +} diff --git a/src/Heimdall.Infrastructure/Migrations/AppDbContextModelSnapshot.cs b/src/Heimdall.Infrastructure/Migrations/AppDbContextModelSnapshot.cs index 24d0a4a..be0eb60 100644 --- a/src/Heimdall.Infrastructure/Migrations/AppDbContextModelSnapshot.cs +++ b/src/Heimdall.Infrastructure/Migrations/AppDbContextModelSnapshot.cs @@ -38,12 +38,45 @@ namespace Heimdall.Infrastructure.Migrations .IsUnicode(false) .HasColumnType("character varying(8)"); + b.Property("Arch") + .HasColumnType("text"); + + b.Property("ContainerCpuLimit") + .HasColumnType("bigint"); + + b.Property("ContainerId") + .HasColumnType("text"); + + b.Property("ContainerImage") + .HasColumnType("text"); + + b.Property("ContainerMemoryLimitBytes") + .HasColumnType("bigint"); + + b.Property("CpuArchitecture") + .HasColumnType("text"); + + b.Property("CpuCacheBytes") + .HasColumnType("bigint"); + b.Property("CpuCores") .HasColumnType("integer"); + b.Property("CpuFlags") + .HasColumnType("text"); + + b.Property("CpuFrequencyMhz") + .HasColumnType("double precision"); + + b.Property("CpuModel") + .HasColumnType("text"); + b.Property("CpuUsagePercent") .HasColumnType("double precision"); + b.Property("CpuVendor") + .HasColumnType("text"); + b.Property("CreatedAt") .ValueGeneratedOnAdd() .HasColumnType("timestamp with time zone") @@ -52,9 +85,15 @@ namespace Heimdall.Infrastructure.Migrations b.Property("DeletedAt") .HasColumnType("timestamp with time zone"); + b.Property("DiskInventoryJson") + .HasColumnType("text"); + b.Property("DiskUsagePercent") .HasColumnType("double precision"); + b.Property("GpuInventoryJson") + .HasColumnType("text"); + b.Property("GpuType") .IsRequired() .HasMaxLength(20) @@ -73,9 +112,21 @@ namespace Heimdall.Infrastructure.Migrations b.Property("IsDeleted") .HasColumnType("boolean"); + b.Property("KernelVersion") + .HasColumnType("text"); + b.Property("LastHeartbeat") .HasColumnType("timestamp with time zone"); + b.Property("LogicalCores") + .HasColumnType("integer"); + + b.Property("MemAvailableBytes") + .HasColumnType("bigint"); + + b.Property("MemTotalBytes") + .HasColumnType("bigint"); + b.Property("MemoryMb") .HasColumnType("bigint"); @@ -88,6 +139,15 @@ namespace Heimdall.Infrastructure.Migrations .IsUnicode(false) .HasColumnType("character varying(200)"); + b.Property("NetworkInterfacesJson") + .HasColumnType("text"); + + b.Property("OsName") + .HasColumnType("text"); + + b.Property("PhysicalCores") + .HasColumnType("integer"); + b.Property("PublicIp") .HasMaxLength(45) .IsUnicode(false) @@ -102,11 +162,26 @@ namespace Heimdall.Infrastructure.Migrations .IsUnicode(false) .HasColumnType("character varying(20)"); + b.Property("SwapFreeBytes") + .HasColumnType("bigint"); + + b.Property("SwapTotalBytes") + .HasColumnType("bigint"); + + b.Property("TemperatureJson") + .HasColumnType("text"); + + b.Property("ThreadsPerCore") + .HasColumnType("integer"); + b.Property("UpdatedAt") .ValueGeneratedOnAdd() .HasColumnType("timestamp with time zone") .HasDefaultValueSql("NOW()"); + b.Property("UptimeMachineSeconds") + .HasColumnType("bigint"); + b.Property("UptimeSeconds") .HasColumnType("bigint"); diff --git a/src/Heimdall.Infrastructure/Services/Discovery/CameraDiscoveryService.cs b/src/Heimdall.Infrastructure/Services/Discovery/CameraDiscoveryService.cs index 6060451..a22a8ca 100644 --- a/src/Heimdall.Infrastructure/Services/Discovery/CameraDiscoveryService.cs +++ b/src/Heimdall.Infrastructure/Services/Discovery/CameraDiscoveryService.cs @@ -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)); } + + /// Process a single discovered device from an agent submission. + /// 0 = skipped, 1 = new, 2 = updated. + private async Task 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; diff --git a/src/Heimdall.Infrastructure/Services/Discovery/StreamTesterService.cs b/src/Heimdall.Infrastructure/Services/Discovery/StreamTesterService.cs index b93e5e8..af8c8ba 100644 --- a/src/Heimdall.Infrastructure/Services/Discovery/StreamTesterService.cs +++ b/src/Heimdall.Infrastructure/Services/Discovery/StreamTesterService.cs @@ -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(); diff --git a/src/Heimdall.Web/Components/Pages/AgentDetail.razor b/src/Heimdall.Web/Components/Pages/AgentDetail.razor index 342ae82..99967d3 100644 --- a/src/Heimdall.Web/Components/Pages/AgentDetail.razor +++ b/src/Heimdall.Web/Components/Pages/AgentDetail.razor @@ -4,7 +4,7 @@ @inject HeimdallApiClient Api @inject ISnackbar Snackbar @inject NavigationManager Nav -@implements IDisposable +@implements IAsyncDisposable @@ -99,6 +99,363 @@ else + @* ─── Hardware Inventory ─── *@ + + @* ─── CPU Inventory ─── *@ + + + + @if (_agent.CpuModel is not null) + { + + Modèle + @_agent.CpuModel + + } + @if (_agent.CpuVendor is not null) + { + + Fabricant + @_agent.CpuVendor + + } + @if (_agent.CpuArchitecture is not null) + { + + Architecture + @_agent.CpuArchitecture + + } + @if (_agent.PhysicalCores.HasValue) + { + + Cœurs physiques + @_agent.PhysicalCores + + } + @if (_agent.LogicalCores.HasValue) + { + + Cœurs logiques + @_agent.LogicalCores + + } + @if (_agent.ThreadsPerCore.HasValue) + { + + Threads/noyau + @_agent.ThreadsPerCore + + } + @if (_agent.CpuFrequencyMhz.HasValue) + { + + Fréquence + @($"{_agent.CpuFrequencyMhz:F0} MHz") + + } + @if (_agent.CpuCacheBytes.HasValue && _agent.CpuCacheBytes > 0) + { + + Cache + @FormatBytes(_agent.CpuCacheBytes.Value) + + } + @if (!string.IsNullOrEmpty(_agent.CpuFlags)) + { + + Instructions clés +
+ @foreach (var flag in _agent.CpuFlags.Split(',', StringSplitOptions.RemoveEmptyEntries)) + { + @flag + } +
+
+ } +
+
+
+ + @* ─── Memory & Disk Inventory ─── *@ + + + + @if (_agent.MemTotalBytes.HasValue) + { + + Mémoire totale + @FormatBytes(_agent.MemTotalBytes.Value) + + } + @if (_agent.MemAvailableBytes.HasValue) + { + + Mémoire dispo + @FormatBytes(_agent.MemAvailableBytes.Value) + + } + @if (_agent.SwapTotalBytes.HasValue && _agent.SwapTotalBytes > 0) + { + + Swap total + @FormatBytes(_agent.SwapTotalBytes.Value) + + } + @if (_agent.SwapFreeBytes.HasValue && _agent.SwapTotalBytes is > 0) + { + + Swap dispo + @FormatBytes(_agent.SwapFreeBytes.Value) + + } + @if (_agent.ContainerMemoryLimitBytes.HasValue) + { + + + Limite conteneur : @FormatBytes(_agent.ContainerMemoryLimitBytes.Value) + + + } + @if (!string.IsNullOrEmpty(_agent.DiskInventoryJson)) + { + + Disques + @{ + var disks = ParseDiskJson(_agent.DiskInventoryJson); + } + @if (disks.Count > 0) + { + + + Point de montage + FS + Taille + Utilisé + Type + + + + @context.MountPoint + + + @context.FileSystem + + + @(context.TotalBytes.HasValue ? FormatBytes(context.TotalBytes.Value) : "-") + + + @(context.UsedBytes.HasValue ? FormatBytes(context.UsedBytes.Value) : "-") + + + + @context.Type + + + + + } + else + { + Aucun disque détecté + } + + } + + + +
+ + + @* ─── GPU Inventory ─── *@ + + + @{ + var gpus = ParseGpuJson(_agent.GpuInventoryJson); + } + @if (gpus.Count > 0) + { + + + Modèle + Backend + VRAM + Temp + Utilisation + Driver + Encoder + + + + @(context.Model ?? "-") + + + @(context.Backend ?? "-") + + + @(context.VramBytes.HasValue ? FormatBytes(context.VramBytes.Value) : "-") + + + @(context.TemperatureCelsius.HasValue ? $"{context.TemperatureCelsius:F0}°C" : "-") + + + @(context.UtilizationPercent.HasValue ? $"{context.UtilizationPercent:F0}%" : "-") + + + @(context.DriverVersion ?? "-") + + + @(context.EncoderSupport ?? "-") + + + + } + else + { + Aucun GPU détecté + } + + + + @* ─── Host & Container ─── *@ + + + + @if (_agent.OsName is not null) + { + + OS + @_agent.OsName + + } + @if (_agent.KernelVersion is not null) + { + + Noyau + @_agent.KernelVersion + + } + @if (_agent.Arch is not null) + { + + Architecture + @_agent.Arch + + } + @if (_agent.UptimeMachineSeconds.HasValue) + { + + Uptime machine + @FormatUptime(_agent.UptimeMachineSeconds.Value) + + } + @if (_agent.ContainerId is not null) + { + + + Conteneur + + + @(_agent.ContainerImage ?? "Conteneur Docker") + + ID: @_agent.ContainerId + + } + @if (_agent.ContainerCpuLimit.HasValue) + { + + + CPU limite: @($"{_agent.ContainerCpuLimit.Value / 100.0:F1} cores") + + + } + + + + + + + @* ─── Network Interfaces ─── *@ + + + @{ + var interfaces = ParseNetworkJson(_agent.NetworkInterfacesJson); + } + @if (interfaces.Count > 0) + { + + + Interface + Adresse IP + MAC + Débit + + + + @context.Name + + + @(context.IpAddress ?? "-") + + + @(context.MacAddress ?? "-") + + + @(context.SpeedMbps.HasValue ? $"{context.SpeedMbps} Mbps" : "-") + + + + } + else + { + Aucune interface réseau détectée + } + + + + @* ─── Temperature ─── *@ + + + @{ + var temps = ParseTemperatureJson(_agent.TemperatureJson); + } + @if (temps.Count > 0) + { + + + Zone + Température + + + + @context.Zone + + + @{ + Color tempColor; + if (context.TemperatureCelsius > 70) + tempColor = Color.Error; + else if (context.TemperatureCelsius > 50) + tempColor = Color.Warning; + else + tempColor = Color.Default; + } + + @($"{context.TemperatureCelsius:F1}°C") + + + + + } + else + { + Aucune sonde de température détectée + } + + + + @* ─── Agent Settings (globals hérités + overrides) ─── *@ 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 ParseDiskJson(string? json) + { + if (string.IsNullOrWhiteSpace(json)) return []; + try + { + return System.Text.Json.JsonSerializer.Deserialize>(json) ?? []; + } + catch { return []; } + } + + private static List ParseGpuJson(string? json) + { + if (string.IsNullOrWhiteSpace(json)) return []; + try + { + return System.Text.Json.JsonSerializer.Deserialize>(json) ?? []; + } + catch { return []; } + } + + private static List ParseNetworkJson(string? json) + { + if (string.IsNullOrWhiteSpace(json)) return []; + try + { + return System.Text.Json.JsonSerializer.Deserialize>(json) ?? []; + } + catch { return []; } + } + + private static List ParseTemperatureJson(string? json) + { + if (string.IsNullOrWhiteSpace(json)) return []; + try + { + return System.Text.Json.JsonSerializer.Deserialize>(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; } + } } diff --git a/src/Heimdall.Web/Components/Settings/StorageSettingsSection.razor b/src/Heimdall.Web/Components/Settings/StorageSettingsSection.razor index 04717ff..b020774 100644 --- a/src/Heimdall.Web/Components/Settings/StorageSettingsSection.razor +++ b/src/Heimdall.Web/Components/Settings/StorageSettingsSection.razor @@ -71,7 +71,7 @@ { - @(_testResult.Healthy == true ? "Opérationnel" : _testResult.Configured == false ? "Non configuré" : "Injoignable") + @GetStorageTestStatus() } @@ -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 diff --git a/src/Heimdall.Web/Components/_Imports.razor b/src/Heimdall.Web/Components/_Imports.razor index 521047f..495be6a 100644 --- a/src/Heimdall.Web/Components/_Imports.razor +++ b/src/Heimdall.Web/Components/_Imports.razor @@ -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 diff --git a/src/Heimdall.Web/Controllers/AgentsController.cs b/src/Heimdall.Web/Controllers/AgentsController.cs index 922bb9d..6be9a67 100644 --- a/src/Heimdall.Web/Controllers/AgentsController.cs +++ b/src/Heimdall.Web/Controllers/AgentsController.cs @@ -23,6 +23,15 @@ namespace Heimdall.Api.Controllers; [EnableRateLimiting("Api")] public class AgentsController : ControllerBase { + /// Query parameters for agent log retrieval. + 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 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 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); diff --git a/src/Heimdall.Web/Program.cs b/src/Heimdall.Web/Program.cs index ac34e11..d9f7579 100644 --- a/src/Heimdall.Web/Program.cs +++ b/src/Heimdall.Web/Program.cs @@ -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("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>(); var userManager = seedScope.ServiceProvider .GetRequiredService>(); + var groupDb = seedScope.ServiceProvider.GetRequiredService(); + 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 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(); + 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 + private static async Task> GetExistingSettingKeysAsync(AppDbContext groupDb) => + new( + await groupDb.AppSettings.Select(s => s.Key).ToListAsync(), + StringComparer.OrdinalIgnoreCase); + + private static async Task SeedStorageSettingsAsync(AppDbContext groupDb, HashSet existingKeys) + { + var defaults = new Dictionary { ["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( - 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 + private static async Task SeedIntegrationSettingsAsync(AppDbContext groupDb, HashSet existingKeys) + { + var defaults = new Dictionary { ["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("Seed:DemoOnStartup", false)) + private static async Task SeedDemoDataAsync( + IConfiguration configuration, + Microsoft.AspNetCore.Identity.UserManager userManager, + AppDbContext groupDb) + { + if (!configuration.GetValue("Seed:DemoOnStartup", false)) + return; + + var adminLogin = configuration.GetValue("Seed:AdminLogin") + ?? Environment.GetEnvironmentVariable("SEED__ADMIN_LOGIN") + ?? "admin@heimdall.test"; + var testAdmin = await userManager.FindByEmailAsync(adminLogin); + if (testAdmin is null) { - var adminLogin = configuration.GetValue("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("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("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(); + } + + 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()) + .AddJsonOptions(options => + { + options.JsonSerializerOptions.Converters.Add( + new System.Text.Json.Serialization.JsonStringEnumConverter()); + }) + .AddApplicationPart(typeof(Program).Assembly); + builder.Services.AddFluentValidationAutoValidation(); + builder.Services.Configure(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(); + builder.Services.AddScoped(); + builder.Services.AddScoped(); + builder.Services.AddScoped(); + builder.Services.AddScoped(); + } + + private static void ConfigureAuthScheme(WebApplicationBuilder builder) + { + builder.Services.Configure(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(); + builder.Services.AddScoped(); + builder.Services.AddTransient(); + builder.Services.AddTransient(); + + 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() + .AddHttpMessageHandler(); + + 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(); builder.Services.AddScoped( sp => sp.GetRequiredService()); + } - // ── 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()) - .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(opts => - opts.SerializerOptions.Converters.Add(new System.Text.Json.Serialization.JsonStringEnumConverter())); - builder.Services.AddSignalR(); - builder.Services.AddScoped(); - builder.Services.AddScoped(); - builder.Services.AddScoped(); - builder.Services.AddScoped(); - builder.Services.AddScoped(); - 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)?.Remove("password"); - if (sentryEvent.Extra?.ContainsKey("token") == true) - (sentryEvent.Extra as IDictionary)?.Remove("token"); - if (sentryEvent.Extra?.ContainsKey("secret") == true) - (sentryEvent.Extra as IDictionary)?.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(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)?.Remove("password"); + if (sentryEvent.Extra?.ContainsKey("token") == true) + (sentryEvent.Extra as IDictionary)?.Remove("token"); + if (sentryEvent.Extra?.ContainsKey("secret") == true) + (sentryEvent.Extra as IDictionary)?.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(); - builder.Services.AddScoped(); - builder.Services.AddTransient(); - builder.Services.AddTransient(); - 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() - .AddHttpMessageHandler(); - if (apiBaseUrlConfigured) - Console.WriteLine($"[DIAG] ApiBaseUrl: {apiBaseUrl} (explicit)"); - else - Console.WriteLine("[DIAG] ApiBaseUrl: same-origin (no explicit config)"); - - builder.Services.AddScoped(); + 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("/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(); var endpoints = dataSource.Endpoints diff --git a/src/Heimdall.Web/Services/HeimdallApiClient.cs b/src/Heimdall.Web/Services/HeimdallApiClient.cs index 273ada1..c714545 100644 --- a/src/Heimdall.Web/Services/HeimdallApiClient.cs +++ b/src/Heimdall.Web/Services/HeimdallApiClient.cs @@ -82,33 +82,24 @@ public class HeimdallApiClient if (errors.Value.ValueKind != JsonValueKind.Object) return Array.Empty(); - var messages = new List(); - 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 diff --git a/tests/Heimdall.Agent.Tests/AgentRegistrationServiceTests.cs b/tests/Heimdall.Agent.Tests/AgentRegistrationServiceTests.cs index eb62cfa..136f6f2 100644 --- a/tests/Heimdall.Agent.Tests/AgentRegistrationServiceTests.cs +++ b/tests/Heimdall.Agent.Tests/AgentRegistrationServiceTests.cs @@ -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.Instance); } diff --git a/tests/Heimdall.Agent.Tests/CameraStreamServiceTests.cs b/tests/Heimdall.Agent.Tests/CameraStreamServiceTests.cs index f9ab642..ed256df 100644 --- a/tests/Heimdall.Agent.Tests/CameraStreamServiceTests.cs +++ b/tests/Heimdall.Agent.Tests/CameraStreamServiceTests.cs @@ -161,6 +161,7 @@ public class CameraStreamServiceTests { using var service = CreateService(); await service.StopAllAsync(); + service.ShouldNotBeNull(); } [Fact] diff --git a/tests/Heimdall.Agent.Tests/Providers/CollectorProviderTests.cs b/tests/Heimdall.Agent.Tests/Providers/CollectorProviderTests.cs new file mode 100644 index 0000000..8b758bb --- /dev/null +++ b/tests/Heimdall.Agent.Tests/Providers/CollectorProviderTests.cs @@ -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); + } +} diff --git a/tests/Heimdall.Agent.Tests/Services/CgroupReaderTests.cs b/tests/Heimdall.Agent.Tests/Services/CgroupReaderTests.cs new file mode 100644 index 0000000..608c1ec --- /dev/null +++ b/tests/Heimdall.Agent.Tests/Services/CgroupReaderTests.cs @@ -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); + } +} diff --git a/tests/Heimdall.Agent.Tests/Services/ContainerInfoProviderDetailedTests.cs b/tests/Heimdall.Agent.Tests/Services/ContainerInfoProviderDetailedTests.cs new file mode 100644 index 0000000..05155bd --- /dev/null +++ b/tests/Heimdall.Agent.Tests/Services/ContainerInfoProviderDetailedTests.cs @@ -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); + } +} diff --git a/tests/Heimdall.Agent.Tests/Services/CpuInfoProviderDetailedTests.cs b/tests/Heimdall.Agent.Tests/Services/CpuInfoProviderDetailedTests.cs new file mode 100644 index 0000000..f365fef --- /dev/null +++ b/tests/Heimdall.Agent.Tests/Services/CpuInfoProviderDetailedTests.cs @@ -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); + } +} diff --git a/tests/Heimdall.Agent.Tests/Services/DiskInventoryProviderDetailedTests.cs b/tests/Heimdall.Agent.Tests/Services/DiskInventoryProviderDetailedTests.cs new file mode 100644 index 0000000..94d7744 --- /dev/null +++ b/tests/Heimdall.Agent.Tests/Services/DiskInventoryProviderDetailedTests.cs @@ -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>(); + } + + [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"); + } +} diff --git a/tests/Heimdall.Agent.Tests/Services/GpuInventoryProviderDetailedTests.cs b/tests/Heimdall.Agent.Tests/Services/GpuInventoryProviderDetailedTests.cs new file mode 100644 index 0000000..2b63e81 --- /dev/null +++ b/tests/Heimdall.Agent.Tests/Services/GpuInventoryProviderDetailedTests.cs @@ -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>(); + } + + [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); + } +} diff --git a/tests/Heimdall.Agent.Tests/Services/HostInfoProviderTests.cs b/tests/Heimdall.Agent.Tests/Services/HostInfoProviderTests.cs new file mode 100644 index 0000000..b289604 --- /dev/null +++ b/tests/Heimdall.Agent.Tests/Services/HostInfoProviderTests.cs @@ -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("."); + } + } +} diff --git a/tests/Heimdall.Agent.Tests/Services/MemoryReaderTests.cs b/tests/Heimdall.Agent.Tests/Services/MemoryReaderTests.cs new file mode 100644 index 0000000..b6bdd4e --- /dev/null +++ b/tests/Heimdall.Agent.Tests/Services/MemoryReaderTests.cs @@ -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); + } + } +} diff --git a/tests/Heimdall.Agent.Tests/Services/ProcFsTests.cs b/tests/Heimdall.Agent.Tests/Services/ProcFsTests.cs new file mode 100644 index 0000000..abfa48e --- /dev/null +++ b/tests/Heimdall.Agent.Tests/Services/ProcFsTests.cs @@ -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); + } +} diff --git a/tests/Heimdall.Agent.Tests/SnapshotPipelineServiceTests.cs b/tests/Heimdall.Agent.Tests/SnapshotPipelineServiceTests.cs index 35e05a8..878d19e 100644 --- a/tests/Heimdall.Agent.Tests/SnapshotPipelineServiceTests.cs +++ b/tests/Heimdall.Agent.Tests/SnapshotPipelineServiceTests.cs @@ -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(); } } diff --git a/tests/Heimdall.Application.Tests/Agents/AgentExtensionsTests.cs b/tests/Heimdall.Application.Tests/Agents/AgentExtensionsTests.cs new file mode 100644 index 0000000..a24f26e --- /dev/null +++ b/tests/Heimdall.Application.Tests/Agents/AgentExtensionsTests.cs @@ -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"); + } +} diff --git a/tests/Heimdall.Application.Tests/Agents/HeartbeatCommandExtensionsTests.cs b/tests/Heimdall.Application.Tests/Agents/HeartbeatCommandExtensionsTests.cs new file mode 100644 index 0000000..ee4c4a7 --- /dev/null +++ b/tests/Heimdall.Application.Tests/Agents/HeartbeatCommandExtensionsTests.cs @@ -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"); + } +} diff --git a/tests/Heimdall.Application.Tests/DTOs/AgentTelemetryFieldsTests.cs b/tests/Heimdall.Application.Tests/DTOs/AgentTelemetryFieldsTests.cs new file mode 100644 index 0000000..e585921 --- /dev/null +++ b/tests/Heimdall.Application.Tests/DTOs/AgentTelemetryFieldsTests.cs @@ -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); + } +} diff --git a/tests/Heimdall.Application.Tests/Handlers/Agents/HeartbeatHandlerInventoryTests.cs b/tests/Heimdall.Application.Tests/Handlers/Agents/HeartbeatHandlerInventoryTests.cs new file mode 100644 index 0000000..69cae0e --- /dev/null +++ b/tests/Heimdall.Application.Tests/Handlers/Agents/HeartbeatHandlerInventoryTests.cs @@ -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(); + context.Agents.Returns(MockDbSetHelper.CreateFor([_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(); + context.Agents.Returns(MockDbSetHelper.CreateFor([_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(); + context.Agents.Returns(MockDbSetHelper.CreateFor([_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(); + context.Agents.Returns(MockDbSetHelper.CreateFor([_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(); + context.Agents.Returns(MockDbSetHelper.CreateFor([_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(); + context.Agents.Returns(MockDbSetHelper.CreateFor([_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(); + } +} diff --git a/tests/Heimdall.Domain.Tests/Entities/AgentInventoryTests.cs b/tests/Heimdall.Domain.Tests/Entities/AgentInventoryTests.cs new file mode 100644 index 0000000..72d9acd --- /dev/null +++ b/tests/Heimdall.Domain.Tests/Entities/AgentInventoryTests.cs @@ -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; + } +} diff --git a/tests/Heimdall.Web.Tests/Services/HeimdallApiClientCoverageTests.cs b/tests/Heimdall.Web.Tests/Services/HeimdallApiClientCoverageTests.cs new file mode 100644 index 0000000..473b585 --- /dev/null +++ b/tests/Heimdall.Web.Tests/Services/HeimdallApiClientCoverageTests.cs @@ -0,0 +1,964 @@ +using System.Net; +using Heimdall.Web.Services; +using NSubstitute; + +namespace Heimdall.Web.Tests.Services; + +/// +/// Additional HeimdallApiClient tests to increase line coverage on +/// Sites, Users, Cameras, Settings, Events, Notifications, AgentSettings, 2FA. +/// +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(); + _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( + [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( + [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( + [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()); + + 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()); + + 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 { ["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( + [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( + [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()); + + 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()); + + 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()); + + 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()); + + 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( + [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); + } +}