Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions Directory.Packages.props
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@
<PackageVersion Include="Azure.Storage.Blobs" Version="12.26.0" />
<PackageVersion Include="Azure.Storage.Queues" Version="12.24.0" />
<PackageVersion Include="ClickHouse.Client" Version="7.14.0" />
<PackageVersion Include="Microsoft.Azure.Kusto.Data" Version="14.0.2" />
<PackageVersion Include="CliWrap" Version="3.9.0" />
<PackageVersion Include="Confluent.Kafka" Version="2.12.0" />
<PackageVersion Include="Consul" Version="1.7.14.9" />
Expand Down Expand Up @@ -102,6 +103,7 @@
<PackageVersion Include="Testcontainers.JanusGraph" Version="$(VersionTestContainers)" />
<PackageVersion Include="Testcontainers.Kafka" Version="$(VersionTestContainers)" />
<PackageVersion Include="Testcontainers.Keycloak" Version="$(VersionTestContainers)" />
<PackageVersion Include="Testcontainers.Kusto" Version="$(VersionTestContainers)" />
<PackageVersion Include="Testcontainers.LocalStack" Version="$(VersionTestContainers)" />
<PackageVersion Include="Testcontainers.MariaDb" Version="$(VersionTestContainers)" />
<PackageVersion Include="Testcontainers.Milvus" Version="$(VersionTestContainers)" />
Expand Down
1 change: 1 addition & 0 deletions HealthChecks.slnx
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@
<Project Path="src/NetEvolve.HealthChecks.Azure.ApplicationInsights/NetEvolve.HealthChecks.Azure.ApplicationInsights.csproj" />
<Project Path="src/NetEvolve.HealthChecks.Azure.Blobs/NetEvolve.HealthChecks.Azure.Blobs.csproj" />
<Project Path="src/NetEvolve.HealthChecks.Azure.EventHubs/NetEvolve.HealthChecks.Azure.EventHubs.csproj" />
<Project Path="src/NetEvolve.HealthChecks.Azure.Kusto/NetEvolve.HealthChecks.Azure.Kusto.csproj" />
<Project Path="src/NetEvolve.HealthChecks.Azure.Queues/NetEvolve.HealthChecks.Azure.Queues.csproj" />
<Project Path="src/NetEvolve.HealthChecks.Azure.ServiceBus/NetEvolve.HealthChecks.Azure.ServiceBus.csproj" />
<Project Path="src/NetEvolve.HealthChecks.Azure.Tables/NetEvolve.HealthChecks.Azure.Tables.csproj" />
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
namespace NetEvolve.HealthChecks.Azure.Kusto;

using System;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Diagnostics.HealthChecks;
using SourceGenerator.Attributes;

