Search in sources :

Example 56 with IndexCommit

use of org.apache.lucene.index.IndexCommit in project crate by crate.

the class InternalEngineTests method testTrimUnsafeCommits.

@Test
public void testTrimUnsafeCommits() throws Exception {
    final AtomicLong globalCheckpoint = new AtomicLong(SequenceNumbers.NO_OPS_PERFORMED);
    final int maxSeqNo = 40;
    final List<Long> seqNos = LongStream.rangeClosed(0, maxSeqNo).boxed().collect(Collectors.toList());
    Collections.shuffle(seqNos, random());
    try (Store store = createStore()) {
        EngineConfig config = config(defaultSettings, store, createTempDir(), newMergePolicy(), null, null, globalCheckpoint::get);
        final List<Long> commitMaxSeqNo = new ArrayList<>();
        final long minTranslogGen;
        try (InternalEngine engine = createEngine(config)) {
            for (int i = 0; i < seqNos.size(); i++) {
                ParsedDocument doc = testParsedDocument(Long.toString(seqNos.get(i)), null, testDocument(), new BytesArray("{}"), null);
                Engine.Index index = new Engine.Index(newUid(doc), doc, seqNos.get(i), 0, 1, null, REPLICA, System.nanoTime(), -1, false, UNASSIGNED_SEQ_NO, 0);
                engine.index(index);
                if (randomBoolean()) {
                    engine.flush();
                    final Long maxSeqNoInCommit = seqNos.subList(0, i + 1).stream().max(Long::compareTo).orElse(-1L);
                    commitMaxSeqNo.add(maxSeqNoInCommit);
                }
            }
            globalCheckpoint.set(randomInt(maxSeqNo));
            engine.syncTranslog();
            minTranslogGen = engine.getTranslog().getMinFileGeneration();
        }
        store.trimUnsafeCommits(globalCheckpoint.get(), minTranslogGen, config.getIndexSettings().getIndexVersionCreated());
        long safeMaxSeqNo = commitMaxSeqNo.stream().filter(s -> s <= globalCheckpoint.get()).reduce(// get the last one.
        (s1, s2) -> s2).orElse(SequenceNumbers.NO_OPS_PERFORMED);
        final List<IndexCommit> commits = DirectoryReader.listCommits(store.directory());
        assertThat(commits, hasSize(1));
        assertThat(commits.get(0).getUserData().get(SequenceNumbers.MAX_SEQ_NO), equalTo(Long.toString(safeMaxSeqNo)));
        try (IndexReader reader = DirectoryReader.open(commits.get(0))) {
            for (LeafReaderContext context : reader.leaves()) {
                final NumericDocValues values = context.reader().getNumericDocValues(SeqNoFieldMapper.NAME);
                if (values != null) {
                    for (int docID = 0; docID < context.reader().maxDoc(); docID++) {
                        if (values.advanceExact(docID) == false) {
                            throw new AssertionError("Document does not have a seq number: " + docID);
                        }
                        assertThat(values.longValue(), lessThanOrEqualTo(globalCheckpoint.get()));
                    }
                }
            }
        }
    }
}
Also used : ShardId(org.elasticsearch.index.shard.ShardId) NoMergePolicy(org.apache.lucene.index.NoMergePolicy) Arrays(java.util.Arrays) Versions(org.elasticsearch.common.lucene.uid.Versions) LongSupplier(java.util.function.LongSupplier) PEER_RECOVERY(org.elasticsearch.index.engine.Engine.Operation.Origin.PEER_RECOVERY) BigArrays(org.elasticsearch.common.util.BigArrays) IndexSettingsModule(org.elasticsearch.test.IndexSettingsModule) IndexMetadata(org.elasticsearch.cluster.metadata.IndexMetadata) Matchers.not(org.hamcrest.Matchers.not) Term(org.apache.lucene.index.Term) Level(org.apache.logging.log4j.Level) AlreadyClosedException(org.apache.lucene.store.AlreadyClosedException) ElasticsearchDirectoryReader(org.elasticsearch.common.lucene.index.ElasticsearchDirectoryReader) LogEvent(org.apache.logging.log4j.core.LogEvent) ReferenceManager(org.apache.lucene.search.ReferenceManager) ParseContext(org.elasticsearch.index.mapper.ParseContext) CoreMatchers.instanceOf(org.hamcrest.CoreMatchers.instanceOf) SeqNoStats(org.elasticsearch.index.seqno.SeqNoStats) LOCAL_TRANSLOG_RECOVERY(org.elasticsearch.index.engine.Engine.Operation.Origin.LOCAL_TRANSLOG_RECOVERY) RandomNumbers(com.carrotsearch.randomizedtesting.generators.RandomNumbers) MergePolicy(org.apache.lucene.index.MergePolicy) TermsEnum(org.apache.lucene.index.TermsEnum) Matchers.nullValue(org.hamcrest.Matchers.nullValue) Map(java.util.Map) TestTranslog(org.elasticsearch.index.translog.TestTranslog) CheckedRunnable(org.elasticsearch.common.CheckedRunnable) FieldsVisitor(org.elasticsearch.index.fieldvisitor.FieldsVisitor) Path(java.nio.file.Path) REPLICA(org.elasticsearch.index.engine.Engine.Operation.Origin.REPLICA) NumericDocValuesField(org.apache.lucene.document.NumericDocValuesField) Matchers.notNullValue(org.hamcrest.Matchers.notNullValue) SoftDeletesRetentionMergePolicy(org.apache.lucene.index.SoftDeletesRetentionMergePolicy) UUIDs(org.elasticsearch.common.UUIDs) Set(java.util.Set) MatchAllDocsQuery(org.apache.lucene.search.MatchAllDocsQuery) SnapshotMatchers(org.elasticsearch.index.translog.SnapshotMatchers) UncheckedIOException(java.io.UncheckedIOException) PointValues(org.apache.lucene.index.PointValues) CountDownLatch(java.util.concurrent.CountDownLatch) SeqNoFieldMapper(org.elasticsearch.index.mapper.SeqNoFieldMapper) AbstractRunnable(org.elasticsearch.common.util.concurrent.AbstractRunnable) Logger(org.apache.logging.log4j.Logger) Matchers.contains(org.hamcrest.Matchers.contains) Matchers.greaterThan(org.hamcrest.Matchers.greaterThan) ReplicationTracker(org.elasticsearch.index.seqno.ReplicationTracker) Matchers.containsString(org.hamcrest.Matchers.containsString) TestShardRouting(org.elasticsearch.cluster.routing.TestShardRouting) IndexCommit(org.apache.lucene.index.IndexCommit) Tuple(io.crate.common.collections.Tuple) LiveIndexWriterConfig(org.apache.lucene.index.LiveIndexWriterConfig) LogDocMergePolicy(org.apache.lucene.index.LogDocMergePolicy) FixedBitSet(org.apache.lucene.util.FixedBitSet) RegexFilter(org.apache.logging.log4j.core.filter.RegexFilter) CodecService(org.elasticsearch.index.codec.CodecService) Mockito.spy(org.mockito.Mockito.spy) ShardRoutingState(org.elasticsearch.cluster.routing.ShardRoutingState) Supplier(java.util.function.Supplier) CheckedBiConsumer(org.elasticsearch.common.CheckedBiConsumer) ArrayList(java.util.ArrayList) LinkedHashMap(java.util.LinkedHashMap) ToLongBiFunction(java.util.function.ToLongBiFunction) BytesArray(org.elasticsearch.common.bytes.BytesArray) RetentionLease(org.elasticsearch.index.seqno.RetentionLease) RetentionLeases(org.elasticsearch.index.seqno.RetentionLeases) Lock(org.apache.lucene.store.Lock) Store(org.elasticsearch.index.store.Store) Matchers.hasSize(org.hamcrest.Matchers.hasSize) Matchers.isIn(org.hamcrest.Matchers.isIn) Bits(org.apache.lucene.util.Bits) TranslogConfig(org.elasticsearch.index.translog.TranslogConfig) TieredMergePolicy(org.apache.lucene.index.TieredMergePolicy) Loggers(org.elasticsearch.common.logging.Loggers) TopDocs(org.apache.lucene.search.TopDocs) Matchers.greaterThanOrEqualTo(org.hamcrest.Matchers.greaterThanOrEqualTo) LongStream(java.util.stream.LongStream) SequenceNumbers(org.elasticsearch.index.seqno.SequenceNumbers) Files(java.nio.file.Files) IdFieldMapper(org.elasticsearch.index.mapper.IdFieldMapper) AbstractAppender(org.apache.logging.log4j.core.appender.AbstractAppender) DocIdAndSeqNo(org.elasticsearch.common.lucene.uid.VersionsAndSeqNoResolver.DocIdAndSeqNo) IOUtils(io.crate.common.io.IOUtils) SequentialStoredFieldsLeafReader(org.elasticsearch.common.lucene.index.SequentialStoredFieldsLeafReader) IOException(java.io.IOException) BrokenBarrierException(java.util.concurrent.BrokenBarrierException) Test(org.junit.Test) ParsedDocument(org.elasticsearch.index.mapper.ParsedDocument) AtomicLong(java.util.concurrent.atomic.AtomicLong) SourceFieldMapper(org.elasticsearch.index.mapper.SourceFieldMapper) VersionFieldMapper(org.elasticsearch.index.mapper.VersionFieldMapper) Matchers.hasItem(org.hamcrest.Matchers.hasItem) Matchers.sameInstance(org.hamcrest.Matchers.sameInstance) Phaser(java.util.concurrent.Phaser) Matcher(org.hamcrest.Matcher) TextField(org.apache.lucene.document.TextField) TranslogDeletionPolicies.createTranslogDeletionPolicy(org.elasticsearch.index.translog.TranslogDeletionPolicies.createTranslogDeletionPolicy) Lucene87StoredFieldsFormat(org.apache.lucene.codecs.lucene87.Lucene87StoredFieldsFormat) ActionListener(org.elasticsearch.action.ActionListener) Randomness(org.elasticsearch.common.Randomness) Collections.shuffle(java.util.Collections.shuffle) CoreMatchers.is(org.hamcrest.CoreMatchers.is) ElasticsearchException(org.elasticsearch.ElasticsearchException) BiFunction(java.util.function.BiFunction) IndexableField(org.apache.lucene.index.IndexableField) ConcurrentCollections(org.elasticsearch.common.util.concurrent.ConcurrentCollections) StoredField(org.apache.lucene.document.StoredField) Matchers.hasKey(org.hamcrest.Matchers.hasKey) VersionType(org.elasticsearch.index.VersionType) Settings(org.elasticsearch.common.settings.Settings) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Directory(org.apache.lucene.store.Directory) ThreadPool(org.elasticsearch.threadpool.ThreadPool) LeafReaderContext(org.apache.lucene.index.LeafReaderContext) ShardUtils(org.elasticsearch.index.shard.ShardUtils) TotalHitCountCollector(org.apache.lucene.search.TotalHitCountCollector) ByteSizeValue(org.elasticsearch.common.unit.ByteSizeValue) CyclicBarrier(java.util.concurrent.CyclicBarrier) Terms(org.apache.lucene.index.Terms) Matchers.lessThanOrEqualTo(org.hamcrest.Matchers.lessThanOrEqualTo) BytesRef(org.apache.lucene.util.BytesRef) DirectoryReader(org.apache.lucene.index.DirectoryReader) UNASSIGNED_PRIMARY_TERM(org.elasticsearch.index.seqno.SequenceNumbers.UNASSIGNED_PRIMARY_TERM) UNASSIGNED_SEQ_NO(org.elasticsearch.index.seqno.SequenceNumbers.UNASSIGNED_SEQ_NO) IndexShardRoutingTable(org.elasticsearch.cluster.routing.IndexShardRoutingTable) BytesReference(org.elasticsearch.common.bytes.BytesReference) Collectors(java.util.stream.Collectors) SegmentInfos(org.apache.lucene.index.SegmentInfos) Searcher(org.elasticsearch.index.engine.Engine.Searcher) MapperService(org.elasticsearch.index.mapper.MapperService) Base64(java.util.Base64) List(java.util.List) IndexWriter(org.apache.lucene.index.IndexWriter) Version(org.elasticsearch.Version) MatcherAssert(org.hamcrest.MatcherAssert) Matchers.containsInAnyOrder(org.hamcrest.Matchers.containsInAnyOrder) TriFunction(org.elasticsearch.common.TriFunction) Matchers.equalTo(org.hamcrest.Matchers.equalTo) LeafReader(org.apache.lucene.index.LeafReader) TimeValue(io.crate.common.unit.TimeValue) Queue(java.util.Queue) IndexWriterConfig(org.apache.lucene.index.IndexWriterConfig) LogByteSizeMergePolicy(org.apache.lucene.index.LogByteSizeMergePolicy) MockDirectoryWrapper(org.apache.lucene.store.MockDirectoryWrapper) IndexReader(org.apache.lucene.index.IndexReader) IndexSearcher(org.apache.lucene.search.IndexSearcher) ShardRouting(org.elasticsearch.cluster.routing.ShardRouting) LongPoint(org.apache.lucene.document.LongPoint) NumericDocValues(org.apache.lucene.index.NumericDocValues) PRIMARY(org.elasticsearch.index.engine.Engine.Operation.Origin.PRIMARY) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) Document(org.elasticsearch.index.mapper.ParseContext.Document) HashMap(java.util.HashMap) VersionsAndSeqNoResolver(org.elasticsearch.common.lucene.uid.VersionsAndSeqNoResolver) Lucene(org.elasticsearch.common.lucene.Lucene) AtomicReference(java.util.concurrent.atomic.AtomicReference) Function(java.util.function.Function) TransportActions(org.elasticsearch.action.support.TransportActions) Strings(org.elasticsearch.common.Strings) HashSet(java.util.HashSet) LOCAL_RESET(org.elasticsearch.index.engine.Engine.Operation.Origin.LOCAL_RESET) Charset(java.nio.charset.Charset) NoneCircuitBreakerService(org.elasticsearch.indices.breaker.NoneCircuitBreakerService) IndexSettings(org.elasticsearch.index.IndexSettings) LocalCheckpointTracker(org.elasticsearch.index.seqno.LocalCheckpointTracker) IntSupplier(java.util.function.IntSupplier) Matchers.empty(org.hamcrest.Matchers.empty) Iterator(java.util.Iterator) Uid(org.elasticsearch.index.mapper.Uid) Matchers(org.hamcrest.Matchers) Mockito.when(org.mockito.Mockito.when) VersionUtils(org.elasticsearch.test.VersionUtils) TimeUnit(java.util.concurrent.TimeUnit) TermQuery(org.apache.lucene.search.TermQuery) NO_OPS_PERFORMED(org.elasticsearch.index.seqno.SequenceNumbers.NO_OPS_PERFORMED) Field(org.apache.lucene.document.Field) Closeable(java.io.Closeable) Translog(org.elasticsearch.index.translog.Translog) Comparator(java.util.Comparator) Collections(java.util.Collections) LogManager(org.apache.logging.log4j.LogManager) NumericDocValues(org.apache.lucene.index.NumericDocValues) BytesArray(org.elasticsearch.common.bytes.BytesArray) ArrayList(java.util.ArrayList) Store(org.elasticsearch.index.store.Store) LongPoint(org.apache.lucene.document.LongPoint) IndexCommit(org.apache.lucene.index.IndexCommit) AtomicLong(java.util.concurrent.atomic.AtomicLong) ParsedDocument(org.elasticsearch.index.mapper.ParsedDocument) AtomicLong(java.util.concurrent.atomic.AtomicLong) IndexReader(org.apache.lucene.index.IndexReader) LeafReaderContext(org.apache.lucene.index.LeafReaderContext) Test(org.junit.Test)

