protected override void ReportHealth(HealthStatus status)
        {
            WriteLine();
            WriteValue("Is Healthy", status.IsHealty ? "Yes" : "No");
            WriteLine();

            var unhealthy = status.Results.Where(r => !r.Check.IsHealthy);
            if (unhealthy.Any())
            {
                WriteMetricName("FAILED CHECKS");
                WriteLine();
                foreach (var result in unhealthy)
                {
                    WriteValue(result.Name, "FAILED: " + result.Check.Message);
                }
            }

            var healthy = status.Results.Where(r => r.Check.IsHealthy);
            if (healthy.Any())
            {
                WriteMetricName("PASSED CHECKS");
                WriteLine();
                foreach (var result in healthy)
                {
                    WriteValue(result.Name, "PASSED: " + result.Check.Message);
                }
            }
        }
 public void GetHealthCheckBorn3_6MonthsSnake2()
 {
     HealthStatus health = new HealthStatus();
     var id = "5";
     List<String> messages = health.GetHealth(id).Item2;
     Assert.AreEqual(2, messages.Count);
 }
 public void GetHealthCheckBorn3_6MonthsSnake()
 {
     HealthStatus health = new HealthStatus();
     var id = "2";
     List<String> weightLossMessage = health.GetHealth(id).Item2;
     Assert.AreEqual(5, weightLossMessage.Count);
 }
  public void GetHealthColourCheckUnmellowYellow()
  {
      HealthStatus health = new HealthStatus();
      var id = "6";
      string yellow = "#FFFF66";
      string colourYellow = health.GetHealth(id).Item1;
      Assert.AreEqual(yellow, colourYellow);
 }
 public void GetHealthColourOrangeYellowSnake()
 {
     HealthStatus health = new HealthStatus();
     var id = "5";
     string orangeYellow = "#FFCC00";
     string colourOrangeYellow = health.GetHealth(id).Item1;
     Assert.AreEqual(orangeYellow, colourOrangeYellow);
 }
 public void GetHealthColourBlackSnake()
 {
     HealthStatus health = new HealthStatus();
     var id = "2";
     string black = "#000000";
     string colourBlack = health.GetHealth(id).Item1;
     Assert.AreEqual(black, colourBlack);
 }
 public void GetHealthColourRedSnake()
 {
     HealthStatus health = new HealthStatus();
     var id = "1";
     string red = "#FF0000";
     string colourRed = health.GetHealth(id).Item1;
     Assert.AreEqual(red, colourRed);
 }
 public void GetHealthColourCheckOrange()
 {
     HealthStatus health = new HealthStatus();
     var id = "7";
     string orange = "#FF9900";
     string colourOrange = health.GetHealth(id).Item1;
     Assert.AreEqual(orange, colourOrange);
 }
 public static string BuildJson(HealthStatus status, Clock clock, bool indented = true)
 {
     return new JsonHealthChecks()
        .AddVersion(Version)
        .AddTimestamp(Clock.Default)
        .AddObject(status)
        .GetJson(indented);
 }
Beispiel #10
0
 protected override void ReportHealth(HealthStatus status)
 {
     Write("All", "HealthChecks", new[] { 
         new Value("All Healthy", status.IsHealthy) }.Union(
         status.Results.SelectMany(r => new[]
     {
         new Value(r.Name + " IsHealthy" ,r.Check.IsHealthy),
         new Value(r.Name + " Message" ,r.Check.Message.Split('\n').First() ) // only first line
     })));
 }
Beispiel #11
0
    public void Reset()
    {
        damageable.Reset ();
        if (myArmor != null)
            myArmor.SetActive (true);
        status = HealthStatus.ALIVE;

        if (Damaged != null)
            Damaged (damageable.GetBasicHealthPercentage ());
    }
