Java Code Examples for org.eclipse.microprofile.health.HealthCheckResponseBuilder

The following examples show how to use org.eclipse.microprofile.health.HealthCheckResponseBuilder. 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
Source Project: boost   Source File: DBHealthCheck.java    License: 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
@Override
public HealthCheckResponse call() {

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

    try {
        serverListening(host,port);
        responseBuilder.up();
    } catch (Exception e) {
        // cannot access the database
        responseBuilder.down()
                .withData("error", e.getMessage());
    }

    return responseBuilder.build();
}
 
Example 3
@Override
public HealthCheckResponse call() {
    HealthCheckResponseBuilder responseBuilder = HealthCheckResponse.named("File system Readiness check");


    boolean tempFileExists = Files.exists(Paths.get("/tmp/tmp.lck"));
    if (!tempFileExists) {
        responseBuilder.up();
    }
    else {
        responseBuilder.down()
                .withData("error", "Lock file detected!");
    }

    return responseBuilder.build();
}
 
Example 4
/**
 * Queries the configured keycloak realm using RestClient and the {@link KeycloakService} typed interface
 * @param builder - health check response builder
 */
private void checkKeycloakRealm(HealthCheckResponseBuilder builder) {
    try {
        URI baseURI = URI.create(baseURL);
        System.out.printf("Checking keycloak(%s), baseURI: %s\n", realmName, baseURI);
        KeycloakService keycloakService = RestClientBuilder.newBuilder()
                .baseUri(baseURI)
                .build(KeycloakService.class);
        KeycloakRealm kcRealm = keycloakService.getRealm(realmName);
        builder.withData("realm", kcRealm.getRealm())
                .withData("publicKey", kcRealm.getPublicKey())
                .withData("accountService", kcRealm.getAccountService())
                .withData("tokenService", kcRealm.getTokenService())
                .up();
    } catch (Exception e) {
        e.printStackTrace();
        builder.withData("exception", e.getMessage())
            .down();
    }
}
 
Example 5
@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
@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 Project: smallrye-health   Source File: SocketHealthCheck.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public HealthCheckResponse call() {
    HealthCheckResponseBuilder healthCheckResponseBuilder = HealthCheckResponse
            .named(name);
    healthCheckResponseBuilder.withData("host", String.format("%s:%d", this.host, this.port));
    try (Socket s = new Socket()) {
        final SocketAddress socketAddress = new InetSocketAddress(host, port);
        s.connect(socketAddress, timeout);
        healthCheckResponseBuilder.up();
    } catch (IOException ex) {
        HealthChecksLogging.log.socketHealthCheckError(ex);

        healthCheckResponseBuilder.withData("error", ex.getMessage());
        healthCheckResponseBuilder.down();
    }
    return healthCheckResponseBuilder.build();
}
 
Example 8
Source Project: smallrye-health   Source File: InetAddressHealthCheck.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public HealthCheckResponse call() {
    final HealthCheckResponseBuilder healthCheckResponseBuilder = HealthCheckResponse.named(this.name);
    healthCheckResponseBuilder.withData("host", this.host);
    try {
        InetAddress addr = InetAddress.getByName(this.host);
        final boolean reachable = addr.isReachable(this.timeout);
        if (!reachable) {
            healthCheckResponseBuilder.withData("error", String.format("Host %s not reachable.", this.host));
        }

        healthCheckResponseBuilder.state(reachable);
    } catch (IOException e) {
        HealthChecksLogging.log.inetAddressHealthCheckError(e);

        healthCheckResponseBuilder.withData("error", e.getMessage());
        healthCheckResponseBuilder.down();
    }

    return healthCheckResponseBuilder.build();
}
 
Example 9
Source Project: smallrye-health   Source File: SmallRyeHealthReporter.java    License: Apache License 2.0 6 votes vote down vote up
private HealthCheckResponse handleFailure(String name, Throwable e) {
    // Log Stacktrace to server log so an error is not just in Health Check response
    HealthLogging.log.healthCheckError(e);

    HealthCheckResponseBuilder response = HealthCheckResponse.named(name).down();

    if (null != uncheckedExceptionDataStyle) {
        switch (uncheckedExceptionDataStyle) {
            case ROOT_CAUSE:
                response.withData(ROOT_CAUSE, getRootCause(e).getMessage());
                break;
            case STACK_TRACE:
                response.withData(STACK_TRACE, getStackTrace(e));
                break;
            default:
                // don't add anything
        }
    }

    return response.build();
}
 
Example 10
@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 11
Source Project: quarkus   Source File: KafkaHealthCheck.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public HealthCheckResponse call() {
    HealthCheckResponseBuilder builder = HealthCheckResponse.named("Kafka connection health check").up();
    try {
        StringBuilder nodes = new StringBuilder();
        for (Node node : client.describeCluster().nodes().get()) {
            if (nodes.length() > 0) {
                nodes.append(',');
            }
            nodes.append(node.host()).append(':').append(node.port());
        }
        return builder.withData("nodes", nodes.toString()).build();
    } catch (Exception e) {
        return builder.down().withData("reason", e.getMessage()).build();
    }
}
 
