Skip to content

armgit / solr

Public Imported from GitHub
0

Apache Solr open-source search software

SOLR-4497: Collection Aliasing.

Mark Robert Miller09f4fa21918b
diff --git a/solr/CHANGES.txt b/solr/CHANGES.txt
index 5189b6f9eef..bcbf37f60e4 100644
--- a/solr/CHANGES.txt
+++ b/solr/CHANGES.txt
@@ -218,6 +218,8 @@ Bug Fixes
dynamic field references that aren't string-equal to the name of
the referenced dynamic field. (Steve Rowe)
+* SOLR-4497: Collection Aliasing. (Mark Miller)
+
Optimizations
----------------------
diff --git a/solr/core/src/java/org/apache/solr/cloud/OverseerCollectionProcessor.java b/solr/core/src/java/org/apache/solr/cloud/OverseerCollectionProcessor.java
index db16f352685..19854abda0c 100644
--- a/solr/core/src/java/org/apache/solr/cloud/OverseerCollectionProcessor.java
+++ b/solr/core/src/java/org/apache/solr/cloud/OverseerCollectionProcessor.java
@@ -19,6 +19,7 @@ package org.apache.solr.cloud;
import java.util.ArrayList;
import java.util.Collections;
+import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
@@ -27,6 +28,7 @@ import org.apache.solr.client.solrj.SolrResponse;
import org.apache.solr.cloud.DistributedQueue.QueueEvent;
import org.apache.solr.common.SolrException;
import org.apache.solr.common.SolrException.ErrorCode;
+import org.apache.solr.common.cloud.Aliases;
import org.apache.solr.common.cloud.ClosableThread;
import org.apache.solr.common.cloud.ClusterState;
import org.apache.solr.common.cloud.DocCollection;
@@ -63,10 +65,12 @@ public class OverseerCollectionProcessor implements Runnable, ClosableThread {
public static final String RELOADCOLLECTION = "reloadcollection";
+ public static final String CREATEALIAS = "createalias";
+
+ public static final String DELETEALIAS = "deletealias";
+
// TODO: use from Overseer?
private static final String QUEUE_OPERATION = "operation";
-
-
private static Logger log = LoggerFactory
.getLogger(OverseerCollectionProcessor.class);
@@ -162,6 +166,10 @@ public class OverseerCollectionProcessor implements Runnable, ClosableThread {
ModifiableSolrParams params = new ModifiableSolrParams();
params.set(CoreAdminParams.ACTION, CoreAdminAction.RELOAD.toString());
collectionCmd(zkStateReader.getClusterState(), message, params);
+ } else if (CREATEALIAS.equals(operation)) {
+ createAlias(zkStateReader.getAliases(), message);
+ } else if (DELETEALIAS.equals(operation)) {
+ deleteAlias(zkStateReader.getAliases(), message);
} else {
throw new SolrException(ErrorCode.BAD_REQUEST, "Unknow the operation:"
+ operation);
@@ -182,15 +190,116 @@ public class OverseerCollectionProcessor implements Runnable, ClosableThread {
}
}
} while (srsp != null);
- } catch (SolrException ex) {
+ } catch (Exception ex) {
SolrException.log(log, "Collection " + operation + " of " + operation
- + " failed");
+ + " failed", ex);
results.add("Operation " + operation + " caused exception:", ex);
} finally {
return new OverseerSolrResponse(results);
}
}
+ private void createAlias(Aliases aliases, ZkNodeProps message) {
+ String aliasName = message.getStr("name");
+ String collections = message.getStr("collections");
+
+ Map<String,Map<String,String>> newAliasesMap = new HashMap<String,Map<String,String>>();
+ Map<String,String> newCollectionAliasesMap = new HashMap<String,String>();
+ Map<String,String> prevColAliases = aliases.getCollectionAliasMap();
+ if (prevColAliases != null) {
+ newCollectionAliasesMap.putAll(prevColAliases);
+ }
+ newCollectionAliasesMap.put(aliasName, collections);
+ newAliasesMap.put("collection", newCollectionAliasesMap);
+ Aliases newAliases = new Aliases(newAliasesMap);
+ byte[] jsonBytes = null;
+ if (newAliases.collectionAliasSize() > 0) { // only sub map right now
+ jsonBytes = ZkStateReader.toJSON(newAliases.getAliasMap());
+ }
+ try {
+ zkStateReader.getZkClient().setData(ZkStateReader.ALIASES,
+ jsonBytes, true);
+
+ checkForAlias(aliasName, collections);
+ // some fudge for other nodes
+ Thread.sleep(100);
+ } catch (KeeperException e) {
+ log.error("", e);
+ throw new SolrException(ErrorCode.SERVER_ERROR, e);
+ } catch (InterruptedException e) {
+ log.warn("", e);
+ throw new SolrException(ErrorCode.SERVER_ERROR, e);
+ }
+
+ }
+
+ private void checkForAlias(String name, String value) {
+
+ long now = System.currentTimeMillis();
+ long timeout = now + 30000;
+ boolean success = false;
+ Aliases aliases = null;
+ while (System.currentTimeMillis() < timeout) {
+ aliases = zkStateReader.getAliases();
+ String collections = aliases.getCollectionAlias(name);
+ if (collections != null && collections.equals(value)) {
+ success = true;
+ break;
+ }
+ }
+ if (!success) {
+ log.warn("Timeout waiting to be notified of Alias change...");
+ }
+ }
+
+ private void checkForAliasAbsence(String name) {
+
+ long now = System.currentTimeMillis();
+ long timeout = now + 30000;
+ boolean success = false;
+ Aliases aliases = null;
+ while (System.currentTimeMillis() < timeout) {
+ aliases = zkStateReader.getAliases();
+ String collections = aliases.getCollectionAlias(name);
+ if (collections == null) {
+ success = true;
+ break;
+ }
+ }
+ if (!success) {
+ log.warn("Timeout waiting to be notified of Alias change...");
+ }
+ }
+
+ private void deleteAlias(Aliases aliases, ZkNodeProps message) {
+ String aliasName = message.getStr("name");
+
+ Map<String,Map<String,String>> newAliasesMap = new HashMap<String,Map<String,String>>();
+ Map<String,String> newCollectionAliasesMap = new HashMap<String,String>();
+ newCollectionAliasesMap.putAll(aliases.getCollectionAliasMap());
+ newCollectionAliasesMap.remove(aliasName);
+ newAliasesMap.put("collection", newCollectionAliasesMap);
+ Aliases newAliases = new Aliases(newAliasesMap);
+ byte[] jsonBytes = null;
+ if (newAliases.collectionAliasSize() > 0) { // only sub map right now
+ jsonBytes = ZkStateReader.toJSON(newAliases.getAliasMap());
+ }
+ try {
+ zkStateReader.getZkClient().setData(ZkStateReader.ALIASES,
+ jsonBytes, true);
+ checkForAliasAbsence(aliasName);
+ // some fudge for other nodes
+ Thread.sleep(100);
+ } catch (KeeperException e) {
+ log.error("", e);
+ throw new SolrException(ErrorCode.SERVER_ERROR, e);
+ } catch (InterruptedException e) {
+ log.warn("", e);
+ throw new SolrException(ErrorCode.SERVER_ERROR, e);
+ }
+
+ }
+
private boolean createCollection(ClusterState clusterState, ZkNodeProps message) {
String collectionName = message.getStr("name");
if (clusterState.getCollections().contains(collectionName)) {
diff --git a/solr/core/src/java/org/apache/solr/handler/admin/CollectionsHandler.java b/solr/core/src/java/org/apache/solr/handler/admin/CollectionsHandler.java
index 2060dfb212f..a77c5c58035 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
@@ -120,7 +120,14 @@ public class CollectionsHandler extends RequestHandlerBase {
this.handleSyncShardAction(req, rsp);
break;
}
-
+ case CREATEALIAS: {
+ this.handleCreateAliasAction(req, rsp);
+ break;
+ }
+ case DELETEALIAS: {
+ this.handleDeleteAliasAction(req, rsp);
+ break;
+ }
default: {
throw new RuntimeException("Unknown action: " + action);
}
@@ -187,7 +194,30 @@ public class CollectionsHandler extends RequestHandlerBase {
reqSyncShard.setCoreName(nodeProps.getCoreName());
server.request(reqSyncShard);
}
-
+
+ private void handleCreateAliasAction(SolrQueryRequest req,
+ SolrQueryResponse rsp) throws Exception {
+ log.info("Create alias action : " + req.getParamString());
+ String name = req.getParams().required().get("name");
+ String collections = req.getParams().required().get("collections");
+
+ ZkNodeProps m = new ZkNodeProps(Overseer.QUEUE_OPERATION,
+ OverseerCollectionProcessor.CREATEALIAS, "name", name, "collections",
+ collections);
+
+ handleResponse(OverseerCollectionProcessor.CREATEALIAS, m, rsp);
+ }
+
+ private void handleDeleteAliasAction(SolrQueryRequest req,
+ SolrQueryResponse rsp) throws Exception {
+ log.info("Delete alias action : " + req.getParamString());
+ String name = req.getParams().required().get("name");
+
+ ZkNodeProps m = new ZkNodeProps(Overseer.QUEUE_OPERATION,
+ OverseerCollectionProcessor.DELETEALIAS, "name", name);
+
+ handleResponse(OverseerCollectionProcessor.CREATEALIAS, m, rsp);
+ }
private void handleDeleteAction(SolrQueryRequest req, SolrQueryResponse rsp) throws KeeperException, InterruptedException {
log.info("Deleting Collection : " + req.getParamString());
@@ -200,7 +230,6 @@ public class CollectionsHandler extends RequestHandlerBase {
handleResponse(OverseerCollectionProcessor.DELETECOLLECTION, m, rsp);
}
-
// very simple currently, you can pass a template collection, and the new collection is created on
// every node the template collection is on
// there is a lot more to add - you should also be able to create with an explicit server list
diff --git a/solr/core/src/java/org/apache/solr/servlet/SolrDispatchFilter.java b/solr/core/src/java/org/apache/solr/servlet/SolrDispatchFilter.java
index 5715d923111..cbc596a139c 100644
--- a/solr/core/src/java/org/apache/solr/servlet/SolrDispatchFilter.java
+++ b/solr/core/src/java/org/apache/solr/servlet/SolrDispatchFilter.java
@@ -17,8 +17,6 @@
package org.apache.solr.servlet;
-import java.io.BufferedInputStream;
-import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
@@ -31,6 +29,7 @@ import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Enumeration;
+import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
@@ -42,7 +41,6 @@ import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
-import javax.servlet.ServletOutputStream;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
@@ -50,6 +48,7 @@ import javax.servlet.http.HttpServletResponse;
import org.apache.commons.io.IOUtils;
import org.apache.solr.common.SolrException;
+import org.apache.solr.common.cloud.Aliases;
import org.apache.solr.common.cloud.ClusterState;
import org.apache.solr.common.cloud.Replica;
import org.apache.solr.common.cloud.Slice;
@@ -58,10 +57,12 @@ import org.apache.solr.common.cloud.ZkNodeProps;
import org.apache.solr.common.cloud.ZkStateReader;
import org.apache.solr.common.params.CommonParams;
import org.apache.solr.common.params.MapSolrParams;
+import org.apache.solr.common.params.ModifiableSolrParams;
import org.apache.solr.common.params.SolrParams;
import org.apache.solr.common.util.ContentStreamBase;
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.core.CoreContainer;
import org.apache.solr.core.SolrConfig;
import org.apache.solr.core.SolrCore;
@@ -134,9 +135,13 @@ public class SolrDispatchFilter implements Filter
cores = null;
}
}
-
+
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
+ doFilter(request, response, chain, false);
+ }
+
+ public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain, boolean retry) throws IOException, ServletException {
if( abortErrorMessage != null ) {
((HttpServletResponse)response).sendError( 500, abortErrorMessage );
return;
@@ -149,12 +154,14 @@ public class SolrDispatchFilter implements Filter
CoreContainer cores = this.cores;
SolrCore core = null;
SolrQueryRequest solrReq = null;
+ Aliases aliases = null;
if( request instanceof HttpServletRequest) {
HttpServletRequest req = (HttpServletRequest)request;
HttpServletResponse resp = (HttpServletResponse)response;
SolrRequestHandler handler = null;
String corename = "";
+ String origCorename = null;
try {
// put the core container in request attribute
req.setAttribute("org.apache.solr.CoreContainer", cores);
@@ -185,6 +192,8 @@ public class SolrDispatchFilter implements Filter
handleAdminRequest(req, response, handler, solrReq);
return;
}
+ boolean usingAliases = false;
+ List<String> collectionsList = null;
// Check for the core admin collections url
if( path.equals( "/admin/collections" ) ) {
handler = cores.getCollectionsHandler();
@@ -198,7 +207,24 @@ public class SolrDispatchFilter implements Filter
if( idx > 1 ) {
// try to get the corename as a request parameter first
corename = path.substring( 1, idx );
+
+ // look at aliases
+ if (cores.isZooKeeperAware()) {
+ origCorename = corename;
+ ZkStateReader reader = cores.getZkController().getZkStateReader();
+ aliases = reader.getAliases();
+ if (aliases != null && aliases.collectionAliasSize() > 0) {
+ usingAliases = true;
+ String alias = aliases.getCollectionAlias(corename);
+ if (alias != null) {
+ collectionsList = StrUtils.splitSmart(alias, ",", true);
+ corename = collectionsList.get(0);
+ }
+ }
+ }
+
core = cores.getCore(corename);
+
if (core != null) {
path = path.substring( idx );
}
@@ -221,11 +247,19 @@ public class SolrDispatchFilter implements Filter
// if we couldn't find it locally, look on other nodes
if (core == null && idx > 0) {
- String coreUrl = getRemotCoreUrl(cores, corename);
+ String coreUrl = getRemotCoreUrl(cores, corename, origCorename);
if (coreUrl != null) {
path = path.substring( idx );
remoteQuery(coreUrl + path, req, solrReq, resp);
return;
+ } else {
+ if (!retry) {
+ // we couldn't find a core to work with, try reloading aliases
+ ZkStateReader reader = cores.getZkController()
+ .getZkStateReader();
+ reader.updateAliases();
+ doFilter(request, response, chain, true);
+ }
}
}
@@ -289,6 +323,10 @@ public class SolrDispatchFilter implements Filter
solrReq = parser.parse( core, path, req );
}
+ if (usingAliases) {
+ processAliases(solrReq, aliases, collectionsList);
+ }
+
final Method reqMethod = Method.getMethod(req.getMethod());
HttpCacheHeaderUtil.setCacheControlHeader(config, resp, reqMethod);
// unless we have been explicitly told not to, do cache validation
@@ -341,9 +379,44 @@ public class SolrDispatchFilter implements Filter
chain.doFilter(request, response);
}
+ private void processAliases(SolrQueryRequest solrReq, Aliases aliases,
+ List<String> collectionsList) {
+ String collection = solrReq.getParams().get("collection");
+ if (collection != null) {
+ collectionsList = StrUtils.splitSmart(collection, ",", true);
+ }
+ if (collectionsList != null) {
+ Set<String> newCollectionsList = new HashSet<String>(
+ collectionsList.size());
+ for (String col : collectionsList) {
+ String al = aliases.getCollectionAlias(col);
+ if (al != null) {
+ List<String> aliasList = StrUtils.splitSmart(al, ",", true);
+ newCollectionsList.addAll(aliasList);
+ } else {
+ newCollectionsList.add(col);
+ }
+ }
+ if (newCollectionsList.size() > 0) {
+ StringBuilder collectionString = new StringBuilder();
+ Iterator<String> it = newCollectionsList.iterator();
+ int sz = newCollectionsList.size();
+ for (int i = 0; i < sz; i++) {
+ collectionString.append(it.next());
+ if (i < newCollectionsList.size() - 1) {
+ collectionString.append(",");
+ }
+ }
+ ModifiableSolrParams params = new ModifiableSolrParams(
+ solrReq.getParams());
+ params.set("collection", collectionString.toString());
+ solrReq.setParams(params);
+ }
+ }
+ }
+
private void remoteQuery(String coreUrl, HttpServletRequest req,
SolrQueryRequest solrReq, HttpServletResponse resp) throws IOException {
-
try {
String urlstr = coreUrl;
@@ -409,7 +482,7 @@ public class SolrDispatchFilter implements Filter
}
- private String getRemotCoreUrl(CoreContainer cores, String collectionName) {
+ private String getRemotCoreUrl(CoreContainer cores, String collectionName, String origCorename) {
ClusterState clusterState = cores.getZkController().getClusterState();
Collection<Slice> slices = clusterState.getSlices(collectionName);
boolean byCoreName = false;
@@ -444,9 +517,14 @@ public class SolrDispatchFilter implements Filter
// don't count a local core
continue;
}
- String coreUrl = coreNodeProps.getCoreUrl();
- if (coreUrl.endsWith("/")) {
- coreUrl = coreUrl.substring(0, coreUrl.length() - 1);
+ String coreUrl;
+ if (origCorename != null) {
+ coreUrl = coreNodeProps.getBaseUrl() + "/" + origCorename;
+ } else {
+ coreUrl = coreNodeProps.getCoreUrl();
+ if (coreUrl.endsWith("/")) {
+ coreUrl = coreUrl.substring(0, coreUrl.length() - 1);
+ }
}
return coreUrl;
diff --git a/solr/core/src/test/org/apache/solr/cloud/AliasIntegrationTest.java b/solr/core/src/test/org/apache/solr/cloud/AliasIntegrationTest.java
new file mode 100644
index 00000000000..c9889e935ad
--- /dev/null
+++ b/solr/core/src/test/org/apache/solr/cloud/AliasIntegrationTest.java
@@ -0,0 +1,266 @@
+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 java.io.IOException;
+import java.util.ArrayList;
+import java.util.List;
+
+import org.apache.lucene.util.LuceneTestCase.Slow;
+import org.apache.solr.client.solrj.SolrQuery;
+import org.apache.solr.client.solrj.SolrServerException;
+import org.apache.solr.client.solrj.embedded.JettySolrRunner;
+import org.apache.solr.client.solrj.impl.HttpSolrServer;
+import org.apache.solr.client.solrj.request.QueryRequest;
+import org.apache.solr.client.solrj.request.UpdateRequest;
+import org.apache.solr.client.solrj.response.QueryResponse;
+import org.apache.solr.common.SolrException;
+import org.apache.solr.common.SolrInputDocument;
+import org.apache.solr.common.params.CollectionParams.CollectionAction;
+import org.apache.solr.common.params.ModifiableSolrParams;
+import org.apache.solr.common.util.NamedList;
+import org.junit.After;
+import org.junit.AfterClass;
+import org.junit.Before;
+import org.junit.BeforeClass;
+
+/**
+ * Test sync phase that occurs when Leader goes down and a new Leader is
+ * elected.
+ */
+@Slow
+public class AliasIntegrationTest extends AbstractFullDistribZkTestBase {
+
+ @BeforeClass
+ public static void beforeSuperClass() throws Exception {
+ }
+
+ @AfterClass
+ public static void afterSuperClass() {
+
+ }
+
+ @Before
+ @Override
+ public void setUp() throws Exception {
+ super.setUp();
+ System.setProperty("numShards", Integer.toString(sliceCount));
+ }
+
+ @Override
+ @After
+ public void tearDown() throws Exception {
+ super.tearDown();
+ resetExceptionIgnores();
+ }
+
+ public AliasIntegrationTest() {
+ super();
+ sliceCount = 1;
+ shardCount = random().nextBoolean() ? 3 : 4;
+ }
+
+ @Override
+ public void doTest() throws Exception {
+
+ handle.clear();
+ handle.put("QTime", SKIPVAL);
+ handle.put("timestamp", SKIPVAL);
+
+ waitForThingsToLevelOut(15);
+
+ del("*:*");
+
+ createCollection("collection2", 2, 1, 10);
+
+ List<Integer> numShardsNumReplicaList = new ArrayList<Integer>(2);
+ numShardsNumReplicaList.add(2);
+ numShardsNumReplicaList.add(1);
+ checkForCollection("collection2", numShardsNumReplicaList, null);
+ waitForRecoveriesToFinish("collection2", true);
+
+ cloudClient.setDefaultCollection("collection1");
+
+ SolrInputDocument doc1 = getDoc(id, 6, i1, -600, tlong, 600, t1,
+ "humpty dumpy sat on a wall");
+ SolrInputDocument doc2 = getDoc(id, 7, i1, -600, tlong, 600, t1,
+ "humpty dumpy3 sat on a walls");
+ SolrInputDocument doc3 = getDoc(id, 8, i1, -600, tlong, 600, t1,
+ "humpty dumpy2 sat on a walled");
+
+ cloudClient.add(doc1);
+ cloudClient.add(doc2);
+ cloudClient.add(doc3);
+
+ cloudClient.commit();
+
+ SolrInputDocument doc6 = getDoc(id, 9, i1, -600, tlong, 600, t1,
+ "humpty dumpy sat on a wall");
+ SolrInputDocument doc7 = getDoc(id, 10, i1, -600, tlong, 600, t1,
+ "humpty dumpy3 sat on a walls");
+
+ cloudClient.setDefaultCollection("collection2");
+
+ cloudClient.add(doc6);
+ cloudClient.add(doc7);
+
+ cloudClient.commit();
+
+ // create alias
+ createAlias("testalias", "collection1");
+
+ // search for alias
+ SolrQuery query = new SolrQuery("*:*");
+ query.set("collection", "testalias");
+ QueryResponse res = cloudClient.query(query);
+ assertEquals(3, res.getResults().getNumFound());
+
+ // search for alias with random non cloud client
+ query = new SolrQuery("*:*");
+ query.set("collection", "testalias");
+ JettySolrRunner jetty = jettys.get(random().nextInt(jettys.size()));
+ int port = jetty.getLocalPort();
+ HttpSolrServer server = new HttpSolrServer("http://127.0.0.1:" + port + context + "/testalias");
+ res = server.query(query);
+ assertEquals(3, res.getResults().getNumFound());
+
+ // now without collections param
+ query = new SolrQuery("*:*");
+ jetty = jettys.get(random().nextInt(jettys.size()));
+ port = jetty.getLocalPort();
+ server = new HttpSolrServer("http://127.0.0.1:" + port + context + "/testalias");
+ res = server.query(query);
+ assertEquals(3, res.getResults().getNumFound());
+
+ // create alias, collection2 first because it's not on every node
+ createAlias("testalias", "collection2,collection1");
+
+ // search for alias with random non cloud client
+ query = new SolrQuery("*:*");
+ query.set("collection", "testalias");
+ jetty = jettys.get(random().nextInt(jettys.size()));
+ port = jetty.getLocalPort();
+ server = new HttpSolrServer("http://127.0.0.1:" + port + context + "/testalias");
+ res = server.query(query);
+ assertEquals(5, res.getResults().getNumFound());
+
+ // now without collections param
+ query = new SolrQuery("*:*");
+ jetty = jettys.get(random().nextInt(jettys.size()));
+ port = jetty.getLocalPort();
+ server = new HttpSolrServer("http://127.0.0.1:" + port + context + "/testalias");
+ res = server.query(query);
+ assertEquals(5, res.getResults().getNumFound());
+
+ // update alias
+ createAlias("testalias", "collection2");
+ //checkForAlias("testalias", "collection2");
+
+ // search for alias
+ query = new SolrQuery("*:*");
+ query.set("collection", "testalias");
+ res = cloudClient.query(query);
+ assertEquals(2, res.getResults().getNumFound());
+
+ // set alias to two collections
+ createAlias("testalias", "collection1,collection2");
+ //checkForAlias("testalias", "collection1,collection2");
+
+ query = new SolrQuery("*:*");
+ query.set("collection", "testalias");
+ res = cloudClient.query(query);
+ assertEquals(5, res.getResults().getNumFound());
+
+ // try a std client
+ // search 1 and 2, but have no collections param
+ query = new SolrQuery("*:*");
+ HttpSolrServer client = new HttpSolrServer(getBaseUrl((HttpSolrServer) clients.get(0)) + "/testalias");
+ res = client.query(query);
+ assertEquals(5, res.getResults().getNumFound());
+
+ createAlias("testalias", "collection2");
+
+ // a second alias
+ createAlias("testalias2", "collection2");
+
+ client = new HttpSolrServer(getBaseUrl((HttpSolrServer) clients.get(0)) + "/testalias");
+ SolrInputDocument doc8 = getDoc(id, 11, i1, -600, tlong, 600, t1,
+ "humpty dumpy4 sat on a walls");
+ client.add(doc8);
+ client.commit();
+ res = client.query(query);
+ assertEquals(3, res.getResults().getNumFound());
+
+ createAlias("testalias", "collection2,collection1");
+
+ query = new SolrQuery("*:*");
+ query.set("collection", "testalias");
+ res = cloudClient.query(query);
+ assertEquals(6, res.getResults().getNumFound());
+
+ deleteAlias("testalias");
+ deleteAlias("testalias2");
+
+ boolean sawException = false;
+ try {
+ res = cloudClient.query(query);
+ } catch (SolrException e) {
+ sawException = true;
+ }
+ assertTrue(sawException);
+ }
+
+ private void createAlias(String alias, String collections) throws SolrServerException, IOException {
+ ModifiableSolrParams params = new ModifiableSolrParams();
+ params.set("collections", collections);
+ params.set("name", alias);
+ params.set("action", CollectionAction.CREATEALIAS.toString());
+ QueryRequest request = new QueryRequest(params);
+ request.setPath("/admin/collections");
+ NamedList<Object> result = createNewSolrServer("", getBaseUrl((HttpSolrServer) clients.get(0))).request(request);
+ }
+
+ private void deleteAlias(String alias) throws SolrServerException, IOException {
+ ModifiableSolrParams params = new ModifiableSolrParams();
+ params.set("name", alias);
+ params.set("action", CollectionAction.DELETEALIAS.toString());
+ QueryRequest request = new QueryRequest(params);
+ request.setPath("/admin/collections");
+ NamedList<Object> result = createNewSolrServer("", getBaseUrl((HttpSolrServer) clients.get(0))).request(request);
+ }
+
+ protected void indexDoc(List<CloudJettyRunner> skipServers, Object... fields) throws IOException,
+ SolrServerException {
+ SolrInputDocument doc = new SolrInputDocument();
+
+ addFields(doc, fields);
+ addFields(doc, "rnd_b", true);
+
+ controlClient.add(doc);
+
+ UpdateRequest ureq = new UpdateRequest();
+ ureq.add(doc);
+ ModifiableSolrParams params = new ModifiableSolrParams();
+ for (CloudJettyRunner skip : skipServers) {
+ params.add("test.distrib.skip.servers", skip.url + "/");
+ }
+ ureq.setParams(params);
+ ureq.process(cloudClient);
+ }
+
+}
diff --git a/solr/core/src/test/org/apache/solr/cloud/ChaosMonkeyNothingIsSafeTest.java b/solr/core/src/test/org/apache/solr/cloud/ChaosMonkeyNothingIsSafeTest.java
index 3620b8efe39..fbb4ff83e86 100644
--- a/solr/core/src/test/org/apache/solr/cloud/ChaosMonkeyNothingIsSafeTest.java
+++ b/solr/core/src/test/org/apache/solr/cloud/ChaosMonkeyNothingIsSafeTest.java
@@ -330,12 +330,5 @@ public class ChaosMonkeyNothingIsSafeTest extends AbstractFullDistribZkTestBase
SolrInputDocument doc = getDoc(fields);
indexDoc(doc);
}
-
- SolrInputDocument getDoc(Object... fields) throws Exception {
- SolrInputDocument doc = new SolrInputDocument();
- addFields(doc, fields);
- addFields(doc, "rnd_b", true);
- return doc;
- }
}
diff --git a/solr/core/src/test/org/apache/solr/cloud/CollectionsAPIDistributedZkTest.java b/solr/core/src/test/org/apache/solr/cloud/CollectionsAPIDistributedZkTest.java
index 63f0633b645..c83a002cc24 100644
--- a/solr/core/src/test/org/apache/solr/cloud/CollectionsAPIDistributedZkTest.java
+++ b/solr/core/src/test/org/apache/solr/cloud/CollectionsAPIDistributedZkTest.java
@@ -44,8 +44,6 @@ import javax.management.ObjectName;
import org.apache.lucene.util.LuceneTestCase.Slow;
import org.apache.lucene.util._TestUtil;
import org.apache.solr.client.solrj.SolrQuery;
-import org.apache.solr.client.solrj.SolrRequest;
-import org.apache.solr.client.solrj.SolrServer;
import org.apache.solr.client.solrj.SolrServerException;
import org.apache.solr.client.solrj.impl.CloudSolrServer;
import org.apache.solr.client.solrj.impl.HttpSolrServer;
@@ -149,10 +147,7 @@ public class CollectionsAPIDistributedZkTest extends AbstractFullDistribZkTestBa
private void testNodesUsedByCreate() throws Exception {
// we can use this client because we just want base url
- final String baseUrl = ((HttpSolrServer) clients.get(0)).getBaseURL().substring(
- 0,
- ((HttpSolrServer) clients.get(0)).getBaseURL().length()
- - DEFAULT_COLLECTION.length() - 1);
+ final String baseUrl = getBaseUrl((HttpSolrServer) clients.get(0));
ModifiableSolrParams params = new ModifiableSolrParams();
params.set("action", CollectionAction.CREATE.toString());
@@ -297,10 +292,7 @@ public class CollectionsAPIDistributedZkTest extends AbstractFullDistribZkTestBa
request.setPath("/admin/collections");
// we can use this client because we just want base url
- final String baseUrl = ((HttpSolrServer) clients.get(0)).getBaseURL().substring(
- 0,
- ((HttpSolrServer) clients.get(0)).getBaseURL().length()
- - DEFAULT_COLLECTION.length() - 1);
+ final String baseUrl = getBaseUrl((HttpSolrServer) clients.get(0));
createNewSolrServer("", baseUrl).request(request);
@@ -409,38 +401,6 @@ public class CollectionsAPIDistributedZkTest extends AbstractFullDistribZkTestBa
checkNoTwoShardsUseTheSameIndexDir();
}
-
- protected void createCollection(Map<String,List<Integer>> collectionInfos,
- String collectionName, int numShards, int numReplicas, int maxShardsPerNode, SolrServer client, String createNodeSetStr) throws SolrServerException, IOException {
- ModifiableSolrParams params = new ModifiableSolrParams();
- params.set("action", CollectionAction.CREATE.toString());
-
- params.set(OverseerCollectionProcessor.NUM_SLICES, numShards);
- params.set(OverseerCollectionProcessor.REPLICATION_FACTOR, numReplicas);
- params.set(OverseerCollectionProcessor.MAX_SHARDS_PER_NODE, maxShardsPerNode);
- if (createNodeSetStr != null) params.set(OverseerCollectionProcessor.CREATE_NODE_SET, createNodeSetStr);
-
- int clientIndex = random().nextInt(2);
- List<Integer> list = new ArrayList<Integer>();
- list.add(numShards);
- list.add(numReplicas);
- collectionInfos.put(collectionName, list);
- params.set("name", collectionName);
- SolrRequest request = new QueryRequest(params);
- request.setPath("/admin/collections");
-
- if (client == null) {
- final String baseUrl = ((HttpSolrServer) clients.get(clientIndex)).getBaseURL().substring(
- 0,
- ((HttpSolrServer) clients.get(clientIndex)).getBaseURL().length()
- - DEFAULT_COLLECTION.length() - 1);
-
- createNewSolrServer("", baseUrl).request(request);
- } else {
- client.request(request);
- }
- }
-
private boolean waitForReloads(String collectionName, Map<String,Long> urlToTimeBefore) throws SolrServerException, IOException {
@@ -549,60 +509,6 @@ public class CollectionsAPIDistributedZkTest extends AbstractFullDistribZkTestBa
fail("Could not find the new collection - " + exp.code() + " : " + collectionClient.getBaseURL());
}
- private String checkCollectionExpectations(String collectionName, List<Integer> numShardsNumReplicaList, List<String> nodesAllowedToRunShards) {
- ClusterState clusterState = getCommonCloudSolrServer().getZkStateReader().getClusterState();
-
- int expectedSlices = numShardsNumReplicaList.get(0);
- // The Math.min thing is here, because we expect replication-factor to be reduced to if there are not enough live nodes to spread all shards of a collection over different nodes
- int expectedShardsPerSlice = numShardsNumReplicaList.get(1);
- int expectedTotalShards = expectedSlices * expectedShardsPerSlice;
-
- Map<String,DocCollection> collections = clusterState
- .getCollectionStates();
- if (collections.containsKey(collectionName)) {
- Map<String,Slice> slices = collections.get(collectionName).getSlicesMap();
- // did we find expectedSlices slices/shards?
- if (slices.size() != expectedSlices) {
- return "Found new collection " + collectionName + ", but mismatch on number of slices. Expected: " + expectedSlices + ", actual: " + slices.size();
- }
- int totalShards = 0;
- for (String sliceName : slices.keySet()) {
- for (Replica replica : slices.get(sliceName).getReplicas()) {
- if (nodesAllowedToRunShards != null && !nodesAllowedToRunShards.contains(replica.getStr(ZkStateReader.NODE_NAME_PROP))) {
- return "Shard " + replica.getName() + " created on node " + replica.getStr(ZkStateReader.NODE_NAME_PROP) + " not allowed to run shards for the created collection " + collectionName;
- }
- }
- totalShards += slices.get(sliceName).getReplicas().size();
- }
- if (totalShards != expectedTotalShards) {
- return "Found new collection " + collectionName + " with correct number of slices, but mismatch on number of shards. Expected: " + expectedTotalShards + ", actual: " + totalShards;
- }
- return null;
- } else {
- return "Could not find new collection " + collectionName;
- }
- }
-
- private void checkForCollection(String collectionName, List<Integer> numShardsNumReplicaList, List<String> nodesAllowedToRunShards)
- throws Exception {
- // check for an expectedSlices new collection - we poll the state
- long timeoutAt = System.currentTimeMillis() + 120000;
- boolean success = false;
- String checkResult = "Didnt get to perform a single check";
- while (System.currentTimeMillis() < timeoutAt) {
- checkResult = checkCollectionExpectations(collectionName, numShardsNumReplicaList, nodesAllowedToRunShards);
- if (checkResult == null) {
- success = true;
- break;
- }
- Thread.sleep(500);
- }
- if (!success) {
- super.printLayout();
- fail(checkResult);
- }
- }
-
private void checkCollectionIsNotCreated(String collectionName)
throws Exception {
// TODO: REMOVE THIS SLEEP WHEN WE HAVE COLLECTION API RESPONSES
@@ -678,42 +584,6 @@ public class CollectionsAPIDistributedZkTest extends AbstractFullDistribZkTestBa
}
}
-
- protected SolrInputDocument getDoc(Object... fields) throws Exception {
- SolrInputDocument doc = new SolrInputDocument();
- addFields(doc, fields);
- return doc;
- }
-
- protected SolrServer createNewSolrServer(String collection, String baseUrl) {
- try {
- // setup the server...
- HttpSolrServer s = new HttpSolrServer(baseUrl + "/" + collection);
- s.setConnectionTimeout(DEFAULT_CONNECTION_TIMEOUT);
- s.setDefaultMaxConnectionsPerHost(100);
- s.setMaxTotalConnections(100);
- return s;
- }
- catch (Exception ex) {
- throw new RuntimeException(ex);
- }
- }
-
- volatile CloudSolrServer commondCloudSolrServer;
- private CloudSolrServer getCommonCloudSolrServer() {
- if (commondCloudSolrServer == null) {
- synchronized(this) {
- try {
- commondCloudSolrServer = new CloudSolrServer(zkServer.getZkAddress());
- commondCloudSolrServer.setDefaultCollection(DEFAULT_COLLECTION);
- commondCloudSolrServer.connect();
- } catch (MalformedURLException e) {
- throw new RuntimeException(e);
- }
- }
- }
- return commondCloudSolrServer;
- }
@Override
protected QueryResponse queryServer(ModifiableSolrParams params) throws SolrServerException {
@@ -731,9 +601,6 @@ public class CollectionsAPIDistributedZkTest extends AbstractFullDistribZkTestBa
@Override
public void tearDown() throws Exception {
super.tearDown();
- if (commondCloudSolrServer != null) {
- commondCloudSolrServer.shutdown();
- }
System.clearProperty("numShards");
System.clearProperty("zkHost");
System.clearProperty("solr.xml.persist");
diff --git a/solr/solrj/src/java/org/apache/solr/client/solrj/impl/CloudSolrServer.java b/solr/solrj/src/java/org/apache/solr/client/solrj/impl/CloudSolrServer.java
index b70349f8b47..e494f148cf2 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
@@ -19,10 +19,13 @@ package org.apache.solr.client.solrj.impl;
import java.io.IOException;
import java.net.MalformedURLException;
+import java.net.URLDecoder;
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.List;
import java.util.Map;
import java.util.Random;
@@ -36,6 +39,8 @@ import org.apache.solr.client.solrj.SolrServerException;
import org.apache.solr.client.solrj.request.IsUpdateRequest;
import org.apache.solr.client.solrj.util.ClientUtils;
import org.apache.solr.common.SolrException;
+import org.apache.solr.common.SolrException.ErrorCode;
+import org.apache.solr.common.cloud.Aliases;
import org.apache.solr.common.cloud.ClusterState;
import org.apache.solr.common.cloud.Slice;
import org.apache.solr.common.cloud.ZkCoreNodeProps;
@@ -183,13 +188,13 @@ public class CloudSolrServer extends SolrServer {
reqParams = new ModifiableSolrParams();
}
List<String> theUrlList = new ArrayList<String>();
- if (request.getPath().equals("/admin/collections")) {
+ if (request.getPath().equals("/admin/collections") || request.getPath().equals("/admin/cores")) {
Set<String> liveNodes = clusterState.getLiveNodes();
for (String liveNode : liveNodes) {
int splitPointBetweenHostPortAndContext = liveNode.indexOf("_");
theUrlList.add("http://"
+ liveNode.substring(0, splitPointBetweenHostPortAndContext) + "/"
- + liveNode.substring(splitPointBetweenHostPortAndContext + 1));
+ + URLDecoder.decode(liveNode, "UTF-8").substring(splitPointBetweenHostPortAndContext + 1));
}
} else {
String collection = reqParams.get("collection", defaultCollection);
@@ -199,9 +204,21 @@ public class CloudSolrServer extends SolrServer {
"No collection param specified on request and no default collection has been set.");
}
- // Extract each comma separated collection name and store in a List.
- List<String> collectionList = StrUtils.splitSmart(collection, ",", true);
+ Set<String> collectionsList = getCollectionList(clusterState, collection);
+ if (collectionsList.size() == 0) {
+ throw new SolrException(ErrorCode.BAD_REQUEST, "Could not find collection: " + collection);
+ }
+ collection = collectionsList.iterator().next();
+ StringBuilder collectionString = new StringBuilder();
+ Iterator<String> it = collectionsList.iterator();
+ for (int i = 0; i < collectionsList.size(); i++) {
+ String col = it.next();
+ collectionString.append(col);
+ if (i < collectionsList.size() - 1) {
+ collectionString.append(",");
+ }
+ }
// TODO: not a big deal because of the caching, but we could avoid looking
// at every shard
// when getting leaders if we tweaked some things
@@ -210,9 +227,12 @@ public class CloudSolrServer extends SolrServer {
// specified,
// add it to the Map of slices.
Map<String,Slice> slices = new HashMap<String,Slice>();
- for (String collectionName : collectionList) {
- ClientUtils.addSlices(slices, collectionName,
- clusterState.getSlices(collectionName), true);
+ for (String collectionName : collectionsList) {
+ Collection<Slice> colSlices = clusterState.getSlices(collectionName);
+ if (colSlices == null) {
+ throw new SolrServerException("Could not find collection:" + collectionName);
+ }
+ ClientUtils.addSlices(slices, collectionName, colSlices, true);
}
Set<String> liveNodes = clusterState.getLiveNodes();
@@ -287,6 +307,30 @@ public class CloudSolrServer extends SolrServer {
return rsp.getResponse();
}
+ private Set<String> getCollectionList(ClusterState clusterState,
+ String collection) {
+ // Extract each comma separated collection name and store in a List.
+ List<String> rawCollectionsList = StrUtils.splitSmart(collection, ",", true);
+ Set<String> collectionsList = new HashSet<String>();
+ // validate collections
+ for (String collectionName : rawCollectionsList) {
+ if (!clusterState.getCollections().contains(collectionName)) {
+ Aliases aliases = zkStateReader.getAliases();
+ String alias = aliases.getCollectionAlias(collectionName);
+ if (alias != null) {
+ List<String> aliasList = StrUtils.splitSmart(alias, ",", true);
+ collectionsList.addAll(aliasList);
+ continue;
+ }
+
+ throw new SolrException(ErrorCode.BAD_REQUEST, "Collection not found: " + collectionName);
+ }
+
+ collectionsList.add(collectionName);
+ }
+ return collectionsList;
+ }
+
@Override
public void shutdown() {
if (zkStateReader != null) {
diff --git a/solr/solrj/src/java/org/apache/solr/common/cloud/Aliases.java b/solr/solrj/src/java/org/apache/solr/common/cloud/Aliases.java
new file mode 100644
index 00000000000..28e76bb4047
--- /dev/null
+++ b/solr/solrj/src/java/org/apache/solr/common/cloud/Aliases.java
@@ -0,0 +1,63 @@
+package org.apache.solr.common.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 java.util.Collections;
+import java.util.HashMap;
+import java.util.Map;
+
+public class Aliases {
+
+ private Map<String,Map<String,String>> aliasMap;
+
+ public Aliases(Map<String,Map<String,String>> aliasMap) {
+ this.aliasMap = aliasMap;
+ }
+
+ public Aliases() {
+ this.aliasMap = new HashMap<String,Map<String,String>>();
+ }
+
+ public Map<String,String> getCollectionAliasMap() {
+ Map<String,String> cam = aliasMap.get("collection");
+ if (cam == null) return null;
+ return Collections.unmodifiableMap(cam);
+ }
+
+ public Map<String,Map<String,String>> getAliasMap() {
+ return Collections.unmodifiableMap(aliasMap);
+ }
+
+ public int collectionAliasSize() {
+ Map<String,String> cam = aliasMap.get("collection");
+ if (cam == null) return 0;
+ return cam.size();
+ }
+
+ @Override
+ public String toString() {
+ return "Aliases [aliasMap=" + aliasMap + "]";
+ }
+
+ public String getCollectionAlias(String collectionName) {
+ Map<String,String> cam = aliasMap.get("collection");
+ if (cam == null) return null;
+ return cam.get(collectionName);
+ }
+
+}
diff --git a/solr/solrj/src/java/org/apache/solr/common/cloud/ClusterState.java b/solr/solrj/src/java/org/apache/solr/common/cloud/ClusterState.java
index 3f5c948363e..867bab55868 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
@@ -17,13 +17,11 @@ package org.apache.solr.common.cloud;
* limitations under the License.
*/
-import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashMap;
-import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
@@ -31,7 +29,6 @@ import java.util.Set;
import org.apache.noggit.JSONWriter;
import org.apache.solr.common.SolrException;
import org.apache.solr.common.SolrException.ErrorCode;
-import org.apache.solr.common.cloud.DocRouter.Range;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.data.Stat;
import org.slf4j.Logger;
@@ -229,6 +226,15 @@ public class ClusterState implements JSONWriter.Writable {
// System.out.println("######## ClusterState.load result:" + collections);
return new ClusterState(version, liveNodes, collections);
}
+
+ public static Aliases load(byte[] bytes) {
+ if (bytes == null || bytes.length == 0) {
+ return new Aliases();
+ }
+ Map<String,Map<String,String>> aliasMap = (Map<String,Map<String,String>>) ZkStateReader.fromJSON(bytes);
+
+ return new Aliases(aliasMap);
+ }
private static DocCollection collectionFromObjects(String name, Map<String,Object> objs) {
Map<String,Object> props;
diff --git a/solr/solrj/src/java/org/apache/solr/common/cloud/ZkStateReader.java b/solr/solrj/src/java/org/apache/solr/common/cloud/ZkStateReader.java
index 239c9cfe3c1..70374e1ee6c 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
@@ -62,6 +62,7 @@ public class ZkStateReader {
public static final String COLLECTIONS_ZKNODE = "/collections";
public static final String LIVE_NODES_ZKNODE = "/live_nodes";
+ public static final String ALIASES = "/aliases.json";
public static final String CLUSTER_STATE = "/clusterstate.json";
public static final String RECOVERING = "recovering";
@@ -129,7 +130,9 @@ public class ZkStateReader {
private boolean closeClient = false;
private ZkCmdExecutor cmdExecutor;
-
+
+ private Aliases aliases = new Aliases();
+
public ZkStateReader(SolrZkClient zkClient) {
this.zkClient = zkClient;
initZkCmdExecutor(zkClient.getZkClientTimeout());
@@ -177,12 +180,17 @@ public class ZkStateReader {
updateClusterState(true, true);
}
+ public Aliases getAliases() {
+ return aliases;
+ }
+
public synchronized void createClusterStateWatchersAndUpdate() throws KeeperException,
InterruptedException {
// We need to fetch the current cluster state and the set of live nodes
synchronized (getUpdateLock()) {
cmdExecutor.ensureExists(CLUSTER_STATE, zkClient);
+ cmdExecutor.ensureExists(ALIASES, zkClient);
log.info("Updating cluster state from ZooKeeper... ");
@@ -286,6 +294,49 @@ public class ZkStateReader {
liveNodeSet.addAll(liveNodes);
ClusterState clusterState = ClusterState.load(zkClient, liveNodeSet);
this.clusterState = clusterState;
+
+ zkClient.exists(ALIASES,
+ 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;
+ }
+ try {
+ synchronized (ZkStateReader.this.getUpdateLock()) {
+ log.info("Updating aliases... ");
+
+ // remake watch
+ final Watcher thisWatch = this;
+ Stat stat = new Stat();
+ byte[] data = zkClient.getData(ALIASES, thisWatch, stat ,
+ true);
+
+ Aliases aliases = ClusterState.load(data);
+
+ ZkStateReader.this.aliases = aliases;
+ }
+ } 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("", e);
+ throw new ZooKeeperException(
+ SolrException.ErrorCode.SERVER_ERROR, "", e);
+ } catch (InterruptedException e) {
+ // Restore the interrupted status
+ Thread.currentThread().interrupt();
+ log.warn("", e);
+ return;
+ }
+ }
+
+ }, true);
}
}
@@ -493,5 +544,13 @@ public class ZkStateReader {
public SolrZkClient getZkClient() {
return zkClient;
}
+
+ public void updateAliases() throws KeeperException, InterruptedException {
+ byte[] data = zkClient.getData(ALIASES, null, null, true);
+
+ Aliases aliases = ClusterState.load(data);
+
+ ZkStateReader.this.aliases = aliases;
+ }
}
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.java
index 6c1c2661786..ce907e61341 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
@@ -28,7 +28,7 @@ public interface CollectionParams
public enum CollectionAction {
- CREATE, DELETE, RELOAD, SYNCSHARD;
+ CREATE, DELETE, RELOAD, SYNCSHARD, CREATEALIAS, DELETEALIAS;
public static CollectionAction get( String p )
{
diff --git a/solr/solrj/src/java/org/apache/solr/common/params/CoreAdminParams.java b/solr/solrj/src/java/org/apache/solr/common/params/CoreAdminParams.java
index ff1ecfea2cb..f465cccfed7 100644
--- a/solr/solrj/src/java/org/apache/solr/common/params/CoreAdminParams.java
+++ b/solr/solrj/src/java/org/apache/solr/common/params/CoreAdminParams.java
@@ -102,7 +102,9 @@ public interface CoreAdminParams
SPLIT,
PREPRECOVERY,
REQUESTRECOVERY,
- REQUESTSYNCSHARD;
+ REQUESTSYNCSHARD,
+ CREATEALIAS,
+ DELETEALIAS;
public static CoreAdminAction get( String p )
{
diff --git a/solr/solrj/src/test/org/apache/solr/client/solrj/impl/CloudSolrServerTest.java b/solr/solrj/src/test/org/apache/solr/client/solrj/impl/CloudSolrServerTest.java
index 32a84f373c5..279dc56bcef 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
@@ -149,10 +149,4 @@ public class CloudSolrServerTest extends AbstractFullDistribZkTestBase {
indexDoc(doc);
}
- SolrInputDocument getDoc(Object... fields) throws Exception {
- SolrInputDocument doc = new SolrInputDocument();
- addFields(doc, fields);
- return doc;
- }
-
}
diff --git a/solr/test-framework/src/java/org/apache/solr/cloud/AbstractFullDistribZkTestBase.java b/solr/test-framework/src/java/org/apache/solr/cloud/AbstractFullDistribZkTestBase.java
index ff75147b55d..a9d9b9dcd7d 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
@@ -33,11 +33,13 @@ import java.util.concurrent.atomic.AtomicInteger;
import org.apache.http.params.CoreConnectionPNames;
import org.apache.lucene.util.LuceneTestCase.Slow;
import org.apache.solr.client.solrj.SolrQuery;
+import org.apache.solr.client.solrj.SolrRequest;
import org.apache.solr.client.solrj.SolrServer;
import org.apache.solr.client.solrj.SolrServerException;
import org.apache.solr.client.solrj.embedded.JettySolrRunner;
import org.apache.solr.client.solrj.impl.CloudSolrServer;
import org.apache.solr.client.solrj.impl.HttpSolrServer;
+import org.apache.solr.client.solrj.request.QueryRequest;
import org.apache.solr.client.solrj.request.UpdateRequest;
import org.apache.solr.client.solrj.response.QueryResponse;
import org.apache.solr.common.SolrDocument;
@@ -51,6 +53,7 @@ import org.apache.solr.common.cloud.Slice;
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.CollectionAction;
import org.apache.solr.common.params.ModifiableSolrParams;
import org.apache.solr.common.params.SolrParams;
import org.junit.After;
@@ -612,6 +615,12 @@ public abstract class AbstractFullDistribZkTestBase extends AbstractDistribZkTes
super.waitForRecoveriesToFinish(DEFAULT_COLLECTION, zkStateReader, verbose);
}
+ protected void waitForRecoveriesToFinish(String collection, boolean verbose)
+ throws Exception {
+ ZkStateReader zkStateReader = cloudClient.getZkStateReader();
+ super.waitForRecoveriesToFinish(collection, zkStateReader, verbose);
+ }
+
protected void waitForRecoveriesToFinish(boolean verbose, int timeoutSeconds)
throws Exception {
ZkStateReader zkStateReader = cloudClient.getZkStateReader();
@@ -1318,6 +1327,9 @@ public abstract class AbstractFullDistribZkTestBase extends AbstractDistribZkTes
if (VERBOSE || printLayoutOnTearDown) {
super.printLayout();
}
+ if (commondCloudSolrServer != null) {
+ commondCloudSolrServer.shutdown();
+ }
if (controlClient != null) {
((HttpSolrServer) controlClient).shutdown();
}
@@ -1355,6 +1367,40 @@ public abstract class AbstractFullDistribZkTestBase extends AbstractDistribZkTes
jettys.clear();
}
+ protected void createCollection(String collectionName, int numShards, int numReplicas, int maxShardsPerNode) throws SolrServerException, IOException {
+ createCollection(null, collectionName, numShards, numReplicas, maxShardsPerNode, null, null);
+ }
+
+ protected void createCollection(Map<String,List<Integer>> collectionInfos,
+ String collectionName, int numShards, int numReplicas, int maxShardsPerNode, SolrServer client, String createNodeSetStr) throws SolrServerException, IOException {
+ ModifiableSolrParams params = new ModifiableSolrParams();
+ params.set("action", CollectionAction.CREATE.toString());
+
+ params.set(OverseerCollectionProcessor.NUM_SLICES, numShards);
+ params.set(OverseerCollectionProcessor.REPLICATION_FACTOR, numReplicas);
+ params.set(OverseerCollectionProcessor.MAX_SHARDS_PER_NODE, maxShardsPerNode);
+ if (createNodeSetStr != null) params.set(OverseerCollectionProcessor.CREATE_NODE_SET, createNodeSetStr);
+
+ int clientIndex = random().nextInt(2);
+ List<Integer> list = new ArrayList<Integer>();
+ list.add(numShards);
+ list.add(numReplicas);
+ if (collectionInfos != null) {
+ collectionInfos.put(collectionName, list);
+ }
+ params.set("name", collectionName);
+ SolrRequest request = new QueryRequest(params);
+ request.setPath("/admin/collections");
+
+ if (client == null) {
+ final String baseUrl = getBaseUrl((HttpSolrServer) clients.get(clientIndex));
+
+ createNewSolrServer("", baseUrl).request(request);
+ } else {
+ client.request(request);
+ }
+ }
+
@Override
protected SolrServer createNewSolrServer(int port) {
try {
@@ -1371,5 +1417,103 @@ public abstract class AbstractFullDistribZkTestBase extends AbstractDistribZkTes
throw new RuntimeException(ex);
}
}
+
+ protected SolrServer createNewSolrServer(String collection, String baseUrl) {
+ try {
+ // setup the server...
+ HttpSolrServer s = new HttpSolrServer(baseUrl + "/" + collection);
+ s.setConnectionTimeout(DEFAULT_CONNECTION_TIMEOUT);
+ s.setDefaultMaxConnectionsPerHost(100);
+ s.setMaxTotalConnections(100);
+ return s;
+ }
+ catch (Exception ex) {
+ throw new RuntimeException(ex);
+ }
+ }
+
+ protected String getBaseUrl(HttpSolrServer client) {
+ return client .getBaseURL().substring(
+ 0, client.getBaseURL().length()
+ - DEFAULT_COLLECTION.length() - 1);
+ }
+
+ protected SolrInputDocument getDoc(Object... fields) throws Exception {
+ SolrInputDocument doc = new SolrInputDocument();
+ addFields(doc, fields);
+ return doc;
+ }
+
+ private String checkCollectionExpectations(String collectionName, List<Integer> numShardsNumReplicaList, List<String> nodesAllowedToRunShards) {
+ ClusterState clusterState = getCommonCloudSolrServer().getZkStateReader().getClusterState();
+
+ int expectedSlices = numShardsNumReplicaList.get(0);
+ // The Math.min thing is here, because we expect replication-factor to be reduced to if there are not enough live nodes to spread all shards of a collection over different nodes
+ int expectedShardsPerSlice = numShardsNumReplicaList.get(1);
+ int expectedTotalShards = expectedSlices * expectedShardsPerSlice;
+
+ Map<String,DocCollection> collections = clusterState
+ .getCollectionStates();
+ if (collections.containsKey(collectionName)) {
+ Map<String,Slice> slices = collections.get(collectionName).getSlicesMap();
+ // did we find expectedSlices slices/shards?
+ if (slices.size() != expectedSlices) {
+ return "Found new collection " + collectionName + ", but mismatch on number of slices. Expected: " + expectedSlices + ", actual: " + slices.size();
+ }
+ int totalShards = 0;
+ for (String sliceName : slices.keySet()) {
+ for (Replica replica : slices.get(sliceName).getReplicas()) {
+ if (nodesAllowedToRunShards != null && !nodesAllowedToRunShards.contains(replica.getStr(ZkStateReader.NODE_NAME_PROP))) {
+ return "Shard " + replica.getName() + " created on node " + replica.getStr(ZkStateReader.NODE_NAME_PROP) + " not allowed to run shards for the created collection " + collectionName;
+ }
+ }
+ totalShards += slices.get(sliceName).getReplicas().size();
+ }
+ if (totalShards != expectedTotalShards) {
+ return "Found new collection " + collectionName + " with correct number of slices, but mismatch on number of shards. Expected: " + expectedTotalShards + ", actual: " + totalShards;
+ }
+ return null;
+ } else {
+ return "Could not find new collection " + collectionName;
+ }
+ }
+
+ protected void checkForCollection(String collectionName,
+ List<Integer> numShardsNumReplicaList,
+ List<String> nodesAllowedToRunShards) throws Exception {
+ // check for an expectedSlices new collection - we poll the state
+ long timeoutAt = System.currentTimeMillis() + 120000;
+ boolean success = false;
+ String checkResult = "Didnt get to perform a single check";
+ while (System.currentTimeMillis() < timeoutAt) {
+ checkResult = checkCollectionExpectations(collectionName,
+ numShardsNumReplicaList, nodesAllowedToRunShards);
+ if (checkResult == null) {
+ success = true;
+ break;
+ }
+ Thread.sleep(500);
+ }
+ if (!success) {
+ super.printLayout();
+ fail(checkResult);
+ }
+ }
+
+ volatile CloudSolrServer commondCloudSolrServer;
+ protected CloudSolrServer getCommonCloudSolrServer() {
+ if (commondCloudSolrServer == null) {
+ synchronized(this) {
+ try {
+ commondCloudSolrServer = new CloudSolrServer(zkServer.getZkAddress());
+ commondCloudSolrServer.setDefaultCollection(DEFAULT_COLLECTION);
+ commondCloudSolrServer.connect();
+ } catch (MalformedURLException e) {
+ throw new RuntimeException(e);
+ }
+ }
+ }
+ return commondCloudSolrServer;
+ }
}