Search in sources :

Example 1 with CreateIndexClusterStateUpdateRequest

use of org.opensearch.action.admin.indices.create.CreateIndexClusterStateUpdateRequest in project OpenSearch by opensearch-project.

the class TransportResizeAction method prepareCreateIndexRequest.

// static for unittesting this method
static CreateIndexClusterStateUpdateRequest prepareCreateIndexRequest(final ResizeRequest resizeRequest, final ClusterState state, final IntFunction<DocsStats> perShardDocStats, String sourceIndexName, String targetIndexName) {
    final CreateIndexRequest targetIndex = resizeRequest.getTargetIndexRequest();
    final IndexMetadata metadata = state.metadata().index(sourceIndexName);
    if (metadata == null) {
        throw new IndexNotFoundException(sourceIndexName);
    }
    final Settings.Builder targetIndexSettingsBuilder = Settings.builder().put(targetIndex.settings()).normalizePrefix(IndexMetadata.INDEX_SETTING_PREFIX);
    targetIndexSettingsBuilder.remove(IndexMetadata.SETTING_HISTORY_UUID);
    final Settings targetIndexSettings = targetIndexSettingsBuilder.build();
    final int numShards;
    if (IndexMetadata.INDEX_NUMBER_OF_SHARDS_SETTING.exists(targetIndexSettings)) {
        numShards = IndexMetadata.INDEX_NUMBER_OF_SHARDS_SETTING.get(targetIndexSettings);
    } else {
        assert resizeRequest.getResizeType() != ResizeType.SPLIT : "split must specify the number of shards explicitly";
        if (resizeRequest.getResizeType() == ResizeType.SHRINK) {
            numShards = 1;
        } else {
            assert resizeRequest.getResizeType() == ResizeType.CLONE;
            numShards = metadata.getNumberOfShards();
        }
    }
    for (int i = 0; i < numShards; i++) {
        if (resizeRequest.getResizeType() == ResizeType.SHRINK) {
            Set<ShardId> shardIds = IndexMetadata.selectShrinkShards(i, metadata, numShards);
            long count = 0;
            for (ShardId id : shardIds) {
                DocsStats docsStats = perShardDocStats.apply(id.id());
                if (docsStats != null) {
                    count += docsStats.getCount();
                }
                if (count > IndexWriter.MAX_DOCS) {
                    throw new IllegalStateException("Can't merge index with more than [" + IndexWriter.MAX_DOCS + "] docs - too many documents in shards " + shardIds);
                }
            }
        } else if (resizeRequest.getResizeType() == ResizeType.SPLIT) {
            Objects.requireNonNull(IndexMetadata.selectSplitShard(i, metadata, numShards));
        // we just execute this to ensure we get the right exceptions if the number of shards is wrong or less then etc.
        } else {
            Objects.requireNonNull(IndexMetadata.selectCloneShard(i, metadata, numShards));
        // we just execute this to ensure we get the right exceptions if the number of shards is wrong etc.
        }
    }
    if (IndexMetadata.INDEX_ROUTING_PARTITION_SIZE_SETTING.exists(targetIndexSettings)) {
        throw new IllegalArgumentException("cannot provide a routing partition size value when resizing an index");
    }
    if (IndexMetadata.INDEX_NUMBER_OF_ROUTING_SHARDS_SETTING.exists(targetIndexSettings)) {
        // if we have a source index with 1 shards it's legal to set this
        final boolean splitFromSingleShards = resizeRequest.getResizeType() == ResizeType.SPLIT && metadata.getNumberOfShards() == 1;
        if (splitFromSingleShards == false) {
            throw new IllegalArgumentException("cannot provide index.number_of_routing_shards on resize");
        }
    }
    if (IndexSettings.INDEX_SOFT_DELETES_SETTING.get(metadata.getSettings()) && IndexSettings.INDEX_SOFT_DELETES_SETTING.exists(targetIndexSettings) && IndexSettings.INDEX_SOFT_DELETES_SETTING.get(targetIndexSettings) == false) {
        throw new IllegalArgumentException("Can't disable [index.soft_deletes.enabled] setting on resize");
    }
    String cause = resizeRequest.getResizeType().name().toLowerCase(Locale.ROOT) + "_index";
    targetIndex.cause(cause);
    Settings.Builder settingsBuilder = Settings.builder().put(targetIndexSettings);
    settingsBuilder.put("index.number_of_shards", numShards);
    targetIndex.settings(settingsBuilder);
    return new CreateIndexClusterStateUpdateRequest(cause, targetIndex.index(), targetIndexName).ackTimeout(targetIndex.timeout()).masterNodeTimeout(targetIndex.masterNodeTimeout()).settings(targetIndex.settings()).aliases(targetIndex.aliases()).waitForActiveShards(targetIndex.waitForActiveShards()).recoverFrom(metadata.getIndex()).resizeType(resizeRequest.getResizeType()).copySettings(resizeRequest.getCopySettings() == null ? false : resizeRequest.getCopySettings());
}
Also used : ShardId(org.opensearch.index.shard.ShardId) CreateIndexClusterStateUpdateRequest(org.opensearch.action.admin.indices.create.CreateIndexClusterStateUpdateRequest) IndexNotFoundException(org.opensearch.index.IndexNotFoundException) DocsStats(org.opensearch.index.shard.DocsStats) CreateIndexRequest(org.opensearch.action.admin.indices.create.CreateIndexRequest) IndexMetadata(org.opensearch.cluster.metadata.IndexMetadata) Settings(org.opensearch.common.settings.Settings) IndexSettings(org.opensearch.index.IndexSettings)

