org.eclipse.microprofile.health.HealthCheckResponse Java Examples

The following examples show how to use org.eclipse.microprofile.health.HealthCheckResponse. 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: DBHealthCheck.java    From boost with Eclipse Public License 1.0 7 votes vote down vote up
@Override
public HealthCheckResponse call() {

    HealthCheckResponseBuilder responseBuilder = HealthCheckResponse.named("membership");
    try {
        Connection connection = datasource.getConnection();
        boolean isValid = connection.isValid(5);

        DatabaseMetaData metaData = connection.getMetaData();

        responseBuilder = responseBuilder
                    .withData("databaseProductName", metaData.getDatabaseProductName())
                    .withData("databaseProductVersion", metaData.getDatabaseProductVersion())
                    .withData("driverName", metaData.getDriverName())
                    .withData("driverVersion", metaData.getDriverVersion())
                    .withData("isValid", isValid);

        return responseBuilder.state(isValid).build();


    } catch(SQLException  e) {
        responseBuilder = responseBuilder
               .withData("exceptionMessage", e.getMessage());
        return responseBuilder.down().build();
    }
}
 
Example #2
Source File: ParserTest.java    From thorntail with Apache License 2.0 6 votes vote down vote up
@Test
public void testHealthCheckResponseBuild() {

    HealthCheckResponse healthStatus = HealthCheckResponse.named("test")
            .up()
            .withData("a", "b")
            .withData("c", "d")
            .build();

    Assert.assertEquals("test", healthStatus.getName());
    Assert.assertSame(State.UP, healthStatus.getState());
    Map<String, Object> data = healthStatus.getData().get();
    Assert.assertEquals(2, data.size());
    Assert.assertEquals("Expected a", "b", data.get("a"));
    Assert.assertEquals("Expected c", "d", data.get("c"));
}
 
Example #3
Source File: DatabaseConnectionHealthCheck.java    From intellij-quarkus with Eclipse Public License 2.0 6 votes vote down vote up
@Override
public HealthCheckResponse call() {

    HealthCheckResponseBuilder responseBuilder = HealthCheckResponse.named("Database connection health check");

    try {
        simulateDatabaseConnectionVerification();
        responseBuilder.up();
    } catch (IllegalStateException e) {
        // cannot access the database
        responseBuilder.down()
            .withData("error", e.getMessage()); // pass the exception message
    }

    return responseBuilder.build();
}
 
Example #4
Source File: InfinispanHealthCheckIT.java    From kogito-runtimes with Apache License 2.0 6 votes vote down vote up
@Test
void testCall() throws Exception {
    InfinispanServerTestResource resource = new InfinispanServerTestResource();
    resource.start();

    this.healthCheck = new InfinispanHealthCheck(instance);

    //testing Up
    HealthCheckResponse response = healthCheck.call();
    Assertions.assertThat(response.getState()).isEqualTo(HealthCheckResponse.State.UP);

    resource.stop();

    //testing Down
    HealthCheckResponse response2 = healthCheck.call();
    Assertions.assertThat(response2.getState()).isEqualTo(HealthCheckResponse.State.DOWN);
}
 
Example #5
Source File: DatabaseConnectionHealthCheck.java    From quarkus-quickstarts with Apache License 2.0 6 votes vote down vote up
@Override
public HealthCheckResponse call() {

    HealthCheckResponseBuilder responseBuilder = HealthCheckResponse.named("Database connection health check");

    try {
        simulateDatabaseConnectionVerification();
        responseBuilder.up();
    } catch (IllegalStateException e) {
        // cannot access the database
        responseBuilder.down()
                .withData("error", e.getMessage()); // pass the exception message
    }

    return responseBuilder.build();
}
 
Example #6
Source File: DatabaseConnectionHealthCheck.java    From intellij-quarkus with Eclipse Public License 2.0 6 votes vote down vote up
@Override
public HealthCheckResponse call() {

    HealthCheckResponseBuilder responseBuilder = HealthCheckResponse.named("Database connection health check");

    try {
        simulateDatabaseConnectionVerification();
        responseBuilder.up();
    } catch (IllegalStateException e) {
        // cannot access the database
        responseBuilder.down()
            .withData("error", e.getMessage()); // pass the exception message
    }

    return responseBuilder.build();
}
 
