Exemplo n.º 1
0
        public async Task <LivenessResult> IsHealthy(LivenessExecutionContext context, CancellationToken cancellationToken = default)
        {
            try
            {
                _logger?.LogInformation($"{nameof(DnsResolveLiveness)} is checking DNS entries.");

                foreach (var item in _options.ConfigureHosts.Values)
                {
                    var ipAddresses = await Dns.GetHostAddressesAsync(item.Host);

                    foreach (var ipAddress in ipAddresses)
                    {
                        if (!item.Resolutions.Contains(ipAddress.ToString()))
                        {
                            _logger?.LogWarning($"The {nameof(DnsResolveLiveness)} check fail for {ipAddress} was not resolved from host {item.Host}.");

                            return(LivenessResult.UnHealthy("Ip Address {ipAddress} was not resolved from host {item.Host}"));
                        }
                    }
                }

                _logger?.LogInformation($"The {nameof(DnsResolveLiveness)} check success.");

                return(LivenessResult.Healthy());
            }
            catch (Exception ex)
            {
                _logger?.LogWarning($"The {nameof(DnsResolveLiveness)} check fail with the exception {ex.ToString()}.");

                return(LivenessResult.UnHealthy(ex));
            }
        }
Exemplo n.º 2
0
        public Task <LivenessResult> IsHealthy(LivenessExecutionContext context, CancellationToken cancellationToken = new CancellationToken())
        {
            try
            {
                _logger?.LogInformation($"{nameof(RabbitMQLiveness)} is checking the RabbitMQ host.");

                var factory = new ConnectionFactory()
                {
                    Uri = new Uri(_rabbitMqConnectionString)
                };

                using (var connection = factory.CreateConnection())
                    using (var channel = connection.CreateModel())
                    {
                        _logger?.LogInformation($"The {nameof(RabbitMQLiveness)} check success.");

                        return(Task.FromResult(
                                   LivenessResult.Healthy()));
                    }
            }
            catch (Exception ex)
            {
                _logger?.LogWarning($"The {nameof(RabbitMQLiveness)} check fail with the exception {ex.ToString()}.");

                return(Task.FromResult(
                           LivenessResult.UnHealthy(ex)));
            }
        }
Exemplo n.º 3
0
        public async Task <LivenessResult> IsHealthy(LivenessExecutionContext context, CancellationToken cancellationToken = default)
        {
            try
            {
                _logger?.LogInformation($"{nameof(IdSvrLiveness)} is checking the IdSvr on {_idSvrUri}.");

                using (var httpClient = new HttpClient()
                {
                    BaseAddress = _idSvrUri
                })
                {
                    var response = await httpClient.GetAsync(IDSVR_DISCOVER_CONFIGURATION_SEGMENT);

                    if (!response.IsSuccessStatusCode)
                    {
                        _logger?.LogWarning($"The {nameof(IdSvrLiveness)} check failed for server {_idSvrUri}.");

                        return(LivenessResult.UnHealthy("Discover endpoint is not responding with 200 OK, the current status is {response.StatusCode} and the content { (await response.Content.ReadAsStringAsync())}"));
                    }

                    _logger?.LogInformation($"The {nameof(IdSvrLiveness)} check success.");

                    return(LivenessResult.Healthy());
                }
            }
            catch (Exception ex)
            {
                _logger?.LogWarning($"The {nameof(IdSvrLiveness)} check fail for IdSvr with the exception {ex.ToString()}.");

                return(LivenessResult.UnHealthy(ex));
            }
        }
