org.springframework.boot.actuate.health.Status Java Examples

The following examples show how to use org.springframework.boot.actuate.health.Status. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: AbstractSolrHealthIndicator.java    From ambari-logsearch with Apache License 2.0 9 votes vote down vote up
@Override
protected void doHealthCheck(Health.Builder builder) throws Exception {
  Status status = Status.DOWN;
  String errorDetails = null;
  if (getSolrTemplate() != null && getSolrTemplate().getSolrClient() != null) {
    try {
      SolrClient solrClient = getSolrTemplate().getSolrClient();
      SolrQuery q = new SolrQuery("*:*");
      q.setRows(0);
      QueryResponse response = solrClient.query(q);
      if (response.getStatus() == 0) {
        status = Status.UP;
        if (response.getResults() != null) {
          builder.withDetail("numDocs", response.getResults().getNumFound());
        }
      }
    } catch (Exception e) {
      errorDetails = e.getMessage();
    }
  }
  builder.status(status);
  if (errorDetails != null) {
    builder.withDetail("error", errorDetails);
  }
}
 
Example #2
Source File: ApplicationInstanceHealthWatcher.java    From microservices-dashboard with Apache License 2.0 6 votes vote down vote up
private void retrieveHealthData(ApplicationInstance instance) {
	instance.getActuatorEndpoint("health").ifPresent(link -> {
		logger.debug("Retrieving [HEALTH] data for {}", instance.getId());
		this.webClient.get().uri(link.getHref()).retrieve().bodyToMono(HealthWrapper.class)
				.defaultIfEmpty(new HealthWrapper(Status.UNKNOWN, new HashMap<>()))
				.map(HealthWrapper::getHealth)
				.doOnError(exception -> {
					logger.debug("Could not retrieve health information for [{}]", link.getHref(), exception);
					this.publisher.publishEvent(new ApplicationInstanceHealthDataRetrievalFailed(instance));
				})
				.subscribe(healthInfo -> {
					logger.debug("Retrieved health information for application instance [{}]", instance.getId());
					this.publisher.publishEvent(new ApplicationInstanceHealthDataRetrieved(instance, healthInfo));
				});
	});
}
 
Example #3
Source File: GeodeCacheServerHealthIndicatorAutoConfigurationIntegrationTests.java    From spring-boot-data-geode with Apache License 2.0 6 votes vote down vote up
@Test
public void mockCacheServerHealthCheckWithServerLoadDetails() {

	Health health = this.healthIndicator.health();

	assertThat(health).isNotNull();
	assertThat(health.getStatus()).isEqualTo(Status.UP);

	Map<String, Object> healthDetails = health.getDetails();

	assertThat(healthDetails).isNotNull();
	assertThat(healthDetails).isNotEmpty();
	assertThat(healthDetails).containsEntry("geode.cache.server.count", 1);
	assertThat(healthDetails).containsEntry("geode.cache.server.0.port", 48484);
	assertThat(healthDetails).containsEntry("geode.cache.server.0.load.connection-load", 0.65f);
	assertThat(healthDetails).containsEntry("geode.cache.server.0.load.load-per-connection", 0.35f);
	assertThat(healthDetails).containsEntry("geode.cache.server.0.load.load-per-subscription-connection", 0.75f);
	assertThat(healthDetails).containsEntry("geode.cache.server.0.load.subscription-connection-load", 0.55f);
	assertThat(healthDetails).containsEntry("geode.cache.server.0.metrics.client-count", 21);
	assertThat(healthDetails).containsEntry("geode.cache.server.0.metrics.max-connection-count", 800);
	assertThat(healthDetails).containsEntry("geode.cache.server.0.metrics.open-connection-count", 400);
	assertThat(healthDetails).containsEntry("geode.cache.server.0.metrics.subscription-connection-count", 200);
}
 
