Search in sources :

Example 11 with IndicesService

use of org.opensearch.indices.IndicesService in project OpenSearch by opensearch-project.

the class IndexShard method startRecovery.

public void startRecovery(RecoveryState recoveryState, PeerRecoveryTargetService recoveryTargetService, RecoveryListener recoveryListener, RepositoriesService repositoriesService, Consumer<MappingMetadata> mappingUpdateConsumer, IndicesService indicesService) {
    // }
    assert recoveryState.getRecoverySource().equals(shardRouting.recoverySource());
    switch(recoveryState.getRecoverySource().getType()) {
        case EMPTY_STORE:
        case EXISTING_STORE:
            executeRecovery("from store", recoveryState, recoveryListener, this::recoverFromStore);
            break;
        case PEER:
            try {
                markAsRecovering("from " + recoveryState.getSourceNode(), recoveryState);
                recoveryTargetService.startRecovery(this, recoveryState.getSourceNode(), recoveryListener);
            } catch (Exception e) {
                failShard("corrupted preexisting index", e);
                recoveryListener.onFailure(recoveryState, new RecoveryFailedException(recoveryState, null, e), true);
            }
            break;
        case SNAPSHOT:
            final String repo = ((SnapshotRecoverySource) recoveryState.getRecoverySource()).snapshot().getRepository();
            executeRecovery("from snapshot", recoveryState, recoveryListener, l -> restoreFromRepository(repositoriesService.repository(repo), l));
            break;
        case LOCAL_SHARDS:
            final IndexMetadata indexMetadata = indexSettings().getIndexMetadata();
            final Index resizeSourceIndex = indexMetadata.getResizeSourceIndex();
            final List<IndexShard> startedShards = new ArrayList<>();
            final IndexService sourceIndexService = indicesService.indexService(resizeSourceIndex);
            final Set<ShardId> requiredShards;
            final int numShards;
            if (sourceIndexService != null) {
                requiredShards = IndexMetadata.selectRecoverFromShards(shardId().id(), sourceIndexService.getMetadata(), indexMetadata.getNumberOfShards());
                for (IndexShard shard : sourceIndexService) {
                    if (shard.state() == IndexShardState.STARTED && requiredShards.contains(shard.shardId())) {
                        startedShards.add(shard);
                    }
                }
                numShards = requiredShards.size();
            } else {
                numShards = -1;
                requiredShards = Collections.emptySet();
            }
            if (numShards == startedShards.size()) {
                assert requiredShards.isEmpty() == false;
                executeRecovery("from local shards", recoveryState, recoveryListener, l -> recoverFromLocalShards(mappingUpdateConsumer, startedShards.stream().filter((s) -> requiredShards.contains(s.shardId())).collect(Collectors.toList()), l));
            } else {
                final RuntimeException e;
                if (numShards == -1) {
                    e = new IndexNotFoundException(resizeSourceIndex);
                } else {
                    e = new IllegalStateException("not all required shards of index " + resizeSourceIndex + " are started yet, expected " + numShards + " found " + startedShards.size() + " can't recover shard " + shardId());
                }
                throw e;
            }
            break;
        default:
            throw new IllegalArgumentException("Unknown recovery source " + recoveryState.getRecoverySource());
    }
}
Also used : Query(org.apache.lucene.search.Query) SeqNoStats(org.opensearch.index.seqno.SeqNoStats) SequenceNumbers(org.opensearch.index.seqno.SequenceNumbers) Arrays(java.util.Arrays) LongSupplier(java.util.function.LongSupplier) CheckedFunction(org.opensearch.common.CheckedFunction) SnapshotRecoverySource(org.opensearch.cluster.routing.RecoverySource.SnapshotRecoverySource) SearchStats(org.opensearch.index.search.stats.SearchStats) MetadataSnapshot(org.opensearch.index.store.Store.MetadataSnapshot) Term(org.apache.lucene.index.Term) AlreadyClosedException(org.apache.lucene.store.AlreadyClosedException) ReferenceManager(org.apache.lucene.search.ReferenceManager) DocumentMapperForType(org.opensearch.index.mapper.DocumentMapperForType) MergeStats(org.opensearch.index.merge.MergeStats) UsageTrackingQueryCachingPolicy(org.apache.lucene.search.UsageTrackingQueryCachingPolicy) WriteStateException(org.opensearch.gateway.WriteStateException) RecoveryState(org.opensearch.indices.recovery.RecoveryState) RefreshFailedEngineException(org.opensearch.index.engine.RefreshFailedEngineException) Map(java.util.Map) Lucene(org.opensearch.common.lucene.Lucene) ObjectLongMap(com.carrotsearch.hppc.ObjectLongMap) QueryCachingPolicy(org.apache.lucene.search.QueryCachingPolicy) ActionListener(org.opensearch.action.ActionListener) GetResult(org.opensearch.index.engine.Engine.GetResult) IndexModule(org.opensearch.index.IndexModule) Segment(org.opensearch.index.engine.Segment) EnumSet(java.util.EnumSet) Repository(org.opensearch.repositories.Repository) TimeValue(org.opensearch.common.unit.TimeValue) ShardRequestCache(org.opensearch.index.cache.request.ShardRequestCache) Index(org.opensearch.index.Index) ExceptionsHelper(org.opensearch.ExceptionsHelper) Set(java.util.Set) Settings(org.opensearch.common.settings.Settings) ReplicationTracker(org.opensearch.index.seqno.ReplicationTracker) ShardBitsetFilterCache(org.opensearch.index.cache.bitset.ShardBitsetFilterCache) GetStats(org.opensearch.index.get.GetStats) StandardCharsets(java.nio.charset.StandardCharsets) Engine(org.opensearch.index.engine.Engine) ClosedByInterruptException(java.nio.channels.ClosedByInterruptException) CountDownLatch(java.util.concurrent.CountDownLatch) VersionType(org.opensearch.index.VersionType) Logger(org.apache.logging.log4j.Logger) EngineConfigFactory(org.opensearch.index.engine.EngineConfigFactory) CheckedRunnable(org.opensearch.common.CheckedRunnable) ThreadInterruptedException(org.apache.lucene.util.ThreadInterruptedException) CopyOnWriteArrayList(java.util.concurrent.CopyOnWriteArrayList) IndexCommit(org.apache.lucene.index.IndexCommit) ShardFieldData(org.opensearch.index.fielddata.ShardFieldData) RepositoriesService(org.opensearch.repositories.RepositoriesService) CodecService(org.opensearch.index.codec.CodecService) FlushRequest(org.opensearch.action.admin.indices.flush.FlushRequest) ThreadPool(org.opensearch.threadpool.ThreadPool) Releasable(org.opensearch.common.lease.Releasable) MeanMetric(org.opensearch.common.metrics.MeanMetric) Supplier(java.util.function.Supplier) ArrayList(java.util.ArrayList) RecoverySource(org.opensearch.cluster.routing.RecoverySource) UNASSIGNED_SEQ_NO(org.opensearch.index.seqno.SequenceNumbers.UNASSIGNED_SEQ_NO) FilterDirectoryReader(org.apache.lucene.index.FilterDirectoryReader) LegacyESVersion(org.opensearch.LegacyESVersion) Mapping(org.opensearch.index.mapper.Mapping) Booleans(org.opensearch.common.Booleans) ReplicationCheckpoint(org.opensearch.indices.replication.checkpoint.ReplicationCheckpoint) BiConsumer(java.util.function.BiConsumer) ParsedDocument(org.opensearch.index.mapper.ParsedDocument) RetentionLeaseStats(org.opensearch.index.seqno.RetentionLeaseStats) StreamSupport(java.util.stream.StreamSupport) CommitStats(org.opensearch.index.engine.CommitStats) EngineFactory(org.opensearch.index.engine.EngineFactory) PublishCheckpointRequest(org.opensearch.indices.replication.checkpoint.PublishCheckpointRequest) CompletionStats(org.opensearch.search.suggest.completion.CompletionStats) SetOnce(org.apache.lucene.util.SetOnce) RecoveryFailedException(org.opensearch.indices.recovery.RecoveryFailedException) PendingReplicationActions(org.opensearch.action.support.replication.PendingReplicationActions) RETAIN_ALL(org.opensearch.index.seqno.RetentionLeaseActions.RETAIN_ALL) FlushStats(org.opensearch.index.flush.FlushStats) IOException(java.io.IOException) BytesStreamOutput(org.opensearch.common.io.stream.BytesStreamOutput) IndexService(org.opensearch.index.IndexService) XContentHelper(org.opensearch.common.xcontent.XContentHelper) AtomicLong(java.util.concurrent.atomic.AtomicLong) RecoveryStats(org.opensearch.index.recovery.RecoveryStats) RetentionLeases(org.opensearch.index.seqno.RetentionLeases) CounterMetric(org.opensearch.common.metrics.CounterMetric) ShardIndexWarmerService(org.opensearch.index.warmer.ShardIndexWarmerService) RetentionLeaseSyncer(org.opensearch.index.seqno.RetentionLeaseSyncer) SafeCommitInfo(org.opensearch.index.engine.SafeCommitInfo) EngineException(org.opensearch.index.engine.EngineException) ReadOnlyEngine(org.opensearch.index.engine.ReadOnlyEngine) IdFieldMapper(org.opensearch.index.mapper.IdFieldMapper) AbstractRunnable(org.opensearch.common.util.concurrent.AbstractRunnable) FieldDataStats(org.opensearch.index.fielddata.FieldDataStats) TimeoutException(java.util.concurrent.TimeoutException) OpenSearchException(org.opensearch.OpenSearchException) ThreadContext(org.opensearch.common.util.concurrent.ThreadContext) Releasables(org.opensearch.common.lease.Releasables) UpgradeRequest(org.opensearch.action.admin.indices.upgrade.post.UpgradeRequest) RunOnce(org.opensearch.common.util.concurrent.RunOnce) ForceMergeRequest(org.opensearch.action.admin.indices.forcemerge.ForceMergeRequest) MapperService(org.opensearch.index.mapper.MapperService) RefreshStats(org.opensearch.index.refresh.RefreshStats) RecoveryListener(org.opensearch.indices.recovery.RecoveryListener) Locale(java.util.Locale) Assertions(org.opensearch.Assertions) SegmentsStats(org.opensearch.index.engine.SegmentsStats) SegmentReplicationCheckpointPublisher(org.opensearch.indices.replication.checkpoint.SegmentReplicationCheckpointPublisher) IndexShardRoutingTable(org.opensearch.cluster.routing.IndexShardRoutingTable) IndicesClusterStateService(org.opensearch.indices.cluster.IndicesClusterStateService) CheckIndex(org.apache.lucene.index.CheckIndex) Sort(org.apache.lucene.search.Sort) DirectoryReader(org.apache.lucene.index.DirectoryReader) IndicesService(org.opensearch.indices.IndicesService) TranslogConfig(org.opensearch.index.translog.TranslogConfig) IndexingMemoryController(org.opensearch.indices.IndexingMemoryController) RestStatus(org.opensearch.rest.RestStatus) Store(org.opensearch.index.store.Store) Collectors(java.util.stream.Collectors) SegmentInfos(org.apache.lucene.index.SegmentInfos) Nullable(org.opensearch.common.Nullable) Tuple(org.opensearch.common.collect.Tuple) WarmerStats(org.opensearch.index.warmer.WarmerStats) Objects(java.util.Objects) GatedCloseable(org.opensearch.common.concurrent.GatedCloseable) List(java.util.List) ResyncTask(org.opensearch.index.shard.PrimaryReplicaSyncer.ResyncTask) LeafReader(org.apache.lucene.index.LeafReader) IndexSettings(org.opensearch.index.IndexSettings) ReplicationResponse(org.opensearch.action.support.replication.ReplicationResponse) Optional(java.util.Optional) BigArrays(org.opensearch.common.util.BigArrays) Uid(org.opensearch.index.mapper.Uid) TranslogStats(org.opensearch.index.translog.TranslogStats) MappingMetadata(org.opensearch.cluster.metadata.MappingMetadata) IndexMetadata(org.opensearch.cluster.metadata.IndexMetadata) ShardSearchStats(org.opensearch.index.search.stats.ShardSearchStats) ActionRunnable(org.opensearch.action.ActionRunnable) SimilarityService(org.opensearch.index.similarity.SimilarityService) CheckedConsumer(org.opensearch.common.CheckedConsumer) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) ByteSizeValue(org.opensearch.common.unit.ByteSizeValue) EngineConfig(org.opensearch.index.engine.EngineConfig) ParameterizedMessage(org.apache.logging.log4j.message.ParameterizedMessage) AtomicReference(java.util.concurrent.atomic.AtomicReference) Function(java.util.function.Function) HashSet(java.util.HashSet) SourceToParse(org.opensearch.index.mapper.SourceToParse) AsyncIOProcessor(org.opensearch.common.util.concurrent.AsyncIOProcessor) PeerRecoveryTargetService(org.opensearch.indices.recovery.PeerRecoveryTargetService) Translog(org.opensearch.index.translog.Translog) StoreFileMetadata(org.opensearch.index.store.StoreFileMetadata) StoreStats(org.opensearch.index.store.StoreStats) RetentionLease(org.opensearch.index.seqno.RetentionLease) PrintStream(java.io.PrintStream) OpenSearchDirectoryReader(org.opensearch.common.lucene.index.OpenSearchDirectoryReader) RecoveryTarget(org.opensearch.indices.recovery.RecoveryTarget) IndexNotFoundException(org.opensearch.index.IndexNotFoundException) IndexCache(org.opensearch.index.cache.IndexCache) DocumentMapper(org.opensearch.index.mapper.DocumentMapper) RootObjectMapper(org.opensearch.index.mapper.RootObjectMapper) ShardRouting(org.opensearch.cluster.routing.ShardRouting) IOUtils(org.opensearch.core.internal.io.IOUtils) TimeUnit(java.util.concurrent.TimeUnit) Consumer(java.util.function.Consumer) ShardGetService(org.opensearch.index.get.ShardGetService) CircuitBreakerService(org.opensearch.indices.breaker.CircuitBreakerService) Closeable(java.io.Closeable) Collections(java.util.Collections) IndexService(org.opensearch.index.IndexService) CopyOnWriteArrayList(java.util.concurrent.CopyOnWriteArrayList) ArrayList(java.util.ArrayList) Index(org.opensearch.index.Index) CheckIndex(org.apache.lucene.index.CheckIndex) AlreadyClosedException(org.apache.lucene.store.AlreadyClosedException) WriteStateException(org.opensearch.gateway.WriteStateException) RefreshFailedEngineException(org.opensearch.index.engine.RefreshFailedEngineException) ClosedByInterruptException(java.nio.channels.ClosedByInterruptException) ThreadInterruptedException(org.apache.lucene.util.ThreadInterruptedException) RecoveryFailedException(org.opensearch.indices.recovery.RecoveryFailedException) IOException(java.io.IOException) EngineException(org.opensearch.index.engine.EngineException) TimeoutException(java.util.concurrent.TimeoutException) OpenSearchException(org.opensearch.OpenSearchException) IndexNotFoundException(org.opensearch.index.IndexNotFoundException) ReplicationCheckpoint(org.opensearch.indices.replication.checkpoint.ReplicationCheckpoint) RecoveryFailedException(org.opensearch.indices.recovery.RecoveryFailedException) IndexNotFoundException(org.opensearch.index.IndexNotFoundException) IndexMetadata(org.opensearch.cluster.metadata.IndexMetadata)

