using System.Net.Http.Json; using System.Text.Json.Serialization; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; namespace Heimdall.Agent.Services; /// /// Registers this agent with the Heimdall Central server and manages the heartbeat loop. /// public class AgentRegistrationService : BackgroundService { private readonly IHttpClientFactory _httpClientFactory; private readonly ILogger _logger; private readonly AgentState _state; private readonly AgentOptions _options; private readonly SystemMetricsProvider _metrics; private HttpClient? _client; public AgentRegistrationService( IHttpClientFactory httpClientFactory, AgentState state, IOptions options, SystemMetricsProvider metrics, ILogger logger) { _httpClientFactory = httpClientFactory; _state = state; _options = options.Value; _metrics = metrics; _logger = logger; } /// /// Sends a final heartbeat on graceful shutdown so Central knows the agent went offline intentionally. /// public override async Task StopAsync(CancellationToken cancellationToken) { 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 base.StopAsync(cancellationToken); } 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("X-API-Key"); client.DefaultRequestHeaders.Add("X-API-Key", existing.ApiKey); _client = client; _logger.LogInformation( "Reusing existing agent identity. ID: {AgentId}, Key prefix: {Prefix}", existing.AgentId, existing.ApiKeyPrefix); } else { // Step 1: Register (with retry) _logger.LogInformation("Registering agent with Central at {CentralUrl}", _options.CentralUrl); var maxRetries = _options.RegistrationMaxRetries; RegisterResponse? registration = null; for (int attempt = 1; attempt <= maxRetries; attempt++) { try { var request = new RegisterRequest(_options.SiteToken, hostname, _options.Version); var response = await client.PostAsJsonAsync("api/agents/register", request, stoppingToken); response.EnsureSuccessStatusCode(); registration = await response.Content.ReadFromJsonAsync(stoppingToken); if (registration is null) throw new InvalidOperationException("Empty registration response"); break; // success } catch (Exception ex) when (attempt < maxRetries && ex is not OperationCanceledException) { var delay = TimeSpan.FromSeconds(Math.Pow(2, attempt)); _logger.LogWarning(ex, "Registration attempt {Attempt}/{Max} failed, retrying in {Delay}s", attempt, maxRetries, delay.TotalSeconds); await Task.Delay(delay, stoppingToken); } } if (registration is null) { _logger.LogError("All {Max} registration attempts failed", maxRetries); throw new InvalidOperationException("Agent registration failed after all retries"); } _state.AgentId = registration.AgentId; _state.ApiKey = registration.ApiKey; _state.ApiKeyPrefix = registration.ApiKeyPrefix; _state.PublicIp = await ResolvePublicIpAsync(stoppingToken); // Persist identity so subsequent restarts reuse it await _state.SaveAsync(stoppingToken); // Set API Key header for subsequent requests (Central's ApiKey scheme reads X-API-Key) client.DefaultRequestHeaders.Remove("X-API-Key"); client.DefaultRequestHeaders.Add("X-API-Key", registration.ApiKey); _client = client; _logger.LogInformation( "Agent registered successfully. ID: {AgentId}, Key prefix: {Prefix}", registration.AgentId, registration.ApiKeyPrefix); } // Step 2: Heartbeat loop var heartbeatInterval = TimeSpan.FromSeconds(_options.HeartbeatIntervalSeconds); _logger.LogInformation("Starting heartbeat loop ({Interval}s interval)", _options.HeartbeatIntervalSeconds); 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); } } catch (Exception ex) when (ex is not OperationCanceledException) { _logger.LogWarning(ex, "Heartbeat error (will retry)"); } await Task.Delay(heartbeatInterval, stoppingToken); } } private async Task ResolvePublicIpAsync(CancellationToken ct) { try { var http = _httpClientFactory.CreateClient("IpResolver"); http.Timeout = TimeSpan.FromSeconds(5); var ip = await http.GetStringAsync("https://api.ipify.org", ct); return ip?.Trim(); } catch { return null; } } } 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);