Search in sources :

Example 26 with IndexShard

use of org.elasticsearch.index.shard.IndexShard in project elasticsearch by elastic.

the class TransportReplicationActionTests method mockIndexShard.

private IndexShard mockIndexShard(ShardId shardId, ClusterService clusterService) {
    final IndexShard indexShard = mock(IndexShard.class);
    doAnswer(invocation -> {
        ActionListener<Releasable> callback = (ActionListener<Releasable>) invocation.getArguments()[0];
        count.incrementAndGet();
        callback.onResponse(count::decrementAndGet);
        return null;
    }).when(indexShard).acquirePrimaryOperationLock(any(ActionListener.class), anyString());
    doAnswer(invocation -> {
        long term = (Long) invocation.getArguments()[0];
        ActionListener<Releasable> callback = (ActionListener<Releasable>) invocation.getArguments()[1];
        final long primaryTerm = indexShard.getPrimaryTerm();
        if (term < primaryTerm) {
            throw new IllegalArgumentException(String.format(Locale.ROOT, "%s operation term [%d] is too old (current [%d])", shardId, term, primaryTerm));
        }
        count.incrementAndGet();
        callback.onResponse(count::decrementAndGet);
        return null;
    }).when(indexShard).acquireReplicaOperationLock(anyLong(), any(ActionListener.class), anyString());
    when(indexShard.routingEntry()).thenAnswer(invocationOnMock -> {
        final ClusterState state = clusterService.state();
        final RoutingNode node = state.getRoutingNodes().node(state.nodes().getLocalNodeId());
        final ShardRouting routing = node.getByShardId(shardId);
        if (routing == null) {
            throw new ShardNotFoundException(shardId, "shard is no longer assigned to current node");
        }
        return routing;
    });
    when(indexShard.state()).thenAnswer(invocationOnMock -> isRelocated.get() ? IndexShardState.RELOCATED : IndexShardState.STARTED);
    doThrow(new AssertionError("failed shard is not supported")).when(indexShard).failShard(anyString(), any(Exception.class));
    when(indexShard.getPrimaryTerm()).thenAnswer(i -> clusterService.state().metaData().getIndexSafe(shardId.getIndex()).primaryTerm(shardId.id()));
    return indexShard;
}
Also used : ClusterState(org.elasticsearch.cluster.ClusterState) IndexShard(org.elasticsearch.index.shard.IndexShard) ElasticsearchException(org.elasticsearch.ElasticsearchException) AlreadyClosedException(org.apache.lucene.store.AlreadyClosedException) IndexClosedException(org.elasticsearch.indices.IndexClosedException) NodeClosedException(org.elasticsearch.node.NodeClosedException) ShardNotFoundException(org.elasticsearch.index.shard.ShardNotFoundException) IndexNotFoundException(org.elasticsearch.index.IndexNotFoundException) NoNodeAvailableException(org.elasticsearch.client.transport.NoNodeAvailableException) TransportException(org.elasticsearch.transport.TransportException) IndexShardClosedException(org.elasticsearch.index.shard.IndexShardClosedException) ClusterBlockException(org.elasticsearch.cluster.block.ClusterBlockException) IOException(java.io.IOException) UnavailableShardsException(org.elasticsearch.action.UnavailableShardsException) ExecutionException(java.util.concurrent.ExecutionException) ActionListener(org.elasticsearch.action.ActionListener) RoutingNode(org.elasticsearch.cluster.routing.RoutingNode) ShardNotFoundException(org.elasticsearch.index.shard.ShardNotFoundException) Matchers.anyLong(org.mockito.Matchers.anyLong) Releasable(org.elasticsearch.common.lease.Releasable) TestShardRouting(org.elasticsearch.cluster.routing.TestShardRouting) ShardRouting(org.elasticsearch.cluster.routing.ShardRouting)

Example 27 with IndexShard

use of org.elasticsearch.index.shard.IndexShard 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 28 with IndexShard

use of org.elasticsearch.index.shard.IndexShard in project elasticsearch by elastic.

