Search in sources :

Example 6 with ClusterHealthRequest

use of org.elasticsearch.action.admin.cluster.health.ClusterHealthRequest in project graylog2-server by Graylog2.

the class ElasticsearchProbe method elasticsearchStats.

public ElasticsearchStats elasticsearchStats() {
    final ClusterAdminClient adminClient = client.admin().cluster();
    final ClusterStatsResponse clusterStatsResponse = adminClient.clusterStats(new ClusterStatsRequest()).actionGet();
    final String clusterName = clusterStatsResponse.getClusterNameAsString();
    final ClusterStatsNodes clusterNodesStats = clusterStatsResponse.getNodesStats();
    final NodesStats nodesStats = NodesStats.create(clusterNodesStats.getCounts().getTotal(), clusterNodesStats.getCounts().getMasterOnly(), clusterNodesStats.getCounts().getDataOnly(), clusterNodesStats.getCounts().getMasterData(), clusterNodesStats.getCounts().getClient());
    final IndicesStats indicesStats = IndicesStats.create(clusterStatsResponse.getIndicesStats().getIndexCount(), clusterStatsResponse.getIndicesStats().getStore().sizeInBytes(), clusterStatsResponse.getIndicesStats().getFieldData().getMemorySizeInBytes());
    final PendingClusterTasksResponse pendingClusterTasksResponse = adminClient.pendingClusterTasks(new PendingClusterTasksRequest()).actionGet();
    final int pendingTasksSize = pendingClusterTasksResponse.pendingTasks().size();
    final List<Long> pendingTasksTimeInQueue = Lists.newArrayListWithCapacity(pendingTasksSize);
    for (PendingClusterTask pendingClusterTask : pendingClusterTasksResponse) {
        pendingTasksTimeInQueue.add(pendingClusterTask.getTimeInQueueInMillis());
    }
    final ClusterHealthResponse clusterHealthResponse = adminClient.health(new ClusterHealthRequest(indexSetRegistry.getIndexWildcards())).actionGet();
    final ClusterHealth clusterHealth = ClusterHealth.create(clusterHealthResponse.getNumberOfNodes(), clusterHealthResponse.getNumberOfDataNodes(), clusterHealthResponse.getActiveShards(), clusterHealthResponse.getRelocatingShards(), clusterHealthResponse.getActivePrimaryShards(), clusterHealthResponse.getInitializingShards(), clusterHealthResponse.getUnassignedShards(), clusterHealthResponse.isTimedOut(), pendingTasksSize, pendingTasksTimeInQueue);
    return ElasticsearchStats.create(clusterName, clusterHealthResponse.getStatus(), clusterHealth, nodesStats, indicesStats);
}
Also used : ClusterHealthResponse(org.elasticsearch.action.admin.cluster.health.ClusterHealthResponse) ClusterAdminClient(org.elasticsearch.client.ClusterAdminClient) ClusterHealthRequest(org.elasticsearch.action.admin.cluster.health.ClusterHealthRequest) ClusterStatsNodes(org.elasticsearch.action.admin.cluster.stats.ClusterStatsNodes) PendingClusterTask(org.elasticsearch.cluster.service.PendingClusterTask) PendingClusterTasksResponse(org.elasticsearch.action.admin.cluster.tasks.PendingClusterTasksResponse) ClusterStatsRequest(org.elasticsearch.action.admin.cluster.stats.ClusterStatsRequest) PendingClusterTasksRequest(org.elasticsearch.action.admin.cluster.tasks.PendingClusterTasksRequest) ClusterStatsResponse(org.elasticsearch.action.admin.cluster.stats.ClusterStatsResponse)

Example 7 with ClusterHealthRequest

use of org.elasticsearch.action.admin.cluster.health.ClusterHealthRequest in project elasticsearch by elastic.

the class ESIntegTestCase method ensureColor.