Exemplo n.º 4
0
        public async Task <LivenessResult> IsHealthy(LivenessExecutionContext context, CancellationToken cancellationToken = default)
        {
            try
            {
                _logger?.LogInformation($"{nameof(AzureServiceBusTopicLiveness)} is checking the Azure Topic.");

                var topicClient = new TopicClient(_connectionString, _topicName);

                var scheduledMessageId = await topicClient.ScheduleMessageAsync(
                    new Message(Encoding.UTF8.GetBytes(TEST_MESSAGE)),
                    new DateTimeOffset(DateTime.UtcNow).AddHours(2));

                await topicClient.CancelScheduledMessageAsync(scheduledMessageId);

                _logger?.LogInformation($"The {nameof(AzureServiceBusTopicLiveness)} check success.");

                return(LivenessResult.Healthy());
            }
            catch (Exception ex)
            {
                _logger?.LogWarning($"The {nameof(AzureServiceBusTopicLiveness)} check fail for {_connectionString} with the exception {ex.ToString()}.");

                return(LivenessResult.UnHealthy(ex));
            }
        }
Exemplo n.º 5
0
        public async Task <LivenessResult> IsHealthy(LivenessExecutionContext context, CancellationToken cancellationToken = default)
        {
            var configuredHosts = _options.ConfiguredHosts.Values;

            try
            {
                _logger?.LogInformation($"{nameof(PingLiveness)} is checking hosts.");

                foreach (var(host, timeout) in configuredHosts)
                {
                    using (var ping = new Ping())
                    {
                        var pingReply = await ping.SendPingAsync(host, timeout);

                        if (pingReply.Status != IPStatus.Success)
                        {
                            _logger?.LogWarning($"The {nameof(PingLiveness)} check failed for host {host} is failed with status reply:{pingReply.Status}.");

                            return(LivenessResult.UnHealthy($"Ping check for host {host} is failed with status reply:{pingReply.Status}"));
                        }
                    }
                }

                _logger?.LogInformation($"The {nameof(PingLiveness)} check success.");

                return(LivenessResult.Healthy());
            }
            catch (Exception ex)
            {
                _logger?.LogWarning($"The {nameof(PingLiveness)} check fail with the exception {ex.ToString()}.");

                return(LivenessResult.UnHealthy(ex));
            }
        }
Exemplo n.º 6
0
        public async Task default_timeout_option_can_be_override_with_querystring_parameter()
        {
            var webHostBuilder = new WebHostBuilder()
                                 .UseBeatPulse(options => options.ConfigureTimeout(milliseconds: 100))
                                 .UseStartup <DefaultStartup>()
                                 .ConfigureServices(svc =>
            {
                svc.AddBeatPulse(setup =>
                {
                    setup.AddLiveness("test", opt =>
                    {
                        opt.UsePath("test");
                        opt.UseLiveness(new ActionLiveness(async ct =>
                        {
                            await Task.Delay(200);

                            return(LivenessResult.Healthy());
                        }));
                    });
                });
            });

            var server = new TestServer(webHostBuilder);

            var response = await server.CreateClient()
                           .GetAsync($"{BeatPulseKeys.BEATPULSE_DEFAULT_PATH}?DetailedOutput=true");

            response.StatusCode.Should().Be(StatusCodes.Status503ServiceUnavailable);

            response = await server.CreateClient()
                       .GetAsync($"{BeatPulseKeys.BEATPULSE_DEFAULT_PATH}?DetailedOutput=true&Timeout=900");

            response.StatusCode.Should().Be(StatusCodes.Status200OK);
        }
Exemplo n.º 7
0
        public async Task <LivenessResult> IsHealthy(LivenessExecutionContext context, CancellationToken cancellationToken = default)
        {
            try
            {
                using (var connection = new SqliteConnection(_connectionString))
                {
                    _logger?.LogInformation($"{nameof(SqliteLiveness)} is checking the Sqlite using the query {_sql}.");

                    await connection.OpenAsync(cancellationToken);

                    using (var command = connection.CreateCommand())
                    {
                        command.CommandText = _sql;
                        await command.ExecuteScalarAsync();
                    }

                    _logger?.LogInformation($"The {nameof(SqliteLiveness)} check success for {_connectionString}");

                    return(LivenessResult.Healthy());
                }
            }
            catch (Exception ex)
            {
                _logger?.LogWarning($"The {nameof(SqliteLiveness)} check fail for {_connectionString} with the exception {ex.ToString()}.");

                return(LivenessResult.UnHealthy(ex));
            }
        }
