Search in sources :

Example 6 with ShardIterator

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

the class RoutingIteratorTests method testRandomRouting.

public void testRandomRouting() {
    MetaData metaData = MetaData.builder().put(IndexMetaData.builder("test1").settings(settings(Version.CURRENT)).numberOfShards(1).numberOfReplicas(1)).put(IndexMetaData.builder("test2").settings(settings(Version.CURRENT)).numberOfShards(1).numberOfReplicas(1)).build();
    RoutingTable routingTable = RoutingTable.builder().addAsNew(metaData.index("test1")).addAsNew(metaData.index("test2")).build();
    ShardIterator shardIterator = routingTable.index("test1").shard(0).shardsRandomIt();
    ShardRouting shardRouting1 = shardIterator.nextOrNull();
    assertThat(shardRouting1, notNullValue());
    assertThat(shardIterator.nextOrNull(), notNullValue());
    assertThat(shardIterator.nextOrNull(), nullValue());
    shardIterator = routingTable.index("test1").shard(0).shardsRandomIt();
    ShardRouting shardRouting2 = shardIterator.nextOrNull();
    assertThat(shardRouting2, notNullValue());
    ShardRouting shardRouting3 = shardIterator.nextOrNull();
    assertThat(shardRouting3, notNullValue());
    assertThat(shardIterator.nextOrNull(), nullValue());
    assertThat(shardRouting1, not(sameInstance(shardRouting2)));
    assertThat(shardRouting1, sameInstance(shardRouting3));
}
Also used : RoutingTable(org.elasticsearch.cluster.routing.RoutingTable) MetaData(org.elasticsearch.cluster.metadata.MetaData) IndexMetaData(org.elasticsearch.cluster.metadata.IndexMetaData) ShardIterator(org.elasticsearch.cluster.routing.ShardIterator) PlainShardIterator(org.elasticsearch.cluster.routing.PlainShardIterator) ShardRouting(org.elasticsearch.cluster.routing.ShardRouting)

Example 7 with ShardIterator

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

the class RoutingIteratorTests method testIterator2.

