public async Task Run_WhenCheckerThrows_FailureResult()
        {
            // Arrange
            var checkerMocks = Enumerable
                .Range(1, 3)
                .Select(x =>
                {
                    var mock = new Mock<IChecker>();
                    mock.SetupGet(y => y.Name).Returns(x.ToString());
                    mock.Setup(y => y.Check()).ThrowsAsync(new Exception("error " + mock.Object.Name));
                    return mock;
                })
                .ToArray();
            var healthCheck = new HealthCheck(checkerMocks.Select(x => x.Object));

            // Act
            var result = await healthCheck.Run();

            // Assert
            Assert.That(result.Passed, Is.False);
            Assert.That(result.Status, Is.EqualTo("failure"));
            Assert.That(result.Results.Length, Is.EqualTo(checkerMocks.Length));
            foreach (var checkerMock in checkerMocks)
            {
                var checkResult = result.Results.Single(x => x.Checker == checkerMock.Object.Name);
                Assert.That(checkResult.Checker, Is.EqualTo(checkerMock.Object.Name));
                Assert.That(checkResult.Passed, Is.False);
                Assert.That(checkResult.Output, Is.EqualTo("error " + checkerMock.Object.Name));
            }
        }
Example #2
0
        public async Task Failed_if_action_throws()
        {
            var name    = "test";
            var check1  = new HealthCheck(name, () => ThrowException());
            var result1 = await check1.ExecuteAsync(CancellationToken.None);

            result1.Check.Status.Should().Be(HealthCheckStatus.Unhealthy);

            var check2 = new HealthCheck(
                name,
                () =>
            {
                ThrowException();
                return(new ValueTask <HealthCheckResult>(HealthCheckResult.Healthy("string")));
            });
            var result2 = await check2.ExecuteAsync();

            result2.Check.Status.Should().Be(HealthCheckStatus.Unhealthy);

            var check3 = new HealthCheck(
                name,
                () =>
            {
                ThrowException();
                return(new ValueTask <HealthCheckResult>(HealthCheckResult.Healthy()));
            });
            var result3 = await check3.ExecuteAsync();

            result3.Check.Status.Should().Be(HealthCheckStatus.Unhealthy);
        }
Example #3
0
 public IActionResult GetHealthCheckAsync()
 {
     try
     {
         HealthCheck healthCheck = new HealthCheck();
         var         ClinicBase  = configuration.GetSection("ClinicBase").Value;
         using (HttpClient client = new HttpClient())
         {
             client.BaseAddress = new Uri(ClinicBase);
             client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", this.AccessToken);
             var responseclinic = client.GetAsync("Clinic/HealthCheck");
             responseclinic.Wait();
             var clinicResult = responseclinic.Result;
             if (clinicResult.IsSuccessStatusCode)
             {
                 healthCheck.Status = "Healthy";
                 healthCheck.Error  = "No error";
                 return(Ok(healthCheck));
             }
             else
             {
                 healthCheck.Status = "UnHealthy";
                 healthCheck.Error  = "Clinic Domain Service is unavailable";
                 return(Ok(healthCheck));
             }
         }
     }
     catch (Exception ex)
     {
         return(StatusCode(500, ex.Message));
     }
 }
Example #4
0
        async void DrawNodes()
        {
            List <Node> alive = await HealthCheck.CheckHealth(Init.Peers);

            List <Node>   dead    = Init.Peers.Except(alive).ToList();
            MarkerOptions moAlive = new MarkerOptions()
            {
                Icon = @"http://i.imgur.com/JPV3KXR.png", Clickable = true, DraggingEnabled = false, Flat = false, Optimized = true, RaiseOnDrag = true
            };
            MarkerOptions moDead = new MarkerOptions()
            {
                Icon = @"http://i.imgur.com/WpTAa9N.png", Clickable = true, DraggingEnabled = false, Flat = false, Optimized = true, RaiseOnDrag = true
            };

            foreach (Node pn in Init.Peers)
            {
                var Marker = Map.AddMarker(new GeographicLocation(pn.NodeLocation.lat, pn.NodeLocation.lon), (alive.Contains(pn) ? moAlive : moDead));
                Marker.Click += (im, gl) =>
                {
                    KeySelection ks = new KeySelection(pn.GetLogs());
                    ks.ShowDialog();
                    Main m = new Main(pn, ks.Selection);
                    m.Show();
                };
            }
        }
        public void CanAssignInterval()
        {
            var healthCheck = new HealthCheck(ServiceHealth.Ok, "ok");
            var check       = new HostHealthCheck(host => healthCheck, 23);

            check.IntervalInSeconds.Should().Be(23);
        }
        public void CanAssignDeregister()
        {
            var healthCheck = new HealthCheck(ServiceHealth.Ok, "ok");
            var check       = new HostHealthCheck(host => healthCheck, deregisterIfCriticalAfterInMinutes: 23);

            check.DeregisterIfCriticalAfterInMinutes.Should().Be(23);
        }
