public static IApplicationBuilder UseMonitoringEndpoint(
            this IApplicationBuilder app,
            Action <HealthCheckOptions> optionsSetup = null)
        {
            if (app == null)
            {
                throw new ArgumentNullException(nameof(app));
            }
            var provider = app.ApplicationServices;

            var collector = provider.GetRequiredService <IResourceStateCollector>();

            collector.Start();
            var lifetime = provider.GetService <IApplicationLifetime>();

            lifetime?.ApplicationStopping.Register(() => collector.Stop());

            var options = new HealthCheckOptions();

            optionsSetup?.Invoke(options);

            IVersionService versionService = null;

            if (options.IncludeVersionInformation)
            {
                versionService = provider.GetService <IVersionService>();
            }

            return(app.Map(
                       options.Path,
                       m => m.UseMiddleware <HealthCheckMiddleware>(collector, options.ToStringStrategy, versionService)));
        }
        /// <summary>
        /// Add the HealthCheck middleware to PipeLine
        /// </summary>
        /// <param name="appBuilder"></param>
        /// <returns></returns>
        public static IApplicationBuilder UseQiHealthChecks(this IApplicationBuilder appBuilder)
        {
            HealthCheckOptions hchkOptions = new HealthCheckOptions()
            {
                ResponseWriter = async(context, report) =>
                {
                    var result = JsonSerializer.Serialize(
                        new
                    {
                        status = report.Status.ToString(),
                        errors = report.Entries.Select(e => new { key = e.Key, value = Enum.GetName(typeof(HealthStatus), e.Value.Status) })
                    }, new JsonSerializerOptions()
                    {
                        IgnoreNullValues = true,
                        WriteIndented    = false
                    });
                    context.Response.ContentType = MediaTypeNames.Application.Json;
                    await context.Response.WriteAsync(result);
                }
            };

            //Setting the response status code for unabailable services as "503"
            hchkOptions.ResultStatusCodes[HealthStatus.Unhealthy] = StatusCodes.Status503ServiceUnavailable;

            appBuilder.UseHealthChecks("/health", hchkOptions);
            return(appBuilder);
        }
        /// <summary>
        /// Maps the Skoruba IdentityServer4 Admin UI health checks to the routes of this application.
        /// </summary>
        /// <param name="endpoint"></param>
        public static IEndpointConventionBuilder MapIdentityServer4AdminUIHealthChecks(this IEndpointRouteBuilder endpoint, string pattern = "/health", Action <HealthCheckOptions> configureAction = null)
        {
            var options = new HealthCheckOptions
            {
                ResponseWriter = UIResponseWriter.WriteHealthCheckUIResponse
            };

            configureAction?.Invoke(options);

            return(endpoint.MapHealthChecks(pattern, options));
        }
Esempio n. 4
0
        public static IApplicationBuilder UseHealthChecksPrometheusExporter(this IApplicationBuilder applicationBuilder, PathString endpoint, Action <HealthCheckOptions> configure)
        {
            var options = new HealthCheckOptions
            {
                ResponseWriter = PrometheusResponseWriter.WritePrometheusResultText
            };

            configure?.Invoke(options);

            applicationBuilder.UseHealthChecks(endpoint, options);
            return(applicationBuilder);
        }
Esempio n. 5
0
        public static IApplicationBuilder UseHealthyHealthCheck(
            this IApplicationBuilder builder,
            string healthCheckPath = "/healthy",
            HealthCheckOptions healthCheckOptions = default)
        {
            if (healthCheckOptions == default)
            {
                healthCheckOptions = new HealthCheckOptions {
                    ResponseWriter = WriteResponse
                };
            }

            builder.UseHealthChecks(healthCheckPath, healthCheckOptions);

            return(builder);
        }
