Search in sources :

Example 11 with ElasticSearchException

use of org.elasticsearch.ElasticSearchException in project elasticsearch by elastic.

the class TransportReplicationActionTests method testPrimaryReference.

public void testPrimaryReference() throws Exception {
    final IndexShard shard = mock(IndexShard.class);
    final long primaryTerm = 1 + randomInt(200);
    when(shard.getPrimaryTerm()).thenReturn(primaryTerm);
    AtomicBoolean closed = new AtomicBoolean();
    Releasable releasable = () -> {
        if (closed.compareAndSet(false, true) == false) {
            fail("releasable is closed twice");
        }
    };
    TestAction.PrimaryShardReference primary = action.new PrimaryShardReference(shard, releasable);
    final Request request = new Request();
    Request replicaRequest = (Request) primary.perform(request).replicaRequest;
    assertThat(replicaRequest.primaryTerm(), equalTo(primaryTerm));
    final ElasticsearchException exception = new ElasticsearchException("testing");
    primary.failShard("test", exception);
    verify(shard).failShard("test", exception);
    primary.close();
    assertTrue(closed.get());
}
Also used : AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) IndexShard(org.elasticsearch.index.shard.IndexShard) TransportRequest(org.elasticsearch.transport.TransportRequest) CloseIndexRequest(org.elasticsearch.action.admin.indices.close.CloseIndexRequest) Releasable(org.elasticsearch.common.lease.Releasable) ElasticsearchException(org.elasticsearch.ElasticsearchException)

Example 12 with ElasticSearchException

use of org.elasticsearch.ElasticSearchException in project elasticsearch by elastic.

the class TransportWriteActionTests method testReplicaProxy.

public void testReplicaProxy() throws InterruptedException, ExecutionException {
    CapturingTransport transport = new CapturingTransport();
    TransportService transportService = new TransportService(clusterService.getSettings(), transport, threadPool, TransportService.NOOP_TRANSPORT_INTERCEPTOR, x -> clusterService.localNode(), null);
    transportService.start();
    transportService.acceptIncomingRequests();
    ShardStateAction shardStateAction = new ShardStateAction(Settings.EMPTY, clusterService, transportService, null, null, threadPool);
    TestAction action = action = new TestAction(Settings.EMPTY, "testAction", transportService, clusterService, shardStateAction, threadPool);
    ReplicationOperation.Replicas proxy = action.newReplicasProxy();
    final String index = "test";
    final ShardId shardId = new ShardId(index, "_na_", 0);
    ClusterState state = ClusterStateCreationUtils.stateWithActivePrimary(index, true, 1 + randomInt(3), randomInt(2));
    logger.info("using state: {}", state);
    ClusterServiceUtils.setState(clusterService, state);
    // check that at unknown node fails
    PlainActionFuture<ReplicaResponse> listener = new PlainActionFuture<>();
    proxy.performOn(TestShardRouting.newShardRouting(shardId, "NOT THERE", false, randomFrom(ShardRoutingState.values())), new TestRequest(), listener);
    assertTrue(listener.isDone());
    assertListenerThrows("non existent node should throw a NoNodeAvailableException", listener, NoNodeAvailableException.class);
    final IndexShardRoutingTable shardRoutings = state.routingTable().shardRoutingTable(shardId);
    final ShardRouting replica = randomFrom(shardRoutings.replicaShards().stream().filter(ShardRouting::assignedToNode).collect(Collectors.toList()));
    listener = new PlainActionFuture<>();
    proxy.performOn(replica, new TestRequest(), listener);
    assertFalse(listener.isDone());
    CapturingTransport.CapturedRequest[] captures = transport.getCapturedRequestsAndClear();
    assertThat(captures, arrayWithSize(1));
    if (randomBoolean()) {
        final TransportReplicationAction.ReplicaResponse response = new TransportReplicationAction.ReplicaResponse(randomAsciiOfLength(10), randomLong());
        transport.handleResponse(captures[0].requestId, response);
        assertTrue(listener.isDone());
        assertThat(listener.get(), equalTo(response));
    } else if (randomBoolean()) {
        transport.handleRemoteError(captures[0].requestId, new ElasticsearchException("simulated"));
        assertTrue(listener.isDone());
        assertListenerThrows("listener should reflect remote error", listener, ElasticsearchException.class);
    } else {
        transport.handleError(captures[0].requestId, new TransportException("simulated"));
        assertTrue(listener.isDone());
        assertListenerThrows("listener should reflect remote error", listener, TransportException.class);
    }
    AtomicReference<Object> failure = new AtomicReference<>();
    AtomicReference<Object> ignoredFailure = new AtomicReference<>();
    AtomicBoolean success = new AtomicBoolean();
    proxy.failShardIfNeeded(replica, randomIntBetween(1, 10), "test", new ElasticsearchException("simulated"), () -> success.set(true), failure::set, ignoredFailure::set);
    CapturingTransport.CapturedRequest[] shardFailedRequests = transport.getCapturedRequestsAndClear();
    // A write replication action proxy should fail the shard
    assertEquals(1, shardFailedRequests.length);
    CapturingTransport.CapturedRequest shardFailedRequest = shardFailedRequests[0];
    ShardStateAction.ShardEntry shardEntry = (ShardStateAction.ShardEntry) shardFailedRequest.request;
    // the shard the request was sent to and the shard to be failed should be the same
    assertEquals(shardEntry.getShardId(), replica.shardId());
    assertEquals(shardEntry.getAllocationId(), replica.allocationId().getId());
    if (randomBoolean()) {
        // simulate success
        transport.handleResponse(shardFailedRequest.requestId, TransportResponse.Empty.INSTANCE);
        assertTrue(success.get());
        assertNull(failure.get());
        assertNull(ignoredFailure.get());
    } else if (randomBoolean()) {
        // simulate the primary has been demoted
        transport.handleRemoteError(shardFailedRequest.requestId, new ShardStateAction.NoLongerPrimaryShardException(replica.shardId(), "shard-failed-test"));
        assertFalse(success.get());
        assertNotNull(failure.get());
        assertNull(ignoredFailure.get());
    } else {
        // simulated an "ignored" exception
        transport.handleRemoteError(shardFailedRequest.requestId, new NodeClosedException(state.nodes().getLocalNode()));
        assertFalse(success.get());
        assertNull(failure.get());
        assertNotNull(ignoredFailure.get());
    }
}
Also used : IndexShardRoutingTable(org.elasticsearch.cluster.routing.IndexShardRoutingTable) ShardStateAction(org.elasticsearch.cluster.action.shard.ShardStateAction) Matchers.anyString(org.mockito.Matchers.anyString) ElasticsearchException(org.elasticsearch.ElasticsearchException) ShardId(org.elasticsearch.index.shard.ShardId) NodeClosedException(org.elasticsearch.node.NodeClosedException) ReplicationOperation(org.elasticsearch.action.support.replication.ReplicationOperation) ClusterState(org.elasticsearch.cluster.ClusterState) CapturingTransport(org.elasticsearch.test.transport.CapturingTransport) AtomicReference(java.util.concurrent.atomic.AtomicReference) TransportException(org.elasticsearch.transport.TransportException) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) TransportService(org.elasticsearch.transport.TransportService) PlainActionFuture(org.elasticsearch.action.support.PlainActionFuture) ReplicaResponse(org.elasticsearch.action.support.replication.ReplicationOperation.ReplicaResponse) TestShardRouting(org.elasticsearch.cluster.routing.TestShardRouting) ShardRouting(org.elasticsearch.cluster.routing.ShardRouting)

