You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@lucene.apache.org by no...@apache.org on 2014/04/16 10:37:27 UTC

svn commit: r1587834 [1/2] - in /lucene/dev/trunk/solr: ./ core/src/java/org/apache/solr/ core/src/java/org/apache/solr/cloud/ core/src/java/org/apache/solr/handler/admin/ core/src/java/org/apache/solr/servlet/ core/src/java/org/apache/solr/util/ core/...

Author: noble
Date: Wed Apr 16 08:37:26 2014
New Revision: 1587834

URL: http://svn.apache.org/r1587834
Log:
 SOLR-5473: Make one state.json per collection ,  SOLR-5474: Have a new mode for SolrJ to support stateFormat=2

Added:
    lucene/dev/trunk/solr/core/src/test/org/apache/solr/cloud/ExternalCollectionsTest.java   (with props)
Modified:
    lucene/dev/trunk/solr/CHANGES.txt
    lucene/dev/trunk/solr/core/src/java/org/apache/solr/SolrLogFormatter.java
    lucene/dev/trunk/solr/core/src/java/org/apache/solr/cloud/Overseer.java
    lucene/dev/trunk/solr/core/src/java/org/apache/solr/cloud/OverseerCollectionProcessor.java
    lucene/dev/trunk/solr/core/src/java/org/apache/solr/cloud/ZkController.java
    lucene/dev/trunk/solr/core/src/java/org/apache/solr/handler/admin/CollectionsHandler.java
    lucene/dev/trunk/solr/core/src/java/org/apache/solr/servlet/SolrDispatchFilter.java
    lucene/dev/trunk/solr/core/src/java/org/apache/solr/servlet/ZookeeperInfoServlet.java
    lucene/dev/trunk/solr/core/src/java/org/apache/solr/util/SolrLogLayout.java
    lucene/dev/trunk/solr/core/src/test/org/apache/solr/cloud/CollectionsAPIDistributedZkTest.java
    lucene/dev/trunk/solr/core/src/test/org/apache/solr/cloud/OverseerStatusTest.java
    lucene/dev/trunk/solr/core/src/test/org/apache/solr/cloud/TestCollectionAPI.java
    lucene/dev/trunk/solr/solrj/src/java/org/apache/solr/client/solrj/impl/CloudSolrServer.java
    lucene/dev/trunk/solr/solrj/src/java/org/apache/solr/common/SolrException.java
    lucene/dev/trunk/solr/solrj/src/java/org/apache/solr/common/cloud/ClusterState.java
    lucene/dev/trunk/solr/solrj/src/java/org/apache/solr/common/cloud/DocCollection.java
    lucene/dev/trunk/solr/solrj/src/java/org/apache/solr/common/cloud/ZkStateReader.java
    lucene/dev/trunk/solr/solrj/src/test/org/apache/solr/client/solrj/impl/CloudSolrServerTest.java
    lucene/dev/trunk/solr/test-framework/src/java/org/apache/solr/cloud/AbstractFullDistribZkTestBase.java
    lucene/dev/trunk/solr/webapp/web/js/scripts/cloud.js

Modified: lucene/dev/trunk/solr/CHANGES.txt
URL: http://svn.apache.org/viewvc/lucene/dev/trunk/solr/CHANGES.txt?rev=1587834&r1=1587833&r2=1587834&view=diff
==============================================================================
--- lucene/dev/trunk/solr/CHANGES.txt (original)
+++ lucene/dev/trunk/solr/CHANGES.txt Wed Apr 16 08:37:26 2014
@@ -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

Modified: lucene/dev/trunk/solr/core/src/java/org/apache/solr/SolrLogFormatter.java
URL: http://svn.apache.org/viewvc/lucene/dev/trunk/solr/core/src/java/org/apache/solr/SolrLogFormatter.java?rev=1587834&r1=1587833&r2=1587834&view=diff
==============================================================================
--- lucene/dev/trunk/solr/core/src/java/org/apache/solr/SolrLogFormatter.java (original)
+++ lucene/dev/trunk/solr/core/src/java/org/apache/solr/SolrLogFormatter.java Wed Apr 16 08:37:26 2014
@@ -263,7 +263,7 @@ sb.append("(group_name=").append(tg.getN
 
   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();
     }

Modified: lucene/dev/trunk/solr/core/src/java/org/apache/solr/cloud/Overseer.java
URL: http://svn.apache.org/viewvc/lucene/dev/trunk/solr/core/src/java/org/apache/solr/cloud/Overseer.java?rev=1587834&r1=1587833&r2=1587834&view=diff
==============================================================================
--- lucene/dev/trunk/solr/core/src/java/org/apache/solr/cloud/Overseer.java (original)
+++ lucene/dev/trunk/solr/core/src/java/org/apache/solr/cloud/Overseer.java Wed Apr 16 08:37:26 2014
@@ -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