Beispiel #12
0
    public void TakeDamage(float damage)
    {
        damageable.TakeDamage (damage);

        if (Damaged != null)
            Damaged (damageable.GetBasicHealthPercentage ());

        if (damageable.GetTotalCurrentHealth () == 0)
            status = HealthStatus.DEAD;
    }
        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            var source    = serializer.Deserialize <HealthStatusData>(reader);
            var healthy   = source.Healthy.Keys.Select(k => new HealthCheck.Result(k, HealthCheckResult.Healthy(source.Healthy[k])));
            var unhealthy = source.Unhealthy.Keys.Select(k => new HealthCheck.Result(k, HealthCheckResult.Unhealthy(source.Unhealthy[k])));
            var degraded  = source.Degraded.Keys.Select(k => new HealthCheck.Result(k, HealthCheckResult.Degraded(source.Degraded[k])));
            var ignored   = source.Ignored.Keys.Select(k => new HealthCheck.Result(k, HealthCheckResult.Ignore(source.Ignored[k])));
            var target    = new HealthStatus(healthy.Concat(unhealthy).Concat(degraded).Concat(ignored));

            return(target);
        }
Beispiel #14
0
 protected override void ReportHealth(HealthStatus status)
 {
     Write("All", "HealthChecks", new[] {
         new Value("All Healthy", status.IsHealthy)
     }.Union(
               status.Results.SelectMany(r => new[]
     {
         new Value(r.Name + " IsHealthy", r.Check.IsHealthy),
         new Value(r.Name + " Message", r.Check.Message.Split('\n').First())  // only first line
     })));
 }
Beispiel #15
0
 public Person(float x, float y, Random random)
 {
     this.x       = x;
     this.y       = y;
     tx           = x;
     ty           = y;
     this.random  = random;
     sicksteps    = 0;
     healthStatus = HealthStatus.Susceptible;
     app          = null;
 }
        public Task <HealthCheckResult> CheckHealthAsync(HealthCheckContext context, CancellationToken cancellationToken = default)
        {
            m_logger.LogInformation(LogIds.Information.StartSchedulerHealthCheck, "Starting scheduler health check");

            HealthStatus      status = m_worker.IsHealthy ? HealthStatus.Healthy : HealthStatus.Unhealthy;
            HealthCheckResult result = new HealthCheckResult(status);

            m_logger.LogInformation(LogIds.Information.EndSchedulerHealthCheck, "Finished scheduler health check: {0}", status);

            return(Task.FromResult(result));
        }
Beispiel #17
0
        public static void Diagnose()
        {
            lock (_locker)
            {
                var deadConsumers = new List <IQueueConsumer>();

                foreach (var consumer in _consumers)
                {
                    try
                    {
                        if (!consumer.IsAlive())
                        {
                            deadConsumers.Add(consumer);
                        }
                    }
                    catch (Exception ex)
                    {
                        Logger.Error("Error occurs on diagnosing \"{0}\".", ex);
                    }
                }

                var rescueCount = 0;

                foreach (var consumer in deadConsumers)
                {
                    try
                    {
                        Logger.Info(string.Format("Consumer \"{0}\" diagnosed dead.", consumer.QueueName));

                        consumer.Rescue();

                        rescueCount++;

                        Logger.Info(string.Format("Consumer \"{0}\" is rescued.", consumer.QueueName));
                    }
                    catch (Exception ex)
                    {
                        Logger.Error(string.Format("Error occurs on rescuing \"{0}\".", consumer.QueueName), ex);
                    }
                }

                var status = new HealthStatus
                {
                    DiagnosedDead  = deadConsumers.Count,
                    DiagnosedAlive = _consumers.Count - deadConsumers.Count,
                    Rescued        = rescueCount,
                    TotalAlive     = _consumers.Count - deadConsumers.Count + rescueCount,
                    ConsumerTotal  = _consumers.Count,
                    DiagnoseAt     = DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss"),
                };

                Logger.Info("Consumer Health Status", status.SerializePretty());
            }
        }
 public void ReadPeerStatus(ITransportPeer peer, HealthStatus status)
 {
     if (status == HealthStatus.Active)
     {
         ValidOwners.Add(peer);
     }
     else
     {
         InvalidOwners.Add(peer);
     }
 }
 public void ReadPeerStatus(ITransportPeer peer, HealthStatus status)
 {
     if (status == HealthStatus.Active)
     {
         ValidOwners.Add(peer);
     }
     else
     {
         InvalidOwners.Add(peer);
     }
 }
