Merge pull request #50 from LD-Reborn/20-feature-add-ldap-healthchecks

Added LDAP health checks
This commit is contained in:
LD50
2025-10-03 17:30:28 +02:00
committed by GitHub
2 changed files with 37 additions and 0 deletions

View File

@@ -0,0 +1,31 @@
using Berufsschule_HAM.Services;
using Microsoft.Extensions.Diagnostics.HealthChecks;
namespace Berufsschule_HAM.HealthChecks;
public class DatabaseHealthCheck : IHealthCheck
{
private readonly ILogger<DatabaseHealthCheck> _logger;
private readonly LdapService _ldapService;
public DatabaseHealthCheck(ILogger<DatabaseHealthCheck> logger, LdapService ldapService)
{
_logger = logger;
_ldapService = ldapService;
}
public async Task<HealthCheckResult> CheckHealthAsync(HealthCheckContext context, CancellationToken cancellationToken = default)
{
_logger.LogTrace("CheckHealthAsync - Checking health");
try
{
await _ldapService.ListUsersAsync();
}
catch (Exception ex)
{
_logger.LogError(ex, "CheckHealthAsync - Unable to list users due to exception {ex.Message} - {ex.StackTrace}", [ex.Message, ex.StackTrace]);
return HealthCheckResult.Unhealthy();
}
_logger.LogTrace("CheckHealthAsync - Health check successful");
return HealthCheckResult.Healthy();
}
}

View File

@@ -4,6 +4,7 @@ using Serilog;
using Microsoft.AspNetCore.Authentication.Cookies;
using Berufsschule_HAM.Services;
using Berufsschule_HAM.Models;
using Berufsschule_HAM.HealthChecks;
var builder = WebApplication.CreateBuilder(args);
// Bind options
@@ -26,6 +27,9 @@ builder.Services.AddElmah<XmlFileErrorLog>(Options =>
builder.Services.AddSingleton<LdapService>();
builder.Services.AddSingleton<MigrationService>();
builder.Services.AddHealthChecks()
.AddCheck<DatabaseHealthCheck>("DatabaseHealthCheck");
builder.Services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
.AddCookie(options =>
{
@@ -53,6 +57,8 @@ app.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
app.MapHealthChecks("/healthz");
// Run migrations
using var scope = app.Services.CreateScope();
var migrationService = scope.ServiceProvider.GetRequiredService<MigrationService>();