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 c6cfa43adef HDDS-17584. Add per-storage-type ContainerBalancer
assessment and estimation. (#11866)
c6cfa43adef is described below
commit c6cfa43adef6cbb355bd9f3d002b31841981e7eb
Author: Devesh Kumar Singh <[email protected]>
AuthorDate: Sun Nov 15 17:02:34 2026 +0530
HDDS-17584. Add per-storage-type ContainerBalancer assessment and
estimation. (#11866)
---
.../balancer/ContainerBalancerAdvisor.java | 22 +-
.../balancer/ContainerBalancerClusterAnalyzer.java | 112 +++++++++-
.../balancer/ContainerBalancerClusterSnapshot.java | 172 +++++++++++++--
.../container/balancer/StorageTypeSnapshot.java | 139 ++++++++++++
.../balancer/TestContainerBalancerAdvisor.java | 64 ++++++
.../TestContainerBalancerClusterAnalyzer.java | 239 +++++++++++++++++++++
.../docs/content/feature/ContainerBalancer.md | 24 +++
.../interface-client/src/main/proto/hdds.proto | 12 ++
.../hadoop/hdds/scm/node/DatanodeUsageInfo.java | 64 ++++++
.../hdds/scm/node/TestDatanodeUsageInfo.java | 118 ++++++++++
.../cli/ContainerBalancerAssessmentSubcommand.java | 190 +++++++++++-----
.../hdds/scm/cli/ContainerBalancerCommands.java | 5 +
.../TestContainerBalancerAssessmentSubcommand.java | 165 ++++++++++++++
.../scm/cli/TestContainerBalancerSubCommand.java | 34 +++
.../hadoop/ozone/recon/TestReconAsPassiveScm.java | 8 +-
.../hadoop/hdds/scm/TestContainerOperations.java | 12 ++
16 files changed, 1301 insertions(+), 79 deletions(-)
diff --git
a/hadoop-hdds/common/src/main/java/org/apache/hadoop/hdds/scm/container/balancer/ContainerBalancerAdvisor.java
b/hadoop-hdds/common/src/main/java/org/apache/hadoop/hdds/scm/container/balancer/ContainerBalancerAdvisor.java
index b7ba0b025cf..a55e0547a40 100644
---
a/hadoop-hdds/common/src/main/java/org/apache/hadoop/hdds/scm/container/balancer/ContainerBalancerAdvisor.java
+++
b/hadoop-hdds/common/src/main/java/org/apache/hadoop/hdds/scm/container/balancer/ContainerBalancerAdvisor.java
@@ -147,13 +147,23 @@ private static ContainerBalancerEstimation
estimateForProfile(OzoneConfiguration
int[] involved =
computeInvolvedDatanodeCounts(snapshot.getSourceCount(),
snapshot.getTargetCount(), maxInvolved);
- long bytesToMove = snapshot.getBytesToMove();
+ long bytesToMove = snapshot.getTotalBytesToMove();
long perIterationBytes = computePerIterationBytes(
bytesToMove,
maxSizeToMovePerIteration,
maxSizeLeavingSource,
maxSizeEnteringTarget,
involved);
+ if (!snapshot.getStorageTypeSnapshots().isEmpty()) {
+ long perIterationBytesAcrossStorageTypes = 0;
+ for (StorageTypeSnapshot typeSnapshot :
snapshot.getStorageTypeSnapshots().values()) {
+ perIterationBytesAcrossStorageTypes +=
Math.min(typeSnapshot.getBytesToMove(), Math.min(
+ typeSnapshot.getSourceCount() * maxSizeLeavingSource,
+ typeSnapshot.getTargetCount() * maxSizeEnteringTarget));
+ }
+ // The shared datanode/traffic caps above still apply across all
types; do not grant each type a new budget.
+ perIterationBytes = Math.min(perIterationBytes,
perIterationBytesAcrossStorageTypes);
+ }
long estimatedIterations = computeEstimatedIterations(perIterationBytes,
bytesToMove);
long cycleTimeMillis = computeCycleTimeMillis(moveTimeoutMillis,
balancingIntervalMillis);
long estimatedDurationMillis = estimatedIterations * cycleTimeMillis;
@@ -246,13 +256,21 @@ private static long minPositive(long... values) {
}
private static void
validateSnapshotForEstimation(ContainerBalancerClusterSnapshot snapshot) {
+ if (snapshot.hasIncompleteStorageTypeUsage()) {
+ throw new IllegalArgumentException("Per-storage-type estimates require
storage-type usage from all eligible "
+ + "datanodes. Some datanodes report missing or incomplete
storage-type usage.");
+ }
+ if (!snapshot.getStorageTypeSnapshots().isEmpty() &&
snapshot.getTotalBytesToMove() <= 0) {
+ throw new IllegalArgumentException(
+ "No bytes to move between source and target datanodes of the same
storage type.");
+ }
if (snapshot.getSourceCount() < 1) {
throw new IllegalArgumentException("No over-utilized datanodes (sources)
found.");
}
if (snapshot.getTargetCount() < 1) {
throw new IllegalArgumentException("No under-utilized datanodes
(targets) found.");
}
- if (snapshot.getBytesToMove() <= 0) {
+ if (snapshot.getTotalBytesToMove() <= 0) {
throw new IllegalArgumentException("No bytes to move.");
}
if (snapshot.getTotalEligibleDatanodes() < 2) {
diff --git
a/hadoop-hdds/common/src/main/java/org/apache/hadoop/hdds/scm/container/balancer/ContainerBalancerClusterAnalyzer.java
b/hadoop-hdds/common/src/main/java/org/apache/hadoop/hdds/scm/container/balancer/ContainerBalancerClusterAnalyzer.java
index a0a79e4be66..7645a55e905 100644
---
a/hadoop-hdds/common/src/main/java/org/apache/hadoop/hdds/scm/container/balancer/ContainerBalancerClusterAnalyzer.java
+++
b/hadoop-hdds/common/src/main/java/org/apache/hadoop/hdds/scm/container/balancer/ContainerBalancerClusterAnalyzer.java
@@ -20,11 +20,18 @@
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
+import java.util.EnumMap;
+import java.util.HashMap;
+import java.util.HashSet;
import java.util.List;
+import java.util.Map;
import java.util.Set;
+import org.apache.hadoop.fs.StorageType;
import org.apache.hadoop.hdds.HddsUtils;
+import org.apache.hadoop.hdds.client.StorageTypeUtils;
import org.apache.hadoop.hdds.protocol.DatanodeDetails;
import org.apache.hadoop.hdds.protocol.proto.HddsProtos.DatanodeUsageInfoProto;
+import
org.apache.hadoop.hdds.protocol.proto.HddsProtos.StorageTypeUsageInfoProto;
import
org.apache.hadoop.hdds.scm.container.balancer.ContainerBalancerClusterSnapshot.NodeUtilization;
/**
@@ -144,6 +151,33 @@ public static ContainerBalancerClusterSnapshot analyze(
}
List<DatanodeUsageInfoProto> eligible = filterEligibleNodes(nodes,
includeNodes, excludeNodes);
+ Map<StorageType, List<DatanodeUsageInfoProto>> byType = new
EnumMap<>(StorageType.class);
+ boolean incomplete = false;
+ for (DatanodeUsageInfoProto node : eligible) {
+ long reportedCapacity = 0;
+ for (StorageTypeUsageInfoProto usage : node.getStorageTypeUsageList()) {
+ if (!usage.hasStorageType() || !usage.hasRemaining() ||
usage.getCapacity() <= 0) {
+ continue;
+ }
+ reportedCapacity += usage.getCapacity();
+ StorageType type =
StorageTypeUtils.getFromProtobuf(usage.getStorageType());
+ byType.computeIfAbsent(type, ignored -> new
ArrayList<>()).add(node.toBuilder().clearStorageTypeUsage()
+
.setCapacity(usage.getCapacity()).setUsed(usage.getUsed()).setRemaining(usage.getRemaining()).build());
+ }
+ incomplete |= reportedCapacity != node.getCapacity();
+ }
+ ContainerBalancerClusterSnapshot overall = analyzeAggregate(eligible,
thresholdRatio, topNodeLimit, null);
+ if (byType.isEmpty()) {
+ return overall;
+ }
+ Map<StorageType, StorageTypeSnapshot> snapshots = new
EnumMap<>(StorageType.class);
+ byType.forEach((type, usages) -> snapshots.put(type,
+ new StorageTypeSnapshot(type, analyzeAggregate(usages, thresholdRatio,
topNodeLimit, type))));
+ return combineStorageTypes(overall, snapshots, topNodeLimit, incomplete);
+ }
+
+ private static ContainerBalancerClusterSnapshot
analyzeAggregate(List<DatanodeUsageInfoProto> eligible,
+ double thresholdRatio, int topNodeLimit, StorageType storageType) {
if (eligible.isEmpty()) {
return emptySnapshot(thresholdRatio);
}
@@ -159,6 +193,8 @@ public static ContainerBalancerClusterSnapshot analyze(
long clusterCapacityBytes = 0;
long totalOverUtilizedBytes = 0;
long totalUnderUtilizedBytes = 0;
+ Set<String> sourceDatanodes = new HashSet<>();
+ Set<String> targetDatanodes = new HashSet<>();
for (DatanodeUsageInfoProto node : eligible) {
long capacity = node.getCapacity();
@@ -168,13 +204,20 @@ public static ContainerBalancerClusterSnapshot analyze(
maxUtilization = Math.max(maxUtilization, utilization);
minUtilization = Math.min(minUtilization, utilization);
+ if (capacity <= 0) {
+ continue;
+ }
+
String hostname = getDisplayHostname(node);
+ String id =
DatanodeDetails.getFromProtoBuf(node.getNode()).getID().toString();
if (isOverUtilized(utilization, upperLimit)) {
totalOverUtilizedBytes += overUtilizedBytes(capacity, utilization,
upperLimit);
- sources.add(new NodeUtilization(hostname, utilization));
+ sources.add(new NodeUtilization(hostname, utilization, id,
storageType));
+ sourceDatanodes.add(id);
} else if (isUnderUtilized(utilization, lowerLimit)) {
totalUnderUtilizedBytes += underUtilizedBytes(capacity, utilization,
lowerLimit);
- targets.add(new NodeUtilization(hostname, utilization));
+ targets.add(new NodeUtilization(hostname, utilization, id,
storageType));
+ targetDatanodes.add(id);
}
}
@@ -195,12 +238,69 @@ public static ContainerBalancerClusterSnapshot analyze(
.setTargetCount(targets.size())
.setTotalOverUtilizedBytes(totalOverUtilizedBytes)
.setTotalUnderUtilizedBytes(totalUnderUtilizedBytes)
+ .setTotalBytesToMove(
+ storageType != null && (sources.isEmpty() || targets.isEmpty()) ?
0 : totalOverUtilizedBytes)
+ .setSourceDatanodes(sourceDatanodes)
+ .setTargetDatanodes(targetDatanodes)
.setImbalance(imbalance)
- .setTopSourceNodes(topNodes(sources, topNodeLimit))
- .setBottomTargetNodes(topNodes(targets, topNodeLimit))
+ .setTopSourceNodesAcrossStorageTypes(topNodes(sources, topNodeLimit))
+ .setBottomTargetNodesAcrossStorageTypes(topNodes(targets,
topNodeLimit))
.build();
}
+ private static ContainerBalancerClusterSnapshot
combineStorageTypes(ContainerBalancerClusterSnapshot overall,
+ Map<StorageType, StorageTypeSnapshot> snapshots, int topNodeLimit,
boolean incomplete) {
+ Set<String> sources = new HashSet<>();
+ Set<String> targets = new HashSet<>();
+ Map<String, NodeUtilization> topSources = new HashMap<>();
+ Map<String, NodeUtilization> bottomTargets = new HashMap<>();
+ long overBytes = 0, underBytes = 0, bytesToMove = 0;
+ double maxImbalance = -1;
+ StorageType mostImbalancedStorageType = null;
+ for (StorageTypeSnapshot snapshot : snapshots.values()) {
+ // Combined node summaries describe the types contributing to the
movement estimate.
+ if (snapshot.getBytesToMove() > 0) {
+ sources.addAll(snapshot.getSourceDatanodes());
+ targets.addAll(snapshot.getTargetDatanodes());
+ for (NodeUtilization node : snapshot.getTopSourceNodes()) {
+ topSources.merge(node.getDatanodeId(), node,
+ (a, b) -> a.getUtilization() >= b.getUtilization() ? a : b);
+ }
+ for (NodeUtilization node : snapshot.getBottomTargetNodes()) {
+ bottomTargets.merge(node.getDatanodeId(), node,
+ (a, b) -> a.getUtilization() <= b.getUtilization() ? a : b);
+ }
+ }
+ overBytes += snapshot.getTotalOverUtilizedBytes();
+ underBytes += snapshot.getTotalUnderUtilizedBytes();
+ bytesToMove += snapshot.getBytesToMove();
+ if (snapshot.getImbalance() > maxImbalance) {
+ maxImbalance = snapshot.getImbalance();
+ mostImbalancedStorageType = snapshot.getStorageType();
+ }
+ }
+ List<NodeUtilization> sourceNodes = new ArrayList<>(topSources.values());
+
sourceNodes.sort(Comparator.comparingDouble(NodeUtilization::getUtilization).reversed()
+ .thenComparing(NodeUtilization::getDatanodeId));
+ List<NodeUtilization> targetNodes = new
ArrayList<>(bottomTargets.values());
+
targetNodes.sort(Comparator.comparingDouble(NodeUtilization::getUtilization)
+ .thenComparing(NodeUtilization::getDatanodeId));
+ return ContainerBalancerClusterSnapshot.newBuilder()
+ .setTotalEligibleDatanodes(overall.getTotalEligibleDatanodes())
+ .setClusterAvgUtilization(overall.getClusterAvgUtilization())
+ .setClusterCapacityBytes(overall.getClusterCapacityBytes())
+
.setUpperLimit(overall.getUpperLimit()).setLowerLimit(overall.getLowerLimit())
+
.setMaxUtilization(overall.getMaxUtilization()).setMinUtilization(overall.getMinUtilization())
+ .setImbalance(overall.getImbalance()).setMaxImbalance(maxImbalance)
+ .setMostImbalancedStorageType(mostImbalancedStorageType)
+ .setSourceCount(sources.size()).setTargetCount(targets.size())
+ .setSourceDatanodes(sources).setTargetDatanodes(targets)
+
.setTotalOverUtilizedBytes(overBytes).setTotalUnderUtilizedBytes(underBytes).setTotalBytesToMove(bytesToMove)
+ .setTopSourceNodesAcrossStorageTypes(topNodes(sourceNodes,
topNodeLimit))
+ .setBottomTargetNodesAcrossStorageTypes(topNodes(targetNodes,
topNodeLimit))
+
.setStorageTypeSnapshots(snapshots).setIncompleteStorageTypeUsage(incomplete).build();
+ }
+
/**
* Function that returns whether a datanode should be excluded from cluster
analysis.
* A datanode is excluded if it appears in excludeNodes set, or if
@@ -292,8 +392,8 @@ private static ContainerBalancerClusterSnapshot
emptySnapshot(double thresholdRa
.setTotalOverUtilizedBytes(0)
.setTotalUnderUtilizedBytes(0)
.setImbalance(0)
- .setTopSourceNodes(Collections.emptyList())
- .setBottomTargetNodes(Collections.emptyList())
+ .setTopSourceNodesAcrossStorageTypes(Collections.emptyList())
+ .setBottomTargetNodesAcrossStorageTypes(Collections.emptyList())
.build();
}
}
diff --git
a/hadoop-hdds/common/src/main/java/org/apache/hadoop/hdds/scm/container/balancer/ContainerBalancerClusterSnapshot.java
b/hadoop-hdds/common/src/main/java/org/apache/hadoop/hdds/scm/container/balancer/ContainerBalancerClusterSnapshot.java
index 7c74c16763e..967b5d35457 100644
---
a/hadoop-hdds/common/src/main/java/org/apache/hadoop/hdds/scm/container/balancer/ContainerBalancerClusterSnapshot.java
+++
b/hadoop-hdds/common/src/main/java/org/apache/hadoop/hdds/scm/container/balancer/ContainerBalancerClusterSnapshot.java
@@ -18,11 +18,20 @@
package org.apache.hadoop.hdds.scm.container.balancer;
import java.util.Collections;
+import java.util.EnumMap;
+import java.util.HashSet;
import java.util.List;
+import java.util.Map;
import java.util.Objects;
+import java.util.Set;
+import org.apache.hadoop.fs.StorageType;
/**
* Point-in-time cluster imbalance view built from datanode usage protos.
+ * Utilization and limits describe whole datanodes. When storage-type reports
are available,
+ * movement totals and source/target datanode sets combine the per-type
results; a datanode is counted once.
+ * Combined source/target counts and lists include only types with a positive
movement estimate.
+ * Per-type snapshots retain all nodes outside their utilization limits.
*/
public final class ContainerBalancerClusterSnapshot {
@@ -38,12 +47,17 @@ public final class ContainerBalancerClusterSnapshot {
private final long totalOverUtilizedBytes;
private final long totalUnderUtilizedBytes;
- // bytesToMove has same value as totalOverUtilizedBytes. The analyzer sets it
- // once via setTotalOverUtilizedBytes(), bytesToMove is assigned here for
assessment output.
- private final long bytesToMove;
+ // Legacy snapshots use totalOverUtilizedBytes. Typed snapshots exclude
storage types without a source/target pair.
+ private final long totalBytesToMove;
private final double imbalance;
- private final List<NodeUtilization> topSourceNodes;
- private final List<NodeUtilization> bottomTargetNodes;
+ private final double maxImbalance;
+ private final StorageType mostImbalancedStorageType;
+ private final List<NodeUtilization> topSourceNodesAcrossStorageTypes;
+ private final List<NodeUtilization> bottomTargetNodesAcrossStorageTypes;
+ private final Map<StorageType, StorageTypeSnapshot> storageTypeSnapshots;
+ private final Set<String> sourceDatanodes;
+ private final Set<String> targetDatanodes;
+ private final boolean incompleteStorageTypeUsage;
private ContainerBalancerClusterSnapshot(Builder b) {
this.totalEligibleDatanodes = b.totalEligibleDatanodes;
@@ -57,12 +71,20 @@ private ContainerBalancerClusterSnapshot(Builder b) {
this.targetCount = b.targetCount;
this.totalOverUtilizedBytes = b.totalOverUtilizedBytes;
this.totalUnderUtilizedBytes = b.totalUnderUtilizedBytes;
- this.bytesToMove = b.totalOverUtilizedBytes;
+ this.totalBytesToMove = b.totalBytesToMove == null ?
b.totalOverUtilizedBytes : b.totalBytesToMove;
this.imbalance = b.imbalance;
- this.topSourceNodes = Collections.unmodifiableList(
- Objects.requireNonNull(b.topSourceNodes));
- this.bottomTargetNodes = Collections.unmodifiableList(
- Objects.requireNonNull(b.bottomTargetNodes));
+ this.maxImbalance = b.maxImbalance == null ? b.imbalance : b.maxImbalance;
+ this.mostImbalancedStorageType = b.mostImbalancedStorageType;
+ this.topSourceNodesAcrossStorageTypes = Collections.unmodifiableList(
+ Objects.requireNonNull(b.topSourceNodesAcrossStorageTypes));
+ this.bottomTargetNodesAcrossStorageTypes = Collections.unmodifiableList(
+ Objects.requireNonNull(b.bottomTargetNodesAcrossStorageTypes));
+ Map<StorageType, StorageTypeSnapshot> byType = new
EnumMap<>(StorageType.class);
+ byType.putAll(b.storageTypeSnapshots);
+ this.storageTypeSnapshots = Collections.unmodifiableMap(byType);
+ this.sourceDatanodes = Collections.unmodifiableSet(new
HashSet<>(b.sourceDatanodes));
+ this.targetDatanodes = Collections.unmodifiableSet(new
HashSet<>(b.targetDatanodes));
+ this.incompleteStorageTypeUsage = b.incompleteStorageTypeUsage;
}
public int getTotalEligibleDatanodes() {
@@ -109,20 +131,62 @@ public long getTotalUnderUtilizedBytes() {
return totalUnderUtilizedBytes;
}
+ /** Returns the combined movement total; retained for existing callers. */
public long getBytesToMove() {
- return bytesToMove;
+ return getTotalBytesToMove();
}
+ public long getTotalBytesToMove() {
+ return totalBytesToMove;
+ }
+
+ /** Returns the largest per-type imbalance, or whole-datanode imbalance for
legacy reports. */
+ public double getMaxImbalance() {
+ return maxImbalance;
+ }
+
+ /** Returns the storage type with the largest imbalance, or null for legacy
reports. */
+ public StorageType getMostImbalancedStorageType() {
+ return mostImbalancedStorageType;
+ }
+
+ /** Returns the difference between the highest and lowest whole-datanode
utilization. */
public double getImbalance() {
return imbalance;
}
+ /** Returns source nodes across storage types, or whole-datanode sources for
legacy reports. */
public List<NodeUtilization> getTopSourceNodes() {
- return topSourceNodes;
+ return getTopSourceNodesAcrossStorageTypes();
}
+ public List<NodeUtilization> getTopSourceNodesAcrossStorageTypes() {
+ return topSourceNodesAcrossStorageTypes;
+ }
+
+ /** Returns target nodes across storage types, or whole-datanode targets for
legacy reports. */
public List<NodeUtilization> getBottomTargetNodes() {
- return bottomTargetNodes;
+ return getBottomTargetNodesAcrossStorageTypes();
+ }
+
+ public List<NodeUtilization> getBottomTargetNodesAcrossStorageTypes() {
+ return bottomTargetNodesAcrossStorageTypes;
+ }
+
+ public Map<StorageType, StorageTypeSnapshot> getStorageTypeSnapshots() {
+ return storageTypeSnapshots;
+ }
+
+ public Set<String> getSourceDatanodes() {
+ return sourceDatanodes;
+ }
+
+ public Set<String> getTargetDatanodes() {
+ return targetDatanodes;
+ }
+
+ public boolean hasIncompleteStorageTypeUsage() {
+ return incompleteStorageTypeUsage;
}
public static Builder newBuilder() {
@@ -145,8 +209,15 @@ public static final class Builder {
private long totalOverUtilizedBytes;
private long totalUnderUtilizedBytes;
private double imbalance;
- private List<NodeUtilization> topSourceNodes = Collections.emptyList();
- private List<NodeUtilization> bottomTargetNodes = Collections.emptyList();
+ private Double maxImbalance;
+ private StorageType mostImbalancedStorageType;
+ private List<NodeUtilization> topSourceNodesAcrossStorageTypes =
Collections.emptyList();
+ private List<NodeUtilization> bottomTargetNodesAcrossStorageTypes =
Collections.emptyList();
+ private Map<StorageType, StorageTypeSnapshot> storageTypeSnapshots =
Collections.emptyMap();
+ private Set<String> sourceDatanodes = Collections.emptySet();
+ private Set<String> targetDatanodes = Collections.emptySet();
+ private Long totalBytesToMove;
+ private boolean incompleteStorageTypeUsage;
private Builder() {
}
@@ -206,24 +277,71 @@ public Builder setTotalUnderUtilizedBytes(long
totalUnderUtilizedBytes) {
return this;
}
+ public Builder setMaxImbalance(double maxImbalance) {
+ this.maxImbalance = maxImbalance;
+ return this;
+ }
+
+ public Builder setMostImbalancedStorageType(StorageType storageType) {
+ this.mostImbalancedStorageType = storageType;
+ return this;
+ }
+
public Builder setImbalance(double imbalance) {
this.imbalance = imbalance;
return this;
}
- public Builder setTopSourceNodes(List<NodeUtilization> topSourceNodes) {
- this.topSourceNodes = topSourceNodes;
+ public Builder setTopSourceNodes(List<NodeUtilization> nodes) {
+ return setTopSourceNodesAcrossStorageTypes(nodes);
+ }
+
+ public Builder setTopSourceNodesAcrossStorageTypes(List<NodeUtilization>
topSourceNodesAcrossStorageTypes) {
+ this.topSourceNodesAcrossStorageTypes = topSourceNodesAcrossStorageTypes;
return this;
}
- public Builder setBottomTargetNodes(List<NodeUtilization>
bottomTargetNodes) {
- this.bottomTargetNodes = bottomTargetNodes;
+ public Builder setBottomTargetNodes(List<NodeUtilization> nodes) {
+ return setBottomTargetNodesAcrossStorageTypes(nodes);
+ }
+
+ public Builder
setBottomTargetNodesAcrossStorageTypes(List<NodeUtilization>
bottomTargetNodesAcrossStorageTypes) {
+ this.bottomTargetNodesAcrossStorageTypes =
bottomTargetNodesAcrossStorageTypes;
return this;
}
public ContainerBalancerClusterSnapshot build() {
return new ContainerBalancerClusterSnapshot(this);
}
+
+ public Builder setStorageTypeSnapshots(Map<StorageType,
StorageTypeSnapshot> snapshots) {
+ this.storageTypeSnapshots = snapshots;
+ return this;
+ }
+
+ public Builder setSourceDatanodes(Set<String> nodes) {
+ this.sourceDatanodes = nodes;
+ return this;
+ }
+
+ public Builder setTargetDatanodes(Set<String> nodes) {
+ this.targetDatanodes = nodes;
+ return this;
+ }
+
+ public Builder setBytesToMove(long bytes) {
+ return setTotalBytesToMove(bytes);
+ }
+
+ public Builder setTotalBytesToMove(long bytes) {
+ this.totalBytesToMove = bytes;
+ return this;
+ }
+
+ public Builder setIncompleteStorageTypeUsage(boolean incomplete) {
+ this.incompleteStorageTypeUsage = incomplete;
+ return this;
+ }
}
/**
@@ -233,10 +351,18 @@ public ContainerBalancerClusterSnapshot build() {
public static final class NodeUtilization {
private final String hostname;
private final double utilization;
+ private final String datanodeId;
+ private final StorageType storageType;
public NodeUtilization(String hostname, double utilization) {
+ this(hostname, utilization, hostname, null);
+ }
+
+ public NodeUtilization(String hostname, double utilization, String
datanodeId, StorageType storageType) {
this.hostname = hostname;
this.utilization = utilization;
+ this.datanodeId = datanodeId;
+ this.storageType = storageType;
}
public String getHostname() {
@@ -246,5 +372,13 @@ public String getHostname() {
public double getUtilization() {
return utilization;
}
+
+ public String getDatanodeId() {
+ return datanodeId;
+ }
+
+ public StorageType getStorageType() {
+ return storageType;
+ }
}
}
diff --git
a/hadoop-hdds/common/src/main/java/org/apache/hadoop/hdds/scm/container/balancer/StorageTypeSnapshot.java
b/hadoop-hdds/common/src/main/java/org/apache/hadoop/hdds/scm/container/balancer/StorageTypeSnapshot.java
new file mode 100644
index 00000000000..a1e2a52aa1b
--- /dev/null
+++
b/hadoop-hdds/common/src/main/java/org/apache/hadoop/hdds/scm/container/balancer/StorageTypeSnapshot.java
@@ -0,0 +1,139 @@
+/*
+ * 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.container.balancer;
+
+import java.util.List;
+import java.util.Set;
+import org.apache.hadoop.fs.StorageType;
+import
org.apache.hadoop.hdds.scm.container.balancer.ContainerBalancerClusterSnapshot.NodeUtilization;
+
+/** Utilization and movement assessment for one storage type, independent of
the cluster summary. */
+public final class StorageTypeSnapshot {
+
+ private final StorageType storageType;
+ private final int eligibleDatanodes;
+ private final double averageUtilization;
+ private final long capacityBytes;
+ private final double maxUtilization;
+ private final double minUtilization;
+ private final double upperLimit;
+ private final double lowerLimit;
+ private final int sourceCount;
+ private final int targetCount;
+ private final long totalOverUtilizedBytes;
+ private final long totalUnderUtilizedBytes;
+ private final long bytesToMove;
+ private final double imbalance;
+ private final List<NodeUtilization> topSourceNodes;
+ private final List<NodeUtilization> bottomTargetNodes;
+ private final Set<String> sourceDatanodes;
+ private final Set<String> targetDatanodes;
+
+ StorageTypeSnapshot(StorageType storageType,
ContainerBalancerClusterSnapshot analysis) {
+ this.storageType = storageType;
+ this.eligibleDatanodes = analysis.getTotalEligibleDatanodes();
+ this.averageUtilization = analysis.getClusterAvgUtilization();
+ this.capacityBytes = analysis.getClusterCapacityBytes();
+ this.maxUtilization = analysis.getMaxUtilization();
+ this.minUtilization = analysis.getMinUtilization();
+ this.upperLimit = analysis.getUpperLimit();
+ this.lowerLimit = analysis.getLowerLimit();
+ this.sourceCount = analysis.getSourceCount();
+ this.targetCount = analysis.getTargetCount();
+ this.totalOverUtilizedBytes = analysis.getTotalOverUtilizedBytes();
+ this.totalUnderUtilizedBytes = analysis.getTotalUnderUtilizedBytes();
+ this.bytesToMove = analysis.getTotalBytesToMove();
+ this.imbalance = analysis.getImbalance();
+ this.topSourceNodes = analysis.getTopSourceNodesAcrossStorageTypes();
+ this.bottomTargetNodes = analysis.getBottomTargetNodesAcrossStorageTypes();
+ this.sourceDatanodes = analysis.getSourceDatanodes();
+ this.targetDatanodes = analysis.getTargetDatanodes();
+ }
+
+ public StorageType getStorageType() {
+ return storageType;
+ }
+
+ public int getEligibleDatanodes() {
+ return eligibleDatanodes;
+ }
+
+ public double getAverageUtilization() {
+ return averageUtilization;
+ }
+
+ public long getCapacityBytes() {
+ return capacityBytes;
+ }
+
+ public double getMaxUtilization() {
+ return maxUtilization;
+ }
+
+ public double getMinUtilization() {
+ return minUtilization;
+ }
+
+ public double getUpperLimit() {
+ return upperLimit;
+ }
+
+ public double getLowerLimit() {
+ return lowerLimit;
+ }
+
+ public int getSourceCount() {
+ return sourceCount;
+ }
+
+ public int getTargetCount() {
+ return targetCount;
+ }
+
+ public long getTotalOverUtilizedBytes() {
+ return totalOverUtilizedBytes;
+ }
+
+ public long getTotalUnderUtilizedBytes() {
+ return totalUnderUtilizedBytes;
+ }
+
+ public long getBytesToMove() {
+ return bytesToMove;
+ }
+
+ public double getImbalance() {
+ return imbalance;
+ }
+
+ public List<NodeUtilization> getTopSourceNodes() {
+ return topSourceNodes;
+ }
+
+ public List<NodeUtilization> getBottomTargetNodes() {
+ return bottomTargetNodes;
+ }
+
+ public Set<String> getSourceDatanodes() {
+ return sourceDatanodes;
+ }
+
+ public Set<String> getTargetDatanodes() {
+ return targetDatanodes;
+ }
+}
diff --git
a/hadoop-hdds/common/src/test/java/org/apache/hadoop/hdds/scm/container/balancer/TestContainerBalancerAdvisor.java
b/hadoop-hdds/common/src/test/java/org/apache/hadoop/hdds/scm/container/balancer/TestContainerBalancerAdvisor.java
index 7d5c97cfd73..474a55197dd 100644
---
a/hadoop-hdds/common/src/test/java/org/apache/hadoop/hdds/scm/container/balancer/TestContainerBalancerAdvisor.java
+++
b/hadoop-hdds/common/src/test/java/org/apache/hadoop/hdds/scm/container/balancer/TestContainerBalancerAdvisor.java
@@ -23,17 +23,73 @@
import static org.junit.jupiter.api.Assertions.assertThrows;
import java.util.ArrayList;
+import java.util.Arrays;
import java.util.List;
import java.util.UUID;
import org.apache.hadoop.hdds.conf.OzoneConfiguration;
import org.apache.hadoop.hdds.protocol.DatanodeDetails;
import org.apache.hadoop.hdds.protocol.proto.HddsProtos.DatanodeUsageInfoProto;
+import org.apache.hadoop.hdds.protocol.proto.HddsProtos.StorageTypeProto;
+import
org.apache.hadoop.hdds.protocol.proto.HddsProtos.StorageTypeUsageInfoProto;
import org.apache.hadoop.ozone.OzoneConsts;
import org.junit.jupiter.api.Test;
/** Tests for {@link ContainerBalancerAdvisor} estimation. */
public final class TestContainerBalancerAdvisor {
+ @Test
+ void testStorageTypesSharePerIterationLimitsDespiteBalancedWholeNodeTotals()
{
+ ContainerBalancerEstimation estimate =
ContainerBalancerAdvisor.estimate(new OzoneConfiguration(),
+ new ContainerBalancerAdvisor.AdvisorRequest()
+ .setNodes(Arrays.asList(typedProto("first", 5, 95),
typedProto("second", 95, 5)))
+ .setMaxDatanodesPercentageToInvolvePerIteration(100)).get(0);
+
+ assertThat(estimate.succeeded()).isTrue();
+ assertEquals(70L * OzoneConsts.GB, estimate.getBytesToMove());
+ // MEDIUM grants 26 GB to each datanode, not a fresh 26 GB for each
storage type.
+ assertEquals(26L * OzoneConsts.GB, estimate.getPerIterationBytes());
+ assertEquals(3, estimate.getEstimatedIterations());
+ }
+
+ @Test
+ void testEstimateRejectsPartialStorageTypeUsage() {
+ IllegalArgumentException ex = assertThrows(IllegalArgumentException.class,
() ->
+ ContainerBalancerAdvisor.estimate(new OzoneConfiguration(), new
ContainerBalancerAdvisor.AdvisorRequest()
+ .setNodes(Arrays.asList(typedProto("new", 5, 95), proto("legacy",
200, 100)))));
+ assertThat(ex).hasMessageContaining("missing or incomplete storage-type
usage");
+ }
+
+ @Test
+ void testEstimateRejectsStorageTypesWithoutSourceTargetPairs() {
+ IllegalArgumentException ex = assertThrows(IllegalArgumentException.class,
() ->
+ ContainerBalancerAdvisor.estimate(new OzoneConfiguration(), new
ContainerBalancerAdvisor.AdvisorRequest()
+ .setNodes(Arrays.asList(typedProto("first", 0, 100),
typedProto("second", 40, 60),
+ typedProto("third", 40, 60))).setThresholdPercent(20.0)));
+ assertThat(ex).hasMessageContaining("No bytes to
move").hasMessageContaining("same storage type");
+ }
+
+ @Test
+ void
testEstimateDoesNotCountIncompatibleSourcesAndTargetsAsExtraThroughput() {
+ List<DatanodeUsageInfoProto> nodes = new ArrayList<>(Arrays.asList(
+ typedProto("first", 0, 100), typedProto("second", 40, 60),
typedProto("third", 40, 60)));
+ // ARCHIVE and PROVIDED share one source/target pair; SSD and DISK have no
pairs at the 20% threshold.
+ for (long remaining : new long[]{50, 950}) {
+ nodes.add(proto("paired-" + remaining, 2000L * OzoneConsts.GB, 2 *
remaining * OzoneConsts.GB).toBuilder()
+
.addStorageTypeUsage(StorageTypeUsageInfoProto.newBuilder().setStorageType(StorageTypeProto.ARCHIVE)
+ .setCapacity(1000L * OzoneConsts.GB).setRemaining(remaining *
OzoneConsts.GB))
+
.addStorageTypeUsage(StorageTypeUsageInfoProto.newBuilder().setStorageType(StorageTypeProto.PROVIDED)
+ .setCapacity(1000L * OzoneConsts.GB).setRemaining(remaining *
OzoneConsts.GB)).build());
+ }
+ ContainerBalancerEstimation estimate =
ContainerBalancerAdvisor.estimate(new OzoneConfiguration(),
+ new
ContainerBalancerAdvisor.AdvisorRequest().setNodes(nodes).setThresholdPercent(20.0)
+ .setMaxDatanodesPercentageToInvolvePerIteration(100)).get(0);
+
+ assertThat(estimate.succeeded()).isTrue();
+ assertEquals(500L * OzoneConsts.GB, estimate.getBytesToMove());
+ // Unpaired nodes must not inflate the shared send/receive limits of the
one participating datanode pair.
+ assertEquals(26L * OzoneConsts.GB, estimate.getPerIterationBytes());
+ }
+
@Test
void testComputePerIterationBytesNeverExceedsBytesToMove() {
int[] involved = {3, 3};
@@ -280,6 +336,14 @@ private static List<DatanodeUsageInfoProto> buildCluster(
return nodes;
}
+ private static DatanodeUsageInfoProto typedProto(String hostname, long
ssdRemaining, long diskRemaining) {
+ return proto(hostname, 200L * OzoneConsts.GB, (ssdRemaining +
diskRemaining) * OzoneConsts.GB).toBuilder()
+
.addStorageTypeUsage(StorageTypeUsageInfoProto.newBuilder().setStorageType(StorageTypeProto.SSD)
+ .setCapacity(100L * OzoneConsts.GB).setRemaining(ssdRemaining *
OzoneConsts.GB))
+
.addStorageTypeUsage(StorageTypeUsageInfoProto.newBuilder().setStorageType(StorageTypeProto.DISK)
+ .setCapacity(100L * OzoneConsts.GB).setRemaining(diskRemaining *
OzoneConsts.GB)).build();
+ }
+
private static DatanodeUsageInfoProto proto(String hostname, long capacity,
long remaining) {
DatanodeDetails datanode = DatanodeDetails.newBuilder()
.setHostName(hostname)
diff --git
a/hadoop-hdds/common/src/test/java/org/apache/hadoop/hdds/scm/container/balancer/TestContainerBalancerClusterAnalyzer.java
b/hadoop-hdds/common/src/test/java/org/apache/hadoop/hdds/scm/container/balancer/TestContainerBalancerClusterAnalyzer.java
index 4d5c40d2591..1c1c8046c83 100644
---
a/hadoop-hdds/common/src/test/java/org/apache/hadoop/hdds/scm/container/balancer/TestContainerBalancerClusterAnalyzer.java
+++
b/hadoop-hdds/common/src/test/java/org/apache/hadoop/hdds/scm/container/balancer/TestContainerBalancerClusterAnalyzer.java
@@ -20,6 +20,7 @@
import static org.apache.hadoop.ozone.ClientVersion.DEFAULT_VERSION;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.util.ArrayList;
@@ -30,8 +31,11 @@
import java.util.Set;
import java.util.UUID;
import java.util.stream.Collectors;
+import org.apache.hadoop.fs.StorageType;
+import org.apache.hadoop.hdds.client.StorageTypeUtils;
import org.apache.hadoop.hdds.protocol.DatanodeDetails;
import org.apache.hadoop.hdds.protocol.proto.HddsProtos.DatanodeUsageInfoProto;
+import
org.apache.hadoop.hdds.protocol.proto.HddsProtos.StorageTypeUsageInfoProto;
import
org.apache.hadoop.hdds.scm.container.balancer.ContainerBalancerClusterSnapshot.NodeUtilization;
import org.junit.jupiter.api.Test;
@@ -40,6 +44,230 @@ public final class TestContainerBalancerClusterAnalyzer {
private static final double THRESHOLD = 0.10;
+ @Test
+ void testOppositeStorageTypeImbalancesAreNotHiddenByWholeNodeTotals() {
+ List<DatanodeUsageInfoProto> nodes = Arrays.asList(typedProto("first", 5,
95), typedProto("second", 95, 5));
+ ContainerBalancerClusterSnapshot snapshot =
ContainerBalancerClusterAnalyzer.analyze(
+ nodes, THRESHOLD, Collections.emptySet(), Collections.emptySet());
+
+ assertEquals(0.5, snapshot.getClusterAvgUtilization());
+ assertEquals(400, snapshot.getClusterCapacityBytes());
+ assertEquals(2, snapshot.getSourceCount());
+ assertEquals(2, snapshot.getTargetCount());
+ assertEquals(snapshot.getSourceDatanodes(), snapshot.getTargetDatanodes());
+ assertEquals(70, snapshot.getBytesToMove());
+ assertFalse(snapshot.hasIncompleteStorageTypeUsage());
+ for (StorageType type : Arrays.asList(StorageType.SSD, StorageType.DISK)) {
+ StorageTypeSnapshot tier = snapshot.getStorageTypeSnapshots().get(type);
+ assertEquals(0.5, tier.getAverageUtilization());
+ assertEquals(1, tier.getSourceCount());
+ assertEquals(1, tier.getTargetCount());
+ assertEquals(35, tier.getBytesToMove());
+ assertEquals(type, tier.getTopSourceNodes().get(0).getStorageType());
+ }
+ }
+
+ @Test
+ void testDatanodeIsCountedOnceWhenSourceForMultipleStorageTypes() {
+ DatanodeUsageInfoProto source = typedProto("a", 5, 60);
+ String sourceId =
DatanodeDetails.getFromProtoBuf(source.getNode()).getID().toString();
+ ContainerBalancerClusterSnapshot snapshot =
ContainerBalancerClusterAnalyzer.analyze(
+ Arrays.asList(source, typedProto("b", 20, 80), typedProto("c", 35,
100)),
+ THRESHOLD, Collections.emptySet(), Collections.emptySet());
+
+ // A is above both upper limits: SSD 95% > 90%, and DISK 40% > 30%.
+ for (StorageType type : Arrays.asList(StorageType.SSD, StorageType.DISK)) {
+ StorageTypeSnapshot typeSnapshot =
snapshot.getStorageTypeSnapshots().get(type);
+ assertEquals(1, typeSnapshot.getSourceCount());
+ assertEquals(Collections.singleton(sourceId),
typeSnapshot.getSourceDatanodes());
+ assertEquals(1, typeSnapshot.getTopSourceNodes().size());
+ NodeUtilization typeSource = typeSnapshot.getTopSourceNodes().get(0);
+ assertEquals(sourceId, typeSource.getDatanodeId());
+ assertEquals(type, typeSource.getStorageType());
+ }
+
+ assertEquals(1, snapshot.getSourceCount());
+ assertEquals(Collections.singleton(sourceId),
snapshot.getSourceDatanodes());
+ assertEquals(1, snapshot.getTopSourceNodesAcrossStorageTypes().size());
+ NodeUtilization topSource =
snapshot.getTopSourceNodesAcrossStorageTypes().get(0);
+ assertEquals("a", topSource.getHostname());
+ assertEquals(sourceId, topSource.getDatanodeId());
+ assertEquals(StorageType.SSD, topSource.getStorageType());
+ assertEquals(0.95, topSource.getUtilization(), 0.0001);
+ }
+
+ @Test
+ void testClusterUtilizationIsSeparateFromMostImbalancedStorageType() {
+ ContainerBalancerClusterSnapshot snapshot =
ContainerBalancerClusterAnalyzer.analyze(
+ Arrays.asList(typedProto("first", 5, 50), typedProto("second", 35,
90)),
+ THRESHOLD, Collections.emptySet(), Collections.emptySet());
+
+ // Whole-datanode utilization is 72.5% and 37.5%; DISK is 50%/10% and SSD
is 95%/65%.
+ assertEquals(0.55, snapshot.getClusterAvgUtilization(), 0.0001);
+ assertEquals(0.725, snapshot.getMaxUtilization(), 0.0001);
+ assertEquals(0.375, snapshot.getMinUtilization(), 0.0001);
+ assertEquals(0.35, snapshot.getImbalance(), 0.0001);
+ assertEquals(0.40, snapshot.getMaxImbalance(), 0.0001);
+ assertEquals(StorageType.DISK, snapshot.getMostImbalancedStorageType());
+ StorageTypeSnapshot disk =
snapshot.getStorageTypeSnapshots().get(StorageType.DISK);
+ assertEquals(0.50, disk.getMaxUtilization(), 0.0001);
+ assertEquals(0.10, disk.getMinUtilization(), 0.0001);
+ assertEquals(0.40, disk.getImbalance(), 0.0001);
+ StorageTypeSnapshot ssd =
snapshot.getStorageTypeSnapshots().get(StorageType.SSD);
+ assertEquals(0.95, ssd.getMaxUtilization(), 0.0001);
+ assertEquals(0.65, ssd.getMinUtilization(), 0.0001);
+ assertEquals(0.30, ssd.getImbalance(), 0.0001);
+ assertEquals(disk.getBytesToMove() + ssd.getBytesToMove(),
snapshot.getTotalBytesToMove());
+ assertEquals(1, snapshot.getSourceCount());
+ assertEquals(1, snapshot.getTargetCount());
+ NodeUtilization source =
snapshot.getTopSourceNodesAcrossStorageTypes().get(0);
+ assertEquals(StorageType.SSD, source.getStorageType());
+ assertEquals(0.95, source.getUtilization(), 0.0001);
+ NodeUtilization target =
snapshot.getBottomTargetNodesAcrossStorageTypes().get(0);
+ assertEquals(StorageType.DISK, target.getStorageType());
+ assertEquals(0.10, target.getUtilization(), 0.0001);
+ }
+
+ @Test
+ void testEqualStorageTypeImbalancesSelectTypeInEnumOrder() {
+ ContainerBalancerClusterSnapshot snapshot =
ContainerBalancerClusterAnalyzer.analyze(
+ Arrays.asList(typedProto("first", 5, 95), typedProto("second", 95, 5)),
+ THRESHOLD, Collections.emptySet(), Collections.emptySet());
+
+ assertEquals(snapshot.getStorageTypeSnapshots().keySet().iterator().next(),
+ snapshot.getMostImbalancedStorageType());
+ assertEquals(0.90, snapshot.getMaxImbalance(), 0.0001);
+ assertEquals(0, snapshot.getImbalance(), 0.0001);
+ }
+
+ @Test
+ void testSourcesAndTargetsOnDifferentStorageTypesCannotBePaired() {
+ // SSD has a source but no target below its lower limit; DISK has the
opposite.
+ List<DatanodeUsageInfoProto> nodes = Arrays.asList(
+ typedProto("first", 0, 100), typedProto("second", 40, 60),
typedProto("third", 40, 60));
+ ContainerBalancerClusterSnapshot snapshot =
ContainerBalancerClusterAnalyzer.analyze(
+ nodes, 0.2, Collections.emptySet(), Collections.emptySet());
+
+ assertEquals(0, snapshot.getSourceCount());
+ assertEquals(0, snapshot.getTargetCount());
+ assertTrue(snapshot.getSourceDatanodes().isEmpty());
+ assertTrue(snapshot.getTargetDatanodes().isEmpty());
+ assertTrue(snapshot.getTopSourceNodesAcrossStorageTypes().isEmpty());
+ assertTrue(snapshot.getBottomTargetNodesAcrossStorageTypes().isEmpty());
+ assertTrue(snapshot.getTotalOverUtilizedBytes() > 0);
+ assertTrue(snapshot.getTotalUnderUtilizedBytes() > 0);
+ assertEquals(0, snapshot.getBytesToMove());
+ assertEquals(0.40, snapshot.getMaxImbalance(), 0.0001);
+
+ Set<String> firstNode =
Collections.singleton(DatanodeDetails.getFromProtoBuf(nodes.get(0).getNode())
+ .getID().toString());
+ StorageTypeSnapshot ssd =
snapshot.getStorageTypeSnapshots().get(StorageType.SSD);
+ assertEquals(1, ssd.getSourceCount());
+ assertEquals(firstNode, ssd.getSourceDatanodes());
+ assertEquals(1, ssd.getTopSourceNodes().size());
+ assertEquals(0, ssd.getTargetCount());
+ assertEquals(0, ssd.getBytesToMove());
+ StorageTypeSnapshot disk =
snapshot.getStorageTypeSnapshots().get(StorageType.DISK);
+ assertEquals(0, disk.getSourceCount());
+ assertEquals(1, disk.getTargetCount());
+ assertEquals(firstNode, disk.getTargetDatanodes());
+ assertEquals(1, disk.getBottomTargetNodes().size());
+ assertEquals(0, disk.getBytesToMove());
+ }
+
+ @Test
+ void testCombinedNodesExcludeUnpairedTypeOnSameDatanode() {
+ List<DatanodeUsageInfoProto> nodes = Arrays.asList(
+ typedProto("first", 0, 20), typedProto("second", 40, 60),
typedProto("third", 40, 100));
+ ContainerBalancerClusterSnapshot snapshot =
ContainerBalancerClusterAnalyzer.analyze(
+ nodes, 0.2, Collections.emptySet(), Collections.emptySet());
+
+ // First is a source for both types, but only DISK has a target. Its SSD
entry must remain per-type only.
+ StorageTypeSnapshot ssd =
snapshot.getStorageTypeSnapshots().get(StorageType.SSD);
+ StorageTypeSnapshot disk =
snapshot.getStorageTypeSnapshots().get(StorageType.DISK);
+ assertEquals(1, ssd.getSourceCount());
+ assertEquals(0, ssd.getTargetCount());
+ assertEquals(0, ssd.getBytesToMove());
+ assertEquals(1.0, ssd.getTopSourceNodes().get(0).getUtilization(), 0.0001);
+ assertTrue(disk.getBytesToMove() > 0);
+ assertEquals(disk.getBytesToMove(), snapshot.getTotalBytesToMove());
+ assertEquals(1, snapshot.getSourceCount());
+ assertEquals(1, snapshot.getTargetCount());
+ assertEquals(disk.getSourceDatanodes(), snapshot.getSourceDatanodes());
+ assertEquals(disk.getTargetDatanodes(), snapshot.getTargetDatanodes());
+ assertEquals(1, snapshot.getTopSourceNodesAcrossStorageTypes().size());
+ assertEquals(1, snapshot.getBottomTargetNodesAcrossStorageTypes().size());
+ NodeUtilization source =
snapshot.getTopSourceNodesAcrossStorageTypes().get(0);
+ assertEquals("first", source.getHostname());
+ assertEquals(StorageType.DISK, source.getStorageType());
+ assertEquals(0.8, source.getUtilization(), 0.0001);
+ NodeUtilization target =
snapshot.getBottomTargetNodesAcrossStorageTypes().get(0);
+ assertEquals("third", target.getHostname());
+ assertEquals(StorageType.DISK, target.getStorageType());
+ assertEquals(0, target.getUtilization(), 0.0001);
+ }
+
+ @Test
+ void testStorageTypeWithOnlyOneDatanodeIsNotPairedWithAnotherType() {
+ DatanodeUsageInfoProto ssd = proto("ssd-only", 100, 5).toBuilder()
+ .addStorageTypeUsage(storageTypeUsage(StorageType.SSD, 5)).build();
+ DatanodeUsageInfoProto disk = proto("disk-only", 100, 95).toBuilder()
+ .addStorageTypeUsage(storageTypeUsage(StorageType.DISK, 95)).build();
+ ContainerBalancerClusterSnapshot snapshot =
ContainerBalancerClusterAnalyzer.analyze(
+ Arrays.asList(ssd, disk), THRESHOLD, Collections.emptySet(),
Collections.emptySet());
+
+ assertEquals(0, snapshot.getSourceCount());
+ assertEquals(0, snapshot.getTargetCount());
+ assertEquals(0, snapshot.getBytesToMove());
+ assertEquals(2, snapshot.getStorageTypeSnapshots().size());
+ assertFalse(snapshot.hasIncompleteStorageTypeUsage());
+ }
+
+ @Test
+ void testStorageTypeNodesExactlyAtLimitsAreNotUnbalanced() {
+ ContainerBalancerClusterSnapshot snapshot =
ContainerBalancerClusterAnalyzer.analyze(
+ Arrays.asList(typedProto("first", 40, 60), typedProto("second", 60,
40)),
+ THRESHOLD, Collections.emptySet(), Collections.emptySet());
+ assertEquals(0, snapshot.getSourceCount());
+ assertEquals(0, snapshot.getTargetCount());
+ assertEquals(0, snapshot.getBytesToMove());
+ }
+
+ @Test
+ void testPartialReportingAndFiltersApplyBeforeStorageTypeAnalysis() {
+ List<DatanodeUsageInfoProto> nodes = Arrays.asList(
+ typedProto("first", 5, 95), typedProto("second", 95, 5),
proto("legacy", 200, 100));
+ ContainerBalancerClusterSnapshot partial =
ContainerBalancerClusterAnalyzer.analyze(
+ nodes, THRESHOLD, Collections.emptySet(), Collections.emptySet());
+ assertTrue(partial.hasIncompleteStorageTypeUsage());
+
+ ContainerBalancerClusterSnapshot filtered =
ContainerBalancerClusterAnalyzer.analyze(
+ nodes, THRESHOLD, Collections.emptySet(),
Collections.singleton("legacy"));
+ assertFalse(filtered.hasIncompleteStorageTypeUsage());
+ assertEquals(2, filtered.getTotalEligibleDatanodes());
+ assertEquals(70, filtered.getBytesToMove());
+ }
+
+ @Test
+ void testMissingStorageTypeCapacityIsReportedAsIncomplete() {
+ DatanodeUsageInfoProto partial = typedProto("partial", 5,
95).toBuilder().removeStorageTypeUsage(1).build();
+ ContainerBalancerClusterSnapshot snapshot =
ContainerBalancerClusterAnalyzer.analyze(
+ Collections.singletonList(partial), THRESHOLD, Collections.emptySet(),
Collections.emptySet());
+ assertTrue(snapshot.hasIncompleteStorageTypeUsage());
+ }
+
+ @Test
+ void testLegacyUsageRetainsAggregateAnalysis() {
+ ContainerBalancerClusterSnapshot snapshot =
ContainerBalancerClusterAnalyzer.analyze(
+ Arrays.asList(proto("source", 100, 10), proto("target", 100, 50)),
+ THRESHOLD, Collections.emptySet(), Collections.emptySet());
+ assertTrue(snapshot.getStorageTypeSnapshots().isEmpty());
+ assertFalse(snapshot.hasIncompleteStorageTypeUsage());
+ assertEquals(10, snapshot.getBytesToMove());
+ assertEquals(snapshot.getImbalance(), snapshot.getMaxImbalance());
+ assertNull(snapshot.getMostImbalancedStorageType());
+ }
+
@Test
void testCalculateAvgUtilizationFromTotals() {
assertEquals(0.70d, ContainerBalancerClusterAnalyzer
@@ -293,6 +521,17 @@ void testShouldExcludeDatanodeDirectly() {
datanode, Collections.emptySet(), Collections.singleton("dn-1")));
}
+ private static DatanodeUsageInfoProto typedProto(String hostname, long
ssdRemaining, long diskRemaining) {
+ return proto(hostname, 200, ssdRemaining + diskRemaining).toBuilder()
+ .addStorageTypeUsage(storageTypeUsage(StorageType.SSD, ssdRemaining))
+ .addStorageTypeUsage(storageTypeUsage(StorageType.DISK,
diskRemaining)).build();
+ }
+
+ private static StorageTypeUsageInfoProto storageTypeUsage(StorageType type,
long remaining) {
+ return
StorageTypeUsageInfoProto.newBuilder().setStorageType(StorageTypeUtils.getStorageTypeProto(type))
+ .setCapacity(100).setUsed(100 -
remaining).setRemaining(remaining).build();
+ }
+
private static DatanodeUsageInfoProto proto(String hostname, long capacity,
long remaining) {
DatanodeDetails datanode = DatanodeDetails.newBuilder()
.setHostName(hostname)
diff --git a/hadoop-hdds/docs/content/feature/ContainerBalancer.md
b/hadoop-hdds/docs/content/feature/ContainerBalancer.md
index b6270c985b8..985f0ceb6d9 100644
--- a/hadoop-hdds/docs/content/feature/ContainerBalancer.md
+++ b/hadoop-hdds/docs/content/feature/ContainerBalancer.md
@@ -64,6 +64,30 @@ ozone admin containerbalancer start [options]
| `--include-datanodes` | A comma-separated
list of datanode hostnames or IP addresses to be included in balancing.
|
| `--exclude-datanodes` | A comma-separated
list of datanode hostnames or IP addresses to be excluded from balancing.
|
+### Assessment and estimate
+
+Inspect storage usage without starting the balancer:
+
+```bash
+ozone admin containerbalancer assessment -t 10
+ozone admin containerbalancer assessment -t 10 --json
+ozone admin containerbalancer estimate -t 10 -d 100 --profile MEDIUM
+```
+
+When SCM reports usage by storage type, assessment shows separate SSD, DISK,
and other
+storage-type sections. For example, two datanodes can both be 50% full overall
while
+one has 90% SSD usage and the other has 10% SSD usage. Assessment shows this
SSD imbalance.
+The JSON report includes a `storageTypes` breakdown and an
`incompleteStorageTypeUsage` flag.
+
+Estimates use separate source and target groups for each storage type. Spare
DISK space
+does not count as spare SSD space. Byte and datanode limits remain shared
across types.
+Assessment warns when storage-type reports are incomplete, and estimation
rejects those
+reports. When no storage-type breakdown is available, both commands use
overall usage.
+
+These commands report and estimate balancing work. The running balancer still
chooses
+moves using overall datanode usage; selecting moves separately for each
storage type is
+separate work.
+
### Status
To check the status of the Container Balancer:
diff --git a/hadoop-hdds/interface-client/src/main/proto/hdds.proto
b/hadoop-hdds/interface-client/src/main/proto/hdds.proto
index 13c8a3f4352..3a1fbf77df2 100644
--- a/hadoop-hdds/interface-client/src/main/proto/hdds.proto
+++ b/hadoop-hdds/interface-client/src/main/proto/hdds.proto
@@ -224,6 +224,18 @@ message DatanodeUsageInfoProto {
// Raw filesystem stats
optional int64 fsCapacity = 10;
optional int64 fsAvailable = 11;
+ repeated StorageTypeUsageInfoProto storageTypeUsage = 12;
+}
+
+// Per-storage-type statistics supplement, rather than replace, the datanode
totals.
+message StorageTypeUsageInfoProto {
+ optional StorageTypeProto storageType = 1;
+ optional int64 capacity = 2;
+ optional int64 used = 3;
+ optional int64 remaining = 4;
+ optional int64 committed = 5;
+ optional int64 freeSpaceToSpare = 6;
+ optional int64 reserved = 7;
}
/**
diff --git
a/hadoop-hdds/server-scm/src/main/java/org/apache/hadoop/hdds/scm/node/DatanodeUsageInfo.java
b/hadoop-hdds/server-scm/src/main/java/org/apache/hadoop/hdds/scm/node/DatanodeUsageInfo.java
index 977f59278e4..2c805b73452 100644
---
a/hadoop-hdds/server-scm/src/main/java/org/apache/hadoop/hdds/scm/node/DatanodeUsageInfo.java
+++
b/hadoop-hdds/server-scm/src/main/java/org/apache/hadoop/hdds/scm/node/DatanodeUsageInfo.java
@@ -17,10 +17,16 @@
package org.apache.hadoop.hdds.scm.node;
+import jakarta.annotation.Nullable;
import java.util.Comparator;
+import java.util.EnumSet;
+import java.util.Set;
+import org.apache.hadoop.fs.StorageType;
+import org.apache.hadoop.hdds.client.StorageTypeUtils;
import org.apache.hadoop.hdds.protocol.DatanodeDetails;
import org.apache.hadoop.hdds.protocol.DatanodeID;
import org.apache.hadoop.hdds.protocol.proto.HddsProtos.DatanodeUsageInfoProto;
+import
org.apache.hadoop.hdds.protocol.proto.HddsProtos.StorageTypeUsageInfoProto;
import org.apache.hadoop.hdds.scm.container.placement.metrics.SCMNodeStat;
import org.apache.hadoop.ozone.ClientVersion;
@@ -105,6 +111,54 @@ public double calculateUtilization() {
return calculateUtilization(0);
}
+ /**
+ * Calculates utilization of a single storage type on this datanode, so the
+ * balancer can compare nodes on the tier it is actually moving data within.
+ *
+ * @param plusSize the increased size
+ * @param storageType the storage type to measure, or null to measure the
+ * datanode as a whole
+ * @return (capacity - remaining) / capacity for that storage type, or 0 when
+ * the datanode has no volume of that type
+ */
+ public double calculateUtilization(long plusSize,
+ @Nullable StorageType storageType) {
+ if (storageType == null) {
+ return calculateUtilization(plusSize);
+ }
+ long capacity = scmNodeStat.getCapacity(storageType).get();
+ if (capacity == 0) {
+ return 0;
+ }
+ long numerator =
+ capacity - scmNodeStat.getRemaining(storageType).get() + plusSize;
+ return numerator / (double) capacity;
+ }
+
+ /**
+ * Calculates current utilization of a single storage type on this datanode.
+ *
+ * @param storageType the storage type to measure, or null to measure the
+ * datanode as a whole
+ */
+ public double calculateUtilization(@Nullable StorageType storageType) {
+ return calculateUtilization(0, storageType);
+ }
+
+ /**
+ * Storage types this datanode actually has capacity for. Used by the
balancer
+ * to decide which tiers are worth considering on this node.
+ */
+ public Set<StorageType> getStorageTypes() {
+ Set<StorageType> types = EnumSet.noneOf(StorageType.class);
+ for (StorageType type : StorageType.values()) {
+ if (scmNodeStat.getCapacity(type).get() > 0) {
+ types.add(type);
+ }
+ }
+ return types;
+ }
+
/**
* Sets DatanodeDetails of this DatanodeUsageInfo.
*
@@ -239,6 +293,16 @@ private DatanodeUsageInfoProto.Builder
toProtoBuilder(ClientVersion clientVersio
builder.setRemaining(scmNodeStat.getRemaining().get());
builder.setCommitted(scmNodeStat.getCommitted().get());
builder.setFreeSpaceToSpare(scmNodeStat.getFreeSpaceToSpare().get());
+ for (StorageType type : getStorageTypes()) {
+ builder.addStorageTypeUsage(StorageTypeUsageInfoProto.newBuilder()
+ .setStorageType(StorageTypeUtils.getStorageTypeProto(type))
+ .setCapacity(scmNodeStat.getCapacity(type).get())
+ .setUsed(scmNodeStat.getScmUsed(type).get())
+ .setRemaining(scmNodeStat.getRemaining(type).get())
+ .setCommitted(scmNodeStat.getCommitted(type).get())
+ .setFreeSpaceToSpare(scmNodeStat.getFreeSpaceToSpare(type).get())
+ .setReserved(scmNodeStat.getReserved(type).get()));
+ }
}
builder.setContainerCount(containerCount);
diff --git
a/hadoop-hdds/server-scm/src/test/java/org/apache/hadoop/hdds/scm/node/TestDatanodeUsageInfo.java
b/hadoop-hdds/server-scm/src/test/java/org/apache/hadoop/hdds/scm/node/TestDatanodeUsageInfo.java
index 220bbbc6550..f10aa81ef55 100644
---
a/hadoop-hdds/server-scm/src/test/java/org/apache/hadoop/hdds/scm/node/TestDatanodeUsageInfo.java
+++
b/hadoop-hdds/server-scm/src/test/java/org/apache/hadoop/hdds/scm/node/TestDatanodeUsageInfo.java
@@ -20,16 +20,78 @@
import static java.util.Collections.singletonMap;
import static
org.apache.hadoop.hdds.protocol.MockDatanodeDetails.randomDatanodeDetails;
import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.data.Offset.offset;
+import java.util.HashMap;
+import java.util.Map;
import org.apache.hadoop.fs.StorageType;
import org.apache.hadoop.hdds.protocol.DatanodeDetails;
import org.apache.hadoop.hdds.protocol.proto.HddsProtos.DatanodeUsageInfoProto;
+import org.apache.hadoop.hdds.protocol.proto.HddsProtos.StorageTypeProto;
+import
org.apache.hadoop.hdds.protocol.proto.HddsProtos.StorageTypeUsageInfoProto;
import org.apache.hadoop.hdds.scm.container.placement.metrics.SCMNodeStat;
import org.apache.hadoop.ozone.ClientVersion;
import org.junit.jupiter.api.Test;
class TestDatanodeUsageInfo {
+ @Test
+ void testToProtoReportsStorageTypesWithoutChangingAggregateUsage() throws
Exception {
+ DatanodeUsageInfo info = new DatanodeUsageInfo(randomDatanodeDetails(),
twoTierStat());
+ DatanodeUsageInfoProto proto = DatanodeUsageInfoProto.parseFrom(
+ info.toProto(ClientVersion.CURRENT).toByteArray());
+
+ assertThat(proto.getCapacity()).isEqualTo(200);
+ assertThat(proto.getUsed()).isEqualTo(110);
+ assertThat(proto.getRemaining()).isEqualTo(90);
+ assertThat(proto.getStorageTypeUsageCount()).isEqualTo(2);
+ for (StorageTypeUsageInfoProto usage : proto.getStorageTypeUsageList()) {
+ assertThat(usage.getCapacity()).isEqualTo(100);
+ assertThat(usage.getCommitted()).isZero();
+ assertThat(usage.getFreeSpaceToSpare()).isZero();
+ assertThat(usage.getReserved()).isZero();
+ if (usage.getStorageType() == StorageTypeProto.SSD) {
+ assertThat(usage.getUsed()).isEqualTo(90);
+ assertThat(usage.getRemaining()).isEqualTo(10);
+ } else {
+ assertThat(usage.getStorageType()).isEqualTo(StorageTypeProto.DISK);
+ assertThat(usage.getUsed()).isEqualTo(20);
+ assertThat(usage.getRemaining()).isEqualTo(80);
+ }
+ }
+ DatanodeUsageInfoProto legacy =
proto.toBuilder().clearStorageTypeUsage().build();
+ assertThat(legacy.getCapacity()).isEqualTo(proto.getCapacity());
+ assertThat(legacy.getUsed()).isEqualTo(proto.getUsed());
+ assertThat(legacy.getRemaining()).isEqualTo(proto.getRemaining());
+ }
+
+ @Test
+ void testToProtoReportsStorageTypeReservations() {
+ SCMNodeStat stat = new SCMNodeStat(singletonMap(StorageType.SSD, 100L),
+ singletonMap(StorageType.SSD, 90L), singletonMap(StorageType.SSD, 10L),
+ singletonMap(StorageType.SSD, 7L), singletonMap(StorageType.SSD, 3L),
+ singletonMap(StorageType.SSD, 2L));
+ DatanodeUsageInfo info = new DatanodeUsageInfo(randomDatanodeDetails(),
stat);
+ info.setReserved(42L);
+
+ DatanodeUsageInfoProto proto = info.toProto(ClientVersion.CURRENT);
+
+ assertThat(proto.getReserved()).isEqualTo(42L);
+ assertThat(proto.getStorageTypeUsageCount()).isEqualTo(1);
+ StorageTypeUsageInfoProto usage = proto.getStorageTypeUsage(0);
+ assertThat(usage.getStorageType()).isEqualTo(StorageTypeProto.SSD);
+ assertThat(usage.getCommitted()).isEqualTo(7L);
+ assertThat(usage.getFreeSpaceToSpare()).isEqualTo(3L);
+ assertThat(usage.getReserved()).isEqualTo(2L);
+ }
+
+ @Test
+ void testToProtoWithoutStatsOmitsStorageTypeUsage() {
+ DatanodeUsageInfo info = new DatanodeUsageInfo(randomDatanodeDetails(),
null);
+
+
assertThat(info.toProto(ClientVersion.CURRENT).getStorageTypeUsageList()).isEmpty();
+ }
+
@Test
void testToProtoDoesNotIncludeFilesystemFieldsByDefault() {
DatanodeDetails dn = randomDatanodeDetails();
@@ -74,5 +136,61 @@ void testToProtoIncludesFilesystemFieldsWhenPresent() {
assertThat(proto.getFsCapacity()).isEqualTo(2000L);
assertThat(proto.getFsAvailable()).isEqualTo(1500L);
}
+
+ /**
+ * The balancer uses this to decide which tiers a node can take part in, so
it
+ * must report only storage types the node actually has capacity for.
+ */
+ @Test
+ void testGetStorageTypesReportsOnlyTypesWithCapacity() {
+ DatanodeUsageInfo info = new DatanodeUsageInfo(randomDatanodeDetails(),
+ twoTierStat());
+
+ assertThat(info.getStorageTypes())
+ .containsExactlyInAnyOrder(StorageType.SSD, StorageType.DISK);
+ }
+
+ /**
+ * Utilization must be measured per storage type, otherwise the balancer
cannot
+ * tell a node that is full on one tier from one that is full overall.
+ */
+ @Test
+ void testCalculateUtilizationPerStorageType() {
+ DatanodeUsageInfo info = new DatanodeUsageInfo(randomDatanodeDetails(),
+ twoTierStat());
+
+ // SSD: 100 capacity, 10 remaining -> 90% used.
+ assertThat(info.calculateUtilization(StorageType.SSD))
+ .isEqualTo(0.9, offset(0.0001));
+ // DISK: 100 capacity, 80 remaining -> 20% used.
+ assertThat(info.calculateUtilization(StorageType.DISK))
+ .isEqualTo(0.2, offset(0.0001));
+ // Whole node: 200 capacity, 90 remaining -> 55% used.
+ assertThat(info.calculateUtilization(null))
+ .isEqualTo(info.calculateUtilization());
+ assertThat(info.calculateUtilization(5L, StorageType.SSD)).isEqualTo(0.95,
offset(0.0001));
+ assertThat(info.calculateUtilization(5L,
null)).isEqualTo(info.calculateUtilization(5L));
+ // A tier the node does not have reports no usage rather than failing.
+ assertThat(info.calculateUtilization(StorageType.ARCHIVE)).isEqualTo(0.0);
+ }
+
+ /**
+ * A node with one unevenly used tier: SSD nearly full, DISK mostly free.
+ */
+ private static SCMNodeStat twoTierStat() {
+ Map<StorageType, Long> capacity = new HashMap<>();
+ capacity.put(StorageType.SSD, 100L);
+ capacity.put(StorageType.DISK, 100L);
+ Map<StorageType, Long> used = new HashMap<>();
+ used.put(StorageType.SSD, 90L);
+ used.put(StorageType.DISK, 20L);
+ Map<StorageType, Long> remaining = new HashMap<>();
+ remaining.put(StorageType.SSD, 10L);
+ remaining.put(StorageType.DISK, 80L);
+ Map<StorageType, Long> zeros = new HashMap<>();
+ zeros.put(StorageType.SSD, 0L);
+ zeros.put(StorageType.DISK, 0L);
+ return new SCMNodeStat(capacity, used, remaining, zeros, zeros, zeros);
+ }
}
diff --git
a/hadoop-ozone/cli-admin/src/main/java/org/apache/hadoop/hdds/scm/cli/ContainerBalancerAssessmentSubcommand.java
b/hadoop-ozone/cli-admin/src/main/java/org/apache/hadoop/hdds/scm/cli/ContainerBalancerAssessmentSubcommand.java
index 2b529ee603b..8e5dd33f12d 100644
---
a/hadoop-ozone/cli-admin/src/main/java/org/apache/hadoop/hdds/scm/cli/ContainerBalancerAssessmentSubcommand.java
+++
b/hadoop-ozone/cli-admin/src/main/java/org/apache/hadoop/hdds/scm/cli/ContainerBalancerAssessmentSubcommand.java
@@ -29,12 +29,14 @@
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;
+import org.apache.hadoop.fs.StorageType;
import org.apache.hadoop.hdds.cli.HddsVersionProvider;
import org.apache.hadoop.hdds.protocol.proto.HddsProtos.DatanodeUsageInfoProto;
import org.apache.hadoop.hdds.scm.client.ScmClient;
import
org.apache.hadoop.hdds.scm.container.balancer.ContainerBalancerClusterAnalyzer;
import
org.apache.hadoop.hdds.scm.container.balancer.ContainerBalancerClusterSnapshot;
import
org.apache.hadoop.hdds.scm.container.balancer.ContainerBalancerConfiguration;
+import org.apache.hadoop.hdds.scm.container.balancer.StorageTypeSnapshot;
import org.apache.hadoop.hdds.server.JsonUtils;
import picocli.CommandLine.Command;
import picocli.CommandLine.Option;
@@ -124,11 +126,41 @@ private static void
printReport(ContainerBalancerClusterSnapshot snapshot, doubl
System.out.println(getSummaryPrettyString(snapshot, thresholdRatio));
System.out.println();
- System.out.println(getSourceNodesPrettyString(snapshot, nodeLimit));
+ if (!snapshot.getStorageTypeSnapshots().isEmpty()) {
+ if (snapshot.hasIncompleteStorageTypeUsage()) {
+ System.out.println("WARNING: Missing or incomplete storage-type usage;
storage-type assessment is partial.");
+ }
+ StorageTypeSnapshot mostImbalanced =
snapshot.getStorageTypeSnapshots().get(
+ snapshot.getMostImbalancedStorageType());
+ System.out.printf("Maximum storage-type drift: %s (%s, max utilization
%s - min utilization %s)%n",
+ formatPercent(snapshot.getMaxImbalance()),
mostImbalanced.getStorageType(),
+ formatPercent(mostImbalanced.getMaxUtilization()),
formatPercent(mostImbalanced.getMinUtilization()));
+ for (Map.Entry<StorageType, StorageTypeSnapshot> entry
+ : snapshot.getStorageTypeSnapshots().entrySet()) {
+ StorageTypeSnapshot typeSnapshot = entry.getValue();
+ System.out.println("Storage type: " + entry.getKey());
+ System.out.println(getStorageTypeSummaryPrettyString(typeSnapshot,
thresholdRatio));
+
System.out.println(getSourceNodesPrettyString(typeSnapshot.getSourceCount(),
typeSnapshot.getTopSourceNodes(),
+ typeSnapshot.getAverageUtilization(), nodeLimit));
+
System.out.println(getTargetNodesPrettyString(typeSnapshot.getTargetCount(),
+ typeSnapshot.getBottomTargetNodes(),
typeSnapshot.getAverageUtilization(), nodeLimit));
+ System.out.println(getMovementSummaryPrettyString(
+ typeSnapshot.getBytesToMove(), typeSnapshot.getCapacityBytes(),
+ typeSnapshot.getStorageType() + " capacity"));
+ }
+ System.out.println("All storage types (shared iteration limits):");
+ System.out.println(getMovementSummaryPrettyString(
+ snapshot.getTotalBytesToMove(), snapshot.getClusterCapacityBytes(),
"cluster capacity"));
+ return;
+ }
+ System.out.println(getSourceNodesPrettyString(snapshot.getSourceCount(),
+ snapshot.getTopSourceNodesAcrossStorageTypes(),
snapshot.getClusterAvgUtilization(), nodeLimit));
System.out.println();
- System.out.println(getTargetNodesPrettyString(snapshot, nodeLimit));
+ System.out.println(getTargetNodesPrettyString(snapshot.getTargetCount(),
+ snapshot.getBottomTargetNodesAcrossStorageTypes(),
snapshot.getClusterAvgUtilization(), nodeLimit));
System.out.println();
- System.out.println(getMovementSummaryPrettyString(snapshot));
+ System.out.println(getMovementSummaryPrettyString(
+ snapshot.getTotalBytesToMove(), snapshot.getClusterCapacityBytes(),
"cluster capacity"));
}
private static String
getSummaryPrettyString(ContainerBalancerClusterSnapshot snapshot,
@@ -153,42 +185,72 @@ private static String
getSummaryPrettyString(ContainerBalancerClusterSnapshot sn
"%-50s %s%n" +
"%-50s %s%n", "Key", "Value",
"Threshold", formatPercent(thresholdRatio),
- "Upper utilization limit", formatPercent(snapshot.getUpperLimit()),
- "Lower utilization limit", formatPercent(snapshot.getLowerLimit()),
- "Drift", String.format(Locale.US, "%s (max utilization %s - min
utilization %s)",
+ snapshot.getStorageTypeSnapshots().isEmpty() ? "Upper utilization
limit" : "Overall upper utilization limit",
+ formatPercent(snapshot.getUpperLimit()),
+ snapshot.getStorageTypeSnapshots().isEmpty() ? "Lower utilization
limit" : "Overall lower utilization limit",
+ formatPercent(snapshot.getLowerLimit()),
+ snapshot.getStorageTypeSnapshots().isEmpty() ? "Drift" : "Overall
datanode drift",
+ String.format(Locale.US, "%s (max utilization %s - min utilization
%s)",
formatPercent(snapshot.getImbalance()),
formatPercent(snapshot.getMaxUtilization()),
formatPercent(snapshot.getMinUtilization())),
- "Mean Utilization", formatPercent(snapshot.getClusterAvgUtilization()),
+ snapshot.getStorageTypeSnapshots().isEmpty() ? "Mean Utilization" :
"Overall mean utilization",
+ formatPercent(snapshot.getClusterAvgUtilization()),
"Eligible datanodes", snapshot.getTotalEligibleDatanodes() + "
datanode"
+ (snapshot.getTotalEligibleDatanodes() == 1 ? "" : "s"),
- "Category", formatCategory(snapshot));
+ snapshot.getStorageTypeSnapshots().isEmpty() ? "Category" : "Category
(maximum storage-type imbalance)",
+ formatCategory(snapshot));
+ }
+
+ private static String getStorageTypeSummaryPrettyString(StorageTypeSnapshot
snapshot, double thresholdRatio) {
+ return String.format("%-50s %s%n" +
+ "%-50s %s%n" +
+ "%-50s %s%n" +
+ "%-50s %s%n" +
+ "%-50s %s%n" +
+ "%-50s %s%n" +
+ "%-50s %s%n" +
+ "%-50s %s%n", "Key", "Value",
+ "Threshold", formatPercent(thresholdRatio),
+ "Upper utilization limit", formatPercent(snapshot.getUpperLimit()),
+ "Lower utilization limit", formatPercent(snapshot.getLowerLimit()),
+ "Drift", String.format(Locale.US, "%s (max utilization %s - min
utilization %s)",
+ formatPercent(snapshot.getImbalance()),
formatPercent(snapshot.getMaxUtilization()),
+ formatPercent(snapshot.getMinUtilization())),
+ "Mean Utilization", formatPercent(snapshot.getAverageUtilization()),
+ "Eligible datanodes", snapshot.getEligibleDatanodes() + " datanode"
+ + (snapshot.getEligibleDatanodes() == 1 ? "" : "s"),
+ "Category", formatClusterSize(snapshot.getEligibleDatanodes()) + ", "
+ + formatImbalance(snapshot.getImbalance()) + ", "
+ + formatMovementRatio(snapshot.getBytesToMove(),
snapshot.getCapacityBytes()));
}
- private static String
getSourceNodesPrettyString(ContainerBalancerClusterSnapshot snapshot, int
nodeLimit) {
+ private static String getSourceNodesPrettyString(int sourceCount,
+ List<ContainerBalancerClusterSnapshot.NodeUtilization> nodes, double
averageUtilization, int nodeLimit) {
StringBuilder builder = new StringBuilder();
builder.append("Source Nodes
(over-utilized):").append(System.lineSeparator())
- .append(String.format("%-50s %s%n", "Datanodes above threshold",
snapshot.getSourceCount()));
- appendNodeList(builder, snapshot.getTopSourceNodes(),
snapshot.getClusterAvgUtilization(), true, nodeLimit);
+ .append(String.format("%-50s %s%n", "Datanodes above threshold",
sourceCount));
+ appendNodeList(builder, nodes, averageUtilization, true, nodeLimit);
return builder.toString();
}
- private static String
getTargetNodesPrettyString(ContainerBalancerClusterSnapshot snapshot, int
nodeLimit) {
+ private static String getTargetNodesPrettyString(int targetCount,
+ List<ContainerBalancerClusterSnapshot.NodeUtilization> nodes, double
averageUtilization, int nodeLimit) {
StringBuilder builder = new StringBuilder();
builder.append("Target Nodes
(under-utilized):").append(System.lineSeparator())
- .append(String.format("%-50s %s%n", "Datanodes below threshold",
snapshot.getTargetCount()));
- appendNodeList(builder, snapshot.getBottomTargetNodes(),
snapshot.getClusterAvgUtilization(), false, nodeLimit);
+ .append(String.format("%-50s %s%n", "Datanodes below threshold",
targetCount));
+ appendNodeList(builder, nodes, averageUtilization, false, nodeLimit);
return builder.toString();
}
- private static String
getMovementSummaryPrettyString(ContainerBalancerClusterSnapshot snapshot) {
- double movementRatio = snapshot.getClusterCapacityBytes() == 0 ? 0
- : (double) snapshot.getBytesToMove() /
snapshot.getClusterCapacityBytes();
+ private static String getMovementSummaryPrettyString(
+ long bytesToMove, long capacityBytes, String capacityDescription) {
+ double movementRatio = capacityBytes == 0 ? 0 : (double) bytesToMove /
capacityBytes;
return String.format("Movement Summary:%n" +
"%-50s %s%n" +
- "%-50s %s%n", "Total bytes to move",
byteDesc(snapshot.getBytesToMove()),
+ "%-50s %s%n", "Total bytes to move", byteDesc(bytesToMove),
"Movement ratio",
- formatPercent(movementRatio) + " of cluster capacity");
+ formatPercent(movementRatio) + " of " + capacityDescription);
}
private static void appendNodeList(StringBuilder builder,
@@ -222,8 +284,8 @@ private static double toJsonPercent(double ratio) {
private static String formatCategory(ContainerBalancerClusterSnapshot
snapshot) {
return formatClusterSize(snapshot.getTotalEligibleDatanodes()) + ", "
- + formatImbalance(snapshot.getImbalance()) + ", "
- + formatMovementRatio(snapshot);
+ + formatImbalance(snapshot.getMaxImbalance()) + ", "
+ + formatMovementRatio(snapshot.getTotalBytesToMove(),
snapshot.getClusterCapacityBytes());
}
private static String formatClusterSize(int eligibleDatanodes) {
@@ -246,11 +308,11 @@ private static String formatImbalance(double imbalance) {
return "Low imbalance";
}
- private static String formatMovementRatio(ContainerBalancerClusterSnapshot
snapshot) {
- if (snapshot.getClusterCapacityBytes() == 0) {
+ private static String formatMovementRatio(long bytesToMove, long
capacityBytes) {
+ if (capacityBytes == 0) {
return "Low movement ratio";
}
- double ratio = (double) snapshot.getBytesToMove() /
snapshot.getClusterCapacityBytes();
+ double ratio = (double) bytesToMove / capacityBytes;
if (ratio >= 0.05) {
return "High movement ratio";
}
@@ -262,6 +324,10 @@ private static String
formatMovementRatio(ContainerBalancerClusterSnapshot snaps
private static void printJsonReport(ContainerBalancerClusterSnapshot
snapshot, double thresholdRatio)
throws IOException {
+
System.out.println(JsonUtils.toJsonStringWithDefaultPrettyPrinter(jsonReport(snapshot,
thresholdRatio)));
+ }
+
+ private static Map<String, Object>
jsonReport(ContainerBalancerClusterSnapshot snapshot, double thresholdRatio) {
Map<String, Object> result = new LinkedHashMap<>();
result.put("totalEligibleDatanodes", snapshot.getTotalEligibleDatanodes());
result.put("thresholdPercentage", toJsonPercent(thresholdRatio));
@@ -272,36 +338,62 @@ private static void
printJsonReport(ContainerBalancerClusterSnapshot snapshot, d
result.put("upperLimitPercentage",
toJsonPercent(snapshot.getUpperLimit()));
result.put("lowerLimitPercentage",
toJsonPercent(snapshot.getLowerLimit()));
- Map<String, Object> sourceNodes = new LinkedHashMap<>();
- sourceNodes.put("count", snapshot.getSourceCount());
- sourceNodes.put("nodes", snapshot.getTopSourceNodes().stream()
- .map(node -> {
- Map<String, Object> nodeMap = new LinkedHashMap<>();
- nodeMap.put("hostname", node.getHostname());
- nodeMap.put("utilizationPercentage",
toJsonPercent(node.getUtilization()));
- return nodeMap;
- })
- .collect(Collectors.toList()));
- result.put("sourceNodes", sourceNodes);
-
- Map<String, Object> targetNodes = new LinkedHashMap<>();
- targetNodes.put("count", snapshot.getTargetCount());
- targetNodes.put("nodes", snapshot.getBottomTargetNodes().stream()
- .map(node -> {
- Map<String, Object> nodeMap = new LinkedHashMap<>();
- nodeMap.put("hostname", node.getHostname());
- nodeMap.put("utilizationPercentage",
toJsonPercent(node.getUtilization()));
- return nodeMap;
- })
- .collect(Collectors.toList()));
- result.put("targetNodes", targetNodes);
+ boolean typed = !snapshot.getStorageTypeSnapshots().isEmpty();
+ result.put(typed ? "sourceNodesAcrossStorageTypes" : "sourceNodes",
+ jsonNodesSummary(snapshot.getSourceCount(),
snapshot.getTopSourceNodesAcrossStorageTypes()));
+ result.put(typed ? "targetNodesAcrossStorageTypes" : "targetNodes",
+ jsonNodesSummary(snapshot.getTargetCount(),
snapshot.getBottomTargetNodesAcrossStorageTypes()));
double movementRatio = snapshot.getClusterCapacityBytes() == 0 ? 0
- : (double) snapshot.getBytesToMove() /
snapshot.getClusterCapacityBytes();
+ : (double) snapshot.getTotalBytesToMove() /
snapshot.getClusterCapacityBytes();
+ result.put(typed ? "totalBytesToMove" : "bytesToMove",
snapshot.getTotalBytesToMove());
+ result.put("movementRatioPercentage", toJsonPercent(movementRatio));
+
+ if (!snapshot.getStorageTypeSnapshots().isEmpty()) {
+ result.put("maxStorageTypeImbalancePercentage",
toJsonPercent(snapshot.getMaxImbalance()));
+ result.put("mostImbalancedStorageType",
snapshot.getMostImbalancedStorageType().name());
+ Map<String, Object> storageTypes = new LinkedHashMap<>();
+ snapshot.getStorageTypeSnapshots().forEach((type, usage) ->
+ storageTypes.put(type.name(), jsonReport(usage, thresholdRatio)));
+ result.put("storageTypes", storageTypes);
+ result.put("incompleteStorageTypeUsage",
snapshot.hasIncompleteStorageTypeUsage());
+ }
+ return result;
+ }
+
+ private static Map<String, Object> jsonReport(StorageTypeSnapshot snapshot,
double thresholdRatio) {
+ Map<String, Object> result = new LinkedHashMap<>();
+ result.put("totalEligibleDatanodes", snapshot.getEligibleDatanodes());
+ result.put("thresholdPercentage", toJsonPercent(thresholdRatio));
+ result.put("averageUtilizationPercentage",
toJsonPercent(snapshot.getAverageUtilization()));
+ result.put("driftPercentage", toJsonPercent(snapshot.getImbalance()));
+ result.put("maxUtilizationPercentage",
toJsonPercent(snapshot.getMaxUtilization()));
+ result.put("minUtilizationPercentage",
toJsonPercent(snapshot.getMinUtilization()));
+ result.put("upperLimitPercentage",
toJsonPercent(snapshot.getUpperLimit()));
+ result.put("lowerLimitPercentage",
toJsonPercent(snapshot.getLowerLimit()));
+ result.put("sourceNodes", jsonNodesSummary(snapshot.getSourceCount(),
snapshot.getTopSourceNodes()));
+ result.put("targetNodes", jsonNodesSummary(snapshot.getTargetCount(),
snapshot.getBottomTargetNodes()));
result.put("bytesToMove", snapshot.getBytesToMove());
+ double movementRatio = snapshot.getCapacityBytes() == 0 ? 0
+ : (double) snapshot.getBytesToMove() / snapshot.getCapacityBytes();
result.put("movementRatioPercentage", toJsonPercent(movementRatio));
+ return result;
+ }
- System.out.println(JsonUtils.toJsonStringWithDefaultPrettyPrinter(result));
+ private static Map<String, Object> jsonNodesSummary(int count,
+ List<ContainerBalancerClusterSnapshot.NodeUtilization> nodes) {
+ Map<String, Object> result = new LinkedHashMap<>();
+ result.put("count", count);
+ result.put("nodes", nodes.stream().map(node -> {
+ Map<String, Object> nodeMap = new LinkedHashMap<>();
+ nodeMap.put("hostname", node.getHostname());
+ nodeMap.put("utilizationPercentage",
toJsonPercent(node.getUtilization()));
+ if (node.getStorageType() != null) {
+ nodeMap.put("storageType", node.getStorageType().name());
+ }
+ return nodeMap;
+ }).collect(Collectors.toList()));
+ return result;
}
private static Set<String> parseNodeList(String commaSeparated) {
diff --git
a/hadoop-ozone/cli-admin/src/main/java/org/apache/hadoop/hdds/scm/cli/ContainerBalancerCommands.java
b/hadoop-ozone/cli-admin/src/main/java/org/apache/hadoop/hdds/scm/cli/ContainerBalancerCommands.java
index c65cb1f4ca1..dc44d3d5de8 100644
---
a/hadoop-ozone/cli-admin/src/main/java/org/apache/hadoop/hdds/scm/cli/ContainerBalancerCommands.java
+++
b/hadoop-ozone/cli-admin/src/main/java/org/apache/hadoop/hdds/scm/cli/ContainerBalancerCommands.java
@@ -93,6 +93,11 @@
* support {@code --profile}, compare estimate profiles to the config you plan
* to pass on start, or wait until profile support is added to start.
* estimate subcommand produces upper-bound estimates.
+ * <p>Assessment and estimate compare usage separately for each storage type
when
+ * SCM reports that information. They use whole-node usage when no storage-type
+ * breakdown is available. Incomplete storage-type reports produce an
assessment
+ * warning and prevent estimation. The running balancer still selects moves
using
+ * whole-node usage; per-storage-type move selection is separate work.
* <p>The threshold parameter is a fraction in the range of (1%, 100%) with a
* default value of 10%. The threshold sets a target for whether the cluster
* is balanced. A cluster is balanced if for each datanode, the utilization
diff --git
a/hadoop-ozone/cli-admin/src/test/java/org/apache/hadoop/hdds/scm/cli/TestContainerBalancerAssessmentSubcommand.java
b/hadoop-ozone/cli-admin/src/test/java/org/apache/hadoop/hdds/scm/cli/TestContainerBalancerAssessmentSubcommand.java
index 1d255954213..feaa5727db6 100644
---
a/hadoop-ozone/cli-admin/src/test/java/org/apache/hadoop/hdds/scm/cli/TestContainerBalancerAssessmentSubcommand.java
+++
b/hadoop-ozone/cli-admin/src/test/java/org/apache/hadoop/hdds/scm/cli/TestContainerBalancerAssessmentSubcommand.java
@@ -24,12 +24,16 @@
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.UUID;
import org.apache.hadoop.hdds.protocol.DatanodeDetails;
import org.apache.hadoop.hdds.protocol.proto.HddsProtos.DatanodeUsageInfoProto;
+import org.apache.hadoop.hdds.protocol.proto.HddsProtos.StorageTypeProto;
+import
org.apache.hadoop.hdds.protocol.proto.HddsProtos.StorageTypeUsageInfoProto;
import org.apache.hadoop.hdds.scm.client.ScmClient;
import org.apache.hadoop.hdds.utils.IOUtils;
import org.apache.ozone.test.GenericTestUtils;
@@ -55,6 +59,159 @@ void tearDown() {
IOUtils.closeQuietly(out);
}
+ @Test
+ void testAssessmentReportsImbalanceSeparatelyForEachStorageType() {
+ ScmClient scmClient = mock(ScmClient.class);
+ mockUsageInfo(scmClient, Arrays.asList(typedProto("first", 5, 95),
typedProto("second", 95, 5)));
+
+ runAssessment(scmClient);
+
+ assertThat(out.get()).contains("Storage type: SSD", "Storage type: DISK",
"35 B", "70 B",
+ "All storage types (shared iteration limits):", "of SSD capacity", "of
DISK capacity", "of cluster capacity")
+ .doesNotContain("WARNING");
+ }
+
+ @Test
+ void testJsonAssessmentIncludesStorageTypesAndUniqueDatanodeCounts() {
+ ScmClient scmClient = mock(ScmClient.class);
+ mockUsageInfo(scmClient, Arrays.asList(typedProto("first", 5, 95),
typedProto("second", 95, 5)));
+
+ runAssessment(scmClient, "--json");
+
+ assertThat(out.get()).contains("\"storageTypes\"", "\"SSD\"", "\"DISK\"",
+ "\"totalBytesToMove\" : 70", "\"count\" : 2",
"\"incompleteStorageTypeUsage\" : false");
+ }
+
+ @Test
+ void
testAssessmentIdentifiesMostImbalancedTypeSeparatelyFromOverallUtilization() {
+ ScmClient scmClient = mock(ScmClient.class);
+ mockUsageInfo(scmClient, Arrays.asList(typedProto("first", 5, 50),
typedProto("second", 35, 90)));
+
+ runAssessment(scmClient);
+
+ assertThat(out.get()).contains("Overall datanode drift", "35.0% (max
utilization 72.5% - min utilization 37.5%)",
+ "Maximum storage-type drift: 40.0% (DISK, max utilization 50.0% - min
utilization 10.0%)",
+ "30.0% (max utilization 95.0% - min utilization 65.0%)");
+ }
+
+ @Test
+ void testJsonSeparatesOverallUtilizationFromStorageTypeMovement() throws
IOException {
+ ScmClient scmClient = mock(ScmClient.class);
+ mockUsageInfo(scmClient, Arrays.asList(typedProto("first", 5, 50),
typedProto("second", 35, 90)));
+
+ runAssessment(scmClient, "--json");
+
+ JsonNode report = new ObjectMapper().readTree(out.get());
+
assertThat(report.path("clusterAvgUtilizationPercentage").asDouble()).isEqualTo(55.0);
+
assertThat(report.path("maxUtilizationPercentage").asDouble()).isEqualTo(72.5);
+
assertThat(report.path("minUtilizationPercentage").asDouble()).isEqualTo(37.5);
+ assertThat(report.path("driftPercentage").asDouble()).isEqualTo(35.0);
+
assertThat(report.path("maxStorageTypeImbalancePercentage").asDouble()).isEqualTo(40.0);
+
assertThat(report.path("mostImbalancedStorageType").asText()).isEqualTo("DISK");
+ JsonNode source = report.path("sourceNodesAcrossStorageTypes");
+ assertThat(source.path("count").asInt()).isEqualTo(1);
+
assertThat(source.path("nodes").get(0).path("storageType").asText()).isEqualTo("SSD");
+
assertThat(source.path("nodes").get(0).path("utilizationPercentage").asDouble()).isEqualTo(95.0);
+ JsonNode target = report.path("targetNodesAcrossStorageTypes");
+ assertThat(target.path("count").asInt()).isEqualTo(1);
+
assertThat(target.path("nodes").get(0).path("storageType").asText()).isEqualTo("DISK");
+
assertThat(target.path("nodes").get(0).path("utilizationPercentage").asDouble()).isEqualTo(10.0);
+ JsonNode disk = report.path("storageTypes").path("DISK");
+
assertThat(disk.path("maxUtilizationPercentage").asDouble()).isEqualTo(50.0);
+
assertThat(disk.path("minUtilizationPercentage").asDouble()).isEqualTo(10.0);
+ JsonNode ssd = report.path("storageTypes").path("SSD");
+
assertThat(ssd.path("maxUtilizationPercentage").asDouble()).isEqualTo(95.0);
+
assertThat(ssd.path("minUtilizationPercentage").asDouble()).isEqualTo(65.0);
+ assertThat(report.path("totalBytesToMove").asLong()).isEqualTo(
+ disk.path("bytesToMove").asLong() + ssd.path("bytesToMove").asLong());
+ assertThat(report.has("sourceNodes")).isFalse();
+ assertThat(report.has("targetNodes")).isFalse();
+ assertThat(report.has("bytesToMove")).isFalse();
+ }
+
+ @Test
+ void testJsonCombinedNodesAreEmptyWhenNoStorageTypeHasMovement() throws
IOException {
+ ScmClient scmClient = mock(ScmClient.class);
+ mockUsageInfo(scmClient, Arrays.asList(
+ typedProto("first", 0, 100), typedProto("second", 40, 60),
typedProto("third", 40, 60)));
+
+ runAssessment(scmClient, "--json", "-t", "20");
+
+ JsonNode report = new ObjectMapper().readTree(out.get());
+ assertThat(report.path("totalBytesToMove").asLong()).isZero();
+
assertThat(report.path("sourceNodesAcrossStorageTypes").path("count").asInt()).isZero();
+
assertThat(report.path("sourceNodesAcrossStorageTypes").path("nodes").size()).isZero();
+
assertThat(report.path("targetNodesAcrossStorageTypes").path("count").asInt()).isZero();
+
assertThat(report.path("targetNodesAcrossStorageTypes").path("nodes").size()).isZero();
+
assertThat(report.path("maxStorageTypeImbalancePercentage").asDouble()).isEqualTo(40.0);
+ JsonNode ssd = report.path("storageTypes").path("SSD");
+ assertThat(ssd.path("sourceNodes").path("count").asInt()).isEqualTo(1);
+
assertThat(ssd.path("sourceNodes").path("nodes").get(0).path("hostname").asText()).isEqualTo("first");
+ assertThat(ssd.path("targetNodes").path("count").asInt()).isZero();
+ assertThat(ssd.path("bytesToMove").asLong()).isZero();
+ JsonNode disk = report.path("storageTypes").path("DISK");
+ assertThat(disk.path("sourceNodes").path("count").asInt()).isZero();
+ assertThat(disk.path("targetNodes").path("count").asInt()).isEqualTo(1);
+
assertThat(disk.path("targetNodes").path("nodes").get(0).path("hostname").asText()).isEqualTo("first");
+ assertThat(disk.path("bytesToMove").asLong()).isZero();
+ }
+
+ @Test
+ void testJsonCombinedNodesExcludeUnpairedStorageType() throws IOException {
+ ScmClient scmClient = mock(ScmClient.class);
+ mockUsageInfo(scmClient, Arrays.asList(
+ typedProto("first", 0, 20), typedProto("second", 40, 60),
typedProto("third", 40, 100)));
+
+ runAssessment(scmClient, "--json", "-t", "20");
+
+ JsonNode report = new ObjectMapper().readTree(out.get());
+ JsonNode source = report.path("sourceNodesAcrossStorageTypes");
+ assertThat(source.path("count").asInt()).isEqualTo(1);
+ assertThat(source.path("nodes").size()).isEqualTo(1);
+
assertThat(source.path("nodes").get(0).path("storageType").asText()).isEqualTo("DISK");
+
assertThat(source.path("nodes").get(0).path("utilizationPercentage").asDouble()).isEqualTo(80.0);
+ JsonNode target = report.path("targetNodesAcrossStorageTypes");
+ assertThat(target.path("count").asInt()).isEqualTo(1);
+ assertThat(target.path("nodes").size()).isEqualTo(1);
+
assertThat(target.path("nodes").get(0).path("storageType").asText()).isEqualTo("DISK");
+
assertThat(target.path("nodes").get(0).path("hostname").asText()).isEqualTo("third");
+ JsonNode ssd = report.path("storageTypes").path("SSD");
+
assertThat(ssd.path("sourceNodes").path("nodes").get(0).path("utilizationPercentage").asDouble()).isEqualTo(100.0);
+ assertThat(ssd.path("bytesToMove").asLong()).isZero();
+
assertThat(report.path("totalBytesToMove").asLong()).isPositive().isEqualTo(
+ report.path("storageTypes").path("DISK").path("bytesToMove").asLong());
+ }
+
+ @Test
+ void testLegacyJsonKeepsAggregateFields() throws IOException {
+ ScmClient scmClient = mock(ScmClient.class);
+ mockUsageInfo(scmClient, sampleNodes());
+
+ runAssessment(scmClient, "--json");
+
+ JsonNode report = new ObjectMapper().readTree(out.get());
+
assertThat(report.path("maxUtilizationPercentage").asDouble()).isEqualTo(90.0);
+
assertThat(report.path("minUtilizationPercentage").asDouble()).isEqualTo(50.0);
+ assertThat(report.path("driftPercentage").asDouble()).isEqualTo(40.0);
+ assertThat(report.path("sourceNodes").path("count").asInt()).isEqualTo(1);
+ assertThat(report.path("targetNodes").path("count").asInt()).isEqualTo(1);
+ assertThat(report.path("bytesToMove").asLong()).isEqualTo(10);
+ assertThat(report.has("storageTypes")).isFalse();
+ assertThat(report.has("mostImbalancedStorageType")).isFalse();
+ assertThat(report.has("totalBytesToMove")).isFalse();
+ }
+
+ @Test
+ void testAssessmentWarnsWhenStorageTypeReportsAreIncomplete() {
+ ScmClient scmClient = mock(ScmClient.class);
+ mockUsageInfo(scmClient, Arrays.asList(typedProto("new", 5, 95),
proto("legacy", 200, 100)));
+
+ runAssessment(scmClient);
+
+ assertThat(out.get()).contains("WARNING: Missing or incomplete
storage-type usage",
+ "storage-type assessment is partial");
+ }
+
@Test
void testDefaultAssessmentOutput() {
ScmClient scmClient = mock(ScmClient.class);
@@ -159,6 +316,14 @@ private static List<DatanodeUsageInfoProto> sampleNodes() {
proto("target-1", 100, 50));
}
+ private static DatanodeUsageInfoProto typedProto(String hostname, long
ssdRemaining, long diskRemaining) {
+ return proto(hostname, 200, ssdRemaining + diskRemaining).toBuilder()
+
.addStorageTypeUsage(StorageTypeUsageInfoProto.newBuilder().setStorageType(StorageTypeProto.SSD)
+ .setCapacity(100).setRemaining(ssdRemaining))
+
.addStorageTypeUsage(StorageTypeUsageInfoProto.newBuilder().setStorageType(StorageTypeProto.DISK)
+ .setCapacity(100).setRemaining(diskRemaining)).build();
+ }
+
private static DatanodeUsageInfoProto proto(String hostname, long capacity,
long remaining) {
DatanodeDetails datanode = DatanodeDetails.newBuilder()
.setHostName(hostname)
diff --git
a/hadoop-ozone/cli-admin/src/test/java/org/apache/hadoop/hdds/scm/cli/TestContainerBalancerSubCommand.java
b/hadoop-ozone/cli-admin/src/test/java/org/apache/hadoop/hdds/scm/cli/TestContainerBalancerSubCommand.java
index fdb27603d82..b962240a986 100644
---
a/hadoop-ozone/cli-admin/src/test/java/org/apache/hadoop/hdds/scm/cli/TestContainerBalancerSubCommand.java
+++
b/hadoop-ozone/cli-admin/src/test/java/org/apache/hadoop/hdds/scm/cli/TestContainerBalancerSubCommand.java
@@ -831,6 +831,30 @@ void
testContainerBalancerStatusVerboseShowsNoBreakdownWhenFailuresMissing() thr
.contains("Failed container moves (no
breakdown available)");
}
+ @Test
+ void testContainerBalancerEstimateUsesPerStorageTypeUsage() throws
IOException {
+ ScmClient scmClient = mock(ScmClient.class);
+ when(scmClient.getDatanodeUsageInfo(true,
Integer.MAX_VALUE)).thenReturn(Arrays.asList(
+ typedDatanodeUsageProto("first", 5, 95),
typedDatanodeUsageProto("second", 95, 5)));
+
+ parseSubcommand(estimateCmd, "-d", "100");
+ estimateCmd.execute(scmClient);
+
+ assertThat(out.get()).contains("Bytes to move:", byteDesc(70L * GB),
+ "Per iteration (estimate): ~" + byteDesc(26L *
GB)).doesNotContain("Estimation failed:");
+ }
+
+ @Test
+ void testContainerBalancerEstimateRejectsPartialStorageTypeUsage() throws
IOException {
+ ScmClient scmClient = mock(ScmClient.class);
+ when(scmClient.getDatanodeUsageInfo(true,
Integer.MAX_VALUE)).thenReturn(Arrays.asList(
+ typedDatanodeUsageProto("new", 5, 95), datanodeUsageProto("legacy",
200L * GB, 100L * GB)));
+
+ parseSubcommand(estimateCmd, "-d", "100");
+ IOException ex = assertThrows(IOException.class, () ->
estimateCmd.execute(scmClient));
+ assertThat(ex).hasMessageContaining("missing or incomplete storage-type
usage");
+ }
+
@Test
void testContainerBalancerEstimateSubcommandDefaultShowsMediumProfile()
throws IOException {
ScmClient scmClient = mock(ScmClient.class);
@@ -1054,6 +1078,16 @@ private static List<HddsProtos.DatanodeUsageInfoProto>
buildCluster(
return nodes;
}
+ private static HddsProtos.DatanodeUsageInfoProto typedDatanodeUsageProto(
+ String hostname, long ssdRemaining, long diskRemaining) {
+ return datanodeUsageProto(hostname, 200L * GB, (ssdRemaining +
diskRemaining) * GB).toBuilder()
+ .addStorageTypeUsage(HddsProtos.StorageTypeUsageInfoProto.newBuilder()
+ .setStorageType(HddsProtos.StorageTypeProto.SSD).setCapacity(100L
* GB).setRemaining(ssdRemaining * GB))
+ .addStorageTypeUsage(HddsProtos.StorageTypeUsageInfoProto.newBuilder()
+ .setStorageType(HddsProtos.StorageTypeProto.DISK).setCapacity(100L
* GB).setRemaining(diskRemaining * GB))
+ .build();
+ }
+
private static HddsProtos.DatanodeUsageInfoProto datanodeUsageProto(
String hostname, long capacity, long remaining) {
DatanodeDetails datanode = DatanodeDetails.newBuilder()
diff --git
a/hadoop-ozone/integration-test-recon/src/test/java/org/apache/hadoop/ozone/recon/TestReconAsPassiveScm.java
b/hadoop-ozone/integration-test-recon/src/test/java/org/apache/hadoop/ozone/recon/TestReconAsPassiveScm.java
index cd8d5381cd8..b15b7757981 100644
---
a/hadoop-ozone/integration-test-recon/src/test/java/org/apache/hadoop/ozone/recon/TestReconAsPassiveScm.java
+++
b/hadoop-ozone/integration-test-recon/src/test/java/org/apache/hadoop/ozone/recon/TestReconAsPassiveScm.java
@@ -138,9 +138,11 @@ public void testDatanodeRegistrationAndReports() throws
Exception {
XceiverClientGrpc client = new XceiverClientGrpc(pipeline, conf);
runTestOzoneContainerViaDataNode(containerID, client);
- // Verify Recon picked up the new container that was created.
- assertEquals(scmContainerManager.getContainers(),
- reconContainerManager.getContainers());
+ // Recon processes datanode reports asynchronously, so wait for the new
container to appear.
+ LambdaTestUtils.await(60000, 1000, () -> {
+ assertEquals(scmContainerManager.getContainers(),
reconContainerManager.getContainers());
+ return true;
+ });
LogCapturer logCapturer = LogCapturer.captureLogs(ReconNodeManager.class);
GenericTestUtils.setLogLevel(ReconNodeManager.class, Level.DEBUG);
diff --git
a/hadoop-ozone/integration-test/src/test/java/org/apache/hadoop/hdds/scm/TestContainerOperations.java
b/hadoop-ozone/integration-test/src/test/java/org/apache/hadoop/hdds/scm/TestContainerOperations.java
index d081747000f..113dc0d86e7 100644
---
a/hadoop-ozone/integration-test/src/test/java/org/apache/hadoop/hdds/scm/TestContainerOperations.java
+++
b/hadoop-ozone/integration-test/src/test/java/org/apache/hadoop/hdds/scm/TestContainerOperations.java
@@ -184,6 +184,7 @@ public void testDatanodeUsageInfoCompatibility() throws
IOException {
for (HddsProtos.DatanodeUsageInfoProto info : usageInfoList) {
assertTrue(info.getNode().getPortsList().stream()
.anyMatch(port -> REPLICATION.name().equals(port.getName())));
+ assertStorageTypeUsageMatchesTotals(info);
}
usageInfoList =
@@ -192,9 +193,20 @@ public void testDatanodeUsageInfoCompatibility() throws
IOException {
for (HddsProtos.DatanodeUsageInfoProto info : usageInfoList) {
assertTrue(info.getNode().getPortsList().stream()
.anyMatch(port -> REPLICATION.name().equals(port.getName())));
+ assertStorageTypeUsageMatchesTotals(info);
}
}
+ private static void
assertStorageTypeUsageMatchesTotals(HddsProtos.DatanodeUsageInfoProto info) {
+ assertThat(info.getStorageTypeUsageList()).isNotEmpty();
+ assertEquals(info.getCapacity(), info.getStorageTypeUsageList().stream()
+ .mapToLong(HddsProtos.StorageTypeUsageInfoProto::getCapacity).sum());
+ assertEquals(info.getUsed(), info.getStorageTypeUsageList().stream()
+ .mapToLong(HddsProtos.StorageTypeUsageInfoProto::getUsed).sum());
+ assertEquals(info.getRemaining(), info.getStorageTypeUsageList().stream()
+ .mapToLong(HddsProtos.StorageTypeUsageInfoProto::getRemaining).sum());
+ }
+
@Test
public void testDatanodeUsageInfoContainerCount() throws Exception {
NodeManager nodeManager =
cluster().getStorageContainerManager().getScmNodeManager();
---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]