Example #1
0
        protected void SetupServices(
            IServiceCollection services,
            HealthEndpointsOptions healthMiddlewareCoreChecksOptions,
            IEnumerable <HealthCheckResult> healthChecks = null)
        {
            services.AddOptions();
            services.AddLogging();

            // TODO: scan for healthchecks
            // var startupAssemblyName = typeof(TestStartup).Assembly.GetName().Name;

            var builder = new HealthBuilder()
                          .Configuration.Configure(options => options.Enabled = true)
                          .OutputHealth.AsPlainText()
                          .OutputHealth.AsJson();

            var checks = healthChecks?.ToList() ?? new List <HealthCheckResult>();

            for (var i = 0; i < checks.Count; i++)
            {
                var check = checks[i];
                builder.HealthChecks.AddCheck("Check" + i, () => new ValueTask <HealthCheckResult>(check));
            }

            services.AddHealth(builder)
            .AddHealthEndpoints(
                options =>
            {
                options.HealthEndpointEnabled = healthMiddlewareCoreChecksOptions.HealthEndpointEnabled;
                options.PingEndpointEnabled   = healthMiddlewareCoreChecksOptions.PingEndpointEnabled;
                options.Timeout = healthMiddlewareCoreChecksOptions.Timeout;
            });
        }
        public void Should_throw_when_task_is_cancelled()
        {
            // Arrange
            const string name = "custom with cancellation token";

            // Act
            var builder = new HealthBuilder().HealthChecks.AddCheck(
                name,
                async token =>
            {
                await Task.Delay(2000, token);
                return(HealthCheckResult.Healthy());
            });

            var tokenSource = new CancellationTokenSource();

            tokenSource.CancelAfter(200);

            var check = builder.Build().Checks.Single();

            // Assert
            Action action = () =>
            {
                var result = check.ExecuteAsync(tokenSource.Token).GetAwaiter().GetResult();

                result.Check.Status.Should().Be(HealthCheckStatus.Unhealthy);
            };

            action.ShouldThrow <OperationCanceledException>();
        }
Example #3
0
        private IHealthRoot ConfigureHealth()
        {
            var healthBuilder = new HealthBuilder();

            healthBuilder.HealthChecks.AddCheck(new SampleHealthCheck());
            return(healthBuilder.Build());
        }
Example #4
0
        private static void Init()
        {
            var configurationBuilder = new ConfigurationBuilder()
                                       .SetBasePath(Directory.GetCurrentDirectory())
                                       .AddJsonFile("appsettings.json");

            Configuration = configurationBuilder.Build();

            var services = new ServiceCollection();

            var unused = new HealthBuilder()
                         .Configuration.ReadFrom(Configuration)
                         .OutputHealth.AsPlainText()
                         .OutputHealth.AsJson()
                         .HealthChecks.AddCheck("inline-check", () => new ValueTask <HealthCheckResult>(HealthCheckResult.Healthy()))
                         .HealthChecks.RegisterFromAssembly(services)
                         .BuildAndAddTo(services);

            // BuildAndAddTo will add services to the IServiceCollection
            // services.AddHealth(health);

            services.AddLogging(builder =>
            {
                builder.SetMinimumLevel(LogLevel.Trace);
                builder.AddConsole();
            });

            ServiceProvider = services.BuildServiceProvider();
        }
Example #5
0
        public async Task Can_apply_ascii_health_formatting()
        {
            // Arrange
            var health = new HealthBuilder()
                         .OutputHealth.AsPlainText()
                         .HealthChecks.AddCheck("test", () => new ValueTask <HealthCheckResult>(HealthCheckResult.Healthy()))
                         .Build();

            var serializer = new HealthStatusSerializer();

            // Act
            var healthStatus = await health.HealthCheckRunner.ReadAsync();

            using (var sw = new StringWriter())
            {
                using (var writer = new HealthStatusTextWriter(sw))
                {
                    serializer.Serialize(writer, healthStatus);
                }

                // Assert
                sw.ToString().Should().Be(
                    "# OVERALL STATUS: Healthy\n--------------------------------------------------------------\n# CHECK: test\n\n           MESSAGE = OK\n            STATUS = Healthy\n--------------------------------------------------------------\n");
            }
        }
