2026-07-16 20:53:56 +00:00
|
|
|
using System.Net.Http.Json;
|
|
|
|
|
using System.Text.Json.Serialization;
|
|
|
|
|
using Microsoft.Extensions.Logging;
|
2026-07-18 14:11:47 +00:00
|
|
|
using Microsoft.Extensions.Options;
|
2026-07-16 20:53:56 +00:00
|
|
|
|
|
|
|
|
namespace Heimdall.Agent.Services;
|
|
|
|
|
|
2026-08-20 14:13:06 +02:00
|
|
|
/// <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;
|
|
|
|
|
}
|
|
|
|
|
|
2026-07-16 20:53:56 +00:00
|
|
|
/// <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;
|
2026-07-18 14:11:47 +00:00
|
|
|
private readonly AgentOptions _options;
|
|
|
|
|
private readonly SystemMetricsProvider _metrics;
|
2026-08-20 14:13:06 +02:00
|
|
|
private readonly InventoryProviders _providers;
|
2026-08-26 23:52:16 +02:00
|
|
|
private readonly GpuDetectorService _gpu;
|
2026-10-20 02:25:27 +02:00
|
|
|
private readonly FrameAnalyzerService? _analyzer;
|
2026-08-11 18:51:52 +02:00
|
|
|
private readonly Logging.LogBufferService _buffer;
|
2026-07-18 14:03:49 +00:00
|
|
|
private HttpClient? _client;
|
2026-07-16 20:53:56 +00:00
|
|
|
|
2026-08-20 14:13:06 +02:00
|
|
|
/// <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;
|
|
|
|
|
|
2026-07-16 20:53:56 +00:00
|
|
|
public AgentRegistrationService(
|
|
|
|
|
IHttpClientFactory httpClientFactory,
|
|
|
|
|
AgentState state,
|
2026-07-18 14:11:47 +00:00
|
|
|
IOptions<AgentOptions> options,
|
|
|
|
|
SystemMetricsProvider metrics,
|
2026-08-20 14:13:06 +02:00
|
|
|
InventoryProviders providers,
|
2026-08-26 23:52:16 +02:00
|
|
|
GpuDetectorService gpu,
|
2026-08-11 18:51:52 +02:00
|
|
|
Logging.LogBufferService buffer,
|
2026-10-20 02:25:27 +02:00
|
|
|
ILogger<AgentRegistrationService> logger, FrameAnalyzerService? analyzer = null)
|
2026-07-16 20:53:56 +00:00
|
|
|
{
|
|
|
|
|
_httpClientFactory = httpClientFactory;
|
|
|
|
|
_state = state;
|
2026-07-18 14:11:47 +00:00
|
|
|
_options = options.Value;
|
|
|
|
|
_metrics = metrics;
|
2026-08-20 14:13:06 +02:00
|
|
|
_providers = providers;
|
2026-08-26 23:52:16 +02:00
|
|
|
_gpu = gpu;
|
2026-08-11 18:51:52 +02:00
|
|
|
_buffer = buffer;
|
2026-07-16 20:53:56 +00:00
|
|
|
_logger = logger;
|
2026-10-20 02:25:27 +02:00
|
|
|
_analyzer = analyzer;
|
2026-07-16 20:53:56 +00:00
|
|
|
}
|
|
|
|
|
|
2026-07-18 14:03:49 +00:00
|
|
|
/// <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...");
|
2026-08-20 14:13:06 +02:00
|
|
|
await SendFinalHeartbeatAsync();
|
2026-07-18 14:03:49 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
await base.StopAsync(cancellationToken);
|
|
|
|
|
}
|
|
|
|
|
|
2026-08-20 14:13:06 +02:00
|
|
|
private async Task SendFinalHeartbeatAsync()
|
|
|
|
|
{
|
|
|
|
|
try
|
|
|
|
|
{
|
|
|
|
|
var metrics = _metrics.Collect();
|
2026-08-26 23:52:16 +02:00
|
|
|
_gpu.RefreshMetrics();
|
|
|
|
|
var gpuInfo = _gpu.GetInfo();
|
|
|
|
|
var totalMemoryMb = metrics.TotalMemoryBytes is { } mem ? mem / (1024 * 1024) : (long?)null;
|
2026-08-20 14:13:06 +02:00
|
|
|
var request = new HeartbeatRequest(_state.PublicIp, IsOffline: true,
|
|
|
|
|
CpuUsagePercent: metrics.CpuUsagePercent,
|
|
|
|
|
MemoryUsageBytes: metrics.MemoryUsageBytes,
|
|
|
|
|
DiskUsagePercent: metrics.DiskUsagePercent,
|
2026-08-27 15:02:17 +02:00
|
|
|
UptimeSeconds: metrics.UptimeSeconds);
|
2026-08-20 14:13:06 +02:00
|
|
|
await _client!.PostAsJsonAsync(
|
|
|
|
|
$"api/agents/{_state.AgentId}/heartbeat",
|
|
|
|
|
request, CancellationToken.None);
|
|
|
|
|
}
|
|
|
|
|
catch (Exception ex)
|
|
|
|
|
{
|
|
|
|
|
_logger.LogWarning(ex, "Final heartbeat failed (non-fatal)");
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2026-07-16 20:53:56 +00:00
|
|
|
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
|
|
|
|
|
{
|
2026-07-18 14:11:47 +00:00
|
|
|
var hostname = string.IsNullOrEmpty(_options.AgentName)
|
|
|
|
|
? System.Net.Dns.GetHostName()
|
|
|
|
|
: _options.AgentName;
|
2026-07-16 20:53:56 +00:00
|
|
|
|
2026-07-18 14:11:47 +00:00
|
|
|
var client = _httpClientFactory.CreateClient("Central");
|
2026-07-16 20:53:56 +00:00
|
|
|
|
2026-07-18 14:05:07 +00:00
|
|
|
// Try to reuse an existing identity (survives restarts)
|
2026-07-18 14:11:47 +00:00
|
|
|
var existing = await _state.LoadAsync(stoppingToken);
|
2026-07-18 14:05:07 +00:00
|
|
|
if (existing is not null)
|
2026-07-16 20:53:56 +00:00
|
|
|
{
|
2026-07-18 14:05:07 +00:00
|
|
|
_state.AgentId = existing.AgentId;
|
|
|
|
|
_state.ApiKey = existing.ApiKey;
|
|
|
|
|
_state.ApiKeyPrefix = existing.ApiKeyPrefix;
|
|
|
|
|
_state.PublicIp = existing.PublicIp;
|
2026-07-16 20:53:56 +00:00
|
|
|
|
2026-08-20 14:13:06 +02:00
|
|
|
client.DefaultRequestHeaders.Remove(ApiKeyHeader);
|
|
|
|
|
client.DefaultRequestHeaders.Add(ApiKeyHeader, existing.ApiKey);
|
2026-07-18 14:05:07 +00:00
|
|
|
_client = client;
|
2026-07-16 20:53:56 +00:00
|
|
|
|
2026-07-18 14:05:07 +00:00
|
|
|
_logger.LogInformation(
|
|
|
|
|
"Reusing existing agent identity. ID: {AgentId}, Key prefix: {Prefix}",
|
|
|
|
|
existing.AgentId, existing.ApiKeyPrefix);
|
2026-07-16 20:53:56 +00:00
|
|
|
}
|
2026-07-18 14:05:07 +00:00
|
|
|
else
|
2026-07-16 20:53:56 +00:00
|
|
|
{
|
2026-08-20 14:13:06 +02:00
|
|
|
await RegisterAgentAsync(client, hostname, stoppingToken);
|
2026-07-16 20:53:56 +00:00
|
|
|
}
|
|
|
|
|
|
2026-07-18 14:11:47 +00:00
|
|
|
// Step 2: Heartbeat loop
|
2026-08-10 11:02:37 +02:00
|
|
|
var heartbeatInterval = TimeSpan.FromSeconds(
|
|
|
|
|
_state.HeartbeatIntervalSeconds ?? _options.HeartbeatIntervalSeconds);
|
|
|
|
|
_logger.LogInformation("Starting heartbeat loop ({Interval}s interval)", heartbeatInterval.TotalSeconds);
|
2026-07-16 20:53:56 +00:00
|
|
|
|
|
|
|
|
while (!stoppingToken.IsCancellationRequested)
|
|
|
|
|
{
|
2026-08-20 14:13:06 +02:00
|
|
|
await SendHeartbeatAsync(client, stoppingToken);
|
2026-07-16 20:53:56 +00:00
|
|
|
|
2026-08-10 11:02:37 +02:00
|
|
|
// Re-read the interval each cycle so a remote setting change
|
|
|
|
|
// (ConfigReceiverService → AgentState.HeartbeatIntervalSeconds)
|
|
|
|
|
// takes effect without a restart.
|
2026-10-25 02:08:00 +01:00
|
|
|
var intervalSnapshot = _state.GetHeartbeatIntervalSnapshot();
|
2026-08-10 11:02:37 +02:00
|
|
|
heartbeatInterval = TimeSpan.FromSeconds(
|
2026-10-25 02:08:00 +01:00
|
|
|
intervalSnapshot.IntervalSeconds ?? _options.HeartbeatIntervalSeconds);
|
|
|
|
|
await WaitForNextHeartbeatAsync(heartbeatInterval, intervalSnapshot.Changed, stoppingToken);
|
2026-10-25 02:58:06 +02:00
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2026-10-25 02:08:00 +01:00
|
|
|
private static async Task WaitForNextHeartbeatAsync(
|
|
|
|
|
TimeSpan interval, Task intervalChanged, CancellationToken stoppingToken)
|
2026-10-25 02:58:06 +02:00
|
|
|
{
|
2026-10-25 02:08:00 +01:00
|
|
|
using var delayCts = CancellationTokenSource.CreateLinkedTokenSource(stoppingToken);
|
|
|
|
|
var delay = Task.Delay(interval, delayCts.Token);
|
2026-10-25 02:58:06 +02:00
|
|
|
await Task.WhenAny(delay, intervalChanged).ConfigureAwait(false);
|
2026-10-25 02:08:00 +01:00
|
|
|
delayCts.Cancel();
|
2026-10-25 02:58:06 +02:00
|
|
|
try
|
|
|
|
|
{
|
2026-10-25 02:08:00 +01:00
|
|
|
await delay.ConfigureAwait(false);
|
2026-10-25 02:58:06 +02:00
|
|
|
}
|
|
|
|
|
catch (OperationCanceledException) when (!stoppingToken.IsCancellationRequested)
|
|
|
|
|
{
|
2026-10-25 02:08:00 +01:00
|
|
|
// A config update woke the loop before the scheduled interval elapsed.
|
2026-07-16 20:53:56 +00:00
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2026-08-20 14:13:06 +02:00
|
|
|
private async Task RegisterAgentAsync(HttpClient client, string hostname, CancellationToken stoppingToken)
|
|
|
|
|
{
|
2026-10-22 06:57:50 +02:00
|
|
|
if (string.IsNullOrWhiteSpace(_options.SiteToken))
|
|
|
|
|
throw new InvalidOperationException(
|
|
|
|
|
"Agent registration requires Agent:SiteToken or a systemd site-token credential.");
|
|
|
|
|
|
2026-08-20 14:13:06 +02:00
|
|
|
_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);
|
|
|
|
|
}
|
|
|
|
|
}
|
2026-11-07 10:24:31 +01:00
|
|
|
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)");
|
|
|
|
|
}
|
2026-08-20 14:13:06 +02:00
|
|
|
catch (Exception ex) when (ex is not OperationCanceledException)
|
|
|
|
|
{
|
|
|
|
|
_logger.LogWarning(ex, "Heartbeat error (will retry)");
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2026-08-26 23:52:16 +02:00
|
|
|
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(
|
2026-08-20 14:13:06 +02:00
|
|
|
_state.PublicIp,
|
2026-10-20 02:25:27 +02:00
|
|
|
HasGpu: false, // The shipped ONNX package executes on CPU; hardware inventory is separate.
|
|
|
|
|
CpuCores: _analyzer is { ModelAvailable: false } ? 0 : Environment.ProcessorCount,
|
|
|
|
|
MemoryMb: totalMemoryMb,
|
2026-08-20 14:13:06 +02:00
|
|
|
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);
|
2026-08-26 23:52:16 +02:00
|
|
|
}
|
2026-08-20 14:13:06 +02:00
|
|
|
|
|
|
|
|
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)
|
|
|
|
|
};
|
|
|
|
|
}
|
|
|
|
|
|
2026-07-18 14:02:40 +00:00
|
|
|
private async Task<string?> ResolvePublicIpAsync(CancellationToken ct)
|
2026-07-16 20:53:56 +00:00
|
|
|
{
|
2026-07-17 19:29:40 +00:00
|
|
|
try
|
|
|
|
|
{
|
2026-07-18 14:02:40 +00:00
|
|
|
var http = _httpClientFactory.CreateClient("IpResolver");
|
2026-11-04 20:55:14 +01:00
|
|
|
if (http.BaseAddress is null)
|
|
|
|
|
return null;
|
2026-07-18 14:02:40 +00:00
|
|
|
http.Timeout = TimeSpan.FromSeconds(5);
|
2026-11-04 20:55:14 +01:00
|
|
|
var ip = await http.GetStringAsync(string.Empty, ct);
|
2026-08-11 18:51:52 +02:00
|
|
|
ip = ip?.Trim();
|
|
|
|
|
_logger.LogDebug("Public IP resolved: {Ip}", ip);
|
|
|
|
|
return ip;
|
2026-07-17 19:29:40 +00:00
|
|
|
}
|
2026-08-11 18:51:52 +02:00
|
|
|
catch (Exception ex)
|
2026-07-17 19:29:40 +00:00
|
|
|
{
|
2026-08-20 14:13:06 +02:00
|
|
|
_logger.LogDebug(ex, "Public IP resolution failed; reporting null");
|
2026-07-17 19:29:40 +00:00
|
|
|
return null;
|
|
|
|
|
}
|
2026-07-16 20:53:56 +00:00
|
|
|
}
|
2026-08-20 14:13:06 +02:00
|
|
|
|
|
|
|
|
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; }
|
|
|
|
|
}
|
2026-07-16 20:53:56 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
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);
|
|
|
|
|
|
2026-07-18 14:03:49 +00:00
|
|
|
internal sealed record HeartbeatRequest(
|
2026-08-12 20:05:12 +02:00
|
|
|
[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,
|
2026-08-20 14:13:06 +02:00
|
|
|
[property: JsonPropertyName("uptimeSeconds")] long? UptimeSeconds = null,
|
|
|
|
|
[property: JsonPropertyName("machineUptimeSeconds")] long? MachineUptimeSeconds = null,
|
2026-10-20 02:25:27 +02:00
|
|
|
[property: JsonPropertyName("hasGpu")] bool? HasGpu = null,
|
|
|
|
|
[property: JsonPropertyName("cpuCores")] int? CpuCores = null,
|
|
|
|
|
[property: JsonPropertyName("memoryMb")] long? MemoryMb = null,
|
2026-08-20 14:13:06 +02:00
|
|
|
// 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);
|