private ClusterHealthStatus ensureColor(ClusterHealthStatus clusterHealthStatus, TimeValue timeout, String... indices) {
    String color = clusterHealthStatus.name().toLowerCase(Locale.ROOT);
    String method = "ensure" + Strings.capitalize(color);
    ClusterHealthRequest healthRequest = Requests.clusterHealthRequest(indices).timeout(timeout).waitForStatus(clusterHealthStatus).waitForEvents(Priority.LANGUID).waitForNoRelocatingShards(true).waitForNodes(Integer.toString(cluster().size()));
    ClusterHealthResponse actionGet = client().admin().cluster().health(healthRequest).actionGet();
    if (actionGet.isTimedOut()) {
        logger.info("{} timed out, cluster state:\n{}\n{}", method, client().admin().cluster().prepareState().get().getState(), client().admin().cluster().preparePendingClusterTasks().get());
        fail("timed out waiting for " + color + " state");
    }
    assertThat("Expected at least " + clusterHealthStatus + " but got " + actionGet.getStatus(), actionGet.getStatus().value(), lessThanOrEqualTo(clusterHealthStatus.value()));
    logger.debug("indices {} are {}", indices.length == 0 ? "[_all]" : indices, color);
    return actionGet.getStatus();
}
Also used : ClusterHealthResponse(org.elasticsearch.action.admin.cluster.health.ClusterHealthResponse) ClusterHealthRequest(org.elasticsearch.action.admin.cluster.health.ClusterHealthRequest)

Example 8 with ClusterHealthRequest

use of org.elasticsearch.action.admin.cluster.health.ClusterHealthRequest in project elasticsearch by elastic.

the class ClusterStateHealthTests method testClusterHealthWaitsForClusterStateApplication.

public void testClusterHealthWaitsForClusterStateApplication() throws InterruptedException, ExecutionException {
    final CountDownLatch applyLatch = new CountDownLatch(1);
    final CountDownLatch listenerCalled = new CountDownLatch(1);
    setState(clusterService, ClusterState.builder(clusterService.state()).nodes(DiscoveryNodes.builder(clusterService.state().nodes()).masterNodeId(null)).build());
    clusterService.addStateApplier(event -> {
        listenerCalled.countDown();
        try {
            applyLatch.await();
        } catch (InterruptedException e) {
            logger.debug("interrupted", e);
        }
    });
    logger.info("--> submit task to restore master");
    clusterService.submitStateUpdateTask("restore master", new LocalClusterUpdateTask() {

        @Override
        public ClusterTasksResult<LocalClusterUpdateTask> execute(ClusterState currentState) throws Exception {
            return newState(ClusterState.builder(currentState).nodes(DiscoveryNodes.builder(currentState.nodes()).masterNodeId(currentState.nodes().getLocalNodeId())).build());
        }

        @Override
        public void onFailure(String source, Exception e) {
            logger.warn("unexpected failure", e);
        }
    });
    logger.info("--> waiting for listener to be called and cluster state being blocked");
    listenerCalled.await();
    TransportClusterHealthAction action = new TransportClusterHealthAction(Settings.EMPTY, transportService, clusterService, threadPool, new ActionFilters(new HashSet<>()), indexNameExpressionResolver, new TestGatewayAllocator());
    PlainActionFuture<ClusterHealthResponse> listener = new PlainActionFuture<>();
    action.execute(new ClusterHealthRequest().waitForGreenStatus(), listener);
    assertFalse(listener.isDone());
    logger.info("--> realising task to restore master");
    applyLatch.countDown();
    listener.get();
}
Also used : TestGatewayAllocator(org.elasticsearch.test.gateway.TestGatewayAllocator) ClusterState(org.elasticsearch.cluster.ClusterState) LocalClusterUpdateTask(org.elasticsearch.cluster.LocalClusterUpdateTask) ClusterHealthResponse(org.elasticsearch.action.admin.cluster.health.ClusterHealthResponse) ClusterHealthRequest(org.elasticsearch.action.admin.cluster.health.ClusterHealthRequest) ActionFilters(org.elasticsearch.action.support.ActionFilters) CountDownLatch(java.util.concurrent.CountDownLatch) IOException(java.io.IOException) ExecutionException(java.util.concurrent.ExecutionException) PlainActionFuture(org.elasticsearch.action.support.PlainActionFuture) TransportClusterHealthAction(org.elasticsearch.action.admin.cluster.health.TransportClusterHealthAction) HashSet(java.util.HashSet)