Exemplo n.º 8
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.Configure <CookiePolicyOptions>(options =>
            {
                // This lambda determines whether user consent for non-essential cookies is needed for a given request.
                options.CheckConsentNeeded    = context => true;
                options.MinimumSameSitePolicy = SameSiteMode.None;
            });


            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);

            services.AddCors();

            services.AddBeatPulse(setup =>
            {
                setup.AddLiveness("sample", opt =>
                {
                    opt.UsePath("path");
                    opt.UseLiveness(new ActionLiveness((_) =>
                    {
                        return(Task.FromResult(
                                   LivenessResult.Healthy()));
                    }));
                });
            });
        }
Exemplo n.º 9
0
        public void get_valid_prometheus_metrics_content_with_custom_labels()
        {
            string path = "sql";
            string name = "liveness1";

            var customLabels = new Dictionary <string, string>()
            {
                { "labelA", "valueA" },
                { "labelB", "valueB" },
            };

            var livenessResult = new LivenessResult(name, path);

            livenessResult.StartCounter();
            livenessResult.StopCounter("ok", true);

            var prometheusMetrics = livenessResult.GetPrometheusMetrics(customLabels);

            prometheusMetrics
            .Should()
            .Contain($"beatpulse_pulse_execution_time_seconds{{labelA=\"valueA\",labelB=\"valueB\",ApplicationName=\"testhost\",Path=\"{path}\",Name=\"{name}\"}}");

            prometheusMetrics
            .Should()
            .Contain($"beatpulse_pulse_ishealthy{{labelA=\"valueA\",labelB=\"valueB\",ApplicationName=\"testhost\",Path=\"{path}\",Name=\"{name}\"}}");
        }
Exemplo n.º 10
0
        private async Task <LivenessResult> ExecuteAuthenticatedUserActions()
        {
            var(User, Password) = _options.AccountOptions.Account;

            if (await _imapConnection.AuthenticateAsync(User, Password))
            {
                if (_options.FolderOptions.CheckFolder &&
                    !await _imapConnection.SelectFolder(_options.FolderOptions.FolderName))
                {
                    _logger?.LogWarning($"{nameof(ImapLiveness)} fail connect to server {_options.Host}- SSL Enabled : {_options.ConnectionType} and open folder {_options.FolderOptions.FolderName}.");

                    return(LivenessResult.UnHealthy($"Folder {_options.FolderOptions.FolderName} check failed."));
                }

                _logger?.LogInformation($"The {nameof(ImapLiveness)} check success.");

                return(LivenessResult.Healthy());
            }
            else
            {
                _logger?.LogWarning($"{nameof(ImapLiveness)} fail connect to server {_options.Host}- SSL Enabled : {_options.ConnectionType}.");

                return(LivenessResult.UnHealthy($"Login on server {_options.Host} failed with configured user"));
            }
        }
Exemplo n.º 11
0
        static string GetLabels(LivenessResult response, IDictionary <string, string> prometheusLabels = null)
        {
            var labelsBuilder = new StringBuilder();

            var ApplicationName = @Assembly.GetEntryAssembly().GetName().Name;

            if (prometheusLabels != null)
            {
                if (prometheusLabels.ContainsKey(nameof(ApplicationName)))
                {
                    ApplicationName = prometheusLabels[nameof(ApplicationName)];
                }

                foreach (var entry in prometheusLabels)
                {
                    labelsBuilder.Append($"{entry.Key}=\"{entry.Value}\",");
                }
            }

            labelsBuilder.Append($"{nameof(ApplicationName)}=\"{ApplicationName}\",");
            labelsBuilder.Append($"{nameof(response.Path)}=\"{response.Path}\",");
            labelsBuilder.Append($"{nameof(response.Name)}=\"{response.Name}\",");


            labelsBuilder.Length -= 1; // remove latest ,

            return($"{{{labelsBuilder.ToString()}}}");
        }
