From 1c08e0394da862bc6f285f6afb4265163cee7cba Mon Sep 17 00:00:00 2001 From: Arnaud Dartois Date: Sat, 18 Jul 2026 14:11:47 +0000 Subject: [PATCH] refactor(agent): use Options pattern with validation instead of raw env vars Introduce AgentOptions class with DataAnnotations validation bound from configuration (env vars with Agent__ prefix). Replace all Environment.GetEnvironmentVariable() calls with typed IOptions injection. Config errors are caught at startup via ValidateOnStart(). --- .env.example | 8 ++-- docker/docker-compose.yml | 7 +-- src/Heimdall.Agent/AgentOptions.cs | 40 +++++++++++++++++ src/Heimdall.Agent/Program.cs | 28 ++++++++++-- .../Services/AgentRegistrationService.cs | 43 ++++++++----------- src/Heimdall.Agent/Services/AgentState.cs | 32 ++++++-------- src/Heimdall.Agent/appsettings.json | 8 ++++ 7 files changed, 115 insertions(+), 51 deletions(-) create mode 100644 src/Heimdall.Agent/AgentOptions.cs diff --git a/.env.example b/.env.example index 33e3f50..d357594 100644 --- a/.env.example +++ b/.env.example @@ -24,6 +24,8 @@ ALARIK_ADMIN_PASSWORD=heimdall123 ALARIK_JWT=ChangeMeAtLeast32BytesLongKeyInProd! # Agent (set per agent instance) -HEIMDALL_CENTRAL_URL=http://heimdall-central:8080 -HEIMDALL_SITE_TOKEN=replace-with-actual-token -HEIMDALL_AGENT_NAME=agent-01 +Agent__CentralUrl=http://heimdall-central:8080 +Agent__SiteToken=replace-with-actual-token +Agent__AgentName=agent-01 +Agent__HeartbeatIntervalSeconds=30 +Agent__RegistrationMaxRetries=5 diff --git a/docker/docker-compose.yml b/docker/docker-compose.yml index 4f34175..01f8aba 100644 --- a/docker/docker-compose.yml +++ b/docker/docker-compose.yml @@ -112,9 +112,10 @@ services: context: .. dockerfile: docker/Dockerfile.agent environment: - HEIMDALL_CENTRAL_URL: ${HEIMDALL_CENTRAL_URL:-http://heimdall-central:8080} - HEIMDALL_SITE_TOKEN: ${HEIMDALL_SITE_TOKEN} - HEIMDALL_AGENT_NAME: ${HEIMDALL_AGENT_NAME:-agent-01} + Agent__CentralUrl: ${HEIMDALL_CENTRAL_URL:-http://heimdall-central:8080} + Agent__SiteToken: ${HEIMDALL_SITE_TOKEN} + Agent__AgentName: ${HEIMDALL_AGENT_NAME:-agent-01} + Agent__HeartbeatIntervalSeconds: 30 healthcheck: test: ["CMD", "wget", "--no-verbose", "--tries=1", "--spider", "http://localhost:8080/healthz"] interval: 30s diff --git a/src/Heimdall.Agent/AgentOptions.cs b/src/Heimdall.Agent/AgentOptions.cs new file mode 100644 index 0000000..2493dd4 --- /dev/null +++ b/src/Heimdall.Agent/AgentOptions.cs @@ -0,0 +1,40 @@ +using System.ComponentModel.DataAnnotations; + +namespace Heimdall.Agent; + +/// +/// Strongly-typed configuration for the Heimdall Agent. +/// Bound from environment variables or appsettings.json on startup. +/// Validated automatically — misconfiguration is caught before any service runs. +/// +public sealed class AgentOptions +{ + public const string SectionName = "Agent"; + + /// URL of the Heimdall Central server (e.g. http://heimdall-central:8080). + [Required, Url] + public string CentralUrl { get; init; } = string.Empty; + + /// Site token for agent registration. + [Required, MinLength(1)] + public string SiteToken { get; init; } = string.Empty; + + /// + /// Display name for this agent instance. Falls back to hostname if empty. + /// + public string? AgentName { get; init; } + + /// Interval between heartbeats in seconds (default: 30). + [Range(5, 300)] + public int HeartbeatIntervalSeconds { get; init; } = 30; + + /// Directory for persisting agent identity state. Defaults to /var/lib/heimdall on Linux. + public string? StateDirectory { get; init; } + + /// Max retries for agent registration (default: 5). + [Range(1, 20)] + public int RegistrationMaxRetries { get; init; } = 5; + + /// Agent software version reported to Central. + public string Version { get; init; } = "1.0.0"; +} diff --git a/src/Heimdall.Agent/Program.cs b/src/Heimdall.Agent/Program.cs index 8b02983..6c58ad9 100644 --- a/src/Heimdall.Agent/Program.cs +++ b/src/Heimdall.Agent/Program.cs @@ -1,12 +1,22 @@ +using Heimdall.Agent; using Heimdall.Agent.Services; using Microsoft.AspNetCore.Diagnostics.HealthChecks; using Microsoft.Extensions.Diagnostics.HealthChecks; +using Microsoft.Extensions.Options; var builder = WebApplication.CreateSlimBuilder(args); +// Strongly-typed configuration with validation +builder.Services.AddOptions() + .BindConfiguration(AgentOptions.SectionName) + .ValidateDataAnnotations() + .ValidateOnStart(); + // HTTP clients -builder.Services.AddHttpClient("Central", client => +builder.Services.AddHttpClient("Central", (sp, client) => { + var options = sp.GetRequiredService>().Value; + client.BaseAddress = new Uri(options.CentralUrl.TrimEnd('/') + "/"); client.Timeout = TimeSpan.FromSeconds(10); }); @@ -16,7 +26,19 @@ builder.Services.AddHttpClient("IpResolver", client => }); // Agent services -builder.Services.AddSingleton(); +builder.Services.AddSingleton(sp => +{ + var state = new AgentState(); + var options = sp.GetRequiredService>().Value; + + var stateDir = options.StateDirectory + ?? (OperatingSystem.IsLinux() ? "/var/lib/heimdall" : Directory.GetCurrentDirectory()); + state.ConfigureStateDirectory(stateDir); + + return state; +}); + +builder.Services.AddSingleton(); builder.Services.AddHostedService(); // Health checks — used by Docker HEALTHCHECK @@ -25,7 +47,7 @@ builder.Services.AddHealthChecks() var app = builder.Build(); -// Health endpoint (port 5001 is mapped in Dockerfile) +// Health endpoint app.MapHealthChecks("/healthz", new HealthCheckOptions { Predicate = _ => true, diff --git a/src/Heimdall.Agent/Services/AgentRegistrationService.cs b/src/Heimdall.Agent/Services/AgentRegistrationService.cs index 5f1d3aa..f076c39 100644 --- a/src/Heimdall.Agent/Services/AgentRegistrationService.cs +++ b/src/Heimdall.Agent/Services/AgentRegistrationService.cs @@ -1,6 +1,7 @@ using System.Net.Http.Json; using System.Text.Json.Serialization; using Microsoft.Extensions.Logging; +using Microsoft.Extensions.Options; namespace Heimdall.Agent.Services; @@ -12,16 +13,21 @@ public class AgentRegistrationService : BackgroundService private readonly IHttpClientFactory _httpClientFactory; private readonly ILogger _logger; private readonly AgentState _state; - private readonly SystemMetricsProvider _metrics = new(); + 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; } @@ -54,28 +60,16 @@ public class AgentRegistrationService : BackgroundService await base.StopAsync(cancellationToken); } - private HttpClient CreateApiClient() - { - var client = _httpClientFactory.CreateClient("Central"); - var centralUrl = Environment.GetEnvironmentVariable("HEIMDALL_CENTRAL_URL") - ?? throw new InvalidOperationException("HEIMDALL_CENTRAL_URL is not set"); - client.BaseAddress = new Uri(centralUrl.TrimEnd('/') + "/"); - return client; - } - protected override async Task ExecuteAsync(CancellationToken stoppingToken) { - var centralUrl = Environment.GetEnvironmentVariable("HEIMDALL_CENTRAL_URL") - ?? throw new InvalidOperationException("HEIMDALL_CENTRAL_URL is not set"); - var siteToken = Environment.GetEnvironmentVariable("HEIMDALL_SITE_TOKEN") - ?? throw new InvalidOperationException("HEIMDALL_SITE_TOKEN is not set"); - var hostname = Environment.GetEnvironmentVariable("HEIMDALL_AGENT_NAME") - ?? System.Net.Dns.GetHostName(); + var hostname = string.IsNullOrEmpty(_options.AgentName) + ? System.Net.Dns.GetHostName() + : _options.AgentName; - var client = CreateApiClient(); + var client = _httpClientFactory.CreateClient("Central"); // Try to reuse an existing identity (survives restarts) - var existing = await AgentState.LoadAsync(stoppingToken); + var existing = await _state.LoadAsync(stoppingToken); if (existing is not null) { _state.AgentId = existing.AgentId; @@ -94,16 +88,16 @@ public class AgentRegistrationService : BackgroundService else { // Step 1: Register (with retry) - _logger.LogInformation("Registering agent with Central at {CentralUrl}", centralUrl); + _logger.LogInformation("Registering agent with Central at {CentralUrl}", _options.CentralUrl); - const int maxRetries = 5; + var maxRetries = _options.RegistrationMaxRetries; RegisterResponse? registration = null; for (int attempt = 1; attempt <= maxRetries; attempt++) { try { - var request = new RegisterRequest(siteToken, hostname, "1.0.0"); + var request = new RegisterRequest(_options.SiteToken, hostname, _options.Version); var response = await client.PostAsJsonAsync("api/agents/register", request, stoppingToken); response.EnsureSuccessStatusCode(); @@ -147,8 +141,9 @@ public class AgentRegistrationService : BackgroundService registration.AgentId, registration.ApiKeyPrefix); } - // Step 2: Heartbeat loop (every 30 seconds) - _logger.LogInformation("Starting heartbeat loop (30s interval)"); + // Step 2: Heartbeat loop + var heartbeatInterval = TimeSpan.FromSeconds(_options.HeartbeatIntervalSeconds); + _logger.LogInformation("Starting heartbeat loop ({Interval}s interval)", _options.HeartbeatIntervalSeconds); while (!stoppingToken.IsCancellationRequested) { @@ -175,7 +170,7 @@ public class AgentRegistrationService : BackgroundService _logger.LogWarning(ex, "Heartbeat error (will retry)"); } - await Task.Delay(TimeSpan.FromSeconds(30), stoppingToken); + await Task.Delay(heartbeatInterval, stoppingToken); } } diff --git a/src/Heimdall.Agent/Services/AgentState.cs b/src/Heimdall.Agent/Services/AgentState.cs index cdd06d2..e949b68 100644 --- a/src/Heimdall.Agent/Services/AgentState.cs +++ b/src/Heimdall.Agent/Services/AgentState.cs @@ -8,8 +8,17 @@ namespace Heimdall.Agent.Services; /// public class AgentState { - private static readonly string StateDir = GetStateDirectory(); - private static readonly string StatePath = Path.Combine(StateDir, "agent-state.json"); + private string _stateDir = "/var/lib/heimdall"; + + /// + /// Sets the directory for the state file. Called during DI setup. + /// + public void ConfigureStateDirectory(string directory) + { + _stateDir = directory; + } + + private string StatePath => Path.Combine(_stateDir, "agent-state.json"); public Guid AgentId { get; set; } public string? ApiKey { get; set; } @@ -19,7 +28,7 @@ public class AgentState /// /// Loads a previously saved identity, or returns null if none exists. /// - public static async Task LoadAsync(CancellationToken ct = default) + public async Task LoadAsync(CancellationToken ct = default) { if (!File.Exists(StatePath)) return null; @@ -41,7 +50,7 @@ public class AgentState /// public async Task SaveAsync(CancellationToken ct = default) { - Directory.CreateDirectory(StateDir); + Directory.CreateDirectory(_stateDir); var json = JsonSerializer.Serialize(this); await File.WriteAllTextAsync(StatePath, json, ct); } @@ -49,22 +58,9 @@ public class AgentState /// /// Removes the persisted state file (e.g. when API key is revoked). /// - public static void Clear() + public void Clear() { if (File.Exists(StatePath)) File.Delete(StatePath); } - - private static string GetStateDirectory() - { - // Prefer a standard Linux path, fall back to current directory - var dataDir = Environment.GetEnvironmentVariable("HEIMDALL_STATE_DIR"); - if (!string.IsNullOrEmpty(dataDir)) - return dataDir; - - if (OperatingSystem.IsLinux()) - return "/var/lib/heimdall"; - - return Directory.GetCurrentDirectory(); - } } diff --git a/src/Heimdall.Agent/appsettings.json b/src/Heimdall.Agent/appsettings.json index b2dcdb6..2fd3557 100644 --- a/src/Heimdall.Agent/appsettings.json +++ b/src/Heimdall.Agent/appsettings.json @@ -4,5 +4,13 @@ "Default": "Information", "Microsoft.Hosting.Lifetime": "Information" } + }, + "Agent": { + "CentralUrl": "", + "SiteToken": "", + "AgentName": "", + "HeartbeatIntervalSeconds": 30, + "RegistrationMaxRetries": 5, + "Version": "1.0.0" } }