Example #7
Source File: LivenessProbe.java    From trader with Apache License 2.0 6 votes vote down vote up
public HealthCheckResponse call() {
	HealthCheckResponse response = null;
	String message = "Live";
	try {
		HealthCheckResponseBuilder builder = HealthCheckResponse.named("Trader");

		if (Summary.error) { //can't run without these env vars
			builder = builder.down();
			message = Summary.message;
			logger.warning("Returning NOT live!");
		} else {
			builder = builder.up();
			logger.fine("Returning live!");
		}

		builder = builder.withData("message", message);

		response = builder.build(); 
	} catch (Throwable t) {
		logger.warning("Exception occurred during health check: "+t.getMessage());
		logException(t);
		throw t;
	}

	return response;
}
 
Example #8
Source File: FailingHealthCheck.java    From quarkus with Apache License 2.0 6 votes vote down vote up
@Override
public HealthCheckResponse call() {
    return new HealthCheckResponse() {
        @Override
        public String getName() {
            return "failing";
        }

        @Override
        public State getState() {
            return State.DOWN;
        }

        @Override
        public Optional<Map<String, Object>> getData() {
            return Optional.of(Collections.singletonMap("status", "all broken"));
        }
    };
}
 
Example #9
Source File: SimpleHealthCheck.java    From quarkus with Apache License 2.0 6 votes vote down vote up
@Override
public HealthCheckResponse call() {
    return new HealthCheckResponse() {
        @Override
        public String getName() {
            return "basic";
        }

        @Override
        public State getState() {
            return State.UP;
        }

        @Override
        public Optional<Map<String, Object>> getData() {
            return Optional.empty();
        }
    };
}
 
Example #10
Source File: KafkaStreamsTopicsHealthCheck.java    From quarkus with Apache License 2.0 6 votes vote down vote up
@Override
public HealthCheckResponse call() {
    HealthCheckResponseBuilder builder = HealthCheckResponse.named("Kafka Streams topics health check").up();

    try {
        Set<String> missingTopics = manager.getMissingTopics(trimmedTopics);
        List<String> availableTopics = new ArrayList<>(trimmedTopics);
        availableTopics.removeAll(missingTopics);

        if (!availableTopics.isEmpty()) {
            builder.withData("available_topics", String.join(",", availableTopics));
        }
        if (!missingTopics.isEmpty()) {
            builder.down().withData("missing_topics", String.join(",", missingTopics));
        }
    } catch (InterruptedException e) {
        LOGGER.error("error when retrieving missing topics", e);
        builder.down().withData("technical_error", e.getMessage());
    }

    return builder.build();
}
 
Example #11
Source File: BasicHealthCheck.java    From quarkus with Apache License 2.0 6 votes vote down vote up
@Override
public HealthCheckResponse call() {
    return new HealthCheckResponse() {
        @Override
        public String getName() {
            return "basic";
        }

        @Override
        public State getState() {
            return State.UP;
        }

        @Override
        public Optional<Map<String, Object>> getData() {
            return Optional.of(Collections.singletonMap("foo", "bar"));
        }
    };
}
 
Example #12
Source File: DatabaseLivenessCheck.java    From blog-tutorials with MIT License 6 votes vote down vote up
@Override
public HealthCheckResponse call() {

    try (var connection = dataSource.getConnection()) {
        var metaData = connection.getMetaData();

        return HealthCheckResponse.builder()
                .name(livenessCheckName)
                .withData("version", String.format("%s - %s.%s",
                        metaData.getDatabaseProductName(),
                        metaData.getDatabaseMajorVersion(),
                        metaData.getDatabaseMinorVersion()))
                .withData("schema", connection.getSchema())
                .withData("databaseName", connection.getCatalog())
                .up()
                .build();
    } catch (SQLException e) {
        return HealthCheckResponse.down(livenessCheckName);
    }
}
 
Example #13
Source File: UrlHealthCheckTest.java    From smallrye-health with Apache License 2.0 5 votes vote down vote up
@Test
public void testUrlCheck() {
    final UrlHealthCheck urlHealthCheck = new UrlHealthCheck("http://www.google.com");
    final HealthCheckResponse healthCheckResponse = urlHealthCheck.call();

    assertEquals(UrlHealthCheck.DEFAULT_NAME, healthCheckResponse.getName());
    assertEquals("GET http://www.google.com", healthCheckResponse.getData().get().get("host"));
    assertEquals(HealthCheckResponse.State.UP, healthCheckResponse.getState());

}
 
