Search in sources :

Example 6 with DummyShardLock

use of org.elasticsearch.test.DummyShardLock in project elasticsearch by elastic.

the class StoreTests method testRefCount.

public void testRefCount() throws IOException {
    final ShardId shardId = new ShardId("index", "_na_", 1);
    DirectoryService directoryService = new LuceneManagedDirectoryService(random());
    IndexSettings indexSettings = INDEX_SETTINGS;
    Store store = new Store(shardId, indexSettings, directoryService, new DummyShardLock(shardId));
    int incs = randomIntBetween(1, 100);
    for (int i = 0; i < incs; i++) {
        if (randomBoolean()) {
            store.incRef();
        } else {
            assertTrue(store.tryIncRef());
        }
        store.ensureOpen();
    }
    for (int i = 0; i < incs; i++) {
        store.decRef();
        store.ensureOpen();
    }
    store.incRef();
    store.close();
    for (int i = 0; i < incs; i++) {
        if (randomBoolean()) {
            store.incRef();
        } else {
            assertTrue(store.tryIncRef());
        }
        store.ensureOpen();
    }
    for (int i = 0; i < incs; i++) {
        store.decRef();
        store.ensureOpen();
    }
    store.decRef();
    assertThat(store.refCount(), Matchers.equalTo(0));
    assertFalse(store.tryIncRef());
    try {
        store.incRef();
        fail(" expected exception");
    } catch (AlreadyClosedException ex) {
    }
    try {
        store.ensureOpen();
        fail(" expected exception");
    } catch (AlreadyClosedException ex) {
    }
}
Also used : ShardId(org.elasticsearch.index.shard.ShardId) IndexSettings(org.elasticsearch.index.IndexSettings) DummyShardLock(org.elasticsearch.test.DummyShardLock) AlreadyClosedException(org.apache.lucene.store.AlreadyClosedException)

Example 7 with DummyShardLock

use of org.elasticsearch.test.DummyShardLock in project elasticsearch by elastic.

the class IndexShardTests method testFailShard.

public void testFailShard() throws Exception {
    IndexShard shard = newStartedShard();
    final ShardPath shardPath = shard.shardPath();
    assertNotNull(shardPath);
    // fail shard
    shard.failShard("test shard fail", new CorruptIndexException("", ""));
    closeShards(shard);
    // check state file still exists
    ShardStateMetaData shardStateMetaData = load(logger, shardPath.getShardStatePath());
    assertEquals(shardStateMetaData, getShardStateMetadata(shard));
    // but index can't be opened for a failed shard
    assertThat("store index should be corrupted", Store.canOpenIndex(logger, shardPath.resolveIndex(), shard.shardId(), (shardId, lockTimeoutMS) -> new DummyShardLock(shardId)), equalTo(false));
}
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) CorruptIndexException(org.apache.lucene.index.CorruptIndexException) DummyShardLock(org.elasticsearch.test.DummyShardLock)

Example 8 with DummyShardLock

use of org.elasticsearch.test.DummyShardLock in project elasticsearch by elastic.

the class StoreTests method testRecoveryDiff.