Modified: lucene/dev/trunk/solr/core/src/java/org/apache/solr/cloud/OverseerCollectionProcessor.java
URL: http://svn.apache.org/viewvc/lucene/dev/trunk/solr/core/src/java/org/apache/solr/cloud/OverseerCollectionProcessor.java?rev=1587834&r1=1587833&r2=1587834&view=diff
==============================================================================
--- lucene/dev/trunk/solr/core/src/java/org/apache/solr/cloud/OverseerCollectionProcessor.java (original)
+++ lucene/dev/trunk/solr/core/src/java/org/apache/solr/cloud/OverseerCollectionProcessor.java Wed Apr 16 08:37:26 2014
@@ -144,7 +144,8 @@ public class OverseerCollectionProcessor
       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
     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
       }
     } 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
         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
    * 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
           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;
     }
   }
 

Modified: lucene/dev/trunk/solr/core/src/java/org/apache/solr/cloud/ZkController.java
URL: http://svn.apache.org/viewvc/lucene/dev/trunk/solr/core/src/java/org/apache/solr/cloud/ZkController.java?rev=1587834&r1=1587833&r2=1587834&view=diff
==============================================================================
--- lucene/dev/trunk/solr/core/src/java/org/apache/solr/cloud/ZkController.java (original)
+++ lucene/dev/trunk/solr/core/src/java/org/apache/solr/cloud/ZkController.java Wed Apr 16 08:37:26 2014
@@ -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);

Modified: lucene/dev/trunk/solr/core/src/java/org/apache/solr/handler/admin/CollectionsHandler.java
URL: http://svn.apache.org/viewvc/lucene/dev/trunk/solr/core/src/java/org/apache/solr/handler/admin/CollectionsHandler.java?rev=1587834&r1=1587833&r2=1587834&view=diff
==============================================================================
--- lucene/dev/trunk/solr/core/src/java/org/apache/solr/handler/admin/CollectionsHandler.java (original)
+++ lucene/dev/trunk/solr/core/src/java/org/apache/solr/handler/admin/CollectionsHandler.java Wed Apr 16 08:37:26 2014
@@ -58,6 +58,7 @@ import org.apache.solr.cloud.OverseerSol
 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 
          MAX_SHARDS_PER_NODE,
         CREATE_NODE_SET ,
         SHARDS_PROP,
+        DocCollection.STATE_FORMAT,
         ASYNC,
         "router.");
 

Modified: lucene/dev/trunk/solr/core/src/java/org/apache/solr/servlet/SolrDispatchFilter.java
URL: http://svn.apache.org/viewvc/lucene/dev/trunk/solr/core/src/java/org/apache/solr/servlet/SolrDispatchFilter.java?rev=1587834&r1=1587833&r2=1587834&view=diff
==============================================================================
--- lucene/dev/trunk/solr/core/src/java/org/apache/solr/servlet/SolrDispatchFilter.java (original)
+++ lucene/dev/trunk/solr/core/src/java/org/apache/solr/servlet/SolrDispatchFilter.java Wed Apr 16 08:37:26 2014
@@ -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 
             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 
             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 
     // 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) {

Modified: lucene/dev/trunk/solr/core/src/java/org/apache/solr/servlet/ZookeeperInfoServlet.java
URL: http://svn.apache.org/viewvc/lucene/dev/trunk/solr/core/src/java/org/apache/solr/servlet/ZookeeperInfoServlet.java?rev=1587834&r1=1587833&r2=1587834&view=diff
==============================================================================
--- lucene/dev/trunk/solr/core/src/java/org/apache/solr/servlet/ZookeeperInfoServlet.java (original)
+++ lucene/dev/trunk/solr/core/src/java/org/apache/solr/servlet/ZookeeperInfoServlet.java Wed Apr 16 08:37:26 2014
@@ -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 
     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 
 
     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 
     printer.dump = dump;
 
     try {
-      printer.print(path);
+      printer.print(path, all);
     } finally {
       printer.close();
     }
-    
+
     out.flush();
   }
 
@@ -184,7 +194,7 @@ public final class ZookeeperInfoServlet 
     }
 
     // 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 
       json.startObject();
 
       if (detail) {
-        if (!printZnode(json, path)) {
+        if (!printZnode(json, path,all)) {
           return;
         }
         json.writeValueSeparator();
@@ -285,7 +295,7 @@ public final class ZookeeperInfoServlet 
 
         if (dump) {
           json.writeValueSeparator();
-          printZnode(json, path);
+          printZnode(json, path, false);
         }
 
       } catch (IllegalArgumentException e) {
@@ -358,7 +368,8 @@ public final class ZookeeperInfoServlet 
       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 
           }
         }
 