Example 12 with IndicesService

use of org.opensearch.indices.IndicesService in project OpenSearch by opensearch-project.

the class GetIndexActionTests method setUp.

@Before
public void setUp() throws Exception {
    super.setUp();
    settingsFilter = new SettingsModule(Settings.EMPTY, emptyList(), emptyList(), emptySet()).getSettingsFilter();
    threadPool = new TestThreadPool("GetIndexActionTests");
    clusterService = getInstanceFromNode(ClusterService.class);
    indicesService = getInstanceFromNode(IndicesService.class);
    CapturingTransport capturingTransport = new CapturingTransport();
    transportService = capturingTransport.createTransportService(clusterService.getSettings(), threadPool, TransportService.NOOP_TRANSPORT_INTERCEPTOR, boundAddress -> clusterService.localNode(), null, emptySet());
    transportService.start();
    transportService.acceptIncomingRequests();
    getIndexAction = new GetIndexActionTests.TestTransportGetIndexAction();
}
Also used : SettingsFilter(org.opensearch.common.settings.SettingsFilter) OpenSearchSingleNodeTestCase(org.opensearch.test.OpenSearchSingleNodeTestCase) Collections.emptySet(java.util.Collections.emptySet) IndexScopedSettings(org.opensearch.common.settings.IndexScopedSettings) Index(org.opensearch.index.Index) Collections.emptyList(java.util.Collections.emptyList) ThreadPool(org.opensearch.threadpool.ThreadPool) IndicesService(org.opensearch.indices.IndicesService) TestThreadPool(org.opensearch.threadpool.TestThreadPool) Settings(org.opensearch.common.settings.Settings) ThreadContext(org.opensearch.common.util.concurrent.ThreadContext) TransportService(org.opensearch.transport.TransportService) ClusterStateCreationUtils(org.opensearch.action.support.replication.ClusterStateCreationUtils) TimeUnit(java.util.concurrent.TimeUnit) IndicesRequest(org.opensearch.action.IndicesRequest) ActionFilters(org.opensearch.action.support.ActionFilters) SettingsModule(org.opensearch.common.settings.SettingsModule) ClusterState(org.opensearch.cluster.ClusterState) After(org.junit.After) ClusterService(org.opensearch.cluster.service.ClusterService) ActionListener(org.opensearch.action.ActionListener) CapturingTransport(org.opensearch.test.transport.CapturingTransport) IndexNameExpressionResolver(org.opensearch.cluster.metadata.IndexNameExpressionResolver) Before(org.junit.Before) ClusterService(org.opensearch.cluster.service.ClusterService) CapturingTransport(org.opensearch.test.transport.CapturingTransport) SettingsModule(org.opensearch.common.settings.SettingsModule) IndicesService(org.opensearch.indices.IndicesService) TestThreadPool(org.opensearch.threadpool.TestThreadPool) Before(org.junit.Before)

