<commit_before>/*
 * Licensed to Elasticsearch under one or more contributor
 * license agreements. See the NOTICE file distributed with
 * this work for additional information regarding copyright
 * ownership. Elasticsearch licenses this file to you under
 * the Apache License, Version 2.0 (the "License"); you may
 * not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */

package org.elasticsearch.cluster.routing;

import org.apache.cassandra.dht.Range;
import org.apache.cassandra.dht.Token;
import org.elassandra.index.search.TokenRangesService;
import org.elasticsearch.cluster.ClusterState;
import org.elasticsearch.cluster.metadata.IndexMetaData;
import org.elasticsearch.cluster.node.DiscoveryNodes;
import org.elasticsearch.cluster.routing.allocation.decider.AwarenessAllocationDecider;
import org.elasticsearch.cluster.service.ClusterService;
import org.elasticsearch.common.Nullable;
import org.elasticsearch.common.Strings;
import org.elasticsearch.common.component.AbstractComponent;
import org.elasticsearch.common.settings.ClusterSettings;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.TransportAddress;
import org.elasticsearch.index.Index;
import org.elasticsearch.index.IndexNotFoundException;
import org.elasticsearch.index.IndexService;
import org.elasticsearch.index.shard.ShardId;
import org.elasticsearch.index.shard.ShardNotFoundException;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

public class OperationRouting extends AbstractComponent {

    private final ClusterService clusterService;
    private String[] awarenessAttributes;

    public OperationRouting(Settings settings, ClusterSettings clusterSettings, ClusterService clusterService) {
        super(settings);
        this.clusterService = clusterService;
        this.awarenessAttributes = AwarenessAllocationDecider.CLUSTER_ROUTING_ALLOCATION_AWARENESS_ATTRIBUTE_SETTING.get(settings);
        clusterSettings.addSettingsUpdateConsumer(AwarenessAllocationDecider.CLUSTER_ROUTING_ALLOCATION_AWARENESS_ATTRIBUTE_SETTING,
            this::setAwarenessAttributes);
    }

    public ShardIterator shard(Index index) {
        IndexService indexService = clusterService.indexServiceSafe(index);
        ShardRouting shardRouting = indexService.getShardOrNull(0).routingEntry();
        return new PlainShardIterator(new ShardId(index, 0), Collections.singletonList(shardRouting));
    }
    
    private void setAwarenessAttributes(String[] awarenessAttributes) {
        this.awarenessAttributes = awarenessAttributes;
    }
    
    public ShardIterator indexShards(ClusterState clusterState, String index, String id, @Nullable String routing) {
        return shard(clusterState.metaData().index(index).getIndex());
    }

    public ShardIterator getShards(ClusterState clusterState, String index, String id, @Nullable String routing, @Nullable String preference) {
        return shard(clusterState.metaData().index(index).getIndex());
    }
    
    public ShardIterator getShards(ClusterState clusterState, String index, int shardId, @Nullable String preference) {
        return shard(clusterState.metaData().index(index).getIndex());
    }

    public GroupShardsIterator<ShardIterator> searchShards(ClusterState clusterState, String[] concreteIndices, @Nullable Map<String, Set<String>> routing, @Nullable String preference) {
        return searchShards( clusterState, concreteIndices, null, routing, preference, null, null);
    }
        
    public GroupShardsIterator<ShardIterator> searchShards(ClusterState clusterState, String[] concreteIndices, 
            @Nullable String[] types,
            @Nullable Map<String, 
            Set<String>> routing, 
            @Nullable String preference, 
            Collection<Range<Token>> tokenRanges, 
            TransportAddress src) {
        final Set<IndexShardRoutingTable> shards = computeTargetedShards(clusterState, concreteIndices, types, routing, preference, tokenRanges, src);
        final Set<ShardIterator> set = new HashSet<>(shards.size());
        for (IndexShardRoutingTable shard : shards) {
            ShardIterator iterator = preferenceActiveShardIterator(shard, clusterState.nodes().getLocalNodeId(), clusterState.nodes(), preference);
            if (iterator != null) {
                set.add(iterator);
            }
        }
        if (logger.isDebugEnabled())
            logger.debug("routing to nodes={}", set.stream().map(it -> it.nextOrNull().currentNodeId()).collect(Collectors.joining(",")));
        return new GroupShardsIterator<>(new ArrayList<>(set));
    }

    private static final Map<String, Set<String>> EMPTY_ROUTING = Collections.emptyMap();

