Search in sources :

Example 6 with ClusterBlock

use of org.elasticsearch.cluster.block.ClusterBlock in project crate by crate.

the class TransportCloseTable method closeRoutingTable.

/**
 * Step 3 - Move index states from OPEN to CLOSE in cluster state for indices that are ready for closing.
 * @param target
 */
static ClusterState closeRoutingTable(ClusterState currentState, AlterTableTarget target, DDLClusterStateService ddlClusterStateService, Map<Index, ClusterBlock> blockedIndices, Map<Index, AcknowledgedResponse> results) {
    // Remove the index routing table of closed indices if the cluster is in a mixed version
    // that does not support the replication of closed indices
    final boolean removeRoutingTable = currentState.nodes().getMinNodeVersion().before(Version.V_4_3_0);
    IndexTemplateMetadata templateMetadata = target.templateMetadata();
    ClusterState updatedState;
    if (templateMetadata == null) {
        updatedState = currentState;
    } else {
        Metadata.Builder metadata = Metadata.builder(currentState.metadata());
        metadata.put(closePartitionTemplate(templateMetadata));
        updatedState = ClusterState.builder(currentState).metadata(metadata).build();
    }
    String partition = target.partition();
    if (partition != null) {
        PartitionName partitionName = PartitionName.fromIndexOrTemplate(partition);
        updatedState = ddlClusterStateService.onCloseTablePartition(updatedState, partitionName);
    } else {
        updatedState = ddlClusterStateService.onCloseTable(updatedState, target.table());
    }
    final Metadata.Builder metadata = Metadata.builder(updatedState.metadata());
    final ClusterBlocks.Builder blocks = ClusterBlocks.builder().blocks(updatedState.blocks());
    final RoutingTable.Builder routingTable = RoutingTable.builder(updatedState.routingTable());
    final Set<String> closedIndices = new HashSet<>();
    for (Map.Entry<Index, AcknowledgedResponse> result : results.entrySet()) {
        final Index index = result.getKey();
        final boolean acknowledged = result.getValue().isAcknowledged();
        try {
            if (acknowledged == false) {
                LOGGER.debug("verification of shards before closing {} failed", index);
                continue;
            }
            final IndexMetadata indexMetadata = metadata.getSafe(index);
            if (indexMetadata.getState() == IndexMetadata.State.CLOSE) {
                LOGGER.debug("verification of shards before closing {} succeeded but index is already closed", index);
                assert currentState.blocks().hasIndexBlock(index.getName(), IndexMetadata.INDEX_CLOSED_BLOCK);
                continue;
            }
            final ClusterBlock closingBlock = blockedIndices.get(index);
            if (currentState.blocks().hasIndexBlock(index.getName(), closingBlock) == false) {
                LOGGER.debug("verification of shards before closing {} succeeded but block has been removed in the meantime", index);
                continue;
            }
            Set<Index> restoringIndices = RestoreService.restoringIndices(updatedState, Set.of(index));
            if (restoringIndices.isEmpty() == false) {
                result.setValue(new AcknowledgedResponse(false));
                LOGGER.debug("verification of shards before closing {} succeeded but index is being restored in the meantime", index);
                continue;
            }
            Set<Index> snapshottingIndices = SnapshotsService.snapshottingIndices(updatedState, Set.of(index));
            if (snapshottingIndices.isEmpty() == false) {
                result.setValue(new AcknowledgedResponse(false));
                LOGGER.debug("verification of shards before closing {} succeeded but index is being snapshot in the meantime", index);
                continue;
            }
            blocks.removeIndexBlockWithId(index.getName(), INDEX_CLOSED_BLOCK_ID);
            blocks.addIndexBlock(index.getName(), IndexMetadata.INDEX_CLOSED_BLOCK);
            final IndexMetadata.Builder updatedMetadata = IndexMetadata.builder(indexMetadata).state(IndexMetadata.State.CLOSE);
            if (removeRoutingTable) {
                metadata.put(updatedMetadata);
                routingTable.remove(index.getName());
            } else {
                metadata.put(updatedMetadata.settingsVersion(indexMetadata.getSettingsVersion() + 1).settings(Settings.builder().put(indexMetadata.getSettings()).put(IndexMetadata.VERIFIED_BEFORE_CLOSE_SETTING.getKey(), true)));
                routingTable.addAsFromOpenToClose(metadata.getSafe(index));
            }
            LOGGER.debug("closing index {} succeeded", index);
            closedIndices.add(index.getName());
        } catch (IndexNotFoundException e) {
            LOGGER.debug("index {} has been deleted since it was blocked before closing, ignoring", index);
        }
    }
    LOGGER.info("completed closing of indices {}", closedIndices);
    return ClusterState.builder(currentState).blocks(blocks).metadata(metadata).routingTable(routingTable.build()).build();
}
Also used : ClusterState(org.elasticsearch.cluster.ClusterState) ClusterBlocks(org.elasticsearch.cluster.block.ClusterBlocks) IndexTemplateMetadata(org.elasticsearch.cluster.metadata.IndexTemplateMetadata) IndexMetadata(org.elasticsearch.cluster.metadata.IndexMetadata) Metadata(org.elasticsearch.cluster.metadata.Metadata) IndexTemplateMetadata(org.elasticsearch.cluster.metadata.IndexTemplateMetadata) AcknowledgedResponse(org.elasticsearch.action.support.master.AcknowledgedResponse) Index(org.elasticsearch.index.Index) PartitionName(io.crate.metadata.PartitionName) ClusterBlock(org.elasticsearch.cluster.block.ClusterBlock) IndexShardRoutingTable(org.elasticsearch.cluster.routing.IndexShardRoutingTable) IndexRoutingTable(org.elasticsearch.cluster.routing.IndexRoutingTable) RoutingTable(org.elasticsearch.cluster.routing.RoutingTable) IndexNotFoundException(org.elasticsearch.index.IndexNotFoundException) IndexMetadata(org.elasticsearch.cluster.metadata.IndexMetadata) Map(java.util.Map) ImmutableOpenIntMap(org.elasticsearch.common.collect.ImmutableOpenIntMap) HashMap(java.util.HashMap) HashSet(java.util.HashSet)