/// <summary>
/// Extensions methods for <see cref="IHealthChecksBuilder"/> with custom Health Checks.
/// </summary>
[HealthCheckHelper]
public static partial class DependencyInjectionExtensions
{
private static readonly string[] _defaultTags = ["azure", "kusto", "adx"];

/// <summary>
/// Adds a health check for Azure Kusto, to check the availability of the cluster and database.
/// </summary>
/// <param name="builder">The <see cref="IHealthChecksBuilder"/>.</param>
/// <param name="name">The name of the <see cref="KustoAvailableHealthCheck"/>.</param>
/// <param name="options">An optional action to configure.</param>
/// <param name="tags">A list of additional tags that can be used to filter sets of health checks. Optional.</param>
/// <exception cref="ArgumentNullException">The <paramref name="builder"/> is <see langword="null" />.</exception>
/// <exception cref="ArgumentNullException">The <paramref name="name"/> is <see langword="null" />.</exception>
/// <exception cref="ArgumentException">The <paramref name="name"/> is <see langword="null" /> or <c>whitespace</c>.</exception>
/// <exception cref="ArgumentException">The <paramref name="name"/> is already in use.</exception>
/// <exception cref="ArgumentNullException">The <paramref name="tags"/> is <see langword="null" />.</exception>
public static IHealthChecksBuilder AddKustoAvailability(
[NotNull] this IHealthChecksBuilder builder,
[NotNull] string name,
Action<KustoAvailableOptions>? options = null,
params string[] tags
)
{
ArgumentNullException.ThrowIfNull(builder);
ArgumentException.ThrowIfNullOrEmpty(name);
ArgumentNullException.ThrowIfNull(tags);

if (!builder.IsServiceTypeRegistered<AzureKustoCheckMarker>())
{
_ = builder
.Services.AddSingleton<AzureKustoCheckMarker>()
.AddSingleton<KustoAvailableHealthCheck>()
.ConfigureOptions<KustoAvailableConfigure>();
}

builder.ThrowIfNameIsAlreadyUsed<KustoAvailableHealthCheck>(name);

if (options is not null)
{
_ = builder.Services.Configure(name, options);
}

return builder.AddCheck<KustoAvailableHealthCheck>(
name,
HealthStatus.Unhealthy,
_defaultTags.Union(tags, StringComparer.OrdinalIgnoreCase)
);
}

private sealed partial class AzureKustoCheckMarker;
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
namespace NetEvolve.HealthChecks.Azure.Kusto;

using System;
using System.Threading;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Options;
using static Microsoft.Extensions.Options.ValidateOptionsResult;

internal sealed class KustoAvailableConfigure
: IConfigureNamedOptions<KustoAvailableOptions>,
IValidateOptions<KustoAvailableOptions>
{
private readonly IConfiguration _configuration;

public KustoAvailableConfigure(IConfiguration configuration) => _configuration = configuration;

public void Configure(string? name, KustoAvailableOptions options)
{
ArgumentException.ThrowIfNullOrWhiteSpace(name);
_configuration.Bind($"HealthChecks:AzureKusto:{name}", options);
}

public void Configure(KustoAvailableOptions options) => Configure(Options.DefaultName, options);

public ValidateOptionsResult Validate(string? name, KustoAvailableOptions options)
{
if (string.IsNullOrWhiteSpace(name))
{
return Fail("The name cannot be null or whitespace.");
}

if (options is null)
{
return Fail("The option cannot be null.");
}

if (options.Timeout < Timeout.Infinite)
{
return Fail("The timeout value must be a positive number in milliseconds or -1 for an infinite timeout.");
}

if (string.IsNullOrWhiteSpace(options.ConnectionString) && options.ClusterUri is null)
{
return Fail("Either ConnectionString or ClusterUri must be provided.");
}

if (options.ClusterUri is not null && !options.ClusterUri.IsAbsoluteUri)
{
return Fail("The ClusterUri must be an absolute URI.");
}

return Success;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
namespace NetEvolve.HealthChecks.Azure.Kusto;

using System;
using System.Threading;
using System.Threading.Tasks;
using global::Kusto.Data;
using global::Kusto.Data.Common;
using global::Kusto.Data.Net.Client;
using Microsoft.Extensions.Diagnostics.HealthChecks;
using NetEvolve.Extensions.Tasks;
using SourceGenerator.Attributes;

[ConfigurableHealthCheck(typeof(KustoAvailableOptions))]
internal sealed partial class KustoAvailableHealthCheck
{
private static async ValueTask<HealthCheckResult> ExecuteHealthCheckAsync(
string name,
#pragma warning disable S1172 // Unused method parameters should be removed
HealthStatus failureStatus,
#pragma warning restore S1172 // Unused method parameters should be removed
KustoAvailableOptions options,
CancellationToken cancellationToken
)
{
ICslQueryProvider? queryProvider = null;
try
{
var connectionString = GetConnectionString(options);
var kcsb = new KustoConnectionStringBuilder(connectionString);
queryProvider = KustoClientFactory.CreateCslQueryProvider(kcsb);

var query = ".show databases";
var queryTask = queryProvider.ExecuteQueryAsync(
options.DatabaseName ?? "NetDefaultDB",
query,
null,
cancellationToken
);

var (isValid, result) = await queryTask
.WithTimeoutAsync(options.Timeout, cancellationToken)
.ConfigureAwait(false);

return HealthCheckState(isValid && result is not null, name);
}
finally
{
queryProvider?.Dispose();
}
}

private static string GetConnectionString(KustoAvailableOptions options)
{
if (!string.IsNullOrWhiteSpace(options.ConnectionString))
{
return options.ConnectionString;
}

if (options.ClusterUri is not null)
{
return options.ClusterUri.ToString();
}

throw new InvalidOperationException("Either ConnectionString or ClusterUri must be provided.");
}
}
29 changes: 29 additions & 0 deletions src/NetEvolve.HealthChecks.Azure.Kusto/KustoAvailableOptions.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
namespace NetEvolve.HealthChecks.Azure.Kusto;

using System;

/// <summary>
/// Options for the <see cref="KustoAvailableHealthCheck"/>.
/// </summary>
public sealed record KustoAvailableOptions
{
/// <summary>
/// Gets or sets the connection string.
/// </summary>
public string? ConnectionString { get; set; }

/// <summary>
/// Gets or sets the timeout in milliseconds for executing the healthcheck.
/// </summary>
public int Timeout { get; set; } = 100;

/// <summary>
/// Gets or sets the cluster URI.
/// </summary>
public Uri? ClusterUri { get; set; }

/// <summary>
/// Gets or sets the database name to query.
/// </summary>
public string? DatabaseName { get; set; }
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFrameworks>$(_ProjectTargetFrameworks)</TargetFrameworks>
<Description>Contains HealthChecks for Azure Kusto.</Description>
<PackageTags>$(PackageTags);azure;kusto;adx</PackageTags>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Azure.Identity" />
<PackageReference Include="Microsoft.Azure.Kusto.Data" />
<PackageReference Include="NetEvolve.Extensions.Tasks" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\SourceGenerator.Attributes\SourceGenerator.Attributes.csproj" PrivateAssets="all" />
<ProjectReference
Include="..\SourceGenerator.HealthChecks\SourceGenerator.HealthChecks.csproj"
ReferenceOutputAssembly="false"
OutputItemType="Analyzer"
/>
</ItemGroup>
</Project>
80 changes: 80 additions & 0 deletions src/NetEvolve.HealthChecks.Azure.Kusto/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
# NetEvolve.HealthChecks.Azure.Kusto

[![NuGet](https://img.shields.io/nuget/v/NetEvolve.HealthChecks.Azure.Kusto?logo=nuget)](https://www.nuget.org/packages/NetEvolve.HealthChecks.Azure.Kusto/)
[![NuGet](https://img.shields.io/nuget/dt/NetEvolve.HealthChecks.Azure.Kusto?logo=nuget)](https://www.nuget.org/packages/NetEvolve.HealthChecks.Azure.Kusto/)

This package provides a health check for Azure Kusto (Azure Data Explorer), based on the [Microsoft.Azure.Kusto.Data](https://www.nuget.org/packages/Microsoft.Azure.Kusto.Data/) package. The main purpose is to check that the Azure Kusto cluster is reachable and that the client can connect to it.

:bulb: This package is available for .NET 8.0 and later.

## Installation
To use this package, you need to add the package to your project. You can do this by using the NuGet package manager or by using the dotnet CLI.
```powershell
dotnet add package NetEvolve.HealthChecks.Azure.Kusto
```

## Health Check - Azure Kusto Availability
The health check is a liveness check. It will check that the Azure Kusto cluster is reachable and that the client can connect to it. If the cluster needs longer than the configured timeout to respond, the health check will return `Degraded`. If the cluster is not reachable, the health check will return `Unhealthy`.

### Usage
After adding the package, you need to import the namespace `NetEvolve.HealthChecks.Azure.Kusto` and add the health check to the service collection.
```csharp
using NetEvolve.HealthChecks.Azure.Kusto;
```
Therefore, you can use two different approaches. In both approaches you have to provide a name for the health check.

### Parameters
- `name`: The name of the health check. The name is used to identify the configuration object. It is required and must be unique within the application.
- `options`: The configuration options for the health check. If you don't provide any options, the health check will use the configuration based approach.
- `tags`: The tags for the health check. The tags `azure`, `kusto` and `adx` are always used as default and combined with the user input. You can provide additional tags to group or filter the health checks.

### Variant 1: Configuration based
The first one is to use the configuration based approach. Therefore, you have to add the configuration section `HealthChecks:AzureKusto` to your `appsettings.json` file.
```csharp
var builder = services.AddHealthChecks();

builder.AddKustoAvailability("<name>");
```

The configuration looks like this:
```json
{
..., // other configuration
"HealthChecks": {
"AzureKusto": {
"<name>": {
"ConnectionString": "<connection-string>", // required (or ClusterUri)
"DatabaseName": "<database-name>", // optional
..., // other configuration
"Timeout": "<timeout>" // optional, default is 100 milliseconds
}
}
}
}
```

### Variant 2: Options based
The second one is to use the options based approach. Therefore, you have to create an instance of `KustoAvailableOptions` and provide the configuration.
```csharp
var builder = services.AddHealthChecks();

builder.AddKustoAvailability("<name>", options =>
{
options.ConnectionString = "<connection-string>";
options.DatabaseName = "<database-name>";
...
options.Timeout = "<timeout>";
});
```

### :bulb: You can always provide tags to all health checks, for grouping or filtering.

```csharp
var builder = services.AddHealthChecks();

builder.AddKustoAvailability("<name>", options => ..., "azure");
```

## License

This project is licensed under the MIT License - see the [LICENSE](https://raw.githubusercontent.com/dailydevops/healthchecks/refs/heads/main/LICENSE) file for details.
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
namespace NetEvolve.HealthChecks.Tests.Integration.Azure.Kusto;

using System;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging.Abstractions;
using Testcontainers.Kusto;

public sealed class KustoAccess : IAsyncInitializer, IAsyncDisposable
{
private readonly KustoContainer _container = new KustoBuilder().WithLogger(NullLogger.Instance).Build();

public string ConnectionString => _container.GetConnectionString();

public async ValueTask DisposeAsync() => await _container.DisposeAsync().ConfigureAwait(false);

public async Task InitializeAsync() => await _container.StartAsync().ConfigureAwait(false);
}
Loading
Loading