the class TransportReplicationActionTests method testRetryOnReplica.

/**
     * test throwing a {@link org.elasticsearch.action.support.replication.TransportReplicationAction.RetryOnReplicaException}
     * causes a retry
     */
public void testRetryOnReplica() throws Exception {
    final ShardId shardId = new ShardId("test", "_na_", 0);
    ClusterState state = state(shardId.getIndexName(), true, ShardRoutingState.STARTED, ShardRoutingState.STARTED);
    final ShardRouting replica = state.getRoutingTable().shardRoutingTable(shardId).replicaShards().get(0);
    // simulate execution of the node holding the replica
    state = ClusterState.builder(state).nodes(DiscoveryNodes.builder(state.nodes()).localNodeId(replica.currentNodeId())).build();
    setState(clusterService, state);
    AtomicBoolean throwException = new AtomicBoolean(true);
    final ReplicationTask task = maybeTask();
    TestAction action = new TestAction(Settings.EMPTY, "testActionWithExceptions", transportService, clusterService, shardStateAction, threadPool) {

        @Override
        protected ReplicaResult shardOperationOnReplica(Request request, IndexShard replica) {
            assertPhase(task, "replica");
            if (throwException.get()) {
                throw new RetryOnReplicaException(shardId, "simulation");
            }
            return new ReplicaResult();
        }
    };
    final TestAction.ReplicaOperationTransportHandler replicaOperationTransportHandler = action.new ReplicaOperationTransportHandler();
    final PlainActionFuture<TestResponse> listener = new PlainActionFuture<>();
    final Request request = new Request().setShardId(shardId);
    request.primaryTerm(state.metaData().getIndexSafe(shardId.getIndex()).primaryTerm(shardId.id()));
    replicaOperationTransportHandler.messageReceived(new TransportReplicationAction.ConcreteShardRequest<>(request, replica.allocationId().getId()), createTransportChannel(listener), task);
    if (listener.isDone()) {
        // fail with the exception if there
        listener.get();
        fail("listener shouldn't be done");
    }
    // no retry yet
    List<CapturingTransport.CapturedRequest> capturedRequests = transport.getCapturedRequestsByTargetNodeAndClear().get(replica.currentNodeId());
    assertThat(capturedRequests, nullValue());
    // release the waiting
    throwException.set(false);
    setState(clusterService, state);
    capturedRequests = transport.getCapturedRequestsByTargetNodeAndClear().get(replica.currentNodeId());
    assertThat(capturedRequests, notNullValue());
    assertThat(capturedRequests.size(), equalTo(1));
    final CapturingTransport.CapturedRequest capturedRequest = capturedRequests.get(0);
    assertThat(capturedRequest.action, equalTo("testActionWithExceptions[r]"));
    assertThat(capturedRequest.request, instanceOf(TransportReplicationAction.ConcreteShardRequest.class));
    assertConcreteShardRequest(capturedRequest.request, request, replica.allocationId());
}
Also used : ClusterState(org.elasticsearch.cluster.ClusterState) IndexShard(org.elasticsearch.index.shard.IndexShard) CapturingTransport(org.elasticsearch.test.transport.CapturingTransport) TransportRequest(org.elasticsearch.transport.TransportRequest) CloseIndexRequest(org.elasticsearch.action.admin.indices.close.CloseIndexRequest) ShardId(org.elasticsearch.index.shard.ShardId) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) PlainActionFuture(org.elasticsearch.action.support.PlainActionFuture) TestShardRouting(org.elasticsearch.cluster.routing.TestShardRouting) ShardRouting(org.elasticsearch.cluster.routing.ShardRouting)

Example 29 with IndexShard

use of org.elasticsearch.index.shard.IndexShard in project elasticsearch by elastic.

the class TransportWriteActionTests method mockIndexShard.