Example 2 with CreateIndexClusterStateUpdateRequest

use of org.opensearch.action.admin.indices.create.CreateIndexClusterStateUpdateRequest in project OpenSearch by opensearch-project.

the class MetadataRolloverService method rolloverAlias.

private RolloverResult rolloverAlias(ClusterState currentState, IndexAbstraction.Alias alias, String aliasName, String newIndexName, CreateIndexRequest createIndexRequest, List<Condition<?>> metConditions, boolean silent, boolean onlyValidate) throws Exception {
    final Metadata metadata = currentState.metadata();
    final IndexMetadata writeIndex = alias.getWriteIndex();
    final AliasMetadata aliasMetadata = writeIndex.getAliases().get(alias.getName());
    final String sourceProvidedName = writeIndex.getSettings().get(IndexMetadata.SETTING_INDEX_PROVIDED_NAME, writeIndex.getIndex().getName());
    final String sourceIndexName = writeIndex.getIndex().getName();
    final String unresolvedName = (newIndexName != null) ? newIndexName : generateRolloverIndexName(sourceProvidedName, indexNameExpressionResolver);
    final String rolloverIndexName = indexNameExpressionResolver.resolveDateMathExpression(unresolvedName);
    final boolean explicitWriteIndex = Boolean.TRUE.equals(aliasMetadata.writeIndex());
    final Boolean isHidden = IndexMetadata.INDEX_HIDDEN_SETTING.exists(createIndexRequest.settings()) ? IndexMetadata.INDEX_HIDDEN_SETTING.get(createIndexRequest.settings()) : null;
    // fails if the index already exists
    createIndexService.validateIndexName(rolloverIndexName, currentState);
    checkNoDuplicatedAliasInIndexTemplate(metadata, rolloverIndexName, aliasName, isHidden);
    if (onlyValidate) {
        return new RolloverResult(rolloverIndexName, sourceIndexName, currentState);
    }
    CreateIndexClusterStateUpdateRequest createIndexClusterStateRequest = prepareCreateIndexRequest(unresolvedName, rolloverIndexName, createIndexRequest);
    ClusterState newState = createIndexService.applyCreateIndexRequest(currentState, createIndexClusterStateRequest, silent);
    newState = indexAliasesService.applyAliasActions(newState, rolloverAliasToNewIndex(sourceIndexName, rolloverIndexName, explicitWriteIndex, aliasMetadata.isHidden(), aliasName));
    RolloverInfo rolloverInfo = new RolloverInfo(aliasName, metConditions, threadPool.absoluteTimeInMillis());
    newState = ClusterState.builder(newState).metadata(Metadata.builder(newState.metadata()).put(IndexMetadata.builder(newState.metadata().index(sourceIndexName)).putRolloverInfo(rolloverInfo))).build();
    return new RolloverResult(rolloverIndexName, sourceIndexName, newState);
}
Also used : ClusterState(org.opensearch.cluster.ClusterState) AliasMetadata(org.opensearch.cluster.metadata.AliasMetadata) CreateIndexClusterStateUpdateRequest(org.opensearch.action.admin.indices.create.CreateIndexClusterStateUpdateRequest) Metadata(org.opensearch.cluster.metadata.Metadata) IndexMetadata(org.opensearch.cluster.metadata.IndexMetadata) AliasMetadata(org.opensearch.cluster.metadata.AliasMetadata) IndexTemplateMetadata(org.opensearch.cluster.metadata.IndexTemplateMetadata) IndexMetadata(org.opensearch.cluster.metadata.IndexMetadata)

