Search in sources :

Example 16 with RestStatus

use of org.graylog.shaded.elasticsearch7.org.elasticsearch.rest.RestStatus in project pancm_project by xuwujing.

the class EsHighLevelCluster method catHealth.

/**
 * @return void
 * @Author pancm
 * @Description 设获取集群的健康情况
 * @Date 2020/1/2
 * @Param [index]
 */
public static void catHealth() throws IOException {
    ClusterHealthRequest request = new ClusterHealthRequest();
    ClusterHealthResponse response = client.cluster().health(request, RequestOptions.DEFAULT);
    String clusterName = response.getClusterName();
    ClusterHealthStatus status = response.getStatus();
    boolean timedOut = response.isTimedOut();
    RestStatus restStatus = response.status();
    int numberOfNodes = response.getNumberOfNodes();
    int numberOfDataNodes = response.getNumberOfDataNodes();
    int activeShards = response.getActiveShards();
    int activePrimaryShards = response.getActivePrimaryShards();
    int relocatingShards = response.getRelocatingShards();
    int initializingShards = response.getInitializingShards();
    int unassignedShards = response.getUnassignedShards();
    int delayedUnassignedShards = response.getDelayedUnassignedShards();
    double activeShardsPercent = response.getActiveShardsPercent();
    logger.info("clusterName:{},status:{},timedOut:{},restStatus:{}", clusterName, status, timedOut, restStatus.getStatus());
    List<Map<String, Object>> mapList = new ArrayList<>();
    response.getIndices().forEach((k, v) -> {
        Map<String, Object> map = new HashMap<>();
        String index = v.getIndex();
        int replicas = v.getNumberOfReplicas();
        int allShards = v.getActiveShards();
        int shards = v.getActivePrimaryShards();
        int status2 = v.getStatus().value();
        map.put("index", index);
        map.put("replicas", replicas);
        map.put("shards", shards);
        map.put("status", status2);
        System.out.println(map);
    });
}
Also used : ClusterHealthResponse(org.elasticsearch.action.admin.cluster.health.ClusterHealthResponse) ClusterHealthRequest(org.elasticsearch.action.admin.cluster.health.ClusterHealthRequest) ClusterHealthStatus(org.elasticsearch.cluster.health.ClusterHealthStatus) RestStatus(org.elasticsearch.rest.RestStatus)

Example 17 with RestStatus

use of org.graylog.shaded.elasticsearch7.org.elasticsearch.rest.RestStatus in project crate by crate.

the class RandomObjects method randomShardInfoFailure.

/**
 * Returns a tuple that contains a randomized {@link Failure} value (left side) and its corresponding
 * value (right side) after it has been printed out as a {@link ToXContent} and parsed back using a parsing
 * method like {@link ShardInfo.Failure#fromXContent(XContentParser)}.
 *
 * @param random Random generator
 */
private static Tuple<Failure, Failure> randomShardInfoFailure(Random random) {
    String index = randomAsciiLettersOfLength(random, 5);
    String indexUuid = randomAsciiLettersOfLength(random, 5);
    int shardId = randomIntBetween(random, 1, 10);
    String nodeId = randomAsciiLettersOfLength(random, 5);
    RestStatus status = randomFrom(random, RestStatus.INTERNAL_SERVER_ERROR, RestStatus.FORBIDDEN, RestStatus.NOT_FOUND);
    boolean primary = random.nextBoolean();
    ShardId shard = new ShardId(index, indexUuid, shardId);
    Exception actualException;
    ElasticsearchException expectedException;
    int type = randomIntBetween(random, 0, 3);
    switch(type) {
        case 0:
            actualException = new ClusterBlockException(singleton(DiscoverySettings.NO_MASTER_BLOCK_WRITES));
            expectedException = new ElasticsearchException("Elasticsearch exception [type=cluster_block_exception, " + "reason=blocked by: [SERVICE_UNAVAILABLE/2/no master];]");
            break;
        case 1:
            actualException = new ShardNotFoundException(shard);
            expectedException = new ElasticsearchException("Elasticsearch exception [type=shard_not_found_exception, " + "reason=no such shard]");
            expectedException.setShard(shard);
            break;
        case 2:
            actualException = new IllegalArgumentException("Closed resource", new RuntimeException("Resource"));
            expectedException = new ElasticsearchException("Elasticsearch exception [type=illegal_argument_exception, " + "reason=Closed resource]", new ElasticsearchException("Elasticsearch exception [type=runtime_exception, reason=Resource]"));
            break;
        case 3:
            actualException = new IndexShardRecoveringException(shard);
            expectedException = new ElasticsearchException("Elasticsearch exception [type=index_shard_recovering_exception, " + "reason=CurrentState[RECOVERING] Already recovering]");
            expectedException.setShard(shard);
            break;
        default:
            throw new UnsupportedOperationException("No randomized exceptions generated for type [" + type + "]");
    }
    Failure actual = new Failure(shard, nodeId, actualException, status, primary);
    Failure expected = new Failure(new ShardId(index, INDEX_UUID_NA_VALUE, shardId), nodeId, expectedException, status, primary);
    return Tuple.tuple(actual, expected);
}
Also used : IndexShardRecoveringException(org.elasticsearch.index.shard.IndexShardRecoveringException) ElasticsearchException(org.elasticsearch.ElasticsearchException) ClusterBlockException(org.elasticsearch.cluster.block.ClusterBlockException) ElasticsearchException(org.elasticsearch.ElasticsearchException) IndexShardRecoveringException(org.elasticsearch.index.shard.IndexShardRecoveringException) ShardNotFoundException(org.elasticsearch.index.shard.ShardNotFoundException) ClusterBlockException(org.elasticsearch.cluster.block.ClusterBlockException) IOException(java.io.IOException) ShardId(org.elasticsearch.index.shard.ShardId) RestStatus(org.elasticsearch.rest.RestStatus) ShardNotFoundException(org.elasticsearch.index.shard.ShardNotFoundException) Failure(org.elasticsearch.action.support.replication.ReplicationResponse.ShardInfo.Failure)

