public static IHealthChecksBuilder AddApplicationInsightsPublisher(this IHealthChecksBuilder builder, Action <ApplicationInsightsHealthCheckPublisherOptions>?configure = null)
        {
            _ = builder ?? throw new ArgumentNullException(nameof(builder));
            builder.Services.AddOptions <ApplicationInsightsHealthCheckPublisherOptions>()
            .Configure(options =>
            {
                var websiteSiteName = Environment.GetEnvironmentVariable("WEBSITE_SITE_NAME");
                var websiteSlotName = Environment.GetEnvironmentVariable("WEBSITE_SLOT_NAME");

                options.RunLocation     = string.IsNullOrEmpty(websiteSiteName) ? Environment.MachineName : websiteSiteName;
                options.ApplicationName = Assembly.GetEntryAssembly()?.GetName().Name ?? string.Empty;
                options.EnvironmentName = string.IsNullOrEmpty(websiteSlotName) ? Environment.MachineName : websiteSlotName;
            })
            .Configure <IConfiguration>((options, configuration) => configuration.GetSection(nameof(ApplicationInsightsHealthCheckPublisher)).Bind(options))
            .Configure(options => configure?.Invoke(options));
            builder.Services.AddSingleton <IHealthCheckPublisher, ApplicationInsightsHealthCheckPublisher>();
            return(builder);
        }
        /// <summary>
        /// Enables multiple existing health checks to be evaluated only when a specific condition occurs,
        /// that is described by a type implementing <see cref="IConditionalHealthCheckPolicy"/>
        /// and which will be executed on every health check request.
        /// </summary>
        /// <remarks>
        /// The health check policy instance is provided by a function that receives as input <see cref="IServiceProvider"/>, <see cref="HealthCheckContext"/> and a <see cref="CancellationToken"/>
        /// and it returns a <see cref="Task"/> representing the asynchronous operation that returns the health check policy instance.
        /// </remarks>
        /// <typeparam name="T">The type implementing <see cref="IConditionalHealthCheckPolicy"/>.</typeparam>
        /// <param name="builder">The builder used to register health checks.</param>
        /// <param name="names">
        /// The list of names of the existing health checks, ie. "Redis", "redis", "S3", "My Health Check".
        /// The health checks must be previously registered using the other <see cref="IHealthChecksBuilder" /> extensions, like AddRedis, AddRabbitMQ, AddCheck, etc.
        /// You can use the static <see cref="Registrations"/> class that contains a list of well-known names,
        /// otherwise specify the name of the previously added health check.
        /// </param>
        /// <param name="policyProvider">The function that returns the instance based on which the health check execution is decided to run on not.</param>
        /// <param name="options">A list of options to override the default behavior. See <see cref="ConditionalHealthCheckOptions"/> for extra details.</param>
        /// <returns>The same builder used to register health checks.</returns>
        /// <exception cref="ArgumentException">When the name of the health check is not provided, ie. is null or is an empty string.</exception>
        /// <exception cref="InvalidOperationException">When the health check identified by the previously given name is not registered yet.</exception>
        public static IHealthChecksBuilder CheckOnlyWhen <T>(this IHealthChecksBuilder builder,
                                                             string[] names,
                                                             Func <IServiceProvider, HealthCheckContext, CancellationToken, Task <T> > policyProvider,
                                                             ConditionalHealthCheckOptions?options = null)
            where T : IConditionalHealthCheckPolicy
        {
            if (names == null || names.Length == 0)
            {
                throw new ArgumentException("The health checks names cannot be null or an empty array.", nameof(names));
            }

            foreach (var name in names)
            {
                builder.CheckOnlyWhen(name, policyProvider, options);
            }

            return(builder);
        }
コード例 #3
0
        public void Setup()
        {
            var healthcheckbuildermock = new Moq.Mock <IHealthChecksBuilder>();

            healthcheckbuildermock
            .Setup(m => m.Services)
            .Returns(new ServiceCollection());
            healthChecksBuilder = healthcheckbuildermock.Object;

            httpendpointhealthcheck = new ServiceHealthCheck()
            {
                Name = "testhealthcheck",
                HealthCheckConditions = new HealthCheckConditions()
                {
                    HttpBehaviour = new HttpBehaviour()
                    {
                        HttpExpectedCode = 200,
                        HttpVerb         = HttpVerb.Get
                    },
                },
                AlertBehaviour = new List <AlertBehaviour>()
                {
                    new AlertBehaviour()
                    {
                        AlertEvery = TimeSpan.FromSeconds(5),
                        AlertOnServiceRecovered = true,
                        TransportName           = "Dummy",
                        TransportMethod         = AlertTransportMethod.Email
                    }
                },
                EndpointOrHost     = "https://www.google.com",
                MonitoringInterval = TimeSpan.FromSeconds(1),
                ServiceType        = ServiceType.Http,
                Alert = true
            };

            alertTransportSettings = new DictionaryTransportSettings()
            {
                Name = "Dummy",
            };

            alertPublisher =
                new DictionaryPublisher(healthChecksBuilder, httpendpointhealthcheck, alertTransportSettings);
        }
