This is an automated email from the ASF dual-hosted git repository.
peterxcli pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/ozone.git
The following commit(s) were added to refs/heads/master by this push:
new b6d0181075e HDDS-16737. Share OM follower read logic between the
Hadoop RPC and gRPC clients (#11418)
b6d0181075e is described below
commit b6d0181075e2f36bf38801f9cf3bea11948e3d32
Author: Peter Lee <[email protected]>
AuthorDate: Sun Oct 25 19:42:42 2026 +0800
HDDS-16737. Share OM follower read logic between the Hadoop RPC and gRPC
clients (#11418)
---
.../ha/FollowerReadFailoverProxyProviderBase.java | 168 +++++++++++++++
.../ozone/om/ha/GrpcOMFailoverProxyProvider.java | 4 -
.../GrpcOMFollowerReadFailoverProxyProvider.java | 125 +++++++++++
...doopRpcOMFollowerReadFailoverProxyProvider.java | 144 ++-----------
.../ozone/om/ha/OMFailoverProxyProviderBase.java | 21 --
.../ozone/om/protocolPB/GrpcOmTransport.java | 149 +-------------
.../TestFollowerReadFailoverProxyProviderBase.java | 205 ++++++++++++++++++
...estGrpcOMFollowerReadFailoverProxyProvider.java | 228 +++++++++++++++++++++
8 files changed, 755 insertions(+), 289 deletions(-)
diff --git
a/hadoop-ozone/common/src/main/java/org/apache/hadoop/ozone/om/ha/FollowerReadFailoverProxyProviderBase.java
b/hadoop-ozone/common/src/main/java/org/apache/hadoop/ozone/om/ha/FollowerReadFailoverProxyProviderBase.java
new file mode 100644
index 00000000000..3d422ade454
--- /dev/null
+++
b/hadoop-ozone/common/src/main/java/org/apache/hadoop/ozone/om/ha/FollowerReadFailoverProxyProviderBase.java
@@ -0,0 +1,168 @@
+/*
+ * 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.hadoop.ozone.om.ha;
+
+import jakarta.annotation.Nonnull;
+import org.apache.hadoop.ozone.OmUtils;
+import org.apache.hadoop.ozone.om.helpers.ReadConsistency;
+import org.apache.hadoop.ozone.om.protocolPB.OzoneManagerProtocolPB;
+import
org.apache.hadoop.ozone.protocol.proto.OzoneManagerProtocolProtos.OMRequest;
+import
org.apache.hadoop.ozone.protocol.proto.OzoneManagerProtocolProtos.ReadConsistencyHint;
+import org.apache.ratis.util.Preconditions;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * Base class for the OM follower read failover proxy providers.
+ * <p>
+ * It keeps the follower read configuration and selects the OM node to send
follower reads to.
+ * Leader-based failover is delegated to the underlying {@link
OMFailoverProxyProviderBase}.
+ */
+public abstract class FollowerReadFailoverProxyProviderBase {
+ private static final Logger LOG =
LoggerFactory.getLogger(FollowerReadFailoverProxyProviderBase.class);
+
+ /** Whether follower reads are supported by the OM service. */
+ private volatile boolean omServiceSupportsFollowerRead;
+
+ /** Whether eligible reads without an explicit consistency hint use
followers. */
+ private final boolean defaultFollowerReadEnabled;
+
+ /** The read consistency hint used when follower read is enabled. */
+ private final ReadConsistencyHint followerReadConsistency;
+ /** The read consistency hint used when follower read is disabled or when
follower read fails. */
+ private final ReadConsistencyHint leaderReadConsistency;
+
+ /**
+ * The index of the OM node used for follower read, in the order of the
leader proxy's OM nodes.
+ * Should only be accessed in synchronized methods.
+ */
+ private int currentIndex = 0;
+
+ protected FollowerReadFailoverProxyProviderBase(ReadConsistency
followerReadConsistencyType,
+ ReadConsistency leaderReadConsistencyType, boolean
defaultFollowerReadEnabled) {
+ Preconditions.assertTrue(followerReadConsistencyType.allowFollowerRead(),
+ "Invalid follower read consistency " + followerReadConsistencyType);
+ Preconditions.assertTrue(!leaderReadConsistencyType.allowFollowerRead(),
+ "Invalid leader read consistency " + leaderReadConsistencyType);
+ // At the start, we don't know whether OM service supports follower read.
Therefore, if the client
+ // is configured to use follower read, we should assume that OM service
supports follower read and
+ // only sets this to false if there is an evidence otherwise (i.e. OM
throws OMNotLeaderException).
+ this.omServiceSupportsFollowerRead = true;
+ this.defaultFollowerReadEnabled = defaultFollowerReadEnabled;
+ this.followerReadConsistency = followerReadConsistencyType.getHint();
+ this.leaderReadConsistency = leaderReadConsistencyType.getHint();
+ }
+
+ /** @return the inner proxy provider used for leader-based failover. */
+ protected abstract OMFailoverProxyProviderBase<OzoneManagerProtocolPB>
getLeaderProxy();
+
+ public boolean isOmServiceSupportsFollowerRead() {
+ return omServiceSupportsFollowerRead;
+ }
+
+ /**
+ * Stop sending reads to OM followers, since an OM follower does not support
follower read
+ * (i.e. it throws OMNotLeaderException).
+ */
+ protected void disableFollowerRead() {
+ omServiceSupportsFollowerRead = false;
+ }
+
+ /**
+ * Determines whether an eligible read request may be sent to an OM follower.
+ *
+ * <p>An explicit consistency hint takes precedence over the configured
+ * default follower-read behavior.</p>
+ */
+ protected boolean shouldUseFollowerRead(OMRequest request) {
+ if (!omServiceSupportsFollowerRead ||
!OmUtils.shouldSendToFollower(request)) {
+ return false;
+ }
+ if (request.hasReadConsistencyHint()) {
+ return getReadConsistency(request).allowFollowerRead();
+ }
+ return defaultFollowerReadEnabled;
+ }
+
+ /**
+ * Add the default follower or leader read consistency hint to the request
+ * if the request does not have a consistency hint.
+ */
+ protected OMRequest addReadConsistencyHint(OMRequest request, boolean
followerRead) {
+ if (request.hasReadConsistencyHint()) {
+ return request;
+ }
+ final ReadConsistencyHint hint = followerRead ? followerReadConsistency :
leaderReadConsistency;
+ return request.toBuilder().setReadConsistencyHint(hint).build();
+ }
+
+ protected static ReadConsistency getReadConsistency(OMRequest request) {
+ return request.hasReadConsistencyHint()
+ ?
ReadConsistency.fromProto(request.getReadConsistencyHint().getReadConsistency())
+ : ReadConsistency.DEFAULT;
+ }
+
+ protected int getOMNodeCount() {
+ return getLeaderProxy().getOMProxyMap().size();
+ }
+
+ protected synchronized String getCurrentFollowerReadNodeId() {
+ return getLeaderProxy().getOMProxyMap().getNodeId(currentIndex);
+ }
+
+ /**
+ * Move to the next OM node for follower read. If the current node is no
longer
+ * the given node, the call is ignored; this is to handle concurrent calls
+ * (to avoid changing the node multiple times).
+ *
+ * @param nodeId the expected current node.
+ */
+ protected synchronized void changeFollowerReadNodeId(@Nonnull String nodeId)
{
+ if (nodeId.equals(getCurrentFollowerReadNodeId())) {
+ currentIndex = (currentIndex + 1) % getOMNodeCount();
+ LOG.debug("Changed follower read OM node from {} to {}", nodeId,
getCurrentFollowerReadNodeId());
+ }
+ }
+
+ /**
+ * Select the OM node to send a follower read with the given consistency to.
+ * A {@link ReadConsistency#LOCAL_LEASE} read skips the leader known by the
leader proxy.
+ *
+ * @return the selected node, or null if no node other than the known leader
is available.
+ */
+ protected synchronized String selectFollowerReadNodeId(ReadConsistency
readConsistency) {
+ String nodeId = getCurrentFollowerReadNodeId();
+ if (readConsistency != ReadConsistency.LOCAL_LEASE) {
+ return nodeId;
+ }
+
+ final String leaderNodeId = getLeaderProxy().getCurrentProxyOMNodeId();
+ for (int i = 0; i < getOMNodeCount(); i++) {
+ if (!nodeId.equals(leaderNodeId)) {
+ return nodeId;
+ }
+ changeFollowerReadNodeId(nodeId);
+ nodeId = getCurrentFollowerReadNodeId();
+ }
+ return null;
+ }
+
+ public synchronized void changeInitialProxyForTest(String initialOmNodeId) {
+ currentIndex = getLeaderProxy().getOMProxyMap().indexOf(initialOmNodeId);
+ }
+}
diff --git
a/hadoop-ozone/common/src/main/java/org/apache/hadoop/ozone/om/ha/GrpcOMFailoverProxyProvider.java
b/hadoop-ozone/common/src/main/java/org/apache/hadoop/ozone/om/ha/GrpcOMFailoverProxyProvider.java
index d74ac47b538..436a721c182 100644
---
a/hadoop-ozone/common/src/main/java/org/apache/hadoop/ozone/om/ha/GrpcOMFailoverProxyProvider.java
+++
b/hadoop-ozone/common/src/main/java/org/apache/hadoop/ozone/om/ha/GrpcOMFailoverProxyProvider.java
@@ -128,10 +128,6 @@ protected synchronized boolean shouldFailover(Exception
ex) {
return super.shouldFailover(ex);
}
- public synchronized boolean shouldFailoverForFollowerRead(Exception ex) {
- return shouldFailover(ex);
- }
-
@Override
public synchronized void close() throws IOException { }
diff --git
a/hadoop-ozone/common/src/main/java/org/apache/hadoop/ozone/om/ha/GrpcOMFollowerReadFailoverProxyProvider.java
b/hadoop-ozone/common/src/main/java/org/apache/hadoop/ozone/om/ha/GrpcOMFollowerReadFailoverProxyProvider.java
new file mode 100644
index 00000000000..298ee6ad69c
--- /dev/null
+++
b/hadoop-ozone/common/src/main/java/org/apache/hadoop/ozone/om/ha/GrpcOMFollowerReadFailoverProxyProvider.java
@@ -0,0 +1,125 @@
+/*
+ * 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.hadoop.ozone.om.ha;
+
+import static
org.apache.hadoop.ozone.om.ha.OMFailoverProxyProviderBase.getLeaderNotReadyException;
+import static
org.apache.hadoop.ozone.om.ha.OMFailoverProxyProviderBase.getNotLeaderException;
+import static
org.apache.hadoop.ozone.om.ha.OMFailoverProxyProviderBase.getReadException;
+import static
org.apache.hadoop.ozone.om.ha.OMFailoverProxyProviderBase.getReadIndexException;
+
+import io.grpc.StatusRuntimeException;
+import java.io.IOException;
+import org.apache.hadoop.ozone.om.helpers.ReadConsistency;
+import org.apache.hadoop.ozone.om.protocolPB.GrpcOmTransport;
+import org.apache.hadoop.ozone.om.protocolPB.OzoneManagerProtocolPB;
+import
org.apache.hadoop.ozone.protocol.proto.OzoneManagerProtocolProtos.OMRequest;
+import
org.apache.hadoop.ozone.protocol.proto.OzoneManagerProtocolProtos.OMResponse;
+import org.apache.ratis.protocol.exceptions.ReadException;
+import org.apache.ratis.protocol.exceptions.ReadIndexException;
+import org.apache.ratis.util.function.CheckedBiFunction;
+import org.apache.ratis.util.function.CheckedFunction;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * Follower read support for {@link GrpcOmTransport}.
+ * <p>
+ * If follower read is enabled, a read request is sent to the current follower
read OM node,
+ * which can be either a leader or a follower. If the OM node fails, the
request is sent
+ * to the next OM node. If all the OM nodes have failed, the request falls
back to the leader OM.
+ * <p>
+ * Write requests, and read requests when follower read is disabled, are sent
to the leader OM.
+ */
+public class GrpcOMFollowerReadFailoverProxyProvider extends
FollowerReadFailoverProxyProviderBase {
+ private static final Logger LOG =
LoggerFactory.getLogger(GrpcOMFollowerReadFailoverProxyProvider.class);
+
+ /** The inner proxy provider used for leader-based failover. */
+ private final GrpcOMFailoverProxyProvider<OzoneManagerProtocolPB>
leaderProxy;
+
+ public
GrpcOMFollowerReadFailoverProxyProvider(GrpcOMFailoverProxyProvider<OzoneManagerProtocolPB>
leaderProxy,
+ ReadConsistency followerReadConsistencyType, ReadConsistency
leaderReadConsistencyType,
+ boolean defaultFollowerReadEnabled) {
+ super(followerReadConsistencyType, leaderReadConsistencyType,
defaultFollowerReadEnabled);
+ this.leaderProxy = leaderProxy;
+ }
+
+ @Override
+ protected GrpcOMFailoverProxyProvider<OzoneManagerProtocolPB>
getLeaderProxy() {
+ return leaderProxy;
+ }
+
+ /**
+ * Submit the request to an OM follower if follower read is used, otherwise
to the leader OM.
+ *
+ * @param payload the request to submit.
+ * @param submitToHost submits a request to the OM at the given gRPC address.
+ * @param submitToLeader submits a request to the leader OM, failing over
between the OMs if needed.
+ * @return the response of the request.
+ */
+ public OMResponse submitRequest(OMRequest payload,
+ CheckedBiFunction<OMRequest, String, OMResponse, IOException>
submitToHost,
+ CheckedFunction<OMRequest, OMResponse, IOException> submitToLeader)
throws IOException {
+ if (shouldUseFollowerRead(payload)) {
+ OMRequest followerPayload = addReadConsistencyHint(payload, true);
+ ReadConsistency readConsistency = getReadConsistency(payload);
+ int failedCount = 0;
+ for (int i = 0; i < getOMNodeCount(); i++) {
+ String nodeId = selectFollowerReadNodeId(readConsistency);
+ if (nodeId == null) {
+ break;
+ }
+ String followerHost = leaderProxy.getGrpcProxyAddress(nodeId);
+ try {
+ OMResponse response = submitToHost.apply(followerPayload,
followerHost);
+ LOG.debug("Invocation with cmdType {} using follower read host {}
was successful",
+ followerPayload.getCmdType(), followerHost);
+ return response;
+ } catch (StatusRuntimeException e) {
+ LOG.debug("Invocation with cmdType {} using follower read host {}
failed",
+ followerPayload.getCmdType(), followerHost, e);
+ Exception unwrapped = GrpcOmTransport.unwrapException(new
Exception(e));
+ if (getNotLeaderException(unwrapped) != null) {
+ LOG.debug("Encountered OMNotLeaderException from {}. "
+ + "Disable OM follower read and retry OM leader directly.",
followerHost);
+ disableFollowerRead();
+ break;
+ }
+ if (getLeaderNotReadyException(unwrapped) != null) {
+ break;
+ }
+ ReadIndexException readIndexException =
getReadIndexException(unwrapped);
+ ReadException readException = getReadException(unwrapped);
+ if (readIndexException != null || readException != null ||
+ leaderProxy.shouldFailover(unwrapped)) {
+ failedCount++;
+ changeFollowerReadNodeId(nodeId);
+ } else {
+ throw e;
+ }
+ }
+ }
+ if (failedCount > 0) {
+ LOG.warn("{} nodes have failed for read request with cmdType {}.
Falling back to leader.",
+ failedCount, payload.getCmdType());
+ }
+ }
+
+ // Either follower read is not used, or no OM node has served the request.
+ return submitToLeader.apply(addReadConsistencyHint(payload, false));
+ }
+}
diff --git
a/hadoop-ozone/common/src/main/java/org/apache/hadoop/ozone/om/ha/HadoopRpcOMFollowerReadFailoverProxyProvider.java
b/hadoop-ozone/common/src/main/java/org/apache/hadoop/ozone/om/ha/HadoopRpcOMFollowerReadFailoverProxyProvider.java
index 521f843a9e8..56031689e97 100644
---
a/hadoop-ozone/common/src/main/java/org/apache/hadoop/ozone/om/ha/HadoopRpcOMFollowerReadFailoverProxyProvider.java
+++
b/hadoop-ozone/common/src/main/java/org/apache/hadoop/ozone/om/ha/HadoopRpcOMFollowerReadFailoverProxyProvider.java
@@ -35,17 +35,14 @@
import org.apache.hadoop.ipc_.RPC;
import org.apache.hadoop.ipc_.RpcNoSuchProtocolException;
import org.apache.hadoop.ipc_.RpcProxy;
-import org.apache.hadoop.ozone.OmUtils;
import org.apache.hadoop.ozone.om.exceptions.OMLeaderNotReadyException;
import org.apache.hadoop.ozone.om.exceptions.OMNotLeaderException;
import org.apache.hadoop.ozone.om.helpers.ReadConsistency;
import org.apache.hadoop.ozone.om.protocolPB.OzoneManagerProtocolPB;
import
org.apache.hadoop.ozone.protocol.proto.OzoneManagerProtocolProtos.OMRequest;
import
org.apache.hadoop.ozone.protocol.proto.OzoneManagerProtocolProtos.OMResponse;
-import
org.apache.hadoop.ozone.protocol.proto.OzoneManagerProtocolProtos.ReadConsistencyHint;
import org.apache.ratis.protocol.exceptions.ReadException;
import org.apache.ratis.protocol.exceptions.ReadIndexException;
-import org.apache.ratis.util.Preconditions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -66,7 +63,8 @@
* Read and write requests will still be sent to leader OM if reading from
* follower is disabled.
*/
-public class HadoopRpcOMFollowerReadFailoverProxyProvider implements
FailoverProxyProvider<OzoneManagerProtocolPB> {
+public class HadoopRpcOMFollowerReadFailoverProxyProvider extends
FollowerReadFailoverProxyProviderBase
+ implements FailoverProxyProvider<OzoneManagerProtocolPB> {
private static final Logger LOG =
LoggerFactory.getLogger(HadoopRpcOMFollowerReadFailoverProxyProvider.class);
/** The inner proxy provider used for leader-based failover. */
@@ -75,35 +73,15 @@ public class HadoopRpcOMFollowerReadFailoverProxyProvider
implements FailoverPro
/** The combined proxy which redirects to other proxies as necessary. */
private final ProxyInfo<OzoneManagerProtocolPB> combinedProxy;
- /** Whether follower reads are supported by the OM service. */
- private volatile boolean omServiceSupportsFollowerRead;
-
- /** Whether eligible reads without an explicit consistency hint use
followers. */
- private final boolean defaultFollowerReadEnabled;
-
- /**
- * The current index of the underlying leader-based proxy provider's
omNodesInOrder currently being used.
- * Should only be accessed in synchronized methods.
- */
- private int currentIndex = -1;
-
/** The last proxy that has been used. Only used for testing. */
private volatile OMProxyInfo<OzoneManagerProtocolPB> lastProxy = null;
- /** The read consistency hint used when follower read is enabled. */
- private final ReadConsistencyHint followerReadConsistency;
- /** The read consistency hint used when follower read is disabled or when
follower read fails. */
- private final ReadConsistencyHint leaderReadConsistency;
-
public HadoopRpcOMFollowerReadFailoverProxyProvider(
HadoopRpcOMFailoverProxyProvider<OzoneManagerProtocolPB> leaderProxy,
ReadConsistency followerReadConsistencyType,
ReadConsistency leaderReadConsistencyType,
boolean defaultFollowerReadEnabled) {
- Preconditions.assertTrue(followerReadConsistencyType.allowFollowerRead(),
- "Invalid follower read consistency " + followerReadConsistencyType);
- Preconditions.assertTrue(!leaderReadConsistencyType.allowFollowerRead(),
- "Invalid leader read consistency " + leaderReadConsistencyType);
+ super(followerReadConsistencyType, leaderReadConsistencyType,
defaultFollowerReadEnabled);
this.leaderProxy = leaderProxy;
// Create a wrapped proxy containing all the proxies. Since this combined
// proxy is just redirecting to other proxies, all invocations can share
it.
@@ -111,13 +89,11 @@ public HadoopRpcOMFollowerReadFailoverProxyProvider(
.map(a -> a.proxyInfo)
.reduce((a, b) -> a + ", " + b).orElse("") + "]";
combinedProxy = new ProxyInfo<>(new FollowerReadProxy(), combinedInfo);
- // At the start, we don't know whether OM service supports follower read.
Therefore, if the client
- // is configured to use follower read, we should assume that OM service
supports follower read and
- // only sets this to false if there is an evidence otherwise (i.e. OM
throws OMNotLeaderException).
- this.omServiceSupportsFollowerRead = true;
- this.defaultFollowerReadEnabled = defaultFollowerReadEnabled;
- this.followerReadConsistency = followerReadConsistencyType.getHint();
- this.leaderReadConsistency = leaderReadConsistencyType.getHint();
+ }
+
+ @Override
+ protected HadoopRpcOMFailoverProxyProvider<OzoneManagerProtocolPB>
getLeaderProxy() {
+ return leaderProxy;
}
@Override
@@ -182,16 +158,7 @@ private OMRequest applyReadConsistency(OMRequest request)
throws ServiceExceptio
// Reject invalid requests before entering the retry loop.
throw new ServiceException(new RpcNoSuchProtocolException("OMRequest
== null"));
}
- if (!request.hasReadConsistencyHint()) {
- ReadConsistencyHint hint = omServiceSupportsFollowerRead
- && defaultFollowerReadEnabled &&
OmUtils.shouldSendToFollower(request)
- ? followerReadConsistency
- : leaderReadConsistency;
- if (hint != null) {
- return request.toBuilder().setReadConsistencyHint(hint).build();
- }
- }
- return request;
+ return addReadConsistencyHint(request, shouldUseFollowerRead(request));
}
@Override
@@ -205,67 +172,17 @@ public void close() throws IOException {
}
}
- private static ReadConsistency getReadConsistency(OMRequest omRequest) {
- return omRequest.hasReadConsistencyHint()
- ? ReadConsistency.fromProto(omRequest.getReadConsistencyHint()
- .getReadConsistency())
- : ReadConsistency.DEFAULT;
- }
-
@VisibleForTesting
public ProxyInfo<OzoneManagerProtocolPB> getLastProxy() {
return lastProxy;
}
/**
- * Return the currently used proxy. If there is none, first calls
- * {@link #changeProxy(OMProxyInfo)} to initialize one.
+ * Return the proxy of the OM node currently used for follower read.
*/
@VisibleForTesting
public OMProxyInfo<OzoneManagerProtocolPB> getCurrentProxy() {
- return changeProxy(null);
- }
-
- /**
- * Move to the next proxy in the proxy list. If the OMProxyInfo supplied by
- * the caller does not match the current proxy, the call is ignored; this is
- * to handle concurrent calls (to avoid changing the proxy multiple times).
- * The service state of the newly selected proxy will be updated before
- * returning.
- *
- * @param initial The expected current proxy
- * @return The new proxy that should be used.
- */
- private synchronized OMProxyInfo<OzoneManagerProtocolPB>
changeProxy(OMProxyInfo<OzoneManagerProtocolPB> initial) {
- OMProxyInfo<OzoneManagerProtocolPB> currentProxy =
leaderProxy.getOMProxyMap().get(currentIndex);
- if (currentProxy != initial) {
- // Must have been a concurrent modification; ignore the move request
- return currentProxy;
- }
- final OMProxyInfo.OrderedMap<OzoneManagerProtocolPB> omProxies =
leaderProxy.getOMProxyMap();
- currentIndex = (currentIndex + 1) % omProxies.size();
- final String currentOmNodeId = omProxies.getNodeId(currentIndex);
- currentProxy = leaderProxy.createOMProxyIfNeeded(currentOmNodeId);
- LOG.debug("Changed current proxy from {} to {}",
- initial == null ? "none" : initial.proxyInfo,
- currentProxy.proxyInfo);
- return currentProxy;
- }
-
- private OMProxyInfo<OzoneManagerProtocolPB> getCurrentProxy(ReadConsistency
readConsistency) {
- OMProxyInfo<OzoneManagerProtocolPB> current = getCurrentProxy();
- if (readConsistency != ReadConsistency.LOCAL_LEASE) {
- return current;
- }
-
- String leaderNodeId = leaderProxy.getCurrentProxyOMNodeId();
- for (int i = 0; i < leaderProxy.getOMProxyMap().size(); i++) {
- if (!current.getNodeId().equals(leaderNodeId)) {
- return current;
- }
- current = changeProxy(current);
- }
- return null;
+ return leaderProxy.createOMProxyIfNeeded(getCurrentFollowerReadNodeId());
}
/**
@@ -283,17 +200,14 @@ private class FollowerReadProxy implements
OzoneManagerProtocolPB, RpcProxy {
public OMResponse submitRequest(RpcController controller, OMRequest
omRequest) throws ServiceException {
lastProxy = null;
ReadConsistency readConsistency = getReadConsistency(omRequest);
- boolean isFollowerReadEligible =
- OMFailoverProxyProviderBase.shouldUseFollowerRead(omRequest,
- omServiceSupportsFollowerRead, defaultFollowerReadEnabled);
-
- if (isFollowerReadEligible) {
+ if (shouldUseFollowerRead(omRequest)) {
int failedCount = 0;
- for (int i = 0; i < leaderProxy.getOMProxyMap().size(); i++) {
- OMProxyInfo<OzoneManagerProtocolPB> current =
getCurrentProxy(readConsistency);
- if (current == null) {
+ for (int i = 0; i < getOMNodeCount(); i++) {
+ final String nodeId = selectFollowerReadNodeId(readConsistency);
+ if (nodeId == null) {
break;
}
+ final OMProxyInfo<OzoneManagerProtocolPB> current =
leaderProxy.createOMProxyIfNeeded(nodeId);
LOG.debug("Attempting to service submitRequest with cmdType {} using
proxy {}",
omRequest.getCmdType(), current.proxyInfo);
try {
@@ -325,7 +239,7 @@ public OMResponse submitRequest(RpcController controller,
OMRequest omRequest) t
// the OM follower does not support / disable follower read or
something is misconfigured
LOG.debug("Encountered OMNotLeaderException from {}. " +
"Disable OM follower read and retry OM leader directly.",
current.proxyInfo);
- omServiceSupportsFollowerRead = false;
+ disableFollowerRead();
// Break here instead of throwing exception so that it is not
counted
// as a failover
break;
@@ -372,7 +286,7 @@ public OMResponse submitRequest(RpcController controller,
OMRequest omRequest) t
LOG.warn(
"Invocation with cmdType {} returned exception on [{}]; {}
failure(s) so far",
omRequest.getCmdType(), current.proxyInfo, failedCount, e);
- changeProxy(current);
+ changeFollowerReadNodeId(nodeId);
}
}
}
@@ -427,7 +341,7 @@ public ConnectionId getConnectionId() {
// visibility hazard, not a tearing one -- but the outcome is the
// same: a stale proxy whose underlying connection has been
// stopped is dialed instead of the live replacement.
- return RPC.getConnectionIdForProxy(omServiceSupportsFollowerRead
+ return RPC.getConnectionIdForProxy(isOmServiceSupportsFollowerRead()
? getCurrentProxy().getProxy() : leaderProxy.getProxy().getProxy());
}
}
@@ -439,31 +353,11 @@ public synchronized void close() throws IOException {
leaderProxy.close();
}
- @VisibleForTesting
- public boolean isOmServiceSupportsFollowerRead() {
- return omServiceSupportsFollowerRead;
- }
-
@VisibleForTesting
public List<OMProxyInfo<OzoneManagerProtocolPB>> getOMProxies() {
return leaderProxy.getOMProxies();
}
- public synchronized void changeInitialProxyForTest(String initialOmNodeId) {
- final OMProxyInfo<OzoneManagerProtocolPB> currentProxy =
leaderProxy.getOMProxyMap().get(currentIndex);
- if (currentProxy != null &&
currentProxy.getNodeId().equals(initialOmNodeId)) {
- return;
- }
-
- Integer indexOfTargetNodeId =
leaderProxy.getOMProxyMap().indexOf(initialOmNodeId);
- if (indexOfTargetNodeId == null) {
- return;
- }
-
- currentIndex = indexOfTargetNodeId;
- leaderProxy.createOMProxyIfNeeded(initialOmNodeId);
- }
-
/**
* Preserve ServiceException instances and wrap other failures in the
protocol's declared exception type.
*/
diff --git
a/hadoop-ozone/common/src/main/java/org/apache/hadoop/ozone/om/ha/OMFailoverProxyProviderBase.java
b/hadoop-ozone/common/src/main/java/org/apache/hadoop/ozone/om/ha/OMFailoverProxyProviderBase.java
index 7486c76e6fb..ad177a5195d 100644
---
a/hadoop-ozone/common/src/main/java/org/apache/hadoop/ozone/om/ha/OMFailoverProxyProviderBase.java
+++
b/hadoop-ozone/common/src/main/java/org/apache/hadoop/ozone/om/ha/OMFailoverProxyProviderBase.java
@@ -44,8 +44,6 @@
import org.apache.hadoop.ozone.om.exceptions.OMException;
import org.apache.hadoop.ozone.om.exceptions.OMLeaderNotReadyException;
import org.apache.hadoop.ozone.om.exceptions.OMNotLeaderException;
-import org.apache.hadoop.ozone.om.helpers.ReadConsistency;
-import
org.apache.hadoop.ozone.protocol.proto.OzoneManagerProtocolProtos.OMRequest;
import org.apache.hadoop.security.AccessControlException;
import org.apache.hadoop.security.UserGroupInformation;
import org.apache.hadoop.security.token.SecretManager;
@@ -428,25 +426,6 @@ public List<OMProxyInfo<T>> getOMProxies() {
return omProxies.getProxies();
}
- /**
- * Determines whether an eligible read request may be sent to an OM follower.
- *
- * <p>An explicit consistency hint takes precedence over the configured
- * default follower-read behavior.</p>
- */
- public static boolean shouldUseFollowerRead(OMRequest request,
- boolean omServiceSupportsFollowerRead,
- boolean defaultFollowerReadEnabled) {
- if (!omServiceSupportsFollowerRead ||
!OmUtils.shouldSendToFollower(request)) {
- return false;
- }
- if (request.hasReadConsistencyHint()) {
- return ReadConsistency.fromProto(request.getReadConsistencyHint()
- .getReadConsistency()).allowFollowerRead();
- }
- return defaultFollowerReadEnabled;
- }
-
public OMProxyInfo.OrderedMap<T> getOMProxyMap() {
return omProxies;
}
diff --git
a/hadoop-ozone/common/src/main/java/org/apache/hadoop/ozone/om/protocolPB/GrpcOmTransport.java
b/hadoop-ozone/common/src/main/java/org/apache/hadoop/ozone/om/protocolPB/GrpcOmTransport.java
index 70d81afe5b9..4507075126c 100644
---
a/hadoop-ozone/common/src/main/java/org/apache/hadoop/ozone/om/protocolPB/GrpcOmTransport.java
+++
b/hadoop-ozone/common/src/main/java/org/apache/hadoop/ozone/om/protocolPB/GrpcOmTransport.java
@@ -55,18 +55,14 @@
import org.apache.hadoop.ozone.om.exceptions.OMException;
import org.apache.hadoop.ozone.om.exceptions.OMException.ResultCodes;
import org.apache.hadoop.ozone.om.ha.GrpcOMFailoverProxyProvider;
-import org.apache.hadoop.ozone.om.ha.OMFailoverProxyProviderBase;
+import org.apache.hadoop.ozone.om.ha.GrpcOMFollowerReadFailoverProxyProvider;
import org.apache.hadoop.ozone.om.helpers.ReadConsistency;
import
org.apache.hadoop.ozone.om.protocolPB.grpc.ClientAddressClientInterceptor;
import org.apache.hadoop.ozone.om.protocolPB.grpc.GrpcClientConstants;
import
org.apache.hadoop.ozone.protocol.proto.OzoneManagerProtocolProtos.OMRequest;
import
org.apache.hadoop.ozone.protocol.proto.OzoneManagerProtocolProtos.OMResponse;
-import
org.apache.hadoop.ozone.protocol.proto.OzoneManagerProtocolProtos.ReadConsistencyHint;
import org.apache.hadoop.ozone.protocol.proto.OzoneManagerServiceGrpc;
import org.apache.hadoop.security.UserGroupInformation;
-import org.apache.ratis.protocol.exceptions.ReadException;
-import org.apache.ratis.protocol.exceptions.ReadIndexException;
-import org.apache.ratis.util.Preconditions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -98,11 +94,7 @@ public class GrpcOmTransport implements OmTransport {
private RetryPolicy retryPolicy;
private final GrpcOMFailoverProxyProvider<OzoneManagerProtocolPB>
omFailoverProxyProvider;
- private final boolean defaultFollowerReadEnabled;
- private volatile boolean omServiceSupportsFollowerRead;
- private final ReadConsistencyHint followerReadConsistency;
- private final ReadConsistencyHint leaderReadConsistency;
- private int currentFollowerReadIndex;
+ private final GrpcOMFollowerReadFailoverProxyProvider
followerReadFailoverProxyProvider;
public static void setCaCerts(List<X509Certificate> x509Certificates) {
caCerts = x509Certificates;
@@ -128,10 +120,9 @@ public GrpcOmTransport(ConfigurationSource conf,
omServiceId,
OzoneManagerProtocolPB.class);
- this.defaultFollowerReadEnabled = conf.getBoolean(
+ boolean defaultFollowerReadEnabled = conf.getBoolean(
OzoneConfigKeys.OZONE_CLIENT_FOLLOWER_READ_ENABLED_KEY,
OzoneConfigKeys.OZONE_CLIENT_FOLLOWER_READ_ENABLED_DEFAULT);
- this.omServiceSupportsFollowerRead = true;
String defaultFollowerReadConsistencyStr = conf.get(
OzoneConfigKeys.OZONE_CLIENT_FOLLOWER_READ_DEFAULT_CONSISTENCY_KEY,
OzoneConfigKeys.OZONE_CLIENT_FOLLOWER_READ_DEFAULT_CONSISTENCY_DEFAULT
@@ -143,12 +134,8 @@ public GrpcOmTransport(ConfigurationSource conf,
OzoneConfigKeys.OZONE_CLIENT_LEADER_READ_DEFAULT_CONSISTENCY_DEFAULT);
ReadConsistency defaultLeaderReadConsistency =
ReadConsistency.valueOf(defaultLeaderReadConsistencyStr);
-
Preconditions.assertTrue(defaultFollowerReadConsistency.allowFollowerRead(),
- "Invalid follower read consistency " + defaultFollowerReadConsistency);
- Preconditions.assertTrue(!defaultLeaderReadConsistency.allowFollowerRead(),
- "Invalid leader read consistency " + defaultLeaderReadConsistency);
- this.followerReadConsistency = defaultFollowerReadConsistency.getHint();
- this.leaderReadConsistency = defaultLeaderReadConsistency.getHint();
+ this.followerReadFailoverProxyProvider = new
GrpcOMFollowerReadFailoverProxyProvider(omFailoverProxyProvider,
+ defaultFollowerReadConsistency, defaultLeaderReadConsistency,
defaultFollowerReadEnabled);
start();
}
@@ -207,68 +194,8 @@ public void start() throws IOException {
@Override
public OMResponse submitRequest(OMRequest payload) throws IOException {
- if (shouldUseFollowerRead(payload)) {
- return submitRequestWithFollowerRead(payload);
- }
- return submitRequestToLeader(addReadConsistencyHint(payload,
- leaderReadConsistency));
- }
-
- private boolean shouldUseFollowerRead(OMRequest payload) {
- return OMFailoverProxyProviderBase.shouldUseFollowerRead(payload,
- omServiceSupportsFollowerRead, defaultFollowerReadEnabled);
- }
-
- private OMResponse submitRequestWithFollowerRead(OMRequest payload)
- throws IOException {
- OMRequest followerPayload = addReadConsistencyHint(payload,
- followerReadConsistency);
- ReadConsistency readConsistency = getReadConsistency(payload);
- int failedCount = 0;
- for (int i = 0;
- i < omFailoverProxyProvider.getOMProxyMap().getNodeIds().size(); i++)
{
- String nodeId = selectFollowerReadNodeId(readConsistency);
- if (nodeId == null) {
- break;
- }
- String followerHost =
omFailoverProxyProvider.getGrpcProxyAddress(nodeId);
- try {
- OMResponse response = submitRequestToHost(followerPayload,
followerHost);
- LOG.debug("Invocation with cmdType {} using follower read host {} was
successful",
- followerPayload.getCmdType(), followerHost);
- return response;
- } catch (StatusRuntimeException e) {
- LOG.debug("Invocation with cmdType {} using follower read host {}
failed",
- followerPayload.getCmdType(), followerHost, e);
- Exception unwrapped = unwrapException(new Exception(e));
- if (OMFailoverProxyProviderBase.getNotLeaderException(unwrapped) !=
null) {
- LOG.debug("Encountered OMNotLeaderException from {}. Disable OM
follower read and retry OM leader directly.",
- followerHost);
- omServiceSupportsFollowerRead = false;
- break;
- }
- if (OMFailoverProxyProviderBase.getLeaderNotReadyException(unwrapped)
!= null) {
- break;
- }
- ReadIndexException readIndexException =
- OMFailoverProxyProviderBase.getReadIndexException(unwrapped);
- ReadException readException =
- OMFailoverProxyProviderBase.getReadException(unwrapped);
- if (readIndexException != null || readException != null ||
- omFailoverProxyProvider.shouldFailoverForFollowerRead(unwrapped)) {
- failedCount++;
- changeFollowerReadProxy(nodeId);
- } else {
- throw e;
- }
- }
- }
- if (failedCount > 0) {
- LOG.warn("{} nodes have failed for read request with cmdType {}. Falling
back to leader.",
- failedCount, payload.getCmdType());
- }
- return submitRequestToLeader(addReadConsistencyHint(payload,
- leaderReadConsistency));
+ return followerReadFailoverProxyProvider.submitRequest(payload,
this::submitRequestToHost,
+ this::submitRequestToLeader);
}
private OMResponse submitRequestToLeader(OMRequest payload)
@@ -316,56 +243,7 @@ private OMResponse submitRequestToHost(OMRequest payload,
String targetHost)
return resp.get();
}
- private OMRequest addReadConsistencyHint(OMRequest payload,
- ReadConsistencyHint readConsistencyHint) {
- if (!payload.hasReadConsistencyHint() && readConsistencyHint != null) {
- return payload.toBuilder()
- .setReadConsistencyHint(readConsistencyHint)
- .build();
- }
- return payload;
- }
-
- private synchronized String getCurrentFollowerReadNodeId() {
- return new
ArrayList<>(omFailoverProxyProvider.getOMProxyMap().getNodeIds())
- .get(currentFollowerReadIndex);
- }
-
- private synchronized String selectFollowerReadNodeId(
- ReadConsistency readConsistency) {
- String nodeId = getCurrentFollowerReadNodeId();
- if (readConsistency != ReadConsistency.LOCAL_LEASE) {
- return nodeId;
- }
-
- String leaderNodeId = omFailoverProxyProvider.getCurrentProxyOMNodeId();
- for (int i = 0; i <
omFailoverProxyProvider.getOMProxyMap().getNodeIds().size();
- i++) {
- if (!nodeId.equals(leaderNodeId)) {
- return nodeId;
- }
- changeFollowerReadProxy(nodeId);
- nodeId = getCurrentFollowerReadNodeId();
- }
- return null;
- }
-
- private synchronized void changeFollowerReadProxy(String currentNodeId) {
- String currentFollowerReadNodeId = getCurrentFollowerReadNodeId();
- if (currentFollowerReadNodeId.equals(currentNodeId)) {
- currentFollowerReadIndex = (currentFollowerReadIndex + 1) %
- omFailoverProxyProvider.getOMProxyMap().getNodeIds().size();
- }
- }
-
- private static ReadConsistency getReadConsistency(OMRequest request) {
- return request.hasReadConsistencyHint()
- ? ReadConsistency.fromProto(request.getReadConsistencyHint()
- .getReadConsistency())
- : ReadConsistency.DEFAULT;
- }
-
- private Exception unwrapException(Exception ex) {
+ public static Exception unwrapException(Exception ex) {
Exception grpcException = null;
try {
StatusRuntimeException srexp =
@@ -534,15 +412,8 @@ public void startClient(String nodeId, ManagedChannel
testChannel) throws IOExce
}
@VisibleForTesting
- public synchronized void changeFollowerReadInitialProxy(String nodeId) {
- List<String> nodeIds = new ArrayList<>(
- omFailoverProxyProvider.getOMProxyMap().getNodeIds());
- for (int i = 0; i < nodeIds.size(); i++) {
- if (nodeIds.get(i).equals(nodeId)) {
- currentFollowerReadIndex = i;
- return;
- }
- }
+ public void changeFollowerReadInitialProxy(String nodeId) {
+ followerReadFailoverProxyProvider.changeInitialProxyForTest(nodeId);
}
@VisibleForTesting
diff --git
a/hadoop-ozone/common/src/test/java/org/apache/hadoop/ozone/om/ha/TestFollowerReadFailoverProxyProviderBase.java
b/hadoop-ozone/common/src/test/java/org/apache/hadoop/ozone/om/ha/TestFollowerReadFailoverProxyProviderBase.java
new file mode 100644
index 00000000000..baf68006222
--- /dev/null
+++
b/hadoop-ozone/common/src/test/java/org/apache/hadoop/ozone/om/ha/TestFollowerReadFailoverProxyProviderBase.java
@@ -0,0 +1,205 @@
+/*
+ * 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.hadoop.ozone.om.ha;
+
+import static org.apache.hadoop.ozone.om.OMConfigKeys.OZONE_OM_ADDRESS_KEY;
+import static org.apache.hadoop.ozone.om.OMConfigKeys.OZONE_OM_NODES_KEY;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertNull;
+import static org.junit.jupiter.api.Assertions.assertSame;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.List;
+import org.apache.hadoop.hdds.conf.OzoneConfiguration;
+import org.apache.hadoop.ozone.ha.ConfUtils;
+import org.apache.hadoop.ozone.om.helpers.ReadConsistency;
+import org.apache.hadoop.ozone.om.protocolPB.OzoneManagerProtocolPB;
+import
org.apache.hadoop.ozone.protocol.proto.OzoneManagerProtocolProtos.OMRequest;
+import org.apache.hadoop.ozone.protocol.proto.OzoneManagerProtocolProtos.Type;
+import org.apache.hadoop.security.UserGroupInformation;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.ValueSource;
+
+/**
+ * Tests for {@link FollowerReadFailoverProxyProviderBase}.
+ */
+public class TestFollowerReadFailoverProxyProviderBase {
+ private static final String OM_SERVICE_ID = "om-service-test1";
+
+ private HadoopRpcOMFailoverProxyProvider<OzoneManagerProtocolPB> leaderProxy;
+ /** The OM nodes in the order used for follower read. */
+ private List<String> nodeIds;
+
+ @BeforeEach
+ void setUp() throws IOException {
+ leaderProxy = newLeaderProxy("om1", "om2", "om3");
+ nodeIds = new ArrayList<>(leaderProxy.getOMProxyMap().getNodeIds());
+ }
+
+ @Test
+ void testRejectInvalidReadConsistency() {
+ assertThrows(IllegalStateException.class, () -> new
FollowerReadProvider(leaderProxy,
+ ReadConsistency.LINEARIZABLE_LEADER_ONLY, ReadConsistency.DEFAULT,
true));
+ assertThrows(IllegalStateException.class, () -> new
FollowerReadProvider(leaderProxy,
+ ReadConsistency.LOCAL_LEASE, ReadConsistency.LOCAL_LEASE, true));
+ }
+
+ @ParameterizedTest
+ @ValueSource(booleans = {true, false})
+ void testReadWithoutHintUsesFollowerReadDefault(boolean
defaultFollowerReadEnabled) {
+ final FollowerReadProvider provider =
newProvider(defaultFollowerReadEnabled);
+
+ assertEquals(defaultFollowerReadEnabled,
provider.shouldUseFollowerRead(newRequest(Type.ListVolume)));
+ assertFalse(provider.shouldUseFollowerRead(newRequest(Type.CreateVolume)));
+ }
+
+ @Test
+ void testReadConsistencyHintOverridesFollowerReadDefault() {
+ final FollowerReadProvider disabledByDefault = newProvider(false);
+
assertTrue(disabledByDefault.shouldUseFollowerRead(newReadRequest(ReadConsistency.LOCAL_LEASE)));
+
assertTrue(disabledByDefault.shouldUseFollowerRead(newReadRequest(ReadConsistency.LINEARIZABLE_ALLOW_FOLLOWER)));
+
+ final FollowerReadProvider enabledByDefault = newProvider(true);
+
assertFalse(enabledByDefault.shouldUseFollowerRead(newReadRequest(ReadConsistency.LINEARIZABLE_LEADER_ONLY)));
+
assertFalse(enabledByDefault.shouldUseFollowerRead(newReadRequest(ReadConsistency.DEFAULT)));
+ }
+
+ @Test
+ void testNoFollowerReadAfterFollowerReadIsDisabled() {
+ final FollowerReadProvider provider = newProvider(true);
+ assertTrue(provider.isOmServiceSupportsFollowerRead());
+
+ provider.disableFollowerRead();
+
+ assertFalse(provider.isOmServiceSupportsFollowerRead());
+ assertFalse(provider.shouldUseFollowerRead(newRequest(Type.ListVolume)));
+
assertFalse(provider.shouldUseFollowerRead(newReadRequest(ReadConsistency.LOCAL_LEASE)));
+ }
+
+ @Test
+ void testAddReadConsistencyHint() {
+ final FollowerReadProvider provider = newProvider(true);
+
+ final OMRequest withoutHint = newRequest(Type.ListVolume);
+ assertEquals(ReadConsistency.LINEARIZABLE_ALLOW_FOLLOWER.getHint(),
+ provider.addReadConsistencyHint(withoutHint,
true).getReadConsistencyHint());
+ assertEquals(ReadConsistency.DEFAULT.getHint(),
+ provider.addReadConsistencyHint(withoutHint,
false).getReadConsistencyHint());
+
+ // An existing hint is kept.
+ final OMRequest withHint = newReadRequest(ReadConsistency.LOCAL_LEASE);
+ assertSame(withHint, provider.addReadConsistencyHint(withHint, true));
+ assertSame(withHint, provider.addReadConsistencyHint(withHint, false));
+ }
+
+ @Test
+ void testChangeFollowerReadNode() {
+ final FollowerReadProvider provider = newProvider(true);
+ assertEquals(nodeIds.get(0), provider.getCurrentFollowerReadNodeId());
+
+ provider.changeFollowerReadNodeId(nodeIds.get(0));
+ assertEquals(nodeIds.get(1), provider.getCurrentFollowerReadNodeId());
+
+ // A change from a node which is no longer the current node is ignored.
+ provider.changeFollowerReadNodeId(nodeIds.get(0));
+ assertEquals(nodeIds.get(1), provider.getCurrentFollowerReadNodeId());
+
+ // The change goes back to the first node after the last node.
+ provider.changeFollowerReadNodeId(nodeIds.get(1));
+ provider.changeFollowerReadNodeId(nodeIds.get(2));
+ assertEquals(nodeIds.get(0), provider.getCurrentFollowerReadNodeId());
+
+ provider.changeInitialProxyForTest(nodeIds.get(2));
+ assertEquals(nodeIds.get(2), provider.getCurrentFollowerReadNodeId());
+ }
+
+ @Test
+ void testOnlyLocalLeaseReadSkipsLeader() {
+ final FollowerReadProvider provider = newProvider(true);
+ changeLeader(nodeIds.get(0));
+
+ assertEquals(nodeIds.get(0),
provider.selectFollowerReadNodeId(ReadConsistency.LINEARIZABLE_ALLOW_FOLLOWER));
+ assertEquals(nodeIds.get(1),
provider.selectFollowerReadNodeId(ReadConsistency.LOCAL_LEASE));
+ assertEquals(nodeIds.get(1), provider.getCurrentFollowerReadNodeId());
+ }
+
+ @Test
+ void testLocalLeaseReadWithoutFollower() throws Exception {
+ final FollowerReadProvider provider = new
FollowerReadProvider(newLeaderProxy("om1"),
+ ReadConsistency.LINEARIZABLE_ALLOW_FOLLOWER, ReadConsistency.DEFAULT,
true);
+
+ assertNull(provider.selectFollowerReadNodeId(ReadConsistency.LOCAL_LEASE));
+ }
+
+ private static HadoopRpcOMFailoverProxyProvider<OzoneManagerProtocolPB>
newLeaderProxy(String... omNodeIds)
+ throws IOException {
+ final OzoneConfiguration conf = new OzoneConfiguration();
+ conf.set(ConfUtils.addKeySuffixes(OZONE_OM_NODES_KEY, OM_SERVICE_ID),
String.join(",", omNodeIds));
+ for (String nodeId : omNodeIds) {
+ conf.set(ConfUtils.addKeySuffixes(OZONE_OM_ADDRESS_KEY, OM_SERVICE_ID,
nodeId), "localhost:8080");
+ }
+ return new HadoopRpcOMFailoverProxyProvider<>(conf,
UserGroupInformation.getCurrentUser(),
+ OM_SERVICE_ID, OzoneManagerProtocolPB.class);
+ }
+
+ private FollowerReadProvider newProvider(boolean defaultFollowerReadEnabled)
{
+ return new FollowerReadProvider(leaderProxy,
ReadConsistency.LINEARIZABLE_ALLOW_FOLLOWER,
+ ReadConsistency.DEFAULT, defaultFollowerReadEnabled);
+ }
+
+ private void changeLeader(String nodeId) {
+ leaderProxy.setNextOmProxy(nodeId);
+ leaderProxy.performFailover(null);
+ }
+
+ private static OMRequest newRequest(Type cmdType) {
+ return OMRequest.newBuilder()
+ .setCmdType(cmdType)
+ .setClientId("test")
+ .build();
+ }
+
+ private static OMRequest newReadRequest(ReadConsistency readConsistency) {
+ return newRequest(Type.ListVolume).toBuilder()
+ .setReadConsistencyHint(readConsistency.getHint())
+ .build();
+ }
+
+ /** A provider with only the base class logic. */
+ private static final class FollowerReadProvider extends
FollowerReadFailoverProxyProviderBase {
+ private final HadoopRpcOMFailoverProxyProvider<OzoneManagerProtocolPB>
leaderProxy;
+
+
FollowerReadProvider(HadoopRpcOMFailoverProxyProvider<OzoneManagerProtocolPB>
leaderProxy,
+ ReadConsistency followerReadConsistency, ReadConsistency
leaderReadConsistency,
+ boolean defaultFollowerReadEnabled) {
+ super(followerReadConsistency, leaderReadConsistency,
defaultFollowerReadEnabled);
+ this.leaderProxy = leaderProxy;
+ }
+
+ @Override
+ protected HadoopRpcOMFailoverProxyProvider<OzoneManagerProtocolPB>
getLeaderProxy() {
+ return leaderProxy;
+ }
+ }
+}
diff --git
a/hadoop-ozone/common/src/test/java/org/apache/hadoop/ozone/om/ha/TestGrpcOMFollowerReadFailoverProxyProvider.java
b/hadoop-ozone/common/src/test/java/org/apache/hadoop/ozone/om/ha/TestGrpcOMFollowerReadFailoverProxyProvider.java
new file mode 100644
index 00000000000..322841a6ad2
--- /dev/null
+++
b/hadoop-ozone/common/src/test/java/org/apache/hadoop/ozone/om/ha/TestGrpcOMFollowerReadFailoverProxyProvider.java
@@ -0,0 +1,228 @@
+/*
+ * 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.hadoop.ozone.om.ha;
+
+import static org.apache.hadoop.ozone.om.OMConfigKeys.OZONE_OM_ADDRESS_KEY;
+import static org.apache.hadoop.ozone.om.OMConfigKeys.OZONE_OM_GRPC_PORT_KEY;
+import static org.apache.hadoop.ozone.om.OMConfigKeys.OZONE_OM_NODES_KEY;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertSame;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+import io.grpc.Status;
+import io.grpc.StatusRuntimeException;
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.stream.Stream;
+import org.apache.hadoop.hdds.conf.OzoneConfiguration;
+import org.apache.hadoop.ozone.ha.ConfUtils;
+import org.apache.hadoop.ozone.om.exceptions.OMLeaderNotReadyException;
+import org.apache.hadoop.ozone.om.exceptions.OMNotLeaderException;
+import org.apache.hadoop.ozone.om.helpers.ReadConsistency;
+import org.apache.hadoop.ozone.om.protocolPB.OzoneManagerProtocolPB;
+import
org.apache.hadoop.ozone.protocol.proto.OzoneManagerProtocolProtos.OMRequest;
+import
org.apache.hadoop.ozone.protocol.proto.OzoneManagerProtocolProtos.OMResponse;
+import org.apache.hadoop.ozone.protocol.proto.OzoneManagerProtocolProtos.Type;
+import org.apache.hadoop.security.UserGroupInformation;
+import org.apache.ratis.protocol.RaftPeerId;
+import org.apache.ratis.protocol.exceptions.ReadException;
+import org.apache.ratis.protocol.exceptions.ReadIndexException;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.MethodSource;
+
+/**
+ * Tests for {@link GrpcOMFollowerReadFailoverProxyProvider}.
+ */
+public class TestGrpcOMFollowerReadFailoverProxyProvider {
+ private static final String OM_SERVICE_ID = "om-service-test1";
+
+ private GrpcOMFollowerReadFailoverProxyProvider provider;
+ /** The OM nodes in the order used for follower read. */
+ private List<String> nodeIds;
+ private final Map<String, String> hostToNodeId = new HashMap<>();
+
+ /** The failure that an OM node returns. An OM node without a failure serves
the request. */
+ private final Map<String, StatusRuntimeException> failures = new HashMap<>();
+ /** The requests sent to each OM node directly. */
+ private final Map<String, List<OMRequest>> nodeRequests = new HashMap<>();
+ /** The requests sent to the leader OM through the leader-based failover. */
+ private final List<OMRequest> leaderRequests = new ArrayList<>();
+
+ @BeforeEach
+ void setUp() throws IOException {
+ final OzoneConfiguration conf = new OzoneConfiguration();
+ conf.set(ConfUtils.addKeySuffixes(OZONE_OM_NODES_KEY, OM_SERVICE_ID),
"om1,om2,om3");
+ for (int i = 1; i <= 3; i++) {
+ conf.set(ConfUtils.addKeySuffixes(OZONE_OM_ADDRESS_KEY, OM_SERVICE_ID,
"om" + i), "localhost");
+ conf.setInt(ConfUtils.addKeySuffixes(OZONE_OM_GRPC_PORT_KEY,
OM_SERVICE_ID, "om" + i), 19880 + i);
+ }
+ final GrpcOMFailoverProxyProvider<OzoneManagerProtocolPB> leaderProxy =
new GrpcOMFailoverProxyProvider<>(
+ conf, UserGroupInformation.getCurrentUser(), OM_SERVICE_ID,
OzoneManagerProtocolPB.class);
+ nodeIds = new ArrayList<>(leaderProxy.getOMProxyMap().getNodeIds());
+ for (String nodeId : nodeIds) {
+ hostToNodeId.put(leaderProxy.getGrpcProxyAddress(nodeId), nodeId);
+ nodeRequests.put(nodeId, new ArrayList<>());
+ }
+ provider = new GrpcOMFollowerReadFailoverProxyProvider(leaderProxy,
+ ReadConsistency.LINEARIZABLE_ALLOW_FOLLOWER, ReadConsistency.DEFAULT,
true);
+ }
+
+ @Test
+ void testReadOnCurrentNode() throws Exception {
+ submit(newRequest(Type.ListVolume));
+
+ assertEquals(1, nodeRequests.get(nodeIds.get(0)).size());
+ assertEquals(ReadConsistency.LINEARIZABLE_ALLOW_FOLLOWER.getHint(),
+ nodeRequests.get(nodeIds.get(0)).get(0).getReadConsistencyHint());
+ assertEquals(0, leaderRequests.size());
+ }
+
+ @Test
+ void testWriteOnLeader() throws Exception {
+ submit(newRequest(Type.CreateVolume));
+
+ assertEquals(0, countNodeRequests());
+ assertEquals(1, leaderRequests.size());
+ assertEquals(ReadConsistency.DEFAULT.getHint(),
leaderRequests.get(0).getReadConsistencyHint());
+ }
+
+ @ParameterizedTest
+ @MethodSource("failuresToTryNextNode")
+ void testFailureTriesNextNode(StatusRuntimeException failure) throws
Exception {
+ failures.put(nodeIds.get(0), failure);
+
+ submit(newRequest(Type.ListVolume));
+
+ assertEquals(1, nodeRequests.get(nodeIds.get(0)).size());
+ assertEquals(1, nodeRequests.get(nodeIds.get(1)).size());
+ assertEquals(0, leaderRequests.size());
+ assertEquals(nodeIds.get(1), provider.getCurrentFollowerReadNodeId());
+ }
+
+ static Stream<StatusRuntimeException> failuresToTryNextNode() {
+ return Stream.of(
+ Status.UNAVAILABLE.asRuntimeException(),
+ toServerError(new ReadIndexException("read index failed")),
+ toServerError(new ReadException("read failed")));
+ }
+
+ @Test
+ void testFallBackToLeaderWhenAllNodesFail() throws Exception {
+ for (String nodeId : nodeIds) {
+ failures.put(nodeId, Status.UNAVAILABLE.asRuntimeException());
+ }
+
+ submit(newRequest(Type.ListVolume));
+
+ for (String nodeId : nodeIds) {
+ assertEquals(1, nodeRequests.get(nodeId).size());
+ }
+ assertEquals(1, leaderRequests.size());
+ // The leader gets the leader read consistency, not the follower read
consistency.
+ assertEquals(ReadConsistency.DEFAULT.getHint(),
leaderRequests.get(0).getReadConsistencyHint());
+ assertTrue(provider.isOmServiceSupportsFollowerRead());
+ }
+
+ @Test
+ void testNotLeaderExceptionDisablesFollowerRead() throws Exception {
+ failures.put(nodeIds.get(0), toServerError(new
OMNotLeaderException(RaftPeerId.valueOf(nodeIds.get(0)))));
+
+ submit(newRequest(Type.ListVolume));
+
+ assertFalse(provider.isOmServiceSupportsFollowerRead());
+ assertEquals(1, countNodeRequests());
+ assertEquals(1, leaderRequests.size());
+
+ // The next read goes to the leader directly.
+ submit(newRequest(Type.ListVolume));
+ assertEquals(1, countNodeRequests());
+ assertEquals(2, leaderRequests.size());
+ }
+
+ @Test
+ void testLeaderNotReadyExceptionFallsBackToLeader() throws Exception {
+ failures.put(nodeIds.get(0), toServerError(new
OMLeaderNotReadyException("leader is not ready")));
+
+ submit(newRequest(Type.ListVolume));
+
+ assertEquals(1, countNodeRequests());
+ assertEquals(1, leaderRequests.size());
+ assertEquals(nodeIds.get(0), provider.getCurrentFollowerReadNodeId());
+ assertTrue(provider.isOmServiceSupportsFollowerRead());
+ }
+
+ @Test
+ void testFailureWithoutFailoverIsThrown() {
+ final StatusRuntimeException failure =
Status.RESOURCE_EXHAUSTED.asRuntimeException();
+ failures.put(nodeIds.get(0), failure);
+
+ assertSame(failure, assertThrows(StatusRuntimeException.class, () ->
submit(newRequest(Type.ListVolume))));
+ assertEquals(1, countNodeRequests());
+ assertEquals(0, leaderRequests.size());
+ assertEquals(nodeIds.get(0), provider.getCurrentFollowerReadNodeId());
+ }
+
+ private void submit(OMRequest request) throws IOException {
+ provider.submitRequest(request, this::submitToHost, this::submitToLeader);
+ }
+
+ private OMResponse submitToHost(OMRequest request, String host) {
+ final String nodeId = hostToNodeId.get(host);
+ nodeRequests.get(nodeId).add(request);
+ final StatusRuntimeException failure = failures.get(nodeId);
+ if (failure != null) {
+ throw failure;
+ }
+ return newResponse(request);
+ }
+
+ private OMResponse submitToLeader(OMRequest request) {
+ leaderRequests.add(request);
+ return newResponse(request);
+ }
+
+ private int countNodeRequests() {
+ return nodeRequests.values().stream().mapToInt(List::size).sum();
+ }
+
+ /** The error that the OM gRPC server returns for an exception, see
OzoneManagerServiceGrpc. */
+ private static StatusRuntimeException toServerError(IOException e) {
+ return Status.INTERNAL.withDescription(e.toString()).asRuntimeException();
+ }
+
+ private static OMRequest newRequest(Type cmdType) {
+ return OMRequest.newBuilder()
+ .setCmdType(cmdType)
+ .setClientId("test")
+ .build();
+ }
+
+ private static OMResponse newResponse(OMRequest request) {
+ return OMResponse.newBuilder()
+ .setCmdType(request.getCmdType())
+
.setStatus(org.apache.hadoop.ozone.protocol.proto.OzoneManagerProtocolProtos.Status.OK)
+ .build();
+ }
+}
---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]