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

The following examples show how to use org.springframework.boot.actuate.health.Health.Builder. 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: ConfigServerHealthIndicator.java    From spring-cloud-config with Apache License 2.0 6 votes vote down vote up
@Override
protected void doHealthCheck(Builder builder) throws Exception {
	PropertySource<?> propertySource = getPropertySource();
	builder.up();
	if (propertySource instanceof CompositePropertySource) {
		List<String> sources = new ArrayList<>();
		for (PropertySource<?> ps : ((CompositePropertySource) propertySource)
				.getPropertySources()) {
			sources.add(ps.getName());
		}
		builder.withDetail("propertySources", sources);
	}
	else if (propertySource != null) {
		builder.withDetail("propertySources", propertySource.toString());
	}
	else {
		builder.unknown().withDetail("error", "no property sources located");
	}
}
 
Example #2
Source File: RefreshScopeHealthIndicator.java    From spring-cloud-commons with Apache License 2.0 6 votes vote down vote up
@Override
protected void doHealthCheck(Builder builder) throws Exception {
	RefreshScope refreshScope = this.scope.getIfAvailable();
	if (refreshScope != null) {
		Map<String, Exception> errors = new HashMap<>(refreshScope.getErrors());
		errors.putAll(this.rebinder.getErrors());
		if (errors.isEmpty()) {
			builder.up();
		}
		else {
			builder.down();
			if (errors.size() == 1) {
				builder.withException(errors.values().iterator().next());
			}
			else {
				for (String name : errors.keySet()) {
					builder.withDetail(name, errors.get(name));
				}
			}
		}
	}
}
 
Example #3
Source File: NacosConfigEndpointTests.java    From spring-cloud-alibaba with Apache License 2.0 6 votes vote down vote up
private void checkoutAcmHealthIndicator() {
	try {
		Builder builder = new Builder();

		NacosConfigHealthIndicator healthIndicator = new NacosConfigHealthIndicator(
				properties.configServiceInstance());
		healthIndicator.doHealthCheck(builder);

		Builder builder1 = new Builder();
		builder1.up();

		assertThat(builder.build()).isEqualTo(builder1.build());
	}
	catch (Exception ignore) {

	}

}
 
Example #4
Source File: CassandraHealthIndicator.java    From micro-service with MIT License 6 votes vote down vote up
@Override
protected void doHealthCheck(Builder builder) throws Exception {
	
	Session session = null;
	
	try {
		session = cluster.connect();
		ResultSet rs = session.execute("SELECT dateof(now()) FROM system.local");
		Date date = rs.one().getTimestamp(0);
		logger.info("cassandra is working, the time is ", date);
		builder.up().withDetail("description", "cassandra is working, the time is " + date);
	} catch (Exception e) {
		logger.error("cassandra launch has error, {}", e.getMessage());
		builder.outOfService().withDetail("description", "cassandra launch has error, " + e.getMessage());
	} finally {
		if(null != session) {
			session.close();
		}
	}
}
 
Example #5
Source File: VaultReactiveHealthIndicator.java    From spring-cloud-vault with Apache License 2.0 5 votes vote down vote up
@Override
protected Mono<Health> doHealthCheck(Builder builder) {

	return this.vaultOperations
			.doWithSession((it) -> it.get().uri("sys/health")
					.header(VaultHttpHeaders.VAULT_NAMESPACE, "").exchange())
			.flatMap((it) -> it.bodyToMono(VaultHealthImpl.class))
			.onErrorResume(WebClientResponseException.class,
					VaultReactiveHealthIndicator::deserializeError)
			.map((vaultHealthResponse) -> getHealth(builder, vaultHealthResponse));
}
 
Example #6
Source File: JobExecutorHealthIndicator.java    From camunda-bpm-platform with Apache License 2.0 5 votes vote down vote up
@Override
protected void doHealthCheck(Builder builder) throws Exception {
  boolean active = jobExecutor.isActive();
  if (active) {
    builder = builder.up();
  } else {
    builder = builder.down();
  }
  builder.withDetail("jobExecutor", Details.from(jobExecutor));
}
 
Example #7
Source File: EurekaHealthIndicator.java    From spring-cloud-netflix with Apache License 2.0 5 votes vote down vote up
@Override
public Health health() {
	Builder builder = Health.unknown();
	Status status = getStatus(builder);
	return builder.status(status).withDetail("applications", getApplications())
			.build();
}
 
Example #8
Source File: RedisHealthIndicator.java    From micro-service with MIT License 5 votes vote down vote up
@Override
protected void doHealthCheck(Builder builder) throws Exception {
	
	try {
		jedisCluster.get("foo");
		logger.info("redis is working");
		builder.up().withDetail("description", "redis is working");
	} catch (Exception e) {
		logger.error("redis launch has error, {}", e.getMessage());
		builder.outOfService().withDetail("description", "redis launch has error, " + e.getMessage());
	}
}
 
