Search in sources :

Example 16 with IndexRoutingTable

use of org.elasticsearch.cluster.routing.IndexRoutingTable in project elasticsearch by elastic.

the class ClusterStateHealthTests method testClusterHealth.

public void testClusterHealth() throws IOException {
    RoutingTableGenerator routingTableGenerator = new RoutingTableGenerator();
    RoutingTableGenerator.ShardCounter counter = new RoutingTableGenerator.ShardCounter();
    RoutingTable.Builder routingTable = RoutingTable.builder();
    MetaData.Builder metaData = MetaData.builder();
    for (int i = randomInt(4); i >= 0; i--) {
        int numberOfShards = randomInt(3) + 1;
        int numberOfReplicas = randomInt(4);
        IndexMetaData indexMetaData = IndexMetaData.builder("test_" + Integer.toString(i)).settings(settings(Version.CURRENT)).numberOfShards(numberOfShards).numberOfReplicas(numberOfReplicas).build();
        IndexRoutingTable indexRoutingTable = routingTableGenerator.genIndexRoutingTable(indexMetaData, counter);
        metaData.put(indexMetaData, true);
        routingTable.add(indexRoutingTable);
    }
    ClusterState clusterState = ClusterState.builder(ClusterName.CLUSTER_NAME_SETTING.getDefault(Settings.EMPTY)).metaData(metaData).routingTable(routingTable.build()).build();
    String[] concreteIndices = indexNameExpressionResolver.concreteIndexNames(clusterState, IndicesOptions.strictExpand(), (String[]) null);
    ClusterStateHealth clusterStateHealth = new ClusterStateHealth(clusterState, concreteIndices);
    logger.info("cluster status: {}, expected {}", clusterStateHealth.getStatus(), counter.status());
    clusterStateHealth = maybeSerialize(clusterStateHealth);
    assertClusterHealth(clusterStateHealth, counter);
}
Also used : IndexRoutingTable(org.elasticsearch.cluster.routing.IndexRoutingTable) ClusterState(org.elasticsearch.cluster.ClusterState) IndexMetaData(org.elasticsearch.cluster.metadata.IndexMetaData) IndexShardRoutingTable(org.elasticsearch.cluster.routing.IndexShardRoutingTable) IndexRoutingTable(org.elasticsearch.cluster.routing.IndexRoutingTable) RoutingTable(org.elasticsearch.cluster.routing.RoutingTable) MetaData(org.elasticsearch.cluster.metadata.MetaData) IndexMetaData(org.elasticsearch.cluster.metadata.IndexMetaData) RoutingTableGenerator(org.elasticsearch.cluster.routing.RoutingTableGenerator)

Example 17 with IndexRoutingTable

use of org.elasticsearch.cluster.routing.IndexRoutingTable in project elasticsearch by elastic.

the class TransportIndicesShardStoresAction method masterOperation.

@Override
protected void masterOperation(IndicesShardStoresRequest request, ClusterState state, ActionListener<IndicesShardStoresResponse> listener) {
    final RoutingTable routingTables = state.routingTable();
    final RoutingNodes routingNodes = state.getRoutingNodes();
    final String[] concreteIndices = indexNameExpressionResolver.concreteIndexNames(state, request);
    final Set<ShardId> shardIdsToFetch = new HashSet<>();
    logger.trace("using cluster state version [{}] to determine shards", state.version());
    // collect relevant shard ids of the requested indices for fetching store infos
    for (String index : concreteIndices) {
        IndexRoutingTable indexShardRoutingTables = routingTables.index(index);
        if (indexShardRoutingTables == null) {
            continue;
        }
        for (IndexShardRoutingTable routing : indexShardRoutingTables) {
            final int shardId = routing.shardId().id();
            ClusterShardHealth shardHealth = new ClusterShardHealth(shardId, routing);
            if (request.shardStatuses().contains(shardHealth.getStatus())) {
                shardIdsToFetch.add(routing.shardId());
            }
        }
    }
    // async fetch store infos from all the nodes
    // NOTE: instead of fetching shard store info one by one from every node (nShards * nNodes requests)
    // we could fetch all shard store info from every node once (nNodes requests)
    // we have to implement a TransportNodesAction instead of using TransportNodesListGatewayStartedShards
    // for fetching shard stores info, that operates on a list of shards instead of a single shard
    new AsyncShardStoresInfoFetches(state.nodes(), routingNodes, shardIdsToFetch, listener).start();
}
Also used : ShardId(org.elasticsearch.index.shard.ShardId) IndexRoutingTable(org.elasticsearch.cluster.routing.IndexRoutingTable) IndexShardRoutingTable(org.elasticsearch.cluster.routing.IndexShardRoutingTable) IndexShardRoutingTable(org.elasticsearch.cluster.routing.IndexShardRoutingTable) IndexRoutingTable(org.elasticsearch.cluster.routing.IndexRoutingTable) RoutingTable(org.elasticsearch.cluster.routing.RoutingTable) RoutingNodes(org.elasticsearch.cluster.routing.RoutingNodes) ClusterShardHealth(org.elasticsearch.cluster.health.ClusterShardHealth) HashSet(java.util.HashSet)