Example #4
Source File: KafkaBinderHealthIndicatorTest.java    From spring-cloud-stream-binder-kafka with Apache License 2.0 6 votes vote down vote up
@Test
public void consumerCreationFailsFirstTime() {
	final List<PartitionInfo> partitions = partitions(new Node(0, null, 0));
	topicsInUse.put(TEST_TOPIC, new KafkaMessageChannelBinder.TopicInformation(
			"foo-healthIndicator", partitions, false));

	org.mockito.BDDMockito.given(consumerFactory.createConsumer())
			.willThrow(KafkaException.class).willReturn(consumer);

	Health health = indicator.health();
	assertThat(health.getStatus()).isEqualTo(Status.DOWN);

	health = indicator.health();
	assertThat(health.getStatus()).isEqualTo(Status.UP);

	org.mockito.Mockito.verify(this.consumerFactory, Mockito.times(2))
			.createConsumer();
}
 
Example #5
Source File: ApplicationInstanceHealthWatcherTests.java    From microservices-dashboard with Apache License 2.0 6 votes vote down vote up
private void assertHealthInfoRetrievalSucceeded(List<ApplicationInstance> applicationInstances) {
	String logOutput = this.outputCapture.toString();
	assertThat(logOutput).contains("Retrieving [HEALTH] data for all application instances");
	applicationInstances.forEach((applicationInstance) -> {
		assertThat(logOutput).contains(String.format("Retrieving [HEALTH] data for %s", applicationInstance.getId()));
		assertThat(logOutput).contains(String.format("Retrieved health information for application instance [%s]",
				applicationInstance.getId()));
	});

	verify(this.applicationEventPublisher, times(applicationInstances.size()))
			.publishEvent(this.applicationEventArgumentCaptor.capture());
	verifyNoMoreInteractions(this.applicationEventPublisher);

	List<ApplicationInstanceHealthDataRetrieved> healthInfoRetrievals =
			(List) this.applicationEventArgumentCaptor.getAllValues();

	healthInfoRetrievals.forEach(healthInfoRetrieved -> {
		ApplicationInstance instance = (ApplicationInstance) healthInfoRetrieved.getSource();

		assertThat(healthInfoRetrieved).isNotNull();
		assertThat(healthInfoRetrieved.getHealth()).isNotNull();
		assertThat(healthInfoRetrieved.getHealth().getStatus()).isEqualTo(Status.UP);
		assertThat(applicationInstances).contains(instance);
	});
}
 
Example #6
Source File: SofaDashboardContextRefreshedListener.java    From sofa-dashboard-client with Apache License 2.0 6 votes vote down vote up
@Override
public void onApplicationEvent(ContextRefreshedEvent event) {
    ApplicationContext context = event.getApplicationContext();
    ReadinessCheckListener readinessCheckListener = context
        .getBean(ReadinessCheckListener.class);
    AppPublisher publisher = context.getBean(AppPublisher.class);

    try {
        String status = readinessCheckListener.getHealthCheckerStatus() ? Status.UP.toString()
            : Status.DOWN.toString();
        publisher.getApplication().setAppState(status);
        publisher.start();
        publisher.register();
    } catch (Exception e) {
        LOGGER.info("sofa dashboard client register failed.", e);
    }
}
 
Example #7
Source File: ReactiveDiscoveryClientHealthIndicator.java    From spring-cloud-commons with Apache License 2.0 6 votes vote down vote up
private Mono<Health> doHealthCheck() {
	// @formatter:off
	return Mono.justOrEmpty(this.discoveryClient)
			.flatMapMany(ReactiveDiscoveryClient::getServices)
			.collectList()
			.defaultIfEmpty(emptyList())
			.map(services -> {
				ReactiveDiscoveryClient client = this.discoveryClient;
				String description = (this.properties.isIncludeDescription())
						? client.description() : "";
				return Health.status(new Status("UP", description))
						.withDetail("services", services).build();
			})
			.onErrorResume(exception -> {
				this.log.error("Error", exception);
				return Mono.just(Health.down().withException(exception).build());
			});
	// @formatter:on
}
 
