Search in sources :

Example 21 with RecoveryState

use of org.elasticsearch.indices.recovery.RecoveryState in project elasticsearch by elastic.

the class RecoveriesCollectionTests method testRecoveryTimeout.

public void testRecoveryTimeout() throws Exception {
    try (ReplicationGroup shards = createGroup(0)) {
        final RecoveriesCollection collection = new RecoveriesCollection(logger, threadPool, v -> {
        });
        final AtomicBoolean failed = new AtomicBoolean();
        final CountDownLatch latch = new CountDownLatch(1);
        final long recoveryId = startRecovery(collection, shards.getPrimaryNode(), shards.addReplica(), new PeerRecoveryTargetService.RecoveryListener() {

            @Override
            public void onRecoveryDone(RecoveryState state) {
                latch.countDown();
            }

            @Override
            public void onRecoveryFailure(RecoveryState state, RecoveryFailedException e, boolean sendShardFailure) {
                failed.set(true);
                latch.countDown();
            }
        }, TimeValue.timeValueMillis(100));
        try {
            latch.await(30, TimeUnit.SECONDS);
            assertTrue("recovery failed to timeout", failed.get());
        } finally {
            collection.cancelRecovery(recoveryId, "meh");
        }
    }
}
Also used : AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) PeerRecoveryTargetService(org.elasticsearch.indices.recovery.PeerRecoveryTargetService) RecoveryFailedException(org.elasticsearch.indices.recovery.RecoveryFailedException) RecoveriesCollection(org.elasticsearch.indices.recovery.RecoveriesCollection) CountDownLatch(java.util.concurrent.CountDownLatch) RecoveryState(org.elasticsearch.indices.recovery.RecoveryState)

Example 22 with RecoveryState

use of org.elasticsearch.indices.recovery.RecoveryState in project elasticsearch by elastic.

the class IndexShardTests method testShardActiveDuringPeerRecovery.

