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

The following examples show how to use org.springframework.boot.actuate.health.HealthIndicator. 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: 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 #2
Source File: JedisConfig.java    From kayenta with Apache License 2.0 6 votes vote down vote up
@Bean
HealthIndicator redisHealth(JedisPool jedisPool) {
  return () -> {
    Jedis jedis = null;
    Health.Builder health = null;

    try {
      jedis = jedisPool.getResource();

      if ("PONG".equals(jedis.ping())) {
        health = Health.up();
      } else {
        health = Health.down();
      }
    } catch (Exception ex) {
      health = Health.down(ex);
    } finally {
      if (jedis != null) {
        jedis.close();
      }
    }

    return health.build();
  };
}
 
Example #3
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 #4
Source File: DiscoveryCompositeHealthContributor.java    From spring-cloud-commons with Apache License 2.0 6 votes vote down vote up
private NamedContributor<HealthContributor> asNamedContributor(
		DiscoveryHealthIndicator indicator) {
	return new NamedContributor<HealthContributor>() {

		@Override
		public String getName() {
			return indicator.getName();
		}

		@Override
		public HealthIndicator getContributor() {
			return asHealthIndicator(indicator);
		}

	};
}
 
Example #5
Source File: EurekaHealthCheckHandler.java    From spring-cloud-netflix with Apache License 2.0 6 votes vote down vote up
void populateHealthIndicators(Map<String, HealthIndicator> healthIndicators) {
	for (Map.Entry<String, HealthIndicator> entry : healthIndicators.entrySet()) {
		// ignore EurekaHealthIndicator and flatten the rest of the composite
		// otherwise there is a never ending cycle of down. See gh-643
		if (entry.getValue() instanceof DiscoveryCompositeHealthContributor) {
			DiscoveryCompositeHealthContributor indicator = (DiscoveryCompositeHealthContributor) entry
					.getValue();
			indicator.forEach(contributor -> {
				if (!(contributor
						.getContributor() instanceof EurekaHealthIndicator)) {
					this.healthIndicators.put(contributor.getName(),
							(HealthIndicator) contributor.getContributor());
				}
			});
		}
		else {
			this.healthIndicators.put(entry.getKey(), entry.getValue());
		}
	}
}
 
Example #6
Source File: HealthAutoConfiguration.java    From sdmq with Apache License 2.0 6 votes vote down vote up
@Bean
@Autowired(required = false)
@ConditionalOnMissingBean
public HealthIndicator jikexiuHealthIndicator(RedisQueueImpl redisQueue,
                                              RedisQueueProperties properties) {
    CompositeHealthIndicator compositeHealthIndicator = new
            CompositeHealthIndicator(healthAggregator);
    Map<String, LeaderManager> leaderManagerMap = AppEnvContext.getCtx().getBeansOfType(LeaderManager.class);
    LeaderManager              manager          = null;
    if (leaderManagerMap != null && !leaderManagerMap.isEmpty()) {
        manager = AppEnvContext.getCtx().getBean(SimpleLeaderManager.class);
    }

    compositeHealthIndicator.addHealthIndicator("dq", new QueueHealthIndicator(
            redisQueue, manager, properties));
    return compositeHealthIndicator;
}
 
Example #7
Source File: HealthMetricsConfiguration.java    From summerframework with Apache License 2.0 6 votes vote down vote up
private static int getStatusCode(HealthIndicator healthIndicator) {
    if (!running) {
        return 0;
    }
    switch (healthIndicator.health().getStatus().getCode()) {
        case "UP":
            return 3;
        case "OUT_OF_SERVICE":
            return 2;
        case "DOWN":
            return 1;
        case "UNKNOWN":
        default:
            return 0;
    }
}
 
Example #8
Source File: JedisClientConfiguration.java    From kork with Apache License 2.0 5 votes vote down vote up
@Bean
@ConditionalOnProperty(
    value = "redis.cluster-enabled",
    havingValue = "false",
    matchIfMissing = true)
public List<HealthIndicator> jedisClientHealthIndicators(
    List<RedisClientDelegate> redisClientDelegates) {
  return redisClientDelegates.stream()
      .filter(it -> it instanceof JedisClientDelegate)
      .map(it -> JedisHealthIndicatorFactory.build((JedisClientDelegate) it))
      .collect(Collectors.toList());
}
 
