Search in sources :

Example 21 with ReplicationResponse

use of org.elasticsearch.action.support.replication.ReplicationResponse in project crate by crate.

the class RetentionLeaseSyncAction method shardOperationOnPrimary.

@Override
protected void shardOperationOnPrimary(Request request, IndexShard primary, ActionListener<PrimaryResult<Request, ReplicationResponse>> listener) {
    ActionListener.completeWith(listener, () -> {
        assert request.waitForActiveShards().equals(ActiveShardCount.NONE) : request.waitForActiveShards();
        Objects.requireNonNull(request);
        Objects.requireNonNull(primary);
        primary.persistRetentionLeases();
        return new WritePrimaryResult<>(request, new ReplicationResponse(), null, null, primary);
    });
}
Also used : ReplicationResponse(org.elasticsearch.action.support.replication.ReplicationResponse)

Example 22 with ReplicationResponse

use of org.elasticsearch.action.support.replication.ReplicationResponse in project crate by crate.

the class PrimaryReplicaSyncerTests method testSyncerOnClosingShard.

public void testSyncerOnClosingShard() throws Exception {
    IndexShard shard = newStartedShard(true);
    AtomicBoolean syncActionCalled = new AtomicBoolean();
    PrimaryReplicaSyncer.SyncAction syncAction = (request, allocationId, primaryTerm, listener) -> {
        logger.info("Sending off {} operations", request.getOperations().length);
        syncActionCalled.set(true);
        threadPool.generic().execute(() -> listener.onResponse(new ReplicationResponse()));
    };
    PrimaryReplicaSyncer syncer = new PrimaryReplicaSyncer(syncAction);
    // every document is sent off separately
    syncer.setChunkSize(new ByteSizeValue(1));
    int numDocs = 10;
    for (int i = 0; i < numDocs; i++) {
        // Index doc but not advance local checkpoint.
        shard.applyIndexOperationOnPrimary(Versions.MATCH_ANY, VersionType.INTERNAL, new SourceToParse(shard.shardId().getIndexName(), Integer.toString(i), new BytesArray("{}"), XContentType.JSON), SequenceNumbers.UNASSIGNED_SEQ_NO, 0, -1L, false);
    }
    String allocationId = shard.routingEntry().allocationId().getId();
    shard.updateShardState(shard.routingEntry(), shard.getPendingPrimaryTerm(), null, 1000L, Collections.singleton(allocationId), new IndexShardRoutingTable.Builder(shard.shardId()).addShard(shard.routingEntry()).build());
    CountDownLatch syncCalledLatch = new CountDownLatch(1);
    PlainActionFuture<PrimaryReplicaSyncer.ResyncTask> fut = new PlainActionFuture<PrimaryReplicaSyncer.ResyncTask>() {

        @Override
        public void onFailure(Exception e) {
            try {
                super.onFailure(e);
            } finally {
                syncCalledLatch.countDown();
            }
        }

        @Override
        public void onResponse(PrimaryReplicaSyncer.ResyncTask result) {
            try {
                super.onResponse(result);
            } finally {
                syncCalledLatch.countDown();
            }
        }
    };
    threadPool.generic().execute(() -> {
        syncer.resync(shard, fut);
    });
    if (randomBoolean()) {
        syncCalledLatch.await();
    }
    closeShards(shard);
    try {
        fut.actionGet();
        assertTrue("Sync action was not called", syncActionCalled.get());
    } catch (AlreadyClosedException | IndexShardClosedException ignored) {
    // ignore
    }
}
Also used : Arrays(java.util.Arrays) Versions(org.elasticsearch.common.lucene.uid.Versions) IsInstanceOf.instanceOf(org.hamcrest.core.IsInstanceOf.instanceOf) XContentType(org.elasticsearch.common.xcontent.XContentType) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) AlreadyClosedException(org.apache.lucene.store.AlreadyClosedException) VersionType(org.elasticsearch.index.VersionType) Matchers.anyString(org.mockito.Matchers.anyString) ArrayList(java.util.ArrayList) BytesArray(org.elasticsearch.common.bytes.BytesArray) Settings(org.elasticsearch.common.settings.Settings) Matchers.eq(org.mockito.Matchers.eq) Matchers.anyLong(org.mockito.Matchers.anyLong) TestTranslog(org.elasticsearch.index.translog.TestTranslog) Mockito.doReturn(org.mockito.Mockito.doReturn) SourceToParse(org.elasticsearch.index.mapper.SourceToParse) ByteSizeValue(org.elasticsearch.common.unit.ByteSizeValue) SequenceNumbers(org.elasticsearch.index.seqno.SequenceNumbers) PlainActionFuture(org.elasticsearch.action.support.PlainActionFuture) IndexShardRoutingTable(org.elasticsearch.cluster.routing.IndexShardRoutingTable) Test(org.junit.Test) Collectors(java.util.stream.Collectors) Engine(org.elasticsearch.index.engine.Engine) CountDownLatch(java.util.concurrent.CountDownLatch) Mockito(org.mockito.Mockito) List(java.util.List) ReplicationResponse(org.elasticsearch.action.support.replication.ReplicationResponse) Matchers.equalTo(org.hamcrest.Matchers.equalTo) Translog(org.elasticsearch.index.translog.Translog) Matchers.is(org.hamcrest.Matchers.is) ResyncReplicationRequest(org.elasticsearch.action.resync.ResyncReplicationRequest) Collections(java.util.Collections) IndexShardRoutingTable(org.elasticsearch.cluster.routing.IndexShardRoutingTable) BytesArray(org.elasticsearch.common.bytes.BytesArray) ByteSizeValue(org.elasticsearch.common.unit.ByteSizeValue) SourceToParse(org.elasticsearch.index.mapper.SourceToParse) Matchers.anyString(org.mockito.Matchers.anyString) AlreadyClosedException(org.apache.lucene.store.AlreadyClosedException) CountDownLatch(java.util.concurrent.CountDownLatch) AlreadyClosedException(org.apache.lucene.store.AlreadyClosedException) ReplicationResponse(org.elasticsearch.action.support.replication.ReplicationResponse) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) PlainActionFuture(org.elasticsearch.action.support.PlainActionFuture)

