fix(agent): settings distants appliqués à chaud — log.level live + full reload complet (Fixes #20)

- log.level appliqué immédiatement via RuntimeLogLevel (règle globale en tête
  du LoggerFilterOptions partagé + RefreshFilters réflexif sur le LoggerFactory,
  API publique AddFilter retirée en .NET 10) — effet observable sur les loggers
  déjà créés, sans redémarrage
- FetchFullConfigAsync applique désormais TOUTES les clés du full config via le
  même pipeline que SettingChanged (heartbeat, log.level, credentials, …) au
  lieu de ne traiter que discovery.credentials
- Settings connus non dynamiques (ai.detection.*, detection.*, model.*,
  ffmpeg.*, yolo.*, camera.*) loggés explicitement « requires restart »
- Tests : effet observable sur loggers existants, abaissement de niveau,
  full reload complet (heartbeat + log.level + credential pool)
This commit is contained in:
Arnaud Dartois committed 2026-08-11 17:34:22 +02:00
1 parent 5db7d84d9c
commit ab705e72fa
4 files changed
+348 -8

No files matched your search

+1
View File
@@ -64,6 +64,7 @@ builder.Services.AddSingleton<SystemMetricsProvider>();
builder.Services.AddSingleton<NetworkCameraScanner>();
builder.Services.AddSingleton<DiscoveryScanTrigger>();
builder.Services.AddSingleton<AgentCredentialStore>();
builder.Services.AddSingleton<RuntimeLogLevel>();
builder.Services.AddHostedService<AgentRegistrationService>();
builder.Services.AddHostedService<ConfigReceiverService>();
builder.Services.AddHostedService<AgentDiscoveryService>();
@@ -19,15 +19,34 @@ public sealed class ConfigReceiverService : BackgroundService
private readonly IHttpClientFactory _httpClientFactory;
private readonly DiscoveryScanTrigger _scanTrigger;
private readonly AgentCredentialStore _credentialStore;
private readonly RuntimeLogLevel _runtimeLogLevel;
private HubConnection? _connection;
/// <summary>
/// Settings that are known but cannot be applied without an agent restart
/// (they are read once at startup by services that do not support hot
/// reload). They are logged explicitly so operators know why the change
/// has no immediate effect.
/// </summary>
private static readonly HashSet<string> RestartRequiredPrefixes =
new(StringComparer.OrdinalIgnoreCase)
{
"ai.detection.",
"detection.",
"model.",
"ffmpeg.",
"yolo.",
"camera.",
};
public ConfigReceiverService(
AgentState state,
IOptions<AgentOptions> options,
ILogger<ConfigReceiverService> logger,
IHttpClientFactory httpClientFactory,
DiscoveryScanTrigger scanTrigger,
AgentCredentialStore credentialStore)
AgentCredentialStore credentialStore,
RuntimeLogLevel runtimeLogLevel)
{
_state = state;
_options = options.Value;
@@ -35,6 +54,7 @@ public sealed class ConfigReceiverService : BackgroundService
_httpClientFactory = httpClientFactory;
_scanTrigger = scanTrigger;
_credentialStore = credentialStore;
_runtimeLogLevel = runtimeLogLevel;
}
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
@@ -147,7 +167,15 @@ public sealed class ConfigReceiverService : BackgroundService
}
break;
case "log.level":
_logger.LogInformation("Log level update received: {Level} (applied on next restart)", value);
if (Enum.TryParse<LogLevel>(value, ignoreCase: true, out var level))
{
_runtimeLogLevel.Set(level);
_logger.LogInformation("Log level updated to {Level} (applied live)", level);
}
else
{
_logger.LogWarning("Ignored invalid log level: {Value}", value);
}
break;
case "discovery.scan.requested":
_logger.LogInformation("Camera discovery scan requested by Central");
@@ -157,7 +185,16 @@ public sealed class ConfigReceiverService : BackgroundService
ApplyCredentialPool(value);
break;
default:
_logger.LogDebug("Unknown setting {Key} = {Value} (stored for future use)", key, value);
if (RestartRequiredPrefixes.Any(p => key.StartsWith(p, StringComparison.OrdinalIgnoreCase)))
{
_logger.LogWarning(
"Setting {Key} = {Value} requires an agent restart to take effect (not applied live)",
key, value);
}
else
{
_logger.LogDebug("Unknown setting {Key} = {Value} (stored for future use)", key, value);
}
break;
}
}
@@ -216,8 +253,11 @@ public sealed class ConfigReceiverService : BackgroundService
_logger.LogInformation("Full configuration fetched successfully ({Count} setting(s))", config.Count);
if (config.TryGetValue("discovery.credentials", out var envelope))
ApplyCredentialPool(envelope);
// Apply every key through the same pipeline as live SettingChanged
// events — heartbeat interval, log level, credentials, restart-required
// documentation, everything.
foreach (var kvp in config)
ApplySetting(kvp.Key, kvp.Value);
}
catch (Exception ex)
{
@@ -0,0 +1,88 @@
using System.Reflection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
namespace Heimdall.Agent.Services;
/// <summary>
/// Holds the agent's current minimum log level and applies it live to the
/// shared <see cref="LoggerFilterOptions"/> used by every ILogger in the
/// process. After updating the shared rules it triggers the LoggerFactory's
/// internal RefreshFilters so already-created loggers re-filter immediately —
/// no restart required.
/// </summary>
/// <remarks>
/// Dynamic (applied live): heartbeat.interval.seconds, log.level,
/// discovery.scan.requested, discovery.credentials.
/// Restart-required (documented, not applied): ai.detection.*, detection.*,
/// model.*, ffmpeg.*, yolo.*, camera.* — those settings are read once at
/// startup by services that do not support hot reload.
/// </remarks>
public sealed class RuntimeLogLevel
{
private readonly ILoggerFactory _loggerFactory;
private readonly LoggerFilterOptions _filterOptions;
private readonly IReadOnlyList<LoggerFilterRule> _originalRules;
private LoggerFilterRule? _currentRule;
public RuntimeLogLevel(ILoggerFactory loggerFactory, IOptions<LoggerFilterOptions> filterOptions)
{
_loggerFactory = loggerFactory;
_filterOptions = filterOptions.Value;
// Snapshot the rules configured at startup (appsettings "Logging:LogLevel")
// so they can be restored after the live global rule is removed.
_originalRules = _filterOptions.Rules.ToList();
}
/// <summary>Current minimum level applied to all loggers.</summary>
public LogLevel Level { get; private set; } = LogLevel.Information;
/// <summary>
/// Applies a new global minimum level. A rule with a null category matches
/// every category and is inserted at the head of the shared rules list so
/// it wins over startup config rules (e.g. "Default"). Then the factory's
/// internal RefreshFilters is invoked so existing loggers re-filter live.
/// </summary>
public void Set(LogLevel level)
{
Level = level;
// Remove the previous live rule (kept by reference) so levels can be
// lowered again — otherwise an old "Warning" rule would keep matching
// before a newer "Information" rule.
if (_currentRule is not null)
_filterOptions.Rules.Remove(_currentRule);
_currentRule = new LoggerFilterRule(null, null, level, null);
_filterOptions.Rules.Insert(0, _currentRule);
RefreshLoggerFilters();
}
/// <summary>
/// Asks the LoggerFactory to recompute each logger's effective filters.
/// LoggerFactory exposes no public API for this (the public AddFilter
/// extension was removed in .NET 10), so we invoke the internal
/// RefreshFilters method via reflection. Best effort: if the shape ever
/// changes, the rules are still in place and take effect on next restart.
/// </summary>
private void RefreshLoggerFilters()
{
try
{
var factoryType = _loggerFactory.GetType();
var refresh = factoryType.GetMethod(
"RefreshFilters",
BindingFlags.Instance | BindingFlags.NonPublic);
if (refresh is null || refresh.GetParameters().Length != 1)
return;
refresh.Invoke(_loggerFactory, [_filterOptions]);
}
catch (Exception)
{
// Rules are already in place; they apply on next logger creation.
}
}
}
@@ -2,6 +2,7 @@ using System.Reflection;
using Heimdall.Agent.Services;
using Heimdall.Application.DTOs;
using Heimdall.Application.Security;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using NSubstitute;
@@ -10,7 +11,11 @@ namespace Heimdall.Agent.Tests;
public class ConfigReceiverServiceTests
{
private static ConfigReceiverService CreateService(AgentState? state = null, AgentCredentialStore? store = null)
private static ConfigReceiverService CreateService(
AgentState? state = null,
AgentCredentialStore? store = null,
RuntimeLogLevel? runtimeLogLevel = null,
IHttpClientFactory? httpFactory = null)
{
state ??= new AgentState { AgentId = Guid.Empty };
var options = Options.Create(new AgentOptions
@@ -19,9 +24,29 @@ public class ConfigReceiverServiceTests
SiteToken = "test"
});
var logger = Substitute.For<ILogger<ConfigReceiverService>>();
var httpFactory = Substitute.For<IHttpClientFactory>();
httpFactory ??= Substitute.For<IHttpClientFactory>();
var scanTrigger = new DiscoveryScanTrigger();
return new ConfigReceiverService(state, options, logger, httpFactory, scanTrigger, store ?? new AgentCredentialStore());
runtimeLogLevel ??= CreateRuntimeLogLevel().Runtime;
return new ConfigReceiverService(state, options, logger, httpFactory, scanTrigger, store ?? new AgentCredentialStore(), runtimeLogLevel);
}
/// <summary>
/// Builds a RuntimeLogLevel sharing the exact LoggerFilterOptions instance
/// used by its LoggerFactory — mirrors the production DI wiring and makes
/// live log-level changes observable on existing loggers.
/// </summary>
private static (RuntimeLogLevel Runtime, ILoggerFactory Factory) CreateRuntimeLogLevel(List<string>? captured = null)
{
var services = new ServiceCollection();
services.AddLogging(builder =>
{
if (captured is not null)
builder.AddProvider(new ListLoggerProvider(captured));
});
var sp = services.BuildServiceProvider();
var factory = sp.GetRequiredService<ILoggerFactory>();
var options = sp.GetRequiredService<IOptions<LoggerFilterOptions>>();
return (new RuntimeLogLevel(factory, options), factory);
}
[Fact]
@@ -208,6 +233,141 @@ public class ConfigReceiverServiceTests
state.HeartbeatIntervalSeconds.ShouldBeNull();
}
[Fact]
public void ApplySetting_LogLevel_AppliesLive()
{
var state = new AgentState { AgentId = Guid.NewGuid(), ApiKey = "test-key" };
var runtime = CreateRuntimeLogLevel().Runtime;
var service = CreateService(state, runtimeLogLevel: runtime);
var method = typeof(ConfigReceiverService).GetMethod("ApplySetting",
BindingFlags.NonPublic | BindingFlags.Instance);
method.ShouldNotBeNull();
method.Invoke(service, ["log.level", "Warning"]);
// The setting is applied live to the shared runtime level (observable effect)
runtime.Level.ShouldBe(LogLevel.Warning);
}
[Fact]
public void ApplySetting_LogLevel_HasObservableEffectOnExistingLoggers()
{
var captured = new List<string>();
var (runtime, factory) = CreateRuntimeLogLevel(captured);
var state = new AgentState { AgentId = Guid.NewGuid(), ApiKey = "test-key" };
var service = CreateService(state, runtimeLogLevel: runtime);
var method = typeof(ConfigReceiverService).GetMethod("ApplySetting",
BindingFlags.NonPublic | BindingFlags.Instance);
method.ShouldNotBeNull();
// A logger created BEFORE the change…
var logger = factory.CreateLogger("Heimdall.Agent.SomeService");
logger.IsEnabled(LogLevel.Information).ShouldBeTrue();
logger.LogInformation("before-change");
// …must re-filter immediately after a remote log.level change.
method.Invoke(service, ["log.level", "Warning"]);
logger.IsEnabled(LogLevel.Information).ShouldBeFalse();
logger.IsEnabled(LogLevel.Warning).ShouldBeTrue();
// The real log pipeline reflects the new minimum: Information is
// dropped, Warning passes through.
logger.LogInformation("after-change-info");
logger.LogWarning("after-change-warning");
captured.ShouldNotContain(m => m.Contains("after-change-info", StringComparison.Ordinal));
captured.ShouldContain(m => m.Contains("after-change-warning", StringComparison.Ordinal));
}
[Fact]
public void ApplySetting_LogLevel_CanBeLoweredAgain()
{
var captured = new List<string>();
var (runtime, factory) = CreateRuntimeLogLevel(captured);
var state = new AgentState { AgentId = Guid.NewGuid(), ApiKey = "test-key" };
var service = CreateService(state, runtimeLogLevel: runtime);
var method = typeof(ConfigReceiverService).GetMethod("ApplySetting",
BindingFlags.NonPublic | BindingFlags.Instance);
method.ShouldNotBeNull();
var logger = factory.CreateLogger("Heimdall.Agent.SomeService");
method.Invoke(service, ["log.level", "Warning"]);
logger.IsEnabled(LogLevel.Information).ShouldBeFalse();
// Lowering back to Debug must not be blocked by a stale Warning rule
method.Invoke(service, ["log.level", "Debug"]);
logger.IsEnabled(LogLevel.Debug).ShouldBeTrue();
}
[Fact]
public void ApplySetting_LogLevel_InvalidValue_KeepsCurrentLevel()
{
var runtime = CreateRuntimeLogLevel().Runtime;
var service = CreateService(runtimeLogLevel: runtime);
var method = typeof(ConfigReceiverService).GetMethod("ApplySetting",
BindingFlags.NonPublic | BindingFlags.Instance);
method.ShouldNotBeNull();
method.Invoke(service, ["log.level", "NotALevel"]);
runtime.Level.ShouldBe(LogLevel.Information);
}
[Fact]
public void ApplySetting_RestartRequiredKey_LogsExplicitly()
{
var state = new AgentState { AgentId = Guid.NewGuid(), ApiKey = "test-key" };
var service = CreateService(state);
var method = typeof(ConfigReceiverService).GetMethod("ApplySetting",
BindingFlags.NonPublic | BindingFlags.Instance);
method.ShouldNotBeNull();
Record.Exception(() => method.Invoke(service, ["ai.detection.enabled", "true"]))
.ShouldBeNull();
}
[Fact]
public async Task FetchFullConfigAsync_AppliesAllSettings()
{
const string apiKey = "test-agent-api-key";
var state = new AgentState { AgentId = Guid.NewGuid(), ApiKey = apiKey };
var store = new AgentCredentialStore();
var runtime = CreateRuntimeLogLevel().Runtime;
var key = AgentCredentialEnvelope.DeriveKeyFromApiKey(apiKey);
var envelope = AgentCredentialEnvelope.Encrypt(
[new AgentCameraCredential("admin", "admin", "secret")], key);
var json = $$"""
{
"heartbeat.interval.seconds": "60",
"log.level": "Warning",
"ai.detection.enabled": "true",
"discovery.credentials": "{{envelope}}"
}
""";
var httpFactory = Substitute.For<IHttpClientFactory>();
httpFactory.CreateClient("Central").Returns(new HttpClient(new StubHttpMessageHandler(json)));
var service = CreateService(state, store, runtime, httpFactory);
var method = typeof(ConfigReceiverService).GetMethod("FetchFullConfigAsync",
BindingFlags.NonPublic | BindingFlags.Instance);
method.ShouldNotBeNull();
await (Task)method.Invoke(service, [CancellationToken.None])!;
// Heartbeat applied live from full reload
state.HeartbeatIntervalSeconds.ShouldBe(60);
// Log level applied live from full reload
runtime.Level.ShouldBe(LogLevel.Warning);
// Credential pool decrypted and stored from full reload
store.Pool.Count.ShouldBe(1);
store.Pool[0].Password.ShouldBe("secret");
}
[Fact]
public async Task StartStop_MultipleTimes_DoesNotThrow()
{
@@ -222,4 +382,55 @@ public class ConfigReceiverServiceTests
await service.StartAsync(CancellationToken.None);
await service.StopAsync(CancellationToken.None);
}
/// <summary>Returns a fixed JSON body for any request (used to stub the Central config API).</summary>
private sealed class StubHttpMessageHandler : HttpMessageHandler
{
private readonly string _json;
public StubHttpMessageHandler(string json) => _json = json;
protected override Task<HttpResponseMessage> SendAsync(
HttpRequestMessage request, CancellationToken cancellationToken)
{
var response = new HttpResponseMessage(System.Net.HttpStatusCode.OK)
{
Content = new StringContent(_json, System.Text.Encoding.UTF8, "application/json")
};
return Task.FromResult(response);
}
}
/// <summary>Captures formatted log messages for assertions (in-memory, no sinks).</summary>
private sealed class ListLoggerProvider : ILoggerProvider
{
private readonly List<string> _captured;
public ListLoggerProvider(List<string> captured) => _captured = captured;
public ILogger CreateLogger(string categoryName) => new ListLogger(_captured);
public void Dispose() { }
private sealed class ListLogger : ILogger
{
private readonly List<string> _captured;
public ListLogger(List<string> captured) => _captured = captured;
public IDisposable? BeginScope<TState>(TState state) where TState : notnull => null;
public bool IsEnabled(LogLevel logLevel) => true;
public void Log<TState>(
LogLevel logLevel,
EventId eventId,
TState state,
Exception? exception,
Func<TState, Exception?, string> formatter)
{
_captured.Add(formatter(state, exception));
}
}
}
}