private void checkHttpStatus(ref HealthCheckResponse response, string url)
        {
            HttpWebRequest  myRequest;
            HttpWebResponse myResponse = null;

            try
            {
                myRequest  = (HttpWebRequest)WebRequest.Create(url);
                myResponse = (HttpWebResponse)myRequest.GetResponse();
                if ((int)myResponse.StatusCode >= 200 && (int)myResponse.StatusCode < 300)
                {
                    _data.Add(url, State.UP);
                }
                else
                {
                    response.Down();
                    _data.Add(url, State.DOWN);
                }
            }
            catch
            {
                response.Down();
                _data.Add(url, State.DOWN);
            }
            finally
            {
                if (myResponse != null)
                {
                    myResponse.Close();
                }
            }
        }
Exemple #2
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }



            // Enable Middelware to serve generated Swager as JSON endpoint
            var swaggerOptions = new SwaggerOptions();

            Configuration.GetSection(nameof(SwaggerOptions)).Bind(swaggerOptions);

            app.UseSwagger(option =>
            {
                option.RouteTemplate = swaggerOptions.JsonRoute;
            });

            // Enable Middelware to serve Swagger UI (HTML, JavaScript, CSS etc.)
            app.UseSwaggerUI(option =>
            {
                option.SwaggerEndpoint(swaggerOptions.UIEndpoint, swaggerOptions.Description);
            });

            // Enable Health Check Middleware
            app.UseHealthChecks("/health", new HealthCheckOptions
            {
                ResponseWriter = async(context, report) =>
                {
                    context.Response.ContentType = "application/json";

                    var response = new HealthCheckResponse()
                    {
                        Status = report.Status.ToString(),
                        Checks = report.Entries.Select(x => new HealthCheck
                        {
                            Status      = x.Value.Status.ToString(),
                            Component   = x.Key,
                            Description = x.Value.Description
                        }),
                        Duration = report.TotalDuration
                    };

                    await context.Response.WriteAsync(text: JsonConvert.SerializeObject(response));
                }
            });

            app.UseCustomExceptionHandler();
            app.UseHttpsRedirection();

            app.UseRouting();

            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });
        }
        public static void AddHealthChecksMiddleware(this IApplicationBuilder app)
        {
            app.UseHealthChecks("/healthcheck", new HealthCheckOptions
            {
                Predicate = _ => false
            });

            app.UseHealthChecks("/healthcheck/dependencies", new HealthCheckOptions
            {
                ResponseWriter = async(context, report) =>
                {
                    context.Response.ContentType = "application/json";

                    var response = new HealthCheckResponse
                    {
                        Status = report.Status.ToString(),
                        Checks = report.Entries.Select(e => new HealthCheck
                        {
                            Status      = e.Value.Status.ToString(),
                            Component   = e.Key,
                            Description = e.Value.Description
                        }),
                        Duration = report.TotalDuration
                    };

                    await context.Response.WriteAsync(JsonConvert.SerializeObject(response));
                }
            });
        }
        public static IApplicationBuilder UseCustomHealthchecks(this IApplicationBuilder app)
        {
            app.UseHealthChecks("/health", new HealthCheckOptions
            {
                ResponseWriter = async(context, report) => {
                    context.Response.ContentType = "application/json";

                    var response = new HealthCheckResponse
                    {
                        status = report.Status.ToString(),
                        Checks = report.Entries.Select(x => new HealthCheck
                        {
                            Componenet  = x.Key,
                            status      = x.Value.Status.ToString(),
                            Description = x.Value.Description
                        }),
                        Duration = report.TotalDuration
                    };
                    await context.Response.WriteAsync(JsonConvert.SerializeObject(response));
                }
            })
            ;
            app.UseHealthChecksUI();

            return(app.UseHealthChecks("/ready", new HealthCheckOptions
            {
                Predicate = registration => registration.Tags.Contains("dependencies")
            }));
        }
        public void WriteResponseTest()
        {
            var err           = "Some exception message";
            var totalDuration = TimeSpan.FromMilliseconds(200);
            var httpContext   = new DefaultHttpContext();

            httpContext.Response.Body = new MemoryStream();
            var reports = new Dictionary <string, HealthReportEntry>
            {
                { "Test1", new HealthReportEntry(HealthStatus.Healthy, "Check 1", TimeSpan.FromMilliseconds(50), null, null) },
                { "Test2", new HealthReportEntry(HealthStatus.Degraded, "Check 2", TimeSpan.FromMilliseconds(45), null, null) },
                { "Test3", new HealthReportEntry(HealthStatus.Unhealthy, "Check 3", TimeSpan.FromMilliseconds(50), new Exception(err), null) }
            };
            var fullReport = new HealthReport(reports, totalDuration);

            HealthCheckResponseWriter.WriteResponse(httpContext, fullReport).Wait();

            httpContext.Response.Body.Position = 0;
            using (var reader = new StreamReader(httpContext.Response.Body))
            {
                var responseText = reader.ReadToEnd();
                var options      = new JsonSerializerOptions()
                {
                    PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
                    WriteIndented        = true
                };
                options.Converters.Add(new JsonStringEnumConverter());
                var jsonResponse = JsonSerializer.Deserialize <HealthCheckResponse>(responseText, options);

                var expected = new HealthCheckResponse(fullReport);
                jsonResponse.Should().BeEquivalentTo(expected);
            }
        }
        public Common.Models.HealthCheckResponse HealthCheck()
        {
            var response = new HealthCheckResponse();

            response.Message     = "Couchbase Health Check - Fail";
            response.StatusCode  = StatusCode.InternalServerError;
            response.ServiceName = ServiceNames.Cache;
            try
            {
                var healthCheckKey = "Couchbase.HealthCheck";
                var toSave         = "HealthCheck";
                // Save
                Save(healthCheckKey, toSave, CacheRegion.Global);
                // Check if saved
                var healthCheckCacheResult = Contains <string>(healthCheckKey, CacheRegion.Global);
                if (healthCheckCacheResult.Exists && healthCheckCacheResult.CachedObj == toSave)
                {
                    // Delete, sucess.
                    Remove(healthCheckKey, CacheRegion.Global);
                    response.Message     = "Couchbase Health Check - Success";
                    response.StatusCode  = StatusCode.Ok;
                    response.ServiceName = ServiceNames.Cache;
                    return(response);
                }
            }
            catch (Exception ex)
            {
                response.Message     = $"Couchbase Health Check - Fail | {ex.Message},";
                response.StatusCode  = StatusCode.InternalServerError;
                response.ServiceName = ServiceNames.Cache;
                return(response);
            }
            // Failed
            return(response);
        }
