com.codahale.metrics.health.HealthCheck Java Examples

The following examples show how to use com.codahale.metrics.health.HealthCheck. 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: HealthCheckMetrics.java    From watcher with Apache License 2.0 6 votes vote down vote up
@Override
public Object watch(Map<String, Object> params) {
	Object key = checkNotNull(params).get(Constants.KEY);
	if (key == null) {
		SortedMap<String, HealthCheck.Result> healthChecks = healthCheckRegistry.runHealthChecks();
		boolean isAllOk = true;
		for (HealthCheck.Result singleResult : healthChecks.values()) {
			if (!singleResult.isHealthy()) {
				isAllOk = false;
				break;
			}
		}
		Map<String, Object> result = Maps.newHashMap();
		result.put("healthy", isAllOk);
		result.put("healthChecks", healthChecks);
		return result;
	} else {
		if (!healthCheckRegistry.getNames().contains(key.toString())) {
			return Collections.emptyMap();
		}
		return healthCheckRegistry.runHealthCheck(key.toString());
	}
}
 
Example #2
Source File: JobManager.java    From jobson with Apache License 2.0 6 votes vote down vote up
public Map<String, HealthCheck> getHealthChecks() {
    return Collections.singletonMap(
            JOB_MANAGER_JOB_QUEUE_OVERFLOW_HEALTHCHECK,
            new HealthCheck() {
                @Override
                protected Result check() throws Exception {
                    final int queueSize = jobQueue.size();
                    if (queueSize < JOB_MANAGER_MAX_JOB_QUEUE_OVERFLOW_THRESHOLD) {
                        return Result.healthy(format("Queue contains %s entries", queueSize));
                    } else {
                        return Result.unhealthy(format(
                                "%s entries in job queue: this exceeds the warning threshold (%s)",
                                queueSize,
                                JOB_MANAGER_MAX_JOB_QUEUE_OVERFLOW_THRESHOLD));
                    }
                }
            });
}
 
Example #3
Source File: JobManagerTest.java    From jobson with Apache License 2.0 6 votes vote down vote up
@Test
public void testGetHealthChecksReturnsAHealthCheckForJobQueueOverflowing() {
    final CancelablePromise<JobExecutionResult> executorPromise = new SimpleCancelablePromise<>();
    final JobManager jobManager = createManagerWith(MockJobExecutor.thatUses(executorPromise));
    final Map<String, HealthCheck> healthChecks = jobManager.getHealthChecks();

    assertThat(healthChecks).containsKeys(JOB_MANAGER_JOB_QUEUE_OVERFLOW_HEALTHCHECK);
    assertThat(healthChecks.get(JOB_MANAGER_JOB_QUEUE_OVERFLOW_HEALTHCHECK)).isNotNull();

    final HealthCheck jobQueueHealthCheck = healthChecks.get(JOB_MANAGER_JOB_QUEUE_OVERFLOW_HEALTHCHECK);

    assertThat(jobQueueHealthCheck.execute().isHealthy());

    for(int i = 0; i < JOB_MANAGER_MAX_JOB_QUEUE_OVERFLOW_THRESHOLD * 2; i++) {
        // These won't finish because we never resolve the promise
        jobManager.submit(STANDARD_VALID_REQUEST);
    }

    assertThat(jobQueueHealthCheck.execute().isHealthy()).isFalse();
}
 
Example #4
Source File: MyApp.java    From dropwizard-websockets with MIT License 6 votes vote down vote up
@Override
public void run(Configuration configuration, Environment environment) throws InvalidKeySpecException, NoSuchAlgorithmException, ServletException, DeploymentException {
    environment.lifecycle().addLifeCycleListener(new AbstractLifeCycle.AbstractLifeCycleListener() {

        @Override
        public void lifeCycleStarted(LifeCycle event) {
            cdl.countDown();
        }
    });
    environment.jersey().register(new MyResource());
    environment.healthChecks().register("alive", new HealthCheck() {
        @Override
        protected HealthCheck.Result check() throws Exception {
            return HealthCheck.Result.healthy();
        }
    });

    // Using ServerEndpointConfig lets you inject objects to the websocket endpoint:
    final ServerEndpointConfig config = ServerEndpointConfig.Builder.create(EchoServer.class, "/extends-ws").build();
    // config.getUserProperties().put(Environment.class.getName(), environment);
    // Then you can get it from the Session object
    // - obj = session.getUserProperties().get("objectName");            
    websocketBundle.addEndpoint(config);
}
 
