Пример #1
0
        public void Configure(IApplicationBuilder app)
        {
            app.UseRouting();
            app.UseEndpoints(endpoints =>
            {
                endpoints.MapMetrics();

                endpoints.MapGet("/ping", (ctx) =>
                {
                    return(ctx.Response.WriteAsync("ok"));
                });

                endpoints.MapGet("/healthz", async(ctx) =>
                {
                    var healthMonitor        = ctx.RequestServices.GetRequiredService <IConsecutiveHealthMonitor>();
                    var uptimeMonitor        = ctx.RequestServices.GetRequiredService <IUptimeMonitor>();
                    var podOptions           = ctx.RequestServices.GetRequiredService <IOptions <PodIdentifierOptions> >();
                    var healthOptions        = ctx.RequestServices.GetRequiredService <IOptions <WatchdogHealthzOptions> >();
                    var lf                   = ctx.RequestServices.GetRequiredService <ILoggerFactory>();
                    var logger               = lf.CreateLogger <WatchdogHealthz>();
                    var ns                   = podOptions.Value.Namespace ?? string.Empty;
                    var name                 = podOptions.Value.Name ?? string.Empty;
                    var alwaysHealthySeconds = healthOptions.Value.AlwaysHealthyAfterSeconds.GetValueOrDefault();
                    if (ns == string.Empty)
                    {
                        throw new ArgumentNullException(nameof(podOptions.Value.Namespace));
                    }

                    if (name == string.Empty)
                    {
                        throw new ArgumentNullException(nameof(podOptions.Value.Name));
                    }

                    var uptime = uptimeMonitor.Uptime;
                    if (alwaysHealthySeconds > 0 && uptime > TimeSpan.FromSeconds(alwaysHealthySeconds))
                    {
                        logger.LogInformation("Uptime {uptime} surpassed {alwaysHealthySeconds}: success", uptime.ToString(), alwaysHealthySeconds);
                        ctx.Response.StatusCode = 200;
                    }

                    var podid = new PodIdentifier(ns, name);
                    await healthMonitor.Probe(podid);

                    if (healthMonitor.IsHealthy(podid))
                    {
                        logger.LogInformation("Pod {podId} is healthy", podid.ToString());
                        ctx.Response.StatusCode = 200;
                        return;
                    }

                    logger.LogInformation("Pod {podId} is not healthy or has not been for long enough", podid.ToString());
                    ctx.Response.StatusCode = 500;
                });
            });
        }