Example 57 with IndexCommit

use of org.apache.lucene.index.IndexCommit in project crate by crate.

the class InternalEngineTests method testKeepTranslogAfterGlobalCheckpoint.

@Test
public void testKeepTranslogAfterGlobalCheckpoint() throws Exception {
    IOUtils.close(engine, store);
    final IndexSettings indexSettings = new IndexSettings(defaultSettings.getIndexMetadata(), defaultSettings.getNodeSettings(), defaultSettings.getScopedSettings());
    IndexMetadata.Builder builder = IndexMetadata.builder(indexSettings.getIndexMetadata()).settings(Settings.builder().put(indexSettings.getSettings()).put(IndexSettings.INDEX_TRANSLOG_RETENTION_AGE_SETTING.getKey(), randomFrom("-1", "100micros", "30m")).put(IndexSettings.INDEX_TRANSLOG_RETENTION_SIZE_SETTING.getKey(), randomFrom("-1", "512b", "1gb")));
    indexSettings.updateIndexMetadata(builder.build());
    final Path translogPath = createTempDir();
    store = createStore();
    final AtomicLong globalCheckpoint = new AtomicLong(SequenceNumbers.NO_OPS_PERFORMED);
    store.createEmpty(Version.CURRENT.luceneVersion);
    final String translogUUID = Translog.createEmptyTranslog(translogPath, globalCheckpoint.get(), shardId, primaryTerm.get());
    store.associateIndexWithNewTranslog(translogUUID);
    final EngineConfig engineConfig = config(indexSettings, store, translogPath, NoMergePolicy.INSTANCE, null, null, () -> globalCheckpoint.get());
    final AtomicLong lastSyncedGlobalCheckpointBeforeCommit = new AtomicLong(Translog.readGlobalCheckpoint(translogPath, translogUUID));
    try (InternalEngine engine = new InternalEngine(engineConfig) {

        @Override
        protected void commitIndexWriter(IndexWriter writer, Translog translog, String syncId) throws IOException {
            lastSyncedGlobalCheckpointBeforeCommit.set(Translog.readGlobalCheckpoint(translogPath, translogUUID));
            // (this value is visible to the deletion policy) and an in memory global checkpoint in the SequenceNumbersService.
            if (rarely()) {
                globalCheckpoint.set(randomLongBetween(globalCheckpoint.get(), getPersistedLocalCheckpoint()));
            }
            super.commitIndexWriter(writer, translog, syncId);
        }
    }) {
        engine.recoverFromTranslog(translogHandler, Long.MAX_VALUE);
        int numDocs = scaledRandomIntBetween(10, 100);
        for (int docId = 0; docId < numDocs; docId++) {
            ParseContext.Document document = testDocumentWithTextField();
            document.add(new Field(SourceFieldMapper.NAME, BytesReference.toBytes(B_1), SourceFieldMapper.Defaults.FIELD_TYPE));
            engine.index(indexForDoc(testParsedDocument(Integer.toString(docId), null, document, B_1, null)));
            if (frequently()) {
                globalCheckpoint.set(randomLongBetween(globalCheckpoint.get(), engine.getPersistedLocalCheckpoint()));
                engine.syncTranslog();
            }
            if (frequently()) {
                engine.flush(randomBoolean(), true);
                final List<IndexCommit> commits = DirectoryReader.listCommits(store.directory());
                // Keep only one safe commit as the oldest commit.
                final IndexCommit safeCommit = commits.get(0);
                if (lastSyncedGlobalCheckpointBeforeCommit.get() == UNASSIGNED_SEQ_NO) {
                    // If the global checkpoint is still unassigned, we keep an empty(eg. initial) commit as a safe commit.
                    assertThat(Long.parseLong(safeCommit.getUserData().get(SequenceNumbers.MAX_SEQ_NO)), equalTo(SequenceNumbers.NO_OPS_PERFORMED));
                } else {
                    assertThat(Long.parseLong(safeCommit.getUserData().get(SequenceNumbers.MAX_SEQ_NO)), lessThanOrEqualTo(lastSyncedGlobalCheckpointBeforeCommit.get()));
                }
                for (int i = 1; i < commits.size(); i++) {
                    assertThat(Long.parseLong(commits.get(i).getUserData().get(SequenceNumbers.MAX_SEQ_NO)), greaterThan(lastSyncedGlobalCheckpointBeforeCommit.get()));
                }
                // Make sure we keep all translog operations after the local checkpoint of the safe commit.
                long localCheckpointFromSafeCommit = Long.parseLong(safeCommit.getUserData().get(SequenceNumbers.LOCAL_CHECKPOINT_KEY));
                try (Translog.Snapshot snapshot = getTranslog(engine).newSnapshot()) {
                    assertThat(snapshot, SnapshotMatchers.containsSeqNoRange(localCheckpointFromSafeCommit + 1, docId));
                }
            }
        }
    }
}
Also used : Path(java.nio.file.Path) IndexSettings(org.elasticsearch.index.IndexSettings) Matchers.containsString(org.hamcrest.Matchers.containsString) LongPoint(org.apache.lucene.document.LongPoint) IndexCommit(org.apache.lucene.index.IndexCommit) TestTranslog(org.elasticsearch.index.translog.TestTranslog) Translog(org.elasticsearch.index.translog.Translog) NumericDocValuesField(org.apache.lucene.document.NumericDocValuesField) TextField(org.apache.lucene.document.TextField) IndexableField(org.apache.lucene.index.IndexableField) StoredField(org.apache.lucene.document.StoredField) Field(org.apache.lucene.document.Field) AtomicLong(java.util.concurrent.atomic.AtomicLong) IndexWriter(org.apache.lucene.index.IndexWriter) Document(org.elasticsearch.index.mapper.ParseContext.Document) ParseContext(org.elasticsearch.index.mapper.ParseContext) IndexMetadata(org.elasticsearch.cluster.metadata.IndexMetadata) Test(org.junit.Test)