Exemplo n.º 12
0
        public async Task <LivenessResult> IsHealthy(LivenessExecutionContext context, CancellationToken cancellationToken = default(CancellationToken))
        {
            try
            {
                var response = await _httpClient.GetAsync("_cluster/health");

                response.EnsureSuccessStatusCode();
                var json = await response.Content.ReadAsStringAsync();

                var results = JsonConvert.DeserializeObject <ClusterHealth>(json);

                switch (results.status)
                {
                case ClusterStatus.Green:
                    return(LivenessResult.Healthy("Green"));

                case ClusterStatus.Yellow:
                    return(LivenessResult.Healthy("Yellow (no replicas)"));

                case ClusterStatus.Red:
                    return(LivenessResult.UnHealthy("Red"));

                default:
                    return(LivenessResult.UnHealthy("Unknown status - " + results.status));
                }
            }
            catch (Exception ex)
            {
                return(LivenessResult.UnHealthy(ex));
            }
        }
Exemplo n.º 13
0
        public async Task <LivenessResult> IsHealthy(LivenessExecutionContext context, CancellationToken cancellationToken = default)
        {
            try
            {
                _logger?.LogInformation($"{nameof(MySqlLiveness)} is checking the MySql.");

                using (var connection = new MySqlConnection(_connectionString))
                {
                    await connection.OpenAsync(cancellationToken);

                    if (!await connection.PingAsync(cancellationToken))
                    {
                        _logger?.LogWarning($"The {nameof(MySqlLiveness)} check fail for {_connectionString}.");

                        return(LivenessResult.UnHealthy($"The {nameof(MySqlLiveness)} check fail."));
                    }

                    _logger?.LogInformation($"The {nameof(MySqlLiveness)} check success for {_connectionString}");

                    return(LivenessResult.Healthy());
                }
            }
            catch (Exception ex)
            {
                _logger?.LogWarning($"The {nameof(MySqlLiveness)} check fail for {_connectionString} with the exception {ex.ToString()}.");

                return(LivenessResult.UnHealthy(ex));
            }
        }
Exemplo n.º 14
0
        public async Task <LivenessResult> IsHealthy(LivenessExecutionContext context, CancellationToken cancellationToken = default)
        {
            try
            {
                _logger?.LogInformation($"{nameof(KafkaLiveness)} is checking the Kafka broker.");

                using (var producer = new Producer <Null, string>(_configuration, null, new StringSerializer(Encoding.UTF8)))
                {
                    var result = await producer.ProduceAsync("beatpulse-topic", null, $"Check Kafka healthy on {DateTime.UtcNow}");

                    if (result.Error.Code != ErrorCode.NoError)
                    {
                        _logger?.LogWarning($"The {nameof(KafkaLiveness)} check failed.");

                        return(LivenessResult.UnHealthy($"ErrorCode {result.Error.Code} with reason ('{result.Error.Reason}')"));
                    }

                    _logger?.LogInformation($"The {nameof(KafkaLiveness)} check success.");

                    return(LivenessResult.Healthy());
                }
            }
            catch (Exception ex)
            {
                _logger?.LogWarning($"The {nameof(KafkaLiveness)} check fail for Kafka broker with the exception {ex.ToString()}.");

                return(LivenessResult.UnHealthy(ex));
            }
        }
        public async Task <LivenessResult> IsHealthy(LivenessExecutionContext context, CancellationToken cancellationToken = default)
        {
            try
            {
                _logger?.LogInformation($"{nameof(AzureEventHubLiveness)} is checking the Azure Event Hub.");

                var connectionStringBuilder = new EventHubsConnectionStringBuilder(_connectionString)
                {
                    EntityPath = _eventHubName
                };

                var eventHubClient = EventHubClient
                                     .CreateFromConnectionString(connectionStringBuilder.ToString());

                await eventHubClient.GetRuntimeInformationAsync();

                _logger?.LogInformation($"The {nameof(AzureEventHubLiveness)} check success.");

                return(LivenessResult.Healthy());
            }
            catch (Exception ex)
            {
                _logger?.LogWarning($"The {nameof(AzureEventHubLiveness)} check fail for {_connectionString} with the exception {ex.ToString()}.");

                return(LivenessResult.UnHealthy(ex));
            }
        }
