2026-08-11 18:51:52 +02:00
|
|
|
using System.Net.Http.Json;
|
|
|
|
|
using System.Text.Json.Serialization;
|
|
|
|
|
using Heimdall.Agent.Logging;
|
|
|
|
|
using Heimdall.Agent.Services;
|
|
|
|
|
using Microsoft.Extensions.Logging;
|
|
|
|
|
using Microsoft.Extensions.Options;
|
|
|
|
|
|
|
|
|
|
namespace Heimdall.Agent.Services;
|
|
|
|
|
|
|
|
|
|
/// <summary>
|
|
|
|
|
/// Periodically flushes the agent's <see cref="LogBufferService"/> to the
|
|
|
|
|
/// Central via <c>POST /api/agents/{id}/logs</c> (API Key auth).
|
|
|
|
|
/// Non-blocking by design: if the Central is unreachable the entries are
|
|
|
|
|
/// re-queued and retried on the next tick; a 400 (validation) drops the
|
|
|
|
|
/// batch to avoid an infinite retry loop.
|
|
|
|
|
/// </summary>
|
|
|
|
|
public class LogUploadService : BackgroundService
|
|
|
|
|
{
|
|
|
|
|
private readonly IHttpClientFactory _httpClientFactory;
|
|
|
|
|
private readonly LogBufferService _buffer;
|
|
|
|
|
private readonly AgentState _state;
|
|
|
|
|
private readonly ILogger<LogUploadService> _logger;
|
|
|
|
|
|
|
|
|
|
public LogUploadService(
|
|
|
|
|
IHttpClientFactory httpClientFactory,
|
|
|
|
|
LogBufferService buffer,
|
|
|
|
|
AgentState state,
|
|
|
|
|
ILogger<LogUploadService> logger)
|
|
|
|
|
{
|
|
|
|
|
_httpClientFactory = httpClientFactory;
|
|
|
|
|
_buffer = buffer;
|
|
|
|
|
_state = state;
|
|
|
|
|
_logger = logger;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
|
|
|
|
|
{
|
|
|
|
|
using var timer = new PeriodicTimer(TimeSpan.FromSeconds(30));
|
|
|
|
|
|
|
|
|
|
while (await timer.WaitForNextTickAsync(stoppingToken).ConfigureAwait(false))
|
|
|
|
|
{
|
|
|
|
|
try
|
|
|
|
|
{
|
|
|
|
|
await UploadOnceAsync(stoppingToken).ConfigureAwait(false);
|
|
|
|
|
}
|
|
|
|
|
catch (OperationCanceledException) when (stoppingToken.IsCancellationRequested)
|
|
|
|
|
{
|
|
|
|
|
break;
|
|
|
|
|
}
|
|
|
|
|
catch (Exception ex)
|
|
|
|
|
{
|
|
|
|
|
_logger.LogWarning(ex, "Log upload tick failed (non-fatal)");
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
internal async Task UploadOnceAsync(CancellationToken ct)
|
|
|
|
|
{
|
|
|
|
|
// No registered identity yet → nothing to attach logs to.
|
|
|
|
|
if (_state.AgentId == Guid.Empty || string.IsNullOrEmpty(_state.ApiKey))
|
|
|
|
|
return;
|
|
|
|
|
|
|
|
|
|
var entries = _buffer.TakeAll();
|
|
|
|
|
if (entries.Count == 0)
|
|
|
|
|
return;
|
|
|
|
|
|
|
|
|
|
var client = _httpClientFactory.CreateClient("Central");
|
|
|
|
|
client.DefaultRequestHeaders.Remove("X-API-Key");
|
|
|
|
|
client.DefaultRequestHeaders.Add("X-API-Key", _state.ApiKey);
|
|
|
|
|
|
|
|
|
|
var payload = new
|
|
|
|
|
{
|
|
|
|
|
entries = entries.Select(e => new
|
|
|
|
|
{
|
|
|
|
|
timestampUtc = e.TimestampUtc,
|
|
|
|
|
level = e.Level.ToString(),
|
|
|
|
|
message = e.Message,
|
|
|
|
|
exception = e.Exception,
|
|
|
|
|
source = e.Source
|
|
|
|
|
}).ToList()
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
try
|
|
|
|
|
{
|
|
|
|
|
using var response = await client.PostAsJsonAsync(
|
|
|
|
|
$"api/agents/{_state.AgentId}/logs", payload, ct).ConfigureAwait(false);
|
|
|
|
|
|
|
|
|
|
if (response.IsSuccessStatusCode)
|
|
|
|
|
{
|
|
|
|
|
if (_buffer.DroppedCount > 0)
|
|
|
|
|
_logger.LogWarning(
|
|
|
|
|
"Log upload OK; {Count} entries uploaded, {Dropped} dropped (buffer full)",
|
|
|
|
|
entries.Count, _buffer.DroppedCount);
|
|
|
|
|
return;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
if ((int)response.StatusCode == 400)
|
|
|
|
|
{
|
|
|
|
|
// Validation error — re-sending the same batch will never succeed.
|
|
|
|
|
_logger.LogWarning(
|
|
|
|
|
"Central rejected log batch ({Status}): dropping {Count} entries",
|
|
|
|
|
(int)response.StatusCode, entries.Count);
|
|
|
|
|
return;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
_logger.LogWarning(
|
|
|
|
|
"Log upload failed ({Status}); {Count} entries re-queued",
|
|
|
|
|
(int)response.StatusCode, entries.Count);
|
|
|
|
|
_buffer.Requeue(entries);
|
|
|
|
|
}
|
|
|
|
|
catch (Exception ex)
|
|
|
|
|
{
|
2026-08-20 14:13:06 +02:00
|
|
|
_logger.LogDebug(ex, "Log upload failed (network): {Count} entries re-queued", entries.Count);
|
2026-08-11 18:51:52 +02:00
|
|
|
_buffer.Requeue(entries);
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|