You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@lucene.apache.org by ro...@apache.org on 2013/01/18 19:31:23 UTC

svn commit: r1435287 [27/41] - in /lucene/dev/branches/LUCENE-2878: ./ dev-tools/ dev-tools/eclipse/ dev-tools/idea/.idea/libraries/ dev-tools/idea/lucene/analysis/icu/ dev-tools/maven/ dev-tools/maven/lucene/benchmark/ dev-tools/maven/solr/ dev-tools/...

Modified: lucene/dev/branches/LUCENE-2878/solr/core/src/java/org/apache/solr/cloud/OverseerCollectionProcessor.java
URL: http://svn.apache.org/viewvc/lucene/dev/branches/LUCENE-2878/solr/core/src/java/org/apache/solr/cloud/OverseerCollectionProcessor.java?rev=1435287&r1=1435286&r2=1435287&view=diff
==============================================================================
--- lucene/dev/branches/LUCENE-2878/solr/core/src/java/org/apache/solr/cloud/OverseerCollectionProcessor.java (original)
+++ lucene/dev/branches/LUCENE-2878/solr/core/src/java/org/apache/solr/cloud/OverseerCollectionProcessor.java Fri Jan 18 18:30:54 2013
@@ -25,7 +25,9 @@ import java.util.Set;
 
 import org.apache.solr.common.SolrException;
 import org.apache.solr.common.SolrException.ErrorCode;
+import org.apache.solr.common.cloud.ClosableThread;
 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.ZkNodeProps;
@@ -34,6 +36,7 @@ import org.apache.solr.common.cloud.ZooK
 import org.apache.solr.common.params.CoreAdminParams;
 import org.apache.solr.common.params.CoreAdminParams.CoreAdminAction;
 import org.apache.solr.common.params.ModifiableSolrParams;
+import org.apache.solr.common.util.StrUtils;
 import org.apache.solr.handler.component.ShardHandler;
 import org.apache.solr.handler.component.ShardRequest;
 import org.apache.solr.handler.component.ShardResponse;
@@ -41,9 +44,16 @@ import org.apache.zookeeper.KeeperExcept
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
-public class OverseerCollectionProcessor implements Runnable {
+public class OverseerCollectionProcessor implements Runnable, ClosableThread {
+  
+  public static final String NUM_SLICES = "numShards";
+  
   public static final String REPLICATION_FACTOR = "replicationFactor";
-
+  
+  public static final String MAX_SHARDS_PER_NODE = "maxShardsPerNode";
+  
+  public static final String CREATE_NODE_SET = "createNodeSet";
+  
   public static final String DELETECOLLECTION = "deletecollection";
 
   public static final String CREATECOLLECTION = "createcollection";
@@ -71,11 +81,15 @@ public class OverseerCollectionProcessor
   private boolean isClosed;
   
   public OverseerCollectionProcessor(ZkStateReader zkStateReader, String myId, ShardHandler shardHandler, String adminPath) {
+    this(zkStateReader, myId, shardHandler, adminPath, Overseer.getCollectionQueue(zkStateReader.getZkClient()));
+  }
+
+  protected OverseerCollectionProcessor(ZkStateReader zkStateReader, String myId, ShardHandler shardHandler, String adminPath, DistributedQueue workQueue) {
     this.zkStateReader = zkStateReader;
     this.myId = myId;
     this.shardHandler = shardHandler;
     this.adminPath = adminPath;
-    workQueue = Overseer.getCollectionQueue(zkStateReader.getZkClient());
+    this.workQueue = workQueue;
   }
   
   @Override
@@ -103,7 +117,10 @@ public class OverseerCollectionProcessor
                   + " failed", t);
         }
         //}