Example #7
0
        private static IDictionary <string, string> ConvertConfigureHealthCheck(ConfigureHealthCheckRequest request)
        {
            IDictionary <string, string> dictionary = new Dictionary <string, string>();

            dictionary["Action"] = "ConfigureHealthCheck";
            if (request.IsSetLoadBalancerName())
            {
                dictionary["LoadBalancerName"] = request.LoadBalancerName;
            }
            if (request.IsSetHealthCheck())
            {
                HealthCheck healthCheck = request.HealthCheck;
                if (healthCheck.IsSetTarget())
                {
                    dictionary["HealthCheck" + "." + "Target"] = healthCheck.Target;
                }
                if (healthCheck.IsSetInterval())
                {
                    dictionary["HealthCheck" + "." + "Interval"] = healthCheck.Interval.ToString();
                }
                if (healthCheck.IsSetTimeout())
                {
                    dictionary["HealthCheck" + "." + "Timeout"] = healthCheck.Timeout.ToString();
                }
                if (healthCheck.IsSetUnhealthyThreshold())
                {
                    dictionary["HealthCheck" + "." + "UnhealthyThreshold"] = healthCheck.UnhealthyThreshold.ToString();
                }
                if (healthCheck.IsSetHealthyThreshold())
                {
                    dictionary["HealthCheck" + "." + "HealthyThreshold"] = healthCheck.HealthyThreshold.ToString();
                }
            }
            return(dictionary);
        }
        /// <summary>
        /// Converts a <see cref="HealthReport"/> to a <see cref="ServiceHealthReport"/>.
        /// </summary>
        /// <param name="healthReport">The health report.</param>
        /// <returns>Returns the converted <see cref="ServiceHealthReport"/>.</returns>
        public static ServiceHealthReport ToServiceHealthReport(this HealthReport healthReport)
        {
            ServiceHealthReport serviceHealth = new ServiceHealthReport();

            foreach (var(name, entry) in healthReport.Entries)
            {
                HealthCheck healthCheck = new HealthCheck
                {
                    Name        = name,
                    Description = entry.Description,
                    Status      = entry.Status.ToString(),
                    Duration    = new Duration()
                    {
                        Milliseconds = entry.Duration.Milliseconds,
                        Seconds      = entry.Duration.Seconds,
                        Ticks        = entry.Duration.Ticks
                    }
                };
                serviceHealth.HealthChecks.Add(healthCheck);
            }
            serviceHealth.Status        = healthReport.Status.ToString();
            serviceHealth.TotalDuration = new Duration()
            {
                Ticks        = healthReport.TotalDuration.Ticks,
                Seconds      = healthReport.TotalDuration.Seconds,
                Milliseconds = healthReport.TotalDuration.Milliseconds
            };
            return(serviceHealth);
        }
        public override async Task CallService(HttpContext context)
        {
            var summary  = GetAggregatedSummary();
            var response = new HealthResponse {
                Stats = summary
            };

            if (_config.Checks?.Count > 0)
            {
                var checks = new Task <HealthCheck> [_config.Checks.Count];
                for (var i = 0; i < checks.Length; i++)
                {
                    checks[i] = _config.Checks[i]();
                }
                await Task.WhenAll(checks);

                var results = new HealthCheck[_config.Checks.Count];
                var code    = HttpStatusCode.OK;
                for (var i = 0; i < checks.Length; i++)
                {
                    results[i] = checks[i].Result;
                    if (!results[i].Ok)
                    {
                        code = HttpStatusCode.InternalServerError;
                    }
                }
                response.HealthChecks       = results;
                context.Response.StatusCode = (int)code;
            }
            else
            {
                context.Response.StatusCode = (int)HttpStatusCode.OK;
            }
            await context.Response.WriteJsonAsync(response);
        }
        private HealthCheck CheckADFS()
        {
            var health = new HealthCheck();

            try
            {
                health.description = "Check ADFS availability";

                var url      = ConfigurationManager.AppSettings["ida:AdfsMetadataEndpoint"];
                var request  = HttpWebRequest.Create(url);
                var response = (System.Net.HttpWebResponse)request.GetResponse();

                if (response.StatusCode == HttpStatusCode.OK)
                {
                    health.status = "Success";
                }
                else
                {
                    health.status = "Error";
                }
            }
            catch (Exception ex)
            {
                health.status = "Error";
            }


            return(health);
        }