public void testIterator2() {
    MetaData metaData = MetaData.builder().put(IndexMetaData.builder("test1").settings(settings(Version.CURRENT)).numberOfShards(1).numberOfReplicas(1)).put(IndexMetaData.builder("test2").settings(settings(Version.CURRENT)).numberOfShards(1).numberOfReplicas(1)).build();
    RoutingTable routingTable = RoutingTable.builder().addAsNew(metaData.index("test1")).addAsNew(metaData.index("test2")).build();
    ShardIterator shardIterator = routingTable.index("test1").shard(0).shardsIt(0);
    assertThat(shardIterator.size(), equalTo(2));
    ShardRouting shardRouting1 = shardIterator.nextOrNull();
    assertThat(shardRouting1, notNullValue());
    assertThat(shardIterator.remaining(), equalTo(1));
    ShardRouting shardRouting2 = shardIterator.nextOrNull();
    assertThat(shardRouting2, notNullValue());
    assertThat(shardIterator.remaining(), equalTo(0));
    assertThat(shardRouting2, not(sameInstance(shardRouting1)));
    assertThat(shardIterator.nextOrNull(), nullValue());
    assertThat(shardIterator.remaining(), equalTo(0));
    assertThat(shardIterator.nextOrNull(), nullValue());
    assertThat(shardIterator.remaining(), equalTo(0));
    shardIterator = routingTable.index("test1").shard(0).shardsIt(1);
    assertThat(shardIterator.size(), equalTo(2));
    ShardRouting shardRouting3 = shardIterator.nextOrNull();
    assertThat(shardRouting1, notNullValue());
    ShardRouting shardRouting4 = shardIterator.nextOrNull();
    assertThat(shardRouting2, notNullValue());
    assertThat(shardRouting2, not(sameInstance(shardRouting1)));
    assertThat(shardIterator.nextOrNull(), nullValue());
    assertThat(shardIterator.nextOrNull(), nullValue());
    assertThat(shardRouting1, not(sameInstance(shardRouting3)));
    assertThat(shardRouting2, not(sameInstance(shardRouting4)));
    assertThat(shardRouting1, sameInstance(shardRouting4));
    assertThat(shardRouting2, sameInstance(shardRouting3));
    shardIterator = routingTable.index("test1").shard(0).shardsIt(2);
    assertThat(shardIterator.size(), equalTo(2));
    ShardRouting shardRouting5 = shardIterator.nextOrNull();
    assertThat(shardRouting5, notNullValue());
    ShardRouting shardRouting6 = shardIterator.nextOrNull();
    assertThat(shardRouting6, notNullValue());
    assertThat(shardRouting6, not(sameInstance(shardRouting5)));
    assertThat(shardIterator.nextOrNull(), nullValue());
    assertThat(shardIterator.nextOrNull(), nullValue());
    assertThat(shardRouting5, sameInstance(shardRouting1));
    assertThat(shardRouting6, sameInstance(shardRouting2));
    shardIterator = routingTable.index("test1").shard(0).shardsIt(3);
    assertThat(shardIterator.size(), equalTo(2));
    ShardRouting shardRouting7 = shardIterator.nextOrNull();
    assertThat(shardRouting7, notNullValue());
    ShardRouting shardRouting8 = shardIterator.nextOrNull();
    assertThat(shardRouting8, notNullValue());
    assertThat(shardRouting8, not(sameInstance(shardRouting7)));
    assertThat(shardIterator.nextOrNull(), nullValue());
    assertThat(shardIterator.nextOrNull(), nullValue());
    assertThat(shardRouting7, sameInstance(shardRouting3));
    assertThat(shardRouting8, sameInstance(shardRouting4));
    shardIterator = routingTable.index("test1").shard(0).shardsIt(4);
    assertThat(shardIterator.size(), equalTo(2));
    ShardRouting shardRouting9 = shardIterator.nextOrNull();
    assertThat(shardRouting9, notNullValue());
    ShardRouting shardRouting10 = shardIterator.nextOrNull();
    assertThat(shardRouting10, notNullValue());
    assertThat(shardRouting10, not(sameInstance(shardRouting9)));
    assertThat(shardIterator.nextOrNull(), nullValue());
    assertThat(shardIterator.nextOrNull(), nullValue());
    assertThat(shardRouting9, sameInstance(shardRouting5));
    assertThat(shardRouting10, sameInstance(shardRouting6));
}
Also used : RoutingTable(org.elasticsearch.cluster.routing.RoutingTable) MetaData(org.elasticsearch.cluster.metadata.MetaData) IndexMetaData(org.elasticsearch.cluster.metadata.IndexMetaData) ShardIterator(org.elasticsearch.cluster.routing.ShardIterator) PlainShardIterator(org.elasticsearch.cluster.routing.PlainShardIterator) ShardRouting(org.elasticsearch.cluster.routing.ShardRouting)

Example 8 with ShardIterator

use of org.elasticsearch.cluster.routing.ShardIterator 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 9 with ShardIterator

use of org.elasticsearch.cluster.routing.ShardIterator 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 10 with ShardIterator

use of org.elasticsearch.cluster.routing.ShardIterator 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

ShardIterator (org.elasticsearch.cluster.routing.ShardIterator)30 ShardRouting (org.elasticsearch.cluster.routing.ShardRouting)22 GroupShardsIterator (org.elasticsearch.cluster.routing.GroupShardsIterator)16 ClusterState (org.elasticsearch.cluster.ClusterState)14 PlainShardIterator (org.elasticsearch.cluster.routing.PlainShardIterator)11 HashMap (java.util.HashMap)7 DiscoveryNode (org.elasticsearch.cluster.node.DiscoveryNode)7 Index (org.elasticsearch.index.Index)7 ArrayList (java.util.ArrayList)6 IndexMetaData (org.elasticsearch.cluster.metadata.IndexMetaData)6 MetaData (org.elasticsearch.cluster.metadata.MetaData)6 RoutingTable (org.elasticsearch.cluster.routing.RoutingTable)6 ShardId (org.elasticsearch.index.shard.ShardId)6 AliasFilter (org.elasticsearch.search.internal.AliasFilter)6 HashSet (java.util.HashSet)4 Map (java.util.Map)4 Set (java.util.Set)4 ActionListener (org.elasticsearch.action.ActionListener)4 Transport (org.elasticsearch.transport.Transport)4 Path (java.nio.file.Path)3