Example 7 with ClusterBlock

use of org.elasticsearch.cluster.block.ClusterBlock in project crate by crate.

the class TransportCloseTable method addCloseBlocks.

/**
 * Step 1 - Start closing indices by adding a write block
 *
 * This step builds the list of indices to close (the ones explicitly requested that are not in CLOSE state) and adds a unique cluster
 * block (or reuses an existing one) to every index to close in the cluster state. After the cluster state is published, the shards
 * should start to reject writing operations and we can proceed with step 2.
 */
private static ClusterState addCloseBlocks(ClusterState currentState, Index[] indices, Map<Index, ClusterBlock> blockedIndices) {
    Metadata.Builder metadata = Metadata.builder(currentState.metadata());
    ClusterBlocks.Builder blocks = ClusterBlocks.builder().blocks(currentState.blocks());
    Set<Index> indicesToClose = new HashSet<>();
    for (Index index : indices) {
        final IndexMetadata indexMetadata = metadata.getSafe(index);
        if (indexMetadata.getState() != IndexMetadata.State.CLOSE) {
            indicesToClose.add(index);
        } else {
            LOGGER.debug("index {} is already closed, ignoring", index);
            assert currentState.blocks().hasIndexBlock(index.getName(), IndexMetadata.INDEX_CLOSED_BLOCK);
        }
    }
    if (indicesToClose.isEmpty()) {
        return currentState;
    }
    Set<Index> restoringIndices = RestoreService.restoringIndices(currentState, indicesToClose);
    if (restoringIndices.isEmpty() == false) {
        throw new IllegalArgumentException("Cannot close indices that are being restored: " + restoringIndices);
    }
    Set<Index> snapshottingIndices = SnapshotsService.snapshottingIndices(currentState, indicesToClose);
    if (snapshottingIndices.isEmpty() == false) {
        throw new SnapshotInProgressException("Cannot close indices that are being snapshotted: " + snapshottingIndices + ". Try again after snapshot finishes or cancel the currently running snapshot.");
    }
    for (var index : indicesToClose) {
        ClusterBlock indexBlock = null;
        final Set<ClusterBlock> clusterBlocks = currentState.blocks().indices().get(index.getName());
        if (clusterBlocks != null) {
            for (ClusterBlock clusterBlock : clusterBlocks) {
                if (clusterBlock.id() == INDEX_CLOSED_BLOCK_ID) {
                    // Reuse the existing index closed block
                    indexBlock = clusterBlock;
                    break;
                }
            }
        }
        if (indexBlock == null) {
            indexBlock = new ClusterBlock(INDEX_CLOSED_BLOCK_ID, UUIDs.randomBase64UUID(), "Table or partition preparing to close. Reopen the table to allow " + "writes again or retry closing the table to fully close it.", false, false, false, RestStatus.FORBIDDEN, EnumSet.of(ClusterBlockLevel.WRITE));
        }
        assert Strings.hasLength(indexBlock.uuid()) : "Closing block should have a UUID";
        blocks.addIndexBlock(index.getName(), indexBlock);
        blockedIndices.put(index, indexBlock);
    }
    return ClusterState.builder(currentState).blocks(blocks).metadata(metadata).routingTable(currentState.routingTable()).build();
}
Also used : ClusterBlocks(org.elasticsearch.cluster.block.ClusterBlocks) IndexMetadata(org.elasticsearch.cluster.metadata.IndexMetadata) Metadata(org.elasticsearch.cluster.metadata.Metadata) IndexTemplateMetadata(org.elasticsearch.cluster.metadata.IndexTemplateMetadata) Index(org.elasticsearch.index.Index) ClusterBlock(org.elasticsearch.cluster.block.ClusterBlock) SnapshotInProgressException(org.elasticsearch.snapshots.SnapshotInProgressException) IndexMetadata(org.elasticsearch.cluster.metadata.IndexMetadata) HashSet(java.util.HashSet)

Example 8 with ClusterBlock

use of org.elasticsearch.cluster.block.ClusterBlock in project crate by crate.

the class ClusterState method toXContent.

