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 b389ef48696 HDDS-17318. SCM client retries non-retriable server 
errors, safemode wait ignores its timeout (#11697)
b389ef48696 is described below

commit b389ef486961d08c51ff080e45addad6157596be
Author: Siyao Meng <[email protected]>
AuthorDate: Sun Nov 22 11:49:22 2026 -0800

    HDDS-17318. SCM client retries non-retriable server errors, safemode wait 
ignores its timeout (#11697)
    
    Co-authored-by: Claude Opus 5.5 <[email protected]>
---
 .../org/apache/hadoop/hdds/scm/ha/SCMHAUtils.java  | 20 ++++-
 .../apache/hadoop/hdds/scm/ha/TestSCMHAUtils.java  | 38 ++++++++++
 .../hdds/scm/cli/SafeModeWaitSubcommand.java       | 77 +++++++++++--------
 .../hdds/scm/cli/TestSafeModeWaitSubcommand.java   | 86 ++++++++++++++++++++++
 .../src/main/smoketest/admincli/safemode.robot     |  2 +-
 5 files changed, 189 insertions(+), 34 deletions(-)

diff --git 
a/hadoop-hdds/framework/src/main/java/org/apache/hadoop/hdds/scm/ha/SCMHAUtils.java
 
b/hadoop-hdds/framework/src/main/java/org/apache/hadoop/hdds/scm/ha/SCMHAUtils.java
index 939777bebd1..6fa8ce4db8b 100644
--- 
a/hadoop-hdds/framework/src/main/java/org/apache/hadoop/hdds/scm/ha/SCMHAUtils.java
+++ 
b/hadoop-hdds/framework/src/main/java/org/apache/hadoop/hdds/scm/ha/SCMHAUtils.java
@@ -19,9 +19,11 @@
 
 import com.google.common.base.Strings;
 import com.google.common.collect.ImmutableList;
+import com.google.common.collect.ImmutableSet;
 import java.io.IOException;
 import java.util.ArrayList;
 import java.util.List;
+import javax.security.sasl.SaslException;
 import org.apache.hadoop.hdds.HddsUtils;
 import org.apache.hadoop.hdds.conf.ConfigurationSource;
 import org.apache.hadoop.hdds.conf.OzoneConfiguration;
@@ -34,6 +36,7 @@
 import org.apache.hadoop.hdds.server.ServerUtils;
 import org.apache.hadoop.io.retry.RetryPolicy;
 import org.apache.hadoop.ipc_.RemoteException;
+import org.apache.hadoop.ipc_.RetriableException;
 import org.apache.hadoop.ozone.ha.ConfUtils;
 import org.apache.hadoop.security.AccessControlException;
 import org.apache.ratis.protocol.exceptions.LeaderNotReadyException;
@@ -57,6 +60,16 @@ public final class SCMHAUtils {
           .add(ResourceUnavailableException.class)
           .build();
 
+  private static final ImmutableSet<String> RETRIABLE_SERVER_EXCEPTIONS = 
ImmutableSet.of(
+      RetriableWithFailOverException.class.getName(),
+      RetriableWithNoFailoverException.class.getName(),
+      ServerNotLeaderException.class.getName(),
+      RetriableException.class.getName(),
+      // Sent by SCM versions before the fork of Hadoop RPC.
+      org.apache.hadoop.ipc.RetriableException.class.getName(),
+      // Authentication can fail temporarily, e.g. Kerberos under load.
+      SaslException.class.getName());
+
   private static final ImmutableList<Class<? extends Exception>>
       NON_RETRIABLE_EXCEPTION_LIST =
       ImmutableList.<Class<? extends Exception>>builder()
@@ -163,7 +176,12 @@ public static boolean checkNonRetriableException(Exception 
e) {
         return true;
       }
     }
-    return false;
+    // Any other exception returned by SCM will not change on retry, unless 
SCM asks for a retry.
+    // SCM converts Ratis exceptions that are worth a retry (e.g. not leader) 
to such exceptions.
+    // Compare class names, since not all of them can be unwrapped from 
RemoteException.
+    final Throwable remote = e instanceof RemoteException ? e : e.getCause();
+    return remote instanceof RemoteException
+        && !RETRIABLE_SERVER_EXCEPTIONS.contains(((RemoteException) 
remote).getClassName());
   }
 
   // This will return the underlying exception after unwrapping
diff --git 
a/hadoop-hdds/framework/src/test/java/org/apache/hadoop/hdds/scm/ha/TestSCMHAUtils.java
 
b/hadoop-hdds/framework/src/test/java/org/apache/hadoop/hdds/scm/ha/TestSCMHAUtils.java
index 863f1185c8e..e389e5d99d6 100644
--- 
a/hadoop-hdds/framework/src/test/java/org/apache/hadoop/hdds/scm/ha/TestSCMHAUtils.java
+++ 
b/hadoop-hdds/framework/src/test/java/org/apache/hadoop/hdds/scm/ha/TestSCMHAUtils.java
@@ -25,15 +25,22 @@
 
 import com.google.protobuf.ServiceException;
 import java.io.IOException;
+import java.net.ConnectException;
 import java.util.Collection;
+import javax.security.sasl.SaslException;
 import org.apache.hadoop.hdds.HddsUtils;
 import org.apache.hadoop.hdds.conf.OzoneConfiguration;
+import org.apache.hadoop.hdds.ratis.ServerNotLeaderException;
+import org.apache.hadoop.hdds.scm.ha.RetriableWithFailOverException;
 import org.apache.hadoop.hdds.scm.ha.RetriableWithNoFailoverException;
 import org.apache.hadoop.hdds.scm.ha.SCMHAUtils;
 import org.apache.hadoop.io.retry.RetryPolicy.RetryAction;
 import org.apache.hadoop.io.retry.RetryPolicy.RetryAction.RetryDecision;
 import org.apache.hadoop.ipc_.RemoteException;
+import org.apache.hadoop.ipc_.RetriableException;
 import org.junit.jupiter.api.Test;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.ValueSource;
 
 /**
  * Tests for {@code SCMHAUtils}.
@@ -58,6 +65,29 @@ void testRemoveSelfId() {
     assertThat(nodesWithoutSelf).doesNotContain(selfId);
   }
 
+  @ParameterizedTest
+  @ValueSource(classes = {IOException.class, IllegalArgumentException.class})
+  void failsOnOtherServerException(Class<?> serverException) {
+    assertEquals(RetryDecision.FAIL, 
getRetryDecision(fromServer(serverException)));
+  }
+
+  @ParameterizedTest
+  @ValueSource(classes = {ServerNotLeaderException.class, 
RetriableWithFailOverException.class,
+      RetriableException.class, 
org.apache.hadoop.ipc.RetriableException.class, SaslException.class})
+  void failsOverOnRetriableServerException(Class<?> serverException) {
+    assertEquals(RetryDecision.FAILOVER_AND_RETRY, 
getRetryDecision(fromServer(serverException)));
+  }
+
+  @Test
+  void failsOnRemoteException() {
+    assertEquals(RetryDecision.FAIL, getRetryDecision(new 
RemoteException(IOException.class.getName(), "error")));
+  }
+
+  @Test
+  void failsOverOnConnectionFailure() {
+    assertEquals(RetryDecision.FAILOVER_AND_RETRY, getRetryDecision(new 
ConnectException("Connection refused")));
+  }
+
   @Test
   void retriesSameScmOnRetriableWithNoFailoverException() {
     Exception e = new ServiceException(new 
RemoteException(RetriableWithNoFailoverException.class.getName(),
@@ -73,4 +103,12 @@ void retriesSameScmOnRetriableWithNoFailoverException() {
     Exception other = new ServiceException(new 
RemoteException(IOException.class.getName(), "error"));
     
assertThat(SCMHAUtils.checkRetriableWithNoFailoverException(other)).isFalse();
   }
+
+  private static Exception fromServer(Class<?> serverException) {
+    return new ServiceException(new RemoteException(serverException.getName(), 
"server error"));
+  }
+
+  private static RetryDecision getRetryDecision(Exception e) {
+    return SCMHAUtils.getRetryAction(0, 0, e, 15, 2000).action;
+  }
 }
diff --git 
a/hadoop-ozone/cli-admin/src/main/java/org/apache/hadoop/hdds/scm/cli/SafeModeWaitSubcommand.java
 
b/hadoop-ozone/cli-admin/src/main/java/org/apache/hadoop/hdds/scm/cli/SafeModeWaitSubcommand.java
index 9690bbf8d45..43ffae5b5d3 100644
--- 
a/hadoop-ozone/cli-admin/src/main/java/org/apache/hadoop/hdds/scm/cli/SafeModeWaitSubcommand.java
+++ 
b/hadoop-ozone/cli-admin/src/main/java/org/apache/hadoop/hdds/scm/cli/SafeModeWaitSubcommand.java
@@ -18,9 +18,15 @@
 package org.apache.hadoop.hdds.scm.cli;
 
 import java.util.concurrent.Callable;
+import java.util.concurrent.ExecutionException;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+import java.util.concurrent.Future;
+import java.util.concurrent.TimeUnit;
 import java.util.concurrent.TimeoutException;
 import org.apache.hadoop.hdds.cli.HddsVersionProvider;
 import org.apache.hadoop.hdds.scm.client.ScmClient;
+import org.apache.hadoop.security.AccessControlException;
 import org.apache.hadoop.util.Time;
 import picocli.CommandLine.Command;
 import picocli.CommandLine.Mixin;
@@ -42,50 +48,57 @@ public class SafeModeWaitSubcommand implements 
Callable<Void> {
       names = { "-t", "--timeout"})
   private long timeoutSeconds;
 
-  private long startTestTime;
-
   @Mixin
   private ScmOption scmOption;
 
   @Override
   public Void call() throws Exception {
-    startTestTime = Time.monotonicNow();
+    try (ScmClient scmClient = scmOption.createScmClient()) {
+      execute(scmClient);
+    }
+    return null;
+  }
 
-    while (getRemainingTimeInSec() > 0) {
-      try (ScmClient scmClient = scmOption.createScmClient()) {
-        long remainingTime;
-        do {
-          if (!scmClient.inSafeMode()) {
+  void execute(ScmClient scmClient) throws Exception {
+    final long deadline = Time.monotonicNow() + 
TimeUnit.SECONDS.toMillis(timeoutSeconds);
+    // Call SCM in another thread, so that the timeout also applies to a call 
that is still retrying.
+    final ExecutorService executor = 
Executors.newSingleThreadExecutor(runnable -> {
+      Thread thread = new Thread(runnable, "SafeModeWait");
+      thread.setDaemon(true);
+      return thread;
+    });
+    Throwable lastError = null;
+    try {
+      for (long remaining = deadline - Time.monotonicNow(); remaining > 0; 
remaining = deadline - Time.monotonicNow()) {
+        final Future<Boolean> inSafeMode = 
executor.submit(scmClient::inSafeMode);
+        try {
+          if (!inSafeMode.get(remaining, TimeUnit.MILLISECONDS)) {
             System.out.println("SCM is out of safe mode.");
-            return null;
+            return;
           }
-
-          remainingTime = getRemainingTimeInSec();
-
-          if (remainingTime > 0) {
-            System.out.printf(
-                "SCM is in safe mode. Will retry in 1 sec. Remaining time "
-                    + "(sec): %s%n",
-                remainingTime);
-            Thread.sleep(1000);
-          } else {
-            System.out.println("SCM is in safe mode. No more retries.");
+          System.out.printf("SCM is in safe mode. Will retry in 1 sec. 
Remaining time (sec): %s%n",
+              getRemainingTimeInSec(deadline));
+        } catch (ExecutionException e) {
+          if (e.getCause() instanceof AccessControlException) {
+            throw (AccessControlException) e.getCause();
           }
-        } while (remainingTime > 0);
-      } catch (InterruptedException ex) {
-        System.out.printf(
-            "SCM is not available (yet?). Error is %s. Will retry in 1 sec. "
-                + "Remaining time (sec): %s%n",
-            ex.getMessage(), getRemainingTimeInSec());
-        Thread.sleep(1000);
-        Thread.currentThread().interrupt();
+          lastError = e.getCause();
+          System.out.printf("SCM is not available (yet?). Error is %s. Will 
retry in 1 sec. Remaining time (sec): %s%n",
+              lastError, getRemainingTimeInSec(deadline));
+        } catch (TimeoutException e) {
+          break;
+        }
+        Thread.sleep(Math.max(0, Math.min(1000, deadline - 
Time.monotonicNow())));
       }
+    } finally {
+      executor.shutdownNow();
     }
-    throw new TimeoutException(
-        "Safe mode is not ended within the timeout period.");
+    final TimeoutException timeout = new TimeoutException("Safe mode is not 
ended within the timeout period.");
+    timeout.initCause(lastError);
+    throw timeout;
   }
 
-  private long getRemainingTimeInSec() {
-    return timeoutSeconds - (Time.monotonicNow() - startTestTime) / 1000;
+  private static long getRemainingTimeInSec(long deadline) {
+    return TimeUnit.MILLISECONDS.toSeconds(Math.max(0, deadline - 
Time.monotonicNow()));
   }
 }
diff --git 
a/hadoop-ozone/cli-admin/src/test/java/org/apache/hadoop/hdds/scm/cli/TestSafeModeWaitSubcommand.java
 
b/hadoop-ozone/cli-admin/src/test/java/org/apache/hadoop/hdds/scm/cli/TestSafeModeWaitSubcommand.java
new file mode 100644
index 00000000000..9c9fb2142c5
--- /dev/null
+++ 
b/hadoop-ozone/cli-admin/src/test/java/org/apache/hadoop/hdds/scm/cli/TestSafeModeWaitSubcommand.java
@@ -0,0 +1,86 @@
+/*
+ * 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.hdds.scm.cli;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.junit.jupiter.api.Assertions.assertTimeoutPreemptively;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.times;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+
+import java.io.IOException;
+import java.time.Duration;
+import java.util.concurrent.TimeoutException;
+import org.apache.hadoop.hdds.scm.client.ScmClient;
+import org.apache.hadoop.security.AccessControlException;
+import org.junit.jupiter.api.Test;
+import picocli.CommandLine;
+
+/**
+ * Tests for `ozone admin safemode wait`.
+ */
+public class TestSafeModeWaitSubcommand {
+
+  private static SafeModeWaitSubcommand newCommand(String timeoutSeconds) {
+    SafeModeWaitSubcommand cmd = new SafeModeWaitSubcommand();
+    new CommandLine(cmd).parseArgs("-t", timeoutSeconds);
+    return cmd;
+  }
+
+  @Test
+  void retriesUntilOutOfSafeMode() throws Exception {
+    ScmClient scmClient = mock(ScmClient.class);
+    when(scmClient.inSafeMode()).thenThrow(new IOException("SCM is not 
available")).thenReturn(true, false);
+
+    assertTimeoutPreemptively(Duration.ofSeconds(10), () -> 
newCommand("30").execute(scmClient));
+    verify(scmClient, times(3)).inSafeMode();
+  }
+
+  @Test
+  void timesOutInSafeMode() throws Exception {
+    ScmClient scmClient = mock(ScmClient.class);
+    when(scmClient.inSafeMode()).thenThrow(new IOException("SCM is not 
available")).thenReturn(true);
+
+    TimeoutException e = assertThrows(TimeoutException.class, () -> 
newCommand("2").execute(scmClient));
+    // The last error is kept as the cause.
+    assertThat(e).hasRootCauseMessage("SCM is not available");
+  }
+
+  @Test
+  void failsOnAccessControlException() throws Exception {
+    ScmClient scmClient = mock(ScmClient.class);
+    when(scmClient.inSafeMode()).thenThrow(new 
AccessControlException("denied"));
+
+    assertThrows(AccessControlException.class, () -> 
newCommand("30").execute(scmClient));
+    verify(scmClient, times(1)).inSafeMode();
+  }
+
+  @Test
+  void timesOutWhileSCMCallIsStillRetrying() throws Exception {
+    ScmClient scmClient = mock(ScmClient.class);
+    when(scmClient.inSafeMode()).thenAnswer(invocation -> {
+      Thread.sleep(Long.MAX_VALUE);
+      return false;
+    });
+
+    assertTimeoutPreemptively(Duration.ofSeconds(10),
+        () -> assertThrows(TimeoutException.class, () -> 
newCommand("1").execute(scmClient)));
+  }
+}
diff --git a/hadoop-ozone/dist/src/main/smoketest/admincli/safemode.robot 
b/hadoop-ozone/dist/src/main/smoketest/admincli/safemode.robot
index 7f0c93dcab6..00551e47cd0 100644
--- a/hadoop-ozone/dist/src/main/smoketest/admincli/safemode.robot
+++ b/hadoop-ozone/dist/src/main/smoketest/admincli/safemode.robot
@@ -32,7 +32,7 @@ Check safemode with explicit host
                         Should contain   ${output}   SCM is out of safe mode
 
 Wait for safemode exit
-    ${output} =         Execute          ozone admin safemode wait -t 2
+    ${output} =         Execute          ozone admin safemode wait -t 10
                         Should contain   ${output}   SCM is out of safe mode
 
 Incomplete command


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

Reply via email to