Search in sources :

Example 41 with MapperService

use of org.elasticsearch.index.mapper.MapperService in project crate by crate.

the class IndexShardTestCase method newShard.

/**
 * creates a new initializing shard.
 * @param routing                       shard routing to use
 * @param shardPath                     path to use for shard data
 * @param indexMetadata                 indexMetadata for the shard, including any mapping
 * @param storeProvider                 an optional custom store provider to use. If null a default file based store will be created
 * @param globalCheckpointSyncer        callback for syncing global checkpoints
 * @param indexEventListener            index event listener
 * @param listeners                     an optional set of listeners to add to the shard
 */
protected IndexShard newShard(ShardRouting routing, ShardPath shardPath, IndexMetadata indexMetadata, @Nullable CheckedFunction<IndexSettings, Store, IOException> storeProvider, @Nullable EngineFactory engineFactory, Runnable globalCheckpointSyncer, RetentionLeaseSyncer retentionLeaseSyncer, IndexEventListener indexEventListener, IndexingOperationListener... listeners) throws IOException {
    final Settings nodeSettings = Settings.builder().put("node.name", routing.currentNodeId()).build();
    final IndexSettings indexSettings = new IndexSettings(indexMetadata, nodeSettings);
    final IndexShard indexShard;
    if (storeProvider == null) {
        storeProvider = is -> createStore(is, shardPath);
    }
    final Store store = storeProvider.apply(indexSettings);
    boolean success = false;
    try {
        IndexCache indexCache = new IndexCache(indexSettings, new DisabledQueryCache(indexSettings));
        MapperService mapperService = MapperTestUtils.newMapperService(xContentRegistry(), createTempDir(), indexSettings.getSettings(), "index");
        mapperService.merge(indexMetadata, MapperService.MergeReason.MAPPING_RECOVERY);
        ClusterSettings clusterSettings = new ClusterSettings(nodeSettings, ClusterSettings.BUILT_IN_CLUSTER_SETTINGS);
        CircuitBreakerService breakerService = new HierarchyCircuitBreakerService(nodeSettings, clusterSettings);
        indexShard = new IndexShard(routing, indexSettings, shardPath, store, indexCache, mapperService, engineFactory, indexEventListener, threadPool, BigArrays.NON_RECYCLING_INSTANCE, Arrays.asList(listeners), globalCheckpointSyncer, retentionLeaseSyncer, breakerService);
        indexShard.addShardFailureCallback(DEFAULT_SHARD_FAILURE_HANDLER);
        success = true;
    } finally {
        if (success == false) {
            IOUtils.close(store);
        }
    }
    return indexShard;
}
Also used : ClusterSettings(org.elasticsearch.common.settings.ClusterSettings) IndexSettings(org.elasticsearch.index.IndexSettings) IndexCache(org.elasticsearch.index.cache.IndexCache) HierarchyCircuitBreakerService(org.elasticsearch.indices.breaker.HierarchyCircuitBreakerService) Store(org.elasticsearch.index.store.Store) CircuitBreakerService(org.elasticsearch.indices.breaker.CircuitBreakerService) HierarchyCircuitBreakerService(org.elasticsearch.indices.breaker.HierarchyCircuitBreakerService) RecoverySettings(org.elasticsearch.indices.recovery.RecoverySettings) Settings(org.elasticsearch.common.settings.Settings) IndexSettings(org.elasticsearch.index.IndexSettings) ClusterSettings(org.elasticsearch.common.settings.ClusterSettings) DisabledQueryCache(org.elasticsearch.index.cache.query.DisabledQueryCache) MapperService(org.elasticsearch.index.mapper.MapperService)

Example 42 with MapperService

use of org.elasticsearch.index.mapper.MapperService in project crate by crate.

the class EngineTestCase method createMapperService.

public static MapperService createMapperService(String type) throws IOException {
    IndexMetadata indexMetadata = IndexMetadata.builder("test").settings(Settings.builder().put(IndexMetadata.SETTING_VERSION_CREATED, Version.CURRENT).put(IndexMetadata.SETTING_NUMBER_OF_SHARDS, 1).put(IndexMetadata.SETTING_NUMBER_OF_REPLICAS, 1)).putMapping(type, "{\"properties\": {}}").build();
    MapperService mapperService = MapperTestUtils.newMapperService(new NamedXContentRegistry(ClusterModule.getNamedXWriteables()), createTempDir(), Settings.EMPTY, "test");
    mapperService.merge(indexMetadata, MapperService.MergeReason.MAPPING_UPDATE);
    return mapperService;
}
Also used : IndexMetadata(org.elasticsearch.cluster.metadata.IndexMetadata) NamedXContentRegistry(org.elasticsearch.common.xcontent.NamedXContentRegistry) MapperService(org.elasticsearch.index.mapper.MapperService)