Example #11
0
        /// <summary>
        /// Registers health checks with the watchdog service.
        /// </summary>
        /// <param name="token">Cancellation token to monitor for cancellation requests.</param>
        /// <returns>A Task that represents outstanding operation.</returns>
        internal async Task RegisterHealthCheckAsync(CancellationToken token)
        {
            HttpClient client = new HttpClient();

            // Called from RunAsync, don't let an exception out so the service will start, but log the exception because the service won't work.
            try
            {
                // Use the reverse proxy to locate the service endpoint.
                string              postUrl = "http://localhost:19081/Watchdog/WatchdogService/healthcheck";
                HealthCheck         hc      = new HealthCheck("Watchdog Health Check", this.Context.ServiceName, this.Context.PartitionId, "watchdog/health");
                HttpResponseMessage msg     = await client.PostAsJsonAsync(postUrl, hc);

                // Log a success or error message based on the returned status code.
                if (HttpStatusCode.OK == msg.StatusCode)
                {
                    ServiceEventSource.Current.Trace(nameof(this.RegisterHealthCheckAsync), Enum.GetName(typeof(HttpStatusCode), msg.StatusCode));
                }
                else
                {
                    ServiceEventSource.Current.Error(nameof(this.RegisterHealthCheckAsync), Enum.GetName(typeof(HttpStatusCode), msg.StatusCode));
                }
            }
            catch (Exception ex)
            {
                ServiceEventSource.Current.Error($"Exception: {ex.Message} at {ex.StackTrace}.");
            }
        }
        /// <summary>
        /// Creates an HttpRequestMessage based on the HealthCheck information.
        /// </summary>
        /// <param name="hc">HealthCheck instance.</param>
        /// <param name="address">Uri containing the full address.</param>
        /// <returns>HttpRequestMessage instance.</returns>
        internal HttpRequestMessage CreateRequestMessage(HealthCheck hc, Uri address)
        {
            // Create the HttpRequestMessage initialized with the values configured for the HealthCheck.
            HttpRequestMessage request = new HttpRequestMessage()
            {
                RequestUri = address, Method = hc.Method
            };

            // If headers are specified, add them to the request.
            if (null != hc.Headers)
            {
                foreach (KeyValuePair <string, string> header in hc.Headers)
                {
                    request.Headers.Add(header.Key, header.Value);
                }
            }

            // If content was specified, add it to the request.
            if (null != hc.Content)
            {
                request.Content = new StringContent(hc.Content, Encoding.Default, hc.MediaType);
            }

            return(request);
        }
Example #13
0
        private void SocketEvent_ProcessMessage(object sender, SocketEventArgs data)
        {
            if (!SocketEvent_InSync)
            {
                SocketEvent_InSync = true;
                this.Queue(false, new Action(() => SocketEvent_InSyncEvent?.Invoke(this, true)));
            }

            switch (data.Command)
            {
            case 1:     //Initial Scan
                this.Queue(false, new Action(() => HealthCheck?.Invoke(sender, new HealthCheckEventArgs(data.ID))));
                HealthCheckEventArgs hc = new HealthCheckEventArgs(data.ID);
                hc.Valid  = flipflop;
                flipflop ^= true;
                HealthCheckResponse(hc);
                break;

            case 10:     //Tote ready for pickup.
                this.Queue(false, new Action(() => ToteReady?.Invoke(sender, data)));
                break;

            case 12:     //Tote Loading complete.
                this.Queue(false, new Action(() => ToteLoadComplete?.Invoke(sender, data)));
                break;

            case 13:     //Tote Unloading complete.
                this.Queue(false, new Action(() => ToteUnloadComplete?.Invoke(sender, data)));
                break;
            }
        }
