Search in sources :

Example 1 with DummyShardLock

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

the class StoreTests method testCanOpenIndex.

public void testCanOpenIndex() throws IOException {
    final ShardId shardId = new ShardId("index", "_na_", 1);
    IndexWriterConfig iwc = newIndexWriterConfig();
    Path tempDir = createTempDir();
    final BaseDirectoryWrapper dir = newFSDirectory(tempDir);
    assertFalse(Store.canOpenIndex(logger, tempDir, shardId, (id, l) -> new DummyShardLock(id)));
    IndexWriter writer = new IndexWriter(dir, iwc);
    Document doc = new Document();
    doc.add(new StringField("id", "1", random().nextBoolean() ? Field.Store.YES : Field.Store.NO));
    writer.addDocument(doc);
    writer.commit();
    writer.close();
    assertTrue(Store.canOpenIndex(logger, tempDir, shardId, (id, l) -> new DummyShardLock(id)));
    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));
    store.markStoreCorrupted(new CorruptIndexException("foo", "bar"));
    assertFalse(Store.canOpenIndex(logger, tempDir, shardId, (id, l) -> new DummyShardLock(id)));
    store.close();
}
Also used : ShardId(org.elasticsearch.index.shard.ShardId) Path(java.nio.file.Path) IndexNotFoundException(org.apache.lucene.index.IndexNotFoundException) ShardId(org.elasticsearch.index.shard.ShardId) NoMergePolicy(org.apache.lucene.index.NoMergePolicy) NoSuchFileException(java.nio.file.NoSuchFileException) Arrays(java.util.Arrays) IndexFormatTooNewException(org.apache.lucene.index.IndexFormatTooNewException) IndexSettingsModule(org.elasticsearch.test.IndexSettingsModule) Date(java.util.Date) Term(org.apache.lucene.index.Term) AlreadyClosedException(org.apache.lucene.store.AlreadyClosedException) Random(java.util.Random) ChecksumIndexInput(org.apache.lucene.store.ChecksumIndexInput) CorruptIndexException(org.apache.lucene.index.CorruptIndexException) InputStreamStreamInput(org.elasticsearch.common.io.stream.InputStreamStreamInput) Document(org.apache.lucene.document.Document) Settings(org.elasticsearch.common.settings.Settings) ByteArrayInputStream(java.io.ByteArrayInputStream) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) CodecUtil(org.apache.lucene.codecs.CodecUtil) Directory(org.apache.lucene.store.Directory) Map(java.util.Map) IOContext(org.apache.lucene.store.IOContext) Path(java.nio.file.Path) Matchers.notNullValue(org.hamcrest.Matchers.notNullValue) BytesRef(org.apache.lucene.util.BytesRef) DirectoryReader(org.apache.lucene.index.DirectoryReader) UUIDs(org.elasticsearch.common.UUIDs) SegmentInfos(org.apache.lucene.index.SegmentInfos) FileNotFoundException(java.io.FileNotFoundException) MockAnalyzer(org.apache.lucene.analysis.MockAnalyzer) Engine(org.elasticsearch.index.engine.Engine) IndexWriter(org.apache.lucene.index.IndexWriter) List(java.util.List) SortedDocValuesField(org.apache.lucene.document.SortedDocValuesField) IndexMetaData(org.elasticsearch.cluster.metadata.IndexMetaData) Matchers.equalTo(org.hamcrest.Matchers.equalTo) Matchers.greaterThan(org.hamcrest.Matchers.greaterThan) Matchers.is(org.hamcrest.Matchers.is) IndexWriterConfig(org.apache.lucene.index.IndexWriterConfig) Matchers.endsWith(org.hamcrest.Matchers.endsWith) ByteArrayOutputStream(java.io.ByteArrayOutputStream) StringField(org.apache.lucene.document.StringField) TestUtil(org.apache.lucene.util.TestUtil) RAMDirectory(org.apache.lucene.store.RAMDirectory) HashMap(java.util.HashMap) Index(org.elasticsearch.index.Index) Lucene(org.elasticsearch.common.lucene.Lucene) OutputStreamStreamOutput(org.elasticsearch.common.io.stream.OutputStreamStreamOutput) ArrayList(java.util.ArrayList) BaseDirectoryWrapper(org.apache.lucene.store.BaseDirectoryWrapper) NoDeletionPolicy(org.apache.lucene.index.NoDeletionPolicy) TimeValue(org.elasticsearch.common.unit.TimeValue) IndexSettings(org.elasticsearch.index.IndexSettings) ESTestCase(org.elasticsearch.test.ESTestCase) VersionUtils.randomVersion(org.elasticsearch.test.VersionUtils.randomVersion) IndexOutput(org.apache.lucene.store.IndexOutput) Matchers.empty(org.hamcrest.Matchers.empty) IndexInput(org.apache.lucene.store.IndexInput) Iterator(java.util.Iterator) SnapshotDeletionPolicy(org.apache.lucene.index.SnapshotDeletionPolicy) IndexFileNames(org.apache.lucene.index.IndexFileNames) IOUtils(org.apache.lucene.util.IOUtils) Matchers(org.hamcrest.Matchers) IOException(java.io.IOException) IndexFormatTooOldException(org.apache.lucene.index.IndexFormatTooOldException) ShardLock(org.elasticsearch.env.ShardLock) Version(org.apache.lucene.util.Version) ExceptionsHelper(org.elasticsearch.ExceptionsHelper) KeepOnlyLastCommitDeletionPolicy(org.apache.lucene.index.KeepOnlyLastCommitDeletionPolicy) Field(org.apache.lucene.document.Field) Translog(org.elasticsearch.index.translog.Translog) Collections.unmodifiableMap(java.util.Collections.unmodifiableMap) TextField(org.apache.lucene.document.TextField) DummyShardLock(org.elasticsearch.test.DummyShardLock) TransportNodesListShardStoreMetaData(org.elasticsearch.indices.store.TransportNodesListShardStoreMetaData) IndexWriter(org.apache.lucene.index.IndexWriter) StringField(org.apache.lucene.document.StringField) BaseDirectoryWrapper(org.apache.lucene.store.BaseDirectoryWrapper) CorruptIndexException(org.apache.lucene.index.CorruptIndexException) DummyShardLock(org.elasticsearch.test.DummyShardLock) Document(org.apache.lucene.document.Document) IndexWriterConfig(org.apache.lucene.index.IndexWriterConfig)

