Search in sources :

Example 1 with GroupShardsIterator

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

the class SearchStatsIT method nodeIdsWithIndex.

private Set<String> nodeIdsWithIndex(String... indices) {
    ClusterState state = client().admin().cluster().prepareState().execute().actionGet().getState();
    GroupShardsIterator allAssignedShardsGrouped = state.routingTable().allAssignedShardsGrouped(indices, true);
    Set<String> nodes = new HashSet<>();
    for (ShardIterator shardIterator : allAssignedShardsGrouped) {
        for (ShardRouting routing : shardIterator.asUnordered()) {
            if (routing.active()) {
                nodes.add(routing.currentNodeId());
            }
        }
    }
    return nodes;
}
Also used : ClusterState(org.elasticsearch.cluster.ClusterState) GroupShardsIterator(org.elasticsearch.cluster.routing.GroupShardsIterator) ShardIterator(org.elasticsearch.cluster.routing.ShardIterator) ShardRouting(org.elasticsearch.cluster.routing.ShardRouting) HashSet(java.util.HashSet)

Example 2 with GroupShardsIterator

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

the class CorruptedFileIT method numShards.

private int numShards(String... index) {
    ClusterState state = client().admin().cluster().prepareState().get().getState();
    GroupShardsIterator shardIterators = state.getRoutingTable().activePrimaryShardsGrouped(index, false);
    return shardIterators.size();
}
Also used : ClusterState(org.elasticsearch.cluster.ClusterState) GroupShardsIterator(org.elasticsearch.cluster.routing.GroupShardsIterator)

Example 3 with GroupShardsIterator

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

the class CorruptedFileIT method testCorruptPrimaryNoReplica.

/**
     * Tests corruption that happens on a single shard when no replicas are present. We make sure that the primary stays unassigned
     * and all other replicas for the healthy shards happens
     */
public void testCorruptPrimaryNoReplica() throws ExecutionException, InterruptedException, IOException {
    int numDocs = scaledRandomIntBetween(100, 1000);
    internalCluster().ensureAtLeastNumDataNodes(2);
    assertAcked(prepareCreate("test").setSettings(Settings.builder().put(IndexMetaData.SETTING_NUMBER_OF_REPLICAS, "0").put(MergePolicyConfig.INDEX_MERGE_ENABLED, false).put(MockFSIndexStore.INDEX_CHECK_INDEX_ON_CLOSE_SETTING.getKey(), // no checkindex - we corrupt shards on purpose
    false).put(IndexSettings.INDEX_TRANSLOG_FLUSH_THRESHOLD_SIZE_SETTING.getKey(), // no translog based flush - it might change the .liv / segments.N files
    new ByteSizeValue(1, ByteSizeUnit.PB))));
    ensureGreen();
    IndexRequestBuilder[] builders = new IndexRequestBuilder[numDocs];
    for (int i = 0; i < builders.length; i++) {
        builders[i] = client().prepareIndex("test", "type").setSource("field", "value");
    }
    indexRandom(true, builders);
    ensureGreen();
    assertAllSuccessful(client().admin().indices().prepareFlush().setForce(true).execute().actionGet());
    // we have to flush at least once here since we don't corrupt the translog
    SearchResponse countResponse = client().prepareSearch().setSize(0).get();
    assertHitCount(countResponse, numDocs);
    ShardRouting shardRouting = corruptRandomPrimaryFile();
    /*
         * we corrupted the primary shard - now lets make sure we never recover from it successfully
         */
    Settings build = Settings.builder().put(IndexMetaData.SETTING_NUMBER_OF_REPLICAS, "1").build();
    client().admin().indices().prepareUpdateSettings("test").setSettings(build).get();
    client().admin().cluster().prepareReroute().get();
    boolean didClusterTurnRed = awaitBusy(() -> {
        ClusterHealthStatus test = client().admin().cluster().health(Requests.clusterHealthRequest("test")).actionGet().getStatus();
        return test == ClusterHealthStatus.RED;
    }, 5, // sometimes on slow nodes the replication / recovery is just dead slow
    TimeUnit.MINUTES);
    final ClusterHealthResponse response = client().admin().cluster().health(Requests.clusterHealthRequest("test")).get();
    if (response.getStatus() != ClusterHealthStatus.RED) {
        logger.info("Cluster turned red in busy loop: {}", didClusterTurnRed);
        logger.info("cluster state:\n{}\n{}", client().admin().cluster().prepareState().get().getState(), client().admin().cluster().preparePendingClusterTasks().get());
    }
    assertThat(response.getStatus(), is(ClusterHealthStatus.RED));
    ClusterState state = client().admin().cluster().prepareState().get().getState();
    GroupShardsIterator shardIterators = state.getRoutingTable().activePrimaryShardsGrouped(new String[] { "test" }, false);
    for (ShardIterator iterator : shardIterators) {
        ShardRouting routing;
        while ((routing = iterator.nextOrNull()) != null) {
            if (routing.getId() == shardRouting.getId()) {
                assertThat(routing.state(), equalTo(ShardRoutingState.UNASSIGNED));
            } else {
                assertThat(routing.state(), anyOf(equalTo(ShardRoutingState.RELOCATING), equalTo(ShardRoutingState.STARTED)));
            }
        }
    }
    final List<Path> files = listShardFiles(shardRouting);
    Path corruptedFile = null;
    for (Path file : files) {
        if (file.getFileName().toString().startsWith("corrupted_")) {
            corruptedFile = file;
            break;
        }
    }
    assertThat(corruptedFile, notNullValue());
}
Also used : Path(java.nio.file.Path) ClusterState(org.elasticsearch.cluster.ClusterState) ClusterHealthResponse(org.elasticsearch.action.admin.cluster.health.ClusterHealthResponse) ByteSizeValue(org.elasticsearch.common.unit.ByteSizeValue) SearchResponse(org.elasticsearch.action.search.SearchResponse) IndexRequestBuilder(org.elasticsearch.action.index.IndexRequestBuilder) ClusterHealthStatus(org.elasticsearch.cluster.health.ClusterHealthStatus) GroupShardsIterator(org.elasticsearch.cluster.routing.GroupShardsIterator) ShardIterator(org.elasticsearch.cluster.routing.ShardIterator) ShardRouting(org.elasticsearch.cluster.routing.ShardRouting) Settings(org.elasticsearch.common.settings.Settings) IndexSettings(org.elasticsearch.index.IndexSettings)