コード例 #4
0
        internal static void AddCustomHealthChecks(this IServiceCollection services, WebApiConfiguration webApiConfiguration, AuthorityConfiguration authorityConfiguration, WebApiScopesConfiguration webApiScopesConfiguration, LDAPServerProfiles ldapServerProfiles)
        {
            Log.Information("{method}", nameof(AddCustomHealthChecks));

            if (!webApiConfiguration.HealthChecksConfiguration.EnableHealthChecks)
            {
                return;
            }

            IHealthChecksBuilder healthChecksBuilder = services.AddHealthChecks();

            if (!webApiScopesConfiguration.BypassApiScopesAuthorization)
            {
                healthChecksBuilder = healthChecksBuilder.AddUrlGroup(new Uri(authorityConfiguration.Authority), name: "OAuth/OpenId Server", tags: new string[] { authorityConfiguration.Authority });
            }

            foreach (var lp in ldapServerProfiles)
            {
                var portLc = lp.GetPort(false);
                var portGc = lp.GetPort(true);

                healthChecksBuilder = healthChecksBuilder.AddTcpHealthCheck(options =>
                {
                    options.AddHost(lp.Server, portLc);
                }, name: $"Connection: {lp.Server}:{portLc}", tags: new string[] { lp.ProfileId, lp.DefaultDomainName, $"SSL:{lp.UseSSL}" });

                healthChecksBuilder = healthChecksBuilder.AddTcpHealthCheck(options =>
                {
                    options.AddHost(lp.Server, portGc);
                }, name: $"Connection: {lp.Server}:{portGc}", tags: new string[] { lp.ProfileId, lp.DefaultDomainName, $"SSL:{lp.UseSSL}" });

                healthChecksBuilder = healthChecksBuilder.AddPingHealthCheck(options => options.AddHost(lp.Server, lp.HealthCheckPingTimeout), $"Ping: {lp.Server}", tags: new string[] { lp.ProfileId, lp.DefaultDomainName, $"SSL:{lp.UseSSL}" });
            }

            services.AddHealthChecksUI(settings =>
            {
                settings
                .SetHeaderText(webApiConfiguration.HealthChecksConfiguration.HealthChecksHeaderText)
                .SetEvaluationTimeInSeconds(webApiConfiguration.HealthChecksConfiguration.EvaluationTime)
                .MaximumHistoryEntriesPerEndpoint(webApiConfiguration.HealthChecksConfiguration.MaximunHistoryEntries)
                .AddHealthCheckEndpoint(webApiConfiguration.HealthChecksConfiguration.HealthChecksGroupName, $"{webApiConfiguration.WebApiBaseUrl}/{webApiConfiguration.HealthChecksConfiguration.ApiEndPointName}");
            })
            .AddInMemoryStorage();
        }
        /// <summary>
        /// Add a health check for single uri.
        /// </summary>
        /// <param name="builder">The <see cref="IHealthChecksBuilder"/>.</param>
        /// <param name="uri">The uri to check.</param>
        /// <param name="name">The health check name. Optional. If <c>null</c> the type name 'uri-group' will be used for the name.</param>
        /// <param name="failureStatus">
        /// The <see cref="HealthStatus"/> that should be reported when the health check fails. Optional. If <c>null</c> then
        /// the default status of <see cref="HealthStatus.Unhealthy"/> will be reported.
        /// </param>
        /// <param name="tags">A list of tags that can be used to filter sets of health checks. Optional.</param>
        /// <param name="timeout">An optional System.TimeSpan representing the timeout of the check.</param>
        /// <returns>The <see cref="IHealthChecksBuilder"/>.</returns></param>
        public static IHealthChecksBuilder AddUrlGroup(this IHealthChecksBuilder builder, Uri uri, string name = default, HealthStatus?failureStatus = default, IEnumerable <string> tags = default, TimeSpan?timeout = default)
        {
            builder.Services.AddHttpClient();

            var registrationName = name ?? NAME;

            return(builder.Add(new HealthCheckRegistration(
                                   registrationName,
                                   sp =>
            {
                var options = new UriHealthCheckOptions()
                              .AddUri(uri);

                return CreateHealthCheck(sp, registrationName, options);
            },
                                   failureStatus,
                                   tags,
                                   timeout)));
        }
コード例 #6
0
        public static IHealthChecksBuilder AddMemoryHealthCheck(
            this IHealthChecksBuilder builder,
            string name,
            HealthStatus?failureStatus = null,
            IEnumerable <string> tags  = null,
            long?thresholdInBytes      = null)
        {
            // Register a check of type GCInfo.
            _ = builder.AddCheck <MemoryHealthCheck>(
                name, failureStatus ?? HealthStatus.Degraded, tags);

            // Configure named options to pass the threshold into the check.
            if (thresholdInBytes.HasValue)
            {
                _ = builder.Services.Configure <MemoryCheckOptions>(name, options => options.Threshold = thresholdInBytes.Value);
            }

            return(builder);
        }
