public static IHealthBuilder AddHttpGetCheck(
            this IHealthCheckBuilder healthCheckBuilder,
            string name,
            Uri uri,
            TimeSpan timeout,
            bool degradedOnError = false)
        {
            healthCheckBuilder.AddCheck(
                name,
                async cancellationToken =>
            {
                try
                {
                    using (var tokenWithTimeout = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken))
                    {
                        tokenWithTimeout.CancelAfter(timeout);

                        var response = await HttpClient.GetAsync(uri, tokenWithTimeout.Token).ConfigureAwait(false);

                        return(response.IsSuccessStatusCode
                                ? HealthCheckResult.Healthy($"OK. {uri}")
                                : HealthCheckResultOnError($"FAILED. {uri} status code was {response.StatusCode}", degradedOnError));
                    }
                }
                catch (Exception ex)
                {
                    return(degradedOnError
                            ? HealthCheckResult.Degraded(ex)
                            : HealthCheckResult.Unhealthy(ex));
                }
            });

            return(healthCheckBuilder.Builder);
        }
        public static IHealthBuilder AddPingCheck(
            this IHealthCheckBuilder healthCheckBuilder,
            string name,
            string host,
            TimeSpan timeout,
            bool degradedOnError = false)
        {
            healthCheckBuilder.AddCheck(
                name,
                async() =>
            {
                try
                {
                    var ping   = new Ping();
                    var result = await ping.SendPingAsync(host, (int)timeout.TotalMilliseconds).ConfigureAwait(false);

                    return(result.Status == IPStatus.Success
                            ? HealthCheckResult.Healthy($"OK. {host}")
                            : HealthCheckResultOnError($"FAILED. {host} ping result was {result.Status}", degradedOnError));
                }
                catch (Exception ex)
                {
                    return(degradedOnError
                            ? HealthCheckResult.Degraded(ex)
                            : HealthCheckResult.Unhealthy(ex));
                }
            });

            return(healthCheckBuilder.Builder);
        }
Esempio n. 3
0
 /// <summary>
 /// Add a RabbitMQ HealthCheck.
 /// </summary>
 /// <param name="builder"><see cref="IHealthCheckBuilder"/></param>
 /// <param name="name">The name of the Health Check</param>
 /// <param name="connectionFactory">A RabbitMQ Connection Factory</param>
 /// <returns><see cref="IHealthBuilder"/></returns>
 public static IHealthBuilder AddRabbitMQHealthCheck(
     this IHealthCheckBuilder builder,
     string name,
     IConnectionFactory connectionFactory)
 {
     return(builder.AddCheck(new RabbitMQHealthCheck(name, connectionFactory)));
 }
Esempio n. 4
0
        public static IHealthBuilder AddHttpPostCheck(
            this IHealthCheckBuilder healthCheckBuilder,
            string name,
            Uri uri,
            HttpContent content,
            int retries,
            TimeSpan delayBetweenRetries,
            TimeSpan timeoutPerRequest,
            bool degradedOnError = false,
            Dictionary <string, string> requestHeaders = null)
        {
            EnsureValidRetries(retries);
            EnsureValidDelayBetweenRequests(delayBetweenRetries);
            EnsureValidTimeoutPerRequest(timeoutPerRequest);

            healthCheckBuilder.AddCheck(
                name,
                async cancellationToken => await ExecuteHealthCheckWithRetriesAsync(
                    uri,
                    content,
                    retries,
                    delayBetweenRetries,
                    timeoutPerRequest,
                    degradedOnError,
                    cancellationToken,
                    requestHeaders));

            return(healthCheckBuilder.Builder);
        }
Esempio n. 5
0
        public static IHealthCheckBuilder AddSqlCheck(this IHealthCheckBuilder builder, string name, string connectionString)
        {
            builder.AddCheck($"SqlCheck({name})", async() =>
            {
                try
                {
                    // TODO: There is probably a much better way to do this.
                    using (var connection = new SqlConnection(connectionString))
                    {
                        connection.Open();
                        using (var command = connection.CreateCommand())
                        {
                            command.CommandType = CommandType.Text;
                            command.CommandText = "SELECT 1";
                            var result          = (int)await command.ExecuteScalarAsync().ConfigureAwait(false);

                            if (result == 1)
                            {
                                return(HealthCheckResult.Healthy($"SqlCheck({name}): Healthy"));
                            }

                            return(HealthCheckResult.Unhealthy($"SqlCheck({name}): Unhealthy"));
                        }
                    }
                }
                catch (Exception ex)
                {
                    return(HealthCheckResult.Unhealthy($"SqlCheck({name}): Exception during check: {ex.GetType().FullName}"));
                }
            });

            return(builder);
        }