public void testShardActiveDuringPeerRecovery() throws IOException {
    Settings settings = Settings.builder().put(IndexMetaData.SETTING_VERSION_CREATED, Version.CURRENT).put(IndexMetaData.SETTING_NUMBER_OF_REPLICAS, 1).put(IndexMetaData.SETTING_NUMBER_OF_SHARDS, 1).build();
    IndexMetaData metaData = IndexMetaData.builder("test").putMapping("test", "{ \"properties\": { \"foo\":  { \"type\": \"text\"}}}").settings(settings).primaryTerm(0, 1).build();
    IndexShard primary = newShard(new ShardId(metaData.getIndex(), 0), true, "n1", metaData, null);
    recoveryShardFromStore(primary);
    indexDoc(primary, "test", "0", "{\"foo\" : \"bar\"}");
    IndexShard replica = newShard(primary.shardId(), false, "n2", metaData, null);
    DiscoveryNode localNode = new DiscoveryNode("foo", buildNewFakeTransportAddress(), emptyMap(), emptySet(), Version.CURRENT);
    replica.markAsRecovering("for testing", new RecoveryState(replica.routingEntry(), localNode, localNode));
    // Shard is still inactive since we haven't started recovering yet
    assertFalse(replica.isActive());
    recoverReplica(replica, primary, (shard, discoveryNode) -> new RecoveryTarget(shard, discoveryNode, recoveryListener, aLong -> {
    }) {

        @Override
        public void prepareForTranslogOperations(int totalTranslogOps, long maxUnsafeAutoIdTimestamp) throws IOException {
            super.prepareForTranslogOperations(totalTranslogOps, maxUnsafeAutoIdTimestamp);
            // Shard is still inactive since we haven't started recovering yet
            assertFalse(replica.isActive());
        }

        @Override
        public void indexTranslogOperations(List<Translog.Operation> operations, int totalTranslogOps) {
            super.indexTranslogOperations(operations, totalTranslogOps);
            // Shard should now be active since we did recover:
            assertTrue(replica.isActive());
        }
    }, false);
    closeShards(primary, replica);
}
Also used : MetaData(org.elasticsearch.cluster.metadata.MetaData) Versions(org.elasticsearch.common.lucene.uid.Versions) Arrays(java.util.Arrays) Releasables(org.elasticsearch.common.lease.Releasables) Term(org.apache.lucene.index.Term) AlreadyClosedException(org.apache.lucene.store.AlreadyClosedException) TranslogTests(org.elasticsearch.index.translog.TranslogTests) XContentBuilder(org.elasticsearch.common.xcontent.XContentBuilder) ParseContext(org.elasticsearch.index.mapper.ParseContext) EMPTY_REPO_GEN(org.elasticsearch.repositories.RepositoryData.EMPTY_REPO_GEN) Map(java.util.Map) Matchers.nullValue(org.hamcrest.Matchers.nullValue) UidFieldMapper(org.elasticsearch.index.mapper.UidFieldMapper) IOContext(org.apache.lucene.store.IOContext) Path(java.nio.file.Path) NumericDocValuesField(org.apache.lucene.document.NumericDocValuesField) PlainActionFuture(org.elasticsearch.action.support.PlainActionFuture) UUIDs(org.elasticsearch.common.UUIDs) Set(java.util.Set) Matchers.instanceOf(org.hamcrest.Matchers.instanceOf) RecoverySource(org.elasticsearch.cluster.routing.RecoverySource) SeqNoFieldMapper(org.elasticsearch.index.mapper.SeqNoFieldMapper) CountDownLatch(java.util.concurrent.CountDownLatch) AbstractRunnable(org.elasticsearch.common.util.concurrent.AbstractRunnable) Logger(org.apache.logging.log4j.Logger) IndexMetaData(org.elasticsearch.cluster.metadata.IndexMetaData) Matchers.greaterThan(org.hamcrest.Matchers.greaterThan) Matchers.containsString(org.hamcrest.Matchers.containsString) TestShardRouting(org.elasticsearch.cluster.routing.TestShardRouting) IndexCommit(org.apache.lucene.index.IndexCommit) FieldDataStats(org.elasticsearch.index.fielddata.FieldDataStats) SnapshotId(org.elasticsearch.snapshots.SnapshotId) SnapshotShardFailure(org.elasticsearch.snapshots.SnapshotShardFailure) BytesStreamOutput(org.elasticsearch.common.io.stream.BytesStreamOutput) ShardRoutingState(org.elasticsearch.cluster.routing.ShardRoutingState) ArrayList(java.util.ArrayList) BytesArray(org.elasticsearch.common.bytes.BytesArray) DiscoveryNode(org.elasticsearch.cluster.node.DiscoveryNode) SequenceNumbersService(org.elasticsearch.index.seqno.SequenceNumbersService) Store(org.elasticsearch.index.store.Store) BiConsumer(java.util.function.BiConsumer) Matchers.hasSize(org.hamcrest.Matchers.hasSize) EngineException(org.elasticsearch.index.engine.EngineException) TopDocs(org.apache.lucene.search.TopDocs) EMPTY_PARAMS(org.elasticsearch.common.xcontent.ToXContent.EMPTY_PARAMS) IOException(java.io.IOException) BrokenBarrierException(java.util.concurrent.BrokenBarrierException) UnassignedInfo(org.elasticsearch.cluster.routing.UnassignedInfo) ParsedDocument(org.elasticsearch.index.mapper.ParsedDocument) ExecutionException(java.util.concurrent.ExecutionException) Lucene.cleanLuceneIndex(org.elasticsearch.common.lucene.Lucene.cleanLuceneIndex) CommonStatsFlags(org.elasticsearch.action.admin.indices.stats.CommonStatsFlags) MappingMetaData(org.elasticsearch.cluster.metadata.MappingMetaData) ConcurrentCollections(org.elasticsearch.common.util.concurrent.ConcurrentCollections) IndicesQueryCache(org.elasticsearch.indices.IndicesQueryCache) SnapshotInfo(org.elasticsearch.snapshots.SnapshotInfo) VersionType(org.elasticsearch.index.VersionType) Matchers.hasKey(org.hamcrest.Matchers.hasKey) CorruptIndexException(org.apache.lucene.index.CorruptIndexException) Settings(org.elasticsearch.common.settings.Settings) ShardRoutingHelper(org.elasticsearch.cluster.routing.ShardRoutingHelper) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) MappedFieldType(org.elasticsearch.index.mapper.MappedFieldType) XContentFactory.jsonBuilder(org.elasticsearch.common.xcontent.XContentFactory.jsonBuilder) ThreadPool(org.elasticsearch.threadpool.ThreadPool) NamedXContentRegistry(org.elasticsearch.common.xcontent.NamedXContentRegistry) Releasable(org.elasticsearch.common.lease.Releasable) CyclicBarrier(java.util.concurrent.CyclicBarrier) DirectoryReader(org.apache.lucene.index.DirectoryReader) BytesReference(org.elasticsearch.common.bytes.BytesReference) Collectors(java.util.stream.Collectors) Engine(org.elasticsearch.index.engine.Engine) List(java.util.List) Version(org.elasticsearch.Version) RecoveryState(org.elasticsearch.indices.recovery.RecoveryState) Matchers.equalTo(org.hamcrest.Matchers.equalTo) CommonStats(org.elasticsearch.action.admin.indices.stats.CommonStats) IndexReader(org.apache.lucene.index.IndexReader) IndexSearcher(org.apache.lucene.search.IndexSearcher) RepositoryData(org.elasticsearch.repositories.RepositoryData) ShardRouting(org.elasticsearch.cluster.routing.ShardRouting) IntStream(java.util.stream.IntStream) XContentType(org.elasticsearch.common.xcontent.XContentType) PRIMARY(org.elasticsearch.index.engine.Engine.Operation.Origin.PRIMARY) IndexShardSnapshotStatus(org.elasticsearch.index.snapshots.IndexShardSnapshotStatus) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) HashMap(java.util.HashMap) IndexId(org.elasticsearch.repositories.IndexId) AtomicReference(java.util.concurrent.atomic.AtomicReference) ForceMergeRequest(org.elasticsearch.action.admin.indices.forcemerge.ForceMergeRequest) HashSet(java.util.HashSet) ShardStats(org.elasticsearch.action.admin.indices.stats.ShardStats) Mapping(org.elasticsearch.index.mapper.Mapping) Collections.emptyMap(java.util.Collections.emptyMap) RepositoryMetaData(org.elasticsearch.cluster.metadata.RepositoryMetaData) Repository(org.elasticsearch.repositories.Repository) Uid(org.elasticsearch.index.mapper.Uid) Collections.emptySet(java.util.Collections.emptySet) Semaphore(java.util.concurrent.Semaphore) RecoveryTarget(org.elasticsearch.indices.recovery.RecoveryTarget) AbstractLifecycleComponent(org.elasticsearch.common.component.AbstractLifecycleComponent) FieldMaskingReader(org.elasticsearch.test.FieldMaskingReader) VersionUtils(org.elasticsearch.test.VersionUtils) TimeUnit(java.util.concurrent.TimeUnit) TermQuery(org.apache.lucene.search.TermQuery) FlushRequest(org.elasticsearch.action.admin.indices.flush.FlushRequest) Constants(org.apache.lucene.util.Constants) NodeEnvironment(org.elasticsearch.env.NodeEnvironment) Field(org.apache.lucene.document.Field) StreamInput(org.elasticsearch.common.io.stream.StreamInput) IndexFieldData(org.elasticsearch.index.fielddata.IndexFieldData) Translog(org.elasticsearch.index.translog.Translog) AllocationId(org.elasticsearch.cluster.routing.AllocationId) DummyShardLock(org.elasticsearch.test.DummyShardLock) Snapshot(org.elasticsearch.snapshots.Snapshot) Collections(java.util.Collections) DiscoveryNode(org.elasticsearch.cluster.node.DiscoveryNode) RecoveryTarget(org.elasticsearch.indices.recovery.RecoveryTarget) IOException(java.io.IOException) IndexMetaData(org.elasticsearch.cluster.metadata.IndexMetaData) RecoveryState(org.elasticsearch.indices.recovery.RecoveryState) Settings(org.elasticsearch.common.settings.Settings)