Beispiel #20
0
 void Start()
 {
     health = MAX_HEALTH;
     InvokeRepeating ("CheckHealth", 1.0f, 1.0f);
     medHealthMaterial = Resources.Load<Material> ("materials/med_health_indicator");
     lowHealthMaterial = Resources.Load<Material> ("materials/low_health_indicator");
     critHealthMaterial = Resources.Load<Material> ("materials/crit_health_indicator");
     //Debug.Log (string.Format ("Medium health indicator: {0}", medHealthIndicator));
     healthIndicatorInstance = null;
     prevHealthStatus = HealthStatus.OK;
 }
 public JsonHealthChecks AddObject(HealthStatus status)
 {
     var properties = new List<JsonProperty>() { new JsonProperty("IsHealthy", status.IsHealthy) };
     var unhealty = status.Results.Where(r => !r.Check.IsHealthy)
         .Select(r => new JsonProperty(r.Name, r.Check.Message));
     properties.Add(new JsonProperty("Unhealthy", unhealty));
     var healty = status.Results.Where(r => r.Check.IsHealthy)
             .Select(r => new JsonProperty(r.Name, r.Check.Message));
     properties.Add(new JsonProperty("Healthy", healty));
     this.root.AddRange(properties);
     return this;
 }
 public JsonDto(JsonReference desire, decimal decayTime, HealthStatus sicknessdesire, decimal threshold, decimal weight, int minAge, int maxAge, PermittedGender gender, StrGuid guid)
 {
     Desire         = desire;
     DecayTime      = decayTime;
     Sicknessdesire = sicknessdesire;
     Threshold      = threshold;
     Weight         = weight;
     MinAge         = minAge;
     MaxAge         = maxAge;
     Gender         = gender;
     Guid           = guid;
 }
Beispiel #23
0
        public async Task Health_Get_Succeeds()
        {
            // Arrange
            using (WebApiProject project = await WebApiProject.StartNewAsync(_outputWriter))
            {
                // Act
                HealthStatus status = await project.Health.GetHealthAsync();

                // Assert
                Assert.Equal(HealthStatus.Healthy, status);
            }
        }
        public async Task MinimumServiceBusQueueWorker_ProbeForHealthReport_ResponseHealthy()
        {
            // Arrange
            await using (var project = await ServiceBusWorkerProject.StartNewWithQueueAsync(_outputWriter))
            {
                // Act
                HealthStatus status = await project.Health.ProbeHealthAsync();

                // Assert
                Assert.Equal(HealthStatus.Healthy, status);
            }
        }
Beispiel #25
0
        public void Write(HealthStatus healthStatus)
        {
            var status = GetOverallStatus(healthStatus.Results);

            _textWriter.Write($"# OVERALL STATUS: {status}");
            _textWriter.Write("\n--------------------------------------------------------------\n");

            foreach (var result in healthStatus.Results.OrderBy(r => (int)r.Check.Status))
            {
                WriteCheckResult(result);
            }
        }
Beispiel #26
0
        public async Task Health_Get_Docker_Succeeds()
        {
            // Arrange
            Uri dockerBaseUrl         = _configuration.GetDockerBaseUrl();
            var healthEndpointService = new HealthEndpointService(dockerBaseUrl, _outputWriter);

            // Act
            HealthStatus status = await healthEndpointService.GetHealthAsync();

            // Assert
            Assert.Equal(HealthStatus.Healthy, status);
        }
Beispiel #27
0
 // Called after all Update functions have been called
 void LateUpdate()
 {
     // If the game is not over, get a new health status for every Spider
     if (!GameManager.gameOver)
     {
         moonSpiderHealthStatus    = setHeathStatus(moonSpiderHealth, Category.Moon);
         messageSpiderHealthStatus = setHeathStatus(messageSpiderHealth, Category.Message);
         heartSpiderHealthStatus   = setHeathStatus(heartSpiderHealth, Category.Heart);
         hammerSpiderHealthStatus  = setHeathStatus(hammerSpiderHealth, Category.Hammer);
         selfSpiderHealthStatus    = setHeathStatus(selfSpiderHealth, Category.Self);
     }
 }