public void testRecoveryDiff() throws IOException, InterruptedException {
    int numDocs = 2 + random().nextInt(100);
    List<Document> docs = new ArrayList<>();
    for (int i = 0; i < numDocs; i++) {
        Document doc = new Document();
        doc.add(new StringField("id", "" + i, random().nextBoolean() ? Field.Store.YES : Field.Store.NO));
        doc.add(new TextField("body", TestUtil.randomRealisticUnicodeString(random()), random().nextBoolean() ? Field.Store.YES : Field.Store.NO));
        doc.add(new SortedDocValuesField("dv", new BytesRef(TestUtil.randomRealisticUnicodeString(random()))));
        docs.add(doc);
    }
    long seed = random().nextLong();
    Store.MetadataSnapshot first;
    {
        Random random = new Random(seed);
        IndexWriterConfig iwc = new IndexWriterConfig(new MockAnalyzer(random)).setCodec(TestUtil.getDefaultCodec());
        iwc.setMergePolicy(NoMergePolicy.INSTANCE);
        iwc.setUseCompoundFile(random.nextBoolean());
        final ShardId shardId = new ShardId("index", "_na_", 1);
        DirectoryService directoryService = new LuceneManagedDirectoryService(random);
        Store store = new Store(shardId, INDEX_SETTINGS, directoryService, new DummyShardLock(shardId));
        IndexWriter writer = new IndexWriter(store.directory(), iwc);
        final boolean lotsOfSegments = rarely(random);
        for (Document d : docs) {
            writer.addDocument(d);
            if (lotsOfSegments && random.nextBoolean()) {
                writer.commit();
            } else if (rarely(random)) {
                writer.commit();
            }
        }
        writer.commit();
        writer.close();
        first = store.getMetadata(null);
        assertDeleteContent(store, directoryService);
        store.close();
    }
    long time = new Date().getTime();
    while (time == new Date().getTime()) {
        // bump the time
        Thread.sleep(10);
    }
    Store.MetadataSnapshot second;
    Store store;
    {
        Random random = new Random(seed);
        IndexWriterConfig iwc = new IndexWriterConfig(new MockAnalyzer(random)).setCodec(TestUtil.getDefaultCodec());
        iwc.setMergePolicy(NoMergePolicy.INSTANCE);
        iwc.setUseCompoundFile(random.nextBoolean());
        final ShardId shardId = new ShardId("index", "_na_", 1);
        DirectoryService directoryService = new LuceneManagedDirectoryService(random);
        store = new Store(shardId, INDEX_SETTINGS, directoryService, new DummyShardLock(shardId));
        IndexWriter writer = new IndexWriter(store.directory(), iwc);
        final boolean lotsOfSegments = rarely(random);
        for (Document d : docs) {
            writer.addDocument(d);
            if (lotsOfSegments && random.nextBoolean()) {
                writer.commit();
            } else if (rarely(random)) {
                writer.commit();
            }
        }
        writer.commit();
        writer.close();
        second = store.getMetadata(null);
    }
    Store.RecoveryDiff diff = first.recoveryDiff(second);
    assertThat(first.size(), equalTo(second.size()));
    for (StoreFileMetaData md : first) {
        assertThat(second.get(md.name()), notNullValue());
        // si files are different - containing timestamps etc
        assertThat(second.get(md.name()).isSame(md), equalTo(false));
    }
    assertThat(diff.different.size(), equalTo(first.size()));
    // in lucene 5 nothing is identical - we use random ids in file headers
    assertThat(diff.identical.size(), equalTo(0));
    assertThat(diff.missing, empty());
    // check the self diff
    Store.RecoveryDiff selfDiff = first.recoveryDiff(first);
    assertThat(selfDiff.identical.size(), equalTo(first.size()));
    assertThat(selfDiff.different, empty());
    assertThat(selfDiff.missing, empty());
    // lets add some deletes
    Random random = new Random(seed);
    IndexWriterConfig iwc = new IndexWriterConfig(new MockAnalyzer(random)).setCodec(TestUtil.getDefaultCodec());
    iwc.setMergePolicy(NoMergePolicy.INSTANCE);
    iwc.setUseCompoundFile(random.nextBoolean());
    iwc.setOpenMode(IndexWriterConfig.OpenMode.APPEND);
    IndexWriter writer = new IndexWriter(store.directory(), iwc);
    writer.deleteDocuments(new Term("id", Integer.toString(random().nextInt(numDocs))));
    writer.commit();
    writer.close();
    Store.MetadataSnapshot metadata = store.getMetadata(null);
    StoreFileMetaData delFile = null;
    for (StoreFileMetaData md : metadata) {
        if (md.name().endsWith(".liv")) {
            delFile = md;
            break;
        }
    }
    Store.RecoveryDiff afterDeleteDiff = metadata.recoveryDiff(second);
    if (delFile != null) {
        // segments_N + del file
        assertThat(afterDeleteDiff.identical.size(), equalTo(metadata.size() - 2));
        assertThat(afterDeleteDiff.different.size(), equalTo(0));
        assertThat(afterDeleteDiff.missing.size(), equalTo(2));
    } else {
        // an entire segment must be missing (single doc segment got dropped)
        assertThat(afterDeleteDiff.identical.size(), greaterThan(0));
        assertThat(afterDeleteDiff.different.size(), equalTo(0));
        // the commit file is different
        assertThat(afterDeleteDiff.missing.size(), equalTo(1));
    }
    // check the self diff
    selfDiff = metadata.recoveryDiff(metadata);
    assertThat(selfDiff.identical.size(), equalTo(metadata.size()));
    assertThat(selfDiff.different, empty());
    assertThat(selfDiff.missing, empty());
    // add a new commit
    iwc = new IndexWriterConfig(new MockAnalyzer(random)).setCodec(TestUtil.getDefaultCodec());
    iwc.setMergePolicy(NoMergePolicy.INSTANCE);
    // force CFS - easier to test here since we know it will add 3 files
    iwc.setUseCompoundFile(true);
    iwc.setOpenMode(IndexWriterConfig.OpenMode.APPEND);
    writer = new IndexWriter(store.directory(), iwc);
    writer.addDocument(docs.get(0));
    writer.close();
    Store.MetadataSnapshot newCommitMetaData = store.getMetadata(null);
    Store.RecoveryDiff newCommitDiff = newCommitMetaData.recoveryDiff(metadata);
    if (delFile != null) {
        // segments_N, del file, cfs, cfe, si for the new segment
        assertThat(newCommitDiff.identical.size(), equalTo(newCommitMetaData.size() - 5));
        // the del file must be different
        assertThat(newCommitDiff.different.size(), equalTo(1));
        assertThat(newCommitDiff.different.get(0).name(), endsWith(".liv"));
        // segments_N,cfs, cfe, si for the new segment
        assertThat(newCommitDiff.missing.size(), equalTo(4));
    } else {
        // segments_N, cfs, cfe, si for the new segment
        assertThat(newCommitDiff.identical.size(), equalTo(newCommitMetaData.size() - 4));
        assertThat(newCommitDiff.different.size(), equalTo(0));
        // an entire segment must be missing (single doc segment got dropped)  plus the commit is different
        assertThat(newCommitDiff.missing.size(), equalTo(4));
    }
    deleteContent(store.directory());
    IOUtils.close(store);
}
Also used : ArrayList(java.util.ArrayList) Term(org.apache.lucene.index.Term) Document(org.apache.lucene.document.Document) Date(java.util.Date) ShardId(org.elasticsearch.index.shard.ShardId) Random(java.util.Random) MockAnalyzer(org.apache.lucene.analysis.MockAnalyzer) IndexWriter(org.apache.lucene.index.IndexWriter) StringField(org.apache.lucene.document.StringField) SortedDocValuesField(org.apache.lucene.document.SortedDocValuesField) TextField(org.apache.lucene.document.TextField) DummyShardLock(org.elasticsearch.test.DummyShardLock) BytesRef(org.apache.lucene.util.BytesRef) IndexWriterConfig(org.apache.lucene.index.IndexWriterConfig)