@Override
@SuppressWarnings("unchecked")
public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException {
    EnumSet<Metric> metrics = Metric.parseString(params.param("metric", "_all"), true);
    // always provide the cluster_uuid as part of the top-level response (also part of the metadata response)
    builder.field("cluster_uuid", metadata().clusterUUID());
    if (metrics.contains(Metric.VERSION)) {
        builder.field("version", version);
        builder.field("state_uuid", stateUUID);
    }
    if (metrics.contains(Metric.MASTER_NODE)) {
        builder.field("master_node", nodes().getMasterNodeId());
    }
    if (metrics.contains(Metric.BLOCKS)) {
        builder.startObject("blocks");
        if (!blocks().global().isEmpty()) {
            builder.startObject("global");
            for (ClusterBlock block : blocks().global()) {
                block.toXContent(builder, params);
            }
            builder.endObject();
        }
        if (!blocks().indices().isEmpty()) {
            builder.startObject("indices");
            for (ObjectObjectCursor<String, Set<ClusterBlock>> entry : blocks().indices()) {
                builder.startObject(entry.key);
                for (ClusterBlock block : entry.value) {
                    block.toXContent(builder, params);
                }
                builder.endObject();
            }
            builder.endObject();
        }
        builder.endObject();
    }
    // nodes
    if (metrics.contains(Metric.NODES)) {
        builder.startObject("nodes");
        for (DiscoveryNode node : nodes) {
            node.toXContent(builder, params);
        }
        builder.endObject();
    }
    // meta data
    if (metrics.contains(Metric.METADATA)) {
        builder.startObject("metadata");
        builder.field("cluster_uuid", metadata().clusterUUID());
        builder.startObject("cluster_coordination");
        coordinationMetadata().toXContent(builder, params);
        builder.endObject();
        builder.startObject("templates");
        for (ObjectCursor<IndexTemplateMetadata> cursor : metadata().templates().values()) {
            IndexTemplateMetadata templateMetadata = cursor.value;
            builder.startObject(templateMetadata.name());
            builder.field("index_patterns", templateMetadata.patterns());
            builder.field("order", templateMetadata.order());
            builder.startObject("settings");
            Settings settings = templateMetadata.settings();
            settings.toXContent(builder, params);
            builder.endObject();
            builder.startObject("mappings");
            for (ObjectObjectCursor<String, CompressedXContent> cursor1 : templateMetadata.mappings()) {
                Map<String, Object> mapping = XContentHelper.convertToMap(new BytesArray(cursor1.value.uncompressed()), false).v2();
                if (mapping.size() == 1 && mapping.containsKey(cursor1.key)) {
                    // the type name is the root value, reduce it
                    mapping = (Map<String, Object>) mapping.get(cursor1.key);
                }
                builder.field(cursor1.key);
                builder.map(mapping);
            }
            builder.endObject();
            builder.endObject();
        }
        builder.endObject();
        builder.startObject("indices");
        for (IndexMetadata indexMetadata : metadata()) {
            builder.startObject(indexMetadata.getIndex().getName());
            builder.field("state", indexMetadata.getState().toString().toLowerCase(Locale.ENGLISH));
            builder.startObject("settings");
            Settings settings = indexMetadata.getSettings();
            settings.toXContent(builder, params);
            builder.endObject();
            builder.startObject("mappings");
            MappingMetadata mmd = indexMetadata.mapping();
            if (mmd != null) {
                Map<String, Object> mapping = XContentHelper.convertToMap(new BytesArray(mmd.source().uncompressed()), false).v2();
                if (mapping.size() == 1 && mapping.containsKey(mmd.type())) {
                    // the type name is the root value, reduce it
                    mapping = (Map<String, Object>) mapping.get(mmd.type());
                }
                builder.field(mmd.type());
                builder.map(mapping);
            }
            builder.endObject();
            builder.startArray("aliases");
            for (ObjectCursor<String> cursor : indexMetadata.getAliases().keys()) {
                builder.value(cursor.value);
            }
            builder.endArray();
            builder.startObject(IndexMetadata.KEY_PRIMARY_TERMS);
            for (int shard = 0; shard < indexMetadata.getNumberOfShards(); shard++) {
                builder.field(Integer.toString(shard), indexMetadata.primaryTerm(shard));
            }
            builder.endObject();
            builder.startObject(IndexMetadata.KEY_IN_SYNC_ALLOCATIONS);
            for (IntObjectCursor<Set<String>> cursor : indexMetadata.getInSyncAllocationIds()) {
                builder.startArray(String.valueOf(cursor.key));
                for (String allocationId : cursor.value) {
                    builder.value(allocationId);
                }
                builder.endArray();
            }
            builder.endObject();
            // index metadata
            builder.endObject();
        }
        builder.endObject();
        for (ObjectObjectCursor<String, Metadata.Custom> cursor : metadata.customs()) {
            builder.startObject(cursor.key);
            cursor.value.toXContent(builder, params);
            builder.endObject();
        }
        builder.endObject();
    }
    // routing table
    if (metrics.contains(Metric.ROUTING_TABLE)) {
        builder.startObject("routing_table");
        builder.startObject("indices");
        for (IndexRoutingTable indexRoutingTable : routingTable()) {
            builder.startObject(indexRoutingTable.getIndex().getName());
            builder.startObject("shards");
            for (IndexShardRoutingTable indexShardRoutingTable : indexRoutingTable) {
                builder.startArray(Integer.toString(indexShardRoutingTable.shardId().id()));
                for (ShardRouting shardRouting : indexShardRoutingTable) {
                    shardRouting.toXContent(builder, params);
                }
                builder.endArray();
            }
            builder.endObject();
            builder.endObject();
        }
        builder.endObject();
        builder.endObject();
    }
    // routing nodes
    if (metrics.contains(Metric.ROUTING_NODES)) {
        builder.startObject("routing_nodes");
        builder.startArray("unassigned");
        for (ShardRouting shardRouting : getRoutingNodes().unassigned()) {
            shardRouting.toXContent(builder, params);
        }
        builder.endArray();
        builder.startObject("nodes");
        for (RoutingNode routingNode : getRoutingNodes()) {
            builder.startArray(routingNode.nodeId() == null ? "null" : routingNode.nodeId());
            for (ShardRouting shardRouting : routingNode) {
                shardRouting.toXContent(builder, params);
            }
            builder.endArray();
        }
        builder.endObject();
        builder.endObject();
    }
    if (metrics.contains(Metric.CUSTOMS)) {
        for (ObjectObjectCursor<String, Custom> cursor : customs) {
            builder.startObject(cursor.key);
            cursor.value.toXContent(builder, params);
            builder.endObject();
        }
    }
    return builder;
}
Also used : IndexRoutingTable(org.elasticsearch.cluster.routing.IndexRoutingTable) IndexShardRoutingTable(org.elasticsearch.cluster.routing.IndexShardRoutingTable) DiscoveryNode(org.elasticsearch.cluster.node.DiscoveryNode) EnumSet(java.util.EnumSet) Set(java.util.Set) ClusterBlock(org.elasticsearch.cluster.block.ClusterBlock) RoutingNode(org.elasticsearch.cluster.routing.RoutingNode) CompressedXContent(org.elasticsearch.common.compress.CompressedXContent) IndexMetadata(org.elasticsearch.cluster.metadata.IndexMetadata) Settings(org.elasticsearch.common.settings.Settings) BytesArray(org.elasticsearch.common.bytes.BytesArray) IndexTemplateMetadata(org.elasticsearch.cluster.metadata.IndexTemplateMetadata) ShardRouting(org.elasticsearch.cluster.routing.ShardRouting) MappingMetadata(org.elasticsearch.cluster.metadata.MappingMetadata)

Example 9 with ClusterBlock