Esempio n. 6
0
        /// <summary>
        ///     Registers a health check on the process confirming that the current amount of virtual memory is below the
        ///     threshold.
        /// </summary>
        /// <param name="healthCheckBuilder">The health check healthCheckBuilder where the health check is registered.</param>
        /// <param name="name">The name of the health check.</param>
        /// <param name="thresholdBytes">The virtual memory threshold in bytes.</param>
        /// <param name="degradedOnError">Return a degraded status instead of unhealthy on error.</param>
        /// <returns>The health check healthCheckBuilder instance</returns>
        public static IHealthBuilder AddProcessVirtualMemorySizeCheck(
            this IHealthCheckBuilder healthCheckBuilder,
            string name,
            long thresholdBytes,
            bool degradedOnError = false)
        {
            healthCheckBuilder.AddCheck(
                name,
                () =>
            {
                try
                {
                    var currentSize = GetCurrentProcess().VirtualMemorySize64;
                    return(new ValueTask <HealthCheckResult>(
                               currentSize <= thresholdBytes
                                ? HealthCheckResult.Healthy($"OK. {thresholdBytes} bytes")
                                : HealthCheckResultOnError($"FAILED. {currentSize} > {thresholdBytes} bytes", degradedOnError)));
                }
                catch (Exception ex)
                {
                    return(degradedOnError
                            ? new ValueTask <HealthCheckResult>(HealthCheckResult.Degraded(ex))
                            : new ValueTask <HealthCheckResult>(HealthCheckResult.Unhealthy(ex)));
                }
            });

            return(healthCheckBuilder.Builder);
        }
        public static IHealthBuilder AddHttpGetCheck(
            this IHealthCheckBuilder healthCheckBuilder,
            string name,
            Uri uri,
            int retries,
            TimeSpan delayBetweenRetries,
            TimeSpan timeoutPerRequest,
            bool degradedOnError = false)
        {
            EnsureValidRetries(retries);
            EnsureValidDelayBetweenRequests(delayBetweenRetries);
            EnsureValidTimeoutPerRequest(timeoutPerRequest);

            healthCheckBuilder.AddCheck(
                name,
                async cancellationToken => await ExecuteHealthCheckWithRetriesAsync(
                    uri,
                    retries,
                    delayBetweenRetries,
                    timeoutPerRequest,
                    degradedOnError,
                    cancellationToken));

            return(healthCheckBuilder.Builder);
        }
Esempio n. 8
0
        public static IHealthBuilder AddAzureServiceBusTopicSubscriptionDeadLetterQueueCheck(
            this IHealthCheckBuilder builder,
            string name,
            string connectionString,
            string topicName,
            string subscriptionName,
            long deadLetterWarningThreshold = 1,
            long?deadLetterErrorThreshold   = null)
        {
            if (deadLetterErrorThreshold.HasValue && (deadLetterWarningThreshold > deadLetterErrorThreshold))
            {
                throw new ArgumentException("Error threshold must exceed warning threshold", nameof(deadLetterErrorThreshold));
            }

            var managementClient = new ManagementClient(connectionString);

            builder.AddCheck(
                name,
                ServiceBusHealthChecks.CheckDeadLetterQueueCount(Logger, EntityNameHelper.FormatSubscriptionPath(topicName, subscriptionName), name, GetQueueMessageCount, deadLetterWarningThreshold, deadLetterErrorThreshold));
            return(builder.Builder);

            async Task <MessageCountDetails> GetQueueMessageCount()
            {
                var info = await managementClient.GetSubscriptionRuntimeInfoAsync(topicName, subscriptionName);

                return(info.MessageCountDetails);
            }
        }
        public static IHealthBuilder AddAzureQueueStorageMessageCountCheck(
            this IHealthCheckBuilder builder,
            string name,
            string connectionString,
            string queueName,
            long degradedThreshold  = 1,
            long?unhealthyThreshold = null)
        {
            if (unhealthyThreshold.HasValue && unhealthyThreshold < degradedThreshold)
            {
                throw new ArgumentException("Unhealthy threshold must not be less than degraded threshold.", nameof(unhealthyThreshold));
            }

            if (degradedThreshold < 0)
            {
                throw new ArgumentException("must be greater than 0", nameof(degradedThreshold));
            }

            if (unhealthyThreshold < 0)
            {
                throw new ArgumentException("must be greater than 0", nameof(unhealthyThreshold));
            }

            builder.AddCheck(name, CheckMessageCount(name, CloudStorageAccount.Parse(connectionString), queueName, degradedThreshold, unhealthyThreshold));

            return(builder.Builder);
        }
        public static IHealthCheckBuilder AddRedisCheck(this IHealthCheckBuilder builder, string name,
                                                        string connectionString, Action <RedisCheckOptions> configureOptions)
        {
            var options = new RedisCheckOptions();

            configureOptions(options);

            return(builder.AddCheck(new RedisCheck(name, connectionString, options)));
        }
