## 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
332 lines
11 KiB
C#
332 lines
11 KiB
C#
using System.Net;
|
|
using System.Text.Json;
|
|
using Heimdall.Agent.Services;
|
|
using Microsoft.AspNetCore.DataProtection;
|
|
using Microsoft.Extensions.Logging.Abstractions;
|
|
using Microsoft.Extensions.Options;
|
|
using NSubstitute;
|
|
|
|
namespace Heimdall.Agent.Tests;
|
|
|
|
public class AgentRegistrationServiceTests : IDisposable
|
|
{
|
|
/// <summary>Shared provider so the file written by the fixture can be read
|
|
/// back by the singleton state (same Data Protection key).</summary>
|
|
private static readonly EphemeralDataProtectionProvider Provider = new();
|
|
|
|
private readonly AgentOptions _options = new()
|
|
{
|
|
CentralUrl = "http://heimdall.test",
|
|
SiteToken = "test-token",
|
|
AgentName = "test-agent",
|
|
HeartbeatIntervalSeconds = 1,
|
|
RegistrationMaxRetries = 3,
|
|
Version = "1.0.0"
|
|
};
|
|
|
|
private readonly TempDir _tmp = new();
|
|
private readonly AgentState _state = new(Provider.CreateProtector(AgentState.KeyProtectionPurpose));
|
|
private readonly SystemMetricsProvider _metrics = new();
|
|
|
|
public AgentRegistrationServiceTests()
|
|
{
|
|
_state.ConfigureStateDirectory(_tmp.Path);
|
|
}
|
|
|
|
[Fact]
|
|
public async Task Registration_Success_SetsAgentIdAndApiKey()
|
|
{
|
|
var handler = CreateOkHandler();
|
|
var factory = CreateHttpClientFactory(handler);
|
|
var service = CreateService(factory);
|
|
|
|
await service.StartAsync(CancellationToken.None);
|
|
await Task.Delay(500);
|
|
await service.StopAsync(CancellationToken.None);
|
|
|
|
_state.AgentId.ShouldNotBe(Guid.Empty);
|
|
_state.ApiKey.ShouldBe("sk_test_abc123");
|
|
_state.ApiKeyPrefix.ShouldBe("sk_test");
|
|
}
|
|
|
|
[Fact]
|
|
public async Task Registration_WithRetry_EventuallySucceeds()
|
|
{
|
|
var attempt = 0;
|
|
var handler = new MockHttpMessageHandler(req =>
|
|
{
|
|
attempt++;
|
|
if (attempt < 3)
|
|
return new HttpResponseMessage(HttpStatusCode.ServiceUnavailable);
|
|
|
|
return CreateRegistrationResponse();
|
|
});
|
|
|
|
var factory = CreateHttpClientFactory(handler);
|
|
var service = CreateService(factory);
|
|
|
|
await service.StartAsync(CancellationToken.None);
|
|
// Retry backoff: 2^1=2s, 2^2=4s → ~7s for 3 attempts.
|
|
// Poll instead of a fixed delay: under parallel CI load the
|
|
// background service can be delayed beyond 8s (flaky #2228).
|
|
var deadline = DateTime.UtcNow.AddSeconds(25);
|
|
while (DateTime.UtcNow < deadline && _state.AgentId == Guid.Empty)
|
|
await Task.Delay(250);
|
|
await service.StopAsync(CancellationToken.None);
|
|
|
|
_state.AgentId.ShouldNotBe(Guid.Empty);
|
|
}
|
|
|
|
[Fact]
|
|
public async Task Registration_AllRetriesFail_LogsError()
|
|
{
|
|
var handler = new MockHttpMessageHandler(_ =>
|
|
new HttpResponseMessage(HttpStatusCode.ServiceUnavailable));
|
|
|
|
var factory = CreateHttpClientFactory(handler);
|
|
var service = CreateService(factory);
|
|
|
|
// StartAsync does not throw — the exception is caught by BackgroundService.
|
|
// Verify the service enters a faulted state.
|
|
await service.StartAsync(CancellationToken.None);
|
|
|
|
// Wait for all retries to exhaust (backoff 2+4+8s under parallel CI load).
|
|
// Poll instead of a fixed delay to avoid flaky timing.
|
|
var deadline = DateTime.UtcNow.AddSeconds(30);
|
|
while (DateTime.UtcNow < deadline && _state.ApiKey is null)
|
|
await Task.Delay(250);
|
|
await service.StopAsync(CancellationToken.None);
|
|
|
|
// AgentId should remain empty because registration never succeeded
|
|
_state.AgentId.ShouldBe(Guid.Empty);
|
|
_state.ApiKey.ShouldBeNull();
|
|
}
|
|
|
|
[Fact]
|
|
public async Task ExistingIdentity_SkipsRegistration()
|
|
{
|
|
// Pre-populate the state file so LoadAsync() finds an identity
|
|
var saved = new AgentState(Provider.CreateProtector(AgentState.KeyProtectionPurpose));
|
|
saved.ConfigureStateDirectory(_tmp.Path);
|
|
saved.AgentId = Guid.NewGuid();
|
|
saved.ApiKey = "existing-key";
|
|
saved.ApiKeyPrefix = "existing";
|
|
await saved.SaveAsync();
|
|
|
|
// Also set the DI singleton state with same values
|
|
_state.AgentId = saved.AgentId;
|
|
_state.ApiKey = saved.ApiKey;
|
|
_state.ApiKeyPrefix = saved.ApiKeyPrefix;
|
|
|
|
var registrationCalled = false;
|
|
var handler = new MockHttpMessageHandler(req =>
|
|
{
|
|
if (req.RequestUri?.ToString().Contains("/register") == true)
|
|
registrationCalled = true;
|
|
|
|
return new HttpResponseMessage(HttpStatusCode.OK)
|
|
{
|
|
Content = new StringContent(JsonSerializer.Serialize(new
|
|
{
|
|
agentId = Guid.NewGuid(),
|
|
apiKey = "new-key",
|
|
apiKeyPrefix = "new"
|
|
}))
|
|
};
|
|
});
|
|
|
|
var factory = CreateHttpClientFactory(handler);
|
|
var service = CreateService(factory);
|
|
|
|
await service.StartAsync(CancellationToken.None);
|
|
await Task.Delay(500);
|
|
await service.StopAsync(CancellationToken.None);
|
|
|
|
registrationCalled.ShouldBeFalse();
|
|
_state.ApiKey.ShouldBe("existing-key"); // unchanged
|
|
}
|
|
|
|
[Fact]
|
|
public async Task StopAsync_SendsOfflineHeartbeat()
|
|
{
|
|
HttpResponseMessage? lastHeartbeat = null;
|
|
var handler = new MockHttpMessageHandler(req =>
|
|
{
|
|
if (req.RequestUri?.ToString().Contains("/register") == true)
|
|
return CreateRegistrationResponse();
|
|
|
|
if (req.RequestUri?.ToString().Contains("/heartbeat") == true)
|
|
{
|
|
lastHeartbeat = new HttpResponseMessage(HttpStatusCode.OK);
|
|
return lastHeartbeat;
|
|
}
|
|
|
|
return new HttpResponseMessage(HttpStatusCode.OK);
|
|
});
|
|
|
|
var factory = CreateHttpClientFactory(handler);
|
|
var service = CreateService(factory);
|
|
|
|
await service.StartAsync(CancellationToken.None);
|
|
await Task.Delay(500);
|
|
|
|
await service.StopAsync(CancellationToken.None);
|
|
|
|
// Agent must be registered after the flow
|
|
_state.AgentId.ShouldNotBe(Guid.Empty);
|
|
}
|
|
|
|
[Fact]
|
|
public async Task Heartbeat_UsesXApiKeyHeader_NotBearer()
|
|
{
|
|
string? xApiKey = null;
|
|
string? authorization = null;
|
|
var handler = new MockHttpMessageHandler(req =>
|
|
{
|
|
if (req.RequestUri?.ToString().Contains("/register") == true)
|
|
return CreateRegistrationResponse();
|
|
|
|
if (req.RequestUri?.ToString().Contains("/heartbeat") == true)
|
|
{
|
|
xApiKey = req.Headers.TryGetValues("X-API-Key", out var values)
|
|
? values.FirstOrDefault()
|
|
: null;
|
|
authorization = req.Headers.Authorization?.ToString();
|
|
return new HttpResponseMessage(HttpStatusCode.OK);
|
|
}
|
|
|
|
return new HttpResponseMessage(HttpStatusCode.OK);
|
|
});
|
|
|
|
var factory = CreateHttpClientFactory(handler);
|
|
var service = CreateService(factory);
|
|
|
|
await service.StartAsync(CancellationToken.None);
|
|
// Registration first, then heartbeat (interval 1s). Poll for the
|
|
// heartbeat instead of a fixed 500ms delay (flaky under CI load).
|
|
var deadline = DateTime.UtcNow.AddSeconds(10);
|
|
while (DateTime.UtcNow < deadline && xApiKey is null)
|
|
await Task.Delay(100);
|
|
await service.StopAsync(CancellationToken.None);
|
|
|
|
xApiKey.ShouldNotBeNull(); // API key sent via X-API-Key header
|
|
authorization.ShouldBeNull(); // never as Bearer
|
|
}
|
|
|
|
[Fact]
|
|
public async Task ExistingIdentity_Heartbeat_UsesXApiKeyHeader()
|
|
{
|
|
// Pre-populate the state file so LoadAsync() finds an identity
|
|
var saved = new AgentState(Provider.CreateProtector(AgentState.KeyProtectionPurpose));
|
|
saved.ConfigureStateDirectory(_tmp.Path);
|
|
saved.AgentId = Guid.NewGuid();
|
|
saved.ApiKey = "existing-key";
|
|
saved.ApiKeyPrefix = "existing";
|
|
await saved.SaveAsync();
|
|
|
|
_state.AgentId = saved.AgentId;
|
|
_state.ApiKey = saved.ApiKey;
|
|
_state.ApiKeyPrefix = saved.ApiKeyPrefix;
|
|
|
|
string? xApiKey = null;
|
|
string? authorization = null;
|
|
var handler = new MockHttpMessageHandler(req =>
|
|
{
|
|
if (req.RequestUri?.ToString().Contains("/heartbeat") == true)
|
|
{
|
|
xApiKey = req.Headers.TryGetValues("X-API-Key", out var values)
|
|
? values.FirstOrDefault()
|
|
: null;
|
|
authorization = req.Headers.Authorization?.ToString();
|
|
}
|
|
return new HttpResponseMessage(HttpStatusCode.OK);
|
|
});
|
|
|
|
var factory = CreateHttpClientFactory(handler);
|
|
var service = CreateService(factory);
|
|
|
|
await service.StartAsync(CancellationToken.None);
|
|
await Task.Delay(500);
|
|
|
|
await service.StopAsync(CancellationToken.None);
|
|
|
|
xApiKey.ShouldBe("existing-key");
|
|
authorization.ShouldBeNull();
|
|
}
|
|
|
|
public void Dispose()
|
|
{
|
|
_tmp.Dispose();
|
|
GC.SuppressFinalize(this);
|
|
}
|
|
|
|
// --- Helpers ---
|
|
|
|
private AgentRegistrationService CreateService(
|
|
IHttpClientFactory factory,
|
|
AgentState? state = null)
|
|
{
|
|
state ??= _state;
|
|
var providers = new InventoryProviders(
|
|
new CpuInfoProvider(),
|
|
new DiskInventoryProvider(),
|
|
new HostInfoProvider(),
|
|
new ContainerInfoProvider());
|
|
return new AgentRegistrationService(
|
|
factory,
|
|
state,
|
|
Options.Create(_options),
|
|
_metrics,
|
|
providers,
|
|
new Logging.LogBufferService(),
|
|
NullLogger<AgentRegistrationService>.Instance);
|
|
}
|
|
|
|
private static IHttpClientFactory CreateHttpClientFactory(
|
|
MockHttpMessageHandler handler)
|
|
{
|
|
var client = new HttpClient(handler) { BaseAddress = new Uri("http://heimdall.test") };
|
|
var factory = Substitute.For<IHttpClientFactory>();
|
|
factory.CreateClient("Central").Returns(client);
|
|
factory.CreateClient("IpResolver").Returns(client);
|
|
return factory;
|
|
}
|
|
|
|
private static MockHttpMessageHandler CreateOkHandler()
|
|
{
|
|
return new MockHttpMessageHandler(req =>
|
|
{
|
|
if (req.RequestUri?.ToString().Contains("/register") == true)
|
|
return CreateRegistrationResponse();
|
|
|
|
return new HttpResponseMessage(HttpStatusCode.OK);
|
|
});
|
|
}
|
|
|
|
private static HttpResponseMessage CreateRegistrationResponse()
|
|
{
|
|
return new HttpResponseMessage(HttpStatusCode.OK)
|
|
{
|
|
Content = new StringContent(JsonSerializer.Serialize(new
|
|
{
|
|
agentId = Guid.NewGuid(),
|
|
apiKey = "sk_test_abc123",
|
|
apiKeyPrefix = "sk_test"
|
|
}))
|
|
};
|
|
}
|
|
}
|
|
|
|
/// <summary>
|
|
/// Mock HTTP handler that returns predefined responses per request.
|
|
/// </summary>
|
|
public class MockHttpMessageHandler(Func<HttpRequestMessage, HttpResponseMessage> handler)
|
|
: HttpMessageHandler
|
|
{
|
|
protected override Task<HttpResponseMessage> SendAsync(
|
|
HttpRequestMessage request, CancellationToken cancellationToken)
|
|
{
|
|
return Task.FromResult(handler(request));
|
|
}
|
|
}
|