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<T> injection. Config errors are caught at startup via ValidateOnStart().
This commit is contained in:
1 parent
58f46fe3dd
commit
1c08e0394d
7 files changed
+115
-51
No files matched your search
+5
-3
@@ -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
|
||||
@@ -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
|
||||
|
||||
@@ -0,0 +1,40 @@
|
||||
using System.ComponentModel.DataAnnotations;
|
||||
|
||||
namespace Heimdall.Agent;
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
public sealed class AgentOptions
|
||||
{
|
||||
public const string SectionName = "Agent";
|
||||
|
||||
/// <summary>URL of the Heimdall Central server (e.g. http://heimdall-central:8080).</summary>
|
||||
[Required, Url]
|
||||
public string CentralUrl { get; init; } = string.Empty;
|
||||
|
||||
/// <summary>Site token for agent registration.</summary>
|
||||
[Required, MinLength(1)]
|
||||
public string SiteToken { get; init; } = string.Empty;
|
||||
|
||||
/// <summary>
|
||||
/// Display name for this agent instance. Falls back to hostname if empty.
|
||||
/// </summary>
|
||||
public string? AgentName { get; init; }
|
||||
|
||||
/// <summary>Interval between heartbeats in seconds (default: 30).</summary>
|
||||
[Range(5, 300)]
|
||||
public int HeartbeatIntervalSeconds { get; init; } = 30;
|
||||
|
||||
/// <summary>Directory for persisting agent identity state. Defaults to /var/lib/heimdall on Linux.</summary>
|
||||
public string? StateDirectory { get; init; }
|
||||
|
||||
/// <summary>Max retries for agent registration (default: 5).</summary>
|
||||
[Range(1, 20)]
|
||||
public int RegistrationMaxRetries { get; init; } = 5;
|
||||
|
||||
/// <summary>Agent software version reported to Central.</summary>
|
||||
public string Version { get; init; } = "1.0.0";
|
||||
}
|
||||
@@ -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<AgentOptions>()
|
||||
.BindConfiguration(AgentOptions.SectionName)
|
||||
.ValidateDataAnnotations()
|
||||
.ValidateOnStart();
|
||||
|
||||
// HTTP clients
|
||||
builder.Services.AddHttpClient("Central", client =>
|
||||
builder.Services.AddHttpClient("Central", (sp, client) =>
|
||||
{
|
||||
var options = sp.GetRequiredService<IOptions<AgentOptions>>().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<AgentState>();
|
||||
builder.Services.AddSingleton<AgentState>(sp =>
|
||||
{
|
||||
var state = new AgentState();
|
||||
var options = sp.GetRequiredService<IOptions<AgentOptions>>().Value;
|
||||
|
||||
var stateDir = options.StateDirectory
|
||||
?? (OperatingSystem.IsLinux() ? "/var/lib/heimdall" : Directory.GetCurrentDirectory());
|
||||
state.ConfigureStateDirectory(stateDir);
|
||||
|
||||
return state;
|
||||
});
|
||||
|
||||
builder.Services.AddSingleton<SystemMetricsProvider>();
|
||||
builder.Services.AddHostedService<AgentRegistrationService>();
|
||||
|
||||
// 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,
|
||||
|
||||
@@ -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<AgentRegistrationService> _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<AgentOptions> options,
|
||||
SystemMetricsProvider metrics,
|
||||
ILogger<AgentRegistrationService> 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);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -8,8 +8,17 @@ namespace Heimdall.Agent.Services;
|
||||
/// </summary>
|
||||
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";
|
||||
|
||||
/// <summary>
|
||||
/// Sets the directory for the state file. Called during DI setup.
|
||||
/// </summary>
|
||||
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
|
||||
/// <summary>
|
||||
/// Loads a previously saved identity, or returns null if none exists.
|
||||
/// </summary>
|
||||
public static async Task<AgentState?> LoadAsync(CancellationToken ct = default)
|
||||
public async Task<AgentState?> LoadAsync(CancellationToken ct = default)
|
||||
{
|
||||
if (!File.Exists(StatePath))
|
||||
return null;
|
||||
@@ -41,7 +50,7 @@ public class AgentState
|
||||
/// </summary>
|
||||
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
|
||||
/// <summary>
|
||||
/// Removes the persisted state file (e.g. when API key is revoked).
|
||||
/// </summary>
|
||||
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();
|
||||
}
|
||||
}
|
||||
@@ -4,5 +4,13 @@
|
||||
"Default": "Information",
|
||||
"Microsoft.Hosting.Lifetime": "Information"
|
||||
}
|
||||
},
|
||||
"Agent": {
|
||||
"CentralUrl": "",
|
||||
"SiteToken": "",
|
||||
"AgentName": "",
|
||||
"HeartbeatIntervalSeconds": 30,
|
||||
"RegistrationMaxRetries": 5,
|
||||
"Version": "1.0.0"
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user