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

devmadhuu pushed a commit to branch HDDS-11233
in repository https://gitbox.apache.org/repos/asf/ozone.git


The following commit(s) were added to refs/heads/HDDS-11233 by this push:
     new cf2733a9f33 HDDS-17820. Add SCM metrics for storage-tier placement 
failures by requested storage type and reason. (#12079)
cf2733a9f33 is described below

commit cf2733a9f3311fc69a98ea73763baa5600bdd8ee
Author: Devesh Kumar Singh <[email protected]>
AuthorDate: Fri Nov 27 12:33:57 2026 +0530

    HDDS-17820. Add SCM metrics for storage-tier placement failures by 
requested storage type and reason. (#12079)
    
    Co-authored-by: Doroszlai, Attila <[email protected]>
---
 .../hdds/scm/pipeline/SCMPipelineMetrics.java      |  82 ++++++++
 .../pipeline/WritableRatisContainerProvider.java   |   8 +
 .../hadoop/hdds/scm/block/TestBlockManager.java    |  54 +++++
 .../scm/pipeline/TestSCMTierPlacementMetrics.java  | 232 +++++++++++++++++++++
 .../TestWritableRatisContainerProvider.java        | 142 +++++++++++++
 5 files changed, 518 insertions(+)

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 527f62b3854..62d94af017d 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
@@ -17,11 +17,17 @@
 
 package org.apache.hadoop.hdds.scm.pipeline;
 
+import java.io.IOException;
+import java.util.EnumMap;
+import java.util.LinkedHashMap;
 import java.util.Map;
 import java.util.Optional;
 import java.util.concurrent.ConcurrentHashMap;
 import org.apache.hadoop.hdds.annotation.InterfaceAudience;
+import org.apache.hadoop.hdds.client.StorageTier;
+import org.apache.hadoop.hdds.scm.exceptions.SCMException;
 import org.apache.hadoop.metrics2.MetricsCollector;
+import org.apache.hadoop.metrics2.MetricsInfo;
 import org.apache.hadoop.metrics2.MetricsRecordBuilder;
 import org.apache.hadoop.metrics2.MetricsSource;
 import org.apache.hadoop.metrics2.MetricsSystem;
@@ -44,6 +50,12 @@ public final class SCMPipelineMetrics implements 
MetricsSource {
 
   private static final String SOURCE_NAME =
       SCMPipelineMetrics.class.getSimpleName();
+  private static final String UNKNOWN_TIER = "UNKNOWN";
+  private static final MetricsInfo REQUESTED_TIER = 
Interns.info("RequestedTier", "Requested allocation tier");
+  private static final MetricsInfo REASON = Interns.info("Reason", "Tier 
allocation failure category");
+  private static final MetricsInfo TIER_PLACEMENT_FAILURES = 
Interns.info("TierPlacementFailures",
+      "Failed RATIS/standalone tier allocations after retries; no_space 
includes storage-type capacity shortages; "
+          + "no_suitable_node includes pipeline limits");
 
   private MetricsRegistry registry;
   private static SCMPipelineMetrics instance;
@@ -59,11 +71,20 @@ public final class SCMPipelineMetrics implements 
MetricsSource {
   private @Metric MutableCounterLong numPipelineContainSameDatanodes;
   private @Metric MutableRate pipelineCreationLatencyNs;
   private final Map<PipelineID, MutableCounterLong> numBlocksAllocated;
+  // Series are allocated once; concurrent updates only change the thread-safe 
counters.
+  private final Map<String, Map<PlacementFailureReason, MutableCounterLong>> 
tierPlacementFailures =
+      new LinkedHashMap<>();
 
   /** Private constructor. */
   private SCMPipelineMetrics() {
     this.registry = new MetricsRegistry(SOURCE_NAME);
     numBlocksAllocated = new ConcurrentHashMap<>();
+    for (StorageTier tier : StorageTier.values()) {
+      if (tier != StorageTier.EMPTY) {
+        addTierPlacementCounters(tier.name());
+      }
+    }
+    addTierPlacementCounters(UNKNOWN_TIER);
   }
 
   /**
@@ -106,6 +127,67 @@ public void getMetrics(MetricsCollector collector, boolean 
all) {
     pipelineCreationLatencyNs.snapshot(recordBuilder, true);
     numBlocksAllocated
         .forEach((pid, metric) -> metric.snapshot(recordBuilder, true));
+    tierPlacementFailures.forEach((tier, counters) -> 
counters.forEach((reason, counter) ->
+        collector.addRecord(SOURCE_NAME)
+            .tag(REQUESTED_TIER, tier)
+            .tag(REASON, reason.getLabel())
+            .addCounter(TIER_PLACEMENT_FAILURES, counter.value())));
+  }
+
+  private void addTierPlacementCounters(String tier) {
+    Map<PlacementFailureReason, MutableCounterLong> counters = new 
EnumMap<>(PlacementFailureReason.class);
+    for (PlacementFailureReason reason : PlacementFailureReason.values()) {
+      counters.put(reason, new MutableCounterLong(TIER_PLACEMENT_FAILURES, 0));
+    }
+    tierPlacementFailures.put(tier, counters);
+  }
+
+  /**
+   * Counts one unsuccessful RATIS/standalone tier allocation after all 
provider retries. A later allocation on a
+   * fallback tier may still succeed. This does not count background pipeline 
creation or change aggregate counters.
+   * Missing/empty tiers are UNKNOWN. Reasons use SCM result codes, never 
exception messages; no_space includes
+   * storage-type capacity shortages, not just full volumes; no_suitable_node 
includes pipeline limits. Unclassified
+   * failures are other.
+   *
+   * @param tier tier of this allocation attempt, including a fallback tier 
when it is attempted
+   * @param failure last unsuccessful creation/wait operation, or null when no 
structured failure is available
+   */
+  void incTierPlacementFailure(StorageTier tier, IOException failure) {
+    String requestedTier = tier == null || tier == StorageTier.EMPTY ? 
UNKNOWN_TIER : tier.name();
+    
tierPlacementFailures.get(requestedTier).get(PlacementFailureReason.fromException(failure)).incr();
+  }
+
+  enum PlacementFailureReason {
+    NO_SPACE("no_space"),
+    NO_SUITABLE_NODE("no_suitable_node"),
+    OTHER("other");
+
+    private final String label;
+
+    PlacementFailureReason(String label) {
+      this.label = label;
+    }
+
+    String getLabel() {
+      return label;
+    }
+
+    private static PlacementFailureReason fromException(IOException failure) {
+      if (failure instanceof SCMException) {
+        SCMException.ResultCodes code = ((SCMException) failure).getResult();
+        if (code == SCMException.ResultCodes.FAILED_TO_FIND_NODES_WITH_SPACE
+            || code == 
SCMException.ResultCodes.FAILED_TO_FIND_CONTAINER_WITH_SPACE) {
+          return NO_SPACE;
+        }
+        if (code == SCMException.ResultCodes.FAILED_TO_FIND_HEALTHY_NODES
+            || code == SCMException.ResultCodes.FAILED_TO_FIND_SUITABLE_NODE
+            || code == SCMException.ResultCodes.FAILED_TO_FIND_NODE_IN_POOL
+            || code == 
SCMException.ResultCodes.FAILED_TO_FIND_ACTIVE_PIPELINE) {
+          return NO_SUITABLE_NODE;
+        }
+      }
+      return OTHER;
+    }
   }
 
   void createPerPipelineMetrics(Pipeline pipeline) {
diff --git 
a/hadoop-hdds/server-scm/src/main/java/org/apache/hadoop/hdds/scm/pipeline/WritableRatisContainerProvider.java
 
b/hadoop-hdds/server-scm/src/main/java/org/apache/hadoop/hdds/scm/pipeline/WritableRatisContainerProvider.java
index 44dfb771489..20e891bd44b 100644
--- 
a/hadoop-hdds/server-scm/src/main/java/org/apache/hadoop/hdds/scm/pipeline/WritableRatisContainerProvider.java
+++ 
b/hadoop-hdds/server-scm/src/main/java/org/apache/hadoop/hdds/scm/pipeline/WritableRatisContainerProvider.java
@@ -75,6 +75,7 @@ public ContainerInfo getContainer(final long size,
     */
 
     String failureReason = null;
+    IOException allocationFailure = null;
     PipelineNotFoundException missingPipeline = null;
 
     //TODO we need to continue the refactor to use repConfig everywhere
@@ -98,6 +99,7 @@ public ContainerInfo getContainer(final long size,
       pipelineManager.waitPipelineReady(pipeline.getId(), 0);
 
     } catch (SCMException se) {
+      allocationFailure = se;
       LOG.warn("Pipeline creation failed for repConfig: {} storageTier: {} " +
           "Datanodes may be used up. Try to see if any pipeline is in " +
               "ALLOCATED state, and then will wait for it to be OPEN",
@@ -106,6 +108,8 @@ public ContainerInfo getContainer(final long size,
               excludeList,
               Pipeline.PipelineState.ALLOCATED, storageTier);
       if (!allocatedPipelines.isEmpty()) {
+        // Creation may fail while an existing pipeline becomes usable. Do not 
retain that obsolete reason.
+        allocationFailure = null;
         List<PipelineID> allocatedPipelineIDs =
                 allocatedPipelines.stream()
                         .map(p -> p.getId())
@@ -114,12 +118,14 @@ public ContainerInfo getContainer(final long size,
           pipelineManager
                   .waitOnePipelineReady(allocatedPipelineIDs, 0);
         } catch (PipelineNotFoundException e) {
+          allocationFailure = e;
           LOG.warn("Waiting for one of pipelines {} to be OPEN failed. ",
                   allocatedPipelineIDs, e);
           failureReason = "Waiting for one of pipelines to be OPEN failed. "
               + e.getMessage();
           missingPipeline = e;
         } catch (IOException e) {
+          allocationFailure = e;
           LOG.warn("Waiting for one of pipelines {} to be OPEN failed. ",
                   allocatedPipelineIDs, e);
           failureReason = "Waiting for one of pipelines to be OPEN failed. "
@@ -129,6 +135,7 @@ public ContainerInfo getContainer(final long size,
         failureReason = se.getMessage();
       }
     } catch (IOException e) {
+      allocationFailure = e;
       LOG.warn("Pipeline creation failed for repConfig: {} storageTier: {}. "
           + "Retrying get pipelines call once.", repConfig, storageTier, e);
       failureReason = e.getMessage();
@@ -146,6 +153,7 @@ public ContainerInfo getContainer(final long size,
     LOG.error(
         "Unable to allocate a block for the size: {}, repConfig: {}, 
storageTier: {}",
         size, repConfig, storageTier);
+    pipelineManager.getMetrics().incTierPlacementFailure(storageTier, 
allocationFailure);
     String message = "Unable to allocate a container to the block of size: " + 
size
         + ", replicationConfig: " + repConfig
         + ", for storageTier: " + storageTier + ". " + failureReason;
diff --git 
a/hadoop-hdds/server-scm/src/test/java/org/apache/hadoop/hdds/scm/block/TestBlockManager.java
 
b/hadoop-hdds/server-scm/src/test/java/org/apache/hadoop/hdds/scm/block/TestBlockManager.java
index f8b07c7a066..a30aa939cd8 100644
--- 
a/hadoop-hdds/server-scm/src/test/java/org/apache/hadoop/hdds/scm/block/TestBlockManager.java
+++ 
b/hadoop-hdds/server-scm/src/test/java/org/apache/hadoop/hdds/scm/block/TestBlockManager.java
@@ -82,6 +82,7 @@
 import org.apache.hadoop.hdds.scm.pipeline.PipelineID;
 import org.apache.hadoop.hdds.scm.pipeline.PipelineManagerImpl;
 import org.apache.hadoop.hdds.scm.pipeline.PipelineProvider;
+import org.apache.hadoop.hdds.scm.pipeline.SCMPipelineMetrics;
 import org.apache.hadoop.hdds.scm.safemode.SCMSafeModeManager;
 import org.apache.hadoop.hdds.scm.safemode.SCMSafeModeManager.SafeModeStatus;
 import org.apache.hadoop.hdds.scm.server.SCMConfigurator;
@@ -89,6 +90,9 @@
 import org.apache.hadoop.hdds.server.events.EventHandler;
 import org.apache.hadoop.hdds.server.events.EventPublisher;
 import org.apache.hadoop.hdds.server.events.EventQueue;
+import org.apache.hadoop.metrics2.AbstractMetric;
+import org.apache.hadoop.metrics2.impl.MetricsCollectorImpl;
+import org.apache.hadoop.metrics2.impl.MetricsRecordImpl;
 import org.apache.hadoop.ozone.OzoneConsts;
 import org.apache.hadoop.ozone.container.common.SCMTestUtils;
 import org.apache.hadoop.ozone.lease.LeaseManager;
@@ -99,6 +103,8 @@
 import org.junit.jupiter.api.BeforeEach;
 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.ValueSource;
 import org.mockito.Mockito;
 
 /**
@@ -259,6 +265,54 @@ public void testAllocateBlockWithStoragePolicy() throws 
Exception {
     }
   }
 
+  @ParameterizedTest
+  @ValueSource(booleans = {true, false})
+  void testTierFailureIsCountedWhetherFallbackIsAllowed(boolean allowFallback) 
throws Exception {
+    staleDatanodeForStorageType(StorageType.SSD, 
nodeManager.getNodes(NodeStatus.inServiceHealthy()));
+
+    if (allowFallback) {
+      AllocatedBlock block = blockManager.allocateBlock(DEFAULT_BLOCK_SIZE, 
replicationConfig, OzoneConsts.OZONE,
+          new ExcludeList(), OzoneStoragePolicy.HOT, true);
+      assertNotNull(block);
+      assertEquals(StorageTier.DISK, block.getStorageTier());
+      assertTrue(block.isFallBack());
+    } else {
+      assertThrows(IOException.class, () -> 
blockManager.allocateBlock(DEFAULT_BLOCK_SIZE, replicationConfig,
+          OzoneConsts.OZONE, new ExcludeList(), OzoneStoragePolicy.HOT, 
false));
+    }
+    assertTierPlacementFailures(StorageTier.SSD, 1);
+    assertTierPlacementFailures(StorageTier.DISK, 0);
+  }
+
+  @Test
+  void testPreferredAndFallbackTierFailuresAreCountedSeparately() throws 
Exception {
+    List<DatanodeDetails> healthyNodes = 
nodeManager.getNodes(NodeStatus.inServiceHealthy());
+    staleDatanodeForStorageType(StorageType.SSD, healthyNodes);
+    staleDatanodeForStorageType(StorageType.DISK, 
nodeManager.getNodes(NodeStatus.inServiceHealthy()));
+
+    assertThrows(IOException.class, () -> 
blockManager.allocateBlock(DEFAULT_BLOCK_SIZE, replicationConfig,
+        OzoneConsts.OZONE, new ExcludeList(), OzoneStoragePolicy.HOT, true));
+    assertTierPlacementFailures(StorageTier.SSD, 1);
+    assertTierPlacementFailures(StorageTier.DISK, 1);
+    assertTierPlacementFailures(StorageTier.ARCHIVE, 0);
+  }
+
+  private void assertTierPlacementFailures(StorageTier tier, long expected) {
+    MetricsCollectorImpl collector = new MetricsCollectorImpl();
+    SCMPipelineMetrics.create().getMetrics(collector, true);
+    long failures = 0;
+    for (MetricsRecordImpl record : collector.getRecords()) {
+      if (record.tags().stream().anyMatch(t -> 
t.name().equals("RequestedTier") && t.value().equals(tier.name()))) {
+        for (AbstractMetric metric : record.metrics()) {
+          if (metric.name().equals("TierPlacementFailures")) {
+            failures += metric.value().longValue();
+          }
+        }
+      }
+    }
+    assertEquals(expected, failures);
+  }
+
   @Test
   public void testAllocateBlockWithExclusion() throws Exception {
     AllocatedBlock block = null;
diff --git 
a/hadoop-hdds/server-scm/src/test/java/org/apache/hadoop/hdds/scm/pipeline/TestSCMTierPlacementMetrics.java
 
b/hadoop-hdds/server-scm/src/test/java/org/apache/hadoop/hdds/scm/pipeline/TestSCMTierPlacementMetrics.java
new file mode 100644
index 00000000000..39ce64605df
--- /dev/null
+++ 
b/hadoop-hdds/server-scm/src/test/java/org/apache/hadoop/hdds/scm/pipeline/TestSCMTierPlacementMetrics.java
@@ -0,0 +1,232 @@
+/*
+ * 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.assertj.core.api.Assertions.assertThat;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNotSame;
+import static org.junit.jupiter.api.Assertions.assertNull;
+import static org.junit.jupiter.api.Assertions.assertSame;
+
+import java.io.IOException;
+import java.io.StringWriter;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+import java.util.concurrent.Future;
+import java.util.concurrent.TimeUnit;
+import java.util.stream.Stream;
+import org.apache.hadoop.hdds.client.StorageTier;
+import org.apache.hadoop.hdds.scm.exceptions.SCMException;
+import org.apache.hadoop.hdds.scm.exceptions.SCMException.ResultCodes;
+import 
org.apache.hadoop.hdds.scm.pipeline.SCMPipelineMetrics.PlacementFailureReason;
+import org.apache.hadoop.hdds.server.http.PrometheusMetricsSink;
+import org.apache.hadoop.metrics2.AbstractMetric;
+import org.apache.hadoop.metrics2.MetricType;
+import org.apache.hadoop.metrics2.impl.MetricsCollectorImpl;
+import org.apache.hadoop.metrics2.impl.MetricsRecordImpl;
+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.Arguments;
+import org.junit.jupiter.params.provider.EnumSource;
+import org.junit.jupiter.params.provider.MethodSource;
+
+/**
+ * Verifies the published tier-allocation counters alongside existing pipeline 
metrics.
+ */
+class TestSCMTierPlacementMetrics {
+  private SCMPipelineMetrics metrics;
+
+  @BeforeEach
+  void setUp() {
+    SCMPipelineMetrics.unRegister();
+    metrics = SCMPipelineMetrics.create();
+  }
+
+  @AfterEach
+  void tearDown() {
+    SCMPipelineMetrics.unRegister();
+  }
+
+  @ParameterizedTest
+  @MethodSource("failureReasons")
+  void classifiesResultCodesWithoutParsingMessages(IOException failure, 
PlacementFailureReason reason)
+      throws Exception {
+    metrics.incTierPlacementFailure(StorageTier.SSD, failure);
+    String output = prometheusOutput();
+    assertThat(output).contains(series("SSD", reason, 1));
+    assertEquals(1, totalFailures());
+  }
+
+  static Stream<Arguments> failureReasons() {
+    return Stream.of(
+        Arguments.of(new 
SCMException(ResultCodes.FAILED_TO_FIND_NODES_WITH_SPACE), 
PlacementFailureReason.NO_SPACE),
+        Arguments.of(new 
SCMException(ResultCodes.FAILED_TO_FIND_CONTAINER_WITH_SPACE),
+            PlacementFailureReason.NO_SPACE),
+        Arguments.of(new 
SCMException(ResultCodes.FAILED_TO_FIND_HEALTHY_NODES),
+            PlacementFailureReason.NO_SUITABLE_NODE),
+        Arguments.of(new 
SCMException(ResultCodes.FAILED_TO_FIND_SUITABLE_NODE),
+            PlacementFailureReason.NO_SUITABLE_NODE),
+        Arguments.of(new SCMException(ResultCodes.FAILED_TO_FIND_NODE_IN_POOL),
+            PlacementFailureReason.NO_SUITABLE_NODE),
+        Arguments.of(new 
SCMException(ResultCodes.FAILED_TO_FIND_ACTIVE_PIPELINE),
+            PlacementFailureReason.NO_SUITABLE_NODE),
+        Arguments.of(new SCMException(ResultCodes.INTERNAL_ERROR), 
PlacementFailureReason.OTHER),
+        Arguments.of(new SCMException("no space and no suitable node"), 
PlacementFailureReason.OTHER),
+        Arguments.of(new IOException("FAILED_TO_FIND_NODES_WITH_SPACE"), 
PlacementFailureReason.OTHER),
+        Arguments.of(null, PlacementFailureReason.OTHER));
+  }
+
+  @Test
+  void publishesStableReasonLabels() {
+    assertEquals("no_space", PlacementFailureReason.NO_SPACE.getLabel());
+    assertEquals("no_suitable_node", 
PlacementFailureReason.NO_SUITABLE_NODE.getLabel());
+    assertEquals("other", PlacementFailureReason.OTHER.getLabel());
+    assertEquals(3, PlacementFailureReason.values().length);
+  }
+
+  @ParameterizedTest
+  @EnumSource(StorageTier.class)
+  void keepsTierSeriesSeparate(StorageTier tier) throws Exception {
+    metrics.incTierPlacementFailure(tier, null);
+    assertThat(prometheusOutput()).contains(
+        series(tier == StorageTier.EMPTY ? "UNKNOWN" : tier.name(), 
PlacementFailureReason.OTHER, 1));
+    assertEquals(1, totalFailures());
+  }
+
+  @Test
+  void missingTierIsUnknownEvenWhenDefaultIsDisk() throws Exception {
+    metrics.incTierPlacementFailure(null, new 
SCMException(ResultCodes.FAILED_TO_FIND_NODES_WITH_SPACE));
+    assertThat(prometheusOutput()).contains(series("UNKNOWN", 
PlacementFailureReason.NO_SPACE, 1),
+        series("DISK", PlacementFailureReason.NO_SPACE, 0));
+  }
+
+  @Test
+  void exportsBoundedCounterLabelsIncludingZeroSeriesAndPreservesAggregates() 
throws Exception {
+    metrics.incNumPipelineCreationFailed();
+    metrics.incNumPipelineCreationFailed();
+    metrics.incTierPlacementFailure(StorageTier.SSD, new 
SCMException(ResultCodes.FAILED_TO_FIND_NODES_WITH_SPACE));
+    metrics.incTierPlacementFailure(StorageTier.SSD, new 
SCMException(ResultCodes.FAILED_TO_FIND_SUITABLE_NODE));
+    metrics.incTierPlacementFailure(StorageTier.DISK, new 
IOException("key=/volume/bucket/private-key"));
+
+    String output = prometheusOutput();
+    assertThat(output).contains("# TYPE 
scm_pipeline_metrics_tier_placement_failures counter",
+        series("SSD", PlacementFailureReason.NO_SPACE, 1), series("SSD", 
PlacementFailureReason.NO_SUITABLE_NODE, 1),
+        series("SSD", PlacementFailureReason.OTHER, 0), series("DISK", 
PlacementFailureReason.OTHER, 1),
+        series("ARCHIVE", PlacementFailureReason.NO_SPACE, 0), 
series("UNKNOWN", PlacementFailureReason.OTHER, 0),
+        "scm_pipeline_metrics_num_pipeline_creation_failed{} 2");
+    assertThat(output).doesNotContain("private-key", "volume=", "bucket=", 
"pipelineid=");
+
+    int labelledRecords = 0;
+    for (MetricsRecordImpl record : snapshot().getRecords()) {
+      for (AbstractMetric metric : record.metrics()) {
+        if (metric.name().equals("TierPlacementFailures")) {
+          labelledRecords++;
+          assertEquals(MetricType.COUNTER, metric.type());
+          assertThat(record.tags()).extracting(tag -> 
tag.name()).containsExactly("RequestedTier", "Reason");
+        } else {
+          assertThat(record.tags()).isEmpty();
+        }
+      }
+    }
+    assertEquals(12, labelledRecords);
+    assertEquals(3, totalFailures());
+    // Unchanged counters must still be exported on successive scrapes.
+    assertThat(prometheusOutput()).contains(series("SSD", 
PlacementFailureReason.NO_SPACE, 1));
+  }
+
+  @Test
+  void concurrentUpdatesAndScrapesDoNotLoseIncrements() throws Exception {
+    int writers = 8;
+    int increments = 1000;
+    ExecutorService executor = Executors.newFixedThreadPool(writers + 1);
+    try {
+      List<Future<?>> futures = new ArrayList<>();
+      for (int i = 0; i < writers; i++) {
+        futures.add(executor.submit(() -> {
+          for (int j = 0; j < increments; j++) {
+            metrics.incTierPlacementFailure(StorageTier.SSD, null);
+          }
+        }));
+      }
+      futures.add(executor.submit(() -> {
+        for (int i = 0; i < increments; i++) {
+          snapshot();
+        }
+      }));
+      for (Future<?> future : futures) {
+        future.get(30, TimeUnit.SECONDS);
+      }
+    } finally {
+      executor.shutdownNow();
+    }
+    assertEquals((long) writers * increments, totalFailures());
+    assertThat(prometheusOutput()).contains(
+        series("SSD", PlacementFailureReason.OTHER, (long) writers * 
increments));
+  }
+
+  @Test
+  void sharesRegistrationAndResetsWithExistingPipelineMetricsLifecycle() {
+    assertSame(metrics, SCMPipelineMetrics.create());
+    assertSame(metrics, 
DefaultMetricsSystem.instance().getSource("SCMPipelineMetrics"));
+    metrics.incTierPlacementFailure(StorageTier.SSD, null);
+    assertEquals(1, totalFailures());
+    SCMPipelineMetrics.unRegister();
+    
assertNull(DefaultMetricsSystem.instance().getSource("SCMPipelineMetrics"));
+    SCMPipelineMetrics restarted = SCMPipelineMetrics.create();
+    assertNotSame(metrics, restarted);
+    metrics = restarted;
+    assertEquals(0, totalFailures());
+  }
+
+  private MetricsCollectorImpl snapshot() {
+    MetricsCollectorImpl collector = new MetricsCollectorImpl();
+    metrics.getMetrics(collector, true);
+    return collector;
+  }
+
+  private long totalFailures() {
+    long count = 0;
+    for (MetricsRecordImpl record : snapshot().getRecords()) {
+      for (AbstractMetric metric : record.metrics()) {
+        if (metric.name().equals("TierPlacementFailures")) {
+          count += metric.value().longValue();
+        }
+      }
+    }
+    return count;
+  }
+
+  private String prometheusOutput() throws IOException {
+    PrometheusMetricsSink sink = new PrometheusMetricsSink("scm");
+    snapshot().getRecords().forEach(sink::putMetrics);
+    sink.flush();
+    StringWriter writer = new StringWriter();
+    sink.writeMetrics(writer);
+    return writer.toString();
+  }
+
+  private static String series(String tier, PlacementFailureReason reason, 
long value) {
+    return "scm_pipeline_metrics_tier_placement_failures{requestedtier=\"" + 
tier
+        + "\",reason=\"" + reason.getLabel() + "\"} " + value;
+  }
+}
diff --git 
a/hadoop-hdds/server-scm/src/test/java/org/apache/hadoop/hdds/scm/pipeline/TestWritableRatisContainerProvider.java
 
b/hadoop-hdds/server-scm/src/test/java/org/apache/hadoop/hdds/scm/pipeline/TestWritableRatisContainerProvider.java
index 6c5510f1033..59e20eeaff8 100644
--- 
a/hadoop-hdds/server-scm/src/test/java/org/apache/hadoop/hdds/scm/pipeline/TestWritableRatisContainerProvider.java
+++ 
b/hadoop-hdds/server-scm/src/test/java/org/apache/hadoop/hdds/scm/pipeline/TestWritableRatisContainerProvider.java
@@ -26,8 +26,10 @@
 import static org.junit.jupiter.api.Assertions.assertEquals;
 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.mockito.ArgumentMatchers.any;
 import static org.mockito.ArgumentMatchers.eq;
+import static org.mockito.Mockito.doThrow;
 import static org.mockito.Mockito.never;
 import static org.mockito.Mockito.times;
 import static org.mockito.Mockito.verify;
@@ -47,10 +49,18 @@
 import org.apache.hadoop.hdds.scm.container.ContainerManager;
 import org.apache.hadoop.hdds.scm.container.common.helpers.ExcludeList;
 import org.apache.hadoop.hdds.scm.exceptions.SCMException;
+import org.apache.hadoop.hdds.scm.exceptions.SCMException.ResultCodes;
 import 
org.apache.hadoop.hdds.scm.pipeline.choose.algorithms.RandomPipelineChoosePolicy;
+import org.apache.hadoop.metrics2.AbstractMetric;
+import org.apache.hadoop.metrics2.impl.MetricsCollectorImpl;
+import org.apache.hadoop.metrics2.impl.MetricsRecordImpl;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
 import org.junit.jupiter.api.RepeatedTest;
 import org.junit.jupiter.api.Test;
 import org.junit.jupiter.api.extension.ExtendWith;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.CsvSource;
 import org.mockito.Mock;
 import org.mockito.junit.jupiter.MockitoExtension;
 import org.mockito.junit.jupiter.MockitoSettings;
@@ -76,6 +86,17 @@ class TestWritableRatisContainerProvider {
   @Mock
   private ContainerManager containerManager;
 
+  @BeforeEach
+  void resetMetrics() {
+    SCMPipelineMetrics.unRegister();
+    when(pipelineManager.getMetrics()).thenReturn(SCMPipelineMetrics.create());
+  }
+
+  @AfterEach
+  void unregisterMetrics() {
+    SCMPipelineMetrics.unRegister();
+  }
+
   @Test
   void returnsExistingContainer() throws Exception {
     Pipeline pipeline = MockPipeline.createPipeline(3);
@@ -88,6 +109,9 @@ void returnsExistingContainer() throws Exception {
 
     assertSame(existingContainer, container);
     verifyPipelineNotCreated();
+    assertFailureCount("no_space", 0);
+    assertFailureCount("no_suitable_node", 0);
+    assertFailureCount("other", 0);
   }
 
   @RepeatedTest(100)
@@ -114,6 +138,7 @@ void createsNewContainerIfNoneFound() throws Exception {
 
     assertSame(newContainer, container);
     verifyPipelineCreated();
+    assertFailureCount("other", 0);
   }
 
   @Test
@@ -125,6 +150,123 @@ void failsIfContainerCannotBeCreated() throws Exception {
             CONTAINER_SIZE, REPLICATION_CONFIG, OWNER, NO_EXCLUSION, 
StorageTier.getDefaultTier()));
 
     verifyPipelineCreated();
+    assertFailureCount("no_suitable_node", 1);
+  }
+
+  @ParameterizedTest
+  @CsvSource({"FAILED_TO_FIND_NODES_WITH_SPACE, no_space", 
"FAILED_TO_FIND_HEALTHY_NODES, no_suitable_node",
+      "INTERNAL_ERROR, other"})
+  void countsOneTerminalFailureAndPreservesException(ResultCodes code, String 
reason) throws Exception {
+    when(pipelineManager.createPipeline(REPLICATION_CONFIG, 
StorageTier.getDefaultTier()))
+        .thenThrow(new SCMException("original failure", code));
+
+    IOException failure = assertThrows(IOException.class, () -> 
createSubject().getContainer(
+        CONTAINER_SIZE, REPLICATION_CONFIG, OWNER, NO_EXCLUSION, 
StorageTier.getDefaultTier()));
+
+    assertEquals(IOException.class, failure.getClass());
+    assertEquals("Unable to allocate a container to the block of size: " + 
CONTAINER_SIZE
+        + ", replicationConfig: " + REPLICATION_CONFIG + ", for storageTier: " 
+ StorageTier.getDefaultTier()
+        + ". original failure", failure.getMessage());
+    assertFailureCount(reason, 1);
+    verifyPipelineCreated();
+  }
+
+  @Test
+  void successfulRetryDoesNotCountCreationFailure() throws Exception {
+    Pipeline pipeline = MockPipeline.createPipeline(3);
+    ContainerInfo expected = pipelineHasContainer(pipeline);
+    throwWhenCreatePipeline();
+    when(pipelineManager.getPipelines(REPLICATION_CONFIG, OPEN, emptySet(), 
emptySet(), StorageTier.getDefaultTier()))
+        .thenReturn(emptyList()).thenReturn(new 
ArrayList<>(singletonList(pipeline)));
+
+    assertSame(expected, createSubject().getContainer(
+        CONTAINER_SIZE, REPLICATION_CONFIG, OWNER, NO_EXCLUSION, 
StorageTier.getDefaultTier()));
+    assertFailureCount("no_suitable_node", 0);
+    assertFailureCount("other", 0);
+    verifyPipelineCreated();
+  }
+
+  @Test
+  void successfulWaitForAllocatedPipelineDoesNotCountFailure() throws 
Exception {
+    Pipeline pipeline = MockPipeline.createPipeline(3);
+    ContainerInfo expected = pipelineHasContainer(pipeline);
+    throwWhenCreatePipeline();
+    when(pipelineManager.getPipelines(REPLICATION_CONFIG, 
Pipeline.PipelineState.ALLOCATED,
+        emptySet(), emptySet(), 
StorageTier.getDefaultTier())).thenReturn(singletonList(pipeline));
+    when(pipelineManager.getPipelines(REPLICATION_CONFIG, OPEN, emptySet(), 
emptySet(), StorageTier.getDefaultTier()))
+        .thenReturn(emptyList()).thenReturn(new 
ArrayList<>(singletonList(pipeline)));
+
+    assertSame(expected, createSubject().getContainer(
+        CONTAINER_SIZE, REPLICATION_CONFIG, OWNER, NO_EXCLUSION, 
StorageTier.getDefaultTier()));
+    
verify(pipelineManager).waitOnePipelineReady(singletonList(pipeline.getId()), 
0);
+    assertFailureCount("no_suitable_node", 0);
+    assertFailureCount("other", 0);
+  }
+
+  @Test
+  void waitFailureReplacesEarlierPlacementReason() throws Exception {
+    Pipeline pipeline = MockPipeline.createPipeline(3);
+    throwWhenCreatePipeline();
+    when(pipelineManager.getPipelines(REPLICATION_CONFIG, 
Pipeline.PipelineState.ALLOCATED,
+        emptySet(), emptySet(), 
StorageTier.getDefaultTier())).thenReturn(singletonList(pipeline));
+    doThrow(new IOException("wait timed out")).when(pipelineManager)
+        .waitOnePipelineReady(singletonList(pipeline.getId()), 0);
+
+    IOException failure = assertThrows(IOException.class, () -> 
createSubject().getContainer(
+        CONTAINER_SIZE, REPLICATION_CONFIG, OWNER, NO_EXCLUSION, 
StorageTier.getDefaultTier()));
+    assertTrue(failure.getMessage().endsWith("Waiting for one of pipelines to 
be OPEN failed. wait timed out"));
+    assertFailureCount("other", 1);
+    assertFailureCount("no_suitable_node", 0);
+  }
+
+  @Test
+  void successfulWaitWithoutContainerDoesNotReuseObsoletePlacementReason() 
throws Exception {
+    Pipeline pipeline = MockPipeline.createPipeline(3);
+    throwWhenCreatePipeline();
+    when(pipelineManager.getPipelines(REPLICATION_CONFIG, 
Pipeline.PipelineState.ALLOCATED,
+        emptySet(), emptySet(), 
StorageTier.getDefaultTier())).thenReturn(singletonList(pipeline));
+
+    assertThrows(IOException.class, () -> createSubject().getContainer(
+        CONTAINER_SIZE, REPLICATION_CONFIG, OWNER, NO_EXCLUSION, 
StorageTier.getDefaultTier()));
+    assertFailureCount("other", 1);
+    assertFailureCount("no_suitable_node", 0);
+  }
+
+  @Test
+  void countsReadinessTimeoutOnce() throws Exception {
+    Pipeline pipeline = MockPipeline.createPipeline(3);
+    when(pipelineManager.createPipeline(REPLICATION_CONFIG, 
StorageTier.getDefaultTier())).thenReturn(pipeline);
+    doThrow(new IOException("pipeline not 
ready")).when(pipelineManager).waitPipelineReady(pipeline.getId(), 0);
+
+    assertThrows(IOException.class, () -> createSubject().getContainer(
+        CONTAINER_SIZE, REPLICATION_CONFIG, OWNER, NO_EXCLUSION, 
StorageTier.getDefaultTier()));
+    assertFailureCount("other", 1);
+    verifyPipelineCreated();
+  }
+
+  @Test
+  void countsNoContainerAfterSuccessfulPipelineCreationAsOther() throws 
Exception {
+    when(pipelineManager.createPipeline(REPLICATION_CONFIG, 
StorageTier.getDefaultTier()))
+        .thenReturn(MockPipeline.createPipeline(3));
+
+    assertThrows(IOException.class, () -> createSubject().getContainer(
+        CONTAINER_SIZE, REPLICATION_CONFIG, OWNER, NO_EXCLUSION, 
StorageTier.getDefaultTier()));
+    assertFailureCount("other", 1);
+    verifyPipelineCreated();
+  }
+
+  private void assertFailureCount(String reason, long expected) {
+    MetricsCollectorImpl collector = new MetricsCollectorImpl();
+    SCMPipelineMetrics.create().getMetrics(collector, true);
+    MetricsRecordImpl record = collector.getRecords().stream()
+        .filter(r -> r.tags().stream().anyMatch(t -> 
t.name().equals("RequestedTier")
+            && t.value().equals(StorageTier.getDefaultTier().name())))
+        .filter(r -> r.tags().stream().anyMatch(t -> t.name().equals("Reason") 
&& t.value().equals(reason)))
+        .findFirst().orElseThrow(AssertionError::new);
+    for (AbstractMetric metric : record.metrics()) {
+      assertEquals("TierPlacementFailures", metric.name());
+      assertEquals(expected, metric.value().longValue());
+    }
   }
 
   @Test


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

Reply via email to