Example #9
Source File: JobExecutorHealthIndicator.java    From camunda-bpm-spring-boot-starter with Apache License 2.0 5 votes vote down vote up
@Override
protected void doHealthCheck(Builder builder) throws Exception {
  boolean active = jobExecutor.isActive();
  if (active) {
    builder = builder.up();
  } else {
    builder = builder.down();
  }
  builder.withDetail("jobExecutor", Details.from(jobExecutor));
}
 
Example #10
Source File: ApplicationConfig.java    From sample-boot-hibernate with MIT License 5 votes vote down vote up
/** 営業日チェック */
@Bean
HealthIndicator dayIndicator(Timestamper time, BusinessDayHandler day) {
    return new AbstractHealthIndicator() {
        @Override
        protected void doHealthCheck(Builder builder) throws Exception {
            builder.up();
            builder.withDetail("day", day.day())
                    .withDetail("dayMinus1", day.day(-1))
                    .withDetail("dayPlus1", day.day(1))
                    .withDetail("dayPlus2", day.day(2))
                    .withDetail("dayPlus3", day.day(3));
        }
    };
}
 
Example #11
Source File: TwitterHealthIndicator.java    From lemonaid with MIT License 5 votes vote down vote up
@Override
protected void doHealthCheck(Builder builder) throws Exception {
	if (twitter.isAuthenticated()) {
		builder.withDetail("handle", twitter.getScreenName()).up();
	} else {
		builder.status("NotAuthenticated");
	}
}
 
Example #12
Source File: LocationHealthIndicator.java    From lemonaid with MIT License 5 votes vote down vote up
@Override
protected void doHealthCheck(Builder builder) throws Exception {
   	log.info("Test geolocation service health - start.");
	long startTime = System.currentTimeMillis();
	Mentor mentor = mentorRepository.findAll().iterator().next();
	Point point = mentorUtils.getLocationOfMentor(mentor);
	if (point.getLatitude() != 0) {
		builder.withDetail("handle", point.toString()).up();
	} else {
		builder.status("GeocodingError");
	}
	log.info("Test geolocation service health - end. Duration: " + Long.toString(System.currentTimeMillis() - startTime) + "ms");
}
 
Example #13
Source File: MicroAssetConfig.java    From sample-boot-micro with MIT License 5 votes vote down vote up
/** 営業日チェック */
@Bean
HealthIndicator dayIndicator(final Timestamper time, final BusinessDayHandler day) {
    return new AbstractHealthIndicator() {
        @Override
        protected void doHealthCheck(Builder builder) throws Exception {
            builder.up();
            builder.withDetail("day", day.day())
                    .withDetail("dayMinus1", day.day(-1))
                    .withDetail("dayPlus1", day.day(1))
                    .withDetail("dayPlus2", day.day(2))
                    .withDetail("dayPlus3", day.day(3));
        }
    };
}
 
Example #14
Source File: MicroAppConfig.java    From sample-boot-micro with MIT License 5 votes vote down vote up
/** 営業日チェック */
@Bean
HealthIndicator dayIndicator(final Timestamper time, final BusinessDayHandler day) {
    return new AbstractHealthIndicator() {
        @Override
        protected void doHealthCheck(Builder builder) throws Exception {
            builder.up();
            builder.withDetail("day", day.day())
                    .withDetail("dayMinus1", day.day(-1))
                    .withDetail("dayPlus1", day.day(1))
                    .withDetail("dayPlus2", day.day(2))
                    .withDetail("dayPlus3", day.day(3));
        }
    };
}
 
Example #15
Source File: TimeoutsHealthIndicator.java    From super-cloudops with Apache License 2.0 5 votes vote down vote up
@Override
protected void doHealthCheck(Builder builder) throws Exception {
	try {
		// Get the statistical parameter (min/max/avg/latest) etc.
		TimesWrapper wrap = this.getLargestMessage();
		if (logger.isDebugEnabled()) {
			logger.debug("TimeoutsHealth message={}", objectMapper.writeValueAsString(wrap));
		}
		if (wrap == null) {
			HealthUtil.up(builder, "Healthy");
			return;
		} else if (wrap.getMax() < conf.getTimeoutsThreshold()) {
			HealthUtil.up(builder, "Healthy");
		} else {
			HealthUtil.down(builder, "Method " + wrap.getMetricsName() + " executes " + wrap.getLatest()
					+ "ms with a response exceeding the threshold value of `" + conf.getTimeoutsThreshold() + "`ms.");
			// When the timeout exception is detected, the exception record
			// is cleared.
			this.postPropertiesReset(wrap);
		}
		builder.withDetail("Method", wrap.getMetricsName()).withDetail("Least", wrap.getMin())
				.withDetail("Largest", wrap.getMax()).withDetail("Avg", wrap.getAvg()).withDetail("Latest", wrap.getLatest())
				.withDetail("Samples", wrap.getSamples()).withDetail("Threshold", conf.getTimeoutsThreshold() + "ms");

	} catch (Exception e) {
		builder.down(e);
		logger.error("Analysis timeouts message failed.", e);
	}

}
 
