Search in sources :

Example 1 with HealthResult

use of io.micronaut.management.health.indicator.HealthResult in project micronaut-core by micronaut-projects.

the class HealthResultFilter method doFilterOnce.

@Override
protected Publisher<MutableHttpResponse<?>> doFilterOnce(HttpRequest<?> request, ServerFilterChain chain) {
    return Publishers.map(chain.proceed(request), response -> {
        Object body = response.body();
        if (body instanceof HealthResult) {
            HealthResult healthResult = (HealthResult) body;
            HealthStatus status = healthResult.getStatus();
            HttpStatus httpStatus = healthEndpoint.getStatusConfiguration().getHttpMapping().get(status.getName());
            if (httpStatus != null) {
                response.status(httpStatus);
            } else {
                boolean operational = status.getOperational().orElse(true);
                if (!operational) {
                    response.status(HttpStatus.SERVICE_UNAVAILABLE);
                }
            }
        }
        return response;
    });
}
Also used : HttpStatus(io.micronaut.http.HttpStatus) HealthStatus(io.micronaut.health.HealthStatus) HealthResult(io.micronaut.management.health.indicator.HealthResult)

Example 2 with HealthResult

use of io.micronaut.management.health.indicator.HealthResult in project micronaut-core by micronaut-projects.

the class JdbcIndicator method getResult.

private Publisher<HealthResult> getResult(DataSource dataSource) {
    if (executorService == null) {
        throw new IllegalStateException("I/O ExecutorService is null");
    }
    return new AsyncSingleResultPublisher<>(executorService, () -> {
        Optional<Throwable> throwable = Optional.empty();
        Map<String, Object> details = null;
        String key;
        try (Connection connection = dataSource.getConnection()) {
            if (connection.isValid(CONNECTION_TIMEOUT)) {
                DatabaseMetaData metaData = connection.getMetaData();
                key = metaData.getURL();
                details = new LinkedHashMap<>(1);
                details.put("database", metaData.getDatabaseProductName());
                details.put("version", metaData.getDatabaseProductVersion());
            } else {
                throw new SQLException("Connection was not valid");
            }
        } catch (SQLException e) {
            throwable = Optional.of(e);
            try {
                String url = dataSource.getClass().getMethod("getUrl").invoke(dataSource).toString();
                if (url.startsWith("jdbc:")) {
                    url = url.substring(5);
                }
                url = url.replaceFirst(";", "?");
                url = url.replaceAll(";", "&");
                URI uri = new URI(url);
                key = uri.getHost() + ":" + uri.getPort() + uri.getPath();
            } catch (Exception n) {
                key = dataSource.getClass().getName() + "@" + Integer.toHexString(dataSource.hashCode());
            }
        }
        HealthResult.Builder builder = HealthResult.builder(key);
        if (throwable.isPresent()) {
            builder.exception(throwable.get());
            builder.status(HealthStatus.DOWN);
        } else {
            builder.status(HealthStatus.UP);
            builder.details(details);
        }
        return builder.build();
    });
}
Also used : SQLException(java.sql.SQLException) Connection(java.sql.Connection) DatabaseMetaData(java.sql.DatabaseMetaData) URI(java.net.URI) SQLException(java.sql.SQLException) AsyncSingleResultPublisher(io.micronaut.core.async.publisher.AsyncSingleResultPublisher) HealthResult(io.micronaut.management.health.indicator.HealthResult)

Example 3 with HealthResult

use of io.micronaut.management.health.indicator.HealthResult in project micronaut-elasticsearch by micronaut-projects.

the class ElasticsearchClientHealthIndicator method getResult.

/**
 * Tries to call the cluster info API on Elasticsearch to obtain information about the cluster. If the call succeeds, the Elasticsearch cluster
 * health status (GREEN / YELLOW / RED) will be included in the health indicator details.
 *
 * @return A positive health result UP if the cluster can be communicated with and is in either GREEN or YELLOW status. A negative health result
 * DOWN if the cluster cannot be communicated with or is in RED status.
 */
@Override
public Publisher<HealthResult> getResult() {
    return (subscriber -> {
        final HealthResult.Builder resultBuilder = HealthResult.builder(NAME);
        try {
            client.cluster().health().handle((health, exception) -> {
                if (exception != null) {
                    subscriber.onNext(resultBuilder.status(DOWN).exception(exception).build());
                    subscriber.onComplete();
                } else {
                    HealthStatus status = health.status() == co.elastic.clients.elasticsearch._types.HealthStatus.Red ? DOWN : UP;
                    subscriber.onNext(resultBuilder.status(status).details(health).build());
                    subscriber.onComplete();
                }
                return health;
            });
        } catch (IOException e) {
            subscriber.onNext(resultBuilder.status(DOWN).exception(e).build());
            subscriber.onComplete();
        }
    });
}
Also used : HealthStatus(io.micronaut.health.HealthStatus) IOException(java.io.IOException) HealthResult(io.micronaut.management.health.indicator.HealthResult)

Example 4 with HealthResult

use of io.micronaut.management.health.indicator.HealthResult in project micronaut-neo4j by micronaut-projects.

the class Neo4jHealthIndicator method getResult.