    private Set<IndexShardRoutingTable> computeTargetedShards(ClusterState clusterState, String[] concreteIndices, 
            @Nullable String[] types, 
            @Nullable Map<String, 
            Set<String>> routing, 
            @Nullable String preference, 
            @Nullable Collection<Range<Token>> tokenRanges, 
            @Nullable TransportAddress src) {
        routing = routing == null ? EMPTY_ROUTING : routing; // just use an empty map
        final Set<IndexShardRoutingTable> set = new HashSet<>();
        // we use set here and not list since we might get duplicates
        for (String index : concreteIndices) {
            final IndexMetaData indexMetaData = indexMetaData(clusterState, index);
            final IndexRoutingTable indexRouting = new IndexRoutingTable.Builder(indexMetaData.getIndex(), this.clusterService, clusterState, preference, src).build();
            
            // ignore routing if types is empty.<commit_msg>Improve debug message<commit_after>/*
 * Licensed to Elasticsearch under one or more contributor
 * license agreements. See the NOTICE file distributed with
 * this work for additional information regarding copyright
 * ownership. Elasticsearch licenses this file to you under
 * the Apache License, Version 2.0 (the "License"); you may
 * not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */

package org.elasticsearch.cluster.routing;

import org.apache.cassandra.dht.Range;
import org.apache.cassandra.dht.Token;
import org.elassandra.index.search.TokenRangesService;
import org.elasticsearch.cluster.ClusterState;
import org.elasticsearch.cluster.metadata.IndexMetaData;
import org.elasticsearch.cluster.node.DiscoveryNodes;
import org.elasticsearch.cluster.routing.allocation.decider.AwarenessAllocationDecider;
import org.elasticsearch.cluster.service.ClusterService;
import org.elasticsearch.common.Nullable;
import org.elasticsearch.common.Strings;
import org.elasticsearch.common.component.AbstractComponent;
import org.elasticsearch.common.settings.ClusterSettings;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.TransportAddress;
import org.elasticsearch.index.Index;
import org.elasticsearch.index.IndexNotFoundException;
import org.elasticsearch.index.IndexService;
import org.elasticsearch.index.shard.ShardId;
import org.elasticsearch.index.shard.ShardNotFoundException;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

public class OperationRouting extends AbstractComponent {

    private final ClusterService clusterService;
    private String[] awarenessAttributes;

    public OperationRouting(Settings settings, ClusterSettings clusterSettings, ClusterService clusterService) {
        super(settings);
        this.clusterService = clusterService;
        this.awarenessAttributes = AwarenessAllocationDecider.CLUSTER_ROUTING_ALLOCATION_AWARENESS_ATTRIBUTE_SETTING.get(settings);
        clusterSettings.addSettingsUpdateConsumer(AwarenessAllocationDecider.CLUSTER_ROUTING_ALLOCATION_AWARENESS_ATTRIBUTE_SETTING,
            this::setAwarenessAttributes);
    }

    public ShardIterator shard(Index index) {
        IndexService indexService = clusterService.indexServiceSafe(index);
        ShardRouting shardRouting = indexService.getShardOrNull(0).routingEntry();
        return new PlainShardIterator(new ShardId(index, 0), Collections.singletonList(shardRouting));
    }
    
    private void setAwarenessAttributes(String[] awarenessAttributes) {
        this.awarenessAttributes = awarenessAttributes;
    }
    
    public ShardIterator indexShards(ClusterState clusterState, String index, String id, @Nullable String routing) {
        return shard(clusterState.metaData().index(index).getIndex());
    }

    public ShardIterator getShards(ClusterState clusterState, String index, String id, @Nullable String routing, 
            @Nullable String preference) {
        return shard(clusterState.metaData().index(index).getIndex());
    }
    
    public ShardIterator getShards(ClusterState clusterState, String index, int shardId, @Nullable String preference) {
        return shard(clusterState.metaData().index(index).getIndex());
    }

    public GroupShardsIterator<ShardIterator> searchShards(ClusterState clusterState, String[] concreteIndices, 
            @Nullable Map<String, Set<String>> routing, @Nullable String preference) {
        return searchShards( clusterState, concreteIndices, null, routing, preference, null, null);
    }
        
    public GroupShardsIterator<ShardIterator> searchShards(ClusterState clusterState, String[] concreteIndices, 
            @Nullable String[] types,
            @Nullable Map<String, 
            Set<String>> routing, 
            @Nullable String preference, 
            Collection<Range<Token>> tokenRanges, 
            TransportAddress src) {
        final Set<IndexShardRoutingTable> shards = computeTargetedShards(clusterState, concreteIndices, types, routing, preference, tokenRanges, src);
        final Set<ShardIterator> set = new HashSet<>(shards.size());
        for (IndexShardRoutingTable shard : shards) {
            ShardIterator iterator = preferenceActiveShardIterator(shard, clusterState.nodes().getLocalNodeId(), clusterState.nodes(), preference);
            if (iterator != null) {
                set.add(iterator);
            }
        }
        if (logger.isDebugEnabled())
            logger.debug("routing to nodes={}", set.stream()    
                    .filter(it -> it.remaining() > 0)
                    .map(it -> {
                        ShardRouting shard = it.nextOrNull();
                        return shard.currentNodeId()+":"+shard.tokenRanges().toString();
                    })
                    .collect(Collectors.joining(", ")));
        return new GroupShardsIterator<>(new ArrayList<>(set));
    }

    private static final Map<String, Set<String>> EMPTY_ROUTING = Collections.emptyMap();

    private Set<IndexShardRoutingTable> computeTargetedShards(ClusterState clusterState, String[] concreteIndices, 
            @Nullable String[] types, 
            @Nullable Map<String, 
            Set<String>> routing, 
            @Nullable String preference, 
            @Nullable Collection<Range<Token>> tokenRanges, 
            @Nullable TransportAddress src) {
        routing = routing == null ? EMPTY_ROUTING : routing; // just use an empty map
        final Set<IndexShardRoutingTable> set = new HashSet<>();
        // we use set here and not list since we might get duplicates
        for (String index : concreteIndices) {
            final IndexMetaData indexMetaData = indexMetaData(clusterState, index);
            final IndexRoutingTable indexRouting = new IndexRoutingTable.Builder(indexMetaData.getIndex(), this.clusterService, clusterState, preference, src).build();
            
            // ignore routing if types is empty.
{'fraction_non_alphanumeric': 0.08637847924117556, 'fraction_numerical': 0.001010729280049759, 'mean_word_length': 3.877891543420554, 'pattern_counts': {'":': 1, '<': 47, '<?xml version=': 0, '>': 51, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '5630836', 'n_tokens_mistral': 3222, 'n_tokens_neox': 3242, 'n_words': 846}