Java Code Examples for org.elasticsearch.action.admin.cluster.health.ClusterHealthResponse#getStatus()

The following examples show how to use org.elasticsearch.action.admin.cluster.health.ClusterHealthResponse#getStatus() . 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: ClientFactory.java    From act-platform with ISC License 6 votes vote down vote up
private boolean waitForConnection(RestHighLevelClient client) {
  long timeout = System.currentTimeMillis() + INITIALIZATION_TIMEOUT;
  while (System.currentTimeMillis() < timeout) {
    try {
      ClusterHealthResponse response = client.cluster().health(new ClusterHealthRequest(), RequestOptions.DEFAULT);
      LOGGER.debug("ElasticSearch cluster (%s) status is %s.", response.getClusterName(), response.getStatus());
      // If ElasticSearch is reachable and its status is at least 'yellow' return immediately.
      if (response.status() == RestStatus.OK && response.getStatus() != ClusterHealthStatus.RED) return true;
    } catch (ElasticsearchException | IOException ex) {
      LOGGER.debug(ex, "Could not fetch ElasticSearch cluster health information.");
    }

    try {
      Thread.sleep(INITIALIZATION_RETRY_WAIT);
    } catch (InterruptedException ignored) {
      // Re-interrupt thread and return immediately in order to trigger a component shutdown.
      Thread.currentThread().interrupt();
      return false;
    }

    LOGGER.warning("ElasticSearch cluster is not available. Trying again.");
  }

  return false;
}
 
Example 2
Source File: AbstractElasticSearchTest.java    From camunda-bpm-elasticsearch with Apache License 2.0 6 votes vote down vote up
/**
   * Waits for all relocating shards to become active and the cluster has reached the given health status
   * using the cluster health API.
   */
  public ClusterHealthStatus waitForRelocation(ClusterHealthStatus status) {
    ClusterHealthRequest request = Requests.clusterHealthRequest().waitForRelocatingShards(0);
    if (status != null) {
      request.waitForStatus(status);
    }
    ClusterHealthResponse actionGet = adminClient.cluster()
        .health(request).actionGet();
    if (actionGet.isTimedOut()) {
//      logger.info("waitForRelocation timed out (status={}), cluster state:\n{}\n{}", status, adminClient.cluster().prepareState().get().getState().prettyPrint(), adminClient.cluster().preparePendingClusterTasks().get().prettyPrint());
      assertThat("timed out waiting for relocation", actionGet.isTimedOut(), equalTo(false));
    }
    if (status != null) {
      assertThat(actionGet.getStatus(), equalTo(status));
    }
    return actionGet.getStatus();
  }
 
Example 3
Source File: ESIntegTestCase.java    From crate with Apache License 2.0 6 votes vote down vote up
/**
 * Waits for all relocating shards to become active and the cluster has reached the given health status
 * using the cluster health API.
 */
public ClusterHealthStatus waitForRelocation(ClusterHealthStatus status) {
    ClusterHealthRequest request = Requests.clusterHealthRequest().waitForNoRelocatingShards(true);
    if (status != null) {
        request.waitForStatus(status);
    }
    ClusterHealthResponse actionGet = client().admin().cluster()
        .health(request).actionGet();
    if (actionGet.isTimedOut()) {
        logger.info("waitForRelocation timed out (status={}), cluster state:\n{}\n{}", status,
            client().admin().cluster().prepareState().get().getState(), client().admin().cluster().preparePendingClusterTasks().get());
        assertThat("timed out waiting for relocation", actionGet.isTimedOut(), equalTo(false));
    }
    if (status != null) {
        assertThat(actionGet.getStatus(), equalTo(status));
    }
    return actionGet.getStatus();
}
 
Example 4
Source File: SQLTransportExecutor.java    From crate with Apache License 2.0 6 votes vote down vote up
private ClusterHealthStatus ensureState(ClusterHealthStatus state) {
    Client client = clientProvider.client();
    ClusterHealthResponse actionGet = client.admin().cluster().health(
        Requests.clusterHealthRequest()
            .waitForStatus(state)
            .waitForEvents(Priority.LANGUID).waitForNoRelocatingShards(false)
    ).actionGet();

    if (actionGet.isTimedOut()) {
        LOGGER.info("ensure state timed out, cluster state:\n{}\n{}",
            client.admin().cluster().prepareState().get().getState(),
            client.admin().cluster().preparePendingClusterTasks().get());
        assertThat("timed out waiting for state", actionGet.isTimedOut(), equalTo(false));
    }
    if (state == ClusterHealthStatus.YELLOW) {
        assertThat(actionGet.getStatus(), Matchers.anyOf(equalTo(state), equalTo(ClusterHealthStatus.GREEN)));
    } else {
        assertThat(actionGet.getStatus(), equalTo(state));
    }
    return actionGet.getStatus();
}
 