Example 43 with MapperService

use of org.elasticsearch.index.mapper.MapperService in project crate by crate.

the class InternalEngineTests method testNoOps.

/*
     * This test tests that a no-op does not generate a new sequence number, that no-ops can advance the local checkpoint, and that no-ops
     * are correctly added to the translog.
     */
@Test
public void testNoOps() throws IOException {
    engine.close();
    InternalEngine noOpEngine = null;
    final int maxSeqNo = randomIntBetween(0, 128);
    final int localCheckpoint = randomIntBetween(0, maxSeqNo);
    try {
        final BiFunction<Long, Long, LocalCheckpointTracker> supplier = (ms, lcp) -> new LocalCheckpointTracker(maxSeqNo, localCheckpoint);
        EngineConfig noopEngineConfig = copy(engine.config(), new SoftDeletesRetentionMergePolicy(Lucene.SOFT_DELETES_FIELD, () -> new MatchAllDocsQuery(), engine.config().getMergePolicy()));
        noOpEngine = new InternalEngine(noopEngineConfig, supplier) {

            @Override
            protected long doGenerateSeqNoForOperation(Operation operation) {
                throw new UnsupportedOperationException();
            }
        };
        noOpEngine.recoverFromTranslog(translogHandler, Long.MAX_VALUE);
        final int gapsFilled = noOpEngine.fillSeqNoGaps(primaryTerm.get());
        final String reason = "filling gaps";
        noOpEngine.noOp(new Engine.NoOp(maxSeqNo + 1, primaryTerm.get(), LOCAL_TRANSLOG_RECOVERY, System.nanoTime(), reason));
        assertThat(noOpEngine.getProcessedLocalCheckpoint(), equalTo((long) (maxSeqNo + 1)));
        assertThat(noOpEngine.getTranslog().stats().getUncommittedOperations(), equalTo(gapsFilled));
        noOpEngine.noOp(new Engine.NoOp(maxSeqNo + 2, primaryTerm.get(), randomFrom(PRIMARY, REPLICA, PEER_RECOVERY), System.nanoTime(), reason));
        assertThat(noOpEngine.getProcessedLocalCheckpoint(), equalTo((long) (maxSeqNo + 2)));
        assertThat(noOpEngine.getTranslog().stats().getUncommittedOperations(), equalTo(gapsFilled + 1));
        // skip to the op that we added to the translog
        Translog.Operation op;
        Translog.Operation last = null;
        try (Translog.Snapshot snapshot = noOpEngine.getTranslog().newSnapshot()) {
            while ((op = snapshot.next()) != null) {
                last = op;
            }
        }
        assertNotNull(last);
        assertThat(last, instanceOf(Translog.NoOp.class));
        final Translog.NoOp noOp = (Translog.NoOp) last;
        assertThat(noOp.seqNo(), equalTo((long) (maxSeqNo + 2)));
        assertThat(noOp.primaryTerm(), equalTo(primaryTerm.get()));
        assertThat(noOp.reason(), equalTo(reason));
        if (engine.engineConfig.getIndexSettings().isSoftDeleteEnabled()) {
            MapperService mapperService = createMapperService("test");
            List<Translog.Operation> operationsFromLucene = readAllOperationsInLucene(noOpEngine, mapperService);
            // fills n gap and 2 manual noop.
            assertThat(operationsFromLucene, hasSize(maxSeqNo + 2 - localCheckpoint));
            for (int i = 0; i < operationsFromLucene.size(); i++) {
                assertThat(operationsFromLucene.get(i), equalTo(new Translog.NoOp(localCheckpoint + 1 + i, primaryTerm.get(), "filling gaps")));
            }
            assertConsistentHistoryBetweenTranslogAndLuceneIndex(noOpEngine, mapperService);
        }
    } finally {
        IOUtils.close(noOpEngine);
    }
}
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) Matchers.containsString(org.hamcrest.Matchers.containsString) MatchAllDocsQuery(org.apache.lucene.search.MatchAllDocsQuery) LongPoint(org.apache.lucene.document.LongPoint) TestTranslog(org.elasticsearch.index.translog.TestTranslog) Translog(org.elasticsearch.index.translog.Translog) LocalCheckpointTracker(org.elasticsearch.index.seqno.LocalCheckpointTracker) SoftDeletesRetentionMergePolicy(org.apache.lucene.index.SoftDeletesRetentionMergePolicy) AtomicLong(java.util.concurrent.atomic.AtomicLong) MapperService(org.elasticsearch.index.mapper.MapperService) Test(org.junit.Test)

