Apache Lucene open-source search software
revert SOLR-5473 , SOLR-5474
Noble Paul2ce57608ee95
diff --git a/solr/CHANGES.txt b/solr/CHANGES.txtindex 10877a57e2a..ab1f3ee2592 100644--- a/solr/CHANGES.txt+++ b/solr/CHANGES.txt@@ -76,10 +76,6 @@ Other Changes* SOLR-5936: Removed deprecated non-Trie-based numeric & date field types.(Steve Rowe)-* SOLR-5473: Make one state.json per collection (Noble Paul)--* SOLR-5474: Have a new mode for SolrJ to support stateFormat=2 (Noble Paul, Tim Potter)-* SOLR-5868: HttpClient should be configured to use ALLOW_ALL_HOSTNAME hostnameverifier to simplify SSL setup. (Steve Davids via Mark Miller)diff --git a/solr/core/src/java/org/apache/solr/SolrLogFormatter.java b/solr/core/src/java/org/apache/solr/SolrLogFormatter.javaindex 8589720f940..ff1cf222c63 100644--- a/solr/core/src/java/org/apache/solr/SolrLogFormatter.java+++ b/solr/core/src/java/org/apache/solr/SolrLogFormatter.java@@ -263,7 +263,7 @@ sb.append("(group_name=").append(tg.getName()).append(")");private Map<String,Object> getReplicaProps(ZkController zkController, SolrCore core) {final String collection = core.getCoreDescriptor().getCloudDescriptor().getCollectionName();- Replica replica = zkController.getClusterState().getCachedReplica(collection, core.getCoreDescriptor().getCloudDescriptor().getCoreNodeName());+ Replica replica = zkController.getClusterState().getReplica(collection, core.getCoreDescriptor().getCloudDescriptor().getCoreNodeName());if(replica!=null) {return replica.getProperties();}diff --git a/solr/core/src/java/org/apache/solr/cloud/Overseer.java b/solr/core/src/java/org/apache/solr/cloud/Overseer.javaindex 6ae31500ba6..0e931e61c8d 100644--- a/solr/core/src/java/org/apache/solr/cloud/Overseer.java+++ b/solr/core/src/java/org/apache/solr/cloud/Overseer.java@@ -105,9 +105,7 @@ public class Overseer {private boolean isClosed = false;- private final Map<String, Object> updateNodes = new LinkedHashMap<String,Object>();- private boolean isClusterStateModified = false;-+public ClusterStateUpdater(final ZkStateReader reader, final String myId, Stats zkStats) {this.zkClient = reader.getZkClient();this.zkStats = zkStats;@@ -119,7 +117,6 @@ public class Overseer {this.myId = myId;this.reader = reader;clusterProps = reader.getClusterProps();- reader.ephemeralCollectionData = Collections.unmodifiableMap(updateNodes);}public Stats getStateUpdateQueueStats() {@@ -260,7 +257,6 @@ public class Overseer {stateUpdateQueue.poll();if (isClosed || System.nanoTime() - lastUpdatedTime > TimeUnit.NANOSECONDS.convert(STATE_UPDATE_DELAY, TimeUnit.MILLISECONDS)) break;- if(!updateNodes.isEmpty()) break;// if an event comes in the next 100ms batch it togetherhead = stateUpdateQueue.peek(100);}@@ -297,28 +293,9 @@ public class Overseer {}private void updateZkStates(ClusterState clusterState) throws KeeperException, InterruptedException {- if(!updateNodes.isEmpty()) {- for (Entry<String, Object> e : updateNodes.entrySet()) {- if (e.getValue() == null) {- if (zkClient.exists(e.getKey(), true)) zkClient.delete(e.getKey(), 0, true);- } else {- if (zkClient.exists(e.getKey(), true)) {- log.info("going to update_collection", e.getKey());- zkClient.setData(e.getKey(), ZkStateReader.toJSON(e.getValue()), true);- } else {- log.info("going to create_collection {}", e.getValue());- zkClient.create(e.getKey(), ZkStateReader.toJSON(e.getValue()), CreateMode.PERSISTENT, true);- }- }- }- updateNodes.clear();- }+ lastUpdatedTime = System.nanoTime();+ zkClient.setData(ZkStateReader.CLUSTER_STATE, ZkStateReader.toJSON(clusterState), true);- if(isClusterStateModified) {- lastUpdatedTime = System.nanoTime();- zkClient.setData(ZkStateReader.CLUSTER_STATE, ZkStateReader.toJSON(clusterState), true);- isClusterStateModified = false;- }}private void checkIfIamStillLeader() {@@ -862,14 +839,6 @@ public class Overseer {if(message.getStr("fromApi") == null) collectionProps.put("autoCreated","true");DocCollection newCollection = new DocCollection(collectionName, newSlices, collectionProps, router);- isClusterStateModified = true;- log.info("_extern {} {}", collectionName, newCollection.isExternal());- if (newCollection.isExternal()) {- updateNodes.put(ZkStateReader.getCollectionPath(collectionName),- new ClusterState(-1, Collections.<String>emptySet(), singletonMap(newCollection.getName(), newCollection), state.getStateReader()));- return state;- }-return newState(state, singletonMap(newCollection.getName(), newCollection));}@@ -995,23 +964,7 @@ public class Overseer {}private ClusterState newState(ClusterState state, Map<String, DocCollection> colls) {- for (Entry<String, DocCollection> e : colls.entrySet()) {- DocCollection c = e.getValue();- if (c == null) {- isClusterStateModified = true;- state = state.copyWith(singletonMap(e.getKey(), (DocCollection) null));- continue;- }-- if (c.isExternal()) {- state.getStateReader().updateExternCollection(c);- updateNodes.put(ZkStateReader.getCollectionPath(c.getName()), new ClusterState(-1, Collections.<String>emptySet(), singletonMap(c.getName(), c), state.getStateReader()));- } else {- isClusterStateModified = true;- state = state.copyWith(singletonMap(e.getKey(), c));- }- }- return state;+ return state.copyWith(colls);}/*@@ -1022,19 +975,7 @@ public class Overseer {if (!checkKeyExistence(message, "name")) return clusterState;DocCollection coll = clusterState.getCollectionOrNull(collection);if(coll !=null) {- isClusterStateModified = true;- if(coll.isExternal()){- try {- log.info("Deleting state for collection : {}", collection);- zkClient.delete(ZkStateReader.getCollectionPath(collection),-1,true);- } catch (Exception e) {- throw new SolrException(SolrException.ErrorCode.SERVER_ERROR,"Unable to remove collection state :"+collection);-- }- return clusterState;- } else{- return clusterState.copyWith(singletonMap(collection,(DocCollection)null));- }+ return clusterState.copyWith(singletonMap(collection,(DocCollection)null));}return clusterState;}diff --git a/solr/core/src/java/org/apache/solr/cloud/OverseerCollectionProcessor.java b/solr/core/src/java/org/apache/solr/cloud/OverseerCollectionProcessor.javaindex e78e99022a5..7750c6bcb65 100644--- a/solr/core/src/java/org/apache/solr/cloud/OverseerCollectionProcessor.java+++ b/solr/core/src/java/org/apache/solr/cloud/OverseerCollectionProcessor.java@@ -143,9 +143,7 @@ public class OverseerCollectionProcessor implements Runnable, ClosableThread {public static final Map<String,Object> COLL_PROPS = ZkNodeProps.makeMap(ROUTER, DocRouter.DEFAULT_NAME,REPLICATION_FACTOR, "1",- MAX_SHARDS_PER_NODE, "1",- "external",null ,- DocCollection.STATE_FORMAT , null);+ MAX_SHARDS_PER_NODE, "1" );// TODO: use from Overseer?@@ -609,13 +607,7 @@ public class OverseerCollectionProcessor implements Runnable, ClosableThread {Set<String> collections = clusterState.getCollections();for (String name : collections) {Map<String, Object> collectionStatus = null;- if (clusterState.hasExternalCollection(name)) {- bytes = ZkStateReader.toJSON(clusterState.getCollection(name));- Map<String, Object> docCollection = (Map<String, Object>) ZkStateReader.fromJSON(bytes);- collectionStatus = getCollectionStatus(docCollection, name, shard);- } else {- collectionStatus = getCollectionStatus((Map<String, Object>) stateMap.get(name), name, shard);- }+ collectionStatus = getCollectionStatus((Map<String, Object>) stateMap.get(name), name, shard);if (collectionVsAliases.containsKey(name) && !collectionVsAliases.get(name).isEmpty()) {collectionStatus.put("aliases", collectionVsAliases.get(name));}@@ -624,12 +616,8 @@ public class OverseerCollectionProcessor implements Runnable, ClosableThread {} else {String routeKey = message.getStr(ShardParams._ROUTE_);Map<String, Object> docCollection = null;- if (clusterState.hasExternalCollection(collection)) {- bytes = ZkStateReader.toJSON(clusterState.getCollection(collection));- docCollection = (Map<String, Object>) ZkStateReader.fromJSON(bytes);- } else {- docCollection = (Map<String, Object>) stateMap.get(collection);- }++ docCollection = (Map<String, Object>) stateMap.get(collection);if (routeKey == null) {Map<String, Object> collectionStatus = getCollectionStatus(docCollection, collection, shard);if (collectionVsAliases.containsKey(collection) && !collectionVsAliases.get(collection).isEmpty()) {diff --git a/solr/core/src/java/org/apache/solr/cloud/ZkController.java b/solr/core/src/java/org/apache/solr/cloud/ZkController.javaindex 4755748efbc..9fb266beb1e 100644--- a/solr/core/src/java/org/apache/solr/cloud/ZkController.java+++ b/solr/core/src/java/org/apache/solr/cloud/ZkController.java@@ -1073,16 +1073,6 @@ public final class ZkController {}CloudDescriptor cloudDescriptor = cd.getCloudDescriptor();- boolean removeWatch = true;- for (SolrCore solrCore : cc.getCores()) {//if there is no SolrCoe which is a member of this collection, remove the watch- CloudDescriptor cloudDesc = solrCore.getCoreDescriptor().getCloudDescriptor();- if (cloudDesc != null && cloudDescriptor.getCollectionName().equals(cloudDesc.getCollectionName())) {- //means- removeWatch = false;- break;- }- }- if(removeWatch) zkStateReader.removeZKWatch(collection);ZkNodeProps m = new ZkNodeProps(Overseer.QUEUE_OPERATION,Overseer.DELETECORE, ZkStateReader.CORE_NAME_PROP, coreName,ZkStateReader.NODE_NAME_PROP, getNodeName(),@@ -1385,10 +1375,6 @@ public final class ZkController {publish(cd, ZkStateReader.DOWN, false, true);DocCollection collection = zkStateReader.getClusterState().getCollectionOrNull(cd.getCloudDescriptor().getCollectionName());- if(collection !=null && collection.isExternal() ){- log.info("Registering watch for external collection {}",cd.getCloudDescriptor().getCollectionName());- zkStateReader.addCollectionWatch(cd.getCloudDescriptor().getCollectionName());- }} catch (KeeperException e) {log.error("", e);throw new ZooKeeperException(SolrException.ErrorCode.SERVER_ERROR, "", e);diff --git a/solr/core/src/java/org/apache/solr/handler/admin/CollectionsHandler.java b/solr/core/src/java/org/apache/solr/handler/admin/CollectionsHandler.javaindex f78ce8e2d83..3ffcb1b55f9 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@@ -466,7 +466,6 @@ public class CollectionsHandler extends RequestHandlerBase {MAX_SHARDS_PER_NODE,CREATE_NODE_SET ,SHARDS_PROP,- DocCollection.STATE_FORMAT,ASYNC,"router.");diff --git a/solr/core/src/java/org/apache/solr/servlet/SolrDispatchFilter.java b/solr/core/src/java/org/apache/solr/servlet/SolrDispatchFilter.javaindex 297596f22fb..da4f9f0cb3f 100644--- a/solr/core/src/java/org/apache/solr/servlet/SolrDispatchFilter.java+++ b/solr/core/src/java/org/apache/solr/servlet/SolrDispatchFilter.java@@ -324,7 +324,6 @@ public class SolrDispatchFilter extends BaseSolrFilter {String coreUrl = getRemotCoreUrl(cores, corename, origCorename);// don't proxy for internal update requestsSolrParams queryParams = SolrRequestParsers.parseQueryString(req.getQueryString());- checkStateIsValid(cores, queryParams.get(CloudSolrServer.STATE_VERSION));if (coreUrl != null&& queryParams.get(DistributingUpdateProcessorFactory.DISTRIB_UPDATE_PARAM) == null) {@@ -380,7 +379,6 @@ public class SolrDispatchFilter extends BaseSolrFilter {if( "/select".equals( path ) || "/select/".equals( path ) ) {solrReq = parser.parse( core, path, req );- checkStateIsValid(cores,solrReq.getParams().get(CloudSolrServer.STATE_VERSION));String qt = solrReq.getParams().get( CommonParams.QT );handler = core.getRequestHandler( qt );if( handler == null ) {@@ -467,23 +465,7 @@ public class SolrDispatchFilter extends BaseSolrFilter {chain.doFilter(request, response);}- private void checkStateIsValid(CoreContainer cores, String stateVer) {- if(stateVer != null && !stateVer.isEmpty() && cores.isZooKeeperAware() ){- // many have multiple collections separated by |- String[] pairs = StringUtils.split(stateVer, '|');- for (String pair : pairs) {- String[] pcs = StringUtils.split(pair, ':');- if(pcs.length == 2 && !pcs[0].isEmpty() && !pcs[1].isEmpty()){- Boolean status = cores.getZkController().getZkStateReader().checkValid(pcs[0],Integer.parseInt(pcs[1]));-- if(Boolean.TRUE != status){- throw new SolrException(ErrorCode.INVALID_STATE, "STATE STALE: " + pair+ "valid : "+status);- }- }- }- }- }-+private void processAliases(SolrQueryRequest solrReq, Aliases aliases,List<String> collectionsList) {String collection = solrReq.getParams().get("collection");diff --git a/solr/core/src/java/org/apache/solr/servlet/ZookeeperInfoServlet.java b/solr/core/src/java/org/apache/solr/servlet/ZookeeperInfoServlet.javaindex d2762496c0e..e5c2e540d95 100644--- a/solr/core/src/java/org/apache/solr/servlet/ZookeeperInfoServlet.java+++ b/solr/core/src/java/org/apache/solr/servlet/ZookeeperInfoServlet.java@@ -112,7 +112,7 @@ public final class ZookeeperInfoServlet extends HttpServlet {printer.dump = dump;try {- printer.print(path, all);+ printer.print(path);} finally {printer.close();}@@ -195,7 +195,7 @@ public final class ZookeeperInfoServlet extends HttpServlet {}// main entry point- void print(String path, boolean all) throws IOException {+ void print(String path) throws IOException {if (zkClient == null) {return;}@@ -225,7 +225,7 @@ public final class ZookeeperInfoServlet extends HttpServlet {json.startObject();if (detail) {- if (!printZnode(json, path,all)) {+ if (!printZnode(json, path)) {return;}json.writeValueSeparator();@@ -296,7 +296,7 @@ public final class ZookeeperInfoServlet extends HttpServlet {if (dump) {json.writeValueSeparator();- printZnode(json, path, false);+ printZnode(json, path);}} catch (IllegalArgumentException e) {@@ -370,7 +370,7 @@ public final class ZookeeperInfoServlet extends HttpServlet {}@SuppressWarnings("unchecked")- boolean printZnode(JSONWriter json, String path, boolean all) throws IOException {+ boolean printZnode(JSONWriter json, String path) throws IOException {try {Stat stat = new Stat();// Trickily, the call to zkClient.getData fills in the stat variable@@ -386,48 +386,6 @@ public final class ZookeeperInfoServlet extends HttpServlet {}}- // pull in external collections too- if ("/clusterstate.json".equals(path) && all) {- SortedMap<String,Object> collectionStates = null;- List<String> children = zkClient.getChildren("/collections", null, true);- java.util.Collections.sort(children);- for (String collection : children) {- String collStatePath = String.format(Locale.ROOT, "/collections/%s/state", collection);- String childDataStr = null;- try {- byte[] childData = zkClient.getData(collStatePath, null, null, true);- if (childData != null) {- childDataStr = (new BytesRef(childData)).utf8ToString();- }- } catch (NoNodeException nne) {- // safe to ignore- } catch (Exception childErr) {- log.error("Failed to get "+collStatePath+" due to: "+childErr);- }-- if (childDataStr != null) {- if (collectionStates == null) {- // initialize lazily as there may not be any external collections- collectionStates = new TreeMap<String,Object>();-- // add the internal collections- if (dataStr != null)- collectionStates.putAll((Map<String,Object>)ObjectBuilder.fromJSON(dataStr));- }-- // now add in the external collections- Map<String,Object> extColl = (Map<String,Object>)ObjectBuilder.fromJSON(childDataStr);- collectionStates.put(collection, extColl.get(collection));- }- }-- if (collectionStates != null) {- CharArr out = new CharArr();- new JSONWriter(out, 2).write(collectionStates);- dataStr = out.toString();- }- }-json.writeString("znode");json.writeNameSeparator();json.startObject();diff --git a/solr/core/src/java/org/apache/solr/util/SolrLogLayout.java b/solr/core/src/java/org/apache/solr/util/SolrLogLayout.javaindex 6251054a435..6e8f8aa33c9 100644--- a/solr/core/src/java/org/apache/solr/util/SolrLogLayout.java+++ b/solr/core/src/java/org/apache/solr/util/SolrLogLayout.java@@ -234,7 +234,7 @@ public class SolrLogLayout extends Layout {private Map<String,Object> getReplicaProps(ZkController zkController, SolrCore core) {final String collection = core.getCoreDescriptor().getCloudDescriptor().getCollectionName();- Replica replica = zkController.getClusterState().getCachedReplica(collection, zkController.getCoreNodeName(core.getCoreDescriptor()));+ Replica replica = zkController.getClusterState().getReplica(collection, zkController.getCoreNodeName(core.getCoreDescriptor()));if(replica!=null) {return replica.getProperties();}diff --git a/solr/core/src/test/org/apache/solr/cloud/AssignTest.java b/solr/core/src/test/org/apache/solr/cloud/AssignTest.javaindex 6d22428b27c..5d56e6c953a 100644--- a/solr/core/src/test/org/apache/solr/cloud/AssignTest.java+++ b/solr/core/src/test/org/apache/solr/cloud/AssignTest.java@@ -86,7 +86,7 @@ public class AssignTest extends SolrTestCaseJ4 {collectionStates.put(cname, docCollection);Set<String> liveNodes = new HashSet<>();- ClusterState state = new ClusterState(-1,liveNodes, collectionStates,ClusterStateTest.getMockZkStateReader(collectionStates.keySet()));+ ClusterState state = new ClusterState(-1,liveNodes, collectionStates);String nodeName = Assign.assignNode("collection1", state);assertEquals("core_node2", nodeName);diff --git a/solr/core/src/test/org/apache/solr/cloud/ClusterStateTest.java b/solr/core/src/test/org/apache/solr/cloud/ClusterStateTest.javaindex 811a4559329..8959140cd0e 100644--- a/solr/core/src/test/org/apache/solr/cloud/ClusterStateTest.java+++ b/solr/core/src/test/org/apache/solr/cloud/ClusterStateTest.java@@ -62,10 +62,10 @@ public class ClusterStateTest extends SolrTestCaseJ4 {collectionStates.put("collection2", new DocCollection("collection2", slices, null, DocRouter.DEFAULT));ZkStateReader zkStateReaderMock = getMockZkStateReader(collectionStates.keySet());- ClusterState clusterState = new ClusterState(-1,liveNodes, collectionStates,zkStateReaderMock);+ ClusterState clusterState = new ClusterState(-1,liveNodes, collectionStates);byte[] bytes = ZkStateReader.toJSON(clusterState);// System.out.println("#################### " + new String(bytes));- ClusterState loadedClusterState = ClusterState.load(-1, bytes, liveNodes,zkStateReaderMock);+ ClusterState loadedClusterState = ClusterState.load(-1, bytes, liveNodes);assertEquals("Provided liveNodes not used properly", 2, loadedClusterState.getLiveNodes().size());@@ -73,13 +73,13 @@ public class ClusterStateTest extends SolrTestCaseJ4 {assertEquals("Poperties not copied properly", replica.getStr("prop1"), loadedClusterState.getSlice("collection1", "shard1").getReplicasMap().get("node1").getStr("prop1"));assertEquals("Poperties not copied properly", replica.getStr("prop2"), loadedClusterState.getSlice("collection1", "shard1").getReplicasMap().get("node1").getStr("prop2"));- loadedClusterState = ClusterState.load(-1, new byte[0], liveNodes, getMockZkStateReader(Collections.<String>emptySet()));+ loadedClusterState = ClusterState.load(-1, new byte[0], liveNodes);assertEquals("Provided liveNodes not used properly", 2, loadedClusterState.getLiveNodes().size());assertEquals("Should not have collections", 0, loadedClusterState.getCollections().size());- loadedClusterState = ClusterState.load(-1, (byte[])null, liveNodes,getMockZkStateReader(Collections.<String>emptySet()));+ loadedClusterState = ClusterState.load(-1, (byte[])null, liveNodes);assertEquals("Provided liveNodes not used properly", 2, loadedClusterState.getLiveNodes().size());@@ -89,13 +89,6 @@ public class ClusterStateTest extends SolrTestCaseJ4 {public static ZkStateReader getMockZkStateReader(final Set<String> collections) {ZkStateReader mock = createMock(ZkStateReader.class);EasyMock.reset(mock);- mock.getAllCollections();- EasyMock.expectLastCall().andAnswer(new IAnswer<Set<String>>() {- @Override- public Set<String> answer() throws Throwable {- return collections;- }- }).anyTimes();EasyMock.replay(mock);return mock;diff --git a/solr/core/src/test/org/apache/solr/cloud/CollectionsAPIDistributedZkTest.java b/solr/core/src/test/org/apache/solr/cloud/CollectionsAPIDistributedZkTest.javaindex 65b97e2aab8..24153bdbf3f 100644--- a/solr/core/src/test/org/apache/solr/cloud/CollectionsAPIDistributedZkTest.java+++ b/solr/core/src/test/org/apache/solr/cloud/CollectionsAPIDistributedZkTest.java@@ -579,8 +579,8 @@ public class CollectionsAPIDistributedZkTest extends AbstractFullDistribZkTestBaprivate void testNoCollectionSpecified() throws Exception {cloudClient.getZkStateReader().updateClusterState(true);- assertFalse(cloudClient.getZkStateReader().getAllCollections().contains("corewithnocollection"));- assertFalse(cloudClient.getZkStateReader().getAllCollections().contains("corewithnocollection2"));+ assertFalse(cloudClient.getZkStateReader().getClusterState().hasCollection("corewithnocollection"));+ assertFalse(cloudClient.getZkStateReader().getClusterState().hasCollection("corewithnocollection2"));// try and create a SolrCore with no collection nameCreate createCmd = new Create();@@ -605,8 +605,8 @@ public class CollectionsAPIDistributedZkTest extends AbstractFullDistribZkTestBa// in both cases, the collection should have default to the core namecloudClient.getZkStateReader().updateClusterState(true);- assertTrue(cloudClient.getZkStateReader().getAllCollections().contains("corewithnocollection"));- assertTrue(cloudClient.getZkStateReader().getAllCollections().contains("corewithnocollection2"));+ assertTrue( cloudClient.getZkStateReader().getClusterState().hasCollection("corewithnocollection"));+ assertTrue(cloudClient.getZkStateReader().getClusterState().hasCollection("corewithnocollection2"));}private void testNodesUsedByCreate() throws Exception {diff --git a/solr/core/src/test/org/apache/solr/cloud/ExternalCollectionsTest.java b/solr/core/src/test/org/apache/solr/cloud/ExternalCollectionsTest.javadeleted file mode 100644index 5985b57477a..00000000000--- a/solr/core/src/test/org/apache/solr/cloud/ExternalCollectionsTest.java+++ /dev/null@@ -1,123 +0,0 @@-package org.apache.solr.cloud;--/*- * Licensed to the Apache Software Foundation (ASF) under one or more- * contributor license agreements. See the NOTICE file distributed with- * this work for additional information regarding copyright ownership.- * The ASF licenses this file to You under the Apache License, Version 2.0- * (the "License"); you may not use this file except in compliance with- * the License. You may obtain a copy of the License at- *- * http://www.apache.org/licenses/LICENSE-2.0- *- * Unless required by applicable law or agreed to in writing, software- * distributed under the License is distributed on an "AS IS" BASIS,- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.- * See the License for the specific language governing permissions and- * limitations under the License.- */--import org.apache.solr.client.solrj.impl.CloudSolrServer;-import org.apache.solr.client.solrj.request.QueryRequest;-import org.apache.solr.common.cloud.SolrZkClient;-import org.apache.solr.common.cloud.ZkStateReader;-import org.apache.solr.common.params.CollectionParams;-import org.apache.solr.common.params.ModifiableSolrParams;-import org.apache.zookeeper.data.Stat;-import org.junit.After;-import org.junit.Before;-import org.junit.BeforeClass;--import java.util.HashMap;-import java.util.List;-import java.util.Map;--import static org.apache.solr.cloud.OverseerCollectionProcessor.MAX_SHARDS_PER_NODE;-import static org.apache.solr.cloud.OverseerCollectionProcessor.NUM_SLICES;-import static org.apache.solr.cloud.OverseerCollectionProcessor.REPLICATION_FACTOR;-import static org.apache.solr.common.cloud.ZkNodeProps.makeMap;--public class ExternalCollectionsTest extends AbstractFullDistribZkTestBase {- private CloudSolrServer client;-- @BeforeClass- public static void beforeThisClass2() throws Exception {-- }-- @Before- @Override- public void setUp() throws Exception {- super.setUp();- System.setProperty("numShards", Integer.toString(sliceCount));- System.setProperty("solr.xml.persist", "true");- client = createCloudClient(null);- }-- @After- public void tearDown() throws Exception {- super.tearDown();- client.shutdown();- }-- protected String getSolrXml() {- return "solr-no-core.xml";- }-- public ExternalCollectionsTest() {- fixShardCount = true;-- sliceCount = 2;- shardCount = 4;-- checkCreatedVsState = false;- }--- @Override- public void doTest() throws Exception {- testZkNodeLocation();- }--- boolean externalColl = false;- @Override- public boolean useExternalCollections() {- return externalColl;- }-- private void testZkNodeLocation() throws Exception{- externalColl=true;-- String collectionName = "myExternColl";-- createCollection(collectionName, client, 2, 2);-- waitForRecoveriesToFinish(collectionName, false);- assertTrue("does not exist collection state externally", cloudClient.getZkStateReader().getZkClient().exists(ZkStateReader.getCollectionPath(collectionName), true));- Stat stat = new Stat();- cloudClient.getZkStateReader().getZkClient().getData(ZkStateReader.getCollectionPath(collectionName),null,stat,true);- assertEquals("", cloudClient.getZkStateReader().getClusterState().getCollection(collectionName).getVersion(), stat.getVersion());- assertTrue("DocCllection#isExternal() must be true", cloudClient.getZkStateReader().getClusterState().getCollection(collectionName).isExternal() );--- // remove collection- ModifiableSolrParams params = new ModifiableSolrParams();- params.set("action", CollectionParams.CollectionAction.DELETE.toString());- params.set("name", collectionName);- QueryRequest request = new QueryRequest(params);- request.setPath("/admin/collections");- if (client == null) {- client = createCloudClient(null);- }-- client.request(request);-- checkForMissingCollection(collectionName);- assertFalse("collection state should not exist externally", cloudClient.getZkStateReader().getZkClient().exists(ZkStateReader.getCollectionPath(collectionName), true));-- }-}---diff --git a/solr/core/src/test/org/apache/solr/cloud/SliceStateTest.java b/solr/core/src/test/org/apache/solr/cloud/SliceStateTest.javaindex 3b7f7694141..461ef446225 100644--- a/solr/core/src/test/org/apache/solr/cloud/SliceStateTest.java+++ b/solr/core/src/test/org/apache/solr/cloud/SliceStateTest.java@@ -50,9 +50,9 @@ public class SliceStateTest extends SolrTestCaseJ4 {collectionStates.put("collection1", new DocCollection("collection1", slices, null, DocRouter.DEFAULT));ZkStateReader mockZkStateReader = ClusterStateTest.getMockZkStateReader(collectionStates.keySet());- ClusterState clusterState = new ClusterState(-1,liveNodes, collectionStates, mockZkStateReader);+ ClusterState clusterState = new ClusterState(-1,liveNodes, collectionStates);byte[] bytes = ZkStateReader.toJSON(clusterState);- ClusterState loadedClusterState = ClusterState.load(-1, bytes, liveNodes, mockZkStateReader);+ ClusterState loadedClusterState = ClusterState.load(-1, bytes, liveNodes);assertEquals("Default state not set to active", "active", loadedClusterState.getSlice("collection1", "shard1").getState());}diff --git a/solr/solrj/src/java/org/apache/solr/client/solrj/impl/CloudSolrServer.java b/solr/solrj/src/java/org/apache/solr/client/solrj/impl/CloudSolrServer.javaindex 34617a0698d..447527063b5 100644--- a/solr/solrj/src/java/org/apache/solr/client/solrj/impl/CloudSolrServer.java+++ b/solr/solrj/src/java/org/apache/solr/client/solrj/impl/CloudSolrServer.java@@ -18,9 +18,7 @@ package org.apache.solr.client.solrj.impl;*/import java.io.IOException;-import java.net.ConnectException;import java.net.MalformedURLException;-import java.net.SocketException;import java.util.ArrayList;import java.util.Collection;import java.util.Collections;@@ -32,16 +30,13 @@ import java.util.Map;import java.util.Random;import java.util.Set;import java.util.concurrent.Callable;-import java.util.concurrent.ConcurrentHashMap;import java.util.concurrent.ExecutionException;import java.util.concurrent.ExecutorService;import java.util.concurrent.Executors;import java.util.concurrent.Future;import java.util.concurrent.TimeoutException;-import org.apache.http.NoHttpResponseException;import org.apache.http.client.HttpClient;-import org.apache.http.conn.ConnectTimeoutException;import org.apache.solr.client.solrj.ResponseParser;import org.apache.solr.client.solrj.SolrRequest;import org.apache.solr.client.solrj.SolrServer;@@ -72,8 +67,6 @@ import org.apache.solr.common.util.NamedList;import org.apache.solr.common.util.SolrjNamedThreadFactory;import org.apache.solr.common.util.StrUtils;import org.apache.zookeeper.KeeperException;-import org.slf4j.Logger;-import org.slf4j.LoggerFactory;/*** SolrJ client class to communicate with SolrCloud.@@ -86,8 +79,6 @@ import org.slf4j.LoggerFactory;* with {@link #setIdField(String)}.*/public class CloudSolrServer extends SolrServer {- private static final Logger log = LoggerFactory.getLogger(CloudSolrServer.class);-private volatile ZkStateReader zkStateReader;private String zkHost; // the zk server addressprivate int zkConnectTimeout = 10000;@@ -104,7 +95,6 @@ public class CloudSolrServer extends SolrServer {.newCachedThreadPool(new SolrjNamedThreadFactory("CloudSolrServer ThreadPool"));private String idField = "id";- public static final String STATE_VERSION = "_stateVer_";private final Set<String> NON_ROUTABLE_PARAMS;{NON_ROUTABLE_PARAMS = new HashSet<>();@@ -122,51 +112,25 @@ public class CloudSolrServer extends SolrServer {// NON_ROUTABLE_PARAMS.add(UpdateParams.ROLLBACK);}- private volatile long timeToLive;--- protected Map<String, ExpiringCachedDocCollection> collectionStateCache = new ConcurrentHashMap<String, ExpiringCachedDocCollection>(){- @Override- public ExpiringCachedDocCollection get(Object key) {- ExpiringCachedDocCollection val = super.get(key);- if(val == null) return null;- if(val.isExpired(timeToLive)) {- super.remove(key);- return null;- }- return val;- }-- };- class ExpiringCachedDocCollection {- DocCollection cached;- long cachedAt;- ExpiringCachedDocCollection(DocCollection cached) {- this.cached = cached;- this.cachedAt = System.currentTimeMillis();- }-- boolean isExpired(long timeToLive) {- return (System.currentTimeMillis() - cachedAt) > timeToLive;- }- }/*** @param zkHost The client endpoint of the zookeeper quorum containing the cloud state,* in the form HOST:PORT.*/public CloudSolrServer(String zkHost) {- this(zkHost, true, 60);- }-- public CloudSolrServer(String zkHost, boolean updatesToLeaders) throws MalformedURLException {- this(zkHost, updatesToLeaders, 60);+ this.zkHost = zkHost;+ this.myClient = HttpClientUtil.createClient(null);+ this.lbServer = new LBHttpSolrServer(myClient);+ this.lbServer.setRequestWriter(new BinaryRequestWriter());+ this.lbServer.setParser(new BinaryResponseParser());+ this.updatesToLeaders = true;+ shutdownLBHttpSolrServer = true;}-- public CloudSolrServer(String zkHost, boolean updatesToLeaders, int cachedStateTimeToLiveSecs) {-++ public CloudSolrServer(String zkHost, boolean updatesToLeaders)+ throws MalformedURLException {this.zkHost = zkHost;this.myClient = HttpClientUtil.createClient(null);this.lbServer = new LBHttpSolrServer(myClient);@@ -174,9 +138,6 @@ public class CloudSolrServer extends SolrServer {this.lbServer.setParser(new BinaryResponseParser());this.updatesToLeaders = updatesToLeaders;shutdownLBHttpSolrServer = true;-- timeToLive = cachedStateTimeToLiveSecs * 1000L;- setupStateVerParamOnQueryString(lbServer);}/**@@ -185,7 +146,10 @@ public class CloudSolrServer extends SolrServer {* @param lbServer LBHttpSolrServer instance for requests.*/public CloudSolrServer(String zkHost, LBHttpSolrServer lbServer) {- this(zkHost, lbServer, true);+ this.zkHost = zkHost;+ this.lbServer = lbServer;+ this.updatesToLeaders = true;+ shutdownLBHttpSolrServer = false;}/**@@ -195,33 +159,12 @@ public class CloudSolrServer extends SolrServer {* @param updatesToLeaders sends updates only to leaders - defaults to true*/public CloudSolrServer(String zkHost, LBHttpSolrServer lbServer, boolean updatesToLeaders) {- this(zkHost, lbServer, updatesToLeaders, 60);- }-- public CloudSolrServer(String zkHost, LBHttpSolrServer lbServer, boolean updatesToLeaders, int cachedStateTimeToLiveSecs) {this.zkHost = zkHost;this.lbServer = lbServer;this.updatesToLeaders = updatesToLeaders;shutdownLBHttpSolrServer = false;- timeToLive = cachedStateTimeToLiveSecs * 1000L;-- setupStateVerParamOnQueryString(lbServer);- }-- /**- * Used internally to setup the _stateVer_ param to be sent in the query string of requests- * coming from this instance.- */- protected void setupStateVerParamOnQueryString(LBHttpSolrServer lbServer) {- // setup the stateVer param to be passed in the query string of every request- Set<String> queryStringParams = lbServer.getQueryParams();- if (queryStringParams == null) {- queryStringParams = new HashSet<String>(2);- lbServer.setQueryParams(queryStringParams);- }- queryStringParams.add("_stateVer_");}-+public ResponseParser getParser() {return lbServer.getParser();}@@ -294,7 +237,10 @@ public class CloudSolrServer extends SolrServer {synchronized (this) {if (zkStateReader == null) {try {- zkStateReader = createZkStateReader(zkHost, zkClientTimeout, zkConnectTimeout);+ ZkStateReader zk = new ZkStateReader(zkHost, zkClientTimeout,+ zkConnectTimeout);+ zk.createClusterStateWatchersAndUpdate();+ zkStateReader = zk;} catch (InterruptedException e) {Thread.currentThread().interrupt();throw new ZooKeeperException(SolrException.ErrorCode.SERVER_ERROR,@@ -347,7 +293,7 @@ public class CloudSolrServer extends SolrServer {}}- DocCollection col = getDocCollection(clusterState, collection);+ DocCollection col = clusterState.getCollection(collection);DocRouter router = col.getRouter();@@ -365,8 +311,8 @@ public class CloudSolrServer extends SolrServer {return null;}- NamedList<Throwable> exceptions = new NamedList<>();- NamedList<NamedList> shardResponses = new NamedList<>();+ NamedList<Throwable> exceptions = new NamedList<Throwable>();+ NamedList<NamedList> shardResponses = new NamedList<NamedList>();Map<String, LBHttpSolrServer.Req> routes = updateRequest.getRoutes(router, col, urlMap, routableParams, this.idField);if (routes == null) {@@ -550,145 +496,7 @@ public class CloudSolrServer extends SolrServer {}@Override- public NamedList<Object> request(SolrRequest request) throws SolrServerException, IOException {- SolrParams reqParams = request.getParams();- String collection = (reqParams != null) ? reqParams.get("collection", getDefaultCollection()) : getDefaultCollection();- return requestWithRetryOnStaleState(request, true, collection);- }-- /**- * As this class doesn't watch external collections on the client side,- * there's a chance that the request will fail due to cached stale state,- * which means the state must be refreshed from ZK and retried.- */- protected NamedList<Object> requestWithRetryOnStaleState(SolrRequest request, boolean retry, String collection)- throws SolrServerException, IOException {-- connect(); // important to call this before you start working with the ZkStateReader-- // build up a _stateVer_ param to pass to the server containing all of the- // external collection state versions involved in this request, which allows- // the server to notify us that our cached state for one or more of the external- // collections is stale and needs to be refreshed ... this code has no impact on internal collections- String stateVerParam = null;- List<DocCollection> requestedExternalCollections = null;- if (collection != null && !request.getPath().startsWith("/admin")) { // don't do _stateVer_ checking for admin requests- Set<String> requestedCollectionNames = getCollectionList(getZkStateReader().getClusterState(), collection);- requestedExternalCollections = new ArrayList<DocCollection>(requestedCollectionNames.size());- StringBuilder stateVerParamBuilder = null;- for (String requestedCollection : requestedCollectionNames) {- // track the version of state we're using on the client side using the _stateVer_ param- DocCollection coll = getDocCollection(getZkStateReader().getClusterState(), requestedCollection);- int collVer = coll.getVersion();- if (coll.isExternal()) {- requestedExternalCollections.add(coll);-- if (stateVerParamBuilder == null) {- stateVerParamBuilder = new StringBuilder();- } else {- stateVerParamBuilder.append("|"); // hopefully pipe is not an allowed char in a collection name- }-- stateVerParamBuilder.append(coll.getName()).append(":").append(collVer);- }- }-- if (stateVerParamBuilder != null) {- stateVerParam = stateVerParamBuilder.toString();- }- }-- if (request.getParams() instanceof ModifiableSolrParams) {- ModifiableSolrParams params = (ModifiableSolrParams) request.getParams();- if (stateVerParam != null) {- params.set(STATE_VERSION, stateVerParam);- } else {- params.remove(STATE_VERSION);- }- } // else: ??? how to set this ???-- NamedList<Object> resp = null;- try {- resp = sendRequest(request);- } catch (Exception exc) {-- Throwable rootCause = SolrException.getRootCause(exc);- // don't do retry support for admin requests or if the request doesn't have a collection specified- if (collection == null || request.getPath().startsWith("/admin")) {- if (exc instanceof SolrServerException) {- throw (SolrServerException)exc;- } else if (exc instanceof IOException) {- throw (IOException)exc;- }else if (exc instanceof RuntimeException) {- throw (RuntimeException) exc;- }- else {- throw new SolrServerException(rootCause);- }- }-- int errorCode = (rootCause instanceof SolrException) ?- ((SolrException)rootCause).code() : SolrException.ErrorCode.UNKNOWN.code;-- log.error("Request to collection {} failed due to ("+errorCode+- ") {}, retry? "+retry, collection, rootCause.toString());-- boolean wasCommError =- (rootCause instanceof ConnectException ||- rootCause instanceof ConnectTimeoutException ||- rootCause instanceof NoHttpResponseException ||- rootCause instanceof SocketException);-- boolean stateWasStale = false;- if (retry &&- !requestedExternalCollections.isEmpty() &&- SolrException.ErrorCode.getErrorCode(errorCode) == SolrException.ErrorCode.INVALID_STATE)- {- // cached state for one or more external collections was stale- // re-issue request using updated state- stateWasStale = true;-- // just re-read state for all of them, which is a little heavy handed but hopefully a rare occurrence- for (DocCollection ext : requestedExternalCollections) {- collectionStateCache.remove(ext.getName());- }- }-- // if we experienced a communication error, it's worth checking the state- // with ZK just to make sure the node we're trying to hit is still part of the collection- if (retry && !stateWasStale && !requestedExternalCollections.isEmpty() && wasCommError) {- for (DocCollection ext : requestedExternalCollections) {- DocCollection latestStateFromZk = getZkStateReader().getExternCollection(ext.getName());- if (latestStateFromZk.getVersion() != ext.getVersion()) {- // looks like we couldn't reach the server because the state was stale == retry- stateWasStale = true;- // we just pulled state from ZK, so update the cache so that the retry uses it- collectionStateCache.put(ext.getName(), new ExpiringCachedDocCollection(latestStateFromZk));- }- }- }-- requestedExternalCollections.clear(); // done with this-- // if the state was stale, then we retry the request once with new state pulled from Zk- if (stateWasStale) {- log.warn("Re-trying request to external collection(s) "+collection+" after stale state error from server.");- resp = requestWithRetryOnStaleState(request, false, collection);- } else {- if (exc instanceof SolrServerException) {- throw (SolrServerException)exc;- } else if (exc instanceof IOException) {- throw (IOException)exc;- } else {- throw new SolrServerException(rootCause);- }- }- }-- return resp;- }-- protected NamedList<Object> sendRequest(SolrRequest request)+ public NamedList<Object> request(SolrRequest request)throws SolrServerException, IOException {connect();@@ -748,7 +556,7 @@ public class CloudSolrServer extends SolrServer {// add it to the Map of slices.Map<String,Slice> slices = new HashMap<>();for (String collectionName : collectionsList) {- DocCollection col = getDocCollection(clusterState, collectionName);+ DocCollection col = clusterState.getCollection(collectionName);Collection<Slice> routeSlices = col.getRouter().getSearchSlices(shardKeys, reqParams , col);ClientUtils.addSlices(slices, collectionName, routeSlices, true);}@@ -829,31 +637,26 @@ public class CloudSolrServer extends SolrServer {return rsp.getResponse();}- protected Set<String> getCollectionList(ClusterState clusterState,- String collection) {+ private Set<String> getCollectionList(ClusterState clusterState,+ String collection) {// Extract each comma separated collection name and store in a List.- Set<String> collectionsList = new HashSet<String>();+ List<String> rawCollectionsList = StrUtils.splitSmart(collection, ",", true);+ Set<String> collectionsList = new HashSet<>();// validate collections- List<String> rawCollectionsList = (collection != null) ? StrUtils.splitSmart(collection, ",", true) : null;- if (rawCollectionsList != null) {- for (String collectionName : rawCollectionsList) {- if (!clusterState.hasCollection(collectionName)) {- Aliases aliases = zkStateReader.getAliases();- String alias = aliases.getCollectionAlias(collectionName);- if (alias != null) {- List<String> aliasList = StrUtils.splitSmart(alias, ",", true);- collectionsList.addAll(aliasList);- continue;- }-- DocCollection docCollection = getDocCollection(clusterState, collection);- if (docCollection == null) {- throw new SolrException(ErrorCode.BAD_REQUEST, "Collection not found: " + collectionName);- }+ for (String collectionName : rawCollectionsList) {+ if (!clusterState.getCollections().contains(collectionName)) {+ Aliases aliases = zkStateReader.getAliases();+ String alias = aliases.getCollectionAlias(collectionName);+ if (alias != null) {+ List<String> aliasList = StrUtils.splitSmart(alias, ",", true);+ collectionsList.addAll(aliasList);+ continue;}-- collectionsList.add(collectionName);++ throw new SolrException(ErrorCode.BAD_REQUEST, "Collection not found: " + collectionName);}++ collectionsList.add(collectionName);}return collectionsList;}@@ -889,26 +692,4 @@ public class CloudSolrServer extends SolrServer {return updatesToLeaders;}- protected DocCollection getDocCollection(ClusterState clusterState, String collection) throws SolrException {- ExpiringCachedDocCollection cachedState = collectionStateCache != null ? collectionStateCache.get(collection) : null;- if (cachedState != null && cachedState.cached != null) {- return cachedState.cached;- }-- DocCollection col = clusterState.getCollectionOrNull(collection);- if(col == null ) return null;- collectionStateCache.put(collection, new ExpiringCachedDocCollection(col));- return col;- }-- /**- * Extension point to allow sub-classes to override the ZkStateReader this class uses internally.- */- protected ZkStateReader createZkStateReader(String zkHost, int zkClientTimeout, int zkConnectTimeout)- throws InterruptedException, TimeoutException, IOException, KeeperException {- ZkStateReader zk = new ZkStateReader(zkHost, zkClientTimeout, zkConnectTimeout);- zk.createClusterStateWatchersAndUpdate();- return zk;- }-}diff --git a/solr/solrj/src/java/org/apache/solr/common/cloud/ClusterState.java b/solr/solrj/src/java/org/apache/solr/common/cloud/ClusterState.javaindex 66075deff26..e5bd28b9f8d 100644--- a/solr/solrj/src/java/org/apache/solr/common/cloud/ClusterState.java+++ b/solr/solrj/src/java/org/apache/solr/common/cloud/ClusterState.java@@ -46,7 +46,6 @@ public class ClusterState implements JSONWriter.Writable {private final Map<String, DocCollection> collectionStates; // Map<collectionName, Map<sliceName,Slice>>private Set<String> liveNodes;- private final ZkStateReader stateReader;/**@@ -57,35 +56,26 @@ public class ClusterState implements JSONWriter.Writable {@Deprecatedpublic ClusterState(Set<String> liveNodes,Map<String, DocCollection> collectionStates) {- this(null, liveNodes, collectionStates, null);+ this(null, liveNodes, collectionStates);}- /**- * @deprecated prefer another constructor- */- public ClusterState(Integer zkClusterStateVersion, Set<String> liveNodes,- Map<String, DocCollection> collectionStates) {- this(zkClusterStateVersion, liveNodes, collectionStates, null);- }/*** Use this constr when ClusterState is meant for consumption.*/public ClusterState(Integer zkClusterStateVersion, Set<String> liveNodes,- Map<String, DocCollection> collectionStates, ZkStateReader stateReader) {- assert stateReader != null;+ Map<String, DocCollection> collectionStates) {this.zkClusterStateVersion = zkClusterStateVersion;this.liveNodes = new HashSet<>(liveNodes.size());this.liveNodes.addAll(liveNodes);this.collectionStates = new LinkedHashMap<>(collectionStates.size());this.collectionStates.putAll(collectionStates);- this.stateReader = stateReader;}public ClusterState copyWith(Map<String,DocCollection> modified){- ClusterState result = new ClusterState(zkClusterStateVersion, liveNodes,collectionStates,stateReader);+ ClusterState result = new ClusterState(zkClusterStateVersion, liveNodes,collectionStates);for (Entry<String, DocCollection> e : modified.entrySet()) {DocCollection c = e.getValue();if(c == null) {@@ -108,12 +98,27 @@ public class ClusterState implements JSONWriter.Writable {if (slice == null) return null;return slice.getLeader();}+ private Replica getReplica(DocCollection coll, String replicaName) {+ if (coll == null) return null;+ for (Slice slice : coll.getSlices()) {+ Replica replica = slice.getReplica(replicaName);+ if (replica != null) return replica;+ }+ return null;+ }public boolean hasCollection(String coll) {- if (collectionStates.containsKey(coll)) return true;- return stateReader.getAllCollections().contains(coll);+ return collectionStates.containsKey(coll) ;}+ /**+ * Gets the replica by the core name (assuming the slice is unknown) or null if replica is not found.+ * If the slice is known, do not use this method.+ * coreNodeName is the same as replicaName+ */+ public Replica getReplica(final String collection, final String coreNodeName) {+ return getReplica(collectionStates.get(collection), coreNodeName);+ }/*** Get the named Slice for collection, or null if not found.@@ -148,35 +153,6 @@ public class ClusterState implements JSONWriter.Writable {return coll.getActiveSlices();}- /**- * Get the {@code DocCollection} object if available. This method will- * never hit ZooKeeper and attempt to fetch collection from locally available- * state only.- *- * @param collection the name of the collection- * @return the {@link org.apache.solr.common.cloud.DocCollection} or null if not found- */- public DocCollection getCachedCollection(String collection) {- DocCollection c = collectionStates.get(collection);- if (c != null) return c;- if (!stateReader.getAllCollections().contains(collection)) return null;- return stateReader.getExternCollection(collection, true); // return from cache- }-- /**- * Gets the replica from caches by the core name (assuming the slice is unknown) or null if replica is not found.- * If the slice is known, do not use this method.- * coreNodeName is the same as replicaName- */- public Replica getCachedReplica(String collectionName, String coreNodeName) {- DocCollection c = getCachedCollection(collectionName);- if (c == null) return null;- for (Slice slice : c.getSlices()) {- Replica replica = slice.getReplica(coreNodeName);- if (replica != null) return replica;- }- return null;- }/*** Get the named DocCollection object, or throw an exception if it doesn't exist.@@ -187,29 +163,21 @@ public class ClusterState implements JSONWriter.Writable {return coll;}- private DocCollection loadExtDocCollection(String coll) {- return stateReader.getExternCollection(coll);- }public DocCollection getCollectionOrNull(String coll) {- DocCollection c = collectionStates.get(coll);- if (c != null) return c;- if (!stateReader.getAllCollections().contains(coll)) return null;- return loadExtDocCollection(coll);+ return collectionStates.get(coll);}/*** Get collection names.*/public Set<String> getCollections() {- return stateReader.getAllCollections();+ return collectionStates.keySet();}/**- * @deprecated use #getAllCollections instead* @return Map<collectionName, Map<sliceName,Slice>>*/- @Deprecatedpublic Map<String, DocCollection> getCollectionStates() {return Collections.unmodifiableMap(collectionStates);}@@ -270,7 +238,7 @@ public class ClusterState implements JSONWriter.Writable {Stat stat = new Stat();byte[] state = zkClient.getData(ZkStateReader.CLUSTER_STATE,null, stat, true);- return load(stat.getVersion(), state, liveNodes, stateReader);+ return load(stat.getVersion(), state, liveNodes);}@@ -284,10 +252,10 @@ public class ClusterState implements JSONWriter.Writable {* @param liveNodes list of live nodes* @return the ClusterState*/- public static ClusterState load(Integer version, byte[] bytes, Set<String> liveNodes, ZkStateReader stateReader) {+ public static ClusterState load(Integer version, byte[] bytes, Set<String> liveNodes) {// System.out.println("######## ClusterState.load:" + (bytes==null ? null : new String(bytes)));if (bytes == null || bytes.length == 0) {- return new ClusterState(version, liveNodes, Collections.<String, DocCollection>emptyMap(),stateReader);+ return new ClusterState(version, liveNodes, Collections.<String, DocCollection>emptyMap());}Map<String, Object> stateMap = (Map<String, Object>) ZkStateReader.fromJSON(bytes);Map<String,DocCollection> collections = new LinkedHashMap<>(stateMap.size());@@ -298,17 +266,10 @@ public class ClusterState implements JSONWriter.Writable {}// System.out.println("######## ClusterState.load result:" + collections);- return new ClusterState( version, liveNodes, collections,stateReader);+ return new ClusterState( version, liveNodes, collections);}- /**- * @deprecated use {@link #load(Integer, byte[], Set, ZkStateReader)}- */- @Deprecated- public static ClusterState load(Integer version, byte[] bytes, Set<String> liveNodes){- return load(version == null ? -1: version, bytes, liveNodes,null);- }-+public static Aliases load(byte[] bytes) {if (bytes == null || bytes.length == 0) {return new Aliases();@@ -403,17 +364,6 @@ public class ClusterState implements JSONWriter.Writable {}- public boolean hasExternalCollection(String coll) {- return stateReader.getAllCollections().contains(coll) && !collectionStates.containsKey(coll);-- }- public Set<String> getAllInternalCollections(){- return Collections.unmodifiableSet(collectionStates.keySet());- }-- public ZkStateReader getStateReader(){- return stateReader;- }/*** Internal API used only by ZkStateReaderdiff --git a/solr/solrj/src/java/org/apache/solr/common/cloud/DocCollection.java b/solr/solrj/src/java/org/apache/solr/common/cloud/DocCollection.javaindex f273464979c..a02dfd5e174 100644--- a/solr/solrj/src/java/org/apache/solr/common/cloud/DocCollection.java+++ b/solr/solrj/src/java/org/apache/solr/common/cloud/DocCollection.java@@ -33,14 +33,12 @@ import java.util.Map;public class DocCollection extends ZkNodeProps {public static final String DOC_ROUTER = "router";public static final String SHARDS = "shards";- public static final String STATE_FORMAT = "stateFormat";private int version;private final String name;private final Map<String, Slice> slices;private final Map<String, Slice> activeSlices;private final DocRouter router;- private final boolean external;public DocCollection(String name, Map<String, Slice> slices, Map<String, Object> props, DocRouter router) {this(name, slices, props, router, -1);@@ -67,7 +65,6 @@ public class DocCollection extends ZkNodeProps {this.activeSlices.put(slice.getKey(), slice.getValue());}this.router = router;- external = getInt(STATE_FORMAT,1)>1;assert name != null && slices != null;}@@ -118,10 +115,6 @@ public class DocCollection extends ZkNodeProps {}- public boolean isExternal(){- return external;- }-public DocRouter getRouter() {return router;diff --git a/solr/solrj/src/java/org/apache/solr/common/cloud/ZkStateReader.java b/solr/solrj/src/java/org/apache/solr/common/cloud/ZkStateReader.javaindex 808aa7cbf41..57fb1a14000 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@@ -98,10 +98,7 @@ public class ZkStateReader {public static final String LEADER_ELECT_ZKNODE = "/leader_elect";public static final String SHARD_LEADERS_ZKNODE = "leaders";- private final Set<String> watchedCollections = new HashSet<String>();- private Map<String , DocCollection> externalWatchedCollections = new ConcurrentHashMap<String, DocCollection>();- private Set<String> allCollections = Collections.emptySet();@@ -254,7 +251,7 @@ public class ZkStateReader {return aliases;}- public Boolean checkValid(String coll, int version){+ /*public Boolean checkValid(String coll, int version){DocCollection collection = clusterState.getCollectionOrNull(coll);if(collection ==null) return null;if(collection.getVersion() < version){@@ -269,7 +266,7 @@ public class ZkStateReader {log.info("wrong version from client {}!={} ",version, collection.getVersion());return Boolean.FALSE;- }+ }*/public synchronized void createClusterStateWatchersAndUpdate() throws KeeperException,InterruptedException {@@ -302,11 +299,10 @@ public class ZkStateReader {byte[] data = zkClient.getData(CLUSTER_STATE, thisWatch, stat ,true);Set<String> ln = ZkStateReader.this.clusterState.getLiveNodes();- ClusterState clusterState = ClusterState.load(stat.getVersion(), data, ln,ZkStateReader.this);+ ClusterState clusterState = ClusterState.load(stat.getVersion(), data, ln);// update volatileZkStateReader.this.clusterState = clusterState;- updateCollectionNames();// HashSet<String> all = new HashSet<>(colls);;// all.addAll(clusterState.getAllInternalCollections());// all.remove(null);@@ -381,8 +377,7 @@ public class ZkStateReader {liveNodeSet.addAll(liveNodes);ClusterState clusterState = ClusterState.load(zkClient, liveNodeSet, ZkStateReader.this);this.clusterState = clusterState;- updateCollectionNames();-+zkClient.exists(ALIASES,new Watcher() {@@ -427,40 +422,6 @@ public class ZkStateReader {}, true);}updateAliases();- //on reconnect of SolrZkClient re-add watchers for the watched external collections- synchronized (this){- for (String watchedCollection : watchedCollections) {- addZkWatch(watchedCollection);- }- }- }-- public void updateCollectionNames() throws KeeperException, InterruptedException {- Set<String> colls = getExternColls();- colls.addAll(clusterState.getAllInternalCollections());- allCollections = Collections.unmodifiableSet(colls);- }-- private Set<String> getExternColls() throws KeeperException, InterruptedException {- List<String> children = null;- try {- children = zkClient.getChildren(COLLECTIONS_ZKNODE, null, true);- } catch (KeeperException.NoNodeException e) {- log.warn("Error fetching collection names");-- return new HashSet<>();- }- if(children == null || children.isEmpty()) return new HashSet<>();- HashSet<String> result = new HashSet<>(children.size());-- for (String c : children) {- try {- if(zkClient.exists(getCollectionPath(c),true)) result.add(c);- } catch (Exception e) {- log.warn("Error checking external collections", e);- }- }- return result;}@@ -488,7 +449,6 @@ public class ZkStateReader {clusterState.setLiveNodes(liveNodesSet);}this.clusterState = clusterState;- updateCollectionNames();}} else {@@ -547,11 +507,7 @@ public class ZkStateReader {}}, SOLRCLOUD_UPDATE_DELAY, TimeUnit.MILLISECONDS);}- synchronized (this) {- for (String watchedCollection : watchedCollections) {- externalWatchedCollections.put(watchedCollection, getExternCollectionFresh(this, watchedCollection));- }- }+}/**@@ -676,9 +632,6 @@ public class ZkStateReader {public SolrZkClient getZkClient() {return zkClient;}- public Set<String> getAllCollections(){- return allCollections;- }public void updateAliases() throws KeeperException, InterruptedException {byte[] data = zkClient.getData(ALIASES, null, null, true);@@ -725,154 +678,4 @@ public class ZkStateReader {}}- public void updateExternCollection(DocCollection c) {- if(watchedCollections.contains(c.getName())){- externalWatchedCollections.put(c.getName(), c);- log.info("Updated DocCollection "+c.getName()+" to: ");- }- }-- /**- * <b>Advance usage</b>- * This method can be used to fetch a collection object and control whether it hits- * the cache only or if information can be looked up from ZooKeeper.- *- * @param coll the collection name- * @param cachedCopyOnly whether to fetch data from cache only or if hitting Zookeeper is acceptable- * @return the {@link org.apache.solr.common.cloud.DocCollection}- */- public DocCollection getExternCollection(String coll, boolean cachedCopyOnly) {- if (watchedCollections.contains(coll) || cachedCopyOnly) {- DocCollection c = externalWatchedCollections.get(coll);- if (c != null || cachedCopyOnly) return c;- }-- return getExternCollectionFresh(this, coll);- }- // this is only set by Overseer not to be set by others. If Overseer has- // unfinished external collections which are yet to be persisted to ZK- // this map is populated and this class can use that information- public Map ephemeralCollectionData;-- public static DocCollection getExternCollectionFresh(ZkStateReader zkStateReader, String coll) {- String collectionPath = getCollectionPath(coll);- if(zkStateReader.ephemeralCollectionData !=null ){- ClusterState cs = (ClusterState) zkStateReader.ephemeralCollectionData.get(collectionPath);- if(cs !=null) {- return cs.getCommonCollection(coll);- }- }- try {- if (!zkStateReader.getZkClient().exists(collectionPath, true)) return null;- Stat stat = new Stat();- byte[] data = zkStateReader.getZkClient().getData(collectionPath, null, stat, true);- ClusterState state = ClusterState.load(stat.getVersion(), data, Collections.<String>emptySet(), zkStateReader);- return state.getCommonCollection(coll);- } catch (KeeperException.NoNodeException e) {- log.warn("No node available : " + collectionPath, e);- return null;- } catch (KeeperException e) {- throw new SolrException(ErrorCode.BAD_REQUEST, "Could not load collection from ZK:" + coll, e);- } catch (InterruptedException e) {- throw new SolrException(ErrorCode.BAD_REQUEST, "Could not load collection from ZK:" + coll, e);- }- }-- public DocCollection getExternCollection(String coll) {- return getExternCollection(coll, false);- }-- public static String getCollectionPath(String coll) {- return COLLECTIONS_ZKNODE+"/"+coll + "/state";- }-- public void addCollectionWatch(String coll) throws KeeperException, InterruptedException {- synchronized (this){- if(watchedCollections.contains(coll)) return;- else {- watchedCollections.add(coll);- }- addZkWatch(coll);- }-- }-- private void addZkWatch(final String coll) throws KeeperException, InterruptedException {- log.info("addZkWatch {}", coll);- final String fullpath = getCollectionPath(coll);- synchronized (getUpdateLock()){-- cmdExecutor.ensureExists(fullpath, zkClient);- log.info("Updating collection state at {} from ZooKeeper... ",fullpath);-- Watcher watcher = new Watcher() {-- @Override- public void process(WatchedEvent event) {- // session events are not change events,- // and do not remove the watcher- if (EventType.None.equals(event.getType())) {- return;- }- log.info("A cluster state change: {}, has occurred - updating... ", (event), ZkStateReader.this.clusterState == null ? 0 : ZkStateReader.this.clusterState.getLiveNodes().size());- try {-- // delayed approach- // ZkStateReader.this.updateClusterState(false, false);- synchronized (ZkStateReader.this.getUpdateLock()) {- if(!watchedCollections.contains(coll)) {- log.info("Unwatched collection {}",coll);- return;- }- // remake watch- final Watcher thisWatch = this;- Stat stat = new Stat();- byte[] data = zkClient.getData(fullpath, thisWatch, stat, true);- if(data == null || data.length ==0){- log.warn("No value set for collection state : {}", coll);- return;-- }- ClusterState clusterState = ClusterState.load(stat.getVersion(), data, Collections.<String>emptySet(),ZkStateReader.this);- // update volatile-- externalWatchedCollections.put(coll,clusterState.getCommonCollection(coll));- log.info("Updating data for {} ", coll);-- }- } catch (KeeperException e) {- if (e.code() == KeeperException.Code.SESSIONEXPIRED- || e.code() == KeeperException.Code.CONNECTIONLOSS) {- log.warn("ZooKeeper watch triggered, but Solr cannot talk to ZK");- return;- }- log.error("Unwatched collection :"+coll , e);- throw new ZooKeeperException(ErrorCode.SERVER_ERROR,- "", e);-- } catch (InterruptedException e) {- // Restore the interrupted status- Thread.currentThread().interrupt();- log.error("Unwatched collection :"+coll , e);- return;- }- }-- };- zkClient.exists(fullpath, watcher, true);- }-- externalWatchedCollections.put(coll, getExternCollectionFresh(this, coll));- }-- /**This is not a public API. Only used by ZkController */- public void removeZKWatch(final String coll){- synchronized (this){- watchedCollections.remove(coll);- }- }----}diff --git a/solr/solrj/src/test/org/apache/solr/client/solrj/impl/CloudSolrServerTest.java b/solr/solrj/src/test/org/apache/solr/client/solrj/impl/CloudSolrServerTest.javaindex 6524b491de4..5b3d87db929 100644--- a/solr/solrj/src/test/org/apache/solr/client/solrj/impl/CloudSolrServerTest.java+++ b/solr/solrj/src/test/org/apache/solr/client/solrj/impl/CloudSolrServerTest.java@@ -124,7 +124,6 @@ public class CloudSolrServerTest extends AbstractFullDistribZkTestBase {@Overridepublic void doTest() throws Exception {allTests();- testStateVersionParam();}private void allTests() throws Exception {@@ -346,81 +345,6 @@ public class CloudSolrServerTest extends AbstractFullDistribZkTestBase {SolrInputDocument doc = getDoc(fields);indexDoc(doc);}- private void testStateVersionParam() throws Exception {- CloudSolrServer client = createCloudClient(null);- String collectionName = "checkStateVerCol";- createCollection(collectionName, client, 2, 2);- waitForRecoveriesToFinish(collectionName, false);-- SolrZkClient zk = client.getZkStateReader().getZkClient();--- DocCollection coll = client.getZkStateReader().getClusterState().getCollection(collectionName);-- Replica r = coll.getSlices().iterator().next().getReplicas().iterator().next();--- HttpSolrServer httpSolrServer = new HttpSolrServer(r.getStr(ZkStateReader.BASE_URL_PROP) + "/"+collectionName);--- SolrQuery q = new SolrQuery().setQuery("*:*");-- log.info("should work query, result {}", httpSolrServer.query(q));- //no problem- q.setParam(CloudSolrServer.STATE_VERSION, collectionName+":"+coll.getVersion());- log.info("2nd query , result {}", httpSolrServer.query(q));- //no error yet good-- q.setParam(CloudSolrServer.STATE_VERSION, collectionName+":"+ (coll.getVersion() -1)); //an older version expect error-- HttpSolrServer.RemoteSolrException sse = null;- try {- httpSolrServer.query(q);- log.info("expected query error");- } catch (HttpSolrServer.RemoteSolrException e) {- sse = e;- }- assertNotNull(sse);- assertEquals(" Error code should be ", sse.code() , SolrException.ErrorCode.INVALID_STATE.code);-- //now send the request to another node that does n ot serve the collection-- Set<String> allNodesOfColl = new HashSet<>();- for (Slice slice : coll.getSlices()) {- for (Replica replica : slice.getReplicas()) {- allNodesOfColl.add(replica.getStr(ZkStateReader.BASE_URL_PROP));- }- }-- String theNode = null;-- for (String s : client.getZkStateReader().getClusterState().getLiveNodes()) {- String n = client.getZkStateReader().getBaseUrlForNodeName(s);- if(!allNodesOfColl.contains(s)){- theNode = n;- break;- }- }- log.info("thenode which does not serve this collection{} ",theNode);- assertNotNull(theNode);- httpSolrServer = new HttpSolrServer(theNode + "/"+collectionName);-- q.setParam(CloudSolrServer.STATE_VERSION, collectionName+":"+coll.getVersion());-- try {- httpSolrServer.query(q);- log.info("error was expected");- } catch (HttpSolrServer.RemoteSolrException e) {- sse = e;- }- assertNotNull(sse);- assertEquals(" Error code should be ", sse.code() , SolrException.ErrorCode.INVALID_STATE.code);--- client.shutdown();--- }public void testShutdown() throws MalformedURLException {CloudSolrServer server = new CloudSolrServer("[ff01::114]:33332");diff --git a/solr/test-framework/src/java/org/apache/solr/cloud/AbstractFullDistribZkTestBase.java b/solr/test-framework/src/java/org/apache/solr/cloud/AbstractFullDistribZkTestBase.javaindex 384c5d72ac6..3958d4258e3 100644--- a/solr/test-framework/src/java/org/apache/solr/cloud/AbstractFullDistribZkTestBase.java+++ b/solr/test-framework/src/java/org/apache/solr/cloud/AbstractFullDistribZkTestBase.java@@ -337,19 +337,6 @@ public abstract class AbstractFullDistribZkTestBase extends AbstractDistribZkTesreturn createJettys(numJettys, false);}- protected int defaultStateFormat = 1 + random().nextInt(2);-- protected int getStateFormat() {- String stateFormat = System.getProperty("tests.solr.stateFormat", null);- if (stateFormat != null) {- if ("2".equals(stateFormat)) {- return defaultStateFormat = 2;- } else if ("1".equals(stateFormat)) {- return defaultStateFormat = 1;- }- }- return defaultStateFormat; // random- }/*** @param checkCreatedVsState@@ -362,17 +349,6 @@ public abstract class AbstractFullDistribZkTestBase extends AbstractDistribZkTesList<SolrServer> clients = new ArrayList<>();StringBuilder sb = new StringBuilder();- if(getStateFormat() == 2) {- log.info("Creating collection1 with stateFormat=2");- SolrZkClient zkClient = new SolrZkClient(zkServer.getZkAddress(), AbstractZkTestCase.TIMEOUT, AbstractZkTestCase.TIMEOUT);- Overseer.getInQueue(zkClient).offer(ZkStateReader.toJSON(ZkNodeProps.makeMap(- Overseer.QUEUE_OPERATION, OverseerCollectionProcessor.CREATECOLLECTION,- "name", DEFAULT_COLLECTION,- "numShards", String.valueOf(sliceCount),- DocCollection.STATE_FORMAT, getStateFormat())));- zkClient.close();- }-for (int i = 1; i <= numJettys; i++) {if (sb.length() > 0) sb.append(',');int cnt = this.jettyIntCntr.incrementAndGet();@@ -1512,10 +1488,6 @@ public abstract class AbstractFullDistribZkTestBase extends AbstractDistribZkTescollectionInfos.put(collectionName, list);}params.set("name", collectionName);- if (useExternalCollections()) {- log.info("Creating external collection: " + collectionName);- params.set(DocCollection.STATE_FORMAT, "2");- }SolrRequest request = new QueryRequest(params);request.setPath("/admin/collections");@@ -1535,10 +1507,6 @@ public abstract class AbstractFullDistribZkTestBase extends AbstractDistribZkTes}- public boolean useExternalCollections() {- return getStateFormat() == 2;- }-protected CollectionAdminResponse createCollection(Map<String,List<Integer>> collectionInfos,String collectionName, int numShards, int replicationFactor, int maxShardsPerNode, SolrServer client, String createNodeSetStr) throws SolrServerException, IOException {diff --git a/solr/webapp/web/js/scripts/cloud.js b/solr/webapp/web/js/scripts/cloud.jsindex 52467ec5db0..d78cb459939 100644--- a/solr/webapp/web/js/scripts/cloud.js+++ b/solr/webapp/web/js/scripts/cloud.js@@ -368,7 +368,7 @@ var prepare_graph = function( graph_element, callback )$.ajax({- url : app.config.solr_path + '/zookeeper?wt=json&detail=true&path=%2Fclusterstate.json&all=true',+ url : app.config.solr_path + '/zookeeper?wt=json&detail=true&path=%2Fclusterstate.json',dataType : 'json',context : graph_element,beforeSend : function( xhr, settings )