Example #9
Source File: JedisHealthIndicatorFactory.java    From kork with Apache License 2.0 5 votes vote down vote up
public static HealthIndicator build(JedisClientDelegate client) {
  try {
    final JedisClientDelegate src = client;
    final Field clientAccess = JedisClientDelegate.class.getDeclaredField("jedisPool");
    clientAccess.setAccessible(true);

    return build((Pool<Jedis>) clientAccess.get(src));
  } catch (IllegalAccessException | NoSuchFieldException e) {
    throw new BeanCreationException("Error creating Redis health indicator", e);
  }
}
 
Example #10
Source File: JedisHealthIndicatorFactory.java    From kork with Apache License 2.0 5 votes vote down vote up
public static HealthIndicator build(Pool<Jedis> jedisPool) {
  try {
    final Pool<Jedis> src = jedisPool;
    final Field poolAccess = Pool.class.getDeclaredField("internalPool");
    poolAccess.setAccessible(true);
    GenericObjectPool<Jedis> internal = (GenericObjectPool<Jedis>) poolAccess.get(jedisPool);
    return () -> {
      Jedis jedis = null;
      Health.Builder health;
      try {
        jedis = src.getResource();
        if ("PONG".equals(jedis.ping())) {
          health = Health.up();
        } else {
          health = Health.down();
        }
      } catch (Exception ex) {
        health = Health.down(ex);
      } finally {
        if (jedis != null) jedis.close();
      }
      health.withDetail("maxIdle", internal.getMaxIdle());
      health.withDetail("minIdle", internal.getMinIdle());
      health.withDetail("numActive", internal.getNumActive());
      health.withDetail("numIdle", internal.getNumIdle());
      health.withDetail("numWaiters", internal.getNumWaiters());

      return health.build();
    };
  } catch (IllegalAccessException | NoSuchFieldException e) {
    throw new BeanCreationException("Error creating Redis health indicator", e);
  }
}
 
Example #11
Source File: EurekaHealthCheckHandlerTests.java    From spring-cloud-netflix with Apache License 2.0 5 votes vote down vote up
@Bean
public HealthIndicator healthIndicator() {
	return new AbstractHealthIndicator() {
		@Override
		protected void doHealthCheck(Health.Builder builder) throws Exception {
			builder.up();
		}
	};
}
 
Example #12
Source File: BootHealthCheckHandler.java    From kork with Apache License 2.0 5 votes vote down vote up
public BootHealthCheckHandler(
    ApplicationInfoManager applicationInfoManager,
    HealthAggregator aggregator,
    Map<String, HealthIndicator> healthIndicators) {
  this.applicationInfoManager =
      Objects.requireNonNull(applicationInfoManager, "applicationInfoManager");
  this.aggregateHealth = new CompositeHealthIndicator(aggregator, healthIndicators);
}
 
Example #13
Source File: EurekaHealthCheckHandler.java    From spring-cloud-netflix with Apache License 2.0 5 votes vote down vote up
@Override
public void afterPropertiesSet() throws Exception {
	final Map<String, HealthIndicator> healthIndicators = applicationContext
			.getBeansOfType(HealthIndicator.class);

	populateHealthIndicators(healthIndicators);
}
 
Example #14
Source File: HealthAutoConfiguration.java    From mykit-delay with Apache License 2.0 5 votes vote down vote up
@Bean
@Autowired(required = false)
@ConditionalOnMissingBean
public HealthIndicator jikexiuHealthIndicator(RedisQueue redisQueue, RedisQueueProperties properties) {
    CompositeHealthIndicator compositeHealthIndicator = new  CompositeHealthIndicator(healthAggregator);
    Map<String, LeaderManager> leaderManagerMap = AppEnvContext.getCtx().getBeansOfType(LeaderManager.class);
    LeaderManager manager = null;
    if (leaderManagerMap != null && !leaderManagerMap.isEmpty()) {
        manager = AppEnvContext.getCtx().getBean(SimpleLeaderManager.class);
    }

    compositeHealthIndicator.addHealthIndicator(Constants.HEALTH_INDICATOR_NAME, new QueueHealthIndicator(redisQueue, manager, properties));
    return compositeHealthIndicator;
}
 