Beispiel #28
0
        /// <summary>
        /// Report health check status as a single Availability metric, with individual
        /// healt checks as properties on the metric.
        /// </summary>
        protected override void ReportHealth(HealthStatus status)
        {
            var rptName = "[" + Client.Context.Properties["MetricsReportContext"] + "] " + Client.Context.Properties["MetricsGroup"];
            var telm    = new AvailabilityTelemetry(rptName, ReportTimestamp, TimeSpan.Zero, null, status.IsHealthy);

            foreach (var h in status.Results)
            {
                telm.Properties.Add(h.Name, "[" + (h.Check.IsHealthy ? "Ok" : "FAILED") + "] " + h.Check.Message);
            }
            telm.Success = status.IsHealthy;
            Client.TrackAvailability(telm);
        }
        public void Build <TPayload>(HealthStatus healthStatus, IHealthStatusPayloadBuilder <TPayload> payloadBuilder)
        {
            var passed   = healthStatus.Results.Where(r => r.Check.Status.IsHealthy()).ToList();
            var failed   = healthStatus.Results.Where(r => r.Check.Status.IsUnhealthy()).ToList();
            var degraded = healthStatus.Results.Where(r => r.Check.Status.IsDegraded()).ToList();
            var ignored  = healthStatus.Results.Where(r => r.Check.Status.IsIgnored()).ToList();

            passed.ForEach(c => payloadBuilder.Pack(c.Name, c.Check.Message, c.Check.Status));
            degraded.ForEach(c => payloadBuilder.Pack(c.Name, c.Check.Message, c.Check.Status));
            failed.ForEach(c => payloadBuilder.Pack(c.Name, c.Check.Message, c.Check.Status));
            ignored.ForEach(c => payloadBuilder.Pack(c.Name, c.Check.Message, c.Check.Status));
        }
        public async Task CheckHealth_ReturnsExpectedFromStatus(bool running, HealthStatus expectedStatus)
        {
            var ctx    = new HealthCheckContext();
            var status = new IrrigationProcessorStatus();

            status.Running = running;

            var check  = new IrrigationProcessorHealthCheck(status);
            var result = await check.CheckHealthAsync(ctx, CancellationToken.None);

            Assert.Equal(expectedStatus, result.Status);
        }
        /// <inheritdoc />
        public async Task <HealthStatus> ReadStatusAsync(CancellationToken cancellationToken = default(CancellationToken))
        {
            var startTimestamp = _logger.IsEnabled(LogLevel.Trace) ? Stopwatch.GetTimestamp() : 0;

            _logger.HealthCheckGetStatusExecuting();

            var results = await Task.WhenAll(
                _healthCheckFactory.Checks.Values.OrderBy(v => v.Name)
                .Select(v => v.ExecuteAsync(cancellationToken)));

            var failed   = new List <HealthCheck.Result>();
            var degraded = new List <HealthCheck.Result>();

            foreach (var result in results)
            {
                var tags = new MetricTags(Constants.Health.TagKeys.HealthCheckName, result.Name);

                if (result.Check.Status == HealthCheckStatus.Degraded)
                {
                    degraded.Add(result);
                    _metrics.Value.Measure.Gauge.SetValue(ApplicationHealthMetricRegistry.Checks, tags, Constants.Health.HealthScore.degraded);
                }
                else if (result.Check.Status == HealthCheckStatus.Unhealthy)
                {
                    failed.Add(result);
                    _metrics.Value.Measure.Gauge.SetValue(ApplicationHealthMetricRegistry.Checks, tags, Constants.Health.HealthScore.unhealthy);
                }
                else if (result.Check.Status == HealthCheckStatus.Healthy)
                {
                    _metrics.Value.Measure.Gauge.SetValue(ApplicationHealthMetricRegistry.Checks, tags, Constants.Health.HealthScore.healthy);
                }
            }

            var healthStatus = new HealthStatus(results.Where(h => !h.Check.Status.IsIgnored()));

            var overallHealthStatus = Constants.Health.HealthScore.healthy;

            if (healthStatus.Status == HealthCheckStatus.Unhealthy)
            {
                overallHealthStatus = Constants.Health.HealthScore.unhealthy;
            }
            else if (healthStatus.Status == HealthCheckStatus.Degraded)
            {
                overallHealthStatus = Constants.Health.HealthScore.degraded;
            }

            _metrics.Value.Measure.Gauge.SetValue(ApplicationHealthMetricRegistry.HealthGauge, overallHealthStatus);

            _logger.HealthCheckGetStatusExecuted(healthStatus, startTimestamp);

            return(healthStatus);
        }
        private static IServiceProvider CreateServices(
            Func <TestDbContext, CancellationToken, Task <bool> > testQuery = null,
            HealthStatus failureStatus = HealthStatus.Unhealthy)
        {
            var serviceCollection = new ServiceCollection();

            serviceCollection.AddDbContext <TestDbContext>(o => o.UseInMemoryDatabase("Test" + Interlocked.Increment(ref _testDbCounter)));

            var builder = serviceCollection.AddHealthChecks();

            builder.AddDbContextCheck <TestDbContext>("test", failureStatus, new[] { "tag1", "tag2", }, testQuery);
            return(serviceCollection.BuildServiceProvider());
        }
        public static IHealthChecksBuilder AddClickHouseHealthCheck(this IHealthChecksBuilder builder,
                                                                    HealthStatus failureStatus = HealthStatus.Unhealthy,
                                                                    string name = default,
                                                                    IEnumerable <string> tags = default)
        {
            var healthCheckName = name ?? "clickhouse";

            return(builder.Add(new HealthCheckRegistration(
                                   healthCheckName,
                                   sp => new ClickHouseHealthCheck(sp.GetService <IClickHouseDatabase>()),
                                   failureStatus,
                                   tags)));
        }