コード例 #7
0
        /// <summary>
        /// Add a health check that reports worker heartbeats
        /// </summary>
        /// <param name="builder"></param>
        /// <param name="configure"></param>
        /// <param name="name">The health check name. Optional. If <c>null</c> the type name 'worker_heartbeat' will be used for the name.</param>
        /// <param name="tags">A list of tags that can be used to filter sets of health checks. Optional.</param>
        /// <param name="timeout">An optional System.TimeSpan representing the timeout of the check.</param>
        /// <returns></returns>
        public static IHealthChecksBuilder AddWorkerHeartbeats(this IHealthChecksBuilder builder,
                                                               Action <HeartbeatHealthCheckOptions> configure = null,
                                                               string name = default,
                                                               IEnumerable <string> tags = default,
                                                               TimeSpan?timeout          = default)
        {
            builder.Services.AddSingleton <HeartbeatHealthCheck>();
            builder.Services.AddSingleton <IHeartbeatMonitor, HeartbeatMonitor>();
            builder.Services.AddOptions <HeartbeatHealthCheckOptions>().Configure(configure ?? DefaultHeartbeatConfig);

            builder.Add(new HealthCheckRegistration(
                            name ?? HEARTBEAT_NAME,
                            sp => sp.GetRequiredService <HeartbeatHealthCheck>(),
                            HealthStatus.Degraded,
                            tags,
                            timeout));

            return(builder);
        }
コード例 #8
0
        /// <summary>
        /// Adds a new health check with the specified name and implementation.
        /// </summary>
        /// <typeparam name="T">The health check implementation type.</typeparam>
        /// <param name="builder">The <see cref="IHealthChecksBuilder"/>.</param>
        /// <param name="name">The name of the health check.</param>
        /// <param name="failureStatus">
        /// The <see cref="HealthStatus"/> that should be reported when the health check reports a failure. If the provided value
        /// is <c>null</c>, then <see cref="HealthStatus.Unhealthy"/> will be reported.
        /// </param>
        /// <param name="tags">A list of tags that can be used to filter health checks.</param>
        /// <param name="timeout">An optional <see cref="TimeSpan"/> representing the timeout of the check.</param>
        /// <returns>The <see cref="IHealthChecksBuilder"/>.</returns>
        /// <remarks>
        /// This method will use <see cref="ActivatorUtilities.GetServiceOrCreateInstance{T}(IServiceProvider)"/> to create the health check
        /// instance when needed. If a service of type <typeparamref name="T"/> is registered in the dependency injection container
        /// with any lifetime it will be used. Otherwise an instance of type <typeparamref name="T"/> will be constructed with
        /// access to services from the dependency injection container.
        /// </remarks>
        public static IHealthChecksBuilder AddCheck <T>(
            this IHealthChecksBuilder builder,
            string name,
            HealthStatus?failureStatus = null,
            IEnumerable <string> tags  = null,
            TimeSpan?timeout           = null) where T : class, IHealthCheck
        {
            if (builder == null)
            {
                throw new ArgumentNullException(nameof(builder));
            }

            if (name == null)
            {
                throw new ArgumentNullException(nameof(name));
            }

            return(builder.Add(new HealthCheckRegistration(name, s => ActivatorUtilities.GetServiceOrCreateInstance <T>(s), failureStatus, tags, timeout)));
        }
        /// <summary>
        /// Add a health check for multiple uri's.
        /// </summary>
        /// <param name="builder">The <see cref="IHealthChecksBuilder"/>.</param>
        /// <param name="uris">The collection of uri's to be checked.</param>
        /// <param name="httpMethod">The http method to be used.</param>
        /// <param name="name">The health check name. Optional. If <c>null</c> the type name 'uri-group' 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>
        public static IHealthChecksBuilder AddUrlGroup(this IHealthChecksBuilder builder, IEnumerable <Uri> uris, HttpMethod httpMethod, string name = default, HealthStatus?failureStatus = default, IEnumerable <string> tags = default)
        {
            builder.Services.AddHttpClient();

            var registrationName = name ?? NAME;

            return(builder.Add(new HealthCheckRegistration(
                                   registrationName,
                                   sp =>
            {
                var options = UriHealthCheckOptions
                              .CreateFromUris(uris)
                              .UseHttpMethod(httpMethod);

                return CreateHealthCheck(sp, registrationName, options);
            },
                                   failureStatus,
                                   tags)));
        }
コード例 #10
0
        public static IHealthChecksBuilder AddNetworkHealthCheck(
            this IHealthChecksBuilder builder,
            string name,
            HealthStatus?failureStatus = null,
            IEnumerable <string> tags  = null,
            int?latencyInMseconds      = null)
        {
            builder.AddCheck <NetworkHealthCheck>(name, failureStatus ?? HealthStatus.Degraded, tags);

            if (latencyInMseconds.HasValue)
            {
                builder.Services.Configure <NetworkCheckOptions>(name, options =>
                {
                    options.MaxLatencyThreshold = latencyInMseconds.Value;
                });
            }

            return(builder);
        }
コード例 #11
0
        public static IHealthChecksBuilder AddGCCheck(
            this IHealthChecksBuilder builder,
            string name,
            HealthStatus?failureStatus = null,
            IEnumerable <string> tags  = null,
            long?thresholdInBytes      = null)
        {
            builder.AddCheck <GCHealthCheck>(name, failureStatus ?? HealthStatus.Degraded, tags);

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

            return(builder);
        }