Exemple #7
0
        public static Task WriteHealthCheckResponse(
            HttpContext httpContext,
            HealthReport report,
            Action <JsonSerializerSettings> jsonConfigurator)
        {
            var response = "{}";

            if (report != null)
            {
                var settings = new JsonSerializerSettings()
                {
                    ContractResolver      = new CamelCasePropertyNamesContractResolver(),
                    NullValueHandling     = NullValueHandling.Include,
                    ReferenceLoopHandling = ReferenceLoopHandling.Ignore,
                };

                jsonConfigurator?.Invoke(settings);

                settings.Converters.Add(new StringEnumConverter());

                httpContext.Response.ContentType = DefaultContentType;

                var uiReport = HealthCheckResponse.CreateFrom(report);
                uiReport.Version = AssemblyVersion;

                response = JsonConvert.SerializeObject(uiReport, settings);
            }

            return(httpContext.Response.WriteAsync(response));
        }
        public async Task <ActionResult> Get()
        {
            try
            {
                var report = await this.healthCheckService.CheckHealthAsync();

                var response = new HealthCheckResponse
                {
                    Status = report.Status.ToString(),
                    Checks = report.Entries.Select(x => new HealthCheck
                    {
                        Component   = x.Key,
                        Status      = x.Value.Status.ToString(),
                        Description = x.Value.Description,
                    }),
                    Duration = report.TotalDuration,
                };

                return(report.Status == HealthStatus.Healthy ? this.Ok(response) : this.StatusCode((int)HttpStatusCode.ServiceUnavailable, response));
            }
            catch (Exception e)
            {
                return(BadRequest(e.InnerException));
            }
        }