Beispiel #34
0
        private HttpResponseMessage GetResponse <T>(T objectContent, HealthStatus healthStatus, HealthCheckService healthCheckService)
        {
            var response = new HttpResponseMessage(healthCheckService.GetStatusCode(healthStatus))
            {
                Content = new ObjectContent <T>(objectContent, new JsonMediaTypeFormatter {
                    SerializerSettings = SerializerSettings
                })
            };

            AddWarningHeaderIfNeeded(response, healthStatus);

            return(response);
        }
        public async Task GetCurrentHealthStatusAsyncTestAsync(int recordsToReturn, HealthStatus expectedStatus)
        {
            //Arrange
            A.CallTo(() => fakeCourseSearchClient.GetCoursesAsync(A <string> .Ignored, false)).Returns(GetTestCourses(recordsToReturn));
            var courseCurrentOpportunitiesRefresh = new CourseCurrentOpportunitiesRefresh(fakeLogger, fakeRepository, fakeCourseSearchClient, fakeMapper, courseSearchSettings, fakejobProfileSegmentRefreshService);

            //Act
            var serviceHealthStatus = await courseCurrentOpportunitiesRefresh.CheckHealthAsync(dummyHealthCheckContext).ConfigureAwait(false);

            //Asserts
            serviceHealthStatus.Status.Should().Be(expectedStatus);
            A.CallTo(() => fakeCourseSearchClient.GetCoursesAsync(A <string> ._, false)).MustHaveHappened();
        }
        private HealthState _hstate(HealthStatus hstatus)
        {
            switch (hstatus)
            {
            case HealthStatus.Error: return(HealthState.Error);

            case HealthStatus.Warning: return(HealthState.Warning);

            case HealthStatus.Healthy: return(HealthState.Ok);

            default: return(HealthState.Unknown);
            }
        }
Beispiel #37
0
 public IHealthCheckBuilder Register <THealthCheck>(
     string name = null,
     HealthStatus failureStatus = HealthStatus.Unhealthy,
     IEnumerable <string> tags  = null,
     TimeSpan?timeout           = null) where THealthCheck : IHealthCheck
 {
     return(Register(
                typeof(THealthCheck),
                string.IsNullOrWhiteSpace(name) ? typeof(THealthCheck).Name : name,
                failureStatus,
                tags,
                timeout));
 }