コード例 #12
0
        private static void RegisterOptions(
            IHealthChecksBuilder builder,
            string name,
            Action <StorageAccountOptions> setup)
        {
            var options = new StorageAccountOptions();

            setup?.Invoke(options);

            builder.Services.ConfigureOptions <StorageAccountOptionsSetup>();

            builder.Services.AddOptions <StorageAccountOptions>(name)
            .Configure((opt) =>
            {
                opt.ConnectionString = options.ConnectionString;
                opt.Name             = options.Name;
                opt.Token            = options.Token;
            });
        }
コード例 #13
0
 /// <summary>
 /// Add a health check for specified Azure Digital Twin existing models.
 /// </summary>
 /// <param name="builder">The <see cref="IHealthChecksBuilder"/>.</param>
 /// <param name="clientId">The azure digital twin client id.</param>
 /// <param name="clientSecret">The azure digital twin client secret.</param>
 /// <param name="tenantId">The azure digital twin tenant id.</param>
 /// <param name="hostName">The azure digital host uri.</param>
 /// <param name="models">The azure digital twin model collection expected.</param>
 /// <param name="name">The health check name. Optional. If <c>null</c> the type name 'azureeventhub' will be used for the name.</param>
 /// <param name="failureStatus">
 /// The <see cref="HealthStatus"/> that should be reported when the health check fails. Optional. If <c>null</c> then
 /// the default status of <see cref="HealthStatus.Unhealthy"/> will be reported.
 /// </param>
 /// <param name="tags">A list of tags that can be used to filter sets of health checks. Optional.</param>
 /// <param name="timeout">An optional System.TimeSpan representing the timeout of the check.</param>
 /// <returns>The <see cref="IHealthChecksBuilder"/>.</returns>
 public static IHealthChecksBuilder AddAzureDigitalTwinModels(
     this IHealthChecksBuilder builder,
     string clientId,
     string clientSecret,
     string tenantId,
     string hostName,
     string[] models,
     string?name = default,
     HealthStatus?failureStatus = default,
     IEnumerable <string>?tags  = default,
     TimeSpan?timeout           = default)
 {
     return(builder.Add(new HealthCheckRegistration(
                            name ?? AZUREDIGITALTWINMODELS_NAME,
                            sp => new AzureDigitalTwinModelsHealthCheck(clientId, clientSecret, tenantId, hostName, models),
                            failureStatus,
                            tags,
                            timeout)));
 }
コード例 #14
0
        public static IServiceCollection AddCustomInfrastructure(this IServiceCollection services,
                                                                 IConfiguration configuration,
                                                                 IHealthChecksBuilder healthChecksBuilder)
        {
            services
            .AddEfCore <ProductCatalogDbContext>(healthChecksBuilder, configuration, Assembly.GetExecutingAssembly())
            .AddAutoMapper(Assembly.GetExecutingAssembly())
            .AddMediatR(Assembly.GetExecutingAssembly())
            .AddValidatorsFromAssembly(Assembly.GetExecutingAssembly())
            .AddCustomRequestValidation()
            .AddDomainEventDispatcher()
            .AddCustomDapr();

            services
            .AddTransient <DaprProductCreatedPublisher>()
            .AddTransient <DaprInventoriesGateway>();

            return(services);
        }
コード例 #15
0
 /// <summary>
 /// Add a health check for IbmMQ services using a managed connection.
 /// </summary>
 /// <param name="builder">The <see cref="IHealthChecksBuilder"/>.</param>
 /// <param name="queueManager">The name of the queue manager to use.</param>
 /// <param name="channel">The name of the channel.</param>
 /// <param name="connectionInfo">The connection information in the following format HOSTNAME(PORT).</param>
 /// <param name="userName">The user name. Optional.</param>
 /// <param name="password">The password. Optional</param>
 /// <param name="name">The health check name. Optional. If <c>null</c> the type name 'ibmmq' will be used for the name.</param>
 /// <param name="failureStatus">
 /// The <see cref="HealthStatus"/> that should be reported when the health check fails. Optional. If <c>null</c> then
 /// the default status of <see cref="HealthStatus.Unhealthy"/> will be reported.
 /// </param>
 /// <param name="tags">A list of tags that can be used to filter sets of health checks. Optional.</param>
 /// <param name="timeout">An optional <see cref="TimeSpan"/> representing the timeout of the check.</param>
 /// <returns>The specified <paramref name="builder"/>.</returns>
 public static IHealthChecksBuilder AddIbmMQManagedConnection(
     this IHealthChecksBuilder builder,
     string queueManager,
     string channel,
     string connectionInfo,
     string?userName            = null,
     string?password            = null,
     string?name                = default,
     HealthStatus?failureStatus = default,
     IEnumerable <string>?tags  = default,
     TimeSpan?timeout           = default)
 {
     return(builder.Add(new HealthCheckRegistration(
                            name ?? NAME,
                            new IbmMQHealthCheck(queueManager, BuildProperties(channel, connectionInfo, userName, password)),
                            failureStatus,
                            tags,
                            timeout)));
 }
        /// <summary>
        /// Add a health check for Elasticsearch databases.
        /// </summary>
        /// <param name="builder">The <see cref="IHealthChecksBuilder"/>.</param>
        /// <param name="elasticsearchUri">The Elasticsearch connection string to be used.</param>
        /// <param name="name">The health check name. Optional. If <c>null</c> the type name 'elasticsearch' will be used for the name.</param>
        /// <param name="failureStatus">
        /// The <see cref="HealthStatus"/> that should be reported when the health check fails. Optional. If <c>null</c> then
        /// the default status of <see cref="HealthStatus.Unhealthy"/> will be reported.
        /// </param>
        /// <param name="tags">A list of tags that can be used to filter sets of health checks. Optional.</param>
        /// <param name="timeout">An optional <see cref="TimeSpan"/> representing the timeout of the check.</param>
        /// <returns>The specified <paramref name="builder"/>.</returns>
        public static IHealthChecksBuilder AddElasticsearch(
            this IHealthChecksBuilder builder,
            string elasticsearchUri,
            string?name = default,
            HealthStatus?failureStatus = default,
            IEnumerable <string>?tags  = default,
            TimeSpan?timeout           = default)
        {
            var options = new ElasticsearchOptions();

            options.UseServer(elasticsearchUri);

            return(builder.Add(new HealthCheckRegistration(
                                   name ?? NAME,
                                   sp => new ElasticsearchHealthCheck(options),
                                   failureStatus,
                                   tags,
                                   timeout)));
        }