Example 13 with IndicesService

use of org.opensearch.indices.IndicesService in project OpenSearch by opensearch-project.

the class ShrinkIndexIT method testShrinkCommitsMergeOnIdle.

public void testShrinkCommitsMergeOnIdle() throws Exception {
    prepareCreate("source").setSettings(Settings.builder().put(indexSettings()).put("index.number_of_replicas", 0).put("number_of_shards", 5)).get();
    for (int i = 0; i < 30; i++) {
        client().prepareIndex("source").setSource("{\"foo\" : \"bar\", \"i\" : " + i + "}", XContentType.JSON).get();
    }
    client().admin().indices().prepareFlush("source").get();
    ImmutableOpenMap<String, DiscoveryNode> dataNodes = client().admin().cluster().prepareState().get().getState().nodes().getDataNodes();
    DiscoveryNode[] discoveryNodes = dataNodes.values().toArray(DiscoveryNode.class);
    // ensure all shards are allocated otherwise the ensure green below might not succeed since we require the merge node
    // if we change the setting too quickly we will end up with one replica unassigned which can't be assigned anymore due
    // to the require._name below.
    ensureGreen();
    // relocate all shards to one node such that we can merge it.
    client().admin().indices().prepareUpdateSettings("source").setSettings(Settings.builder().put("index.routing.allocation.require._name", discoveryNodes[0].getName()).put("index.blocks.write", true)).get();
    ensureGreen();
    IndicesSegmentResponse sourceStats = client().admin().indices().prepareSegments("source").get();
    // disable rebalancing to be able to capture the right stats. balancing can move the target primary
    // making it hard to pin point the source shards.
    client().admin().cluster().prepareUpdateSettings().setTransientSettings(Settings.builder().put(EnableAllocationDecider.CLUSTER_ROUTING_REBALANCE_ENABLE_SETTING.getKey(), "none")).get();
    // now merge source into a single shard index
    assertAcked(client().admin().indices().prepareResizeIndex("source", "target").setSettings(Settings.builder().put("index.number_of_replicas", 0).build()).get());
    ensureGreen();
    ClusterStateResponse clusterStateResponse = client().admin().cluster().prepareState().get();
    IndexMetadata target = clusterStateResponse.getState().getMetadata().index("target");
    client().admin().indices().prepareForceMerge("target").setMaxNumSegments(1).setFlush(false).get();
    IndicesSegmentResponse targetSegStats = client().admin().indices().prepareSegments("target").get();
    ShardSegments segmentsStats = targetSegStats.getIndices().get("target").getShards().get(0).getShards()[0];
    assertTrue(segmentsStats.getNumberOfCommitted() > 0);
    assertNotEquals(segmentsStats.getSegments(), segmentsStats.getNumberOfCommitted());
    Iterable<IndicesService> dataNodeInstances = internalCluster().getDataNodeInstances(IndicesService.class);
    for (IndicesService service : dataNodeInstances) {
        if (service.hasIndex(target.getIndex())) {
            IndexService indexShards = service.indexService(target.getIndex());
            IndexShard shard = indexShards.getShard(0);
            assertTrue(shard.isActive());
            shard.flushOnIdle(0);
            assertFalse(shard.isActive());
        }
    }
    assertBusy(() -> {
        IndicesSegmentResponse targetStats = client().admin().indices().prepareSegments("target").get();
        ShardSegments targetShardSegments = targetStats.getIndices().get("target").getShards().get(0).getShards()[0];
        Map<Integer, IndexShardSegments> source = sourceStats.getIndices().get("source").getShards();
        int numSourceSegments = 0;
        for (IndexShardSegments s : source.values()) {
            numSourceSegments += s.getAt(0).getNumberOfCommitted();
        }
        assertTrue(targetShardSegments.getSegments().size() < numSourceSegments);
        assertEquals(targetShardSegments.getNumberOfCommitted(), targetShardSegments.getNumberOfSearch());
        assertEquals(targetShardSegments.getNumberOfCommitted(), targetShardSegments.getSegments().size());
        assertEquals(1, targetShardSegments.getSegments().size());
    });
    // clean up
    client().admin().cluster().prepareUpdateSettings().setTransientSettings(Settings.builder().put(EnableAllocationDecider.CLUSTER_ROUTING_REBALANCE_ENABLE_SETTING.getKey(), (String) null)).get();
}
Also used : DiscoveryNode(org.opensearch.cluster.node.DiscoveryNode) IndexService(org.opensearch.index.IndexService) ClusterStateResponse(org.opensearch.action.admin.cluster.state.ClusterStateResponse) IndexShard(org.opensearch.index.shard.IndexShard) IndicesService(org.opensearch.indices.IndicesService) IndicesSegmentResponse(org.opensearch.action.admin.indices.segments.IndicesSegmentResponse) Matchers.containsString(org.hamcrest.Matchers.containsString) IndexShardSegments(org.opensearch.action.admin.indices.segments.IndexShardSegments) ShardSegments(org.opensearch.action.admin.indices.segments.ShardSegments) IndexShardSegments(org.opensearch.action.admin.indices.segments.IndexShardSegments) IndexMetadata(org.opensearch.cluster.metadata.IndexMetadata)