use of org.elasticsearch.cluster.block.ClusterBlock in project elasticsearch by elastic.

the class MetaDataCreateIndexService method onlyCreateIndex.

private void onlyCreateIndex(final CreateIndexClusterStateUpdateRequest request, final ActionListener<ClusterStateUpdateResponse> listener) {
    Settings.Builder updatedSettingsBuilder = Settings.builder();
    updatedSettingsBuilder.put(request.settings()).normalizePrefix(IndexMetaData.INDEX_SETTING_PREFIX);
    indexScopedSettings.validate(updatedSettingsBuilder);
    request.settings(updatedSettingsBuilder.build());
    clusterService.submitStateUpdateTask("create-index [" + request.index() + "], cause [" + request.cause() + "]", new AckedClusterStateUpdateTask<ClusterStateUpdateResponse>(Priority.URGENT, request, wrapPreservingContext(listener)) {

        @Override
        protected ClusterStateUpdateResponse newResponse(boolean acknowledged) {
            return new ClusterStateUpdateResponse(acknowledged);
        }

        @Override
        public ClusterState execute(ClusterState currentState) throws Exception {
            Index createdIndex = null;
            String removalExtraInfo = null;
            IndexRemovalReason removalReason = IndexRemovalReason.FAILURE;
            try {
                validate(request, currentState);
                for (Alias alias : request.aliases()) {
                    aliasValidator.validateAlias(alias, request.index(), currentState.metaData());
                }
                // we only find a template when its an API call (a new index)
                // find templates, highest order are better matching
                List<IndexTemplateMetaData> templates = findTemplates(request, currentState);
                Map<String, Custom> customs = new HashMap<>();
                // add the request mapping
                Map<String, Map<String, Object>> mappings = new HashMap<>();
                Map<String, AliasMetaData> templatesAliases = new HashMap<>();
                List<String> templateNames = new ArrayList<>();
                for (Map.Entry<String, String> entry : request.mappings().entrySet()) {
                    mappings.put(entry.getKey(), MapperService.parseMapping(xContentRegistry, entry.getValue()));
                }
                for (Map.Entry<String, Custom> entry : request.customs().entrySet()) {
                    customs.put(entry.getKey(), entry.getValue());
                }
                // apply templates, merging the mappings into the request mapping if exists
                for (IndexTemplateMetaData template : templates) {
                    templateNames.add(template.getName());
                    for (ObjectObjectCursor<String, CompressedXContent> cursor : template.mappings()) {
                        String mappingString = cursor.value.string();
                        if (mappings.containsKey(cursor.key)) {
                            XContentHelper.mergeDefaults(mappings.get(cursor.key), MapperService.parseMapping(xContentRegistry, mappingString));
                        } else {
                            mappings.put(cursor.key, MapperService.parseMapping(xContentRegistry, mappingString));
                        }
                    }
                    // handle custom
                    for (ObjectObjectCursor<String, Custom> cursor : template.customs()) {
                        String type = cursor.key;
                        IndexMetaData.Custom custom = cursor.value;
                        IndexMetaData.Custom existing = customs.get(type);
                        if (existing == null) {
                            customs.put(type, custom);
                        } else {
                            IndexMetaData.Custom merged = existing.mergeWith(custom);
                            customs.put(type, merged);
                        }
                    }
                    //handle aliases
                    for (ObjectObjectCursor<String, AliasMetaData> cursor : template.aliases()) {
                        AliasMetaData aliasMetaData = cursor.value;
                        // ignore this one taken from the index template
                        if (request.aliases().contains(new Alias(aliasMetaData.alias()))) {
                            continue;
                        }
                        //if an alias with same name was already processed, ignore this one
                        if (templatesAliases.containsKey(cursor.key)) {
                            continue;
                        }
                        //Allow templatesAliases to be templated by replacing a token with the name of the index that we are applying it to
                        if (aliasMetaData.alias().contains("{index}")) {
                            String templatedAlias = aliasMetaData.alias().replace("{index}", request.index());
                            aliasMetaData = AliasMetaData.newAliasMetaData(aliasMetaData, templatedAlias);
                        }
                        aliasValidator.validateAliasMetaData(aliasMetaData, request.index(), currentState.metaData());
                        templatesAliases.put(aliasMetaData.alias(), aliasMetaData);
                    }
                }
                Settings.Builder indexSettingsBuilder = Settings.builder();
                // apply templates, here, in reverse order, since first ones are better matching
                for (int i = templates.size() - 1; i >= 0; i--) {
                    indexSettingsBuilder.put(templates.get(i).settings());
                }
                // now, put the request settings, so they override templates
                indexSettingsBuilder.put(request.settings());
                if (indexSettingsBuilder.get(SETTING_NUMBER_OF_SHARDS) == null) {
                    indexSettingsBuilder.put(SETTING_NUMBER_OF_SHARDS, settings.getAsInt(SETTING_NUMBER_OF_SHARDS, 5));
                }
                if (indexSettingsBuilder.get(SETTING_NUMBER_OF_REPLICAS) == null) {
                    indexSettingsBuilder.put(SETTING_NUMBER_OF_REPLICAS, settings.getAsInt(SETTING_NUMBER_OF_REPLICAS, 1));
                }
                if (settings.get(SETTING_AUTO_EXPAND_REPLICAS) != null && indexSettingsBuilder.get(SETTING_AUTO_EXPAND_REPLICAS) == null) {
                    indexSettingsBuilder.put(SETTING_AUTO_EXPAND_REPLICAS, settings.get(SETTING_AUTO_EXPAND_REPLICAS));
                }
                if (indexSettingsBuilder.get(SETTING_VERSION_CREATED) == null) {
                    DiscoveryNodes nodes = currentState.nodes();
                    final Version createdVersion = Version.min(Version.CURRENT, nodes.getSmallestNonClientNodeVersion());
                    indexSettingsBuilder.put(SETTING_VERSION_CREATED, createdVersion);
                }
                if (indexSettingsBuilder.get(SETTING_CREATION_DATE) == null) {
                    indexSettingsBuilder.put(SETTING_CREATION_DATE, new DateTime(DateTimeZone.UTC).getMillis());
                }
                indexSettingsBuilder.put(IndexMetaData.SETTING_INDEX_PROVIDED_NAME, request.getProvidedName());
                indexSettingsBuilder.put(SETTING_INDEX_UUID, UUIDs.randomBase64UUID());
                final Index shrinkFromIndex = request.shrinkFrom();
                int routingNumShards = IndexMetaData.INDEX_NUMBER_OF_SHARDS_SETTING.get(indexSettingsBuilder.build());
                ;
                if (shrinkFromIndex != null) {
                    prepareShrinkIndexSettings(currentState, mappings.keySet(), indexSettingsBuilder, shrinkFromIndex, request.index());
                    IndexMetaData sourceMetaData = currentState.metaData().getIndexSafe(shrinkFromIndex);
                    routingNumShards = sourceMetaData.getRoutingNumShards();
                }
                Settings actualIndexSettings = indexSettingsBuilder.build();
                IndexMetaData.Builder tmpImdBuilder = IndexMetaData.builder(request.index()).setRoutingNumShards(routingNumShards);
                // Set up everything, now locally create the index to see that things are ok, and apply
                final IndexMetaData tmpImd = tmpImdBuilder.settings(actualIndexSettings).build();
                ActiveShardCount waitForActiveShards = request.waitForActiveShards();
                if (waitForActiveShards == ActiveShardCount.DEFAULT) {
                    waitForActiveShards = tmpImd.getWaitForActiveShards();
                }
                if (waitForActiveShards.validate(tmpImd.getNumberOfReplicas()) == false) {
                    throw new IllegalArgumentException("invalid wait_for_active_shards[" + request.waitForActiveShards() + "]: cannot be greater than number of shard copies [" + (tmpImd.getNumberOfReplicas() + 1) + "]");
                }
                // create the index here (on the master) to validate it can be created, as well as adding the mapping
                final IndexService indexService = indicesService.createIndex(tmpImd, Collections.emptyList(), shardId -> {
                });
                createdIndex = indexService.index();
                // now add the mappings
                MapperService mapperService = indexService.mapperService();
                try {
                    mapperService.merge(mappings, MergeReason.MAPPING_UPDATE, request.updateAllTypes());
                } catch (Exception e) {
                    removalExtraInfo = "failed on parsing default mapping/mappings on index creation";
                    throw e;
                }
                // the context is only used for validation so it's fine to pass fake values for the shard id and the current
                // timestamp
                final QueryShardContext queryShardContext = indexService.newQueryShardContext(0, null, () -> 0L);
                for (Alias alias : request.aliases()) {
                    if (Strings.hasLength(alias.filter())) {
                        aliasValidator.validateAliasFilter(alias.name(), alias.filter(), queryShardContext, xContentRegistry);
                    }
                }
                for (AliasMetaData aliasMetaData : templatesAliases.values()) {
                    if (aliasMetaData.filter() != null) {
                        aliasValidator.validateAliasFilter(aliasMetaData.alias(), aliasMetaData.filter().uncompressed(), queryShardContext, xContentRegistry);
                    }
                }
                // now, update the mappings with the actual source
                Map<String, MappingMetaData> mappingsMetaData = new HashMap<>();
                for (DocumentMapper mapper : mapperService.docMappers(true)) {
                    MappingMetaData mappingMd = new MappingMetaData(mapper);
                    mappingsMetaData.put(mapper.type(), mappingMd);
                }
                final IndexMetaData.Builder indexMetaDataBuilder = IndexMetaData.builder(request.index()).settings(actualIndexSettings).setRoutingNumShards(routingNumShards);
                for (MappingMetaData mappingMd : mappingsMetaData.values()) {
                    indexMetaDataBuilder.putMapping(mappingMd);
                }
                for (AliasMetaData aliasMetaData : templatesAliases.values()) {
                    indexMetaDataBuilder.putAlias(aliasMetaData);
                }
                for (Alias alias : request.aliases()) {
                    AliasMetaData aliasMetaData = AliasMetaData.builder(alias.name()).filter(alias.filter()).indexRouting(alias.indexRouting()).searchRouting(alias.searchRouting()).build();
                    indexMetaDataBuilder.putAlias(aliasMetaData);
                }
                for (Map.Entry<String, Custom> customEntry : customs.entrySet()) {
                    indexMetaDataBuilder.putCustom(customEntry.getKey(), customEntry.getValue());
                }
                indexMetaDataBuilder.state(request.state());
                final IndexMetaData indexMetaData;
                try {
                    indexMetaData = indexMetaDataBuilder.build();
                } catch (Exception e) {
                    removalExtraInfo = "failed to build index metadata";
                    throw e;
                }
                indexService.getIndexEventListener().beforeIndexAddedToCluster(indexMetaData.getIndex(), indexMetaData.getSettings());
                MetaData newMetaData = MetaData.builder(currentState.metaData()).put(indexMetaData, false).build();
                String maybeShadowIndicator = indexMetaData.isIndexUsingShadowReplicas() ? "s" : "";
                logger.info("[{}] creating index, cause [{}], templates {}, shards [{}]/[{}{}], mappings {}", request.index(), request.cause(), templateNames, indexMetaData.getNumberOfShards(), indexMetaData.getNumberOfReplicas(), maybeShadowIndicator, mappings.keySet());
                ClusterBlocks.Builder blocks = ClusterBlocks.builder().blocks(currentState.blocks());
                if (!request.blocks().isEmpty()) {
                    for (ClusterBlock block : request.blocks()) {
                        blocks.addIndexBlock(request.index(), block);
                    }
                }
                blocks.updateBlocks(indexMetaData);
                ClusterState updatedState = ClusterState.builder(currentState).blocks(blocks).metaData(newMetaData).build();
                if (request.state() == State.OPEN) {
                    RoutingTable.Builder routingTableBuilder = RoutingTable.builder(updatedState.routingTable()).addAsNew(updatedState.metaData().index(request.index()));
                    updatedState = allocationService.reroute(ClusterState.builder(updatedState).routingTable(routingTableBuilder.build()).build(), "index [" + request.index() + "] created");
                }
                removalExtraInfo = "cleaning up after validating index on master";
                removalReason = IndexRemovalReason.NO_LONGER_ASSIGNED;
                return updatedState;
            } finally {
                if (createdIndex != null) {
                    // Index was already partially created - need to clean up
                    indicesService.removeIndex(createdIndex, removalReason, removalExtraInfo);
                }
            }
        }

        @Override
        public void onFailure(String source, Exception e) {
            if (e instanceof ResourceAlreadyExistsException) {
                logger.trace((Supplier<?>) () -> new ParameterizedMessage("[{}] failed to create", request.index()), e);
            } else {
                logger.debug((Supplier<?>) () -> new ParameterizedMessage("[{}] failed to create", request.index()), e);
            }
            super.onFailure(source, e);
        }
    });
}
Also used : ElasticsearchException(org.elasticsearch.ElasticsearchException) SETTING_INDEX_UUID(org.elasticsearch.cluster.metadata.IndexMetaData.SETTING_INDEX_UUID) DateTimeZone(org.joda.time.DateTimeZone) QueryShardContext(org.elasticsearch.index.query.QueryShardContext) Alias(org.elasticsearch.action.admin.indices.alias.Alias) Environment(org.elasticsearch.env.Environment) BiFunction(java.util.function.BiFunction) AllocationService(org.elasticsearch.cluster.routing.allocation.AllocationService) ClusterBlocks(org.elasticsearch.cluster.block.ClusterBlocks) ObjectObjectCursor(com.carrotsearch.hppc.cursors.ObjectObjectCursor) ClusterState(org.elasticsearch.cluster.ClusterState) Settings(org.elasticsearch.common.settings.Settings) CreateIndexClusterStateUpdateResponse(org.elasticsearch.cluster.ack.CreateIndexClusterStateUpdateResponse) ClusterBlock(org.elasticsearch.cluster.block.ClusterBlock) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) CompressedXContent(org.elasticsearch.common.compress.CompressedXContent) IndexNotFoundException(org.elasticsearch.index.IndexNotFoundException) IndexCreationException(org.elasticsearch.indices.IndexCreationException) Locale(java.util.Locale) Map(java.util.Map) ValidationException(org.elasticsearch.common.ValidationException) ThreadPool(org.elasticsearch.threadpool.ThreadPool) State(org.elasticsearch.cluster.metadata.IndexMetaData.State) Path(java.nio.file.Path) NamedXContentRegistry(org.elasticsearch.common.xcontent.NamedXContentRegistry) CreateIndexClusterStateUpdateRequest(org.elasticsearch.action.admin.indices.create.CreateIndexClusterStateUpdateRequest) Priority(org.elasticsearch.common.Priority) Predicate(java.util.function.Predicate) UUIDs(org.elasticsearch.common.UUIDs) Set(java.util.Set) ObjectCursor(com.carrotsearch.hppc.cursors.ObjectCursor) ActiveShardCount(org.elasticsearch.action.support.ActiveShardCount) ContextPreservingActionListener(org.elasticsearch.action.support.ContextPreservingActionListener) MapperService(org.elasticsearch.index.mapper.MapperService) List(java.util.List) Version(org.elasticsearch.Version) IndexRoutingTable(org.elasticsearch.cluster.routing.IndexRoutingTable) Supplier(org.apache.logging.log4j.util.Supplier) ClusterStateUpdateResponse(org.elasticsearch.cluster.ack.ClusterStateUpdateResponse) InvalidIndexNameException(org.elasticsearch.indices.InvalidIndexNameException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) ShardRouting(org.elasticsearch.cluster.routing.ShardRouting) AckedClusterStateUpdateTask(org.elasticsearch.cluster.AckedClusterStateUpdateTask) ClusterService(org.elasticsearch.cluster.service.ClusterService) HashMap(java.util.HashMap) Index(org.elasticsearch.index.Index) ShardRoutingState(org.elasticsearch.cluster.routing.ShardRoutingState) ParameterizedMessage(org.apache.logging.log4j.message.ParameterizedMessage) ResourceAlreadyExistsException(org.elasticsearch.ResourceAlreadyExistsException) ActiveShardsObserver(org.elasticsearch.action.support.ActiveShardsObserver) Strings(org.elasticsearch.common.Strings) Inject(org.elasticsearch.common.inject.Inject) ArrayList(java.util.ArrayList) SETTING_NUMBER_OF_REPLICAS(org.elasticsearch.cluster.metadata.IndexMetaData.SETTING_NUMBER_OF_REPLICAS) XContentHelper(org.elasticsearch.common.xcontent.XContentHelper) IndexRemovalReason(org.elasticsearch.indices.cluster.IndicesClusterStateService.AllocatedIndices.IndexRemovalReason) Custom(org.elasticsearch.cluster.metadata.IndexMetaData.Custom) Regex(org.elasticsearch.common.regex.Regex) SETTING_VERSION_CREATED(org.elasticsearch.cluster.metadata.IndexMetaData.SETTING_VERSION_CREATED) IndicesService(org.elasticsearch.indices.IndicesService) SETTING_AUTO_EXPAND_REPLICAS(org.elasticsearch.cluster.metadata.IndexMetaData.SETTING_AUTO_EXPAND_REPLICAS) ClusterBlockLevel(org.elasticsearch.cluster.block.ClusterBlockLevel) SETTING_CREATION_DATE(org.elasticsearch.cluster.metadata.IndexMetaData.SETTING_CREATION_DATE) PathUtils(org.elasticsearch.common.io.PathUtils) DocumentMapper(org.elasticsearch.index.mapper.DocumentMapper) DiscoveryNodes(org.elasticsearch.cluster.node.DiscoveryNodes) AbstractComponent(org.elasticsearch.common.component.AbstractComponent) SETTING_NUMBER_OF_SHARDS(org.elasticsearch.cluster.metadata.IndexMetaData.SETTING_NUMBER_OF_SHARDS) IndexService(org.elasticsearch.index.IndexService) DateTime(org.joda.time.DateTime) IOException(java.io.IOException) IndexScopedSettings(org.elasticsearch.common.settings.IndexScopedSettings) CollectionUtil(org.apache.lucene.util.CollectionUtil) RoutingTable(org.elasticsearch.cluster.routing.RoutingTable) MergeReason(org.elasticsearch.index.mapper.MapperService.MergeReason) Comparator(java.util.Comparator) Collections(java.util.Collections) ActionListener(org.elasticsearch.action.ActionListener) IndexService(org.elasticsearch.index.IndexService) Index(org.elasticsearch.index.Index) DateTime(org.joda.time.DateTime) ClusterBlock(org.elasticsearch.cluster.block.ClusterBlock) Version(org.elasticsearch.Version) QueryShardContext(org.elasticsearch.index.query.QueryShardContext) List(java.util.List) ArrayList(java.util.ArrayList) Supplier(org.apache.logging.log4j.util.Supplier) CreateIndexClusterStateUpdateResponse(org.elasticsearch.cluster.ack.CreateIndexClusterStateUpdateResponse) ClusterStateUpdateResponse(org.elasticsearch.cluster.ack.ClusterStateUpdateResponse) Settings(org.elasticsearch.common.settings.Settings) IndexScopedSettings(org.elasticsearch.common.settings.IndexScopedSettings) DiscoveryNodes(org.elasticsearch.cluster.node.DiscoveryNodes) ClusterState(org.elasticsearch.cluster.ClusterState) DocumentMapper(org.elasticsearch.index.mapper.DocumentMapper) ResourceAlreadyExistsException(org.elasticsearch.ResourceAlreadyExistsException) Custom(org.elasticsearch.cluster.metadata.IndexMetaData.Custom) ActiveShardCount(org.elasticsearch.action.support.ActiveShardCount) ElasticsearchException(org.elasticsearch.ElasticsearchException) IndexNotFoundException(org.elasticsearch.index.IndexNotFoundException) IndexCreationException(org.elasticsearch.indices.IndexCreationException) ValidationException(org.elasticsearch.common.ValidationException) InvalidIndexNameException(org.elasticsearch.indices.InvalidIndexNameException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) ResourceAlreadyExistsException(org.elasticsearch.ResourceAlreadyExistsException) IOException(java.io.IOException) IndexRemovalReason(org.elasticsearch.indices.cluster.IndicesClusterStateService.AllocatedIndices.IndexRemovalReason) Alias(org.elasticsearch.action.admin.indices.alias.Alias) ParameterizedMessage(org.apache.logging.log4j.message.ParameterizedMessage) ObjectObjectCursor(com.carrotsearch.hppc.cursors.ObjectObjectCursor) Map(java.util.Map) HashMap(java.util.HashMap) MapperService(org.elasticsearch.index.mapper.MapperService)