Example #5
Source File: MacroBaseServer.java    From macrobase with Apache License 2.0 6 votes vote down vote up
@Override
public void run(MacroBaseConf configuration,
                Environment environment) throws Exception {
    configuration.loadSystemProperties();
    environment.jersey().register(new AnalyzeResource(configuration));
    environment.jersey().register(new SchemaResource(configuration));
    environment.jersey().register(new RowSetResource(configuration));
    environment.jersey().register(new FormattedRowSetResource(configuration));
    environment.jersey().register(new MultipleRowSetResource(configuration));

    environment.healthChecks().register("basic", new HealthCheck() {
        @Override
        protected Result check() throws Exception {
            return null;
        }
    });

    environment.jersey().setUrlPattern("/api/*");
}
 
Example #6
Source File: HealthChecksServer.java    From StubbornJava with MIT License 6 votes vote down vote up
public static void main(String[] args) {
    /*
     *  Init connection pools. They auto register their own health checks.
     */
    ConnectionPools.getProcessing();
    ConnectionPools.getTransactional();

    // Assume some global HttpClient.
    OkHttpClient client = new OkHttpClient.Builder().build();

    HttpUrl passingPath = HttpUrl.parse("http://localhost:8080/ping");
    HealthCheck passing = new ExternalServiceHealthCheck(client, passingPath);
    HealthChecks.getHealthCheckRegistry().register("ping", passing);

    // Since this route doesn't exist it will respond with 404 and should fail the check.
    HttpUrl failingPath = HttpUrl.parse("http://localhost:8080/failingPath");
    HealthCheck failing = new ExternalServiceHealthCheck(client, failingPath);
    HealthChecks.getHealthCheckRegistry().register("shouldFail", failing);

    // Once again pull in a bunch of common middleware.
    SimpleServer server = SimpleServer.simpleServer(Middleware.common(ROUTES));
    server.start();
}
 
Example #7
Source File: DropwizardModule.java    From dropwizard-guicier with Apache License 2.0 6 votes vote down vote up
@Override
public void configure(final Binder binder) {
  binder.bindListener(Matchers.any(), new ProvisionListener() {
    @Override
    public <T> void onProvision(ProvisionInvocation<T> provision) {
      Object obj = provision.provision();

      if (obj instanceof Managed) {
        handle((Managed) obj);
      }

      if (obj instanceof Task) {
        handle((Task) obj);
      }

      if (obj instanceof HealthCheck) {
        handle((HealthCheck) obj);
      }

      if (obj instanceof ServerLifecycleListener) {
        handle((ServerLifecycleListener) obj);
      }
    }
  });
}
 
Example #8
Source File: CodahaleHealthCheck.java    From attic-polygene-java with Apache License 2.0 6 votes vote down vote up
static HealthCheck.Result unwrap( Result result )
{
    String message = result.getMessage();
    if( result.isHealthy() )
    {
        if( message != null )
        {
            return HealthCheck.Result.healthy( message );
        }
        return HealthCheck.Result.healthy();
    }
    Throwable error = result.getException();
    if( error != null )
    {
        return HealthCheck.Result.unhealthy( error );
    }
    return HealthCheck.Result.unhealthy( message );
}
 
Example #9
Source File: CasDatabusTest.java    From emodb with Apache License 2.0 6 votes vote down vote up
@Test
public void testHealthCheck() throws Exception {
    ArgumentCaptor<HealthCheck> captor = ArgumentCaptor.forClass(HealthCheck.class);
    verify(_healthChecks, atLeastOnce()).addHealthCheck(Matchers.anyString(), captor.capture());
    List<HealthCheck> healthChecks = captor.getAllValues();

    int numCassandraHealthChecks = 0;
    for (HealthCheck healthCheck : healthChecks) {
        if (healthCheck instanceof CassandraHealthCheck) {
            HealthCheck.Result result = healthCheck.execute();
            assertTrue(result.isHealthy(), result.getMessage());
            numCassandraHealthChecks++;
        }
    }
    assertEquals(numCassandraHealthChecks, 3);  // app, ugc, databus
}
 