Example 3 with CreateIndexClusterStateUpdateRequest

use of org.opensearch.action.admin.indices.create.CreateIndexClusterStateUpdateRequest in project OpenSearch by opensearch-project.

the class MetadataCreateDataStreamService method createDataStream.

static ClusterState createDataStream(MetadataCreateIndexService metadataCreateIndexService, ClusterState currentState, CreateDataStreamClusterStateUpdateRequest request) throws Exception {
    if (currentState.nodes().getMinNodeVersion().before(LegacyESVersion.V_7_9_0)) {
        throw new IllegalStateException("data streams require minimum node version of " + LegacyESVersion.V_7_9_0);
    }
    if (currentState.metadata().dataStreams().containsKey(request.name)) {
        throw new ResourceAlreadyExistsException("data_stream [" + request.name + "] already exists");
    }
    MetadataCreateIndexService.validateIndexOrAliasName(request.name, (s1, s2) -> new IllegalArgumentException("data_stream [" + s1 + "] " + s2));
    if (request.name.toLowerCase(Locale.ROOT).equals(request.name) == false) {
        throw new IllegalArgumentException("data_stream [" + request.name + "] must be lowercase");
    }
    if (request.name.startsWith(".")) {
        throw new IllegalArgumentException("data_stream [" + request.name + "] must not start with '.'");
    }
    ComposableIndexTemplate template = lookupTemplateForDataStream(request.name, currentState.metadata());
    String firstBackingIndexName = DataStream.getDefaultBackingIndexName(request.name, 1);
    CreateIndexClusterStateUpdateRequest createIndexRequest = new CreateIndexClusterStateUpdateRequest("initialize_data_stream", firstBackingIndexName, firstBackingIndexName).dataStreamName(request.name).settings(Settings.builder().put("index.hidden", true).build());
    try {
        currentState = metadataCreateIndexService.applyCreateIndexRequest(currentState, createIndexRequest, false);
    } catch (ResourceAlreadyExistsException e) {
        // (otherwise bulk execution fails later, because data stream will also not have been created)
        throw new OpenSearchStatusException("data stream could not be created because backing index [{}] already exists", RestStatus.BAD_REQUEST, e, firstBackingIndexName);
    }
    IndexMetadata firstBackingIndex = currentState.metadata().index(firstBackingIndexName);
    assert firstBackingIndex != null;
    assert firstBackingIndex.mapping() != null : "no mapping found for backing index [" + firstBackingIndexName + "]";
    String fieldName = template.getDataStreamTemplate().getTimestampField().getName();
    DataStream.TimestampField timestampField = new DataStream.TimestampField(fieldName);
    DataStream newDataStream = new DataStream(request.name, timestampField, Collections.singletonList(firstBackingIndex.getIndex()));
    Metadata.Builder builder = Metadata.builder(currentState.metadata()).put(newDataStream);
    logger.info("adding data stream [{}]", request.name);
    return ClusterState.builder(currentState).metadata(builder).build();
}
Also used : ResourceAlreadyExistsException(org.opensearch.ResourceAlreadyExistsException) CreateIndexClusterStateUpdateRequest(org.opensearch.action.admin.indices.create.CreateIndexClusterStateUpdateRequest) OpenSearchStatusException(org.opensearch.OpenSearchStatusException)