Example 23 with ReplicationResponse

use of org.elasticsearch.action.support.replication.ReplicationResponse in project crate by crate.

the class RetentionLeaseIT method testRetentionLeasesSyncedOnAdd.

@Test
public void testRetentionLeasesSyncedOnAdd() throws Exception {
    final int numberOfReplicas = 2 - scaledRandomIntBetween(0, 2);
    internalCluster().ensureAtLeastNumDataNodes(1 + numberOfReplicas);
    execute("create table doc.tbl (x int) clustered into 1 shards " + "with (number_of_replicas = ?, \"soft_deletes.enabled\" = true)", new Object[] { numberOfReplicas });
    ensureGreen("tbl");
    final String primaryShardNodeId = clusterService().state().routingTable().index("tbl").shard(0).primaryShard().currentNodeId();
    final String primaryShardNodeName = clusterService().state().nodes().get(primaryShardNodeId).getName();
    final IndexShard primary = internalCluster().getInstance(IndicesService.class, primaryShardNodeName).getShardOrNull(new ShardId(resolveIndex("tbl"), 0));
    // we will add multiple retention leases and expect to see them synced to all replicas
    final int length = randomIntBetween(1, 8);
    final Map<String, RetentionLease> currentRetentionLeases = new HashMap<>();
    for (int i = 0; i < length; i++) {
        final String id = randomValueOtherThanMany(currentRetentionLeases.keySet()::contains, () -> randomAlphaOfLength(8));
        final long retainingSequenceNumber = randomLongBetween(0, Long.MAX_VALUE);
        final String source = randomAlphaOfLength(8);
        final CountDownLatch latch = new CountDownLatch(1);
        final ActionListener<ReplicationResponse> listener = ActionListener.wrap(r -> latch.countDown(), e -> fail(e.toString()));
        // simulate a peer recovery which locks the soft deletes policy on the primary
        final Closeable retentionLock = randomBoolean() ? primary.acquireHistoryRetentionLock(Engine.HistorySource.INDEX) : () -> {
        };
        currentRetentionLeases.put(id, primary.addRetentionLease(id, retainingSequenceNumber, source, listener));
        latch.await();
        retentionLock.close();
        // check retention leases have been written on the primary
        assertThat(currentRetentionLeases, equalTo(RetentionLeaseUtils.toMapExcludingPeerRecoveryRetentionLeases(primary.loadRetentionLeases())));
        // check current retention leases have been synced to all replicas
        for (final ShardRouting replicaShard : clusterService().state().routingTable().index("tbl").shard(0).replicaShards()) {
            final String replicaShardNodeId = replicaShard.currentNodeId();
            final String replicaShardNodeName = clusterService().state().nodes().get(replicaShardNodeId).getName();
            final IndexShard replica = internalCluster().getInstance(IndicesService.class, replicaShardNodeName).getShardOrNull(new ShardId(resolveIndex("tbl"), 0));
            final Map<String, RetentionLease> retentionLeasesOnReplica = RetentionLeaseUtils.toMapExcludingPeerRecoveryRetentionLeases(replica.getRetentionLeases());
            assertThat(retentionLeasesOnReplica, equalTo(currentRetentionLeases));
            // check retention leases have been written on the replica
            assertThat(currentRetentionLeases, equalTo(RetentionLeaseUtils.toMapExcludingPeerRecoveryRetentionLeases(replica.loadRetentionLeases())));
        }
    }
}
Also used : HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) IndexShard(org.elasticsearch.index.shard.IndexShard) Closeable(java.io.Closeable) IndicesService(org.elasticsearch.indices.IndicesService) CountDownLatch(java.util.concurrent.CountDownLatch) ReplicationResponse(org.elasticsearch.action.support.replication.ReplicationResponse) ShardId(org.elasticsearch.index.shard.ShardId) ShardRouting(org.elasticsearch.cluster.routing.ShardRouting) Test(org.junit.Test)

