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

The following examples show how to use org.springframework.boot.actuate.health.Health. These examples are extracted from open source projects. 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
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 2
@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
@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 4
Source Project: influxdb-client-java   Source File: InfluxDB2HealthIndicator.java    License: 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 5
@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 6
@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 7
@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 Project: sdmq   Source File: QueueHealthIndicator.java    License: 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 9
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 10
Source Project: spring-cloud-vault   Source File: HealthBuilderDelegate.java    License: 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
@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 12
@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 13
@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 14
/**
 * 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 15
@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 16
@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 17
@Override
protected void doHealthCheck(Health.Builder builder) {
    if (jetInstance.getHazelcastInstance().getLifecycleService().isRunning()) {
        builder.up();
    } else {
        builder.down();
    }
    builder.withDetail("name", jetInstance.getName()).withDetail("uuid",
            jetInstance.getHazelcastInstance().getLocalEndpoint().getUuid().toString());
}
 
Example 18
@Test
public void whenAutoConfigured_thenHazelcastJetUp() {
    this.contextRunner.run((context) -> {
        assertThat(context).hasSingleBean(JetInstance.class).hasSingleBean(HazelcastJetHealthIndicator.class);
        JetInstance jet = context.getBean(JetInstance.class);
        Health health = context.getBean(HazelcastJetHealthIndicator.class).health();
        assertThat(health.getStatus()).isEqualTo(Status.UP);
        assertThat(health.getDetails())
                .containsOnlyKeys("name", "uuid")
                .containsEntry("name", jet.getName())
                .containsEntry("uuid", jet.getHazelcastInstance().getLocalEndpoint().getUuid().toString());
    });
}
 
Example 19
@Override
protected void doHealthCheck(Health.Builder builder) {

	if (getGemFireCache().isPresent()) {

		Set<Region<?, ?>> rootRegions = getGemFireCache()
			.map(GemFireCache::rootRegions)
			.orElseGet(Collections::emptySet);

		builder.withDetail("geode.cache.regions", rootRegions.stream()
			.filter(Objects::nonNull)
			.map(Region::getFullPath)
			.sorted()
			.collect(Collectors.toList()));

		builder.withDetail("geode.cache.regions.count", rootRegions.stream().filter(Objects::nonNull).count());

		rootRegions.stream()
			.filter(Objects::nonNull)
			.forEach(region -> getGemfireRegionHealthIndicatorConsumers().accept(region, builder));

		builder.up();

		return;
	}

	builder.unknown();
}
 
Example 20
@Test
public void kafkaBinderIsUp() {
	final List<PartitionInfo> partitions = partitions(new Node(0, null, 0));
	topicsInUse.put(TEST_TOPIC, new KafkaMessageChannelBinder.TopicInformation(
			"group1-healthIndicator", partitions, false));
	org.mockito.BDDMockito.given(consumer.partitionsFor(TEST_TOPIC))
			.willReturn(partitions);
	Health health = indicator.health();
	assertThat(health.getStatus()).isEqualTo(Status.UP);
}
 
Example 21
@Override
public Health health() {
	int errorCode = appHealthCheck();
       if (errorCode != UP) {
           return Health.down().withDetail("Error Code", errorCode).build();
       }
       return Health.up().build();
}
 
Example 22
@Override
public Mono<Integer> check(String serviceName) {
    return Flux.fromIterable(healthIndicators)
            .flatMap(healthIndicator -> healthIndicator
                    .health().map(Health::getStatus))
            .all(status -> status == Status.UP)
            .map(result -> result ? SERVING_STATUS : DOWN_STATUS);
}
 
Example 23
Source Project: hedera-mirror-node   Source File: GrpcHealthIndicator.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public Health health() {
    HealthGrpc.HealthImplBase healthService = (HealthGrpc.HealthImplBase) healthStatusManager
            .getHealthService();
    HealthCheckRequest healthcheckRequest = HealthCheckRequest.newBuilder().setService(serviceName).build();
    HealthStreamObserver healthStreamObserver = new HealthStreamObserver();
    healthService.check(healthcheckRequest, healthStreamObserver);
    return healthStreamObserver.getHealth();
}
 
Example 24
@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 25
Source Project: pro-spring-boot   Source File: QuotaHealthIndicator.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public Health health() {
	long size = repo.count();
	if(size <= QUOTA_MAX_SIZE)
		return Health.up().withDetail("quota.entries", size).build();
	else
		return Health.down().withDetail("quota.entries", size).withException(new QuotaException("Quota Exceeded. Max allow: " + QUOTA_MAX_SIZE + ". See your Administrator for Quota policies.")).build();
}
 
Example 26
@Test
public void shouldReportStandbyService() {

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

	Health health = this.healthIndicator.health();

	assertThat(health.getStatus()).isEqualTo(Status.UP);
	assertThat(health.getDetails()).containsEntry("state", "Vault in standby");
}
 
Example 27
Source Project: jeecg-cloud   Source File: MailHealthIndicator.java    License: Apache License 2.0 5 votes vote down vote up
@Override public Health health() {
    int errorCode = check();
    if (errorCode != 0) {
        return Health.down().withDetail("Error Code", errorCode) .build();
    }
    return Health.up().build();
}
 
Example 28
Source Project: mojito   Source File: HealthRotation.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public Health health() {
    Health.Builder builder;

    if (inRotation) {
        builder = Health.up();
    } else {
        builder = Health.down();
    }
    return builder.withDetail("host", host).build();
}
 
Example 29
@Override
public Health health() {
    try {
        long count = repository.count();
        if (count >= 0) {
            return Health.up().withDetail("count", count).build();
        } else {
            return Health.unknown().withDetail("count", count).build();
        }
    } catch (Exception e) {
        return Health.down(e).build();
    }
}
 
Example 30
Source Project: kayenta   Source File: AtlasStorageUpdaterService.java    License: Apache License 2.0 5 votes vote down vote up
@Override
protected synchronized void doHealthCheck(Health.Builder builder) throws Exception {
  if (checksCompleted == atlasStorageUpdaters.size()) {
    builder.up();
  } else {
    builder.down();
  }
  builder.withDetail("checksCompleted", checksCompleted);
  builder.withDetail("checksExpected", atlasStorageUpdaters.size());
}