Apache Lucene open-source search software
SOLR-10339: New set-trigger and remove-trigger APIs for autoscaling
Shalin Shekhar Mangare4b3df41a9b1
diff --git a/solr/CHANGES.txt b/solr/CHANGES.txtindex e74e4ae3be0..c839a072265 100644--- a/solr/CHANGES.txt+++ b/solr/CHANGES.txt@@ -61,6 +61,8 @@ New Features* SOLR-10292: Adds CartesianProductStream which turns a single tuple with a multi-valued field into Ntuples, one for each value in the multi-valued field. (Dennis Gove)+* SOLR-10339: New set-trigger and remove-trigger APIs for autoscaling. (shalin)+Bug Fixes----------------------* SOLR-9262: Connection and read timeouts are being ignored by UpdateShardHandler after SOLR-4509.diff --git a/solr/core/src/java/org/apache/solr/cloud/ZkController.java b/solr/core/src/java/org/apache/solr/cloud/ZkController.javaindex 69a77f94820..d7072e75057 100644--- a/solr/core/src/java/org/apache/solr/cloud/ZkController.java+++ b/solr/core/src/java/org/apache/solr/cloud/ZkController.java@@ -666,6 +666,7 @@ public class ZkController {byte[] emptyJson = "{}".getBytes(StandardCharsets.UTF_8);cmdExecutor.ensureExists(ZkStateReader.CLUSTER_STATE, emptyJson, CreateMode.PERSISTENT, zkClient);cmdExecutor.ensureExists(ZkStateReader.SOLR_SECURITY_CONF_PATH, emptyJson, CreateMode.PERSISTENT, zkClient);+ cmdExecutor.ensureExists(ZkStateReader.SOLR_AUTOSCALING_CONF_PATH, emptyJson, CreateMode.PERSISTENT, zkClient);}private void init(CurrentCoreDescriptorProvider registerOnReconnect) {diff --git a/solr/core/src/java/org/apache/solr/cloud/autoscaling/AutoScaling.java b/solr/core/src/java/org/apache/solr/cloud/autoscaling/AutoScaling.javanew file mode 100644index 00000000000..ae11e78c6be--- /dev/null+++ b/solr/core/src/java/org/apache/solr/cloud/autoscaling/AutoScaling.java@@ -0,0 +1,32 @@+/*+ * 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;++public class AutoScaling {++ public enum EventType {+ NODEADDED,+ NODELOST,+ REPLICALOST,+ MANUAL,+ SCHEDULED,+ SEARCHRATE,+ INDEXRATE+ }++}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.javanew file mode 100644index 00000000000..73508c34be7--- /dev/null+++ b/solr/core/src/java/org/apache/solr/cloud/autoscaling/AutoScalingHandler.java@@ -0,0 +1,221 @@+/*+ * 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.lang.invoke.MethodHandles;+import java.util.ArrayList;+import java.util.Collection;+import java.util.HashMap;+import java.util.List;+import java.util.Locale;+import java.util.Map;+import java.util.concurrent.TimeUnit;++import org.apache.solr.api.Api;+import org.apache.solr.api.ApiBag;+import org.apache.solr.common.SolrException;+import org.apache.solr.common.cloud.ZkNodeProps;+import org.apache.solr.common.cloud.ZkStateReader;+import org.apache.solr.common.util.Utils;+import org.apache.solr.core.CoreContainer;+import org.apache.solr.handler.RequestHandlerBase;+import org.apache.solr.request.SolrQueryRequest;+import org.apache.solr.response.SolrQueryResponse;+import org.apache.solr.security.AuthorizationContext;+import org.apache.solr.security.PermissionNameProvider;+import org.apache.solr.util.CommandOperation;+import org.apache.zookeeper.KeeperException;+import org.apache.zookeeper.data.Stat;+import org.slf4j.Logger;+import org.slf4j.LoggerFactory;++import static org.apache.solr.common.cloud.ZkStateReader.SOLR_AUTOSCALING_CONF_PATH;++/**+ * Handler for /cluster/autoscaling+ */+public class AutoScalingHandler extends RequestHandlerBase implements PermissionNameProvider {+ public static final String HANDLER_PATH = "/admin/autoscaling";+ private static final Logger log = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());+ protected final CoreContainer container;+ private final List<Map<String, String>> DEFAULT_ACTIONS = new ArrayList<>(3);++ public AutoScalingHandler(CoreContainer container) {+ this.container = container;+ Map<String, String> map = new HashMap<>(2);+ map.put("name", "compute_plan");+ map.put("class", "solr.ComputePlanAction");+ DEFAULT_ACTIONS.add(map);+ map = new HashMap<>(2);+ map.put("name", "execute_plan");+ map.put("class", "solr.ExecutePlanAction");+ DEFAULT_ACTIONS.add(map);+ map = new HashMap<>(2);+ map.put("name", "log_plan");+ map.put("class", "solr.LogPlanAction");+ DEFAULT_ACTIONS.add(map);+ }++ @Override+ public void handleRequestBody(SolrQueryRequest req, SolrQueryResponse rsp) throws Exception {+ if (req.getContentStreams() == null) {+ throw new SolrException(SolrException.ErrorCode.BAD_REQUEST, "No contentStream");+ }+ List<CommandOperation> ops = CommandOperation.readCommands(req.getContentStreams(), rsp);+ if (ops == null) {+ // errors have already been added to the response so there's nothing left to do+ return;+ }+ for (CommandOperation op : ops) {+ switch (op.name) {+ case "set-trigger":+ handleSetTrigger(req, rsp, op);+ break;+ case "remove-trigger":+ handleRemoveTrigger(req, rsp, op);+ }+ }+ }++ private void handleSetTrigger(SolrQueryRequest req, SolrQueryResponse rsp, CommandOperation op) throws KeeperException, InterruptedException {+ String triggerName = op.getStr("name");++ if (triggerName == null || triggerName.trim().length() == 0) {+ throw new SolrException(SolrException.ErrorCode.BAD_REQUEST, "The trigger name cannot be null or empty");+ }++ String eventTypeStr = op.getStr("event");+ if (eventTypeStr == null || eventTypeStr.trim().length() == 0) {+ throw new SolrException(SolrException.ErrorCode.BAD_REQUEST, "The event type cannot be null or empty in trigger: " + triggerName);+ }+ AutoScaling.EventType eventType = AutoScaling.EventType.valueOf(eventTypeStr.trim().toUpperCase(Locale.ROOT));++ String waitForStr = op.getStr("waitFor", null);+ if (waitForStr != null) {+ char c = waitForStr.charAt(waitForStr.length() - 1);+ long waitForValue = Long.parseLong(waitForStr.substring(0, waitForStr.length() - 1));+ int seconds;+ switch (c) {+ case 'h':+ seconds = (int) TimeUnit.HOURS.toSeconds(waitForValue);+ break;+ case 'm':+ seconds = (int) TimeUnit.MINUTES.toSeconds(waitForValue);+ break;+ case 's':+ seconds = (int) waitForValue;+ break;+ default:+ throw new SolrException(SolrException.ErrorCode.BAD_REQUEST, "Invalid 'waitFor' value in trigger: " + triggerName);+ }+ op.getDataMap().put("waitFor", seconds);+ }++ Integer lowerBound = op.getInt("lowerBound", null);+ Integer upperBound = op.getInt("upperBound", null);++ List<Map<String, String>> actions = (List<Map<String, String>>) op.getVal("actions");+ if (actions == null) {+ actions = DEFAULT_ACTIONS;+ }++ // validate that we can load all the actions+ // todo nocommit -- what about MemClassLoader?+ for (Map<String, String> action : actions) {+ if (!action.containsKey("name") || !action.containsKey("class")) {+ throw new SolrException(SolrException.ErrorCode.BAD_REQUEST, "No 'name' or 'class' specified for action: " + action);+ }+ String klass = action.get("class");+ try {+ container.getResourceLoader().findClass(klass, TriggerAction.class);+ } catch (Exception e) {+ throw new SolrException(SolrException.ErrorCode.BAD_REQUEST, "Error trying to find Action: " + klass, e);+ }+ }++ zkSetTrigger(container.getZkController().getZkStateReader(), triggerName, op.getValuesExcluding("name"));+ rsp.getValues().add("result", "success");+ }++ private void handleRemoveTrigger(SolrQueryRequest req, SolrQueryResponse rsp, CommandOperation op) throws KeeperException, InterruptedException {+ String triggerName = op.getStr("name");++ if (triggerName == null || triggerName.trim().length() == 0) {+ throw new SolrException(SolrException.ErrorCode.BAD_REQUEST, "The trigger name cannot be null or empty");+ }+ Map<String, Object> autoScalingConf = zkReadAutoScalingConf(container.getZkController().getZkStateReader());+ Map<String, Object> triggers = (Map<String, Object>) autoScalingConf.get("triggers");+ if (triggers == null || !triggers.containsKey(triggerName)) {+ throw new SolrException(SolrException.ErrorCode.BAD_REQUEST, "No trigger exists with name: " + triggerName);+ }+ zkSetTrigger(container.getZkController().getZkStateReader(), triggerName, null);+ rsp.getValues().add("result", "success");+ }++ private void zkSetTrigger(ZkStateReader reader, String triggerName, Map<String, Object> triggerProperties) throws KeeperException, InterruptedException {+ while (true) {+ Stat stat = new Stat();+ ZkNodeProps loaded = null;+ byte[] data = reader.getZkClient().getData(SOLR_AUTOSCALING_CONF_PATH, null, stat, true);+ loaded = ZkNodeProps.load(data);+ Map<String, Object> triggers = (Map<String, Object>) loaded.get("triggers");+ if (triggers == null) triggers = new HashMap<>(1);+ if (triggerProperties != null) {+ triggers.put(triggerName, triggerProperties);+ } else {+ triggers.remove(triggerName);+ }+ loaded = loaded.plus("triggers", triggers);+ try {+ reader.getZkClient().setData(SOLR_AUTOSCALING_CONF_PATH, Utils.toJSON(loaded), stat.getVersion(), true);+ } catch (KeeperException.BadVersionException bve) {+ // somebody else has changed the configuration so we must retry+ continue;+ }+ break;+ }+ }++ private Map<String, Object> zkReadAutoScalingConf(ZkStateReader reader) throws KeeperException, InterruptedException {+ byte[] data = reader.getZkClient().getData(SOLR_AUTOSCALING_CONF_PATH, null, null, true);+ ZkNodeProps loaded = ZkNodeProps.load(data);+ return loaded.getProperties();+ }++ @Override+ public String getDescription() {+ return "A handler for autoscaling configuration";+ }++ @Override+ public Name getPermissionName(AuthorizationContext request) {+ switch (request.getHttpMethod()) {+ case "GET":+ return Name.AUTOSCALING_READ_PERM;+ case "POST":+ return Name.AUTOSCALING_WRITE_PERM;+ default:+ return null;+ }+ }++ @Override+ public Collection<Api> getApis() {+ return ApiBag.wrapRequestHandlers(this, "scaling.Commands");+ }+}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.javanew file mode 100644index 00000000000..79366d1cfbe--- /dev/null+++ b/solr/core/src/java/org/apache/solr/cloud/autoscaling/ComputePlanAction.java@@ -0,0 +1,36 @@+/*+ * 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.Map;++/**+ * todo nocommit+ */+public class ComputePlanAction implements TriggerAction {+ @Override+ public void close() throws IOException {++ }++ @Override+ public void init(Map<String, String> args) {++ }+}diff --git a/solr/core/src/java/org/apache/solr/cloud/autoscaling/ExecutePlanAction.java b/solr/core/src/java/org/apache/solr/cloud/autoscaling/ExecutePlanAction.javanew file mode 100644index 00000000000..454530f7f3e--- /dev/null+++ b/solr/core/src/java/org/apache/solr/cloud/autoscaling/ExecutePlanAction.java@@ -0,0 +1,36 @@+/*+ * 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.Map;++/**+ * todo nocommit+ */+public class ExecutePlanAction implements TriggerAction {+ @Override+ public void close() throws IOException {++ }++ @Override+ public void init(Map<String, String> args) {++ }+}diff --git a/solr/core/src/java/org/apache/solr/cloud/autoscaling/LogPlanAction.java b/solr/core/src/java/org/apache/solr/cloud/autoscaling/LogPlanAction.javanew file mode 100644index 00000000000..3a92eed7c3e--- /dev/null+++ b/solr/core/src/java/org/apache/solr/cloud/autoscaling/LogPlanAction.java@@ -0,0 +1,36 @@+/*+ * 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.Map;++/**+ * todo nocommit+ */+public class LogPlanAction implements TriggerAction {+ @Override+ public void close() throws IOException {++ }++ @Override+ public void init(Map<String, String> args) {++ }+}diff --git a/solr/core/src/java/org/apache/solr/cloud/autoscaling/TriggerAction.java b/solr/core/src/java/org/apache/solr/cloud/autoscaling/TriggerAction.javanew file mode 100644index 00000000000..7765ac25601--- /dev/null+++ b/solr/core/src/java/org/apache/solr/cloud/autoscaling/TriggerAction.java@@ -0,0 +1,29 @@+/*+ * 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.Closeable;++import org.apache.solr.util.plugin.MapInitializedPlugin;++/**+ * Interface for actions performed in response to a trigger being activated+ */+public interface TriggerAction extends MapInitializedPlugin, Closeable {+ // todo nocommit+}diff --git a/solr/core/src/java/org/apache/solr/core/CoreContainer.java b/solr/core/src/java/org/apache/solr/core/CoreContainer.javaindex 9e22f91b49c..7efdc29730f 100644--- a/solr/core/src/java/org/apache/solr/core/CoreContainer.java+++ b/solr/core/src/java/org/apache/solr/core/CoreContainer.java@@ -49,6 +49,7 @@ import org.apache.solr.client.solrj.impl.SolrHttpClientContextBuilder;import org.apache.solr.client.solrj.impl.SolrHttpClientContextBuilder.AuthSchemeRegistryProvider;import org.apache.solr.client.solrj.impl.SolrHttpClientContextBuilder.CredentialsProviderProvider;import org.apache.solr.client.solrj.util.SolrIdentifierValidator;+import org.apache.solr.cloud.autoscaling.AutoScalingHandler;import org.apache.solr.cloud.CloudDescriptor;import org.apache.solr.cloud.Overseer;import org.apache.solr.cloud.ZkController;@@ -179,6 +180,8 @@ public class CoreContainer {protected MetricsCollectorHandler metricsCollectorHandler;+ protected AutoScalingHandler autoScalingHandler;+private enum CoreInitFailedAction { fromleader, none }/**@@ -516,6 +519,9 @@ public class CoreContainer {metricsCollectorHandler = createHandler(MetricsCollectorHandler.HANDLER_PATH, MetricsCollectorHandler.class.getName(), MetricsCollectorHandler.class);// may want to add some configuration here in the futuremetricsCollectorHandler.init(null);++ autoScalingHandler = createHandler(AutoScalingHandler.HANDLER_PATH, AutoScalingHandler.class.getName(), AutoScalingHandler.class);+containerHandlers.put(AUTHZ_PATH, securityConfHandler);securityConfHandler.initializeMetrics(metricManager, SolrInfoMBean.Group.node.toString(), AUTHZ_PATH);containerHandlers.put(AUTHC_PATH, securityConfHandler);diff --git a/solr/core/src/java/org/apache/solr/core/SolrResourceLoader.java b/solr/core/src/java/org/apache/solr/core/SolrResourceLoader.javaindex d310ff23c71..d08646a3348 100644--- a/solr/core/src/java/org/apache/solr/core/SolrResourceLoader.java+++ b/solr/core/src/java/org/apache/solr/core/SolrResourceLoader.java@@ -90,7 +90,8 @@ public class SolrResourceLoader implements ResourceLoader,Closeablestatic final String[] packages = {"", "analysis.", "schema.", "handler.", "search.", "update.", "core.", "response.", "request.","update.processor.", "util.", "spelling.", "handler.component.", "handler.dataimport.",- "spelling.suggest.", "spelling.suggest.fst.", "rest.schema.analysis.", "security.","handler.admin."+ "spelling.suggest.", "spelling.suggest.fst.", "rest.schema.analysis.", "security.","handler.admin.",+ "cloud.autoscaling."};private static final java.lang.String SOLR_CORE_NAME = "solr.core.name";private static Set<String> loggedOnce = new ConcurrentSkipListSet<>();diff --git a/solr/core/src/java/org/apache/solr/security/PermissionNameProvider.java b/solr/core/src/java/org/apache/solr/security/PermissionNameProvider.javaindex 425be38360f..92210587b08 100644--- a/solr/core/src/java/org/apache/solr/security/PermissionNameProvider.java+++ b/solr/core/src/java/org/apache/solr/security/PermissionNameProvider.java@@ -47,6 +47,8 @@ public interface PermissionNameProvider {SECURITY_EDIT_PERM("security-edit", null),SECURITY_READ_PERM("security-read", null),METRICS_READ_PERM("metrics-read", null),+ AUTOSCALING_READ_PERM("autoscaling-read", null),+ AUTOSCALING_WRITE_PERM("autoscaling-write", null),ALL("all", unmodifiableSet(new HashSet<>(asList("*", null))));final String name;diff --git a/solr/core/src/resources/apispec/autoscaling.Commands.json b/solr/core/src/resources/apispec/autoscaling.Commands.jsonnew file mode 100644index 00000000000..b374eacfa92--- /dev/null+++ b/solr/core/src/resources/apispec/autoscaling.Commands.json@@ -0,0 +1,65 @@+{+ "documentation": "TODO NOCOMMIT",+ "description": "The Scaling API provides API for adding cluster level scaling rules, triggers and event listeners",+ "methods": [+ "POST"+ ],+ "url": {+ "paths": [+ "/cluster/autoscaling"+ ]+ },+ "commands": {+ "set-trigger": {+ "type":"object",+ "description": "The set-trigger command allows you to add and update triggers on various system metrics",+ "properties": {+ "name": {+ "type": "string",+ "description": "The name of the trigger"+ },+ "event" : {+ "type" : "string",+ "description" : "The event type on which to set a trigger"+ },+ "waitFor" : {+ "type" : "string",+ "description" : "The amount of time to wait after the trigger condition is satisfied before trigger is activated"+ },+ "lowerBound" : {+ "type" : "number",+ "description" : "The lower bound of the condition below which the trigger is activated"+ },+ "upperBound" : {+ "type" : "number",+ "description" : "The upper bound of the condition below which the trigger is activated"+ },+ "enabled" : {+ "type" : "boolean",+ "description" : "The state of the trigger"+ },+ "actions" : {+ "type" : "array",+ "description" : "The actions to be performed in sequence when the trigger is activated",+ "items": {+ "type": "object"+ }+ }+ },+ "required": [+ "name",+ "event"+ ]+ },+ "remove-trigger": {+ "description": "Remove a trigger",+ "type":"object",+ "properties" : {+ "name" : {+ "type" : "string",+ "description" : "The name of the trigger to be removed"+ }+ }+ }+ }+}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.javanew file mode 100644index 00000000000..9a1eb0175bf--- /dev/null+++ b/solr/core/src/test/org/apache/solr/cloud/autoscaling/AutoScalingHandlerTest.java@@ -0,0 +1,132 @@+/*+ * 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.Collection;+import java.util.Collections;+import java.util.Map;++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.impl.CloudSolrClient;+import org.apache.solr.cloud.SolrCloudTestCase;+import org.apache.solr.common.cloud.ZkNodeProps;+import org.apache.solr.common.cloud.ZkStateReader;+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.NamedList;+import org.junit.BeforeClass;+import org.junit.Test;++/**+ * Test for AutoScalingHandler+ */+public class AutoScalingHandlerTest extends SolrCloudTestCase {+ @BeforeClass+ public static void setupCluster() throws Exception {+ configureCluster(2)+ .addConfig("conf", configset("cloud-minimal"))+ .configure();+ }++ @Test+ public void test() throws Exception {+ CloudSolrClient solrClient = cluster.getSolrClient();+ // todo nocommit -- add testing for the v2 path+ // String path = random().nextBoolean() ? "/admin/autoscaling" : "/v2/cluster/autoscaling";+ String path = "/admin/autoscaling";+ String addTriggerCommand = "{\n" ++ "\t\"set-trigger\" : {\n" ++ "\t\t\"name\" : \"node_lost_trigger\",\n" ++ "\t\t\"event\" : \"nodeLost\",\n" ++ "\t\t\"waitFor\" : \"10m\",\n" ++ "\t\t\"enabled\" : \"true\",\n" ++ "\t\t\"actions\" : [\n" ++ "\t\t\t{\n" ++ "\t\t\t\t\"name\" : \"compute_plan\",\n" ++ "\t\t\t\t\"class\" : \"solr.ComputePlanAction\"\n" ++ "\t\t\t},\n" ++ "\t\t\t{\n" ++ "\t\t\t\t\"name\" : \"execute_plan\",\n" ++ "\t\t\t\t\"class\" : \"solr.ExecutePlanAction\"\n" ++ "\t\t\t},\n" ++ "\t\t\t{\n" ++ "\t\t\t\t\"name\" : \"log_plan\",\n" ++ "\t\t\t\t\"class\" : \"solr.LogPlanAction\",\n" ++ "\t\t\t\t\"collection\" : \".system\"\n" ++ "\t\t\t}\n" ++ "\t\t]\n" ++ "\t}\n" ++ "}";+ SolrRequest req = new AutoScalingRequest(SolrRequest.METHOD.POST, path, addTriggerCommand);++ NamedList<Object> response = solrClient.request(req);+ assertEquals(response.get("result").toString(), "success");++ byte[] data = zkClient().getData(ZkStateReader.SOLR_AUTOSCALING_CONF_PATH, null, null, true);+ ZkNodeProps loaded = ZkNodeProps.load(data);+ Map<String, Object> triggers = (Map<String, Object>) loaded.get("triggers");+ assertNotNull(triggers);+ assertEquals(1, triggers.size());+ assertTrue(triggers.containsKey("node_lost_trigger"));+ Map<String, Object> nodeLostTrigger = (Map<String, Object>) triggers.get("node_lost_trigger");+ assertEquals(4, nodeLostTrigger.size());+ assertEquals("600", nodeLostTrigger.get("waitFor").toString());++ String removeTriggerCommand = "{\n" ++ "\t\"remove-trigger\" : {\n" ++ "\t\t\"name\" : \"node_lost_trigger\"\n" ++ "\t}\n" ++ "}";+ req = new AutoScalingRequest(SolrRequest.METHOD.POST, path, removeTriggerCommand);+ response = solrClient.request(req);+ assertEquals(response.get("result").toString(), "success");+ data = zkClient().getData(ZkStateReader.SOLR_AUTOSCALING_CONF_PATH, null, null, true);+ loaded = ZkNodeProps.load(data);+ triggers = (Map<String, Object>) loaded.get("triggers");+ assertNotNull(triggers);+ assertEquals(0, triggers.size());+ }++ static class AutoScalingRequest extends SolrRequest {+ protected final String message;++ public AutoScalingRequest(METHOD m, String path, String message) {+ super(m, path);+ this.message = message;+ }++ @Override+ public SolrParams getParams() {+ return null;+ }++ @Override+ public Collection<ContentStream> getContentStreams() throws IOException {+ return Collections.singletonList(new ContentStreamBase.StringStream(message));+ }++ @Override+ protected SolrResponse createResponse(SolrClient client) {+ return null;+ }+ }+}diff --git a/solr/solrj/src/java/org/apache/solr/client/solrj/impl/CloudSolrClient.java b/solr/solrj/src/java/org/apache/solr/client/solrj/impl/CloudSolrClient.javaindex 4c6dd51a781..2ded78543fc 100644--- a/solr/solrj/src/java/org/apache/solr/client/solrj/impl/CloudSolrClient.java+++ b/solr/solrj/src/java/org/apache/solr/client/solrj/impl/CloudSolrClient.java@@ -84,8 +84,8 @@ import org.slf4j.Logger;import org.slf4j.LoggerFactory;import org.slf4j.MDC;-import static org.apache.solr.common.params.CommonParams.ADMIN_PATHS;import static org.apache.solr.common.params.CommonParams.ID;+import static org.apache.solr.common.params.CommonParams.ADMIN_PATHS;/*** SolrJ client class to communicate with SolrCloud.diff --git a/solr/solrj/src/java/org/apache/solr/common/cloud/ZkStateReader.java b/solr/solrj/src/java/org/apache/solr/common/cloud/ZkStateReader.javaindex 51b4b59d806..af3dc83b677 100644--- a/solr/solrj/src/java/org/apache/solr/common/cloud/ZkStateReader.java+++ b/solr/solrj/src/java/org/apache/solr/common/cloud/ZkStateReader.java@@ -91,6 +91,7 @@ public class ZkStateReader implements Closeable {public static final String CLUSTER_PROPS = "/clusterprops.json";public static final String REJOIN_AT_HEAD_PROP = "rejoinAtHead";public static final String SOLR_SECURITY_CONF_PATH = "/security.json";+ public static final String SOLR_AUTOSCALING_CONF_PATH = "/autoscaling.json";public static final String REPLICATION_FACTOR = "replicationFactor";public static final String MAX_SHARDS_PER_NODE = "maxShardsPerNode";diff --git a/solr/solrj/src/java/org/apache/solr/common/params/CommonParams.java b/solr/solrj/src/java/org/apache/solr/common/params/CommonParams.javaindex c3a011c3f21..efb0ac16d0d 100644--- a/solr/solrj/src/java/org/apache/solr/common/params/CommonParams.java+++ b/solr/solrj/src/java/org/apache/solr/common/params/CommonParams.java@@ -181,6 +181,7 @@ public interface CommonParams {String AUTHC_PATH = "/admin/authentication";String ZK_PATH = "/admin/zookeeper";String METRICS_PATH = "/admin/metrics";+ String AUTOSCALING_PATH = "/admin/autoscaling";Set<String> ADMIN_PATHS = new HashSet<>(Arrays.asList(CORES_HANDLER_PATH,@@ -189,6 +190,7 @@ public interface CommonParams {AUTHC_PATH,AUTHZ_PATH,METRICS_PATH,+ AUTOSCALING_PATH,"/____v2/cluster/security/authentication","/____v2/cluster/security/authorization"));