Example 18 with IndexRoutingTable

use of org.elasticsearch.cluster.routing.IndexRoutingTable in project elasticsearch by elastic.

the class MetaDataCreateIndexService method validateShrinkIndex.

/**
     * Validates the settings and mappings for shrinking an index.
     * @return the list of nodes at least one instance of the source index shards are allocated
     */
static List<String> validateShrinkIndex(ClusterState state, String sourceIndex, Set<String> targetIndexMappingsTypes, String targetIndexName, Settings targetIndexSettings) {
    if (state.metaData().hasIndex(targetIndexName)) {
        throw new ResourceAlreadyExistsException(state.metaData().index(targetIndexName).getIndex());
    }
    final IndexMetaData sourceMetaData = state.metaData().index(sourceIndex);
    if (sourceMetaData == null) {
        throw new IndexNotFoundException(sourceIndex);
    }
    // ensure index is read-only
    if (state.blocks().indexBlocked(ClusterBlockLevel.WRITE, sourceIndex) == false) {
        throw new IllegalStateException("index " + sourceIndex + " must be read-only to shrink index. use \"index.blocks.write=true\"");
    }
    if (sourceMetaData.getNumberOfShards() == 1) {
        throw new IllegalArgumentException("can't shrink an index with only one shard");
    }
    if ((targetIndexMappingsTypes.size() > 1 || (targetIndexMappingsTypes.isEmpty() || targetIndexMappingsTypes.contains(MapperService.DEFAULT_MAPPING)) == false)) {
        throw new IllegalArgumentException("mappings are not allowed when shrinking indices" + ", all mappings are copied from the source index");
    }
    if (IndexMetaData.INDEX_NUMBER_OF_SHARDS_SETTING.exists(targetIndexSettings)) {
        // this method applies all necessary checks ie. if the target shards are less than the source shards
        // of if the source shards are divisible by the number of target shards
        IndexMetaData.getRoutingFactor(sourceMetaData, IndexMetaData.INDEX_NUMBER_OF_SHARDS_SETTING.get(targetIndexSettings));
    }
    // now check that index is all on one node
    final IndexRoutingTable table = state.routingTable().index(sourceIndex);
    Map<String, AtomicInteger> nodesToNumRouting = new HashMap<>();
    int numShards = sourceMetaData.getNumberOfShards();
    for (ShardRouting routing : table.shardsWithState(ShardRoutingState.STARTED)) {
        nodesToNumRouting.computeIfAbsent(routing.currentNodeId(), (s) -> new AtomicInteger(0)).incrementAndGet();
    }
    List<String> nodesToAllocateOn = new ArrayList<>();
    for (Map.Entry<String, AtomicInteger> entries : nodesToNumRouting.entrySet()) {
        int numAllocations = entries.getValue().get();
        assert numAllocations <= numShards : "wait what? " + numAllocations + " is > than num shards " + numShards;
        if (numAllocations == numShards) {
            nodesToAllocateOn.add(entries.getKey());
        }
    }
    if (nodesToAllocateOn.isEmpty()) {
        throw new IllegalStateException("index " + sourceIndex + " must have all shards allocated on the same node to shrink index");
    }
    return nodesToAllocateOn;
}
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) IndexRoutingTable(org.elasticsearch.cluster.routing.IndexRoutingTable) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) ResourceAlreadyExistsException(org.elasticsearch.ResourceAlreadyExistsException) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) IndexNotFoundException(org.elasticsearch.index.IndexNotFoundException) ShardRouting(org.elasticsearch.cluster.routing.ShardRouting) Map(java.util.Map) HashMap(java.util.HashMap)

