using Cassandra; using JiShe.CollectBus.Cassandra; using Microsoft.Extensions.Diagnostics.HealthChecks; namespace JiShe.CollectBus.Host.HealthChecks { /// /// CassandraHealthCheck /// /// public class CassandraHealthCheck : IHealthCheck { private readonly IConfiguration _configuration; /// /// Initializes a new instance of the class. /// /// The configuration. public CassandraHealthCheck(IConfiguration configuration) { _configuration = configuration; } /// /// Runs the health check, returning the status of the component being checked. /// /// A context object associated with the current execution. /// A that can be used to cancel the health check. /// /// A that completes when the health check has finished, yielding the status of the component being checked. /// public async Task CheckHealthAsync(HealthCheckContext context, CancellationToken cancellationToken = default) { var cassandraConfig = new CassandraConfig(); _configuration.GetSection("Cassandra").Bind(cassandraConfig); try { var clusterBuilder = Cluster.Builder(); foreach (var node in cassandraConfig.Nodes) { clusterBuilder.AddContactPoint(node.Host) .WithPort(node.Port); } clusterBuilder.WithCredentials(cassandraConfig.Username, cassandraConfig.Password); var cluster = clusterBuilder.Build(); using var session = await cluster.ConnectAsync(); var result = await Task.FromResult(session.Execute("SELECT release_version FROM system.local")); var version = result.First().GetValue("release_version"); return HealthCheckResult.Healthy($"Cassandra is healthy. Version: {version}"); } catch (Exception ex) { return new HealthCheckResult(context.Registration.FailureStatus, $"Cassandra is unhealthy: {ex.Message}", ex); } } } }