Esempio n. 6
0
        /// <summary>
        /// Enable usage of the basic liveness check that returns 200 http status code.
        /// Default registered health check is self.
        /// </summary>
        /// <param name="builder"></param>
        /// <param name="healthCheckPath"></param>
        /// <param name="healthCheckOptions"></param>
        /// <returns></returns>
        public static IApplicationBuilder UseLivenessHealthCheck(
            this IApplicationBuilder builder,
            string healthCheckPath = "/liveness",
            HealthCheckOptions healthCheckOptions = default)
        {
            if (healthCheckOptions == default)
            {
                // Exclude all checks and return a 200-Ok. Default registered health check is self.
                healthCheckOptions = new HealthCheckOptions {
                    Predicate = (p) => false
                };
            }

            builder.UseHealthChecks(healthCheckPath, healthCheckOptions);

            return(builder);
        }
        /// <summary>
        /// Adds a health checks endpoint to the <see cref="IEndpointRouteBuilder"/> with the specified template and options.
        /// </summary>
        /// <param name="endpoints">The <see cref="IEndpointRouteBuilder"/> to add the health checks endpoint to.</param>
        /// <param name="pattern">The URL pattern of the health checks endpoint.</param>
        /// <param name="options">A <see cref="HealthCheckOptions"/> used to configure the health checks.</param>
        /// <returns>A convention routes for the health checks endpoint.</returns>
        public static IEndpointConventionBuilder MapHealthChecks(
            this IEndpointRouteBuilder endpoints,
            string pattern,
            HealthCheckOptions options)
        {
            if (endpoints == null)
            {
                throw new ArgumentNullException(nameof(endpoints));
            }

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

            return(MapHealthChecksCore(endpoints, pattern, options));
        }
        /// <summary>
        /// Adds a health checks endpoint to the <see cref="IEndpointRouteBuilder"/> with the specified template and options.
        /// </summary>
        /// <param name="builder">The <see cref="IEndpointRouteBuilder"/> to add the health checks endpoint to.</param>
        /// <param name="pattern">The URL pattern of the health checks endpoint.</param>
        /// <param name="options">A <see cref="HealthCheckOptions"/> used to configure the health checks.</param>
        /// <returns>A convention builder for the health checks endpoint.</returns>
        public static IEndpointConventionBuilder MapHealthChecks(
            this IEndpointRouteBuilder builder,
            string pattern,
            HealthCheckOptions options)
        {
            if (builder == null)
            {
                throw new ArgumentNullException(nameof(builder));
            }

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

            return(MapHealthChecksCore(builder, pattern, options, DefaultDisplayName));
        }
Esempio n. 9
0
        /// <summary>
        /// Enable health check endpoint.
        /// </summary>
        /// <param name="app"></param>
        /// <param name="path">Request path.</param>
        /// <returns></returns>
        public static IApplicationBuilder UseHealthCheck(this IApplicationBuilder app, string path)
        {
            if (app == null)
            {
                throw new ArgumentNullException(nameof(app));
            }

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

            var options = new HealthCheckOptions {
                Path = new PathString(path)
            };

            return(app.UseHealthCheck(options));
        }
        /// <summary>
        /// Adds a health checks endpoint to the <see cref="IEndpointRouteBuilder"/> with the specified template, options and display name.
        /// </summary>
        /// <param name="builder">The <see cref="IEndpointRouteBuilder"/> to add the health checks endpoint to.</param>
        /// <param name="pattern">The URL pattern of the health checks endpoint.</param>
        /// <param name="options">A <see cref="HealthCheckOptions"/> used to configure the health checks.</param>
        /// <param name="displayName">The display name for the endpoint.</param>
        /// <returns>A convention builder for the health checks endpoint.</returns>
        public static IEndpointConventionBuilder MapHealthChecks(
            this IEndpointRouteBuilder builder,
            string pattern,
            HealthCheckOptions options,
            string displayName)
        {
            if (builder == null)
            {
                throw new ArgumentNullException(nameof(builder));
            }

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

            if (string.IsNullOrEmpty(displayName))
            {
                throw new ArgumentException("A valid non-empty display name must be provided.", nameof(displayName));
            }

            return(MapHealthChecksCore(builder, pattern, options, displayName));
        }
        private static IEndpointConventionBuilder MapHealthChecksCore(IEndpointRouteBuilder builder, string pattern, HealthCheckOptions options)
        {
            var args = options != null ? new[] { Options.Create(options) } : Array.Empty <object>();

            var pipeline = builder.CreateApplicationBuilder()
                           .UseMiddleware <HealthCheckMiddleware>(args)
                           .Build();

            return(builder.Map(pattern, "Health checks", pipeline));
        }
Esempio n. 12
0
        /// <summary>
        /// Adds a middleware that provides health check status.
        /// </summary>
        /// <param name="app">The <see cref="IApplicationBuilder"/>.</param>
        /// <param name="path">The path on which to provide health check status.</param>
        /// <param name="options">A <see cref="HealthCheckOptions"/> used to configure the middleware.</param>
        /// <returns>A reference to the <paramref name="app"/> after the operation has completed.</returns>
        /// <remarks>
        /// <para>
        /// If <paramref name="path"/> is set to <c>null</c> or the empty string then the health check middleware
        /// will ignore the URL path and process all requests. If <paramref name="path"/> is set to a non-empty
        /// value, the health check middleware will process requests with a URL that matches the provided value
        /// of <paramref name="path"/> case-insensitively, allowing for an extra trailing slash ('/') character.
        /// </para>
        /// </remarks>
        public static IApplicationBuilder UseHealthChecksWithAuth(this IApplicationBuilder app, PathString path, HealthCheckOptions options)
        {
            if (app == null)
            {
                throw new ArgumentNullException(nameof(app));
            }

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

            UseHealthChecksCore(app: app, path: path, port: null, args: new[] { Options.Create(options), });
            return(app);
        }
