fix(agent): dispatch manual update checks #18
No files matched your search
@@ -149,7 +149,8 @@ builder.Services.AddSingleton<AgentUpdateService>();
|
||||
builder.Services.AddHostedService(sp => sp.GetRequiredService<AgentUpdateService>());
|
||||
|
||||
// Docker auto-update (ticket #97)
|
||||
builder.Services.AddHostedService<DockerUpdateService>();
|
||||
builder.Services.AddSingleton<DockerUpdateService>();
|
||||
builder.Services.AddHostedService(sp => sp.GetRequiredService<DockerUpdateService>());
|
||||
|
||||
// Health checks — used by Docker HEALTHCHECK
|
||||
builder.Services.AddHealthChecks()
|
||||
|
||||
@@ -18,17 +18,27 @@ public sealed class AgentUpdateService : BackgroundService
|
||||
private readonly IOptions<AgentOptions> _options;
|
||||
private readonly IHttpClientFactory _httpClientFactory;
|
||||
private readonly ILogger<AgentUpdateService> _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<AgentOptions> options,
|
||||
IHttpClientFactory httpClientFactory, ILogger<AgentUpdateService> logger)
|
||||
{ _state = state; _options = options; _httpClientFactory = httpClientFactory; _logger = logger; }
|
||||
IHttpClientFactory httpClientFactory, ILogger<AgentUpdateService> logger, ContainerInfoProvider containerInfo)
|
||||
{ _state = state; _options = options; _httpClientFactory = httpClientFactory; _logger = logger; _containerInfo = containerInfo; }
|
||||
|
||||
public void SetCapturing(bool capturing) => _isCapturing = capturing;
|
||||
|
||||
/// <summary>Runs an update check immediately when requested by Central.</summary>
|
||||
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<LatestReleaseResponse>(Json, ct);
|
||||
}
|
||||
|
||||
@@ -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<string, string>("SettingChanged", async (key, value) =>
|
||||
|
||||
@@ -35,9 +35,21 @@ public sealed class DockerUpdateService : BackgroundService
|
||||
}
|
||||
}
|
||||
|
||||
private async Task CheckAndUpdateAsync(ContainerInfo info, CancellationToken ct)
|
||||
/// <summary>Runs a Docker image update check immediately when requested by Central.</summary>
|
||||
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<LatestUpdateResponse>(ct); return u?.Version; }
|
||||
if (r.StatusCode == System.Net.HttpStatusCode.NotFound)
|
||||
{
|
||||
|
||||
@@ -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<bool> RequestAgentUpdate(Guid agentId, CancellationToken ct = default);
|
||||
Task NotifyAllAgentsReload(CancellationToken ct = default);
|
||||
}
|
||||
@@ -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<UpdatesController> _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<UpdatesController> logger)
|
||||
public UpdatesController(IHttpClientFactory httpClientFactory, ILogger<UpdatesController> 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);
|
||||
}
|
||||
|
||||
/// <summary>Release manifest for a registered agent authenticated with its API key.</summary>
|
||||
[Authorize(AuthenticationSchemes = "ApiKey")]
|
||||
[HttpGet("agent/latest")]
|
||||
[ProducesResponseType(typeof(LatestReleaseResponse), StatusCodes.Status200OK)]
|
||||
public async Task<IActionResult> 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<IActionResult> 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<LatestReleaseResponse?> FetchLatestReleaseAsync(CancellationToken ct)
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
|
||||
/// <summary>Requests an immediate update check from connected, authorized agents.</summary>
|
||||
public async Task<bool> RequestAgentUpdate(Guid agentId, CancellationToken ct = default)
|
||||
{
|
||||
using var scope = _scopeFactory.CreateScope();
|
||||
var services = scope.ServiceProvider;
|
||||
var access = services.GetRequiredService<ResourceAccess>();
|
||||
var subscriptions = services.GetRequiredService<LiveSubscriptions>();
|
||||
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;
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public async Task NotifyAllAgentsReload(CancellationToken ct = default)
|
||||
{
|
||||
|
||||
@@ -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<IHttpClientFactory>();
|
||||
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<ILogger<AgentUpdateService>>(), 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();
|
||||
}
|
||||
}
|
||||
@@ -33,7 +33,11 @@ public class ConfigReceiverServiceTests
|
||||
httpFactory ??= Substitute.For<IHttpClientFactory>();
|
||||
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<ILogger<AgentUpdateService>>(), new ContainerInfoProvider());
|
||||
var dockerUpdateService = new DockerUpdateService(options, state, new ContainerInfoProvider(), httpFactory,
|
||||
Substitute.For<ILogger<DockerUpdateService>>());
|
||||
return new ConfigReceiverService(state, options, logger, httpFactory, scanTrigger, store ?? new AgentCredentialStore(), runtimeLogLevel, cameraStore ?? new CameraConfigStore(), updateService, dockerUpdateService, new ContainerInfoProvider());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
|
||||
Reference in new issue
Block a user