public async Task <IDictionary <string, BpHealthReportEntry> > GetSanity()
        {
            var reports = (await _healthCheckService.CheckHealthAsync(checks =>
                                                                      checks.Tags.Contains(HealthCheckTag.SANITY))).Entries;

            return(reports.ToDictionary(pair => pair.Key, pair => new BpHealthReportEntry(pair.Value)));
        }
        public override async Task <HealthCheckResponse> Check(HealthCheckRequest request, ServerCallContext context)
        {
            HealthReport healthReport;

            if (string.IsNullOrWhiteSpace(request.Service))
            {
                healthReport = await _healthCheckService.CheckHealthAsync();
            }
            else
            {
                healthReport = await _healthCheckService.CheckHealthAsync(
                    s => string.Equals(s.Name, request.Service, StringComparison.OrdinalIgnoreCase));

                if (healthReport.Entries.Count == 0)
                {
                    throw new RpcException(new Status(StatusCode.NotFound, $"Service {request.Service} not found"));
                }
            }

            _logger.LogInformation("HealthReport {@HealthReport}", healthReport);

            return(new HealthCheckResponse
            {
                Status = healthReport.Status switch
                {
                    HealthStatus.Degraded => HealthCheckResponse.Types.ServingStatus.Serving,
                    HealthStatus.Healthy => HealthCheckResponse.Types.ServingStatus.Serving,
                    HealthStatus.Unhealthy => HealthCheckResponse.Types.ServingStatus.NotServing,
                    _ => HealthCheckResponse.Types.ServingStatus.Unknown,
                }
            });
        private async Task <IActionResult> GetHealthChecksReportAsync(Func <HealthCheckRegistration, bool> filter)
        {
            var report = await _service.CheckHealthAsync(filter, HttpContext.RequestAborted);

            if (!_options.Value.ResultStatusCodes.TryGetValue(report.Status, out var statusCode))
            {
                throw new InvalidOperationException(
                          _localizer.GetString("No status code mapping found for HealthStatus '{0}'",
                                               report.Status));
            }

            HttpContext.Response.StatusCode = statusCode;

            if (!_options.Value.AllowCachingResponses)
            {
                var headers = HttpContext.Response.Headers;
                headers["Cache-Control"] = "no-store, no-cache";
                headers["Pragma"]        = "no-cache";
                headers["Expires"]       = "Thu, 01 Jan 1970 00:00:00 GMT";
            }

            return(Ok(new One <HealthReport> {
                Value = report
            }));
        }
        private async Task UpdateHeartbeatAsync(CancellationToken token)
        {
            try
            {
                // Get health check results
                var result = await _healthCheckService.CheckHealthAsync(token);

                var isHealthy = result.Status == HealthStatus.Healthy;

                if (!isHealthy)
                {
                    _listener.Stop();
                    _logger.LogInformation("Service is unhealthy. Listener stopped.");
                    return;
                }

                _listener.Start();
                while (_listener.Server.IsBound && _listener.Pending())
                {
                    var client = await _listener.AcceptTcpClientAsync();

                    client.Close();
                    _logger.LogInformation("Successfully processed health check request.");
                }

                _logger.LogDebug("Heartbeat check executed.");
            }
#pragma warning disable CA1031 // Do not catch general exception types
            catch (Exception ex)
            {
                _logger.LogCritical(ex, "An error occurred while checking heartbeat.");
            }
#pragma warning restore CA1031 // Do not catch general exception types
        }
        public async Task <IActionResult> Get()
        {
            var report = await _healthCheckService.CheckHealthAsync();

            return(report.Status == HealthStatus.Healthy ? Ok(report) :
                   StatusCode((int)HttpStatusCode.ServiceUnavailable, report));
        }
Beispiel #6
0
        private async Task HeartbeatAsync(CancellationToken stoppingToken)
        {
            try
            {
                var result = await _healthCheckService.CheckHealthAsync(stoppingToken);

                var isHealthy = result.Status == HealthStatus.Healthy;

                if (!isHealthy)
                {
                    _listener.Stop();
                    _logger.LogInformation("Service is {status}. Probe stopped.", result.Status);
                    return;
                }

                _listener.Start();
                while (_listener.Server.IsBound && _listener.Pending())
                {
                    var client = await _listener.AcceptTcpClientAsync();

                    client.Close();
                    _logger.LogInformation("Successfully processed heartbeat request.");
                }
            }
            catch (Exception e)
            {
                _logger.LogError(e, "An error occurred when processing heartbeat");
            }
        }
Beispiel #7
0
        public async Task <ContentResult> HealthTest()
        {
            HealthReport healthResult = await _healthChecks.CheckHealthAsync().ConfigureAwait(false);

            return(new ContentResult
            {
                ContentType = "text/html",
                StatusCode = (int)HttpStatusCode.OK,
                Content = HealthTestPage.GetContents(
                    healthResult,
                    "/api/health",
                    new List <HealthTestPageLink>
                {
                    new HealthTestPageLink {
                        TestEndpoint = "/api/artists", Name = "Artists", Description = "Returns all records."
                    },
                    new HealthTestPageLink {
                        TestEndpoint = "/api/artists/150", Name = "U2", Description = "Returns single record."
                    },
                    new HealthTestPageLink {
                        TestEndpoint = "/api/artists/150/albums", Name = "U2 albums", Description = "Returns multiple queries results."
                    },
                }),
            });
        }
        public async Task <IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Function, "get", Route = "v1/health")] HttpRequest request,
            CancellationToken cancellation)
        {
            try
            {
                Logger.LogInformation("C# HTTP trigger 'health' function processed a request");
                if (AcceptsJson(request) == false)
                {
                    string accept = String.Join(", ", GetAcceptMediaTypes(request));
                    Logger.LogError("Could not process current request because the response could not accept JSON (Accept: {Accept})", accept);

                    return(UnsupportedMediaType("Could not process current request because the response could not accept JSON"));
                }

                if (TryHttpCorrelate(out string errorMessage) == false)
                {
                    return(BadRequest(errorMessage));
                }

                HealthReport healthReport = await _healthCheckService.CheckHealthAsync(cancellation);

                if (healthReport?.Status == HealthStatus.Healthy)
                {
                    return(Json(healthReport));
                }

                return(Json(healthReport, statusCode: StatusCodes.Status503ServiceUnavailable));
            }
            catch (Exception exception)
            {
                Logger.LogCritical(exception, exception.Message);
                return(InternalServerError("Could not process the current request due to an unexpected exception"));
            }
        }