コード例 #17
0
        public static IHealthChecksBuilder AddApiEndpointHealthChecks(this IHealthChecksBuilder builder, ApiHealthConfiguration configuration)
        {
            if (configuration.Enabled)
            {
                foreach (var endpoint in configuration.Endpoints)
                {
                    var name          = endpoint.Name;
                    var uri           = endpoint.Uri;
                    var tags          = endpoint.Tags;
                    var failureStatus = (HealthStatus)Enum.Parse(typeof(HealthStatus), endpoint.FailureStatus, true);
                    var httpMethod    = new HttpMethod(endpoint.HttpMethod.ToUpper());

                    builder.AddUrlGroup(new Uri(uri), name: name, tags: tags,
                                        httpMethod: httpMethod, failureStatus: failureStatus);
                }
            }

            return(builder);
        }
        /// <summary>
        /// Add a Healthcheck to resolve a hostname and verify the number of resolved address is within the configured minimum and maximum
        /// </summary>
        /// <remarks>
        /// Add host configurations using setup.ResolveHost(host).To(registrations);
        /// </remarks>
        /// <param name="builder">The <see cref="IHealthChecksBuilder"/>.</param>
        /// <param name="setup">Action to add hosts and configure minimum and maximum resolved addresses</param>
        /// <param name="name">The health check name. Optional. If <c>null</c> the type name 'dns' 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>
        /// <returns>The <see cref="IHealthChecksBuilder"/>.</returns>
        public static IHealthChecksBuilder AddDnsResolveHostCountHealthCheck(this IHealthChecksBuilder builder,
                                                                             Action <DnsResolveCountOptions> setup, string name = default, HealthStatus?failureStatus = default,
                                                                             IEnumerable <string> tags = default)
        {
            var options = new DnsResolveCountOptions();

            setup?.Invoke(options);

            if (!options.HostRegistrations.Any())
            {
                throw new ArgumentNullException(nameof(options), "No dns hosts have been registered");
            }

            return(builder.Add(new HealthCheckRegistration(
                                   name ?? DNS_COUNT_NAME,
                                   sp => new DnsResolveHostCountHealthCheck(options),
                                   failureStatus,
                                   tags)));
        }
コード例 #19
0
        ///  <summary>
        ///   Adds a new Cached HealthCheck with the specified name and implementation.
        ///  </summary>
        ///  <param name="builder">The <see cref="IHealthChecksBuilder" />.</param>
        ///  <param name="name">The HealthCheck name.</param>
        /// <param name="instance">An <see cref="IHealthCheck"/> instance.</param>
        /// <param name="failureStatus">
        /// The <see cref="HealthStatus"/> that should be reported when the health check reports a failure. If the provided value
        /// is <c>null</c>, then <see cref="HealthStatus.Unhealthy"/> will be reported.
        /// </param>
        /// <param name="tags">A list of tags that can be used to filter health checks.</param>
        /// <param name="cacheExpirationMs">The Expiration of the Cache in milliseconds.</param>
        ///  <returns>The <see cref="IHealthChecksBuilder"/>.</returns>
        public static IHealthChecksBuilder AddCachedCheck([NotNull] this IHealthChecksBuilder builder,
                                                          [NotNull] string name, [NotNull] IHealthCheck instance, HealthStatus?failureStatus = null,
                                                          IEnumerable <string> tags = null, ulong cacheExpirationMs = CachedHealthCheck.DefaultCacheExpirationMs)
        {
            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));
            }
            if (instance == null)
            {
                throw new ArgumentNullException(nameof(instance));
            }

            return(AddCachedCheck(builder, name, _ => instance, failureStatus, tags, cacheExpirationMs));
        }
