public static HealthChecksBuilder AddHealthChecks(this HttpConfiguration httpConfiguration, string healthEndpoint = "health") { var hcBuilder = new HealthChecksBuilder(); var dependencyResolver = httpConfiguration.DependencyResolver; var hcConfig = hcBuilder.HealthCheckConfig; // Service Instances var healthChecksService = new HealthCheckService(dependencyResolver, hcConfig.HealthChecksDependencies); var authenticationService = new AuthenticationService(hcConfig); // Handler Instances var authenticationHandler = new AuthenticationHandler(hcConfig, authenticationService); var healthCheckHandler = new HealthCheckHandler(hcConfig, healthChecksService); // ChainOfResponsibility authenticationHandler.SetNextHandler(healthCheckHandler); httpConfiguration.Routes.MapHttpRoute( name: "health_check", routeTemplate: healthEndpoint, defaults: new { check = RouteParameter.Optional }, constraints: null, handler: authenticationHandler ); return(hcBuilder); }
public void SetUp() { var hangingChecker = Substitute.For <ISystemChecker>(); hangingChecker.SystemName.Returns("Hanging checker"); hangingChecker.CheckSystem().Returns(x => { Thread.Sleep(TimeSpan.FromSeconds(10)); return((SystemCheckResult)null); }); var healthyChecker = Substitute.For <ISystemChecker>(); healthyChecker.CheckSystem().Returns(x => new SystemCheckResult { SystemName = "Healthy checker", Health = HealthState.Good }); var healthNetConfiguration = Substitute.For <IHealthNetConfiguration>(); healthNetConfiguration.DefaultSystemCheckTimeout.Returns(TimeSpan.FromSeconds(1)); var service = new HealthCheckService(healthNetConfiguration, Substitute.For <IVersionProvider>(), new[] { hangingChecker, healthyChecker }); var task = Task <HealthResult> .Factory.StartNew(() => service.CheckHealth()); if (Task.WaitAll(new Task[] { task }, TimeSpan.FromSeconds(5))) { result = task.Result; } else { throw new TimeoutException(); } }
public async Task Invoke(Env environment) { if (IsCallToHealthCheck(environment)) { var responseHeaders = (IDictionary <string, string[]>)environment["owin.ResponseHeaders"]; responseHeaders["Content-Type"] = new[] { $"{Constants.Response.ContentType.Json}; charset=utf-8" }; var responseStream = (Stream)environment["owin.ResponseBody"]; var healthCheckService = new HealthCheckService(configuration, versionProvider ?? new AssemblyFileVersionProvider(configuration), systemCheckerResolverFactory()); var result = healthCheckService.CheckHealth(IsIntrusive(environment)); using (var writeStream = new MemoryStream()) { var contentLength = new HealthResultJsonSerializer().SerializeToStream(writeStream, result); responseHeaders["Content-Length"] = new[] { contentLength.ToString("D") }; writeStream.Position = 0; await writeStream.CopyToAsync(responseStream); } } else { await next.Invoke(environment); } }
public DiagnosticsController(HealthCheckService healthCheckService, IMapper mapper, HealthCheckOptions healthCheckOptions = null) { _healthCheckService = healthCheckService ?? throw new ArgumentNullException(nameof(healthCheckService)); _healthCheckOptions = healthCheckOptions ?? new HealthCheckOptions(); _mapper = mapper ?? throw new ArgumentNullException(nameof(mapper)); }
protected override async Task <HttpResponseMessage> GetResponseAsync(HttpRequestMessage request, CancellationToken cancellationToken) { var healthChecks = GetHealthChecks(); var service = new HealthCheckService(healthChecks, HealthChecksBuilder.ResultStatusCodes); var queryParameters = request.GetQueryNameValuePairs() .ToDictionary(kv => kv.Key, kv => kv.Value, StringComparer.OrdinalIgnoreCase); HealthStatus status; if (queryParameters.TryGetValue("check", out var check) && !string.IsNullOrEmpty(check)) { var healthResult = await service.GetHealthAsync(check); if (healthResult == null) { return(CheckNotFound(check)); } status = healthResult.Status; } else { var result = await service.GetHealthAsync(cancellationToken); status = result.Status; } return(CreateResponse(status)); }
public LogHealthChecksHostedService( ILogger <LogHealthChecksHostedService> logger, HealthCheckService healthCheckService) { _logger = logger; _healthCheckService = healthCheckService; }
public HealthCheckPublisherHostedService( HealthCheckService healthCheckService, IOptions <HealthCheckPublisherOptions> options, ILogger <HealthCheckPublisherHostedService> logger, IEnumerable <IHealthCheckPublisher> publishers) { if (healthCheckService == null) { throw new ArgumentNullException(nameof(healthCheckService)); } if (options == null) { throw new ArgumentNullException(nameof(options)); } if (logger == null) { throw new ArgumentNullException(nameof(logger)); } if (publishers == null) { throw new ArgumentNullException(nameof(publishers)); } _healthCheckService = healthCheckService; _options = options; _logger = logger; _publishers = publishers.ToArray(); _stopping = new CancellationTokenSource(); }
public static HealthChecksBuilder AddHealthChecks(this HttpConfiguration httpConfiguration, string healthEndpoint = "health") { System.Diagnostics.Debug.WriteLine("Iniciei"); // ToDo: Era para isso estar aqui mesmo? var healthChecksBuilder = new HealthChecksBuilder(); var healthChecksService = new HealthCheckService(healthChecksBuilder); var authenticationService = new AuthenticationService(healthChecksBuilder); var dependencyHandler = new DependencyHandler(httpConfiguration, healthChecksBuilder); var authenticationHandler = new AuthenticationHandler(authenticationService); var healthCheckHandler = new HealthCheckHandler(healthChecksService); dependencyHandler.SetNextHandler(authenticationHandler); authenticationHandler.SetNextHandler(healthCheckHandler); httpConfiguration.Routes.MapHttpRoute( name: "health_check", routeTemplate: healthEndpoint, defaults: new { check = RouteParameter.Optional }, constraints: null, handler: dependencyHandler ); return(healthChecksBuilder); }
public IndexModel(ILogger <IndexModel> log, IWebHostEnvironment webHostEnvironment, IOptions <AppSettings> appSettings, HealthCheckService healthCheckService) { this.log = log; this.appSettings = appSettings.Value; this.webHostEnvironment = webHostEnvironment; this.healthCheckService = healthCheckService; }
public async Task InvokeAsync(HttpContext context, HealthCheckService healthCheckService) { if (IsCallToHealthCheck(context)) { var responseHeaders = context.Response.Headers; responseHeaders["Content-Type"] = new[] { $"{Constants.Response.ContentType.Json}; charset=utf-8" }; var responseStream = context.Response.Body; var result = healthCheckService.CheckHealth(IsIntrusive(context)); using (var writeStream = new MemoryStream()) { var contentLength = serializer.SerializeToStream(writeStream, result); responseHeaders["Content-Length"] = new[] { contentLength.ToString("D") }; writeStream.Position = 0; await writeStream.CopyToAsync(responseStream); } } else { await next(context); } }
protected override void ActivateInternal() { var setting = Resolver.GetInstance <DeconzToMqttSetting>(); var logManager = Resolver.GetInstance <ILogManager>(); var metricRecorder = Resolver.GetInstance <IMetricRecorder>(); var sensorRepository = new SensorRepository(setting.DeconzApiKey, new Uri($"ws://{setting.DeconzAddress}:{setting.DeconzApiPort}")); var lightRepository = new LightRepository(setting.DeconzApiKey, new Uri($"ws://{setting.DeconzAddress}:{setting.DeconzApiPort}")); var healthCheckService = new HealthCheckService(logManager.GetLogger <HealthCheckService>()); var websockerReceiver = new WebsocketReceiver(logManager.GetLogger <WebsocketReceiver>(), new Uri($"ws://{setting.DeconzAddress}:{setting.DeconzWebsocketPort}")); var mqttClient = new MqttClient(logManager.GetLogger <MqttClient>(), metricRecorder, logManager, setting.MqttAddress, setting.MqttUsername, setting.MqttPassword); var eventHandler = new EventHandlingService(logManager.GetLogger <EventHandlingService>(), websockerReceiver, mqttClient, sensorRepository); var telemetryService = new TelemetryService(logManager.GetLogger <TelemetryService>(), metricRecorder, new DeconzRepository[] { sensorRepository, lightRepository }, mqttClient); healthCheckService.AddHealthCheck(websockerReceiver); healthCheckService.AddHealthCheck(mqttClient); mqttClient.Start(); eventHandler.Start(); websockerReceiver.Start(); telemetryService.Start(); healthCheckService.Start(); }
/// <summary>Snippet for PatchAsync</summary> public async Task PatchAsync() { // Snippet: PatchAsync(string, string, string, HealthCheckService, CallSettings) // Additional: PatchAsync(string, string, string, HealthCheckService, CancellationToken) // Create client RegionHealthCheckServicesClient regionHealthCheckServicesClient = await RegionHealthCheckServicesClient.CreateAsync(); // Initialize request argument(s) string project = ""; string region = ""; string healthCheckService = ""; HealthCheckService healthCheckServiceResource = new HealthCheckService(); // Make the request lro::Operation <Operation, Operation> response = await regionHealthCheckServicesClient.PatchAsync(project, region, healthCheckService, healthCheckServiceResource); // 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 regionHealthCheckServicesClient.PollOncePatchAsync(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 SetUp() { var hangingChecker = Substitute.For<ISystemChecker>(); hangingChecker.SystemName.Returns("Hanging checker"); hangingChecker.CheckSystem().Returns(x => { Thread.Sleep(TimeSpan.FromSeconds(10)); return (SystemCheckResult)null; }); var healthyChecker = Substitute.For<ISystemChecker>(); healthyChecker.CheckSystem().Returns(x => new SystemCheckResult { SystemName = "Healthy checker", Health = HealthState.Good }); var healthNetConfiguration = Substitute.For<IHealthNetConfiguration>(); healthNetConfiguration.DefaultSystemCheckTimeout.Returns(TimeSpan.FromSeconds(1)); var service = new HealthCheckService(healthNetConfiguration, Substitute.For<IVersionProvider>(), new[] { hangingChecker, healthyChecker }); var task = Task<HealthResult>.Factory.StartNew(() => service.CheckHealth()); if (Task.WaitAll(new Task[] {task}, TimeSpan.FromSeconds(5))) { result = task.Result; } else { throw new TimeoutException(); } }
//public PackageCache ApplicationPackageCache {get;} public PhotonServer() { Http = new HttpServer(this); Projects = new ProjectManager(); Sessions = new ServerSessionManager(); MessageRegistry = new MessageProcessorRegistry(); Variables = new VariableSetDocumentManager(); HealthChecks = new HealthCheckService(); UserMgr = new UserGroupManager(); ProjectPackageCache = new ProjectPackageCache(); ServerConfiguration = new ServerConfigurationManager(); Agents = new ServerAgentManager(); ProjectPackages = new ProjectPackageManager { PackageDirectory = Configuration.ProjectPackageDirectory, }; ApplicationPackages = new ApplicationPackageManager { PackageDirectory = Configuration.ApplicationPackageDirectory, }; Queue = new ScriptQueue { MaxDegreeOfParallelism = Configuration.Parallelism, }; ProjectPackages.PackageAdded += ProjectPackages_OnPackageAdded; }
public HomeController( ILogger <HomeController> logger, HealthCheckService healthCheckService) { _logger = logger; _healthCheckService = healthCheckService; }
public void Configure( IServiceProvider serviceProvider, IApplicationBuilder app, IWebHostEnvironment env, IHostApplicationLifetime appLifetime, ILoggerFactory loggerFactory, IApiVersionDescriptionProvider apiVersionProvider, MsSqlStreamStore streamStore, ApiDataDogToggle datadogToggle, ApiDebugDataDogToggle debugDataDogToggle, HealthCheckService healthCheckService) { StartupHelpers.CheckDatabases(healthCheckService, DatabaseTag).GetAwaiter().GetResult(); StartupHelpers.EnsureSqlStreamStoreSchema <Startup>(streamStore, loggerFactory); app .UseDatadog <Startup>( serviceProvider, loggerFactory, datadogToggle, debugDataDogToggle, _configuration["DataDog:ServiceName"]) .UseDefaultForApi(new StartupUseOptions { Common = { ApplicationContainer = _applicationContainer, ServiceProvider = serviceProvider, HostingEnvironment = env, ApplicationLifetime = appLifetime, LoggerFactory = loggerFactory, }, Api = { VersionProvider = apiVersionProvider, Info = groupName => $"exira.com - Dns API {groupName}", CustomExceptionHandlers = new IExceptionHandler[] { new DomainExceptionHandler(), new Exceptions.ApiExceptionHandler(), new AggregateNotFoundExceptionHandling(), new WrongExpectedVersionExceptionHandling(), new InvalidTopLevelDomainExceptionHandling(), new InvalidRecordTypeExceptionHandling(), new InvalidServiceTypeExceptionHandling(), new ValidationExceptionHandler(), } }, Server = { PoweredByName = "exira.com", ServerName = "exira.com" }, MiddlewareHooks = { AfterMiddleware = x => x.UseMiddleware <AddNoCacheHeadersMiddleware>(), }, }); }
/// <summary> /// Initializes a new instance of the <see cref="TcpHealthListener"/> class. /// </summary> /// <param name="configuration">The key-value application configuration properties.</param> /// <param name="tcpListenerOptions">The additional options to configure the TCP listener.</param> /// <param name="healthService">The service to retrieve the current health of the application.</param> /// <exception cref="ArgumentNullException">Thrown when the <paramref name="configuration"/>, <paramref name="tcpListenerOptions"/>, or <paramref name="healthService"/> is <c>null</c>.</exception> /// <exception cref="ArgumentException">Thrown when the <paramref name="tcpListenerOptions"/> doesn't have a filled-out value.</exception> public TcpHealthListener( IConfiguration configuration, TcpHealthListenerOptions tcpListenerOptions, HealthCheckService healthService) : this(configuration, tcpListenerOptions, healthService, NullLogger <TcpHealthListener> .Instance) { }
public static string FullyQualifiedApplicationPath(HealthCheckService svc) { //Return variable declaration var appPath = string.Empty; //Getting the current context of HTTP request var context = svc.HttpContext; //Checking the current context content if (context != null) { //Formatting the fully qualified website url/name appPath = string.Format("{0}://{1}{2}{3}", context.Request.Url.Scheme, context.Request.Url.Host, context.Request.Url.Port == 80 ? string.Empty : ":" + context.Request.Url.Port, context.Request.ApplicationPath); } if (!appPath.EndsWith("/")) { appPath += "/"; } return(appPath); }
public async Task <DateHealthReport> GetOrCheckHealthAsync(HealthCheckService healthCheckService, CancellationToken cancellationToken = default) { try { if ((Evaluating) || (Result?.Date.Add(options.CacheDuration) > DateTimeOffset.UtcNow)) { return(Result); } await _mutex.WaitAsync(cancellationToken); Evaluating = true; var report = await healthCheckService.CheckHealthAsync(cancellationToken); Result = new DateHealthReport() { Date = DateTimeOffset.UtcNow, Report = report }; Evaluating = false; return(Result); } catch (Exception) { Evaluating = false; return(Result); } finally { _mutex.Release(); } }
public DiagnoseController(DiagnoseService diagnoseService, HealthCheckService healthCheckService, DoctorService doctorService, PatientService patientService, UserManager <ApplicationUser> userManager) { _diagnoseService = diagnoseService; _healthCheckService = healthCheckService; _doctorService = doctorService; _patientService = patientService; _userManager = userManager; }
public HealthCheckServer( int port, HealthCheckService healthCheckService, string url = "/health", bool useHttps = false) : this("+", port, healthCheckService, url, useHttps) { }
public HealthController(HealthCheckService service, ITelemetryService telemetryService, ApplicationInsightsJsHelper applicationInsightsJsHelper = null, IMemoryCache memoryCache = null) { _service = service; _applicationInsightsJsHelper = applicationInsightsJsHelper; _telemetryService = telemetryService; _cache = memoryCache; }
public HealthCheckStartupFilter(HealthCheckService service, IOptionsSnapshot <ServicesDebugOptions> serviceDebug, IOptionsSnapshot <OptionsDebugOptions> optionsDebug) { _service = service; _serviceDebug = serviceDebug; _optionsDebug = optionsDebug; }
public async Task ShouldReturnUnhealthIfThrows() { var sut = new HealthCheckService(getFakeHealthChecksThatThrows(), getBuilder().ResultStatusCodes); var act = await sut.GetHealthAsync(); Assert.Equal(HealthStatus.Unhealthy, act.OverAllStatus); }
public HealthCheckHubNotifier(HealthCheckService svc) { service = svc; service.TestCompleted += service_TestCompleted; service.TestStarted += service_TestStarted; service.TestEventReceived += service_TestEventReceived; service.TestProgressChanged += service_TestProgressChanged; }
public static void RegisterTests(HealthCheckService svc) { svc.Add(new NotDebugTest(1)); svc.Add(new DbConnectionTest(2)); svc.Add(new SmtpTest(3)); svc.Setup <Hubs.HealthCheckHub>(); svc.Trace(); }
public HomeController(ILogger <HomeController> logger, IVenjixOptionsService optionsService, IMapper mapper, ITelegramService telegramService, HealthCheckService healthCheck, VenjixContext context) { _logger = logger; _optionsService = optionsService; _mapper = mapper; _telegramService = telegramService; _healthCheck = healthCheck; _context = context; }
/// <summary> /// Initializes a new instance of the <see cref="HealthFunction" /> class. /// </summary> /// <param name="healthCheckService">The service to check the current health of the running Azure Function.</param> /// <param name="httpCorrelation">The instance to handle the HTTP request correlation.</param> /// <param name="logger">The logger instance to write diagnostic trace messages while handling the HTTP request.</param> /// <exception cref="ArgumentNullException">Thrown when the <paramref name="httpCorrelation"/> is <c>null</c>.</exception> public HealthFunction( HealthCheckService healthCheckService, HttpCorrelation httpCorrelation, ILogger <HealthFunction> logger) : base(httpCorrelation, logger) { Guard.NotNull(healthCheckService, nameof(healthCheckService), "Requires a health check service to check the current health of the running Azure Function"); _healthCheckService = healthCheckService; }
public CommandHealthProbeService( HealthCheckService healthCheckService, ILogger <TcpHealthProbeService> logger, CommandHealthProbeOptions options) { _healthCheckService = healthCheckService ?? throw new ArgumentNullException(nameof(healthCheckService)); _logger = logger; _options = options; }
public HealthCheckServiceTests(AppHostFixture fixture) { this.fixture = fixture; this.fixture.Host.Container.RegisterAutoWired<HealthCheckService>(); consulFeature = fixture.Host.GetPlugin<ConsulFeature>(); var mockHttpRequest = new MockHttpRequest("Heartbeat", "GET", "json", "heartbeat", null, null, null); service = new HealthCheckService { Request = mockHttpRequest }; }
public DoctorDashboardController(PatientService patientsService, DiagnoseService diagnoseService, HealthCheckService healthCheckService, UserManager <ApplicationUser> userManager, DoctorService doctorService, TreatmentService treatmentService) { _patientsService = patientsService; _diagnoseService = diagnoseService; _healthCheckService = healthCheckService; _doctorService = doctorService; _userManager = userManager; _treatmentService = treatmentService; }
public TcpHealthProbeService( HealthCheckService healthCheckService, ILogger <TcpHealthProbeService> logger, TcpHealthProbeOptions options) { _healthCheckService = healthCheckService ?? throw new ArgumentNullException(nameof(healthCheckService)); _logger = logger; _options = options; _listener = new TcpListener(options.IpAddress, options.Port); }
public void SetUp() { var versionProvider = Substitute.For<IVersionProvider>(); versionProvider.GetSystemVersion().Returns("1.2.3.4"); var healthNetConfiguration = Substitute.For<IHealthNetConfiguration>(); healthNetConfiguration.DefaultSystemCheckTimeout.Returns(TimeSpan.FromSeconds(5)); var service = new HealthCheckService(healthNetConfiguration, versionProvider, SystemStateCheckers()); Result = service.CheckHealth(PerformeIntrusive); }
public HealthNetModule(IHealthNetConfiguration configuration, IEnumerable<ISystemChecker> systemCheckers) : base(configuration.Path) { Get[""] = p => { var healthChecker = new HealthCheckService(configuration, new VersionProvider(configuration), systemCheckers); var intrusive = false; if (Request.Query.intrusive != null) { intrusive = Request.Query.intrusive == "true"; } Action<Stream> performeHealthCheck = stream => new HealthResultJsonSerializer().SerializeToStream(stream, healthChecker.CheckHealth(intrusive)); return new Response { Contents = performeHealthCheck, ContentType = Constants.Response.ContentType.Json + "; charset=utf-8", StatusCode = HttpStatusCode.OK }; }; }