Beispiel #9
0
        public async Task <DateHealthReport> GetOrCheckHealthAsync(HealthCheckService healthCheckService, CancellationToken cancellationToken = default)
        {
            try
            {
                if ((Evaluating) || (Result?.Date.Add(options.CacheDuration) > DateTimeOffset.UtcNow))
                {
                    return(Result);
                }

                await _mutex.WaitAsync(cancellationToken);

                Evaluating = true;

                var report = await healthCheckService.CheckHealthAsync(cancellationToken);

                Result = new DateHealthReport()
                {
                    Date   = DateTimeOffset.UtcNow,
                    Report = report
                };

                Evaluating = false;

                return(Result);
            }
            catch (Exception)
            {
                Evaluating = false;
                return(Result);
            }
            finally
            {
                _mutex.Release();
            }
        }
        public async Task InvokeInternal(IOwinContext context)
        {
            // Get results
            var result = await _healthCheckService.CheckHealthAsync(_healthCheckOptions?.Predicate, context.Request.CallCancelled);

            // Map status to response code - this is customizable via options.
            if (!_healthCheckOptions.ResultStatusCodes.TryGetValue(result.Status, out var statusCode))
            {
                var message =
                    $"No status code mapping found for {nameof(HealthStatus)} value: {result.Status}." +
                    $"{nameof(HealthCheckOptions)}.{nameof(HealthCheckOptions.ResultStatusCodes)} must contain" +
                    $"an entry for {result.Status}.";

                throw new InvalidOperationException(message);
            }

            context.Response.StatusCode = statusCode;

            if (!_healthCheckOptions.AllowCachingResponses)
            {
                // Similar to: https://github.com/aspnet/Security/blob/7b6c9cf0eeb149f2142dedd55a17430e7831ea99/src/Microsoft.AspNetCore.Authentication.Cookies/CookieAuthenticationHandler.cs#L377-L379
                var headers = context.Response.Headers;
                headers[HeaderNames.CacheControl] = "no-store, no-cache";
                headers[HeaderNames.Pragma]       = "no-cache";
                headers[HeaderNames.Expires]      = "Thu, 01 Jan 1970 00:00:00 GMT";
            }

            if (_healthCheckOptions.ResponseWriter != null)
            {
                await _healthCheckOptions.ResponseWriter(context, result);
            }
        }