Example 4 with CreateIndexClusterStateUpdateRequest

use of org.opensearch.action.admin.indices.create.CreateIndexClusterStateUpdateRequest in project OpenSearch by opensearch-project.

the class MetadataCreateIndexService method applyCreateIndexRequestWithV1Templates.

private ClusterState applyCreateIndexRequestWithV1Templates(final ClusterState currentState, final CreateIndexClusterStateUpdateRequest request, final boolean silent, final List<IndexTemplateMetadata> templates, final BiConsumer<Metadata.Builder, IndexMetadata> metadataTransformer) throws Exception {
    logger.debug("applying create index request using legacy templates {}", templates.stream().map(IndexTemplateMetadata::name).collect(Collectors.toList()));
    final Map<String, Map<String, Object>> mappings = Collections.unmodifiableMap(parseV1Mappings(request.mappings(), templates.stream().map(IndexTemplateMetadata::getMappings).map(iom -> {
        Map<String, CompressedXContent> converted = new HashMap<>(iom.size());
        for (ObjectObjectCursor<String, CompressedXContent> cursor : iom) {
            converted.put(cursor.key, cursor.value);
        }
        return converted;
    }).collect(toList()), xContentRegistry));
    final Settings aggregatedIndexSettings = aggregateIndexSettings(currentState, request, MetadataIndexTemplateService.resolveSettings(templates), null, settings, indexScopedSettings, shardLimitValidator, indexSettingProviders);
    int routingNumShards = getIndexNumberOfRoutingShards(aggregatedIndexSettings, null);
    IndexMetadata tmpImd = buildAndValidateTemporaryIndexMetadata(currentState, aggregatedIndexSettings, request, routingNumShards);
    return applyCreateIndexWithTemporaryService(currentState, request, silent, null, tmpImd, Collections.singletonList(mappings), indexService -> resolveAndValidateAliases(request.index(), request.aliases(), MetadataIndexTemplateService.resolveAliases(templates), currentState.metadata(), aliasValidator, // shard id and the current timestamp
    xContentRegistry, indexService.newQueryShardContext(0, null, () -> 0L, null)), templates.stream().map(IndexTemplateMetadata::getName).collect(toList()), metadataTransformer);
}
Also used : CreateIndexClusterStateUpdateRequest(org.opensearch.action.admin.indices.create.CreateIndexClusterStateUpdateRequest) SETTING_AUTO_EXPAND_REPLICAS(org.opensearch.cluster.metadata.IndexMetadata.SETTING_AUTO_EXPAND_REPLICAS) IndexScopedSettings(org.opensearch.common.settings.IndexScopedSettings) BiFunction(java.util.function.BiFunction) AllocationService(org.opensearch.cluster.routing.allocation.AllocationService) Level(org.apache.logging.log4j.Level) INDEX_NUMBER_OF_SHARDS_SETTING(org.opensearch.cluster.metadata.IndexMetadata.INDEX_NUMBER_OF_SHARDS_SETTING) Version(org.opensearch.Version) OpenSearchException(org.opensearch.OpenSearchException) Strings(org.opensearch.common.Strings) ObjectObjectCursor(com.carrotsearch.hppc.cursors.ObjectObjectCursor) MapperService(org.opensearch.index.mapper.MapperService) Alias(org.opensearch.action.admin.indices.alias.Alias) ClusterBlock(org.opensearch.cluster.block.ClusterBlock) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Locale(java.util.Locale) Map(java.util.Map) ActionListener(org.opensearch.action.ActionListener) IndexSettingProvider(org.opensearch.index.shard.IndexSettingProvider) IndexModule(org.opensearch.index.IndexModule) Path(java.nio.file.Path) SETTING_NUMBER_OF_REPLICAS(org.opensearch.cluster.metadata.IndexMetadata.SETTING_NUMBER_OF_REPLICAS) Index(org.opensearch.index.Index) Predicate(java.util.function.Predicate) IndicesService(org.opensearch.indices.IndicesService) Set(java.util.Set) Settings(org.opensearch.common.settings.Settings) Instant(java.time.Instant) Collectors(java.util.stream.Collectors) Nullable(org.opensearch.common.Nullable) ValidationException(org.opensearch.common.ValidationException) InvalidIndexNameException(org.opensearch.indices.InvalidIndexNameException) List(java.util.List) Logger(org.apache.logging.log4j.Logger) SystemIndexDescriptor(org.opensearch.indices.SystemIndexDescriptor) IndexSettings(org.opensearch.index.IndexSettings) QueryShardContext(org.opensearch.index.query.QueryShardContext) SETTING_CREATION_DATE(org.opensearch.cluster.metadata.IndexMetadata.SETTING_CREATION_DATE) ResourceAlreadyExistsException(org.opensearch.ResourceAlreadyExistsException) IndexCreationException(org.opensearch.indices.IndexCreationException) ClusterStateUpdateResponse(org.opensearch.cluster.ack.ClusterStateUpdateResponse) UnsupportedEncodingException(java.io.UnsupportedEncodingException) PathUtils(org.opensearch.common.io.PathUtils) IntStream(java.util.stream.IntStream) DiscoveryNodes(org.opensearch.cluster.node.DiscoveryNodes) INDEX_NUMBER_OF_REPLICAS_SETTING(org.opensearch.cluster.metadata.IndexMetadata.INDEX_NUMBER_OF_REPLICAS_SETTING) ThreadPool(org.opensearch.threadpool.ThreadPool) CompressedXContent(org.opensearch.common.compress.CompressedXContent) SETTING_INDEX_UUID(org.opensearch.cluster.metadata.IndexMetadata.SETTING_INDEX_UUID) CreateIndexClusterStateUpdateResponse(org.opensearch.cluster.ack.CreateIndexClusterStateUpdateResponse) Priority(org.opensearch.common.Priority) HashMap(java.util.HashMap) ParameterizedMessage(org.apache.logging.log4j.message.ParameterizedMessage) Function(java.util.function.Function) Supplier(java.util.function.Supplier) ArrayList(java.util.ArrayList) DeprecationLogger(org.opensearch.common.logging.DeprecationLogger) HashSet(java.util.HashSet) IndexRoutingTable(org.opensearch.cluster.routing.IndexRoutingTable) ClusterState(org.opensearch.cluster.ClusterState) LegacyESVersion(org.opensearch.LegacyESVersion) AckedClusterStateUpdateTask(org.opensearch.cluster.AckedClusterStateUpdateTask) ShardRoutingState(org.opensearch.cluster.routing.ShardRoutingState) BiConsumer(java.util.function.BiConsumer) Collections.singletonMap(java.util.Collections.singletonMap) UUIDs(org.opensearch.common.UUIDs) ClusterBlocks(org.opensearch.cluster.block.ClusterBlocks) Environment(org.opensearch.env.Environment) ResizeType(org.opensearch.action.admin.indices.shrink.ResizeType) Setting(org.opensearch.common.settings.Setting) ShardLimitValidator(org.opensearch.indices.ShardLimitValidator) ClusterBlockLevel(org.opensearch.cluster.block.ClusterBlockLevel) IndexNotFoundException(org.opensearch.index.IndexNotFoundException) IOException(java.io.IOException) IndexService(org.opensearch.index.IndexService) ActiveShardCount(org.opensearch.action.support.ActiveShardCount) DocumentMapper(org.opensearch.index.mapper.DocumentMapper) ShardRouting(org.opensearch.cluster.routing.ShardRouting) XContentHelper(org.opensearch.common.xcontent.XContentHelper) SystemIndices(org.opensearch.indices.SystemIndices) Collectors.toList(java.util.stream.Collectors.toList) MergeReason(org.opensearch.index.mapper.MapperService.MergeReason) ActiveShardsObserver(org.opensearch.action.support.ActiveShardsObserver) NamedXContentRegistry(org.opensearch.common.xcontent.NamedXContentRegistry) ClusterService(org.opensearch.cluster.service.ClusterService) RoutingTable(org.opensearch.cluster.routing.RoutingTable) SETTING_NUMBER_OF_SHARDS(org.opensearch.cluster.metadata.IndexMetadata.SETTING_NUMBER_OF_SHARDS) LogManager(org.apache.logging.log4j.LogManager) Collections(java.util.Collections) ObjectObjectCursor(com.carrotsearch.hppc.cursors.ObjectObjectCursor) Map(java.util.Map) HashMap(java.util.HashMap) Collections.singletonMap(java.util.Collections.singletonMap) IndexScopedSettings(org.opensearch.common.settings.IndexScopedSettings) Settings(org.opensearch.common.settings.Settings) IndexSettings(org.opensearch.index.IndexSettings)

