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

The following examples show how to use org.springframework.boot.actuate.health.Health. 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: 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 #2
Source File: NacosDiscoveryHealthIndicator.java    From spring-cloud-alibaba with Apache License 2.0 6 votes vote down vote up
@Override
protected void doHealthCheck(Health.Builder builder) throws Exception {
	// Just return "UP" or "DOWN"
	String status = namingService.getServerStatus();
	// Set the status to Builder
	builder.status(status);
	switch (status) {
	case "UP":
		builder.up();
		break;
	case "DOWN":
		builder.down();
		break;
	default:
		builder.unknown();
		break;
	}
}
 
Example #3
Source File: GeodeRegionsHealthIndicator.java    From spring-boot-data-geode with Apache License 2.0 6 votes vote down vote up
private BiConsumer<Region<?, ?>, Health.Builder> withRegionExpirationPolicyDetails() {

		return (region, builder) -> {

			if (isRegionAttributesPresent(region)) {

				String regionName = region.getName();

				RegionAttributes<?, ?> regionAttributes = region.getAttributes();

				ExpirationAttributes entryTimeToLive = regionAttributes.getEntryTimeToLive();

				if (entryTimeToLive != null) {
					builder.withDetail(cacheRegionExpirationKey(regionName, "entry.ttl.action"), String.valueOf(entryTimeToLive.getAction()))
						.withDetail(cacheRegionExpirationKey(regionName, "entry.ttl.timeout"), entryTimeToLive.getTimeout());
				}

				ExpirationAttributes entryIdleTimeout = regionAttributes.getEntryIdleTimeout();

				if (entryIdleTimeout != null) {
					builder.withDetail(cacheRegionExpirationKey(regionName, "entry.tti.action"), String.valueOf(entryIdleTimeout.getAction()))
						.withDetail(cacheRegionExpirationKey(regionName, "entry.tti.timeout"), entryIdleTimeout.getTimeout());
				}
			}
		};
	}
 
Example #4
Source File: GrpcClientHealthAutoConfiguration.java    From grpc-spring-boot-starter with MIT License 6 votes vote down vote up
/**
 * Creates a HealthIndicator based on the channels' {@link ConnectivityState}s from the underlying
 * {@link GrpcChannelFactory}.
 *
 * @param factory The factory to derive the connectivity states from.
 * @return A health indicator bean, that uses the following assumption
 *         <code>DOWN == states.contains(TRANSIENT_FAILURE)</code>.
 */
@Bean
@Lazy
public HealthIndicator grpcChannelHealthIndicator(final GrpcChannelFactory factory) {
    return () -> {
        final ImmutableMap<String, ConnectivityState> states = ImmutableMap.copyOf(factory.getConnectivityState());
        final Health.Builder health;
        if (states.containsValue(ConnectivityState.TRANSIENT_FAILURE)) {
            health = Health.down();
        } else {
            health = Health.up();
        }
        return health.withDetails(states)
                .build();
    };
}
 
Example #5
Source File: NacosDiscoveryHealthIndicator.java    From nacos-spring-boot-project with Apache License 2.0 6 votes vote down vote up
@Override
protected void doHealthCheck(Health.Builder builder) throws Exception {
	builder.up();
	NacosServiceFactory nacosServiceFactory = CacheableEventPublishingNacosServiceFactory
			.getSingleton();
	for (NamingService namingService : nacosServiceFactory.getNamingServices()) {
		if (namingService instanceof NacosServiceMetaData) {
			NacosServiceMetaData nacosServiceMetaData = (NacosServiceMetaData) namingService;
			Properties properties = nacosServiceMetaData.getProperties();
			builder.withDetail(
					JSON.toJSONString(
							PropertiesUtils.extractSafeProperties(properties)),
					namingService.getServerStatus());
		}
		if (!namingService.getServerStatus().equalsIgnoreCase(UP_STATUS)) {
			builder.down();
		}
	}
}
 