Example 5
Source File: AwsRestHighLevelClient.java    From aws-athena-query-federation with Apache License 2.0 5 votes vote down vote up
/**
 * Retrieves cluster-health information for shards associated with the specified index. The request will time out
 * if no results are returned after a period of time indicated by timeout.
 * @param index is used to restrict the request to a specified index.
 * @param timeout is the command timeout period in seconds.
 * @return a set of shard ids for the specified index.
 * @throws IOException if an error occurs while sending the request to the Elasticsearch instance.
 * @throws RuntimeException if the request times out, or no active-primary shards are present.
 */
public Set<Integer> getShardIds(String index, long timeout)
        throws RuntimeException, IOException
{
    ClusterHealthRequest request = new ClusterHealthRequest(index)
            .timeout(new TimeValue(timeout, TimeUnit.SECONDS));
    // Set request to shard-level details
    request.level(ClusterHealthRequest.Level.SHARDS);

    ClusterHealthResponse response = cluster().health(request, RequestOptions.DEFAULT);

    if (response.isTimedOut()) {
        throw new RuntimeException("Request timed out for index (" + index + ").");
    }
    else if (response.getActiveShards() == 0) {
        throw new RuntimeException("There are no active shards for index (" + index + ").");
    }
    else if (response.getStatus() == ClusterHealthStatus.RED) {
        throw new RuntimeException("Request aborted for index (" + index +
                ") due to cluster's status (RED) - One or more primary shards are unassigned.");
    }
    else if (!response.getIndices().containsKey(index)) {
        throw new RuntimeException("Request has an invalid index (" + index + ").");
    }

    return response.getIndices().get(index).getShards().keySet();
}
 
Example 6
Source File: ElasticsearchClient.java    From yacy_grid_mcp with GNU Lesser General Public License v2.1 5 votes vote down vote up
@SuppressWarnings("unused")
private boolean clusterReady() {
    if (clusterReadyCache) return true;
    ClusterHealthResponse chr = elasticsearchClient.admin().cluster().prepareHealth().get();
    clusterReadyCache = chr.getStatus() != ClusterHealthStatus.RED;
    return clusterReadyCache;
}
 
Example 7
Source File: ElasticSearchHealthCheck.java    From james-project with Apache License 2.0 5 votes vote down vote up
@VisibleForTesting
Result toHealthCheckResult(ClusterHealthResponse response) {
    switch (response.getStatus()) {
        case GREEN:
        case YELLOW:
            return Result.healthy(COMPONENT_NAME);
        case RED:
            return Result.unhealthy(COMPONENT_NAME, response.getClusterName() + " status is RED");
        default:
            throw new NotImplementedException("Un-handled ElasticSearch cluster status");
    }
}
 
Example 8
Source File: ElasticsearchClusterRunner.java    From elasticsearch-cluster-runner with Apache License 2.0 5 votes vote down vote up
/**
 * Wait for green state of a cluster.
 *
 * @param indices indices to check status
 * @return cluster health status
 */
public ClusterHealthStatus ensureGreen(final String... indices) {
    final ClusterHealthResponse actionGet = client().admin().cluster().health(
            Requests.clusterHealthRequest(indices).waitForGreenStatus().waitForEvents(Priority.LANGUID).waitForNoRelocatingShards(true))
            .actionGet();
    if (actionGet.isTimedOut()) {
        onFailure("ensureGreen timed out, cluster state:\n" + client().admin().cluster().prepareState().get().getState() + "\n"
                + client().admin().cluster().preparePendingClusterTasks().get(), actionGet);
    }
    return actionGet.getStatus();
}
 
Example 9
Source File: ElasticsearchClusterRunner.java    From elasticsearch-cluster-runner with Apache License 2.0 5 votes vote down vote up
/**
 * Wait for yellow state of a cluster.
 *
 * @param indices indices to check status
 * @return cluster health status
 */
public ClusterHealthStatus ensureYellow(final String... indices) {
    final ClusterHealthResponse actionGet = client().admin().cluster().health(Requests.clusterHealthRequest(indices)
            .waitForNoRelocatingShards(true).waitForYellowStatus().waitForEvents(Priority.LANGUID)).actionGet();
    if (actionGet.isTimedOut()) {
        onFailure("ensureYellow timed out, cluster state:\n" + "\n" + client().admin().cluster().prepareState().get().getState() + "\n"
                + client().admin().cluster().preparePendingClusterTasks().get(), actionGet);
    }
    return actionGet.getStatus();
}
 
Example 10
Source File: ElasticsearchClusterRunner.java    From elasticsearch-cluster-runner with Apache License 2.0 5 votes vote down vote up
public ClusterHealthStatus waitForRelocation() {
    final ClusterHealthRequest request = Requests.clusterHealthRequest().waitForNoRelocatingShards(true);
    final ClusterHealthResponse actionGet = client().admin().cluster().health(request).actionGet();
    if (actionGet.isTimedOut()) {
        onFailure("waitForRelocation timed out, cluster state:\n" + "\n" + client().admin().cluster().prepareState().get().getState()
                + "\n" + client().admin().cluster().preparePendingClusterTasks().get(), actionGet);
    }
    return actionGet.getStatus();
}
 