Exemple #9
0
        private HealthCheckResponse GetHealthCheckResponse(string service, bool throwOnNotFound)
        {
            HealthCheckResponse response = null;

            lock (statusLock)
            {
                HealthCheckResponse.Types.ServingStatus status;
                if (!statusMap.TryGetValue(service, out status))
                {
                    if (throwOnNotFound)
                    {
                        // TODO(jtattermusch): returning specific status from server handler is not supported yet.
                        throw new RpcException(new Status(StatusCode.NotFound, ""));
                    }
                    else
                    {
                        status = HealthCheckResponse.Types.ServingStatus.ServiceUnknown;
                    }
                }
                response = new HealthCheckResponse {
                    Status = status
                };
            }

            return(response);
        }
Exemple #10
0
        public static void UseCustomHealthCheck(this IApplicationBuilder app)
        {
            app.UseHealthChecks("/health", new HealthCheckOptions
            {
                AllowCachingResponses = false,
                ResponseWriter        = async(context, report) =>
                {
                    context.Response.ContentType = "application/json";
                    var response = new HealthCheckResponse
                    {
                        Status = report.Status.ToString(),
                        Checks = report.Entries.Select(x =>
                                                       new HealthCheck
                        {
                            Component   = x.Key,
                            Status      = x.Value.Status.ToString(),
                            Description = x.Value.Description,
                            Duration    = x.Value.Duration.ToString()
                        }),
                        Duration = report.TotalDuration.ToString()
                    };

                    await context.Response.WriteAsync(JsonSerializer.Serialize(response)).ConfigureAwait(true);
                }
            });
        }
        public async Task <HealthCheckResponse> GetHealthAsync(CancellationToken cancellationToken = default)
        {
            var healthCheckResponse = new HealthCheckResponse();
            var healthChecks        = ResolveDependencies();
            var sw = new Stopwatch();

            foreach (var task in healthChecks)
            {
                try
                {
                    cancellationToken.ThrowIfCancellationRequested();
                    sw.Reset();
                    sw.Start();
                    var result = await task.Value.CheckHealthAsync(cancellationToken);

                    sw.Stop();

                    healthCheckResponse.HealthChecks.Add(task.Key, new HealthCheckResultExtended(result)
                    {
                        ResponseTime = sw.ElapsedMilliseconds
                    });
                }
                catch (OperationCanceledException)
                {
                    throw;
                }
                catch
                {
                    healthCheckResponse.HealthChecks.Add(task.Key, new HealthCheckResultExtended(new HealthCheckResult(HealthStatus.Unhealthy)));
                }
            }

            return(healthCheckResponse);
        }
Exemple #12
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
                app.UseMigrationsEndPoint();
            }
            else
            {
                app.UseExceptionHandler("/Error");
                // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
                //app.UseHsts();
            }

            var swaggerOptions = new SwOptions.SwaggerOptions();

            Configuration.GetSection(nameof(SwaggerOptions)).Bind(swaggerOptions);

            app.UseSwagger(option =>
            {
                option.RouteTemplate = swaggerOptions.JsonRoute;
            });

            app.UseSwaggerUI(option =>
            {
                option.SwaggerEndpoint(swaggerOptions.UIEndpoint, swaggerOptions.Description);
            });

            app.UseHealthChecks("/health", new HealthCheckOptions
            {
                ResponseWriter = async(context, report) =>
                {
                    context.Response.ContentType = "application/json";

                    var response = new HealthCheckResponse
                    {
                        Status = report.Status.ToString(),
                        Checks = report.Entries.Select(x => new HealthCheck
                        {
                            Component   = x.Key,
                            Status      = x.Value.Status.ToString(),
                            Description = x.Value.Description
                        }),
                        Duration = report.TotalDuration
                    };

                    await context.Response.WriteAsync((JsonConvert.SerializeObject(response)));
                }
            });

            //app.UseHttpsRedirection();
            app.UseStaticFiles();

            app.UseRouting();

            app.UseAuthentication();
            app.UseAuthorization();

            app.UseEndpoints(endpoints => { endpoints.MapControllers(); });
        }
Exemple #13
0
        static async Task Main(string[] args)
        {
            AppContext.SetSwitch(
                "System.Net.Http.SocketsHttpHandler.Http2UnencryptedSupport", true);

            Channel channel = new Channel("healthchecker:5000",
                                          ChannelCredentials.Insecure);

            Health.HealthClient client = new Health.HealthClient(channel);

            while (true)
            {
                try
                {
                    var watch = System.Diagnostics.Stopwatch.StartNew();

                    HealthCheckResponse response = await client.CheckAsync(new HealthCheckRequest()
                    {
                        Service = "healthchecker"
                    });

                    watch.Stop();
                    Console.WriteLine("gRPC call to Healthchecker Server took " + watch.ElapsedMilliseconds + "ms");

                    response.Status.ToString();
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message + " " + ex.StackTrace);
                }

                System.Threading.Thread.Sleep(1000);
            }
        }