Example #14
0
        public void Health_check_consists_of_a_single_monitor()
        {
            var healthCheck = new HealthCheck(MonitorConfig.Build("Test"), () => true);

            healthCheck.GetAllMonitors().Should().HaveCount(1);
            healthCheck.GetAllMonitors().Single().Should().BeSameAs(healthCheck);
        }
        public void HealthCheck_ConstructorTest()
        {
            HealthCheck hcDefault = new HealthCheck();

            Assert.IsNull(hcDefault.ServiceName);
            Assert.IsNull(hcDefault.SuffixPath);
            Assert.IsNull(hcDefault.Content);
            Assert.IsNull(hcDefault.MediaType);
            Assert.IsNull(hcDefault.Headers);
            Assert.IsNull(hcDefault.WarningStatusCodes);
            Assert.IsNull(hcDefault.ErrorStatusCodes);
            Assert.AreEqual(default(Guid), hcDefault.Partition);
            Assert.AreEqual(default(TimeSpan), hcDefault.Frequency);
            Assert.AreEqual(default(HttpMethod), hcDefault.Method);
            Assert.AreEqual(default(TimeSpan), hcDefault.ExpectedDuration);
            Assert.AreEqual(default(TimeSpan), hcDefault.MaximumDuration);
            Assert.AreEqual(default(DateTimeOffset), hcDefault.LastAttempt);
            Assert.AreEqual(default(long), hcDefault.FailureCount);
            Assert.AreEqual(default(long), hcDefault.Duration);
            Assert.AreEqual(default(HttpStatusCode), hcDefault.ResultCode);

            // Check this equals the default HealthCheck value.
            Assert.IsTrue(hcDefault.Equals(HealthCheck.Default));

            // Check the copy constructor.
            HealthCheck hc1 = new HealthCheck(hc);

            Assert.IsTrue(hc.Equals(hc1));
        }
Example #16
0
        public static HealthCheckBuilder AddValueTaskCheck(this HealthCheckBuilder builder, string name,
                                                           Func <ValueTask <IHealthCheckResult> > check)
        {
            Guard.ArgumentNotNull(nameof(builder), builder);

            return(builder.AddCheck(name, HealthCheck.FromValueTaskCheck(check), builder.DefaultCacheDuration));
        }
Example #17
0
 /// <summary>
 /// Registers a custom health check.
 /// </summary>
 /// <param name="healthCheck">Custom health check to register.</param>
 public static void RegisterHealthCheck(HealthCheck healthCheck)
 {
     if (!checks.TryAdd(healthCheck.Name, healthCheck))
     {
         throw new InvalidOperationException("HealthCheck named " + healthCheck.Name + " already registered");
     }
 }
Example #18
0
        public static HealthCheckBuilder AddValueTaskCheck(this HealthCheckBuilder builder, string name,
                                                           Func <CancellationToken, ValueTask <IHealthCheckResult> > check, TimeSpan cacheDuration)
        {
            Guard.ArgumentNotNull(nameof(builder), builder);

            return(builder.AddCheck(name, HealthCheck.FromValueTaskCheck(check), cacheDuration));
        }
Example #19
0
        public async Task Failed_and_does_not_throw_unhandled_exception_if_action_throws_exception_with_brackets_in_message()
        {
            var name = "test";

            var check1  = new HealthCheck(name, () => ThrowExceptionWithBracketsInMessage());
            var result1 = await check1.ExecuteAsync(CancellationToken.None);

            result1.Check.Status.Should().Be(HealthCheckStatus.Unhealthy);

            var check2 = new HealthCheck(
                name,
                () =>
            {
                ThrowExceptionWithBracketsInMessage();
                return(new ValueTask <HealthCheckResult>(HealthCheckResult.Healthy("string")));
            });
            var result2 = await check2.ExecuteAsync(CancellationToken.None);

            result2.Check.Status.Should().Be(HealthCheckStatus.Unhealthy);

            var check3 = new HealthCheck(
                name,
                () =>
            {
                ThrowExceptionWithBracketsInMessage();
                return(new ValueTask <HealthCheckResult>(HealthCheckResult.Healthy()));
            });
            var result3 = await check3.ExecuteAsync(CancellationToken.None);

            result3.Check.Status.Should().Be(HealthCheckStatus.Unhealthy);
        }
        public void CanAssignInterval()
        {
            var healthCheck = new HealthCheck(ServiceHealth.Ok, "ok");
            var check = new HostHealthCheck(host => healthCheck, 23);

            check.IntervalInSeconds.Should().Be(23);
        }