Example 9 with ClusterHealthRequest

use of org.elasticsearch.action.admin.cluster.health.ClusterHealthRequest in project elasticsearch by elastic.

the class TransportClientTests method testThatUsingAClosedClientThrowsAnException.

public void testThatUsingAClosedClientThrowsAnException() throws ExecutionException, InterruptedException {
    final TransportClient client = new MockTransportClient(Settings.EMPTY);
    client.close();
    final IllegalStateException e = expectThrows(IllegalStateException.class, () -> client.admin().cluster().health(new ClusterHealthRequest()).get());
    assertThat(e, hasToString(containsString("transport client is closed")));
}
Also used : MockTransportClient(org.elasticsearch.transport.MockTransportClient) ClusterHealthRequest(org.elasticsearch.action.admin.cluster.health.ClusterHealthRequest) MockTransportClient(org.elasticsearch.transport.MockTransportClient)

Example 10 with ClusterHealthRequest

use of org.elasticsearch.action.admin.cluster.health.ClusterHealthRequest in project graylog2-server by Graylog2.

the class IndexerSetupService method startUp.

@Override
protected void startUp() throws Exception {
    Tools.silenceUncaughtExceptionsInThisThread();
    LOG.debug("Starting indexer");
    node.start();
    final Client client = node.client();
    try {
        /* try to determine the cluster health. if this times out we could not connect and try to determine if there's
                   anything listening at all. if that happens this usually has these reasons:
                    1. cluster.name is different
                    2. network.publish_host is not reachable
                    3. wrong address configured
                    4. multicast in use but broken in this environment
                   we handle a red cluster state differently because if we can get that result it means the cluster itself
                   is reachable, which is a completely different problem from not being able to join at all.
                 */
        final ClusterHealthRequest atLeastRed = client.admin().cluster().prepareHealth().setWaitForStatus(ClusterHealthStatus.RED).request();
        final ClusterHealthResponse health = client.admin().cluster().health(atLeastRed).actionGet(configuration.getClusterDiscoveryTimeout(), MILLISECONDS);
        // we don't get here if we couldn't join the cluster. just check for red cluster state
        if (ClusterHealthStatus.RED.equals(health.getStatus())) {
            final Notification notification = notificationService.buildNow().addSeverity(Notification.Severity.URGENT).addType(Notification.Type.ES_CLUSTER_RED);
            notificationService.publishIfFirst(notification);
            LOG.warn("The Elasticsearch cluster state is RED which means shards are unassigned.");
            LOG.info("This usually indicates a crashed and corrupt cluster and needs to be investigated. Graylog will write into the local disk journal.");
            LOG.info("See {} for details.", DocsHelper.PAGE_ES_CONFIGURATION);
        }
        if (ClusterHealthStatus.GREEN.equals(health.getStatus())) {
            notificationService.fixed(Notification.Type.ES_CLUSTER_RED);
        }
        notificationService.fixed(Notification.Type.ES_UNAVAILABLE);
    } catch (ElasticsearchTimeoutException e) {
        final String hosts = node.settings().get("discovery.zen.ping.unicast.hosts");
        if (!isNullOrEmpty(hosts)) {
            final Iterable<String> hostList = Splitter.on(',').omitEmptyStrings().trimResults().split(hosts);
            for (String host : hostList) {
                final URI esUri = URI.create("http://" + HostAndPort.fromString(host).getHostText() + ":9200/");
                LOG.info("Checking Elasticsearch HTTP API at {}", esUri);
                // Try the HTTP API endpoint
                final Request request = new Request.Builder().get().url(esUri.resolve("/_nodes").toString()).build();
                try (final Response response = httpClient.newCall(request).execute()) {
                    if (response.isSuccessful()) {
                        final JsonNode resultTree = objectMapper.readTree(response.body().byteStream());
                        final JsonNode nodesList = resultTree.get("nodes");
                        if (!configuration.isDisableVersionCheck()) {
                            final Iterator<String> nodes = nodesList.fieldNames();
                            while (nodes.hasNext()) {
                                final String id = nodes.next();
                                final Version clusterVersion = Version.fromString(nodesList.get(id).get("version").textValue());
                                checkClusterVersion(clusterVersion);
                            }
                        }
                        final String clusterName = resultTree.get("cluster_name").textValue();
                        checkClusterName(clusterName);
                    } else {
                        LOG.error("Could not connect to Elasticsearch at " + esUri + ". Is it running?");
                    }
                } catch (IOException ioException) {
                    LOG.error("Could not connect to Elasticsearch: {}", ioException.getMessage());
                }
            }
        }
        final Notification notification = notificationService.buildNow().addSeverity(Notification.Severity.URGENT).addType(Notification.Type.ES_UNAVAILABLE);
        notificationService.publishIfFirst(notification);
        LOG.warn("Could not connect to Elasticsearch");
        LOG.info("If you're using multicast, check that it is working in your network and that Elasticsearch is accessible. Also check that the cluster name setting is correct.");
        LOG.info("See {} for details.", DocsHelper.PAGE_ES_CONFIGURATION);
    }
}
Also used : ClusterHealthResponse(org.elasticsearch.action.admin.cluster.health.ClusterHealthResponse) ClusterHealthRequest(org.elasticsearch.action.admin.cluster.health.ClusterHealthRequest) ThreadFactoryBuilder(com.google.common.util.concurrent.ThreadFactoryBuilder) Request(okhttp3.Request) ClusterHealthRequest(org.elasticsearch.action.admin.cluster.health.ClusterHealthRequest) JsonNode(com.fasterxml.jackson.databind.JsonNode) IOException(java.io.IOException) URI(java.net.URI) Notification(org.graylog2.notifications.Notification) Response(okhttp3.Response) ClusterHealthResponse(org.elasticsearch.action.admin.cluster.health.ClusterHealthResponse) ElasticsearchTimeoutException(org.elasticsearch.ElasticsearchTimeoutException) Version(org.elasticsearch.Version) Iterator(java.util.Iterator) Client(org.elasticsearch.client.Client) OkHttpClient(okhttp3.OkHttpClient)

Aggregations

ClusterHealthRequest (org.elasticsearch.action.admin.cluster.health.ClusterHealthRequest)11 ClusterHealthResponse (org.elasticsearch.action.admin.cluster.health.ClusterHealthResponse)8 IOException (java.io.IOException)3 Settings (org.elasticsearch.common.settings.Settings)3 Collections (java.util.Collections)2 HashSet (java.util.HashSet)2 Locale (java.util.Locale)2 Set (java.util.Set)2 NodeClient (org.elasticsearch.client.node.NodeClient)2 ClusterState (org.elasticsearch.cluster.ClusterState)2 ClusterHealthStatus (org.elasticsearch.cluster.health.ClusterHealthStatus)2 Strings (org.elasticsearch.common.Strings)2 RestController (org.elasticsearch.rest.RestController)2 RestRequest (org.elasticsearch.rest.RestRequest)2 JsonNode (com.fasterxml.jackson.databind.JsonNode)1 ThreadFactoryBuilder (com.google.common.util.concurrent.ThreadFactoryBuilder)1 CrateSettings (io.crate.metadata.settings.CrateSettings)1 URI (java.net.URI)1 UnknownHostException (java.net.UnknownHostException)1 Arrays (java.util.Arrays)1