Example #14
Source File: SmallRyeHealthReporter.java    From smallrye-health with Apache License 2.0 5 votes vote down vote up
private void initUnis(List<Uni<HealthCheckResponse>> list, Iterable<HealthCheck> checks,
        Iterable<AsyncHealthCheck> asyncChecks) {
    for (HealthCheck check : checks) {
        list.add(callSync(check));
    }

    for (AsyncHealthCheck asyncCheck : asyncChecks) {
        list.add(callAsync(asyncCheck));
    }
}
 
Example #15
Source File: KafkaStreamsStateHealthCheck.java    From quarkus with Apache License 2.0 5 votes vote down vote up
@Override
public HealthCheckResponse call() {
    HealthCheckResponseBuilder responseBuilder = HealthCheckResponse.named("Kafka Streams state health check");
    try {
        KafkaStreams.State state = manager.getStreams().state();
        responseBuilder.state(state.isRunningOrRebalancing())
                .withData("state", state.name());
    } catch (Exception e) {
        responseBuilder.down().withData("technical_error", e.getMessage());
    }
    return responseBuilder.build();
}
 
Example #16
Source File: ReadinessHealthCheck.java    From javaee8-cookbook with Apache License 2.0 5 votes vote down vote up
@Override
public HealthCheckResponse call() {
    if (isAcessible()){
        return HealthCheckResponse.up("I'm up and ready!");
    } else{
        return HealthCheckResponse.down("I'm up, but not ready...");
    }
}
 
Example #17
Source File: ResponseBuilder.java    From smallrye-health with Apache License 2.0 5 votes vote down vote up
@Override
public HealthCheckResponse build() {
    if (null == this.name || this.name.trim().length() == 0) {
        throw HealthMessages.msg.invalidHealthCheckName();
    }

    return new Response(this.name, this.state, this.data.isEmpty() ? null : this.data);
}
 
Example #18
Source File: HealthCheckServlet.java    From hammock with Apache License 2.0 5 votes vote down vote up
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    Jsonb jsonb = JsonbBuilder.newBuilder().build();
    HealthCheckModel healthCheckModel = healthCheckManager.performHealthChecks();
    if (healthCheckModel.getOutcome().equalsIgnoreCase(HealthCheckResponse.State.UP.name())) {
        resp.setStatus(200);
    } else {
        resp.setStatus(503);
    }
    jsonb.toJson(healthCheckModel, resp.getOutputStream());
}
 
Example #19
Source File: UrlHealthCheck.java    From smallrye-health with Apache License 2.0 5 votes vote down vote up
@Override
public HealthCheckResponse call() {
    final HealthCheckResponseBuilder healthCheckResponseBuilder = HealthCheckResponse
            .named(name);
    healthCheckResponseBuilder.withData("host", String.format("%s %s", this.requestMethod, this.url));
    try {
        final HttpURLConnection httpUrlConn = (HttpURLConnection) new URL(this.url)
                .openConnection();

        httpUrlConn.setRequestMethod(requestMethod);

        httpUrlConn.setConnectTimeout(timeout);
        httpUrlConn.setReadTimeout(timeout);

        final boolean isUp = httpUrlConn.getResponseCode() == statusCode;

        if (!isUp) {
            healthCheckResponseBuilder.withData("error", String.format("Expected response code %d but actual is %d",
                    statusCode, httpUrlConn.getResponseCode()));
        }

        healthCheckResponseBuilder.state(isUp);

    } catch (Exception e) {
        HealthChecksLogging.log.urlHealthCheckError(e);

        healthCheckResponseBuilder.withData("error",
                String.format("%s: %s", e.getClass().getCanonicalName(), e.getMessage()));
        healthCheckResponseBuilder.down();
    }

    return healthCheckResponseBuilder.build();
}
 
Example #20
Source File: DBHealthCheckTest.java    From trellis with Apache License 2.0 5 votes vote down vote up
@Test
void testHealthy() throws SQLException {
    final DataSource mockDataSource = mock(DataSource.class);
    final Connection mockConnection = mock(Connection.class);
    when(mockDataSource.getConnection()).thenReturn(mockConnection);
    when(mockConnection.isClosed()).thenReturn(false);

    final HealthCheck check = new DBHealthCheck(mockDataSource);
    assertEquals(HealthCheckResponse.State.UP, check.call().getState(), "Database connection isn't healthy!");
}
 
