Exemplo n.º 1
0
        public static IHealthChecksBuilder AddSelfCheck(this IHealthChecksBuilder builder, string name, HealthStatus?failureStatus = null, IEnumerable <string> tags = null)
        {
            // Register a check of type SelfHealthCheck
            builder.AddCheck <SelfHealthCheck>(name, failureStatus ?? HealthStatus.Degraded, tags);

            return(builder);
        }
Exemplo n.º 2
0
 private static IHealthChecksBuilder AddQuartzHealthCheck(
     this IHealthChecksBuilder builder,
     string suffix,
     IHealthCheck healthCheck)
 {
     return(builder.AddCheck($"quartz-{suffix}", healthCheck));
 }
Exemplo n.º 3
0
 private static IHealthChecksBuilder AddQuartzHealthCheck(
     this IHealthChecksBuilder builder,
     string suffix,
     IHealthCheck healthCheck)
 {
     return(builder.AddCheck($"quartz-{suffix}", healthCheck, HealthStatus.Unhealthy, new[] { "ready" }));
 }
Exemplo n.º 4
0
        /// <summary>
        /// Adds Azure Storage Health Check.
        /// </summary>
        /// <param name="builder"></param>
        /// <param name="name"></param>
        /// <param name="containerName"></param>
        /// <param name="setup"></param>
        /// <param name="failureStatus"></param>
        /// <param name="tags"></param>
        /// <returns></returns>
        public static IHealthChecksBuilder AddAzureBlobStorageCheck(
            this IHealthChecksBuilder builder,
            string name,
            string containerName,
            Action <StorageAccountOptions> setup,
            HealthStatus?failureStatus = default,
            IEnumerable <string> tags  = default)
        {
            var options = new StorageAccountOptions();

            setup?.Invoke(options);

            builder.Services.AddOptions <StorageAccountOptions>(name)
            .Configure((opt) =>
            {
                opt.ConnectionString = options.ConnectionString;
                opt.ContainerName    = containerName;
                opt.Name             = options.Name;
                opt.Token            = options.Token;
            });

            builder.AddCheck <AzureBlobStorageHealthCheck>(name, failureStatus ?? HealthStatus.Degraded, tags);

            return(builder);
        }
    public static IHealthChecksBuilder AddAutoNamedCheck <T>(this IHealthChecksBuilder builder, params string[] tags) where T : class, IHealthCheck
    {
        var    checkType = typeof(T);
        string name      = checkType.Name;

        if (checkType.IsConstructedGenericType && checkType.GenericTypeArguments.Length == 1)
        {
            name = checkType.GenericTypeArguments[0].Name;
        }

        if (name.EndsWith("HealthCheck", StringComparison.OrdinalIgnoreCase))
        {
            name = name.Substring(0, name.Length - 11);
        }
        if (name.EndsWith("Check", StringComparison.OrdinalIgnoreCase))
        {
            name = name.Substring(0, name.Length - 5);
        }
        if (name.EndsWith("Job", StringComparison.OrdinalIgnoreCase))
        {
            name = name.Substring(0, name.Length - 3);
        }

        var allTags = new List <string>(tags)
        {
            name
        };

        return(builder.AddCheck <T>(name, null, allTags));
    }
        public static IHealthChecksBuilder AddSelfCheck(this IHealthChecksBuilder builder, string name, HealthStatus?failureStatus = null, IEnumerable <string> tags = null)
        {
            builder.AddCheck <SelfHealthCheck>(name, failureStatus ?? HealthStatus.Degraded, tags);
            builder.AddDbContextCheck <CompraContext>();

            return(builder);
        }