Exemplo n.º 16
0
        public async Task <LivenessResult> IsHealthy(LivenessExecutionContext context, CancellationToken cancellationToken = default)
        {
            try
            {
                _logger?.LogInformation($"{nameof(TcpLiveness)} is checking hosts.");

                foreach (var(host, port) in _options.ConfiguredHosts)
                {
                    using (var tcpClient = new TcpClient())
                    {
                        await tcpClient.ConnectAsync(host, port);

                        if (!tcpClient.Connected)
                        {
                            _logger?.LogWarning($"The {nameof(TcpLiveness)} check failed for host {host} and port {port}.");

                            return(LivenessResult.UnHealthy($"Connection to host {host}:{port} failed"));
                        }
                    }
                }

                _logger?.LogInformation($"The {nameof(TcpLiveness)} check success.");

                return(LivenessResult.Healthy());
            }
            catch (Exception ex)
            {
                _logger?.LogWarning($"The {nameof(TcpLiveness)} check fail with the exception {ex.ToString()}.");

                return(LivenessResult.UnHealthy(ex));
            }
        }
Exemplo n.º 17
0
        public Task Track(LivenessResult livenessResult)
        {
            var properties = new Dictionary <string, string>()
            {
                { nameof(livenessResult.IsHealthy), livenessResult.IsHealthy.ToString(CultureInfo.InvariantCulture) },
                { nameof(livenessResult.Run), livenessResult.Run.ToString(CultureInfo.InvariantCulture) },
                { nameof(livenessResult.Path), livenessResult.Path },
                { nameof(livenessResult.Name), livenessResult.Name },
                { nameof(Environment.MachineName), Environment.MachineName },
                { nameof(Assembly), Assembly.GetEntryAssembly().GetName().Name }
            };

            var metrics = new Dictionary <string, double>()
            {
                { RESPONSE_TIME_METRIC_NAME, livenessResult.Elapsed.TotalMilliseconds },
                { AVAILABILITY_METRIC_NAME, livenessResult.IsHealthy ? 1 : 0 }
            };

            var configuration = String.IsNullOrWhiteSpace(_instrumentationKey) ? TelemetryConfiguration.Active : new TelemetryConfiguration(_instrumentationKey);

            new TelemetryClient(configuration)
            .TrackEvent(EVENT_NAME, properties, metrics);

            return(Task.CompletedTask);
        }
Exemplo n.º 18
0
        public Task <LivenessResult> IsHealthy(LivenessExecutionContext context, CancellationToken cancellationToken = default)
        {
            try
            {
                _logger?.LogInformation($"{nameof(RedisLiveness)} is checking the Redis status.");

                ConnectionMultiplexer connection;

                if (!_connections.TryGetValue(_redisConnectionString, out connection))
                {
                    connection = ConnectionMultiplexer.Connect(_redisConnectionString);

                    if (!_connections.TryAdd(_redisConnectionString, connection))
                    {
                        return(Task.FromResult(
                                   LivenessResult.UnHealthy("Redis connection can't be added into the dictionary.")));
                    }
                }

                connection.GetDatabase()
                .Ping();

                _logger?.LogInformation($"The {nameof(RedisLiveness)} check success.");

                return(Task.FromResult(
                           LivenessResult.Healthy()));
            }
            catch (Exception ex)
            {
                _logger?.LogWarning($"The {nameof(RedisLiveness)} check fail with the exception {ex.ToString()}.");

                return(Task.FromResult(
                           LivenessResult.UnHealthy(ex)));
            }
        }