Example 14 with IndicesService

use of org.opensearch.indices.IndicesService in project OpenSearch by opensearch-project.

the class TransportSearchIT method testSearchIdle.

public void testSearchIdle() throws Exception {
    int numOfReplicas = randomIntBetween(0, 1);
    internalCluster().ensureAtLeastNumDataNodes(numOfReplicas + 1);
    final Settings.Builder settings = Settings.builder().put(IndexMetadata.SETTING_NUMBER_OF_SHARDS, randomIntBetween(1, 5)).put(IndexMetadata.SETTING_NUMBER_OF_REPLICAS, numOfReplicas).put(IndexSettings.INDEX_SEARCH_IDLE_AFTER.getKey(), TimeValue.timeValueMillis(randomIntBetween(50, 500)));
    assertAcked(prepareCreate("test").setSettings(settings).setMapping("created_date", "type=date,format=yyyy-MM-dd"));
    ensureGreen("test");
    assertBusy(() -> {
        for (String node : internalCluster().nodesInclude("test")) {
            final IndicesService indicesService = internalCluster().getInstance(IndicesService.class, node);
            for (IndexShard indexShard : indicesService.indexServiceSafe(resolveIndex("test"))) {
                assertTrue(indexShard.isSearchIdle());
            }
        }
    });
    client().prepareIndex("test").setId("1").setSource("created_date", "2020-01-01").get();
    client().prepareIndex("test").setId("2").setSource("created_date", "2020-01-02").get();
    client().prepareIndex("test").setId("3").setSource("created_date", "2020-01-03").get();
    assertBusy(() -> {
        SearchResponse resp = client().prepareSearch("test").setQuery(new RangeQueryBuilder("created_date").gte("2020-01-02").lte("2020-01-03")).setPreFilterShardSize(randomIntBetween(1, 3)).get();
        assertThat(resp.getHits().getTotalHits().value, equalTo(2L));
    });
}
Also used : IndexShard(org.opensearch.index.shard.IndexShard) IndicesService(org.opensearch.indices.IndicesService) Matchers.containsString(org.hamcrest.Matchers.containsString) RangeQueryBuilder(org.opensearch.index.query.RangeQueryBuilder) Settings(org.opensearch.common.settings.Settings) IndexSettings(org.opensearch.index.IndexSettings)