Example 23 with RecoveryState

use of org.elasticsearch.indices.recovery.RecoveryState in project elasticsearch by elastic.

the class IndexShardTests method testRecoverFromLocalShard.

public void testRecoverFromLocalShard() throws IOException {
    Settings settings = Settings.builder().put(IndexMetaData.SETTING_VERSION_CREATED, Version.CURRENT).put(IndexMetaData.SETTING_NUMBER_OF_REPLICAS, 1).put(IndexMetaData.SETTING_NUMBER_OF_SHARDS, 1).build();
    IndexMetaData metaData = IndexMetaData.builder("source").putMapping("test", "{ \"properties\": { \"foo\":  { \"type\": \"text\"}}}").settings(settings).primaryTerm(0, 1).build();
    IndexShard sourceShard = newShard(new ShardId(metaData.getIndex(), 0), true, "n1", metaData, null);
    recoveryShardFromStore(sourceShard);
    indexDoc(sourceShard, "test", "0", "{\"foo\" : \"bar\"}");
    indexDoc(sourceShard, "test", "1", "{\"foo\" : \"bar\"}");
    sourceShard.refresh("test");
    ShardRouting targetRouting = TestShardRouting.newShardRouting(new ShardId("index_1", "index_1", 0), "n1", true, ShardRoutingState.INITIALIZING, RecoverySource.LocalShardsRecoverySource.INSTANCE);
    final IndexShard targetShard;
    DiscoveryNode localNode = new DiscoveryNode("foo", buildNewFakeTransportAddress(), emptyMap(), emptySet(), Version.CURRENT);
    Map<String, MappingMetaData> requestedMappingUpdates = ConcurrentCollections.newConcurrentMap();
    {
        targetShard = newShard(targetRouting);
        targetShard.markAsRecovering("store", new RecoveryState(targetShard.routingEntry(), localNode, null));
        BiConsumer<String, MappingMetaData> mappingConsumer = (type, mapping) -> {
            assertNull(requestedMappingUpdates.put(type, mapping));
        };
        final IndexShard differentIndex = newShard(new ShardId("index_2", "index_2", 0), true);
        recoveryShardFromStore(differentIndex);
        expectThrows(IllegalArgumentException.class, () -> {
            targetShard.recoverFromLocalShards(mappingConsumer, Arrays.asList(sourceShard, differentIndex));
        });
        closeShards(differentIndex);
        assertTrue(targetShard.recoverFromLocalShards(mappingConsumer, Arrays.asList(sourceShard)));
        RecoveryState recoveryState = targetShard.recoveryState();
        assertEquals(RecoveryState.Stage.DONE, recoveryState.getStage());
        assertTrue(recoveryState.getIndex().fileDetails().size() > 0);
        for (RecoveryState.File file : recoveryState.getIndex().fileDetails()) {
            if (file.reused()) {
                assertEquals(file.recovered(), 0);
            } else {
                assertEquals(file.recovered(), file.length());
            }
        }
        targetShard.updateRoutingEntry(ShardRoutingHelper.moveToStarted(targetShard.routingEntry()));
        assertDocCount(targetShard, 2);
    }
    // now check that it's persistent ie. that the added shards are committed
    {
        final IndexShard newShard = reinitShard(targetShard);
        recoveryShardFromStore(newShard);
        assertDocCount(newShard, 2);
        closeShards(newShard);
    }
    assertThat(requestedMappingUpdates, hasKey("test"));
    assertThat(requestedMappingUpdates.get("test").get().source().string(), equalTo("{\"properties\":{\"foo\":{\"type\":\"text\"}}}"));
    closeShards(sourceShard, targetShard);
}
Also used : DiscoveryNode(org.elasticsearch.cluster.node.DiscoveryNode) Matchers.containsString(org.hamcrest.Matchers.containsString) MappingMetaData(org.elasticsearch.cluster.metadata.MappingMetaData) IndexMetaData(org.elasticsearch.cluster.metadata.IndexMetaData) TestShardRouting(org.elasticsearch.cluster.routing.TestShardRouting) ShardRouting(org.elasticsearch.cluster.routing.ShardRouting) RecoveryState(org.elasticsearch.indices.recovery.RecoveryState) Settings(org.elasticsearch.common.settings.Settings) BiConsumer(java.util.function.BiConsumer)

