Search in sources :

Example 76 with AlreadyClosedException

use of org.apache.lucene.store.AlreadyClosedException in project crate by crate.

the class ReplicationOperationTests method testPrimaryFailureHandlingReplicaResponse.

@Test
public void testPrimaryFailureHandlingReplicaResponse() throws Exception {
    final String index = "test";
    final ShardId shardId = new ShardId(index, "_na_", 0);
    final Request request = new Request(shardId);
    final ClusterState state = stateWithActivePrimary(index, true, 1, 0);
    final IndexMetadata indexMetadata = state.getMetadata().index(index);
    final long primaryTerm = indexMetadata.primaryTerm(0);
    final ShardRouting primaryRouting = state.getRoutingTable().shardRoutingTable(shardId).primaryShard();
    final Set<String> inSyncAllocationIds = indexMetadata.inSyncAllocationIds(0);
    final IndexShardRoutingTable shardRoutingTable = state.routingTable().index(index).shard(shardId.id());
    final Set<String> trackedShards = shardRoutingTable.getAllAllocationIds();
    final ReplicationGroup initialReplicationGroup = new ReplicationGroup(shardRoutingTable, inSyncAllocationIds, trackedShards);
    final boolean fatal = randomBoolean();
    final AtomicBoolean primaryFailed = new AtomicBoolean();
    final ReplicationOperation.Primary<Request, Request, TestPrimary.Result> primary = new TestPrimary(primaryRouting, () -> initialReplicationGroup) {

        @Override
        public void failShard(String message, Exception exception) {
            primaryFailed.set(true);
        }

        @Override
        public void updateLocalCheckpointForShard(String allocationId, long checkpoint) {
            if (primaryRouting.allocationId().getId().equals(allocationId)) {
                super.updateLocalCheckpointForShard(allocationId, checkpoint);
            } else {
                if (fatal) {
                    throw new NullPointerException();
                } else {
                    throw new AlreadyClosedException("already closed");
                }
            }
        }
    };
    final PlainActionFuture<TestPrimary.Result> listener = new PlainActionFuture<>();
    final ReplicationOperation.Replicas<Request> replicas = new TestReplicaProxy(Collections.emptyMap());
    TestReplicationOperation operation = new TestReplicationOperation(request, primary, listener, replicas, primaryTerm);
    operation.execute();
    assertThat(primaryFailed.get(), equalTo(fatal));
    final ShardInfo shardInfo = listener.actionGet().getShardInfo();
    assertThat(shardInfo.getFailed(), equalTo(0));
    assertThat(shardInfo.getFailures(), arrayWithSize(0));
    assertThat(shardInfo.getSuccessful(), equalTo(1 + getExpectedReplicas(shardId, state, trackedShards).size()));
}
Also used : IndexShardRoutingTable(org.elasticsearch.cluster.routing.IndexShardRoutingTable) AlreadyClosedException(org.apache.lucene.store.AlreadyClosedException) ReplicationGroup(org.elasticsearch.index.shard.ReplicationGroup) ShardId(org.elasticsearch.index.shard.ShardId) IndexMetadata(org.elasticsearch.cluster.metadata.IndexMetadata) ShardInfo(org.elasticsearch.action.support.replication.ReplicationResponse.ShardInfo) ClusterState(org.elasticsearch.cluster.ClusterState) AlreadyClosedException(org.apache.lucene.store.AlreadyClosedException) NodeClosedException(org.elasticsearch.node.NodeClosedException) CorruptIndexException(org.apache.lucene.index.CorruptIndexException) IndexShardNotStartedException(org.elasticsearch.index.shard.IndexShardNotStartedException) UnavailableShardsException(org.elasticsearch.action.UnavailableShardsException) ExecutionException(java.util.concurrent.ExecutionException) SendRequestTransportException(org.elasticsearch.transport.SendRequestTransportException) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) PlainActionFuture(org.elasticsearch.action.support.PlainActionFuture) ShardRouting(org.elasticsearch.cluster.routing.ShardRouting) Test(org.junit.Test)