Esempio n. 11
0
        public static IHealthCheckBuilder AddHttpCheck(this IHealthCheckBuilder builder, string name, Uri uri,
                                                       Action <HttpCheckOptions> configureOptions)
        {
            var options = new HttpCheckOptions();

            configureOptions(options);

            return(builder.AddCheck(new HttpCheck(name, uri, options)));
        }
        public static IHealthBuilder AddAzureServiceBusTopicConnectivityCheck(
            this IHealthCheckBuilder builder,
            string name,
            TopicClient topicClient)
        {
            builder.AddCheck(name, CheckServiceBusTopicConnectivity(name, topicClient));

            return(builder.Builder);
        }
Esempio n. 13
0
        public static IHealthBuilder AddAzureTableStorageConnectivityCheck(
            this IHealthCheckBuilder builder,
            string name,
            string connectionString)
        {
            builder.AddCheck(name, CheckTableStorageConnectivity(name, CloudStorageAccount.Parse(connectionString)));

            return(builder.Builder);
        }
Esempio n. 14
0
        public static IHealthBuilder AddAzureBlobStorageConnectivityCheck(
            this IHealthCheckBuilder builder,
            string name,
            CloudStorageAccount storageAccount)
        {
            builder.AddCheck(name, CheckBlobStorageConnectivity(name, storageAccount));

            return(builder.Builder);
        }
Esempio n. 15
0
        public static IHealthBuilder AddAzureDocumentDBCollectionCheck(
            this IHealthCheckBuilder builder,
            string name,
            Uri collectionUri,
            DocumentClient documentClient)
        {
            builder.AddCheck(name, CheckDocumentDbCollectionExists(collectionUri, documentClient));

            return(builder.Builder);
        }
Esempio n. 16
0
        public static IHealthBuilder AddQuiteTimeCheck(
            this IHealthCheckBuilder builder,
            string name,
            Func <CancellationToken, ValueTask <HealthCheckResult> > check,
            HealthCheck.QuiteTime quiteTime)
        {
            builder.AddCheck(new HealthCheck(name, check, quiteTime));

            return(builder.Builder);
        }
        public static IHealthBuilder AddAzureQueueStorageCheck(
            this IHealthCheckBuilder builder,
            string name,
            CloudStorageAccount storageAccount,
            string queueName)
        {
            builder.AddCheck(name, CheckQueueExistsAsync(name, storageAccount, queueName));

            return(builder.Builder);
        }
Esempio n. 18
0
        public static IHealthBuilder AddAzureDocumentDBDatabaseCheck(
            this IHealthCheckBuilder builder,
            string name,
            Uri databaseUri,
            DocumentClient documentClient)
        {
            builder.AddCheck(name, CheckDocumentDBDatabaseConnectivity(databaseUri, documentClient));

            return(builder.Builder);
        }
Esempio n. 19
0
        public static IHealthBuilder AddAzureTableStorageTableCheck(
            this IHealthCheckBuilder builder,
            string name,
            CloudStorageAccount storageAccount,
            string tableName)
        {
            builder.AddCheck(name, CheckAzureTableStorageTableExists(name, storageAccount, tableName));

            return(builder.Builder);
        }
Esempio n. 20
0
        public static IHealthBuilder AddAzureBlobStorageContainerCheck(
            this IHealthCheckBuilder builder,
            string name,
            CloudStorageAccount storageAccount,
            string containerName)
        {
            builder.AddCheck(name, CheckAzureBlobStorageContainerExists(name, storageAccount, containerName));

            return(builder.Builder);
        }
        public static IHealthBuilder AddAzureQueueStorageCheck(
            this IHealthCheckBuilder builder,
            string name,
            string connectionString,
            string queueName)
        {
            builder.AddCheck(name, CheckQueueExists(name, CloudStorageAccount.Parse(connectionString), queueName));

            return(builder.Builder);
        }
        public static IHealthBuilder AddCachedCheck(
            this IHealthCheckBuilder builder,
            string name,
            Func <CancellationToken, ValueTask <HealthCheckResult> > check,
            TimeSpan cacheDuration)
        {
            builder.AddCheck(new HealthCheck(name, check, cacheDuration));

            return(builder.Builder);
        }