Exemplo n.º 19
0
        public async Task <LivenessResult> IsHealthy(LivenessExecutionContext context, CancellationToken cancellationToken = default)
        {
            try
            {
                _logger?.LogInformation($"{nameof(FtpLiveness)} is checking FTP connections.");

                foreach (var item in _options.Hosts.Values)
                {
                    var ftpRequest = CreateFtpWebRequest(item.host, item.createFile, item.credentials);

                    using (var ftpResponse = (FtpWebResponse)await ftpRequest.GetResponseAsync())
                    {
                        if (ftpResponse.StatusCode != FtpStatusCode.PathnameCreated &&
                            ftpResponse.StatusCode != FtpStatusCode.ClosingData)
                        {
                            _logger?.LogWarning($"The {nameof(FtpLiveness)} check fail for ftp host {item.host} with exit code {ftpResponse.StatusCode}.");

                            LivenessResult.UnHealthy($"Error connecting to ftp host {item.host} with exit code {ftpResponse.StatusCode}");
                        }
                    }
                }

                _logger?.LogInformation($"The {nameof(FtpLiveness)} check success.");

                return(LivenessResult.Healthy());
            }
            catch (Exception ex)
            {
                _logger?.LogWarning($"The {nameof(FtpLiveness)} check fail with the exception {ex.ToString()}.");

                return(LivenessResult.UnHealthy(ex));
            }
        }
Exemplo n.º 20
0
 public async Task Track(LivenessResult response)
 {
     if (response.IsHealthy)
     {
         await _statusPageClient.SolveIncident();
     }
     else
     {
         await _statusPageClient.CreateIncident(response.Message);
     }
 }
Exemplo n.º 21
0
        public static string GetPrometheusMetrics(this LivenessResult response, IDictionary <string, string> prometheusLabels = null)
        {
            var builder = new StringBuilder();

            var labels = GetLabels(response, prometheusLabels);

            builder.Append($"beatpulse_pulse_execution_time_seconds{labels} { ((double)response.MilliSeconds / 1000)}\n");
            builder.Append($"beatpulse_pulse_ishealthy{labels} {Convert.ToInt32(response.IsHealthy)}\n");

            return(builder.ToString());
        }
Exemplo n.º 22
0
        public async Task <LivenessResult> IsHealthy(LivenessExecutionContext context, CancellationToken cancellationToken = default)
        {
            var defaultHttpMethod = _options.HttpMethod;
            var defaultCodes      = _options.ExpectedHttpCodes;
            var idx = 0;

            try
            {
                _logger?.LogInformation($"{nameof(UriLiveness)} is checking configured uri's.");

                foreach (var item in _options.UrisOptions)
                {
                    var method        = item.HttpMethod ?? defaultHttpMethod;
                    var expectedCodes = item.ExpectedHttpCodes ?? defaultCodes;

                    if (cancellationToken.IsCancellationRequested)
                    {
                        return(LivenessResult.UnHealthy($"Liveness execution is cancelled."));
                    }

                    using (var httpClient = new HttpClient())
                    {
                        var requestMessage = new HttpRequestMessage(method, item.Uri);

                        foreach (var header in item.Headers)
                        {
                            requestMessage.Headers.Add(header.Name, header.Value);
                        }

                        var response = await httpClient.SendAsync(requestMessage);

                        if (!((int)response.StatusCode >= expectedCodes.Min && (int)response.StatusCode <= expectedCodes.Max))
                        {
                            _logger?.LogWarning($"The {nameof(UriLiveness)} check fail for uri {item.Uri}.");

                            return(LivenessResult.UnHealthy($"Discover endpoint #{idx} is not responding with code in {expectedCodes.Min}...{expectedCodes.Max} range, the current status is {response.StatusCode}."));
                        }

                        ++idx;
                    }
                }

                _logger?.LogDebug($"The {nameof(UriLiveness)} check success.");

                return(LivenessResult.Healthy());
            }
            catch (Exception ex)
            {
                _logger?.LogWarning($"The {nameof(UriLiveness)} check fail with the exception {ex.ToString()}.");

                return(LivenessResult.UnHealthy(ex));
            }
        }