Exemplo n.º 7
0
        /// <summary>
        /// Adds a health check to see whether the specified subscription exists for the specified topic, and optionally, checking configuration details.
        /// </summary>
        /// <param name="builder">The ASP.Net Core health check builder.</param>
        /// <param name="topicName">The topic to be checked.</param>
        /// <param name="subscriptionName">The subscription to be checked.</param>
        /// <param name="requiredConfiguration">Setup for the options specific to this topic &amp; subscription.</param>
        public static IHealthChecksBuilder AddAzureServiceBusSubscriptionCheck(this IHealthChecksBuilder builder, string topicName, string subscriptionName, Action <SubscriptionHealthCheckOptions> requiredConfiguration = null)
        {
            if (builder == null)
            {
                throw new ArgumentNullException(nameof(builder));
            }

            if (string.IsNullOrWhiteSpace(topicName))
            {
                throw new ArgumentNullException(nameof(topicName));
            }

            if (string.IsNullOrWhiteSpace(subscriptionName))
            {
                throw new ArgumentNullException(nameof(subscriptionName));
            }

            var topicSubscriptionName = $"{topicName}/{subscriptionName}";

            builder.Services.AddAzureServiceBusDefaultServices().Configure <SubscriptionHealthCheckOptions>(topicSubscriptionName, config =>
            {
                config.TopicName        = topicName;
                config.SubscriptionName = subscriptionName;
                requiredConfiguration?.Invoke(config);
            });

            return(builder.AddCheck <SubscriptionHealthCheck>(topicSubscriptionName));
        }
Exemplo n.º 8
0
        /// <summary>
        /// Adds a health check for the specified <see cref="DbContext"/> type.
        /// </summary>
        /// <typeparam name="TContext">The <see cref="DbContext"/> type.</typeparam>
        /// <param name="builder">The <see cref="IHealthChecksBuilder"/>.</param>
        /// <param name="name">
        /// The health check name. Optional. If <c>null</c> the type name of <typeparamref name="TContext"/> 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="customTestQuery">
        /// A custom test query that will be executed when the health check executes to test the health of the database
        /// connection and configurations.
        /// </param>
        /// <returns>The <see cref="IHealthChecksBuilder"/>.</returns>
        /// <remarks>
        /// <para>
        /// The health check implementation added by this method will use the dependency injection container
        /// to create an instance of <typeparamref name="TContext"/>.
        /// </para>
        /// <para>
        /// By default the health check implementation will use the <see cref="DatabaseFacade.CanConnectAsync(CancellationToken)"/> method
        /// to test connectivity to the database. This method requires that the database provider has correctly implemented the
        /// <see cref="IDatabaseCreatorWithCanConnect" /> interface. If the database provide has not implemented this interface
        /// then the health check will report a failure.
        /// </para>
        /// <para>
        /// Providing a <paramref name="customTestQuery" /> will replace the use of <see cref="DatabaseFacade.CanConnectAsync(CancellationToken)"/>
        /// to test database connectivity. An implementation of a test query should handle exceptions that can arise due to connectivity failure,
        /// and should return a pass/fail result. The test query should be be designed to complete in a short and predicatable amount of time.
        /// </para>
        /// </remarks>
        public static IHealthChecksBuilder AddDbContextCheck <TContext>(
            this IHealthChecksBuilder builder,
            string name = null,
            HealthStatus?failureStatus = default,
            IEnumerable <string> tags  = default,
            Func <TContext, CancellationToken, Task <bool> > customTestQuery = default)
            where TContext : DbContext
        {
            if (builder == null)
            {
                throw new ArgumentNullException(nameof(builder));
            }

            if (name == null)
            {
                name = typeof(TContext).Name;
            }

            if (customTestQuery != null)
            {
                builder.Services.Configure <DbContextHealthCheckOptions <TContext> >(name, options => options.CustomTestQuery = customTestQuery);
            }

            return(builder.AddCheck <DbContextHealthCheck <TContext> >(name, failureStatus, tags));
        }