Example #6
Source File: MessageReceiverEndpointHealthIndicatorTest.java    From synapse with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldIndicateDownWhenSomeEventSourceIsFailed() {
    // given
    MessageReceiverEndpointHealthIndicator healthCheck = new MessageReceiverEndpointHealthIndicator();

    EventSource mockEventSource = mock(EventSource.class);
    when(mockEventSource.getChannelName()).thenReturn("some-stream");

    MessageReceiverNotification messageEndpointNotification = builder()
            .withStatus(FAILED)
            .withMessage("some message")
            .withChannelName("some-stream")
            .build();
    healthCheck.on(messageEndpointNotification);

    // when
    Health health = healthCheck.health();

    // then
    assertThat(health.getStatus(), is(Status.DOWN));
    assertThat(health.getDetails(), hasEntry("message", "some message"));
    assertThat(health.getDetails(), hasEntry("channelName", "some-stream"));
}
 
Example #7
Source File: LearningSpringBootHealthIndicator.java    From Learning-Spring-Boot-2.0-Second-Edition with MIT License 6 votes vote down vote up
@Override
public Health health() {
	try {
		URL url =
			new URL("http://greglturnquist.com/learning-spring-boot");
		HttpURLConnection conn =
			(HttpURLConnection) url.openConnection();
		int statusCode = conn.getResponseCode();
		if (statusCode >= 200 && statusCode < 300) {
			return Health.up().build();
		} else {
			return Health.down()
				.withDetail("HTTP Status Code", statusCode)
				.build();
		}
	} catch (IOException e) {
		return Health.down(e).build();
	}
}
 
Example #8
Source File: ReactiveDiscoveryCompositeHealthContributorTests.java    From spring-cloud-commons with Apache License 2.0 6 votes vote down vote up
@Test
void shouldReturnKnownContributor() {
	ReactiveDiscoveryHealthIndicator indicator = mock(
			ReactiveDiscoveryHealthIndicator.class);
	Health health = Health.up().build();
	when(indicator.getName()).thenReturn("known");
	when(indicator.health()).thenReturn(Mono.just(health));

	ReactiveDiscoveryCompositeHealthContributor healthContributor = new ReactiveDiscoveryCompositeHealthContributor(
			singletonList(indicator));

	assertThat(healthContributor.getContributor("known")).isNotNull();
	Iterator<NamedContributor<ReactiveHealthContributor>> iterator = healthContributor
			.iterator();
	assertThat(iterator.hasNext()).isTrue();
	NamedContributor<ReactiveHealthContributor> contributor = iterator.next();
	assertThat(contributor).isNotNull();
	assertThat(contributor.getName()).isEqualTo("known");
	assertThat(contributor.getContributor()).isNotNull();
	assertThat(contributor.getContributor())
			.isInstanceOf(ReactiveHealthIndicator.class);
	ReactiveHealthIndicator healthIndicator = (ReactiveHealthIndicator) contributor
			.getContributor();
	StepVerifier.create(healthIndicator.getHealth(true)).expectNext(health)
			.expectComplete().verify();
}
 
Example #9
Source File: InfluxDB2HealthIndicator.java    From influxdb-client-java with MIT License 6 votes vote down vote up
@Override
protected void doHealthCheck(final Health.Builder builder) {
    HealthCheck check = this.influxDBClient.health();

    switch (check.getStatus()) {
        case PASS:
            builder.up();
            break;
        case FAIL:
            builder.down();
            break;
        default:
            builder.unknown();
    }

    builder
            .withDetail("status", check.getStatus())
            .withDetail("message", check.getMessage());
}
 
Example #10
Source File: HealthBuilderDelegate.java    From spring-cloud-vault with Apache License 2.0 6 votes vote down vote up
static void contributeToHealth(VaultHealth healthResponse, Health.Builder builder) {

		if (!healthResponse.isInitialized()) {
			builder.down().withDetail("state", "Vault uninitialized");
		}
		else if (healthResponse.isSealed()) {
			builder.down().withDetail("state", "Vault sealed");
		}
		else if (healthResponse.isStandby()) {
			builder.up().withDetail("state", "Vault in standby");
		}
		else if (healthResponse.isPerformanceStandby()) {
			builder.up().withDetail("state", "Vault in performance standby");
		}
		else if (healthResponse.isRecoveryReplicationSecondary()) {
			builder.up().withDetail("state",
					"Vault in recovery replication secondary mode");
		}
		else {
			builder.up();
		}

		if (StringUtils.hasText(healthResponse.getVersion())) {
			builder.withDetail("version", healthResponse.getVersion());
		}
	}
 