Esempio n. 13
0
        /// <summary>
        /// Adds a middleware that provides health check status.
        /// </summary>
        /// <param name="app">The <see cref="IApplicationBuilder"/>.</param>
        /// <param name="path">The path on which to provide health check status.</param>
        /// <param name="port">The port to listen on. Must be a local port on which the server is listening.</param>
        /// <param name="options">A <see cref="HealthCheckOptions"/> used to configure the middleware.</param>
        /// <returns>A reference to the <paramref name="app"/> after the operation has completed.</returns>
        /// <remarks>
        /// <para>
        /// If <paramref name="path"/> is set to <c>null</c> or the empty string then the health check middleware
        /// will ignore the URL path and process all requests on the specified port. If <paramref name="path"/> is
        /// set to a non-empty value, the health check middleware will process requests with a URL that matches the
        /// provided value of <paramref name="path"/> case-insensitively, allowing for an extra trailing slash ('/')
        /// character.
        /// </para>
        /// </remarks>
        public static IApplicationBuilder UseHealthChecksWithAuth(this IApplicationBuilder app, PathString path, string port, HealthCheckOptions options)
        {
            if (app == null)
            {
                throw new ArgumentNullException(nameof(app));
            }

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

            if (!int.TryParse(port, out var portAsInt))
            {
                throw new ArgumentException("The port must be a valid integer.", nameof(port));
            }

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

            UseHealthChecksCore(app, path, portAsInt, new[] { Options.Create(options), });
            return(app);
        }
        private static IEndpointConventionBuilder MapHealthChecksCore(IEndpointRouteBuilder endpoints, string pattern, HealthCheckOptions options)
        {
            if (endpoints.ServiceProvider.GetService(typeof(HealthCheckService)) == null)
            {
                throw new InvalidOperationException($"Unable to find the required services. Please add all the required services by calling '{nameof(IServiceCollection)}.{nameof(HealthCheckServiceCollectionExtensions.AddHealthChecks)}' inside the call to '{"ConfigureServices(...)"}' in the application startup code.");
            }

            var args = options != null ? new[] { Options.Create(options) } : Array.Empty <object>();

            var pipeline = endpoints.CreateApplicationBuilder()
                           .UseMiddleware <HealthCheckMiddleware>(args)
                           .Build();

            return(endpoints.Map(pattern, pipeline).WithDisplayName(DefaultDisplayName));
        }
        private static IEndpointConventionBuilder MapHealthChecksCore(IEndpointRouteBuilder builder, string pattern, HealthCheckOptions options, string displayName)
        {
            if (builder.ServiceProvider.GetService(typeof(HealthCheckService)) == null)
            {
                throw new InvalidOperationException(Resources.FormatUnableToFindServices(
                                                        nameof(IServiceCollection),
                                                        nameof(HealthCheckServiceCollectionExtensions.AddHealthChecks),
                                                        "ConfigureServices(...)"));
            }

            var args = options != null ? new[] { Options.Create(options) } : Array.Empty <object>();

            var pipeline = builder.CreateApplicationBuilder()
                           .UseMiddleware <HealthCheckMiddleware>(args)
                           .Build();

            return(builder.Map(pattern, displayName, pipeline));
        }
Esempio n. 16
0
        /// <summary>
        /// Adds a middleware that provides health check status.
        /// </summary>
        /// <param name="app">The <see cref="IApplicationBuilder"/>.</param>
        /// <param name="path">The path on which to provide health check status.</param>
        /// <param name="options">A <see cref="HealthCheckOptions"/> used to configure the middleware.</param>
        /// <returns>A reference to the <paramref name="app"/> after the operation has completed.</returns>
        /// <remarks>
        /// <para>
        /// This method will use <see cref="MapExtensions.Map(IApplicationBuilder, PathString, Action{IApplicationBuilder})"/> to
        /// listen to health checks requests on the specified URL path.
        /// </para>
        /// </remarks>
        public static IApplicationBuilder UseHealthChecks(this IApplicationBuilder app, PathString path, HealthCheckOptions options)
        {
            if (app == null)
            {
                throw new ArgumentNullException(nameof(app));
            }

            if (!path.HasValue)
            {
                throw new ArgumentException("A URL path must be provided", nameof(path));
            }

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

            UseHealthChecksCore(app, path, port: null, new[] { Options.Create(options), });
            return(app);
        }
Esempio n. 17
0
        /// <summary>
        /// Enable health check endpoint.
        /// </summary>
        /// <param name="app"></param>
        /// <param name="options">Options for request path.</param>
        /// <returns></returns>
        public static IApplicationBuilder UseHealthCheck(this IApplicationBuilder app, HealthCheckOptions options)
        {
            if (app == null)
            {
                throw new ArgumentNullException(nameof(app));
            }

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

            return(app.UseMiddleware <HealthCheckMiddleware>(Options.Create(options)));
        }