Exemple #14
0
 public static void InitializeHealthChecks(IApplicationBuilder app)
 {
     app.UseHealthChecks("/healthcheck", new HealthCheckOptions()
     {
         ResponseWriter = async(context, report) =>
         {
             context.Response.ContentType = "application/json";
             var Response = new HealthCheckResponse()
             {
                 Status = report.Status.ToString(),
                 Checks = report.Entries.Select(x => new HealthCheck
                 {
                     Status      = x.Value.Status.ToString(),
                     Component   = x.Key,
                     Description = x.Value.Description,
                     Duration    = x.Value.Duration
                 }),
                 Duration = report.TotalDuration
             };
             await context.Response.WriteAsync(
                 JsonConvert.SerializeObject(Response));
         }
     });
     AddSecurityToHealthCheck(app);
 }
        public async Task <IActionResult> HealthCheck(
            [HttpTrigger(AuthorizationLevel.Anonymous, "get", Route = "healthcheck")] HttpRequest req,
            ILogger log)
        {
            // list the categories
            try
            {
                // get the user ID
                if (!await this.UserAuthenticationService.GetUserIdAsync(req, out var userId, out var responseResult).ConfigureAwait(false))
                {
                    return(responseResult);
                }

                var healthCheckResponse = new HealthCheckResponse()
                {
                    Status      = HealthCheckStatus.OK,
                    Application = req.Host.Host,
                };

                return(new OkObjectResult(healthCheckResponse));
            }
            catch (Exception ex)
            {
                log.LogError(ex, UnhandledExceptionError);
                throw;
            }
        }
Exemple #16
0
        /// <summary>
        /// Determines whether the specified endpoint is connected to the specified service
        /// that responds with health status 'Serving' .
        /// </summary>
        /// <param name="healthClient"></param>
        /// <param name="serviceName"></param>
        /// <returns>StatusCode.OK if the service is healthy.</returns>
        public static async Task <StatusCode> IsServingAsync(
            [NotNull] Health.HealthClient healthClient,
            [NotNull] string serviceName)
        {
            StatusCode statusCode = StatusCode.Unknown;

            try
            {
                HealthCheckResponse healthResponse =
                    await healthClient.CheckAsync(new HealthCheckRequest()
                {
                    Service = serviceName
                });

                statusCode =
                    healthResponse.Status == HealthCheckResponse.Types.ServingStatus.Serving
                                                ? StatusCode.OK
                                                : StatusCode.ResourceExhausted;
            }
            catch (RpcException rpcException)
            {
                _msg.Debug($"Error checking health of service {serviceName}", rpcException);

                statusCode = rpcException.StatusCode;
            }
            catch (Exception e)
            {
                _msg.Debug($"Error checking health of service {serviceName}", e);
                return(statusCode);
            }

            return(statusCode);
        }
Exemple #17
0
        /// <summary>
        /// Determines whether the specified endpoint is connected to the specified service
        /// that responds with health status 'Serving' .
        /// </summary>
        /// <param name="healthClient"></param>
        /// <param name="serviceName"></param>
        /// <param name="statusCode">Status code from the RPC call</param>
        /// <returns></returns>
        public static bool IsServing([NotNull] Health.HealthClient healthClient,
                                     [NotNull] string serviceName,
                                     out StatusCode statusCode)
        {
            statusCode = StatusCode.Unknown;

            try
            {
                HealthCheckResponse healthResponse =
                    healthClient.Check(new HealthCheckRequest()
                {
                    Service = serviceName
                });

                statusCode = StatusCode.OK;

                return(healthResponse.Status == HealthCheckResponse.Types.ServingStatus.Serving);
            }
            catch (RpcException rpcException)
            {
                _msg.Debug($"Error checking health of service {serviceName}", rpcException);

                statusCode = rpcException.StatusCode;
            }
            catch (Exception e)
            {
                _msg.Debug($"Error checking health of service {serviceName}", e);
                return(false);
            }

            return(false);
        }
 /// <summary>
 /// Sets the health status for given service.
 /// </summary>
 /// <param name="service">The service. Cannot be null.</param>
 /// <param name="status">the health status</param>
 public void SetStatus(string service, HealthCheckResponse.Types.ServingStatus status)
 {
     lock (myLock)
     {
         statusMap[service] = status;
     }
 }