Example 2 with DummyShardLock

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

the class StoreTests method testOnCloseCallback.

public void testOnCloseCallback() throws IOException {
    final ShardId shardId = new ShardId(new Index(randomRealisticUnicodeOfCodepointLengthBetween(1, 10), "_na_"), randomIntBetween(0, 100));
    DirectoryService directoryService = new LuceneManagedDirectoryService(random());
    final AtomicInteger count = new AtomicInteger(0);
    final ShardLock lock = new DummyShardLock(shardId);
    Store store = new Store(shardId, INDEX_SETTINGS, directoryService, lock, theLock -> {
        assertEquals(shardId, theLock.getShardId());
        assertEquals(lock, theLock);
        count.incrementAndGet();
    });
    assertEquals(count.get(), 0);
    final int iters = randomIntBetween(1, 10);
    for (int i = 0; i < iters; i++) {
        store.close();
    }
    assertEquals(count.get(), 1);
}
Also used : ShardId(org.elasticsearch.index.shard.ShardId) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Index(org.elasticsearch.index.Index) DummyShardLock(org.elasticsearch.test.DummyShardLock) ShardLock(org.elasticsearch.env.ShardLock) DummyShardLock(org.elasticsearch.test.DummyShardLock)

Example 3 with DummyShardLock

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

the class StoreTests method testUserDataRead.