Example #21
0
        /// <inheritdoc/>
        public void Normalize()
        {
            Labels      = Labels ?? new Dictionary <string, string>(StringComparer.InvariantCultureIgnoreCase);
            Command     = Command ?? new List <string>();
            Args        = Args ?? new List <string>();
            Env         = Env ?? new List <string>();
            Groups      = Groups ?? new List <string>();
            Secrets     = Secrets ?? new List <ServiceSecret>();
            Configs     = Configs ?? new List <ServiceConfig>();
            Mounts      = Mounts ?? new List <ServiceMount>();
            HealthCheck = HealthCheck ?? new ServiceHealthCheck();
            Hosts       = Hosts ?? new List <string>();

            Privileges?.Normalize();
            HealthCheck?.Normalize();
            DNSConfig?.Normalize();

            foreach (var item in Secrets)
            {
                item?.Normalize();
            }

            foreach (var item in Configs)
            {
                item?.Normalize();
            }

            foreach (var item in Mounts)
            {
                item?.Normalize();
            }
        }
        /// <summary>
        /// Creates a HealthCheck resource in the specified project using the data included in the request.
        /// Documentation https://developers.google.com/compute/alpha/reference/healthChecks/insert
        /// Generation Note: This does not always build corectly.  Google needs to standardise things I need to figuer out which ones are wrong.
        /// </summary>
        /// <param name="service">Authenticated Compute service.</param>
        /// <param name="project">Project ID for this request.</param>
        /// <param name="body">A valid Compute alpha body.</param>
        /// <param name="optional">Optional paramaters.</param>
        /// <returns>OperationResponse</returns>
        public static Operation Insert(ComputeService service, string project, HealthCheck body, HealthChecksInsertOptionalParms optional = null)
        {
            try
            {
                // Initial validation.
                if (service == null)
                {
                    throw new ArgumentNullException("service");
                }
                if (body == null)
                {
                    throw new ArgumentNullException("body");
                }
                if (project == null)
                {
                    throw new ArgumentNullException(project);
                }

                // Building the initial request.
                var request = service.HealthChecks.Insert(body, project);

                // Applying optional parameters to the request.
                request = (HealthChecksResource.InsertRequest)SampleHelpers.ApplyOptionalParms(request, optional);

                // Requesting data.
                return(request.Execute());
            }
            catch (Exception ex)
            {
                throw new Exception("Request HealthChecks.Insert failed.", ex);
            }
        }
        public async Task failed_if_result_is_unhealthy()
        {
            var check  = new HealthCheck("test", () => Task.FromResult(HealthCheckResult.Unhealthy()));
            var result = await check.ExecuteAsync();

            result.Check.Status.Should().Be(HealthCheckStatus.Unhealthy);
        }
