Apache Solr open-source search software
SORL-5609 Don't let cores create slices/named replicas , SOLR-5130 addReplica Collections API
Noble Paul79e9707ce7dc
diff --git a/solr/core/src/java/org/apache/solr/cloud/Overseer.java b/solr/core/src/java/org/apache/solr/cloud/Overseer.javaindex 26484975b0f..48348581a09 100644--- a/solr/core/src/java/org/apache/solr/cloud/Overseer.java+++ b/solr/core/src/java/org/apache/solr/cloud/Overseer.java@@ -47,6 +47,9 @@ import org.slf4j.Logger;import org.slf4j.LoggerFactory;import static java.util.Collections.singletonMap;+import static org.apache.solr.common.cloud.ZkNodeProps.makeMap;+import static org.apache.solr.common.params.CollectionParams.CollectionAction.ADDREPLICA;+import static org.apache.solr.common.params.CollectionParams.CollectionAction.CLUSTERPROP;/*** Cluster leader. Responsible node assignments, cluster state file?@@ -66,7 +69,7 @@ public class Overseer {static enum LeaderStatus { DONT_KNOW, NO, YES };private long lastUpdatedTime = 0;-+private class ClusterStateUpdater implements Runnable, ClosableThread {private final ZkStateReader reader;@@ -78,13 +81,15 @@ public class Overseer {//If Overseer dies while extracting the main queue a new overseer will start from this queueprivate final DistributedQueue workQueue;private volatile boolean isClosed;-+ private Map clusterProps;+public ClusterStateUpdater(final ZkStateReader reader, final String myId) {this.zkClient = reader.getZkClient();this.stateUpdateQueue = getInQueue(zkClient);this.workQueue = getInternalQueue(zkClient);this.myId = myId;this.reader = reader;+ clusterProps = reader.getClusterProps();}@Override@@ -221,7 +226,11 @@ public class Overseer {private ClusterState processMessage(ClusterState clusterState,final ZkNodeProps message, final String operation) {if ("state".equals(operation)) {- clusterState = updateState(clusterState, message);+ if( isLegacy( clusterProps )) {+ clusterState = updateState(clusterState, message);+ } else {+ clusterState = updateStateNew(clusterState, message);+ }} else if (DELETECORE.equals(operation)) {clusterState = removeCore(clusterState, message);} else if (REMOVECOLLECTION.equals(operation)) {@@ -248,16 +257,59 @@ public class Overseer {clusterState = updateShardState(clusterState, message);} else if (OverseerCollectionProcessor.CREATECOLLECTION.equals(operation)) {clusterState = buildCollection(clusterState, message);+ } else if(ADDREPLICA.isEqual(operation)){+ clusterState = createReplica(clusterState, message);} else if (Overseer.ADD_ROUTING_RULE.equals(operation)) {clusterState = addRoutingRule(clusterState, message);} else if (Overseer.REMOVE_ROUTING_RULE.equals(operation)) {clusterState = removeRoutingRule(clusterState, message);+ } else if(CLUSTERPROP.isEqual(operation)){+ handleProp(message);} else {throw new RuntimeException("unknown operation:" + operation+ " contents:" + message.getProperties());}return clusterState;}+ private void handleProp(ZkNodeProps message) {+ String name = message.getStr("name");+ String val = message.getStr("val");+ Map m = reader.getClusterProps();+ if(val ==null) m.remove(name);+ else m.put(name,val);++ try {+ if(reader.getZkClient().exists(ZkStateReader.CLUSTER_PROPS,true))+ reader.getZkClient().setData(ZkStateReader.CLUSTER_PROPS,ZkStateReader.toJSON(m),true);+ else+ reader.getZkClient().create(ZkStateReader.CLUSTER_PROPS, ZkStateReader.toJSON(m),CreateMode.PERSISTENT, true);+ clusterProps = reader.getClusterProps();+ } catch (Exception e) {+ log.error("Unable to set cluster property", e);++ }+ }++ private ClusterState createReplica(ClusterState clusterState, ZkNodeProps message) {+ log.info("createReplica() {} ", message);+ String coll = message.getStr(ZkStateReader.COLLECTION_PROP);+ String slice = message.getStr(ZkStateReader.SHARD_ID_PROP);+ Slice sl = clusterState.getSlice(coll, slice);+ if(sl == null){+ log.error("Invalid Collection/Slice {}/{} ",coll,slice);+ return clusterState;+ }++ String coreNodeName = Assign.assignNode(coll, clusterState);+ Replica replica = new Replica(coreNodeName,+ makeMap(+ ZkStateReader.CORE_NAME_PROP, message.getStr(ZkStateReader.CORE_NAME_PROP),+ ZkStateReader.BASE_URL_PROP,message.getStr(ZkStateReader.BASE_URL_PROP),+ ZkStateReader.STATE_PROP,message.getStr(ZkStateReader.STATE_PROP),+ ZkStateReader.CORE_NODE_NAME_PROP, coreNodeName));+ sl.getReplicasMap().put(coreNodeName, replica);+ return clusterState;+ }private ClusterState buildCollection(ClusterState clusterState, ZkNodeProps message) {String collection = message.getStr("name");@@ -415,6 +467,23 @@ public class Overseer {log.info("According to ZK I (id=" + myId + ") am no longer a leader.");return LeaderStatus.NO;}++ private ClusterState updateStateNew(ClusterState clusterState, ZkNodeProps message) {+ String collection = message.getStr(ZkStateReader.COLLECTION_PROP);+ String sliceName = message.getStr(ZkStateReader.SHARD_ID_PROP);++ if(collection==null || sliceName == null){+ log.error("Invalid collection and slice {}", message);+ return clusterState;+ }+ Slice slice = clusterState.getSlice(collection, sliceName);+ if(slice == null){+ log.error("No such slice exists {}", message);+ return clusterState;+ }++ return updateState(clusterState, message);+ }/*** Try to assign core to the cluster.@@ -535,6 +604,8 @@ public class Overseer {return newClusterState;}++private ClusterState checkAndCompleteShardSplit(ClusterState state, String collection, String coreNodeName, String sliceName, Map<String,Object> replicaProps) {Slice slice = state.getSlice(collection, sliceName);Map<String, Object> sliceProps = slice.getProperties();@@ -966,7 +1037,8 @@ public class Overseer {private ShardHandler shardHandler;private String adminPath;-++ private OverseerCollectionProcessor ocp;// overseer not responsible for closing readerpublic Overseer(ShardHandler shardHandler, String adminPath, final ZkStateReader reader) throws KeeperException, InterruptedException {this.reader = reader;@@ -984,7 +1056,9 @@ public class Overseer {updaterThread.setDaemon(true);ThreadGroup ccTg = new ThreadGroup("Overseer collection creation process.");- ccThread = new OverseerThread(ccTg, new OverseerCollectionProcessor(reader, id, shardHandler, adminPath),++ ocp = new OverseerCollectionProcessor(reader, id, shardHandler, adminPath);+ ccThread = new OverseerThread(ccTg, ocp,"Overseer-" + id);ccThread.setDaemon(true);@@ -1055,5 +1129,8 @@ public class Overseer {throw new RuntimeException(e);}}+ public static boolean isLegacy(Map clusterProps) {+ return !"false".equals(clusterProps.get(ZkStateReader.LEGACY_CLOUD));+ }}diff --git a/solr/core/src/java/org/apache/solr/cloud/OverseerCollectionProcessor.java b/solr/core/src/java/org/apache/solr/cloud/OverseerCollectionProcessor.javaindex 4fe47ef7751..6cf8e20e820 100644--- a/solr/core/src/java/org/apache/solr/cloud/OverseerCollectionProcessor.java+++ b/solr/core/src/java/org/apache/solr/cloud/OverseerCollectionProcessor.java@@ -50,9 +50,11 @@ import org.apache.solr.common.params.CoreAdminParams;import org.apache.solr.common.params.CoreAdminParams.CoreAdminAction;import org.apache.solr.common.params.MapSolrParams;import org.apache.solr.common.params.ModifiableSolrParams;+import org.apache.solr.common.params.ShardParams;import org.apache.solr.common.util.NamedList;import org.apache.solr.common.util.SimpleOrderedMap;import org.apache.solr.common.util.StrUtils;+import org.apache.solr.handler.component.HttpShardHandlerFactory;import org.apache.solr.handler.component.ShardHandler;import org.apache.solr.handler.component.ShardRequest;import org.apache.solr.handler.component.ShardResponse;@@ -84,6 +86,7 @@ import static org.apache.solr.cloud.Assign.getNodesForNewShard;import static org.apache.solr.common.cloud.ZkStateReader.COLLECTION_PROP;import static org.apache.solr.common.cloud.ZkStateReader.REPLICA_PROP;import static org.apache.solr.common.cloud.ZkStateReader.SHARD_ID_PROP;+import static org.apache.solr.common.params.CollectionParams.CollectionAction.ADDREPLICA;import static org.apache.solr.common.params.CollectionParams.CollectionAction.ADDROLE;import static org.apache.solr.common.params.CollectionParams.CollectionAction.REMOVEROLE;@@ -126,7 +129,8 @@ public class OverseerCollectionProcessor implements Runnable, ClosableThread {public static final String COLL_PROP_PREFIX = "property.";- public static final Set<String> KNOWN_CLUSTER_PROPS = ImmutableSet.of("legacyCloud","urlScheme");++ public static final Set<String> KNOWN_CLUSTER_PROPS = ImmutableSet.of(ZkStateReader.LEGACY_CLOUD, ZkStateReader.URL_SCHEME);public static final Map<String,Object> COLL_PROPS = ZkNodeProps.makeMap(ROUTER, DocRouter.DEFAULT_NAME,@@ -403,10 +407,10 @@ public class OverseerCollectionProcessor implements Runnable, ClosableThread {deleteReplica(zkStateReader.getClusterState(), message, results);} else if (MIGRATE.equals(operation)) {migrate(zkStateReader.getClusterState(), message, results);- } else if(CollectionParams.CollectionAction.CLUSTERPROP.toString().equalsIgnoreCase(operation)){- handleProp(message,results);- } else if(REMOVEROLE.toString().toLowerCase(Locale.ROOT).equals(operation) || ADDROLE.toString().toLowerCase(Locale.ROOT).equals(operation) ){+ } else if(REMOVEROLE.isEqual(operation) || ADDROLE.isEqual(operation) ){processRoleCommand(message, operation);+ } else if (ADDREPLICA.isEqual(operation)) {+ addReplica(zkStateReader.getClusterState(), message, results);}else {@@ -427,7 +431,7 @@ public class OverseerCollectionProcessor implements Runnable, ClosableThread {return new OverseerSolrResponse(results);}- private void handleProp(ZkNodeProps message, NamedList results) throws KeeperException, InterruptedException {+ /* private void handleProp(ZkNodeProps message, NamedList results) throws KeeperException, InterruptedException {String name = message.getStr("name");String val = message.getStr("val");Map m = zkStateReader.getClusterProps();@@ -440,7 +444,7 @@ public class OverseerCollectionProcessor implements Runnable, ClosableThread {- }+ }*/private void processRoleCommand(ZkNodeProps message, String operation) throws KeeperException, InterruptedException {SolrZkClient zkClient = zkStateReader.getZkClient();Map roles = null;@@ -511,6 +515,7 @@ public class OverseerCollectionProcessor implements Runnable, ClosableThread {ShardRequest sreq = new ShardRequest();sreq.purpose = 1;+ if (baseUrl.startsWith("http://")) baseUrl = baseUrl.substring(7);sreq.shards = new String[] {baseUrl};sreq.actualShards = sreq.shards;sreq.params = new ModifiableSolrParams(new MapSolrParams(m));@@ -829,13 +834,7 @@ public class OverseerCollectionProcessor implements Runnable, ClosableThread {}// find the leader for the shard- Replica parentShardLeader = null;- try {- parentShardLeader = zkStateReader.getLeaderRetry(collectionName, slice, 10000);- } catch (InterruptedException e) {- Thread.currentThread().interrupt();- }-+ Replica parentShardLeader = clusterState.getLeader(collectionName, slice);DocRouter.Range range = parentSlice.getRange();if (range == null) {range = new PlainIdRouter().fullRange();@@ -1358,7 +1357,7 @@ public class OverseerCollectionProcessor implements Runnable, ClosableThread {}log.info("Common hash range between source shard: {} and target shard: {} = " + splitRange, sourceSlice.getName(), targetSlice.getName());- Replica targetLeader = zkStateReader.getLeaderRetry(targetCollection.getName(), targetSlice.getName(), 10000);+ Replica targetLeader = targetSlice.getLeader();log.info("Asking target leader node: " + targetLeader.getNodeName() + " core: "+ targetLeader.getStr("core") + " to buffer updates");@@ -1402,7 +1401,7 @@ public class OverseerCollectionProcessor implements Runnable, ClosableThread {log.info("Routing rule added successfully");// Create temp core on source shard- Replica sourceLeader = zkStateReader.getLeaderRetry(sourceCollection.getName(), sourceSlice.getName(), 10000);+ Replica sourceLeader = sourceSlice.getLeader();// create a temporary collection with just one node on the shard leaderString configName = zkStateReader.readConfigName(sourceCollection.getName());@@ -1418,7 +1417,7 @@ public class OverseerCollectionProcessor implements Runnable, ClosableThread {// refresh cluster stateclusterState = zkStateReader.getClusterState();Slice tempSourceSlice = clusterState.getCollection(tempSourceCollectionName).getSlices().iterator().next();- Replica tempSourceLeader = zkStateReader.getLeaderRetry(tempSourceCollectionName, tempSourceSlice.getName(), 120000);+ Replica tempSourceLeader = zkStateReader.getLeaderRetry(tempSourceCollectionName, tempSourceSlice.getName(), 60000);String tempCollectionReplica1 = tempSourceCollectionName + "_" + tempSourceSlice.getName() + "_replica1";String coreNodeName = waitForCoreNodeName(clusterState.getCollection(tempSourceCollectionName),@@ -1618,7 +1617,9 @@ public class OverseerCollectionProcessor implements Runnable, ClosableThread {+ ". This requires " + requestedShardsToCreate+ " shards to be created (higher than the allowed number)");}- String configName = createConfNode(collectionName, message);+ boolean isLegacyCloud = Overseer.isLegacy(zkStateReader.getClusterProps());++ String configName = createConfNode(collectionName, message, isLegacyCloud);Overseer.getInQueue(zkStateReader.getZkClient()).offer(ZkStateReader.toJSON(message));@@ -1638,16 +1639,31 @@ public class OverseerCollectionProcessor implements Runnable, ClosableThread {String sliceName = shardNames.get(i-1);for (int j = 1; j <= repFactor; j++) {String nodeName = nodeList.get((repFactor * (i - 1) + (j - 1)) % nodeList.size());- String shardName = collectionName + "_" + sliceName + "_replica" + j;- log.info("Creating shard " + shardName + " as part of slice "+ String coreName = collectionName + "_" + sliceName + "_replica" + j;+ log.info("Creating shard " + coreName + " as part of slice "+ sliceName + " of collection " + collectionName + " on "+ nodeName);++ String baseUrl = zkStateReader.getBaseUrlForNodeName(nodeName);+ //in the new mode, create the replica in clusterstate prior to creating the core.+ // Otherwise the core creation fails+ if(!isLegacyCloud){+ ZkNodeProps props = new ZkNodeProps(+ Overseer.QUEUE_OPERATION, CollectionParams.CollectionAction.ADDREPLICA.toString(),+ ZkStateReader.COLLECTION_PROP, collectionName,+ ZkStateReader.SHARD_ID_PROP, sliceName,+ ZkStateReader.CORE_NAME_PROP, coreName,+ ZkStateReader.STATE_PROP, ZkStateReader.DOWN,+ ZkStateReader.BASE_URL_PROP,baseUrl);+ Overseer.getInQueue(zkStateReader.getZkClient()).offer(ZkStateReader.toJSON(props));+ }+// Need to create new params for each requestModifiableSolrParams params = new ModifiableSolrParams();params.set(CoreAdminParams.ACTION, CoreAdminAction.CREATE.toString());- params.set(CoreAdminParams.NAME, shardName);+ params.set(CoreAdminParams.NAME, coreName);params.set(COLL_CONF, configName);params.set(CoreAdminParams.COLLECTION, collectionName);params.set(CoreAdminParams.SHARD, sliceName);@@ -1685,7 +1701,99 @@ public class OverseerCollectionProcessor implements Runnable, ClosableThread {}}- private String createConfNode(String coll, ZkNodeProps message) throws KeeperException, InterruptedException {+ private void addReplica(ClusterState clusterState, ZkNodeProps message, NamedList results) throws KeeperException, InterruptedException {+ String collection = message.getStr(COLLECTION_PROP);+ String node = message.getStr("node");+ String shard = message.getStr(SHARD_ID_PROP);+ String coreName = message.getStr(CoreAdminParams.NAME);+++ DocCollection coll = clusterState.getCollection(collection);+ if (coll == null) {+ throw new SolrException(ErrorCode.BAD_REQUEST, "Collection: " + collection + " does not exist");+ }+ if (coll.getSlice(shard) == null) {+ throw new SolrException(ErrorCode.BAD_REQUEST,+ "Collection: " + collection + " shard: " + shard + " does not exist");+ }++ if(node== null){+ node = getNodesForNewShard(clusterState,collection, coll.getSlices().size() , coll.getInt(MAX_SHARDS_PER_NODE, 1),coll.getInt(REPLICATION_FACTOR, 1),null).get(0).nodeName;+ log.info("node not provided , Identified {} for creating new replica",node);+ }+++ if (!clusterState.liveNodesContain(node)) {+ throw new SolrException(ErrorCode.BAD_REQUEST, "Node: " + node + " is not live");+ }+ if (coreName == null) {+ // assign a name to this core+ Slice slice = coll.getSlice(shard);+ int replicaNum = slice.getReplicas().size();+ for (;;) {+ String replicaName = collection + "_" + shard + "_replica" + replicaNum;+ boolean exists = false;+ for (Replica replica : slice.getReplicas()) {+ if (replicaName.equals(replica.getStr("core"))) {+ exists = true;+ break;+ }+ }+ if (exists) replicaNum++;+ else break;+ }+ coreName = collection + "_" + shard + "_replica" + replicaNum;+ }++ if(!Overseer.isLegacy(zkStateReader.getClusterProps())){+ ZkNodeProps props = new ZkNodeProps(+ Overseer.QUEUE_OPERATION, ADDREPLICA.toString(),+ ZkStateReader.COLLECTION_PROP, collection,+ ZkStateReader.SHARD_ID_PROP, shard,+ ZkStateReader.CORE_NAME_PROP, coreName,+ ZkStateReader.STATE_PROP, ZkStateReader.DOWN,+ ZkStateReader.BASE_URL_PROP,zkStateReader.getBaseUrlForNodeName(node));+ Overseer.getInQueue(zkStateReader.getZkClient()).offer(ZkStateReader.toJSON(props));+ }+++ String configName = zkStateReader.readConfigName(collection);+ String routeKey = message.getStr(ShardParams._ROUTE_);+ String dataDir = message.getStr(CoreAdminParams.DATA_DIR);+ String instanceDir = message.getStr(CoreAdminParams.INSTANCE_DIR);++ ModifiableSolrParams params = new ModifiableSolrParams();+ params.set(CoreAdminParams.ACTION, CoreAdminAction.CREATE.toString());+ params.set(CoreAdminParams.NAME, coreName);+ params.set(COLL_CONF, configName);+ params.set(CoreAdminParams.COLLECTION, collection);+ if (shard != null) {+ params.set(CoreAdminParams.SHARD, shard);+ } else if (routeKey != null) {+ Collection<Slice> slices = coll.getRouter().getSearchSlicesSingle(routeKey, null, coll);+ if (slices.isEmpty()) {+ throw new SolrException(ErrorCode.BAD_REQUEST, "No active shard serving _route_=" + routeKey + " found");+ } else {+ params.set(CoreAdminParams.SHARD, slices.iterator().next().getName());+ }+ } else {+ throw new SolrException(ErrorCode.BAD_REQUEST, "Specify either 'shard' or _route_ param");+ }+ if (dataDir != null) {+ params.set(CoreAdminParams.DATA_DIR, dataDir);+ }+ if (instanceDir != null) {+ params.set(CoreAdminParams.INSTANCE_DIR, instanceDir);+ }+ addPropertyParams(message, params);++ sendShardRequest(node, params);++ collectShardResponses(results, true,+ "ADDREPLICA failed to create replica");+ }++ private String createConfNode(String coll, ZkNodeProps message, boolean isLegacyCloud) throws KeeperException, InterruptedException {String configName = message.getStr(OverseerCollectionProcessor.COLL_CONF);if(configName == null){// if there is only one conf, use that@@ -1709,8 +1817,11 @@ public class OverseerCollectionProcessor implements Runnable, ClosableThread {ZkStateReader.toJSON(ZkNodeProps.makeMap(ZkController.CONFIGNAME_PROP,configName)),true );} else {- String msg = "Could not obtain config name";- log.warn(msg);+ if(isLegacyCloud){+ log.warn("Could not obtain config name");+ } else {+ throw new SolrException(ErrorCode.BAD_REQUEST,"Unable to get config name");+ }}return configName;@@ -1755,6 +1866,8 @@ public class OverseerCollectionProcessor implements Runnable, ClosableThread {// yes, they must use same admin handler path everywhere...cloneParams.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 = cloneParams;diff --git a/solr/core/src/java/org/apache/solr/cloud/ZkController.java b/solr/core/src/java/org/apache/solr/cloud/ZkController.javaindex 796b9f5a6d1..a5b6b8ba753 100644--- a/solr/core/src/java/org/apache/solr/cloud/ZkController.java+++ b/solr/core/src/java/org/apache/solr/cloud/ZkController.java@@ -36,8 +36,6 @@ import java.util.Properties;import java.util.Set;import java.util.concurrent.Future;import java.util.concurrent.TimeoutException;-import java.util.regex.Matcher;-import java.util.regex.Pattern;import org.apache.commons.io.FileUtils;import org.apache.commons.lang.StringUtils;@@ -580,7 +578,7 @@ public final class ZkController {for (Slice slice : slices) {Collection<Replica> replicas = slice.getReplicas();for (Replica replica : replicas) {- if (replica.getNodeName().equals(getNodeName())+ if (getNodeName().equals(replica.getNodeName())&& !(replica.getStr(ZkStateReader.STATE_PROP).equals(ZkStateReader.DOWN))) {ZkNodeProps m = new ZkNodeProps(Overseer.QUEUE_OPERATION, "state",@@ -1355,6 +1353,8 @@ public final class ZkController {public void preRegister(CoreDescriptor cd ) {String coreNodeName = getCoreNodeName(cd);++ checkStateInZk(cd);// before becoming available, make sure we are not live and active// this also gets us our assigned shard id if it was not specifiedtry {@@ -1385,6 +1385,31 @@ public final class ZkController {}+ private void checkStateInZk(CoreDescriptor cd) {+ if(!Overseer.isLegacy(zkStateReader.getClusterProps())){+ DocCollection coll = zkStateReader.getClusterState().getCollection(cd.getCollectionName());+ CloudDescriptor cloudDesc = cd.getCloudDescriptor();+ if(cloudDesc.getShardId() == null) throw new RuntimeException("No shard id for :"+ cd.toString());+ Slice slice = coll.getSlice(cloudDesc.getShardId());+ if(slice == null) throw new RuntimeException("Invalid slice : "+cloudDesc.getShardId());+ Replica replica = null;+ if(cloudDesc.getCoreNodeName() !=null){+ replica = slice.getReplica(cloudDesc.getCoreNodeName());+ } else {+ for (Replica r : slice.getReplicas()) {+ if(cd.getName().equals(r.get(ZkStateReader.CORE_NAME_PROP)) && getBaseUrl().equals(r.get(ZkStateReader.BASE_URL_PROP))){+ replica = r;+ break;+ }+ }+ }+ if(replica == null){+ throw new RuntimeException(" No such replica in clusterstate "+cd.toString());+ }++ }+ }+private ZkCoreNodeProps waitForLeaderToSeeDownState(CoreDescriptor descriptor, final String coreZkNodeName) {CloudDescriptor cloudDesc = descriptor.getCloudDescriptor();diff --git a/solr/core/src/java/org/apache/solr/handler/admin/CollectionsHandler.java b/solr/core/src/java/org/apache/solr/handler/admin/CollectionsHandler.javaindex 585f1f81364..06158ba20b0 100644--- a/solr/core/src/java/org/apache/solr/handler/admin/CollectionsHandler.java+++ b/solr/core/src/java/org/apache/solr/handler/admin/CollectionsHandler.java@@ -38,6 +38,7 @@ import org.apache.solr.common.params.CollectionParams;import org.apache.solr.common.params.CollectionParams.CollectionAction;import org.apache.solr.common.params.CoreAdminParams;import org.apache.solr.common.params.ModifiableSolrParams;+import org.apache.solr.common.params.ShardParams;import org.apache.solr.common.params.SolrParams;import org.apache.solr.common.util.NamedList;import org.apache.solr.common.util.SimpleOrderedMap;@@ -71,6 +72,7 @@ import static org.apache.solr.common.cloud.ZkNodeProps.makeMap;import static org.apache.solr.common.cloud.ZkStateReader.COLLECTION_PROP;import static org.apache.solr.common.cloud.ZkStateReader.SHARD_ID_PROP;import static org.apache.solr.common.params.CollectionParams.CollectionAction.ADDROLE;+import static org.apache.solr.common.params.CollectionParams.CollectionAction.CLUSTERPROP;import static org.apache.solr.common.params.CollectionParams.CollectionAction.REMOVEROLE;public class CollectionsHandler extends RequestHandlerBase {@@ -180,10 +182,12 @@ public class CollectionsHandler extends RequestHandlerBase {case MIGRATE: {this.handleMigrate(req, rsp);break;- } case ADDROLE:{+ }+ case ADDROLE: {handleRole(ADDROLE, req, rsp);break;- } case REMOVEROLE:{+ }+ case REMOVEROLE: {handleRole(REMOVEROLE, req, rsp);break;}@@ -191,6 +195,10 @@ public class CollectionsHandler extends RequestHandlerBase {this.handleProp(req, rsp);break;}+ case ADDREPLICA: {+ this.handleAddReplica(req, rsp);+ break;+ }default: {throw new RuntimeException("Unknown action: " + action);}@@ -207,19 +215,19 @@ public class CollectionsHandler extends RequestHandlerBase {}Map<String,Object> props = ZkNodeProps.makeMap(- Overseer.QUEUE_OPERATION, CollectionAction.CLUSTERPROP.toString().toLowerCase(Locale.ROOT) );+ Overseer.QUEUE_OPERATION, CLUSTERPROP.toLower() );copyIfNotNull(req.getParams(),props,"name","val");- handleResponse(CollectionAction.CLUSTERPROP.toString().toLowerCase(Locale.ROOT),new ZkNodeProps(props),rsp);+ Overseer.getInQueue(coreContainer.getZkController().getZkClient()).offer(ZkStateReader.toJSON(props)) ;}static Set<String> KNOWN_ROLES = ImmutableSet.of("overseer");private void handleRole(CollectionAction action, SolrQueryRequest req, SolrQueryResponse rsp) throws KeeperException, InterruptedException {req.getParams().required().check("role", "node");- Map<String, Object> map = ZkNodeProps.makeMap(Overseer.QUEUE_OPERATION, action.toString().toLowerCase(Locale.ROOT));+ Map<String, Object> map = ZkNodeProps.makeMap(Overseer.QUEUE_OPERATION, action.toLower());copyIfNotNull(req.getParams(), map,"role", "node");ZkNodeProps m = new ZkNodeProps(map);if(!KNOWN_ROLES.contains(m.getStr("role"))) throw new SolrException(ErrorCode.BAD_REQUEST,"Unknown role. Supported roles are ,"+ KNOWN_ROLES);@@ -494,6 +502,16 @@ public class CollectionsHandler extends RequestHandlerBase {handleResponse(OverseerCollectionProcessor.MIGRATE, m, rsp, DEFAULT_ZK_TIMEOUT * 20);}+ private void handleAddReplica(SolrQueryRequest req, SolrQueryResponse rsp) throws KeeperException, InterruptedException {+ log.info("Add replica action invoked: " + req.getParamString());+ Map<String,Object> props = new HashMap<String,Object>();+ props.put(Overseer.QUEUE_OPERATION, CollectionAction.ADDREPLICA.toString());+ copyIfNotNull(req.getParams(), props, COLLECTION_PROP, "node", SHARD_ID_PROP, ShardParams._ROUTE_,+ CoreAdminParams.NAME, CoreAdminParams.INSTANCE_DIR, CoreAdminParams.DATA_DIR);+ ZkNodeProps m = new ZkNodeProps(props);+ handleResponse(CollectionAction.ADDREPLICA.toString(), m, rsp);+ }+public static ModifiableSolrParams params(String... params) {ModifiableSolrParams msp = new ModifiableSolrParams();for (int i=0; i<params.length; i+=2) {diff --git a/solr/core/src/test/org/apache/solr/cloud/CollectionsAPIDistributedZkTest.java b/solr/core/src/test/org/apache/solr/cloud/CollectionsAPIDistributedZkTest.javaindex 60c13069a40..22867918e64 100644--- a/solr/core/src/test/org/apache/solr/cloud/CollectionsAPIDistributedZkTest.java+++ b/solr/core/src/test/org/apache/solr/cloud/CollectionsAPIDistributedZkTest.java@@ -17,6 +17,8 @@ package org.apache.solr.cloud;* limitations under the License.*/+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;@@ -25,14 +27,15 @@ import java.io.IOException;import java.lang.management.ManagementFactory;import java.util.ArrayList;import java.util.Collection;+import java.util.Collections;import java.util.HashMap;import java.util.HashSet;import java.util.Iterator;import java.util.LinkedList;import java.util.List;-import java.util.Locale;import java.util.Map;import java.util.Map.Entry;+import java.util.Objects;import java.util.Set;import java.util.concurrent.CompletionService;import java.util.concurrent.ExecutorCompletionService;@@ -74,7 +77,9 @@ import org.apache.solr.common.cloud.SolrZkClient;import org.apache.solr.common.cloud.ZkCoreNodeProps;import org.apache.solr.common.cloud.ZkNodeProps;import org.apache.solr.common.cloud.ZkStateReader;+import org.apache.solr.common.params.CollectionParams;import org.apache.solr.common.params.CollectionParams.CollectionAction;+import org.apache.solr.common.params.CoreAdminParams;import org.apache.solr.common.params.MapSolrParams;import org.apache.solr.common.params.ModifiableSolrParams;import org.apache.solr.common.params.SolrParams;@@ -205,6 +210,8 @@ public class CollectionsAPIDistributedZkTest extends AbstractFullDistribZkTestBadeleteCollectionRemovesStaleZkCollectionsNode();clusterPropTest();+ addReplicaTest();+// lastdeleteCollectionWithDownNodes();if (DEBUG) {@@ -1177,6 +1184,69 @@ public class CollectionsAPIDistributedZkTest extends AbstractFullDistribZkTestBa}}+ private void addReplicaTest()throws Exception{+ String collectionName = "addReplicaColl";+ CloudSolrServer client = createCloudClient(null);+ try {+ createCollection(collectionName, client,2,2);++ waitForRecoveriesToFinish(collectionName, false);+ String newReplicaName = Assign.assignNode(collectionName , client.getZkStateReader().getClusterState() );+ ArrayList<String> nodeList = new ArrayList<String>(client.getZkStateReader().getClusterState().getLiveNodes());+ Collections.shuffle(nodeList);+ Map m = makeMap(+ "action", CollectionAction.ADDREPLICA.toString(),+ ZkStateReader.COLLECTION_PROP, collectionName,+ ZkStateReader.SHARD_ID_PROP, "shard1",+ "node", nodeList.get(0));++ SolrRequest request = new QueryRequest(new MapSolrParams(m));+ request.setPath("/admin/collections");+ client.request(request);++ long timeout = System.currentTimeMillis() + 3000;+ Replica newReplica = null;++ for(; System.currentTimeMillis()<timeout;){+ Slice slice = client.getZkStateReader().getClusterState().getSlice(collectionName, "shard1");+ newReplica = slice.getReplica(newReplicaName);+ }++ assertNotNull(newReplica);++ log.info("newReplica {},\n{} ", newReplica,client.getZkStateReader().getBaseUrlForNodeName(nodeList.get(0)));+//+ assertEquals("Replica should be created on the right node",+ client.getZkStateReader().getBaseUrlForNodeName(nodeList.get(0)), newReplica.getStr(ZkStateReader.BASE_URL_PROP));++ newReplicaName = Assign.assignNode(collectionName , client.getZkStateReader().getClusterState() );+ m = makeMap(+ "action", CollectionAction.ADDREPLICA.toString(),+ ZkStateReader.COLLECTION_PROP, collectionName,+ ZkStateReader.SHARD_ID_PROP, "shard2");++ request = new QueryRequest(new MapSolrParams(m));+ request.setPath("/admin/collections");+ client.request(request);++ timeout = System.currentTimeMillis() + 3000;+ newReplica = null;++ for(; System.currentTimeMillis()<timeout;){+ Slice slice = client.getZkStateReader().getClusterState().getSlice(collectionName, "shard2");+ newReplica = slice.getReplica(newReplicaName);+ }++ assertNotNull(newReplica);+++ } finally {+ client.shutdown();+ }++ }++@Overrideprotected QueryResponse queryServer(ModifiableSolrParams params) throws SolrServerException {@@ -1190,6 +1260,18 @@ public class CollectionsAPIDistributedZkTest extends AbstractFullDistribZkTestBaQueryResponse rsp = getCommonCloudSolrServer().query(params);return rsp;}++ protected void createCollection(String COLL_NAME, CloudSolrServer client,int replicationFactor , int numShards ) throws Exception {+ int maxShardsPerNode = ((((numShards+1) * replicationFactor) / getCommonCloudSolrServer()+ .getZkStateReader().getClusterState().getLiveNodes().size())) + 1;++ Map<String, Object> props = makeMap(+ REPLICATION_FACTOR, replicationFactor,+ MAX_SHARDS_PER_NODE, maxShardsPerNode,+ NUM_SLICES, numShards);+ Map<String,List<Integer>> collectionInfos = new HashMap<String,List<Integer>>();+ createCollection(collectionInfos, COLL_NAME, props, client);+ }@Overridepublic void tearDown() throws Exception {@@ -1203,17 +1285,31 @@ public class CollectionsAPIDistributedZkTest extends AbstractFullDistribZkTestBa}private void clusterPropTest() throws Exception {- Map m = makeMap(- "action", CollectionAction.CLUSTERPROP.toString().toLowerCase(Locale.ROOT),- "name", "legacyCloud",- "val", "true");- SolrParams params = new MapSolrParams(m);- SolrRequest request = new QueryRequest(params);- request.setPath("/admin/collections");CloudSolrServer client = createCloudClient(null);- client.request(request);- assertEquals("cluster property not set", "true", client.getZkStateReader().getClusterProps().get("legacyCloud"));+ assertTrue("cluster property not set", setClusterProp(client, ZkStateReader.LEGACY_CLOUD, "false"));+ assertTrue("cluster property not unset ", setClusterProp(client, ZkStateReader.LEGACY_CLOUD, null));+client.shutdown();}++ public static boolean setClusterProp(CloudSolrServer client, String name , String val) throws SolrServerException, IOException, InterruptedException {+ Map m = makeMap(+ "action", CollectionAction.CLUSTERPROP.toLower(),+ "name",name);++ if(val != null) m.put("val", val);+ SolrRequest request = new QueryRequest(new MapSolrParams(m));+ request.setPath("/admin/collections");+ client.request(request);++ long tomeOut = System.currentTimeMillis() + 3000;+ boolean changed = false;+ while(System.currentTimeMillis() <tomeOut){+ Thread.sleep(10);+ changed = Objects.equals(val,client.getZkStateReader().getClusterProps().get(name));+ if(changed) break;+ }+ return changed;+ }}diff --git a/solr/core/src/test/org/apache/solr/cloud/DeleteInactiveReplicaTest.java b/solr/core/src/test/org/apache/solr/cloud/DeleteInactiveReplicaTest.javaindex 0382e27ce55..8968b21048d 100644--- a/solr/core/src/test/org/apache/solr/cloud/DeleteInactiveReplicaTest.java+++ b/solr/core/src/test/org/apache/solr/cloud/DeleteInactiveReplicaTest.java@@ -17,6 +17,7 @@ package org.apache.solr.cloud;* limitations under the License.*/+import static org.apache.solr.cloud.CollectionsAPIDistributedZkTest.setClusterProp;import static org.apache.solr.common.cloud.ZkNodeProps.makeMap;import java.net.URL;@@ -30,15 +31,15 @@ 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.ZkStateReader;+import org.apache.solr.common.params.CoreAdminParams;import org.apache.solr.common.params.MapSolrParams;import org.apache.solr.common.util.NamedList;import org.junit.After;import org.junit.Before;import org.junit.Ignore;-@Ignore("Not currently valid see SOLR-5580")+//@Ignore("Not currently valid see SOLR-5580")public class DeleteInactiveReplicaTest extends DeleteReplicaTest{- private CloudSolrServer client;@Overridepublic void doTest() throws Exception {@@ -48,64 +49,62 @@ public class DeleteInactiveReplicaTest extends DeleteReplicaTest{@Beforepublic void setUp() throws Exception {super.setUp();- client = createCloudClient(null);}@Afterpublic void tearDown() throws Exception {super.tearDown();- client.shutdown();}private void deleteInactiveReplicaTest() throws Exception {+ CloudSolrServer client = createCloudClient(null);+String collectionName = "delDeadColl";++ setClusterProp(client, ZkStateReader.LEGACY_CLOUD, "false");createCollection(collectionName, client);waitForRecoveriesToFinish(collectionName, false);-++ Thread.sleep(3000);+boolean stopped = false;JettySolrRunner stoppedJetty = null;StringBuilder sb = new StringBuilder();Replica replica1 = null;Slice shard1 = null;- DocCollection testcoll = getCommonCloudSolrServer().getZkStateReader()- .getClusterState().getCollection(collectionName);- for (JettySolrRunner jetty : jettys)- sb.append(jetty.getBaseUrl()).append(",");-- for (Slice slice : testcoll.getActiveSlices()) {- for (Replica replica : slice.getReplicas())- for (JettySolrRunner jetty : jettys) {- URL baseUrl = null;- try {- baseUrl = jetty.getBaseUrl();- } catch (Exception e) {- continue;- }- if (baseUrl.toString().startsWith(- replica.getStr(ZkStateReader.BASE_URL_PROP))) {- stoppedJetty = jetty;- ChaosMonkey.stop(jetty);- replica1 = replica;- shard1 = slice;- stopped = true;- break;+ long timeout = System.currentTimeMillis() + 3000;+ DocCollection testcoll = null;+ while(!stopped && System.currentTimeMillis()<timeout ) {+ testcoll = client.getZkStateReader().getClusterState().getCollection(collectionName);+ for (JettySolrRunner jetty : jettys)+ sb.append(jetty.getBaseUrl()).append(",");++ for (Slice slice : testcoll.getActiveSlices()) {+ for (Replica replica : slice.getReplicas())+ for (JettySolrRunner jetty : jettys) {+ URL baseUrl = null;+ try {+ baseUrl = jetty.getBaseUrl();+ } catch (Exception e) {+ continue;+ }+ if (baseUrl.toString().startsWith(+ replica.getStr(ZkStateReader.BASE_URL_PROP))) {+ stoppedJetty = jetty;+ ChaosMonkey.stop(jetty);+ replica1 = replica;+ shard1 = slice;+ stopped = true;+ break;+ }}- }+ }+ Thread.sleep(100);}-- /*- * final Slice shard1 = testcoll.getSlices().iterator().next();- * if(!shard1.getState().equals(Slice.ACTIVE)) fail("shard is not active");- * Replica replica1 = shard1.getReplicas().iterator().next();- * JettySolrRunner stoppedJetty = null; StringBuilder sb = new- * StringBuilder(); for (JettySolrRunner jetty : jettys) {- * sb.append(jetty.getBaseUrl()).append(","); if(- * jetty.getBaseUrl().toString- * ().startsWith(replica1.getStr(ZkStateReader.BASE_URL_PROP)) ) {- * stoppedJetty = jetty; ChaosMonkey.stop(jetty); stopped = true; break; } }- */++if (!stopped) {fail("Could not find jetty to stop in collection " + testcoll+ " jettys: " + sb);@@ -114,7 +113,7 @@ public class DeleteInactiveReplicaTest extends DeleteReplicaTest{long endAt = System.currentTimeMillis() + 3000;boolean success = false;while (System.currentTimeMillis() < endAt) {- testcoll = getCommonCloudSolrServer().getZkStateReader()+ testcoll = client.getZkStateReader().getClusterState().getCollection(collectionName);if (!"active".equals(testcoll.getSlice(shard1.getName()).getReplica(replica1.getName()).getStr(Slice.STATE))) {@@ -123,19 +122,42 @@ public class DeleteInactiveReplicaTest extends DeleteReplicaTest{if (success) break;Thread.sleep(100);}+log.info("removed_replicas {}/{} ", shard1.getName(), replica1.getName());removeAndWaitForReplicaGone(collectionName, client, replica1,shard1.getName());-ChaosMonkey.start(stoppedJetty);log.info("restarted jetty");-+Map m = makeMap("qt", "/admin/cores", "action", "status");-- NamedList<Object> resp = new HttpSolrServer(replica1.getStr("base_url"))++ NamedList<Object> resp = new HttpSolrServer(replica1.getStr(ZkStateReader.BASE_URL_PROP)).request(new QueryRequest(new MapSolrParams(m)));assertNull("The core is up and running again",((NamedList) resp.get("status")).get(replica1.getStr("core")));-+++ Exception exp = null;++ try {++ m = makeMap(+ "action", CoreAdminParams.CoreAdminAction.CREATE.toString(),+ ZkStateReader.COLLECTION_PROP, collectionName,+ ZkStateReader.SHARD_ID_PROP, "shard2",+ CoreAdminParams.NAME, "testcore");++ QueryRequest request = new QueryRequest(new MapSolrParams(m));+ request.setPath("/admin/cores");+ NamedList<Object> rsp = client.request(request);+ } catch (Exception e) {+ exp = e;+ log.info("error_expected",e);+ }+ assertNotNull( "Exception expected", exp);+ setClusterProp(client,ZkStateReader.LEGACY_CLOUD,null);+ client.shutdown();++}}diff --git a/solr/core/src/test/org/apache/solr/cloud/DeleteReplicaTest.java b/solr/core/src/test/org/apache/solr/cloud/DeleteReplicaTest.javaindex c9f63a53212..bcebb34bce4 100644--- a/solr/core/src/test/org/apache/solr/cloud/DeleteReplicaTest.java+++ b/solr/core/src/test/org/apache/solr/cloud/DeleteReplicaTest.java@@ -102,11 +102,7 @@ public class DeleteReplicaTest extends AbstractFullDistribZkTestBase {if ("active".equals(replica.getStr("state"))) replica1 = replica;}}- // final Slice shard1 = testcoll.getSlices().iterator().next();- // if(!shard1.getState().equals(Slice.ACTIVE))- // fail("shard is not active");- // for (Replica replica : shard1.getReplicas())- // if("active".equals(replica.getStr("state"))) replica1 =replica;+if (replica1 == null) fail("no active replicas found");removeAndWaitForReplicaGone(collectionName, client, replica1,shard1.getName());diff --git a/solr/core/src/test/org/apache/solr/cloud/OverseerCollectionProcessorTest.java b/solr/core/src/test/org/apache/solr/cloud/OverseerCollectionProcessorTest.javaindex e24b45b9c7a..9b8e012668c 100644--- a/solr/core/src/test/org/apache/solr/cloud/OverseerCollectionProcessorTest.java+++ b/solr/core/src/test/org/apache/solr/cloud/OverseerCollectionProcessorTest.java@@ -218,6 +218,13 @@ public class OverseerCollectionProcessorTest extends SolrTestCaseJ4 {}).anyTimes();}+ zkStateReaderMock.getClusterProps();+ expectLastCall().andAnswer(new IAnswer<Map>() {+ @Override+ public Map answer() throws Throwable {+ return new HashMap();+ }+ });solrZkClientMock.getZkClientTimeout();expectLastCall().andAnswer(new IAnswer<Object>() {diff --git a/solr/solrj/src/java/org/apache/solr/common/cloud/ZkStateReader.java b/solr/solrj/src/java/org/apache/solr/common/cloud/ZkStateReader.javaindex a1f024453aa..ae86b32c584 100644--- a/solr/solrj/src/java/org/apache/solr/common/cloud/ZkStateReader.java+++ b/solr/solrj/src/java/org/apache/solr/common/cloud/ZkStateReader.java@@ -84,6 +84,10 @@ public class ZkStateReader {public static final String CONFIGS_ZKNODE = "/configs";public final static String CONFIGNAME_PROP="configName";++ public static final String LEGACY_CLOUD = "legacyCloud";++ public static final String URL_SCHEME = "urlScheme";private volatile ClusterState clusterState;@@ -635,7 +639,7 @@ public class ZkStateReader {final String hostAndPort = nodeName.substring(0,_offset);try {final String path = URLDecoder.decode(nodeName.substring(1+_offset), "UTF-8");- String urlScheme = (String) getClusterProps().get("urlScheme");+ String urlScheme = (String) getClusterProps().get(URL_SCHEME);if(urlScheme == null) {urlScheme = "http";}diff --git a/solr/solrj/src/java/org/apache/solr/common/params/CollectionParams.java b/solr/solrj/src/java/org/apache/solr/common/params/CollectionParams.javaindex 9421486e961..b24c1ea54ae 100644--- a/solr/solrj/src/java/org/apache/solr/common/params/CollectionParams.java+++ b/solr/solrj/src/java/org/apache/solr/common/params/CollectionParams.java@@ -41,7 +41,8 @@ public interface CollectionParamsMIGRATE,ADDROLE,REMOVEROLE,- CLUSTERPROP;+ CLUSTERPROP,+ ADDREPLICA;public static CollectionAction get( String p ){@@ -53,5 +54,13 @@ public interface CollectionParams}return null;}+ public boolean isEqual(String s){+ if(s == null) return false;+ return toString().equals(s.toUpperCase(Locale.ROOT));+ }+ public String toLower(){+ return toString().toLowerCase(Locale.ROOT);+ }+}}