-
Notifications
You must be signed in to change notification settings - Fork 808
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Add health cheks vault #2249
Open
SaeedSafi1999
wants to merge
15
commits into
Xabaril:master
Choose a base branch
from
SaeedSafi1999:Add-HealthCheks-Vault
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Add health cheks vault #2249
Changes from all commits
Commits
Show all changes
15 commits
Select commit
Hold shift + click to select a range
edbef62
Add AuthOprion Classes
SaeedSafi1999 6384958
add HealthCheckVault Class
SaeedSafi1999 f7c9242
Add Depency Injection
SaeedSafi1999 54f9d91
fix bugs
SaeedSafi1999 12abf7a
change design of code and add dependency injection
SaeedSafi1999 215b202
add unit tests
SaeedSafi1999 f3f2057
clean up folder add refrences
SaeedSafi1999 e9583f0
cleanup project solution
SaeedSafi1999 787f56f
deleteTest
SaeedSafi1999 d928ef1
add registration test and functional test cleanup namespaces as talk …
SaeedSafi1999 ad69249
change try finaly with using statement
SaeedSafi1999 4713166
add functional test for vault health check
SaeedSafi1999 648f936
merge accept
SaeedSafi1999 56744f8
fic bugs
SaeedSafi1999 87d0570
bug fixes and clean up code
SaeedSafi1999 File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Large diffs are not rendered by default.
Oops, something went wrong.
46 changes: 46 additions & 0 deletions
46
src/HealthChecks.Vault/DependencyInjection/VaultHealthCkecksBuilderExtension.cs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,46 @@ | ||
using HealthChecks.Vault; | ||
using Microsoft.Extensions.Diagnostics.HealthChecks; | ||
using VaultSharp; | ||
|
||
|
||
namespace Microsoft.Extensions.DependencyInjection; | ||
|
||
|
||
/// <summary> | ||
/// Extension methods to configure vault services. | ||
/// </summary> | ||
public static class VaultHealthChecksBuilderExtension | ||
{ | ||
private const string NAME = "vault"; | ||
|
||
/// <summary> | ||
/// Add a health check for vault services. | ||
/// </summary> | ||
/// <param name="builder">The <see cref="IHealthChecksBuilder"/>.</param> | ||
/// <param name="clientFactory"> | ||
/// An optional factory to obtain <see cref="IVaultClient" /> instance. | ||
/// When not provided, <see cref="IVaultClient" /> is simply resolved from <see cref="IServiceProvider"/>.</param> | ||
/// <param name="name">The health check name. Optional. If <c>null</c> the type name 'vault' will be used for the name.</param> | ||
/// <param name="failureStatus"> | ||
/// The <see cref="HealthStatus"/> that should be reported when the health check fails. Optional. If <c>null</c> then | ||
/// the default status of <see cref="HealthStatus.Unhealthy"/> will be reported. | ||
/// </param> | ||
/// <param name="tags">A list of tags that can be used to filter sets of health checks. Optional.</param> | ||
/// <param name="timeout">An optional <see cref="TimeSpan"/> representing the timeout of the check.</param> | ||
/// <returns>The specified <paramref name="builder"/>.</returns> | ||
public static IHealthChecksBuilder AddVault( | ||
this IHealthChecksBuilder builder, | ||
Func<IServiceProvider, IVaultClient>? clientFactory = default, | ||
string? name = null, | ||
HealthStatus? failureStatus = default, | ||
IEnumerable<string>? tags = default, | ||
TimeSpan? timeout = default) | ||
{ | ||
return builder.Add(new HealthCheckRegistration( | ||
name ?? NAME, | ||
sp => new VaultHealthChecks(clientFactory?.Invoke(sp) ?? sp.GetRequiredService<IVaultClient>()), | ||
failureStatus, | ||
tags, | ||
timeout)); | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,12 @@ | ||
<Project Sdk="Microsoft.NET.Sdk"> | ||
<PropertyGroup> | ||
<TargetFrameworks>$(DefaultLibraryTargetFrameworks)</TargetFrameworks> | ||
<PackageTags>$(PackageTags);Vault</PackageTags> | ||
<Description>HealthChecks.Vault is the health check package for Hashicorp Vault.</Description> | ||
</PropertyGroup> | ||
|
||
<ItemGroup> | ||
<PackageReference Include="VaultSharp"></PackageReference> | ||
</ItemGroup> | ||
|
||
</Project> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,35 @@ | ||
using Microsoft.Extensions.Diagnostics.HealthChecks; | ||
using VaultSharp; | ||
|
||
namespace HealthChecks.Vault; | ||
|
||
public class VaultHealthChecks : IHealthCheck | ||
{ | ||
private readonly IVaultClient _vaultClient; | ||
|
||
public VaultHealthChecks(IVaultClient vaultClient) | ||
{ | ||
_vaultClient = Guard.ThrowIfNull(vaultClient); | ||
} | ||
|
||
public async Task<HealthCheckResult> CheckHealthAsync(HealthCheckContext context, CancellationToken cancellationToken = default) | ||
{ | ||
try | ||
{ | ||
var healthStatus = await _vaultClient.V1.System | ||
.GetHealthStatusAsync() | ||
.ConfigureAwait(false); | ||
|
||
if (healthStatus.Initialized && healthStatus.Sealed) | ||
return new HealthCheckResult(context.Registration.FailureStatus, description: "Vault is initialized but sealed."); | ||
else if (!healthStatus.Initialized) | ||
return new HealthCheckResult(context.Registration.FailureStatus, description: "Vault is not initialized."); | ||
|
||
return HealthCheckResult.Healthy(); | ||
} | ||
catch (Exception ex) | ||
{ | ||
return new HealthCheckResult(context.Registration.FailureStatus, exception: ex); | ||
} | ||
} | ||
} |
48 changes: 48 additions & 0 deletions
48
test/HealthChecks.Vault.Tests/DependencyInjection/RegistrationTest.cs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,48 @@ | ||
using VaultSharp; | ||
using VaultSharp.V1.AuthMethods; | ||
using VaultSharp.V1.AuthMethods.Token; | ||
|
||
namespace HealthChecks.Vault.Tests.DependencyInjection; | ||
|
||
public class vault_registration_should | ||
{ | ||
[Fact] | ||
public void add_health_check_when_properly_configured() | ||
{ | ||
var services = new ServiceCollection(); | ||
services.AddHealthChecks() | ||
.AddVault(Factory); | ||
|
||
using var serviceProvider = services.BuildServiceProvider(); | ||
var options = serviceProvider.GetRequiredService<IOptions<HealthCheckServiceOptions>>(); | ||
|
||
var registration = options.Value.Registrations.First(); | ||
var check = registration.Factory(serviceProvider); | ||
|
||
registration.Name.ShouldBe("vault"); | ||
check.ShouldBeOfType<VaultHealthChecks>(); | ||
} | ||
|
||
[Fact] | ||
public void add_named_health_check_when_properly_configured() | ||
{ | ||
var services = new ServiceCollection(); | ||
services.AddHealthChecks() | ||
.AddVault(clientFactory: Factory, name: "vault"); | ||
|
||
using var serviceProvider = services.BuildServiceProvider(); | ||
var options = serviceProvider.GetRequiredService<IOptions<HealthCheckServiceOptions>>(); | ||
|
||
var registration = options.Value.Registrations.First(); | ||
var check = registration.Factory(serviceProvider); | ||
|
||
registration.Name.ShouldBe("vault"); | ||
check.ShouldBeOfType<VaultHealthChecks>(); | ||
} | ||
|
||
private IVaultClient Factory(IServiceProvider _) | ||
{ | ||
IAuthMethodInfo authMethod = new TokenAuthMethodInfo("token"); | ||
return new VaultClient(new VaultClientSettings("http://localhost:8200", authMethod)); | ||
} | ||
} |
40 changes: 40 additions & 0 deletions
40
test/HealthChecks.Vault.Tests/Fixtures/VaultContainerFixture.cs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,40 @@ | ||
using DotNet.Testcontainers.Containers; | ||
using DotNet.Testcontainers.Builders; | ||
|
||
namespace HealthChecks.Vault.Tests.Fixtures; | ||
|
||
public class VaultContainerFixture : IAsyncLifetime | ||
{ | ||
public string RootToken { get; } = "root"; | ||
|
||
private readonly IContainer _container; | ||
|
||
public string GetConnectionString() | ||
{ | ||
if (_container is null) | ||
throw new InvalidOperationException("container is not initialized"); | ||
return $"http://localhost:{_container.GetMappedPublicPort(8200)}"; | ||
} | ||
|
||
public VaultContainerFixture() | ||
{ | ||
_container = new ContainerBuilder() | ||
.WithImage("hashicorp/vault:1.18") | ||
.WithPortBinding(8200, true) | ||
.WithWaitStrategy(Wait.ForUnixContainer().UntilHttpRequestIsSucceeded(r => r.ForPort(8200))) | ||
.WithEnvironment("VAULT_DEV_ROOT_TOKEN_ID", RootToken) | ||
.WithEnvironment("VAULT_LOCAL_CONFIG", "{\"backend\": {\"file\": {\"path\": \"/vault/file\"}}, \"default_lease_ttl\": \"168h\", \"max_lease_ttl\": \"720h\"}") | ||
.WithCommand($"server -dev -dev-root-token-id={RootToken}") | ||
.Build(); | ||
} | ||
|
||
public async Task InitializeAsync() => await _container.StartAsync(); | ||
|
||
public async Task DisposeAsync() | ||
{ | ||
if (_container != null) | ||
{ | ||
await _container.StopAsync(); | ||
} | ||
} | ||
} |
109 changes: 109 additions & 0 deletions
109
test/HealthChecks.Vault.Tests/Functional/HealthChecksVaultTest.cs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,109 @@ | ||
using System.Net; | ||
using VaultSharp; | ||
using VaultSharp.V1.AuthMethods; | ||
using VaultSharp.V1.AuthMethods.Token; | ||
|
||
namespace HealthChecks.Vault.Tests.Functional; | ||
|
||
public class vault_healthcheck_should : IClassFixture<Fixtures.VaultContainerFixture> | ||
{ | ||
private readonly Fixtures.VaultContainerFixture _vaultContainerFixture; | ||
|
||
public vault_healthcheck_should(Fixtures.VaultContainerFixture vaultContainerFixture) | ||
{ | ||
_vaultContainerFixture = vaultContainerFixture; | ||
} | ||
|
||
[Fact] | ||
public async Task be_healthy_when_vault_is_available_using_client_factory() | ||
{ | ||
var webHostBuilder = new WebHostBuilder() | ||
.ConfigureServices(services => | ||
{ | ||
services | ||
.AddHealthChecks() | ||
.AddVault( | ||
clientFactory: sp => | ||
{ | ||
var vaultAddress = _vaultContainerFixture.GetConnectionString(); | ||
var rootToken = _vaultContainerFixture.RootToken; | ||
IAuthMethodInfo authMethod = new TokenAuthMethodInfo(rootToken); | ||
var vaultClientSettings = new VaultClientSettings(vaultAddress, authMethod); | ||
IVaultClient vaultClient = new VaultClient(vaultClientSettings); | ||
return vaultClient; | ||
}, tags: new string[] { "vault" }); | ||
}) | ||
.Configure(app => | ||
{ | ||
app.UseHealthChecks("/health", new HealthCheckOptions | ||
{ | ||
Predicate = r => r.Tags.Contains("vault") | ||
}); | ||
}); | ||
|
||
using var server = new TestServer(webHostBuilder); | ||
|
||
using var response = await server.CreateRequest("/health").GetAsync(); | ||
|
||
response.StatusCode.ShouldBe(HttpStatusCode.OK); | ||
} | ||
|
||
[Fact] | ||
public async Task be_healthy_when_vault_is_available_using_singleton() | ||
{ | ||
var webHostBuilder = new WebHostBuilder() | ||
.ConfigureServices(services => | ||
{ | ||
var vaultAddress = _vaultContainerFixture.GetConnectionString(); | ||
var rootToken = _vaultContainerFixture.RootToken; | ||
IAuthMethodInfo authMethod = new TokenAuthMethodInfo(rootToken); | ||
var vaultClientSettings = new VaultClientSettings(vaultAddress, authMethod); | ||
IVaultClient vaultClient = new VaultClient(vaultClientSettings); | ||
|
||
services | ||
.AddSingleton(vaultClient) | ||
.AddHealthChecks() | ||
.AddVault(tags: new string[] { "vault" }); | ||
}) | ||
.Configure(app => | ||
{ | ||
app.UseHealthChecks("/health", new HealthCheckOptions | ||
{ | ||
Predicate = r => r.Tags.Contains("vault") | ||
}); | ||
}); | ||
|
||
using var server = new TestServer(webHostBuilder); | ||
|
||
using var response = await server.CreateRequest("/health").GetAsync(); | ||
|
||
response.StatusCode.ShouldBe(HttpStatusCode.OK); | ||
} | ||
|
||
[Fact] | ||
public async Task be_unhealthy_when_vault_is_unavailable() | ||
{ | ||
var webHostBuilder = new WebHostBuilder() | ||
.ConfigureServices(services => | ||
{ | ||
services | ||
.AddHealthChecks() | ||
.AddVault( | ||
clientFactory: sp => new VaultClient(new VaultClientSettings("http://localhost:8200", new TokenAuthMethodInfo("root"))), tags: new string[] { "vault" }); | ||
}) | ||
.Configure(app => | ||
{ | ||
app.UseHealthChecks("/health", new HealthCheckOptions | ||
{ | ||
Predicate = r => r.Tags.Contains("vault") | ||
}); | ||
}); | ||
|
||
using var server = new TestServer(webHostBuilder); | ||
|
||
using var response = await server.CreateRequest("/health").GetAsync(); | ||
|
||
response.StatusCode.ShouldBe(HttpStatusCode.ServiceUnavailable); | ||
} | ||
} | ||
|
6 changes: 6 additions & 0 deletions
6
test/HealthChecks.Vault.Tests/HealthChecks.Vault.Tests.csproj
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,6 @@ | ||
<Project Sdk="Microsoft.NET.Sdk"> | ||
<ItemGroup> | ||
<ProjectReference Include="..\..\src\HealthChecks.Vault\HealthChecks.Vault.csproj" /> | ||
<PackageReference Include="Testcontainers"/> | ||
</ItemGroup> | ||
</Project> |
15 changes: 15 additions & 0 deletions
15
test/HealthChecks.Vault.Tests/HealthChecks.Vault.approved.txt
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,15 @@ | ||
namespace HealthChecks.Vault | ||
{ | ||
public class VaultHealthChecks : Microsoft.Extensions.Diagnostics.HealthChecks.IHealthCheck | ||
{ | ||
public VaultHealthChecks(VaultSharp.IVaultClient vaultClient) { } | ||
public System.Threading.Tasks.Task<Microsoft.Extensions.Diagnostics.HealthChecks.HealthCheckResult> CheckHealthAsync(Microsoft.Extensions.Diagnostics.HealthChecks.HealthCheckContext context, System.Threading.CancellationToken cancellationToken = default) { } | ||
} | ||
} | ||
namespace Microsoft.Extensions.DependencyInjection | ||
{ | ||
public static class VaultHealthChecksBuilderExtension | ||
{ | ||
public static Microsoft.Extensions.DependencyInjection.IHealthChecksBuilder AddVault(this Microsoft.Extensions.DependencyInjection.IHealthChecksBuilder builder, System.Func<System.IServiceProvider, VaultSharp.IVaultClient>? clientFactory = null, string? name = null, Microsoft.Extensions.Diagnostics.HealthChecks.HealthStatus? failureStatus = default, System.Collections.Generic.IEnumerable<string>? tags = null, System.TimeSpan? timeout = default) { } | ||
} | ||
} |
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
in this repo we typically configure the containers from github workflow level, here you can find some examples of how we do that:
https://github.com/Xabaril/AspNetCore.Diagnostics.HealthChecks/blob/master/.github/workflows/healthchecks_redis_cd.yml
https://github.com/Xabaril/AspNetCore.Diagnostics.HealthChecks/blob/master/.github/workflows/healthchecks_redis_cd_preview.yml
https://github.com/Xabaril/AspNetCore.Diagnostics.HealthChecks/blob/master/.github/workflows/healthchecks_redis_ci.yml
could you please do that for this project as well (we need that to be able to run the tests in the CI) and remove the dependency to
Testcontainers
?I am not saying that
Testcontainers
are bad (it actually looks very neat), we just use a different approach in this repo and I would prefer for all of the health checks to implement the same pattern.