Example 10 with ClusterBlock

use of org.elasticsearch.cluster.block.ClusterBlock in project elasticsearch by elastic.

the class ClusterState method toXContent.

@Override
public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException {
    EnumSet<Metric> metrics = Metric.parseString(params.param("metric", "_all"), true);
    if (metrics.contains(Metric.VERSION)) {
        builder.field("version", version);
        builder.field("state_uuid", stateUUID);
    }
    if (metrics.contains(Metric.MASTER_NODE)) {
        builder.field("master_node", nodes().getMasterNodeId());
    }
    if (metrics.contains(Metric.BLOCKS)) {
        builder.startObject("blocks");
        if (!blocks().global().isEmpty()) {
            builder.startObject("global");
            for (ClusterBlock block : blocks().global()) {
                block.toXContent(builder, params);
            }
            builder.endObject();
        }
        if (!blocks().indices().isEmpty()) {
            builder.startObject("indices");
            for (ObjectObjectCursor<String, Set<ClusterBlock>> entry : blocks().indices()) {
                builder.startObject(entry.key);
                for (ClusterBlock block : entry.value) {
                    block.toXContent(builder, params);
                }
                builder.endObject();
            }
            builder.endObject();
        }
        builder.endObject();
    }
    // nodes
    if (metrics.contains(Metric.NODES)) {
        builder.startObject("nodes");
        for (DiscoveryNode node : nodes) {
            node.toXContent(builder, params);
        }
        builder.endObject();
    }
    // meta data
    if (metrics.contains(Metric.METADATA)) {
        builder.startObject("metadata");
        builder.field("cluster_uuid", metaData().clusterUUID());
        builder.startObject("templates");
        for (ObjectCursor<IndexTemplateMetaData> cursor : metaData().templates().values()) {
            IndexTemplateMetaData templateMetaData = cursor.value;
            builder.startObject(templateMetaData.name());
            builder.field("index_patterns", templateMetaData.patterns());
            builder.field("order", templateMetaData.order());
            builder.startObject("settings");
            Settings settings = templateMetaData.settings();
            settings.toXContent(builder, params);
            builder.endObject();
            builder.startObject("mappings");
            for (ObjectObjectCursor<String, CompressedXContent> cursor1 : templateMetaData.mappings()) {
                Map<String, Object> mapping = XContentHelper.convertToMap(new BytesArray(cursor1.value.uncompressed()), false).v2();
                if (mapping.size() == 1 && mapping.containsKey(cursor1.key)) {
                    // the type name is the root value, reduce it
                    mapping = (Map<String, Object>) mapping.get(cursor1.key);
                }
                builder.field(cursor1.key);
                builder.map(mapping);
            }
            builder.endObject();
            builder.endObject();
        }
        builder.endObject();
        builder.startObject("indices");
        for (IndexMetaData indexMetaData : metaData()) {
            builder.startObject(indexMetaData.getIndex().getName());
            builder.field("state", indexMetaData.getState().toString().toLowerCase(Locale.ENGLISH));
            builder.startObject("settings");
            Settings settings = indexMetaData.getSettings();
            settings.toXContent(builder, params);
            builder.endObject();
            builder.startObject("mappings");
            for (ObjectObjectCursor<String, MappingMetaData> cursor : indexMetaData.getMappings()) {
                Map<String, Object> mapping = XContentHelper.convertToMap(new BytesArray(cursor.value.source().uncompressed()), false).v2();
                if (mapping.size() == 1 && mapping.containsKey(cursor.key)) {
                    // the type name is the root value, reduce it
                    mapping = (Map<String, Object>) mapping.get(cursor.key);
                }
                builder.field(cursor.key);
                builder.map(mapping);
            }
            builder.endObject();
            builder.startArray("aliases");
            for (ObjectCursor<String> cursor : indexMetaData.getAliases().keys()) {
                builder.value(cursor.value);
            }
            builder.endArray();
            builder.startObject(IndexMetaData.KEY_PRIMARY_TERMS);
            for (int shard = 0; shard < indexMetaData.getNumberOfShards(); shard++) {
                builder.field(Integer.toString(shard), indexMetaData.primaryTerm(shard));
            }
            builder.endObject();
            builder.startObject(IndexMetaData.KEY_IN_SYNC_ALLOCATIONS);
            for (IntObjectCursor<Set<String>> cursor : indexMetaData.getInSyncAllocationIds()) {
                builder.startArray(String.valueOf(cursor.key));
                for (String allocationId : cursor.value) {
                    builder.value(allocationId);
                }
                builder.endArray();
            }
            builder.endObject();
            // index metadata
            builder.endObject();
        }
        builder.endObject();
        for (ObjectObjectCursor<String, MetaData.Custom> cursor : metaData.customs()) {
            builder.startObject(cursor.key);
            cursor.value.toXContent(builder, params);
            builder.endObject();
        }
        builder.endObject();
    }
    // routing table
    if (metrics.contains(Metric.ROUTING_TABLE)) {
        builder.startObject("routing_table");
        builder.startObject("indices");
        for (IndexRoutingTable indexRoutingTable : routingTable()) {
            builder.startObject(indexRoutingTable.getIndex().getName());
            builder.startObject("shards");
            for (IndexShardRoutingTable indexShardRoutingTable : indexRoutingTable) {
                builder.startArray(Integer.toString(indexShardRoutingTable.shardId().id()));
                for (ShardRouting shardRouting : indexShardRoutingTable) {
                    shardRouting.toXContent(builder, params);
                }
                builder.endArray();
            }
            builder.endObject();
            builder.endObject();
        }
        builder.endObject();
        builder.endObject();
    }
    // routing nodes
    if (metrics.contains(Metric.ROUTING_NODES)) {
        builder.startObject("routing_nodes");
        builder.startArray("unassigned");
        for (ShardRouting shardRouting : getRoutingNodes().unassigned()) {
            shardRouting.toXContent(builder, params);
        }
        builder.endArray();
        builder.startObject("nodes");
        for (RoutingNode routingNode : getRoutingNodes()) {
            builder.startArray(routingNode.nodeId() == null ? "null" : routingNode.nodeId());
            for (ShardRouting shardRouting : routingNode) {
                shardRouting.toXContent(builder, params);
            }
            builder.endArray();
        }
        builder.endObject();
        builder.endObject();
    }
    if (metrics.contains(Metric.CUSTOMS)) {
        for (ObjectObjectCursor<String, Custom> cursor : customs) {
            builder.startObject(cursor.key);
            cursor.value.toXContent(builder, params);
            builder.endObject();
        }
    }
    return builder;
}
Also used : IndexRoutingTable(org.elasticsearch.cluster.routing.IndexRoutingTable) IndexShardRoutingTable(org.elasticsearch.cluster.routing.IndexShardRoutingTable) DiscoveryNode(org.elasticsearch.cluster.node.DiscoveryNode) EnumSet(java.util.EnumSet) Set(java.util.Set) ClusterBlock(org.elasticsearch.cluster.block.ClusterBlock) RoutingNode(org.elasticsearch.cluster.routing.RoutingNode) IndexTemplateMetaData(org.elasticsearch.cluster.metadata.IndexTemplateMetaData) CompressedXContent(org.elasticsearch.common.compress.CompressedXContent) Settings(org.elasticsearch.common.settings.Settings) BytesArray(org.elasticsearch.common.bytes.BytesArray) MappingMetaData(org.elasticsearch.cluster.metadata.MappingMetaData) IndexMetaData(org.elasticsearch.cluster.metadata.IndexMetaData) ShardRouting(org.elasticsearch.cluster.routing.ShardRouting)