Example 18 with RestStatus

use of org.graylog.shaded.elasticsearch7.org.elasticsearch.rest.RestStatus in project elasticsearch by elastic.

the class ReplicationOperation method performOnReplica.

private void performOnReplica(final ShardRouting shard, final ReplicaRequest replicaRequest) {
    if (logger.isTraceEnabled()) {
        logger.trace("[{}] sending op [{}] to replica {} for request [{}]", shard.shardId(), opType, shard, replicaRequest);
    }
    totalShards.incrementAndGet();
    pendingActions.incrementAndGet();
    replicasProxy.performOn(shard, replicaRequest, new ActionListener<ReplicaResponse>() {

        @Override
        public void onResponse(ReplicaResponse response) {
            successfulShards.incrementAndGet();
            primary.updateLocalCheckpointForShard(response.allocationId(), response.localCheckpoint());
            decPendingAndFinishIfNeeded();
        }

        @Override
        public void onFailure(Exception replicaException) {
            logger.trace((org.apache.logging.log4j.util.Supplier<?>) () -> new ParameterizedMessage("[{}] failure while performing [{}] on replica {}, request [{}]", shard.shardId(), opType, shard, replicaRequest), replicaException);
            if (TransportActions.isShardNotAvailableException(replicaException)) {
                decPendingAndFinishIfNeeded();
            } else {
                RestStatus restStatus = ExceptionsHelper.status(replicaException);
                shardReplicaFailures.add(new ReplicationResponse.ShardInfo.Failure(shard.shardId(), shard.currentNodeId(), replicaException, restStatus, false));
                String message = String.format(Locale.ROOT, "failed to perform %s on replica %s", opType, shard);
                replicasProxy.failShardIfNeeded(shard, replicaRequest.primaryTerm(), message, replicaException, ReplicationOperation.this::decPendingAndFinishIfNeeded, ReplicationOperation.this::onPrimaryDemoted, throwable -> decPendingAndFinishIfNeeded());
            }
        }
    });
}
Also used : ElasticsearchException(org.elasticsearch.ElasticsearchException) ShardRouting(org.elasticsearch.cluster.routing.ShardRouting) ShardId(org.elasticsearch.index.shard.ShardId) Nullable(org.elasticsearch.common.Nullable) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) ParameterizedMessage(org.apache.logging.log4j.message.ParameterizedMessage) Supplier(java.util.function.Supplier) TransportActions(org.elasticsearch.action.support.TransportActions) ArrayList(java.util.ArrayList) ClusterState(org.elasticsearch.cluster.ClusterState) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Locale(java.util.Locale) VersionConflictEngineException(org.elasticsearch.index.engine.VersionConflictEngineException) Set(java.util.Set) IndexShardRoutingTable(org.elasticsearch.cluster.routing.IndexShardRoutingTable) IOException(java.io.IOException) Collectors(java.util.stream.Collectors) Sets(org.elasticsearch.common.util.set.Sets) UnavailableShardsException(org.elasticsearch.action.UnavailableShardsException) ActiveShardCount(org.elasticsearch.action.support.ActiveShardCount) Objects(java.util.Objects) Consumer(java.util.function.Consumer) ExceptionsHelper(org.elasticsearch.ExceptionsHelper) List(java.util.List) Logger(org.apache.logging.log4j.Logger) IndexRoutingTable(org.elasticsearch.cluster.routing.IndexRoutingTable) IndexMetaData(org.elasticsearch.cluster.metadata.IndexMetaData) StreamInput(org.elasticsearch.common.io.stream.StreamInput) RestStatus(org.elasticsearch.rest.RestStatus) AllocationId(org.elasticsearch.cluster.routing.AllocationId) Collections(java.util.Collections) ActionListener(org.elasticsearch.action.ActionListener) ElasticsearchException(org.elasticsearch.ElasticsearchException) VersionConflictEngineException(org.elasticsearch.index.engine.VersionConflictEngineException) IOException(java.io.IOException) UnavailableShardsException(org.elasticsearch.action.UnavailableShardsException) RestStatus(org.elasticsearch.rest.RestStatus) Supplier(java.util.function.Supplier) ParameterizedMessage(org.apache.logging.log4j.message.ParameterizedMessage)