Example #21
Source File: DataHealthCheck.java    From intellij-quarkus with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public HealthCheckResponse call() {
    return HealthCheckResponse.named("Health check with data")
        .up()
        .withData("foo", "fooValue")
        .withData("bar", "barValue")
        .build();
}
 
Example #22
Source File: UrlHealthCheckTest.java    From smallrye-health with Apache License 2.0 5 votes vote down vote up
@Test
public void testUrlCheckIncorrectStatusCode() {
    final HealthCheck urlHealthCheck = new UrlHealthCheck("http://www.google.com")
            .statusCode(HttpURLConnection.HTTP_CREATED);
    final HealthCheckResponse healthCheckResponse = urlHealthCheck.call();

    assertEquals(HealthCheckResponse.State.DOWN, healthCheckResponse.getState());
    assertEquals("Expected response code 201 but actual is 200", healthCheckResponse.getData().get().get("error"));
}
 
Example #23
Source File: InventoryHealth.java    From microprofile-sandbox with Apache License 2.0 5 votes vote down vote up
@Override
public HealthCheckResponse call() {
    if (!isHealthy()) {
        return HealthCheckResponse.named(InventoryResource.class.getSimpleName())
                .withData("services", "not available").down().build();
    }
    return HealthCheckResponse.named(InventoryResource.class.getSimpleName()).withData("services", "available").up()
            .build();
}
 
Example #24
Source File: TriplestoreHealthCheckTest.java    From trellis with Apache License 2.0 5 votes vote down vote up
@Test
void testHealthy() {
    final Dataset dataset = rdf.createDataset();
    final RDFConnection rdfConnection = connect(wrap(toJena(dataset)));
    final HealthCheck check = new TriplestoreHealthCheck(rdfConnection);
    assertEquals(HealthCheckResponse.State.UP, check.call().getState(), "RDFConnection isn't healthy!");
}
 
Example #25
Source File: SmallRyeHealthReporter.java    From smallrye-health with Apache License 2.0 5 votes vote down vote up
private SmallRyeHealth createSmallRyeHealth(JsonArrayBuilder results, HealthCheckResponse.State status) {
    JsonObjectBuilder builder = jsonProvider.createObjectBuilder();
    JsonArray checkResults = results.build();

    builder.add("status", checkResults.isEmpty() ? emptyChecksOutcome : status.toString());
    builder.add("checks", checkResults);

    return new SmallRyeHealth(builder.build());
}
 
Example #26
Source File: DispatchedThreadTest.java    From quarkus with Apache License 2.0 5 votes vote down vote up
@Override
public HealthCheckResponse call() {
    return HealthCheckResponse.named("my-liveness-check")
            .up()
            .withData("thread", Thread.currentThread().getName())
            .withData("request", Arc.container().requestContext().isActive())
            .build();
}
 
Example #27
Source File: DataHealthCheck.java    From quarkus-quickstarts with Apache License 2.0 5 votes vote down vote up
@Override
public HealthCheckResponse call() {
    return HealthCheckResponse.named("Health check with data")
            .up()
            .withData("foo", "fooValue")
            .withData("bar", "barValue")
            .build();
}
 
Example #28
Source File: SystemHealth.java    From boost with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public HealthCheckResponse call() {
    if (!System.getProperty("wlp.server.name").equals("defaultServer")) {
        return HealthCheckResponse.named(SystemResource.class.getSimpleName())
                .withData("default server", "not available").down().build();
    }
    return HealthCheckResponse.named(SystemResource.class.getSimpleName()).withData("default server", "available")
            .up().build();
}
 
Example #29
Source File: InfinispanHealthCheck.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
private HealthCheckResponse buildResponse(ChannelFactory channelFactory, boolean state) {
    return HealthCheckResponse.builder()
            .withData("nodes", Optional.ofNullable(channelFactory.getServers())
                    .orElse(Collections.emptyList())
                    .stream()
                    .map(String::valueOf)
                    .collect(Collectors.joining(",")))
            .name(state ? "Infinispan is Up" : "Infinispan is Down")
            .state(state)
            .build();
}
 
Example #30
Source File: SystemHealth.java    From boost with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public HealthCheckResponse call() {
    if (!System.getProperty("wlp.server.name").equals("defaultServer")) {
        return HealthCheckResponse.named(SystemResource.class.getSimpleName())
                .withData("default server", "not available").down().build();
    }
    return HealthCheckResponse.named(SystemResource.class.getSimpleName()).withData("default server", "available")
            .up().build();
}