Example 24 with RecoveryState

use of org.elasticsearch.indices.recovery.RecoveryState in project elasticsearch by elastic.

the class IndexShardTests method testRecoverFromCleanStore.

public void testRecoverFromCleanStore() throws IOException {
    final IndexShard shard = newStartedShard(true);
    indexDoc(shard, "test", "0");
    if (randomBoolean()) {
        flushShard(shard);
    }
    final ShardRouting shardRouting = shard.routingEntry();
    IndexShard newShard = reinitShard(shard, ShardRoutingHelper.initWithSameId(shardRouting, RecoverySource.StoreRecoverySource.EMPTY_STORE_INSTANCE));
    DiscoveryNode localNode = new DiscoveryNode("foo", buildNewFakeTransportAddress(), emptyMap(), emptySet(), Version.CURRENT);
    newShard.markAsRecovering("store", new RecoveryState(newShard.routingEntry(), localNode, null));
    assertTrue(newShard.recoverFromStore());
    assertEquals(0, newShard.recoveryState().getTranslog().recoveredOperations());
    assertEquals(0, newShard.recoveryState().getTranslog().totalOperations());
    assertEquals(0, newShard.recoveryState().getTranslog().totalOperationsOnStart());
    assertEquals(100.0f, newShard.recoveryState().getTranslog().recoveredPercent(), 0.01f);
    newShard.updateRoutingEntry(newShard.routingEntry().moveToStarted());
    assertDocCount(newShard, 0);
    closeShards(newShard);
}
Also used : DiscoveryNode(org.elasticsearch.cluster.node.DiscoveryNode) TestShardRouting(org.elasticsearch.cluster.routing.TestShardRouting) ShardRouting(org.elasticsearch.cluster.routing.ShardRouting) RecoveryState(org.elasticsearch.indices.recovery.RecoveryState)