Example 77 with AlreadyClosedException

use of org.apache.lucene.store.AlreadyClosedException 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 78 with AlreadyClosedException

use of org.apache.lucene.store.AlreadyClosedException in project crate by crate.

the class InternalEngineTests method testForceMergeAndClose.

@Test
public void testForceMergeAndClose() throws IOException, InterruptedException {
    int numIters = randomIntBetween(2, 10);
    for (int j = 0; j < numIters; j++) {
        try (Store store = createStore()) {
            final InternalEngine engine = createEngine(store, createTempDir());
            final CountDownLatch startGun = new CountDownLatch(1);
            final CountDownLatch indexed = new CountDownLatch(1);
            Thread thread = new Thread() {

                @Override
                public void run() {
                    try {
                        try {
                            startGun.await();
                        } catch (InterruptedException e) {
                            throw new RuntimeException(e);
                        }
                        int i = 0;
                        while (true) {
                            int numDocs = randomIntBetween(1, 20);
                            for (int j = 0; j < numDocs; j++) {
                                i++;
                                ParsedDocument doc = testParsedDocument(Integer.toString(i), null, testDocument(), B_1, null);
                                Engine.Index index = indexForDoc(doc);
                                engine.index(index);
                            }
                            engine.refresh("test");
                            indexed.countDown();
                            try {
                                engine.forceMerge(randomBoolean(), 1, false, randomBoolean(), randomBoolean(), UUIDs.randomBase64UUID());
                            } catch (IOException e) {
                                return;
                            }
                        }
                    } catch (AlreadyClosedException ex) {
                    // fine
                    } catch (IOException e) {
                        throw new AssertionError(e);
                    }
                }
            };
            thread.start();
            startGun.countDown();
            int someIters = randomIntBetween(1, 10);
            for (int i = 0; i < someIters; i++) {
                engine.forceMerge(randomBoolean(), 1, false, randomBoolean(), randomBoolean(), UUIDs.randomBase64UUID());
            }
            indexed.await();
            IOUtils.close(engine);
            thread.join();
        }
    }
}
Also used : Store(org.elasticsearch.index.store.Store) UncheckedIOException(java.io.UncheckedIOException) IOException(java.io.IOException) AlreadyClosedException(org.apache.lucene.store.AlreadyClosedException) CountDownLatch(java.util.concurrent.CountDownLatch) LongPoint(org.apache.lucene.document.LongPoint) ParsedDocument(org.elasticsearch.index.mapper.ParsedDocument) Test(org.junit.Test)

Example 79 with AlreadyClosedException

use of org.apache.lucene.store.AlreadyClosedException in project crate by crate.

the class InternalEngineTests method testFailEngineOnRandomIO.