Example 9 with DummyShardLock

use of org.elasticsearch.test.DummyShardLock in project elasticsearch by elastic.

the class StoreTests method testMarkCorruptedOnTruncatedSegmentsFile.

public void testMarkCorruptedOnTruncatedSegmentsFile() throws IOException {
    IndexWriterConfig iwc = newIndexWriterConfig();
    final ShardId shardId = new ShardId("index", "_na_", 1);
    DirectoryService directoryService = new LuceneManagedDirectoryService(random());
    Store store = new Store(shardId, INDEX_SETTINGS, directoryService, new DummyShardLock(shardId));
    IndexWriter writer = new IndexWriter(store.directory(), iwc);
    int numDocs = 1 + random().nextInt(10);
    List<Document> docs = new ArrayList<>();
    for (int i = 0; i < numDocs; i++) {
        Document doc = new Document();
        doc.add(new StringField("id", "" + i, random().nextBoolean() ? Field.Store.YES : Field.Store.NO));
        doc.add(new TextField("body", TestUtil.randomRealisticUnicodeString(random()), random().nextBoolean() ? Field.Store.YES : Field.Store.NO));
        doc.add(new SortedDocValuesField("dv", new BytesRef(TestUtil.randomRealisticUnicodeString(random()))));
        docs.add(doc);
    }
    for (Document d : docs) {
        writer.addDocument(d);
    }
    writer.commit();
    writer.close();
    SegmentInfos segmentCommitInfos = store.readLastCommittedSegmentsInfo();
    store.directory().deleteFile(segmentCommitInfos.getSegmentsFileName());
    try (IndexOutput out = store.directory().createOutput(segmentCommitInfos.getSegmentsFileName(), IOContext.DEFAULT)) {
    // empty file
    }
    try {
        if (randomBoolean()) {
            store.getMetadata(null);
        } else {
            store.readLastCommittedSegmentsInfo();
        }
        fail("corrupted segments_N file");
    } catch (CorruptIndexException ex) {
    // expected
    }
    assertTrue(store.isMarkedCorrupted());
    // we have to remove the index since it's corrupted and might fail the MocKDirWrapper checkindex call
    Lucene.cleanLuceneIndex(store.directory());
    store.close();
}
Also used : SegmentInfos(org.apache.lucene.index.SegmentInfos) ArrayList(java.util.ArrayList) CorruptIndexException(org.apache.lucene.index.CorruptIndexException) IndexOutput(org.apache.lucene.store.IndexOutput) Document(org.apache.lucene.document.Document) ShardId(org.elasticsearch.index.shard.ShardId) IndexWriter(org.apache.lucene.index.IndexWriter) StringField(org.apache.lucene.document.StringField) SortedDocValuesField(org.apache.lucene.document.SortedDocValuesField) TextField(org.apache.lucene.document.TextField) DummyShardLock(org.elasticsearch.test.DummyShardLock) BytesRef(org.apache.lucene.util.BytesRef) IndexWriterConfig(org.apache.lucene.index.IndexWriterConfig)

