Apache Solr open-source search software
SOLR-10798: Add support for different replica types in the new policy framework
Noble Paule204ab0eefd3
diff --git a/solr/core/src/test/org/apache/solr/cloud/autoscaling/AutoScalingHandlerTest.java b/solr/core/src/test/org/apache/solr/cloud/autoscaling/AutoScalingHandlerTest.javaindex 3da155fdb3a..74b61609862 100644--- a/solr/core/src/test/org/apache/solr/cloud/autoscaling/AutoScalingHandlerTest.java+++ b/solr/core/src/test/org/apache/solr/cloud/autoscaling/AutoScalingHandlerTest.java@@ -46,6 +46,7 @@ import org.junit.BeforeClass;import org.junit.Test;import static org.apache.solr.common.cloud.ZkStateReader.SOLR_AUTOSCALING_CONF_PATH;+import static org.apache.solr.common.util.Utils.getObjectByPath;/*** Test for AutoScalingHandler@@ -688,7 +689,8 @@ public class AutoScalingHandlerTest extends SolrCloudTestCase {for (Map<String, Object> violation : violations) {assertEquals("readApiTestViolations", violation.get("collection"));assertEquals("shard1", violation.get("shard"));- assertEquals(Utils.makeMap("replica", "3", "delta", -1), violation.get("violation"));+ assertEquals(-1l, getObjectByPath(violation, true, "violation/delta"));+ assertEquals(3l, getObjectByPath(violation, true, "violation/replica/NRT"));assertNotNull(violation.get("clause"));}}diff --git a/solr/solrj/src/java/org/apache/solr/client/solrj/impl/SolrClientDataProvider.java b/solr/solrj/src/java/org/apache/solr/client/solrj/impl/SolrClientDataProvider.javaindex 6fb42232747..6f6d3091583 100644--- a/solr/solrj/src/java/org/apache/solr/client/solrj/impl/SolrClientDataProvider.java+++ b/solr/solrj/src/java/org/apache/solr/client/solrj/impl/SolrClientDataProvider.java@@ -75,13 +75,10 @@ public class SolrClientDataProvider implements ClusterDataProvider, MapWriter {DocCollection coll = ref.get();if (coll == null) return;coll.forEachReplica((shard, replica) -> {- Map<String, Map<String, List<ReplicaInfo>>> nodeData = data.get(replica.getNodeName());- if (nodeData == null) data.put(replica.getNodeName(), nodeData = new HashMap<>());- Map<String, List<ReplicaInfo>> collData = nodeData.get(collName);- if (collData == null) nodeData.put(collName, collData = new HashMap<>());- List<ReplicaInfo> replicas = collData.get(shard);- if (replicas == null) collData.put(shard, replicas = new ArrayList<>());- replicas.add(new ReplicaInfo(replica.getName(), collName, shard, new HashMap<>()));+ Map<String, Map<String, List<ReplicaInfo>>> nodeData = data.computeIfAbsent(replica.getNodeName(), k -> new HashMap<>());+ Map<String, List<ReplicaInfo>> collData = nodeData.computeIfAbsent(collName, k -> new HashMap<>());+ List<ReplicaInfo> replicas = collData.computeIfAbsent(shard, k -> new ArrayList<>());+ replicas.add(new ReplicaInfo(replica.getName(), collName, shard,replica.getType(), new HashMap<>()));});});}diff --git a/solr/solrj/src/java/org/apache/solr/cloud/autoscaling/AddReplicaSuggester.java b/solr/solrj/src/java/org/apache/solr/cloud/autoscaling/AddReplicaSuggester.javaindex 587077792dc..bbdf5a7fd35 100644--- a/solr/solrj/src/java/org/apache/solr/cloud/autoscaling/AddReplicaSuggester.java+++ b/solr/solrj/src/java/org/apache/solr/cloud/autoscaling/AddReplicaSuggester.java@@ -22,6 +22,7 @@ import java.util.List;import org.apache.solr.client.solrj.SolrRequest;import org.apache.solr.client.solrj.request.CollectionAdminRequest;import org.apache.solr.cloud.autoscaling.Policy.Suggester;+import org.apache.solr.common.cloud.Replica;class AddReplicaSuggester extends Suggester {@@ -34,6 +35,7 @@ class AddReplicaSuggester extends Suggester {SolrRequest tryEachNode(boolean strict) {String coll = (String) hints.get(Hint.COLL);String shard = (String) hints.get(Hint.SHARD);+ Replica.Type type = Replica.Type.get((String) hints.get(Hint.REPLICATYPE));if (coll == null || shard == null)throw new RuntimeException("add-replica requires 'collection' and 'shard'");//iterate through elements and identify the least loaded@@ -44,7 +46,7 @@ class AddReplicaSuggester extends Suggester {Row row = getMatrix().get(i);if(!row.isLive) continue;if (!isAllowed(row.node, Hint.TARGET_NODE)) continue;- Row tmpRow = row.addReplica(coll, shard);+ Row tmpRow = row.addReplica(coll, shard, type);tmpRow.violations.clear();List<Clause.Violation> errs = testChangedMatrix(strict, getModifiedMatrix(getMatrix(), tmpRow, i));@@ -57,9 +59,10 @@ class AddReplicaSuggester extends Suggester {}if (targetNodeIndex != null) {// there are no rule violations- getMatrix().set(targetNodeIndex, getMatrix().get(targetNodeIndex).addReplica(coll, shard));+ getMatrix().set(targetNodeIndex, getMatrix().get(targetNodeIndex).addReplica(coll, shard, type));return CollectionAdminRequest.addReplicaToShard(coll, shard)+ .setType(type).setNode(getMatrix().get(targetNodeIndex).node);}diff --git a/solr/solrj/src/java/org/apache/solr/cloud/autoscaling/Clause.java b/solr/solrj/src/java/org/apache/solr/cloud/autoscaling/Clause.javaindex 5e4078a4290..09053a4b18c 100644--- a/solr/solrj/src/java/org/apache/solr/cloud/autoscaling/Clause.java+++ b/solr/solrj/src/java/org/apache/solr/cloud/autoscaling/Clause.java@@ -23,15 +23,17 @@ import java.util.Arrays;import java.util.Collections;import java.util.HashMap;import java.util.HashSet;+import java.util.LinkedHashMap;import java.util.List;+import java.util.Locale;import java.util.Map;import java.util.Objects;import java.util.Optional;import java.util.Set;-import java.util.concurrent.atomic.AtomicInteger;import org.apache.solr.cloud.autoscaling.Policy.ReplicaInfo;import org.apache.solr.common.MapWriter;+import org.apache.solr.common.cloud.Replica;import org.apache.solr.common.cloud.rule.ImplicitSnitch;import org.apache.solr.common.util.StrUtils;import org.apache.solr.common.util.Utils;@@ -52,11 +54,14 @@ import static org.apache.solr.common.params.CoreAdminParams.SHARD;public class Clause implements MapWriter, Comparable<Clause> {Map<String, Object> original;Condition collection, shard, replica, tag, globalTag;+ final Replica.Type type;boolean strict = true;Clause(Map<String, Object> m) {this.original = m;+ String type = (String) m.get("type");+ this.type = type == null || ANY.equals(type) ? null : Replica.Type.valueOf(type.toUpperCase(Locale.ROOT));strict = Boolean.parseBoolean(String.valueOf(m.getOrDefault("strict", "true")));Optional<String> globalTagName = m.keySet().stream().filter(Policy.GLOBAL_ONLY_TAGS::contains).findFirst();if (globalTagName.isPresent()) {@@ -100,24 +105,29 @@ public class Clause implements MapWriter, Comparable<Clause> {tag = parse(s, singletonMap(s, o));}+ private int compareTypes(Replica.Type t1, Replica.Type t2) {+ if (t1 == null && t2 == null) return 0;+ if (t1 != null && t2 == null) return -1;+ if (t1 == null) return 1;+ return 0;+ }+@Overridepublic int compareTo(Clause that) {- try {- int v = Integer.compare(this.tag.op.priority, that.tag.op.priority);- if (v != 0) return v;- if (this.isPerCollectiontag() && that.isPerCollectiontag()) {- v = Integer.compare(this.replica.op.priority, that.replica.op.priority);- if (v == 0) {- v = Long.compare((Long) this.replica.val, (Long) that.replica.val);- v = this.replica.op == LESS_THAN ? v : v * -1;- }- return v;- } else {- return 0;+ int v = Integer.compare(this.tag.op.priority, that.tag.op.priority);+ if (v != 0) return v;+ if (this.isPerCollectiontag() && that.isPerCollectiontag()) {+ v = Integer.compare(this.replica.op.priority, that.replica.op.priority);+ if (v == 0) {// higher the number of replicas , harder to satisfy+ v = Long.compare((Long) this.replica.val, (Long) that.replica.val);+ v = this.replica.op == LESS_THAN ? v : v * -1;}- } catch (NullPointerException e) {- throw e;+ if (v == 0) v = compareTypes(this.type, that.type);+ return v;+ } else {+ return 0;}+}void addTags(List<String> params) {@@ -125,7 +135,7 @@ public class Clause implements MapWriter, Comparable<Clause> {if (tag != null && !params.contains(tag.name)) params.add(tag.name);}- static class Condition {+ class Condition {final String name;final Object val;final Operand op;@@ -136,15 +146,8 @@ public class Clause implements MapWriter, Comparable<Clause> {this.op = op;}- TestStatus match(Row row) {- return op.match(val, row.getVal(name));- }-- TestStatus match(Object testVal) {- return op.match(this.val, testVal);- }-boolean isPass(Object inputVal) {+ if (inputVal instanceof ReplicaCount) inputVal = ((ReplicaCount) inputVal).getVal(type);return op.match(val, validate(name, inputVal, false)) == PASS;}@@ -161,12 +164,12 @@ public class Clause implements MapWriter, Comparable<Clause> {return false;}- public Integer delta(Object val) {+ public Long delta(Object val) {return op.delta(this.val, val);}}- static Condition parse(String s, Map m) {+ Condition parse(String s, Map m) {Object expectedVal = null;Object val = m.get(s);try {@@ -197,12 +200,12 @@ public class Clause implements MapWriter, Comparable<Clause> {public class Violation implements MapWriter {final String shard, coll, node;final Object actualVal;- final Integer delta;//how far is the actual value from the expected value+ final Long delta;//how far is the actual value from the expected valuefinal Object tagKey;private final int hash;- private Violation(String coll, String shard, String node, Object actualVal, Integer delta, Object tagKey) {+ private Violation(String coll, String shard, String node, Object actualVal, Long delta, Object tagKey) {this.shard = shard;this.coll = coll;this.node = node;@@ -239,6 +242,11 @@ public class Clause implements MapWriter, Comparable<Clause> {return false;}+ @Override+ public String toString() {+ return Utils.toJSONString(Utils.getDeepCopy(toMap(new LinkedHashMap<>()), 5));+ }+@Overridepublic void writeMap(EntryWriter ew) throws IOException {ew.putIfNotNull("collection", coll);@@ -246,8 +254,8 @@ public class Clause implements MapWriter, Comparable<Clause> {ew.putIfNotNull("node", node);ew.putIfNotNull("tagKey", String.valueOf(tagKey));ew.putIfNotNull("violation", (MapWriter) ew1 -> {- ew1.put(getClause().isPerCollectiontag() ? "replica" : tag.name,- String.valueOf(actualVal));+ if (getClause().isPerCollectiontag()) ew1.put("replica", actualVal);+ else ew1.put(tag.name, String.valueOf(actualVal));ew1.putIfNotNull("delta", delta);});ew.put("clause", getClause());@@ -258,12 +266,12 @@ public class Clause implements MapWriter, Comparable<Clause> {public List<Violation> test(List<Row> allRows) {List<Violation> violations = new ArrayList<>();if (isPerCollectiontag()) {- Map<String, Map<String, Map<String, AtomicInteger>>> replicaCount = computeReplicaCounts(allRows);- for (Map.Entry<String, Map<String, Map<String, AtomicInteger>>> e : replicaCount.entrySet()) {+ Map<String, Map<String, Map<String, ReplicaCount>>> replicaCount = computeReplicaCounts(allRows);+ for (Map.Entry<String, Map<String, Map<String, ReplicaCount>>> e : replicaCount.entrySet()) {if (!collection.isPass(e.getKey())) continue;- for (Map.Entry<String, Map<String, AtomicInteger>> shardVsCount : e.getValue().entrySet()) {+ for (Map.Entry<String, Map<String, ReplicaCount>> shardVsCount : e.getValue().entrySet()) {if (!shard.isPass(shardVsCount.getKey())) continue;- for (Map.Entry<String, AtomicInteger> counts : shardVsCount.getValue().entrySet()) {+ for (Map.Entry<String, ReplicaCount> counts : shardVsCount.getValue().entrySet()) {if (!replica.isPass(counts.getValue())) {violations.add(new Violation(e.getKey(),@@ -289,24 +297,23 @@ public class Clause implements MapWriter, Comparable<Clause> {}- private Map<String, Map<String, Map<String, AtomicInteger>>> computeReplicaCounts(List<Row> allRows) {- Map<String, Map<String, Map<String, AtomicInteger>>> collVsShardVsTagVsCount = new HashMap<>();- for (Row row : allRows)+ private Map<String, Map<String, Map<String, ReplicaCount>>> computeReplicaCounts(List<Row> allRows) {+ Map<String, Map<String, Map<String, ReplicaCount>>> collVsShardVsTagVsCount = new HashMap<>();+ for (Row row : allRows) {for (Map.Entry<String, Map<String, List<ReplicaInfo>>> colls : row.collectionVsShardVsReplicas.entrySet()) {String collectionName = colls.getKey();if (!collection.isPass(collectionName)) continue;- collVsShardVsTagVsCount.putIfAbsent(collectionName, new HashMap<>());- Map<String, Map<String, AtomicInteger>> collMap = collVsShardVsTagVsCount.get(collectionName);+ Map<String, Map<String, ReplicaCount>> collMap = collVsShardVsTagVsCount.computeIfAbsent(collectionName, s -> new HashMap<>());for (Map.Entry<String, List<ReplicaInfo>> shards : colls.getValue().entrySet()) {String shardName = shards.getKey();if (ANY.equals(shard.val)) shardName = ANY;if (!shard.isPass(shardName)) break;- collMap.putIfAbsent(shardName, new HashMap<>());- Map<String, AtomicInteger> tagVsCount = collMap.get(shardName);+ Map<String, ReplicaCount> tagVsCount = collMap.computeIfAbsent(shardName, s -> new HashMap<>());Object tagVal = row.getVal(tag.name);- tagVsCount.putIfAbsent(tag.isPass(tagVal) ? String.valueOf(tagVal) : "", new AtomicInteger());+ tagVsCount.computeIfAbsent(tag.isPass(tagVal) ? String.valueOf(tagVal) : "", s -> new ReplicaCount());if (tag.isPass(tagVal)) {- tagVsCount.get(String.valueOf(tagVal)).addAndGet(shards.getValue().size());+ tagVsCount.get(String.valueOf(tagVal)).increment(shards.getValue());+ }}}}@@ -331,7 +338,7 @@ public class Clause implements MapWriter, Comparable<Clause> {NOT_APPLICABLE, FAIL, PASS}- private static final Set<String> IGNORE_TAGS = new HashSet<>(Arrays.asList(REPLICA, COLLECTION, SHARD, "strict"));+ private static final Set<String> IGNORE_TAGS = new HashSet<>(Arrays.asList(REPLICA, COLLECTION, SHARD, "strict", "type"));static class ValidateInfo {final Class type;@@ -344,17 +351,18 @@ public class Clause implements MapWriter, Comparable<Clause> {this.type = type;this.vals = vals;this.min = min;- if(min != null && !type.isInstance(min)) throw new RuntimeException("wrong min value type, expected: " + type.getName() + " actual: " + min.getClass().getName());+ if (min != null && !type.isInstance(min))+ throw new RuntimeException("wrong min value type, expected: " + type.getName() + " actual: " + min.getClass().getName());this.max = max;- if(max != null && !type.isInstance(max)) throw new RuntimeException("wrong max value type, expected: " + type.getName() + " actual: " + max.getClass().getName());+ if (max != null && !type.isInstance(max))+ throw new RuntimeException("wrong max value type, expected: " + type.getName() + " actual: " + max.getClass().getName());}}/**- *- * @param name name of the condition- * @param val value of the condition+ * @param name name of the condition+ * @param val value of the condition* @param isRuleVal is this provided in the rule* @return actual validated value*/@@ -413,7 +421,7 @@ public class Clause implements MapWriter, Comparable<Clause> {num = (Number) val;}- if (num != null) {+ if (num != null) {return num.longValue();}throw new RuntimeException(name + ": " + val + "not a valid number");@@ -434,7 +442,7 @@ public class Clause implements MapWriter, Comparable<Clause> {num = (Number) val;}- if (num != null) {+ if (num != null) {return num.doubleValue();}throw new RuntimeException(name + ": " + val + "not a valid number");diff --git a/solr/solrj/src/java/org/apache/solr/cloud/autoscaling/MoveReplicaSuggester.java b/solr/solrj/src/java/org/apache/solr/cloud/autoscaling/MoveReplicaSuggester.javaindex 7a3cfaad79e..4c0d6a051c8 100644--- a/solr/solrj/src/java/org/apache/solr/cloud/autoscaling/MoveReplicaSuggester.java+++ b/solr/solrj/src/java/org/apache/solr/cloud/autoscaling/MoveReplicaSuggester.java@@ -46,7 +46,7 @@ public class MoveReplicaSuggester extends Suggester {ReplicaInfo replicaInfo = fromReplica.first();String coll = replicaInfo.collection;String shard = replicaInfo.shard;- Pair<Row, ReplicaInfo> pair = fromRow.removeReplica(coll, shard);+ Pair<Row, ReplicaInfo> pair = fromRow.removeReplica(coll, shard, replicaInfo.type);Row tmpRow = pair.first();if (tmpRow == null) {//no such replica available@@ -59,7 +59,7 @@ public class MoveReplicaSuggester extends Suggester {Row targetRow = getMatrix().get(j);if(!targetRow.isLive) continue;if (!isAllowed(targetRow.node, Hint.TARGET_NODE)) continue;- targetRow = targetRow.addReplica(coll, shard);+ targetRow = targetRow.addReplica(coll, shard, replicaInfo.type);targetRow.violations.clear();List<Violation> errs = testChangedMatrix(strict, getModifiedMatrix(getModifiedMatrix(getMatrix(), tmpRow, i), targetRow, j));if (!containsNewErrors(errs) && isLessSerious(errs, leastSeriousViolation)) {@@ -71,8 +71,8 @@ public class MoveReplicaSuggester extends Suggester {}}if (targetNodeIndex != null && fromNodeIndex != null) {- getMatrix().set(fromNodeIndex, getMatrix().get(fromNodeIndex).removeReplica(fromReplicaInfo.collection, fromReplicaInfo.shard).first());- getMatrix().set(targetNodeIndex, getMatrix().get(targetNodeIndex).addReplica(fromReplicaInfo.collection, fromReplicaInfo.shard));+ getMatrix().set(fromNodeIndex, getMatrix().get(fromNodeIndex).removeReplica(fromReplicaInfo.collection, fromReplicaInfo.shard, fromReplicaInfo.type).first());+ getMatrix().set(targetNodeIndex, getMatrix().get(targetNodeIndex).addReplica(fromReplicaInfo.collection, fromReplicaInfo.shard, fromReplicaInfo.type));return new CollectionAdminRequest.MoveReplica(fromReplicaInfo.collection,fromReplicaInfo.name,diff --git a/solr/solrj/src/java/org/apache/solr/cloud/autoscaling/Operand.java b/solr/solrj/src/java/org/apache/solr/cloud/autoscaling/Operand.javaindex f961cac6b21..3f82416ebd2 100644--- a/solr/solrj/src/java/org/apache/solr/cloud/autoscaling/Operand.java+++ b/solr/solrj/src/java/org/apache/solr/cloud/autoscaling/Operand.java@@ -20,6 +20,7 @@ package org.apache.solr.cloud.autoscaling;import java.util.Objects;import org.apache.solr.cloud.autoscaling.Clause.TestStatus;+import org.apache.solr.common.params.CoreAdminParams;import static org.apache.solr.cloud.autoscaling.Clause.TestStatus.FAIL;import static org.apache.solr.cloud.autoscaling.Clause.TestStatus.NOT_APPLICABLE;@@ -37,7 +38,7 @@ public enum Operand {},EQUAL("", 0) {@Override- public int _delta(int expected, int actual) {+ public long _delta(long expected, long actual) {return expected - actual;}},@@ -48,7 +49,7 @@ public enum Operand {}@Override- public int _delta(int expected, int actual) {+ public long _delta(long expected, long actual) {return expected - actual;}@@ -64,7 +65,7 @@ public enum Operand {}@Override- protected int _delta(int expected, int actual) {+ protected long _delta(long expected, long actual) {return actual > expected ? 0 : (expected + 1) - actual;}},@@ -79,7 +80,7 @@ public enum Operand {}@Override- protected int _delta(int expected, int actual) {+ protected long _delta(long expected, long actual) {return actual < expected ? 0 : (expected ) - actual;}@@ -107,17 +108,17 @@ public enum Operand {}- public Integer delta(Object expected, Object actual) {+ public Long delta(Object expected, Object actual) {try {- Integer expectedInt = Integer.parseInt(String.valueOf(expected));- Integer actualInt = Integer.parseInt(String.valueOf(actual));+ Long expectedInt = (Long) Clause.validate(CoreAdminParams.REPLICA, expected, false);+ Long actualInt = (Long) Clause.validate(CoreAdminParams.REPLICA, actual, false);return _delta(expectedInt, actualInt);} catch (Exception e) {return null;}}- protected int _delta(int expected, int actual) {+ protected long _delta(long expected, long actual) {return 0;}}diff --git a/solr/solrj/src/java/org/apache/solr/cloud/autoscaling/Policy.java b/solr/solrj/src/java/org/apache/solr/cloud/autoscaling/Policy.javaindex 33088e29ca8..515eb70a1df 100644--- a/solr/solrj/src/java/org/apache/solr/cloud/autoscaling/Policy.java+++ b/solr/solrj/src/java/org/apache/solr/cloud/autoscaling/Policy.java@@ -40,6 +40,7 @@ import org.apache.solr.client.solrj.SolrRequest;import org.apache.solr.cloud.autoscaling.Clause.Violation;import org.apache.solr.common.IteratorWriter;import org.apache.solr.common.MapWriter;+import org.apache.solr.common.cloud.Replica;import org.apache.solr.common.params.CollectionParams.CollectionAction;import org.apache.solr.common.util.Pair;import org.apache.solr.common.util.StrUtils;@@ -302,18 +303,27 @@ public class Policy implements MapWriter {public static class ReplicaInfo implements MapWriter {final String name;String core, collection, shard;+ Replica.Type type;Map<String, Object> variables;- public ReplicaInfo(String name, String coll, String shard, Map<String, Object> vals) {+ public ReplicaInfo(String name, String coll, String shard, Replica.Type type, Map<String, Object> vals) {this.name = name;this.variables = vals;this.collection = coll;this.shard = shard;+ this.type = type;}@Overridepublic void writeMap(EntryWriter ew) throws IOException {- ew.put(name, variables);+ ew.put(name, (MapWriter) ew1 -> {+ if(variables !=null){+ for (Map.Entry<String, Object> e : variables.entrySet()) {+ ew1.put(e.getKey(), e.getValue());+ }+ }+ if(type != null) ew1.put("type", type.toString());+ });}public String getCore() {@@ -352,7 +362,7 @@ public class Policy implements MapWriter {if (hint == Hint.TARGET_NODE || hint == Hint.SRC_NODE) {((Set) hints.computeIfAbsent(hint, h -> new HashSet<>())).add(value);} else {- hints.put(hint, value);+ hints.put(hint, value == null ? null : String.valueOf(value));}return this;}@@ -447,7 +457,7 @@ public class Policy implements MapWriter {for (Map.Entry<String, Map<String, List<Policy.ReplicaInfo>>> e : r.collectionVsShardVsReplicas.entrySet()) {if (!isAllowed(e.getKey(), Hint.COLL)) continue;for (Map.Entry<String, List<Policy.ReplicaInfo>> shard : e.getValue().entrySet()) {- if (!isAllowed(e.getKey(), Hint.SHARD)) continue;+ if (!isAllowed(e.getKey(), Hint.SHARD)) continue;//todo fixreplicaList.add(new Pair<>(shard.getValue().get(0), r));}}@@ -483,7 +493,7 @@ public class Policy implements MapWriter {}public enum Hint {- COLL, SHARD, SRC_NODE, TARGET_NODE+ COLL, SHARD, SRC_NODE, TARGET_NODE, REPLICATYPE}diff --git a/solr/solrj/src/java/org/apache/solr/cloud/autoscaling/ReplicaCount.java b/solr/solrj/src/java/org/apache/solr/cloud/autoscaling/ReplicaCount.javanew file mode 100644index 00000000000..7d470719ded--- /dev/null+++ b/solr/solrj/src/java/org/apache/solr/cloud/autoscaling/ReplicaCount.java@@ -0,0 +1,92 @@+/*+ * 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.autoscaling;++import java.io.IOException;+import java.util.List;++import org.apache.solr.common.MapWriter;+import org.apache.solr.common.cloud.Replica;++class ReplicaCount extends Number implements MapWriter {+ long nrt, tlog, pull;++ public long total() {+ return nrt + tlog + pull;+ }++ @Override+ public int intValue() {+ return (int) total();+ }++ @Override+ public long longValue() {+ return total();+ }++ @Override+ public float floatValue() {+ return total();+ }++ @Override+ public double doubleValue() {+ return total();+ }++ @Override+ public void writeMap(EntryWriter ew) throws IOException {+ ew.put(Replica.Type.NRT.name(), nrt);+ ew.put(Replica.Type.PULL.name(), pull);+ ew.put(Replica.Type.TLOG.name(), tlog);+ ew.put("count", total());+ }++ public Long getVal(Replica.Type type) {+ if (type == null) return total();+ switch (type) {+ case NRT:+ return nrt;+ case PULL:+ return pull;+ case TLOG:+ return tlog;+ }+ return total();+ }++ public void increment(List<Policy.ReplicaInfo> infos) {+ if (infos == null) return;+ for (Policy.ReplicaInfo info : infos) {+ switch (info.type) {+ case NRT:+ nrt++;+ break;+ case PULL:+ pull++;+ break;+ case TLOG:+ tlog++;+ break;+ default:+ nrt++;+ }+ }+ }+}diff --git a/solr/solrj/src/java/org/apache/solr/cloud/autoscaling/Row.java b/solr/solrj/src/java/org/apache/solr/cloud/autoscaling/Row.javaindex 7c7b467ab57..bc86a2d02fa 100644--- a/solr/solrj/src/java/org/apache/solr/cloud/autoscaling/Row.java+++ b/solr/solrj/src/java/org/apache/solr/cloud/autoscaling/Row.java@@ -27,6 +27,7 @@ import java.util.Random;import org.apache.solr.common.IteratorWriter;import org.apache.solr.common.MapWriter;+import org.apache.solr.common.cloud.Replica;import org.apache.solr.common.util.Pair;import org.apache.solr.common.util.Utils;import org.apache.solr.cloud.autoscaling.Policy.ReplicaInfo;@@ -94,11 +95,11 @@ class Row implements MapWriter {}// this adds a replica to the replica info- Row addReplica(String coll, String shard) {+ Row addReplica(String coll, String shard, Replica.Type type) {Row row = copy();Map<String, List<ReplicaInfo>> c = row.collectionVsShardVsReplicas.computeIfAbsent(coll, k -> new HashMap<>());List<ReplicaInfo> replicas = c.computeIfAbsent(shard, k -> new ArrayList<>());- replicas.add(new ReplicaInfo("" + new Random().nextInt(1000) + 1000, coll, shard, new HashMap<>()));+ replicas.add(new ReplicaInfo("" + new Random().nextInt(1000) + 1000, coll, shard, type, new HashMap<>()));for (Cell cell : row.cells) {if (cell.name.equals("cores")) {cell.val = cell.val == null ? 0 : ((Number) cell.val).longValue() + 1;@@ -108,18 +109,28 @@ class Row implements MapWriter {}- Pair<Row, ReplicaInfo> removeReplica(String coll, String shard) {+ Pair<Row, ReplicaInfo> removeReplica(String coll, String shard, Replica.Type type) {Row row = copy();Map<String, List<ReplicaInfo>> c = row.collectionVsShardVsReplicas.get(coll);if (c == null) return null;- List<ReplicaInfo> s = c.get(shard);- if (s == null || s.isEmpty()) return null;+ List<ReplicaInfo> r = c.get(shard);+ if (r == null) return null;+ int idx = -1;+ for (int i = 0; i < r.size(); i++) {+ ReplicaInfo info = r.get(i);+ if (type == null || info.type == type) {+ idx = i;+ break;+ }+ }+ if(idx == -1) return null;+for (Cell cell : row.cells) {if (cell.name.equals("cores")) {cell.val = cell.val == null ? 0 : ((Number) cell.val).longValue() - 1;}}- return new Pair(row, s.remove(0));+ return new Pair(row, r.remove(idx));}}diff --git a/solr/solrj/src/java/org/apache/solr/common/cloud/Replica.java b/solr/solrj/src/java/org/apache/solr/common/cloud/Replica.javaindex b7655be3135..863372e3bf4 100644--- a/solr/solrj/src/java/org/apache/solr/common/cloud/Replica.java+++ b/solr/solrj/src/java/org/apache/solr/common/cloud/Replica.java@@ -102,7 +102,11 @@ public class Replica extends ZkNodeProps {* replicas can’t become shard leaders (i.e., if there are only pull replicas in the collection at some point, updates will fail* same as if there is no leaders, queries continue to work), so they don’t even participate in elections.*/- PULL+ PULL;++ public static Type get(String name){+ return name == null ? Type.NRT : Type.valueOf(name);+ }}private final String name;@@ -120,13 +124,7 @@ public class Replica extends ZkNodeProps {this.state = State.ACTIVE; //Default to ACTIVEpropMap.put(ZkStateReader.STATE_PROP, state.toString());}- String typeString = (String)propMap.get(ZkStateReader.REPLICA_TYPE);- if (typeString == null) {- this.type = Type.NRT;- } else {- this.type = Type.valueOf(typeString);- }-+ type = Type.get((String) propMap.get(ZkStateReader.REPLICA_TYPE));}public String getName() {diff --git a/solr/solrj/src/test/org/apache/solr/cloud/autoscaling/TestPolicy.java b/solr/solrj/src/test/org/apache/solr/cloud/autoscaling/TestPolicy.javaindex 9a73a2d3ea3..3fb5544f020 100644--- a/solr/solrj/src/test/org/apache/solr/cloud/autoscaling/TestPolicy.java+++ b/solr/solrj/src/test/org/apache/solr/cloud/autoscaling/TestPolicy.java@@ -34,6 +34,8 @@ import org.apache.solr.client.solrj.SolrRequest;import org.apache.solr.client.solrj.request.CollectionAdminRequest;import org.apache.solr.cloud.autoscaling.Clause.Violation;import org.apache.solr.cloud.autoscaling.Policy.Suggester.Hint;+import org.apache.solr.common.cloud.Replica;+import org.apache.solr.common.cloud.ZkStateReader;import org.apache.solr.common.params.CollectionParams;import org.apache.solr.common.params.SolrParams;import org.apache.solr.common.util.Utils;@@ -99,11 +101,9 @@ public class TestPolicy extends SolrTestCaseJ4 {ValidatingJsonMap r = (ValidatingJsonMap) o2;String node_name = (String) r.get("node_name");if (!node_name.equals(node)) return;- Map<String, List<Policy.ReplicaInfo>> shardVsReplicaStats = result.get(collName);- if (shardVsReplicaStats == null) result.put(collName, shardVsReplicaStats = new HashMap<>());- List<Policy.ReplicaInfo> replicaInfos = shardVsReplicaStats.get(shard);- if (replicaInfos == null) shardVsReplicaStats.put(shard, replicaInfos = new ArrayList<>());- replicaInfos.add(new Policy.ReplicaInfo(replicaName, collName, shard, new HashMap<>()));+ Map<String, List<Policy.ReplicaInfo>> shardVsReplicaStats = result.computeIfAbsent(collName, k -> new HashMap<>());+ List<Policy.ReplicaInfo> replicaInfos = shardVsReplicaStats.computeIfAbsent(shard, k -> new ArrayList<>());+ replicaInfos.add(new Policy.ReplicaInfo(replicaName, collName, shard, Replica.Type.get((String) r.get(ZkStateReader.REPLICA_TYPE)), new HashMap<>()));});});});@@ -194,8 +194,8 @@ public class TestPolicy extends SolrTestCaseJ4 {" '127.0.0.1:65417_solr'," +" '127.0.0.1:65434_solr']," +" 'replicaInfo':{" +- " '127.0.0.1:65427_solr':{'testNodeLost':{'shard1':[{'core_node2':{}}]}}," +- " '127.0.0.1:65417_solr':{'testNodeLost':{'shard1':[{'core_node1':{}}]}}," ++ " '127.0.0.1:65427_solr':{'testNodeLost':{'shard1':[{'core_node2':{type: NRT}}]}}," ++ " '127.0.0.1:65417_solr':{'testNodeLost':{'shard1':[{'core_node1':{type: NRT}}]}}," +" '127.0.0.1:65434_solr':{}}," +" 'nodeValues':{" +" '127.0.0.1:65417_solr':{" +@@ -272,7 +272,7 @@ public class TestPolicy extends SolrTestCaseJ4 {Object o = l3.get(i);Map m3 = (Map) o;l3.set(i, new Policy.ReplicaInfo(m3.keySet().iterator().next().toString()- ,coll.toString(), shard.toString(),new HashMap<>()));+ ,coll.toString(), shard.toString(), Replica.Type.get((String)m3.get("type")), new HashMap<>()));}});@@ -304,10 +304,80 @@ public class TestPolicy extends SolrTestCaseJ4 {}+ public void testPolicyWithReplicaType() {+ Map policies = (Map) Utils.fromJSONString("{" ++ " 'cluster-preferences': [" ++ " { 'maximize': 'freedisk', 'precision': 50}," ++ " { 'minimize': 'cores', 'precision': 50}" ++ " ]," ++ " 'cluster-policy': [" ++ " { 'replica': 0, 'nodeRole': 'overseer'}" ++ " { 'replica': '<2', 'shard': '#EACH', 'node': '#ANY'}," ++ " { 'replica': 0, 'shard': '#EACH', sysprop.fs : '!ssd', type : TLOG }" ++ " { 'replica': 0, 'shard': '#EACH', sysprop.fs : '!slowdisk' , type : PULL }" ++ " ]" ++ "}");+ Map<String, Map> nodeValues = (Map<String, Map>) Utils.fromJSONString("{" ++ "node1:{cores:12, freedisk: 334, heapUsage:10480, rack: rack4, sysprop.fs: slowdisk}," ++ "node2:{cores:4, freedisk: 749, heapUsage:6873, rack: rack3}," ++ "node3:{cores:7, freedisk: 262, heapUsage:7834, rack: rack2, sysprop.fs : ssd}," ++ "node4:{cores:8, freedisk: 375, heapUsage:16900, nodeRole:overseer, rack: rack1}" ++ "}");+ Policy policy = new Policy(policies);+ Policy.Suggester suggester = policy.createSession(getClusterDataProvider(nodeValues, clusterState))+ .getSuggester(ADDREPLICA)+ .hint(Hint.COLL, "newColl")+ .hint(Hint.REPLICATYPE, Replica.Type.PULL)+ .hint(Hint.SHARD, "shard1");+ SolrRequest op = suggester.getOperation();+ assertNotNull(op);+ assertEquals(Replica.Type.PULL.name(), op.getParams().get("type"));+ assertEquals("PULL type node must be in 'slowdisk' node","node1", op.getParams().get("node"));++ suggester = suggester.getSession()+ .getSuggester(ADDREPLICA)+ .hint(Hint.COLL, "newColl")+ .hint(Hint.REPLICATYPE, Replica.Type.PULL)+ .hint(Hint.SHARD, "shard2");+ op = suggester.getOperation();+ assertNotNull(op);+ assertEquals(Replica.Type.PULL.name(), op.getParams().get("type"));+ assertEquals("PULL type node must be in 'slowdisk' node","node1", op.getParams().get("node"));++ suggester = suggester.getSession()+ .getSuggester(ADDREPLICA)+ .hint(Hint.COLL, "newColl")+ .hint(Hint.REPLICATYPE, Replica.Type.TLOG)+ .hint(Hint.SHARD, "shard1");+ op = suggester.getOperation();+ assertNotNull(op);+ assertEquals(Replica.Type.TLOG.name(), op.getParams().get("type"));+ assertEquals("TLOG type node must be in 'ssd' node","node3", op.getParams().get("node"));++ suggester = suggester.getSession()+ .getSuggester(ADDREPLICA)+ .hint(Hint.COLL, "newColl")+ .hint(Hint.REPLICATYPE, Replica.Type.TLOG)+ .hint(Hint.SHARD, "shard2");+ op = suggester.getOperation();+ assertNotNull(op);+ assertEquals(Replica.Type.TLOG.name(), op.getParams().get("type"));+ assertEquals("TLOG type node must be in 'ssd' node","node3", op.getParams().get("node"));++ suggester = suggester.getSession()+ .getSuggester(ADDREPLICA)+ .hint(Hint.COLL, "newColl")+ .hint(Hint.REPLICATYPE, Replica.Type.TLOG)+ .hint(Hint.SHARD, "shard2");+ op = suggester.getOperation();+ assertNull("No node should qualify for this" ,op);++ }+public void testRow() {Row row = new Row("nodex", new Cell[]{new Cell(0, "node", "nodex")}, false, new HashMap<>(), new ArrayList<>(), true);- Row r1 = row.addReplica("c1", "s1");- Row r2 = r1.addReplica("c1", "s1");+ Row r1 = row.addReplica("c1", "s1", null);+ Row r2 = r1.addReplica("c1", "s1",null);assertEquals(1, r1.collectionVsShardVsReplicas.get("c1").get("s1").size());assertEquals(2, r2.collectionVsShardVsReplicas.get("c1").get("s1").size());assertTrue(r2.collectionVsShardVsReplicas.get("c1").get("s1").get(0) instanceof Policy.ReplicaInfo);@@ -532,8 +602,8 @@ public class TestPolicy extends SolrTestCaseJ4 {" {'core_node2':{}}]}}}");Map m = (Map) Utils.getObjectByPath(replicaInfoMap, false, "127.0.0.1:60089_solr/compute_plan_action_test");m.put("shard1", Arrays.asList(- new Policy.ReplicaInfo("core_node1", "compute_plan_action_test", "shard1", Collections.emptyMap()),- new Policy.ReplicaInfo("core_node2", "compute_plan_action_test", "shard1", Collections.emptyMap())+ new Policy.ReplicaInfo("core_node1", "compute_plan_action_test", "shard1", Replica.Type.NRT, Collections.emptyMap()),+ new Policy.ReplicaInfo("core_node2", "compute_plan_action_test", "shard1", Replica.Type.NRT, Collections.emptyMap())));Map<String, Map<String, Object>> tagsMap = (Map) Utils.fromJSONString("{" +