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

ivandika3 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 3e491ccdc5d HDDS-15960. Hadoop metrics leak detection (#10941)
3e491ccdc5d is described below

commit 3e491ccdc5d9f3087aab1cf100f58b4404d8307f
Author: Ivan Andika <[email protected]>
AuthorDate: Thu Oct 22 13:07:23 2026 +0800

    HDDS-15960. Hadoop metrics leak detection (#10941)
---
 .../org/apache/hadoop/ozone/util/MetricUtil.java   |  20 ++
 .../apache/hadoop/ozone/util/TestMetricUtil.java   |  47 +++++
 .../hadoop/ozone/HddsDatanodeHttpServer.java       |   7 +-
 .../apache/hadoop/ozone/HddsDatanodeService.java   |   3 +-
 .../container/common/volume/MutableVolumeSet.java  |   8 +
 .../container/common/volume/TestVolumeSet.java     |  30 +++
 .../hadoop/hdds/server/http/BaseHttpServer.java    |   9 +-
 .../hadoop/hdds/server/http/HttpServer2.java       |  13 +-
 .../hdds/server/http/HttpServer2Metrics.java       |  18 +-
 .../hadoop/hdds/server/http/TestHttpServer2.java   |  37 ++++
 .../hdds/server/http/TestHttpServer2Metrics.java   |  30 +++
 .../container/placement/metrics/SCMMetrics.java    |  20 +-
 .../hdds/scm/server/SCMContainerMetrics.java       |  17 +-
 .../hdds/scm/server/StorageContainerManager.java   |  12 +-
 .../server/StorageContainerManagerHttpServer.java  |   2 +-
 .../hadoop/hdds/scm/ha/TestSCMStateMachine.java    |   2 +-
 .../hdds/scm/server/TestSCMContainerMetrics.java   |   3 +-
 .../org/apache/hadoop/fs/ozone/TestSafeMode.java   |   4 +-
 .../scm/node/TestDecommissionAndMaintenance.java   |   3 +
 .../hadoop/ozone/TestMetricsLeakAssertion.java     | 134 ++++++++++++
 .../apache/hadoop/ozone/TestMiniOzoneCluster.java  |  42 ++++
 .../ozone/om/TestGetDBUpdatesAuthorization.java    |  23 +--
 .../TestGetDBUpdatesAuthorizationWithoutRecon.java |  53 +++++
 .../om/TestOMHALeaderSpecificACLEnforcement.java   |   2 +
 .../apache/hadoop/ozone/MetricsLeakAssertion.java  | 226 +++++++++++++++++++++
 .../org/apache/hadoop/ozone/MiniOzoneCluster.java  |  12 ++
 .../apache/hadoop/ozone/MiniOzoneClusterImpl.java  |  29 ++-
 .../hadoop/ozone/MiniOzoneHAClusterImpl.java       |   1 +
 .../hadoop/ozone/om/OmSnapshotInternalMetrics.java |  36 +++-
 .../org/apache/hadoop/ozone/om/OzoneManager.java   |   9 +-
 .../hadoop/ozone/om/OzoneManagerHttpServer.java    |   3 +-
 .../hadoop/ozone/om/VolumeUtilizationMetrics.java  |  15 +-
 .../ozone/om/TestOmSnapshotInternalMetrics.java    |  57 ++++++
 .../ozone/om/TestVolumeUtilizationMetrics.java     |  35 +++-
 .../snapshot/SnapshotRequestAndResponseTests.java  |   2 +-
 35 files changed, 891 insertions(+), 73 deletions(-)

diff --git 
a/hadoop-hdds/common/src/main/java/org/apache/hadoop/ozone/util/MetricUtil.java 
b/hadoop-hdds/common/src/main/java/org/apache/hadoop/ozone/util/MetricUtil.java
index 91255c3947c..4b3de307ca1 100644
--- 
a/hadoop-hdds/common/src/main/java/org/apache/hadoop/ozone/util/MetricUtil.java
+++ 
b/hadoop-hdds/common/src/main/java/org/apache/hadoop/ozone/util/MetricUtil.java
@@ -23,6 +23,7 @@
 import java.util.List;
 import java.util.function.Consumer;
 import java.util.stream.Collectors;
+import org.apache.hadoop.metrics2.lib.DefaultMetricsSystem;
 import org.apache.hadoop.metrics2.lib.MetricsRegistry;
 import org.apache.hadoop.metrics2.lib.MutableQuantiles;
 import org.apache.hadoop.metrics2.lib.MutableStat;
@@ -125,4 +126,23 @@ public static void stop(Iterable<MutableQuantiles> 
quantiles) {
       }
     }
   }
+
+  /**
+   * Returns a source name that is unique for a service in a mini cluster.
+   */
+  public static String getMetricsSourceName(String sourceName, String id) {
+    return DefaultMetricsSystem.inMiniClusterMode() && id != null
+        ? sourceName + '-' + id : sourceName;
+  }
+
+  /**
+   * Returns a source name that is unique for a service instance in a mini
+   * cluster.
+   */
+  public static String getMetricsSourceName(String sourceName,
+      String serviceId, String id) {
+    String metricsId = serviceId == null || serviceId.isEmpty()
+        ? id : serviceId + '-' + id;
+    return getMetricsSourceName(sourceName, metricsId);
+  }
 }
diff --git 
a/hadoop-hdds/common/src/test/java/org/apache/hadoop/ozone/util/TestMetricUtil.java
 
b/hadoop-hdds/common/src/test/java/org/apache/hadoop/ozone/util/TestMetricUtil.java
new file mode 100644
index 00000000000..1e9e18b8f4a
--- /dev/null
+++ 
b/hadoop-hdds/common/src/test/java/org/apache/hadoop/ozone/util/TestMetricUtil.java
@@ -0,0 +1,47 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.hadoop.ozone.util;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+
+import org.apache.hadoop.metrics2.lib.DefaultMetricsSystem;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.Test;
+
+class TestMetricUtil {
+
+  @AfterEach
+  void resetMiniClusterMode() {
+    DefaultMetricsSystem.setMiniClusterMode(false);
+  }
+
+  @Test
+  void testGetMetricsSourceName() {
+    assertEquals("source", MetricUtil.getMetricsSourceName("source", "id"));
+
+    DefaultMetricsSystem.setMiniClusterMode(true);
+    assertEquals("source-id",
+        MetricUtil.getMetricsSourceName("source", "id"));
+    assertEquals("source",
+        MetricUtil.getMetricsSourceName("source", null));
+    assertEquals("source-service-id",
+        MetricUtil.getMetricsSourceName("source", "service", "id"));
+    assertEquals("source-id",
+        MetricUtil.getMetricsSourceName("source", null, "id"));
+  }
+}
diff --git 
a/hadoop-hdds/container-service/src/main/java/org/apache/hadoop/ozone/HddsDatanodeHttpServer.java
 