Example #16
Source File: VaultReactiveHealthIndicator.java    From spring-cloud-vault with Apache License 2.0 4 votes vote down vote up
private static Health getHealth(Builder builder,
		VaultHealthImpl vaultHealthResponse) {

	HealthBuilderDelegate.contributeToHealth(vaultHealthResponse, builder);
	return builder.build();
}
 
Example #17
Source File: AbstractAdvancedHealthIndicator.java    From super-cloudops with Apache License 2.0 4 votes vote down vote up
@Override
protected void doHealthCheck(Builder builder) throws Exception {
	int index = 0;
	StringBuffer desc = new StringBuffer();
	for (String name : this.eventStores.keySet()) {
		try {
			EventStore<Partition> store = this.eventStores.get(name);
			Partition latestPart = store.latest();
			if (logger.isDebugEnabled())
				logger.debug("Health performance:{}", mapper.writeValueAsString(latestPart));

			if (latestPart == null) {
				builder.up();
				return;
			}

			// Get partition configuration by current partition.
			Partition confPart = this.conf.getPartitions().get(name);
			if (confPart == null)
				throw new Error("It should not come here. " + name);

			// Check threshold.
			long threshold = confPart.getValue();
			long curVal = latestPart.getValue();
			if (this.compare(curVal, threshold) < 0) { // Trigger event.
				if (desc.length() > 0) {
					desc.append("<br/>");
				}
				desc.append(name).append(":").append(formatValue(curVal)).append(" exceed the threshold:")
						.append(formatValue(confPart.getValue()));
			}
			// Meaningful field name prefix.
			String p = this.compareFieldName();
			builder.withDetail("AcqPosition_" + index, name).withDetail("AcqSamples_" + index, latestPart.getSamples())
					.withDetail("AcqTime_" + index, latestPart.getFormatTimestamp())
					.withDetail(p + "Avg_" + index, formatValue(store.average()))
					.withDetail(p + "Lgt_" + index, formatValue(store.largest().getValue()))
					.withDetail(p + "Let_" + index, formatValue(store.least().getValue()))
					.withDetail(p + "Lat_" + index, formatValue(store.latest().getValue()))
					.withDetail(p + "Threshold_" + index, formatValue(threshold));
			// All the checks are normal.
			if (desc.length() > 0) {
				HealthUtil.down(builder, desc.toString());
				desc.setLength(0); // Reset.
			} else {
				builder.up();
			}
			if (logger.isDebugEnabled()) {
				logger.debug("Acquisition unhealthy description:{}", desc);
			}

		} catch (Exception e) {
			builder.down(e);
			logger.error("Advanced health check failed.", e);
		} finally {
			// Increase by 1
			++index;
		}
	}

}
 
Example #18
Source File: VaultHealthIndicator.java    From spring-cloud-vault with Apache License 2.0 4 votes vote down vote up
@Override
protected void doHealthCheck(Builder builder) {

	VaultHealth vaultHealthResponse = this.vaultOperations.opsForSys().health();
	HealthBuilderDelegate.contributeToHealth(vaultHealthResponse, builder);
}
 
Example #19
Source File: ExampleHealthIndicator.java    From building-microservices with Apache License 2.0 4 votes vote down vote up
@Override
protected void doHealthCheck(Builder builder) throws Exception {
	builder.status(this.up ? Status.UP : Status.DOWN);
}
 
Example #20
Source File: ProcessEngineHealthIndicator.java    From camunda-bpm-spring-boot-starter with Apache License 2.0 4 votes vote down vote up
@Override
protected void doHealthCheck(Builder builder) throws Exception {
  builder.up().withDetail("name", processEngine.getName());
}
 
Example #21
Source File: MyHealthIndicator.java    From spring-boot-inside with MIT License 4 votes vote down vote up
@Override
protected void doHealthCheck(Builder builder) throws Exception {
	builder.status(Status.UP);
	builder.withDetail("hello", "world");
}
 
Example #22
Source File: HealthUtil.java    From super-cloudops with Apache License 2.0 4 votes vote down vote up
public static Builder build(Builder builder, String statusCode, String desc) {
	return builder.status(new Status(statusCode, desc));
}
 
Example #23
Source File: HealthUtil.java    From super-cloudops with Apache License 2.0 4 votes vote down vote up
public static Builder down(Builder builder, String desc) {
	return build(builder, Status.DOWN.getCode(), desc);
}
 
Example #24
Source File: HealthUtil.java    From super-cloudops with Apache License 2.0 4 votes vote down vote up
public static Builder up(Builder builder, String desc) {
	return build(builder, Status.UP.getCode(), desc);
}
 
Example #25
Source File: ProcessEngineHealthIndicator.java    From camunda-bpm-platform with Apache License 2.0 4 votes vote down vote up
@Override
protected void doHealthCheck(Builder builder) throws Exception {
  builder.up().withDetail("name", processEngine.getName());
}