Example 12
Source Project: quarkus   Source File: MongoHealthCheck.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public HealthCheckResponse call() {
    HealthCheckResponseBuilder builder = HealthCheckResponse.named("MongoDB connection health check").up();
    for (Map.Entry<String, MongoClient> client : clients.entrySet()) {
        boolean isDefault = DEFAULT_CLIENT.equals(client.getKey());
        MongoClient mongoClient = client.getValue();
        try {
            Document document = mongoClient.getDatabase("admin").runCommand(new Document("ping", 1));
            String mongoClientName = isDefault ? "default" : client.getKey();
            builder.up().withData(mongoClientName, document.toJson());
        } catch (Exception e) {
            return builder.down().withData("reason", e.getMessage()).build();
        }
    }
    return builder.build();
}
 
Example 13
Source Project: quarkus   Source File: Neo4jHealthCheck.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public HealthCheckResponse call() {

    HealthCheckResponseBuilder builder = HealthCheckResponse.named("Neo4j connection health check").up();
    try {
        ResultSummary resultSummary;
        // Retry one time when the session has been expired
        try {
            resultSummary = runHealthCheckQuery();
        } catch (SessionExpiredException sessionExpiredException) {
            log.warn(MESSAGE_SESSION_EXPIRED);
            resultSummary = runHealthCheckQuery();
        }
        return buildStatusUp(resultSummary, builder);
    } catch (Exception e) {
        return builder.down().withData("reason", e.getMessage()).build();
    }
}
 
Example 14
Source Project: quarkus   Source File: GrpcHealthCheck.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public HealthCheckResponse call() {
    ServingStatus servingStatus = healthService.getStatuses().get(GrpcHealthStorage.DEFAULT_SERVICE_NAME);

    HealthCheckResponseBuilder builder = HealthCheckResponse.named("gRPC Server health check").up();
    builder.name("gRPC Server");

    if (isUp(servingStatus)) {
        builder.up();
    } else {
        builder.down();
    }

    for (Map.Entry<String, ServingStatus> statusEntry : healthService.getStatuses().entrySet()) {
        String serviceName = statusEntry.getKey();
        if (!serviceName.equals(GrpcHealthStorage.DEFAULT_SERVICE_NAME)) {
            builder.withData(serviceName, isUp(statusEntry.getValue()));
        }
    }

    return builder.build();
}
 
Example 15
@Override
public HealthCheckResponse call() {
    HealthCheckResponseBuilder builder = HealthCheckResponse.named("Reactive MySQL connection health check").up();

    try {
        CompletableFuture<Void> databaseConnectionAttempt = new CompletableFuture<>();
        mySQLPool.query("SELECT 1")
                .execute(ar -> {
                    if (ar.failed()) {
                        builder.down();
                    }
                    databaseConnectionAttempt.complete(null);
                });
        databaseConnectionAttempt.get(10, TimeUnit.SECONDS);
    } catch (Exception exception) {
        builder.down();
    }

    return builder.build();
}
 
Example 16
Source Project: quarkus   Source File: ReactivePgDataSourceHealthCheck.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public HealthCheckResponse call() {
    HealthCheckResponseBuilder builder = HealthCheckResponse.named("Reactive PostgreSQL connection health check").up();

    try {
        CompletableFuture<Void> databaseConnectionAttempt = new CompletableFuture<>();
        pgPool.query("SELECT 1")
                .execute(ar -> {
                    if (ar.failed()) {
                        builder.down();
                    }
                    databaseConnectionAttempt.complete(null);
                });
        databaseConnectionAttempt.get(10, TimeUnit.SECONDS);
    } catch (Exception exception) {
        builder.down();
    }

    return builder.build();
}
 