Beispiel #11
0
        public async Task Get()
        {
            var result = await _healthCheckService.CheckHealthAsync(_healthCheckOptions.Predicate, HttpContext.RequestAborted);

            // Map status to response code - this is customizable via options.
            if (!_healthCheckOptions.ResultStatusCodes.TryGetValue(result.Status, out var statusCode))
            {
                var message =
                    $"No status code mapping found for {nameof(HealthStatus)} value: {result.Status}." +
                    $"{nameof(HealthCheckOptions)}.{nameof(HealthCheckOptions.ResultStatusCodes)} must contain" +
                    $"an entry for {result.Status}.";

                throw new InvalidOperationException(message);
            }

            HttpContext.Response.StatusCode = statusCode;

            if (!_healthCheckOptions.AllowCachingResponses)
            {
                var headers = HttpContext.Response.Headers;
                headers[HeaderNames.CacheControl] = "no-store, no-cache";
                headers[HeaderNames.Pragma]       = "no-cache";
                headers[HeaderNames.Expires]      = "Thu, 01 Jan 1970 00:00:00 GMT";
            }

            if (_healthCheckOptions.ResponseWriter != null)
            {
                await _healthCheckOptions.ResponseWriter(HttpContext, result);
            }
        }
    public Task StartAsync(CancellationToken cancellationToken)
    {
        ThrowIfDisposed();

        _logging = Task.Run(async() =>
        {
            using var cts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, _cts.Token);

            while (true)
            {
                cts.Token.ThrowIfCancellationRequested();

                var report = await _healthCheckService.CheckHealthAsync(cancellationToken)
                             .ConfigureAwait(false);

                if (report.Status == HealthStatus.Healthy)
                {
                    _logger.LogInformation(HealthCheckLogMessage, report.Status, report);
                }
                else
                {
                    _logger.LogWarning(HealthCheckLogMessage, report.Status, report);
                }

                await Task.Delay(TimeSpan.FromSeconds(10))
                .ConfigureAwait(false);
            }
        });

        return(Task.CompletedTask);
    }
Beispiel #13
0
        public async Task <IActionResult> OnGet()
        {
            if (!HttpContext.User.Identity.IsAuthenticated)
            {
                return(Challenge(AspNet.Security.OAuth.Discord.DiscordAuthenticationDefaults.AuthenticationScheme));
            }

            if ((await healthCheckService.CheckHealthAsync()).Status == HealthStatus.Healthy)
            {
                var guildIds = await backendService.GetGuildIds();

                var userId = User.FindFirst("http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier")?.Value;

                var guildClaim = User.FindFirst("http://schemas.xmlsoap.org/ws/2005/05/identity/claims/guilds");

                if (guildClaim != null)
                {
                    var             json       = guildClaim.Value;
                    DiscordServer[] serverList = JsonConvert.DeserializeObject <DiscordServer[]>(json);
                    Servers = serverList.Join(guildIds, k => k.Id, k => k, (l, r) => l)
                              .Where(x => (x.Permissions & Permissions.BAN_MEMBERS) != 0 || userId == "367018778409566209").ToArray();
                }
            }

            return(Page());
        }