Example 13 with ElasticSearchException

use of org.elasticsearch.ElasticSearchException in project elasticsearch by elastic.

the class BytesRestResponseTests method testErrorToAndFromXContent.

public void testErrorToAndFromXContent() throws IOException {
    final boolean detailed = randomBoolean();
    Exception original;
    ElasticsearchException cause = null;
    String reason;
    String type = "exception";
    RestStatus status = RestStatus.INTERNAL_SERVER_ERROR;
    boolean addHeadersOrMetadata = false;
    switch(randomIntBetween(0, 5)) {
        case 0:
            original = new ElasticsearchException("ElasticsearchException without cause");
            if (detailed) {
                addHeadersOrMetadata = randomBoolean();
                reason = "ElasticsearchException without cause";
            } else {
                reason = "ElasticsearchException[ElasticsearchException without cause]";
            }
            break;
        case 1:
            original = new ElasticsearchException("ElasticsearchException with a cause", new FileNotFoundException("missing"));
            if (detailed) {
                addHeadersOrMetadata = randomBoolean();
                type = "exception";
                reason = "ElasticsearchException with a cause";
                cause = new ElasticsearchException("Elasticsearch exception [type=file_not_found_exception, reason=missing]");
            } else {
                reason = "ElasticsearchException[ElasticsearchException with a cause]";
            }
            break;
        case 2:
            original = new ResourceNotFoundException("ElasticsearchException with custom status");
            status = RestStatus.NOT_FOUND;
            if (detailed) {
                addHeadersOrMetadata = randomBoolean();
                type = "resource_not_found_exception";
                reason = "ElasticsearchException with custom status";
            } else {
                reason = "ResourceNotFoundException[ElasticsearchException with custom status]";
            }
            break;
        case 3:
            TransportAddress address = buildNewFakeTransportAddress();
            original = new RemoteTransportException("remote", address, "action", new ResourceAlreadyExistsException("ElasticsearchWrapperException with a cause that has a custom status"));
            status = RestStatus.BAD_REQUEST;
            if (detailed) {
                type = "resource_already_exists_exception";
                reason = "ElasticsearchWrapperException with a cause that has a custom status";
            } else {
                reason = "RemoteTransportException[[remote][" + address.toString() + "][action]]";
            }
            break;
        case 4:
            original = new RemoteTransportException("ElasticsearchWrapperException with a cause that has a special treatment", new IllegalArgumentException("wrong"));
            status = RestStatus.BAD_REQUEST;
            if (detailed) {
                type = "illegal_argument_exception";
                reason = "wrong";
            } else {
                reason = "RemoteTransportException[[ElasticsearchWrapperException with a cause that has a special treatment]]";
            }
            break;
        case 5:
            status = randomFrom(RestStatus.values());
            original = new ElasticsearchStatusException("ElasticsearchStatusException with random status", status);
            if (detailed) {
                addHeadersOrMetadata = randomBoolean();
                type = "status_exception";
                reason = "ElasticsearchStatusException with random status";
            } else {
                reason = "ElasticsearchStatusException[ElasticsearchStatusException with random status]";
            }
            break;
        default:
            throw new UnsupportedOperationException("Failed to generate random exception");
    }
    String message = "Elasticsearch exception [type=" + type + ", reason=" + reason + "]";
    ElasticsearchStatusException expected = new ElasticsearchStatusException(message, status, cause);
    if (addHeadersOrMetadata) {
        ElasticsearchException originalException = ((ElasticsearchException) original);
        if (randomBoolean()) {
            originalException.addHeader("foo", "bar", "baz");
            expected.addHeader("foo", "bar", "baz");
        }
        if (randomBoolean()) {
            originalException.addMetadata("es.metadata_0", "0");
            expected.addMetadata("es.metadata_0", "0");
        }
        if (randomBoolean()) {
            String resourceType = randomAsciiOfLength(5);
            String resourceId = randomAsciiOfLength(5);
            originalException.setResources(resourceType, resourceId);
            expected.setResources(resourceType, resourceId);
        }
        if (randomBoolean()) {
            originalException.setIndex("_index");
            expected.setIndex("_index");
        }
    }
    final XContentType xContentType = randomFrom(XContentType.values());
    Map<String, String> params = Collections.singletonMap("format", xContentType.mediaType());
    RestRequest request = new FakeRestRequest.Builder(xContentRegistry()).withParams(params).build();
    RestChannel channel = detailed ? new DetailedExceptionRestChannel(request) : new SimpleExceptionRestChannel(request);
    BytesRestResponse response = new BytesRestResponse(channel, original);
    ElasticsearchException parsedError;
    try (XContentParser parser = createParser(xContentType.xContent(), response.content())) {
        parsedError = BytesRestResponse.errorFromXContent(parser);
        assertNull(parser.nextToken());
    }
    assertEquals(expected.status(), parsedError.status());
    assertDeepEquals(expected, parsedError);
}
Also used : RemoteTransportException(org.elasticsearch.transport.RemoteTransportException) TransportAddress(org.elasticsearch.common.transport.TransportAddress) XContentBuilder(org.elasticsearch.common.xcontent.XContentBuilder) FileNotFoundException(java.io.FileNotFoundException) ResourceAlreadyExistsException(org.elasticsearch.ResourceAlreadyExistsException) ElasticsearchException(org.elasticsearch.ElasticsearchException) Matchers.containsString(org.hamcrest.Matchers.containsString) ElasticsearchException(org.elasticsearch.ElasticsearchException) ParsingException(org.elasticsearch.common.ParsingException) ResourceAlreadyExistsException(org.elasticsearch.ResourceAlreadyExistsException) ElasticsearchStatusException(org.elasticsearch.ElasticsearchStatusException) ResourceNotFoundException(org.elasticsearch.ResourceNotFoundException) IOException(java.io.IOException) FileNotFoundException(java.io.FileNotFoundException) SearchPhaseExecutionException(org.elasticsearch.action.search.SearchPhaseExecutionException) RemoteTransportException(org.elasticsearch.transport.RemoteTransportException) ElasticsearchStatusException(org.elasticsearch.ElasticsearchStatusException) XContentType(org.elasticsearch.common.xcontent.XContentType) FakeRestRequest(org.elasticsearch.test.rest.FakeRestRequest) ResourceNotFoundException(org.elasticsearch.ResourceNotFoundException) XContentParser(org.elasticsearch.common.xcontent.XContentParser)