+        // 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();

Modified: lucene/dev/trunk/solr/core/src/java/org/apache/solr/util/SolrLogLayout.java
URL: http://svn.apache.org/viewvc/lucene/dev/trunk/solr/core/src/java/org/apache/solr/util/SolrLogLayout.java?rev=1587834&r1=1587833&r2=1587834&view=diff
==============================================================================
--- lucene/dev/trunk/solr/core/src/java/org/apache/solr/util/SolrLogLayout.java (original)
+++ lucene/dev/trunk/solr/core/src/java/org/apache/solr/util/SolrLogLayout.java Wed Apr 16 08:37:26 2014
@@ -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 Layou
 
   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();
     }

Modified: lucene/dev/trunk/solr/core/src/test/org/apache/solr/cloud/CollectionsAPIDistributedZkTest.java
URL: http://svn.apache.org/viewvc/lucene/dev/trunk/solr/core/src/test/org/apache/solr/cloud/CollectionsAPIDistributedZkTest.java?rev=1587834&r1=1587833&r2=1587834&view=diff
==============================================================================
--- lucene/dev/trunk/solr/core/src/test/org/apache/solr/cloud/CollectionsAPIDistributedZkTest.java (original)
+++ lucene/dev/trunk/solr/core/src/test/org/apache/solr/cloud/CollectionsAPIDistributedZkTest.java Wed Apr 16 08:37:26 2014
@@ -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 CollectionsAPIDistributedZk
     checkForMissingCollection(collectionName);
     
     assertFalse(cloudClient.getZkStateReader().getZkClient().exists(ZkStateReader.COLLECTIONS_ZKNODE + "/" + collectionName, true));
-    
+
   }
 
   private void testSolrJAPICalls() throws Exception {
@@ -410,7 +411,7 @@ public class CollectionsAPIDistributedZk
     }
 
     assertFalse("Still found collection that should be gone", cloudClient.getZkStateReader().getClusterState().hasCollection("halfdeletedcollection2"));
-    
+
   }
 
   private void testErrorHandling() throws Exception {
@@ -1162,27 +1163,6 @@ public class CollectionsAPIDistributedZk
     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<>();
     

Added: lucene/dev/trunk/solr/core/src/test/org/apache/solr/cloud/ExternalCollectionsTest.java
URL: http://svn.apache.org/viewvc/lucene/dev/trunk/solr/core/src/test/org/apache/solr/cloud/ExternalCollectionsTest.java?rev=1587834&view=auto
==============================================================================
--- lucene/dev/trunk/solr/core/src/test/org/apache/solr/cloud/ExternalCollectionsTest.java (added)
+++ lucene/dev/trunk/solr/core/src/test/org/apache/solr/cloud/ExternalCollectionsTest.java Wed Apr 16 08:37:26 2014
@@ -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));
+
+  }
+}
+
+
+

Modified: lucene/dev/trunk/solr/core/src/test/org/apache/solr/cloud/OverseerStatusTest.java
URL: http://svn.apache.org/viewvc/lucene/dev/trunk/solr/core/src/test/org/apache/solr/cloud/OverseerStatusTest.java?rev=1587834&r1=1587833&r2=1587834&view=diff
==============================================================================
--- lucene/dev/trunk/solr/core/src/test/org/apache/solr/cloud/OverseerStatusTest.java (original)
+++ lucene/dev/trunk/solr/core/src/test/org/apache/solr/cloud/OverseerStatusTest.java Wed Apr 16 08:37:26 2014
@@ -68,16 +68,37 @@ public class OverseerStatusTest extends 
   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",

Modified: lucene/dev/trunk/solr/core/src/test/org/apache/solr/cloud/TestCollectionAPI.java
URL: http://svn.apache.org/viewvc/lucene/dev/trunk/solr/core/src/test/org/apache/solr/cloud/TestCollectionAPI.java?rev=1587834&r1=1587833&r2=1587834&view=diff
==============================================================================
--- lucene/dev/trunk/solr/core/src/test/org/apache/solr/cloud/TestCollectionAPI.java (original)
+++ lucene/dev/trunk/solr/core/src/test/org/apache/solr/cloud/TestCollectionAPI.java Wed Apr 16 08:37:26 2014
@@ -63,6 +63,11 @@ public class TestCollectionAPI extends A
       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();