Exemple #19
0
        /// <summary>
        /// Tries to write the health check result data into HTTP response message.
        /// </summary>
        /// <param name="httpContext">Instance of <see cref="HttpContext"/>.</param>
        /// <param name="result">Instance of <see cref="HealthReport"/>.</param>
        /// <returns>A task.</returns>
        public static Task WriteResponse(HttpContext httpContext, HealthReport result)
        {
            _ = httpContext ?? throw new ArgumentNullException(nameof(httpContext));
            _ = result ?? throw new ArgumentNullException(nameof(result));

            httpContext.Response.ContentType = "application/json";

            var response = new HealthCheckResponse
            {
                Status       = Enum.GetName(result.Status),
                HealthChecks = result.Entries.Select(pair => new HealthCheckInfo
                {
                    Name   = pair.Key,
                    Report = new HealthCheckData
                    {
                        Status              = Enum.GetName(pair.Value.Status),
                        Description         = pair.Value.Description,
                        ElapsedMilliseconds = pair.Value.Duration.TotalMilliseconds,
                        Tags = pair.Value.Tags,
                        Data = pair.Value.Data
                    }
                })
            };

            return(httpContext.Response.WriteAsync(JsonSerializer.Serialize(response, new JsonSerializerOptions {
                WriteIndented = true
            })));
        }
 /// <summary>
 /// Sets the health status for given host and service.
 /// </summary>
 /// <param name="host">The host. Cannot be null.</param>
 /// <param name="service">The service. Cannot be null.</param>
 /// <param name="status">the health status</param>
 public void SetStatus(string host, string service, HealthCheckResponse.Types.ServingStatus status)
 {
     lock (myLock)
     {
         statusMap[CreateKey(host, service)] = status;
     }
 }
Exemple #21
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseHsts();
            }

            //health checks
            //  app.UseHealthChecks("/health");
            app.UseHealthChecks("/health", new HealthCheckOptions
            {
                ResponseWriter = async(context, report) =>
                {
                    context.Response.ContentType = "application/json";

                    var response = new HealthCheckResponse
                    {
                        Status = report.Status.ToString(),
                        Checks = report.Entries.Select(x => new HealthCheck
                        {
                            Component   = x.Key,
                            Status      = x.Value.Status.ToString(),
                            Description = x.Value.Description
                        }),
                        Duration = report.TotalDuration
                    };

                    await context.Response.WriteAsync(JsonConvert.SerializeObject(response));
                }
            });


            #region Swager#1
            var swaggerOptions = new SwaggerOptions();
            Configuration.GetSection(nameof(SwaggerOptions)).Bind(swaggerOptions);
            app.UseSwagger(options =>
            {
                options.RouteTemplate = swaggerOptions.JsonRoute;
            });

            app.UseSwaggerUI(options =>
            {
                options.SwaggerEndpoint(swaggerOptions.UIEndpoint, swaggerOptions.Description);
            });
            #endregion


            app.UseHttpsRedirection();
            app.UseStaticFiles();

            //JWT token
            app.UseAuthentication();
            //Its Ok
            app.UseMvc();
        }
 private void MarkDelayedHealthyResponseAsWarning(HealthCheckResponse healthCheckResponse, DateTime healthCheckRequestDate)
 {
     if (healthCheckResponse.ResponseStatus.Equals(HealthCheckResponseStatus.Success) &&
         (healthCheckResponse.MessageDate.Subtract(healthCheckRequestDate).TotalSeconds > _expectHealthResponseInSeconds))
     {
         healthCheckResponse.ResponseStatus = HealthCheckResponseStatus.Warning;
     }
 }
Exemple #23
0
        public override async Task <IResponseMessage> Process(HealthCheckRequest requestMessage)
        {
            var response = new HealthCheckResponse {
                AgentVersion = Configuration.Version,
            };

            return(await Task.FromResult(response));
        }
