Skip to content

Apache Lucene open-source search software

SOLR-5473: Make one state.json per collection , SOLR-5474: Have a new mode for SolrJ to support stateFormat=2

Noble Paul3cb0a855a01e
diff --git a/solr/CHANGES.txt b/solr/CHANGES.txt
index 657f70a4a27..b3cbd0670ce 100644
--- a/solr/CHANGES.txt
+++ b/solr/CHANGES.txt
@@ -109,6 +109,11 @@ Other Changes
* SOLR-5980: AbstractFullDistribZkTestBase#compareResults always returns false
for shouldFail. (Mark Miller, Gregory Chanan)
+* SOLR-5473: Make one state.json per collection (Noble Paul)
+
+* SOLR-5474: Have a new mode for SolrJ to support stateFormat=2 (Noble Paul, Tim Potter)
+
+
================== 4.8.0 ==================
Versions of Major Components
diff --git a/solr/core/src/java/org/apache/solr/SolrLogFormatter.java b/solr/core/src/java/org/apache/solr/SolrLogFormatter.java
index ff1cf222c63..8589720f940 100644
--- a/solr/core/src/java/org/apache/solr/SolrLogFormatter.java
+++ b/solr/core/src/java/org/apache/solr/SolrLogFormatter.java
@@ -263,7 +263,7 @@ sb.append("(group_name=").append(tg.getName()).append(")");
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());
+ Replica replica = zkController.getClusterState().getCachedReplica(collection, core.getCoreDescriptor().getCloudDescriptor().getCoreNodeName());
if(replica!=null) {
return replica.getProperties();
}
diff --git a/solr/core/src/java/org/apache/solr/cloud/Overseer.java b/solr/core/src/java/org/apache/solr/cloud/Overseer.java
index 94b9e0bec1a..6ae31500ba6 100644
--- a/solr/core/src/java/org/apache/solr/cloud/Overseer.java
+++ b/solr/core/src/java/org/apache/solr/cloud/Overseer.java
@@ -104,6 +104,10 @@ public class Overseer {
private Map clusterProps;
private boolean isClosed = false;
+
+ private final Map<String, Object> updateNodes = new LinkedHashMap<String,Object>();
+ private boolean isClusterStateModified = false;
+
public ClusterStateUpdater(final ZkStateReader reader, final String myId, Stats zkStats) {
this.zkClient = reader.getZkClient();
this.zkStats = zkStats;
@@ -115,6 +119,7 @@ public class Overseer {
this.myId = myId;
this.reader = reader;
clusterProps = reader.getClusterProps();
+ reader.ephemeralCollectionData = Collections.unmodifiableMap(updateNodes);
}
public Stats getStateUpdateQueueStats() {
@@ -161,7 +166,7 @@ public class Overseer {
stats.success(operation);
} catch (Exception e) {
// generally there is nothing we can do - in most cases, we have
- // an issue that will fail again on retry or we cannot communicate with
+ // an issue that will fail again on retry or we cannot communicate with a
// ZooKeeper in which case another Overseer should take over
// TODO: if ordering for the message is not important, we could
// track retries and put it back on the end of the queue
@@ -170,9 +175,8 @@ public class Overseer {
} finally {
timerContext.stop();
}
- zkClient.setData(ZkStateReader.CLUSTER_STATE,
- ZkStateReader.toJSON(clusterState), true);
-
+ updateZkStates(clusterState);
+
workQueue.poll(); // poll-ing removes the element we got by peek-ing
}
else {
@@ -256,13 +260,11 @@ public class Overseer {
stateUpdateQueue.poll();
if (isClosed || System.nanoTime() - lastUpdatedTime > TimeUnit.NANOSECONDS.convert(STATE_UPDATE_DELAY, TimeUnit.MILLISECONDS)) break;
-
+ if(!updateNodes.isEmpty()) break;
// if an event comes in the next 100ms batch it together
head = stateUpdateQueue.peek(100);
}
- lastUpdatedTime = System.nanoTime();
- zkClient.setData(ZkStateReader.CLUSTER_STATE,
- ZkStateReader.toJSON(clusterState), true);
+ updateZkStates(clusterState);
// clean work queue
while (workQueue.poll() != null) ;
@@ -294,6 +296,31 @@ public class Overseer {
}
}
+ private void updateZkStates(ClusterState clusterState) throws KeeperException, InterruptedException {
+ if(!updateNodes.isEmpty()) {
+ for (Entry<String, Object> e : updateNodes.entrySet()) {
+ if (e.getValue() == null) {
+ if (zkClient.exists(e.getKey(), true)) zkClient.delete(e.getKey(), 0, true);
+ } else {
+ if (zkClient.exists(e.getKey(), true)) {
+ log.info("going to update_collection", e.getKey());
+ zkClient.setData(e.getKey(), ZkStateReader.toJSON(e.getValue()), true);
+ } else {
+ log.info("going to create_collection {}", e.getValue());
+ zkClient.create(e.getKey(), ZkStateReader.toJSON(e.getValue()), CreateMode.PERSISTENT, true);
+ }
+ }
+ }
+ updateNodes.clear();
+ }
+
+ if(isClusterStateModified) {
+ lastUpdatedTime = System.nanoTime();
+ zkClient.setData(ZkStateReader.CLUSTER_STATE, ZkStateReader.toJSON(clusterState), true);
+ isClusterStateModified = false;
+ }
+ }
+
private void checkIfIamStillLeader() {
org.apache.zookeeper.data.Stat stat = new org.apache.zookeeper.data.Stat();
String path = "/overseer_elect/leader";
@@ -406,7 +433,8 @@ public class Overseer {
String coll = message.getStr(ZkStateReader.COLLECTION_PROP);
if (!checkCollectionKeyExistence(message)) return clusterState;
String slice = message.getStr(ZkStateReader.SHARD_ID_PROP);
- Slice sl = clusterState.getSlice(coll, slice);
+ DocCollection collection = clusterState.getCollection(coll);
+ Slice sl = collection.getSlice(slice);
if(sl == null){
log.error("Invalid Collection/Slice {}/{} ",coll,slice);
return clusterState;
@@ -419,7 +447,7 @@ public class Overseer {
ZkStateReader.BASE_URL_PROP,message.getStr(ZkStateReader.BASE_URL_PROP),
ZkStateReader.STATE_PROP,message.getStr(ZkStateReader.STATE_PROP)));
sl.getReplicasMap().put(coreNodeName, replica);
- return clusterState;
+ return newState(clusterState, singletonMap(coll, collection));
}
private ClusterState buildCollection(ClusterState clusterState, ZkNodeProps message) {
@@ -440,7 +468,7 @@ public class Overseer {
getShardNames(numShards, shardNames);
}
- return createCollection(clusterState,collection,shardNames,message);
+ return createCollection(clusterState, collection, shardNames, message);
}
private ClusterState updateShardState(ClusterState clusterState, ZkNodeProps message) {
@@ -807,16 +835,12 @@ public class Overseer {
List<DocRouter.Range> ranges = router.partitionRange(shards.size(), router.fullRange());
-// Map<String, DocCollection> newCollections = new LinkedHashMap<String,DocCollection>();
Map<String, Slice> newSlices = new LinkedHashMap<>();
-// newCollections.putAll(state.getCollectionStates());
+
for (int i = 0; i < shards.size(); i++) {
String sliceName = shards.get(i);
- /*}
- for (int i = 0; i < numShards; i++) {
- final String sliceName = "shard" + (i+1);*/
Map<String, Object> sliceProps = new LinkedHashMap<>(1);
sliceProps.put(Slice.RANGE, ranges == null? null: ranges.get(i));
@@ -838,11 +862,15 @@ public class Overseer {
if(message.getStr("fromApi") == null) collectionProps.put("autoCreated","true");
DocCollection newCollection = new DocCollection(collectionName, newSlices, collectionProps, router);
+ isClusterStateModified = true;
+ log.info("_extern {} {}", collectionName, newCollection.isExternal());
+ if (newCollection.isExternal()) {
+ updateNodes.put(ZkStateReader.getCollectionPath(collectionName),
+ new ClusterState(-1, Collections.<String>emptySet(), singletonMap(newCollection.getName(), newCollection), state.getStateReader()));
+ return state;
+ }
-// newCollections.put(collectionName, newCollection);
- return state.copyWith(singletonMap(newCollection.getName(), newCollection));
-// ClusterState newClusterState = new ClusterState(state.getLiveNodes(), newCollections);
-// return newClusterState;
+ return newState(state, singletonMap(newCollection.getName(), newCollection));
}
/*
@@ -884,8 +912,8 @@ public class Overseer {
private ClusterState updateSlice(ClusterState state, String collectionName, Slice slice) {
// System.out.println("###!!!### OLD CLUSTERSTATE: " + JSONUtil.toJSON(state.getCollectionStates()));
// System.out.println("Updating slice:" + slice);
- Map<String, DocCollection> newCollections = new LinkedHashMap<>(state.getCollectionStates()); // make a shallow copy
- DocCollection coll = newCollections.get(collectionName);
+
+ DocCollection coll = state.getCollectionOrNull(collectionName) ;
Map<String,Slice> slices;
Map<String,Object> props;
DocRouter router;
@@ -904,17 +932,15 @@ public class Overseer {
}
slices.put(slice.getName(), slice);
DocCollection newCollection = new DocCollection(collectionName, slices, props, router);
- newCollections.put(collectionName, newCollection);
// System.out.println("###!!!### NEW CLUSTERSTATE: " + JSONUtil.toJSON(newCollections));
- return new ClusterState(state.getLiveNodes(), newCollections);
+ return newState(state, singletonMap(collectionName, newCollection));
}
private ClusterState setShardLeader(ClusterState state, String collectionName, String sliceName, String leaderUrl) {
+ DocCollection coll = state.getCollectionOrNull(collectionName);
- final Map<String, DocCollection> newCollections = new LinkedHashMap<>(state.getCollectionStates());
- DocCollection coll = newCollections.get(collectionName);
if(coll == null) {
log.error("Could not mark shard leader for non existing collection:" + collectionName);
return state;
@@ -965,12 +991,28 @@ public class Overseer {
DocCollection newCollection = new DocCollection(coll.getName(), slices, coll.getProperties(), coll.getRouter());
- newCollections.put(collectionName, newCollection);
- return new ClusterState(state.getLiveNodes(), newCollections);
+ return newState(state, singletonMap(collectionName, newCollection));
+ }
+
+ private ClusterState newState(ClusterState state, Map<String, DocCollection> colls) {
+ for (Entry<String, DocCollection> e : colls.entrySet()) {
+ DocCollection c = e.getValue();
+ if (c == null) {
+ isClusterStateModified = true;
+ state = state.copyWith(singletonMap(e.getKey(), (DocCollection) null));
+ continue;
+ }
+
+ if (c.isExternal()) {
+ state.getStateReader().updateExternCollection(c);
+ updateNodes.put(ZkStateReader.getCollectionPath(c.getName()), new ClusterState(-1, Collections.<String>emptySet(), singletonMap(c.getName(), c), state.getStateReader()));
+ } else {
+ isClusterStateModified = true;
+ state = state.copyWith(singletonMap(e.getKey(), c));
+ }
+ }
+ return state;
}
- private ClusterState newState(ClusterState state, Map<String, DocCollection> colls) {
- return state.copyWith(colls);
- }
/*
* Remove collection from cloudstate
@@ -978,8 +1020,23 @@ public class Overseer {
private ClusterState removeCollection(final ClusterState clusterState, ZkNodeProps message) {
final String collection = message.getStr("name");
if (!checkKeyExistence(message, "name")) return clusterState;
+ DocCollection coll = clusterState.getCollectionOrNull(collection);
+ if(coll !=null) {
+ isClusterStateModified = true;
+ if(coll.isExternal()){
+ try {
+ log.info("Deleting state for collection : {}", collection);
+ zkClient.delete(ZkStateReader.getCollectionPath(collection),-1,true);
+ } catch (Exception e) {
+ throw new SolrException(SolrException.ErrorCode.SERVER_ERROR,"Unable to remove collection state :"+collection);
- return clusterState.copyWith(singletonMap(collection, (DocCollection)null));
+ }
+ return clusterState;
+ } else{
+ return clusterState.copyWith(singletonMap(collection,(DocCollection)null));
+ }
+ }
+ return clusterState;
}
/*
@@ -1060,7 +1117,6 @@ public class Overseer {
// if there are no slices left in the collection, remove it?
if (newSlices.size() == 0) {
-// newCollections.remove(coll.getName());
// TODO: it might be better logically to have this in ZkController
// but for tests (it's easier) it seems better for the moment to leave CoreContainer and/or
@@ -1075,16 +1131,11 @@ public class Overseer {
}
return newState(clusterState,singletonMap(collection, (DocCollection) null));
-
-
} else {
DocCollection newCollection = new DocCollection(coll.getName(), newSlices, coll.getProperties(), coll.getRouter());
return newState(clusterState,singletonMap(collection,newCollection));
-// newCollections.put(newCollection.getName(), newCollection);
}
-// ClusterState newState = new ClusterState(clusterState.getLiveNodes(), newCollections);
-// return newState;
}
@Override
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 905071c33e4..e78e99022a5 100644
--- a/solr/core/src/java/org/apache/solr/cloud/OverseerCollectionProcessor.java
+++ b/solr/core/src/java/org/apache/solr/cloud/OverseerCollectionProcessor.java
@@ -144,7 +144,8 @@ public class OverseerCollectionProcessor implements Runnable, ClosableThread {
ROUTER, DocRouter.DEFAULT_NAME,
REPLICATION_FACTOR, "1",
MAX_SHARDS_PER_NODE, "1",
- "external",null );
+ "external",null ,
+ DocCollection.STATE_FORMAT , null);
// TODO: use from Overseer?
@@ -607,7 +608,14 @@ public class OverseerCollectionProcessor implements Runnable, ClosableThread {
if (collection == null) {
Set<String> collections = clusterState.getCollections();
for (String name : collections) {
- Map<String, Object> collectionStatus = getCollectionStatus(stateMap, name, shard);
+ Map<String, Object> collectionStatus = null;
+ if (clusterState.hasExternalCollection(name)) {
+ bytes = ZkStateReader.toJSON(clusterState.getCollection(name));
+ Map<String, Object> docCollection = (Map<String, Object>) ZkStateReader.fromJSON(bytes);
+ collectionStatus = getCollectionStatus(docCollection, name, shard);
+ } else {
+ collectionStatus = getCollectionStatus((Map<String, Object>) stateMap.get(name), name, shard);
+ }
if (collectionVsAliases.containsKey(name) && !collectionVsAliases.get(name).isEmpty()) {
collectionStatus.put("aliases", collectionVsAliases.get(name));
}
@@ -615,16 +623,23 @@ public class OverseerCollectionProcessor implements Runnable, ClosableThread {
}
} else {
String routeKey = message.getStr(ShardParams._ROUTE_);
+ Map<String, Object> docCollection = null;
+ if (clusterState.hasExternalCollection(collection)) {
+ bytes = ZkStateReader.toJSON(clusterState.getCollection(collection));
+ docCollection = (Map<String, Object>) ZkStateReader.fromJSON(bytes);
+ } else {
+ docCollection = (Map<String, Object>) stateMap.get(collection);
+ }
if (routeKey == null) {
- Map<String, Object> collectionStatus = getCollectionStatus(stateMap, collection, shard);
+ Map<String, Object> collectionStatus = getCollectionStatus(docCollection, collection, shard);
if (collectionVsAliases.containsKey(collection) && !collectionVsAliases.get(collection).isEmpty()) {
collectionStatus.put("aliases", collectionVsAliases.get(collection));
}
collectionProps.add(collection, collectionStatus);
} else {
- DocCollection docCollection = clusterState.getCollection(collection);
- DocRouter router = docCollection.getRouter();
- Collection<Slice> slices = router.getSearchSlices(routeKey, null, docCollection);
+ DocCollection coll = clusterState.getCollection(collection);
+ DocRouter router = coll.getRouter();
+ Collection<Slice> slices = router.getSearchSlices(routeKey, null, coll);
String s = "";
for (Slice slice : slices) {
s += slice.getName() + ",";
@@ -632,7 +647,7 @@ public class OverseerCollectionProcessor implements Runnable, ClosableThread {
if (shard != null) {
s += shard;
}
- Map<String, Object> collectionStatus = getCollectionStatus(stateMap, collection, s);
+ Map<String, Object> collectionStatus = getCollectionStatus(docCollection, collection, s);
if (collectionVsAliases.containsKey(collection) && !collectionVsAliases.get(collection).isEmpty()) {
collectionStatus.put("aliases", collectionVsAliases.get(collection));
}
@@ -663,20 +678,19 @@ public class OverseerCollectionProcessor implements Runnable, ClosableThread {
* Can return collection status by given shard name.
*
*
- * @param clusterState cloud state map parsed from JSON-serialized {@link ClusterState}
+ * @param collection collection map parsed from JSON-serialized {@link ClusterState}
* @param name collection name
* @param shardStr comma separated shard names
* @return map of collection properties
*/
- private Map<String, Object> getCollectionStatus(Map<String, Object> clusterState, String name, String shardStr) {
- Map<String, Object> docCollection = (Map<String, Object>) clusterState.get(name);
- if (docCollection == null) {
+ private Map<String, Object> getCollectionStatus(Map<String, Object> collection, String name, String shardStr) {
+ if (collection == null) {
throw new SolrException(ErrorCode.BAD_REQUEST, "Collection: " + name + " not found");
}
if (shardStr == null) {
- return docCollection;
+ return collection;
} else {
- Map<String, Object> shards = (Map<String, Object>) docCollection.get("shards");
+ Map<String, Object> shards = (Map<String, Object>) collection.get("shards");
Map<String, Object> selected = new HashMap<>();
List<String> selectedShards = Arrays.asList(shardStr.split(","));
for (String selectedShard : selectedShards) {
@@ -684,9 +698,9 @@ public class OverseerCollectionProcessor implements Runnable, ClosableThread {
throw new SolrException(ErrorCode.BAD_REQUEST, "Collection: " + name + " shard: " + selectedShard + " not found");
}
selected.put(selectedShard, shards.get(selectedShard));
- docCollection.put("shards", selected);
+ collection.put("shards", selected);
}
- return docCollection;
+ return collection;
}
}
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 f56702c03bd..8d9652d53d4 100644
--- a/solr/core/src/java/org/apache/solr/cloud/ZkController.java
+++ b/solr/core/src/java/org/apache/solr/cloud/ZkController.java
@@ -1072,9 +1072,18 @@ public final class ZkController {
if (context != null) {
context.cancelElection();
}
-
+
CloudDescriptor cloudDescriptor = cd.getCloudDescriptor();
-
+ boolean removeWatch = true;
+ for (SolrCore solrCore : cc.getCores()) {//if there is no SolrCoe which is a member of this collection, remove the watch
+ CloudDescriptor cloudDesc = solrCore.getCoreDescriptor().getCloudDescriptor();
+ if (cloudDesc != null && cloudDescriptor.getCollectionName().equals(cloudDesc.getCollectionName())) {
+ //means
+ removeWatch = false;
+ break;
+ }
+ }
+ if(removeWatch) zkStateReader.removeZKWatch(collection);
ZkNodeProps m = new ZkNodeProps(Overseer.QUEUE_OPERATION,
Overseer.DELETECORE, ZkStateReader.CORE_NAME_PROP, coreName,
ZkStateReader.NODE_NAME_PROP, getNodeName(),
@@ -1291,7 +1300,7 @@ public final class ZkController {
log.info("waiting to find shard id in clusterstate for " + cd.getName());
int retryCount = 320;
while (retryCount-- > 0) {
- final String shardId = zkStateReader.getClusterState().getShardId(getNodeName(), cd.getName());
+ final String shardId = zkStateReader.getClusterState().getShardId(cd.getCollectionName(), getNodeName(), cd.getName());
if (shardId != null) {
cd.getCloudDescriptor().setShardId(shardId);
return;
@@ -1376,6 +1385,11 @@ public final class ZkController {
}
publish(cd, ZkStateReader.DOWN, false, true);
+ DocCollection collection = zkStateReader.getClusterState().getCollectionOrNull(cd.getCloudDescriptor().getCollectionName());
+ if(collection !=null && collection.isExternal() ){
+ log.info("Registering watch for external collection {}",cd.getCloudDescriptor().getCollectionName());
+ zkStateReader.addCollectionWatch(cd.getCloudDescriptor().getCollectionName());
+ }
} catch (KeeperException e) {
log.error("", e);
throw new ZooKeeperException(SolrException.ErrorCode.SERVER_ERROR, "", e);
diff --git a/solr/core/src/java/org/apache/solr/handler/admin/CollectionsHandler.java b/solr/core/src/java/org/apache/solr/handler/admin/CollectionsHandler.java
index 46acf578892..f78ce8e2d83 100644
--- a/solr/core/src/java/org/apache/solr/handler/admin/CollectionsHandler.java
+++ b/solr/core/src/java/org/apache/solr/handler/admin/CollectionsHandler.java
@@ -58,6 +58,7 @@ import org.apache.solr.cloud.OverseerSolrResponse;
import org.apache.solr.common.SolrException;
import org.apache.solr.common.SolrException.ErrorCode;
import org.apache.solr.common.cloud.ClusterState;
+import org.apache.solr.common.cloud.DocCollection;
import org.apache.solr.common.cloud.ImplicitDocRouter;
import org.apache.solr.common.cloud.ZkCoreNodeProps;
import org.apache.solr.common.cloud.ZkNodeProps;
@@ -465,6 +466,7 @@ public class CollectionsHandler extends RequestHandlerBase {
MAX_SHARDS_PER_NODE,
CREATE_NODE_SET ,
SHARDS_PROP,
+ DocCollection.STATE_FORMAT,
ASYNC,
"router.");
diff --git a/solr/core/src/java/org/apache/solr/servlet/SolrDispatchFilter.java b/solr/core/src/java/org/apache/solr/servlet/SolrDispatchFilter.java
index efee05ea3c0..297596f22fb 100644
--- a/solr/core/src/java/org/apache/solr/servlet/SolrDispatchFilter.java
+++ b/solr/core/src/java/org/apache/solr/servlet/SolrDispatchFilter.java
@@ -34,6 +34,7 @@ import org.apache.http.HeaderIterator;
import org.apache.http.HttpEntity;
import org.apache.http.HttpEntityEnclosingRequest;
import org.apache.http.HttpResponse;
+import org.apache.solr.client.solrj.impl.CloudSolrServer;
import org.apache.solr.common.SolrException;
import org.apache.solr.common.SolrException.ErrorCode;
import org.apache.solr.common.cloud.Aliases;
@@ -323,6 +324,7 @@ public class SolrDispatchFilter extends BaseSolrFilter {
String coreUrl = getRemotCoreUrl(cores, corename, origCorename);
// don't proxy for internal update requests
SolrParams queryParams = SolrRequestParsers.parseQueryString(req.getQueryString());
+ checkStateIsValid(cores, queryParams.get(CloudSolrServer.STATE_VERSION));
if (coreUrl != null
&& queryParams
.get(DistributingUpdateProcessorFactory.DISTRIB_UPDATE_PARAM) == null) {
@@ -377,6 +379,8 @@ public class SolrDispatchFilter extends BaseSolrFilter {
if( handler == null && parser.isHandleSelect() ) {
if( "/select".equals( path ) || "/select/".equals( path ) ) {
solrReq = parser.parse( core, path, req );
+
+ checkStateIsValid(cores,solrReq.getParams().get(CloudSolrServer.STATE_VERSION));
String qt = solrReq.getParams().get( CommonParams.QT );
handler = core.getRequestHandler( qt );
if( handler == null ) {
@@ -462,6 +466,23 @@ public class SolrDispatchFilter extends BaseSolrFilter {
// Otherwise let the webapp handle the request
chain.doFilter(request, response);
}
+
+ private void checkStateIsValid(CoreContainer cores, String stateVer) {
+ if(stateVer != null && !stateVer.isEmpty() && cores.isZooKeeperAware() ){
+ // many have multiple collections separated by |
+ String[] pairs = StringUtils.split(stateVer, '|');
+ for (String pair : pairs) {
+ String[] pcs = StringUtils.split(pair, ':');
+ if(pcs.length == 2 && !pcs[0].isEmpty() && !pcs[1].isEmpty()){
+ Boolean status = cores.getZkController().getZkStateReader().checkValid(pcs[0],Integer.parseInt(pcs[1]));
+
+ if(Boolean.TRUE != status){
+ throw new SolrException(ErrorCode.INVALID_STATE, "STATE STALE: " + pair+ "valid : "+status);
+ }
+ }
+ }
+ }
+ }
private void processAliases(SolrQueryRequest solrReq, Aliases aliases,
List<String> collectionsList) {
diff --git a/solr/core/src/java/org/apache/solr/servlet/ZookeeperInfoServlet.java b/solr/core/src/java/org/apache/solr/servlet/ZookeeperInfoServlet.java
index 06718c32410..148cf675fa8 100644
--- a/solr/core/src/java/org/apache/solr/servlet/ZookeeperInfoServlet.java
+++ b/solr/core/src/java/org/apache/solr/servlet/ZookeeperInfoServlet.java
@@ -24,19 +24,28 @@ import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.Date;
import java.util.List;
+import java.util.Map;
+import java.util.SortedMap;
+import java.util.TreeMap;
import javax.servlet.ServletException;
+import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.lucene.util.BytesRef;
+import org.noggit.CharArr;
+import org.noggit.JSONWriter;
+import org.noggit.ObjectBuilder;
import org.apache.solr.cloud.ZkController;
import org.apache.solr.common.SolrException;
import org.apache.solr.common.cloud.SolrZkClient;
+import org.apache.solr.common.cloud.ZkStateReader;
import org.apache.solr.common.params.SolrParams;
import org.apache.solr.core.CoreContainer;
import org.apache.solr.util.FastWriter;
import org.apache.zookeeper.KeeperException;
+import org.apache.zookeeper.KeeperException.NoNodeException;
import org.apache.zookeeper.data.Stat;
import org.noggit.CharArr;
import org.noggit.JSONWriter;
@@ -49,9 +58,9 @@ import org.slf4j.LoggerFactory;
*
* @since solr 4.0
*/
-public final class ZookeeperInfoServlet extends BaseSolrServlet {
+public final class ZookeeperInfoServlet extends HttpServlet {
static final Logger log = LoggerFactory.getLogger(ZookeeperInfoServlet.class);
-
+
@Override
public void init() {
}
@@ -65,7 +74,7 @@ public final class ZookeeperInfoServlet extends BaseSolrServlet {
if (cores == null) {
throw new ServletException("Missing request attribute org.apache.solr.CoreContainer.");
}
-
+
final SolrParams params;
try {
params = SolrRequestParsers.DEFAULT.parse(null, request.getServletPath(), request).getParams();
@@ -80,6 +89,7 @@ public final class ZookeeperInfoServlet extends BaseSolrServlet {
String path = params.get("path");
String addr = params.get("addr");
+ boolean all = "true".equals(params.get("all"));
if (addr != null && addr.length() == 0) {
addr = null;
@@ -101,11 +111,11 @@ public final class ZookeeperInfoServlet extends BaseSolrServlet {
printer.dump = dump;
try {
- printer.print(path);
+ printer.print(path, all);
} finally {
printer.close();
}
-
+
out.flush();
}
@@ -184,7 +194,7 @@ public final class ZookeeperInfoServlet extends BaseSolrServlet {
}
// main entry point
- void print(String path) throws IOException {
+ void print(String path, boolean all) throws IOException {
if (zkClient == null) {
return;
}
@@ -214,7 +224,7 @@ public final class ZookeeperInfoServlet extends BaseSolrServlet {
json.startObject();
if (detail) {
- if (!printZnode(json, path)) {
+ if (!printZnode(json, path,all)) {
return;
}
json.writeValueSeparator();
@@ -285,7 +295,7 @@ public final class ZookeeperInfoServlet extends BaseSolrServlet {
if (dump) {
json.writeValueSeparator();
- printZnode(json, path);
+ printZnode(json, path, false);
}
} catch (IllegalArgumentException e) {
@@ -358,7 +368,8 @@ public final class ZookeeperInfoServlet extends BaseSolrServlet {
json.write(v);
}
- boolean printZnode(JSONWriter json, String path) throws IOException {
+ @SuppressWarnings("unchecked")
+ boolean printZnode(JSONWriter json, String path, boolean all) throws IOException {
try {
Stat stat = new Stat();
// Trickily, the call to zkClient.getData fills in the stat variable
@@ -374,6 +385,48 @@ public final class ZookeeperInfoServlet extends BaseSolrServlet {
}
}
+ // pull in external collections too
+ if ("/clusterstate.json".equals(path) && all) {
+ SortedMap<String,Object> collectionStates = null;
+ List<String> children = zkClient.getChildren("/collections", null, true);
+ java.util.Collections.sort(children);
+ for (String collection : children) {
+ String collStatePath = String.format("/collections/%s/state", collection);
+ String childDataStr = null;
+ try {
+ byte[] childData = zkClient.getData(collStatePath, null, null, true);
+ if (childData != null) {
+ childDataStr = (new BytesRef(childData)).utf8ToString();
+ }
+ } catch (NoNodeException nne) {
+ // safe to ignore
+ } catch (Exception childErr) {
+ log.error("Failed to get "+collStatePath+" due to: "+childErr);
+ }
+
+ if (childDataStr != null) {
+ if (collectionStates == null) {
+ // initialize lazily as there may not be any external collections
+ collectionStates = new TreeMap<String,Object>();
+
+ // add the internal collections
+ if (dataStr != null)
+ collectionStates.putAll((Map<String,Object>)ObjectBuilder.fromJSON(dataStr));
+ }
+
+ // now add in the external collections
+ Map<String,Object> extColl = (Map<String,Object>)ObjectBuilder.fromJSON(childDataStr);
+ collectionStates.put(collection, extColl.get(collection));
+ }
+ }
+
+ if (collectionStates != null) {
+ CharArr out = new CharArr();
+ new JSONWriter(out, 2).write(collectionStates);
+ dataStr = out.toString();
+ }
+ }
+
json.writeString("znode");
json.writeNameSeparator();
json.startObject();
diff --git a/solr/core/src/java/org/apache/solr/util/SolrLogLayout.java b/solr/core/src/java/org/apache/solr/util/SolrLogLayout.java
index fe4d79ca396..6251054a435 100644
--- a/solr/core/src/java/org/apache/solr/util/SolrLogLayout.java
+++ b/solr/core/src/java/org/apache/solr/util/SolrLogLayout.java
@@ -11,7 +11,10 @@ import org.apache.log4j.spi.LoggingEvent;
import org.apache.log4j.spi.ThrowableInformation;
import org.apache.solr.cloud.ZkController;
import org.apache.solr.common.SolrException;
+import org.apache.solr.common.cloud.ClusterState;
+import org.apache.solr.common.cloud.DocCollection;
import org.apache.solr.common.cloud.Replica;
+import org.apache.solr.common.cloud.Slice;
import org.apache.solr.core.SolrCore;
import org.apache.solr.request.SolrQueryRequest;
import org.apache.solr.request.SolrRequestInfo;
@@ -231,7 +234,7 @@ public class SolrLogLayout extends Layout {
private Map<String,Object> getReplicaProps(ZkController zkController, SolrCore core) {
final String collection = core.getCoreDescriptor().getCloudDescriptor().getCollectionName();
- Replica replica = zkController.getClusterState().getReplica(collection, zkController.getCoreNodeName(core.getCoreDescriptor()));
+ Replica replica = zkController.getClusterState().getCachedReplica(collection, zkController.getCoreNodeName(core.getCoreDescriptor()));
if(replica!=null) {
return replica.getProperties();
}
diff --git a/solr/core/src/test/org/apache/solr/cloud/CollectionsAPIDistributedZkTest.java b/solr/core/src/test/org/apache/solr/cloud/CollectionsAPIDistributedZkTest.java
index 3e1780b1a2e..65b97e2aab8 100644
--- a/solr/core/src/test/org/apache/solr/cloud/CollectionsAPIDistributedZkTest.java
+++ b/solr/core/src/test/org/apache/solr/cloud/CollectionsAPIDistributedZkTest.java
@@ -50,6 +50,7 @@ import javax.management.ObjectName;
import org.apache.lucene.util.LuceneTestCase.Slow;
import org.apache.lucene.util.TestUtil;
+import org.apache.solr.SolrTestCaseJ4;
import org.apache.solr.client.solrj.SolrQuery;
import org.apache.solr.client.solrj.SolrRequest;
import org.apache.solr.client.solrj.SolrServer;
@@ -245,7 +246,7 @@ public class CollectionsAPIDistributedZkTest extends AbstractFullDistribZkTestBa
checkForMissingCollection(collectionName);
assertFalse(cloudClient.getZkStateReader().getZkClient().exists(ZkStateReader.COLLECTIONS_ZKNODE + "/" + collectionName, true));
-
+
}
private void testSolrJAPICalls() throws Exception {
@@ -410,7 +411,7 @@ public class CollectionsAPIDistributedZkTest extends AbstractFullDistribZkTestBa
}
assertFalse("Still found collection that should be gone", cloudClient.getZkStateReader().getClusterState().hasCollection("halfdeletedcollection2"));
-
+
}
private void testErrorHandling() throws Exception {
@@ -1162,27 +1163,6 @@ public class CollectionsAPIDistributedZkTest extends AbstractFullDistribZkTestBa
fail("Could not find the new collection - " + exp.code() + " : " + collectionClient.getBaseURL());
}*/
- private void checkForMissingCollection(String collectionName)
- throws Exception {
- // check for a collection - we poll the state
- long timeoutAt = System.currentTimeMillis() + 45000;
- boolean found = true;
- while (System.currentTimeMillis() < timeoutAt) {
- getCommonCloudSolrServer().getZkStateReader().updateClusterState(true);
- ClusterState clusterState = getCommonCloudSolrServer().getZkStateReader().getClusterState();
-// Map<String,DocCollection> collections = clusterState
-// .getCollectionStates();
- if (! clusterState.hasCollection(collectionName)) {
- found = false;
- break;
- }
- Thread.sleep(100);
- }
- if (found) {
- fail("Found collection that should be gone " + collectionName);
- }
- }
-
private void checkNoTwoShardsUseTheSameIndexDir() throws Exception {
Map<String, Set<String>> indexDirToShardNamesMap = new HashMap<>();
diff --git a/solr/core/src/test/org/apache/solr/cloud/ExternalCollectionsTest.java b/solr/core/src/test/org/apache/solr/cloud/ExternalCollectionsTest.java
new file mode 100644
index 00000000000..5985b57477a
--- /dev/null
+++ b/solr/core/src/test/org/apache/solr/cloud/ExternalCollectionsTest.java
@@ -0,0 +1,123 @@
+package org.apache.solr.cloud;
+
+/*
+ * 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 org.apache.solr.client.solrj.impl.CloudSolrServer;
+import org.apache.solr.client.solrj.request.QueryRequest;
+import org.apache.solr.common.cloud.SolrZkClient;
+import org.apache.solr.common.cloud.ZkStateReader;
+import org.apache.solr.common.params.CollectionParams;
+import org.apache.solr.common.params.ModifiableSolrParams;
+import org.apache.zookeeper.data.Stat;
+import org.junit.After;
+import org.junit.Before;
+import org.junit.BeforeClass;
+
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+import static org.apache.solr.cloud.OverseerCollectionProcessor.MAX_SHARDS_PER_NODE;
+import static org.apache.solr.cloud.OverseerCollectionProcessor.NUM_SLICES;
+import static org.apache.solr.cloud.OverseerCollectionProcessor.REPLICATION_FACTOR;
+import static org.apache.solr.common.cloud.ZkNodeProps.makeMap;
+
+public class ExternalCollectionsTest extends AbstractFullDistribZkTestBase {
+ private CloudSolrServer client;
+
+ @BeforeClass
+ public static void beforeThisClass2() throws Exception {
+
+ }
+
+ @Before
+ @Override
+ public void setUp() throws Exception {
+ super.setUp();
+ System.setProperty("numShards", Integer.toString(sliceCount));
+ System.setProperty("solr.xml.persist", "true");
+ client = createCloudClient(null);
+ }
+
+ @After
+ public void tearDown() throws Exception {
+ super.tearDown();
+ client.shutdown();
+ }
+
+ protected String getSolrXml() {
+ return "solr-no-core.xml";
+ }
+
+ public ExternalCollectionsTest() {
+ fixShardCount = true;
+
+ sliceCount = 2;
+ shardCount = 4;
+
+ checkCreatedVsState = false;
+ }
+
+
+ @Override
+ public void doTest() throws Exception {
+ testZkNodeLocation();
+ }
+
+
+ boolean externalColl = false;
+ @Override
+ public boolean useExternalCollections() {
+ return externalColl;
+ }
+
+ private void testZkNodeLocation() throws Exception{
+ externalColl=true;
+
+ String collectionName = "myExternColl";
+
+ createCollection(collectionName, client, 2, 2);
+
+ waitForRecoveriesToFinish(collectionName, false);
+ assertTrue("does not exist collection state externally", cloudClient.getZkStateReader().getZkClient().exists(ZkStateReader.getCollectionPath(collectionName), true));
+ Stat stat = new Stat();
+ cloudClient.getZkStateReader().getZkClient().getData(ZkStateReader.getCollectionPath(collectionName),null,stat,true);
+ assertEquals("", cloudClient.getZkStateReader().getClusterState().getCollection(collectionName).getVersion(), stat.getVersion());
+ assertTrue("DocCllection#isExternal() must be true", cloudClient.getZkStateReader().getClusterState().getCollection(collectionName).isExternal() );
+
+
+ // remove collection
+ ModifiableSolrParams params = new ModifiableSolrParams();
+ params.set("action", CollectionParams.CollectionAction.DELETE.toString());
+ params.set("name", collectionName);
+ QueryRequest request = new QueryRequest(params);
+ request.setPath("/admin/collections");
+ if (client == null) {
+ client = createCloudClient(null);
+ }
+
+ client.request(request);
+
+ checkForMissingCollection(collectionName);
+ assertFalse("collection state should not exist externally", cloudClient.getZkStateReader().getZkClient().exists(ZkStateReader.getCollectionPath(collectionName), true));
+
+ }
+}
+
+
+
diff --git a/solr/core/src/test/org/apache/solr/cloud/OverseerStatusTest.java b/solr/core/src/test/org/apache/solr/cloud/OverseerStatusTest.java
index 48297363cb9..8404aed55b3 100644
--- a/solr/core/src/test/org/apache/solr/cloud/OverseerStatusTest.java
+++ b/solr/core/src/test/org/apache/solr/cloud/OverseerStatusTest.java
@@ -68,16 +68,37 @@ public class OverseerStatusTest extends BasicDistributedZkTest {
public void doTest() throws Exception {
waitForThingsToLevelOut(15);
+ // find existing command counts because collection may be created by base test class too
+ int numCollectionCreates = 0, numOverseerCreates = 0;
+ NamedList<Object> resp = invokeCollectionApi("action",
+ CollectionParams.CollectionAction.OVERSEERSTATUS.toLower());
+ if (resp != null) {
+ NamedList<Object> collection_operations = (NamedList<Object>) resp.get("collection_operations");
+ if (collection_operations != null) {
+ SimpleOrderedMap<Object> createcollection = (SimpleOrderedMap<Object>) collection_operations.get(OverseerCollectionProcessor.CREATECOLLECTION);
+ if (createcollection != null && createcollection.get("requests") != null) {
+ numCollectionCreates = (Integer) createcollection.get("requests");
+ }
+ NamedList<Object> overseer_operations = (NamedList<Object>) resp.get("overseer_operations");
+ if (overseer_operations != null) {
+ createcollection = (SimpleOrderedMap<Object>) overseer_operations.get("createcollection");
+ if (createcollection != null && createcollection.get("requests") != null) {
+ numOverseerCreates = (Integer) createcollection.get("requests");
+ }
+ }
+ }
+ }
+
String collectionName = "overseer_status_test";
CollectionAdminResponse response = createCollection(collectionName, 1, 1, 1);
- NamedList<Object> resp = invokeCollectionApi("action",
+ resp = invokeCollectionApi("action",
CollectionParams.CollectionAction.OVERSEERSTATUS.toLower());
NamedList<Object> collection_operations = (NamedList<Object>) resp.get("collection_operations");
NamedList<Object> overseer_operations = (NamedList<Object>) resp.get("overseer_operations");
SimpleOrderedMap<Object> createcollection = (SimpleOrderedMap<Object>) collection_operations.get(OverseerCollectionProcessor.CREATECOLLECTION);
- assertEquals("No stats for createcollection in OverseerCollectionProcessor", 1, createcollection.get("requests"));
+ assertEquals("No stats for createcollection in OverseerCollectionProcessor", numCollectionCreates + 1, createcollection.get("requests"));
createcollection = (SimpleOrderedMap<Object>) overseer_operations.get("createcollection");
- assertEquals("No stats for createcollection in Overseer", 1, createcollection.get("requests"));
+ assertEquals("No stats for createcollection in Overseer", numOverseerCreates + 1, createcollection.get("requests"));
invokeCollectionApi("action", CollectionParams.CollectionAction.RELOAD.toLower(), "name", collectionName);
resp = invokeCollectionApi("action",
diff --git a/solr/core/src/test/org/apache/solr/cloud/TestCollectionAPI.java b/solr/core/src/test/org/apache/solr/cloud/TestCollectionAPI.java
index 329ec34370f..31eda5265a8 100644
--- a/solr/core/src/test/org/apache/solr/cloud/TestCollectionAPI.java
+++ b/solr/core/src/test/org/apache/solr/cloud/TestCollectionAPI.java
@@ -63,6 +63,11 @@ public class TestCollectionAPI extends AbstractFullDistribZkTestBase {
client.shutdown();
}
+ waitForCollection(cloudClient.getZkStateReader(), COLLECTION_NAME, 2);
+ waitForCollection(cloudClient.getZkStateReader(), COLLECTION_NAME1, 1);
+ waitForRecoveriesToFinish(COLLECTION_NAME, false);
+ waitForRecoveriesToFinish(COLLECTION_NAME1, false);
+
listCollection();
clusterStatusNoCollection();
clusterStatusWithCollection();
diff --git a/solr/solrj/src/java/org/apache/solr/client/solrj/impl/CloudSolrServer.java b/solr/solrj/src/java/org/apache/solr/client/solrj/impl/CloudSolrServer.java
index 4fd66a79bb2..ba24e0b3678 100644
--- a/solr/solrj/src/java/org/apache/solr/client/solrj/impl/CloudSolrServer.java
+++ b/solr/solrj/src/java/org/apache/solr/client/solrj/impl/CloudSolrServer.java
@@ -18,7 +18,9 @@ package org.apache.solr.client.solrj.impl;
*/
import java.io.IOException;
+import java.net.ConnectException;
import java.net.MalformedURLException;
+import java.net.SocketException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
@@ -30,13 +32,16 @@ import java.util.Map;
import java.util.Random;
import java.util.Set;
import java.util.concurrent.Callable;
+import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeoutException;
+import org.apache.http.NoHttpResponseException;
import org.apache.http.client.HttpClient;
+import org.apache.http.conn.ConnectTimeoutException;
import org.apache.solr.client.solrj.ResponseParser;
import org.apache.solr.client.solrj.SolrRequest;
import org.apache.solr.client.solrj.SolrServer;
@@ -67,6 +72,8 @@ import org.apache.solr.common.util.NamedList;
import org.apache.solr.common.util.SolrjNamedThreadFactory;
import org.apache.solr.common.util.StrUtils;
import org.apache.zookeeper.KeeperException;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
/**
* SolrJ client class to communicate with SolrCloud.
@@ -79,6 +86,8 @@ import org.apache.zookeeper.KeeperException;
* with {@link #setIdField(String)}.
*/
public class CloudSolrServer extends SolrServer {
+ private static final Logger log = LoggerFactory.getLogger(CloudSolrServer.class);
+
private volatile ZkStateReader zkStateReader;
private String zkHost; // the zk server address
private int zkConnectTimeout = 10000;
@@ -95,6 +104,7 @@ public class CloudSolrServer extends SolrServer {
.newCachedThreadPool(new SolrjNamedThreadFactory(
"CloudSolrServer ThreadPool"));
private String idField = "id";
+ public static final String STATE_VERSION = "_stateVer_";
private final Set<String> NON_ROUTABLE_PARAMS;
{
NON_ROUTABLE_PARAMS = new HashSet<>();
@@ -112,25 +122,51 @@ public class CloudSolrServer extends SolrServer {
// NON_ROUTABLE_PARAMS.add(UpdateParams.ROLLBACK);
}
+ private volatile long timeToLive;
+
+
+ protected Map<String, ExpiringCachedDocCollection> collectionStateCache = new ConcurrentHashMap<String, ExpiringCachedDocCollection>(){
+ @Override
+ public ExpiringCachedDocCollection get(Object key) {
+ ExpiringCachedDocCollection val = super.get(key);
+ if(val == null) return null;
+ if(val.isExpired(timeToLive)) {
+ super.remove(key);
+ return null;
+ }
+ return val;
+ }
+
+ };
+ class ExpiringCachedDocCollection {
+ DocCollection cached;
+ long cachedAt;
+ ExpiringCachedDocCollection(DocCollection cached) {
+ this.cached = cached;
+ this.cachedAt = System.currentTimeMillis();
+ }
+
+ boolean isExpired(long timeToLive) {
+ return (System.currentTimeMillis() - cachedAt) > timeToLive;
+ }
+ }
/**
* @param zkHost The client endpoint of the zookeeper quorum containing the cloud state,
* in the form HOST:PORT.
*/
public CloudSolrServer(String zkHost) {
- this.zkHost = zkHost;
- this.myClient = HttpClientUtil.createClient(null);
- this.lbServer = new LBHttpSolrServer(myClient);
- this.lbServer.setRequestWriter(new BinaryRequestWriter());
- this.lbServer.setParser(new BinaryResponseParser());
- this.updatesToLeaders = true;
- shutdownLBHttpSolrServer = true;
+ this(zkHost, true, 60);
}
-
- public CloudSolrServer(String zkHost, boolean updatesToLeaders)
- throws MalformedURLException {
+
+ public CloudSolrServer(String zkHost, boolean updatesToLeaders) throws MalformedURLException {
+ this(zkHost, updatesToLeaders, 60);
+ }
+
+ public CloudSolrServer(String zkHost, boolean updatesToLeaders, int cachedStateTimeToLiveSecs) {
+
this.zkHost = zkHost;
this.myClient = HttpClientUtil.createClient(null);
this.lbServer = new LBHttpSolrServer(myClient);
@@ -138,6 +174,9 @@ public class CloudSolrServer extends SolrServer {
this.lbServer.setParser(new BinaryResponseParser());
this.updatesToLeaders = updatesToLeaders;
shutdownLBHttpSolrServer = true;
+
+ timeToLive = cachedStateTimeToLiveSecs * 1000L;
+ setupStateVerParamOnQueryString(lbServer);
}
/**
@@ -146,10 +185,7 @@ public class CloudSolrServer extends SolrServer {
* @param lbServer LBHttpSolrServer instance for requests.
*/
public CloudSolrServer(String zkHost, LBHttpSolrServer lbServer) {
- this.zkHost = zkHost;
- this.lbServer = lbServer;
- this.updatesToLeaders = true;
- shutdownLBHttpSolrServer = false;
+ this(zkHost, lbServer, true);
}
/**
@@ -159,12 +195,34 @@ public class CloudSolrServer extends SolrServer {
* @param updatesToLeaders sends updates only to leaders - defaults to true
*/
public CloudSolrServer(String zkHost, LBHttpSolrServer lbServer, boolean updatesToLeaders) {
+ this(zkHost, lbServer, updatesToLeaders, 60);
+ }
+
+ public CloudSolrServer(String zkHost, LBHttpSolrServer lbServer, boolean updatesToLeaders, int cachedStateTimeToLiveSecs) {
this.zkHost = zkHost;
this.lbServer = lbServer;
this.updatesToLeaders = updatesToLeaders;
shutdownLBHttpSolrServer = false;
+ timeToLive = cachedStateTimeToLiveSecs * 1000L;
+
+ setupStateVerParamOnQueryString(lbServer);
}
-
+
+ /**
+ * Used internally to setup the _stateVer_ param to be sent in the query string of requests
+ * coming from this instance.
+ * @param lbServer
+ */
+ protected void setupStateVerParamOnQueryString(LBHttpSolrServer lbServer) {
+ // setup the stateVer param to be passed in the query string of every request
+ Set<String> queryStringParams = lbServer.getQueryParams();
+ if (queryStringParams == null) {
+ queryStringParams = new HashSet<String>(2);
+ lbServer.setQueryParams(queryStringParams);
+ }
+ queryStringParams.add("_stateVer_");
+ }
+
public ResponseParser getParser() {
return lbServer.getParser();
}
@@ -237,10 +295,7 @@ public class CloudSolrServer extends SolrServer {
synchronized (this) {
if (zkStateReader == null) {
try {
- ZkStateReader zk = new ZkStateReader(zkHost, zkClientTimeout,
- zkConnectTimeout);
- zk.createClusterStateWatchersAndUpdate();
- zkStateReader = zk;
+ zkStateReader = createZkStateReader(zkHost, zkClientTimeout, zkConnectTimeout);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new ZooKeeperException(SolrException.ErrorCode.SERVER_ERROR,
@@ -293,7 +348,7 @@ public class CloudSolrServer extends SolrServer {
}
}
- DocCollection col = clusterState.getCollection(collection);
+ DocCollection col = getDocCollection(clusterState, collection);
DocRouter router = col.getRouter();
@@ -311,8 +366,8 @@ public class CloudSolrServer extends SolrServer {
return null;
}
- NamedList<Throwable> exceptions = new NamedList<Throwable>();
- NamedList<NamedList> shardResponses = new NamedList<NamedList>();
+ NamedList<Throwable> exceptions = new NamedList<>();
+ NamedList<NamedList> shardResponses = new NamedList<>();
Map<String, LBHttpSolrServer.Req> routes = updateRequest.getRoutes(router, col, urlMap, routableParams, this.idField);
if (routes == null) {
@@ -496,7 +551,145 @@ public class CloudSolrServer extends SolrServer {
}
@Override
- public NamedList<Object> request(SolrRequest request)
+ public NamedList<Object> request(SolrRequest request) throws SolrServerException, IOException {
+ SolrParams reqParams = request.getParams();
+ String collection = (reqParams != null) ? reqParams.get("collection", getDefaultCollection()) : getDefaultCollection();
+ return requestWithRetryOnStaleState(request, true, collection);
+ }
+
+ /**
+ * As this class doesn't watch external collections on the client side,
+ * there's a chance that the request will fail due to cached stale state,
+ * which means the state must be refreshed from ZK and retried.
+ */
+ protected NamedList<Object> requestWithRetryOnStaleState(SolrRequest request, boolean retry, String collection)
+ throws SolrServerException, IOException {
+
+ connect(); // important to call this before you start working with the ZkStateReader
+
+ // build up a _stateVer_ param to pass to the server containing all of the
+ // external collection state versions involved in this request, which allows
+ // the server to notify us that our cached state for one or more of the external
+ // collections is stale and needs to be refreshed ... this code has no impact on internal collections
+ String stateVerParam = null;
+ List<DocCollection> requestedExternalCollections = null;
+ if (collection != null && !request.getPath().startsWith("/admin")) { // don't do _stateVer_ checking for admin requests
+ Set<String> requestedCollectionNames = getCollectionList(getZkStateReader().getClusterState(), collection);
+ requestedExternalCollections = new ArrayList<DocCollection>(requestedCollectionNames.size());
+ StringBuilder stateVerParamBuilder = null;
+ for (String requestedCollection : requestedCollectionNames) {
+ // track the version of state we're using on the client side using the _stateVer_ param
+ DocCollection coll = getDocCollection(getZkStateReader().getClusterState(), requestedCollection);
+ int collVer = coll.getVersion();
+ if (coll.isExternal()) {
+ requestedExternalCollections.add(coll);
+
+ if (stateVerParamBuilder == null) {
+ stateVerParamBuilder = new StringBuilder();
+ } else {
+ stateVerParamBuilder.append("|"); // hopefully pipe is not an allowed char in a collection name
+ }
+
+ stateVerParamBuilder.append(coll.getName()).append(":").append(collVer);
+ }
+ }
+
+ if (stateVerParamBuilder != null) {
+ stateVerParam = stateVerParamBuilder.toString();
+ }
+ }
+
+ if (request.getParams() instanceof ModifiableSolrParams) {
+ ModifiableSolrParams params = (ModifiableSolrParams) request.getParams();
+ if (stateVerParam != null) {
+ params.set(STATE_VERSION, stateVerParam);
+ } else {
+ params.remove(STATE_VERSION);
+ }
+ } // else: ??? how to set this ???
+
+ NamedList<Object> resp = null;
+ try {
+ resp = sendRequest(request);
+ } catch (Exception exc) {
+
+ Throwable rootCause = SolrException.getRootCause(exc);
+ // don't do retry support for admin requests or if the request doesn't have a collection specified
+ if (collection == null || request.getPath().startsWith("/admin")) {
+ if (exc instanceof SolrServerException) {
+ throw (SolrServerException)exc;
+ } else if (exc instanceof IOException) {
+ throw (IOException)exc;
+ }else if (exc instanceof RuntimeException) {
+ throw (RuntimeException) exc;
+ }
+ else {
+ throw new SolrServerException(rootCause);
+ }
+ }
+
+ int errorCode = (rootCause instanceof SolrException) ?
+ ((SolrException)rootCause).code() : SolrException.ErrorCode.UNKNOWN.code;
+
+ log.error("Request to collection {} failed due to ("+errorCode+
+ ") {}, retry? "+retry, collection, rootCause.toString());
+
+ boolean wasCommError =
+ (rootCause instanceof ConnectException ||
+ rootCause instanceof ConnectTimeoutException ||
+ rootCause instanceof NoHttpResponseException ||
+ rootCause instanceof SocketException);
+
+ boolean stateWasStale = false;
+ if (retry &&
+ !requestedExternalCollections.isEmpty() &&
+ SolrException.ErrorCode.getErrorCode(errorCode) == SolrException.ErrorCode.INVALID_STATE)
+ {
+ // cached state for one or more external collections was stale
+ // re-issue request using updated state
+ stateWasStale = true;
+
+ // just re-read state for all of them, which is a little heavy handed but hopefully a rare occurrence
+ for (DocCollection ext : requestedExternalCollections) {
+ collectionStateCache.remove(ext.getName());
+ }
+ }
+
+ // if we experienced a communication error, it's worth checking the state
+ // with ZK just to make sure the node we're trying to hit is still part of the collection
+ if (retry && !stateWasStale && !requestedExternalCollections.isEmpty() && wasCommError) {
+ for (DocCollection ext : requestedExternalCollections) {
+ DocCollection latestStateFromZk = getZkStateReader().getExternCollection(ext.getName());
+ if (latestStateFromZk.getVersion() != ext.getVersion()) {
+ // looks like we couldn't reach the server because the state was stale == retry
+ stateWasStale = true;
+ // we just pulled state from ZK, so update the cache so that the retry uses it
+ collectionStateCache.put(ext.getName(), new ExpiringCachedDocCollection(latestStateFromZk));
+ }
+ }
+ }
+
+ requestedExternalCollections.clear(); // done with this
+
+ // if the state was stale, then we retry the request once with new state pulled from Zk
+ if (stateWasStale) {
+ log.warn("Re-trying request to external collection(s) "+collection+" after stale state error from server.");
+ resp = requestWithRetryOnStaleState(request, false, collection);
+ } else {
+ if (exc instanceof SolrServerException) {
+ throw (SolrServerException)exc;
+ } else if (exc instanceof IOException) {
+ throw (IOException)exc;
+ } else {
+ throw new SolrServerException(rootCause);
+ }
+ }
+ }
+
+ return resp;
+ }
+
+ protected NamedList<Object> sendRequest(SolrRequest request)
throws SolrServerException, IOException {
connect();
@@ -556,7 +749,7 @@ public class CloudSolrServer extends SolrServer {
// add it to the Map of slices.
Map<String,Slice> slices = new HashMap<>();
for (String collectionName : collectionsList) {
- DocCollection col = clusterState.getCollection(collectionName);
+ DocCollection col = getDocCollection(clusterState, collectionName);
Collection<Slice> routeSlices = col.getRouter().getSearchSlices(shardKeys, reqParams , col);
ClientUtils.addSlices(slices, collectionName, routeSlices, true);
}
@@ -637,26 +830,31 @@ public class CloudSolrServer extends SolrServer {
return rsp.getResponse();
}
- private Set<String> getCollectionList(ClusterState clusterState,
- String collection) {
+ protected Set<String> getCollectionList(ClusterState clusterState,
+ String collection) {
// Extract each comma separated collection name and store in a List.
- List<String> rawCollectionsList = StrUtils.splitSmart(collection, ",", true);
- Set<String> collectionsList = new HashSet<>();
+ Set<String> collectionsList = new HashSet<String>();
// validate collections
- for (String collectionName : rawCollectionsList) {
- if (!clusterState.getCollections().contains(collectionName)) {
- Aliases aliases = zkStateReader.getAliases();
- String alias = aliases.getCollectionAlias(collectionName);
- if (alias != null) {
- List<String> aliasList = StrUtils.splitSmart(alias, ",", true);
- collectionsList.addAll(aliasList);
- continue;
+ List<String> rawCollectionsList = (collection != null) ? StrUtils.splitSmart(collection, ",", true) : null;
+ if (rawCollectionsList != null) {
+ for (String collectionName : rawCollectionsList) {
+ if (!clusterState.hasCollection(collectionName)) {
+ Aliases aliases = zkStateReader.getAliases();
+ String alias = aliases.getCollectionAlias(collectionName);
+ if (alias != null) {
+ List<String> aliasList = StrUtils.splitSmart(alias, ",", true);
+ collectionsList.addAll(aliasList);
+ continue;
+ }
+
+ DocCollection docCollection = getDocCollection(clusterState, collection);
+ if (docCollection == null) {
+ throw new SolrException(ErrorCode.BAD_REQUEST, "Collection not found: " + collectionName);
+ }
}
-
- throw new SolrException(ErrorCode.BAD_REQUEST, "Collection not found: " + collectionName);
+
+ collectionsList.add(collectionName);
}
-
- collectionsList.add(collectionName);
}
return collectionsList;
}
@@ -692,4 +890,26 @@ public class CloudSolrServer extends SolrServer {
return updatesToLeaders;
}
+ protected DocCollection getDocCollection(ClusterState clusterState, String collection) throws SolrException {
+ ExpiringCachedDocCollection cachedState = collectionStateCache != null ? collectionStateCache.get(collection) : null;
+ if (cachedState != null && cachedState.cached != null) {
+ return cachedState.cached;
+ }
+
+ DocCollection col = clusterState.getCollectionOrNull(collection);
+ if(col == null ) return null;
+ collectionStateCache.put(collection, new ExpiringCachedDocCollection(col));
+ return col;
+ }
+
+ /**
+ * Extension point to allow sub-classes to override the ZkStateReader this class uses internally.
+ */
+ protected ZkStateReader createZkStateReader(String zkHost, int zkClientTimeout, int zkConnectTimeout)
+ throws InterruptedException, TimeoutException, IOException, KeeperException {
+ ZkStateReader zk = new ZkStateReader(zkHost, zkClientTimeout, zkConnectTimeout);
+ zk.createClusterStateWatchersAndUpdate();
+ return zk;
+ }
+
}
diff --git a/solr/solrj/src/java/org/apache/solr/common/SolrException.java b/solr/solrj/src/java/org/apache/solr/common/SolrException.java
index 3cd03e5d71d..f0723e28464 100644
--- a/solr/solrj/src/java/org/apache/solr/common/SolrException.java
+++ b/solr/solrj/src/java/org/apache/solr/common/SolrException.java
@@ -45,6 +45,7 @@ public class SolrException extends RuntimeException {
UNSUPPORTED_MEDIA_TYPE( 415 ),
SERVER_ERROR( 500 ),
SERVICE_UNAVAILABLE( 503 ),
+ INVALID_STATE( 510 ),
UNKNOWN(0);
public final int code;
diff --git a/solr/solrj/src/java/org/apache/solr/common/cloud/ClusterState.java b/solr/solrj/src/java/org/apache/solr/common/cloud/ClusterState.java
index 237cfda379b..2a7b4c9bed3 100644
--- a/solr/solrj/src/java/org/apache/solr/common/cloud/ClusterState.java
+++ b/solr/solrj/src/java/org/apache/solr/common/cloud/ClusterState.java
@@ -54,6 +54,7 @@ public class ClusterState implements JSONWriter.Writable {
*
* hashCode and equals will only depend on liveNodes and not clusterStateVersion.
*/
+ @Deprecated
public ClusterState(Set<String> liveNodes,
Map<String, DocCollection> collectionStates) {
this(null, liveNodes, collectionStates, null);
@@ -73,6 +74,7 @@ public class ClusterState implements JSONWriter.Writable {
*/
public ClusterState(Integer zkClusterStateVersion, Set<String> liveNodes,
Map<String, DocCollection> collectionStates, ZkStateReader stateReader) {
+ assert stateReader != null;
this.zkClusterStateVersion = zkClusterStateVersion;
this.liveNodes = new HashSet<>(liveNodes.size());
this.liveNodes.addAll(liveNodes);
@@ -100,32 +102,16 @@ public class ClusterState implements JSONWriter.Writable {
* Get the lead replica for specific collection, or null if one currently doesn't exist.
*/
public Replica getLeader(String collection, String sliceName) {
- DocCollection coll = collectionStates.get(collection);
+ DocCollection coll = getCollectionOrNull(collection);
if (coll == null) return null;
Slice slice = coll.getSlice(sliceName);
if (slice == null) return null;
return slice.getLeader();
}
-
- /**
- * Gets the replica by the core name (assuming the slice is unknown) or null if replica is not found.
- * If the slice is known, do not use this method.
- * coreNodeName is the same as replicaName
- */
- public Replica getReplica(final String collection, final String coreNodeName) {
- return getReplica(collectionStates.get(collection), coreNodeName);
- }
- private Replica getReplica(DocCollection coll, String replicaName) {
- if (coll == null) return null;
- for(Slice slice: coll.getSlices()) {
- Replica replica = slice.getReplica(replicaName);
- if (replica != null) return replica;
- }
- return null;
- }
- public boolean hasCollection(String coll){
- return collectionStates.get(coll)!=null;
+ public boolean hasCollection(String coll) {
+ if (collectionStates.containsKey(coll)) return true;
+ return stateReader.getAllCollections().contains(coll);
}
@@ -133,58 +119,94 @@ public class ClusterState implements JSONWriter.Writable {
* Get the named Slice for collection, or null if not found.
*/
public Slice getSlice(String collection, String sliceName) {
- DocCollection coll = collectionStates.get(collection);
+ DocCollection coll = getCollectionOrNull(collection);
if (coll == null) return null;
return coll.getSlice(sliceName);
}
public Map<String, Slice> getSlicesMap(String collection) {
- DocCollection coll = collectionStates.get(collection);
+ DocCollection coll = getCollectionOrNull(collection);
if (coll == null) return null;
return coll.getSlicesMap();
}
public Map<String, Slice> getActiveSlicesMap(String collection) {
- DocCollection coll = collectionStates.get(collection);
+ DocCollection coll = getCollectionOrNull(collection);
if (coll == null) return null;
return coll.getActiveSlicesMap();
}
public Collection<Slice> getSlices(String collection) {
- DocCollection coll = collectionStates.get(collection);
+ DocCollection coll = getCollectionOrNull(collection);
if (coll == null) return null;
return coll.getSlices();
}
public Collection<Slice> getActiveSlices(String collection) {
- DocCollection coll = collectionStates.get(collection);
+ DocCollection coll = getCollectionOrNull(collection);
if (coll == null) return null;
return coll.getActiveSlices();
}
- public DocCollection getCollectionOrNull(String collection) {
- return collectionStates.get(collection);
+ /**
+ * Get the {@code DocCollection} object if available. This method will
+ * never hit ZooKeeper and attempt to fetch collection from locally available
+ * state only.
+ *
+ * @param collection the name of the collection
+ * @return the {@link org.apache.solr.common.cloud.DocCollection} or null if not found
+ */
+ public DocCollection getCachedCollection(String collection) {
+ DocCollection c = collectionStates.get(collection);
+ if (c != null) return c;
+ if (!stateReader.getAllCollections().contains(collection)) return null;
+ return stateReader.getExternCollection(collection, true); // return from cache
+ }
+ /**
+ * Gets the replica from caches by the core name (assuming the slice is unknown) or null if replica is not found.
+ * If the slice is known, do not use this method.
+ * coreNodeName is the same as replicaName
+ */
+ public Replica getCachedReplica(String collectionName, String coreNodeName) {
+ DocCollection c = getCachedCollection(collectionName);
+ if (c == null) return null;
+ for (Slice slice : c.getSlices()) {
+ Replica replica = slice.getReplica(coreNodeName);
+ if (replica != null) return replica;
+ }
+ return null;
}
+
/**
* Get the named DocCollection object, or throw an exception if it doesn't exist.
*/
public DocCollection getCollection(String collection) {
- DocCollection coll = collectionStates.get(collection);
- if (coll == null) {
- throw new SolrException(ErrorCode.BAD_REQUEST, "Could not find collection:" + collection);
- }
+ DocCollection coll = getCollectionOrNull(collection);
+ if (coll == null) throw new SolrException(ErrorCode.BAD_REQUEST, "Could not find collection : " + collection);
return coll;
}
+ private DocCollection loadExtDocCollection(String coll) {
+ return stateReader.getExternCollection(coll);
+ }
+
+ public DocCollection getCollectionOrNull(String coll) {
+ DocCollection c = collectionStates.get(coll);
+ if (c != null) return c;
+ if (!stateReader.getAllCollections().contains(coll)) return null;
+ return loadExtDocCollection(coll);
+ }
+
/**
* Get collection names.
*/
public Set<String> getCollections() {
- return Collections.unmodifiableSet(collectionStates.keySet());
+ return stateReader.getAllCollections();
}
/**
+ * @deprecated use #getAllCollections instead
* @return Map&lt;collectionName, Map&lt;sliceName,Slice&gt;&gt;
*/
@Deprecated
@@ -200,8 +222,18 @@ public class ClusterState implements JSONWriter.Writable {
}
public String getShardId(String nodeName, String coreName) {
- // System.out.println("###### getShardId(" + baseUrl + "," + coreName + ") in " + collectionStates);
- for (DocCollection coll : collectionStates.values()) {
+ return getShardId(null, nodeName, coreName);
+ }
+
+
+ public String getShardId(String collectionName, String nodeName, String coreName) {
+ Collection<DocCollection> states = collectionStates.values();
+ if (collectionName != null) {
+ DocCollection c = getCollectionOrNull(collectionName);
+ if (c != null) states = Collections.singletonList(c);
+ }
+
+ for (DocCollection coll : states) {
for (Slice slice : coll.getSlices()) {
for (Replica replica : slice.getReplicas()) {
// TODO: for really large clusters, we could 'index' on this
@@ -261,12 +293,20 @@ public class ClusterState implements JSONWriter.Writable {
Map<String,DocCollection> collections = new LinkedHashMap<>(stateMap.size());
for (Entry<String, Object> entry : stateMap.entrySet()) {
String collectionName = entry.getKey();
- DocCollection coll = collectionFromObjects(collectionName, (Map<String,Object>)entry.getValue());
+ DocCollection coll = collectionFromObjects(collectionName, (Map<String,Object>)entry.getValue(), version);
collections.put(collectionName, coll);
}
// System.out.println("######## ClusterState.load result:" + collections);
- return new ClusterState(version, liveNodes, collections);
+ return new ClusterState( version, liveNodes, collections,stateReader);
+ }
+
+ /**
+ * @deprecated
+ */
+ @Deprecated
+ public static ClusterState load(Integer version, byte[] bytes, Set<String> liveNodes){
+ return load(version == null ? -1: version, bytes, liveNodes,null);
}
public static Aliases load(byte[] bytes) {
@@ -278,7 +318,7 @@ public class ClusterState implements JSONWriter.Writable {
return new Aliases(aliasMap);
}
- private static DocCollection collectionFromObjects(String name, Map<String,Object> objs) {
+ private static DocCollection collectionFromObjects(String name, Map<String, Object> objs, Integer version) {
Map<String,Object> props;
Map<String,Slice> slices;
@@ -305,7 +345,7 @@ public class ClusterState implements JSONWriter.Writable {
router = DocRouter.getDocRouter(routerProps.get("name"));
}
- return new DocCollection(name, slices, props, router);
+ return new DocCollection(name, slices, props, router, version);
}
private static Map<String,Slice> makeSlices(Map<String,Object> genericSlices) {
@@ -362,6 +402,19 @@ public class ClusterState implements JSONWriter.Writable {
return true;
}
+
+ public boolean hasExternalCollection(String coll) {
+ return stateReader.getAllCollections().contains(coll) && !collectionStates.containsKey(coll);
+
+ }
+ public Set<String> getAllInternalCollections(){
+ return Collections.unmodifiableSet(collectionStates.keySet());
+ }
+
+ public ZkStateReader getStateReader(){
+ return stateReader;
+ }
+
/**
* Internal API used only by ZkStateReader
*/
@@ -369,4 +422,9 @@ public class ClusterState implements JSONWriter.Writable {
this.liveNodes = liveNodes;
}
+ public DocCollection getCommonCollection(String name){
+ return collectionStates.get(name);
+
+ }
+
}
diff --git a/solr/solrj/src/java/org/apache/solr/common/cloud/DocCollection.java b/solr/solrj/src/java/org/apache/solr/common/cloud/DocCollection.java
index 5755d717875..f273464979c 100644
--- a/solr/solrj/src/java/org/apache/solr/common/cloud/DocCollection.java
+++ b/solr/solrj/src/java/org/apache/solr/common/cloud/DocCollection.java
@@ -33,19 +33,27 @@ import java.util.Map;
public class DocCollection extends ZkNodeProps {
public static final String DOC_ROUTER = "router";
public static final String SHARDS = "shards";
+ public static final String STATE_FORMAT = "stateFormat";
+ private int version;
private final String name;
private final Map<String, Slice> slices;
private final Map<String, Slice> activeSlices;
private final DocRouter router;
+ private final boolean external;
+
+ public DocCollection(String name, Map<String, Slice> slices, Map<String, Object> props, DocRouter router) {
+ this(name, slices, props, router, -1);
+ }
/**
* @param name The name of the collection
* @param slices The logical shards of the collection. This is used directly and a copy is not made.
* @param props The properties of the slice. This is used directly and a copy is not made.
*/
- public DocCollection(String name, Map<String, Slice> slices, Map<String, Object> props, DocRouter router) {
- super( props==null ? props = new HashMap<>() : props);
+ public DocCollection(String name, Map<String, Slice> slices, Map<String, Object> props, DocRouter router, int zkVersion) {
+ super( props==null ? props = new HashMap<String,Object>() : props);
+ this.version = zkVersion;
this.name = name;
this.slices = slices;
@@ -59,6 +67,7 @@ public class DocCollection extends ZkNodeProps {
this.activeSlices.put(slice.getKey(), slice.getValue());
}
this.router = router;
+ external = getInt(STATE_FORMAT,1)>1;
assert name != null && slices != null;
}
@@ -104,6 +113,16 @@ public class DocCollection extends ZkNodeProps {
return activeSlices;
}
+ public int getVersion(){
+ return version;
+
+ }
+
+ public boolean isExternal(){
+ return external;
+ }
+
+
public DocRouter getRouter() {
return router;
}
diff --git a/solr/solrj/src/java/org/apache/solr/common/cloud/ZkStateReader.java b/solr/solrj/src/java/org/apache/solr/common/cloud/ZkStateReader.java
index d2c0175513e..5fcf56d417b 100644
--- a/solr/solrj/src/java/org/apache/solr/common/cloud/ZkStateReader.java
+++ b/solr/solrj/src/java/org/apache/solr/common/cloud/ZkStateReader.java
@@ -10,7 +10,7 @@ package org.apache.solr.common.cloud;
*
* http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
+ * Unless required byOCP 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
@@ -37,12 +37,14 @@ import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.Arrays;
+import java.util.Collections;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
+import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ThreadFactory;
@@ -96,7 +98,10 @@ public class ZkStateReader {
public static final String LEADER_ELECT_ZKNODE = "/leader_elect";
public static final String SHARD_LEADERS_ZKNODE = "leaders";
+ private final Set<String> watchedCollections = new HashSet<String>();
+ private Map<String , DocCollection> externalWatchedCollections = new ConcurrentHashMap<String, DocCollection>();
+ private Set<String> allCollections = Collections.emptySet();
@@ -131,7 +136,7 @@ public class ZkStateReader {
/**
* Returns config set name for collection.
- *
+ *
* @param collection to return config set name for
*/
public String readConfigName(String collection) {
@@ -248,6 +253,23 @@ public class ZkStateReader {
public Aliases getAliases() {
return aliases;
}
+
+ public Boolean checkValid(String coll, int version){
+ DocCollection collection = clusterState.getCollectionOrNull(coll);
+ if(collection ==null) return null;
+ if(collection.getVersion() < version){
+ log.info("server older than client {}<{}",collection.getVersion(),version);
+ DocCollection nu = getExternCollectionFresh(this, coll);
+ if(nu.getVersion()> collection.getVersion()){
+ updateExternCollection(nu);
+ collection = nu;
+ }
+ }
+ if(collection.getVersion() == version) return Boolean.TRUE;
+ log.info("wrong version from client {}!={} ",version, collection.getVersion());
+ return Boolean.FALSE;
+
+ }
public synchronized void createClusterStateWatchersAndUpdate() throws KeeperException,
InterruptedException {
@@ -283,6 +305,12 @@ public class ZkStateReader {
ClusterState clusterState = ClusterState.load(stat.getVersion(), data, ln,ZkStateReader.this);
// update volatile
ZkStateReader.this.clusterState = clusterState;
+
+ updateCollectionNames();
+// HashSet<String> all = new HashSet<>(colls);;
+// all.addAll(clusterState.getAllInternalCollections());
+// all.remove(null);
+
}
} catch (KeeperException e) {
if (e.code() == KeeperException.Code.SESSIONEXPIRED
@@ -322,14 +350,13 @@ public class ZkStateReader {
synchronized (ZkStateReader.this.getUpdateLock()) {
List<String> liveNodes = zkClient.getChildren(
LIVE_NODES_ZKNODE, this, true);
- log.info("Updating live nodes... ({})", liveNodes.size());
+ log.debug("Updating live nodes... ({})", liveNodes.size());
Set<String> liveNodesSet = new HashSet<>();
liveNodesSet.addAll(liveNodes);
- ClusterState clusterState = new ClusterState(
- ZkStateReader.this.clusterState.getZkClusterStateVersion(),
- liveNodesSet, ZkStateReader.this.clusterState
- .getCollectionStates());
- ZkStateReader.this.clusterState = clusterState;
+
+ ClusterState clusterState = ZkStateReader.this.clusterState;
+
+ clusterState.setLiveNodes(liveNodesSet);
}
} catch (KeeperException e) {
if (e.code() == KeeperException.Code.SESSIONEXPIRED
@@ -354,6 +381,7 @@ public class ZkStateReader {
liveNodeSet.addAll(liveNodes);
ClusterState clusterState = ClusterState.load(zkClient, liveNodeSet, ZkStateReader.this);
this.clusterState = clusterState;
+ updateCollectionNames();
zkClient.exists(ALIASES,
new Watcher() {
@@ -399,9 +427,43 @@ public class ZkStateReader {
}, true);
}
updateAliases();
+ //on reconnect of SolrZkClient re-add watchers for the watched external collections
+ synchronized (this){
+ for (String watchedCollection : watchedCollections) {
+ addZkWatch(watchedCollection);
+ }
+ }
}
-
-
+
+ public void updateCollectionNames() throws KeeperException, InterruptedException {
+ Set<String> colls = getExternColls();
+ colls.addAll(clusterState.getAllInternalCollections());
+ allCollections = Collections.unmodifiableSet(colls);
+ }
+
+ private Set<String> getExternColls() throws KeeperException, InterruptedException {
+ List<String> children = null;
+ try {
+ children = zkClient.getChildren(COLLECTIONS_ZKNODE, null, true);
+ } catch (KeeperException.NoNodeException e) {
+ log.warn("Error fetching collection names");
+
+ return new HashSet<>();
+ }
+ if(children == null || children.isEmpty()) return new HashSet<>();
+ HashSet<String> result = new HashSet<>(children.size());
+
+ for (String c : children) {
+ try {
+ if(zkClient.exists(getCollectionPath(c),true)) result.add(c);
+ } catch (Exception e) {
+ log.warn("Error checking external collections", e);
+ }
+ }
+ return result;
+ }
+
+
// load and publish a new CollectionInfo
private synchronized void updateClusterState(boolean immediate,
final boolean onlyLiveNodes) throws KeeperException,
@@ -424,11 +486,9 @@ public class ZkStateReader {
log.info("Updating live nodes from ZooKeeper... ({})", liveNodesSet.size());
clusterState = this.clusterState;
clusterState.setLiveNodes(liveNodesSet);
- /*clusterState = new ClusterState(
- ZkStateReader.this.clusterState.getZkClusterStateVersion(), liveNodesSet,
- ZkStateReader.this.clusterState.getCollectionStates());*/
}
this.clusterState = clusterState;
+ updateCollectionNames();
}
} else {
@@ -458,7 +518,9 @@ public class ZkStateReader {
clusterState = ClusterState.load(zkClient, liveNodesSet,ZkStateReader.this);
} else {
log.info("Updating live nodes from ZooKeeper... ");
- clusterState = new ClusterState(ZkStateReader.this.clusterState.getZkClusterStateVersion(), liveNodesSet, ZkStateReader.this.clusterState.getCollectionStates());
+ clusterState = ZkStateReader.this.clusterState;
+ clusterState.setLiveNodes(liveNodesSet);
+
}
ZkStateReader.this.clusterState = clusterState;
@@ -485,7 +547,11 @@ public class ZkStateReader {
}
}, SOLRCLOUD_UPDATE_DELAY, TimeUnit.MILLISECONDS);
}
-
+ synchronized (this) {
+ for (String watchedCollection : watchedCollections) {
+ externalWatchedCollections.put(watchedCollection, getExternCollectionFresh(this, watchedCollection));
+ }
+ }
}
/**
@@ -611,7 +677,7 @@ public class ZkStateReader {
return zkClient;
}
public Set<String> getAllCollections(){
- return clusterState.getCollections();
+ return allCollections;
}
public void updateAliases() throws KeeperException, InterruptedException {
@@ -658,5 +724,157 @@ public class ZkStateReader {
throw new IllegalStateException("JVM Does not seem to support UTF-8", e);
}
}
-
+
+ public void updateExternCollection(DocCollection c) {
+ if(watchedCollections.contains(c.getName())){
+ externalWatchedCollections.put(c.getName(), c);
+ log.info("Updated DocCollection "+c.getName()+" to: ");
+ }
+ }
+
+ /**
+ * <b>Advance usage</b>
+ * This method can be used to fetch a collection object and control whether it hits
+ * the cache only or if information can be looked up from ZooKeeper.
+ *
+ * @param coll the collection name
+ * @param cachedCopyOnly whether to fetch data from cache only or if hitting Zookeeper is acceptable
+ * @return the {@link org.apache.solr.common.cloud.DocCollection}
+ */
+ public DocCollection getExternCollection(String coll, boolean cachedCopyOnly) {
+ if (watchedCollections.contains(coll) || cachedCopyOnly) {
+ DocCollection c = externalWatchedCollections.get(coll);
+ if (c != null || cachedCopyOnly) return c;
+ }
+
+ return getExternCollectionFresh(this, coll);
+ }
+ // this is only set by Overseer not to be set by others. If Overseer has
+ // unfinished external collections which are yet to be persisted to ZK
+ // this map is populated and this class can use that information
+ public Map ephemeralCollectionData;
+
+ public static DocCollection getExternCollectionFresh(ZkStateReader zkStateReader, String coll) {
+ String collectionPath = getCollectionPath(coll);
+ if(zkStateReader.ephemeralCollectionData !=null ){
+ ClusterState cs = (ClusterState) zkStateReader.ephemeralCollectionData.get(collectionPath);
+ if(cs !=null) {
+ return cs.getCommonCollection(coll);
+ }
+ }
+ try {
+ if (!zkStateReader.getZkClient().exists(collectionPath, true)) return null;
+ Stat stat = new Stat();
+ byte[] data = zkStateReader.getZkClient().getData(collectionPath, null, stat, true);
+ ClusterState state = ClusterState.load(stat.getVersion(), data, Collections.<String>emptySet(), zkStateReader);
+ return state.getCommonCollection(coll);
+ } catch (KeeperException.NoNodeException e) {
+ log.warn("No node available : " + collectionPath, e);
+ return null;
+ } catch (KeeperException e) {
+ throw new SolrException(ErrorCode.BAD_REQUEST, "Could not load collection from ZK:" + coll, e);
+ } catch (InterruptedException e) {
+ throw new SolrException(ErrorCode.BAD_REQUEST, "Could not load collection from ZK:" + coll, e);
+ }
+ }
+
+ public DocCollection getExternCollection(String coll) {
+ return getExternCollection(coll, false);
+ }
+
+ public static String getCollectionPath(String coll) {
+ return COLLECTIONS_ZKNODE+"/"+coll + "/state";
+ }
+
+ public void addCollectionWatch(String coll) throws KeeperException, InterruptedException {
+ synchronized (this){
+ if(watchedCollections.contains(coll)) return;
+ else {
+ watchedCollections.add(coll);
+ }
+ addZkWatch(coll);
+ }
+
+ }
+
+ private void addZkWatch(final String coll) throws KeeperException, InterruptedException {
+ log.info("addZkWatch {}", coll);
+ final String fullpath = getCollectionPath(coll);
+ synchronized (getUpdateLock()){
+
+ cmdExecutor.ensureExists(fullpath, zkClient);
+ log.info("Updating collection state at {} from ZooKeeper... ",fullpath);
+
+ Watcher watcher = new Watcher() {
+
+ @Override
+ public void process(WatchedEvent event) {
+ // session events are not change events,
+ // and do not remove the watcher
+ if (EventType.None.equals(event.getType())) {
+ return;
+ }
+ log.info("A cluster state change: {}, has occurred - updating... ", (event), ZkStateReader.this.clusterState == null ? 0 : ZkStateReader.this.clusterState.getLiveNodes().size());
+ try {
+
+ // delayed approach
+ // ZkStateReader.this.updateClusterState(false, false);
+ synchronized (ZkStateReader.this.getUpdateLock()) {
+ if(!watchedCollections.contains(coll)) {
+ log.info("Unwatched collection {}",coll);
+ return;
+ }
+ // remake watch
+ final Watcher thisWatch = this;
+ Stat stat = new Stat();
+ byte[] data = zkClient.getData(fullpath, thisWatch, stat, true);
+ if(data == null || data.length ==0){
+ log.warn("No value set for collection state : {}", coll);
+ return;
+
+ }
+ ClusterState clusterState = ClusterState.load(stat.getVersion(), data, Collections.<String>emptySet(),ZkStateReader.this);
+ // update volatile
+
+ externalWatchedCollections.put(coll,clusterState.getCommonCollection(coll));
+ log.info("Updating data for {} ", coll);
+
+ }
+ } catch (KeeperException e) {
+ if (e.code() == KeeperException.Code.SESSIONEXPIRED
+ || e.code() == KeeperException.Code.CONNECTIONLOSS) {
+ log.warn("ZooKeeper watch triggered, but Solr cannot talk to ZK");
+ return;
+ }
+ log.error("Unwatched collection :"+coll , e);
+ throw new ZooKeeperException(ErrorCode.SERVER_ERROR,
+ "", e);
+
+ } catch (InterruptedException e) {
+ // Restore the interrupted status
+ Thread.currentThread().interrupt();
+ log.error("Unwatched collection :"+coll , e);
+ return;
+ }
+ }
+
+ };
+ zkClient.exists(fullpath, watcher, true);
+ }
+
+ externalWatchedCollections.put(coll, getExternCollectionFresh(this, coll));
+ }
+
+ /**This is not a public API. Only used by ZkController
+ * @param coll
+ */
+ public void removeZKWatch(final String coll){
+ synchronized (this){
+ watchedCollections.remove(coll);
+ }
+ }
+
+
+
+
}
diff --git a/solr/solrj/src/test/org/apache/solr/client/solrj/impl/CloudSolrServerTest.java b/solr/solrj/src/test/org/apache/solr/client/solrj/impl/CloudSolrServerTest.java
index 3e45fa06ace..6524b491de4 100644
--- a/solr/solrj/src/test/org/apache/solr/client/solrj/impl/CloudSolrServerTest.java
+++ b/solr/solrj/src/test/org/apache/solr/client/solrj/impl/CloudSolrServerTest.java
@@ -20,7 +20,9 @@ package org.apache.solr.client.solrj.impl;
import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
+import java.util.ArrayList;
import java.util.Collection;
+import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
@@ -32,6 +34,7 @@ import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import org.apache.lucene.util.LuceneTestCase.Slow;
+import org.apache.solr.client.solrj.SolrQuery;
import org.apache.solr.client.solrj.SolrServerException;
import org.apache.solr.client.solrj.request.AbstractUpdateRequest;
import org.apache.solr.client.solrj.request.QueryRequest;
@@ -39,6 +42,7 @@ import org.apache.solr.client.solrj.request.UpdateRequest;
import org.apache.solr.client.solrj.response.QueryResponse;
import org.apache.solr.cloud.AbstractFullDistribZkTestBase;
import org.apache.solr.cloud.AbstractZkTestCase;
+import org.apache.solr.cloud.Overseer;
import org.apache.solr.common.SolrDocumentList;
import org.apache.solr.common.SolrException;
import org.apache.solr.common.SolrInputDocument;
@@ -47,6 +51,7 @@ import org.apache.solr.common.cloud.DocCollection;
import org.apache.solr.common.cloud.DocRouter;
import org.apache.solr.common.cloud.Replica;
import org.apache.solr.common.cloud.Slice;
+import org.apache.solr.common.cloud.SolrZkClient;
import org.apache.solr.common.cloud.ZkStateReader;
import org.apache.solr.common.params.CommonParams;
import org.apache.solr.common.params.ModifiableSolrParams;
@@ -56,6 +61,9 @@ import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
+import org.junit.Test;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
/**
@@ -63,7 +71,8 @@ import org.junit.BeforeClass;
*/
@Slow
public class CloudSolrServerTest extends AbstractFullDistribZkTestBase {
-
+ static Logger log = LoggerFactory.getLogger(CloudSolrServerTest.class);
+
private static final String SOLR_HOME = getFile("solrj" + File.separator + "solr").getAbsolutePath();
@BeforeClass
@@ -111,9 +120,20 @@ public class CloudSolrServerTest extends AbstractFullDistribZkTestBase {
sliceCount = 2;
shardCount = 3;
}
-
+
@Override
public void doTest() throws Exception {
+ allTests();
+ testStateVersionParam();
+ }
+
+ private void allTests() throws Exception {
+
+ String collectionName = "clientTestExternColl";
+ createCollection(collectionName, controlClientCloud, 2, 2);
+ waitForRecoveriesToFinish(collectionName, false);
+ CloudSolrServer cloudClient = createCloudClient(collectionName);
+
assertNotNull(cloudClient);
handle.clear();
@@ -122,10 +142,13 @@ public class CloudSolrServerTest extends AbstractFullDistribZkTestBase {
waitForThingsToLevelOut(30);
- del("*:*");
+ controlClient.deleteByQuery("*:*");
+ cloudClient.deleteByQuery("*:*");
+
+
+ controlClient.commit();
+ this.cloudClient.commit();
- commit();
-
SolrInputDocument doc1 = new SolrInputDocument();
doc1.addField(id, "0");
doc1.addField("a_t", "hello1");
@@ -181,7 +204,7 @@ public class CloudSolrServerTest extends AbstractFullDistribZkTestBase {
try {
threadedClient = new CloudSolrServer(zkServer.getZkAddress());
threadedClient.setParallelUpdates(true);
- threadedClient.setDefaultCollection("collection1");
+ threadedClient.setDefaultCollection(collectionName);
response = threadedClient.request(request);
rr = (CloudSolrServer.RouteResponse) response;
routes = rr.getRoutes();
@@ -211,12 +234,12 @@ public class CloudSolrServerTest extends AbstractFullDistribZkTestBase {
// Track request counts on each node before query calls
ClusterState clusterState = cloudClient.getZkStateReader().getClusterState();
- DocCollection col = clusterState.getCollection(DEFAULT_COLLECTION);
+ DocCollection col = clusterState.getCollection(collectionName);
Map<String, Long> requestCountsMap = Maps.newHashMap();
for (Slice slice : col.getSlices()) {
for (Replica replica : slice.getReplicas()) {
String baseURL = (String) replica.get(ZkStateReader.BASE_URL_PROP);
- requestCountsMap.put(baseURL, getNumRequests(new HttpSolrServer(baseURL)));
+ requestCountsMap.put(baseURL, getNumRequests(baseURL,collectionName));
}
}
@@ -248,6 +271,7 @@ public class CloudSolrServerTest extends AbstractFullDistribZkTestBase {
for (int i = 1; i < n; i++) {
String shardKey = Integer.toString(i);
Collection<Slice> slices = router.getSearchSlicesSingle(shardKey, null, col);
+ log.info("Expected Slices {}", slices);
if (expectedSlices.equals(slices)) {
sameShardRoutes.add(shardKey);
}
@@ -260,7 +284,7 @@ public class CloudSolrServerTest extends AbstractFullDistribZkTestBase {
ModifiableSolrParams solrParams = new ModifiableSolrParams();
solrParams.set(CommonParams.Q, "*:*");
solrParams.set(ShardParams._ROUTE_, sameShardRoutes.get(random().nextInt(sameShardRoutes.size())));
- cloudClient.query(solrParams);
+ log.info("output : {}" ,cloudClient.query(solrParams));
}
// Request counts increase from expected nodes should aggregate to 1000, while there should be
@@ -273,7 +297,7 @@ public class CloudSolrServerTest extends AbstractFullDistribZkTestBase {
String baseURL = (String) replica.get(ZkStateReader.BASE_URL_PROP);
Long prevNumRequests = requestCountsMap.get(baseURL);
- Long curNumRequests = getNumRequests(new HttpSolrServer(baseURL));
+ Long curNumRequests = getNumRequests(baseURL, collectionName);
long delta = curNumRequests - prevNumRequests;
if (expectedBaseURLs.contains(baseURL)) {
@@ -289,13 +313,17 @@ public class CloudSolrServerTest extends AbstractFullDistribZkTestBase {
assertEquals("Unexpected number of requests to unexpected URLs: " + numRequestsToUnexpectedUrls,
0, increaseFromUnexpectedUrls);
- del("*:*");
- commit();
+ controlClient.deleteByQuery("*:*");
+ cloudClient.deleteByQuery("*:*");
+
+ controlClient.commit();
+ cloudClient.commit();
+ cloudClient.shutdown();
}
- private Long getNumRequests(HttpSolrServer solrServer) throws
+ private Long getNumRequests(String baseUrl, String collectionName) throws
SolrServerException, IOException {
- HttpSolrServer server = new HttpSolrServer(solrServer.getBaseURL());
+ HttpSolrServer server = new HttpSolrServer(baseUrl + "/"+ collectionName);
server.setConnectionTimeout(15000);
server.setSoTimeout(60000);
ModifiableSolrParams params = new ModifiableSolrParams();
@@ -318,6 +346,81 @@ public class CloudSolrServerTest extends AbstractFullDistribZkTestBase {
SolrInputDocument doc = getDoc(fields);
indexDoc(doc);
}
+ private void testStateVersionParam() throws Exception {
+ CloudSolrServer client = createCloudClient(null);
+ String collectionName = "checkStateVerCol";
+ createCollection(collectionName, client, 2, 2);
+ waitForRecoveriesToFinish(collectionName, false);
+
+ SolrZkClient zk = client.getZkStateReader().getZkClient();
+
+
+ DocCollection coll = client.getZkStateReader().getClusterState().getCollection(collectionName);
+
+ Replica r = coll.getSlices().iterator().next().getReplicas().iterator().next();
+
+
+ HttpSolrServer httpSolrServer = new HttpSolrServer(r.getStr(ZkStateReader.BASE_URL_PROP) + "/"+collectionName);
+
+
+ SolrQuery q = new SolrQuery().setQuery("*:*");
+
+ log.info("should work query, result {}", httpSolrServer.query(q));
+ //no problem
+ q.setParam(CloudSolrServer.STATE_VERSION, collectionName+":"+coll.getVersion());
+ log.info("2nd query , result {}", httpSolrServer.query(q));
+ //no error yet good
+
+ q.setParam(CloudSolrServer.STATE_VERSION, collectionName+":"+ (coll.getVersion() -1)); //an older version expect error
+
+ HttpSolrServer.RemoteSolrException sse = null;
+ try {
+ httpSolrServer.query(q);
+ log.info("expected query error");
+ } catch (HttpSolrServer.RemoteSolrException e) {
+ sse = e;
+ }
+ assertNotNull(sse);
+ assertEquals(" Error code should be ", sse.code() , SolrException.ErrorCode.INVALID_STATE.code);
+
+ //now send the request to another node that does n ot serve the collection
+
+ Set<String> allNodesOfColl = new HashSet<>();
+ for (Slice slice : coll.getSlices()) {
+ for (Replica replica : slice.getReplicas()) {
+ allNodesOfColl.add(replica.getStr(ZkStateReader.BASE_URL_PROP));
+ }
+ }
+
+ String theNode = null;
+
+ for (String s : client.getZkStateReader().getClusterState().getLiveNodes()) {
+ String n = client.getZkStateReader().getBaseUrlForNodeName(s);
+ if(!allNodesOfColl.contains(s)){
+ theNode = n;
+ break;
+ }
+ }
+ log.info("thenode which does not serve this collection{} ",theNode);
+ assertNotNull(theNode);
+ httpSolrServer = new HttpSolrServer(theNode + "/"+collectionName);
+
+ q.setParam(CloudSolrServer.STATE_VERSION, collectionName+":"+coll.getVersion());
+
+ try {
+ httpSolrServer.query(q);
+ log.info("error was expected");
+ } catch (HttpSolrServer.RemoteSolrException e) {
+ sse = e;
+ }
+ assertNotNull(sse);
+ assertEquals(" Error code should be ", sse.code() , SolrException.ErrorCode.INVALID_STATE.code);
+
+
+ client.shutdown();
+
+
+ }
public void testShutdown() throws MalformedURLException {
CloudSolrServer server = new CloudSolrServer("[ff01::114]:33332");
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 d15db177563..988ba6ac384 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
@@ -22,6 +22,7 @@ import static org.apache.solr.cloud.OverseerCollectionProcessor.MAX_SHARDS_PER_N
import static org.apache.solr.cloud.OverseerCollectionProcessor.NUM_SLICES;
import static org.apache.solr.cloud.OverseerCollectionProcessor.REPLICATION_FACTOR;
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;
@@ -60,6 +61,7 @@ import org.apache.solr.common.cloud.ClusterState;
import org.apache.solr.common.cloud.DocCollection;
import org.apache.solr.common.cloud.Replica;
import org.apache.solr.common.cloud.Slice;
+import org.apache.solr.common.cloud.SolrZkClient;
import org.apache.solr.common.cloud.ZkCoreNodeProps;
import org.apache.solr.common.cloud.ZkNodeProps;
import org.apache.solr.common.cloud.ZkStateReader;
@@ -312,7 +314,7 @@ public abstract class AbstractFullDistribZkTestBase extends AbstractDistribZkTes
protected void waitForCollection(ZkStateReader reader, String collection, int slices) throws Exception {
// wait until shards have started registering...
int cnt = 30;
- while (!reader.getClusterState().getCollections().contains(collection)) {
+ while (!reader.getClusterState().hasCollection(collection)) {
if (cnt == 0) {
throw new RuntimeException("timeout waiting for collection in cluster state: collection=" + collection);
}
@@ -334,7 +336,20 @@ public abstract class AbstractFullDistribZkTestBase extends AbstractDistribZkTes
protected List<JettySolrRunner> createJettys(int numJettys) throws Exception {
return createJettys(numJettys, false);
}
-
+
+ protected int defaultStateFormat = 1 + random().nextInt(2);
+
+ protected int getStateFormat() {
+ String stateFormat = System.getProperty("tests.solr.stateFormat", null);
+ if (stateFormat != null) {
+ if ("2".equals(stateFormat)) {
+ return defaultStateFormat = 2;
+ } else if ("1".equals(stateFormat)) {
+ return defaultStateFormat = 1;
+ }
+ }
+ return defaultStateFormat; // random
+ }
/**
* @param checkCreatedVsState
@@ -346,6 +361,18 @@ public abstract class AbstractFullDistribZkTestBase extends AbstractDistribZkTes
List<JettySolrRunner> jettys = new ArrayList<>();
List<SolrServer> clients = new ArrayList<>();
StringBuilder sb = new StringBuilder();
+
+ if(getStateFormat() == 2) {
+ log.info("Creating collection1 with stateFormat=2");
+ SolrZkClient zkClient = new SolrZkClient(zkServer.getZkAddress(), AbstractZkTestCase.TIMEOUT, AbstractZkTestCase.TIMEOUT);
+ Overseer.getInQueue(zkClient).offer(ZkStateReader.toJSON(ZkNodeProps.makeMap(
+ Overseer.QUEUE_OPERATION, OverseerCollectionProcessor.CREATECOLLECTION,
+ "name", DEFAULT_COLLECTION,
+ "numShards", String.valueOf(sliceCount),
+ DocCollection.STATE_FORMAT, getStateFormat())));
+ zkClient.close();
+ }
+
for (int i = 1; i <= numJettys; i++) {
if (sb.length() > 0) sb.append(',');
int cnt = this.jettyIntCntr.incrementAndGet();
@@ -354,7 +381,7 @@ public abstract class AbstractFullDistribZkTestBase extends AbstractDistribZkTes
jettyDir.mkdirs();
setupJettySolrHome(jettyDir);
- log.info("create jetty " + i);
+ log.info("create jetty " + i);
JettySolrRunner j = createJetty(jettyDir, useJettyDataDir ? getDataDir(testDir + "/jetty"
+ cnt) : null, null, "solrconfig.xml", null);
jettys.add(j);
@@ -1632,6 +1659,10 @@ public abstract class AbstractFullDistribZkTestBase extends AbstractDistribZkTes
collectionInfos.put(collectionName, list);
}
params.set("name", collectionName);
+ if (useExternalCollections()) {
+ log.info("Creating external collection: " + collectionName);
+ params.set(DocCollection.STATE_FORMAT, "2");
+ }
SolrRequest request = new QueryRequest(params);
request.setPath("/admin/collections");
@@ -1650,6 +1681,11 @@ public abstract class AbstractFullDistribZkTestBase extends AbstractDistribZkTes
return res;
}
+
+ public boolean useExternalCollections() {
+ return getStateFormat() == 2;
+ }
+
protected CollectionAdminResponse createCollection(Map<String,List<Integer>> collectionInfos,
String collectionName, int numShards, int replicationFactor, int maxShardsPerNode, SolrServer client, String createNodeSetStr) throws SolrServerException, IOException {
@@ -1841,4 +1877,41 @@ public abstract class AbstractFullDistribZkTestBase extends AbstractDistribZkTes
fail("Could not find the new collection - " + exp.code() + " : " + collectionClient.getBaseURL());
}
-}
+ protected void checkForMissingCollection(String collectionName)
+ throws Exception {
+ // check for a collection - we poll the state
+ long timeoutAt = System.currentTimeMillis() + 45000;
+ boolean found = true;
+ while (System.currentTimeMillis() < timeoutAt) {
+ getCommonCloudSolrServer().getZkStateReader().updateClusterState(true);
+ ClusterState clusterState = getCommonCloudSolrServer().getZkStateReader().getClusterState();
+// Map<String,DocCollection> collections = clusterState
+// .getCollectionStates();
+ if (! clusterState.hasCollection(collectionName)) {
+ found = false;
+ break;
+ }
+ Thread.sleep(100);
+ }
+ if (found) {
+ fail("Found collection that should be gone " + collectionName);
+ }
+ }
+
+
+ protected void createCollection(String collName,
+ CloudSolrServer client,
+ int replicationFactor ,
+ int numShards ) throws Exception {
+ int maxShardsPerNode = ((((numShards+1) * replicationFactor) / getCommonCloudSolrServer()
+ .getZkStateReader().getClusterState().getLiveNodes().size())) + 1;
+
+ Map<String, Object> props = makeMap(
+ REPLICATION_FACTOR, replicationFactor,
+ MAX_SHARDS_PER_NODE, maxShardsPerNode,
+ NUM_SLICES, numShards);
+ Map<String,List<Integer>> collectionInfos = new HashMap<String,List<Integer>>();
+ createCollection(collectionInfos, collName, props, client);
+ }
+
+}
\ No newline at end of file
diff --git a/solr/webapp/web/js/scripts/cloud.js b/solr/webapp/web/js/scripts/cloud.js
index d78cb459939..52467ec5db0 100644
--- a/solr/webapp/web/js/scripts/cloud.js
+++ b/solr/webapp/web/js/scripts/cloud.js
@@ -368,7 +368,7 @@ var prepare_graph = function( graph_element, callback )
$.ajax
(
{
- url : app.config.solr_path + '/zookeeper?wt=json&detail=true&path=%2Fclusterstate.json',
+ url : app.config.solr_path + '/zookeeper?wt=json&detail=true&path=%2Fclusterstate.json&all=true',
dataType : 'json',
context : graph_element,
beforeSend : function( xhr, settings )