Example 10 with DummyShardLock

use of org.elasticsearch.test.DummyShardLock in project elasticsearch by elastic.

the class StoreTests method testDeserializeCorruptionException.

public void testDeserializeCorruptionException() throws IOException {
    final ShardId shardId = new ShardId("index", "_na_", 1);
    // I use ram dir to prevent that virusscanner being a PITA
    final Directory dir = new RAMDirectory();
    DirectoryService directoryService = new DirectoryService(shardId, INDEX_SETTINGS) {

        @Override
        public Directory newDirectory() throws IOException {
            return dir;
        }
    };
    Store store = new Store(shardId, INDEX_SETTINGS, directoryService, new DummyShardLock(shardId));
    CorruptIndexException ex = new CorruptIndexException("foo", "bar");
    store.markStoreCorrupted(ex);
    try {
        store.failIfCorrupted();
        fail("should be corrupted");
    } catch (CorruptIndexException e) {
        assertEquals(ex.getMessage(), e.getMessage());
        assertEquals(ex.toString(), e.toString());
        assertArrayEquals(ex.getStackTrace(), e.getStackTrace());
    }
    store.removeCorruptionMarker();
    assertFalse(store.isMarkedCorrupted());
    FileNotFoundException ioe = new FileNotFoundException("foobar");
    store.markStoreCorrupted(ioe);
    try {
        store.failIfCorrupted();
        fail("should be corrupted");
    } catch (CorruptIndexException e) {
        assertEquals("foobar (resource=preexisting_corruption)", e.getMessage());
        assertArrayEquals(ioe.getStackTrace(), e.getCause().getStackTrace());
    }
    store.close();
}
Also used : ShardId(org.elasticsearch.index.shard.ShardId) FileNotFoundException(java.io.FileNotFoundException) CorruptIndexException(org.apache.lucene.index.CorruptIndexException) DummyShardLock(org.elasticsearch.test.DummyShardLock) RAMDirectory(org.apache.lucene.store.RAMDirectory) Directory(org.apache.lucene.store.Directory) RAMDirectory(org.apache.lucene.store.RAMDirectory)

Aggregations

DummyShardLock (org.elasticsearch.test.DummyShardLock)16 ShardId (org.elasticsearch.index.shard.ShardId)11 Document (org.apache.lucene.document.Document)6 TextField (org.apache.lucene.document.TextField)6 IndexWriter (org.apache.lucene.index.IndexWriter)6 IndexWriterConfig (org.apache.lucene.index.IndexWriterConfig)6 MockAnalyzer (org.apache.lucene.analysis.MockAnalyzer)5 SortedDocValuesField (org.apache.lucene.document.SortedDocValuesField)5 CorruptIndexException (org.apache.lucene.index.CorruptIndexException)5 Directory (org.apache.lucene.store.Directory)5 BytesRef (org.apache.lucene.util.BytesRef)5 IndexSettings (org.elasticsearch.index.IndexSettings)5 ArrayList (java.util.ArrayList)4 Term (org.apache.lucene.index.Term)4 IndexOutput (org.apache.lucene.store.IndexOutput)4 RAMDirectory (org.apache.lucene.store.RAMDirectory)4 Store (org.elasticsearch.index.store.Store)4 IOException (java.io.IOException)3 Path (java.nio.file.Path)3 HashMap (java.util.HashMap)3