private IndexShard mockIndexShard(ShardId shardId, ClusterService clusterService) {
    final IndexShard indexShard = mock(IndexShard.class);
    doAnswer(invocation -> {
        ActionListener<Releasable> callback = (ActionListener<Releasable>) invocation.getArguments()[0];
        count.incrementAndGet();
        callback.onResponse(count::decrementAndGet);
        return null;
    }).when(indexShard).acquirePrimaryOperationLock(any(ActionListener.class), anyString());
    doAnswer(invocation -> {
        long term = (Long) invocation.getArguments()[0];
        ActionListener<Releasable> callback = (ActionListener<Releasable>) invocation.getArguments()[1];
        final long primaryTerm = indexShard.getPrimaryTerm();
        if (term < primaryTerm) {
            throw new IllegalArgumentException(String.format(Locale.ROOT, "%s operation term [%d] is too old (current [%d])", shardId, term, primaryTerm));
        }
        count.incrementAndGet();
        callback.onResponse(count::decrementAndGet);
        return null;
    }).when(indexShard).acquireReplicaOperationLock(anyLong(), any(ActionListener.class), anyString());
    when(indexShard.routingEntry()).thenAnswer(invocationOnMock -> {
        final ClusterState state = clusterService.state();
        final RoutingNode node = state.getRoutingNodes().node(state.nodes().getLocalNodeId());
        final ShardRouting routing = node.getByShardId(shardId);
        if (routing == null) {
            throw new ShardNotFoundException(shardId, "shard is no longer assigned to current node");
        }
        return routing;
    });
    when(indexShard.state()).thenAnswer(invocationOnMock -> isRelocated.get() ? IndexShardState.RELOCATED : IndexShardState.STARTED);
    doThrow(new AssertionError("failed shard is not supported")).when(indexShard).failShard(anyString(), any(Exception.class));
    when(indexShard.getPrimaryTerm()).thenAnswer(i -> clusterService.state().metaData().getIndexSafe(shardId.getIndex()).primaryTerm(shardId.id()));
    return indexShard;
}
Also used : ClusterState(org.elasticsearch.cluster.ClusterState) IndexShard(org.elasticsearch.index.shard.IndexShard) ElasticsearchException(org.elasticsearch.ElasticsearchException) NodeClosedException(org.elasticsearch.node.NodeClosedException) ShardNotFoundException(org.elasticsearch.index.shard.ShardNotFoundException) NoNodeAvailableException(org.elasticsearch.client.transport.NoNodeAvailableException) TransportException(org.elasticsearch.transport.TransportException) ExecutionException(java.util.concurrent.ExecutionException) ActionListener(org.elasticsearch.action.ActionListener) RoutingNode(org.elasticsearch.cluster.routing.RoutingNode) ShardNotFoundException(org.elasticsearch.index.shard.ShardNotFoundException) Matchers.anyLong(org.mockito.Matchers.anyLong) Releasable(org.elasticsearch.common.lease.Releasable) TestShardRouting(org.elasticsearch.cluster.routing.TestShardRouting) ShardRouting(org.elasticsearch.cluster.routing.ShardRouting)

Example 30 with IndexShard

use of org.elasticsearch.index.shard.IndexShard in project elasticsearch by elastic.

the class SyncedFlushSingleNodeTests method testModificationPreventsFlushing.