Exemplo n.º 23
0
 public Task <LivenessResult> IsHealthy(LivenessExecutionContext context, CancellationToken cancellationToken = default)
 {
     try
     {
         throw _throwException();
     }
     catch (Exception ex)
     {
         return(Task.FromResult(
                    LivenessResult.UnHealthy(ex)));
     }
 }
Exemplo n.º 24
0
        public Task <LivenessResult> IsHealthy(LivenessExecutionContext context, CancellationToken cancellationToken = default)
        {
            var currentValue = currentValueFunc();

            if (currentValue.CompareTo(maximunValue) <= 0)
            {
                return(Task.FromResult(
                           LivenessResult.Healthy()));
            }

            return(Task.FromResult(
                       LivenessResult.UnHealthy($"Maximun={maximunValue}, Current={currentValue}")));
        }
Exemplo n.º 25
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.Configure <CookiePolicyOptions>(options =>
            {
                // This lambda determines whether user consent for non-essential cookies is needed for a given request.
                options.CheckConsentNeeded    = context => true;
                options.MinimumSameSitePolicy = SameSiteMode.None;
            });

            services.AddBeatPulse(setup =>
            {
                //
                //configure a sample ad-hoc liveness
                //

                setup.AddLiveness("catapi", opt =>
                {
                    opt.UsePath("catapi");
                    opt.UseLiveness(new ActionLiveness((_) =>
                    {
                        if ((DateTime.Now.Second & 1) == 1)
                        {
                            return(Task.FromResult(LivenessResult.UnHealthy("liveness is not working")));
                        }

                        return(Task.FromResult(LivenessResult.Healthy()));
                    }));
                });

                //
                //add trackers
                //

                setup.AddApplicationInsightsTracker();

                //setup.AddPrometheusTracker(new Uri("http://localhost:9091"), new Dictionary<string, string>()
                //{
                //    {"MachineName",Environment.MachineName}
                //});

                //setup.AddStatusPageTracker(opt =>
                //{
                //    opt.PageId = "your-page-id";
                //    opt.ComponentId = "your-component-id";
                //    opt.ApiKey = "your-api.key";
                //    opt.IncidentName = "BeatPulse mark this component as outage";
                //});
            });

            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
        }
Exemplo n.º 26
0
        public async Task break_the_liveness_execution_if_detailed_output_is_disabled()
        {
            var check1IsExecuted = false;
            var check2IsExecuted = false;

            var healthCheck1 = new ActionLiveness(
                (cancellationToken) =>
            {
                check1IsExecuted = true;
                return(Task.FromResult(LivenessResult.UnHealthy("custom check1 is not working")));
            });

            var healthCheck2 = new ActionLiveness(
                (cancellationToken) =>
            {
                check2IsExecuted = false;
                return(Task.FromResult(LivenessResult.Healthy()));
            });

            var webHostBuilder = new WebHostBuilder()
                                 .UseBeatPulse()
                                 .UseStartup <DefaultStartup>()
                                 .ConfigureServices(svc =>
            {
                svc.AddBeatPulse(context =>
                {
                    context.AddLiveness("check1", opt =>
                    {
                        opt.UsePath("check1");
                        opt.UseLiveness(healthCheck1);
                    });
                    context.AddLiveness("check2", opt =>
                    {
                        opt.UsePath("check2");
                        opt.UseLiveness(healthCheck2);
                    });
                });
            });

            var server = new TestServer(webHostBuilder);

            var response = await server.CreateClient()
                           .GetAsync(BeatPulseKeys.BEATPULSE_DEFAULT_PATH);

            response.StatusCode
            .Should().Be(StatusCodes.Status503ServiceUnavailable);

            check1IsExecuted.Should().BeTrue();
            check2IsExecuted.Should().BeFalse();
        }
        public Task Track(LivenessResult response)
        {
            const string PROMETHEUS_METRIC_JOB_PATH = "metrics/jobs/beatpulse";

            //this tracker use prometheus gateway to send
            //liveness results into prometheus with a push model
            //for more information about prometheus please read https://prometheus.io/

            var prometheusMetrics = response.GetPrometheusMetrics(_prometheusLabels);

            var content = new StringContent(prometheusMetrics, Encoding.UTF8, "multipart/form-data");

            return(_httpClient.PostAsync(PROMETHEUS_METRIC_JOB_PATH, content));
        }