Example 44 with MapperService

use of org.elasticsearch.index.mapper.MapperService in project crate by crate.

the class InternalEngineTests method assertOperationHistoryInLucene.

private void assertOperationHistoryInLucene(List<Engine.Operation> operations) throws IOException {
    final MergePolicy keepSoftDeleteDocsMP = new SoftDeletesRetentionMergePolicy(Lucene.SOFT_DELETES_FIELD, MatchAllDocsQuery::new, engine.config().getMergePolicy());
    Settings.Builder settings = Settings.builder().put(defaultSettings.getSettings()).put(IndexSettings.INDEX_SOFT_DELETES_SETTING.getKey(), true).put(IndexSettings.INDEX_SOFT_DELETES_RETENTION_OPERATIONS_SETTING.getKey(), randomLongBetween(0, 10));
    final IndexMetadata indexMetadata = IndexMetadata.builder(defaultSettings.getIndexMetadata()).settings(settings).build();
    final IndexSettings indexSettings = IndexSettingsModule.newIndexSettings(indexMetadata);
    Set<Long> expectedSeqNos = new HashSet<>();
    try (Store store = createStore();
        Engine engine = createEngine(config(indexSettings, store, createTempDir(), keepSoftDeleteDocsMP, null))) {
        for (Engine.Operation op : operations) {
            if (op instanceof Engine.Index) {
                Engine.IndexResult indexResult = engine.index((Engine.Index) op);
                assertThat(indexResult.getFailure(), nullValue());
                expectedSeqNos.add(indexResult.getSeqNo());
            } else {
                Engine.DeleteResult deleteResult = engine.delete((Engine.Delete) op);
                assertThat(deleteResult.getFailure(), nullValue());
                expectedSeqNos.add(deleteResult.getSeqNo());
            }
            if (rarely()) {
                engine.refresh("test");
            }
            if (rarely()) {
                engine.flush();
            }
            if (rarely()) {
                engine.forceMerge(true, 1, false, false, false, UUIDs.randomBase64UUID());
            }
        }
        MapperService mapperService = createMapperService("test");
        List<Translog.Operation> actualOps = readAllOperationsInLucene(engine, mapperService);
        assertThat(actualOps.stream().map(o -> o.seqNo()).collect(Collectors.toList()), containsInAnyOrder(expectedSeqNos.toArray()));
        assertConsistentHistoryBetweenTranslogAndLuceneIndex(engine, mapperService);
    }
}
Also used : IndexSettings(org.elasticsearch.index.IndexSettings) Store(org.elasticsearch.index.store.Store) MatchAllDocsQuery(org.apache.lucene.search.MatchAllDocsQuery) SoftDeletesRetentionMergePolicy(org.apache.lucene.index.SoftDeletesRetentionMergePolicy) NoMergePolicy(org.apache.lucene.index.NoMergePolicy) MergePolicy(org.apache.lucene.index.MergePolicy) SoftDeletesRetentionMergePolicy(org.apache.lucene.index.SoftDeletesRetentionMergePolicy) LogDocMergePolicy(org.apache.lucene.index.LogDocMergePolicy) TieredMergePolicy(org.apache.lucene.index.TieredMergePolicy) LogByteSizeMergePolicy(org.apache.lucene.index.LogByteSizeMergePolicy) AtomicLong(java.util.concurrent.atomic.AtomicLong) IndexMetadata(org.elasticsearch.cluster.metadata.IndexMetadata) Settings(org.elasticsearch.common.settings.Settings) IndexSettings(org.elasticsearch.index.IndexSettings) MapperService(org.elasticsearch.index.mapper.MapperService) HashSet(java.util.HashSet)

Example 45 with MapperService

