181 lines
6.2 KiB
C#
181 lines
6.2 KiB
C#
using Microsoft.AspNetCore.SignalR.Client;
|
|||
|
|
using Microsoft.Extensions.Options;
|
||
|
|
|
||
|
|
namespace Heimdall.Agent.Services;
|
||
|
|
|
||
|
|
/// <summary>
|
||
|
|
/// Connects to the Central SignalR ConfigHub to receive real-time configuration updates.
|
||
|
|
/// When a setting changes, applies it locally and logs the change.
|
||
|
|
/// Service will auto-reconnect on connection loss.
|
||
|
|
/// </summary>
|
||
|
|
public sealed class ConfigReceiverService : BackgroundService
|
||
|
|
{
|
||
|
|
private readonly AgentState _state;
|
||
|
|
private readonly AgentOptions _options;
|
||
|
|
private readonly ILogger<ConfigReceiverService> _logger;
|
||
|
|
private HubConnection? _connection;
|
||
|
|
|
||
|
|
public ConfigReceiverService(
|
||
|
|
AgentState state,
|
||
|
|
IOptions<AgentOptions> options,
|
||
|
|
ILogger<ConfigReceiverService> logger)
|
||
|
|
{
|
||
|
|
_state = state;
|
||
|
|
_options = options.Value;
|
||
|
|
_logger = logger;
|
||
|
|
}
|
||
|
|
|
||
|
|
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
|
||
|
|
{
|
||
|
|
// Wait until the agent is registered (has an AgentId)
|
||
|
|
while (_state.AgentId == Guid.Empty && !stoppingToken.IsCancellationRequested)
|
||
|
|
{
|
||
|
|
await Task.Delay(1000, stoppingToken);
|
||
|
|
}
|
||
|
|
|
||
|
|
if (stoppingToken.IsCancellationRequested) return;
|
||
|
|
|
||
|
|
var hubUrl = $"{_options.CentralUrl.TrimEnd('/')}/hubs/config";
|
||
|
|
|
||
|
|
_connection = new HubConnectionBuilder()
|
||
|
|
.WithUrl(hubUrl, options =>
|
||
|
|
{
|
||
|
|
options.AccessTokenProvider = () => Task.FromResult(_state.ApiKey);
|
||
|
|
})
|
||
|
|
.WithAutomaticReconnect(new RetryDelayed(TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(5), TimeSpan.FromSeconds(30)))
|
||
|
|
.Build();
|
||
|
|
|
||
|
|
// Listen for setting changes
|
||
|
|
_connection.On<string, string>("SettingChanged", (key, value) =>
|
||
|
|
{
|
||
|
|
_logger.LogInformation("Config update received: {Key} = {Value}", key, value);
|
||
|
|
ApplySetting(key, value);
|
||
|
|
});
|
||
|
|
|
||
|
|
// Listen for full reload signal
|
||
|
|
_connection.On("ConfigReload", () =>
|
||
|
|
{
|
||
|
|
_logger.LogInformation("Full config reload requested, fetching from API...");
|
||
|
|
_ = FetchFullConfigAsync(CancellationToken.None);
|
||
|
|
});
|
||
|
|
|
||
|
|
// Reconnection events
|
||
|
|
_connection.Reconnecting += _ =>
|
||
|
|
{
|
||
|
|
_logger.LogWarning("Config hub connection lost, reconnecting...");
|
||
|
|
return Task.CompletedTask;
|
||
|
|
};
|
||
|
|
|
||
|
|
_connection.Reconnected += async _ =>
|
||
|
|
{
|
||
|
|
_logger.LogInformation("Config hub reconnected, rejoining agent group...");
|
||
|
|
try
|
||
|
|
{
|
||
|
|
await _connection.InvokeAsync("JoinAgentGroup", _state.AgentId.ToString(), stoppingToken);
|
||
|
|
}
|
||
|
|
catch (Exception ex)
|
||
|
|
{
|
||
|
|
_logger.LogWarning(ex, "Failed to rejoin agent group after reconnect");
|
||
|
|
}
|
||
|
|
};
|
||
|
|
|
||
|
|
// Retry loop for initial connection (auto-reconnect handles the rest)
|
||
|
|
while (!stoppingToken.IsCancellationRequested)
|
||
|
|
{
|
||
|
|
try
|
||
|
|
{
|
||
|
|
await _connection.StartAsync(stoppingToken);
|
||
|
|
_logger.LogInformation("Connected to config hub at {HubUrl}", hubUrl);
|
||
|
|
|
||
|
|
// Join our personal config channel
|
||
|
|
await _connection.InvokeAsync("JoinAgentGroup", _state.AgentId.ToString(), stoppingToken);
|
||
|
|
|
||
|
|
// Fetch initial full config
|
||
|
|
await FetchFullConfigAsync(stoppingToken);
|
||
|
|
|
||
|
|
// Keep service alive until cancellation — auto-reconnect handles reconnection
|
||
|
|
await Task.Delay(Timeout.Infinite, stoppingToken);
|
||
|
|
}
|
||
|
|
catch (OperationCanceledException)
|
||
|
|
{
|
||
|
|
break;
|
||
|
|
}
|
||
|
|
catch (Exception ex)
|
||
|
|
{
|
||
|
|
_logger.LogWarning(ex, "Config hub connection failed, retrying in 15s...");
|
||
|
|
await Task.Delay(TimeSpan.FromSeconds(15), stoppingToken);
|
||
|
|
}
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
public override async Task StopAsync(CancellationToken cancellationToken)
|
||
|
|
{
|
||
|
|
if (_connection is not null)
|
||
|
|
{
|
||
|
|
try { await _connection.DisposeAsync(); }
|
||
|
|
catch { /* best effort */ }
|
||
|
|
}
|
||
|
|
await base.StopAsync(cancellationToken);
|
||
|
|
}
|
||
|
|
|
||
|
|
private void ApplySetting(string key, string value)
|
||
|
|
{
|
||
|
|
// Apply known settings locally
|
||
|
|
switch (key)
|
||
|
|
{
|
||
|
|
case "heartbeat.interval.seconds":
|
||
|
|
if (int.TryParse(value, out var interval) && interval >= 5)
|
||
|
|
{
|
||
|
|
// The heartbeat interval will be read from options on next heartbeat
|
||
|
|
_logger.LogInformation("Heartbeat interval updated to {Interval}s (applied on next restart)", interval);
|
||
|
|
}
|
||
|
|
break;
|
||
|
|
case "log.level":
|
||
|
|
_logger.LogInformation("Log level update received: {Level} (applied on next restart)", value);
|
||
|
|
break;
|
||
|
|
default:
|
||
|
|
_logger.LogDebug("Unknown setting {Key} = {Value} (stored for future use)", key, value);
|
||
|
|
break;
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
private async Task FetchFullConfigAsync(CancellationToken ct)
|
||
|
|
{
|
||
|
|
try
|
||
|
|
{
|
||
|
|
using var http = new HttpClient { Timeout = TimeSpan.FromSeconds(10) };
|
||
|
|
http.DefaultRequestHeaders.Add("Authorization", $"Bearer {_state.ApiKey}");
|
||
|
|
|
||
|
|
var url = $"{_options.CentralUrl.TrimEnd('/')}/api/settings/agent/{_state.AgentId}";
|
||
|
|
var response = await http.GetAsync(url, ct);
|
||
|
|
|
||
|
|
if (response.IsSuccessStatusCode)
|
||
|
|
{
|
||
|
|
_logger.LogInformation("Full configuration fetched successfully");
|
||
|
|
}
|
||
|
|
}
|
||
|
|
catch (Exception ex)
|
||
|
|
{
|
||
|
|
_logger.LogWarning(ex, "Failed to fetch full configuration");
|
||
|
|
}
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
/// <summary>
|
||
|
|
/// Retry policy for SignalR reconnection with specific delays.
|
||
|
|
/// </summary>
|
||
|
|
internal sealed class RetryDelayed : IRetryPolicy
|
||
|
|
{
|
||
|
|
private readonly TimeSpan[] _delays;
|
||
|
|
|
||
|
|
public RetryDelayed(params TimeSpan[] delays) => _delays = delays;
|
||
|
|
|
||
|
|
public TimeSpan? NextRetryDelay(RetryContext context)
|
||
|
|
{
|
||
|
|
if (context.PreviousRetryCount < _delays.Length)
|
||
|
|
return _delays[context.PreviousRetryCount];
|
||
|
|
|
||
|
|
// After exhausting specified delays, retry every 60 seconds
|
||
|
|
return TimeSpan.FromSeconds(60);
|
||
|
|
}
|
||
|
|
}
|