@Override
public Publisher<HealthResult> getResult() {
    try {
        Mono<HealthResult> healthResultSingle = Mono.create(emitter -> {
            AsyncSession session = boltDriver.asyncSession();
            CompletionStage<ResultSummary> query = session.writeTransactionAsync(tx -> tx.runAsync("RETURN 1 AS result").thenCompose(ResultCursor::consumeAsync));
            query.handleAsync((resultSummaryStage, throwable) -> {
                if (throwable != null) {
                    return buildErrorResult(throwable);
                } else {
                    HealthResult.Builder status = HealthResult.builder(NAME, HealthStatus.UP);
                    ServerInfo serverInfo = resultSummaryStage.server();
                    status.details(Collections.singletonMap("server", serverInfo.version() + "@" + serverInfo.address()));
                    return status.build();
                }
            }).thenComposeAsync(status -> session.closeAsync().handle((signal, throwable) -> status)).thenAccept(emitter::success);
        });
        return healthResultSingle.subscribeOn(Schedulers.fromExecutorService(ioExecutor));
    } catch (Throwable e) {
        return Mono.just(buildErrorResult(e));
    }
}
Also used : Driver(org.neo4j.driver.Driver) Publisher(org.reactivestreams.Publisher) Singleton(jakarta.inject.Singleton) HealthIndicator(io.micronaut.management.health.indicator.HealthIndicator) Mono(reactor.core.publisher.Mono) HealthStatus(io.micronaut.health.HealthStatus) ServerInfo(org.neo4j.driver.summary.ServerInfo) TaskExecutors(io.micronaut.scheduling.TaskExecutors) CompletionStage(java.util.concurrent.CompletionStage) AsyncSession(org.neo4j.driver.async.AsyncSession) ResultSummary(org.neo4j.driver.summary.ResultSummary) Requires(io.micronaut.context.annotation.Requires) Schedulers(reactor.core.scheduler.Schedulers) ResultCursor(org.neo4j.driver.async.ResultCursor) HealthResult(io.micronaut.management.health.indicator.HealthResult) Collections(java.util.Collections) ExecutorService(java.util.concurrent.ExecutorService) Named(jakarta.inject.Named) ServerInfo(org.neo4j.driver.summary.ServerInfo) AsyncSession(org.neo4j.driver.async.AsyncSession) ResultSummary(org.neo4j.driver.summary.ResultSummary) HealthResult(io.micronaut.management.health.indicator.HealthResult)

Example 5 with HealthResult

use of io.micronaut.management.health.indicator.HealthResult in project micronaut-mongodb by micronaut-projects.

the class MongoHealthIndicator method checkRegisteredMongoClient.

private Publisher<HealthResult> checkRegisteredMongoClient(BeanRegistration<MongoClient> registration) {
    MongoClient mongoClient = registration.getBean();
    String databaseName = "mongodb (" + registration.getIdentifier().getName() + ")";
    Flux<Map<String, String>> databasePings = Flux.from(pingMongo(mongoClient)).map(this::getVersionDetails).timeout(Duration.of(10, ChronoUnit.SECONDS)).retry(3);
    return databasePings.map(detail -> buildStatusUp(databaseName, detail)).onErrorResume(throwable -> Flux.just(buildStatusDown(throwable, databaseName)));
}
Also used : Document(org.bson.Document) java.util(java.util) BeanRegistration(io.micronaut.context.BeanRegistration) BeanContext(io.micronaut.context.BeanContext) Publisher(org.reactivestreams.Publisher) BasicDBObject(com.mongodb.BasicDBObject) HealthAggregator(io.micronaut.management.health.aggregator.HealthAggregator) Singleton(jakarta.inject.Singleton) HealthIndicator(io.micronaut.management.health.indicator.HealthIndicator) Collectors(java.util.stream.Collectors) MongoClient(com.mongodb.reactivestreams.client.MongoClient) HealthStatus(io.micronaut.health.HealthStatus) Flux(reactor.core.publisher.Flux) ChronoUnit(java.time.temporal.ChronoUnit) Duration(java.time.Duration) Requires(io.micronaut.context.annotation.Requires) HealthResult(io.micronaut.management.health.indicator.HealthResult) MongoClient(com.mongodb.reactivestreams.client.MongoClient)

Aggregations

HealthResult (io.micronaut.management.health.indicator.HealthResult)12 HealthStatus (io.micronaut.health.HealthStatus)8 Requires (io.micronaut.context.annotation.Requires)3 HealthIndicator (io.micronaut.management.health.indicator.HealthIndicator)3 Singleton (jakarta.inject.Singleton)3 Publisher (org.reactivestreams.Publisher)3 Row (io.vertx.reactivex.sqlclient.Row)2 IOException (java.io.IOException)2 Collections (java.util.Collections)2 Flux (reactor.core.publisher.Flux)2 BasicDBObject (com.mongodb.BasicDBObject)1 MongoClient (com.mongodb.reactivestreams.client.MongoClient)1 AbstractKafkaConfiguration (io.micronaut.configuration.kafka.config.AbstractKafkaConfiguration)1 KafkaDefaultConfiguration (io.micronaut.configuration.kafka.config.KafkaDefaultConfiguration)1 KafkaReactorUtil (io.micronaut.configuration.kafka.reactor.KafkaReactorUtil)1 BeanContext (io.micronaut.context.BeanContext)1 BeanRegistration (io.micronaut.context.BeanRegistration)1 AsyncSingleResultPublisher (io.micronaut.core.async.publisher.AsyncSingleResultPublisher)1 CollectionUtils (io.micronaut.core.util.CollectionUtils)1 CurrentHealthStatus (io.micronaut.health.CurrentHealthStatus)1