- Agent : LogBufferService (ring buffer borné, drop-oldest), AgentLoggingProvider
(capture ILogger non-bloquante), LogSanitizer (masque password/token/secret/bearer),
LogUploadService (batch POST /api/agents/{id}/logs, retry, drop si 400)
- Central : entité AgentLogEntry + migration AddAgentLogEntries (index AgentId+TimestampUtc),
SubmitAgentLogsCommand (batch <= 200, entrées invalides ignorées),
GetAgentLogsQuery (pagination, filtres niveau/période/recherche),
endpoints POST + GET /api/agents/{id}/logs
- UI : onglet Logs dans AgentDetail (filtres, pagination, auto-refresh toggle)
- Logs agent enrichis : heartbeat succès (Debug), résolution IP (Debug)
- Tests : LogBufferServiceTests (6), AgentDetailLogsTests (4), handlers AgentLogs (8)
This commit is contained in:
1 parent
ab705e72fa
commit
0136bf33ec
28 files changed
+3261
-3
No files matched your search
@@ -0,0 +1,69 @@
|
||||
using Microsoft.Extensions.Logging;
|
||||
|
||||
namespace Heimdall.Agent.Logging;
|
||||
|
||||
/// <summary>
|
||||
/// Additional <see cref="ILoggerProvider"/> that captures every log entry
|
||||
/// passing the process-wide filter (RuntimeLogLevel) into the
|
||||
/// <see cref="LogBufferService"/> for upload to the Central.
|
||||
/// This is a sink only: it never writes to console or files, so the
|
||||
/// existing stdout/Docker output is untouched.
|
||||
/// </summary>
|
||||
public sealed class AgentLoggingProvider : ILoggerProvider
|
||||
{
|
||||
private readonly LogBufferService _buffer;
|
||||
|
||||
public AgentLoggingProvider(LogBufferService buffer) => _buffer = buffer;
|
||||
|
||||
public ILogger CreateLogger(string categoryName) => new BufferLogger(_buffer, categoryName);
|
||||
|
||||
public void Dispose() { }
|
||||
|
||||
private sealed class BufferLogger : ILogger
|
||||
{
|
||||
private readonly LogBufferService _buffer;
|
||||
private readonly string _category;
|
||||
|
||||
public BufferLogger(LogBufferService buffer, string category)
|
||||
{
|
||||
_buffer = buffer;
|
||||
_category = category;
|
||||
}
|
||||
|
||||
public IDisposable? BeginScope<TState>(TState state) where TState : notnull => null;
|
||||
|
||||
public bool IsEnabled(LogLevel logLevel) => true;
|
||||
|
||||
public void Log<TState>(
|
||||
LogLevel logLevel,
|
||||
EventId eventId,
|
||||
TState state,
|
||||
Exception? exception,
|
||||
Func<TState, Exception?, string> formatter)
|
||||
{
|
||||
try
|
||||
{
|
||||
var message = LogSanitizer.Sanitize(formatter(state, exception));
|
||||
if (string.IsNullOrWhiteSpace(message))
|
||||
return;
|
||||
|
||||
_buffer.Enqueue(new BufferedLogEntry(
|
||||
DateTime.UtcNow,
|
||||
logLevel,
|
||||
message,
|
||||
LogSanitizer.Sanitize(exception?.ToString()),
|
||||
ShortCategory(_category)));
|
||||
}
|
||||
catch (Exception)
|
||||
{
|
||||
// Logging must never crash the caller (FFmpeg/YOLO hot path).
|
||||
}
|
||||
}
|
||||
|
||||
private static string ShortCategory(string category)
|
||||
{
|
||||
var dot = category.LastIndexOf('.');
|
||||
return dot >= 0 ? category[(dot + 1)..] : category;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,83 @@
|
||||
using System.Collections.Concurrent;
|
||||
using Microsoft.Extensions.Logging;
|
||||
|
||||
namespace Heimdall.Agent.Logging;
|
||||
|
||||
/// <summary>
|
||||
/// Captured log entry waiting to be uploaded to the Central.
|
||||
/// </summary>
|
||||
public readonly record struct BufferedLogEntry(
|
||||
DateTime TimestampUtc,
|
||||
LogLevel Level,
|
||||
string Message,
|
||||
string? Exception,
|
||||
string? Source);
|
||||
|
||||
/// <summary>
|
||||
/// Bounded, thread-safe in-memory buffer of log entries produced by the
|
||||
/// agent and destined for the Central's <c>POST /api/agents/{id}/logs</c>.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// Full-buffer policy: <b>drop oldest</b>. The most recent entries are the
|
||||
/// most useful for diagnosing the agent's current state (a fresh Error must
|
||||
/// never be dropped because a burst of older Warnings filled the buffer).
|
||||
/// Dropped entries are counted so the operator can see the agent is logging
|
||||
/// faster than it uploads. Logging never blocks the caller.
|
||||
/// </remarks>
|
||||
public sealed class LogBufferService
|
||||
{
|
||||
private readonly ConcurrentQueue<BufferedLogEntry> _queue = new();
|
||||
private readonly int _capacity;
|
||||
private int _droppedCount;
|
||||
|
||||
public LogBufferService(int capacity = 500)
|
||||
{
|
||||
_capacity = capacity > 0 ? capacity : 500;
|
||||
}
|
||||
|
||||
public int Capacity => _capacity;
|
||||
|
||||
/// <summary>Number of entries dropped because the buffer was full.</summary>
|
||||
public int DroppedCount => Volatile.Read(ref _droppedCount);
|
||||
|
||||
/// <summary>Current number of buffered entries.</summary>
|
||||
public int Count => _queue.Count;
|
||||
|
||||
/// <summary>
|
||||
/// Adds an entry, dropping the oldest one when the buffer is full.
|
||||
/// Never throws and never blocks the logging hot path.
|
||||
/// </summary>
|
||||
public void Enqueue(BufferedLogEntry entry)
|
||||
{
|
||||
_queue.Enqueue(entry);
|
||||
|
||||
while (_queue.Count > _capacity)
|
||||
{
|
||||
if (_queue.TryDequeue(out _))
|
||||
Interlocked.Increment(ref _droppedCount);
|
||||
else
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Atomically removes and returns all buffered entries (oldest first).
|
||||
/// </summary>
|
||||
public IReadOnlyList<BufferedLogEntry> TakeAll()
|
||||
{
|
||||
if (_queue.IsEmpty)
|
||||
return [];
|
||||
|
||||
var entries = new List<BufferedLogEntry>(_queue.Count);
|
||||
while (_queue.TryDequeue(out var entry))
|
||||
entries.Add(entry);
|
||||
return entries;
|
||||
}
|
||||
|
||||
/// <summary>Re-queues entries that failed to upload (drops oldest if needed).</summary>
|
||||
public void Requeue(IEnumerable<BufferedLogEntry> entries)
|
||||
{
|
||||
foreach (var entry in entries)
|
||||
Enqueue(entry);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
using System.Text.RegularExpressions;
|
||||
|
||||
namespace Heimdall.Agent.Logging;
|
||||
|
||||
/// <summary>
|
||||
/// Masks secrets in log messages before they leave the agent (spec P1:
|
||||
/// "Secrets dans logs — sanitized : password, token, secret, snapshotUrl").
|
||||
/// Applied to both message and exception text at capture time.
|
||||
/// </summary>
|
||||
public static partial class LogSanitizer
|
||||
{
|
||||
// Matches "key=value", "key: value", "key= 'value'" or JSON "key":"value"
|
||||
// for well-known secret keys. Also handles "Authorization: Bearer <token>".
|
||||
[GeneratedRegex(
|
||||
@"(?i)(?<key>password|passwd|pwd|token|secret|apikey|api_key|authorization|snapshoturl|credential|private[_-]?key)(['""]?\s*[:=]\s*)(?<quote>['""]?)(?:(?:bearer|basic)\s+)?(?<value>[^'""\s,;&]+)",
|
||||
RegexOptions.Compiled)]
|
||||
private static partial Regex SecretValueRegex();
|
||||
|
||||
public static string Sanitize(string? text)
|
||||
{
|
||||
if (string.IsNullOrEmpty(text))
|
||||
return string.Empty;
|
||||
|
||||
return SecretValueRegex().Replace(text, "${key}${2}${3}***");
|
||||
}
|
||||
}
|
||||
@@ -1,9 +1,11 @@
|
||||
using Sentry.AspNetCore;
|
||||
|
||||
using Heimdall.Agent;
|
||||
using Heimdall.Agent.Logging;
|
||||
using Heimdall.Agent.Services;
|
||||
using Microsoft.AspNetCore.Diagnostics.HealthChecks;
|
||||
using Microsoft.Extensions.Diagnostics.HealthChecks;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Microsoft.Extensions.Options;
|
||||
|
||||
var builder = WebApplication.CreateSlimBuilder(args);
|
||||
@@ -69,6 +71,12 @@ builder.Services.AddHostedService<AgentRegistrationService>();
|
||||
builder.Services.AddHostedService<ConfigReceiverService>();
|
||||
builder.Services.AddHostedService<AgentDiscoveryService>();
|
||||
|
||||
// Log capture & upload to Central (ticket #50)
|
||||
builder.Services.AddSingleton<LogBufferService>();
|
||||
builder.Services.AddSingleton<AgentLoggingProvider>();
|
||||
builder.Services.AddSingleton<ILoggerProvider>(sp => sp.GetRequiredService<AgentLoggingProvider>());
|
||||
builder.Services.AddHostedService<LogUploadService>();
|
||||
|
||||
// Health checks — used by Docker HEALTHCHECK
|
||||
builder.Services.AddHealthChecks()
|
||||
.AddCheck<AgentHealthCheck>("agent_health", tags: ["ready"]);
|
||||
|
||||
@@ -15,6 +15,7 @@ public class AgentRegistrationService : BackgroundService
|
||||
private readonly AgentState _state;
|
||||
private readonly AgentOptions _options;
|
||||
private readonly SystemMetricsProvider _metrics;
|
||||
private readonly Logging.LogBufferService _buffer;
|
||||
private HttpClient? _client;
|
||||
|
||||
public AgentRegistrationService(
|
||||
@@ -22,12 +23,14 @@ public class AgentRegistrationService : BackgroundService
|
||||
AgentState state,
|
||||
IOptions<AgentOptions> options,
|
||||
SystemMetricsProvider metrics,
|
||||
Logging.LogBufferService buffer,
|
||||
ILogger<AgentRegistrationService> logger)
|
||||
{
|
||||
_httpClientFactory = httpClientFactory;
|
||||
_state = state;
|
||||
_options = options.Value;
|
||||
_metrics = metrics;
|
||||
_buffer = buffer;
|
||||
_logger = logger;
|
||||
}
|
||||
|
||||
@@ -165,6 +168,11 @@ public class AgentRegistrationService : BackgroundService
|
||||
{
|
||||
_logger.LogWarning("Heartbeat failed: {StatusCode}", heartbeatResponse.StatusCode);
|
||||
}
|
||||
else
|
||||
{
|
||||
_logger.LogDebug("Heartbeat OK — agent online, {Buffered} log(s) buffered",
|
||||
_buffer.Count);
|
||||
}
|
||||
}
|
||||
catch (Exception ex) when (ex is not OperationCanceledException)
|
||||
{
|
||||
@@ -187,10 +195,13 @@ public class AgentRegistrationService : BackgroundService
|
||||
var http = _httpClientFactory.CreateClient("IpResolver");
|
||||
http.Timeout = TimeSpan.FromSeconds(5);
|
||||
var ip = await http.GetStringAsync("https://api.ipify.org", ct);
|
||||
return ip?.Trim();
|
||||
ip = ip?.Trim();
|
||||
_logger.LogDebug("Public IP resolved: {Ip}", ip);
|
||||
return ip;
|
||||
}
|
||||
catch
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogDebug("Public IP resolution failed ({Error}); reporting null", ex.Message);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,117 @@
|
||||
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)
|
||||
{
|
||||
_logger.LogDebug("Log upload failed (network): {Error}; {Count} entries re-queued", ex.Message, entries.Count);
|
||||
_buffer.Requeue(entries);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
using Heimdall.Application.Common;
|
||||
using Heimdall.Application.DTOs;
|
||||
using MediatR;
|
||||
|
||||
namespace Heimdall.Application.AgentLogs.Commands.SubmitAgentLogs;
|
||||
|
||||
public record SubmitAgentLogsCommand(
|
||||
Guid AgentId,
|
||||
IReadOnlyList<AgentLogEntryRequest> Entries) : IRequest<ServiceResult>;
|
||||
@@ -0,0 +1,68 @@
|
||||
using Heimdall.Application.Common;
|
||||
using Heimdall.Application.DTOs;
|
||||
using Heimdall.Domain.Entities;
|
||||
using Heimdall.Domain.Enums;
|
||||
using MediatR;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
|
||||
namespace Heimdall.Application.AgentLogs.Commands.SubmitAgentLogs;
|
||||
|
||||
public class SubmitAgentLogsHandler : IRequestHandler<SubmitAgentLogsCommand, ServiceResult>
|
||||
{
|
||||
private readonly IApplicationDbContext _db;
|
||||
|
||||
public SubmitAgentLogsHandler(IApplicationDbContext db) => _db = db;
|
||||
|
||||
public async Task<ServiceResult> Handle(SubmitAgentLogsCommand request, CancellationToken ct)
|
||||
{
|
||||
var agentExists = await _db.Agents
|
||||
.AnyAsync(a => a.Id == request.AgentId, ct)
|
||||
.ConfigureAwait(false);
|
||||
if (!agentExists)
|
||||
return ServiceResult.NotFound("Agent not found");
|
||||
|
||||
var nowUtc = DateTime.UtcNow;
|
||||
var entries = new List<AgentLogEntry>(request.Entries.Count);
|
||||
|
||||
foreach (var entry in request.Entries)
|
||||
{
|
||||
// Skip malformed entries instead of failing the whole batch:
|
||||
// an agent misconfiguration must not block log collection.
|
||||
if (!Enum.TryParse<AgentLogLevel>(entry.Level, true, out var level))
|
||||
continue;
|
||||
if (string.IsNullOrWhiteSpace(entry.Message))
|
||||
continue;
|
||||
|
||||
var timestamp = entry.TimestampUtc.Kind == DateTimeKind.Unspecified
|
||||
? DateTime.SpecifyKind(entry.TimestampUtc, DateTimeKind.Utc)
|
||||
: entry.TimestampUtc.ToUniversalTime();
|
||||
|
||||
// Clamp absurdly old timestamps (agent buffered through a long outage);
|
||||
// entries in the future are dropped by the validator.
|
||||
if (timestamp < nowUtc.AddDays(-30))
|
||||
continue;
|
||||
|
||||
entries.Add(new AgentLogEntry(
|
||||
request.AgentId,
|
||||
timestamp,
|
||||
level,
|
||||
entry.Message.Trim(),
|
||||
Normalize(entry.Exception),
|
||||
Normalize(entry.Source)));
|
||||
}
|
||||
|
||||
if (entries.Count == 0)
|
||||
return ServiceResult.Failure("No valid log entries in batch", 400);
|
||||
|
||||
foreach (var entry in entries)
|
||||
_db.AgentLogEntries.Add(entry);
|
||||
await _db.SaveChangesWithRetryAsync(ct: ct).ConfigureAwait(false);
|
||||
return ServiceResult.Success();
|
||||
}
|
||||
|
||||
private static string? Normalize(string? value)
|
||||
{
|
||||
var trimmed = value?.Trim();
|
||||
return string.IsNullOrWhiteSpace(trimmed) ? null : trimmed;
|
||||
}
|
||||
}
|
||||
+39
@@ -0,0 +1,39 @@
|
||||
using Heimdall.Application.AgentLogs.Commands.SubmitAgentLogs;
|
||||
using FluentValidation;
|
||||
|
||||
namespace Heimdall.Application.AgentLogs.Commands.SubmitAgentLogs;
|
||||
|
||||
public class SubmitAgentLogsValidator : AbstractValidator<SubmitAgentLogsCommand>
|
||||
{
|
||||
public const int MaxBatchSize = 200;
|
||||
public const int MaxMessageLength = 2000;
|
||||
|
||||
public SubmitAgentLogsValidator()
|
||||
{
|
||||
RuleFor(x => x.AgentId)
|
||||
.NotEmpty();
|
||||
|
||||
RuleFor(x => x.Entries)
|
||||
.NotNull()
|
||||
.NotEmpty()
|
||||
.WithMessage("Log entries are required.")
|
||||
.Must(e => e.Count <= MaxBatchSize)
|
||||
.WithMessage($"Batch size exceeds the maximum of {MaxBatchSize} entries.");
|
||||
|
||||
RuleForEach(x => x.Entries)
|
||||
.ChildRules(entry =>
|
||||
{
|
||||
entry.RuleFor(e => e.Message)
|
||||
.NotEmpty()
|
||||
.WithMessage("Log message is required.")
|
||||
.MaximumLength(MaxMessageLength)
|
||||
.WithMessage($"Log message exceeds {MaxMessageLength} characters.");
|
||||
|
||||
entry.RuleFor(e => e.TimestampUtc)
|
||||
.Must(ts => ts.Kind == DateTimeKind.Utc || ts.Kind == DateTimeKind.Unspecified)
|
||||
.WithMessage("TimestampUtc must be UTC.")
|
||||
.Must(ts => ts <= DateTime.UtcNow.AddMinutes(5))
|
||||
.WithMessage("TimestampUtc is in the future (clock skew > 5 min).");
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
using Heimdall.Application.AgentLogs.Queries.GetAgentLogs;
|
||||
using Heimdall.Application.Common;
|
||||
using Heimdall.Application.DTOs;
|
||||
using Heimdall.Domain.Enums;
|
||||
using MediatR;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
|
||||
namespace Heimdall.Application.AgentLogs.Queries.GetAgentLogs;
|
||||
|
||||
public class GetAgentLogsHandler : IRequestHandler<GetAgentLogsQuery, ServiceResult<PagedResult<AgentLogEntryDto>>>
|
||||
{
|
||||
private readonly IApplicationDbContext _db;
|
||||
|
||||
public GetAgentLogsHandler(IApplicationDbContext db) => _db = db;
|
||||
|
||||
public async Task<ServiceResult<PagedResult<AgentLogEntryDto>>> Handle(GetAgentLogsQuery request, CancellationToken ct)
|
||||
{
|
||||
var query = _db.AgentLogEntries.Where(e => e.AgentId == request.AgentId);
|
||||
|
||||
if (!string.IsNullOrWhiteSpace(request.Level)
|
||||
&& Enum.TryParse<AgentLogLevel>(request.Level, true, out var level))
|
||||
{
|
||||
query = query.Where(e => e.Level == level);
|
||||
}
|
||||
|
||||
if (request.From.HasValue)
|
||||
query = query.Where(e => e.TimestampUtc >= request.From.Value.ToUniversalTime());
|
||||
|
||||
if (request.To.HasValue)
|
||||
query = query.Where(e => e.TimestampUtc <= request.To.Value.ToUniversalTime());
|
||||
|
||||
if (!string.IsNullOrWhiteSpace(request.Search))
|
||||
{
|
||||
var search = request.Search.Trim();
|
||||
query = query.Where(e =>
|
||||
e.Message.Contains(search, StringComparison.OrdinalIgnoreCase)
|
||||
|| (e.Source != null && e.Source.Contains(search, StringComparison.OrdinalIgnoreCase)));
|
||||
}
|
||||
|
||||
var total = await query.CountAsync(ct).ConfigureAwait(false);
|
||||
|
||||
var items = await query
|
||||
.OrderByDescending(e => e.TimestampUtc)
|
||||
.Skip((request.Page - 1) * request.PageSize)
|
||||
.Take(request.PageSize)
|
||||
.Select(e => new AgentLogEntryDto(
|
||||
e.Id,
|
||||
e.AgentId,
|
||||
e.TimestampUtc,
|
||||
e.Level.ToString(),
|
||||
e.Message,
|
||||
e.Exception,
|
||||
e.Source))
|
||||
.ToListAsync(ct)
|
||||
.ConfigureAwait(false);
|
||||
|
||||
return ServiceResult<PagedResult<AgentLogEntryDto>>.Success(
|
||||
new PagedResult<AgentLogEntryDto>(items, total, request.Page, request.PageSize));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
using Heimdall.Application.Common;
|
||||
using Heimdall.Application.DTOs;
|
||||
using MediatR;
|
||||
|
||||
namespace Heimdall.Application.AgentLogs.Queries.GetAgentLogs;
|
||||
|
||||
public record GetAgentLogsQuery(
|
||||
Guid AgentId,
|
||||
int Page = 1,
|
||||
int PageSize = 50,
|
||||
string? Level = null,
|
||||
DateTime? From = null,
|
||||
DateTime? To = null,
|
||||
string? Search = null) : IRequest<ServiceResult<PagedResult<AgentLogEntryDto>>>;
|
||||
@@ -6,6 +6,7 @@ namespace Heimdall.Application.Common;
|
||||
public interface IApplicationDbContext
|
||||
{
|
||||
DbSet<Agent> Agents { get; }
|
||||
DbSet<AgentLogEntry> AgentLogEntries { get; }
|
||||
DbSet<AgentSetting> AgentSettings { get; }
|
||||
DbSet<ApiKey> ApiKeys { get; }
|
||||
DbSet<AppSetting> AppSettings { get; }
|
||||
|
||||
@@ -0,0 +1,23 @@
|
||||
namespace Heimdall.Application.DTOs;
|
||||
|
||||
/// <summary>Single log entry as submitted by an agent.</summary>
|
||||
public record AgentLogEntryRequest(
|
||||
DateTime TimestampUtc,
|
||||
string Level,
|
||||
string Message,
|
||||
string? Exception = null,
|
||||
string? Source = null);
|
||||
|
||||
/// <summary>Batch of log entries submitted by an agent.</summary>
|
||||
public record SubmitAgentLogsRequest(
|
||||
IReadOnlyList<AgentLogEntryRequest> Entries);
|
||||
|
||||
/// <summary>Log entry as returned to the admin UI.</summary>
|
||||
public record AgentLogEntryDto(
|
||||
Guid Id,
|
||||
Guid AgentId,
|
||||
DateTime TimestampUtc,
|
||||
string Level,
|
||||
string Message,
|
||||
string? Exception,
|
||||
string? Source);
|
||||
@@ -0,0 +1,39 @@
|
||||
using Heimdall.Domain.Enums;
|
||||
|
||||
namespace Heimdall.Domain.Entities;
|
||||
|
||||
/// <summary>
|
||||
/// Append-only log entry reported by an agent (FFmpeg, YOLO, RTSP, lifecycle…).
|
||||
/// Purged periodically by the AgentLogCleanupJob (retention policy).
|
||||
/// </summary>
|
||||
public class AgentLogEntry
|
||||
{
|
||||
public Guid Id { get; private set; } = Guid.NewGuid();
|
||||
public Guid AgentId { get; private set; }
|
||||
public DateTime TimestampUtc { get; private set; }
|
||||
public AgentLogLevel Level { get; private set; }
|
||||
public string Message { get; private set; } = string.Empty;
|
||||
public string? Exception { get; private set; }
|
||||
public string? Source { get; private set; }
|
||||
|
||||
// Navigation
|
||||
public Agent Agent { get; private set; } = null!;
|
||||
|
||||
private AgentLogEntry() { } // EF Core
|
||||
|
||||
public AgentLogEntry(
|
||||
Guid agentId,
|
||||
DateTime timestampUtc,
|
||||
AgentLogLevel level,
|
||||
string message,
|
||||
string? exception = null,
|
||||
string? source = null)
|
||||
{
|
||||
AgentId = agentId;
|
||||
TimestampUtc = timestampUtc;
|
||||
Level = level;
|
||||
Message = message;
|
||||
Exception = exception;
|
||||
Source = source;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
namespace Heimdall.Domain.Enums;
|
||||
|
||||
/// <summary>
|
||||
/// Severity level of an agent log entry, mirroring Microsoft.Extensions.Logging levels.
|
||||
/// </summary>
|
||||
public enum AgentLogLevel
|
||||
{
|
||||
Trace = 0,
|
||||
Debug = 1,
|
||||
Information = 2,
|
||||
Warning = 3,
|
||||
Error = 4,
|
||||
Critical = 5
|
||||
}
|
||||
@@ -23,6 +23,7 @@ public class AppDbContext : IdentityDbContext<AppUser, AppRole, Guid>, IApplicat
|
||||
public DbSet<Site> Sites => Set<Site>();
|
||||
public DbSet<SiteCredential> SiteCredentials => Set<SiteCredential>();
|
||||
public DbSet<Agent> Agents => Set<Agent>();
|
||||
public DbSet<AgentLogEntry> AgentLogEntries => Set<AgentLogEntry>();
|
||||
public DbSet<Camera> Cameras => Set<Camera>();
|
||||
public DbSet<CameraCredentials> CameraCredentials => Set<CameraCredentials>();
|
||||
public DbSet<CameraDetectionProfile> CameraDetectionProfiles => Set<CameraDetectionProfile>();
|
||||
|
||||
@@ -0,0 +1,44 @@
|
||||
using Heimdall.Domain.Entities;
|
||||
using Heimdall.Domain.Enums;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.EntityFrameworkCore.Metadata.Builders;
|
||||
|
||||
namespace Heimdall.Infrastructure.Data.Configurations;
|
||||
|
||||
public class AgentLogEntryConfiguration : IEntityTypeConfiguration<AgentLogEntry>
|
||||
{
|
||||
public void Configure(EntityTypeBuilder<AgentLogEntry> builder)
|
||||
{
|
||||
builder.ToTable("agent_log_entries");
|
||||
|
||||
builder.HasKey(e => e.Id);
|
||||
|
||||
builder.Property(e => e.TimestampUtc)
|
||||
.IsRequired();
|
||||
|
||||
builder.Property(e => e.Level)
|
||||
.HasConversion<string>()
|
||||
.HasMaxLength(20)
|
||||
.IsRequired()
|
||||
.IsUnicode(false);
|
||||
|
||||
builder.Property(e => e.Message)
|
||||
.HasMaxLength(2000)
|
||||
.IsRequired();
|
||||
|
||||
builder.Property(e => e.Exception)
|
||||
.HasMaxLength(4000);
|
||||
|
||||
builder.Property(e => e.Source)
|
||||
.HasMaxLength(200)
|
||||
.IsUnicode(false);
|
||||
|
||||
// Composite index: reads per agent (logs page) + purge by age.
|
||||
builder.HasIndex(e => new { e.AgentId, e.TimestampUtc });
|
||||
|
||||
builder.HasOne(e => e.Agent)
|
||||
.WithMany()
|
||||
.HasForeignKey(e => e.AgentId)
|
||||
.OnDelete(DeleteBehavior.Cascade);
|
||||
}
|
||||
}
|
||||
+1881
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,50 @@
|
||||
using System;
|
||||
using Microsoft.EntityFrameworkCore.Migrations;
|
||||
|
||||
#nullable disable
|
||||
|
||||
namespace Heimdall.Infrastructure.Migrations
|
||||
{
|
||||
/// <inheritdoc />
|
||||
public partial class AddAgentLogEntries : Migration
|
||||
{
|
||||
/// <inheritdoc />
|
||||
protected override void Up(MigrationBuilder migrationBuilder)
|
||||
{
|
||||
migrationBuilder.CreateTable(
|
||||
name: "agent_log_entries",
|
||||
columns: table => new
|
||||
{
|
||||
Id = table.Column<Guid>(type: "uuid", nullable: false),
|
||||
AgentId = table.Column<Guid>(type: "uuid", nullable: false),
|
||||
TimestampUtc = table.Column<DateTime>(type: "timestamp with time zone", nullable: false),
|
||||
Level = table.Column<string>(type: "character varying(20)", unicode: false, maxLength: 20, nullable: false),
|
||||
Message = table.Column<string>(type: "character varying(2000)", maxLength: 2000, nullable: false),
|
||||
Exception = table.Column<string>(type: "character varying(4000)", maxLength: 4000, nullable: true),
|
||||
Source = table.Column<string>(type: "character varying(200)", unicode: false, maxLength: 200, nullable: true)
|
||||
},
|
||||
constraints: table =>
|
||||
{
|
||||
table.PrimaryKey("PK_agent_log_entries", x => x.Id);
|
||||
table.ForeignKey(
|
||||
name: "FK_agent_log_entries_agents_AgentId",
|
||||
column: x => x.AgentId,
|
||||
principalTable: "agents",
|
||||
principalColumn: "Id",
|
||||
onDelete: ReferentialAction.Cascade);
|
||||
});
|
||||
|
||||
migrationBuilder.CreateIndex(
|
||||
name: "IX_agent_log_entries_AgentId_TimestampUtc",
|
||||
table: "agent_log_entries",
|
||||
columns: new[] { "AgentId", "TimestampUtc" });
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
protected override void Down(MigrationBuilder migrationBuilder)
|
||||
{
|
||||
migrationBuilder.DropTable(
|
||||
name: "agent_log_entries");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -126,6 +126,45 @@ namespace Heimdall.Infrastructure.Migrations
|
||||
b.ToTable("agents", (string)null);
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Heimdall.Domain.Entities.AgentLogEntry", b =>
|
||||
{
|
||||
b.Property<Guid>("Id")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("uuid");
|
||||
|
||||
b.Property<Guid>("AgentId")
|
||||
.HasColumnType("uuid");
|
||||
|
||||
b.Property<string>("Exception")
|
||||
.HasMaxLength(4000)
|
||||
.HasColumnType("character varying(4000)");
|
||||
|
||||
b.Property<string>("Level")
|
||||
.IsRequired()
|
||||
.HasMaxLength(20)
|
||||
.IsUnicode(false)
|
||||
.HasColumnType("character varying(20)");
|
||||
|
||||
b.Property<string>("Message")
|
||||
.IsRequired()
|
||||
.HasMaxLength(2000)
|
||||
.HasColumnType("character varying(2000)");
|
||||
|
||||
b.Property<string>("Source")
|
||||
.HasMaxLength(200)
|
||||
.IsUnicode(false)
|
||||
.HasColumnType("character varying(200)");
|
||||
|
||||
b.Property<DateTime>("TimestampUtc")
|
||||
.HasColumnType("timestamp with time zone");
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.HasIndex("AgentId", "TimestampUtc");
|
||||
|
||||
b.ToTable("agent_log_entries", (string)null);
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Heimdall.Domain.Entities.AgentSetting", b =>
|
||||
{
|
||||
b.Property<Guid>("Id")
|
||||
@@ -1546,6 +1585,17 @@ namespace Heimdall.Infrastructure.Migrations
|
||||
b.Navigation("Site");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Heimdall.Domain.Entities.AgentLogEntry", b =>
|
||||
{
|
||||
b.HasOne("Heimdall.Domain.Entities.Agent", "Agent")
|
||||
.WithMany()
|
||||
.HasForeignKey("AgentId")
|
||||
.OnDelete(DeleteBehavior.Cascade)
|
||||
.IsRequired();
|
||||
|
||||
b.Navigation("Agent");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Heimdall.Domain.Entities.AgentSetting", b =>
|
||||
{
|
||||
b.HasOne("Heimdall.Domain.Entities.Agent", "Agent")
|
||||
|
||||
@@ -228,6 +228,124 @@ else
|
||||
}
|
||||
</SectionCard>
|
||||
|
||||
@* ─── Agent Logs ─── *@
|
||||
<SectionCard Title="Logs"
|
||||
Icon="@Icons.Material.Filled.ReceiptLong"
|
||||
Elevation="2"
|
||||
HelpText="Logs remontés par l'agent, purgés quotidiennement (rétention 7 jours).">
|
||||
<ChildContent>
|
||||
<div class="d-flex flex-wrap gap-2 mb-4">
|
||||
<MudSelect T="string" @bind-Value="_logLevel" Label="Niveau" Variant="Variant.Outlined"
|
||||
Dense="true" Clearable="true" Class="logs-level-filter" Immediate="true">
|
||||
<MudSelectItem T="string" Value="@null">Tous les niveaux</MudSelectItem>
|
||||
<MudSelectItem Value="@("Critical")">Critical</MudSelectItem>
|
||||
<MudSelectItem Value="@("Error")">Error</MudSelectItem>
|
||||
<MudSelectItem Value="@("Warning")">Warning</MudSelectItem>
|
||||
<MudSelectItem Value="@("Information")">Information</MudSelectItem>
|
||||
<MudSelectItem Value="@("Debug")">Debug</MudSelectItem>
|
||||
<MudSelectItem Value="@("Trace")">Trace</MudSelectItem>
|
||||
</MudSelect>
|
||||
<MudTextField T="string" @bind-Value="_logSearch" Label="Recherche" Variant="Variant.Outlined"
|
||||
Dense="true" Immediate="true" Class="logs-search-filter"
|
||||
Placeholder="Message ou source..." />
|
||||
<MudButton Variant="Variant.Filled" Color="Color.Primary" OnClick="@(() => LoadLogsAsync(keepPage: false))"
|
||||
StartIcon="@Icons.Material.Filled.Search" Class="align-self-center">
|
||||
Filtrer
|
||||
</MudButton>
|
||||
</div>
|
||||
|
||||
@if (_logsLoading)
|
||||
{
|
||||
<MudPaper Elevation="1" Class="pa-4" Style="border-radius: 8px;">
|
||||
<MudSkeleton Width="100%" Height="40px" />
|
||||
<MudSkeleton Width="100%" Height="40px" Class="mt-1" />
|
||||
<MudSkeleton Width="100%" Height="40px" Class="mt-1" />
|
||||
</MudPaper>
|
||||
}
|
||||
else if (_logsError)
|
||||
{
|
||||
<MudAlert Severity="Severity.Error" Class="mb-4" Variant="Variant.Filled">
|
||||
<MudText>Erreur lors du chargement des logs.</MudText>
|
||||
<MudButton Variant="Variant.Text" Color="Color.Inherit"
|
||||
OnClick="@(() => LoadLogsAsync(keepPage: true))" Class="mt-2">
|
||||
<MudIcon Icon="@Icons.Material.Filled.Refresh" Class="mr-1" Size="Size.Small" /> Réessayer
|
||||
</MudButton>
|
||||
</MudAlert>
|
||||
}
|
||||
else
|
||||
{
|
||||
<MudTable Items="@_logs" Hover="true" Striped="true" Elevation="2" Dense="true">
|
||||
<HeaderContent>
|
||||
<MudTh>Date</MudTh>
|
||||
<MudTh>Niveau</MudTh>
|
||||
<MudTh>Source</MudTh>
|
||||
<MudTh>Message</MudTh>
|
||||
</HeaderContent>
|
||||
<RowTemplate>
|
||||
<MudTd DataLabel="Date">
|
||||
<MudTooltip Text="@context.TimestampUtc.ToLocalTime().ToString("F")">
|
||||
<MudText Typo="Typo.body2">@context.TimestampUtc.ToLocalTime().ToString("g")</MudText>
|
||||
</MudTooltip>
|
||||
</MudTd>
|
||||
<MudTd DataLabel="Niveau">
|
||||
<MudChip T="string" Size="Size.Small" Color="@GetLogLevelColor(context.Level)">
|
||||
@context.Level
|
||||
</MudChip>
|
||||
</MudTd>
|
||||
<MudTd DataLabel="Source">
|
||||
<MudText Typo="Typo.body2" Color="Color.Secondary">@(context.Source ?? "-")</MudText>
|
||||
</MudTd>
|
||||
<MudTd DataLabel="Message">
|
||||
@if (!string.IsNullOrEmpty(context.Exception))
|
||||
{
|
||||
<MudTooltip Text="@context.Exception">
|
||||
<MudText Typo="Typo.body2" Class="logs-message">@context.Message</MudText>
|
||||
</MudTooltip>
|
||||
}
|
||||
else
|
||||
{
|
||||
<MudText Typo="Typo.body2" Class="logs-message">@context.Message</MudText>
|
||||
}
|
||||
</MudTd>
|
||||
</RowTemplate>
|
||||
<NoRecordsContent>
|
||||
<MudPaper Class="pa-8 text-center" Style="border-radius: 12px;">
|
||||
<MudIcon Icon="@Icons.Material.Filled.ReceiptLong" Size="Size.Large" Color="Color.Secondary" />
|
||||
<MudText Typo="Typo.h6" Color="Color.Secondary" Class="mt-4">Aucun log</MudText>
|
||||
<MudText Typo="Typo.body2" Color="Color.Secondary">
|
||||
L'agent n'a rien remonté pour ces filtres.
|
||||
</MudText>
|
||||
</MudPaper>
|
||||
</NoRecordsContent>
|
||||
</MudTable>
|
||||
|
||||
<div class="d-flex align-center pa-4 mt-4" Style="border-radius: 8px;">
|
||||
<MudText Typo="Typo.body2" Class="mr-4">
|
||||
Page @_logPage sur @_logTotalPages (@_logTotal entrées)
|
||||
</MudText>
|
||||
<MudSpacer />
|
||||
<MudButton Variant="Variant.Outlined" Size="Size.Small" Class="mr-2"
|
||||
Disabled="@(_logPage <= 1)" OnClick="@(() => GoToLogPage(_logPage - 1))">
|
||||
← Précédent
|
||||
</MudButton>
|
||||
<MudButton Variant="Variant.Outlined" Size="Size.Small"
|
||||
Disabled="@(_logPage >= _logTotalPages)" OnClick="@(() => GoToLogPage(_logPage + 1))">
|
||||
Suivant →
|
||||
</MudButton>
|
||||
</div>
|
||||
}
|
||||
</ChildContent>
|
||||
<Actions>
|
||||
<MudSwitch T="bool" Value="@_autoRefresh" ValueChanged="@ToggleAutoRefresh"
|
||||
Color="Color.Primary" Class="mr-2" AdornmentLabel="Auto-refresh"
|
||||
Label="Auto-refresh" />
|
||||
<MudTooltip Text="Rafraîchir">
|
||||
<MudIconButton Icon="@Icons.Material.Filled.Refresh" Size="Size.Small"
|
||||
OnClick="@(() => LoadLogsAsync(keepPage: true))" aria-label="Actualiser les logs" />
|
||||
</MudTooltip>
|
||||
</Actions>
|
||||
</SectionCard>
|
||||
|
||||
<div class="d-flex gap-4 mt-4">
|
||||
<MudButton Variant="Variant.Outlined" Color="Color.Default"
|
||||
OnClick="@(() => Nav.NavigateTo($"/sites/{_agent.SiteId}/agents"))">
|
||||
@@ -316,6 +434,19 @@ else
|
||||
private bool _confirmDeleteVisible;
|
||||
private string _deletingKey = string.Empty;
|
||||
private bool _deleting;
|
||||
|
||||
// Logs
|
||||
private IReadOnlyList<AgentLogItem>? _logs;
|
||||
private bool _logsLoading;
|
||||
private bool _logsError;
|
||||
private int _logPage = 1;
|
||||
private int _logTotalPages = 1;
|
||||
private int _logTotal;
|
||||
private string? _logLevel;
|
||||
private string? _logSearch;
|
||||
private bool _autoRefresh;
|
||||
private CancellationTokenSource? _refreshCts;
|
||||
private bool _disposed;
|
||||
private readonly DialogOptions _dialogOptions = new()
|
||||
{
|
||||
MaxWidth = MaxWidth.Small,
|
||||
@@ -329,7 +460,10 @@ else
|
||||
{
|
||||
_agent = await Api.GetAgentAsync(Id);
|
||||
if (_agent is not null)
|
||||
{
|
||||
await LoadSettingsAsync();
|
||||
await LoadLogsAsync(keepPage: false);
|
||||
}
|
||||
}
|
||||
catch { Snackbar.Add(UiErrors.OperationFailed(), Severity.Error); }
|
||||
finally { _loading = false; }
|
||||
@@ -478,9 +612,81 @@ else
|
||||
finally { _deleting = false; }
|
||||
}
|
||||
|
||||
private async Task LoadLogsAsync(bool keepPage)
|
||||
{
|
||||
if (!keepPage) _logPage = 1;
|
||||
_logsError = false;
|
||||
_logsLoading = true;
|
||||
try
|
||||
{
|
||||
var result = await Api.GetAgentLogsAsync(Id, _logLevel, _logSearch, _logPage);
|
||||
if (result is not null)
|
||||
{
|
||||
_logs = result.Items;
|
||||
_logTotal = result.TotalCount;
|
||||
_logTotalPages = Math.Max(1, (int)Math.Ceiling(result.TotalCount / (double)result.PageSize));
|
||||
}
|
||||
}
|
||||
catch
|
||||
{
|
||||
_logsError = true;
|
||||
_logs = [];
|
||||
}
|
||||
finally
|
||||
{
|
||||
_logsLoading = false;
|
||||
if (!_disposed) await InvokeAsync(StateHasChanged);
|
||||
}
|
||||
}
|
||||
|
||||
private async Task GoToLogPage(int page)
|
||||
{
|
||||
_logPage = page;
|
||||
await LoadLogsAsync(keepPage: true);
|
||||
}
|
||||
|
||||
private async Task ToggleAutoRefresh(bool enabled)
|
||||
{
|
||||
_autoRefresh = enabled;
|
||||
_refreshCts?.Cancel();
|
||||
_refreshCts?.Dispose();
|
||||
_refreshCts = null;
|
||||
|
||||
if (enabled)
|
||||
{
|
||||
_refreshCts = new CancellationTokenSource();
|
||||
_ = AutoRefreshLoopAsync(_refreshCts.Token);
|
||||
}
|
||||
}
|
||||
|
||||
private async Task AutoRefreshLoopAsync(CancellationToken ct)
|
||||
{
|
||||
try
|
||||
{
|
||||
while (!ct.IsCancellationRequested)
|
||||
{
|
||||
await Task.Delay(TimeSpan.FromSeconds(10), ct);
|
||||
if (!_disposed && _agent is not null)
|
||||
await LoadLogsAsync(keepPage: true);
|
||||
}
|
||||
}
|
||||
catch (OperationCanceledException) { /* arrêt volontaire */ }
|
||||
}
|
||||
|
||||
private static Color GetLogLevelColor(string level) => level switch
|
||||
{
|
||||
"Critical" or "Error" => Color.Error,
|
||||
"Warning" => Color.Warning,
|
||||
"Information" => Color.Info,
|
||||
_ => Color.Default
|
||||
};
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
// No unmanaged resources to dispose
|
||||
_disposed = true;
|
||||
_refreshCts?.Cancel();
|
||||
_refreshCts?.Dispose();
|
||||
_refreshCts = null;
|
||||
}
|
||||
|
||||
private static Color GetStatusColor(string status) => status switch
|
||||
|
||||
@@ -4,6 +4,8 @@ using Heimdall.Application.AgentDiscovery.Commands.SubmitAgentDiscovery;
|
||||
using Heimdall.Application.Agents.Queries.GetAgent;
|
||||
using Heimdall.Application.Agents.Queries.GetAgentsBySite;
|
||||
using Heimdall.Application.Agents.Queries.GetAllAgents;
|
||||
using Heimdall.Application.AgentLogs.Commands.SubmitAgentLogs;
|
||||
using Heimdall.Application.AgentLogs.Queries.GetAgentLogs;
|
||||
using Heimdall.Application.DTOs;
|
||||
using Heimdall.Domain.Enums;
|
||||
using Heimdall.Infrastructure.Security;
|
||||
@@ -117,6 +119,44 @@ public class AgentsController : ControllerBase
|
||||
return Ok(result.Data);
|
||||
}
|
||||
|
||||
/// <summary>Submit a batch of log entries from an agent (API Key auth).</summary>
|
||||
[Authorize(AuthenticationSchemes = "ApiKey")]
|
||||
[HttpPost("{id:guid}/logs")]
|
||||
[ProducesResponseType(StatusCodes.Status200OK)]
|
||||
[ProducesResponseType(typeof(void), StatusCodes.Status400BadRequest)]
|
||||
[ProducesResponseType(typeof(void), StatusCodes.Status404NotFound)]
|
||||
public async Task<IActionResult> SubmitLogs(
|
||||
Guid id, [FromBody] SubmitAgentLogsRequest request, CancellationToken ct)
|
||||
{
|
||||
var command = new SubmitAgentLogsCommand(id, request.Entries);
|
||||
var result = await _mediator.Send(command, ct);
|
||||
return result.IsSuccess
|
||||
? Ok()
|
||||
: StatusCode(result.StatusCode ?? 400, new { error = result.Error });
|
||||
}
|
||||
|
||||
/// <summary>Get agent log entries (JWT auth).</summary>
|
||||
[Authorize(AuthenticationSchemes = "JwtBearer,Cookies", Policy = AppPermissions.SiteRead)]
|
||||
[HttpGet("{id:guid}/logs")]
|
||||
[ProducesResponseType(typeof(PagedResult<AgentLogEntryDto>), StatusCodes.Status200OK)]
|
||||
[ProducesResponseType(typeof(void), StatusCodes.Status400BadRequest)]
|
||||
public async Task<IActionResult> GetLogs(
|
||||
Guid id,
|
||||
[FromQuery] int page = 1,
|
||||
[FromQuery] int pageSize = 50,
|
||||
[FromQuery] string? level = null,
|
||||
[FromQuery] DateTime? from = null,
|
||||
[FromQuery] DateTime? to = null,
|
||||
[FromQuery] string? search = null,
|
||||
CancellationToken ct = default)
|
||||
{
|
||||
var result = await _mediator.Send(
|
||||
new GetAgentLogsQuery(id, page, pageSize, level, from, to, search), ct);
|
||||
if (!result.IsSuccess)
|
||||
return StatusCode(result.StatusCode ?? 400, new { error = result.Error });
|
||||
return Ok(result.Data);
|
||||
}
|
||||
|
||||
/// <summary>List all agents across all sites.</summary>
|
||||
[Authorize(AuthenticationSchemes = "JwtBearer,Cookies", Policy = AppPermissions.SiteRead)]
|
||||
[HttpGet]
|
||||
|
||||
@@ -397,6 +397,16 @@ public class HeimdallApiClient
|
||||
return await client.GetFromJsonAsync<PagedData<AuditLogItem>>(query, Json);
|
||||
}
|
||||
|
||||
public async Task<PagedData<AgentLogItem>?> GetAgentLogsAsync(
|
||||
Guid agentId, string? level = null, string? search = null, int page = 1, int pageSize = 50)
|
||||
{
|
||||
var client = CreateClient();
|
||||
var query = $"api/agents/{agentId}/logs?page={page}&pageSize={pageSize}";
|
||||
if (!string.IsNullOrEmpty(level)) query += $"&level={Uri.EscapeDataString(level)}";
|
||||
if (!string.IsNullOrEmpty(search)) query += $"&search={Uri.EscapeDataString(search)}";
|
||||
return await client.GetFromJsonAsync<PagedData<AgentLogItem>>(query, Json);
|
||||
}
|
||||
|
||||
public async Task<StatsResult?> GetStatsAsync()
|
||||
{
|
||||
var client = CreateClient();
|
||||
@@ -650,6 +660,17 @@ public class AgentItem
|
||||
public long? UptimeSeconds { get; set; }
|
||||
}
|
||||
|
||||
public class AgentLogItem
|
||||
{
|
||||
public Guid Id { get; set; }
|
||||
public Guid AgentId { get; set; }
|
||||
public DateTime TimestampUtc { get; set; }
|
||||
public string Level { get; set; } = "";
|
||||
public string Message { get; set; } = "";
|
||||
public string? Exception { get; set; }
|
||||
public string? Source { get; set; }
|
||||
}
|
||||
|
||||
// ─── Settings DTOs ────────────────────────────────────────────────
|
||||
|
||||
public record AppSettingItem(
|
||||
|
||||
@@ -257,6 +257,7 @@ public class AgentRegistrationServiceTests : IDisposable
|
||||
state,
|
||||
Options.Create(_options),
|
||||
_metrics,
|
||||
new Logging.LogBufferService(),
|
||||
NullLogger<AgentRegistrationService>.Instance);
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,91 @@
|
||||
using Heimdall.Agent.Logging;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Shouldly;
|
||||
|
||||
namespace Heimdall.Agent.Tests;
|
||||
|
||||
public class LogBufferServiceTests
|
||||
{
|
||||
private static BufferedLogEntry Entry(string message, LogLevel level = LogLevel.Information)
|
||||
=> new(DateTime.UtcNow, level, message, null, "TestService");
|
||||
|
||||
[Fact]
|
||||
public void TakeAll_ReturnsEntriesInOrder()
|
||||
{
|
||||
var buffer = new LogBufferService(10);
|
||||
buffer.Enqueue(Entry("first"));
|
||||
buffer.Enqueue(Entry("second"));
|
||||
buffer.Enqueue(Entry("third"));
|
||||
|
||||
var entries = buffer.TakeAll();
|
||||
|
||||
entries.Count.ShouldBe(3);
|
||||
entries[0].Message.ShouldBe("first");
|
||||
entries[1].Message.ShouldBe("second");
|
||||
entries[2].Message.ShouldBe("third");
|
||||
buffer.Count.ShouldBe(0);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TakeAll_WhenEmpty_ReturnsEmptyList()
|
||||
{
|
||||
var buffer = new LogBufferService(10);
|
||||
buffer.TakeAll().ShouldBeEmpty();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Enqueue_WhenFull_DropsOldestAndCounts()
|
||||
{
|
||||
var buffer = new LogBufferService(3);
|
||||
buffer.Enqueue(Entry("a"));
|
||||
buffer.Enqueue(Entry("b"));
|
||||
buffer.Enqueue(Entry("c"));
|
||||
|
||||
// Overflow: the newest entry must survive (fresh Error > old Warnings).
|
||||
buffer.Enqueue(Entry("d"));
|
||||
buffer.Enqueue(Entry("e"));
|
||||
|
||||
var entries = buffer.TakeAll();
|
||||
entries.Select(e => e.Message).ShouldBe(["c", "d", "e"]);
|
||||
buffer.DroppedCount.ShouldBe(2);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Requeue_RestoresFailedUploadEntries()
|
||||
{
|
||||
var buffer = new LogBufferService(10);
|
||||
buffer.Enqueue(Entry("a"));
|
||||
var taken = buffer.TakeAll();
|
||||
|
||||
buffer.Requeue(taken);
|
||||
|
||||
buffer.Count.ShouldBe(1);
|
||||
buffer.TakeAll()[0].Message.ShouldBe("a");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Sanitize_MasksSecrets()
|
||||
{
|
||||
LogSanitizer.Sanitize("Connecting with password=hunter2 and token=abc123")
|
||||
.ShouldNotContain("hunter2");
|
||||
LogSanitizer.Sanitize("Connecting with password=hunter2 and token=abc123")
|
||||
.ShouldContain("***");
|
||||
|
||||
LogSanitizer.Sanitize("Authorization: Bearer eyJhbGciOiJIUzI1NiJ9")
|
||||
.ShouldNotContain("eyJhbGciOiJIUzI1NiJ9");
|
||||
|
||||
LogSanitizer.Sanitize("{\"api_key\":\"super-secret-value\",\"user\":\"bob\"}")
|
||||
.ShouldNotContain("super-secret-value");
|
||||
|
||||
LogSanitizer.Sanitize("snapshotUrl=https://cdn.example.com/snap/1.jpg")
|
||||
.ShouldNotContain("cdn.example.com");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Sanitize_LeavesNormalMessagesIntact()
|
||||
{
|
||||
const string message = "Heartbeat OK — agent online";
|
||||
LogSanitizer.Sanitize(message).ShouldBe(message);
|
||||
LogSanitizer.Sanitize(null).ShouldBeEmpty();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,81 @@
|
||||
using Heimdall.Application.AgentLogs.Queries.GetAgentLogs;
|
||||
using Heimdall.Application.Common;
|
||||
using Heimdall.Application.Tests.Common;
|
||||
using Heimdall.Domain.Entities;
|
||||
using Heimdall.Domain.Enums;
|
||||
using NSubstitute;
|
||||
using Shouldly;
|
||||
|
||||
namespace Heimdall.Application.Tests.Handlers.AgentLogs;
|
||||
|
||||
public class GetAgentLogsHandlerTests
|
||||
{
|
||||
private readonly Agent _agent = new(Guid.NewGuid(), "agent-1", "agent-1", "1.0.0");
|
||||
private readonly Guid _otherAgent = Guid.NewGuid();
|
||||
|
||||
private static AgentLogEntry Entry(Guid agentId, AgentLogLevel level, string message, DateTime ts)
|
||||
=> new(agentId, ts, level, message, null, "TestService");
|
||||
|
||||
private IApplicationDbContext CreateContext()
|
||||
{
|
||||
var context = Substitute.For<IApplicationDbContext>();
|
||||
context.Agents.Returns(MockDbSetHelper.CreateFor<Agent>([_agent]));
|
||||
context.AgentLogEntries.Returns(MockDbSetHelper.CreateFor<AgentLogEntry>(
|
||||
[
|
||||
Entry(_agent.Id, AgentLogLevel.Warning, "first warning", DateTime.UtcNow.AddMinutes(-2)),
|
||||
Entry(_agent.Id, AgentLogLevel.Error, "ffmpeg crash", DateTime.UtcNow.AddMinutes(-1)),
|
||||
Entry(_agent.Id, AgentLogLevel.Information, "started", DateTime.UtcNow),
|
||||
Entry(_otherAgent, AgentLogLevel.Error, "other agent", DateTime.UtcNow)
|
||||
]));
|
||||
return context;
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Get_ReturnsOnlyThisAgentEntries_NewestFirst()
|
||||
{
|
||||
var handler = new GetAgentLogsHandler(CreateContext());
|
||||
|
||||
var result = await handler.Handle(
|
||||
new GetAgentLogsQuery(_agent.Id, 1, 50), CancellationToken.None);
|
||||
|
||||
result.IsSuccess.ShouldBeTrue();
|
||||
result.Data!.TotalCount.ShouldBe(3);
|
||||
result.Data.Items.Select(i => i.Message).ShouldBe(["started", "ffmpeg crash", "first warning"]);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Get_FiltersByLevel()
|
||||
{
|
||||
var handler = new GetAgentLogsHandler(CreateContext());
|
||||
|
||||
var result = await handler.Handle(
|
||||
new GetAgentLogsQuery(_agent.Id, 1, 50, Level: "Error"), CancellationToken.None);
|
||||
|
||||
result.Data!.TotalCount.ShouldBe(1);
|
||||
result.Data.Items.Single().Level.ShouldBe("Error");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Get_SearchFiltersMessage()
|
||||
{
|
||||
var handler = new GetAgentLogsHandler(CreateContext());
|
||||
|
||||
var result = await handler.Handle(
|
||||
new GetAgentLogsQuery(_agent.Id, 1, 50, Search: "ffmpeg"), CancellationToken.None);
|
||||
|
||||
result.Data!.TotalCount.ShouldBe(1);
|
||||
result.Data.Items.Single().Message.ShouldBe("ffmpeg crash");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Get_PaginationSlices()
|
||||
{
|
||||
var handler = new GetAgentLogsHandler(CreateContext());
|
||||
|
||||
var result = await handler.Handle(
|
||||
new GetAgentLogsQuery(_agent.Id, 1, 2), CancellationToken.None);
|
||||
|
||||
result.Data!.TotalCount.ShouldBe(3);
|
||||
result.Data.Items.Count.ShouldBe(2);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,84 @@
|
||||
using Heimdall.Application.AgentLogs.Commands.SubmitAgentLogs;
|
||||
using Heimdall.Application.Common;
|
||||
using Heimdall.Application.DTOs;
|
||||
using Heimdall.Application.Tests.Common;
|
||||
using Heimdall.Domain.Entities;
|
||||
using NSubstitute;
|
||||
using Shouldly;
|
||||
|
||||
namespace Heimdall.Application.Tests.Handlers.AgentLogs;
|
||||
|
||||
public class SubmitAgentLogsHandlerTests
|
||||
{
|
||||
private readonly Agent _agent = new(Guid.NewGuid(), "agent-1", "agent-1", "1.0.0");
|
||||
|
||||
private IApplicationDbContext CreateContext()
|
||||
{
|
||||
var context = Substitute.For<IApplicationDbContext>();
|
||||
context.Agents.Returns(MockDbSetHelper.CreateFor<Agent>([_agent]));
|
||||
context.AgentLogEntries.Returns(MockDbSetHelper.CreateFor<AgentLogEntry>());
|
||||
return context;
|
||||
}
|
||||
|
||||
private static SubmitAgentLogsCommand Command(
|
||||
Guid agentId, params AgentLogEntryRequest[] entries) => new(agentId, entries);
|
||||
|
||||
[Fact]
|
||||
public async Task Submit_ValidBatch_ReturnsSuccessAndPersists()
|
||||
{
|
||||
var context = CreateContext();
|
||||
var handler = new SubmitAgentLogsHandler(context);
|
||||
var command = Command(_agent.Id,
|
||||
new AgentLogEntryRequest(DateTime.UtcNow, "Warning", "Heartbeat failed"),
|
||||
new AgentLogEntryRequest(DateTime.UtcNow, "Error", "FFmpeg crashed", "System.Exception: boom"));
|
||||
|
||||
var result = await handler.Handle(command, CancellationToken.None);
|
||||
|
||||
result.IsSuccess.ShouldBeTrue();
|
||||
context.AgentLogEntries.Count().ShouldBe(2);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Submit_NonexistentAgent_ReturnsNotFound()
|
||||
{
|
||||
var context = CreateContext();
|
||||
var handler = new SubmitAgentLogsHandler(context);
|
||||
var command = Command(Guid.NewGuid(),
|
||||
new AgentLogEntryRequest(DateTime.UtcNow, "Warning", "msg"));
|
||||
|
||||
var result = await handler.Handle(command, CancellationToken.None);
|
||||
|
||||
result.IsSuccess.ShouldBeFalse();
|
||||
result.StatusCode.ShouldBe(404);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Submit_InvalidLevelEntries_AreSkipped()
|
||||
{
|
||||
var context = CreateContext();
|
||||
var handler = new SubmitAgentLogsHandler(context);
|
||||
var command = Command(_agent.Id,
|
||||
new AgentLogEntryRequest(DateTime.UtcNow, "Warning", "valid"),
|
||||
new AgentLogEntryRequest(DateTime.UtcNow, "NotALevel", "invalid level"));
|
||||
|
||||
var result = await handler.Handle(command, CancellationToken.None);
|
||||
|
||||
result.IsSuccess.ShouldBeTrue();
|
||||
context.AgentLogEntries.Count().ShouldBe(1);
|
||||
context.AgentLogEntries.Single().Message.ShouldBe("valid");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Submit_AllEntriesInvalid_ReturnsBadRequest()
|
||||
{
|
||||
var context = CreateContext();
|
||||
var handler = new SubmitAgentLogsHandler(context);
|
||||
var command = Command(_agent.Id,
|
||||
new AgentLogEntryRequest(DateTime.UtcNow, "Bogus", "x"));
|
||||
|
||||
var result = await handler.Handle(command, CancellationToken.None);
|
||||
|
||||
result.IsSuccess.ShouldBeFalse();
|
||||
result.StatusCode.ShouldBe(400);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,127 @@
|
||||
using Bunit;
|
||||
using Heimdall.Web.Components.Pages;
|
||||
using Heimdall.Web.Services;
|
||||
using Shouldly;
|
||||
|
||||
namespace Heimdall.Web.Tests.Components.Pages;
|
||||
|
||||
public class AgentDetailLogsTests : PageTestBase
|
||||
{
|
||||
private static readonly Guid AgentId = Guid.NewGuid();
|
||||
private static readonly Guid SiteId = Guid.NewGuid();
|
||||
|
||||
private static AgentItem Agent() => new()
|
||||
{
|
||||
Id = AgentId,
|
||||
SiteId = SiteId,
|
||||
SiteName = "Site Test",
|
||||
Name = "Agent Caméras",
|
||||
Hostname = "cam-01",
|
||||
Version = "1.0.0",
|
||||
Status = "Online",
|
||||
CreatedAt = DateTime.UtcNow.AddDays(-5)
|
||||
};
|
||||
|
||||
private static AgentLogItem Log(
|
||||
string message,
|
||||
string level = "Warning",
|
||||
string? source = "AgentRegistrationService",
|
||||
string? exception = null) => new()
|
||||
{
|
||||
Id = Guid.NewGuid(),
|
||||
AgentId = AgentId,
|
||||
TimestampUtc = DateTime.UtcNow.AddMinutes(-5),
|
||||
Level = level,
|
||||
Message = message,
|
||||
Source = source,
|
||||
Exception = exception
|
||||
};
|
||||
|
||||
private void HandlerLogs(PagedData<AgentLogItem> data)
|
||||
=> Handler.OnGet($"api/agents/{AgentId}/logs", data);
|
||||
|
||||
private void HandlerBase()
|
||||
{
|
||||
// Order matters: RoutedHandler matches by substring, first route wins.
|
||||
Handler.OnGet($"api/agents/{AgentId}/logs", new PagedData<AgentLogItem>([], 0, 1, 50));
|
||||
Handler.OnGet("api/agents/", Agent());
|
||||
Handler.OnGet("api/settings/agent/", new List<AgentSettingItem>());
|
||||
Handler.OnGet("api/settings", new List<AppSettingItem>());
|
||||
LoginAs();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void AgentLogs_AfficheLesEntreesRemontees()
|
||||
{
|
||||
HandlerLogs(new PagedData<AgentLogItem>(
|
||||
[Log("Heartbeat failed: ServiceUnavailable", "Error", "AgentRegistrationService")],
|
||||
1, 1, 50));
|
||||
HandlerBase();
|
||||
|
||||
var cut = RenderPage<AgentDetail>(p => p.Add(x => x.Id, AgentId));
|
||||
|
||||
cut.WaitForAssertion(() =>
|
||||
{
|
||||
cut.Markup.ShouldContain("Agent : Agent Caméras");
|
||||
cut.Markup.ShouldContain("Heartbeat failed: ServiceUnavailable");
|
||||
cut.Markup.ShouldContain("Error");
|
||||
cut.Markup.ShouldContain("AgentRegistrationService");
|
||||
cut.Markup.ShouldContain("1 entrée");
|
||||
});
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void AgentLogs_AfficheVide_QuandAucuneEntree()
|
||||
{
|
||||
HandlerBase();
|
||||
|
||||
var cut = RenderPage<AgentDetail>(p => p.Add(x => x.Id, AgentId));
|
||||
|
||||
cut.WaitForAssertion(() =>
|
||||
{
|
||||
cut.Markup.ShouldContain("Aucun log");
|
||||
cut.Markup.ShouldContain("L'agent n'a rien remonté pour ces filtres.");
|
||||
});
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void AgentLogs_RefreshManuel_RechargeLesLogs()
|
||||
{
|
||||
HandlerLogs(new PagedData<AgentLogItem>(
|
||||
[Log("First batch entry", "Warning")], 1, 1, 50));
|
||||
HandlerBase();
|
||||
|
||||
var cut = RenderPage<AgentDetail>(p => p.Add(x => x.Id, AgentId));
|
||||
|
||||
cut.WaitForAssertion(() => cut.Markup.ShouldContain("First batch entry"));
|
||||
|
||||
var initialCount = Handler.Requests.Count(r =>
|
||||
r.RequestUri!.AbsolutePath.Contains($"/api/agents/{AgentId}/logs"));
|
||||
|
||||
// Le bouton refresh (aria-label) recharge les logs.
|
||||
cut.Find("button[aria-label='Actualiser les logs']").Click();
|
||||
|
||||
cut.WaitForAssertion(() =>
|
||||
{
|
||||
var logRequests = Handler.Requests.Count(r =>
|
||||
r.RequestUri!.AbsolutePath.Contains($"/api/agents/{AgentId}/logs"));
|
||||
logRequests.ShouldBeGreaterThan(initialCount);
|
||||
});
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void AgentLogs_Pagination_AfficheLeCompteur()
|
||||
{
|
||||
HandlerLogs(new PagedData<AgentLogItem>(
|
||||
[Log("Warning one"), Log("Warning two")], 7, 1, 50));
|
||||
HandlerBase();
|
||||
|
||||
var cut = RenderPage<AgentDetail>(p => p.Add(x => x.Id, AgentId));
|
||||
|
||||
cut.WaitForAssertion(() =>
|
||||
{
|
||||
cut.Markup.ShouldContain("Page 1 sur 1");
|
||||
cut.Markup.ShouldContain("7 entrées");
|
||||
});
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user