Skip to content

Apache Lucene open-source search software

SOLR-7590: Finish and improve MDC context logging support.

Mark Robert Millerfeb1f86d84d1
diff --git a/solr/CHANGES.txt b/solr/CHANGES.txt
index 91e62ef8445..062eb4c0e83 100644
--- a/solr/CHANGES.txt
+++ b/solr/CHANGES.txt
@@ -100,6 +100,8 @@ Other Changes
* SOLR-7146: MiniSolrCloudCluster based tests can fail with ZooKeeperException NoNode for /live_nodes.
(Vamsee Yarlagadda via shalin)
+* SOLR-7590: Finish and improve MDC context logging support. (Mark Miller)
+
================== 5.2.0 ==================
Consult the LUCENE_CHANGES.txt file for additional, low level, changes in this release
diff --git a/solr/core/src/java/org/apache/solr/SolrLogFormatter.java b/solr/core/src/java/org/apache/solr/SolrLogFormatter.java
deleted file mode 100644
index ff1cf222c63..00000000000
--- a/solr/core/src/java/org/apache/solr/SolrLogFormatter.java
+++ /dev/null
@@ -1,461 +0,0 @@
-package org.apache.solr;
-
-/*
- * 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.
- */
-
-import java.util.Collections;
-import java.util.HashMap;
-import java.util.Map;
-import java.util.WeakHashMap;
-import java.util.logging.ConsoleHandler;
-import java.util.logging.Formatter;
-import java.util.logging.Handler;
-import java.util.logging.Level;
-import java.util.logging.LogRecord;
-import java.util.logging.Logger;
-
-import org.apache.solr.cloud.ZkController;
-import org.apache.solr.common.SolrException;
-import org.apache.solr.common.cloud.Replica;
-import org.apache.solr.core.SolrCore;
-import org.apache.solr.request.SolrQueryRequest;
-import org.apache.solr.request.SolrRequestInfo;
-import org.slf4j.LoggerFactory;
-
-public class SolrLogFormatter extends Formatter {
-
- /** Add this interface to a thread group and the string returned by
- * getTag() will appear in log statements of any threads under that group.
- */
- public static interface TG {
- public String getTag();
- }
-
- long startTime = System.currentTimeMillis();
- long lastTime = startTime;
- Map<Method, String> methodAlias = new HashMap<>();
-
- public static class Method {
- public String className;
- public String methodName;
-
- public Method(String className, String methodName) {
- this.className = className;
- this.methodName = methodName;
- }
-
- @Override
- public int hashCode() {
- return className.hashCode() + methodName.hashCode();
- }
-
- @Override
- public boolean equals(Object obj) {
- if (!(obj instanceof Method)) return false;
- Method other = (Method)obj;
- return (className.equals(other.className) && methodName.equals(other.methodName));
- }
-
- @Override
- public String toString() {
- return className + '.' + methodName;
- }
- }
-
-
- public SolrLogFormatter() {
- super();
-
- methodAlias.put(new Method("org.apache.solr.update.processor.LogUpdateProcessor","finish"), "UPDATE");
- methodAlias.put(new Method("org.apache.solr.core.SolrCore","execute"), "REQ");
- }
-
-
- // TODO: name this better... it's only for cloud tests where every core container has just one solr server so Port/Core are fine
- public boolean shorterFormat = false;
-
- /** Removes info that is redundant for current cloud tests including core name, webapp, and common labels path= and params=
- * [] webapp=/solr path=/select params={q=foobarbaz} hits=0 status=0 QTime=1
- * /select {q=foobarbaz} hits=0 status=0 QTime=1
- * NOTE: this is a work in progress and different settings may be ideal for other types of tests.
- */
- public void setShorterFormat() {
- shorterFormat = true;
- // looking at /update is enough... we don't need "UPDATE /update"
- methodAlias.put(new Method("org.apache.solr.update.processor.LogUpdateProcessor","finish"), "");
- }
-
- public static class CoreInfo {
- static int maxCoreNum;
- String shortId;
- String url;
- Map<String, Object> coreProps;
- }
-
- Map<SolrCore, CoreInfo> coreInfoMap = new WeakHashMap<>(); // TODO: use something that survives across a core reload?
-
- public Map<String,String> classAliases = new HashMap<>();
-
- @Override
- public String format(LogRecord record) {
- try {
- return _format(record);
- } catch (Exception e) {
- // logging swallows exceptions, so if we hit an exception we need to convert it to a string to see it
- return "ERROR IN SolrLogFormatter! original message:" + record.getMessage() + "\n\tException: " + SolrException.toStr(e);
- }
- }
-
-
- public void appendThread(StringBuilder sb, LogRecord record) {
- Thread th = Thread.currentThread();
-
-
-/******
- sb.append(" T=");
- sb.append(th.getName()).append(' ');
-
- // NOTE: tried creating a thread group around jetty but we seem to lose it and request
- // threads are in the normal "main" thread group
- ThreadGroup tg = th.getThreadGroup();
- while (tg != null) {
-sb.append("(group_name=").append(tg.getName()).append(")");
-
- if (tg instanceof TG) {
- sb.append(((TG)tg).getTag());
- sb.append('/');
- }
- try {
- tg = tg.getParent();
- } catch (Throwable e) {
- tg = null;
- }
- }
- ******/
-
- // NOTE: LogRecord.getThreadID is *not* equal to Thread.getId()
- sb.append(" T");
- sb.append(th.getId());
- }
-
-
- public String _format(LogRecord record) {
- String message = record.getMessage();
-
- StringBuilder sb = new StringBuilder(message.length() + 80);
-
- long now = record.getMillis();
- long timeFromStart = now - startTime;
- long timeSinceLast = now - lastTime;
- lastTime = now;
- String shortClassName = getShortClassName(record.getSourceClassName(), record.getSourceMethodName());
-
-/***
- sb.append(timeFromStart).append(' ').append(timeSinceLast);
- sb.append(' ');
- sb.append(record.getSourceClassName()).append('.').append(record.getSourceMethodName());
- sb.append(' ');
- sb.append(record.getLevel());
-***/
-
- SolrRequestInfo requestInfo = SolrRequestInfo.getRequestInfo();
- SolrQueryRequest req = requestInfo == null ? null : requestInfo.getReq();
- SolrCore core = req == null ? null : req.getCore();
- ZkController zkController = null;
- CoreInfo info = null;
-
- if (core != null) {
- info = coreInfoMap.get(core);
- if (info == null) {
- info = new CoreInfo();
- info.shortId = "C"+Integer.toString(CoreInfo.maxCoreNum++);
- coreInfoMap.put(core, info);
-
- if (sb.length() == 0) sb.append("ASYNC ");
- sb.append(" NEW_CORE "+info.shortId);
- sb.append(" name=" + core.getName());
- sb.append(" " + core);
- }
-
- if (zkController == null) {
- zkController = core.getCoreDescriptor().getCoreContainer().getZkController();
- }
- if (zkController != null) {
- if (info.url == null) {
- info.url = zkController.getBaseUrl() + "/" + core.getName();
- sb.append(" url="+info.url + " node="+zkController.getNodeName());
- }
-
- Map<String, Object> coreProps = getReplicaProps(zkController, core);
- if (info.coreProps == null || !coreProps.equals(info.coreProps)) {
- info.coreProps = coreProps;
- final String corePropsString = "coll:" + core.getCoreDescriptor().getCloudDescriptor().getCollectionName() + " core:" + core.getName() + " props:" + coreProps;
- sb.append(" " + info.shortId + "_STATE=" + corePropsString);
- }
- }
- }
-
-
- if (sb.length() > 0) sb.append('\n');
- sb.append(timeFromStart);
-
-// sb.append("\nL").append(record.getSequenceNumber()); // log number is useful for sequencing when looking at multiple parts of a log file, but ms since start should be fine.
- appendThread(sb, record);
-
-
- if (info != null) {
- sb.append(' ').append(info.shortId); // core
- }
- if (zkController != null) {
- sb.append(" P").append(zkController.getHostPort()); // todo: should be able to get this from core container for non zk tests
- }
-
- if (shortClassName.length() > 0) {
- sb.append(' ').append(shortClassName);
- }
-
- if (record.getLevel() != Level.INFO) {
- sb.append(' ').append(record.getLevel());
- }
-
- sb.append(' ');
- appendMultiLineString(sb, message);
- Throwable th = record.getThrown();
- if (th != null) {
- sb.append(' ');
- String err = SolrException.toStr(th);
- String ignoredMsg = SolrException.doIgnore(th, err);
- if (ignoredMsg != null) {
- sb.append(ignoredMsg);
- } else {
- sb.append(err);
- }
- }
-
- sb.append('\n');
-
- /*** Isn't core specific... prob better logged from zkController
- if (info != null) {
- ClusterState clusterState = zkController.getClusterState();
- if (info.clusterState != clusterState) {
- // something has changed in the matrix...
- sb.append(zkController.getBaseUrl() + " sees new ClusterState:");
- }
- }
- ***/
-
- return sb.toString();
- }
-
- private Map<String,Object> getReplicaProps(ZkController zkController, SolrCore core) {
- final String collection = core.getCoreDescriptor().getCloudDescriptor().getCollectionName();
- Replica replica = zkController.getClusterState().getReplica(collection, core.getCoreDescriptor().getCloudDescriptor().getCoreNodeName());
- if(replica!=null) {
- return replica.getProperties();
- }
- return Collections.EMPTY_MAP;
- }
-
-
- private Method classAndMethod = new Method(null,null); // don't need to be thread safe
- private String getShortClassName(String name, String method) {
- classAndMethod.className = name;
- classAndMethod.methodName = method;
-
- String out = methodAlias.get(classAndMethod);
- if (out != null) return out;
-
- StringBuilder sb = new StringBuilder();
-
- int lastDot = name.lastIndexOf('.');
- if (lastDot < 0) return name + '.' + method;
-
- int prevIndex = -1;
- for (;;) {
- char ch = name.charAt(prevIndex + 1);
- sb.append(ch);
- int idx = name.indexOf('.', prevIndex+1);
- ch = name.charAt(idx+1);
- if (idx >= lastDot || Character.isUpperCase(ch)) {
- sb.append(name.substring(idx));
- break;
- }
- prevIndex = idx;
- }
-
- return sb.toString() + '.' + method;
- }
-
- private void addFirstLine(StringBuilder sb, String msg) {
-// INFO: [] webapp=/solr path=/select params={q=foobarbaz} hits=0 status=0 QTime=1
-
- if (!shorterFormat || !msg.startsWith("[")) {
- sb.append(msg);
- return;
- }
-
- int idx = msg.indexOf(']');
- if (idx < 0 || !msg.startsWith(" webapp=", idx+1)) {
- sb.append(msg);
- return;
- }
-
- idx = msg.indexOf(' ',idx+8); // space after webapp=
- if (idx < 0) { sb.append(msg); return; }
- idx = msg.indexOf('=',idx+1); // = in path=
- if (idx < 0) { sb.append(msg); return; }
-
- int idx2 = msg.indexOf(' ',idx+1);
- if (idx2 < 0) { sb.append(msg); return; }
-
-
- sb.append(msg.substring(idx+1, idx2+1)); // path
-
- idx = msg.indexOf("params=", idx2);
- if (idx < 0) {
- sb.append(msg.substring(idx2));
- } else {
- sb.append(msg.substring(idx+7));
- }
- }
-
- private void appendMultiLineString(StringBuilder sb, String msg) {
- int idx = msg.indexOf('\n');
- if (idx < 0) {
- addFirstLine(sb, msg);
- return;
- }
-
- int lastIdx = -1;
- for (;;) {
- if (idx < 0) {
- if (lastIdx == -1) {
- addFirstLine(sb, msg.substring(lastIdx+1));
- } else {
- sb.append(msg.substring(lastIdx+1));
- }
- break;
- }
- if (lastIdx == -1) {
- addFirstLine(sb, msg.substring(lastIdx+1, idx));
- } else {
- sb.append(msg.substring(lastIdx+1, idx));
- }
-
- sb.append("\n\t");
- lastIdx = idx;
- idx = msg.indexOf('\n',lastIdx+1);
- }
- }
-
- @Override
- public String getHead(Handler h) {
- return super.getHead(h);
- }
-
- @Override
- public String getTail(Handler h) {
- return super.getTail(h);
- }
-
- @Override
- public String formatMessage(LogRecord record) {
- return format(record);
- }
-
-
-
- static ThreadLocal<String> threadLocal = new ThreadLocal<>();
-
- public static void main(String[] args) throws Exception {
-
- Handler[] handlers = Logger.getLogger("").getHandlers();
- boolean foundConsoleHandler = false;
- for (int index = 0; index < handlers.length; index++) {
- // set console handler to SEVERE
- if (handlers[index] instanceof ConsoleHandler) {
- handlers[index].setLevel(Level.ALL);
- handlers[index].setFormatter(new SolrLogFormatter());
- foundConsoleHandler = true;
- }
- }
- if (!foundConsoleHandler) {
- // no console handler found
- System.err.println("No consoleHandler found, adding one.");
- ConsoleHandler consoleHandler = new ConsoleHandler();
- consoleHandler.setLevel(Level.ALL);
- consoleHandler.setFormatter(new SolrLogFormatter());
- Logger.getLogger("").addHandler(consoleHandler);
- }
-
-
-
- final org.slf4j.Logger log = LoggerFactory.getLogger(SolrLogFormatter.class);
- log.error("HELLO");
-
- ThreadGroup tg = new MyThreadGroup("YCS");
-
- Thread th = new Thread(tg, "NEW_THREAD") {
-
- @Override
- public void run() {
- try {
- go();
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- };
-
- th.start();
- th.join();
- }
-
-
- static class MyThreadGroup extends ThreadGroup implements TG {
- public MyThreadGroup(String name) {
- super(name);
- }
- @Override
- public String getTag() { return "HELLO"; }
- }
-
- public static void go() throws Exception {
- final org.slf4j.Logger log = LoggerFactory.getLogger(SolrLogFormatter.class);
-
- Thread thread1 = new Thread() {
- @Override
- public void run() {
- threadLocal.set("from thread1");
- log.error("[] webapp=/solr path=/select params={hello} wow");
- }
- };
-
- Thread thread2 = new Thread() {
- @Override
- public void run() {
- threadLocal.set("from thread2");
- log.error("InThread2");
- }
- };
-
- thread1.start();
- thread2.start();
- thread1.join();
- thread2.join();
- }
-}
diff --git a/solr/core/src/java/org/apache/solr/cloud/ElectionContext.java b/solr/core/src/java/org/apache/solr/cloud/ElectionContext.java
index 11763137dd0..62f9913ce9a 100644
--- a/solr/core/src/java/org/apache/solr/cloud/ElectionContext.java
+++ b/solr/core/src/java/org/apache/solr/cloud/ElectionContext.java
@@ -1,5 +1,11 @@
package org.apache.solr.cloud;
+import java.io.Closeable;
+import java.io.IOException;
+import java.util.List;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.TimeUnit;
+
import org.apache.lucene.search.MatchAllDocsQuery;
import org.apache.solr.cloud.overseer.OverseerAction;
import org.apache.solr.common.SolrException;
@@ -15,7 +21,7 @@ import org.apache.solr.common.util.RetryUtil;
import org.apache.solr.common.util.RetryUtil.RetryCmd;
import org.apache.solr.core.CoreContainer;
import org.apache.solr.core.SolrCore;
-import org.apache.solr.logging.MDCUtils;
+import org.apache.solr.logging.MDCLoggingContext;
import org.apache.solr.search.SolrIndexSearcher;
import org.apache.solr.update.UpdateLog;
import org.apache.solr.util.RefCounted;
@@ -25,14 +31,6 @@ import org.apache.zookeeper.KeeperException.NoNodeException;
import org.apache.zookeeper.KeeperException.NodeExistsException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import org.slf4j.MDC;
-
-import java.io.Closeable;
-import java.io.IOException;
-import java.util.List;
-import java.util.Map;
-import java.util.concurrent.ExecutorService;
-import java.util.concurrent.TimeUnit;
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
@@ -117,8 +115,6 @@ class ShardLeaderElectionContextBase extends ElectionContext {
this.shardId = shardId;
this.collection = collection;
- Map previousMDCContext = MDC.getCopyOfContextMap();
- MDCUtils.setMDC(collection, shardId, null, null);
try {
new ZkCmdExecutor(zkStateReader.getZkClient().getZkClientTimeout())
.ensureExists(ZkStateReader.COLLECTIONS_ZKNODE + "/" + collection,
@@ -128,8 +124,6 @@ class ShardLeaderElectionContextBase extends ElectionContext {
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new SolrException(ErrorCode.SERVER_ERROR, e);
- } finally {
- MDCUtils.cleanupMDC(previousMDCContext);
}
}
@@ -203,158 +197,152 @@ final class ShardLeaderElectionContext extends ShardLeaderElectionContextBase {
*/
@Override
void runLeaderProcess(boolean weAreReplacement, int pauseBeforeStart) throws KeeperException,
- InterruptedException, IOException {
- log.info("Running the leader process for shard " + shardId);
-
+ InterruptedException, IOException {
String coreName = leaderProps.getStr(ZkStateReader.CORE_NAME_PROP);
ActionThrottle lt;
try (SolrCore core = cc.getCore(coreName)) {
-
if (core == null) {
cancelElection();
- throw new SolrException(ErrorCode.SERVER_ERROR,
- "SolrCore not found:" + coreName + " in "
- + cc.getCoreNames());
+ throw new SolrException(ErrorCode.SERVER_ERROR, "SolrCore not found:" + coreName + " in " + cc.getCoreNames());
}
-
+ MDCLoggingContext.setCore(core);
lt = core.getUpdateHandler().getSolrCoreState().getLeaderThrottle();
}
-
- lt.minimumWaitBetweenActions();
- lt.markAttemptingAction();
-
- // clear the leader in clusterstate
- ZkNodeProps m = new ZkNodeProps(Overseer.QUEUE_OPERATION, OverseerAction.LEADER.toLower(),
- ZkStateReader.SHARD_ID_PROP, shardId, ZkStateReader.COLLECTION_PROP,
- collection);
- Overseer.getInQueue(zkClient).offer(ZkStateReader.toJSON(m));
-
- int leaderVoteWait = cc.getZkController().getLeaderVoteWait();
- if (!weAreReplacement) {
- waitForReplicasToComeUp(leaderVoteWait);
- }
- try (SolrCore core = cc.getCore(coreName)) {
-
- if (core == null) {
- cancelElection();
- throw new SolrException(ErrorCode.SERVER_ERROR,
- "SolrCore not found:" + coreName + " in "
- + cc.getCoreNames());
- }
-
- // should I be leader?
- if (weAreReplacement && !shouldIBeLeader(leaderProps, core, weAreReplacement)) {
- rejoinLeaderElection(core);
- return;
- }
-
- log.info("I may be the new leader - try and sync");
-
+ try {
+ lt.minimumWaitBetweenActions();
+ lt.markAttemptingAction();
- // we are going to attempt to be the leader
- // first cancel any current recovery
- core.getUpdateHandler().getSolrCoreState().cancelRecovery();
+ log.info("Running the leader process for shard " + shardId);
+ // clear the leader in clusterstate
+ ZkNodeProps m = new ZkNodeProps(Overseer.QUEUE_OPERATION, OverseerAction.LEADER.toLower(),
+ ZkStateReader.SHARD_ID_PROP, shardId, ZkStateReader.COLLECTION_PROP, collection);
+ Overseer.getInQueue(zkClient).offer(ZkStateReader.toJSON(m));
- if (weAreReplacement) {
- // wait a moment for any floating updates to finish
- try {
- Thread.sleep(2500);
- } catch (InterruptedException e) {
- Thread.currentThread().interrupt();
- throw new SolrException(ErrorCode.SERVICE_UNAVAILABLE, e);
- }
+ int leaderVoteWait = cc.getZkController().getLeaderVoteWait();
+ if (!weAreReplacement) {
+ waitForReplicasToComeUp(leaderVoteWait);
}
- boolean success = false;
- try {
- success = syncStrategy.sync(zkController, core, leaderProps, weAreReplacement);
- } catch (Exception e) {
- SolrException.log(log, "Exception while trying to sync", e);
- success = false;
- }
-
- UpdateLog ulog = core.getUpdateHandler().getUpdateLog();
-
- if (!success) {
- boolean hasRecentUpdates = false;
- if (ulog != null) {
- // TODO: we could optimize this if necessary
- UpdateLog.RecentUpdates recentUpdates = ulog.getRecentUpdates();
+ try (SolrCore core = cc.getCore(coreName)) {
+
+ if (core == null) {
+ cancelElection();
+ throw new SolrException(ErrorCode.SERVER_ERROR,
+ "SolrCore not found:" + coreName + " in " + cc.getCoreNames());
+ }
+
+ // should I be leader?
+ if (weAreReplacement && !shouldIBeLeader(leaderProps, core, weAreReplacement)) {
+ rejoinLeaderElection(core);
+ return;
+ }
+
+ log.info("I may be the new leader - try and sync");
+
+ // we are going to attempt to be the leader
+ // first cancel any current recovery
+ core.getUpdateHandler().getSolrCoreState().cancelRecovery();
+
+ if (weAreReplacement) {
+ // wait a moment for any floating updates to finish
try {
- hasRecentUpdates = !recentUpdates.getVersions(1).isEmpty();
- } finally {
- recentUpdates.close();
+ Thread.sleep(2500);
+ } catch (InterruptedException e) {
+ Thread.currentThread().interrupt();
+ throw new SolrException(ErrorCode.SERVICE_UNAVAILABLE, e);
}
}
-
- if (!hasRecentUpdates) {
- // we failed sync, but we have no versions - we can't sync in that case
- // - we were active
- // before, so become leader anyway
- log.info("We failed sync, but we have no versions - we can't sync in that case - we were active before, so become leader anyway");
- success = true;
- }
- }
-
- // solrcloud_debug
- if (log.isDebugEnabled()) {
+
+ boolean success = false;
try {
- RefCounted<SolrIndexSearcher> searchHolder = core
- .getNewestSearcher(false);
- SolrIndexSearcher searcher = searchHolder.get();
+ success = syncStrategy.sync(zkController, core, leaderProps, weAreReplacement);
+ } catch (Exception e) {
+ SolrException.log(log, "Exception while trying to sync", e);
+ success = false;
+ }
+
+ UpdateLog ulog = core.getUpdateHandler().getUpdateLog();
+
+ if (!success) {
+ boolean hasRecentUpdates = false;
+ if (ulog != null) {
+ // TODO: we could optimize this if necessary
+ UpdateLog.RecentUpdates recentUpdates = ulog.getRecentUpdates();
+ try {
+ hasRecentUpdates = !recentUpdates.getVersions(1).isEmpty();
+ } finally {
+ recentUpdates.close();
+ }
+ }
+
+ if (!hasRecentUpdates) {
+ // we failed sync, but we have no versions - we can't sync in that case
+ // - we were active
+ // before, so become leader anyway
+ log.info(
+ "We failed sync, but we have no versions - we can't sync in that case - we were active before, so become leader anyway");
+ success = true;
+ }
+ }
+
+ // solrcloud_debug
+ if (log.isDebugEnabled()) {
try {
- log.debug(core.getCoreDescriptor().getCoreContainer()
- .getZkController().getNodeName()
- + " synched "
- + searcher.search(new MatchAllDocsQuery(), 1).totalHits);
- } finally {
- searchHolder.decref();
+ RefCounted<SolrIndexSearcher> searchHolder = core.getNewestSearcher(false);
+ SolrIndexSearcher searcher = searchHolder.get();
+ try {
+ log.debug(core.getCoreDescriptor().getCoreContainer().getZkController().getNodeName() + " synched "
+ + searcher.search(new MatchAllDocsQuery(), 1).totalHits);
+ } finally {
+ searchHolder.decref();
+ }
+ } catch (Exception e) {
+ log.error("Error in solrcloud_debug block", e);
}
- } catch (Exception e) {
- log.error("Error in solrcloud_debug block", e);
}
- }
- if (!success) {
- rejoinLeaderElection(core);
- return;
- }
-
- log.info("I am the new leader: "
- + ZkCoreNodeProps.getCoreUrl(leaderProps) + " " + shardId);
- core.getCoreDescriptor().getCloudDescriptor().setLeader(true);
- }
-
- boolean isLeader = true;
- try {
- super.runLeaderProcess(weAreReplacement, 0);
- } catch (Exception e) {
- isLeader = false;
- SolrException.log(log, "There was a problem trying to register as the leader", e);
-
- try (SolrCore core = cc.getCore(coreName)) {
-
- if (core == null) {
- log.debug("SolrCore not found:" + coreName + " in " + cc.getCoreNames());
+ if (!success) {
+ rejoinLeaderElection(core);
return;
}
- core.getCoreDescriptor().getCloudDescriptor().setLeader(false);
-
- // we could not publish ourselves as leader - try and rejoin election
- rejoinLeaderElection(core);
+ log.info("I am the new leader: " + ZkCoreNodeProps.getCoreUrl(leaderProps) + " " + shardId);
+ core.getCoreDescriptor().getCloudDescriptor().setLeader(true);
}
- }
-
- if (isLeader) {
- // check for any replicas in my shard that were set to down by the previous leader
+
+ boolean isLeader = true;
try {
- startLeaderInitiatedRecoveryOnReplicas(coreName);
- } catch (Exception exc) {
- // don't want leader election to fail because of
- // an error trying to tell others to recover
+ super.runLeaderProcess(weAreReplacement, 0);
+ } catch (Exception e) {
+ isLeader = false;
+ SolrException.log(log, "There was a problem trying to register as the leader", e);
+
+ try (SolrCore core = cc.getCore(coreName)) {
+
+ if (core == null) {
+ log.debug("SolrCore not found:" + coreName + " in " + cc.getCoreNames());
+ return;
+ }
+
+ core.getCoreDescriptor().getCloudDescriptor().setLeader(false);
+
+ // we could not publish ourselves as leader - try and rejoin election
+ rejoinLeaderElection(core);
+ }
}
- }
+
+ if (isLeader) {
+ // check for any replicas in my shard that were set to down by the previous leader
+ try {
+ startLeaderInitiatedRecoveryOnReplicas(coreName);
+ } catch (Exception exc) {
+ // don't want leader election to fail because of
+ // an error trying to tell others to recover
+ }
+ }
+ } finally {
+ MDCLoggingContext.clear();
+ }
}
private void startLeaderInitiatedRecoveryOnReplicas(String coreName) throws Exception {
@@ -493,8 +481,7 @@ final class ShardLeaderElectionContext extends ShardLeaderElectionContextBase {
}
private boolean shouldIBeLeader(ZkNodeProps leaderProps, SolrCore core, boolean weAreReplacement) {
- log.info("Checking if I (core={},coreNodeName={}) should try and be the leader.", core.getName(),
- core.getCoreDescriptor().getCloudDescriptor().getCoreNodeName());
+ log.info("Checking if I should try and be the leader.");
if (isClosed) {
log.info("Bailing on leader process because we have been closed");
@@ -534,7 +521,7 @@ final class ShardLeaderElectionContext extends ShardLeaderElectionContextBase {
}
final class OverseerElectionContext extends ElectionContext {
-
+ private static Logger log = LoggerFactory.getLogger(OverseerElectionContext.class);
private final SolrZkClient zkClient;
private Overseer overseer;
public static final String PATH = "/overseer_elect";
diff --git a/solr/core/src/java/org/apache/solr/cloud/OverseerCollectionProcessor.java b/solr/core/src/java/org/apache/solr/cloud/OverseerCollectionProcessor.java
index f01ac511c71..2e160c66424 100644
--- a/solr/core/src/java/org/apache/solr/cloud/OverseerCollectionProcessor.java
+++ b/solr/core/src/java/org/apache/solr/cloud/OverseerCollectionProcessor.java
@@ -91,7 +91,7 @@ import org.apache.solr.handler.component.ShardHandler;
import org.apache.solr.handler.component.ShardHandlerFactory;
import org.apache.solr.handler.component.ShardRequest;
import org.apache.solr.handler.component.ShardResponse;
-import org.apache.solr.logging.MDCUtils;
+import org.apache.solr.logging.MDCLoggingContext;
import org.apache.solr.update.SolrIndexSplitter;
import org.apache.solr.util.DefaultSolrThreadFactory;
import org.apache.solr.util.stats.Snapshot;
@@ -998,68 +998,66 @@ public class OverseerCollectionProcessor implements Runnable, Closeable {
}
@SuppressWarnings("unchecked")
- private void deleteReplica(ClusterState clusterState, ZkNodeProps message, NamedList results) throws KeeperException, InterruptedException {
- checkRequired(message, COLLECTION_PROP, SHARD_ID_PROP,REPLICA_PROP);
+ private void deleteReplica(ClusterState clusterState, ZkNodeProps message, NamedList results)
+ throws KeeperException, InterruptedException {
+ checkRequired(message, COLLECTION_PROP, SHARD_ID_PROP, REPLICA_PROP);
String collectionName = message.getStr(COLLECTION_PROP);
String shard = message.getStr(SHARD_ID_PROP);
String replicaName = message.getStr(REPLICA_PROP);
- Map previousMDCContext = MDC.getCopyOfContextMap();
- MDCUtils.setMDC(collectionName, shard, replicaName, null);
+
+ DocCollection coll = clusterState.getCollection(collectionName);
+ Slice slice = coll.getSlice(shard);
+ ShardHandler shardHandler = shardHandlerFactory.getShardHandler();
+ if (slice == null) {
+ throw new SolrException(ErrorCode.BAD_REQUEST,
+ "Invalid shard name : " + shard + " in collection : " + collectionName);
+ }
+ Replica replica = slice.getReplica(replicaName);
+ if (replica == null) {
+ ArrayList<String> l = new ArrayList<>();
+ for (Replica r : slice.getReplicas())
+ l.add(r.getName());
+ throw new SolrException(ErrorCode.BAD_REQUEST, "Invalid replica : " + replicaName + " in shard/collection : "
+ + shard + "/" + collectionName + " available replicas are " + StrUtils.join(l, ','));
+ }
+
+ // If users are being safe and only want to remove a shard if it is down, they can specify onlyIfDown=true
+ // on the command.
+ if (Boolean.parseBoolean(message.getStr(ONLY_IF_DOWN)) && replica.getState() != Replica.State.DOWN) {
+ throw new SolrException(ErrorCode.BAD_REQUEST,
+ "Attempted to remove replica : " + collectionName + "/" + shard + "/" + replicaName
+ + " with onlyIfDown='true', but state is '" + replica.getStr(ZkStateReader.STATE_PROP) + "'");
+ }
+
+ String baseUrl = replica.getStr(ZkStateReader.BASE_URL_PROP);
+ String core = replica.getStr(ZkStateReader.CORE_NAME_PROP);
+
+ // assume the core exists and try to unload it
+ Map m = makeMap("qt", adminPath, CoreAdminParams.ACTION, CoreAdminAction.UNLOAD.toString(), CoreAdminParams.CORE,
+ core, CoreAdminParams.DELETE_INSTANCE_DIR, "true", CoreAdminParams.DELETE_DATA_DIR, "true");
+
+ ShardRequest sreq = new ShardRequest();
+ sreq.purpose = 1;
+ sreq.shards = new String[] {baseUrl};
+ sreq.actualShards = sreq.shards;
+ sreq.params = new ModifiableSolrParams(new MapSolrParams(m));
try {
- DocCollection coll = clusterState.getCollection(collectionName);
- Slice slice = coll.getSlice(shard);
- ShardHandler shardHandler = shardHandlerFactory.getShardHandler();
- if (slice == null) {
- throw new SolrException(ErrorCode.BAD_REQUEST, "Invalid shard name : " + shard + " in collection : " + collectionName);
- }
- Replica replica = slice.getReplica(replicaName);
- if (replica == null) {
- ArrayList<String> l = new ArrayList<>();
- for (Replica r : slice.getReplicas()) l.add(r.getName());
- throw new SolrException(ErrorCode.BAD_REQUEST, "Invalid replica : " + replicaName + " in shard/collection : "
- + shard + "/" + collectionName + " available replicas are " + StrUtils.join(l, ','));
- }
-
- // If users are being safe and only want to remove a shard if it is down, they can specify onlyIfDown=true
- // on the command.
- if (Boolean.parseBoolean(message.getStr(ONLY_IF_DOWN)) && replica.getState() != Replica.State.DOWN) {
- throw new SolrException(ErrorCode.BAD_REQUEST, "Attempted to remove replica : " + collectionName + "/" +
- shard + "/" + replicaName +
- " with onlyIfDown='true', but state is '" + replica.getStr(ZkStateReader.STATE_PROP) + "'");
- }
-
- String baseUrl = replica.getStr(ZkStateReader.BASE_URL_PROP);
- String core = replica.getStr(ZkStateReader.CORE_NAME_PROP);
-
- // assume the core exists and try to unload it
- Map m = makeMap("qt", adminPath, CoreAdminParams.ACTION,
- CoreAdminAction.UNLOAD.toString(), CoreAdminParams.CORE, core,
- CoreAdminParams.DELETE_INSTANCE_DIR, "true",
- CoreAdminParams.DELETE_DATA_DIR, "true");
-
- ShardRequest sreq = new ShardRequest();
- sreq.purpose = 1;
- sreq.shards = new String[]{baseUrl};
- sreq.actualShards = sreq.shards;
- sreq.params = new ModifiableSolrParams(new MapSolrParams(m));
- try {
- shardHandler.submit(sreq, baseUrl, sreq.params);
- } catch (Exception e) {
- log.warn("Exception trying to unload core " + sreq, e);
- }
-
- collectShardResponses(replica.getState() != Replica.State.ACTIVE ? new NamedList() : results,
- false, null, shardHandler);
-
- if (waitForCoreNodeGone(collectionName, shard, replicaName, 5000))
- return;//check if the core unload removed the corenode zk enry
- deleteCoreNode(collectionName, replicaName, replica, core); // try and ensure core info is removed from clusterstate
- if (waitForCoreNodeGone(collectionName, shard, replicaName, 30000)) return;
-
- throw new SolrException(ErrorCode.SERVER_ERROR, "Could not remove replica : " + collectionName + "/" + shard + "/" + replicaName);
- } finally {
- MDCUtils.cleanupMDC(previousMDCContext);
+ shardHandler.submit(sreq, baseUrl, sreq.params);
+ } catch (Exception e) {
+ log.warn("Exception trying to unload core " + sreq, e);
}
+
+ collectShardResponses(replica.getState() != Replica.State.ACTIVE ? new NamedList() : results, false, null,
+ shardHandler);
+
+ if (waitForCoreNodeGone(collectionName, shard, replicaName, 5000)) return;// check if the core unload removed the
+ // corenode zk enry
+ deleteCoreNode(collectionName, replicaName, replica, core); // try and ensure core info is removed from clusterstate
+ if (waitForCoreNodeGone(collectionName, shard, replicaName, 30000)) return;
+
+ throw new SolrException(ErrorCode.SERVER_ERROR,
+ "Could not remove replica : " + collectionName + "/" + shard + "/" + replicaName);
+
}
private boolean waitForCoreNodeGone(String collectionName, String shard, String replicaName, int timeoutms) throws InterruptedException {
@@ -1155,42 +1153,33 @@ public class OverseerCollectionProcessor implements Runnable, Closeable {
private void createAlias(Aliases aliases, ZkNodeProps message) {
String aliasName = message.getStr(NAME);
String collections = message.getStr("collections");
-
- Map previousMDCContext = MDC.getCopyOfContextMap();
- MDCUtils.setCollection(aliasName);
-
+
+ Map<String,Map<String,String>> newAliasesMap = new HashMap<>();
+ Map<String,String> newCollectionAliasesMap = new HashMap<>();
+ Map<String,String> prevColAliases = aliases.getCollectionAliasMap();
+ if (prevColAliases != null) {
+ newCollectionAliasesMap.putAll(prevColAliases);
+ }
+ newCollectionAliasesMap.put(aliasName, collections);
+ newAliasesMap.put("collection", newCollectionAliasesMap);
+ Aliases newAliases = new Aliases(newAliasesMap);
+ byte[] jsonBytes = null;
+ if (newAliases.collectionAliasSize() > 0) { // only sub map right now
+ jsonBytes = ZkStateReader.toJSON(newAliases.getAliasMap());
+ }
try {
- Map<String, Map<String, String>> newAliasesMap = new HashMap<>();
- Map<String, String> newCollectionAliasesMap = new HashMap<>();
- Map<String, String> prevColAliases = aliases.getCollectionAliasMap();
- if (prevColAliases != null) {
- newCollectionAliasesMap.putAll(prevColAliases);
- }
- newCollectionAliasesMap.put(aliasName, collections);
- newAliasesMap.put("collection", newCollectionAliasesMap);
- Aliases newAliases = new Aliases(newAliasesMap);
- byte[] jsonBytes = null;
- if (newAliases.collectionAliasSize() > 0) { // only sub map right now
- jsonBytes = ZkStateReader.toJSON(newAliases.getAliasMap());
- }
- try {
- zkStateReader.getZkClient().setData(ZkStateReader.ALIASES,
- jsonBytes, true);
-
- checkForAlias(aliasName, collections);
- // some fudge for other nodes
- Thread.sleep(100);
- } catch (KeeperException e) {
- log.error("", e);
- throw new SolrException(ErrorCode.SERVER_ERROR, e);
- } catch (InterruptedException e) {
- log.warn("", e);
- throw new SolrException(ErrorCode.SERVER_ERROR, e);
- }
- } finally {
- MDCUtils.cleanupMDC(previousMDCContext);
+ zkStateReader.getZkClient().setData(ZkStateReader.ALIASES, jsonBytes, true);
+
+ checkForAlias(aliasName, collections);
+ // some fudge for other nodes
+ Thread.sleep(100);
+ } catch (KeeperException e) {
+ log.error("", e);
+ throw new SolrException(ErrorCode.SERVER_ERROR, e);
+ } catch (InterruptedException e) {
+ log.warn("", e);
+ throw new SolrException(ErrorCode.SERVER_ERROR, e);
}
-
}
private void checkForAlias(String name, String value) {
@@ -1233,8 +1222,6 @@ public class OverseerCollectionProcessor implements Runnable, Closeable {
private void deleteAlias(Aliases aliases, ZkNodeProps message) {
String aliasName = message.getStr(NAME);
- Map previousMDCContext = MDC.getCopyOfContextMap();
- MDCUtils.setCollection(aliasName);
Map<String,Map<String,String>> newAliasesMap = new HashMap<>();
Map<String,String> newCollectionAliasesMap = new HashMap<>();
@@ -1258,282 +1245,393 @@ public class OverseerCollectionProcessor implements Runnable, Closeable {
} catch (InterruptedException e) {
log.warn("", e);
throw new SolrException(ErrorCode.SERVER_ERROR, e);
- } finally {
- MDCUtils.cleanupMDC(previousMDCContext);
- }
+ }
}
private boolean createShard(ClusterState clusterState, ZkNodeProps message, NamedList results)
throws KeeperException, InterruptedException {
- Map previousMDCContext = MDC.getCopyOfContextMap();
String collectionName = message.getStr(COLLECTION_PROP);
String sliceName = message.getStr(SHARD_ID_PROP);
-
- MDCUtils.setMDC(collectionName, sliceName, null, null);
- try {
- log.info("Create shard invoked: {}", message);
- if (collectionName == null || sliceName == null)
- throw new SolrException(ErrorCode.BAD_REQUEST, "'collection' and 'shard' are required parameters");
- int numSlices = 1;
-
- ShardHandler shardHandler = shardHandlerFactory.getShardHandler();
- DocCollection collection = clusterState.getCollection(collectionName);
- int repFactor = message.getInt(REPLICATION_FACTOR, collection.getInt(REPLICATION_FACTOR, 1));
- String createNodeSetStr = message.getStr(CREATE_NODE_SET);
- List<Node> sortedNodeList = getNodesForNewShard(clusterState, collectionName, sliceName, repFactor,
- createNodeSetStr, overseer.getZkController().getCoreContainer());
-
- Overseer.getInQueue(zkStateReader.getZkClient()).offer(ZkStateReader.toJSON(message));
- // wait for a while until we see the shard
- long waitUntil = System.nanoTime() + TimeUnit.NANOSECONDS.convert(30, TimeUnit.SECONDS);
- boolean created = false;
- while (System.nanoTime() < waitUntil) {
- Thread.sleep(100);
- created = zkStateReader.getClusterState().getCollection(collectionName).getSlice(sliceName) != null;
- if (created) break;
- }
- if (!created)
- throw new SolrException(ErrorCode.SERVER_ERROR, "Could not fully create shard: " + message.getStr(NAME));
-
-
- String configName = message.getStr(COLL_CONF);
- for (int j = 1; j <= repFactor; j++) {
- String nodeName = sortedNodeList.get(((j - 1)) % sortedNodeList.size()).nodeName;
- String shardName = collectionName + "_" + sliceName + "_replica" + j;
- log.info("Creating shard " + shardName + " as part of slice "
- + sliceName + " of collection " + collectionName + " on "
- + nodeName);
-
- // Need to create new params for each request
- ModifiableSolrParams params = new ModifiableSolrParams();
- params.set(CoreAdminParams.ACTION, CoreAdminAction.CREATE.toString());
-
- params.set(CoreAdminParams.NAME, shardName);
- params.set(COLL_CONF, configName);
- params.set(CoreAdminParams.COLLECTION, collectionName);
- params.set(CoreAdminParams.SHARD, sliceName);
- params.set(ZkStateReader.NUM_SHARDS_PROP, numSlices);
- addPropertyParams(message, params);
-
- ShardRequest sreq = new ShardRequest();
- params.set("qt", adminPath);
- sreq.purpose = 1;
- String replica = zkStateReader.getBaseUrlForNodeName(nodeName);
- sreq.shards = new String[]{replica};
- sreq.actualShards = sreq.shards;
- sreq.params = params;
-
- shardHandler.submit(sreq, replica, sreq.params);
-
- }
-
- processResponses(results, shardHandler);
-
- log.info("Finished create command on all shards for collection: "
- + collectionName);
-
- return true;
- } finally {
- MDCUtils.cleanupMDC(previousMDCContext);
+
+ log.info("Create shard invoked: {}", message);
+ if (collectionName == null || sliceName == null)
+ throw new SolrException(ErrorCode.BAD_REQUEST, "'collection' and 'shard' are required parameters");
+ int numSlices = 1;
+
+ ShardHandler shardHandler = shardHandlerFactory.getShardHandler();
+ DocCollection collection = clusterState.getCollection(collectionName);
+ int repFactor = message.getInt(REPLICATION_FACTOR, collection.getInt(REPLICATION_FACTOR, 1));
+ String createNodeSetStr = message.getStr(CREATE_NODE_SET);
+ List<Node> sortedNodeList = getNodesForNewShard(clusterState, collectionName, sliceName, repFactor,
+ createNodeSetStr, overseer.getZkController().getCoreContainer());
+
+ Overseer.getInQueue(zkStateReader.getZkClient()).offer(ZkStateReader.toJSON(message));
+ // wait for a while until we see the shard
+ long waitUntil = System.nanoTime() + TimeUnit.NANOSECONDS.convert(30, TimeUnit.SECONDS);
+ boolean created = false;
+ while (System.nanoTime() < waitUntil) {
+ Thread.sleep(100);
+ created = zkStateReader.getClusterState().getCollection(collectionName).getSlice(sliceName) != null;
+ if (created) break;
+ }
+ if (!created)
+ throw new SolrException(ErrorCode.SERVER_ERROR, "Could not fully create shard: " + message.getStr(NAME));
+
+ String configName = message.getStr(COLL_CONF);
+ for (int j = 1; j <= repFactor; j++) {
+ String nodeName = sortedNodeList.get(((j - 1)) % sortedNodeList.size()).nodeName;
+ String shardName = collectionName + "_" + sliceName + "_replica" + j;
+ log.info("Creating shard " + shardName + " as part of slice " + sliceName + " of collection " + collectionName
+ + " on " + nodeName);
+
+ // Need to create new params for each request
+ ModifiableSolrParams params = new ModifiableSolrParams();
+ params.set(CoreAdminParams.ACTION, CoreAdminAction.CREATE.toString());
+
+ params.set(CoreAdminParams.NAME, shardName);
+ params.set(COLL_CONF, configName);
+ params.set(CoreAdminParams.COLLECTION, collectionName);
+ params.set(CoreAdminParams.SHARD, sliceName);
+ params.set(ZkStateReader.NUM_SHARDS_PROP, numSlices);
+ addPropertyParams(message, params);
+
+ ShardRequest sreq = new ShardRequest();
+ params.set("qt", adminPath);
+ sreq.purpose = 1;
+ String replica = zkStateReader.getBaseUrlForNodeName(nodeName);
+ sreq.shards = new String[] {replica};
+ sreq.actualShards = sreq.shards;
+ sreq.params = params;
+
+ shardHandler.submit(sreq, replica, sreq.params);
+
}
+
+ processResponses(results, shardHandler);
+
+ log.info("Finished create command on all shards for collection: " + collectionName);
+
+ return true;
}
private boolean splitShard(ClusterState clusterState, ZkNodeProps message, NamedList results) {
String collectionName = message.getStr("collection");
String slice = message.getStr(ZkStateReader.SHARD_ID_PROP);
- Map previousMDCContext = MDC.getCopyOfContextMap();
- MDCUtils.setMDC(collectionName, slice, null, null);
- try {
- log.info("Split shard invoked");
- String splitKey = message.getStr("split.key");
- ShardHandler shardHandler = shardHandlerFactory.getShardHandler();
-
- DocCollection collection = clusterState.getCollection(collectionName);
- DocRouter router = collection.getRouter() != null ? collection.getRouter() : DocRouter.DEFAULT;
-
- Slice parentSlice = null;
-
- if (slice == null) {
- if (router instanceof CompositeIdRouter) {
- Collection<Slice> searchSlices = router.getSearchSlicesSingle(splitKey, new ModifiableSolrParams(), collection);
- if (searchSlices.isEmpty()) {
- throw new SolrException(ErrorCode.BAD_REQUEST, "Unable to find an active shard for split.key: " + splitKey);
- }
- if (searchSlices.size() > 1) {
- throw new SolrException(ErrorCode.BAD_REQUEST,
- "Splitting a split.key: " + splitKey + " which spans multiple shards is not supported");
- }
- parentSlice = searchSlices.iterator().next();
- slice = parentSlice.getName();
- log.info("Split by route.key: {}, parent shard is: {} ", splitKey, slice);
- } else {
+
+ log.info("Split shard invoked");
+ String splitKey = message.getStr("split.key");
+ ShardHandler shardHandler = shardHandlerFactory.getShardHandler();
+
+ DocCollection collection = clusterState.getCollection(collectionName);
+ DocRouter router = collection.getRouter() != null ? collection.getRouter() : DocRouter.DEFAULT;
+
+ Slice parentSlice = null;
+
+ if (slice == null) {
+ if (router instanceof CompositeIdRouter) {
+ Collection<Slice> searchSlices = router.getSearchSlicesSingle(splitKey, new ModifiableSolrParams(), collection);
+ if (searchSlices.isEmpty()) {
+ throw new SolrException(ErrorCode.BAD_REQUEST, "Unable to find an active shard for split.key: " + splitKey);
+ }
+ if (searchSlices.size() > 1) {
throw new SolrException(ErrorCode.BAD_REQUEST,
- "Split by route key can only be used with CompositeIdRouter or subclass. Found router: " + router.getClass().getName());
+ "Splitting a split.key: " + splitKey + " which spans multiple shards is not supported");
}
+ parentSlice = searchSlices.iterator().next();
+ slice = parentSlice.getName();
+ log.info("Split by route.key: {}, parent shard is: {} ", splitKey, slice);
} else {
- parentSlice = clusterState.getSlice(collectionName, slice);
- }
-
- if (parentSlice == null) {
- if (clusterState.hasCollection(collectionName)) {
- throw new SolrException(ErrorCode.BAD_REQUEST, "No shard with the specified name exists: " + slice);
- } else {
- throw new SolrException(ErrorCode.BAD_REQUEST, "No collection with the specified name exists: " + collectionName);
- }
- }
-
- // find the leader for the shard
- Replica parentShardLeader = null;
- try {
- parentShardLeader = zkStateReader.getLeaderRetry(collectionName, slice, 10000);
- } catch (InterruptedException e) {
- Thread.currentThread().interrupt();
+ throw new SolrException(ErrorCode.BAD_REQUEST,
+ "Split by route key can only be used with CompositeIdRouter or subclass. Found router: "
+ + router.getClass().getName());
}
-
- DocRouter.Range range = parentSlice.getRange();
- if (range == null) {
- range = new PlainIdRouter().fullRange();
+ } else {
+ parentSlice = clusterState.getSlice(collectionName, slice);
+ }
+
+ if (parentSlice == null) {
+ if (clusterState.hasCollection(collectionName)) {
+ throw new SolrException(ErrorCode.BAD_REQUEST, "No shard with the specified name exists: " + slice);
+ } else {
+ throw new SolrException(ErrorCode.BAD_REQUEST,
+ "No collection with the specified name exists: " + collectionName);
}
-
- List<DocRouter.Range> subRanges = null;
- String rangesStr = message.getStr(CoreAdminParams.RANGES);
- if (rangesStr != null) {
- String[] ranges = rangesStr.split(",");
- if (ranges.length == 0 || ranges.length == 1) {
- throw new SolrException(ErrorCode.BAD_REQUEST, "There must be at least two ranges specified to split a shard");
- } else {
- subRanges = new ArrayList<>(ranges.length);
- for (int i = 0; i < ranges.length; i++) {
- String r = ranges[i];
- try {
- subRanges.add(DocRouter.DEFAULT.fromString(r));
- } catch (Exception e) {
- throw new SolrException(ErrorCode.BAD_REQUEST, "Exception in parsing hexadecimal hash range: " + r, e);
- }
- if (!subRanges.get(i).isSubsetOf(range)) {
- throw new SolrException(ErrorCode.BAD_REQUEST,
- "Specified hash range: " + r + " is not a subset of parent shard's range: " + range.toString());
- }
+ }
+
+ // find the leader for the shard
+ Replica parentShardLeader = null;
+ try {
+ parentShardLeader = zkStateReader.getLeaderRetry(collectionName, slice, 10000);
+ } catch (InterruptedException e) {
+ Thread.currentThread().interrupt();
+ }
+
+ DocRouter.Range range = parentSlice.getRange();
+ if (range == null) {
+ range = new PlainIdRouter().fullRange();
+ }
+
+ List<DocRouter.Range> subRanges = null;
+ String rangesStr = message.getStr(CoreAdminParams.RANGES);
+ if (rangesStr != null) {
+ String[] ranges = rangesStr.split(",");
+ if (ranges.length == 0 || ranges.length == 1) {
+ throw new SolrException(ErrorCode.BAD_REQUEST, "There must be at least two ranges specified to split a shard");
+ } else {
+ subRanges = new ArrayList<>(ranges.length);
+ for (int i = 0; i < ranges.length; i++) {
+ String r = ranges[i];
+ try {
+ subRanges.add(DocRouter.DEFAULT.fromString(r));
+ } catch (Exception e) {
+ throw new SolrException(ErrorCode.BAD_REQUEST, "Exception in parsing hexadecimal hash range: " + r, e);
}
- List<DocRouter.Range> temp = new ArrayList<>(subRanges); // copy to preserve original order
- Collections.sort(temp);
- if (!range.equals(new DocRouter.Range(temp.get(0).min, temp.get(temp.size() - 1).max))) {
+ if (!subRanges.get(i).isSubsetOf(range)) {
throw new SolrException(ErrorCode.BAD_REQUEST,
- "Specified hash ranges: " + rangesStr + " do not cover the entire range of parent shard: " + range);
- }
- for (int i = 1; i < temp.size(); i++) {
- if (temp.get(i - 1).max + 1 != temp.get(i).min) {
- throw new SolrException(ErrorCode.BAD_REQUEST,
- "Specified hash ranges: " + rangesStr + " either overlap with each other or " +
- "do not cover the entire range of parent shard: " + range);
- }
+ "Specified hash range: " + r + " is not a subset of parent shard's range: " + range.toString());
}
}
- } else if (splitKey != null) {
- if (router instanceof CompositeIdRouter) {
- CompositeIdRouter compositeIdRouter = (CompositeIdRouter) router;
- subRanges = compositeIdRouter.partitionRangeByKey(splitKey, range);
- if (subRanges.size() == 1) {
- throw new SolrException(ErrorCode.BAD_REQUEST,
- "The split.key: " + splitKey + " has a hash range that is exactly equal to hash range of shard: " + slice);
- }
- for (DocRouter.Range subRange : subRanges) {
- if (subRange.min == subRange.max) {
- throw new SolrException(ErrorCode.BAD_REQUEST, "The split.key: " + splitKey + " must be a compositeId");
- }
- }
- log.info("Partitioning parent shard " + slice + " range: " + parentSlice.getRange() + " yields: " + subRanges);
- rangesStr = "";
- for (int i = 0; i < subRanges.size(); i++) {
- DocRouter.Range subRange = subRanges.get(i);
- rangesStr += subRange.toString();
- if (i < subRanges.size() - 1)
- rangesStr += ',';
+ List<DocRouter.Range> temp = new ArrayList<>(subRanges); // copy to preserve original order
+ Collections.sort(temp);
+ if (!range.equals(new DocRouter.Range(temp.get(0).min, temp.get(temp.size() - 1).max))) {
+ throw new SolrException(ErrorCode.BAD_REQUEST,
+ "Specified hash ranges: " + rangesStr + " do not cover the entire range of parent shard: " + range);
+ }
+ for (int i = 1; i < temp.size(); i++) {
+ if (temp.get(i - 1).max + 1 != temp.get(i).min) {
+ throw new SolrException(ErrorCode.BAD_REQUEST, "Specified hash ranges: " + rangesStr
+ + " either overlap with each other or " + "do not cover the entire range of parent shard: " + range);
}
}
- } else {
- // todo: fixed to two partitions?
- subRanges = router.partitionRange(2, range);
}
-
- try {
- List<String> subSlices = new ArrayList<>(subRanges.size());
- List<String> subShardNames = new ArrayList<>(subRanges.size());
- String nodeName = parentShardLeader.getNodeName();
+ } else if (splitKey != null) {
+ if (router instanceof CompositeIdRouter) {
+ CompositeIdRouter compositeIdRouter = (CompositeIdRouter) router;
+ subRanges = compositeIdRouter.partitionRangeByKey(splitKey, range);
+ if (subRanges.size() == 1) {
+ throw new SolrException(ErrorCode.BAD_REQUEST, "The split.key: " + splitKey
+ + " has a hash range that is exactly equal to hash range of shard: " + slice);
+ }
+ for (DocRouter.Range subRange : subRanges) {
+ if (subRange.min == subRange.max) {
+ throw new SolrException(ErrorCode.BAD_REQUEST, "The split.key: " + splitKey + " must be a compositeId");
+ }
+ }
+ log.info("Partitioning parent shard " + slice + " range: " + parentSlice.getRange() + " yields: " + subRanges);
+ rangesStr = "";
for (int i = 0; i < subRanges.size(); i++) {
- String subSlice = slice + "_" + i;
- subSlices.add(subSlice);
- String subShardName = collectionName + "_" + subSlice + "_replica1";
- subShardNames.add(subShardName);
-
- Slice oSlice = clusterState.getSlice(collectionName, subSlice);
- if (oSlice != null) {
- final Slice.State state = oSlice.getState();
- if (state == Slice.State.ACTIVE) {
- throw new SolrException(ErrorCode.BAD_REQUEST, "Sub-shard: " + subSlice + " exists in active state. Aborting split shard.");
- } else if (state == Slice.State.CONSTRUCTION || state == Slice.State.RECOVERY) {
- // delete the shards
- for (String sub : subSlices) {
- log.info("Sub-shard: {} already exists therefore requesting its deletion", sub);
- Map<String, Object> propMap = new HashMap<>();
- propMap.put(Overseer.QUEUE_OPERATION, "deleteshard");
- propMap.put(COLLECTION_PROP, collectionName);
- propMap.put(SHARD_ID_PROP, sub);
- ZkNodeProps m = new ZkNodeProps(propMap);
- try {
- deleteShard(clusterState, m, new NamedList());
- } catch (Exception e) {
- throw new SolrException(ErrorCode.SERVER_ERROR, "Unable to delete already existing sub shard: " + sub, e);
- }
+ DocRouter.Range subRange = subRanges.get(i);
+ rangesStr += subRange.toString();
+ if (i < subRanges.size() - 1) rangesStr += ',';
+ }
+ }
+ } else {
+ // todo: fixed to two partitions?
+ subRanges = router.partitionRange(2, range);
+ }
+
+ try {
+ List<String> subSlices = new ArrayList<>(subRanges.size());
+ List<String> subShardNames = new ArrayList<>(subRanges.size());
+ String nodeName = parentShardLeader.getNodeName();
+ for (int i = 0; i < subRanges.size(); i++) {
+ String subSlice = slice + "_" + i;
+ subSlices.add(subSlice);
+ String subShardName = collectionName + "_" + subSlice + "_replica1";
+ subShardNames.add(subShardName);
+
+ Slice oSlice = clusterState.getSlice(collectionName, subSlice);
+ if (oSlice != null) {
+ final Slice.State state = oSlice.getState();
+ if (state == Slice.State.ACTIVE) {
+ throw new SolrException(ErrorCode.BAD_REQUEST,
+ "Sub-shard: " + subSlice + " exists in active state. Aborting split shard.");
+ } else if (state == Slice.State.CONSTRUCTION || state == Slice.State.RECOVERY) {
+ // delete the shards
+ for (String sub : subSlices) {
+ log.info("Sub-shard: {} already exists therefore requesting its deletion", sub);
+ Map<String,Object> propMap = new HashMap<>();
+ propMap.put(Overseer.QUEUE_OPERATION, "deleteshard");
+ propMap.put(COLLECTION_PROP, collectionName);
+ propMap.put(SHARD_ID_PROP, sub);
+ ZkNodeProps m = new ZkNodeProps(propMap);
+ try {
+ deleteShard(clusterState, m, new NamedList());
+ } catch (Exception e) {
+ throw new SolrException(ErrorCode.SERVER_ERROR, "Unable to delete already existing sub shard: " + sub,
+ e);
}
}
}
}
-
- // do not abort splitshard if the unloading fails
- // this can happen because the replicas created previously may be down
- // the only side effect of this is that the sub shard may end up having more replicas than we want
- collectShardResponses(results, false, null, shardHandler);
-
- String asyncId = message.getStr(ASYNC);
- HashMap<String, String> requestMap = new HashMap<String, String>();
-
- for (int i = 0; i < subRanges.size(); i++) {
- String subSlice = subSlices.get(i);
- String subShardName = subShardNames.get(i);
- DocRouter.Range subRange = subRanges.get(i);
-
- log.info("Creating slice "
- + subSlice + " of collection " + collectionName + " on "
- + nodeName);
-
- Map<String, Object> propMap = new HashMap<>();
- propMap.put(Overseer.QUEUE_OPERATION, CREATESHARD.toLower());
- propMap.put(ZkStateReader.SHARD_ID_PROP, subSlice);
- propMap.put(ZkStateReader.COLLECTION_PROP, collectionName);
- propMap.put(ZkStateReader.SHARD_RANGE_PROP, subRange.toString());
- propMap.put(ZkStateReader.SHARD_STATE_PROP, Slice.State.CONSTRUCTION.toString());
- propMap.put(ZkStateReader.SHARD_PARENT_PROP, parentSlice.getName());
- DistributedQueue inQueue = Overseer.getInQueue(zkStateReader.getZkClient());
- inQueue.offer(ZkStateReader.toJSON(new ZkNodeProps(propMap)));
-
- // wait until we are able to see the new shard in cluster state
- waitForNewShard(collectionName, subSlice);
-
- // refresh cluster state
- clusterState = zkStateReader.getClusterState();
-
- log.info("Adding replica " + subShardName + " as part of slice "
- + subSlice + " of collection " + collectionName + " on "
- + nodeName);
- propMap = new HashMap<>();
+ }
+
+ // do not abort splitshard if the unloading fails
+ // this can happen because the replicas created previously may be down
+ // the only side effect of this is that the sub shard may end up having more replicas than we want
+ collectShardResponses(results, false, null, shardHandler);
+
+ String asyncId = message.getStr(ASYNC);
+ HashMap<String,String> requestMap = new HashMap<String,String>();
+
+ for (int i = 0; i < subRanges.size(); i++) {
+ String subSlice = subSlices.get(i);
+ String subShardName = subShardNames.get(i);
+ DocRouter.Range subRange = subRanges.get(i);
+
+ log.info("Creating slice " + subSlice + " of collection " + collectionName + " on " + nodeName);
+
+ Map<String,Object> propMap = new HashMap<>();
+ propMap.put(Overseer.QUEUE_OPERATION, CREATESHARD.toLower());
+ propMap.put(ZkStateReader.SHARD_ID_PROP, subSlice);
+ propMap.put(ZkStateReader.COLLECTION_PROP, collectionName);
+ propMap.put(ZkStateReader.SHARD_RANGE_PROP, subRange.toString());
+ propMap.put(ZkStateReader.SHARD_STATE_PROP, Slice.State.CONSTRUCTION.toString());
+ propMap.put(ZkStateReader.SHARD_PARENT_PROP, parentSlice.getName());
+ DistributedQueue inQueue = Overseer.getInQueue(zkStateReader.getZkClient());
+ inQueue.offer(ZkStateReader.toJSON(new ZkNodeProps(propMap)));
+
+ // wait until we are able to see the new shard in cluster state
+ waitForNewShard(collectionName, subSlice);
+
+ // refresh cluster state
+ clusterState = zkStateReader.getClusterState();
+
+ log.info("Adding replica " + subShardName + " as part of slice " + subSlice + " of collection " + collectionName
+ + " on " + nodeName);
+ propMap = new HashMap<>();
+ propMap.put(Overseer.QUEUE_OPERATION, ADDREPLICA.toLower());
+ propMap.put(COLLECTION_PROP, collectionName);
+ propMap.put(SHARD_ID_PROP, subSlice);
+ propMap.put("node", nodeName);
+ propMap.put(CoreAdminParams.NAME, subShardName);
+ // copy over property params:
+ for (String key : message.keySet()) {
+ if (key.startsWith(COLL_PROP_PREFIX)) {
+ propMap.put(key, message.getStr(key));
+ }
+ }
+ // add async param
+ if (asyncId != null) {
+ propMap.put(ASYNC, asyncId);
+ }
+ addReplica(clusterState, new ZkNodeProps(propMap), results);
+ }
+
+ collectShardResponses(results, true, "SPLITSHARD failed to create subshard leaders", shardHandler);
+
+ completeAsyncRequest(asyncId, requestMap, results);
+
+ for (String subShardName : subShardNames) {
+ // wait for parent leader to acknowledge the sub-shard core
+ log.info("Asking parent leader to wait for: " + subShardName + " to be alive on: " + nodeName);
+ String coreNodeName = waitForCoreNodeName(collectionName, nodeName, subShardName);
+ CoreAdminRequest.WaitForState cmd = new CoreAdminRequest.WaitForState();
+ cmd.setCoreName(subShardName);
+ cmd.setNodeName(nodeName);
+ cmd.setCoreNodeName(coreNodeName);
+ cmd.setState(Replica.State.ACTIVE);
+ cmd.setCheckLive(true);
+ cmd.setOnlyIfLeader(true);
+
+ ModifiableSolrParams p = new ModifiableSolrParams(cmd.getParams());
+ sendShardRequest(nodeName, p, shardHandler, asyncId, requestMap);
+ }
+
+ collectShardResponses(results, true, "SPLITSHARD timed out waiting for subshard leaders to come up",
+ shardHandler);
+
+ completeAsyncRequest(asyncId, requestMap, results);
+
+ log.info("Successfully created all sub-shards for collection " + collectionName + " parent shard: " + slice
+ + " on: " + parentShardLeader);
+
+ log.info("Splitting shard " + parentShardLeader.getName() + " as part of slice " + slice + " of collection "
+ + collectionName + " on " + parentShardLeader);
+
+ ModifiableSolrParams params = new ModifiableSolrParams();
+ params.set(CoreAdminParams.ACTION, CoreAdminAction.SPLIT.toString());
+ params.set(CoreAdminParams.CORE, parentShardLeader.getStr("core"));
+ for (int i = 0; i < subShardNames.size(); i++) {
+ String subShardName = subShardNames.get(i);
+ params.add(CoreAdminParams.TARGET_CORE, subShardName);
+ }
+ params.set(CoreAdminParams.RANGES, rangesStr);
+
+ sendShardRequest(parentShardLeader.getNodeName(), params, shardHandler, asyncId, requestMap);
+
+ collectShardResponses(results, true, "SPLITSHARD failed to invoke SPLIT core admin command", shardHandler);
+ completeAsyncRequest(asyncId, requestMap, results);
+
+ log.info("Index on shard: " + nodeName + " split into two successfully");
+
+ // apply buffered updates on sub-shards
+ for (int i = 0; i < subShardNames.size(); i++) {
+ String subShardName = subShardNames.get(i);
+
+ log.info("Applying buffered updates on : " + subShardName);
+
+ params = new ModifiableSolrParams();
+ params.set(CoreAdminParams.ACTION, CoreAdminAction.REQUESTAPPLYUPDATES.toString());
+ params.set(CoreAdminParams.NAME, subShardName);
+
+ sendShardRequest(nodeName, params, shardHandler, asyncId, requestMap);
+ }
+
+ collectShardResponses(results, true, "SPLITSHARD failed while asking sub shard leaders to apply buffered updates",
+ shardHandler);
+
+ completeAsyncRequest(asyncId, requestMap, results);
+
+ log.info("Successfully applied buffered updates on : " + subShardNames);
+
+ // Replica creation for the new Slices
+
+ // look at the replication factor and see if it matches reality
+ // if it does not, find best nodes to create more cores
+
+ // TODO: Have replication factor decided in some other way instead of numShards for the parent
+
+ int repFactor = clusterState.getSlice(collectionName, slice).getReplicas().size();
+
+ // we need to look at every node and see how many cores it serves
+ // add our new cores to existing nodes serving the least number of cores
+ // but (for now) require that each core goes on a distinct node.
+
+ // TODO: add smarter options that look at the current number of cores per
+ // node?
+ // for now we just go random
+ Set<String> nodes = clusterState.getLiveNodes();
+ List<String> nodeList = new ArrayList<>(nodes.size());
+ nodeList.addAll(nodes);
+
+ Collections.shuffle(nodeList, RANDOM);
+
+ // TODO: Have maxShardsPerNode param for this operation?
+
+ // Remove the node that hosts the parent shard for replica creation.
+ nodeList.remove(nodeName);
+
+ // TODO: change this to handle sharding a slice into > 2 sub-shards.
+
+ for (int i = 1; i <= subSlices.size(); i++) {
+ Collections.shuffle(nodeList, RANDOM);
+ String sliceName = subSlices.get(i - 1);
+ for (int j = 2; j <= repFactor; j++) {
+ String subShardNodeName = nodeList.get((repFactor * (i - 1) + (j - 2)) % nodeList.size());
+ String shardName = collectionName + "_" + sliceName + "_replica" + (j);
+
+ log.info("Creating replica shard " + shardName + " as part of slice " + sliceName + " of collection "
+ + collectionName + " on " + subShardNodeName);
+
+ HashMap<String,Object> propMap = new HashMap<>();
propMap.put(Overseer.QUEUE_OPERATION, ADDREPLICA.toLower());
propMap.put(COLLECTION_PROP, collectionName);
- propMap.put(SHARD_ID_PROP, subSlice);
- propMap.put("node", nodeName);
- propMap.put(CoreAdminParams.NAME, subShardName);
+ propMap.put(SHARD_ID_PROP, sliceName);
+ propMap.put("node", subShardNodeName);
+ propMap.put(CoreAdminParams.NAME, shardName);
// copy over property params:
for (String key : message.keySet()) {
if (key.startsWith(COLL_PROP_PREFIX)) {
@@ -1541,203 +1639,69 @@ public class OverseerCollectionProcessor implements Runnable, Closeable {
}
}
// add async param
- if(asyncId != null) {
+ if (asyncId != null) {
propMap.put(ASYNC, asyncId);
}
addReplica(clusterState, new ZkNodeProps(propMap), results);
- }
-
- collectShardResponses(results, true,
- "SPLITSHARD failed to create subshard leaders", shardHandler);
-
- completeAsyncRequest(asyncId, requestMap, results);
-
- for (String subShardName : subShardNames) {
- // wait for parent leader to acknowledge the sub-shard core
- log.info("Asking parent leader to wait for: " + subShardName + " to be alive on: " + nodeName);
- String coreNodeName = waitForCoreNodeName(collectionName, nodeName, subShardName);
+
+ String coreNodeName = waitForCoreNodeName(collectionName, subShardNodeName, shardName);
+ // wait for the replicas to be seen as active on sub shard leader
+ log.info("Asking sub shard leader to wait for: " + shardName + " to be alive on: " + subShardNodeName);
CoreAdminRequest.WaitForState cmd = new CoreAdminRequest.WaitForState();
- cmd.setCoreName(subShardName);
- cmd.setNodeName(nodeName);
+ cmd.setCoreName(subShardNames.get(i - 1));
+ cmd.setNodeName(subShardNodeName);
cmd.setCoreNodeName(coreNodeName);
- cmd.setState(Replica.State.ACTIVE);
+ cmd.setState(Replica.State.RECOVERING);
cmd.setCheckLive(true);
cmd.setOnlyIfLeader(true);
-
ModifiableSolrParams p = new ModifiableSolrParams(cmd.getParams());
+
sendShardRequest(nodeName, p, shardHandler, asyncId, requestMap);
+
}
-
- collectShardResponses(results, true,
- "SPLITSHARD timed out waiting for subshard leaders to come up", shardHandler);
-
- completeAsyncRequest(asyncId, requestMap, results);
-
- log.info("Successfully created all sub-shards for collection "
- + collectionName + " parent shard: " + slice + " on: " + parentShardLeader);
-
- log.info("Splitting shard " + parentShardLeader.getName() + " as part of slice "
- + slice + " of collection " + collectionName + " on "
- + parentShardLeader);
-
- ModifiableSolrParams params = new ModifiableSolrParams();
- params.set(CoreAdminParams.ACTION, CoreAdminAction.SPLIT.toString());
- params.set(CoreAdminParams.CORE, parentShardLeader.getStr("core"));
- for (int i = 0; i < subShardNames.size(); i++) {
- String subShardName = subShardNames.get(i);
- params.add(CoreAdminParams.TARGET_CORE, subShardName);
- }
- params.set(CoreAdminParams.RANGES, rangesStr);
-
- sendShardRequest(parentShardLeader.getNodeName(), params, shardHandler, asyncId, requestMap);
-
- collectShardResponses(results, true, "SPLITSHARD failed to invoke SPLIT core admin command",
- shardHandler);
- completeAsyncRequest(asyncId, requestMap, results);
-
- log.info("Index on shard: " + nodeName + " split into two successfully");
-
- // apply buffered updates on sub-shards
- for (int i = 0; i < subShardNames.size(); i++) {
- String subShardName = subShardNames.get(i);
-
- log.info("Applying buffered updates on : " + subShardName);
-
- params = new ModifiableSolrParams();
- params.set(CoreAdminParams.ACTION, CoreAdminAction.REQUESTAPPLYUPDATES.toString());
- params.set(CoreAdminParams.NAME, subShardName);
-
- sendShardRequest(nodeName, params, shardHandler, asyncId, requestMap);
- }
-
- collectShardResponses(results, true,
- "SPLITSHARD failed while asking sub shard leaders to apply buffered updates",
- shardHandler);
-
- completeAsyncRequest(asyncId, requestMap, results);
-
- log.info("Successfully applied buffered updates on : " + subShardNames);
-
- // Replica creation for the new Slices
-
- // look at the replication factor and see if it matches reality
- // if it does not, find best nodes to create more cores
-
- // TODO: Have replication factor decided in some other way instead of numShards for the parent
-
- int repFactor = clusterState.getSlice(collectionName, slice).getReplicas().size();
-
- // we need to look at every node and see how many cores it serves
- // add our new cores to existing nodes serving the least number of cores
- // but (for now) require that each core goes on a distinct node.
-
- // TODO: add smarter options that look at the current number of cores per
- // node?
- // for now we just go random
- Set<String> nodes = clusterState.getLiveNodes();
- List<String> nodeList = new ArrayList<>(nodes.size());
- nodeList.addAll(nodes);
-
- Collections.shuffle(nodeList, RANDOM);
-
- // TODO: Have maxShardsPerNode param for this operation?
-
- // Remove the node that hosts the parent shard for replica creation.
- nodeList.remove(nodeName);
-
- // TODO: change this to handle sharding a slice into > 2 sub-shards.
-
- for (int i = 1; i <= subSlices.size(); i++) {
- Collections.shuffle(nodeList, RANDOM);
- String sliceName = subSlices.get(i - 1);
- for (int j = 2; j <= repFactor; j++) {
- String subShardNodeName = nodeList.get((repFactor * (i - 1) + (j - 2)) % nodeList.size());
- String shardName = collectionName + "_" + sliceName + "_replica" + (j);
-
- log.info("Creating replica shard " + shardName + " as part of slice "
- + sliceName + " of collection " + collectionName + " on "
- + subShardNodeName);
-
- HashMap<String, Object> propMap = new HashMap<>();
- propMap.put(Overseer.QUEUE_OPERATION, ADDREPLICA.toLower());
- propMap.put(COLLECTION_PROP, collectionName);
- propMap.put(SHARD_ID_PROP, sliceName);
- propMap.put("node", subShardNodeName);
- propMap.put(CoreAdminParams.NAME, shardName);
- // copy over property params:
- for (String key : message.keySet()) {
- if (key.startsWith(COLL_PROP_PREFIX)) {
- propMap.put(key, message.getStr(key));
- }
- }
- // add async param
- if (asyncId != null) {
- propMap.put(ASYNC, asyncId);
- }
- addReplica(clusterState, new ZkNodeProps(propMap), results);
-
- String coreNodeName = waitForCoreNodeName(collectionName, subShardNodeName, shardName);
- // wait for the replicas to be seen as active on sub shard leader
- log.info("Asking sub shard leader to wait for: " + shardName + " to be alive on: " + subShardNodeName);
- CoreAdminRequest.WaitForState cmd = new CoreAdminRequest.WaitForState();
- cmd.setCoreName(subShardNames.get(i - 1));
- cmd.setNodeName(subShardNodeName);
- cmd.setCoreNodeName(coreNodeName);
- cmd.setState(Replica.State.RECOVERING);
- cmd.setCheckLive(true);
- cmd.setOnlyIfLeader(true);
- ModifiableSolrParams p = new ModifiableSolrParams(cmd.getParams());
-
- sendShardRequest(nodeName, p, shardHandler, asyncId, requestMap);
-
- }
+ }
+
+ collectShardResponses(results, true,
+ "SPLITSHARD failed to create subshard replicas or timed out waiting for them to come up", shardHandler);
+
+ completeAsyncRequest(asyncId, requestMap, results);
+
+ log.info("Successfully created all replica shards for all sub-slices " + subSlices);
+
+ commit(results, slice, parentShardLeader);
+
+ if (repFactor == 1) {
+ // switch sub shard states to 'active'
+ log.info("Replication factor is 1 so switching shard states");
+ DistributedQueue inQueue = Overseer.getInQueue(zkStateReader.getZkClient());
+ Map<String,Object> propMap = new HashMap<>();
+ propMap.put(Overseer.QUEUE_OPERATION, OverseerAction.UPDATESHARDSTATE.toLower());
+ propMap.put(slice, Slice.State.INACTIVE.toString());
+ for (String subSlice : subSlices) {
+ propMap.put(subSlice, Slice.State.ACTIVE.toString());
}
-
- collectShardResponses(results, true,
- "SPLITSHARD failed to create subshard replicas or timed out waiting for them to come up",
- shardHandler);
-
- completeAsyncRequest(asyncId, requestMap, results);
-
- log.info("Successfully created all replica shards for all sub-slices " + subSlices);
-
- commit(results, slice, parentShardLeader);
-
- if (repFactor == 1) {
- // switch sub shard states to 'active'
- log.info("Replication factor is 1 so switching shard states");
- DistributedQueue inQueue = Overseer.getInQueue(zkStateReader.getZkClient());
- Map<String, Object> propMap = new HashMap<>();
- propMap.put(Overseer.QUEUE_OPERATION, OverseerAction.UPDATESHARDSTATE.toLower());
- propMap.put(slice, Slice.State.INACTIVE.toString());
- for (String subSlice : subSlices) {
- propMap.put(subSlice, Slice.State.ACTIVE.toString());
- }
- propMap.put(ZkStateReader.COLLECTION_PROP, collectionName);
- ZkNodeProps m = new ZkNodeProps(propMap);
- inQueue.offer(ZkStateReader.toJSON(m));
- } else {
- log.info("Requesting shard state be set to 'recovery'");
- DistributedQueue inQueue = Overseer.getInQueue(zkStateReader.getZkClient());
- Map<String, Object> propMap = new HashMap<>();
- propMap.put(Overseer.QUEUE_OPERATION, OverseerAction.UPDATESHARDSTATE.toLower());
- for (String subSlice : subSlices) {
- propMap.put(subSlice, Slice.State.RECOVERY.toString());
- }
- propMap.put(ZkStateReader.COLLECTION_PROP, collectionName);
- ZkNodeProps m = new ZkNodeProps(propMap);
- inQueue.offer(ZkStateReader.toJSON(m));
+ propMap.put(ZkStateReader.COLLECTION_PROP, collectionName);
+ ZkNodeProps m = new ZkNodeProps(propMap);
+ inQueue.offer(ZkStateReader.toJSON(m));
+ } else {
+ log.info("Requesting shard state be set to 'recovery'");
+ DistributedQueue inQueue = Overseer.getInQueue(zkStateReader.getZkClient());
+ Map<String,Object> propMap = new HashMap<>();
+ propMap.put(Overseer.QUEUE_OPERATION, OverseerAction.UPDATESHARDSTATE.toLower());
+ for (String subSlice : subSlices) {
+ propMap.put(subSlice, Slice.State.RECOVERY.toString());
}
-
- return true;
- } catch (SolrException e) {
- throw e;
- } catch (Exception e) {
- log.error("Error executing split operation for collection: " + collectionName + " parent shard: " + slice, e);
- throw new SolrException(ErrorCode.SERVER_ERROR, null, e);
+ propMap.put(ZkStateReader.COLLECTION_PROP, collectionName);
+ ZkNodeProps m = new ZkNodeProps(propMap);
+ inQueue.offer(ZkStateReader.toJSON(m));
}
- } finally {
- MDCUtils.cleanupMDC(previousMDCContext);
+
+ return true;
+ } catch (SolrException e) {
+ throw e;
+ } catch (Exception e) {
+ log.error("Error executing split operation for collection: " + collectionName + " parent shard: " + slice, e);
+ throw new SolrException(ErrorCode.SERVER_ERROR, null, e);
}
}
@@ -1846,71 +1810,64 @@ public class OverseerCollectionProcessor implements Runnable, Closeable {
private void deleteShard(ClusterState clusterState, ZkNodeProps message, NamedList results) {
String collection = message.getStr(ZkStateReader.COLLECTION_PROP);
String sliceId = message.getStr(ZkStateReader.SHARD_ID_PROP);
- Map previousMDCContext = MDC.getCopyOfContextMap();
- MDCUtils.setMDC(collection, sliceId, null, null);
- try {
- log.info("Delete shard invoked");
- Slice slice = clusterState.getSlice(collection, sliceId);
-
- if (slice == null) {
- if (clusterState.hasCollection(collection)) {
- throw new SolrException(ErrorCode.BAD_REQUEST,
- "No shard with name " + sliceId + " exists for collection " + collection);
- } else {
- throw new SolrException(ErrorCode.BAD_REQUEST,
- "No collection with the specified name exists: " + collection);
- }
- }
- // For now, only allow for deletions of Inactive slices or custom hashes (range==null).
- // TODO: Add check for range gaps on Slice deletion
- final Slice.State state = slice.getState();
- if (!(slice.getRange() == null || state == Slice.State.INACTIVE
- || state == Slice.State.RECOVERY || state == Slice.State.CONSTRUCTION)) {
+
+ log.info("Delete shard invoked");
+ Slice slice = clusterState.getSlice(collection, sliceId);
+
+ if (slice == null) {
+ if (clusterState.hasCollection(collection)) {
throw new SolrException(ErrorCode.BAD_REQUEST,
- "The slice: " + slice.getName() + " is currently "
- + state + ". Only non-active (or custom-hashed) slices can be deleted.");
+ "No shard with name " + sliceId + " exists for collection " + collection);
+ } else {
+ throw new SolrException(ErrorCode.BAD_REQUEST, "No collection with the specified name exists: " + collection);
}
- ShardHandler shardHandler = shardHandlerFactory.getShardHandler();
-
- try {
- ModifiableSolrParams params = new ModifiableSolrParams();
- params.set(CoreAdminParams.ACTION, CoreAdminAction.UNLOAD.toString());
- params.set(CoreAdminParams.DELETE_INDEX, "true");
- sliceCmd(clusterState, params, null, slice, shardHandler);
-
- processResponses(results, shardHandler);
-
- ZkNodeProps m = new ZkNodeProps(Overseer.QUEUE_OPERATION,
- DELETESHARD.toLower(), ZkStateReader.COLLECTION_PROP, collection,
- ZkStateReader.SHARD_ID_PROP, sliceId);
- Overseer.getInQueue(zkStateReader.getZkClient()).offer(ZkStateReader.toJSON(m));
-
- // wait for a while until we don't see the shard
- long now = System.nanoTime();
- long timeout = now + TimeUnit.NANOSECONDS.convert(30, TimeUnit.SECONDS);
- boolean removed = false;
- while (System.nanoTime() < timeout) {
- Thread.sleep(100);
- removed = zkStateReader.getClusterState().getSlice(collection, sliceId) == null;
- if (removed) {
- Thread.sleep(100); // just a bit of time so it's more likely other readers see on return
- break;
- }
- }
- if (!removed) {
- throw new SolrException(ErrorCode.SERVER_ERROR,
- "Could not fully remove collection: " + collection + " shard: " + sliceId);
+ }
+ // For now, only allow for deletions of Inactive slices or custom hashes (range==null).
+ // TODO: Add check for range gaps on Slice deletion
+ final Slice.State state = slice.getState();
+ if (!(slice.getRange() == null || state == Slice.State.INACTIVE || state == Slice.State.RECOVERY
+ || state == Slice.State.CONSTRUCTION)) {
+ throw new SolrException(ErrorCode.BAD_REQUEST, "The slice: " + slice.getName() + " is currently " + state
+ + ". Only non-active (or custom-hashed) slices can be deleted.");
+ }
+ ShardHandler shardHandler = shardHandlerFactory.getShardHandler();
+
+ try {
+ ModifiableSolrParams params = new ModifiableSolrParams();
+ params.set(CoreAdminParams.ACTION, CoreAdminAction.UNLOAD.toString());
+ params.set(CoreAdminParams.DELETE_INDEX, "true");
+ sliceCmd(clusterState, params, null, slice, shardHandler);
+
+ processResponses(results, shardHandler);
+
+ ZkNodeProps m = new ZkNodeProps(Overseer.QUEUE_OPERATION, DELETESHARD.toLower(), ZkStateReader.COLLECTION_PROP,
+ collection, ZkStateReader.SHARD_ID_PROP, sliceId);
+ Overseer.getInQueue(zkStateReader.getZkClient()).offer(ZkStateReader.toJSON(m));
+
+ // wait for a while until we don't see the shard
+ long now = System.nanoTime();
+ long timeout = now + TimeUnit.NANOSECONDS.convert(30, TimeUnit.SECONDS);
+ boolean removed = false;
+ while (System.nanoTime() < timeout) {
+ Thread.sleep(100);
+ removed = zkStateReader.getClusterState().getSlice(collection, sliceId) == null;
+ if (removed) {
+ Thread.sleep(100); // just a bit of time so it's more likely other readers see on return
+ break;
}
-
- log.info("Successfully deleted collection: " + collection + ", shard: " + sliceId);
-
- } catch (SolrException e) {
- throw e;
- } catch (Exception e) {
- throw new SolrException(ErrorCode.SERVER_ERROR, "Error executing delete operation for collection: " + collection + " shard: " + sliceId, e);
}
- } finally {
- MDCUtils.cleanupMDC(previousMDCContext);
+ if (!removed) {
+ throw new SolrException(ErrorCode.SERVER_ERROR,
+ "Could not fully remove collection: " + collection + " shard: " + sliceId);
+ }
+
+ log.info("Successfully deleted collection: " + collection + ", shard: " + sliceId);
+
+ } catch (SolrException e) {
+ throw e;
+ } catch (Exception e) {
+ throw new SolrException(ErrorCode.SERVER_ERROR,
+ "Error executing delete operation for collection: " + collection + " shard: " + sliceId, e);
}
}
@@ -2505,110 +2462,101 @@ public class OverseerCollectionProcessor implements Runnable, Closeable {
}
}
- private void addReplica(ClusterState clusterState, ZkNodeProps message, NamedList results) throws KeeperException, InterruptedException {
+ private void addReplica(ClusterState clusterState, ZkNodeProps message, NamedList results)
+ throws KeeperException, InterruptedException {
String collection = message.getStr(COLLECTION_PROP);
String node = message.getStr("node");
String shard = message.getStr(SHARD_ID_PROP);
String coreName = message.getStr(CoreAdminParams.NAME);
- Map previousMDCContext = MDC.getCopyOfContextMap();
- MDCUtils.setMDC(collection, shard, null, coreName);
- try {
- String asyncId = message.getStr("async");
-
- DocCollection coll = clusterState.getCollection(collection);
- if (coll == null) {
- throw new SolrException(ErrorCode.BAD_REQUEST, "Collection: " + collection + " does not exist");
- }
- if (coll.getSlice(shard) == null) {
- throw new SolrException(ErrorCode.BAD_REQUEST,
- "Collection: " + collection + " shard: " + shard + " does not exist");
- }
- ShardHandler shardHandler = shardHandlerFactory.getShardHandler();
-
- if (node == null) {
-
- node = getNodesForNewShard(clusterState, collection, shard, 1,
- null, overseer.getZkController().getCoreContainer()).get(0).nodeName;
- log.info("Node not provided, Identified {} for creating new replica", node);
- }
-
-
- if (!clusterState.liveNodesContain(node)) {
- throw new SolrException(ErrorCode.BAD_REQUEST, "Node: " + node + " is not live");
- }
- if (coreName == null) {
- // assign a name to this core
- Slice slice = coll.getSlice(shard);
- int replicaNum = slice.getReplicas().size();
- for (; ; ) {
- String replicaName = collection + "_" + shard + "_replica" + replicaNum;
- boolean exists = false;
- for (Replica replica : slice.getReplicas()) {
- if (replicaName.equals(replica.getStr("core"))) {
- exists = true;
- break;
- }
+
+ String asyncId = message.getStr("async");
+
+ DocCollection coll = clusterState.getCollection(collection);
+ if (coll == null) {
+ throw new SolrException(ErrorCode.BAD_REQUEST, "Collection: " + collection + " does not exist");
+ }
+ if (coll.getSlice(shard) == null) {
+ throw new SolrException(ErrorCode.BAD_REQUEST,
+ "Collection: " + collection + " shard: " + shard + " does not exist");
+ }
+ ShardHandler shardHandler = shardHandlerFactory.getShardHandler();
+
+ if (node == null) {
+
+ node = getNodesForNewShard(clusterState, collection, shard, 1, null,
+ overseer.getZkController().getCoreContainer()).get(0).nodeName;
+ log.info("Node not provided, Identified {} for creating new replica", node);
+ }
+
+ if (!clusterState.liveNodesContain(node)) {
+ throw new SolrException(ErrorCode.BAD_REQUEST, "Node: " + node + " is not live");
+ }
+ if (coreName == null) {
+ // assign a name to this core
+ Slice slice = coll.getSlice(shard);
+ int replicaNum = slice.getReplicas().size();
+ for (;;) {
+ String replicaName = collection + "_" + shard + "_replica" + replicaNum;
+ boolean exists = false;
+ for (Replica replica : slice.getReplicas()) {
+ if (replicaName.equals(replica.getStr("core"))) {
+ exists = true;
+ break;
}
- if (exists) replicaNum++;
- else break;
- }
- coreName = collection + "_" + shard + "_replica" + replicaNum;
- }
- ModifiableSolrParams params = new ModifiableSolrParams();
-
- if (!Overseer.isLegacy(zkStateReader.getClusterProps())) {
- ZkNodeProps props = new ZkNodeProps(
- Overseer.QUEUE_OPERATION, ADDREPLICA.toLower(),
- ZkStateReader.COLLECTION_PROP, collection,
- ZkStateReader.SHARD_ID_PROP, shard,
- ZkStateReader.CORE_NAME_PROP, coreName,
- ZkStateReader.STATE_PROP, Replica.State.DOWN.toString(),
- ZkStateReader.BASE_URL_PROP, zkStateReader.getBaseUrlForNodeName(node));
- Overseer.getInQueue(zkStateReader.getZkClient()).offer(ZkStateReader.toJSON(props));
- params.set(CoreAdminParams.CORE_NODE_NAME, waitToSeeReplicasInState(collection, Collections.singletonList(coreName)).get(coreName).getName());
- }
-
-
- String configName = zkStateReader.readConfigName(collection);
- String routeKey = message.getStr(ShardParams._ROUTE_);
- String dataDir = message.getStr(CoreAdminParams.DATA_DIR);
- String instanceDir = message.getStr(CoreAdminParams.INSTANCE_DIR);
-
- params.set(CoreAdminParams.ACTION, CoreAdminAction.CREATE.toString());
- params.set(CoreAdminParams.NAME, coreName);
- params.set(COLL_CONF, configName);
- params.set(CoreAdminParams.COLLECTION, collection);
- if (shard != null) {
- params.set(CoreAdminParams.SHARD, shard);
- } else if (routeKey != null) {
- Collection<Slice> slices = coll.getRouter().getSearchSlicesSingle(routeKey, null, coll);
- if (slices.isEmpty()) {
- throw new SolrException(ErrorCode.BAD_REQUEST, "No active shard serving _route_=" + routeKey + " found");
- } else {
- params.set(CoreAdminParams.SHARD, slices.iterator().next().getName());
}
- } else {
- throw new SolrException(ErrorCode.BAD_REQUEST, "Specify either 'shard' or _route_ param");
- }
- if (dataDir != null) {
- params.set(CoreAdminParams.DATA_DIR, dataDir);
+ if (exists) replicaNum++;
+ else break;
}
- if (instanceDir != null) {
- params.set(CoreAdminParams.INSTANCE_DIR, instanceDir);
+ coreName = collection + "_" + shard + "_replica" + replicaNum;
+ }
+ ModifiableSolrParams params = new ModifiableSolrParams();
+
+ if (!Overseer.isLegacy(zkStateReader.getClusterProps())) {
+ ZkNodeProps props = new ZkNodeProps(Overseer.QUEUE_OPERATION, ADDREPLICA.toLower(), ZkStateReader.COLLECTION_PROP,
+ collection, ZkStateReader.SHARD_ID_PROP, shard, ZkStateReader.CORE_NAME_PROP, coreName,
+ ZkStateReader.STATE_PROP, Replica.State.DOWN.toString(), ZkStateReader.BASE_URL_PROP,
+ zkStateReader.getBaseUrlForNodeName(node));
+ Overseer.getInQueue(zkStateReader.getZkClient()).offer(ZkStateReader.toJSON(props));
+ params.set(CoreAdminParams.CORE_NODE_NAME,
+ waitToSeeReplicasInState(collection, Collections.singletonList(coreName)).get(coreName).getName());
+ }
+
+ String configName = zkStateReader.readConfigName(collection);
+ String routeKey = message.getStr(ShardParams._ROUTE_);
+ String dataDir = message.getStr(CoreAdminParams.DATA_DIR);
+ String instanceDir = message.getStr(CoreAdminParams.INSTANCE_DIR);
+
+ params.set(CoreAdminParams.ACTION, CoreAdminAction.CREATE.toString());
+ params.set(CoreAdminParams.NAME, coreName);
+ params.set(COLL_CONF, configName);
+ params.set(CoreAdminParams.COLLECTION, collection);
+ if (shard != null) {
+ params.set(CoreAdminParams.SHARD, shard);
+ } else if (routeKey != null) {
+ Collection<Slice> slices = coll.getRouter().getSearchSlicesSingle(routeKey, null, coll);
+ if (slices.isEmpty()) {
+ throw new SolrException(ErrorCode.BAD_REQUEST, "No active shard serving _route_=" + routeKey + " found");
+ } else {
+ params.set(CoreAdminParams.SHARD, slices.iterator().next().getName());
}
- addPropertyParams(message, params);
-
- // For tracking async calls.
- HashMap<String, String> requestMap = new HashMap<>();
- sendShardRequest(node, params, shardHandler, asyncId, requestMap);
-
- collectShardResponses(results, true,
- "ADDREPLICA failed to create replica", shardHandler);
-
- completeAsyncRequest(asyncId, requestMap, results);
- } finally {
- MDCUtils.cleanupMDC(previousMDCContext);
+ } else {
+ throw new SolrException(ErrorCode.BAD_REQUEST, "Specify either 'shard' or _route_ param");
+ }
+ if (dataDir != null) {
+ params.set(CoreAdminParams.DATA_DIR, dataDir);
+ }
+ if (instanceDir != null) {
+ params.set(CoreAdminParams.INSTANCE_DIR, instanceDir);
}
+ addPropertyParams(message, params);
+
+ // For tracking async calls.
+ HashMap<String,String> requestMap = new HashMap<>();
+ sendShardRequest(node, params, shardHandler, asyncId, requestMap);
+
+ collectShardResponses(results, true, "ADDREPLICA failed to create replica", shardHandler);
+
+ completeAsyncRequest(asyncId, requestMap, results);
}
private void processResponses(NamedList results, ShardHandler shardHandler) {
@@ -2867,8 +2815,7 @@ public class OverseerCollectionProcessor implements Runnable, Closeable {
String asyncId = message.getStr(ASYNC);
String collectionName = message.containsKey(COLLECTION_PROP) ?
message.getStr(COLLECTION_PROP) : message.getStr(NAME);
- Map previousMDCContext = MDC.getCopyOfContextMap();
- MDCUtils.setCollection(collectionName);
+
try {
try {
log.debug("Runner processing {}", head.getId());
@@ -2913,7 +2860,6 @@ public class OverseerCollectionProcessor implements Runnable, Closeable {
synchronized (waitLock){
waitLock.notifyAll();
}
- MDCUtils.cleanupMDC(previousMDCContext);
}
}
diff --git a/solr/core/src/java/org/apache/solr/cloud/RecoveryStrategy.java b/solr/core/src/java/org/apache/solr/cloud/RecoveryStrategy.java
index 73ba4c1b5df..d9ae88017f9 100644
--- a/solr/core/src/java/org/apache/solr/cloud/RecoveryStrategy.java
+++ b/solr/core/src/java/org/apache/solr/cloud/RecoveryStrategy.java
@@ -50,6 +50,7 @@ import org.apache.solr.core.CoreDescriptor;
import org.apache.solr.core.DirectoryFactory.DirContext;
import org.apache.solr.core.SolrCore;
import org.apache.solr.handler.ReplicationHandler;
+import org.apache.solr.logging.MDCLoggingContext;
import org.apache.solr.request.LocalSolrQueryRequest;
import org.apache.solr.request.SolrQueryRequest;
import org.apache.solr.request.SolrRequestHandler;
@@ -125,7 +126,7 @@ public class RecoveryStrategy extends Thread implements ClosableThread {
private void recoveryFailed(final SolrCore core,
final ZkController zkController, final String baseUrl,
final String shardZkNodeName, final CoreDescriptor cd) throws KeeperException, InterruptedException {
- SolrException.log(log, "Recovery failed - I give up. core=" + coreName);
+ SolrException.log(log, "Recovery failed - I give up.");
try {
zkController.publish(cd, Replica.State.RECOVERY_FAILED);
} finally {
@@ -140,7 +141,7 @@ public class RecoveryStrategy extends Thread implements ClosableThread {
ZkCoreNodeProps leaderCNodeProps = new ZkCoreNodeProps(leaderprops);
String leaderUrl = leaderCNodeProps.getCoreUrl();
- log.info("Attempting to replicate from " + leaderUrl + ". core=" + coreName);
+ log.info("Attempting to replicate from " + leaderUrl + ".");
// send commit
commitOnLeader(leaderUrl);
@@ -218,12 +219,9 @@ public class RecoveryStrategy extends Thread implements ClosableThread {
SolrException.log(log, "SolrCore not found - cannot recover:" + coreName);
return;
}
+ MDCLoggingContext.setCore(core);
- SolrQueryRequest req = new LocalSolrQueryRequest(core, new ModifiableSolrParams());
- SolrQueryResponse rsp = new SolrQueryResponse();
- SolrRequestInfo.setRequestInfo(new SolrRequestInfo(req, rsp));
-
- log.info("Starting recovery process. core=" + coreName + " recoveringAfterStartup=" + recoveringAfterStartup);
+ log.info("Starting recovery process. recoveringAfterStartup=" + recoveringAfterStartup);
try {
doRecovery(core);
@@ -236,7 +234,7 @@ public class RecoveryStrategy extends Thread implements ClosableThread {
throw new ZooKeeperException(SolrException.ErrorCode.SERVER_ERROR, "", e);
}
} finally {
- SolrRequestInfo.clearRequestInfo();
+ MDCLoggingContext.clear();
}
}
@@ -248,7 +246,7 @@ public class RecoveryStrategy extends Thread implements ClosableThread {
UpdateLog ulog;
ulog = core.getUpdateHandler().getUpdateLog();
if (ulog == null) {
- SolrException.log(log, "No UpdateLog found - cannot recover. core=" + coreName);
+ SolrException.log(log, "No UpdateLog found - cannot recover.");
recoveryFailed(core, zkController, baseUrl, coreZkNodeName,
core.getCoreDescriptor());
return;
@@ -262,7 +260,7 @@ public class RecoveryStrategy extends Thread implements ClosableThread {
recentUpdates = ulog.getRecentUpdates();
recentVersions = recentUpdates.getVersions(ulog.getNumRecordsToKeep());
} catch (Exception e) {
- SolrException.log(log, "Corrupt tlog - ignoring. core=" + coreName, e);
+ SolrException.log(log, "Corrupt tlog - ignoring.", e);
recentVersions = new ArrayList<>(0);
} finally {
if (recentUpdates != null) {
@@ -291,7 +289,7 @@ public class RecoveryStrategy extends Thread implements ClosableThread {
log.info("###### startupVersions=" + startingVersions);
} catch (Exception e) {
- SolrException.log(log, "Error getting recent versions. core=" + coreName, e);
+ SolrException.log(log, "Error getting recent versions.", e);
recentVersions = new ArrayList<>(0);
}
}
@@ -306,13 +304,11 @@ public class RecoveryStrategy extends Thread implements ClosableThread {
// this means we were previously doing a full index replication
// that probably didn't complete and buffering updates in the
// meantime.
- log.info("Looks like a previous replication recovery did not complete - skipping peer sync. core="
- + coreName);
+ log.info("Looks like a previous replication recovery did not complete - skipping peer sync.");
firstTime = false; // skip peersync
}
} catch (Exception e) {
- SolrException.log(log, "Error trying to get ulog starting operation. core="
- + coreName, e);
+ SolrException.log(log, "Error trying to get ulog starting operation.", e);
firstTime = false; // skip peersync
}
}
@@ -337,13 +333,14 @@ public class RecoveryStrategy extends Thread implements ClosableThread {
}
if (cloudDesc.isLeader()) {
// we are now the leader - no one else must have been suitable
- log.warn("We have not yet recovered - but we are now the leader! core=" + coreName);
- log.info("Finished recovery process. core=" + coreName);
+ log.warn("We have not yet recovered - but we are now the leader!");
+ log.info("Finished recovery process.");
zkController.publish(core.getCoreDescriptor(), Replica.State.ACTIVE);
return;
}
- log.info("Publishing state of core "+core.getName()+" as recovering, leader is "+leaderUrl+" and I am "+ourUrl);
+ log.info("Publishing state of core " + core.getName() + " as recovering, leader is " + leaderUrl + " and I am "
+ + ourUrl);
zkController.publish(core.getCoreDescriptor(), Replica.State.RECOVERING);
@@ -380,7 +377,7 @@ public class RecoveryStrategy extends Thread implements ClosableThread {
// first thing we just try to sync
if (firstTime) {
firstTime = false; // only try sync the first time through the loop
- log.info("Attempting to PeerSync from " + leaderUrl + " core=" + coreName + " - recoveringAfterStartup="+recoveringAfterStartup);
+ log.info("Attempting to PeerSync from " + leaderUrl + " - recoveringAfterStartup="+recoveringAfterStartup);
// System.out.println("Attempting to PeerSync from " + leaderUrl
// + " i am:" + zkController.getNodeName());
PeerSync peerSync = new PeerSync(core,
@@ -392,7 +389,7 @@ public class RecoveryStrategy extends Thread implements ClosableThread {
new ModifiableSolrParams());
// force open a new searcher
core.getUpdateHandler().commit(new CommitUpdateCommand(req, false));
- log.info("PeerSync Recovery was successful - registering as Active. core=" + coreName);
+ log.info("PeerSync Recovery was successful - registering as Active.");
// solrcloud_debug
if (log.isDebugEnabled()) {
@@ -420,7 +417,7 @@ public class RecoveryStrategy extends Thread implements ClosableThread {
return;
}
- log.info("PeerSync Recovery was not successful - trying replication. core=" + coreName);
+ log.info("PeerSync Recovery was not successful - trying replication.");
}
if (isClosed()) {
@@ -428,9 +425,9 @@ public class RecoveryStrategy extends Thread implements ClosableThread {
break;
}
- log.info("Starting Replication Recovery. core=" + coreName);
+ log.info("Starting Replication Recovery.");
- log.info("Begin buffering updates. core=" + coreName);
+ log.info("Begin buffering updates.");
ulog.bufferUpdates();
replayed = false;
@@ -451,7 +448,7 @@ public class RecoveryStrategy extends Thread implements ClosableThread {
break;
}
- log.info("Replication Recovery was successful - registering as Active. core=" + coreName);
+ log.info("Replication Recovery was successful - registering as Active.");
// if there are pending recovery requests, don't advert as active
zkController.publish(core.getCoreDescriptor(), Replica.State.ACTIVE);
close = true;
@@ -475,7 +472,7 @@ public class RecoveryStrategy extends Thread implements ClosableThread {
}
} catch (Exception e) {
- SolrException.log(log, "Error while trying to recover. core=" + coreName, e);
+ SolrException.log(log, "Error while trying to recover.", e);
}
if (!successfulRecovery) {
@@ -488,11 +485,11 @@ public class RecoveryStrategy extends Thread implements ClosableThread {
break;
}
- log.error("Recovery failed - trying again... (" + retries + ") core=" + coreName);
+ log.error("Recovery failed - trying again... (" + retries + ")");
retries++;
if (retries >= MAX_RETRIES) {
- SolrException.log(log, "Recovery failed - max retries exceeded (" + retries + "). core=" + coreName);
+ SolrException.log(log, "Recovery failed - max retries exceeded (" + retries + ").");
try {
recoveryFailed(core, zkController, baseUrl, coreZkNodeName, core.getCoreDescriptor());
} catch (Exception e) {
@@ -501,7 +498,7 @@ public class RecoveryStrategy extends Thread implements ClosableThread {
break;
}
} catch (Exception e) {
- SolrException.log(log, "core=" + coreName, e);
+ SolrException.log(log, "", e);
}
try {
@@ -514,13 +511,13 @@ public class RecoveryStrategy extends Thread implements ClosableThread {
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
- log.warn("Recovery was interrupted. core=" + coreName, e);
+ log.warn("Recovery was interrupted.", e);
close = true;
}
}
}
- log.info("Finished recovery process. core=" + coreName);
+ log.info("Finished recovery process.");
}
@@ -530,9 +527,9 @@ public class RecoveryStrategy extends Thread implements ClosableThread {
Future<RecoveryInfo> future = core.getUpdateHandler().getUpdateLog().applyBufferedUpdates();
if (future == null) {
// no replay needed\
- log.info("No replay needed. core=" + coreName);
+ log.info("No replay needed.");
} else {
- log.info("Replaying buffered documents. core=" + coreName);
+ log.info("Replaying buffered documents.");
// wait for replay
RecoveryInfo report = future.get();
if (report.failed) {
diff --git a/solr/core/src/java/org/apache/solr/cloud/SyncStrategy.java b/solr/core/src/java/org/apache/solr/cloud/SyncStrategy.java
index 9625024b6ac..a88f7bc3930 100644
--- a/solr/core/src/java/org/apache/solr/cloud/SyncStrategy.java
+++ b/solr/core/src/java/org/apache/solr/cloud/SyncStrategy.java
@@ -1,5 +1,10 @@
package org.apache.solr.cloud;
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.concurrent.ExecutorService;
+
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
@@ -33,6 +38,7 @@ import org.apache.solr.core.SolrCore;
import org.apache.solr.handler.component.ShardHandler;
import org.apache.solr.handler.component.ShardRequest;
import org.apache.solr.handler.component.ShardResponse;
+import org.apache.solr.logging.MDCLoggingContext;
import org.apache.solr.request.LocalSolrQueryRequest;
import org.apache.solr.request.SolrQueryRequest;
import org.apache.solr.request.SolrRequestInfo;
@@ -41,11 +47,7 @@ import org.apache.solr.update.PeerSync;
import org.apache.solr.update.UpdateShardHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-
-import java.io.IOException;
-import java.util.ArrayList;
-import java.util.List;
-import java.util.concurrent.ExecutorService;
+import org.slf4j.MDC;
public class SyncStrategy {
protected final Logger log = LoggerFactory.getLogger(getClass());
@@ -76,15 +78,16 @@ public class SyncStrategy {
return sync(zkController, core, leaderProps, false);
}
- public boolean sync(ZkController zkController, SolrCore core, ZkNodeProps leaderProps, boolean peerSyncOnlyWithActive) {
+ public boolean sync(ZkController zkController, SolrCore core, ZkNodeProps leaderProps,
+ boolean peerSyncOnlyWithActive) {
if (SKIP_AUTO_RECOVERY) {
return true;
}
- boolean success;
- SolrQueryRequest req = new LocalSolrQueryRequest(core, new ModifiableSolrParams());
- SolrQueryResponse rsp = new SolrQueryResponse();
- SolrRequestInfo.setRequestInfo(new SolrRequestInfo(req, rsp));
+
+ MDCLoggingContext.setCore(core);
try {
+ boolean success;
+
if (isClosed) {
log.warn("Closed, skipping sync up.");
return false;
@@ -95,12 +98,13 @@ public class SyncStrategy {
log.error("No UpdateLog found - cannot sync");
return false;
}
-
+
success = syncReplicas(zkController, core, leaderProps, peerSyncOnlyWithActive);
+
+ return success;
} finally {
- SolrRequestInfo.clearRequestInfo();
+ MDCLoggingContext.clear();
}
- return success;
}
private boolean syncReplicas(ZkController zkController, SolrCore core,
diff --git a/solr/core/src/java/org/apache/solr/cloud/ZkController.java b/solr/core/src/java/org/apache/solr/cloud/ZkController.java
index c4de44f146f..ea39c382e43 100644
--- a/solr/core/src/java/org/apache/solr/cloud/ZkController.java
+++ b/solr/core/src/java/org/apache/solr/cloud/ZkController.java
@@ -82,7 +82,7 @@ import org.apache.solr.core.CoreContainer;
import org.apache.solr.core.CoreDescriptor;
import org.apache.solr.core.SolrCore;
import org.apache.solr.handler.component.ShardHandler;
-import org.apache.solr.logging.MDCUtils;
+import org.apache.solr.logging.MDCLoggingContext;
import org.apache.solr.update.UpdateLog;
import org.apache.solr.update.UpdateShardHandler;
import org.apache.zookeeper.CreateMode;
@@ -96,7 +96,6 @@ import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.data.Stat;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import org.slf4j.MDC;
import com.google.common.base.Strings;
@@ -248,9 +247,7 @@ public final class ZkController {
this.localHostPort = cloudConfig.getSolrHostPort();
this.hostName = normalizeHostName(cloudConfig.getHost());
this.nodeName = generateNodeName(this.hostName, Integer.toString(this.localHostPort), localHostContext);
-
- MDC.put(NODE_NAME_PROP, nodeName);
-
+ MDCLoggingContext.setNode(nodeName);
this.leaderVoteWait = cloudConfig.getLeaderVoteWait();
this.leaderConflictResolveWait = cloudConfig.getLeaderConflictResolveWait();
@@ -849,39 +846,38 @@ public final class ZkController {
* @return the shardId for the SolrCore
*/
public String register(String coreName, final CoreDescriptor desc, boolean recoverReloadedCores, boolean afterExpiration) throws Exception {
- // pre register has published our down state
- final String baseUrl = getBaseUrl();
-
- final CloudDescriptor cloudDesc = desc.getCloudDescriptor();
- final String collection = cloudDesc.getCollectionName();
-
- Map previousMDCContext = MDC.getCopyOfContextMap();
- MDCUtils.setCollection(collection);
-
- final String coreZkNodeName = desc.getCloudDescriptor().getCoreNodeName();
- assert coreZkNodeName != null : "we should have a coreNodeName by now";
-
- String shardId = cloudDesc.getShardId();
- MDCUtils.setShard(shardId);
- Map<String, Object> props = new HashMap<>();
- // we only put a subset of props into the leader node
- props.put(ZkStateReader.BASE_URL_PROP, baseUrl);
- props.put(ZkStateReader.CORE_NAME_PROP, coreName);
- props.put(ZkStateReader.NODE_NAME_PROP, getNodeName());
-
-
- if (log.isInfoEnabled()) {
- log.info("Register replica - core:" + coreName + " address:"
- + baseUrl + " collection:" + cloudDesc.getCollectionName() + " shard:" + shardId);
+ try (SolrCore core = cc.getCore(desc.getName())) {
+ MDCLoggingContext.setCore(core);
}
-
- ZkNodeProps leaderProps = new ZkNodeProps(props);
-
try {
+ // pre register has published our down state
+ final String baseUrl = getBaseUrl();
+
+ final CloudDescriptor cloudDesc = desc.getCloudDescriptor();
+ final String collection = cloudDesc.getCollectionName();
+
+ final String coreZkNodeName = desc.getCloudDescriptor().getCoreNodeName();
+ assert coreZkNodeName != null : "we should have a coreNodeName by now";
+
+ String shardId = cloudDesc.getShardId();
+ Map<String,Object> props = new HashMap<>();
+ // we only put a subset of props into the leader node
+ props.put(ZkStateReader.BASE_URL_PROP, baseUrl);
+ props.put(ZkStateReader.CORE_NAME_PROP, coreName);
+ props.put(ZkStateReader.NODE_NAME_PROP, getNodeName());
+
+ if (log.isInfoEnabled()) {
+ log.info("Register replica - core:" + coreName + " address:" + baseUrl + " collection:"
+ + cloudDesc.getCollectionName() + " shard:" + shardId);
+ }
+
+ ZkNodeProps leaderProps = new ZkNodeProps(props);
+
try {
// If we're a preferred leader, insert ourselves at the head of the queue
boolean joinAtHead = false;
- Replica replica = zkStateReader.getClusterState().getReplica(desc.getCloudDescriptor().getCollectionName(), coreZkNodeName);
+ Replica replica = zkStateReader.getClusterState().getReplica(desc.getCloudDescriptor().getCollectionName(),
+ coreZkNodeName);
if (replica != null) {
joinAtHead = replica.getBool(SliceMutator.PREFERRED_LEADER_PROP, false);
}
@@ -893,25 +889,24 @@ public final class ZkController {
} catch (KeeperException | IOException e) {
throw new ZooKeeperException(SolrException.ErrorCode.SERVER_ERROR, "", e);
}
-
-
- // in this case, we want to wait for the leader as long as the leader might
+
+ // in this case, we want to wait for the leader as long as the leader might
// wait for a vote, at least - but also long enough that a large cluster has
// time to get its act together
String leaderUrl = getLeader(cloudDesc, leaderVoteWait + 600000);
-
+
String ourUrl = ZkCoreNodeProps.getCoreUrl(baseUrl, coreName);
log.info("We are " + ourUrl + " and leader is " + leaderUrl);
boolean isLeader = leaderUrl.equals(ourUrl);
-
+
try (SolrCore core = cc.getCore(desc.getName())) {
-
+
// recover from local transaction log and wait for it to complete before
// going active
// TODO: should this be moved to another thread? To recoveryStrat?
// TODO: should this actually be done earlier, before (or as part of)
// leader election perhaps?
-
+
UpdateLog ulog = core.getUpdateHandler().getUpdateLog();
// we will call register again after zk expiration and on reload
@@ -931,18 +926,18 @@ public final class ZkController {
}
}
}
- boolean didRecovery = checkRecovery(coreName, desc, recoverReloadedCores, isLeader, cloudDesc,
- collection, coreZkNodeName, shardId, leaderProps, core, cc, afterExpiration);
+ boolean didRecovery = checkRecovery(coreName, desc, recoverReloadedCores, isLeader, cloudDesc, collection,
+ coreZkNodeName, shardId, leaderProps, core, cc, afterExpiration);
if (!didRecovery) {
publish(desc, Replica.State.ACTIVE);
}
}
-
+
// make sure we have an update cluster state right away
zkStateReader.updateClusterState(true);
return shardId;
} finally {
- MDCUtils.cleanupMDC(previousMDCContext);
+ MDCLoggingContext.clear();
}
}
@@ -1138,28 +1133,26 @@ public final class ZkController {
if (core == null || core.isClosed()) {
return;
}
+ MDCLoggingContext.setCore(core);
}
+ } else {
+ MDCLoggingContext.setCoreDescriptor(cd);
}
- String collection = cd.getCloudDescriptor().getCollectionName();
-
- Map previousMDCContext = MDC.getCopyOfContextMap();
- MDCUtils.setCollection(collection);
-
try {
- if (cd != null && cd.getName() != null)
- MDCUtils.setCore(cd.getName());
- log.info("publishing core={} state={} collection={}", cd.getName(), state.toString(), collection);
- //System.out.println(Thread.currentThread().getStackTrace()[3]);
+ String collection = cd.getCloudDescriptor().getCollectionName();
+
+ log.info("publishing state={}", state.toString());
+ // System.out.println(Thread.currentThread().getStackTrace()[3]);
Integer numShards = cd.getCloudDescriptor().getNumShards();
- if (numShards == null) { //XXX sys prop hack
+ if (numShards == null) { // XXX sys prop hack
log.info("numShards not found on descriptor - reading it from system property");
numShards = Integer.getInteger(ZkStateReader.NUM_SHARDS_PROP);
}
-
+
assert collection != null && collection.length() > 0;
-
+
String shardId = cd.getCloudDescriptor().getShardId();
- MDCUtils.setShard(shardId);
+
String coreNodeName = cd.getCloudDescriptor().getCoreNodeName();
// If the leader initiated recovery, then verify that this replica has performed
// recovery as requested before becoming active; don't even look at lirState if going down
@@ -1182,8 +1175,8 @@ public final class ZkController {
}
}
}
-
- Map<String, Object> props = new HashMap<>();
+
+ Map<String,Object> props = new HashMap<>();
props.put(Overseer.QUEUE_OPERATION, "state");
props.put(ZkStateReader.STATE_PROP, state.toString());
props.put(ZkStateReader.BASE_URL_PROP, getBaseUrl());
@@ -1198,7 +1191,7 @@ public final class ZkController {
if (coreNodeName != null) {
props.put(ZkStateReader.CORE_NODE_NAME_PROP, coreNodeName);
}
-
+
if (ClusterStateUtil.isAutoAddReplicas(getZkStateReader(), collection)) {
try (SolrCore core = cc.getCore(cd.getName())) {
if (core != null && core.getDirectoryFactory().isSharedStorage()) {
@@ -1210,15 +1203,15 @@ public final class ZkController {
}
}
}
-
+
ZkNodeProps m = new ZkNodeProps(props);
-
+
if (updateLastState) {
cd.getCloudDescriptor().lastPublished = state;
}
overseerJobQueue.offer(ZkStateReader.toJSON(m));
} finally {
- MDCUtils.cleanupMDC(previousMDCContext);
+ MDCLoggingContext.clear();
}
}
diff --git a/solr/core/src/java/org/apache/solr/core/CoreContainer.java b/solr/core/src/java/org/apache/solr/core/CoreContainer.java
index 46c8a8947a0..0b4533adfc1 100644
--- a/solr/core/src/java/org/apache/solr/core/CoreContainer.java
+++ b/solr/core/src/java/org/apache/solr/core/CoreContainer.java
@@ -46,6 +46,7 @@ import org.apache.solr.handler.admin.InfoHandler;
import org.apache.solr.handler.component.HttpShardHandlerFactory;
import org.apache.solr.handler.component.ShardHandlerFactory;
import org.apache.solr.logging.LogWatcher;
+import org.apache.solr.logging.MDCLoggingContext;
import org.apache.solr.request.SolrRequestHandler;
import org.apache.solr.security.AuthorizationPlugin;
import org.apache.solr.security.AuthenticationPlugin;
@@ -312,7 +313,6 @@ public class CoreContainer {
* Load the cores defined for this CoreContainer
*/
public void load() {
-
log.info("Loading cores into CoreContainer [instanceDir={}]", loader.getInstanceDir());
// add the sharedLib to the shared resource loader before initializing cfg based plugins
@@ -334,7 +334,6 @@ public class CoreContainer {
logging = LogWatcher.newRegisteredLogWatcher(cfg.getLogWatcherConfig(), loader);
hostName = cfg.getNodeName();
- log.info("Node Name: " + hostName);
zkSys.initZooKeeper(this, solrHome, cfg.getCloudConfig());
@@ -627,7 +626,7 @@ public class CoreContainer {
SolrCore core = null;
try {
-
+ MDCLoggingContext.setCore(core);
if (zkSys.getZkController() != null) {
zkSys.getZkController().preRegister(dcore);
}
@@ -657,6 +656,8 @@ public class CoreContainer {
coreInitFailures.put(dcore.getName(), new CoreLoadFailure(dcore, e));
IOUtils.closeQuietly(core);
throw t;
+ } finally {
+ MDCLoggingContext.clear();
}
}
diff --git a/solr/core/src/java/org/apache/solr/core/CoreDescriptor.java b/solr/core/src/java/org/apache/solr/core/CoreDescriptor.java
index 31de693a0f3..49e1b90f711 100644
--- a/solr/core/src/java/org/apache/solr/core/CoreDescriptor.java
+++ b/solr/core/src/java/org/apache/solr/core/CoreDescriptor.java
@@ -207,7 +207,7 @@ public class CoreDescriptor {
cloudDesc = null;
}
- SolrCore.log.info("CORE DESCRIPTOR: " + coreProperties);
+ SolrCore.log.info("Created CoreDescriptor: " + coreProperties);
}
/**
diff --git a/solr/core/src/java/org/apache/solr/core/SolrCore.java b/solr/core/src/java/org/apache/solr/core/SolrCore.java
index 6dfe5b87e6a..8488041370f 100644
--- a/solr/core/src/java/org/apache/solr/core/SolrCore.java
+++ b/solr/core/src/java/org/apache/solr/core/SolrCore.java
@@ -90,7 +90,7 @@ import org.apache.solr.handler.RequestHandlerBase;
import org.apache.solr.handler.admin.ShowFileRequestHandler;
import org.apache.solr.handler.component.HighlightComponent;
import org.apache.solr.handler.component.SearchComponent;
-import org.apache.solr.logging.MDCUtils;
+import org.apache.solr.logging.MDCLoggingContext;
import org.apache.solr.request.SolrQueryRequest;
import org.apache.solr.request.SolrRequestHandler;
import org.apache.solr.response.BinaryResponseWriter;
@@ -711,7 +711,7 @@ public final class SolrCore implements SolrInfoMBean, Closeable {
this.coreDescriptor = coreDescriptor;
setName(name);
- MDCUtils.setCore(name); // show the core name in the error logs
+ MDCLoggingContext.setCore(this);
resourceLoader = config.getResourceLoader();
this.solrConfig = config;
diff --git a/solr/core/src/java/org/apache/solr/core/SolrCores.java b/solr/core/src/java/org/apache/solr/core/SolrCores.java
index 3a15bee3e55..31b77350f13 100644
--- a/solr/core/src/java/org/apache/solr/core/SolrCores.java
+++ b/solr/core/src/java/org/apache/solr/core/SolrCores.java
@@ -19,6 +19,7 @@ package org.apache.solr.core;
import com.google.common.collect.Lists;
import org.apache.solr.common.SolrException;
+import org.apache.solr.logging.MDCLoggingContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -113,6 +114,7 @@ class SolrCores {
}
for (SolrCore core : coreList) {
+ MDCLoggingContext.setCore(core);
try {
core.close();
} catch (Throwable e) {
@@ -120,6 +122,8 @@ class SolrCores {
if (e instanceof Error) {
throw (Error) e;
}
+ } finally {
+ MDCLoggingContext.clear();
}
}
} while (coreList.size() > 0);
diff --git a/solr/core/src/java/org/apache/solr/core/ZkContainer.java b/solr/core/src/java/org/apache/solr/core/ZkContainer.java
index ae6e20036e9..99daddb6552 100644
--- a/solr/core/src/java/org/apache/solr/core/ZkContainer.java
+++ b/solr/core/src/java/org/apache/solr/core/ZkContainer.java
@@ -37,7 +37,7 @@ import org.apache.solr.common.cloud.Replica;
import org.apache.solr.common.cloud.ZkConfigManager;
import org.apache.solr.common.cloud.ZooKeeperException;
import org.apache.solr.common.util.ExecutorUtil;
-import org.apache.solr.logging.MDCUtils;
+import org.apache.solr.logging.MDCLoggingContext;
import org.apache.solr.util.DefaultSolrThreadFactory;
import org.apache.zookeeper.KeeperException;
import org.slf4j.Logger;
@@ -181,6 +181,8 @@ public class ZkContainer {
Thread thread = new Thread() {
@Override
public void run() {
+ MDCLoggingContext.setCore(core);
+ try {
try {
zkController.register(core.getName(), core.getCoreDescriptor());
} catch (InterruptedException e) {
@@ -198,20 +200,23 @@ public class ZkContainer {
}
SolrException.log(log, "", e);
}
+ } finally {
+ MDC.clear();
}
-
+ }
+
};
if (zkController != null) {
- MDCUtils.setCore(core.getName());
- try {
- if (background) {
- coreZkRegister.execute(thread);
- } else {
+ if (background) {
+ coreZkRegister.execute(thread);
+ } else {
+ MDCLoggingContext.setCore(core);
+ try {
thread.run();
+ } finally {
+ MDC.clear();
}
- } finally {
- MDC.remove(CORE_NAME_PROP);
}
}
}
diff --git a/solr/core/src/java/org/apache/solr/logging/MDCLoggingContext.java b/solr/core/src/java/org/apache/solr/logging/MDCLoggingContext.java
new file mode 100644
index 00000000000..488adb4d45e
--- /dev/null
+++ b/solr/core/src/java/org/apache/solr/logging/MDCLoggingContext.java
@@ -0,0 +1,163 @@
+package org.apache.solr.logging;
+
+/*
+ * 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.
+ */
+
+import static org.apache.solr.common.cloud.ZkStateReader.COLLECTION_PROP;
+import static org.apache.solr.common.cloud.ZkStateReader.CORE_NAME_PROP;
+import static org.apache.solr.common.cloud.ZkStateReader.NODE_NAME_PROP;
+import static org.apache.solr.common.cloud.ZkStateReader.REPLICA_PROP;
+import static org.apache.solr.common.cloud.ZkStateReader.SHARD_ID_PROP;
+
+import java.util.function.Supplier;
+
+import org.apache.solr.cloud.CloudDescriptor;
+import org.apache.solr.cloud.ZkController;
+import org.apache.solr.core.CoreContainer;
+import org.apache.solr.core.CoreDescriptor;
+import org.apache.solr.core.SolrCore;
+import org.slf4j.MDC;
+
+/**
+ * Set's per thread context info for logging. Nested calls will use the top level parent for all context. The first
+ * caller always owns the context until it calls {@link #clear()}. Always call {@link #setCore(SolrCore)} or
+ * {@link #setCoreDescriptor(CoreDescriptor)} and then {@link #clear()} in a finally block.
+ */
+public class MDCLoggingContext {
+ // When a thread sets context and finds that the context is already set, we should noop and ignore the finally clear
+ private static ThreadLocal<Integer> CALL_DEPTH = ThreadLocal.withInitial(new Supplier<Integer>() {
+ @Override
+ public Integer get() {
+ return 0;
+ }
+ });
+
+ private static void setCollection(String collection) {
+ if (collection != null) {
+ MDC.put(COLLECTION_PROP, "c:" + collection);
+ } else {
+ MDC.remove(COLLECTION_PROP);
+ }
+ }
+
+ private static void setShard(String shard) {
+ if (shard != null) {
+ MDC.put(SHARD_ID_PROP, "s:" + shard);
+ } else {
+ MDC.remove(SHARD_ID_PROP);
+ }
+ }
+
+ private static void setReplica(String replica) {
+ if (replica != null) {
+ MDC.put(REPLICA_PROP, "r:" + replica);
+ } else {
+ MDC.remove(REPLICA_PROP);
+ }
+ }
+
+ private static void setCoreName(String core) {
+ if (core != null) {
+ MDC.put(CORE_NAME_PROP, "x:" + core);
+ } else {
+ MDC.remove(CORE_NAME_PROP);
+ }
+ }
+
+ public static void setNode(CoreContainer cc) {
+ if (cc != null) {
+ ZkController zk = cc.getZkController();
+ if (zk != null) {
+ setNode(zk.getNodeName());
+ }
+ }
+ }
+
+ // we allow the host to be set like this because it is the same for any thread
+ // in the thread pool - we can't do this with the per core properties!
+ public static void setNode(String node) {
+ int used = CALL_DEPTH.get();
+ if (used == 0) {
+ setNodeName(node);
+ }
+ }
+
+ private static void setNodeName(String node) {
+ if (node != null) {
+ MDC.put(NODE_NAME_PROP, "n:" + node);
+ } else {
+ MDC.remove(NODE_NAME_PROP);
+ }
+ }
+
+ public static void setCore(SolrCore core) {
+ if (core != null) {
+ CoreDescriptor cd = core.getCoreDescriptor();
+ setCoreDescriptor(cd);
+ }
+ }
+
+ public static void setCoreDescriptor(CoreDescriptor cd) {
+ if (cd != null) {
+ int callDepth = CALL_DEPTH.get();
+ CALL_DEPTH.set(callDepth + 1);
+ if (callDepth > 0) {
+ return;
+ }
+
+ setCoreName(cd.getName());
+ CoreContainer cc = cd.getCoreContainer();
+ if (cc != null) {
+ ZkController zkController = cc.getZkController();
+ if (zkController != null) {
+ setNodeName(zkController.getNodeName());
+ }
+ }
+
+ CloudDescriptor ccd = cd.getCloudDescriptor();
+ if (ccd != null) {
+ setCollection(ccd.getCollectionName());
+ setShard(ccd.getShardId());
+ setReplica(ccd.getCoreNodeName());
+ }
+ }
+ }
+
+ public static void clear() {
+ int used = CALL_DEPTH.get();
+ CALL_DEPTH.set(used - 1);
+ if (used == 0) {
+ MDC.remove(COLLECTION_PROP);
+ MDC.remove(CORE_NAME_PROP);
+ MDC.remove(REPLICA_PROP);
+ MDC.remove(SHARD_ID_PROP);
+ }
+ }
+
+ private static void removeAll() {
+ MDC.remove(COLLECTION_PROP);
+ MDC.remove(CORE_NAME_PROP);
+ MDC.remove(REPLICA_PROP);
+ MDC.remove(SHARD_ID_PROP);
+ MDC.remove(NODE_NAME_PROP);
+ }
+
+ public static void reset() {
+ CALL_DEPTH.set(0);
+ removeAll();
+ }
+}
diff --git a/solr/core/src/java/org/apache/solr/logging/MDCUtils.java b/solr/core/src/java/org/apache/solr/logging/MDCUtils.java
deleted file mode 100644
index 61a0aef8644..00000000000
--- a/solr/core/src/java/org/apache/solr/logging/MDCUtils.java
+++ /dev/null
@@ -1,69 +0,0 @@
-package org.apache.solr.logging;
-
-import java.util.Map;
-
-import org.apache.solr.common.cloud.ZkStateReader;
-import org.slf4j.MDC;
-
-import static org.apache.solr.common.cloud.ZkStateReader.COLLECTION_PROP;
-import static org.apache.solr.common.cloud.ZkStateReader.CORE_NAME_PROP;
-import static org.apache.solr.common.cloud.ZkStateReader.REPLICA_PROP;
-import static org.apache.solr.common.cloud.ZkStateReader.SHARD_ID_PROP;
-
-/*
- * 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.
- */
-
-public class MDCUtils {
- public static void cleanupMDC(Map previousMDCContext) {
- if (previousMDCContext != null)
- MDC.setContextMap(previousMDCContext);
- }
-
- public static void setMDC (String collection, String shard, String replica, String core) {
- setCollection(collection);
- setShard(shard);
- setReplica(replica);
- setCore(core);
- }
-
- public static void setCollection(String collection) {
- if (collection != null)
- MDC.put(COLLECTION_PROP, collection);
- }
-
- public static void setShard(String shard) {
- if (shard != null)
- MDC.put(SHARD_ID_PROP, shard);
- }
-
- public static void setReplica(String replica) {
- if (replica != null)
- MDC.put(REPLICA_PROP, replica);
- }
-
- public static void setCore(String core) {
- if (core != null)
- MDC.put(CORE_NAME_PROP, core);
- }
-
- public static void clearMDC() {
- MDC.remove(COLLECTION_PROP);
- MDC.remove(CORE_NAME_PROP);
- MDC.remove(REPLICA_PROP);
- MDC.remove(SHARD_ID_PROP);
- }
-}
diff --git a/solr/core/src/java/org/apache/solr/servlet/HttpSolrCall.java b/solr/core/src/java/org/apache/solr/servlet/HttpSolrCall.java
index d4574d9be5b..49c7845251e 100644
--- a/solr/core/src/java/org/apache/solr/servlet/HttpSolrCall.java
+++ b/solr/core/src/java/org/apache/solr/servlet/HttpSolrCall.java
@@ -1,5 +1,37 @@
package org.apache.solr.servlet;
+import static org.apache.solr.common.cloud.ZkStateReader.BASE_URL_PROP;
+import static org.apache.solr.common.cloud.ZkStateReader.COLLECTION_PROP;
+import static org.apache.solr.common.cloud.ZkStateReader.CORE_NAME_PROP;
+import static org.apache.solr.common.cloud.ZkStateReader.NODE_NAME_PROP;
+import static org.apache.solr.common.params.CollectionParams.CollectionAction.CREATE;
+import static org.apache.solr.common.params.CollectionParams.CollectionAction.DELETE;
+import static org.apache.solr.common.params.CollectionParams.CollectionAction.RELOAD;
+import static org.apache.solr.servlet.SolrDispatchFilter.Action.ADMIN;
+import static org.apache.solr.servlet.SolrDispatchFilter.Action.FORWARD;
+import static org.apache.solr.servlet.SolrDispatchFilter.Action.PASSTHROUGH;
+import static org.apache.solr.servlet.SolrDispatchFilter.Action.PROCESS;
+import static org.apache.solr.servlet.SolrDispatchFilter.Action.REMOTEQUERY;
+import static org.apache.solr.servlet.SolrDispatchFilter.Action.RETRY;
+import static org.apache.solr.servlet.SolrDispatchFilter.Action.RETURN;
+
+import java.io.EOFException;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+import java.io.UnsupportedEncodingException;
+import java.security.Principal;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.Enumeration;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
@@ -19,22 +51,6 @@ package org.apache.solr.servlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
-import java.io.EOFException;
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.OutputStream;
-import java.io.UnsupportedEncodingException;
-import java.security.Principal;
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.Collections;
-import java.util.Enumeration;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.StringUtils;
@@ -54,7 +70,6 @@ import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.entity.InputStreamEntity;
import org.apache.http.util.EntityUtils;
import org.apache.solr.client.solrj.impl.CloudSolrClient;
-import org.apache.solr.cloud.CloudDescriptor;
import org.apache.solr.common.SolrException;
import org.apache.solr.common.cloud.Aliases;
import org.apache.solr.common.cloud.ClusterState;
@@ -73,7 +88,7 @@ import org.apache.solr.core.CoreContainer;
import org.apache.solr.core.SolrConfig;
import org.apache.solr.core.SolrCore;
import org.apache.solr.handler.ContentStreamHandlerBase;
-import org.apache.solr.logging.MDCUtils;
+import org.apache.solr.logging.MDCLoggingContext;
import org.apache.solr.request.SolrQueryRequest;
import org.apache.solr.request.SolrQueryRequestBase;
import org.apache.solr.request.SolrRequestHandler;
@@ -85,30 +100,14 @@ import org.apache.solr.security.AuthorizationContext;
import org.apache.solr.security.AuthorizationContext.CollectionRequest;
import org.apache.solr.security.AuthorizationContext.RequestType;
import org.apache.solr.security.AuthorizationResponse;
+import org.apache.solr.servlet.SolrDispatchFilter.Action;
import org.apache.solr.servlet.cache.HttpCacheHeaderUtil;
import org.apache.solr.servlet.cache.Method;
import org.apache.solr.update.processor.DistributingUpdateProcessorFactory;
import org.apache.solr.util.RTimer;
import org.apache.zookeeper.KeeperException;
import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.slf4j.MDC;
-
-import static org.apache.solr.common.cloud.ZkStateReader.BASE_URL_PROP;
-import static org.apache.solr.common.cloud.ZkStateReader.COLLECTION_PROP;
-import static org.apache.solr.common.cloud.ZkStateReader.CORE_NAME_PROP;
-import static org.apache.solr.common.cloud.ZkStateReader.NODE_NAME_PROP;
-import static org.apache.solr.common.params.CollectionParams.CollectionAction.CREATE;
-import static org.apache.solr.common.params.CollectionParams.CollectionAction.DELETE;
-import static org.apache.solr.common.params.CollectionParams.CollectionAction.RELOAD;
-import static org.apache.solr.servlet.SolrDispatchFilter.Action;
-import static org.apache.solr.servlet.SolrDispatchFilter.Action.ADMIN;
-import static org.apache.solr.servlet.SolrDispatchFilter.Action.FORWARD;
-import static org.apache.solr.servlet.SolrDispatchFilter.Action.PASSTHROUGH;
-import static org.apache.solr.servlet.SolrDispatchFilter.Action.PROCESS;
-import static org.apache.solr.servlet.SolrDispatchFilter.Action.REMOTEQUERY;
-import static org.apache.solr.servlet.SolrDispatchFilter.Action.RETRY;
-import static org.apache.solr.servlet.SolrDispatchFilter.Action.RETURN;
+import org.slf4j.LoggerFactory;
/**
* This class represents a call made to Solr
@@ -242,15 +241,12 @@ public class HttpSolrCall {
}
}
- if (core != null) addMDCValues();
-
if (core == null && cores.isZooKeeperAware()) {
// we couldn't find the core - lets make sure a collection was not specified instead
core = getCoreByCollection(corename);
if (core != null) {
// we found a core, update the path
path = path.substring(idx);
- addMDCValues();
if (collectionsList == null)
collectionsList = new ArrayList<>();
collectionsList.add(corename);
@@ -263,12 +259,12 @@ public class HttpSolrCall {
// try the default core
if (core == null) {
core = cores.getCore("");
- if (core != null) addMDCValues();
}
}
// With a valid core...
if (core != null) {
+ MDCLoggingContext.setCore(core);
config = core.getSolrConfig();
// get or create/cache the parser for the core
SolrRequestParsers parser = config.getRequestParsers();
@@ -378,17 +374,14 @@ public class HttpSolrCall {
* This method processes the request.
*/
public Action call() throws IOException {
- MDCUtils.clearMDC();
+ MDCLoggingContext.reset();
+ MDCLoggingContext.setNode(cores);
if (cores == null) {
sendError(503, "Server is shutting down or failed to initialize");
return RETURN;
}
- if (cores.isZooKeeperAware()) {
- MDC.put(NODE_NAME_PROP, cores.getZkController().getNodeName());
- }
-
if (solrDispatchFilter.abortErrorMessage != null) {
sendError(500, solrDispatchFilter.abortErrorMessage);
return RETURN;
@@ -461,6 +454,8 @@ public class HttpSolrCall {
t = t.getCause();
}
return RETURN;
+ } finally {
+ MDCLoggingContext.clear();
}
}
@@ -622,16 +617,6 @@ public class HttpSolrCall {
}
}
- private void addMDCValues() {
- MDCUtils.setCore(core.getName());
- if (cores.isZooKeeperAware()) {
- CloudDescriptor cloud = core.getCoreDescriptor().getCloudDescriptor();
- MDCUtils.setCollection(cloud.getCollectionName());
- MDCUtils.setShard(cloud.getShardId());
- MDCUtils.setReplica(cloud.getCoreNodeName());
- }
- }
-
protected void execute(SolrQueryResponse rsp) {
// a custom filter could add more stuff to the request before passing it on.
// for example: sreq.getContext().put( "HttpServletRequest", req );
diff --git a/solr/core/src/java/org/apache/solr/update/DefaultSolrCoreState.java b/solr/core/src/java/org/apache/solr/update/DefaultSolrCoreState.java
index d38fc6b3ad8..60fe8e9f9e6 100644
--- a/solr/core/src/java/org/apache/solr/update/DefaultSolrCoreState.java
+++ b/solr/core/src/java/org/apache/solr/update/DefaultSolrCoreState.java
@@ -30,6 +30,7 @@ import org.apache.solr.core.CoreContainer;
import org.apache.solr.core.CoreDescriptor;
import org.apache.solr.core.DirectoryFactory;
import org.apache.solr.core.SolrCore;
+import org.apache.solr.logging.MDCLoggingContext;
import org.apache.solr.util.RefCounted;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -282,52 +283,57 @@ public final class DefaultSolrCoreState extends SolrCoreState implements Recover
@Override
public void doRecovery(CoreContainer cc, CoreDescriptor cd) {
- if (SKIP_AUTO_RECOVERY) {
- log.warn("Skipping recovery according to sys prop solrcloud.skip.autorecovery");
- return;
- }
-
- // check before we grab the lock
- if (cc.isShutDown()) {
- log.warn("Skipping recovery because Solr is close");
- return;
- }
-
- synchronized (recoveryLock) {
- // to be air tight we must also check after lock
+ MDCLoggingContext.setCoreDescriptor(cd);
+ try {
+ if (SKIP_AUTO_RECOVERY) {
+ log.warn("Skipping recovery according to sys prop solrcloud.skip.autorecovery");
+ return;
+ }
+
+ // check before we grab the lock
if (cc.isShutDown()) {
- log.warn("Skipping recovery because Solr is close");
+ log.warn("Skipping recovery because Solr is shutdown");
return;
}
- log.info("Running recovery - first canceling any ongoing recovery");
- cancelRecovery();
- while (recoveryRunning) {
- try {
- recoveryLock.wait(1000);
- } catch (InterruptedException e) {
-
- }
- // check again for those that were waiting
+ synchronized (recoveryLock) {
+ // to be air tight we must also check after lock
if (cc.isShutDown()) {
- log.warn("Skipping recovery because Solr is close");
+ log.warn("Skipping recovery because Solr is shutdown");
return;
}
- if (closed) return;
+ log.info("Running recovery - first canceling any ongoing recovery");
+ cancelRecovery();
+
+ while (recoveryRunning) {
+ try {
+ recoveryLock.wait(1000);
+ } catch (InterruptedException e) {
+
+ }
+ // check again for those that were waiting
+ if (cc.isShutDown()) {
+ log.warn("Skipping recovery because Solr is shutdown");
+ return;
+ }
+ if (closed) return;
+ }
+
+ // if true, we are recovering after startup and shouldn't have (or be receiving) additional updates (except for
+ // local tlog recovery)
+ boolean recoveringAfterStartup = recoveryStrat == null;
+
+ recoveryThrottle.minimumWaitBetweenActions();
+ recoveryThrottle.markAttemptingAction();
+
+ recoveryStrat = new RecoveryStrategy(cc, cd, this);
+ recoveryStrat.setRecoveringAfterStartup(recoveringAfterStartup);
+ recoveryStrat.start();
+ recoveryRunning = true;
}
-
- // if true, we are recovering after startup and shouldn't have (or be receiving) additional updates (except for local tlog recovery)
- boolean recoveringAfterStartup = recoveryStrat == null;
-
- recoveryThrottle.minimumWaitBetweenActions();
- recoveryThrottle.markAttemptingAction();
-
- recoveryStrat = new RecoveryStrategy(cc, cd, this);
- recoveryStrat.setRecoveringAfterStartup(recoveringAfterStartup);
- recoveryStrat.start();
- recoveryRunning = true;
+ } finally {
+ MDCLoggingContext.clear();
}
-
}
@Override
diff --git a/solr/core/src/java/org/apache/solr/update/PeerSync.java b/solr/core/src/java/org/apache/solr/update/PeerSync.java
index 1b3bf96353b..88ce82199d3 100644
--- a/solr/core/src/java/org/apache/solr/update/PeerSync.java
+++ b/solr/core/src/java/org/apache/solr/update/PeerSync.java
@@ -46,6 +46,7 @@ import org.apache.solr.handler.component.ShardHandler;
import org.apache.solr.handler.component.ShardHandlerFactory;
import org.apache.solr.handler.component.ShardRequest;
import org.apache.solr.handler.component.ShardResponse;
+import org.apache.solr.logging.MDCLoggingContext;
import org.apache.solr.request.LocalSolrQueryRequest;
import org.apache.solr.request.SolrQueryRequest;
import org.apache.solr.response.SolrQueryResponse;
@@ -80,6 +81,7 @@ public class PeerSync {
private final boolean getNoVersionsIsSuccess;
private final HttpClient client;
private final boolean onlyIfActive;
+ private SolrCore core;
// comparator that sorts by absolute value, putting highest first
private static Comparator<Long> absComparator = new Comparator<Long>() {
@@ -128,6 +130,7 @@ public class PeerSync {
}
public PeerSync(SolrCore core, List<String> replicas, int nUpdates, boolean cantReachIsSuccess, boolean getNoVersionsIsSuccess, boolean onlyIfActive) {
+ this.core = core;
this.replicas = replicas;
this.nUpdates = nUpdates;
this.maxUpdates = nUpdates;
@@ -175,95 +178,102 @@ public class PeerSync {
if (ulog == null) {
return false;
}
-
- log.info(msg() + "START replicas=" + replicas + " nUpdates=" + nUpdates);
-
- // TODO: does it ever make sense to allow sync when buffering or applying buffered? Someone might request that we do it...
- if (!(ulog.getState() == UpdateLog.State.ACTIVE || ulog.getState()==UpdateLog.State.REPLAYING)) {
- log.error(msg() + "ERROR, update log not in ACTIVE or REPLAY state. " + ulog);
- // return false;
- }
-
- if (debug) {
- if (startingVersions != null) {
- log.debug(msg() + "startingVersions=" + startingVersions.size() + " " + startingVersions);
- }
- }
-
- // Fire off the requests before getting our own recent updates (for better concurrency)
- // This also allows us to avoid getting updates we don't need... if we got our updates and then got their updates, they would
- // have newer stuff that we also had (assuming updates are going on and are being forwarded).
- for (String replica : replicas) {
- requestVersions(replica);
- }
-
- recentUpdates = ulog.getRecentUpdates();
+ MDCLoggingContext.setCore(core);
try {
- ourUpdates = recentUpdates.getVersions(nUpdates);
- } finally {
- recentUpdates.close();
- }
-
- Collections.sort(ourUpdates, absComparator);
-
- if (startingVersions != null) {
- if (startingVersions.size() == 0) {
- log.warn("no frame of reference to tell if we've missed updates");
- return false;
- }
- Collections.sort(startingVersions, absComparator);
-
- ourLowThreshold = percentile(startingVersions, 0.8f);
- ourHighThreshold = percentile(startingVersions, 0.2f);
-
- // now make sure that the starting updates overlap our updates
- // there shouldn't be reorders, so any overlap will do.
-
- long smallestNewUpdate = Math.abs(ourUpdates.get(ourUpdates.size()-1));
-
- if (Math.abs(startingVersions.get(0)) < smallestNewUpdate) {
- log.warn(msg() + "too many updates received since start - startingUpdates no longer overlaps with our currentUpdates");
- return false;
+ log.info(msg() + "START replicas=" + replicas + " nUpdates=" + nUpdates);
+
+ // TODO: does it ever make sense to allow sync when buffering or applying buffered? Someone might request that we
+ // do it...
+ if (!(ulog.getState() == UpdateLog.State.ACTIVE || ulog.getState() == UpdateLog.State.REPLAYING)) {
+ log.error(msg() + "ERROR, update log not in ACTIVE or REPLAY state. " + ulog);
+ // return false;
}
-
- // let's merge the lists
- List<Long> newList = new ArrayList<>(ourUpdates);
- for (Long ver : startingVersions) {
- if (Math.abs(ver) < smallestNewUpdate) {
- newList.add(ver);
+
+ if (debug) {
+ if (startingVersions != null) {
+ log.debug(msg() + "startingVersions=" + startingVersions.size() + " " + startingVersions);
}
}
-
- ourUpdates = newList;
- } else {
-
- if (ourUpdates.size() > 0) {
- ourLowThreshold = percentile(ourUpdates, 0.8f);
- ourHighThreshold = percentile(ourUpdates, 0.2f);
- } else {
- // we have no versions and hence no frame of reference to tell if we can use a peers
- // updates to bring us into sync
- log.info(msg() + "DONE. We have no versions. sync failed.");
- return false;
+
+ // Fire off the requests before getting our own recent updates (for better concurrency)
+ // This also allows us to avoid getting updates we don't need... if we got our updates and then got their updates,
+ // they would
+ // have newer stuff that we also had (assuming updates are going on and are being forwarded).
+ for (String replica : replicas) {
+ requestVersions(replica);
}
- }
-
- ourUpdateSet = new HashSet<>(ourUpdates);
- requestedUpdateSet = new HashSet<>(ourUpdates);
-
- for(;;) {
- ShardResponse srsp = shardHandler.takeCompletedOrError();
- if (srsp == null) break;
- boolean success = handleResponse(srsp);
- if (!success) {
- log.info(msg() + "DONE. sync failed");
- shardHandler.cancelAll();
- return false;
+
+ recentUpdates = ulog.getRecentUpdates();
+ try {
+ ourUpdates = recentUpdates.getVersions(nUpdates);
+ } finally {
+ recentUpdates.close();
+ }
+
+ Collections.sort(ourUpdates, absComparator);
+
+ if (startingVersions != null) {
+ if (startingVersions.size() == 0) {
+ log.warn("no frame of reference to tell if we've missed updates");
+ return false;
+ }
+ Collections.sort(startingVersions, absComparator);
+
+ ourLowThreshold = percentile(startingVersions, 0.8f);
+ ourHighThreshold = percentile(startingVersions, 0.2f);
+
+ // now make sure that the starting updates overlap our updates
+ // there shouldn't be reorders, so any overlap will do.
+
+ long smallestNewUpdate = Math.abs(ourUpdates.get(ourUpdates.size() - 1));
+
+ if (Math.abs(startingVersions.get(0)) < smallestNewUpdate) {
+ log.warn(msg()
+ + "too many updates received since start - startingUpdates no longer overlaps with our currentUpdates");
+ return false;
+ }
+
+ // let's merge the lists
+ List<Long> newList = new ArrayList<>(ourUpdates);
+ for (Long ver : startingVersions) {
+ if (Math.abs(ver) < smallestNewUpdate) {
+ newList.add(ver);
+ }
+ }
+
+ ourUpdates = newList;
+ } else {
+
+ if (ourUpdates.size() > 0) {
+ ourLowThreshold = percentile(ourUpdates, 0.8f);
+ ourHighThreshold = percentile(ourUpdates, 0.2f);
+ } else {
+ // we have no versions and hence no frame of reference to tell if we can use a peers
+ // updates to bring us into sync
+ log.info(msg() + "DONE. We have no versions. sync failed.");
+ return false;
+ }
+ }
+
+ ourUpdateSet = new HashSet<>(ourUpdates);
+ requestedUpdateSet = new HashSet<>(ourUpdates);
+
+ for (;;) {
+ ShardResponse srsp = shardHandler.takeCompletedOrError();
+ if (srsp == null) break;
+ boolean success = handleResponse(srsp);
+ if (!success) {
+ log.info(msg() + "DONE. sync failed");
+ shardHandler.cancelAll();
+ return false;
+ }
}
+
+ log.info(msg() + "DONE. sync succeeded");
+ return true;
+ } finally {
+ MDCLoggingContext.clear();
}
-
- log.info(msg() + "DONE. sync succeeded");
- return true;
}
private void requestVersions(String replica) {
diff --git a/solr/core/src/test-files/log4j.properties b/solr/core/src/test-files/log4j.properties
index 659b430231b..86446e93953 100644
--- a/solr/core/src/test-files/log4j.properties
+++ b/solr/core/src/test-files/log4j.properties
@@ -3,9 +3,8 @@ log4j.rootLogger=INFO, CONSOLE
log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender
log4j.appender.CONSOLE.Target=System.err
-log4j.appender.CONSOLE.layout=org.apache.solr.util.SolrLogLayout
-log4j.appender.CONSOLE.layout.ConversionPattern=%-5p - %d{yyyy-MM-dd HH:mm:ss.SSS}; %C; %m\n
-
+log4j.appender.CONSOLE.layout=org.apache.log4j.EnhancedPatternLayout
+log4j.appender.CONSOLE.layout.ConversionPattern=%-4r %-5p (%t) [%X{node_name} %X{collection} %X{shard} %X{replica} %X{core}] %c{1.} %m%n
log4j.logger.org.apache.zookeeper=WARN
log4j.logger.org.apache.hadoop=WARN
log4j.logger.org.apache.directory=WARN
diff --git a/solr/server/resources/log4j.properties b/solr/server/resources/log4j.properties
index 1f2916a6bfd..2465eaeb83f 100644
--- a/solr/server/resources/log4j.properties
+++ b/solr/server/resources/log4j.properties
@@ -4,8 +4,8 @@ log4j.rootLogger=INFO, file, CONSOLE
log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender
-log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout
-log4j.appender.CONSOLE.layout.ConversionPattern=%-4r [%t] %-5p %c %x [%X{collection} %X{shard} %X{replica} %X{core}] \u2013 %m%n
+log4j.appender.CONSOLE.layout=org.apache.log4j.EnhancedPatternLayout
+log4j.appender.CONSOLE.layout.ConversionPattern=%-4r %-5p (%t) [%X{collection} %X{shard} %X{replica} %X{core}] %c{1.} %m%n
#- size rotation with log cleanup.
log4j.appender.file=org.apache.log4j.RollingFileAppender
@@ -14,8 +14,8 @@ log4j.appender.file.MaxBackupIndex=9
#- File to log to and log format
log4j.appender.file.File=${solr.log}/solr.log
-log4j.appender.file.layout=org.apache.log4j.PatternLayout
-log4j.appender.file.layout.ConversionPattern=%-5p - %d{yyyy-MM-dd HH:mm:ss.SSS}; [%X{collection} %X{shard} %X{replica} %X{core}] %C; %m\n
+log4j.appender.file.layout=org.apache.log4j.EnhancedPatternLayout
+log4j.appender.file.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss.SSS} %-5p (%t) [%X{collection} %X{shard} %X{replica} %X{core}] %c{1.} %m\n
log4j.logger.org.apache.zookeeper=WARN
log4j.logger.org.apache.hadoop=WARN
diff --git a/solr/solrj/src/java/org/apache/solr/common/util/ExecutorUtil.java b/solr/solrj/src/java/org/apache/solr/common/util/ExecutorUtil.java
index 55b183de121..87b60e27b05 100644
--- a/solr/solrj/src/java/org/apache/solr/common/util/ExecutorUtil.java
+++ b/solr/solrj/src/java/org/apache/solr/common/util/ExecutorUtil.java
@@ -1,5 +1,7 @@
package org.apache.solr.common.util;
+import java.util.Collection;
+
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
@@ -128,8 +130,19 @@ public class ExecutorUtil {
@Override
public void execute(final Runnable command) {
final Map<String, String> submitterContext = MDC.getCopyOfContextMap();
- String ctxStr = submitterContext != null && !submitterContext.isEmpty() ?
- submitterContext.toString().replace("/", "//") : "";
+ StringBuilder contextString = new StringBuilder();
+ if (submitterContext != null) {
+ Collection<String> values = submitterContext.values();
+
+ for (String value : values) {
+ contextString.append(value + " ");
+ }
+ if (contextString.length() > 1) {
+ contextString.setLength(contextString.length() - 1);
+ }
+ }
+
+ String ctxStr = contextString.toString().replace("/", "//");
final String submitterContextStr = ctxStr.length() <= MAX_THREAD_NAME_LEN ? ctxStr : ctxStr.substring(0, MAX_THREAD_NAME_LEN);
final Exception submitterStackTrace = new Exception("Submitter stack trace");
super.execute(new Runnable() {
diff --git a/solr/solrj/src/test-files/log4j.properties b/solr/solrj/src/test-files/log4j.properties
index 9b74a5f22b2..86446e93953 100644
--- a/solr/solrj/src/test-files/log4j.properties
+++ b/solr/solrj/src/test-files/log4j.properties
@@ -3,8 +3,28 @@ log4j.rootLogger=INFO, CONSOLE
log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender
log4j.appender.CONSOLE.Target=System.err
-log4j.appender.CONSOLE.layout=org.apache.solr.util.SolrLogLayout
-log4j.appender.CONSOLE.layout.ConversionPattern=%-5p - %d{yyyy-MM-dd HH:mm:ss.SSS}; %C; %m\n
-
+log4j.appender.CONSOLE.layout=org.apache.log4j.EnhancedPatternLayout
+log4j.appender.CONSOLE.layout.ConversionPattern=%-4r %-5p (%t) [%X{node_name} %X{collection} %X{shard} %X{replica} %X{core}] %c{1.} %m%n
log4j.logger.org.apache.zookeeper=WARN
log4j.logger.org.apache.hadoop=WARN
+log4j.logger.org.apache.directory=WARN
+log4j.logger.org.apache.solr.hadoop=INFO
+
+#log4j.logger.org.apache.solr.update.processor.LogUpdateProcessor=DEBUG
+#log4j.logger.org.apache.solr.update.processor.DistributedUpdateProcessor=DEBUG
+#log4j.logger.org.apache.solr.update.PeerSync=DEBUG
+#log4j.logger.org.apache.solr.core.CoreContainer=DEBUG
+#log4j.logger.org.apache.solr.cloud.RecoveryStrategy=DEBUG
+#log4j.logger.org.apache.solr.cloud.SyncStrategy=DEBUG
+#log4j.logger.org.apache.solr.handler.admin.CoreAdminHandler=DEBUG
+#log4j.logger.org.apache.solr.cloud.ZkController=DEBUG
+#log4j.logger.org.apache.solr.update.DefaultSolrCoreState=DEBUG
+#log4j.logger.org.apache.solr.common.cloud.ConnectionManager=DEBUG
+#log4j.logger.org.apache.solr.update.UpdateLog=DEBUG
+#log4j.logger.org.apache.solr.cloud.ChaosMonkey=DEBUG
+#log4j.logger.org.apache.solr.update.TransactionLog=DEBUG
+#log4j.logger.org.apache.solr.handler.ReplicationHandler=DEBUG
+#log4j.logger.org.apache.solr.handler.IndexFetcher=DEBUG
+
+#log4j.logger.org.apache.solr.common.cloud.ClusterStateUtil=DEBUG
+#log4j.logger.org.apache.solr.cloud.OverseerAutoReplicaFailoverThread=DEBUG
\ No newline at end of file
diff --git a/solr/test-framework/src/java/org/apache/solr/SolrTestCaseJ4.java b/solr/test-framework/src/java/org/apache/solr/SolrTestCaseJ4.java
index f56a2c5d41c..aa1e5121228 100644
--- a/solr/test-framework/src/java/org/apache/solr/SolrTestCaseJ4.java
+++ b/solr/test-framework/src/java/org/apache/solr/SolrTestCaseJ4.java
@@ -17,9 +17,41 @@
package org.apache.solr;
-import com.carrotsearch.randomizedtesting.RandomizedContext;
-import com.carrotsearch.randomizedtesting.annotations.ThreadLeakFilters;
-import com.carrotsearch.randomizedtesting.rules.SystemPropertiesRestoreRule;
+import static com.google.common.base.Preconditions.checkNotNull;
+
+import java.io.File;
+import java.io.IOException;
+import java.io.OutputStreamWriter;
+import java.io.Reader;
+import java.io.StringReader;
+import java.io.StringWriter;
+import java.io.Writer;
+import java.lang.annotation.Documented;
+import java.lang.annotation.ElementType;
+import java.lang.annotation.Inherited;
+import java.lang.annotation.Retention;
+import java.lang.annotation.RetentionPolicy;
+import java.lang.annotation.Target;
+import java.net.URL;
+import java.nio.charset.Charset;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Comparator;
+import java.util.Date;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.Iterator;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Locale;
+import java.util.Map;
+import java.util.Properties;
+import java.util.logging.Level;
+
+import javax.xml.xpath.XPathExpressionException;
+
import org.apache.commons.codec.Charsets;
import org.apache.commons.io.FileUtils;
import org.apache.lucene.analysis.MockAnalyzer;
@@ -55,7 +87,6 @@ import org.apache.solr.core.SolrConfig;
import org.apache.solr.core.SolrCore;
import org.apache.solr.core.SolrResourceLoader;
import org.apache.solr.core.SolrXmlConfig;
-import org.apache.solr.core.ZkContainer;
import org.apache.solr.handler.UpdateRequestHandler;
import org.apache.solr.request.LocalSolrQueryRequest;
import org.apache.solr.request.SolrQueryRequest;
@@ -83,42 +114,9 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.xml.sax.SAXException;
-import javax.xml.xpath.XPathExpressionException;
-import java.io.File;
-import java.io.IOException;
-import java.io.OutputStreamWriter;
-import java.io.Reader;
-import java.io.StringReader;
-import java.io.StringWriter;
-import java.io.Writer;
-import java.lang.annotation.Documented;
-import java.lang.annotation.ElementType;
-import java.lang.annotation.Inherited;
-import java.lang.annotation.Retention;
-import java.lang.annotation.RetentionPolicy;
-import java.lang.annotation.Target;
-import java.net.URL;
-import java.nio.charset.Charset;
-import java.nio.file.Files;
-import java.nio.file.Path;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Comparator;
-import java.util.Date;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.Iterator;
-import java.util.LinkedHashMap;
-import java.util.List;
-import java.util.Locale;
-import java.util.Map;
-import java.util.Properties;
-import java.util.logging.ConsoleHandler;
-import java.util.logging.Handler;
-import java.util.logging.Level;
-import java.util.regex.Pattern;
-
-import static com.google.common.base.Preconditions.checkNotNull;
+import com.carrotsearch.randomizedtesting.RandomizedContext;
+import com.carrotsearch.randomizedtesting.annotations.ThreadLeakFilters;
+import com.carrotsearch.randomizedtesting.rules.SystemPropertiesRestoreRule;
/**
* A junit4 Solr test harness that extends LuceneTestCaseJ4. To change which core is used when loading the schema and solrconfig.xml, simply
@@ -209,7 +207,6 @@ public abstract class SolrTestCaseJ4 extends LuceneTestCase {
System.setProperty("enable.update.log", usually() ? "true" : "false");
System.setProperty("tests.shardhandler.randomSeed", Long.toString(random().nextLong()));
System.setProperty("solr.clustering.enabled", "false");
- setupLogging();
startTrackingSearchers();
ignoreException("ignore_exception");
newRandomConfig();
@@ -396,33 +393,6 @@ public abstract class SolrTestCaseJ4 extends LuceneTestCase {
super.tearDown();
}
- public static SolrLogFormatter formatter;
-
- public static void setupLogging() {
- boolean register = false;
- Handler[] handlers = java.util.logging.Logger.getLogger("").getHandlers();
- ConsoleHandler consoleHandler = null;
- for (Handler handler : handlers) {
- if (handler instanceof ConsoleHandler) {
- consoleHandler = (ConsoleHandler)handler;
- break;
- }
- }
-
- if (consoleHandler == null) {
- consoleHandler = new ConsoleHandler();
- register = true;
- }
-
- consoleHandler.setLevel(Level.ALL);
- formatter = new SolrLogFormatter();
- consoleHandler.setFormatter(formatter);
-
- if (register) {
- java.util.logging.Logger.getLogger("").addHandler(consoleHandler);
- }
- }
-
public static void setLoggingLevel(Level level) {
java.util.logging.Logger logger = java.util.logging.Logger.getLogger("");
logger.setLevel(level);
diff --git a/solr/test-framework/src/java/org/apache/solr/cloud/AbstractFullDistribZkTestBase.java b/solr/test-framework/src/java/org/apache/solr/cloud/AbstractFullDistribZkTestBase.java
index 660925608de..6af9a6f3b1e 100644
--- a/solr/test-framework/src/java/org/apache/solr/cloud/AbstractFullDistribZkTestBase.java
+++ b/solr/test-framework/src/java/org/apache/solr/cloud/AbstractFullDistribZkTestBase.java
@@ -16,9 +16,10 @@ package org.apache.solr.cloud;
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-
-import static org.apache.solr.cloud.OverseerCollectionProcessor.*;
-import static org.apache.solr.common.cloud.ZkNodeProps.*;
+import static org.apache.solr.cloud.OverseerCollectionProcessor.CREATE_NODE_SET;
+import static org.apache.solr.cloud.OverseerCollectionProcessor.NUM_SLICES;
+import static org.apache.solr.cloud.OverseerCollectionProcessor.SHARDS_PROP;
+import static org.apache.solr.common.cloud.ZkNodeProps.makeMap;
import java.io.File;
import java.io.IOException;
@@ -92,8 +93,6 @@ public abstract class AbstractFullDistribZkTestBase extends AbstractDistribZkTes
@BeforeClass
public static void beforeFullSolrCloudTest() {
- // shorten the log output more for this test type
- if (formatter != null) formatter.setShorterFormat();
}
public static final String SHARD1 = "shard1";