Example #6
0
        private static async Task Main(string[] args)
        {
            var health = new HealthBuilder()
                         .HealthChecks.AddCheck <SampleHealthCheck>()
                         .HealthChecks.AddCheck("Healthy Check",
                                                () => new ValueTask <HealthCheckResult>(HealthCheckResult.Healthy()))
                         .HealthChecks.AddCheck("Degraded Check",
                                                () => new ValueTask <HealthCheckResult>(HealthCheckResult.Degraded()))
                         .HealthChecks.AddCheck("Unhealthy Check",
                                                () => new ValueTask <HealthCheckResult>(HealthCheckResult.Unhealthy()))
                         .HealthChecks.AddProcessPrivateMemorySizeCheck("Private Memory Size", 100)
                         .HealthChecks.AddProcessVirtualMemorySizeCheck("Virtual Memory Size", 200)
                         .HealthChecks.AddProcessPhysicalMemoryCheck("Working Set", 300)
                         .HealthChecks.AddPingCheck("google ping", "google.com", TimeSpan.FromSeconds(10))
                         .HealthChecks.AddHttpGetCheck("github", new Uri("https://github.com/"), TimeSpan.FromSeconds(10))
                         .Build();



            var healthStatus = await health.HealthCheckRunner.ReadAsync();

            using (var stream = new MemoryStream())
            {
                await health.DefaultOutputHealthFormatter.WriteAsync(stream, healthStatus);

                var result = Encoding.UTF8.GetString(stream.ToArray());
                WriteLine(result);
            }

            ReadKey();
        }
Example #7
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc(options =>
            {
                //options.Filters.Add(new ValidationAttribute());
                options.Filters.Add(new ExceptionHandlerFilterAttribute(_loggerFactory));
            })
            .SetCompatibilityVersion(CompatibilityVersion.Version_2_2)
            .AddFluentValidation(fv => fv.RegisterValidatorsFromAssembly(Assembly.GetExecutingAssembly()));

            services.AddCors();
            ConfigureServicesDI(services);
            services.AddAutoMapper();
            ConfigureServicesVersioning(services);
            ConfigureServicesSwagger(services);

            var memoryThreshhold = 800000000; // 800 MB
            var healthBuilder    = new HealthBuilder()
                                              // Check that the current amount of physical memory in bytes is below a threshold
                                   .HealthChecks.AddProcessPhysicalMemoryCheck("Working Set", memoryThreshhold)
                                              // Check connectivity to google with a "ping", passes if the result is `IPStatus.Success`
                                   .HealthChecks.AddPingCheck("google ping", "google.com", TimeSpan.FromSeconds(10))
                                              // Check that our SQL Server is still up and running
                                   .HealthChecks.AddSqlCheck("Food Truck Database",
                                                             _configuration.GetConnectionString("FoodTruckConnectionString"), TimeSpan.FromSeconds(10))
                                   .OutputHealth.AsJson()
                                   .BuildAndAddTo(services);

            services.AddHealthEndpoints();
        }
Example #8
0
        public static async Task Main()
        {
            long threshold      = 1;
            var  metricsBuilder = new MetricsBuilder();
            var  healthBuilder  = new HealthBuilder();

            var metrics = metricsBuilder.Report.ToInfluxDb(AppSetting.InfluxDB.Url,
                                                           AppSetting.InfluxDB.DatabaseName,
                                                           TimeSpan.FromSeconds(5))
                          .Report.ToConsole(TimeSpan.FromSeconds(5))
                          .Build()
            ;
            var health = healthBuilder.Configuration
                         .Configure(p =>
            {
                p.Enabled          = true;
                p.ReportingEnabled = true;
            })
                         .Report
                         .ToMetrics(metrics)
                         .HealthChecks.AddProcessPrivateMemorySizeCheck("Private Memory Size", threshold)
                         .HealthChecks.AddProcessVirtualMemorySizeCheck("Virtual Memory Size", threshold)
                         .HealthChecks.AddProcessPhysicalMemoryCheck("Working Set", threshold)
                         .HealthChecks.AddPingCheck("google ping", "google.com", TimeSpan.FromSeconds(10))
                         .Build();

            var counter = new CounterOptions {
                Name = "my_counter"
            };

            metrics.Measure.Counter.Increment(counter);

            var scheduler =
                new AppMetricsTaskScheduler(TimeSpan.FromSeconds(5),
                                            async() =>
            {
                await Task.WhenAll(metrics.ReportRunner.RunAllAsync());
                var healthStatus =
                    await health.HealthCheckRunner.ReadAsync();

                using (var stream = new MemoryStream())
                {
                    await health.DefaultOutputHealthFormatter
                    .WriteAsync(stream, healthStatus);
                    var result = Encoding.UTF8.GetString(stream.ToArray());
                    Console.WriteLine(result);
                }

                foreach (var reporter in health.Reporters)
                {
                    await reporter.ReportAsync(health.Options,
                                               healthStatus);
                }
            });

            scheduler.Start();

            Console.ReadKey();
        }
Example #9
0
        public HealthTestFixture()
        {
            var health = new HealthBuilder()
                         .HealthChecks.AddCheck("test", () => new ValueTask <HealthCheckResult>(HealthCheckResult.Healthy()))
                         .Build();

            HealthCheckRunner = health.HealthCheckRunner;
        }