Example 24 with ReplicationResponse

use of org.elasticsearch.action.support.replication.ReplicationResponse in project crate by crate.

the class RetentionLeaseIT method runUnderBlockTest.

private void runUnderBlockTest(final String idForInitialRetentionLease, final long initialRetainingSequenceNumber, final BiConsumer<IndexShard, ActionListener<ReplicationResponse>> primaryConsumer, final Consumer<IndexShard> afterSync) throws InterruptedException {
    execute("create table doc.tbl (x int) clustered into 1 shards " + "with (" + "   number_of_replicas = 0, " + "   \"soft_deletes.enabled\" = true, " + "   \"soft_deletes.retention_lease.sync_interval\" = '1s' " + ")");
    ensureGreen("tbl");
    final String primaryShardNodeId = clusterService().state().routingTable().index("tbl").shard(0).primaryShard().currentNodeId();
    final String primaryShardNodeName = clusterService().state().nodes().get(primaryShardNodeId).getName();
    final IndexShard primary = internalCluster().getInstance(IndicesService.class, primaryShardNodeName).getShardOrNull(new ShardId(resolveIndex("tbl"), 0));
    final String source = randomAlphaOfLength(8);
    final CountDownLatch latch = new CountDownLatch(1);
    final ActionListener<ReplicationResponse> listener = ActionListener.wrap(r -> latch.countDown(), e -> fail(e.toString()));
    primary.addRetentionLease(idForInitialRetentionLease, initialRetainingSequenceNumber, source, listener);
    latch.await();
    final String block = randomFrom("read_only", "read_only_allow_delete", "read", "write", "metadata");
    execute("alter table doc.tbl set (\"blocks." + block + "\" = true)");
    try {
        final CountDownLatch actionLatch = new CountDownLatch(1);
        final AtomicBoolean success = new AtomicBoolean();
        primaryConsumer.accept(primary, new ActionListener<ReplicationResponse>() {

            @Override
            public void onResponse(final ReplicationResponse replicationResponse) {
                success.set(true);
                actionLatch.countDown();
            }

            @Override
            public void onFailure(final Exception e) {
                fail(e.toString());
            }
        });
        actionLatch.await();
        assertTrue(success.get());
        afterSync.accept(primary);
    } finally {
        execute("alter table doc.tbl reset (\"blocks." + block + "\")");
    }
}
Also used : ShardId(org.elasticsearch.index.shard.ShardId) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) IndexShard(org.elasticsearch.index.shard.IndexShard) IndicesService(org.elasticsearch.indices.IndicesService) CountDownLatch(java.util.concurrent.CountDownLatch) ElasticsearchException(org.elasticsearch.ElasticsearchException) ReplicationResponse(org.elasticsearch.action.support.replication.ReplicationResponse)

Aggregations

ReplicationResponse (org.elasticsearch.action.support.replication.ReplicationResponse)24 Test (org.junit.Test)10 CountDownLatch (java.util.concurrent.CountDownLatch)9 IndexShard (org.elasticsearch.index.shard.IndexShard)9 ShardId (org.elasticsearch.index.shard.ShardId)8 ShardRouting (org.elasticsearch.cluster.routing.ShardRouting)7 Collections (java.util.Collections)6 List (java.util.List)6 AtomicBoolean (java.util.concurrent.atomic.AtomicBoolean)6 PlainActionFuture (org.elasticsearch.action.support.PlainActionFuture)6 IndexShardRoutingTable (org.elasticsearch.cluster.routing.IndexShardRoutingTable)6 IndicesService (org.elasticsearch.indices.IndicesService)6 IOException (java.io.IOException)5 ArrayList (java.util.ArrayList)5 Arrays (java.util.Arrays)5 BytesArray (org.elasticsearch.common.bytes.BytesArray)5 ByteSizeValue (org.elasticsearch.common.unit.ByteSizeValue)5 Engine (org.elasticsearch.index.engine.Engine)5 SequenceNumbers (org.elasticsearch.index.seqno.SequenceNumbers)5 Translog (org.elasticsearch.index.translog.Translog)5