-        workQueue.remove();
+        
+        
+        workQueue.poll();
+       
       } catch (KeeperException e) {
         if (e.code() == KeeperException.Code.SESSIONEXPIRED
             || e.code() == KeeperException.Code.CONNECTIONLOSS) {
@@ -124,7 +141,7 @@ public class OverseerCollectionProcessor
     isClosed = true;
   }
   
-  private boolean amILeader() {
+  protected boolean amILeader() {
     try {
       ZkNodeProps props = ZkNodeProps.load(zkStateReader.getZkClient().getData(
           "/overseer_elect/leader", null, null, true));
@@ -140,7 +157,7 @@ public class OverseerCollectionProcessor
     return false;
   }
   
-  private boolean processMessage(ZkNodeProps message, String operation) {
+  protected boolean processMessage(ZkNodeProps message, String operation) {
     if (CREATECOLLECTION.equals(operation)) {
       return createCollection(zkStateReader.getClusterState(), message);
     } else if (DELETECOLLECTION.equals(operation)) {
@@ -163,124 +180,149 @@ public class OverseerCollectionProcessor
       SolrException.log(log, "collection already exists: " + collectionName);
       return false;
     }
-
-    // look at the replication factor and see if it matches reality
-    // if it does not, find best nodes to create more cores
     
-    String numReplicasString = message.getStr(REPLICATION_FACTOR);
-    int numReplicas;
-    try {
-      numReplicas = numReplicasString == null ? 0 : Integer.parseInt(numReplicasString);
-    } catch (Exception ex) {
-      SolrException.log(log, "Could not parse " + REPLICATION_FACTOR, ex);
-      return false;
-    }
-    String numShardsString = message.getStr("numShards");
-    int numShards;
     try {
-      numShards = numShardsString == null ? 0 : Integer.parseInt(numShardsString);
-    } catch (Exception ex) {
-      SolrException.log(log, "Could not parse numShards", ex);
-      return false;
-    }
-    
-    if (numReplicas < 0) {
-      SolrException.log(log, REPLICATION_FACTOR + " must be > 0");
-      return false;
-    }
-    
-    if (numShards < 0) {
-      SolrException.log(log, "numShards must be > 0");
-      return false;
-    }
-    
-    
-    String name = message.getStr("name");
-    String configName = message.getStr("collection.configName");
-    
-    // we need to look at every node and see how many cores it serves
-    // add our new cores to existing nodes serving the least number of cores
-    // but (for now) require that each core goes on a distinct node.
-    
-    ModifiableSolrParams params = new ModifiableSolrParams();
-    params.set(CoreAdminParams.ACTION, CoreAdminAction.CREATE.toString());
-    
-    
-    // TODO: add smarter options that look at the current number of cores per node?
-    // for now we just go random
-    Set<String> nodes = clusterState.getLiveNodes();
-    List<String> nodeList = new ArrayList<String>(nodes.size());
-    nodeList.addAll(nodes);
-    Collections.shuffle(nodeList);
-    
-    int numNodes = numShards * (numReplicas + 1);
-    if (nodeList.size() < numNodes) {
-      log.warn("Not enough nodes available to satisfy create collection request for collection:"
-          + collectionName
-          + " nodes needed:"
-          + numNodes
-          + " nodes available:"
-          + nodeList.size() + " - using nodes available");
-    }
-
-    List<String> createOnNodes = nodeList.subList(0, Math.min(nodeList.size(), numNodes));
-    
-    log.info("Create collection " + name + " on " + createOnNodes);
-    
-    for (String replica : createOnNodes) {
-      // TODO: this does not work if original url had _ in it
-      // We should have a master list
-      replica = replica.replaceAll("_", "/");
-      params.set(CoreAdminParams.NAME, name);
-      params.set("collection.configName", configName);
-      params.set("numShards", numShards);
-      ShardRequest sreq = new ShardRequest();
-      params.set("qt", adminPath);
-      sreq.purpose = 1;
-      // TODO: this sucks
-      if (replica.startsWith("http://")) replica = replica.substring(7);
-      sreq.shards = new String[] {replica};
-      sreq.actualShards = sreq.shards;
-      sreq.params = params;
+      // look at the replication factor and see if it matches reality
+      // if it does not, find best nodes to create more cores
       
-      shardHandler.submit(sreq, replica, sreq.params);
-    }
-    
-    int failed = 0;
-    ShardResponse srsp;
-    do {
-      srsp = shardHandler.takeCompletedOrError();
-      if (srsp != null) {
-        Throwable e = srsp.getException();
-        if (e != null) {
-          // should we retry?
-          // TODO: we should return errors to the client
-          // TODO: what if one fails and others succeed?
-          failed++;
-          log.error("Error talking to shard: " + srsp.getShard(), e);
+      int repFactor = msgStrToInt(message, REPLICATION_FACTOR, 1);
+      int numSlices = msgStrToInt(message, NUM_SLICES, 0);
+      int maxShardsPerNode = msgStrToInt(message, MAX_SHARDS_PER_NODE, 1);
+      String createNodeSetStr; 
+      List<String> createNodeList = ((createNodeSetStr = message.getStr(CREATE_NODE_SET)) == null)?null:StrUtils.splitSmart(createNodeSetStr, ",", true);
+      
+      if (repFactor <= 0) {
+        SolrException.log(log, REPLICATION_FACTOR + " must be > 0");
+        return false;
+      }
+      
+      if (numSlices < 0) {
+        SolrException.log(log, NUM_SLICES + " must be > 0");
+        return false;
+      }
+      
+      String configName = message.getStr("collection.configName");
+      
+      // we need to look at every node and see how many cores it serves
+      // add our new cores to existing nodes serving the least number of cores
+      // but (for now) require that each core goes on a distinct node.
+      
+      // TODO: add smarter options that look at the current number of cores per
+      // node?
+      // for now we just go random
+      Set<String> nodes = clusterState.getLiveNodes();
+      List<String> nodeList = new ArrayList<String>(nodes.size());
+      nodeList.addAll(nodes);
+      if (createNodeList != null) nodeList.retainAll(createNodeList);
+      Collections.shuffle(nodeList);
+      
+      if (nodeList.size() <= 0) {
+        log.error("Cannot create collection " + collectionName
+            + ". No live Solr-instaces" + ((createNodeList != null)?" among Solr-instances specified in " + CREATE_NODE_SET:""));
+        return false;
+      }
+      
+      if (repFactor > nodeList.size()) {
+        log.warn("Specified "
+            + REPLICATION_FACTOR
+            + " of "
+            + repFactor
+            + " on collection "
+            + collectionName
+            + " is higher than or equal to the number of Solr instances currently live ("
+            + nodeList.size()
+            + "). Its unusual to run two replica of the same slice on the same Solr-instance.");
+      }
+      
+      int maxShardsAllowedToCreate = maxShardsPerNode * nodeList.size();
+      int requestedShardsToCreate = numSlices * repFactor;
+      if (maxShardsAllowedToCreate < requestedShardsToCreate) {
+        log.error("Cannot create collection " + collectionName + ". Value of "
+            + MAX_SHARDS_PER_NODE + " is " + maxShardsPerNode
+            + ", and the number of live nodes is " + nodeList.size()
+            + ". This allows a maximum of " + maxShardsAllowedToCreate
+            + " to be created. Value of " + NUM_SLICES + " is " + numSlices
+            + " and value of " + REPLICATION_FACTOR + " is " + repFactor
+            + ". This requires " + requestedShardsToCreate
+            + " shards to be created (higher than the allowed number)");
+        return false;
+      }
+      
+      for (int i = 1; i <= numSlices; i++) {
+        for (int j = 1; j <= repFactor; j++) {
+          String nodeName = nodeList.get(((i - 1) + (j - 1)) % nodeList.size());
+          String sliceName = "shard" + i;
+          String shardName = collectionName + "_" + sliceName + "_replica" + j;
+          log.info("Creating shard " + shardName + " as part of slice "
+              + sliceName + " of collection " + collectionName + " on "
+              + nodeName);
+          
+          // Need to create new params for each request
+          ModifiableSolrParams params = new ModifiableSolrParams();
+          params.set(CoreAdminParams.ACTION, CoreAdminAction.CREATE.toString());
+          
+          params.set(CoreAdminParams.NAME, shardName);
+          params.set("collection.configName", configName);
+          params.set(CoreAdminParams.COLLECTION, collectionName);
+          params.set(CoreAdminParams.SHARD, sliceName);
+          params.set(ZkStateReader.NUM_SHARDS_PROP, numSlices);
+          
+          ShardRequest sreq = new ShardRequest();
+          params.set("qt", adminPath);
+          sreq.purpose = 1;
+          String replica = zkStateReader.getZkClient()
+            .getBaseUrlForNodeName(nodeName);
+          if (replica.startsWith("http://")) replica = replica.substring(7);
+          sreq.shards = new String[] {replica};
+          sreq.actualShards = sreq.shards;
+          sreq.params = params;
+          
+          shardHandler.submit(sreq, replica, sreq.params);
+          
         }
       }
-    } while (srsp != null);
-
-    
-    // if all calls succeeded, return true
-    if (failed > 0) {
+      
+      int failed = 0;
+      ShardResponse srsp;
+      do {
+        srsp = shardHandler.takeCompletedOrError();
+        if (srsp != null) {
+          Throwable e = srsp.getException();
+          if (e != null) {
+            // should we retry?
+            // TODO: we should return errors to the client
+            // TODO: what if one fails and others succeed?
+            failed++;
+            log.error("Error talking to shard: " + srsp.getShard(), e);
+          }
+        }
+      } while (srsp != null);
+      
+      // if all calls succeeded, return true
+      if (failed > 0) {
+        return false;
+      }
+      log.info("Successfully created all shards for collection "
+          + collectionName);
+      return true;
+    } catch (Exception ex) {
+      // Expecting that the necessary logging has already been performed
       return false;
     }
-    return true;
   }
   
   private boolean collectionCmd(ClusterState clusterState, ZkNodeProps message, ModifiableSolrParams params) {
     log.info("Executing Collection Cmd : " + params);
-    String name = message.getStr("name");
+    String collectionName = message.getStr("name");
     
-    Map<String,Slice> slices = clusterState.getCollectionStates().get(name);
+    DocCollection coll = clusterState.getCollection(collectionName);
     
-    if (slices == null) {
-      throw new SolrException(ErrorCode.BAD_REQUEST, "Could not find collection:" + name);
+    if (coll == null) {
+      throw new SolrException(ErrorCode.BAD_REQUEST,
+          "Could not find collection:" + collectionName);
     }
     
-    for (Map.Entry<String,Slice> entry : slices.entrySet()) {
+    for (Map.Entry<String,Slice> entry : coll.getSlicesMap().entrySet()) {
       Slice slice = entry.getValue();
       Map<String,Replica> shards = slice.getReplicasMap();
       Set<Map.Entry<String,Replica>> shardEntries = shards.entrySet();
@@ -334,4 +376,20 @@ public class OverseerCollectionProcessor
     }
     return true;
   }
+  
+  private int msgStrToInt(ZkNodeProps message, String key, Integer def)
+      throws Exception {
+    String str = message.getStr(key);
+    try {
+      return str == null ? def : Integer.parseInt(str);
+    } catch (Exception ex) {
+      SolrException.log(log, "Could not parse " + key, ex);
+      throw ex;
+    }
+  }
+
+  @Override
+  public boolean isClosed() {
+    return isClosed;
+  }
 }

Modified: lucene/dev/branches/LUCENE-2878/solr/core/src/java/org/apache/solr/cloud/RecoveryStrategy.java
URL: http://svn.apache.org/viewvc/lucene/dev/branches/LUCENE-2878/solr/core/src/java/org/apache/solr/cloud/RecoveryStrategy.java?rev=1435287&r1=1435286&r2=1435287&view=diff
==============================================================================
--- lucene/dev/branches/LUCENE-2878/solr/core/src/java/org/apache/solr/cloud/RecoveryStrategy.java (original)
+++ lucene/dev/branches/LUCENE-2878/solr/core/src/java/org/apache/solr/cloud/RecoveryStrategy.java Fri Jan 18 18:30:54 2013
@@ -99,6 +99,7 @@ public class RecoveryStrategy extends Th
   }
 
   // make sure any threads stop retrying
+  @Override
   public void close() {
     close = true;
     log.warn("Stopping recovery for zkNodeName=" + coreZkNodeName + "core=" + coreName );
@@ -174,7 +175,7 @@ public class RecoveryStrategy extends Th
   private void commitOnLeader(String leaderUrl) throws SolrServerException, IOException {
     HttpSolrServer server = new HttpSolrServer(leaderUrl);
     server.setConnectionTimeout(30000);
-    server.setSoTimeout(30000);
+    server.setSoTimeout(60000);
     UpdateRequest ureq = new UpdateRequest();
     ureq.setParams(new ModifiableSolrParams());
     ureq.getParams().set(DistributedUpdateProcessor.COMMIT_END_POINT, true);
@@ -189,7 +190,7 @@ public class RecoveryStrategy extends Th
       IOException {
     HttpSolrServer server = new HttpSolrServer(leaderBaseUrl);
     server.setConnectionTimeout(45000);
-    server.setSoTimeout(45000);
+    server.setSoTimeout(120000);
     WaitForState prepCmd = new WaitForState();
     prepCmd.setCoreName(leaderCoreName);
     prepCmd.setNodeName(zkController.getNodeName());
@@ -317,7 +318,7 @@ public class RecoveryStrategy extends Th
       try {
         CloudDescriptor cloudDesc = core.getCoreDescriptor()
             .getCloudDescriptor();
-        ZkNodeProps leaderprops = zkStateReader.getLeaderProps(
+        ZkNodeProps leaderprops = zkStateReader.getLeaderRetry(
             cloudDesc.getCollectionName(), cloudDesc.getShardId());
       
         String leaderBaseUrl = leaderprops.getStr(ZkStateReader.BASE_URL_PROP);
@@ -340,6 +341,18 @@ public class RecoveryStrategy extends Th
         }
         
         zkController.publish(core.getCoreDescriptor(), ZkStateReader.RECOVERING);
+        
+        
+        sendPrepRecoveryCmd(leaderBaseUrl, leaderCoreName);
+        
+        // we wait a bit so that any updates on the leader
+        // that started before they saw recovering state 
+        // are sure to have finished
+        try {
+          Thread.sleep(2000);
+        } catch (InterruptedException e) {
+          Thread.currentThread().interrupt();
+        }
 
         // first thing we just try to sync
         if (firstTime) {
@@ -387,17 +400,6 @@ public class RecoveryStrategy extends Th
 
         log.info("Starting Replication Recovery. core=" + coreName);
         
-        sendPrepRecoveryCmd(leaderBaseUrl, leaderCoreName);
-        
-        // we wait a bit so that any updates on the leader
-        // that started before they saw recovering state 
-        // are sure to have finished
-        try {
-          Thread.sleep(2000);
-        } catch (InterruptedException e) {
-          Thread.currentThread().interrupt();
-        }
-        
         log.info("Begin buffering updates. core=" + coreName);
         ulog.bufferUpdates();
         replayed = false;
@@ -532,6 +534,7 @@ public class RecoveryStrategy extends Th
     return future;
   }
 
+  @Override
   public boolean isClosed() {
     return close;
   }

Modified: lucene/dev/branches/LUCENE-2878/solr/core/src/java/org/apache/solr/cloud/SyncStrategy.java
URL: http://svn.apache.org/viewvc/lucene/dev/branches/LUCENE-2878/solr/core/src/java/org/apache/solr/cloud/SyncStrategy.java?rev=1435287&r1=1435286&r2=1435287&view=diff
==============================================================================
--- lucene/dev/branches/LUCENE-2878/solr/core/src/java/org/apache/solr/cloud/SyncStrategy.java (original)
+++ lucene/dev/branches/LUCENE-2878/solr/core/src/java/org/apache/solr/cloud/SyncStrategy.java Fri Jan 18 18:30:54 2013
@@ -271,7 +271,11 @@ public class SyncStrategy {
   
   public void close() {
     this.isClosed = true;
-    ExecutorUtil.shutdownNowAndAwaitTermination(recoveryCmdExecutor);
+    try {
+      ExecutorUtil.shutdownNowAndAwaitTermination(recoveryCmdExecutor);
+    } catch (Throwable e) {
+      SolrException.log(log, e);
+    }
   }
   
   private void requestRecovery(final ZkNodeProps leaderProps, final String baseUrl, final String coreName) throws SolrServerException, IOException {

Modified: lucene/dev/branches/LUCENE-2878/solr/core/src/java/org/apache/solr/cloud/ZkCLI.java
URL: http://svn.apache.org/viewvc/lucene/dev/branches/LUCENE-2878/solr/core/src/java/org/apache/solr/cloud/ZkCLI.java?rev=1435287&r1=1435286&r2=1435287&view=diff
==============================================================================
--- lucene/dev/branches/LUCENE-2878/solr/core/src/java/org/apache/solr/cloud/ZkCLI.java (original)
+++ lucene/dev/branches/LUCENE-2878/solr/core/src/java/org/apache/solr/cloud/ZkCLI.java Fri Jan 18 18:30:54 2013
@@ -123,12 +123,12 @@ public class ZkCLI {
         HelpFormatter formatter = new HelpFormatter();
         formatter.printHelp(ZK_CLI_NAME, options);
         System.out.println("Examples:");
-        System.out.println("zkcli.sh -cmd " + BOOTSTRAP + " -" + SOLRHOME + " /opt/solr");
-        System.out.println("zkcli.sh -cmd " + UPCONFIG + " -" + CONFDIR + " /opt/solr/collection1/conf" + " -" + CONFNAME + " myconf");
-        System.out.println("zkcli.sh -cmd " + DOWNCONFIG + " -" + CONFDIR + " /opt/solr/collection1/conf" + " -" + CONFNAME + " myconf");
-        System.out.println("zkcli.sh -cmd " + LINKCONFIG + " -" + COLLECTION + " collection1" + " -" + CONFNAME + " myconf");
-        System.out.println("zkcli.sh -cmd " + MAKEPATH + " /apache/solr");
-        System.out.println("zkcli.sh -cmd " + CLEAR + " /solr");
+        System.out.println("zkcli.sh -zkhost localhost:9983 -cmd " + BOOTSTRAP + " -" + SOLRHOME + " /opt/solr");
+        System.out.println("zkcli.sh -zkhost localhost:9983 -cmd " + UPCONFIG + " -" + CONFDIR + " /opt/solr/collection1/conf" + " -" + CONFNAME + " myconf");
+        System.out.println("zkcli.sh -zkhost localhost:9983 -cmd " + DOWNCONFIG + " -" + CONFDIR + " /opt/solr/collection1/conf" + " -" + CONFNAME + " myconf");
+        System.out.println("zkcli.sh -zkhost localhost:9983 -cmd " + LINKCONFIG + " -" + COLLECTION + " collection1" + " -" + CONFNAME + " myconf");
+        System.out.println("zkcli.sh -zkhost localhost:9983 -cmd " + MAKEPATH + " /apache/solr");
+        System.out.println("zkcli.sh -zkhost localhost:9983 -cmd " + CLEAR + " /solr");
         return;
       }
       
@@ -173,6 +173,12 @@ public class ZkCLI {
           InputSource cfgis = new InputSource(new File(solrHome, SOLR_XML)
               .toURI().toASCIIString());
           Config cfg = new Config(loader, null, cfgis, null, false);
+          
+          if(!ZkController.checkChrootPath(zkServerAddress, true)) {
+            System.out.println("A chroot was specified in zkHost but the znode doesn't exist. ");
+            System.exit(1);
+          }
+          
           ZkController.bootstrapConf(zkClient, cfg, solrHome);
           
         } else if (line.getOptionValue(CMD).equals(UPCONFIG)) {
@@ -184,6 +190,11 @@ public class ZkCLI {
           String confDir = line.getOptionValue(CONFDIR);
           String confName = line.getOptionValue(CONFNAME);
           
+          if(!ZkController.checkChrootPath(zkServerAddress, true)) {
+            System.out.println("A chroot was specified in zkHost but the znode doesn't exist. ");
+            System.exit(1);
+          }
+          
           ZkController.uploadConfigDir(zkClient, new File(confDir), confName);
         } else if (line.getOptionValue(CMD).equals(DOWNCONFIG)) {
           if (!line.hasOption(CONFDIR) || !line.hasOption(CONFNAME)) {

Modified: lucene/dev/branches/LUCENE-2878/solr/core/src/java/org/apache/solr/cloud/ZkController.java
URL: http://svn.apache.org/viewvc/lucene/dev/branches/LUCENE-2878/solr/core/src/java/org/apache/solr/cloud/ZkController.java?rev=1435287&r1=1435286&r2=1435287&view=diff
==============================================================================
--- lucene/dev/branches/LUCENE-2878/solr/core/src/java/org/apache/solr/cloud/ZkController.java (original)
+++ lucene/dev/branches/LUCENE-2878/solr/core/src/java/org/apache/solr/cloud/ZkController.java Fri Jan 18 18:30:54 2013
@@ -19,8 +19,11 @@ package org.apache.solr.cloud;
 
 import java.io.File;
 import java.io.IOException;
+import java.io.UnsupportedEncodingException;
 import java.net.InetAddress;
 import java.net.NetworkInterface;
+import java.net.URLEncoder;
+import java.net.UnknownHostException;
 import java.util.Collections;
 import java.util.Enumeration;
 import java.util.HashMap;
@@ -29,9 +32,6 @@ import java.util.List;
 import java.util.Map;
 import java.util.Properties;
 import java.util.concurrent.Future;
-import java.util.concurrent.SynchronousQueue;
-import java.util.concurrent.ThreadPoolExecutor;
-import java.util.concurrent.TimeUnit;
 import java.util.concurrent.TimeoutException;
 import java.util.regex.Matcher;
 import java.util.regex.Pattern;
@@ -44,6 +44,9 @@ import org.apache.solr.client.solrj.requ
 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.DocRouter;
+import org.apache.solr.common.cloud.ImplicitDocRouter;
 import org.apache.solr.common.cloud.OnReconnect;
 import org.apache.solr.common.cloud.SolrZkClient;
 import org.apache.solr.common.cloud.ZkCmdExecutor;
@@ -52,16 +55,14 @@ import org.apache.solr.common.cloud.ZkNo
 import org.apache.solr.common.cloud.ZkStateReader;
 import org.apache.solr.common.cloud.ZooKeeperException;
 import org.apache.solr.common.params.SolrParams;
-import org.apache.solr.common.util.ExecutorUtil;
-
 import org.apache.solr.core.Config;
 import org.apache.solr.core.CoreContainer;
 import org.apache.solr.core.CoreDescriptor;
 import org.apache.solr.core.SolrCore;
 import org.apache.solr.handler.component.ShardHandler;
 import org.apache.solr.update.UpdateLog;
+import org.apache.solr.update.UpdateShardHandler;
 import org.apache.solr.util.DOMUtil;
-import org.apache.solr.util.DefaultSolrThreadFactory;
 import org.apache.zookeeper.CreateMode;
 import org.apache.zookeeper.KeeperException;
 import org.apache.zookeeper.KeeperException.NoNodeException;
@@ -96,17 +97,11 @@ public final class ZkController {
   private final DistributedQueue overseerJobQueue;
   private final DistributedQueue overseerCollectionQueue;
   
-  // package private for tests
-
-  static final String CONFIGS_ZKNODE = "/configs";
+  public static final String CONFIGS_ZKNODE = "/configs";
 
   public final static String COLLECTION_PARAM_PREFIX="collection.";
   public final static String CONFIGNAME_PROP="configName";
 
-  private ThreadPoolExecutor cmdDistribExecutor = new ThreadPoolExecutor(
-      0, Integer.MAX_VALUE, 5, TimeUnit.SECONDS,
-      new SynchronousQueue<Runnable>(), new DefaultSolrThreadFactory(
-          "cmdDistribExecutor"));
   
   private final Map<String, ElectionContext> electionContexts = Collections.synchronizedMap(new HashMap<String, ElectionContext>());
   
@@ -139,37 +134,43 @@ public final class ZkController {
 
   private int clientTimeout;
 
-
-  public ZkController(final CoreContainer cc, String zkServerAddress, int zkClientTimeout, int zkClientConnectTimeout, String localHost, String locaHostPort,
-      String localHostContext, final CurrentCoreDescriptorProvider registerOnReconnect) throws InterruptedException,
-      TimeoutException, IOException {
-    this(cc, zkServerAddress, zkClientTimeout, zkClientConnectTimeout, localHost, locaHostPort, localHostContext, null, registerOnReconnect);
-  }
+  private volatile boolean isClosed;
   
+  private UpdateShardHandler updateShardHandler;
 
   public ZkController(final CoreContainer cc, String zkServerAddress, int zkClientTimeout, int zkClientConnectTimeout, String localHost, String locaHostPort,
-      String localHostContext, String leaderVoteWait, final CurrentCoreDescriptorProvider registerOnReconnect) throws InterruptedException,
+      String localHostContext, String leaderVoteWait, int distribUpdateConnTimeout, int distribUpdateSoTimeout, final CurrentCoreDescriptorProvider registerOnReconnect) throws InterruptedException,
       TimeoutException, IOException {
     if (cc == null) throw new IllegalArgumentException("CoreContainer cannot be null.");
     this.cc = cc;
-    if (localHostContext.contains("/")) {
-      throw new IllegalArgumentException("localHostContext ("
-          + localHostContext + ") should not contain a /");
-    }
+
+    // be forgiving and strip this off leading/trailing slashes
+    // this allows us to support users specifying hostContext="/" in 
+    // solr.xml to indicate the root context, instead of hostContext="" 
+    // which means the default of "solr"
+    localHostContext = trimLeadingAndTrailingSlashes(localHostContext);
+    
+    updateShardHandler = new UpdateShardHandler(distribUpdateConnTimeout, distribUpdateSoTimeout);
     
     this.zkServerAddress = zkServerAddress;
     this.localHostPort = locaHostPort;
     this.localHostContext = localHostContext;
     this.localHost = getHostAddress(localHost);
+    this.baseURL = this.localHost + ":" + this.localHostPort + 
+      (this.localHostContext.isEmpty() ? "" : ("/" + this.localHostContext));
+
     this.hostName = getHostNameFromAddress(this.localHost);
-    this.nodeName = this.hostName + ':' + this.localHostPort + '_' + this.localHostContext;
-    this.baseURL = this.localHost + ":" + this.localHostPort + "/" + this.localHostContext;
+    this.nodeName = generateNodeName(this.hostName, 
+                                     this.localHostPort, 
+                                     this.localHostContext);
+
     this.leaderVoteWait = leaderVoteWait;
     this.clientTimeout = zkClientTimeout;
     zkClient = new SolrZkClient(zkServerAddress, zkClientTimeout, zkClientConnectTimeout,
         // on reconnect, reload cloud info
         new OnReconnect() {
 
+          @Override
           public void command() {
             try {
               markAllAsNotLeader(registerOnReconnect);
@@ -232,7 +233,7 @@ public final class ZkController {
     
     this.overseerJobQueue = Overseer.getInQueue(zkClient);
     this.overseerCollectionQueue = Overseer.getCollectionQueue(zkClient);
-    cmdExecutor = new ZkCmdExecutor();
+    cmdExecutor = new ZkCmdExecutor(zkClientTimeout);
     leaderElector = new LeaderElector(zkClient);
     zkStateReader = new ZkStateReader(zkClient);
     
@@ -247,6 +248,7 @@ public final class ZkController {
       final CurrentCoreDescriptorProvider registerOnReconnect, boolean updateLastPublished) {
     List<CoreDescriptor> descriptors = registerOnReconnect
         .getCurrentDescriptors();
+    if (isClosed) return;
     if (descriptors != null) {
       // before registering as live, make sure everyone is in a
       // down state
@@ -257,6 +259,9 @@ public final class ZkController {
           descriptor.getCloudDescriptor().isLeader = false;
           publish(descriptor, ZkStateReader.DOWN, updateLastPublished);
         } catch (Exception e) {
+          if (isClosed) {
+            return;
+          }
           try {
             Thread.sleep(1000);
           } catch (InterruptedException e1) {
@@ -269,10 +274,39 @@ public final class ZkController {
             continue;
           }
         }
+        
+        // if it looks like we are going to be the leader, we don't
+        // want to wait for the following stuff
+        CloudDescriptor cloudDesc = descriptor.getCloudDescriptor();
+        String collection = cloudDesc.getCollectionName();
+        String slice = cloudDesc.getShardId();
+        try {
+          
+          int children = zkStateReader
+              .getZkClient()
+              .getChildren(
+                  ZkStateReader.COLLECTIONS_ZKNODE + "/" + collection
+                      + "/leader_elect/" + slice + "/election", null, true).size();
+          if (children == 0) {
+            return;
+          }
+
+        } catch (NoNodeException e) {
+         return;
+        } catch (InterruptedException e2) {
+          Thread.currentThread().interrupt();
+        } catch (KeeperException e) {
+          log.warn("", e);
+          Thread.currentThread().interrupt();
+        }
+        
         try {
           waitForLeaderToSeeDownState(descriptor, coreZkNodeName);
         } catch (Exception e) {
           SolrException.log(log, "", e);
+          if (isClosed) {
+            return;
+          }
           try {
             Thread.sleep(5000);
           } catch (InterruptedException e1) {
@@ -298,14 +332,7 @@ public final class ZkController {
    * Closes the underlying ZooKeeper client.
    */
   public void close() {
-    
-    if (cmdDistribExecutor != null) {
-      try {
-        ExecutorUtil.shutdownNowAndAwaitTermination(cmdDistribExecutor);
-      } catch (Throwable e) {
-        SolrException.log(log, e);
-      }
-    }
+    this.isClosed = true;
     
     for (ElectionContext context : electionContexts.values()) {
       try {
@@ -320,7 +347,20 @@ public final class ZkController {
     } catch(Throwable t) {
       log.error("Error closing overseer", t);
     }
-    zkClient.close();
+    
+    try {
+      zkClient.close();;
+    } catch(Throwable t) {
+      log.error("Error closing zkClient", t);
+    } 
+    
+    if (updateShardHandler != null) {
+      try {
+        updateShardHandler.close();
+      } catch(Throwable t) {
+        log.error("Error closing updateShardHandler", t);
+      }
+    }
   }
 
   /**
@@ -360,7 +400,12 @@ public final class ZkController {
   private String getHostAddress(String host) throws IOException {
 
     if (host == null) {
-      String hostaddress = InetAddress.getLocalHost().getHostAddress();
+      String hostaddress;
+      try {
+        hostaddress = InetAddress.getLocalHost().getHostAddress();
+      } catch (UnknownHostException e) {
+        hostaddress = "127.0.0.1"; // cannot resolve system hostname, fall through
+      }
       // Re-get the IP again for "127.0.0.1", the other case we trust the hosts
       // file is right.
       if ("127.0.0.1".equals(hostaddress)) {
@@ -469,6 +514,37 @@ public final class ZkController {
 
   }
 
+  /**
+   * Validates if the chroot exists in zk (or if it is successfully created). Optionally, if create is set to true this method will create the path
+   * in case it doesn't exist
+   * @return true if the path exists or is created
+   * false if the path doesn't exist and 'create' = false
+   */
+  public static boolean checkChrootPath(String zkHost, boolean create) throws KeeperException, InterruptedException {
+    if(!containsChroot(zkHost)) {
+      return true;
+    }
+    log.info("zkHost includes chroot");
+    String chrootPath = zkHost.substring(zkHost.indexOf("/"), zkHost.length());
+    SolrZkClient tmpClient = new SolrZkClient(zkHost.substring(0, zkHost.indexOf("/")), 60*1000);
+    boolean exists = tmpClient.exists(chrootPath, true);
+    if(!exists && create) {
+      tmpClient.makePath(chrootPath, false, true);
+      exists = true;
+    }
+    tmpClient.close();
+    return exists;
+  }
+
+
+  /**
+   * Validates if zkHost contains a chroot. See http://zookeeper.apache.org/doc/r3.2.2/zookeeperProgrammers.html#ch_zkSessions
+   */
+  private static boolean containsChroot(String zkHost) {
+    return zkHost.contains("/");
+  }
+
+
   public boolean isConnected() {
     return zkClient.isConnected();
   }
@@ -582,8 +658,8 @@ public final class ZkController {
 
 
     if (log.isInfoEnabled()) {
-        log.info("Register shard - core:" + coreName + " address:"
-            + baseUrl + " shardId:" + shardId);
+        log.info("Register replica - core:" + coreName + " address:"
+            + baseUrl + " collection:" + cloudDesc.getCollectionName() + " shard:" + shardId);
     }
 
     ZkNodeProps leaderProps = new ZkNodeProps(props);
@@ -600,7 +676,11 @@ public final class ZkController {
       throw new ZooKeeperException(SolrException.ErrorCode.SERVER_ERROR, "", e);
     }
     
-    String leaderUrl = getLeader(cloudDesc);
+
+    // in this case, we want to wait for the leader as long as the leader might 
+    // wait for a vote, at least - but also long enough that a large cluster has
+    // time to get its act together
+    String leaderUrl = getLeader(cloudDesc, Integer.parseInt(leaderVoteWait) + 600000);
     
     String ourUrl = ZkCoreNodeProps.getCoreUrl(baseUrl, coreName);
     log.info("We are " + ourUrl + " and leader is " + leaderUrl);
@@ -652,7 +732,9 @@ public final class ZkController {
     return shardId;
   }
 
-  private String getLeader(final CloudDescriptor cloudDesc) {
+  // timeoutms is the timeout for the first call to get the leader - there is then
+  // a longer wait to make sure that leader matches our local state
+  private String getLeader(final CloudDescriptor cloudDesc, int timeoutms) {
     
     String collection = cloudDesc.getCollectionName();
     String shardId = cloudDesc.getShardId();
@@ -661,12 +743,13 @@ public final class ZkController {
     // cluster state node that won't be updated for a moment
     String leaderUrl;
     try {
-      leaderUrl = getLeaderProps(collection, cloudDesc.getShardId())
+      leaderUrl = getLeaderProps(collection, cloudDesc.getShardId(), timeoutms)
           .getCoreUrl();
       
       // now wait until our currently cloud state contains the latest leader
       String clusterStateLeader = zkStateReader.getLeaderUrl(collection,
-          shardId, 30000);
+          shardId, timeoutms * 2); // since we found it in zk, we are willing to
+                                   // wait a while to find it in state
       int tries = 0;
       while (!leaderUrl.equals(clusterStateLeader)) {
         if (tries == 60) {
@@ -678,8 +761,8 @@ public final class ZkController {
         Thread.sleep(1000);
         tries++;
         clusterStateLeader = zkStateReader.getLeaderUrl(collection, shardId,
-            30000);
-        leaderUrl = getLeaderProps(collection, cloudDesc.getShardId())
+            timeoutms);
+        leaderUrl = getLeaderProps(collection, cloudDesc.getShardId(), timeoutms)
             .getCoreUrl();
       }
       
@@ -695,8 +778,8 @@ public final class ZkController {
    * Get leader props directly from zk nodes.
    */
   public ZkCoreNodeProps getLeaderProps(final String collection,
-      final String slice) throws InterruptedException {
-    return getLeaderProps(collection, slice, false);
+      final String slice, int timeoutms) throws InterruptedException {
+    return getLeaderProps(collection, slice, timeoutms, false);
   }
   
   /**
@@ -705,8 +788,8 @@ public final class ZkController {
    * @return leader props
    */
   public ZkCoreNodeProps getLeaderProps(final String collection,
-      final String slice, boolean failImmediatelyOnExpiration) throws InterruptedException {
-    int iterCount = 60;
+      final String slice, int timeoutms, boolean failImmediatelyOnExpiration) throws InterruptedException {
+    int iterCount = timeoutms / 1000;
     Exception exp = null;
     while (iterCount-- > 0) {
       try {
@@ -723,10 +806,10 @@ public final class ZkController {
           throw new RuntimeException("Session has expired - could not get leader props", exp);
         }
         exp = e;
-        Thread.sleep(500);
+        Thread.sleep(1000);
       }  catch (Exception e) {
         exp = e;
-        Thread.sleep(500);
+        Thread.sleep(1000);
       }
       if (cc.isShutDown()) {
         throw new SolrException(ErrorCode.SERVICE_UNAVAILABLE, "CoreContainer is shutdown");
@@ -804,6 +887,7 @@ public final class ZkController {
    * Publish core state to overseer.
    */
   public void publish(final CoreDescriptor cd, final String state, boolean updateLastState) throws KeeperException, InterruptedException {
+    log.info("publishing core={} state={}", cd.getName(), state);
     //System.out.println(Thread.currentThread().getStackTrace()[3]);
     Integer numShards = cd.getCloudDescriptor().getNumShards();
     if (numShards == null) { //XXX sys prop hack
@@ -889,6 +973,7 @@ public final class ZkController {
 
         try {
           Map<String,Object> collectionProps = new HashMap<String,Object>();
+
           // TODO: if collection.configName isn't set, and there isn't already a conf in zk, just use that?
           String defaultConfigName = System.getProperty(COLLECTION_PARAM_PREFIX+CONFIGNAME_PROP, collection);
 
@@ -903,8 +988,10 @@ public final class ZkController {
             }
 
             // if the config name wasn't passed in, use the default
-            if (!collectionProps.containsKey(CONFIGNAME_PROP))
+            if (!collectionProps.containsKey(CONFIGNAME_PROP)) {
+              // TODO: getting the configName from the collectionPath should fail since we already know it doesn't exist?
               getConfName(collection, collectionPath, collectionProps);
+            }
             
           } else if(System.getProperty("bootstrap_confdir") != null) {
             // if we are bootstrapping a collection, default the config for
@@ -928,7 +1015,21 @@ public final class ZkController {
           } else {
             getConfName(collection, collectionPath, collectionProps);
           }
-          
+
+          if (collectionProps.get(DocCollection.DOC_ROUTER) == null) {
+            Object numShards = collectionProps.get(ZkStateReader.NUM_SHARDS_PROP);
+            if (numShards == null) {
+              numShards = System.getProperty(ZkStateReader.NUM_SHARDS_PROP);
+            }
+            if (numShards == null) {
+              collectionProps.put(DocCollection.DOC_ROUTER, ImplicitDocRouter.NAME);
+            } else {
+              collectionProps.put(DocCollection.DOC_ROUTER, DocRouter.DEFAULT_NAME);
+            }
+          }
+
+          collectionProps.remove(ZkStateReader.NUM_SHARDS_PROP);  // we don't put numShards in the collections properties
+
           ZkNodeProps zkProps = new ZkNodeProps(collectionProps);
           zkClient.makePath(collectionPath, ZkStateReader.toJSON(zkProps), CreateMode.PERSISTENT, null, true);
 
@@ -1005,7 +1106,7 @@ public final class ZkController {
 
   private String doGetShardIdProcess(String coreName, CloudDescriptor descriptor) {
     final String shardZkNodeName = getNodeName() + "_" + coreName;
-    int retryCount = 120;
+    int retryCount = 320;
     while (retryCount-- > 0) {
       final String shardId = zkStateReader.getClusterState().getShardId(
           shardZkNodeName);
@@ -1013,7 +1114,7 @@ public final class ZkController {
         return shardId;
       }
       try {
-        Thread.sleep(500);
+        Thread.sleep(1000);
       } catch (InterruptedException e) {
         Thread.currentThread().interrupt();
       }
@@ -1094,7 +1195,7 @@ public final class ZkController {
     for (int i = 0; i < retries; i++) {
       try {
         // go straight to zk, not the cloud state - we must have current info
-        leaderProps = getLeaderProps(collection, shard);
+        leaderProps = getLeaderProps(collection, shard, 30000);
         break;
       } catch (Exception e) {
         SolrException.log(log, "There was a problem finding the leader in zk", e);
@@ -1120,7 +1221,7 @@ public final class ZkController {
       HttpSolrServer server = null;
       server = new HttpSolrServer(leaderBaseUrl);
       server.setConnectionTimeout(45000);
-      server.setSoTimeout(45000);
+      server.setSoTimeout(120000);
       WaitForState prepCmd = new WaitForState();
       prepCmd.setCoreName(leaderCoreName);
       prepCmd.setNodeName(getNodeName());
@@ -1235,8 +1336,45 @@ public final class ZkController {
   }
 
   // may return null if not in zk mode
-  public ThreadPoolExecutor getCmdDistribExecutor() {
-    return cmdDistribExecutor;
+  public UpdateShardHandler getUpdateShardHandler() {
+    return updateShardHandler;
   }
 
+  /**
+   * Returns the nodeName that should be used based on the specified properties.
+   *
+   * @param hostName - must not be null or the empty string
+   * @param hostPort - must consist only of digits, must not be null or the empty string
+   * @param hostContext - should not begin or end with a slash (leading/trailin slashes will be ignored), must not be null, may be the empty string to denote the root context
+   * @lucene.experimental
+   * @see SolrZkClient#getBaseUrlForNodeName
+   */
+  static String generateNodeName(final String hostName,
+                                 final String hostPort,
+                                 final String hostContext) {
+    try {
+      return hostName + ':' + hostPort + '_' + 
+        URLEncoder.encode(trimLeadingAndTrailingSlashes(hostContext), "UTF-8");
+    } catch (UnsupportedEncodingException e) {
+      throw new IllegalStateException("JVM Does not seem to support UTF-8", e);
+    }
+  }
+  
+  /**
+   * utilitiy method fro trimming and leading and/or trailing slashes from 
+   * it's input.  May return the empty string.  May return null if and only 
+   * if the input is null.
+   */
+  private static String trimLeadingAndTrailingSlashes(final String in) {
+    if (null == in) return in;
+    
+    String out = in;
+    if (out.startsWith("/")) {
+      out = out.substring(1);
+    }
+    if (out.endsWith("/")) {
+      out = out.substring(0,out.length()-1);
+    }
+    return out;
+  }
 }

Modified: lucene/dev/branches/LUCENE-2878/solr/core/src/java/org/apache/solr/core/AbstractSolrEventListener.java
URL: http://svn.apache.org/viewvc/lucene/dev/branches/LUCENE-2878/solr/core/src/java/org/apache/solr/core/AbstractSolrEventListener.java?rev=1435287&r1=1435286&r2=1435287&view=diff
==============================================================================
--- lucene/dev/branches/LUCENE-2878/solr/core/src/java/org/apache/solr/core/AbstractSolrEventListener.java (original)
+++ lucene/dev/branches/LUCENE-2878/solr/core/src/java/org/apache/solr/core/AbstractSolrEventListener.java Fri Jan 18 18:30:54 2013
@@ -30,10 +30,12 @@ public class AbstractSolrEventListener i
   }
   protected NamedList args;
 
+  @Override
   public void init(NamedList args) {
     this.args = args;
   }
 
+  @Override
   public void postCommit() {
     throw new UnsupportedOperationException();
   }
@@ -43,6 +45,7 @@ public class AbstractSolrEventListener i
     throw new UnsupportedOperationException();
   }
 
+  @Override
   public void newSearcher(SolrIndexSearcher newSearcher, SolrIndexSearcher currentSearcher) {
     throw new UnsupportedOperationException();
   }

Modified: lucene/dev/branches/LUCENE-2878/solr/core/src/java/org/apache/solr/core/CachingDirectoryFactory.java
URL: http://svn.apache.org/viewvc/lucene/dev/branches/LUCENE-2878/solr/core/src/java/org/apache/solr/core/CachingDirectoryFactory.java?rev=1435287&r1=1435286&r2=1435287&view=diff
==============================================================================
--- lucene/dev/branches/LUCENE-2878/solr/core/src/java/org/apache/solr/core/CachingDirectoryFactory.java (original)
+++ lucene/dev/branches/LUCENE-2878/solr/core/src/java/org/apache/solr/core/CachingDirectoryFactory.java Fri Jan 18 18:30:54 2013
@@ -26,8 +26,10 @@ import java.util.Locale;
 import java.util.Map;
 
 import org.apache.lucene.store.Directory;
+import org.apache.lucene.store.IOContext.Context;
 import org.apache.lucene.store.NativeFSLockFactory;
 import org.apache.lucene.store.NoLockFactory;
+import org.apache.lucene.store.RateLimitedDirectoryWrapper;
 import org.apache.lucene.store.SimpleFSLockFactory;
 import org.apache.lucene.store.SingleInstanceLockFactory;
 import org.apache.solr.common.SolrException;
@@ -38,7 +40,7 @@ import org.slf4j.LoggerFactory;
 /**
  * A {@link DirectoryFactory} impl base class for caching Directory instances
  * per path. Most DirectoryFactory implementations will want to extend this
- * class and simply implement {@link DirectoryFactory#create(String)}.
+ * class and simply implement {@link DirectoryFactory#create(String, DirContext)}.
  * 
  */
 public abstract class CachingDirectoryFactory extends DirectoryFactory {
@@ -47,6 +49,7 @@ public abstract class CachingDirectoryFa
     public int refCnt = 1;
     public String path;
     public boolean doneWithDir = false;
+    @Override
     public String toString() {
       return "CachedDir<<" + directory.toString() + ";refCount=" + refCnt + ";path=" + path + ";done=" + doneWithDir + ">>";
     }
@@ -60,6 +63,16 @@ public abstract class CachingDirectoryFa
   protected Map<Directory,CacheValue> byDirectoryCache = new HashMap<Directory,CacheValue>();
   
   protected Map<Directory,List<CloseListener>> closeListeners = new HashMap<Directory,List<CloseListener>>();
+
+  private Double maxWriteMBPerSecFlush;
+
+  private Double maxWriteMBPerSecMerge;
+
+  private Double maxWriteMBPerSecRead;
+
+  private Double maxWriteMBPerSecDefault;
+
+  private boolean closed;
   
   public interface CloseListener {
     public void postClose();
@@ -109,6 +122,7 @@ public abstract class CachingDirectoryFa
   @Override
   public void close() throws IOException {
     synchronized (this) {
+      this.closed = true;
       for (CacheValue val : byDirectoryCache.values()) {
         try {
           // if there are still refs out, we have to wait for them
@@ -116,14 +130,15 @@ public abstract class CachingDirectoryFa
           while(val.refCnt != 0) {
             wait(100);
             
-            if (cnt++ >= 600) {
+            if (cnt++ >= 1200) {
               log.error("Timeout waiting for all directory ref counts to be released");
               break;
             }
           }
           
           assert val.refCnt == 0 : val.refCnt;
-          val.directory.close();
+          log.info("Closing directory when closing factory:" + val.path);
+          closeDirectory(val);
         } catch (Throwable t) {
           SolrException.log(log, "Error closing directory", t);
         }
@@ -135,6 +150,9 @@ public abstract class CachingDirectoryFa
   
   private void close(Directory directory) throws IOException {
     synchronized (this) {
+      // don't check if already closed here - we need to able to release
+      // while #close() waits.
+      
       CacheValue cacheValue = byDirectoryCache.get(directory);
       if (cacheValue == null) {
         throw new IllegalArgumentException("Unknown directory: " + directory
@@ -146,32 +164,45 @@ public abstract class CachingDirectoryFa
 
       if (cacheValue.refCnt == 0 && cacheValue.doneWithDir) {
         log.info("Closing directory:" + cacheValue.path);
-        List<CloseListener> listeners = closeListeners.remove(directory);
-        if (listeners != null) {
-          for (CloseListener listener : listeners) {
-            listener.preClose();
-          }
-        }
+        closeDirectory(cacheValue);
+        
+        byDirectoryCache.remove(directory);
+        byPathCache.remove(cacheValue.path);
+      }
+    }
+  }
+
+  private void closeDirectory(CacheValue cacheValue) {
+    List<CloseListener> listeners = closeListeners.remove(cacheValue.directory);
+    if (listeners != null) {
+      for (CloseListener listener : listeners) {
         try {
-          directory.close();
+          listener.preClose();
         } catch (Throwable t) {
-          SolrException.log(log, "Error closing directory", t);
+          SolrException.log(log, "Error executing preClose for directory", t);
         }
-
-        if (listeners != null) {
-          for (CloseListener listener : listeners) {
-            listener.postClose();
-          }
-          closeListeners.remove(directory);
+      }
+    }
+    try {
+      log.info("Closing directory:" + cacheValue.path);
+      cacheValue.directory.close();
+    } catch (Throwable t) {
+      SolrException.log(log, "Error closing directory", t);
+    }
+    
+    if (listeners != null) {
+      for (CloseListener listener : listeners) {
+        try {
+          listener.postClose();
+        } catch (Throwable t) {
+          SolrException.log(log, "Error executing postClose for directory", t);
         }
-        
-        byDirectoryCache.remove(directory);
-        byPathCache.remove(cacheValue.path);
       }
     }
   }
   
-  protected abstract Directory create(String path) throws IOException;
+  @Override
+  protected abstract Directory create(String path, DirContext dirContext) throws IOException;
   
   @Override
   public boolean exists(String path) {
@@ -187,9 +218,9 @@ public abstract class CachingDirectoryFa
    * java.lang.String)
    */
   @Override
-  public final Directory get(String path, String rawLockType)
+  public final Directory get(String path,  DirContext dirContext, String rawLockType)
       throws IOException {
-    return get(path, rawLockType, false);
+    return get(path, dirContext, rawLockType, false);
   }
   
   /*
@@ -199,10 +230,14 @@ public abstract class CachingDirectoryFa
    * java.lang.String, boolean)
    */
   @Override
-  public final Directory get(String path, String rawLockType, boolean forceNew)
+  public final Directory get(String path,  DirContext dirContext, String rawLockType, boolean forceNew)
       throws IOException {
     String fullPath = new File(path).getAbsolutePath();
     synchronized (this) {
+      if (closed) {
+        throw new RuntimeException("Already closed");
+      }
+      
       final CacheValue cacheValue = byPathCache.get(fullPath);
       Directory directory = null;
       if (cacheValue != null) {
@@ -229,7 +264,9 @@ public abstract class CachingDirectoryFa
       }
       
       if (directory == null || forceNew) { 
-        directory = create(fullPath);
+        directory = create(fullPath, dirContext);
+        
+        directory = rateLimit(directory);
         
         CacheValue newCacheValue = new CacheValue();
         newCacheValue.directory = directory;
@@ -247,6 +284,25 @@ public abstract class CachingDirectoryFa
       return directory;
     }
   }
+
+  private Directory rateLimit(Directory directory) {
+    if (maxWriteMBPerSecDefault != null || maxWriteMBPerSecFlush != null || maxWriteMBPerSecMerge != null || maxWriteMBPerSecRead != null) {
+      directory = new RateLimitedDirectoryWrapper(directory);
+      if (maxWriteMBPerSecDefault != null) {
+        ((RateLimitedDirectoryWrapper)directory).setMaxWriteMBPerSec(maxWriteMBPerSecDefault, Context.DEFAULT);
+      }
+      if (maxWriteMBPerSecFlush != null) {
+        ((RateLimitedDirectoryWrapper)directory).setMaxWriteMBPerSec(maxWriteMBPerSecFlush, Context.FLUSH);
+      }
+      if (maxWriteMBPerSecMerge != null) {
+        ((RateLimitedDirectoryWrapper)directory).setMaxWriteMBPerSec(maxWriteMBPerSecMerge, Context.MERGE);
+      }
+      if (maxWriteMBPerSecRead != null) {
+        ((RateLimitedDirectoryWrapper)directory).setMaxWriteMBPerSec(maxWriteMBPerSecRead, Context.READ);
+      }
+    }
+    return directory;
+  }
   
   /*
    * (non-Javadoc)
@@ -255,6 +311,7 @@ public abstract class CachingDirectoryFa
    * org.apache.solr.core.DirectoryFactory#incRef(org.apache.lucene.store.Directory
    * )
    */
+  @Override
   public void incRef(Directory directory) {
     synchronized (this) {
       CacheValue cacheValue = byDirectoryCache.get(directory);
@@ -266,7 +323,13 @@ public abstract class CachingDirectoryFa
     }
   }
   
-  public void init(NamedList args) {}
+  @Override
+  public void init(NamedList args) {
+    maxWriteMBPerSecFlush = (Double) args.get("maxWriteMBPerSecFlush");
+    maxWriteMBPerSecMerge = (Double) args.get("maxWriteMBPerSecMerge");
+    maxWriteMBPerSecRead = (Double) args.get("maxWriteMBPerSecRead");
+    maxWriteMBPerSecDefault = (Double) args.get("maxWriteMBPerSecDefault");
+  }
   
   /*
    * (non-Javadoc)

Modified: lucene/dev/branches/LUCENE-2878/solr/core/src/java/org/apache/solr/core/CodecFactory.java
URL: http://svn.apache.org/viewvc/lucene/dev/branches/LUCENE-2878/solr/core/src/java/org/apache/solr/core/CodecFactory.java?rev=1435287&r1=1435286&r2=1435287&view=diff
==============================================================================
--- lucene/dev/branches/LUCENE-2878/solr/core/src/java/org/apache/solr/core/CodecFactory.java (original)
+++ lucene/dev/branches/LUCENE-2878/solr/core/src/java/org/apache/solr/core/CodecFactory.java Fri Jan 18 18:30:54 2013
@@ -25,6 +25,7 @@ import org.apache.solr.util.plugin.Named
  * Factory for plugging in a custom {@link Codec}
  */
 public abstract class CodecFactory implements NamedListInitializedPlugin {
+  @Override
   public void init(NamedList args) {  
   }
   

Modified: lucene/dev/branches/LUCENE-2878/solr/core/src/java/org/apache/solr/core/CoreContainer.java
URL: http://svn.apache.org/viewvc/lucene/dev/branches/LUCENE-2878/solr/core/src/java/org/apache/solr/core/CoreContainer.java?rev=1435287&r1=1435286&r2=1435287&view=diff
==============================================================================
--- lucene/dev/branches/LUCENE-2878/solr/core/src/java/org/apache/solr/core/CoreContainer.java (original)
+++ lucene/dev/branches/LUCENE-2878/solr/core/src/java/org/apache/solr/core/CoreContainer.java Fri Jan 18 18:30:54 2013
@@ -41,8 +41,7 @@ import java.util.concurrent.ConcurrentHa
 import java.util.concurrent.ExecutionException;
 import java.util.concurrent.ExecutorCompletionService;
 import java.util.concurrent.Future;
-import java.util.concurrent.RejectedExecutionException;
-import java.util.concurrent.SynchronousQueue;
+import java.util.concurrent.LinkedBlockingQueue;
 import java.util.concurrent.ThreadPoolExecutor;
 import java.util.concurrent.TimeUnit;
 import java.util.concurrent.TimeoutException;
@@ -78,7 +77,6 @@ import org.apache.solr.logging.LogWatche
 import org.apache.solr.logging.jul.JulWatcher;
 import org.apache.solr.schema.IndexSchema;
 import org.apache.solr.update.SolrCoreState;
-import org.apache.solr.util.AdjustableSemaphore;
 import org.apache.solr.util.DOMUtil;
 import org.apache.solr.util.DefaultSolrThreadFactory;
 import org.apache.solr.util.FileUtils;
@@ -114,21 +112,24 @@ public class CoreContainer 
   private static final String CORE_CONFIG = "config";
   private static final String CORE_INSTDIR = "instanceDir";
   private static final String CORE_DATADIR = "dataDir";
+  private static final String CORE_ULOGDIR = "ulogDir";
   private static final String CORE_SCHEMA = "schema";
   private static final String CORE_SHARD = "shard";
   private static final String CORE_COLLECTION = "collection";
   private static final String CORE_ROLES = "roles";
   private static final String CORE_PROPERTIES = "properties";
   private static final String CORE_LOADONSTARTUP = "loadOnStartup";
-  private static final String CORE_SWAPPABLE = "swappable";
+  private static final String CORE_TRANSIENT = "transient";
 
 
   protected final Map<String, SolrCore> cores = new LinkedHashMap<String, SolrCore>(); // For "permanent" cores
 
-  protected Map<String, SolrCore> swappableCores = new LinkedHashMap<String, SolrCore>(); // For "lazily loaded" cores
+  protected Map<String, SolrCore> transientCores = new LinkedHashMap<String, SolrCore>(); // For "lazily loaded" cores
 
   protected final Map<String, CoreDescriptor> dynamicDescriptors = new LinkedHashMap<String, CoreDescriptor>();
 
+  protected final Set<String> pendingDynamicCoreLoads = new HashSet<String>();
+
   protected final Map<String,Exception> coreInitFailures = 
     Collections.synchronizedMap(new LinkedHashMap<String,Exception>());
   
@@ -158,8 +159,10 @@ public class CoreContainer 
   protected LogWatcher logging = null;
   private String zkHost;
   private Map<SolrCore,String> coreToOrigName = new ConcurrentHashMap<SolrCore,String>();
-  private String leaderVoteWait;
-  protected int swappableCacheSize = Integer.MAX_VALUE; // Use as a flag too, if swappableCacheSize set in solr.xml this will be changed
+  private String leaderVoteWait = LEADER_VOTE_WAIT;
+  private int distribUpdateConnTimeout = 0;
+  private int distribUpdateSoTimeout = 0;
+  protected int transientCacheSize = Integer.MAX_VALUE; // Use as a flag too, if transientCacheSize set in solr.xml this will be changed
   private int coreLoadThreads;
   
   {
@@ -242,20 +245,30 @@ public class CoreContainer 
         } else {
           log.info("Zookeeper client=" + zookeeperHost);          
         }
-        zkController = new ZkController(this, zookeeperHost, zkClientTimeout, zkClientConnectTimeout, host, hostPort, hostContext, leaderVoteWait, new CurrentCoreDescriptorProvider() {
-          
-          @Override
-          public List<CoreDescriptor> getCurrentDescriptors() {
-            List<CoreDescriptor> descriptors = new ArrayList<CoreDescriptor>(getCoreNames().size());
-            for (SolrCore core : getCores()) {
-              descriptors.add(core.getCoreDescriptor());
-            }
-            return descriptors;
-          }
-        });        
-
         String confDir = System.getProperty("bootstrap_confdir");
-        boolean boostrapConf = Boolean.getBoolean("bootstrap_conf");
+        boolean boostrapConf = Boolean.getBoolean("bootstrap_conf");  
+        
+        if(!ZkController.checkChrootPath(zookeeperHost, (confDir!=null) || boostrapConf)) {
+          throw new ZooKeeperException(SolrException.ErrorCode.SERVER_ERROR,
+              "A chroot was specified in ZkHost but the znode doesn't exist. ");
+        }
+        
+        zkController = new ZkController(this, zookeeperHost, zkClientTimeout,
+            zkClientConnectTimeout, host, hostPort, hostContext,
+            leaderVoteWait, distribUpdateConnTimeout, distribUpdateSoTimeout,
+            new CurrentCoreDescriptorProvider() {
+              
+              @Override
+              public List<CoreDescriptor> getCurrentDescriptors() {
+                List<CoreDescriptor> descriptors = new ArrayList<CoreDescriptor>(
+                    getCoreNames().size());
+                for (SolrCore core : getCores()) {
+                  descriptors.add(core.getCoreDescriptor());
+                }
+                return descriptors;
+              }
+            });
+        
         
         if (zkRun != null && zkServer.getServers().size() > 1 && confDir == null && boostrapConf == false) {
           // we are part of an ensemble and we are not uploading the config - pause to give the config time
@@ -360,14 +373,14 @@ public class CoreContainer 
     return p;
   }
 
-  // Trivial helper method for load, note it implements LRU on swappable cores
+  // Trivial helper method for load, note it implements LRU on transient cores
   private void allocateLazyCores(Config cfg) {
-    swappableCacheSize = cfg.getInt("solr/cores/@swappableCacheSize", Integer.MAX_VALUE);
-    if (swappableCacheSize != Integer.MAX_VALUE) {
-      swappableCores = new LinkedHashMap<String, SolrCore>(swappableCacheSize, 0.75f, true) {
+    transientCacheSize = cfg.getInt("solr/cores/@transientCacheSize", Integer.MAX_VALUE);
+    if (transientCacheSize != Integer.MAX_VALUE) {
+      transientCores = new LinkedHashMap<String, SolrCore>(transientCacheSize, 0.75f, true) {
         @Override
         protected boolean removeEldestEntry(Map.Entry<String, SolrCore> eldest) {
-          if (size() > swappableCacheSize) {
+          if (size() > transientCacheSize) {
             eldest.getValue().close();
             return true;
           }
@@ -421,6 +434,8 @@ public class CoreContainer 
     // now.
     cfg.substituteProperties();
     
+    initShardHandler(cfg);
+    
     allocateLazyCores(cfg);
     
     // Initialize Logging
@@ -446,6 +461,9 @@ public class CoreContainer 
       if (fname != null) {
         if ("JUL".equalsIgnoreCase(fname)) {
           logging = new JulWatcher(slf4jImpl);
+//      else if( "Log4j".equals(fname) ) {
+//        logging = new Log4jWatcher(slf4jImpl);
+//      }
         } else {
           try {
             logging = loader.newInstance(fname, LogWatcher.class);
@@ -480,6 +498,9 @@ public class CoreContainer 
     zkClientTimeout = cfg.getInt("solr/cores/@zkClientTimeout",
         DEFAULT_ZK_CLIENT_TIMEOUT);
     
+    distribUpdateConnTimeout = cfg.getInt("solr/cores/@distribUpdateConnTimeout", 0);
+    distribUpdateSoTimeout = cfg.getInt("solr/cores/@distribUpdateSoTimeout", 0);
+    
     hostPort = cfg.get("solr/cores/@hostPort", DEFAULT_HOST_PORT);
     
     hostContext = cfg.get("solr/cores/@hostContext", DEFAULT_HOST_CONTEXT);
@@ -529,14 +550,11 @@ public class CoreContainer 
         XPathConstants.NODESET);
     
     // setup executor to load cores in parallel
-    coreLoadExecutor = new ThreadPoolExecutor(0, Integer.MAX_VALUE, 5,
-        TimeUnit.SECONDS, new SynchronousQueue<Runnable>(),
+    coreLoadExecutor = new ThreadPoolExecutor(coreLoadThreads, coreLoadThreads, 1,
+        TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>(),
         new DefaultSolrThreadFactory("coreLoadExecutor"));
     try {
-      // 4 threads at a time max
-      final AdjustableSemaphore semaphore = new AdjustableSemaphore(
-          coreLoadThreads);
-      
+
       CompletionService<SolrCore> completionService = new ExecutorCompletionService<SolrCore>(
           coreLoadExecutor);
       Set<Future<SolrCore>> pending = new HashSet<Future<SolrCore>>();
@@ -595,49 +613,42 @@ public class CoreContainer 
                 .equalsIgnoreCase(opt)) ? true : false);
           }
           
-          opt = DOMUtil.getAttr(node, CORE_SWAPPABLE, null);
+          opt = DOMUtil.getAttr(node, CORE_TRANSIENT, null);
           if (opt != null) {
-            p.setSwappable(("true".equalsIgnoreCase(opt) || "on"
+            p.setTransient(("true".equalsIgnoreCase(opt) || "on"
                 .equalsIgnoreCase(opt)) ? true : false);
           }
           
-          if (!p.isSwappable() && p.isLoadOnStartup()) { // Just like current
-                                                         // case.
+          if (p.isLoadOnStartup()) { // The normal case
+
             Callable<SolrCore> task = new Callable<SolrCore>() {
+              @Override
               public SolrCore call() {
                 SolrCore c = null;
                 try {
                   c = create(p);
-                  register(name, c, false);
+                  if (p.isTransient()) {
+                    registerLazyCore(name, c, false);
+                  } else {
+                    register(name, c, false);
+                  }
+
                 } catch (Throwable t) {
                   SolrException.log(log, null, t);
                   if (c != null) {
                     c.close();
                   }
                 }
-                semaphore.release();
-                
                 return c;
               }
             };
-            
-            try {
-              semaphore.acquire();
-            } catch (InterruptedException e) {
-              Thread.currentThread().interrupt();
-              throw new SolrException(ErrorCode.SERVER_ERROR,
-                  "Interrupted while loading SolrCore(s)", e);
-            }
-            
-            try {
-              pending.add(completionService.submit(task));
-            } catch (RejectedExecutionException e) {
-              semaphore.release();
-              throw e;
-            }
+
+
+            pending.add(completionService.submit(task));
+
             
           } else {
-            // Store it away for later use. includes non-swappable but not
+            // Store it away for later use. includes non-transient but not
             // loaded at startup cores.
             dynamicDescriptors.put(rawName, p);
           }
@@ -659,14 +670,12 @@ public class CoreContainer 
               coreToOrigName.put(c, c.getName());
             }
           } catch (ExecutionException e) {
-            // shouldn't happen since we catch exceptions ourselves
-            SolrException.log(SolrCore.log,
-                "error sending update request to shard", e);
+            SolrException.log(SolrCore.log, "error loading core", e);
           }
           
         } catch (InterruptedException e) {
           throw new SolrException(SolrException.ErrorCode.SERVICE_UNAVAILABLE,
-              "interrupted waiting for shard update response", e);
+              "interrupted while loading core", e);
         }
       }
     } finally {
@@ -676,6 +685,27 @@ public class CoreContainer 
     }
   }
 
+  protected void initShardHandler(Config cfg) {
+    PluginInfo info = null;
+    if (cfg != null) {
+      Node shfn = cfg.getNode("solr/cores/shardHandlerFactory", false);
+  
+      if (shfn != null) {
+        info = new PluginInfo(shfn, "shardHandlerFactory", false, true);
+      } else {
+        Map m = new HashMap();
+        m.put("class",HttpShardHandlerFactory.class.getName());
+        info = new PluginInfo("shardHandlerFactory", m, null, Collections.<PluginInfo>emptyList());
+      }
+    }
+
+    HttpShardHandlerFactory fac = new HttpShardHandlerFactory();
+    if (info != null) {
+      fac.init(info);
+    }
+    shardHandlerFactory = fac;
+  }
+
   private Document copyDoc(Document document) throws TransformerException {
     TransformerFactory tfactory = TransformerFactory.newInstance();
     Transformer tx   = tfactory.newTransformer();
@@ -727,15 +757,15 @@ public class CoreContainer 
         }
         cores.clear();
       }
-      synchronized (swappableCores) {
-        for (SolrCore core : swappableCores.values()) {
+      synchronized (transientCores) {
+        for (SolrCore core : transientCores.values()) {
           try {
             core.close();
           } catch (Throwable t) {
             SolrException.log(log, "Error shutting down core", t);
           }
         }
-        swappableCores.clear();
+        transientCores.clear();
       }
     } finally {
       if (shardHandlerFactory != null) {
@@ -794,7 +824,7 @@ public class CoreContainer 
   }
 
   protected SolrCore registerLazyCore(String name, SolrCore core, boolean returnPrevNotClosed) {
-    return registerCore(swappableCores, name, core, returnPrevNotClosed);
+    return registerCore(transientCores, name, core, returnPrevNotClosed);
   }
 
   protected SolrCore registerCore(Map<String,SolrCore> whichCores, String name, SolrCore core, boolean returnPrevNotClosed) {
@@ -1029,8 +1059,8 @@ public class CoreContainer 
     synchronized (cores) {
       lst.addAll(this.cores.keySet());
     }
-    synchronized (swappableCores) {
-      lst.addAll(this.swappableCores.keySet());
+    synchronized (transientCores) {
+      lst.addAll(this.transientCores.keySet());
     }
     return lst;
   }
@@ -1047,8 +1077,8 @@ public class CoreContainer 
         }
       }
     }
-    synchronized (swappableCores) {
-      for (Map.Entry<String,SolrCore> entry : swappableCores.entrySet()) {
+    synchronized (transientCores) {
+      for (Map.Entry<String,SolrCore> entry : transientCores.entrySet()) {
         if (core == entry.getValue()) {
           lst.add(entry.getKey());
         }
@@ -1217,49 +1247,84 @@ public class CoreContainer 
       }
     }
   }
-  
-  /** Gets a core by name and increase its refcount.
-   * @see SolrCore#close() 
-   * @param name the core name
-   * @return the core if found
-   */
-  public SolrCore getCore(String name) {
-    name = checkDefault(name);
-    // Do this in two phases since we don't want to lock access to the cores over a load.
+  private SolrCore getCoreFromAnyList(String name) {
     SolrCore core;
-
     synchronized (cores) {
       core = cores.get(name);
       if (core != null) {
-        core.open();
+        core.open();    // increment the ref count while still synchronized
         return core;
       }
     }
 
-    if (dynamicDescriptors.size() == 0) return null; // Nobody even tried to define any swappable cores, so we're done.
+    if (dynamicDescriptors.size() == 0) return null; // Nobody even tried to define any transient cores, so we're done.
 
-    // Now look for already loaded swappable cores.
-    synchronized (swappableCores) {
-      core = swappableCores.get(name);
+    // Now look for already loaded transient cores.
+    synchronized (transientCores) {
+      core = transientCores.get(name);
       if (core != null) {
         core.open();
         return core;
       }
     }
+    return null;
+  }
+  /** Gets a core by name and increase its refcount.
+   * @see SolrCore#close() 
+   * @param name the core name
+   * @return the core if found
+   */
+  public SolrCore getCore(String name) {
+    name = checkDefault(name);
+    // Do this in two phases since we don't want to lock access to the cores over a load.
+    SolrCore core = getCoreFromAnyList(name);
+
+    if (core != null) return core;
+
+    // OK, it's not presently in any list, is it in the list of dynamic cores but not loaded yet? If so, load it.
     CoreDescriptor desc =  dynamicDescriptors.get(name);
-    if (desc == null) { //Nope, no swappable core with this name
+    if (desc == null) { //Nope, no transient core with this name
       return null;
     }
+
+    // Keep multiple threads from loading the same core at the same time.
     try {
-      core = create(desc); // This should throw an error if it fails.
-      core.open();
-      if (desc.isSwappable()) {
-        registerLazyCore(name, core, false);    // This is a swappable core
-      } else {
-        register(name, core, false); // This is a "permanent", although deferred-load core
+      boolean isPending;
+      synchronized (pendingDynamicCoreLoads) {
+        isPending = pendingDynamicCoreLoads.contains(name);
+        if (! isPending) {
+          pendingDynamicCoreLoads.add(name);
+        }
       }
-    } catch (Exception ex) {
-      throw recordAndThrow(name, "Unable to create core" + name, ex);
+
+      while (isPending) {
+        try {
+          Thread.sleep(100);
+        } catch (InterruptedException e) {
+          return null; // Seems best not to do anything at all if the thread is interrupted
+        }
+
+        synchronized (pendingDynamicCoreLoads) {
+          if (!pendingDynamicCoreLoads.contains(name)) {
+            // NOTE: If, for some reason, the load failed, we'll return null here and presumably the log will show
+            // why. We'll fail all over again next time if the problem isn't corrected.
+            return getCoreFromAnyList(name);
+          }
+        }
+      }
+      try {
+        core = create(desc); // This should throw an error if it fails.
+        core.open();
+        if (desc.isTransient()) {
+          registerLazyCore(name, core, false);    // This is a transient core
+        } else {
+          register(name, core, false); // This is a "permanent", although deferred-load core
+        }
+      } catch (Exception ex) {
+        throw recordAndThrow(name, "Unable to create core" + name, ex);
+      }
+    } finally {
+      pendingDynamicCoreLoads.remove(name);
     }
     return core;
   }
@@ -1363,8 +1428,8 @@ public class CoreContainer 
       coresAttribs.put("defaultCoreName", defaultCoreName);
     }
 
-    if (swappableCacheSize != Integer.MAX_VALUE) {
-      coresAttribs.put("swappableCacheSize", Integer.toString(swappableCacheSize));
+    if (transientCacheSize != Integer.MAX_VALUE) {
+      coresAttribs.put("transientCacheSize", Integer.toString(transientCacheSize));
     }
     
     addCoresAttrib(coresAttribs, "hostPort", this.hostPort, DEFAULT_HOST_PORT);
@@ -1442,8 +1507,10 @@ public class CoreContainer 
         addCoreProperty(coreAttribs, coreNode, CORE_SCHEMA, schema, dcore.getDefaultSchemaName());
         
         String dataDir = dcore.dataDir;
+        String ulogDir = dcore.ulogDir;
         addCoreProperty(coreAttribs, coreNode, CORE_DATADIR, dataDir, null);
-        addCoreProperty(coreAttribs, coreNode, CORE_SWAPPABLE, Boolean.toString(dcore.isSwappable()), null);
+        addCoreProperty(coreAttribs, coreNode, CORE_ULOGDIR, ulogDir, null);
+        addCoreProperty(coreAttribs, coreNode, CORE_TRANSIENT, Boolean.toString(dcore.isTransient()), null);
         addCoreProperty(coreAttribs, coreNode, CORE_LOADONSTARTUP, Boolean.toString(dcore.isLoadOnStartup()), null);
 
         CloudDescriptor cd = dcore.getCloudDescriptor();
@@ -1555,18 +1622,7 @@ public class CoreContainer 
 
   /** The default ShardHandlerFactory used to communicate with other solr instances */
   public ShardHandlerFactory getShardHandlerFactory() {
-    synchronized (this) {
-      if (shardHandlerFactory == null) {
-        Map m = new HashMap();
-        m.put("class",HttpShardHandlerFactory.class.getName());
-        PluginInfo info = new PluginInfo("shardHandlerFactory", m,null,Collections.<PluginInfo>emptyList());
-
-        HttpShardHandlerFactory fac = new HttpShardHandlerFactory();
-        fac.init(info);
-        shardHandlerFactory = fac;
-      }
-      return shardHandlerFactory;
-    }
+    return shardHandlerFactory;
   }
   
   private SolrConfig getSolrConfigFromZk(String zkConfigName, String solrConfigFileName,
@@ -1607,10 +1663,15 @@ public class CoreContainer 
     return schema;
   }
   
-  private static final String DEF_SOLR_XML ="<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n" +
-          "<solr persistent=\"false\">\n" +
-          "  <cores adminPath=\"/admin/cores\" defaultCoreName=\"" + DEFAULT_DEFAULT_CORE_NAME + "\">\n" +
-          "    <core name=\""+ DEFAULT_DEFAULT_CORE_NAME + "\" shard=\"${shard:}\" instanceDir=\"collection1\" />\n" +
-          "  </cores>\n" +
-          "</solr>";
+  private static final String DEF_SOLR_XML = "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n"
+      + "<solr persistent=\"false\">\n"
+      + "  <cores adminPath=\"/admin/cores\" defaultCoreName=\""
+      + DEFAULT_DEFAULT_CORE_NAME
+      + "\""
+      + " host=\"${host:}\" hostPort=\"${hostPort:}\" hostContext=\"${hostContext:}\" zkClientTimeout=\"${zkClientTimeout:15000}\""
+      + ">\n"
+      + "    <core name=\""
+      + DEFAULT_DEFAULT_CORE_NAME
+      + "\" shard=\"${shard:}\" collection=\"${collection:}\" instanceDir=\"collection1\" />\n"
+      + "  </cores>\n" + "</solr>";
 }

Modified: lucene/dev/branches/LUCENE-2878/solr/core/src/java/org/apache/solr/core/CoreDescriptor.java
URL: http://svn.apache.org/viewvc/lucene/dev/branches/LUCENE-2878/solr/core/src/java/org/apache/solr/core/CoreDescriptor.java?rev=1435287&r1=1435286&r2=1435287&view=diff
==============================================================================
--- lucene/dev/branches/LUCENE-2878/solr/core/src/java/org/apache/solr/core/CoreDescriptor.java (original)
+++ lucene/dev/branches/LUCENE-2878/solr/core/src/java/org/apache/solr/core/CoreDescriptor.java Fri Jan 18 18:30:54 2013
@@ -31,13 +31,14 @@ public class CoreDescriptor {
   protected String name;
   protected String instanceDir;
   protected String dataDir;
+  protected String ulogDir;
   protected String configName;
   protected String propertiesName;
   protected String schemaName;
   private final CoreContainer coreContainer;
   private Properties coreProperties;
   private boolean loadOnStartup = true;
-  private boolean swappable = false;
+  private boolean isTransient = false;
 
 
   private CloudDescriptor cloudDesc;
@@ -218,11 +219,19 @@ public class CoreDescriptor {
     this.loadOnStartup = loadOnStartup;
   }
 
-  public boolean isSwappable() {
-    return swappable;
+  public boolean isTransient() {
+    return isTransient;
   }
 
-  public void setSwappable(boolean swappable) {
-    this.swappable = swappable;
+  public void setTransient(boolean aTransient) {
+    this.isTransient = aTransient;
+  }
+
+  public String getUlogDir() {
+    return ulogDir;
+  }
+
+  public void setUlogDir(String ulogDir) {
+    this.ulogDir = ulogDir;
   }
 }

Modified: lucene/dev/branches/LUCENE-2878/solr/core/src/java/org/apache/solr/core/DirectoryFactory.java
URL: http://svn.apache.org/viewvc/lucene/dev/branches/LUCENE-2878/solr/core/src/java/org/apache/solr/core/DirectoryFactory.java?rev=1435287&r1=1435286&r2=1435287&view=diff
==============================================================================
--- lucene/dev/branches/LUCENE-2878/solr/core/src/java/org/apache/solr/core/DirectoryFactory.java (original)
+++ lucene/dev/branches/LUCENE-2878/solr/core/src/java/org/apache/solr/core/DirectoryFactory.java Fri Jan 18 18:30:54 2013
@@ -21,6 +21,7 @@ import java.io.Closeable;
 import java.io.IOException;
 
 import org.apache.lucene.store.Directory;
+import org.apache.lucene.store.FlushInfo;
 import org.apache.lucene.store.IOContext;
 import org.apache.solr.common.SolrException;
 import org.apache.solr.core.CachingDirectoryFactory.CloseListener;
@@ -34,7 +35,15 @@ import org.slf4j.LoggerFactory;
  */
 public abstract class DirectoryFactory implements NamedListInitializedPlugin,
     Closeable {
-  
+
+  // Estimate 10M docs, 100GB size, to avoid caching by NRTCachingDirectory
+  // Stayed away from upper bounds of the int/long in case any other code tried to aggregate these numbers.
+  // A large estimate should currently have no other side effects.
+  public static final IOContext IOCONTEXT_NO_CACHE = new IOContext(new FlushInfo(10*1000*1000, 100L*1000*1000*1000));
+
+  // hint about what the directory contains - default is index directory
+  public enum DirContext {DEFAULT, META_DATA}
+
   private static final Logger log = LoggerFactory.getLogger(DirectoryFactory.class.getName());
   
   /**
@@ -56,6 +65,7 @@ public abstract class DirectoryFactory i
    * 
    * @throws IOException If there is a low-level I/O error.
    */
+  @Override
   public abstract void close() throws IOException;
   
   /**
@@ -63,7 +73,7 @@ public abstract class DirectoryFactory i
    * 
    * @throws IOException If there is a low-level I/O error.
    */
-  protected abstract Directory create(String path) throws IOException;
+  protected abstract Directory create(String path,  DirContext dirContext) throws IOException;
   
   /**
    * Returns true if a Directory exists for a given path.
@@ -81,12 +91,22 @@ public abstract class DirectoryFactory i
   public abstract void remove(Directory dir) throws IOException;
   
   /**
+   * This remove is special in that it may be called even after
+   * the factory has been closed. Remove only makes sense for
+   * persistent directory factories.
+   * 
+   * @param path to remove
+   * @throws IOException If there is a low-level I/O error.
+   */
+  public abstract void remove(String path) throws IOException;
+  
+  /**
    * Override for more efficient moves.
    * 
    * @throws IOException If there is a low-level I/O error.
    */
-  public void move(Directory fromDir, Directory toDir, String fileName) throws IOException {
-    fromDir.copy(toDir, fileName, fileName, IOContext.DEFAULT);
+  public void move(Directory fromDir, Directory toDir, String fileName, IOContext ioContext) throws IOException {
+    fromDir.copy(toDir, fileName, fileName, ioContext);
     fromDir.deleteFile(fileName);
   }
   
@@ -100,7 +120,7 @@ public abstract class DirectoryFactory i
    * 
    * @throws IOException If there is a low-level I/O error.
    */
-  public abstract Directory get(String path, String rawLockType)
+  public abstract Directory get(String path, DirContext dirContext, String rawLockType)
       throws IOException;
   
   /**
@@ -112,7 +132,7 @@ public abstract class DirectoryFactory i
    * 
    * @throws IOException If there is a low-level I/O error.
    */
-  public abstract Directory get(String path, String rawLockType,
+  public abstract Directory get(String path,  DirContext dirContext, String rawLockType,
       boolean forceNew) throws IOException;
   
   /**
@@ -122,6 +142,12 @@ public abstract class DirectoryFactory i
    */
   public abstract void incRef(Directory directory);
   
+  
+  /**
+   * @return true if data is kept after close.
+   */
+  public abstract boolean isPersistent();
+  
   /**
    * Releases the Directory so that it may be closed when it is no longer
    * referenced.
@@ -158,7 +184,7 @@ public abstract class DirectoryFactory i
   
   public static long sizeOf(Directory directory, String file) throws IOException {
     if (!directory.fileExists(file)) {
-      throw new IllegalArgumentException(file + " does not exist");
+      return 0;
     }
     
     return directory.fileLength(file);

Modified: lucene/dev/branches/LUCENE-2878/solr/core/src/java/org/apache/solr/core/EphemeralDirectoryFactory.java
URL: http://svn.apache.org/viewvc/lucene/dev/branches/LUCENE-2878/solr/core/src/java/org/apache/solr/core/EphemeralDirectoryFactory.java?rev=1435287&r1=1435286&r2=1435287&view=diff
==============================================================================
--- lucene/dev/branches/LUCENE-2878/solr/core/src/java/org/apache/solr/core/EphemeralDirectoryFactory.java (original)
+++ lucene/dev/branches/LUCENE-2878/solr/core/src/java/org/apache/solr/core/EphemeralDirectoryFactory.java Fri Jan 18 18:30:54 2013
@@ -44,12 +44,21 @@ public abstract class EphemeralDirectory
     }
   }
   
+  public boolean isPersistent() {
+    return false;
+  }
+  
   @Override
   public void remove(Directory dir) throws IOException {
     // ram dir does not persist its dir anywhere
   }
   
   @Override
+  public void remove(String path) throws IOException {
+    // ram dir does not persist its dir anywhere
+  }
+  
+  @Override
   public String normalize(String path) throws IOException {
     return path;
   }

Modified: lucene/dev/branches/LUCENE-2878/solr/core/src/java/org/apache/solr/core/IndexDeletionPolicyWrapper.java
URL: http://svn.apache.org/viewvc/lucene/dev/branches/LUCENE-2878/solr/core/src/java/org/apache/solr/core/IndexDeletionPolicyWrapper.java?rev=1435287&r1=1435286&r2=1435287&view=diff
==============================================================================
--- lucene/dev/branches/LUCENE-2878/solr/core/src/java/org/apache/solr/core/IndexDeletionPolicyWrapper.java (original)
+++ lucene/dev/branches/LUCENE-2878/solr/core/src/java/org/apache/solr/core/IndexDeletionPolicyWrapper.java Fri Jan 18 18:30:54 2013
@@ -124,6 +124,7 @@ public class IndexDeletionPolicyWrapper 
   /**
    * Internal use for Lucene... do not explicitly call.
    */
+  @Override
   public void onInit(List list) throws IOException {
     List<IndexCommitWrapper> wrapperList = wrap(list);
     deletionPolicy.onInit(wrapperList);
@@ -134,6 +135,7 @@ public class IndexDeletionPolicyWrapper 
   /**
    * Internal use for Lucene... do not explicitly call.
    */
+  @Override
   public void onCommit(List list) throws IOException {
     List<IndexCommitWrapper> wrapperList = wrap(list);
     deletionPolicy.onCommit(wrapperList);

Modified: lucene/dev/branches/LUCENE-2878/solr/core/src/java/org/apache/solr/core/IndexReaderFactory.java
URL: http://svn.apache.org/viewvc/lucene/dev/branches/LUCENE-2878/solr/core/src/java/org/apache/solr/core/IndexReaderFactory.java?rev=1435287&r1=1435286&r2=1435287&view=diff
==============================================================================
--- lucene/dev/branches/LUCENE-2878/solr/core/src/java/org/apache/solr/core/IndexReaderFactory.java (original)
+++ lucene/dev/branches/LUCENE-2878/solr/core/src/java/org/apache/solr/core/IndexReaderFactory.java Fri Jan 18 18:30:54 2013
@@ -39,6 +39,7 @@ public abstract class IndexReaderFactory
    * when declaring an indexReaderFactory in solrconfig.xml
    *
    */
+  @Override
   public void init(NamedList args) {
     Integer v = (Integer)args.get("setTermIndexDivisor");
     if (v != null) {

Modified: lucene/dev/branches/LUCENE-2878/solr/core/src/java/org/apache/solr/core/JmxMonitoredMap.java
URL: http://svn.apache.org/viewvc/lucene/dev/branches/LUCENE-2878/solr/core/src/java/org/apache/solr/core/JmxMonitoredMap.java?rev=1435287&r1=1435286&r2=1435287&view=diff
==============================================================================
--- lucene/dev/branches/LUCENE-2878/solr/core/src/java/org/apache/solr/core/JmxMonitoredMap.java (original)
+++ lucene/dev/branches/LUCENE-2878/solr/core/src/java/org/apache/solr/core/JmxMonitoredMap.java Fri Jan 18 18:30:54 2013
@@ -215,6 +215,7 @@ public class JmxMonitoredMap<K, V> exten
       this.coreHashCode = coreHashCode;
     }
 
+    @Override
     public MBeanInfo getMBeanInfo() {
       ArrayList<MBeanAttributeInfo> attrInfoList = new ArrayList<MBeanAttributeInfo>();
 
@@ -273,6 +274,7 @@ public class JmxMonitoredMap<K, V> exten
       return null;
     }
 
+    @Override
     public Object getAttribute(String attribute)
             throws AttributeNotFoundException, MBeanException, ReflectionException {
       Object val;
@@ -307,6 +309,7 @@ public class JmxMonitoredMap<K, V> exten
       return null;
     }
 
+    @Override
     public AttributeList getAttributes(String[] attributes) {
       AttributeList list = new AttributeList();
       for (String attribute : attributes) {
@@ -320,16 +323,19 @@ public class JmxMonitoredMap<K, V> exten
       return list;
     }
 
+    @Override
     public void setAttribute(Attribute attribute)
             throws AttributeNotFoundException, InvalidAttributeValueException,
             MBeanException, ReflectionException {
       throw new UnsupportedOperationException("Operation not Supported");
     }
 
+    @Override
     public AttributeList setAttributes(AttributeList attributes) {
       throw new UnsupportedOperationException("Operation not Supported");
     }
 
+    @Override
     public Object invoke(String actionName, Object[] params, String[] signature)
             throws MBeanException, ReflectionException {
       throw new UnsupportedOperationException("Operation not Supported");