コード例 #20
0
        private static IHealthChecksBuilder AddSignalRCheck(this IHealthChecksBuilder builder, IConfiguration configuration)
        {
            var baseUri = ConfigurationHandler.GetBaseUri(configuration);

            if (baseUri == null)
            {
                logger.Warn("SignalR Check: No valid BaseUrl found. Skipping check.");
                return(builder);
            }

            string absoluteUri = baseUri.AbsoluteUri;

            if (!absoluteUri.EndsWith("/"))
            {
                absoluteUri += "/";
            }

            return(builder.AddSignalRHub($"{absoluteUri}hub"));
        }
コード例 #21
0
        /// <summary>
        /// Adds a new type activated health check with the specified name and implementation.
        /// </summary>
        /// <typeparam name="T">The health check implementation type.</typeparam>
        /// <param name="builder">The <see cref="IHealthChecksBuilder"/>.</param>
        /// <param name="name">The name of the health check.</param>
        /// <param name="failureStatus">
        /// The <see cref="HealthStatus"/> that should be reported when the health check reports a failure. If the provided value
        /// is <c>null</c>, then <see cref="HealthStatus.Unhealthy"/> will be reported.
        /// </param>
        /// <param name="tags">A list of tags that can be used to filter health checks.</param>
        /// <param name="args">Additional arguments to provide to the constructor.</param>
        /// <returns>The <see cref="IHealthChecksBuilder"/>.</returns>
        /// <remarks>
        /// This method will use <see cref="ActivatorUtilities.CreateInstance{T}(IServiceProvider, object[])"/> to create the health check
        /// instance when needed. Additional arguments can be provided to the constructor via <paramref name="args"/>.
        /// </remarks>
        public static IHealthChecksBuilder AddTypeActivatedCheck <T>(
            this IHealthChecksBuilder builder,
            string name,
            HealthStatus?failureStatus,
            IEnumerable <string> tags,
            params object[] args) where T : class, IHealthCheck
        {
            if (builder == null)
            {
                throw new ArgumentNullException(nameof(builder));
            }

            if (name == null)
            {
                throw new ArgumentNullException(nameof(name));
            }

            return(builder.Add(new HealthCheckRegistration(name, s => ActivatorUtilities.CreateInstance <T>(s, args), failureStatus, tags)));
        }
コード例 #22
0
        private static IHealthChecksBuilder AddImapHealthCheck(this IHealthChecksBuilder builder, IConfiguration configuration)
        {
            var imapSettings = ConfigurationHandler.GetImapSettings(configuration);

            if (string.IsNullOrWhiteSpace(imapSettings.Host))
            {
                logger.Info("IMAP Check: No valid Host found. Skipping check.");
                return(builder);
            }

            return(builder.AddImapHealthCheck(setup =>
            {
                setup.Host = imapSettings.Host;
                setup.Port = imapSettings.Port.GetValueOrDefault();
                setup.AllowInvalidRemoteCertificates = true;
                setup.ConnectionType = imapSettings.EnableSsl.Value == true ? ImapConnectionType.SSL_TLS : ImapConnectionType.AUTO;
                setup.LoginWith(imapSettings.Username, imapSettings.Password);
            }));
        }
コード例 #23
0
        /// <summary>
        /// Add a health check for RabbitMQ services using connection string (amqp uri).
        /// </summary>
        /// <param name="builder">The <see cref="IHealthChecksBuilder"/>.</param>
        /// <param name="rabbitConnectionString">The RabbitMQ connection string to be used.</param>
        /// <param name="sslOption">The RabbitMQ ssl options. Optional. If <c>null</c>, the ssl option will counted as disabled and not used.</param>
        /// <param name="name">The health check name. Optional. If <c>null</c> the type name 'rabbitmq' will be used for the name.</param>
        /// <param name="failureStatus">
        /// The <see cref="HealthStatus"/> that should be reported when the health check fails. Optional. If <c>null</c> then
        /// the default status of <see cref="HealthStatus.Unhealthy"/> will be reported.
        /// </param>
        /// <param name="tags">A list of tags that can be used to filter sets of health checks. Optional.</param>
        /// <param name="timeout">An optional <see cref="TimeSpan"/> representing the timeout of the check.</param>
        /// <returns>The specified <paramref name="builder"/>.</returns>
        public static IHealthChecksBuilder AddRabbitMQ(
            this IHealthChecksBuilder builder,
            Uri rabbitConnectionString,
            SslOption?sslOption        = default,
            string?name                = default,
            HealthStatus?failureStatus = default,
            IEnumerable <string>?tags  = default,
            TimeSpan?timeout           = default)
        {
            builder.Services
            .AddSingleton(sp => new RabbitMQHealthCheck(rabbitConnectionString, sslOption));

            return(builder.Add(new HealthCheckRegistration(
                                   name ?? NAME,
                                   sp => sp.GetRequiredService <RabbitMQHealthCheck>(),
                                   failureStatus,
                                   tags,
                                   timeout)));
        }