Example #10
Source File: CasDataStoreTest.java    From emodb with Apache License 2.0 6 votes vote down vote up
@Test
public void testHealthCheck() throws Exception {
    ArgumentCaptor<HealthCheck> captor = ArgumentCaptor.forClass(HealthCheck.class);
    verify(_healthChecks, atLeastOnce()).addHealthCheck(Matchers.anyString(), captor.capture());
    List<HealthCheck> healthChecks = captor.getAllValues();

    int numCassandraHealthChecks = 0;
    for (HealthCheck healthCheck : healthChecks) {
        if (healthCheck instanceof CassandraHealthCheck) {
            HealthCheck.Result result = healthCheck.execute();
            assertTrue(result.isHealthy(), result.getMessage());
            numCassandraHealthChecks++;
        }
    }
    assertEquals(numCassandraHealthChecks, 2);  // app, ugc
}
 
Example #11
Source File: HealthCheckHandler.java    From pippo with Apache License 2.0 6 votes vote down vote up
@Override
public void handle(RouteContext routeContext) {
    Response response = routeContext.getResponse().noCache().text();

    SortedMap<String, HealthCheck.Result> healthChecks = healthCheckRegistry.runHealthChecks();
    if (healthChecks.isEmpty()) {
        response.notImplemented().send("The health checks are empty");
    } else {
        boolean notHealthy = healthChecks.values().stream().anyMatch(hc -> !hc.isHealthy());
        if (notHealthy) {
            response.internalError().send("The health is bad");
        } else {
            response.ok().send("The health is good");
        }
    }
}
 
Example #12
Source File: CasBlobStoreTest.java    From emodb with Apache License 2.0 6 votes vote down vote up
@Test
public void testHealthCheck() throws Exception {
    ArgumentCaptor<HealthCheck> captor = ArgumentCaptor.forClass(HealthCheck.class);
    verify(_healthChecks, atLeastOnce()).addHealthCheck(Matchers.anyString(), captor.capture());
    List<HealthCheck> healthChecks = captor.getAllValues();

    int numCassandraHealthChecks = 0;
    for (HealthCheck healthCheck : healthChecks) {
        if (healthCheck instanceof CassandraHealthCheck) {
            HealthCheck.Result result = healthCheck.execute();
            assertTrue(result.isHealthy(), result.getMessage());
            numCassandraHealthChecks++;
        }
    }
    assertEquals(numCassandraHealthChecks, 3);  // app, ugc, media
}
 
Example #13
Source File: TenacityCircuitBreakerHealthCheckTest.java    From tenacity with Apache License 2.0 6 votes vote down vote up
@Test
public void multipleUnhealthyWhenThereIsAnOpenCircuitBreaker() {
    final ImmutableList<TenacityPropertyKey> keys = ImmutableList.<TenacityPropertyKey>of(
            DependencyKey.EXISTENT_HEALTHCHECK, DependencyKey.ANOTHER_EXISTENT_HEALTHCHECK);
    final HealthCheck healthCheck = new TenacityCircuitBreakerHealthCheck(keys);

    assertThat(CircuitBreakers.all(keys)).isEmpty();
    tryToOpenCircuitBreaker(DependencyKey.EXISTENT_HEALTHCHECK);
    tryToOpenCircuitBreaker(DependencyKey.ANOTHER_EXISTENT_HEALTHCHECK);
    assertThat(CircuitBreakers.all(keys))
            .contains(CircuitBreaker.open(DependencyKey.EXISTENT_HEALTHCHECK),
                    CircuitBreaker.open(DependencyKey.ANOTHER_EXISTENT_HEALTHCHECK));

    assertThat(healthCheck.execute())
            .isEqualToComparingOnlyGivenFields(HealthCheck.Result.unhealthy(""), "healthy");
}
 
