Apache Solr open-source search software
SOLR-13445: Preferred replicas on nodes with same system properties as the query master
Cao Manh Dat6b5b74bc9c95
diff --git a/solr/CHANGES.txt b/solr/CHANGES.txtindex a942c3b690e..6cc873a2d5d 100644--- a/solr/CHANGES.txt+++ b/solr/CHANGES.txt@@ -77,6 +77,7 @@ New Features* SOLR-13306: Add a request parameter to execute a streaming expression locally+* SOLR-13445: Preferred replicas on nodes with same system properties as the query master (Cao Manh Dat)================== 8.1.0 ==================diff --git a/solr/core/src/java/org/apache/solr/cloud/NodesSysPropsCacher.java b/solr/core/src/java/org/apache/solr/cloud/NodesSysPropsCacher.javanew file mode 100644index 00000000000..acd765db644--- /dev/null+++ b/solr/core/src/java/org/apache/solr/cloud/NodesSysPropsCacher.java@@ -0,0 +1,204 @@+/*+ * Licensed to the Apache Software Foundation (ASF) under one or more+ * contributor license agreements. See the NOTICE file distributed with+ * this work for additional information regarding copyright ownership.+ * The ASF 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.apache.solr.cloud;++import java.lang.invoke.MethodHandles;+import java.util.ArrayList;+import java.util.Collection;+import java.util.Collections;+import java.util.HashMap;+import java.util.Map;+import java.util.Set;+import java.util.concurrent.ConcurrentHashMap;+import java.util.concurrent.atomic.AtomicBoolean;+import java.util.concurrent.atomic.AtomicInteger;+import java.util.stream.Collectors;++import com.google.common.annotations.VisibleForTesting;+import org.apache.solr.client.solrj.cloud.NodeStateProvider;+import org.apache.solr.client.solrj.impl.PreferenceRule;+import org.apache.solr.common.SolrCloseable;+import org.apache.solr.common.cloud.ZkStateReader;+import org.apache.solr.common.params.ShardParams;+import org.apache.solr.util.TestInjection;+import org.slf4j.Logger;+import org.slf4j.LoggerFactory;++import static org.apache.solr.common.cloud.rule.ImplicitSnitch.SYSPROP;++/**+ * Caching other nodes system properties. The properties that will be cached based on the value define in+ * {@link org.apache.solr.common.cloud.ZkStateReader#DEFAULT_SHARD_PREFERENCES } of+ * {@link org.apache.solr.common.cloud.ZkStateReader#CLUSTER_PROPS }.+ * If that key does not present then this cacher will do nothing.+ *+ * The cache will be refresh whenever /live_nodes get changed.+ */+public class NodesSysPropsCacher implements SolrCloseable {+ private static final Logger log = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());+ private static final int NUM_RETRY = 5;++ private final AtomicBoolean isRunning = new AtomicBoolean(false);+ private final NodeStateProvider nodeStateProvider;+ private final Map<String, String> additionalProps = TestInjection.injectAdditionalProps();+ private final String currentNode;+ private final ConcurrentHashMap<String, Map<String, Object>> cache = new ConcurrentHashMap<>();+ private final AtomicInteger fetchCounting = new AtomicInteger(0);++ private volatile boolean isClosed;+ private volatile Collection<String> tags = new ArrayList<>();++ NodesSysPropsCacher(NodeStateProvider nodeStateProvider,+ String currentNode,+ ZkStateReader stateReader) {+ this.nodeStateProvider = nodeStateProvider;+ this.currentNode = currentNode;++ stateReader.registerClusterPropertiesListener(properties -> {+ Collection<String> tags = new ArrayList<>();+ String shardPreferences = (String) properties.getOrDefault(ZkStateReader.DEFAULT_SHARD_PREFERENCES, "");+ if (shardPreferences.contains(ShardParams.SHARDS_PREFERENCE_NODE_WITH_SAME_SYSPROP)) {+ try {+ tags = PreferenceRule+ .from(shardPreferences)+ .stream()+ .filter(r -> ShardParams.SHARDS_PREFERENCE_NODE_WITH_SAME_SYSPROP.equals(r.name))+ .map(r -> r.value)+ .collect(Collectors.toSet());+ } catch (Exception e) {+ log.info("Error on parsing shards preference:{}", shardPreferences);+ }+ }++ if (tags.isEmpty()) {+ pause();+ } else {+ start(tags);+ // start fetching now+ fetchSysProps(stateReader.getClusterState().getLiveNodes());+ }+ return isClosed;+ });++ stateReader.registerLiveNodesListener((oldLiveNodes, newLiveNodes) -> {+ fetchSysProps(newLiveNodes);+ return isClosed;+ });+ }++ private void start(Collection<String> tags) {+ if (isClosed)+ return;+ this.tags = tags;+ isRunning.set(true);+ }++ private void fetchSysProps(Set<String> newLiveNodes) {+ if (isRunning.get()) {+ int fetchRound = fetchCounting.incrementAndGet();+ //TODO smarter keeping caching entries by relying on Stat.cversion+ cache.clear();+ for (String node: newLiveNodes) {+ // this might takes some times to finish, therefore if there are a latter change in listener+ // triggering this method, skipping the old runner+ if (isClosed && fetchRound != fetchCounting.get())+ return;++ if (currentNode.equals(node)) {+ Map<String, String> props = new HashMap<>();+ for (String tag : tags) {+ String propName = tag.substring(SYSPROP.length());+ if (additionalProps != null && additionalProps.containsKey(propName)) {+ props.put(tag, additionalProps.get(propName));+ } else {+ props.put(tag, System.getProperty(propName));+ }+ }+ cache.put(node, Collections.unmodifiableMap(props));+ } else {+ fetchRemoteProps(node, fetchRound);+ }++ }+ }+ }++ private void fetchRemoteProps(String node, int fetchRound) {+ for (int i = 0; i < NUM_RETRY; i++) {+ if (isClosed && fetchRound != fetchCounting.get())+ return;++ try {+ Map<String, Object> props = nodeStateProvider.getNodeValues(node, tags);+ cache.put(node, Collections.unmodifiableMap(props));+ break;+ } catch (Exception e) {+ try {+ // 1, 4, 9+ int backOffTime = 1000 * (i+1);+ backOffTime = backOffTime * backOffTime;+ backOffTime = Math.min(10000, backOffTime);+ Thread.sleep(backOffTime);+ } catch (InterruptedException e1) {+ Thread.currentThread().interrupt();+ log.info("Exception on caching node:{} system.properties:{}, retry {}/{}", node, tags, i+1, NUM_RETRY, e);+ break;+ }+ log.info("Exception on caching node:{} system.properties:{}, retry {}/{}", node, tags, i+1, NUM_RETRY, e);+ }+ }+ }++ public Map<String, Object> getSysProps(String node, Collection<String> tags) {+ Map<String, Object> props = cache.get(node);+ HashMap<String, Object> result = new HashMap<>();+ if (props != null) {+ for (String tag: tags) {+ if (props.containsKey(tag)) {+ result.put(tag, props.get(tag));+ }+ }+ }+ return result;+ }++ @VisibleForTesting+ public int getCacheSize() {+ return cache.size();+ }++ @VisibleForTesting+ public boolean isRunning() {+ return isRunning.get();+ }++ private void pause() {+ isRunning.set(false);+ }++ @Override+ public boolean isClosed() {+ return isClosed;+ }++ @Override+ public void close() {+ isClosed = true;+ pause();+ }+}diff --git a/solr/core/src/java/org/apache/solr/cloud/ZkController.java b/solr/core/src/java/org/apache/solr/cloud/ZkController.javaindex b5bced1856d..f9fa06aba55 100644--- a/solr/core/src/java/org/apache/solr/cloud/ZkController.java+++ b/solr/core/src/java/org/apache/solr/cloud/ZkController.java@@ -215,6 +215,7 @@ public class ZkController implements Closeable {private String baseURL; // example: http://127.0.0.1:54065/solrprivate final CloudConfig cloudConfig;+ private final NodesSysPropsCacher sysPropsCacher;private LeaderElector overseerElector;@@ -462,6 +463,8 @@ public class ZkController implements Closeable {this.overseerJobQueue = overseer.getStateUpdateQueue();this.overseerCollectionQueue = overseer.getCollectionQueue(zkClient);this.overseerConfigSetQueue = overseer.getConfigSetQueue(zkClient);+ this.sysPropsCacher = new NodesSysPropsCacher(getSolrCloudManager().getNodeStateProvider(),+ getNodeName(), zkStateReader);assert ObjectReleaseTracker.track(this);}@@ -525,6 +528,10 @@ public class ZkController implements Closeable {}}+ public NodesSysPropsCacher getSysPropsCacher() {+ return sysPropsCacher;+ }+private void closeOutstandingElections(final CurrentCoreDescriptorProvider registerOnReconnect) {List<CoreDescriptor> descriptors = registerOnReconnect.getCurrentDescriptors();@@ -614,6 +621,7 @@ public class ZkController implements Closeable {} finally {+ sysPropsCacher.close();customThreadPool.submit(() -> Collections.singleton(cloudSolrClient).parallelStream().forEach(IOUtils::closeQuietly));customThreadPool.submit(() -> Collections.singleton(cloudManager).parallelStream().forEach(IOUtils::closeQuietly));diff --git a/solr/core/src/java/org/apache/solr/handler/admin/MetricsHandler.java b/solr/core/src/java/org/apache/solr/handler/admin/MetricsHandler.javaindex 752e0218688..f61d799e62b 100644--- a/solr/core/src/java/org/apache/solr/handler/admin/MetricsHandler.java+++ b/solr/core/src/java/org/apache/solr/handler/admin/MetricsHandler.java@@ -48,6 +48,7 @@ import org.apache.solr.request.SolrQueryRequest;import org.apache.solr.response.SolrQueryResponse;import org.apache.solr.security.AuthorizationContext;import org.apache.solr.security.PermissionNameProvider;+import org.apache.solr.util.TestInjection;import org.apache.solr.util.stats.MetricUtils;/**@@ -69,6 +70,7 @@ public class MetricsHandler extends RequestHandlerBase implements PermissionNameprivate static final Pattern KEY_REGEX = Pattern.compile("(?<!" + Pattern.quote("\\") + ")" + Pattern.quote(":"));private CoreContainer cc;+ private final Map<String, String> injectedSysProps = TestInjection.injectAdditionalProps();public MetricsHandler() {this.metricManager = null;@@ -158,6 +160,12 @@ public class MetricsHandler extends RequestHandlerBase implements PermissionName// use escaped versionskey = parts[0] + ":" + parts[1];}+ if (injectedSysProps != null+ && SolrMetricManager.JVM_REGISTRY.equals(registryName)+ && "system.properties".equals(metricName) && injectedSysProps.containsKey(propertyName)) {+ result.add(registryName+":"+metricName+":"+propertyName, injectedSysProps.get(propertyName));+ continue;+ }MetricUtils.convertMetric(key, m, propertyFilter, false, true, true, false, ":", (k, v) -> {if ((v instanceof Map) && propertyName != null) {((Map)v).forEach((k1, v1) -> result.add(k + ":" + k1, v1));diff --git a/solr/core/src/java/org/apache/solr/handler/component/HttpShardHandlerFactory.java b/solr/core/src/java/org/apache/solr/handler/component/HttpShardHandlerFactory.javaindex 4f0db88a41b..cf16fa2f13b 100644--- a/solr/core/src/java/org/apache/solr/handler/component/HttpShardHandlerFactory.java+++ b/solr/core/src/java/org/apache/solr/handler/component/HttpShardHandlerFactory.java@@ -23,11 +23,12 @@ import java.io.IOException;import java.lang.invoke.MethodHandles;import java.net.MalformedURLException;import java.net.URL;-import java.util.ArrayList;import java.util.Arrays;+import java.util.Collection;import java.util.Collections;import java.util.Comparator;import java.util.List;+import java.util.Map;import java.util.Random;import java.util.Set;import java.util.concurrent.ArrayBlockingQueue;@@ -48,12 +49,15 @@ import org.apache.solr.client.solrj.impl.HttpClientUtil;import org.apache.solr.client.solrj.impl.HttpSolrClient;import org.apache.solr.client.solrj.impl.LBHttp2SolrClient;import org.apache.solr.client.solrj.impl.LBSolrClient;+import org.apache.solr.client.solrj.impl.PreferenceRule;import org.apache.solr.client.solrj.request.QueryRequest;+import org.apache.solr.cloud.NodesSysPropsCacher;import org.apache.solr.cloud.ZkController;import org.apache.solr.common.SolrException;import org.apache.solr.common.SolrException.ErrorCode;import org.apache.solr.common.cloud.ClusterState;import org.apache.solr.common.cloud.Replica;+import org.apache.solr.common.cloud.ZkStateReader;import org.apache.solr.common.params.CommonParams;import org.apache.solr.common.params.ShardParams;import org.apache.solr.common.params.SolrParams;@@ -342,31 +346,26 @@ public class HttpShardHandlerFactory extends ShardHandlerFactory implements org.* to one bad node.*/static class NodePreferenceRulesComparator implements Comparator<Object> {- private static class PreferenceRule {- public final String name;- public final String value;-- public PreferenceRule(String name, String value) {- this.name = name;- this.value = value;- }- }private final SolrQueryRequest request;+ private final NodesSysPropsCacher sysPropsCache;+ private final String nodeName;private List<PreferenceRule> preferenceRules;private String localHostAddress = null;- public NodePreferenceRulesComparator(final List<String> sortRules, final SolrQueryRequest request) {+ public NodePreferenceRulesComparator(final List<PreferenceRule> sortRules, final SolrQueryRequest request) {this.request = request;- this.preferenceRules = new ArrayList<PreferenceRule>(sortRules.size());- sortRules.forEach(rule -> {- String[] parts = rule.split(":", 2);- if (parts.length != 2) {- throw new IllegalArgumentException("Invalid " + ShardParams.SHARDS_PREFERENCE + " rule: " + rule);- }- this.preferenceRules.add(new PreferenceRule(parts[0], parts[1]));- });+ if (request != null && request.getCore().getCoreContainer().getZkController() != null) {+ ZkController zkController = request.getCore().getCoreContainer().getZkController();+ sysPropsCache = zkController.getSysPropsCacher();+ nodeName = zkController.getNodeName();+ } else {+ sysPropsCache = null;+ nodeName = null;+ }+ this.preferenceRules = sortRules;}+@Overridepublic int compare(Object left, Object right) {for (PreferenceRule preferenceRule: this.preferenceRules) {@@ -381,6 +380,14 @@ public class HttpShardHandlerFactory extends ShardHandlerFactory implements org.lhs = hasCoreUrlPrefix(left, preferenceRule.value);rhs = hasCoreUrlPrefix(right, preferenceRule.value);break;+ case ShardParams.SHARDS_PREFERENCE_NODE_WITH_SAME_SYSPROP:+ if (sysPropsCache == null) {+ throw new IllegalArgumentException("Unable to get the NodesSysPropsCacher" ++ " on sorting replicas by preference:"+ preferenceRule.value);+ }+ lhs = hasSameMetric(left, preferenceRule.value);+ rhs = hasSameMetric(right, preferenceRule.value);+ break;default:throw new IllegalArgumentException("Invalid " + ShardParams.SHARDS_PREFERENCE + " type: " + preferenceRule.name);}@@ -390,6 +397,19 @@ public class HttpShardHandlerFactory extends ShardHandlerFactory implements org.}return 0;}++ private boolean hasSameMetric(Object o, String metricTag) {+ if (!(o instanceof Replica)) {+ return false;+ }++ Collection<String> tags = Collections.singletonList(metricTag);+ String otherNodeName = ((Replica) o).getNodeName();+ Map<String, Object> currentNodeMetric = sysPropsCache.getSysProps(nodeName, tags);+ Map<String, Object> otherNodeMetric = sysPropsCache.getSysProps(otherNodeName, tags);+ return currentNodeMetric.equals(otherNodeMetric);+ }+private boolean hasCoreUrlPrefix(Object o, String prefix) {final String s;if (o instanceof String) {@@ -431,9 +451,18 @@ public class HttpShardHandlerFactory extends ShardHandlerFactory implements org.protected ReplicaListTransformer getReplicaListTransformer(final SolrQueryRequest req) {final SolrParams params = req.getParams();+ ZkController zkController = req.getCore().getCoreContainer().getZkController();+ String defaultShardPreference = "";+ if (zkController != null) {+ defaultShardPreference = zkController.getZkStateReader().getClusterProperties()+ .getOrDefault(ZkStateReader.DEFAULT_SHARD_PREFERENCES, "")+ .toString();+ }++@SuppressWarnings("deprecation")final boolean preferLocalShards = params.getBool(CommonParams.PREFER_LOCAL_SHARDS, false);- final String shardsPreferenceSpec = params.get(ShardParams.SHARDS_PREFERENCE, "");+ final String shardsPreferenceSpec = params.get(ShardParams.SHARDS_PREFERENCE, defaultShardPreference);if (preferLocalShards || !shardsPreferenceSpec.isEmpty()) {if (preferLocalShards && !shardsPreferenceSpec.isEmpty()) {@@ -442,9 +471,9 @@ public class HttpShardHandlerFactory extends ShardHandlerFactory implements org."preferLocalShards is deprecated and must not be used with shards.preference");}- List<String> preferenceRules = StrUtils.splitSmart(shardsPreferenceSpec, ',');+ List<PreferenceRule> preferenceRules = PreferenceRule.from(shardsPreferenceSpec);if (preferLocalShards) {- preferenceRules.add(ShardParams.SHARDS_PREFERENCE_REPLICA_LOCATION + ":" + ShardParams.REPLICA_LOCAL);+ preferenceRules.add(new PreferenceRule(ShardParams.SHARDS_PREFERENCE_REPLICA_LOCATION, ShardParams.REPLICA_LOCAL));}return new ShufflingReplicaListTransformer(r) {diff --git a/solr/core/src/java/org/apache/solr/util/TestInjection.java b/solr/core/src/java/org/apache/solr/util/TestInjection.javaindex 7a49ba496e8..12de7feb2b0 100644--- a/solr/core/src/java/org/apache/solr/util/TestInjection.java+++ b/solr/core/src/java/org/apache/solr/util/TestInjection.java@@ -20,6 +20,7 @@ import java.lang.invoke.MethodHandles;import java.lang.reflect.Method;import java.util.Collections;import java.util.HashSet;+import java.util.Map;import java.util.Random;import java.util.Set;import java.util.Timer;@@ -51,7 +52,7 @@ import org.slf4j.LoggerFactory;* @lucene.internal*/public class TestInjection {-+public static class TestShutdownFailError extends OutOfMemoryError {public TestShutdownFailError(String msg) {@@ -142,6 +143,8 @@ public class TestInjection {public volatile static boolean uifOutOfMemoryError = false;+ public volatile static Map<String, String> additionalSystemProps = null;+private volatile static CountDownLatch notifyPauseForeverDone = new CountDownLatch(1);public static void notifyPauseForeverDone() {@@ -150,6 +153,7 @@ public class TestInjection {}public static void reset() {+ additionalSystemProps = null;nonGracefullClose = null;failReplicaRequests = null;failUpdateRequests = null;@@ -484,6 +488,10 @@ public class TestInjection {return true;}+ public static Map<String,String> injectAdditionalProps() {+ return additionalSystemProps;+ }+public static boolean injectUIFOutOfMemoryError() {if (uifOutOfMemoryError ) {throw new OutOfMemoryError("Test Injection");diff --git a/solr/core/src/test/org/apache/solr/cloud/RoutingToNodesWithPropertiesTest.java b/solr/core/src/test/org/apache/solr/cloud/RoutingToNodesWithPropertiesTest.javanew file mode 100644index 00000000000..8335f15ca51--- /dev/null+++ b/solr/core/src/test/org/apache/solr/cloud/RoutingToNodesWithPropertiesTest.java@@ -0,0 +1,267 @@+/*+ * Licensed to the Apache Software Foundation (ASF) under one or more+ * contributor license agreements. See the NOTICE file distributed with+ * this work for additional information regarding copyright ownership.+ * The ASF 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.apache.solr.cloud;++import java.lang.invoke.MethodHandles;+import java.util.ArrayList;+import java.util.Collections;+import java.util.LinkedList;+import java.util.List;+import java.util.Map;+import java.util.concurrent.TimeUnit;+import java.util.stream.Collectors;++import com.google.common.collect.ImmutableMap;+import org.apache.solr.client.solrj.SolrQuery;+import org.apache.solr.client.solrj.SolrRequest;+import org.apache.solr.client.solrj.cloud.NodeStateProvider;+import org.apache.solr.client.solrj.cloud.SolrCloudManager;+import org.apache.solr.client.solrj.embedded.JettySolrRunner;+import org.apache.solr.client.solrj.impl.SolrClientCloudManager;+import org.apache.solr.client.solrj.request.CollectionAdminRequest;+import org.apache.solr.client.solrj.request.UpdateRequest;+import org.apache.solr.client.solrj.response.QueryResponse;+import org.apache.solr.common.cloud.Replica;+import org.apache.solr.common.cloud.Slice;+import org.apache.solr.common.cloud.ZkStateReader;+import org.apache.solr.common.params.ModifiableSolrParams;+import org.apache.solr.common.params.ShardParams;+import org.apache.solr.common.util.NamedList;+import org.apache.solr.common.util.SimpleOrderedMap;+import org.apache.solr.common.util.TimeSource;+import org.apache.solr.handler.component.TestTrackingShardHandlerFactory;+import org.apache.solr.handler.component.TrackingShardHandlerFactory;+import org.apache.solr.util.TestInjection;+import org.apache.solr.util.TimeOut;+import org.junit.AfterClass;+import org.junit.BeforeClass;+import org.junit.Test;+import org.slf4j.Logger;+import org.slf4j.LoggerFactory;++import static org.apache.solr.common.cloud.rule.ImplicitSnitch.SYSPROP;++public class RoutingToNodesWithPropertiesTest extends SolrCloudTestCase {+ private static final Logger log = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());+ private static final String PROP_NAME = SYSPROP + "zone";++ final static List<String> ZONE1_NODES = new ArrayList<>();+ final static List<String> ZONE2_NODES = new ArrayList<>();+ final static LinkedList<TrackingShardHandlerFactory.ShardRequestAndParams> ZONE1_QUEUE = new LinkedList<>();+ final static LinkedList<TrackingShardHandlerFactory.ShardRequestAndParams> ZONE2_QUEUE = new LinkedList<>();++ final static String COLLECTION = "coll";++ @BeforeClass+ public static void setupCluster() throws Exception {+ TestInjection.additionalSystemProps = ImmutableMap.of("zone", "us-west1");+ configureCluster(2)+ .withSolrXml(TEST_PATH().resolve("solr-trackingshardhandler.xml"))+ .addConfig("config", TEST_PATH().resolve("configsets").resolve("cloud-minimal").resolve("conf"))+ .configure();++ ZONE1_NODES.addAll(cluster.getJettySolrRunners().stream().map(JettySolrRunner::getNodeName).collect(Collectors.toSet()));+ TestInjection.additionalSystemProps = ImmutableMap.of("zone", "us-west2");+ ZONE2_NODES.add(cluster.startJettySolrRunner().getNodeName());+ ZONE2_NODES.add(cluster.startJettySolrRunner().getNodeName());++ String commands = "{set-cluster-policy :[{" ++ " 'replica':'#EQUAL'," ++ " 'shard':'#EACH'," ++ " 'sysprop.zone':'#EACH'}]}";++ SolrRequest req = CloudTestUtils.AutoScalingRequest.create(SolrRequest.METHOD.POST, commands);+ NamedList<Object> response = cluster.getSolrClient().request(req);++ CollectionAdminRequest.createCollection(COLLECTION, 2, 2)+ .process(cluster.getSolrClient());+ cluster.waitForActiveCollection(COLLECTION, 2, 4);++ // Checking putting replicas+ for (Slice slice : getCollectionState(COLLECTION).getSlices()) {+ int numReplicaInZone1 = 0;+ int numReplicaInZone2 = 0;+ for (Replica replica : slice.getReplicas()) {+ if (ZONE1_NODES.contains(replica.getNodeName()))+ numReplicaInZone1++;+ if (ZONE2_NODES.contains(replica.getNodeName()))+ numReplicaInZone2++;+ }++ assertEquals(1, numReplicaInZone1);+ assertEquals(1, numReplicaInZone2);+ }++ // check inject props+ SolrCloudManager cloudManager = new SolrClientCloudManager(new ZkDistributedQueueFactory(cluster.getZkClient()),+ cluster.getSolrClient());+ for (String zone1Node: ZONE1_NODES) {+ NodeStateProvider nodeStateProvider = cloudManager.getNodeStateProvider();+ Map<String, Object> map = nodeStateProvider.getNodeValues(zone1Node, Collections.singletonList(PROP_NAME));+ assertEquals("us-west1", map.get(PROP_NAME));+ }++ for (String zone1Node: ZONE2_NODES) {+ NodeStateProvider nodeStateProvider = cloudManager.getNodeStateProvider();+ Map<String, Object> map = nodeStateProvider.getNodeValues(zone1Node, Collections.singletonList(PROP_NAME));+ assertEquals("us-west2", map.get(PROP_NAME));+ }++ for (JettySolrRunner jetty : cluster.getJettySolrRunners()) {+ if (ZONE1_NODES.contains(jetty.getNodeName())) {+ ((TrackingShardHandlerFactory)jetty.getCoreContainer().getShardHandlerFactory()).setTrackingQueue(ZONE1_QUEUE);+ } else {+ ((TrackingShardHandlerFactory)jetty.getCoreContainer().getShardHandlerFactory()).setTrackingQueue(ZONE2_QUEUE);+ }+ }++ for (int i = 0; i < 20; i++) {+ new UpdateRequest()+ .add("id", String.valueOf(i))+ .process(cluster.getSolrClient(), COLLECTION);+ }++ new UpdateRequest()+ .commit(cluster.getSolrClient(), COLLECTION);+ }++ @AfterClass+ public static void afterSuperClass() {+ TestInjection.reset();+ }++ @Test+ public void test() throws Exception {+ final int NUM_TRY = 10;+ CollectionAdminRequest+ .setClusterProperty(ZkStateReader.DEFAULT_SHARD_PREFERENCES, ShardParams.SHARDS_PREFERENCE_NODE_WITH_SAME_SYSPROP +":"+PROP_NAME)+ .process(cluster.getSolrClient());+ {+ TimeOut timeOut = new TimeOut(20, TimeUnit.SECONDS, TimeSource.NANO_TIME);+ timeOut.waitFor("Timeout waiting for sysprops are cached in all nodes", () -> {+ int total = 0;+ for (JettySolrRunner runner : cluster.getJettySolrRunners()) {+ total += runner.getCoreContainer().getZkController().getSysPropsCacher().getCacheSize();+ }+ return total == cluster.getJettySolrRunners().size() * cluster.getJettySolrRunners().size();+ });+ }++ for (int i = 0; i < NUM_TRY; i++) {+ SolrQuery qRequest = new SolrQuery("*:*");+ ModifiableSolrParams qParams = new ModifiableSolrParams();+ qParams.add(ShardParams.SHARDS_INFO, "true");+ qRequest.add(qParams);+ QueryResponse qResponse = cluster.getSolrClient().query(COLLECTION, qRequest);++ Object shardsInfo = qResponse.getResponse().get(ShardParams.SHARDS_INFO);+ assertNotNull("Unable to obtain "+ShardParams.SHARDS_INFO, shardsInfo);+ SimpleOrderedMap<?> shardsInfoMap = (SimpleOrderedMap<?>)shardsInfo;+ String firstReplicaAddr = ((SimpleOrderedMap) shardsInfoMap.getVal(0)).get("shardAddress").toString();+ String secondReplicaAddr = ((SimpleOrderedMap) shardsInfoMap.getVal(1)).get("shardAddress").toString();+ boolean firstReplicaInZone1 = false;+ boolean secondReplicaInZone1 = false;+ for (String zone1Node : ZONE1_NODES) {+ zone1Node = zone1Node.replace("_solr", "");+ firstReplicaInZone1 = firstReplicaInZone1 || firstReplicaAddr.contains(zone1Node);+ secondReplicaInZone1 = secondReplicaInZone1 || secondReplicaAddr.contains(zone1Node);+ }++ assertEquals(firstReplicaInZone1, secondReplicaInZone1);+ }++ // intense asserting using TrackingShardHandlerFactory+ assertRoutingToSameZone();++ // Cachers should be stop running+ CollectionAdminRequest+ .setClusterProperty(ZkStateReader.DEFAULT_SHARD_PREFERENCES, ShardParams.SHARDS_PREFERENCE_REPLICA_TYPE+":PULL")+ .process(cluster.getSolrClient());+ {+ TimeOut timeOut = new TimeOut(20, TimeUnit.SECONDS, TimeSource.NANO_TIME);+ timeOut.waitFor("Timeout waiting for sysPropsCache stop", () -> {+ int numNodeStillRunningCache = 0;+ for (JettySolrRunner runner: cluster.getJettySolrRunners()) {+ if (runner.getCoreContainer().getZkController().getSysPropsCacher().isRunning()) {+ numNodeStillRunningCache++;+ }+ }+ return numNodeStillRunningCache == 0;+ });+ }++ // Testing disable default shard preferences+ CollectionAdminRequest+ .setClusterProperty(ZkStateReader.DEFAULT_SHARD_PREFERENCES, null)+ .process(cluster.getSolrClient());+ {+ TimeOut timeOut = new TimeOut(20, TimeUnit.SECONDS, TimeSource.NANO_TIME);+ timeOut.waitFor("Timeout waiting cluster properties get updated", () -> {+ int numNodeGetUpdatedPref = 0;+ int numNodeStillRunningCache = 0;+ for (JettySolrRunner runner: cluster.getJettySolrRunners()) {+ if (runner.getCoreContainer().getZkController()+ .getZkStateReader().getClusterProperties().containsKey(ZkStateReader.DEFAULT_SHARD_PREFERENCES)) {+ numNodeGetUpdatedPref++;+ }+ if (runner.getCoreContainer().getZkController().getSysPropsCacher().isRunning()) {+ numNodeStillRunningCache++;+ }+ }+ return numNodeGetUpdatedPref == 0 && numNodeStillRunningCache == 0;+ });+ }++ int totalTimeSameZoneGetHitted = 0;+ for (int i = 0; i < NUM_TRY; i++) {+ SolrQuery qRequest = new SolrQuery("*:*");+ ModifiableSolrParams qParams = new ModifiableSolrParams();+ qParams.add(ShardParams.SHARDS_INFO, "true");+ qRequest.add(qParams);+ QueryResponse qResponse = cluster.getSolrClient().query(COLLECTION, qRequest);++ Object shardsInfo = qResponse.getResponse().get(ShardParams.SHARDS_INFO);+ assertNotNull("Unable to obtain "+ShardParams.SHARDS_INFO, shardsInfo);+ SimpleOrderedMap<?> shardsInfoMap = (SimpleOrderedMap<?>)shardsInfo;+ String firstReplicaAddr = ((SimpleOrderedMap) shardsInfoMap.getVal(0)).get("shardAddress").toString();+ String secondReplicaAddr = ((SimpleOrderedMap) shardsInfoMap.getVal(1)).get("shardAddress").toString();+ boolean firstReplicaInZone1 = false;+ boolean secondReplicaInZone1 = false;+ for (String zone1Node : ZONE1_NODES) {+ zone1Node = zone1Node.replace("_solr", "");+ firstReplicaInZone1 = firstReplicaInZone1 || firstReplicaAddr.contains(zone1Node);+ secondReplicaInZone1 = secondReplicaInZone1 || secondReplicaAddr.contains(zone1Node);+ }+ totalTimeSameZoneGetHitted += firstReplicaInZone1 == secondReplicaInZone1 ? 1 : 0;+ }+ assertTrue("Hitting same zone after " + NUM_TRY + " queries",+ totalTimeSameZoneGetHitted < NUM_TRY);++ }++ private void assertRoutingToSameZone() {+ for (TrackingShardHandlerFactory.ShardRequestAndParams sreq: ZONE1_QUEUE) {+ String firstNode = sreq.shard.split("\\|")[0];+ assertTrue(ZONE1_NODES.stream().anyMatch(s -> firstNode.contains(s.replace('_','/'))));+ }+ for (TrackingShardHandlerFactory.ShardRequestAndParams sreq: ZONE2_QUEUE) {+ String firstNode = sreq.shard.split("\\|")[0];+ assertTrue(ZONE2_NODES.stream().anyMatch(s -> firstNode.contains(s.replace('_','/'))));+ }+ }+}diff --git a/solr/core/src/test/org/apache/solr/handler/component/TestHttpShardHandlerFactory.java b/solr/core/src/test/org/apache/solr/handler/component/TestHttpShardHandlerFactory.javaindex 2ee73cb02bf..bde28f9372a 100644--- a/solr/core/src/test/org/apache/solr/handler/component/TestHttpShardHandlerFactory.java+++ b/solr/core/src/test/org/apache/solr/handler/component/TestHttpShardHandlerFactory.java@@ -32,13 +32,13 @@ import java.util.List;import java.util.Set;import org.apache.solr.SolrTestCaseJ4;import org.apache.solr.client.solrj.impl.LBSolrClient;+import org.apache.solr.client.solrj.impl.PreferenceRule;import org.apache.solr.client.solrj.request.QueryRequest;import org.apache.solr.common.SolrException;import org.apache.solr.common.cloud.ClusterState;import org.apache.solr.common.cloud.Replica;import org.apache.solr.common.cloud.ZkStateReader;import org.apache.solr.common.params.ShardParams;-import org.apache.solr.common.util.StrUtils;import org.apache.solr.core.CoreContainer;import org.apache.solr.handler.component.HttpShardHandlerFactory.WhitelistHostChecker;import org.junit.AfterClass;@@ -153,11 +153,8 @@ public class TestHttpShardHandlerFactory extends SolrTestCaseJ4 {);// Simple replica type rule- List<String> rules = StrUtils.splitSmart(- ShardParams.SHARDS_PREFERENCE_REPLICA_TYPE + ":NRT," +- ShardParams.SHARDS_PREFERENCE_REPLICA_TYPE + ":TLOG",- ','- );+ List<PreferenceRule> rules = PreferenceRule.from(ShardParams.SHARDS_PREFERENCE_REPLICA_TYPE + ":NRT," ++ ShardParams.SHARDS_PREFERENCE_REPLICA_TYPE + ":TLOG");HttpShardHandlerFactory.NodePreferenceRulesComparator comparator =new HttpShardHandlerFactory.NodePreferenceRulesComparator(rules, null);replicas.sort(comparator);@@ -165,18 +162,15 @@ public class TestHttpShardHandlerFactory extends SolrTestCaseJ4 {assertEquals("node2", replicas.get(1).getNodeName());// Another simple replica type rule- rules = StrUtils.splitSmart(- ShardParams.SHARDS_PREFERENCE_REPLICA_TYPE + ":TLOG," +- ShardParams.SHARDS_PREFERENCE_REPLICA_TYPE + ":NRT",- ','- );+ rules = PreferenceRule.from(ShardParams.SHARDS_PREFERENCE_REPLICA_TYPE + ":TLOG," ++ ShardParams.SHARDS_PREFERENCE_REPLICA_TYPE + ":NRT");comparator = new HttpShardHandlerFactory.NodePreferenceRulesComparator(rules, null);replicas.sort(comparator);assertEquals("node2", replicas.get(0).getNodeName());assertEquals("node1", replicas.get(1).getNodeName());// replicaLocation rule- rules = StrUtils.splitSmart(ShardParams.SHARDS_PREFERENCE_REPLICA_LOCATION + ":http://host2:8983", ',');+ rules = PreferenceRule.from(ShardParams.SHARDS_PREFERENCE_REPLICA_LOCATION + ":http://host2:8983");comparator = new HttpShardHandlerFactory.NodePreferenceRulesComparator(rules, null);replicas.sort(comparator);assertEquals("node2", replicas.get(0).getNodeName());@@ -196,12 +190,10 @@ public class TestHttpShardHandlerFactory extends SolrTestCaseJ4 {);// replicaType and replicaLocation combined rule- rules = StrUtils.splitSmart(+ rules = PreferenceRule.from(ShardParams.SHARDS_PREFERENCE_REPLICA_TYPE + ":NRT," +ShardParams.SHARDS_PREFERENCE_REPLICA_TYPE + ":TLOG," +- ShardParams.SHARDS_PREFERENCE_REPLICA_LOCATION + ":http://host2_2",- ','- );+ ShardParams.SHARDS_PREFERENCE_REPLICA_LOCATION + ":http://host2_2");comparator = new HttpShardHandlerFactory.NodePreferenceRulesComparator(rules, null);replicas.sort(comparator);assertEquals("node1", replicas.get(0).getNodeName());@@ -210,17 +202,16 @@ public class TestHttpShardHandlerFactory extends SolrTestCaseJ4 {assertEquals("node3", replicas.get(3).getNodeName());// Bad rule- rules = StrUtils.splitSmart(ShardParams.SHARDS_PREFERENCE_REPLICA_TYPE, ',');+try {- comparator = new HttpShardHandlerFactory.NodePreferenceRulesComparator(rules, null);- replicas.sort(comparator);+ rules = PreferenceRule.from(ShardParams.SHARDS_PREFERENCE_REPLICA_TYPE);fail();} catch (IllegalArgumentException e) {assertEquals("Invalid shards.preference rule: " + ShardParams.SHARDS_PREFERENCE_REPLICA_TYPE, e.getMessage());}// Unknown rule- rules = StrUtils.splitSmart("badRule:test", ',');+ rules = PreferenceRule.from("badRule:test");try {comparator = new HttpShardHandlerFactory.NodePreferenceRulesComparator(rules, null);replicas.sort(comparator);diff --git a/solr/solrj/src/java/org/apache/solr/client/solrj/impl/PreferenceRule.java b/solr/solrj/src/java/org/apache/solr/client/solrj/impl/PreferenceRule.javanew file mode 100644index 00000000000..6ada81d48d1--- /dev/null+++ b/solr/solrj/src/java/org/apache/solr/client/solrj/impl/PreferenceRule.java@@ -0,0 +1,47 @@+/*+ * Licensed to the Apache Software Foundation (ASF) under one or more+ * contributor license agreements. See the NOTICE file distributed with+ * this work for additional information regarding copyright ownership.+ * The ASF 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.apache.solr.client.solrj.impl;++import java.util.ArrayList;+import java.util.List;++import org.apache.solr.common.params.ShardParams;+import org.apache.solr.common.util.StrUtils;++public class PreferenceRule {+ public final String name;+ public final String value;++ public PreferenceRule(String name, String value) {+ this.name = name;+ this.value = value;+ }++ public static List<PreferenceRule> from(String rules) {+ List<String> prefs = StrUtils.splitSmart(rules, ',');+ ArrayList<PreferenceRule> preferenceRules = new ArrayList<>(prefs.size());+ prefs.forEach(rule -> {+ String[] parts = rule.split(":", 2);+ if (parts.length != 2) {+ throw new IllegalArgumentException("Invalid " + ShardParams.SHARDS_PREFERENCE + " rule: " + rule);+ }+ preferenceRules.add(new PreferenceRule(parts[0], parts[1]));+ });+ return preferenceRules;+ }+}diff --git a/solr/solrj/src/java/org/apache/solr/common/cloud/ClusterPropertiesListener.java b/solr/solrj/src/java/org/apache/solr/common/cloud/ClusterPropertiesListener.javanew file mode 100644index 00000000000..f93b54c40c1--- /dev/null+++ b/solr/solrj/src/java/org/apache/solr/common/cloud/ClusterPropertiesListener.java@@ -0,0 +1,39 @@+/*+ * Licensed to the Apache Software Foundation (ASF) under one or more+ * contributor license agreements. See the NOTICE file distributed with+ * this work for additional information regarding copyright ownership.+ * The ASF 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.apache.solr.common.cloud;++import java.util.Map;++/**+ * Listener that can be used with {@link ZkStateReader#registerClusterPropertiesListener(ClusterPropertiesListener)}+ * and called whenever the cluster properties changes.+ */+public interface ClusterPropertiesListener {++ /**+ * Called when a change in the cluster properties occurs.+ *+ * Note that, due to the way Zookeeper watchers are implemented, a single call may be+ * the result of several state changes+ *+ * @param properties current cluster properties+ *+ * @return true if the listener should be removed+ */+ boolean onChange(Map<String, Object> properties);+}diff --git a/solr/solrj/src/java/org/apache/solr/common/cloud/ZkStateReader.java b/solr/solrj/src/java/org/apache/solr/common/cloud/ZkStateReader.javaindex 2e98189a790..0ec88c4e2cd 100644--- a/solr/solrj/src/java/org/apache/solr/common/cloud/ZkStateReader.java+++ b/solr/solrj/src/java/org/apache/solr/common/cloud/ZkStateReader.java@@ -117,6 +117,7 @@ public class ZkStateReader implements SolrCloseable {public static final String SOLR_AUTOSCALING_NODE_ADDED_PATH = "/autoscaling/nodeAdded";public static final String SOLR_AUTOSCALING_NODE_LOST_PATH = "/autoscaling/nodeLost";+ public static final String DEFAULT_SHARD_PREFERENCES = "defaultShardPreferences";public static final String REPLICATION_FACTOR = "replicationFactor";public static final String MAX_SHARDS_PER_NODE = "maxShardsPerNode";public static final String AUTO_ADD_REPLICAS = "autoAddReplicas";@@ -189,6 +190,8 @@ public class ZkStateReader implements SolrCloseable {private Set<LiveNodesListener> liveNodesListeners = ConcurrentHashMap.newKeySet();+ private Set<ClusterPropertiesListener> clusterPropertiesListeners = ConcurrentHashMap.newKeySet();+/** Used to submit notifications to Collection Properties watchers in order **/private final ExecutorService collectionPropsNotifications = ExecutorUtil.newMDCAwareSingleThreadExecutor(new SolrjNamedThreadFactory("collectionPropsNotifications"));@@ -241,6 +244,7 @@ public class ZkStateReader implements SolrCloseable {URL_SCHEME,AUTO_ADD_REPLICAS,CoreAdminParams.BACKUP_LOCATION,+ DEFAULT_SHARD_PREFERENCES,MAX_CORES_PER_NODE,CollectionAdminParams.DEFAULTS)));@@ -813,6 +817,19 @@ public class ZkStateReader implements SolrCloseable {}}+ public void registerClusterPropertiesListener(ClusterPropertiesListener listener) {+ // fire it once with current properties+ if (listener.onChange(getClusterProperties())) {+ removeClusterPropertiesListener(listener);+ } else {+ clusterPropertiesListeners.add(listener);+ }+ }++ public void removeClusterPropertiesListener(ClusterPropertiesListener listener) {+ clusterPropertiesListeners.remove(listener);+ }+public void registerLiveNodesListener(LiveNodesListener listener) {// fire it once with current live nodesif (listener.onChange(new TreeSet<>(getClusterState().getLiveNodes()), new TreeSet<>(getClusterState().getLiveNodes()))) {@@ -1054,6 +1071,10 @@ public class ZkStateReader implements SolrCloseable {byte[] data = zkClient.getData(ZkStateReader.CLUSTER_PROPS, clusterPropertiesWatcher, new Stat(), true);this.clusterProperties = ClusterProperties.convertCollectionDefaultsToNestedFormat((Map<String, Object>) Utils.fromJSON(data));log.debug("Loaded cluster properties: {}", this.clusterProperties);++ for (ClusterPropertiesListener listener: clusterPropertiesListeners) {+ listener.onChange(getClusterProperties());+ }return;} catch (KeeperException.NoNodeException e) {this.clusterProperties = Collections.emptyMap();diff --git a/solr/solrj/src/java/org/apache/solr/common/params/ShardParams.java b/solr/solrj/src/java/org/apache/solr/common/params/ShardParams.javaindex 262c18af79a..7844e03f719 100644--- a/solr/solrj/src/java/org/apache/solr/common/params/ShardParams.java+++ b/solr/solrj/src/java/org/apache/solr/common/params/ShardParams.java@@ -63,6 +63,9 @@ public interface ShardParams {/** Replica location sort rule */String SHARDS_PREFERENCE_REPLICA_LOCATION = "replica.location";+ /** Node with same system property sort rule */+ String SHARDS_PREFERENCE_NODE_WITH_SAME_SYSPROP = "node.sysprop";+/** Value denoting local replicas */String REPLICA_LOCAL = "local";