Beispiel #14
0
        public async Task <IActionResult> OnGet(ulong id)
        {
            this.Id = id;

            if ((await healthCheckService.CheckHealthAsync()).Status != HealthStatus.Healthy)
            {
                return(Page());
            }

            var guildInformation = await backendService.GetGuildInformation(id);

            GuildName        = guildInformation?.Name;
            GuildIconUrl     = guildInformation?.IconUrl;
            GuildDescription = guildInformation?.Description;
            return(Page());
        }
Beispiel #15
0
        public async Task <IActionResult> Get()
        {
            var healthReport = await _healthCheckService.CheckHealthAsync();

            var applications = await _applicationManagementService.GetApplications();

            if (applications != null)
            {
                foreach (var entry in healthReport.Entries)
                {
                    var app = applications.FirstOrDefault(x => x.Name == entry.Key);
                    if (app != null)
                    {
                        if (entry.Value.Status == HealthStatus.Unhealthy)
                        {
                            app.IsHealthy = false;
                        }
                        else if (entry.Value.Status == HealthStatus.Healthy)
                        {
                            app.IsHealthy = true;
                        }
                    }
                }
                _memoryCache.Remove(CacheKey.Applications);
                _memoryCache.Set(CacheKey.Applications, applications);
            }

            return(Ok(healthReport));
        }
 /// <summary>
 /// This method is called when the <see cref="T:Microsoft.Extensions.Hosting.IHostedService" /> starts. The implementation should return a task that represents
 /// the lifetime of the long running operation(s) being performed.
 /// </summary>
 /// <param name="stoppingToken">Triggered when <see cref="M:Microsoft.Extensions.Hosting.IHostedService.StopAsync(System.Threading.CancellationToken)" /> is called.</param>
 /// <returns>A <see cref="T:System.Threading.Tasks.Task" /> that represents the long running operations.</returns>
 protected override async Task ExecuteAsync(CancellationToken stoppingToken)
 {
     while (!stoppingToken.IsCancellationRequested)
     {
         HealthReport report = await _healthService.CheckHealthAsync(stoppingToken);
         await AcceptConnectionAsync(report);
     }
 }
Beispiel #17
0
        public async Task <IActionResult> Get()
        {
            var reports = await healthCheckService.CheckHealthAsync();

            var models = HealthReportModel.CreateFromReport(reports, "Identity");

            return(Ok(models));
        }
        public Action <IApplicationBuilder> Configure(Action <IApplicationBuilder> next)
        {
            var report = _service.CheckHealthAsync(r => r.Tags.Contains("startup")).GetAwaiter().GetResult();

            return(report.Status == HealthStatus.Unhealthy
                ? ThrowOnUnhealthyCheck(report)
                : next);
        }
        public async Task <string> GetHealthStatusAsync()
        {
            var report = await _healthCheckService.CheckHealthAsync();

            _logger.LogTrace("Health report: {@report}", report);

            return(report.Status.ToString());
        }
Beispiel #20
0
        public async Task <IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Function, "get", Route = null)] HttpRequest req
            )
        {
            var healthReport = await _healthCheckService.CheckHealthAsync();

            return(HealthReportObjectResult.GetHealthReportObjectResult <Startup>(healthReport));
        }
        public async Task <HealthReport> Get()
        {
            return(await _healthCheck.CheckHealthAsync());

            //var timedTokenSource = new CancellationTokenSource(TimeSpan.FromSeconds(3));
            //HealthReport checkHealth = await _healthCheck.CheckHealthAsync(timedTokenSource.Token);
            //return checkHealth;
        }
Beispiel #22
0
        /// <inheritdoc cref="IHealthCheckMonitor.CheckAsync" />
        public async Task CheckAsync(CancellationToken cancellationToken = default(CancellationToken))
        {
            var reports = await _healthCheckService.CheckHealthAsync(cancellationToken);

            foreach (var report in reports.Entries)
            {
                _storage.Write(report.Key, report.Value);
            }
        }