Example 15 with IndicesService

use of org.opensearch.indices.IndicesService in project OpenSearch by opensearch-project.

the class MetadataIndexTemplateService method addComponentTemplate.

// Package visible for testing
ClusterState addComponentTemplate(final ClusterState currentState, final boolean create, final String name, final ComponentTemplate template) throws Exception {
    final ComponentTemplate existing = currentState.metadata().componentTemplates().get(name);
    if (create && existing != null) {
        throw new IllegalArgumentException("component template [" + name + "] already exists");
    }
    CompressedXContent mappings = template.template().mappings();
    String stringMappings = mappings == null ? null : mappings.string();
    // We may need to normalize index settings, so do that also
    Settings finalSettings = template.template().settings();
    if (finalSettings != null) {
        finalSettings = Settings.builder().put(finalSettings).normalizePrefix(IndexMetadata.INDEX_SETTING_PREFIX).build();
    }
    // Collect all the composable (index) templates that use this component template, we'll use
    // this for validating that they're still going to be valid after this component template
    // has been updated
    final Map<String, ComposableIndexTemplate> templatesUsingComponent = currentState.metadata().templatesV2().entrySet().stream().filter(e -> e.getValue().composedOf().contains(name)).collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
    // if we're updating a component template, let's check if it's part of any V2 template that will yield the CT update invalid
    if (create == false && finalSettings != null) {
        // if the CT is specifying the `index.hidden` setting it cannot be part of any global template
        if (IndexMetadata.INDEX_HIDDEN_SETTING.exists(finalSettings)) {
            List<String> globalTemplatesThatUseThisComponent = new ArrayList<>();
            for (Map.Entry<String, ComposableIndexTemplate> entry : templatesUsingComponent.entrySet()) {
                ComposableIndexTemplate templateV2 = entry.getValue();
                if (templateV2.indexPatterns().stream().anyMatch(Regex::isMatchAllPattern)) {
                    // global templates don't support configuring the `index.hidden` setting so we don't need to resolve the settings as
                    // no other component template can remove this setting from the resolved settings, so just invalidate this update
                    globalTemplatesThatUseThisComponent.add(entry.getKey());
                }
            }
            if (globalTemplatesThatUseThisComponent.isEmpty() == false) {
                throw new IllegalArgumentException("cannot update component template [" + name + "] because the following global templates would resolve to specifying the [" + IndexMetadata.SETTING_INDEX_HIDDEN + "] setting: [" + String.join(",", globalTemplatesThatUseThisComponent) + "]");
            }
        }
    }
    // Mappings in component templates don't include _doc, so update the mappings to include this single type
    if (stringMappings != null) {
        Map<String, Object> parsedMappings = MapperService.parseMapping(xContentRegistry, stringMappings);
        if (parsedMappings.size() > 0) {
            stringMappings = Strings.toString(XContentFactory.jsonBuilder().startObject().field(MapperService.SINGLE_MAPPING_NAME, parsedMappings).endObject());
        }
    }
    final Template finalTemplate = new Template(finalSettings, stringMappings == null ? null : new CompressedXContent(stringMappings), template.template().aliases());
    final ComponentTemplate finalComponentTemplate = new ComponentTemplate(finalTemplate, template.version(), template.metadata());
    if (finalComponentTemplate.equals(existing)) {
        return currentState;
    }
    validateTemplate(finalSettings, stringMappings, indicesService, xContentRegistry);
    validate(name, finalComponentTemplate);
    // Validate all composable index templates that use this component template
    if (templatesUsingComponent.size() > 0) {
        ClusterState tempStateWithComponentTemplateAdded = ClusterState.builder(currentState).metadata(Metadata.builder(currentState.metadata()).put(name, finalComponentTemplate)).build();
        Exception validationFailure = null;
        for (Map.Entry<String, ComposableIndexTemplate> entry : templatesUsingComponent.entrySet()) {
            final String composableTemplateName = entry.getKey();
            final ComposableIndexTemplate composableTemplate = entry.getValue();
            try {
                validateCompositeTemplate(tempStateWithComponentTemplateAdded, composableTemplateName, composableTemplate, indicesService, xContentRegistry);
            } catch (Exception e) {
                if (validationFailure == null) {
                    validationFailure = new IllegalArgumentException("updating component template [" + name + "] results in invalid composable template [" + composableTemplateName + "] after templates are merged", e);
                } else {
                    validationFailure.addSuppressed(e);
                }
            }
        }
        if (validationFailure != null) {
            throw validationFailure;
        }
    }
    logger.info("{} component template [{}]", existing == null ? "adding" : "updating", name);
    return ClusterState.builder(currentState).metadata(Metadata.builder(currentState.metadata()).put(name, finalComponentTemplate)).build();
}
Also used : NO_LONGER_ASSIGNED(org.opensearch.indices.cluster.IndicesClusterStateService.AllocatedIndices.IndexRemovalReason.NO_LONGER_ASSIGNED) IndexScopedSettings(org.opensearch.common.settings.IndexScopedSettings) Version(org.opensearch.Version) Regex(org.opensearch.common.regex.Regex) Strings(org.opensearch.common.Strings) ObjectObjectCursor(com.carrotsearch.hppc.cursors.ObjectObjectCursor) MasterNodeRequest(org.opensearch.action.support.master.MasterNodeRequest) Operations(org.apache.lucene.util.automaton.Operations) MapperService(org.opensearch.index.mapper.MapperService) Alias(org.opensearch.action.admin.indices.alias.Alias) Locale(java.util.Locale) Map(java.util.Map) XContentFactory(org.opensearch.common.xcontent.XContentFactory) Inject(org.opensearch.common.inject.Inject) ActionListener(org.opensearch.action.ActionListener) HeaderWarning(org.opensearch.common.logging.HeaderWarning) TimeValue(org.opensearch.common.unit.TimeValue) Automaton(org.apache.lucene.util.automaton.Automaton) Index(org.opensearch.index.Index) Predicate(java.util.function.Predicate) MetadataCreateDataStreamService.validateTimestampFieldMapping(org.opensearch.cluster.metadata.MetadataCreateDataStreamService.validateTimestampFieldMapping) IndicesService(org.opensearch.indices.IndicesService) Set(java.util.Set) Settings(org.opensearch.common.settings.Settings) ObjectCursor(com.carrotsearch.hppc.cursors.ObjectCursor) Collectors(java.util.stream.Collectors) Nullable(org.opensearch.common.Nullable) ValidationException(org.opensearch.common.ValidationException) UncheckedIOException(java.io.UncheckedIOException) Objects(java.util.Objects) List(java.util.List) Logger(org.apache.logging.log4j.Logger) ClusterStateUpdateTask(org.opensearch.cluster.ClusterStateUpdateTask) Optional(java.util.Optional) XContentType(org.opensearch.common.xcontent.XContentType) IndexTemplateMissingException(org.opensearch.indices.IndexTemplateMissingException) BytesReference(org.opensearch.common.bytes.BytesReference) MapperParsingException(org.opensearch.index.mapper.MapperParsingException) CompressedXContent(org.opensearch.common.compress.CompressedXContent) Priority(org.opensearch.common.Priority) HashMap(java.util.HashMap) Function(java.util.function.Function) TreeSet(java.util.TreeSet) ArrayList(java.util.ArrayList) HashSet(java.util.HashSet) ClusterState(org.opensearch.cluster.ClusterState) UUIDs(org.opensearch.common.UUIDs) LinkedList(java.util.LinkedList) IOException(java.io.IOException) IndexService(org.opensearch.index.IndexService) CollectionUtil(org.apache.lucene.util.CollectionUtil) AcknowledgedResponse(org.opensearch.action.support.master.AcknowledgedResponse) XContentBuilder(org.opensearch.common.xcontent.XContentBuilder) Sets(org.opensearch.common.util.set.Sets) MergeReason(org.opensearch.index.mapper.MapperService.MergeReason) NamedXContentRegistry(org.opensearch.common.xcontent.NamedXContentRegistry) ClusterService(org.opensearch.cluster.service.ClusterService) InvalidIndexTemplateException(org.opensearch.indices.InvalidIndexTemplateException) Comparator(java.util.Comparator) LogManager(org.apache.logging.log4j.LogManager) Collections(java.util.Collections) ClusterState(org.opensearch.cluster.ClusterState) ArrayList(java.util.ArrayList) ValidationException(org.opensearch.common.ValidationException) UncheckedIOException(java.io.UncheckedIOException) IndexTemplateMissingException(org.opensearch.indices.IndexTemplateMissingException) MapperParsingException(org.opensearch.index.mapper.MapperParsingException) IOException(java.io.IOException) InvalidIndexTemplateException(org.opensearch.indices.InvalidIndexTemplateException) Regex(org.opensearch.common.regex.Regex) CompressedXContent(org.opensearch.common.compress.CompressedXContent) Map(java.util.Map) HashMap(java.util.HashMap) IndexScopedSettings(org.opensearch.common.settings.IndexScopedSettings) Settings(org.opensearch.common.settings.Settings)

Aggregations

IndicesService (org.opensearch.indices.IndicesService)88 IndexService (org.opensearch.index.IndexService)70 IndexShard (org.opensearch.index.shard.IndexShard)45 Index (org.opensearch.index.Index)29 Settings (org.opensearch.common.settings.Settings)28 IndexMetadata (org.opensearch.cluster.metadata.IndexMetadata)24 ClusterState (org.opensearch.cluster.ClusterState)22 ClusterService (org.opensearch.cluster.service.ClusterService)21 IOException (java.io.IOException)19 AtomicBoolean (java.util.concurrent.atomic.AtomicBoolean)16 ActionListener (org.opensearch.action.ActionListener)16 Matchers.containsString (org.hamcrest.Matchers.containsString)15 Collections (java.util.Collections)14 CountDownLatch (java.util.concurrent.CountDownLatch)14 ShardId (org.opensearch.index.shard.ShardId)14 ArrayList (java.util.ArrayList)12 List (java.util.List)12 SearchRequest (org.opensearch.action.search.SearchRequest)12 ShardRouting (org.opensearch.cluster.routing.ShardRouting)12 ActionFilters (org.opensearch.action.support.ActionFilters)9