Exemplo n.º 9
0
        /// <summary>
        ///  Add Machine Learning Health Check for ML.NET model.
        /// </summary>
        /// <typeparam name="TInput"></typeparam>
        /// <typeparam name="TPrediction"></typeparam>
        /// <param name="builder"></param>
        /// <param name="name"></param>
        /// <param name="configure"></param>
        /// <param name="failureStatus"></param>
        /// <param name="tags"></param>
        /// <returns></returns>
        public static IHealthChecksBuilder AddMachineLearningModelCheck <TInput, TPrediction>(
            this IHealthChecksBuilder builder,
            string name,
            Action <MachineLearningHealthCheckOptions <TInput> >?configure = null,
            HealthStatus?failureStatus = default,
            IEnumerable <string>?tags  = default)
            where TInput : class, new()
            where TPrediction : class, new()
        {
            if (tags == default)
            {
                tags = new[] { "machine_learning" };
            }

            builder.AddCheck <MachineLearningHealthCheck <TInput, TPrediction> >(name, failureStatus ?? HealthStatus.Unhealthy, tags);

            // Configure named options to pass the threshold into the check.
            builder.Services.Configure <MachineLearningHealthCheckOptions <TInput> >(
                name,
                options =>
            {
                configure?.Invoke(options);
            });

            return(builder);
        }
        public static IHealthChecksBuilder AddPerformanceCounter(this IHealthChecksBuilder builder, String WMIClassName, params string[] columns)
        {
            string columnsJoined = string.Join(", ", columns);

            builder.AddCheck($"PerformanceCounter for " + WMIClassName + " Columns " + columnsJoined, () =>
            {
                try
                {
                    IDictionary <string, Object> data = RunQueryforData("SELECT " + columnsJoined + " FROM " + WMIClassName);
                    data.Add("type", "PerformanceCounter");
                    data.Add("wmiClassName", WMIClassName);
                    data.Add("column", columnsJoined);
                    ReadOnlyDictionary <string, Object> rodata = new ReadOnlyDictionary <string, object>(data);
                    string description = $"PerformanceCounter for " + WMIClassName + " Columns " + columnsJoined;
                    return(HealthCheckResult.Healthy(description, rodata));
                }
                catch (PlatformNotSupportedException ex)
                {
                    return(HealthCheckResult.Degraded(ex.Message, ex, new Dictionary <string, object> {
                        { "type", "PerformanceCounter" }, { "wmiClassName", WMIClassName }, { "column", columnsJoined }
                    }));
                }
                catch (Exception ex)
                {
                    return(HealthCheckResult.Unhealthy(ex.Message, ex, new Dictionary <string, object> {
                        { "type", "PerformanceCounter" }, { "wmiClassName", WMIClassName }, { "column", columnsJoined }
                    }));
                }
            });
            return(builder);
        }
 public static IHealthChecksBuilder AddPerformanceCounter(this IHealthChecksBuilder builder, String WMIClassName, string Column)
 {
     builder.AddCheck($"PerformanceCounter for " + WMIClassName + " Column " + Column, () =>
     {
         try
         {
             IDictionary <string, Object> data = RunQueryforData("SELECT " + Column + " FROM " + WMIClassName); ////Win32_PerfRawData_PerfOS_Memory
             data.Add("type", "PerformanceCounter");
             data.Add("wmiClassName", WMIClassName);
             data.Add("column", Column);
             ReadOnlyDictionary <string, Object> rodata = new ReadOnlyDictionary <string, object>(data);
             string description = "PerformanceCounter for " + WMIClassName + " Column " + Column;
             return(HealthCheckResult.Healthy(description, rodata));
         }
         catch (PlatformNotSupportedException ex)
         {
             return(HealthCheckResult.Degraded(ex.Message, ex, new Dictionary <string, object> {
                 { "type", "PerformanceCounter" }, { "wmiClassName", WMIClassName }, { "column", Column }
             }));
         }
         catch (Exception ex)
         {
             return(HealthCheckResult.Unhealthy(ex.Message, ex, new Dictionary <string, object> {
                 { "type", "PerformanceCounter" }, { "wmiClassName", WMIClassName }, { "column", Column }
             }));
         }
     });
     return(builder);
 }
Exemplo n.º 12
0
        public static IHealthChecksBuilder AddOurChecks(this IHealthChecksBuilder healthChecksBuilder)
        {
            healthChecksBuilder
            .AddCheck("assembly", () => HealthCheckResult.Healthy())
            .AddCheck <VaultHealthCheck>("Vault");

            return(healthChecksBuilder);
        }
Exemplo n.º 13
0
        public static IHealthChecksBuilder AddFileWritePermissionsCheck(this IHealthChecksBuilder builder, string folderToTest)
        {
            var check = new VerifyWritePermissionsHealthCheck(folderToTest);

            builder.AddCheck("Check folder write permissions", check);

            return(builder);
        }
