Files
Heimdall/src/Heimdall.Agent/Program.cs
T

186 lines
7.9 KiB
C#
Raw Normal View History

using Sentry.AspNetCore;
using Heimdall.Agent;
using Heimdall.Agent.Logging;
using Heimdall.Agent.Services;
using Heimdall.Application.Discovery;
using Heimdall.Application.Metrics;
using Microsoft.AspNetCore.DataProtection;
using Microsoft.AspNetCore.Diagnostics.HealthChecks;
using Microsoft.Extensions.Diagnostics.HealthChecks;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using OpenTelemetry.Metrics;
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);
});
// Broker HTTP client — used by RemoteFrameBrokerService when AnalysisMode=Remote.
// BaseAddress is set from AgentOptions.BrokerUrl at client creation time.
builder.Services.AddHttpClient("Broker", (sp, client) =>
{
var options = sp.GetRequiredService<IOptions<AgentOptions>>().Value;
if (!string.IsNullOrEmpty(options.BrokerUrl))
{
var baseUrl = options.BrokerUrl.EndsWith('/') ? options.BrokerUrl : options.BrokerUrl + "/";
client.BaseAddress = new Uri(baseUrl);
}
client.Timeout = TimeSpan.FromSeconds(5);
});
// Data Protection — encrypts the agent API key at rest (issue #21). The key
// ring is persisted next to the state file so the agent can decrypt its
// identity after a restart. Directory locked to owner-only (0700). For
// production hardening against full-volume compromise, bind the key ring to a
// TPM/HSM-backed store or mount it outside the backed-up volume.
var stateDir = builder.Configuration["Agent:StateDirectory"]
?? (OperatingSystem.IsLinux() ? "/var/lib/heimdall" : Directory.GetCurrentDirectory());
var keysDir = Path.Combine(stateDir, "dp-keys");
Directory.CreateDirectory(keysDir);
if (OperatingSystem.IsLinux())
File.SetUnixFileMode(keysDir, UnixFileMode.UserRead | UnixFileMode.UserWrite | UnixFileMode.UserExecute);
builder.Services.AddDataProtection()
.SetApplicationName("Heimdall.Agent")
.PersistKeysToFileSystem(new DirectoryInfo(keysDir));
// Agent services
builder.Services.AddSingleton<AgentState>(sp =>
{
var state = new AgentState(
sp.GetRequiredService<IDataProtectionProvider>().CreateProtector(AgentState.KeyProtectionPurpose),
sp.GetRequiredService<ILogger<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>();
// Inventory providers (grouped under InventoryProviders to reduce constructor parameter count)
builder.Services.AddSingleton<CpuInfoProvider>();
builder.Services.AddSingleton<DiskInventoryProvider>();
builder.Services.AddSingleton<HostInfoProvider>();
builder.Services.AddSingleton<ContainerInfoProvider>();
builder.Services.AddSingleton<InventoryProviders>();
builder.Services.AddSingleton<GpuDetectorService>();
builder.Services.AddSingleton<NetworkCameraScanner>();
builder.Services.AddSingleton<HomeKitMdnsProbe>();
builder.Services.AddSingleton<ICameraDatabase, SqliteCameraDatabase>();
builder.Services.AddSingleton<CameraStatusReporterService>();
builder.Services.AddSingleton<ICameraStatusReporter>(sp => sp.GetRequiredService<CameraStatusReporterService>());
builder.Services.AddSingleton<DetectionReporterService>();
builder.Services.AddSingleton<IDetectionReporter>(sp => sp.GetRequiredService<DetectionReporterService>());
builder.Services.AddSingleton<DiscoveryScanTrigger>();
builder.Services.AddSingleton<AgentCredentialStore>();
builder.Services.AddSingleton<RuntimeLogLevel>();
builder.Services.AddHostedService<AgentRegistrationService>();
builder.Services.AddHostedService<ConfigReceiverService>();
builder.Services.AddHostedService<AgentDiscoveryService>();
// Video capture pipeline (ticket #1): FFmpeg capture per assigned camera,
// bounded snapshot channel, adaptive interval, frames → FrameAnalyzerService.
// Circuit breaker + degradation manager for graceful IA pipeline degradation.
builder.Services.AddSingleton<PipelineDegradationManager>();
builder.Services.AddSingleton<CircuitBreaker>();
builder.Services.AddSingleton<SceneStateTracker>();
builder.Services.AddSingleton<CameraConfigStore>();
builder.Services.AddSingleton<FrameAnalyzerService>(sp => new FrameAnalyzerService(
sp.GetRequiredService<ILogger<FrameAnalyzerService>>(),
sp.GetRequiredService<CircuitBreaker>(),
sp.GetRequiredService<PipelineDegradationManager>()));
builder.Services.AddSingleton<CameraStreamService>();
builder.Services.AddSingleton<FrameResizer>();
builder.Services.AddSingleton<RemoteFrameBrokerService>();
builder.Services.AddSingleton<IRemoteFrameBroker>(sp => sp.GetRequiredService<RemoteFrameBrokerService>());
builder.Services.AddHostedService<SnapshotPipelineService>();
// 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"])
.AddCheck<LiveHealthCheck>("live", tags: ["live"]);
// ── OpenTelemetry metrics (spec 13.1) ──────────────────────────────
builder.Services.AddOpenTelemetry()
.WithMetrics(metrics =>
{
metrics.AddPrometheusExporter();
metrics.AddMeter(HeimdallMetrics.MeterName);
});
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,
}
});
// ── Prometheus metrics endpoint (spec 13.1) ────────────────────────
app.MapPrometheusScrapingEndpoint("/metrics");
// Live health endpoint (MASTER_SPEC) — reports degradation level
app.MapHealthChecks("/health/live", new HealthCheckOptions
{
Predicate = check => check.Tags.Contains("live"),
ResultStatusCodes =
{
[HealthStatus.Healthy] = StatusCodes.Status200OK,
[HealthStatus.Degraded] = StatusCodes.Status503ServiceUnavailable,
[HealthStatus.Unhealthy] = StatusCodes.Status503ServiceUnavailable,
}
});
await app.RunAsync();