Example #11
Source File: WackoHealthIndicator.java    From spring-in-action-5-samples with Apache License 2.0 6 votes vote down vote up
@Override
public Health health() {
  int hour = Calendar.getInstance().get(Calendar.HOUR_OF_DAY);
  if (hour > 12) {
    return Health
        .outOfService()
        .withDetail("reason",
            "I'm out of service after lunchtime")
     .withDetail("hour", hour)
     .build();
  }
  
  if (Math.random() < 0.1) {
    return Health
        .down()
        .withDetail("reason", "I break 10% of the time")
        .build();
  }
  
  return Health
      .up()
      .withDetail("reason", "All is good!")
      .build();
}
 
Example #12
Source File: WackoHealthIndicator.java    From spring-in-action-5-samples with Apache License 2.0 6 votes vote down vote up
@Override
public Health health() {
  int hour = Calendar.getInstance().get(Calendar.HOUR_OF_DAY);
  if (hour > 12) {
    return Health
        .outOfService()
        .withDetail("reason",
            "I'm out of service after lunchtime")
     .withDetail("hour", hour)
     .build();
  }
  
  if (Math.random() < 0.1) {
    return Health
        .down()
        .withDetail("reason", "I break 10% of the time")
        .build();
  }
  
  return Health
      .up()
      .withDetail("reason", "All is good!")
      .build();
}
 
Example #13
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 #14
Source File: QueueHealthIndicator.java    From sdmq with Apache License 2.0 6 votes vote down vote up
@Override
public Health health() {
    try {
        Health.Builder builder = Health.up();
        if (leaderManager == null) {
            builder.withDetail("run", queue.isRunning());
        } else {
            builder.withDetail("run", queue.isRunning()).withDetail("isMaster", leaderManager.isLeader());
        }
        return builder
                .withDetail("isCluster", redisQueueProperties.isCluster())
                .withDetail("bucketSize", redisQueueProperties.getBucketSize())
                .withDetail("prefix", redisQueueProperties.getPrefix())
                .withDetail("namespace", ServerNode.NAMESPACE)
                .build();
    } catch (Exception e) {
        return Health.down(e).build();
    }
}
 
Example #15
Source File: LearningSpringBootHealthIndicator.java    From Learning-Spring-Boot-2.0-Second-Edition with MIT License 6 votes vote down vote up
@Override
public Health health() {
	try {
		URL url =
			new URL("http://greglturnquist.com/learning-spring-boot");
		HttpURLConnection conn =
			(HttpURLConnection) url.openConnection();
		int statusCode = conn.getResponseCode();
		if (statusCode >= 200 && statusCode < 300) {
			return Health.up().build();
		} else {
			return Health.down()
				.withDetail("HTTP Status Code", statusCode)
				.build();
		}
	} catch (IOException e) {
		return Health.down(e).build();
	}
}
 
Example #16
Source File: GatewayHealthIndicatorTest.java    From api-layer with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void testStatusIsDownWhenDiscoveryIsNotAvailable() {
    DiscoveryClient discoveryClient = mock(DiscoveryClient.class);
    when(discoveryClient.getInstances(CoreService.API_CATALOG.getServiceId())).thenReturn(
        Collections.singletonList(new DefaultServiceInstance(CoreService.API_CATALOG.getServiceId(), "host", 10014, true)));
    when(discoveryClient.getInstances(CoreService.DISCOVERY.getServiceId())).thenReturn(Collections.emptyList());
    when(discoveryClient.getInstances(ZOSMF)).thenReturn(Collections.emptyList());

    GatewayHealthIndicator gatewayHealthIndicator = new GatewayHealthIndicator(discoveryClient, authConfigurationProperties);
    Health.Builder builder = new Health.Builder();
    gatewayHealthIndicator.doHealthCheck(builder);
    assertEquals(Status.DOWN, builder.build().getStatus());
}
 
