From ab705e72fa79169cc28b3f2620a6ec9d53dcde38 Mon Sep 17 00:00:00 2001 From: Arnaud Dartois Date: Tue, 11 Aug 2026 17:34:22 +0200 Subject: [PATCH] =?UTF-8?q?fix(agent):=20settings=20distants=20appliqu?= =?UTF-8?q?=C3=A9s=20=C3=A0=20chaud=20=E2=80=94=20log.level=20live=20+=20f?= =?UTF-8?q?ull=20reload=20complet=20(Fixes=20#20)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 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) --- src/Heimdall.Agent/Program.cs | 1 + .../Services/ConfigReceiverService.cs | 50 +++- .../Services/RuntimeLogLevel.cs | 88 +++++++ .../ConfigReceiverServiceTests.cs | 217 +++++++++++++++++- 4 files changed, 348 insertions(+), 8 deletions(-) create mode 100644 src/Heimdall.Agent/Services/RuntimeLogLevel.cs diff --git a/src/Heimdall.Agent/Program.cs b/src/Heimdall.Agent/Program.cs index 68f5a79..3a829e0 100644 --- a/src/Heimdall.Agent/Program.cs +++ b/src/Heimdall.Agent/Program.cs @@ -64,6 +64,7 @@ builder.Services.AddSingleton(); builder.Services.AddSingleton(); builder.Services.AddSingleton(); builder.Services.AddSingleton(); +builder.Services.AddSingleton(); builder.Services.AddHostedService(); builder.Services.AddHostedService(); builder.Services.AddHostedService(); diff --git a/src/Heimdall.Agent/Services/ConfigReceiverService.cs b/src/Heimdall.Agent/Services/ConfigReceiverService.cs index 90abb7f..53698b1 100644 --- a/src/Heimdall.Agent/Services/ConfigReceiverService.cs +++ b/src/Heimdall.Agent/Services/ConfigReceiverService.cs @@ -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; + /// + /// 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. + /// + private static readonly HashSet RestartRequiredPrefixes = + new(StringComparer.OrdinalIgnoreCase) + { + "ai.detection.", + "detection.", + "model.", + "ffmpeg.", + "yolo.", + "camera.", + }; + public ConfigReceiverService( AgentState state, IOptions options, ILogger 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(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) { diff --git a/src/Heimdall.Agent/Services/RuntimeLogLevel.cs b/src/Heimdall.Agent/Services/RuntimeLogLevel.cs new file mode 100644 index 0000000..d8f60ab --- /dev/null +++ b/src/Heimdall.Agent/Services/RuntimeLogLevel.cs @@ -0,0 +1,88 @@ +using System.Reflection; +using Microsoft.Extensions.Logging; +using Microsoft.Extensions.Options; + +namespace Heimdall.Agent.Services; + +/// +/// Holds the agent's current minimum log level and applies it live to the +/// shared 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. +/// +/// +/// 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. +/// +public sealed class RuntimeLogLevel +{ + private readonly ILoggerFactory _loggerFactory; + private readonly LoggerFilterOptions _filterOptions; + private readonly IReadOnlyList _originalRules; + private LoggerFilterRule? _currentRule; + + public RuntimeLogLevel(ILoggerFactory loggerFactory, IOptions 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(); + } + + /// Current minimum level applied to all loggers. + public LogLevel Level { get; private set; } = LogLevel.Information; + + /// + /// 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. + /// + 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(); + } + + /// + /// 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. + /// + 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. + } + } +} diff --git a/tests/Heimdall.Agent.Tests/ConfigReceiverServiceTests.cs b/tests/Heimdall.Agent.Tests/ConfigReceiverServiceTests.cs index 9c2b4d7..1170fee 100644 --- a/tests/Heimdall.Agent.Tests/ConfigReceiverServiceTests.cs +++ b/tests/Heimdall.Agent.Tests/ConfigReceiverServiceTests.cs @@ -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>(); - var httpFactory = Substitute.For(); + httpFactory ??= Substitute.For(); 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); + } + + /// + /// 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. + /// + private static (RuntimeLogLevel Runtime, ILoggerFactory Factory) CreateRuntimeLogLevel(List? 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(); + var options = sp.GetRequiredService>(); + 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(); + 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(); + 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(); + 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); } + + /// Returns a fixed JSON body for any request (used to stub the Central config API). + private sealed class StubHttpMessageHandler : HttpMessageHandler + { + private readonly string _json; + + public StubHttpMessageHandler(string json) => _json = json; + + protected override Task 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); + } + } + + /// Captures formatted log messages for assertions (in-memory, no sinks). + private sealed class ListLoggerProvider : ILoggerProvider + { + private readonly List _captured; + + public ListLoggerProvider(List captured) => _captured = captured; + + public ILogger CreateLogger(string categoryName) => new ListLogger(_captured); + + public void Dispose() { } + + private sealed class ListLogger : ILogger + { + private readonly List _captured; + + public ListLogger(List captured) => _captured = captured; + + public IDisposable? BeginScope(TState state) where TState : notnull => null; + + public bool IsEnabled(LogLevel logLevel) => true; + + public void Log( + LogLevel logLevel, + EventId eventId, + TState state, + Exception? exception, + Func formatter) + { + _captured.Add(formatter(state, exception)); + } + } + } }