Modified: lucene/dev/trunk/solr/solrj/src/java/org/apache/solr/client/solrj/impl/CloudSolrServer.java
URL: http://svn.apache.org/viewvc/lucene/dev/trunk/solr/solrj/src/java/org/apache/solr/client/solrj/impl/CloudSolrServer.java?rev=1587834&r1=1587833&r2=1587834&view=diff
==============================================================================
--- lucene/dev/trunk/solr/solrj/src/java/org/apache/solr/client/solrj/impl/CloudSolrServer.java (original)
+++ lucene/dev/trunk/solr/solrj/src/java/org/apache/solr/client/solrj/impl/CloudSolrServer.java Wed Apr 16 08:37:26 2014
@@ -18,7 +18,9 @@ package org.apache.solr.client.solrj.imp
  */
 
 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.Named
 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.KeeperExcept
  * 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 Sol
       .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 Sol
     // 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 Sol
     this.lbServer.setParser(new BinaryResponseParser());
     this.updatesToLeaders = updatesToLeaders;
     shutdownLBHttpSolrServer = true;
+
+    timeToLive = cachedStateTimeToLiveSecs * 1000L;
+    setupStateVerParamOnQueryString(lbServer);
   }
 
   /**
@@ -146,10 +185,7 @@ public class CloudSolrServer extends Sol
    * @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 Sol
    * @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 Sol
       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 Sol
       }
     }
 
-    DocCollection col = clusterState.getCollection(collection);
+    DocCollection col = getDocCollection(clusterState, collection);
 
     DocRouter router = col.getRouter();
     
@@ -311,8 +366,8 @@ public class CloudSolrServer extends Sol
       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 Sol
   }
 
   @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 Sol
       // 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 Sol
     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 Sol
     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;
+  }
+
 }

Modified: lucene/dev/trunk/solr/solrj/src/java/org/apache/solr/common/SolrException.java
URL: http://svn.apache.org/viewvc/lucene/dev/trunk/solr/solrj/src/java/org/apache/solr/common/SolrException.java?rev=1587834&r1=1587833&r2=1587834&view=diff
==============================================================================
--- lucene/dev/trunk/solr/solrj/src/java/org/apache/solr/common/SolrException.java (original)
+++ lucene/dev/trunk/solr/solrj/src/java/org/apache/solr/common/SolrException.java Wed Apr 16 08:37:26 2014
@@ -45,6 +45,7 @@ public class SolrException extends Runti
     UNSUPPORTED_MEDIA_TYPE( 415 ),
     SERVER_ERROR( 500 ),
     SERVICE_UNAVAILABLE( 503 ),
+    INVALID_STATE( 510 ),
     UNKNOWN(0);
     public final int code;
     

Modified: lucene/dev/trunk/solr/solrj/src/java/org/apache/solr/common/cloud/ClusterState.java
URL: http://svn.apache.org/viewvc/lucene/dev/trunk/solr/solrj/src/java/org/apache/solr/common/cloud/ClusterState.java?rev=1587834&r1=1587833&r2=1587834&view=diff
==============================================================================
--- lucene/dev/trunk/solr/solrj/src/java/org/apache/solr/common/cloud/ClusterState.java (original)
+++ lucene/dev/trunk/solr/solrj/src/java/org/apache/solr/common/cloud/ClusterState.java Wed Apr 16 08:37:26 2014
@@ -54,6 +54,7 @@ public class ClusterState implements JSO
    * 
    * 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 JSO
    */
   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 JSO
    * 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 JSO
    * 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 JSO
   }
 
   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 JSO
     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 JSO
     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 JSO
       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 JSO
     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 JSO
     this.liveNodes = liveNodes;
   }
 
+  public DocCollection getCommonCollection(String name){
+    return collectionStates.get(name);
+
+  }
+
 }

Modified: lucene/dev/trunk/solr/solrj/src/java/org/apache/solr/common/cloud/DocCollection.java
URL: http://svn.apache.org/viewvc/lucene/dev/trunk/solr/solrj/src/java/org/apache/solr/common/cloud/DocCollection.java?rev=1587834&r1=1587833&r2=1587834&view=diff
==============================================================================
--- lucene/dev/trunk/solr/solrj/src/java/org/apache/solr/common/cloud/DocCollection.java (original)
+++ lucene/dev/trunk/solr/solrj/src/java/org/apache/solr/common/cloud/DocCollection.java Wed Apr 16 08:37:26 2014
@@ -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 ZkNod
         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 ZkNod
     return activeSlices;
   }
 
+  public int getVersion(){
+    return version;
+
+  }
+
+  public boolean isExternal(){
+    return external;
+  }
+
+
   public DocRouter getRouter() {
     return router;
   }