Example #10
0
        public static IServiceCollection AddHealth(this IServiceCollection services, Action <IHealthBuilder> setupHealth)
        {
            var builder = new HealthBuilder();

            setupHealth(builder);

            return(AddHealth(services, builder));
        }
Example #11
0
        public void Options_should_not_be_null_when_configuration_not_used()
        {
            // Arrange
            var builder = new HealthBuilder();

            // Act
            var health = builder.Build();

            // Assert
            health.Options.Should().NotBeNull();
        }
Example #12
0
        public void When_checks_registered_should_not_use_noop_runner()
        {
            // Arrange
            var builder = new HealthBuilder();

            // Act
            var health = builder.HealthChecks.AddCheck("test", () => new ValueTask <HealthCheckResult>(HealthCheckResult.Healthy())).Build();

            // Assert
            health.HealthCheckRunner.Should().NotBeOfType <NoOpHealthCheckRunner>();
        }
Example #13
0
        public void When_no_checks_registered_use_noop_runner()
        {
            // Arrange
            var builder = new HealthBuilder();

            // Act
            var health = builder.OutputHealth.AsPlainText().Build();

            // Assert
            health.HealthCheckRunner.Should().BeOfType <NoOpHealthCheckRunner>();
        }
Example #14
0
        public void Can_use_reporter_of_type()
        {
            // Arrange
            var builder = new HealthBuilder().Report.Using <TestReporter>();

            // Act
            var metrics = builder.Build();

            // Assert
            metrics.Reporters.Should().Contain(reportMetrics => reportMetrics is TestReporter);
        }
        public void At_least_one_formatter_is_required()
        {
            // Arrange
            var builder = new HealthBuilder();

            // Act
            var health = builder.Build();

            // Assert
            health.OutputHealthFormatters.Count.Should().Be(1);
            health.DefaultOutputHealthFormatter.Should().NotBeNull();
        }
Example #16
0
        public void Default_formatter_should_default_to_text_if_not_configured()
        {
            // Arrange
            var builder = new HealthBuilder();

            // Act
            var health = builder.Build();

            // Assert
            health.DefaultOutputHealthFormatter.Should().NotBeNull();
            health.DefaultOutputHealthFormatter.Should().BeOfType <HealthStatusTextOutputFormatter>();
        }
Example #17
0
        public void Cannot_set_null_reporter()
        {
            // Arrange
            Action action = () =>
            {
                // Act
                var unused = new HealthBuilder().Report.Using(reporter: null);
            };

            // Assert
            action.Should().Throw <ArgumentNullException>();
        }
Example #18
0
        public void Can_use_reporter_of_type_and_override_flushinterval()
        {
            // Arrange
            var builder = new HealthBuilder().Report.Using <TestReporter>(reportInterval: TimeSpan.FromDays(1));

            // Act
            var metrics  = builder.Build();
            var reporter = (metrics.Reporters as HealthReporterCollection)?.GetType <TestReporter>();

            // Assert
            reporter?.ReportInterval.Should().Be(TimeSpan.FromDays(1));
        }
        public void Cannot_set_null_health_output_formatter()
        {
            // Arrange
            Action action = () =>
            {
                // Act
                var unused = new HealthBuilder().OutputHealth.Using(null);
            };

            // Assert
            action.Should().Throw <ArgumentNullException>();
        }
Example #20
0
        /// <summary>
        ///     Initializes a new instance of the <see cref="IHealthBuilder" /> class with pre-configured defaults.
        /// </summary>
        /// <remarks>
        ///     The following defaults are applied to the returned <see cref="IHealthBuilder" />:
        ///     use, JSON and Plain Text health check result formatting.
        /// </remarks>
        /// <returns>The initialized <see cref="IHealthBuilder" />.</returns>
        public static IHealthBuilder CreateDefaultBuilder()
        {
            var builder = new HealthBuilder().Configuration.Configure(
                options =>
            {
                options.Enabled = true;
            })
                          .OutputHealth.AsJson()
                          .OutputHealth.AsPlainText();

            return(builder);
        }
Example #21
0
        public void Cannot_set_null_health_check()
        {
            // Arrange
            Action action = () =>
            {
                // Act
                var unused = new HealthBuilder().HealthChecks.AddCheck(null, () => HealthyResult);
            };

            // Assert
            action.Should().Throw <ArgumentNullException>();
        }
Example #22
0
        public void Can_register_type_health_checks()
        {
            // Arrange
            var builder = new HealthBuilder();

            // Act
            var health = builder.HealthChecks.AddCheck <SampleHealthCheck>().Build();

            // Assert
            health.Checks.Count().Should().Be(1);
            health.Checks.Single().Name.Should().Be("SampleHealthCheck");
        }