Example #8
Source File: VaultReactiveHealthIndicatorIntegrationTests.java    From spring-cloud-vault with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldReturnHealthState() {

	ReactiveVaultTemplate vaultTemplate = new ReactiveVaultTemplate(
			TestRestTemplateFactory.TEST_VAULT_ENDPOINT,
			ClientHttpConnectorFactory.create(new ClientOptions(),
					Settings.createSslConfiguration()),
			() -> Mono.just(Settings.token()));

	VaultReactiveHealthIndicator healthIndicator = new VaultReactiveHealthIndicator(
			vaultTemplate);

	healthIndicator.doHealthCheck(Health.up()).as(StepVerifier::create)
			.consumeNextWith(actual -> {
				assertThat(actual.getStatus()).isEqualTo(Status.UP);
			}).verifyComplete();
}
 
Example #9
Source File: KafkaBinderHealthIndicatorTest.java    From spring-cloud-stream-binder-kafka with Apache License 2.0 5 votes vote down vote up
@Test
public void kafkaBinderIsUpWithRegexTopic() {
	topicsInUse.put(REGEX_TOPIC, new KafkaMessageChannelBinder.TopicInformation(
			"regex-healthIndicator", null, true));
	Health health = indicator.health();
	// verify no consumer interaction for retrieving partitions
	org.mockito.BDDMockito.verify(consumer, Mockito.never())
			.partitionsFor(REGEX_TOPIC);
	// Ensuring the normal health check returns with status "up"
	assertThat(health.getStatus()).isEqualTo(Status.UP);
}
 
Example #10
Source File: DatastoreHealthIndicatorTests.java    From spring-cloud-gcp with Apache License 2.0 5 votes vote down vote up
@Test
public void testUnhealthy() {
	DatastoreHealthIndicator datastoreHealthIndicator = new DatastoreHealthIndicator(() -> datastore);

	when(datastore.run(any())).thenThrow(new RuntimeException("Cloud Datastore is down!!!"));

	assertThat(datastoreHealthIndicator.health().getStatus()).isEqualTo(Status.DOWN);
}
 
Example #11
Source File: ApplicationInstanceHealthWatcherTests.java    From microservices-dashboard with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldRetrieveTheHealthDataAfterActuatorEndpointsHaveBeenUpdatedWithHealthLink() {
	ActuatorEndpointsUpdated event =
			ApplicationInstanceEventMother.actuatorEndpointsUpdated("a-1", "a",
					new Links(new Link("http://localhost:8080/actuator/health", "health")));

	when(this.responseSpec.bodyToMono(ApplicationInstanceHealthWatcher.HealthWrapper.class)).thenReturn(Mono
			.just(new ApplicationInstanceHealthWatcher.HealthWrapper(Status.UP, null)));

	this.healthWatcher.retrieveHealthData(event);

	assertHealthInfoRetrievalSucceeded((ApplicationInstance) event.getSource());
}
 
Example #12
Source File: ReactiveDiscoveryClientHealthIndicatorTests.java    From spring-cloud-commons with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldReturnUnknownStatusWhenNotInitialized() {
	Health expectedHealth = Health.status(
			new Status(Status.UNKNOWN.getCode(), "Discovery Client not initialized"))
			.build();
	Mono<Health> health = indicator.health();
	StepVerifier.create(health).expectNext(expectedHealth).expectComplete().verify();
}
 
Example #13
Source File: KafkaStreamsBinderHealthIndicatorTests.java    From spring-cloud-stream-binder-kafka with Apache License 2.0 5 votes vote down vote up
private static boolean waitFor(Status status, Map<String, Object> details) {
	if (status == Status.UP) {
		String threadState = (String) details.get("threadState");
		return threadState != null
				&& (threadState.equalsIgnoreCase(KafkaStreams.State.REBALANCING.name())
						|| threadState.equalsIgnoreCase("PARTITIONS_REVOKED")
						|| threadState.equalsIgnoreCase("PARTITIONS_ASSIGNED")
						|| threadState.equalsIgnoreCase(
								KafkaStreams.State.PENDING_SHUTDOWN.name()));
	}
	return false;
}
 
