public async Task <LivenessResult> IsHealthy(LivenessExecutionContext context, CancellationToken cancellationToken = default(CancellationToken)) { try { var response = await _httpClient.GetAsync("_cluster/health"); response.EnsureSuccessStatusCode(); var json = await response.Content.ReadAsStringAsync(); var results = JsonConvert.DeserializeObject <ClusterHealth>(json); switch (results.status) { case ClusterStatus.Green: return(LivenessResult.Healthy("Green")); case ClusterStatus.Yellow: return(LivenessResult.Healthy("Yellow (no replicas)")); case ClusterStatus.Red: return(LivenessResult.UnHealthy("Red")); default: return(LivenessResult.UnHealthy("Unknown status - " + results.status)); } } catch (Exception ex) { return(LivenessResult.UnHealthy(ex)); } }
public async Task <LivenessResult> IsHealthy(LivenessExecutionContext context, CancellationToken cancellationToken = default) { try { using (var connection = new OracleConnection(_connectionString)) { _logger?.LogDebug($"{nameof(OracleLiveness)} is checking the Oracle using the query {_sql}."); await connection.OpenAsync(); using (var command = connection.CreateCommand()) { command.CommandText = _sql; await command.ExecuteScalarAsync(); } _logger?.LogDebug($"The {nameof(OracleLiveness)} check success for {_connectionString}"); return(LivenessResult.Healthy()); } } catch (Exception ex) { _logger?.LogWarning($"The {nameof(OracleLiveness)} check fail for {_connectionString} with the exception {ex.ToString()}."); return(LivenessResult.UnHealthy(ex)); } }
public async Task <LivenessResult> IsHealthy(LivenessExecutionContext context, CancellationToken cancellationToken = default) { var defaultHttpMethod = _options.HttpMethod; var defaultCodes = _options.ExpectedHttpCodes; var idx = 0; try { _logger?.LogInformation($"{nameof(UriLiveness)} is checking configured uri's."); foreach (var item in _options.UrisOptions) { var method = item.HttpMethod ?? defaultHttpMethod; var expectedCodes = item.ExpectedHttpCodes ?? defaultCodes; if (cancellationToken.IsCancellationRequested) { return(LivenessResult.UnHealthy($"Liveness execution is cancelled.")); } using (var httpClient = new HttpClient()) { var requestMessage = new HttpRequestMessage(method, item.Uri); foreach (var header in item.Headers) { requestMessage.Headers.Add(header.Name, header.Value); } var response = await httpClient.SendAsync(requestMessage); if (!((int)response.StatusCode >= expectedCodes.Min && (int)response.StatusCode <= expectedCodes.Max)) { _logger?.LogWarning($"The {nameof(UriLiveness)} check fail for uri {item.Uri}."); return(LivenessResult.UnHealthy($"Discover endpoint #{idx} is not responding with code in {expectedCodes.Min}...{expectedCodes.Max} range, the current status is {response.StatusCode}.")); } ++idx; } } _logger?.LogDebug($"The {nameof(UriLiveness)} check success."); return(LivenessResult.Healthy()); } catch (Exception ex) { _logger?.LogWarning($"The {nameof(UriLiveness)} check fail with the exception {ex.ToString()}."); return(LivenessResult.UnHealthy(ex)); } }
public Task <LivenessResult> IsHealthy(LivenessExecutionContext context, CancellationToken cancellationToken = default) { var currentValue = currentValueFunc(); if (currentValue.CompareTo(maximunValue) <= 0) { return(Task.FromResult( LivenessResult.Healthy())); } return(Task.FromResult( LivenessResult.UnHealthy($"Maximun={maximunValue}, Current={currentValue}"))); }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.Configure <CookiePolicyOptions>(options => { // This lambda determines whether user consent for non-essential cookies is needed for a given request. options.CheckConsentNeeded = context => true; options.MinimumSameSitePolicy = SameSiteMode.None; }); services.AddBeatPulse(setup => { // //configure a sample ad-hoc liveness // setup.AddLiveness("catapi", opt => { opt.UsePath("catapi"); opt.UseLiveness(new ActionLiveness((_) => { if ((DateTime.Now.Second & 1) == 1) { return(Task.FromResult(LivenessResult.UnHealthy("liveness is not working"))); } return(Task.FromResult(LivenessResult.Healthy())); })); }); // //add trackers // setup.AddApplicationInsightsTracker(); //setup.AddPrometheusTracker(new Uri("http://localhost:9091"), new Dictionary<string, string>() //{ // {"MachineName",Environment.MachineName} //}); //setup.AddStatusPageTracker(opt => //{ // opt.PageId = "your-page-id"; // opt.ComponentId = "your-component-id"; // opt.ApiKey = "your-api.key"; // opt.IncidentName = "BeatPulse mark this component as outage"; //}); }); services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1); }
public async Task break_the_liveness_execution_if_detailed_output_is_disabled() { var check1IsExecuted = false; var check2IsExecuted = false; var healthCheck1 = new ActionLiveness( (cancellationToken) => { check1IsExecuted = true; return(Task.FromResult(LivenessResult.UnHealthy("custom check1 is not working"))); }); var healthCheck2 = new ActionLiveness( (cancellationToken) => { check2IsExecuted = false; return(Task.FromResult(LivenessResult.Healthy())); }); var webHostBuilder = new WebHostBuilder() .UseBeatPulse() .UseStartup <DefaultStartup>() .ConfigureServices(svc => { svc.AddBeatPulse(context => { context.AddLiveness("check1", opt => { opt.UsePath("check1"); opt.UseLiveness(healthCheck1); }); context.AddLiveness("check2", opt => { opt.UsePath("check2"); opt.UseLiveness(healthCheck2); }); }); }); var server = new TestServer(webHostBuilder); var response = await server.CreateClient() .GetAsync(BeatPulseKeys.BEATPULSE_DEFAULT_PATH); response.StatusCode .Should().Be(StatusCodes.Status503ServiceUnavailable); check1IsExecuted.Should().BeTrue(); check2IsExecuted.Should().BeFalse(); }
public Task <LivenessResult> IsHealthy(LivenessExecutionContext context, CancellationToken cancellationToken = default) { try { _logger?.LogInformation($"{nameof(SftpLiveness)} is checking SFTP connections."); foreach (var item in _options.ConfiguredHosts.Values) { var connectionInfo = new ConnectionInfo(item.Host, item.UserName, item.AuthenticationMethods.ToArray()); using (var sftpClient = new SftpClient(connectionInfo)) { sftpClient.Connect(); var connectionSuccess = sftpClient.IsConnected && sftpClient.ConnectionInfo.IsAuthenticated; if (connectionSuccess) { if (item.FileCreationOptions.createFile) { using (var stream = new MemoryStream(new byte[] { 0x0 }, 0, 1)) { sftpClient.UploadFile(stream, item.FileCreationOptions.remoteFilePath); } } } else { _logger?.LogWarning($"The {nameof(SftpLiveness)} check fail for sftp host {item.Host}."); return(Task.FromResult( LivenessResult.UnHealthy($"Connection with sftp host {item.Host}:{item.Port} failed"))); } } } _logger?.LogInformation($"The {nameof(SftpLiveness)} check success."); return(Task.FromResult( LivenessResult.Healthy())); } catch (Exception ex) { _logger?.LogWarning($"The {nameof(SftpLiveness)} check fail with the exception {ex.ToString()}."); return(Task.FromResult( LivenessResult.UnHealthy(ex))); } }
public async Task <LivenessResult> IsHealthy(LivenessExecutionContext context, CancellationToken cancellationToken = default(CancellationToken)) { try { var tokenCredentials = await GetTokenCredentials(_clientID, _clientSecret, _tenantID); var relayManagementClient = new RelayManagementClient(tokenCredentials); return(LivenessResult.Healthy()); } catch (Exception ex) { return(LivenessResult.UnHealthy(ex)); } }
public void get_valid_prometheus_metrics_content() { string path = "sql"; string name = "liveness1"; var livenessResult = LivenessResult.Healthy() .SetEnforced(name, path, TimeSpan.FromSeconds(1)); livenessResult.GetPrometheusMetrics() .Should() .Contain($"beatpulse_pulse_execution_time_seconds{{ApplicationName=\"testhost\",Path=\"{path}\",Name=\"{name}\"}}"); livenessResult.GetPrometheusMetrics() .Should() .Contain($"beatpulse_pulse_ishealthy{{ApplicationName=\"testhost\",Path=\"{path}\",Name=\"{name}\"}}"); }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.Configure <CookiePolicyOptions>(options => { // This lambda determines whether user consent for non-essential cookies is needed for a given request. options.CheckConsentNeeded = context => true; options.MinimumSameSitePolicy = SameSiteMode.None; }); // // Configure BeatPulse Authenthication filters // //api-key filter //services.AddSingleton<IBeatPulseAuthenticationFilter> // (new ApiKeyAuthenticationFilter("api-key-secret")); //local filter //services.AddSingleton<IBeatPulseAuthenticationFilter>( // new LocalAuthenticationFilter()); //custom filter ( defined on this project ) //services.AddSingleton<IBeatPulseAuthenticationFilter> // (new HeaderValueAuthenticationFilter("header1", "value1")); services.AddBeatPulse(setup => { // //create simple ad-hoc liveness // setup.AddLiveness("catapi", opt => { opt.UsePath("catapi"); opt.UseLiveness(new ActionLiveness((cancellationToken) => { return(Task.FromResult( LivenessResult.Healthy())); })); }); }); services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1); }
public async Task <LivenessResult> IsHealthy(LivenessExecutionContext context, CancellationToken cancellationToken = default) { try { _logger?.LogInformation($"{nameof(BeatPulseLiveness)} is checking configured uri's."); if (cancellationToken.IsCancellationRequested) { return(LivenessResult.UnHealthy($"Liveness execution is cancelled.")); } var content = string.Empty; using (var httpClient = new HttpClient()) { var requestMessage = new HttpRequestMessage(HttpMethod.Get, _uri); var response = await httpClient.SendAsync(requestMessage); content = await response.Content.ReadAsStringAsync(); } var message = JsonConvert.DeserializeObject <OutputLivenessMessageResponse>(content); string unHealthyItems = string.Join(",", message.Checks.Where(b => !b.IsHealthy).Select(c => c.Name)); if (message.Checks.Any(c => !c.IsHealthy)) { _logger?.LogWarning($"The {nameof(BeatPulseLiveness)} check fail for uri {_uri}"); return(LivenessResult.UnHealthy($"{nameof(BeatPulseLiveness)} {unHealthyItems} failing.")); } _logger?.LogDebug($"The {nameof(BeatPulseLiveness)} check success."); return(LivenessResult.Healthy()); } catch (Exception ex) { _logger?.LogWarning($"The {nameof(BeatPulseLiveness)} check fail with the exception {ex.ToString()}."); return(LivenessResult.UnHealthy(ex)); } }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddTransient <IHeroesRepository, HeroesRepository>(); services.AddDbContext <HeroesContext>(options => options.UseSqlServer(Configuration.GetConnectionString("heroesConnection"))); services.AddCors(); services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1); services.AddBeatPulse(setup => { setup.AddApplicationInsightsTracker(); setup.AddLiveness("external", opt => { opt.UsePath("external"); opt.UseLiveness(new ActionLiveness((__) => Task.FromResult(LivenessResult.Healthy()))); }); }); services.AddSingleton <IBeatPulseAuthenticationFilter>(new ApiKeyAuthenticationFilter(Configuration["LivenessAPIKey"])); }
public Task <LivenessResult> IsHealthy(LivenessExecutionContext context, CancellationToken cancellationToken = default) { try { _logger?.LogInformation($"{nameof(DiskStorageLiveness)} is checking configured drives."); var configuredDrives = _options.ConfiguredDrives.Values; foreach (var item in configuredDrives) { var systemDriveInfo = GetSystemDriveInfo(item.DriveName); if (systemDriveInfo.Exists) { if (systemDriveInfo.ActualFreeMegabytes < item.MinimumFreeMegabytes) { _logger?.LogWarning($"The {nameof(DiskStorageLiveness)} check fail for drive {item.DriveName}."); return(Task.FromResult( LivenessResult.UnHealthy($"Minimum configured megabytes for disk {item.DriveName} is {item.MinimumFreeMegabytes} but actual free space are {systemDriveInfo.ActualFreeMegabytes} megabytes"))); } } else { _logger?.LogWarning($"{nameof(DiskStorageLiveness)} is checking a not present disk {item.DriveName} on system."); return(Task.FromResult( LivenessResult.UnHealthy($"Configured drive {item.DriveName} is not present on system"))); } } _logger?.LogDebug($"The {nameof(DiskStorageLiveness)} check success."); return(Task.FromResult( LivenessResult.Healthy())); } catch (Exception ex) { _logger?.LogWarning($"The {nameof(DiskStorageLiveness)} check fail with the exception {ex.ToString()}."); return(Task.FromResult( LivenessResult.UnHealthy(ex))); } }
public async Task response_http_status_serviceunavailable_when_beat_pulse_service_beat_pulse_execution_is_timeout() { string defaultName; string defaultPath; var healthCheck = new ActionLiveness( async(cancellationToken) => { await Task.Delay(100); return(LivenessResult.Healthy()); }); var webHostBuilder = new WebHostBuilder() .UseBeatPulse(options => options.ConfigureTimeout(50)) .UseStartup <DefaultStartup>() .ConfigureServices(svc => { svc.AddBeatPulse(context => { context.AddLiveness(nameof(defaultName), opt => { opt.UsePath(nameof(defaultPath)); opt.UseLiveness(healthCheck); }); }); }); var server = new TestServer(webHostBuilder); var response = await server.CreateClient() .GetAsync(BeatPulseKeys.BEATPULSE_DEFAULT_PATH); var expected = HttpStatusCode.ServiceUnavailable; response.StatusCode .Should() .Be(expected); (await response.Content.ReadAsStringAsync()).Should() .Be(Enum.GetName(typeof(HttpStatusCode), expected)); }
public async Task <LivenessResult> IsHealthy(LivenessExecutionContext context, CancellationToken cancellationToken = default) { try { _logger?.LogInformation($"{nameof(RedisLiveness)} is checking the Redis status."); using (var connection = await ConnectionMultiplexer.ConnectAsync(_redisConnectionString)) { _logger?.LogInformation($"The {nameof(RedisLiveness)} check success."); return(LivenessResult.Healthy()); } } catch (Exception ex) { _logger?.LogWarning($"The {nameof(RedisLiveness)} check fail with the exception {ex.ToString()}."); return(LivenessResult.UnHealthy(ex)); } }
public async Task <LivenessResult> IsHealthy(LivenessExecutionContext context, CancellationToken cancellationToken = default) { try { _logger?.LogInformation($"{nameof(SmtpLiveness)} is checking SMTP connections."); using (var smtpConnection = new SmtpConnection(_options)) { if (await smtpConnection.ConnectAsync()) { if (_options.AccountOptions.Login) { var(user, password) = _options.AccountOptions.Account; if (!await smtpConnection.AuthenticateAsync(user, password)) { _logger?.LogWarning($"The {nameof(SmtpLiveness)} check fail with invalid login to smtp server {_options.Host}:{_options.Port} with configured credentials."); return(LivenessResult.UnHealthy($"Error login to smtp server{_options.Host}:{_options.Port} with configured credentials")); } } _logger?.LogInformation($"The {nameof(SmtpLiveness)} check success."); return(LivenessResult.Healthy()); } else { _logger?.LogWarning($"The {nameof(SmtpLiveness)} check fail for connecting to smtp server {_options.Host}:{_options.Port} - SSL : {_options.ConnectionType}."); return(LivenessResult.UnHealthy($"Could not connect to smtp server {_options.Host}:{_options.Port} - SSL : {_options.ConnectionType}")); } } } catch (Exception ex) { _logger?.LogWarning($"The {nameof(SmtpLiveness)} check fail with the exception {ex.ToString()}."); return(LivenessResult.UnHealthy(ex)); } }
public async Task <LivenessResult> IsHealthy(LivenessExecutionContext context, CancellationToken cancellationToken = default) { try { _logger?.LogInformation($"{nameof(EventStoreLiveness)} is checking the EventStore host."); var eventStoreUri = new Uri(_uri); ConnectionSettings connectionSettings; if (string.IsNullOrEmpty(_login) || string.IsNullOrEmpty(_password)) { connectionSettings = ConnectionSettings.Create() .KeepRetrying() .Build(); } else { connectionSettings = ConnectionSettings.Create() .KeepRetrying() .SetDefaultUserCredentials(new UserCredentials(_login, _password)) .Build(); } var connection = EventStoreConnection.Create( connectionSettings, new Uri(_uri), "BeatPulse HealthCheck"); await connection.ConnectAsync(); return(LivenessResult.Healthy()); } catch (Exception ex) { _logger?.LogWarning($"The {nameof(EventStoreLiveness)} check fail for Eventstore with the exception {ex.ToString()}."); return(LivenessResult.UnHealthy(ex)); } }
public async Task <LivenessResult> IsHealthy(LivenessExecutionContext context, CancellationToken cancellationToken = default) { try { _logger?.LogDebug($"{nameof(DynamoDbLiveness)} is checking DynamoDb database availability."); var credentials = new BasicAWSCredentials(_options.AccessKey, _options.SecretKey); var client = new AmazonDynamoDBClient(credentials, _options.RegionEndpoint); await client.ListTablesAsync(); _logger?.LogDebug($"The {nameof(DynamoDbLiveness)} check success."); return(LivenessResult.Healthy()); } catch (Exception ex) { _logger?.LogDebug($"The {nameof(DynamoDbLiveness)} check fail with the exception {ex.ToString()}."); return(LivenessResult.UnHealthy(ex)); } }
public async Task <LivenessResult> IsHealthy(LivenessExecutionContext context, CancellationToken cancellationToken = new CancellationToken()) { try { _logger?.LogInformation($"{nameof(ElasticsearchLiveness)} is checking the Elasticsearch host."); var client = new ElasticClient(new Uri(_elasticsearchConnectionString)); var result = await client.PingAsync(cancellationToken : cancellationToken); var success = result.ApiCall.HttpStatusCode == StatusCodes.Status200OK; return(success ? LivenessResult.Healthy() : LivenessResult.UnHealthy(result.ApiCall.OriginalException)); } catch (Exception ex) { _logger?.LogWarning($"The {nameof(ElasticsearchLiveness)} check fail with the exception {ex.ToString()}."); return(LivenessResult.UnHealthy(ex)); } }
/// <summary> /// Add BeatPulse services to the container, /// </summary> /// <param name="services">The <see cref="IServiceCollection"/> to add the BeatPulse services.</param> /// <param name="setup">Provided delegate to configure <see cref="BeatPulseContext"/> with required BeatPulse Liveness.</param> /// <returns>The <see cref="IServiceCollection"/> with BeatPulse added.</returns> public static IServiceCollection AddBeatPulse(this IServiceCollection services, Action <BeatPulseContext> setup = null) { var context = new BeatPulseContext(); context.AddLiveness(BeatPulseKeys.BEATPULSE_SELF_NAME, opt => { opt.UsePath(BeatPulseKeys.BEATPULSE_SELF_SEGMENT); opt.UseLiveness(new ActionLiveness((cancellationToken) => { return(Task.FromResult( LivenessResult.Healthy())); })); }); setup?.Invoke(context); services.TryAddSingleton(context); services.TryAddSingleton <IBeatPulseService, BeatPulseService>(); services.TryAddSingleton <IBeatPulseAuthenticationFilter, NoAuthenticationFilter>(); return(services); }
public async Task <LivenessResult> IsHealthy(LivenessExecutionContext context, CancellationToken cancellationToken = default) { try { _logger?.LogInformation($"{nameof(AzureQueueStorageLiveness)} is checking the Azure Queue."); var blobClient = _storageAccount.CreateCloudQueueClient(); var serviceProperties = await blobClient.GetServicePropertiesAsync( new QueueRequestOptions(), operationContext : null, cancellationToken : cancellationToken); _logger?.LogInformation($"The {nameof(AzureQueueStorageLiveness)} check success."); return(LivenessResult.Healthy()); } catch (Exception ex) { _logger?.LogWarning($"The {nameof(AzureQueueStorageLiveness)} check fail for {_storageAccount.QueueStorageUri} with the exception {ex.ToString()}."); return(LivenessResult.UnHealthy(ex)); } }
public async Task <LivenessResult> IsHealthy(LivenessExecutionContext context, CancellationToken cancellationToken = default) { try { _logger?.LogInformation($"{nameof(ImapLiveness)} is checking IMAP entries."); _imapConnection = new ImapConnection(_options); if (await _imapConnection.ConnectAsync()) { if (_options.AccountOptions.Login) { return(await ExecuteAuthenticatedUserActions()); } } else { _logger?.LogWarning($"{nameof(ImapLiveness)} fail connect to server {_options.Host}- SSL Enabled : {_options.ConnectionType}."); return(LivenessResult.UnHealthy($"Connection to server {_options.Host} has failed - SSL Enabled : {_options.ConnectionType}")); } _logger?.LogInformation($"The {nameof(ImapLiveness)} check success."); return(LivenessResult.Healthy()); } catch (Exception ex) { _logger?.LogWarning($"The {nameof(ImapLiveness)} check fail with the exception {ex.ToString()}."); return(LivenessResult.UnHealthy(ex)); } finally { _imapConnection.Dispose(); } }
public async Task <LivenessResult> IsHealthy(LivenessExecutionContext context, CancellationToken cancellationToken = default) { try { _logger?.LogDebug($"{nameof(DocumentDbLiveness)} is checking DocumentDb database availability."); using (var documentDbClient = new DocumentClient( new Uri(_documentDbOptions.UriEndpoint), _documentDbOptions.PrimaryKey)) { await documentDbClient.OpenAsync(); _logger?.LogDebug($"The {nameof(DocumentDbLiveness)} check success."); return(LivenessResult.Healthy()); } } catch (Exception ex) { _logger?.LogDebug($"The {nameof(DocumentDbLiveness)} check fail with the exception {ex.ToString()}."); return(LivenessResult.UnHealthy(ex)); } }
public void get_valid_prometheus_metrics_content_with_custom_labels() { string path = "sql"; string name = "liveness1"; var customLabels = new Dictionary <string, string>() { { "labelA", "valueA" }, { "labelB", "valueB" }, }; var livenessResult = LivenessResult.Healthy() .SetEnforced(name, path, TimeSpan.FromSeconds(1)); var prometheusMetrics = livenessResult.GetPrometheusMetrics(customLabels); prometheusMetrics .Should() .Contain($"beatpulse_pulse_execution_time_seconds{{labelA=\"valueA\",labelB=\"valueB\",ApplicationName=\"testhost\",Path=\"{path}\",Name=\"{name}\"}}"); prometheusMetrics .Should() .Contain($"beatpulse_pulse_ishealthy{{labelA=\"valueA\",labelB=\"valueB\",ApplicationName=\"testhost\",Path=\"{path}\",Name=\"{name}\"}}"); }
public Task <LivenessResult> IsHealthy(LivenessExecutionContext context, CancellationToken cancellationToken = default) { return(Task.FromResult( LivenessResult.Healthy())); }
public void register_multiple_liveness_with_the_same_name_and_path() { var context = new BeatPulseContext(); var options = new BeatPulseLivenessRegistrationOptions("name"); options.UsePath("path"); options.UseLiveness(new ActionLiveness((cancellationToken) => Task.FromResult(LivenessResult.Healthy()))); context.AddLiveness(options.CreateRegistration()); options = new BeatPulseLivenessRegistrationOptions("name"); options.UsePath("path"); options.UseLiveness(new ActionLiveness((cancellationToken) => Task.FromResult(LivenessResult.Healthy()))); context.AddLiveness(options.CreateRegistration()); context.GetAllLiveness("path") .Should() .HaveCount(2); }
public void throw_if_try_to_register_a_default_system_path() { var context = new BeatPulseContext(); var options = new BeatPulseLivenessRegistrationOptions("name1"); options.UsePath(string.Empty); options.UseLiveness(new ActionLiveness((cancellationToken) => Task.FromResult(LivenessResult.Healthy()))); Assert.Throws <InvalidOperationException>(() => { context.AddLiveness(options.CreateRegistration()); }); }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.Configure <CookiePolicyOptions>(options => { // This lambda determines whether user consent for non-essential cookies is needed for a given request. options.CheckConsentNeeded = context => true; options.MinimumSameSitePolicy = SameSiteMode.None; }); services.AddBeatPulse(setup => { // //add existing liveness packages // //setup.AddSqlServer("Server=.;Integrated Security=true;Initial Catalog=master"); // or setup.AddXXXX() for all liveness packages on Nuget (mysql,sqlite,urlgroup,redis,idsvr,kafka,aws dynamo,azure storage and much more) // ie: setup.AddOracle("Data Source=localhost:49161/xe;User Id=system;Password=oracle"); setup.AddUrlGroup(new Uri[] { new Uri("http://www.google.es") }); //setup.AddUrlGroup(opt => //{ // opt.AddUri(new Uri("http://google.com"), uri => // { // uri.UsePost() // .AddCustomHeader("X-Method-Override", "DELETE"); // }); //}, "uri-group2", "UriLiveness2"); // //create simple ad-hoc liveness // setup.AddLiveness("custom-liveness", opt => { opt.UsePath("custom-liveness"); opt.UseLiveness(new ActionLiveness((cancellationToken) => { if (DateTime.Now.Minute % 3 == 0) { return(Task.FromResult( LivenessResult.Healthy())); } else { return(Task.FromResult( LivenessResult.UnHealthy(new ArgumentNullException("param1")))); } })); }); // //ceate ad-hoc liveness with dependency resolution // //setup.AddLiveness("custom-liveness-with-dependency", opt => //{ // opt.UsePath("custom-liveness-with-dependency"); // opt.UseFactory(sp => new ActionLiveness((cancellationToken) => // { // var logger = sp.GetRequiredService<ILogger<Startup>>(); // logger.LogInformation("Logger is a dependency for this liveness"); // return Task.FromResult( // LivenessResult.Healthy()); // })); //}); }); services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1); }
public async Task response_http_status_ok_and_detailed_information_when_beat_pulse_service_is_healthy_and_detailed_information_is_configured() { string defaultName; string defaultPath; var healthCheck = new ActionLiveness((cancellationToken) => Task.FromResult(LivenessResult.Healthy())); var webHostBuilder = new WebHostBuilder() .UseBeatPulse(options => options.ConfigureDetailedOutput()) .UseStartup <DefaultStartup>() .ConfigureServices(svc => { svc.AddBeatPulse(context => { context.AddLiveness(nameof(defaultName), opt => { opt.UsePath(nameof(defaultPath)); opt.UseLiveness(healthCheck); }); }); }); var server = new TestServer(webHostBuilder); var response = await server.CreateClient() .GetAsync(BeatPulseKeys.BEATPULSE_DEFAULT_PATH); response.StatusCode .Should() .Be(HttpStatusCode.OK); var content = await response.Content.ReadAsStringAsync(); JsonConvert.DeserializeObject <OutputMessage>(content) .Should().NotBeNull(); }