Example 5 with CreateIndexClusterStateUpdateRequest

use of org.opensearch.action.admin.indices.create.CreateIndexClusterStateUpdateRequest in project OpenSearch by opensearch-project.

the class MetadataRolloverServiceTests method testCreateIndexRequest.

public void testCreateIndexRequest() {
    String alias = randomAlphaOfLength(10);
    String rolloverIndex = randomAlphaOfLength(10);
    final RolloverRequest rolloverRequest = new RolloverRequest(alias, randomAlphaOfLength(10));
    final ActiveShardCount activeShardCount = randomBoolean() ? ActiveShardCount.ALL : ActiveShardCount.ONE;
    rolloverRequest.getCreateIndexRequest().waitForActiveShards(activeShardCount);
    final Settings settings = Settings.builder().put(IndexMetadata.SETTING_VERSION_CREATED, Version.CURRENT).put(IndexMetadata.SETTING_INDEX_UUID, UUIDs.randomBase64UUID()).put(IndexMetadata.SETTING_NUMBER_OF_SHARDS, 1).put(IndexMetadata.SETTING_NUMBER_OF_REPLICAS, 0).build();
    rolloverRequest.getCreateIndexRequest().settings(settings);
    final CreateIndexClusterStateUpdateRequest createIndexRequest = MetadataRolloverService.prepareCreateIndexRequest(rolloverIndex, rolloverIndex, rolloverRequest.getCreateIndexRequest());
    assertThat(createIndexRequest.settings(), equalTo(settings));
    assertThat(createIndexRequest.index(), equalTo(rolloverIndex));
    assertThat(createIndexRequest.cause(), equalTo("rollover_index"));
}
Also used : CreateIndexClusterStateUpdateRequest(org.opensearch.action.admin.indices.create.CreateIndexClusterStateUpdateRequest) Matchers.containsString(org.hamcrest.Matchers.containsString) ActiveShardCount(org.opensearch.action.support.ActiveShardCount) IndexScopedSettings(org.opensearch.common.settings.IndexScopedSettings) Settings(org.opensearch.common.settings.Settings)

