This is an automated email from the ASF dual-hosted git repository. dsmiley pushed a commit to branch branch_9x in repository https://gitbox.apache.org/repos/asf/solr.git
commit 53bd3808061da21a4e05fe1d78f0818c29d6b9d0 Author: Nick <[email protected]> AuthorDate: Sat Nov 14 22:46:17 2026 -0700 SOLR-18606: CloudSolrClient: get collection state without repeated alias lookups (#5314) Refresh missing ZooKeeper collection state in CloudSolrClient without repeatedly refreshing known aliases. A performance issue when aliases are in play. branch_10x delta: omitted CloudHttp2SolrClientTest.testShardReplicationFactors and testShardReplicationFactorsWithoutRouteFactors, which depend on CloudSolrClient.REPFACT_BY_ROUTE from the not-backported SOLR-18603 (#5267). branch_9x delta: the new tests are adapted to branch_9x: no records (Java 11), SolrZkClient.getData/setData take a retryOnConnLoss flag, and CloudSolrClient.Builder takes a ZK host list with Optional.empty(). (cherry picked from commit 459157a2b8d2d9ee5ae5bf2bc2c58d9a808353e3) (cherry picked from commit 0b2fa93853b3e6cbb180c333d77dbb7e66d84805) --- changelog/unreleased/SOLR-18606.yml | 9 ++ solr/solrj-zookeeper/build.gradle | 1 + .../solrj/impl/ZkClientClusterStateProvider.java | 33 ++++- .../impl/ZkClientClusterStateProviderTest.java | 157 +++++++++++++++++++++ .../solr/client/solrj/impl/CloudSolrClient.java | 17 ++- .../solrj/impl/CloudHttp2SolrClientTest.java | 24 ++++ .../solrj/impl/CloudSolrClientCacheTest.java | 20 +++ .../solrj/impl/ClusterStateProviderTest.java | 98 +++++++++++++ 8 files changed, 353 insertions(+), 6 deletions(-) diff --git a/changelog/unreleased/SOLR-18606.yml b/changelog/unreleased/SOLR-18606.yml new file mode 100644 index 00000000000..50a51b64dfd --- /dev/null +++ b/changelog/unreleased/SOLR-18606.yml @@ -0,0 +1,9 @@ +title: > + Refresh missing ZooKeeper collection state in CloudSolrClient without repeatedly + refreshing known aliases. +type: fixed +authors: + - name: Nick Shanin +links: + - name: SOLR-18606 + url: https://issues.apache.org/jira/browse/SOLR-18606 diff --git a/solr/solrj-zookeeper/build.gradle b/solr/solrj-zookeeper/build.gradle index 173c17a7233..8b9a5e4090c 100644 --- a/solr/solrj-zookeeper/build.gradle +++ b/solr/solrj-zookeeper/build.gradle @@ -45,6 +45,7 @@ dependencies { testImplementation project(':solr:test-framework') testImplementation project(':solr:core') + testImplementation 'org.apache.lucene:lucene-test-framework' testImplementation 'junit:junit' testImplementation 'commons-io:commons-io' diff --git a/solr/solrj-zookeeper/src/java/org/apache/solr/client/solrj/impl/ZkClientClusterStateProvider.java b/solr/solrj-zookeeper/src/java/org/apache/solr/client/solrj/impl/ZkClientClusterStateProvider.java index 0a1ee9ab439..f059e28debb 100644 --- a/solr/solrj-zookeeper/src/java/org/apache/solr/client/solrj/impl/ZkClientClusterStateProvider.java +++ b/solr/solrj-zookeeper/src/java/org/apache/solr/client/solrj/impl/ZkClientClusterStateProvider.java @@ -144,12 +144,37 @@ public class ZkClientClusterStateProvider @Override public ClusterState.CollectionRef getState(String collection) { - ClusterState clusterState = getZkStateReader().getClusterState(); - if (clusterState != null) { - return clusterState.getCollectionRef(collection); - } else { + ZkStateReader reader = getZkStateReader(); + ClusterState clusterState = reader.getClusterState(); + if (clusterState == null) { return null; } + ClusterState.CollectionRef ref = clusterState.getCollectionRef(collection); + // Alias names are probed as collections before they are resolved. Avoid a ZooKeeper + // lookup for a known alias on every request. + if (ref != null || reader.getAliases().hasAlias(collection)) { + return ref; + } + + try { + reader.forceUpdateCollection(collection); + return reader.getClusterState().getCollectionRef(collection); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + throw new ZooKeeperException(SolrException.ErrorCode.SERVER_ERROR, e.toString(), e); + } catch (KeeperException e) { + throw new ZooKeeperException(SolrException.ErrorCode.SERVER_ERROR, e.toString(), e); + } catch (SolrException e) { + Throwable cause = e.getCause(); + if (e.code() == SolrException.ErrorCode.BAD_REQUEST.code + && (cause instanceof KeeperException || cause instanceof InterruptedException)) { + if (cause instanceof InterruptedException) { + Thread.currentThread().interrupt(); + } + throw new ZooKeeperException(SolrException.ErrorCode.SERVER_ERROR, e.toString(), cause); + } + throw e; + } } @Override diff --git a/solr/solrj-zookeeper/src/test/org/apache/solr/client/solrj/impl/ZkClientClusterStateProviderTest.java b/solr/solrj-zookeeper/src/test/org/apache/solr/client/solrj/impl/ZkClientClusterStateProviderTest.java new file mode 100644 index 00000000000..7b336bc8def --- /dev/null +++ b/solr/solrj-zookeeper/src/test/org/apache/solr/client/solrj/impl/ZkClientClusterStateProviderTest.java @@ -0,0 +1,157 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.solr.client.solrj.impl; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.concurrent.CopyOnWriteArrayList; +import java.util.concurrent.TimeUnit; +import org.apache.solr.SolrTestCase; +import org.apache.solr.cloud.ZkController; +import org.apache.solr.cloud.ZkTestServer; +import org.apache.solr.common.cloud.DocCollection; +import org.apache.solr.common.cloud.SolrZkClient; +import org.apache.solr.common.cloud.ZkStateReader; +import org.apache.solr.common.util.Utils; +import org.apache.zookeeper.KeeperException; +import org.apache.zookeeper.Watcher; +import org.apache.zookeeper.data.Stat; +import org.junit.Test; + +public class ZkClientClusterStateProviderTest extends SolrTestCase { + + private static final class ReadAttempt { + final String path; + final String failure; + + ReadAttempt(String path, String failure) { + this.path = path; + this.failure = failure; + } + + @Override + public boolean equals(Object o) { + return o instanceof ReadAttempt + && Objects.equals(path, ((ReadAttempt) o).path) + && Objects.equals(failure, ((ReadAttempt) o).failure); + } + + @Override + public int hashCode() { + return Objects.hash(path, failure); + } + + @Override + public String toString() { + return path + (failure == null ? "" : " (" + failure + ")"); + } + } + + private static class RecordingSolrZkClient extends SolrZkClient { + private final List<ReadAttempt> readAttempts = new CopyOnWriteArrayList<>(); + + RecordingSolrZkClient(Builder builder) { + super(builder); + } + + @Override + public byte[] getData(String path, Watcher watcher, Stat stat, boolean retryOnConnLoss) + throws KeeperException, InterruptedException { + try { + byte[] data = super.getData(path, watcher, stat, retryOnConnLoss); + readAttempts.add(new ReadAttempt(path, null)); + return data; + } catch (KeeperException | InterruptedException e) { + readAttempts.add(new ReadAttempt(path, e.getClass().getSimpleName())); + throw e; + } + } + + List<ReadAttempt> getReadAttempts() { + return new ArrayList<>(readAttempts); + } + + void clearReadAttempts() { + readAttempts.clear(); + } + } + + @Test + public void testKnownAliasDoesNotReadAliasCollectionState() throws Exception { + String collection = "target"; + String alias = collection + "_alias"; + String aliasCollectionPath = DocCollection.getCollectionPath(alias); + ZkTestServer server = new ZkTestServer(createTempDir("alias-read-signal")); + RecordingSolrZkClient zkClient = null; + ZkStateReader reader = null; + try { + server.run(); + zkClient = + new RecordingSolrZkClient( + new SolrZkClient.Builder() + .withUrl(server.getZkAddress()) + .withTimeout(30, TimeUnit.SECONDS)); + ZkController.createClusterZkNodes(zkClient); + zkClient.setData( + ZkStateReader.ALIASES, + Utils.toJSON(Map.of("collection", Map.of(alias, collection))), + true); + + reader = new ZkStateReader(zkClient); + reader.createClusterStateWatchersAndUpdate(); + assertTrue(reader.getAliases().hasAlias(alias)); + ZkClientClusterStateProvider provider = new ZkClientClusterStateProvider(reader); + + // Positive control: this client-specific recorder observes the exact missing path and + // distinguishes the failed ZooKeeper read from a successful read. + zkClient.clearReadAttempts(); + RecordingSolrZkClient observedClient = zkClient; + KeeperException.NoNodeException missing = + expectThrows( + KeeperException.NoNodeException.class, + () -> observedClient.getData(aliasCollectionPath, null, null, true)); + assertTrue( + "Unexpected missing path: " + missing.getPath(), + missing.getPath().endsWith(aliasCollectionPath)); + assertEquals( + Collections.singletonList(new ReadAttempt(aliasCollectionPath, "NoNodeException")), + zkClient.getReadAttempts()); + + // With the known-alias guard present, probing the alias must not read its collection-state + // path. Removing the guard makes this assertion fail with the exact NoNode path recorded. + zkClient.clearReadAttempts(); + assertNull(provider.getState(alias)); + assertFalse( + "Known alias triggered a read of " + + aliasCollectionPath + + ": " + + zkClient.getReadAttempts(), + zkClient.getReadAttempts().stream().anyMatch(a -> aliasCollectionPath.equals(a.path))); + } finally { + if (reader != null) { + reader.close(); + } + if (zkClient != null) { + zkClient.close(); + } + server.shutdown(); + } + } +} diff --git a/solr/solrj/src/java/org/apache/solr/client/solrj/impl/CloudSolrClient.java b/solr/solrj/src/java/org/apache/solr/client/solrj/impl/CloudSolrClient.java index 3e6c0fd1e0c..72e8e5b0a64 100644 --- a/solr/solrj/src/java/org/apache/solr/client/solrj/impl/CloudSolrClient.java +++ b/solr/solrj/src/java/org/apache/solr/client/solrj/impl/CloudSolrClient.java @@ -928,12 +928,17 @@ public abstract class CloudSolrClient extends SolrClient { if (!inputCollections.isEmpty() && !isAdmin && !isCollectionRequestOfV2) { // don't do _stateVer_ checking for admin, v2 api requests - Set<String> requestedCollectionNames = resolveAliases(inputCollections); + Set<String> missingInputCollections = new HashSet<>(); + Set<String> requestedCollectionNames = + resolveAliases(inputCollections, missingInputCollections); StringBuilder stateVerParamBuilder = null; for (String requestedCollection : requestedCollectionNames) { // track the version of state we're using on the client side using the _stateVer_ param - DocCollection coll = getDocCollection(requestedCollection, null); + DocCollection coll = + missingInputCollections.contains(requestedCollection) + ? null + : getDocCollection(requestedCollection, null); if (coll == null) { throw new SolrException( SolrException.ErrorCode.BAD_REQUEST, "Collection not found: " + requestedCollection); @@ -1334,12 +1339,20 @@ public abstract class CloudSolrClient extends SolrClient { * collection existence. */ private Set<String> resolveAliases(List<String> inputCollections) { + return resolveAliases(inputCollections, null); + } + + private Set<String> resolveAliases( + List<String> inputCollections, Set<String> missingInputCollections) { if (inputCollections.isEmpty()) { return Collections.emptySet(); } LinkedHashSet<String> uniqueNames = new LinkedHashSet<>(); // consistent ordering for (String collectionName : inputCollections) { if (getDocCollection(collectionName, -1) == null) { + if (missingInputCollections != null) { + missingInputCollections.add(collectionName); + } // perhaps it's an alias uniqueNames.addAll(getClusterStateProvider().resolveAlias(collectionName)); } else { 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 8fa2a7d0ab2..bfbbb978605 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 @@ -314,6 +314,30 @@ public class CloudHttp2SolrClientTest extends SolrCloudTestCase { return new CloudHttp2SolrClient.Builder(solrUrls).build(); } + @Test + public void testZkAliasRequestsResolveAndQuery() throws Exception { + String collection = getSaferTestName(); + String alias = collection + "_alias"; + CollectionAdminRequest.createCollection(collection, "conf", 2, 1) + .process(cluster.getSolrClient()); + cluster.waitForActiveCollection(collection, 2, 2); + CollectionAdminRequest.createAlias(alias, collection).process(cluster.getSolrClient()); + + try (CloudSolrClient client = + new CloudSolrClient.Builder( + Collections.singletonList(cluster.getZkServer().getZkAddress()), Optional.empty()) + .build()) { + assertEquals(List.of(collection), client.getClusterStateProvider().resolveAlias(alias)); + assertEquals(0, client.query(alias, params("q", "*:*")).getResults().getNumFound()); + for (int i = 0; i < 3; i++) { + assertEquals(0, client.query(alias, params("q", "*:*")).getResults().getNumFound()); + } + } finally { + CollectionAdminRequest.deleteAlias(alias).process(cluster.getSolrClient()); + CollectionAdminRequest.deleteCollection(collection).process(cluster.getSolrClient()); + } + } + @Test public void testRouting() throws Exception { CollectionAdminRequest.createCollection("routing_collection", "conf", 2, 1) diff --git a/solr/solrj/src/test/org/apache/solr/client/solrj/impl/CloudSolrClientCacheTest.java b/solr/solrj/src/test/org/apache/solr/client/solrj/impl/CloudSolrClientCacheTest.java index 4d292d6fd22..2f0acb32992 100644 --- a/solr/solrj/src/test/org/apache/solr/client/solrj/impl/CloudSolrClientCacheTest.java +++ b/solr/solrj/src/test/org/apache/solr/client/solrj/impl/CloudSolrClientCacheTest.java @@ -20,6 +20,9 @@ package org.apache.solr.client.solrj.impl; import static java.nio.charset.StandardCharsets.UTF_8; import static org.mockito.Mockito.any; import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.spy; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import java.io.IOException; @@ -136,6 +139,23 @@ public class CloudSolrClientCacheTest extends SolrTestCaseJ4 { } } + public void testMissingCollectionIsCheckedOncePerRequest() throws Exception { + String collection = "gettingstarted"; + Map<String, ClusterState.CollectionRef> refs = new HashMap<>(); + try (ClusterStateProvider provider = spy(getStateProvider(Set.of(), refs)); + RecordingCloudSolrClient client = new RecordingCloudSolrClient(provider, 2)) { + SolrException error = + expectThrows( + SolrException.class, () -> client.request(new DummyRequest(collection), collection)); + assertEquals(SolrException.ErrorCode.BAD_REQUEST.code, error.code()); + verify(provider, times(1)).getState(collection); + + refs.put(collection, new ClusterState.CollectionRef(loadCollection(collection, 1))); + assertNotNull(client.request(new DummyRequest(collection), collection)); + verify(provider, times(2)).getState(collection); + } + } + public void testStaleStateRetrySkipsStateVersionBeforeWait() throws Exception { String collName = "gettingstarted"; Set<String> liveNodes = new HashSet<>(Set.of("192.168.1.108:8983_solr")); diff --git a/solr/solrj/src/test/org/apache/solr/client/solrj/impl/ClusterStateProviderTest.java b/solr/solrj/src/test/org/apache/solr/client/solrj/impl/ClusterStateProviderTest.java index fa2c6a32fee..2eeedcadbc1 100644 --- a/solr/solrj/src/test/org/apache/solr/client/solrj/impl/ClusterStateProviderTest.java +++ b/solr/solrj/src/test/org/apache/solr/client/solrj/impl/ClusterStateProviderTest.java @@ -22,6 +22,12 @@ import static org.apache.solr.common.util.URLUtil.getNodeNameForBaseUrl; import static org.hamcrest.Matchers.containsInAnyOrder; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.lessThanOrEqualTo; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyBoolean; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.ArgumentMatchers.isNull; +import static org.mockito.Mockito.doThrow; +import static org.mockito.Mockito.spy; import com.carrotsearch.randomizedtesting.annotations.ParametersFactory; import java.io.IOException; @@ -29,6 +35,7 @@ import java.lang.invoke.MethodHandles; import java.lang.reflect.InvocationTargetException; import java.nio.file.Path; import java.time.Instant; +import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; @@ -39,14 +46,24 @@ import org.apache.solr.client.solrj.SolrServerException; import org.apache.solr.client.solrj.request.CollectionAdminRequest; import org.apache.solr.client.solrj.response.CollectionAdminResponse; import org.apache.solr.cloud.SolrCloudTestCase; +import org.apache.solr.cloud.Stats; import org.apache.solr.cloud.ZkController; import org.apache.solr.cloud.ZkTestServer; +import org.apache.solr.cloud.overseer.ZkStateWriter; +import org.apache.solr.cloud.overseer.ZkWriteCommand; +import org.apache.solr.common.SolrException; import org.apache.solr.common.cloud.ClusterProperties; import org.apache.solr.common.cloud.ClusterState; import org.apache.solr.common.cloud.DocCollection; +import org.apache.solr.common.cloud.DocRouter; +import org.apache.solr.common.cloud.PerReplicaStatesOps; import org.apache.solr.common.cloud.SolrZkClient; import org.apache.solr.common.cloud.ZkStateReader; import org.apache.solr.common.util.NamedList; +import org.apache.solr.common.util.ZLibCompressor; +import org.apache.solr.handler.admin.ConfigSetsHandler; +import org.apache.zookeeper.KeeperException; +import org.apache.zookeeper.data.Stat; import org.eclipse.jetty.http.HttpField; import org.eclipse.jetty.http.HttpHeader; import org.hamcrest.Matchers; @@ -142,6 +159,87 @@ public class ClusterStateProviderTest extends SolrCloudTestCase { } } + @Test + public void testProviderRefreshesCollectionMissingFromLocalState() throws Exception { + ZkTestServer server = new ZkTestServer(createTempDir("stale-state")); + server.run(); + try (SolrZkClient zkClient = new SolrZkClient.Builder().withUrl(server.getZkAddress()).build(); + ZkStateReader reader = new ZkStateReader(zkClient); + ZkClientClusterStateProvider provider = new ZkClientClusterStateProvider(reader)) { + ZkController.createClusterZkNodes(zkClient); + reader.createClusterStateWatchersAndUpdate(); + ZkStateWriter writer = new ZkStateWriter(reader, new Stats(), -1, new ZLibCompressor()); + synchronized (reader.getUpdateLock()) { + assertNull(reader.getClusterState().getCollectionRef("new_collection")); + zkClient.makePath(ZkStateReader.COLLECTIONS_ZKNODE + "/new_collection", true); + DocCollection state = + DocCollection.create( + "new_collection", + new HashMap<>(), + Map.of(ZkStateReader.CONFIGNAME_PROP, ConfigSetsHandler.DEFAULT_CONFIGSET_NAME), + DocRouter.DEFAULT, + 0, + Instant.now(), + PerReplicaStatesOps.getZkClientPrsSupplier( + zkClient, DocCollection.getCollectionPath("new_collection"))); + writer.enqueueUpdate( + reader.getClusterState(), List.of(new ZkWriteCommand("new_collection", state)), null); + writer.writePendingUpdates(); + + // The watcher cannot publish the new collection while this lock is held. + assertNull(reader.getClusterState().getCollectionRef("new_collection")); + ClusterState.CollectionRef refreshed = provider.getState("new_collection"); + assertNotNull(refreshed); + assertEquals("new_collection", refreshed.get().getName()); + } + } finally { + server.shutdown(); + } + } + + @Test + public void testProviderPropagatesCollectionReadFailures() throws Exception { + assumeWorkingMockito(); + SolrZkClient zkClient = spy(cluster.getZkClient()); + try (ZkStateReader reader = new ZkStateReader(zkClient); + ZkClientClusterStateProvider provider = new ZkClientClusterStateProvider(reader)) { + reader.createClusterStateWatchersAndUpdate(); + KeeperException failure = new KeeperException.ConnectionLossException(); + doThrow(failure) + .when(zkClient) + .getData( + eq(DocCollection.getCollectionPath("missing")), + isNull(), + any(Stat.class), + anyBoolean()); + SolrException readerError = + expectThrows(SolrException.class, () -> reader.forceUpdateCollection("missing")); + assertEquals(SolrException.ErrorCode.BAD_REQUEST.code, readerError.code()); + assertSame(failure, readerError.getCause()); + + SolrException error = expectThrows(SolrException.class, () -> provider.getState("missing")); + assertEquals(SolrException.ErrorCode.SERVER_ERROR.code, error.code()); + assertSame(failure, error.getCause()); + + InterruptedException interrupted = new InterruptedException("interrupted"); + doThrow(interrupted) + .when(zkClient) + .getData( + eq(DocCollection.getCollectionPath("interrupted")), + isNull(), + any(Stat.class), + anyBoolean()); + try { + error = expectThrows(SolrException.class, () -> provider.getState("interrupted")); + assertEquals(SolrException.ErrorCode.SERVER_ERROR.code, error.code()); + assertSame(interrupted, error.getCause()); + assertTrue(Thread.currentThread().isInterrupted()); + } finally { + Thread.interrupted(); + } + } + } + @Test public void testGetState() throws Exception {
