Files
Heimdall/src/Heimdall.Agent/Services/AgentRegistrationService.cs
T
arnaud.dartois 1b512ab040
Heimdall Gitea / Detect CI scope (push) Successful in 12s
Heimdall Gitea / Build and tests (push) Successful in 25m48s
Heimdall Gitea / Publish versioned release (push) Skipped
Heimdall Gitea / Build and scan agent image (push) Successful in 10m1s
Heimdall Gitea / Build and scan server image (push) Successful in 10m4s
Heimdall Gitea / Publish Docker Hub latest tags (push) Successful in 2m13s
Heimdall Gitea / Build and scan NVIDIA Agent image (push) Successful in 23m19s
Heimdall Gitea / CI policy (push) Successful in 7s
fix(agent): keep heartbeat timeouts transient (#277)
Co-authored-by: Arnaud Dartois <admin@tordais.cc>
2026-11-07 10:24:31 +01:00

420 lines
18 KiB
C#

using System.Net.Http.Json;
using System.Text.Json.Serialization;
using Microsoft.Extensions.Logging;
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>
public class AgentRegistrationService : BackgroundService
{
private readonly IHttpClientFactory _httpClientFactory;
private readonly ILogger<AgentRegistrationService> _logger;
private readonly AgentState _state;
private readonly AgentOptions _options;
private readonly SystemMetricsProvider _metrics;
private readonly InventoryProviders _providers;
private readonly GpuDetectorService _gpu;
private readonly FrameAnalyzerService? _analyzer;
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,
GpuDetectorService gpu,
Logging.LogBufferService buffer,
ILogger<AgentRegistrationService> logger, FrameAnalyzerService? analyzer = null)
{
_httpClientFactory = httpClientFactory;
_state = state;
_options = options.Value;
_metrics = metrics;
_providers = providers;
_gpu = gpu;
_buffer = buffer;
_logger = logger;
_analyzer = analyzer;
}
/// <summary>
/// Sends a final heartbeat on graceful shutdown so Central knows the agent went offline intentionally.
/// </summary>
public override async Task StopAsync(CancellationToken cancellationToken)
{
if (_client is not null && _state.AgentId != Guid.Empty)
{
_logger.LogInformation("Agent stopping, sending final heartbeat...");
await SendFinalHeartbeatAsync();
}
await base.StopAsync(cancellationToken);
}
private async Task SendFinalHeartbeatAsync()
{
try
{
var metrics = _metrics.Collect();
_gpu.RefreshMetrics();
var gpuInfo = _gpu.GetInfo();
var totalMemoryMb = metrics.TotalMemoryBytes is { } mem ? mem / (1024 * 1024) : (long?)null;
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)
? System.Net.Dns.GetHostName()
: _options.AgentName;
var client = _httpClientFactory.CreateClient("Central");
// Try to reuse an existing identity (survives restarts)
var existing = await _state.LoadAsync(stoppingToken);
if (existing is not null)
{
_state.AgentId = existing.AgentId;
_state.ApiKey = existing.ApiKey;
_state.ApiKeyPrefix = existing.ApiKeyPrefix;
_state.PublicIp = existing.PublicIp;
client.DefaultRequestHeaders.Remove(ApiKeyHeader);
client.DefaultRequestHeaders.Add(ApiKeyHeader, existing.ApiKey);
_client = client;
_logger.LogInformation(
"Reusing existing agent identity. ID: {AgentId}, Key prefix: {Prefix}",
existing.AgentId, existing.ApiKeyPrefix);
}
else
{
await RegisterAgentAsync(client, hostname, stoppingToken);
}
// Step 2: Heartbeat loop
var heartbeatInterval = TimeSpan.FromSeconds(
_state.HeartbeatIntervalSeconds ?? _options.HeartbeatIntervalSeconds);
_logger.LogInformation("Starting heartbeat loop ({Interval}s interval)", heartbeatInterval.TotalSeconds);
while (!stoppingToken.IsCancellationRequested)
{
await SendHeartbeatAsync(client, stoppingToken);
// Re-read the interval each cycle so a remote setting change
// (ConfigReceiverService → AgentState.HeartbeatIntervalSeconds)
// takes effect without a restart.
var intervalSnapshot = _state.GetHeartbeatIntervalSnapshot();
heartbeatInterval = TimeSpan.FromSeconds(
intervalSnapshot.IntervalSeconds ?? _options.HeartbeatIntervalSeconds);
await WaitForNextHeartbeatAsync(heartbeatInterval, intervalSnapshot.Changed, stoppingToken);
}
}
private static async Task WaitForNextHeartbeatAsync(
TimeSpan interval, Task intervalChanged, CancellationToken stoppingToken)
{
using var delayCts = CancellationTokenSource.CreateLinkedTokenSource(stoppingToken);
var delay = Task.Delay(interval, delayCts.Token);
await Task.WhenAny(delay, intervalChanged).ConfigureAwait(false);
delayCts.Cancel();
try
{
await delay.ConfigureAwait(false);
}
catch (OperationCanceledException) when (!stoppingToken.IsCancellationRequested)
{
// A config update woke the loop before the scheduled interval elapsed.
}
}
private async Task RegisterAgentAsync(HttpClient client, string hostname, CancellationToken stoppingToken)
{
if (string.IsNullOrWhiteSpace(_options.SiteToken))
throw new InvalidOperationException(
"Agent registration requires Agent:SiteToken or a systemd site-token credential.");
_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 (OperationCanceledException ex) when (!stoppingToken.IsCancellationRequested)
{
// HttpClient.Timeout cancels only this request; keep the hosted service alive.
_logger.LogWarning(ex, "Heartbeat timed out (will retry)");
}
catch (Exception ex) when (ex is not OperationCanceledException)
{
_logger.LogWarning(ex, "Heartbeat error (will retry)");
}
}
private HeartbeatRequest BuildHeartbeatRequest(SystemMetrics metrics, InventorySnapshot? inventory)
{
_gpu.RefreshMetrics();
var gpuInfo = _gpu.GetInfo();
var totalMemoryMb = metrics.TotalMemoryBytes is { } mem ? mem / (1024 * 1024) : (long?)null;
return new HeartbeatRequest(
_state.PublicIp,
HasGpu: false, // The shipped ONNX package executes on CPU; hardware inventory is separate.
CpuCores: _analyzer is { ModelAvailable: false } ? 0 : Environment.ProcessorCount,
MemoryMb: totalMemoryMb,
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
{
var http = _httpClientFactory.CreateClient("IpResolver");
if (http.BaseAddress is null)
return null;
http.Timeout = TimeSpan.FromSeconds(5);
var ip = await http.GetStringAsync(string.Empty, ct);
ip = ip?.Trim();
_logger.LogDebug("Public IP resolved: {Ip}", ip);
return ip;
}
catch (Exception ex)
{
_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);
internal sealed record RegisterResponse(
[property: JsonPropertyName("agentId")] Guid AgentId,
[property: JsonPropertyName("apiKey")] string ApiKey,
[property: JsonPropertyName("apiKeyPrefix")] string ApiKeyPrefix);
internal sealed record HeartbeatRequest(
[property: JsonPropertyName("publicIp")] string? PublicIp,
[property: JsonPropertyName("isOffline")] bool IsOffline = false,
[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("machineUptimeSeconds")] long? MachineUptimeSeconds = null,
[property: JsonPropertyName("hasGpu")] bool? HasGpu = null,
[property: JsonPropertyName("cpuCores")] int? CpuCores = null,
[property: JsonPropertyName("memoryMb")] long? MemoryMb = 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);