Example #17
Source File: GatewayHealthIndicatorTest.java    From api-layer with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void testStatusIsUpWhenCatalogAndDiscoveryAreAvailable() {
    DiscoveryClient discoveryClient = mock(DiscoveryClient.class);
    when(discoveryClient.getInstances(CoreService.API_CATALOG.getServiceId())).thenReturn(
        Collections.singletonList(new DefaultServiceInstance(CoreService.API_CATALOG.getServiceId(), "host", 10014, true)));
    when(discoveryClient.getInstances(CoreService.DISCOVERY.getServiceId())).thenReturn(
        Collections.singletonList(new DefaultServiceInstance(CoreService.DISCOVERY.getServiceId(), "host", 10011, true)));
    when(discoveryClient.getInstances(ZOSMF)).thenReturn(
        Collections.singletonList(new DefaultServiceInstance(ZOSMF, "host", 10050, true)));

    GatewayHealthIndicator gatewayHealthIndicator = new GatewayHealthIndicator(discoveryClient, authConfigurationProperties);
    Health.Builder builder = new Health.Builder();
    gatewayHealthIndicator.doHealthCheck(builder);
    assertEquals(Status.UP, builder.build().getStatus());
}
 
Example #18
Source File: AdvancedDiskSpaceHealthIndicator.java    From super-cloudops with Apache License 2.0 5 votes vote down vote up
@Bean(BEAN_NAME)
public HealthIndicator diskSpaceHealthIndicator(HealthAggregator healthAggregator, DiskSpaceHealthProperties conf) {
	if (logger.isInfoEnabled())
		logger.info("Initial diskSpaceHealthIndicator. {}", conf);

	AdvancedDiskSpaceHealthIndicator healthIndicator = new AdvancedDiskSpaceHealthIndicator(conf);
	Map<String, Health> healths = new LinkedHashMap<String, Health>();
	healths.put(AdvancedDiskSpaceHealthIndicator.class.getSimpleName(), healthIndicator.health());
	return healthIndicator;
}
 
Example #19
Source File: ServiceDiscoveryConfiguration.java    From Kafdrop with Apache License 2.0 5 votes vote down vote up
@Override
protected void doHealthCheck(Health.Builder builder) throws Exception
{
   if (framework.getZookeeperClient().isConnected())
   {
      builder.up();
   }
   else
   {
      builder.down();
   }
}
 