Example 58 with IndexCommit

use of org.apache.lucene.index.IndexCommit in project crate by crate.

the class InternalEngineTests method testCleanupCommitsWhenReleaseSnapshot.

@Test
public void testCleanupCommitsWhenReleaseSnapshot() throws Exception {
    IOUtils.close(engine, store);
    store = createStore();
    final AtomicLong globalCheckpoint = new AtomicLong(SequenceNumbers.NO_OPS_PERFORMED);
    try (InternalEngine engine = createEngine(store, createTempDir(), globalCheckpoint::get)) {
        final int numDocs = scaledRandomIntBetween(10, 100);
        for (int docId = 0; docId < numDocs; docId++) {
            index(engine, docId);
            if (frequently()) {
                engine.flush(randomBoolean(), true);
            }
        }
        engine.flush(false, randomBoolean());
        int numSnapshots = between(1, 10);
        final List<Engine.IndexCommitRef> snapshots = new ArrayList<>();
        for (int i = 0; i < numSnapshots; i++) {
            // taking snapshots from the safe commit.
            snapshots.add(engine.acquireSafeIndexCommit());
        }
        globalCheckpoint.set(engine.getPersistedLocalCheckpoint());
        engine.syncTranslog();
        final List<IndexCommit> commits = DirectoryReader.listCommits(store.directory());
        for (int i = 0; i < numSnapshots - 1; i++) {
            snapshots.get(i).close();
            // pending snapshots - should not release any commit.
            assertThat(DirectoryReader.listCommits(store.directory()), equalTo(commits));
        }
        // release the last snapshot - delete all except the last commit
        snapshots.get(numSnapshots - 1).close();
        assertThat(DirectoryReader.listCommits(store.directory()), hasSize(1));
    }
}
Also used : AtomicLong(java.util.concurrent.atomic.AtomicLong) ArrayList(java.util.ArrayList) LongPoint(org.apache.lucene.document.LongPoint) IndexCommit(org.apache.lucene.index.IndexCommit) Test(org.junit.Test)