Example #15
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 #16
Source File: EurekaComponents.java    From kork with Apache License 2.0 5 votes vote down vote up
@Bean
HealthCheckHandler healthCheckHandler(
    ApplicationInfoManager applicationInfoManager,
    HealthAggregator healthAggregator,
    Map<String, HealthIndicator> healthIndicators) {
  return new BootHealthCheckHandler(applicationInfoManager, healthAggregator, healthIndicators);
}
 
Example #17
Source File: NacosDiscoveryEndpointAutoConfiguration.java    From spring-cloud-alibaba with Apache License 2.0 5 votes vote down vote up
@Bean
@ConditionalOnEnabledHealthIndicator("nacos-discovery")
public HealthIndicator nacosDiscoveryHealthIndicator(
		NacosDiscoveryProperties nacosDiscoveryProperties) {
	return new NacosDiscoveryHealthIndicator(
			nacosDiscoveryProperties.namingServiceInstance());
}
 
Example #18
Source File: DiscoveryCompositeHealthContributorTests.java    From spring-cloud-commons with Apache License 2.0 5 votes vote down vote up
@Test
public void getContributorWhenMissingReturnsNull() throws Exception {
	TestDiscoveryHealthIndicator indicator = new TestDiscoveryHealthIndicator("test",
			Health.up().build());
	DiscoveryCompositeHealthContributor composite = new DiscoveryCompositeHealthContributor(
			Arrays.asList(indicator));
	assertThat((HealthIndicator) composite.getContributor("missing")).isNull();
}
 
Example #19
Source File: SidecarHealthChecker.java    From spring-cloud-alibaba with Apache License 2.0 5 votes vote down vote up
public SidecarHealthChecker(SidecarDiscoveryClient sidecarDiscoveryClient,
		HealthIndicator healthIndicator, SidecarProperties sidecarProperties,
		ConfigurableEnvironment environment) {
	this.sidecarDiscoveryClient = sidecarDiscoveryClient;
	this.healthIndicator = healthIndicator;
	this.sidecarProperties = sidecarProperties;
	this.environment = environment;
}
 
Example #20
Source File: EurekaHealthCheckHandlerTests.java    From spring-cloud-netflix with Apache License 2.0 5 votes vote down vote up
@Bean
public HealthIndicator healthIndicator() {
	return new AbstractHealthIndicator() {
		@Override
		protected void doHealthCheck(Health.Builder builder) throws Exception {
			builder.down();
		}
	};
}
 
Example #21
Source File: AdvancedCpuHealthIndicator.java    From super-cloudops with Apache License 2.0 5 votes vote down vote up
@Bean(BEAN_NAME)
public HealthIndicator coreHealthIndicator(HealthAggregator healthAggregator, CpuHealthProperties conf) {
	if (logger.isInfoEnabled())
		logger.info("Initial CoreHealthIndicator. {}", conf);

	AdvancedCpuHealthIndicator healthIndicator = new AdvancedCpuHealthIndicator(conf);
	Map<String, Health> healths = new LinkedHashMap<String, Health>();
	healths.put(AdvancedCpuHealthIndicator.class.getSimpleName(), healthIndicator.health());
	return healthIndicator;
}
 
Example #22
Source File: AdvancedMemoryHealthIndicator.java    From super-cloudops with Apache License 2.0 5 votes vote down vote up
@Bean(BEAN_NAME)
public HealthIndicator memoryHealthIndicator(HealthAggregator healthAggregator, MemoryHealthProperties conf) {
	if (logger.isInfoEnabled())
		logger.info("Initial memoryHealthIndicator. {}", conf);

	AdvancedMemoryHealthIndicator healthIndicator = new AdvancedMemoryHealthIndicator(conf);
	Map<String, Health> healths = new LinkedHashMap<String, Health>();
	healths.put(AdvancedMemoryHealthIndicator.class.getSimpleName(), healthIndicator.health());
	return healthIndicator;
}
 
