You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@solr.apache.org by ds...@apache.org on 2026/09/09 14:15:03 UTC
(solr) 09/17: SOLR-18390: test-framework SolrClient accessor improvements (#4778)
This is an automated email from the ASF dual-hosted git repository.
dsmiley pushed a commit to branch branch_10x
in repository https://gitbox.apache.org/repos/asf/solr.git
commit 1079929502d627fff6d9907685583a3503d57fa4
Author: Serhiy Bzhezytskyy <me...@serhiy-bzhezytskyy.com>
AuthorDate: Wed Sep 9 02:01:48 2026 +0300
SOLR-18390: test-framework SolrClient accessor improvements (#4778)
Converted many tests to use them -- any test that was using one we want to remove.
Co-authored-by: David Smiley <ds...@apache.org>
Co-authored-by: Claude Sonnet 5 <no...@anthropic.com>
(cherry picked from commit cc2d450f935c7d61621cadc3f40606d672b649de)
---
.../apache/solr/bench/lifecycle/SolrStartup.java | 7 +-
.../test/org/apache/solr/TestCpuTimeSearch.java | 5 +-
.../org/apache/solr/cli/TestSolrCLIRunExample.java | 5 +-
.../apache/solr/cloud/AliasIntegrationTest.java | 7 +-
.../apache/solr/cloud/BasicDistributedZk2Test.java | 47 +-
.../apache/solr/cloud/BasicDistributedZkTest.java | 180 +++---
.../cloud/CloudExitableDirectoryReaderTest.java | 2 +-
.../apache/solr/cloud/CollectionsAPISolrJTest.java | 19 +-
.../cloud/ConcurrentCreateRoutedAliasTest.java | 6 +-
.../solr/cloud/DeleteInactiveReplicaTest.java | 29 +-
.../DistribDocExpirationUpdateProcessorTest.java | 61 +-
.../solr/cloud/DistributedVersionInfoTest.java | 127 ++--
.../solr/cloud/FullSolrCloudDistribCmdsTest.java | 416 ++++++-------
.../solr/cloud/HttpPartitionOnCommitTest.java | 35 +-
.../org/apache/solr/cloud/HttpPartitionTest.java | 39 +-
.../cloud/LeaderFailoverAfterPartitionTest.java | 10 +-
.../org/apache/solr/cloud/MigrateReplicasTest.java | 30 +-
.../org/apache/solr/cloud/MigrateRouteKeyTest.java | 101 ++--
.../org/apache/solr/cloud/MoveReplicaTest.java | 49 +-
.../solr/cloud/NestedShardedAtomicUpdateTest.java | 9 +-
.../apache/solr/cloud/RemoteQueryErrorTest.java | 19 +-
.../org/apache/solr/cloud/ReplaceNodeTest.java | 24 +-
.../apache/solr/cloud/ReplicationFactorTest.java | 31 +-
.../test/org/apache/solr/cloud/SplitShardTest.java | 16 +-
.../apache/solr/cloud/TestBaseStatsCacheCloud.java | 79 ++-
.../apache/solr/cloud/TestCloudConsistency.java | 25 +-
.../apache/solr/cloud/TestCloudDeleteByQuery.java | 46 +-
.../TestCloudPhrasesIdentificationComponent.java | 2 +-
.../solr/cloud/TestCloudPseudoReturnFields.java | 2 +-
.../org/apache/solr/cloud/TestCloudRecovery2.java | 33 +-
.../org/apache/solr/cloud/TestConfigSetsAPI.java | 114 ++--
.../solr/cloud/TestConfigSetsAPIExclusivity.java | 8 +-
.../solr/cloud/TestConfigSetsAPIZkFailure.java | 5 +-
.../solr/cloud/TestGracefulJettyShutdown.java | 4 +-
.../solr/cloud/TestMiniSolrCloudClusterSSL.java | 2 +-
.../org/apache/solr/cloud/TestPullReplica.java | 111 ++--
.../solr/cloud/TestPullReplicaErrorHandling.java | 37 +-
.../apache/solr/cloud/TestPullReplicaWithAuth.java | 10 +-
.../solr/cloud/TestQueryingOnDownCollection.java | 59 +-
.../cloud/TestStressCloudBlindAtomicUpdates.java | 13 +-
.../solr/cloud/TestTlogReplayVsRecovery.java | 22 +-
.../org/apache/solr/cloud/TestTlogReplica.java | 138 +++--
.../cloud/TestTolerantUpdateProcessorCloud.java | 26 +-
.../TestTolerantUpdateProcessorRandomCloud.java | 11 +-
.../apache/solr/cloud/UnloadDistributedZkTest.java | 132 ++---
.../solr/cloud/ZkShardTermsRecoveryTest.java | 11 +-
.../ConcurrentDeleteAndCreateCollectionTest.java | 6 +-
.../solr/cloud/api/collections/ShardSplitTest.java | 330 +++++------
.../org/apache/solr/core/TestCustomStream.java | 17 +-
.../core/snapshots/TestSolrCloudSnapshots.java | 32 +-
.../solr/core/snapshots/TestSolrCoreSnapshots.java | 265 ++++-----
.../solr/filestore/TestDistribFileStore.java | 23 +-
.../solr/handler/TestReplicationHandler.java | 56 +-
.../solr/handler/TestStressIncrementalBackup.java | 11 +-
.../solr/handler/TestStressThreadBackup.java | 11 +-
.../org/apache/solr/handler/V2StandaloneTest.java | 17 +-
.../solr/handler/admin/CoreAdminHandlerTest.java | 11 +-
.../solr/handler/admin/HealthCheckHandlerTest.java | 34 +-
.../solr/handler/admin/LukeHandlerCloudTest.java | 29 +-
.../solr/handler/component/UpdateLogCloudTest.java | 6 +-
.../solr/metrics/SolrMetricsIntegrationTest.java | 43 +-
.../response/TestPrometheusResponseWriter.java | 154 +++--
.../apache/solr/response/TestRawTransformer.java | 4 +-
.../schema/ManagedSchemaRoundRobinCloudTest.java | 27 +-
.../apache/solr/search/TestCoordinatorRole.java | 464 ++++++++-------
.../search/facet/TestCloudJSONFacetJoinDomain.java | 2 +-
.../solr/search/facet/TestCloudJSONFacetSKG.java | 2 +-
.../search/facet/TestCloudJSONFacetSKGEquiv.java | 2 +-
.../apache/solr/search/stats/TestDistribIDF.java | 105 ++--
.../solr/security/BasicAuthIntegrationTest.java | 15 +-
.../solr/security/BasicAuthStandaloneTest.java | 99 ++--
.../apache/solr/security/MultiAuthPluginTest.java | 658 ++++++++++-----------
.../solr/update/DeleteByIdWithRouterFieldTest.java | 28 +-
.../update/processor/TestCloudDeduplication.java | 2 +-
.../apache/solr/client/solrj/SolrExampleTests.java | 12 +-
.../solr/client/solrj/SolrExampleTestsBase.java | 6 +-
.../solrj/impl/CloudHttp2SolrClientTest.java | 104 ++--
.../solrj/impl/HttpSolrClientBadInputTest.java | 80 +--
.../solr/client/solrj/impl/LB2SolrClientTest.java | 4 +-
.../apache/solr/BaseDistributedSearchTestCase.java | 5 +-
.../src/java/org/apache/solr/SolrTestCaseHS.java | 4 +-
.../src/java/org/apache/solr/SolrTestCaseJ4.java | 48 --
.../solr/cloud/AbstractFullDistribZkTestBase.java | 28 +-
.../apache/solr/cloud/MiniSolrCloudCluster.java | 38 +-
...bstractCollectionsAPIDistributedZkTestBase.java | 15 +-
.../org/apache/solr/embedded/JettySolrRunner.java | 17 +-
.../org/apache/solr/util/SolrJMetricTestUtils.java | 6 +-
.../apache/solr/embedded/TestJettySolrRunner.java | 11 +-
.../webapp/AdminUiCoreAdminStandaloneTest.java | 19 +-
.../apache/solr/webapp/AdminUiQueryScreenTest.java | 4 +-
.../webapp/AdminUiReplicationStandaloneTest.java | 23 +-
.../solr/webapp/AdminUiSecurityAuthTest.java | 9 +-
.../org/apache/solr/webapp/AdminUiTestBase.java | 7 +-
93 files changed, 2356 insertions(+), 2701 deletions(-)
diff --git a/solr/benchmark/src/java/org/apache/solr/bench/lifecycle/SolrStartup.java b/solr/benchmark/src/java/org/apache/solr/bench/lifecycle/SolrStartup.java
index d0bd64d56ba..359be6e2e68 100644
--- a/solr/benchmark/src/java/org/apache/solr/bench/lifecycle/SolrStartup.java
+++ b/solr/benchmark/src/java/org/apache/solr/bench/lifecycle/SolrStartup.java
@@ -78,10 +78,9 @@ public class SolrStartup {
solrRunner = new JettySolrRunner(tmpSolrHome.toString(), buildJettyConfig());
solrRunner.start(false);
- try (SolrClient client = solrRunner.newClient()) {
- for (int i = 0; i < NUM_CORES; i++) {
- createCore(client, "core-prefix-" + i);
- }
+ SolrClient client = solrRunner.getSolrClient();
+ for (int i = 0; i < NUM_CORES; i++) {
+ createCore(client, "core-prefix-" + i);
}
solrRunner.stop();
}
diff --git a/solr/core/src/test/org/apache/solr/TestCpuTimeSearch.java b/solr/core/src/test/org/apache/solr/TestCpuTimeSearch.java
index 427205d300c..fec884f0afa 100644
--- a/solr/core/src/test/org/apache/solr/TestCpuTimeSearch.java
+++ b/solr/core/src/test/org/apache/solr/TestCpuTimeSearch.java
@@ -18,7 +18,6 @@ package org.apache.solr;
import java.io.IOException;
import java.util.List;
-import org.apache.solr.client.solrj.SolrClient;
import org.apache.solr.client.solrj.SolrServerException;
import org.apache.solr.client.solrj.request.CollectionAdminRequest;
import org.apache.solr.client.solrj.request.SolrQuery;
@@ -100,9 +99,7 @@ public class TestCpuTimeSearch extends SolrCloudTestCase {
coll.getSlices().stream()
.flatMap(s -> s.getReplicas().stream())
.toArray(Replica[]::new));
- try (SolrClient client = getHttpSolrClient(randomReplica.getCoreUrl())) {
- response = client.query(query);
- }
+ response = cluster.getSolrClient(randomReplica).query(query);
SolrDocumentList results = response.getResults();
int size = results.size();
diff --git a/solr/core/src/test/org/apache/solr/cli/TestSolrCLIRunExample.java b/solr/core/src/test/org/apache/solr/cli/TestSolrCLIRunExample.java
index 7a7f105c084..2e2157878ae 100644
--- a/solr/core/src/test/org/apache/solr/cli/TestSolrCLIRunExample.java
+++ b/solr/core/src/test/org/apache/solr/cli/TestSolrCLIRunExample.java
@@ -39,6 +39,7 @@ import org.apache.lucene.tests.util.LuceneTestCase;
import org.apache.solr.SolrTestCaseJ4;
import org.apache.solr.client.solrj.SolrClient;
import org.apache.solr.client.solrj.impl.CloudSolrClient;
+import org.apache.solr.client.solrj.jetty.HttpJettySolrClient;
import org.apache.solr.client.solrj.request.SolrQuery;
import org.apache.solr.client.solrj.response.QueryResponse;
import org.apache.solr.cloud.MiniSolrCloudCluster;
@@ -376,7 +377,9 @@ public class TestSolrCLIRunExample extends SolrTestCaseJ4 {
if ("techproducts".equals(exampleName)) {
try (SolrClient solrClient =
- getHttpSolrClient("http://localhost:" + bindPort + "/solr", exampleName)) {
+ new HttpJettySolrClient.Builder("http://localhost:" + bindPort + "/solr")
+ .withDefaultCollection(exampleName)
+ .build()) {
SolrQuery query = new SolrQuery("*:*");
QueryResponse qr = solrClient.query(query);
long numFound = qr.getResults().getNumFound();
diff --git a/solr/core/src/test/org/apache/solr/cloud/AliasIntegrationTest.java b/solr/core/src/test/org/apache/solr/cloud/AliasIntegrationTest.java
index 7f2fa3b1de1..ceb0bdb7184 100644
--- a/solr/core/src/test/org/apache/solr/cloud/AliasIntegrationTest.java
+++ b/solr/core/src/test/org/apache/solr/cloud/AliasIntegrationTest.java
@@ -960,13 +960,12 @@ public class AliasIntegrationTest extends SolrCloudTestCase {
// HttpSolrClient
JettySolrRunner jetty = cluster.getRandomJetty(random());
if (random().nextBoolean()) {
- try (SolrClient client = getHttpSolrClient(jetty.getBaseUrl().toString(), collectionList)) {
+ try (SolrClient client = jetty.newSolrClient(collectionList)) {
responseConsumer.accept(client.query(null, solrQuery));
}
} else {
- try (SolrClient client = getHttpSolrClient(jetty.getBaseUrl().toString())) {
- responseConsumer.accept(client.query(collectionList, solrQuery));
- }
+ SolrClient client = jetty.getSolrClient();
+ responseConsumer.accept(client.query(collectionList, solrQuery));
}
// Recursively do again; this time with the &collection= param
diff --git a/solr/core/src/test/org/apache/solr/cloud/BasicDistributedZk2Test.java b/solr/core/src/test/org/apache/solr/cloud/BasicDistributedZk2Test.java
index 61edcfa0f1f..d4c1ad631ed 100644
--- a/solr/core/src/test/org/apache/solr/cloud/BasicDistributedZk2Test.java
+++ b/solr/core/src/test/org/apache/solr/cloud/BasicDistributedZk2Test.java
@@ -210,18 +210,17 @@ public class BasicDistributedZk2Test extends AbstractFullDistribZkTestBase {
int docs = 2;
for (JettySolrRunner jetty : jettys) {
- final String clientUrl = getBaseUrl(jetty);
- addAndQueryDocs(clientUrl, docs);
+ addAndQueryDocs(jetty, docs);
docs += 2;
}
}
// 2 docs added every call
- private void addAndQueryDocs(final String baseUrl, int docs) throws Exception {
+ private void addAndQueryDocs(final JettySolrRunner jetty, int docs) throws Exception {
SolrQuery query = new SolrQuery("*:*");
- try (SolrClient client = getHttpSolrClient(baseUrl, "onenodecollection")) {
+ try (SolrClient client = jetty.newSolrClient("onenodecollection")) {
// add a doc
client.add(sdoc("id", docs));
client.commit();
@@ -441,27 +440,25 @@ public class BasicDistributedZk2Test extends AbstractFullDistribZkTestBase {
checkShardConsistency(true, false);
// try a backup command
- try (final SolrClient client =
- getHttpSolrClient((String) shardToJetty.get(SHARD2).get(0).info.get("base_url"))) {
- final String backupName = "the_backup";
- ModifiableSolrParams params = new ModifiableSolrParams();
- params.set("command", "backup");
- params.set("name", backupName);
- final Path location = FilterPath.unwrap(createTempDir()).toRealPath();
- // Allow non-standard location outside SOLR_HOME
- jettys.forEach(j -> j.getCoreContainer().getAllowPaths().add(location));
- params.set("location", location.toString());
-
- QueryRequest request = new QueryRequest(ReplicationHandler.PATH, params);
- client.request(request, DEFAULT_TEST_COLLECTION_NAME);
-
- final BackupStatusChecker backupStatus =
- new BackupStatusChecker(client, "/" + DEFAULT_TEST_COLLECTION_NAME + "/replication");
- final String backupDirName = backupStatus.waitForBackupSuccess(backupName, 30);
- assertTrue(
- "Backup dir does not exist: " + backupDirName,
- Files.exists(location.resolve(backupDirName)));
- }
+ final SolrClient client = shardToJetty.get(SHARD2).get(0).jetty.getSolrClient();
+ final String backupName = "the_backup";
+ ModifiableSolrParams params = new ModifiableSolrParams();
+ params.set("command", "backup");
+ params.set("name", backupName);
+ final Path location = FilterPath.unwrap(createTempDir()).toRealPath();
+ // Allow non-standard location outside SOLR_HOME
+ jettys.forEach(j -> j.getCoreContainer().getAllowPaths().add(location));
+ params.set("location", location.toString());
+
+ QueryRequest request = new QueryRequest(ReplicationHandler.PATH, params);
+ client.request(request, DEFAULT_TEST_COLLECTION_NAME);
+
+ final BackupStatusChecker backupStatus =
+ new BackupStatusChecker(client, "/" + DEFAULT_TEST_COLLECTION_NAME + "/replication");
+ final String backupDirName = backupStatus.waitForBackupSuccess(backupName, 30);
+ assertTrue(
+ "Backup dir does not exist: " + backupDirName,
+ Files.exists(location.resolve(backupDirName)));
}
private void addNewReplica() throws Exception {
diff --git a/solr/core/src/test/org/apache/solr/cloud/BasicDistributedZkTest.java b/solr/core/src/test/org/apache/solr/cloud/BasicDistributedZkTest.java
index a21f4938228..f392491ca4d 100644
--- a/solr/core/src/test/org/apache/solr/cloud/BasicDistributedZkTest.java
+++ b/solr/core/src/test/org/apache/solr/cloud/BasicDistributedZkTest.java
@@ -36,7 +36,6 @@ import java.util.concurrent.SynchronousQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
-import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.atomic.AtomicReference;
import org.apache.lucene.util.IOUtils;
@@ -49,7 +48,6 @@ import org.apache.solr.client.solrj.SolrServerException;
import org.apache.solr.client.solrj.impl.HttpSolrClient;
import org.apache.solr.client.solrj.request.AbstractUpdateRequest;
import org.apache.solr.client.solrj.request.CollectionAdminRequest;
-import org.apache.solr.client.solrj.request.CoreAdminRequest.Create;
import org.apache.solr.client.solrj.request.CoreAdminRequest.Unload;
import org.apache.solr.client.solrj.request.GenericSolrRequest;
import org.apache.solr.client.solrj.request.MetricsRequest;
@@ -111,8 +109,6 @@ public class BasicDistributedZkTest extends AbstractFullDistribZkTestBase {
private String oneInstanceCollection = "oneInstanceCollection";
private String oneInstanceCollection2 = "oneInstanceCollection2";
- private AtomicInteger nodeCounter = new AtomicInteger();
-
CompletionService<Object> completionService;
Set<Future<Object>> pending;
@@ -914,18 +910,17 @@ public class BasicDistributedZkTest extends AbstractFullDistribZkTestBase {
for (Slice slice : dColl.getActiveSlices()) {
long sliceDocCount = -1;
for (Replica rep : slice.getReplicas()) {
- try (SolrClient one = getHttpSolrClient(rep)) {
- SolrQuery query = new SolrQuery("*:*");
- query.setDistrib(false);
- QueryResponse resp = one.query(query);
- long hits = resp.getResults().getNumFound();
- if (sliceDocCount == -1) {
- sliceDocCount = hits;
- docTotal += hits;
- } else {
- if (hits != sliceDocCount) {
- return -1;
- }
+ SolrClient one = getSolrClient(rep);
+ SolrQuery query = new SolrQuery("*:*");
+ query.setDistrib(false);
+ QueryResponse resp = one.query(query);
+ long hits = resp.getResults().getNumFound();
+ if (sliceDocCount == -1) {
+ sliceDocCount = hits;
+ docTotal += hits;
+ } else {
+ if (hits != sliceDocCount) {
+ return -1;
}
}
}
@@ -1043,26 +1038,25 @@ public class BasicDistributedZkTest extends AbstractFullDistribZkTestBase {
private void testStopAndStartCoresInOneInstance() throws Exception {
JettySolrRunner jetty = jettys.get(0);
- try (final var httpSolrClient = jetty.newClient(15000, 60000)) {
- ThreadPoolExecutor executor = null;
- try {
- executor =
- new ExecutorUtil.MDCAwareThreadPoolExecutor(
- 0,
- Integer.MAX_VALUE,
- 5,
- TimeUnit.SECONDS,
- new SynchronousQueue<Runnable>(),
- new SolrNamedThreadFactory("testExecutor"));
- int cnt = 3;
-
- // create the cores
- createCollectionInOneInstance(
- httpSolrClient, jetty.getNodeName(), executor, "multiunload2", 1, cnt);
- } finally {
- if (executor != null) {
- ExecutorUtil.shutdownAndAwaitTermination(executor);
- }
+ var httpSolrClient = jetty.getSolrClient();
+ ThreadPoolExecutor executor = null;
+ try {
+ executor =
+ new ExecutorUtil.MDCAwareThreadPoolExecutor(
+ 0,
+ Integer.MAX_VALUE,
+ 5,
+ TimeUnit.SECONDS,
+ new SynchronousQueue<Runnable>(),
+ new SolrNamedThreadFactory("testExecutor"));
+ int cnt = 3;
+
+ // create the cores
+ createCollectionInOneInstance(
+ httpSolrClient, jetty.getNodeName(), executor, "multiunload2", 1, cnt);
+ } finally {
+ if (executor != null) {
+ ExecutorUtil.shutdownAndAwaitTermination(executor);
}
}
@@ -1379,47 +1373,46 @@ public class BasicDistributedZkTest extends AbstractFullDistribZkTestBase {
.getLeader("shard1");
// now test that unloading a core gets us a new leader
- try (SolrClient unloadClient = jettys.getFirst().newClient(15000, 60000)) {
- Unload unloadCmd = new Unload(true);
- unloadCmd.setCoreName(leader.getCoreName());
-
- String leaderUrl = leader.getCoreUrl();
-
- testExecutor.execute(
- new Runnable() {
-
- @Override
- public void run() {
- try {
- unloadClient.request(unloadCmd);
- } catch (SolrServerException e) {
- throw new RuntimeException(e);
- } catch (IOException e) {
- throw new RuntimeException(e);
- }
+ SolrClient unloadClient = jettys.getFirst().getSolrClient();
+ Unload unloadCmd = new Unload(true);
+ unloadCmd.setCoreName(leader.getCoreName());
+
+ String leaderUrl = leader.getCoreUrl();
+
+ testExecutor.execute(
+ new Runnable() {
+
+ @Override
+ public void run() {
+ try {
+ unloadClient.request(unloadCmd);
+ } catch (SolrServerException e) {
+ throw new RuntimeException(e);
+ } catch (IOException e) {
+ throw new RuntimeException(e);
}
- });
+ }
+ });
- try {
- ZkStateReader.from(getCommonCloudSolrClient())
- .waitForState(
- oneInstanceCollection2,
- 20000,
- TimeUnit.MILLISECONDS,
- (n, c) -> {
- try {
- if (leaderUrl.equals(
- zkStateReader.getLeaderUrl(oneInstanceCollection2, "shard1", 10000))) {
- return false;
- }
- } catch (InterruptedException e) {
- throw new RuntimeException(e);
+ try {
+ ZkStateReader.from(getCommonCloudSolrClient())
+ .waitForState(
+ oneInstanceCollection2,
+ 20000,
+ TimeUnit.MILLISECONDS,
+ (n, c) -> {
+ try {
+ if (leaderUrl.equals(
+ zkStateReader.getLeaderUrl(oneInstanceCollection2, "shard1", 10000))) {
+ return false;
}
- return true;
- });
- } catch (TimeoutException | InterruptedException e) {
- fail("Leader never changed");
- }
+ } catch (InterruptedException e) {
+ throw new RuntimeException(e);
+ }
+ return true;
+ });
+ } catch (TimeoutException | InterruptedException e) {
+ fail("Leader never changed");
}
IOUtils.close(collectionClients);
@@ -1497,45 +1490,6 @@ public class BasicDistributedZkTest extends AbstractFullDistribZkTestBase {
IOUtils.close(collectionClients);
}
- private void createSolrCore(
- final String collection,
- List<SolrClient> collectionClients,
- final String baseUrl,
- final int num,
- final String shardId) {
- Callable<Object> call =
- () -> {
- try (SolrClient client = getHttpSolrClient(baseUrl)) {
- // client.setConnectionTimeout(15000);
- Create createCmd = new Create();
- createCmd.setCoreName(collection + num);
- createCmd.setCollection(collection);
-
- if (random().nextBoolean()) {
- // sometimes we use an explicit core node name
- createCmd.setCoreNodeName("anode" + nodeCounter.incrementAndGet());
- }
-
- if (shardId == null) {
- createCmd.setNumShards(2);
- }
- createCmd.setDataDir(getDataDir(createTempDir(collection).toString()));
- if (shardId != null) {
- createCmd.setShardId(shardId);
- }
- client.request(createCmd);
- } catch (Exception e) {
- log.error("error creating core", e);
- // fail
- }
- return null;
- };
-
- pending.add(completionService.submit(call));
-
- collectionClients.add(createNewSolrClient(baseUrl, collection + num));
- }
-
private void testMultipleCollections() throws Exception {
log.info("### STARTING testMultipleCollections");
// create another 2 collections and search across them
diff --git a/solr/core/src/test/org/apache/solr/cloud/CloudExitableDirectoryReaderTest.java b/solr/core/src/test/org/apache/solr/cloud/CloudExitableDirectoryReaderTest.java
index 24d02a389cf..28bd7dc9d4b 100644
--- a/solr/core/src/test/org/apache/solr/cloud/CloudExitableDirectoryReaderTest.java
+++ b/solr/core/src/test/org/apache/solr/cloud/CloudExitableDirectoryReaderTest.java
@@ -81,7 +81,7 @@ public class CloudExitableDirectoryReaderTest extends SolrCloudTestCase {
clusterBuilder.configure();
// pick an arbitrary node to use for our requests
- client = cluster.getRandomJetty(random()).newClient();
+ client = cluster.getRandomJetty(random()).newSolrClient(null);
CollectionAdminRequest.createCollection(COLLECTION, "conf", 2, 1)
.processAndWait(cluster.getSolrClient(), DEFAULT_TIMEOUT);
diff --git a/solr/core/src/test/org/apache/solr/cloud/CollectionsAPISolrJTest.java b/solr/core/src/test/org/apache/solr/cloud/CollectionsAPISolrJTest.java
index 44c24de9b10..077d4a6f557 100644
--- a/solr/core/src/test/org/apache/solr/cloud/CollectionsAPISolrJTest.java
+++ b/solr/core/src/test/org/apache/solr/cloud/CollectionsAPISolrJTest.java
@@ -296,17 +296,16 @@ public class CollectionsAPISolrJTest extends SolrCloudTestCase {
cluster.waitForActiveCollection(collectionName, 2, 4);
- String nodeName = response._getStr("success[0]/key");
- String corename = response._getStr(asList("success", nodeName, "core"), null);
+ String successKey = response._getStr("success[0]/key"); // "nodeName/coreNodeName"
+ String corename = response._getStr(asList("success", successKey, "core"), null);
+ String nodeName = successKey.substring(0, successKey.indexOf('/'));
- try (SolrClient coreClient =
- getHttpSolrClient(cluster.getZkStateReader().getBaseUrlForNodeName(nodeName))) {
- CoreAdminResponse status = CoreAdminRequest.getStatus(corename, coreClient);
- assertEquals(
- collectionName, status._get(asList("status", corename, "cloud", "collection"), null));
- assertNotNull(status._get(asList("status", corename, "cloud", "shard"), null));
- assertNotNull(status._get(asList("status", corename, "cloud", "replica"), null));
- }
+ SolrClient coreClient = cluster.getJetty(nodeName).getSolrClient();
+ CoreAdminResponse status = CoreAdminRequest.getStatus(corename, coreClient);
+ assertEquals(
+ collectionName, status._get(asList("status", corename, "cloud", "collection"), null));
+ assertNotNull(status._get(asList("status", corename, "cloud", "shard"), null));
+ assertNotNull(status._get(asList("status", corename, "cloud", "replica"), null));
}
@Test
diff --git a/solr/core/src/test/org/apache/solr/cloud/ConcurrentCreateRoutedAliasTest.java b/solr/core/src/test/org/apache/solr/cloud/ConcurrentCreateRoutedAliasTest.java
index 504bfd94fac..50a177d5eff 100644
--- a/solr/core/src/test/org/apache/solr/cloud/ConcurrentCreateRoutedAliasTest.java
+++ b/solr/core/src/test/org/apache/solr/cloud/ConcurrentCreateRoutedAliasTest.java
@@ -95,8 +95,7 @@ public class ConcurrentCreateRoutedAliasTest extends SolrTestCaseJ4 {
int numStart = num;
for (; num < threads.length + numStart; num++) {
final String aliasName = "testAlias" + num;
- final String baseUrl = solrCluster.getJettySolrRunners().get(0).getBaseUrl().toString();
- final SolrClient solrClient = getHttpSolrClient(baseUrl);
+ final SolrClient solrClient = solrCluster.getJettySolrRunners().get(0).newSolrClient(null);
int i = num - numStart;
threads[i] =
@@ -119,8 +118,7 @@ public class ConcurrentCreateRoutedAliasTest extends SolrTestCaseJ4 {
System.out.println("NUM ==> " + num);
for (; num < threads.length + numStart; num++) {
final String aliasName = "testAliasCplx" + num;
- final String baseUrl = solrCluster.getJettySolrRunners().get(0).getBaseUrl().toString();
- final SolrClient solrClient = getHttpSolrClient(baseUrl);
+ final SolrClient solrClient = solrCluster.getJettySolrRunners().get(0).newSolrClient(null);
int i = num - numStart;
threads[i] =
diff --git a/solr/core/src/test/org/apache/solr/cloud/DeleteInactiveReplicaTest.java b/solr/core/src/test/org/apache/solr/cloud/DeleteInactiveReplicaTest.java
index e84e9e436dc..35b017aef12 100644
--- a/solr/core/src/test/org/apache/solr/cloud/DeleteInactiveReplicaTest.java
+++ b/solr/core/src/test/org/apache/solr/cloud/DeleteInactiveReplicaTest.java
@@ -108,20 +108,19 @@ public class DeleteInactiveReplicaTest extends SolrCloudTestCase {
&& !FileUtils.fileExists(replicaCd.getDataDir()));
// Check that we can't create a core with no coreNodeName
- try (SolrClient queryClient = getHttpSolrClient(jetty.getBaseUrl().toString())) {
- Exception e =
- expectThrows(
- Exception.class,
- () -> {
- CoreAdminRequest.Create createRequest = new CoreAdminRequest.Create();
- createRequest.setCoreName("testcore");
- createRequest.setCollection(collectionName);
- createRequest.setShardId("shard2");
- queryClient.request(createRequest);
- });
- assertTrue(
- "Unexpected error message: " + e.getMessage(),
- e.getMessage().contains("coreNodeName missing"));
- }
+ SolrClient queryClient = jetty.getSolrClient();
+ Exception e =
+ expectThrows(
+ Exception.class,
+ () -> {
+ CoreAdminRequest.Create createRequest = new CoreAdminRequest.Create();
+ createRequest.setCoreName("testcore");
+ createRequest.setCollection(collectionName);
+ createRequest.setShardId("shard2");
+ queryClient.request(createRequest);
+ });
+ assertTrue(
+ "Unexpected error message: " + e.getMessage(),
+ e.getMessage().contains("coreNodeName missing"));
}
}
diff --git a/solr/core/src/test/org/apache/solr/cloud/DistribDocExpirationUpdateProcessorTest.java b/solr/core/src/test/org/apache/solr/cloud/DistribDocExpirationUpdateProcessorTest.java
index 821548e1238..ef5d87ae29b 100644
--- a/solr/core/src/test/org/apache/solr/cloud/DistribDocExpirationUpdateProcessorTest.java
+++ b/solr/core/src/test/org/apache/solr/cloud/DistribDocExpirationUpdateProcessorTest.java
@@ -289,37 +289,36 @@ public class DistribDocExpirationUpdateProcessorTest extends SolrCloudTestCase {
for (Replica replica : slice.getReplicas()) {
String coreName = replica.getCoreName();
- try (SolrClient client = getHttpSolrClient(replica)) {
-
- ModifiableSolrParams params = new ModifiableSolrParams();
- params.set("command", "indexversion");
- params.set("_trace", "getIndexVersion");
- QueryRequest req = setAuthIfNeeded(new QueryRequest(ReplicationHandler.PATH, params));
-
- NamedList<Object> res = client.request(req);
- assertNotNull("null response from server: " + coreName, res);
-
- Object version = res.get("indexversion");
- assertNotNull("null version from server: " + coreName, version);
- assertTrue("version isn't a long: " + coreName, version instanceof Long);
-
- long numDocs =
- setAuthIfNeeded(
- new QueryRequest(
- params(
- "q", "*:*",
- "distrib", "false",
- "rows", "0",
- "_trace", "counting_docs")))
- .process(client)
- .getResults()
- .getNumFound();
-
- final ReplicaData data =
- new ReplicaData(replica.getShard(), coreName, (Long) version, numDocs);
- log.info("{}", data);
- results.put(coreName, data);
- }
+ SolrClient client = cluster.getSolrClient(replica);
+
+ ModifiableSolrParams params = new ModifiableSolrParams();
+ params.set("command", "indexversion");
+ params.set("_trace", "getIndexVersion");
+ QueryRequest req = setAuthIfNeeded(new QueryRequest(ReplicationHandler.PATH, params));
+
+ NamedList<Object> res = client.request(req);
+ assertNotNull("null response from server: " + coreName, res);
+
+ Object version = res.get("indexversion");
+ assertNotNull("null version from server: " + coreName, version);
+ assertTrue("version isn't a long: " + coreName, version instanceof Long);
+
+ long numDocs =
+ setAuthIfNeeded(
+ new QueryRequest(
+ params(
+ "q", "*:*",
+ "distrib", "false",
+ "rows", "0",
+ "_trace", "counting_docs")))
+ .process(client)
+ .getResults()
+ .getNumFound();
+
+ final ReplicaData data =
+ new ReplicaData(replica.getShard(), coreName, (Long) version, numDocs);
+ log.info("{}", data);
+ results.put(coreName, data);
}
}
diff --git a/solr/core/src/test/org/apache/solr/cloud/DistributedVersionInfoTest.java b/solr/core/src/test/org/apache/solr/cloud/DistributedVersionInfoTest.java
index a67f0c0495e..7c557eb5166 100644
--- a/solr/core/src/test/org/apache/solr/cloud/DistributedVersionInfoTest.java
+++ b/solr/core/src/test/org/apache/solr/cloud/DistributedVersionInfoTest.java
@@ -110,32 +110,29 @@ public class DistributedVersionInfoTest extends SolrCloudTestCase {
maxOnReplica);
// send the same doc but with a lower version than the max in the index
- try (SolrClient client = getHttpSolrClient(replica)) {
- String docId = String.valueOf(1);
- SolrInputDocument doc = new SolrInputDocument();
- doc.setField("id", docId);
- doc.setField("_version_", maxOnReplica - 1); // bad version!!!
-
- // simulate what the leader does when sending a doc to a replica
- ModifiableSolrParams params = new ModifiableSolrParams();
- params.set(
- DISTRIB_UPDATE_PARAM, DistributedUpdateProcessor.DistribPhase.FROMLEADER.toString());
- params.set(DISTRIB_FROM, leader.getCoreUrl());
-
- UpdateRequest req = new UpdateRequest();
- req.setParams(params);
- req.add(doc);
-
- log.info(
- "Sending doc with out-of-date version ({}) document directly to replica",
- maxOnReplica - 1);
-
- client.request(req);
- client.commit();
-
- Long docVersion = getVersionFromIndex(replica, docId);
- assertEquals("older version should have been thrown away", maxOnReplica, docVersion);
- }
+ SolrClient client = cluster.getSolrClient(replica);
+ String docId = String.valueOf(1);
+ SolrInputDocument doc = new SolrInputDocument();
+ doc.setField("id", docId);
+ doc.setField("_version_", maxOnReplica - 1); // bad version!!!
+
+ // simulate what the leader does when sending a doc to a replica
+ ModifiableSolrParams params = new ModifiableSolrParams();
+ params.set(DISTRIB_UPDATE_PARAM, DistributedUpdateProcessor.DistribPhase.FROMLEADER.toString());
+ params.set(DISTRIB_FROM, leader.getCoreUrl());
+
+ UpdateRequest req = new UpdateRequest();
+ req.setParams(params);
+ req.add(doc);
+
+ log.info(
+ "Sending doc with out-of-date version ({}) document directly to replica", maxOnReplica - 1);
+
+ client.request(req);
+ client.commit();
+
+ Long docVersion = getVersionFromIndex(replica, docId);
+ assertEquals("older version should have been thrown away", maxOnReplica, docVersion);
reloadCollection(leader, COLLECTION);
@@ -301,13 +298,12 @@ public class DistributedVersionInfoTest extends SolrCloudTestCase {
query.addSort(new SolrQuery.SortClause("_version_", SolrQuery.ORDER.desc));
query.setParam("distrib", false);
- try (SolrClient client = getHttpSolrClient(replica)) {
- QueryResponse qr = client.query(query);
- SolrDocumentList hits = qr.getResults();
- if (hits.isEmpty()) fail("No results returned from query: " + query);
+ SolrClient client = cluster.getSolrClient(replica);
+ QueryResponse qr = client.query(query);
+ SolrDocumentList hits = qr.getResults();
+ if (hits.isEmpty()) fail("No results returned from query: " + query);
- vers = (Long) hits.get(0).getFirstValue("_version_");
- }
+ vers = (Long) hits.get(0).getFirstValue("_version_");
if (vers == null)
fail("Failed to get version using query " + query + " from " + replica.getCoreUrl());
@@ -323,27 +319,18 @@ public class DistributedVersionInfoTest extends SolrCloudTestCase {
int lastDocId,
Set<Integer> deletedDocs)
throws Exception {
- SolrClient leaderSolr = getHttpSolrClient(leader);
+ SolrClient leaderSolr = cluster.getSolrClient(leader);
List<SolrClient> replicas = new ArrayList<SolrClient>(notLeaders.size());
- for (Replica r : notLeaders) replicas.add(getHttpSolrClient(r));
+ for (Replica r : notLeaders) replicas.add(cluster.getSolrClient(r));
- try {
- for (int d = firstDocId; d <= lastDocId; d++) {
+ for (int d = firstDocId; d <= lastDocId; d++) {
- if (deletedDocs != null && deletedDocs.contains(d)) continue;
+ if (deletedDocs != null && deletedDocs.contains(d)) continue;
- String docId = String.valueOf(d);
- Long leaderVers = assertDocExists(leaderSolr, docId, null);
- for (SolrClient replicaSolr : replicas) {
- assertDocExists(replicaSolr, docId, leaderVers);
- }
- }
- } finally {
- if (leaderSolr != null) {
- leaderSolr.close();
- }
+ String docId = String.valueOf(d);
+ Long leaderVers = assertDocExists(leaderSolr, docId, null);
for (SolrClient replicaSolr : replicas) {
- replicaSolr.close();
+ assertDocExists(replicaSolr, docId, leaderVers);
}
}
}
@@ -379,30 +366,30 @@ public class DistributedVersionInfoTest extends SolrCloudTestCase {
protected boolean reloadCollection(Replica replica, String testCollectionName) throws Exception {
String coreName = replica.getCoreName();
boolean reloadedOk = false;
- try (SolrClient client = getHttpSolrClient(replica.getBaseUrl())) {
- CoreAdminResponse statusResp = CoreAdminRequest.getStatus(coreName, client);
- long leaderCoreStartTime = statusResp.getStartTime(coreName).getTime();
-
- Thread.sleep(1000);
-
- // send reload command for the collection
- log.info("Sending RELOAD command for {}", testCollectionName);
- CollectionAdminRequest.reloadCollection(testCollectionName).process(client);
- Thread.sleep(2000); // reload can take a short while
-
- // verify reload is done, waiting up to 30 seconds for slow test environments
- long timeout = System.nanoTime() + TimeUnit.NANOSECONDS.convert(30, TimeUnit.SECONDS);
- while (System.nanoTime() < timeout) {
- statusResp = CoreAdminRequest.getStatus(coreName, client);
- long startTimeAfterReload = statusResp.getStartTime(coreName).getTime();
- if (startTimeAfterReload > leaderCoreStartTime) {
- reloadedOk = true;
- break;
- }
- // else ... still waiting to see the reloaded core report a later start time
- Thread.sleep(1000);
+ SolrClient client = cluster.getSolrClient(replica);
+ CoreAdminResponse statusResp = CoreAdminRequest.getStatus(coreName, client);
+ long leaderCoreStartTime = statusResp.getStartTime(coreName).getTime();
+
+ Thread.sleep(1000);
+
+ // send reload command for the collection
+ log.info("Sending RELOAD command for {}", testCollectionName);
+ CollectionAdminRequest.reloadCollection(testCollectionName).process(client);
+ Thread.sleep(2000); // reload can take a short while
+
+ // verify reload is done, waiting up to 30 seconds for slow test environments
+ long timeout = System.nanoTime() + TimeUnit.NANOSECONDS.convert(30, TimeUnit.SECONDS);
+ while (System.nanoTime() < timeout) {
+ statusResp = CoreAdminRequest.getStatus(coreName, client);
+ long startTimeAfterReload = statusResp.getStartTime(coreName).getTime();
+ if (startTimeAfterReload > leaderCoreStartTime) {
+ reloadedOk = true;
+ break;
}
+ // else ... still waiting to see the reloaded core report a later start time
+ Thread.sleep(1000);
}
+
return reloadedOk;
}
}
diff --git a/solr/core/src/test/org/apache/solr/cloud/FullSolrCloudDistribCmdsTest.java b/solr/core/src/test/org/apache/solr/cloud/FullSolrCloudDistribCmdsTest.java
index cb5bee46878..84de1bb043c 100644
--- a/solr/core/src/test/org/apache/solr/cloud/FullSolrCloudDistribCmdsTest.java
+++ b/solr/core/src/test/org/apache/solr/cloud/FullSolrCloudDistribCmdsTest.java
@@ -31,6 +31,7 @@ import org.apache.lucene.tests.util.TestUtil;
import org.apache.solr.client.solrj.SolrClient;
import org.apache.solr.client.solrj.impl.CloudSolrClient;
import org.apache.solr.client.solrj.jetty.ConcurrentUpdateJettySolrClient;
+import org.apache.solr.client.solrj.jetty.HttpJettySolrClient;
import org.apache.solr.client.solrj.request.CollectionAdminRequest;
import org.apache.solr.client.solrj.request.SolrQuery;
import org.apache.solr.client.solrj.request.UpdateRequest;
@@ -170,106 +171,105 @@ public class FullSolrCloudDistribCmdsTest extends SolrCloudTestCase {
(n, c1) -> SolrCloudTestCase.replicasForCollectionAreFullyActive(n, c1, 2, 2));
final DocCollection docCol = cloudClient.getClusterState().getCollection(testCollectionName);
- try (SolrClient shard1 = getHttpSolrClient(docCol.getSlice("shard1").getLeader());
- SolrClient shard2 = getHttpSolrClient(docCol.getSlice("shard2").getLeader())) {
-
- // Add three documents to shard1
- shard1.add(sdoc("id", "1", "title", "s1 one"));
- shard1.add(sdoc("id", "2", "title", "s1 two"));
- shard1.add(sdoc("id", "3", "title", "s1 three"));
- shard1.commit();
- final AtomicInteger docCounts1 = new AtomicInteger(3);
-
- // Add two documents to shard2
- shard2.add(sdoc("id", "4", "title", "s2 four"));
- shard2.add(sdoc("id", "5", "title", "s2 five"));
- shard2.commit();
- final AtomicInteger docCounts2 = new AtomicInteger(2);
-
- // A re-usable helper to verify that the expected number of documents can be found on each
- // shard...
- Runnable checkShardCounts =
- () -> {
- try {
- // including cloudClient helps us test view from other nodes that aren't the
- // leaders...
- for (SolrClient c : Arrays.asList(cloudClient, shard1, shard2)) {
-
- ModifiableSolrParams params = params("q", "*:*");
- if (c instanceof CloudSolrClient) {
- params.add("collection", testCollectionName);
- }
- assertEquals(
- docCounts1.get() + docCounts2.get(),
- c.query(params).getResults().getNumFound());
-
- assertEquals(
- docCounts1.get(),
- c.query(params.set("shards", "shard1")).getResults().getNumFound());
- assertEquals(
- docCounts2.get(),
- c.query(params.set("shards", "shard2")).getResults().getNumFound());
-
- assertEquals(
- docCounts1.get() + docCounts2.get(),
- c.query(params.set("shards", "shard2,shard1")).getResults().getNumFound());
+ Replica shard1Leader = docCol.getSlice("shard1").getLeader();
+ Replica shard2Leader = docCol.getSlice("shard2").getLeader();
+ SolrClient shard1 = cluster.getSolrClient(shard1Leader);
+ SolrClient shard2 = cluster.getSolrClient(shard2Leader);
+ // Add three documents to shard1
+ shard1.add(sdoc("id", "1", "title", "s1 one"));
+ shard1.add(sdoc("id", "2", "title", "s1 two"));
+ shard1.add(sdoc("id", "3", "title", "s1 three"));
+ shard1.commit();
+ final AtomicInteger docCounts1 = new AtomicInteger(3);
+
+ // Add two documents to shard2
+ shard2.add(sdoc("id", "4", "title", "s2 four"));
+ shard2.add(sdoc("id", "5", "title", "s2 five"));
+ shard2.commit();
+ final AtomicInteger docCounts2 = new AtomicInteger(2);
+
+ // A re-usable helper to verify that the expected number of documents can be found on each
+ // shard...
+ Runnable checkShardCounts =
+ () -> {
+ try {
+ // including cloudClient helps us test view from other nodes that aren't the
+ // leaders...
+ for (SolrClient c : Arrays.asList(cloudClient, shard1, shard2)) {
+
+ ModifiableSolrParams params = params("q", "*:*");
+ if (c instanceof CloudSolrClient) {
+ params.add("collection", testCollectionName);
}
+ assertEquals(
+ docCounts1.get() + docCounts2.get(), c.query(params).getResults().getNumFound());
assertEquals(
docCounts1.get(),
- shard1.query(params("q", "*:*", "distrib", "false")).getResults().getNumFound());
+ c.query(params.set("shards", "shard1")).getResults().getNumFound());
assertEquals(
docCounts2.get(),
- shard2.query(params("q", "*:*", "distrib", "false")).getResults().getNumFound());
+ c.query(params.set("shards", "shard2")).getResults().getNumFound());
- } catch (Exception sse) {
- throw new RuntimeException(sse);
+ assertEquals(
+ docCounts1.get() + docCounts2.get(),
+ c.query(params.set("shards", "shard2,shard1")).getResults().getNumFound());
}
- };
- checkShardCounts.run();
-
- { // Send a delete request for a doc on shard1 to core hosting shard1 with NO routing info
- // Should delete (implicitly) since doc is (implicitly) located on this shard
- final UpdateRequest deleteRequest = new UpdateRequest();
- deleteRequest.deleteById("1");
- shard1.request(deleteRequest);
- shard1.commit();
- docCounts1.decrementAndGet();
- }
- checkShardCounts.run();
-
- { // Send a delete request to core hosting shard1 with a route param for a document that is
- // actually in shard2 should delete.
- final UpdateRequest deleteRequest = new UpdateRequest();
- deleteRequest.deleteById("4").withRoute("shard2");
- shard1.request(deleteRequest);
- shard1.commit();
- docCounts2.decrementAndGet();
- }
- checkShardCounts.run();
-
- { // Send a delete request to core hosting shard1 with NO route param for a document that is
- // actually in shard2. Shouldn't delete, since deleteById requests are not broadcast to all
- // shard leaders. (This is effectively a request to delete "5" if and only if it is on
- // shard1)
- final UpdateRequest deleteRequest = new UpdateRequest();
- deleteRequest.deleteById("5");
- shard1.request(deleteRequest);
- shard1.commit();
- }
- checkShardCounts.run();
-
- { // Multiple deleteById commands for different shards in a single request
- final UpdateRequest deleteRequest = new UpdateRequest();
- deleteRequest.deleteById("2", "shard1");
- deleteRequest.deleteById("5", "shard2");
- shard1.request(deleteRequest);
- shard1.commit();
- docCounts1.decrementAndGet();
- docCounts2.decrementAndGet();
- }
- checkShardCounts.run();
+
+ assertEquals(
+ docCounts1.get(),
+ shard1.query(params("q", "*:*", "distrib", "false")).getResults().getNumFound());
+ assertEquals(
+ docCounts2.get(),
+ shard2.query(params("q", "*:*", "distrib", "false")).getResults().getNumFound());
+
+ } catch (Exception sse) {
+ throw new RuntimeException(sse);
+ }
+ };
+ checkShardCounts.run();
+
+ { // Send a delete request for a doc on shard1 to core hosting shard1 with NO routing info
+ // Should delete (implicitly) since doc is (implicitly) located on this shard
+ final UpdateRequest deleteRequest = new UpdateRequest();
+ deleteRequest.deleteById("1");
+ shard1.request(deleteRequest);
+ shard1.commit();
+ docCounts1.decrementAndGet();
+ }
+ checkShardCounts.run();
+
+ { // Send a delete request to core hosting shard1 with a route param for a document that is
+ // actually in shard2 should delete.
+ final UpdateRequest deleteRequest = new UpdateRequest();
+ deleteRequest.deleteById("4").withRoute("shard2");
+ shard1.request(deleteRequest);
+ shard1.commit();
+ docCounts2.decrementAndGet();
}
+ checkShardCounts.run();
+
+ { // Send a delete request to core hosting shard1 with NO route param for a document that is
+ // actually in shard2. Shouldn't delete, since deleteById requests are not broadcast to all
+ // shard leaders. (This is effectively a request to delete "5" if and only if it is on
+ // shard1)
+ final UpdateRequest deleteRequest = new UpdateRequest();
+ deleteRequest.deleteById("5");
+ shard1.request(deleteRequest);
+ shard1.commit();
+ }
+ checkShardCounts.run();
+
+ { // Multiple deleteById commands for different shards in a single request
+ final UpdateRequest deleteRequest = new UpdateRequest();
+ deleteRequest.deleteById("2", "shard1");
+ deleteRequest.deleteById("5", "shard2");
+ shard1.request(deleteRequest);
+ shard1.commit();
+ docCounts1.decrementAndGet();
+ docCounts2.decrementAndGet();
+ }
+ checkShardCounts.run();
}
public void testRTGCompositeRouterWithRouterField() throws Exception {
@@ -325,102 +325,102 @@ public class FullSolrCloudDistribCmdsTest extends SolrCloudTestCase {
(n, c1) -> SolrCloudTestCase.replicasForCollectionAreFullyActive(n, c1, 2, 2));
final DocCollection docCol = cloudClient.getClusterState().getCollection(testCollectionName);
- try (SolrClient shard1 = getHttpSolrClient(docCol.getSlice("shard1").getLeader());
- SolrClient shard2 = getHttpSolrClient(docCol.getSlice("shard2").getLeader())) {
-
- // Add six documents w/diff routes (all sent to shard1 leader's core)
- shard1.add(sdoc("id", "1", "routefield_s", "europe"));
- shard1.add(sdoc("id", "3", "routefield_s", "europe"));
- shard1.add(sdoc("id", "5", "routefield_s", "africa"));
- shard1.add(sdoc("id", "7", "routefield_s", "europe"));
- shard1.add(sdoc("id", "9", "routefield_s", "europe"));
- shard1.add(sdoc("id", "11", "routefield_s", "africa"));
- shard1.commit();
-
- // Add four documents w/diff routes (all sent to shard2 leader's core)
- shard2.add(sdoc("id", "8", "routefield_s", "africa"));
- shard2.add(sdoc("id", "6", "routefield_s", "europe"));
- shard2.add(sdoc("id", "4", "routefield_s", "africa"));
- shard2.add(sdoc("id", "2", "routefield_s", "europe"));
- shard2.commit();
-
- final AtomicInteger docCountsEurope = new AtomicInteger(6);
- final AtomicInteger docCountsAfrica = new AtomicInteger(4);
-
- // A re-usable helper to verify that the expected number of documents can be found based on
- // _route_ key...
- Runnable checkShardCounts =
- () -> {
- try {
- // including cloudClient helps us test view from other nodes that aren't the
- // leaders...
- for (SolrClient c : Arrays.asList(cloudClient, shard1, shard2)) {
-
- ModifiableSolrParams params = params("q", "*:*");
- if (c instanceof CloudSolrClient) {
- params.add("collection", testCollectionName);
- }
- assertEquals(
- docCountsEurope.get() + docCountsAfrica.get(),
- c.query(params).getResults().getNumFound());
-
- assertEquals(
- docCountsEurope.get(),
- c.query(params.set("_route_", "europe")).getResults().getNumFound());
- assertEquals(
- docCountsAfrica.get(),
- c.query(params.set("_route_", "africa")).getResults().getNumFound());
+ Replica shard1Leader = docCol.getSlice("shard1").getLeader();
+ Replica shard2Leader = docCol.getSlice("shard2").getLeader();
+ SolrClient shard1 = cluster.getSolrClient(shard1Leader);
+ SolrClient shard2 = cluster.getSolrClient(shard2Leader);
+ // Add six documents w/diff routes (all sent to shard1 leader's core)
+ shard1.add(sdoc("id", "1", "routefield_s", "europe"));
+ shard1.add(sdoc("id", "3", "routefield_s", "europe"));
+ shard1.add(sdoc("id", "5", "routefield_s", "africa"));
+ shard1.add(sdoc("id", "7", "routefield_s", "europe"));
+ shard1.add(sdoc("id", "9", "routefield_s", "europe"));
+ shard1.add(sdoc("id", "11", "routefield_s", "africa"));
+ shard1.commit();
+
+ // Add four documents w/diff routes (all sent to shard2 leader's core)
+ shard2.add(sdoc("id", "8", "routefield_s", "africa"));
+ shard2.add(sdoc("id", "6", "routefield_s", "europe"));
+ shard2.add(sdoc("id", "4", "routefield_s", "africa"));
+ shard2.add(sdoc("id", "2", "routefield_s", "europe"));
+ shard2.commit();
+
+ final AtomicInteger docCountsEurope = new AtomicInteger(6);
+ final AtomicInteger docCountsAfrica = new AtomicInteger(4);
+
+ // A re-usable helper to verify that the expected number of documents can be found based on
+ // _route_ key...
+ Runnable checkShardCounts =
+ () -> {
+ try {
+ // including cloudClient helps us test view from other nodes that aren't the
+ // leaders...
+ for (SolrClient c : Arrays.asList(cloudClient, shard1, shard2)) {
+
+ ModifiableSolrParams params = params("q", "*:*");
+ if (c instanceof CloudSolrClient) {
+ params.add("collection", testCollectionName);
}
- } catch (Exception sse) {
- throw new RuntimeException(sse);
+ assertEquals(
+ docCountsEurope.get() + docCountsAfrica.get(),
+ c.query(params).getResults().getNumFound());
+
+ assertEquals(
+ docCountsEurope.get(),
+ c.query(params.set("_route_", "europe")).getResults().getNumFound());
+ assertEquals(
+ docCountsAfrica.get(),
+ c.query(params.set("_route_", "africa")).getResults().getNumFound());
}
- };
- checkShardCounts.run();
-
- { // Send a delete request to core hosting shard1 with a route param for a document that was
- // originally added via core on shard2
- final UpdateRequest deleteRequest = new UpdateRequest();
- deleteRequest.deleteById("4", "africa");
- shard1.request(deleteRequest);
- shard1.commit();
- docCountsAfrica.decrementAndGet();
- }
- checkShardCounts.run();
-
- { // Multiple deleteById commands with different routes in a single request
- final UpdateRequest deleteRequest = new UpdateRequest();
- deleteRequest.deleteById("2", "europe");
- deleteRequest.deleteById("5", "africa");
- shard1.request(deleteRequest);
- shard1.commit();
- docCountsEurope.decrementAndGet();
- docCountsAfrica.decrementAndGet();
- }
- checkShardCounts.run();
-
- // Tests for distributing delete by id when route is missing from the request
- { // Send a delete request with no route to shard1 for document on shard2, should be
- // distributed
- final UpdateRequest deleteRequest = new UpdateRequest();
- deleteRequest.deleteById("8");
- shard1.request(deleteRequest);
- shard1.commit();
- docCountsAfrica.decrementAndGet();
- }
- checkShardCounts.run();
-
- { // Multiple deleteById commands with missing route in a single request, should be
- // distributed
- final UpdateRequest deleteRequest = new UpdateRequest();
- deleteRequest.deleteById("6");
- deleteRequest.deleteById("11");
- shard1.request(deleteRequest);
- shard1.commit();
- docCountsEurope.decrementAndGet();
- docCountsAfrica.decrementAndGet();
- }
- checkShardCounts.run();
+ } catch (Exception sse) {
+ throw new RuntimeException(sse);
+ }
+ };
+ checkShardCounts.run();
+
+ { // Send a delete request to core hosting shard1 with a route param for a document that was
+ // originally added via core on shard2
+ final UpdateRequest deleteRequest = new UpdateRequest();
+ deleteRequest.deleteById("4", "africa");
+ shard1.request(deleteRequest);
+ shard1.commit();
+ docCountsAfrica.decrementAndGet();
}
+ checkShardCounts.run();
+
+ { // Multiple deleteById commands with different routes in a single request
+ final UpdateRequest deleteRequest = new UpdateRequest();
+ deleteRequest.deleteById("2", "europe");
+ deleteRequest.deleteById("5", "africa");
+ shard1.request(deleteRequest);
+ shard1.commit();
+ docCountsEurope.decrementAndGet();
+ docCountsAfrica.decrementAndGet();
+ }
+ checkShardCounts.run();
+
+ // Tests for distributing delete by id when route is missing from the request
+ { // Send a delete request with no route to shard1 for document on shard2, should be
+ // distributed
+ final UpdateRequest deleteRequest = new UpdateRequest();
+ deleteRequest.deleteById("8");
+ shard1.request(deleteRequest);
+ shard1.commit();
+ docCountsAfrica.decrementAndGet();
+ }
+ checkShardCounts.run();
+
+ { // Multiple deleteById commands with missing route in a single request, should be
+ // distributed
+ final UpdateRequest deleteRequest = new UpdateRequest();
+ deleteRequest.deleteById("6");
+ deleteRequest.deleteById("11");
+ shard1.request(deleteRequest);
+ shard1.commit();
+ docCountsEurope.decrementAndGet();
+ docCountsAfrica.decrementAndGet();
+ }
+ checkShardCounts.run();
}
public void testThatCantForwardToLeaderFails() throws Exception {
@@ -488,7 +488,10 @@ public class FullSolrCloudDistribCmdsTest extends SolrCloudTestCase {
}
// create client to send our updates to...
- try (SolrClient indexClient = getHttpSolrClient(indexingBaseUrl, collectionName)) {
+ try (SolrClient indexClient =
+ new HttpJettySolrClient.Builder(indexingBaseUrl)
+ .withDefaultCollection(collectionName)
+ .build()) {
// Sanity check: we should be able to send a bunch of updates that work right now...
for (int i = 0; i < 100; i++) {
@@ -862,30 +865,27 @@ public class FullSolrCloudDistribCmdsTest extends SolrCloudTestCase {
final Slice slice = entry.getValue();
log.info("Checking: {} -> {}", shardName, slice);
final Replica leader = entry.getValue().getLeader();
- try (SolrClient leaderClient = getHttpSolrClient(leader)) {
- final SolrDocumentList leaderResults = leaderClient.query(perReplicaParams).getResults();
- log.debug("Shard {}: Leader results: {}", shardName, leaderResults);
- for (Replica replica : slice) {
- try (SolrClient replicaClient = getHttpSolrClient(replica)) {
- final SolrDocumentList replicaResults =
- replicaClient.query(perReplicaParams).getResults();
- if (log.isDebugEnabled()) {
- log.debug(
- "Shard {}: Replica ({}) results: {}",
- shardName,
- replica.getCoreName(),
- replicaResults);
- }
- assertEquals(
- "inconsistency w/leader: shard=" + shardName + "core=" + replica.getCoreName(),
- Set.of(),
- CloudInspectUtil.showDiff(
- leaderResults,
- replicaResults,
- shardName + " leader: " + leader.getCoreUrl(),
- shardName + ": " + replica.getCoreUrl()));
- }
+ SolrClient leaderClient = cluster.getSolrClient(leader);
+ final SolrDocumentList leaderResults = leaderClient.query(perReplicaParams).getResults();
+ log.debug("Shard {}: Leader results: {}", shardName, leaderResults);
+ for (Replica replica : slice) {
+ SolrClient replicaClient = cluster.getSolrClient(replica);
+ final SolrDocumentList replicaResults = replicaClient.query(perReplicaParams).getResults();
+ if (log.isDebugEnabled()) {
+ log.debug(
+ "Shard {}: Replica ({}) results: {}",
+ shardName,
+ replica.getCoreName(),
+ replicaResults);
}
+ assertEquals(
+ "inconsistency w/leader: shard=" + shardName + "core=" + replica.getCoreName(),
+ Set.of(),
+ CloudInspectUtil.showDiff(
+ leaderResults,
+ replicaResults,
+ shardName + " leader: " + leader.getCoreUrl(),
+ shardName + ": " + replica.getCoreUrl()));
}
}
}
diff --git a/solr/core/src/test/org/apache/solr/cloud/HttpPartitionOnCommitTest.java b/solr/core/src/test/org/apache/solr/cloud/HttpPartitionOnCommitTest.java
index c271c88adb7..a41b5e2b061 100644
--- a/solr/core/src/test/org/apache/solr/cloud/HttpPartitionOnCommitTest.java
+++ b/solr/core/src/test/org/apache/solr/cloud/HttpPartitionOnCommitTest.java
@@ -190,25 +190,24 @@ public class HttpPartitionOnCommitTest extends BasicDistributedZkTest {
String replicaCoreUrl = replica.getCoreUrl();
log.info("Sending commit request to: {}", replicaCoreUrl);
final RTimer timer = new RTimer();
- try (SolrClient client = getHttpSolrClient(replica)) {
- try {
- client.commit();
+ SolrClient client = getSolrClient(replica);
+ try {
+ client.commit();
- if (log.isInfoEnabled()) {
- log.info("Sent commit request to {} OK, took {}ms", replicaCoreUrl, timer.getTime());
- }
- } catch (Exception exc) {
- Throwable rootCause = SolrException.getRootCause(exc);
- if (rootCause instanceof IOException) {
- log.warn(
- "No HTTP response from sending commit request to {}; will re-try after waiting 3 seconds",
- replicaCoreUrl);
- Thread.sleep(3000);
- client.commit();
- log.info("Second attempt at sending commit to {} succeeded", replicaCoreUrl);
- } else {
- throw exc;
- }
+ if (log.isInfoEnabled()) {
+ log.info("Sent commit request to {} OK, took {}ms", replicaCoreUrl, timer.getTime());
+ }
+ } catch (Exception exc) {
+ Throwable rootCause = SolrException.getRootCause(exc);
+ if (rootCause instanceof IOException) {
+ log.warn(
+ "No HTTP response from sending commit request to {}; will re-try after waiting 3 seconds",
+ replicaCoreUrl);
+ Thread.sleep(3000);
+ client.commit();
+ log.info("Second attempt at sending commit to {} succeeded", replicaCoreUrl);
+ } else {
+ throw exc;
}
}
}
diff --git a/solr/core/src/test/org/apache/solr/cloud/HttpPartitionTest.java b/solr/core/src/test/org/apache/solr/cloud/HttpPartitionTest.java
index ee536f12ae1..b3008764c21 100644
--- a/solr/core/src/test/org/apache/solr/cloud/HttpPartitionTest.java
+++ b/solr/core/src/test/org/apache/solr/cloud/HttpPartitionTest.java
@@ -430,21 +430,15 @@ public class HttpPartitionTest extends AbstractFullDistribZkTestBase {
if (log.isInfoEnabled()) {
log.info("Sending doc 2 to old leader {}", leader.getName());
}
- try (SolrClient leaderSolr = getHttpSolrClient(leader, testCollectionName)) {
-
- leaderSolr.add(doc);
- leaderSolr.close();
+ try {
+ getSolrClient(leader).add(doc);
// if the add worked, then the doc must exist on the new leader
- try (SolrClient newLeaderSolr = getHttpSolrClient(currentLeader, testCollectionName)) {
- assertDocExists(newLeaderSolr, "2");
- }
+ assertDocExists(getSolrClient(currentLeader), "2");
} catch (SolrException exc) {
// this is ok provided the doc doesn't exist on the current leader
- try (SolrClient client = getHttpSolrClient(currentLeader, testCollectionName)) {
- client.add(doc); // this should work
- }
+ getSolrClient(currentLeader).add(doc); // this should work
}
List<Replica> participatingReplicas =
@@ -491,34 +485,21 @@ public class HttpPartitionTest extends AbstractFullDistribZkTestBase {
throws Exception {
Replica leader =
ZkStateReader.from(cloudClient).getLeaderRetry(testCollectionName, "shard1", 10000);
- SolrClient leaderSolr = getHttpSolrClient(leader, testCollectionName);
+ SolrClient leaderSolr = getSolrClient(leader);
List<SolrClient> replicas = new ArrayList<SolrClient>(notLeaders.size());
for (Replica r : notLeaders) {
- replicas.add(getHttpSolrClient(r, testCollectionName));
+ replicas.add(getSolrClient(r));
}
- try {
- for (int d = firstDocId; d <= lastDocId; d++) {
- String docId = String.valueOf(d);
- assertDocExists(leaderSolr, docId);
- for (SolrClient replicaSolr : replicas) {
- assertDocExists(replicaSolr, docId);
- }
- }
- } finally {
- if (leaderSolr != null) {
- leaderSolr.close();
- }
+ for (int d = firstDocId; d <= lastDocId; d++) {
+ String docId = String.valueOf(d);
+ assertDocExists(leaderSolr, docId);
for (SolrClient replicaSolr : replicas) {
- replicaSolr.close();
+ assertDocExists(replicaSolr, docId);
}
}
}
- protected SolrClient getHttpSolrClient(Replica replica, String collection) {
- return getHttpSolrClient(replica.getBaseUrl(), collection);
- }
-
// Send doc directly to a server (without going through proxy)
protected int sendDoc(String collectionName, int docId, JettySolrRunner leaderJetty)
throws IOException, SolrServerException {
diff --git a/solr/core/src/test/org/apache/solr/cloud/LeaderFailoverAfterPartitionTest.java b/solr/core/src/test/org/apache/solr/cloud/LeaderFailoverAfterPartitionTest.java
index 18e3d792cbe..9a8ff0fef95 100644
--- a/solr/core/src/test/org/apache/solr/cloud/LeaderFailoverAfterPartitionTest.java
+++ b/solr/core/src/test/org/apache/solr/cloud/LeaderFailoverAfterPartitionTest.java
@@ -22,7 +22,6 @@ import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import org.apache.solr.SolrTestCaseJ4.SuppressSSL;
-import org.apache.solr.client.solrj.SolrClient;
import org.apache.solr.common.SolrInputDocument;
import org.apache.solr.common.cloud.Replica;
import org.apache.solr.common.cloud.ZkStateReader;
@@ -124,13 +123,8 @@ public class LeaderFailoverAfterPartitionTest extends HttpPartitionTest {
// doc should be on leader and 1 replica
sendDoc(testCollectionName, 5);
- try (SolrClient server = getHttpSolrClient(leader, testCollectionName)) {
- assertDocExists(server, "5");
- }
-
- try (SolrClient server = getHttpSolrClient(notLeaders.get(1), testCollectionName)) {
- assertDocExists(server, "5");
- }
+ assertDocExists(getSolrClient(leader), "5");
+ assertDocExists(getSolrClient(notLeaders.get(1)), "5");
Thread.sleep(sleepMsBeforeHealPartition);
diff --git a/solr/core/src/test/org/apache/solr/cloud/MigrateReplicasTest.java b/solr/core/src/test/org/apache/solr/cloud/MigrateReplicasTest.java
index 1d4d431d6df..a72e991690f 100644
--- a/solr/core/src/test/org/apache/solr/cloud/MigrateReplicasTest.java
+++ b/solr/core/src/test/org/apache/solr/cloud/MigrateReplicasTest.java
@@ -35,7 +35,6 @@ import org.apache.solr.client.solrj.response.CoreAdminResponse;
import org.apache.solr.common.cloud.DocCollection;
import org.apache.solr.common.cloud.Replica;
import org.apache.solr.common.cloud.Slice;
-import org.apache.solr.common.cloud.ZkStateReader;
import org.apache.solr.common.util.StrUtils;
import org.apache.solr.common.util.Utils;
import org.apache.solr.core.CoreContainer;
@@ -122,15 +121,12 @@ public class MigrateReplicasTest extends SolrCloudTestCase {
"MigrateReplicas request was unsuccessful",
0L,
((Map<?, ?>) response.get("responseHeader")).get("status"));
- ZkStateReader zkStateReader = ZkStateReader.from(cloudClient);
- try (SolrClient coreClient =
- getHttpSolrClient(zkStateReader.getBaseUrlForNodeName(nodeToBeDecommissioned))) {
- CoreAdminResponse status = CoreAdminRequest.getStatus(null, coreClient);
- assertEquals(
- "There should not be any cores left on decommissioned node",
- 0,
- status.getCoreStatus().size());
- }
+ SolrClient coreClient = cluster.getJetty(nodeToBeDecommissioned).getSolrClient();
+ CoreAdminResponse status = CoreAdminRequest.getStatus(null, coreClient);
+ assertEquals(
+ "There should not be any cores left on decommissioned node",
+ 0,
+ status.getCoreStatus().size());
Thread.sleep(5000);
collection = cloudClient.getClusterState().getCollectionOrNull(coll, false);
@@ -150,14 +146,12 @@ public class MigrateReplicasTest extends SolrCloudTestCase {
0L,
((Map<?, ?>) response.get("responseHeader")).get("status"));
- try (SolrClient coreClient =
- getHttpSolrClient(zkStateReader.getBaseUrlForNodeName(emptyNode))) {
- CoreAdminResponse status = CoreAdminRequest.getStatus(null, coreClient);
- assertEquals(
- "Expecting no cores but found some: " + status.getCoreStatus(),
- 0,
- status.getCoreStatus().size());
- }
+ SolrClient emptyNodeClient = cluster.getJetty(emptyNode).getSolrClient();
+ CoreAdminResponse emptyNodeStatus = CoreAdminRequest.getStatus(null, emptyNodeClient);
+ assertEquals(
+ "Expecting no cores but found some: " + emptyNodeStatus.getCoreStatus(),
+ 0,
+ emptyNodeStatus.getCoreStatus().size());
collection = cluster.getSolrClient().getClusterState().getCollection(coll);
assertEquals(create.getNumShards().intValue(), collection.getSlices().size());
diff --git a/solr/core/src/test/org/apache/solr/cloud/MigrateRouteKeyTest.java b/solr/core/src/test/org/apache/solr/cloud/MigrateRouteKeyTest.java
index 09114574f2a..c0b1ce96d67 100644
--- a/solr/core/src/test/org/apache/solr/cloud/MigrateRouteKeyTest.java
+++ b/solr/core/src/test/org/apache/solr/cloud/MigrateRouteKeyTest.java
@@ -133,14 +133,13 @@ public class MigrateRouteKeyTest extends SolrCloudTestCase {
DocCollection sourceState = getCollectionState(sourceCollection);
assertEquals(2, sourceState.getSlice("shard1").getReplicas().size());
for (Replica replica : sourceState.getSlice("shard1")) {
- try (SolrClient replicaClient = getHttpSolrClient(replica)) {
- SolrQuery query = new SolrQuery("id:\"a!2\"");
- query.set("distrib", false);
- assertEquals(
- "Document missing from replica " + replica.getName(),
- 1,
- replicaClient.query(query).getResults().getNumFound());
- }
+ var replicaClient = cluster.getSolrClient(replica);
+ SolrQuery query = new SolrQuery("id:\"a!2\"");
+ query.set("distrib", false);
+ assertEquals(
+ "Document missing from replica " + replica.getName(),
+ 1,
+ replicaClient.query(query).getResults().getNumFound());
}
waitForState(
@@ -187,56 +186,54 @@ public class MigrateRouteKeyTest extends SolrCloudTestCase {
DocCollection state = getCollectionState(targetCollection);
Replica replica = state.replicaStream().findFirst().orElseThrow();
- try (SolrClient collectionClient = getHttpSolrClient(replica)) {
+ SolrClient collectionClient = cluster.getSolrClient(replica);
+ SolrQuery solrQuery = new SolrQuery("*:*");
+ assertEquals(
+ "DocCount on target collection does not match",
+ 0,
+ collectionClient.query(solrQuery).getResults().getNumFound());
- SolrQuery solrQuery = new SolrQuery("*:*");
- assertEquals(
- "DocCount on target collection does not match",
- 0,
- collectionClient.query(solrQuery).getResults().getNumFound());
+ invokeCollectionMigration(
+ CollectionAdminRequest.migrateData(
+ sourceCollection, targetCollection, splitKey + "/" + BIT_SEP + "!")
+ .setForwardTimeout(45));
- invokeCollectionMigration(
- CollectionAdminRequest.migrateData(
- sourceCollection, targetCollection, splitKey + "/" + BIT_SEP + "!")
- .setForwardTimeout(45));
+ long finishTime = System.nanoTime();
- long finishTime = System.nanoTime();
+ indexer.join();
+ splitKeyCount += indexer.getSplitKeyCount();
- indexer.join();
- splitKeyCount += indexer.getSplitKeyCount();
+ try {
+ cluster.getSolrClient().deleteById(sourceCollection, "a/" + BIT_SEP + "!104");
+ splitKeyCount--;
+ } catch (Exception e) {
+ log.warn("Error deleting document a/{}!104", BIT_SEP, e);
+ }
+ cluster.getSolrClient().commit(sourceCollection);
+ collectionClient.commit();
- try {
- cluster.getSolrClient().deleteById(sourceCollection, "a/" + BIT_SEP + "!104");
- splitKeyCount--;
- } catch (Exception e) {
- log.warn("Error deleting document a/{}!104", BIT_SEP, e);
- }
- cluster.getSolrClient().commit(sourceCollection);
- collectionClient.commit();
+ solrQuery = new SolrQuery("*:*").setRows(1000);
+ QueryResponse response = collectionClient.query(solrQuery);
+ log.info("Response from target collection: {}", response);
+ assertEquals(
+ "DocCount on target collection does not match",
+ splitKeyCount,
+ response.getResults().getNumFound());
- solrQuery = new SolrQuery("*:*").setRows(1000);
- QueryResponse response = collectionClient.query(solrQuery);
- log.info("Response from target collection: {}", response);
- assertEquals(
- "DocCount on target collection does not match",
- splitKeyCount,
- response.getResults().getNumFound());
-
- waitForState(
- "Expected to find routing rule for split key " + splitKey,
- sourceCollection,
- c -> {
- if (c == null) return false;
- Slice shard = c.getSlice("shard2");
- if (shard == null) return false;
- if (shard.getRoutingRules() == null || shard.getRoutingRules().isEmpty()) return false;
- if (shard.getRoutingRules().get(splitKey + "!") == null) return false;
- return true;
- });
-
- boolean ruleRemoved = waitForRuleToExpire(sourceCollection, "shard2", splitKey, finishTime);
- assertTrue("Routing rule was not expired", ruleRemoved);
- }
+ waitForState(
+ "Expected to find routing rule for split key " + splitKey,
+ sourceCollection,
+ c -> {
+ if (c == null) return false;
+ Slice shard = c.getSlice("shard2");
+ if (shard == null) return false;
+ if (shard.getRoutingRules() == null || shard.getRoutingRules().isEmpty()) return false;
+ if (shard.getRoutingRules().get(splitKey + "!") == null) return false;
+ return true;
+ });
+
+ boolean ruleRemoved = waitForRuleToExpire(sourceCollection, "shard2", splitKey, finishTime);
+ assertTrue("Routing rule was not expired", ruleRemoved);
}
static class Indexer extends Thread {
diff --git a/solr/core/src/test/org/apache/solr/cloud/MoveReplicaTest.java b/solr/core/src/test/org/apache/solr/cloud/MoveReplicaTest.java
index 68524274e02..7e9706f9410 100644
--- a/solr/core/src/test/org/apache/solr/cloud/MoveReplicaTest.java
+++ b/solr/core/src/test/org/apache/solr/cloud/MoveReplicaTest.java
@@ -38,7 +38,6 @@ import org.apache.solr.common.SolrInputDocument;
import org.apache.solr.common.cloud.DocCollection;
import org.apache.solr.common.cloud.Replica;
import org.apache.solr.common.cloud.Slice;
-import org.apache.solr.common.cloud.ZkStateReader;
import org.apache.solr.common.util.NamedList;
import org.apache.solr.embedded.JettySolrRunner;
import org.apache.solr.util.IdUtils;
@@ -364,35 +363,33 @@ public class MoveReplicaTest extends SolrCloudTestCase {
private int getNumOfCores(
CloudSolrClient cloudClient, String nodeName, String collectionName, String replicaType)
throws IOException, SolrServerException {
- try (SolrClient coreclient =
- getHttpSolrClient(ZkStateReader.from(cloudClient).getBaseUrlForNodeName(nodeName))) {
- CoreAdminResponse status = CoreAdminRequest.getStatus(null, coreclient);
- if (status.getCoreStatus().size() == 0) {
- return 0;
- }
- if (collectionName == null && replicaType == null) {
- return status.getCoreStatus().size();
- }
- // filter size by collection name
- int size = 0;
- for (Map.Entry<String, CoreStatusResponse.SingleCoreData> coreStatusEntry :
- status.getCoreStatus().entrySet()) {
- if (collectionName != null) {
- String coll = coreStatusEntry.getValue().cloud.collection;
- if (!collectionName.equals(coll)) {
- continue;
- }
+ SolrClient coreclient = cluster.getJetty(nodeName).getSolrClient();
+ CoreAdminResponse status = CoreAdminRequest.getStatus(null, coreclient);
+ if (status.getCoreStatus().size() == 0) {
+ return 0;
+ }
+ if (collectionName == null && replicaType == null) {
+ return status.getCoreStatus().size();
+ }
+ // filter size by collection name
+ int size = 0;
+ for (Map.Entry<String, CoreStatusResponse.SingleCoreData> coreStatusEntry :
+ status.getCoreStatus().entrySet()) {
+ if (collectionName != null) {
+ String coll = coreStatusEntry.getValue().cloud.collection;
+ if (!collectionName.equals(coll)) {
+ continue;
}
- if (replicaType != null) {
- String type = coreStatusEntry.getValue().cloud.replicaType;
- if (!replicaType.equals(type)) {
- continue;
- }
+ }
+ if (replicaType != null) {
+ String type = coreStatusEntry.getValue().cloud.replicaType;
+ if (!replicaType.equals(type)) {
+ continue;
}
- size++;
}
- return size;
+ size++;
}
+ return size;
}
protected void addDocs(String collection, int numDocs) throws Exception {
diff --git a/solr/core/src/test/org/apache/solr/cloud/NestedShardedAtomicUpdateTest.java b/solr/core/src/test/org/apache/solr/cloud/NestedShardedAtomicUpdateTest.java
index c284d581cd8..c3569fc7865 100644
--- a/solr/core/src/test/org/apache/solr/cloud/NestedShardedAtomicUpdateTest.java
+++ b/solr/core/src/test/org/apache/solr/cloud/NestedShardedAtomicUpdateTest.java
@@ -22,7 +22,6 @@ import java.lang.invoke.MethodHandles;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;
-import org.apache.lucene.util.IOUtils;
import org.apache.solr.client.solrj.SolrClient;
import org.apache.solr.client.solrj.SolrServerException;
import org.apache.solr.client.solrj.impl.CloudSolrClient;
@@ -36,7 +35,6 @@ import org.apache.solr.common.cloud.ClusterState;
import org.apache.solr.common.params.ModifiableSolrParams;
import org.apache.solr.common.params.SolrParams;
import org.apache.solr.util.RandomNoReverseMergePolicyFactory;
-import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.ClassRule;
import org.junit.Test;
@@ -73,12 +71,7 @@ public class NestedShardedAtomicUpdateTest extends SolrCloudTestCase {
clusterState
.getCollection(DEFAULT_COLLECTION)
.replicaStream()
- .forEach(replica -> clients.add(getHttpSolrClient(replica)));
- }
-
- @AfterClass
- public static void afterClass() throws Exception {
- IOUtils.close(clients);
+ .forEach(replica -> clients.add(cluster.getSolrClient(replica)));
}
@Test
diff --git a/solr/core/src/test/org/apache/solr/cloud/RemoteQueryErrorTest.java b/solr/core/src/test/org/apache/solr/cloud/RemoteQueryErrorTest.java
index 9da524dfc9b..a1465260522 100644
--- a/solr/core/src/test/org/apache/solr/cloud/RemoteQueryErrorTest.java
+++ b/solr/core/src/test/org/apache/solr/cloud/RemoteQueryErrorTest.java
@@ -43,16 +43,15 @@ public class RemoteQueryErrorTest extends SolrCloudTestCase {
.process(cluster.getSolrClient());
for (JettySolrRunner jetty : cluster.getJettySolrRunners()) {
- try (SolrClient client = jetty.newClient()) {
- SolrException e =
- expectThrows(
- SolrException.class,
- () -> {
- client.add("collection", new SolrInputDocument());
- });
- assertThat(
- e.getMessage(), containsString("Document is missing mandatory uniqueKey field: id"));
- }
+ SolrClient client = jetty.getSolrClient();
+ SolrException e =
+ expectThrows(
+ SolrException.class,
+ () -> {
+ client.add("collection", new SolrInputDocument());
+ });
+ assertThat(
+ e.getMessage(), containsString("Document is missing mandatory uniqueKey field: id"));
}
}
}
diff --git a/solr/core/src/test/org/apache/solr/cloud/ReplaceNodeTest.java b/solr/core/src/test/org/apache/solr/cloud/ReplaceNodeTest.java
index bc64635d2d8..fac7fe5928e 100644
--- a/solr/core/src/test/org/apache/solr/cloud/ReplaceNodeTest.java
+++ b/solr/core/src/test/org/apache/solr/cloud/ReplaceNodeTest.java
@@ -36,7 +36,6 @@ import org.apache.solr.common.SolrException;
import org.apache.solr.common.cloud.DocCollection;
import org.apache.solr.common.cloud.Replica;
import org.apache.solr.common.cloud.Slice;
-import org.apache.solr.common.cloud.ZkStateReader;
import org.apache.solr.common.params.CollectionParams;
import org.apache.solr.common.params.ModifiableSolrParams;
import org.apache.solr.common.params.SolrParams;
@@ -116,12 +115,9 @@ public class ReplaceNodeTest extends SolrCloudTestCase {
log.info("excluded_node : {} ", emptyNode);
createReplaceNodeRequest(nodeToBeDecommissioned, emptyNode, null)
.processAndWait("000", cloudClient, 15);
- ZkStateReader zkStateReader = ZkStateReader.from(cloudClient);
- try (SolrClient coreClient =
- getHttpSolrClient(zkStateReader.getBaseUrlForNodeName(nodeToBeDecommissioned))) {
- CoreAdminResponse status = CoreAdminRequest.getStatus(null, coreClient);
- assertEquals(0, status.getCoreStatus().size());
- }
+ SolrClient coreClient = cluster.getJetty(nodeToBeDecommissioned).getSolrClient();
+ CoreAdminResponse status = CoreAdminRequest.getStatus(null, coreClient);
+ assertEquals(0, status.getCoreStatus().size());
Thread.sleep(5000);
collection = cloudClient.getClusterState().getCollection(coll);
@@ -136,14 +132,12 @@ public class ReplaceNodeTest extends SolrCloudTestCase {
replaceNodeRequest.setWaitForFinalState(true);
replaceNodeRequest.processAndWait("001", cloudClient, 10);
- try (SolrClient coreClient =
- getHttpSolrClient(zkStateReader.getBaseUrlForNodeName(emptyNode))) {
- CoreAdminResponse status = CoreAdminRequest.getStatus(null, coreClient);
- assertEquals(
- "Expecting no cores but found some: " + status.getCoreStatus(),
- 0,
- status.getCoreStatus().size());
- }
+ SolrClient emptyNodeClient = cluster.getJetty(emptyNode).getSolrClient();
+ CoreAdminResponse emptyNodeStatus = CoreAdminRequest.getStatus(null, emptyNodeClient);
+ assertEquals(
+ "Expecting no cores but found some: " + emptyNodeStatus.getCoreStatus(),
+ 0,
+ emptyNodeStatus.getCoreStatus().size());
collection = cluster.getSolrClient().getClusterState().getCollection(coll);
assertEquals(create.getNumShards().intValue(), collection.getSlices().size());
diff --git a/solr/core/src/test/org/apache/solr/cloud/ReplicationFactorTest.java b/solr/core/src/test/org/apache/solr/cloud/ReplicationFactorTest.java
index eb63af4a5ac..1d967a55c25 100644
--- a/solr/core/src/test/org/apache/solr/cloud/ReplicationFactorTest.java
+++ b/solr/core/src/test/org/apache/solr/cloud/ReplicationFactorTest.java
@@ -29,7 +29,6 @@ import java.util.concurrent.TimeoutException;
import java.util.stream.Collectors;
import org.apache.lucene.tests.util.LuceneTestCase.AwaitsFix;
import org.apache.solr.SolrTestCaseJ4.SuppressSSL;
-import org.apache.solr.client.solrj.SolrClient;
import org.apache.solr.client.solrj.SolrServerException;
import org.apache.solr.client.solrj.request.CollectionAdminRequest;
import org.apache.solr.client.solrj.request.UpdateRequest;
@@ -268,22 +267,20 @@ public class ReplicationFactorTest extends AbstractFullDistribZkTestBase {
protected void sendNonDirectUpdateRequestReplica(
Replica replica, UpdateRequest up, int expectedRf, String collection) throws Exception {
- try (SolrClient solrServer = getHttpSolrClient(replica.getBaseUrl(), collection)) {
- NamedList<?> resp = solrServer.request(up);
- NamedList<?> hdr = (NamedList<?>) resp.get("responseHeader");
- Integer batchRf = (Integer) hdr.get(UpdateRequest.REPFACT);
- // Note that this also tests if we're wonky and return an achieved rf greater than the number
- // of live replicas.
- assertEquals(
- "Expected rf="
- + expectedRf
- + " for batch but got "
- + batchRf
- + "; clusterState: "
- + printClusterStateInfo(),
- (int) batchRf,
- expectedRf);
- }
+ NamedList<?> resp = getSolrClient(replica).request(up);
+ NamedList<?> hdr = (NamedList<?>) resp.get("responseHeader");
+ Integer batchRf = (Integer) hdr.get(UpdateRequest.REPFACT);
+ // Note that this also tests if we're wonky and return an achieved rf greater than the number
+ // of live replicas.
+ assertEquals(
+ "Expected rf="
+ + expectedRf
+ + " for batch but got "
+ + batchRf
+ + "; clusterState: "
+ + printClusterStateInfo(),
+ (int) batchRf,
+ expectedRf);
}
protected void testRf3() throws Exception {
diff --git a/solr/core/src/test/org/apache/solr/cloud/SplitShardTest.java b/solr/core/src/test/org/apache/solr/cloud/SplitShardTest.java
index 0b539bd39d0..a7405273e26 100644
--- a/solr/core/src/test/org/apache/solr/cloud/SplitShardTest.java
+++ b/solr/core/src/test/org/apache/solr/cloud/SplitShardTest.java
@@ -229,18 +229,10 @@ public class SplitShardTest extends SolrCloudTestCase {
if (!slice.getState().equals(Slice.State.ACTIVE)) continue;
long lastReplicaCount = -1;
for (Replica replica : slice.getReplicas()) {
- SolrClient replicaClient = getHttpSolrClient(replica);
- long numFound;
- try {
- numFound =
- replicaClient
- .query(params("q", "*:*", "distrib", "false"))
- .getResults()
- .getNumFound();
- log.info("Replica count={} for {}", numFound, replica);
- } finally {
- replicaClient.close();
- }
+ SolrClient replicaClient = cluster.getSolrClient(replica);
+ long numFound =
+ replicaClient.query(params("q", "*:*", "distrib", "false")).getResults().getNumFound();
+ log.info("Replica count={} for {}", numFound, replica);
if (lastReplicaCount >= 0) {
assertEquals("Replica doc count for " + replica, lastReplicaCount, numFound);
}
diff --git a/solr/core/src/test/org/apache/solr/cloud/TestBaseStatsCacheCloud.java b/solr/core/src/test/org/apache/solr/cloud/TestBaseStatsCacheCloud.java
index a7dc3f8d12f..f73c4447059 100644
--- a/solr/core/src/test/org/apache/solr/cloud/TestBaseStatsCacheCloud.java
+++ b/solr/core/src/test/org/apache/solr/cloud/TestBaseStatsCacheCloud.java
@@ -131,46 +131,45 @@ public abstract class TestBaseStatsCacheCloud extends SolrCloudTestCase {
// check cache metrics
StatsCache.StatsCacheMetrics statsCacheMetrics = new StatsCache.StatsCacheMetrics();
for (JettySolrRunner jettySolrRunner : cluster.getJettySolrRunners()) {
- try (SolrClient client = getHttpSolrClient(jettySolrRunner.getBaseUrl().toString())) {
- var req = new MetricsRequest(SolrParams.of("wt", "prometheus"));
-
- NamedList<Object> resp = client.request(req);
- try (InputStream in = (InputStream) resp.get("stream")) {
- String output = new String(in.readAllBytes(), StandardCharsets.UTF_8);
-
- for (String line : output.lines().toList()) {
- if (line.startsWith("solr_core_indexsearcher_termstats_cache")) {
- String type = extractTypeAttribute(line);
- long value = extractMetricValue(line);
- switch (type) {
- case "lookups":
- statsCacheMetrics.lookups.add(value);
- break;
- case "return_local":
- statsCacheMetrics.returnLocalStats.add(value);
- break;
- case "merge_to_global":
- statsCacheMetrics.mergeToGlobalStats.add(value);
- break;
- case "missing_global_field":
- statsCacheMetrics.missingGlobalFieldStats.add(value);
- break;
- case "missing_global_term":
- statsCacheMetrics.missingGlobalTermStats.add(value);
- break;
- case "receive_global":
- statsCacheMetrics.receiveGlobalStats.add(value);
- break;
- case "retrieve":
- statsCacheMetrics.retrieveStats.add(value);
- break;
- case "send_global":
- statsCacheMetrics.sendGlobalStats.add(value);
- break;
- case "use_cached_global":
- statsCacheMetrics.useCachedGlobalStats.add(value);
- break;
- }
+ SolrClient client = jettySolrRunner.getSolrClient();
+ var req = new MetricsRequest(SolrParams.of("wt", "prometheus"));
+
+ NamedList<Object> resp = client.request(req);
+ try (InputStream in = (InputStream) resp.get("stream")) {
+ String output = new String(in.readAllBytes(), StandardCharsets.UTF_8);
+
+ for (String line : output.lines().toList()) {
+ if (line.startsWith("solr_core_indexsearcher_termstats_cache")) {
+ String type = extractTypeAttribute(line);
+ long value = extractMetricValue(line);
+ switch (type) {
+ case "lookups":
+ statsCacheMetrics.lookups.add(value);
+ break;
+ case "return_local":
+ statsCacheMetrics.returnLocalStats.add(value);
+ break;
+ case "merge_to_global":
+ statsCacheMetrics.mergeToGlobalStats.add(value);
+ break;
+ case "missing_global_field":
+ statsCacheMetrics.missingGlobalFieldStats.add(value);
+ break;
+ case "missing_global_term":
+ statsCacheMetrics.missingGlobalTermStats.add(value);
+ break;
+ case "receive_global":
+ statsCacheMetrics.receiveGlobalStats.add(value);
+ break;
+ case "retrieve":
+ statsCacheMetrics.retrieveStats.add(value);
+ break;
+ case "send_global":
+ statsCacheMetrics.sendGlobalStats.add(value);
+ break;
+ case "use_cached_global":
+ statsCacheMetrics.useCachedGlobalStats.add(value);
+ break;
}
}
}
diff --git a/solr/core/src/test/org/apache/solr/cloud/TestCloudConsistency.java b/solr/core/src/test/org/apache/solr/cloud/TestCloudConsistency.java
index b3c7c4142ae..39f9661bd40 100644
--- a/solr/core/src/test/org/apache/solr/cloud/TestCloudConsistency.java
+++ b/solr/core/src/test/org/apache/solr/cloud/TestCloudConsistency.java
@@ -309,26 +309,17 @@ public class TestCloudConsistency extends SolrCloudTestCase {
List<Replica> notLeaders, String testCollectionName, int firstDocId, int lastDocId)
throws Exception {
Replica leader = cluster.getZkStateReader().getLeaderRetry(testCollectionName, "shard1", 10000);
- SolrClient leaderSolr = getHttpSolrClient(leader, testCollectionName);
+ SolrClient leaderSolr = cluster.getSolrClient(leader);
List<SolrClient> replicas = new ArrayList<>(notLeaders.size());
for (Replica r : notLeaders) {
- replicas.add(getHttpSolrClient(r, testCollectionName));
+ replicas.add(cluster.getSolrClient(r));
}
- try {
- for (int d = firstDocId; d <= lastDocId; d++) {
- String docId = String.valueOf(d);
- assertDocExists(leaderSolr, docId);
- for (SolrClient replicaSolr : replicas) {
- assertDocExists(replicaSolr, docId);
- }
- }
- } finally {
- if (leaderSolr != null) {
- leaderSolr.close();
- }
+ for (int d = firstDocId; d <= lastDocId; d++) {
+ String docId = String.valueOf(d);
+ assertDocExists(leaderSolr, docId);
for (SolrClient replicaSolr : replicas) {
- replicaSolr.close();
+ assertDocExists(replicaSolr, docId);
}
}
}
@@ -349,8 +340,4 @@ public class TestCloudConsistency extends SolrCloudTestCase {
params("id", docId, "distrib", "false"))
.setRequiresCollection(true));
}
-
- protected SolrClient getHttpSolrClient(Replica replica, String coll) {
- return getHttpSolrClient(replica.getBaseUrl(), coll);
- }
}
diff --git a/solr/core/src/test/org/apache/solr/cloud/TestCloudDeleteByQuery.java b/solr/core/src/test/org/apache/solr/cloud/TestCloudDeleteByQuery.java
index 451ef12dab6..c5fe0b43e98 100644
--- a/solr/core/src/test/org/apache/solr/cloud/TestCloudDeleteByQuery.java
+++ b/solr/core/src/test/org/apache/solr/cloud/TestCloudDeleteByQuery.java
@@ -27,6 +27,7 @@ import java.util.Map;
import java.util.UUID;
import org.apache.solr.client.solrj.SolrClient;
import org.apache.solr.client.solrj.impl.CloudSolrClient;
+import org.apache.solr.client.solrj.impl.CollectionScopedSolrClient;
import org.apache.solr.client.solrj.request.CollectionAdminRequest;
import org.apache.solr.client.solrj.request.UpdateRequest;
import org.apache.solr.common.SolrDocument;
@@ -88,26 +89,11 @@ public class TestCloudDeleteByQuery extends SolrCloudTestCase {
COLLECTION_CLIENT.close();
COLLECTION_CLIENT = null;
}
- if (null != S_ONE_LEADER_CLIENT) {
- S_ONE_LEADER_CLIENT.close();
- S_ONE_LEADER_CLIENT = null;
- }
- if (null != S_TWO_LEADER_CLIENT) {
- S_TWO_LEADER_CLIENT.close();
- S_TWO_LEADER_CLIENT = null;
- }
- if (null != S_ONE_NON_LEADER_CLIENT) {
- S_ONE_NON_LEADER_CLIENT.close();
- S_ONE_NON_LEADER_CLIENT = null;
- }
- if (null != S_TWO_NON_LEADER_CLIENT) {
- S_TWO_NON_LEADER_CLIENT.close();
- S_TWO_NON_LEADER_CLIENT = null;
- }
- if (null != NO_COLLECTION_CLIENT) {
- NO_COLLECTION_CLIENT.close();
- NO_COLLECTION_CLIENT = null;
- }
+ S_ONE_LEADER_CLIENT = null;
+ S_TWO_LEADER_CLIENT = null;
+ S_ONE_NON_LEADER_CLIENT = null;
+ S_TWO_NON_LEADER_CLIENT = null;
+ NO_COLLECTION_CLIENT = null;
}
@BeforeClass
@@ -166,17 +152,27 @@ public class TestCloudDeleteByQuery extends SolrCloudTestCase {
assertNotNull("could not find URL for " + shardName + " replica", passiveUrl);
if (shardName.equals("shard1")) {
- S_ONE_LEADER_CLIENT = getHttpSolrClient(leaderUrl, COLLECTION_NAME);
- S_ONE_NON_LEADER_CLIENT = getHttpSolrClient(passiveUrl, COLLECTION_NAME);
+ S_ONE_LEADER_CLIENT =
+ new CollectionScopedSolrClient(
+ cluster.getJetty(leaderUrl).getSolrClient(), COLLECTION_NAME);
+ S_ONE_NON_LEADER_CLIENT =
+ new CollectionScopedSolrClient(
+ cluster.getJetty(passiveUrl).getSolrClient(), COLLECTION_NAME);
} else if (shardName.equals("shard2")) {
- S_TWO_LEADER_CLIENT = getHttpSolrClient(leaderUrl, COLLECTION_NAME);
- S_TWO_NON_LEADER_CLIENT = getHttpSolrClient(passiveUrl, COLLECTION_NAME);
+ S_TWO_LEADER_CLIENT =
+ new CollectionScopedSolrClient(
+ cluster.getJetty(leaderUrl).getSolrClient(), COLLECTION_NAME);
+ S_TWO_NON_LEADER_CLIENT =
+ new CollectionScopedSolrClient(
+ cluster.getJetty(passiveUrl).getSolrClient(), COLLECTION_NAME);
} else {
fail("unexpected shard: " + shardName);
}
}
assertEquals("Should be exactly one server left (not hosting either shard)", 1, urlMap.size());
- NO_COLLECTION_CLIENT = getHttpSolrClient(urlMap.values().iterator().next(), COLLECTION_NAME);
+ NO_COLLECTION_CLIENT =
+ new CollectionScopedSolrClient(
+ cluster.getJetty(urlMap.values().iterator().next()).getSolrClient(), COLLECTION_NAME);
assertNotNull(S_ONE_LEADER_CLIENT);
assertNotNull(S_TWO_LEADER_CLIENT);
diff --git a/solr/core/src/test/org/apache/solr/cloud/TestCloudPhrasesIdentificationComponent.java b/solr/core/src/test/org/apache/solr/cloud/TestCloudPhrasesIdentificationComponent.java
index 2a979299698..cedc2927c73 100644
--- a/solr/core/src/test/org/apache/solr/cloud/TestCloudPhrasesIdentificationComponent.java
+++ b/solr/core/src/test/org/apache/solr/cloud/TestCloudPhrasesIdentificationComponent.java
@@ -80,7 +80,7 @@ public class TestCloudPhrasesIdentificationComponent extends SolrCloudTestCase {
waitForRecoveriesToFinish(COLLECTION_CLIENT);
for (JettySolrRunner jetty : cluster.getJettySolrRunners()) {
- CLIENTS.add(getHttpSolrClient(jetty.getBaseUrl().toString(), COLLECTION_NAME));
+ CLIENTS.add(jetty.newSolrClient(COLLECTION_NAME));
}
// index some docs...
diff --git a/solr/core/src/test/org/apache/solr/cloud/TestCloudPseudoReturnFields.java b/solr/core/src/test/org/apache/solr/cloud/TestCloudPseudoReturnFields.java
index 81969dae345..848d88fc2b6 100644
--- a/solr/core/src/test/org/apache/solr/cloud/TestCloudPseudoReturnFields.java
+++ b/solr/core/src/test/org/apache/solr/cloud/TestCloudPseudoReturnFields.java
@@ -97,7 +97,7 @@ public class TestCloudPseudoReturnFields extends SolrCloudTestCase {
waitForRecoveriesToFinish(COLLECTION_CLIENT);
for (JettySolrRunner jetty : cluster.getJettySolrRunners()) {
- CLIENTS.add(getHttpSolrClient(jetty.getBaseUrl().toString(), COLLECTION_NAME));
+ CLIENTS.add(jetty.newSolrClient(COLLECTION_NAME));
}
assertEquals(
diff --git a/solr/core/src/test/org/apache/solr/cloud/TestCloudRecovery2.java b/solr/core/src/test/org/apache/solr/cloud/TestCloudRecovery2.java
index d4af2692573..b1962539f18 100644
--- a/solr/core/src/test/org/apache/solr/cloud/TestCloudRecovery2.java
+++ b/solr/core/src/test/org/apache/solr/cloud/TestCloudRecovery2.java
@@ -49,7 +49,8 @@ public class TestCloudRecovery2 extends SolrCloudTestCase {
public void test() throws Exception {
JettySolrRunner node1 = cluster.getJettySolrRunner(0);
JettySolrRunner node2 = cluster.getJettySolrRunner(1);
- try (SolrClient client1 = getHttpSolrClient(node1.getBaseUrl().toString())) {
+ {
+ SolrClient client1 = node1.getSolrClient();
node2.stop();
waitForState("", COLLECTION, (liveNodes, collectionState) -> liveNodes.size() == 1);
@@ -63,9 +64,10 @@ public class TestCloudRecovery2 extends SolrCloudTestCase {
node2.start();
waitForState("", COLLECTION, clusterShape(1, 2));
- try (SolrClient client = getHttpSolrClient(node2.getBaseUrl().toString())) {
+ {
long numFound =
- client
+ node2
+ .getSolrClient()
.query(COLLECTION, new SolrQuery("q", "*:*", "distrib", "false"))
.getResults()
.getNumFound();
@@ -80,9 +82,10 @@ public class TestCloudRecovery2 extends SolrCloudTestCase {
new UpdateRequest().add("id", "1", "num", "10").commit(client1, COLLECTION);
- try (SolrClient client = getHttpSolrClient(node2.getBaseUrl().toString())) {
+ {
Object v =
- client
+ node2
+ .getSolrClient()
.query(COLLECTION, new SolrQuery("q", "id:1", "distrib", "false"))
.getResults()
.get(0)
@@ -112,9 +115,10 @@ public class TestCloudRecovery2 extends SolrCloudTestCase {
node2.start();
waitForState("", COLLECTION, clusterShape(1, 2));
- try (SolrClient client = getHttpSolrClient(node2.getBaseUrl().toString())) {
+ {
v =
- client
+ node2
+ .getSolrClient()
.query(COLLECTION, new SolrQuery("q", "id:1", "distrib", "false"))
.getResults()
.get(0)
@@ -137,9 +141,10 @@ public class TestCloudRecovery2 extends SolrCloudTestCase {
node2.start();
waitForState("", COLLECTION, clusterShape(1, 2));
- try (SolrClient client = getHttpSolrClient(node2.getBaseUrl().toString())) {
+ {
v =
- client
+ node2
+ .getSolrClient()
.query(COLLECTION, new SolrQuery("q", "id:1", "distrib", "false"))
.getResults()
.get(0)
@@ -166,18 +171,20 @@ public class TestCloudRecovery2 extends SolrCloudTestCase {
node1.start();
waitForState("", COLLECTION, clusterShape(1, 2));
- try (SolrClient client = getHttpSolrClient(node1.getBaseUrl().toString())) {
+ {
Object v =
- client
+ node1
+ .getSolrClient()
.query(COLLECTION, new SolrQuery("q", "id:1", "distrib", "false"))
.getResults()
.get(0)
.get("num");
assertEquals("30", v.toString());
}
- try (SolrClient client = getHttpSolrClient(node2.getBaseUrl().toString())) {
+ {
Object v =
- client
+ node2
+ .getSolrClient()
.query(COLLECTION, new SolrQuery("q", "id:1", "distrib", "false"))
.getResults()
.get(0)
diff --git a/solr/core/src/test/org/apache/solr/cloud/TestConfigSetsAPI.java b/solr/core/src/test/org/apache/solr/cloud/TestConfigSetsAPI.java
index c7ece98ae62..f2f80ed019e 100644
--- a/solr/core/src/test/org/apache/solr/cloud/TestConfigSetsAPI.java
+++ b/solr/core/src/test/org/apache/solr/cloud/TestConfigSetsAPI.java
@@ -136,39 +136,37 @@ public class TestConfigSetsAPI extends SolrCloudTestCase {
@Test
public void testCreateErrors() throws Exception {
- final String baseUrl = cluster.getJettySolrRunners().get(0).getBaseUrl().toString();
- try (final SolrClient solrClient = getHttpSolrClient(baseUrl)) {
- getConfigSetService().uploadConfig("configSet", configset("configset-2"));
-
- // no action
- CreateNoErrorChecking createNoAction = new CreateNoErrorChecking();
- createNoAction.setAction(null);
- verifyException(solrClient, createNoAction, "action");
-
- // no ConfigSet name
- CreateNoErrorChecking create = new CreateNoErrorChecking();
- verifyException(solrClient, create, NAME);
-
- // set ConfigSet
- create.setConfigSetName("configSetName");
-
- // ConfigSet already exists
- Create alreadyExists = new Create();
- alreadyExists.setConfigSetName("configSet").setBaseConfigSetName("baseConfigSet");
- verifyException(solrClient, alreadyExists, "ConfigSet already exists");
-
- // Base ConfigSet does not exist
- Create baseConfigNoExists = new Create();
- baseConfigNoExists.setConfigSetName("newConfigSet").setBaseConfigSetName("baseConfigSet");
- verifyException(solrClient, baseConfigNoExists, "Base ConfigSet does not exist");
-
- // Invalid configset names
- for (String invalidName :
- new String[] {"configset!", "configset\"", "-configset", "configset name"}) {
- Create invalidNameCreate = new Create();
- invalidNameCreate.setConfigSetName(invalidName).setBaseConfigSetName("_default");
- verifyException(solrClient, invalidNameCreate, "Invalid configset");
- }
+ final SolrClient solrClient = cluster.getJettySolrRunners().get(0).getSolrClient();
+ getConfigSetService().uploadConfig("configSet", configset("configset-2"));
+
+ // no action
+ CreateNoErrorChecking createNoAction = new CreateNoErrorChecking();
+ createNoAction.setAction(null);
+ verifyException(solrClient, createNoAction, "action");
+
+ // no ConfigSet name
+ CreateNoErrorChecking create = new CreateNoErrorChecking();
+ verifyException(solrClient, create, NAME);
+
+ // set ConfigSet
+ create.setConfigSetName("configSetName");
+
+ // ConfigSet already exists
+ Create alreadyExists = new Create();
+ alreadyExists.setConfigSetName("configSet").setBaseConfigSetName("baseConfigSet");
+ verifyException(solrClient, alreadyExists, "ConfigSet already exists");
+
+ // Base ConfigSet does not exist
+ Create baseConfigNoExists = new Create();
+ baseConfigNoExists.setConfigSetName("newConfigSet").setBaseConfigSetName("baseConfigSet");
+ verifyException(solrClient, baseConfigNoExists, "Base ConfigSet does not exist");
+
+ // Invalid configset names
+ for (String invalidName :
+ new String[] {"configset!", "configset\"", "-configset", "configset name"}) {
+ Create invalidNameCreate = new Create();
+ invalidNameCreate.setConfigSetName(invalidName).setBaseConfigSetName("_default");
+ verifyException(solrClient, invalidNameCreate, "Invalid configset");
}
}
@@ -223,25 +221,23 @@ public class TestConfigSetsAPI extends SolrCloudTestCase {
Map<String, String> newProps,
String username)
throws Exception {
- final String baseUrl = cluster.getJettySolrRunners().get(0).getBaseUrl().toString();
- try (final SolrClient solrClient = getHttpSolrClient(baseUrl)) {
- setupBaseConfigSet(baseConfigSetName, oldProps);
-
- try (SolrZkClient zkClient =
- new SolrZkClient.Builder()
- .withUrl(cluster.getZkServer().getZkAddress())
- .withTimeout(AbstractZkTestCase.TIMEOUT, TimeUnit.MILLISECONDS)
- .withConnTimeOut(AbstractZkTestCase.TIMEOUT, TimeUnit.MILLISECONDS)
- .build()) {
- assertFalse(getConfigSetService().checkConfigExists(configSetName));
-
- ConfigSetAdminResponse response =
- createConfigSet(baseConfigSetName, configSetName, newProps, solrClient, username);
- assertNotNull(response.getResponse());
- assertTrue(getConfigSetService().checkConfigExists(configSetName));
-
- verifyProperties(configSetName, oldProps, newProps, zkClient);
- }
+ final SolrClient solrClient = cluster.getJettySolrRunners().get(0).getSolrClient();
+ setupBaseConfigSet(baseConfigSetName, oldProps);
+
+ try (SolrZkClient zkClient =
+ new SolrZkClient.Builder()
+ .withUrl(cluster.getZkServer().getZkAddress())
+ .withTimeout(AbstractZkTestCase.TIMEOUT, TimeUnit.MILLISECONDS)
+ .withConnTimeOut(AbstractZkTestCase.TIMEOUT, TimeUnit.MILLISECONDS)
+ .build()) {
+ assertFalse(getConfigSetService().checkConfigExists(configSetName));
+
+ ConfigSetAdminResponse response =
+ createConfigSet(baseConfigSetName, configSetName, newProps, solrClient, username);
+ assertNotNull(response.getResponse());
+ assertTrue(getConfigSetService().checkConfigExists(configSetName));
+
+ verifyProperties(configSetName, oldProps, newProps, zkClient);
}
}
@@ -1639,8 +1635,7 @@ public class TestConfigSetsAPI extends SolrCloudTestCase {
@Test
public void testDeleteErrors() throws Exception {
- final String baseUrl = cluster.getJettySolrRunners().get(0).getBaseUrl().toString();
- final SolrClient solrClient = getHttpSolrClient(baseUrl);
+ final SolrClient solrClient = cluster.getJettySolrRunners().get(0).getSolrClient();
final Path configDir = getFile("solr").resolve("configsets/configset-2/conf");
final Path tmpConfigDir = createTempDir();
// Ensure ConfigSet is immutable
@@ -1658,8 +1653,6 @@ public class TestConfigSetsAPI extends SolrCloudTestCase {
// ConfigSet is immutable
delete.setConfigSetName("configSet");
verifyException(solrClient, delete, "Requested delete of immutable ConfigSet");
-
- solrClient.close();
}
@SuppressWarnings("try")
@@ -1675,13 +1668,11 @@ public class TestConfigSetsAPI extends SolrCloudTestCase {
@Test
public void testDelete() throws Exception {
- final String baseUrl = cluster.getJettySolrRunners().get(0).getBaseUrl().toString();
- final SolrClient solrClient = getHttpSolrClient(baseUrl);
+ final SolrClient solrClient = cluster.getJettySolrRunners().get(0).getSolrClient();
final String configSet = "testDelete";
getConfigSetService().uploadConfig(configSet, configset("configset-2"));
assertDelete(solrClient, configSet, true);
assertDelete(solrClient, "configSetBogus", false);
- solrClient.close();
}
private void assertDelete(SolrClient solrClient, String configSet, boolean assertExists)
@@ -1707,8 +1698,7 @@ public class TestConfigSetsAPI extends SolrCloudTestCase {
@Test
public void testList() throws Exception {
- final String baseUrl = cluster.getJettySolrRunners().get(0).getBaseUrl().toString();
- final SolrClient solrClient = getHttpSolrClient(baseUrl);
+ final SolrClient solrClient = cluster.getJettySolrRunners().get(0).getSolrClient();
SolrZkClient zkClient =
new SolrZkClient.Builder()
@@ -1737,8 +1727,6 @@ public class TestConfigSetsAPI extends SolrCloudTestCase {
} finally {
zkClient.close();
}
-
- solrClient.close();
}
/**
diff --git a/solr/core/src/test/org/apache/solr/cloud/TestConfigSetsAPIExclusivity.java b/solr/core/src/test/org/apache/solr/cloud/TestConfigSetsAPIExclusivity.java
index 722ed01c1fa..4f4c715f742 100644
--- a/solr/core/src/test/org/apache/solr/cloud/TestConfigSetsAPIExclusivity.java
+++ b/solr/core/src/test/org/apache/solr/cloud/TestConfigSetsAPIExclusivity.java
@@ -118,8 +118,7 @@ public class TestConfigSetsAPIExclusivity extends SolrTestCaseJ4 {
@Override
public void run() {
- final String baseUrl = solrCluster.getJettySolrRunners().get(0).getBaseUrl().toString();
- final SolrClient solrClient = getHttpSolrClient(baseUrl);
+ final SolrClient solrClient = solrCluster.getJettySolrRunners().get(0).getSolrClient();
ConfigSetAdminRequest<?, ?> request = createRequest();
for (int i = 0; i < trials; ++i) {
@@ -129,11 +128,6 @@ public class TestConfigSetsAPIExclusivity extends SolrTestCaseJ4 {
verifyException(e);
}
}
- try {
- solrClient.close();
- } catch (Exception e) {
- log.error("Error closing client", e);
- }
}
private void verifyException(Exception e) {
diff --git a/solr/core/src/test/org/apache/solr/cloud/TestConfigSetsAPIZkFailure.java b/solr/core/src/test/org/apache/solr/cloud/TestConfigSetsAPIZkFailure.java
index 0cce6aef96f..2ce4b74190e 100644
--- a/solr/core/src/test/org/apache/solr/cloud/TestConfigSetsAPIZkFailure.java
+++ b/solr/core/src/test/org/apache/solr/cloud/TestConfigSetsAPIZkFailure.java
@@ -108,8 +108,7 @@ public class TestConfigSetsAPIZkFailure extends SolrTestCaseJ4 {
@Test
public void testCreateZkFailure() throws Exception {
- final String baseUrl = solrCluster.getJettySolrRunners().get(0).getBaseUrl().toString();
- final SolrClient solrClient = getHttpSolrClient(baseUrl);
+ final SolrClient solrClient = solrCluster.getJettySolrRunners().get(0).getSolrClient();
final ConfigSetService configSetService =
solrCluster.getOpenOverseer().getCoreContainer().getConfigSetService();
@@ -136,8 +135,6 @@ public class TestConfigSetsAPIZkFailure extends SolrTestCaseJ4 {
} finally {
zkClient.close();
}
-
- solrClient.close();
}
private void setupBaseConfigSet(String baseConfigSetName, Map<String, String> oldProps)
diff --git a/solr/core/src/test/org/apache/solr/cloud/TestGracefulJettyShutdown.java b/solr/core/src/test/org/apache/solr/cloud/TestGracefulJettyShutdown.java
index c0cc72fb206..a0c6fdbec99 100644
--- a/solr/core/src/test/org/apache/solr/cloud/TestGracefulJettyShutdown.java
+++ b/solr/core/src/test/org/apache/solr/cloud/TestGracefulJettyShutdown.java
@@ -28,6 +28,7 @@ import java.util.concurrent.TimeUnit;
import org.apache.solr.SolrTestCaseJ4;
import org.apache.solr.client.solrj.SolrClient;
import org.apache.solr.client.solrj.impl.CloudSolrClient;
+import org.apache.solr.client.solrj.jetty.HttpJettySolrClient;
import org.apache.solr.client.solrj.request.CollectionAdminRequest;
import org.apache.solr.client.solrj.request.QueryRequest;
import org.apache.solr.client.solrj.response.QueryResponse;
@@ -84,7 +85,8 @@ public class TestGracefulJettyShutdown extends SolrTestCaseJ4 {
final List<Future<QueryResponse>> results = new ArrayList<>(13);
- try (SolrClient jettyClient = nodeToStop.newClient()) {
+ try (SolrClient jettyClient =
+ new HttpJettySolrClient.Builder(nodeToStop.getBaseUrl().toString()).build()) {
final QueryRequest req = new QueryRequest(handler, params("q", "foo_s:aaa"));
// check inflight requests using both clients...
diff --git a/solr/core/src/test/org/apache/solr/cloud/TestMiniSolrCloudClusterSSL.java b/solr/core/src/test/org/apache/solr/cloud/TestMiniSolrCloudClusterSSL.java
index 39d6561381c..e49441cdd4e 100644
--- a/solr/core/src/test/org/apache/solr/cloud/TestMiniSolrCloudClusterSSL.java
+++ b/solr/core/src/test/org/apache/solr/cloud/TestMiniSolrCloudClusterSSL.java
@@ -412,6 +412,6 @@ public class TestMiniSolrCloudClusterSSL extends SolrTestCaseJ4 {
if (random().nextBoolean()) {
return HttpSolrClient.builder(url).build();
} // else...
- return getHttpSolrClient(url);
+ return new HttpJettySolrClient.Builder(url).build();
}
}
diff --git a/solr/core/src/test/org/apache/solr/cloud/TestPullReplica.java b/solr/core/src/test/org/apache/solr/cloud/TestPullReplica.java
index c6f30385972..d3e4c120b13 100644
--- a/solr/core/src/test/org/apache/solr/cloud/TestPullReplica.java
+++ b/solr/core/src/test/org/apache/solr/cloud/TestPullReplica.java
@@ -36,6 +36,7 @@ import java.util.stream.Collectors;
import org.apache.lucene.tests.util.LuceneTestCase.Nightly;
import org.apache.solr.client.solrj.SolrClient;
import org.apache.solr.client.solrj.SolrServerException;
+import org.apache.solr.client.solrj.jetty.HttpJettySolrClient;
import org.apache.solr.client.solrj.request.CollectionAdminRequest;
import org.apache.solr.client.solrj.request.QueryRequest;
import org.apache.solr.client.solrj.request.SolrQuery;
@@ -297,9 +298,10 @@ public class TestPullReplica extends SolrCloudTestCase {
log.info("Committed doc {} to leader", numDocs);
Slice s = docCollection.getSlices().iterator().next();
- try (SolrClient leaderClient = getHttpSolrClient(s.getLeader())) {
- assertEquals(numDocs, leaderClient.query(new SolrQuery("*:*")).getResults().getNumFound());
- }
+ Replica sliceLeader = s.getLeader();
+ SolrClient leaderClient = cluster.getSolrClient(sliceLeader);
+ assertEquals(numDocs, leaderClient.query(new SolrQuery("*:*")).getResults().getNumFound());
+
log.info(
"Found {} docs in leader, verifying updates make it to {} pull replicas",
numDocs,
@@ -532,33 +534,32 @@ public class TestPullReplica extends SolrCloudTestCase {
Slice slice = docCollection.getSlice("shard1");
List<String> ids = new ArrayList<>(slice.getReplicas().size());
for (Replica rAdd : slice.getReplicas()) {
- try (SolrClient client = getHttpSolrClient(rAdd.getBaseUrl(), rAdd.getCoreName())) {
- client.add(new SolrInputDocument("id", String.valueOf(id), "foo_s", "bar"));
- }
+ SolrClient client = cluster.getSolrClient(rAdd);
+ client.add(new SolrInputDocument("id", String.valueOf(id), "foo_s", "bar"));
+
SolrDocument docCloudClient =
cluster.getSolrClient().getById(collectionName, String.valueOf(id));
assertEquals("bar", docCloudClient.getFieldValue("foo_s"));
for (Replica rGet : slice.getReplicas()) {
- try (SolrClient client = getHttpSolrClient(rGet.getBaseUrl(), rGet.getCoreName())) {
- SolrDocument doc = client.getById(String.valueOf(id));
- assertEquals("bar", doc.getFieldValue("foo_s"));
- }
+ SolrClient getClient = cluster.getSolrClient(rGet);
+ SolrDocument doc = getClient.getById(String.valueOf(id));
+ assertEquals("bar", doc.getFieldValue("foo_s"));
}
ids.add(String.valueOf(id));
id++;
}
SolrDocumentList previousAllIdsResult = null;
for (Replica rAdd : slice.getReplicas()) {
- try (SolrClient client = getHttpSolrClient(rAdd.getBaseUrl(), rAdd.getCoreName())) {
- SolrDocumentList allIdsResult = client.getById(ids);
- if (previousAllIdsResult != null) {
- assertTrue(compareSolrDocumentList(previousAllIdsResult, allIdsResult));
- } else {
- // set the first response here
- previousAllIdsResult = allIdsResult;
- assertEquals("Unexpected number of documents", ids.size(), allIdsResult.getNumFound());
- }
+ SolrClient client = cluster.getSolrClient(rAdd);
+ SolrDocumentList allIdsResult = client.getById(ids);
+ if (previousAllIdsResult != null) {
+ assertTrue(compareSolrDocumentList(previousAllIdsResult, allIdsResult));
+ } else {
+ // set the first response here
+ previousAllIdsResult = allIdsResult;
+ assertEquals("Unexpected number of documents", ids.size(), allIdsResult.getNumFound());
}
+
id++;
}
}
@@ -580,9 +581,9 @@ public class TestPullReplica extends SolrCloudTestCase {
cluster.getSolrClient().add(collectionName, new SolrInputDocument("id", "1", "foo", "bar"));
cluster.getSolrClient().commit(collectionName);
Slice s = docCollection.getSlices().iterator().next();
- try (SolrClient leaderClient = getHttpSolrClient(s.getLeader())) {
- assertEquals(1, leaderClient.query(new SolrQuery("*:*")).getResults().getNumFound());
- }
+ Replica sliceLeader = s.getLeader();
+ SolrClient leaderClient = cluster.getSolrClient(sliceLeader);
+ assertEquals(1, leaderClient.query(new SolrQuery("*:*")).getResults().getNumFound());
waitForNumDocsInAllReplicas(1, getReplicas(docCollection, EnumSet.of(Replica.Type.PULL)));
@@ -637,7 +638,11 @@ public class TestPullReplica extends SolrCloudTestCase {
// Also fails if I send the update to the pull replica explicitly
try (SolrClient pullReplicaClient =
- getHttpSolrClient(getReplicas(docCollection, EnumSet.of(Replica.Type.PULL)).get(0))) {
+ new HttpJettySolrClient.Builder(
+ getReplicas(docCollection, EnumSet.of(Replica.Type.PULL)).get(0).getBaseUrl())
+ .withDefaultCollection(
+ getReplicas(docCollection, EnumSet.of(Replica.Type.PULL)).get(0).getCoreName())
+ .build()) {
expectThrows(
SolrException.class,
() ->
@@ -685,10 +690,11 @@ public class TestPullReplica extends SolrCloudTestCase {
// add docs agin
cluster.getSolrClient().add(collectionName, new SolrInputDocument("id", "2", "foo", "zoo"));
s = docCollection.getSlices().iterator().next();
- try (SolrClient leaderClient = getHttpSolrClient(s.getLeader())) {
- leaderClient.commit();
- assertEquals(1, leaderClient.query(new SolrQuery("*:*")).getResults().getNumFound());
- }
+ sliceLeader = s.getLeader();
+ leaderClient = cluster.getSolrClient(sliceLeader);
+ leaderClient.commit();
+ assertEquals(1, leaderClient.query(new SolrQuery("*:*")).getResults().getNumFound());
+
waitForNumDocsInAllReplicas(
1, getReplicas(docCollection, EnumSet.of(Replica.Type.PULL)), "id:2", null, null);
waitForNumDocsInAllReplicas(1, getReplicas(docCollection, EnumSet.of(Replica.Type.PULL)));
@@ -889,32 +895,31 @@ public class TestPullReplica extends SolrCloudTestCase {
TimeOut t = new TimeOut(REPLICATION_TIMEOUT_SECS, TimeUnit.SECONDS, TimeSource.NANO_TIME);
for (Replica r : replicas) {
String replicaUrl = r.getCoreUrl();
- try (SolrClient replicaClient = getHttpSolrClient(r)) {
- while (true) {
- QueryRequest req = new QueryRequest(new SolrQuery(query));
- if (user != null && pass != null) {
- req.setBasicAuthCredentials(user, pass);
- }
- try {
- long numFound = req.process(replicaClient).getResults().getNumFound();
- assertEquals(
- "Replica "
- + r.getName()
- + " ("
- + replicaUrl
- + ") not up to date after "
- + REPLICATION_TIMEOUT_SECS
- + " seconds",
- numDocs,
- numFound);
- log.info("Replica {} ({}) has all {} docs", r.name, replicaUrl, numDocs);
- break;
- } catch (AssertionError e) {
- if (t.hasTimedOut()) {
- throw e;
- } else {
- Thread.sleep(200);
- }
+ SolrClient replicaClient = cluster.getSolrClient(r);
+ while (true) {
+ QueryRequest req = new QueryRequest(new SolrQuery(query));
+ if (user != null && pass != null) {
+ req.setBasicAuthCredentials(user, pass);
+ }
+ try {
+ long numFound = req.process(replicaClient).getResults().getNumFound();
+ assertEquals(
+ "Replica "
+ + r.getName()
+ + " ("
+ + replicaUrl
+ + ") not up to date after "
+ + REPLICATION_TIMEOUT_SECS
+ + " seconds",
+ numDocs,
+ numFound);
+ log.info("Replica {} ({}) has all {} docs", r.name, replicaUrl, numDocs);
+ break;
+ } catch (AssertionError e) {
+ if (t.hasTimedOut()) {
+ throw e;
+ } else {
+ Thread.sleep(200);
}
}
}
diff --git a/solr/core/src/test/org/apache/solr/cloud/TestPullReplicaErrorHandling.java b/solr/core/src/test/org/apache/solr/cloud/TestPullReplicaErrorHandling.java
index c4c4047487c..5797e0d3020 100644
--- a/solr/core/src/test/org/apache/solr/cloud/TestPullReplicaErrorHandling.java
+++ b/solr/core/src/test/org/apache/solr/cloud/TestPullReplicaErrorHandling.java
@@ -29,6 +29,7 @@ import java.util.concurrent.TimeUnit;
import org.apache.solr.SolrTestCaseJ4.SuppressSSL;
import org.apache.solr.client.solrj.SolrClient;
import org.apache.solr.client.solrj.SolrServerException;
+import org.apache.solr.client.solrj.jetty.HttpJettySolrClient;
import org.apache.solr.client.solrj.request.CollectionAdminRequest;
import org.apache.solr.client.solrj.request.SolrQuery;
import org.apache.solr.common.SolrException;
@@ -140,9 +141,8 @@ public class TestPullReplicaErrorHandling extends SolrCloudTestCase {
proxy.close();
for (int i = 1; i <= 10; i++) {
addDocs(10 + i);
- try (SolrClient leaderClient = getHttpSolrClient(s.getLeader())) {
- assertNumDocs(10 + i, leaderClient);
- }
+ Replica leader = s.getLeader();
+ assertNumDocs(10 + i, cluster.getSolrClient(leader));
}
SolrServerException e =
@@ -150,7 +150,11 @@ public class TestPullReplicaErrorHandling extends SolrCloudTestCase {
SolrServerException.class,
() -> {
try (SolrClient pullReplicaClient =
- getHttpSolrClient(s.getReplicas(EnumSet.of(Replica.Type.PULL)).get(0))) {
+ new HttpJettySolrClient.Builder(
+ s.getReplicas(EnumSet.of(Replica.Type.PULL)).get(0).getBaseUrl())
+ .withDefaultCollection(
+ s.getReplicas(EnumSet.of(Replica.Type.PULL)).get(0).getCoreName())
+ .build()) {
pullReplicaClient.query(new SolrQuery("*:*")).getResults().getNumFound();
}
});
@@ -174,10 +178,7 @@ public class TestPullReplicaErrorHandling extends SolrCloudTestCase {
proxy.reopen();
}
- try (SolrClient pullReplicaClient =
- getHttpSolrClient(s.getReplicas(EnumSet.of(Replica.Type.PULL)).get(0))) {
- assertNumDocs(20, pullReplicaClient);
- }
+ assertNumDocs(20, cluster.getSolrClient(s.getReplicas(EnumSet.of(Replica.Type.PULL)).get(0)));
}
public void testCantConnectToLeader() throws Exception {
@@ -191,16 +192,10 @@ public class TestPullReplicaErrorHandling extends SolrCloudTestCase {
SocketProxy proxy = getProxyForReplica(s.getLeader());
try {
// wait for replication
- try (SolrClient pullReplicaClient =
- getHttpSolrClient(s.getReplicas(EnumSet.of(Replica.Type.PULL)).get(0))) {
- assertNumDocs(10, pullReplicaClient);
- }
+ assertNumDocs(10, cluster.getSolrClient(s.getReplicas(EnumSet.of(Replica.Type.PULL)).get(0)));
proxy.close();
expectThrows(SolrException.class, () -> addDocs(1));
- try (SolrClient pullReplicaClient =
- getHttpSolrClient(s.getReplicas(EnumSet.of(Replica.Type.PULL)).get(0))) {
- assertNumDocs(10, pullReplicaClient);
- }
+ assertNumDocs(10, cluster.getSolrClient(s.getReplicas(EnumSet.of(Replica.Type.PULL)).get(0)));
assertNumDocs(10, cluster.getSolrClient(collectionName));
} finally {
log.info("Opening leader node");
@@ -227,10 +222,7 @@ public class TestPullReplicaErrorHandling extends SolrCloudTestCase {
addDocs(10);
DocCollection docCollection = assertNumberOfReplicas(numShards, 0, numShards, false, true);
Slice s = docCollection.getSlices().iterator().next();
- try (SolrClient pullReplicaClient =
- getHttpSolrClient(s.getReplicas(EnumSet.of(Replica.Type.PULL)).get(0))) {
- assertNumDocs(10, pullReplicaClient);
- }
+ assertNumDocs(10, cluster.getSolrClient(s.getReplicas(EnumSet.of(Replica.Type.PULL)).get(0)));
addDocs(20);
JettySolrRunner jetty = getJettyForReplica(s.getReplicas(EnumSet.of(Replica.Type.PULL)).get(0));
cluster.expireZkSession(jetty);
@@ -238,10 +230,7 @@ public class TestPullReplicaErrorHandling extends SolrCloudTestCase {
waitForState("Expecting node to be disconnected", collectionName, activeReplicaCount(1, 0, 0));
addDocs(40);
waitForState("Expecting node to be reconnected", collectionName, activeReplicaCount(1, 0, 1));
- try (SolrClient pullReplicaClient =
- getHttpSolrClient(s.getReplicas(EnumSet.of(Replica.Type.PULL)).get(0))) {
- assertNumDocs(40, pullReplicaClient);
- }
+ assertNumDocs(40, cluster.getSolrClient(s.getReplicas(EnumSet.of(Replica.Type.PULL)).get(0)));
}
public void testCloseHooksDeletedOnReconnect() throws Exception {
diff --git a/solr/core/src/test/org/apache/solr/cloud/TestPullReplicaWithAuth.java b/solr/core/src/test/org/apache/solr/cloud/TestPullReplicaWithAuth.java
index 4439f8fbf35..8d3fea023d3 100644
--- a/solr/core/src/test/org/apache/solr/cloud/TestPullReplicaWithAuth.java
+++ b/solr/core/src/test/org/apache/solr/cloud/TestPullReplicaWithAuth.java
@@ -93,11 +93,11 @@ public class TestPullReplicaWithAuth extends SolrCloudTestCase {
ureq.commit(solrClient, collectionName);
Slice s = docCollection.getSlices().iterator().next();
- try (SolrClient leaderClient = getHttpSolrClient(s.getLeader())) {
- assertEquals(
- numDocs,
- queryWithBasicAuth(leaderClient, new SolrQuery("*:*")).getResults().getNumFound());
- }
+ Replica leader = s.getLeader();
+ SolrClient leaderClient = cluster.getSolrClient(leader);
+ assertEquals(
+ numDocs,
+ queryWithBasicAuth(leaderClient, new SolrQuery("*:*")).getResults().getNumFound());
List<Replica> pullReplicas = s.getReplicas(EnumSet.of(Replica.Type.PULL));
waitForNumDocsInAllReplicas(
diff --git a/solr/core/src/test/org/apache/solr/cloud/TestQueryingOnDownCollection.java b/solr/core/src/test/org/apache/solr/cloud/TestQueryingOnDownCollection.java
index 2d9d9749221..0fa50874d0d 100644
--- a/solr/core/src/test/org/apache/solr/cloud/TestQueryingOnDownCollection.java
+++ b/solr/core/src/test/org/apache/solr/cloud/TestQueryingOnDownCollection.java
@@ -19,7 +19,6 @@ package org.apache.solr.cloud;
import java.util.Map;
import org.apache.solr.client.solrj.SolrClient;
import org.apache.solr.client.solrj.SolrRequest;
-import org.apache.solr.client.solrj.jetty.HttpJettySolrClient;
import org.apache.solr.client.solrj.request.CollectionAdminRequest;
import org.apache.solr.client.solrj.request.QueryRequest;
import org.apache.solr.client.solrj.request.SolrQuery;
@@ -82,41 +81,33 @@ public class TestQueryingOnDownCollection extends SolrCloudTestCase {
new QueryRequest(new SolrQuery("*:*").setRows(0))
.setBasicAuthCredentials(USERNAME, PASSWORD);
- try (SolrClient client = cluster.getJettySolrRunner(0).newClient()) {
- // Without the SOLR-13793 fix, this causes requests to "down collection" to pile up (until the
- // nodes run out of serviceable threads, and they crash, even for other collections hosted on
- // the
- // nodes).
- SolrException error =
- expectThrows(
- SolrException.class,
- "Request should fail after trying all replica nodes once",
- () -> client.request(req, COLLECTION_NAME));
-
- assertEquals(error.code(), SolrException.ErrorCode.INVALID_STATE.code);
- assertTrue(
- error
- .getMessage()
- .contains("No active replicas found for collection: " + COLLECTION_NAME));
- }
+ SolrClient client = cluster.getJettySolrRunner(0).getSolrClient();
+ // Without the SOLR-13793 fix, this causes requests to "down collection" to pile up (until the
+ // nodes run out of serviceable threads, and they crash, even for other collections hosted on
+ // the
+ // nodes).
+ SolrException error =
+ expectThrows(
+ SolrException.class,
+ "Request should fail after trying all replica nodes once",
+ () -> client.request(req, COLLECTION_NAME));
+
+ assertEquals(error.code(), SolrException.ErrorCode.INVALID_STATE.code);
+ assertTrue(
+ error.getMessage().contains("No active replicas found for collection: " + COLLECTION_NAME));
// run same set of tests on v2 client which uses V2HttpCall
- try (SolrClient v2Client =
- new HttpJettySolrClient.Builder(cluster.getJettySolrRunner(0).getBaseUrl().toString())
- .build()) {
-
- SolrException error =
- expectThrows(
- SolrException.class,
- "Request should fail after trying all replica nodes once",
- () -> v2Client.request(req, COLLECTION_NAME));
-
- assertEquals(error.code(), SolrException.ErrorCode.INVALID_STATE.code);
- assertTrue(
- error
- .getMessage()
- .contains("No active replicas found for collection: " + COLLECTION_NAME));
- }
+ SolrClient v2Client = cluster.getJettySolrRunner(0).getSolrClient();
+
+ error =
+ expectThrows(
+ SolrException.class,
+ "Request should fail after trying all replica nodes once",
+ () -> v2Client.request(req, COLLECTION_NAME));
+
+ assertEquals(error.code(), SolrException.ErrorCode.INVALID_STATE.code);
+ assertTrue(
+ error.getMessage().contains("No active replicas found for collection: " + COLLECTION_NAME));
}
@SuppressWarnings({"unchecked"})
diff --git a/solr/core/src/test/org/apache/solr/cloud/TestStressCloudBlindAtomicUpdates.java b/solr/core/src/test/org/apache/solr/cloud/TestStressCloudBlindAtomicUpdates.java
index 8abccaf7fbd..d9297f2d206 100644
--- a/solr/core/src/test/org/apache/solr/cloud/TestStressCloudBlindAtomicUpdates.java
+++ b/solr/core/src/test/org/apache/solr/cloud/TestStressCloudBlindAtomicUpdates.java
@@ -17,7 +17,6 @@
package org.apache.solr.cloud;
import java.lang.invoke.MethodHandles;
-import java.net.URL;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Arrays;
@@ -33,6 +32,7 @@ import org.apache.lucene.tests.util.TestUtil;
import org.apache.solr.SolrTestCaseJ4.SuppressSSL;
import org.apache.solr.client.solrj.SolrClient;
import org.apache.solr.client.solrj.impl.CloudSolrClient;
+import org.apache.solr.client.solrj.impl.CollectionScopedSolrClient;
import org.apache.solr.client.solrj.request.CollectionAdminRequest;
import org.apache.solr.client.solrj.request.UpdateRequest;
import org.apache.solr.client.solrj.request.schema.SchemaRequest.Field;
@@ -139,9 +139,7 @@ public class TestStressCloudBlindAtomicUpdates extends SolrCloudTestCase {
CLIENTS.clear();
for (JettySolrRunner jetty : cluster.getJettySolrRunners()) {
assertNotNull("Cluster contains null jetty?", jetty);
- final URL baseUrl = jetty.getBaseUrl();
- assertNotNull("Jetty has null baseUrl: " + jetty, baseUrl);
- CLIENTS.add(getHttpSolrClient(baseUrl.toString(), COLLECTION_NAME));
+ CLIENTS.add(new CollectionScopedSolrClient(jetty.getSolrClient(), COLLECTION_NAME));
}
// sanity check no one broke the assumptions we make about our schema
@@ -166,12 +164,7 @@ public class TestStressCloudBlindAtomicUpdates extends SolrCloudTestCase {
IOUtils.closeQuietly(COLLECTION_CLIENT);
COLLECTION_CLIENT = null;
}
- for (SolrClient client : CLIENTS) {
- if (null == client) {
- log.error("CLIENTS contains a null SolrClient???");
- }
- IOUtils.closeQuietly(client);
- }
+ // the jettys own these clients
CLIENTS.clear();
}
diff --git a/solr/core/src/test/org/apache/solr/cloud/TestTlogReplayVsRecovery.java b/solr/core/src/test/org/apache/solr/cloud/TestTlogReplayVsRecovery.java
index af90ea36ee3..b181eaa7cb3 100644
--- a/solr/core/src/test/org/apache/solr/cloud/TestTlogReplayVsRecovery.java
+++ b/solr/core/src/test/org/apache/solr/cloud/TestTlogReplayVsRecovery.java
@@ -243,11 +243,10 @@ public class TestTlogReplayVsRecovery extends SolrCloudTestCase {
}
// For simplicity, we always add out docs directly to NODE0
// (where the leader should be) and bypass the proxy...
- try (SolrClient client = getHttpSolrClient(NODE0.getBaseUrl().toString())) {
- assertEquals(0, client.add(COLLECTION, docs).getStatus());
- if (commit) {
- assertEquals(0, client.commit(COLLECTION).getStatus());
- }
+ SolrClient client = NODE0.getSolrClient();
+ assertEquals(0, client.add(COLLECTION, docs).getStatus());
+ if (commit) {
+ assertEquals(0, client.commit(COLLECTION).getStatus());
}
}
@@ -256,13 +255,12 @@ public class TestTlogReplayVsRecovery extends SolrCloudTestCase {
* (inclusive) can be found on both the leader and the replica
*/
private void assertDocsExistInBothReplicas(int firstDocId, int lastDocId) throws Exception {
- try (SolrClient leaderSolr = getHttpSolrClient(NODE0.getBaseUrl().toString());
- SolrClient replicaSolr = getHttpSolrClient(NODE1.getBaseUrl().toString())) {
- for (int d = firstDocId; d <= lastDocId; d++) {
- String docId = String.valueOf(d);
- assertDocExists("leader", leaderSolr, docId);
- assertDocExists("replica", replicaSolr, docId);
- }
+ SolrClient leaderSolr = NODE0.getSolrClient();
+ SolrClient replicaSolr = NODE1.getSolrClient();
+ for (int d = firstDocId; d <= lastDocId; d++) {
+ String docId = String.valueOf(d);
+ assertDocExists("leader", leaderSolr, docId);
+ assertDocExists("replica", replicaSolr, docId);
}
}
diff --git a/solr/core/src/test/org/apache/solr/cloud/TestTlogReplica.java b/solr/core/src/test/org/apache/solr/cloud/TestTlogReplica.java
index 855a6562ce4..9a1e9f7524c 100644
--- a/solr/core/src/test/org/apache/solr/cloud/TestTlogReplica.java
+++ b/solr/core/src/test/org/apache/solr/cloud/TestTlogReplica.java
@@ -257,50 +257,49 @@ public class TestTlogReplica extends SolrCloudTestCase {
cluster.getSolrClient().commit(collectionName);
Slice s = docCollection.getSlices().iterator().next();
- try (SolrClient leaderClient = getHttpSolrClient(s.getLeader())) {
- assertEquals(1, leaderClient.query(new SolrQuery("*:*")).getResults().getNumFound());
- }
+ Replica sliceLeader = s.getLeader();
+ SolrClient leaderClient = cluster.getSolrClient(sliceLeader);
+ assertEquals(1, leaderClient.query(new SolrQuery("*:*")).getResults().getNumFound());
TimeOut t = new TimeOut(REPLICATION_TIMEOUT_SECS, TimeUnit.SECONDS, TimeSource.NANO_TIME);
for (Replica r : s.getReplicas(EnumSet.of(Replica.Type.TLOG))) {
// TODO: assert replication < REPLICATION_TIMEOUT_SECS
- try (SolrClient tlogReplicaClient = getHttpSolrClient(r)) {
- while (true) {
- try {
+ SolrClient tlogReplicaClient = cluster.getSolrClient(r);
+ while (true) {
+ try {
+ assertEquals(
+ "Replica " + r.getName() + " not up to date after 10 seconds",
+ 1,
+ tlogReplicaClient.query(new SolrQuery("*:*")).getResults().getNumFound());
+ JettySolrRunner jetty =
+ cluster.getJettySolrRunners().stream()
+ .filter(j -> j.getBaseUrl().toString().equals(r.getBaseUrl()))
+ .findFirst()
+ .orElse(null);
+ assertNotNull("Could not find jetty for replica " + r, jetty);
+
+ try (SolrCore core = jetty.getCoreContainer().getCore(r.getCoreName())) {
+ var cumulativeAddsDatapoint =
+ SolrMetricTestUtils.getGaugeDatapoint(
+ core,
+ "solr_core_update_cumulative_ops",
+ SolrMetricTestUtils.newCloudLabelsBuilder(core)
+ .label("category", "UPDATE")
+ .label("ops", "adds")
+ .build());
+ assertNotNull("Could not find cumulative adds metric", cumulativeAddsDatapoint);
assertEquals(
- "Replica " + r.getName() + " not up to date after 10 seconds",
- 1,
- tlogReplicaClient.query(new SolrQuery("*:*")).getResults().getNumFound());
- JettySolrRunner jetty =
- cluster.getJettySolrRunners().stream()
- .filter(j -> j.getBaseUrl().toString().equals(r.getBaseUrl()))
- .findFirst()
- .orElse(null);
- assertNotNull("Could not find jetty for replica " + r, jetty);
-
- try (SolrCore core = jetty.getCoreContainer().getCore(r.getCoreName())) {
- var cumulativeAddsDatapoint =
- SolrMetricTestUtils.getGaugeDatapoint(
- core,
- "solr_core_update_cumulative_ops",
- SolrMetricTestUtils.newCloudLabelsBuilder(core)
- .label("category", "UPDATE")
- .label("ops", "adds")
- .build());
- assertNotNull("Could not find cumulative adds metric", cumulativeAddsDatapoint);
- assertEquals(
- "Append replicas should receive all updates. Replica: " + r,
- 1.0,
- cumulativeAddsDatapoint.getValue(),
- 0.0);
- }
- break;
- } catch (AssertionError e) {
- if (t.hasTimedOut()) {
- throw e;
- } else {
- Thread.sleep(100);
- }
+ "Append replicas should receive all updates. Replica: " + r,
+ 1.0,
+ cumulativeAddsDatapoint.getValue(),
+ 0.0);
+ }
+ break;
+ } catch (AssertionError e) {
+ if (t.hasTimedOut()) {
+ throw e;
+ } else {
+ Thread.sleep(100);
}
}
}
@@ -443,9 +442,9 @@ public class TestTlogReplica extends SolrCloudTestCase {
cluster.getSolrClient().add(collectionName, new SolrInputDocument("id", "1", "foo", "bar"));
cluster.getSolrClient().commit(collectionName);
Slice s = docCollection.getSlices().iterator().next();
- try (SolrClient leaderClient = getHttpSolrClient(s.getLeader())) {
- assertEquals(1, leaderClient.query(new SolrQuery("*:*")).getResults().getNumFound());
- }
+ Replica sliceLeader = s.getLeader();
+ SolrClient leaderClient = cluster.getSolrClient(sliceLeader);
+ assertEquals(1, leaderClient.query(new SolrQuery("*:*")).getResults().getNumFound());
waitForNumDocsInAllReplicas(
1, getReplicas(docCollection, EnumSet.of(Replica.Type.TLOG)), REPLICATION_TIMEOUT_SECS);
@@ -895,10 +894,9 @@ public class TestTlogReplica extends SolrCloudTestCase {
updates.add(simulatedDBQ("inplace_updatable_int:5", 3L));
updates.add(simulatedUpdateRequest(1L, "id", 1, "inplace_updatable_int", 6, "_version_", 2L));
for (JettySolrRunner solrRunner : getSolrRunner(false)) {
- try (SolrClient client = solrRunner.newClient()) {
- for (UpdateRequest up : updates) {
- up.process(client, collectionName);
- }
+ SolrClient client = solrRunner.getSolrClient();
+ for (UpdateRequest up : updates) {
+ up.process(client, collectionName);
}
}
JettySolrRunner oldLeaderJetty = getSolrRunner(true).get(0);
@@ -1000,20 +998,19 @@ public class TestTlogReplica extends SolrCloudTestCase {
if (!r.isActive(cluster.getSolrClient().getClusterState().getLiveNodes())) {
continue;
}
- try (SolrClient replicaClient = getHttpSolrClient(r)) {
- while (true) {
- try {
- assertEquals(
- "Replica " + r.getName() + " not up to date after " + timeout + " seconds",
- numDocs,
- replicaClient.query(new SolrQuery(query)).getResults().getNumFound());
- break;
- } catch (AssertionError e) {
- if (t.hasTimedOut()) {
- throw e;
- } else {
- Thread.sleep(100);
- }
+ SolrClient replicaClient = cluster.getSolrClient(r);
+ while (true) {
+ try {
+ assertEquals(
+ "Replica " + r.getName() + " not up to date after " + timeout + " seconds",
+ numDocs,
+ replicaClient.query(new SolrQuery(query)).getResults().getNumFound());
+ break;
+ } catch (AssertionError e) {
+ if (t.hasTimedOut()) {
+ throw e;
+ } else {
+ Thread.sleep(100);
}
}
}
@@ -1150,17 +1147,16 @@ public class TestTlogReplica extends SolrCloudTestCase {
private void checkRTG(int from, int to, List<JettySolrRunner> solrRunners) throws Exception {
for (JettySolrRunner solrRunner : solrRunners) {
- try (SolrClient client = solrRunner.newClient()) {
- for (int i = from; i <= to; i++) {
- SolrQuery query = new SolrQuery();
- query.set("distrib", false);
- query.setRequestHandler("/get");
- query.set("id", i);
- QueryResponse res = client.query(collectionName, query);
- assertNotNull(
- "Can not find doc " + i + " in " + solrRunner.getBaseUrl(),
- res.getResponse().get("doc"));
- }
+ SolrClient client = solrRunner.getSolrClient();
+ for (int i = from; i <= to; i++) {
+ SolrQuery query = new SolrQuery();
+ query.set("distrib", false);
+ query.setRequestHandler("/get");
+ query.set("id", i);
+ QueryResponse res = client.query(collectionName, query);
+ assertNotNull(
+ "Can not find doc " + i + " in " + solrRunner.getBaseUrl(),
+ res.getResponse().get("doc"));
}
}
}
diff --git a/solr/core/src/test/org/apache/solr/cloud/TestTolerantUpdateProcessorCloud.java b/solr/core/src/test/org/apache/solr/cloud/TestTolerantUpdateProcessorCloud.java
index dc0a4435949..107f7b273b3 100644
--- a/solr/core/src/test/org/apache/solr/cloud/TestTolerantUpdateProcessorCloud.java
+++ b/solr/core/src/test/org/apache/solr/cloud/TestTolerantUpdateProcessorCloud.java
@@ -27,6 +27,7 @@ import java.util.List;
import java.util.Set;
import org.apache.solr.client.solrj.SolrClient;
import org.apache.solr.client.solrj.impl.CloudSolrClient;
+import org.apache.solr.client.solrj.impl.CollectionScopedSolrClient;
import org.apache.solr.client.solrj.request.CollectionAdminRequest;
import org.apache.solr.client.solrj.request.UpdateRequest;
import org.apache.solr.client.solrj.response.UpdateResponse;
@@ -145,17 +146,27 @@ public class TestTolerantUpdateProcessorCloud extends SolrCloudTestCase {
assertNotNull("could not find URL for " + shardName + " replica", passiveUrl);
if (shardName.equals("shard1")) {
- S_ONE_LEADER_CLIENT = getHttpSolrClient(leaderUrl, COLLECTION_NAME);
- S_ONE_NON_LEADER_CLIENT = getHttpSolrClient(passiveUrl, COLLECTION_NAME);
+ S_ONE_LEADER_CLIENT =
+ new CollectionScopedSolrClient(
+ cluster.getJetty(leaderUrl).getSolrClient(), COLLECTION_NAME);
+ S_ONE_NON_LEADER_CLIENT =
+ new CollectionScopedSolrClient(
+ cluster.getJetty(passiveUrl).getSolrClient(), COLLECTION_NAME);
} else if (shardName.equals("shard2")) {
- S_TWO_LEADER_CLIENT = getHttpSolrClient(leaderUrl, COLLECTION_NAME);
- S_TWO_NON_LEADER_CLIENT = getHttpSolrClient(passiveUrl, COLLECTION_NAME);
+ S_TWO_LEADER_CLIENT =
+ new CollectionScopedSolrClient(
+ cluster.getJetty(leaderUrl).getSolrClient(), COLLECTION_NAME);
+ S_TWO_NON_LEADER_CLIENT =
+ new CollectionScopedSolrClient(
+ cluster.getJetty(passiveUrl).getSolrClient(), COLLECTION_NAME);
} else {
fail("unexpected shard: " + shardName);
}
}
assertEquals("Should be exactly one server left (not hosting either shard)", 1, urlMap.size());
- NO_COLLECTION_CLIENT = getHttpSolrClient(urlMap.values().iterator().next(), COLLECTION_NAME);
+ NO_COLLECTION_CLIENT =
+ new CollectionScopedSolrClient(
+ cluster.getJetty(urlMap.values().iterator().next()).getSolrClient(), COLLECTION_NAME);
assertNotNull(S_ONE_LEADER_CLIENT);
assertNotNull(S_TWO_LEADER_CLIENT);
@@ -204,15 +215,10 @@ public class TestTolerantUpdateProcessorCloud extends SolrCloudTestCase {
@AfterClass
public static void afterClass() throws IOException {
- close(S_ONE_LEADER_CLIENT);
S_ONE_LEADER_CLIENT = null;
- close(S_TWO_LEADER_CLIENT);
S_TWO_LEADER_CLIENT = null;
- close(S_ONE_NON_LEADER_CLIENT);
S_ONE_NON_LEADER_CLIENT = null;
- close(S_TWO_NON_LEADER_CLIENT);
S_TWO_NON_LEADER_CLIENT = null;
- close(NO_COLLECTION_CLIENT);
NO_COLLECTION_CLIENT = null;
close(COLLECTION_CLIENT);
COLLECTION_CLIENT = null;
diff --git a/solr/core/src/test/org/apache/solr/cloud/TestTolerantUpdateProcessorRandomCloud.java b/solr/core/src/test/org/apache/solr/cloud/TestTolerantUpdateProcessorRandomCloud.java
index a39197320cf..c96a633577b 100644
--- a/solr/core/src/test/org/apache/solr/cloud/TestTolerantUpdateProcessorRandomCloud.java
+++ b/solr/core/src/test/org/apache/solr/cloud/TestTolerantUpdateProcessorRandomCloud.java
@@ -27,7 +27,6 @@ import static org.apache.solr.common.params.CursorMarkParams.CURSOR_MARK_START;
import java.io.IOException;
import java.lang.invoke.MethodHandles;
-import java.net.URL;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.BitSet;
@@ -39,6 +38,7 @@ import org.apache.lucene.tests.util.TestUtil;
import org.apache.solr.SolrTestCaseJ4.SuppressSSL;
import org.apache.solr.client.solrj.SolrClient;
import org.apache.solr.client.solrj.impl.CloudSolrClient;
+import org.apache.solr.client.solrj.impl.CollectionScopedSolrClient;
import org.apache.solr.client.solrj.request.CollectionAdminRequest;
import org.apache.solr.client.solrj.request.UpdateRequest;
import org.apache.solr.client.solrj.response.QueryResponse;
@@ -114,8 +114,7 @@ public class TestTolerantUpdateProcessorRandomCloud extends SolrCloudTestCase {
NODE_CLIENTS = new ArrayList<SolrClient>(numServers);
for (JettySolrRunner jetty : cluster.getJettySolrRunners()) {
- URL jettyURL = jetty.getBaseUrl();
- NODE_CLIENTS.add(getHttpSolrClient(jettyURL.toString(), COLLECTION_NAME));
+ NODE_CLIENTS.add(new CollectionScopedSolrClient(jetty.getSolrClient(), COLLECTION_NAME));
}
assertEquals(numServers, NODE_CLIENTS.size());
}
@@ -133,11 +132,7 @@ public class TestTolerantUpdateProcessorRandomCloud extends SolrCloudTestCase {
@AfterClass
public static void afterClass() throws IOException {
- if (NODE_CLIENTS != null) {
- for (SolrClient client : NODE_CLIENTS) {
- client.close();
- }
- }
+ // the jettys own these clients
NODE_CLIENTS = null;
if (COLLECTION_CLIENT != null) {
COLLECTION_CLIENT.close();
diff --git a/solr/core/src/test/org/apache/solr/cloud/UnloadDistributedZkTest.java b/solr/core/src/test/org/apache/solr/cloud/UnloadDistributedZkTest.java
index 93781dbbd1e..c79fa27b77a 100644
--- a/solr/core/src/test/org/apache/solr/cloud/UnloadDistributedZkTest.java
+++ b/solr/core/src/test/org/apache/solr/cloud/UnloadDistributedZkTest.java
@@ -155,29 +155,22 @@ public class UnloadDistributedZkTest extends AbstractFullDistribZkTestBase {
final String unloadCmdCoreName1 = (unloadInOrder ? coreName1 : coreName2);
final String unloadCmdCoreName2 = (unloadInOrder ? coreName2 : coreName1);
- try (SolrClient adminClient = getHttpSolrClient(buildUrl(jettys.get(0).getLocalPort()))) {
- // now unload one of the two
- Unload unloadCmd = new Unload(false);
- unloadCmd.setCoreName(unloadCmdCoreName1);
- adminClient.request(unloadCmd);
-
- // there should still be two shards (as of SOLR-5209)
- checkCoreNamePresenceAndSliceCount(
- collection,
- unloadCmdCoreName1,
- false /* shouldBePresent */,
- numShards /* expectedSliceCount */);
-
- // now unload one of the other
- unloadCmd = new Unload(false);
- unloadCmd.setCoreName(unloadCmdCoreName2);
- adminClient.request(unloadCmd);
- checkCoreNamePresenceAndSliceCount(
- collection,
- unloadCmdCoreName2,
- false /* shouldBePresent */,
- numShards /* expectedSliceCount */);
- }
+ SolrClient adminClient = jettys.get(0).getSolrClient();
+ // now unload one of the two
+ Unload unloadCmd = new Unload(false);
+ unloadCmd.setCoreName(unloadCmdCoreName1);
+ adminClient.request(unloadCmd);
+
+ // there should still be two shards (as of SOLR-5209)
+ checkCoreNamePresenceAndSliceCount(
+ collection, unloadCmdCoreName1, false /* shouldBePresent */, numShards);
+
+ // now unload one of the other
+ unloadCmd = new Unload(false);
+ unloadCmd.setCoreName(unloadCmdCoreName2);
+ adminClient.request(unloadCmd);
+ checkCoreNamePresenceAndSliceCount(
+ collection, unloadCmdCoreName2, false /* shouldBePresent */, numShards);
// printLayout();
// the collection should still be present (as of SOLR-5209 replica removal does not cascade to
@@ -391,56 +384,55 @@ public class UnloadDistributedZkTest extends AbstractFullDistribZkTestBase {
private void testUnloadLotsOfCores() throws Exception {
JettySolrRunner jetty = jettys.get(0);
int shards = TEST_NIGHTLY ? 2 : 1;
- try (final SolrClient adminClient = jetty.newClient(15000, 60000)) {
- int numReplicas = atLeast(3);
- ThreadPoolExecutor executor =
- new ExecutorUtil.MDCAwareThreadPoolExecutor(
- 0,
- Integer.MAX_VALUE,
- 5,
- TimeUnit.SECONDS,
- new SynchronousQueue<>(),
- new SolrNamedThreadFactory("testExecutor"));
- try {
- // create the cores
- BasicDistributedZkTest.createCollectionInOneInstance(
- adminClient, jetty.getNodeName(), executor, "multiunload", shards, numReplicas);
- } finally {
- ExecutorUtil.shutdownAndAwaitTermination(executor);
- }
+ final SolrClient adminClient = jetty.getSolrClient();
+ int numReplicas = atLeast(3);
+ ThreadPoolExecutor executor =
+ new ExecutorUtil.MDCAwareThreadPoolExecutor(
+ 0,
+ Integer.MAX_VALUE,
+ 5,
+ TimeUnit.SECONDS,
+ new SynchronousQueue<>(),
+ new SolrNamedThreadFactory("testExecutor"));
+ try {
+ // create the cores
+ BasicDistributedZkTest.createCollectionInOneInstance(
+ adminClient, jetty.getNodeName(), executor, "multiunload", shards, numReplicas);
+ } finally {
+ ExecutorUtil.shutdownAndAwaitTermination(executor);
+ }
- if (TEST_NIGHTLY == false) {
- // with nightly tests, we can try doing the unloads before the creates are done
- // it still works, but takes much longer since we end up waiting for a timeout
- waitForRecoveriesToFinish("multiunload", false);
- }
+ if (TEST_NIGHTLY == false) {
+ // with nightly tests, we can try doing the unloads before the creates are done
+ // it still works, but takes much longer since we end up waiting for a timeout
+ waitForRecoveriesToFinish("multiunload", false);
+ }
- executor =
- new ExecutorUtil.MDCAwareThreadPoolExecutor(
- 0,
- Integer.MAX_VALUE,
- 5,
- TimeUnit.SECONDS,
- new SynchronousQueue<>(),
- new SolrNamedThreadFactory("testExecutor"));
- try {
- for (int j = 0; j < numReplicas; j++) {
- final int freezeJ = j;
- executor.execute(
- () -> {
- Unload unloadCmd = new Unload(true);
- unloadCmd.setCoreName("multiunload" + freezeJ);
- try {
- adminClient.request(unloadCmd);
- } catch (SolrServerException | IOException e) {
- throw new RuntimeException(e);
- }
- });
- Thread.sleep(random().nextInt(50));
- }
- } finally {
- ExecutorUtil.shutdownAndAwaitTermination(executor);
+ executor =
+ new ExecutorUtil.MDCAwareThreadPoolExecutor(
+ 0,
+ Integer.MAX_VALUE,
+ 5,
+ TimeUnit.SECONDS,
+ new SynchronousQueue<>(),
+ new SolrNamedThreadFactory("testExecutor"));
+ try {
+ for (int j = 0; j < numReplicas; j++) {
+ final int freezeJ = j;
+ executor.execute(
+ () -> {
+ Unload unloadCmd = new Unload(true);
+ unloadCmd.setCoreName("multiunload" + freezeJ);
+ try {
+ adminClient.request(unloadCmd);
+ } catch (SolrServerException | IOException e) {
+ throw new RuntimeException(e);
+ }
+ });
+ Thread.sleep(random().nextInt(50));
}
+ } finally {
+ ExecutorUtil.shutdownAndAwaitTermination(executor);
}
}
}
diff --git a/solr/core/src/test/org/apache/solr/cloud/ZkShardTermsRecoveryTest.java b/solr/core/src/test/org/apache/solr/cloud/ZkShardTermsRecoveryTest.java
index 10385f2c54c..cc0f5ca7e6c 100644
--- a/solr/core/src/test/org/apache/solr/cloud/ZkShardTermsRecoveryTest.java
+++ b/solr/core/src/test/org/apache/solr/cloud/ZkShardTermsRecoveryTest.java
@@ -190,12 +190,11 @@ public class ZkShardTermsRecoveryTest extends SolrCloudTestCase {
if (!r.isActive(cluster.getSolrClient().getClusterState().getLiveNodes())) {
continue;
}
- try (SolrClient replicaClient = getHttpSolrClient(r)) {
- assertEquals(
- "Replica " + r.getName() + " not up to date",
- numDocs,
- replicaClient.query(new SolrQuery(query)).getResults().getNumFound());
- }
+ SolrClient replicaClient = cluster.getSolrClient(r);
+ assertEquals(
+ "Replica " + r.getName() + " not up to date",
+ numDocs,
+ replicaClient.query(new SolrQuery(query)).getResults().getNumFound());
}
}
diff --git a/solr/core/src/test/org/apache/solr/cloud/api/collections/ConcurrentDeleteAndCreateCollectionTest.java b/solr/core/src/test/org/apache/solr/cloud/api/collections/ConcurrentDeleteAndCreateCollectionTest.java
index c89f46ccf39..44edb664e3c 100644
--- a/solr/core/src/test/org/apache/solr/cloud/api/collections/ConcurrentDeleteAndCreateCollectionTest.java
+++ b/solr/core/src/test/org/apache/solr/cloud/api/collections/ConcurrentDeleteAndCreateCollectionTest.java
@@ -67,8 +67,7 @@ public class ConcurrentDeleteAndCreateCollectionTest extends SolrTestCaseJ4 {
for (int i = 0; i < threads.length; i++) {
final String collectionName = "collection" + i;
solrCluster.uploadConfigSet(configset("configset-2"), collectionName);
- final String baseUrl = solrCluster.getJettySolrRunners().get(0).getBaseUrl().toString();
- final SolrClient solrClient = getHttpSolrClient(baseUrl);
+ final SolrClient solrClient = solrCluster.getJettySolrRunners().get(0).newSolrClient(null);
threads[i] =
new CreateDeleteSearchCollectionThread(
"create-delete-search-" + i,
@@ -89,13 +88,12 @@ public class ConcurrentDeleteAndCreateCollectionTest extends SolrTestCaseJ4 {
final String configName = "testconfig";
// upload config once, to be used by all collections
solrCluster.uploadConfigSet(configset("configset-2"), configName);
- final String baseUrl = solrCluster.getJettySolrRunners().get(0).getBaseUrl().toString();
final AtomicReference<Exception> failure = new AtomicReference<>();
final int timeToRunSec = 30;
final CreateDeleteCollectionThread[] threads = new CreateDeleteCollectionThread[2];
for (int i = 0; i < threads.length; i++) {
final String collectionName = "collection" + i;
- final SolrClient solrClient = getHttpSolrClient(baseUrl);
+ final SolrClient solrClient = solrCluster.getJettySolrRunners().get(0).newSolrClient(null);
threads[i] =
new CreateDeleteCollectionThread(
"create-delete-" + i, collectionName, configName, timeToRunSec, solrClient, failure);
diff --git a/solr/core/src/test/org/apache/solr/cloud/api/collections/ShardSplitTest.java b/solr/core/src/test/org/apache/solr/cloud/api/collections/ShardSplitTest.java
index 074d0431342..a366a849a42 100644
--- a/solr/core/src/test/org/apache/solr/cloud/api/collections/ShardSplitTest.java
+++ b/solr/core/src/test/org/apache/solr/cloud/api/collections/ShardSplitTest.java
@@ -43,6 +43,7 @@ import org.apache.solr.client.solrj.SolrRequest.METHOD;
import org.apache.solr.client.solrj.SolrRequest.SolrRequestType;
import org.apache.solr.client.solrj.SolrServerException;
import org.apache.solr.client.solrj.impl.CloudSolrClient;
+import org.apache.solr.client.solrj.impl.CollectionScopedSolrClient;
import org.apache.solr.client.solrj.request.CollectionAdminRequest;
import org.apache.solr.client.solrj.request.GenericSolrRequest;
import org.apache.solr.client.solrj.request.SolrQuery;
@@ -966,52 +967,52 @@ public class ShardSplitTest extends BasicDistributedZkTest {
getCommonCloudSolrClient();
String baseUrl = getBaseUrlFromZk(cloudClient.getClusterState(), collectionName);
- try (SolrClient collectionClient = getHttpSolrClient(baseUrl, collectionName)) {
+ SolrClient collectionClient =
+ new CollectionScopedSolrClient(getJetty(baseUrl).getSolrClient(), collectionName);
- ClusterState clusterState = cloudClient.getClusterState();
- final DocRouter router = clusterState.getCollection(collectionName).getRouter();
- Slice shard1 = clusterState.getCollection(collectionName).getSlice(SHARD1);
- DocRouter.Range shard1Range =
- shard1.getRange() != null ? shard1.getRange() : router.fullRange();
- final List<DocRouter.Range> ranges = router.partitionRange(2, shard1Range);
- final int[] docCounts = new int[ranges.size()];
+ ClusterState clusterState = cloudClient.getClusterState();
+ final DocRouter router = clusterState.getCollection(collectionName).getRouter();
+ Slice shard1 = clusterState.getCollection(collectionName).getSlice(SHARD1);
+ DocRouter.Range shard1Range =
+ shard1.getRange() != null ? shard1.getRange() : router.fullRange();
+ final List<DocRouter.Range> ranges = router.partitionRange(2, shard1Range);
+ final int[] docCounts = new int[ranges.size()];
- for (int i = 100; i <= 200; i++) {
- // See comment in ShardRoutingTest for hash distribution
- String shardKey = "" + (char) ('a' + (i % 26));
+ for (int i = 100; i <= 200; i++) {
+ // See comment in ShardRoutingTest for hash distribution
+ String shardKey = "" + (char) ('a' + (i % 26));
- collectionClient.add(getDoc(id, i, "n_ti", i, shard_fld, shardKey));
- int idx = getHashRangeIdx(router, ranges, shardKey);
- if (idx != -1) {
- docCounts[idx]++;
- }
+ collectionClient.add(getDoc(id, i, "n_ti", i, shard_fld, shardKey));
+ int idx = getHashRangeIdx(router, ranges, shardKey);
+ if (idx != -1) {
+ docCounts[idx]++;
}
+ }
- for (int i = 0; i < docCounts.length; i++) {
- int docCount = docCounts[i];
- log.info("Shard shard1_{} docCount = {}", i, docCount);
- }
+ for (int i = 0; i < docCounts.length; i++) {
+ int docCount = docCounts[i];
+ log.info("Shard shard1_{} docCount = {}", i, docCount);
+ }
- collectionClient.commit();
+ collectionClient.commit();
- trySplit(collectionName, null, SHARD1, 3);
+ trySplit(collectionName, null, SHARD1, 3);
- waitForRecoveriesToFinish(collectionName, false);
+ waitForRecoveriesToFinish(collectionName, false);
- assertEquals(
- docCounts[0],
- collectionClient
- .query(new SolrQuery("*:*").setParam("shards", "shard1_0"))
- .getResults()
- .getNumFound());
- assertEquals(
- docCounts[1],
- collectionClient
- .query(new SolrQuery("*:*").setParam("shards", "shard1_1"))
- .getResults()
- .getNumFound());
- assertEquals(101, collectionClient.query(new SolrQuery("*:*")).getResults().getNumFound());
- }
+ assertEquals(
+ docCounts[0],
+ collectionClient
+ .query(new SolrQuery("*:*").setParam("shards", "shard1_0"))
+ .getResults()
+ .getNumFound());
+ assertEquals(
+ docCounts[1],
+ collectionClient
+ .query(new SolrQuery("*:*").setParam("shards", "shard1_1"))
+ .getResults()
+ .getNumFound());
+ assertEquals(101, collectionClient.query(new SolrQuery("*:*")).getResults().getNumFound());
}
public void splitByNumericRouteFieldTest() throws Exception {
@@ -1043,43 +1044,44 @@ public class ShardSplitTest extends BasicDistributedZkTest {
getCommonCloudSolrClient();
String baseUrl = getBaseUrlFromZk(cloudClient.getClusterState(), collectionName);
- try (SolrClient collectionClient = getHttpSolrClient(baseUrl, collectionName)) {
- ClusterState clusterState = cloudClient.getClusterState();
- final DocRouter router = clusterState.getCollection(collectionName).getRouter();
- Slice shard1 = clusterState.getCollection(collectionName).getSlice(SHARD1);
- DocRouter.Range shard1Range =
- shard1.getRange() != null ? shard1.getRange() : router.fullRange();
- final List<DocRouter.Range> ranges = router.partitionRange(2, shard1Range);
- final int[] docCounts = new int[ranges.size()];
-
- for (int i = 100; i <= 200; i++) {
- collectionClient.add(getDoc(id, i, "n_ti", i, shardField, i));
- int idx = getHashRangeIdx(router, ranges, Integer.toString(i));
- if (idx != -1) {
- docCounts[idx]++;
- }
+ SolrClient collectionClient =
+ new CollectionScopedSolrClient(getJetty(baseUrl).getSolrClient(), collectionName);
+
+ ClusterState clusterState = cloudClient.getClusterState();
+ final DocRouter router = clusterState.getCollection(collectionName).getRouter();
+ Slice shard1 = clusterState.getCollection(collectionName).getSlice(SHARD1);
+ DocRouter.Range shard1Range =
+ shard1.getRange() != null ? shard1.getRange() : router.fullRange();
+ final List<DocRouter.Range> ranges = router.partitionRange(2, shard1Range);
+ final int[] docCounts = new int[ranges.size()];
+
+ for (int i = 100; i <= 200; i++) {
+ collectionClient.add(getDoc(id, i, "n_ti", i, shardField, i));
+ int idx = getHashRangeIdx(router, ranges, Integer.toString(i));
+ if (idx != -1) {
+ docCounts[idx]++;
}
+ }
- collectionClient.commit();
+ collectionClient.commit();
- trySplit(collectionName, null, SHARD1, 3);
+ trySplit(collectionName, null, SHARD1, 3);
- waitForRecoveriesToFinish(collectionName, false);
+ waitForRecoveriesToFinish(collectionName, false);
- assertEquals(
- docCounts[0],
- collectionClient
- .query(new SolrQuery("*:*").setParam("shards", "shard1_0"))
- .getResults()
- .getNumFound());
- assertEquals(
- docCounts[1],
- collectionClient
- .query(new SolrQuery("*:*").setParam("shards", "shard1_1"))
- .getResults()
- .getNumFound());
- assertEquals(101, collectionClient.query(new SolrQuery("*:*")).getResults().getNumFound());
- }
+ assertEquals(
+ docCounts[0],
+ collectionClient
+ .query(new SolrQuery("*:*").setParam("shards", "shard1_0"))
+ .getResults()
+ .getNumFound());
+ assertEquals(
+ docCounts[1],
+ collectionClient
+ .query(new SolrQuery("*:*").setParam("shards", "shard1_1"))
+ .getResults()
+ .getNumFound());
+ assertEquals(101, collectionClient.query(new SolrQuery("*:*")).getResults().getNumFound());
}
private void splitByRouteKeyTest() throws Exception {
@@ -1106,92 +1108,92 @@ public class ShardSplitTest extends BasicDistributedZkTest {
getCommonCloudSolrClient();
String baseUrl = getBaseUrlFromZk(cloudClient.getClusterState(), collectionName);
- try (SolrClient collectionClient = getHttpSolrClient(baseUrl, collectionName)) {
-
- String splitKey = "b!";
-
- ClusterState clusterState = cloudClient.getClusterState();
- final DocRouter router = clusterState.getCollection(collectionName).getRouter();
- Slice shard1 = clusterState.getCollection(collectionName).getSlice(SHARD1);
- DocRouter.Range shard1Range =
- shard1.getRange() != null ? shard1.getRange() : router.fullRange();
- final List<DocRouter.Range> ranges =
- ((CompositeIdRouter) router).partitionRangeByKey(splitKey, shard1Range);
- final int[] docCounts = new int[ranges.size()];
-
- int uniqIdentifier = (1 << 12);
- int splitKeyDocCount = 0;
- for (int i = 100; i <= 200; i++) {
- // See comment in ShardRoutingTest for hash distribution
- String shardKey = "" + (char) ('a' + (i % 26));
-
- String idStr = shardKey + "!" + i;
- collectionClient.add(
- getDoc(id, idStr, "n_ti", (shardKey + "!").equals(splitKey) ? uniqIdentifier : i));
- int idx = getHashRangeIdx(router, ranges, idStr);
- if (idx != -1) {
- docCounts[idx]++;
- }
- if (splitKey.equals(shardKey + "!")) splitKeyDocCount++;
- }
+ SolrClient collectionClient =
+ new CollectionScopedSolrClient(getJetty(baseUrl).getSolrClient(), collectionName);
- for (int i = 0; i < docCounts.length; i++) {
- int docCount = docCounts[i];
- log.info("Shard shard1_{} docCount = {}", i, docCount);
- }
- log.info("Route key doc count = {}", splitKeyDocCount);
+ String splitKey = "b!";
- collectionClient.commit();
+ ClusterState clusterState = cloudClient.getClusterState();
+ final DocRouter router = clusterState.getCollection(collectionName).getRouter();
+ Slice shard1 = clusterState.getCollection(collectionName).getSlice(SHARD1);
+ DocRouter.Range shard1Range =
+ shard1.getRange() != null ? shard1.getRange() : router.fullRange();
+ final List<DocRouter.Range> ranges =
+ ((CompositeIdRouter) router).partitionRangeByKey(splitKey, shard1Range);
+ final int[] docCounts = new int[ranges.size()];
- trySplit(collectionName, splitKey, null, 3);
+ int uniqIdentifier = (1 << 12);
+ int splitKeyDocCount = 0;
+ for (int i = 100; i <= 200; i++) {
+ // See comment in ShardRoutingTest for hash distribution
+ String shardKey = "" + (char) ('a' + (i % 26));
+
+ String idStr = shardKey + "!" + i;
+ collectionClient.add(
+ getDoc(id, idStr, "n_ti", (shardKey + "!").equals(splitKey) ? uniqIdentifier : i));
+ int idx = getHashRangeIdx(router, ranges, idStr);
+ if (idx != -1) {
+ docCounts[idx]++;
+ }
+ if (splitKey.equals(shardKey + "!")) splitKeyDocCount++;
+ }
- waitForRecoveriesToFinish(collectionName, false);
- SolrQuery solrQuery = new SolrQuery("*:*");
- assertEquals(
- "DocCount on shard1_0 does not match",
- docCounts[0],
- collectionClient
- .query(solrQuery.setParam("shards", "shard1_0"))
- .getResults()
- .getNumFound());
- assertEquals(
- "DocCount on shard1_1 does not match",
- docCounts[1],
- collectionClient
- .query(solrQuery.setParam("shards", "shard1_1"))
- .getResults()
- .getNumFound());
- assertEquals(
- "DocCount on shard1_2 does not match",
- docCounts[2],
- collectionClient
- .query(solrQuery.setParam("shards", "shard1_2"))
- .getResults()
- .getNumFound());
-
- solrQuery = new SolrQuery("n_ti:" + uniqIdentifier);
- assertEquals(
- "shard1_0 must have 0 docs for route key: " + splitKey,
- 0,
- collectionClient
- .query(solrQuery.setParam("shards", "shard1_0"))
- .getResults()
- .getNumFound());
- assertEquals(
- "Wrong number of docs on shard1_1 for route key: " + splitKey,
- splitKeyDocCount,
- collectionClient
- .query(solrQuery.setParam("shards", "shard1_1"))
- .getResults()
- .getNumFound());
- assertEquals(
- "shard1_2 must have 0 docs for route key: " + splitKey,
- 0,
- collectionClient
- .query(solrQuery.setParam("shards", "shard1_2"))
- .getResults()
- .getNumFound());
+ for (int i = 0; i < docCounts.length; i++) {
+ int docCount = docCounts[i];
+ log.info("Shard shard1_{} docCount = {}", i, docCount);
}
+ log.info("Route key doc count = {}", splitKeyDocCount);
+
+ collectionClient.commit();
+
+ trySplit(collectionName, splitKey, null, 3);
+
+ waitForRecoveriesToFinish(collectionName, false);
+ SolrQuery solrQuery = new SolrQuery("*:*");
+ assertEquals(
+ "DocCount on shard1_0 does not match",
+ docCounts[0],
+ collectionClient
+ .query(solrQuery.setParam("shards", "shard1_0"))
+ .getResults()
+ .getNumFound());
+ assertEquals(
+ "DocCount on shard1_1 does not match",
+ docCounts[1],
+ collectionClient
+ .query(solrQuery.setParam("shards", "shard1_1"))
+ .getResults()
+ .getNumFound());
+ assertEquals(
+ "DocCount on shard1_2 does not match",
+ docCounts[2],
+ collectionClient
+ .query(solrQuery.setParam("shards", "shard1_2"))
+ .getResults()
+ .getNumFound());
+
+ solrQuery = new SolrQuery("n_ti:" + uniqIdentifier);
+ assertEquals(
+ "shard1_0 must have 0 docs for route key: " + splitKey,
+ 0,
+ collectionClient
+ .query(solrQuery.setParam("shards", "shard1_0"))
+ .getResults()
+ .getNumFound());
+ assertEquals(
+ "Wrong number of docs on shard1_1 for route key: " + splitKey,
+ splitKeyDocCount,
+ collectionClient
+ .query(solrQuery.setParam("shards", "shard1_1"))
+ .getResults()
+ .getNumFound());
+ assertEquals(
+ "shard1_2 must have 0 docs for route key: " + splitKey,
+ 0,
+ collectionClient
+ .query(solrQuery.setParam("shards", "shard1_2"))
+ .getResults()
+ .getNumFound());
}
private void trySplit(String collectionName, String splitKey, String shardId, int maxTries)
@@ -1260,18 +1262,16 @@ public class ShardSplitTest extends BasicDistributedZkTest {
Replica shard1_0 = getLeaderFromZk(AbstractFullDistribZkTestBase.DEFAULT_COLLECTION, SHARD1_0);
QueryResponse response;
- try (SolrClient shard1_0Client =
- getHttpSolrClient(shard1_0.getBaseUrl(), shard1_0.getCoreName())) {
- response = shard1_0Client.query(query);
- }
+ SolrClient shard1_0Client = getSolrClient(shard1_0);
+ response = shard1_0Client.query(query);
+
long shard10Count = response.getResults().getNumFound();
Replica shard1_1 = getLeaderFromZk(AbstractFullDistribZkTestBase.DEFAULT_COLLECTION, SHARD1_1);
QueryResponse response2;
- try (SolrClient shard1_1Client =
- getHttpSolrClient(shard1_1.getBaseUrl(), shard1_1.getCoreName())) {
- response2 = shard1_1Client.query(query);
- }
+ SolrClient shard1_1Client = getSolrClient(shard1_1);
+ response2 = shard1_1Client.query(query);
+
long shard11Count = response2.getResults().getNumFound();
logDebugHelp(docCounts, response, shard10Count, response2, shard11Count, documentIds);
@@ -1294,9 +1294,9 @@ public class ShardSplitTest extends BasicDistributedZkTest {
for (Replica replica : slice.getReplicas()) {
String coreUrl = replica.getCoreUrl();
QueryResponse response;
- try (SolrClient client = getHttpSolrClient(replica)) {
- response = client.query(query);
- }
+ SolrClient client = getSolrClient(replica);
+ response = client.query(query);
+
numFound[c++] = response.getResults().getNumFound();
if (log.isInfoEnabled()) {
log.info(
@@ -1345,11 +1345,9 @@ public class ShardSplitTest extends BasicDistributedZkTest {
new GenericSolrRequest(METHOD.POST, "/admin/collections", SolrRequestType.ADMIN, params);
JettySolrRunner jetty = shardToJetty.get(SHARD1).getFirst().jetty;
- try (SolrClient baseServer = jetty.newClient(30_000, 300_000)) {
- NamedList<Object> rsp = baseServer.request(request);
- if (log.isInfoEnabled()) {
- log.info("Shard split response: {}", Utils.toJSONString(rsp));
- }
+ NamedList<Object> rsp = jetty.getSolrClient().request(request);
+ if (log.isInfoEnabled()) {
+ log.info("Shard split response: {}", Utils.toJSONString(rsp));
}
}
diff --git a/solr/core/src/test/org/apache/solr/core/TestCustomStream.java b/solr/core/src/test/org/apache/solr/core/TestCustomStream.java
index 73c8afc93de..e167c798aad 100644
--- a/solr/core/src/test/org/apache/solr/core/TestCustomStream.java
+++ b/solr/core/src/test/org/apache/solr/core/TestCustomStream.java
@@ -18,21 +18,30 @@
package org.apache.solr.core;
import java.util.Arrays;
-import org.apache.solr.cloud.AbstractFullDistribZkTestBase;
+import org.apache.solr.client.solrj.request.CollectionAdminRequest;
+import org.apache.solr.cloud.SolrCloudTestCase;
import org.apache.solr.util.RestTestHarness;
+import org.junit.BeforeClass;
import org.junit.Test;
-public class TestCustomStream extends AbstractFullDistribZkTestBase {
+public class TestCustomStream extends SolrCloudTestCase {
+
+ @BeforeClass
+ public static void setupCluster() throws Exception {
+ configureCluster(2).addConfig("conf1", configset("cloud-minimal")).configure();
+ CollectionAdminRequest.createCollection("collection1", "conf1", 1, 2)
+ .process(cluster.getSolrClient());
+ cluster.waitForActiveCollection("collection1", 1, 2);
+ }
@Test
public void testDynamicLoadingCustomStream() throws Exception {
- setupRestTestHarnesses();
String payload =
"{\n"
+ "'create-expressible' : { 'name' : 'hello', 'class': 'org.apache.solr.core.HelloStream' }\n"
+ "}";
- RestTestHarness client = randomRestTestHarness();
+ RestTestHarness client = cluster.getRandomJetty(random()).getRestClient("collection1");
TestSolrConfigHandler.runConfigCommand(client, "/config", payload);
TestSolrConfigHandler.testForResponseElement(
client,
diff --git a/solr/core/src/test/org/apache/solr/core/snapshots/TestSolrCloudSnapshots.java b/solr/core/src/test/org/apache/solr/core/snapshots/TestSolrCloudSnapshots.java
index 6fa70f020e6..6ead68205f9 100644
--- a/solr/core/src/test/org/apache/solr/core/snapshots/TestSolrCloudSnapshots.java
+++ b/solr/core/src/test/org/apache/solr/core/snapshots/TestSolrCloudSnapshots.java
@@ -151,20 +151,18 @@ public class TestSolrCloudSnapshots extends SolrCloudTestCase {
continue; // We know that the snapshot is not created for this replica.
}
- String replicaBaseUrl = replica.getBaseUrl();
String coreName = replica.getCoreName();
assertTrue(snapshotByCoreName.containsKey(coreName));
CoreSnapshotMetaData coreSnapshot = snapshotByCoreName.get(coreName);
- try (SolrClient adminClient = getHttpSolrClient(replicaBaseUrl)) {
- Collection<SnapshotMetaData> snapshots = listCoreSnapshots(adminClient, coreName);
- Optional<SnapshotMetaData> metaData =
- snapshots.stream().filter(x -> commitName.equals(x.getName())).findFirst();
- assertTrue("Snapshot not created for core " + coreName, metaData.isPresent());
- assertEquals(coreSnapshot.getIndexDirPath(), metaData.get().getIndexDirPath());
- assertEquals(coreSnapshot.getGenerationNumber(), metaData.get().getGenerationNumber());
- }
+ SolrClient adminClient = cluster.getSolrClient(replica);
+ Collection<SnapshotMetaData> snapshots = listCoreSnapshots(adminClient, coreName);
+ Optional<SnapshotMetaData> metaData =
+ snapshots.stream().filter(x -> commitName.equals(x.getName())).findFirst();
+ assertTrue("Snapshot not created for core " + coreName, metaData.isPresent());
+ assertEquals(coreSnapshot.getIndexDirPath(), metaData.get().getIndexDirPath());
+ assertEquals(coreSnapshot.getGenerationNumber(), metaData.get().getGenerationNumber());
}
}
@@ -273,17 +271,15 @@ public class TestSolrCloudSnapshots extends SolrCloudTestCase {
continue; // We know that the snapshot was not created for this replica.
}
- String replicaBaseUrl = replica.getBaseUrl();
String coreName = replica.getCoreName();
- try (SolrClient adminClient = getHttpSolrClient(replicaBaseUrl)) {
- Collection<SnapshotMetaData> snapshots = listCoreSnapshots(adminClient, coreName);
- Optional<SnapshotMetaData> metaData =
- snapshots.stream().filter(x -> commitName.equals(x.getName())).findFirst();
- assertFalse("Snapshot not deleted for core " + coreName, metaData.isPresent());
- // Remove the entry for core if the snapshot is deleted successfully.
- snapshotByCoreName.remove(coreName);
- }
+ SolrClient adminClient = cluster.getSolrClient(replica);
+ Collection<SnapshotMetaData> snapshots = listCoreSnapshots(adminClient, coreName);
+ Optional<SnapshotMetaData> metaData =
+ snapshots.stream().filter(x -> commitName.equals(x.getName())).findFirst();
+ assertFalse("Snapshot not deleted for core " + coreName, metaData.isPresent());
+ // Remove the entry for core if the snapshot is deleted successfully.
+ snapshotByCoreName.remove(coreName);
}
}
diff --git a/solr/core/src/test/org/apache/solr/core/snapshots/TestSolrCoreSnapshots.java b/solr/core/src/test/org/apache/solr/core/snapshots/TestSolrCoreSnapshots.java
index 431a43a2fb7..b251c5b3dcd 100644
--- a/solr/core/src/test/org/apache/solr/core/snapshots/TestSolrCoreSnapshots.java
+++ b/solr/core/src/test/org/apache/solr/core/snapshots/TestSolrCoreSnapshots.java
@@ -33,7 +33,6 @@ import org.apache.lucene.tests.util.TestUtil;
import org.apache.solr.SolrTestCaseJ4;
import org.apache.solr.client.solrj.SolrClient;
import org.apache.solr.client.solrj.impl.CloudSolrClient;
-import org.apache.solr.client.solrj.jetty.HttpJettySolrClient;
import org.apache.solr.client.solrj.request.CollectionAdminRequest;
import org.apache.solr.client.solrj.request.CoreAdminRequest.CreateSnapshot;
import org.apache.solr.client.solrj.request.CoreAdminRequest.DeleteSnapshot;
@@ -98,79 +97,73 @@ public class TestSolrCoreSnapshots extends SolrCloudTestCase {
String commitName = TestUtil.randomSimpleString(random(), 1, 5);
String duplicateName = commitName.concat("_duplicate");
- try (SolrClient adminClient =
- getHttpSolrClient(cluster.getJettySolrRunners().get(0).getBaseUrl().toString());
- SolrClient leaderClient =
- new HttpJettySolrClient.Builder(replica.getBaseUrl())
- .withDefaultCollection(replica.getCoreName())
- .build()) {
-
- SnapshotMetaData metaData = createSnapshot(adminClient, coreName, commitName);
- // Create another snapshot referring to the same index commit to verify the
- // reference counting implementation during snapshot deletion.
- SnapshotMetaData duplicateCommit = createSnapshot(adminClient, coreName, duplicateName);
-
- assertEquals(metaData.getIndexDirPath(), duplicateCommit.getIndexDirPath());
- assertEquals(metaData.getGenerationNumber(), duplicateCommit.getGenerationNumber());
-
- // Delete all documents
- leaderClient.deleteByQuery("*:*");
- leaderClient.commit();
- BackupRestoreUtils.verifyDocs(0, cluster.getSolrClient(), collectionName);
-
- // Verify that the index directory contains at least 2 index commits - one referred by the
- // snapshots and the other containing document deletions.
- {
- List<IndexCommit> commits = listCommits(metaData.getIndexDirPath());
- assertTrue(commits.size() >= 2);
- }
+ SolrClient adminClient = cluster.getJettySolrRunners().get(0).getSolrClient();
+ SolrClient leaderClient = cluster.getSolrClient(replica);
+ SnapshotMetaData metaData = createSnapshot(adminClient, coreName, commitName);
+ // Create another snapshot referring to the same index commit to verify the
+ // reference counting implementation during snapshot deletion.
+ SnapshotMetaData duplicateCommit = createSnapshot(adminClient, coreName, duplicateName);
+
+ assertEquals(metaData.getIndexDirPath(), duplicateCommit.getIndexDirPath());
+ assertEquals(metaData.getGenerationNumber(), duplicateCommit.getGenerationNumber());
+
+ // Delete all documents
+ leaderClient.deleteByQuery("*:*");
+ leaderClient.commit();
+ BackupRestoreUtils.verifyDocs(0, cluster.getSolrClient(), collectionName);
+
+ // Verify that the index directory contains at least 2 index commits - one referred by the
+ // snapshots and the other containing document deletions.
+ {
+ List<IndexCommit> commits = listCommits(metaData.getIndexDirPath());
+ assertTrue(commits.size() >= 2);
+ }
- // Backup the earlier created snapshot.
- {
- Map<String, String> params = new HashMap<>();
- params.put("name", backupName);
- params.put("commitName", commitName);
- params.put("location", location);
- params.put("incremental", "false");
- BackupRestoreUtils.runCoreAdminCommand(
- replicaBaseUrl, coreName, CoreAdminAction.BACKUPCORE.toString(), params);
- }
+ // Backup the earlier created snapshot.
+ {
+ Map<String, String> params = new HashMap<>();
+ params.put("name", backupName);
+ params.put("commitName", commitName);
+ params.put("location", location);
+ params.put("incremental", "false");
+ BackupRestoreUtils.runCoreAdminCommand(
+ replicaBaseUrl, coreName, CoreAdminAction.BACKUPCORE.toString(), params);
+ }
- // Restore the backup
- {
- Map<String, String> params = new HashMap<>();
- params.put("name", "snapshot." + backupName);
- params.put("location", location);
- BackupRestoreUtils.runCoreAdminCommand(
- replicaBaseUrl, coreName, CoreAdminAction.RESTORECORE.toString(), params);
- BackupRestoreUtils.verifyDocs(nDocs, cluster.getSolrClient(), collectionName);
- }
+ // Restore the backup
+ {
+ Map<String, String> params = new HashMap<>();
+ params.put("name", "snapshot." + backupName);
+ params.put("location", location);
+ BackupRestoreUtils.runCoreAdminCommand(
+ replicaBaseUrl, coreName, CoreAdminAction.RESTORECORE.toString(), params);
+ BackupRestoreUtils.verifyDocs(nDocs, cluster.getSolrClient(), collectionName);
+ }
- // Verify that the old index directory (before restore) contains only those index commits
- // referred by snapshots. The IndexWriter (used to clean up index files) creates an additional
- // commit during closing. Hence, we expect 2 commits (instead of 1).
- {
- List<IndexCommit> commits = listCommits(metaData.getIndexDirPath());
- assertEquals(2, commits.size());
- assertEquals(metaData.getGenerationNumber(), commits.get(0).getGeneration());
- }
+ // Verify that the old index directory (before restore) contains only those index commits
+ // referred by snapshots. The IndexWriter (used to clean up index files) creates an additional
+ // commit during closing. Hence, we expect 2 commits (instead of 1).
+ {
+ List<IndexCommit> commits = listCommits(metaData.getIndexDirPath());
+ assertEquals(2, commits.size());
+ assertEquals(metaData.getGenerationNumber(), commits.get(0).getGeneration());
+ }
- // Delete first snapshot
- deleteSnapshot(adminClient, coreName, commitName);
+ // Delete first snapshot
+ deleteSnapshot(adminClient, coreName, commitName);
- // Verify that corresponding index files have NOT been deleted (due to reference counting).
- assertFalse(listCommits(metaData.getIndexDirPath()).isEmpty());
+ // Verify that corresponding index files have NOT been deleted (due to reference counting).
+ assertFalse(listCommits(metaData.getIndexDirPath()).isEmpty());
- // Delete second snapshot
- deleteSnapshot(adminClient, coreName, duplicateCommit.getName());
+ // Delete second snapshot
+ deleteSnapshot(adminClient, coreName, duplicateCommit.getName());
- // Verify that corresponding index files have been deleted. Ideally this directory should
- // be removed immediately. But the current DirectoryFactory impl waits until the
- // closing the core (or the directoryFactory) for actual removal. Since the IndexWriter
- // (used to clean up index files) creates an additional commit during closing, we expect a
- // single commit (instead of 0).
- assertEquals(1, listCommits(duplicateCommit.getIndexDirPath()).size());
- }
+ // Verify that corresponding index files have been deleted. Ideally this directory should
+ // be removed immediately. But the current DirectoryFactory impl waits until the
+ // closing the core (or the directoryFactory) for actual removal. Since the IndexWriter
+ // (used to clean up index files) creates an additional commit during closing, we expect a
+ // single commit (instead of 0).
+ assertEquals(1, listCommits(duplicateCommit.getIndexDirPath()).size());
}
@Test
@@ -192,72 +185,20 @@ public class TestSolrCoreSnapshots extends SolrCloudTestCase {
String coreName = replica.getStr(ZkStateReader.CORE_NAME_PROP);
String commitName = TestUtil.randomSimpleString(random(), 1, 5);
- try (SolrClient adminClient =
- getHttpSolrClient(cluster.getJettySolrRunners().get(0).getBaseUrl().toString());
- SolrClient leaderClient =
- new HttpJettySolrClient.Builder(replica.getBaseUrl())
- .withDefaultCollection(replica.getCoreName())
- .build()) {
-
- SnapshotMetaData metaData = createSnapshot(adminClient, coreName, commitName);
-
- int numTests = nDocs > 0 ? TestUtil.nextInt(random(), 1, 5) : 1;
- for (int attempt = 0; attempt < numTests; attempt++) {
- // Modify existing index before we call optimize.
- if (nDocs > 0) {
- // Delete a few docs
- int numDeletes = TestUtil.nextInt(random(), 1, nDocs);
- for (int i = 0; i < numDeletes; i++) {
- leaderClient.deleteByQuery("id:" + i);
- }
- // Add a few more
- int moreAdds = TestUtil.nextInt(random(), 1, 100);
- for (int i = 0; i < moreAdds; i++) {
- SolrInputDocument doc = new SolrInputDocument();
- doc.addField("id", i + nDocs);
- doc.addField("name", "name = " + (i + nDocs));
- leaderClient.add(doc);
- }
- leaderClient.commit();
+ SolrClient adminClient = cluster.getJettySolrRunners().get(0).getSolrClient();
+ SolrClient leaderClient = cluster.getSolrClient(replica);
+ SnapshotMetaData metaData = createSnapshot(adminClient, coreName, commitName);
+
+ int numTests = nDocs > 0 ? TestUtil.nextInt(random(), 1, 5) : 1;
+ for (int attempt = 0; attempt < numTests; attempt++) {
+ // Modify existing index before we call optimize.
+ if (nDocs > 0) {
+ // Delete a few docs
+ int numDeletes = TestUtil.nextInt(random(), 1, nDocs);
+ for (int i = 0; i < numDeletes; i++) {
+ leaderClient.deleteByQuery("id:" + i);
}
- }
-
- // Before invoking optimize command, verify that the index directory contains multiple commits
- // (including the one we snapshotted earlier).
- {
- Collection<IndexCommit> commits = listCommits(metaData.getIndexDirPath());
- // Verify that multiple index commits are stored in this directory.
- assertTrue(commits.size() > 0);
- // Verify that the snapshot commit is present in this directory.
- assertTrue(
- commits.stream()
- .filter(x -> x.getGeneration() == metaData.getGenerationNumber())
- .findFirst()
- .isPresent());
- }
-
- // Optimize the index.
- leaderClient.optimize(true, true, 1);
-
- // After invoking optimize command, verify that the index directory contains multiple commits
- // (including the one we snapshotted earlier).
- {
- List<IndexCommit> commits = listCommits(metaData.getIndexDirPath());
- // Verify that multiple index commits are stored in this directory.
- assertTrue(commits.size() > 1);
- // Verify that the snapshot commit is present in this directory.
- assertTrue(
- commits.stream()
- .filter(x -> x.getGeneration() == metaData.getGenerationNumber())
- .findFirst()
- .isPresent());
- }
-
- // Delete the snapshot
- deleteSnapshot(adminClient, coreName, metaData.getName());
-
- // Add few documents. Without this the optimize command below does not take effect.
- {
+ // Add a few more
int moreAdds = TestUtil.nextInt(random(), 1, 100);
for (int i = 0; i < moreAdds; i++) {
SolrInputDocument doc = new SolrInputDocument();
@@ -267,20 +208,66 @@ public class TestSolrCoreSnapshots extends SolrCloudTestCase {
}
leaderClient.commit();
}
+ }
- // Optimize the index.
- leaderClient.optimize(true, true, 1);
-
- // Verify that the index directory contains only 1 index commit (which is not the same as the
- // snapshotted commit).
+ // Before invoking optimize command, verify that the index directory contains multiple commits
+ // (including the one we snapshotted earlier).
+ {
Collection<IndexCommit> commits = listCommits(metaData.getIndexDirPath());
- assertEquals(1, commits.size());
- assertFalse(
+ // Verify that multiple index commits are stored in this directory.
+ assertTrue(commits.size() > 0);
+ // Verify that the snapshot commit is present in this directory.
+ assertTrue(
+ commits.stream()
+ .filter(x -> x.getGeneration() == metaData.getGenerationNumber())
+ .findFirst()
+ .isPresent());
+ }
+
+ // Optimize the index.
+ leaderClient.optimize(true, true, 1);
+
+ // After invoking optimize command, verify that the index directory contains multiple commits
+ // (including the one we snapshotted earlier).
+ {
+ List<IndexCommit> commits = listCommits(metaData.getIndexDirPath());
+ // Verify that multiple index commits are stored in this directory.
+ assertTrue(commits.size() > 1);
+ // Verify that the snapshot commit is present in this directory.
+ assertTrue(
commits.stream()
.filter(x -> x.getGeneration() == metaData.getGenerationNumber())
.findFirst()
.isPresent());
}
+
+ // Delete the snapshot
+ deleteSnapshot(adminClient, coreName, metaData.getName());
+
+ // Add few documents. Without this the optimize command below does not take effect.
+ {
+ int moreAdds = TestUtil.nextInt(random(), 1, 100);
+ for (int i = 0; i < moreAdds; i++) {
+ SolrInputDocument doc = new SolrInputDocument();
+ doc.addField("id", i + nDocs);
+ doc.addField("name", "name = " + (i + nDocs));
+ leaderClient.add(doc);
+ }
+ leaderClient.commit();
+ }
+
+ // Optimize the index.
+ leaderClient.optimize(true, true, 1);
+
+ // Verify that the index directory contains only 1 index commit (which is not the same as the
+ // snapshotted commit).
+ Collection<IndexCommit> commits = listCommits(metaData.getIndexDirPath());
+ assertEquals(1, commits.size());
+ assertFalse(
+ commits.stream()
+ .filter(x -> x.getGeneration() == metaData.getGenerationNumber())
+ .findFirst()
+ .isPresent());
}
private SnapshotMetaData createSnapshot(
diff --git a/solr/core/src/test/org/apache/solr/filestore/TestDistribFileStore.java b/solr/core/src/test/org/apache/solr/filestore/TestDistribFileStore.java
index 8e7b5ab80ed..133116e6908 100644
--- a/solr/core/src/test/org/apache/solr/filestore/TestDistribFileStore.java
+++ b/solr/core/src/test/org/apache/solr/filestore/TestDistribFileStore.java
@@ -173,18 +173,17 @@ public class TestDistribFileStore extends SolrCloudTestCase {
for (JettySolrRunner jettySolrRunner : cluster.getJettySolrRunners()) {
final var fetchReq = new FileStoreApi.FetchFile("/package/mypkg/v1.0/runtimelibs.jar2");
fetchReq.setGetFrom("someFakeSolrNode:8983_solr");
- try (final var solrClient = jettySolrRunner.newClient()) {
- final var expectedExc =
- expectThrows(
- RemoteSolrException.class,
- () -> {
- fetchReq.process(solrClient);
- });
- assertEquals(400, expectedExc.code());
- assertThat(
- expectedExc.getMessage(), containsString("File store cannot fetch from source node"));
- assertThat(expectedExc.getMessage(), containsString("does not appear in live-nodes"));
- }
+ final var solrClient = jettySolrRunner.getSolrClient();
+ final var expectedExc =
+ expectThrows(
+ RemoteSolrException.class,
+ () -> {
+ fetchReq.process(solrClient);
+ });
+ assertEquals(400, expectedExc.code());
+ assertThat(
+ expectedExc.getMessage(), containsString("File store cannot fetch from source node"));
+ assertThat(expectedExc.getMessage(), containsString("does not appear in live-nodes"));
}
// Delete Jars
diff --git a/solr/core/src/test/org/apache/solr/handler/TestReplicationHandler.java b/solr/core/src/test/org/apache/solr/handler/TestReplicationHandler.java
index cc719d054c4..b531dc113f0 100644
--- a/solr/core/src/test/org/apache/solr/handler/TestReplicationHandler.java
+++ b/solr/core/src/test/org/apache/solr/handler/TestReplicationHandler.java
@@ -239,14 +239,13 @@ public class TestReplicationHandler extends SolrTestCaseJ4 {
new GenericSolrRequest(
SolrRequest.METHOD.POST, "/admin/cores", SolrRequestType.ADMIN, params);
- try (SolrClient adminClient = adminClient(jettySolrRunner)) {
- NamedList<Object> res = adminClient.request(req);
- assertNotNull("null response from server", res);
- }
+ SolrClient adminClient = adminClient(jettySolrRunner);
+ NamedList<Object> res = adminClient.request(req);
+ assertNotNull("null response from server", res);
}
private SolrClient adminClient(JettySolrRunner client) {
- return getHttpSolrClient(client.getBaseUrl().toString());
+ return client.getSolrClient();
}
@Test
@@ -1721,33 +1720,32 @@ public class TestReplicationHandler extends SolrTestCaseJ4 {
final long sleepInterval = 200;
long timeSlept = 0;
- try (SolrClient adminClient = adminClient(jettySolrRunner)) {
- final var statusRequest = new CoresApi.GetCoreStatus("collection1");
- while (timeSlept < TIMEOUT) {
- try {
- final var statusResponse = statusRequest.process(adminClient);
- assertNotNull(statusResponse.status);
- assertTrue(statusResponse.status.containsKey("collection1"));
- final var coreStatus = statusResponse.status.get("collection1");
- Date startTime = coreStatus.startTime;
-
- assertNotNull("core has null startTime", startTime);
- if (null == min || startTime.after(min)) {
- return startTime;
- }
- } catch (SolrException e) {
- // workaround for SOLR-4668
- if (500 != e.code()) {
- throw e;
- } // else server possibly from the core reload in progress...
+ SolrClient adminClient = adminClient(jettySolrRunner);
+ final var statusRequest = new CoresApi.GetCoreStatus("collection1");
+ while (timeSlept < TIMEOUT) {
+ try {
+ final var statusResponse = statusRequest.process(adminClient);
+ assertNotNull(statusResponse.status);
+ assertTrue(statusResponse.status.containsKey("collection1"));
+ final var coreStatus = statusResponse.status.get("collection1");
+ Date startTime = coreStatus.startTime;
+
+ assertNotNull("core has null startTime", startTime);
+ if (null == min || startTime.after(min)) {
+ return startTime;
}
-
- timeSlept += sleepInterval;
- Thread.sleep(sleepInterval);
+ } catch (SolrException e) {
+ // workaround for SOLR-4668
+ if (500 != e.code()) {
+ throw e;
+ } // else server possibly from the core reload in progress...
}
- fail("timed out waiting for collection1 startAt time to exceed: " + min);
- return min; // compilation necessity
+
+ timeSlept += sleepInterval;
+ Thread.sleep(sleepInterval);
}
+ fail("timed out waiting for collection1 startAt time to exceed: " + min);
+ return min; // compilation necessity
}
@Test
diff --git a/solr/core/src/test/org/apache/solr/handler/TestStressIncrementalBackup.java b/solr/core/src/test/org/apache/solr/handler/TestStressIncrementalBackup.java
index 6305473b94e..54856313195 100644
--- a/solr/core/src/test/org/apache/solr/handler/TestStressIncrementalBackup.java
+++ b/solr/core/src/test/org/apache/solr/handler/TestStressIncrementalBackup.java
@@ -62,7 +62,7 @@ public class TestStressIncrementalBackup extends SolrCloudTestCase {
(CollectionAdminRequest.createCollection(DEFAULT_TEST_COLLECTION_NAME, "conf1", 1, 1)
.process(cluster.getSolrClient())
.getStatus()));
- adminClient = getHttpSolrClient(cluster.getJettySolrRunners().get(0).getBaseUrl().toString());
+ adminClient = cluster.getJettySolrRunners().get(0).getSolrClient();
initCoreNameAndSolrCoreClient();
}
@@ -80,20 +80,13 @@ public class TestStressIncrementalBackup extends SolrCloudTestCase {
.iterator()
.next();
coreName = r.getCoreName();
- coreClient = getHttpSolrClient(r);
+ coreClient = cluster.getSolrClient(r);
}
@After
public void afterTest() throws Exception {
// we use a clean cluster instance for every test, so we need to clean it up
shutdownCluster();
-
- if (null != adminClient) {
- adminClient.close();
- }
- if (null != coreClient) {
- coreClient.close();
- }
}
@SuppressWarnings("AssertionFailureIgnored") // failure happens inside a thread
diff --git a/solr/core/src/test/org/apache/solr/handler/TestStressThreadBackup.java b/solr/core/src/test/org/apache/solr/handler/TestStressThreadBackup.java
index 70db545fced..ea4d54c5c22 100644
--- a/solr/core/src/test/org/apache/solr/handler/TestStressThreadBackup.java
+++ b/solr/core/src/test/org/apache/solr/handler/TestStressThreadBackup.java
@@ -96,7 +96,7 @@ public class TestStressThreadBackup extends SolrCloudTestCase {
(CollectionAdminRequest.createCollection(DEFAULT_TEST_COLLECTION_NAME, "conf1", 1, 1)
.process(cluster.getSolrClient())
.getStatus()));
- adminClient = getHttpSolrClient(cluster.getJettySolrRunners().get(0).getBaseUrl().toString());
+ adminClient = cluster.getJettySolrRunners().get(0).getSolrClient();
initCoreNameAndSolrCoreClient();
}
@@ -104,13 +104,6 @@ public class TestStressThreadBackup extends SolrCloudTestCase {
public void afterTest() throws Exception {
// we use a clean cluster instance for every test, so we need to clean it up
shutdownCluster();
-
- if (null != adminClient) {
- adminClient.close();
- }
- if (null != coreClient) {
- coreClient.close();
- }
}
@Test
@@ -371,7 +364,7 @@ public class TestStressThreadBackup extends SolrCloudTestCase {
.iterator()
.next();
coreName = r.getCoreName();
- coreClient = getHttpSolrClient(r);
+ coreClient = cluster.getSolrClient(r);
}
/**
diff --git a/solr/core/src/test/org/apache/solr/handler/V2StandaloneTest.java b/solr/core/src/test/org/apache/solr/handler/V2StandaloneTest.java
index aa76092cf5d..5d6184ce0f0 100644
--- a/solr/core/src/test/org/apache/solr/handler/V2StandaloneTest.java
+++ b/solr/core/src/test/org/apache/solr/handler/V2StandaloneTest.java
@@ -39,15 +39,14 @@ public class V2StandaloneTest extends SolrTestCaseJ4 {
new JettySolrRunner(solrHomeTmp.toString(), JettyConfig.builder().build());
jetty.start();
- try (SolrClient client = getHttpSolrClient(buildUrl(jetty.getLocalPort()))) {
- NamedList<?> res = client.request(new V2Request.Builder("/").build());
- NamedList<?> header = (NamedList<?>) res.get("responseHeader");
- assertEquals(0, header.get("status"));
-
- res = client.request(new V2Request.Builder("/_introspect").build());
- header = (NamedList<?>) res.get("responseHeader");
- assertEquals(0, header.get("status"));
- }
+ SolrClient client = jetty.getSolrClient();
+ NamedList<?> res = client.request(new V2Request.Builder("/").build());
+ NamedList<?> header = (NamedList<?>) res.get("responseHeader");
+ assertEquals(0, header.get("status"));
+
+ res = client.request(new V2Request.Builder("/_introspect").build());
+ header = (NamedList<?>) res.get("responseHeader");
+ assertEquals(0, header.get("status"));
jetty.stop();
}
diff --git a/solr/core/src/test/org/apache/solr/handler/admin/CoreAdminHandlerTest.java b/solr/core/src/test/org/apache/solr/handler/admin/CoreAdminHandlerTest.java
index 0c85bbee765..e3b3a1084f0 100644
--- a/solr/core/src/test/org/apache/solr/handler/admin/CoreAdminHandlerTest.java
+++ b/solr/core/src/test/org/apache/solr/handler/admin/CoreAdminHandlerTest.java
@@ -419,12 +419,11 @@ public class CoreAdminHandlerTest extends SolrTestCaseJ4 {
runner.getSolrClient().commit("corex");
Path dataDir = null;
- try (SolrClient client = getHttpSolrClient(runner.getBaseUrl().toString())) {
- final var status = CoreAdminRequest.getCoreStatus("corex", true, client);
- String dataDirectory = status.dataDir;
- dataDir = Path.of(dataDirectory);
- assertTrue(Files.exists(dataDir));
- }
+ SolrClient client = runner.getSolrClient();
+ final var status = CoreAdminRequest.getCoreStatus("corex", true, client);
+ String dataDirectory = status.dataDir;
+ dataDir = Path.of(dataDirectory);
+ assertTrue(Files.exists(dataDir));
Path subHome = solrHomeDirectory.resolve("corex").resolve("conf");
Path top = SolrTestCaseJ4.TEST_HOME().resolve("collection1").resolve("conf");
diff --git a/solr/core/src/test/org/apache/solr/handler/admin/HealthCheckHandlerTest.java b/solr/core/src/test/org/apache/solr/handler/admin/HealthCheckHandlerTest.java
index 96cb2f4c425..4fadec44fef 100644
--- a/solr/core/src/test/org/apache/solr/handler/admin/HealthCheckHandlerTest.java
+++ b/solr/core/src/test/org/apache/solr/handler/admin/HealthCheckHandlerTest.java
@@ -74,14 +74,13 @@ public class HealthCheckHandlerTest extends SolrCloudTestCase {
genericHealthcheck.process(cluster.getSolrClient()).getResponse().get(CommonParams.STATUS));
// positive check that our exiting "healthy" node works with direct http client
- try (SolrClient solrClient =
- getHttpSolrClient(cluster.getJettySolrRunner(0).getBaseUrl().toString())) {
- assertEquals(CommonParams.OK, runHealthcheckWithClient(solrClient).getNodeStatus());
- }
+ assertEquals(
+ CommonParams.OK,
+ runHealthcheckWithClient(cluster.getJettySolrRunner(0).getSolrClient()).getNodeStatus());
// successfully create a dummy collection
- try (SolrClient solrClient =
- getHttpSolrClient(cluster.getJettySolrRunner(0).getBaseUrl().toString())) {
+ try {
+ SolrClient solrClient = cluster.getJettySolrRunner(0).getSolrClient();
CollectionAdminResponse collectionAdminResponse =
CollectionAdminRequest.createCollection("test", "_default", 1, 1)
.withProperty("solr.directoryFactory", "solr.StandardDirectoryFactory")
@@ -95,7 +94,8 @@ public class HealthCheckHandlerTest extends SolrCloudTestCase {
// add a new node for the purpose of negative testing
JettySolrRunner newJetty = cluster.startJettySolrRunner();
- try (SolrClient solrClient = getHttpSolrClient(newJetty.getBaseUrl().toString())) {
+ try {
+ SolrClient solrClient = newJetty.getSolrClient();
// positive check that our (new) "healthy" node works with direct http client
final var response = runHealthcheckWithClient(solrClient);
@@ -115,22 +115,17 @@ public class HealthCheckHandlerTest extends SolrCloudTestCase {
// (redundant) positive check that our (previously) exiting "healthy" node (still) works
// after getting negative results from our broken node and failed core container
- try (SolrClient solrClient =
- getHttpSolrClient(cluster.getJettySolrRunner(0).getBaseUrl().toString())) {
-
- assertEquals(CommonParams.OK, runHealthcheckWithClient(solrClient).getNodeStatus());
- }
+ assertEquals(
+ CommonParams.OK,
+ runHealthcheckWithClient(cluster.getJettySolrRunner(0).getSolrClient()).getNodeStatus());
}
@Test
public void testHealthCheckHandlerSolrJ() throws IOException, SolrServerException {
// positive check of a HealthCheckRequest using http client
HealthCheckRequest req = new HealthCheckRequest();
- try (SolrClient solrClient =
- getHttpSolrClient(cluster.getJettySolrRunner(0).getBaseUrl().toString())) {
- HealthCheckResponse rsp = req.process(solrClient);
- assertEquals(CommonParams.OK, rsp.getNodeStatus());
- }
+ HealthCheckResponse rsp = req.process(cluster.getJettySolrRunner(0).getSolrClient());
+ assertEquals(CommonParams.OK, rsp.getNodeStatus());
}
/**
@@ -148,9 +143,10 @@ public class HealthCheckHandlerTest extends SolrCloudTestCase {
@Test
public void testV1FailureResponseIncludesStatusField() throws Exception {
JettySolrRunner newJetty = cluster.startJettySolrRunner();
- try (SolrClient solrClient = getHttpSolrClient(newJetty.getBaseUrl().toString())) {
+ try {
// Sanity check: the new node is initially healthy.
- assertEquals(CommonParams.OK, runHealthcheckWithClient(solrClient).getNodeStatus());
+ assertEquals(
+ CommonParams.OK, runHealthcheckWithClient(newJetty.getSolrClient()).getNodeStatus());
String nodeName = newJetty.getCoreContainer().getZkController().getNodeName();
diff --git a/solr/core/src/test/org/apache/solr/handler/admin/LukeHandlerCloudTest.java b/solr/core/src/test/org/apache/solr/handler/admin/LukeHandlerCloudTest.java
index c9ddbabe2bb..ed418d1621e 100644
--- a/solr/core/src/test/org/apache/solr/handler/admin/LukeHandlerCloudTest.java
+++ b/solr/core/src/test/org/apache/solr/handler/admin/LukeHandlerCloudTest.java
@@ -137,13 +137,12 @@ public class LukeHandlerCloudTest extends SolrCloudTestCase {
String targetSliceName = null;
for (Slice slice : docColl.getSlices()) {
Replica leader = slice.getLeader();
- try (SolrClient client = getHttpSolrClient(leader)) {
- SolrQuery q = new SolrQuery("id:target");
- q.set(DISTRIB, "false");
- QueryResponse qr = client.query(q);
- if (qr.getResults().getNumFound() > 0) {
- targetSliceName = slice.getName();
- }
+ SolrClient client = cluster.getSolrClient(leader);
+ SolrQuery q = new SolrQuery("id:target");
+ q.set(DISTRIB, "false");
+ QueryResponse qr = client.query(q);
+ if (qr.getResults().getNumFound() > 0) {
+ targetSliceName = slice.getName();
}
}
assertNotNull("target doc should exist on a shard", targetSliceName);
@@ -153,14 +152,14 @@ public class LukeHandlerCloudTest extends SolrCloudTestCase {
for (Slice slice : docColl.getSlices()) {
if (!slice.getName().equals(targetSliceName)) {
Replica leader = slice.getLeader();
- try (SolrClient client = getHttpSolrClient(leader)) {
- SolrQuery q = new SolrQuery("*:*");
- q.setRows(1);
- q.set(DISTRIB, "false");
- QueryResponse qr = client.query(q);
- assertTrue("other shard should have seed docs", qr.getResults().getNumFound() > 0);
- otherDocId = (String) qr.getResults().getFirst().getFieldValue("id");
- }
+ SolrClient client = cluster.getSolrClient(leader);
+ SolrQuery q = new SolrQuery("*:*");
+ q.setRows(1);
+ q.set(DISTRIB, "false");
+ QueryResponse qr = client.query(q);
+ assertTrue("other shard should have seed docs", qr.getResults().getNumFound() > 0);
+ otherDocId = (String) qr.getResults().getFirst().getFieldValue("id");
+
break;
}
}
diff --git a/solr/core/src/test/org/apache/solr/handler/component/UpdateLogCloudTest.java b/solr/core/src/test/org/apache/solr/handler/component/UpdateLogCloudTest.java
index fcc0efde3ba..cf44fc09300 100644
--- a/solr/core/src/test/org/apache/solr/handler/component/UpdateLogCloudTest.java
+++ b/solr/core/src/test/org/apache/solr/handler/component/UpdateLogCloudTest.java
@@ -22,6 +22,7 @@ import java.util.Deque;
import java.util.List;
import java.util.stream.Collectors;
import org.apache.solr.client.solrj.SolrClient;
+import org.apache.solr.client.solrj.jetty.HttpJettySolrClient;
import org.apache.solr.client.solrj.request.CollectionAdminRequest;
import org.apache.solr.client.solrj.request.QueryRequest;
import org.apache.solr.client.solrj.request.UpdateRequest;
@@ -90,7 +91,10 @@ public class UpdateLogCloudTest extends SolrCloudTestCase {
.equals(getCollectionState(COLLECTION).getLeader("shard1").getBaseUrl())) {
specialIdx = solrClients.size();
}
- solrClients.add(jettySolrRunner.newClient());
+ // own clients on purpose: this test stops and restarts a node, which the runner's
+ // cached client does not survive
+ solrClients.add(
+ new HttpJettySolrClient.Builder(jettySolrRunner.getBaseUrl().toString()).build());
}
new UpdateRequest()
diff --git a/solr/core/src/test/org/apache/solr/metrics/SolrMetricsIntegrationTest.java b/solr/core/src/test/org/apache/solr/metrics/SolrMetricsIntegrationTest.java
index ad9bcf5a479..78120c4ed55 100644
--- a/solr/core/src/test/org/apache/solr/metrics/SolrMetricsIntegrationTest.java
+++ b/solr/core/src/test/org/apache/solr/metrics/SolrMetricsIntegrationTest.java
@@ -123,31 +123,30 @@ public class SolrMetricsIntegrationTest extends SolrTestCaseJ4 {
reader, "solr_zk_ops", baseLabels.merge(Labels.of("ops", type))));
}
- try (SolrClient solrClient = j.newClient()) {
- assertNotNull(solrClient);
- HttpClient httpClient = j.getSolrClient().getHttpClient();
- var initialChildFetches =
- SolrMetricTestUtils.getCounterDatapoint(reader, "solr_zk_get_children_ops", baseLabels)
- .getValue();
- var initialExistsOp =
- SolrMetricTestUtils.getCounterDatapoint(
- reader, "solr_zk_ops", baseLabels.merge(Labels.of("ops", "exists")))
- .getValue();
+ SolrClient solrClient = j.getSolrClient();
+ assertNotNull(solrClient);
+ HttpClient httpClient = j.getSolrClient().getHttpClient();
+ var initialChildFetches =
+ SolrMetricTestUtils.getCounterDatapoint(reader, "solr_zk_get_children_ops", baseLabels)
+ .getValue();
+ var initialExistsOp =
+ SolrMetricTestUtils.getCounterDatapoint(
+ reader, "solr_zk_ops", baseLabels.merge(Labels.of("ops", "exists")))
+ .getValue();
- // Send GET request to trigger some metrics
- httpClient.GET(j.getBaseURLV2() + "/cluster/zookeeper/children/live_nodes");
+ // Send GET request to trigger some metrics
+ httpClient.GET(j.getBaseURLV2() + "/cluster/zookeeper/children/live_nodes");
- var childFetches =
- SolrMetricTestUtils.getCounterDatapoint(reader, "solr_zk_get_children_ops", baseLabels)
- .getValue();
- var existsOp =
- SolrMetricTestUtils.getCounterDatapoint(
- reader, "solr_zk_ops", builder.label("ops", "exists").build())
- .getValue();
+ var childFetches =
+ SolrMetricTestUtils.getCounterDatapoint(reader, "solr_zk_get_children_ops", baseLabels)
+ .getValue();
+ var existsOp =
+ SolrMetricTestUtils.getCounterDatapoint(
+ reader, "solr_zk_ops", builder.label("ops", "exists").build())
+ .getValue();
- assertTrue(childFetches - initialChildFetches >= 1.0);
- assertTrue(existsOp - initialExistsOp >= 4.0);
- }
+ assertTrue(childFetches - initialChildFetches >= 1.0);
+ assertTrue(existsOp - initialExistsOp >= 4.0);
cluster.shutdown();
}
diff --git a/solr/core/src/test/org/apache/solr/response/TestPrometheusResponseWriter.java b/solr/core/src/test/org/apache/solr/response/TestPrometheusResponseWriter.java
index 610b7267cbe..3c6032df129 100644
--- a/solr/core/src/test/org/apache/solr/response/TestPrometheusResponseWriter.java
+++ b/solr/core/src/test/org/apache/solr/response/TestPrometheusResponseWriter.java
@@ -68,47 +68,46 @@ public class TestPrometheusResponseWriter extends SolrTestCaseJ4 {
params.set("wt", "prometheus");
var req = new MetricsRequest(params); // response parser set in MetricsRequest constructor
- try (SolrClient adminClient = getHttpSolrClient(solrTestRule.getBaseUrl())) {
- NamedList<Object> res = adminClient.request(req);
- String output = InputStreamResponseParser.consumeResponseToString(res);
-
- Set<String> seenTypeInfo = new HashSet<>();
-
- List<String> filteredResponse =
- output
- .lines()
- .filter(
- line -> {
- if (!line.startsWith("#")) {
- return true;
- }
- assertTrue(
- "Prometheus exposition format cannot have duplicate TYPE information",
- seenTypeInfo.add(line));
- return false;
- })
- .toList();
- filteredResponse.forEach(
- (actualMetric) -> {
- String actualValue;
- if (actualMetric.contains("}")) {
- actualValue = actualMetric.substring(actualMetric.lastIndexOf("} ") + 1);
- } else {
- actualValue = actualMetric.split(" ")[1];
- }
- if (actualMetric.startsWith("target_info")) {
- // Skip standard OTEL metric
- return;
- }
- assertTrue("All metrics should start with 'solr_'", actualMetric.startsWith("solr_"));
- try {
- Float.parseFloat(actualValue);
- } catch (NumberFormatException e) {
- log.warn("Prometheus value not a parsable float");
- assertTrue(VALID_PROMETHEUS_VALUES.contains(actualValue));
- }
- });
- }
+ SolrClient adminClient = solrTestRule.getAdminClient();
+ NamedList<Object> res = adminClient.request(req);
+ String output = InputStreamResponseParser.consumeResponseToString(res);
+
+ Set<String> seenTypeInfo = new HashSet<>();
+
+ List<String> filteredResponse =
+ output
+ .lines()
+ .filter(
+ line -> {
+ if (!line.startsWith("#")) {
+ return true;
+ }
+ assertTrue(
+ "Prometheus exposition format cannot have duplicate TYPE information",
+ seenTypeInfo.add(line));
+ return false;
+ })
+ .toList();
+ filteredResponse.forEach(
+ (actualMetric) -> {
+ String actualValue;
+ if (actualMetric.contains("}")) {
+ actualValue = actualMetric.substring(actualMetric.lastIndexOf("} ") + 1);
+ } else {
+ actualValue = actualMetric.split(" ")[1];
+ }
+ if (actualMetric.startsWith("target_info")) {
+ // Skip standard OTEL metric
+ return;
+ }
+ assertTrue("All metrics should start with 'solr_'", actualMetric.startsWith("solr_"));
+ try {
+ Float.parseFloat(actualValue);
+ } catch (NumberFormatException e) {
+ log.warn("Prometheus value not a parsable float");
+ assertTrue(VALID_PROMETHEUS_VALUES.contains(actualValue));
+ }
+ });
}
@Test
@@ -119,15 +118,14 @@ public class TestPrometheusResponseWriter extends SolrTestCaseJ4 {
req.addHeader("Accept", "application/openmetrics-text;version=1.0.0");
- try (SolrClient adminClient = getHttpSolrClient(solrTestRule.getBaseUrl())) {
- NamedList<Object> res = adminClient.request(req);
+ SolrClient adminClient = solrTestRule.getAdminClient();
+ NamedList<Object> res = adminClient.request(req);
- try (InputStream in = (InputStream) res.get(STREAM_KEY)) {
- String output = new String(in.readAllBytes(), StandardCharsets.UTF_8);
- assertTrue(
- "Should use OpenMetrics format when Accept header is set",
- output.trim().endsWith("# EOF"));
- }
+ try (InputStream in = (InputStream) res.get(STREAM_KEY)) {
+ String output = new String(in.readAllBytes(), StandardCharsets.UTF_8);
+ assertTrue(
+ "Should use OpenMetrics format when Accept header is set",
+ output.trim().endsWith("# EOF"));
}
}
@@ -137,15 +135,14 @@ public class TestPrometheusResponseWriter extends SolrTestCaseJ4 {
req.setResponseParser(new InputStreamResponseParser("openmetrics"));
- try (SolrClient adminClient = getHttpSolrClient(solrTestRule.getBaseUrl())) {
- NamedList<Object> res = adminClient.request(req);
+ SolrClient adminClient = solrTestRule.getAdminClient();
+ NamedList<Object> res = adminClient.request(req);
- try (InputStream in = (InputStream) res.get(STREAM_KEY)) {
- String output = new String(in.readAllBytes(), StandardCharsets.UTF_8);
- assertTrue(
- "Should use OpenMetrics format when wt=openmetrics is set",
- output.trim().endsWith("# EOF"));
- }
+ try (InputStream in = (InputStream) res.get(STREAM_KEY)) {
+ String output = new String(in.readAllBytes(), StandardCharsets.UTF_8);
+ assertTrue(
+ "Should use OpenMetrics format when wt=openmetrics is set",
+ output.trim().endsWith("# EOF"));
}
}
@@ -155,15 +152,14 @@ public class TestPrometheusResponseWriter extends SolrTestCaseJ4 {
req.setResponseParser(new InputStreamResponseParser("prometheus"));
- try (SolrClient adminClient = getHttpSolrClient(solrTestRule.getBaseUrl())) {
- NamedList<Object> res = adminClient.request(req);
+ SolrClient adminClient = solrTestRule.getAdminClient();
+ NamedList<Object> res = adminClient.request(req);
- try (InputStream in = (InputStream) res.get(STREAM_KEY)) {
- String output = new String(in.readAllBytes(), StandardCharsets.UTF_8);
- assertFalse(
- "Should use Prometheus format when wt=prometheus is set",
- output.trim().endsWith("# EOF"));
- }
+ try (InputStream in = (InputStream) res.get(STREAM_KEY)) {
+ String output = new String(in.readAllBytes(), StandardCharsets.UTF_8);
+ assertFalse(
+ "Should use Prometheus format when wt=prometheus is set",
+ output.trim().endsWith("# EOF"));
}
}
@@ -173,15 +169,14 @@ public class TestPrometheusResponseWriter extends SolrTestCaseJ4 {
req.setResponseParser(new InputStreamResponseParser(null));
- try (SolrClient adminClient = getHttpSolrClient(solrTestRule.getBaseUrl())) {
- NamedList<Object> res = adminClient.request(req);
+ SolrClient adminClient = solrTestRule.getAdminClient();
+ NamedList<Object> res = adminClient.request(req);
- try (InputStream in = (InputStream) res.get(STREAM_KEY)) {
- String output = new String(in.readAllBytes(), StandardCharsets.UTF_8);
- assertFalse(
- "Should default to Prometheus format when no wt parameter is set",
- output.trim().endsWith("# EOF"));
- }
+ try (InputStream in = (InputStream) res.get(STREAM_KEY)) {
+ String output = new String(in.readAllBytes(), StandardCharsets.UTF_8);
+ assertFalse(
+ "Should default to Prometheus format when no wt parameter is set",
+ output.trim().endsWith("# EOF"));
}
}
@@ -191,12 +186,11 @@ public class TestPrometheusResponseWriter extends SolrTestCaseJ4 {
req.setResponseParser(new InputStreamResponseParser("unknownFormat"));
- try (SolrClient adminClient = getHttpSolrClient(solrTestRule.getBaseUrl())) {
- NamedList<Object> res = adminClient.request(req);
- InputStream stream = (InputStream) res.get("stream");
- if (stream != null) stream.close();
- // Unknown wt parameter should return a 400 error
- assertEquals(400, res.get("responseStatus"));
- }
+ SolrClient adminClient = solrTestRule.getAdminClient();
+ NamedList<Object> res = adminClient.request(req);
+ InputStream stream = (InputStream) res.get("stream");
+ if (stream != null) stream.close();
+ // Unknown wt parameter should return a 400 error
+ assertEquals(400, res.get("responseStatus"));
}
}
diff --git a/solr/core/src/test/org/apache/solr/response/TestRawTransformer.java b/solr/core/src/test/org/apache/solr/response/TestRawTransformer.java
index 0190653249b..1fff683d95a 100644
--- a/solr/core/src/test/org/apache/solr/response/TestRawTransformer.java
+++ b/solr/core/src/test/org/apache/solr/response/TestRawTransformer.java
@@ -62,13 +62,13 @@ public class TestRawTransformer extends SolrCloudTestCase {
initStandalone();
JSR.start();
if (random().nextBoolean()) {
- CLIENT = JSR.newClient();
+ CLIENT = JSR.getSolrClient();
} else {
CLIENT = new EmbeddedSolrServer(JSR.getCoreContainer(), null);
}
} else {
initCloud();
- CLIENT = JSR.newClient();
+ CLIENT = JSR.getSolrClient();
JSR = null;
}
initIndex();
diff --git a/solr/core/src/test/org/apache/solr/schema/ManagedSchemaRoundRobinCloudTest.java b/solr/core/src/test/org/apache/solr/schema/ManagedSchemaRoundRobinCloudTest.java
index 2b770f7f23c..bd75970eca2 100644
--- a/solr/core/src/test/org/apache/solr/schema/ManagedSchemaRoundRobinCloudTest.java
+++ b/solr/core/src/test/org/apache/solr/schema/ManagedSchemaRoundRobinCloudTest.java
@@ -55,23 +55,16 @@ public class ManagedSchemaRoundRobinCloudTest extends SolrCloudTestCase {
@Test
public void testAddFieldsRoundRobin() throws Exception {
List<SolrClient> clients = new ArrayList<>(NUM_SHARDS);
- try {
- for (int shardNum = 0; shardNum < NUM_SHARDS; ++shardNum) {
- clients.add(
- getHttpSolrClient(cluster.getJettySolrRunners().get(shardNum).getBaseUrl().toString()));
- }
- int shardNum = 0;
- for (int fieldNum = 0; fieldNum < NUM_FIELDS_TO_ADD; ++fieldNum) {
- addField(
- clients.get(shardNum),
- keyValueArrayToMap("name", FIELD_PREFIX + fieldNum, "type", "string"));
- if (++shardNum == NUM_SHARDS) {
- shardNum = 0;
- }
- }
- } finally {
- for (int shardNum = 0; shardNum < NUM_SHARDS; ++shardNum) {
- clients.get(shardNum).close();
+ for (int shardNum = 0; shardNum < NUM_SHARDS; ++shardNum) {
+ clients.add(cluster.getJettySolrRunners().get(shardNum).getSolrClient());
+ }
+ int shardNum = 0;
+ for (int fieldNum = 0; fieldNum < NUM_FIELDS_TO_ADD; ++fieldNum) {
+ addField(
+ clients.get(shardNum),
+ keyValueArrayToMap("name", FIELD_PREFIX + fieldNum, "type", "string"));
+ if (++shardNum == NUM_SHARDS) {
+ shardNum = 0;
}
}
}
diff --git a/solr/core/src/test/org/apache/solr/search/TestCoordinatorRole.java b/solr/core/src/test/org/apache/solr/search/TestCoordinatorRole.java
index 053fb9e4d7c..3019cf48fd6 100644
--- a/solr/core/src/test/org/apache/solr/search/TestCoordinatorRole.java
+++ b/solr/core/src/test/org/apache/solr/search/TestCoordinatorRole.java
@@ -35,7 +35,6 @@ import java.util.function.Consumer;
import java.util.stream.Collectors;
import org.apache.solr.client.solrj.SolrClient;
import org.apache.solr.client.solrj.impl.CloudSolrClient;
-import org.apache.solr.client.solrj.jetty.HttpJettySolrClient;
import org.apache.solr.client.solrj.request.CollectionAdminRequest;
import org.apache.solr.client.solrj.request.QueryRequest;
import org.apache.solr.client.solrj.request.SolrQuery;
@@ -219,225 +218,224 @@ public class TestCoordinatorRole extends SolrCloudTestCase {
}
assertNotNull(nrtJetty);
assertNotNull(pullJetty);
- try (SolrClient client = pullJetty.newClient()) {
- client.add(COLL, sid);
- client.commit(COLL);
- assertEquals(
- nrtCore,
- getHostCoreName(
- COLL, qaJettyBase, p -> p.add(ShardParams.SHARDS_PREFERENCE, "replica.type:NRT")));
- assertEquals(
- pullCore,
- getHostCoreName(
- COLL, qaJettyBase, p -> p.add(ShardParams.SHARDS_PREFERENCE, "replica.type:PULL")));
- // Now , kill NRT jetty
- JettySolrRunner nrtJettyF = nrtJetty;
- JettySolrRunner pullJettyF = pullJetty;
- Random r = random();
- final long establishBaselineMs = r.nextInt(1000);
- final long nrtDowntimeMs = r.nextInt(10000);
- // NOTE: for `pullServiceTimeMs`, it can't be super-short. This is just to simplify our
- // indexing code,
- // based on the fact that our indexing is based on a PULL-node client.
- final long pullServiceTimeMs = 1000 + (long) r.nextInt(9000);
- Future<?> jettyManipulationFuture =
- executor.submit(
- () -> {
- // we manipulate the jetty instances in a separate thread to more closely mimic
- // the behavior we'd see irl.
+ SolrClient client = pullJetty.getSolrClient();
+ client.add(COLL, sid);
+ client.commit(COLL);
+ assertEquals(
+ nrtCore,
+ getHostCoreName(
+ COLL, qaJettyBase, p -> p.add(ShardParams.SHARDS_PREFERENCE, "replica.type:NRT")));
+ assertEquals(
+ pullCore,
+ getHostCoreName(
+ COLL, qaJettyBase, p -> p.add(ShardParams.SHARDS_PREFERENCE, "replica.type:PULL")));
+ // Now , kill NRT jetty
+ JettySolrRunner nrtJettyF = nrtJetty;
+ JettySolrRunner pullJettyF = pullJetty;
+ Random r = random();
+ final long establishBaselineMs = r.nextInt(1000);
+ final long nrtDowntimeMs = r.nextInt(10000);
+ // NOTE: for `pullServiceTimeMs`, it can't be super-short. This is just to simplify our
+ // indexing code,
+ // based on the fact that our indexing is based on a PULL-node client.
+ final long pullServiceTimeMs = 1000 + (long) r.nextInt(9000);
+ Future<?> jettyManipulationFuture =
+ executor.submit(
+ () -> {
+ // we manipulate the jetty instances in a separate thread to more closely mimic
+ // the behavior we'd see irl.
+ try {
+ Thread.sleep(establishBaselineMs);
+ log.info("stopping NRT jetty ...");
+ nrtJettyF.stop();
+ log.info("NRT jetty stopped.");
+ Thread.sleep(nrtDowntimeMs); // let NRT be down for a while
+ log.info("restarting NRT jetty ...");
+ nrtJettyF.start(true);
+ log.info("NRT jetty restarted.");
+ // once NRT is back up, we expect PULL to continue serving until the TTL on ZK
+ // state used for query request routing has expired (60s). But here we force a
+ // return to NRT by stopping the PULL replica after a brief delay ...
+ Thread.sleep(pullServiceTimeMs);
+ log.info("stopping PULL jetty ...");
+ pullJettyF.stop();
+ log.info("PULL jetty stopped.");
+ } catch (Exception e) {
+ throw new RuntimeException(e);
+ }
+ });
+ String hostCore;
+ long start = new Date().getTime();
+ long individualRequestStart = start;
+ int count = 0;
+ while (nrtCore.equals(
+ hostCore =
+ getHostCoreName(
+ COLL,
+ qaJettyBase,
+ p -> p.add(ShardParams.SHARDS_PREFERENCE, "replica.type:NRT")))) {
+ count++;
+ Thread.sleep(100);
+ individualRequestStart = new Date().getTime();
+ }
+ long now = new Date().getTime();
+ log.info(
+ "phase1 NRT queries count={}, overall_duration={}, baseline_expected_overall_duration={}, switch-to-pull_duration={}",
+ count,
+ now - start,
+ establishBaselineMs,
+ now - individualRequestStart);
+ // default tolerance of 500ms below should suffice. Failover to PULL for this case should be
+ // very fast, because our QA-based client already knows both replicas are active, the index
+ // is stable, so the moment the client finds NRT is down it should be able to failover
+ // immediately and transparently to PULL.
+ assertEquals(
+ "when we break out of the NRT query loop, should be b/c routed to PULL",
+ pullCore,
+ hostCore);
+ SolrInputDocument d = new SolrInputDocument();
+ d.addField("id", "345");
+ d.addField("desc_s", "Another Document");
+ // attempts to add another doc while NRT is down should fail, then eventually succeed when
+ // NRT comes back up
+ count = 0;
+ start = new Date().getTime();
+ individualRequestStart = start;
+ for (; ; ) {
+ try {
+ client.add(COLL, d);
+ client.commit(COLL);
+ break;
+ } catch (SolrException ex) {
+ // we expect these until nrtJetty is back up.
+ count++;
+ Thread.sleep(100);
+ }
+ individualRequestStart = new Date().getTime();
+ }
+ now = new Date().getTime();
+ log.info(
+ "successfully added another doc; duration: {}, overall_duration={}, baseline_expected_overall_duration={}, exception_count={}",
+ now - individualRequestStart,
+ now - start,
+ nrtDowntimeMs,
+ count);
+ // NRT replica is back up, registered as available with Zk, and availability info has been
+ // pulled down by our PULL-replica-based `client`, forwarded indexing command to NRT,
+ // index/commit completed. All of this accounts for the 3000ms tolerance allowed for below.
+ // This is not a strict value, and if it causes failures regularly we should feel free to
+ // increase the tolerance; but it's meant to provide a stable baseline from which to detect
+ // regressions.
+ count = 0;
+ start = new Date().getTime();
+ individualRequestStart = start;
+ while (pullCore.equals(
+ hostCore =
+ getHostCoreName(
+ COLL,
+ qaJettyBase,
+ p -> {
+ p.set(CommonParams.Q, "id:345");
+ p.add(ShardParams.SHARDS_PREFERENCE, "replica.type:NRT");
+ }))) {
+ count++;
+ Thread.sleep(100);
+ individualRequestStart = new Date().getTime();
+ }
+ now = new Date().getTime();
+ log.info(
+ "query retries between NRT index-ready and query-ready: {}; overall_duration={}; baseline_expected_overall_duration={}; failover-request_duration={}",
+ count,
+ now - start,
+ pullServiceTimeMs,
+ now - individualRequestStart);
+ assertEquals(nrtCore, hostCore);
+ // allow any exceptions to propagate
+ jettyManipulationFuture.get();
+
+ // next phase: just toggle a bunch
+ // TODO: could separate this out into a different test method, but this should suffice for
+ // now
+ pullJetty.start(true);
+ waitForState(
+ "Pull jetty replicas didn't become active in time",
+ COLL,
+ ((liveNodes, collectionState) ->
+ collectionState.getReplicasOnNode(pullJettyF.getNodeName()).stream()
+ .allMatch(rep -> rep.getState() == Replica.State.ACTIVE)));
+ AtomicBoolean done = new AtomicBoolean();
+ long runMinutes = 1;
+ long finishTimeMs =
+ new Date().getTime() + TimeUnit.MILLISECONDS.convert(runMinutes, TimeUnit.MINUTES);
+ JettySolrRunner[] jettys = new JettySolrRunner[] {pullJettyF, nrtJettyF};
+ Random threadRandom = new Random(r.nextInt());
+ Future<Integer> f =
+ executor.submit(
+ () -> {
+ int iteration = 0;
+ while (new Date().getTime() < finishTimeMs && !done.get()) {
+ int idx = iteration++ % jettys.length;
+ JettySolrRunner toManipulate = jettys[idx];
try {
- Thread.sleep(establishBaselineMs);
- log.info("stopping NRT jetty ...");
- nrtJettyF.stop();
- log.info("NRT jetty stopped.");
- Thread.sleep(nrtDowntimeMs); // let NRT be down for a while
- log.info("restarting NRT jetty ...");
- nrtJettyF.start(true);
- log.info("NRT jetty restarted.");
- // once NRT is back up, we expect PULL to continue serving until the TTL on ZK
- // state used for query request routing has expired (60s). But here we force a
- // return to NRT by stopping the PULL replica after a brief delay ...
- Thread.sleep(pullServiceTimeMs);
- log.info("stopping PULL jetty ...");
- pullJettyF.stop();
- log.info("PULL jetty stopped.");
+ int serveTogetherTime = threadRandom.nextInt(7000);
+ int downTime = threadRandom.nextInt(7000);
+ log.info("serving together for {}ms", serveTogetherTime);
+ Thread.sleep(serveTogetherTime);
+ log.info("stopping {} ...", idx);
+ toManipulate.stop();
+ log.info("stopped {}.", idx);
+ Thread.sleep(downTime);
+ log.info("restarting {} ...", idx);
+ toManipulate.start(true);
+ log.info("restarted {}.", idx);
+ waitForState(
+ toManipulate.getNodeName() + " replicas didn't become active in time",
+ COLL,
+ ((liveNodes, collectionState) ->
+ collectionState.getReplicasOnNode(toManipulate.getNodeName()).stream()
+ .allMatch(rep -> rep.getState() == Replica.State.ACTIVE)));
} catch (Exception e) {
throw new RuntimeException(e);
}
- });
- String hostCore;
- long start = new Date().getTime();
- long individualRequestStart = start;
- int count = 0;
- while (nrtCore.equals(
- hostCore =
- getHostCoreName(
- COLL,
- qaJettyBase,
- p -> p.add(ShardParams.SHARDS_PREFERENCE, "replica.type:NRT")))) {
- count++;
- Thread.sleep(100);
- individualRequestStart = new Date().getTime();
- }
- long now = new Date().getTime();
- log.info(
- "phase1 NRT queries count={}, overall_duration={}, baseline_expected_overall_duration={}, switch-to-pull_duration={}",
- count,
- now - start,
- establishBaselineMs,
- now - individualRequestStart);
- // default tolerance of 500ms below should suffice. Failover to PULL for this case should be
- // very fast, because our QA-based client already knows both replicas are active, the index
- // is stable, so the moment the client finds NRT is down it should be able to failover
- // immediately and transparently to PULL.
- assertEquals(
- "when we break out of the NRT query loop, should be b/c routed to PULL",
- pullCore,
- hostCore);
- SolrInputDocument d = new SolrInputDocument();
- d.addField("id", "345");
- d.addField("desc_s", "Another Document");
- // attempts to add another doc while NRT is down should fail, then eventually succeed when
- // NRT comes back up
- count = 0;
- start = new Date().getTime();
- individualRequestStart = start;
- for (; ; ) {
- try {
- client.add(COLL, d);
- client.commit(COLL);
- break;
- } catch (SolrException ex) {
- // we expect these until nrtJetty is back up.
- count++;
- Thread.sleep(100);
+ }
+ done.set(true);
+ return iteration;
+ });
+ count = 0;
+ start = new Date().getTime();
+ try {
+ do {
+ if (pullCore.equals(
+ getHostCoreName(
+ COLL,
+ qaJettyBase,
+ p -> {
+ p.set(CommonParams.Q, "id:345");
+ p.add(ShardParams.SHARDS_PREFERENCE, "replica.type:NRT");
+ }))) {
+ done.set(true);
}
- individualRequestStart = new Date().getTime();
- }
- now = new Date().getTime();
- log.info(
- "successfully added another doc; duration: {}, overall_duration={}, baseline_expected_overall_duration={}, exception_count={}",
- now - individualRequestStart,
- now - start,
- nrtDowntimeMs,
- count);
- // NRT replica is back up, registered as available with Zk, and availability info has been
- // pulled down by our PULL-replica-based `client`, forwarded indexing command to NRT,
- // index/commit completed. All of this accounts for the 3000ms tolerance allowed for below.
- // This is not a strict value, and if it causes failures regularly we should feel free to
- // increase the tolerance; but it's meant to provide a stable baseline from which to detect
- // regressions.
- count = 0;
- start = new Date().getTime();
- individualRequestStart = start;
- while (pullCore.equals(
- hostCore =
- getHostCoreName(
- COLL,
- qaJettyBase,
- p -> {
- p.set(CommonParams.Q, "id:345");
- p.add(ShardParams.SHARDS_PREFERENCE, "replica.type:NRT");
- }))) {
count++;
Thread.sleep(100);
- individualRequestStart = new Date().getTime();
+ } while (!done.get());
+ } finally {
+ final String result;
+ if (done.getAndSet(true)) {
+ result = "Success";
+ } else {
+ // not yet set to done, completed abnormally (exception will be thrown beyond `finally`
+ // block)
+ result = "Failure";
}
- now = new Date().getTime();
+ Integer toggleCount = f.get();
+ long secondsDuration =
+ TimeUnit.SECONDS.convert(new Date().getTime() - start, TimeUnit.MILLISECONDS);
log.info(
- "query retries between NRT index-ready and query-ready: {}; overall_duration={}; baseline_expected_overall_duration={}; failover-request_duration={}",
- count,
- now - start,
- pullServiceTimeMs,
- now - individualRequestStart);
- assertEquals(nrtCore, hostCore);
- // allow any exceptions to propagate
- jettyManipulationFuture.get();
-
- // next phase: just toggle a bunch
- // TODO: could separate this out into a different test method, but this should suffice for
- // now
- pullJetty.start(true);
- waitForState(
- "Pull jetty replicas didn't become active in time",
- COLL,
- ((liveNodes, collectionState) ->
- collectionState.getReplicasOnNode(pullJettyF.getNodeName()).stream()
- .allMatch(rep -> rep.getState() == Replica.State.ACTIVE)));
- AtomicBoolean done = new AtomicBoolean();
- long runMinutes = 1;
- long finishTimeMs =
- new Date().getTime() + TimeUnit.MILLISECONDS.convert(runMinutes, TimeUnit.MINUTES);
- JettySolrRunner[] jettys = new JettySolrRunner[] {pullJettyF, nrtJettyF};
- Random threadRandom = new Random(r.nextInt());
- Future<Integer> f =
- executor.submit(
- () -> {
- int iteration = 0;
- while (new Date().getTime() < finishTimeMs && !done.get()) {
- int idx = iteration++ % jettys.length;
- JettySolrRunner toManipulate = jettys[idx];
- try {
- int serveTogetherTime = threadRandom.nextInt(7000);
- int downTime = threadRandom.nextInt(7000);
- log.info("serving together for {}ms", serveTogetherTime);
- Thread.sleep(serveTogetherTime);
- log.info("stopping {} ...", idx);
- toManipulate.stop();
- log.info("stopped {}.", idx);
- Thread.sleep(downTime);
- log.info("restarting {} ...", idx);
- toManipulate.start(true);
- log.info("restarted {}.", idx);
- waitForState(
- toManipulate.getNodeName() + " replicas didn't become active in time",
- COLL,
- ((liveNodes, collectionState) ->
- collectionState.getReplicasOnNode(toManipulate.getNodeName()).stream()
- .allMatch(rep -> rep.getState() == Replica.State.ACTIVE)));
- } catch (Exception e) {
- throw new RuntimeException(e);
- }
- }
- done.set(true);
- return iteration;
- });
- count = 0;
- start = new Date().getTime();
- try {
- do {
- if (pullCore.equals(
- getHostCoreName(
- COLL,
- qaJettyBase,
- p -> {
- p.set(CommonParams.Q, "id:345");
- p.add(ShardParams.SHARDS_PREFERENCE, "replica.type:NRT");
- }))) {
- done.set(true);
- }
- count++;
- Thread.sleep(100);
- } while (!done.get());
- } finally {
- final String result;
- if (done.getAndSet(true)) {
- result = "Success";
- } else {
- // not yet set to done, completed abnormally (exception will be thrown beyond `finally`
- // block)
- result = "Failure";
- }
- Integer toggleCount = f.get();
- long secondsDuration =
- TimeUnit.SECONDS.convert(new Date().getTime() - start, TimeUnit.MILLISECONDS);
- log.info(
- "{}! {} seconds, {} toggles, {} requests served",
- result,
- secondsDuration,
- toggleCount,
- count);
- }
+ "{}! {} seconds, {} toggles, {} requests served",
+ result,
+ secondsDuration,
+ toggleCount,
+ count);
}
} finally {
try {
@@ -463,31 +461,31 @@ public class TestCoordinatorRole extends SolrCloudTestCase {
CommonParams.JAVABIN);
p.accept(q);
SolrDocumentList docs = null;
- try (SolrClient solrClient = new HttpJettySolrClient.Builder(qaNode).build()) {
- for (int i = 0; i < 100; i++) {
- try {
- QueryResponse queryResponse = solrClient.query(COLL, q);
- docs = queryResponse.getResults();
- assertNotNull("Docs should not be null. Query response was: " + queryResponse, docs);
- if (docs.size() > 0) {
- found = true;
- break;
- }
- } catch (SolrException ex) {
- // we know we're doing tricky things that might cause transient errors
- // TODO: all these query requests go to the QA node -- should QA propagate internal
- // request errors to the external client (and the external client retry?) or should QA
- // attempt to failover transparently in the event of an error?
- if (i < 5) {
- log.info("swallowing transient error", ex);
- } else {
- log.error("only expect actual _errors_ within a small window (e.g. 500ms)", ex);
- fail("initial error time threshold exceeded");
- }
+ SolrClient solrClient = cluster.getJetty(qaNode).getSolrClient();
+ for (int i = 0; i < 100; i++) {
+ try {
+ QueryResponse queryResponse = solrClient.query(COLL, q);
+ docs = queryResponse.getResults();
+ assertNotNull("Docs should not be null. Query response was: " + queryResponse, docs);
+ if (docs.size() > 0) {
+ found = true;
+ break;
+ }
+ } catch (SolrException ex) {
+ // we know we're doing tricky things that might cause transient errors
+ // TODO: all these query requests go to the QA node -- should QA propagate internal
+ // request errors to the external client (and the external client retry?) or should QA
+ // attempt to failover transparently in the event of an error?
+ if (i < 5) {
+ log.info("swallowing transient error", ex);
+ } else {
+ log.error("only expect actual _errors_ within a small window (e.g. 500ms)", ex);
+ fail("initial error time threshold exceeded");
}
- Thread.sleep(100);
}
+ Thread.sleep(100);
}
+
assertTrue(found);
return (String) docs.get(0).getFieldValue("_core_");
}
diff --git a/solr/core/src/test/org/apache/solr/search/facet/TestCloudJSONFacetJoinDomain.java b/solr/core/src/test/org/apache/solr/search/facet/TestCloudJSONFacetJoinDomain.java
index 1d0c4aaccf1..42534ae8b72 100644
--- a/solr/core/src/test/org/apache/solr/search/facet/TestCloudJSONFacetJoinDomain.java
+++ b/solr/core/src/test/org/apache/solr/search/facet/TestCloudJSONFacetJoinDomain.java
@@ -124,7 +124,7 @@ public class TestCloudJSONFacetJoinDomain extends SolrCloudTestCase {
waitForRecoveriesToFinish(CLOUD_CLIENT);
for (JettySolrRunner jetty : cluster.getJettySolrRunners())
- CLIENTS.add(getHttpSolrClient(jetty.getBaseUrl().toString(), COLLECTION_NAME));
+ CLIENTS.add(jetty.newSolrClient(COLLECTION_NAME));
final int numDocs = atLeast(100);
for (int id = 0; id < numDocs; id++) {
diff --git a/solr/core/src/test/org/apache/solr/search/facet/TestCloudJSONFacetSKG.java b/solr/core/src/test/org/apache/solr/search/facet/TestCloudJSONFacetSKG.java
index 3695c732e50..1b21d8d7d24 100644
--- a/solr/core/src/test/org/apache/solr/search/facet/TestCloudJSONFacetSKG.java
+++ b/solr/core/src/test/org/apache/solr/search/facet/TestCloudJSONFacetSKG.java
@@ -151,7 +151,7 @@ public class TestCloudJSONFacetSKG extends SolrCloudTestCase {
waitForRecoveriesToFinish(CLOUD_CLIENT);
for (JettySolrRunner jetty : cluster.getJettySolrRunners()) {
- CLIENTS.add(getHttpSolrClient(jetty.getBaseUrl().toString(), COLLECTION_NAME));
+ CLIENTS.add(jetty.newSolrClient(COLLECTION_NAME));
}
final int numDocs = atLeast(100);
diff --git a/solr/core/src/test/org/apache/solr/search/facet/TestCloudJSONFacetSKGEquiv.java b/solr/core/src/test/org/apache/solr/search/facet/TestCloudJSONFacetSKGEquiv.java
index deec286fd21..5446cea0945 100644
--- a/solr/core/src/test/org/apache/solr/search/facet/TestCloudJSONFacetSKGEquiv.java
+++ b/solr/core/src/test/org/apache/solr/search/facet/TestCloudJSONFacetSKGEquiv.java
@@ -142,7 +142,7 @@ public class TestCloudJSONFacetSKGEquiv extends SolrCloudTestCase {
waitForRecoveriesToFinish(CLOUD_CLIENT);
for (JettySolrRunner jetty : cluster.getJettySolrRunners()) {
- CLIENTS.add(getHttpSolrClient(jetty.getBaseUrl().toString(), COLLECTION_NAME));
+ CLIENTS.add(jetty.newSolrClient(COLLECTION_NAME));
}
final int numDocs = atLeast(100);
diff --git a/solr/core/src/test/org/apache/solr/search/stats/TestDistribIDF.java b/solr/core/src/test/org/apache/solr/search/stats/TestDistribIDF.java
index 4f63b16f52f..0522942543c 100644
--- a/solr/core/src/test/org/apache/solr/search/stats/TestDistribIDF.java
+++ b/solr/core/src/test/org/apache/solr/search/stats/TestDistribIDF.java
@@ -108,34 +108,31 @@ public class TestDistribIDF extends SolrTestCaseJ4 {
// Test against all nodes
for (JettySolrRunner jettySolrRunner : solrCluster.getJettySolrRunners()) {
- try (SolrClient solrClient = getHttpSolrClient(jettySolrRunner.getBaseUrl().toString())) {
- try (SolrClient solrClient_local =
- getHttpSolrClient(jettySolrRunner.getBaseUrl().toString())) {
-
- SolrQuery query = new SolrQuery("cat:football");
- query.setFields("*,score");
- QueryResponse queryResponse = solrClient.query("onecollection", query);
- assertEquals(2, queryResponse.getResults().getNumFound());
- float score1 = (float) queryResponse.getResults().get(0).get("score");
- float score2 = (float) queryResponse.getResults().get(1).get("score");
- assertEquals(
- "Doc1 score=" + score1 + " Doc2 score=" + score2, 0, Float.compare(score1, score2));
-
- query = new SolrQuery("cat:football");
- query.setShowDebugInfo(true);
- query.setFields("*,score");
- queryResponse = solrClient_local.query("onecollection_local", query);
- assertEquals(2, queryResponse.getResults().getNumFound());
- assertEquals("2", queryResponse.getResults().get(0).get("id"));
- assertEquals("1", queryResponse.getResults().get(1).get("id"));
- float score1_local = (float) queryResponse.getResults().get(0).get("score");
- float score2_local = (float) queryResponse.getResults().get(1).get("score");
- assertEquals(
- "Doc1 score=" + score1_local + " Doc2 score=" + score2_local,
- 1,
- Float.compare(score1_local, score2_local));
- }
- }
+ SolrClient solrClient = jettySolrRunner.getSolrClient();
+ SolrClient solrClient_local = jettySolrRunner.getSolrClient();
+
+ SolrQuery query = new SolrQuery("cat:football");
+ query.setFields("*,score");
+ QueryResponse queryResponse = solrClient.query("onecollection", query);
+ assertEquals(2, queryResponse.getResults().getNumFound());
+ float score1 = (float) queryResponse.getResults().get(0).get("score");
+ float score2 = (float) queryResponse.getResults().get(1).get("score");
+ assertEquals(
+ "Doc1 score=" + score1 + " Doc2 score=" + score2, 0, Float.compare(score1, score2));
+
+ query = new SolrQuery("cat:football");
+ query.setShowDebugInfo(true);
+ query.setFields("*,score");
+ queryResponse = solrClient_local.query("onecollection_local", query);
+ assertEquals(2, queryResponse.getResults().getNumFound());
+ assertEquals("2", queryResponse.getResults().get(0).get("id"));
+ assertEquals("1", queryResponse.getResults().get(1).get("id"));
+ float score1_local = (float) queryResponse.getResults().get(0).get("score");
+ float score2_local = (float) queryResponse.getResults().get(1).get("score");
+ assertEquals(
+ "Doc1 score=" + score1_local + " Doc2 score=" + score2_local,
+ 1,
+ Float.compare(score1_local, score2_local));
}
}
@@ -159,34 +156,30 @@ public class TestDistribIDF extends SolrTestCaseJ4 {
// Test against all nodes
for (JettySolrRunner jettySolrRunner : solrCluster.getJettySolrRunners()) {
-
- try (SolrClient solrClient = getHttpSolrClient(jettySolrRunner.getBaseUrl().toString())) {
-
- try (SolrClient solrClient_local =
- getHttpSolrClient(jettySolrRunner.getBaseUrl().toString())) {
- SolrQuery query = new SolrQuery("cat:football");
- query.setFields("*,score").add("collection", "collection1,collection2");
- QueryResponse queryResponse = solrClient.query("collection1", query);
- assertEquals(2, queryResponse.getResults().getNumFound());
- float score1 = (float) queryResponse.getResults().get(0).get("score");
- float score2 = (float) queryResponse.getResults().get(1).get("score");
- assertEquals(
- "Doc1 score=" + score1 + " Doc2 score=" + score2, 0, Float.compare(score1, score2));
-
- query = new SolrQuery("cat:football");
- query.setFields("*,score").add("collection", "collection1_local,collection2_local");
- queryResponse = solrClient_local.query("collection1_local", query);
- assertEquals(2, queryResponse.getResults().getNumFound());
- assertEquals("2", queryResponse.getResults().get(0).get("id"));
- assertEquals("1", queryResponse.getResults().get(1).get("id"));
- float score1_local = (float) queryResponse.getResults().get(0).get("score");
- float score2_local = (float) queryResponse.getResults().get(1).get("score");
- assertEquals(
- "Doc1 score=" + score1_local + " Doc2 score=" + score2_local,
- 1,
- Float.compare(score1_local, score2_local));
- }
- }
+ SolrClient solrClient = jettySolrRunner.getSolrClient();
+ SolrClient solrClient_local = jettySolrRunner.getSolrClient();
+
+ SolrQuery query = new SolrQuery("cat:football");
+ query.setFields("*,score").add("collection", "collection1,collection2");
+ QueryResponse queryResponse = solrClient.query("collection1", query);
+ assertEquals(2, queryResponse.getResults().getNumFound());
+ float score1 = (float) queryResponse.getResults().get(0).get("score");
+ float score2 = (float) queryResponse.getResults().get(1).get("score");
+ assertEquals(
+ "Doc1 score=" + score1 + " Doc2 score=" + score2, 0, Float.compare(score1, score2));
+
+ query = new SolrQuery("cat:football");
+ query.setFields("*,score").add("collection", "collection1_local,collection2_local");
+ queryResponse = solrClient_local.query("collection1_local", query);
+ assertEquals(2, queryResponse.getResults().getNumFound());
+ assertEquals("2", queryResponse.getResults().get(0).get("id"));
+ assertEquals("1", queryResponse.getResults().get(1).get("id"));
+ float score1_local = (float) queryResponse.getResults().get(0).get("score");
+ float score2_local = (float) queryResponse.getResults().get(1).get("score");
+ assertEquals(
+ "Doc1 score=" + score1_local + " Doc2 score=" + score2_local,
+ 1,
+ Float.compare(score1_local, score2_local));
}
}
diff --git a/solr/core/src/test/org/apache/solr/security/BasicAuthIntegrationTest.java b/solr/core/src/test/org/apache/solr/security/BasicAuthIntegrationTest.java
index 9684d5447cf..71c1da0c463 100644
--- a/solr/core/src/test/org/apache/solr/security/BasicAuthIntegrationTest.java
+++ b/solr/core/src/test/org/apache/solr/security/BasicAuthIntegrationTest.java
@@ -176,7 +176,8 @@ public class BasicAuthIntegrationTest extends SolrCloudAuthTestCase {
executeCommand(httpClient, baseUrl + authzPrefix, command, "solr", "SolrRocks");
assertAuthMetricsMinimums(5, 2, 3, 0, 0, 0);
- baseUrl = cluster.getBaseUrl(random());
+ final JettySolrRunner secondRandomJetty = cluster.getRandomJetty(random());
+ baseUrl = secondRandomJetty.getBaseUrl().toString();
verifySecurityStatus(
httpClient, baseUrl + authzPrefix, "authorization/user-role/harry", NOT_NULL_PREDICATE, 20);
@@ -210,11 +211,10 @@ public class BasicAuthIntegrationTest extends SolrCloudAuthTestCase {
CollectionAdminRequest.Reload reload = CollectionAdminRequest.reloadCollection(COLLECTION);
- try (var solrClient2 = getHttpSolrClient(baseUrl)) {
- expectThrows(RemoteSolrException.class, () -> solrClient2.request(reload));
- reload.setMethod(SolrRequest.METHOD.POST);
- expectThrows(RemoteSolrException.class, () -> solrClient2.request(reload));
- }
+ var solrClient2 = secondRandomJetty.getSolrClient();
+ expectThrows(RemoteSolrException.class, () -> solrClient2.request(reload));
+ reload.setMethod(SolrRequest.METHOD.POST);
+ expectThrows(RemoteSolrException.class, () -> solrClient2.request(reload));
cluster
.getSolrClient()
.request(
@@ -247,7 +247,7 @@ public class BasicAuthIntegrationTest extends SolrCloudAuthTestCase {
// Test for SOLR-12514. Create a new jetty . This jetty does not have the collection.
// Make a request to that jetty and it should fail
JettySolrRunner aNewJetty = cluster.startJettySolrRunner();
- SolrClient aNewClient = aNewJetty.newClient();
+ SolrClient aNewClient = aNewJetty.getSolrClient();
UpdateRequest delQuery = null;
delQuery = new UpdateRequest().deleteByQuery("*:*");
delQuery.setBasicAuthCredentials("harry", "HarryIsUberCool");
@@ -261,7 +261,6 @@ public class BasicAuthIntegrationTest extends SolrCloudAuthTestCase {
});
assertEquals(401, e.code()); // Authentication failed
} finally {
- aNewClient.close();
cluster.stopJettySolrRunner(aNewJetty);
}
diff --git a/solr/core/src/test/org/apache/solr/security/BasicAuthStandaloneTest.java b/solr/core/src/test/org/apache/solr/security/BasicAuthStandaloneTest.java
index 63c83c13579..bdd26321183 100644
--- a/solr/core/src/test/org/apache/solr/security/BasicAuthStandaloneTest.java
+++ b/solr/core/src/test/org/apache/solr/security/BasicAuthStandaloneTest.java
@@ -26,7 +26,6 @@ import java.nio.file.Path;
import java.util.Base64;
import java.util.Map;
import org.apache.solr.SolrTestCaseJ4;
-import org.apache.solr.client.solrj.SolrClient;
import org.apache.solr.common.params.MapSolrParams;
import org.apache.solr.common.util.Utils;
import org.apache.solr.embedded.JettySolrRunner;
@@ -70,66 +69,58 @@ public class BasicAuthStandaloneTest extends SolrTestCaseJ4 {
String authcPrefix = "/admin/authentication";
String authzPrefix = "/admin/authorization";
- HttpClient httpClient;
- SolrClient solrClient = null;
- try {
- httpClient = jetty.getSolrClient().getHttpClient();
- String baseUrl = buildUrl(jetty.getLocalPort());
- solrClient = getHttpSolrClient(baseUrl);
+ var solrClient = jetty.getSolrClient();
+ HttpClient httpClient = solrClient.getHttpClient();
+ String baseUrl = buildUrl(jetty.getLocalPort());
- verifySecurityStatus(httpClient, baseUrl + authcPrefix, "/errorMessages", null, 20);
+ verifySecurityStatus(httpClient, baseUrl + authcPrefix, "/errorMessages", null, 20);
- // Write security.json locally. Should cause security to be initialized
- securityConfHandler.persistConf(
- new SecurityConfHandler.SecurityConfig()
- .setData(Utils.fromJSONString(STD_CONF.replace("'", "\""))));
- securityConfHandler.securityConfEdited();
- verifySecurityStatus(
- httpClient, baseUrl + authcPrefix, "authentication/class", "solr.BasicAuthPlugin", 20);
+ // Write security.json locally. Should cause security to be initialized
+ securityConfHandler.persistConf(
+ new SecurityConfHandler.SecurityConfig()
+ .setData(Utils.fromJSONString(STD_CONF.replace("'", "\""))));
+ securityConfHandler.securityConfEdited();
+ verifySecurityStatus(
+ httpClient, baseUrl + authcPrefix, "authentication/class", "solr.BasicAuthPlugin", 20);
- String command = "{\n" + "'set-user': {'harry':'HarryIsCool'}\n" + "}";
+ String command = "{\n" + "'set-user': {'harry':'HarryIsCool'}\n" + "}";
- doHttpPost(httpClient, baseUrl + authcPrefix, command, null, null, 401);
- verifySecurityStatus(httpClient, baseUrl + authcPrefix, "authentication.enabled", "true", 20);
+ doHttpPost(httpClient, baseUrl + authcPrefix, command, null, null, 401);
+ verifySecurityStatus(httpClient, baseUrl + authcPrefix, "authentication.enabled", "true", 20);
- command = "{\n" + "'set-user': {'harry':'HarryIsUberCool'}\n" + "}";
+ command = "{\n" + "'set-user': {'harry':'HarryIsUberCool'}\n" + "}";
- doHttpPost(httpClient, baseUrl + authcPrefix, command, "solr", "SolrRocks");
- verifySecurityStatus(
- httpClient,
- baseUrl + authcPrefix,
- "authentication/credentials/harry",
- NOT_NULL_PREDICATE,
- 20);
-
- // Read file from SOLR_HOME and verify that it contains our new user
- assertTrue(
- new String(Utils.toJSON(securityConfHandler.getSecurityConfig(false).getData()), UTF_8)
- .contains("harry"));
-
- // Edit authorization
+ doHttpPost(httpClient, baseUrl + authcPrefix, command, "solr", "SolrRocks");
+ verifySecurityStatus(
+ httpClient,
+ baseUrl + authcPrefix,
+ "authentication/credentials/harry",
+ NOT_NULL_PREDICATE,
+ 20);
+
+ // Read file from SOLR_HOME and verify that it contains our new user
+ assertTrue(
+ new String(Utils.toJSON(securityConfHandler.getSecurityConfig(false).getData()), UTF_8)
+ .contains("harry"));
+
+ // Edit authorization
+ verifySecurityStatus(
+ httpClient, baseUrl + authzPrefix, "authorization/permissions[1]/role", null, 20);
+ doHttpPost(
+ httpClient,
+ baseUrl + authzPrefix,
+ "{'set-permission': {'name': 'update', 'role':'updaterole'}}",
+ "solr",
+ "SolrRocks");
+ command = "{\n" + "'set-permission': {'name': 'read', 'role':'solr'}\n" + "}";
+ doHttpPost(httpClient, baseUrl + authzPrefix, command, "solr", "SolrRocks");
+ try {
+ solrClient.query("collection1", new MapSolrParams(Map.of("q", "foo")));
+ fail("Should return a 401 response");
+ } catch (Exception e) {
+ // Test that the second doPost request to /security/authorization went through
verifySecurityStatus(
- httpClient, baseUrl + authzPrefix, "authorization/permissions[1]/role", null, 20);
- doHttpPost(
- httpClient,
- baseUrl + authzPrefix,
- "{'set-permission': {'name': 'update', 'role':'updaterole'}}",
- "solr",
- "SolrRocks");
- command = "{\n" + "'set-permission': {'name': 'read', 'role':'solr'}\n" + "}";
- doHttpPost(httpClient, baseUrl + authzPrefix, command, "solr", "SolrRocks");
- try {
- solrClient.query("collection1", new MapSolrParams(Map.of("q", "foo")));
- fail("Should return a 401 response");
- } catch (Exception e) {
- // Test that the second doPost request to /security/authorization went through
- verifySecurityStatus(
- httpClient, baseUrl + authzPrefix, "authorization/permissions[2]/role", "solr", 20);
- }
- } finally {
- if (solrClient != null) {
- solrClient.close();
- }
+ httpClient, baseUrl + authzPrefix, "authorization/permissions[2]/role", "solr", 20);
}
}
diff --git a/solr/core/src/test/org/apache/solr/security/MultiAuthPluginTest.java b/solr/core/src/test/org/apache/solr/security/MultiAuthPluginTest.java
index 9cb8d774989..3076b0f3277 100644
--- a/solr/core/src/test/org/apache/solr/security/MultiAuthPluginTest.java
+++ b/solr/core/src/test/org/apache/solr/security/MultiAuthPluginTest.java
@@ -38,7 +38,6 @@ import java.util.Objects;
import java.util.function.Predicate;
import java.util.stream.Collectors;
import org.apache.solr.SolrTestCaseJ4;
-import org.apache.solr.client.solrj.SolrClient;
import org.apache.solr.common.SolrException;
import org.apache.solr.common.params.CommonParams;
import org.apache.solr.common.util.CommandOperation;
@@ -85,175 +84,166 @@ public class MultiAuthPluginTest extends SolrTestCaseJ4 {
final String user = "admin";
final String pass = "SolrRocks";
- HttpClient httpClient = null;
- SolrClient solrClient = null;
- try {
- httpClient = jetty.getSolrClient().getHttpClient();
- String baseUrl = buildUrl(jetty.getLocalPort());
- solrClient = getHttpSolrClient(baseUrl);
-
- verifySecurityStatus(httpClient, baseUrl + authcPrefix, "/errorMessages", null, 5);
-
- // Initialize security.json with multiple auth plugins configured
- String multiAuthPluginSecurityJson =
- Files.readString(
- TEST_PATH().resolve("security").resolve("multi_auth_plugin_security.json"),
- StandardCharsets.UTF_8);
- securityConfHandler.persistConf(
- new SecurityConfHandler.SecurityConfig()
- .setData(Utils.fromJSONString(multiAuthPluginSecurityJson)));
- securityConfHandler.securityConfEdited();
-
- // verify "WWW-Authenticate" headers are returned
- verifyWWWAuthenticateHeaders(httpClient, baseUrl);
-
- verifySecurityStatus(
- httpClient,
- baseUrl + authcPrefix,
- "authentication/class",
- "solr.MultiAuthPlugin",
- 5,
- user,
- pass);
- verifySecurityStatus(
- httpClient,
- baseUrl + authzPrefix,
- "authorization/class",
- "solr.MultiAuthRuleBasedAuthorizationPlugin",
- 5,
- user,
- pass);
-
- // anonymous requests are blocked by all plugins
- int statusCode = doHttpGetAnonymous(httpClient, baseUrl + CommonParams.SYSTEM_INFO_PATH);
- assertEquals("anonymous get succeeded but should not have", 401, statusCode);
- // update blockUnknown to allow anonymous for the basic plugin
- String command = "{\n" + "'set-property': { 'basic': {'blockUnknown':false} }\n" + "}";
- doHttpPost(httpClient, baseUrl + authcPrefix, command, user, pass, 200);
- statusCode = doHttpGetAnonymous(httpClient, baseUrl + CommonParams.SYSTEM_INFO_PATH);
- assertEquals("anonymous get failed but should have succeeded", 200, statusCode);
-
- // For the multi-auth plugin, every command is wrapped with an object that identifies the
- // "scheme"
- command = "{\n" + "'set-user': {'harry':'HarryIsCool'}\n" + "}";
- // no scheme identified!
- doHttpPost(httpClient, baseUrl + authcPrefix, command, user, pass, 400);
-
- command = "{\n" + "'set-user': { 'foo': {'harry':'HarryIsCool'} }\n" + "}";
- // no "foo" scheme configured
- doHttpPost(httpClient, baseUrl + authcPrefix, command, user, pass, 400);
-
- command = "{\n" + "'set-user': { 'basic': {'harry':'HarryIsCool'} }\n" + "}";
-
- // no creds, should fail ...
- doHttpPost(httpClient, baseUrl + authcPrefix, command, null, null, 401);
- // with basic creds, should pass ...
- doHttpPost(httpClient, baseUrl + authcPrefix, command, user, pass, 200);
- verifySecurityStatus(
- httpClient,
- baseUrl + authcPrefix,
- "authentication/schemes[0]/credentials/harry",
- NOT_NULL_PREDICATE,
- 5,
- user,
- pass);
-
- // authz command but missing the "scheme" wrapper
- command = "{\n" + "'set-user-role': {'harry':['users']}\n" + "}";
- doHttpPost(httpClient, baseUrl + authzPrefix, command, user, pass, 400);
-
- // add "harry" to the "users" role ...
- command = "{\n" + "'set-user-role': { 'basic': {'harry':['users']} }\n" + "}";
- doHttpPost(httpClient, baseUrl + authzPrefix, command, user, pass, 200);
- verifySecurityStatus(
- httpClient,
- baseUrl + authzPrefix,
- "authorization/schemes[0]/user-role/harry",
- NOT_NULL_PREDICATE,
- 5,
- user,
- pass);
-
- // give the users role a custom permission
- verifySecurityStatus(
- httpClient,
- baseUrl + authzPrefix,
- "authorization/permissions[6]",
- NULL_PREDICATE,
- 5,
- user,
- pass);
- command =
- "{\n"
- + "'set-permission': { 'name':'k8s-zk', 'role':'users', 'collection':null, 'path':'/admin/zookeeper/status' }\n"
- + "}";
- doHttpPost(httpClient, baseUrl + authzPrefix, command, user, pass, 200);
- verifySecurityStatus(
- httpClient,
- baseUrl + authzPrefix,
- "authorization/permissions[6]/path",
- new ExpectedValuePredicate("/admin/zookeeper/status"),
- 5,
- user,
- pass);
-
- command =
- "{\n"
- + "'update-permission': { 'index':'7', 'name':'k8s-zk', 'role':'users', 'collection':null, 'path':'/admin/zookeeper/status2' }\n"
- + "}";
- doHttpPost(httpClient, baseUrl + authzPrefix, command, user, pass, 200);
- verifySecurityStatus(
- httpClient,
- baseUrl + authzPrefix,
- "authorization/permissions[6]/path",
- new ExpectedValuePredicate("/admin/zookeeper/status2"),
- 5,
- user,
- pass);
-
- // delete the permission
- command = "{\n" + "'delete-permission': 7\n" + "}";
- doHttpPost(httpClient, baseUrl + authzPrefix, command, user, pass, 200);
- verifySecurityStatus(
- httpClient,
- baseUrl + authzPrefix,
- "authorization/permissions[6]",
- NULL_PREDICATE,
- 5,
- user,
- pass);
-
- // delete the user
- command = "{\n" + "'delete-user': { 'basic': 'harry' }\n" + "}";
-
- doHttpPost(httpClient, baseUrl + authcPrefix, command, user, pass, 200);
- verifySecurityStatus(
- httpClient,
- baseUrl + authcPrefix,
- "authentication/schemes[0]/credentials/harry",
- NULL_PREDICATE,
- 5,
- user,
- pass);
-
- // update the property on the mock (just to test routing to the mock plugin)
- command = "{\n" + "'set-property': { 'mock': { 'blockUnknown':false } }\n" + "}";
-
- doHttpPostWithHeader(
- httpClient, baseUrl + authcPrefix, command, "Authorization", "mock foo", 200);
- verifySecurityStatus(
- httpClient,
- baseUrl + authcPrefix,
- "authentication/schemes[1]/blockUnknown",
- new ExpectedValuePredicate(Boolean.FALSE),
- 5,
- user,
- pass);
- } finally {
- if (solrClient != null) {
- solrClient.close();
- }
- }
+ HttpClient httpClient = jetty.getSolrClient().getHttpClient();
+ String baseUrl = buildUrl(jetty.getLocalPort());
+
+ verifySecurityStatus(httpClient, baseUrl + authcPrefix, "/errorMessages", null, 5);
+
+ // Initialize security.json with multiple auth plugins configured
+ String multiAuthPluginSecurityJson =
+ Files.readString(
+ TEST_PATH().resolve("security").resolve("multi_auth_plugin_security.json"),
+ StandardCharsets.UTF_8);
+ securityConfHandler.persistConf(
+ new SecurityConfHandler.SecurityConfig()
+ .setData(Utils.fromJSONString(multiAuthPluginSecurityJson)));
+ securityConfHandler.securityConfEdited();
+
+ // verify "WWW-Authenticate" headers are returned
+ verifyWWWAuthenticateHeaders(httpClient, baseUrl);
+
+ verifySecurityStatus(
+ httpClient,
+ baseUrl + authcPrefix,
+ "authentication/class",
+ "solr.MultiAuthPlugin",
+ 5,
+ user,
+ pass);
+ verifySecurityStatus(
+ httpClient,
+ baseUrl + authzPrefix,
+ "authorization/class",
+ "solr.MultiAuthRuleBasedAuthorizationPlugin",
+ 5,
+ user,
+ pass);
+
+ // anonymous requests are blocked by all plugins
+ int statusCode = doHttpGetAnonymous(httpClient, baseUrl + CommonParams.SYSTEM_INFO_PATH);
+ assertEquals("anonymous get succeeded but should not have", 401, statusCode);
+ // update blockUnknown to allow anonymous for the basic plugin
+ String command = "{\n" + "'set-property': { 'basic': {'blockUnknown':false} }\n" + "}";
+ doHttpPost(httpClient, baseUrl + authcPrefix, command, user, pass, 200);
+ statusCode = doHttpGetAnonymous(httpClient, baseUrl + CommonParams.SYSTEM_INFO_PATH);
+ assertEquals("anonymous get failed but should have succeeded", 200, statusCode);
+
+ // For the multi-auth plugin, every command is wrapped with an object that identifies the
+ // "scheme"
+ command = "{\n" + "'set-user': {'harry':'HarryIsCool'}\n" + "}";
+ // no scheme identified!
+ doHttpPost(httpClient, baseUrl + authcPrefix, command, user, pass, 400);
+
+ command = "{\n" + "'set-user': { 'foo': {'harry':'HarryIsCool'} }\n" + "}";
+ // no "foo" scheme configured
+ doHttpPost(httpClient, baseUrl + authcPrefix, command, user, pass, 400);
+
+ command = "{\n" + "'set-user': { 'basic': {'harry':'HarryIsCool'} }\n" + "}";
+
+ // no creds, should fail ...
+ doHttpPost(httpClient, baseUrl + authcPrefix, command, null, null, 401);
+ // with basic creds, should pass ...
+ doHttpPost(httpClient, baseUrl + authcPrefix, command, user, pass, 200);
+ verifySecurityStatus(
+ httpClient,
+ baseUrl + authcPrefix,
+ "authentication/schemes[0]/credentials/harry",
+ NOT_NULL_PREDICATE,
+ 5,
+ user,
+ pass);
+
+ // authz command but missing the "scheme" wrapper
+ command = "{\n" + "'set-user-role': {'harry':['users']}\n" + "}";
+ doHttpPost(httpClient, baseUrl + authzPrefix, command, user, pass, 400);
+
+ // add "harry" to the "users" role ...
+ command = "{\n" + "'set-user-role': { 'basic': {'harry':['users']} }\n" + "}";
+ doHttpPost(httpClient, baseUrl + authzPrefix, command, user, pass, 200);
+ verifySecurityStatus(
+ httpClient,
+ baseUrl + authzPrefix,
+ "authorization/schemes[0]/user-role/harry",
+ NOT_NULL_PREDICATE,
+ 5,
+ user,
+ pass);
+
+ // give the users role a custom permission
+ verifySecurityStatus(
+ httpClient,
+ baseUrl + authzPrefix,
+ "authorization/permissions[6]",
+ NULL_PREDICATE,
+ 5,
+ user,
+ pass);
+ command =
+ "{\n"
+ + "'set-permission': { 'name':'k8s-zk', 'role':'users', 'collection':null, 'path':'/admin/zookeeper/status' }\n"
+ + "}";
+ doHttpPost(httpClient, baseUrl + authzPrefix, command, user, pass, 200);
+ verifySecurityStatus(
+ httpClient,
+ baseUrl + authzPrefix,
+ "authorization/permissions[6]/path",
+ new ExpectedValuePredicate("/admin/zookeeper/status"),
+ 5,
+ user,
+ pass);
+
+ command =
+ "{\n"
+ + "'update-permission': { 'index':'7', 'name':'k8s-zk', 'role':'users', 'collection':null, 'path':'/admin/zookeeper/status2' }\n"
+ + "}";
+ doHttpPost(httpClient, baseUrl + authzPrefix, command, user, pass, 200);
+ verifySecurityStatus(
+ httpClient,
+ baseUrl + authzPrefix,
+ "authorization/permissions[6]/path",
+ new ExpectedValuePredicate("/admin/zookeeper/status2"),
+ 5,
+ user,
+ pass);
+
+ // delete the permission
+ command = "{\n" + "'delete-permission': 7\n" + "}";
+ doHttpPost(httpClient, baseUrl + authzPrefix, command, user, pass, 200);
+ verifySecurityStatus(
+ httpClient,
+ baseUrl + authzPrefix,
+ "authorization/permissions[6]",
+ NULL_PREDICATE,
+ 5,
+ user,
+ pass);
+
+ // delete the user
+ command = "{\n" + "'delete-user': { 'basic': 'harry' }\n" + "}";
+
+ doHttpPost(httpClient, baseUrl + authcPrefix, command, user, pass, 200);
+ verifySecurityStatus(
+ httpClient,
+ baseUrl + authcPrefix,
+ "authentication/schemes[0]/credentials/harry",
+ NULL_PREDICATE,
+ 5,
+ user,
+ pass);
+
+ // update the property on the mock (just to test routing to the mock plugin)
+ command = "{\n" + "'set-property': { 'mock': { 'blockUnknown':false } }\n" + "}";
+
+ doHttpPostWithHeader(
+ httpClient, baseUrl + authcPrefix, command, "Authorization", "mock foo", 200);
+ verifySecurityStatus(
+ httpClient,
+ baseUrl + authcPrefix,
+ "authentication/schemes[1]/blockUnknown",
+ new ExpectedValuePredicate(Boolean.FALSE),
+ 5,
+ user,
+ pass);
}
@Test
@@ -261,40 +251,29 @@ public class MultiAuthPluginTest extends SolrTestCaseJ4 {
final String user = "admin";
final String pass = "SolrRocks";
- HttpClient httpClient = null;
- SolrClient solrClient = null;
- try {
- httpClient = jetty.getSolrClient().getHttpClient();
- String baseUrl = buildUrl(jetty.getLocalPort());
- solrClient = getHttpSolrClient(baseUrl);
-
- verifySecurityStatus(httpClient, baseUrl + authcPrefix, "/errorMessages", null, 5);
-
- // Initialize security.json with multiple xbasic auth and other configured
- String multiAuthPluginSecurityJson =
- Files.readString(
- TEST_PATH()
- .resolve("security")
- .resolve("multi_auth_plugin_with_xbasic_security.json"),
- StandardCharsets.UTF_8);
- securityConfHandler.persistConf(
- new SecurityConfHandler.SecurityConfig()
- .setData(Utils.fromJSONString(multiAuthPluginSecurityJson)));
- securityConfHandler.securityConfEdited();
-
- // verify "WWW-Authenticate" headers are returned
- verifyWWWAuthenticateHeaders(httpClient, baseUrl);
-
- // Command that does not update anything in the current config
- String command = "{ 'set-property': { 'xbasic': { 'blockUnknown': true } } }";
-
- // verify that clients can still use "Basic" scheme with xBasic scheme configured in MultiAuth
- doHttpPost(httpClient, baseUrl + authcPrefix, command, user, pass, 200);
- } finally {
- if (solrClient != null) {
- solrClient.close();
- }
- }
+ HttpClient httpClient = jetty.getSolrClient().getHttpClient();
+ String baseUrl = buildUrl(jetty.getLocalPort());
+
+ verifySecurityStatus(httpClient, baseUrl + authcPrefix, "/errorMessages", null, 5);
+
+ // Initialize security.json with multiple xbasic auth and other configured
+ String multiAuthPluginSecurityJson =
+ Files.readString(
+ TEST_PATH().resolve("security").resolve("multi_auth_plugin_with_xbasic_security.json"),
+ StandardCharsets.UTF_8);
+ securityConfHandler.persistConf(
+ new SecurityConfHandler.SecurityConfig()
+ .setData(Utils.fromJSONString(multiAuthPluginSecurityJson)));
+ securityConfHandler.securityConfEdited();
+
+ // verify "WWW-Authenticate" headers are returned
+ verifyWWWAuthenticateHeaders(httpClient, baseUrl);
+
+ // Command that does not update anything in the current config
+ String command = "{ 'set-property': { 'xbasic': { 'blockUnknown': true } } }";
+
+ // verify that clients can still use "Basic" scheme with xBasic scheme configured in MultiAuth
+ doHttpPost(httpClient, baseUrl + authcPrefix, command, user, pass, 200);
}
@Test
@@ -303,45 +282,36 @@ public class MultiAuthPluginTest extends SolrTestCaseJ4 {
final String xUser = "xadmin";
final String pass = "SolrRocks";
- HttpClient httpClient = null;
- SolrClient solrClient = null;
- try {
- httpClient = jetty.getSolrClient().getHttpClient();
- String baseUrl = buildUrl(jetty.getLocalPort());
- solrClient = getHttpSolrClient(baseUrl);
-
- verifySecurityStatus(httpClient, baseUrl + authcPrefix, "/errorMessages", null, 5);
-
- // Initialize security.json with basic and xbasic scheme
- String multiAuthPluginSecurityJson =
- Files.readString(
- TEST_PATH()
- .resolve("security")
- .resolve("multi_auth_plugin_with_basic_and_xbasic_security.json"),
- StandardCharsets.UTF_8);
- securityConfHandler.persistConf(
- new SecurityConfHandler.SecurityConfig()
- .setData(Utils.fromJSONString(multiAuthPluginSecurityJson)));
- securityConfHandler.securityConfEdited();
-
- // verify "WWW-Authenticate" headers are returned
- verifyWWWAuthenticateHeaders(httpClient, baseUrl);
-
- // Command that does not update anything in the current config
- String command = "{ 'set-property': { 'basic': { 'blockUnknown': true } } }";
-
- // verify that basic takes precedence over xbasic when both present
- doHttpPost(httpClient, baseUrl + authcPrefix, command, user, pass, 200);
-
- // Since both are present, xbasic will never be looked up if client does not send XBasic
- // as auth scheme, and using xBasic won't work with BasicAuthPlugin, so this security
- // configuration should return 401 as it resolves with the plugin that uses "basic" as scheme
- doHttpPost(httpClient, baseUrl + authcPrefix, command, xUser, pass, 401);
- } finally {
- if (solrClient != null) {
- solrClient.close();
- }
- }
+ HttpClient httpClient = jetty.getSolrClient().getHttpClient();
+ String baseUrl = buildUrl(jetty.getLocalPort());
+
+ verifySecurityStatus(httpClient, baseUrl + authcPrefix, "/errorMessages", null, 5);
+
+ // Initialize security.json with basic and xbasic scheme
+ String multiAuthPluginSecurityJson =
+ Files.readString(
+ TEST_PATH()
+ .resolve("security")
+ .resolve("multi_auth_plugin_with_basic_and_xbasic_security.json"),
+ StandardCharsets.UTF_8);
+ securityConfHandler.persistConf(
+ new SecurityConfHandler.SecurityConfig()
+ .setData(Utils.fromJSONString(multiAuthPluginSecurityJson)));
+ securityConfHandler.securityConfEdited();
+
+ // verify "WWW-Authenticate" headers are returned
+ verifyWWWAuthenticateHeaders(httpClient, baseUrl);
+
+ // Command that does not update anything in the current config
+ String command = "{ 'set-property': { 'basic': { 'blockUnknown': true } } }";
+
+ // verify that basic takes precedence over xbasic when both present
+ doHttpPost(httpClient, baseUrl + authcPrefix, command, user, pass, 200);
+
+ // Since both are present, xbasic will never be looked up if client does not send XBasic
+ // as auth scheme, and using xBasic won't work with BasicAuthPlugin, so this security
+ // configuration should return 401 as it resolves with the plugin that uses "basic" as scheme
+ doHttpPost(httpClient, baseUrl + authcPrefix, command, xUser, pass, 401);
}
@Test
@@ -349,40 +319,31 @@ public class MultiAuthPluginTest extends SolrTestCaseJ4 {
final String user = "admin";
final String pass = "SolrRocks";
- HttpClient httpClient = null;
- SolrClient solrClient = null;
- try {
- httpClient = jetty.getSolrClient().getHttpClient();
- String baseUrl = buildUrl(jetty.getLocalPort());
- solrClient = getHttpSolrClient(baseUrl);
-
- verifySecurityStatus(httpClient, baseUrl + authcPrefix, "/errorMessages", null, 5);
-
- // Initialize security.json with a single plugin configured
- String multiAuthPluginSecurityJson =
- Files.readString(
- TEST_PATH()
- .resolve("security")
- .resolve("multi_auth_plugin_with_basic_only_security.json"),
- StandardCharsets.UTF_8);
- securityConfHandler.persistConf(
- new SecurityConfHandler.SecurityConfig()
- .setData(Utils.fromJSONString(multiAuthPluginSecurityJson)));
- securityConfHandler.securityConfEdited();
-
- // verify "WWW-Authenticate" headers are returned
- verifyWWWAuthenticateHeaders(httpClient, baseUrl);
-
- // Command that does not update anything in the current config
- String command = "{ 'set-property': { 'basic': { 'blockUnknown': true } } }";
-
- // verify that a single plugin configuration is allowed and works
- doHttpPost(httpClient, baseUrl + authcPrefix, command, user, pass, 200);
- } finally {
- if (solrClient != null) {
- solrClient.close();
- }
- }
+ HttpClient httpClient = jetty.getSolrClient().getHttpClient();
+ String baseUrl = buildUrl(jetty.getLocalPort());
+
+ verifySecurityStatus(httpClient, baseUrl + authcPrefix, "/errorMessages", null, 5);
+
+ // Initialize security.json with a single plugin configured
+ String multiAuthPluginSecurityJson =
+ Files.readString(
+ TEST_PATH()
+ .resolve("security")
+ .resolve("multi_auth_plugin_with_basic_only_security.json"),
+ StandardCharsets.UTF_8);
+ securityConfHandler.persistConf(
+ new SecurityConfHandler.SecurityConfig()
+ .setData(Utils.fromJSONString(multiAuthPluginSecurityJson)));
+ securityConfHandler.securityConfEdited();
+
+ // verify "WWW-Authenticate" headers are returned
+ verifyWWWAuthenticateHeaders(httpClient, baseUrl);
+
+ // Command that does not update anything in the current config
+ String command = "{ 'set-property': { 'basic': { 'blockUnknown': true } } }";
+
+ // verify that a single plugin configuration is allowed and works
+ doHttpPost(httpClient, baseUrl + authcPrefix, command, user, pass, 200);
}
@Test
@@ -390,91 +351,74 @@ public class MultiAuthPluginTest extends SolrTestCaseJ4 {
final String user = "admin";
final String pass = "SolrRocks";
- HttpClient httpClient = null;
- SolrClient solrClient = null;
- try {
- httpClient = jetty.getSolrClient().getHttpClient();
- String baseUrl = buildUrl(jetty.getLocalPort());
- solrClient = getHttpSolrClient(baseUrl);
-
- verifySecurityStatus(httpClient, baseUrl + authcPrefix, "/errorMessages", null, 5);
-
- // Initialize security.json with a single plugin configured
- String multiAuthPluginSecurityJson =
- Files.readString(
- TEST_PATH()
- .resolve("security")
- .resolve("multi_auth_plugin_with_mock_and_basic_security.json"),
- StandardCharsets.UTF_8);
- securityConfHandler.persistConf(
- new SecurityConfHandler.SecurityConfig()
- .setData(Utils.fromJSONString(multiAuthPluginSecurityJson)));
- securityConfHandler.securityConfEdited();
-
- // verify "WWW-Authenticate" headers are returned
- verifyWWWAuthenticateHeaders(httpClient, baseUrl);
-
- // Command that does not update anything in the current config
- String command = "{ 'set-property': { 'basic': { 'blockUnknown': true } } }";
-
- // verify that the basic auth plugin works and is looked up as expected
- doHttpPost(httpClient, baseUrl + authcPrefix, command, user, pass, 200);
- } finally {
- if (solrClient != null) {
- solrClient.close();
- }
- }
+ HttpClient httpClient = jetty.getSolrClient().getHttpClient();
+ String baseUrl = buildUrl(jetty.getLocalPort());
+
+ verifySecurityStatus(httpClient, baseUrl + authcPrefix, "/errorMessages", null, 5);
+
+ // Initialize security.json with a single plugin configured
+ String multiAuthPluginSecurityJson =
+ Files.readString(
+ TEST_PATH()
+ .resolve("security")
+ .resolve("multi_auth_plugin_with_mock_and_basic_security.json"),
+ StandardCharsets.UTF_8);
+ securityConfHandler.persistConf(
+ new SecurityConfHandler.SecurityConfig()
+ .setData(Utils.fromJSONString(multiAuthPluginSecurityJson)));
+ securityConfHandler.securityConfEdited();
+
+ // verify "WWW-Authenticate" headers are returned
+ verifyWWWAuthenticateHeaders(httpClient, baseUrl);
+
+ // Command that does not update anything in the current config
+ String command = "{ 'set-property': { 'basic': { 'blockUnknown': true } } }";
+
+ // verify that the basic auth plugin works and is looked up as expected
+ doHttpPost(httpClient, baseUrl + authcPrefix, command, user, pass, 200);
}
@Test
public void testMultiAuthWithBasicPluginAndAjax() throws Exception {
- SolrClient solrClient = null;
+ var httpClient = jetty.getSolrClient().getHttpClient();
+ String baseUrl = buildUrl(jetty.getLocalPort());
+
+ verifySecurityStatus(httpClient, baseUrl + authcPrefix, "/errorMessages", null, 5);
+
+ // Initialize security.json with a single plugin configured
+ String multiAuthPluginSecurityJson =
+ Files.readString(
+ TEST_PATH().resolve("security").resolve("multi_auth_plugin_security.json"),
+ StandardCharsets.UTF_8);
+ securityConfHandler.persistConf(
+ new SecurityConfHandler.SecurityConfig()
+ .setData(Utils.fromJSONString(multiAuthPluginSecurityJson)));
+ securityConfHandler.securityConfEdited();
+
+ // Pretend to send unauthorized AJAX request
try {
- var httpClient = jetty.getSolrClient().getHttpClient();
- String baseUrl = buildUrl(jetty.getLocalPort());
- solrClient = getHttpSolrClient(baseUrl);
-
- verifySecurityStatus(httpClient, baseUrl + authcPrefix, "/errorMessages", null, 5);
-
- // Initialize security.json with a single plugin configured
- String multiAuthPluginSecurityJson =
- Files.readString(
- TEST_PATH().resolve("security").resolve("multi_auth_plugin_security.json"),
- StandardCharsets.UTF_8);
- securityConfHandler.persistConf(
- new SecurityConfHandler.SecurityConfig()
- .setData(Utils.fromJSONString(multiAuthPluginSecurityJson)));
- securityConfHandler.securityConfEdited();
-
- // Pretend to send unauthorized AJAX request
- try {
- var response =
- httpClient
- .newRequest(baseUrl + CommonParams.SYSTEM_INFO_PATH)
- .headers(h -> h.add("X-Requested-With", "XMLHttpRequest"))
- .send();
- assertEquals("Unauthorized response was expected", 401, response.getStatus());
-
- // Only first plugin is expected as response, which is also xBasic if BasicAuthPlugin
- List<String> actualSchemes = response.getHeaders().getValuesList("WWW-Authenticate");
-
- // Only the first scheme is expected for AJAX-Requests
- assertEquals("Only one scheme was expected", 1, actualSchemes.size());
-
- // In case of BasicAuthPlugin, xBasic should be returned if AJAX request sent and handled by
- // BasicAuthPlugin
- String expectedScheme = "xBasic realm=\"solr\"";
- assertEquals(
- "Mapped xBasic challenge expected from first plugin which is BasicAuthPlugin",
- expectedScheme,
- actualSchemes.getFirst());
- } catch (Exception e) {
- throw new RuntimeException(e);
- }
- } finally {
- if (solrClient != null) {
- solrClient.close();
- }
+ var response =
+ httpClient
+ .newRequest(baseUrl + CommonParams.SYSTEM_INFO_PATH)
+ .headers(h -> h.add("X-Requested-With", "XMLHttpRequest"))
+ .send();
+ assertEquals("Unauthorized response was expected", 401, response.getStatus());
+
+ // Only first plugin is expected as response, which is also xBasic if BasicAuthPlugin
+ List<String> actualSchemes = response.getHeaders().getValuesList("WWW-Authenticate");
+
+ // Only the first scheme is expected for AJAX-Requests
+ assertEquals("Only one scheme was expected", 1, actualSchemes.size());
+
+ // In case of BasicAuthPlugin, xBasic should be returned if AJAX request sent and handled by
+ // BasicAuthPlugin
+ String expectedScheme = "xBasic realm=\"solr\"";
+ assertEquals(
+ "Mapped xBasic challenge expected from first plugin which is BasicAuthPlugin",
+ expectedScheme,
+ actualSchemes.getFirst());
+ } catch (Exception e) {
+ throw new RuntimeException(e);
}
}
diff --git a/solr/core/src/test/org/apache/solr/update/DeleteByIdWithRouterFieldTest.java b/solr/core/src/test/org/apache/solr/update/DeleteByIdWithRouterFieldTest.java
index e879b3281bd..0d5e86ffd54 100644
--- a/solr/core/src/test/org/apache/solr/update/DeleteByIdWithRouterFieldTest.java
+++ b/solr/core/src/test/org/apache/solr/update/DeleteByIdWithRouterFieldTest.java
@@ -117,21 +117,19 @@ public class DeleteByIdWithRouterFieldTest extends SolrCloudTestCase {
final String shardName = entry.getKey();
final Slice slice = entry.getValue();
final Replica leader = entry.getValue().getLeader();
- try (SolrClient leaderClient = getHttpSolrClient(leader)) {
- final SolrDocumentList leaderResults = leaderClient.query(params).getResults();
- for (Replica replica : slice) {
- try (SolrClient replicaClient = getHttpSolrClient(replica)) {
- final SolrDocumentList replicaResults = replicaClient.query(params).getResults();
- assertEquals(
- "inconsistency w/leader: shard=" + shardName + "core=" + replica.getCoreName(),
- Set.of(),
- CloudInspectUtil.showDiff(
- leaderResults,
- replicaResults,
- shardName + " leader: " + leader.getCoreUrl(),
- shardName + ": " + replica.getCoreUrl()));
- }
- }
+ SolrClient leaderClient = cluster.getSolrClient(leader);
+ final SolrDocumentList leaderResults = leaderClient.query(params).getResults();
+ for (Replica replica : slice) {
+ SolrClient replicaClient = cluster.getSolrClient(replica);
+ final SolrDocumentList replicaResults = replicaClient.query(params).getResults();
+ assertEquals(
+ "inconsistency w/leader: shard=" + shardName + "core=" + replica.getCoreName(),
+ Set.of(),
+ CloudInspectUtil.showDiff(
+ leaderResults,
+ replicaResults,
+ shardName + " leader: " + leader.getCoreUrl(),
+ shardName + ": " + replica.getCoreUrl()));
}
}
}
diff --git a/solr/core/src/test/org/apache/solr/update/processor/TestCloudDeduplication.java b/solr/core/src/test/org/apache/solr/update/processor/TestCloudDeduplication.java
index 6c1dcc0fa8b..5c8b2f14043 100644
--- a/solr/core/src/test/org/apache/solr/update/processor/TestCloudDeduplication.java
+++ b/solr/core/src/test/org/apache/solr/update/processor/TestCloudDeduplication.java
@@ -59,7 +59,7 @@ public class TestCloudDeduplication extends SolrCloudTestCase {
CLIENTS.add(cluster.getSolrClient());
for (JettySolrRunner jetty : cluster.getJettySolrRunners()) {
- final SolrClient c = getHttpSolrClient(jetty.getBaseUrl().toString());
+ final SolrClient c = jetty.getSolrClient();
NODE_CLIENTS.add(c);
CLIENTS.add(c);
}
diff --git a/solr/solrj/src/test/org/apache/solr/client/solrj/SolrExampleTests.java b/solr/solrj/src/test/org/apache/solr/client/solrj/SolrExampleTests.java
index f1314c29b92..7b2ae5e6a29 100644
--- a/solr/solrj/src/test/org/apache/solr/client/solrj/SolrExampleTests.java
+++ b/solr/solrj/src/test/org/apache/solr/client/solrj/SolrExampleTests.java
@@ -439,14 +439,12 @@ public abstract class SolrExampleTests extends SolrExampleTestsBase {
if (solrTestRule.getJetty() != null) {
// check system wide system handler + "/admin/info/system"
- String url = solrTestRule.getBaseUrl();
- try (SolrClient adminClient = getHttpSolrClient(url)) {
- SolrQuery q = new SolrQuery();
+ SolrClient adminClient = solrTestRule.getAdminClient();
+ SolrQuery q = new SolrQuery();
- final var rsp = new SystemInfoRequest().process(adminClient);
- assertNotNull(rsp.getResponse().get("mode"));
- assertNotNull(rsp.getResponse().get("lucene"));
- }
+ final var rsp = new SystemInfoRequest().process(adminClient);
+ assertNotNull(rsp.getResponse().get("mode"));
+ assertNotNull(rsp.getResponse().get("lucene"));
}
}
diff --git a/solr/solrj/src/test/org/apache/solr/client/solrj/SolrExampleTestsBase.java b/solr/solrj/src/test/org/apache/solr/client/solrj/SolrExampleTestsBase.java
index 8d41ab9ce22..f4716ee0de1 100644
--- a/solr/solrj/src/test/org/apache/solr/client/solrj/SolrExampleTestsBase.java
+++ b/solr/solrj/src/test/org/apache/solr/client/solrj/SolrExampleTestsBase.java
@@ -22,6 +22,7 @@ import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import org.apache.solr.SolrTestCaseJ4;
+import org.apache.solr.client.solrj.jetty.HttpJettySolrClient;
import org.apache.solr.client.solrj.request.AbstractUpdateRequest.ACTION;
import org.apache.solr.client.solrj.request.SolrQuery;
import org.apache.solr.client.solrj.request.UpdateRequest;
@@ -78,8 +79,9 @@ public abstract class SolrExampleTestsBase extends SolrTestCaseJ4 {
* options.
*/
public SolrClient createNewSolrClient() {
- return SolrTestCaseJ4.getHttpSolrClient(
- solrTestRule.getBaseUrl(), DEFAULT_TEST_COLLECTION_NAME);
+ return new HttpJettySolrClient.Builder(solrTestRule.getBaseUrl())
+ .withDefaultCollection(DEFAULT_TEST_COLLECTION_NAME)
+ .build();
}
/** query the example */
diff --git a/solr/solrj/src/test/org/apache/solr/client/solrj/impl/CloudHttp2SolrClientTest.java b/solr/solrj/src/test/org/apache/solr/client/solrj/impl/CloudHttp2SolrClientTest.java
index 94ca36f2b15..ee80cbb85b9 100644
--- a/solr/solrj/src/test/org/apache/solr/client/solrj/impl/CloudHttp2SolrClientTest.java
+++ b/solr/solrj/src/test/org/apache/solr/client/solrj/impl/CloudHttp2SolrClientTest.java
@@ -395,11 +395,11 @@ public class CloudHttp2SolrClientTest extends SolrCloudTestCase {
params.add("distrib", "false");
QueryRequest queryRequest = new QueryRequest(params);
- try (SolrClient solrClient = getHttpSolrClient(baseUrl, coreName)) {
- QueryResponse queryResponse = queryRequest.process(solrClient);
- SolrDocumentList docList = queryResponse.getResults();
- assertEquals(1, docList.getNumFound());
- }
+ SolrClient solrClient =
+ new CollectionScopedSolrClient(cluster.getJetty(baseUrl).getSolrClient(), coreName);
+ QueryResponse queryResponse = queryRequest.process(solrClient);
+ SolrDocumentList docList = queryResponse.getResults();
+ assertEquals(1, docList.getNumFound());
}
// Test the deleteById routing for UpdateRequest
@@ -444,11 +444,11 @@ public class CloudHttp2SolrClientTest extends SolrCloudTestCase {
params.add("q", "id:" + id);
params.add("distrib", "false");
QueryRequest queryRequest = new QueryRequest(params);
- try (SolrClient solrClient = getHttpSolrClient(baseUrl, coreName)) {
- QueryResponse queryResponse = queryRequest.process(solrClient);
- SolrDocumentList docList = queryResponse.getResults();
- assertEquals(1, docList.getNumFound());
- }
+ SolrClient solrClient =
+ new CollectionScopedSolrClient(cluster.getJetty(baseUrl).getSolrClient(), coreName);
+ QueryResponse queryResponse = queryRequest.process(solrClient);
+ SolrDocumentList docList = queryResponse.getResults();
+ assertEquals(1, docList.getNumFound());
}
}
@@ -728,9 +728,7 @@ public class CloudHttp2SolrClientTest extends SolrCloudTestCase {
for (JettySolrRunner runner : cluster.getJettySolrRunners()) {
Double numRequests =
SolrJMetricTestUtils.getNumNodeRequestErrors(
- runner.getBaseUrl().toString(),
- SolrRequest.SolrRequestType.ADMIN.name(),
- adminPath);
+ runner, SolrRequest.SolrRequestType.ADMIN.name(), adminPath);
errorsBefore += numRequests.longValue();
if (log.isInfoEnabled()) {
log.info(
@@ -754,9 +752,7 @@ public class CloudHttp2SolrClientTest extends SolrCloudTestCase {
for (JettySolrRunner runner : cluster.getJettySolrRunners()) {
Double numRequests =
SolrJMetricTestUtils.getNumNodeRequestErrors(
- runner.getBaseUrl().toString(),
- SolrRequest.SolrRequestType.ADMIN.name(),
- adminPath);
+ runner, SolrRequest.SolrRequestType.ADMIN.name(), adminPath);
errorsAfter += numRequests.longValue();
if (log.isInfoEnabled()) {
log.info(
@@ -836,33 +832,33 @@ public class CloudHttp2SolrClientTest extends SolrCloudTestCase {
SolrQuery q = new SolrQuery().setQuery("*:*");
RemoteSolrException sse = null;
- try (SolrClient solrClient = getHttpSolrClient(r.getBaseUrl(), COLLECTION)) {
+ // addressed by collection (not core) on purpose: that is what exercises _stateVer_
+ SolrClient solrClient =
+ new CollectionScopedSolrClient(cluster.getReplicaJetty(r).getSolrClient(), COLLECTION);
- if (log.isInfoEnabled()) {
- log.info("should work query, result {}", solrClient.query(q));
- }
- // no problem
- q.setParam(CloudSolrClient.STATE_VERSION, COLLECTION + ":" + coll.getZNodeVersion());
- if (log.isInfoEnabled()) {
- log.info("2nd query , result {}", solrClient.query(q));
- }
- // no error yet good
-
- q.setParam(
- CloudSolrClient.STATE_VERSION,
- COLLECTION + ":" + (coll.getZNodeVersion() - 1)); // an older version expect error
-
- QueryResponse rsp = solrClient.query(q);
- final NamedList<Object> response = rsp.getResponse();
- final int stateVersionIdx =
- response.indexOf(CloudSolrClient.STATE_VERSION, response.size() - 1);
- @SuppressWarnings({"rawtypes"})
- Map m = stateVersionIdx == -1 ? null : (Map) response.getVal(stateVersionIdx);
- assertNotNull(
- "Expected an extra information from server with the list of invalid collection states",
- m);
- assertNotNull(m.get(COLLECTION));
+ if (log.isInfoEnabled()) {
+ log.info("should work query, result {}", solrClient.query(q));
+ }
+ // no problem
+ q.setParam(CloudSolrClient.STATE_VERSION, COLLECTION + ":" + coll.getZNodeVersion());
+ if (log.isInfoEnabled()) {
+ log.info("2nd query , result {}", solrClient.query(q));
}
+ // no error yet good
+
+ q.setParam(
+ CloudSolrClient.STATE_VERSION,
+ COLLECTION + ":" + (coll.getZNodeVersion() - 1)); // an older version expect error
+
+ QueryResponse rsp = solrClient.query(q);
+ final NamedList<Object> response = rsp.getResponse();
+ final int stateVersionIdx =
+ response.indexOf(CloudSolrClient.STATE_VERSION, response.size() - 1);
+ @SuppressWarnings({"rawtypes"})
+ Map m = stateVersionIdx == -1 ? null : (Map) response.getVal(stateVersionIdx);
+ assertNotNull(
+ "Expected an extra information from server with the list of invalid collection states", m);
+ assertNotNull(m.get(COLLECTION));
// now send the request to another node that does not serve the collection
@@ -884,19 +880,20 @@ public class CloudHttp2SolrClientTest extends SolrCloudTestCase {
log.info("the node which does not serve this collection{} ", theNode);
assertNotNull(theNode);
- try (SolrClient solrClient = getHttpSolrClient(theNode, COLLECTION)) {
+ // this node has no replica of the collection, so it is addressed by node rather than replica
+ SolrClient otherNodeClient =
+ new CollectionScopedSolrClient(cluster.getJetty(theNode).getSolrClient(), COLLECTION);
- q.setParam(CloudSolrClient.STATE_VERSION, COLLECTION + ":" + (coll.getZNodeVersion() - 1));
- try {
- QueryResponse rsp = solrClient.query(q);
- log.info("error was expected");
- } catch (RemoteSolrException e) {
- sse = e;
- }
- assertNotNull(sse);
- assertEquals(
- " Error code should be 510", SolrException.ErrorCode.INVALID_STATE.code, sse.code());
+ q.setParam(CloudSolrClient.STATE_VERSION, COLLECTION + ":" + (coll.getZNodeVersion() - 1));
+ try {
+ otherNodeClient.query(q);
+ log.info("error was expected");
+ } catch (RemoteSolrException e) {
+ sse = e;
}
+ assertNotNull(sse);
+ assertEquals(
+ " Error code should be 510", SolrException.ErrorCode.INVALID_STATE.code, sse.code());
}
@Test
@@ -937,7 +934,8 @@ public class CloudHttp2SolrClientTest extends SolrCloudTestCase {
@Test
public void customHttpClientTest() throws Exception {
String baseUrl = cluster.getJettySolrRunners().get(0).getBaseUrl().toString();
- try (HttpJettySolrClient httpClient = new HttpJettySolrClient.Builder(baseUrl).build()) {
+ try (HttpJettySolrClient httpClient =
+ cluster.getJettySolrRunners().get(0).newSolrClient(null)) {
try (CloudSolrClient cloudClient =
new CloudJettySolrClient.Builder(List.of(baseUrl)).withHttpClient(httpClient).build()) {
// Verify the CloudJettySolrClient uses the provided HttpJettySolrClient
diff --git a/solr/solrj/src/test/org/apache/solr/client/solrj/impl/HttpSolrClientBadInputTest.java b/solr/solrj/src/test/org/apache/solr/client/solrj/impl/HttpSolrClientBadInputTest.java
index e9c4e9e093a..e9781b67d86 100644
--- a/solr/solrj/src/test/org/apache/solr/client/solrj/impl/HttpSolrClientBadInputTest.java
+++ b/solr/solrj/src/test/org/apache/solr/client/solrj/impl/HttpSolrClientBadInputTest.java
@@ -49,59 +49,31 @@ public class HttpSolrClientBadInputTest extends SolrTestCaseJ4 {
}
@Test
- public void testDeleteByIdReportsInvalidIdLists() throws Exception {
- try (SolrClient client = getHttpSolrClient(solrTestRule.getBaseUrl(), ANY_COLLECTION)) {
- assertExceptionThrownWithMessageContaining(
- IllegalArgumentException.class,
- List.of("ids", "null"),
- () -> {
- client.deleteById(NULL_STR_LIST);
- });
- assertExceptionThrownWithMessageContaining(
- IllegalArgumentException.class,
- List.of("ids", "empty"),
- () -> {
- client.deleteById(EMPTY_STR_LIST);
- });
- assertExceptionThrownWithMessageContaining(
- IllegalArgumentException.class,
- List.of("ids", "null"),
- () -> {
- client.deleteById(NULL_STR_LIST, ANY_COMMIT_WITHIN_TIME);
- });
- assertExceptionThrownWithMessageContaining(
- IllegalArgumentException.class,
- List.of("ids", "empty"),
- () -> {
- client.deleteById(EMPTY_STR_LIST, ANY_COMMIT_WITHIN_TIME);
- });
- }
-
- try (SolrClient client = getHttpSolrClient(solrTestRule.getBaseUrl())) {
- assertExceptionThrownWithMessageContaining(
- IllegalArgumentException.class,
- List.of("ids", "null"),
- () -> {
- client.deleteById(ANY_COLLECTION, NULL_STR_LIST);
- });
- assertExceptionThrownWithMessageContaining(
- IllegalArgumentException.class,
- List.of("ids", "empty"),
- () -> {
- client.deleteById(ANY_COLLECTION, EMPTY_STR_LIST);
- });
- assertExceptionThrownWithMessageContaining(
- IllegalArgumentException.class,
- List.of("ids", "null"),
- () -> {
- client.deleteById(ANY_COLLECTION, NULL_STR_LIST, ANY_COMMIT_WITHIN_TIME);
- });
- assertExceptionThrownWithMessageContaining(
- IllegalArgumentException.class,
- List.of("ids", "empty"),
- () -> {
- client.deleteById(ANY_COLLECTION, EMPTY_STR_LIST, ANY_COMMIT_WITHIN_TIME);
- });
- }
+ public void testDeleteByIdReportsInvalidIdLists() {
+ SolrClient client = solrTestRule.getSolrClient(ANY_COLLECTION);
+ assertExceptionThrownWithMessageContaining(
+ IllegalArgumentException.class,
+ List.of("ids", "null"),
+ () -> {
+ client.deleteById(NULL_STR_LIST);
+ });
+ assertExceptionThrownWithMessageContaining(
+ IllegalArgumentException.class,
+ List.of("ids", "empty"),
+ () -> {
+ client.deleteById(EMPTY_STR_LIST);
+ });
+ assertExceptionThrownWithMessageContaining(
+ IllegalArgumentException.class,
+ List.of("ids", "null"),
+ () -> {
+ client.deleteById(NULL_STR_LIST, ANY_COMMIT_WITHIN_TIME);
+ });
+ assertExceptionThrownWithMessageContaining(
+ IllegalArgumentException.class,
+ List.of("ids", "empty"),
+ () -> {
+ client.deleteById(EMPTY_STR_LIST, ANY_COMMIT_WITHIN_TIME);
+ });
}
}
diff --git a/solr/solrj/src/test/org/apache/solr/client/solrj/impl/LB2SolrClientTest.java b/solr/solrj/src/test/org/apache/solr/client/solrj/impl/LB2SolrClientTest.java
index 849d8953c0f..5fca5e8f789 100644
--- a/solr/solrj/src/test/org/apache/solr/client/solrj/impl/LB2SolrClientTest.java
+++ b/solr/solrj/src/test/org/apache/solr/client/solrj/impl/LB2SolrClientTest.java
@@ -91,7 +91,9 @@ public class LB2SolrClientTest extends SolrTestCaseJ4 {
}
SolrResponseBase resp;
try (SolrClient client =
- getHttpSolrClient(solrInstance.getBaseUrl(), solrInstance.getDefaultCollection())) {
+ new HttpJettySolrClient.Builder(solrInstance.getBaseUrl())
+ .withDefaultCollection(solrInstance.getDefaultCollection())
+ .build()) {
resp = client.add(docs);
assertEquals(0, resp.getStatus());
resp = client.commit();
diff --git a/solr/test-framework/src/java/org/apache/solr/BaseDistributedSearchTestCase.java b/solr/test-framework/src/java/org/apache/solr/BaseDistributedSearchTestCase.java
index 11aa4fb83a0..219f5e19a03 100644
--- a/solr/test-framework/src/java/org/apache/solr/BaseDistributedSearchTestCase.java
+++ b/solr/test-framework/src/java/org/apache/solr/BaseDistributedSearchTestCase.java
@@ -51,6 +51,7 @@ import org.apache.solr.client.solrj.SolrClient;
import org.apache.solr.client.solrj.SolrResponse;
import org.apache.solr.client.solrj.SolrServerException;
import org.apache.solr.client.solrj.impl.HttpSolrClient;
+import org.apache.solr.client.solrj.jetty.HttpJettySolrClient;
import org.apache.solr.client.solrj.request.QueryRequest;
import org.apache.solr.client.solrj.request.UpdateRequest;
import org.apache.solr.client.solrj.response.QueryResponse;
@@ -447,7 +448,9 @@ public abstract class BaseDistributedSearchTestCase extends SolrTestCaseJ4 {
}
protected HttpSolrClient createNewSolrClient(int port) {
- return getHttpSolrClient(buildUrl(port), DEFAULT_TEST_CORENAME);
+ return new HttpJettySolrClient.Builder(buildUrl(port))
+ .withDefaultCollection(DEFAULT_TEST_CORENAME)
+ .build();
}
protected static void addFields(SolrInputDocument doc, Object... fields) {
diff --git a/solr/test-framework/src/java/org/apache/solr/SolrTestCaseHS.java b/solr/test-framework/src/java/org/apache/solr/SolrTestCaseHS.java
index fa5dd6e6d83..be382bcbbb7 100644
--- a/solr/test-framework/src/java/org/apache/solr/SolrTestCaseHS.java
+++ b/solr/test-framework/src/java/org/apache/solr/SolrTestCaseHS.java
@@ -35,6 +35,7 @@ import org.apache.lucene.util.IOUtils;
import org.apache.solr.client.solrj.SolrClient;
import org.apache.solr.client.solrj.SolrServerException;
import org.apache.solr.client.solrj.embedded.EmbeddedSolrServer;
+import org.apache.solr.client.solrj.jetty.HttpJettySolrClient;
import org.apache.solr.client.solrj.request.QueryRequest;
import org.apache.solr.client.solrj.request.UpdateRequest;
import org.apache.solr.client.solrj.response.InputStreamResponseParser;
@@ -405,7 +406,8 @@ public class SolrTestCaseHS extends SolrTestCaseJ4 {
public SolrClient getSolrJ() {
if (solrj == null) {
- solrj = getHttpSolrClient(getBaseURL(), collection);
+ solrj =
+ new HttpJettySolrClient.Builder(getBaseURL()).withDefaultCollection(collection).build();
}
return solrj;
}
diff --git a/solr/test-framework/src/java/org/apache/solr/SolrTestCaseJ4.java b/solr/test-framework/src/java/org/apache/solr/SolrTestCaseJ4.java
index 295f595bf1c..141b6db0a7f 100644
--- a/solr/test-framework/src/java/org/apache/solr/SolrTestCaseJ4.java
+++ b/solr/test-framework/src/java/org/apache/solr/SolrTestCaseJ4.java
@@ -88,7 +88,6 @@ import org.apache.solr.common.SolrDocumentList;
import org.apache.solr.common.SolrException;
import org.apache.solr.common.SolrInputDocument;
import org.apache.solr.common.SolrInputField;
-import org.apache.solr.common.cloud.Replica;
import org.apache.solr.common.params.CommonParams;
import org.apache.solr.common.params.ModifiableSolrParams;
import org.apache.solr.common.params.MultiMapSolrParams;
@@ -2524,53 +2523,6 @@ public abstract class SolrTestCaseJ4 extends SolrTestCase {
}
}
- /**
- * This method creates a basic HttpSolrClient. Tests that want to control the creation process
- * should use the {@link org.apache.solr.client.solrj.jetty.HttpJettySolrClient.Builder} class
- * directly
- *
- * @param url the base URL for a Solr node. Should not contain a core or collection name.
- */
- /**
- * @deprecated Prefer an existing client, e.g. from a {@link
- * org.apache.solr.util.SolrClientTestRule} or {@link
- * org.apache.solr.embedded.JettySolrRunner#getSolrClient()}.
- */
- @Deprecated(since = "10.1") // probably use an existing client like on a testRule/jettyRunner
- public static HttpJettySolrClient getHttpSolrClient(String url) {
- return new HttpJettySolrClient.Builder(url).build();
- }
-
- /** Create a basic HttpSolrClient pointed at the specified replica */
- /**
- * @deprecated Prefer an existing client, e.g. from a {@link
- * org.apache.solr.util.SolrClientTestRule} or {@link
- * org.apache.solr.embedded.JettySolrRunner#getSolrClient()}.
- */
- @Deprecated(since = "10.1") // probably use an existing client like on a testRule/jettyRunner
- public static HttpJettySolrClient getHttpSolrClient(Replica replica) {
- return getHttpSolrClient(replica.getBaseUrl(), replica.getCoreName());
- }
-
- /**
- * This method creates a basic HttpSolrClient. Tests that want to control the creation process
- * should use the {@link org.apache.solr.client.solrj.jetty.HttpJettySolrClient.Builder} class
- * directly
- *
- * @param url the base URL of a Solr node. Should <em>not</em> include a collection or core name.
- * @param defaultCoreName the name of a core that the created client should default to when making
- * core-aware requests
- */
- /**
- * @deprecated Prefer an existing client, e.g. from a {@link
- * org.apache.solr.util.SolrClientTestRule} or {@link
- * org.apache.solr.embedded.JettySolrRunner#getSolrClient()}.
- */
- @Deprecated(since = "10.1") // probably use an existing client like on a testRule/jettyRunner
- public static HttpJettySolrClient getHttpSolrClient(String url, String defaultCoreName) {
- return new HttpJettySolrClient.Builder(url).withDefaultCollection(defaultCoreName).build();
- }
-
/**
* Returns a randomly generated Date in the appropriate Solr external (input) format
*
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 7a62af77d0e..0b8e194abc7 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
@@ -59,6 +59,7 @@ import org.apache.solr.client.solrj.SolrRequest.METHOD;
import org.apache.solr.client.solrj.SolrRequest.SolrRequestType;
import org.apache.solr.client.solrj.SolrServerException;
import org.apache.solr.client.solrj.impl.CloudSolrClient;
+import org.apache.solr.client.solrj.impl.CollectionScopedSolrClient;
import org.apache.solr.client.solrj.impl.HttpSolrClient;
import org.apache.solr.client.solrj.jetty.HttpJettySolrClient;
import org.apache.solr.client.solrj.request.CollectionAdminRequest;
@@ -2556,6 +2557,31 @@ public abstract class AbstractFullDistribZkTestBase extends BaseDistributedSearc
return commonCloudSolrClient;
}
+ /** Returns the jetty identified by node name or base URL. */
+ protected JettySolrRunner getJetty(String nodeNameOrUrl) {
+ return MiniSolrCloudCluster.findJetty(allRunners(), nodeNameOrUrl);
+ }
+
+ /**
+ * Returns the jetty-owned client for the node hosting {@code replica}, scoped to that replica's
+ * core. The caller must not close it -- the jetty owns it.
+ */
+ protected SolrClient getSolrClient(Replica replica) {
+ return new CollectionScopedSolrClient(
+ MiniSolrCloudCluster.findReplicaJetty(allRunners(), replica).getSolrClient(),
+ replica.getCoreName());
+ }
+
+ /** All runners of this cluster; the control jetty is kept outside {@link #jettys}. */
+ private List<JettySolrRunner> allRunners() {
+ if (controlJetty == null) {
+ return jettys;
+ }
+ List<JettySolrRunner> all = new ArrayList<>(jettys);
+ all.add(controlJetty);
+ return all;
+ }
+
protected CloudSolrClient getSolrClient(String collectionName) {
return solrClientByCollection.computeIfAbsent(
collectionName,
@@ -2816,7 +2842,7 @@ public abstract class AbstractFullDistribZkTestBase extends BaseDistributedSearc
protected boolean reloadCollection(Replica replica, String testCollectionName) throws Exception {
String coreName = replica.getCoreName();
boolean reloadedOk = false;
- try (SolrClient client = getHttpSolrClient(replica.getBaseUrl())) {
+ try (SolrClient client = new HttpJettySolrClient.Builder(replica.getBaseUrl()).build()) {
CoreAdminResponse statusResp = CoreAdminRequest.getStatus(coreName, client);
long leaderCoreStartTime = statusResp.getStartTime(coreName).getTime();
diff --git a/solr/test-framework/src/java/org/apache/solr/cloud/MiniSolrCloudCluster.java b/solr/test-framework/src/java/org/apache/solr/cloud/MiniSolrCloudCluster.java
index 161760e3e70..7aba36a9188 100644
--- a/solr/test-framework/src/java/org/apache/solr/cloud/MiniSolrCloudCluster.java
+++ b/solr/test-framework/src/java/org/apache/solr/cloud/MiniSolrCloudCluster.java
@@ -53,8 +53,10 @@ import java.util.function.Consumer;
import org.apache.lucene.tests.util.LuceneTestCase;
import org.apache.solr.SolrBackend;
import org.apache.solr.SolrTestCaseJ4;
+import org.apache.solr.client.solrj.SolrClient;
import org.apache.solr.client.solrj.SolrServerException;
import org.apache.solr.client.solrj.impl.CloudSolrClient;
+import org.apache.solr.client.solrj.impl.CollectionScopedSolrClient;
import org.apache.solr.client.solrj.impl.ZkClientClusterStateProvider;
import org.apache.solr.client.solrj.jetty.CloudJettySolrClient;
import org.apache.solr.client.solrj.jetty.HttpJettySolrClient;
@@ -738,14 +740,48 @@ public class MiniSolrCloudCluster implements SolrBackend {
/** Return the jetty that a particular replica resides on */
public JettySolrRunner getReplicaJetty(Replica replica) {
- for (JettySolrRunner jetty : jettys) {
+ return findReplicaJetty(jettys, replica);
+ }
+
+ /** Returns the runner among {@code runners} that hosts {@code replica}. */
+ static JettySolrRunner findReplicaJetty(Collection<JettySolrRunner> runners, Replica replica) {
+ for (JettySolrRunner jetty : runners) {
if (jetty.isStopped()) continue;
if (replica.getCoreUrl().startsWith(jetty.getBaseUrl().toString())) return jetty;
+ // a proxied jetty registers its replicas under the proxy's port
+ if (replica.getCoreUrl().startsWith(jetty.getProxyBaseUrl().toString())) return jetty;
}
throw new IllegalArgumentException(
"Cannot find Jetty for a replica with core url " + replica.getCoreUrl());
}
+ /** Return the jetty for a node, identified by either its node name or its base URL. */
+ public JettySolrRunner getJetty(String nodeNameOrUrl) {
+ return findJetty(jettys, nodeNameOrUrl);
+ }
+
+ /** Returns the runner among {@code runners} identified by node name or base URL. */
+ static JettySolrRunner findJetty(Collection<JettySolrRunner> runners, String nodeNameOrUrl) {
+ for (JettySolrRunner jetty : runners) {
+ if (jetty.isStopped()) continue;
+ if (nodeNameOrUrl.equals(jetty.getNodeName())
+ || nodeNameOrUrl.equals(jetty.getBaseUrl().toString())) {
+ return jetty;
+ }
+ }
+ throw new IllegalArgumentException("Cannot find Jetty for node " + nodeNameOrUrl);
+ }
+
+ /**
+ * Returns the jetty-owned client for the node hosting {@code replica}, scoped to that replica's
+ * core. The caller must not close the returned client -- it delegates to the jetty's own shared
+ * client, which the jetty itself owns.
+ */
+ public SolrClient getSolrClient(Replica replica) {
+ return new CollectionScopedSolrClient(
+ getReplicaJetty(replica).getSolrClient(), replica.getCoreName());
+ }
+
/** Make the zookeeper session on a particular jetty lose connection and expire */
public void expireZkSession(JettySolrRunner jetty) {
ChaosMonkey.expireSession(jetty, zkServer);
diff --git a/solr/test-framework/src/java/org/apache/solr/cloud/api/collections/AbstractCollectionsAPIDistributedZkTestBase.java b/solr/test-framework/src/java/org/apache/solr/cloud/api/collections/AbstractCollectionsAPIDistributedZkTestBase.java
index 59a66bec4b2..febda3ee265 100644
--- a/solr/test-framework/src/java/org/apache/solr/cloud/api/collections/AbstractCollectionsAPIDistributedZkTestBase.java
+++ b/solr/test-framework/src/java/org/apache/solr/cloud/api/collections/AbstractCollectionsAPIDistributedZkTestBase.java
@@ -560,9 +560,8 @@ public abstract class AbstractCollectionsAPIDistributedZkTestBase extends SolrCl
for (Slice shard : collectionState) {
for (Replica replica : shard) {
CoreStatusResponse.SingleCoreData coreStatus;
- try (SolrClient server = getHttpSolrClient(replica.getBaseUrl())) {
- coreStatus = CoreAdminRequest.getCoreStatus(replica.getCoreName(), false, server);
- }
+ SolrClient server = cluster.getSolrClient(replica);
+ coreStatus = CoreAdminRequest.getCoreStatus(replica.getCoreName(), false, server);
long before = coreStatus.startTime.getTime();
urlToTime.put(replica.getCoreUrl(), before);
}
@@ -640,12 +639,10 @@ public abstract class AbstractCollectionsAPIDistributedZkTestBase extends SolrCl
assertNotNull(newReplica);
cluster.waitForActiveCollection(collectionName, 2, 6);
- try (SolrClient coreclient = getHttpSolrClient(newReplica.getBaseUrl())) {
- CoreAdminResponse status = CoreAdminRequest.getStatus(newReplica.getStr("core"), coreclient);
- final var coreStatus = status.getCoreStatus(newReplica.getStr("core"));
- String instanceDirStr = coreStatus.instanceDir;
- assertEquals(instanceDirStr, instancePath.toString());
- }
+ SolrClient coreclient = cluster.getSolrClient(newReplica);
+ CoreAdminResponse status = CoreAdminRequest.getStatus(newReplica.getStr("core"), coreclient);
+ final var coreStatus = status.getCoreStatus(newReplica.getStr("core"));
+ assertEquals(coreStatus.instanceDir, instancePath.toString());
// Test to make sure we can't create another replica with an existing core_name of that
// collection
diff --git a/solr/test-framework/src/java/org/apache/solr/embedded/JettySolrRunner.java b/solr/test-framework/src/java/org/apache/solr/embedded/JettySolrRunner.java
index bd97bf8c690..aea83190d9f 100644
--- a/solr/test-framework/src/java/org/apache/solr/embedded/JettySolrRunner.java
+++ b/solr/test-framework/src/java/org/apache/solr/embedded/JettySolrRunner.java
@@ -690,7 +690,7 @@ public class JettySolrRunner implements SolrBackend {
if (getCoreContainer() != null) {
final var coreStatusReq = new CoresApi.GetAllCoreStatus();
coreStatusReq.setIndexInfo(true);
- try (final var client = newClient()) {
+ try (final var client = new HttpJettySolrClient.Builder(getBaseUrl().toString()).build()) {
final var coreStatusRsp = coreStatusReq.process(client);
Utils.writeJson(coreStatusRsp, pw, true);
} catch (SolrServerException | IOException e) {
@@ -785,21 +785,6 @@ public class JettySolrRunner implements SolrBackend {
}
}
- /**
- * @deprecated Use {@link #getSolrClient()} or {@link #newClient(int, int)} instead.
- */
- @Deprecated(since = "10.1")
- public HttpJettySolrClient newClient() {
- return new HttpJettySolrClient.Builder(getBaseUrl().toString()).build();
- }
-
- public HttpJettySolrClient newClient(int connectionTimeoutMillis, int socketTimeoutMillis) {
- return new HttpJettySolrClient.Builder(getBaseUrl().toString())
- .withConnectionTimeout(connectionTimeoutMillis, TimeUnit.MILLISECONDS)
- .withIdleTimeout(socketTimeoutMillis, TimeUnit.MILLISECONDS)
- .build();
- }
-
// --------------------------------------------------------------
// --------------------------------------------------------------
diff --git a/solr/test-framework/src/java/org/apache/solr/util/SolrJMetricTestUtils.java b/solr/test-framework/src/java/org/apache/solr/util/SolrJMetricTestUtils.java
index 7669c3755cf..f589887b49e 100644
--- a/solr/test-framework/src/java/org/apache/solr/util/SolrJMetricTestUtils.java
+++ b/solr/test-framework/src/java/org/apache/solr/util/SolrJMetricTestUtils.java
@@ -26,6 +26,7 @@ import org.apache.solr.client.solrj.jetty.HttpJettySolrClient;
import org.apache.solr.client.solrj.request.MetricsRequest;
import org.apache.solr.common.params.SolrParams;
import org.apache.solr.common.util.NamedList;
+import org.apache.solr.embedded.JettySolrRunner;
public final class SolrJMetricTestUtils {
@@ -72,10 +73,11 @@ public final class SolrJMetricTestUtils {
}
}
- public static Double getNumNodeRequestErrors(String baseUrl, String category, String handler)
+ public static Double getNumNodeRequestErrors(
+ JettySolrRunner runner, String category, String handler)
throws SolrServerException, IOException {
- try (var client = new HttpJettySolrClient.Builder(baseUrl).build()) {
+ try (var client = runner.newSolrClient(null)) {
var req = new MetricsRequest(SolrParams.of("wt", "prometheus"));
NamedList<Object> resp = client.request(req);
diff --git a/solr/test-framework/src/test/org/apache/solr/embedded/TestJettySolrRunner.java b/solr/test-framework/src/test/org/apache/solr/embedded/TestJettySolrRunner.java
index 230a279864d..a874787c0ea 100644
--- a/solr/test-framework/src/test/org/apache/solr/embedded/TestJettySolrRunner.java
+++ b/solr/test-framework/src/test/org/apache/solr/embedded/TestJettySolrRunner.java
@@ -55,13 +55,12 @@ public class TestJettySolrRunner extends SolrTestCaseJ4 {
try {
runner.start();
- try (SolrClient client = getHttpSolrClient(runner.getBaseUrl().toString())) {
- CoreAdminRequest.Create createReq = new CoreAdminRequest.Create();
- createReq.setCoreName("newcore");
- createReq.setConfigSet("minimal");
+ SolrClient client = runner.getSolrClient();
+ CoreAdminRequest.Create createReq = new CoreAdminRequest.Create();
+ createReq.setCoreName("newcore");
+ createReq.setConfigSet("minimal");
- client.request(createReq);
- }
+ client.request(createReq);
assertTrue(Files.exists(coresDir.resolve("newcore").resolve("core.properties")));
diff --git a/solr/webapp/src/test/org/apache/solr/webapp/AdminUiCoreAdminStandaloneTest.java b/solr/webapp/src/test/org/apache/solr/webapp/AdminUiCoreAdminStandaloneTest.java
index 0508fd636e7..1707bc9f2a3 100644
--- a/solr/webapp/src/test/org/apache/solr/webapp/AdminUiCoreAdminStandaloneTest.java
+++ b/solr/webapp/src/test/org/apache/solr/webapp/AdminUiCoreAdminStandaloneTest.java
@@ -95,12 +95,11 @@ public class AdminUiCoreAdminStandaloneTest extends AdminUiStandaloneTestBase {
@Test
public void testSwapCoresViaUi() throws Exception {
// make the cores distinguishable: swapa gets one document, swapb stays empty
- try (var client = standaloneJetty.newClient()) {
- var doc = new SolrInputDocument();
- doc.addField("id", "swap-doc");
- client.add("swapa", doc);
- client.commit("swapa");
- }
+ var client = standaloneJetty.getSolrClient();
+ var doc = new SolrInputDocument();
+ doc.addField("id", "swap-doc");
+ client.add("swapa", doc);
+ client.commit("swapa");
assertEquals(1, numDocs("swapa"));
assertEquals(0, numDocs("swapb"));
@@ -136,8 +135,12 @@ public class AdminUiCoreAdminStandaloneTest extends AdminUiStandaloneTestBase {
}
private long numDocs(String coreName) {
- try (var client = standaloneJetty.newClient()) {
- return client.query(coreName, new SolrQuery("*:*")).getResults().getNumFound();
+ try {
+ return standaloneJetty
+ .getSolrClient()
+ .query(coreName, new SolrQuery("*:*"))
+ .getResults()
+ .getNumFound();
} catch (Exception e) {
throw new RuntimeException(e);
}
diff --git a/solr/webapp/src/test/org/apache/solr/webapp/AdminUiQueryScreenTest.java b/solr/webapp/src/test/org/apache/solr/webapp/AdminUiQueryScreenTest.java
index 86ee2ba1fe0..08b9d18e6f1 100644
--- a/solr/webapp/src/test/org/apache/solr/webapp/AdminUiQueryScreenTest.java
+++ b/solr/webapp/src/test/org/apache/solr/webapp/AdminUiQueryScreenTest.java
@@ -93,9 +93,7 @@ public class AdminUiQueryScreenTest extends AdminUiTestBase {
setParams.setContentWriter(
new RequestWriter.StringPayloadContentWriter(
"{\"set\":{\"" + paramset + "\":{\"rows\":\"2\"}}}", CommonParams.JSON_MIME));
- try (SolrClient client = cluster.getJettySolrRunner(0).newClient()) {
- client.request(setParams);
- }
+ cluster.getJettySolrRunner(0).getSolrClient().request(setParams);
openPage(COLLECTION + "/query", By.id("query"));
chosenSelect("useParams", paramset);
diff --git a/solr/webapp/src/test/org/apache/solr/webapp/AdminUiReplicationStandaloneTest.java b/solr/webapp/src/test/org/apache/solr/webapp/AdminUiReplicationStandaloneTest.java
index d7e78d7f0d0..3434feebb0e 100644
--- a/solr/webapp/src/test/org/apache/solr/webapp/AdminUiReplicationStandaloneTest.java
+++ b/solr/webapp/src/test/org/apache/solr/webapp/AdminUiReplicationStandaloneTest.java
@@ -91,15 +91,14 @@ public class AdminUiReplicationStandaloneTest extends AdminUiStandaloneTestBase
"polling should be disabled", () -> "true".equals(followerDetail("isPollingDisabled")));
// index documents on the leader; the follower does not poll them
- try (var client = leaderJetty.newClient()) {
- for (int i = 1; i <= 2; i++) {
- SolrInputDocument doc = new SolrInputDocument();
- doc.addField("id", "repl-doc-" + i);
- doc.addField("name", "replicated");
- client.add(CORE, doc);
- }
- client.commit(CORE);
+ var client = leaderJetty.getSolrClient();
+ for (int i = 1; i <= 2; i++) {
+ SolrInputDocument doc = new SolrInputDocument();
+ doc.addField("id", "repl-doc-" + i);
+ doc.addField("name", "replicated");
+ client.add(CORE, doc);
}
+ client.commit(CORE);
// replicate on demand and watch the docs arrive on the follower
click(By.cssSelector("#replication button.replicate-now"));
@@ -151,8 +150,12 @@ public class AdminUiReplicationStandaloneTest extends AdminUiStandaloneTestBase
}
private long followerNumDocs() {
- try (var client = standaloneJetty.newClient()) {
- return client.query(CORE, new SolrQuery("*:*")).getResults().getNumFound();
+ try {
+ return standaloneJetty
+ .getSolrClient()
+ .query(CORE, new SolrQuery("*:*"))
+ .getResults()
+ .getNumFound();
} catch (Exception e) {
throw new RuntimeException(e);
}
diff --git a/solr/webapp/src/test/org/apache/solr/webapp/AdminUiSecurityAuthTest.java b/solr/webapp/src/test/org/apache/solr/webapp/AdminUiSecurityAuthTest.java
index 8ac87a18af5..a3269ccfc3f 100644
--- a/solr/webapp/src/test/org/apache/solr/webapp/AdminUiSecurityAuthTest.java
+++ b/solr/webapp/src/test/org/apache/solr/webapp/AdminUiSecurityAuthTest.java
@@ -18,7 +18,6 @@ package org.apache.solr.webapp;
import java.util.List;
import java.util.Map;
-import org.apache.solr.client.solrj.SolrClient;
import org.apache.solr.client.solrj.SolrRequest;
import org.apache.solr.client.solrj.request.GenericSolrRequest;
import org.apache.solr.common.util.NamedList;
@@ -134,11 +133,11 @@ public class AdminUiSecurityAuthTest extends AdminUiTestBase {
/** Returns the authorization config as fetched with credentials. */
private NamedList<Object> authorizationApi() {
- try (SolrClient client = cluster.getJettySolrRunner(0).newClient()) {
+ try {
GenericSolrRequest req =
new GenericSolrRequest(SolrRequest.METHOD.GET, "/admin/authorization", params());
req.setBasicAuthCredentials(USER, PASS);
- return client.request(req);
+ return cluster.getJettySolrRunner(0).getSolrClient().request(req);
} catch (Exception e) {
throw new RuntimeException(e);
}
@@ -158,11 +157,11 @@ public class AdminUiSecurityAuthTest extends AdminUiTestBase {
/** Checks via the authentication API (with credentials) whether the user exists. */
private boolean userExists(String user) {
- try (SolrClient client = cluster.getJettySolrRunner(0).newClient()) {
+ try {
GenericSolrRequest req =
new GenericSolrRequest(SolrRequest.METHOD.GET, "/admin/authentication", params());
req.setBasicAuthCredentials(USER, PASS);
- NamedList<Object> response = client.request(req);
+ NamedList<Object> response = cluster.getJettySolrRunner(0).getSolrClient().request(req);
Map<?, ?> authentication = (Map<?, ?>) response.get("authentication");
Map<?, ?> credentials = (Map<?, ?>) authentication.get("credentials");
return credentials.containsKey(user);
diff --git a/solr/webapp/src/test/org/apache/solr/webapp/AdminUiTestBase.java b/solr/webapp/src/test/org/apache/solr/webapp/AdminUiTestBase.java
index 54e1a79d424..a0f6469aa17 100644
--- a/solr/webapp/src/test/org/apache/solr/webapp/AdminUiTestBase.java
+++ b/solr/webapp/src/test/org/apache/solr/webapp/AdminUiTestBase.java
@@ -38,7 +38,6 @@ import org.apache.lucene.tests.util.QuickPatchThreadsFilter;
import org.apache.lucene.util.SuppressForbidden;
import org.apache.solr.SolrIgnoredThreadsFilter;
import org.apache.solr.SolrTestCaseJ4;
-import org.apache.solr.client.solrj.SolrClient;
import org.apache.solr.client.solrj.SolrRequest;
import org.apache.solr.client.solrj.SolrServerException;
import org.apache.solr.client.solrj.request.CollectionAdminRequest;
@@ -382,9 +381,9 @@ public abstract class AdminUiTestBase extends SolrCloudTestCase {
throws IOException, SolrServerException {
ensureCloudCluster();
JettySolrRunner jetty = standaloneMode ? standaloneJetty : cluster.getJettySolrRunner(0);
- try (SolrClient client = jetty.newClient()) {
- return client.request(new GenericSolrRequest(SolrRequest.METHOD.GET, path, params));
- }
+ return jetty
+ .getSolrClient()
+ .request(new GenericSolrRequest(SolrRequest.METHOD.GET, path, params));
}
/**