use of org.elasticsearch.index.mapper.MapperService in project crate by crate.

the class InternalEngineTests method testForceMergeWithSoftDeletesRetentionAndRecoverySource.

@Test
public void testForceMergeWithSoftDeletesRetentionAndRecoverySource() throws Exception {
    final long retainedExtraOps = randomLongBetween(0, 10);
    Settings.Builder settings = Settings.builder().put(defaultSettings.getSettings()).put(IndexSettings.INDEX_SOFT_DELETES_SETTING.getKey(), true).put(IndexSettings.INDEX_SOFT_DELETES_RETENTION_OPERATIONS_SETTING.getKey(), retainedExtraOps);
    final IndexMetadata indexMetadata = IndexMetadata.builder(defaultSettings.getIndexMetadata()).settings(settings).build();
    final IndexSettings indexSettings = IndexSettingsModule.newIndexSettings(indexMetadata);
    final AtomicLong globalCheckpoint = new AtomicLong(SequenceNumbers.NO_OPS_PERFORMED);
    final MapperService mapperService = createMapperService("test");
    final boolean omitSourceAllTheTime = randomBoolean();
    final Set<String> liveDocs = new HashSet<>();
    final Set<String> liveDocsWithSource = new HashSet<>();
    try (Store store = createStore();
        InternalEngine engine = createEngine(config(indexSettings, store, createTempDir(), newMergePolicy(), null, null, globalCheckpoint::get))) {
        int numDocs = scaledRandomIntBetween(10, 100);
        for (int i = 0; i < numDocs; i++) {
            boolean useRecoverySource = randomBoolean() || omitSourceAllTheTime;
            ParsedDocument doc = testParsedDocument(Integer.toString(i), null, testDocument(), B_1, null, useRecoverySource);
            engine.index(indexForDoc(doc));
            liveDocs.add(doc.id());
            if (useRecoverySource == false) {
                liveDocsWithSource.add(Integer.toString(i));
            }
        }
        for (int i = 0; i < numDocs; i++) {
            boolean useRecoverySource = randomBoolean() || omitSourceAllTheTime;
            ParsedDocument doc = testParsedDocument(Integer.toString(i), null, testDocument(), B_1, null, useRecoverySource);
            if (randomBoolean()) {
                engine.delete(new Engine.Delete(doc.id(), newUid(doc.id()), primaryTerm.get()));
                liveDocs.remove(doc.id());
                liveDocsWithSource.remove(doc.id());
            }
            if (randomBoolean()) {
                engine.index(indexForDoc(doc));
                liveDocs.add(doc.id());
                if (useRecoverySource == false) {
                    liveDocsWithSource.add(doc.id());
                } else {
                    liveDocsWithSource.remove(doc.id());
                }
            }
            if (randomBoolean()) {
                engine.flush(randomBoolean(), true);
            }
        }
        engine.flush();
        globalCheckpoint.set(randomLongBetween(0, engine.getPersistedLocalCheckpoint()));
        engine.syncTranslog();
        final long minSeqNoToRetain;
        try (Engine.IndexCommitRef safeCommit = engine.acquireSafeIndexCommit()) {
            long safeCommitLocalCheckpoint = Long.parseLong(safeCommit.getIndexCommit().getUserData().get(SequenceNumbers.LOCAL_CHECKPOINT_KEY));
            minSeqNoToRetain = Math.min(globalCheckpoint.get() + 1 - retainedExtraOps, safeCommitLocalCheckpoint + 1);
        }
        engine.forceMerge(true, 1, false, false, false, UUIDs.randomBase64UUID());
        assertConsistentHistoryBetweenTranslogAndLuceneIndex(engine, mapperService);
        Map<Long, Translog.Operation> ops = readAllOperationsInLucene(engine, mapperService).stream().collect(Collectors.toMap(Translog.Operation::seqNo, Function.identity()));
        for (long seqno = 0; seqno <= engine.getPersistedLocalCheckpoint(); seqno++) {
            String msg = "seq# [" + seqno + "], global checkpoint [" + globalCheckpoint + "], retained-ops [" + retainedExtraOps + "]";
            if (seqno < minSeqNoToRetain) {
                Translog.Operation op = ops.get(seqno);
                if (op != null) {
                    assertThat(op, instanceOf(Translog.Index.class));
                    assertThat(msg, ((Translog.Index) op).id(), isIn(liveDocs));
                }
            } else {
                Translog.Operation op = ops.get(seqno);
                assertThat(msg, op, notNullValue());
                if (op instanceof Translog.Index) {
                    assertEquals(msg, ((Translog.Index) op).source(), B_1);
                }
            }
        }
        settings.put(IndexSettings.INDEX_SOFT_DELETES_RETENTION_OPERATIONS_SETTING.getKey(), 0);
        indexSettings.updateIndexMetadata(IndexMetadata.builder(defaultSettings.getIndexMetadata()).settings(settings).build());
        engine.onSettingsChanged(indexSettings.getTranslogRetentionAge(), indexSettings.getTranslogRetentionSize(), indexSettings.getSoftDeleteRetentionOperations());
        // If we already merged down to 1 segment, then the next force-merge will be a noop. We need to add an extra segment to make
        // merges happen so we can verify that _recovery_source are pruned. See: https://github.com/elastic/elasticsearch/issues/41628.
        final int numSegments;
        try (Engine.Searcher searcher = engine.acquireSearcher("test", Engine.SearcherScope.INTERNAL)) {
            numSegments = searcher.getDirectoryReader().leaves().size();
        }
        if (numSegments == 1) {
            boolean useRecoverySource = randomBoolean() || omitSourceAllTheTime;
            ParsedDocument doc = testParsedDocument("dummy", null, testDocument(), B_1, null, useRecoverySource);
            engine.index(indexForDoc(doc));
            if (useRecoverySource == false) {
                liveDocsWithSource.add(doc.id());
            }
            engine.syncTranslog();
            globalCheckpoint.set(engine.getPersistedLocalCheckpoint());
            engine.flush(randomBoolean(), true);
        } else {
            globalCheckpoint.set(engine.getPersistedLocalCheckpoint());
            engine.syncTranslog();
        }
        engine.forceMerge(true, 1, false, false, false, UUIDs.randomBase64UUID());
        assertConsistentHistoryBetweenTranslogAndLuceneIndex(engine, mapperService);
        assertThat(readAllOperationsInLucene(engine, mapperService), hasSize(liveDocsWithSource.size()));
    }
}
Also used : IndexSettings(org.elasticsearch.index.IndexSettings) Store(org.elasticsearch.index.store.Store) Matchers.containsString(org.hamcrest.Matchers.containsString) TestTranslog(org.elasticsearch.index.translog.TestTranslog) Translog(org.elasticsearch.index.translog.Translog) ParsedDocument(org.elasticsearch.index.mapper.ParsedDocument) IndexMetadata(org.elasticsearch.cluster.metadata.IndexMetadata) Settings(org.elasticsearch.common.settings.Settings) IndexSettings(org.elasticsearch.index.IndexSettings) HashSet(java.util.HashSet) Searcher(org.elasticsearch.index.engine.Engine.Searcher) LongPoint(org.apache.lucene.document.LongPoint) AtomicLong(java.util.concurrent.atomic.AtomicLong) AtomicLong(java.util.concurrent.atomic.AtomicLong) MapperService(org.elasticsearch.index.mapper.MapperService) Test(org.junit.Test)

Aggregations

MapperService (org.elasticsearch.index.mapper.MapperService)46 Settings (org.elasticsearch.common.settings.Settings)16 DocumentMapper (org.elasticsearch.index.mapper.DocumentMapper)14 IndexSettings (org.elasticsearch.index.IndexSettings)13 CompressedXContent (org.elasticsearch.common.compress.CompressedXContent)12 IOException (java.io.IOException)10 Store (org.elasticsearch.index.store.Store)9 Matchers.containsString (org.hamcrest.Matchers.containsString)9 IndexMetadata (org.elasticsearch.cluster.metadata.IndexMetadata)8 Index (org.elasticsearch.index.Index)8 ParsedDocument (org.elasticsearch.index.mapper.ParsedDocument)8 HashMap (java.util.HashMap)7 Map (java.util.Map)7 IndexService (org.elasticsearch.index.IndexService)7 AtomicLong (java.util.concurrent.atomic.AtomicLong)6 IndexAnalyzers (org.elasticsearch.index.analysis.IndexAnalyzers)6 Collections (java.util.Collections)5 HashSet (java.util.HashSet)5 List (java.util.List)5 Analyzer (org.apache.lucene.analysis.Analyzer)5