Example #14
Source File: HealthCheckResourceTest.java    From pay-publicapi with MIT License 6 votes vote down vote up
@Test
public void checkHealthCheck_isUnHealthy() throws JsonProcessingException {
    SortedMap<String,HealthCheck.Result> map = new TreeMap<>();
    map.put("ping", HealthCheck.Result.unhealthy("application is unavailable"));
    map.put("deadlocks", HealthCheck.Result.unhealthy("no new threads available"));

    when(healthCheckRegistry.runHealthChecks()).thenReturn(map);

    Response response = resource.healthCheck();

    assertThat(response.getStatus(), is(503));

    ObjectWriter ow = new ObjectMapper().writer().withDefaultPrettyPrinter();
    String body = ow.writeValueAsString(response.getEntity());
    JsonAssert.with(body)
            .assertThat("$.*", hasSize(2))
            .assertThat("$.ping.healthy", is(false))
            .assertThat("$.deadlocks.healthy", is(false));
}
 
Example #15
Source File: ClusterManager.java    From foxtrot with Apache License 2.0 6 votes vote down vote up
@Inject
public ClusterManager(HazelcastConnection connection, List<HealthCheck> healthChecks, ServerFactory serverFactory) throws IOException {
    this.hazelcastConnection = connection;
    this.healthChecks = healthChecks;
    MapConfig mapConfig = new MapConfig(MAP_NAME);
    mapConfig.setTimeToLiveSeconds(MAP_REFRESH_TIME + 2); //Reduce jitter
    mapConfig.setBackupCount(1);
    mapConfig.setAsyncBackupCount(2);
    mapConfig.setEvictionPolicy(EvictionPolicy.NONE);
    hazelcastConnection.getHazelcastConfig()
            .getMapConfigs()
            .put(MAP_NAME, mapConfig);
    String hostname = Inet4Address.getLocalHost()
            .getCanonicalHostName();
    //Auto detect marathon environment and query for host environment variable
    if(!Strings.isNullOrEmpty(System.getenv("HOST")))
        hostname = System.getenv("HOST");
    Preconditions.checkNotNull(hostname, "Could not retrieve hostname, cannot proceed");
    int port = ServerUtils.port(serverFactory);
    //Auto detect marathon environment and query for host environment variable
    if(!Strings.isNullOrEmpty(System.getenv("PORT_" + port)))
        port = Integer.parseInt(System.getenv("PORT_" + port));
    executor = Executors.newScheduledThreadPool(1);
    clusterMember = new ClusterMember(hostname, port);
}
 
Example #16
Source File: ExampleApplication.java    From okta-auth-java with Apache License 2.0 6 votes vote down vote up
@Override
public void run(final ExampleConfiguration configuration, final Environment environment) {
    // example health check
    environment.healthChecks().register("example", new HealthCheck() {
        @Override
        protected HealthCheck.Result check() {
            // Everything is in memory, so we are always healthy ;)
            return Result.healthy();
        }
    });

    environment.servlets().addFilter("csrf", new OverlySimpleCsrfFilter())
            .addMappingForUrlPatterns(EnumSet.allOf(DispatcherType.class), false, "/*");

    configureShiro(environment);

    configureJersey(environment.jersey());
}
 
Example #17
Source File: HealthCheckScanner.java    From robe with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Override
public void scanAndAdd(Environment environment, Injector injector, Reflections reflections) {
    Set<Class<? extends HealthCheck>> healthCheckClasses = reflections.getSubTypesOf(HealthCheck.class);
    for (Class<? extends HealthCheck> healthCheck : healthCheckClasses) {
        environment.healthChecks().register(healthCheck.getName(), injector.getInstance(healthCheck));
        LOGGER.info("Added healthCheck: " + healthCheck.getName());
    }
}
 
