Apache Lucene open-source search software
SOLR-11216: Race condition in peerSync
Cao Manh Datdaff67e27931
diff --git a/solr/CHANGES.txt b/solr/CHANGES.txtindex bdefda9806f..fcb1a281e97 100644--- a/solr/CHANGES.txt+++ b/solr/CHANGES.txt@@ -96,6 +96,8 @@ Bug FixesA user can now specify nrtReplicas/tlogReplicas/pullReplicas while restoring the collection.Specifying replicationFactor or nrtReplicas have the same effect and only one can be specified (Varun Thacker)+* SOLR-11216: Race condition in PeerSync (Cao Manh Dat)+Optimizations----------------------diff --git a/solr/core/src/java/org/apache/solr/cloud/RecoveryStrategy.java b/solr/core/src/java/org/apache/solr/cloud/RecoveryStrategy.javaindex 966497b0938..f49f626f5d3 100644--- a/solr/core/src/java/org/apache/solr/cloud/RecoveryStrategy.java+++ b/solr/core/src/java/org/apache/solr/cloud/RecoveryStrategy.java@@ -21,7 +21,6 @@ import java.io.IOException;import java.lang.invoke.MethodHandles;import java.util.ArrayList;import java.util.Arrays;-import java.util.Collections;import java.util.List;import java.util.concurrent.ExecutionException;import java.util.concurrent.Future;@@ -60,7 +59,7 @@ import org.apache.solr.request.SolrRequestHandler;import org.apache.solr.search.SolrIndexSearcher;import org.apache.solr.update.CdcrUpdateLog;import org.apache.solr.update.CommitUpdateCommand;-import org.apache.solr.update.PeerSync;+import org.apache.solr.update.PeerSyncWithLeader;import org.apache.solr.update.UpdateLog;import org.apache.solr.update.UpdateLog.RecoveryInfo;import org.apache.solr.update.processor.DistributedUpdateProcessor;@@ -573,6 +572,7 @@ public class RecoveryStrategy implements Runnable, Closeable {// that started before they saw recovering state// are sure to have finished (see SOLR-7141 for// discussion around current value)+ //TODO since SOLR-11216, we probably won't need thistry {Thread.sleep(waitForUpdatesWithStaleStatePauseMilliSeconds);} catch (InterruptedException e) {@@ -585,15 +585,15 @@ public class RecoveryStrategy implements Runnable, Closeable {LOG.info("Attempting to PeerSync from [{}] - recoveringAfterStartup=[{}]", leader.getCoreUrl(), recoveringAfterStartup);// System.out.println("Attempting to PeerSync from " + leaderUrl// + " i am:" + zkController.getNodeName());- PeerSync peerSync = new PeerSync(core,- Collections.singletonList(leader.getCoreUrl()), ulog.getNumRecordsToKeep(), false, false);- peerSync.setStartingVersions(recentVersions);- boolean syncSuccess = peerSync.sync().isSuccess();+ PeerSyncWithLeader peerSyncWithLeader = new PeerSyncWithLeader(core,+ leader.getCoreUrl(), ulog.getNumRecordsToKeep());+ boolean syncSuccess = peerSyncWithLeader.sync(recentVersions).isSuccess();if (syncSuccess) {SolrQueryRequest req = new LocalSolrQueryRequest(core,new ModifiableSolrParams());// force open a new searchercore.getUpdateHandler().commit(new CommitUpdateCommand(req, false));+ req.close();LOG.info("PeerSync stage of recovery was successful.");// solrcloud_debug@@ -786,6 +786,7 @@ public class RecoveryStrategy implements Runnable, Closeable {SolrQueryRequest req = new LocalSolrQueryRequest(core,new ModifiableSolrParams());core.getUpdateHandler().getUpdateLog().copyOverBufferingUpdates(new CommitUpdateCommand(req, false));+ req.close();return null;}Future<RecoveryInfo> future = core.getUpdateHandler().getUpdateLog().applyBufferedUpdates();diff --git a/solr/core/src/java/org/apache/solr/cloud/SyncStrategy.java b/solr/core/src/java/org/apache/solr/cloud/SyncStrategy.javaindex 4368af9458a..3d9a964f8d6 100644--- a/solr/core/src/java/org/apache/solr/cloud/SyncStrategy.java+++ b/solr/core/src/java/org/apache/solr/cloud/SyncStrategy.java@@ -176,7 +176,7 @@ public class SyncStrategy {// Fingerprinting here is off because the we currently rely on having at least one of the nodes return "true", and if replicas are out-of-sync// we still need to pick one as leader. A followup sync from the replica to the new leader (with fingerprinting on) should then fail and// initiate recovery-by-replication.- PeerSync peerSync = new PeerSync(core, syncWith, core.getUpdateHandler().getUpdateLog().getNumRecordsToKeep(), true, true, peerSyncOnlyWithActive, false);+ PeerSync peerSync = new PeerSync(core, syncWith, core.getUpdateHandler().getUpdateLog().getNumRecordsToKeep(), true, peerSyncOnlyWithActive, false);return peerSync.sync();}@@ -252,6 +252,7 @@ public class SyncStrategy {}private void requestSync(String baseUrl, String replica, String leaderUrl, String coreName, int nUpdates) {+ //TODO should we use peerSyncWithLeader instead?ShardCoreRequest sreq = new ShardCoreRequest();sreq.coreName = coreName;sreq.baseUrl = baseUrl;diff --git a/solr/core/src/java/org/apache/solr/handler/component/RealTimeGetComponent.java b/solr/core/src/java/org/apache/solr/handler/component/RealTimeGetComponent.javaindex 29e8219ec2a..ff3cdbf1c5b 100644--- a/solr/core/src/java/org/apache/solr/handler/component/RealTimeGetComponent.java+++ b/solr/core/src/java/org/apache/solr/handler/component/RealTimeGetComponent.java@@ -80,6 +80,7 @@ import org.apache.solr.update.CdcrUpdateLog;import org.apache.solr.update.DocumentBuilder;import org.apache.solr.update.IndexFingerprint;import org.apache.solr.update.PeerSync;+import org.apache.solr.update.PeerSyncWithLeader;import org.apache.solr.update.UpdateLog;import org.apache.solr.util.RefCounted;import org.apache.solr.util.TestInjection;@@ -1009,6 +1010,15 @@ public class RealTimeGetComponent extends SearchComponentUpdateLog ulog = req.getCore().getUpdateHandler().getUpdateLog();if (ulog == null) return;+ String syncWithLeader = params.get("syncWithLeader");+ if (syncWithLeader != null) {+ List<Long> versions;+ try (UpdateLog.RecentUpdates recentUpdates = ulog.getRecentUpdates()) {+ versions = recentUpdates.getVersions(nVersions);+ }+ processSyncWithLeader(rb, nVersions, syncWithLeader, versions);+ return;+ }// get fingerprint first as it will cause a soft commit// and would avoid mismatch if documents are being actively index especially during PeerSync@@ -1023,6 +1033,12 @@ public class RealTimeGetComponent extends SearchComponent}}+ public void processSyncWithLeader(ResponseBuilder rb, int nVersions, String syncWithLeader, List<Long> versions) {+ PeerSyncWithLeader peerSync = new PeerSyncWithLeader(rb.req.getCore(), syncWithLeader, nVersions);+ boolean success = peerSync.sync(versions).isSuccess();+ rb.rsp.add("syncWithLeader", success);+ }+public void processSync(ResponseBuilder rb, int nVersions, String sync) {@@ -1040,7 +1056,7 @@ public class RealTimeGetComponent extends SearchComponentboolean cantReachIsSuccess = rb.req.getParams().getBool("cantReachIsSuccess", false);- PeerSync peerSync = new PeerSync(rb.req.getCore(), replicas, nVersions, cantReachIsSuccess, true);+ PeerSync peerSync = new PeerSync(rb.req.getCore(), replicas, nVersions, cantReachIsSuccess);boolean success = peerSync.sync().isSuccess();// TODO: more complex response?@@ -1106,7 +1122,9 @@ public class RealTimeGetComponent extends SearchComponent// Must return all delete-by-query commands that occur after the first add requested// since they may apply.- updates.addAll(recentUpdates.getDeleteByQuery(minVersion));+ if (params.getBool("skipDbq", false)) {+ updates.addAll(recentUpdates.getDeleteByQuery(minVersion));+ }rb.rsp.add("updates", updates);diff --git a/solr/core/src/java/org/apache/solr/update/HdfsUpdateLog.java b/solr/core/src/java/org/apache/solr/update/HdfsUpdateLog.javaindex 8ca4b1cb3e5..c0bbeca6f2b 100644--- a/solr/core/src/java/org/apache/solr/update/HdfsUpdateLog.java+++ b/solr/core/src/java/org/apache/solr/update/HdfsUpdateLog.java@@ -304,6 +304,7 @@ public class HdfsUpdateLog extends UpdateLog {String newLogName = String.format(Locale.ROOT, LOG_FILENAME_PATTERN, BUFFER_TLOG_NAME, System.nanoTime());bufferTlog = new HdfsTransactionLog(fs, new Path(tlogDir, newLogName),globalStrings, tlogDfsReplication);+ bufferTlog.isBuffer = true;}@Overridediff --git a/solr/core/src/java/org/apache/solr/update/PeerSync.java b/solr/core/src/java/org/apache/solr/update/PeerSync.javaindex 8931e63a501..6c3c5784a8e 100644--- a/solr/core/src/java/org/apache/solr/update/PeerSync.java+++ b/solr/core/src/java/org/apache/solr/update/PeerSync.java@@ -21,12 +21,12 @@ import java.lang.invoke.MethodHandles;import java.net.ConnectException;import java.net.SocketException;import java.util.ArrayList;-import java.util.Collections;import java.util.Comparator;import java.util.HashSet;import java.util.List;import java.util.Optional;import java.util.Set;+import java.util.function.Supplier;import java.util.stream.Collectors;import com.codahale.metrics.Counter;@@ -46,7 +46,6 @@ import org.apache.solr.core.SolrCore;import org.apache.solr.core.SolrInfoBean;import org.apache.solr.handler.component.HttpShardHandlerFactory;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;@@ -73,11 +72,10 @@ import static org.apache.solr.update.processor.DistributingUpdateProcessorFactor*/public class PeerSync implements SolrMetricProducer {private static final Logger log = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());- private boolean debug = log.isDebugEnabled();+ private static final boolean debug = log.isDebugEnabled();private List<String> replicas;private int nUpdates;- private int maxUpdates; // maximum number of updates to request before failingprivate UpdateHandler uhandler;private UpdateLog ulog;@@ -85,20 +83,14 @@ public class PeerSync implements SolrMetricProducer {private ShardHandler shardHandler;private List<SyncShardRequest> requests = new ArrayList<>();- private List<Long> startingVersions;-- private List<Long> ourUpdates;- private Set<Long> ourUpdateSet;- private Set<Long> requestedUpdateSet;- private long ourLowThreshold; // 20th percentile- private long ourHighThreshold; // 80th percentile- private long ourHighest; // currently just used for logging/debugging purposesprivate final boolean cantReachIsSuccess;- private final boolean getNoVersionsIsSuccess;private final boolean doFingerprint;private final HttpClient client;private final boolean onlyIfActive;private SolrCore core;+ private Updater updater;++ private MissedUpdatesFinder missedUpdatesFinder;// metricsprivate Timer syncTime;@@ -106,55 +98,24 @@ public class PeerSync implements SolrMetricProducer {private Counter syncSkipped;// comparator that sorts by absolute value, putting highest first- public static Comparator<Long> absComparator = (o1, o2) -> {- long l1 = Math.abs(o1);- long l2 = Math.abs(o2);- if (l1 > l2) return -1;- if (l1 < l2) return 1;- return 0;- };-- // comparator that sorts update records by absolute value of version, putting lowest first- private static Comparator<Object> updateRecordComparator = (o1, o2) -> {- if (!(o1 instanceof List)) return 1;- if (!(o2 instanceof List)) return -1;-- List lst1 = (List) o1;- List lst2 = (List) o2;-- long l1 = Math.abs((Long) lst1.get(1));- long l2 = Math.abs((Long) lst2.get(1));-- if (l1 > l2) return 1;- if (l1 < l2) return -1;- return 0;- };+ public static Comparator<Long> absComparator = (l1, l2) -> Long.compare(Math.abs(l2), Math.abs(l1));private static class SyncShardRequest extends ShardRequest {- List<Long> reportedVersions;IndexFingerprint fingerprint;boolean doFingerprintComparison;- List<Long> requestedUpdates;Exception updateException;- List<String> requestedRanges;long totalRequestedUpdates;}- public PeerSync(SolrCore core, List<String> replicas, int nUpdates) {- this(core, replicas, nUpdates, false, true);- }-- public PeerSync(SolrCore core, List<String> replicas, int nUpdates, boolean cantReachIsSuccess, boolean getNoVersionsIsSuccess) {- this(core, replicas, nUpdates, cantReachIsSuccess, getNoVersionsIsSuccess, false, true);+ public PeerSync(SolrCore core, List<String> replicas, int nUpdates, boolean cantReachIsSuccess) {+ this(core, replicas, nUpdates, cantReachIsSuccess, false, true);}- public PeerSync(SolrCore core, List<String> replicas, int nUpdates, boolean cantReachIsSuccess, boolean getNoVersionsIsSuccess, boolean onlyIfActive, boolean doFingerprint) {+ public PeerSync(SolrCore core, List<String> replicas, int nUpdates, boolean cantReachIsSuccess, boolean onlyIfActive, boolean doFingerprint) {this.core = core;this.replicas = replicas;this.nUpdates = nUpdates;- this.maxUpdates = nUpdates;this.cantReachIsSuccess = cantReachIsSuccess;- this.getNoVersionsIsSuccess = getNoVersionsIsSuccess;this.doFingerprint = doFingerprint && !("true".equals(System.getProperty("solr.disableFingerprint")));this.client = core.getCoreContainer().getUpdateShardHandler().getDefaultHttpClient();this.onlyIfActive = onlyIfActive;@@ -164,6 +125,7 @@ public class PeerSync implements SolrMetricProducer {// TODO: closeshardHandlerFactory = (HttpShardHandlerFactory) core.getCoreContainer().getShardHandlerFactory();shardHandler = shardHandlerFactory.getShardHandler(client);+ this.updater = new Updater(msg(), core);core.getCoreMetricManager().registerMetricProducer(SolrInfoBean.Category.REPLICATION.toString(), this);}@@ -177,12 +139,7 @@ public class PeerSync implements SolrMetricProducer {syncSkipped = manager.counter(null, registry, "skipped", scope, METRIC_SCOPE);}- /** optional list of updates we had before possibly receiving new updates */- public void setStartingVersions(List<Long> startingVersions) {- this.startingVersions = startingVersions;- }-- public long percentile(List<Long> arr, float frac) {+ public static long percentile(List<Long> arr, float frac) {int elem = (int) (arr.size() * frac);return Math.abs(arr.get(elem));}@@ -201,36 +158,6 @@ public class PeerSync implements SolrMetricProducer {return "PeerSync: core="+uhandler.core.getName()+ " url="+myURL +" ";}- public static class PeerSyncResult {- private final boolean success;- private final Boolean otherHasVersions;-- public PeerSyncResult(boolean success, Boolean otherHasVersions) {- this.success = success;- this.otherHasVersions = otherHasVersions;- }-- public boolean isSuccess() {- return success;- }-- public Optional<Boolean> getOtherHasVersions() {- return Optional.ofNullable(otherHasVersions);- }-- public static PeerSyncResult success() {- return new PeerSyncResult(true, null);- }-- public static PeerSyncResult failure() {- return new PeerSyncResult(false, null);- }-- public static PeerSyncResult failure(boolean otherHasVersions) {- return new PeerSyncResult(false, otherHasVersions);- }- }-/** Returns true if peer sync was successful, meaning that this core may be considered to have the latest updates.* It does not mean that the remote replica is in sync with us.*/@@ -243,12 +170,7 @@ public class PeerSync implements SolrMetricProducer {Timer.Context timerContext = null;try {log.info(msg() + "START replicas=" + replicas + " nUpdates=" + nUpdates);-- if (debug) {- if (startingVersions != null) {- log.debug(msg() + "startingVersions=" + startingVersions.size() + " " + startingVersions);- }- }+// check if we already in sync to begin withif(doFingerprint && alreadyInSync()) {syncSkipped.inc();@@ -266,82 +188,38 @@ public class PeerSync implements SolrMetricProducer {requestVersions(replica);}- try {- // waiting a little bit, there are a chance that an update is sending from leader,- // so it will present in the response, but not in our recent updates (SOLR-10126)- Thread.sleep(300);- } catch (InterruptedException e) {- throw new SolrException(SolrException.ErrorCode.SERVER_ERROR, e);- }-+ long ourLowThreshold, ourHighThreshold;+ List<Long> ourUpdates;try (UpdateLog.RecentUpdates recentUpdates = ulog.getRecentUpdates()) {ourUpdates = recentUpdates.getVersions(nUpdates);}- Collections.sort(ourUpdates, absComparator);-- if (startingVersions != null) {- if (startingVersions.size() == 0) {- log.warn("no frame of reference to tell if we've missed updates");- syncErrors.inc();- return PeerSyncResult.failure();- }- 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");- syncErrors.inc();- return PeerSyncResult.failure();- }-- // 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;- Collections.sort(ourUpdates, absComparator);+ ourUpdates.sort(absComparator);++ if (ourUpdates.size() > 0) {+ ourLowThreshold = percentile(ourUpdates, 0.8f);+ ourHighThreshold = percentile(ourUpdates, 0.2f);} 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.");- for (;;) {- ShardResponse srsp = shardHandler.takeCompletedOrError();- if (srsp == null) break;- if (srsp.getException() == null) {- List<Long> otherVersions = (List<Long>)srsp.getSolrResponse().getResponse().get("versions");- if (otherVersions != null && !otherVersions.isEmpty()) {- syncErrors.inc();- return PeerSyncResult.failure(true);- }+ // 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.");+ for (;;) {+ ShardResponse srsp = shardHandler.takeCompletedOrError();+ if (srsp == null) break;+ if (srsp.getException() == null) {+ List<Long> otherVersions = (List<Long>)srsp.getSolrResponse().getResponse().get("versions");+ if (otherVersions != null && !otherVersions.isEmpty()) {+ syncErrors.inc();+ return PeerSyncResult.failure(true);}}- syncErrors.inc();- return PeerSyncResult.failure(false);}+ syncErrors.inc();+ return PeerSyncResult.failure(false);}- ourHighest = ourUpdates.get(0);- ourUpdateSet = new HashSet<>(ourUpdates);- requestedUpdateSet = new HashSet<>();-+ this.missedUpdatesFinder = new MissedUpdatesFinder(ourUpdates, msg(), nUpdates, ourLowThreshold, ourHighThreshold);+for (;;) {ShardResponse srsp = shardHandler.takeCompletedOrError();if (srsp == null) break;@@ -540,86 +418,12 @@ public class PeerSync implements SolrMetricProducer {return true;}- private boolean handleVersionsWithRanges(ShardResponse srsp, List<Long> otherVersions, SyncShardRequest sreq,- boolean completeList, long otherHigh, long otherHighest) {- // we may endup asking for updates for too many versions, causing 2MB post payload limit. Construct a range of- // versions to request instead of asking individual versions- List<String> rangesToRequest = new ArrayList<>();-- // construct ranges to request- // both ourUpdates and otherVersions are sorted with highest range first- // may be we can create another reverse the lists and avoid confusion- int ourUpdatesIndex = ourUpdates.size() - 1;- int otherUpdatesIndex = otherVersions.size() - 1;- long totalRequestedVersions = 0;-- while (otherUpdatesIndex >= 0) {- // we have run out of ourUpdates, pick up all the remaining versions from the other versions- if (ourUpdatesIndex < 0) {- String range = otherVersions.get(otherUpdatesIndex) + "..." + otherVersions.get(0);- rangesToRequest.add(range);- totalRequestedVersions += otherUpdatesIndex + 1;- break;- }-- // stop when the entries get old enough that reorders may lead us to see updates we don't need- if (!completeList && Math.abs(otherVersions.get(otherUpdatesIndex)) < ourLowThreshold) break;-- if (ourUpdates.get(ourUpdatesIndex).longValue() == otherVersions.get(otherUpdatesIndex).longValue()) {- ourUpdatesIndex--;- otherUpdatesIndex--;- } else if (Math.abs(ourUpdates.get(ourUpdatesIndex)) < Math.abs(otherVersions.get(otherUpdatesIndex))) {- ourUpdatesIndex--;- } else {- long rangeStart = otherVersions.get(otherUpdatesIndex);- while ((otherUpdatesIndex < otherVersions.size())- && (Math.abs(otherVersions.get(otherUpdatesIndex)) < Math.abs(ourUpdates.get(ourUpdatesIndex)))) {- otherUpdatesIndex--;- totalRequestedVersions++;- }- // construct range here- rangesToRequest.add(rangeStart + "..." + otherVersions.get(otherUpdatesIndex + 1));- }- }-- // TODO, do we really need to hold on to all the ranges we requested- // keeping track of totalRequestedUpdates should suffice for verification- sreq.requestedRanges = rangesToRequest;- sreq.totalRequestedUpdates = totalRequestedVersions;-- if (rangesToRequest.isEmpty()) {- log.info(msg() + " No additional versions requested. ourLowThreshold=" + ourLowThreshold + " otherHigh="- + otherHigh + " ourHighest=" + ourHighest + " otherHighest=" + otherHighest);-- // we had (or already requested) all the updates referenced by the replica-- // If we requested updates from another replica, we can't compare fingerprints yet with this replica, we need to- // defer- if (doFingerprint) {- sreq.doFingerprintComparison = true;- }-- return true;- }-- if (totalRequestedVersions > maxUpdates) {- log.info(msg() + " Failing due to needing too many updates:" + maxUpdates);- return false;- }-- String rangesToRequestStr = rangesToRequest.stream().collect(Collectors.joining(","));- return requestUpdates(srsp, rangesToRequestStr, totalRequestedVersions);- }--private boolean handleVersions(ShardResponse srsp) {// we retrieved the last N updates from the replicaList<Long> otherVersions = (List<Long>)srsp.getSolrResponse().getResponse().get("versions");// TODO: how to handle short lists?SyncShardRequest sreq = (SyncShardRequest) srsp.getShardRequest();- sreq.reportedVersions = otherVersions;-Object fingerprint = srsp.getSolrResponse().getResponse().get("fingerprint");log.info(msg() + " Received " + otherVersions.size() + " versions from " + sreq.shards[0] + " fingerprint:" + fingerprint );@@ -628,90 +432,28 @@ public class PeerSync implements SolrMetricProducer {}if (otherVersions.size() == 0) {- return getNoVersionsIsSuccess;- }-- boolean completeList = otherVersions.size() < nUpdates; // do we have their complete list of updates?-- Collections.sort(otherVersions, absComparator);-- if (debug) {- log.debug(msg() + " sorted versions from " + sreq.shards[0] + " = " + otherVersions);- }-- long otherHigh = percentile(otherVersions, .2f);- long otherLow = percentile(otherVersions, .8f);- long otherHighest = otherVersions.get(0);-- if (ourHighThreshold < otherLow) {- // Small overlap between version windows and ours is older- // This means that we might miss updates if we attempted to use this method.- // Since there exists just one replica that is so much newer, we must- // fail the sync.- log.info(msg() + " Our versions are too old. ourHighThreshold="+ourHighThreshold + " otherLowThreshold="+otherLow + " ourHighest=" + ourHighest + " otherHighest=" + otherHighest);- return false;- }-- if (ourLowThreshold > otherHigh) {- // Small overlap between windows and ours is newer.- // Using this list to sync would result in requesting/replaying results we don't need- // and possibly bringing deleted docs back to life.- log.info(msg() + " Our versions are newer. ourLowThreshold="+ourLowThreshold + " otherHigh="+otherHigh+ " ourHighest=" + ourHighest + " otherHighest=" + otherHighest);-- // Because our versions are newer, IndexFingerprint with the remote would not match us.- // We return true on our side, but the remote peersync with us should fail.+ // when sync with other replicas, they may not contains any updatesreturn true;}- if(core.getSolrConfig().useRangeVersionsForPeerSync && canHandleVersionRanges(sreq.shards[0])) {- return handleVersionsWithRanges(srsp, otherVersions, sreq, completeList, otherHigh, otherHighest);- } else {- return handleIndividualVersions(srsp, otherVersions, sreq, completeList, otherHigh, otherHighest);- }- }-- private boolean handleIndividualVersions(ShardResponse srsp, List<Long> otherVersions, SyncShardRequest sreq,- boolean completeList, long otherHigh, long otherHighest) {- List<Long> toRequest = new ArrayList<>();- for (Long otherVersion : otherVersions) {- // stop when the entries get old enough that reorders may lead us to see updates we don't need- if (!completeList && Math.abs(otherVersion) < ourLowThreshold) break;-- if (ourUpdateSet.contains(otherVersion) || requestedUpdateSet.contains(otherVersion)) {- // we either have this update, or already requested it- // TODO: what if the shard we previously requested this from returns failure (because it goes- // down)- continue;- }-- toRequest.add(otherVersion);- requestedUpdateSet.add(otherVersion);- }-- // TODO, do we really need to hold on to all the version numbers we requested.- // keeping track of totalRequestedUpdates should suffice for verification- sreq.requestedUpdates = toRequest;- sreq.totalRequestedUpdates = toRequest.size();-- if (toRequest.isEmpty()) {- log.info(msg() + " No additional versions requested. ourLowThreshold="+ourLowThreshold + " otherHigh="+otherHigh+ " ourHighest=" + ourHighest + " otherHighest=" + otherHighest);-- // we had (or already requested) all the updates referenced by the replica+ MissedUpdatesRequest updatesRequest = missedUpdatesFinder.find(+ otherVersions, sreq.shards[0],+ () -> core.getSolrConfig().useRangeVersionsForPeerSync && canHandleVersionRanges(sreq.shards[0]));+ if (updatesRequest == MissedUpdatesRequest.ALREADY_IN_SYNC) {+ return true;+ } else if (updatesRequest == MissedUpdatesRequest.UNABLE_TO_SYNC) {+ return false;+ } else if (updatesRequest == MissedUpdatesRequest.EMPTY) {// If we requested updates from another replica, we can't compare fingerprints yet with this replica, we need to deferif (doFingerprint) {sreq.doFingerprintComparison = true;}-return true;}-- if (toRequest.size() > maxUpdates) {- log.info(msg() + " Failing due to needing too many updates:" + maxUpdates);- return false;- }- return requestUpdates(srsp, StrUtils.join(toRequest, ','), toRequest.size());+ sreq.totalRequestedUpdates = updatesRequest.totalRequestedUpdates;+ return requestUpdates(srsp, updatesRequest.versionsAndRanges, updatesRequest.totalRequestedUpdates);}private boolean compareFingerprint(SyncShardRequest sreq) {@@ -746,11 +488,7 @@ public class PeerSync implements SolrMetricProducer {sreq.params.set(DISTRIB, false);sreq.params.set("getUpdates", versionsAndRanges);sreq.params.set("onlyIfActive", onlyIfActive);-- // fingerprint should really be requested only for the maxversion we are requesting updates for- // In case updates are coming in while node is coming up after restart, node would have already- // buffered some of the updates. fingerprint we requested with versions would reflect versions- // in our buffer as well and will definitely cause a mismatch+sreq.params.set("fingerprint",doFingerprint);sreq.responses.clear(); // needs to be zeroed for correct correlation to occur@@ -777,146 +515,364 @@ public class PeerSync implements SolrMetricProducer {sreq.fingerprint = IndexFingerprint.fromObject(fingerprint);}+ try {+ this.updater.applyUpdates(updates, sreq.shards);+ } catch (Exception e) {+ sreq.updateException = e;+ return false;+ }++ return compareFingerprint(sreq);+ }- ModifiableSolrParams params = new ModifiableSolrParams();- params.set(DISTRIB_UPDATE_PARAM, FROMLEADER.toString());- params.set("peersync",true); // debugging- SolrQueryRequest req = new LocalSolrQueryRequest(uhandler.core, params);- SolrQueryResponse rsp = new SolrQueryResponse();+ public static class PeerSyncResult {+ private final boolean success;+ private final Boolean otherHasVersions;- UpdateRequestProcessorChain processorChain = req.getCore().getUpdateProcessingChain(null);- UpdateRequestProcessor proc = processorChain.createProcessor(req, rsp);+ PeerSyncResult(boolean success, Boolean otherHasVersions) {+ this.success = success;+ this.otherHasVersions = otherHasVersions;+ }- Collections.sort(updates, updateRecordComparator);+ public boolean isSuccess() {+ return success;+ }- Object o = null;- long lastVersion = 0;- try {- // Apply oldest updates first- for (Object obj : updates) {- // should currently be a List<Oper,Ver,Doc/Id>- o = obj;- List<Object> entry = (List<Object>)o;-- if (debug) {- log.debug(msg() + "raw update record " + o);- }+ public Optional<Boolean> getOtherHasVersions() {+ return Optional.ofNullable(otherHasVersions);+ }- int oper = (Integer)entry.get(0) & UpdateLog.OPERATION_MASK;- long version = (Long) entry.get(1);- if (version == lastVersion && version != 0) continue;- lastVersion = version;-- switch (oper) {- case UpdateLog.ADD:- {- // byte[] idBytes = (byte[]) entry.get(2);- SolrInputDocument sdoc = (SolrInputDocument)entry.get(entry.size()-1);- AddUpdateCommand cmd = new AddUpdateCommand(req);- // cmd.setIndexedId(new BytesRef(idBytes));- cmd.solrDoc = sdoc;- cmd.setVersion(version);- cmd.setFlags(UpdateCommand.PEER_SYNC | UpdateCommand.IGNORE_AUTOCOMMIT);- if (debug) {- log.debug(msg() + "add " + cmd + " id " + sdoc.getField(ID));- }- proc.processAdd(cmd);- break;+ public static PeerSyncResult success() {+ return new PeerSyncResult(true, null);+ }++ public static PeerSyncResult failure() {+ return new PeerSyncResult(false, null);+ }++ public static PeerSyncResult failure(boolean otherHasVersions) {+ return new PeerSyncResult(false, otherHasVersions);+ }+ }++ /**+ * Helper class for apply missed updates+ */+ static class Updater {+ // comparator that sorts update records by absolute value of version, putting lowest first+ private static final Comparator<Object> updateRecordComparator = (o1, o2) -> {+ if (!(o1 instanceof List)) return 1;+ if (!(o2 instanceof List)) return -1;++ List lst1 = (List) o1;+ List lst2 = (List) o2;++ long l1 = Math.abs((Long) lst1.get(1));+ long l2 = Math.abs((Long) lst2.get(1));++ return Long.compare(l1, l2);+ };++ private String logPrefix;+ private SolrCore solrCore;++ Updater(String logPrefix, SolrCore solrCore) {+ this.logPrefix = logPrefix;+ this.solrCore = solrCore;+ }++ void applyUpdates(List<Object> updates, Object updateFrom) throws Exception {+ ModifiableSolrParams params = new ModifiableSolrParams();+ params.set(DISTRIB_UPDATE_PARAM, FROMLEADER.toString());+ params.set("peersync",true); // debugging+ SolrQueryRequest req = new LocalSolrQueryRequest(solrCore, params);+ SolrQueryResponse rsp = new SolrQueryResponse();++ UpdateRequestProcessorChain processorChain = req.getCore().getUpdateProcessingChain(null);+ UpdateRequestProcessor proc = processorChain.createProcessor(req, rsp);++ updates.sort(updateRecordComparator);++ Object o = null;+ long lastVersion = 0;+ try {+ // Apply oldest updates first+ for (Object obj : updates) {+ // should currently be a List<Oper,Ver,Doc/Id>+ o = obj;+ List<Object> entry = (List<Object>)o;++ if (debug) {+ log.debug(logPrefix + "raw update record " + o);}- case UpdateLog.DELETE:- {- byte[] idBytes = (byte[]) entry.get(2);- DeleteUpdateCommand cmd = new DeleteUpdateCommand(req);- cmd.setIndexedId(new BytesRef(idBytes));- cmd.setVersion(version);- cmd.setFlags(UpdateCommand.PEER_SYNC | UpdateCommand.IGNORE_AUTOCOMMIT);- if (debug) {- log.debug(msg() + "delete " + cmd + " " + new BytesRef(idBytes).utf8ToString());++ int oper = (Integer)entry.get(0) & UpdateLog.OPERATION_MASK;+ long version = (Long) entry.get(1);+ if (version == lastVersion && version != 0) continue;+ lastVersion = version;++ switch (oper) {+ case UpdateLog.ADD:+ {+ // byte[] idBytes = (byte[]) entry.get(2);+ SolrInputDocument sdoc = (SolrInputDocument)entry.get(entry.size()-1);+ AddUpdateCommand cmd = new AddUpdateCommand(req);+ // cmd.setIndexedId(new BytesRef(idBytes));+ cmd.solrDoc = sdoc;+ cmd.setVersion(version);+ cmd.setFlags(UpdateCommand.PEER_SYNC | UpdateCommand.IGNORE_AUTOCOMMIT);+ if (debug) {+ log.debug(logPrefix + "add " + cmd + " id " + sdoc.getField(ID));+ }+ proc.processAdd(cmd);+ break;+ }+ case UpdateLog.DELETE:+ {+ byte[] idBytes = (byte[]) entry.get(2);+ DeleteUpdateCommand cmd = new DeleteUpdateCommand(req);+ cmd.setIndexedId(new BytesRef(idBytes));+ cmd.setVersion(version);+ cmd.setFlags(UpdateCommand.PEER_SYNC | UpdateCommand.IGNORE_AUTOCOMMIT);+ if (debug) {+ log.debug(logPrefix + "delete " + cmd + " " + new BytesRef(idBytes).utf8ToString());+ }+ proc.processDelete(cmd);+ break;}- proc.processDelete(cmd);- break;- }- case UpdateLog.DELETE_BY_QUERY:- {- String query = (String)entry.get(2);- DeleteUpdateCommand cmd = new DeleteUpdateCommand(req);- cmd.query = query;- cmd.setVersion(version);- cmd.setFlags(UpdateCommand.PEER_SYNC | UpdateCommand.IGNORE_AUTOCOMMIT);- if (debug) {- log.debug(msg() + "deleteByQuery " + cmd);+ case UpdateLog.DELETE_BY_QUERY:+ {+ String query = (String)entry.get(2);+ DeleteUpdateCommand cmd = new DeleteUpdateCommand(req);+ cmd.query = query;+ cmd.setVersion(version);+ cmd.setFlags(UpdateCommand.PEER_SYNC | UpdateCommand.IGNORE_AUTOCOMMIT);+ if (debug) {+ log.debug(logPrefix + "deleteByQuery " + cmd);+ }+ proc.processDelete(cmd);+ break;}- proc.processDelete(cmd);- break;- }- case UpdateLog.UPDATE_INPLACE:- {- AddUpdateCommand cmd = UpdateLog.convertTlogEntryToAddUpdateCommand(req, entry, oper, version);- cmd.setFlags(UpdateCommand.PEER_SYNC | UpdateCommand.IGNORE_AUTOCOMMIT);- if (debug) {- log.debug(msg() + "inplace update " + cmd + " prevVersion=" + cmd.prevVersion + ", doc=" + cmd.solrDoc);+ case UpdateLog.UPDATE_INPLACE:+ {+ AddUpdateCommand cmd = UpdateLog.convertTlogEntryToAddUpdateCommand(req, entry, oper, version);+ cmd.setFlags(UpdateCommand.PEER_SYNC | UpdateCommand.IGNORE_AUTOCOMMIT);+ if (debug) {+ log.debug(logPrefix + "inplace update " + cmd + " prevVersion=" + cmd.prevVersion + ", doc=" + cmd.solrDoc);+ }+ proc.processAdd(cmd);+ break;}- proc.processAdd(cmd);- break;++ default:+ throw new SolrException(SolrException.ErrorCode.SERVER_ERROR, "Unknown Operation! " + oper);}- default:- throw new SolrException(SolrException.ErrorCode.SERVER_ERROR, "Unknown Operation! " + oper);}+ } catch (IOException e) {+ // TODO: should this be handled separately as a problem with us?+ // I guess it probably already will by causing replication to be kicked off.+ log.error(logPrefix + "Error applying updates from " + updateFrom + " ,update=" + o, e);+ throw e;+ } catch (Exception e) {+ log.error(logPrefix + "Error applying updates from " + updateFrom + " ,update=" + o, e);+ throw e;+ } finally {+ try {+ proc.finish();+ } catch (Exception e) {+ log.error(logPrefix + "Error applying updates from " + updateFrom + " ,finish()", e);+ throw e;+ } finally {+ IOUtils.closeQuietly(proc);+ }}+ }+ }+ /**+ * Helper class for doing comparison ourUpdates and other replicas's updates to find the updates that we missed+ */+ public static class MissedUpdatesFinder {+ private List<Long> ourUpdates;+ private Set<Long> ourUpdateSet;+ private Set<Long> requestedUpdateSet;++ private long ourLowThreshold; // 20th percentile+ private long ourHighThreshold; // 80th percentile+ private long ourHighest; // currently just used for logging/debugging purposes+ private String logPrefix;+ private long nUpdates;++ MissedUpdatesFinder(List<Long> ourUpdates, String logPrefix, long nUpdates,+ long ourLowThreshold, long ourHighThreshold) {+ assert sorted(ourUpdates);++ this.logPrefix = logPrefix;+ this.ourUpdates = ourUpdates;+ this.ourLowThreshold = ourLowThreshold;+ this.ourHighThreshold = ourHighThreshold;+ this.ourHighest = ourUpdates.get(0);+ this.nUpdates = nUpdates;++ this.ourUpdateSet = new HashSet<>(ourUpdates);+ this.requestedUpdateSet = new HashSet<>();+ }++ private boolean sorted(List<Long> list) {+ long prev = Long.MAX_VALUE;+ for (long a : list) {+ if (Math.abs(a) > prev) return false;+ prev = Math.abs(a);+ }+ return true;}- catch (IOException e) {- // TODO: should this be handled separately as a problem with us?- // I guess it probably already will by causing replication to be kicked off.- sreq.updateException = e;- log.error(msg() + "Error applying updates from " + sreq.shards + " ,update=" + o, e);- return false;++ public MissedUpdatesRequest find(List<Long> otherVersions, Object updateFrom, Supplier<Boolean> canHandleVersionRanges) {+ otherVersions.sort(absComparator);+ if (debug) {+ log.debug("{} sorted versions from {} = {}", logPrefix, otherVersions, updateFrom);+ }++ long otherHigh = percentile(otherVersions, .2f);+ long otherLow = percentile(otherVersions, .8f);+ long otherHighest = otherVersions.get(0);++ if (ourHighThreshold < otherLow) {+ // Small overlap between version windows and ours is older+ // This means that we might miss updates if we attempted to use this method.+ // Since there exists just one replica that is so much newer, we must+ // fail the sync.+ log.info("{} Our versions are too old. ourHighThreshold={} otherLowThreshold={} ourHighest={} otherHighest={}",+ logPrefix, ourHighThreshold, otherLow, ourHighest, otherHighest);+ return MissedUpdatesRequest.UNABLE_TO_SYNC;+ }++ if (ourLowThreshold > otherHigh) {+ // Small overlap between windows and ours is newer.+ // Using this list to sync would result in requesting/replaying results we don't need+ // and possibly bringing deleted docs back to life.+ log.info("{} Our versions are newer. ourHighThreshold={} otherLowThreshold={} ourHighest={} otherHighest={}",+ logPrefix, ourHighThreshold, otherLow, ourHighest, otherHighest);++ // Because our versions are newer, IndexFingerprint with the remote would not match us.+ // We return true on our side, but the remote peersync with us should fail.+ return MissedUpdatesRequest.ALREADY_IN_SYNC;+ }++ boolean completeList = otherVersions.size() < nUpdates;++ MissedUpdatesRequest updatesRequest;+ if (canHandleVersionRanges.get()) {+ updatesRequest = handleVersionsWithRanges(otherVersions, completeList);+ } else {+ updatesRequest = handleIndividualVersions(otherVersions, completeList);+ }++ if (updatesRequest.totalRequestedUpdates > nUpdates) {+ log.info("{} Failing due to needing too many updates:{}", logPrefix, nUpdates);+ return MissedUpdatesRequest.UNABLE_TO_SYNC;+ }++ if (updatesRequest == MissedUpdatesRequest.EMPTY) {+ log.info("{} No additional versions requested. ourHighThreshold={} otherLowThreshold={} ourHighest={} otherHighest={}",+ logPrefix, ourHighThreshold, otherLow, ourHighest, otherHighest);+ }++ return updatesRequest;}- catch (Exception e) {- sreq.updateException = e;- log.error(msg() + "Error applying updates from " + sreq.shards + " ,update=" + o, e);- return false;++ private MissedUpdatesRequest handleVersionsWithRanges(List<Long> otherVersions, boolean completeList) {+ // we may endup asking for updates for too many versions, causing 2MB post payload limit. Construct a range of+ // versions to request instead of asking individual versions+ List<String> rangesToRequest = new ArrayList<>();++ // construct ranges to request+ // both ourUpdates and otherVersions are sorted with highest range first+ // may be we can create another reverse the lists and avoid confusion+ int ourUpdatesIndex = ourUpdates.size() - 1;+ int otherUpdatesIndex = otherVersions.size() - 1;+ long totalRequestedVersions = 0;++ while (otherUpdatesIndex >= 0) {+ // we have run out of ourUpdates, pick up all the remaining versions from the other versions+ if (ourUpdatesIndex < 0) {+ String range = otherVersions.get(otherUpdatesIndex) + "..." + otherVersions.get(0);+ rangesToRequest.add(range);+ totalRequestedVersions += otherUpdatesIndex + 1;+ break;+ }++ // stop when the entries get old enough that reorders may lead us to see updates we don't need+ if (!completeList && Math.abs(otherVersions.get(otherUpdatesIndex)) < ourLowThreshold) break;++ if (ourUpdates.get(ourUpdatesIndex).longValue() == otherVersions.get(otherUpdatesIndex).longValue()) {+ ourUpdatesIndex--;+ otherUpdatesIndex--;+ } else if (Math.abs(ourUpdates.get(ourUpdatesIndex)) < Math.abs(otherVersions.get(otherUpdatesIndex))) {+ ourUpdatesIndex--;+ } else {+ long rangeStart = otherVersions.get(otherUpdatesIndex);+ while ((otherUpdatesIndex < otherVersions.size())+ && (Math.abs(otherVersions.get(otherUpdatesIndex)) < Math.abs(ourUpdates.get(ourUpdatesIndex)))) {+ otherUpdatesIndex--;+ totalRequestedVersions++;+ }+ // construct range here+ rangesToRequest.add(rangeStart + "..." + otherVersions.get(otherUpdatesIndex + 1));+ }+ }++ String rangesToRequestStr = rangesToRequest.stream().collect(Collectors.joining(","));+ return MissedUpdatesRequest.of(rangesToRequestStr, totalRequestedVersions);}- finally {- try {- proc.finish();- } catch (Exception e) {- sreq.updateException = e;- log.error(msg() + "Error applying updates from " + sreq.shards + " ,finish()", e);- return false;- } finally {- IOUtils.closeQuietly(proc);++ private MissedUpdatesRequest handleIndividualVersions(List<Long> otherVersions, boolean completeList) {+ List<Long> toRequest = new ArrayList<>();+ for (Long otherVersion : otherVersions) {+ // stop when the entries get old enough that reorders may lead us to see updates we don't need+ if (!completeList && Math.abs(otherVersion) < ourLowThreshold) break;++ if (ourUpdateSet.contains(otherVersion) || requestedUpdateSet.contains(otherVersion)) {+ // we either have this update, or already requested it+ // TODO: what if the shard we previously requested this from returns failure (because it goes+ // down)+ continue;+ }++ toRequest.add(otherVersion);+ requestedUpdateSet.add(otherVersion);}++ return MissedUpdatesRequest.of(StrUtils.join(toRequest, ','), toRequest.size());}- return compareFingerprint(sreq);}+ /**+ * Result of {@link MissedUpdatesFinder}+ */+ public static class MissedUpdatesRequest {+ static final MissedUpdatesRequest UNABLE_TO_SYNC = new MissedUpdatesRequest();+ static final MissedUpdatesRequest ALREADY_IN_SYNC = new MissedUpdatesRequest();+ public static final MissedUpdatesRequest EMPTY = new MissedUpdatesRequest();+ String versionsAndRanges;+ long totalRequestedUpdates;- /** Requests and applies recent updates from peers */- public static void sync(SolrCore core, List<String> replicas, int nUpdates) {- ShardHandlerFactory shardHandlerFactory = core.getCoreContainer().getShardHandlerFactory();+ private MissedUpdatesRequest(){}- ShardHandler shardHandler = shardHandlerFactory.getShardHandler();-- for (String replica : replicas) {- ShardRequest sreq = new ShardRequest();- sreq.shards = new String[]{replica};- sreq.params = new ModifiableSolrParams();- sreq.params.set("qt","/get");- sreq.params.set(DISTRIB, false);- sreq.params.set("getVersions",nUpdates);- shardHandler.submit(sreq, replica, sreq.params);- }-- for (String replica : replicas) {- ShardResponse srsp = shardHandler.takeCompletedOrError();+ public static MissedUpdatesRequest of(String versionsAndRanges, long totalRequestedUpdates) {+ if (totalRequestedUpdates == 0) return EMPTY;+ return new MissedUpdatesRequest(versionsAndRanges, totalRequestedUpdates);}+ MissedUpdatesRequest(String versionsAndRanges, long totalRequestedUpdates) {+ this.versionsAndRanges = versionsAndRanges;+ this.totalRequestedUpdates = totalRequestedUpdates;+ }}}diff --git a/solr/core/src/java/org/apache/solr/update/PeerSyncWithLeader.java b/solr/core/src/java/org/apache/solr/update/PeerSyncWithLeader.javanew file mode 100644index 00000000000..ce4bc77f58c--- /dev/null+++ b/solr/core/src/java/org/apache/solr/update/PeerSyncWithLeader.java@@ -0,0 +1,372 @@+/*+ * Licensed to the Apache Software Foundation (ASF) under one or more+ * contributor license agreements. See the NOTICE file distributed with+ * this work for additional information regarding copyright ownership.+ * The ASF licenses this file to You under the Apache License, Version 2.0+ * (the "License"); you may not use this file except in compliance with+ * the License. You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++package org.apache.solr.update;++import java.io.IOException;+import java.lang.invoke.MethodHandles;+import java.util.List;+import java.util.Set;++import com.codahale.metrics.Counter;+import com.codahale.metrics.Timer;+import org.apache.http.client.HttpClient;+import org.apache.solr.client.solrj.SolrRequest;+import org.apache.solr.client.solrj.SolrServerException;+import org.apache.solr.client.solrj.impl.HttpSolrClient;+import org.apache.solr.client.solrj.request.QueryRequest;+import org.apache.solr.client.solrj.response.QueryResponse;+import org.apache.solr.cloud.ZkController;+import org.apache.solr.common.SolrException;+import org.apache.solr.common.params.ModifiableSolrParams;+import org.apache.solr.common.util.NamedList;+import org.apache.solr.core.SolrCore;+import org.apache.solr.core.SolrInfoBean;+import org.apache.solr.logging.MDCLoggingContext;+import org.apache.solr.metrics.SolrMetricManager;+import org.apache.solr.metrics.SolrMetricProducer;+import org.slf4j.Logger;+import org.slf4j.LoggerFactory;++import static org.apache.solr.common.params.CommonParams.DISTRIB;+import static org.apache.solr.update.PeerSync.absComparator;+import static org.apache.solr.update.PeerSync.percentile;+import static org.apache.solr.update.PeerSync.MissedUpdatesRequest;++public class PeerSyncWithLeader implements SolrMetricProducer {+ private static final Logger log = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());+ private boolean debug = log.isDebugEnabled();++ private String leaderUrl;+ private int nUpdates;++ private UpdateHandler uhandler;+ private UpdateLog ulog;+ private HttpSolrClient clientToLeader;++ private boolean doFingerprint;++ private SolrCore core;+ private PeerSync.Updater updater;+ private PeerSync.MissedUpdatesFinder missedUpdatesFinder;+ private Set<Long> bufferedUpdates;++ // metrics+ private Timer syncTime;+ private Counter syncErrors;+ private Counter syncSkipped;++ public PeerSyncWithLeader(SolrCore core, String leaderUrl, int nUpdates) {+ this.core = core;+ this.leaderUrl = leaderUrl;+ this.nUpdates = nUpdates;++ this.doFingerprint = !"true".equals(System.getProperty("solr.disableFingerprint"));+ this.uhandler = core.getUpdateHandler();+ this.ulog = uhandler.getUpdateLog();+ HttpClient httpClient = core.getCoreContainer().getUpdateShardHandler().getDefaultHttpClient();+ this.clientToLeader = new HttpSolrClient.Builder(leaderUrl).withHttpClient(httpClient).build();++ this.updater = new PeerSync.Updater(msg(), core);++ core.getCoreMetricManager().registerMetricProducer(SolrInfoBean.Category.REPLICATION.toString(), this);+ }++ public static final String METRIC_SCOPE = "peerSync";++ @Override+ public void initializeMetrics(SolrMetricManager manager, String registry, String tag, String scope) {+ syncTime = manager.timer(null, registry, "time", scope, METRIC_SCOPE);+ syncErrors = manager.counter(null, registry, "errors", scope, METRIC_SCOPE);+ syncSkipped = manager.counter(null, registry, "skipped", scope, METRIC_SCOPE);+ }++ // start of peersync related debug messages. includes the core name for correlation.+ private String msg() {+ ZkController zkController = uhandler.core.getCoreContainer().getZkController();+ String myURL = "";+ if (zkController != null) {+ myURL = zkController.getBaseUrl();+ }++ return "PeerSync: core="+uhandler.core.getName()+ " url="+myURL +" ";+ }++ /**+ * Sync with leader+ * @param startingVersions : recent versions on startup+ * @return result of PeerSync with leader+ */+ public PeerSync.PeerSyncResult sync(List<Long> startingVersions){+ if (ulog == null) {+ syncErrors.inc();+ return PeerSync.PeerSyncResult.failure();+ }++ if (startingVersions.isEmpty()) {+ log.warn("no frame of reference to tell if we've missed updates");+ syncErrors.inc();+ return PeerSync.PeerSyncResult.failure();+ }++ MDCLoggingContext.setCore(core);+ Timer.Context timerContext = null;+ try {+ log.info(msg() + "START leader=" + leaderUrl + " nUpdates=" + nUpdates);++ if (debug) {+ log.debug(msg() + "startingVersions=" + startingVersions.size() + " " + startingVersions);+ }+ // check if we already in sync to begin with+ if(doFingerprint && alreadyInSync()) {+ syncSkipped.inc();+ return PeerSync.PeerSyncResult.success();+ }++ // measure only when actual sync is performed+ timerContext = syncTime.time();++ List<Long> ourUpdates;+ try (UpdateLog.RecentUpdates recentUpdates = ulog.getRecentUpdates()) {+ ourUpdates = recentUpdates.getVersions(nUpdates);+ bufferedUpdates = recentUpdates.getBufferUpdates();+ }++ ourUpdates.sort(absComparator);+ startingVersions.sort(absComparator);++ long ourLowThreshold = percentile(startingVersions, 0.8f);+ long 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");+ syncErrors.inc();+ return PeerSync.PeerSyncResult.failure();+ }++ // let's merge the lists+ for (Long ver : startingVersions) {+ if (Math.abs(ver) < smallestNewUpdate) {+ ourUpdates.add(ver);+ }+ }++ boolean success = doSync(ourUpdates, ourLowThreshold, ourHighThreshold);++ log.info(msg() + "DONE. sync " + (success ? "succeeded" : "failed"));+ if (!success) {+ syncErrors.inc();+ }+ return success ? PeerSync.PeerSyncResult.success() : PeerSync.PeerSyncResult.failure();+ } finally {+ if (timerContext != null) {+ timerContext.close();+ }+ try {+ clientToLeader.close();+ } catch (IOException e) {+ log.warn("{} unable to close client to leader", msg(), e);+ }+ MDCLoggingContext.clear();+ }+ }++ private boolean doSync(List<Long> ourUpdates, long ourLowThreshold, long ourHighThreshold) {+ // get leader's recent versions and fingerprint+ // note: by getting leader's versions later, we guarantee that leader's versions always super set of {@link bufferedUpdates}+ NamedList<Object> leaderVersionsAndFingerprint = getVersions();+ IndexFingerprint leaderFingerprint = getFingerprint(leaderVersionsAndFingerprint);+ if (doFingerprint) {+ if (leaderFingerprint == null) {+ log.warn("Could not get fingerprint from the leader");+ return false;+ }+ log.info("Leader fingerprint {}", leaderFingerprint);+ }++ missedUpdatesFinder = new PeerSync.MissedUpdatesFinder(ourUpdates, msg(), nUpdates, ourLowThreshold, ourHighThreshold);+ MissedUpdatesRequest missedUpdates = buildMissedUpdatesRequest(leaderVersionsAndFingerprint);+ if (missedUpdates == MissedUpdatesRequest.ALREADY_IN_SYNC) return true;+ if (missedUpdates != MissedUpdatesRequest.UNABLE_TO_SYNC) {+ NamedList<Object> missedUpdatesRsp = requestUpdates(missedUpdates);+ if (handleUpdates(missedUpdatesRsp, missedUpdates.totalRequestedUpdates, leaderFingerprint)) {+ if (doFingerprint) {+ return compareFingerprint(leaderFingerprint);+ }+ return true;+ }+ }+ return false;+ }++ private MissedUpdatesRequest buildMissedUpdatesRequest(NamedList<Object> rsp) {+ // we retrieved the last N updates from the replica+ List<Long> otherVersions = (List<Long>)rsp.get("versions");+ log.info(msg() + " Received " + otherVersions.size() + " versions from " + leaderUrl);++ if (otherVersions.isEmpty()) {+ return MissedUpdatesRequest.UNABLE_TO_SYNC;+ }++ MissedUpdatesRequest updatesRequest = missedUpdatesFinder.find(otherVersions, leaderUrl, () -> core.getSolrConfig().useRangeVersionsForPeerSync && canHandleVersionRanges());+ if (updatesRequest == MissedUpdatesRequest.EMPTY) {+ if (doFingerprint) return MissedUpdatesRequest.UNABLE_TO_SYNC;+ return MissedUpdatesRequest.ALREADY_IN_SYNC;+ }++ return updatesRequest;+ }++ private NamedList<Object> requestUpdates(MissedUpdatesRequest missedUpdatesRequest) {+ log.info(msg() + "Requesting updates from " + leaderUrl + " n=" + missedUpdatesRequest.totalRequestedUpdates + " versions=" + missedUpdatesRequest.versionsAndRanges);++ ModifiableSolrParams params = new ModifiableSolrParams();+ params.set("qt", "/get");+ params.set(DISTRIB, false);+ params.set("getUpdates", missedUpdatesRequest.versionsAndRanges);+ params.set("onlyIfActive", false);+ params.set("skipDbq", true);++ return request(params, "Failed on getting missed updates from the leader");+ }++ private boolean handleUpdates(NamedList<Object> rsp, long numRequestedUpdates, IndexFingerprint leaderFingerprint) {+ // missed updates from leader, it does not contains updates from bufferedUpdates+ List<Object> updates = (List<Object>)rsp.get("updates");++ if (updates.size() < numRequestedUpdates) {+ log.error(msg() + " Requested " + numRequestedUpdates + " updates from " + leaderUrl + " but retrieved " + updates.size());+ return false;+ }++ // by apply buffering update, replica will have fingerprint equals to leader.+ try (UpdateLog.RecentUpdates recentUpdates = ulog.getRecentUpdates()) {+ for (Long bufferUpdate : bufferedUpdates) {+ // updater will sort updates before apply+ updates.add(recentUpdates.lookup(bufferUpdate));+ }+ }++ // Leader will compute its fingerprint, then retrieve its recent updates versions.+ // There are a case that some updates (gap) get into recent versions but do not exist in index (fingerprint).+ // If the gap do not contains DBQ or DBI, it is safe to use leaderFingerprint.maxVersionEncountered as a cut point.+ // TODO leader should do fingerprint and retrieve recent updates version in atomic+ if (leaderFingerprint != null) {+ boolean existDBIOrDBQInTheGap = updates.stream().anyMatch(e -> {+ List<Object> u = (List<Object>) e;+ long version = (Long) u.get(1);+ int oper = (Integer)u.get(0) & UpdateLog.OPERATION_MASK;+ // only DBI or DBQ in the gap (above) will satisfy this predicate+ return version > leaderFingerprint.getMaxVersionEncountered() && (oper == UpdateLog.DELETE || oper == UpdateLog.DELETE_BY_QUERY);+ });+ if (!existDBIOrDBQInTheGap) {+ // it is safe to use leaderFingerprint.maxVersionEncountered as cut point now.+ updates.removeIf(e -> {+ List<Object> u = (List<Object>) e;+ long version = (Long) u.get(1);+ return version > leaderFingerprint.getMaxVersionEncountered();+ });+ }+ }++ try {+ updater.applyUpdates(updates, leaderUrl);+ } catch (Exception e) {+ return false;+ }+ return true;+ }++ // determine if leader can handle version ranges+ private boolean canHandleVersionRanges() {+ ModifiableSolrParams params = new ModifiableSolrParams();+ params.set("qt", "/get");+ params.set(DISTRIB, false);+ params.set("checkCanHandleVersionRanges", false);++ NamedList<Object> rsp = request(params, "Failed on determine if leader can handle version ranges");+ Boolean canHandleVersionRanges = rsp.getBooleanArg("canHandleVersionRanges");++ return canHandleVersionRanges != null && canHandleVersionRanges;+ }++ private NamedList<Object> request(ModifiableSolrParams params, String onFail) {+ try {+ QueryResponse rsp = new QueryRequest(params, SolrRequest.METHOD.POST).process(clientToLeader);+ Exception exception = rsp.getException();+ if (exception != null) {+ throw new SolrException(SolrException.ErrorCode.SERVER_ERROR, onFail);+ }+ return rsp.getResponse();+ } catch (SolrServerException | IOException e) {+ throw new SolrException(SolrException.ErrorCode.SERVER_ERROR, onFail);+ }+ }++ private NamedList<Object> getVersions() {+ ModifiableSolrParams params = new ModifiableSolrParams();+ params.set("qt","/get");+ params.set(DISTRIB,false);+ params.set("getVersions",nUpdates);+ params.set("fingerprint",doFingerprint);++ return request(params, "Failed to get recent versions from leader");+ }++ private boolean alreadyInSync() {+ ModifiableSolrParams params = new ModifiableSolrParams();+ params.set("qt", "/get");+ params.set(DISTRIB,false);+ params.set("getFingerprint", String.valueOf(Long.MAX_VALUE));++ NamedList<Object> rsp = request(params, "Failed to get fingerprint from leader");+ IndexFingerprint leaderFingerprint = getFingerprint(rsp);+ return compareFingerprint(leaderFingerprint);+ }++ private IndexFingerprint getFingerprint(NamedList<Object> rsp) {+ Object fingerprint = null;+ if (rsp != null) fingerprint = rsp.get("fingerprint");+ if (fingerprint == null) return null;+ return IndexFingerprint.fromObject(fingerprint);+ }++ private boolean compareFingerprint(IndexFingerprint leaderFingerprint) {+ if (leaderFingerprint == null) {+ log.warn("Replica did not return a fingerprint - possibly an older Solr version or exception");+ return false;+ }++ try {+ IndexFingerprint ourFingerprint = IndexFingerprint.getFingerprint(core, Long.MAX_VALUE);+ int cmp = IndexFingerprint.compare(leaderFingerprint, ourFingerprint);+ log.info("Fingerprint comparison: {}" , cmp);+ if(cmp != 0) {+ log.info("Other fingerprint: {}, Our fingerprint: {}", leaderFingerprint , ourFingerprint);+ }+ return cmp == 0; // currently, we only check for equality...+ } catch (IOException e) {+ log.warn("Could not confirm if we are already in sync. Continue with PeerSync");+ }+ return false;+ }+}diff --git a/solr/core/src/java/org/apache/solr/update/TransactionLog.java b/solr/core/src/java/org/apache/solr/update/TransactionLog.javaindex 2a23896d491..9bb08788b9c 100644--- a/solr/core/src/java/org/apache/solr/update/TransactionLog.java+++ b/solr/core/src/java/org/apache/solr/update/TransactionLog.java@@ -78,6 +78,7 @@ public class TransactionLog implements Closeable {OutputStream os;FastOutputStream fos; // all accesses to this stream should be synchronized on "this" (The TransactionLog)int numRecords;+ boolean isBuffer;protected volatile boolean deleteOnClose = true; // we can delete old tlogs since they are currently only used for real-time-get (and in the future, recovery)diff --git a/solr/core/src/java/org/apache/solr/update/UpdateLog.java b/solr/core/src/java/org/apache/solr/update/UpdateLog.javaindex 1bda23fc038..46d84353440 100644--- a/solr/core/src/java/org/apache/solr/update/UpdateLog.java+++ b/solr/core/src/java/org/apache/solr/update/UpdateLog.java@@ -30,6 +30,7 @@ import java.util.Collection;import java.util.Collections;import java.util.Deque;import java.util.HashMap;+import java.util.HashSet;import java.util.LinkedHashMap;import java.util.LinkedList;import java.util.List;@@ -1302,6 +1303,7 @@ public class UpdateLog implements PluginInfoInitialized, SolrMetricProducer {if (bufferTlog != null) return;String newLogName = String.format(Locale.ROOT, LOG_FILENAME_PATTERN, BUFFER_TLOG_NAME, System.nanoTime());bufferTlog = newTransactionLog(new File(tlogDir, newLogName), globalStrings, false);+ bufferTlog.isBuffer = true;}// Cleanup old buffer tlogs@@ -1398,6 +1400,7 @@ public class UpdateLog implements PluginInfoInitialized, SolrMetricProducer {HashMap<Long, Update> updates;List<Update> deleteByQueryList;List<DeleteUpdate> deleteList;+ Set<Long> bufferUpdates = new HashSet<>();public RecentUpdates(Deque<TransactionLog> logList) {this.logList = logList;@@ -1418,6 +1421,10 @@ public class UpdateLog implements PluginInfoInitialized, SolrMetricProducer {return getVersions(n, Long.MAX_VALUE);}+ public Set<Long> getBufferUpdates() {+ return Collections.unmodifiableSet(bufferUpdates);+ }+public List<Long> getVersions(int n, long maxVersion) {List<Long> ret = new ArrayList<>(n);@@ -1479,6 +1486,8 @@ public class UpdateLog implements PluginInfoInitialized, SolrMetricProducer {int oper = opAndFlags & UpdateLog.OPERATION_MASK;long version = (Long) entry.get(UpdateLog.VERSION_IDX);+ if (oldLog.isBuffer) bufferUpdates.add(version);+switch (oper) {case UpdateLog.ADD:case UpdateLog.UPDATE_INPLACE:diff --git a/solr/core/src/test/org/apache/solr/update/PeerSyncWithBufferUpdatesTest.java b/solr/core/src/test/org/apache/solr/update/PeerSyncWithBufferUpdatesTest.javanew file mode 100644index 00000000000..eff120d3a53--- /dev/null+++ b/solr/core/src/test/org/apache/solr/update/PeerSyncWithBufferUpdatesTest.java@@ -0,0 +1,223 @@+/*+ * Licensed to the Apache Software Foundation (ASF) under one or more+ * contributor license agreements. See the NOTICE file distributed with+ * this work for additional information regarding copyright ownership.+ * The ASF licenses this file to You under the Apache License, Version 2.0+ * (the "License"); you may not use this file except in compliance with+ * the License. You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++package org.apache.solr.update;++import java.io.IOException;+import java.lang.invoke.MethodHandles;+import java.util.ArrayList;+import java.util.HashSet;+import java.util.LinkedHashSet;+import java.util.List;+import java.util.Set;++import org.apache.solr.BaseDistributedSearchTestCase;+import org.apache.solr.SolrTestCaseJ4;+import org.apache.solr.client.solrj.SolrClient;+import org.apache.solr.client.solrj.SolrServerException;+import org.apache.solr.client.solrj.request.QueryRequest;+import org.apache.solr.client.solrj.response.QueryResponse;+import org.apache.solr.common.SolrInputDocument;+import org.apache.solr.common.params.ModifiableSolrParams;+import org.apache.solr.common.util.NamedList;+import org.apache.solr.core.SolrCore;+import org.apache.solr.update.processor.DistributedUpdateProcessor;+import org.junit.Test;+import org.slf4j.Logger;+import org.slf4j.LoggerFactory;++import static org.apache.solr.update.processor.DistributingUpdateProcessorFactory.DISTRIB_UPDATE_PARAM;+[email protected](bugUrl = "https://issues.apache.org/jira/browse/SOLR-5776")+public class PeerSyncWithBufferUpdatesTest extends BaseDistributedSearchTestCase {+ private static final Logger log = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());++ private static int numVersions = 100; // number of versions to use when syncing+ private final String FROM_LEADER = DistributedUpdateProcessor.DistribPhase.FROMLEADER.toString();++ private ModifiableSolrParams seenLeader =+ params(DISTRIB_UPDATE_PARAM, FROM_LEADER);++ public PeerSyncWithBufferUpdatesTest() {+ stress = 0;++ // TODO: a better way to do this?+ configString = "solrconfig-tlog.xml";+ schemaString = "schema.xml";+ }++ @Test+ @ShardsFixed(num = 3)+ public void test() throws Exception {+ Set<Integer> docsAdded = new LinkedHashSet<>();+ handle.clear();+ handle.put("timestamp", SKIPVAL);+ handle.put("score", SKIPVAL);+ handle.put("maxScore", SKIPVAL);++ SolrClient client0 = clients.get(0);+ SolrClient client1 = clients.get(1);+ SolrClient client2 = clients.get(2);++ long v = 0;+ // add some context+ for (int i = 1; i <= 10; i++) {+ add(client0, seenLeader, sdoc("id",String.valueOf(i),"_version_",++v));+ add(client1, seenLeader, sdoc("id",String.valueOf(i),"_version_",v));+ }++ // jetty1 was down+ for (int i = 11; i <= 15; i++) {+ add(client0, seenLeader, sdoc("id",String.valueOf(i),"_version_",++v));+ }++ // it restarted and must do PeerSync+ SolrCore jetty1Core = jettys.get(1).getCoreContainer().getCores().iterator().next();+ jetty1Core.getUpdateHandler().getUpdateLog().bufferUpdates();+ for (int i = 16; i <= 20; i++) {+ add(client0, seenLeader, sdoc("id",String.valueOf(i),"_version_",++v));+ add(client1, seenLeader, sdoc("id",String.valueOf(i),"_version_",v));+ }++ // some updates are on-wire+ add(client0, seenLeader, sdoc("id","21","_version_",++v));+ add(client0, seenLeader, sdoc("id","22","_version_",++v));++ // this will make a gap in buffer tlog+ add(client0, seenLeader, sdoc("id","23","_version_",++v));+ add(client1, seenLeader, sdoc("id","23","_version_",v));++ // client1 should be able to sync+ assertSync(client1, numVersions, true, shardsArr[0]);++ // on-wire updates arrived on jetty1+ add(client1, seenLeader, sdoc("id","21","_version_",v-2));+ add(client1, seenLeader, sdoc("id","22","_version_",v-1));++ log.info("Apply buffered updates");+ jetty1Core.getUpdateHandler().getUpdateLog().applyBufferedUpdates().get();++ for (int i = 1; i <= 23; i++) docsAdded.add(i);++ validateDocs(docsAdded, client0, client1);++ // random test+ v = 2000;+ if (random().nextBoolean()) {+ for (int i = 24; i <= 30; i++) {+ add(client0, seenLeader, sdoc("id",String.valueOf(i),"_version_",++v));+ add(client1, seenLeader, sdoc("id",String.valueOf(i),"_version_",v));+ }+ }++ log.info("After buffer updates");+ jetty1Core.getUpdateHandler().getUpdateLog().bufferUpdates();+ List<Object> onWireUpdates = new ArrayList<>();+ Set<Integer> docIds = new HashSet<>();++ for (int i = 0; i <= 50; i++) {+ int kindOfUpdate = random().nextInt(100);+ if (docIds.size() < 10) kindOfUpdate = 0;+ //TODO test atomic update+ if (kindOfUpdate <= 50) {+ // add a new document update, may by duplicate with the current one+ int val = random().nextInt(1000);+ int docId = random().nextInt(10000);+ docIds.add(docId);++ SolrInputDocument doc = sdoc("id", docId, "val_i_dvo", val, "_version_",++v);+ add(client0, seenLeader, doc);+ if (random().nextBoolean()) add(client1, seenLeader, doc);+ else onWireUpdates.add(doc);++ } else if (kindOfUpdate <= 65) {+ // delete by query+ ArrayList<Integer> ids = new ArrayList<>(docIds);+ int docId1 = ids.get(random().nextInt(ids.size()));+ int docId2 = ids.get(random().nextInt(ids.size()));++ String query = "id:" +docId1+" OR id:"+docId2;+ String version = Long.toString(-++v);+ delQ(client0, params(DISTRIB_UPDATE_PARAM,FROM_LEADER,"_version_",version), query);+ if (random().nextBoolean()) {+ delQ(client1, params(DISTRIB_UPDATE_PARAM,FROM_LEADER,"_version_",version), query);+ } else {+ onWireUpdates.add(new DeleteByQuery(query, version));+ }++ } else {+ // delete by id+ ArrayList<Integer> ids = new ArrayList<>(docIds);+ String docId = ids.get(random().nextInt(ids.size())) + "";+ String version = Long.toString(-++v);++ del(client0, params(DISTRIB_UPDATE_PARAM,FROM_LEADER,"_version_",version), docId);+ if (random().nextBoolean()) {+ del(client1, params(DISTRIB_UPDATE_PARAM,FROM_LEADER,"_version_",version), docId);+ } else {+ onWireUpdates.add(new DeleteById(docId, version));+ }+ }+ }+ // with many gaps, client1 should be able to sync+ assertSync(client1, numVersions, true, shardsArr[0]);+ }++ private static class DeleteByQuery {+ String query;+ String version;++ public DeleteByQuery(String query, String version) {+ this.query = query;+ this.version = version;+ }+ }++ private static class DeleteById {+ String id;+ String version;++ public DeleteById(String id, String version) {+ this.id = id;+ this.version = version;+ }+ }++ private void validateDocs(Set<Integer> docsAdded, SolrClient client0, SolrClient client1) throws SolrServerException, IOException {+ client0.commit();+ client1.commit();+ QueryResponse qacResponse;+ qacResponse = queryAndCompare(params("q", "*:*", "rows", "10000", "sort","_version_ desc"), client0, client1);+ validateQACResponse(docsAdded, qacResponse);+ }++ void validateQACResponse(Set<Integer> docsAdded, QueryResponse qacResponse) {+ Set<Integer> qacDocs = new LinkedHashSet<>();+ for (int i=0; i<qacResponse.getResults().size(); i++) {+ qacDocs.add(Integer.parseInt(qacResponse.getResults().get(i).getFieldValue("id").toString()));+ }+ assertEquals(docsAdded, qacDocs);+ assertEquals(docsAdded.size(), qacResponse.getResults().getNumFound());+ }++ void assertSync(SolrClient client, int numVersions, boolean expectedResult, String syncWith) throws IOException, SolrServerException {+ QueryRequest qr = new QueryRequest(params("qt","/get", "getVersions",Integer.toString(numVersions), "syncWithLeader", syncWith));+ NamedList rsp = client.request(qr);+ assertEquals(expectedResult, (Boolean) rsp.get("syncWithLeader"));+ }++}diff --git a/solr/core/src/test/org/apache/solr/update/PeerSyncWithLeaderAndIndexFingerprintCachingTest.java b/solr/core/src/test/org/apache/solr/update/PeerSyncWithLeaderAndIndexFingerprintCachingTest.javanew file mode 100644index 00000000000..aa668187d4f--- /dev/null+++ b/solr/core/src/test/org/apache/solr/update/PeerSyncWithLeaderAndIndexFingerprintCachingTest.java@@ -0,0 +1,36 @@+/*+ * Licensed to the Apache Software Foundation (ASF) under one or more+ * contributor license agreements. See the NOTICE file distributed with+ * this work for additional information regarding copyright ownership.+ * The ASF licenses this file to You under the Apache License, Version 2.0+ * (the "License"); you may not use this file except in compliance with+ * the License. You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++package org.apache.solr.update;++import java.io.IOException;+import java.util.Arrays;++import org.apache.solr.client.solrj.SolrClient;+import org.apache.solr.client.solrj.SolrServerException;+import org.apache.solr.client.solrj.request.QueryRequest;+import org.apache.solr.common.util.NamedList;+import org.apache.solr.common.util.StrUtils;++public class PeerSyncWithLeaderAndIndexFingerprintCachingTest extends PeerSyncWithIndexFingerprintCachingTest {+ @Override+ void assertSync(SolrClient client, int numVersions, boolean expectedResult, String... syncWith) throws IOException, SolrServerException {+ QueryRequest qr = new QueryRequest(params("qt","/get", "getVersions",Integer.toString(numVersions), "syncWithLeader", StrUtils.join(Arrays.asList(syncWith), ',')));+ NamedList rsp = client.request(qr);+ assertEquals(expectedResult, (Boolean) rsp.get("syncWithLeader"));+ }+}diff --git a/solr/core/src/test/org/apache/solr/update/PeerSyncWithLeaderTest.java b/solr/core/src/test/org/apache/solr/update/PeerSyncWithLeaderTest.javanew file mode 100644index 00000000000..4ca343a1d2b--- /dev/null+++ b/solr/core/src/test/org/apache/solr/update/PeerSyncWithLeaderTest.java@@ -0,0 +1,39 @@+/*+ * Licensed to the Apache Software Foundation (ASF) under one or more+ * contributor license agreements. See the NOTICE file distributed with+ * this work for additional information regarding copyright ownership.+ * The ASF licenses this file to You under the Apache License, Version 2.0+ * (the "License"); you may not use this file except in compliance with+ * the License. You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++package org.apache.solr.update;++import java.io.IOException;+import java.util.Arrays;++import org.apache.solr.SolrTestCaseJ4;+import org.apache.solr.client.solrj.SolrClient;+import org.apache.solr.client.solrj.SolrServerException;+import org.apache.solr.client.solrj.request.QueryRequest;+import org.apache.solr.common.util.NamedList;+import org.apache.solr.common.util.StrUtils;+[email protected](bugUrl = "https://issues.apache.org/jira/browse/SOLR-5776")+public class PeerSyncWithLeaderTest extends PeerSyncTest {++ @Override+ void assertSync(SolrClient client, int numVersions, boolean expectedResult, String... syncWith) throws IOException, SolrServerException {+ QueryRequest qr = new QueryRequest(params("qt","/get", "getVersions",Integer.toString(numVersions), "syncWithLeader", StrUtils.join(Arrays.asList(syncWith), ',')));+ NamedList rsp = client.request(qr);+ assertEquals(expectedResult, (Boolean) rsp.get("syncWithLeader"));+ }+}