Apache Solr open-source search software
SOLR-11524: A new autoscaling/suggestions API end-point which gives autoscaling suggestions
Noble Paul6305ed6695a9
diff --git a/solr/core/src/java/org/apache/solr/cloud/autoscaling/AutoScalingHandler.java b/solr/core/src/java/org/apache/solr/cloud/autoscaling/AutoScalingHandler.javaindex 4053e776cc7..0f93a2b47ec 100644--- a/solr/core/src/java/org/apache/solr/cloud/autoscaling/AutoScalingHandler.java+++ b/solr/core/src/java/org/apache/solr/cloud/autoscaling/AutoScalingHandler.java@@ -126,8 +126,12 @@ public class AutoScalingHandler extends RequestHandlerBase implements Permissionreturn this;}});- } else if (parts.size() == 3 && DIAGNOSTICS.equals(parts.get(2))) {- handleDiagnostics(rsp, autoScalingConf);+ } else if (parts.size() == 3) {+ if (DIAGNOSTICS.equals(parts.get(2))) {+ handleDiagnostics(rsp, autoScalingConf);+ } else if (SUGGESTIONS.equals(parts.get(2))) {+ handleSuggestions(rsp, autoScalingConf);+ }}} else {if (req.getContentStreams() == null) {@@ -148,7 +152,21 @@ public class AutoScalingHandler extends RequestHandlerBase implements Permission}}- public void processOps(SolrQueryRequest req, SolrQueryResponse rsp, List<CommandOperation> ops) throws KeeperException, InterruptedException, IOException {++ private void handleSuggestions(SolrQueryResponse rsp, AutoScalingConfig autoScalingConf) throws IOException {+ try (CloudSolrClient build = new CloudSolrClient.Builder()+ .withHttpClient(container.getUpdateShardHandler().getHttpClient())+ .withZkHost(container.getZkController().getZkServerAddress()).build()) {+ DistributedQueueFactory queueFactory = new ZkDistributedQueueFactory(container.getZkController().getZkClient());+ rsp.getValues().add("suggestions",+ PolicyHelper.getSuggestions(autoScalingConf, new SolrClientCloudManager(queueFactory, build)));+ }+++ }++ public void processOps(SolrQueryRequest req, SolrQueryResponse rsp, List<CommandOperation> ops)+ throws KeeperException, InterruptedException, IOException {while (true) {AutoScalingConfig initialConfig = container.getZkController().zkStateReader.getAutoScalingConfig();AutoScalingConfig currentConfig = initialConfig;@@ -651,7 +669,7 @@ public class AutoScalingHandler extends RequestHandlerBase implements Permission@Overridepublic SolrRequestHandler getSubHandler(String path) {- if (path.equals("/diagnostics")) return this;+ if (path.equals("/diagnostics") || path.equals("/suggestions")) return this;return null;}}diff --git a/solr/core/src/java/org/apache/solr/cloud/autoscaling/ComputePlanAction.java b/solr/core/src/java/org/apache/solr/cloud/autoscaling/ComputePlanAction.javaindex 29543255871..66093c2f5f9 100644--- a/solr/core/src/java/org/apache/solr/cloud/autoscaling/ComputePlanAction.java+++ b/solr/core/src/java/org/apache/solr/cloud/autoscaling/ComputePlanAction.java@@ -61,7 +61,7 @@ public class ComputePlanAction extends TriggerActionBase {Policy.Session session = policy.createSession(cloudManager);Suggester suggester = getSuggester(session, event, cloudManager);while (true) {- SolrRequest operation = suggester.getOperation();+ SolrRequest operation = suggester.getSuggestion();if (operation == null) break;log.info("Computed Plan: {}", operation.getParams());Map<String, Object> props = context.getProperties();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 335fdbc307b..7f820d0476c 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@@ -18,6 +18,7 @@package org.apache.solr.cloud.autoscaling;import java.io.IOException;+import java.lang.invoke.MethodHandles;import java.util.Collection;import java.util.Collections;import java.util.List;@@ -29,6 +30,7 @@ import org.apache.solr.client.solrj.SolrClient;import org.apache.solr.client.solrj.SolrRequest;import org.apache.solr.client.solrj.SolrResponse;import org.apache.solr.client.solrj.cloud.autoscaling.Policy;+import org.apache.solr.client.solrj.embedded.JettySolrRunner;import org.apache.solr.client.solrj.impl.CloudSolrClient;import org.apache.solr.client.solrj.impl.HttpSolrClient;import org.apache.solr.client.solrj.request.CollectionAdminRequest;@@ -46,6 +48,8 @@ import org.apache.zookeeper.data.Stat;import org.junit.Before;import org.junit.BeforeClass;import org.junit.Test;+import org.slf4j.Logger;+import org.slf4j.LoggerFactory;import static org.apache.solr.common.cloud.ZkStateReader.SOLR_AUTOSCALING_CONF_PATH;import static org.apache.solr.common.util.Utils.getObjectByPath;@@ -54,6 +58,7 @@ import static org.apache.solr.common.util.Utils.getObjectByPath;* Test for AutoScalingHandler*/public class AutoScalingHandlerTest extends SolrCloudTestCase {+ private static final Logger log = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());final static String CONFIGSET_NAME = "conf";@BeforeClasspublic static void setupCluster() throws Exception {@@ -692,10 +697,27 @@ public class AutoScalingHandlerTest extends SolrCloudTestCase {for (Map<String, Object> violation : violations) {assertEquals("readApiTestViolations", violation.get("collection"));assertEquals("shard1", violation.get("shard"));- assertEquals(-1l, getObjectByPath(violation, true, "violation/delta"));+ assertEquals(2l, getObjectByPath(violation, true, "violation/delta"));assertEquals(3l, getObjectByPath(violation, true, "violation/replica/NRT"));assertNotNull(violation.get("clause"));}+ JettySolrRunner runner1 = cluster.startJettySolrRunner();+ cluster.waitForAllNodes(30);++ req = createAutoScalingRequest(SolrRequest.METHOD.GET, "/suggestions", null);+ response = solrClient.request(req);+ List l = (List) response.get("suggestions");+ assertNotNull(l);+ assertEquals(1, l.size());+ for (int i = 0; i < l.size(); i++) {+ Object suggestion = l.get(i);+ assertEquals("violation", Utils.getObjectByPath(suggestion, true, "type"));+ assertEquals("POST", Utils.getObjectByPath(suggestion, true, "operation/method"));+ assertEquals("/c/readApiTestViolations", Utils.getObjectByPath(suggestion, true, "operation/path"));+ String node = (String) Utils.getObjectByPath(suggestion, true, "operation/command/move-replica/targetNode");+ assertNotNull(node);+ assertEquals(runner1.getNodeName(), node);+ }}@Testdiff --git a/solr/core/src/test/org/apache/solr/cloud/autoscaling/ComputePlanActionTest.java b/solr/core/src/test/org/apache/solr/cloud/autoscaling/ComputePlanActionTest.javaindex 621fc1a4b49..837c683dea0 100644--- a/solr/core/src/test/org/apache/solr/cloud/autoscaling/ComputePlanActionTest.java+++ b/solr/core/src/test/org/apache/solr/cloud/autoscaling/ComputePlanActionTest.java@@ -162,7 +162,6 @@ public class ComputePlanActionTest extends SolrCloudTestCase {CollectionAdminRequest.Create create = CollectionAdminRequest.createCollection("testNodeLost","conf",1, 2);-// create.setMaxShardsPerNode(1);create.process(solrClient);waitForState("Timed out waiting for replicas of new collection to be active",@@ -188,7 +187,7 @@ public class ComputePlanActionTest extends SolrCloudTestCase {break;}}- log.info("$$$$$$$$$$$$$$Stopped_node : {}", node);+ log.info("Stopped_node : {}", node);cluster.waitForAllNodes(30);assertTrue("Trigger was not fired even after 10 seconds", triggerFiredLatch.await(10, TimeUnit.SECONDS));diff --git a/solr/core/src/test/org/apache/solr/cloud/autoscaling/TestPolicyCloud.java b/solr/core/src/test/org/apache/solr/cloud/autoscaling/TestPolicyCloud.javaindex 4136d27c344..f53dde1a556 100644--- a/solr/core/src/test/org/apache/solr/cloud/autoscaling/TestPolicyCloud.java+++ b/solr/core/src/test/org/apache/solr/cloud/autoscaling/TestPolicyCloud.java@@ -22,6 +22,7 @@ import java.nio.charset.StandardCharsets;import java.util.Arrays;import java.util.List;import java.util.Map;+import java.util.concurrent.atomic.AtomicInteger;import java.util.function.BiConsumer;import org.apache.lucene.util.Constants;@@ -29,7 +30,12 @@ import org.apache.lucene.util.LuceneTestCase;import org.apache.solr.client.solrj.SolrRequest;import org.apache.solr.client.solrj.SolrServerException;import org.apache.solr.client.solrj.cloud.DistributedQueueFactory;+import org.apache.solr.client.solrj.cloud.autoscaling.AutoScalingConfig;+import org.apache.solr.client.solrj.cloud.autoscaling.Policy;+import org.apache.solr.client.solrj.cloud.autoscaling.ReplicaInfo;+import org.apache.solr.client.solrj.cloud.autoscaling.Row;import org.apache.solr.client.solrj.cloud.autoscaling.SolrCloudManager;+import org.apache.solr.client.solrj.cloud.autoscaling.Suggestion;import org.apache.solr.client.solrj.embedded.JettySolrRunner;import org.apache.solr.client.solrj.impl.CloudSolrClient;import org.apache.solr.client.solrj.impl.HttpSolrClient;@@ -74,6 +80,46 @@ public class TestPolicyCloud extends SolrCloudTestCase {"{}".getBytes(StandardCharsets.UTF_8), true);}+ public void testDataProviderPerReplicaDetails() throws Exception {+ CollectionAdminRequest.createCollection("perReplicaDataColl", "conf", 1, 5)+ .process(cluster.getSolrClient());++ DocCollection coll = getCollectionState("perReplicaDataColl");+ String autoScaleJson = "{" ++ " 'cluster-preferences': [" ++ " { maximize : freedisk , precision: 50}," ++ " { minimize : cores, precision: 2}" ++ " ]," ++ " 'cluster-policy': [" ++ " { replica : '0' , 'nodeRole': 'overseer'}," ++ " { 'replica': '<2', 'shard': '#ANY', 'node': '#ANY'" ++ " }" ++ " ]," ++ " 'policies': {" ++ " 'policy1': [" ++ " { 'replica': '<2', 'shard': '#EACH', 'node': '#ANY'}," ++ " { 'replica': '<2', 'shard': '#EACH', 'sysprop.rack': 'rack1'}" ++ " ]" ++ " }" ++ "}";+ AutoScalingConfig config = new AutoScalingConfig((Map<String, Object>) Utils.fromJSONString(autoScaleJson));+ SolrCloudManager cloudManager = new SolrClientCloudManager(new ZkDistributedQueueFactory(cluster.getZkClient()), cluster.getSolrClient());+ Policy.Session session = config.getPolicy().createSession(cloudManager);++ AtomicInteger count = new AtomicInteger(0);+ for (Row row : session.getSorted()) {+ row.collectionVsShardVsReplicas.forEach((c, shardVsReplicas) -> shardVsReplicas.forEach((s, replicaInfos) -> {+ for (ReplicaInfo replicaInfo : replicaInfos) {+ if (replicaInfo.getVariables().containsKey(Suggestion.ConditionType.CORE_IDX.tagName)) count.incrementAndGet();+ }+ }));+ }+ assertTrue(count.get() > 0);++ CollectionAdminRequest.deleteCollection("perReplicaDataColl").process(cluster.getSolrClient());++ }+public void testCreateCollectionAddReplica() throws Exception {JettySolrRunner jetty = cluster.getRandomJetty(random());int port = jetty.getLocalPort();@@ -137,6 +183,8 @@ public class TestPolicyCloud extends SolrCloudTestCase {assertEquals("Expected exactly three replica of collection on node with port: " + firstNodePort, 3, replicasOnNode1);assertEquals("Expected exactly three replica of collection on node with port: " + secondNodePort, 3, replicasOnNode2);+ CollectionAdminRequest.deleteCollection(collectionName).process(cluster.getSolrClient());+}public void testMetricsTag() throws Exception {diff --git a/solr/solrj/src/java/org/apache/solr/client/solrj/cloud/autoscaling/Clause.java b/solr/solrj/src/java/org/apache/solr/client/solrj/cloud/autoscaling/Clause.javaindex 7e14b4c41c7..20ff5e20eee 100644--- a/solr/solrj/src/java/org/apache/solr/client/solrj/cloud/autoscaling/Clause.java+++ b/solr/solrj/src/java/org/apache/solr/client/solrj/cloud/autoscaling/Clause.java@@ -18,10 +18,8 @@package org.apache.solr.client.solrj.cloud.autoscaling;import java.io.IOException;-import java.util.ArrayList;import java.util.Arrays;import java.util.Collection;-import java.util.Collections;import java.util.HashMap;import java.util.HashSet;import java.util.List;@@ -33,7 +31,6 @@ import java.util.Set;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;@@ -147,6 +144,10 @@ public class Clause implements MapWriter, Comparable<Clause> {if (tag != null && !params.contains(tag.name)) params.add(tag.name);}+ boolean isReplicaZero() {+ return replica != null && replica.getOperand() == EQUAL && 0L == (Long) replica.val;+ }+class Condition {final String name;final Object val;@@ -158,10 +159,11 @@ public class Clause implements MapWriter, Comparable<Clause> {this.op = op;}+boolean isPass(Object inputVal) {if (inputVal instanceof ReplicaCount) inputVal = ((ReplicaCount) inputVal).getVal(type);- ValidateInfo validator = getValidator(name);- if (validator == LazyValidator.INST) { // we don't know the type+ Suggestion.ConditionType validator = Suggestion.getTagType(name);+ if (validator == Suggestion.ConditionType.LAZY) { // we don't know the typereturn op.match(parseString(val), parseString(inputVal)) == PASS;} else {return op.match(val, validate(name, inputVal, false)) == PASS;@@ -183,13 +185,18 @@ public class Clause implements MapWriter, Comparable<Clause> {}public Long delta(Object val) {+ if (val instanceof ReplicaCount) val = ((ReplicaCount) val).getVal(type);if (this.val instanceof String) {if (op == LESS_THAN || op == GREATER_THAN) {- return op.delta(Clause.parseDouble(name, this.val), Clause.parseDouble(name, val));+ return op+ .opposite(isReplicaZero() && this == tag)+ .delta(Clause.parseDouble(name, this.val), Clause.parseDouble(name, val));} else {return 0l;}- } else return op.delta(this.val, val);+ } else return op+ .opposite(isReplicaZero() && this == tag)+ .delta(this.val, val);}public String getName() {@@ -235,7 +242,7 @@ public class Clause implements MapWriter, Comparable<Clause> {public List<Violation> test(List<Row> allRows) {- List<Violation> violations = new ArrayList<>();+ Suggestion.ViolationCtx ctx = new Suggestion.ViolationCtx(this, allRows);if (isPerCollectiontag()) {Map<String, Map<String, Map<String, ReplicaCount>>> replicaCount = computeReplicaCounts(allRows);for (Map.Entry<String, Map<String, Map<String, ReplicaCount>>> e : replicaCount.entrySet()) {@@ -244,14 +251,15 @@ public class Clause implements MapWriter, Comparable<Clause> {if (!shard.isPass(shardVsCount.getKey())) continue;for (Map.Entry<String, ReplicaCount> counts : shardVsCount.getValue().entrySet()) {if (!replica.isPass(counts.getValue())) {- violations.add(new Violation(this,+ Violation violation = new Violation(this,e.getKey(),shardVsCount.getKey(),tag.name.equals("node") ? counts.getKey() : null,counts.getValue(),replica.delta(counts.getValue()),- counts.getKey()- ));+ counts.getKey());+ Suggestion.getTagType(tag.name).addViolatingReplicas(ctx.reset(counts.getKey(), counts.getValue(), violation));+// Suggestion.getByTag(tag.name).violationFun.accept(ctx.reset(counts.getKey(), counts.getValue(), violation));}}}@@ -259,11 +267,12 @@ public class Clause implements MapWriter, Comparable<Clause> {} else {for (Row r : allRows) {if (!tag.isPass(r)) {- violations.add(new Violation(this, null, null, r.node, r.getVal(tag.name), tag.delta(r.getVal(tag.name)), null));+ Suggestion.ConditionType.CORES.addViolatingReplicas(ctx.reset(null, null,+ new Violation(this, null, null, r.node, r.getVal(tag.name), tag.delta(r.getVal(tag.name)), null)));}}}- return violations;+ return ctx.allViolations;}@@ -311,71 +320,6 @@ public class Clause implements MapWriter, Comparable<Clause> {private static final Set<String> IGNORE_TAGS = new HashSet<>(Arrays.asList(REPLICA, COLLECTION, SHARD, "strict", "type"));- static class ValidateInfo {- final Class type;- final Set<String> vals;- final Number min;- final Number max;--- ValidateInfo(Class type, Set<String> vals, Number min, Number max) {- 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());- this.max = max;- if (max != null && !type.isInstance(max))- throw new RuntimeException("wrong max value type, expected: " + type.getName() + " actual: " + max.getClass().getName());- }-- public Object validate(String name, Object val, boolean isRuleVal) {- if (type == Double.class) {- Double num = parseDouble(name, val);- if (isRuleVal) {- if (min != null)- if (Double.compare(num, (Double) min) == -1)- throw new RuntimeException(name + ": " + val + " must be greater than " + min);- if (max != null)- if (Double.compare(num, (Double) max) == 1)- throw new RuntimeException(name + ": " + val + " must be less than " + max);- }- return num;- } else if (type == Long.class) {- Long num = parseLong(name, val);- if (isRuleVal) {- if (min != null)- if (num < min.longValue())- throw new RuntimeException(name + ": " + val + " must be greater than " + min);- if (max != null)- if (num > max.longValue())- throw new RuntimeException(name + ": " + val + " must be less than " + max);- }- return num;- } else if (type == String.class) {- if (isRuleVal && vals != null && !vals.contains(val))- throw new RuntimeException(name + ": " + val + " must be one of " + StrUtils.join(vals, ','));- return val;- } else {- throw new RuntimeException("Invalid type ");- }-- }- }-- static class LazyValidator extends ValidateInfo {- static final LazyValidator INST = new LazyValidator();-- LazyValidator() {- super(null, null, null, null);- }-- @Override- public Object validate(String name, Object val, boolean isRuleVal) {- return parseString(val);- }- }-public static String parseString(Object val) {return val == null ? null : String.valueOf(val);}@@ -388,18 +332,11 @@ public class Clause implements MapWriter, Comparable<Clause> {*/public static Object validate(String name, Object val, boolean isRuleVal) {if (val == null) return null;- ValidateInfo info = getValidator(name);+ Suggestion.ConditionType info = Suggestion.getTagType(name);if (info == null) throw new RuntimeException("Unknown type :" + name);return info.validate(name, val, isRuleVal);}- private static ValidateInfo getValidator(String name) {- ValidateInfo info = validatetypes.get(name);- if (info == null && name.startsWith(ImplicitSnitch.SYSPROP)) info = validatetypes.get("STRING");- if (info == null && name.startsWith(METRICS_PREFIX)) info = LazyValidator.INST;- return info;- }-public static Long parseLong(String name, Object val) {if (val == null) return null;if (val instanceof Long) return (Long) val;@@ -425,6 +362,7 @@ public class Clause implements MapWriter, Comparable<Clause> {throw new RuntimeException(name + ": " + val + "not a valid number");}+public static Double parseDouble(String name, Object val) {if (val == null) return null;if (val instanceof Double) return (Double) val;@@ -448,22 +386,4 @@ public class Clause implements MapWriter, Comparable<Clause> {public static final String METRICS_PREFIX = "metrics:";- private static final Map<String, ValidateInfo> validatetypes = new HashMap<>();-- static {- validatetypes.put("collection", new ValidateInfo(String.class, null, null, null));- validatetypes.put("shard", new ValidateInfo(String.class, null, null, null));- validatetypes.put("replica", new ValidateInfo(Long.class, null, 0L, null));- validatetypes.put(ImplicitSnitch.PORT, new ValidateInfo(Long.class, null, 1L, 65535L));- validatetypes.put(ImplicitSnitch.DISK, new ValidateInfo(Double.class, null, 0d, Double.MAX_VALUE));- validatetypes.put(ImplicitSnitch.NODEROLE, new ValidateInfo(String.class, Collections.singleton("overseer"), null, null));- validatetypes.put(ImplicitSnitch.CORES, new ValidateInfo(Long.class, null, 0L, Long.MAX_VALUE));- validatetypes.put(ImplicitSnitch.SYSLOADAVG, new ValidateInfo(Double.class, null, 0d, 100d));- validatetypes.put(ImplicitSnitch.HEAPUSAGE, new ValidateInfo(Double.class, null, 0d, null));- validatetypes.put("NUMBER", new ValidateInfo(Long.class, null, 0L, Long.MAX_VALUE));//generic number validation- validatetypes.put("STRING", new ValidateInfo(String.class, null, null, null));//generic string validation- validatetypes.put("node", new ValidateInfo(String.class, null, null, null));- validatetypes.put("LAZY", LazyValidator.INST);- for (String ip : ImplicitSnitch.IP_SNITCHES) validatetypes.put(ip, new ValidateInfo(Long.class, null, 0L, 255L));- }}diff --git a/solr/solrj/src/java/org/apache/solr/client/solrj/cloud/autoscaling/MoveReplicaSuggester.java b/solr/solrj/src/java/org/apache/solr/client/solrj/cloud/autoscaling/MoveReplicaSuggester.javaindex 47a5549bda8..156f7025f2c 100644--- a/solr/solrj/src/java/org/apache/solr/client/solrj/cloud/autoscaling/MoveReplicaSuggester.java+++ b/solr/solrj/src/java/org/apache/solr/client/solrj/cloud/autoscaling/MoveReplicaSuggester.java@@ -41,8 +41,8 @@ public class MoveReplicaSuggester extends Suggester {for (Pair<ReplicaInfo, Row> fromReplica : getValidReplicas(true, true, -1)) {Row fromRow = fromReplica.second();ReplicaInfo replicaInfo = fromReplica.first();- String coll = replicaInfo.collection;- String shard = replicaInfo.shard;+ String coll = replicaInfo.getCollection();+ String shard = replicaInfo.getShard();Pair<Row, ReplicaInfo> pair = fromRow.removeReplica(coll, shard, replicaInfo.getType());Row srcTmpRow = pair.first();if (srcTmpRow == null) {@@ -67,11 +67,11 @@ public class MoveReplicaSuggester extends Suggester {}}if (targetNodeIndex != null && sourceNodeIndex != null) {- getMatrix().set(sourceNodeIndex, getMatrix().get(sourceNodeIndex).removeReplica(sourceReplicaInfo.collection, sourceReplicaInfo.shard, sourceReplicaInfo.getType()).first());- getMatrix().set(targetNodeIndex, getMatrix().get(targetNodeIndex).addReplica(sourceReplicaInfo.collection, sourceReplicaInfo.shard, sourceReplicaInfo.getType()));+ getMatrix().set(sourceNodeIndex, getMatrix().get(sourceNodeIndex).removeReplica(sourceReplicaInfo.getCollection(), sourceReplicaInfo.getShard(), sourceReplicaInfo.getType()).first());+ getMatrix().set(targetNodeIndex, getMatrix().get(targetNodeIndex).addReplica(sourceReplicaInfo.getCollection(), sourceReplicaInfo.getShard(), sourceReplicaInfo.getType()));return new CollectionAdminRequest.MoveReplica(- sourceReplicaInfo.collection,- sourceReplicaInfo.name,+ sourceReplicaInfo.getCollection(),+ sourceReplicaInfo.getName(),getMatrix().get(targetNodeIndex).node);}return null;diff --git a/solr/solrj/src/java/org/apache/solr/client/solrj/cloud/autoscaling/NoneSuggester.java b/solr/solrj/src/java/org/apache/solr/client/solrj/cloud/autoscaling/NoneSuggester.javaindex 5925bbb1566..1a18f261990 100644--- a/solr/solrj/src/java/org/apache/solr/client/solrj/cloud/autoscaling/NoneSuggester.java+++ b/solr/solrj/src/java/org/apache/solr/client/solrj/cloud/autoscaling/NoneSuggester.java@@ -28,7 +28,7 @@ public class NoneSuggester extends Suggester {}@Override- public SolrRequest getOperation() {+ public SolrRequest getSuggestion() {return null;}}diff --git a/solr/solrj/src/java/org/apache/solr/client/solrj/cloud/autoscaling/Operand.java b/solr/solrj/src/java/org/apache/solr/client/solrj/cloud/autoscaling/Operand.javaindex 13738c636f6..33decf077b3 100644--- a/solr/solrj/src/java/org/apache/solr/client/solrj/cloud/autoscaling/Operand.java+++ b/solr/solrj/src/java/org/apache/solr/client/solrj/cloud/autoscaling/Operand.java@@ -17,16 +17,15 @@package org.apache.solr.client.solrj.cloud.autoscaling;+import java.util.Objects;++import org.apache.solr.client.solrj.cloud.autoscaling.Clause.TestStatus;+import static org.apache.solr.client.solrj.cloud.autoscaling.Clause.TestStatus.FAIL;import static org.apache.solr.client.solrj.cloud.autoscaling.Clause.TestStatus.NOT_APPLICABLE;import static org.apache.solr.client.solrj.cloud.autoscaling.Clause.TestStatus.PASS;import static org.apache.solr.client.solrj.cloud.autoscaling.Policy.ANY;-import java.util.Objects;--import org.apache.solr.client.solrj.cloud.autoscaling.Clause.TestStatus;-import org.apache.solr.common.params.CoreAdminParams;-public enum Operand {WILDCARD(ANY, Integer.MAX_VALUE) {@@ -65,6 +64,11 @@ public enum Operand {return getLong(testVal) > getLong(ruleVal) ? PASS: FAIL ;}+ @Override+ public Operand opposite(boolean flag) {+ return flag ? LESS_THAN : GREATER_THAN;+ }+@Overrideprotected long _delta(long expected, long actual) {return actual > expected ? 0 : (expected + 1) - actual;@@ -83,10 +87,18 @@ public enum Operand {@Overrideprotected long _delta(long expected, long actual) {- return actual < expected ? 0 : (expected ) - actual;+ return actual < expected ? 0 : (actual + 1) - expected;}+ @Override+ public Operand opposite(boolean flag) {+ return flag ? GREATER_THAN : this;+ }};++ public Operand opposite(boolean flag) {+ return this;+ }public final String operand;final int priority;@@ -107,13 +119,14 @@ public enum Operand {}public Long delta(Object expected, Object actual) {- try {- 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;+ if (expected instanceof Number && actual instanceof Number) {+ Long expectedL = ((Number) expected).longValue();+ Long actualL = ((Number) actual).longValue();+ return _delta(expectedL, actualL);+ } else {+ return 0l;}+}protected long _delta(long expected, long actual) {diff --git a/solr/solrj/src/java/org/apache/solr/client/solrj/cloud/autoscaling/Policy.java b/solr/solrj/src/java/org/apache/solr/client/solrj/cloud/autoscaling/Policy.javaindex 85aa511058c..63ab8cb0016 100644--- a/solr/solrj/src/java/org/apache/solr/client/solrj/cloud/autoscaling/Policy.java+++ b/solr/solrj/src/java/org/apache/solr/client/solrj/cloud/autoscaling/Policy.java@@ -27,6 +27,7 @@ import java.util.HashSet;import java.util.LinkedHashMap;import java.util.List;import java.util.Map;+import java.util.Objects;import java.util.Set;import java.util.SortedSet;import java.util.TreeSet;@@ -67,6 +68,7 @@ public class Policy implements MapWriter {final List<Clause> clusterPolicy;final List<Preference> clusterPreferences;final List<String> params;+ final List<String> perReplicaAttributes;public Policy() {this(Collections.emptyMap());@@ -104,7 +106,13 @@ public class Policy implements MapWriter {this.policies = Collections.unmodifiableMap(policiesFromMap((Map<String, List<Map<String, Object>>>)jsonMap.getOrDefault(POLICIES, emptyMap()), newParams));this.params = Collections.unmodifiableList(newParams);-+ perReplicaAttributes = readPerReplicaAttrs();+ }+ private List<String> readPerReplicaAttrs() {+ return this.params.stream()+ .map(Suggestion.tagVsPerReplicaVal::get)+ .filter(Objects::nonNull)+ .collect(Collectors.toList());}private Policy(Map<String, List<Clause>> policies, List<Clause> clusterPolicy, List<Preference> clusterPreferences) {@@ -113,6 +121,7 @@ public class Policy implements MapWriter {this.clusterPreferences = clusterPreferences != null ? Collections.unmodifiableList(clusterPreferences) :Collections.singletonList(DEFAULT_PREFERENCE);this.params = Collections.unmodifiableList(buildParams(this.clusterPreferences, this.clusterPolicy, this.policies));+ perReplicaAttributes = readPerReplicaAttrs();}private List<String> buildParams(List<Preference> preferences, List<Clause> policy, Map<String, List<Clause>> policies) {@@ -230,7 +239,7 @@ public class Policy implements MapWriter {Collections.sort(expandedClauses);matrix = new ArrayList<>(nodes.size());- for (String node : nodes) matrix.add(new Row(node, params, cloudManager));+ for (String node : nodes) matrix.add(new Row(node, params, perReplicaAttributes,cloudManager));applyRules();}@@ -238,8 +247,10 @@ public class Policy implements MapWriter {String p = stateProvider.getPolicyNameByCollection(c);if (p != null) {List<Clause> perCollPolicy = policies.get(p);- if (perCollPolicy == null)- throw new RuntimeException(StrUtils.formatString("Policy for collection {0} is {1} . It does not exist", c, p));+ if (perCollPolicy == null) {+ return;+// throw new RuntimeException(StrUtils.formatString("Policy for collection {0} is {1} . It does not exist", c, p));+ }}expandedClauses.addAll(mergePolicies(c, policies.getOrDefault(p, emptyList()), clusterPolicy));}diff --git a/solr/solrj/src/java/org/apache/solr/client/solrj/cloud/autoscaling/PolicyHelper.java b/solr/solrj/src/java/org/apache/solr/client/solrj/cloud/autoscaling/PolicyHelper.javaindex 76fde67f3dc..46195a76429 100644--- a/solr/solrj/src/java/org/apache/solr/client/solrj/cloud/autoscaling/PolicyHelper.java+++ b/solr/solrj/src/java/org/apache/solr/client/solrj/cloud/autoscaling/PolicyHelper.java@@ -89,7 +89,7 @@ public class PolicyHelper {suggester = suggester.hint(Hint.TARGET_NODE, nodeName);}}- SolrRequest op = suggester.getOperation();+ SolrRequest op = suggester.getSuggestion();if (op == null) {throw new SolrException(SolrException.ErrorCode.BAD_REQUEST, "No node can satisfy the rules " +Utils.toJSONString(Utils.getDeepCopy(session.expandedClauses, 4, true)));@@ -140,6 +140,18 @@ public class PolicyHelper {}+ public static List<Suggester.SuggestionInfo> getSuggestions(AutoScalingConfig autoScalingConf, SolrCloudManager cloudManager) {+ Policy policy = autoScalingConf.getPolicy();+ Suggestion.SuggestionCtx suggestionCtx = new Suggestion.SuggestionCtx();+ suggestionCtx.session = policy.createSession(cloudManager);+ List<Violation> violations = suggestionCtx.session.getViolations();+ for (Violation violation : violations) {+ Suggestion.getTagType(violation.getClause().tag.name).getSuggestions(suggestionCtx.setViolation(violation));+ suggestionCtx.violation = null;+ }+ return suggestionCtx.getSuggestions();+ }+public static class SessionRef {private final AtomicLong myVersion = new AtomicLong(0);AtomicInteger refCount = new AtomicInteger();diff --git a/solr/solrj/src/java/org/apache/solr/client/solrj/cloud/autoscaling/ReplicaInfo.java b/solr/solrj/src/java/org/apache/solr/client/solrj/cloud/autoscaling/ReplicaInfo.javaindex dd48267c0ce..5f7281f33d8 100644--- a/solr/solrj/src/java/org/apache/solr/client/solrj/cloud/autoscaling/ReplicaInfo.java+++ b/solr/solrj/src/java/org/apache/solr/client/solrj/cloud/autoscaling/ReplicaInfo.java@@ -18,36 +18,52 @@package org.apache.solr.client.solrj.cloud.autoscaling;import java.io.IOException;-import java.util.HashMap;import java.util.Locale;import java.util.Map;import org.apache.solr.common.MapWriter;import org.apache.solr.common.cloud.Replica;import org.apache.solr.common.cloud.ZkStateReader;+import org.apache.solr.common.util.Utils;public class ReplicaInfo implements MapWriter {- final String name;- final String core, collection, shard;- final Map<String, Object> variables = new HashMap<>();+// private final Replica replica;+ private final String name;+ private String core, collection, shard;+ private Replica.Type type;+ private String node;+ private Map<String, Object> variables;++ public ReplicaInfo(String coll,String shard, Replica r, Map<String, Object> vals){+ this.name = r.getName();+ this.core = r.getCoreName();+ this.collection = coll;+ this.shard = shard;+ this.type = r.getType();+ this.variables = vals;+ this.node = r.getNodeName();+ }- public ReplicaInfo(String name, String coreName, String coll, String shard, Map<String, Object> vals) {+ public ReplicaInfo(String name, String core, String coll, String shard, Replica.Type type, String node, Map<String, Object> vals) {this.name = name;- this.core = coreName == null ? (String) vals.get("core") : coreName;- if (vals != null) {- this.variables.putAll(vals);- }+ this.variables = vals;this.collection = coll;this.shard = shard;+ this.type = type;+ this.core = core;+ this.node = node;}@Overridepublic void writeMap(EntryWriter ew) throws IOException {ew.put(name, (MapWriter) ew1 -> {- for (Map.Entry<String, Object> e : variables.entrySet()) {- ew1.put(e.getKey(), e.getValue());+ 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());});}@@ -68,15 +84,13 @@ public class ReplicaInfo implements MapWriter {}public Replica.Type getType() {- Object o = variables.get(ZkStateReader.REPLICA_TYPE);+ Object o = type == null ? variables.get(ZkStateReader.REPLICA_TYPE) : type;if (o == null) {- variables.put(ZkStateReader.REPLICA_TYPE, Replica.Type.NRT);return Replica.Type.NRT;} else if (o instanceof Replica.Type) {return (Replica.Type)o;} else {Replica.Type type = Replica.Type.get(String.valueOf(o).toUpperCase(Locale.ROOT));- variables.put(ZkStateReader.REPLICA_TYPE, type);return type;}}@@ -101,11 +115,10 @@ public class ReplicaInfo implements MapWriter {@Overridepublic String toString() {- return "ReplicaInfo{" +- "name='" + name + '\'' +- ", collection='" + collection + '\'' +- ", shard='" + shard + '\'' +- ", variables=" + variables +- '}';+ return Utils.toJSONString(this);+ }++ public String getNode() {+ return node;}}diff --git a/solr/solrj/src/java/org/apache/solr/client/solrj/cloud/autoscaling/Row.java b/solr/solrj/src/java/org/apache/solr/client/solrj/cloud/autoscaling/Row.javaindex a5c7a437369..e842fb97d25 100644--- a/solr/solrj/src/java/org/apache/solr/client/solrj/cloud/autoscaling/Row.java+++ b/solr/solrj/src/java/org/apache/solr/client/solrj/cloud/autoscaling/Row.java@@ -24,6 +24,7 @@ import java.util.HashMap;import java.util.List;import java.util.Map;import java.util.Random;+import java.util.function.Consumer;import org.apache.solr.common.IteratorWriter;import org.apache.solr.common.MapWriter;@@ -42,9 +43,9 @@ public class Row implements MapWriter {boolean anyValueMissing = false;boolean isLive = true;- public Row(String node, List<String> params, SolrCloudManager cloudManager) {+ public Row(String node, List<String> params, List<String> perReplicaAttributes, SolrCloudManager cloudManager) {NodeStateProvider nodeStateProvider = cloudManager.getNodeStateProvider();- collectionVsShardVsReplicas = nodeStateProvider.getReplicaInfo(node, params);+ collectionVsShardVsReplicas = nodeStateProvider.getReplicaInfo(node, perReplicaAttributes);if (collectionVsShardVsReplicas == null) collectionVsShardVsReplicas = new HashMap<>();this.node = node;cells = new Cell[params.size()];@@ -88,6 +89,14 @@ public class Row implements MapWriter {return null;}+ Object getVal(String name, Object def) {+ for (Cell cell : cells)+ if (cell.name.equals(name)) {+ return cell.val == null ? def : cell.val;+ }+ return def;+ }+@Overridepublic String toString() {return node;@@ -99,7 +108,7 @@ public class Row implements MapWriter {Map<String, List<ReplicaInfo>> c = row.collectionVsShardVsReplicas.computeIfAbsent(coll, k -> new HashMap<>());List<ReplicaInfo> replicas = c.computeIfAbsent(shard, k -> new ArrayList<>());String replicaname = "" + new Random().nextInt(1000) + 1000;- replicas.add(new ReplicaInfo(replicaname,replicaname, coll, shard,+ replicas.add(new ReplicaInfo(replicaname, replicaname, coll, shard, type, this.node,Collections.singletonMap(ZkStateReader.REPLICA_TYPE, type != null ? type.toString() : Replica.Type.NRT.toString())));for (Cell cell : row.cells) {if (cell.name.equals("cores")) {@@ -138,4 +147,15 @@ public class Row implements MapWriter {public Cell[] getCells() {return cells;}++ public void forEachReplica(Consumer<ReplicaInfo> consumer) {+ forEachReplica(collectionVsShardVsReplicas, consumer);+ }++ public static void forEachReplica(Map<String, Map<String, List<ReplicaInfo>>> collectionVsShardVsReplicas, Consumer<ReplicaInfo> consumer) {+ collectionVsShardVsReplicas.forEach((coll, shardVsReplicas) -> shardVsReplicas+ .forEach((shard, replicaInfos) -> {+ for (ReplicaInfo r : replicaInfos) consumer.accept(r);+ }));+ }}diff --git a/solr/solrj/src/java/org/apache/solr/client/solrj/cloud/autoscaling/Suggester.java b/solr/solrj/src/java/org/apache/solr/client/solrj/cloud/autoscaling/Suggester.javaindex 4eb25dbcefe..a0db4eddbf4 100644--- a/solr/solrj/src/java/org/apache/solr/client/solrj/cloud/autoscaling/Suggester.java+++ b/solr/solrj/src/java/org/apache/solr/client/solrj/cloud/autoscaling/Suggester.java@@ -17,6 +17,7 @@package org.apache.solr.client.solrj.cloud.autoscaling;+import java.io.IOException;import java.util.ArrayList;import java.util.Collection;import java.util.Collections;@@ -31,6 +32,7 @@ import java.util.function.Consumer;import org.apache.solr.client.solrj.SolrRequest;import org.apache.solr.client.solrj.impl.ClusterStateProvider;+import org.apache.solr.common.MapWriter;import org.apache.solr.common.cloud.Replica;import org.apache.solr.common.util.Pair;@@ -66,7 +68,7 @@ public abstract class Suggester {abstract SolrRequest init();- public SolrRequest getOperation() {+ public SolrRequest getSuggestion() {if (!isInitialized) {Set<String> collections = (Set<String>) hints.getOrDefault(Hint.COLL, Collections.emptySet());Set<Pair<String, String>> s = (Set<Pair<String, String>>) hints.getOrDefault(Hint.COLL_SHARD, Collections.emptySet());@@ -92,7 +94,7 @@ public abstract class Suggester {// the source node is dead so live nodes may not have itfor (String srcNode : srcNodes) {if(session.matrix.stream().noneMatch(row -> row.node.equals(srcNode)))- session.matrix.add(new Row(srcNode, session.getPolicy().params, session.cloudManager));+ session.matrix.add(new Row(srcNode, session.getPolicy().params, session.getPolicy().perReplicaAttributes, session.cloudManager));}}session.applyRules();@@ -112,6 +114,31 @@ public abstract class Suggester {}+ public static class SuggestionInfo implements MapWriter {+ Violation violation;+ SolrRequest operation;++ public SuggestionInfo(Violation violation, SolrRequest op) {+ this.violation = violation;+ this.operation = op;+ }++ public SolrRequest getOperation() {+ return operation;+ }++ public Violation getViolation() {+ return violation;+ }++ @Override+ public void writeMap(EntryWriter ew) throws IOException {+ ew.put("type", violation == null ? "improvement" : "violation");+ ew.putIfNotNull("violation", violation);+ ew.put("operation", operation);+ }+ }+//check if the fresh set of violations is less serious than the last set of violationsboolean isLessSerious(List<Violation> fresh, List<Violation> old) {if (old == null || fresh.size() < old.size()) return true;diff --git a/solr/solrj/src/java/org/apache/solr/client/solrj/cloud/autoscaling/Suggestion.java b/solr/solrj/src/java/org/apache/solr/client/solrj/cloud/autoscaling/Suggestion.javanew file mode 100644index 00000000000..d14643fdba5--- /dev/null+++ b/solr/solrj/src/java/org/apache/solr/client/solrj/cloud/autoscaling/Suggestion.java@@ -0,0 +1,304 @@+/*+ * 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.cloud.autoscaling;++import java.util.ArrayList;+import java.util.Collections;+import java.util.Comparator;+import java.util.HashMap;+import java.util.List;+import java.util.Map;+import java.util.Set;+import java.util.stream.Collectors;+import java.util.stream.Stream;++import org.apache.solr.client.solrj.SolrRequest;+import org.apache.solr.client.solrj.V2RequestSupport;+import org.apache.solr.common.cloud.rule.ImplicitSnitch;+import org.apache.solr.common.util.Pair;+import org.apache.solr.common.util.StrUtils;++import static org.apache.solr.client.solrj.cloud.autoscaling.Policy.ANY;+import static org.apache.solr.common.params.CollectionParams.CollectionAction.MOVEREPLICA;++public class Suggestion {+ static final String coreidxsize = "INDEX.sizeInBytes";+ static final Map<String, ConditionType> validatetypes = new HashMap<>();++ public static ConditionType getTagType(String name) {+ ConditionType info = validatetypes.get(name);+ if (info == null && name.startsWith(ImplicitSnitch.SYSPROP)) info = validatetypes.get("STRING");+ if (info == null && name.startsWith(Clause.METRICS_PREFIX)) info = ConditionType.LAZY;+ return info;+ }++ static class ViolationCtx {+ String tagKey;+ Clause clause;+ ReplicaCount count;++ Violation currentViolation;+ List<Row> allRows;++ List<Violation> allViolations = new ArrayList<>();++ public ViolationCtx(Clause clause, List<Row> allRows) {+ this.allRows = allRows;+ this.clause = clause;+ }++ public ViolationCtx reset(String tagKey, ReplicaCount count, Violation currentViolation) {+ this.tagKey = tagKey;+ this.count = count;+ this.currentViolation = currentViolation;+ allViolations.add(currentViolation);+ return this;+ }+ }+++ static class SuggestionCtx {+ public Policy.Session session;+ public Violation violation;+ private List<Suggester.SuggestionInfo> suggestions = new ArrayList<>();++ SolrRequest addSuggestion(Suggester suggester) {+ SolrRequest op = suggester.getSuggestion();+ if (op != null) {+ session = suggester.getSession();+ suggestions.add(new Suggester.SuggestionInfo( violation,+ ((V2RequestSupport) op.setUseV2(true)).getV2Request()));+ }+ return op;+ }+++ public SuggestionCtx setViolation(Violation violation) {+ this.violation = violation;+ return this;+ }++ public List<Suggester.SuggestionInfo> getSuggestions() {+ return suggestions;+ }+ }+++ public static final Map<String, String> tagVsPerReplicaVal = Stream.of(ConditionType.values())+ .filter(tag -> tag.perReplicaValue != null)+ .collect(Collectors.toMap(tag -> tag.tagName, tag -> tag.perReplicaValue));++ public enum ConditionType {++ COLL("collection", String.class, null, null, null),+ SHARD("shard", String.class, null, null, null),+ REPLICA("replica", Long.class, null, 0L, null),+ PORT(ImplicitSnitch.PORT, Long.class, null, 1L, 65535L),+ IP_1("ip_1", Long.class, null, 0L, 255L),+ IP_2("ip_2", Long.class, null, 0L, 255L),+ IP_3("ip_3", Long.class, null, 0L, 255L),+ IP_4("ip_4", Long.class, null, 0L, 255L),+ FREEDISK(ImplicitSnitch.DISK, Double.class, null, 0d, Double.MAX_VALUE, coreidxsize) {+ @Override+ public Object convertVal(Object val) {+ Number value = (Number) super.validate(ImplicitSnitch.DISK, val, false);+ if (value != null) {+ value = value.doubleValue() / 1024.0d / 1024.0d / 1024.0d;+ }+ return value;+ }++ @Override+ public void getSuggestions(SuggestionCtx ctx) {+ if (ctx.violation == null) return;+ if (ctx.violation.replicaCountDelta < 0 && !ctx.violation.getViolatingReplicas().isEmpty()) {++ Comparator<Row> rowComparator = Comparator.comparing(r -> ((Long) r.getVal(ImplicitSnitch.DISK, 0l)));+ List<Row> matchingNodes = ctx.session.matrix.stream().filter(+ row -> ctx.violation.getViolatingReplicas()+ .stream()+ .anyMatch(p -> row.node.equals(p.first().getNode())))+ .sorted(rowComparator)+ .collect(Collectors.toList());+++ for (Row r : matchingNodes) {+ //lets try to start moving the smallest cores off of the node+ ArrayList<ReplicaInfo> replicas = new ArrayList<>();+ r.forEachReplica(replicas::add);+ replicas.sort((r1, r2) -> {+ Long s1 = Clause.parseLong(ConditionType.CORE_IDX.tagName, r1.getVariables().get(ConditionType.CORE_IDX.tagName));+ Long s2 = Clause.parseLong(ConditionType.CORE_IDX.tagName, r2.getVariables().get(ConditionType.CORE_IDX.tagName));+ if (s1 != null && s2 != null) return s1.compareTo(s2);+ return 0;+ });+ long currentDelta = ctx.violation.getClause().tag.delta(r.getVal(ImplicitSnitch.DISK));+ for (ReplicaInfo replica : replicas) {+ if (currentDelta <= 0) break;+ if (replica.getVariables().get(ConditionType.CORE_IDX.tagName) == null) continue;+ Suggester suggester = ctx.session.getSuggester(MOVEREPLICA)+ .hint(Suggester.Hint.COLL_SHARD, new Pair<>(replica.getCollection(), replica.getShard()))+ .hint(Suggester.Hint.SRC_NODE, r.node);+ if (ctx.addSuggestion(suggester) == null) break;+ currentDelta -= Clause.parseLong(ConditionType.CORE_IDX.tagName, replica.getVariables().get(ConditionType.CORE_IDX.tagName));+ }+ }+ }+ }+ },+ CORE_IDX(coreidxsize, Double.class, null, 0d, Double.MAX_VALUE) {+ @Override+ public Object convertVal(Object val) {+ return FREEDISK.convertVal(val);+ }+ },+ NODE_ROLE(ImplicitSnitch.NODEROLE, String.class, Collections.singleton("overseer"), null, null),+ CORES(ImplicitSnitch.CORES, Long.class, null, 0L, Long.MAX_VALUE) {+ @Override+ public void addViolatingReplicas(ViolationCtx ctx) {+ for (Row r : ctx.allRows) {+ if (!ctx.clause.tag.isPass(r)) {+ r.forEachReplica(replicaInfo -> ctx.currentViolation.addReplica(replicaInfo,+ new Violation.ViolationMeta().withDelta(ctx.clause.tag.delta(r.getVal(ImplicitSnitch.CORES)))));+ }+ }++ }++ @Override+ public void getSuggestions(SuggestionCtx ctx) {+ if (ctx.violation == null || ctx.violation.replicaCountDelta == 0) return;+ if (ctx.violation.replicaCountDelta > 0) {//there are more replicas than necessary+ for (int i = 0; i < Math.abs(ctx.violation.replicaCountDelta); i++) {+ Suggester suggester = ctx.session.getSuggester(MOVEREPLICA)+ .hint(Suggester.Hint.SRC_NODE, ctx.violation.node)+ .hint(ctx.violation.shard.equals(ANY) ? Suggester.Hint.COLL : Suggester.Hint.COLL_SHARD,+ ctx.violation.shard.equals(ANY) ? ctx.violation.coll : new Pair<>(ctx.violation.coll, ctx.violation.shard));+ ctx.addSuggestion(suggester);+ }+ }++ }+ },+ SYSLOADAVG(ImplicitSnitch.SYSLOADAVG, Double.class, null, 0d, 100d),+ HEAPUSAGE(ImplicitSnitch.HEAPUSAGE, Double.class, null, 0d, null),+ NUMBER("NUMBER", Long.class, null, 0L, Long.MAX_VALUE),+ STRING("STRING", String.class, null, null, null),+ NODE("node", String.class, null, null, null) {+ @Override+ public void getSuggestions(SuggestionCtx ctx) {+ if (ctx.violation == null || ctx.violation.replicaCountDelta == 0) return;+ if (ctx.violation.replicaCountDelta > 0) {//there are more replicas than necessary+ for (int i = 0; i < Math.abs(ctx.violation.replicaCountDelta); i++) {+ Suggester suggester = ctx.session.getSuggester(MOVEREPLICA)+ .hint(Suggester.Hint.SRC_NODE, ctx.violation.node)+ .hint(ctx.violation.shard.equals(ANY) ? Suggester.Hint.COLL : Suggester.Hint.COLL_SHARD,+ ctx.violation.shard.equals(ANY) ? ctx.violation.coll : new Pair<>(ctx.violation.coll, ctx.violation.shard));+ ctx.addSuggestion(suggester);+ }+ }++ }+ },+ LAZY("LAZY", null, null, null, null) {+ @Override+ public Object validate(String name, Object val, boolean isRuleVal) {+ return Clause.parseString(val);+ }+ },;++ final Class type;+ final Set<String> vals;+ final Number min;+ final Number max;+ public final String tagName;+ public final String perReplicaValue;++ ConditionType(String tagName, Class type, Set<String> vals, Number min, Number max) {+ this(tagName, type, vals, min, max, null);++ }++ ConditionType(String tagName, Class type, Set<String> vals, Number min, Number max, String perReplicaValue) {+ this.tagName = tagName;+ this.type = type;+ this.vals = vals;+ this.min = min;+ this.max = max;+ this.perReplicaValue = perReplicaValue;+ }++ public void getSuggestions(SuggestionCtx ctx) {++ }++ public void addViolatingReplicas(ViolationCtx ctx) {+ for (Row row : ctx.allRows) {+ row.forEachReplica(replica -> {+ if (ctx.clause.replica.isPass(0) && !ctx.clause.tag.isPass(row)) return;+ if (!ctx.clause.replica.isPass(0) && ctx.clause.tag.isPass(row)) return;+ if (!ctx.clause.collection.isPass(ctx.currentViolation.coll) || !ctx.clause.shard.isPass(ctx.currentViolation.shard))+ return;+ ctx.currentViolation.addReplica(replica, new Violation.ViolationMeta().withDelta(ctx.clause.tag.delta(row.getVal(ctx.clause.tag.name))));+ });+ }+ }+++ public Object convertVal(Object val) {+ return val;+ }++ public Object validate(String name, Object val, boolean isRuleVal) {+ if (type == Double.class) {+ Double num = Clause.parseDouble(name, val);+ if (isRuleVal) {+ if (min != null)+ if (Double.compare(num, (Double) min) == -1)+ throw new RuntimeException(name + ": " + val + " must be greater than " + min);+ if (max != null)+ if (Double.compare(num, (Double) max) == 1)+ throw new RuntimeException(name + ": " + val + " must be less than " + max);+ }+ return num;+ } else if (type == Long.class) {+ Long num = Clause.parseLong(name, val);+ if (isRuleVal) {+ if (min != null)+ if (num < min.longValue())+ throw new RuntimeException(name + ": " + val + " must be greater than " + min);+ if (max != null)+ if (num > max.longValue())+ throw new RuntimeException(name + ": " + val + " must be less than " + max);+ }+ return num;+ } else if (type == String.class) {+ if (isRuleVal && vals != null && !vals.contains(val))+ throw new RuntimeException(name + ": " + val + " must be one of " + StrUtils.join(vals, ','));+ return val;+ } else {+ throw new RuntimeException("Invalid type ");+ }++ }+ }++ static {+ for (Suggestion.ConditionType t : Suggestion.ConditionType.values()) Suggestion.validatetypes.put(t.tagName, t);+ }+}diff --git a/solr/solrj/src/java/org/apache/solr/client/solrj/cloud/autoscaling/Violation.java b/solr/solrj/src/java/org/apache/solr/client/solrj/cloud/autoscaling/Violation.javaindex e7d827241d2..8c9752265a6 100644--- a/solr/solrj/src/java/org/apache/solr/client/solrj/cloud/autoscaling/Violation.java+++ b/solr/solrj/src/java/org/apache/solr/client/solrj/cloud/autoscaling/Violation.java@@ -18,33 +18,45 @@package org.apache.solr.client.solrj.cloud.autoscaling;import java.io.IOException;+import java.util.ArrayList;import java.util.HashMap;import java.util.LinkedHashMap;+import java.util.List;import java.util.Objects;import org.apache.solr.common.MapWriter;+import org.apache.solr.common.util.Pair;import org.apache.solr.common.util.Utils;public class Violation implements MapWriter {final String shard, coll, node;final Object actualVal;- final Long delta;//how far is the actual value from the expected value+ final Long replicaCountDelta;//how far is the actual value from the expected valuefinal Object tagKey;private final int hash;private final Clause clause;+ private List<Pair<ReplicaInfo, ViolationMeta>> violationVsMetaData = new ArrayList<>();-- Violation(Clause clause, String coll, String shard, String node, Object actualVal, Long delta, Object tagKey) {+ Violation(Clause clause, String coll, String shard, String node, Object actualVal, Long replicaCountDelta, Object tagKey) {this.clause = clause;this.shard = shard;this.coll = coll;this.node = node;- this.delta = delta;+ this.replicaCountDelta = replicaCountDelta;this.actualVal = actualVal;this.tagKey = tagKey;hash = ("" + coll + " " + shard + " " + node + " " + String.valueOf(tagKey) + " " + Utils.toJSONString(getClause().toMap(new HashMap<>()))).hashCode();}+ public Violation addReplica(ReplicaInfo r, ViolationMeta meta) {+ violationVsMetaData.add(new Pair<>(r, meta));+ return this;+ }++ public List<Pair<ReplicaInfo, ViolationMeta>> getViolatingReplicas() {+ return violationVsMetaData;+ }+public Clause getClause() {return clause;}@@ -55,8 +67,8 @@ public class Violation implements MapWriter {}//if the delta is lower , this violation is less seriouspublic boolean isLessSerious(Violation that) {- return that.delta != null && delta != null &&- Math.abs(delta) < Math.abs(that.delta);+ return that.replicaCountDelta != null && replicaCountDelta != null &&+ Math.abs(replicaCountDelta) < Math.abs(that.replicaCountDelta);}@Override@@ -86,8 +98,27 @@ public class Violation implements MapWriter {ew.putIfNotNull("violation", (MapWriter) ew1 -> {if (getClause().isPerCollectiontag()) ew1.put("replica", actualVal);else ew1.put(clause.tag.name, String.valueOf(actualVal));- ew1.putIfNotNull("delta", delta);+ ew1.putIfNotNull("delta", replicaCountDelta);});ew.put("clause", getClause());}++ static class ViolationMeta implements MapWriter {+ Long delta;++ public ViolationMeta withDelta(Long delta) {+ this.delta = delta;+ return this;+ }++ @Override+ public void writeMap(EntryWriter ew) throws IOException {+ ew.putIfNotNull("delta", delta);+ }++ @Override+ public String toString() {+ return Utils.toJSONString(this);+ }+ }}diff --git a/solr/solrj/src/java/org/apache/solr/client/solrj/impl/SolrClientNodeStateProvider.java b/solr/solrj/src/java/org/apache/solr/client/solrj/impl/SolrClientNodeStateProvider.javaindex 31580494644..7048067e79f 100644--- a/solr/solrj/src/java/org/apache/solr/client/solrj/impl/SolrClientNodeStateProvider.java+++ b/solr/solrj/src/java/org/apache/solr/client/solrj/impl/SolrClientNodeStateProvider.java@@ -22,19 +22,22 @@ import java.lang.invoke.MethodHandles;import java.util.ArrayList;import java.util.Arrays;import java.util.Collection;-import java.util.Collections;import java.util.HashMap;import java.util.HashSet;import java.util.List;import java.util.Map;import java.util.Set;+import java.util.stream.Collectors;import org.apache.solr.client.solrj.SolrRequest;import org.apache.solr.client.solrj.SolrServerException;import org.apache.solr.client.solrj.cloud.autoscaling.NodeStateProvider;import org.apache.solr.client.solrj.cloud.autoscaling.ReplicaInfo;+import org.apache.solr.client.solrj.cloud.autoscaling.Row;+import org.apache.solr.client.solrj.cloud.autoscaling.Suggestion;import org.apache.solr.client.solrj.request.GenericSolrRequest;import org.apache.solr.client.solrj.response.SimpleSolrResponse;+import org.apache.solr.common.MapWriter;import org.apache.solr.common.SolrException;import org.apache.solr.common.cloud.ClusterState;import org.apache.solr.common.cloud.DocCollection;@@ -46,18 +49,20 @@ import org.apache.solr.common.params.CommonParams;import org.apache.solr.common.params.ModifiableSolrParams;import org.apache.solr.common.params.SolrParams;import org.apache.solr.common.util.NamedList;+import org.apache.solr.common.util.Pair;import org.apache.solr.common.util.StrUtils;import org.apache.solr.common.util.Utils;import org.apache.zookeeper.KeeperException;import org.slf4j.Logger;import org.slf4j.LoggerFactory;+import static java.util.Collections.emptyMap;import static org.apache.solr.client.solrj.cloud.autoscaling.Clause.METRICS_PREFIX;/****/-public class SolrClientNodeStateProvider implements NodeStateProvider {+public class SolrClientNodeStateProvider implements NodeStateProvider, MapWriter {private static final Logger log = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());//only for debuggingpublic static SolrClientNodeStateProvider INST;@@ -65,7 +70,7 @@ public class SolrClientNodeStateProvider implements NodeStateProvider {private final CloudSolrClient solrClient;private final ZkStateReader zkStateReader;- private final Map<String, Map<String, Map<String, List<ReplicaInfo>>>> data = new HashMap<>();+ private final Map<String, Map<String, Map<String, List<ReplicaInfo>>>> nodeVsCollectionVsShardVsReplicaInfo = new HashMap<>();private Map<String, Object> snitchSession = new HashMap<>();private Map<String, Map> nodeVsTags = new HashMap<>();@@ -81,15 +86,23 @@ public class SolrClientNodeStateProvider implements NodeStateProvider {DocCollection coll = ref.get();if (coll == null) return;coll.forEachReplica((shard, replica) -> {- Map<String, Map<String, List<ReplicaInfo>>> nodeData = data.computeIfAbsent(replica.getNodeName(), k -> new HashMap<>());+ Map<String, Map<String, List<ReplicaInfo>>> nodeData = nodeVsCollectionVsShardVsReplicaInfo.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(), replica.getCoreName(), collName, shard, replica.getProperties()));+ replicas.add(new ReplicaInfo(collName, shard, replica, new HashMap<>(replica.getProperties())));});});if(log.isDebugEnabled()) INST = this;}+ @Override+ public void writeMap(EntryWriter ew) throws IOException {+// ew.put("liveNodes", liveNodes);+ ew.put("replicaInfo", Utils.getDeepCopy(nodeVsCollectionVsShardVsReplicaInfo, 5));+ ew.put("nodeValues", nodeVsTags);++ }+@Overridepublic Map<String, Object> getNodeValues(String node, Collection<String> tags) {AutoScalingSnitch snitch = new AutoScalingSnitch();@@ -102,7 +115,45 @@ public class SolrClientNodeStateProvider implements NodeStateProvider {@Overridepublic Map<String, Map<String, List<ReplicaInfo>>> getReplicaInfo(String node, Collection<String> keys) {- return data.computeIfAbsent(node, s -> Collections.emptyMap());//todo fill other details+ Map<String, Map<String, List<ReplicaInfo>>> result = nodeVsCollectionVsShardVsReplicaInfo.computeIfAbsent(node, s -> emptyMap());+ if (!keys.isEmpty()) {+ Map<String, Pair<String, ReplicaInfo>> keyVsReplica = new HashMap<>();+ Row.forEachReplica(result, r -> {+ for (String key : keys) {+ if (r.getVariables().containsKey(key)) continue;+ keyVsReplica.put("solr.core." + r.getCollection() + "." + r.getShard() + "." + Utils.parseMetricsReplicaName(r.getCollection(), r.getCore()) + ":" + key, new Pair<>(key, r));+ }+ });++ if (!keyVsReplica.isEmpty()) {+ ClientSnitchCtx ctx = new ClientSnitchCtx(null, null, emptyMap(), solrClient);+ fetchMetrics(node, ctx,+ keyVsReplica.entrySet().stream()+ .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getKey)));+ ctx.getTags().forEach((k, o) -> {+ Pair<String, ReplicaInfo> p = keyVsReplica.get(k);+ Suggestion.ConditionType validator = Suggestion.getTagType(p.first());+ if (validator != null) o = validator.convertVal(o);+ if (p != null) p.second().getVariables().put(p.first(), o);+ });++ }+ }+ return result;+ }++ static void fetchMetrics(String solrNode, ClientSnitchCtx ctx, Map<String, String> metricsKeyVsTag) {+ ModifiableSolrParams params = new ModifiableSolrParams();+ params.add("key", metricsKeyVsTag.keySet().toArray(new String[metricsKeyVsTag.size()]));+ try {+ SimpleSolrResponse rsp = ctx.invoke(solrNode, CommonParams.METRICS_PATH, params);+ metricsKeyVsTag.forEach((key, tag) -> {+ Object v = Utils.getObjectByPath(rsp.nl, true, Arrays.asList("metrics", key));+ if (v != null) ctx.getTags().put(tag, v);+ });+ } catch (Exception e) {+ log.warn("could not get tags from node " + solrNode, e);+ }}//uses metrics API to get node information@@ -119,17 +170,7 @@ public class SolrClientNodeStateProvider implements NodeStateProvider {}}if (!metricsKeyVsTag.isEmpty()) {- ModifiableSolrParams params = new ModifiableSolrParams();- params.add("key", metricsKeyVsTag.keySet().toArray(new String[metricsKeyVsTag.size()]));- try {- SimpleSolrResponse rsp = snitchContext.invoke(solrNode, CommonParams.METRICS_PATH, params);- metricsKeyVsTag.forEach((key, tag) -> {- Object v = Utils.getObjectByPath(rsp.nl, true, Arrays.asList("metrics", key));- if (v != null) snitchContext.getTags().put(tag, v);- });- } catch (Exception e) {- log.warn("could not get tags from node " + solrNode, e);- }+ fetchMetrics(solrNode, snitchContext, metricsKeyVsTag);}Set<String> groups = new HashSet<>();@@ -160,8 +201,8 @@ public class SolrClientNodeStateProvider implements NodeStateProvider {SimpleSolrResponse rsp = snitchContext.invoke(solrNode, CommonParams.METRICS_PATH, params);Map m = rsp.nl.asMap(4);if (requestedTags.contains(DISK)) {- Number n = (Number) Utils.getObjectByPath(m, true, "metrics/solr.node/CONTAINER.fs.usableSpace");- if (n != null) ctx.getTags().put(DISK, n.doubleValue() / 1024.0d / 1024.0d / 1024.0d);+ Object n = Utils.getObjectByPath(m, true, "metrics/solr.node/CONTAINER.fs.usableSpace");+ if (n != null) ctx.getTags().put(DISK, Suggestion.getTagType(DISK).convertVal(n));}if (requestedTags.contains(CORES)) {int count = 0;diff --git a/solr/solrj/src/java/org/apache/solr/client/solrj/request/V2Request.java b/solr/solrj/src/java/org/apache/solr/client/solrj/request/V2Request.javaindex 66944878ff3..c6a553826f6 100644--- a/solr/solrj/src/java/org/apache/solr/client/solrj/request/V2Request.java+++ b/solr/solrj/src/java/org/apache/solr/client/solrj/request/V2Request.java@@ -30,17 +30,17 @@ import java.util.regex.Pattern;import org.apache.solr.client.solrj.SolrClient;import org.apache.solr.client.solrj.SolrRequest;import org.apache.solr.client.solrj.response.V2Response;-import org.apache.solr.common.SolrException;+import org.apache.solr.common.MapWriter;import org.apache.solr.common.params.SolrParams;import org.apache.solr.common.util.ContentStream;import org.apache.solr.common.util.ContentStreamBase;import org.apache.solr.common.util.Utils;-public class V2Request extends SolrRequest<V2Response> {+public class V2Request extends SolrRequest<V2Response> implements MapWriter {//only for debugging purposespublic static final ThreadLocal<AtomicLong> v2Calls = new ThreadLocal<>();static final Pattern COLL_REQ_PATTERN = Pattern.compile("/(c|collections)/([^/])+/(?!shards)");- private InputStream payload;+ private Object payload;private SolrParams solrParams;public final boolean useBinary;private String collection;@@ -69,7 +69,9 @@ public class V2Request extends SolrRequest<V2Response> {return Collections.singleton(new ContentStreamBase() {@Overridepublic InputStream getStream() throws IOException {- return payload;+ if(payload instanceof InputStream) return (InputStream) payload;+ if (useBinary) return Utils.toJavabin(payload);+ else return new ByteArrayInputStream(Utils.toJSON(payload));}@Override@@ -95,6 +97,14 @@ public class V2Request extends SolrRequest<V2Response> {return new V2Response();}+ @Override+ public void writeMap(EntryWriter ew) throws IOException {+ ew.put("method", getMethod().toString());+ ew.put("path", getPath());+ ew.putIfNotNull("params", solrParams);+ ew.putIfNotNull("command", payload);+ }+public static class Builder {private String resource;private METHOD method = METHOD.GET;@@ -135,10 +145,6 @@ public class V2Request extends SolrRequest<V2Response> {return this;}- public Builder withPayload(InputStream payload) {- this.payload = payload;- return this;- }public Builder withParams(SolrParams params) {this.params = params;@@ -151,22 +157,10 @@ public class V2Request extends SolrRequest<V2Response> {}public V2Request build() {- try {- V2Request v2Request = new V2Request(method, resource, useBinary);- v2Request.solrParams = params;- InputStream is = null;- if (payload != null) {- if (payload instanceof InputStream) is = (InputStream) payload;- else if (useBinary) is = Utils.toJavabin(payload);- else is = new ByteArrayInputStream(Utils.toJSON(payload));- }- v2Request.payload = is;- return v2Request;- } catch (IOException e) {- throw new SolrException(SolrException.ErrorCode.SERVER_ERROR, e);- }--+ V2Request v2Request = new V2Request(method, resource, useBinary);+ v2Request.solrParams = params;+ v2Request.payload = payload;+ return v2Request;}}}diff --git a/solr/solrj/src/java/org/apache/solr/common/params/AutoScalingParams.java b/solr/solrj/src/java/org/apache/solr/common/params/AutoScalingParams.javaindex f0c3d779bed..c2782866149 100644--- a/solr/solrj/src/java/org/apache/solr/common/params/AutoScalingParams.java+++ b/solr/solrj/src/java/org/apache/solr/common/params/AutoScalingParams.java@@ -23,6 +23,7 @@ public interface AutoScalingParams {// parametersString DIAGNOSTICS = "diagnostics";+ String SUGGESTIONS = "suggestions";String NAME = "name";String TRIGGER = "trigger";String EVENT = "event";diff --git a/solr/solrj/src/java/org/apache/solr/common/params/SolrParams.java b/solr/solrj/src/java/org/apache/solr/common/params/SolrParams.javaindex dcf5e21170a..130ca3e7e54 100644--- a/solr/solrj/src/java/org/apache/solr/common/params/SolrParams.java+++ b/solr/solrj/src/java/org/apache/solr/common/params/SolrParams.java@@ -31,7 +31,7 @@ import java.util.List;import java.util.Map;import org.apache.solr.client.solrj.util.ClientUtils;-import org.apache.solr.common.MapSerializable;+import org.apache.solr.common.MapWriter;import org.apache.solr.common.SolrException;import org.apache.solr.common.util.NamedList;import org.apache.solr.common.util.SimpleOrderedMap;@@ -41,7 +41,7 @@ import org.apache.solr.common.util.StrUtils;***/-public abstract class SolrParams implements Serializable, MapSerializable {+public abstract class SolrParams implements Serializable, MapWriter {/** returns the String value of a param, or null if not set */public abstract String get(String param);@@ -550,11 +550,17 @@ public abstract class SolrParams implements Serializable, MapSerializable {}@Override- public Map toMap(Map<String, Object> map) {+ public void writeMap(EntryWriter ew) throws IOException {toNamedList().forEach((k, v) -> {if (v == null || "".equals(v)) return;- map.put(k, v);+ try {+ ew.put(k, v);+ } catch (IOException e) {+ throw new RuntimeException("Error serializing", e);+ }});- return map;+}++}diff --git a/solr/solrj/src/resources/apispec/autoscaling.Commands.json b/solr/solrj/src/resources/apispec/autoscaling.Commands.jsonindex 95563ed257f..30ebc7a0fa9 100644--- a/solr/solrj/src/resources/apispec/autoscaling.Commands.json+++ b/solr/solrj/src/resources/apispec/autoscaling.Commands.json@@ -8,7 +8,8 @@"url": {"paths": ["/cluster/autoscaling",- "/cluster/autoscaling/diagnostics"+ "/cluster/autoscaling/diagnostics",+ "/cluster/autoscaling/suggestions"]},"commands": {diff --git a/solr/solrj/src/test/org/apache/solr/client/solrj/cloud/autoscaling/TestPolicy.java b/solr/solrj/src/test/org/apache/solr/client/solrj/cloud/autoscaling/TestPolicy.javaindex 0a21872b9c1..26de13d8464 100644--- a/solr/solrj/src/test/org/apache/solr/client/solrj/cloud/autoscaling/TestPolicy.java+++ b/solr/solrj/src/test/org/apache/solr/client/solrj/cloud/autoscaling/TestPolicy.java@@ -114,7 +114,8 @@ public class TestPolicy extends SolrTestCaseJ4 {if (!node_name.equals(node)) return;Map<String, List<ReplicaInfo>> shardVsReplicaStats = result.computeIfAbsent(collName, k -> new HashMap<>());List<ReplicaInfo> replicaInfos = shardVsReplicaStats.computeIfAbsent(shard, k -> new ArrayList<>());- replicaInfos.add(new ReplicaInfo(replicaName,replicaName, collName, shard, r));+ replicaInfos.add(new ReplicaInfo(replicaName, (String) r.get("core"), collName, shard,+ Replica.Type.get((String) r.get(ZkStateReader.REPLICA_TYPE)), node, r));});});});@@ -273,7 +274,7 @@ public class TestPolicy extends SolrTestCaseJ4 {Policy policy = new Policy((Map<String, Object>) Utils.fromJSONString(autoScalingjson));Policy.Session session = policy.createSession(cloudManagerWithData(dataproviderdata));- SolrRequest op = session.getSuggester(MOVEREPLICA).hint(Hint.SRC_NODE, "127.0.0.1:65427_solr").getOperation();+ SolrRequest op = session.getSuggester(MOVEREPLICA).hint(Hint.SRC_NODE, "127.0.0.1:65427_solr").getSuggestion();assertNotNull(op);assertEquals( "127.0.0.1:65434_solr",op.getParams().get("targetNode") );}@@ -311,21 +312,21 @@ public class TestPolicy extends SolrTestCaseJ4 {Suggester suggester = session.getSuggester(MOVEREPLICA).hint(Hint.SRC_NODE, "node1");- SolrRequest operation = suggester.getOperation();+ SolrRequest operation = suggester.getSuggestion();assertNotNull(operation);assertEquals("node2", operation.getParams().get("targetNode"));session = suggester.getSession();suggester = session.getSuggester(MOVEREPLICA).hint(Hint.SRC_NODE, "node1");- operation = suggester.getOperation();+ operation = suggester.getSuggestion();assertNotNull(operation);assertEquals("node3", operation.getParams().get("targetNode"));session = suggester.getSession();suggester = session.getSuggester(MOVEREPLICA).hint(Hint.SRC_NODE, "node1");- operation = suggester.getOperation();+ operation = suggester.getSuggestion();assertNull(operation);// lets change the policy such that all replicas that were on node1@@ -346,7 +347,7 @@ public class TestPolicy extends SolrTestCaseJ4 {suggester = session.getSuggester(MOVEREPLICA).hint(Hint.SRC_NODE, "node1");- operation = suggester.getOperation();+ operation = suggester.getSuggestion();assertNotNull(operation);assertEquals("node2", operation.getParams().get("targetNode"));assertEquals("r3", operation.getParams().get("replica"));@@ -354,7 +355,7 @@ public class TestPolicy extends SolrTestCaseJ4 {session = suggester.getSession();suggester = session.getSuggester(MOVEREPLICA).hint(Hint.SRC_NODE, "node1");- operation = suggester.getOperation();+ operation = suggester.getSuggestion();assertNotNull(operation);assertEquals("node2", operation.getParams().get("targetNode"));assertEquals("r5", operation.getParams().get("replica"));@@ -362,14 +363,14 @@ public class TestPolicy extends SolrTestCaseJ4 {session = suggester.getSession();suggester = session.getSuggester(MOVEREPLICA).hint(Hint.SRC_NODE, "node1");- operation = suggester.getOperation();+ operation = suggester.getSuggestion();assertEquals("node2", operation.getParams().get("targetNode"));assertEquals("r1", operation.getParams().get("replica"));session = suggester.getSession();suggester = session.getSuggester(MOVEREPLICA).hint(Hint.SRC_NODE, "node1");- operation = suggester.getOperation();+ operation = suggester.getSuggestion();assertNull(operation);// now lets change the policy such that a node can have 2 shard2 replicas@@ -390,7 +391,7 @@ public class TestPolicy extends SolrTestCaseJ4 {suggester = session.getSuggester(MOVEREPLICA).hint(Hint.SRC_NODE, "node1");- operation = suggester.getOperation();+ operation = suggester.getSuggestion();assertNotNull(operation);assertEquals("node2", operation.getParams().get("targetNode"));assertEquals("r3", operation.getParams().get("replica"));@@ -398,7 +399,7 @@ public class TestPolicy extends SolrTestCaseJ4 {session = suggester.getSession();suggester = session.getSuggester(MOVEREPLICA).hint(Hint.SRC_NODE, "node1");- operation = suggester.getOperation();+ operation = suggester.getSuggestion();assertNotNull(operation);assertEquals("node2", operation.getParams().get("targetNode"));assertEquals("r5", operation.getParams().get("replica"));@@ -406,7 +407,7 @@ public class TestPolicy extends SolrTestCaseJ4 {session = suggester.getSession();suggester = session.getSuggester(MOVEREPLICA).hint(Hint.SRC_NODE, "node1");- operation = suggester.getOperation();+ operation = suggester.getSuggestion();assertEquals("node3", operation.getParams().get("targetNode"));assertEquals("r1", operation.getParams().get("replica"));}@@ -424,8 +425,10 @@ public class TestPolicy extends SolrTestCaseJ4 {Object o = l3.get(i);Map m3 = (Map) o;String name = m3.keySet().iterator().next().toString();+ m3 = (Map) m3.get(name);+ Replica.Type type = Replica.Type.get((String) m3.get("type"));l3.set(i, new ReplicaInfo(name,name- ,coll.toString(), shard.toString(), m3));+ , coll.toString(), shard.toString(), type, (String) node, m3));}});@@ -484,7 +487,7 @@ public class TestPolicy extends SolrTestCaseJ4 {.getSuggester(ADDREPLICA).hint(Hint.COLL_SHARD, new Pair("newColl", "shard1")).hint(Hint.REPLICATYPE, Replica.Type.PULL);- SolrRequest op = suggester.getOperation();+ SolrRequest op = suggester.getSuggestion();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"));@@ -493,7 +496,7 @@ public class TestPolicy extends SolrTestCaseJ4 {.getSuggester(ADDREPLICA).hint(Hint.COLL_SHARD, new Pair<>("newColl", "shard2")).hint(Hint.REPLICATYPE, Replica.Type.PULL);- op = suggester.getOperation();+ op = suggester.getSuggestion();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"));@@ -502,7 +505,7 @@ public class TestPolicy extends SolrTestCaseJ4 {.getSuggester(ADDREPLICA).hint(Hint.COLL_SHARD, new Pair("newColl", "shard1")).hint(Hint.REPLICATYPE, Replica.Type.TLOG);- op = suggester.getOperation();+ op = suggester.getSuggestion();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"));@@ -511,7 +514,7 @@ public class TestPolicy extends SolrTestCaseJ4 {.getSuggester(ADDREPLICA).hint(Hint.COLL_SHARD, new Pair("newColl", "shard2")).hint(Hint.REPLICATYPE, Replica.Type.TLOG);- op = suggester.getOperation();+ op = suggester.getSuggestion();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"));@@ -520,7 +523,7 @@ public class TestPolicy extends SolrTestCaseJ4 {.getSuggester(ADDREPLICA).hint(Hint.COLL_SHARD, new Pair<>("newColl", "shard2")).hint(Hint.REPLICATYPE, Replica.Type.TLOG);- op = suggester.getOperation();+ op = suggester.getSuggestion();assertNull("No node should qualify for this" ,op);}@@ -625,7 +628,7 @@ public class TestPolicy extends SolrTestCaseJ4 {.hint(Hint.COLL, "collection1").hint(Hint.COLL, "collection2").hint(Suggester.Hint.SRC_NODE, "node2");- SolrRequest op = suggester.getOperation();+ SolrRequest op = suggester.getSuggestion();assertNotNull(op);assertEquals("collection2", op.getParams().get("collection"));assertEquals("node1", op.getParams().get("targetNode"));@@ -637,7 +640,7 @@ public class TestPolicy extends SolrTestCaseJ4 {.hint(Hint.COLL, "collection1").hint(Hint.COLL, "collection2").hint(Suggester.Hint.SRC_NODE, "node2");- op = suggester.getOperation();+ op = suggester.getSuggestion();assertNotNull(op);assertEquals("collection2", op.getParams().get("collection"));assertEquals("node1", op.getParams().get("targetNode"));@@ -649,7 +652,7 @@ public class TestPolicy extends SolrTestCaseJ4 {.hint(Hint.COLL, "collection1").hint(Hint.COLL, "collection2").hint(Suggester.Hint.SRC_NODE, "node2");- op = suggester.getOperation();+ op = suggester.getSuggestion();assertNull(op);}@@ -685,7 +688,7 @@ public class TestPolicy extends SolrTestCaseJ4 {int countOp = 0;int countNewCollOp = 0;int countNewColl2Op = 0;- while ((op = suggester.getOperation()) != null) {+ while ((op = suggester.getSuggestion()) != null) {countOp++;suggester = suggester.getSession().getSuggester(ADDREPLICA).hint(Hint.REPLICATYPE, Replica.Type.PULL)@@ -710,7 +713,7 @@ public class TestPolicy extends SolrTestCaseJ4 {.hint(Hint.COLL_SHARD, new Pair<>("newColl", "shard2")).hint(Hint.COLL_SHARD, new Pair<>("newColl2", "shard2")).hint(Hint.REPLICATYPE, Replica.Type.TLOG);- while ((op = suggester.getOperation()) != null) {+ while ((op = suggester.getSuggestion()) != null) {countOp++;suggester = suggester.getSession().getSuggester(ADDREPLICA)@@ -821,7 +824,7 @@ public class TestPolicy extends SolrTestCaseJ4 {Suggester suggester = session.getSuggester(ADDREPLICA).hint(Hint.COLL_SHARD, new Pair<>("gettingstarted","r1"));- SolrParams operation = suggester.getOperation().getParams();+ SolrParams operation = suggester.getSuggestion().getParams();assertEquals("node2", operation.get("node"));nodeValues = (Map<String, Map>) Utils.fromJSONString("{" +@@ -834,7 +837,7 @@ public class TestPolicy extends SolrTestCaseJ4 {session = policy.createSession(getSolrCloudManager(nodeValues, clusterState));SolrRequest opReq = session.getSuggester(MOVEREPLICA).hint(Hint.TARGET_NODE, "node5")- .getOperation();+ .getSuggestion();assertNotNull(opReq);assertEquals("node5", opReq.getParams().get("targetNode"));}@@ -938,7 +941,7 @@ public class TestPolicy extends SolrTestCaseJ4 {Suggester suggester = session.getSuggester(ADDREPLICA);SolrRequest op = suggester.hint(Hint.COLL_SHARD, new Pair<>("newColl","shard1"))- .getOperation();+ .getSuggestion();assertNotNull(op);assertEquals("node3", op.getParams().get("node"));session = suggester.getSession();@@ -969,14 +972,14 @@ public class TestPolicy extends SolrTestCaseJ4 {Suggester suggester = session.getSuggester(ADDREPLICA);SolrRequest op = suggester.hint(Hint.COLL_SHARD, new Pair<>("newColl", "shard1"))- .getOperation();+ .getSuggestion();assertNotNull(op);assertEquals("node3", op.getParams().get("node"));suggester = suggester.getSession().getSuggester(ADDREPLICA).hint(Hint.COLL_SHARD, new Pair<>("newColl", "shard1"));- op = suggester.getOperation();+ op = suggester.getSuggestion();assertNotNull(op);assertEquals("node3", op.getParams().get("node"));@@ -984,7 +987,7 @@ public class TestPolicy extends SolrTestCaseJ4 {.getSession().getSuggester(ADDREPLICA).hint(Hint.COLL_SHARD, new Pair<>("newColl", "shard1"));- op = suggester.getOperation();+ op = suggester.getSuggestion();assertNotNull(op);assertEquals("node2", op.getParams().get("node"));}@@ -1006,9 +1009,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 ReplicaInfo("core_node1", "core_node1", "compute_plan_action_test", "shard1", Collections.singletonMap(ZkStateReader.REPLICA_TYPE, Replica.Type.NRT)),- new ReplicaInfo("core_node2", "core_node2", "compute_plan_action_test", "shard1", Collections.singletonMap(ZkStateReader.REPLICA_TYPE, Replica.Type.NRT))- ));+ new ReplicaInfo("core_node1", "core_node1", "compute_plan_action_test", "shard1", Replica.Type.NRT, "127.0.0.1:60089_solr", Collections.emptyMap()),+ new ReplicaInfo("core_node2", "core_node2", "compute_plan_action_test", "shard1", Replica.Type.NRT, "127.0.0.1:60089_solr", Collections.emptyMap())));Map<String, Map<String, Object>> tagsMap = (Map) Utils.fromJSONString("{" +" '127.0.0.1:60099_solr':{" +@@ -1048,7 +1050,7 @@ public class TestPolicy extends SolrTestCaseJ4 {});Suggester suggester = session.getSuggester(MOVEREPLICA).hint(Hint.TARGET_NODE, "127.0.0.1:60099_solr");- SolrRequest op = suggester.getOperation();+ SolrRequest op = suggester.getSuggestion();assertNotNull(op);}@@ -1119,7 +1121,7 @@ public class TestPolicy extends SolrTestCaseJ4 {CollectionAdminRequest.AddReplica op = (CollectionAdminRequest.AddReplica) session.getSuggester(ADDREPLICA)- .hint(Hint.COLL_SHARD, new Pair<>("newColl", "s1")).getOperation();+ .hint(Hint.COLL_SHARD, new Pair<>("newColl", "s1")).getSuggestion();assertNotNull(op);assertEquals("node2", op.getNode());}@@ -1309,10 +1311,10 @@ public class TestPolicy extends SolrTestCaseJ4 {Policy policy = new Policy((Map<String, Object>) Utils.fromJSONString(autoScalingjson));Policy.Session session = policy.createSession(cloudManagerWithData(dataproviderdata));Suggester suggester = session.getSuggester(MOVEREPLICA).hint(Hint.TARGET_NODE, "10.0.0.6:7574_solr");- SolrRequest op = suggester.getOperation();+ SolrRequest op = suggester.getSuggestion();assertNotNull(op);suggester = suggester.getSession().getSuggester(MOVEREPLICA).hint(Hint.TARGET_NODE, "10.0.0.6:7574_solr");- op = suggester.getOperation();+ op = suggester.getSuggestion();assertNull(op);}@@ -1347,11 +1349,95 @@ public class TestPolicy extends SolrTestCaseJ4 {Policy.Session session = policy.createSession(cloudManagerWithData(dataproviderdata));Suggester suggester = session.getSuggester(CollectionParams.CollectionAction.MOVEREPLICA).hint(Hint.TARGET_NODE, "127.0.0.1:51147_solr");- SolrRequest op = suggester.getOperation();+ SolrRequest op = suggester.getSuggestion();log.info("" + op);assertNotNull(op);}-+ public void testReplicaCountSuggestions() {+ String dataproviderdata = "{" ++ " 'liveNodes':[" ++ " '10.0.0.6:7574_solr'," ++ " '10.0.0.6:8983_solr']," ++ " 'replicaInfo':{" ++ " '10.0.0.6:7574_solr':{}," ++ " '10.0.0.6:8983_solr':{'mycoll1':{" ++ " 'shard2':[{'core_node2':{'type':'NRT'}}]," ++ " 'shard1':[{'core_node1':{'type':'NRT'}}]}}}," ++ " 'nodeValues':{" ++ " '10.0.0.6:7574_solr':{" ++ " 'node':'10.0.0.6:7574_solr'," ++ " 'cores':0}," ++ " '10.0.0.6:8983_solr':{" ++ " 'node':'10.0.0.6:8983_solr'," ++ " 'cores':2}}}";+ String autoScalingjson = " { cluster-policy:[" ++ " { cores :'<10', node :'#ANY'}," ++ " { replica :'<2', node:'#ANY'}," ++ " { nodeRole : overseer, replica :0}]," ++ " cluster-preferences :[{ minimize : cores }]}";+ List<Suggester.SuggestionInfo> l = PolicyHelper.getSuggestions(new AutoScalingConfig((Map<String, Object>) Utils.fromJSONString(autoScalingjson)),+ cloudManagerWithData(dataproviderdata));+ assertFalse(l.isEmpty());++ Map m = l.get(0).toMap(new LinkedHashMap<>());+ assertEquals(1l, Utils.getObjectByPath(m, true, "violation/violation/delta"));+ assertEquals("POST", Utils.getObjectByPath(m, true, "operation/method"));+ assertEquals("/c/mycoll1", Utils.getObjectByPath(m, true, "operation/path"));+ assertNotNull(Utils.getObjectByPath(m, false, "operation/command/move-replica"));+ assertEquals("10.0.0.6:7574_solr", Utils.getObjectByPath(m, true, "operation/command/move-replica/targetNode"));+ assertEquals("core_node2", Utils.getObjectByPath(m, true, "operation/command/move-replica/replica"));+ }++ // @Ignore+ public void testFreeDiskSuggestions() {+ String dataproviderdata = "{" ++ " liveNodes:[node1,node2]," ++ " replicaInfo : {" ++ " node1:{}," ++ " node2:{mycoll1:{" ++ " shard1:[{r1:{type:NRT, INDEX.sizeInBytes:900}}]," ++ " shard2:[{r2:{type:NRT, INDEX.sizeInBytes:300}}]," ++ " shard3:[{r3:{type:NRT, INDEX.sizeInBytes:200}}]," ++ " shard4:[{r4:{type:NRT, INDEX.sizeInBytes:100}}]}}}" ++ " nodeValues : {" ++ " node1: { node : node1 , cores:0 , freedisk : 2000}," ++ " node2: { node : node2 , cores:4 , freedisk : 500}}}";+++ String autoScalingjson = " { cluster-policy:[" ++// " { cores :'<10', node :'#ANY'}," ++// " { replica :'<2', shard:'#EACH' node:'#ANY'}," ++ " { replica :'0', freedisk:'<1000'}," ++ " { nodeRole : overseer, replica :0}]," ++ " cluster-preferences :[{ minimize : cores, precision : 2 }]}";+ AutoScalingConfig cfg = new AutoScalingConfig((Map<String, Object>) Utils.fromJSONString(autoScalingjson));+ List<Violation> violations = cfg.getPolicy().createSession(cloudManagerWithData(dataproviderdata)).getViolations();+ assertEquals(1, violations.size());+ assertEquals(4, violations.get(0).getViolatingReplicas().size());+ List<Suggester.SuggestionInfo> l = PolicyHelper.getSuggestions(cfg, cloudManagerWithData(dataproviderdata));+ assertEquals(3, l.size());+ Map m = l.get(0).toMap(new LinkedHashMap<>());+ assertEquals("r4", Utils.getObjectByPath(m, true, "operation/command/move-replica/replica"));+ assertEquals("node1", Utils.getObjectByPath(m, true, "operation/command/move-replica/targetNode"));++ m = l.get(1).toMap(new LinkedHashMap<>());+ assertEquals("r3", Utils.getObjectByPath(m, true, "operation/command/move-replica/replica"));+ assertEquals("node1", Utils.getObjectByPath(m, true, "operation/command/move-replica/targetNode"));++ m = l.get(2).toMap(new LinkedHashMap<>());+ assertEquals("r2", Utils.getObjectByPath(m, true, "operation/command/move-replica/replica"));+ assertEquals("node1", Utils.getObjectByPath(m, true, "operation/command/move-replica/targetNode"));++// System.out.println(Utils.toJSONString(l.get(0)));+// Map m = l.get(0).toMap(new LinkedHashMap<>());+ /*assertEquals(1l,Utils.getObjectByPath(m,true,"violation/violation/delta"));+ assertEquals("POST",Utils.getObjectByPath(m,true,"operation/method"));+ assertEquals("/c/mycoll1",Utils.getObjectByPath(m,true,"operation/path"));+ assertNotNull(Utils.getObjectByPath(m,false,"operation/command/move-replica"));+ assertEquals("10.0.0.6:7574_solr",Utils.getObjectByPath(m,true,"operation/command/move-replica/targetNode"));+ assertEquals("core_node2",Utils.getObjectByPath(m,true,"operation/command/move-replica/replica"));*/++ }}