Beispiel #38
0
        public IActionResult CheckHealth()
        {
            HealthStatus status = atcSvc_.CheckHealth();

            if (status.Healthy)
            {
                return(Ok());
            }
            else
            {
                return(StatusCode((int)HttpStatusCode.InternalServerError, status));
            }
        }
        public void SetStatus(string service, HealthStatus status)
        {
            _log.LogInformation("setting status of [{service}] to [{status}]",
                                service, status);
            var servingStatus = status switch
            {
                HealthStatus.Serving => HealthCheckResponse.Types.ServingStatus.Serving,
                HealthStatus.NotServing => HealthCheckResponse.Types.ServingStatus.NotServing,
                HealthStatus.Unknown => HealthCheckResponse.Types.ServingStatus.Unknown,
                _ => HealthCheckResponse.Types.ServingStatus.Unknown,
            };

            SetStatus(service, servingStatus);
        }
        public async Task ReportPartitionStatus(HealthStatus health, int id, string message)
        {
            var rt = GraphEngineStatefulServiceRuntime.Instance;
            await rt.GetRoleAsync();

            var guid = rt.Partitions[id].PartitionInformation.Id;
            var hi   = new HealthInformation(sourceId, "ReportPartitionStatus", _hstate(health))
            {
                Description = message
            };

            m_fclient.HealthManager.ReportHealth(
                new PartitionHealthReport(guid, hi));
        }
        public void produces_expected_json_when_null_unhealthy_checks()
        {
            var expected   = HealthStatusSamples.NullHealthy.SampleJson();
            var healthyOne = new HealthCheck.Result("test_one_healthy", HealthCheckResult.Healthy("first check was good"));
            var healthyTwo = new HealthCheck.Result("test_two_healthy", HealthCheckResult.Healthy("second check was good"));

            var checks = new[] { healthyOne, healthyTwo };

            var healthStatus = new HealthStatus(checks);

            var result = _serializer.Serialize(healthStatus).ParseAsJson();

            result.Should().Be(expected);
        }
        public void produces_expected_json_when_null_healthy_checks()
        {
            var expected     = HealthStatusSamples.NullUnhealthy.SampleJson();
            var unhealthyOne = new HealthCheck.Result("test_three_unhealthy", HealthCheckResult.Unhealthy("something failed"));
            var unhealthyTwo = new HealthCheck.Result("test_four_unhealthy", HealthCheckResult.Unhealthy("something else failed"));

            var checks = new[] { unhealthyOne, unhealthyTwo };

            var healthStatus = new HealthStatus(checks);

            var result = _serializer.Serialize(healthStatus).ParseAsJson();

            result.Should().Be(expected);
        }
Beispiel #43
0
        public Task <HealthCheckResult> CheckHealthAsync(HealthCheckContext context, CancellationToken cancellationToken = new CancellationToken())
        {
            TimeSpan runtime     = DateTime.UtcNow - Process.GetCurrentProcess().StartTime.ToUniversalTime();
            int      upTimeValue = (runtime.Days * 3600) + (runtime.Minutes * 60) + runtime.Seconds;

            Dictionary <string, object> data = new Dictionary <string, object>
            {
                { "Uptime", upTimeValue }
            };

            HealthStatus status = HealthStatus.Healthy;

            return(Task.FromResult(new HealthCheckResult(status, description: "Uptime, seconds", exception: null, data: data)));
        }
Beispiel #44
0
        public static async ValueTask <HealthCheckResult> DefaultUrlCheck(HttpResponseMessage response)
        {
            HealthStatus status = response.IsSuccessStatusCode ? HealthStatus.Healthy : HealthStatus.Unhealthy;
            Dictionary <string, object> data = new Dictionary <string, object>
            {
                { "url", response.RequestMessage.RequestUri.ToString() },
                { "status", (int)response.StatusCode },
                { "reason", response.ReasonPhrase },
                { "body", await response.Content?.ReadAsStringAsync() },
                { "type", "UrlChecker" }
            };

            return(new HealthCheckResult(status, $"status code {response.StatusCode} ({(int)response.StatusCode})", null, data));
        }