Example 11
Source File: PingResponse.java    From fess with Apache License 2.0 5 votes vote down vote up
public PingResponse(final ClusterHealthResponse response) {
    status = response.getStatus() == ClusterHealthStatus.RED ? 1 : 0;
    clusterName = response.getClusterName();
    clusterStatus = response.getStatus().toString();
    try (OutputStream out = EsUtil.getXContentBuilderOutputStream((builder, params) -> {
        builder.startObject();
        builder.field(CLUSTER_NAME, response.getClusterName());
        builder.field(STATUS, response.getStatus().name().toLowerCase(Locale.ROOT));
        builder.field(TIMED_OUT, response.isTimedOut());
        builder.field(NUMBER_OF_NODES, response.getNumberOfNodes());
        builder.field(NUMBER_OF_DATA_NODES, response.getNumberOfDataNodes());
        builder.field(ACTIVE_PRIMARY_SHARDS, response.getActivePrimaryShards());
        builder.field(ACTIVE_SHARDS, response.getActiveShards());
        builder.field(RELOCATING_SHARDS, response.getRelocatingShards());
        builder.field(INITIALIZING_SHARDS, response.getInitializingShards());
        builder.field(UNASSIGNED_SHARDS, response.getUnassignedShards());
        builder.field(DELAYED_UNASSIGNED_SHARDS, response.getDelayedUnassignedShards());
        builder.field(NUMBER_OF_PENDING_TASKS, response.getNumberOfPendingTasks());
        builder.field(NUMBER_OF_IN_FLIGHT_FETCH, response.getNumberOfInFlightFetch());
        builder.field(TASK_MAX_WAIT_TIME_IN_QUEUE_IN_MILLIS, response.getTaskMaxWaitingTime().getMillis());
        builder.field(ACTIVE_SHARDS_PERCENT_AS_NUMBER, response.getActiveShardsPercent());
        builder.endObject();
        return builder;
    }, XContentType.JSON)) {
        message = ((ByteArrayOutputStream) out).toString(Constants.UTF_8);
        if (StringUtil.isBlank(message)) {
            message = "{}";
        }
    } catch (final IOException e) {
        message = "{ \"error\" : \"" + StringEscapeUtils.escapeJson(e.getMessage()) + "\"}";
    }
}
 
Example 12
Source File: ESIntegTestCase.java    From crate with Apache License 2.0 5 votes vote down vote up
private ClusterHealthStatus ensureColor(ClusterHealthStatus clusterHealthStatus, TimeValue timeout, boolean waitForNoInitializingShards,
                                        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)
        .waitForNoInitializingShards(waitForNoInitializingShards)
        // We currently often use ensureGreen or ensureYellow to check whether the cluster is back in a good state after shutting down
        // a node. If the node that is stopped is the master node, another node will become master and publish a cluster state where it
        // is master but where the node that was stopped hasn't been removed yet from the cluster state. It will only subsequently
        // publish a second state where the old master is removed. If the ensureGreen/ensureYellow is timed just right, it will get to
        // execute before the second cluster state update removes the old master and the condition ensureGreen / ensureYellow will
        // trivially hold if it held before the node was shut down. The following "waitForNodes" condition ensures that the node has
        // been removed by the master so that the health check applies to the set of nodes we expect to be part of the cluster.
        .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();
}
 
Example 13
Source File: ESSingleNodeTestCase.java    From crate with Apache License 2.0 5 votes vote down vote up
/**
 * Ensures the cluster has a green state via the cluster health API. This method will also wait for relocations.
 * It is useful to ensure that all action on the cluster have finished and all shards that were currently relocating
 * are now allocated and started.
 *
 * @param timeout time out value to set on {@link org.elasticsearch.action.admin.cluster.health.ClusterHealthRequest}
 */
public ClusterHealthStatus ensureGreen(TimeValue timeout, String... indices) {
    ClusterHealthResponse actionGet = client().admin().cluster()
            .health(Requests.clusterHealthRequest(indices).timeout(timeout).waitForGreenStatus().waitForEvents(Priority.LANGUID)
                    .waitForNoRelocatingShards(true)).actionGet();
    if (actionGet.isTimedOut()) {
        logger.info("ensureGreen timed out, cluster state:\n{}\n{}", client().admin().cluster().prepareState().get().getState(),
            client().admin().cluster().preparePendingClusterTasks().get());
        assertThat("timed out waiting for green state", actionGet.isTimedOut(), equalTo(false));
    }
    assertThat(actionGet.getStatus(), equalTo(ClusterHealthStatus.GREEN));
    logger.debug("indices {} are green", indices.length == 0 ? "[_all]" : indices);
    return actionGet.getStatus();
}