-
Notifications
You must be signed in to change notification settings - Fork 803
/
ElasticsearchHealthCheck.cs
88 lines (73 loc) · 3.27 KB
/
ElasticsearchHealthCheck.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
using System.Collections.Concurrent;
using Elasticsearch.Net;
using Microsoft.Extensions.Diagnostics.HealthChecks;
using Nest;
namespace HealthChecks.Elasticsearch;
public class ElasticsearchHealthCheck : IHealthCheck
{
private static readonly ConcurrentDictionary<string, ElasticClient> _connections = new();
private readonly ElasticsearchOptions _options;
public ElasticsearchHealthCheck(ElasticsearchOptions options)
{
_options = Guard.ThrowIfNull(options);
}
/// <inheritdoc />
public async Task<HealthCheckResult> CheckHealthAsync(HealthCheckContext context, CancellationToken cancellationToken = default)
{
try
{
if (!_connections.TryGetValue(_options.Uri, out var lowLevelClient))
{
var settings = new ConnectionSettings(new Uri(_options.Uri));
if (_options.RequestTimeout.HasValue)
{
settings = settings.RequestTimeout(_options.RequestTimeout.Value);
}
if (_options.AuthenticateWithBasicCredentials)
{
settings = settings.BasicAuthentication(_options.UserName, _options.Password);
}
else if (_options.AuthenticateWithCertificate)
{
settings = settings.ClientCertificate(_options.Certificate);
}
else if (_options.AuthenticateWithApiKey)
{
settings = settings.ApiKeyAuthentication(_options.ApiKeyAuthenticationCredentials);
}
if (_options.CertificateValidationCallback != null)
{
settings = settings.ServerCertificateValidationCallback(_options.CertificateValidationCallback);
}
lowLevelClient = new ElasticClient(settings);
if (!_connections.TryAdd(_options.Uri, lowLevelClient))
{
lowLevelClient = _connections[_options.Uri];
}
}
if (_options.UseClusterHealthApi)
{
var healthResponse = await lowLevelClient.Cluster.HealthAsync(ct: cancellationToken).ConfigureAwait(false);
if (healthResponse.ApiCall.HttpStatusCode != 200)
{
return new HealthCheckResult(context.Registration.FailureStatus);
}
return healthResponse.Status switch
{
Health.Green => HealthCheckResult.Healthy(),
Health.Yellow => HealthCheckResult.Degraded(),
_ => new HealthCheckResult(context.Registration.FailureStatus)
};
}
var pingResult = await lowLevelClient.PingAsync(ct: cancellationToken).ConfigureAwait(false);
bool isSuccess = pingResult.ApiCall.HttpStatusCode == 200;
return isSuccess
? HealthCheckResult.Healthy()
: new HealthCheckResult(context.Registration.FailureStatus);
}
catch (Exception ex)
{
return new HealthCheckResult(context.Registration.FailureStatus, exception: ex);
}
}
}