public void testUserDataRead() throws IOException {
    final ShardId shardId = new ShardId("index", "_na_", 1);
    DirectoryService directoryService = new LuceneManagedDirectoryService(random());
    Store store = new Store(shardId, INDEX_SETTINGS, directoryService, new DummyShardLock(shardId));
    IndexWriterConfig config = newIndexWriterConfig(random(), new MockAnalyzer(random())).setCodec(TestUtil.getDefaultCodec());
    SnapshotDeletionPolicy deletionPolicy = new SnapshotDeletionPolicy(new KeepOnlyLastCommitDeletionPolicy());
    config.setIndexDeletionPolicy(deletionPolicy);
    IndexWriter writer = new IndexWriter(store.directory(), config);
    Document doc = new Document();
    doc.add(new TextField("id", "1", Field.Store.NO));
    writer.addDocument(doc);
    Map<String, String> commitData = new HashMap<>(2);
    String syncId = "a sync id";
    String translogId = "a translog id";
    commitData.put(Engine.SYNC_COMMIT_ID, syncId);
    commitData.put(Translog.TRANSLOG_GENERATION_KEY, translogId);
    writer.setCommitData(commitData);
    writer.commit();
    writer.close();
    Store.MetadataSnapshot metadata;
    metadata = store.getMetadata(randomBoolean() ? null : deletionPolicy.snapshot());
    assertFalse(metadata.asMap().isEmpty());
    // do not check for correct files, we have enough tests for that above
    assertThat(metadata.getCommitUserData().get(Engine.SYNC_COMMIT_ID), equalTo(syncId));
    assertThat(metadata.getCommitUserData().get(Translog.TRANSLOG_GENERATION_KEY), equalTo(translogId));
    TestUtil.checkIndex(store.directory());
    assertDeleteContent(store, directoryService);
    IOUtils.close(store);
}
Also used : KeepOnlyLastCommitDeletionPolicy(org.apache.lucene.index.KeepOnlyLastCommitDeletionPolicy) HashMap(java.util.HashMap) Document(org.apache.lucene.document.Document) SnapshotDeletionPolicy(org.apache.lucene.index.SnapshotDeletionPolicy) ShardId(org.elasticsearch.index.shard.ShardId) MockAnalyzer(org.apache.lucene.analysis.MockAnalyzer) IndexWriter(org.apache.lucene.index.IndexWriter) TextField(org.apache.lucene.document.TextField) DummyShardLock(org.elasticsearch.test.DummyShardLock) IndexWriterConfig(org.apache.lucene.index.IndexWriterConfig)

Example 4 with DummyShardLock

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

the class IndexShardIT method testLockTryingToDelete.

public void testLockTryingToDelete() throws Exception {
    createIndex("test");
    ensureGreen();
    NodeEnvironment env = getInstanceFromNode(NodeEnvironment.class);
    ClusterService cs = getInstanceFromNode(ClusterService.class);
    final Index index = cs.state().metaData().index("test").getIndex();
    Path[] shardPaths = env.availableShardPaths(new ShardId(index, 0));
    logger.info("--> paths: [{}]", (Object) shardPaths);
    // Should not be able to acquire the lock because it's already open
    try {
        NodeEnvironment.acquireFSLockForPaths(IndexSettingsModule.newIndexSettings("test", Settings.EMPTY), shardPaths);
        fail("should not have been able to acquire the lock");
    } catch (LockObtainFailedException e) {
        assertTrue("msg: " + e.getMessage(), e.getMessage().contains("unable to acquire write.lock"));
    }
    // Test without the regular shard lock to assume we can acquire it
    // (worst case, meaning that the shard lock could be acquired and
    // we're green to delete the shard's directory)
    ShardLock sLock = new DummyShardLock(new ShardId(index, 0));
    try {
        env.deleteShardDirectoryUnderLock(sLock, IndexSettingsModule.newIndexSettings("test", Settings.EMPTY));
        fail("should not have been able to delete the directory");
    } catch (LockObtainFailedException e) {
        assertTrue("msg: " + e.getMessage(), e.getMessage().contains("unable to acquire write.lock"));
    }
}
Also used : Path(java.nio.file.Path) ClusterService(org.elasticsearch.cluster.service.ClusterService) NodeEnvironment(org.elasticsearch.env.NodeEnvironment) LockObtainFailedException(org.apache.lucene.store.LockObtainFailedException) Index(org.elasticsearch.index.Index) DummyShardLock(org.elasticsearch.test.DummyShardLock) ShardLock(org.elasticsearch.env.ShardLock) DummyShardLock(org.elasticsearch.test.DummyShardLock)

Example 5 with DummyShardLock

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

the class StoreTests method testCanReadOldCorruptionMarker.