Exemple #24
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env, ILoggerFactory loggerFactory)
        {
            loggerFactory.AddLog4Net();

            app.Use((context, next) =>
            {
                context.Features.Get <IHttpMaxRequestBodySizeFeature>().MaxRequestBodySize = null;
                return(next.Invoke());
            });

            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            // setup api to work with proxy servers and load balancers
            app.UseForwardedHeaders(new ForwardedHeadersOptions
            {
                ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto
            });

            app.UseStaticFiles();

            app.UseRouting();

            app.UseCors(builder => builder
                        .AllowAnyHeader()
                        .AllowAnyMethod()
                        .AllowAnyOrigin()
                        .WithExposedHeaders(tusdotnet.Helpers.CorsHelper.GetExposedHeaders().Append("upload-data").ToArray()));

            app.UseStorageManager();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });

            app.UseHealthChecks("/health", new HealthCheckOptions
            {
                ResponseWriter = async(context, report) =>
                {
                    context.Response.ContentType = "application/json";
                    var response = new HealthCheckResponse
                    {
                        Status = report.Status.ToString(),
                        Checks = report.Entries.Select(x => new HealthCheck
                        {
                            Component   = x.Key,
                            Status      = x.Value.Status.ToString(),
                            Description = x.Value.Description
                        }),
                        Duration = report.TotalDuration
                    };
                    await context.Response.WriteAsync(Helpers.JsonSerialize(response));
                }
            });
        }
Exemple #25
0
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseCors(builder => builder.WithOrigins("http://localhost:4200").AllowAnyHeader().AllowAnyMethod());

            app.UseHealthChecks("/health", new HealthCheckOptions
            {
                ResponseWriter = async(context, report) =>
                {
                    context.Response.ContentType = "application/json";

                    var response = new HealthCheckResponse
                    {
                        Status = report.Status.ToString(),
                        Checks = report.Entries.Select(x => new HealthCheck
                        {
                            Component   = x.Key,
                            Status      = x.Value.Status.ToString(),
                            Description = x.Value.Description
                        }),
                        Duration = report.TotalDuration
                    };

                    await context.Response.WriteAsync(JsonConvert.SerializeObject(response));
                }
            });

            var swaggerOptions = new SwaggerOptions();

            Configuration.GetSection(nameof(SwaggerOptions)).Bind(swaggerOptions);

            app.UseSwagger(options =>
            {
                options.RouteTemplate = swaggerOptions.JsonRoute;
            });

            app.UseSwaggerUI(options =>
            {
                options.SwaggerEndpoint(swaggerOptions.UIEndpoint, swaggerOptions.Description);
            });

            app.UseHttpsRedirection();

            app.UseRouting();

            app.UseAuthorization();
            app.UseAuthentication();


            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });
        }
Exemple #26
0
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
                app.UseHsts();
            }

            app.UseHealthChecks("/health", new Microsoft.AspNetCore.Diagnostics.HealthChecks.HealthCheckOptions
            {
                ResponseWriter = async(context, report) =>
                {
                    context.Response.ContentType = "application/json";

                    var response = new HealthCheckResponse
                    {
                        Status = report.Status.ToString(),
                        Checks = report.Entries.Select(x => new HealthCheckss
                        {
                            Component   = x.Key,
                            Status      = x.Value.Status.ToString(),
                            Description = x.Value.Description
                        }),
                        Duration = report.TotalDuration
                    };

                    await context.Response.WriteAsync(JsonConvert.SerializeObject(response));
                }
            });

            app.UseHttpsRedirection();
            app.UseStaticFiles();

            app.UseResponseCaching();

            app.UseAuthentication();

            var swaggerOptions = new SwaggerOption();

            Configuration.GetSection(nameof(SwaggerOptions)).Bind(swaggerOptions);
            //nếu k cần lấy ngay giá trị đc bind, có thể dùng
            app.UseSwagger(options =>
            {
                options.RouteTemplate = swaggerOptions.JsonRoute;
            });
            app.UseSwaggerUI(options =>
            {
                options.SwaggerEndpoint(swaggerOptions.UIEndPoint, swaggerOptions.Description);
            });


            app.UseMvc();
        }