Example 14 with ElasticSearchException

use of org.elasticsearch.ElasticSearchException in project elasticsearch by elastic.

the class BytesRestResponseTests method testNonElasticsearchExceptionIsNotShownAsSimpleMessage.

public void testNonElasticsearchExceptionIsNotShownAsSimpleMessage() throws Exception {
    RestRequest request = new FakeRestRequest();
    RestChannel channel = new SimpleExceptionRestChannel(request);
    Exception t = new UnknownException("an error occurred reading data", new FileNotFoundException("/foo/bar"));
    BytesRestResponse response = new BytesRestResponse(channel, t);
    String text = response.content().utf8ToString();
    assertThat(text, not(containsString("UnknownException[an error occurred reading data]")));
    assertThat(text, not(containsString("FileNotFoundException[/foo/bar]")));
    assertThat(text, not(containsString("error_trace")));
    assertThat(text, containsString("\"error\":\"No ElasticsearchException found\""));
}
Also used : FakeRestRequest(org.elasticsearch.test.rest.FakeRestRequest) FileNotFoundException(java.io.FileNotFoundException) Matchers.containsString(org.hamcrest.Matchers.containsString) FakeRestRequest(org.elasticsearch.test.rest.FakeRestRequest) ElasticsearchException(org.elasticsearch.ElasticsearchException) ParsingException(org.elasticsearch.common.ParsingException) ResourceAlreadyExistsException(org.elasticsearch.ResourceAlreadyExistsException) ElasticsearchStatusException(org.elasticsearch.ElasticsearchStatusException) ResourceNotFoundException(org.elasticsearch.ResourceNotFoundException) IOException(java.io.IOException) FileNotFoundException(java.io.FileNotFoundException) SearchPhaseExecutionException(org.elasticsearch.action.search.SearchPhaseExecutionException) RemoteTransportException(org.elasticsearch.transport.RemoteTransportException)