Example 59 with IndexCommit

use of org.apache.lucene.index.IndexCommit in project crate by crate.

the class CombinedDeletionPolicyTests method mockIndexCommit.

IndexCommit mockIndexCommit(long localCheckpoint, long maxSeqNo, UUID translogUUID) throws IOException {
    final Map<String, String> userData = new HashMap<>();
    userData.put(SequenceNumbers.LOCAL_CHECKPOINT_KEY, Long.toString(localCheckpoint));
    userData.put(SequenceNumbers.MAX_SEQ_NO, Long.toString(maxSeqNo));
    userData.put(Translog.TRANSLOG_UUID_KEY, translogUUID.toString());
    final IndexCommit commit = mock(IndexCommit.class);
    final Directory directory = mock(Directory.class);
    when(commit.getUserData()).thenReturn(userData);
    when(commit.getDirectory()).thenReturn(directory);
    resetDeletion(commit);
    return commit;
}
Also used : HashMap(java.util.HashMap) IndexCommit(org.apache.lucene.index.IndexCommit) Directory(org.apache.lucene.store.Directory)

Example 60 with IndexCommit

use of org.apache.lucene.index.IndexCommit in project crate by crate.

the class CombinedDeletionPolicyTests method testDeleteInvalidCommits.

public void testDeleteInvalidCommits() throws Exception {
    final AtomicLong globalCheckpoint = new AtomicLong(randomNonNegativeLong());
    final SoftDeletesPolicy softDeletesPolicy = new SoftDeletesPolicy(globalCheckpoint::get, -1, 0, () -> RetentionLeases.EMPTY);
    TranslogDeletionPolicy translogPolicy = createTranslogDeletionPolicy();
    CombinedDeletionPolicy indexPolicy = newCombinedDeletionPolicy(translogPolicy, softDeletesPolicy, globalCheckpoint);
    final int invalidCommits = between(1, 10);
    final List<IndexCommit> commitList = new ArrayList<>();
    for (int i = 0; i < invalidCommits; i++) {
        long maxSeqNo = randomNonNegativeLong();
        commitList.add(mockIndexCommit(randomLongBetween(-1, maxSeqNo), maxSeqNo, UUID.randomUUID()));
    }
    final UUID expectedTranslogUUID = UUID.randomUUID();
    final int validCommits = between(1, 10);
    long lastMaxSeqNo = between(1, 1000);
    long lastCheckpoint = randomLongBetween(-1, lastMaxSeqNo);
    for (int i = 0; i < validCommits; i++) {
        lastMaxSeqNo += between(1, 1000);
        lastCheckpoint = randomLongBetween(lastCheckpoint, lastMaxSeqNo);
        commitList.add(mockIndexCommit(lastCheckpoint, lastMaxSeqNo, expectedTranslogUUID));
    }
    // We should never keep invalid commits regardless of the value of the global checkpoint.
    indexPolicy.onCommit(commitList);
    for (int i = 0; i < invalidCommits - 1; i++) {
        verify(commitList.get(i), times(1)).delete();
    }
    assertThat(softDeletesPolicy.getMinRetainedSeqNo(), equalTo(getLocalCheckpoint(CombinedDeletionPolicy.findSafeCommitPoint(commitList, globalCheckpoint.get())) + 1));
}
Also used : AtomicLong(java.util.concurrent.atomic.AtomicLong) LongArrayList(com.carrotsearch.hppc.LongArrayList) ArrayList(java.util.ArrayList) UUID(java.util.UUID) TranslogDeletionPolicy(org.elasticsearch.index.translog.TranslogDeletionPolicy) TranslogDeletionPolicies.createTranslogDeletionPolicy(org.elasticsearch.index.translog.TranslogDeletionPolicies.createTranslogDeletionPolicy) IndexCommit(org.apache.lucene.index.IndexCommit)

Aggregations

IndexCommit (org.apache.lucene.index.IndexCommit)60 IOException (java.io.IOException)24 ArrayList (java.util.ArrayList)22 AtomicLong (java.util.concurrent.atomic.AtomicLong)11 Directory (org.apache.lucene.store.Directory)11 Test (org.junit.Test)10 IndexWriter (org.apache.lucene.index.IndexWriter)9 Store (org.elasticsearch.index.store.Store)9 Translog (org.elasticsearch.index.translog.Translog)8 List (java.util.List)7 Map (java.util.Map)7 SolrException (org.apache.solr.common.SolrException)7 NoSuchFileException (java.nio.file.NoSuchFileException)6 HashMap (java.util.HashMap)6 LongPoint (org.apache.lucene.document.LongPoint)6 DirectoryReader (org.apache.lucene.index.DirectoryReader)6 IndexReader (org.apache.lucene.index.IndexReader)6 UncheckedIOException (java.io.UncheckedIOException)5 Collections (java.util.Collections)5 IndexSettings (org.elasticsearch.index.IndexSettings)5