Files
Heimdall/src/Heimdall.Agent/Program.cs
T
Arnaud Dartois 0136bf33ec feat(logs): remontée des logs agents vers le central — buffer, API, UI (Fixes #50 #51 #52)
- 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)
2026-08-11 18:51:52 +02:00

99 lines
3.4 KiB
C#

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);
// ── Sentry (GlitchTip) — DSN from config pipeline with legacy env var fallback ──
// Primary: Sentry:Dsn from appsettings.json or env var Sentry__Dsn
// Fallback: legacy SENTRY_DSN env var (Docker backward compat)
// Neither set → DSN is null → Sentry SDK no-ops gracefully
var sentryDsn = builder.Configuration["Sentry:Dsn"]
?? Environment.GetEnvironmentVariable("SENTRY_DSN");
if (!string.IsNullOrEmpty(sentryDsn))
{
builder.WebHost.UseSentry((SentryAspNetCoreOptions options) =>
{
options.Dsn = sentryDsn;
options.MinimumBreadcrumbLevel = LogLevel.Debug;
options.MinimumEventLevel = LogLevel.Error;
options.TracesSampleRate = 0.05;
options.MaxRequestBodySize = Sentry.Extensibility.RequestSize.Small;
options.ProfilesSampleRate = 0.05;
});
}
// Strongly-typed configuration with validation
builder.Services.AddOptions<AgentOptions>()
.BindConfiguration(AgentOptions.SectionName)
.ValidateDataAnnotations()
.ValidateOnStart();
// HTTP clients
builder.Services.AddHttpClient("Central", (sp, client) =>
{
var options = sp.GetRequiredService<IOptions<AgentOptions>>().Value;
var baseUrl = options.CentralUrl.EndsWith('/') ? options.CentralUrl : options.CentralUrl + "/";
client.BaseAddress = new Uri(baseUrl);
client.Timeout = TimeSpan.FromSeconds(10);
});
builder.Services.AddHttpClient("IpResolver", client =>
{
client.Timeout = TimeSpan.FromSeconds(5);
});
// Agent services
builder.Services.AddSingleton<AgentState>(sp =>
{
var state = new AgentState();
var options = sp.GetRequiredService<IOptions<AgentOptions>>().Value;
var stateDir = options.StateDirectory
?? (OperatingSystem.IsLinux() ? "/var/lib/heimdall" : Directory.GetCurrentDirectory());
state.ConfigureStateDirectory(stateDir);
return state;
});
builder.Services.AddSingleton<SystemMetricsProvider>();
builder.Services.AddSingleton<NetworkCameraScanner>();
builder.Services.AddSingleton<DiscoveryScanTrigger>();
builder.Services.AddSingleton<AgentCredentialStore>();
builder.Services.AddSingleton<RuntimeLogLevel>();
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"]);
var app = builder.Build();
// Health endpoint
app.MapHealthChecks("/healthz", new HealthCheckOptions
{
Predicate = _ => true,
ResultStatusCodes =
{
[HealthStatus.Healthy] = StatusCodes.Status200OK,
[HealthStatus.Degraded] = StatusCodes.Status200OK,
[HealthStatus.Unhealthy] = StatusCodes.Status503ServiceUnavailable,
}
});
await app.RunAsync();