Example #24
0
        public static HealthCheckBuilder AddCheck(this HealthCheckBuilder builder, string name,
                                                  Func <CancellationToken, IHealthCheckResult> check)
        {
            Guard.ArgumentNotNull(nameof(builder), builder);

            return(builder.AddCheck(name, HealthCheck.FromCheck(check), builder.DefaultCacheDuration));
        }
        public async Task failed_and_does_not_throw_unhandled_exception_if_action_throws_exception_with_brackets_in_message()
        {
            var name = "test";

            var check1  = new HealthCheck(name, () => ThrowExceptionWithBracketsInMessage());
            var result1 = await check1.ExecuteAsync(CancellationToken.None);

            result1.Check.Status.Should().Be(HealthCheckStatus.Unhealthy);

            var check2 = new HealthCheck(
                name,
                () =>
            {
                ThrowExceptionWithBracketsInMessage();
                return(Task.FromResult("string"));
            });
            var result2 = await check2.ExecuteAsync(CancellationToken.None);

            result2.Check.Status.Should().Be(HealthCheckStatus.Unhealthy);

            var check3 = new HealthCheck(
                name,
                () =>
            {
                ThrowExceptionWithBracketsInMessage();
                return(AppMetricsTaskCache.CompletedHealthyTask);
            });
            var result3 = await check3.ExecuteAsync(CancellationToken.None);

            result3.Check.Status.Should().Be(HealthCheckStatus.Unhealthy);
        }
        public async Task failed_if_action_throws()
        {
            var name    = "test";
            var check1  = new HealthCheck(name, () => ThrowException());
            var result1 = await check1.ExecuteAsync(CancellationToken.None);

            result1.Check.Status.Should().Be(HealthCheckStatus.Unhealthy);

            var check2 = new HealthCheck(
                name,
                () =>
            {
                ThrowException();
                return(Task.FromResult("string"));
            });
            var result2 = await check2.ExecuteAsync();

            result2.Check.Status.Should().Be(HealthCheckStatus.Unhealthy);

            var check3 = new HealthCheck(
                name,
                () =>
            {
                ThrowException();
                return(AppMetricsTaskCache.CompletedHealthyTask);
            });
            var result3 = await check3.ExecuteAsync();

            result3.Check.Status.Should().Be(HealthCheckStatus.Unhealthy);
        }
        /// <summary>
        /// Creates a HealthCheck resource in the specified project using the data included in the request.
        /// Documentation https://developers.google.com/compute/alpha/reference/healthChecks/insert
        /// Generation Note: This does not always build corectly.  Google needs to standardise things I need to figuer out which ones are wrong.
        /// </summary>
        /// <param name="service">Authenticated compute service.</param>
        /// <param name="project">Project ID for this request.</param>
        /// <param name="body">A valid compute alpha body.</param>
        /// <returns>OperationResponse</returns>
        public static Operation Insert(computeService service, string project, HealthCheck body)
        {
            try
            {
                // Initial validation.
                if (service == null)
                {
                    throw new ArgumentNullException("service");
                }
                if (body == null)
                {
                    throw new ArgumentNullException("body");
                }
                if (project == null)
                {
                    throw new ArgumentNullException(project);
                }

                // Make the request.
                return(service.HealthChecks.Insert(body, project).Execute());
            }
            catch (Exception ex)
            {
                throw new Exception("Request HealthChecks.Insert failed.", ex);
            }
        }
        public async Task <HttpResponseMessage> PostHealthCheck([FromBody] HealthCheck hcm)
        {
            // Check required parameters.
            if (hcm.Equals(HealthCheck.Default))
            {
                return(this.Request.CreateResponse(HttpStatusCode.BadRequest));
            }
            if (null == this._operations)
            {
                return(this.Request.CreateResponse(HttpStatusCode.InternalServerError));
            }

            try
            {
                ServiceEventSource.Current.ServiceRequestStart(nameof(this.PostHealthCheck));

                // Call the operations class to add the health check.
                await this._operations.AddHealthCheckAsync(hcm);

                ServiceEventSource.Current.ServiceRequestStop(nameof(this.PostHealthCheck));
                return(this.Request.CreateResponse(HttpStatusCode.OK));
            }
            catch (ArgumentException ex)
            {
                ServiceEventSource.Current.Exception(ex.Message, ex.GetType().Name, nameof(this.PostHealthCheck));
                return(this.Request.CreateResponse(HttpStatusCode.BadRequest));
            }
            catch (Exception ex)
            {
                ServiceEventSource.Current.Exception(ex.Message, ex.GetType().Name, nameof(this.PostHealthCheck));
                return(this.Request.CreateErrorResponse(HttpStatusCode.InternalServerError, ex));
            }
        }
Example #29
0
 internal void Register(HealthCheck healthCheck)
 {
     if (Checks.TryAdd(healthCheck.Name, healthCheck))
     {
         _logger.HealthCheckRegistered(healthCheck.Name);
     }
 }
Example #30
0
        /// <summary>
        /// Attempts to save the settings. On catching an exception will prompt the user and close XC.
        /// </summary>
        public static void TrySaveSettings()
        {
            try
            {
                Properties.Settings.Default.Save();
            }
            catch (ConfigurationErrorsException ex)
            {
                // Show a warning to the user and exit the application.
                using (var dlg = new ThreeButtonDialog(
                           new ThreeButtonDialog.Details(
                               SystemIcons.Error,
                               string.Format(Messages.MESSAGEBOX_SAVE_CORRUPTED, Settings.GetUserConfigPath()),
                               Messages.MESSAGEBOX_SAVE_CORRUPTED_TITLE)
                           ))
                {
                    dlg.ShowDialog(Program.MainWindow);
                }

                log.Error("Could not save settings. Exiting application.");
                log.Error(ex, ex);
                Application.Exit();
            }

            HealthCheck.SendMetadataToHealthCheck();
        }
        public void CanAssignDeregister()
        {
            var healthCheck = new HealthCheck(ServiceHealth.Ok, "ok");
            var check = new HostHealthCheck(host => healthCheck,deregisterIfCriticalAfterInMinutes: 23);

            check.DeregisterIfCriticalAfterInMinutes.Should().Be(23);
        }