Exemplo n.º 14
0
 public static IHealthChecksBuilder AddBlobStorageHealthChecks(this IHealthChecksBuilder builder)
 {
     if (!builder.Services.Any(x => x.ServiceType == typeof(IBlobStorageFactory)))
     {
         throw new InvalidOperationException("You must register an implementation for IBlobStorageFactory before calling AddBlobStorageHealthChecks");                                                                           //we don't want to register one here because we don't know what implementation they might want to use
     }
     builder.AddCheck <BlobStorageHealthCheck>("BlobStorage");
     return(builder);
 }
Exemplo n.º 15
0
 public static IHealthChecksBuilder AddLivenessHealthCheck(
     this IHealthChecksBuilder builder,
     string name,
     HealthStatus?failureStatus,
     IEnumerable <string> tags) =>
 builder.AddCheck <LivenessHealthCheck>(
     name,
     failureStatus,
     tags);
Exemplo n.º 16
0
        public static IHealthChecksBuilder AddGenericHealthCheck <T>(
            this IHealthChecksBuilder builder,
            string name,
            HealthStatus?failureStatus = null,
            IEnumerable <string> tags  = null) where T : class, IHealthCheck
        {
            builder.AddCheck <T>(name, failureStatus ?? HealthStatus.Degraded, tags);

            return(builder);
        }
Exemplo n.º 17
0
        /// <summary>
        /// Add SIGTERM Healcheck that provides notification for orchestrator with unhealthy status once the application begins to shut down.
        /// </summary>
        /// <param name="builder">The <see cref="IHealthChecksBuilder"/>.</param>
        /// <param name="name">The name of the HealthCheck.</param>
        /// <param name="failureStatus">The <see cref="HealthStatus"/>The type should be reported when the health check fails. Optional. If <see langword="null"/> then.</param>
        /// <param name="tags">A list of tags that can be used to filter sets of health checks. Optional.</param>
        /// <returns></returns>
        public static IHealthChecksBuilder AddSigtermCheck(
            this IHealthChecksBuilder builder,
            string name,
            HealthStatus?failureStatus = null,
            IEnumerable <string>?tags  = default)
        {
            builder.AddCheck <SigtermHealthCheck>(name, failureStatus, tags);

            return(builder);
        }
        public static IHealthChecksBuilder AddMPassSamlHealthCheck(this IHealthChecksBuilder builder, string name, HealthStatus?failureStatus = default, IEnumerable <string> tags = default)
        {
            if (String.IsNullOrWhiteSpace(name))
            {
                throw new ArgumentException("Please provide a configuration name, such as MPassSamlDefaults.AuthenticationScheme", nameof(name));
            }

            builder.Services.TryAddSingleton <MPassSamlHealthCheck>();
            return(builder.AddCheck <MPassSamlHealthCheck>(name, failureStatus, tags));
        }
 public static IHealthChecksBuilder AddBrokerCheck(
     this IHealthChecksBuilder builder,
     string name,
     HealthStatus?failureStatus = null,
     IEnumerable <string> tags  = null,
     long?thresholdInBytes      = null)
 {
     builder.AddCheck <BrokerHealthCheck>(name, failureStatus ?? HealthStatus.Degraded, tags);
     return(builder);
 }
Exemplo n.º 20
0
 public static IHealthChecksBuilder AddReadinessHealthCheck(
     this IHealthChecksBuilder builder,
     string name,
     HealthStatus?failureStatus,
     IEnumerable <string> tags)
 {
     return(builder.AddCheck <ReadinessHealthCheck>(
                name,
                failureStatus,
                tags));
 }
Exemplo n.º 21
0
 public static IHealthChecksBuilder AddAzureServiceBusTopicHealthCheck(this IHealthChecksBuilder builder,
                                                                       string connectionString,
                                                                       string topicName,
                                                                       string name = default,
                                                                       HealthStatus failureStatus = HealthStatus.Degraded,
                                                                       IEnumerable <string> tags  = default,
                                                                       TimeSpan?timeout           = default)
 {
     return(builder.AddCheck(name ?? $"Azure Service Bus: {topicName}",
                             new AzureServiceBusHealthCheck(connectionString, topicName), failureStatus, tags, timeout));
 }
