2026-08-27 18:56:57 +02:00
|
|
|
using System.Net.Http.Json;
|
|
|
|
|
using System.Runtime.InteropServices;
|
|
|
|
|
using System.Security.Cryptography;
|
|
|
|
|
using System.Text.Json;
|
|
|
|
|
using System.Text.Json.Serialization;
|
|
|
|
|
using Microsoft.Extensions.Options;
|
|
|
|
|
|
|
|
|
|
namespace Heimdall.Agent.Services;
|
|
|
|
|
|
|
|
|
|
/// <summary>
|
|
|
|
|
/// Background service that periodically checks the Central server for new releases
|
|
|
|
|
/// and auto-updates the agent binary when a newer version is available (native mode).
|
|
|
|
|
/// Skipped when AutoUpdateEnabled is false or when the capture pipeline is active.
|
|
|
|
|
/// </summary>
|
|
|
|
|
public sealed class AgentUpdateService : BackgroundService
|
|
|
|
|
{
|
|
|
|
|
private readonly AgentState _state;
|
|
|
|
|
private readonly IOptions<AgentOptions> _options;
|
|
|
|
|
private readonly IHttpClientFactory _httpClientFactory;
|
|
|
|
|
private readonly ILogger<AgentUpdateService> _logger;
|
2026-10-21 09:20:07 +02:00
|
|
|
private readonly ContainerInfoProvider _containerInfo;
|
|
|
|
|
private readonly SemaphoreSlim _updateLock = new(1, 1);
|
2026-08-27 18:56:57 +02:00
|
|
|
private static readonly JsonSerializerOptions Json = new() { PropertyNameCaseInsensitive = true };
|
|
|
|
|
private volatile bool _isCapturing;
|
|
|
|
|
|
|
|
|
|
public AgentUpdateService(AgentState state, IOptions<AgentOptions> options,
|
2026-10-21 09:20:07 +02:00
|
|
|
IHttpClientFactory httpClientFactory, ILogger<AgentUpdateService> logger, ContainerInfoProvider containerInfo)
|
|
|
|
|
{ _state = state; _options = options; _httpClientFactory = httpClientFactory; _logger = logger; _containerInfo = containerInfo; }
|
2026-08-27 18:56:57 +02:00
|
|
|
|
|
|
|
|
public void SetCapturing(bool capturing) => _isCapturing = capturing;
|
|
|
|
|
|
2026-10-21 09:20:07 +02:00
|
|
|
/// <summary>Runs an update check immediately when requested by Central.</summary>
|
|
|
|
|
public Task RequestUpdateAsync(CancellationToken ct = default) => CheckAndApplyUpdateAsync(ct);
|
|
|
|
|
|
2026-08-27 18:56:57 +02:00
|
|
|
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
|
|
|
|
|
{
|
2026-10-21 09:20:07 +02:00
|
|
|
if (_containerInfo.Collect().IsContainer)
|
|
|
|
|
{
|
|
|
|
|
_logger.LogInformation("Native binary updater disabled in a container; Docker updater owns container updates");
|
|
|
|
|
return;
|
|
|
|
|
}
|
2026-08-27 18:56:57 +02:00
|
|
|
while (_state.AgentId == Guid.Empty && !stoppingToken.IsCancellationRequested)
|
|
|
|
|
await Task.Delay(1000, stoppingToken);
|
|
|
|
|
if (stoppingToken.IsCancellationRequested) return;
|
|
|
|
|
var intervalHours = _options.Value.UpdateCheckIntervalHours;
|
|
|
|
|
if (intervalHours <= 0) { _logger.LogInformation("Auto-update disabled (interval <= 0)"); return; }
|
|
|
|
|
var interval = TimeSpan.FromHours(intervalHours);
|
|
|
|
|
_logger.LogInformation("Auto-update check interval: {Interval}", interval);
|
|
|
|
|
await Task.Delay(TimeSpan.FromSeconds(30), stoppingToken);
|
|
|
|
|
while (!stoppingToken.IsCancellationRequested)
|
|
|
|
|
{
|
|
|
|
|
try { if (_options.Value.AutoUpdateEnabled) await CheckAndApplyUpdateAsync(stoppingToken); }
|
|
|
|
|
catch (OperationCanceledException) { break; }
|
|
|
|
|
catch (Exception ex) { _logger.LogError(ex, "Error during auto-update check"); }
|
|
|
|
|
await Task.Delay(interval, stoppingToken);
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
private async Task CheckAndApplyUpdateAsync(CancellationToken ct)
|
2026-10-21 09:20:07 +02:00
|
|
|
{
|
|
|
|
|
await _updateLock.WaitAsync(ct);
|
|
|
|
|
try
|
|
|
|
|
{
|
|
|
|
|
await CheckAndApplyUpdateCoreAsync(ct);
|
|
|
|
|
}
|
|
|
|
|
finally
|
|
|
|
|
{
|
|
|
|
|
_updateLock.Release();
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
private async Task CheckAndApplyUpdateCoreAsync(CancellationToken ct)
|
2026-08-27 18:56:57 +02:00
|
|
|
{
|
|
|
|
|
if (_isCapturing) { _logger.LogDebug("Capture active, deferring update"); return; }
|
|
|
|
|
_logger.LogInformation("Checking for updates...");
|
|
|
|
|
var release = await FetchLatestReleaseAsync(ct);
|
|
|
|
|
if (release is null) return;
|
|
|
|
|
var currentVersion = _options.Value.Version;
|
|
|
|
|
var remoteVersion = release.Version;
|
|
|
|
|
_logger.LogInformation("Current: v{Current}, Remote: v{Remote}", currentVersion, remoteVersion);
|
|
|
|
|
if (!IsNewerVersion(remoteVersion, currentVersion))
|
|
|
|
|
{ _logger.LogInformation("Up to date (v{Version})", currentVersion); return; }
|
|
|
|
|
_logger.LogInformation("New version available: v{Remote}", remoteVersion);
|
|
|
|
|
var platformKey = GetPlatformKey();
|
|
|
|
|
if (platformKey is null || !release.Assets.TryGetValue(platformKey, out var asset))
|
|
|
|
|
{ _logger.LogWarning("No binary for platform"); return; }
|
|
|
|
|
var currentBinaryPath = Environment.ProcessPath;
|
|
|
|
|
if (string.IsNullOrEmpty(currentBinaryPath)) return;
|
|
|
|
|
var tempPath = currentBinaryPath + ".update.tmp";
|
|
|
|
|
try
|
|
|
|
|
{
|
|
|
|
|
await DownloadAndVerifyAsync(asset.Url, asset.Sha256, tempPath, ct);
|
|
|
|
|
File.Move(currentBinaryPath, currentBinaryPath + ".bak", overwrite: true);
|
|
|
|
|
File.Move(tempPath, currentBinaryPath, overwrite: true);
|
|
|
|
|
_logger.LogInformation("Updated from v{Old} to v{New}. Restarting...", currentVersion, remoteVersion);
|
|
|
|
|
Environment.Exit(0);
|
|
|
|
|
}
|
|
|
|
|
catch (Exception ex)
|
|
|
|
|
{ _logger.LogError(ex, "Failed to apply update"); try { if (File.Exists(tempPath)) File.Delete(tempPath); } catch { } }
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
private async Task<LatestReleaseResponse?> FetchLatestReleaseAsync(CancellationToken ct)
|
|
|
|
|
{
|
|
|
|
|
try
|
|
|
|
|
{
|
|
|
|
|
using var client = _httpClientFactory.CreateClient("Central");
|
|
|
|
|
client.DefaultRequestHeaders.Remove("X-API-Key");
|
|
|
|
|
client.DefaultRequestHeaders.Add("X-API-Key", _state.ApiKey);
|
2026-10-21 09:20:07 +02:00
|
|
|
var response = await client.GetAsync("api/updates/agent/latest", ct);
|
2026-08-27 18:56:57 +02:00
|
|
|
if (!response.IsSuccessStatusCode) return null;
|
|
|
|
|
return await response.Content.ReadFromJsonAsync<LatestReleaseResponse>(Json, ct);
|
|
|
|
|
}
|
|
|
|
|
catch (Exception ex) { _logger.LogWarning(ex, "Error fetching release"); return null; }
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
private async Task DownloadAndVerifyAsync(string url, string? expectedSha256, string destPath, CancellationToken ct)
|
|
|
|
|
{
|
|
|
|
|
using var client = _httpClientFactory.CreateClient("Central");
|
|
|
|
|
client.Timeout = TimeSpan.FromMinutes(10);
|
|
|
|
|
var response = await client.GetAsync(url, ct);
|
|
|
|
|
response.EnsureSuccessStatusCode();
|
|
|
|
|
await using var rs = await response.Content.ReadAsStreamAsync(ct);
|
|
|
|
|
await using var fs = File.Create(destPath);
|
|
|
|
|
await rs.CopyToAsync(fs, ct);
|
|
|
|
|
await fs.FlushAsync(ct);
|
|
|
|
|
await fs.DisposeAsync();
|
|
|
|
|
if (!string.IsNullOrEmpty(expectedSha256))
|
|
|
|
|
{
|
|
|
|
|
var hashBytes = await SHA256.HashDataAsync(File.OpenRead(destPath), ct);
|
|
|
|
|
var hex = Convert.ToHexString(hashBytes).ToLowerInvariant();
|
|
|
|
|
if (!string.Equals(hex, expectedSha256, StringComparison.OrdinalIgnoreCase))
|
|
|
|
|
throw new InvalidOperationException($"SHA256 mismatch: expected {expectedSha256}, got {hex}");
|
|
|
|
|
_logger.LogInformation("SHA256 verified: {Hash}", hex);
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
private static bool IsNewerVersion(string remote, string current)
|
|
|
|
|
{
|
|
|
|
|
var r = ParseVersion(remote);
|
|
|
|
|
var c = ParseVersion(current);
|
|
|
|
|
if (r[0] != c[0]) return r[0] > c[0];
|
|
|
|
|
if (r[1] != c[1]) return r[1] > c[1];
|
|
|
|
|
return r[2] > c[2];
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
private static int[] ParseVersion(string version)
|
|
|
|
|
{
|
|
|
|
|
var clean = version.Split('-', '+')[0];
|
|
|
|
|
var parts = clean.Split('.', StringSplitOptions.RemoveEmptyEntries);
|
|
|
|
|
var result = new int[3];
|
|
|
|
|
for (var i = 0; i < Math.Min(parts.Length, 3); i++)
|
|
|
|
|
_ = int.TryParse(parts[i], out result[i]);
|
|
|
|
|
return result;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
private static string? GetPlatformKey()
|
|
|
|
|
{
|
|
|
|
|
var arch = RuntimeInformation.ProcessArchitecture;
|
|
|
|
|
var isWin = RuntimeInformation.IsOSPlatform(OSPlatform.Windows);
|
|
|
|
|
var isLinux = RuntimeInformation.IsOSPlatform(OSPlatform.Linux);
|
|
|
|
|
var isMac = RuntimeInformation.IsOSPlatform(OSPlatform.OSX);
|
|
|
|
|
return (arch, isWin, isLinux, isMac) switch
|
|
|
|
|
{
|
|
|
|
|
(Architecture.X64, true, false, false) => "win-x64",
|
|
|
|
|
(Architecture.X64, false, true, false) => "linux-x64",
|
|
|
|
|
(Architecture.X64, false, false, true) => "osx-x64",
|
|
|
|
|
(Architecture.Arm64, false, true, false) => "linux-arm64",
|
|
|
|
|
(Architecture.Arm64, false, false, true) => "osx-arm64",
|
|
|
|
|
(Architecture.Arm, false, true, false) => "linux-arm",
|
|
|
|
|
_ => null,
|
|
|
|
|
};
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
private sealed class LatestReleaseResponse
|
|
|
|
|
{
|
|
|
|
|
[JsonPropertyName("version")]
|
|
|
|
|
public string Version { get; set; } = string.Empty;
|
|
|
|
|
[JsonPropertyName("assets")]
|
|
|
|
|
public Dictionary<string, AssetDto> Assets { get; set; } = [];
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
private sealed class AssetDto
|
|
|
|
|
{
|
|
|
|
|
[JsonPropertyName("url")]
|
|
|
|
|
public string Url { get; set; } = string.Empty;
|
|
|
|
|
[JsonPropertyName("sha256")]
|
|
|
|
|
public string? Sha256 { get; set; }
|
|
|
|
|
}
|
|
|
|
|
}
|