Example 19 with IndexRoutingTable

use of org.elasticsearch.cluster.routing.IndexRoutingTable in project crate by crate.

the class BulkRetryCoordinatorPool method coordinator.

public BulkRetryCoordinator coordinator(ShardId shardId) throws IndexNotFoundException, ShardNotFoundException {
    synchronized (coordinatorsByShardId) {
        BulkRetryCoordinator coordinator = coordinatorsByShardId.get(shardId);
        if (coordinator == null) {
            IndexRoutingTable indexRoutingTable = clusterService.state().routingTable().index(shardId.getIndex());
            if (indexRoutingTable == null) {
                throw new IndexNotFoundException("cannot find index " + shardId.index());
            }
            IndexShardRoutingTable shardRoutingTable = indexRoutingTable.shard(shardId.id());
            if (shardRoutingTable == null) {
                throw new ShardNotFoundException(shardId);
            }
            String nodeId = shardRoutingTable.primaryShard().currentNodeId();
            // wow, that is a long comment!
            synchronized (coordinatorsByNodeId) {
                coordinator = coordinatorsByNodeId.get(nodeId);
                if (coordinator == null) {
                    LOGGER.debug("create new coordinator for node {} and shard {}", nodeId, shardId);
                    coordinator = new BulkRetryCoordinator(threadPool);
                    coordinatorsByNodeId.put(nodeId, coordinator);
                }
            }
            coordinatorsByShardId.put(shardId, coordinator);
        }
        return coordinator;
    }
}
Also used : IndexRoutingTable(org.elasticsearch.cluster.routing.IndexRoutingTable) IndexShardRoutingTable(org.elasticsearch.cluster.routing.IndexShardRoutingTable) ShardNotFoundException(org.elasticsearch.index.shard.ShardNotFoundException) IndexNotFoundException(org.elasticsearch.index.IndexNotFoundException)

Example 20 with IndexRoutingTable

use of org.elasticsearch.cluster.routing.IndexRoutingTable in project elasticsearch by elastic.

the class TransportUpgradeAction method indicesWithMissingPrimaries.

/**
     * Finds all indices that have not all primaries available
     */
private Set<String> indicesWithMissingPrimaries(ClusterState clusterState, String[] concreteIndices) {
    Set<String> indices = new HashSet<>();
    RoutingTable routingTable = clusterState.routingTable();
    for (String index : concreteIndices) {
        IndexRoutingTable indexRoutingTable = routingTable.index(index);
        if (indexRoutingTable.allPrimaryShardsActive() == false) {
            indices.add(index);
        }
    }
    return indices;
}
Also used : IndexRoutingTable(org.elasticsearch.cluster.routing.IndexRoutingTable) IndexRoutingTable(org.elasticsearch.cluster.routing.IndexRoutingTable) RoutingTable(org.elasticsearch.cluster.routing.RoutingTable) HashSet(java.util.HashSet)

Aggregations

IndexRoutingTable (org.elasticsearch.cluster.routing.IndexRoutingTable)35 IndexShardRoutingTable (org.elasticsearch.cluster.routing.IndexShardRoutingTable)29 ShardRouting (org.elasticsearch.cluster.routing.ShardRouting)21 ClusterState (org.elasticsearch.cluster.ClusterState)18 RoutingTable (org.elasticsearch.cluster.routing.RoutingTable)15 IndexMetaData (org.elasticsearch.cluster.metadata.IndexMetaData)14 ShardId (org.elasticsearch.index.shard.ShardId)11 HashSet (java.util.HashSet)7 DiscoveryNode (org.elasticsearch.cluster.node.DiscoveryNode)6 DiscoveryNodes (org.elasticsearch.cluster.node.DiscoveryNodes)6 MetaData (org.elasticsearch.cluster.metadata.MetaData)5 Settings (org.elasticsearch.common.settings.Settings)5 ObjectIntHashMap (com.carrotsearch.hppc.ObjectIntHashMap)3 ArrayList (java.util.ArrayList)3 Set (java.util.Set)3 ClusterName (org.elasticsearch.cluster.ClusterName)3 TestShardRouting (org.elasticsearch.cluster.routing.TestShardRouting)3 UnassignedInfo (org.elasticsearch.cluster.routing.UnassignedInfo)3 IOException (java.io.IOException)2 HashMap (java.util.HashMap)2