Example 25 with RecoveryState

use of org.elasticsearch.indices.recovery.RecoveryState in project elasticsearch by elastic.

the class IndexShardTests method testRestoreShard.

public void testRestoreShard() throws IOException {
    final IndexShard source = newStartedShard(true);
    IndexShard target = newStartedShard(true);
    indexDoc(source, "test", "0");
    if (randomBoolean()) {
        source.refresh("test");
    }
    indexDoc(target, "test", "1");
    target.refresh("test");
    assertDocs(target, new Uid("test", "1"));
    // only flush source
    flushShard(source);
    final ShardRouting origRouting = target.routingEntry();
    ShardRouting routing = ShardRoutingHelper.reinitPrimary(origRouting);
    final Snapshot snapshot = new Snapshot("foo", new SnapshotId("bar", UUIDs.randomBase64UUID()));
    routing = ShardRoutingHelper.newWithRestoreSource(routing, new RecoverySource.SnapshotRecoverySource(snapshot, Version.CURRENT, "test"));
    target = reinitShard(target, routing);
    Store sourceStore = source.store();
    Store targetStore = target.store();
    DiscoveryNode localNode = new DiscoveryNode("foo", buildNewFakeTransportAddress(), emptyMap(), emptySet(), Version.CURRENT);
    target.markAsRecovering("store", new RecoveryState(routing, localNode, null));
    assertTrue(target.restoreFromRepository(new RestoreOnlyRepository("test") {

        @Override
        public void restoreShard(IndexShard shard, SnapshotId snapshotId, Version version, IndexId indexId, ShardId snapshotShardId, RecoveryState recoveryState) {
            try {
                cleanLuceneIndex(targetStore.directory());
                for (String file : sourceStore.directory().listAll()) {
                    if (file.equals("write.lock") || file.startsWith("extra")) {
                        continue;
                    }
                    targetStore.directory().copyFrom(sourceStore.directory(), file, file, IOContext.DEFAULT);
                }
            } catch (Exception ex) {
                throw new RuntimeException(ex);
            }
        }
    }));
    target.updateRoutingEntry(routing.moveToStarted());
    assertDocs(target, new Uid("test", "0"));
    closeShards(source, target);
}
Also used : IndexId(org.elasticsearch.repositories.IndexId) DiscoveryNode(org.elasticsearch.cluster.node.DiscoveryNode) Store(org.elasticsearch.index.store.Store) Matchers.containsString(org.hamcrest.Matchers.containsString) AlreadyClosedException(org.apache.lucene.store.AlreadyClosedException) EngineException(org.elasticsearch.index.engine.EngineException) IOException(java.io.IOException) BrokenBarrierException(java.util.concurrent.BrokenBarrierException) ExecutionException(java.util.concurrent.ExecutionException) CorruptIndexException(org.apache.lucene.index.CorruptIndexException) Uid(org.elasticsearch.index.mapper.Uid) Snapshot(org.elasticsearch.snapshots.Snapshot) SnapshotId(org.elasticsearch.snapshots.SnapshotId) Version(org.elasticsearch.Version) TestShardRouting(org.elasticsearch.cluster.routing.TestShardRouting) ShardRouting(org.elasticsearch.cluster.routing.ShardRouting) RecoveryState(org.elasticsearch.indices.recovery.RecoveryState)

Aggregations

RecoveryState (org.elasticsearch.indices.recovery.RecoveryState)29 DiscoveryNode (org.elasticsearch.cluster.node.DiscoveryNode)16 ShardRouting (org.elasticsearch.cluster.routing.ShardRouting)9 Settings (org.elasticsearch.common.settings.Settings)7 Store (org.elasticsearch.index.store.Store)6 IOException (java.io.IOException)5 TestShardRouting (org.elasticsearch.cluster.routing.TestShardRouting)5 RecoveryResponse (org.elasticsearch.action.admin.indices.recovery.RecoveryResponse)4 UnassignedInfo (org.elasticsearch.cluster.routing.UnassignedInfo)4 EngineException (org.elasticsearch.index.engine.EngineException)4 Matchers.containsString (org.hamcrest.Matchers.containsString)4 ArrayList (java.util.ArrayList)3 HashMap (java.util.HashMap)3 List (java.util.List)3 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)3 Version (org.elasticsearch.Version)3 IndexMetaData (org.elasticsearch.cluster.metadata.IndexMetaData)3 IndexService (org.elasticsearch.index.IndexService)3 IndexShard (org.elasticsearch.index.shard.IndexShard)3 Path (java.nio.file.Path)2