Example #23
Source File: TimeoutsHealthIndicator.java    From super-cloudops with Apache License 2.0 5 votes vote down vote up
@Bean
public HealthIndicator timeoutsHealthIndicator(HealthAggregator healthAggregator, TimerMetricsProperties conf) {
	if (conf.getSamples() == 0)
		throw new IllegalArgumentException("Latest measure count is 0.");
	if (logger.isInfoEnabled())
		logger.info("Initial timeoutsHealthIndicator. {}", conf);

	TimeoutsHealthIndicator healthIndicator = new TimeoutsHealthIndicator(conf);
	Map<String, Health> healths = new LinkedHashMap<String, Health>();
	healths.put(TimeoutsHealthIndicator.class.getSimpleName(), healthIndicator.health());
	return healthIndicator;
}
 
Example #24
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 #25
Source File: DbCountAutoConfiguration.java    From Spring-Boot-2.0-Cookbook-Second-Edition with MIT License 5 votes vote down vote up
@Bean
public HealthIndicator dbCountHealthIndicator(Collection<CrudRepository> repositories) {
    CompositeHealthIndicator compositeHealthIndicator = new CompositeHealthIndicator(healthAggregator);
    for (CrudRepository repository : repositories) {
        String name = DbCountRunner.getRepositoryName(repository.getClass());
        compositeHealthIndicator.addHealthIndicator(name, new DbCountHealthIndicator(repository));
    }
    return compositeHealthIndicator;
}
 
Example #26
Source File: DbCountAutoConfiguration.java    From Spring-Boot-2.0-Cookbook-Second-Edition with MIT License 5 votes vote down vote up
@Bean
public HealthIndicator dbCountHealthIndicator(Collection<CrudRepository> repositories) {
    CompositeHealthIndicator compositeHealthIndicator = new CompositeHealthIndicator(healthAggregator);
    for (CrudRepository repository : repositories) {
        String name = DbCountRunner.getRepositoryName(repository.getClass());
        compositeHealthIndicator.addHealthIndicator(name, new DbCountHealthIndicator(repository));
    }
    return compositeHealthIndicator;
}
 
Example #27
Source File: DbCountAutoConfiguration.java    From Spring-Boot-2.0-Cookbook-Second-Edition with MIT License 5 votes vote down vote up
@Bean
public HealthIndicator dbCountHealthIndicator(Collection<CrudRepository> repositories) {
    CompositeHealthIndicator compositeHealthIndicator = new CompositeHealthIndicator(healthAggregator);
    for (CrudRepository repository : repositories) {
        String name = DbCountRunner.getRepositoryName(repository.getClass());
        compositeHealthIndicator.addHealthIndicator(name, new DbCountHealthIndicator(repository));
    }
    return compositeHealthIndicator;
}
 
Example #28
Source File: EurekaHealthCheckHandlerTests.java    From spring-cloud-netflix with Apache License 2.0 5 votes vote down vote up
@Bean
public HealthIndicator healthIndicator() {
	return new AbstractHealthIndicator() {
		@Override
		protected void doHealthCheck(Health.Builder builder) throws Exception {
			builder.status("fatal");
		}
	};
}
 
Example #29
Source File: DiscoveryCompositeHealthContributorTests.java    From spring-cloud-commons with Apache License 2.0 5 votes vote down vote up
@Test
public void getContributorReturnsContributor() throws Exception {
	TestDiscoveryHealthIndicator indicator = new TestDiscoveryHealthIndicator("test",
			Health.up().build());
	DiscoveryCompositeHealthContributor composite = new DiscoveryCompositeHealthContributor(
			Arrays.asList(indicator));
	HealthIndicator adapted = (HealthIndicator) composite.getContributor("test");
	assertThat(adapted).isNotNull();
	assertThat(adapted.health()).isSameAs(indicator.health());
}
 
Example #30
Source File: HealthMetricsConfiguration.java    From summerframework with Apache License 2.0 5 votes vote down vote up
public HealthMetricsConfiguration(HealthAggregator healthAggregator, List<HealthIndicator> healthIndicators,
    MeterRegistry registry, PlatformTag platformTag) {
    healthIndicator = new CompositeHealthIndicator(healthAggregator);
    healthIndicators.forEach(h -> {
        registry.gauge("health." + h.getClass().getSimpleName().replace("HealthIndicator", "").toLowerCase(),
            platformTag.getTags(), h, HealthMetricsConfiguration::getStatusCode);
        healthIndicator.addHealthIndicator(h.toString(), h);
    });
    registry.gauge("health", platformTag.getTags(), healthIndicator, HealthMetricsConfiguration::getStatusCode);
}