diff --git a/src/Heimdall.Agent/Program.cs b/src/Heimdall.Agent/Program.cs index eabc10a..d71eaf6 100644 --- a/src/Heimdall.Agent/Program.cs +++ b/src/Heimdall.Agent/Program.cs @@ -149,7 +149,8 @@ builder.Services.AddSingleton(); builder.Services.AddHostedService(sp => sp.GetRequiredService()); // Docker auto-update (ticket #97) -builder.Services.AddHostedService(); +builder.Services.AddSingleton(); +builder.Services.AddHostedService(sp => sp.GetRequiredService()); // Health checks — used by Docker HEALTHCHECK builder.Services.AddHealthChecks() diff --git a/src/Heimdall.Agent/Services/AgentUpdateService.cs b/src/Heimdall.Agent/Services/AgentUpdateService.cs index 1c9ebcb..0e32eea 100644 --- a/src/Heimdall.Agent/Services/AgentUpdateService.cs +++ b/src/Heimdall.Agent/Services/AgentUpdateService.cs @@ -18,17 +18,27 @@ public sealed class AgentUpdateService : BackgroundService private readonly IOptions _options; private readonly IHttpClientFactory _httpClientFactory; private readonly ILogger _logger; + private readonly ContainerInfoProvider _containerInfo; + private readonly SemaphoreSlim _updateLock = new(1, 1); private static readonly JsonSerializerOptions Json = new() { PropertyNameCaseInsensitive = true }; private volatile bool _isCapturing; public AgentUpdateService(AgentState state, IOptions options, - IHttpClientFactory httpClientFactory, ILogger logger) - { _state = state; _options = options; _httpClientFactory = httpClientFactory; _logger = logger; } + IHttpClientFactory httpClientFactory, ILogger logger, ContainerInfoProvider containerInfo) + { _state = state; _options = options; _httpClientFactory = httpClientFactory; _logger = logger; _containerInfo = containerInfo; } public void SetCapturing(bool capturing) => _isCapturing = capturing; + /// Runs an update check immediately when requested by Central. + public Task RequestUpdateAsync(CancellationToken ct = default) => CheckAndApplyUpdateAsync(ct); + protected override async Task ExecuteAsync(CancellationToken stoppingToken) { + if (_containerInfo.Collect().IsContainer) + { + _logger.LogInformation("Native binary updater disabled in a container; Docker updater owns container updates"); + return; + } while (_state.AgentId == Guid.Empty && !stoppingToken.IsCancellationRequested) await Task.Delay(1000, stoppingToken); if (stoppingToken.IsCancellationRequested) return; @@ -47,6 +57,19 @@ public sealed class AgentUpdateService : BackgroundService } private async Task CheckAndApplyUpdateAsync(CancellationToken ct) + { + await _updateLock.WaitAsync(ct); + try + { + await CheckAndApplyUpdateCoreAsync(ct); + } + finally + { + _updateLock.Release(); + } + } + + private async Task CheckAndApplyUpdateCoreAsync(CancellationToken ct) { if (_isCapturing) { _logger.LogDebug("Capture active, deferring update"); return; } _logger.LogInformation("Checking for updates..."); @@ -83,7 +106,7 @@ public sealed class AgentUpdateService : BackgroundService using var client = _httpClientFactory.CreateClient("Central"); client.DefaultRequestHeaders.Remove("X-API-Key"); client.DefaultRequestHeaders.Add("X-API-Key", _state.ApiKey); - var response = await client.GetAsync("api/updates/latest", ct); + var response = await client.GetAsync("api/updates/agent/latest", ct); if (!response.IsSuccessStatusCode) return null; return await response.Content.ReadFromJsonAsync(Json, ct); } diff --git a/src/Heimdall.Agent/Services/ConfigReceiverService.cs b/src/Heimdall.Agent/Services/ConfigReceiverService.cs index a0e51e7..a028e50 100644 --- a/src/Heimdall.Agent/Services/ConfigReceiverService.cs +++ b/src/Heimdall.Agent/Services/ConfigReceiverService.cs @@ -21,6 +21,9 @@ public sealed class ConfigReceiverService : BackgroundService private readonly AgentCredentialStore _credentialStore; private readonly RuntimeLogLevel _runtimeLogLevel; private readonly CameraConfigStore _cameraStore; + private readonly AgentUpdateService _updateService; + private readonly DockerUpdateService _dockerUpdateService; + private readonly ContainerInfoProvider _containerInfo; private HubConnection? _connection; private readonly SemaphoreSlim _reloadLock = new(1, 1); @@ -48,7 +51,10 @@ public sealed class ConfigReceiverService : BackgroundService DiscoveryScanTrigger scanTrigger, AgentCredentialStore credentialStore, RuntimeLogLevel runtimeLogLevel, - CameraConfigStore cameraStore) + CameraConfigStore cameraStore, + AgentUpdateService updateService, + DockerUpdateService dockerUpdateService, + ContainerInfoProvider containerInfo) { _state = state; _options = options.Value; @@ -58,6 +64,9 @@ public sealed class ConfigReceiverService : BackgroundService _credentialStore = credentialStore; _runtimeLogLevel = runtimeLogLevel; _cameraStore = cameraStore; + _updateService = updateService; + _dockerUpdateService = dockerUpdateService; + _containerInfo = containerInfo; } protected override async Task ExecuteAsync(CancellationToken stoppingToken) @@ -81,6 +90,9 @@ public sealed class ConfigReceiverService : BackgroundService .Build(); _connection.On("DiscoveryScanRequested", () => _scanTrigger.Trigger()); + _connection.On("AgentUpdateRequested", () => _containerInfo.Collect().IsContainer + ? _dockerUpdateService.RequestUpdateAsync(stoppingToken) + : _updateService.RequestUpdateAsync(stoppingToken)); // Listen for setting changes _connection.On("SettingChanged", async (key, value) => diff --git a/src/Heimdall.Agent/Services/DockerUpdateService.cs b/src/Heimdall.Agent/Services/DockerUpdateService.cs index ecc13f2..c6b6e98 100644 --- a/src/Heimdall.Agent/Services/DockerUpdateService.cs +++ b/src/Heimdall.Agent/Services/DockerUpdateService.cs @@ -35,9 +35,21 @@ public sealed class DockerUpdateService : BackgroundService } } - private async Task CheckAndUpdateAsync(ContainerInfo info, CancellationToken ct) + /// Runs a Docker image update check immediately when requested by Central. + public Task RequestUpdateAsync(CancellationToken ct = default) { - if (!_options.AutoUpdateEnabled) return; + var info = _containerInfo.Collect(); + if (!info.IsContainer) + { + _logger.LogWarning("Received Docker update request outside a container"); + return Task.CompletedTask; + } + return CheckAndUpdateAsync(info, ct, force: true); + } + + private async Task CheckAndUpdateAsync(ContainerInfo info, CancellationToken ct, bool force = false) + { + if (!force && !_options.AutoUpdateEnabled) return; if (_state.AgentId == Guid.Empty || string.IsNullOrEmpty(_state.ApiKey)) return; _logger.LogInformation("Checking for agent updates..."); var latest = await FetchLatestVersionAsync(ct).ConfigureAwait(false); @@ -91,7 +103,7 @@ public sealed class DockerUpdateService : BackgroundService using var http = _httpClientFactory.CreateClient("Central"); http.DefaultRequestHeaders.Remove("X-API-Key"); http.DefaultRequestHeaders.Add("X-API-Key", _state.ApiKey); - var r = await http.GetAsync(_options.CentralUrl.TrimEnd('/') + "/api/updates/latest", ct); + var r = await http.GetAsync(_options.CentralUrl.TrimEnd('/') + "/api/updates/agent/latest", ct); if (r.IsSuccessStatusCode) { var u = await r.Content.ReadFromJsonAsync(ct); return u?.Version; } if (r.StatusCode == System.Net.HttpStatusCode.NotFound) { diff --git a/src/Heimdall.Application/Services/IConfigBroadcastService.cs b/src/Heimdall.Application/Services/IConfigBroadcastService.cs index b78dc91..a430902 100644 --- a/src/Heimdall.Application/Services/IConfigBroadcastService.cs +++ b/src/Heimdall.Application/Services/IConfigBroadcastService.cs @@ -4,5 +4,6 @@ public interface IConfigBroadcastService { Task NotifyGlobalSettingChanged(string key, string value, CancellationToken ct = default); Task NotifyAgentSettingChanged(Guid agentId, string key, string value, CancellationToken ct = default); + Task RequestAgentUpdate(Guid agentId, CancellationToken ct = default); Task NotifyAllAgentsReload(CancellationToken ct = default); } diff --git a/src/Heimdall.Web/Controllers/UpdatesController.cs b/src/Heimdall.Web/Controllers/UpdatesController.cs index f81cede..f807be5 100644 --- a/src/Heimdall.Web/Controllers/UpdatesController.cs +++ b/src/Heimdall.Web/Controllers/UpdatesController.cs @@ -2,6 +2,8 @@ using System.Net.Http.Json; using System.Text.Json; using System.Text.Json.Serialization; using Heimdall.Infrastructure.Security; +using Heimdall.Application.Services; +using Heimdall.Api.Security; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.RateLimiting; @@ -15,6 +17,8 @@ public class UpdatesController : ControllerBase { private readonly IHttpClientFactory _httpClientFactory; private readonly ILogger _logger; + private readonly IConfigBroadcastService _configBroadcast; + private readonly ResourceAccess _resourceAccess; private static readonly JsonSerializerOptions Json = new() { @@ -28,10 +32,13 @@ public class UpdatesController : ControllerBase private const string ForgejoApiUrl = "https://forgejo.tordais.cc/api/v1/repos/nonobis/Heimdall/releases/latest"; - public UpdatesController(IHttpClientFactory httpClientFactory, ILogger logger) + public UpdatesController(IHttpClientFactory httpClientFactory, ILogger logger, + IConfigBroadcastService configBroadcast, ResourceAccess resourceAccess) { _httpClientFactory = httpClientFactory; _logger = logger; + _configBroadcast = configBroadcast; + _resourceAccess = resourceAccess; } [Authorize(AuthenticationSchemes = "JwtBearer,Cookies", Policy = AppPermissions.SiteRead)] @@ -53,19 +60,38 @@ public class UpdatesController : ControllerBase return Ok(result); } + /// Release manifest for a registered agent authenticated with its API key. + [Authorize(AuthenticationSchemes = "ApiKey")] + [HttpGet("agent/latest")] + [ProducesResponseType(typeof(LatestReleaseResponse), StatusCodes.Status200OK)] + public async Task GetLatestReleaseForAgent(CancellationToken ct) + { + var requester = await _resourceAccess.ResolveAsync(User, ct); + if (requester is null || requester.Kind != RequesterKind.Agent) return Forbid(); + var cached = GetCached(); + if (cached is not null && !IsStale(cached)) return Ok(cached.Response); + if (cached is not null) + { + _ = RefreshCacheAsync(ct); + return Ok(cached.Response); + } + var result = await FetchLatestReleaseAsync(ct); + return result is null ? StatusCode(502, new { error = "Failed to fetch release info" }) : Ok(result); + } + [Authorize(AuthenticationSchemes = "JwtBearer,Cookies", Policy = AppPermissions.SiteWrite)] [HttpPost("agents/{id:guid}/update")] - [ProducesResponseType(typeof(LatestReleaseResponse), StatusCodes.Status200OK)] + [ProducesResponseType(StatusCodes.Status202Accepted)] public async Task TriggerAgentUpdate(Guid id, CancellationToken ct) { - _logger.LogInformation("Update triggered for agent {AgentId}", id); + _logger.LogInformation("Manual update requested for agent {AgentId}", id); var cached = GetCached(); - if (cached is not null && !IsStale(cached)) - return Ok(cached.Response); - var result = await FetchLatestReleaseAsync(ct); - if (result is null) + var release = cached is not null && !IsStale(cached) ? cached.Response : await FetchLatestReleaseAsync(ct); + if (release is null) return StatusCode(502, new { error = "Failed to fetch release info" }); - return Ok(result); + if (!await _configBroadcast.RequestAgentUpdate(id, ct)) + return Conflict(new { error = "Agent is not connected to the configuration channel", agentId = id }); + return Accepted(new { agentId = id, command = "update-check", dispatched = true, release }); } private async Task FetchLatestReleaseAsync(CancellationToken ct) diff --git a/src/Heimdall.Web/Hubs/ConfigHub.cs b/src/Heimdall.Web/Hubs/ConfigHub.cs index 72fbbf2..f6fdc22 100644 --- a/src/Heimdall.Web/Hubs/ConfigHub.cs +++ b/src/Heimdall.Web/Hubs/ConfigHub.cs @@ -119,6 +119,21 @@ public class ConfigBroadcastService : IConfigBroadcastService await _hubContext.Clients.Clients(await subscriptions.AuthorizedAsync("config", $"agent_{agentId}", access, r => access.AgentAsync(r, agentId, ct), ct)).SendAsync("SettingChanged", key, value, ct); } + /// Requests an immediate update check from connected, authorized agents. + public async Task RequestAgentUpdate(Guid agentId, CancellationToken ct = default) + { + using var scope = _scopeFactory.CreateScope(); + var services = scope.ServiceProvider; + var access = services.GetRequiredService(); + var subscriptions = services.GetRequiredService(); + var recipients = await subscriptions.AuthorizedAsync("config", $"agent_{agentId}", access, + r => access.AgentAsync(r, agentId, ct), ct); + if (recipients.Count == 0) return false; + await _hubContext.Clients.Clients(recipients).SendAsync("AgentUpdateRequested", ct); + _logger.LogInformation("Requested update check from agent {AgentId}", agentId); + return true; + } + /// public async Task NotifyAllAgentsReload(CancellationToken ct = default) { diff --git a/tests/Heimdall.Agent.Tests/AgentUpdateServiceTests.cs b/tests/Heimdall.Agent.Tests/AgentUpdateServiceTests.cs new file mode 100644 index 0000000..6fba891 --- /dev/null +++ b/tests/Heimdall.Agent.Tests/AgentUpdateServiceTests.cs @@ -0,0 +1,42 @@ +using System.Net; +using System.Reflection; +using Heimdall.Agent.Services; +using Microsoft.Extensions.Logging; +using Microsoft.Extensions.Options; +using NSubstitute; +using Shouldly; + +namespace Heimdall.Agent.Tests; + +public sealed class AgentUpdateServiceTests +{ + [Fact] + public async Task FetchLatestRelease_UsesAgentApiKeyManifestEndpoint() + { + HttpRequestMessage? sent = null; + var handler = new MockHttpMessageHandler(request => + { + sent = request; + return new HttpResponseMessage(HttpStatusCode.OK) + { + Content = new StringContent("{\"version\":\"1.2.3\",\"assets\":{}}") + }; + }); + var client = new HttpClient(handler) { BaseAddress = new Uri("https://central.example/") }; + var factory = Substitute.For(); + factory.CreateClient("Central").Returns(client); + var state = new AgentState { AgentId = Guid.NewGuid(), ApiKey = "agent-key" }; + var service = new AgentUpdateService(state, Options.Create(new AgentOptions()), factory, + Substitute.For>(), new ContainerInfoProvider()); + + var fetch = typeof(AgentUpdateService).GetMethod("FetchLatestReleaseAsync", + BindingFlags.Instance | BindingFlags.NonPublic)!; + var task = (Task)fetch.Invoke(service, [CancellationToken.None])!; + await task; + + sent.ShouldNotBeNull(); + sent.RequestUri!.AbsolutePath.ShouldBe("/api/updates/agent/latest"); + sent.Headers.GetValues("X-API-Key").Single().ShouldBe("agent-key"); + task.GetType().GetProperty("Result")!.GetValue(task).ShouldNotBeNull(); + } +} diff --git a/tests/Heimdall.Agent.Tests/ConfigReceiverServiceTests.cs b/tests/Heimdall.Agent.Tests/ConfigReceiverServiceTests.cs index e8816f9..c094fd7 100644 --- a/tests/Heimdall.Agent.Tests/ConfigReceiverServiceTests.cs +++ b/tests/Heimdall.Agent.Tests/ConfigReceiverServiceTests.cs @@ -33,7 +33,11 @@ public class ConfigReceiverServiceTests httpFactory ??= Substitute.For(); var scanTrigger = new DiscoveryScanTrigger(); runtimeLogLevel ??= CreateRuntimeLogLevel().Runtime; - return new ConfigReceiverService(state, options, logger, httpFactory, scanTrigger, store ?? new AgentCredentialStore(), runtimeLogLevel, cameraStore ?? new CameraConfigStore()); + var updateService = new AgentUpdateService(state, options, httpFactory, + Substitute.For>(), new ContainerInfoProvider()); + var dockerUpdateService = new DockerUpdateService(options, state, new ContainerInfoProvider(), httpFactory, + Substitute.For>()); + return new ConfigReceiverService(state, options, logger, httpFactory, scanTrigger, store ?? new AgentCredentialStore(), runtimeLogLevel, cameraStore ?? new CameraConfigStore(), updateService, dockerUpdateService, new ContainerInfoProvider()); } ///