206 lines
9.8 KiB
C#
206 lines
9.8 KiB
C#
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;
|
|
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, 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;
|
|
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)
|
|
{
|
|
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...");
|
|
var release = await FetchLatestReleaseAsync(ct);
|
|
if (release is null) return;
|
|
var signed = ReleaseSignatureVerifier.Verify(release.SignedManifest, release.ManifestSignature,
|
|
_options.Value.UpdatePublicKeyPath);
|
|
if (!string.Equals(signed.Version, release.Version, StringComparison.Ordinal))
|
|
throw new InvalidOperationException("Release version differs from the signed manifest");
|
|
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) &&
|
|
!release.Assets.TryGetValue("portable", out asset))
|
|
{ _logger.LogWarning("No binary for platform"); return; }
|
|
var signedPlatform = release.Assets.TryGetValue(platformKey, out _) ? platformKey : "portable";
|
|
if (!signed.Assets.TryGetValue(signedPlatform, out var signedSha256) ||
|
|
!string.Equals(signedSha256, asset.Sha256, StringComparison.OrdinalIgnoreCase))
|
|
throw new InvalidOperationException("Agent archive digest differs from the signed manifest");
|
|
var installRoot = _options.Value.UpdateInstallRoot;
|
|
if (!OperatingSystem.IsLinux() || string.IsNullOrWhiteSpace(installRoot))
|
|
throw new InvalidOperationException("Native update requires a managed Linux installation root");
|
|
var tempPath = Path.Combine(Path.GetTempPath(), "heimdall-update-" + Guid.NewGuid().ToString("N") + ".tar.gz");
|
|
try
|
|
{
|
|
await DownloadAndVerifyAsync(asset.Url, signedSha256, tempPath, ct);
|
|
await NativeAgentPackageInstaller.ActivateAsync(tempPath, installRoot, signed.Version, ct);
|
|
_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"); }
|
|
finally { try { 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);
|
|
var response = await client.GetAsync("api/updates/agent/latest", ct);
|
|
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)
|
|
{
|
|
if (expectedSha256 is null || expectedSha256.Length != 64 || expectedSha256.Any(c => !Uri.IsHexDigit(c)))
|
|
throw new InvalidOperationException("The release manifest does not contain a valid SHA-256 digest; refusing an unverified update");
|
|
|
|
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();
|
|
await using var downloaded = File.OpenRead(destPath);
|
|
var hashBytes = await SHA256.HashDataAsync(downloaded, 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].TrimStart('v', 'V');
|
|
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; } = [];
|
|
[JsonPropertyName("signedManifest")]
|
|
public string? SignedManifest { get; set; }
|
|
[JsonPropertyName("manifestSignature")]
|
|
public string? ManifestSignature { get; set; }
|
|
}
|
|
|
|
private sealed class AssetDto
|
|
{
|
|
[JsonPropertyName("url")]
|
|
public string Url { get; set; } = string.Empty;
|
|
[JsonPropertyName("sha256")]
|
|
public string? Sha256 { get; set; }
|
|
}
|
|
}
|