b/hadoop-hdds/container-service/src/main/java/org/apache/hadoop/ozone/HddsDatanodeHttpServer.java
index 4393f4e7b12..5800fd31f14 100644
--- 
a/hadoop-hdds/container-service/src/main/java/org/apache/hadoop/ozone/HddsDatanodeHttpServer.java
+++ 
b/hadoop-hdds/container-service/src/main/java/org/apache/hadoop/ozone/HddsDatanodeHttpServer.java
@@ -31,7 +31,12 @@ public class HddsDatanodeHttpServer extends BaseHttpServer {
 
   public HddsDatanodeHttpServer(MutableConfigurationSource conf)
       throws IOException {
-    super(conf, "hddsDatanode");
+    this(conf, null);
+  }
+
+  public HddsDatanodeHttpServer(MutableConfigurationSource conf,
+      String datanodeId) throws IOException {
+    super(conf, "hddsDatanode", datanodeId);
   }
 
   @Override
diff --git 
a/hadoop-hdds/container-service/src/main/java/org/apache/hadoop/ozone/HddsDatanodeService.java
 
b/hadoop-hdds/container-service/src/main/java/org/apache/hadoop/ozone/HddsDatanodeService.java
index 493c341d402..feb61f8bc0a 100644
--- 
a/hadoop-hdds/container-service/src/main/java/org/apache/hadoop/ozone/HddsDatanodeService.java
+++ 
b/hadoop-hdds/container-service/src/main/java/org/apache/hadoop/ozone/HddsDatanodeService.java
@@ -336,7 +336,8 @@ public String getNamespace() {
           dnCertClient, secretKeyClient, this::terminateDatanode,
           reconfigurationHandler);
       try {
-        httpServer = new HddsDatanodeHttpServer(conf);
+        httpServer = new HddsDatanodeHttpServer(conf,
+            datanodeDetails.getUuidString());
         httpServer.start();
         HttpConfig.Policy policy = HttpConfig.getHttpPolicy(conf);
 
diff --git 
a/hadoop-hdds/container-service/src/main/java/org/apache/hadoop/ozone/container/common/volume/MutableVolumeSet.java
 
b/hadoop-hdds/container-service/src/main/java/org/apache/hadoop/ozone/container/common/volume/MutableVolumeSet.java
index 4d60015a050..7332e317f3b 100644
--- 
a/hadoop-hdds/container-service/src/main/java/org/apache/hadoop/ozone/container/common/volume/MutableVolumeSet.java
+++ 
b/hadoop-hdds/container-service/src/main/java/org/apache/hadoop/ozone/container/common/volume/MutableVolumeSet.java
@@ -361,6 +361,14 @@ public void shutdown() {
     }
     volumeMap.clear();
 
+    // Failed volumes keep VolumeInfoMetrics registered (HDDS-7086) while the 
datanode runs.
+    for (StorageVolume volume : failedVolumeMap.values()) {
+      if (volume instanceof HddsVolume && ((HddsVolume) 
volume).getVolumeInfoStats() != null) {
+        ((HddsVolume) volume).getVolumeInfoStats().unregister();
+      }
+    }
+    failedVolumeMap.clear();
+
     if (volumeHealthMetrics != null) {
       volumeHealthMetrics.unregister();
     }
diff --git 
a/hadoop-hdds/container-service/src/test/java/org/apache/hadoop/ozone/container/common/volume/TestVolumeSet.java
 
b/hadoop-hdds/container-service/src/test/java/org/apache/hadoop/ozone/container/common/volume/TestVolumeSet.java
index 64e1c00e70e..76e0ed3ac6b 100644
--- 
a/hadoop-hdds/container-service/src/test/java/org/apache/hadoop/ozone/container/common/volume/TestVolumeSet.java
+++ 
b/hadoop-hdds/container-service/src/test/java/org/apache/hadoop/ozone/container/common/volume/TestVolumeSet.java
@@ -25,15 +25,22 @@
 import static org.assertj.core.api.Assumptions.assumeThat;
 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.junit.jupiter.api.Assertions.assertTrue;
+import static org.mockito.Mockito.never;
+import static org.mockito.Mockito.spy;
+import static org.mockito.Mockito.verify;
 
 import java.io.File;
 import java.io.IOException;
 import java.lang.reflect.Method;
 import java.nio.file.Path;
 import java.util.ArrayList;
+import java.util.HashMap;
 import java.util.List;
+import java.util.Map;
 import java.util.UUID;
 import java.util.concurrent.CompletableFuture;
 import java.util.concurrent.TimeUnit;
@@ -43,6 +50,8 @@
 import org.apache.hadoop.hdds.conf.OzoneConfiguration;
 import org.apache.hadoop.hdds.scm.ScmConfigKeys;
 import org.apache.hadoop.metrics2.MetricsRecordBuilder;
+import org.apache.hadoop.metrics2.MetricsSystem;
+import org.apache.hadoop.metrics2.lib.DefaultMetricsSystem;
 import org.apache.hadoop.ozone.OzoneConfigKeys;
 import org.apache.hadoop.ozone.container.common.utils.HddsVolumeUtil;
 import org.junit.jupiter.api.AfterEach;
@@ -131,6 +140,11 @@ public void testVolumeSetInitialization() throws Exception 
{
   public void testFailVolume() throws Exception {
     assertNumVolumes(volumeSet, 2, 0);
 
+    String volumeRoot = HddsVolumeUtil.getHddsRoot(volume1);
+    Map<String, StorageVolume> volumeMap = new 
HashMap<>(volumeSet.getVolumeMap());
+    StorageVolume failedVolume = spy(volumeMap.get(volumeRoot));
+    volumeMap.put(volumeRoot, failedVolume);
+    volumeSet.setVolumeMapForTesting(volumeMap);
     volumeSet.failVolume(HddsVolumeUtil.getHddsRoot(volume1));
 
     assertEquals(1, volumeSet.getVolumesList().size());
@@ -142,6 +156,13 @@ public void testFailVolume() throws Exception {
     assertThat(volumeSet.getVolumeMap()).doesNotContainKey(volume1);
 
     assertNumVolumes(volumeSet, 1, 1);
+
+    MetricsSystem ms = DefaultMetricsSystem.instance();
+    String sourceName = VolumeInfoMetrics.class.getSimpleName() + "-" + 
volume1;
+    assertNotNull(ms.getSource(sourceName));
+    volumeSet.shutdown();
+    verify(failedVolume, never()).shutdown();
+    assertNull(ms.getSource(sourceName));
   }
 
   @Test
@@ -195,7 +216,16 @@ void testFailVolumes(@TempDir File readOnlyVolumePath, 
@TempDir File volumePath)
     assertEquals(readOnlyVolumePath, volSet.getFailedVolumesList().get(0)
         .getStorageDir());
     assertNumVolumes(volSet, 1, 1);
+
+    // The failed volume's VolumeInfoMetrics is registered on creation
+    // (HDDS-7086) and must be unregistered when the volume set shuts down.
+    MetricsSystem ms = DefaultMetricsSystem.instance();
+    String failedVolumeMetrics = VolumeInfoMetrics.class.getSimpleName()
+        + "-" + readOnlyVolumePath.getAbsolutePath();
+    assertNotNull(ms.getSource(failedVolumeMetrics));
+
     volSet.shutdown();
+    assertNull(ms.getSource(failedVolumeMetrics));
   }
 
   @Test
diff --git 
a/hadoop-hdds/framework/src/main/java/org/apache/hadoop/hdds/server/http/BaseHttpServer.java
 
b/hadoop-hdds/framework/src/main/java/org/apache/hadoop/hdds/server/http/BaseHttpServer.java
index 25cdaba4f01..6ec801143b1 100644
--- 
a/hadoop-hdds/framework/src/main/java/org/apache/hadoop/hdds/server/http/BaseHttpServer.java
+++ 
b/hadoop-hdds/framework/src/main/java/org/apache/hadoop/hdds/server/http/BaseHttpServer.java
@@ -93,6 +93,12 @@ public abstract class BaseHttpServer implements 
AutoCloseable {
 
   public BaseHttpServer(MutableConfigurationSource conf, String name)
       throws IOException {
+    this(conf, name, null);
+  }
+
+  public BaseHttpServer(MutableConfigurationSource conf, String name,
+      String metricsSourceId)
+      throws IOException {
     this.name = name;
     this.conf = conf;
     policy = getHttpPolicy(conf);
@@ -106,7 +112,8 @@ public BaseHttpServer(MutableConfigurationSource conf, 
String name)
       conf.set("hadoop.prometheus.endpoint.enabled", "false");
 
       HttpServer2.Builder builder = newHttpServer2BuilderForOzone(
-          conf, httpAddress, httpsAddress, name);
+          conf, httpAddress, httpsAddress, name)
+          .setMetricsSourceId(metricsSourceId);
 
       LOG.info("Hadoop Security Enabled: {} " +
               "Ozone Security Enabled: {} " +
diff --git 
a/hadoop-hdds/framework/src/main/java/org/apache/hadoop/hdds/server/http/HttpServer2.java
 
b/hadoop-hdds/framework/src/main/java/org/apache/hadoop/hdds/server/http/HttpServer2.java
index e1d05567f93..f59d33209fc 100644
--- 
a/hadoop-hdds/framework/src/main/java/org/apache/hadoop/hdds/server/http/HttpServer2.java
+++ 
b/hadoop-hdds/framework/src/main/java/org/apache/hadoop/hdds/server/http/HttpServer2.java
@@ -48,6 +48,7 @@
 import java.util.Map;
 import java.util.Objects;
 import java.util.Properties;
+import java.util.UUID;
 import java.util.regex.Matcher;
 import java.util.regex.Pattern;
 import javax.servlet.Filter;
@@ -265,6 +266,7 @@ public final class HttpServer2 implements FilterContainer {
   public static class Builder {
     private ArrayList<URI> endpoints = Lists.newArrayList();
     private String name;
+    private String metricsSourceId;
     private MutableConfigurationSource conf;
     private ConfigurationSource sslConf;
     private String[] pathSpecs;
@@ -305,6 +307,11 @@ public Builder setName(String serverName) {
       return this;
     }
 
+    public Builder setMetricsSourceId(String sourceId) {
+      this.metricsSourceId = sourceId;
+      return this;
+    }
+
     /**
      * Add an endpoint that the HTTP server should listen to.
      *
@@ -730,7 +737,8 @@ private void initializeWebServer(Builder builder) throws 
IOException {
       threadPool.setMaxThreads(maxThreads);
     }
 
-    metrics = HttpServer2Metrics.create(threadPool, builder.name);
+    metrics = HttpServer2Metrics.create(threadPool, builder.name,
+        builder.metricsSourceId == null ? builder.name + '-' + 
UUID.randomUUID() : builder.metricsSourceId);
     SessionHandler handler = webAppContext.getSessionHandler();
     handler.setHttpOnly(true);
     handler.getSessionCookieConfig().setSecure(true);
@@ -1516,11 +1524,12 @@ public void stop() throws Exception {
       // clear & stop webAppContext attributes to avoid memory leaks.
       webAppContext.clearAttributes();
       webAppContext.stop();
-      metrics.unRegister();
     } catch (Exception e) {
       LOG.error("Error while stopping web app context for webapp "
           + webAppContext.getDisplayName(), e);
       exception = addMultiException(exception, e);
+    } finally {
+      metrics.unRegister();
     }
 
     try {
diff --git 
a/hadoop-hdds/framework/src/main/java/org/apache/hadoop/hdds/server/http/HttpServer2Metrics.java
 
b/hadoop-hdds/framework/src/main/java/org/apache/hadoop/hdds/server/http/HttpServer2Metrics.java
index d013f060be0..fc7f51efd18 100644
--- 
a/hadoop-hdds/framework/src/main/java/org/apache/hadoop/hdds/server/http/HttpServer2Metrics.java
+++ 
b/hadoop-hdds/framework/src/main/java/org/apache/hadoop/hdds/server/http/HttpServer2Metrics.java
@@ -24,6 +24,7 @@
 import org.apache.hadoop.metrics2.MetricsSource;
 import org.apache.hadoop.metrics2.MetricsSystem;
 import org.apache.hadoop.metrics2.lib.DefaultMetricsSystem;
+import org.apache.hadoop.ozone.util.MetricUtil;
 import org.eclipse.jetty.util.thread.QueuedThreadPool;
 
 /**
@@ -38,17 +39,26 @@ public final class HttpServer2Metrics implements 
MetricsSource {
 
   private final QueuedThreadPool threadPool;
   private final String name;
+  private final String sourceName;
 
-  private HttpServer2Metrics(QueuedThreadPool threadPool, String name) {
+  private HttpServer2Metrics(QueuedThreadPool threadPool, String name,
+      String sourceId) {
     this.threadPool = threadPool;
     this.name = name;
+    this.sourceName = MetricUtil.getMetricsSourceName(NAME, sourceId);
   }
 
   public static HttpServer2Metrics create(
       QueuedThreadPool threadPool, String name) {
+    return create(threadPool, name, name);
+  }
+
+  public static HttpServer2Metrics create(QueuedThreadPool threadPool,
+      String name, String sourceId) {
+    HttpServer2Metrics metrics =
+        new HttpServer2Metrics(threadPool, name, sourceId);
     MetricsSystem ms = DefaultMetricsSystem.instance();
-    return ms.register(NAME, "HttpServer2 Metrics",
-        new HttpServer2Metrics(threadPool, name));
+    return ms.register(metrics.sourceName, "HttpServer2 Metrics", metrics);
   }
 
   @Override
@@ -69,7 +79,7 @@ public void getMetrics(MetricsCollector collector, boolean 
all) {
 
   public void unRegister() {
     MetricsSystem ms = DefaultMetricsSystem.instance();
-    ms.unregisterSource(NAME);
+    ms.unregisterSource(sourceName);
   }
 
   enum HttpServer2MetricsInfo implements MetricsInfo {
diff --git 
a/hadoop-hdds/framework/src/test/java/org/apache/hadoop/hdds/server/http/TestHttpServer2.java
 
b/hadoop-hdds/framework/src/test/java/org/apache/hadoop/hdds/server/http/TestHttpServer2.java
index 1dcad11e414..bd48dae72a1 100644
--- 
a/hadoop-hdds/framework/src/test/java/org/apache/hadoop/hdds/server/http/TestHttpServer2.java
+++ 
b/hadoop-hdds/framework/src/test/java/org/apache/hadoop/hdds/server/http/TestHttpServer2.java
@@ -23,6 +23,7 @@
 import static org.junit.jupiter.api.Assertions.assertNotNull;
 import static org.junit.jupiter.api.Assertions.assertNull;
 import static org.junit.jupiter.api.Assertions.assertSame;
+import static org.junit.jupiter.api.Assertions.assertThrows;
 import static org.junit.jupiter.api.Assertions.assertTrue;
 import static org.junit.jupiter.api.Assumptions.assumeTrue;
 
@@ -45,12 +46,14 @@
 import javax.servlet.http.HttpServletRequest;
 import javax.servlet.http.HttpServletResponse;
 import org.apache.hadoop.hdds.conf.OzoneConfiguration;
+import org.apache.hadoop.metrics2.lib.DefaultMetricsSystem;
 import org.apache.hadoop.ozone.OzoneConfigKeys;
 import org.eclipse.jetty.http.UriCompliance;
 import org.eclipse.jetty.server.Handler;
 import org.eclipse.jetty.server.HttpConnectionFactory;
 import org.eclipse.jetty.server.ServerConnector;
 import org.eclipse.jetty.server.handler.ContextHandler;
+import org.eclipse.jetty.util.component.LifeCycle;
 import org.junit.jupiter.api.Test;
 import org.junit.jupiter.api.io.TempDir;
 
@@ -59,6 +62,40 @@
  */
 public class TestHttpServer2 {
 
+  @Test
+  void testMetricsUnregisteredWhenContextStopFails() throws Exception {
+    boolean miniClusterMode = DefaultMetricsSystem.inMiniClusterMode();
+    DefaultMetricsSystem.setMiniClusterMode(true);
+    LifeCycle.Listener listener = new LifeCycle.Listener() {
+      @Override
+      public void lifeCycleStopping(LifeCycle event) {
+        throw new IllegalStateException("Context stop failed");
+      }
+    };
+    try {
+      HttpServer2 server = new HttpServer2.Builder()
+          .setConf(new OzoneConfiguration())
+          .setName("test")
+          .setMetricsSourceId("context-stop-failure")
+          .addEndpoint(URI.create("http://localhost:0";))
+          .build();
+      String sourceName = HttpServer2Metrics.NAME + "-context-stop-failure";
+      try {
+        server.start();
+        assertNotNull(DefaultMetricsSystem.instance().getSource(sourceName));
+        server.getWebAppContext().addEventListener(listener);
+        assertThrows(Exception.class, server::stop);
+        assertNull(DefaultMetricsSystem.instance().getSource(sourceName));
+      } finally {
+        server.getWebAppContext().removeEventListener(listener);
+        server.stop();
+        DefaultMetricsSystem.instance().unregisterSource(sourceName);
+      }
+    } finally {
+      DefaultMetricsSystem.setMiniClusterMode(miniClusterMode);
+    }
+  }
+
   /**
    * Test hadoop.http.idle_timeout.ms correctly loaded, and not being default
    * value from core-default.xml of hadoop-common.
diff --git 
a/hadoop-hdds/framework/src/test/java/org/apache/hadoop/hdds/server/http/TestHttpServer2Metrics.java
 
b/hadoop-hdds/framework/src/test/java/org/apache/hadoop/hdds/server/http/TestHttpServer2Metrics.java
index 07e842068d1..28d6196c2ec 100644
--- 
a/hadoop-hdds/framework/src/test/java/org/apache/hadoop/hdds/server/http/TestHttpServer2Metrics.java
+++ 
b/hadoop-hdds/framework/src/test/java/org/apache/hadoop/hdds/server/http/TestHttpServer2Metrics.java
@@ -22,6 +22,8 @@
 import static 
org.apache.hadoop.hdds.server.http.HttpServer2Metrics.HttpServer2MetricsInfo.HttpServerThreadCount;
 import static 
org.apache.hadoop.hdds.server.http.HttpServer2Metrics.HttpServer2MetricsInfo.HttpServerThreadQueueWaitingTaskCount;
 import static 
org.apache.hadoop.hdds.server.http.HttpServer2Metrics.HttpServer2MetricsInfo.SERVER_NAME;
+import static org.junit.jupiter.api.Assertions.assertNull;
+import static org.junit.jupiter.api.Assertions.assertSame;
 import static org.mockito.Mockito.any;
 import static org.mockito.Mockito.anyInt;
 import static org.mockito.Mockito.anyString;
@@ -33,6 +35,8 @@
 import org.apache.hadoop.metrics2.MetricsCollector;
 import org.apache.hadoop.metrics2.MetricsInfo;
 import org.apache.hadoop.metrics2.MetricsRecordBuilder;
+import org.apache.hadoop.metrics2.MetricsSystem;
+import org.apache.hadoop.metrics2.lib.DefaultMetricsSystem;
 import org.eclipse.jetty.util.thread.QueuedThreadPool;
 import org.junit.jupiter.api.BeforeEach;
 import org.junit.jupiter.api.Test;
@@ -88,4 +92,30 @@ public void testMetrics() {
     verify(recorder).addGauge(HttpServerThreadQueueWaitingTaskCount,
         threadQueueWaitingTaskCount);
   }
+
+  @Test
+  void testUnregisterWithMultipleMetricsSourceIds() {
+    MetricsSystem metricsSystem = 
DefaultMetricsSystem.initialize("TestHttpServer2Metrics");
+    String firstName = HttpServer2Metrics.NAME + "-service1";
+    String secondName = HttpServer2Metrics.NAME + "-service2";
+    boolean miniClusterMode = DefaultMetricsSystem.inMiniClusterMode();
+    DefaultMetricsSystem.setMiniClusterMode(true);
+    try {
+      HttpServer2Metrics first = 
HttpServer2Metrics.create(mock(QueuedThreadPool.class), "server", "service1");
+      HttpServer2Metrics second = 
HttpServer2Metrics.create(mock(QueuedThreadPool.class), "server", "service2");
+      assertSame(first, metricsSystem.getSource(firstName));
+      assertSame(second, metricsSystem.getSource(secondName));
+
+      second.unRegister();
+      assertNull(metricsSystem.getSource(secondName));
+      assertSame(first, metricsSystem.getSource(firstName));
+      first.unRegister();
+      assertNull(metricsSystem.getSource(firstName));
+    } finally {
+      metricsSystem.unregisterSource(firstName);
+      metricsSystem.unregisterSource(secondName);
+      DefaultMetricsSystem.shutdown();
+      DefaultMetricsSystem.setMiniClusterMode(miniClusterMode);
+    }
+  }
 }
diff --git 
a/hadoop-hdds/server-scm/src/main/java/org/apache/hadoop/hdds/scm/container/placement/metrics/SCMMetrics.java
 
b/hadoop-hdds/server-scm/src/main/java/org/apache/hadoop/hdds/scm/container/placement/metrics/SCMMetrics.java
index b746f7eaea1..cc2a3648588 100644
--- 
a/hadoop-hdds/server-scm/src/main/java/org/apache/hadoop/hdds/scm/container/placement/metrics/SCMMetrics.java
+++ 
b/hadoop-hdds/server-scm/src/main/java/org/apache/hadoop/hdds/scm/container/placement/metrics/SCMMetrics.java
@@ -27,18 +27,20 @@
 import org.apache.hadoop.metrics2.lib.DefaultMetricsSystem;
 import org.apache.hadoop.metrics2.lib.MutableCounterLong;
 import org.apache.hadoop.metrics2.lib.MutableGaugeLong;
+import org.apache.hadoop.ozone.util.MetricUtil;
 import org.apache.hadoop.util.Time;
 
 /**
  * This class is for maintaining StorageContainerManager statistics.
  */
 @Metrics(about = "Storage Container Manager Metrics", context = "dfs")
-public class SCMMetrics {
+public final class SCMMetrics {
   public static final String SOURCE_NAME =
       SCMMetrics.class.getSimpleName();
 
   private final LinkedList<String> ratisEvents = new LinkedList<>();
   private final int maxRatisEvents;
+  private final String sourceName;
 
   /**
    * Container stat metrics, the meaning of following metrics
@@ -66,23 +68,25 @@ public DBCheckpointMetrics getDBCheckpointMetrics() {
     return dbCheckpointMetrics;
   }
 
-  public SCMMetrics(int maxRatisEvents) {
+  private SCMMetrics(String sourceName, int maxRatisEvents) {
+    this.sourceName = sourceName;
     dbCheckpointMetrics = DBCheckpointMetrics.create("SCM Metrics");
     this.maxRatisEvents = maxRatisEvents;
   }
 
-  public static SCMMetrics create() {
-    return create(null);
+  public static SCMMetrics create(String scmId) {
+    return create(scmId, null);
   }
 
-  public static SCMMetrics create(ConfigurationSource conf) {
+  public static SCMMetrics create(String scmId, ConfigurationSource conf) {
     MetricsSystem ms = DefaultMetricsSystem.instance();
     int maxRatisEvents = conf == null
         ? ScmConfigKeys.OZONE_SCM_RATIS_EVENTS_MAX_LIMIT_DEFAULT
         : conf.getInt(ScmConfigKeys.OZONE_SCM_RATIS_EVENTS_MAX_LIMIT,
         ScmConfigKeys.OZONE_SCM_RATIS_EVENTS_MAX_LIMIT_DEFAULT);
-    return ms.register(SOURCE_NAME, "Storage Container Manager Metrics",
-        new SCMMetrics(maxRatisEvents));
+    String sourceName = MetricUtil.getMetricsSourceName(SOURCE_NAME, scmId);
+    return ms.register(sourceName, "Storage Container Manager Metrics",
+        new SCMMetrics(sourceName, maxRatisEvents));
   }
 
   public void setLastContainerReportSize(long size) {
@@ -191,6 +195,6 @@ public String getRatisEvents() {
 
   public void unRegister() {
     MetricsSystem ms = DefaultMetricsSystem.instance();
-    ms.unregisterSource(SOURCE_NAME);
+    ms.unregisterSource(sourceName);
   }
 }
diff --git 
a/hadoop-hdds/server-scm/src/main/java/org/apache/hadoop/hdds/scm/server/SCMContainerMetrics.java
 
b/hadoop-hdds/server-scm/src/main/java/org/apache/hadoop/hdds/scm/server/SCMContainerMetrics.java
index f1187d41e78..e4e6e31378f 100644
--- 
a/hadoop-hdds/server-scm/src/main/java/org/apache/hadoop/hdds/scm/server/SCMContainerMetrics.java
+++ 
b/hadoop-hdds/server-scm/src/main/java/org/apache/hadoop/hdds/scm/server/SCMContainerMetrics.java
@@ -34,31 +34,36 @@
 import org.apache.hadoop.metrics2.lib.DefaultMetricsSystem;
 import org.apache.hadoop.metrics2.lib.Interns;
 import org.apache.hadoop.ozone.OzoneConsts;
+import org.apache.hadoop.ozone.util.MetricUtil;
 
 /**
  * Metrics source to report number of containers in different states.
  */
 @InterfaceAudience.Private
 @Metrics(about = "SCM Container Manager Metrics", context = OzoneConsts.OZONE)
-public class SCMContainerMetrics implements MetricsSource {
+public final class SCMContainerMetrics implements MetricsSource {
 
   private final SCMMXBean scmmxBean;
   private static final String SOURCE =
       SCMContainerMetrics.class.getSimpleName();
 
-  public SCMContainerMetrics(SCMMXBean scmmxBean) {
+  private final String sourceName;
+
+  SCMContainerMetrics(String sourceName, SCMMXBean scmmxBean) {
+    this.sourceName = sourceName;
     this.scmmxBean = scmmxBean;
   }
 
-  public static SCMContainerMetrics create(SCMMXBean scmmxBean) {
+  public static SCMContainerMetrics create(String scmId, SCMMXBean scmmxBean) {
     MetricsSystem ms = DefaultMetricsSystem.instance();
-    return ms.register(SOURCE, "Storage " +
-        "Container Manager Metrics", new SCMContainerMetrics(scmmxBean));
+    String sourceName = MetricUtil.getMetricsSourceName(SOURCE, scmId);
+    return ms.register(sourceName, "Storage " +
+        "Container Manager Metrics", new SCMContainerMetrics(sourceName, 
scmmxBean));
   }
 
   public void unRegister() {
     MetricsSystem ms = DefaultMetricsSystem.instance();
-    ms.unregisterSource(SOURCE);
+    ms.unregisterSource(sourceName);
   }
 
   @Override
diff --git 
a/hadoop-hdds/server-scm/src/main/java/org/apache/hadoop/hdds/scm/server/StorageContainerManager.java
 
b/hadoop-hdds/server-scm/src/main/java/org/apache/hadoop/hdds/scm/server/StorageContainerManager.java
index a3a61dfb374..b292c8a6e08 100644
--- 
a/hadoop-hdds/server-scm/src/main/java/org/apache/hadoop/hdds/scm/server/StorageContainerManager.java
+++ 
b/hadoop-hdds/server-scm/src/main/java/org/apache/hadoop/hdds/scm/server/StorageContainerManager.java
@@ -360,9 +360,8 @@ private StorageContainerManager(OzoneConfiguration conf,
 
     scmHANodeDetails = SCMHANodeDetails.loadSCMHAConfig(conf, 
scmStorageConfig);
 
-    initMetrics();
-    initPerfMetrics();
-
+    // Check storage state before registering any metrics, so that a failed
+    // construction does not leak registered metrics sources.
     if (scmStorageConfig.getState() != StorageState.INITIALIZED) {
       String errMsg = "Please make sure you have run 'ozone scm --init' " +
           "command to generate all the required metadata to " +
@@ -374,6 +373,9 @@ private StorageContainerManager(OzoneConfiguration conf,
           "failure.", ResultCodes.SCM_NOT_INITIALIZED);
     }
 
+    initMetrics();
+    initPerfMetrics();
+
     // Initialize Ratis if needed.
     // This is for the clusters which got upgraded from older version of Ozone.
     // We enable Ratis by default.
@@ -1401,7 +1403,7 @@ private static InetSocketAddress 
getScmAddress(SCMHANodeDetails haDetails,
    * Initialize SCM metrics.
    */
   public void initMetrics() {
-    metrics = SCMMetrics.create(configuration);
+    metrics = SCMMetrics.create(getScmId(), configuration);
   }
 
   /**
@@ -1454,7 +1456,7 @@ private void registerMXBean() {
   }
 
   private void registerMetricsSource(SCMMXBean scmMBean) {
-    scmContainerMetrics = SCMContainerMetrics.create(scmMBean);
+    scmContainerMetrics = SCMContainerMetrics.create(getScmId(), scmMBean);
   }
 
   private void unregisterMXBean() {
diff --git 
a/hadoop-hdds/server-scm/src/main/java/org/apache/hadoop/hdds/scm/server/StorageContainerManagerHttpServer.java
 
b/hadoop-hdds/server-scm/src/main/java/org/apache/hadoop/hdds/scm/server/StorageContainerManagerHttpServer.java
index 674eaf624c0..a730a86de33 100644
--- 
a/hadoop-hdds/server-scm/src/main/java/org/apache/hadoop/hdds/scm/server/StorageContainerManagerHttpServer.java
+++ 
b/hadoop-hdds/server-scm/src/main/java/org/apache/hadoop/hdds/scm/server/StorageContainerManagerHttpServer.java
@@ -33,7 +33,7 @@ public class StorageContainerManagerHttpServer extends 
BaseHttpServer {
   public StorageContainerManagerHttpServer(MutableConfigurationSource conf,
                                            StorageContainerManager scm)
       throws IOException {
-    super(conf, "scm");
+    super(conf, "scm", scm == null ? null : scm.getScmId());
     addServlet("dbCheckpoint", OZONE_DB_CHECKPOINT_HTTP_ENDPOINT,
         SCMDBCheckpointServlet.class);
     getWebAppContext().setAttribute(OzoneConsts.SCM_CONTEXT_ATTRIBUTE, scm);
diff --git 
a/hadoop-hdds/server-scm/src/test/java/org/apache/hadoop/hdds/scm/ha/TestSCMStateMachine.java
 
b/hadoop-hdds/server-scm/src/test/java/org/apache/hadoop/hdds/scm/ha/TestSCMStateMachine.java
index 58ab1130b02..f9040caedb8 100644
--- 
a/hadoop-hdds/server-scm/src/test/java/org/apache/hadoop/hdds/scm/ha/TestSCMStateMachine.java
+++ 
b/hadoop-hdds/server-scm/src/test/java/org/apache/hadoop/hdds/scm/ha/TestSCMStateMachine.java
@@ -97,7 +97,7 @@ public class TestSCMStateMachine {
   @BeforeEach
   void setUp() {
     StorageContainerManager scm = mock(StorageContainerManager.class);
-    metrics = SCMMetrics.create();
+    metrics = SCMMetrics.create("scm1");
     SCMHADBTransactionBuffer buffer = mock(SCMHADBTransactionBuffer.class);
     datanodeProtocolServer = mock(SCMDatanodeProtocolServer.class);
     safeModeManager = mock(SCMSafeModeManager.class);
diff --git 
a/hadoop-hdds/server-scm/src/test/java/org/apache/hadoop/hdds/scm/server/TestSCMContainerMetrics.java
 
b/hadoop-hdds/server-scm/src/test/java/org/apache/hadoop/hdds/scm/server/TestSCMContainerMetrics.java
index 4ab807e251f..52e57ae71ae 100644
--- 
a/hadoop-hdds/server-scm/src/test/java/org/apache/hadoop/hdds/scm/server/TestSCMContainerMetrics.java
+++ 
b/hadoop-hdds/server-scm/src/test/java/org/apache/hadoop/hdds/scm/server/TestSCMContainerMetrics.java
@@ -60,7 +60,8 @@ public void testSCMContainerMetrics() {
     MetricsCollector metricsCollector = mock(MetricsCollector.class);
     when(metricsCollector.addRecord(anyString())).thenReturn(mb);
 
-    SCMContainerMetrics containerMetrics = new SCMContainerMetrics(scmmxBean);
+    SCMContainerMetrics containerMetrics =
+        new SCMContainerMetrics("SCMContainerMetrics", scmmxBean);
 
     containerMetrics.getMetrics(metricsCollector, true);
 
diff --git 
a/hadoop-ozone/integration-test/src/test/java/org/apache/hadoop/fs/ozone/TestSafeMode.java
 
b/hadoop-ozone/integration-test/src/test/java/org/apache/hadoop/fs/ozone/TestSafeMode.java
index 1300c61b1f8..ef086782948 100644
--- 
a/hadoop-ozone/integration-test/src/test/java/org/apache/hadoop/fs/ozone/TestSafeMode.java
+++ 
b/hadoop-ozone/integration-test/src/test/java/org/apache/hadoop/fs/ozone/TestSafeMode.java
@@ -59,7 +59,9 @@ class TestSafeMode {
   static void setup() {
     OzoneConfiguration conf = new OzoneConfiguration();
     clusterProvider = new MiniOzoneClusterProvider(
-        MiniOzoneCluster.newBuilder(conf), 2);
+        // Clusters overlap via MiniOzoneClusterProvider, so the metrics leak
+        // assertion would see a concurrent cluster's sources.
+        MiniOzoneCluster.newBuilder(conf).setMetricsLeakAssertEnabled(false), 
2);
   }
 
   @BeforeEach
diff --git 
a/hadoop-ozone/integration-test/src/test/java/org/apache/hadoop/hdds/scm/node/TestDecommissionAndMaintenance.java
 
b/hadoop-ozone/integration-test/src/test/java/org/apache/hadoop/hdds/scm/node/TestDecommissionAndMaintenance.java
index b17a0a99952..d1322772cad 100644
--- 
a/hadoop-ozone/integration-test/src/test/java/org/apache/hadoop/hdds/scm/node/TestDecommissionAndMaintenance.java
+++ 
b/hadoop-ozone/integration-test/src/test/java/org/apache/hadoop/hdds/scm/node/TestDecommissionAndMaintenance.java
@@ -150,6 +150,9 @@ public static void init() {
 
     MiniOzoneCluster.Builder builder = MiniOzoneCluster.newBuilder(conf)
         .setNumDatanodes(DATANODE_COUNT)
+        // Clusters overlap via MiniOzoneClusterProvider, so the metrics leak
+        // assertion would see a concurrent cluster's sources.
+        .setMetricsLeakAssertEnabled(false)
         .setDatanodeFactory(UniformDatanodesFactory.newBuilder()
             .build());
 
diff --git 
a/hadoop-ozone/integration-test/src/test/java/org/apache/hadoop/ozone/TestMetricsLeakAssertion.java
 
b/hadoop-ozone/integration-test/src/test/java/org/apache/hadoop/ozone/TestMetricsLeakAssertion.java
new file mode 100644
index 00000000000..af22571d9c3
--- /dev/null
+++ 
b/hadoop-ozone/integration-test/src/test/java/org/apache/hadoop/ozone/TestMetricsLeakAssertion.java
@@ -0,0 +1,134 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.hadoop.ozone;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertNull;
+import static org.junit.jupiter.api.Assertions.assertSame;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.mockStatic;
+
+import java.util.ArrayList;
+import java.util.List;
+import org.apache.hadoop.metrics2.MetricsSource;
+import org.apache.hadoop.metrics2.MetricsSystem;
+import org.apache.hadoop.metrics2.impl.MetricsSystemImpl;
+import org.apache.hadoop.metrics2.lib.DefaultMetricsSystem;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.ValueSource;
+import org.mockito.MockedStatic;
+
+/**
+ * Tests detection of leaked Hadoop metrics sources.
+ */
+class TestMetricsLeakAssertion {
+
+  private MetricsSystem originalMetricsSystem;
+  private MetricsSystem metricsSystem;
+  private final List<String> registeredSources = new ArrayList<>();
+
+  @BeforeEach
+  void setUp() {
+    originalMetricsSystem = DefaultMetricsSystem.instance();
+    // A subclass also verifies that the assertion finds inherited fields.
+    metricsSystem = new MetricsSystemImpl() { };
+    DefaultMetricsSystem.setInstance(metricsSystem);
+  }
+
+  @AfterEach
+  void tearDown() {
+    try {
+      registeredSources.forEach(metricsSystem::unregisterSource);
+      metricsSystem.shutdown();
+    } finally {
+      DefaultMetricsSystem.setInstance(originalMetricsSystem);
+    }
+  }
+
+  @ParameterizedTest
+  @ValueSource(strings = {"LeakedMetricsSource", 
"HttpServer2Metrics-service1"})
+  void testUnexpectedSourceFails(String sourceName) {
+    registerSource("ContainerCacheMetrics");
+    registerSource(sourceName);
+
+    AssertionError error = assertThrows(AssertionError.class, 
MetricsLeakAssertion::assertNoLeaks);
+    assertThat(error).hasMessageContaining(sourceName);
+    assertNull(metricsSystem.getSource(sourceName));
+    assertNotNull(metricsSystem.getSource("ContainerCacheMetrics"));
+    assertDoesNotThrow(MetricsLeakAssertion::assertNoLeaks);
+  }
+
+  @ParameterizedTest
+  @ValueSource(strings = {"ContainerCacheMetrics", "ContainerCacheMetrics-1", 
"ContainerCacheMetrics-123",
+      "JvmMetricsOM", "RpcActivityForPort15000", "VolumeIOStats-/data/volume", 
"keyTableCache", "keyTableCache-1"})
+  void testAllowedSourcePasses(String sourceName) {
+    registerSource(sourceName);
+
+    assertDoesNotThrow(MetricsLeakAssertion::assertNoLeaks);
+  }
+
+  @ParameterizedTest
+  @ValueSource(strings = {"ContainerCacheMetrics-unexpected", 
"ContainerCacheMetrics-", "keyTableCache-unexpected"})
+  void testUnexpectedSuffixFails(String sourceName) {
+    registerSource(sourceName);
+
+    AssertionError error = assertThrows(AssertionError.class, 
MetricsLeakAssertion::assertNoLeaks);
+    assertThat(error).hasMessageContaining(sourceName);
+  }
+
+  @Test
+  void testMissingSourcesFieldFails() {
+    DefaultMetricsSystem.setInstance(mock(MetricsSystem.class));
+
+    AssertionError error = assertThrows(AssertionError.class, 
MetricsLeakAssertion::assertNoLeaks);
+    assertThat(error).hasMessageContaining("field not found");
+  }
+
+  @Test
+  void testInvalidSourcesFieldFails() {
+    DefaultMetricsSystem.setInstance(new MetricsSystemImpl() {
+      @SuppressWarnings("PMD.UnusedPrivateField") // Accessed reflectively by 
MetricsLeakAssertion.
+      private final String allSources = "not a map";
+    });
+
+    AssertionError error = assertThrows(AssertionError.class, 
MetricsLeakAssertion::assertNoLeaks);
+    assertThat(error).hasMessageContaining("is not a Map");
+  }
+
+  @Test
+  void testMetricsSystemAccessFailureFails() {
+    SecurityException failure = new SecurityException("metrics access denied");
+    try (MockedStatic<DefaultMetricsSystem> defaultMetricsSystem = 
mockStatic(DefaultMetricsSystem.class)) {
+      
defaultMetricsSystem.when(DefaultMetricsSystem::instance).thenThrow(failure);
+
+      AssertionError error = assertThrows(AssertionError.class, 
MetricsLeakAssertion::assertNoLeaks);
+      assertSame(failure, error.getCause());
+    }
+  }
+
+  private void registerSource(String name) {
+    metricsSystem.register(name, name, (MetricsSource) (collector, all) -> { 
});
+    registeredSources.add(name);
+  }
+}
diff --git 
a/hadoop-ozone/integration-test/src/test/java/org/apache/hadoop/ozone/TestMiniOzoneCluster.java
 
b/hadoop-ozone/integration-test/src/test/java/org/apache/hadoop/ozone/TestMiniOzoneCluster.java
index 50befdac1f6..7a6f87848fe 100644
--- 
a/hadoop-ozone/integration-test/src/test/java/org/apache/hadoop/ozone/TestMiniOzoneCluster.java
+++ 
b/hadoop-ozone/integration-test/src/test/java/org/apache/hadoop/ozone/TestMiniOzoneCluster.java
@@ -20,15 +20,22 @@
 import static org.apache.hadoop.hdds.protocol.DatanodeDetails.Port;
 import static 
org.apache.hadoop.hdds.protocol.MockDatanodeDetails.randomDatanodeDetails;
 import static 
org.apache.hadoop.ozone.OzoneConfigKeys.HDDS_CONTAINER_RATIS_IPC_RANDOM_PORT;
+import static org.apache.ozone.test.MetricsAsserts.assertCounter;
+import static org.apache.ozone.test.MetricsAsserts.getMetrics;
 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.assertNotEquals;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertThrows;
 import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.mockito.Mockito.CALLS_REAL_METHODS;
+import static org.mockito.Mockito.mockStatic;
 
 import java.io.File;
 import java.io.IOException;
 import java.io.OutputStream;
+import java.lang.reflect.Field;
 import java.nio.file.Files;
 import java.util.ArrayList;
 import java.util.HashSet;
@@ -48,11 +55,14 @@
 import org.apache.hadoop.hdds.scm.pipeline.Pipeline;
 import org.apache.hadoop.hdds.scm.pipeline.PipelineID;
 import org.apache.hadoop.hdds.scm.server.StorageContainerManager;
+import org.apache.hadoop.metrics2.MetricsSource;
+import org.apache.hadoop.metrics2.lib.DefaultMetricsSystem;
 import org.apache.hadoop.ozone.container.common.DatanodeStorage;
 import org.apache.hadoop.ozone.container.common.SCMTestUtils;
 import 
org.apache.hadoop.ozone.container.common.statemachine.DatanodeStateMachine;
 import 
org.apache.hadoop.ozone.container.common.statemachine.EndpointStateMachine;
 import org.apache.hadoop.ozone.container.common.volume.StorageVolume;
+import org.apache.hadoop.ozone.om.OmSnapshotInternalMetrics;
 import org.junit.jupiter.api.AfterEach;
 import org.junit.jupiter.api.BeforeEach;
 import org.junit.jupiter.api.Test;
@@ -60,6 +70,7 @@
 import org.junit.jupiter.params.ParameterizedTest;
 import org.junit.jupiter.params.provider.CsvSource;
 import org.junit.jupiter.params.provider.ValueSource;
+import org.mockito.MockedStatic;
 
 /**
  * Test cases for mini ozone cluster.
@@ -85,6 +96,37 @@ public void cleanup() {
     }
   }
 
+  @Test
+  void testSnapshotMetricsAfterOmRestart() throws Exception {
+    cluster = MiniOzoneCluster.newBuilder(conf).withoutDatanodes().build();
+    OmSnapshotInternalMetrics metrics = 
cluster.getOzoneManager().getOmSnapshotIntMetrics();
+    Field field = 
OmSnapshotInternalMetrics.class.getDeclaredField("sourceName");
+    field.setAccessible(true);
+    String sourceName = (String) field.get(metrics);
+    assertNotNull(DefaultMetricsSystem.instance().getSource(sourceName));
+    metrics.incNumSnapshotPurges();
+
+    cluster.restartOzoneManager();
+
+    assertNotNull(DefaultMetricsSystem.instance().getSource(sourceName));
+    assertCounter("NumSnapshotPurges", 1L, 
getMetrics(DefaultMetricsSystem.instance().getSource(sourceName)));
+  }
+
+  @Test
+  void testMetricsSystemShutdownOnLeak() throws Exception {
+    cluster = MiniOzoneCluster.newBuilder(conf).withoutDatanodes().build();
+    String sourceName = "TestMiniOzoneClusterLeakedMetrics";
+    DefaultMetricsSystem.instance().register(sourceName, "Test metrics", 
(MetricsSource) (collector, all) -> { });
+    try (MockedStatic<DefaultMetricsSystem> metricsSystem =
+        mockStatic(DefaultMetricsSystem.class, CALLS_REAL_METHODS)) {
+      AssertionError error = assertThrows(AssertionError.class, 
cluster::shutdown);
+      assertThat(error).hasMessageContaining(sourceName);
+      metricsSystem.verify(DefaultMetricsSystem::shutdown);
+    } finally {
+      DefaultMetricsSystem.instance().unregisterSource(sourceName);
+    }
+  }
+
   @Test
   void testHAServiceReturnsDefensiveCopy() {
     List<String> active = new ArrayList<>();
diff --git 
a/hadoop-ozone/integration-test/src/test/java/org/apache/hadoop/ozone/om/TestGetDBUpdatesAuthorization.java
 
b/hadoop-ozone/integration-test/src/test/java/org/apache/hadoop/ozone/om/TestGetDBUpdatesAuthorization.java
index bf0e875f2cf..57d05effff9 100644
--- 
a/hadoop-ozone/integration-test/src/test/java/org/apache/hadoop/ozone/om/TestGetDBUpdatesAuthorization.java
+++ 
b/hadoop-ozone/integration-test/src/test/java/org/apache/hadoop/ozone/om/TestGetDBUpdatesAuthorization.java
@@ -64,7 +64,7 @@ public class TestGetDBUpdatesAuthorization {
   private static final String BUCKET = "bucket1";
   private static final String KEY = "key1";
   private static final String READONLY_ADMIN = "roadmin";
-  private static final String RECON_PRINCIPAL = "reconsvc";
+  static final String RECON_PRINCIPAL = "reconsvc";
 
   @BeforeAll
   static void init() throws Exception {
@@ -95,7 +95,7 @@ static void shutdown() {
     }
   }
 
-  private static OzoneConfiguration authTestConfiguration() {
+  static OzoneConfiguration authTestConfiguration() {
     OzoneConfiguration testConf = new OzoneConfiguration();
     testConf.setBoolean(OZONE_ACL_ENABLED, true);
     testConf.set(OZONE_ACL_AUTHORIZER_CLASS, 
OZONE_ACL_AUTHORIZER_CLASS_NATIVE);
@@ -108,7 +108,7 @@ private static OzoneConfiguration authTestConfiguration() {
     return testConf;
   }
 
-  private static DBUpdates getDBUpdates(OzoneConfiguration ozoneConf, 
UserGroupInformation user)
+  static DBUpdates getDBUpdates(OzoneConfiguration ozoneConf, 
UserGroupInformation user)
       throws Exception {
     return user.doAs((PrivilegedExceptionAction<DBUpdates>) () -> {
       OzoneManagerProtocolClientSideTranslatorPB omClient =
@@ -156,21 +156,4 @@ void reconPrincipalIsAllowed() throws Exception {
     assertDbUpdatesNonEmpty(getDBUpdates(conf, recon));
   }
 
-  @Test
-  void accessDeniedWhenReconPrincipalNotConfigured() throws Exception {
-    OzoneConfiguration noReconConf = authTestConfiguration();
-    noReconConf.unset(OZONE_RECON_KERBEROS_PRINCIPAL_KEY);
-    MiniOzoneCluster denyCluster =
-        MiniOzoneCluster.newBuilder(noReconConf).setNumDatanodes(1).build();
-    try {
-      denyCluster.waitForClusterToBeReady();
-      UserGroupInformation reconLikeUser =
-          UserGroupInformation.createUserForTesting(RECON_PRINCIPAL, new 
String[] {"recon"});
-      OMException ex = assertThrows(OMException.class,
-          () -> getDBUpdates(noReconConf, reconLikeUser));
-      assertEquals(OMException.ResultCodes.PERMISSION_DENIED, ex.getResult());
-    } finally {
-      denyCluster.shutdown();
-    }
-  }
 }
diff --git 
a/hadoop-ozone/integration-test/src/test/java/org/apache/hadoop/ozone/om/TestGetDBUpdatesAuthorizationWithoutRecon.java
 
b/hadoop-ozone/integration-test/src/test/java/org/apache/hadoop/ozone/om/TestGetDBUpdatesAuthorizationWithoutRecon.java
new file mode 100644
index 00000000000..935962cfdc5
--- /dev/null
+++ 
b/hadoop-ozone/integration-test/src/test/java/org/apache/hadoop/ozone/om/TestGetDBUpdatesAuthorizationWithoutRecon.java
@@ -0,0 +1,53 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.hadoop.ozone.om;
+
+import static 
org.apache.hadoop.hdds.recon.ReconConfig.ConfigStrings.OZONE_RECON_KERBEROS_PRINCIPAL_KEY;
+import static 
org.apache.hadoop.ozone.om.TestGetDBUpdatesAuthorization.RECON_PRINCIPAL;
+import static 
org.apache.hadoop.ozone.om.TestGetDBUpdatesAuthorization.authTestConfiguration;
+import static 
org.apache.hadoop.ozone.om.TestGetDBUpdatesAuthorization.getDBUpdates;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+
+import org.apache.hadoop.hdds.conf.OzoneConfiguration;
+import org.apache.hadoop.ozone.MiniOzoneCluster;
+import org.apache.hadoop.ozone.om.exceptions.OMException;
+import org.apache.hadoop.security.UserGroupInformation;
+import org.junit.jupiter.api.Test;
+
+/**
+ * Tests getDBUpdates authorization when the Recon service principal is not 
configured.
+ */
+class TestGetDBUpdatesAuthorizationWithoutRecon {
+
+  @Test
+  void accessDeniedWhenReconPrincipalNotConfigured() throws Exception {
+    OzoneConfiguration conf = authTestConfiguration();
+    conf.unset(OZONE_RECON_KERBEROS_PRINCIPAL_KEY);
+    MiniOzoneCluster cluster = 
MiniOzoneCluster.newBuilder(conf).setNumDatanodes(1).build();
+    try {
+      cluster.waitForClusterToBeReady();
+      UserGroupInformation reconLikeUser =
+          UserGroupInformation.createUserForTesting(RECON_PRINCIPAL, new 
String[] {"recon"});
+      OMException ex = assertThrows(OMException.class, () -> 
getDBUpdates(conf, reconLikeUser));
+      assertEquals(OMException.ResultCodes.PERMISSION_DENIED, ex.getResult());
+    } finally {
+      cluster.shutdown();
+    }
+  }
+}
diff --git 
a/hadoop-ozone/integration-test/src/test/java/org/apache/hadoop/ozone/om/TestOMHALeaderSpecificACLEnforcement.java
 
b/hadoop-ozone/integration-test/src/test/java/org/apache/hadoop/ozone/om/TestOMHALeaderSpecificACLEnforcement.java
index 22553de8ca5..55023f62982 100644
--- 
a/hadoop-ozone/integration-test/src/test/java/org/apache/hadoop/ozone/om/TestOMHALeaderSpecificACLEnforcement.java
+++ 
b/hadoop-ozone/integration-test/src/test/java/org/apache/hadoop/ozone/om/TestOMHALeaderSpecificACLEnforcement.java
@@ -148,6 +148,8 @@ public void testOMHAAdminPrivilegesAfterLeadershipChange() 
throws Exception {
     
     // Step 4: Force leadership transfer to another OM node
     OzoneManager newLeader = 
cluster.transferOMLeadershipToAnotherNode(currentLeader);
+    assertEquals(NUM_OF_OMS, cluster.getOzoneManagersList().size(),
+        "Leadership transfer must preserve the cluster's OM list");
     assertNotEquals(leaderNodeId, newLeader.getOMNodeId(), 
         "Leadership should have transferred to a different node");
     
diff --git 
a/hadoop-ozone/mini-cluster/src/main/java/org/apache/hadoop/ozone/MetricsLeakAssertion.java
 
b/hadoop-ozone/mini-cluster/src/main/java/org/apache/hadoop/ozone/MetricsLeakAssertion.java
new file mode 100644
index 00000000000..2a35f5dd2b2
--- /dev/null
+++ 
b/hadoop-ozone/mini-cluster/src/main/java/org/apache/hadoop/ozone/MetricsLeakAssertion.java
@@ -0,0 +1,226 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.hadoop.ozone;
+
+import java.lang.reflect.Field;
+import java.util.Arrays;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.TreeSet;
+import org.apache.hadoop.metrics2.MetricsSource;
+import org.apache.hadoop.metrics2.MetricsSystem;
+import org.apache.hadoop.metrics2.lib.DefaultMetricsSystem;
+
+/**
+ * Asserts that no metrics sources remain registered in the
+ * {@link DefaultMetricsSystem} after a mini cluster is shut down.
+ *
+ * <p>Hadoop's {@code MetricsSystemImpl} does not remove registered sources on
+ * {@code stop()} or {@code shutdown()}; a metrics class that forgets to call
+ * {@code unregisterSource(...)} leaks its registration silently.  This helper
+ * inspects the private {@code allSources} map via reflection and fails the
+ * test if anything is still registered.
+ */
+public final class MetricsLeakAssertion {
+
+  private static final String ALL_SOURCES_FIELD = "allSources";
+
+  /**
+   * Metrics sources that are registered once per JVM (or once per service)
+   * and intentionally never unregistered, so they are expected to still be
+   * present after a mini cluster shuts down.  These are JVM-level singletons
+   * with no per-service owner; do not add per-service metrics here.
+   *
+   * <p>For the matching rules see {@link #isExpectedLeftover(String)}.
+   */
+  private static final List<String> EXPECTED_LEFTOVER_SOURCES = Arrays.asList(
+      "JvmMetrics*", // per service, via HddsServerUtil.initializeMetrics
+      "UgiMetrics", // Hadoop security UGI metrics
+      "ManagedRocksObjectMetrics",
+      "ContainerCacheMetrics" // ContainerCache singleton, created once per JVM
+  );
+
+  /**
+   * Metrics sources that leak: they should be unregistered when the mini
+   * cluster shuts down but currently are not.  This is a transitional list to
+   * keep the integration suite green while the leaks are being fixed.  Each
+   * entry should be removed once the corresponding source unregisters
+   * properly; do not add new entries, fix the leak instead.
+   *
+   * <p>For the matching rules see {@link #isExpectedLeftover(String)}.
+   */
+  private static final List<String> TODO_LEFTOVER_SOURCES = Arrays.asList(
+      // RPC / HTTP server metrics (name embeds the listening port).
+      "RpcActivityForPort*",
+      "RpcDetailedActivityForPort*",
+      "LocalJobRunnerMetrics*",
+
+      // Datanode per-instance metrics.
+      "StorageContainerMetrics",
+      "ContainerDataScannerMetrics*", // name embeds the volume path
+      "ContainerMetadataScannerMetrics",
+      "On-demand container scanner metrics",
+      "BackgroundVolumeScannerMetrics",
+      "VolumeHealthMetrics-*",
+      "VolumeIOStats-*", // name embeds the volume path
+      // Name embeds the volume path.  Also intentionally kept registered for
+      // failed volumes (HDDS-7086), so only the healthy-volume case is a leak.
+      "VolumeInfoMetrics-*",
+      "CommandHandlerMetrics",
+      "HddsDispatcher",
+      "ECReconstructionMetrics",
+      "ReplicationSupervisorMetrics",
+      "ContainerReplicator/push",
+      "BlockDeletingService",
+      "GrpcMetrics",
+
+      // SCM metrics.
+      "SCMNodeMetrics",
+      "SCMContainerManagerMetrics",
+      "SafeModeMetrics",
+      "ContainerBalancerMetrics",
+      "NodeDecommissionMetrics",
+      "SCMDatanodeProtocol",
+      "ScmBlockLocationProtocol",
+      "ScmContainerLocationProtocol",
+      "ScmSecurityProtocol",
+      "EventQueue*", // per event/handler pair, registered by SCM EventQueue
+
+      // OM metrics.
+      "OMMetrics",
+      "OMPerformanceMetrics",
+      "OMLockMetrics",
+      "OMHAMetrics",
+      "OMSnapshotDirectoryMetrics",
+      "OmSnapshotMetrics",
+      "OmClientProtocol",
+      "DeletingServiceMetrics",
+      "KeyLifecycleServiceMetrics",
+      "BucketUtilizationMetrics",
+      "DelegationTokenSecretManagerMetrics",
+
+      // OM / SCM RocksDB table cache and DB metrics (name embeds path/uuid).
+      "Rocksdb_*",
+      "SSTFilePruningMetrics-*",
+      "DBCheckpointMetrics",
+      "*TableCache",
+
+      // Ratis / third-party infrastructure metrics.
+      "CSMMetricsgroup-*", // Ratis container state machine, embeds a random id
+      "CacheMetrics-*", // Hadoop cache metrics (XceiverClientManager, etc.)
+      "NettyMetrics*",
+      "ContainerClientMetrics1",
+      "ReconTaskMetrics",
+      "ReconTaskControllerMetrics"
+  );
+
+  private MetricsLeakAssertion() {
+  }
+
+  /**
+   * Throws an {@link AssertionError} if any metrics sources are still
+   * registered with the default metrics system, or if the expected
+   * {@code allSources} field cannot be found or read (e.g. a Hadoop version
+   * change restructured {@code MetricsSystemImpl}), so that a broken or
+   * missing check fails loudly instead of going unnoticed.
+   */
+  public static void assertNoLeaks() {
+    try {
+      MetricsSystem ms = DefaultMetricsSystem.instance();
+      Field field = findAllSourcesField(ms.getClass());
+      if (field == null) {
+        throw new AssertionError("Cannot check for metrics leaks: '" + 
ALL_SOURCES_FIELD +
+            "' field not found on " + ms.getClass().getName() +
+            ". The metrics system implementation may have changed.");
+      }
+      field.setAccessible(true);
+      Object value = field.get(ms);
+      if (!(value instanceof Map)) {
+        throw new AssertionError("Cannot check for metrics leaks: '" + 
ALL_SOURCES_FIELD +
+            "' on " + ms.getClass().getName() + " is not a Map.");
+      }
+      @SuppressWarnings("unchecked")
+      Map<String, MetricsSource> sources = (Map<String, MetricsSource>) value;
+      Set<String> leaked = new TreeSet<>(sources.keySet());
+      leaked.removeIf(MetricsLeakAssertion::isExpectedLeftover);
+      if (!leaked.isEmpty()) {
+        leaked.forEach(ms::unregisterSource);
+        throw new AssertionError("Found " + leaked.size() +
+            " metrics source(s) still registered after cluster shutdown: " + 
leaked);
+      }
+    } catch (IllegalAccessException | RuntimeException e) {
+      throw new AssertionError("Cannot check for metrics leaks: unable to 
inspect '" +
+          ALL_SOURCES_FIELD + "' in the default metrics system.", e);
+    }
+  }
+
+  /**
+   * Matching rules for {@link #EXPECTED_LEFTOVER_SOURCES} and
+   * {@link #TODO_LEFTOVER_SOURCES}:
+   * <ul>
+   *   <li>An entry ending in {@code *} is a prefix match, used for sources
+   *   whose registered name embeds a random id, an absolute path, or a port
+   *   (e.g. {@code RpcActivityForPort15000}).</li>
+   *   <li>An entry starting with {@code *} is a suffix match, used for sources
+   *   whose registered name embeds a table-specific prefix (e.g.
+   *   {@code keyTableCache-1}).</li>
+   *   <li>Any other entry matches the source name exactly, or the name with a
+   *   numeric suffix the metrics system appends for repeated registrations
+   *   (e.g. {@code JvmMetrics-1}).</li>
+   * </ul>
+   */
+  private static boolean isExpectedLeftover(String name) {
+    return matches(EXPECTED_LEFTOVER_SOURCES, name) || 
matches(TODO_LEFTOVER_SOURCES, name);
+  }
+
+  private static boolean matches(List<String> entries, String name) {
+    for (String entry : entries) {
+      if (entry.startsWith("*")) {
+        // Suffix match, also tolerating a trailing numeric suffix (-N).
+        String suffix = entry.substring(1);
+        if (name.endsWith(suffix) || 
stripNumericSuffix(name).endsWith(suffix)) {
+          return true;
+        }
+      } else if (entry.endsWith("*")) {
+        if (name.startsWith(entry.substring(0, entry.length() - 1))) {
+          return true;
+        }
+      } else if (name.equals(entry) || stripNumericSuffix(name).equals(entry)) 
{
+        return true;
+      }
+    }
+    return false;
+  }
+
+  private static String stripNumericSuffix(String name) {
+    return name.replaceFirst("-\\d+$", "");
+  }
+
+  private static Field findAllSourcesField(Class<?> clazz) {
+    Class<?> current = clazz;
+    while (current != null) {
+      try {
+        return current.getDeclaredField(ALL_SOURCES_FIELD);
+      } catch (NoSuchFieldException e) {
+        current = current.getSuperclass();
+      }
+    }
+    return null;
+  }
+}
diff --git 
a/hadoop-ozone/mini-cluster/src/main/java/org/apache/hadoop/ozone/MiniOzoneCluster.java
 
b/hadoop-ozone/mini-cluster/src/main/java/org/apache/hadoop/ozone/MiniOzoneCluster.java
index fc96311e8f4..be0345afa09 100644
--- 
a/hadoop-ozone/mini-cluster/src/main/java/org/apache/hadoop/ozone/MiniOzoneCluster.java
+++ 
b/hadoop-ozone/mini-cluster/src/main/java/org/apache/hadoop/ozone/MiniOzoneCluster.java
@@ -274,6 +274,7 @@ abstract class Builder {
 
     protected int numOfDatanodes = 3;
     protected boolean  startDataNodes = true;
+    protected boolean metricsLeakAssertEnabled = true;
     protected CertificateClient certClient;
     protected SecretKeyClient secretKeyClient;
     protected DatanodeFactory dnFactory = 
UniformDatanodesFactory.newBuilder().build();
@@ -388,6 +389,17 @@ public Builder setStartDataNodes(boolean nodes) {
       return this;
     }
 
+    /**
+     * Whether to assert that no metrics sources leak on cluster shutdown.
+     * Disable for tests that run multiple clusters concurrently (e.g. via
+     * MiniOzoneClusterProvider), because the metrics registry is shared
+     * JVM-wide and a concurrent cluster's sources would be flagged as leaks.
+     */
+    public Builder setMetricsLeakAssertEnabled(boolean enabled) {
+      this.metricsLeakAssertEnabled = enabled;
+      return this;
+    }
+
     public Builder setCertificateClient(CertificateClient client) {
       this.certClient = client;
       return this;
diff --git 
a/hadoop-ozone/mini-cluster/src/main/java/org/apache/hadoop/ozone/MiniOzoneClusterImpl.java
 
b/hadoop-ozone/mini-cluster/src/main/java/org/apache/hadoop/ozone/MiniOzoneClusterImpl.java
index a1a53dbe569..a4ab08d46b9 100644
--- 
a/hadoop-ozone/mini-cluster/src/main/java/org/apache/hadoop/ozone/MiniOzoneClusterImpl.java
+++ 
b/hadoop-ozone/mini-cluster/src/main/java/org/apache/hadoop/ozone/MiniOzoneClusterImpl.java
@@ -116,6 +116,9 @@ public class MiniOzoneClusterImpl implements 
MiniOzoneCluster {
 
   private OzoneConfiguration conf;
   private final SCMConfigurator scmConfigurator;
+  // Whether to assert no metrics sources leak on shutdown.  Tests running
+  // multiple clusters concurrently disable this via the builder.
+  private boolean metricsLeakAssertEnabled = true;
   private StorageContainerManager scm;
   private OzoneManager ozoneManager;
   private final List<HddsDatanodeService> hddsDatanodes;
@@ -168,6 +171,10 @@ protected void setConf(OzoneConfiguration newConf) {
     this.conf = newConf;
   }
 
+  void setMetricsLeakAssertEnabled(boolean enabled) {
+    this.metricsLeakAssertEnabled = enabled;
+  }
+
   public void waitForSCMToBeReady() throws TimeoutException,
       InterruptedException {
     GenericTestUtils.waitFor(scm::checkLeader,
@@ -393,12 +400,23 @@ public void shutdown() {
       stop();
       FileUtils.deleteDirectory(baseDir);
       ContainerCache.getInstance(conf).shutdownCache();
-      DefaultMetricsSystem.shutdown();
+      // RocksDB object leaks are often the root cause; check them first.
       ManagedRocksObjectMetrics.INSTANCE.assertNoLeaks();
+      // Assert before tearing down the metrics system: Hadoop does not clear
+      // allSources on shutdown, but checking before shutdown makes the
+      // assertion independent of that behavior.  Tests running multiple
+      // clusters concurrently disable this because the registry is JVM-wide.
+      if (metricsLeakAssertEnabled) {
+        MetricsLeakAssertion.assertNoLeaks();
+      }
     } catch (Exception e) {
       LOG.error("Exception while shutting down the cluster.", e);
     } finally {
-      resetStaticMappingIfConfigured(conf);
+      try {
+        DefaultMetricsSystem.shutdown();
+      } finally {
+        resetStaticMappingIfConfigured(conf);
+      }
     }
   }
 
@@ -539,6 +557,7 @@ public MiniOzoneCluster build() throws IOException {
         MiniOzoneClusterImpl cluster = new MiniOzoneClusterImpl(conf,
             scmConfigurator, om, scm,
             hddsDatanodes, getServices());
+        cluster.setMetricsLeakAssertEnabled(metricsLeakAssertEnabled);
         cluster.startServices();
 
         cluster.setCAClient(certClient);
@@ -630,6 +649,12 @@ protected void initializeConfiguration() throws 
IOException {
       // pipeline.
       conf.setInt(HddsConfigKeys.HDDS_SCM_SAFEMODE_MIN_DATANODE,
           numOfDatanodes >= 3 ? 3 : 1);
+      // Enable metrics percentile collection so that the quantile code paths
+      // are exercised by every integration test.
+      
conf.setIfUnset(OzoneConfigKeys.OZONE_GPRC_METRICS_PERCENTILES_INTERVALS_KEY, 
"60,300");
+      
conf.setIfUnset(OzoneConfigKeys.OZONE_XCEIVER_CLIENT_METRICS_PERCENTILES_INTERVALS_SECONDS_KEY,
 "60,300");
+      conf.setIfUnset(HddsConfigKeys.HDDS_METRICS_PERCENTILES_INTERVALS_KEY, 
"60,300");
+      
conf.setIfUnset(HddsConfigKeys.OZONE_DATANODE_IO_METRICS_PERCENTILES_INTERVALS_SECONDS_KEY,
 "60,300");
 
       configureHostAndRackTopology();
     }
diff --git 
a/hadoop-ozone/mini-cluster/src/main/java/org/apache/hadoop/ozone/MiniOzoneHAClusterImpl.java
 
b/hadoop-ozone/mini-cluster/src/main/java/org/apache/hadoop/ozone/MiniOzoneHAClusterImpl.java
index c314e2cf371..ed7795b7554 100644
--- 
a/hadoop-ozone/mini-cluster/src/main/java/org/apache/hadoop/ozone/MiniOzoneHAClusterImpl.java
+++ 
b/hadoop-ozone/mini-cluster/src/main/java/org/apache/hadoop/ozone/MiniOzoneHAClusterImpl.java
@@ -502,6 +502,7 @@ public MiniOzoneHAClusterImpl build() throws IOException {
 
       MiniOzoneHAClusterImpl cluster = new MiniOzoneHAClusterImpl(conf,
           scmConfigurator, omService, scmService, hddsDatanodes, path, 
getServices());
+      cluster.setMetricsLeakAssertEnabled(metricsLeakAssertEnabled);
       try {
         cluster.startServices();
       } catch (Exception e) {
diff --git 
a/hadoop-ozone/ozone-manager/src/main/java/org/apache/hadoop/ozone/om/OmSnapshotInternalMetrics.java
 
b/hadoop-ozone/ozone-manager/src/main/java/org/apache/hadoop/ozone/om/OmSnapshotInternalMetrics.java
index 5dc74690fac..b81f48ab04d 100644
--- 
a/hadoop-ozone/ozone-manager/src/main/java/org/apache/hadoop/ozone/om/OmSnapshotInternalMetrics.java
+++ 
b/hadoop-ozone/ozone-manager/src/main/java/org/apache/hadoop/ozone/om/OmSnapshotInternalMetrics.java
@@ -17,22 +17,26 @@
 
 package org.apache.hadoop.ozone.om;
 
+import org.apache.hadoop.metrics2.MetricsCollector;
+import org.apache.hadoop.metrics2.MetricsSource;
 import org.apache.hadoop.metrics2.annotation.Metric;
 import org.apache.hadoop.metrics2.annotation.Metrics;
 import org.apache.hadoop.metrics2.lib.DefaultMetricsSystem;
 import org.apache.hadoop.metrics2.lib.MetricsRegistry;
 import org.apache.hadoop.metrics2.lib.MutableCounterLong;
 import org.apache.hadoop.ozone.OzoneConsts;
+import org.apache.hadoop.ozone.util.MetricUtil;
 
 /**
  * This class contains internal Snapshot Operation metrics.
  */
 @Metrics(about = "Snapshot Internal Operation Metrics", context = 
OzoneConsts.OZONE)
-public class OmSnapshotInternalMetrics {
+public final class OmSnapshotInternalMetrics implements MetricsSource {
 
   public static final String METRICS_SOURCE_NAME =
       OmSnapshotInternalMetrics.class.getSimpleName();
   private MetricsRegistry registry;
+  private String sourceName;
 
   /*
    * Total internal snapshot deletion operation metrics since last restart.
@@ -73,21 +77,35 @@ public class OmSnapshotInternalMetrics {
   @Metric("Total no. of delta files processed during incremental 
defragmentation")
   private MutableCounterLong numSnapshotIncDefragDeltaFilesProcessed;
 
-  public OmSnapshotInternalMetrics() {
-    this.registry = new MetricsRegistry(METRICS_SOURCE_NAME);
+  private OmSnapshotInternalMetrics(String sourceName) {
+    this.sourceName = sourceName;
+    this.registry = new MetricsRegistry(sourceName);
   }
 
-  public static OmSnapshotInternalMetrics create() {
-    return DefaultMetricsSystem.instance().register(METRICS_SOURCE_NAME,
-        "Metrics tracking the progress of snapshot internal operations",
-        new OmSnapshotInternalMetrics());
+  public static OmSnapshotInternalMetrics create(String omServiceId,
+      String omNodeId) {
+    String sourceName = MetricUtil.getMetricsSourceName(METRICS_SOURCE_NAME,
+        omServiceId, omNodeId);
+    OmSnapshotInternalMetrics metrics = new 
OmSnapshotInternalMetrics(sourceName);
+    metrics.register();
+    return metrics;
+  }
+
+  public void register() {
+    DefaultMetricsSystem.instance().register(sourceName,
+        "Metrics tracking the progress of snapshot internal operations", this);
+  }
+
+  @Override
+  public void getMetrics(MetricsCollector collector, boolean all) {
+    registry.snapshot(collector.addRecord(registry.info()), all);
   }
 
   /**
    * Unregister the metrics instance.
    */
-  public static void unregister() {
-    DefaultMetricsSystem.instance().unregisterSource(METRICS_SOURCE_NAME);
+  public void unregister() {
+    DefaultMetricsSystem.instance().unregisterSource(sourceName);
   }
 
   public void incNumSnapshotPurges() {
diff --git 
a/hadoop-ozone/ozone-manager/src/main/java/org/apache/hadoop/ozone/om/OzoneManager.java
 
b/hadoop-ozone/ozone-manager/src/main/java/org/apache/hadoop/ozone/om/OzoneManager.java
index b1746fd1fc8..cce07fa8f61 100644
--- 
a/hadoop-ozone/ozone-manager/src/main/java/org/apache/hadoop/ozone/om/OzoneManager.java
+++ 
b/hadoop-ozone/ozone-manager/src/main/java/org/apache/hadoop/ozone/om/OzoneManager.java
@@ -767,8 +767,8 @@ private OzoneManager(OzoneConfiguration conf, StartupOption 
startupOption)
         OzoneConfigKeys.OZONE_S3G_STS_HTTP_ENABLED_DEFAULT);
 
     metrics = OMMetrics.create(conf);
-
-    omSnapshotIntMetrics = OmSnapshotInternalMetrics.create();
+    omSnapshotIntMetrics = OmSnapshotInternalMetrics.create(getOMServiceId(),
+        getOMNodeId());
     perfMetrics = OMPerformanceMetrics.register();
     omDeletionMetrics = DeletingServiceMetrics.create();
     // Get admin list
@@ -829,7 +829,8 @@ private OzoneManager(OzoneConfiguration conf, StartupOption 
startupOption)
       omState = State.INITIALIZED;
     }
 
-    volumeUtilizationMetrics = 
VolumeUtilizationMetrics.create(metadataManager);
+    volumeUtilizationMetrics = VolumeUtilizationMetrics.create(metadataManager,
+        getOMServiceId(), getOMNodeId());
     bucketUtilizationMetrics = 
BucketUtilizationMetrics.create(metadataManager);
     omHostName = HddsUtils.getHostName(conf);
   }
@@ -2129,6 +2130,7 @@ public void restart() throws IOException {
         omRpcAddress));
 
     HddsServerUtil.initializeMetrics(configuration, "OzoneManager");
+    omSnapshotIntMetrics.register();
 
     instantiateServices(false);
 
@@ -2638,6 +2640,7 @@ public boolean stop() {
       serviceManager.stop();
       DeletingServiceMetrics.unregister();
       OMPerformanceMetrics.unregister();
+      omSnapshotIntMetrics.unregister();
       RatisDropwizardExports.clear(ratisMetricsMap, ratisReporterList);
       scmClient.close();
       if (certClient != null) {
diff --git 
a/hadoop-ozone/ozone-manager/src/main/java/org/apache/hadoop/ozone/om/OzoneManagerHttpServer.java
 
b/hadoop-ozone/ozone-manager/src/main/java/org/apache/hadoop/ozone/om/OzoneManagerHttpServer.java
index fd79f153de3..7115de39b1b 100644
--- 
a/hadoop-ozone/ozone-manager/src/main/java/org/apache/hadoop/ozone/om/OzoneManagerHttpServer.java
+++ 
b/hadoop-ozone/ozone-manager/src/main/java/org/apache/hadoop/ozone/om/OzoneManagerHttpServer.java
@@ -33,7 +33,8 @@ public class OzoneManagerHttpServer extends BaseHttpServer {
 
   public OzoneManagerHttpServer(MutableConfigurationSource conf,
       OzoneManager om) throws IOException {
-    super(conf, "ozoneManager");
+    super(conf, "ozoneManager", om == null ? null
+        : om.getOMServiceId() + '-' + om.getOMNodeId());
     addServlet("serviceList", OZONE_OM_SERVICE_LIST_HTTP_ENDPOINT,
         ServiceListJSONServlet.class);
     addServlet("snapshotList", "/snapshotList",
diff --git 
a/hadoop-ozone/ozone-manager/src/main/java/org/apache/hadoop/ozone/om/VolumeUtilizationMetrics.java
 
b/hadoop-ozone/ozone-manager/src/main/java/org/apache/hadoop/ozone/om/VolumeUtilizationMetrics.java
index 961e99c6485..dc8779067a4 100644
--- 
a/hadoop-ozone/ozone-manager/src/main/java/org/apache/hadoop/ozone/om/VolumeUtilizationMetrics.java
+++ 
b/hadoop-ozone/ozone-manager/src/main/java/org/apache/hadoop/ozone/om/VolumeUtilizationMetrics.java
@@ -30,6 +30,7 @@
 import org.apache.hadoop.metrics2.lib.DefaultMetricsSystem;
 import org.apache.hadoop.ozone.OzoneConsts;
 import org.apache.hadoop.ozone.om.helpers.OmVolumeArgs;
+import org.apache.hadoop.ozone.util.MetricUtil;
 
 /**
  * A class for collecting and reporting volume utilization metrics.
@@ -49,14 +50,20 @@ public class VolumeUtilizationMetrics implements 
MetricsSource {
   private static final String SOURCE = 
VolumeUtilizationMetrics.class.getSimpleName();
 
   private final OMMetadataManager metadataManager;
+  private final String sourceName;
 
-  public VolumeUtilizationMetrics(OMMetadataManager metadataManager) {
+  public VolumeUtilizationMetrics(OMMetadataManager metadataManager,
+      String omServiceId, String omNodeId) {
     this.metadataManager = metadataManager;
+    sourceName = MetricUtil.getMetricsSourceName(SOURCE, omServiceId, 
omNodeId);
   }
 
-  public static VolumeUtilizationMetrics create(OMMetadataManager 
metadataManager) {
+  public static VolumeUtilizationMetrics create(OMMetadataManager 
metadataManager,
+      String omServiceId, String omNodeId) {
     MetricsSystem ms = DefaultMetricsSystem.instance();
-    return ms.register(SOURCE, "Volume Utilization Metrics", new 
VolumeUtilizationMetrics(metadataManager));
+    VolumeUtilizationMetrics metrics = new VolumeUtilizationMetrics(
+        metadataManager, omServiceId, omNodeId);
+    return ms.register(metrics.sourceName, "Volume Utilization Metrics", 
metrics);
   }
 
   @Override
@@ -82,7 +89,7 @@ public void getMetrics(MetricsCollector collector, boolean 
all) {
 
   public void unRegister() {
     MetricsSystem ms = DefaultMetricsSystem.instance();
-    ms.unregisterSource(SOURCE);
+    ms.unregisterSource(sourceName);
   }
 
   enum VolumeMetricsInfo implements MetricsInfo {
diff --git 
a/hadoop-ozone/ozone-manager/src/test/java/org/apache/hadoop/ozone/om/TestOmSnapshotInternalMetrics.java
 
b/hadoop-ozone/ozone-manager/src/test/java/org/apache/hadoop/ozone/om/TestOmSnapshotInternalMetrics.java
new file mode 100644
index 00000000000..be0fe4e8083
--- /dev/null
+++ 
b/hadoop-ozone/ozone-manager/src/test/java/org/apache/hadoop/ozone/om/TestOmSnapshotInternalMetrics.java
@@ -0,0 +1,57 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.hadoop.ozone.om;
+
+import static org.junit.jupiter.api.Assertions.assertNull;
+import static org.junit.jupiter.api.Assertions.assertSame;
+
+import org.apache.hadoop.metrics2.MetricsSystem;
+import org.apache.hadoop.metrics2.lib.DefaultMetricsSystem;
+import org.junit.jupiter.api.Test;
+
+/**
+ * Tests for {@link OmSnapshotInternalMetrics}.
+ */
+class TestOmSnapshotInternalMetrics {
+
+  @Test
+  void testUnregisterWithMultipleOmNodeIds() {
+    MetricsSystem metricsSystem = 
DefaultMetricsSystem.initialize("TestOmSnapshotInternalMetrics");
+    String firstName = OmSnapshotInternalMetrics.METRICS_SOURCE_NAME + 
"-service1-om1";
+    String secondName = OmSnapshotInternalMetrics.METRICS_SOURCE_NAME + 
"-service1-om2";
+    boolean miniClusterMode = DefaultMetricsSystem.inMiniClusterMode();
+    DefaultMetricsSystem.setMiniClusterMode(true);
+    try {
+      OmSnapshotInternalMetrics first = 
OmSnapshotInternalMetrics.create("service1", "om1");
+      OmSnapshotInternalMetrics second = 
OmSnapshotInternalMetrics.create("service1", "om2");
+      assertSame(first, metricsSystem.getSource(firstName));
+      assertSame(second, metricsSystem.getSource(secondName));
+
+      second.unregister();
+      assertNull(metricsSystem.getSource(secondName));
+      assertSame(first, metricsSystem.getSource(firstName));
+      first.unregister();
+      assertNull(metricsSystem.getSource(firstName));
+    } finally {
+      metricsSystem.unregisterSource(firstName);
+      metricsSystem.unregisterSource(secondName);
+      DefaultMetricsSystem.shutdown();
+      DefaultMetricsSystem.setMiniClusterMode(miniClusterMode);
+    }
+  }
+}
diff --git 
a/hadoop-ozone/ozone-manager/src/test/java/org/apache/hadoop/ozone/om/TestVolumeUtilizationMetrics.java
 
b/hadoop-ozone/ozone-manager/src/test/java/org/apache/hadoop/ozone/om/TestVolumeUtilizationMetrics.java
index d0880ed0c62..fbe03abb0e8 100644
--- 
a/hadoop-ozone/ozone-manager/src/test/java/org/apache/hadoop/ozone/om/TestVolumeUtilizationMetrics.java
+++ 
b/hadoop-ozone/ozone-manager/src/test/java/org/apache/hadoop/ozone/om/TestVolumeUtilizationMetrics.java
@@ -17,6 +17,8 @@
 
 package org.apache.hadoop.ozone.om;
 
+import static org.junit.jupiter.api.Assertions.assertNull;
+import static org.junit.jupiter.api.Assertions.assertSame;
 import static org.mockito.ArgumentMatchers.any;
 import static org.mockito.ArgumentMatchers.anyInt;
 import static org.mockito.ArgumentMatchers.anyLong;
@@ -33,6 +35,8 @@
 import org.apache.hadoop.metrics2.MetricsCollector;
 import org.apache.hadoop.metrics2.MetricsInfo;
 import org.apache.hadoop.metrics2.MetricsRecordBuilder;
+import org.apache.hadoop.metrics2.MetricsSystem;
+import org.apache.hadoop.metrics2.lib.DefaultMetricsSystem;
 import org.apache.hadoop.ozone.om.VolumeUtilizationMetrics.VolumeMetricsInfo;
 import org.apache.hadoop.ozone.om.helpers.OmVolumeArgs;
 import org.junit.jupiter.api.Test;
@@ -81,7 +85,8 @@ void testVolumeUtilizationMetrics() {
     MetricsCollector metricsCollector = mock(MetricsCollector.class);
     when(metricsCollector.addRecord(anyString())).thenReturn(mb);
 
-    VolumeUtilizationMetrics volumeMetrics = new 
VolumeUtilizationMetrics(omMetadataManager);
+    VolumeUtilizationMetrics volumeMetrics = new VolumeUtilizationMetrics(
+        omMetadataManager, "service1", "om1");
     volumeMetrics.getMetrics(metricsCollector, true);
 
     verify(mb, times(1)).tag(VolumeMetricsInfo.VolumeName, VOLUME_NAME_1);
@@ -95,6 +100,34 @@ void testVolumeUtilizationMetrics() {
     verify(mb, times(1)).addGauge(VolumeMetricsInfo.VolumeUsedNamespace, 
USED_NAMESPACE_2);
   }
 
+  @Test
+  void testUnregisterWithMultipleInstances() {
+    MetricsSystem metricsSystem = 
DefaultMetricsSystem.initialize("TestVolumeUtilizationMetrics");
+    String firstName = VolumeUtilizationMetrics.class.getSimpleName() + 
"-service1-om1";
+    String secondName = VolumeUtilizationMetrics.class.getSimpleName() + 
"-service1-om2";
+    boolean miniClusterMode = DefaultMetricsSystem.inMiniClusterMode();
+    DefaultMetricsSystem.setMiniClusterMode(true);
+    try {
+      VolumeUtilizationMetrics first =
+          VolumeUtilizationMetrics.create(mock(OMMetadataManager.class), 
"service1", "om1");
+      VolumeUtilizationMetrics second =
+          VolumeUtilizationMetrics.create(mock(OMMetadataManager.class), 
"service1", "om2");
+      assertSame(first, metricsSystem.getSource(firstName));
+      assertSame(second, metricsSystem.getSource(secondName));
+
+      second.unRegister();
+      assertNull(metricsSystem.getSource(secondName));
+      assertSame(first, metricsSystem.getSource(firstName));
+      first.unRegister();
+      assertNull(metricsSystem.getSource(firstName));
+    } finally {
+      metricsSystem.unregisterSource(firstName);
+      metricsSystem.unregisterSource(secondName);
+      DefaultMetricsSystem.shutdown();
+      DefaultMetricsSystem.setMiniClusterMode(miniClusterMode);
+    }
+  }
+
   private static Map.Entry<CacheKey<String>, CacheValue<OmVolumeArgs>> 
createMockEntry(
       String volumeName, long quotaInBytes, long quotaInNamespace, long 
usedNamespace) {
     Map.Entry<CacheKey<String>, CacheValue<OmVolumeArgs>> entry = 
mock(Map.Entry.class);
diff --git 
a/hadoop-ozone/ozone-manager/src/test/java/org/apache/hadoop/ozone/om/snapshot/SnapshotRequestAndResponseTests.java
 
b/hadoop-ozone/ozone-manager/src/test/java/org/apache/hadoop/ozone/om/snapshot/SnapshotRequestAndResponseTests.java
index 752c47ebee7..c449b308831 100644
--- 
a/hadoop-ozone/ozone-manager/src/test/java/org/apache/hadoop/ozone/om/snapshot/SnapshotRequestAndResponseTests.java
+++ 
b/hadoop-ozone/ozone-manager/src/test/java/org/apache/hadoop/ozone/om/snapshot/SnapshotRequestAndResponseTests.java
@@ -144,7 +144,7 @@ public void baseSetup() throws Exception {
     ozoneManager = mock(OzoneManager.class);
     OzoneConfiguration ozoneConfiguration = new OzoneConfiguration();
     omMetrics = OMMetrics.create(ozoneConfiguration);
-    omSnapshotIntMetrics = OmSnapshotInternalMetrics.create();
+    omSnapshotIntMetrics = OmSnapshotInternalMetrics.create("service1", "om1");
     ozoneConfiguration.set(OMConfigKeys.OZONE_OM_DB_DIRS,
         testDir.getAbsolutePath());
     ozoneConfiguration.set(OzoneConfigKeys.OZONE_METADATA_DIRS,


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

Reply via email to