コード例 #24
0
        /// <summary>
        /// Adds a new health check with the specified name and implementation.
        /// </summary>
        /// <param name="builder">The <see cref="IHealthChecksBuilder"/> to add the check to.</param>
        /// <param name="name">The name of the health check, which should indicate the component being checked.</param>
        /// <param name="check">A delegate which provides the code to execute when the health check is run.</param>
        /// <returns>The <see cref="IHealthChecksBuilder"/>.</returns>
        public static IHealthChecksBuilder AddCheck(this IHealthChecksBuilder builder, string name, Func <Task <HealthCheckResult> > check)
        {
            if (builder == null)
            {
                throw new ArgumentNullException(nameof(builder));
            }

            if (name == null)
            {
                throw new ArgumentNullException(nameof(name));
            }

            if (check == null)
            {
                throw new ArgumentNullException(nameof(check));
            }

            return(builder.AddCheck(name, _ => check()));
        }
コード例 #25
0
        /// <summary>
        /// Add a health check for Identity Server.
        /// </summary>
        /// <param name="builder">The <see cref="IHealthChecksBuilder"/>.</param>
        /// <param name="idSvrUri">The uri of the Identity Server to check.</param>
        /// <param name="name">The health check name. Optional. If <c>null</c> the type name 'idsvr' will be used for the name.</param>
        /// <param name="failureStatus">
        /// The <see cref="HealthStatus"/> that should be reported when the health check fails. Optional. If <c>null</c> then
        /// the default status of <see cref="HealthStatus.Unhealthy"/> will be reported.
        /// </param>
        /// <param name="tags">A list of tags that can be used to filter sets of health checks. Optional.</param>
        /// <param name="timeout">An optional <see cref="TimeSpan"/> representing the timeout of the check.</param>
        /// <returns>The specified <paramref name="builder"/>.</returns>
        public static IHealthChecksBuilder AddIdentityServer(
            this IHealthChecksBuilder builder,
            Uri idSvrUri,
            string?name = default,
            HealthStatus?failureStatus = default,
            IEnumerable <string>?tags  = default,
            TimeSpan?timeout           = default)
        {
            var registrationName = name ?? NAME;

            builder.Services.AddHttpClient(registrationName, client => client.BaseAddress = idSvrUri);

            return(builder.Add(new HealthCheckRegistration(
                                   registrationName,
                                   sp => new IdSvrHealthCheck(() => sp.GetRequiredService <IHttpClientFactory>().CreateClient(registrationName)),
                                   failureStatus,
                                   tags,
                                   timeout)));
        }
        /// <summary>
        /// Adds Azure Storage Health Check.
        /// </summary>
        /// <param name="builder">The hc builder.</param>
        /// <param name="name">The name of the hc.</param>
        /// <param name="containerName">The name of the container to be checked.</param>
        /// <param name="setup">The setup action for the hc.</param>
        /// <param name="sectionName">
        /// The name of the configuration section for Azure Storage Account.
        /// Example: AzureStorage:DefaultAccount
        /// The default is <see cref="AzureStorageConstants.DefaultAccount"/>.
        /// </param>
        /// <param name="rootSectionName">
        /// The root section name for Azure Storage Account.
        /// Example: AzureStorage:DefaultAccount
        /// The default is <see cref="AzureStorageConstants.AzureStorage"/>.
        /// </param>
        /// <param name="failureStatus">The failure status to be returned. The default is 'HealthStatus.Degraded'.</param>
        /// <param name="tags">The optional tags.</param>
        /// <returns></returns>
        public static IHealthChecksBuilder AddAzureBlobStorageCheck(
            this IHealthChecksBuilder builder,
            string name,
            string containerName,
            Action <StorageAccountOptions>?setup = null,
            string sectionName         = AzureStorageConstants.DefaultAccount,
            string rootSectionName     = AzureStorageConstants.AzureStorage,
            HealthStatus?failureStatus = default,
            IEnumerable <string>?tags  = default)
        {
            // register azure storage account with the container to be monitored.
            builder.Services
            .AddAzureStorageAccount(name, sectionName, rootSectionName, setup)
            .AddAzureBlobContainer(name, containerName);

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

            return(builder);
        }
コード例 #27
0
        /// <summary>
        /// Add a health check for disk storage.
        /// </summary>
        /// <param name="builder">The <see cref="IHealthChecksBuilder"/>.</param>
        /// <param name="setup">The action method to configure the health check parameters.</param>
        /// <param name="name">The health check name. Optional. If <c>null</c> the type name 'diskstorage' will be used for the name.</param>
        /// <param name="failureStatus">
        /// The <see cref="HealthStatus"/> that should be reported when the health check fails. Optional. If <c>null</c> then
        /// the default status of <see cref="HealthStatus.Unhealthy"/> will be reported.
        /// </param>
        /// <param name="tags">A list of tags that can be used to filter sets of health checks. Optional.</param>
        /// <param name="timeout">An optional <see cref="TimeSpan"/> representing the timeout of the check.</param>
        /// <returns>The specified <paramref name="builder"/>.</returns>
        public static IHealthChecksBuilder AddDiskStorageHealthCheck(
            this IHealthChecksBuilder builder,
            Action <DiskStorageOptions>?setup,
            string?name = default,
            HealthStatus?failureStatus = default,
            IEnumerable <string>?tags  = default,
            TimeSpan?timeout           = default)
        {
            var options = new DiskStorageOptions();

            setup?.Invoke(options);

            return(builder.Add(new HealthCheckRegistration(
                                   name ?? DISK_NAME,
                                   sp => new DiskStorageHealthCheck(options),
                                   failureStatus,
                                   tags,
                                   timeout)));
        }