Example #32
0
        /// <summary>Snippet for Update</summary>
        public void Update()
        {
            // Snippet: Update(string, string, HealthCheck, CallSettings)
            // Create client
            HealthChecksClient healthChecksClient = HealthChecksClient.Create();
            // Initialize request argument(s)
            string      project             = "";
            string      healthCheck         = "";
            HealthCheck healthCheckResource = new HealthCheck();
            // Make the request
            lro::Operation <Operation, Operation> response = healthChecksClient.Update(project, healthCheck, healthCheckResource);

            // Poll until the returned long-running operation is complete
            lro::Operation <Operation, Operation> completedResponse = response.PollUntilCompleted();
            // Retrieve the operation result
            Operation result = completedResponse.Result;

            // Or get the name of the operation
            string operationName = response.Name;
            // This name can be stored, then the long-running operation retrieved later by name
            lro::Operation <Operation, Operation> retrievedResponse = healthChecksClient.PollOnceUpdate(operationName);

            // Check if the retrieved long-running operation has completed
            if (retrievedResponse.IsCompleted)
            {
                // If it has completed, then access the result
                Operation retrievedResult = retrievedResponse.Result;
            }
            // End snippet
        }
Example #33
0
        /// <summary>Snippet for InsertAsync</summary>
        public async Task InsertAsync()
        {
            // Snippet: InsertAsync(string, HealthCheck, CallSettings)
            // Additional: InsertAsync(string, HealthCheck, CancellationToken)
            // Create client
            HealthChecksClient healthChecksClient = await HealthChecksClient.CreateAsync();

            // Initialize request argument(s)
            string      project             = "";
            HealthCheck healthCheckResource = new HealthCheck();
            // Make the request
            lro::Operation <Operation, Operation> response = await healthChecksClient.InsertAsync(project, healthCheckResource);

            // Poll until the returned long-running operation is complete
            lro::Operation <Operation, Operation> completedResponse = await response.PollUntilCompletedAsync();

            // Retrieve the operation result
            Operation result = completedResponse.Result;

            // Or get the name of the operation
            string operationName = response.Name;
            // This name can be stored, then the long-running operation retrieved later by name
            lro::Operation <Operation, Operation> retrievedResponse = await healthChecksClient.PollOnceInsertAsync(operationName);

            // Check if the retrieved long-running operation has completed
            if (retrievedResponse.IsCompleted)
            {
                // If it has completed, then access the result
                Operation retrievedResult = retrievedResponse.Result;
            }
            // End snippet
        }
        public void CanAssignDelegate()
        {
            var healthCheck = new HealthCheck(ServiceHealth.Ok, "testing123");
            var check = new HostHealthCheck(host => healthCheck);

            var result = check.HealthCheckDelegate(fixture.Host);

            result.Should().Be(healthCheck);
        }
        public void HealthCheck_Should_Return_200()
        {
            var req = new HealthCheck();

            var res = service.Get(req);

            var check = res.Should().BeOfType<HealthCheck>().Subject;
            check.HealthResult.Should().Be(ServiceHealth.Ok);
            check.Message.Should().Be("Not implemented");
        }
        public void Critical_HealthCheck_Should_Return_503_With_Message()
        {
            consulFeature.Settings.AddServiceCheck(host => new HealthCheck(ServiceHealth.Critical, "My fatal"));
            var req = new HealthCheck();

            var res = service.Get(req);

            var check = res.Should().BeOfType<HttpError>().Subject;
            check.StatusCode.Should().Be(HttpStatusCode.ServiceUnavailable);
            check.Message.Should().Be("My fatal");
        }
        public void Exception_HealthCheck_Should_Return_503_With_Message()
        {
            consulFeature.Settings.AddServiceCheck(host => { throw new ApplicationException("oh dear"); });
            var req = new HealthCheck();

            var res = service.Get(req);

            var check = res.Should().BeOfType<HttpError>().Subject;
            check.StatusCode.Should().Be(HttpStatusCode.ServiceUnavailable);
            check.Message.Should().StartWith(@"Health check threw unexpected exception System.ApplicationException: oh dear");
        }
        public async Task Run_WhenNoCheckers_SuccessResult()
        {
            // Arrange
            var healthCheck = new HealthCheck(Enumerable.Empty<IChecker>());

            // Act
            var result = await healthCheck.Run();

            // Assert
            Assert.That(result.Passed, Is.True);
            Assert.That(result.Status, Is.EqualTo("success"));
            Assert.That(result.Results, Is.Empty);
        }
        public async Task Run_RunsAllCheckers()
        {
            // Arrange
            var checkerMocks = Enumerable
                .Range(1, 3)
                .Select(x =>
                {
                    var mock = new Mock<IChecker>();
                    mock.SetupGet(y => y.Name).Returns(x.ToString());
                    mock.Setup(y => y.Check()).ReturnsAsync(new CheckResult());
                    return mock;
                })
                .ToArray();
            var healthCheck = new HealthCheck(checkerMocks.Select(x => x.Object));

            // Act
            await healthCheck.Run();

            // Assert
            foreach (var checkerMock in checkerMocks)
            {
                checkerMock.Verify(x => x.Check(), Times.Once);
            }
        }
        public void Warning_HealthCheck_Should_Return_429_With_Message()
        {
            consulFeature.Settings.AddServiceCheck(host => new HealthCheck(ServiceHealth.Warning, "My warning"));
            var req = new HealthCheck();

            var res = service.Get(req);

            var check = res.Should().BeOfType<HttpError>().Subject;
            check.StatusCode.Should().Be((HttpStatusCode)429);
            check.Message.Should().Be("My warning");
        }
        public async Task Run_WhenSomethingOutsideOfTheCheckersThrows_FailureResult()
        {
            // Arrange
            var checkersMock = new Mock<IEnumerable<IChecker>>();
            var exception = new Exception("surprise");
            checkersMock.Setup(x => x.GetEnumerator()).Throws(exception);
            var healthCheck = new HealthCheck(checkersMock.Object);

            // Act
            var result = await healthCheck.Run();

            // Assert
            Assert.That(result.Passed, Is.False);
            Assert.That(result.Status, Is.EqualTo("failure"));
            Assert.That(result.Results, Is.Not.Null);
            Assert.That(result.Results.Single().Checker, Is.EqualTo("HealthCheck"));
            Assert.That(result.Results.Single().Passed, Is.False);
            Assert.That(result.Results.Single().Output, Is.EqualTo(exception.Message));
        }
        public async Task Run_WhenAllCheckersPass_SuccessResult()
        {
            // Arrange
            var checkerMocks = Enumerable
                .Range(1, 3)
                .Select(x =>
                {
                    var mock = new Mock<IChecker>();
                    mock.SetupGet(y => y.Name).Returns(x.ToString());
                    mock.Setup(y => y.Check()).ReturnsAsync(new CheckResult { Passed = true });
                    return mock;
                })
                .ToArray();
            var healthCheck = new HealthCheck(checkerMocks.Select(x => x.Object));

            // Act
            var result = await healthCheck.Run();

            // Assert
            Assert.That(result.Passed, Is.True);
            Assert.That(result.Status, Is.EqualTo("success"));
            Assert.That(result.Results.Length, Is.EqualTo(checkerMocks.Length));
            Assert.That(result.Results.Count(x => x.Passed), Is.EqualTo(checkerMocks.Length));
        }
        public async Task Run_WhenAtLeastOneCheckerFails_FailureResult()
        {
            // Arrange
            var checkerMocks = Enumerable
                .Range(1, 3)
                .Select(x =>
                {
                    var mock = new Mock<IChecker>();
                    mock.SetupGet(y => y.Name).Returns(x.ToString());
                    mock.Setup(y => y.Check()).ReturnsAsync(new CheckResult { Passed = true });
                    return mock;
                })
                .ToArray();
            var exception = new Exception("error message");
            checkerMocks[1].Setup(x => x.Check()).ThrowsAsync(exception);
            var healthCheck = new HealthCheck(checkerMocks.Select(x => x.Object));

            // Act
            var result = await healthCheck.Run();

            // Assert
            Assert.That(result.Passed, Is.False);
            Assert.That(result.Status, Is.EqualTo("failure"));
            Assert.That(result.Results.Length, Is.EqualTo(checkerMocks.Length));
            Assert.That(result.Results.Count(x => x.Passed), Is.EqualTo(checkerMocks.Length - 1));
        }
        public void HealthCheck_Should_Return_200_With_Message()
        {
            consulFeature.Settings.AddServiceCheck(host => new HealthCheck(ServiceHealth.Ok, "My message"));
            var req = new HealthCheck();

            var res = service.Get(req);

            var check = res.Should().BeOfType<HealthCheck>().Subject;
            check.HealthResult.Should().Be(ServiceHealth.Ok);
            check.Message.Should().Be("My message");
        }
 public static HealthCheck CreateHealthCheck(string status, bool active, long ID, global::System.Guid tid, string name, long createdById, long modifiedById, global::System.DateTimeOffset created, global::System.DateTimeOffset modified)
 {
     HealthCheck healthCheck = new HealthCheck();
     healthCheck.Status = status;
     healthCheck.Active = active;
     healthCheck.Id = ID;
     healthCheck.Tid = tid;
     healthCheck.Name = name;
     healthCheck.CreatedById = createdById;
     healthCheck.ModifiedById = modifiedById;
     healthCheck.Created = created;
     healthCheck.Modified = modified;
     return healthCheck;
 }