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