public void testModificationPreventsFlushing() throws InterruptedException {
    createIndex("test");
    client().prepareIndex("test", "test", "1").setSource("{}", XContentType.JSON).get();
    IndexService test = getInstanceFromNode(IndicesService.class).indexService(resolveIndex("test"));
    IndexShard shard = test.getShardOrNull(0);
    SyncedFlushService flushService = getInstanceFromNode(SyncedFlushService.class);
    final ShardId shardId = shard.shardId();
    final ClusterState state = getInstanceFromNode(ClusterService.class).state();
    final IndexShardRoutingTable shardRoutingTable = flushService.getShardRoutingTable(shardId, state);
    final List<ShardRouting> activeShards = shardRoutingTable.activeShards();
    assertEquals("exactly one active shard", 1, activeShards.size());
    Map<String, Engine.CommitId> commitIds = SyncedFlushUtil.sendPreSyncRequests(flushService, activeShards, state, shardId);
    assertEquals("exactly one commit id", 1, commitIds.size());
    client().prepareIndex("test", "test", "2").setSource("{}", XContentType.JSON).get();
    String syncId = UUIDs.base64UUID();
    SyncedFlushUtil.LatchedListener<ShardsSyncedFlushResult> listener = new SyncedFlushUtil.LatchedListener<>();
    flushService.sendSyncRequests(syncId, activeShards, state, commitIds, shardId, shardRoutingTable.size(), listener);
    listener.latch.await();
    assertNull(listener.error);
    ShardsSyncedFlushResult syncedFlushResult = listener.result;
    assertNotNull(syncedFlushResult);
    assertEquals(0, syncedFlushResult.successfulShards());
    assertEquals(1, syncedFlushResult.totalShards());
    assertEquals(syncId, syncedFlushResult.syncId());
    assertNotNull(syncedFlushResult.shardResponses().get(activeShards.get(0)));
    assertFalse(syncedFlushResult.shardResponses().get(activeShards.get(0)).success());
    assertEquals("pending operations", syncedFlushResult.shardResponses().get(activeShards.get(0)).failureReason());
    // pull another commit and make sure we can't sync-flush with the old one
    SyncedFlushUtil.sendPreSyncRequests(flushService, activeShards, state, shardId);
    listener = new SyncedFlushUtil.LatchedListener();
    flushService.sendSyncRequests(syncId, activeShards, state, commitIds, shardId, shardRoutingTable.size(), listener);
    listener.latch.await();
    assertNull(listener.error);
    syncedFlushResult = listener.result;
    assertNotNull(syncedFlushResult);
    assertEquals(0, syncedFlushResult.successfulShards());
    assertEquals(1, syncedFlushResult.totalShards());
    assertEquals(syncId, syncedFlushResult.syncId());
    assertNotNull(syncedFlushResult.shardResponses().get(activeShards.get(0)));
    assertFalse(syncedFlushResult.shardResponses().get(activeShards.get(0)).success());
    assertEquals("commit has changed", syncedFlushResult.shardResponses().get(activeShards.get(0)).failureReason());
}
Also used : ClusterState(org.elasticsearch.cluster.ClusterState) IndexShardRoutingTable(org.elasticsearch.cluster.routing.IndexShardRoutingTable) IndexService(org.elasticsearch.index.IndexService) IndexShard(org.elasticsearch.index.shard.IndexShard) IndicesService(org.elasticsearch.indices.IndicesService) ShardId(org.elasticsearch.index.shard.ShardId) ClusterService(org.elasticsearch.cluster.service.ClusterService) ShardRouting(org.elasticsearch.cluster.routing.ShardRouting)

Aggregations

IndexShard (org.elasticsearch.index.shard.IndexShard)94 IndexService (org.elasticsearch.index.IndexService)51 IndicesService (org.elasticsearch.indices.IndicesService)20 ShardRouting (org.elasticsearch.cluster.routing.ShardRouting)19 ShardId (org.elasticsearch.index.shard.ShardId)19 IOException (java.io.IOException)16 Engine (org.elasticsearch.index.engine.Engine)16 ElasticsearchException (org.elasticsearch.ElasticsearchException)13 IndexMetaData (org.elasticsearch.cluster.metadata.IndexMetaData)13 Settings (org.elasticsearch.common.settings.Settings)11 Translog (org.elasticsearch.index.translog.Translog)10 AtomicBoolean (java.util.concurrent.atomic.AtomicBoolean)9 HashMap (java.util.HashMap)8 IndexRequest (org.elasticsearch.action.index.IndexRequest)8 DiscoveryNode (org.elasticsearch.cluster.node.DiscoveryNode)8 ClusterState (org.elasticsearch.cluster.ClusterState)7 Releasable (org.elasticsearch.common.lease.Releasable)7 ClusterService (org.elasticsearch.cluster.service.ClusterService)6 Path (java.nio.file.Path)5 ArrayList (java.util.ArrayList)5