Exemplo n.º 22
0
        public static IHealthChecksBuilder AddGCInfoCheck(this IHealthChecksBuilder builder, string name, HealthStatus?failureStatus = null, IEnumerable <string> tags = null, long?thresholdInBytes = null)
        {
            builder.AddCheck <GCInfoHealthCheck>(name, failureStatus ?? HealthStatus.Degraded, tags);

            if (thresholdInBytes.HasValue)
            {
                builder.Services.Configure <GCInfoOptions>(name, options => options.Threshold = thresholdInBytes.Value);
            }

            return(builder);
        }
        /// <summary>
        /// Adds the Orleans HealthCheck with the Ready Tag.
        /// </summary>
        /// <param name="healthChecksBuilder">The <see cref="IHealthChecksBuilder" />.</param>
        /// <returns>The <see cref="IHealthChecksBuilder" />.</returns>
        public static IHealthChecksBuilder AddOrleansHealthCheck([NotNull] this IHealthChecksBuilder healthChecksBuilder)
        {
            if (healthChecksBuilder == null)
            {
                throw new ArgumentNullException(nameof(healthChecksBuilder));
            }

            return(healthChecksBuilder.AddCheck <OrleansHealthCheck>(HealthCheckName, HealthStatus.Unhealthy,
                                                                     new List <string> {
                Constants.ReadyTag
            }));
        }