Example #14
Source File: ProcessEngineHealthIndicatorTest.java    From camunda-bpm-platform with Apache License 2.0 5 votes vote down vote up
@Test
public void upTest() {
  when(processEngine.getName()).thenReturn(PROCESS_ENGINE_NAME);
  Health health = new ProcessEngineHealthIndicator(processEngine).health();
  assertEquals(Status.UP, health.getStatus());
  assertEquals(PROCESS_ENGINE_NAME, health.getDetails().get("name"));
}
 
Example #15
Source File: KafkaStreamsBinderHealthIndicatorTests.java    From spring-cloud-stream-binder-kafka with Apache License 2.0 5 votes vote down vote up
@Test
public void healthIndicatorUpTest() throws Exception {
	try (ConfigurableApplicationContext context = singleStream("ApplicationHealthTest-xyz")) {
		receive(context,
				Lists.newArrayList(new ProducerRecord<>("in", "{\"id\":\"123\"}"),
						new ProducerRecord<>("in", "{\"id\":\"123\"}")),
				Status.UP, "out");
	}
}
 
Example #16
Source File: VaultHealthIndicatorUnitTests.java    From spring-cloud-vault with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldReportHealthyService() {

	when(this.healthResponse.isInitialized()).thenReturn(true);
	when(this.vaultOperations.opsForSys()).thenReturn(this.vaultSysOperations);

	Health health = this.healthIndicator.health();
	assertThat(health.getStatus()).isEqualTo(Status.UP);
	assertThat(health.getDetails()).isEmpty();
}
 
Example #17
Source File: KafkaStreamsBinderHealthIndicatorTests.java    From spring-cloud-stream-binder-kafka with Apache License 2.0 5 votes vote down vote up
@Test
public void healthIndicatorDownMultipleKStreamsTest() throws Exception {
	try (ConfigurableApplicationContext context = multipleStream()) {
		receive(context,
				Lists.newArrayList(new ProducerRecord<>("in", "{\"id\":\"123\"}"),
						new ProducerRecord<>("in2", "{\"id\":\"124\"}")),
				Status.DOWN, "out", "out2");
	}
}
 
Example #18
Source File: AbstractChannelHealthIndicatorTest.java    From synapse with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldBeDownIfOneChannelStarted() {
    // given
    final List<String> eventSourceNames = asList("some-stream","other-stream");
    final AbstractChannelHealthIndicator healthCheck = createHealthIndicator(eventSourceNames);

    // when
    whenRunning(healthCheck, "some-stream", ofSeconds(0));


    // then
    final Health health = healthCheck.health();
    assertThat(health.getStatus(), is(Status.DOWN));
    assertThat(health.getDetails(), hasEntry("message", "Channel(s) not yet up to date"));
}
 
Example #19
Source File: EurekaHealthCheckHandler.java    From spring-cloud-netflix with Apache License 2.0 5 votes vote down vote up
protected Status getStatus(StatusAggregator statusAggregator) {
	Status status;
	Set<Status> statusSet = healthIndicators.values().stream()
			.map(HealthIndicator::health).map(Health::getStatus)
			.collect(Collectors.toSet());
	status = statusAggregator.getAggregateStatus(statusSet);
	return status;
}
 
Example #20
Source File: JobExecutorHealthIndicatorTest.java    From camunda-bpm-spring-boot-starter with Apache License 2.0 5 votes vote down vote up
@Test
public void upTest() {
  when(jobExecutor.isActive()).thenReturn(true);
  JobExecutorHealthIndicator indicator = new JobExecutorHealthIndicator(jobExecutor);
  Health health = indicator.health();
  assertEquals(Status.UP, health.getStatus());
  assertDetails(health);
}
 