コード例 #28
0
 /// <summary>
 /// Add a health check for Azure Service Bus Subscription.
 /// </summary>
 /// <param name="builder">The <see cref="IHealthChecksBuilder"/>.</param>
 /// <param name="endpoint">The azure service bus endpoint to be used, format sb://myservicebus.servicebus.windows.net/.</param>
 /// <param name="topicName">The topic name of the topic to check.</param>
 /// <param name="subscriptionName">The subscription name of the topic to check.</param>
 /// <param name="tokenCredential">The token credential for auth.</param>
 /// <param name="name">The health check name. Optional. If <c>null</c> the type name 'azuretopic' will be used for the name.</param>
 /// <param name="failureStatus">
 /// The <see cref="HealthStatus"/> that should be reported when the health check fails. Optional. If <c>null</c> then
 /// the default status of <see cref="HealthStatus.Unhealthy"/> will be reported.
 /// </param>
 /// <param name="tags">A list of tags that can be used to filter sets of health checks. Optional.</param>
 /// <param name="timeout">An optional <see cref="TimeSpan"/> representing the timeout of the check.</param>
 /// <returns>The specified <paramref name="builder"/>.</returns>
 public static IHealthChecksBuilder AddAzureServiceBusSubscription(
     this IHealthChecksBuilder builder,
     string endpoint,
     string topicName,
     string subscriptionName,
     TokenCredential tokenCredential,
     string?name = default,
     HealthStatus?failureStatus = default,
     IEnumerable <string>?tags  = default,
     TimeSpan?timeout           = default) =>
 builder.AddAzureServiceBusSubscription(
     _ => endpoint,
     _ => topicName,
     _ => subscriptionName,
     _ => tokenCredential,
     name,
     failureStatus,
     tags,
     timeout);
        /// <summary>
        /// Add a health check for Cloud Firestore (of the Firebase platform).
        /// </summary>
        /// <param name="builder">The <see cref="IHealthChecksBuilder"/>.</param>
        /// <param name="setup">The action to configure the Cloud Firestore parameters.</param>
        /// <param name="name">The health check name. Optional. If <c>null</c> the type name 'cloud firestore' will be used for the name.</param>
        /// <param name="failureStatus">
        /// The <see cref="HealthStatus"/> that should be reported when the health check fails. Optional. If <c>null</c> then
        /// the default status of <see cref="HealthStatus.Unhealthy"/> will be reported.
        /// </param>
        /// <param name="tags">A list of tags that can be used to filter sets of health checks. Optional.</param>
        /// <param name="timeout">An optional <see cref="TimeSpan"/> representing the timeout of the check.</param>
        /// <returns>The specified <paramref name="builder"/>.</returns>
        public static IHealthChecksBuilder AddCloudFirestore(
            this IHealthChecksBuilder builder,
            Action <CloudFirestoreOptions>?setup,
            string?name = default,
            HealthStatus?failureStatus = default,
            IEnumerable <string>?tags  = default,
            TimeSpan?timeout           = default)
        {
            var cloudFirestoreOptions = new CloudFirestoreOptions();

            setup?.Invoke(cloudFirestoreOptions);

            return(builder.Add(new HealthCheckRegistration(
                                   name ?? NAME,
                                   sp => new CloudFirestoreHealthCheck(cloudFirestoreOptions),
                                   failureStatus,
                                   tags,
                                   timeout)));
        }
コード例 #30
0
        /// <summary>
        /// Add a health check for Consul services.
        /// </summary>
        /// <param name="builder">The <see cref="IHealthChecksBuilder"/>.</param>
        /// <param name="setup">The action to configure Consul. </param>
        /// <param name="name">The health check name. Optional. If <c>null</c> the type name 'consul' will be used for the name.</param>
        /// <param name="failureStatus">
        /// The <see cref="HealthStatus"/> that should be reported when the health check fails. Optional. If <c>null</c> then
        /// the default status of <see cref="HealthStatus.Unhealthy"/> will be reported.
        /// </param>
        /// <param name="tags">A list of tags that can be used to filter sets of health checks. Optional.</param>
        /// <param name="timeout">An optional <see cref="TimeSpan"/> representing the timeout of the check.</param>
        /// <returns>The specified <paramref name="builder"/>.</returns>
        public static IHealthChecksBuilder AddConsul(
            this IHealthChecksBuilder builder,
            Action <ConsulOptions>?setup,
            string?name = default,
            HealthStatus?failureStatus = default,
            IEnumerable <string>?tags  = default,
            TimeSpan?timeout           = default)
        {
            builder.Services.AddHttpClient();

            var registrationName = name ?? NAME;

            return(builder.Add(new HealthCheckRegistration(
                                   registrationName,
                                   sp => CreateHealthCheck(sp, setup, registrationName),
                                   failureStatus,
                                   tags,
                                   timeout)));
        }