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 eef3e71885c HDDS-17580. Scrub open pipelines with unregistered 
datanodes before SCM safemode exit (#12024)
eef3e71885c is described below

commit eef3e71885cf9bcf6ab8a4c1ff8c851e7d5d4a56
Author: Ethan Rose <[email protected]>
AuthorDate: Fri Nov 13 13:51:53 2026 -0500

    HDDS-17580. Scrub open pipelines with unregistered datanodes before SCM 
safemode exit (#12024)
---
 .../common/src/main/resources/ozone-default.xml    |   8 +-
 .../org/apache/hadoop/hdds/scm/ha/SCMService.java  |   4 +-
 .../scm/pipeline/BackgroundPipelineCreator.java    |   7 +-
 .../scm/pipeline/BackgroundPipelineScrubber.java   | 238 +++++++++++++++++++++
 .../hdds/scm/pipeline/PipelineManagerImpl.java     | 167 +++++++++------
 .../hdds/scm/pipeline/SCMPipelineMetrics.java      |   9 +
 .../scm/safemode/HealthyPipelineSafeModeRule.java  |  87 ++++++--
 .../hdds/scm/safemode/SCMSafeModeManager.java      |  11 +
 .../hdds/scm/safemode/SafeModeRuleFactory.java     |   8 +-
 .../hadoop/hdds/scm/container/MockNodeManager.java |   3 +-
 .../pipeline/TestBackgroundPipelineCreator.java    |  26 +++
 .../pipeline/TestBackgroundPipelineScrubber.java   | 170 +++++++++++++++
 .../hdds/scm/pipeline/TestPipelineManagerImpl.java |  70 ++++++
 .../safemode/TestHealthyPipelineSafeModeRule.java  | 176 +++++++++++++++
 .../hdds/scm/safemode/TestSCMSafeModeManager.java  |  39 +++-
 .../hdds/scm/safemode/TestSafeModeRuleFactory.java |  12 +-
 .../main/compose/upgrade/compose/ha/docker-config  |   7 +-
 .../safemode/TestSCMSafeModeWithPipelineRules.java |  60 ++++--
 18 files changed, 987 insertions(+), 115 deletions(-)

diff --git a/hadoop-hdds/common/src/main/resources/ozone-default.xml 
b/hadoop-hdds/common/src/main/resources/ozone-default.xml
index a4fd106c51a..01ed7033d77 100644
--- a/hadoop-hdds/common/src/main/resources/ozone-default.xml
+++ b/hadoop-hdds/common/src/main/resources/ozone-default.xml
@@ -1675,7 +1675,10 @@
     <tag>OZONE, SCM, PIPELINE</tag>
     <description>
       SCM schedules a fixed interval job using the configured interval to
-      scrub pipelines.
+      scrub pipelines. While SCM is in safe mode, the job starts on the leader
+      once the container safe mode rules have passed and
+      ozone.scm.stale.node.interval has elapsed since SCM started, so that open
+      pipelines with unregistered datanodes are closed before safe mode exits.
     </description>
   </property>
   <property>
@@ -1727,8 +1730,7 @@
     <value>5m</value>
     <tag>HDDS,SCM,OPERATION</tag>
     <description> After exiting safemode, wait for configured interval of
-      time to start replication monitor and cleanup activities of unhealthy
-      pipelines.
+      time to start replication monitor and other background services.
     </description>
   </property>
 
diff --git 
a/hadoop-hdds/server-scm/src/main/java/org/apache/hadoop/hdds/scm/ha/SCMService.java
 
b/hadoop-hdds/server-scm/src/main/java/org/apache/hadoop/hdds/scm/ha/SCMService.java
index fb2c43686c9..d69cb8580bd 100644
--- 
a/hadoop-hdds/server-scm/src/main/java/org/apache/hadoop/hdds/scm/ha/SCMService.java
+++ 
b/hadoop-hdds/server-scm/src/main/java/org/apache/hadoop/hdds/scm/ha/SCMService.java
@@ -62,7 +62,9 @@ enum Event {
     PRE_CHECK_COMPLETED,
     NEW_NODE_HANDLER_TRIGGERED,
     NODE_ADDRESS_UPDATE_HANDLER_TRIGGERED,
-    UNHEALTHY_TO_HEALTHY_NODE_HANDLER_TRIGGERED
+    UNHEALTHY_TO_HEALTHY_NODE_HANDLER_TRIGGERED,
+    CONTAINER_SAFE_MODE_RULES_VALIDATED,
+    SCRUBBER_CLOSED_PIPELINES
   }
 
   /**
diff --git 
a/hadoop-hdds/server-scm/src/main/java/org/apache/hadoop/hdds/scm/pipeline/BackgroundPipelineCreator.java
 
b/hadoop-hdds/server-scm/src/main/java/org/apache/hadoop/hdds/scm/pipeline/BackgroundPipelineCreator.java
index 97455d56d51..845e673918c 100644
--- 
a/hadoop-hdds/server-scm/src/main/java/org/apache/hadoop/hdds/scm/pipeline/BackgroundPipelineCreator.java
+++ 
b/hadoop-hdds/server-scm/src/main/java/org/apache/hadoop/hdds/scm/pipeline/BackgroundPipelineCreator.java
@@ -23,6 +23,7 @@
 import static 
org.apache.hadoop.hdds.scm.ha.SCMService.Event.NEW_NODE_HANDLER_TRIGGERED;
 import static 
org.apache.hadoop.hdds.scm.ha.SCMService.Event.NODE_ADDRESS_UPDATE_HANDLER_TRIGGERED;
 import static 
org.apache.hadoop.hdds.scm.ha.SCMService.Event.PRE_CHECK_COMPLETED;
+import static 
org.apache.hadoop.hdds.scm.ha.SCMService.Event.SCRUBBER_CLOSED_PIPELINES;
 import static 
org.apache.hadoop.hdds.scm.ha.SCMService.Event.UNHEALTHY_TO_HEALTHY_NODE_HANDLER_TRIGGERED;
 
 import com.google.common.annotations.VisibleForTesting;
@@ -67,7 +68,8 @@ public class BackgroundPipelineCreator implements SCMService {
    * 1) after leaving safe mode, BackgroundPipelineCreator needs to
    *    wait for a while before really take effect.
    * 2) NewNodeHandler, NodeAddressUpdateHandler,
-   *    NonHealthyToHealthyNodeHandler, PreCheckComplete
+   *    NonHealthyToHealthyNodeHandler, PreCheckComplete,
+   *    BackgroundPipelineScrubber closing pipelines
    *    will trigger a one-shot run of BackgroundPipelineCreator,
    *    no matter in safe mode or not.
    */
@@ -315,7 +317,8 @@ public void notifyEventTriggered(Event event) {
     if (event == NEW_NODE_HANDLER_TRIGGERED
             || event == NODE_ADDRESS_UPDATE_HANDLER_TRIGGERED
             || event == UNHEALTHY_TO_HEALTHY_NODE_HANDLER_TRIGGERED
-            || event == PRE_CHECK_COMPLETED) {
+            || event == PRE_CHECK_COMPLETED
+            || event == SCRUBBER_CLOSED_PIPELINES) {
       LOG.info("trigger a one-shot run on {}.", threadName);
 
       serviceLock.lock();
diff --git 
a/hadoop-hdds/server-scm/src/main/java/org/apache/hadoop/hdds/scm/pipeline/BackgroundPipelineScrubber.java
 
b/hadoop-hdds/server-scm/src/main/java/org/apache/hadoop/hdds/scm/pipeline/BackgroundPipelineScrubber.java
new file mode 100644
index 00000000000..167992e5aca
--- /dev/null
+++ 
b/hadoop-hdds/server-scm/src/main/java/org/apache/hadoop/hdds/scm/pipeline/BackgroundPipelineScrubber.java
@@ -0,0 +1,238 @@
+/*
+ * 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.pipeline;
+
+import static 
org.apache.hadoop.hdds.scm.ha.SCMService.Event.CONTAINER_SAFE_MODE_RULES_VALIDATED;
+
+import com.google.common.annotations.VisibleForTesting;
+import java.time.Clock;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.concurrent.locks.Lock;
+import java.util.concurrent.locks.ReentrantLock;
+import org.apache.hadoop.hdds.conf.ConfigurationSource;
+import org.apache.hadoop.hdds.scm.ScmConfigKeys;
+import org.apache.hadoop.hdds.scm.ha.SCMContext;
+import org.apache.hadoop.hdds.scm.ha.SCMService;
+import org.apache.hadoop.hdds.utils.HddsServerUtil;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * Background service which periodically scrubs pipelines on the leader SCM.
+ *
+ * Open pipelines with datanodes which are not registered must be closed
+ * before SCM exits safe mode, so that those datanodes are not handed out for
+ * reads or writes. Therefore, besides running out of safe mode, this service
+ * also runs in safe mode once:
+ * 1) all container safe mode rules have passed, so that the datanodes which
+ *    are coming back have mostly registered, and
+ * 2) the stale node interval has elapsed since the service was created at SCM
+ *    startup, so that datanodes which are still unregistered are treated like
+ *    stale nodes, whose pipelines are closed by StaleNodeHandler.
+ */
+public class BackgroundPipelineScrubber implements SCMService {
+
+  private static final Logger LOG =
+      LoggerFactory.getLogger(BackgroundPipelineScrubber.class);
+
+  private static final String SERVICE_NAME = "BackgroundPipelineScrubber";
+
+  private final Runnable scrubTask;
+  private final SCMContext scmContext;
+  private volatile Clock clock;
+  private final long intervalInMillis;
+  private final long safeModeRunDelayInMillis;
+  private final long createdTimeInMillis;
+  private final String threadName;
+
+  private final Lock serviceLock = new ReentrantLock();
+  private ServiceStatus serviceStatus = ServiceStatus.PAUSING;
+  private boolean containerSafeModeRulesValidated = false;
+
+  private final AtomicBoolean running = new AtomicBoolean(false);
+  private Thread thread;
+  private final Object monitor = new Object();
+  private boolean runImmediately = false;
+
+  BackgroundPipelineScrubber(Runnable scrubTask, ConfigurationSource conf,
+      SCMContext scmContext, Clock clock) {
+    this.scrubTask = scrubTask;
+    this.scmContext = scmContext;
+    this.clock = clock;
+    this.intervalInMillis = conf.getTimeDuration(
+        ScmConfigKeys.OZONE_SCM_PIPELINE_SCRUB_INTERVAL,
+        ScmConfigKeys.OZONE_SCM_PIPELINE_SCRUB_INTERVAL_DEFAULT,
+        TimeUnit.MILLISECONDS);
+    this.safeModeRunDelayInMillis = HddsServerUtil.getStaleNodeInterval(conf);
+    this.createdTimeInMillis = clock.millis();
+    this.threadName = scmContext.threadNamePrefix() + SERVICE_NAME;
+  }
+
+  @Override
+  public void start() {
+    if (!running.compareAndSet(false, true)) {
+      LOG.info("{} is already started, just ignore.", threadName);
+      return;
+    }
+    LOG.info("Starting {}.", threadName);
+    thread = new Thread(this::run);
+    thread.setName(threadName);
+    thread.setDaemon(true);
+    thread.start();
+  }
+
+  @Override
+  public void stop() {
+    if (!running.compareAndSet(true, false)) {
+      LOG.info("{} is not running, just ignore.", threadName);
+      return;
+    }
+    LOG.info("Stopping {}.", threadName);
+    thread.interrupt();
+  }
+
+  @VisibleForTesting
+  public boolean isRunning() {
+    return running.get();
+  }
+
+  private void run() {
+    while (running.get()) {
+      try {
+        final boolean shouldRun;
+        final long waitInMillis;
+        serviceLock.lock();
+        try {
+          // Decide whether to run and how long to wait from one check, so the 
safe mode run delay cannot elapse in
+          // between and leave the service waiting for a full interval. While 
the delay is pending, wake up as soon as
+          // it elapses instead of waiting for the full interval.
+          final long remainingDelay = getRemainingSafeModeRunDelayInMillis();
+          shouldRun = (serviceStatus == ServiceStatus.RUNNING) && 
(remainingDelay <= 0);
+          waitInMillis = remainingDelay > 0 ? Math.min(intervalInMillis, 
remainingDelay) : intervalInMillis;
+        } finally {
+          serviceLock.unlock();
+        }
+        if (shouldRun) {
+          try {
+            scrubTask.run();
+          } catch (Throwable e) {
+            LOG.error("Caught unhandled exception in {}. The task will be 
re-tried in {}ms",
+                threadName, intervalInMillis, e);
+          }
+        }
+        synchronized (monitor) {
+          if (!runImmediately) {
+            monitor.wait(waitInMillis);
+          }
+          runImmediately = false;
+        }
+      } catch (InterruptedException e) {
+        LOG.warn("{} is interrupted, exit", threadName);
+        Thread.currentThread().interrupt();
+        running.set(false);
+      }
+    }
+  }
+
+  @Override
+  public void notifyStatusChanged() {
+    boolean transitionedToRunning = false;
+    serviceLock.lock();
+    try {
+      if (scmContext.isLeaderReady() && (!scmContext.isInSafeMode() || 
containerSafeModeRulesValidated)) {
+        if (serviceStatus != ServiceStatus.RUNNING) {
+          LOG.info("Service {} transitions to RUNNING.", getServiceName());
+          serviceStatus = ServiceStatus.RUNNING;
+          transitionedToRunning = true;
+        }
+      } else if (serviceStatus != ServiceStatus.PAUSING) {
+        LOG.info("Service {} transitions to PAUSING.", getServiceName());
+        serviceStatus = ServiceStatus.PAUSING;
+      }
+    } finally {
+      serviceLock.unlock();
+    }
+    // Do not sit out the current interval once the service is allowed to run.
+    if (transitionedToRunning) {
+      runImmediately();
+    }
+  }
+
+  @Override
+  public void notifyEventTriggered(Event event) {
+    if (event != CONTAINER_SAFE_MODE_RULES_VALIDATED) {
+      return;
+    }
+    // Recorded on followers too, so that the service can run in safe mode if
+    // this SCM becomes the leader later.
+    serviceLock.lock();
+    try {
+      if (containerSafeModeRulesValidated) {
+        return;
+      }
+      LOG.info("Service {} is allowed to run in safe mode after event {}.", 
getServiceName(), event);
+      containerSafeModeRulesValidated = true;
+    } finally {
+      serviceLock.unlock();
+    }
+    notifyStatusChanged();
+  }
+
+  @Override
+  public boolean shouldRun() {
+    serviceLock.lock();
+    try {
+      return serviceStatus == ServiceStatus.RUNNING && 
getRemainingSafeModeRunDelayInMillis() <= 0;
+    } finally {
+      serviceLock.unlock();
+    }
+  }
+
+  /**
+   * @return The time left before the service may scrub in safe mode, or 0 if 
it is not waiting.
+   */
+  private long getRemainingSafeModeRunDelayInMillis() {
+    if (serviceStatus != ServiceStatus.RUNNING || !scmContext.isInSafeMode()) {
+      return 0;
+    }
+    return safeModeRunDelayInMillis - (clock.millis() - createdTimeInMillis);
+  }
+
+  /**
+   * Replaces the clock used to check the safe mode run delay, and wakes up 
the service to check it again. The delay is
+   * still measured from the time the service was created.
+   */
+  @VisibleForTesting
+  public void setClock(Clock clock) {
+    this.clock = clock;
+    runImmediately();
+  }
+
+  private void runImmediately() {
+    synchronized (monitor) {
+      runImmediately = true;
+      monitor.notifyAll();
+    }
+  }
+
+  @Override
+  public String getServiceName() {
+    return SERVICE_NAME;
+  }
+}
diff --git 
a/hadoop-hdds/server-scm/src/main/java/org/apache/hadoop/hdds/scm/pipeline/PipelineManagerImpl.java
 
b/hadoop-hdds/server-scm/src/main/java/org/apache/hadoop/hdds/scm/pipeline/PipelineManagerImpl.java
index 8890632a60b..f5a4a43b39a 100644
--- 
a/hadoop-hdds/server-scm/src/main/java/org/apache/hadoop/hdds/scm/pipeline/PipelineManagerImpl.java
+++ 
b/hadoop-hdds/server-scm/src/main/java/org/apache/hadoop/hdds/scm/pipeline/PipelineManagerImpl.java
@@ -49,9 +49,10 @@
 import org.apache.hadoop.hdds.scm.container.ContainerManager;
 import org.apache.hadoop.hdds.scm.container.ContainerReplica;
 import org.apache.hadoop.hdds.scm.events.SCMEvents;
-import org.apache.hadoop.hdds.scm.ha.BackgroundSCMService;
+import org.apache.hadoop.hdds.scm.exceptions.SCMException;
 import org.apache.hadoop.hdds.scm.ha.SCMContext;
 import org.apache.hadoop.hdds.scm.ha.SCMHAManager;
+import org.apache.hadoop.hdds.scm.ha.SCMService.Event;
 import org.apache.hadoop.hdds.scm.ha.SCMServiceManager;
 import org.apache.hadoop.hdds.scm.node.DatanodeInfo;
 import org.apache.hadoop.hdds.scm.node.NodeManager;
@@ -81,7 +82,7 @@ public class PipelineManagerImpl implements PipelineManager {
   private PipelineFactory pipelineFactory;
   private PipelineStateManager stateManager;
   private BackgroundPipelineCreator backgroundPipelineCreator;
-  private BackgroundSCMService backgroundPipelineScrubber;
+  private BackgroundPipelineScrubber backgroundPipelineScrubber;
   private final ConfigurationSource conf;
   private final EventPublisher eventPublisher;
   // Pipeline Manager MXBean
@@ -156,26 +157,12 @@ public static PipelineManagerImpl newPipelineManager(
     serviceManager.register(backgroundPipelineCreator);
     backgroundPipelineCreator.start();
 
-    final long scrubberIntervalInMillis = conf.getTimeDuration(
-        ScmConfigKeys.OZONE_SCM_PIPELINE_SCRUB_INTERVAL,
-        ScmConfigKeys.OZONE_SCM_PIPELINE_SCRUB_INTERVAL_DEFAULT,
-        TimeUnit.MILLISECONDS);
-    final long safeModeWaitMs = conf.getTimeDuration(
-        HddsConfigKeys.HDDS_SCM_WAIT_TIME_AFTER_SAFE_MODE_EXIT,
-        HddsConfigKeys.HDDS_SCM_WAIT_TIME_AFTER_SAFE_MODE_EXIT_DEFAULT,
-        TimeUnit.MILLISECONDS);
-
-    BackgroundSCMService backgroundPipelineScrubber =
-        new BackgroundSCMService.Builder().setClock(clock)
-            .setScmContext(scmContext)
-            .setServiceName("BackgroundPipelineScrubber")
-            .setIntervalInMillis(scrubberIntervalInMillis)
-            .setWaitTimeInMillis(safeModeWaitMs)
-            
.setPeriodicalTask(pipelineManager::scrubAndClosePipelinesMissingDataStreamPort)
-            .build();
+    BackgroundPipelineScrubber backgroundPipelineScrubber = new 
BackgroundPipelineScrubber(
+        pipelineManager::scrubAndClosePipelinesMissingDataStreamPort, conf, 
scmContext, clock);
 
     pipelineManager.setBackgroundPipelineScrubber(backgroundPipelineScrubber);
     serviceManager.register(backgroundPipelineScrubber);
+    backgroundPipelineScrubber.start();
 
     return pipelineManager;
   }
@@ -473,17 +460,28 @@ private void closeContainersForPipeline(final PipelineID 
pipelineId)
   @Override
   public void closePipeline(PipelineID pipelineID) throws IOException {
     HddsProtos.PipelineID pipelineIDProtobuf = pipelineID.getProtobuf();
-    // close containers.
-    closeContainersForPipeline(pipelineID);
-    if (!getPipeline(pipelineID).isClosed()) {
-      acquireWriteLock();
-      try {
-        stateManager.updatePipelineState(pipelineIDProtobuf,
-            HddsProtos.PipelineState.PIPELINE_CLOSED);
-      } finally {
-        releaseWriteLock();
+    try {
+      // close containers.
+      closeContainersForPipeline(pipelineID);
+      if (!getPipeline(pipelineID).isClosed()) {
+        acquireWriteLock();
+        try {
+          stateManager.updatePipelineState(pipelineIDProtobuf,
+              HddsProtos.PipelineState.PIPELINE_CLOSED);
+        } finally {
+          releaseWriteLock();
+        }
+        LOG.info("Pipeline {} moved to CLOSED state", pipelineID);
+      }
+    } catch (PipelineNotFoundException e) {
+      // There is no pipeline left to close.
+      throw e;
+    } catch (IOException e) {
+      // Followers are expected to fail with not-leader errors, so they are 
not counted as close failures.
+      if (!(e instanceof SCMException && ((SCMException) e).getResult() == 
SCMException.ResultCodes.SCM_NOT_LEADER)) {
+        metrics.incNumPipelineCloseFailed();
       }
-      LOG.info("Pipeline {} moved to CLOSED state", pipelineID);
+      throw e;
     }
 
     metrics.removePipelineMetrics(pipelineID);
@@ -557,6 +555,7 @@ void closePipelinesMissingDataStreamPort() {
     if (!isDataStreamEnabled()) {
       return;
     }
+    boolean closedPipelines = false;
     for (Pipeline pipeline : getPipelines()) {
       if (!pipeline.isOpen()
           || pipeline.getType() != ReplicationType.RATIS
@@ -567,12 +566,16 @@ void closePipelinesMissingDataStreamPort() {
         final PipelineID id = pipeline.getId();
         LOG.info("Closing RATIS pipeline {}", id);
         closePipeline(id);
+        closedPipelines = true;
         deletePipeline(id);
       } catch (IOException e) {
         LOG.error("Failed to close RATIS pipeline {} missing the datastream "
             + "port", pipeline.getId(), e);
       }
     }
+    if (closedPipelines) {
+      notifyPipelineCreatorOfClosedPipelines();
+    }
   }
 
   private boolean isDataStreamEnabled() {
@@ -597,6 +600,8 @@ private boolean nodesMissingDataStreamPort(Pipeline 
pipeline) {
     return false;
   }
 
+  // TODO: Move pipeline scrubbing, including 
closePipelinesMissingDataStreamPort and isOpenWithUnregisteredNodes, out
+  //  of the pipeline manager into BackgroundPipelineScrubber in a follow-up 
change.
   /**
    * Scrub pipelines.
    */
@@ -613,55 +618,86 @@ public void scrubPipelines() throws IOException {
             TimeUnit.MILLISECONDS);
 
     List<Pipeline> candidates = stateManager.getPipelines();
+    boolean closedPipelines = false;
 
     for (Pipeline p : candidates) {
       final PipelineID id = p.getId();
-      // scrub pipelines who stay ALLOCATED for too long.
-      if (p.getPipelineState() == Pipeline.PipelineState.ALLOCATED &&
-          (currentTime.toEpochMilli() - p.getCreationTimestamp()
-              .toEpochMilli() >= pipelineScrubTimeoutInMills)) {
-
-        LOG.info("Scrubbing pipeline: id: {} since it stays at ALLOCATED " +
-            "stage for {} mins.", id,
-            Duration.between(p.getCreationTimestamp(), currentTime)
-                .toMinutes());
-        closePipeline(id);
-        deletePipeline(id);
-      }
-      // scrub pipelines who stay CLOSED for too long.
-      if (p.getPipelineState() == Pipeline.PipelineState.CLOSED &&
-          (currentTime.toEpochMilli() - p.getStateEnterTime().toEpochMilli())
-              >= pipelineDeleteTimoutInMills) {
-        LOG.info("Scrubbing pipeline: id: {} since it stays at CLOSED stage.",
-            p.getId());
-        deletePipeline(id);
-      }
-      // If a datanode is stopped and then SCM is restarted, a pipeline can get
-      // stuck in an open state. For Ratis, provided some other DNs that were
-      // part of the open pipeline register to SCM after the restart, the Ratis
-      // pipeline close will get triggered by the DNs. For EC that will never
-      // happen, as the DNs are not aware of the pipeline. Therefore we should
-      // close any pipelines in the scrubber if they have nodes which are not
-      // registered
-      if (isOpenWithUnregisteredNodes(p)) {
-        LOG.info("Scrubbing pipeline: id: {} as it has unregistered nodes",
-            p.getId());
-        closePipeline(id);
+      // Handle failures per pipeline so one bad pipeline does not stop the
+      // rest from being scrubbed until the next run.
+      try {
+        // scrub pipelines who stay ALLOCATED for too long.
+        if (p.getPipelineState() == Pipeline.PipelineState.ALLOCATED &&
+            (currentTime.toEpochMilli() - p.getCreationTimestamp()
+                .toEpochMilli() >= pipelineScrubTimeoutInMills)) {
+
+          LOG.info("Scrubbing pipeline: id: {} since it stays at ALLOCATED " +
+              "stage for {} mins.", id,
+              Duration.between(p.getCreationTimestamp(), currentTime)
+                  .toMinutes());
+          closePipeline(id);
+          closedPipelines = true;
+          deletePipeline(id);
+        }
+        // scrub pipelines who stay CLOSED for too long.
+        if (p.getPipelineState() == Pipeline.PipelineState.CLOSED &&
+            (currentTime.toEpochMilli() - p.getStateEnterTime().toEpochMilli())
+                >= pipelineDeleteTimoutInMills) {
+          LOG.info("Scrubbing pipeline: id: {} since it stays at CLOSED 
stage.",
+              p.getId());
+          deletePipeline(id);
+        }
+        // If a datanode is stopped and then SCM is restarted, a pipeline can 
get
+        // stuck in an open state. For Ratis, provided some other DNs that were
+        // part of the open pipeline register to SCM after the restart, the 
Ratis
+        // pipeline close will get triggered by the DNs. For EC that will never
+        // happen, as the DNs are not aware of the pipeline. Therefore we 
should
+        // close any pipelines in the scrubber if they have nodes which are not
+        // registered
+        if (isOpenWithUnregisteredNodes(p, nodeManager)) {
+          LOG.info("Scrubbing pipeline: id: {} as it has unregistered nodes",
+              p.getId());
+          closePipeline(id);
+          closedPipelines = true;
+        }
+      } catch (SCMException e) {
+        // No other pipeline can be scrubbed once this SCM is no longer the 
leader.
+        if (e.getResult() == SCMException.ResultCodes.SCM_NOT_LEADER) {
+          throw e;
+        }
+        LOG.error("Failed to scrub pipeline {}", id, e);
+      } catch (IOException e) {
+        LOG.error("Failed to scrub pipeline {}", id, e);
       }
     }
+
+    if (closedPipelines) {
+      notifyPipelineCreatorOfClosedPipelines();
+    }
+  }
+
+  /**
+   * Closed pipelines free up the pipeline limit on their nodes, so let the
+   * creator check for replacements now instead of waiting for its next run.
+   * Pipelines which were only deleted had already been closed.
+   */
+  private void notifyPipelineCreatorOfClosedPipelines() {
+    if (backgroundPipelineCreator != null) {
+      
backgroundPipelineCreator.notifyEventTriggered(Event.SCRUBBER_CLOSED_PIPELINES);
+    }
   }
 
   /**
    * @param pipeline The pipeline to check
+   * @param nodeManager The node manager holding the registered nodes
    * @return True if the pipeline is open and contains unregistered nodes. 
False
    *         otherwise.
    */
-  private boolean isOpenWithUnregisteredNodes(Pipeline pipeline) {
+  public static boolean isOpenWithUnregisteredNodes(Pipeline pipeline, 
NodeManager nodeManager) {
     if (!pipeline.isOpen()) {
       return false;
     }
     for (DatanodeDetails dn : pipeline.getNodes()) {
-      if (nodeManager.getNode(dn.getID()) == null) {
+      if (!nodeManager.isNodeRegistered(dn)) {
         return true;
       }
     }
@@ -893,7 +929,8 @@ public SCMHAManager getScmhaManager() {
     return scmhaManager;
   }
 
-  private void setBackgroundPipelineCreator(
+  @VisibleForTesting
+  void setBackgroundPipelineCreator(
       BackgroundPipelineCreator backgroundPipelineCreator) {
     this.backgroundPipelineCreator = backgroundPipelineCreator;
   }
@@ -904,12 +941,12 @@ public BackgroundPipelineCreator 
getBackgroundPipelineCreator() {
   }
 
   private void setBackgroundPipelineScrubber(
-      BackgroundSCMService backgroundPipelineScrubber) {
+      BackgroundPipelineScrubber backgroundPipelineScrubber) {
     this.backgroundPipelineScrubber = backgroundPipelineScrubber;
   }
 
   @VisibleForTesting
-  public BackgroundSCMService getBackgroundPipelineScrubber() {
+  public BackgroundPipelineScrubber getBackgroundPipelineScrubber() {
     return this.backgroundPipelineScrubber;
   }
 
diff --git 
a/hadoop-hdds/server-scm/src/main/java/org/apache/hadoop/hdds/scm/pipeline/SCMPipelineMetrics.java
 
b/hadoop-hdds/server-scm/src/main/java/org/apache/hadoop/hdds/scm/pipeline/SCMPipelineMetrics.java
index 187d4be74b6..527f62b3854 100644
--- 
a/hadoop-hdds/server-scm/src/main/java/org/apache/hadoop/hdds/scm/pipeline/SCMPipelineMetrics.java
+++ 
b/hadoop-hdds/server-scm/src/main/java/org/apache/hadoop/hdds/scm/pipeline/SCMPipelineMetrics.java
@@ -53,6 +53,7 @@ public final class SCMPipelineMetrics implements 
MetricsSource {
   private @Metric MutableCounterLong numPipelineCreationFailed;
   private @Metric MutableCounterLong numPipelineDestroyed;
   private @Metric MutableCounterLong numPipelineDestroyFailed;
+  private @Metric MutableCounterLong numPipelineCloseFailed;
   private @Metric MutableCounterLong numPipelineReportProcessed;
   private @Metric MutableCounterLong numPipelineReportProcessingFailed;
   private @Metric MutableCounterLong numPipelineContainSameDatanodes;
@@ -98,6 +99,7 @@ public void getMetrics(MetricsCollector collector, boolean 
all) {
     numPipelineCreationFailed.snapshot(recordBuilder, true);
     numPipelineDestroyed.snapshot(recordBuilder, true);
     numPipelineDestroyFailed.snapshot(recordBuilder, true);
+    numPipelineCloseFailed.snapshot(recordBuilder, true);
     numPipelineReportProcessed.snapshot(recordBuilder, true);
     numPipelineReportProcessingFailed.snapshot(recordBuilder, true);
     numPipelineContainSameDatanodes.snapshot(recordBuilder, true);
@@ -165,6 +167,13 @@ void incNumPipelineDestroyFailed() {
     numPipelineDestroyFailed.incr();
   }
 
+  /**
+   * Increments number of failed pipeline close count.
+   */
+  void incNumPipelineCloseFailed() {
+    numPipelineCloseFailed.incr();
+  }
+
   /**
    * Increments number of pipeline report processed count.
    */
diff --git 
a/hadoop-hdds/server-scm/src/main/java/org/apache/hadoop/hdds/scm/safemode/HealthyPipelineSafeModeRule.java
 
b/hadoop-hdds/server-scm/src/main/java/org/apache/hadoop/hdds/scm/safemode/HealthyPipelineSafeModeRule.java
index 038314cee75..4a28d622f26 100644
--- 
a/hadoop-hdds/server-scm/src/main/java/org/apache/hadoop/hdds/scm/safemode/HealthyPipelineSafeModeRule.java
+++ 
b/hadoop-hdds/server-scm/src/main/java/org/apache/hadoop/hdds/scm/safemode/HealthyPipelineSafeModeRule.java
@@ -33,12 +33,14 @@
 import org.apache.hadoop.hdds.protocol.proto.HddsProtos;
 import org.apache.hadoop.hdds.protocol.proto.HddsProtos.ReplicationFactor;
 import org.apache.hadoop.hdds.scm.events.SCMEvents;
+import org.apache.hadoop.hdds.scm.ha.SCMContext;
 import org.apache.hadoop.hdds.scm.node.NodeManager;
 import org.apache.hadoop.hdds.scm.node.NodeStatus;
 import org.apache.hadoop.hdds.scm.node.states.NodeNotFoundException;
 import org.apache.hadoop.hdds.scm.pipeline.Pipeline;
 import org.apache.hadoop.hdds.scm.pipeline.PipelineID;
 import org.apache.hadoop.hdds.scm.pipeline.PipelineManager;
+import org.apache.hadoop.hdds.scm.pipeline.PipelineManagerImpl;
 import org.apache.hadoop.hdds.server.events.EventQueue;
 import org.apache.hadoop.hdds.server.events.TypedEvent;
 import org.slf4j.Logger;
@@ -50,6 +52,13 @@
  * This rule defines percentage of healthy pipelines need to be reported.
  * Once safe mode exit happens, this rules take care of writes can go
  * through in a cluster.
+ *
+ * The rule also requires that no open pipeline of any replication type has a
+ * datanode which is not registered with SCM, so that unregistered datanodes 
are
+ * not handed out for reads or writes after safe mode exit. Such pipelines are
+ * closed by the pipeline scrubber on the leader SCM while it is in safe mode,
+ * so followers wait for the leader to close them. This check applies even when
+ * the RATIS/THREE healthy pipeline threshold is disabled.
  */
 public class HealthyPipelineSafeModeRule extends SafeModeExitRule<Pipeline> {
 
@@ -64,19 +73,25 @@ public class HealthyPipelineSafeModeRule extends 
SafeModeExitRule<Pipeline> {
   private final int minHealthyPipelines;
   private final Set<PipelineID> unProcessedPipelineSet = new HashSet<>();
   private final NodeManager nodeManager;
+  private final SCMContext scmContext;
   private final RatisReplicationConfig targetReplicationConfig =
       RatisReplicationConfig.getInstance(ReplicationFactor.THREE);
   private final int targetRequiredNodes =
       HddsProtos.ReplicationFactor.THREE_VALUE;
   private final String targetReplicationLabel =
       targetReplicationConfig.configFormat();
+  // Whether the RATIS/THREE healthy pipeline threshold applies.
+  private final boolean ratisThreeRuleEnabled;
 
   HealthyPipelineSafeModeRule(EventQueue eventQueue,
       PipelineManager pipelineManager, SCMSafeModeManager manager,
-      ConfigurationSource configuration, NodeManager nodeManager) {
+      ConfigurationSource configuration, NodeManager nodeManager, SCMContext 
scmContext,
+      boolean ratisThreeRuleEnabled) {
     super(manager, eventQueue);
     this.pipelineManager = pipelineManager;
     this.nodeManager = nodeManager;
+    this.scmContext = scmContext;
+    this.ratisThreeRuleEnabled = ratisThreeRuleEnabled;
     healthyPipelinesPercent =
         configuration.getDouble(HddsConfigKeys.
                 HDDS_SCM_SAFEMODE_HEALTHY_PIPELINE_THRESHOLD_PCT,
@@ -117,10 +132,32 @@ protected TypedEvent<Pipeline> getEventType() {
 
   @Override
   protected synchronized boolean validate() {
-    if (!validateBasedOnReportProcessing()) {
-      return validateHealthyPipelineSafeModeRuleUsingPipelineManager();
+    return validateRatisThreePipelines() && 
getOpenPipelinesWithUnregisteredNodes(1).isEmpty();
+  }
+
+  /**
+   * @return True if the RATIS/THREE healthy pipeline threshold is met or 
disabled.
+   */
+  private synchronized boolean validateRatisThreePipelines() {
+    if (!ratisThreeRuleEnabled) {
+      return true;
     }
-    return currentHealthyPipelineCount >= healthyPipelineThresholdCount;
+    if (validateBasedOnReportProcessing()) {
+      return currentHealthyPipelineCount >= healthyPipelineThresholdCount;
+    }
+    return validateHealthyPipelineSafeModeRuleUsingPipelineManager();
+  }
+
+  /**
+   * @param limit The maximum number of pipelines to return
+   * @return IDs of open pipelines of any replication type which have a 
datanode that is not registered with SCM.
+   */
+  private List<PipelineID> getOpenPipelinesWithUnregisteredNodes(int limit) {
+    return pipelineManager.getPipelines().stream()
+        .filter(p -> PipelineManagerImpl.isOpenWithUnregisteredNodes(p, 
nodeManager))
+        .map(Pipeline::getId)
+        .limit(limit)
+        .collect(Collectors.toList());
   }
 
   @Override
@@ -146,7 +183,7 @@ protected synchronized void process(Pipeline pipeline) {
 
     // Skip already processed ones.
     if (processedPipelineIDs.contains(pipeline.getId())) {
-      LOG.info("Skipping pipeline safemode report processing check as 
pipeline: {} is already recorded.",
+      LOG.debug("Skipping pipeline safemode report processing check as 
pipeline: {} is already recorded.",
           pipeline.getId());
       return;
     }
@@ -202,13 +239,19 @@ public synchronized void refresh(boolean forceRefresh) {
     if (forceRefresh) {
       initializeRule(true);
     } else {
-      if (!validate()) {
+      // Only the RATIS/THREE threshold depends on the rule's initialized 
state. Open pipelines with unregistered
+      // datanodes are checked against the current pipelines on each 
validation.
+      if (!validateRatisThreePipelines()) {
         initializeRule(true);
       }
     }
   }
 
   private synchronized void initializeRule(boolean refresh) {
+    if (!ratisThreeRuleEnabled) {
+      healthyPipelineThresholdCount = 0;
+      return;
+    }
     unProcessedPipelineSet.addAll(pipelineManager.getPipelines(
             targetReplicationConfig,
             Pipeline.PipelineState.OPEN).stream().map(Pipeline::getId)
@@ -307,15 +350,35 @@ public synchronized int 
getHealthyPipelineThresholdCount() {
 
   @Override
   public String getStatusText() {
-    String status = String.format(
-        "healthy %s pipelines (=%d) >= healthyPipelineThresholdCount" +
-            " (=%d)", targetReplicationLabel,
-        getCurrentHealthyPipelineCount(),
-        getHealthyPipelineThresholdCount());
-    status = updateStatusTextWithSamplePipelines(status);
+    String status = "";
+    if (ratisThreeRuleEnabled) {
+      status = String.format(
+          "healthy %s pipelines (=%d) >= healthyPipelineThresholdCount" +
+              " (=%d)", targetReplicationLabel,
+          getCurrentHealthyPipelineCount(),
+          getHealthyPipelineThresholdCount());
+      status = updateStatusTextWithSamplePipelines(status).concat("\n");
+    }
+    List<PipelineID> unregisteredNodePipelines = 
getOpenPipelinesWithUnregisteredNodes(Integer.MAX_VALUE);
+    status = status.concat(String.format("open pipelines with unregistered 
datanodes (=%d) == 0",
+        unregisteredNodePipelines.size()));
+    if (!unregisteredNodePipelines.isEmpty()) {
+      // Only the leader's pipeline scrubber closes these pipelines.
+      if (!scmContext.isLeader()) {
+        status = status.concat("\nWaiting for the leader SCM to close the 
pipelines with unregistered datanodes");
+      }
+      status = status.concat("\nSample pipelines with unregistered datanodes : 
"
+          + unregisteredNodePipelines.subList(0, 
Math.min(SAMPLE_PIPELINE_DISPLAY_LIMIT,
+          unregisteredNodePipelines.size())));
+    }
     return status;
   }
 
+  @VisibleForTesting
+  boolean isRatisThreeRuleEnabled() {
+    return ratisThreeRuleEnabled;
+  }
+
   private synchronized String updateStatusTextWithSamplePipelines(
       String status) {
     if (validateBasedOnReportProcessing()) {
diff --git 
a/hadoop-hdds/server-scm/src/main/java/org/apache/hadoop/hdds/scm/safemode/SCMSafeModeManager.java
 
b/hadoop-hdds/server-scm/src/main/java/org/apache/hadoop/hdds/scm/safemode/SCMSafeModeManager.java
index fff90db4a1d..82c93032c1c 100644
--- 
a/hadoop-hdds/server-scm/src/main/java/org/apache/hadoop/hdds/scm/safemode/SCMSafeModeManager.java
+++ 
b/hadoop-hdds/server-scm/src/main/java/org/apache/hadoop/hdds/scm/safemode/SCMSafeModeManager.java
@@ -85,6 +85,7 @@ public class SCMSafeModeManager implements SafeModeManager {
   private final Set<String> preCheckRules = new HashSet<>();
   private final Set<String> validatedRules = new HashSet<>();
   private final Set<String> validatedPreCheckRules = new HashSet<>();
+  private boolean containerRulesValidated = false;
 
   private final SCMServiceManager serviceManager;
   private final SCMContext scmContext;
@@ -203,6 +204,16 @@ public synchronized void validateSafeModeExitRules(String 
ruleName) {
       LOG.error("No Such Exit rule {}", ruleName);
     }
 
+    // Once all container rules have been validated, notify the services that 
are
+    // allowed to start in safe mode at that point, such as the pipeline 
scrubber.
+    if (!containerRulesValidated && exitRules.values().stream()
+        .filter(rule -> rule instanceof AbstractContainerSafeModeRule)
+        .allMatch(rule -> validatedRules.contains(rule.getRuleName()))) {
+      containerRulesValidated = true;
+      LOG.info("All SCM safe mode container rules have passed");
+      
serviceManager.notifyEventTriggered(Event.CONTAINER_SAFE_MODE_RULES_VALIDATED);
+    }
+
     // If all the precheck rules have been validated, set status to 
PRE_CHECKS_PASSED
     // and notify listeners.
     if (validatedPreCheckRules.size() == preCheckRules.size()
diff --git 
a/hadoop-hdds/server-scm/src/main/java/org/apache/hadoop/hdds/scm/safemode/SafeModeRuleFactory.java
 
b/hadoop-hdds/server-scm/src/main/java/org/apache/hadoop/hdds/scm/safemode/SafeModeRuleFactory.java
index 6b3ca407fc5..b5c30ef6ca8 100644
--- 
a/hadoop-hdds/server-scm/src/main/java/org/apache/hadoop/hdds/scm/safemode/SafeModeRuleFactory.java
+++ 
b/hadoop-hdds/server-scm/src/main/java/org/apache/hadoop/hdds/scm/safemode/SafeModeRuleFactory.java
@@ -99,9 +99,11 @@ private void loadRules(SCMSafeModeManager safeModeManager) {
     }
 
     if (pipelineManager != null) {
-      if (shouldEnableRatisThreePipelineRules()) {
-        safeModeRules.add(new HealthyPipelineSafeModeRule(eventQueue,
-            pipelineManager, safeModeManager, config, nodeManager));
+      final boolean ratisThreePipelineRulesEnabled = 
shouldEnableRatisThreePipelineRules();
+      // Always added, as it also checks that no open pipeline of any type has 
unregistered datanodes.
+      safeModeRules.add(new HealthyPipelineSafeModeRule(eventQueue,
+          pipelineManager, safeModeManager, config, nodeManager, scmContext, 
ratisThreePipelineRulesEnabled));
+      if (ratisThreePipelineRulesEnabled) {
         safeModeRules.add(new OneReplicaPipelineSafeModeRule(eventQueue, 
pipelineManager,
             safeModeManager, config));
       } else {
diff --git 
a/hadoop-hdds/server-scm/src/test/java/org/apache/hadoop/hdds/scm/container/MockNodeManager.java
 
b/hadoop-hdds/server-scm/src/test/java/org/apache/hadoop/hdds/scm/container/MockNodeManager.java
index 8111abb6e9b..561e1b52126 100644
--- 
a/hadoop-hdds/server-scm/src/test/java/org/apache/hadoop/hdds/scm/container/MockNodeManager.java
+++ 
b/hadoop-hdds/server-scm/src/test/java/org/apache/hadoop/hdds/scm/container/MockNodeManager.java
@@ -843,7 +843,8 @@ public List<SCMCommand<?>> processHeartbeat(DatanodeDetails 
datanodeDetails,
   @Override
   public Boolean isNodeRegistered(
       DatanodeDetails datanodeDetails) {
-    return healthyNodes.contains(datanodeDetails);
+    // Registered nodes are added to the cluster map regardless of their 
health.
+    return getNode(datanodeDetails.getID()) != null;
   }
 
   @Override
diff --git 
a/hadoop-hdds/server-scm/src/test/java/org/apache/hadoop/hdds/scm/pipeline/TestBackgroundPipelineCreator.java
 
b/hadoop-hdds/server-scm/src/test/java/org/apache/hadoop/hdds/scm/pipeline/TestBackgroundPipelineCreator.java
index e297266cc28..86ad8f2bcb6 100644
--- 
a/hadoop-hdds/server-scm/src/test/java/org/apache/hadoop/hdds/scm/pipeline/TestBackgroundPipelineCreator.java
+++ 
b/hadoop-hdds/server-scm/src/test/java/org/apache/hadoop/hdds/scm/pipeline/TestBackgroundPipelineCreator.java
@@ -21,15 +21,18 @@
 import static org.junit.jupiter.api.Assertions.assertFalse;
 import static org.junit.jupiter.api.Assertions.assertTrue;
 import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.when;
 
 import java.time.Clock;
 import java.util.List;
+import org.apache.hadoop.hdds.HddsConfigKeys;
 import org.apache.hadoop.hdds.client.RatisReplicationConfig;
 import org.apache.hadoop.hdds.client.ReplicationConfig;
 import org.apache.hadoop.hdds.conf.OzoneConfiguration;
 import org.apache.hadoop.hdds.protocol.proto.HddsProtos;
 import org.apache.hadoop.hdds.scm.ScmConfigKeys;
 import org.apache.hadoop.hdds.scm.ha.SCMContext;
+import org.apache.hadoop.hdds.scm.ha.SCMService.Event;
 import org.apache.hadoop.ozone.OzoneConfigKeys;
 import org.junit.jupiter.api.Test;
 
@@ -113,4 +116,27 @@ public void 
testInvalidDefaultReplicationConfigCreatesNoPipelines() {
     assertTrue(configs.isEmpty());
   }
 
+  @Test
+  public void testScrubberClosedPipelinesTriggerOneShotRunInSafeMode() {
+    OzoneConfiguration conf = new OzoneConfiguration();
+    // The one-shot run should trigger pipeline creation even if background 
creation is disabled in safemode.
+    conf.setBoolean(HddsConfigKeys.HDDS_SCM_SAFEMODE_PIPELINE_CREATION, false);
+    SCMContext scmContext = mock(SCMContext.class);
+    when(scmContext.isLeader()).thenReturn(true);
+    when(scmContext.isLeaderReady()).thenReturn(true);
+    when(scmContext.isInSafeMode()).thenReturn(true);
+
+    BackgroundPipelineCreator creator = new BackgroundPipelineCreator(
+        mock(PipelineManager.class), conf, scmContext, Clock.systemUTC());
+    creator.notifyStatusChanged();
+    // Since creation in safemode is disabled outside of one-shot runs, this 
should not trigger a run.
+    assertFalse(creator.shouldRun());
+
+    // A relevant event should trigger a one-shot run.
+    creator.notifyEventTriggered(Event.SCRUBBER_CLOSED_PIPELINES);
+    assertTrue(creator.shouldRun());
+    // The one-shot run is consumed.
+    assertFalse(creator.shouldRun());
+  }
+
 }
diff --git 
a/hadoop-hdds/server-scm/src/test/java/org/apache/hadoop/hdds/scm/pipeline/TestBackgroundPipelineScrubber.java
 
b/hadoop-hdds/server-scm/src/test/java/org/apache/hadoop/hdds/scm/pipeline/TestBackgroundPipelineScrubber.java
new file mode 100644
index 00000000000..6e2b6286f30
--- /dev/null
+++ 
b/hadoop-hdds/server-scm/src/test/java/org/apache/hadoop/hdds/scm/pipeline/TestBackgroundPipelineScrubber.java
@@ -0,0 +1,170 @@
+/*
+ * 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.pipeline;
+
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.mockito.Mockito.mock;
+
+import java.time.Instant;
+import java.time.ZoneOffset;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicInteger;
+import org.apache.hadoop.hdds.conf.OzoneConfiguration;
+import org.apache.hadoop.hdds.scm.ScmConfigKeys;
+import org.apache.hadoop.hdds.scm.ha.SCMContext;
+import org.apache.hadoop.hdds.scm.ha.SCMService.Event;
+import org.apache.hadoop.hdds.scm.safemode.SCMSafeModeManager.SafeModeStatus;
+import org.apache.hadoop.hdds.scm.server.OzoneStorageContainerManager;
+import org.apache.hadoop.hdds.utils.HddsServerUtil;
+import org.apache.ozone.test.GenericTestUtils;
+import org.apache.ozone.test.MockClock;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+
+/**
+ * Tests for BackgroundPipelineScrubber.
+ */
+public class TestBackgroundPipelineScrubber {
+  private OzoneConfiguration conf;
+  private MockClock clock;
+  private final AtomicInteger scrubCount = new AtomicInteger();
+  private BackgroundPipelineScrubber scrubber;
+
+  @BeforeEach
+  public void setup() {
+    conf = new OzoneConfiguration();
+    // The interval is long enough that the task only runs if the service is 
woken up.
+    conf.setTimeDuration(ScmConfigKeys.OZONE_SCM_PIPELINE_SCRUB_INTERVAL, 1, 
TimeUnit.HOURS);
+    clock = new MockClock(Instant.now(), ZoneOffset.UTC);
+  }
+
+  @AfterEach
+  public void teardown() {
+    if (scrubber != null) {
+      scrubber.stop();
+    }
+  }
+
+  @Test
+  public void testRunsInSafeModeWhenEventArrivesBeforeDelay() {
+    SCMContext scmContext = SCMContext.emptyContext();
+    scmContext.updateSafeModeStatus(SafeModeStatus.PRE_CHECKS_PASSED);
+    scrubber = newScrubber(scmContext);
+
+    // In safe mode the service does not run without the event.
+    scrubber.notifyStatusChanged();
+    assertFalse(scrubber.shouldRun());
+    scrubber.notifyEventTriggered(Event.PRE_CHECK_COMPLETED);
+    assertFalse(scrubber.shouldRun());
+
+    // After the event, it still waits for the stale node interval since it 
was created.
+    scrubber.notifyEventTriggered(Event.CONTAINER_SAFE_MODE_RULES_VALIDATED);
+    assertFalse(scrubber.shouldRun());
+    clock.fastForward(HddsServerUtil.getStaleNodeInterval(conf));
+    assertTrue(scrubber.shouldRun());
+
+    // Exiting safe mode does not add another wait.
+    scmContext.updateSafeModeStatus(SafeModeStatus.OUT_OF_SAFE_MODE);
+    scrubber.notifyStatusChanged();
+    assertTrue(scrubber.shouldRun());
+  }
+
+  @Test
+  public void testRunsInSafeModeWhenEventArrivesAfterDelay() {
+    SCMContext scmContext = SCMContext.emptyContext();
+    scmContext.updateSafeModeStatus(SafeModeStatus.PRE_CHECKS_PASSED);
+    scrubber = newScrubber(scmContext);
+    scrubber.notifyStatusChanged();
+
+    // The stale node interval elapsing alone does not let the service run in 
safe mode.
+    clock.fastForward(HddsServerUtil.getStaleNodeInterval(conf));
+    assertFalse(scrubber.shouldRun());
+
+    // Once the container safe mode rules pass, it runs without any further 
wait.
+    scrubber.notifyEventTriggered(Event.CONTAINER_SAFE_MODE_RULES_VALIDATED);
+    assertTrue(scrubber.shouldRun());
+  }
+
+  @Test
+  public void testRunsImmediatelyOutOfSafeMode() {
+    SCMContext scmContext = SCMContext.emptyContext();
+    scmContext.updateSafeModeStatus(SafeModeStatus.PRE_CHECKS_PASSED);
+    scrubber = newScrubber(scmContext);
+    scrubber.notifyStatusChanged();
+    assertFalse(scrubber.shouldRun());
+
+    // A forced safe mode exit before the event or delay lets the service run 
right away.
+    scmContext.updateSafeModeStatus(SafeModeStatus.OUT_OF_SAFE_MODE);
+    scrubber.notifyStatusChanged();
+    assertTrue(scrubber.shouldRun());
+
+    // Going back into safe mode pauses the service.
+    scmContext.updateSafeModeStatus(SafeModeStatus.PRE_CHECKS_PASSED);
+    scrubber.notifyStatusChanged();
+    assertFalse(scrubber.shouldRun());
+  }
+
+  @Test
+  public void testEventSurvivesLeaderChange() {
+    SCMContext scmContext = new SCMContext.Builder()
+        .setLeader(false)
+        .setTerm(1)
+        .setSafeModeStatus(SafeModeStatus.PRE_CHECKS_PASSED)
+        .setSCM(mock(OzoneStorageContainerManager.class))
+        .build();
+    scrubber = newScrubber(scmContext);
+    clock.fastForward(HddsServerUtil.getStaleNodeInterval(conf));
+
+    // The event arrives while this SCM is a follower.
+    scrubber.notifyEventTriggered(Event.CONTAINER_SAFE_MODE_RULES_VALIDATED);
+    assertFalse(scrubber.shouldRun());
+
+    scmContext.updateLeaderAndTerm(true, 2);
+    scmContext.setLeaderReady();
+    scrubber.notifyStatusChanged();
+    assertTrue(scrubber.shouldRun());
+  }
+
+  @Test
+  public void testWakesUpWithoutWaitingForInterval() throws Exception {
+    SCMContext scmContext = SCMContext.emptyContext();
+    scmContext.updateSafeModeStatus(SafeModeStatus.PRE_CHECKS_PASSED);
+    scrubber = newScrubber(scmContext);
+    scrubber.start();
+    clock.fastForward(HddsServerUtil.getStaleNodeInterval(conf));
+
+    scrubber.notifyStatusChanged();
+    scrubber.notifyEventTriggered(Event.CONTAINER_SAFE_MODE_RULES_VALIDATED);
+    GenericTestUtils.waitFor(() -> scrubCount.get() > 0, 100, 3000);
+  }
+
+  @Test
+  public void testStop() {
+    scrubber = newScrubber(SCMContext.emptyContext());
+    scrubber.start();
+    assertTrue(scrubber.isRunning());
+    scrubber.stop();
+    assertFalse(scrubber.isRunning());
+  }
+
+  private BackgroundPipelineScrubber newScrubber(SCMContext scmContext) {
+    return new BackgroundPipelineScrubber(scrubCount::incrementAndGet, conf, 
scmContext, clock);
+  }
+}
diff --git 
a/hadoop-hdds/server-scm/src/test/java/org/apache/hadoop/hdds/scm/pipeline/TestPipelineManagerImpl.java
 
b/hadoop-hdds/server-scm/src/test/java/org/apache/hadoop/hdds/scm/pipeline/TestPipelineManagerImpl.java
index 3e46dd24380..b49e9702de7 100644
--- 
a/hadoop-hdds/server-scm/src/test/java/org/apache/hadoop/hdds/scm/pipeline/TestPipelineManagerImpl.java
+++ 
b/hadoop-hdds/server-scm/src/test/java/org/apache/hadoop/hdds/scm/pipeline/TestPipelineManagerImpl.java
@@ -45,6 +45,7 @@
 import static org.mockito.Mockito.doThrow;
 import static org.mockito.Mockito.eq;
 import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.never;
 import static org.mockito.Mockito.spy;
 import static org.mockito.Mockito.times;
 import static org.mockito.Mockito.verify;
@@ -55,6 +56,7 @@
 import java.time.Instant;
 import java.time.ZoneOffset;
 import java.util.ArrayList;
+import java.util.Arrays;
 import java.util.Collection;
 import java.util.Collections;
 import java.util.HashSet;
@@ -87,6 +89,7 @@
 import org.apache.hadoop.hdds.scm.ha.SCMHADBTransactionBuffer;
 import org.apache.hadoop.hdds.scm.ha.SCMHADBTransactionBufferStub;
 import org.apache.hadoop.hdds.scm.ha.SCMHAManagerStub;
+import org.apache.hadoop.hdds.scm.ha.SCMService.Event;
 import org.apache.hadoop.hdds.scm.ha.SCMServiceManager;
 import org.apache.hadoop.hdds.scm.metadata.SCMDBDefinition;
 import org.apache.hadoop.hdds.scm.node.DatanodeInfo;
@@ -595,6 +598,73 @@ public void testScrubOpenWithUnregisteredNodes() throws 
Exception {
         pipeline.getPipelineState());
   }
 
+  @Test
+  public void testScrubContinuesAfterPipelineFailure() throws Exception {
+    PipelineManagerImpl pipelineManager = createPipelineManager(true);
+    BackgroundPipelineCreator creator = 
mockBackgroundPipelineCreator(pipelineManager);
+    for (int i = 0; i < 2; i++) {
+      Pipeline pipeline = pipelineManager.createPipeline(new 
ECReplicationConfig(3, 2));
+      pipelineManager.openPipeline(pipeline.getId());
+    }
+    // scrubPipelines iterates in this order, so the failing pipeline comes 
before the one that should be scrubbed.
+    List<Pipeline> pipelines = pipelineManager.getPipelines();
+    assertEquals(2, pipelines.size());
+    Pipeline failingPipeline = pipelines.get(0);
+    Pipeline otherPipeline = pipelines.get(1);
+
+    // "Unregister" a node from each pipeline.
+    for (Pipeline p : Arrays.asList(failingPipeline, otherPipeline)) {
+      DatanodeDetails dn = nodeManager.getNode(p.getNodes().get(0).getID());
+      if (dn != null) {
+        nodeManager.getClusterNetworkTopologyMap().remove(dn);
+      }
+    }
+    // Closing the pipeline fails because SCM does not know about its 
container.
+    pipelineManager.addContainerToPipeline(failingPipeline.getId(), 
ContainerID.valueOf(1));
+    long numPipelineCloseFailed = getLongCounter("NumPipelineCloseFailed",
+        getMetrics(SCMPipelineMetrics.class.getSimpleName()));
+
+    pipelineManager.scrubPipelines();
+
+    // The failure on one pipeline does not stop the other from being scrubbed.
+    assertEquals(OPEN, 
pipelineManager.getPipeline(failingPipeline.getId()).getPipelineState());
+    assertEquals(Pipeline.PipelineState.CLOSED, 
pipelineManager.getPipeline(otherPipeline.getId()).getPipelineState());
+    assertEquals(numPipelineCloseFailed + 1, 
getLongCounter("NumPipelineCloseFailed",
+        getMetrics(SCMPipelineMetrics.class.getSimpleName())));
+    // Replacement pipelines are requested after the scrubber closes pipelines.
+    verify(creator).notifyEventTriggered(Event.SCRUBBER_CLOSED_PIPELINES);
+    pipelineManager.close();
+  }
+
+  @Test
+  public void testScrubOnlyDeletingClosedPipelinesDoesNotTriggerCreator() 
throws Exception {
+    conf.setTimeDuration(OZONE_SCM_PIPELINE_DESTROY_TIMEOUT, 50, 
TimeUnit.SECONDS);
+    PipelineManagerImpl pipelineManager = createPipelineManager(true);
+    BackgroundPipelineCreator creator = 
mockBackgroundPipelineCreator(pipelineManager);
+    Pipeline pipeline = 
pipelineManager.createPipeline(RatisReplicationConfig.getInstance(ReplicationFactor.THREE));
+    pipelineManager.openPipeline(pipeline.getId());
+    pipelineManager.closePipeline(pipeline.getId());
+    testClock.set(Instant.now());
+    testClock.fastForward(60000);
+
+    pipelineManager.scrubPipelines();
+
+    // Deleting an already closed pipeline does not free up any pipeline limit.
+    assertFalse(pipelineManager.containsPipeline(pipeline.getId()));
+    verify(creator, 
never()).notifyEventTriggered(Event.SCRUBBER_CLOSED_PIPELINES);
+    pipelineManager.close();
+  }
+
+  /**
+   * Replaces the pipeline manager's background pipeline creator with a mock, 
after stopping the real one.
+   */
+  private BackgroundPipelineCreator 
mockBackgroundPipelineCreator(PipelineManagerImpl pipelineManager) {
+    pipelineManager.getBackgroundPipelineCreator().stop();
+    BackgroundPipelineCreator creator = mock(BackgroundPipelineCreator.class);
+    pipelineManager.setBackgroundPipelineCreator(creator);
+    return creator;
+  }
+
   @Test
   public void testScrubPipelinesShouldFailOnFollower() throws Exception {
     conf.setTimeDuration(
diff --git 
a/hadoop-hdds/server-scm/src/test/java/org/apache/hadoop/hdds/scm/safemode/TestHealthyPipelineSafeModeRule.java
 
b/hadoop-hdds/server-scm/src/test/java/org/apache/hadoop/hdds/scm/safemode/TestHealthyPipelineSafeModeRule.java
index b1312512d56..7baca270e33 100644
--- 
a/hadoop-hdds/server-scm/src/test/java/org/apache/hadoop/hdds/scm/safemode/TestHealthyPipelineSafeModeRule.java
+++ 
b/hadoop-hdds/server-scm/src/test/java/org/apache/hadoop/hdds/scm/safemode/TestHealthyPipelineSafeModeRule.java
@@ -17,6 +17,7 @@
 
 package org.apache.hadoop.hdds.scm.safemode;
 
+import static org.assertj.core.api.Assertions.assertThat;
 import static org.junit.jupiter.api.Assertions.assertEquals;
 import static org.junit.jupiter.api.Assertions.assertFalse;
 import static org.junit.jupiter.api.Assertions.assertTrue;
@@ -27,17 +28,23 @@
 import java.time.Clock;
 import java.time.ZoneOffset;
 import java.util.ArrayList;
+import java.util.Arrays;
 import java.util.List;
+import java.util.stream.Stream;
 import org.apache.hadoop.hdds.HddsConfigKeys;
+import org.apache.hadoop.hdds.client.ECReplicationConfig;
 import org.apache.hadoop.hdds.client.RatisReplicationConfig;
+import org.apache.hadoop.hdds.client.ReplicationConfig;
 import org.apache.hadoop.hdds.conf.OzoneConfiguration;
 import org.apache.hadoop.hdds.protocol.DatanodeDetails;
 import org.apache.hadoop.hdds.protocol.proto.HddsProtos;
 import org.apache.hadoop.hdds.protocol.proto.HddsProtos.ReplicationFactor;
 import org.apache.hadoop.hdds.scm.HddsTestUtils;
+import org.apache.hadoop.hdds.scm.ScmConfigKeys;
 import org.apache.hadoop.hdds.scm.container.ContainerInfo;
 import org.apache.hadoop.hdds.scm.container.ContainerManager;
 import org.apache.hadoop.hdds.scm.container.MockNodeManager;
+import 
org.apache.hadoop.hdds.scm.container.placement.algorithms.SCMContainerPlacementRandom;
 import org.apache.hadoop.hdds.scm.events.SCMEvents;
 import org.apache.hadoop.hdds.scm.ha.SCMContext;
 import org.apache.hadoop.hdds.scm.ha.SCMHAManagerStub;
@@ -49,10 +56,14 @@
 import org.apache.hadoop.hdds.scm.pipeline.PipelineManagerImpl;
 import org.apache.hadoop.hdds.scm.pipeline.PipelineProvider;
 import org.apache.hadoop.hdds.server.events.EventQueue;
+import org.apache.hadoop.ozone.OzoneConfigKeys;
 import org.apache.ozone.test.GenericTestUtils;
 import org.apache.ozone.test.GenericTestUtils.LogCapturer;
 import org.junit.jupiter.api.Test;
 import org.junit.jupiter.api.io.TempDir;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.MethodSource;
+import org.junit.jupiter.params.provider.ValueSource;
 
 /**
  * This class tests HealthyPipelineSafeMode rule.
@@ -480,6 +491,171 @@ public void testPipelineIgnoredWhenDnIsUnhealthy() throws 
Exception {
     }
   }
 
+  private static Stream<ReplicationConfig> unregisteredNodePipelineConfigs() {
+    return Stream.of(
+        new ECReplicationConfig(3, 2),
+        RatisReplicationConfig.getInstance(ReplicationFactor.THREE),
+        RatisReplicationConfig.getInstance(ReplicationFactor.ONE));
+  }
+
+  @ParameterizedTest
+  @MethodSource("unregisteredNodePipelineConfigs")
+  public void 
testOpenPipelinesWithUnregisteredNodesBlockRule(ReplicationConfig 
replicationConfig) throws Exception {
+    EventQueue eventQueue = new EventQueue();
+    SCMServiceManager serviceManager = new SCMServiceManager();
+    SCMContext scmContext = SCMContext.emptyContext();
+    List<ContainerInfo> containers = new 
ArrayList<>(HddsTestUtils.getContainerInfo(1));
+
+    OzoneConfiguration config = new OzoneConfiguration();
+    MockNodeManager nodeManager = new MockNodeManager(true, 12);
+    ContainerManager containerManager = mock(ContainerManager.class);
+    when(containerManager.getContainers()).thenReturn(containers);
+    config.set(HddsConfigKeys.OZONE_METADATA_DIRS, tempFile.getPath());
+    config.setBoolean(HddsConfigKeys.HDDS_SCM_SAFEMODE_PIPELINE_CREATION, 
false);
+    // With at most 2 open RATIS/THREE pipelines, the threshold is max(3 / 3, 
ceil(0.1 * 2)) = 1, so the one healthy
+    // RATIS/THREE pipeline meets it.
+    config.setInt(HddsConfigKeys.HDDS_SCM_SAFEMODE_MIN_DATANODE, 3);
+    
config.setDouble(HddsConfigKeys.HDDS_SCM_SAFEMODE_HEALTHY_PIPELINE_THRESHOLD_PCT,
 0.1);
+    // MockNodeManager does not set up racks for the default EC placement 
policy.
+    config.set(ScmConfigKeys.OZONE_SCM_CONTAINER_PLACEMENT_EC_IMPL_KEY, 
SCMContainerPlacementRandom.class.getName());
+
+    SCMMetadataStore scmMetadataStore = new SCMMetadataStoreImpl(config);
+    try {
+      PipelineManagerImpl pipelineManager =
+          PipelineManagerImpl.newPipelineManager(
+              config,
+              SCMHAManagerStub.getInstance(true),
+              nodeManager,
+              scmMetadataStore.getPipelineTable(),
+              eventQueue,
+              scmContext,
+              serviceManager,
+              Clock.system(ZoneOffset.UTC));
+      PipelineProvider mockRatisProvider =
+          new MockRatisPipelineProvider(nodeManager, 
pipelineManager.getStateManager(), config);
+      pipelineManager.setPipelineProvider(HddsProtos.ReplicationType.RATIS, 
mockRatisProvider);
+
+      Pipeline ratisPipeline = 
pipelineManager.createPipeline(RatisReplicationConfig.getInstance(
+          ReplicationFactor.THREE));
+      pipelineManager.openPipeline(ratisPipeline.getId());
+      ratisPipeline = pipelineManager.getPipeline(ratisPipeline.getId());
+      MockRatisPipelineProvider.markPipelineHealthy(ratisPipeline);
+      Pipeline pipeline = pipelineManager.createPipeline(replicationConfig);
+      pipelineManager.openPipeline(pipeline.getId());
+
+      SCMSafeModeManager scmSafeModeManager = new SCMSafeModeManager(config,
+          nodeManager, pipelineManager, containerManager, serviceManager, 
eventQueue, scmContext);
+      scmSafeModeManager.start();
+
+      HealthyPipelineSafeModeRule rule = SafeModeRuleFactory.getInstance()
+          .getSafeModeRule(HealthyPipelineSafeModeRule.class);
+      firePipelineEvent(ratisPipeline, eventQueue);
+      GenericTestUtils.waitFor(rule::validate, 100, 5000);
+
+      // "Unregister" a node of the pipeline.
+      DatanodeDetails unregisteredNode = 
nodeManager.getNode(pipeline.getNodes().get(0).getID());
+      nodeManager.getClusterNetworkTopologyMap().remove(unregisteredNode);
+      assertFalse(rule.validate());
+      assertThat(rule.getStatusText()).contains("open pipelines with 
unregistered datanodes (=")
+          .contains(pipeline.getId().toString())
+          .doesNotContain("Waiting for the leader SCM");
+
+      // A follower notes that it is waiting for the leader to close the 
pipelines.
+      scmContext.updateLeaderAndTerm(false, 0);
+      assertFalse(rule.validate());
+      assertThat(rule.getStatusText())
+          .contains("Waiting for the leader SCM to close the pipelines with 
unregistered datanodes")
+          .contains(pipeline.getId().toString());
+
+      // Once the node registers again, the rule can pass again.
+      nodeManager.getClusterNetworkTopologyMap().add(unregisteredNode);
+      assertTrue(rule.validate());
+      assertThat(rule.getStatusText()).contains("open pipelines with 
unregistered datanodes (=0)")
+          .doesNotContain("Waiting for the leader SCM");
+    } finally {
+      scmMetadataStore.getStore().close();
+    }
+  }
+
+  @ParameterizedTest
+  @ValueSource(booleans = {true, false})
+  public void 
testEcDefaultWithRatisThreeDisabledOnlyChecksUnregisteredNodes(boolean 
validateBasedOnReportProcessing)
+      throws Exception {
+    EventQueue eventQueue = new EventQueue();
+    SCMServiceManager serviceManager = new SCMServiceManager();
+    SCMContext scmContext = SCMContext.emptyContext();
+    List<ContainerInfo> containers = new 
ArrayList<>(HddsTestUtils.getContainerInfo(1));
+
+    OzoneConfiguration config = new OzoneConfiguration();
+    MockNodeManager nodeManager = new MockNodeManager(true, 12);
+    ContainerManager containerManager = mock(ContainerManager.class);
+    when(containerManager.getContainers()).thenReturn(containers);
+    config.set(HddsConfigKeys.OZONE_METADATA_DIRS, tempFile.getPath());
+    config.setBoolean(HddsConfigKeys.HDDS_SCM_SAFEMODE_PIPELINE_CREATION, 
false);
+    config.set(OzoneConfigKeys.OZONE_REPLICATION_TYPE, 
HddsProtos.ReplicationType.EC.name());
+    config.set(OzoneConfigKeys.OZONE_REPLICATION, "rs-3-2-1024k");
+    config.setBoolean(ScmConfigKeys.OZONE_SCM_PIPELINE_CREATE_RATIS_THREE, 
false);
+    // If the RATIS/THREE threshold were applied, it would require max(30 / 3, 
ceil(0.1 * 1)) = 10 healthy RATIS/THREE
+    // pipelines.
+    config.setInt(HddsConfigKeys.HDDS_SCM_SAFEMODE_MIN_DATANODE, 30);
+    
config.setDouble(HddsConfigKeys.HDDS_SCM_SAFEMODE_HEALTHY_PIPELINE_THRESHOLD_PCT,
 0.1);
+    // MockNodeManager does not set up racks for the default EC placement 
policy.
+    config.set(ScmConfigKeys.OZONE_SCM_CONTAINER_PLACEMENT_EC_IMPL_KEY, 
SCMContainerPlacementRandom.class.getName());
+
+    SCMMetadataStore scmMetadataStore = new SCMMetadataStoreImpl(config);
+    try {
+      PipelineManagerImpl pipelineManager =
+          PipelineManagerImpl.newPipelineManager(
+              config,
+              SCMHAManagerStub.getInstance(true),
+              nodeManager,
+              scmMetadataStore.getPipelineTable(),
+              eventQueue,
+              scmContext,
+              serviceManager,
+              Clock.system(ZoneOffset.UTC));
+      PipelineProvider mockRatisProvider =
+          new MockRatisPipelineProvider(nodeManager, 
pipelineManager.getStateManager(), config);
+      pipelineManager.setPipelineProvider(HddsProtos.ReplicationType.RATIS, 
mockRatisProvider);
+
+      // One open RATIS/THREE pipeline will not be enough to meet the 
threshold for Ratis, but the rule should only
+      // check EC pipelines and node registration.
+      Pipeline ratisPipeline = 
pipelineManager.createPipeline(RatisReplicationConfig.getInstance(
+          ReplicationFactor.THREE));
+      pipelineManager.openPipeline(ratisPipeline.getId());
+      Pipeline ecPipeline = pipelineManager.createPipeline(new 
ECReplicationConfig(3, 2));
+      pipelineManager.openPipeline(ecPipeline.getId());
+
+      SCMSafeModeManager scmSafeModeManager = new SCMSafeModeManager(config,
+          nodeManager, pipelineManager, containerManager, serviceManager, 
eventQueue, scmContext);
+      scmSafeModeManager.start();
+
+      HealthyPipelineSafeModeRule rule = SafeModeRuleFactory.getInstance()
+          .getSafeModeRule(HealthyPipelineSafeModeRule.class);
+      assertFalse(rule.isRatisThreeRuleEnabled());
+      rule.setValidateBasedOnReportProcessing(validateBasedOnReportProcessing);
+      assertTrue(rule.validate());
+      
assertThat(rule.getStatusText()).doesNotContain("healthyPipelineThresholdCount")
+          .contains("open pipelines with unregistered datanodes (=0)");
+
+      // An unregistered member of either pipeline blocks the rule, even 
though the RATIS/THREE pipeline count does not.
+      for (Pipeline pipeline : Arrays.asList(ecPipeline, ratisPipeline)) {
+        // "Unregister" a node of the pipeline.
+        DatanodeDetails unregisteredNode = 
nodeManager.getNode(pipeline.getNodes().get(0).getID());
+        nodeManager.getClusterNetworkTopologyMap().remove(unregisteredNode);
+        assertFalse(rule.validate());
+        assertThat(rule.getStatusText()).contains("open pipelines with 
unregistered datanodes (=")
+            .contains(pipeline.getId().toString());
+
+        // Once the node registers again, the rule can pass again.
+        nodeManager.getClusterNetworkTopologyMap().add(unregisteredNode);
+        assertTrue(rule.validate());
+      }
+    } finally {
+      scmMetadataStore.getStore().close();
+    }
+  }
+
   private void firePipelineEvent(Pipeline pipeline, EventQueue eventQueue) {
     eventQueue.fireEvent(SCMEvents.OPEN_PIPELINE, pipeline);
   }
diff --git 
a/hadoop-hdds/server-scm/src/test/java/org/apache/hadoop/hdds/scm/safemode/TestSCMSafeModeManager.java
 
b/hadoop-hdds/server-scm/src/test/java/org/apache/hadoop/hdds/scm/safemode/TestSCMSafeModeManager.java
index d1556eeea0b..fa0784123a8 100644
--- 
a/hadoop-hdds/server-scm/src/test/java/org/apache/hadoop/hdds/scm/safemode/TestSCMSafeModeManager.java
+++ 
b/hadoop-hdds/server-scm/src/test/java/org/apache/hadoop/hdds/scm/safemode/TestSCMSafeModeManager.java
@@ -25,6 +25,9 @@
 import static org.junit.jupiter.params.provider.Arguments.arguments;
 import static org.mockito.ArgumentMatchers.any;
 import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.never;
+import static org.mockito.Mockito.times;
+import static org.mockito.Mockito.verify;
 import static org.mockito.Mockito.when;
 
 import java.io.File;
@@ -57,6 +60,8 @@
 import org.apache.hadoop.hdds.scm.ha.SCMHAManager;
 import org.apache.hadoop.hdds.scm.ha.SCMHAManagerStub;
 import org.apache.hadoop.hdds.scm.ha.SCMRatisServer;
+import org.apache.hadoop.hdds.scm.ha.SCMService;
+import org.apache.hadoop.hdds.scm.ha.SCMService.Event;
 import org.apache.hadoop.hdds.scm.ha.SCMServiceManager;
 import org.apache.hadoop.hdds.scm.ha.SCMStateMachine;
 import org.apache.hadoop.hdds.scm.metadata.SCMMetadataStore;
@@ -171,6 +176,31 @@ private void testSafeMode(int numContainers) throws 
Exception {
 
   }
 
+  @Test
+  public void testContainerRulesValidatedEventFiredOnce() throws Exception {
+    containers = new ArrayList<>(HddsTestUtils.getContainerInfo(5));
+    for (ContainerInfo container : containers) {
+      container.setState(HddsProtos.LifeCycleState.CLOSED);
+      container.setNumberOfKeys(10);
+    }
+    ContainerManager containerManager = mock(ContainerManager.class);
+    
when(containerManager.getContainers(ReplicationType.RATIS)).thenReturn(containers);
+    SCMService service = mock(SCMService.class);
+    serviceManager.register(service);
+    scmSafeModeManager = new SCMSafeModeManager(config, null, null, 
containerManager,
+        serviceManager, queue, scmContext);
+    scmSafeModeManager.start();
+    verify(service, 
never()).notifyEventTriggered(Event.CONTAINER_SAFE_MODE_RULES_VALIDATED);
+
+    SCMDatanodeProtocolServer.NodeRegistrationContainerReport 
nodeRegistrationContainerReport =
+        HddsTestUtils.createNodeRegistrationContainerReport(containers);
+    queue.fireEvent(SCMEvents.NODE_REGISTRATION_CONT_REPORT, 
nodeRegistrationContainerReport);
+    queue.fireEvent(SCMEvents.CONTAINER_REGISTRATION_REPORT, 
nodeRegistrationContainerReport);
+    GenericTestUtils.waitFor(() -> !scmSafeModeManager.getInSafeMode(), 100, 
1000 * 5);
+
+    verify(service, 
times(1)).notifyEventTriggered(Event.CONTAINER_SAFE_MODE_RULES_VALIDATED);
+  }
+
   @Test
   public void testSafeModeExitWithPeriodicContainerRuleRefresh() throws 
Exception {
     /*
@@ -850,8 +880,13 @@ public void 
testEcDefaultDisablesHealthyPipelineRuleWhenRatisThreeDisabled() {
         pipelineManager, containerManager, serviceManager, queue, scmContext);
     scmSafeModeManager.start();
 
-    assertThat(SafeModeRuleFactory.getInstance()
-        .getSafeModeRule(HealthyPipelineSafeModeRule.class)).isNull();
+    // The rule is still registered to check for pipelines with unregistered
+    // datanodes, but without the RATIS/THREE threshold.
+    HealthyPipelineSafeModeRule healthyPipelineRule = 
SafeModeRuleFactory.getInstance()
+        .getSafeModeRule(HealthyPipelineSafeModeRule.class);
+    assertThat(healthyPipelineRule).isNotNull();
+    assertFalse(healthyPipelineRule.isRatisThreeRuleEnabled());
+    assertTrue(healthyPipelineRule.validate());
     assertThat(SafeModeRuleFactory.getInstance()
         .getSafeModeRule(OneReplicaPipelineSafeModeRule.class)).isNull();
     ECMinDataNodeSafeModeRule ecMinDnRule = SafeModeRuleFactory.getInstance()
diff --git 
a/hadoop-hdds/server-scm/src/test/java/org/apache/hadoop/hdds/scm/safemode/TestSafeModeRuleFactory.java
 
b/hadoop-hdds/server-scm/src/test/java/org/apache/hadoop/hdds/scm/safemode/TestSafeModeRuleFactory.java
index 3f0b8f415f2..7f87ebd3e40 100644
--- 
a/hadoop-hdds/server-scm/src/test/java/org/apache/hadoop/hdds/scm/safemode/TestSafeModeRuleFactory.java
+++ 
b/hadoop-hdds/server-scm/src/test/java/org/apache/hadoop/hdds/scm/safemode/TestSafeModeRuleFactory.java
@@ -18,6 +18,9 @@
 package org.apache.hadoop.hdds.scm.safemode;
 
 import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertNull;
 import static org.junit.jupiter.api.Assertions.assertThrows;
 import static org.mockito.Mockito.mock;
 import static org.mockito.Mockito.when;
@@ -89,8 +92,13 @@ public void 
testRuleCountForEcDefaultWithRatisThreeFlagDisabled() {
     final SafeModeRuleFactory factory = SafeModeRuleFactory.getInstance();
     factory.addSafeModeManager(safeModeManager);
 
-    assertEquals(4, factory.getSafeModeRules().size(),
-        "EC default with flag=false should skip RATIS/THREE pipeline rules");
+    // HealthyPipelineSafeModeRule stays to check for pipelines with 
unregistered datanodes.
+    assertEquals(5, factory.getSafeModeRules().size(),
+        "EC default with flag=false should skip 
OneReplicaPipelineSafeModeRule");
+    HealthyPipelineSafeModeRule healthyPipelineRule = 
factory.getSafeModeRule(HealthyPipelineSafeModeRule.class);
+    assertNotNull(healthyPipelineRule);
+    assertFalse(healthyPipelineRule.isRatisThreeRuleEnabled());
+    assertNull(factory.getSafeModeRule(OneReplicaPipelineSafeModeRule.class));
   }
 
   @Test
diff --git 
a/hadoop-ozone/dist/src/main/compose/upgrade/compose/ha/docker-config 
b/hadoop-ozone/dist/src/main/compose/upgrade/compose/ha/docker-config
index 59ca7bada10..243eaf025a4 100644
--- a/hadoop-ozone/dist/src/main/compose/upgrade/compose/ha/docker-config
+++ b/hadoop-ozone/dist/src/main/compose/upgrade/compose/ha/docker-config
@@ -50,9 +50,10 @@ OZONE-SITE.XML_ozone.hbase.enhancements.allowed=true
 # a CLOSED state so the datanodes can progress with finalization.
 #
 # This config sets the amount of time SCM will wait after safemode exit to
-# start the replication manager and pipeline scrubber. The default of 5 minutes
-# is fine in real clusters to prevent unnecessary over-replication,
-# but it is too long for this test.
+# start the replication manager. Older versions also delay the pipeline
+# scrubber by this amount; newer versions start it without this delay.
+# The default of 5 minutes is fine in real clusters to prevent unnecessary
+# over-replication, but it is too long for this test.
 OZONE-SITE.XML_hdds.scm.wait.time.after.safemode.exit=5s
 # If datanodes take too long to close pipelines during finalization, let the
 # scrubber force close them to move the test forward.
diff --git 
a/hadoop-ozone/integration-test/src/test/java/org/apache/hadoop/hdds/scm/safemode/TestSCMSafeModeWithPipelineRules.java
 
b/hadoop-ozone/integration-test/src/test/java/org/apache/hadoop/hdds/scm/safemode/TestSCMSafeModeWithPipelineRules.java
index ef3c1e22e49..58826fc2fed 100644
--- 
a/hadoop-ozone/integration-test/src/test/java/org/apache/hadoop/hdds/scm/safemode/TestSCMSafeModeWithPipelineRules.java
+++ 
b/hadoop-ozone/integration-test/src/test/java/org/apache/hadoop/hdds/scm/safemode/TestSCMSafeModeWithPipelineRules.java
@@ -24,10 +24,13 @@
 import static 
org.apache.hadoop.hdds.HddsConfigKeys.HDDS_PIPELINE_REPORT_INTERVAL;
 import static 
org.apache.hadoop.hdds.scm.ScmConfigKeys.OZONE_DATANODE_PIPELINE_LIMIT;
 import static 
org.apache.hadoop.hdds.scm.ScmConfigKeys.OZONE_SCM_HEARTBEAT_PROCESS_INTERVAL;
-import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.junit.jupiter.api.Assertions.assertFalse;
 import static org.junit.jupiter.api.Assertions.assertTrue;
 import static org.junit.jupiter.api.Assertions.fail;
 
+import java.time.Instant;
+import java.time.ZoneOffset;
 import java.util.List;
 import java.util.concurrent.TimeUnit;
 import java.util.concurrent.TimeoutException;
@@ -42,15 +45,20 @@
 import org.apache.hadoop.hdds.scm.ScmConfigKeys;
 import 
org.apache.hadoop.hdds.scm.container.placement.algorithms.SCMContainerPlacementCapacity;
 import org.apache.hadoop.hdds.scm.container.replication.ReplicationManager;
+import org.apache.hadoop.hdds.scm.node.NodeManager;
+import org.apache.hadoop.hdds.scm.pipeline.BackgroundPipelineScrubber;
 import org.apache.hadoop.hdds.scm.pipeline.Pipeline;
 import org.apache.hadoop.hdds.scm.pipeline.PipelineManager;
+import org.apache.hadoop.hdds.scm.pipeline.PipelineManagerImpl;
 import org.apache.hadoop.hdds.scm.server.StorageContainerManager;
+import org.apache.hadoop.hdds.utils.HddsServerUtil;
 import org.apache.hadoop.ozone.DataTestUtil;
 import org.apache.hadoop.ozone.MiniOzoneCluster;
 import org.apache.hadoop.ozone.OzoneConfigKeys;
 import org.apache.hadoop.ozone.client.OzoneBucket;
 import org.apache.hadoop.ozone.client.OzoneClient;
 import org.apache.ozone.test.GenericTestUtils;
+import org.apache.ozone.test.MockClock;
 import org.junit.jupiter.api.AfterEach;
 import org.junit.jupiter.api.Test;
 
@@ -122,12 +130,14 @@ void testScmSafeMode() throws Exception {
     SCMSafeModeManager scmSafeModeManager =
         cluster.getStorageContainerManager().getScmSafeModeManager();
 
-    // Ceil(0.1 * 2) is 1, as one pipeline is healthy pipeline rule is
-    // satisfied
-
+    // Ceil(0.1 * 2) is 1, as one pipeline is healthy the healthy pipeline
+    // threshold is satisfied. The rule still does not pass while open
+    // pipelines have datanodes which are not registered.
     final HealthyPipelineSafeModeRule healthyPipelineRule = 
SafeModeRuleFactory.getInstance()
         .getSafeModeRule(HealthyPipelineSafeModeRule.class);
-    GenericTestUtils.waitFor(healthyPipelineRule::validate, 1000, 60000);
+    GenericTestUtils.waitFor(() -> 
healthyPipelineRule.getCurrentHealthyPipelineCount()
+        >= healthyPipelineRule.getHealthyPipelineThresholdCount(), 1000, 
60000);
+    assertFalse(healthyPipelineRule.validate());
 
     // As Ceil(0.9 * 2) is 2, and from second pipeline no datanodes's are
     // reported this rule is not met yet.
@@ -143,23 +153,31 @@ void testScmSafeMode() throws Exception {
 
     GenericTestUtils.waitFor(oneReplicaPipelineRule::validate, 1000, 60000);
 
-    // All safeMode preChecks are now satisfied, SCM should be out of safe 
mode.
-
-    GenericTestUtils.waitFor(() -> !scmSafeModeManager.getInSafeMode(), 1000,
-        60000);
-
-    // As after safeMode wait time is not completed, we should have total
-    // pipeline's as original count 6(1 node pipelines) + 2 (3 node pipeline)
-    assertEquals(totalPipelineCount, pipelineManager.getPipelines().size());
-
-    // The below check calls pipelineManager.getPipelines()
-    // which is a call to the SCM to get the list of pipeline infos.
-    // This is independent of DN reports or whether any number of DataNodes are
-    // alive as the pipeline info is persisted to SCM upon creation and loaded
-    // back upon restart.
+    // Two datanodes of the 2nd pipeline are still unregistered. Once the
+    // container rules pass and the stale node interval elapses, the scrubber
+    // closes the open pipelines containing them while SCM is in safe mode,
+    // and then SCM exits safe mode. Skip ahead past the stale node interval
+    // instead of waiting for it.
+    BackgroundPipelineScrubber scrubber = ((PipelineManagerImpl) 
pipelineManager).getBackgroundPipelineScrubber();
+    MockClock clock = new MockClock(Instant.now(), ZoneOffset.UTC);
+    clock.fastForward(HddsServerUtil.getStaleNodeInterval(cluster.getConf()));
+    scrubber.setClock(clock);
+    GenericTestUtils.waitFor(() -> !scmSafeModeManager.getInSafeMode(), 1000, 
60000);
+
+    // No open pipeline has unregistered datanodes at safe mode exit.
+    NodeManager nodeManager = 
cluster.getStorageContainerManager().getScmNodeManager();
+    for (Pipeline pipeline : pipelineManager.getPipelines()) {
+      assertFalse(PipelineManagerImpl.isOpenWithUnregisteredNodes(pipeline, 
nodeManager),
+          "Open pipeline " + pipeline.getId() + " has unregistered datanodes");
+    }
+    // All pipelines are still known to SCM. The scrubbed ones are closed.
+    
assertThat(pipelineManager.getPipelines().size()).isGreaterThanOrEqualTo(totalPipelineCount);
 
-    waitForRatis1NodePipelines(datanodeCount);
-    waitForRatis3NodePipelines(datanodeCount / 3);
+    // The 1 node pipelines of the two unregistered datanodes and the 2nd
+    // 3 node pipeline are closed. The 4 registered datanodes cannot form
+    // another 3 node pipeline with a pipeline limit of 1.
+    waitForRatis1NodePipelines(datanodeCount - 2);
+    waitForRatis3NodePipelines(1);
 
     ReplicationManager replicationManager =
         cluster.getStorageContainerManager().getReplicationManager();


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

Reply via email to