Example #21
Source File: SentinelHealthIndicatorTests.java    From spring-cloud-alibaba with Apache License 2.0 5 votes vote down vote up
@Test
public void testSentinelDashboardConfiguredFailed() throws Exception {
	when(sentinelProperties.isEnabled()).thenReturn(true);
	SentinelConfig.setConfig(TransportConfig.CONSOLE_SERVER, "localhost:8080");
	when(heartbeatSender.sendHeartbeat()).thenReturn(false);

	Health health = sentinelHealthIndicator.health();

	assertThat(health.getStatus()).isEqualTo(Status.DOWN);
	assertThat(health.getDetails().get("dashboard")).isEqualTo(
			new Status(Status.DOWN.getCode(), "localhost:8080 can't be connected"));
}
 
Example #22
Source File: DatastoreHealthIndicatorTests.java    From spring-cloud-gcp with Apache License 2.0 5 votes vote down vote up
@Test
public void testHealthy()  {
	DatastoreHealthIndicator datastoreHealthIndicator = new DatastoreHealthIndicator(() -> datastore);

	when(datastore.run(any())).thenReturn(null);

	assertThat(datastoreHealthIndicator.health().getStatus()).isSameAs(Status.UP);
}
 
Example #23
Source File: PubSubHealthIndicatorTests.java    From spring-cloud-gcp with Apache License 2.0 5 votes vote down vote up
@Test
public void healthDownGenericException() {
	when(pubSubTemplate.pull(anyString(), anyInt(), anyBoolean()))
			.thenThrow(new IllegalStateException("Illegal State"));
	PubSubHealthIndicator healthIndicator = new PubSubHealthIndicator(pubSubTemplate);
	assertThat(healthIndicator.health().getStatus()).isEqualTo(Status.DOWN);
}
 
Example #24
Source File: ApplicationInstanceHealthWatcherTests.java    From microservices-dashboard with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldUpdateTheHealthOfAnApplicationInstanceWhenHealthDataRetrieved() {
	ApplicationInstanceHealthDataRetrieved event = ApplicationInstanceEventMother
			.applicationInstanceHealthDataRetrieved("a-1", "a", Health.up().build());

	this.healthWatcher.updateHealthForApplicationInstance(event);

	ArgumentCaptor<UpdateApplicationInstanceHealth> captor = ArgumentCaptor.forClass(UpdateApplicationInstanceHealth.class);
	verify(this.applicationInstanceService).updateApplicationInstanceHealth(captor.capture());
	UpdateApplicationInstanceHealth command = captor.getValue();
	assertThat(command.getId()).isEqualTo("a-1");
	assertThat(command.getHealthStatus()).isEqualTo(Status.UP);
	verifyNoMoreInteractions(this.applicationInstanceService);
	verifyZeroInteractions(this.applicationEventPublisher);
}
 
Example #25
Source File: ApplicationInstanceServiceTests.java    From microservices-dashboard with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldUpdateTheHealthOfAnApplicationInstance() {
	when(this.repository.getById("a-1")).thenReturn(ApplicationInstanceMother.instance("a-1", "a"));
	when(this.repository.save(any(ApplicationInstance.class)))
			.thenAnswer((Answer<ApplicationInstance>) invocation -> invocation.getArgument(0));

	UpdateApplicationInstanceHealth command = new UpdateApplicationInstanceHealth("a-1", Status.UP);
	this.service.updateApplicationInstanceHealth(command);

	verify(this.repository).save(this.applicationInstanceArgumentCaptor.capture());
	ApplicationInstance applicationInstance = this.applicationInstanceArgumentCaptor.getValue();
	assertThat(applicationInstance.getId()).isEqualTo("a-1");
}
 