Exemplo n.º 24
0
 public static IHealthChecksBuilder AddDateTimeHealthCheck(this IHealthChecksBuilder builder, string ntpserver, double toleratesec = 10, string name = "Date and  time health check")
 {
     return(builder.AddCheck(name, () =>
     {
         HealthCheckResult result;
         try
         {
             var dtx = new List <(int Id, DateTime webtime, DateTime locdateTime)>();
             for (int i = 0; i < 3; i++)
             {
                 var webtime1 = getWebTime(ntpserver);
                 dtx.Add((i, webtime1, DateTime.Now));
             }
Exemplo n.º 25
0
        /// <summary>
        /// Registers a check that validates that all Entity Framework migrations declared by the given context were executed on the server the app is connected to
        /// If any migration is missing, it will report it in the data dictionary
        /// </summary>
        /// <typeparam name="TContext"></typeparam>
        /// <param name="builder"></param>
        /// <param name="checkName"></param>
        /// <returns></returns>
        public static IHealthChecksBuilder AddEntityFrameworkMigrationsCheck <TContext>(this IHealthChecksBuilder builder, string checkName = null)
            where TContext : DbContext
        {
            // PendingMigrationsCheckerStorage is registered as a singleton, to provide persistent memory and remember whether last check was successful or not
            builder.Services.TryAddSingleton <IEntityFrameworkPendingMigrationsCheckerStorage <TContext>, EntityFrameworkPendingMigrationsCheckerStorage <TContext> >();

            // the scope created here will be disposed by the parent scope
            // todo fix when issue is resolved https://github.com/dotnet/aspnetcore/issues/14453
            builder.Services.TryAddScoped <IEntityFrameworkPendingMigrationsChecker <TContext> >(provider => new EntityFrameworkPendingMigrationsChecker <TContext>(provider.CreateScope().ServiceProvider.GetRequiredService <TContext>()));

            builder.AddCheck <EntityFrameworkMigrationsHealthCheck <TContext> >(checkName ?? $"{typeof(TContext).Name}MigrationsHealthCheck");

            return(builder);
        }
Exemplo n.º 26
0
        public static IHealthChecksBuilder AddMemoryHealthCheck(this IHealthChecksBuilder builder, string name, HealthStatus?failureStatus = null, IEnumerable <string> tags = null, long?thresholdInBytes = null)
        {
            builder.AddCheck <MemoryHealthCheck>(name, failureStatus ?? HealthStatus.Degraded, tags ?? new string[0]);

            if (thresholdInBytes.HasValue)
            {
                builder.Services.Configure <MemoryCheckOptions>(opts =>
                {
                    opts.Threshold = thresholdInBytes.Value;
                });
            }

            return(builder);
        }
        /// <summary>
        ///  Adds a new HealthCheck with the specified name and implementation.
        ///  Adds the Live Tag to the HealthCheck automatically.
        /// </summary>
        /// <typeparam name="T">The HealthCheck type.</typeparam>
        /// <param name="builder">The <see cref="IHealthChecksBuilder" />.</param>
        /// <param name="name">The HealthCheck name.</param>
        /// <param name="healthStatus">The <see cref="HealthStatus" /> that should be
        ///     reported when the HealthCheck reports a failure. If the provided value is null,
        ///     then <see cref="HealthStatus.Unhealthy" /> will
        ///     be reported.
        ///</param>
        /// <returns>The <see cref="IHealthChecksBuilder" />.</returns>
        public static IHealthChecksBuilder AddLiveCheck <T>([NotNull] this IHealthChecksBuilder builder,
                                                            [NotNull] string name, HealthStatus?healthStatus = null) where T : class, IHealthCheck
        {
            if (builder == null)
            {
                throw new ArgumentNullException(nameof(builder));
            }
            if (string.IsNullOrWhiteSpace(name))
            {
                throw new ArgumentException($"'{nameof(name)}' must not be null, empty or whitespace.", nameof(name));
            }

            return(builder.AddCheck <T>(name, healthStatus, new[] { Constants.LiveTag }));
        }
Exemplo n.º 28
0
        public MetricsBuilder RegisterAsHealthCheck <TMetric, TValue>(Func <IMetricsHost, TMetric> builderFunc,
                                                                      Func <TMetric, TValue> valueFunc, Func <TValue, bool> checkFunc,
                                                                      HealthStatus onCheckFailure = HealthStatus.Unhealthy) where TMetric : IMetric
        {
            // FIXME: throwaway host to resolve the name, which we need in advance for registration
            var name = builderFunc(new MetricsHost(new MemoryMetricsStore())).Name.Name;

            Services.AddSingleton(r => new MetricHealthCheck <TMetric, TValue>(name,
                                                                               r.GetRequiredService <IMetricsHost>(), builderFunc, valueFunc, checkFunc, onCheckFailure));
            _builder.Add(new HealthCheckRegistration(name,
                                                     r => r.GetRequiredService <MetricHealthCheck <TMetric, TValue> >(), onCheckFailure, null, null));
            _builder.AddCheck <MetricHealthCheck <TMetric, TValue> >($"health_check.{name}");
            return(this);
        }
Exemplo n.º 29
0
        /// <summary>
        ///     Add health check for integration with Promitor Resource Discovery
        /// </summary>
        /// <param name="healthChecksBuilder">Builder for adding health checks</param>
        /// <param name="configuration">Configuration of Promitor</param>
        /// <returns></returns>
        public static IHealthChecksBuilder AddResourceDiscoveryHealthCheck(this IHealthChecksBuilder healthChecksBuilder, IConfiguration configuration)
        {
            Guard.NotNull(healthChecksBuilder, nameof(healthChecksBuilder));
            Guard.NotNull(configuration, nameof(configuration));

            var resourceDiscoveryConfiguration = configuration.GetSection("resourceDiscovery").Get <ResourceDiscoveryConfiguration>();

            if (resourceDiscoveryConfiguration?.IsConfigured == true)
            {
                healthChecksBuilder.AddCheck <ResourceDiscoveryHealthCheck>("Promitor Resource Discovery", HealthStatus.Degraded);
            }

            return(healthChecksBuilder);
        }
        /// <summary>
        ///  Add Machine Learning Health Check for ML.NET model.
        /// </summary>
        /// <typeparam name="TInput"></typeparam>
        /// <typeparam name="TPrediction"></typeparam>
        /// <param name="builder"></param>
        /// <param name="name"></param>
        /// <param name="failureStatus"></param>
        /// <param name="tags"></param>
        /// <returns></returns>
        public static IHealthChecksBuilder AddMachineLearningModelCheck <TInput, TPrediction>(
            this IHealthChecksBuilder builder,
            string name,
            HealthStatus?failureStatus = default,
            IEnumerable <string>?tags  = default) where TInput : class, new() where TPrediction : class, new()
        {
            if (tags == default)
            {
                tags = new[] { "machine_learning" };
            }

            builder.AddCheck <MachineLearningHealthCheck <TInput, TPrediction> >(name, failureStatus ?? HealthStatus.Unhealthy, tags);

            return(builder);
        }