Beispiel #23
0
        private async Task <(HealthReportEntry loggingSource1HealthReport, HealthReportEntry loggingSource2HealthReport, HealthReportEntry globalHealthReport)> GetResultAsync()
        {
            var result = await healthCheckService.CheckHealthAsync();

            result.Entries.TryGetValue(IHealthChecksBuilderExtensionMethods.LOGS_NAME, out var globalHealthReport).Should().BeTrue();
            result.Entries.TryGetValue(nameof(LoggingSource1), out var loggingSource1HealthReport).Should().BeTrue();
            result.Entries.TryGetValue(nameof(LoggingSource2), out var loggingSource2HealthReport).Should().BeTrue();
            return(loggingSource1HealthReport, loggingSource2HealthReport, globalHealthReport);
        }
Beispiel #24
0
 public async Task OnGet()
 {
     Title = "Home";
     InformationalVersion = Assembly.GetEntryAssembly().GetCustomAttribute <AssemblyInformationalVersionAttribute>().InformationalVersion;
     EnvironmentName      = webHostEnvironment.EnvironmentName;
     ContentRootPath      = webHostEnvironment.ContentRootPath;
     SettingsPath         = System.IO.Path.Combine(ContentRootPath, "appsettings.json");
     WebRootPath          = webHostEnvironment.WebRootPath;
     HealthStatus         = (await healthCheckService.CheckHealthAsync(CancellationToken.None)).Status.ToString();
 }
Beispiel #25
0
        public async Task <IActionResult> Index()
        {
            var models = new List <HealthReportModel>();

            models.AddRange(await endpointsHealthService.GetIdentityHealthReport());
            models.AddRange(await endpointsHealthService.GetApiHealthReport());
            models.AddRange(HealthReportModel.CreateFromReport(await healthCheckService.CheckHealthAsync(), "Admin"));

            return(View(models));
        }
        public async Task <IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Anonymous, "get", Route = "health")] HttpRequestMessage req,
            ILogger log)
        {
            _logger.Log(LogLevel.Information, "Received health request");

            var status = await _healthCheck.CheckHealthAsync();

            return(new OkObjectResult(Enum.GetName(typeof(HealthStatus), status.Status)));
        }
Beispiel #27
0
        public async Task <IActionResult> Settings()
        {
            var health = await _healthCheck.CheckHealthAsync();

            var model = _mapper.Map <SettingsModel>(_optionsService.Options);

            model.HealthStatus = health.Status.ToString();
            model.HealthChecks = health.Entries.ToDictionary(x => x.Key, y => y.Value.Status.ToString());

            return(View("Settings", model));
        }
        public async Task <IActionResult> Get()
        {
            HealthReport healthReport = await _healthCheckService.CheckHealthAsync();

            if (healthReport?.Status == HealthStatus.Healthy)
            {
                return(Ok(healthReport));
            }

            return(StatusCode(StatusCodes.Status503ServiceUnavailable, healthReport));
        }
        public Action <IApplicationBuilder> Configure(Action <IApplicationBuilder> next)
        {
            if (!AnyStartupHealthChecksIncluded())
            {
                return(next);
            }

            var report = _service.CheckHealthAsync(r => r.Tags.Contains("startup")).GetAwaiter().GetResult();

            return(report.Status == HealthStatus.Unhealthy
                                ? throw new Exception("Application failed to start due to failing startup health checks.")
                                : next);
        }
        public async Task <IActionResult> HealthCheckActionResult()
        {
            var report = await _healthCheckService.CheckHealthAsync();

            var list = new List <HealthCheckResponse>();

            foreach (var item in report.Entries)
            {
                var healthCheckItem = _mapper.Map <HealthCheckResponse>(item.Value);
                healthCheckItem.ServiceName = item.Key;
                list.Add(healthCheckItem);
            }

            return(report.Status == HealthStatus.Healthy ? Ok(list) : StatusCode((int)HttpStatusCode.ServiceUnavailable, list));
        }