Apache Solr open-source search software
SOLR-10745: Reliably create nodeLost / nodeAdded events.
Andrzej Bialecki8bc7c47152e0
diff --git a/solr/core/src/java/org/apache/solr/cloud/ZkController.java b/solr/core/src/java/org/apache/solr/cloud/ZkController.javaindex dc7605ab310..54514ba320a 100644--- a/solr/core/src/java/org/apache/solr/cloud/ZkController.java+++ b/solr/core/src/java/org/apache/solr/cloud/ZkController.java@@ -49,29 +49,13 @@ import org.apache.commons.lang.StringUtils;import org.apache.solr.client.solrj.impl.HttpSolrClient;import org.apache.solr.client.solrj.impl.HttpSolrClient.Builder;import org.apache.solr.client.solrj.request.CoreAdminRequest.WaitForState;+import org.apache.solr.cloud.autoscaling.AutoScaling;+import org.apache.solr.cloud.autoscaling.AutoScalingConfig;import org.apache.solr.cloud.overseer.OverseerAction;import org.apache.solr.cloud.overseer.SliceMutator;import org.apache.solr.common.SolrException;import org.apache.solr.common.SolrException.ErrorCode;-import org.apache.solr.common.cloud.BeforeReconnect;-import org.apache.solr.common.cloud.ClusterState;-import org.apache.solr.common.cloud.ClusterStateUtil;-import org.apache.solr.common.cloud.DefaultConnectionStrategy;-import org.apache.solr.common.cloud.DefaultZkACLProvider;-import org.apache.solr.common.cloud.DefaultZkCredentialsProvider;-import org.apache.solr.common.cloud.DocCollection;-import org.apache.solr.common.cloud.OnReconnect;-import org.apache.solr.common.cloud.Replica;-import org.apache.solr.common.cloud.Slice;-import org.apache.solr.common.cloud.SolrZkClient;-import org.apache.solr.common.cloud.ZkACLProvider;-import org.apache.solr.common.cloud.ZkCmdExecutor;-import org.apache.solr.common.cloud.ZkConfigManager;-import org.apache.solr.common.cloud.ZkCoreNodeProps;-import org.apache.solr.common.cloud.ZkCredentialsProvider;-import org.apache.solr.common.cloud.ZkNodeProps;-import org.apache.solr.common.cloud.ZkStateReader;-import org.apache.solr.common.cloud.ZooKeeperException;+import org.apache.solr.common.cloud.*;import org.apache.solr.common.params.CollectionParams;import org.apache.solr.common.params.CommonParams;import org.apache.solr.common.params.SolrParams;@@ -575,6 +559,16 @@ public class ZkController {return zkStateReader.getClusterState();}+ /**+ *+ * @return current configuration from <code>autoscaling.json</code>. NOTE:+ * this data is retrieved from ZK on each call.+ */+ public AutoScalingConfig getAutoScalingConfig() throws KeeperException, InterruptedException {+ Map<String, Object> jsonMap = zkClient.getJson(ZkStateReader.SOLR_AUTOSCALING_CONF_PATH, true);+ return new AutoScalingConfig(jsonMap);+ }+/*** Returns config file data (in bytes)*/@@ -666,6 +660,8 @@ public class ZkController {cmdExecutor.ensureExists(ZkStateReader.ALIASES, zkClient);cmdExecutor.ensureExists(ZkStateReader.SOLR_AUTOSCALING_EVENTS_PATH, zkClient);cmdExecutor.ensureExists(ZkStateReader.SOLR_AUTOSCALING_TRIGGER_STATE_PATH, zkClient);+ cmdExecutor.ensureExists(ZkStateReader.SOLR_AUTOSCALING_NODE_ADDED_PATH, zkClient);+ cmdExecutor.ensureExists(ZkStateReader.SOLR_AUTOSCALING_NODE_LOST_PATH, zkClient);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);@@ -680,6 +676,7 @@ public class ZkController {this.baseURL = zkStateReader.getBaseUrlForNodeName(this.nodeName);checkForExistingEphemeralNode();+ registerLiveNodesListener();// start the overseer first as following code may need it's processingif (!zkRunOnly) {@@ -750,6 +747,53 @@ public class ZkController {}}+ private void registerLiveNodesListener() {+ // this listener is used for generating nodeLost events, so we check only if+ // some nodes went missing compared to last state+ LiveNodesListener listener = (oldNodes, newNodes) -> {+ oldNodes.removeAll(newNodes);+ if (oldNodes.isEmpty()) { // only added nodes+ return;+ }+ if (isClosed) {+ return;+ }+ // if this node is in the top three then attempt to create nodeLost message+ int i = 0;+ for (String n : newNodes) {+ if (n.equals(getNodeName())) {+ break;+ }+ if (i > 2) {+ return; // this node is not in the top three+ }+ i++;+ }++ // retrieve current trigger config - if there are no nodeLost triggers+ // then don't create markers+ boolean createNodes = false;+ try {+ createNodes = getAutoScalingConfig().hasTriggerForEvents(AutoScaling.EventType.NODELOST);+ } catch (KeeperException | InterruptedException e1) {+ log.warn("Unable to read autoscaling.json", e1);+ }+ if (createNodes) {+ for (String n : oldNodes) {+ String path = ZkStateReader.SOLR_AUTOSCALING_NODE_LOST_PATH + "/" + n;+ try {+ zkClient.create(path, null, CreateMode.PERSISTENT, true);+ } catch (KeeperException.NodeExistsException e) {+ // someone else already created this node - ignore+ } catch (KeeperException | InterruptedException e1) {+ log.warn("Unable to register nodeLost path for " + n, e1);+ }+ }+ }+ };+ zkStateReader.registerLiveNodesListener(listener);+ }+public void publishAndWaitForDownStates() throws KeeperException,InterruptedException {@@ -824,8 +868,18 @@ public class ZkController {}String nodeName = getNodeName();String nodePath = ZkStateReader.LIVE_NODES_ZKNODE + "/" + nodeName;+ String nodeAddedPath = ZkStateReader.SOLR_AUTOSCALING_NODE_ADDED_PATH + "/" + nodeName;log.info("Register node as live in ZooKeeper:" + nodePath);- zkClient.makePath(nodePath, CreateMode.EPHEMERAL, true);+ List<Op> ops = new ArrayList<>(2);+ ops.add(Op.create(nodePath, null, zkClient.getZkACLProvider().getACLsToAdd(nodePath), CreateMode.EPHEMERAL));+ // if there are nodeAdded triggers don't create nodeAdded markers+ boolean createMarkerNode = getAutoScalingConfig().hasTriggerForEvents(AutoScaling.EventType.NODEADDED);+ if (createMarkerNode && !zkClient.exists(nodeAddedPath, true)) {+ // use EPHEMERAL so that it disappears if this node goes down+ // and no other action is taken+ ops.add(Op.create(nodeAddedPath, null, zkClient.getZkACLProvider().getACLsToAdd(nodeAddedPath), CreateMode.EPHEMERAL));+ }+ zkClient.multi(ops, true);}public String getNodeName() {diff --git a/solr/core/src/java/org/apache/solr/cloud/autoscaling/AutoScalingConfig.java b/solr/core/src/java/org/apache/solr/cloud/autoscaling/AutoScalingConfig.javanew file mode 100644index 00000000000..fb812fec4ca--- /dev/null+++ b/solr/core/src/java/org/apache/solr/cloud/autoscaling/AutoScalingConfig.java@@ -0,0 +1,146 @@+/*+ * 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.util.Collections;+import java.util.HashMap;+import java.util.List;+import java.util.Locale;+import java.util.Map;++import org.apache.solr.common.params.AutoScalingParams;+import org.apache.solr.common.util.Utils;++/**+ * Simple bean representation of <code>autoscaling.json</code>, which parses data+ * lazily.+ */+public class AutoScalingConfig {++ private final Map<String, Object> jsonMap;++ private Policy policy;+ private Map<String, TriggerConfig> triggers;+ private Map<String, ListenerConfig> listeners;++ /**+ * Bean representation of {@link org.apache.solr.cloud.autoscaling.AutoScaling.TriggerListener} config.+ */+ public static class ListenerConfig {+ public String trigger;+ public List<String> stages;+ public String listenerClass;+ public List<Map<String, String>> beforeActions;+ public List<Map<String, String>> afterActions;++ public ListenerConfig(Map<String, Object> properties) {+ trigger = (String)properties.get(AutoScalingParams.TRIGGER);+ stages = (List<String>)properties.getOrDefault(AutoScalingParams.STAGE, Collections.emptyList());+ listenerClass = (String)properties.get(AutoScalingParams.CLASS);+ beforeActions = (List<Map<String, String>>)properties.getOrDefault(AutoScalingParams.BEFORE_ACTION, Collections.emptyList());+ afterActions = (List<Map<String, String>>)properties.getOrDefault(AutoScalingParams.AFTER_ACTION, Collections.emptyList());+ }+ }++ /**+ * Bean representation of {@link org.apache.solr.cloud.autoscaling.AutoScaling.Trigger} config.+ */+ public static class TriggerConfig {+ public final AutoScaling.EventType eventType;+ public final Map<String, Object> properties = new HashMap<>();++ public TriggerConfig(Map<String, Object> properties) {+ String event = (String) properties.get(AutoScalingParams.EVENT);+ this.eventType = AutoScaling.EventType.valueOf(event.toUpperCase(Locale.ROOT));+ this.properties.putAll(properties);+ }+ }++ /**+ * Construct from a JSON map representation.+ * @param jsonMap+ */+ public AutoScalingConfig(Map<String, Object> jsonMap) {+ this.jsonMap = Utils.getDeepCopy(jsonMap, 10);+ }++ /**+ * Get {@link Policy} configuration.+ */+ public Policy getPolicy() {+ if (policy == null) {+ policy = new Policy(jsonMap);+ }+ return policy;+ }++ /**+ * Get trigger configurations.+ */+ public Map<String, TriggerConfig> getTriggerConfigs() {+ if (triggers == null) {+ Map<String, Object> trigMap = (Map<String, Object>)jsonMap.get("triggers");+ if (trigMap == null) {+ triggers = Collections.emptyMap();+ } else {+ triggers = new HashMap<>(trigMap.size());+ for (Map.Entry<String, Object> entry : trigMap.entrySet()) {+ triggers.put(entry.getKey(), new TriggerConfig((Map<String, Object>)entry.getValue()));+ }+ }+ }+ return triggers;+ }++ /**+ * Get listener configurations.+ */+ public Map<String, ListenerConfig> getListenerConfigs() {+ if (listeners == null) {+ Map<String, Object> map = (Map<String, Object>)jsonMap.get("listeners");+ if (map == null) {+ listeners = Collections.emptyMap();+ } else {+ listeners = new HashMap<>(map.size());+ for (Map.Entry<String, Object> entry : map.entrySet()) {+ listeners.put(entry.getKey(), new ListenerConfig((Map<String, Object>)entry.getValue()));+ }+ }+ }+ return listeners;+ }++ /**+ * Check whether triggers for specific event type exist.+ * @param types list of event types+ * @return true if there's at least one trigger matching at least one event type,+ * false otherwise,+ */+ public boolean hasTriggerForEvents(AutoScaling.EventType... types) {+ if (types == null || types.length == 0) {+ return false;+ }+ for (TriggerConfig config : getTriggerConfigs().values()) {+ for (AutoScaling.EventType type : types) {+ if (config.eventType.equals(type)) {+ return true;+ }+ }+ }+ return false;+ }+}diff --git a/solr/core/src/java/org/apache/solr/cloud/autoscaling/NodeAddedTrigger.java b/solr/core/src/java/org/apache/solr/cloud/autoscaling/NodeAddedTrigger.javaindex 642ae563c21..4162ef2b8dd 100644--- a/solr/core/src/java/org/apache/solr/cloud/autoscaling/NodeAddedTrigger.java+++ b/solr/core/src/java/org/apache/solr/cloud/autoscaling/NodeAddedTrigger.java@@ -24,6 +24,7 @@ import java.util.Collection;import java.util.Collections;import java.util.HashMap;import java.util.HashSet;+import java.util.Iterator;import java.util.List;import java.util.Locale;import java.util.Map;@@ -37,6 +38,7 @@ import org.apache.solr.common.SolrException;import org.apache.solr.common.cloud.ZkStateReader;import org.apache.solr.core.CoreContainer;import org.apache.solr.util.TimeSource;+import org.apache.zookeeper.KeeperException;import org.slf4j.Logger;import org.slf4j.LoggerFactory;@@ -97,6 +99,23 @@ public class NodeAddedTrigger extends TriggerBase {actions.get(i).init(map);}}+ // pick up added nodes for which marker paths were created+ try {+ List<String> added = container.getZkController().getZkClient().getChildren(ZkStateReader.SOLR_AUTOSCALING_NODE_ADDED_PATH, null, true);+ added.forEach(n -> {+ // don't add nodes that have since gone away+ if (lastLiveNodes.contains(n)) {+ log.debug("Adding node from marker path: {}", n);+ nodeNameVsTimeAdded.put(n, timeSource.getTime());+ }+ removeNodeAddedMarker(n);+ });+ } catch (KeeperException.NoNodeException e) {+ // ignore+ } catch (KeeperException | InterruptedException e) {+ log.warn("Exception retrieving nodeLost markers", e);+ }+}@Override@@ -223,12 +242,13 @@ public class NodeAddedTrigger extends TriggerBase {copyOfNew.removeAll(lastLiveNodes);copyOfNew.forEach(n -> {long eventTime = timeSource.getTime();- nodeNameVsTimeAdded.put(n, eventTime);log.debug("Tracking new node: {} at time {}", n, eventTime);+ nodeNameVsTimeAdded.put(n, eventTime);});// has enough time expired to trigger events for a node?- for (Map.Entry<String, Long> entry : nodeNameVsTimeAdded.entrySet()) {+ for (Iterator<Map.Entry<String, Long>> it = nodeNameVsTimeAdded.entrySet().iterator(); it.hasNext(); ) {+ Map.Entry<String, Long> entry = it.next();String nodeName = entry.getKey();Long timeAdded = entry.getValue();long now = timeSource.getTime();@@ -239,20 +259,35 @@ public class NodeAddedTrigger extends TriggerBase {log.debug("NodeAddedTrigger {} firing registered listener for node: {} added at time {} , now: {}", name, nodeName, timeAdded, now);if (listener.triggerFired(new NodeAddedEvent(getEventType(), getName(), timeAdded, nodeName))) {// remove from tracking set only if the fire was accepted- trackingKeySet.remove(nodeName);+ it.remove();+ removeNodeAddedMarker(nodeName);}} else {- trackingKeySet.remove(nodeName);+ it.remove();+ removeNodeAddedMarker(nodeName);}}}-lastLiveNodes = new HashSet(newLiveNodes);} catch (RuntimeException e) {log.error("Unexpected exception in NodeAddedTrigger", e);}}+ private void removeNodeAddedMarker(String nodeName) {+ String path = ZkStateReader.SOLR_AUTOSCALING_NODE_ADDED_PATH + "/" + nodeName;+ try {+ if (container.getZkController().getZkClient().exists(path, true)) {+ container.getZkController().getZkClient().delete(path, -1, true);+ }+ } catch (KeeperException.NoNodeException e) {+ // ignore+ } catch (KeeperException | InterruptedException e) {+ log.debug("Exception removing nodeAdded marker " + nodeName, e);+ }++ }+@Overridepublic boolean isClosed() {synchronized (this) {diff --git a/solr/core/src/java/org/apache/solr/cloud/autoscaling/NodeLostTrigger.java b/solr/core/src/java/org/apache/solr/cloud/autoscaling/NodeLostTrigger.javaindex 76c59db2a7f..9db388dd282 100644--- a/solr/core/src/java/org/apache/solr/cloud/autoscaling/NodeLostTrigger.java+++ b/solr/core/src/java/org/apache/solr/cloud/autoscaling/NodeLostTrigger.java@@ -24,6 +24,7 @@ import java.util.Collection;import java.util.Collections;import java.util.HashMap;import java.util.HashSet;+import java.util.Iterator;import java.util.List;import java.util.Locale;import java.util.Map;@@ -37,6 +38,7 @@ import org.apache.solr.common.SolrException;import org.apache.solr.common.cloud.ZkStateReader;import org.apache.solr.core.CoreContainer;import org.apache.solr.util.TimeSource;+import org.apache.zookeeper.KeeperException;import org.slf4j.Logger;import org.slf4j.LoggerFactory;@@ -96,6 +98,22 @@ public class NodeLostTrigger extends TriggerBase {actions.get(i).init(map);}}+ // pick up lost nodes for which marker paths were created+ try {+ List<String> lost = container.getZkController().getZkClient().getChildren(ZkStateReader.SOLR_AUTOSCALING_NODE_LOST_PATH, null, true);+ lost.forEach(n -> {+ // don't add nodes that have since came back+ if (!lastLiveNodes.contains(n)) {+ log.debug("Adding lost node from marker path: {}", n);+ nodeNameVsTimeRemoved.put(n, timeSource.getTime());+ }+ removeNodeLostMarker(n);+ });+ } catch (KeeperException.NoNodeException e) {+ // ignore+ } catch (KeeperException | InterruptedException e) {+ log.warn("Exception retrieving nodeLost markers", e);+ }}@Override@@ -226,7 +244,8 @@ public class NodeLostTrigger extends TriggerBase {});// has enough time expired to trigger events for a node?- for (Map.Entry<String, Long> entry : nodeNameVsTimeRemoved.entrySet()) {+ for (Iterator<Map.Entry<String, Long>> it = nodeNameVsTimeRemoved.entrySet().iterator(); it.hasNext(); ) {+ Map.Entry<String, Long> entry = it.next();String nodeName = entry.getKey();Long timeRemoved = entry.getValue();if (TimeUnit.SECONDS.convert(timeSource.getTime() - timeRemoved, TimeUnit.NANOSECONDS) >= getWaitForSecond()) {@@ -235,20 +254,34 @@ public class NodeLostTrigger extends TriggerBase {if (listener != null) {log.debug("NodeLostTrigger firing registered listener");if (listener.triggerFired(new NodeLostEvent(getEventType(), getName(), timeRemoved, nodeName))) {- trackingKeySet.remove(nodeName);+ it.remove();+ removeNodeLostMarker(nodeName);}} else {- trackingKeySet.remove(nodeName);+ it.remove();+ removeNodeLostMarker(nodeName);}}}-lastLiveNodes = new HashSet<>(newLiveNodes);} catch (RuntimeException e) {log.error("Unexpected exception in NodeLostTrigger", e);}}+ private void removeNodeLostMarker(String nodeName) {+ String path = ZkStateReader.SOLR_AUTOSCALING_NODE_LOST_PATH + "/" + nodeName;+ try {+ if (container.getZkController().getZkClient().exists(path, true)) {+ container.getZkController().getZkClient().delete(path, -1, true);+ }+ } catch (KeeperException.NoNodeException e) {+ // ignore+ } catch (KeeperException | InterruptedException e) {+ log.warn("Exception removing nodeLost marker " + nodeName, e);+ }+ }+@Overridepublic boolean isClosed() {synchronized (this) {diff --git a/solr/core/src/java/org/apache/solr/cloud/autoscaling/OverseerTriggerThread.java b/solr/core/src/java/org/apache/solr/cloud/autoscaling/OverseerTriggerThread.javaindex 4a89ce7920d..91146b66f27 100644--- a/solr/core/src/java/org/apache/solr/cloud/autoscaling/OverseerTriggerThread.java+++ b/solr/core/src/java/org/apache/solr/cloud/autoscaling/OverseerTriggerThread.java@@ -35,6 +35,7 @@ import org.apache.solr.common.cloud.SolrZkClient;import org.apache.solr.common.cloud.ZkNodeProps;import org.apache.solr.common.cloud.ZkStateReader;import org.apache.solr.common.cloud.ZooKeeperException;+import org.apache.solr.common.params.AutoScalingParams;import org.apache.solr.common.util.IOUtils;import org.apache.zookeeper.KeeperException;import org.apache.zookeeper.WatchedEvent;@@ -169,10 +170,59 @@ public class OverseerTriggerThread implements Runnable, Closeable {scheduledTriggers.remove(managedTriggerName);}}+ // check for nodeLost triggers in the current config, and if+ // absent then clean up old nodeLost / nodeAdded markers+ boolean cleanOldNodeLostMarkers = true;+ boolean cleanOldNodeAddedMarkers = true;// add new triggers and/or replace and close the replaced triggersfor (Map.Entry<String, AutoScaling.Trigger> entry : copy.entrySet()) {+ if (entry.getValue().getEventType().equals(AutoScaling.EventType.NODELOST)) {+ cleanOldNodeLostMarkers = false;+ }+ if (entry.getValue().getEventType().equals(AutoScaling.EventType.NODEADDED)) {+ cleanOldNodeAddedMarkers = false;+ }scheduledTriggers.add(entry.getValue());}+ if (cleanOldNodeLostMarkers) {+ log.debug("-- clean old nodeLost markers");+ try {+ List<String> markers = zkClient.getChildren(ZkStateReader.SOLR_AUTOSCALING_NODE_LOST_PATH, null, true);+ markers.forEach(n -> {+ removeNodeMarker(ZkStateReader.SOLR_AUTOSCALING_NODE_LOST_PATH, n);+ });+ } catch (KeeperException.NoNodeException e) {+ // ignore+ } catch (KeeperException | InterruptedException e) {+ log.warn("Error removing old nodeLost markers", e);+ }+ }+ if (cleanOldNodeAddedMarkers) {+ log.debug("-- clean old nodeAdded markers");+ try {+ List<String> markers = zkClient.getChildren(ZkStateReader.SOLR_AUTOSCALING_NODE_ADDED_PATH, null, true);+ markers.forEach(n -> {+ removeNodeMarker(ZkStateReader.SOLR_AUTOSCALING_NODE_ADDED_PATH, n);+ });+ } catch (KeeperException.NoNodeException e) {+ // ignore+ } catch (KeeperException | InterruptedException e) {+ log.warn("Error removing old nodeAdded markers", e);+ }++ }+ }+ }++ private void removeNodeMarker(String path, String nodeName) {+ path = path + "/" + nodeName;+ try {+ zkClient.delete(path, -1, true);+ log.debug(" -- deleted " + path);+ } catch (KeeperException.NoNodeException e) {+ // ignore+ } catch (KeeperException | InterruptedException e) {+ log.warn("Error removing old marker " + path, e);}}@@ -250,7 +300,7 @@ public class OverseerTriggerThread implements Runnable, Closeable {for (Map.Entry<String, Object> entry : triggers.entrySet()) {Map<String, Object> props = (Map<String, Object>) entry.getValue();- String event = (String) props.get("event");+ String event = (String) props.get(AutoScalingParams.EVENT);AutoScaling.EventType eventType = AutoScaling.EventType.valueOf(event.toUpperCase(Locale.ROOT));String triggerName = entry.getKey();triggerMap.put(triggerName, triggerFactory.create(eventType, triggerName, props));diff --git a/solr/core/src/java/org/apache/solr/cloud/autoscaling/ScheduledTriggers.java b/solr/core/src/java/org/apache/solr/cloud/autoscaling/ScheduledTriggers.javaindex 6180b358b2f..d595d4dbaf2 100644--- a/solr/core/src/java/org/apache/solr/cloud/autoscaling/ScheduledTriggers.java+++ b/solr/core/src/java/org/apache/solr/cloud/autoscaling/ScheduledTriggers.java@@ -20,6 +20,7 @@ package org.apache.solr.cloud.autoscaling;import java.io.Closeable;import java.io.IOException;import java.lang.invoke.MethodHandles;+import java.util.ArrayList;import java.util.Collections;import java.util.HashSet;import java.util.List;@@ -42,6 +43,7 @@ import org.apache.solr.common.util.ExecutorUtil;import org.apache.solr.common.util.IOUtils;import org.apache.solr.util.DefaultSolrThreadFactory;import org.apache.zookeeper.KeeperException;+import org.apache.zookeeper.Op;import org.slf4j.Logger;import org.slf4j.LoggerFactory;@@ -208,7 +210,13 @@ public class ScheduledTriggers implements Closeable {}try {if (zkClient.exists(eventsPath, true)) {- zkClient.delete(eventsPath, -1, true);+ List<String> events = zkClient.getChildren(eventsPath, null, true);+ List<Op> ops = new ArrayList<>(events.size() + 1);+ events.forEach(ev -> {+ ops.add(Op.delete(eventsPath + "/" + ev, -1));+ });+ ops.add(Op.delete(eventsPath, -1));+ zkClient.multi(ops, true);}} catch (KeeperException | InterruptedException e) {log.warn("Failed to remove events for removed trigger " + eventsPath, e);diff --git a/solr/core/src/java/org/apache/solr/cloud/autoscaling/TriggerBase.java b/solr/core/src/java/org/apache/solr/cloud/autoscaling/TriggerBase.javaindex ef9a3cfb6f3..7aff8464c22 100644--- a/solr/core/src/java/org/apache/solr/cloud/autoscaling/TriggerBase.java+++ b/solr/core/src/java/org/apache/solr/cloud/autoscaling/TriggerBase.java@@ -97,11 +97,11 @@ public abstract class TriggerBase implements AutoScaling.Trigger {LOG.warn("Exception getting trigger state '" + path + "'", e);}if (data != null) {- Map<String, Object> state = (Map<String, Object>)Utils.fromJSON(data);+ Map<String, Object> restoredState = (Map<String, Object>)Utils.fromJSON(data);// make sure lastState is sorted- state = Utils.getDeepCopy(state, 10, false, true);;- setState(state);- lastState = state;+ restoredState = Utils.getDeepCopy(restoredState, 10, false, true);+ setState(restoredState);+ lastState = restoredState;}}}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 503827811d1..a80987365a2 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@@ -30,7 +30,6 @@ import org.apache.solr.cloud.OverseerTaskProcessor;import org.apache.solr.cloud.SolrCloudTestCase;import org.apache.solr.common.cloud.DocCollection;import org.apache.solr.common.cloud.ZkStateReader;-import org.apache.solr.common.util.Utils;import org.apache.zookeeper.KeeperException;import org.junit.After;import org.junit.BeforeClass;diff --git a/solr/core/src/test/org/apache/solr/cloud/autoscaling/TriggerIntegrationTest.java b/solr/core/src/test/org/apache/solr/cloud/autoscaling/TriggerIntegrationTest.javaindex 1c189aebd5c..70f0fdc4f64 100644--- a/solr/core/src/test/org/apache/solr/cloud/autoscaling/TriggerIntegrationTest.java+++ b/solr/core/src/test/org/apache/solr/cloud/autoscaling/TriggerIntegrationTest.java@@ -19,13 +19,16 @@ package org.apache.solr.cloud.autoscaling;import java.io.IOException;import java.lang.invoke.MethodHandles;+import java.util.HashSet;import java.util.List;import java.util.Map;+import java.util.Set;+import java.util.SortedSet;+import java.util.concurrent.ConcurrentHashMap;import java.util.concurrent.CountDownLatch;import java.util.concurrent.TimeUnit;import java.util.concurrent.atomic.AtomicBoolean;import java.util.concurrent.atomic.AtomicLong;-import java.util.concurrent.atomic.AtomicReference;import java.util.concurrent.locks.ReentrantLock;import org.apache.solr.client.solrj.SolrRequest;@@ -34,12 +37,16 @@ import org.apache.solr.client.solrj.impl.CloudSolrClient;import org.apache.solr.client.solrj.request.CollectionAdminRequest;import org.apache.solr.client.solrj.response.CollectionAdminResponse;import org.apache.solr.cloud.SolrCloudTestCase;+import org.apache.solr.common.cloud.LiveNodesListener;import org.apache.solr.common.cloud.ZkNodeProps;+import org.apache.solr.common.cloud.ZkStateReader;import org.apache.solr.common.util.NamedList;import org.apache.solr.common.util.Utils;import org.apache.solr.util.LogLevel;import org.apache.solr.util.TimeOut;import org.apache.solr.util.TimeSource;+import org.apache.zookeeper.KeeperException;+import org.apache.zookeeper.ZKUtil;import org.apache.zookeeper.data.Stat;import org.junit.Before;import org.junit.BeforeClass;@@ -65,7 +72,8 @@ public class TriggerIntegrationTest extends SolrCloudTestCase {private static CountDownLatch actionInterrupted;private static CountDownLatch actionCompleted;private static AtomicBoolean triggerFired;- private static AtomicReference<TriggerEvent> eventRef;+ private static Set<TriggerEvent> events = ConcurrentHashMap.newKeySet();+ private static ZkStateReader zkStateReader;private String path;@@ -77,6 +85,7 @@ public class TriggerIntegrationTest extends SolrCloudTestCase {configureCluster(2).addConfig("conf", configset("cloud-minimal")).configure();+ zkStateReader = cluster.getSolrClient().getZkStateReader();}private static CountDownLatch getTriggerFiredLatch() {@@ -105,10 +114,16 @@ public class TriggerIntegrationTest extends SolrCloudTestCase {actionStarted = new CountDownLatch(1);actionInterrupted = new CountDownLatch(1);actionCompleted = new CountDownLatch(1);- eventRef = new AtomicReference<>();+ events.clear();// clear any persisted auto scaling configurationStat stat = zkClient().setData(SOLR_AUTOSCALING_CONF_PATH, Utils.toJSON(new ZkNodeProps()), true);log.info(SOLR_AUTOSCALING_CONF_PATH + " reset, new znode version {}", stat.getVersion());+ // clear any events or markers+ // todo: consider the impact of such cleanup on regular cluster restarts+ deleteChildrenRecursively(ZkStateReader.SOLR_AUTOSCALING_EVENTS_PATH);+ deleteChildrenRecursively(ZkStateReader.SOLR_AUTOSCALING_TRIGGER_STATE_PATH);+ deleteChildrenRecursively(ZkStateReader.SOLR_AUTOSCALING_NODE_LOST_PATH);+ deleteChildrenRecursively(ZkStateReader.SOLR_AUTOSCALING_NODE_ADDED_PATH);// todo nocommit -- add testing for the v2 path// String path = random().nextBoolean() ? "/admin/autoscaling" : "/v2/cluster/autoscaling";this.path = "/admin/autoscaling";@@ -119,6 +134,19 @@ public class TriggerIntegrationTest extends SolrCloudTestCase {}}+ private void deleteChildrenRecursively(String path) throws Exception {+ List<String> paths = zkClient().getChildren(path, null, true);+ paths.forEach(n -> {+ try {+ ZKUtil.deleteRecursive(zkClient().getSolrZooKeeper(), path + "/" + n);+ } catch (KeeperException.NoNodeException e) {+ // ignore+ } catch (KeeperException | InterruptedException e) {+ log.warn("Error deleting old data", e);+ }+ });+ }+@Testpublic void testTriggerThrottling() throws Exception {// for this test we want to create two triggers so we must assert that the actions were created twice@@ -316,7 +344,7 @@ public class TriggerIntegrationTest extends SolrCloudTestCase {boolean await = triggerFiredLatch.await(5, TimeUnit.SECONDS);assertTrue("The trigger did not fire at all", await);assertTrue(triggerFired.get());- NodeLostTrigger.NodeLostEvent nodeLostEvent = (NodeLostTrigger.NodeLostEvent) eventRef.get();+ NodeLostTrigger.NodeLostEvent nodeLostEvent = (NodeLostTrigger.NodeLostEvent) events.iterator().next();assertNotNull(nodeLostEvent);assertEquals("The node added trigger was fired but for a different node",nodeName, nodeLostEvent.getProperty(NodeLostTrigger.NodeLostEvent.NODE_NAME));@@ -374,7 +402,7 @@ public class TriggerIntegrationTest extends SolrCloudTestCase {boolean await = triggerFiredLatch.await(5, TimeUnit.SECONDS);assertTrue("The trigger did not fire at all", await);assertTrue(triggerFired.get());- NodeAddedTrigger.NodeAddedEvent nodeAddedEvent = (NodeAddedTrigger.NodeAddedEvent) eventRef.get();+ NodeAddedTrigger.NodeAddedEvent nodeAddedEvent = (NodeAddedTrigger.NodeAddedEvent) events.iterator().next();assertNotNull(nodeAddedEvent);assertEquals("The node added trigger was fired but for a different node",newNode.getNodeName(), nodeAddedEvent.getProperty(NodeAddedTrigger.NodeAddedEvent.NODE_NAME));@@ -403,7 +431,7 @@ public class TriggerIntegrationTest extends SolrCloudTestCase {boolean await = triggerFiredLatch.await(20, TimeUnit.SECONDS);assertTrue("The trigger did not fire at all", await);assertTrue(triggerFired.get());- NodeAddedTrigger.NodeAddedEvent nodeAddedEvent = (NodeAddedTrigger.NodeAddedEvent) eventRef.get();+ NodeAddedTrigger.NodeAddedEvent nodeAddedEvent = (NodeAddedTrigger.NodeAddedEvent) events.iterator().next();assertNotNull(nodeAddedEvent);assertEquals("The node added trigger was fired but for a different node",newNode.getNodeName(), nodeAddedEvent.getProperty(TriggerEvent.NODE_NAME));@@ -466,7 +494,7 @@ public class TriggerIntegrationTest extends SolrCloudTestCase {boolean await = triggerFiredLatch.await(20, TimeUnit.SECONDS);assertTrue("The trigger did not fire at all", await);assertTrue(triggerFired.get());- NodeLostTrigger.NodeLostEvent nodeLostEvent = (NodeLostTrigger.NodeLostEvent) eventRef.get();+ NodeLostTrigger.NodeLostEvent nodeLostEvent = (NodeLostTrigger.NodeLostEvent) events.iterator().next();assertNotNull(nodeLostEvent);assertEquals("The node lost trigger was fired but for a different node",lostNodeName, nodeLostEvent.getProperty(TriggerEvent.NODE_NAME));@@ -538,7 +566,7 @@ public class TriggerIntegrationTest extends SolrCloudTestCase {boolean await = triggerFiredLatch.await(20, TimeUnit.SECONDS);assertTrue("The trigger did not fire at all", await);assertTrue(triggerFired.get());- NodeAddedTrigger.NodeAddedEvent nodeAddedEvent = (NodeAddedTrigger.NodeAddedEvent) eventRef.get();+ NodeAddedTrigger.NodeAddedEvent nodeAddedEvent = (NodeAddedTrigger.NodeAddedEvent) events.iterator().next();assertNotNull(nodeAddedEvent);assertEquals("The node added trigger was fired but for a different node",newNode.getNodeName(), nodeAddedEvent.getProperty(TriggerEvent.NODE_NAME));@@ -564,7 +592,7 @@ public class TriggerIntegrationTest extends SolrCloudTestCase {public void process(TriggerEvent event) {try {if (triggerFired.compareAndSet(false, true)) {- eventRef.set(event);+ events.add(event);if (TimeUnit.MILLISECONDS.convert(timeSource.getTime() - event.getEventTime(), TimeUnit.NANOSECONDS) <= TimeUnit.MILLISECONDS.convert(waitForSeconds, TimeUnit.SECONDS)) {fail("NodeAddedListener was fired before the configured waitFor period");}@@ -608,10 +636,11 @@ public class TriggerIntegrationTest extends SolrCloudTestCase {@Overridepublic void process(TriggerEvent event) {- eventRef.set(event);+ log.info("-- event: " + event);+ events.add(event);getActionStarted().countDown();try {- Thread.sleep(5000);+ Thread.sleep(eventQueueActionWait);triggerFired.compareAndSet(false, true);getActionCompleted().countDown();} catch (InterruptedException e) {@@ -632,6 +661,8 @@ public class TriggerIntegrationTest extends SolrCloudTestCase {}}+ public static long eventQueueActionWait = 5000;+@Testpublic void testEventQueue() throws Exception {CloudSolrClient solrClient = cluster.getSolrClient();@@ -666,23 +697,24 @@ public class TriggerIntegrationTest extends SolrCloudTestCase {boolean await = actionStarted.await(60, TimeUnit.SECONDS);assertTrue("action did not start", await);// event should be there- NodeAddedTrigger.NodeAddedEvent nodeAddedEvent = (NodeAddedTrigger.NodeAddedEvent) eventRef.get();+ NodeAddedTrigger.NodeAddedEvent nodeAddedEvent = (NodeAddedTrigger.NodeAddedEvent) events.iterator().next();assertNotNull(nodeAddedEvent);// but action did not complete yet so the event is still enqueuedassertFalse(triggerFired.get());+ events.clear();actionStarted = new CountDownLatch(1);+ eventQueueActionWait = 1;// kill overseer leadercluster.stopJettySolrRunner(overseerLeaderIndex);Thread.sleep(5000);+ // new overseer leader should be elected and run triggersawait = actionInterrupted.await(3, TimeUnit.SECONDS);assertTrue("action wasn't interrupted", await);- // new overseer leader should be elected and run triggers- newNode = cluster.startJettySolrRunner();- // it should fire again but not complete yet+ // it should fire again from enqueued eventawait = actionStarted.await(60, TimeUnit.SECONDS);- TriggerEvent replayedEvent = eventRef.get();+ TriggerEvent replayedEvent = events.iterator().next();assertTrue(replayedEvent.getProperty(TriggerEventQueue.ENQUEUE_TIME) != null);- assertTrue(replayedEvent.getProperty(TriggerEventQueue.DEQUEUE_TIME) != null);+ assertTrue(events + "\n" + replayedEvent.toString(), replayedEvent.getProperty(TriggerEventQueue.DEQUEUE_TIME) != null);await = actionCompleted.await(10, TimeUnit.SECONDS);assertTrue(triggerFired.get());}@@ -717,6 +749,8 @@ public class TriggerIntegrationTest extends SolrCloudTestCase {}}+ events.clear();+JettySolrRunner newNode = cluster.startJettySolrRunner();boolean await = triggerFiredLatch.await(20, TimeUnit.SECONDS);assertTrue("The trigger did not fire at all", await);@@ -724,7 +758,7 @@ public class TriggerIntegrationTest extends SolrCloudTestCase {// resettriggerFired.set(false);triggerFiredLatch = new CountDownLatch(1);- NodeAddedTrigger.NodeAddedEvent nodeAddedEvent = (NodeAddedTrigger.NodeAddedEvent) eventRef.get();+ NodeAddedTrigger.NodeAddedEvent nodeAddedEvent = (NodeAddedTrigger.NodeAddedEvent) events.iterator().next();assertNotNull(nodeAddedEvent);assertEquals("The node added trigger was fired but for a different node",newNode.getNodeName(), nodeAddedEvent.getProperty(NodeAddedTrigger.NodeAddedEvent.NODE_NAME));@@ -737,4 +771,206 @@ public class TriggerIntegrationTest extends SolrCloudTestCase {assertTrue("The trigger did not fire at all", await);assertTrue(triggerFired.get());}++ private static class TestLiveNodesListener implements LiveNodesListener {+ Set<String> lostNodes = new HashSet<>();+ Set<String> addedNodes = new HashSet<>();+ CountDownLatch onChangeLatch = new CountDownLatch(1);++ public void reset() {+ lostNodes.clear();+ addedNodes.clear();+ onChangeLatch = new CountDownLatch(1);+ }++ @Override+ public void onChange(SortedSet<String> oldLiveNodes, SortedSet<String> newLiveNodes) {+ onChangeLatch.countDown();+ Set<String> old = new HashSet<>(oldLiveNodes);+ old.removeAll(newLiveNodes);+ if (!old.isEmpty()) {+ lostNodes.addAll(old);+ }+ newLiveNodes.removeAll(oldLiveNodes);+ if (!newLiveNodes.isEmpty()) {+ addedNodes.addAll(newLiveNodes);+ }+ }+ }++ private TestLiveNodesListener registerLiveNodesListener() {+ TestLiveNodesListener listener = new TestLiveNodesListener();+ zkStateReader.registerLiveNodesListener(listener);+ return listener;+ }++ public static class TestEventMarkerAction implements TriggerAction {++ public TestEventMarkerAction() {+ actionConstructorCalled.countDown();+ }++ @Override+ public String getName() {+ return "TestEventMarkerAction";+ }++ @Override+ public String getClassName() {+ return this.getClass().getName();+ }++ @Override+ public void process(TriggerEvent event) {+ boolean locked = lock.tryLock();+ if (!locked) {+ log.info("We should never have a tryLock fail because actions are never supposed to be executed concurrently");+ return;+ }+ try {+ events.add(event);+ getTriggerFiredLatch().countDown();+ } catch (Throwable t) {+ log.debug("--throwable", t);+ throw t;+ } finally {+ if (locked) {+ lock.unlock();+ }+ }+ }++ @Override+ public void close() throws IOException {++ }++ @Override+ public void init(Map<String, String> args) {+ log.info("TestEventMarkerAction init");+ actionInitCalled.countDown();+ }+ }++ @Test+ public void testNodeMarkersRegistration() throws Exception {+ // for this test we want to create two triggers so we must assert that the actions were created twice+ actionInitCalled = new CountDownLatch(2);+ // similarly we want both triggers to fire+ triggerFiredLatch = new CountDownLatch(2);+ TestLiveNodesListener listener = registerLiveNodesListener();++ NamedList<Object> overSeerStatus = cluster.getSolrClient().request(CollectionAdminRequest.getOverseerStatus());+ String overseerLeader = (String) overSeerStatus.get("leader");+ int overseerLeaderIndex = 0;+ for (int i = 0; i < cluster.getJettySolrRunners().size(); i++) {+ JettySolrRunner jetty = cluster.getJettySolrRunner(i);+ if (jetty.getNodeName().equals(overseerLeader)) {+ overseerLeaderIndex = i;+ break;+ }+ }+ // add a node+ JettySolrRunner node = cluster.startJettySolrRunner();+ if (!listener.onChangeLatch.await(10, TimeUnit.SECONDS)) {+ fail("onChange listener didn't execute on cluster change");+ }+ assertEquals(1, listener.addedNodes.size());+ assertEquals(node.getNodeName(), listener.addedNodes.iterator().next());+ // verify that a znode doesn't exist (no trigger)+ String pathAdded = ZkStateReader.SOLR_AUTOSCALING_NODE_ADDED_PATH + "/" + node.getNodeName();+ assertFalse("Path " + pathAdded + " was created but there are no nodeAdded triggers", zkClient().exists(pathAdded, true));+ listener.reset();+ // stop overseer+ log.info("====== KILL OVERSEER 1");+ cluster.stopJettySolrRunner(overseerLeaderIndex);+ if (!listener.onChangeLatch.await(10, TimeUnit.SECONDS)) {+ fail("onChange listener didn't execute on cluster change");+ }+ assertEquals(1, listener.lostNodes.size());+ assertEquals(overseerLeader, listener.lostNodes.iterator().next());+ assertEquals(0, listener.addedNodes.size());+ // wait until the new overseer is up+ Thread.sleep(5000);+ // verify that a znode does NOT exist - there's no nodeLost trigger,+ // so the new overseer cleaned up existing nodeLost markers+ String pathLost = ZkStateReader.SOLR_AUTOSCALING_NODE_LOST_PATH + "/" + overseerLeader;+ assertFalse("Path " + pathLost + " exists", zkClient().exists(pathLost, true));++ listener.reset();++ // set up triggers+ CloudSolrClient solrClient = cluster.getSolrClient();++ log.info("====== ADD TRIGGERS");+ String setTriggerCommand = "{" ++ "'set-trigger' : {" ++ "'name' : 'node_added_trigger'," ++ "'event' : 'nodeAdded'," ++ "'waitFor' : '1s'," ++ "'enabled' : true," ++ "'actions' : [{'name':'test','class':'" + TestEventMarkerAction.class.getName() + "'}]" ++ "}}";+ SolrRequest req = new AutoScalingHandlerTest.AutoScalingRequest(SolrRequest.METHOD.POST, path, setTriggerCommand);+ NamedList<Object> response = solrClient.request(req);+ assertEquals(response.get("result").toString(), "success");++ setTriggerCommand = "{" ++ "'set-trigger' : {" ++ "'name' : 'node_lost_trigger'," ++ "'event' : 'nodeLost'," ++ "'waitFor' : '1s'," ++ "'enabled' : true," ++ "'actions' : [{'name':'test','class':'" + TestEventMarkerAction.class.getName() + "'}]" ++ "}}";+ req = new AutoScalingHandlerTest.AutoScalingRequest(SolrRequest.METHOD.POST, path, setTriggerCommand);+ response = solrClient.request(req);+ assertEquals(response.get("result").toString(), "success");++ overSeerStatus = cluster.getSolrClient().request(CollectionAdminRequest.getOverseerStatus());+ overseerLeader = (String) overSeerStatus.get("leader");+ overseerLeaderIndex = 0;+ for (int i = 0; i < cluster.getJettySolrRunners().size(); i++) {+ JettySolrRunner jetty = cluster.getJettySolrRunner(i);+ if (jetty.getNodeName().equals(overseerLeader)) {+ overseerLeaderIndex = i;+ break;+ }+ }++ // create another node+ log.info("====== ADD NODE 1");+ JettySolrRunner node1 = cluster.startJettySolrRunner();+ if (!listener.onChangeLatch.await(10, TimeUnit.SECONDS)) {+ fail("onChange listener didn't execute on cluster change");+ }+ assertEquals(1, listener.addedNodes.size());+ assertEquals(node1.getNodeName(), listener.addedNodes.iterator().next());+ // verify that a znode exists+ pathAdded = ZkStateReader.SOLR_AUTOSCALING_NODE_ADDED_PATH + "/" + node1.getNodeName();+ assertTrue("Path " + pathAdded + " wasn't created", zkClient().exists(pathAdded, true));++ Thread.sleep(5000);+ // nodeAdded marker should be consumed now by nodeAdded trigger+ assertFalse("Path " + pathAdded + " should have been deleted", zkClient().exists(pathAdded, true));++ listener.reset();+ events.clear();+ triggerFiredLatch = new CountDownLatch(1);+ // kill overseer again+ log.info("====== KILL OVERSEER 2");+ cluster.stopJettySolrRunner(overseerLeaderIndex);+ if (!listener.onChangeLatch.await(10, TimeUnit.SECONDS)) {+ fail("onChange listener didn't execute on cluster change");+ }+++ if (!triggerFiredLatch.await(20, TimeUnit.SECONDS)) {+ fail("Trigger should have fired by now");+ }+ assertEquals(1, events.size());+ TriggerEvent ev = events.iterator().next();+ assertEquals(overseerLeader, ev.getProperty(TriggerEvent.NODE_NAME));+ assertEquals(AutoScaling.EventType.NODELOST, ev.getEventType());+ }}diff --git a/solr/solrj/src/java/org/apache/solr/common/cloud/LiveNodesListener.java b/solr/solrj/src/java/org/apache/solr/common/cloud/LiveNodesListener.javanew file mode 100644index 00000000000..1cf16e17eee--- /dev/null+++ b/solr/solrj/src/java/org/apache/solr/common/cloud/LiveNodesListener.java@@ -0,0 +1,38 @@+/*+ * Licensed to the Apache Software Foundation (ASF) under one or more+ * contributor license agreements. See the NOTICE file distributed with+ * this work for additional information regarding copyright ownership.+ * The ASF licenses this file to You under the Apache License, Version 2.0+ * (the "License"); you may not use this file except in compliance with+ * the License. You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++package org.apache.solr.common.cloud;++import java.util.SortedSet;++/**+ * Listener that can be used with {@link ZkStateReader#registerLiveNodesListener(LiveNodesListener)}+ * and called whenever the live nodes set changes.+ */+public interface LiveNodesListener {++ /**+ * Called when a change in the live nodes set occurs.+ *+ * Note that, due to the way Zookeeper watchers are implemented, a single call may be+ * the result of several state changes+ *+ * @param oldLiveNodes set of live nodes before the change+ * @param newLiveNodes set of live nodes after the change+ */+ void onChange(SortedSet<String> oldLiveNodes, SortedSet<String> newLiveNodes);+}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 f23b0b562d1..afb4acf83dd 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@@ -30,6 +30,7 @@ import java.util.Map;import java.util.Map.Entry;import java.util.Objects;import java.util.Set;+import java.util.SortedSet;import java.util.TreeSet;import java.util.concurrent.ConcurrentHashMap;import java.util.concurrent.CountDownLatch;@@ -59,6 +60,7 @@ import static java.util.Arrays.asList;import static java.util.Collections.EMPTY_MAP;import static java.util.Collections.emptyMap;import static java.util.Collections.emptySet;+import static java.util.Collections.emptySortedSet;import static java.util.Collections.unmodifiableSet;import static org.apache.solr.common.util.Utils.fromJSON;@@ -94,6 +96,8 @@ public class ZkStateReader implements Closeable {public static final String SOLR_AUTOSCALING_CONF_PATH = "/autoscaling.json";public static final String SOLR_AUTOSCALING_EVENTS_PATH = "/autoscaling/events";public static final String SOLR_AUTOSCALING_TRIGGER_STATE_PATH = "/autoscaling/triggerState";+ public static final String SOLR_AUTOSCALING_NODE_ADDED_PATH = "/autoscaling/nodeAdded";+ public static final String SOLR_AUTOSCALING_NODE_LOST_PATH = "/autoscaling/nodeLost";public static final String REPLICATION_FACTOR = "replicationFactor";public static final String MAX_SHARDS_PER_NODE = "maxShardsPerNode";@@ -134,7 +138,7 @@ public class ZkStateReader implements Closeable {/** Collections with format2 state.json, not "interesting" and not actively watched. */private final ConcurrentHashMap<String, LazyCollectionRef> lazyCollectionStates = new ConcurrentHashMap<>();- private volatile Set<String> liveNodes = emptySet();+ private volatile SortedSet<String> liveNodes = emptySortedSet();private volatile Map<String, Object> clusterProperties = Collections.emptyMap();@@ -159,6 +163,8 @@ public class ZkStateReader implements Closeable {}+ private Set<LiveNodesListener> liveNodesListeners = ConcurrentHashMap.newKeySet();+public static final Set<String> KNOWN_CLUSTER_PROPS = unmodifiableSet(new HashSet<>(asList(LEGACY_CLOUD,URL_SCHEME,@@ -656,25 +662,25 @@ public class ZkStateReader implements Closeable {// We don't get a Stat or track versions on getChildren() calls, so force linearization.private final Object refreshLiveNodesLock = new Object();// Ensures that only the latest getChildren fetch gets applied.- private final AtomicReference<Set<String>> lastFetchedLiveNodes = new AtomicReference<>();+ private final AtomicReference<SortedSet<String>> lastFetchedLiveNodes = new AtomicReference<>();/*** Refresh live_nodes.*/private void refreshLiveNodes(Watcher watcher) throws KeeperException, InterruptedException {synchronized (refreshLiveNodesLock) {- Set<String> newLiveNodes;+ SortedSet<String> newLiveNodes;try {List<String> nodeList = zkClient.getChildren(LIVE_NODES_ZKNODE, watcher, true);- newLiveNodes = new HashSet<>(nodeList);+ newLiveNodes = new TreeSet<>(nodeList);} catch (KeeperException.NoNodeException e) {- newLiveNodes = emptySet();+ newLiveNodes = emptySortedSet();}lastFetchedLiveNodes.set(newLiveNodes);}// Can't lock getUpdateLock() until we release the other, it would cause deadlock.- Set<String> oldLiveNodes, newLiveNodes;+ SortedSet<String> oldLiveNodes, newLiveNodes;synchronized (getUpdateLock()) {newLiveNodes = lastFetchedLiveNodes.getAndSet(null);if (newLiveNodes == null) {@@ -692,10 +698,22 @@ public class ZkStateReader implements Closeable {LOG.info("Updated live nodes from ZooKeeper... ({}) -> ({})", oldLiveNodes.size(), newLiveNodes.size());}if (LOG.isDebugEnabled()) {- LOG.debug("Updated live nodes from ZooKeeper... {} -> {}", new TreeSet<>(oldLiveNodes), new TreeSet<>(newLiveNodes));+ LOG.debug("Updated live nodes from ZooKeeper... {} -> {}", oldLiveNodes, newLiveNodes);+ }+ if (!oldLiveNodes.equals(newLiveNodes)) { // fire listeners+ liveNodesListeners.forEach(listener ->+ listener.onChange(new TreeSet<>(oldLiveNodes), new TreeSet<>(newLiveNodes)));}}+ public void registerLiveNodesListener(LiveNodesListener listener) {+ liveNodesListeners.add(listener);+ }++ public void removeLiveNodesListener(LiveNodesListener listener) {+ liveNodesListeners.remove(listener);+ }+/*** @return information about the cluster from ZooKeeper*/