Example #20
Source File: AbstractChannelHealthIndicatorTest.java    From synapse with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldIndicateDownBeforeLastChannelHasFinished_OneMessage() {
    // given
    final List<String> eventSourceNames = asList("some-stream","other-stream");
    final AbstractChannelHealthIndicator healthCheck = createHealthIndicator(eventSourceNames);

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

    // 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 #21
Source File: KafkaBinderHealthIndicatorTest.java    From spring-cloud-stream-binder-kafka with Apache License 2.0 5 votes vote down vote up
@Test(timeout = 5000)
public void kafkaBinderDoesNotAnswer() {
	final List<PartitionInfo> partitions = partitions(new Node(-1, null, 0));
	topicsInUse.put(TEST_TOPIC, new KafkaMessageChannelBinder.TopicInformation(
			"group3-healthIndicator", partitions, false));
	org.mockito.BDDMockito.given(consumer.partitionsFor(TEST_TOPIC))
			.willAnswer(invocation -> {
				final int fiveMinutes = 1000 * 60 * 5;
				Thread.sleep(fiveMinutes);
				return partitions;
			});
	this.indicator.setTimeout(1);
	Health health = indicator.health();
	assertThat(health.getStatus()).isEqualTo(Status.DOWN);
}
 
Example #22
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 #23
Source File: RpcAfterHealthCheckCallback.java    From sofa-rpc-boot-projects with Apache License 2.0 5 votes vote down vote up
/**
 * 健康检查
 *
 * @param applicationContext Spring 上下文
 * @return 健康检查结果
 */
@Override
public Health onHealthy(ApplicationContext applicationContext) {
    Health.Builder builder = new Health.Builder();

    //rpc 开始启动事件监听器
    applicationContext.publishEvent(new SofaBootRpcStartEvent(applicationContext));

    //rpc 启动完毕事件监听器
    applicationContext.publishEvent(new SofaBootRpcStartAfterEvent(applicationContext));

    return builder.status(Status.UP).build();
}
 
Example #24
Source File: GeodeCacheHealthIndicator.java    From spring-boot-data-geode with Apache License 2.0 5 votes vote down vote up
private Function<Health.Builder, Health.Builder> withCacheDetails() {

		return healthBuilder -> healthBuilder.withDetail("geode.cache.name", getGemFireCache().map(GemFireCache::getName).orElse(""))
				.withDetail("geode.cache.closed", getGemFireCache().map(GemFireCache::isClosed).map(this::toYesNoString).orElse("Yes"))
			.withDetail("geode.cache.cancel-in-progress", getGemFireCache()
				.map(GemFireCache::getCancelCriterion)
				.filter(CancelCriterion::isCancelInProgress)
				.isPresent() ? "Yes" : "No");
	}
 
Example #25
Source File: RabbitMQCheck.java    From flow-platform-x with Apache License 2.0 5 votes vote down vote up
@Override
protected void doHealthCheck(Health.Builder builder) {
    Map<String, Object> properties = connection.getServerProperties();
    Status status = connection.isOpen() ? Status.UP : Status.DOWN;
    builder.status(status)
            .withDetail("address", connection.getAddress())
            .withDetail("version", properties.get("version").toString());
}
 
Example #26
Source File: SentinelHealthIndicatorTests.java    From spring-cloud-alibaba with Apache License 2.0 5 votes vote down vote up
@Test
public void testSentinelDataSourceFailed() 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);
	when(fileDataSource2.loadConfig())
			.thenThrow(new RuntimeException("fileDataSource2 error"));
	dataSourceMap.put("ds2-sentinel-file-datasource", fileDataSource2);

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

	Health health = sentinelHealthIndicator.health();

	assertThat(health.getStatus()).isEqualTo(Status.DOWN);
	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(new Status(Status.DOWN.getCode(), "fileDataSource2 error"));
}
 
Example #27
Source File: ExampleHealthIndicator.java    From building-microservices with Apache License 2.0 5 votes vote down vote up
@Override
public Health health() {
	if ((int) (System.currentTimeMillis() / 1000) % 2 == 0) {
		return Health.outOfService().withDetail("time", "is running out").build();
	}
	return Health.up().build();
}
 
Example #28
Source File: ProductCompositeIntegration.java    From Hands-On-Microservices-with-Spring-Boot-and-Spring-Cloud with MIT License 5 votes vote down vote up
private Mono<Health> getHealth(String url) {
    url += "/actuator/health";
    LOG.debug("Will call the Health API on URL: {}", url);
    return getWebClient().get().uri(url).retrieve().bodyToMono(String.class)
        .map(s -> new Health.Builder().up().build())
        .onErrorResume(ex -> Mono.just(new Health.Builder().down(ex).build()))
        .log();
}
 
Example #29
Source File: ODataHealthIndicator.java    From cloud-s4-sdk-examples with Apache License 2.0 5 votes vote down vote up
@Override
public Health health() {
    final SapClient sapClient = new SapClient("SAPCLIENT-NUMBER"); // adjust SAP client to your respective S/4HANA system
    final String problem = checkForProblem(sapClient);
    if (problem != null) {
        return Health.down().withDetail("Error", problem).build();
    }
    return Health.up().build();
}
 
Example #30
Source File: EventStoreHealthIndicator.java    From sourcerer with MIT License 5 votes vote down vote up
private Health runHealthProbe() {
    logger.debug("Reading Event Store for health check");
    try {
        final AllEventsSlice currentEventInfo = readLastEventBlocking();

        logger.debug("Event store successfully pinged");
        return Health
                .up()
                .withDetail("position", currentEventInfo.nextPosition.toString())
                .build();
    } catch (final Exception ex) {
        logger.warn("Error in EventStore health check, marking as down", ex);
        return Health.down(ex).build();
    }
}