Beispiel #45
0
        public void Status_MatchesWorstStatusInResults(HealthStatus status)
        {
            var result = new HealthReport(new Dictionary <string, HealthReportEntry>()
            {
                { "Foo", new HealthReportEntry(HealthStatus.Healthy, null, TimeSpan.MinValue, null, null) },
                { "Bar", new HealthReportEntry(HealthStatus.Healthy, null, TimeSpan.MinValue, null, null) },
                { "Baz", new HealthReportEntry(status, exception: null, description: null, duration: TimeSpan.MinValue, data: null) },
                { "Quick", new HealthReportEntry(HealthStatus.Healthy, null, TimeSpan.MinValue, null, null) },
                { "Quack", new HealthReportEntry(HealthStatus.Healthy, null, TimeSpan.MinValue, null, null) },
                { "Quock", new HealthReportEntry(HealthStatus.Healthy, null, TimeSpan.MinValue, null, null) },
            }, totalDuration: TimeSpan.MinValue);

            Assert.Equal(status, result.Status);
        }
        public void CheckHealth_should_update_the_endpoint_with_its_health_status(HealthStatus healthStatus)
        {
            var tokenSource = new CancellationTokenSource();
            var healthInfo = new HealthInfo(healthStatus, TimeSpan.FromSeconds(1), new Dictionary<string, string> { { "property1", "value1" }, { "property2", "value2" } });
            var monitor = MonitorMock.GetMock("monitor");
            monitor.Setup(x => x.CheckHealthAsync("address", It.IsAny<CancellationToken>())).Returns(Task.FromResult(healthInfo));

            var endpoint = new Endpoint(Guid.NewGuid(), monitor.Object, "address", "name", "group");

            endpoint.CheckHealth(tokenSource.Token, MonitorSettingsHelper.ConfigureDefaultSettings()).Wait();

            var health = endpoint.Health;
            Assert.NotNull(health);
            Assert.Equal(healthInfo.ResponseTime, health.ResponseTime);
            Assert.Equal(healthInfo.Status.ToString(), health.Status.ToString());
            Assert.True(DateTime.UtcNow - health.CheckTimeUtc < TimeSpan.FromMilliseconds(500), "CheckTimeUtc should be captured");
            Assert.Equal(healthInfo.Details, health.Details);
        }
        private void Given_an_endpoint_with_push_integration()
        {
            _endpointUniqueName = Guid.NewGuid().ToString();
            _endpointHostName = Guid.NewGuid().ToString();
            _endpointGroupName = Guid.NewGuid().ToString();
            _endpointName = Guid.NewGuid().ToString();
            _endpointTags = new[] { "tag1", "tag2" };
            _password = Guid.NewGuid().ToString();

            _pushClient = HealthMonitorPushClient.UsingHealthMonitor(ClientHelper.GetHealthMonitorUrl().ToString())
                .DefineEndpoint(b => b
                    .DefineAddress(_endpointHostName, _endpointUniqueName)
                    .DefineGroup(_endpointGroupName)
                    .DefineName(_endpointName)
                    .DefineTags(_endpointTags)
                    .DefinePassword(_password))
                .WithHealthCheck(this);

            _currentEndpointStatus = HealthStatus.Healthy;
        }
Beispiel #48
0
    public void RefreshDotColors()
    {
        if (numDots == 0)
        {
            healthStatus = HealthStatus.Dead;
            return;
        }

        if (numDots > greenThreshold)
        {
            SetAllDotSprites(green);
            healthStatus = HealthStatus.Normal;
        }
        else if (numDots > yellowThreshold)
        {
            SetAllDotSprites(yellow);
            healthStatus = HealthStatus.Low;
        }
        else
        {
            SetAllDotSprites(red);
            healthStatus = HealthStatus.Critical;
        }
    }
        public void CheckHealth_should_use_short_timeout_for_endpoints_with_non_faulty_statuses(HealthStatus status)
        {
            var expectedTime = TimeSpan.FromMilliseconds(300);
            _settings.Setup(s => s.ShortTimeOut).Returns(expectedTime);
            _settings.Setup(s => s.HealthyResponseTimeLimit).Returns(TimeSpan.FromSeconds(5));
            _settings.Setup(s => s.FailureTimeOut).Returns(TimeSpan.FromSeconds(1));

            _monitor
                .Setup(m => m.CheckHealthAsync(_endpoint.Address, It.IsAny<CancellationToken>()))
                .Returns(async (string address, CancellationToken token) =>
                {
                    if (_endpoint.Health == null)
                        return new HealthInfo(status);
                    await Task.Delay(TimeSpan.FromSeconds(2), token);
                    return new HealthInfo(HealthStatus.Healthy);
                });

            //First state
            _endpoint.CheckHealth(_sampler, new CancellationToken()).Wait();
            Assert.Equal(status.ToString(), _endpoint.Health.Status.ToString());

            //Timed out state
            var result = _sampler.CheckHealth(_endpoint, new CancellationToken()).Result;
            Assert.Equal(EndpointStatus.TimedOut, result.Status);
            AssertResponseTime(result, expectedTime);
            AssertCheckTime(result);
        }
 public static string Serialize(HealthStatus status)
 {
     return new JsonFormatter().AddObject(status).GetJson();
 }
 private EndpointStatus GetStatus(HealthStatus status, TimeSpan responseTime)
 {
     if (status == HealthStatus.Healthy && responseTime > _settings.HealthyResponseTimeLimit)
         return EndpointStatus.Unhealthy;
     return (EndpointStatus)status;
 }
 public TestableHealthChecker(HealthStatus status, string key, string value)
 {
     _status = status;
     _value = value;
     _key = key;
 }