Example 19 with RestStatus

use of org.graylog.shaded.elasticsearch7.org.elasticsearch.rest.RestStatus in project elasticsearch by elastic.

the class RestMainAction method convertMainResponse.

static BytesRestResponse convertMainResponse(MainResponse response, RestRequest request, XContentBuilder builder) throws IOException {
    RestStatus status = response.isAvailable() ? RestStatus.OK : RestStatus.SERVICE_UNAVAILABLE;
    // Default to pretty printing, but allow ?pretty=false to disable
    if (request.hasParam("pretty") == false) {
        builder.prettyPrint().lfAtEnd();
    }
    response.toXContent(builder, request);
    return new BytesRestResponse(status, builder);
}
Also used : RestStatus(org.elasticsearch.rest.RestStatus) BytesRestResponse(org.elasticsearch.rest.BytesRestResponse)

Example 20 with RestStatus

use of org.graylog.shaded.elasticsearch7.org.elasticsearch.rest.RestStatus in project elasticsearch by elastic.

the class RestMainActionTests method testHeadResponse.

public void testHeadResponse() throws Exception {
    final String nodeName = "node1";
    final ClusterName clusterName = new ClusterName("cluster1");
    final String clusterUUID = randomAsciiOfLengthBetween(10, 20);
    final boolean available = randomBoolean();
    final RestStatus expectedStatus = available ? RestStatus.OK : RestStatus.SERVICE_UNAVAILABLE;
    final Version version = Version.CURRENT;
    final Build build = Build.CURRENT;
    final MainResponse mainResponse = new MainResponse(nodeName, version, clusterName, clusterUUID, build, available);
    XContentBuilder builder = JsonXContent.contentBuilder();
    RestRequest restRequest = new FakeRestRequest() {

        @Override
        public Method method() {
            return Method.HEAD;
        }
    };
    BytesRestResponse response = RestMainAction.convertMainResponse(mainResponse, restRequest, builder);
    assertNotNull(response);
    assertEquals(expectedStatus, response.status());
// the empty responses are handled in the HTTP layer so we do
// not assert on them here
}
Also used : FakeRestRequest(org.elasticsearch.test.rest.FakeRestRequest) RestRequest(org.elasticsearch.rest.RestRequest) RestStatus(org.elasticsearch.rest.RestStatus) Version(org.elasticsearch.Version) MainResponse(org.elasticsearch.action.main.MainResponse) Build(org.elasticsearch.Build) BytesRestResponse(org.elasticsearch.rest.BytesRestResponse) ClusterName(org.elasticsearch.cluster.ClusterName) FakeRestRequest(org.elasticsearch.test.rest.FakeRestRequest) XContentBuilder(org.elasticsearch.common.xcontent.XContentBuilder)

Aggregations

RestStatus (org.elasticsearch.rest.RestStatus)32 IOException (java.io.IOException)17 ElasticsearchException (org.elasticsearch.ElasticsearchException)12 MainResponse (org.elasticsearch.action.main.MainResponse)11 XContentBuilder (org.elasticsearch.common.xcontent.XContentBuilder)10 Version (org.elasticsearch.Version)9 HttpHost (org.apache.http.HttpHost)8 HttpResponse (org.apache.http.HttpResponse)8 BasicHttpResponse (org.apache.http.message.BasicHttpResponse)8 List (java.util.List)7 HttpEntity (org.apache.http.HttpEntity)7 StringEntity (org.apache.http.entity.StringEntity)7 Build (org.elasticsearch.Build)7 ActionListener (org.elasticsearch.action.ActionListener)7 ClusterName (org.elasticsearch.cluster.ClusterName)7 Collections (java.util.Collections)6 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)6 ActionRequestValidationException (org.elasticsearch.action.ActionRequestValidationException)6 JsonParseException (com.fasterxml.jackson.core.JsonParseException)5 SocketTimeoutException (java.net.SocketTimeoutException)5