Example 15 with ElasticSearchException

use of org.elasticsearch.ElasticSearchException in project elasticsearch by elastic.

the class BytesRestResponseTests method testGuessRootCause.

public void testGuessRootCause() throws IOException {
    RestRequest request = new FakeRestRequest();
    RestChannel channel = new DetailedExceptionRestChannel(request);
    {
        Exception e = new ElasticsearchException("an error occurred reading data", new FileNotFoundException("/foo/bar"));
        BytesRestResponse response = new BytesRestResponse(channel, e);
        String text = response.content().utf8ToString();
        assertThat(text, containsString("{\"root_cause\":[{\"type\":\"exception\",\"reason\":\"an error occurred reading data\"}]"));
    }
    {
        Exception e = new FileNotFoundException("/foo/bar");
        BytesRestResponse response = new BytesRestResponse(channel, e);
        String text = response.content().utf8ToString();
        assertThat(text, containsString("{\"root_cause\":[{\"type\":\"file_not_found_exception\",\"reason\":\"/foo/bar\"}]"));
    }
}
Also used : FakeRestRequest(org.elasticsearch.test.rest.FakeRestRequest) FileNotFoundException(java.io.FileNotFoundException) ElasticsearchException(org.elasticsearch.ElasticsearchException) Matchers.containsString(org.hamcrest.Matchers.containsString) FakeRestRequest(org.elasticsearch.test.rest.FakeRestRequest) ElasticsearchException(org.elasticsearch.ElasticsearchException) ParsingException(org.elasticsearch.common.ParsingException) ResourceAlreadyExistsException(org.elasticsearch.ResourceAlreadyExistsException) ElasticsearchStatusException(org.elasticsearch.ElasticsearchStatusException) ResourceNotFoundException(org.elasticsearch.ResourceNotFoundException) IOException(java.io.IOException) FileNotFoundException(java.io.FileNotFoundException) SearchPhaseExecutionException(org.elasticsearch.action.search.SearchPhaseExecutionException) RemoteTransportException(org.elasticsearch.transport.RemoteTransportException)

Aggregations

ElasticsearchException (org.elasticsearch.ElasticsearchException)309 IOException (java.io.IOException)127 Settings (org.elasticsearch.common.settings.Settings)32 XContentBuilder (org.elasticsearch.common.xcontent.XContentBuilder)30 HashMap (java.util.HashMap)29 ClusterState (org.elasticsearch.cluster.ClusterState)29 ArrayList (java.util.ArrayList)28 Matchers.containsString (org.hamcrest.Matchers.containsString)25 List (java.util.List)20 Map (java.util.Map)20 AtomicReference (java.util.concurrent.atomic.AtomicReference)20 ParameterizedMessage (org.apache.logging.log4j.message.ParameterizedMessage)18 XContentParser (org.elasticsearch.common.xcontent.XContentParser)17 Path (java.nio.file.Path)16 Test (org.junit.Test)16 ActionListener (org.elasticsearch.action.ActionListener)15 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)14 Version (org.elasticsearch.Version)14 AtomicBoolean (java.util.concurrent.atomic.AtomicBoolean)13 ResourceNotFoundException (org.elasticsearch.ResourceNotFoundException)13