Example #18
Source File: CodahaleHealthCheck.java    From attic-polygene-java with Apache License 2.0 5 votes vote down vote up
static Result wrap( HealthCheck.Result result )
{
    if( result.isHealthy() )
    {
        return Result.healthOk();
    }
    String message = result.getMessage();
    Throwable error = result.getError();
    if( error != null )
    {
        return Result.exception( message, error );
    }
    return Result.unhealthy( message );
}
 
Example #19
Source File: HealthCheckTest.java    From hammock with Apache License 2.0 5 votes vote down vote up
@Before
public void addHealthCheck() {
    HealthCheckRegistry registry = CDI.current().select(HealthCheckRegistry.class).get();
    registry.register("hammock", new HealthCheck() {
        @Override
        protected Result check() throws Exception {
            return Result.healthy("Hammock is online");
        }
    });
}
 
Example #20
Source File: DropwizardArmeriaApplicationTest.java    From armeria with Apache License 2.0 5 votes vote down vote up
@Test
void testPingHealthCheck() {
    final HealthCheck ping = new PingCheck();

    final Result res = ping.execute();

    assertThat(res.isHealthy()).isTrue();
    assertThat(res.getMessage()).isEqualTo("pong");
}
 
Example #21
Source File: LdapHealthCheckTest.java    From dropwizard-auth-ldap with Apache License 2.0 5 votes vote down vote up
@Test
public void healthy() throws Exception {
    LdapAuthenticator ldapAuthenticator = mock(LdapAuthenticator.class);
    when(ldapAuthenticator.authenticate(any(BasicCredentials.class))).thenReturn(true);
    LdapHealthCheck healthCheck = new LdapHealthCheck<>(new ResourceAuthenticator(ldapAuthenticator));
    assertThat(healthCheck.check(), is(HealthCheck.Result.healthy()));
}
 
Example #22
Source File: MorphlineTest.java    From kite with Apache License 2.0 5 votes vote down vote up
@Test
public void testMorphlineContext() throws Exception {
  ExceptionHandler ex = new ExceptionHandler() {      
    @Override
    public void handleException(Throwable t, Record record) {
      throw new RuntimeException(t);        
    }
  };
  
  MetricRegistry metricRegistry = new MetricRegistry();
  metricRegistry.register("myCounter", new Counter());
  
  HealthCheckRegistry healthChecks = new HealthCheckRegistry();
  healthChecks.register("foo", new HealthCheck() {      
    @Override
    protected Result check() throws Exception {
      return Result.healthy("flawless");
    }
  });

  Map<String,Object> settings = new HashMap<String,Object>(); 
  
  MorphlineContext ctx = new MorphlineContext.Builder()
    .setSettings(settings)
    .setExceptionHandler(ex)
    .setHealthCheckRegistry(healthChecks)
    .setMetricRegistry(metricRegistry)
    .build();
  
  assertSame(settings, ctx.getSettings());
  assertSame(ex, ctx.getExceptionHandler());
  assertSame(metricRegistry, ctx.getMetricRegistry());
  assertSame(healthChecks, ctx.getHealthCheckRegistry());
  ctx.getHealthCheckRegistry().runHealthChecks();
  
  assertEquals(0, new MorphlineContext.Builder().build().getSettings().size());
}
 
Example #23
Source File: ChassisConfiguration.java    From chassis with Apache License 2.0 5 votes vote down vote up
/**
 * Initializes the health check registry
 *
 * @return health check registry bean
 */
@Bean
public HealthCheckRegistry healthCheckRegistry(ApplicationContext context, DiscoveryManager eureka) {
    final HealthCheckRegistry bean = new HealthCheckRegistry();

    // auto-register beans implementing health checks
    Map<String, HealthCheck> healthChecks = context.getBeansOfType(HealthCheck.class);
    for (HealthCheck check : healthChecks.values()) {
        bean.register(check.getClass().getName(), check);
    }

    // connect health checks into Eureka
    if (!disableEureka) {
        eureka.getDiscoveryClient().registerHealthCheckCallback(
                new HealthCheckCallback() {
                    @Override
                    public boolean isHealthy() {
                        for (Entry<String, HealthCheck.Result> entry : bean.runHealthChecks().entrySet()) {
                            if (!entry.getValue().isHealthy()) {
                                return false;
                            }
                        }
                        return true;
                    }
                });
    }

    return bean;
}
 