Aggregations

CreateIndexClusterStateUpdateRequest (org.opensearch.action.admin.indices.create.CreateIndexClusterStateUpdateRequest)13 Settings (org.opensearch.common.settings.Settings)7 IndexScopedSettings (org.opensearch.common.settings.IndexScopedSettings)6 ClusterState (org.opensearch.cluster.ClusterState)5 IndexSettings (org.opensearch.index.IndexSettings)5 ActiveShardCount (org.opensearch.action.support.ActiveShardCount)4 IndexMetadata (org.opensearch.cluster.metadata.IndexMetadata)3 MetadataCreateIndexService.aggregateIndexSettings (org.opensearch.cluster.metadata.MetadataCreateIndexService.aggregateIndexSettings)3 Matchers.containsString (org.hamcrest.Matchers.containsString)2 ResourceAlreadyExistsException (org.opensearch.ResourceAlreadyExistsException)2 IndexNotFoundException (org.opensearch.index.IndexNotFoundException)2 QueryShardContext (org.opensearch.index.query.QueryShardContext)2 ObjectObjectCursor (com.carrotsearch.hppc.cursors.ObjectObjectCursor)1 IOException (java.io.IOException)1 UnsupportedEncodingException (java.io.UnsupportedEncodingException)1 Path (java.nio.file.Path)1 Instant (java.time.Instant)1 ArrayList (java.util.ArrayList)1 Collections (java.util.Collections)1 Collections.singletonMap (java.util.Collections.singletonMap)1