public void testCanReadOldCorruptionMarker() 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 exception = new CorruptIndexException("foo", "bar");
    String uuid = Store.CORRUPTED + UUIDs.randomBase64UUID();
    try (IndexOutput output = dir.createOutput(uuid, IOContext.DEFAULT)) {
        CodecUtil.writeHeader(output, Store.CODEC, Store.VERSION_STACK_TRACE);
        output.writeString(ExceptionsHelper.detailedMessage(exception));
        output.writeString(ExceptionsHelper.stackTrace(exception));
        CodecUtil.writeFooter(output);
    }
    try {
        store.failIfCorrupted();
        fail("should be corrupted");
    } catch (CorruptIndexException e) {
        assertTrue(e.getMessage().startsWith("[index][1] Preexisting corrupted index [" + uuid + "] caused by: CorruptIndexException[foo (resource=bar)]"));
        assertTrue(e.getMessage().contains(ExceptionsHelper.stackTrace(exception)));
    }
    store.removeCorruptionMarker();
    try (IndexOutput output = dir.createOutput(uuid, IOContext.DEFAULT)) {
        CodecUtil.writeHeader(output, Store.CODEC, Store.VERSION_START);
        output.writeString(ExceptionsHelper.detailedMessage(exception));
        CodecUtil.writeFooter(output);
    }
    try {
        store.failIfCorrupted();
        fail("should be corrupted");
    } catch (CorruptIndexException e) {
        assertTrue(e.getMessage().startsWith("[index][1] Preexisting corrupted index [" + uuid + "] caused by: CorruptIndexException[foo (resource=bar)]"));
        assertFalse(e.getMessage().contains(ExceptionsHelper.stackTrace(exception)));
    }
    store.removeCorruptionMarker();
    try (IndexOutput output = dir.createOutput(uuid, IOContext.DEFAULT)) {
        // corrupted header
        CodecUtil.writeHeader(output, Store.CODEC, Store.VERSION_START - 1);
        CodecUtil.writeFooter(output);
    }
    try {
        store.failIfCorrupted();
        fail("should be too old");
    } catch (IndexFormatTooOldException e) {
    }
    store.removeCorruptionMarker();
    try (IndexOutput output = dir.createOutput(uuid, IOContext.DEFAULT)) {
        // corrupted header
        CodecUtil.writeHeader(output, Store.CODEC, Store.VERSION + 1);
        CodecUtil.writeFooter(output);
    }
    try {
        store.failIfCorrupted();
        fail("should be too new");
    } catch (IndexFormatTooNewException e) {
    }
    store.close();
}
Also used : ShardId(org.elasticsearch.index.shard.ShardId) IndexFormatTooOldException(org.apache.lucene.index.IndexFormatTooOldException) CorruptIndexException(org.apache.lucene.index.CorruptIndexException) IndexOutput(org.apache.lucene.store.IndexOutput) DummyShardLock(org.elasticsearch.test.DummyShardLock) IndexFormatTooNewException(org.apache.lucene.index.IndexFormatTooNewException) RAMDirectory(org.apache.lucene.store.RAMDirectory) Directory(org.apache.lucene.store.Directory) RAMDirectory(org.apache.lucene.store.RAMDirectory)

Aggregations

DummyShardLock (org.elasticsearch.test.DummyShardLock)29 ShardId (org.elasticsearch.index.shard.ShardId)24 Document (org.apache.lucene.document.Document)12 TextField (org.apache.lucene.document.TextField)12 IndexWriter (org.apache.lucene.index.IndexWriter)12 BytesRef (org.apache.lucene.util.BytesRef)12 IndexWriterConfig (org.apache.lucene.index.IndexWriterConfig)11 MockAnalyzer (org.apache.lucene.analysis.MockAnalyzer)10 SortedDocValuesField (org.apache.lucene.document.SortedDocValuesField)10 Term (org.apache.lucene.index.Term)9 Directory (org.apache.lucene.store.Directory)9 Matchers.containsString (org.hamcrest.Matchers.containsString)9 CorruptIndexException (org.apache.lucene.index.CorruptIndexException)8 IndexOutput (org.apache.lucene.store.IndexOutput)8 RAMDirectory (org.apache.lucene.store.RAMDirectory)8 IndexSettings (org.elasticsearch.index.IndexSettings)8 ArrayList (java.util.ArrayList)7 Index (org.elasticsearch.index.Index)6 IOException (java.io.IOException)5 HashMap (java.util.HashMap)5