Exemple #27
0
        /// <summary>
        ///  健康检查报告
        /// </summary>
        /// <param name="httpContext"></param>
        /// <param name="result"></param>
        /// <returns></returns>
        private static Task WriteResponse(HttpContext httpContext, HealthReport result)
        {
            httpContext.Response.ContentType = "application/json";

            HealthCheckResponse healthCheckResponse = new HealthCheckResponse(result);
            var msg = healthCheckResponse.ToString();

            return(httpContext.Response.WriteAsync(msg));
        }
Exemple #28
0
        public async Task <HealthCheckResponse> GetHealthAsync(CancellationToken cancellationToken = default)
        {
            var healthCheckResults = new HealthCheckResponse();

            var tasks = _healthChecks.Select(c => new { name = c.Key, result = c.Value.CheckHealthAsync(cancellationToken) });

            var sw = new Stopwatch();

            foreach (var task in tasks)
            {
                try
                {
                    cancellationToken.ThrowIfCancellationRequested();

                    sw.Reset();
                    sw.Start();
                    var result = await task.result;
                    sw.Stop();

                    healthCheckResults.Entries.Add(task.name, new HealthCheckResultExtended(result)
                    {
                        ResponseTime = sw.ElapsedMilliseconds
                    });
                }
                catch (OperationCanceledException)
                {
                    throw;
                }
                catch
                {
                    healthCheckResults.Entries.Add(task.name, new HealthCheckResultExtended(new HealthCheckResult(HealthStatus.Unhealthy)));
                }
            }

            var status = HealthStatus.Healthy;

            //Extrair pra classe
            foreach (var healthCheckResultExtended in healthCheckResults.Entries.Values)
            {
                if (healthCheckResultExtended.Status == HealthStatus.Unhealthy)
                {
                    status = HealthStatus.Unhealthy;
                    break;
                }

                if (healthCheckResultExtended.Status == HealthStatus.Degraded)
                {
                    status = HealthStatus.Degraded;
                }
            }
            //Classe

            healthCheckResults.OverAllStatus     = status;
            healthCheckResults.TotalResponseTime = healthCheckResults.Entries.Values.Sum(c => c.ResponseTime);

            return(healthCheckResults);
        }
        public void ShouldReturnDegraded()
        {
            var sut = new HealthCheckResponse();

            sut.Entries.Add("AnyName", HealthyResult);
            sut.Entries.Add("AnyAnotherName", DegradedResult);

            Assert.Equal(HealthStatus.Degraded, sut.OverAllStatus);
        }
Exemple #30
0
 public override async Task Watch(HealthCheckRequest request, IServerStreamWriter <HealthCheckResponse> responseStream, ServerCallContext context)
 {
     var status   = GetAPIServingStatus();
     var response = new HealthCheckResponse()
     {
         Status = status
     };
     await responseStream.WriteAsync(response);
 }
Exemple #31
0
        public void IsActive()
        {
            DecidirConnector    decidir  = new DecidirConnector(Ambiente.AMBIENTE_SANDBOX, "", "");
            HealthCheckResponse response = decidir.HealthCheck();

            Assert.AreEqual(true, response.buildTime != null);
            Assert.AreEqual(true, response.name != null);
            Assert.AreEqual(true, response.version != null);
        }
        public void ShouldSumCorrectly()
        {
            var sut = new HealthCheckResponse();

            sut.Entries.Add("AnyName", HealthyResult);
            sut.Entries.Add("AnyAnotherName", DegradedResult);
            sut.Entries.Add("UnhealthyAnotherName", UnhealthyResult);

            Assert.Equal(3, sut.TotalResponseTime);
        }
        public ModuleSelectionPresenter()
        {
            deviceList = new List<DeviceEntity>();
            objKiosk = new monitoringProxy.DeviceEntity();
            objPrinter = new monitoringProxy.DeviceEntity();
            objCashAcceptor = new monitoringProxy.DeviceEntity();
            objServiceResponse = new HealthCheckResponse();
            IsBackendServiceConnected = InitConnectivityPolling();

            pollcounter = Convert.ToInt16(string.IsNullOrWhiteSpace(ConfigurationManager.AppSettings["PUSHMONITORINGUPDATECOUNT"]) ? "10" : ConfigurationManager.AppSettings["PUSHMONITORINGUPDATECOUNT"]);

            //if (bool.Parse(ConfigurationManager.AppSettings["StandAloneMode"]) == false)
            //    IsBackendServiceConnected = InitConnectivityPolling();
            //else
            //    IsBackendServiceConnected = true;
        }