Example 4 with GroupShardsIterator

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

the class SuggestStatsIT method nodeIdsWithIndex.

private Set<String> nodeIdsWithIndex(String... indices) {
    ClusterState state = client().admin().cluster().prepareState().execute().actionGet().getState();
    GroupShardsIterator allAssignedShardsGrouped = state.routingTable().allAssignedShardsGrouped(indices, true);
    Set<String> nodes = new HashSet<>();
    for (ShardIterator shardIterator : allAssignedShardsGrouped) {
        for (ShardRouting routing : shardIterator.asUnordered()) {
            if (routing.active()) {
                nodes.add(routing.currentNodeId());
            }
        }
    }
    return nodes;
}
Also used : ClusterState(org.elasticsearch.cluster.ClusterState) GroupShardsIterator(org.elasticsearch.cluster.routing.GroupShardsIterator) ShardIterator(org.elasticsearch.cluster.routing.ShardIterator) ShardRouting(org.elasticsearch.cluster.routing.ShardRouting) HashSet(java.util.HashSet)

Example 5 with GroupShardsIterator

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

the class TransportSearchAction method executeSearch.

private void executeSearch(SearchTask task, long startTimeInMillis, SearchRequest searchRequest, String[] localIndices, List<ShardIterator> remoteShardIterators, Function<String, Transport.Connection> remoteConnections, ClusterState clusterState, Map<String, AliasFilter> remoteAliasMap, ActionListener<SearchResponse> listener) {
    clusterState.blocks().globalBlockedRaiseException(ClusterBlockLevel.READ);
    // TODO: I think startTime() should become part of ActionRequest and that should be used both for index name
    // date math expressions and $now in scripts. This way all apis will deal with now in the same way instead
    // of just for the _search api
    final Index[] indices;
    if (localIndices.length == 0 && remoteShardIterators.size() > 0) {
        // don't search on _all if only remote indices were specified
        indices = Index.EMPTY_ARRAY;
    } else {
        indices = indexNameExpressionResolver.concreteIndices(clusterState, searchRequest.indicesOptions(), startTimeInMillis, localIndices);
    }
    Map<String, AliasFilter> aliasFilter = buildPerIndexAliasFilter(searchRequest, clusterState, indices, remoteAliasMap);
    Map<String, Set<String>> routingMap = indexNameExpressionResolver.resolveSearchRouting(clusterState, searchRequest.routing(), searchRequest.indices());
    String[] concreteIndices = new String[indices.length];
    for (int i = 0; i < indices.length; i++) {
        concreteIndices[i] = indices[i].getName();
    }
    GroupShardsIterator localShardsIterator = clusterService.operationRouting().searchShards(clusterState, concreteIndices, routingMap, searchRequest.preference());
    GroupShardsIterator shardIterators = mergeShardsIterators(localShardsIterator, remoteShardIterators);
    failIfOverShardCountLimit(clusterService, shardIterators.size());
    Map<String, Float> concreteIndexBoosts = resolveIndexBoosts(searchRequest, clusterState);
    // optimize search type for cases where there is only one shard group to search on
    if (shardIterators.size() == 1) {
        // if we only have one group, then we always want Q_A_F, no need for DFS, and no need to do THEN since we hit one shard
        searchRequest.searchType(QUERY_THEN_FETCH);
    }
    if (searchRequest.isSuggestOnly()) {
        // disable request cache if we have only suggest
        searchRequest.requestCache(false);
        switch(searchRequest.searchType()) {
            case DFS_QUERY_THEN_FETCH:
                // convert to Q_T_F if we have only suggest
                searchRequest.searchType(QUERY_THEN_FETCH);
                break;
        }
    }
    final DiscoveryNodes nodes = clusterState.nodes();
    Function<String, Transport.Connection> connectionLookup = (nodeId) -> {
        final DiscoveryNode discoveryNode = nodes.get(nodeId);
        final Transport.Connection connection;
        if (discoveryNode != null) {
            connection = searchTransportService.getConnection(discoveryNode);
        } else {
            connection = remoteConnections.apply(nodeId);
        }
        if (connection == null) {
            throw new IllegalStateException("no node found for id: " + nodeId);
        }
        return connection;
    };
    searchAsyncAction(task, searchRequest, shardIterators, startTimeInMillis, connectionLookup, clusterState.version(), Collections.unmodifiableMap(aliasFilter), concreteIndexBoosts, listener).start();
}
Also used : ShardIterator(org.elasticsearch.cluster.routing.ShardIterator) Property(org.elasticsearch.common.settings.Setting.Property) ClusterService(org.elasticsearch.cluster.service.ClusterService) HashMap(java.util.HashMap) Index(org.elasticsearch.index.Index) Function(java.util.function.Function) SearchService(org.elasticsearch.search.SearchService) GroupShardsIterator(org.elasticsearch.cluster.routing.GroupShardsIterator) Strings(org.elasticsearch.common.Strings) Inject(org.elasticsearch.common.inject.Inject) ArrayList(java.util.ArrayList) ClusterState(org.elasticsearch.cluster.ClusterState) DiscoveryNode(org.elasticsearch.cluster.node.DiscoveryNode) Settings(org.elasticsearch.common.settings.Settings) HandledTransportAction(org.elasticsearch.action.support.HandledTransportAction) Map(java.util.Map) SearchSourceBuilder(org.elasticsearch.search.builder.SearchSourceBuilder) ThreadPool(org.elasticsearch.threadpool.ThreadPool) TransportService(org.elasticsearch.transport.TransportService) ClusterBlockLevel(org.elasticsearch.cluster.block.ClusterBlockLevel) DiscoveryNodes(org.elasticsearch.cluster.node.DiscoveryNodes) ActionFilters(org.elasticsearch.action.support.ActionFilters) Transport(org.elasticsearch.transport.Transport) Setting(org.elasticsearch.common.settings.Setting) Executor(java.util.concurrent.Executor) Set(java.util.Set) QUERY_THEN_FETCH(org.elasticsearch.action.search.SearchType.QUERY_THEN_FETCH) AliasFilter(org.elasticsearch.search.internal.AliasFilter) List(java.util.List) IndexNameExpressionResolver(org.elasticsearch.cluster.metadata.IndexNameExpressionResolver) Task(org.elasticsearch.tasks.Task) Collections(java.util.Collections) ActionListener(org.elasticsearch.action.ActionListener) AliasFilter(org.elasticsearch.search.internal.AliasFilter) DiscoveryNode(org.elasticsearch.cluster.node.DiscoveryNode) Set(java.util.Set) Index(org.elasticsearch.index.Index) GroupShardsIterator(org.elasticsearch.cluster.routing.GroupShardsIterator) DiscoveryNodes(org.elasticsearch.cluster.node.DiscoveryNodes)

Aggregations

GroupShardsIterator (org.elasticsearch.cluster.routing.GroupShardsIterator)21 ClusterState (org.elasticsearch.cluster.ClusterState)16 ShardIterator (org.elasticsearch.cluster.routing.ShardIterator)16 ShardRouting (org.elasticsearch.cluster.routing.ShardRouting)16 Path (java.nio.file.Path)4 ArrayList (java.util.ArrayList)4 HashSet (java.util.HashSet)4 PlainShardIterator (org.elasticsearch.cluster.routing.PlainShardIterator)4 Index (org.elasticsearch.index.Index)4 HashMap (java.util.HashMap)3 Map (java.util.Map)3 Set (java.util.Set)3 TreeSet (java.util.TreeSet)3 NodesStatsResponse (org.elasticsearch.action.admin.cluster.node.stats.NodesStatsResponse)3 ClusterSettings (org.elasticsearch.common.settings.ClusterSettings)3 ShardId (org.elasticsearch.index.shard.ShardId)3 FsInfo (org.elasticsearch.monitor.fs.FsInfo)3 ImmutableMap (com.google.common.collect.ImmutableMap)2 List (java.util.List)2 IndexMetaData (org.elasticsearch.cluster.metadata.IndexMetaData)2