Example 17
Source Project: quarkus   Source File: KafkaStreamsTopicsHealthCheck.java    License: 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 18
Source Project: microprofile-sandbox   Source File: DBHealthCheck.java    License: Apache License 2.0 6 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 19
Source Project: trader   Source File: LivenessProbe.java    License: 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 20
Source Project: trader   Source File: ReadinessProbe.java    License: Apache License 2.0 6 votes vote down vote up
public HealthCheckResponse call() {
	HealthCheckResponse response = null;
	String message = "Ready";
	try {
		HealthCheckResponseBuilder builder = HealthCheckResponse.named("Trader");

		if ((jwtAudience==null) || (jwtIssuer==null)) { //can't run without these env vars
			builder = builder.down();
			message = "JWT environment variables not set!";
			logger.warning("Returning NOT ready!");
		} else {
			builder = builder.up();
			logger.fine("Returning ready!");
		}

		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 21
@Override
public HealthCheckResponse call() {
    HealthCheckResponseBuilder responseBuilder = HealthCheckResponse.named("MemoryHealthCheck Liveness check");
    long freeMemory = Runtime.getRuntime().freeMemory();

    if (freeMemory >= threshold) {
        responseBuilder.up();
    }
    else {
        responseBuilder.down()
                .withData("error", "Not enough free memory! Please restart application");
    }
    return responseBuilder.build();
}
 
Example 22
Source Project: camel-quarkus   Source File: CamelUptimeHealthCheck.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public HealthCheckResponse call() {
    HealthCheckResponseBuilder builder = HealthCheckResponse.named("Uptime readiness check");

    if (camelContext.getUptimeMillis() > 0) {
        builder.up();
    } else {
        builder.down();
    }

    return builder.build();
}
 
Example 23
private void checkDiskspace(HealthCheckResponseBuilder builder) {
    File root = new File(pathToMonitor);
    long usableSpace = root.getUsableSpace();
    long freeSpace = root.getFreeSpace();
    long pctFree = 0;
    if (usableSpace > 0) {
        pctFree = (100 * usableSpace) / freeSpace;
    }
    builder.withData("path", root.getAbsolutePath())
            .withData("exits", root.exists())
            .withData("usableSpace", usableSpace)
            .withData("freeSpace", freeSpace)
            .withData("pctFree", pctFree)
            .state(freeSpace >= freeSpaceThreshold);
}
 
Example 24
Source Project: smallrye-health   Source File: UrlHealthCheck.java    License: 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 25
Source Project: smallrye-health   Source File: ResponseBuilder.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public HealthCheckResponseBuilder state(boolean up) {
    if (up) {
        return up();
    }

    return down();
}
 
Example 26
Source Project: quarkus   Source File: ReactiveDB2DataSourceHealthCheck.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public HealthCheckResponse call() {
    HealthCheckResponseBuilder builder = HealthCheckResponse.named("Reactive DB2 connection health check").up();

    try {
        db2Pool.query("SELECT 1 FROM SYSIBM.SYSDUMMY1")
                .execute()
                .await().atMost(Duration.ofSeconds(10));
    } catch (Exception exception) {
        builder.down();
    }

    return builder.build();
}
 
Example 27
Source Project: quarkus   Source File: Neo4jHealthCheck.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Applies the given {@link ResultSummary} to the {@link HealthCheckResponseBuilder builder} and calls {@code build}
 * afterwards.
 *
 * @param resultSummary the result summary returned by the server
 * @param builder the health builder to be modified
 * @return the final {@link HealthCheckResponse health check response}
 */
private static HealthCheckResponse buildStatusUp(ResultSummary resultSummary, HealthCheckResponseBuilder builder) {
    ServerInfo serverInfo = resultSummary.server();

    builder.withData("server", serverInfo.version() + "@" + serverInfo.address());

    String databaseName = resultSummary.database().name();
    if (!(databaseName == null || databaseName.trim().isEmpty())) {
        builder.withData("database", databaseName.trim());
    }

    return builder.build();
}
 
Example 28
Source Project: quarkus   Source File: VaultHealthCheck.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public HealthCheckResponse call() {

    final HealthCheckResponseBuilder builder = HealthCheckResponse.named("Vault connection health check");

    try {
        final VaultHealth vaultHealth = this.vaultSystemBackendEngine.health();

        if (vaultHealth.isInitializedUnsealedActive()) {
            builder.up();
        }

        if (vaultHealth.isUnsealedStandby()) {
            builder.down().withData("reason", "Unsealed and Standby");
        }

        if (vaultHealth.isRecoveryReplicationSecondary()) {
            builder.down().withData("reason", "Disaster recovery mode replication secondary and active");
        }

        if (vaultHealth.isPerformanceStandby()) {
            builder.down().withData("reason", "Performance standby");
        }

        if (vaultHealth.isNotInitialized()) {
            builder.down().withData("reason", "Not initialized");
        }

        if (vaultHealth.isSealed()) {
            builder.down().withData("reason", "Sealed");
        }

        return builder.build();

    } catch (Exception e) {
        return builder.down().withData("reason", e.getMessage()).build();
    }
}
 
Example 29
Source Project: quarkus   Source File: ConnectionFactoryHealthCheck.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public HealthCheckResponse call() {
    HealthCheckResponseBuilder builder = HealthCheckResponse.named("Artemis JMS health check");
    try (Connection connection = connectionFactory.createConnection()) {
        builder.up();
    } catch (Exception e) {
        builder.down();
    }
    return builder.build();
}
 
Example 30
Source Project: quarkus   Source File: ServerLocatorHealthCheck.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public HealthCheckResponse call() {
    HealthCheckResponseBuilder builder = HealthCheckResponse.named("Artemis Core health check");
    try (ClientSessionFactory factory = serverLocator.createSessionFactory()) {
        builder.up();
    } catch (Exception e) {
        builder.down();
    }
    return builder.build();
}