Example #26
Source File: VaultHealthIndicatorUnitTests.java    From spring-cloud-vault with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldReportRecoveryReplication() {

	when(this.healthResponse.isInitialized()).thenReturn(true);
	when(this.healthResponse.isRecoveryReplicationSecondary()).thenReturn(true);

	Health health = this.healthIndicator.health();

	assertThat(health.getStatus()).isEqualTo(Status.UP);
	assertThat(health.getDetails()).containsEntry("state",
			"Vault in recovery replication secondary mode");
}
 
Example #27
Source File: BootHealthCheckHandler.java    From kork with Apache License 2.0 5 votes vote down vote up
@Override
public InstanceInfo.InstanceStatus getStatus(InstanceInfo.InstanceStatus currentStatus) {
  final String statusCode = aggregateHealth.health().getStatus().getCode();
  if (Status.UP.getCode().equals(statusCode)) {
    return InstanceInfo.InstanceStatus.UP;
  } else if (Status.OUT_OF_SERVICE.getCode().equals(statusCode)) {
    return InstanceInfo.InstanceStatus.OUT_OF_SERVICE;
  } else if (Status.DOWN.getCode().equals(statusCode)) {
    return InstanceInfo.InstanceStatus.DOWN;
  } else {
    return InstanceInfo.InstanceStatus.UNKNOWN;
  }
}
 
Example #28
Source File: PortalDeServicosIndexHealthIndicatorTest.java    From portal-de-servicos with MIT License 5 votes vote down vote up
@Test
public void retornaUpParaAmbosIndicesCriados() throws Exception {
    given(es.count(any(SearchQuery.class))).willReturn(42L);

    given(es.indexExists(PORTAL_DE_SERVICOS_INDEX)).willReturn(true);

    Health health = indicator.health();

    assertThat(health.getStatus(), is(Status.UP));
    assertThat(health.getDetails().get(PORTAL_DE_SERVICOS_INDEX), is("ok (42 docs)"));
}
 
Example #29
Source File: SentinelHealthIndicatorTests.java    From spring-cloud-alibaba with Apache License 2.0 5 votes vote down vote up
@Test
public void testSentinelDataSourceSuccess() throws Exception {
	when(sentinelProperties.isEnabled()).thenReturn(true);
	SentinelConfig.setConfig(TransportConfig.CONSOLE_SERVER, "localhost:8080");
	when(heartbeatSender.sendHeartbeat()).thenReturn(true);

	Map<String, AbstractDataSource> dataSourceMap = new HashMap<>();

	FileRefreshableDataSource fileDataSource1 = mock(FileRefreshableDataSource.class);
	dataSourceMap.put("ds1-sentinel-file-datasource", fileDataSource1);

	FileRefreshableDataSource fileDataSource2 = mock(FileRefreshableDataSource.class);
	dataSourceMap.put("ds2-sentinel-file-datasource", fileDataSource2);

	when(beanFactory.getBeansOfType(AbstractDataSource.class))
			.thenReturn(dataSourceMap);

	Health health = sentinelHealthIndicator.health();

	assertThat(health.getStatus()).isEqualTo(Status.UP);
	Map<String, Status> dataSourceDetailMap = (Map<String, Status>) health
			.getDetails().get("dataSource");
	assertThat(dataSourceDetailMap.get("ds1-sentinel-file-datasource"))
			.isEqualTo(Status.UP);
	assertThat(dataSourceDetailMap.get("ds2-sentinel-file-datasource"))
			.isEqualTo(Status.UP);
}
 
Example #30
Source File: HazelcastJetHealthContributorAutoConfigurationIntegrationTests.java    From hazelcast-jet-contrib with Apache License 2.0 5 votes vote down vote up
@Test
public void whenShutdown_thenHazelcastJetDown() {
    this.contextRunner.run((context) -> {
        context.getBean(JetInstance.class).shutdown();
        assertThat(context).hasSingleBean(HazelcastJetHealthIndicator.class);
        Health health = context.getBean(HazelcastJetHealthIndicator.class).health();
        assertThat(health.getStatus()).isEqualTo(Status.DOWN);
    });
}