Aggregations

ClusterBlock (org.elasticsearch.cluster.block.ClusterBlock)15 ClusterBlocks (org.elasticsearch.cluster.block.ClusterBlocks)11 PlainActionFuture (org.elasticsearch.action.support.PlainActionFuture)7 ClusterState (org.elasticsearch.cluster.ClusterState)7 Set (java.util.Set)6 Settings (org.elasticsearch.common.settings.Settings)6 ClusterBlockException (org.elasticsearch.cluster.block.ClusterBlockException)5 IndexMetadata (org.elasticsearch.cluster.metadata.IndexMetadata)5 IndexRoutingTable (org.elasticsearch.cluster.routing.IndexRoutingTable)5 IndexShardRoutingTable (org.elasticsearch.cluster.routing.IndexShardRoutingTable)5 ShardRouting (org.elasticsearch.cluster.routing.ShardRouting)5 ExecutionException (java.util.concurrent.ExecutionException)4 ClusterBlockLevel (org.elasticsearch.cluster.block.ClusterBlockLevel)4 ClusterService (org.elasticsearch.cluster.service.ClusterService)4 TransportResponse (org.elasticsearch.transport.TransportResponse)4 IOException (java.io.IOException)3 EnumSet (java.util.EnumSet)3 HashSet (java.util.HashSet)3 List (java.util.List)3 ActionListener (org.elasticsearch.action.ActionListener)3