Example #24
Source File: NettyClient.java    From jstorm with Apache License 2.0 5 votes vote down vote up
@Override
protected Result check() throws Exception {
    Double size = getValue();
    if (size > 8 * JStormUtils.SIZE_1_M) {
        return HealthCheck.Result.unhealthy(name + QueueGauge.QUEUE_IS_FULL);
    } else {
        return healthy;
    }
}
 
Example #25
Source File: HealthResource.java    From airpal with Apache License 2.0 5 votes vote down vote up
@GET
@CacheControl(mustRevalidate = true, noCache = true, noStore = true)
public Response health() {
    final SortedMap<String, HealthCheck.Result> results = registry.runHealthChecks();
    if (results.isEmpty()) {
        return Response.status(new NotImplementedStatus()).entity(results).build();
    } else {
        if (isAllHealthy(results)) {
            return Response.status(Response.Status.OK).entity(results).build();
        } else {
            return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(results).build();
        }
    }
}
 
Example #26
Source File: StatusResourceTest.java    From keywhiz with Apache License 2.0 5 votes vote down vote up
@Test
public void testStatusWarn() throws Exception {
  TreeMap<String, HealthCheck.Result> map = new TreeMap<>();
  map.put("test", HealthCheck.Result.unhealthy("failing"));

  when(registry.runHealthChecks()).thenReturn(map);
  Response r = status.get();
  assertThat(r.getStatus()).isEqualTo(500);
}
 
Example #27
Source File: FoxtrotModule.java    From foxtrot with Apache License 2.0 5 votes vote down vote up
@Override
protected void configure() {
    bind(TableMetadataManager.class)
            .to(DistributedTableMetadataManager.class);
    bind(DataStore.class)
            .to(HBaseDataStore.class);
    bind(QueryStore.class)
            .to(ElasticsearchQueryStore.class);
    bind(FqlStoreService.class)
            .to(FqlStoreServiceImpl.class);
    bind(CacheFactory.class)
            .to(DistributedCacheFactory.class);
    bind(InternalEventBus.class)
            .to(GuavaInternalEventBus.class);
    bind(InternalEventBusConsumer.class)
            .to(AlertingSystemEventConsumer.class);
    bind(ConsolePersistence.class)
            .to(ElasticsearchConsolePersistence.class);
    bind(EmailSubjectBuilder.class)
            .to(StrSubstitutorEmailSubjectBuilder.class);
    bind(EmailBodyBuilder.class)
            .to(StrSubstitutorEmailBodyBuilder.class);
    bind(TableManager.class)
            .to(FoxtrotTableManager.class);
    bind(new TypeLiteral<List<HealthCheck>>() {
    }).toProvider(HealthcheckListProvider.class);
}
 
Example #28
Source File: HealthCheckProducerMethodBean.java    From metrics-cdi with Apache License 2.0 5 votes vote down vote up
@Produces
@Named("not_registered_healthcheck")
HealthCheck anInjectedCheck(HealthCheckRegistry registry, InjectionPoint ip) {
    HealthCheck check3 = new HealthCheck() {
        @Override
        protected Result check() {
            return Result.healthy("check3");
        }
    };
    registry.register("check3", check3);
    return check3;
}
 
Example #29
Source File: Application.java    From xrpc with Apache License 2.0 5 votes vote down vote up
public static void configure(Server server) {
  // Add handlers for /people routes
  server.addRoutes(new PeopleRoutes());

  // Add a service specific health check
  server.addHealthCheck(
      "simple",
      new HealthCheck() {
        @Override
        protected Result check() {
          System.out.println("Health Check Ran");
          return Result.healthy();
        }
      });
}
 
Example #30
Source File: HealthCheckProducerMethodBean.java    From metrics-cdi with Apache License 2.0 5 votes vote down vote up
@Produces
@Named("check1")
HealthCheck aHealthyCheck() {
    return new HealthCheck() {
        @Override
        protected Result check() {
            return Result.healthy("check1");
        }
    };
}