Java Code Examples for org.eclipse.microprofile.health.HealthCheckResponseBuilder#build()

The following examples show how to use org.eclipse.microprofile.health.HealthCheckResponseBuilder#build() . 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 Hands-On-Cloud-Native-Applications-with-Java-and-Quarkus with MIT License 6 votes vote down vote up
@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 2
Source File: ReactivePgDataSourceHealthCheck.java    From quarkus with 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 3
Source File: MongoHealthCheck.java    From quarkus with 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 4
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 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: SmallRyeHealthReporter.java    From smallrye-health with 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 7
Source File: ReadinessProbe.java    From trader with 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 8
Source File: InetAddressHealthCheck.java    From smallrye-health with 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 File: SocketHealthCheck.java    From smallrye-health with 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 10
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 11
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 12
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 13
Source File: ReactiveMySQLDataSourceHealthCheck.java    From quarkus with Apache License 2.0 6 votes vote down vote up
@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 14
Source File: ReadinessHealthCheck.java    From Hands-On-Cloud-Native-Applications-with-Java-and-Quarkus with MIT License 6 votes vote down vote up
@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 15
Source File: ConnectionFactoryHealthCheck.java    From quarkus with 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 16
Source File: ServerLocatorHealthCheck.java    From quarkus with 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();
}
 
Example 17
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 18
Source File: VaultHealthCheck.java    From quarkus with 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 19
Source File: MemoryHealthCheck.java    From Hands-On-Cloud-Native-Applications-with-Java-and-Quarkus with MIT License 5 votes vote down vote up
@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 20
Source File: KeycloakHealthCheck.java    From Hands-On-Enterprise-Java-Microservices-with-Eclipse-MicroProfile with MIT License 4 votes vote down vote up
@Override
public HealthCheckResponse call() {
    HealthCheckResponseBuilder builder = HealthCheckResponse.named("keycloak");
    checkKeycloakRealm(builder);
    return builder.build();
}