Example #23
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.Configure <EndpointsConfig>(Configuration.GetSection("Endpoints"));

            services.AddSingleton <IBusDataStore, RedisBusDataStore>();

            services.AddSingleton <IRabbitMQPersistentConnection>(sp =>
            {
                var factory = new ConnectionFactory()
                {
                    HostName = Configuration.GetValue <string>("Endpoints:RabbitMq")
                };

                if (!string.IsNullOrEmpty(Configuration["EventBusUserName"]))
                {
                    factory.UserName = Configuration["EventBusUserName"];
                }

                if (!string.IsNullOrEmpty(Configuration["EventBusPassword"]))
                {
                    factory.Password = Configuration["EventBusPassword"];
                }

                var retryCount = 5;
                if (!string.IsNullOrEmpty(Configuration["EventBusRetryCount"]))
                {
                    retryCount = int.Parse(Configuration["EventBusRetryCount"]);
                }

                return(new DefaultRabbitMQPersistentConnection(factory, retryCount));
            });

            RegisterEventBus(services);
            var identityServerEndpoint = Configuration.GetValue <string>("Endpoints:IdentityServer");

            // Add health checks
            var healthBuilder = new HealthBuilder()
                                .HealthChecks.AddHttpGetCheck("IdentityServer", new Uri(new Uri(identityServerEndpoint), "/_system/health"), 3, TimeSpan.FromSeconds(2), TimeSpan.FromSeconds(2));

            services.AddHealth(healthBuilder.Build());
            services.TryAddEnumerable(ServiceDescriptor.Singleton <IConfigureOptions <HealthEndpointsHostingOptions>, HealthCheckOptions>());

            services.AddMvc();

            services.AddAuthentication("Bearer")
            .AddIdentityServerAuthentication(options =>
            {
                options.Authority            = identityServerEndpoint;
                options.RequireHttpsMetadata = false;
                options.ApiName = "resources";
            });
        }
Example #24
0
        public void Can_register_instance_health_checks()
        {
            // Arrange
            var builder = new HealthBuilder();
            var check   = new DatabaseHealthCheck(new Database());

            // Act
            var health = builder.HealthChecks.AddCheck(check).Build();

            // Assert
            health.Checks.Count().Should().Be(1);
            health.Checks.Single().Name.Should().Be("DatabaseCheck");
        }
Example #25
0
        public void Can_register_health_check_without_cancellation_token()
        {
            // Arrange
            const string check   = "check";
            var          builder = new HealthBuilder();

            // Act
            var health = builder.HealthChecks.AddCheck(check, () => new ValueTask <HealthCheckResult>(HealthCheckResult.Degraded())).Build();

            // Assert
            health.Checks.Count().Should().Be(1);
            health.Checks.First(c => c.Name == check).Should().NotBeNull();
        }
        public void Can_set_options_with_instance()
        {
            // Arrange
            var options = new HealthOptions {
                Enabled = true
            };

            // Act
            var health = new HealthBuilder().Configuration.Configure(options).Build();

            // Assert
            health.Options.Enabled.Should().BeTrue();
        }
Example #27
0
        public void Can_bind_metrics_options_from_configuration()
        {
            // Arrange
            var builder       = new HealthBuilder();
            var configuration = new ConfigurationBuilder().AddJsonFile("JsonFIles/HealthOptions.json").Build();

            // Act
            builder.Configuration.ReadFrom(configuration);
            var health = builder.Build();

            // Assert
            health.Options.Enabled.Should().BeFalse();
        }
        public void Should_set_health_output_formatters_when_selected_via_type()
        {
            // Arrange
            var builder = new HealthBuilder()
                          .OutputHealth.Using <HealthStatusTextOutputFormatter>()
                          .OutputHealth.Using <HealthStatusJsonOutputFormatter>();

            // Act
            var health = builder.Build();

            // Assert
            health.OutputHealthFormatters.Count.Should().Be(2);
        }
        public void Default_health_output_formatter_should_be_first_formatter_selected_via_type()
        {
            // Arrange
            var builder = new HealthBuilder()
                          .OutputHealth.Using <HealthStatusJsonOutputFormatter>()
                          .OutputHealth.Using <HealthStatusTextOutputFormatter>();

            // Act
            var health = builder.Build();

            // Assert
            health.DefaultOutputHealthFormatter.Should().BeOfType <HealthStatusJsonOutputFormatter>();
        }
        public void Should_only_add_a_single_formatter_of_the_same_type()
        {
            // Arrange
            var builder = new HealthBuilder()
                          .OutputHealth.Using <HealthStatusTextOutputFormatter>()
                          .OutputHealth.Using <HealthStatusTextOutputFormatter>();

            // Act
            var health = builder.Build();

            // Assert
            health.OutputHealthFormatters.Count.Should().Be(1);
            health.DefaultOutputHealthFormatter.Should().NotBeNull();
        }