feat(agent): télémétrie inventaire matériel — CPU/mémoire/disque/GPU/OS/réseau (Fixes #82 #83 #84 #85) (#137)
## Contexte Implémentation des tickets #82, #83, #84, #85 — télémétrie inventaire matériel agent. L'objectif est de fournir au central un maximum d'informations sur les machines des agents (CPU, mémoire, disques, GPU, OS, réseau, conteneur) sans SSH. ## Changements ### Nouveaux collecteurs (src/Heimdall.Agent/Services/) - **CpuInfoProvider** : parse `/proc/cpuinfo` (vendor, modèle, cœurs physiques/logiques, fréquence, flags AVX/AVX2/FMA/AVX512, cache), topologie, détection cgroup CPU (`/sys/fs/cgroup/cpu.max` v2) - **DiskInventoryProvider** : énumère les montages (`/proc/mounts`), capacité/libre/type SSD/HDD via `/sys/block/*/queue/rotation` - **GpuInventoryProvider** : nvidia-smi, sysfs DRM, vainfo, rocm-smi avec fallback silencieux, multi-GPU - **HostInfoProvider** : os-release, uname, `/proc/uptime` (uptime machine ≠ process), températures sysfs - **ContainerInfoProvider** : détection Docker (/.dockerenv, cgroup), ID conteneur, limites CPU/mémoire ### Refonte SystemMetricsProvider - Séparation host vs process (RAM machine ≠ RAM conteneur ≠ WorkingSet64) - Uptime machine (`/proc/uptime`) distinct de l'uptime process - Mémoire swap ### Entité Agent + Migration - Champs structurés CPU/mémoire/disque/GPU/OS/réseau (tous nullable, rétrocompatible) - Migration EF `AddAgentTelemetryInventory` ### Transport heartbeat - Inventaire au register + refresh périodique (5 min, pas à chaque tick) - Champs JSON pour listes (disques, GPU, interfaces réseau, températures) ### UI Admin (AgentDetail.razor) - Sections CPU, Mémoire/Disques, GPU, Machine/Conteneur avec barres de progression et badges ### Tests - 40+ tests unitaires : providers, handlers, entité Agent - Total : 999 tests verts (Domain 149, Application 397, Agent 210, Web 243) ## Tickets liés - Fixes #82 — CPU inventory - Fixes #83 — Mémoire & disque - Fixes #84 — GPU inventory - Fixes #85 — OS, conteneur, réseau ## Résultats des tests - `dotnet build` : 0 erreur, 0 warning - Domain.Tests : 149 passed - Application.Tests : 397 passed - Agent.Tests : 210 passed - Web.Tests : 243 passed - Total : 999 tests ✅ ## Checklist - [x] `dotnet build` vert (TreatWarningsAsErrors) - [x] Tests unitaires verts - [x] Migration EF créée - [x] Champs nullable (rétrocompatible) - [x] Pas de référence Infrastructure dans les contrôleurs - [x] Collecteurs avec fallback silencieux (pas de crash sans GPU/Docker/sysfs) Reviewed-on: https://forgejo.tordais.cc/nonobis/Heimdall/pulls/137
This commit is contained in:
1 parent
f7e6b0cec3
commit
4792b69e46
63 files changed
+8711
-563
No files matched your search
@@ -21,6 +21,6 @@
|
||||
<PackageReference Include="Microsoft.AspNetCore.SignalR.Client" Version="10.0.8" />
|
||||
<PackageReference Include="Microsoft.ML.OnnxRuntime" Version="1.22.0" />
|
||||
<PackageReference Include="Sentry.AspNetCore" Version="6.8.0" />
|
||||
<PackageReference Include="SixLabors.ImageSharp" Version="4.1.0" />
|
||||
<PackageReference Include="Magick.NET-Q16-AnyCPU" Version="14.16.0" />
|
||||
</ItemGroup>
|
||||
</Project>
|
||||
@@ -82,6 +82,14 @@ builder.Services.AddSingleton<AgentState>(sp =>
|
||||
});
|
||||
|
||||
builder.Services.AddSingleton<SystemMetricsProvider>();
|
||||
|
||||
// Inventory providers (grouped under InventoryProviders to reduce constructor parameter count)
|
||||
builder.Services.AddSingleton<CpuInfoProvider>();
|
||||
builder.Services.AddSingleton<DiskInventoryProvider>();
|
||||
builder.Services.AddSingleton<HostInfoProvider>();
|
||||
builder.Services.AddSingleton<ContainerInfoProvider>();
|
||||
builder.Services.AddSingleton<InventoryProviders>();
|
||||
|
||||
builder.Services.AddSingleton<NetworkCameraScanner>();
|
||||
builder.Services.AddSingleton<HomeKitMdnsProbe>();
|
||||
builder.Services.AddSingleton<ICameraDatabase, SqliteCameraDatabase>();
|
||||
|
||||
@@ -5,6 +5,21 @@ using Microsoft.Extensions.Options;
|
||||
|
||||
namespace Heimdall.Agent.Services;
|
||||
|
||||
/// <summary>
|
||||
/// Groups inventory-related services to reduce constructor parameter count.
|
||||
/// </summary>
|
||||
public sealed class InventoryProviders(
|
||||
CpuInfoProvider cpuInfo,
|
||||
DiskInventoryProvider diskInventory,
|
||||
HostInfoProvider hostInfo,
|
||||
ContainerInfoProvider containerInfo)
|
||||
{
|
||||
public CpuInfoProvider CpuInfo { get; } = cpuInfo;
|
||||
public DiskInventoryProvider DiskInventory { get; } = diskInventory;
|
||||
public HostInfoProvider HostInfo { get; } = hostInfo;
|
||||
public ContainerInfoProvider ContainerInfo { get; } = containerInfo;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Registers this agent with the Heimdall Central server and manages the heartbeat loop.
|
||||
/// </summary>
|
||||
@@ -15,14 +30,21 @@ public class AgentRegistrationService : BackgroundService
|
||||
private readonly AgentState _state;
|
||||
private readonly AgentOptions _options;
|
||||
private readonly SystemMetricsProvider _metrics;
|
||||
private readonly InventoryProviders _providers;
|
||||
private readonly Logging.LogBufferService _buffer;
|
||||
private HttpClient? _client;
|
||||
|
||||
/// <summary>Interval for full inventory refresh (5 minutes).</summary>
|
||||
private static readonly TimeSpan InventoryRefreshInterval = TimeSpan.FromMinutes(5);
|
||||
private const string ApiKeyHeader = "X-API-Key";
|
||||
private DateTime _lastInventoryRefresh = DateTime.MinValue;
|
||||
|
||||
public AgentRegistrationService(
|
||||
IHttpClientFactory httpClientFactory,
|
||||
AgentState state,
|
||||
IOptions<AgentOptions> options,
|
||||
SystemMetricsProvider metrics,
|
||||
InventoryProviders providers,
|
||||
Logging.LogBufferService buffer,
|
||||
ILogger<AgentRegistrationService> logger)
|
||||
{
|
||||
@@ -30,6 +52,7 @@ public class AgentRegistrationService : BackgroundService
|
||||
_state = state;
|
||||
_options = options.Value;
|
||||
_metrics = metrics;
|
||||
_providers = providers;
|
||||
_buffer = buffer;
|
||||
_logger = logger;
|
||||
}
|
||||
@@ -42,27 +65,32 @@ public class AgentRegistrationService : BackgroundService
|
||||
if (_client is not null && _state.AgentId != Guid.Empty)
|
||||
{
|
||||
_logger.LogInformation("Agent stopping, sending final heartbeat...");
|
||||
try
|
||||
{
|
||||
var metrics = _metrics.Collect();
|
||||
var request = new HeartbeatRequest(_state.PublicIp, IsOffline: true,
|
||||
CpuUsagePercent: metrics.CpuUsagePercent,
|
||||
MemoryUsageBytes: metrics.MemoryUsageBytes,
|
||||
DiskUsagePercent: metrics.DiskUsagePercent,
|
||||
UptimeSeconds: metrics.UptimeSeconds);
|
||||
await _client.PostAsJsonAsync(
|
||||
$"api/agents/{_state.AgentId}/heartbeat",
|
||||
request, CancellationToken.None);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogWarning(ex, "Final heartbeat failed (non-fatal)");
|
||||
}
|
||||
await SendFinalHeartbeatAsync();
|
||||
}
|
||||
|
||||
await base.StopAsync(cancellationToken);
|
||||
}
|
||||
|
||||
private async Task SendFinalHeartbeatAsync()
|
||||
{
|
||||
try
|
||||
{
|
||||
var metrics = _metrics.Collect();
|
||||
var request = new HeartbeatRequest(_state.PublicIp, IsOffline: true,
|
||||
CpuUsagePercent: metrics.CpuUsagePercent,
|
||||
MemoryUsageBytes: metrics.MemoryUsageBytes,
|
||||
DiskUsagePercent: metrics.DiskUsagePercent,
|
||||
UptimeSeconds: metrics.UptimeSeconds);
|
||||
await _client!.PostAsJsonAsync(
|
||||
$"api/agents/{_state.AgentId}/heartbeat",
|
||||
request, CancellationToken.None);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogWarning(ex, "Final heartbeat failed (non-fatal)");
|
||||
}
|
||||
}
|
||||
|
||||
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
|
||||
{
|
||||
var hostname = string.IsNullOrEmpty(_options.AgentName)
|
||||
@@ -80,8 +108,8 @@ public class AgentRegistrationService : BackgroundService
|
||||
_state.ApiKeyPrefix = existing.ApiKeyPrefix;
|
||||
_state.PublicIp = existing.PublicIp;
|
||||
|
||||
client.DefaultRequestHeaders.Remove("X-API-Key");
|
||||
client.DefaultRequestHeaders.Add("X-API-Key", existing.ApiKey);
|
||||
client.DefaultRequestHeaders.Remove(ApiKeyHeader);
|
||||
client.DefaultRequestHeaders.Add(ApiKeyHeader, existing.ApiKey);
|
||||
_client = client;
|
||||
|
||||
_logger.LogInformation(
|
||||
@@ -90,58 +118,7 @@ public class AgentRegistrationService : BackgroundService
|
||||
}
|
||||
else
|
||||
{
|
||||
// Step 1: Register (with retry)
|
||||
_logger.LogInformation("Registering agent with Central at {CentralUrl}", _options.CentralUrl);
|
||||
|
||||
var maxRetries = _options.RegistrationMaxRetries;
|
||||
RegisterResponse? registration = null;
|
||||
|
||||
for (int attempt = 1; attempt <= maxRetries; attempt++)
|
||||
{
|
||||
try
|
||||
{
|
||||
var request = new RegisterRequest(_options.SiteToken, hostname, _options.Version);
|
||||
var response = await client.PostAsJsonAsync("api/agents/register", request, stoppingToken);
|
||||
response.EnsureSuccessStatusCode();
|
||||
|
||||
registration = await response.Content.ReadFromJsonAsync<RegisterResponse>(stoppingToken);
|
||||
if (registration is null)
|
||||
throw new InvalidOperationException("Empty registration response");
|
||||
|
||||
break; // success
|
||||
}
|
||||
catch (Exception ex) when (attempt < maxRetries && ex is not OperationCanceledException)
|
||||
{
|
||||
var delay = TimeSpan.FromSeconds(Math.Pow(2, attempt));
|
||||
_logger.LogWarning(ex,
|
||||
"Registration attempt {Attempt}/{Max} failed, retrying in {Delay}s",
|
||||
attempt, maxRetries, delay.TotalSeconds);
|
||||
await Task.Delay(delay, stoppingToken);
|
||||
}
|
||||
}
|
||||
|
||||
if (registration is null)
|
||||
{
|
||||
_logger.LogError("All {Max} registration attempts failed", maxRetries);
|
||||
throw new InvalidOperationException("Agent registration failed after all retries");
|
||||
}
|
||||
|
||||
_state.AgentId = registration.AgentId;
|
||||
_state.ApiKey = registration.ApiKey;
|
||||
_state.ApiKeyPrefix = registration.ApiKeyPrefix;
|
||||
_state.PublicIp = await ResolvePublicIpAsync(stoppingToken);
|
||||
|
||||
// Persist identity so subsequent restarts reuse it
|
||||
await _state.SaveAsync(stoppingToken);
|
||||
|
||||
// Set API Key header for subsequent requests (Central's ApiKey scheme reads X-API-Key)
|
||||
client.DefaultRequestHeaders.Remove("X-API-Key");
|
||||
client.DefaultRequestHeaders.Add("X-API-Key", registration.ApiKey);
|
||||
_client = client;
|
||||
|
||||
_logger.LogInformation(
|
||||
"Agent registered successfully. ID: {AgentId}, Key prefix: {Prefix}",
|
||||
registration.AgentId, registration.ApiKeyPrefix);
|
||||
await RegisterAgentAsync(client, hostname, stoppingToken);
|
||||
}
|
||||
|
||||
// Step 2: Heartbeat loop
|
||||
@@ -151,33 +128,7 @@ public class AgentRegistrationService : BackgroundService
|
||||
|
||||
while (!stoppingToken.IsCancellationRequested)
|
||||
{
|
||||
try
|
||||
{
|
||||
var metrics = _metrics.Collect();
|
||||
var heartbeatRequest = new HeartbeatRequest(
|
||||
_state.PublicIp,
|
||||
CpuUsagePercent: metrics.CpuUsagePercent,
|
||||
MemoryUsageBytes: metrics.MemoryUsageBytes,
|
||||
DiskUsagePercent: metrics.DiskUsagePercent,
|
||||
UptimeSeconds: metrics.UptimeSeconds);
|
||||
var heartbeatResponse = await client.PostAsJsonAsync(
|
||||
$"api/agents/{_state.AgentId}/heartbeat",
|
||||
heartbeatRequest, stoppingToken);
|
||||
|
||||
if (!heartbeatResponse.IsSuccessStatusCode)
|
||||
{
|
||||
_logger.LogWarning("Heartbeat failed: {StatusCode}", heartbeatResponse.StatusCode);
|
||||
}
|
||||
else
|
||||
{
|
||||
_logger.LogDebug("Heartbeat OK — agent online, {Buffered} log(s) buffered",
|
||||
_buffer.Count);
|
||||
}
|
||||
}
|
||||
catch (Exception ex) when (ex is not OperationCanceledException)
|
||||
{
|
||||
_logger.LogWarning(ex, "Heartbeat error (will retry)");
|
||||
}
|
||||
await SendHeartbeatAsync(client, stoppingToken);
|
||||
|
||||
// Re-read the interval each cycle so a remote setting change
|
||||
// (ConfigReceiverService → AgentState.HeartbeatIntervalSeconds)
|
||||
@@ -188,6 +139,153 @@ public class AgentRegistrationService : BackgroundService
|
||||
}
|
||||
}
|
||||
|
||||
private async Task RegisterAgentAsync(HttpClient client, string hostname, CancellationToken stoppingToken)
|
||||
{
|
||||
_logger.LogInformation("Registering agent with Central at {CentralUrl}", _options.CentralUrl);
|
||||
|
||||
var maxRetries = _options.RegistrationMaxRetries;
|
||||
RegisterResponse? registration = null;
|
||||
|
||||
for (int attempt = 1; attempt <= maxRetries; attempt++)
|
||||
{
|
||||
try
|
||||
{
|
||||
var request = new RegisterRequest(_options.SiteToken, hostname, _options.Version);
|
||||
var response = await client.PostAsJsonAsync("api/agents/register", request, stoppingToken);
|
||||
response.EnsureSuccessStatusCode();
|
||||
|
||||
registration = await response.Content.ReadFromJsonAsync<RegisterResponse>(stoppingToken);
|
||||
if (registration is null)
|
||||
throw new InvalidOperationException("Empty registration response");
|
||||
|
||||
break; // success
|
||||
}
|
||||
catch (Exception ex) when (attempt < maxRetries && ex is not OperationCanceledException)
|
||||
{
|
||||
var delay = TimeSpan.FromSeconds(Math.Pow(2, attempt));
|
||||
_logger.LogWarning(ex,
|
||||
"Registration attempt {Attempt}/{Max} failed, retrying in {Delay}s",
|
||||
attempt, maxRetries, delay.TotalSeconds);
|
||||
await Task.Delay(delay, stoppingToken);
|
||||
}
|
||||
}
|
||||
|
||||
if (registration is null)
|
||||
{
|
||||
_logger.LogError("All {Max} registration attempts failed", maxRetries);
|
||||
throw new InvalidOperationException("Agent registration failed after all retries");
|
||||
}
|
||||
|
||||
_state.AgentId = registration.AgentId;
|
||||
_state.ApiKey = registration.ApiKey;
|
||||
_state.ApiKeyPrefix = registration.ApiKeyPrefix;
|
||||
_state.PublicIp = await ResolvePublicIpAsync(stoppingToken);
|
||||
|
||||
// Persist identity so subsequent restarts reuse it
|
||||
await _state.SaveAsync(stoppingToken);
|
||||
|
||||
// Set API Key header for subsequent requests
|
||||
client.DefaultRequestHeaders.Remove(ApiKeyHeader);
|
||||
client.DefaultRequestHeaders.Add(ApiKeyHeader, registration.ApiKey);
|
||||
_client = client;
|
||||
|
||||
_logger.LogInformation(
|
||||
"Agent registered successfully. ID: {AgentId}, Key prefix: {Prefix}",
|
||||
registration.AgentId, registration.ApiKeyPrefix);
|
||||
}
|
||||
|
||||
private async Task SendHeartbeatAsync(HttpClient client, CancellationToken stoppingToken)
|
||||
{
|
||||
try
|
||||
{
|
||||
var metrics = _metrics.Collect();
|
||||
var inventory = CollectInventoryIfNeeded();
|
||||
|
||||
var heartbeatRequest = BuildHeartbeatRequest(metrics, inventory);
|
||||
var heartbeatResponse = await client.PostAsJsonAsync(
|
||||
$"api/agents/{_state.AgentId}/heartbeat",
|
||||
heartbeatRequest, stoppingToken);
|
||||
|
||||
if (!heartbeatResponse.IsSuccessStatusCode)
|
||||
{
|
||||
_logger.LogWarning("Heartbeat failed: {StatusCode}", heartbeatResponse.StatusCode);
|
||||
}
|
||||
else
|
||||
{
|
||||
_logger.LogDebug("Heartbeat OK — agent online, {Buffered} log(s) buffered",
|
||||
_buffer.Count);
|
||||
}
|
||||
}
|
||||
catch (Exception ex) when (ex is not OperationCanceledException)
|
||||
{
|
||||
_logger.LogWarning(ex, "Heartbeat error (will retry)");
|
||||
}
|
||||
}
|
||||
|
||||
private HeartbeatRequest BuildHeartbeatRequest(SystemMetrics metrics, InventorySnapshot? inventory) => new(
|
||||
_state.PublicIp,
|
||||
CpuUsagePercent: metrics.CpuUsagePercent,
|
||||
MemoryUsageBytes: metrics.MemoryUsageBytes,
|
||||
DiskUsagePercent: metrics.DiskUsagePercent,
|
||||
UptimeSeconds: metrics.UptimeSeconds,
|
||||
MachineUptimeSeconds: metrics.MachineUptimeSeconds,
|
||||
CpuVendor: inventory?.Cpu?.Vendor,
|
||||
CpuModel: inventory?.Cpu?.Model,
|
||||
CpuArchitecture: inventory?.Cpu?.Architecture,
|
||||
PhysicalCores: inventory?.Cpu?.PhysicalCores,
|
||||
LogicalCores: inventory?.Cpu?.LogicalCores,
|
||||
ThreadsPerCore: inventory?.Cpu?.ThreadsPerCore,
|
||||
CpuFrequencyMhz: inventory?.Cpu?.FrequencyMhz,
|
||||
CpuFlags: inventory?.Cpu?.Flags,
|
||||
CpuCacheBytes: inventory?.Cpu?.CacheBytes,
|
||||
ContainerCpuLimit: inventory?.Cpu?.ContainerCpuLimit,
|
||||
MemTotalBytes: inventory?.MemTotalBytes,
|
||||
MemAvailableBytes: inventory?.MemAvailableBytes,
|
||||
SwapTotalBytes: inventory?.SwapTotalBytes,
|
||||
SwapFreeBytes: inventory?.SwapFreeBytes,
|
||||
ContainerMemoryLimitBytes: inventory?.Container?.MemoryLimitBytes,
|
||||
DiskInventoryJson: inventory?.DiskJson,
|
||||
GpuInventoryJson: inventory?.GpuJson,
|
||||
OsName: inventory?.Host?.OsName,
|
||||
KernelVersion: inventory?.Host?.KernelVersion,
|
||||
Arch: inventory?.Host?.Arch,
|
||||
UptimeMachineSeconds: inventory?.Host?.UptimeSeconds,
|
||||
ContainerId: inventory?.Container?.ContainerId,
|
||||
ContainerImage: inventory?.Container?.ContainerImage,
|
||||
NetworkInterfacesJson: inventory?.NetworkJson,
|
||||
TemperatureJson: inventory?.TemperatureJson);
|
||||
|
||||
private InventorySnapshot? CollectInventoryIfNeeded()
|
||||
{
|
||||
var now = DateTime.UtcNow;
|
||||
if (now - _lastInventoryRefresh < InventoryRefreshInterval)
|
||||
return null; // use cached/null inventory this tick
|
||||
|
||||
_lastInventoryRefresh = now;
|
||||
_logger.LogDebug("Collecting hardware inventory...");
|
||||
|
||||
var cpu = _providers.CpuInfo.Collect();
|
||||
var disks = _providers.DiskInventory.Collect();
|
||||
var gpus = GpuInventoryProvider.Collect();
|
||||
var host = _providers.HostInfo.Collect();
|
||||
var container = _providers.ContainerInfo.Collect();
|
||||
|
||||
return new InventorySnapshot
|
||||
{
|
||||
Cpu = cpu,
|
||||
Host = host,
|
||||
Container = container,
|
||||
MemTotalBytes = MemoryReader.GetMemoryTotal(),
|
||||
MemAvailableBytes = MemoryReader.GetMemoryAvailable(),
|
||||
SwapTotalBytes = MemoryReader.GetSwapTotal(),
|
||||
SwapFreeBytes = MemoryReader.GetSwapFree(),
|
||||
DiskJson = System.Text.Json.JsonSerializer.Serialize(disks),
|
||||
GpuJson = System.Text.Json.JsonSerializer.Serialize(gpus),
|
||||
NetworkJson = System.Text.Json.JsonSerializer.Serialize(host.NetworkInterfaces),
|
||||
TemperatureJson = System.Text.Json.JsonSerializer.Serialize(host.Temperature)
|
||||
};
|
||||
}
|
||||
|
||||
private async Task<string?> ResolvePublicIpAsync(CancellationToken ct)
|
||||
{
|
||||
try
|
||||
@@ -201,10 +299,25 @@ public class AgentRegistrationService : BackgroundService
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogDebug("Public IP resolution failed ({Error}); reporting null", ex.Message);
|
||||
_logger.LogDebug(ex, "Public IP resolution failed; reporting null");
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private sealed class InventorySnapshot
|
||||
{
|
||||
public CpuInfo? Cpu { get; init; }
|
||||
public HostInfo? Host { get; init; }
|
||||
public ContainerInfo? Container { get; init; }
|
||||
public long? MemTotalBytes { get; init; }
|
||||
public long? MemAvailableBytes { get; init; }
|
||||
public long? SwapTotalBytes { get; init; }
|
||||
public long? SwapFreeBytes { get; init; }
|
||||
public string? DiskJson { get; init; }
|
||||
public string? GpuJson { get; init; }
|
||||
public string? NetworkJson { get; init; }
|
||||
public string? TemperatureJson { get; init; }
|
||||
}
|
||||
}
|
||||
|
||||
internal sealed record RegisterRequest(string Token, string Hostname, string Version);
|
||||
@@ -220,4 +333,37 @@ internal sealed record HeartbeatRequest(
|
||||
[property: JsonPropertyName("cpuUsagePercent")] double? CpuUsagePercent = null,
|
||||
[property: JsonPropertyName("memoryUsageBytes")] long? MemoryUsageBytes = null,
|
||||
[property: JsonPropertyName("diskUsagePercent")] double? DiskUsagePercent = null,
|
||||
[property: JsonPropertyName("uptimeSeconds")] long? UptimeSeconds = null);
|
||||
[property: JsonPropertyName("uptimeSeconds")] long? UptimeSeconds = null,
|
||||
[property: JsonPropertyName("machineUptimeSeconds")] long? MachineUptimeSeconds = null,
|
||||
// CPU inventory
|
||||
[property: JsonPropertyName("cpuVendor")] string? CpuVendor = null,
|
||||
[property: JsonPropertyName("cpuModel")] string? CpuModel = null,
|
||||
[property: JsonPropertyName("cpuArchitecture")] string? CpuArchitecture = null,
|
||||
[property: JsonPropertyName("physicalCores")] int? PhysicalCores = null,
|
||||
[property: JsonPropertyName("logicalCores")] int? LogicalCores = null,
|
||||
[property: JsonPropertyName("threadsPerCore")] int? ThreadsPerCore = null,
|
||||
[property: JsonPropertyName("cpuFrequencyMhz")] double? CpuFrequencyMhz = null,
|
||||
[property: JsonPropertyName("cpuFlags")] string? CpuFlags = null,
|
||||
[property: JsonPropertyName("cpuCacheBytes")] long? CpuCacheBytes = null,
|
||||
[property: JsonPropertyName("containerCpuLimit")] long? ContainerCpuLimit = null,
|
||||
// Memory inventory
|
||||
[property: JsonPropertyName("memTotalBytes")] long? MemTotalBytes = null,
|
||||
[property: JsonPropertyName("memAvailableBytes")] long? MemAvailableBytes = null,
|
||||
[property: JsonPropertyName("swapTotalBytes")] long? SwapTotalBytes = null,
|
||||
[property: JsonPropertyName("swapFreeBytes")] long? SwapFreeBytes = null,
|
||||
[property: JsonPropertyName("containerMemoryLimitBytes")] long? ContainerMemoryLimitBytes = null,
|
||||
// Disk inventory
|
||||
[property: JsonPropertyName("diskInventoryJson")] string? DiskInventoryJson = null,
|
||||
// GPU inventory
|
||||
[property: JsonPropertyName("gpuInventoryJson")] string? GpuInventoryJson = null,
|
||||
// Host info
|
||||
[property: JsonPropertyName("osName")] string? OsName = null,
|
||||
[property: JsonPropertyName("kernelVersion")] string? KernelVersion = null,
|
||||
[property: JsonPropertyName("arch")] string? Arch = null,
|
||||
[property: JsonPropertyName("uptimeMachineSeconds")] long? UptimeMachineSeconds = null,
|
||||
// Container info
|
||||
[property: JsonPropertyName("containerId")] string? ContainerId = null,
|
||||
[property: JsonPropertyName("containerImage")] string? ContainerImage = null,
|
||||
// Network & Temperature
|
||||
[property: JsonPropertyName("networkInterfacesJson")] string? NetworkInterfacesJson = null,
|
||||
[property: JsonPropertyName("temperatureJson")] string? TemperatureJson = null);
|
||||
@@ -0,0 +1,88 @@
|
||||
namespace Heimdall.Agent.Services;
|
||||
|
||||
/// <summary>
|
||||
/// Shared cgroup limit readers. Eliminates duplication between
|
||||
/// <see cref="CpuInfoProvider"/> and <see cref="ContainerInfoProvider"/>.
|
||||
/// </summary>
|
||||
internal static class CgroupReader
|
||||
{
|
||||
/// <summary>
|
||||
/// Reads the CPU limit from cgroup v1/v2. Returns the limit as a
|
||||
/// percentage-based value (e.g. 200 = 2 cores), or null if unlimited.
|
||||
/// </summary>
|
||||
public static long? GetCpuLimit()
|
||||
{
|
||||
try
|
||||
{
|
||||
if (!OperatingSystem.IsLinux()) return null;
|
||||
|
||||
// cgroup v2: /sys/fs/cgroup/cpu.max → "max 100000" or "200000 100000"
|
||||
var cpuMaxPath = "/sys/fs/cgroup/cpu.max";
|
||||
if (File.Exists(cpuMaxPath))
|
||||
{
|
||||
var content = File.ReadAllText(cpuMaxPath).Trim();
|
||||
var parts = content.Split(' ', StringSplitOptions.RemoveEmptyEntries);
|
||||
if (parts.Length == 2 && parts[0] != "max" &&
|
||||
long.TryParse(parts[0], out var quota) &&
|
||||
long.TryParse(parts[1], out var period) && period > 0)
|
||||
{
|
||||
return (long)Math.Ceiling((double)quota / period * 100);
|
||||
}
|
||||
}
|
||||
|
||||
// cgroup v1: /sys/fs/cgroup/cpu/cpu.cfs_quota_us and cpu.cfs_period_us
|
||||
var quotaPath = "/sys/fs/cgroup/cpu/cpu.cfs_quota_us";
|
||||
var periodPath = "/sys/fs/cgroup/cpu/cpu.cfs_period_us";
|
||||
if (File.Exists(quotaPath) && File.Exists(periodPath))
|
||||
{
|
||||
var quotaStr = File.ReadAllText(quotaPath).Trim();
|
||||
var periodStr = File.ReadAllText(periodPath).Trim();
|
||||
if (long.TryParse(quotaStr, out var quota) && quota > 0 &&
|
||||
long.TryParse(periodStr, out var period) && period > 0)
|
||||
{
|
||||
return (long)Math.Ceiling((double)quota / period * 100);
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
catch
|
||||
{
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Reads the memory limit from cgroup v1/v2. Returns bytes, or null if unlimited.
|
||||
/// </summary>
|
||||
public static long? GetMemoryLimit()
|
||||
{
|
||||
try
|
||||
{
|
||||
if (!OperatingSystem.IsLinux()) return null;
|
||||
|
||||
// cgroup v2: /sys/fs/cgroup/memory.max
|
||||
var memMaxPath = "/sys/fs/cgroup/memory.max";
|
||||
if (File.Exists(memMaxPath))
|
||||
{
|
||||
var content = File.ReadAllText(memMaxPath).Trim();
|
||||
if (content != "max" && long.TryParse(content, out var limit) && limit > 0)
|
||||
return limit;
|
||||
}
|
||||
|
||||
// cgroup v1: /sys/fs/cgroup/memory/memory.limit_in_bytes
|
||||
var v1Path = "/sys/fs/cgroup/memory/memory.limit_in_bytes";
|
||||
if (File.Exists(v1Path))
|
||||
{
|
||||
var content = File.ReadAllText(v1Path).Trim();
|
||||
if (long.TryParse(content, out var limit) && limit > 0 &&
|
||||
limit < long.MaxValue / 2) // sanity: ignore unlimited
|
||||
{
|
||||
return limit;
|
||||
}
|
||||
}
|
||||
}
|
||||
catch { /* best effort */ }
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
using System.Diagnostics;
|
||||
|
||||
namespace Heimdall.Agent.Services;
|
||||
|
||||
/// <summary>
|
||||
/// Shared utility for running external commands. Eliminates duplication
|
||||
/// across GpuInventoryProvider, HostInfoProvider, and other providers.
|
||||
/// </summary>
|
||||
internal static class CommandRunner
|
||||
{
|
||||
/// <summary>
|
||||
/// Runs an external command and returns its standard output.
|
||||
/// Returns null on failure or timeout.
|
||||
/// </summary>
|
||||
public static string? Run(string command, string arguments, int timeoutMs = 5000)
|
||||
{
|
||||
try
|
||||
{
|
||||
using var process = Process.Start(new ProcessStartInfo
|
||||
{
|
||||
FileName = command,
|
||||
Arguments = arguments,
|
||||
RedirectStandardOutput = true,
|
||||
RedirectStandardError = true,
|
||||
UseShellExecute = false,
|
||||
CreateNoWindow = true
|
||||
});
|
||||
|
||||
if (process is null) return null;
|
||||
|
||||
var outputTask = process.StandardOutput.ReadToEndAsync();
|
||||
|
||||
if (!process.WaitForExit(timeoutMs))
|
||||
{
|
||||
try { process.Kill(); } catch { /* best effort */ }
|
||||
return null;
|
||||
}
|
||||
|
||||
return outputTask.IsCompletedSuccessfully ? outputTask.Result : null;
|
||||
}
|
||||
catch
|
||||
{
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,136 @@
|
||||
namespace Heimdall.Agent.Services;
|
||||
|
||||
/// <summary>
|
||||
/// Detects container environment (Docker, Podman, etc.) and reads cgroup limits.
|
||||
/// </summary>
|
||||
public sealed class ContainerInfoProvider
|
||||
{
|
||||
private const string ProcEnvironPath = "/proc/1/environ";
|
||||
private const string Proc1CgroupPath = "/proc/1/cgroup";
|
||||
private const string ProcSelfCgroupPath = "/proc/self/cgroup";
|
||||
|
||||
public ContainerInfo Collect()
|
||||
{
|
||||
var isContainer = DetectContainer();
|
||||
return new ContainerInfo
|
||||
{
|
||||
IsContainer = isContainer,
|
||||
ContainerId = isContainer ? GetContainerId() : null,
|
||||
ContainerImage = isContainer ? GetContainerImage() : null,
|
||||
MemoryLimitBytes = CgroupReader.GetMemoryLimit(),
|
||||
CpuLimit = CgroupReader.GetCpuLimit()
|
||||
};
|
||||
}
|
||||
|
||||
private static bool DetectContainer()
|
||||
{
|
||||
try
|
||||
{
|
||||
if (File.Exists("/.dockerenv") || File.Exists("/run/.containerenv"))
|
||||
return true;
|
||||
|
||||
if (DetectFromCgroup() || DetectFromEnviron())
|
||||
return true;
|
||||
}
|
||||
catch { /* best effort */ }
|
||||
return false;
|
||||
}
|
||||
|
||||
private static bool DetectFromCgroup()
|
||||
{
|
||||
if (!File.Exists(Proc1CgroupPath)) return false;
|
||||
|
||||
var cgroupContent = File.ReadAllText(Proc1CgroupPath);
|
||||
return cgroupContent.Contains("docker", StringComparison.OrdinalIgnoreCase) ||
|
||||
cgroupContent.Contains("containerd", StringComparison.OrdinalIgnoreCase) ||
|
||||
cgroupContent.Contains("kubepods", StringComparison.OrdinalIgnoreCase) ||
|
||||
cgroupContent.Contains("lxc", StringComparison.OrdinalIgnoreCase) ||
|
||||
cgroupContent.Contains("podman", StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
|
||||
private static bool DetectFromEnviron()
|
||||
{
|
||||
if (!File.Exists(ProcEnvironPath)) return false;
|
||||
|
||||
var environ = File.ReadAllText(ProcEnvironPath);
|
||||
return environ.Contains("container=docker", StringComparison.OrdinalIgnoreCase) ||
|
||||
environ.Contains("container=podman", StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
|
||||
private static string? GetContainerId()
|
||||
{
|
||||
try
|
||||
{
|
||||
var id = GetContainerIdFromCgroup();
|
||||
if (id is not null) return id;
|
||||
|
||||
// Try hostname (Docker sets container ID as hostname)
|
||||
var hostname = Environment.MachineName;
|
||||
if (hostname.Length >= 12 && hostname.All(c => "0123456789abcdef".Contains(c)))
|
||||
return hostname[..12];
|
||||
}
|
||||
catch { /* best effort */ }
|
||||
return null;
|
||||
}
|
||||
|
||||
private static string? GetContainerIdFromCgroup()
|
||||
{
|
||||
if (!File.Exists(ProcSelfCgroupPath)) return null;
|
||||
|
||||
foreach (var line in File.ReadLines(ProcSelfCgroupPath))
|
||||
{
|
||||
var parts = line.Split(':', StringSplitOptions.RemoveEmptyEntries);
|
||||
if (parts.Length < 3) continue;
|
||||
|
||||
var segments = parts[2].Split('/', StringSplitOptions.RemoveEmptyEntries);
|
||||
var lastSegment = segments.LastOrDefault();
|
||||
if (lastSegment is { Length: >= 12 } && lastSegment.All(c => "0123456789abcdef".Contains(c)))
|
||||
return lastSegment[..Math.Min(12, lastSegment.Length)];
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
private static string? GetContainerImage()
|
||||
{
|
||||
try
|
||||
{
|
||||
var envImage = Environment.GetEnvironmentVariable("DOCKER_IMAGE")
|
||||
?? Environment.GetEnvironmentVariable("CONTAINER_IMAGE");
|
||||
if (!string.IsNullOrWhiteSpace(envImage))
|
||||
return envImage;
|
||||
|
||||
return ReadImageFromEnviron();
|
||||
}
|
||||
catch { /* best effort */ }
|
||||
return null;
|
||||
}
|
||||
|
||||
private static string? ReadImageFromEnviron()
|
||||
{
|
||||
if (!File.Exists(ProcEnvironPath)) return null;
|
||||
|
||||
var environ = File.ReadAllText(ProcEnvironPath);
|
||||
foreach (var pair in environ.Split('\0'))
|
||||
{
|
||||
if (pair.StartsWith("DOCKER_IMAGE=", StringComparison.OrdinalIgnoreCase))
|
||||
return pair["DOCKER_IMAGE=".Length..];
|
||||
if (pair.StartsWith("IMAGE_NAME=", StringComparison.OrdinalIgnoreCase))
|
||||
return pair["IMAGE_NAME=".Length..];
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Container environment information.
|
||||
/// </summary>
|
||||
public sealed record ContainerInfo
|
||||
{
|
||||
public bool IsContainer { get; init; }
|
||||
public string? ContainerId { get; init; }
|
||||
public string? ContainerImage { get; init; }
|
||||
public long? MemoryLimitBytes { get; init; }
|
||||
public long? CpuLimit { get; init; }
|
||||
}
|
||||
@@ -0,0 +1,204 @@
|
||||
using System.Runtime.InteropServices;
|
||||
using System.Text.RegularExpressions;
|
||||
|
||||
namespace Heimdall.Agent.Services;
|
||||
|
||||
/// <summary>
|
||||
/// Collects CPU inventory information from /proc/cpuinfo, topology, and cgroup limits.
|
||||
/// </summary>
|
||||
public sealed partial class CpuInfoProvider
|
||||
{
|
||||
public CpuInfo Collect()
|
||||
{
|
||||
var info = ParseProcCpuinfo();
|
||||
var topology = GetTopology();
|
||||
|
||||
return new CpuInfo
|
||||
{
|
||||
Vendor = info.GetValueOrDefault("vendor_id"),
|
||||
Model = info.GetValueOrDefault("model name"),
|
||||
Architecture = GetArchitecture(),
|
||||
PhysicalCores = topology.PhysicalCores,
|
||||
LogicalCores = topology.LogicalCores,
|
||||
ThreadsPerCore = topology.ThreadsPerCore,
|
||||
FrequencyMhz = ParseFrequency(info.GetValueOrDefault("cpu MHz")),
|
||||
Flags = FilterKeyFlags(info.GetValueOrDefault("flags") ?? info.GetValueOrDefault("Features") ?? ""),
|
||||
CacheBytes = GetCacheSize(),
|
||||
ContainerCpuLimit = CgroupReader.GetCpuLimit()
|
||||
};
|
||||
}
|
||||
|
||||
private static Dictionary<string, string> ParseProcCpuinfo()
|
||||
{
|
||||
var result = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
|
||||
try
|
||||
{
|
||||
if (!File.Exists("/proc/cpuinfo"))
|
||||
return result;
|
||||
|
||||
foreach (var line in File.ReadLines("/proc/cpuinfo"))
|
||||
{
|
||||
var idx = line.IndexOf(':');
|
||||
if (idx <= 0) continue;
|
||||
var key = line[..idx].Trim();
|
||||
var value = line[(idx + 1)..].Trim();
|
||||
if (!result.ContainsKey(key))
|
||||
result[key] = value;
|
||||
}
|
||||
}
|
||||
catch { /* best effort */ }
|
||||
return result;
|
||||
}
|
||||
|
||||
private static (int? PhysicalCores, int? LogicalCores, int? ThreadsPerCore) GetTopology()
|
||||
{
|
||||
try
|
||||
{
|
||||
if (!OperatingSystem.IsLinux())
|
||||
return (null, Environment.ProcessorCount, null);
|
||||
|
||||
var logicalCount = Environment.ProcessorCount;
|
||||
var physicalCores = CountPhysicalCores();
|
||||
var threadsPerCore = physicalCores is > 0 ? (int?)(logicalCount / physicalCores.Value) : null;
|
||||
|
||||
return (physicalCores, logicalCount, threadsPerCore);
|
||||
}
|
||||
catch
|
||||
{
|
||||
return (null, Environment.ProcessorCount, null);
|
||||
}
|
||||
}
|
||||
|
||||
private static int? CountPhysicalCores()
|
||||
{
|
||||
var physicalEntries = new HashSet<string>();
|
||||
var cpuDirs = Directory.GetDirectories("/sys/devices/system/cpu")
|
||||
.Where(d => CoreDirPattern().IsMatch(Path.GetFileName(d)));
|
||||
|
||||
foreach (var cpuDir in cpuDirs)
|
||||
{
|
||||
var physicalIdPath = Path.Combine(cpuDir, "topology", "physical_package_id");
|
||||
var coreIdPath = Path.Combine(cpuDir, "topology", "core_id");
|
||||
|
||||
if (File.Exists(physicalIdPath) && File.Exists(coreIdPath))
|
||||
{
|
||||
var physId = File.ReadAllText(physicalIdPath).Trim();
|
||||
var coreId = File.ReadAllText(coreIdPath).Trim();
|
||||
physicalEntries.Add($"{physId}:{coreId}");
|
||||
}
|
||||
}
|
||||
|
||||
return physicalEntries.Count > 0 ? physicalEntries.Count : null;
|
||||
}
|
||||
|
||||
[GeneratedRegex(@"^cpu\d+$")]
|
||||
private static partial Regex CoreDirPattern();
|
||||
|
||||
private static string? GetArchitecture()
|
||||
{
|
||||
try
|
||||
{
|
||||
if (File.Exists("/proc/version"))
|
||||
{
|
||||
var version = File.ReadAllText("/proc/version");
|
||||
if (version.Contains("x86_64", StringComparison.OrdinalIgnoreCase) ||
|
||||
version.Contains("amd64", StringComparison.OrdinalIgnoreCase))
|
||||
return "x86_64";
|
||||
if (version.Contains("aarch64", StringComparison.OrdinalIgnoreCase) ||
|
||||
version.Contains("arm64", StringComparison.OrdinalIgnoreCase))
|
||||
return "aarch64";
|
||||
}
|
||||
|
||||
return RuntimeInformation.ProcessArchitecture switch
|
||||
{
|
||||
Architecture.X64 => "x86_64",
|
||||
Architecture.Arm64 => "aarch64",
|
||||
Architecture.Arm => "armv7l",
|
||||
_ => null
|
||||
};
|
||||
}
|
||||
catch
|
||||
{
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private static double? ParseFrequency(string? mhzStr)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(mhzStr)) return null;
|
||||
if (double.TryParse(mhzStr, System.Globalization.NumberStyles.Float,
|
||||
System.Globalization.CultureInfo.InvariantCulture, out var mhz))
|
||||
return Math.Round(mhz, 1);
|
||||
return null;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Filters CPU flags to only include key modern instruction set flags.
|
||||
/// </summary>
|
||||
private static string FilterKeyFlags(string allFlags)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(allFlags)) return "";
|
||||
|
||||
string[] keyFlags = ["avx", "avx2", "fma", "avx512f", "avx512bw", "avx512dq",
|
||||
"avx512vl", "sse4_1", "sse4_2", "ssse3", "aes", "pclmulqdq",
|
||||
"sha_ni", "sse2"];
|
||||
|
||||
var flags = allFlags.Split(' ', StringSplitOptions.RemoveEmptyEntries);
|
||||
var matched = flags.Where(f => keyFlags.Contains(f, StringComparer.OrdinalIgnoreCase));
|
||||
return string.Join(',', matched);
|
||||
}
|
||||
|
||||
private static long? GetCacheSize()
|
||||
{
|
||||
try
|
||||
{
|
||||
if (!OperatingSystem.IsLinux()) return null;
|
||||
|
||||
var cacheDir = "/sys/devices/system/cpu/cpu0/cache";
|
||||
if (!Directory.Exists(cacheDir)) return null;
|
||||
|
||||
long totalBytes = 0;
|
||||
foreach (var indexDir in Directory.GetDirectories(cacheDir))
|
||||
{
|
||||
var levelPath = Path.Combine(indexDir, "level");
|
||||
var sizePath = Path.Combine(indexDir, "size");
|
||||
var typePath = Path.Combine(indexDir, "type");
|
||||
|
||||
if (!File.Exists(levelPath) || !File.Exists(sizePath)) continue;
|
||||
|
||||
var level = File.ReadAllText(levelPath).Trim();
|
||||
var sizeStr = File.ReadAllText(sizePath).Trim();
|
||||
var type = File.Exists(typePath) ? File.ReadAllText(typePath).Trim() : "";
|
||||
|
||||
// Only sum unified or data caches per level to avoid double counting
|
||||
if (type == "Instruction" && level == "1") continue;
|
||||
|
||||
if (long.TryParse(sizeStr.Replace("K", "").Replace("k", ""), out var kb))
|
||||
totalBytes += kb * 1024;
|
||||
}
|
||||
|
||||
return totalBytes > 0 ? totalBytes : null;
|
||||
}
|
||||
catch
|
||||
{
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// CPU inventory data collected from the system.
|
||||
/// </summary>
|
||||
public sealed record CpuInfo
|
||||
{
|
||||
public string? Vendor { get; init; }
|
||||
public string? Model { get; init; }
|
||||
public string? Architecture { get; init; }
|
||||
public int? PhysicalCores { get; init; }
|
||||
public int? LogicalCores { get; init; }
|
||||
public int? ThreadsPerCore { get; init; }
|
||||
public double? FrequencyMhz { get; init; }
|
||||
public string? Flags { get; init; }
|
||||
public long? CacheBytes { get; init; }
|
||||
public long? ContainerCpuLimit { get; init; }
|
||||
}
|
||||
@@ -0,0 +1,160 @@
|
||||
namespace Heimdall.Agent.Services;
|
||||
|
||||
/// <summary>
|
||||
/// Enumerates disk mounts from /proc/mounts and detects disk type (SSD/HDD) from sysfs.
|
||||
/// </summary>
|
||||
public sealed class DiskInventoryProvider
|
||||
{
|
||||
private const string ProcMountsPath = "/proc/mounts";
|
||||
private const string Unknown = "Unknown";
|
||||
|
||||
public IReadOnlyList<DiskInfo> Collect()
|
||||
{
|
||||
var disks = new List<DiskInfo>();
|
||||
try
|
||||
{
|
||||
if (!OperatingSystem.IsLinux())
|
||||
return disks;
|
||||
|
||||
var mounts = ParseProcMounts();
|
||||
foreach (var mount in mounts)
|
||||
{
|
||||
var diskInfo = new DiskInfo
|
||||
{
|
||||
MountPoint = mount.MountPoint,
|
||||
FileSystem = mount.FileSystem,
|
||||
TotalBytes = GetDiskTotalBytes(mount.MountPoint),
|
||||
UsedBytes = GetDiskUsedBytes(mount.MountPoint),
|
||||
Type = DetectDiskType(mount.MountPoint)
|
||||
};
|
||||
|
||||
if (diskInfo.TotalBytes is > 0)
|
||||
disks.Add(diskInfo);
|
||||
}
|
||||
}
|
||||
catch { /* best effort */ }
|
||||
return disks;
|
||||
}
|
||||
|
||||
private static List<MountEntry> ParseProcMounts()
|
||||
{
|
||||
var mounts = new List<MountEntry>();
|
||||
try
|
||||
{
|
||||
if (!File.Exists(ProcMountsPath))
|
||||
return mounts;
|
||||
|
||||
HashSet<string> skipFs =
|
||||
[
|
||||
"proc", "sysfs", "devpts", "tmpfs", "cgroup", "cgroup2",
|
||||
"overlay", "squashfs", "devtmpfs", "securityfs", "pstore",
|
||||
"debugfs", "hugetlbfs", "mqueue", "fusectl", "configfs",
|
||||
"tracefs", "bpf", "rpc_pipefs", "nfsd", "autofs"
|
||||
];
|
||||
|
||||
foreach (var line in File.ReadLines(ProcMountsPath))
|
||||
{
|
||||
var parts = line.Split(' ', StringSplitOptions.RemoveEmptyEntries);
|
||||
if (parts.Length < 2) continue;
|
||||
|
||||
var device = parts[0];
|
||||
var mountPoint = parts[1];
|
||||
var fsType = parts[2];
|
||||
|
||||
if (skipFs.Contains(fsType, StringComparer.OrdinalIgnoreCase)) continue;
|
||||
if (!device.StartsWith("/dev/", StringComparison.Ordinal)) continue;
|
||||
|
||||
mounts.Add(new MountEntry
|
||||
{
|
||||
Device = device,
|
||||
MountPoint = mountPoint,
|
||||
FileSystem = fsType
|
||||
});
|
||||
}
|
||||
}
|
||||
catch { /* best effort */ }
|
||||
return mounts;
|
||||
}
|
||||
|
||||
private static long? GetDiskTotalBytes(string mountPoint)
|
||||
{
|
||||
try
|
||||
{
|
||||
var drive = new DriveInfo(mountPoint);
|
||||
if (drive.IsReady)
|
||||
return drive.TotalSize;
|
||||
}
|
||||
catch { /* best effort */ }
|
||||
return null;
|
||||
}
|
||||
|
||||
private static long? GetDiskUsedBytes(string mountPoint)
|
||||
{
|
||||
try
|
||||
{
|
||||
var drive = new DriveInfo(mountPoint);
|
||||
if (drive.IsReady)
|
||||
return drive.TotalSize - drive.AvailableFreeSpace;
|
||||
}
|
||||
catch { /* best effort */ }
|
||||
return null;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Detects disk type (SSD/HDD) by checking /sys/block/*/queue/rotation.
|
||||
/// rotation=0 means SSD, rotation=1 means HDD.
|
||||
/// </summary>
|
||||
private static string DetectDiskType(string mountPoint)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (!File.Exists(ProcMountsPath))
|
||||
return Unknown;
|
||||
|
||||
return FindDiskRotation(mountPoint) ?? Unknown;
|
||||
}
|
||||
catch
|
||||
{
|
||||
return Unknown;
|
||||
}
|
||||
}
|
||||
|
||||
private static string? FindDiskRotation(string mountPoint)
|
||||
{
|
||||
foreach (var line in File.ReadLines(ProcMountsPath))
|
||||
{
|
||||
var parts = line.Split(' ', StringSplitOptions.RemoveEmptyEntries);
|
||||
if (parts.Length < 2 || parts[1] != mountPoint || !parts[0].StartsWith("/dev/", StringComparison.Ordinal))
|
||||
continue;
|
||||
|
||||
var deviceName = Path.GetFileName(parts[0]);
|
||||
var rotationPath = $"/sys/block/{deviceName}/queue/rotation";
|
||||
|
||||
if (!File.Exists(rotationPath)) return null;
|
||||
|
||||
var rotation = File.ReadAllText(rotationPath).Trim();
|
||||
return rotation == "0" ? "SSD" : "HDD";
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
private sealed class MountEntry
|
||||
{
|
||||
public string Device { get; init; } = "";
|
||||
public string MountPoint { get; init; } = "";
|
||||
public string FileSystem { get; init; } = "";
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Disk inventory data for a single mount point.
|
||||
/// </summary>
|
||||
public sealed record DiskInfo
|
||||
{
|
||||
public string MountPoint { get; init; } = "";
|
||||
public string FileSystem { get; init; } = "";
|
||||
public long? TotalBytes { get; init; }
|
||||
public long? UsedBytes { get; init; }
|
||||
public string Type { get; init; } = "Unknown";
|
||||
}
|
||||
@@ -3,9 +3,7 @@ using System.Threading.Channels;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Microsoft.ML.OnnxRuntime;
|
||||
using Microsoft.ML.OnnxRuntime.Tensors;
|
||||
using SixLabors.ImageSharp;
|
||||
using SixLabors.ImageSharp.PixelFormats;
|
||||
using SixLabors.ImageSharp.Processing;
|
||||
using ImageMagick;
|
||||
|
||||
namespace Heimdall.Agent.Services;
|
||||
|
||||
@@ -94,7 +92,7 @@ public sealed class FrameAnalyzerService : IDisposable
|
||||
|
||||
// Determine number of classes from output shape [1, 4+C, 8400]
|
||||
var outputMeta = _session.OutputMetadata.Values.ToArray()[0];
|
||||
_numClasses = outputMeta.Dimensions.Length >= 2 ? (int)outputMeta.Dimensions[1] - 4 : 80;
|
||||
_numClasses = outputMeta.Dimensions.Length >= 2 ? outputMeta.Dimensions[1] - 4 : 80;
|
||||
|
||||
_logger.LogInformation(
|
||||
"FrameAnalyzer initialized with model: {ModelPath} (input: {InputName}, classes: {Classes})",
|
||||
@@ -204,10 +202,11 @@ public sealed class FrameAnalyzerService : IDisposable
|
||||
if (_session is null)
|
||||
return [];
|
||||
|
||||
using var image = Image.Load<Rgb24>(jpegData);
|
||||
using var image = new MagickImage(jpegData);
|
||||
image.Format = MagickFormat.Jpeg;
|
||||
|
||||
// Resize to model input size (640×640)
|
||||
image.Mutate(x => x.Resize(InputSize, InputSize));
|
||||
// Resize to model input size (640×640), ignoring aspect ratio (like ImageSharp Resize(640,640))
|
||||
image.Resize(new MagickGeometry(InputSize, InputSize) { IgnoreAspectRatio = true });
|
||||
|
||||
var inputTensor = PreprocessImage(image);
|
||||
|
||||
@@ -219,32 +218,29 @@ public sealed class FrameAnalyzerService : IDisposable
|
||||
using var results = _session.Run(inputs);
|
||||
var output = results[0].AsTensor<float>().ToArray();
|
||||
|
||||
return ParseYoloOutput(output, image.Width, image.Height);
|
||||
return ParseYoloOutput(output, (int)image.Width, (int)image.Height);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Convert ImageSharp image to a normalized NCHW tensor [1, 3, 640, 640].
|
||||
/// Convert Magick.NET image to a normalized NCHW tensor [1, 3, 640, 640].
|
||||
/// YOLOv8 expects RGB channels, each normalized to [0, 1].
|
||||
/// </summary>
|
||||
private static DenseTensor<float> PreprocessImage(Image<Rgb24> image)
|
||||
private static DenseTensor<float> PreprocessImage(MagickImage image)
|
||||
{
|
||||
var tensor = new DenseTensor<float>([1, 3, InputSize, InputSize]);
|
||||
var width = image.Width;
|
||||
// GetPixels().ToArray() returns contiguous interleaved RGB channel values
|
||||
// (Q16 build => ushort ranging 0..65535), row-major.
|
||||
var rgb = image.GetPixels()?.ToArray() ?? [];
|
||||
|
||||
image.ProcessPixelRows(accessor =>
|
||||
var idx = 0;
|
||||
for (var y = 0; y < InputSize; y++)
|
||||
{
|
||||
for (var y = 0; y < accessor.Height; y++)
|
||||
for (var x = 0; x < InputSize; x++)
|
||||
{
|
||||
var pixelRow = accessor.GetRowSpan(y);
|
||||
for (var x = 0; x < pixelRow.Length; x++)
|
||||
{
|
||||
var pixel = pixelRow[x];
|
||||
tensor[0, 0, y, x] = pixel.R / 255f;
|
||||
tensor[0, 1, y, x] = pixel.G / 255f;
|
||||
tensor[0, 2, y, x] = pixel.B / 255f;
|
||||
}
|
||||
for (var c = 0; c < 3; c++)
|
||||
tensor[0, c, y, x] = rgb[idx++] / 65535f;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
return tensor;
|
||||
}
|
||||
@@ -329,21 +325,30 @@ public sealed class FrameAnalyzerService : IDisposable
|
||||
Height: best.Y2 - best.Y1,
|
||||
ClassIndex: best.ClassIdx));
|
||||
|
||||
// Suppress overlapping boxes of the same class
|
||||
for (var j = i + 1; j < candidates.Count; j++)
|
||||
{
|
||||
if (suppressed[j]) continue;
|
||||
if (candidates[j].ClassIdx != best.ClassIdx) continue;
|
||||
|
||||
var iou = ComputeIoU(best, candidates[j]);
|
||||
if (iou >= NmsIouThreshold)
|
||||
suppressed[j] = true;
|
||||
}
|
||||
SuppressOverlapping(candidates, suppressed, i, best);
|
||||
}
|
||||
|
||||
return results.ToArray();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Mark overlapping candidates of the same class as suppressed.
|
||||
/// Extracted from ApplyNms to reduce cognitive complexity (S3776).
|
||||
/// </summary>
|
||||
private static void SuppressOverlapping(
|
||||
List<RawDetection> candidates, bool[] suppressed, int index, RawDetection best)
|
||||
{
|
||||
for (var j = index + 1; j < candidates.Count; j++)
|
||||
{
|
||||
if (suppressed[j]) continue;
|
||||
if (candidates[j].ClassIdx != best.ClassIdx) continue;
|
||||
|
||||
var iou = ComputeIoU(best, candidates[j]);
|
||||
if (iou >= NmsIouThreshold)
|
||||
suppressed[j] = true;
|
||||
}
|
||||
}
|
||||
|
||||
private static float ComputeIoU(RawDetection a, RawDetection b)
|
||||
{
|
||||
var interX1 = Math.Max(a.X1, b.X1);
|
||||
|
||||
@@ -0,0 +1,296 @@
|
||||
using System.Text.Json;
|
||||
using System.Text.RegularExpressions;
|
||||
|
||||
namespace Heimdall.Agent.Services;
|
||||
|
||||
/// <summary>
|
||||
/// Collects GPU inventory information via nvidia-smi, sysfs DRM, vainfo, and rocm-smi.
|
||||
/// Supports multi-GPU configurations.
|
||||
/// </summary>
|
||||
public sealed partial class GpuInventoryProvider
|
||||
{
|
||||
// SonarQube S1118: prevent instantiation — all members are static.
|
||||
private GpuInventoryProvider() { }
|
||||
|
||||
private const string DeviceDir = "device";
|
||||
|
||||
public static IReadOnlyList<GpuInfo> Collect()
|
||||
{
|
||||
var gpus = CollectNvidiaSmi();
|
||||
if (gpus.Count == 0)
|
||||
{
|
||||
gpus = CollectDrmDevices();
|
||||
}
|
||||
|
||||
EnrichWithVaapiInfo(gpus);
|
||||
|
||||
var rocmGpus = CollectRocmSmi();
|
||||
foreach (var rocm in rocmGpus.Where(rocm => !gpus.Any(g => g.Model?.Contains(rocm.Model ?? "", StringComparison.OrdinalIgnoreCase) == true)))
|
||||
{
|
||||
gpus.Add(rocm);
|
||||
}
|
||||
|
||||
return gpus;
|
||||
}
|
||||
|
||||
private static List<GpuInfo> CollectNvidiaSmi()
|
||||
{
|
||||
var gpus = new List<GpuInfo>();
|
||||
try
|
||||
{
|
||||
var output = CommandRunner.Run("nvidia-smi",
|
||||
"--query-gpu=index,name,driver_version,memory.total,memory.used,temperature.gpu,utilization.gpu --format=csv,noheader,nounits");
|
||||
if (string.IsNullOrWhiteSpace(output)) return gpus;
|
||||
|
||||
foreach (var line in output.Split('\n', StringSplitOptions.RemoveEmptyEntries))
|
||||
{
|
||||
var parts = line.Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries);
|
||||
if (parts.Length < 7) continue;
|
||||
|
||||
if (!long.TryParse(parts[3], out var vramMb)) vramMb = 0;
|
||||
double.TryParse(parts[5], System.Globalization.NumberStyles.Float,
|
||||
System.Globalization.CultureInfo.InvariantCulture, out var temp);
|
||||
double.TryParse(parts[6], System.Globalization.NumberStyles.Float,
|
||||
System.Globalization.CultureInfo.InvariantCulture, out var util);
|
||||
|
||||
gpus.Add(new GpuInfo
|
||||
{
|
||||
Vendor = "Nvidia",
|
||||
Model = parts[1],
|
||||
VramBytes = vramMb * 1024 * 1024,
|
||||
DriverVersion = parts[2],
|
||||
TemperatureCelsius = temp,
|
||||
UtilizationPercent = util,
|
||||
Backend = "Cuda",
|
||||
EncoderSupport = DetectNvidiaEncoder()
|
||||
});
|
||||
}
|
||||
}
|
||||
catch { /* best effort */ }
|
||||
return gpus;
|
||||
}
|
||||
|
||||
private static string? DetectNvidiaEncoder()
|
||||
{
|
||||
try
|
||||
{
|
||||
var output = CommandRunner.Run("nvidia-smi", "-q --format=csv,noheader");
|
||||
if (output is null) return null;
|
||||
|
||||
if (output.Contains("NVENC", StringComparison.OrdinalIgnoreCase))
|
||||
return output.Contains("NVJPG", StringComparison.OrdinalIgnoreCase) ? "NVENC+NVJPG" : "NVENC";
|
||||
return null;
|
||||
}
|
||||
catch { return null; }
|
||||
}
|
||||
|
||||
private static List<GpuInfo> CollectDrmDevices()
|
||||
{
|
||||
var gpus = new List<GpuInfo>();
|
||||
try
|
||||
{
|
||||
if (!OperatingSystem.IsLinux() || !Directory.Exists("/sys/class/drm"))
|
||||
return gpus;
|
||||
|
||||
foreach (var cardDir in Directory.GetDirectories("/sys/class/drm"))
|
||||
{
|
||||
var name = Path.GetFileName(cardDir);
|
||||
if (!name.StartsWith("card", StringComparison.Ordinal) || name.Contains('-'))
|
||||
continue;
|
||||
|
||||
var vendorPath = Path.Combine(cardDir, DeviceDir, "vendor");
|
||||
if (!File.Exists(vendorPath)) continue;
|
||||
|
||||
var vendor = File.ReadAllText(vendorPath).Trim();
|
||||
var model = GetDrmCardModel(cardDir);
|
||||
|
||||
gpus.Add(new GpuInfo
|
||||
{
|
||||
Vendor = MapVendor(vendor),
|
||||
Model = model,
|
||||
Backend = MapBackend(vendor)
|
||||
});
|
||||
}
|
||||
}
|
||||
catch { /* best effort */ }
|
||||
return gpus;
|
||||
}
|
||||
|
||||
private static string MapVendor(string vendor) => vendor switch
|
||||
{
|
||||
"0x10de" => "Nvidia",
|
||||
"0x1002" => "AMD",
|
||||
"0x8086" => "Intel",
|
||||
_ => vendor
|
||||
};
|
||||
|
||||
private static string MapBackend(string vendor) => vendor switch
|
||||
{
|
||||
"0x10de" => "Cuda",
|
||||
"0x1002" => "ROCm",
|
||||
"0x8086" => "VAAPI",
|
||||
_ => "Unknown"
|
||||
};
|
||||
|
||||
private static string? GetDrmCardModel(string cardDir)
|
||||
{
|
||||
try
|
||||
{
|
||||
var ueventPath = Path.Combine(cardDir, DeviceDir, "uevent");
|
||||
if (!File.Exists(ueventPath)) return null;
|
||||
|
||||
return ReadPciModelFromUevent(ueventPath);
|
||||
}
|
||||
catch { /* best effort */ }
|
||||
return null;
|
||||
}
|
||||
|
||||
private static string? ReadPciModelFromUevent(string ueventPath)
|
||||
{
|
||||
foreach (var line in File.ReadLines(ueventPath))
|
||||
{
|
||||
if (!line.StartsWith("PCI_ID=", StringComparison.OrdinalIgnoreCase)) continue;
|
||||
|
||||
var pciId = line["PCI_ID=".Length..].Trim();
|
||||
var output = CommandRunner.Run("lspci", $"-d {pciId} -mm");
|
||||
if (!string.IsNullOrWhiteSpace(output))
|
||||
{
|
||||
var modelName = ParsePciLspciOutput(output);
|
||||
if (!string.IsNullOrWhiteSpace(modelName))
|
||||
return modelName;
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
private static void EnrichWithVaapiInfo(List<GpuInfo> gpus)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (!OperatingSystem.IsLinux()) return;
|
||||
|
||||
var output = CommandRunner.Run("vainfo", "");
|
||||
if (string.IsNullOrWhiteSpace(output)) return;
|
||||
|
||||
if (!output.Contains("VAProfile", StringComparison.OrdinalIgnoreCase)) return;
|
||||
|
||||
// Reject software renderers (llvmpipe, swrast) — these are Mesa fallbacks, not real GPUs
|
||||
if (output.Contains("llvmpipe", StringComparison.OrdinalIgnoreCase) ||
|
||||
output.Contains("swrast", StringComparison.OrdinalIgnoreCase))
|
||||
return;
|
||||
|
||||
// If no GPU was found but vainfo works with a real driver, report it
|
||||
if (gpus.Count == 0)
|
||||
{
|
||||
gpus.Add(new GpuInfo
|
||||
{
|
||||
Vendor = "Intel",
|
||||
Model = "VAAPI Renderer",
|
||||
Backend = "VAAPI"
|
||||
});
|
||||
}
|
||||
}
|
||||
catch { /* best effort */ }
|
||||
}
|
||||
|
||||
private static List<GpuInfo> CollectRocmSmi()
|
||||
{
|
||||
var gpus = new List<GpuInfo>();
|
||||
try
|
||||
{
|
||||
var output = CommandRunner.Run("rocm-smi",
|
||||
"--showid --showtemp --showmemuse --showproductname --showuse --csv");
|
||||
if (string.IsNullOrWhiteSpace(output)) return gpus;
|
||||
|
||||
var lines = output.Split('\n', StringSplitOptions.RemoveEmptyEntries);
|
||||
if (lines.Length < 2) return gpus;
|
||||
|
||||
var headers = lines[0].Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries);
|
||||
|
||||
for (int i = 1; i < lines.Length; i++)
|
||||
{
|
||||
var values = lines[i].Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries);
|
||||
if (values.Length < 2) continue;
|
||||
|
||||
var gpuInfo = ParseRocmLine(headers, values);
|
||||
if (gpuInfo is not null) gpus.Add(gpuInfo);
|
||||
}
|
||||
}
|
||||
catch { /* best effort */ }
|
||||
return gpus;
|
||||
}
|
||||
|
||||
private static GpuInfo? ParseRocmLine(string[] headers, string[] values)
|
||||
{
|
||||
string? gpuModel = null;
|
||||
double? gpuTemp = null;
|
||||
double? gpuUtil = null;
|
||||
|
||||
for (int j = 0; j < Math.Min(headers.Length, values.Length); j++)
|
||||
{
|
||||
var header = headers[j].ToLowerInvariant();
|
||||
var value = values[j];
|
||||
|
||||
if (header.Contains("name") || header.Contains("card"))
|
||||
gpuModel = value;
|
||||
else if (header.Contains("temp"))
|
||||
gpuTemp = TryParseTemperature(value);
|
||||
else if (header.Contains("use"))
|
||||
gpuUtil = TryParsePercent(value);
|
||||
}
|
||||
|
||||
return gpuModel is not null ? new GpuInfo
|
||||
{
|
||||
Vendor = "AMD",
|
||||
Model = gpuModel,
|
||||
Backend = "ROCm",
|
||||
TemperatureCelsius = gpuTemp,
|
||||
UtilizationPercent = gpuUtil
|
||||
} : null;
|
||||
}
|
||||
|
||||
private static double? TryParseTemperature(string value)
|
||||
{
|
||||
double.TryParse(value.Replace("c", "").Replace("C", "").Trim(),
|
||||
System.Globalization.NumberStyles.Float,
|
||||
System.Globalization.CultureInfo.InvariantCulture, out var t);
|
||||
return t > 0 ? t : null;
|
||||
}
|
||||
|
||||
private static double? TryParsePercent(string value)
|
||||
{
|
||||
double.TryParse(value.Replace("%", "").Trim(),
|
||||
System.Globalization.NumberStyles.Float,
|
||||
System.Globalization.CultureInfo.InvariantCulture,
|
||||
out var util);
|
||||
return util;
|
||||
}
|
||||
|
||||
private static string? ParsePciLspciOutput(string output)
|
||||
{
|
||||
// lspci -mm output format: "vendor" "device" "class" "rev"
|
||||
var match = PciLspciPattern().Match(output);
|
||||
if (match.Success)
|
||||
return match.Groups[2].Value.Trim();
|
||||
return output.Split('\n', StringSplitOptions.RemoveEmptyEntries).FirstOrDefault()?.Trim().Trim('"');
|
||||
}
|
||||
|
||||
[GeneratedRegex(@"""([^""]+)""\s+""([^""]+)""")]
|
||||
private static partial Regex PciLspciPattern();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// GPU inventory data for a single GPU device.
|
||||
/// </summary>
|
||||
public sealed record GpuInfo
|
||||
{
|
||||
public string? Vendor { get; init; }
|
||||
public string? Model { get; init; }
|
||||
public long? VramBytes { get; init; }
|
||||
public string? DriverVersion { get; init; }
|
||||
public double? TemperatureCelsius { get; init; }
|
||||
public double? UtilizationPercent { get; init; }
|
||||
public string? Backend { get; init; }
|
||||
public string? EncoderSupport { get; init; }
|
||||
}
|
||||
@@ -0,0 +1,291 @@
|
||||
using System.Diagnostics;
|
||||
using System.Net.NetworkInformation;
|
||||
|
||||
namespace Heimdall.Agent.Services;
|
||||
|
||||
/// <summary>
|
||||
/// Collects host information: OS, kernel, uptime, network interfaces, and temperature.
|
||||
/// </summary>
|
||||
public sealed class HostInfoProvider
|
||||
{
|
||||
public HostInfo Collect()
|
||||
{
|
||||
return new HostInfo
|
||||
{
|
||||
OsName = GetOsName(),
|
||||
KernelVersion = GetKernelVersion(),
|
||||
Arch = GetArchitecture(),
|
||||
UptimeSeconds = ProcFs.GetMachineUptime(),
|
||||
NetworkInterfaces = CollectNetworkInterfaces(),
|
||||
Temperature = CollectTemperature()
|
||||
};
|
||||
}
|
||||
|
||||
private static string? GetOsName()
|
||||
{
|
||||
try
|
||||
{
|
||||
if (OperatingSystem.IsLinux())
|
||||
return GetLinuxOsName();
|
||||
if (OperatingSystem.IsWindows())
|
||||
return Environment.OSVersion.VersionString;
|
||||
if (OperatingSystem.IsMacOS())
|
||||
return GetMacOsName();
|
||||
}
|
||||
catch { /* best effort */ }
|
||||
return null;
|
||||
}
|
||||
|
||||
private static string? GetLinuxOsName()
|
||||
{
|
||||
var prettyName = ReadPrettyNameFromOsRelease();
|
||||
if (prettyName is not null)
|
||||
return prettyName;
|
||||
|
||||
var output = CommandRunner.Run("uname", "-sro");
|
||||
return !string.IsNullOrWhiteSpace(output) ? output.Trim() : null;
|
||||
}
|
||||
|
||||
private static string? ReadPrettyNameFromOsRelease()
|
||||
{
|
||||
if (!File.Exists("/etc/os-release")) return null;
|
||||
return File.ReadLines("/etc/os-release")
|
||||
.Where(line => line.StartsWith("PRETTY_NAME=", StringComparison.OrdinalIgnoreCase))
|
||||
.Select(line => line["PRETTY_NAME=".Length..].Trim().Trim('"'))
|
||||
.FirstOrDefault();
|
||||
}
|
||||
|
||||
private static string? GetMacOsName()
|
||||
{
|
||||
var output = CommandRunner.Run("sw_vers", "-productVersion");
|
||||
return !string.IsNullOrWhiteSpace(output) ? $"macOS {output.Trim()}" : null;
|
||||
}
|
||||
|
||||
private static string? GetKernelVersion()
|
||||
{
|
||||
try
|
||||
{
|
||||
if (OperatingSystem.IsLinux() || OperatingSystem.IsMacOS())
|
||||
{
|
||||
var output = CommandRunner.Run("uname", "-r");
|
||||
if (!string.IsNullOrWhiteSpace(output))
|
||||
return output.Trim();
|
||||
}
|
||||
else if (OperatingSystem.IsWindows())
|
||||
{
|
||||
return Environment.OSVersion.VersionString;
|
||||
}
|
||||
}
|
||||
catch { /* best effort */ }
|
||||
return null;
|
||||
}
|
||||
|
||||
private static string? GetArchitecture()
|
||||
{
|
||||
try
|
||||
{
|
||||
return System.Runtime.InteropServices.RuntimeInformation.ProcessArchitecture switch
|
||||
{
|
||||
System.Runtime.InteropServices.Architecture.X64 => "x86_64",
|
||||
System.Runtime.InteropServices.Architecture.Arm64 => "aarch64",
|
||||
System.Runtime.InteropServices.Architecture.Arm => "armv7l",
|
||||
_ => System.Runtime.InteropServices.RuntimeInformation.ProcessArchitecture.ToString()
|
||||
};
|
||||
}
|
||||
catch { return null; }
|
||||
}
|
||||
|
||||
private static List<NetworkInterfaceInfo> CollectNetworkInterfaces()
|
||||
{
|
||||
var interfaces = new List<NetworkInterfaceInfo>();
|
||||
try
|
||||
{
|
||||
if (OperatingSystem.IsLinux() && File.Exists("/proc/net/dev"))
|
||||
{
|
||||
var lines = File.ReadAllLines("/proc/net/dev");
|
||||
// Skip header lines
|
||||
foreach (var line in lines.Skip(2))
|
||||
{
|
||||
var trimmed = line.Trim();
|
||||
var colonIdx = trimmed.IndexOf(':');
|
||||
if (colonIdx <= 0) continue;
|
||||
|
||||
var name = trimmed[..colonIdx].Trim();
|
||||
if (name == "lo") continue; // skip loopback
|
||||
|
||||
interfaces.Add(new NetworkInterfaceInfo
|
||||
{
|
||||
Name = name,
|
||||
IpAddress = GetInterfaceIp(name),
|
||||
MacAddress = GetInterfaceMac(name),
|
||||
SpeedMbps = GetInterfaceSpeed(name)
|
||||
});
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
// Fallback: use NetworkInterface API
|
||||
CollectFallbackInterfaces(interfaces);
|
||||
}
|
||||
}
|
||||
catch { /* best effort */ }
|
||||
return interfaces;
|
||||
}
|
||||
|
||||
private static void CollectFallbackInterfaces(List<NetworkInterfaceInfo> interfaces)
|
||||
{
|
||||
foreach (var ni in NetworkInterface.GetAllNetworkInterfaces())
|
||||
{
|
||||
if (ni.OperationalStatus != OperationalStatus.Up) continue;
|
||||
if (ni.NetworkInterfaceType == NetworkInterfaceType.Loopback) continue;
|
||||
|
||||
var ipProps = ni.GetIPProperties();
|
||||
var ip = ipProps.UnicastAddresses
|
||||
.FirstOrDefault(a => a.Address.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)
|
||||
?.Address.ToString();
|
||||
|
||||
var mac = ni.GetPhysicalAddress().ToString();
|
||||
if (!string.IsNullOrEmpty(mac) && mac.Length == 12)
|
||||
mac = $"{mac[0..2]}:{mac[2..4]}:{mac[4..6]}:{mac[6..8]}:{mac[8..10]}:{mac[10..12]}";
|
||||
|
||||
interfaces.Add(new NetworkInterfaceInfo
|
||||
{
|
||||
Name = ni.Name,
|
||||
IpAddress = ip,
|
||||
MacAddress = string.IsNullOrEmpty(mac) ? null : mac,
|
||||
SpeedMbps = ni.Speed > 0 ? (long?)ni.Speed / 1_000_000 : null
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
private static string? GetInterfaceIp(string interfaceName)
|
||||
{
|
||||
try
|
||||
{
|
||||
var output = CommandRunner.Run("ip", $"-4 addr show {interfaceName}");
|
||||
if (string.IsNullOrWhiteSpace(output)) return null;
|
||||
|
||||
foreach (var line in output.Split('\n'))
|
||||
{
|
||||
var trimmed = line.Trim();
|
||||
if (trimmed.StartsWith("inet ", StringComparison.Ordinal))
|
||||
{
|
||||
var parts = trimmed.Split(' ', StringSplitOptions.RemoveEmptyEntries);
|
||||
if (parts.Length >= 2)
|
||||
{
|
||||
var addr = parts[1];
|
||||
var slashIdx = addr.IndexOf('/');
|
||||
return slashIdx > 0 ? addr[..slashIdx] : addr;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
catch { /* best effort */ }
|
||||
return null;
|
||||
}
|
||||
|
||||
private static string? GetInterfaceMac(string interfaceName)
|
||||
{
|
||||
try
|
||||
{
|
||||
var path = $"/sys/class/net/{interfaceName}/address";
|
||||
if (File.Exists(path))
|
||||
return File.ReadAllText(path).Trim();
|
||||
}
|
||||
catch { /* best effort */ }
|
||||
return null;
|
||||
}
|
||||
|
||||
private static long? GetInterfaceSpeed(string interfaceName)
|
||||
{
|
||||
try
|
||||
{
|
||||
var path = $"/sys/class/net/{interfaceName}/speed";
|
||||
if (File.Exists(path))
|
||||
{
|
||||
var content = File.ReadAllText(path).Trim();
|
||||
if (long.TryParse(content, out var speed) && speed > 0)
|
||||
return speed;
|
||||
}
|
||||
}
|
||||
catch { /* best effort */ }
|
||||
return null;
|
||||
}
|
||||
|
||||
private static List<TemperatureInfo> CollectTemperature()
|
||||
{
|
||||
var temps = new List<TemperatureInfo>();
|
||||
try
|
||||
{
|
||||
if (!OperatingSystem.IsLinux()) return temps;
|
||||
|
||||
var thermalDir = "/sys/class/thermal";
|
||||
if (!Directory.Exists(thermalDir)) return temps;
|
||||
|
||||
foreach (var zoneDir in Directory.GetDirectories(thermalDir))
|
||||
{
|
||||
if (!Path.GetFileName(zoneDir).StartsWith("thermal_zone", StringComparison.Ordinal))
|
||||
continue;
|
||||
|
||||
var tempPath = Path.Combine(zoneDir, "temp");
|
||||
if (!File.Exists(tempPath)) continue;
|
||||
|
||||
var typePath = Path.Combine(zoneDir, "type");
|
||||
var zoneName = File.Exists(typePath) ? File.ReadAllText(typePath).Trim() : Path.GetFileName(zoneDir);
|
||||
var tempStr = File.ReadAllText(tempPath).Trim();
|
||||
|
||||
if (TryParseMillidegrees(tempStr, out var tempCelsius) && tempCelsius is > -40 and < 200)
|
||||
{
|
||||
temps.Add(new TemperatureInfo
|
||||
{
|
||||
Zone = zoneName,
|
||||
TemperatureCelsius = Math.Round(tempCelsius, 1)
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
catch { /* best effort */ }
|
||||
return temps;
|
||||
}
|
||||
|
||||
private static bool TryParseMillidegrees(string tempStr, out double celsius)
|
||||
{
|
||||
celsius = 0;
|
||||
if (!long.TryParse(tempStr, out var millidegrees)) return false;
|
||||
celsius = millidegrees / 1000.0;
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Host information data.
|
||||
/// </summary>
|
||||
public sealed record HostInfo
|
||||
{
|
||||
public string? OsName { get; init; }
|
||||
public string? KernelVersion { get; init; }
|
||||
public string? Arch { get; init; }
|
||||
public long? UptimeSeconds { get; init; }
|
||||
public List<NetworkInterfaceInfo> NetworkInterfaces { get; init; } = [];
|
||||
public List<TemperatureInfo> Temperature { get; init; } = [];
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Network interface information.
|
||||
/// </summary>
|
||||
public sealed record NetworkInterfaceInfo
|
||||
{
|
||||
public string Name { get; init; } = "";
|
||||
public string? IpAddress { get; init; }
|
||||
public string? MacAddress { get; init; }
|
||||
public long? SpeedMbps { get; init; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Thermal zone temperature information.
|
||||
/// </summary>
|
||||
public sealed record TemperatureInfo
|
||||
{
|
||||
public string Zone { get; init; } = "";
|
||||
public double TemperatureCelsius { get; init; }
|
||||
}
|
||||
@@ -110,7 +110,7 @@ public class LogUploadService : BackgroundService
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogDebug("Log upload failed (network): {Error}; {Count} entries re-queued", ex.Message, entries.Count);
|
||||
_logger.LogDebug(ex, "Log upload failed (network): {Count} entries re-queued", entries.Count);
|
||||
_buffer.Requeue(entries);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,39 @@
|
||||
namespace Heimdall.Agent.Services;
|
||||
|
||||
/// <summary>
|
||||
/// Shared memory info reader from /proc/meminfo. Eliminates duplication
|
||||
/// in <see cref="AgentRegistrationService"/> (GetMemoryTotal, GetMemoryAvailable,
|
||||
/// GetSwapTotal, GetSwapFree are all the same pattern).
|
||||
/// </summary>
|
||||
internal static class MemoryReader
|
||||
{
|
||||
private const string ProcMeminfoPath = "/proc/meminfo";
|
||||
|
||||
/// <summary>
|
||||
/// Reads a named field from /proc/meminfo and returns its value in bytes.
|
||||
/// Returns null if the field is not found or parsing fails.
|
||||
/// </summary>
|
||||
public static long? ReadFieldBytes(string fieldName)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (!OperatingSystem.IsLinux()) return null;
|
||||
|
||||
var line = File.ReadLines(ProcMeminfoPath)
|
||||
.FirstOrDefault(l => l.StartsWith($"{fieldName}:", StringComparison.Ordinal));
|
||||
if (line is not null)
|
||||
{
|
||||
var parts = line.Split(' ', StringSplitOptions.RemoveEmptyEntries);
|
||||
if (parts.Length >= 2 && long.TryParse(parts[1], out var kb))
|
||||
return kb * 1024;
|
||||
}
|
||||
}
|
||||
catch { /* best effort */ }
|
||||
return null;
|
||||
}
|
||||
|
||||
public static long? GetMemoryTotal() => ReadFieldBytes("MemTotal");
|
||||
public static long? GetMemoryAvailable() => ReadFieldBytes("MemAvailable");
|
||||
public static long? GetSwapTotal() => ReadFieldBytes("SwapTotal");
|
||||
public static long? GetSwapFree() => ReadFieldBytes("SwapFree");
|
||||
}
|
||||
@@ -1484,7 +1484,7 @@ public sealed class NetworkCameraScanner
|
||||
|
||||
using var ms = new MemoryStream();
|
||||
var copyTask = process.StandardOutput.BaseStream.CopyToAsync(ms, cts.Token);
|
||||
var stderrTask = process.StandardError.ReadToEndAsync(cts.Token);
|
||||
_ = process.StandardError.ReadToEndAsync(cts.Token); // drain stderr to prevent deadlock
|
||||
|
||||
var completed = await Task.WhenAny(copyTask, Task.Delay(ScreenshotTimeout, ct)).ConfigureAwait(false);
|
||||
if (completed != copyTask)
|
||||
|
||||
@@ -0,0 +1,33 @@
|
||||
namespace Heimdall.Agent.Services;
|
||||
|
||||
/// <summary>
|
||||
/// Shared utilities for reading Linux proc filesystem values.
|
||||
/// </summary>
|
||||
internal static class ProcFs
|
||||
{
|
||||
/// <summary>
|
||||
/// Gets machine uptime in seconds from /proc/uptime.
|
||||
/// </summary>
|
||||
public static long? GetMachineUptime()
|
||||
{
|
||||
try
|
||||
{
|
||||
if (OperatingSystem.IsLinux() && File.Exists("/proc/uptime"))
|
||||
{
|
||||
var content = File.ReadAllText("/proc/uptime").Trim();
|
||||
var spaceIdx = content.IndexOf(' ');
|
||||
if (spaceIdx > 0)
|
||||
{
|
||||
var uptimeStr = content[..spaceIdx];
|
||||
if (double.TryParse(uptimeStr, System.Globalization.NumberStyles.Float,
|
||||
System.Globalization.CultureInfo.InvariantCulture, out var uptime))
|
||||
{
|
||||
return (long)uptime;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
catch { /* best effort */ }
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -22,16 +22,12 @@ public sealed class RuntimeLogLevel
|
||||
{
|
||||
private readonly ILoggerFactory _loggerFactory;
|
||||
private readonly LoggerFilterOptions _filterOptions;
|
||||
private readonly IReadOnlyList<LoggerFilterRule> _originalRules;
|
||||
private LoggerFilterRule? _currentRule;
|
||||
|
||||
public RuntimeLogLevel(ILoggerFactory loggerFactory, IOptions<LoggerFilterOptions> filterOptions)
|
||||
{
|
||||
_loggerFactory = loggerFactory;
|
||||
_filterOptions = filterOptions.Value;
|
||||
// Snapshot the rules configured at startup (appsettings "Logging:LogLevel")
|
||||
// so they can be restored after the live global rule is removed.
|
||||
_originalRules = _filterOptions.Rules.ToList();
|
||||
}
|
||||
|
||||
/// <summary>Current minimum level applied to all loggers.</summary>
|
||||
|
||||
@@ -113,14 +113,14 @@ public sealed class SnapshotPipelineService : BackgroundService
|
||||
.ToList();
|
||||
|
||||
// Stop streams for cameras no longer assigned/disabled.
|
||||
foreach (var activeId in _streams.ActiveCameraIds)
|
||||
var toStop = _streams.ActiveCameraIds
|
||||
.Where(activeId => !desired.Any(c => c.CameraId == activeId))
|
||||
.ToList();
|
||||
foreach (var activeId in toStop)
|
||||
{
|
||||
if (!desired.Any(c => c.CameraId == activeId))
|
||||
{
|
||||
await _streams.StopStreamAsync(activeId);
|
||||
// Camera removed/disabled → Disabled status at the Central.
|
||||
await _statusReporter.ReportAsync(activeId, "Disabled", ct);
|
||||
}
|
||||
await _streams.StopStreamAsync(activeId);
|
||||
// Camera removed/disabled → Disabled status at the Central.
|
||||
await _statusReporter.ReportAsync(activeId, "Disabled", ct);
|
||||
}
|
||||
|
||||
// Start streams for newly assigned cameras.
|
||||
|
||||
@@ -24,7 +24,8 @@ public sealed class SystemMetricsProvider
|
||||
MemoryUsageBytes = Process.GetCurrentProcess().WorkingSet64,
|
||||
TotalMemoryBytes = GetTotalMemory(),
|
||||
DiskUsagePercent = GetDiskUsage(),
|
||||
UptimeSeconds = (long)(DateTime.UtcNow - ProcessStart).TotalSeconds
|
||||
UptimeSeconds = (long)(DateTime.UtcNow - ProcessStart).TotalSeconds,
|
||||
MachineUptimeSeconds = ProcFs.GetMachineUptime()
|
||||
};
|
||||
}
|
||||
|
||||
@@ -151,6 +152,8 @@ public sealed class SystemMetricsProvider
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
||||
public sealed record SystemMetrics
|
||||
@@ -160,6 +163,7 @@ public sealed record SystemMetrics
|
||||
public long? TotalMemoryBytes { get; init; }
|
||||
public double? DiskUsagePercent { get; init; }
|
||||
public long? UptimeSeconds { get; init; }
|
||||
public long? MachineUptimeSeconds { get; init; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -182,8 +186,9 @@ internal static class SystemInfo
|
||||
});
|
||||
|
||||
if (proc is null) return 0;
|
||||
var output = proc.StandardOutput.ReadToEnd();
|
||||
var outputTask = proc.StandardOutput.ReadToEndAsync();
|
||||
proc.WaitForExit(1000);
|
||||
var output = outputTask.IsCompletedSuccessfully ? outputTask.Result : null;
|
||||
return long.TryParse(output?.Trim(), out var mem) ? mem : 0;
|
||||
}
|
||||
catch
|
||||
|
||||
Reference in new issue
Block a user