Esempio n. 23
0
        public static IHealthBuilder AddAzureDocumentDBDatabaseCheck(
            this IHealthCheckBuilder builder,
            string name,
            Uri databaseUri,
            string endpointUri,
            string key)
        {
            builder.AddCheck(name, CheckDocumentDBDatabaseConnectivity(databaseUri, endpointUri, key));

            return(builder.Builder);
        }
Esempio n. 24
0
        public static IHealthBuilder AddAzureDocumentDBCollectionCheck(
            this IHealthCheckBuilder builder,
            string name,
            Uri collectionUri,
            string endpointUri,
            string key)
        {
            builder.AddCheck(name, CheckDocumentDbCollectionExists(collectionUri, endpointUri, key));

            return(builder.Builder);
        }
Esempio n. 25
0
        public static IHealthBuilder AddSqlCheck(
            this IHealthCheckBuilder healthCheckBuilder,
            string name,
            Func <IDbConnection> newDbConnection,
            TimeSpan timeout,
            bool degradedOnError = false)
        {
            if (timeout <= TimeSpan.Zero)
            {
                throw new InvalidOperationException($"{nameof(timeout)} must be greater than 0");
            }

            healthCheckBuilder.AddCheck(name, cancellationToken =>
            {
                var sw = new Stopwatch();

                try
                {
                    using (var tokenWithTimeout = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken))
                    {
                        tokenWithTimeout.CancelAfter(timeout);

                        sw.Start();
                        using (var connection = newDbConnection())
                        {
                            connection.Open();
                            using (var command = connection.CreateCommand())
                            {
                                command.CommandType = CommandType.Text;
                                command.CommandText = "SELECT 1";
                                var commandResult   = (int)command.ExecuteScalar();

                                var result = commandResult == 1
                                    ? HealthCheckResult.Healthy($"OK. {name}.")
                                    : HealthCheckResultOnError($"FAILED. {name} SELECT failed. Time taken: {sw.ElapsedMilliseconds}ms.", degradedOnError);

                                return(new ValueTask <HealthCheckResult>(result));
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    var failedResult = degradedOnError
                        ? HealthCheckResult.Degraded(ex)
                        : HealthCheckResult.Unhealthy(ex);

                    return(new ValueTask <HealthCheckResult>(failedResult));
                }
            });

            return(healthCheckBuilder.Builder);
        }
Esempio n. 26
0
        public static IHealthCheckBuilder AddHttpPingCheck(this IHealthCheckBuilder builder, string name, Uri baseAddress)
        {
            var options = new HttpCheckOptions {
                ExpectedContent = "PONG"
            };

            var uriBuilder = new UriBuilder(baseAddress.GetLeftPart(UriPartial.Authority))
            {
                Path = "_diagnostics/ping"
            };

            return(builder.AddCheck(new HttpCheck(name, uriBuilder.Uri, options)));
        }
Esempio n. 27
0
        public static IHealthBuilder AddPingCheck(
            this IHealthCheckBuilder healthCheckBuilder,
            string name,
            string host,
            TimeSpan timeout,
            bool degradedOnError = false)
        {
            healthCheckBuilder.AddCheck(
                name,
                async() => await ExecutePingCheckAsync(host, timeout, degradedOnError));

            return(healthCheckBuilder.Builder);
        }
        public static IHealthBuilder AddHttpGetCheck(
            this IHealthCheckBuilder healthCheckBuilder,
            string name,
            Uri uri,
            TimeSpan timeout,
            bool degradedOnError = false)
        {
            EnsureValidTimeout(timeout);

            healthCheckBuilder.AddCheck(
                name,
                async cancellationToken => await ExecuteHttpCheckNoRetriesAsync(uri, timeout, degradedOnError, cancellationToken));

            return(healthCheckBuilder.Builder);
        }
        public static IHealthBuilder AddAzureServiceBusTopicConnectivityCheck(
            this IHealthCheckBuilder builder,
            string name,
            string connectionString,
            string topicName)
        {
            var topicClient = new TopicClient(connectionString, topicName)
            {
                OperationTimeout = DefaultTimeout
            };

            builder.AddCheck(name, CheckServiceBusTopicConnectivity(name, topicClient));

            return(builder.Builder);
        }
Esempio n. 30
0
        public static IHealthBuilder AddSqlCheck(
            this IHealthCheckBuilder healthCheckBuilder,
            string name,
            Func <IDbConnection> newDbConnection,
            TimeSpan timeout,
            bool degradedOnError = false)
        {
            EnsureValidTimeout(timeout);

            healthCheckBuilder.AddCheck(
                name,
                cancellationToken => ExecuteSqlCheckAsync(name, newDbConnection, timeout, degradedOnError, cancellationToken));

            return(healthCheckBuilder.Builder);
        }