@Test
public void testFailEngineOnRandomIO() throws IOException, InterruptedException {
    MockDirectoryWrapper wrapper = newMockDirectory();
    final Path translogPath = createTempDir("testFailEngineOnRandomIO");
    try (Store store = createStore(wrapper)) {
        CyclicBarrier join = new CyclicBarrier(2);
        CountDownLatch start = new CountDownLatch(1);
        AtomicInteger controller = new AtomicInteger(0);
        EngineConfig config = config(defaultSettings, store, translogPath, newMergePolicy(), new ReferenceManager.RefreshListener() {

            @Override
            public void beforeRefresh() throws IOException {
            }

            @Override
            public void afterRefresh(boolean didRefresh) throws IOException {
                int i = controller.incrementAndGet();
                if (i == 1) {
                    throw new MockDirectoryWrapper.FakeIOException();
                } else if (i == 2) {
                    try {
                        start.await();
                    } catch (InterruptedException e) {
                        throw new AssertionError(e);
                    }
                    throw new ElasticsearchException("something completely different");
                }
            }
        });
        InternalEngine internalEngine = createEngine(config);
        int docId = 0;
        final ParsedDocument doc = testParsedDocument(Integer.toString(docId), null, testDocumentWithTextField(), new BytesArray("{}".getBytes(Charset.defaultCharset())), null);
        Engine.Index index = randomBoolean() ? indexForDoc(doc) : randomAppendOnly(doc, false, docId);
        internalEngine.index(index);
        Runnable r = () -> {
            try {
                join.await();
            } catch (Exception e) {
                throw new AssertionError(e);
            }
            try {
                internalEngine.refresh("test");
                fail();
            } catch (AlreadyClosedException ex) {
                if (ex.getCause() != null) {
                    assertTrue(ex.toString(), ex.getCause() instanceof MockDirectoryWrapper.FakeIOException);
                }
            } catch (RefreshFailedEngineException ex) {
            // fine
            } finally {
                start.countDown();
            }
        };
        Thread t = new Thread(r);
        Thread t1 = new Thread(r);
        t.start();
        t1.start();
        t.join();
        t1.join();
        assertTrue(internalEngine.isClosed.get());
        assertTrue(internalEngine.failedEngine.get() instanceof MockDirectoryWrapper.FakeIOException);
    }
}
Also used : Store(org.elasticsearch.index.store.Store) ElasticsearchException(org.elasticsearch.ElasticsearchException) AlreadyClosedException(org.apache.lucene.store.AlreadyClosedException) ReferenceManager(org.apache.lucene.search.ReferenceManager) ParsedDocument(org.elasticsearch.index.mapper.ParsedDocument) MockDirectoryWrapper(org.apache.lucene.store.MockDirectoryWrapper) Path(java.nio.file.Path) BytesArray(org.elasticsearch.common.bytes.BytesArray) UncheckedIOException(java.io.UncheckedIOException) IOException(java.io.IOException) CountDownLatch(java.util.concurrent.CountDownLatch) LongPoint(org.apache.lucene.document.LongPoint) AlreadyClosedException(org.apache.lucene.store.AlreadyClosedException) UncheckedIOException(java.io.UncheckedIOException) IOException(java.io.IOException) BrokenBarrierException(java.util.concurrent.BrokenBarrierException) ElasticsearchException(org.elasticsearch.ElasticsearchException) CyclicBarrier(java.util.concurrent.CyclicBarrier) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) CheckedRunnable(org.elasticsearch.common.CheckedRunnable) AbstractRunnable(org.elasticsearch.common.util.concurrent.AbstractRunnable) Test(org.junit.Test)

Aggregations

AlreadyClosedException (org.apache.lucene.store.AlreadyClosedException)79 IOException (java.io.IOException)53 LockObtainFailedException (org.apache.lucene.store.LockObtainFailedException)16 CountDownLatch (java.util.concurrent.CountDownLatch)15 MockDirectoryWrapper (org.apache.lucene.store.MockDirectoryWrapper)14 TranslogCorruptedException (org.elasticsearch.index.translog.TranslogCorruptedException)13 MockAnalyzer (org.apache.lucene.analysis.MockAnalyzer)12 AtomicBoolean (java.util.concurrent.atomic.AtomicBoolean)11 Document (org.apache.lucene.document.Document)11 ElasticsearchException (org.elasticsearch.ElasticsearchException)11 ReleasableLock (org.elasticsearch.common.util.concurrent.ReleasableLock)10 UncheckedIOException (java.io.UncheckedIOException)9 ParsedDocument (org.elasticsearch.index.mapper.ParsedDocument)9 EOFException (java.io.EOFException)8 ArrayList (java.util.ArrayList)7 FileNotFoundException (java.io.FileNotFoundException)6 FileAlreadyExistsException (java.nio.file.FileAlreadyExistsException)6 NoSuchFileException (java.nio.file.NoSuchFileException)6 BrokenBarrierException (java.util.concurrent.BrokenBarrierException)6 CopyOnWriteArrayList (java.util.concurrent.CopyOnWriteArrayList)6