This is an automated email from the ASF dual-hosted git repository.

adoroszlai 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 f9707d898ec HDDS-17462. Send structured errors from OM gRPC server 
instead of exception class names (#11763)
f9707d898ec is described below

commit f9707d898ec9115f199d3ad39ede602fca4d3bb0
Author: Peter Lee <[email protected]>
AuthorDate: Sun Nov 8 00:01:30 2026 +0800

    HDDS-17462. Send structured errors from OM gRPC server instead of exception 
class names (#11763)
---
 hadoop-ozone/common/pom.xml                        |  10 ++
 .../ozone/om/exceptions/OMNotLeaderException.java  |   6 +-
 .../ozone/om/ha/OMFailoverProxyProviderBase.java   |  61 +++----
 .../org/apache/hadoop/ozone/om/ha/OMProxyInfo.java |   8 -
 .../ozone/om/protocolPB/GrpcOmTransport.java       |  39 ++---
 .../ozone/om/protocolPB/grpc/OMGrpcError.java      | 188 +++++++++++++++++++++
 ...estGrpcOMFollowerReadFailoverProxyProvider.java |   3 +-
 .../ozone/om/ha/TestOMFailoverProxyProvider.java   |  56 ++++++
 .../TestGrpcOmTransportConcurrentFailover.java     |  11 +-
 .../ozone/om/protocolPB/TestS3GrpcOmTransport.java |  53 +++---
 .../ozone/om/protocolPB/grpc/TestOMGrpcError.java  | 118 +++++++++++++
 .../src/main/proto/OmClientProtocol.proto          |  27 +++
 .../hadoop/ozone/om/OzoneManagerServiceGrpc.java   |  11 +-
 .../ozone/om/TestGrpcOzoneManagerServer.java       |  28 +++
 14 files changed, 513 insertions(+), 106 deletions(-)

diff --git a/hadoop-ozone/common/pom.xml b/hadoop-ozone/common/pom.xml
index 1e7235bb174..e807f6645e0 100644
--- a/hadoop-ozone/common/pom.xml
+++ b/hadoop-ozone/common/pom.xml
@@ -65,6 +65,16 @@
       <groupId>io.grpc</groupId>
       <artifactId>grpc-netty</artifactId>
     </dependency>
+    <dependency>
+      <groupId>io.grpc</groupId>
+      <artifactId>grpc-protobuf</artifactId>
+      <exclusions>
+        <exclusion>
+          <groupId>com.google.code.findbugs</groupId>
+          <artifactId>jsr305</artifactId>
+        </exclusion>
+      </exclusions>
+    </dependency>
     <dependency>
       <groupId>io.netty</groupId>
       <artifactId>netty-handler</artifactId>
diff --git 
a/hadoop-ozone/common/src/main/java/org/apache/hadoop/ozone/om/exceptions/OMNotLeaderException.java
 
b/hadoop-ozone/common/src/main/java/org/apache/hadoop/ozone/om/exceptions/OMNotLeaderException.java
index bd7caf0071d..1ff62b7f4ea 100644
--- 
a/hadoop-ozone/common/src/main/java/org/apache/hadoop/ozone/om/exceptions/OMNotLeaderException.java
+++ 
b/hadoop-ozone/common/src/main/java/org/apache/hadoop/ozone/om/exceptions/OMNotLeaderException.java
@@ -52,8 +52,12 @@ public OMNotLeaderException(RaftPeerId currentPeerId,
   }
 
   public OMNotLeaderException(String msg) {
+    this(msg, null);
+  }
+
+  public OMNotLeaderException(String msg, String suggestedLeaderNodeId) {
     super(msg);
-    this.leaderPeerId = null;
+    this.leaderPeerId = suggestedLeaderNodeId;
     this.leaderAddress = null;
   }
 
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 52e662702ec..e23a4d33653 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
@@ -202,12 +202,20 @@ public RetryPolicy getRetryPolicy(int maxFailovers) {
     // Client will attempt up to maxFailovers number of failovers between
     // available OMs before throwing exception.
     RetryPolicy retryPolicy = new RetryPolicy() {
+      // Stores the failed OMs per request, to debounce repeatedly failed 
OM-suggested leaders.
+      private final ThreadLocal<Set<String>> failedOMs = 
ThreadLocal.withInitial(HashSet::new);
+
       @Override
       public RetryAction shouldRetry(Exception exception, int retries,
           int failovers, boolean isIdempotentOrAtMostOnce)
           throws Exception {
 
         String omNodeId = getCurrentProxyOMNodeId();
+        final Set<String> failedOMsOfRequest = failedOMs.get();
+        if (failovers == 0) {
+          failedOMsOfRequest.clear();
+        }
+        failedOMsOfRequest.add(omNodeId);
 
         if (LOG.isDebugEnabled()) {
           if (exception.getCause() != null) {
@@ -226,13 +234,10 @@ public RetryAction shouldRetry(Exception exception, int 
retries,
           if (notLeaderException != null) {
             // Prepare the next OM to be tried. This will help with calculation
             // of the wait times needed get creating the retryAction.
-            String suggestedLeaderAddress =
-                notLeaderException.getSuggestedLeaderAddress();
             String suggestedNodeId =
                 notLeaderException.getSuggestedLeaderNodeId();
-            if (suggestedLeaderAddress != null &&
-                suggestedNodeId != null &&
-                omProxies.contains(suggestedNodeId, suggestedLeaderAddress)) {
+            if (suggestedNodeId != null && omProxies.get(suggestedNodeId) != 
null
+                && !failedOMsOfRequest.contains(suggestedNodeId)) {
               setNextOmProxy(suggestedNodeId);
               return getRetryAction(RetryDecision.FAILOVER_AND_RETRY,
                   failovers);
@@ -438,15 +443,7 @@ public OMProxyInfo.OrderedMap<T> getOMProxyMap() {
    */
   public static OMLeaderNotReadyException getLeaderNotReadyException(
       Exception exception) {
-    Throwable cause = exception.getCause();
-    if (cause instanceof RemoteException) {
-      IOException ioException =
-          ((RemoteException) cause).unwrapRemoteException();
-      if (ioException instanceof OMLeaderNotReadyException) {
-        return (OMLeaderNotReadyException) ioException;
-      }
-    }
-    return null;
+    return getCause(exception, OMLeaderNotReadyException.class);
   }
 
   /**
@@ -458,15 +455,7 @@ public static OMLeaderNotReadyException 
getLeaderNotReadyException(
    */
   public static OMNotLeaderException getNotLeaderException(
       Exception exception) {
-    Throwable cause = exception.getCause();
-    if (cause instanceof RemoteException) {
-      IOException ioException =
-          ((RemoteException) cause).unwrapRemoteException();
-      if (ioException instanceof OMNotLeaderException) {
-        return (OMNotLeaderException) ioException;
-      }
-    }
-    return null;
+    return getCause(exception, OMNotLeaderException.class);
   }
 
   /**
@@ -477,15 +466,7 @@ public static OMNotLeaderException getNotLeaderException(
    *         exception is not ReadIndexException.
    */
   public static ReadIndexException getReadIndexException(Exception exception) {
-    Throwable cause = exception.getCause();
-    if (cause instanceof RemoteException) {
-      IOException ioException =
-          ((RemoteException) cause).unwrapRemoteException();
-      if (ioException instanceof ReadIndexException) {
-        return (ReadIndexException) ioException;
-      }
-    }
-    return null;
+    return getCause(exception, ReadIndexException.class);
   }
 
   /**
@@ -496,15 +477,19 @@ public static ReadIndexException 
getReadIndexException(Exception exception) {
    *         exception is not ReadException.
    */
   public static ReadException getReadException(Exception exception) {
+    return getCause(exception, ReadException.class);
+  }
+
+  /**
+   * @return the cause of the given exception if it has the given type, 
otherwise null.
+   *         A cause in a {@link RemoteException} is unwrapped first.
+   */
+  private static <T extends IOException> T getCause(Exception exception, 
Class<T> type) {
     Throwable cause = exception.getCause();
     if (cause instanceof RemoteException) {
-      IOException ioException =
-          ((RemoteException) cause).unwrapRemoteException();
-      if (ioException instanceof ReadException) {
-        return (ReadException) ioException;
-      }
+      cause = ((RemoteException) cause).unwrapRemoteException();
     }
-    return null;
+    return type.isInstance(cause) ? type.cast(cause) : null;
   }
 
   protected ConfigurationSource getConf() {
diff --git 
a/hadoop-ozone/common/src/main/java/org/apache/hadoop/ozone/om/ha/OMProxyInfo.java
 
b/hadoop-ozone/common/src/main/java/org/apache/hadoop/ozone/om/ha/OMProxyInfo.java
index 8f9b89e9149..285b79de92b 100644
--- 
a/hadoop-ozone/common/src/main/java/org/apache/hadoop/ozone/om/ha/OMProxyInfo.java
+++ 
b/hadoop-ozone/common/src/main/java/org/apache/hadoop/ozone/om/ha/OMProxyInfo.java
@@ -344,14 +344,6 @@ Integer indexOf(String nodeID) {
       return ordering.get(nodeID);
     }
 
-    boolean contains(String nodeId, String address) {
-      if (nodeId == null || address == null) {
-        return false;
-      }
-      final OMProxyInfo<P> p = get(nodeId);
-      return p != null && address.equals(p.getAddressString());
-    }
-
     @Override
     public String toString() {
       return proxies.toString();
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 4ff4c451d8d..ae453b08f0c 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
@@ -50,7 +50,6 @@
 import org.apache.hadoop.hdds.security.SecurityConfig;
 import org.apache.hadoop.io.Text;
 import org.apache.hadoop.io.retry.RetryPolicy;
-import org.apache.hadoop.ipc_.RemoteException;
 import org.apache.hadoop.ozone.OzoneConfigKeys;
 import org.apache.hadoop.ozone.om.exceptions.OMException;
 import org.apache.hadoop.ozone.om.exceptions.OMException.ResultCodes;
@@ -59,6 +58,7 @@
 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.om.protocolPB.grpc.OMGrpcError;
 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.OzoneManagerServiceGrpc;
@@ -215,7 +215,7 @@ public OMResponse submitRequest(OMRequest payload) throws 
IOException {
         }
         Exception exp = new Exception(e);
         tryOtherHost = shouldRetry(unwrapException(exp),
-            expectedFailoverCount, ++requestFailoverCount);
+            expectedFailoverCount, requestFailoverCount++);
         if (!tryOtherHost) {
           throw new OMException(resultCode);
         }
@@ -243,30 +243,21 @@ private OMResponse submitRequestToHost(OMRequest payload, 
String targetHost)
   }
 
   public static Exception unwrapException(Exception ex) {
-    Exception grpcException = null;
-    try {
-      StatusRuntimeException srexp =
-          (StatusRuntimeException)ex.getCause();
-      Status status = srexp.getStatus();
-      LOG.debug("GRPC exception wrapped: {}", status.getDescription());
-      if (status.getCode() == Status.Code.INTERNAL) {
-        // exception potentially generated by OzoneManagerServiceGrpc
-        String description = status.getDescription();
-        int colonIndex = description.indexOf(':');
-        grpcException = new ServiceException(new 
RemoteException(description.substring(0, colonIndex),
-            description.substring(colonIndex + 2)));
-      } else if ((status.getCode() == Status.Code.RESOURCE_EXHAUSTED) ||
-              (status.getCode() == Status.Code.DATA_LOSS)) {
-        grpcException = srexp;
-      } else {
-        // exception generated by connection failure, gRPC
-        grpcException = ex;
+    StatusRuntimeException srexp = (StatusRuntimeException) ex.getCause();
+    Status status = srexp.getStatus();
+    LOG.debug("GRPC exception wrapped: {}", status.getDescription());
+    if (status.getCode() == Status.Code.INTERNAL) {
+      OMGrpcError omError = OMGrpcError.fromStatusRuntimeException(srexp);
+      if (omError != null) {
+        // exception generated by OzoneManagerServiceGrpc
+        return new ServiceException(omError.toException());
       }
-    } catch (Exception e) {
-      grpcException = new IOException(e);
-      LOG.error("error unwrapping exception from OMResponse {}");
+    } else if ((status.getCode() == Status.Code.RESOURCE_EXHAUSTED) ||
+            (status.getCode() == Status.Code.DATA_LOSS)) {
+      return srexp;
     }
-    return grpcException;
+    // exception generated by gRPC, e.g. a connection failure
+    return ex;
   }
 
   private boolean shouldRetry(Exception ex, int expectedFailoverCount, int 
requestFailoverCount) {
diff --git 
a/hadoop-ozone/common/src/main/java/org/apache/hadoop/ozone/om/protocolPB/grpc/OMGrpcError.java
 
b/hadoop-ozone/common/src/main/java/org/apache/hadoop/ozone/om/protocolPB/grpc/OMGrpcError.java
new file mode 100644
index 00000000000..9358d2ad67a
--- /dev/null
+++ 
b/hadoop-ozone/common/src/main/java/org/apache/hadoop/ozone/om/protocolPB/grpc/OMGrpcError.java
@@ -0,0 +1,188 @@
+/*
+ * 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.protocolPB.grpc;
+
+import io.grpc.Metadata;
+import io.grpc.Status;
+import io.grpc.StatusRuntimeException;
+import io.grpc.protobuf.ProtoUtils;
+import java.io.IOException;
+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.protocol.proto.OzoneManagerProtocolProtos.OMGrpcErrorProto;
+import org.apache.ratis.protocol.exceptions.ReadException;
+import org.apache.ratis.protocol.exceptions.ReadIndexException;
+
+/**
+ * The Java form of {@link OMGrpcErrorProto}, the error that the OM gRPC 
server sends in the gRPC trailers.
+ */
+public final class OMGrpcError {
+  private static final Metadata.Key<OMGrpcErrorProto> ERROR_KEY = 
Metadata.Key.of("om-grpc-error-bin",
+      ProtoUtils.metadataMarshaller(OMGrpcErrorProto.getDefaultInstance()));
+
+  private final Kind kind;
+  private final String message;
+  /** The OM node ID of the suggested leader, for {@link Kind#NOT_LEADER}. */
+  private final String suggestedLeaderNodeId;
+
+  /** A kind for each error in {@link OMGrpcErrorProto}, and {@link #INTERNAL} 
for any other error. */
+  public enum Kind {
+    NOT_LEADER,
+    LEADER_NOT_READY,
+    READ_INDEX_FAILED,
+    READ_FAILED,
+    INTERNAL
+  }
+
+  private OMGrpcError(Kind kind, String message, String suggestedLeaderNodeId) 
{
+    this.kind = kind;
+    this.message = message;
+    this.suggestedLeaderNodeId = suggestedLeaderNodeId;
+  }
+
+  /** @return the error for the given exception thrown by OM. */
+  public static OMGrpcError fromException(Throwable omException) {
+    if (omException instanceof OMNotLeaderException) {
+      return new OMGrpcError(Kind.NOT_LEADER, omException.getMessage(),
+          ((OMNotLeaderException) omException).getSuggestedLeaderNodeId());
+    } else if (omException instanceof OMLeaderNotReadyException) {
+      return new OMGrpcError(Kind.LEADER_NOT_READY, omException.getMessage(), 
null);
+    } else if (omException instanceof ReadIndexException) {
+      return new OMGrpcError(Kind.READ_INDEX_FAILED, omException.getMessage(), 
null);
+    } else if (omException instanceof ReadException) {
+      return new OMGrpcError(Kind.READ_FAILED, omException.getMessage(), null);
+    }
+    return new OMGrpcError(Kind.INTERNAL, omException.toString(), null);
+  }
+
+  public static OMGrpcError getFromProtobuf(OMGrpcErrorProto proto) {
+    switch (proto.getErrorCase()) {
+    case NOTLEADER:
+      final OMGrpcErrorProto.NotLeader notLeader = proto.getNotLeader();
+      return new OMGrpcError(Kind.NOT_LEADER, notLeader.hasMessage() ? 
notLeader.getMessage() : null,
+          notLeader.hasSuggestedLeaderNodeId() ? 
notLeader.getSuggestedLeaderNodeId() : null);
+    case LEADERNOTREADY:
+      final OMGrpcErrorProto.LeaderNotReady leaderNotReady = 
proto.getLeaderNotReady();
+      return new OMGrpcError(Kind.LEADER_NOT_READY,
+          leaderNotReady.hasMessage() ? leaderNotReady.getMessage() : null, 
null);
+    case READINDEXFAILED:
+      final OMGrpcErrorProto.ReadIndexFailed readIndexFailed = 
proto.getReadIndexFailed();
+      return new OMGrpcError(Kind.READ_INDEX_FAILED,
+          readIndexFailed.hasMessage() ? readIndexFailed.getMessage() : null, 
null);
+    case READFAILED:
+      final OMGrpcErrorProto.ReadFailed readFailed = proto.getReadFailed();
+      return new OMGrpcError(Kind.READ_FAILED, readFailed.hasMessage() ? 
readFailed.getMessage() : null, null);
+    default:
+      return new OMGrpcError(Kind.INTERNAL, null, null);
+    }
+  }
+
+  /**
+   * @return the error that the gRPC error carries, or null if the gRPC error 
does not come from OM.
+   */
+  public static OMGrpcError fromStatusRuntimeException(StatusRuntimeException 
e) {
+    final Metadata trailers = e.getTrailers();
+    final OMGrpcErrorProto proto = trailers == null ? null : 
trailers.get(ERROR_KEY);
+    if (proto == null) {
+      return null;
+    }
+    final OMGrpcError error = getFromProtobuf(proto);
+    return error.kind == Kind.INTERNAL ? new OMGrpcError(Kind.INTERNAL, 
e.getStatus().getDescription(), null) : error;
+  }
+
+  /** @return the gRPC error for the given exception thrown by OM. */
+  public static StatusRuntimeException toStatusRuntimeException(Throwable 
omException) {
+    final Metadata trailers = new Metadata();
+    trailers.put(ERROR_KEY, fromException(omException).getProtobuf());
+    // NOTE: gRPC clients of old versions read the exception class and message 
from the description.
+    return 
Status.INTERNAL.withDescription(omException.toString()).asRuntimeException(trailers);
+  }
+
+  /**
+   * @return the protobuf of this error. An {@link Kind#INTERNAL} error is 
empty,
+   *         since the gRPC status description already has its message.
+   */
+  public OMGrpcErrorProto getProtobuf() {
+    final OMGrpcErrorProto.Builder proto = OMGrpcErrorProto.newBuilder();
+    switch (kind) {
+    case NOT_LEADER:
+      final OMGrpcErrorProto.NotLeader.Builder notLeader = 
OMGrpcErrorProto.NotLeader.newBuilder();
+      if (message != null) {
+        notLeader.setMessage(message);
+      }
+      if (suggestedLeaderNodeId != null) {
+        notLeader.setSuggestedLeaderNodeId(suggestedLeaderNodeId);
+      }
+      proto.setNotLeader(notLeader);
+      break;
+    case LEADER_NOT_READY:
+      final OMGrpcErrorProto.LeaderNotReady.Builder leaderNotReady = 
OMGrpcErrorProto.LeaderNotReady.newBuilder();
+      if (message != null) {
+        leaderNotReady.setMessage(message);
+      }
+      proto.setLeaderNotReady(leaderNotReady);
+      break;
+    case READ_INDEX_FAILED:
+      final OMGrpcErrorProto.ReadIndexFailed.Builder readIndexFailed = 
OMGrpcErrorProto.ReadIndexFailed.newBuilder();
+      if (message != null) {
+        readIndexFailed.setMessage(message);
+      }
+      proto.setReadIndexFailed(readIndexFailed);
+      break;
+    case READ_FAILED:
+      final OMGrpcErrorProto.ReadFailed.Builder readFailed = 
OMGrpcErrorProto.ReadFailed.newBuilder();
+      if (message != null) {
+        readFailed.setMessage(message);
+      }
+      proto.setReadFailed(readFailed);
+      break;
+    default:
+      break;
+    }
+    return proto.build();
+  }
+
+  /** @return the exception thrown by OM. */
+  public IOException toException() {
+    switch (kind) {
+    case NOT_LEADER:
+      return new OMNotLeaderException(message, suggestedLeaderNodeId);
+    case LEADER_NOT_READY:
+      return new OMLeaderNotReadyException(message);
+    case READ_INDEX_FAILED:
+      return new ReadIndexException(message);
+    case READ_FAILED:
+      return new ReadException(message);
+    default:
+      return new OMException(message, OMException.ResultCodes.INTERNAL_ERROR);
+    }
+  }
+
+  public Kind getKind() {
+    return kind;
+  }
+
+  public String getMessage() {
+    return message;
+  }
+
+  public String getSuggestedLeaderNodeId() {
+    return suggestedLeaderNodeId;
+  }
+}
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
index dacbb6a155a..390c348bfbf 100644
--- 
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
@@ -40,6 +40,7 @@
 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.om.protocolPB.grpc.OMGrpcError;
 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;
@@ -209,7 +210,7 @@ private int countNodeRequests() {
 
   /** 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();
+    return OMGrpcError.toStatusRuntimeException(e);
   }
 
   private static OMRequest newRequest(Type cmdType) {
diff --git 
a/hadoop-ozone/common/src/test/java/org/apache/hadoop/ozone/om/ha/TestOMFailoverProxyProvider.java
 
b/hadoop-ozone/common/src/test/java/org/apache/hadoop/ozone/om/ha/TestOMFailoverProxyProvider.java
index 6f74ab936cd..ff8d74977fd 100644
--- 
a/hadoop-ozone/common/src/test/java/org/apache/hadoop/ozone/om/ha/TestOMFailoverProxyProvider.java
+++ 
b/hadoop-ozone/common/src/test/java/org/apache/hadoop/ozone/om/ha/TestOMFailoverProxyProvider.java
@@ -27,17 +27,22 @@
 import static org.junit.jupiter.api.Assertions.assertNull;
 import static org.junit.jupiter.api.Assertions.assertTrue;
 
+import com.google.protobuf.ServiceException;
 import java.io.IOException;
 import java.util.ArrayList;
 import java.util.Arrays;
 import java.util.Collection;
 import java.util.Collections;
+import java.util.HashSet;
 import java.util.Iterator;
 import java.util.List;
+import java.util.Set;
 import java.util.StringJoiner;
 import org.apache.hadoop.hdds.conf.OzoneConfiguration;
 import org.apache.hadoop.io.Text;
+import org.apache.hadoop.io.retry.RetryPolicy;
 import org.apache.hadoop.ozone.ha.ConfUtils;
+import org.apache.hadoop.ozone.om.exceptions.OMNotLeaderException;
 import org.apache.hadoop.ozone.om.protocolPB.OzoneManagerProtocolPB;
 import org.apache.hadoop.security.UserGroupInformation;
 import org.junit.jupiter.api.BeforeEach;
@@ -129,6 +134,57 @@ public void testWaitTimeWithSuggestedNewNode() {
     assertEquals(0, provider.getWaitTime());
   }
 
+  @Test
+  public void testNotLeaderFailsOverToSuggestedLeader() throws Exception {
+    final List<String> nodeIds = new 
ArrayList<>(provider.getOMProxyMap().getNodeIds());
+    // Not the next node, which a failover without the suggested leader would 
try.
+    final String suggestedLeader = 
nodeIds.get((nodeIds.indexOf(provider.getCurrentProxyOMNodeId()) + 2) % 
numNodes);
+
+    final RetryPolicy.RetryAction action = 
provider.getRetryPolicy(10).shouldRetry(
+        new ServiceException(new OMNotLeaderException("not the leader", 
suggestedLeader)), 0, 0, true);
+
+    assertEquals(RetryPolicy.RetryAction.RetryDecision.FAILOVER_AND_RETRY, 
action.action);
+    assertEquals(suggestedLeader, provider.getNextProxyOMNodeId());
+  }
+
+  @Test
+  public void testDownSuggestedLeaderFallsBackToRoundRobin() throws Exception {
+    final List<String> nodeIds = new 
ArrayList<>(provider.getOMProxyMap().getNodeIds());
+    final String suggestedLeader = 
nodeIds.get((nodeIds.indexOf(provider.getCurrentProxyOMNodeId()) + 2) % 
numNodes);
+    final RetryPolicy retryPolicy = provider.getRetryPolicy(10);
+
+    final Set<String> triedNodes = new HashSet<>();
+    long waitTime = 0;
+    for (int failovers = 0; failovers < 2 * numNodes && waitTime == 0; 
failovers++) {
+      final String nodeId = provider.getCurrentProxyOMNodeId();
+      triedNodes.add(nodeId);
+      final Exception failure = nodeId.equals(suggestedLeader)
+          ? new IOException("connection refused")
+          : new ServiceException(new OMNotLeaderException("not the leader", 
suggestedLeader));
+      waitTime = retryPolicy.shouldRetry(failure, 0, failovers, 
true).delayMillis;
+      provider.performFailover(null);
+    }
+
+    assertEquals(numNodes, triedNodes.size());
+    assertEquals(waitBetweenRetries, waitTime);
+  }
+
+  @Test
+  public void testSuggestedLeaderIsTriedEvenIfAnEarlierRequestFailedOnIt() 
throws Exception {
+    final RetryPolicy retryPolicy = provider.getRetryPolicy(10);
+    final String newLeader = provider.getCurrentProxyOMNodeId();
+
+    // An earlier request fails on the OM while it is down, and then succeeds 
on the next OM.
+    retryPolicy.shouldRetry(new IOException("connection refused"), 0, 0, true);
+    provider.performFailover(null);
+
+    final RetryPolicy.RetryAction action = retryPolicy.shouldRetry(
+        new ServiceException(new OMNotLeaderException("not the leader", 
newLeader)), 0, 0, true);
+
+    assertEquals(0, action.delayMillis);
+    assertEquals(newLeader, provider.getNextProxyOMNodeId());
+  }
+
   /**
    * Tests waitTime reset after same node failover.
    */
diff --git 
a/hadoop-ozone/common/src/test/java/org/apache/hadoop/ozone/om/protocolPB/TestGrpcOmTransportConcurrentFailover.java
 
b/hadoop-ozone/common/src/test/java/org/apache/hadoop/ozone/om/protocolPB/TestGrpcOmTransportConcurrentFailover.java
index c8890eaa49c..ca0ec669a13 100644
--- 
a/hadoop-ozone/common/src/test/java/org/apache/hadoop/ozone/om/protocolPB/TestGrpcOmTransportConcurrentFailover.java
+++ 
b/hadoop-ozone/common/src/test/java/org/apache/hadoop/ozone/om/protocolPB/TestGrpcOmTransportConcurrentFailover.java
@@ -28,8 +28,6 @@
 
 import io.grpc.Server;
 import io.grpc.ServerBuilder;
-import io.grpc.Status;
-import io.grpc.StatusRuntimeException;
 import io.grpc.stub.StreamObserver;
 import java.io.IOException;
 import java.util.HashMap;
@@ -45,6 +43,8 @@
 import org.apache.hadoop.hdds.conf.OzoneConfiguration;
 import org.apache.hadoop.ozone.OzoneConfigKeys;
 import org.apache.hadoop.ozone.ha.ConfUtils;
+import org.apache.hadoop.ozone.om.exceptions.OMNotLeaderException;
+import org.apache.hadoop.ozone.om.protocolPB.grpc.OMGrpcError;
 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;
@@ -246,11 +246,8 @@ public void submitRequest(OMRequest request, 
StreamObserver<OMResponse> response
 
                 if (!isLeader.get()) {
                   failureCount.incrementAndGet();
-                  String errorMsg = 
"org.apache.hadoop.ozone.om.exceptions.OMNotLeaderException: " +
-                      "OM:" + nodeId + " is not the leader. Suggested leader: 
om2";
-
-                  responseObserver.onError(new StatusRuntimeException(
-                      Status.INTERNAL.withDescription(errorMsg)));
+                  
responseObserver.onError(OMGrpcError.toStatusRuntimeException(
+                      new OMNotLeaderException("OM:" + nodeId + " is not the 
leader. Suggested leader: om2")));
                 } else {
                   successCount.incrementAndGet();
                   OMResponse response = OMResponse.newBuilder()
diff --git 
a/hadoop-ozone/common/src/test/java/org/apache/hadoop/ozone/om/protocolPB/TestS3GrpcOmTransport.java
 
b/hadoop-ozone/common/src/test/java/org/apache/hadoop/ozone/om/protocolPB/TestS3GrpcOmTransport.java
index ef78ebacfa7..fda263e1057 100644
--- 
a/hadoop-ozone/common/src/test/java/org/apache/hadoop/ozone/om/protocolPB/TestS3GrpcOmTransport.java
+++ 
b/hadoop-ozone/common/src/test/java/org/apache/hadoop/ozone/om/protocolPB/TestS3GrpcOmTransport.java
@@ -45,6 +45,7 @@
 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.protocolPB.grpc.OMGrpcError;
 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;
@@ -117,11 +118,7 @@ public void 
submitRequest(org.apache.hadoop.ozone.protocol.proto
                       responseObserver.onCompleted();
                     }
                   } catch (Throwable e) {
-                    IOException ex = new IOException(e.getCause());
-                    responseObserver.onError(io.grpc.Status
-                        .INTERNAL
-                        .withDescription(ex.getMessage())
-                        .asRuntimeException());
+                    
responseObserver.onError(OMGrpcError.toStatusRuntimeException(e.getCause()));
                   }
                 }
               }));
@@ -131,8 +128,6 @@ public void 
submitRequest(org.apache.hadoop.ozone.protocol.proto
   private ServiceException createNotLeaderException() {
     RaftPeerId raftPeerId = RaftPeerId.getRaftPeerId("testNodeId");
 
-    // TODO: Set suggest leaderID. Right now, client is not using suggest
-    // leaderID. Need to fix this.
     OMNotLeaderException notLeaderException =
         new OMNotLeaderException(raftPeerId);
     LOG.debug(notLeaderException.getMessage());
@@ -246,7 +241,7 @@ public void 
testGrpcFailoverProxyCalculatesFailoverCountPerRequest() throws Exce
     client.startClient(channel);
 
     assertThrows(Exception.class, () -> 
client.submitRequest(arbitraryOmRequest()));
-    assertEquals(maxFailoverAttempts, failoverCount);
+    assertEquals(maxFailoverAttempts + 1, failoverCount);
 
     failoverCount = 0;
     completeFailover = true;
@@ -286,6 +281,27 @@ public void testGrpcFailoverExceedMaxMesgLen() throws 
Exception {
     assertThrows(Exception.class, () -> client.submitRequest(omRequest));
   }
 
+  @Test
+  public void testNotLeaderExceptionGoesToSuggestedLeader() throws Exception {
+    configureHaOmService("om0", "om1", "om2");
+
+    AtomicInteger notLeaderCount = new AtomicInteger();
+    AtomicInteger leaderRequestCount = new AtomicInteger();
+    OMNotLeaderException notLeaderException =
+        new OMNotLeaderException(RaftPeerId.valueOf("om0"), 
RaftPeerId.valueOf("om2"), null);
+
+    client = new GrpcOmTransport(conf, ugi, omServiceId);
+    client.startClient("om0", createNotLeaderNodeChannel(notLeaderCount, 
notLeaderException));
+    client.startClient("om1", createNotLeaderNodeChannel(notLeaderCount, 
notLeaderException));
+    client.startClient("om2", createNodeChannel("om2", leaderRequestCount, new 
AtomicReference<>()));
+    client.changeLeaderProxyForTest("om0");
+
+    client.submitRequest(arbitraryOmRequest());
+
+    assertEquals(1, notLeaderCount.get());
+    assertEquals(1, leaderRequestCount.get());
+  }
+
   @Test
   public void testFollowerReadDoesNotFailoverFromKnownLeader() throws 
Exception {
     conf.setBoolean(OzoneConfigKeys.OZONE_CLIENT_FOLLOWER_READ_ENABLED_KEY, 
true);
@@ -506,7 +522,8 @@ public void 
testFollowerReadFallsBackToLeaderOnNotLeaderException() throws Excep
     client = new GrpcOmTransport(conf, ugi, omServiceId);
     client.startClient("om0", createNodeChannel("om0",
         leaderRequestCount, leaderRequest));
-    client.startClient("om1", 
createNotLeaderNodeChannel(followerRequestCount));
+    client.startClient("om1", createNotLeaderNodeChannel(followerRequestCount,
+        new OMNotLeaderException(RaftPeerId.valueOf("om1"))));
     client.changeLeaderProxyForTest("om0");
     client.changeFollowerReadInitialProxy("om1");
 
@@ -640,8 +657,8 @@ private ManagedChannel 
createNotReadyLeaderNodeChannel(String nodeId, int notRea
           public void submitRequest(OMRequest request, 
StreamObserver<OMResponse> responseObserver) {
             requests.add(request);
             if (requests.size() <= notReadyCount) {
-              IOException ex = new IOException(new 
OMLeaderNotReadyException(nodeId + " is not ready"));
-              
responseObserver.onError(io.grpc.Status.INTERNAL.withDescription(ex.getMessage()).asRuntimeException());
+              responseObserver.onError(OMGrpcError.toStatusRuntimeException(
+                  new OMLeaderNotReadyException(nodeId + " is not ready")));
               return;
             }
             responseObserver.onNext(newSuccessResponse(nodeId, request));
@@ -663,8 +680,8 @@ private static OMResponse newSuccessResponse(String nodeId, 
OMRequest request) {
         .build();
   }
 
-  private ManagedChannel createNotLeaderNodeChannel(AtomicInteger requestCount)
-      throws IOException {
+  private ManagedChannel createNotLeaderNodeChannel(AtomicInteger requestCount,
+      OMNotLeaderException notLeaderException) throws IOException {
     String nodeServerName = InProcessServerBuilder.generateName();
     grpcCleanup.register(InProcessServerBuilder
         .forName(nodeServerName)
@@ -674,15 +691,7 @@ private ManagedChannel 
createNotLeaderNodeChannel(AtomicInteger requestCount)
           public void submitRequest(OMRequest request,
               StreamObserver<OMResponse> responseObserver) {
             requestCount.incrementAndGet();
-            try {
-              throw createNotLeaderException();
-            } catch (Throwable e) {
-              IOException ex = new IOException(e.getCause());
-              responseObserver.onError(io.grpc.Status
-                  .INTERNAL
-                  .withDescription(ex.getMessage())
-                  .asRuntimeException());
-            }
+            
responseObserver.onError(OMGrpcError.toStatusRuntimeException(notLeaderException));
           }
         })
         .build()
diff --git 
a/hadoop-ozone/common/src/test/java/org/apache/hadoop/ozone/om/protocolPB/grpc/TestOMGrpcError.java
 
b/hadoop-ozone/common/src/test/java/org/apache/hadoop/ozone/om/protocolPB/grpc/TestOMGrpcError.java
new file mode 100644
index 00000000000..b2f1481f920
--- /dev/null
+++ 
b/hadoop-ozone/common/src/test/java/org/apache/hadoop/ozone/om/protocolPB/grpc/TestOMGrpcError.java
@@ -0,0 +1,118 @@
+/*
+ * 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.protocolPB.grpc;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNull;
+
+import io.grpc.Status;
+import io.grpc.StatusRuntimeException;
+import java.io.IOException;
+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.protocolPB.grpc.OMGrpcError.Kind;
+import 
org.apache.hadoop.ozone.protocol.proto.OzoneManagerProtocolProtos.OMGrpcErrorProto;
+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.Test;
+
+/**
+ * Tests for {@link OMGrpcError}.
+ */
+public class TestOMGrpcError {
+  private static final OMNotLeaderException NOT_LEADER =
+      new OMNotLeaderException(RaftPeerId.valueOf("om1"), 
RaftPeerId.valueOf("om2"), "host2/10.0.0.2");
+
+  @Test
+  void testFromException() {
+    assertError(OMGrpcError.fromException(NOT_LEADER), Kind.NOT_LEADER, 
NOT_LEADER.getMessage(), "om2");
+    assertError(OMGrpcError.fromException(new OMLeaderNotReadyException("om1 
is not ready")),
+        Kind.LEADER_NOT_READY, "om1 is not ready", null);
+    assertError(OMGrpcError.fromException(new ReadIndexException("read index 
failed")),
+        Kind.READ_INDEX_FAILED, "read index failed", null);
+    assertError(OMGrpcError.fromException(new ReadException("read failed")), 
Kind.READ_FAILED, "read failed", null);
+
+    final IllegalStateException other = new 
IllegalStateException("unexpected");
+    assertError(OMGrpcError.fromException(other), Kind.INTERNAL, 
other.toString(), null);
+  }
+
+  @Test
+  void testProtobuf() {
+    final OMGrpcError notLeader = OMGrpcError.fromException(NOT_LEADER);
+    assertError(OMGrpcError.getFromProtobuf(notLeader.getProtobuf()), 
Kind.NOT_LEADER, NOT_LEADER.getMessage(), "om2");
+
+    for (IOException omException : new IOException[] {new 
OMLeaderNotReadyException("om1 is not ready"),
+        new ReadIndexException("read index failed"), new ReadException("read 
failed")}) {
+      final OMGrpcError error = OMGrpcError.fromException(omException);
+      assertError(OMGrpcError.getFromProtobuf(error.getProtobuf()), 
error.getKind(), omException.getMessage(), null);
+    }
+
+    // The message of any other error is only in the gRPC status description.
+    assertEquals(OMGrpcErrorProto.getDefaultInstance(),
+        OMGrpcError.fromException(new 
IllegalStateException("unexpected")).getProtobuf());
+  }
+
+  @Test
+  void testStatusRuntimeException() {
+    final StatusRuntimeException notLeader = 
OMGrpcError.toStatusRuntimeException(NOT_LEADER);
+    assertEquals(Status.Code.INTERNAL, notLeader.getStatus().getCode());
+    assertEquals(NOT_LEADER.toString(), 
notLeader.getStatus().getDescription());
+    assertError(OMGrpcError.fromStatusRuntimeException(notLeader), 
Kind.NOT_LEADER, NOT_LEADER.getMessage(), "om2");
+
+    final IllegalStateException other = new 
IllegalStateException("unexpected");
+    
assertError(OMGrpcError.fromStatusRuntimeException(OMGrpcError.toStatusRuntimeException(other)),
+        Kind.INTERNAL, other.toString(), null);
+  }
+
+  @Test
+  void testErrorWithoutOmError() {
+    
assertNull(OMGrpcError.fromStatusRuntimeException(Status.INTERNAL.withDescription("a:
 b").asRuntimeException()));
+    
assertNull(OMGrpcError.fromStatusRuntimeException(Status.UNAVAILABLE.asRuntimeException()));
+  }
+
+  @Test
+  void testToException() {
+    final IOException notLeader = 
OMGrpcError.fromException(NOT_LEADER).toException();
+    
assertThat(notLeader).isInstanceOf(OMNotLeaderException.class).hasMessage(NOT_LEADER.getMessage());
+    assertEquals("om2", ((OMNotLeaderException) 
notLeader).getSuggestedLeaderNodeId());
+
+    assertToException(new OMLeaderNotReadyException("om1 is not ready"));
+    assertToException(new ReadIndexException("read index failed"));
+    assertToException(new ReadException("read failed"));
+
+    final IllegalStateException other = new 
IllegalStateException("unexpected");
+    final IOException internal = 
OMGrpcError.fromException(other).toException();
+    
assertThat(internal).isInstanceOf(OMException.class).hasMessage(other.toString());
+    assertEquals(OMException.ResultCodes.INTERNAL_ERROR, ((OMException) 
internal).getResult());
+  }
+
+  private static void assertError(OMGrpcError error, Kind kind, String 
message, String suggestedLeaderNodeId) {
+    assertEquals(kind, error.getKind());
+    assertEquals(message, error.getMessage());
+    assertEquals(suggestedLeaderNodeId, error.getSuggestedLeaderNodeId());
+  }
+
+  private static void assertToException(IOException omException) {
+    final IOException e = OMGrpcError.fromException(omException).toException();
+    assertEquals(omException.getClass(), e.getClass());
+    assertEquals(omException.getMessage(), e.getMessage());
+  }
+}
diff --git 
a/hadoop-ozone/interface-client/src/main/proto/OmClientProtocol.proto 
b/hadoop-ozone/interface-client/src/main/proto/OmClientProtocol.proto
index 126b9282f2d..3ad67ac68c5 100644
--- a/hadoop-ozone/interface-client/src/main/proto/OmClientProtocol.proto
+++ b/hadoop-ozone/interface-client/src/main/proto/OmClientProtocol.proto
@@ -2879,6 +2879,33 @@ service OzoneManagerService {
           returns(OMResponse);
 }
 
+/**
+ The error that OzoneManagerService sends in the gRPC trailers when 
submitRequest fails.
+*/
+message OMGrpcErrorProto {
+  message NotLeader {
+    optional string message = 1;
+    optional string suggestedLeaderNodeId = 2;
+  }
+  message LeaderNotReady {
+    optional string message = 1;
+  }
+  message ReadIndexFailed {
+    optional string message = 1;
+  }
+  message ReadFailed {
+    optional string message = 1;
+  }
+
+  // Not set for any other error.
+  oneof error {
+    NotLeader notLeader = 1;
+    LeaderNotReady leaderNotReady = 2;
+    ReadIndexFailed readIndexFailed = 3;
+    ReadFailed readFailed = 4;
+  }
+}
+
 message GetLifecycleServiceStatusRequest {
 }
 
diff --git 
a/hadoop-ozone/ozone-manager/src/main/java/org/apache/hadoop/ozone/om/OzoneManagerServiceGrpc.java
 
b/hadoop-ozone/ozone-manager/src/main/java/org/apache/hadoop/ozone/om/OzoneManagerServiceGrpc.java
index 99d376e7549..dd0c0604eff 100644
--- 
a/hadoop-ozone/ozone-manager/src/main/java/org/apache/hadoop/ozone/om/OzoneManagerServiceGrpc.java
+++ 
b/hadoop-ozone/ozone-manager/src/main/java/org/apache/hadoop/ozone/om/OzoneManagerServiceGrpc.java
@@ -18,13 +18,15 @@
 package org.apache.hadoop.ozone.om;
 
 import com.google.protobuf.RpcController;
+import com.google.protobuf.ServiceException;
 import io.grpc.Status;
-import java.io.IOException;
 import java.util.EnumSet;
 import java.util.Set;
 import java.util.concurrent.atomic.AtomicInteger;
+import org.apache.hadoop.ipc_.ProtobufHelper;
 import org.apache.hadoop.ipc_.RPC;
 import org.apache.hadoop.ipc_.Server;
+import org.apache.hadoop.ozone.om.protocolPB.grpc.OMGrpcError;
 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;
@@ -108,10 +110,9 @@ public void submitRequest(OMRequest request,
       responseObserver.onNext(omResponse);
     } catch (Throwable e) {
       LOG.error("Failed to submit request", e);
-      IOException ex = new IOException(e.getCause());
-      responseObserver.onError(
-          Status.INTERNAL.withDescription(ex.getMessage())
-              .asRuntimeException());
+      Throwable omException =
+          e instanceof ServiceException ? 
ProtobufHelper.getRemoteException((ServiceException) e) : e;
+      
responseObserver.onError(OMGrpcError.toStatusRuntimeException(omException));
       return;
     }
     responseObserver.onCompleted();
diff --git 
a/hadoop-ozone/ozone-manager/src/test/java/org/apache/hadoop/ozone/om/TestGrpcOzoneManagerServer.java
 
b/hadoop-ozone/ozone-manager/src/test/java/org/apache/hadoop/ozone/om/TestGrpcOzoneManagerServer.java
index d23da421fb1..ef15f62e274 100644
--- 
a/hadoop-ozone/ozone-manager/src/test/java/org/apache/hadoop/ozone/om/TestGrpcOzoneManagerServer.java
+++ 
b/hadoop-ozone/ozone-manager/src/test/java/org/apache/hadoop/ozone/om/TestGrpcOzoneManagerServer.java
@@ -20,6 +20,7 @@
 import static org.apache.hadoop.hdds.HddsConfigKeys.HDDS_GRPC_TLS_ENABLED;
 import static 
org.apache.hadoop.ozone.OzoneConfigKeys.OZONE_SECURITY_ENABLED_KEY;
 import static 
org.apache.hadoop.ozone.om.request.OMRequestTestUtils.createRequestWithS3Credentials;
+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.assertThrows;
@@ -32,18 +33,23 @@
 import static org.mockito.Mockito.when;
 
 import com.google.protobuf.ServiceException;
+import io.grpc.StatusRuntimeException;
 import io.grpc.stub.StreamObserver;
 import org.apache.hadoop.hdds.conf.OzoneConfiguration;
 import 
org.apache.hadoop.hdds.security.x509.certificate.client.CertificateClient;
 import org.apache.hadoop.hdds.security.x509.exception.CertificateException;
 import org.apache.hadoop.metrics2.lib.DefaultMetricsSystem;
 import org.apache.hadoop.ozone.grpc.metrics.GrpcMetrics;
+import org.apache.hadoop.ozone.om.exceptions.OMNotLeaderException;
+import org.apache.hadoop.ozone.om.protocolPB.grpc.OMGrpcError;
 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.Status;
 import org.apache.hadoop.ozone.protocol.proto.OzoneManagerProtocolProtos.Type;
 import 
org.apache.hadoop.ozone.protocolPB.OzoneManagerProtocolServerSideTranslatorPB;
+import org.apache.ratis.protocol.RaftPeerId;
 import org.junit.jupiter.api.Test;
+import org.mockito.ArgumentCaptor;
 
 /**
  * Tests for GrpcOzoneManagerServer.
@@ -130,6 +136,28 @@ public void 
testRequestWithoutS3AuthAllowedWhenAuthNotRequired()
     assertRequestPassedThrough(request, false);
   }
 
+  @Test
+  public void testOmExceptionIsSentAsOmGrpcError() throws ServiceException {
+    OzoneManagerProtocolServerSideTranslatorPB omTranslator = 
mock(OzoneManagerProtocolServerSideTranslatorPB.class);
+    when(omTranslator.submitRequest(any(), any())).thenThrow(new 
ServiceException(
+        new OMNotLeaderException(RaftPeerId.valueOf("om1"), 
RaftPeerId.valueOf("om2"), null)));
+    OzoneManagerServiceGrpc service = new 
OzoneManagerServiceGrpc(omTranslator, false);
+    @SuppressWarnings("unchecked")
+    StreamObserver<OMResponse> observer = mock(StreamObserver.class);
+
+    service.submitRequest(OMRequest.newBuilder()
+        .setCmdType(Type.ServiceList)
+        .setClientId("test-client")
+        .build(), observer);
+
+    ArgumentCaptor<Throwable> error = ArgumentCaptor.forClass(Throwable.class);
+    verify(observer).onError(error.capture());
+    verify(observer, never()).onCompleted();
+    OMGrpcError omError = 
OMGrpcError.fromStatusRuntimeException((StatusRuntimeException) 
error.getValue());
+    assertEquals(OMGrpcError.Kind.NOT_LEADER, omError.getKind());
+    assertEquals("om2", omError.getSuggestedLeaderNodeId());
+  }
+
   /**
    * Asserts the request is forwarded to the translator and its response is
    * relayed back to the client (onNext + onCompleted, no onError).


---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]

Reply via email to