Apache Solr open-source search software
SOLR-14546: OverseerTaskProcessor can process messages out of order (#1561)
Ilan Ginzburg3e42286e9e78
diff --git a/solr/CHANGES.txt b/solr/CHANGES.txtindex 1ad5c6afaae..9ca7a8a92e4 100644--- a/solr/CHANGES.txt+++ b/solr/CHANGES.txt@@ -76,8 +76,11 @@ Other Changes* SOLR-14486: Autoscaling simulation framework no longer creates /clusterstate.json (format 1),instead it creates individual per-collection /state.json files (format 2). (ab)- * SOLR-12823: Remove /clusterstate.json support: support for collections created with stateFormat=1,- as well as support for Collection API MIGRATESTATEFORMAT action and support for the legacyCloud flag (Ilan Ginzburg).+* SOLR-12823: Remove /clusterstate.json support, including support for collections created with stateFormat=1,+ as well as support for Collection API MIGRATESTATEFORMAT action and support for the legacyCloud flag (Ilan Ginzburg).++* SOLR-14546: Fix for a relatively hard to hit issue in OverseerTaskProcessor that could lead to out of order execution+ of Collection API tasks competing for a lock (Ilan Ginzburg).================== 8.6.0 ==================diff --git a/solr/core/src/java/org/apache/solr/cloud/LockTree.java b/solr/core/src/java/org/apache/solr/cloud/LockTree.javaindex 25bc345ac0a..1ada7d7a221 100644--- a/solr/core/src/java/org/apache/solr/cloud/LockTree.java+++ b/solr/core/src/java/org/apache/solr/cloud/LockTree.java@@ -39,12 +39,6 @@ public class LockTree {private static final Logger log = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());private final Node root = new Node(null, LockLevel.CLUSTER, null);- public void clear() {- synchronized (this) {- root.clear();- }- }-private class LockImpl implements Lock {final Node node;@@ -66,15 +60,24 @@ public class LockTree {}+ /**+ * This class is used to mark nodes for which acquiring a lock was attempted but didn't succeed. Lock acquisition failure+ * needs to be "remembered" to trigger failures to acquire a competing lock until the Session is replaced, to prevent+ * tasks enqueued later (and dequeued later once the busy lock got released) from being executed before earlier tasks+ * that failed to execute because the lock wasn't available earlier when they attempted to acquire it.<p>+ *+ * A new Session is created each time the iteration over the queue tasks is restarted starting at the oldest non+ * running or completed tasks.+ */public class Session {private SessionNode root = new SessionNode(LockLevel.CLUSTER);public Lock lock(CollectionParams.CollectionAction action, List<String> path) {+ if (action.lockLevel == LockLevel.NONE) return FREELOCK;synchronized (LockTree.this) {- if (action.lockLevel == LockLevel.NONE) return FREELOCK;if (root.isBusy(action.lockLevel, path)) return null;Lock lockObject = LockTree.this.root.lock(action.lockLevel, path);- if (lockObject == null) root.markBusy(path, 0);+ if (lockObject == null) root.markBusy(action.lockLevel, path);return lockObject;}}@@ -89,22 +92,31 @@ public class LockTree {this.level = level;}- void markBusy(List<String> path, int depth) {- if (path.size() == depth) {+ /**+ * Marks busy the SessionNode corresponding to <code>lockLevel</code> (node names coming from <code>path</code>).+ * @param path contains at least <code>lockLevel.getHeight()</code> strings, capturing the names of the+ * <code>SessionNode</code> being walked from the {@link Session#root} to the <code>SessionNode</code>+ * that is to be marked busy.+ * @param lockLevel the level of the node that should be marked busy.+ */+ void markBusy(LockLevel lockLevel, List<String> path) {+ if (level == lockLevel) {+ // Lock is to be set on current nodebusy = true;} else {- String s = path.get(depth);+ // Recursively create the required SessionNode subtree to capture lock being set on child node.+ String s = path.get(level.getHeight());if (kids == null) kids = new HashMap<>();- SessionNode node = kids.get(s);- if (node == null) kids.put(s, node = new SessionNode(level.getChild()));- node.markBusy(path, depth + 1);+ SessionNode child = kids.get(s);+ if (child == null) kids.put(s, child = new SessionNode(level.getChild()));+ child.markBusy(lockLevel, path);}}boolean isBusy(LockLevel lockLevel, List<String> path) {if (lockLevel.isHigherOrEqual(level)) {if (busy) return true;- String s = path.get(level.level);+ String s = path.get(level.getHeight());if (kids == null || kids.get(s) == null) return false;return kids.get(s).isBusy(lockLevel, path);} else {@@ -155,10 +167,10 @@ public class LockTree {if (isLocked()) return null;return myLock = new LockImpl(this);} else {- String childName = path.get(level.level);+ String childName = path.get(level.getHeight());Node child = children.get(childName);if (child == null)- children.put(childName, child = new Node(childName, LockLevel.getLevel(level.level + 1), this));+ children.put(childName, child = new Node(childName, level.getChild(), this));return child.lock(lockLevel, path);}}@@ -168,14 +180,6 @@ public class LockTree {if (mom != null) mom.constructPath(collect);return collect;}-- void clear() {- if (myLock != null) {- log.warn("lock_is_leaked at {}", constructPath(new LinkedList<>()));- myLock = null;- }- for (Node node : children.values()) node.clear();- }}static final Lock FREELOCK = () -> {};diff --git a/solr/core/src/java/org/apache/solr/cloud/OverseerConfigSetMessageHandler.java b/solr/core/src/java/org/apache/solr/cloud/OverseerConfigSetMessageHandler.javaindex ebb460dce35..4f5b28f83e3 100644--- a/solr/core/src/java/org/apache/solr/cloud/OverseerConfigSetMessageHandler.java+++ b/solr/core/src/java/org/apache/solr/cloud/OverseerConfigSetMessageHandler.java@@ -150,7 +150,7 @@ public class OverseerConfigSetMessageHandler implements OverseerMessageHandler {}@Override- public Lock lockTask(ZkNodeProps message, OverseerTaskProcessor.TaskBatch taskBatch) {+ public Lock lockTask(ZkNodeProps message, long ignored) {String configSetName = getTaskKey(message);if (canExecute(configSetName, message)) {markExclusiveTask(configSetName, message);diff --git a/solr/core/src/java/org/apache/solr/cloud/OverseerMessageHandler.java b/solr/core/src/java/org/apache/solr/cloud/OverseerMessageHandler.javaindex 1a40a0a539e..f4601ae844e 100644--- a/solr/core/src/java/org/apache/solr/cloud/OverseerMessageHandler.java+++ b/solr/core/src/java/org/apache/solr/cloud/OverseerMessageHandler.java@@ -47,10 +47,11 @@ public interface OverseerMessageHandler {void unlock();}- /**Try to provide an exclusive lock for this particular task- * return null if locking is not possible. If locking is not necessary+ /**+ * Grabs an exclusive lock for this particular task.+ * @return <code>null</code> if locking is not possible.*/- Lock lockTask(ZkNodeProps message, OverseerTaskProcessor.TaskBatch taskBatch);+ Lock lockTask(ZkNodeProps message, long batchSessionId);/*** @param message the message being processeddiff --git a/solr/core/src/java/org/apache/solr/cloud/OverseerTaskProcessor.java b/solr/core/src/java/org/apache/solr/cloud/OverseerTaskProcessor.javaindex cf860335f3b..720222c085a 100644--- a/solr/core/src/java/org/apache/solr/cloud/OverseerTaskProcessor.java+++ b/solr/core/src/java/org/apache/solr/cloud/OverseerTaskProcessor.java@@ -20,12 +20,12 @@ import java.io.Closeable;import java.lang.invoke.MethodHandles;import java.util.ArrayList;import java.util.Collections;-import java.util.HashMap;-import java.util.HashSet;+import java.util.Iterator;import java.util.LinkedHashMap;import java.util.List;import java.util.Map;import java.util.Set;+import java.util.concurrent.ConcurrentHashMap;import java.util.concurrent.ExecutorService;import java.util.concurrent.SynchronousQueue;import java.util.concurrent.TimeUnit;@@ -81,11 +81,11 @@ public class OverseerTaskProcessor implements Runnable, Closeable {private DistributedMap completedMap;private DistributedMap failureMap;- // Set that maintains a list of all the tasks that are running. This is keyed on zk id of the task.+ /** Set that maintains a list of all the tasks that are running. This is keyed on zk id of the task. */final private Set<String> runningTasks;- // List of completed tasks. This is used to clean up workQueue in zk.- final private HashMap<String, QueueEvent> completedTasks;+ /** List of completed tasks. This is used to clean up workQueue in zk. */+ final private ConcurrentHashMap<String, QueueEvent> completedTasks;private volatile String myId;@@ -95,16 +95,25 @@ public class OverseerTaskProcessor implements Runnable, Closeable {private volatile Stats stats;- // Set of tasks that have been picked up for processing but not cleaned up from zk work-queue.- // It may contain tasks that have completed execution, have been entered into the completed/failed map in zk but not- // deleted from the work-queue as that is a batched operation.+ /**+ * Set of tasks that have been picked up for processing but not cleaned up from zk work-queue.+ * It may contain tasks that have completed execution, have been entered into the completed/failed map in zk but not+ * deleted from the work-queue as that is a batched operation.+ */final private Set<String> runningZKTasks;- // This map may contain tasks which are read from work queue but could not- // be executed because they are blocked or the execution queue is full- // This is an optimization to ensure that we do not read the same tasks- // again and again from ZK.++ /**+ * This map may contain tasks which are read from work queue but could not+ * be executed because they are blocked or the execution queue is full+ * This is an optimization to ensure that we do not read the same tasks+ * again and again from ZK.+ */final private Map<String, QueueEvent> blockedTasks = Collections.synchronizedMap(new LinkedHashMap<>());- final private Predicate<String> excludedTasks = new Predicate<String>() {++ /**+ * Predicate used to filter out tasks from the Zookeeper queue that should not be returned for processing.+ */+ final private Predicate<String> excludedTasks = new Predicate<>() {@Overridepublic boolean test(String s) {return runningTasks.contains(s) || blockedTasks.containsKey(s);@@ -114,7 +123,6 @@ public class OverseerTaskProcessor implements Runnable, Closeable {public String toString() {return StrUtils.join(ImmutableSet.of(runningTasks, blockedTasks.keySet()), ',');}-};private final Object waitLock = new Object();@@ -142,9 +150,9 @@ public class OverseerTaskProcessor implements Runnable, Closeable {this.runningMap = runningMap;this.completedMap = completedMap;this.failureMap = failureMap;- this.runningZKTasks = new HashSet<>();- this.runningTasks = new HashSet<>();- this.completedTasks = new HashMap<>();+ this.runningZKTasks = ConcurrentHashMap.newKeySet();+ this.runningTasks = ConcurrentHashMap.newKeySet();+ this.completedTasks = new ConcurrentHashMap<>();thisNode = Utils.getMDCNode();}@@ -195,8 +203,13 @@ public class OverseerTaskProcessor implements Runnable, Closeable {// TODO: Make maxThreads configurable.this.tpe = new ExecutorUtil.MDCAwareThreadPoolExecutor(5, MAX_PARALLEL_TASKS, 0L, TimeUnit.MILLISECONDS,- new SynchronousQueue<Runnable>(),+ new SynchronousQueue<>(),new SolrNamedThreadFactory("OverseerThreadFactory"));++ // In OverseerCollectionMessageHandler, a new Session needs to be created for each new iteration over the tasks in the+ // queue. Incrementing this id causes a new session to be created there.+ long batchSessionId = 0;+try {while (!this.isClosed) {try {@@ -209,7 +222,7 @@ public class OverseerTaskProcessor implements Runnable, Closeable {}if (log.isDebugEnabled()) {- log.debug("Cleaning up work-queue. #Running tasks: {} #Completed tasks: {}", runningTasksSize(), completedTasks.size());+ log.debug("Cleaning up work-queue. #Running tasks: {} #Completed tasks: {}", runningTasks.size(), completedTasks.size());}cleanUpWorkQueue();@@ -217,7 +230,7 @@ public class OverseerTaskProcessor implements Runnable, Closeable {boolean waited = false;- while (runningTasksSize() > MAX_PARALLEL_TASKS) {+ while (runningTasks.size() > MAX_PARALLEL_TASKS) {synchronized (waitLock) {waitLock.wait(100);//wait for 100 ms or till a task is complete}@@ -227,7 +240,6 @@ public class OverseerTaskProcessor implements Runnable, Closeable {if (waited)cleanUpWorkQueue();-ArrayList<QueueEvent> heads = new ArrayList<>(blockedTasks.size() + MAX_PARALLEL_TASKS);heads.addAll(blockedTasks.values());@@ -236,14 +248,26 @@ public class OverseerTaskProcessor implements Runnable, Closeable {// to clear out at least a few items in the queue before we read more itemsif (heads.size() < MAX_BLOCKED_TASKS) {//instead of reading MAX_PARALLEL_TASKS items always, we should only fetch as much as we can execute- int toFetch = Math.min(MAX_BLOCKED_TASKS - heads.size(), MAX_PARALLEL_TASKS - runningTasksSize());+ int toFetch = Math.min(MAX_BLOCKED_TASKS - heads.size(), MAX_PARALLEL_TASKS - runningTasks.size());List<QueueEvent> newTasks = workQueue.peekTopN(toFetch, excludedTasks, 2000L);if (log.isDebugEnabled()) {log.debug("Got {} tasks from work-queue : [{}]", newTasks.size(), newTasks);}+ // heads has at most MAX_BLOCKED_TASKS tasks.heads.addAll(newTasks);} else {- // Prevent free-spinning this loop.+ // The sleep below slows down spinning when heads is full from previous work dispatch attempt below and no new+ // tasks got executed (all executors are busy or all waiting tasks require locks currently held by executors).+ //+ // When heads is not full but no progress was made (no new work got dispatched in the for loop below), slowing down+ // of the spinning is done by the wait time in the call to workQueue.peekTopN() above.+ // (at least in theory because the method eventually called from there is ZkDistributedQueue.peekElements()+ // and because it filters out entries that have just completed on a Runner thread in a different way than the+ // predicate based filtering, it can return quickly without waiting the configured delay time. Therefore spinning+ // can be observed, likely something to clean up at some point).+ //+ // If heads is not empty and new tasks appeared in the queue there's no delay, workQueue.peekTopN() above will+ // return immediately.Thread.sleep(1000);}@@ -253,25 +277,25 @@ public class OverseerTaskProcessor implements Runnable, Closeable {continue;}- blockedTasks.clear(); // clear it now; may get refilled below.+ // clear the blocked tasks, may get refilled below. Given blockedTasks can only get entries from heads and heads+ // has at most MAX_BLOCKED_TASKS tasks, blockedTasks will never exceed MAX_BLOCKED_TASKS entries.+ // Note blockedTasks can't be cleared too early as it is used in the excludedTasks Predicate above.+ blockedTasks.clear();++ // Trigger the creation of a new Session used for locking when/if a lock is later acquired on the OverseerCollectionMessageHandler+ batchSessionId++;- taskBatch.batchId++;boolean tooManyTasks = false;for (QueueEvent head : heads) {if (!tooManyTasks) {- synchronized (runningTasks) {- tooManyTasks = runningTasksSize() >= MAX_PARALLEL_TASKS;- }+ tooManyTasks = runningTasks.size() >= MAX_PARALLEL_TASKS;}if (tooManyTasks) {// Too many tasks are running, just shove the rest into the "blocked" queue.- if(blockedTasks.size() < MAX_BLOCKED_TASKS)- blockedTasks.put(head.getId(), head);+ blockedTasks.put(head.getId(), head);continue;}- synchronized (runningZKTasks) {- if (runningZKTasks.contains(head.getId())) continue;- }+ if (runningZKTasks.contains(head.getId())) continue;final ZkNodeProps message = ZkNodeProps.load(head.getBytes());final String asyncId = message.getStr(ASYNC);if (hasLeftOverItems) {@@ -290,14 +314,12 @@ public class OverseerTaskProcessor implements Runnable, Closeable {continue;}OverseerMessageHandler messageHandler = selector.selectOverseerMessageHandler(message);- OverseerMessageHandler.Lock lock = messageHandler.lockTask(message, taskBatch);+ OverseerMessageHandler.Lock lock = messageHandler.lockTask(message, batchSessionId);if (lock == null) {if (log.isDebugEnabled()) {log.debug("Exclusivity check failed for [{}]", message);}- //we may end crossing the size of the MAX_BLOCKED_TASKS. They are fine- if (blockedTasks.size() < MAX_BLOCKED_TASKS)- blockedTasks.put(head.getId(), head);+ blockedTasks.put(head.getId(), head);continue;}try {@@ -353,21 +375,13 @@ public class OverseerTaskProcessor implements Runnable, Closeable {}}- private int runningTasksSize() {- synchronized (runningTasks) {- return runningTasks.size();- }- }-private void cleanUpWorkQueue() throws KeeperException, InterruptedException {- synchronized (completedTasks) {- for (Map.Entry<String, QueueEvent> entry : completedTasks.entrySet()) {- workQueue.remove(entry.getValue());- synchronized (runningZKTasks) {- runningZKTasks.remove(entry.getKey());- }- }- completedTasks.clear();+ Iterator<Map.Entry<String, QueueEvent>> it = completedTasks.entrySet().iterator();+ while (it.hasNext()) {+ Map.Entry<String, QueueEvent> entry = it.next();+ workQueue.remove(entry.getValue());+ runningZKTasks.remove(entry.getKey());+ it.remove();}}@@ -470,14 +484,8 @@ public class OverseerTaskProcessor implements Runnable, Closeable {@SuppressWarnings("unchecked")private void markTaskAsRunning(QueueEvent head, String asyncId)throws KeeperException, InterruptedException {- synchronized (runningZKTasks) {- runningZKTasks.add(head.getId());- }-- synchronized (runningTasks) {- runningTasks.add(head.getId());- }-+ runningZKTasks.add(head.getId());+ runningTasks.add(head.getId());if (asyncId != null)runningMap.put(asyncId, null);@@ -575,15 +583,9 @@ public class OverseerTaskProcessor implements Runnable, Closeable {}}- private void markTaskComplete(String id, String asyncId)- throws KeeperException, InterruptedException {- synchronized (completedTasks) {- completedTasks.put(id, head);- }-- synchronized (runningTasks) {- runningTasks.remove(id);- }+ private void markTaskComplete(String id, String asyncId) throws KeeperException, InterruptedException {+ completedTasks.put(id, head);+ runningTasks.remove(id);if (asyncId != null) {if (!runningMap.remove(asyncId)) {@@ -603,10 +605,7 @@ public class OverseerTaskProcessor implements Runnable, Closeable {}}- synchronized (runningTasks) {- runningTasks.remove(id);- }-+ runningTasks.remove(id);} catch (KeeperException e) {SolrException.log(log, "", e);} catch (InterruptedException e) {@@ -633,25 +632,13 @@ public class OverseerTaskProcessor implements Runnable, Closeable {private void printTrackingMaps() {if (log.isDebugEnabled()) {- synchronized (runningTasks) {- log.debug("RunningTasks: {}", runningTasks);- }- if (log.isDebugEnabled()) {- log.debug("BlockedTasks: {}", blockedTasks.keySet());- }- synchronized (completedTasks) {- if (log.isDebugEnabled()) {- log.debug("CompletedTasks: {}", completedTasks.keySet());- }- }- synchronized (runningZKTasks) {- log.info("RunningZKTasks: {}", runningZKTasks);- }+ log.debug("RunningTasks: {}", runningTasks);+ log.debug("BlockedTasks: {}", blockedTasks.keySet()); // logOk+ log.debug("CompletedTasks: {}", completedTasks.keySet()); // logOk+ log.debug("RunningZKTasks: {}", runningZKTasks); // logOk}}--String getId(){return myId;}@@ -666,21 +653,4 @@ public class OverseerTaskProcessor implements Runnable, Closeable {public interface OverseerMessageHandlerSelector extends Closeable {OverseerMessageHandler selectOverseerMessageHandler(ZkNodeProps message);}-- final private TaskBatch taskBatch = new TaskBatch();-- public class TaskBatch {- private long batchId = 0;-- public long getId() {- return batchId;- }-- public int getRunningTasks() {- synchronized (runningTasks) {- return runningTasks.size();- }- }- }-}diff --git a/solr/core/src/java/org/apache/solr/cloud/api/collections/OverseerCollectionMessageHandler.java b/solr/core/src/java/org/apache/solr/cloud/api/collections/OverseerCollectionMessageHandler.javaindex 07ce33d27be..63366a81aef 100644--- a/solr/core/src/java/org/apache/solr/cloud/api/collections/OverseerCollectionMessageHandler.java+++ b/solr/core/src/java/org/apache/solr/cloud/api/collections/OverseerCollectionMessageHandler.java@@ -50,7 +50,6 @@ import org.apache.solr.cloud.Overseer;import org.apache.solr.cloud.OverseerMessageHandler;import org.apache.solr.cloud.OverseerNodePrioritizer;import org.apache.solr.cloud.OverseerSolrResponse;-import org.apache.solr.cloud.OverseerTaskProcessor;import org.apache.solr.cloud.Stats;import org.apache.solr.cloud.ZkController;import org.apache.solr.cloud.overseer.OverseerAction;@@ -867,26 +866,31 @@ public class OverseerCollectionMessageHandler implements OverseerMessageHandler,}+ // -1 is not a possible batchSessionId so -1 will force initialization of lockSessionprivate long sessionId = -1;private LockTree.Session lockSession;+ /**+ * Grabs an exclusive lock for this particular task.+ * @return <code>null</code> if locking is not possible. When locking is not possible, it will remain+ * impossible for the passed value of <code>batchSessionId</code>. This is to guarantee tasks are executed+ * in queue order (and a later task is not run earlier than its turn just because it happens that a lock got released).+ */@Override- public Lock lockTask(ZkNodeProps message, OverseerTaskProcessor.TaskBatch taskBatch) {- if (lockSession == null || sessionId != taskBatch.getId()) {+ public Lock lockTask(ZkNodeProps message, long batchSessionId) {+ if (sessionId != batchSessionId) {//this is always called in the same thread.//Each batch is supposed to have a new taskBatch//So if taskBatch changes we must create a new Session- // also check if the running tasks are empty. If yes, clear lockTree- // this will ensure that locks are not 'leaked'- if(taskBatch.getRunningTasks() == 0) lockTree.clear();lockSession = lockTree.getSession();+ sessionId = batchSessionId;}+return lockSession.lock(getCollectionAction(message.getStr(Overseer.QUEUE_OPERATION)),Arrays.asList(getTaskKey(message),message.getStr(ZkStateReader.SHARD_ID_PROP),message.getStr(ZkStateReader.REPLICA_PROP))-);}diff --git a/solr/solrj/src/java/org/apache/solr/common/params/CollectionParams.java b/solr/solrj/src/java/org/apache/solr/common/params/CollectionParams.javaindex 8e8a027b022..fce970fa340 100644--- a/solr/solrj/src/java/org/apache/solr/common/params/CollectionParams.java+++ b/solr/solrj/src/java/org/apache/solr/common/params/CollectionParams.java@@ -42,31 +42,30 @@ public interface CollectionParams {enum LockLevel {- CLUSTER(0),- COLLECTION(1),- SHARD(2),- REPLICA(3),- NONE(10);-- public final int level;-- LockLevel(int i) {- this.level = i;+ NONE(10, null),+ REPLICA(3, null),+ SHARD(2, REPLICA),+ COLLECTION(1, SHARD),+ CLUSTER(0, COLLECTION);++ private final int height;+ private final LockLevel child;++ LockLevel(int height, LockLevel child) {+ this.height = height;+ this.child = child;}public LockLevel getChild() {- return getLevel(level + 1);+ return this.child;}- public static LockLevel getLevel(int i) {- for (LockLevel v : values()) {- if (v.level == i) return v;- }- return null;+ public int getHeight() {+ return this.height;}public boolean isHigherOrEqual(LockLevel that) {- return that.level <= level;+ return height >= that.height;}}