Exemplo n.º 28
0
        public Task <LivenessResult> IsHealthy(LivenessExecutionContext context, CancellationToken cancellationToken = default)
        {
            try
            {
                _logger?.LogInformation($"{nameof(SftpLiveness)} is checking SFTP connections.");

                foreach (var item in _options.ConfiguredHosts.Values)
                {
                    var connectionInfo = new ConnectionInfo(item.Host, item.UserName, item.AuthenticationMethods.ToArray());

                    using (var sftpClient = new SftpClient(connectionInfo))
                    {
                        sftpClient.Connect();

                        var connectionSuccess = sftpClient.IsConnected && sftpClient.ConnectionInfo.IsAuthenticated;

                        if (connectionSuccess)
                        {
                            if (item.FileCreationOptions.createFile)
                            {
                                using (var stream = new MemoryStream(new byte[] { 0x0 }, 0, 1))
                                {
                                    sftpClient.UploadFile(stream, item.FileCreationOptions.remoteFilePath);
                                }
                            }
                        }
                        else
                        {
                            _logger?.LogWarning($"The {nameof(SftpLiveness)} check fail for sftp host {item.Host}.");

                            return(Task.FromResult(
                                       LivenessResult.UnHealthy($"Connection with sftp host {item.Host}:{item.Port} failed")));
                        }
                    }
                }

                _logger?.LogInformation($"The {nameof(SftpLiveness)} check success.");

                return(Task.FromResult(
                           LivenessResult.Healthy()));
            }
            catch (Exception ex)
            {
                _logger?.LogWarning($"The {nameof(SftpLiveness)} check fail with the exception {ex.ToString()}.");

                return(Task.FromResult(
                           LivenessResult.UnHealthy(ex)));
            }
        }
Exemplo n.º 29
0
        public async Task <LivenessResult> IsHealthy(LivenessExecutionContext context, CancellationToken cancellationToken = default(CancellationToken))
        {
            try
            {
                var tokenCredentials = await GetTokenCredentials(_clientID, _clientSecret, _tenantID);

                var relayManagementClient = new RelayManagementClient(tokenCredentials);

                return(LivenessResult.Healthy());
            }
            catch (Exception ex)
            {
                return(LivenessResult.UnHealthy(ex));
            }
        }
Exemplo n.º 30
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.Configure <CookiePolicyOptions>(options =>
            {
                // This lambda determines whether user consent for non-essential cookies is needed for a given request.
                options.CheckConsentNeeded    = context => true;
                options.MinimumSameSitePolicy = SameSiteMode.None;
            });

            //
            // Configure BeatPulse Authenthication filters
            //

            //api-key filter
            //services.AddSingleton<IBeatPulseAuthenticationFilter>
            //         (new ApiKeyAuthenticationFilter("api-key-secret"));

            //local filter
            //services.AddSingleton<IBeatPulseAuthenticationFilter>(
            //    new LocalAuthenticationFilter());

            //custom filter ( defined on this project )
            //services.AddSingleton<IBeatPulseAuthenticationFilter>
            //        (new HeaderValueAuthenticationFilter("header1", "value1"));


            services.AddBeatPulse(setup =>
            {
                //
                //create simple ad-hoc liveness
                //

                setup.AddLiveness("catapi", opt =>
                {
                    opt.UsePath("catapi");
                    opt.UseLiveness(new ActionLiveness((cancellationToken) =>
                    {
                        return(Task.FromResult(
                                   LivenessResult.Healthy()));
                    }));
                });
            });


            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
        }