Beispiel #53
0
 /// <summary>Initializes a new instance of the <see cref="T:OregonTrailDotNet.Module.Scoring.HealthScoring" /> class.</summary>
 /// <param name="partyHealthStatus">The party Health Level.</param>
 /// <param name="pointsPerPerson">The points Per Person.</param>
 public HealthScoring(HealthStatus partyHealthStatus, int pointsPerPerson)
 {
     PartyHealthStatus = partyHealthStatus;
     PointsPerPerson = pointsPerPerson;
 }
 public async Task HealthChecker_should_capture_status(HealthStatus expected)
 {
     var result = await new TestableHealthChecker(expected, "key", "value").CheckHealthAsync(CancellationToken.None);
     Assert.Equal(expected, result.Status);
 }
 protected override void ReportHealth(HealthStatus status)
 {
 }
        public void GetEndpoint_should_return_endpoint_information_with_details(HealthStatus status)
        {
            Guid id = Guid.NewGuid();
            var monitor = MonitorMock.GetMock("monitor");
            var healthInfo = new HealthInfo(status, TimeSpan.FromSeconds(2), new Dictionary<string, string> { { "a", "b" }, { "c", "d" } });
            monitor.Setup(p => p.CheckHealthAsync("address", It.IsAny<CancellationToken>())).Returns(Task.FromResult(healthInfo));

            var endpoint = new Endpoint(id, monitor.Object, "address", "name", "group");
            endpoint.CheckHealth(new CancellationToken(), MonitorSettingsHelper.ConfigureDefaultSettings()).Wait();
            _endpointRegistry.Setup(r => r.GetById(id)).Returns(endpoint);

            var result = _controller.GetEndpoint(id) as OkNegotiatedContentResult<EndpointDetails>;
            Assert.NotNull(result);
            AssertEndpoint(endpoint, result.Content);

            Assert.Equal(status.ToString(), result.Content.Status.ToString());
            Assert.NotNull(result.Content.LastCheckUtc);
            Assert.Equal(healthInfo.ResponseTime, result.Content.LastResponseTime);
            Assert.Equal(healthInfo.Details, result.Content.Details);
        }
 public void OwnsButIsInState(Uri subject, HealthStatus status)
 {
     OwnedSubjects.Fill(subject);
     SubjectStatus[subject] = status;
 }
Beispiel #58
0
    void Update()
    {
        if (health <= MED_HEALTH) {
            Material healthMaterial = medHealthMaterial;
            HealthStatus healthStatus = HealthStatus.MED;
            if (health <= CRIT_HEALTH) {
                healthMaterial = critHealthMaterial;
                healthStatus = HealthStatus.CRIT;
            } else if (health <= LOW_HEALTH) {
                healthMaterial = lowHealthMaterial;
                healthStatus = HealthStatus.LOW;
            }

            Transform cameraTransform = Camera.main.gameObject.transform;

            // Materialize the health indicator thing
            Vector3 indicatorPos = cameraTransform.position + cameraTransform.forward;
            Quaternion indicatorRot = cameraTransform.rotation;

            if (healthIndicatorInstance == null) {
                healthIndicatorInstance = GameObject.CreatePrimitive(PrimitiveType.Quad);
            }

            if (prevHealthStatus != healthStatus) {
                healthIndicatorInstance.renderer.material = healthMaterial;
            }

            healthIndicatorInstance.transform.localScale = new Vector3(2f*Camera.main.aspect, 2f, 1f);
            healthIndicatorInstance.transform.position = indicatorPos;
            healthIndicatorInstance.transform.rotation = indicatorRot;

            prevHealthStatus = healthStatus;
        } else {
            if (healthIndicatorInstance != null) {
                Destroy (healthIndicatorInstance);
                healthIndicatorInstance = null;
            }
            prevHealthStatus = HealthStatus.OK;
        }
    }
 public PersistentTaskStatus(Uri subject, HealthStatus status)
 {
     Subject = subject;
     Status = status;
 }
 public static string BuildJson(HealthStatus status) { return BuildJson(status, Clock.Default, indented: false); }