You are viewing a plain text version of this content. The canonical link for it is here.
Posted to issues@ozone.apache.org by "ashishkumar50 (via GitHub)" <gi...@apache.org> on 2026/03/30 04:23:46 UTC
[PR] HDDS-14921. Improve space accounting in SCM with In-Flight container allocation tracking. [ozone]
ashishkumar50 opened a new pull request, #10000:
URL: https://github.com/apache/ozone/pull/10000
## What changes were proposed in this pull request?
Maintain space accounting during container allocation in SCM. More detail description is in Jira.
## What is the link to the Apache JIRA
https://issues.apache.org/jira/browse/HDDS-14921
## How was this patch tested?
UT and IT. (More test scenario TBD)
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org
For additional commands, e-mail: issues-help@ozone.apache.org
Re: [PR] HDDS-14921. Improve space accounting in SCM with In-Flight container allocation tracking. [ozone]
Posted by "ashishkumar50 (via GitHub)" <gi...@apache.org>.
ashishkumar50 commented on code in PR #10000:
URL: https://github.com/apache/ozone/pull/10000#discussion_r3035996607
##########
hadoop-hdds/server-scm/src/main/java/org/apache/hadoop/hdds/scm/container/ContainerReportHandler.java:
##########
@@ -175,6 +175,15 @@ public void onMessage(final ContainerReportFromDatanode reportFromDatanode,
if (!alreadyInDn) {
// This is a new Container not in the nodeManager -> dn map yet
getNodeManager().addContainer(datanodeDetails, cid);
+
+ // Remove from pending tracker when container is added to DN
+ // This container was just confirmed for the first time on this DN
+ // No need to remove on subsequent reports (it's already been removed)
+ if (container != null && getContainerManager() instanceof ContainerManagerImpl) {
Review Comment:
Same now
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org
For additional commands, e-mail: issues-help@ozone.apache.org
Re: [PR] HDDS-14921. Improve space accounting in SCM with In-Flight container allocation tracking. [ozone]
Posted by "ashishkumar50 (via GitHub)" <gi...@apache.org>.
ashishkumar50 commented on PR #10000:
URL: https://github.com/apache/ozone/pull/10000#issuecomment-4204786858
@rakeshadr @aswinshakil Fixed review comments.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org
For additional commands, e-mail: issues-help@ozone.apache.org
Re: [PR] HDDS-14921. Improve space accounting in SCM with In-Flight container allocation tracking. [ozone]
Posted by "szetszwo (via GitHub)" <gi...@apache.org>.
szetszwo commented on code in PR #10000:
URL: https://github.com/apache/ozone/pull/10000#discussion_r3183672411
##########
hadoop-hdds/server-scm/src/test/java/org/apache/hadoop/hdds/scm/pipeline/MockPipelineManager.java:
##########
Review Comment:
recordPendingAllocation(..) is not used anywhere. Please remove it.
##########
hadoop-hdds/server-scm/src/main/java/org/apache/hadoop/hdds/scm/pipeline/PipelineManager.java:
##########
@@ -232,6 +232,17 @@ void reinitialize(Table<PipelineID, Pipeline> pipelineStore)
*/
boolean hasEnoughSpace(Pipeline pipeline);
Review Comment:
hasEnoughSpace(..) is now only used in tests. Please remove it.
##########
hadoop-hdds/server-scm/src/main/java/org/apache/hadoop/hdds/scm/node/SCMNodeManager.java:
##########
Review Comment:
hasSpaceForNewContainerAllocation and hasEffectiveAllocatableSpaceForNewContainer are also become unused.
##########
hadoop-hdds/server-scm/src/main/java/org/apache/hadoop/hdds/scm/container/ContainerReportHandler.java:
##########
@@ -153,6 +154,7 @@ public void onMessage(final ContainerReportFromDatanode reportFromDatanode,
containerReport.getReportsList();
final Set<ContainerID> expectedContainersInDatanode =
getNodeManager().getContainers(datanodeDetails);
+ DatanodeInfo datanodeInfo = getNodeManager().getDatanodeInfo(datanodeDetails);
Review Comment:
datanodeDetails and datanodeInfo are the same object; see HDDS-15146.
##########
hadoop-hdds/server-scm/src/test/java/org/apache/hadoop/hdds/scm/pipeline/MockPipelineManager.java:
##########
@@ -335,7 +335,12 @@ public boolean isPipelineCreationFrozen() {
@Override
public boolean hasEnoughSpace(Pipeline pipeline) {
- return false;
+ for (DatanodeDetails node : pipeline.getNodes()) {
+ if (!nodeManager.hasSpaceForNewContainerAllocation(node.getID())) {
Review Comment:
After hasEnoughSpace(..) is removed, hasSpaceForNewContainerAllocation(..) is also only used in tests. Please remove it.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org
For additional commands, e-mail: issues-help@ozone.apache.org
Re: [PR] HDDS-14921. Improve space accounting in SCM with In-Flight container allocation tracking. [ozone]
Posted by "rakeshadr (via GitHub)" <gi...@apache.org>.
rakeshadr commented on code in PR #10000:
URL: https://github.com/apache/ozone/pull/10000#discussion_r3038092049
##########
hadoop-hdds/server-scm/src/main/java/org/apache/hadoop/hdds/scm/container/ContainerManagerImpl.java:
##########
Review Comment:
Since this PR is adding more stricter/defensive "two-window tumbling bucket" logic, there is a high chance to hit the `return null` code path flow. Please double check all the callers of API [ContainerManagerImpl#allocateContainer()](https://github.com/apache/ozone/blob/master/hadoop-hdds/server-scm/src/main/java/org/apache/hadoop/hdds/scm/container/ContainerManagerImpl.java#L245) then safeguard with null check, otw it would result in NPE.
For example, [SCMClientProtocolServer.java#L258](https://github.com/apache/ozone/blob/master/hadoop-hdds/server-scm/src/main/java/org/apache/hadoop/hdds/scm/server/SCMClientProtocolServer.java#L258), this would hit NPE.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org
For additional commands, e-mail: issues-help@ozone.apache.org
Re: [PR] HDDS-14921. Improve space accounting in SCM with In-Flight container allocation tracking. [ozone]
Posted by "ashishkumar50 (via GitHub)" <gi...@apache.org>.
ashishkumar50 commented on code in PR #10000:
URL: https://github.com/apache/ozone/pull/10000#discussion_r3050030672
##########
hadoop-hdds/server-scm/src/main/java/org/apache/hadoop/hdds/scm/node/PendingContainerTracker.java:
##########
@@ -0,0 +1,425 @@
+/*
+ * 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.node;
+
+import com.google.common.annotations.VisibleForTesting;
+import java.util.Collections;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Set;
+import java.util.UUID;
+import java.util.concurrent.ConcurrentHashMap;
+import org.apache.hadoop.hdds.protocol.DatanodeDetails;
+import org.apache.hadoop.hdds.protocol.proto.StorageContainerDatanodeProtocolProtos.StorageReportProto;
+import org.apache.hadoop.hdds.scm.container.ContainerID;
+import org.apache.hadoop.hdds.scm.pipeline.Pipeline;
+import org.apache.hadoop.ozone.container.common.volume.VolumeUsage;
+import org.apache.hadoop.util.Time;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * Tracks per-datanode pending container allocations at SCM using a Two Window Tumbling Bucket
+ * pattern (similar to HDFS HADOOP-3707).
+ *
+ * Two Window Tumbling Bucket for automatic aging and cleanup.
+ *
+ * How It Works:
+ * <li>Each DataNode has two sets: <b>currentWindow</b> and <b>previousWindow</b></li>
+ * <li>New allocations go into <b>currentWindow</b></li>
+ * <li>Every <b>ROLL_INTERVAL</b> (default 5 minutes):
+ * <ul>
+ * <li>previousWindow = currentWindow (shift)</li>
+ * <li>currentWindow = new empty set (reset)</li>
+ * <li>Old previousWindow is discarded (automatic aging)</li>
+ * </ul>
+ * </li>
+ * <li>When checking pending: return <b>union</b> of currentWindow + previousWindow</li>
+ *
+ *
+ * Example Timeline:
+ * <pre>
+ * Time | Action | CurrentWindow | PreviousWindow | Total Pending
+ * ------+---------------------------+---------------+----------------+--------------
+ * 00:00 | Allocate Container-1 | {C1} | {} | {C1}
+ * 00:02 | Allocate Container-2 | {C1, C2} | {} | {C1, C2}
+ * 00:05 | [ROLL] Window tumbles | {} | {C1, C2} | {C1, C2}
+ * 00:07 | Allocate Container-3 | {C3} | {C1, C2} | {C1, C2, C3}
+ * 00:08 | Report confirms C1 | {C3} | {C2} | {C2, C3}
+ * 00:10 | [ROLL] Window tumbles | {} | {C3} | {C3}
+ * | (C2 aged out if not reported)
+ * </pre>
+ *
+ * <p>Thread-safety: all mutations and reads for a given datanode run under
+ * {@code synchronized (bucket)} on that datanode's {@link TwoWindowBucket}, including
+ * map insert/remove, so concurrent record/remove/report paths cannot interleave or orphan
+ * a bucket after it was dropped from the map.</p>
+ */
+public class PendingContainerTracker {
+
+ private static final Logger LOG = LoggerFactory.getLogger(PendingContainerTracker.class);
+
+ /**
+ * Roll interval in milliseconds.
+ * Configurable via hdds.scm.container.pending.allocation.roll.interval.
+ * Default: 5 minutes.
+ * Containers automatically age out after 2 × rollIntervalMs.
+ */
+ private final long rollIntervalMs;
+
+ /**
+ * Map of DataNode UUID to TwoWindowBucket.
+ */
+ private final ConcurrentHashMap<UUID, TwoWindowBucket> datanodeBuckets;
+
+ /**
+ * Maximum container size in bytes.
+ */
+ private final long maxContainerSize;
+
+ /**
+ * Metrics for tracking pending containers (same instance as {@link SCMNodeManager}'s node metrics).
+ */
+ private final SCMNodeMetrics metrics;
+
+ /**
+ * Two-window bucket for a single DataNode.
+ * Contains current and previous window sets, plus last roll timestamp.
+ */
+ private static class TwoWindowBucket {
+ private Set<ContainerID> currentWindow = new HashSet<>();
+ private Set<ContainerID> previousWindow = new HashSet<>();
+ private long lastRollTime = Time.monotonicNow();
+ private final long rollIntervalMs;
+
+ TwoWindowBucket(long rollIntervalMs) {
+ this.rollIntervalMs = rollIntervalMs;
+ }
+
+ /**
+ * Roll the windows: previous = current, current = empty.
+ * Called when current time exceeds lastRollTime + rollIntervalMs.
+ */
+ synchronized void rollIfNeeded() {
+ long now = Time.monotonicNow();
+ if (now - lastRollTime >= rollIntervalMs) {
+ // Shift: current becomes previous
+ previousWindow = currentWindow;
+ // Reset: new empty current window
+ currentWindow = new HashSet<>();
+ lastRollTime = now;
+ LOG.debug("Rolled window. Previous window size: {}, Current window reset to empty", previousWindow.size());
+ }
+ }
+
+ /**
+ * Get union of both windows (all pending containers).
+ */
+ synchronized Set<ContainerID> getAllPending() {
+ Set<ContainerID> all = new HashSet<>();
+ all.addAll(currentWindow);
+ all.addAll(previousWindow);
+ return all;
+ }
+
+ /**
+ * Add container to current window.
+ */
+ synchronized boolean add(ContainerID containerID) {
+ return currentWindow.add(containerID);
+ }
+
+ /**
+ * Remove container from both windows.
+ */
+ synchronized boolean remove(ContainerID containerID) {
+ boolean removedFromCurrent = currentWindow.remove(containerID);
+ boolean removedFromPrevious = previousWindow.remove(containerID);
+ return removedFromCurrent || removedFromPrevious;
+ }
+
+ /**
+ * Check if either window is non-empty.
+ */
+ synchronized boolean isEmpty() {
+ return currentWindow.isEmpty() && previousWindow.isEmpty();
+ }
+
+ /**
+ * Count of pending containers in both windows.
+ */
+ synchronized int getCount() {
+ return currentWindow.size() + previousWindow.size();
Review Comment:
getAllPending is creating two new set which may be costly. Instead this looks less costly. Sumit had given comment above to avoid creating new list. If we want other way then we need to cache size value, which i think may not be needed here to store size as well.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org
For additional commands, e-mail: issues-help@ozone.apache.org
Re: [PR] HDDS-14921. Improve space accounting in SCM with In-Flight container allocation tracking. [ozone]
Posted by "ashishkumar50 (via GitHub)" <gi...@apache.org>.
ashishkumar50 commented on code in PR #10000:
URL: https://github.com/apache/ozone/pull/10000#discussion_r3035996309
##########
hadoop-hdds/common/src/main/java/org/apache/hadoop/hdds/scm/ScmConfig.java:
##########
@@ -138,10 +138,31 @@ public class ScmConfig extends ReconfigurableConfig {
)
private int transactionToDNsCommitMapLimit = 5000000;
+ @Config(key = "hdds.scm.container.pending-allocation.roll-interval",
+ defaultValue = "10m",
+ type = ConfigType.TIME,
+ tags = { ConfigTag.SCM, ConfigTag.CONTAINER },
+ description =
+ "Time interval for rolling the pending container allocation window. " +
+ "Pending container allocations are tracked in a two-window tumbling bucket " +
+ "pattern. Each window has this duration. " +
+ "After 2x this interval, allocations that haven't been confirmed via " +
+ "container reports will automatically age out. Default is 10 minutes."
+ )
+ private Duration pendingContainerAllocationRollInterval = Duration.ofMinutes(10);
Review Comment:
5 minute
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org
For additional commands, e-mail: issues-help@ozone.apache.org
Re: [PR] HDDS-14921. Improve space accounting in SCM with In-Flight container allocation tracking. [ozone]
Posted by "szetszwo (via GitHub)" <gi...@apache.org>.
szetszwo commented on code in PR #10000:
URL: https://github.com/apache/ozone/pull/10000#discussion_r3328941800
##########
hadoop-hdds/server-scm/src/main/java/org/apache/hadoop/hdds/scm/pipeline/PipelineManagerImpl.java:
##########
@@ -634,22 +636,23 @@ private boolean isOpenWithUnregisteredNodes(Pipeline pipeline) {
}
@Override
- public boolean hasEnoughSpace(Pipeline pipeline) {
- for (DatanodeDetails node : pipeline.getNodes()) {
- if (!nodeManager.hasSpaceForNewContainerAllocation(node.getID())) {
+ public boolean checkSpaceAndRecordAllocation(Pipeline pipeline, ContainerID containerID) {
+ List<DatanodeDetails> successfulNodes = new ArrayList<>();
+ for (DatanodeDetails dn : pipeline.getNodes()) {
Review Comment:
We should getDatanodeInfo first:
```java
public boolean checkSpaceAndRecordAllocation(Pipeline pipeline, ContainerID containerID) {
final Set<DatanodeDetails> datanodeDetails = pipeline.getNodeSet();
final List<DatanodeInfo> datanodeInfos = new ArrayList<>(datanodeDetails.size());
for (DatanodeDetails dn : datanodeDetails) {
final DatanodeInfo info = nodeManager.getDatanodeInfo(dn);
if (info == null) {
LOG.warn("DatanodeInfo not found for {}", dn.getID());
return false;
}
datanodeInfos.add(info);
}
final List<DatanodeInfo> successfulNodes = new ArrayList<>(datanodeInfos.size());
for (DatanodeInfo dn : datanodeInfos) {
if (!nodeManager.checkSpaceAndRecordAllocation(dn, containerID)) {
for (DatanodeInfo rollbackNode : successfulNodes) {
nodeManager.removePendingAllocationForDatanode(rollbackNode, containerID);
}
return false;
}
successfulNodes.add(dn);
}
return true;
}
```
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org
For additional commands, e-mail: issues-help@ozone.apache.org
Re: [PR] HDDS-14921. Improve space accounting in SCM with In-Flight container allocation tracking. [ozone]
Posted by "ashishkumar50 (via GitHub)" <gi...@apache.org>.
ashishkumar50 commented on PR #10000:
URL: https://github.com/apache/ozone/pull/10000#issuecomment-4376658856
@szetszwo Thanks for the review, as i mentioned in https://github.com/apache/ozone/pull/10000#discussion_r3172549299, we need hasEnoughSpace and recordPendingAllocation methods so i haven't removed it.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org
For additional commands, e-mail: issues-help@ozone.apache.org
Re: [PR] HDDS-14921. Improve space accounting in SCM with In-Flight container allocation tracking. [ozone]
Posted by "rakeshadr (via GitHub)" <gi...@apache.org>.
rakeshadr commented on code in PR #10000:
URL: https://github.com/apache/ozone/pull/10000#discussion_r3044295093
##########
hadoop-hdds/server-scm/src/main/java/org/apache/hadoop/hdds/scm/node/PendingContainerTracker.java:
##########
@@ -0,0 +1,425 @@
+/*
+ * 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.node;
+
+import com.google.common.annotations.VisibleForTesting;
+import java.util.Collections;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Set;
+import java.util.UUID;
+import java.util.concurrent.ConcurrentHashMap;
+import org.apache.hadoop.hdds.protocol.DatanodeDetails;
+import org.apache.hadoop.hdds.protocol.proto.StorageContainerDatanodeProtocolProtos.StorageReportProto;
+import org.apache.hadoop.hdds.scm.container.ContainerID;
+import org.apache.hadoop.hdds.scm.pipeline.Pipeline;
+import org.apache.hadoop.ozone.container.common.volume.VolumeUsage;
+import org.apache.hadoop.util.Time;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * Tracks per-datanode pending container allocations at SCM using a Two Window Tumbling Bucket
+ * pattern (similar to HDFS HADOOP-3707).
+ *
+ * Two Window Tumbling Bucket for automatic aging and cleanup.
+ *
+ * How It Works:
+ * <li>Each DataNode has two sets: <b>currentWindow</b> and <b>previousWindow</b></li>
+ * <li>New allocations go into <b>currentWindow</b></li>
+ * <li>Every <b>ROLL_INTERVAL</b> (default 5 minutes):
+ * <ul>
+ * <li>previousWindow = currentWindow (shift)</li>
+ * <li>currentWindow = new empty set (reset)</li>
+ * <li>Old previousWindow is discarded (automatic aging)</li>
+ * </ul>
+ * </li>
+ * <li>When checking pending: return <b>union</b> of currentWindow + previousWindow</li>
+ *
+ *
+ * Example Timeline:
+ * <pre>
+ * Time | Action | CurrentWindow | PreviousWindow | Total Pending
+ * ------+---------------------------+---------------+----------------+--------------
+ * 00:00 | Allocate Container-1 | {C1} | {} | {C1}
+ * 00:02 | Allocate Container-2 | {C1, C2} | {} | {C1, C2}
+ * 00:05 | [ROLL] Window tumbles | {} | {C1, C2} | {C1, C2}
+ * 00:07 | Allocate Container-3 | {C3} | {C1, C2} | {C1, C2, C3}
+ * 00:08 | Report confirms C1 | {C3} | {C2} | {C2, C3}
+ * 00:10 | [ROLL] Window tumbles | {} | {C3} | {C3}
+ * | (C2 aged out if not reported)
+ * </pre>
+ *
+ * <p>Thread-safety: all mutations and reads for a given datanode run under
+ * {@code synchronized (bucket)} on that datanode's {@link TwoWindowBucket}, including
+ * map insert/remove, so concurrent record/remove/report paths cannot interleave or orphan
+ * a bucket after it was dropped from the map.</p>
+ */
+public class PendingContainerTracker {
+
+ private static final Logger LOG = LoggerFactory.getLogger(PendingContainerTracker.class);
+
+ /**
+ * Roll interval in milliseconds.
+ * Configurable via hdds.scm.container.pending.allocation.roll.interval.
+ * Default: 5 minutes.
+ * Containers automatically age out after 2 × rollIntervalMs.
+ */
+ private final long rollIntervalMs;
+
+ /**
+ * Map of DataNode UUID to TwoWindowBucket.
+ */
+ private final ConcurrentHashMap<UUID, TwoWindowBucket> datanodeBuckets;
+
+ /**
+ * Maximum container size in bytes.
+ */
+ private final long maxContainerSize;
+
+ /**
+ * Metrics for tracking pending containers (same instance as {@link SCMNodeManager}'s node metrics).
+ */
+ private final SCMNodeMetrics metrics;
+
+ /**
+ * Two-window bucket for a single DataNode.
+ * Contains current and previous window sets, plus last roll timestamp.
+ */
+ private static class TwoWindowBucket {
+ private Set<ContainerID> currentWindow = new HashSet<>();
+ private Set<ContainerID> previousWindow = new HashSet<>();
+ private long lastRollTime = Time.monotonicNow();
+ private final long rollIntervalMs;
+
+ TwoWindowBucket(long rollIntervalMs) {
+ this.rollIntervalMs = rollIntervalMs;
+ }
+
+ /**
+ * Roll the windows: previous = current, current = empty.
+ * Called when current time exceeds lastRollTime + rollIntervalMs.
+ */
+ synchronized void rollIfNeeded() {
+ long now = Time.monotonicNow();
+ if (now - lastRollTime >= rollIntervalMs) {
Review Comment:
Now, its making single-step roll, please do multi-step roll to stay clock-aligned regardless of when the roll fires.
should be `lastRollTime += rollIntervalMs`
```
while (now - lastRollTime >= rollIntervalMs) {
// Shift: current becomes previous
previousWindow = currentWindow;
// Reset: new empty current window
currentWindow = new HashSet<>();
lastRollTime += rollIntervalMs; // clock-aligned, not drifting
LOG.debug("Rolled window. Previous window size: {}, Current window reset to empty", previousWindow.size());
if (getAllPending().size() <= 0 ) { // exit if both windows got rollover
lastRollTime = now;
break;
}
}
```
##########
hadoop-hdds/server-scm/src/main/java/org/apache/hadoop/hdds/scm/node/PendingContainerTracker.java:
##########
@@ -0,0 +1,425 @@
+/*
+ * 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.node;
+
+import com.google.common.annotations.VisibleForTesting;
+import java.util.Collections;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Set;
+import java.util.UUID;
+import java.util.concurrent.ConcurrentHashMap;
+import org.apache.hadoop.hdds.protocol.DatanodeDetails;
+import org.apache.hadoop.hdds.protocol.proto.StorageContainerDatanodeProtocolProtos.StorageReportProto;
+import org.apache.hadoop.hdds.scm.container.ContainerID;
+import org.apache.hadoop.hdds.scm.pipeline.Pipeline;
+import org.apache.hadoop.ozone.container.common.volume.VolumeUsage;
+import org.apache.hadoop.util.Time;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * Tracks per-datanode pending container allocations at SCM using a Two Window Tumbling Bucket
+ * pattern (similar to HDFS HADOOP-3707).
+ *
+ * Two Window Tumbling Bucket for automatic aging and cleanup.
+ *
+ * How It Works:
+ * <li>Each DataNode has two sets: <b>currentWindow</b> and <b>previousWindow</b></li>
+ * <li>New allocations go into <b>currentWindow</b></li>
+ * <li>Every <b>ROLL_INTERVAL</b> (default 5 minutes):
+ * <ul>
+ * <li>previousWindow = currentWindow (shift)</li>
+ * <li>currentWindow = new empty set (reset)</li>
+ * <li>Old previousWindow is discarded (automatic aging)</li>
+ * </ul>
+ * </li>
+ * <li>When checking pending: return <b>union</b> of currentWindow + previousWindow</li>
+ *
+ *
+ * Example Timeline:
+ * <pre>
+ * Time | Action | CurrentWindow | PreviousWindow | Total Pending
+ * ------+---------------------------+---------------+----------------+--------------
+ * 00:00 | Allocate Container-1 | {C1} | {} | {C1}
+ * 00:02 | Allocate Container-2 | {C1, C2} | {} | {C1, C2}
+ * 00:05 | [ROLL] Window tumbles | {} | {C1, C2} | {C1, C2}
+ * 00:07 | Allocate Container-3 | {C3} | {C1, C2} | {C1, C2, C3}
+ * 00:08 | Report confirms C1 | {C3} | {C2} | {C2, C3}
+ * 00:10 | [ROLL] Window tumbles | {} | {C3} | {C3}
+ * | (C2 aged out if not reported)
+ * </pre>
+ *
+ * <p>Thread-safety: all mutations and reads for a given datanode run under
+ * {@code synchronized (bucket)} on that datanode's {@link TwoWindowBucket}, including
+ * map insert/remove, so concurrent record/remove/report paths cannot interleave or orphan
+ * a bucket after it was dropped from the map.</p>
+ */
+public class PendingContainerTracker {
+
+ private static final Logger LOG = LoggerFactory.getLogger(PendingContainerTracker.class);
+
+ /**
+ * Roll interval in milliseconds.
+ * Configurable via hdds.scm.container.pending.allocation.roll.interval.
+ * Default: 5 minutes.
+ * Containers automatically age out after 2 × rollIntervalMs.
+ */
+ private final long rollIntervalMs;
+
+ /**
+ * Map of DataNode UUID to TwoWindowBucket.
+ */
+ private final ConcurrentHashMap<UUID, TwoWindowBucket> datanodeBuckets;
+
+ /**
+ * Maximum container size in bytes.
+ */
+ private final long maxContainerSize;
+
+ /**
+ * Metrics for tracking pending containers (same instance as {@link SCMNodeManager}'s node metrics).
+ */
+ private final SCMNodeMetrics metrics;
+
+ /**
+ * Two-window bucket for a single DataNode.
+ * Contains current and previous window sets, plus last roll timestamp.
+ */
+ private static class TwoWindowBucket {
+ private Set<ContainerID> currentWindow = new HashSet<>();
+ private Set<ContainerID> previousWindow = new HashSet<>();
+ private long lastRollTime = Time.monotonicNow();
+ private final long rollIntervalMs;
+
+ TwoWindowBucket(long rollIntervalMs) {
+ this.rollIntervalMs = rollIntervalMs;
+ }
+
+ /**
+ * Roll the windows: previous = current, current = empty.
+ * Called when current time exceeds lastRollTime + rollIntervalMs.
+ */
+ synchronized void rollIfNeeded() {
+ long now = Time.monotonicNow();
+ if (now - lastRollTime >= rollIntervalMs) {
+ // Shift: current becomes previous
+ previousWindow = currentWindow;
+ // Reset: new empty current window
+ currentWindow = new HashSet<>();
+ lastRollTime = now;
+ LOG.debug("Rolled window. Previous window size: {}, Current window reset to empty", previousWindow.size());
+ }
+ }
+
+ /**
+ * Get union of both windows (all pending containers).
+ */
+ synchronized Set<ContainerID> getAllPending() {
+ Set<ContainerID> all = new HashSet<>();
+ all.addAll(currentWindow);
+ all.addAll(previousWindow);
+ return all;
+ }
+
+ /**
+ * Add container to current window.
+ */
+ synchronized boolean add(ContainerID containerID) {
+ return currentWindow.add(containerID);
+ }
+
+ /**
+ * Remove container from both windows.
+ */
+ synchronized boolean remove(ContainerID containerID) {
+ boolean removedFromCurrent = currentWindow.remove(containerID);
+ boolean removedFromPrevious = previousWindow.remove(containerID);
+ return removedFromCurrent || removedFromPrevious;
+ }
+
+ /**
+ * Check if either window is non-empty.
+ */
+ synchronized boolean isEmpty() {
+ return currentWindow.isEmpty() && previousWindow.isEmpty();
+ }
+
+ /**
+ * Count of pending containers in both windows.
+ */
+ synchronized int getCount() {
+ return currentWindow.size() + previousWindow.size();
+ }
+ }
+
+ public PendingContainerTracker(long maxContainerSize) {
+ this(maxContainerSize, 10 * 60 * 1000, null); // Default 10 minutes
+ }
+
+ public PendingContainerTracker(long maxContainerSize, long rollIntervalMs,
+ SCMNodeMetrics metrics) {
+ this.datanodeBuckets = new ConcurrentHashMap<>();
+ this.maxContainerSize = maxContainerSize;
+ this.rollIntervalMs = rollIntervalMs;
+ this.metrics = metrics;
+ LOG.info("PendingContainerTracker initialized with maxContainerSize={}B, rollInterval={}ms",
+ maxContainerSize, rollIntervalMs);
+ }
+
+ /**
+ * Whether the datanode can fit another container of {@code containerSize} after accounting for
+ * SCM pending allocations for {@code node} (this tracker) and usable space on {@code datanodeInfo}.
+ * Combines {@link #getPendingAllocationSize} with the per-disk slot check in one call.
+ *
+ * @param node identity used to look up pending allocations (same DN as {@code datanodeInfo})
+ * @param datanodeInfo storage reports for the datanode
+ * @param containerSize required container size in bytes (typically SCM max container size)
+ */
+ /**
+ * Advances the two-window tumbling bucket for this datanode when the roll interval has elapsed.
+ * Call on periodic paths (e.g. node report) so windows age even when there are no new
+ * allocations or container reports touching this tracker.
+ */
+ public void rollWindowsIfNeeded(DatanodeDetails node) {
+ if (node == null) {
+ return;
+ }
+ UUID uuid = node.getUuid();
+ TwoWindowBucket bucket = datanodeBuckets.get(uuid);
+ if (bucket == null) {
+ return;
+ }
+ synchronized (bucket) {
+ bucket.rollIfNeeded();
+ if (bucket.isEmpty()) {
+ datanodeBuckets.remove(uuid, bucket);
+ }
+ }
+ }
+
+ public boolean hasEffectiveAllocatableSpaceForNewContainer(
+ DatanodeDetails node, DatanodeInfo datanodeInfo, long containerSize) {
+ if (node == null || datanodeInfo == null || containerSize <= 0) {
+ return false;
+ }
+ long pendingBytes = getPendingAllocationSize(node);
+ return hasAllocatableSpaceAfterPending(datanodeInfo, containerSize, pendingBytes);
+ }
+
+ private static boolean hasAllocatableSpaceAfterPending(
+ DatanodeInfo datanodeInfo, long containerSize, long pendingAllocationBytes) {
+ List<StorageReportProto> storageReports = datanodeInfo.getStorageReports();
+ if (storageReports == null || storageReports.isEmpty()) {
+ return false;
+ }
+ long effectiveAllocatableSpace = 0L;
+ for (StorageReportProto report : storageReports) {
+ long usableSpace = VolumeUsage.getUsableSpace(report);
+ long containersOnThisDisk = usableSpace / containerSize;
+ effectiveAllocatableSpace += containersOnThisDisk * containerSize;
+ if (effectiveAllocatableSpace - pendingAllocationBytes >= containerSize) {
+ return true;
+ }
+ }
+ return false;
+ }
+
+ /**
+ * Drops all pending allocation state for a datanode (e.g. stale/dead cleanup).
+ */
+ public void clearPendingForDatanode(DatanodeDetails node) {
+ if (node == null) {
+ return;
+ }
+ UUID uuid = node.getUuid();
+ TwoWindowBucket bucket = datanodeBuckets.get(uuid);
+ if (bucket == null) {
+ return;
+ }
+ synchronized (bucket) {
+ datanodeBuckets.remove(uuid, bucket);
Review Comment:
ConcurrentHashMap.remove(key, value) is already atomic. The synchronized(bucket) doesn't protect any bucket-internal state here, right? You can remove this unncessary lock?
##########
hadoop-ozone/integration-test/src/test/java/org/apache/hadoop/hdds/scm/container/TestPendingContainerTrackerIntegration.java:
##########
@@ -0,0 +1,263 @@
+/*
+ * 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;
+
+import static java.nio.charset.StandardCharsets.UTF_8;
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Set;
+import org.apache.hadoop.hdds.HddsConfigKeys;
+import org.apache.hadoop.hdds.client.RatisReplicationConfig;
+import org.apache.hadoop.hdds.conf.OzoneConfiguration;
+import org.apache.hadoop.hdds.protocol.DatanodeDetails;
+import org.apache.hadoop.hdds.protocol.proto.HddsProtos.ReplicationFactor;
+import org.apache.hadoop.hdds.scm.container.common.helpers.ContainerWithPipeline;
+import org.apache.hadoop.hdds.scm.node.PendingContainerTracker;
+import org.apache.hadoop.hdds.scm.node.SCMNodeManager;
+import org.apache.hadoop.hdds.scm.node.SCMNodeMetrics;
+import org.apache.hadoop.hdds.scm.pipeline.Pipeline;
+import org.apache.hadoop.hdds.scm.server.StorageContainerManager;
+import org.apache.hadoop.ozone.MiniOzoneCluster;
+import org.apache.hadoop.ozone.TestDataUtil;
+import org.apache.hadoop.ozone.client.OzoneBucket;
+import org.apache.hadoop.ozone.client.OzoneClient;
+import org.apache.hadoop.ozone.client.io.OzoneOutputStream;
+import org.apache.ozone.test.GenericTestUtils;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.Timeout;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * Integration tests for PendingContainerTracker.
+ */
+@Timeout(300)
+public class TestPendingContainerTrackerIntegration {
+
+ private static final Logger LOG =
+ LoggerFactory.getLogger(TestPendingContainerTrackerIntegration.class);
+ private MiniOzoneCluster cluster;
+ private StorageContainerManager scm;
+ private OzoneClient client;
+ private ContainerManager containerManager;
+ private PendingContainerTracker pendingTracker;
+ private SCMNodeMetrics metrics;
+ private OzoneBucket bucket;
+
+ @BeforeEach
+ public void setup() throws Exception {
+ OzoneConfiguration conf = new OzoneConfiguration();
+
+ conf.set(HddsConfigKeys.HDDS_CONTAINER_REPORT_INTERVAL, "60s");
+
+ // Reduce heartbeat interval for faster container reports
+ conf.set(HddsConfigKeys.HDDS_HEARTBEAT_INTERVAL, "10s");
+
+ conf.set("ozone.scm.container.size", "100MB");
+ conf.set("ozone.scm.pipeline.owner.container.count", "1");
+ conf.set("ozone.scm.pipeline.per.metadata.disk", "1");
+ conf.set("ozone.scm.datanode.pipeline.limit", "1");
+
+ cluster = MiniOzoneCluster.newBuilder(conf)
+ .setNumDatanodes(3)
+ .build();
+ cluster.waitForClusterToBeReady();
+ cluster.waitTobeOutOfSafeMode();
+
+ scm = cluster.getStorageContainerManager();
+ containerManager = scm.getContainerManager();
+ client = cluster.newClient();
+
+ // Create bucket for testing
+ bucket = TestDataUtil.createVolumeAndBucket(client);
+
+ SCMNodeManager nodeManager = (SCMNodeManager) scm.getScmNodeManager();
+ assertNotNull(nodeManager);
+ pendingTracker = nodeManager.getPendingContainerTracker();
+ assertNotNull(pendingTracker, "PendingContainerTracker should be initialized");
+ metrics = pendingTracker.getMetrics();
+
+ LOG.info("Test setup complete - ICR interval: 5s, Heartbeat interval: 1s");
+ }
+
+ @AfterEach
+ public void cleanup() throws Exception {
+ if (client != null) {
+ client.close();
+ }
+ if (cluster != null) {
+ cluster.shutdown();
+ }
+ }
+
+ /**
+ * Test: Write key → Container allocation → Pending tracked → ICR → Pending removed.
+ */
+ @Test
+ public void testKeyWriteRecordsPendingAndICRRemovesIt() throws Exception {
+ long initialAdded = metrics.getNumPendingContainersAdded();
+ long initialRemoved = metrics.getNumPendingContainersRemoved();
+
+ // Allocate a container directly
+ ContainerInfo container = containerManager.allocateContainer(
+ RatisReplicationConfig.getInstance(ReplicationFactor.THREE),
+ "omServiceIdDefault");
+
+ // Find the container that was allocated
+ ContainerInfo containerInfo = scm.getContainerManager().getContainers().get(0);
+ ContainerWithPipeline containerWithPipeline =
+ scm.getClientProtocolServer().getContainerWithPipeline(
+ containerInfo.getContainerID());
+
+ Pipeline pipeline = containerWithPipeline.getPipeline();
+
+ // Verify pending containers are tracked for all nodes in pipeline
+ List<DatanodeDetails> nodesWithPending = new ArrayList<>();
+ for (DatanodeDetails dn : pipeline.getNodes()) {
+ long pendingSize = pendingTracker.getPendingAllocationSize(dn);
+ if (pendingSize > 0) {
+ nodesWithPending.add(dn);
+ LOG.info("DataNode {} has {} bytes pending", dn.getUuidString(), pendingSize);
+
+ Set<ContainerID> pendingContainers = pendingTracker.getPendingContainers(dn);
+ assertThat(pendingContainers.contains(container.containerID()));
Review Comment:
Should this be `assertThat(pendingContainers).contains(container.containerID());` ?
Please visit all the occurrences of assertThat() in this file and fix it.
##########
hadoop-hdds/server-scm/src/main/java/org/apache/hadoop/hdds/scm/node/PendingContainerTracker.java:
##########
@@ -0,0 +1,425 @@
+/*
+ * 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.node;
+
+import com.google.common.annotations.VisibleForTesting;
+import java.util.Collections;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Set;
+import java.util.UUID;
+import java.util.concurrent.ConcurrentHashMap;
+import org.apache.hadoop.hdds.protocol.DatanodeDetails;
+import org.apache.hadoop.hdds.protocol.proto.StorageContainerDatanodeProtocolProtos.StorageReportProto;
+import org.apache.hadoop.hdds.scm.container.ContainerID;
+import org.apache.hadoop.hdds.scm.pipeline.Pipeline;
+import org.apache.hadoop.ozone.container.common.volume.VolumeUsage;
+import org.apache.hadoop.util.Time;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * Tracks per-datanode pending container allocations at SCM using a Two Window Tumbling Bucket
+ * pattern (similar to HDFS HADOOP-3707).
+ *
+ * Two Window Tumbling Bucket for automatic aging and cleanup.
+ *
+ * How It Works:
+ * <li>Each DataNode has two sets: <b>currentWindow</b> and <b>previousWindow</b></li>
+ * <li>New allocations go into <b>currentWindow</b></li>
+ * <li>Every <b>ROLL_INTERVAL</b> (default 5 minutes):
+ * <ul>
+ * <li>previousWindow = currentWindow (shift)</li>
+ * <li>currentWindow = new empty set (reset)</li>
+ * <li>Old previousWindow is discarded (automatic aging)</li>
+ * </ul>
+ * </li>
+ * <li>When checking pending: return <b>union</b> of currentWindow + previousWindow</li>
+ *
+ *
+ * Example Timeline:
+ * <pre>
+ * Time | Action | CurrentWindow | PreviousWindow | Total Pending
+ * ------+---------------------------+---------------+----------------+--------------
+ * 00:00 | Allocate Container-1 | {C1} | {} | {C1}
+ * 00:02 | Allocate Container-2 | {C1, C2} | {} | {C1, C2}
+ * 00:05 | [ROLL] Window tumbles | {} | {C1, C2} | {C1, C2}
+ * 00:07 | Allocate Container-3 | {C3} | {C1, C2} | {C1, C2, C3}
+ * 00:08 | Report confirms C1 | {C3} | {C2} | {C2, C3}
+ * 00:10 | [ROLL] Window tumbles | {} | {C3} | {C3}
+ * | (C2 aged out if not reported)
+ * </pre>
+ *
+ * <p>Thread-safety: all mutations and reads for a given datanode run under
+ * {@code synchronized (bucket)} on that datanode's {@link TwoWindowBucket}, including
+ * map insert/remove, so concurrent record/remove/report paths cannot interleave or orphan
+ * a bucket after it was dropped from the map.</p>
+ */
+public class PendingContainerTracker {
+
+ private static final Logger LOG = LoggerFactory.getLogger(PendingContainerTracker.class);
+
+ /**
+ * Roll interval in milliseconds.
+ * Configurable via hdds.scm.container.pending.allocation.roll.interval.
+ * Default: 5 minutes.
+ * Containers automatically age out after 2 × rollIntervalMs.
+ */
+ private final long rollIntervalMs;
+
+ /**
+ * Map of DataNode UUID to TwoWindowBucket.
+ */
+ private final ConcurrentHashMap<UUID, TwoWindowBucket> datanodeBuckets;
+
+ /**
+ * Maximum container size in bytes.
+ */
+ private final long maxContainerSize;
+
+ /**
+ * Metrics for tracking pending containers (same instance as {@link SCMNodeManager}'s node metrics).
+ */
+ private final SCMNodeMetrics metrics;
+
+ /**
+ * Two-window bucket for a single DataNode.
+ * Contains current and previous window sets, plus last roll timestamp.
+ */
+ private static class TwoWindowBucket {
+ private Set<ContainerID> currentWindow = new HashSet<>();
+ private Set<ContainerID> previousWindow = new HashSet<>();
+ private long lastRollTime = Time.monotonicNow();
+ private final long rollIntervalMs;
+
+ TwoWindowBucket(long rollIntervalMs) {
+ this.rollIntervalMs = rollIntervalMs;
+ }
+
+ /**
+ * Roll the windows: previous = current, current = empty.
+ * Called when current time exceeds lastRollTime + rollIntervalMs.
+ */
+ synchronized void rollIfNeeded() {
+ long now = Time.monotonicNow();
+ if (now - lastRollTime >= rollIntervalMs) {
+ // Shift: current becomes previous
+ previousWindow = currentWindow;
+ // Reset: new empty current window
+ currentWindow = new HashSet<>();
+ lastRollTime = now;
+ LOG.debug("Rolled window. Previous window size: {}, Current window reset to empty", previousWindow.size());
+ }
+ }
+
+ /**
+ * Get union of both windows (all pending containers).
+ */
+ synchronized Set<ContainerID> getAllPending() {
+ Set<ContainerID> all = new HashSet<>();
+ all.addAll(currentWindow);
+ all.addAll(previousWindow);
+ return all;
+ }
+
+ /**
+ * Add container to current window.
+ */
+ synchronized boolean add(ContainerID containerID) {
+ return currentWindow.add(containerID);
+ }
+
+ /**
+ * Remove container from both windows.
+ */
+ synchronized boolean remove(ContainerID containerID) {
+ boolean removedFromCurrent = currentWindow.remove(containerID);
+ boolean removedFromPrevious = previousWindow.remove(containerID);
+ return removedFromCurrent || removedFromPrevious;
+ }
+
+ /**
+ * Check if either window is non-empty.
+ */
+ synchronized boolean isEmpty() {
+ return currentWindow.isEmpty() && previousWindow.isEmpty();
+ }
+
+ /**
+ * Count of pending containers in both windows.
+ */
+ synchronized int getCount() {
+ return currentWindow.size() + previousWindow.size();
+ }
+ }
+
+ public PendingContainerTracker(long maxContainerSize) {
+ this(maxContainerSize, 10 * 60 * 1000, null); // Default 10 minutes
+ }
+
+ public PendingContainerTracker(long maxContainerSize, long rollIntervalMs,
+ SCMNodeMetrics metrics) {
+ this.datanodeBuckets = new ConcurrentHashMap<>();
+ this.maxContainerSize = maxContainerSize;
+ this.rollIntervalMs = rollIntervalMs;
+ this.metrics = metrics;
+ LOG.info("PendingContainerTracker initialized with maxContainerSize={}B, rollInterval={}ms",
+ maxContainerSize, rollIntervalMs);
+ }
+
+ /**
+ * Whether the datanode can fit another container of {@code containerSize} after accounting for
+ * SCM pending allocations for {@code node} (this tracker) and usable space on {@code datanodeInfo}.
+ * Combines {@link #getPendingAllocationSize} with the per-disk slot check in one call.
+ *
+ * @param node identity used to look up pending allocations (same DN as {@code datanodeInfo})
+ * @param datanodeInfo storage reports for the datanode
+ * @param containerSize required container size in bytes (typically SCM max container size)
+ */
+ /**
+ * Advances the two-window tumbling bucket for this datanode when the roll interval has elapsed.
+ * Call on periodic paths (e.g. node report) so windows age even when there are no new
+ * allocations or container reports touching this tracker.
+ */
+ public void rollWindowsIfNeeded(DatanodeDetails node) {
+ if (node == null) {
+ return;
+ }
+ UUID uuid = node.getUuid();
+ TwoWindowBucket bucket = datanodeBuckets.get(uuid);
+ if (bucket == null) {
+ return;
+ }
+ synchronized (bucket) {
+ bucket.rollIfNeeded();
+ if (bucket.isEmpty()) {
+ datanodeBuckets.remove(uuid, bucket);
+ }
+ }
+ }
+
+ public boolean hasEffectiveAllocatableSpaceForNewContainer(
+ DatanodeDetails node, DatanodeInfo datanodeInfo, long containerSize) {
+ if (node == null || datanodeInfo == null || containerSize <= 0) {
+ return false;
+ }
+ long pendingBytes = getPendingAllocationSize(node);
+ return hasAllocatableSpaceAfterPending(datanodeInfo, containerSize, pendingBytes);
+ }
+
+ private static boolean hasAllocatableSpaceAfterPending(
+ DatanodeInfo datanodeInfo, long containerSize, long pendingAllocationBytes) {
+ List<StorageReportProto> storageReports = datanodeInfo.getStorageReports();
+ if (storageReports == null || storageReports.isEmpty()) {
+ return false;
+ }
+ long effectiveAllocatableSpace = 0L;
+ for (StorageReportProto report : storageReports) {
+ long usableSpace = VolumeUsage.getUsableSpace(report);
+ long containersOnThisDisk = usableSpace / containerSize;
+ effectiveAllocatableSpace += containersOnThisDisk * containerSize;
+ if (effectiveAllocatableSpace - pendingAllocationBytes >= containerSize) {
+ return true;
+ }
+ }
+ return false;
+ }
+
+ /**
+ * Drops all pending allocation state for a datanode (e.g. stale/dead cleanup).
+ */
+ public void clearPendingForDatanode(DatanodeDetails node) {
+ if (node == null) {
+ return;
+ }
+ UUID uuid = node.getUuid();
+ TwoWindowBucket bucket = datanodeBuckets.get(uuid);
+ if (bucket == null) {
+ return;
+ }
+ synchronized (bucket) {
+ datanodeBuckets.remove(uuid, bucket);
+ }
+ LOG.debug("Cleared pending container allocations for datanode {}",
+ node.getUuidString());
+ }
+
+ /**
+ * Record a pending container allocation for all DataNodes in the pipeline.
+ * Container is added to the current window.
+ *
+ * @param pipeline The pipeline where container is allocated
+ * @param containerID The container being allocated
+ */
+ public void recordPendingAllocation(Pipeline pipeline, ContainerID containerID) {
+ if (pipeline == null || containerID == null) {
+ LOG.warn("Ignoring null pipeline or containerID");
+ return;
+ }
+
+ for (DatanodeDetails node : pipeline.getNodes()) {
+ recordPendingAllocationForDatanode(node, containerID);
+ }
+ }
+
+ /**
+ * Record a pending container allocation for a single DataNode.
+ * Container is added to the current window.
+ *
+ * @param node The DataNode where container is being allocated/replicated
+ * @param containerID The container being allocated/replicated
+ */
+ public void recordPendingAllocationForDatanode(DatanodeDetails node, ContainerID containerID) {
+ if (node == null || containerID == null) {
+ LOG.warn("Ignoring null node or containerID");
+ return;
+ }
+
+ UUID uuid = node.getUuid();
+ TwoWindowBucket bucket = datanodeBuckets.computeIfAbsent(
+ uuid,
+ k -> new TwoWindowBucket(rollIntervalMs)
+ );
+
+ synchronized (bucket) {
+ bucket.rollIfNeeded();
+ boolean added = bucket.add(containerID);
+ if (!bucket.isEmpty()) {
+ datanodeBuckets.put(uuid, bucket);
+ }
+ LOG.debug("Recorded pending container {} on DataNode {}. Added={}, Total pending={}",
+ containerID, node.getUuidString(), added, bucket.getCount());
+
+ if (added && metrics != null) {
+ metrics.incNumPendingContainersAdded();
+ }
+ }
+ }
+
+ /**
+ * Remove a pending container allocation from a specific DataNode.
+ * Removes from both current and previous windows.
+ * Called when container is confirmed.
+ *
+ * @param node The DataNode
+ * @param containerID The container to remove from pending
+ */
+ public void removePendingAllocation(DatanodeDetails node, ContainerID containerID) {
+ if (node == null || containerID == null) {
+ return;
+ }
+
+ UUID uuid = node.getUuid();
+ TwoWindowBucket bucket = datanodeBuckets.get(uuid);
+ if (bucket == null) {
+ return;
+ }
+
+ synchronized (bucket) {
+ bucket.rollIfNeeded();
+
+ boolean removed = bucket.remove(containerID);
+ LOG.debug("Removed pending container {} from DataNode {}. Removed={}, Remaining={}",
+ containerID, node.getUuidString(), removed, bucket.getCount());
+
+ if (removed && metrics != null) {
+ metrics.incNumPendingContainersRemoved();
+ }
+
+ if (bucket.isEmpty()) {
+ LOG.debug("Cleanup pending bucket containerID {}", containerID);
+ datanodeBuckets.remove(uuid, bucket);
+ }
+ }
+ }
+
+ /**
+ * Bytes of SCM-side pending container allocations for this datanode (count × configured max
+ * container size). For whether a new container can be placed, prefer
+ * {@link #hasEffectiveAllocatableSpaceForNewContainer}.
+ *
+ * @param node The DataNode
+ * @return Total bytes of pending container allocations
+ */
+ public long getPendingAllocationSize(DatanodeDetails node) {
+ if (node == null) {
+ return 0;
+ }
+
+ TwoWindowBucket bucket = datanodeBuckets.get(node.getUuid());
+ if (bucket == null) {
+ return 0;
+ }
+
+ synchronized (bucket) {
+ bucket.rollIfNeeded();
Review Comment:
Can you update the javadoc saying that,
```
/**
* Bytes of SCM-side pending container allocations for this datanode (count × configured max
* container size). For whether a new container can be placed, prefer
* {@link #hasEffectiveAllocatableSpaceForNewContainer}.
*
* <p>Note: this call may advance the internal tumbling window if the roll interval has elapsed,
* ensuring the returned value reflects the most up-to-date pending state.</p>
*
* @param node The DataNode
* @return Total bytes of pending container allocations
*/
```
##########
hadoop-hdds/server-scm/src/main/java/org/apache/hadoop/hdds/scm/node/PendingContainerTracker.java:
##########
@@ -0,0 +1,425 @@
+/*
+ * 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.node;
+
+import com.google.common.annotations.VisibleForTesting;
+import java.util.Collections;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Set;
+import java.util.UUID;
+import java.util.concurrent.ConcurrentHashMap;
+import org.apache.hadoop.hdds.protocol.DatanodeDetails;
+import org.apache.hadoop.hdds.protocol.proto.StorageContainerDatanodeProtocolProtos.StorageReportProto;
+import org.apache.hadoop.hdds.scm.container.ContainerID;
+import org.apache.hadoop.hdds.scm.pipeline.Pipeline;
+import org.apache.hadoop.ozone.container.common.volume.VolumeUsage;
+import org.apache.hadoop.util.Time;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * Tracks per-datanode pending container allocations at SCM using a Two Window Tumbling Bucket
+ * pattern (similar to HDFS HADOOP-3707).
+ *
+ * Two Window Tumbling Bucket for automatic aging and cleanup.
+ *
+ * How It Works:
+ * <li>Each DataNode has two sets: <b>currentWindow</b> and <b>previousWindow</b></li>
+ * <li>New allocations go into <b>currentWindow</b></li>
+ * <li>Every <b>ROLL_INTERVAL</b> (default 5 minutes):
+ * <ul>
+ * <li>previousWindow = currentWindow (shift)</li>
+ * <li>currentWindow = new empty set (reset)</li>
+ * <li>Old previousWindow is discarded (automatic aging)</li>
+ * </ul>
+ * </li>
+ * <li>When checking pending: return <b>union</b> of currentWindow + previousWindow</li>
+ *
+ *
+ * Example Timeline:
+ * <pre>
+ * Time | Action | CurrentWindow | PreviousWindow | Total Pending
+ * ------+---------------------------+---------------+----------------+--------------
+ * 00:00 | Allocate Container-1 | {C1} | {} | {C1}
+ * 00:02 | Allocate Container-2 | {C1, C2} | {} | {C1, C2}
+ * 00:05 | [ROLL] Window tumbles | {} | {C1, C2} | {C1, C2}
+ * 00:07 | Allocate Container-3 | {C3} | {C1, C2} | {C1, C2, C3}
+ * 00:08 | Report confirms C1 | {C3} | {C2} | {C2, C3}
+ * 00:10 | [ROLL] Window tumbles | {} | {C3} | {C3}
+ * | (C2 aged out if not reported)
+ * </pre>
+ *
+ * <p>Thread-safety: all mutations and reads for a given datanode run under
+ * {@code synchronized (bucket)} on that datanode's {@link TwoWindowBucket}, including
+ * map insert/remove, so concurrent record/remove/report paths cannot interleave or orphan
+ * a bucket after it was dropped from the map.</p>
+ */
+public class PendingContainerTracker {
+
+ private static final Logger LOG = LoggerFactory.getLogger(PendingContainerTracker.class);
+
+ /**
+ * Roll interval in milliseconds.
+ * Configurable via hdds.scm.container.pending.allocation.roll.interval.
+ * Default: 5 minutes.
+ * Containers automatically age out after 2 × rollIntervalMs.
+ */
+ private final long rollIntervalMs;
+
+ /**
+ * Map of DataNode UUID to TwoWindowBucket.
+ */
+ private final ConcurrentHashMap<UUID, TwoWindowBucket> datanodeBuckets;
+
+ /**
+ * Maximum container size in bytes.
+ */
+ private final long maxContainerSize;
+
+ /**
+ * Metrics for tracking pending containers (same instance as {@link SCMNodeManager}'s node metrics).
+ */
+ private final SCMNodeMetrics metrics;
+
+ /**
+ * Two-window bucket for a single DataNode.
+ * Contains current and previous window sets, plus last roll timestamp.
+ */
+ private static class TwoWindowBucket {
+ private Set<ContainerID> currentWindow = new HashSet<>();
+ private Set<ContainerID> previousWindow = new HashSet<>();
+ private long lastRollTime = Time.monotonicNow();
+ private final long rollIntervalMs;
+
+ TwoWindowBucket(long rollIntervalMs) {
+ this.rollIntervalMs = rollIntervalMs;
+ }
+
+ /**
+ * Roll the windows: previous = current, current = empty.
+ * Called when current time exceeds lastRollTime + rollIntervalMs.
+ */
+ synchronized void rollIfNeeded() {
+ long now = Time.monotonicNow();
+ if (now - lastRollTime >= rollIntervalMs) {
+ // Shift: current becomes previous
+ previousWindow = currentWindow;
+ // Reset: new empty current window
+ currentWindow = new HashSet<>();
+ lastRollTime = now;
+ LOG.debug("Rolled window. Previous window size: {}, Current window reset to empty", previousWindow.size());
+ }
+ }
+
+ /**
+ * Get union of both windows (all pending containers).
+ */
+ synchronized Set<ContainerID> getAllPending() {
+ Set<ContainerID> all = new HashSet<>();
+ all.addAll(currentWindow);
+ all.addAll(previousWindow);
+ return all;
+ }
+
+ /**
+ * Add container to current window.
+ */
+ synchronized boolean add(ContainerID containerID) {
+ return currentWindow.add(containerID);
+ }
+
+ /**
+ * Remove container from both windows.
+ */
+ synchronized boolean remove(ContainerID containerID) {
+ boolean removedFromCurrent = currentWindow.remove(containerID);
+ boolean removedFromPrevious = previousWindow.remove(containerID);
+ return removedFromCurrent || removedFromPrevious;
+ }
+
+ /**
+ * Check if either window is non-empty.
+ */
+ synchronized boolean isEmpty() {
+ return currentWindow.isEmpty() && previousWindow.isEmpty();
+ }
+
+ /**
+ * Count of pending containers in both windows.
+ */
+ synchronized int getCount() {
+ return currentWindow.size() + previousWindow.size();
+ }
+ }
+
+ public PendingContainerTracker(long maxContainerSize) {
+ this(maxContainerSize, 10 * 60 * 1000, null); // Default 10 minutes
+ }
+
+ public PendingContainerTracker(long maxContainerSize, long rollIntervalMs,
+ SCMNodeMetrics metrics) {
+ this.datanodeBuckets = new ConcurrentHashMap<>();
+ this.maxContainerSize = maxContainerSize;
+ this.rollIntervalMs = rollIntervalMs;
+ this.metrics = metrics;
+ LOG.info("PendingContainerTracker initialized with maxContainerSize={}B, rollInterval={}ms",
+ maxContainerSize, rollIntervalMs);
+ }
+
+ /**
+ * Whether the datanode can fit another container of {@code containerSize} after accounting for
+ * SCM pending allocations for {@code node} (this tracker) and usable space on {@code datanodeInfo}.
+ * Combines {@link #getPendingAllocationSize} with the per-disk slot check in one call.
+ *
+ * @param node identity used to look up pending allocations (same DN as {@code datanodeInfo})
+ * @param datanodeInfo storage reports for the datanode
+ * @param containerSize required container size in bytes (typically SCM max container size)
+ */
+ /**
+ * Advances the two-window tumbling bucket for this datanode when the roll interval has elapsed.
+ * Call on periodic paths (e.g. node report) so windows age even when there are no new
+ * allocations or container reports touching this tracker.
+ */
+ public void rollWindowsIfNeeded(DatanodeDetails node) {
+ if (node == null) {
+ return;
+ }
+ UUID uuid = node.getUuid();
+ TwoWindowBucket bucket = datanodeBuckets.get(uuid);
+ if (bucket == null) {
+ return;
+ }
+ synchronized (bucket) {
+ bucket.rollIfNeeded();
+ if (bucket.isEmpty()) {
+ datanodeBuckets.remove(uuid, bucket);
+ }
+ }
+ }
+
+ public boolean hasEffectiveAllocatableSpaceForNewContainer(
+ DatanodeDetails node, DatanodeInfo datanodeInfo, long containerSize) {
+ if (node == null || datanodeInfo == null || containerSize <= 0) {
+ return false;
+ }
+ long pendingBytes = getPendingAllocationSize(node);
+ return hasAllocatableSpaceAfterPending(datanodeInfo, containerSize, pendingBytes);
+ }
+
+ private static boolean hasAllocatableSpaceAfterPending(
+ DatanodeInfo datanodeInfo, long containerSize, long pendingAllocationBytes) {
+ List<StorageReportProto> storageReports = datanodeInfo.getStorageReports();
+ if (storageReports == null || storageReports.isEmpty()) {
+ return false;
+ }
+ long effectiveAllocatableSpace = 0L;
+ for (StorageReportProto report : storageReports) {
+ long usableSpace = VolumeUsage.getUsableSpace(report);
+ long containersOnThisDisk = usableSpace / containerSize;
+ effectiveAllocatableSpace += containersOnThisDisk * containerSize;
+ if (effectiveAllocatableSpace - pendingAllocationBytes >= containerSize) {
+ return true;
+ }
+ }
+ return false;
+ }
+
+ /**
+ * Drops all pending allocation state for a datanode (e.g. stale/dead cleanup).
+ */
+ public void clearPendingForDatanode(DatanodeDetails node) {
+ if (node == null) {
+ return;
+ }
+ UUID uuid = node.getUuid();
+ TwoWindowBucket bucket = datanodeBuckets.get(uuid);
+ if (bucket == null) {
+ return;
+ }
+ synchronized (bucket) {
+ datanodeBuckets.remove(uuid, bucket);
+ }
+ LOG.debug("Cleared pending container allocations for datanode {}",
+ node.getUuidString());
+ }
+
+ /**
+ * Record a pending container allocation for all DataNodes in the pipeline.
+ * Container is added to the current window.
+ *
+ * @param pipeline The pipeline where container is allocated
+ * @param containerID The container being allocated
+ */
+ public void recordPendingAllocation(Pipeline pipeline, ContainerID containerID) {
+ if (pipeline == null || containerID == null) {
+ LOG.warn("Ignoring null pipeline or containerID");
+ return;
+ }
+
+ for (DatanodeDetails node : pipeline.getNodes()) {
+ recordPendingAllocationForDatanode(node, containerID);
+ }
+ }
+
+ /**
+ * Record a pending container allocation for a single DataNode.
+ * Container is added to the current window.
+ *
+ * @param node The DataNode where container is being allocated/replicated
+ * @param containerID The container being allocated/replicated
+ */
+ public void recordPendingAllocationForDatanode(DatanodeDetails node, ContainerID containerID) {
+ if (node == null || containerID == null) {
+ LOG.warn("Ignoring null node or containerID");
+ return;
+ }
+
+ UUID uuid = node.getUuid();
+ TwoWindowBucket bucket = datanodeBuckets.computeIfAbsent(
Review Comment:
Since `datanodeBuckets` is concurrent hashmap, can we simplify the logic instead of synchronized bucket and avoids unnecessary null check?
```
boolean added = addContainerToBucket(node.getUuid(), containerID);
if (added && metrics != null) {
metrics.incNumPendingContainersAdded();
}
```
```
private boolean addContainerToBucket(UUID uuid, ContainerID containerID) {
AtomicBoolean added = new AtomicBoolean(false);
datanodeBuckets.compute(uuid, (k, existing) -> {
TwoWindowBucket bucket = (existing != null) ? existing : new TwoWindowBucket(rollIntervalMs);
bucket.rollIfNeeded();
added.set(bucket.add(containerID));
LOG.debug("Recorded pending container {} on DataNode {}. Added={}, Total pending={}",
containerID, uuid, added.get(), bucket.getCount());
return bucket;
});
return added.get();
}
```
##########
hadoop-hdds/server-scm/src/main/java/org/apache/hadoop/hdds/scm/node/PendingContainerTracker.java:
##########
@@ -0,0 +1,425 @@
+/*
+ * 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.node;
+
+import com.google.common.annotations.VisibleForTesting;
+import java.util.Collections;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Set;
+import java.util.UUID;
+import java.util.concurrent.ConcurrentHashMap;
+import org.apache.hadoop.hdds.protocol.DatanodeDetails;
+import org.apache.hadoop.hdds.protocol.proto.StorageContainerDatanodeProtocolProtos.StorageReportProto;
+import org.apache.hadoop.hdds.scm.container.ContainerID;
+import org.apache.hadoop.hdds.scm.pipeline.Pipeline;
+import org.apache.hadoop.ozone.container.common.volume.VolumeUsage;
+import org.apache.hadoop.util.Time;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * Tracks per-datanode pending container allocations at SCM using a Two Window Tumbling Bucket
+ * pattern (similar to HDFS HADOOP-3707).
+ *
+ * Two Window Tumbling Bucket for automatic aging and cleanup.
+ *
+ * How It Works:
+ * <li>Each DataNode has two sets: <b>currentWindow</b> and <b>previousWindow</b></li>
+ * <li>New allocations go into <b>currentWindow</b></li>
+ * <li>Every <b>ROLL_INTERVAL</b> (default 5 minutes):
+ * <ul>
+ * <li>previousWindow = currentWindow (shift)</li>
+ * <li>currentWindow = new empty set (reset)</li>
+ * <li>Old previousWindow is discarded (automatic aging)</li>
+ * </ul>
+ * </li>
+ * <li>When checking pending: return <b>union</b> of currentWindow + previousWindow</li>
+ *
+ *
+ * Example Timeline:
+ * <pre>
+ * Time | Action | CurrentWindow | PreviousWindow | Total Pending
+ * ------+---------------------------+---------------+----------------+--------------
+ * 00:00 | Allocate Container-1 | {C1} | {} | {C1}
+ * 00:02 | Allocate Container-2 | {C1, C2} | {} | {C1, C2}
+ * 00:05 | [ROLL] Window tumbles | {} | {C1, C2} | {C1, C2}
+ * 00:07 | Allocate Container-3 | {C3} | {C1, C2} | {C1, C2, C3}
+ * 00:08 | Report confirms C1 | {C3} | {C2} | {C2, C3}
+ * 00:10 | [ROLL] Window tumbles | {} | {C3} | {C3}
+ * | (C2 aged out if not reported)
+ * </pre>
+ *
+ * <p>Thread-safety: all mutations and reads for a given datanode run under
+ * {@code synchronized (bucket)} on that datanode's {@link TwoWindowBucket}, including
+ * map insert/remove, so concurrent record/remove/report paths cannot interleave or orphan
+ * a bucket after it was dropped from the map.</p>
+ */
+public class PendingContainerTracker {
+
+ private static final Logger LOG = LoggerFactory.getLogger(PendingContainerTracker.class);
+
+ /**
+ * Roll interval in milliseconds.
+ * Configurable via hdds.scm.container.pending.allocation.roll.interval.
+ * Default: 5 minutes.
+ * Containers automatically age out after 2 × rollIntervalMs.
+ */
+ private final long rollIntervalMs;
+
+ /**
+ * Map of DataNode UUID to TwoWindowBucket.
+ */
+ private final ConcurrentHashMap<UUID, TwoWindowBucket> datanodeBuckets;
+
+ /**
+ * Maximum container size in bytes.
+ */
+ private final long maxContainerSize;
+
+ /**
+ * Metrics for tracking pending containers (same instance as {@link SCMNodeManager}'s node metrics).
+ */
+ private final SCMNodeMetrics metrics;
+
+ /**
+ * Two-window bucket for a single DataNode.
+ * Contains current and previous window sets, plus last roll timestamp.
+ */
+ private static class TwoWindowBucket {
+ private Set<ContainerID> currentWindow = new HashSet<>();
+ private Set<ContainerID> previousWindow = new HashSet<>();
+ private long lastRollTime = Time.monotonicNow();
+ private final long rollIntervalMs;
+
+ TwoWindowBucket(long rollIntervalMs) {
+ this.rollIntervalMs = rollIntervalMs;
+ }
+
+ /**
+ * Roll the windows: previous = current, current = empty.
+ * Called when current time exceeds lastRollTime + rollIntervalMs.
+ */
+ synchronized void rollIfNeeded() {
+ long now = Time.monotonicNow();
+ if (now - lastRollTime >= rollIntervalMs) {
+ // Shift: current becomes previous
+ previousWindow = currentWindow;
+ // Reset: new empty current window
+ currentWindow = new HashSet<>();
+ lastRollTime = now;
+ LOG.debug("Rolled window. Previous window size: {}, Current window reset to empty", previousWindow.size());
+ }
+ }
+
+ /**
+ * Get union of both windows (all pending containers).
+ */
+ synchronized Set<ContainerID> getAllPending() {
+ Set<ContainerID> all = new HashSet<>();
+ all.addAll(currentWindow);
+ all.addAll(previousWindow);
+ return all;
+ }
+
+ /**
+ * Add container to current window.
+ */
+ synchronized boolean add(ContainerID containerID) {
+ return currentWindow.add(containerID);
+ }
+
+ /**
+ * Remove container from both windows.
+ */
+ synchronized boolean remove(ContainerID containerID) {
+ boolean removedFromCurrent = currentWindow.remove(containerID);
+ boolean removedFromPrevious = previousWindow.remove(containerID);
+ return removedFromCurrent || removedFromPrevious;
+ }
+
+ /**
+ * Check if either window is non-empty.
+ */
+ synchronized boolean isEmpty() {
+ return currentWindow.isEmpty() && previousWindow.isEmpty();
+ }
+
+ /**
+ * Count of pending containers in both windows.
+ */
+ synchronized int getCount() {
+ return currentWindow.size() + previousWindow.size();
+ }
+ }
+
+ public PendingContainerTracker(long maxContainerSize) {
+ this(maxContainerSize, 10 * 60 * 1000, null); // Default 10 minutes
+ }
+
+ public PendingContainerTracker(long maxContainerSize, long rollIntervalMs,
+ SCMNodeMetrics metrics) {
+ this.datanodeBuckets = new ConcurrentHashMap<>();
+ this.maxContainerSize = maxContainerSize;
+ this.rollIntervalMs = rollIntervalMs;
+ this.metrics = metrics;
+ LOG.info("PendingContainerTracker initialized with maxContainerSize={}B, rollInterval={}ms",
+ maxContainerSize, rollIntervalMs);
+ }
+
+ /**
+ * Whether the datanode can fit another container of {@code containerSize} after accounting for
+ * SCM pending allocations for {@code node} (this tracker) and usable space on {@code datanodeInfo}.
+ * Combines {@link #getPendingAllocationSize} with the per-disk slot check in one call.
+ *
+ * @param node identity used to look up pending allocations (same DN as {@code datanodeInfo})
+ * @param datanodeInfo storage reports for the datanode
+ * @param containerSize required container size in bytes (typically SCM max container size)
+ */
+ /**
+ * Advances the two-window tumbling bucket for this datanode when the roll interval has elapsed.
+ * Call on periodic paths (e.g. node report) so windows age even when there are no new
+ * allocations or container reports touching this tracker.
+ */
+ public void rollWindowsIfNeeded(DatanodeDetails node) {
+ if (node == null) {
+ return;
+ }
+ UUID uuid = node.getUuid();
+ TwoWindowBucket bucket = datanodeBuckets.get(uuid);
+ if (bucket == null) {
+ return;
+ }
+ synchronized (bucket) {
+ bucket.rollIfNeeded();
+ if (bucket.isEmpty()) {
+ datanodeBuckets.remove(uuid, bucket);
+ }
+ }
+ }
+
+ public boolean hasEffectiveAllocatableSpaceForNewContainer(
+ DatanodeDetails node, DatanodeInfo datanodeInfo, long containerSize) {
+ if (node == null || datanodeInfo == null || containerSize <= 0) {
+ return false;
+ }
+ long pendingBytes = getPendingAllocationSize(node);
+ return hasAllocatableSpaceAfterPending(datanodeInfo, containerSize, pendingBytes);
+ }
+
+ private static boolean hasAllocatableSpaceAfterPending(
+ DatanodeInfo datanodeInfo, long containerSize, long pendingAllocationBytes) {
+ List<StorageReportProto> storageReports = datanodeInfo.getStorageReports();
+ if (storageReports == null || storageReports.isEmpty()) {
+ return false;
+ }
+ long effectiveAllocatableSpace = 0L;
+ for (StorageReportProto report : storageReports) {
+ long usableSpace = VolumeUsage.getUsableSpace(report);
+ long containersOnThisDisk = usableSpace / containerSize;
+ effectiveAllocatableSpace += containersOnThisDisk * containerSize;
+ if (effectiveAllocatableSpace - pendingAllocationBytes >= containerSize) {
+ return true;
+ }
+ }
+ return false;
+ }
+
+ /**
+ * Drops all pending allocation state for a datanode (e.g. stale/dead cleanup).
+ */
+ public void clearPendingForDatanode(DatanodeDetails node) {
+ if (node == null) {
+ return;
+ }
+ UUID uuid = node.getUuid();
+ TwoWindowBucket bucket = datanodeBuckets.get(uuid);
+ if (bucket == null) {
+ return;
+ }
+ synchronized (bucket) {
+ datanodeBuckets.remove(uuid, bucket);
+ }
+ LOG.debug("Cleared pending container allocations for datanode {}",
+ node.getUuidString());
+ }
+
+ /**
+ * Record a pending container allocation for all DataNodes in the pipeline.
+ * Container is added to the current window.
+ *
+ * @param pipeline The pipeline where container is allocated
+ * @param containerID The container being allocated
+ */
+ public void recordPendingAllocation(Pipeline pipeline, ContainerID containerID) {
+ if (pipeline == null || containerID == null) {
+ LOG.warn("Ignoring null pipeline or containerID");
+ return;
+ }
+
+ for (DatanodeDetails node : pipeline.getNodes()) {
+ recordPendingAllocationForDatanode(node, containerID);
+ }
+ }
+
+ /**
+ * Record a pending container allocation for a single DataNode.
+ * Container is added to the current window.
+ *
+ * @param node The DataNode where container is being allocated/replicated
+ * @param containerID The container being allocated/replicated
+ */
+ public void recordPendingAllocationForDatanode(DatanodeDetails node, ContainerID containerID) {
+ if (node == null || containerID == null) {
+ LOG.warn("Ignoring null node or containerID");
+ return;
+ }
+
+ UUID uuid = node.getUuid();
+ TwoWindowBucket bucket = datanodeBuckets.computeIfAbsent(
+ uuid,
+ k -> new TwoWindowBucket(rollIntervalMs)
+ );
+
+ synchronized (bucket) {
+ bucket.rollIfNeeded();
+ boolean added = bucket.add(containerID);
+ if (!bucket.isEmpty()) {
+ datanodeBuckets.put(uuid, bucket);
+ }
+ LOG.debug("Recorded pending container {} on DataNode {}. Added={}, Total pending={}",
+ containerID, node.getUuidString(), added, bucket.getCount());
+
+ if (added && metrics != null) {
+ metrics.incNumPendingContainersAdded();
+ }
+ }
+ }
+
+ /**
+ * Remove a pending container allocation from a specific DataNode.
+ * Removes from both current and previous windows.
+ * Called when container is confirmed.
+ *
+ * @param node The DataNode
+ * @param containerID The container to remove from pending
+ */
+ public void removePendingAllocation(DatanodeDetails node, ContainerID containerID) {
+ if (node == null || containerID == null) {
+ return;
+ }
+
+ UUID uuid = node.getUuid();
+ TwoWindowBucket bucket = datanodeBuckets.get(uuid);
+ if (bucket == null) {
+ return;
+ }
+
+ synchronized (bucket) {
+ bucket.rollIfNeeded();
+
+ boolean removed = bucket.remove(containerID);
+ LOG.debug("Removed pending container {} from DataNode {}. Removed={}, Remaining={}",
+ containerID, node.getUuidString(), removed, bucket.getCount());
+
+ if (removed && metrics != null) {
+ metrics.incNumPendingContainersRemoved();
+ }
+
+ if (bucket.isEmpty()) {
+ LOG.debug("Cleanup pending bucket containerID {}", containerID);
+ datanodeBuckets.remove(uuid, bucket);
+ }
+ }
+ }
+
+ /**
+ * Bytes of SCM-side pending container allocations for this datanode (count × configured max
+ * container size). For whether a new container can be placed, prefer
+ * {@link #hasEffectiveAllocatableSpaceForNewContainer}.
+ *
+ * @param node The DataNode
+ * @return Total bytes of pending container allocations
+ */
+ public long getPendingAllocationSize(DatanodeDetails node) {
+ if (node == null) {
+ return 0;
+ }
+
+ TwoWindowBucket bucket = datanodeBuckets.get(node.getUuid());
+ if (bucket == null) {
+ return 0;
+ }
+
+ synchronized (bucket) {
+ bucket.rollIfNeeded();
+ return (long) bucket.getCount() * maxContainerSize;
+ }
+ }
+
+ /**
+ * Get the set of pending container IDs for a DataNode.
+ * Returns union of current and previous windows.
+ * Useful for debugging and monitoring.
+ *
+ * @param node The DataNode
+ * @return Set of pending container IDs
+ */
+ public Set<ContainerID> getPendingContainers(DatanodeDetails node) {
+ if (node == null) {
+ return Collections.emptySet();
+ }
+
+ TwoWindowBucket bucket = datanodeBuckets.get(node.getUuid());
+ if (bucket == null) {
+ return Collections.emptySet();
+ }
+
+ synchronized (bucket) {
+ bucket.rollIfNeeded();
Review Comment:
Can you update the javadoc saying that,
```
/**
* Get the set of pending container IDs for a DataNode.
* Returns union of current and previous windows.
* Useful for debugging and monitoring.
*
* <p>Note: this call may advance the internal tumbling window if the roll interval has elapsed,
* ensuring the returned set reflects the most up-to-date pending state.</p>
*
* @param node The DataNode
* @return Set of pending container IDs
*/
```
##########
hadoop-hdds/server-scm/src/test/java/org/apache/hadoop/hdds/scm/node/TestPendingContainerTracker.java:
##########
@@ -0,0 +1,406 @@
+/*
+ * 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.node;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+
+import java.io.IOException;
+import java.util.Set;
+import org.apache.hadoop.hdds.protocol.DatanodeDetails;
+import org.apache.hadoop.hdds.protocol.MockDatanodeDetails;
+import org.apache.hadoop.hdds.scm.container.ContainerID;
+import org.apache.hadoop.hdds.scm.pipeline.MockPipeline;
+import org.apache.hadoop.hdds.scm.pipeline.Pipeline;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.Timeout;
+
+/**
+ * Tests for PendingContainerTracker.
+ */
+public class TestPendingContainerTracker {
+
+ private static final long MAX_CONTAINER_SIZE = 5L * 1024 * 1024 * 1024; // 5GB
+
+ private PendingContainerTracker tracker;
+ private Pipeline pipeline;
+ private DatanodeDetails dn1;
+ private DatanodeDetails dn2;
+ private DatanodeDetails dn3;
+ private ContainerID container1;
+ private ContainerID container2;
+ private ContainerID container3;
+
+ @BeforeEach
+ public void setUp() throws IOException {
+ tracker = new PendingContainerTracker(MAX_CONTAINER_SIZE);
+
+ // Create a 3-node Ratis pipeline
+ pipeline = MockPipeline.createPipeline(3);
+ dn1 = pipeline.getNodes().get(0);
+ dn2 = pipeline.getNodes().get(1);
+ dn3 = pipeline.getNodes().get(2);
+
+ container1 = ContainerID.valueOf(1L);
+ container2 = ContainerID.valueOf(2L);
+ container3 = ContainerID.valueOf(3L);
+ }
+
+ @Test
+ public void testRecordPendingAllocation() {
+ // Initially no pending containers
+ assertEquals(0, tracker.getPendingContainers(dn1).size());
+ assertEquals(0, tracker.getPendingAllocationSize(dn1));
+
+ // Record a pending allocation
+ tracker.recordPendingAllocation(pipeline, container1);
+
+ // All 3 DNs should have the container pending
+ assertEquals(1, tracker.getPendingContainers(dn1).size());
+ assertEquals(1, tracker.getPendingContainers(dn2).size());
+ assertEquals(1, tracker.getPendingContainers(dn3).size());
+
+ // Size should be MAX_CONTAINER_SIZE for each DN
+ assertEquals(MAX_CONTAINER_SIZE, tracker.getPendingAllocationSize(dn1));
+ assertEquals(MAX_CONTAINER_SIZE, tracker.getPendingAllocationSize(dn2));
+ assertEquals(MAX_CONTAINER_SIZE, tracker.getPendingAllocationSize(dn3));
+ }
+
+ @Test
+ public void testRecordMultiplePendingAllocations() {
+ tracker.recordPendingAllocation(pipeline, container1);
+ tracker.recordPendingAllocation(pipeline, container2);
+ tracker.recordPendingAllocation(pipeline, container3);
+
+ // Each DN should have 3 pending containers
+ assertEquals(3, tracker.getPendingContainers(dn1).size());
+ assertEquals(3, tracker.getPendingContainers(dn2).size());
+ assertEquals(3, tracker.getPendingContainers(dn3).size());
+
+ // Size should be 3 × MAX_CONTAINER_SIZE
+ assertEquals(3 * MAX_CONTAINER_SIZE, tracker.getPendingAllocationSize(dn1));
+ }
+
+ @Test
+ public void testIdempotentRecording() {
+ tracker.recordPendingAllocation(pipeline, container1);
+ tracker.recordPendingAllocation(pipeline, container1); // Duplicate
+
+ // Should still be 1 container (Set deduplication)
+ assertEquals(1, tracker.getPendingContainers(dn1).size());
+ assertEquals(MAX_CONTAINER_SIZE, tracker.getPendingAllocationSize(dn1));
+ }
+
+ /**
+ * After one roll interval, pending entries move from currentWindow to previousWindow and remain
+ * visible. After a second roll (2× interval total), the old previousWindow is discarded and the
+ * container ages out if not confirmed.
+ */
+ @Test
+ @Timeout(30)
+ public void testTwoWindowRollAgesOutContainerAfterTwoIntervals() throws InterruptedException {
+ long rollMs = 200L;
+ PendingContainerTracker shortRollTracker =
+ new PendingContainerTracker(MAX_CONTAINER_SIZE, rollMs, null);
+
+ shortRollTracker.recordPendingAllocationForDatanode(dn1, container1);
+ assertEquals(1, shortRollTracker.getPendingContainers(dn1).size());
+ assertThat(shortRollTracker.getPendingContainers(dn1)).contains(container1);
+
+ // First roll: C1 moves from currentWindow to previousWindow; union still includes C1
+ Thread.sleep(rollMs + 80);
+ shortRollTracker.rollWindowsIfNeeded(dn1);
+ assertEquals(1, shortRollTracker.getPendingContainers(dn1).size());
+ assertThat(shortRollTracker.getPendingContainers(dn1)).contains(container1);
+
+ // Second roll: prior previousWindow (holding C1) is dropped; C1 is no longer pending
+ Thread.sleep(rollMs + 80);
+ shortRollTracker.rollWindowsIfNeeded(dn1);
+ assertEquals(0, shortRollTracker.getPendingContainers(dn1).size());
+ assertEquals(0L, shortRollTracker.getPendingAllocationSize(dn1));
+ }
+
+ @Test
+ public void testRemovePendingAllocation() {
+ tracker.recordPendingAllocation(pipeline, container1);
+ tracker.recordPendingAllocation(pipeline, container2);
+
+ assertEquals(2, tracker.getPendingContainers(dn1).size());
+
+ // Remove one container from DN1
+ tracker.removePendingAllocation(dn1, container1);
+
+ assertEquals(1, tracker.getPendingContainers(dn1).size());
+ assertEquals(MAX_CONTAINER_SIZE, tracker.getPendingAllocationSize(dn1));
+
+ // DN2 and DN3 should still have both containers
+ assertEquals(2, tracker.getPendingContainers(dn2).size());
+ assertEquals(2, tracker.getPendingContainers(dn3).size());
+ }
+
+ @Test
+ public void testRemovePendingAllocationFromPipeline() {
+ tracker.recordPendingAllocation(pipeline, container1);
+ tracker.recordPendingAllocation(pipeline, container2);
+
+ // Remove container1 from all nodes in pipeline
+ for (DatanodeDetails dn : pipeline.getNodes()) {
+ tracker.removePendingAllocation(dn, container1);
+ }
+
+ // All DNs should have only container2 remaining
+ assertEquals(1, tracker.getPendingContainers(dn1).size());
+ assertEquals(1, tracker.getPendingContainers(dn2).size());
+ assertEquals(1, tracker.getPendingContainers(dn3).size());
+ }
+
+ @Test
+ public void testRemoveNonExistentContainer() {
+ tracker.recordPendingAllocation(pipeline, container1);
+
+ // Remove a container that was never added - should not throw exception
+ tracker.removePendingAllocation(dn1, container2);
+
+ // DN1 should still have container1
+ assertEquals(1, tracker.getPendingContainers(dn1).size());
+ }
+
+ @Test
+ public void testGetPendingContainers() {
+ tracker.recordPendingAllocation(pipeline, container1);
+ tracker.recordPendingAllocation(pipeline, container2);
+
+ Set<ContainerID> pending = tracker.getPendingContainers(dn1);
+
+ assertEquals(2, pending.size());
+ assertThat(pending.contains(container1));
Review Comment:
Should this be `assertThat(pending).contains(container1);` ?
Please visit all the occurrences of assertThat() in this file and fix it.
##########
hadoop-hdds/server-scm/src/main/java/org/apache/hadoop/hdds/scm/node/PendingContainerTracker.java:
##########
@@ -0,0 +1,425 @@
+/*
+ * 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.node;
+
+import com.google.common.annotations.VisibleForTesting;
+import java.util.Collections;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Set;
+import java.util.UUID;
+import java.util.concurrent.ConcurrentHashMap;
+import org.apache.hadoop.hdds.protocol.DatanodeDetails;
+import org.apache.hadoop.hdds.protocol.proto.StorageContainerDatanodeProtocolProtos.StorageReportProto;
+import org.apache.hadoop.hdds.scm.container.ContainerID;
+import org.apache.hadoop.hdds.scm.pipeline.Pipeline;
+import org.apache.hadoop.ozone.container.common.volume.VolumeUsage;
+import org.apache.hadoop.util.Time;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * Tracks per-datanode pending container allocations at SCM using a Two Window Tumbling Bucket
+ * pattern (similar to HDFS HADOOP-3707).
+ *
+ * Two Window Tumbling Bucket for automatic aging and cleanup.
+ *
+ * How It Works:
+ * <li>Each DataNode has two sets: <b>currentWindow</b> and <b>previousWindow</b></li>
+ * <li>New allocations go into <b>currentWindow</b></li>
+ * <li>Every <b>ROLL_INTERVAL</b> (default 5 minutes):
+ * <ul>
+ * <li>previousWindow = currentWindow (shift)</li>
+ * <li>currentWindow = new empty set (reset)</li>
+ * <li>Old previousWindow is discarded (automatic aging)</li>
+ * </ul>
+ * </li>
+ * <li>When checking pending: return <b>union</b> of currentWindow + previousWindow</li>
+ *
+ *
+ * Example Timeline:
+ * <pre>
+ * Time | Action | CurrentWindow | PreviousWindow | Total Pending
+ * ------+---------------------------+---------------+----------------+--------------
+ * 00:00 | Allocate Container-1 | {C1} | {} | {C1}
+ * 00:02 | Allocate Container-2 | {C1, C2} | {} | {C1, C2}
+ * 00:05 | [ROLL] Window tumbles | {} | {C1, C2} | {C1, C2}
+ * 00:07 | Allocate Container-3 | {C3} | {C1, C2} | {C1, C2, C3}
+ * 00:08 | Report confirms C1 | {C3} | {C2} | {C2, C3}
+ * 00:10 | [ROLL] Window tumbles | {} | {C3} | {C3}
+ * | (C2 aged out if not reported)
+ * </pre>
+ *
+ * <p>Thread-safety: all mutations and reads for a given datanode run under
+ * {@code synchronized (bucket)} on that datanode's {@link TwoWindowBucket}, including
+ * map insert/remove, so concurrent record/remove/report paths cannot interleave or orphan
+ * a bucket after it was dropped from the map.</p>
+ */
+public class PendingContainerTracker {
+
+ private static final Logger LOG = LoggerFactory.getLogger(PendingContainerTracker.class);
+
+ /**
+ * Roll interval in milliseconds.
+ * Configurable via hdds.scm.container.pending.allocation.roll.interval.
+ * Default: 5 minutes.
+ * Containers automatically age out after 2 × rollIntervalMs.
+ */
+ private final long rollIntervalMs;
+
+ /**
+ * Map of DataNode UUID to TwoWindowBucket.
+ */
+ private final ConcurrentHashMap<UUID, TwoWindowBucket> datanodeBuckets;
+
+ /**
+ * Maximum container size in bytes.
+ */
+ private final long maxContainerSize;
+
+ /**
+ * Metrics for tracking pending containers (same instance as {@link SCMNodeManager}'s node metrics).
+ */
+ private final SCMNodeMetrics metrics;
+
+ /**
+ * Two-window bucket for a single DataNode.
+ * Contains current and previous window sets, plus last roll timestamp.
+ */
+ private static class TwoWindowBucket {
+ private Set<ContainerID> currentWindow = new HashSet<>();
+ private Set<ContainerID> previousWindow = new HashSet<>();
+ private long lastRollTime = Time.monotonicNow();
+ private final long rollIntervalMs;
+
+ TwoWindowBucket(long rollIntervalMs) {
+ this.rollIntervalMs = rollIntervalMs;
+ }
+
+ /**
+ * Roll the windows: previous = current, current = empty.
+ * Called when current time exceeds lastRollTime + rollIntervalMs.
+ */
+ synchronized void rollIfNeeded() {
+ long now = Time.monotonicNow();
+ if (now - lastRollTime >= rollIntervalMs) {
+ // Shift: current becomes previous
+ previousWindow = currentWindow;
+ // Reset: new empty current window
+ currentWindow = new HashSet<>();
+ lastRollTime = now;
+ LOG.debug("Rolled window. Previous window size: {}, Current window reset to empty", previousWindow.size());
+ }
+ }
+
+ /**
+ * Get union of both windows (all pending containers).
+ */
+ synchronized Set<ContainerID> getAllPending() {
+ Set<ContainerID> all = new HashSet<>();
+ all.addAll(currentWindow);
+ all.addAll(previousWindow);
+ return all;
+ }
+
+ /**
+ * Add container to current window.
+ */
+ synchronized boolean add(ContainerID containerID) {
+ return currentWindow.add(containerID);
+ }
+
+ /**
+ * Remove container from both windows.
+ */
+ synchronized boolean remove(ContainerID containerID) {
+ boolean removedFromCurrent = currentWindow.remove(containerID);
+ boolean removedFromPrevious = previousWindow.remove(containerID);
+ return removedFromCurrent || removedFromPrevious;
+ }
+
+ /**
+ * Check if either window is non-empty.
+ */
+ synchronized boolean isEmpty() {
+ return currentWindow.isEmpty() && previousWindow.isEmpty();
+ }
+
+ /**
+ * Count of pending containers in both windows.
+ */
+ synchronized int getCount() {
+ return currentWindow.size() + previousWindow.size();
Review Comment:
For safe coding, can you please do union,
```
synchronized int getCount() {
return getAllPending().size()
}
```
##########
hadoop-hdds/server-scm/src/main/java/org/apache/hadoop/hdds/scm/node/PendingContainerTracker.java:
##########
@@ -0,0 +1,425 @@
+/*
+ * 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.node;
+
+import com.google.common.annotations.VisibleForTesting;
+import java.util.Collections;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Set;
+import java.util.UUID;
+import java.util.concurrent.ConcurrentHashMap;
+import org.apache.hadoop.hdds.protocol.DatanodeDetails;
+import org.apache.hadoop.hdds.protocol.proto.StorageContainerDatanodeProtocolProtos.StorageReportProto;
+import org.apache.hadoop.hdds.scm.container.ContainerID;
+import org.apache.hadoop.hdds.scm.pipeline.Pipeline;
+import org.apache.hadoop.ozone.container.common.volume.VolumeUsage;
+import org.apache.hadoop.util.Time;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * Tracks per-datanode pending container allocations at SCM using a Two Window Tumbling Bucket
+ * pattern (similar to HDFS HADOOP-3707).
+ *
+ * Two Window Tumbling Bucket for automatic aging and cleanup.
+ *
+ * How It Works:
+ * <li>Each DataNode has two sets: <b>currentWindow</b> and <b>previousWindow</b></li>
+ * <li>New allocations go into <b>currentWindow</b></li>
+ * <li>Every <b>ROLL_INTERVAL</b> (default 5 minutes):
+ * <ul>
+ * <li>previousWindow = currentWindow (shift)</li>
+ * <li>currentWindow = new empty set (reset)</li>
+ * <li>Old previousWindow is discarded (automatic aging)</li>
+ * </ul>
+ * </li>
+ * <li>When checking pending: return <b>union</b> of currentWindow + previousWindow</li>
+ *
+ *
+ * Example Timeline:
+ * <pre>
+ * Time | Action | CurrentWindow | PreviousWindow | Total Pending
+ * ------+---------------------------+---------------+----------------+--------------
+ * 00:00 | Allocate Container-1 | {C1} | {} | {C1}
+ * 00:02 | Allocate Container-2 | {C1, C2} | {} | {C1, C2}
+ * 00:05 | [ROLL] Window tumbles | {} | {C1, C2} | {C1, C2}
+ * 00:07 | Allocate Container-3 | {C3} | {C1, C2} | {C1, C2, C3}
+ * 00:08 | Report confirms C1 | {C3} | {C2} | {C2, C3}
+ * 00:10 | [ROLL] Window tumbles | {} | {C3} | {C3}
+ * | (C2 aged out if not reported)
+ * </pre>
+ *
+ * <p>Thread-safety: all mutations and reads for a given datanode run under
+ * {@code synchronized (bucket)} on that datanode's {@link TwoWindowBucket}, including
+ * map insert/remove, so concurrent record/remove/report paths cannot interleave or orphan
+ * a bucket after it was dropped from the map.</p>
+ */
+public class PendingContainerTracker {
+
+ private static final Logger LOG = LoggerFactory.getLogger(PendingContainerTracker.class);
+
+ /**
+ * Roll interval in milliseconds.
+ * Configurable via hdds.scm.container.pending.allocation.roll.interval.
+ * Default: 5 minutes.
+ * Containers automatically age out after 2 × rollIntervalMs.
+ */
+ private final long rollIntervalMs;
+
+ /**
+ * Map of DataNode UUID to TwoWindowBucket.
+ */
+ private final ConcurrentHashMap<UUID, TwoWindowBucket> datanodeBuckets;
+
+ /**
+ * Maximum container size in bytes.
+ */
+ private final long maxContainerSize;
+
+ /**
+ * Metrics for tracking pending containers (same instance as {@link SCMNodeManager}'s node metrics).
+ */
+ private final SCMNodeMetrics metrics;
+
+ /**
+ * Two-window bucket for a single DataNode.
+ * Contains current and previous window sets, plus last roll timestamp.
+ */
+ private static class TwoWindowBucket {
+ private Set<ContainerID> currentWindow = new HashSet<>();
+ private Set<ContainerID> previousWindow = new HashSet<>();
+ private long lastRollTime = Time.monotonicNow();
+ private final long rollIntervalMs;
+
+ TwoWindowBucket(long rollIntervalMs) {
+ this.rollIntervalMs = rollIntervalMs;
+ }
+
+ /**
+ * Roll the windows: previous = current, current = empty.
+ * Called when current time exceeds lastRollTime + rollIntervalMs.
+ */
+ synchronized void rollIfNeeded() {
+ long now = Time.monotonicNow();
+ if (now - lastRollTime >= rollIntervalMs) {
+ // Shift: current becomes previous
+ previousWindow = currentWindow;
+ // Reset: new empty current window
+ currentWindow = new HashSet<>();
+ lastRollTime = now;
+ LOG.debug("Rolled window. Previous window size: {}, Current window reset to empty", previousWindow.size());
+ }
+ }
+
+ /**
+ * Get union of both windows (all pending containers).
+ */
+ synchronized Set<ContainerID> getAllPending() {
+ Set<ContainerID> all = new HashSet<>();
+ all.addAll(currentWindow);
+ all.addAll(previousWindow);
+ return all;
+ }
+
+ /**
+ * Add container to current window.
+ */
+ synchronized boolean add(ContainerID containerID) {
+ return currentWindow.add(containerID);
+ }
+
+ /**
+ * Remove container from both windows.
+ */
+ synchronized boolean remove(ContainerID containerID) {
+ boolean removedFromCurrent = currentWindow.remove(containerID);
+ boolean removedFromPrevious = previousWindow.remove(containerID);
+ return removedFromCurrent || removedFromPrevious;
+ }
+
+ /**
+ * Check if either window is non-empty.
+ */
+ synchronized boolean isEmpty() {
+ return currentWindow.isEmpty() && previousWindow.isEmpty();
+ }
+
+ /**
+ * Count of pending containers in both windows.
+ */
+ synchronized int getCount() {
+ return currentWindow.size() + previousWindow.size();
+ }
+ }
+
+ public PendingContainerTracker(long maxContainerSize) {
+ this(maxContainerSize, 10 * 60 * 1000, null); // Default 10 minutes
+ }
+
+ public PendingContainerTracker(long maxContainerSize, long rollIntervalMs,
+ SCMNodeMetrics metrics) {
+ this.datanodeBuckets = new ConcurrentHashMap<>();
+ this.maxContainerSize = maxContainerSize;
+ this.rollIntervalMs = rollIntervalMs;
+ this.metrics = metrics;
+ LOG.info("PendingContainerTracker initialized with maxContainerSize={}B, rollInterval={}ms",
+ maxContainerSize, rollIntervalMs);
+ }
+
+ /**
Review Comment:
This has two javadocs. I think the below one is meant for `hasEffectiveAllocatableSpaceForNewContainer` mthod, right?. Please move this javadoc there.
```
/**
* Whether the datanode can fit another container of {@code containerSize} after accounting for
* SCM pending allocations for {@code node} (this tracker) and usable space on {@code datanodeInfo}.
* Combines {@link #getPendingAllocationSize} with the per-disk slot check in one call.
*
* @param node identity used to look up pending allocations (same DN as {@code datanodeInfo})
* @param datanodeInfo storage reports for the datanode
* @param containerSize required container size in bytes (typically SCM max container size)
*/
```
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org
For additional commands, e-mail: issues-help@ozone.apache.org
Re: [PR] HDDS-14921. Improve space accounting in SCM with In-Flight container allocation tracking. [ozone]
Posted by "ashishkumar50 (via GitHub)" <gi...@apache.org>.
ashishkumar50 commented on code in PR #10000:
URL: https://github.com/apache/ozone/pull/10000#discussion_r3050056386
##########
hadoop-hdds/server-scm/src/main/java/org/apache/hadoop/hdds/scm/container/ContainerManagerImpl.java:
##########
Review Comment:
@aswinshakil Some allocation may happen extra but that will be taken care by [PR](https://github.com/apache/ozone/pull/10054) as DN has more buffer to handle of these extra allocation. In my opinion synchronizing completely will be too costly here.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org
For additional commands, e-mail: issues-help@ozone.apache.org
Re: [PR] HDDS-14921. Improve space accounting in SCM with In-Flight container allocation tracking. [ozone]
Posted by "ashishkumar50 (via GitHub)" <gi...@apache.org>.
ashishkumar50 commented on code in PR #10000:
URL: https://github.com/apache/ozone/pull/10000#discussion_r3035994917
##########
hadoop-hdds/server-scm/src/test/java/org/apache/hadoop/hdds/scm/node/TestPendingContainerTracker.java:
##########
@@ -0,0 +1,375 @@
+/*
+ * 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;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+
+import java.io.IOException;
+import java.util.Set;
+import org.apache.hadoop.hdds.protocol.DatanodeDetails;
+import org.apache.hadoop.hdds.protocol.MockDatanodeDetails;
+import org.apache.hadoop.hdds.scm.pipeline.MockPipeline;
+import org.apache.hadoop.hdds.scm.pipeline.Pipeline;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+
+/**
+ * Tests for PendingContainerTracker.
+ */
+public class TestPendingContainerTracker {
+
+ private static final long MAX_CONTAINER_SIZE = 5L * 1024 * 1024 * 1024; // 5GB
+
+ private PendingContainerTracker tracker;
+ private Pipeline pipeline;
+ private DatanodeDetails dn1;
+ private DatanodeDetails dn2;
+ private DatanodeDetails dn3;
+ private ContainerID container1;
+ private ContainerID container2;
+ private ContainerID container3;
+
+ @BeforeEach
+ public void setUp() throws IOException {
+ tracker = new PendingContainerTracker(MAX_CONTAINER_SIZE);
+
+ // Create a 3-node Ratis pipeline
+ pipeline = MockPipeline.createPipeline(3);
+ dn1 = pipeline.getNodes().get(0);
+ dn2 = pipeline.getNodes().get(1);
+ dn3 = pipeline.getNodes().get(2);
+
+ container1 = ContainerID.valueOf(1L);
+ container2 = ContainerID.valueOf(2L);
+ container3 = ContainerID.valueOf(3L);
+ }
+
+ @Test
+ public void testRecordPendingAllocation() {
+ // Initially no pending containers
+ assertEquals(0, tracker.getPendingContainers(dn1).size());
+ assertEquals(0, tracker.getPendingAllocationSize(dn1));
+
+ // Record a pending allocation
+ tracker.recordPendingAllocation(pipeline, container1);
+
+ // All 3 DNs should have the container pending
+ assertEquals(1, tracker.getPendingContainers(dn1).size());
+ assertEquals(1, tracker.getPendingContainers(dn2).size());
+ assertEquals(1, tracker.getPendingContainers(dn3).size());
+
+ // Size should be MAX_CONTAINER_SIZE for each DN
+ assertEquals(MAX_CONTAINER_SIZE, tracker.getPendingAllocationSize(dn1));
+ assertEquals(MAX_CONTAINER_SIZE, tracker.getPendingAllocationSize(dn2));
+ assertEquals(MAX_CONTAINER_SIZE, tracker.getPendingAllocationSize(dn3));
+ }
+
+ @Test
+ public void testRecordMultiplePendingAllocations() {
+ tracker.recordPendingAllocation(pipeline, container1);
+ tracker.recordPendingAllocation(pipeline, container2);
+ tracker.recordPendingAllocation(pipeline, container3);
+
+ // Each DN should have 3 pending containers
+ assertEquals(3, tracker.getPendingContainers(dn1).size());
+ assertEquals(3, tracker.getPendingContainers(dn2).size());
+ assertEquals(3, tracker.getPendingContainers(dn3).size());
+
+ // Size should be 3 × MAX_CONTAINER_SIZE
+ assertEquals(3 * MAX_CONTAINER_SIZE, tracker.getPendingAllocationSize(dn1));
+ }
+
+ @Test
+ public void testIdempotentRecording() {
+ tracker.recordPendingAllocation(pipeline, container1);
+ tracker.recordPendingAllocation(pipeline, container1); // Duplicate
+
+ // Should still be 1 container (Set deduplication)
+ assertEquals(1, tracker.getPendingContainers(dn1).size());
+ assertEquals(MAX_CONTAINER_SIZE, tracker.getPendingAllocationSize(dn1));
+ }
+
+ @Test
+ public void testRemovePendingAllocation() {
+ tracker.recordPendingAllocation(pipeline, container1);
+ tracker.recordPendingAllocation(pipeline, container2);
+
+ assertEquals(2, tracker.getPendingContainers(dn1).size());
+
+ // Remove one container from DN1
+ tracker.removePendingAllocation(dn1, container1);
+
+ assertEquals(1, tracker.getPendingContainers(dn1).size());
+ assertEquals(MAX_CONTAINER_SIZE, tracker.getPendingAllocationSize(dn1));
+
+ // DN2 and DN3 should still have both containers
+ assertEquals(2, tracker.getPendingContainers(dn2).size());
+ assertEquals(2, tracker.getPendingContainers(dn3).size());
+ }
+
+ @Test
+ public void testRemovePendingAllocationFromPipeline() {
+ tracker.recordPendingAllocation(pipeline, container1);
+ tracker.recordPendingAllocation(pipeline, container2);
+
+ // Remove container1 from all nodes in pipeline
+ for (DatanodeDetails dn : pipeline.getNodes()) {
+ tracker.removePendingAllocation(dn, container1);
+ }
+
+ // All DNs should have only container2 remaining
+ assertEquals(1, tracker.getPendingContainers(dn1).size());
+ assertEquals(1, tracker.getPendingContainers(dn2).size());
+ assertEquals(1, tracker.getPendingContainers(dn3).size());
+ }
+
+ @Test
+ public void testRemoveNonExistentContainer() {
+ tracker.recordPendingAllocation(pipeline, container1);
+
+ // Remove a container that was never added - should not throw exception
+ tracker.removePendingAllocation(dn1, container2);
+
+ // DN1 should still have container1
+ assertEquals(1, tracker.getPendingContainers(dn1).size());
+ }
+
+ @Test
+ public void testGetPendingContainers() {
+ tracker.recordPendingAllocation(pipeline, container1);
+ tracker.recordPendingAllocation(pipeline, container2);
+
+ Set<ContainerID> pending = tracker.getPendingContainers(dn1);
+
+ assertEquals(2, pending.size());
+ assertThat(pending.contains(container1));
+ assertThat(pending.contains(container2));
+
+ // Returned set should be a copy - modifying it shouldn't affect tracker
+ pending.add(container3);
+ assertEquals(2, tracker.getPendingContainers(dn1).size()); // Should still be 2
+ }
+
+ @Test
+ public void testGetPendingContainersForNonExistentDN() {
+ DatanodeDetails unknownDN = MockDatanodeDetails.randomDatanodeDetails();
+
+ Set<ContainerID> pending = tracker.getPendingContainers(unknownDN);
+
+ assertThat(pending.isEmpty());
+ }
+
+ @Test
+ public void testGetTotalPendingCount() {
+ assertEquals(0, tracker.getTotalPendingCount());
+
+ tracker.recordPendingAllocation(pipeline, container1);
+
+ // 1 container × 3 DNs = 3 total pending
+ assertEquals(3, tracker.getTotalPendingCount());
+
+ tracker.recordPendingAllocation(pipeline, container2);
+
+ // 2 containers × 3 DNs = 6 total pending
+ assertEquals(6, tracker.getTotalPendingCount());
+
+ // Remove from one DN
+ tracker.removePendingAllocation(dn1, container1);
+
+ // (2 containers × 2 DNs) + (1 container × 1 DN) = 5 total
+ assertEquals(5, tracker.getTotalPendingCount());
+ }
+
+ @Test
+ public void testConcurrentModification() throws InterruptedException {
+ // Test thread-safety by having multiple threads add/remove containers
+ final int numThreads = 10;
+ final int operationsPerThread = 100;
+
+ Thread[] threads = new Thread[numThreads];
+
+ for (int i = 0; i < numThreads; i++) {
+ final int threadId = i;
+ threads[i] = new Thread(() -> {
+ for (int j = 0; j < operationsPerThread; j++) {
+ ContainerID cid = ContainerID.valueOf(threadId * 1000L + j);
+ tracker.recordPendingAllocation(pipeline, cid);
+
+ if (j % 2 == 0) {
+ tracker.removePendingAllocation(dn1, cid);
+ }
+ }
+ });
+ }
+
+ // Start all threads
+ for (Thread thread : threads) {
+ thread.start();
+ }
+
+ // Wait for all to finish
+ for (Thread thread : threads) {
+ thread.join();
+ }
+
+ // Verify no exceptions occurred and counts are reasonable
+ assertThat(tracker.getTotalPendingCount() >= 0);
+ assertThat(tracker.getDataNodeCount() <= 3);
+ }
+
+ @Test
+ public void testMemoryCleanupOnEmptySet() {
+ tracker.recordPendingAllocation(pipeline, container1);
+
+ assertEquals(3, tracker.getDataNodeCount());
+
+ // Remove the only pending container from DN1
+ tracker.removePendingAllocation(dn1, container1);
+
+ // DN1 should be removed from the map (memory cleanup)
+ assertEquals(2, tracker.getDataNodeCount());
+ }
+
+ @Test
+ public void testPendingContainer() {
+ // Simulate allocation and confirmation flow
+
+ // Allocate 3 containers
+ tracker.recordPendingAllocation(pipeline, container1);
+ tracker.recordPendingAllocation(pipeline, container2);
+ tracker.recordPendingAllocation(pipeline, container3);
+
+ // Each DN should have 3 pending, 15GB total
+ assertEquals(3, tracker.getPendingContainers(dn1).size());
+ assertEquals(3 * MAX_CONTAINER_SIZE, tracker.getPendingAllocationSize(dn1));
+
+ // DN1 confirms container1 via container report
+ tracker.removePendingAllocation(dn1, container1);
+
+ // DN1 now has 2 pending, 10GB
+ assertEquals(2, tracker.getPendingContainers(dn1).size());
+ assertEquals(2 * MAX_CONTAINER_SIZE, tracker.getPendingAllocationSize(dn1));
+
+ // DN2 and DN3 still have 3 pending
+ assertEquals(3, tracker.getPendingContainers(dn2).size());
+ assertEquals(3, tracker.getPendingContainers(dn3).size());
+
+ // All DNs eventually confirm all containers
+ for (DatanodeDetails dn : pipeline.getNodes()) {
+ tracker.removePendingAllocation(dn, container1);
+ tracker.removePendingAllocation(dn, container2);
+ tracker.removePendingAllocation(dn, container3);
+ }
+
+ // All DNs should have 0 pending
+ assertEquals(0, tracker.getPendingContainers(dn1).size());
+ assertEquals(0, tracker.getPendingContainers(dn2).size());
+ assertEquals(0, tracker.getPendingContainers(dn3).size());
+ assertEquals(0, tracker.getTotalPendingCount());
+ assertEquals(0, tracker.getDataNodeCount());
+ }
+
+ @Test
+ public void testRemoveFromBothWindows() {
Review Comment:
Added test for this `testTwoWindowRollAgesOutContainerAfterTwoIntervals`.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org
For additional commands, e-mail: issues-help@ozone.apache.org
Re: [PR] HDDS-14921. Improve space accounting in SCM with In-Flight container allocation tracking. [ozone]
Posted by "rakeshadr (via GitHub)" <gi...@apache.org>.
rakeshadr commented on code in PR #10000:
URL: https://github.com/apache/ozone/pull/10000#discussion_r3045242417
##########
hadoop-hdds/server-scm/src/main/java/org/apache/hadoop/hdds/scm/node/PendingContainerTracker.java:
##########
@@ -0,0 +1,338 @@
+/*
+ * 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;
+
+import com.google.common.annotations.VisibleForTesting;
+import java.util.Collections;
+import java.util.HashSet;
+import java.util.Set;
+import java.util.UUID;
+import java.util.concurrent.ConcurrentHashMap;
+import org.apache.hadoop.hdds.protocol.DatanodeDetails;
+import org.apache.hadoop.hdds.scm.container.metrics.SCMContainerManagerMetrics;
+import org.apache.hadoop.hdds.scm.pipeline.Pipeline;
+import org.apache.hadoop.util.Time;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * Tracks pending container allocations using a Two Window Tumbling Bucket pattern.
+ * Similar like HDFS HADOOP-3707.
+ *
+ * Two Window Tumbling Bucket for automatic aging and cleanup.
+ *
+ * How It Works:
+ * <li>Each DataNode has two sets: <b>currentWindow</b> and <b>previousWindow</b></li>
+ * <li>New allocations go into <b>currentWindow</b></li>
+ * <li>Every <b>ROLL_INTERVAL</b> (default 10 minutes):
+ * <ul>
+ * <li>previousWindow = currentWindow (shift)</li>
+ * <li>currentWindow = new empty set (reset)</li>
+ * <li>Old previousWindow is discarded (automatic aging)</li>
+ * </ul>
+ * </li>
+ * <li>When checking pending: return <b>union</b> of currentWindow + previousWindow</li>
+ *
+ *
+ * Example Timeline:
+ * <pre>
+ * Time | Action | CurrentWindow | PreviousWindow | Total Pending
+ * ------+---------------------------+---------------+----------------+--------------
+ * 00:00 | Allocate Container-1 | {C1} | {} | {C1}
+ * 00:05 | Allocate Container-2 | {C1, C2} | {} | {C1, C2}
+ * 00:10 | [ROLL] Window tumbles | {} | {C1, C2} | {C1, C2}
+ * 00:12 | Allocate Container-3 | {C3} | {C1, C2} | {C1, C2, C3}
+ * 00:15 | Report confirms C1 | {C3} | {C2} | {C2, C3}
+ * 00:20 | [ROLL] Window tumbles | {} | {C3} | {C3}
+ * | (C2 aged out if not reported)
+ * </pre>
+ *
+ */
+public class PendingContainerTracker {
+
+ private static final Logger LOG = LoggerFactory.getLogger(PendingContainerTracker.class);
+
+ /**
+ * Roll interval in milliseconds.
+ * Configurable via hdds.scm.container.pending-allocation.roll-interval.
+ * Default: 10 minutes.
+ * Containers automatically age out after 2 × rollIntervalMs.
+ */
+ private final long rollIntervalMs;
+
+ /**
+ * Map of DataNode UUID to TwoWindowBucket.
+ */
+ private final ConcurrentHashMap<UUID, TwoWindowBucket> datanodeBuckets;
+
+ /**
+ * Maximum container size in bytes.
+ */
+ private final long maxContainerSize;
+
+ /**
+ * Metrics for tracking pending containers.
+ */
+ private final SCMContainerManagerMetrics metrics;
+
+ /**
+ * Two-window bucket for a single DataNode.
+ * Contains current and previous window sets, plus last roll timestamp.
+ */
+ private static class TwoWindowBucket {
+ private Set<ContainerID> currentWindow = ConcurrentHashMap.newKeySet();
+ private Set<ContainerID> previousWindow = ConcurrentHashMap.newKeySet();
+ private long lastRollTime = Time.monotonicNow();
+ private final long rollIntervalMs;
+
+ TwoWindowBucket(long rollIntervalMs) {
+ this.rollIntervalMs = rollIntervalMs;
+ }
+
+ /**
+ * Roll the windows: previous = current, current = empty.
+ * Called when current time exceeds lastRollTime + rollIntervalMs.
+ */
+ synchronized void rollIfNeeded() {
+ long now = Time.monotonicNow();
+ if (now - lastRollTime >= rollIntervalMs) {
+ // Shift: current becomes previous
+ previousWindow = currentWindow;
+ // Reset: new empty current window
+ currentWindow = ConcurrentHashMap.newKeySet();
+ lastRollTime = now;
+ LOG.debug("Rolled window. Previous window size: {}, Current window reset to empty", previousWindow.size());
+ }
+ }
+
+ /**
+ * Get union of both windows (all pending containers).
+ */
+ synchronized Set<ContainerID> getAllPending() {
+ Set<ContainerID> all = new HashSet<>();
+ all.addAll(currentWindow);
+ all.addAll(previousWindow);
+ return all;
+ }
+
+ /**
+ * Add container to current window.
+ */
+ synchronized boolean add(ContainerID containerID) {
+ return currentWindow.add(containerID);
+ }
+
+ /**
+ * Remove container from both windows.
+ */
+ synchronized boolean remove(ContainerID containerID) {
+ boolean removedFromCurrent = currentWindow.remove(containerID);
+ boolean removedFromPrevious = previousWindow.remove(containerID);
+ return removedFromCurrent || removedFromPrevious;
+ }
+
+ /**
+ * Check if either window is non-empty.
+ */
+ synchronized boolean isEmpty() {
+ return currentWindow.isEmpty() && previousWindow.isEmpty();
+ }
+
+ /**
+ * Get count of all pending containers (union).
+ */
+ synchronized int getCount() {
+ return getAllPending().size();
+ }
+ }
+
+ public PendingContainerTracker(long maxContainerSize) {
+ this(maxContainerSize, 10 * 60 * 1000, null); // Default 10 minutes
+ }
+
+ public PendingContainerTracker(long maxContainerSize, long rollIntervalMs,
+ SCMContainerManagerMetrics metrics) {
+ this.datanodeBuckets = new ConcurrentHashMap<>();
+ this.maxContainerSize = maxContainerSize;
+ this.rollIntervalMs = rollIntervalMs;
+ this.metrics = metrics;
+ LOG.info("PendingContainerTracker initialized with maxContainerSize={}B, rollInterval={}ms",
+ maxContainerSize, rollIntervalMs);
+ }
+
+ /**
+ * Record a pending container allocation for all DataNodes in the pipeline.
+ * Container is added to the current window.
+ *
+ * @param pipeline The pipeline where container is allocated
+ * @param containerID The container being allocated
+ */
+ public void recordPendingAllocation(Pipeline pipeline, ContainerID containerID) {
+ if (pipeline == null || containerID == null) {
+ LOG.warn("Ignoring null pipeline or containerID");
+ return;
+ }
+
+ for (DatanodeDetails node : pipeline.getNodes()) {
+ recordPendingAllocationForDatanode(node, containerID);
+ }
+ }
+
+ /**
+ * Record a pending container allocation for a single DataNode.
+ * Container is added to the current window.
+ *
+ * @param node The DataNode where container is being allocated/replicated
+ * @param containerID The container being allocated/replicated
+ */
+ public void recordPendingAllocationForDatanode(DatanodeDetails node, ContainerID containerID) {
+ if (node == null || containerID == null) {
+ LOG.warn("Ignoring null node or containerID");
+ return;
+ }
+
+ TwoWindowBucket bucket = datanodeBuckets.computeIfAbsent(
+ node.getUuid(),
+ k -> new TwoWindowBucket(rollIntervalMs)
+ );
+
+ // Roll window if needed before adding
+ bucket.rollIfNeeded();
+
+ boolean added = bucket.add(containerID);
+ LOG.info("Recorded pending container {} on DataNode {}. Added={}, Total pending={}",
+ containerID, node.getUuidString(), added, bucket.getCount());
+
+ // Increment metrics counter
+ if (added && metrics != null) {
+ metrics.incNumPendingContainersAdded();
+ }
+ }
+
+ /**
+ * Remove a pending container allocation from a specific DataNode.
+ * Removes from both current and previous windows.
+ * Called when container is confirmed.
+ *
+ * @param node The DataNode
+ * @param containerID The container to remove from pending
+ */
+ public void removePendingAllocation(DatanodeDetails node, ContainerID containerID) {
+ if (node == null || containerID == null) {
+ return;
+ }
+
+ TwoWindowBucket bucket = datanodeBuckets.get(node.getUuid());
+ if (bucket != null) {
+ // Roll window if needed before removing
+ bucket.rollIfNeeded();
+
+ boolean removed = bucket.remove(containerID);
+ LOG.info("Removed pending container {} from DataNode {}. Removed={}, Remaining={}",
+ containerID, node.getUuidString(), removed, bucket.getCount());
+
+ // Increment metrics counter
+ if (removed && metrics != null) {
+ metrics.incNumPendingContainersRemoved();
+ }
+
+ // Cleanup empty buckets to prevent memory leak
+ if (bucket.isEmpty()) {
Review Comment:
Please use CHM mutation, that will simplify it.
```
bucket.rollIfNeeded();
removed.set(bucket.remove(containerID));
remaining.set(bucket.getCount());
LOG.debug("Removed pending container {} from DataNode {}. Removed={}, Remaining={}",
containerID, node.getUuidString(), removed.get(), remaining.get());
return bucket.isEmpty() ? null : bucket;
});
if (removed.get() && metrics != null) {
metrics.incNumPendingContainersRemoved();
}
```
_Important lock design principle:-_
PendingContainerTracker: Please ensure no bucket -> map mutation path anymore. You need to switch remove/roll/clear to concurrenthashmap compute-based mutations, keep bucket internals intact.
##########
hadoop-hdds/server-scm/src/main/java/org/apache/hadoop/hdds/scm/node/PendingContainerTracker.java:
##########
@@ -0,0 +1,425 @@
+/*
+ * 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.node;
+
+import com.google.common.annotations.VisibleForTesting;
+import java.util.Collections;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Set;
+import java.util.UUID;
+import java.util.concurrent.ConcurrentHashMap;
+import org.apache.hadoop.hdds.protocol.DatanodeDetails;
+import org.apache.hadoop.hdds.protocol.proto.StorageContainerDatanodeProtocolProtos.StorageReportProto;
+import org.apache.hadoop.hdds.scm.container.ContainerID;
+import org.apache.hadoop.hdds.scm.pipeline.Pipeline;
+import org.apache.hadoop.ozone.container.common.volume.VolumeUsage;
+import org.apache.hadoop.util.Time;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * Tracks per-datanode pending container allocations at SCM using a Two Window Tumbling Bucket
+ * pattern (similar to HDFS HADOOP-3707).
+ *
+ * Two Window Tumbling Bucket for automatic aging and cleanup.
+ *
+ * How It Works:
+ * <li>Each DataNode has two sets: <b>currentWindow</b> and <b>previousWindow</b></li>
+ * <li>New allocations go into <b>currentWindow</b></li>
+ * <li>Every <b>ROLL_INTERVAL</b> (default 5 minutes):
+ * <ul>
+ * <li>previousWindow = currentWindow (shift)</li>
+ * <li>currentWindow = new empty set (reset)</li>
+ * <li>Old previousWindow is discarded (automatic aging)</li>
+ * </ul>
+ * </li>
+ * <li>When checking pending: return <b>union</b> of currentWindow + previousWindow</li>
+ *
+ *
+ * Example Timeline:
+ * <pre>
+ * Time | Action | CurrentWindow | PreviousWindow | Total Pending
+ * ------+---------------------------+---------------+----------------+--------------
+ * 00:00 | Allocate Container-1 | {C1} | {} | {C1}
+ * 00:02 | Allocate Container-2 | {C1, C2} | {} | {C1, C2}
+ * 00:05 | [ROLL] Window tumbles | {} | {C1, C2} | {C1, C2}
+ * 00:07 | Allocate Container-3 | {C3} | {C1, C2} | {C1, C2, C3}
+ * 00:08 | Report confirms C1 | {C3} | {C2} | {C2, C3}
+ * 00:10 | [ROLL] Window tumbles | {} | {C3} | {C3}
+ * | (C2 aged out if not reported)
+ * </pre>
+ *
+ * <p>Thread-safety: all mutations and reads for a given datanode run under
+ * {@code synchronized (bucket)} on that datanode's {@link TwoWindowBucket}, including
+ * map insert/remove, so concurrent record/remove/report paths cannot interleave or orphan
+ * a bucket after it was dropped from the map.</p>
+ */
+public class PendingContainerTracker {
+
+ private static final Logger LOG = LoggerFactory.getLogger(PendingContainerTracker.class);
+
+ /**
+ * Roll interval in milliseconds.
+ * Configurable via hdds.scm.container.pending.allocation.roll.interval.
+ * Default: 5 minutes.
+ * Containers automatically age out after 2 × rollIntervalMs.
+ */
+ private final long rollIntervalMs;
+
+ /**
+ * Map of DataNode UUID to TwoWindowBucket.
+ */
+ private final ConcurrentHashMap<UUID, TwoWindowBucket> datanodeBuckets;
+
+ /**
+ * Maximum container size in bytes.
+ */
+ private final long maxContainerSize;
+
+ /**
+ * Metrics for tracking pending containers (same instance as {@link SCMNodeManager}'s node metrics).
+ */
+ private final SCMNodeMetrics metrics;
+
+ /**
+ * Two-window bucket for a single DataNode.
+ * Contains current and previous window sets, plus last roll timestamp.
+ */
+ private static class TwoWindowBucket {
+ private Set<ContainerID> currentWindow = new HashSet<>();
+ private Set<ContainerID> previousWindow = new HashSet<>();
+ private long lastRollTime = Time.monotonicNow();
+ private final long rollIntervalMs;
+
+ TwoWindowBucket(long rollIntervalMs) {
+ this.rollIntervalMs = rollIntervalMs;
+ }
+
+ /**
+ * Roll the windows: previous = current, current = empty.
+ * Called when current time exceeds lastRollTime + rollIntervalMs.
+ */
+ synchronized void rollIfNeeded() {
+ long now = Time.monotonicNow();
+ if (now - lastRollTime >= rollIntervalMs) {
+ // Shift: current becomes previous
+ previousWindow = currentWindow;
+ // Reset: new empty current window
+ currentWindow = new HashSet<>();
+ lastRollTime = now;
+ LOG.debug("Rolled window. Previous window size: {}, Current window reset to empty", previousWindow.size());
+ }
+ }
+
+ /**
+ * Get union of both windows (all pending containers).
+ */
+ synchronized Set<ContainerID> getAllPending() {
+ Set<ContainerID> all = new HashSet<>();
+ all.addAll(currentWindow);
+ all.addAll(previousWindow);
+ return all;
+ }
+
+ /**
+ * Add container to current window.
+ */
+ synchronized boolean add(ContainerID containerID) {
+ return currentWindow.add(containerID);
+ }
+
+ /**
+ * Remove container from both windows.
+ */
+ synchronized boolean remove(ContainerID containerID) {
+ boolean removedFromCurrent = currentWindow.remove(containerID);
+ boolean removedFromPrevious = previousWindow.remove(containerID);
+ return removedFromCurrent || removedFromPrevious;
+ }
+
+ /**
+ * Check if either window is non-empty.
+ */
+ synchronized boolean isEmpty() {
+ return currentWindow.isEmpty() && previousWindow.isEmpty();
+ }
+
+ /**
+ * Count of pending containers in both windows.
+ */
+ synchronized int getCount() {
+ return currentWindow.size() + previousWindow.size();
+ }
+ }
+
+ public PendingContainerTracker(long maxContainerSize) {
+ this(maxContainerSize, 10 * 60 * 1000, null); // Default 10 minutes
+ }
+
+ public PendingContainerTracker(long maxContainerSize, long rollIntervalMs,
+ SCMNodeMetrics metrics) {
+ this.datanodeBuckets = new ConcurrentHashMap<>();
+ this.maxContainerSize = maxContainerSize;
+ this.rollIntervalMs = rollIntervalMs;
+ this.metrics = metrics;
+ LOG.info("PendingContainerTracker initialized with maxContainerSize={}B, rollInterval={}ms",
+ maxContainerSize, rollIntervalMs);
+ }
+
+ /**
+ * Whether the datanode can fit another container of {@code containerSize} after accounting for
+ * SCM pending allocations for {@code node} (this tracker) and usable space on {@code datanodeInfo}.
+ * Combines {@link #getPendingAllocationSize} with the per-disk slot check in one call.
+ *
+ * @param node identity used to look up pending allocations (same DN as {@code datanodeInfo})
+ * @param datanodeInfo storage reports for the datanode
+ * @param containerSize required container size in bytes (typically SCM max container size)
+ */
+ /**
+ * Advances the two-window tumbling bucket for this datanode when the roll interval has elapsed.
+ * Call on periodic paths (e.g. node report) so windows age even when there are no new
+ * allocations or container reports touching this tracker.
+ */
+ public void rollWindowsIfNeeded(DatanodeDetails node) {
+ if (node == null) {
+ return;
+ }
+ UUID uuid = node.getUuid();
+ TwoWindowBucket bucket = datanodeBuckets.get(uuid);
+ if (bucket == null) {
+ return;
+ }
+ synchronized (bucket) {
+ bucket.rollIfNeeded();
+ if (bucket.isEmpty()) {
+ datanodeBuckets.remove(uuid, bucket);
+ }
+ }
+ }
+
+ public boolean hasEffectiveAllocatableSpaceForNewContainer(
+ DatanodeDetails node, DatanodeInfo datanodeInfo, long containerSize) {
+ if (node == null || datanodeInfo == null || containerSize <= 0) {
+ return false;
+ }
+ long pendingBytes = getPendingAllocationSize(node);
+ return hasAllocatableSpaceAfterPending(datanodeInfo, containerSize, pendingBytes);
+ }
+
+ private static boolean hasAllocatableSpaceAfterPending(
+ DatanodeInfo datanodeInfo, long containerSize, long pendingAllocationBytes) {
+ List<StorageReportProto> storageReports = datanodeInfo.getStorageReports();
+ if (storageReports == null || storageReports.isEmpty()) {
+ return false;
+ }
+ long effectiveAllocatableSpace = 0L;
+ for (StorageReportProto report : storageReports) {
+ long usableSpace = VolumeUsage.getUsableSpace(report);
+ long containersOnThisDisk = usableSpace / containerSize;
+ effectiveAllocatableSpace += containersOnThisDisk * containerSize;
+ if (effectiveAllocatableSpace - pendingAllocationBytes >= containerSize) {
+ return true;
+ }
+ }
+ return false;
+ }
+
+ /**
+ * Drops all pending allocation state for a datanode (e.g. stale/dead cleanup).
+ */
+ public void clearPendingForDatanode(DatanodeDetails node) {
+ if (node == null) {
+ return;
+ }
+ UUID uuid = node.getUuid();
+ TwoWindowBucket bucket = datanodeBuckets.get(uuid);
+ if (bucket == null) {
+ return;
+ }
+ synchronized (bucket) {
+ datanodeBuckets.remove(uuid, bucket);
+ }
+ LOG.debug("Cleared pending container allocations for datanode {}",
+ node.getUuidString());
+ }
+
+ /**
+ * Record a pending container allocation for all DataNodes in the pipeline.
+ * Container is added to the current window.
+ *
+ * @param pipeline The pipeline where container is allocated
+ * @param containerID The container being allocated
+ */
+ public void recordPendingAllocation(Pipeline pipeline, ContainerID containerID) {
+ if (pipeline == null || containerID == null) {
+ LOG.warn("Ignoring null pipeline or containerID");
+ return;
+ }
+
+ for (DatanodeDetails node : pipeline.getNodes()) {
+ recordPendingAllocationForDatanode(node, containerID);
+ }
+ }
+
+ /**
+ * Record a pending container allocation for a single DataNode.
+ * Container is added to the current window.
+ *
+ * @param node The DataNode where container is being allocated/replicated
+ * @param containerID The container being allocated/replicated
+ */
+ public void recordPendingAllocationForDatanode(DatanodeDetails node, ContainerID containerID) {
+ if (node == null || containerID == null) {
+ LOG.warn("Ignoring null node or containerID");
+ return;
+ }
+
+ UUID uuid = node.getUuid();
+ TwoWindowBucket bucket = datanodeBuckets.computeIfAbsent(
Review Comment:
_Important lock design principle:-_
PendingContainerTracker: Please ensure `no bucket -> map` mutation path anymore. You need to switch remove/roll/clear to concurrenthashmap compute-based mutations, keep bucket internals intact.
##########
hadoop-hdds/server-scm/src/main/java/org/apache/hadoop/hdds/scm/node/PendingContainerTracker.java:
##########
@@ -0,0 +1,425 @@
+/*
+ * 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.node;
+
+import com.google.common.annotations.VisibleForTesting;
+import java.util.Collections;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Set;
+import java.util.UUID;
+import java.util.concurrent.ConcurrentHashMap;
+import org.apache.hadoop.hdds.protocol.DatanodeDetails;
+import org.apache.hadoop.hdds.protocol.proto.StorageContainerDatanodeProtocolProtos.StorageReportProto;
+import org.apache.hadoop.hdds.scm.container.ContainerID;
+import org.apache.hadoop.hdds.scm.pipeline.Pipeline;
+import org.apache.hadoop.ozone.container.common.volume.VolumeUsage;
+import org.apache.hadoop.util.Time;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * Tracks per-datanode pending container allocations at SCM using a Two Window Tumbling Bucket
+ * pattern (similar to HDFS HADOOP-3707).
+ *
+ * Two Window Tumbling Bucket for automatic aging and cleanup.
+ *
+ * How It Works:
+ * <li>Each DataNode has two sets: <b>currentWindow</b> and <b>previousWindow</b></li>
+ * <li>New allocations go into <b>currentWindow</b></li>
+ * <li>Every <b>ROLL_INTERVAL</b> (default 5 minutes):
+ * <ul>
+ * <li>previousWindow = currentWindow (shift)</li>
+ * <li>currentWindow = new empty set (reset)</li>
+ * <li>Old previousWindow is discarded (automatic aging)</li>
+ * </ul>
+ * </li>
+ * <li>When checking pending: return <b>union</b> of currentWindow + previousWindow</li>
+ *
+ *
+ * Example Timeline:
+ * <pre>
+ * Time | Action | CurrentWindow | PreviousWindow | Total Pending
+ * ------+---------------------------+---------------+----------------+--------------
+ * 00:00 | Allocate Container-1 | {C1} | {} | {C1}
+ * 00:02 | Allocate Container-2 | {C1, C2} | {} | {C1, C2}
+ * 00:05 | [ROLL] Window tumbles | {} | {C1, C2} | {C1, C2}
+ * 00:07 | Allocate Container-3 | {C3} | {C1, C2} | {C1, C2, C3}
+ * 00:08 | Report confirms C1 | {C3} | {C2} | {C2, C3}
+ * 00:10 | [ROLL] Window tumbles | {} | {C3} | {C3}
+ * | (C2 aged out if not reported)
+ * </pre>
+ *
+ * <p>Thread-safety: all mutations and reads for a given datanode run under
+ * {@code synchronized (bucket)} on that datanode's {@link TwoWindowBucket}, including
+ * map insert/remove, so concurrent record/remove/report paths cannot interleave or orphan
+ * a bucket after it was dropped from the map.</p>
+ */
+public class PendingContainerTracker {
+
+ private static final Logger LOG = LoggerFactory.getLogger(PendingContainerTracker.class);
+
+ /**
+ * Roll interval in milliseconds.
+ * Configurable via hdds.scm.container.pending.allocation.roll.interval.
+ * Default: 5 minutes.
+ * Containers automatically age out after 2 × rollIntervalMs.
+ */
+ private final long rollIntervalMs;
+
+ /**
+ * Map of DataNode UUID to TwoWindowBucket.
+ */
+ private final ConcurrentHashMap<UUID, TwoWindowBucket> datanodeBuckets;
+
+ /**
+ * Maximum container size in bytes.
+ */
+ private final long maxContainerSize;
+
+ /**
+ * Metrics for tracking pending containers (same instance as {@link SCMNodeManager}'s node metrics).
+ */
+ private final SCMNodeMetrics metrics;
+
+ /**
+ * Two-window bucket for a single DataNode.
+ * Contains current and previous window sets, plus last roll timestamp.
+ */
+ private static class TwoWindowBucket {
+ private Set<ContainerID> currentWindow = new HashSet<>();
+ private Set<ContainerID> previousWindow = new HashSet<>();
+ private long lastRollTime = Time.monotonicNow();
+ private final long rollIntervalMs;
+
+ TwoWindowBucket(long rollIntervalMs) {
+ this.rollIntervalMs = rollIntervalMs;
+ }
+
+ /**
+ * Roll the windows: previous = current, current = empty.
+ * Called when current time exceeds lastRollTime + rollIntervalMs.
+ */
+ synchronized void rollIfNeeded() {
+ long now = Time.monotonicNow();
+ if (now - lastRollTime >= rollIntervalMs) {
+ // Shift: current becomes previous
+ previousWindow = currentWindow;
+ // Reset: new empty current window
+ currentWindow = new HashSet<>();
+ lastRollTime = now;
+ LOG.debug("Rolled window. Previous window size: {}, Current window reset to empty", previousWindow.size());
+ }
+ }
+
+ /**
+ * Get union of both windows (all pending containers).
+ */
+ synchronized Set<ContainerID> getAllPending() {
+ Set<ContainerID> all = new HashSet<>();
+ all.addAll(currentWindow);
+ all.addAll(previousWindow);
+ return all;
+ }
+
+ /**
+ * Add container to current window.
+ */
+ synchronized boolean add(ContainerID containerID) {
+ return currentWindow.add(containerID);
+ }
+
+ /**
+ * Remove container from both windows.
+ */
+ synchronized boolean remove(ContainerID containerID) {
+ boolean removedFromCurrent = currentWindow.remove(containerID);
+ boolean removedFromPrevious = previousWindow.remove(containerID);
+ return removedFromCurrent || removedFromPrevious;
+ }
+
+ /**
+ * Check if either window is non-empty.
+ */
+ synchronized boolean isEmpty() {
+ return currentWindow.isEmpty() && previousWindow.isEmpty();
+ }
+
+ /**
+ * Count of pending containers in both windows.
+ */
+ synchronized int getCount() {
+ return currentWindow.size() + previousWindow.size();
+ }
+ }
+
+ public PendingContainerTracker(long maxContainerSize) {
+ this(maxContainerSize, 10 * 60 * 1000, null); // Default 10 minutes
+ }
+
+ public PendingContainerTracker(long maxContainerSize, long rollIntervalMs,
+ SCMNodeMetrics metrics) {
+ this.datanodeBuckets = new ConcurrentHashMap<>();
+ this.maxContainerSize = maxContainerSize;
+ this.rollIntervalMs = rollIntervalMs;
+ this.metrics = metrics;
+ LOG.info("PendingContainerTracker initialized with maxContainerSize={}B, rollInterval={}ms",
+ maxContainerSize, rollIntervalMs);
+ }
+
+ /**
+ * Whether the datanode can fit another container of {@code containerSize} after accounting for
+ * SCM pending allocations for {@code node} (this tracker) and usable space on {@code datanodeInfo}.
+ * Combines {@link #getPendingAllocationSize} with the per-disk slot check in one call.
+ *
+ * @param node identity used to look up pending allocations (same DN as {@code datanodeInfo})
+ * @param datanodeInfo storage reports for the datanode
+ * @param containerSize required container size in bytes (typically SCM max container size)
+ */
+ /**
+ * Advances the two-window tumbling bucket for this datanode when the roll interval has elapsed.
+ * Call on periodic paths (e.g. node report) so windows age even when there are no new
+ * allocations or container reports touching this tracker.
+ */
+ public void rollWindowsIfNeeded(DatanodeDetails node) {
+ if (node == null) {
+ return;
+ }
+ UUID uuid = node.getUuid();
Review Comment:
Please use CHM mutation, that will simplify it.
```
UUID uuid = node.getUuid();
datanodeBuckets.computeIfPresent(uuid, (k, bucket) -> {
bucket.rollIfNeeded();
return bucket.isEmpty() ? null : bucket;
});
```
_Important lock design principle:-_
PendingContainerTracker: Please ensure `no bucket -> map` mutation path anymore. You need to switch remove/roll/clear to concurrenthashmap compute-based mutations, keep bucket internals intact.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org
For additional commands, e-mail: issues-help@ozone.apache.org
Re: [PR] HDDS-14921. Improve space accounting in SCM with In-Flight container allocation tracking. [ozone]
Posted by "szetszwo (via GitHub)" <gi...@apache.org>.
szetszwo commented on code in PR #10000:
URL: https://github.com/apache/ozone/pull/10000#discussion_r3132909987
##########
hadoop-hdds/server-scm/src/main/java/org/apache/hadoop/hdds/scm/node/SCMNodeManager.java:
##########
@@ -225,6 +241,40 @@ private void unregisterMXBean() {
}
}
+ @Override
+ public PendingContainerTracker getPendingContainerTracker() {
+ return pendingContainerTracker;
+ }
+
+ /**
+ * Effective space check aligned with container allocation: per-disk slot model minus
+ * SCM pending allocations.
+ */
+ @Override
+ public boolean hasSpaceForNewContainerAllocation(DatanodeDetails node) {
+ Objects.requireNonNull(node, "node==null");
+ try {
+ DatanodeInfo datanodeInfo = getDatanodeInfo(node);
+ if (datanodeInfo == null) {
+ LOG.warn("DatanodeInfo not found for node {}", node.getUuidString());
+ return false;
+ }
+ return pendingContainerTracker.hasEffectiveAllocatableSpaceForNewContainer(
+ node, datanodeInfo);
Review Comment:
We should remove the DatanodeDetails parameter from hasEffectiveAllocatableSpaceForNewContainer(..) since datanodeInfo already has all the information.
##########
hadoop-hdds/common/src/main/java/org/apache/hadoop/hdds/scm/ScmConfig.java:
##########
@@ -138,10 +138,31 @@ public class ScmConfig extends ReconfigurableConfig {
)
private int transactionToDNsCommitMapLimit = 5000000;
+ @Config(key = "hdds.scm.container.pending.allocation.roll.interval",
Review Comment:
The other `ozone.scm.container.*` confs are in ScmConfigKeys. Let's move this new conf to ScmConfigKeys.
##########
hadoop-hdds/server-scm/src/main/java/org/apache/hadoop/hdds/scm/container/ContainerReportHandler.java:
##########
@@ -175,6 +176,17 @@ public void onMessage(final ContainerReportFromDatanode reportFromDatanode,
if (!alreadyInDn) {
// This is a new Container not in the nodeManager -> dn map yet
getNodeManager().addContainer(datanodeDetails, cid);
+
+ // Remove from pending tracker when container is added to DN
+ // This container was just confirmed for the first time on this DN
+ // No need to remove on subsequent reports (it's already been removed)
+ if (container != null) {
+ PendingContainerTracker tracker =
+ getNodeManager().getPendingContainerTracker();
+ if (tracker != null) {
Review Comment:
tracker seems never null.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org
For additional commands, e-mail: issues-help@ozone.apache.org
Re: [PR] HDDS-14921. Improve space accounting in SCM with In-Flight container allocation tracking. [ozone]
Posted by "ashishkumar50 (via GitHub)" <gi...@apache.org>.
ashishkumar50 commented on PR #10000:
URL: https://github.com/apache/ozone/pull/10000#issuecomment-4234240298
> @ashishkumar50 , thanks for working on this!
>
> This change is quite big and complicated. Let's split it into multiple subtasks. The first one could be adding the new `PendingContainerTracker` class and the related test.
>
> (Sorry for reviewing this late.)
@szetszwo Here is the first split PR https://github.com/apache/ozone/pull/10073
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org
For additional commands, e-mail: issues-help@ozone.apache.org
Re: [PR] HDDS-14921. Improve space accounting in SCM with In-Flight container allocation tracking. [ozone]
Posted by "ashishkumar50 (via GitHub)" <gi...@apache.org>.
ashishkumar50 commented on code in PR #10000:
URL: https://github.com/apache/ozone/pull/10000#discussion_r3172549299
##########
hadoop-hdds/server-scm/src/main/java/org/apache/hadoop/hdds/scm/container/ContainerManagerImpl.java:
##########
@@ -269,6 +269,7 @@ private ContainerInfo allocateContainer(final Pipeline pipeline,
}
containerStateManager.addContainer(containerInfoBuilder.build());
+ pipelineManager.recordPendingAllocation(pipeline, containerID);
Review Comment:
I have made `hasEnoughSpace` and `recordPendingAllocation` atomic and will be used during new container allocation. But still i have kept `hasEnoughSpace` and `recordPendingAllocation` methods as we need this during replication which is used by placement policy for space check. In placement policy there is no container id so it can just check for space and later record by replication manager. There is already subtask for it HDDS-14924. If there are some over allocation of container during replication it should be accepted by datanode soft and hard limit check which is being handled in https://github.com/apache/ozone/pull/10054.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org
For additional commands, e-mail: issues-help@ozone.apache.org
Re: [PR] HDDS-14921. Improve space accounting in SCM with In-Flight container allocation tracking. [ozone]
Posted by "ashishkumar50 (via GitHub)" <gi...@apache.org>.
ashishkumar50 merged PR #10000:
URL: https://github.com/apache/ozone/pull/10000
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org
For additional commands, e-mail: issues-help@ozone.apache.org
Re: [PR] HDDS-14921. Improve space accounting in SCM with In-Flight container allocation tracking. [ozone]
Posted by "szetszwo (via GitHub)" <gi...@apache.org>.
szetszwo commented on code in PR #10000:
URL: https://github.com/apache/ozone/pull/10000#discussion_r3186869795
##########
hadoop-hdds/server-scm/src/main/java/org/apache/hadoop/hdds/scm/node/PendingContainerTracker.java:
##########
@@ -189,6 +190,47 @@ public boolean hasEffectiveAllocatableSpaceForNewContainer(DatanodeInfo datanode
return false;
}
+ /**
+ * Atomically checks if the datanode has space for a new container and records the allocation
+ * if space is available. This prevents race conditions where multiple threads check space
+ * concurrently and over-allocate.
+ *
+ * @param datanodeInfo storage reports for the datanode
+ * @param containerID The container being allocated
+ * @return true if space was available and allocation was recorded, false otherwise
+ */
+ public boolean checkSpaceAndRecordAllocation(DatanodeInfo datanodeInfo, ContainerID containerID) {
+ Objects.requireNonNull(datanodeInfo, "datanodeInfo == null");
+ Objects.requireNonNull(containerID, "containerID == null");
+
+ TwoWindowBucket bucket = datanodeInfo.getPendingContainerAllocations();
+ synchronized (bucket) {
Review Comment:
We should not synchronized local variables; see
<img width="830" height="296" alt="image" src="https://github.com/user-attachments/assets/6b481856-fdeb-406d-b2e8-a68e5f44f83a" />
Move the code to TwoWindowBucket.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org
For additional commands, e-mail: issues-help@ozone.apache.org
Re: [PR] HDDS-14921. Improve space accounting in SCM with In-Flight container allocation tracking. [ozone]
Posted by "sumitagrawl (via GitHub)" <gi...@apache.org>.
sumitagrawl commented on code in PR #10000:
URL: https://github.com/apache/ozone/pull/10000#discussion_r3021666985
##########
hadoop-hdds/common/src/main/java/org/apache/hadoop/hdds/scm/ScmConfig.java:
##########
@@ -138,10 +138,31 @@ public class ScmConfig extends ReconfigurableConfig {
)
private int transactionToDNsCommitMapLimit = 5000000;
+ @Config(key = "hdds.scm.container.pending-allocation.roll-interval",
Review Comment:
we can have config as hdds.scm.container.pending.allocation.roll.interval
##########
hadoop-hdds/server-scm/src/main/java/org/apache/hadoop/hdds/scm/container/IncrementalContainerReportHandler.java:
##########
@@ -89,6 +89,15 @@ protected void processICR(IncrementalContainerReportFromDatanode report,
ContainerID id = ContainerID.valueOf(replicaProto.getContainerID());
final ContainerInfo container;
try {
+ // Check if container is already known to this DN before adding
+ boolean alreadyOnDn = false;
Review Comment:
Do we really need check if container exist? or just remove if exist as single call ?
##########
hadoop-hdds/server-scm/src/main/java/org/apache/hadoop/hdds/scm/container/PendingContainerTracker.java:
##########
@@ -0,0 +1,338 @@
+/*
+ * 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;
+
+import com.google.common.annotations.VisibleForTesting;
+import java.util.Collections;
+import java.util.HashSet;
+import java.util.Set;
+import java.util.UUID;
+import java.util.concurrent.ConcurrentHashMap;
+import org.apache.hadoop.hdds.protocol.DatanodeDetails;
+import org.apache.hadoop.hdds.scm.container.metrics.SCMContainerManagerMetrics;
+import org.apache.hadoop.hdds.scm.pipeline.Pipeline;
+import org.apache.hadoop.util.Time;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * Tracks pending container allocations using a Two Window Tumbling Bucket pattern.
+ * Similar like HDFS HADOOP-3707.
+ *
+ * Two Window Tumbling Bucket for automatic aging and cleanup.
+ *
+ * How It Works:
+ * <li>Each DataNode has two sets: <b>currentWindow</b> and <b>previousWindow</b></li>
+ * <li>New allocations go into <b>currentWindow</b></li>
+ * <li>Every <b>ROLL_INTERVAL</b> (default 10 minutes):
+ * <ul>
+ * <li>previousWindow = currentWindow (shift)</li>
+ * <li>currentWindow = new empty set (reset)</li>
+ * <li>Old previousWindow is discarded (automatic aging)</li>
+ * </ul>
+ * </li>
+ * <li>When checking pending: return <b>union</b> of currentWindow + previousWindow</li>
+ *
+ *
+ * Example Timeline:
+ * <pre>
+ * Time | Action | CurrentWindow | PreviousWindow | Total Pending
+ * ------+---------------------------+---------------+----------------+--------------
+ * 00:00 | Allocate Container-1 | {C1} | {} | {C1}
+ * 00:05 | Allocate Container-2 | {C1, C2} | {} | {C1, C2}
+ * 00:10 | [ROLL] Window tumbles | {} | {C1, C2} | {C1, C2}
+ * 00:12 | Allocate Container-3 | {C3} | {C1, C2} | {C1, C2, C3}
+ * 00:15 | Report confirms C1 | {C3} | {C2} | {C2, C3}
+ * 00:20 | [ROLL] Window tumbles | {} | {C3} | {C3}
+ * | (C2 aged out if not reported)
+ * </pre>
+ *
+ */
+public class PendingContainerTracker {
+
+ private static final Logger LOG = LoggerFactory.getLogger(PendingContainerTracker.class);
+
+ /**
+ * Roll interval in milliseconds.
+ * Configurable via hdds.scm.container.pending-allocation.roll-interval.
+ * Default: 10 minutes.
+ * Containers automatically age out after 2 × rollIntervalMs.
+ */
+ private final long rollIntervalMs;
+
+ /**
+ * Map of DataNode UUID to TwoWindowBucket.
+ */
+ private final ConcurrentHashMap<UUID, TwoWindowBucket> datanodeBuckets;
+
+ /**
+ * Maximum container size in bytes.
+ */
+ private final long maxContainerSize;
+
+ /**
+ * Metrics for tracking pending containers.
+ */
+ private final SCMContainerManagerMetrics metrics;
+
+ /**
+ * Two-window bucket for a single DataNode.
+ * Contains current and previous window sets, plus last roll timestamp.
+ */
+ private static class TwoWindowBucket {
+ private Set<ContainerID> currentWindow = ConcurrentHashMap.newKeySet();
+ private Set<ContainerID> previousWindow = ConcurrentHashMap.newKeySet();
+ private long lastRollTime = Time.monotonicNow();
+ private final long rollIntervalMs;
+
+ TwoWindowBucket(long rollIntervalMs) {
+ this.rollIntervalMs = rollIntervalMs;
+ }
+
+ /**
+ * Roll the windows: previous = current, current = empty.
+ * Called when current time exceeds lastRollTime + rollIntervalMs.
+ */
+ synchronized void rollIfNeeded() {
+ long now = Time.monotonicNow();
+ if (now - lastRollTime >= rollIntervalMs) {
+ // Shift: current becomes previous
+ previousWindow = currentWindow;
+ // Reset: new empty current window
+ currentWindow = ConcurrentHashMap.newKeySet();
+ lastRollTime = now;
+ LOG.debug("Rolled window. Previous window size: {}, Current window reset to empty", previousWindow.size());
+ }
+ }
+
+ /**
+ * Get union of both windows (all pending containers).
+ */
+ synchronized Set<ContainerID> getAllPending() {
+ Set<ContainerID> all = new HashSet<>();
+ all.addAll(currentWindow);
+ all.addAll(previousWindow);
+ return all;
+ }
+
+ /**
+ * Add container to current window.
+ */
+ synchronized boolean add(ContainerID containerID) {
+ return currentWindow.add(containerID);
+ }
+
+ /**
+ * Remove container from both windows.
+ */
+ synchronized boolean remove(ContainerID containerID) {
+ boolean removedFromCurrent = currentWindow.remove(containerID);
+ boolean removedFromPrevious = previousWindow.remove(containerID);
+ return removedFromCurrent || removedFromPrevious;
+ }
+
+ /**
+ * Check if either window is non-empty.
+ */
+ synchronized boolean isEmpty() {
+ return currentWindow.isEmpty() && previousWindow.isEmpty();
+ }
+
+ /**
+ * Get count of all pending containers (union).
+ */
+ synchronized int getCount() {
+ return getAllPending().size();
+ }
+ }
+
+ public PendingContainerTracker(long maxContainerSize) {
+ this(maxContainerSize, 10 * 60 * 1000, null); // Default 10 minutes
+ }
+
+ public PendingContainerTracker(long maxContainerSize, long rollIntervalMs,
+ SCMContainerManagerMetrics metrics) {
+ this.datanodeBuckets = new ConcurrentHashMap<>();
+ this.maxContainerSize = maxContainerSize;
+ this.rollIntervalMs = rollIntervalMs;
+ this.metrics = metrics;
+ LOG.info("PendingContainerTracker initialized with maxContainerSize={}B, rollInterval={}ms",
+ maxContainerSize, rollIntervalMs);
+ }
+
+ /**
+ * Record a pending container allocation for all DataNodes in the pipeline.
+ * Container is added to the current window.
+ *
+ * @param pipeline The pipeline where container is allocated
+ * @param containerID The container being allocated
+ */
+ public void recordPendingAllocation(Pipeline pipeline, ContainerID containerID) {
Review Comment:
This needs to be part of SCMNodeManager, more specific to SCMNodeStat. Reason,
1. need handle even like stale node / dead node handler as cleanup
2. May need report this when reporting to CLI for available space in the DN
3. To be used for pipeline allocation policy, where container manager does not come in role
Its datanode space, just trying to identify already allocated space. And needs to be part of committed space at SCM when reporting to CLI, or other breakup.
##########
hadoop-hdds/server-scm/src/main/java/org/apache/hadoop/hdds/scm/container/ContainerManagerImpl.java:
##########
@@ -242,12 +262,75 @@ private ContainerInfo createContainer(Pipeline pipeline, String owner)
return containerInfo;
}
+ /**
+ * Check if a pipeline has sufficient space after considering pending allocations.
+ * Tracks containers scheduled but not yet written to DataNodes, preventing over-allocation.
+ *
+ * @param pipeline The pipeline to check
+ * @return true if sufficient space is available, false otherwise
+ */
+ private boolean hasSpaceAfterPendingAllocations(Pipeline pipeline) {
+ try {
+ for (DatanodeDetails node : pipeline.getNodes()) {
+ // Get DN's storage statistics
+ DatanodeInfo datanodeInfo = pipelineManager.getDatanodeInfo(node);
+ if (datanodeInfo == null) {
+ LOG.warn("DatanodeInfo not found for node {}", node.getUuidString());
+ return false;
+ }
+
+ List<StorageReportProto> storageReports = datanodeInfo.getStorageReports();
+ if (storageReports == null || storageReports.isEmpty()) {
+ LOG.warn("No storage reports for node {}", node.getUuidString());
+ return false;
+ }
+
+ // Calculate total capacity and effective allocatable space
+ // For each disk, calculate how many containers can actually fit,
+ // since containers are written to individual disks, not spread across them.
+ // Example: disk1=9GB, disk2=14GB with 5GB containers
+ // (1*5GB) + (2*5GB) = 15GB → actually 3 containers
+ long totalCapacity = 0L;
+ long effectiveAllocatableSpace = 0L;
+ for (StorageReportProto report : storageReports) {
Review Comment:
Instead of calcuating all available and then removing, we can do progressive base, like,
required=pending+newAllocation
for each report
required = required - volumeUsage in roundoff value
if (required <= 0)
return true
But we need to reserve also, can do first add and check, if not present, remove containerId
OR other way,
when DN report storage handling, total consolidate value can also be added to memory to avoid looping on every call.
##########
hadoop-hdds/server-scm/src/main/java/org/apache/hadoop/hdds/scm/container/IncrementalContainerReportHandler.java:
##########
@@ -103,6 +112,13 @@ protected void processICR(IncrementalContainerReportFromDatanode report,
}
if (ContainerReportValidator.validate(container, dd, replicaProto)) {
processContainerReplica(dd, container, replicaProto, publisher, detailsForLogging);
+
+ // Remove from pending tracker when container is added to DN
+ if (!alreadyOnDn && getContainerManager() instanceof ContainerManagerImpl) {
Review Comment:
Please check if node report is also send in ICR, this is for reason that node information should be updated with ICR at same time.
##########
hadoop-hdds/server-scm/src/main/java/org/apache/hadoop/hdds/scm/container/PendingContainerTracker.java:
##########
@@ -0,0 +1,338 @@
+/*
+ * 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;
+
+import com.google.common.annotations.VisibleForTesting;
+import java.util.Collections;
+import java.util.HashSet;
+import java.util.Set;
+import java.util.UUID;
+import java.util.concurrent.ConcurrentHashMap;
+import org.apache.hadoop.hdds.protocol.DatanodeDetails;
+import org.apache.hadoop.hdds.scm.container.metrics.SCMContainerManagerMetrics;
+import org.apache.hadoop.hdds.scm.pipeline.Pipeline;
+import org.apache.hadoop.util.Time;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * Tracks pending container allocations using a Two Window Tumbling Bucket pattern.
+ * Similar like HDFS HADOOP-3707.
+ *
+ * Two Window Tumbling Bucket for automatic aging and cleanup.
+ *
+ * How It Works:
+ * <li>Each DataNode has two sets: <b>currentWindow</b> and <b>previousWindow</b></li>
+ * <li>New allocations go into <b>currentWindow</b></li>
+ * <li>Every <b>ROLL_INTERVAL</b> (default 10 minutes):
+ * <ul>
+ * <li>previousWindow = currentWindow (shift)</li>
+ * <li>currentWindow = new empty set (reset)</li>
+ * <li>Old previousWindow is discarded (automatic aging)</li>
+ * </ul>
+ * </li>
+ * <li>When checking pending: return <b>union</b> of currentWindow + previousWindow</li>
+ *
+ *
+ * Example Timeline:
+ * <pre>
+ * Time | Action | CurrentWindow | PreviousWindow | Total Pending
+ * ------+---------------------------+---------------+----------------+--------------
+ * 00:00 | Allocate Container-1 | {C1} | {} | {C1}
+ * 00:05 | Allocate Container-2 | {C1, C2} | {} | {C1, C2}
+ * 00:10 | [ROLL] Window tumbles | {} | {C1, C2} | {C1, C2}
+ * 00:12 | Allocate Container-3 | {C3} | {C1, C2} | {C1, C2, C3}
+ * 00:15 | Report confirms C1 | {C3} | {C2} | {C2, C3}
+ * 00:20 | [ROLL] Window tumbles | {} | {C3} | {C3}
+ * | (C2 aged out if not reported)
+ * </pre>
+ *
+ */
+public class PendingContainerTracker {
+
+ private static final Logger LOG = LoggerFactory.getLogger(PendingContainerTracker.class);
+
+ /**
+ * Roll interval in milliseconds.
+ * Configurable via hdds.scm.container.pending-allocation.roll-interval.
+ * Default: 10 minutes.
+ * Containers automatically age out after 2 × rollIntervalMs.
+ */
+ private final long rollIntervalMs;
+
+ /**
+ * Map of DataNode UUID to TwoWindowBucket.
+ */
+ private final ConcurrentHashMap<UUID, TwoWindowBucket> datanodeBuckets;
+
+ /**
+ * Maximum container size in bytes.
+ */
+ private final long maxContainerSize;
+
+ /**
+ * Metrics for tracking pending containers.
+ */
+ private final SCMContainerManagerMetrics metrics;
+
+ /**
+ * Two-window bucket for a single DataNode.
+ * Contains current and previous window sets, plus last roll timestamp.
+ */
+ private static class TwoWindowBucket {
+ private Set<ContainerID> currentWindow = ConcurrentHashMap.newKeySet();
+ private Set<ContainerID> previousWindow = ConcurrentHashMap.newKeySet();
+ private long lastRollTime = Time.monotonicNow();
+ private final long rollIntervalMs;
+
+ TwoWindowBucket(long rollIntervalMs) {
+ this.rollIntervalMs = rollIntervalMs;
+ }
+
+ /**
+ * Roll the windows: previous = current, current = empty.
+ * Called when current time exceeds lastRollTime + rollIntervalMs.
+ */
+ synchronized void rollIfNeeded() {
+ long now = Time.monotonicNow();
+ if (now - lastRollTime >= rollIntervalMs) {
+ // Shift: current becomes previous
+ previousWindow = currentWindow;
+ // Reset: new empty current window
+ currentWindow = ConcurrentHashMap.newKeySet();
+ lastRollTime = now;
+ LOG.debug("Rolled window. Previous window size: {}, Current window reset to empty", previousWindow.size());
+ }
+ }
+
+ /**
+ * Get union of both windows (all pending containers).
+ */
+ synchronized Set<ContainerID> getAllPending() {
+ Set<ContainerID> all = new HashSet<>();
+ all.addAll(currentWindow);
+ all.addAll(previousWindow);
+ return all;
+ }
+
+ /**
+ * Add container to current window.
+ */
+ synchronized boolean add(ContainerID containerID) {
+ return currentWindow.add(containerID);
+ }
+
+ /**
+ * Remove container from both windows.
+ */
+ synchronized boolean remove(ContainerID containerID) {
+ boolean removedFromCurrent = currentWindow.remove(containerID);
+ boolean removedFromPrevious = previousWindow.remove(containerID);
+ return removedFromCurrent || removedFromPrevious;
+ }
+
+ /**
+ * Check if either window is non-empty.
+ */
+ synchronized boolean isEmpty() {
+ return currentWindow.isEmpty() && previousWindow.isEmpty();
+ }
+
+ /**
+ * Get count of all pending containers (union).
+ */
+ synchronized int getCount() {
+ return getAllPending().size();
+ }
+ }
+
+ public PendingContainerTracker(long maxContainerSize) {
+ this(maxContainerSize, 10 * 60 * 1000, null); // Default 10 minutes
+ }
+
+ public PendingContainerTracker(long maxContainerSize, long rollIntervalMs,
+ SCMContainerManagerMetrics metrics) {
+ this.datanodeBuckets = new ConcurrentHashMap<>();
+ this.maxContainerSize = maxContainerSize;
+ this.rollIntervalMs = rollIntervalMs;
+ this.metrics = metrics;
+ LOG.info("PendingContainerTracker initialized with maxContainerSize={}B, rollInterval={}ms",
+ maxContainerSize, rollIntervalMs);
+ }
+
+ /**
+ * Record a pending container allocation for all DataNodes in the pipeline.
+ * Container is added to the current window.
+ *
+ * @param pipeline The pipeline where container is allocated
+ * @param containerID The container being allocated
+ */
+ public void recordPendingAllocation(Pipeline pipeline, ContainerID containerID) {
+ if (pipeline == null || containerID == null) {
+ LOG.warn("Ignoring null pipeline or containerID");
+ return;
+ }
+
+ for (DatanodeDetails node : pipeline.getNodes()) {
+ recordPendingAllocationForDatanode(node, containerID);
+ }
+ }
+
+ /**
+ * Record a pending container allocation for a single DataNode.
+ * Container is added to the current window.
+ *
+ * @param node The DataNode where container is being allocated/replicated
+ * @param containerID The container being allocated/replicated
+ */
+ public void recordPendingAllocationForDatanode(DatanodeDetails node, ContainerID containerID) {
+ if (node == null || containerID == null) {
+ LOG.warn("Ignoring null node or containerID");
+ return;
+ }
+
+ TwoWindowBucket bucket = datanodeBuckets.computeIfAbsent(
+ node.getUuid(),
+ k -> new TwoWindowBucket(rollIntervalMs)
+ );
+
+ // Roll window if needed before adding
+ bucket.rollIfNeeded();
+
+ boolean added = bucket.add(containerID);
+ LOG.info("Recorded pending container {} on DataNode {}. Added={}, Total pending={}",
+ containerID, node.getUuidString(), added, bucket.getCount());
+
+ // Increment metrics counter
+ if (added && metrics != null) {
+ metrics.incNumPendingContainersAdded();
+ }
+ }
+
+ /**
+ * Remove a pending container allocation from a specific DataNode.
+ * Removes from both current and previous windows.
+ * Called when container is confirmed.
+ *
+ * @param node The DataNode
+ * @param containerID The container to remove from pending
+ */
+ public void removePendingAllocation(DatanodeDetails node, ContainerID containerID) {
+ if (node == null || containerID == null) {
+ return;
+ }
+
+ TwoWindowBucket bucket = datanodeBuckets.get(node.getUuid());
+ if (bucket != null) {
+ // Roll window if needed before removing
+ bucket.rollIfNeeded();
+
+ boolean removed = bucket.remove(containerID);
+ LOG.info("Removed pending container {} from DataNode {}. Removed={}, Remaining={}",
+ containerID, node.getUuidString(), removed, bucket.getCount());
+
+ // Increment metrics counter
+ if (removed && metrics != null) {
+ metrics.incNumPendingContainersRemoved();
+ }
+
+ // Cleanup empty buckets to prevent memory leak
+ if (bucket.isEmpty()) {
+ LOG.info("Cleanup pending bucket");
+ datanodeBuckets.remove(node.getUuid(), bucket);
+ }
+ }
+ }
+
+ /**
+ * Get the total size of pending allocations on a DataNode.
+ * Returns union of current and previous windows.
+ *
+ * @param node The DataNode
+ * @return Total bytes of pending container allocations
+ */
+ public long getPendingAllocationSize(DatanodeDetails node) {
+ if (node == null) {
+ return 0;
+ }
+
+ TwoWindowBucket bucket = datanodeBuckets.get(node.getUuid());
+ LOG.info("Get pending from DataNode {}",
+ node.getUuidString());
+ if (bucket == null) {
+ LOG.info("Get pending from DataNode {} is null",
+ node.getUuidString());
+ return 0;
+ }
+
+ // Roll window if needed before querying
+ bucket.rollIfNeeded();
+
+ // Each pending container assumes max size
+ return (long) bucket.getCount() * maxContainerSize;
Review Comment:
This is costly operation as first it combine 2 list, and then it performs count.
##########
hadoop-hdds/server-scm/src/main/java/org/apache/hadoop/hdds/scm/container/PendingContainerTracker.java:
##########
@@ -0,0 +1,338 @@
+/*
+ * 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;
+
+import com.google.common.annotations.VisibleForTesting;
+import java.util.Collections;
+import java.util.HashSet;
+import java.util.Set;
+import java.util.UUID;
+import java.util.concurrent.ConcurrentHashMap;
+import org.apache.hadoop.hdds.protocol.DatanodeDetails;
+import org.apache.hadoop.hdds.scm.container.metrics.SCMContainerManagerMetrics;
+import org.apache.hadoop.hdds.scm.pipeline.Pipeline;
+import org.apache.hadoop.util.Time;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * Tracks pending container allocations using a Two Window Tumbling Bucket pattern.
+ * Similar like HDFS HADOOP-3707.
+ *
+ * Two Window Tumbling Bucket for automatic aging and cleanup.
+ *
+ * How It Works:
+ * <li>Each DataNode has two sets: <b>currentWindow</b> and <b>previousWindow</b></li>
+ * <li>New allocations go into <b>currentWindow</b></li>
+ * <li>Every <b>ROLL_INTERVAL</b> (default 10 minutes):
+ * <ul>
+ * <li>previousWindow = currentWindow (shift)</li>
+ * <li>currentWindow = new empty set (reset)</li>
+ * <li>Old previousWindow is discarded (automatic aging)</li>
+ * </ul>
+ * </li>
+ * <li>When checking pending: return <b>union</b> of currentWindow + previousWindow</li>
+ *
+ *
+ * Example Timeline:
+ * <pre>
+ * Time | Action | CurrentWindow | PreviousWindow | Total Pending
+ * ------+---------------------------+---------------+----------------+--------------
+ * 00:00 | Allocate Container-1 | {C1} | {} | {C1}
+ * 00:05 | Allocate Container-2 | {C1, C2} | {} | {C1, C2}
+ * 00:10 | [ROLL] Window tumbles | {} | {C1, C2} | {C1, C2}
+ * 00:12 | Allocate Container-3 | {C3} | {C1, C2} | {C1, C2, C3}
+ * 00:15 | Report confirms C1 | {C3} | {C2} | {C2, C3}
+ * 00:20 | [ROLL] Window tumbles | {} | {C3} | {C3}
+ * | (C2 aged out if not reported)
+ * </pre>
+ *
+ */
+public class PendingContainerTracker {
+
+ private static final Logger LOG = LoggerFactory.getLogger(PendingContainerTracker.class);
+
+ /**
+ * Roll interval in milliseconds.
+ * Configurable via hdds.scm.container.pending-allocation.roll-interval.
+ * Default: 10 minutes.
+ * Containers automatically age out after 2 × rollIntervalMs.
+ */
+ private final long rollIntervalMs;
+
+ /**
+ * Map of DataNode UUID to TwoWindowBucket.
+ */
+ private final ConcurrentHashMap<UUID, TwoWindowBucket> datanodeBuckets;
+
+ /**
+ * Maximum container size in bytes.
+ */
+ private final long maxContainerSize;
+
+ /**
+ * Metrics for tracking pending containers.
+ */
+ private final SCMContainerManagerMetrics metrics;
+
+ /**
+ * Two-window bucket for a single DataNode.
+ * Contains current and previous window sets, plus last roll timestamp.
+ */
+ private static class TwoWindowBucket {
+ private Set<ContainerID> currentWindow = ConcurrentHashMap.newKeySet();
Review Comment:
if we use synchronized in all methods, then set need not be threadsafe.
##########
hadoop-hdds/server-scm/src/main/java/org/apache/hadoop/hdds/scm/container/ContainerReportHandler.java:
##########
@@ -175,6 +175,15 @@ public void onMessage(final ContainerReportFromDatanode reportFromDatanode,
if (!alreadyInDn) {
// This is a new Container not in the nodeManager -> dn map yet
getNodeManager().addContainer(datanodeDetails, cid);
+
+ // Remove from pending tracker when container is added to DN
+ // This container was just confirmed for the first time on this DN
+ // No need to remove on subsequent reports (it's already been removed)
+ if (container != null && getContainerManager() instanceof ContainerManagerImpl) {
Review Comment:
code handling different from ICR and FCR, can be same only.
##########
hadoop-hdds/common/src/main/java/org/apache/hadoop/hdds/scm/ScmConfig.java:
##########
@@ -138,10 +138,31 @@ public class ScmConfig extends ReconfigurableConfig {
)
private int transactionToDNsCommitMapLimit = 5000000;
+ @Config(key = "hdds.scm.container.pending-allocation.roll-interval",
+ defaultValue = "10m",
+ type = ConfigType.TIME,
+ tags = { ConfigTag.SCM, ConfigTag.CONTAINER },
+ description =
+ "Time interval for rolling the pending container allocation window. " +
+ "Pending container allocations are tracked in a two-window tumbling bucket " +
+ "pattern. Each window has this duration. " +
+ "After 2x this interval, allocations that haven't been confirmed via " +
+ "container reports will automatically age out. Default is 10 minutes."
+ )
+ private Duration pendingContainerAllocationRollInterval = Duration.ofMinutes(10);
Review Comment:
rolling period is 5 min or 10 min ? mean previous bucket to be there for additional 5 min to capture containerList IN-Progress
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org
For additional commands, e-mail: issues-help@ozone.apache.org
Re: [PR] HDDS-14921. Improve space accounting in SCM with In-Flight container allocation tracking. [ozone]
Posted by "aswinshakil (via GitHub)" <gi...@apache.org>.
aswinshakil commented on code in PR #10000:
URL: https://github.com/apache/ozone/pull/10000#discussion_r3030331856
##########
hadoop-hdds/server-scm/src/main/java/org/apache/hadoop/hdds/scm/container/ContainerManagerImpl.java:
##########
@@ -242,12 +262,75 @@ private ContainerInfo createContainer(Pipeline pipeline, String owner)
return containerInfo;
}
+ /**
+ * Check if a pipeline has sufficient space after considering pending allocations.
+ * Tracks containers scheduled but not yet written to DataNodes, preventing over-allocation.
+ *
+ * @param pipeline The pipeline to check
+ * @return true if sufficient space is available, false otherwise
+ */
+ private boolean hasSpaceAfterPendingAllocations(Pipeline pipeline) {
+ try {
+ for (DatanodeDetails node : pipeline.getNodes()) {
+ // Get DN's storage statistics
+ DatanodeInfo datanodeInfo = pipelineManager.getDatanodeInfo(node);
+ if (datanodeInfo == null) {
+ LOG.warn("DatanodeInfo not found for node {}", node.getUuidString());
+ return false;
+ }
+
+ List<StorageReportProto> storageReports = datanodeInfo.getStorageReports();
+ if (storageReports == null || storageReports.isEmpty()) {
+ LOG.warn("No storage reports for node {}", node.getUuidString());
+ return false;
+ }
+
+ // Calculate total capacity and effective allocatable space
+ // For each disk, calculate how many containers can actually fit,
+ // since containers are written to individual disks, not spread across them.
+ // Example: disk1=9GB, disk2=14GB with 5GB containers
+ // (1*5GB) + (2*5GB) = 15GB → actually 3 containers
+ long totalCapacity = 0L;
+ long effectiveAllocatableSpace = 0L;
+ for (StorageReportProto report : storageReports) {
+ totalCapacity += report.getCapacity();
+ long usableSpace = VolumeUsage.getUsableSpace(report);
+ // Calculate how many containers can fit on this disk
+ long containersOnThisDisk = usableSpace / maxContainerSize;
+ // Add effective space (containers that fit * container size)
+ effectiveAllocatableSpace += containersOnThisDisk * maxContainerSize;
+ }
+
+ // Get pending allocations from tracker
+ long pendingAllocations = pendingContainerTracker.getPendingAllocationSize(node);
+
+ // Calculate effective remaining space after pending allocations
+ long effectiveRemaining = effectiveAllocatableSpace - pendingAllocations;
+
+ // Check if there's enough space for a new container
+ if (effectiveRemaining < maxContainerSize) {
+ LOG.info("Node {} insufficient space: capacity={}, effective allocatable={}, " +
+ "pending allocations={}, effective remaining={}, required={}",
+ node.getUuidString(), totalCapacity, effectiveAllocatableSpace,
+ pendingAllocations, effectiveRemaining, maxContainerSize);
+ return false;
+ }
+ }
+
+ return true;
+ } catch (Exception e) {
+ LOG.warn("Error checking space for pipeline {}", pipeline.getId(), e);
+ return true;
Review Comment:
If we are not sure if we can create container here, Should we still choose this pipeline? Instead of making it generic, we can specify what to do for each exception we might see.
##########
hadoop-hdds/server-scm/src/main/java/org/apache/hadoop/hdds/scm/container/PendingContainerTracker.java:
##########
@@ -0,0 +1,338 @@
+/*
+ * 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;
+
+import com.google.common.annotations.VisibleForTesting;
+import java.util.Collections;
+import java.util.HashSet;
+import java.util.Set;
+import java.util.UUID;
+import java.util.concurrent.ConcurrentHashMap;
+import org.apache.hadoop.hdds.protocol.DatanodeDetails;
+import org.apache.hadoop.hdds.scm.container.metrics.SCMContainerManagerMetrics;
+import org.apache.hadoop.hdds.scm.pipeline.Pipeline;
+import org.apache.hadoop.util.Time;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * Tracks pending container allocations using a Two Window Tumbling Bucket pattern.
+ * Similar like HDFS HADOOP-3707.
+ *
+ * Two Window Tumbling Bucket for automatic aging and cleanup.
+ *
+ * How It Works:
+ * <li>Each DataNode has two sets: <b>currentWindow</b> and <b>previousWindow</b></li>
+ * <li>New allocations go into <b>currentWindow</b></li>
+ * <li>Every <b>ROLL_INTERVAL</b> (default 10 minutes):
+ * <ul>
+ * <li>previousWindow = currentWindow (shift)</li>
+ * <li>currentWindow = new empty set (reset)</li>
+ * <li>Old previousWindow is discarded (automatic aging)</li>
+ * </ul>
+ * </li>
+ * <li>When checking pending: return <b>union</b> of currentWindow + previousWindow</li>
+ *
+ *
+ * Example Timeline:
+ * <pre>
+ * Time | Action | CurrentWindow | PreviousWindow | Total Pending
+ * ------+---------------------------+---------------+----------------+--------------
+ * 00:00 | Allocate Container-1 | {C1} | {} | {C1}
+ * 00:05 | Allocate Container-2 | {C1, C2} | {} | {C1, C2}
+ * 00:10 | [ROLL] Window tumbles | {} | {C1, C2} | {C1, C2}
+ * 00:12 | Allocate Container-3 | {C3} | {C1, C2} | {C1, C2, C3}
+ * 00:15 | Report confirms C1 | {C3} | {C2} | {C2, C3}
+ * 00:20 | [ROLL] Window tumbles | {} | {C3} | {C3}
+ * | (C2 aged out if not reported)
+ * </pre>
+ *
+ */
+public class PendingContainerTracker {
+
+ private static final Logger LOG = LoggerFactory.getLogger(PendingContainerTracker.class);
+
+ /**
+ * Roll interval in milliseconds.
+ * Configurable via hdds.scm.container.pending-allocation.roll-interval.
+ * Default: 10 minutes.
+ * Containers automatically age out after 2 × rollIntervalMs.
+ */
+ private final long rollIntervalMs;
+
+ /**
+ * Map of DataNode UUID to TwoWindowBucket.
+ */
+ private final ConcurrentHashMap<UUID, TwoWindowBucket> datanodeBuckets;
+
+ /**
+ * Maximum container size in bytes.
+ */
+ private final long maxContainerSize;
+
+ /**
+ * Metrics for tracking pending containers.
+ */
+ private final SCMContainerManagerMetrics metrics;
+
+ /**
+ * Two-window bucket for a single DataNode.
+ * Contains current and previous window sets, plus last roll timestamp.
+ */
+ private static class TwoWindowBucket {
+ private Set<ContainerID> currentWindow = ConcurrentHashMap.newKeySet();
+ private Set<ContainerID> previousWindow = ConcurrentHashMap.newKeySet();
+ private long lastRollTime = Time.monotonicNow();
+ private final long rollIntervalMs;
+
+ TwoWindowBucket(long rollIntervalMs) {
+ this.rollIntervalMs = rollIntervalMs;
+ }
+
+ /**
+ * Roll the windows: previous = current, current = empty.
+ * Called when current time exceeds lastRollTime + rollIntervalMs.
+ */
+ synchronized void rollIfNeeded() {
Review Comment:
Pending allocations can persist beyond 2× roll interval after long idle periods because `rollIfNeeded()` only rolls once.A single roll doesn’t clear entries older than two windows which can incorrectly block new allocations.
##########
hadoop-hdds/server-scm/src/main/java/org/apache/hadoop/hdds/scm/container/ContainerReportHandler.java:
##########
@@ -175,6 +175,15 @@ public void onMessage(final ContainerReportFromDatanode reportFromDatanode,
if (!alreadyInDn) {
// This is a new Container not in the nodeManager -> dn map yet
getNodeManager().addContainer(datanodeDetails, cid);
+
+ // Remove from pending tracker when container is added to DN
+ // This container was just confirmed for the first time on this DN
+ // No need to remove on subsequent reports (it's already been removed)
+ if (container != null && getContainerManager() instanceof ContainerManagerImpl) {
Review Comment:
Why not just add this to the ContainerManager interface? We can avoid these conversions. Is this because Recon uses the same code path and we don't want it to this? For Recon we can just make it a No-Op.
##########
hadoop-hdds/server-scm/src/test/java/org/apache/hadoop/hdds/scm/pipeline/MockPipelineManager.java:
##########
@@ -346,4 +346,9 @@ public int openContainerLimit(List<DatanodeDetails> datanodes) {
public SCMPipelineMetrics getMetrics() {
return null;
}
+
+ @Override
+ public org.apache.hadoop.hdds.scm.node.DatanodeInfo getDatanodeInfo(DatanodeDetails datanodeDetails) {
Review Comment:
Nit: We can import `DatanodeInfo`
##########
hadoop-hdds/server-scm/src/main/java/org/apache/hadoop/hdds/scm/container/ContainerManagerImpl.java:
##########
@@ -242,12 +262,75 @@ private ContainerInfo createContainer(Pipeline pipeline, String owner)
return containerInfo;
}
+ /**
+ * Check if a pipeline has sufficient space after considering pending allocations.
+ * Tracks containers scheduled but not yet written to DataNodes, preventing over-allocation.
+ *
+ * @param pipeline The pipeline to check
+ * @return true if sufficient space is available, false otherwise
+ */
+ private boolean hasSpaceAfterPendingAllocations(Pipeline pipeline) {
+ try {
+ for (DatanodeDetails node : pipeline.getNodes()) {
+ // Get DN's storage statistics
+ DatanodeInfo datanodeInfo = pipelineManager.getDatanodeInfo(node);
+ if (datanodeInfo == null) {
+ LOG.warn("DatanodeInfo not found for node {}", node.getUuidString());
+ return false;
+ }
+
+ List<StorageReportProto> storageReports = datanodeInfo.getStorageReports();
+ if (storageReports == null || storageReports.isEmpty()) {
+ LOG.warn("No storage reports for node {}", node.getUuidString());
+ return false;
+ }
+
+ // Calculate total capacity and effective allocatable space
+ // For each disk, calculate how many containers can actually fit,
+ // since containers are written to individual disks, not spread across them.
+ // Example: disk1=9GB, disk2=14GB with 5GB containers
+ // (1*5GB) + (2*5GB) = 15GB → actually 3 containers
+ long totalCapacity = 0L;
+ long effectiveAllocatableSpace = 0L;
+ for (StorageReportProto report : storageReports) {
+ totalCapacity += report.getCapacity();
+ long usableSpace = VolumeUsage.getUsableSpace(report);
+ // Calculate how many containers can fit on this disk
+ long containersOnThisDisk = usableSpace / maxContainerSize;
+ // Add effective space (containers that fit * container size)
+ effectiveAllocatableSpace += containersOnThisDisk * maxContainerSize;
+ }
+
+ // Get pending allocations from tracker
+ long pendingAllocations = pendingContainerTracker.getPendingAllocationSize(node);
+
+ // Calculate effective remaining space after pending allocations
+ long effectiveRemaining = effectiveAllocatableSpace - pendingAllocations;
+
+ // Check if there's enough space for a new container
+ if (effectiveRemaining < maxContainerSize) {
Review Comment:
This makes the allocation little aggressive right? Even if we just have 5GB we allocate it. Should we have leave some buffer when allocating a container?
##########
hadoop-hdds/server-scm/src/main/java/org/apache/hadoop/hdds/scm/container/PendingContainerTracker.java:
##########
@@ -0,0 +1,338 @@
+/*
+ * 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;
+
+import com.google.common.annotations.VisibleForTesting;
+import java.util.Collections;
+import java.util.HashSet;
+import java.util.Set;
+import java.util.UUID;
+import java.util.concurrent.ConcurrentHashMap;
+import org.apache.hadoop.hdds.protocol.DatanodeDetails;
+import org.apache.hadoop.hdds.scm.container.metrics.SCMContainerManagerMetrics;
+import org.apache.hadoop.hdds.scm.pipeline.Pipeline;
+import org.apache.hadoop.util.Time;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * Tracks pending container allocations using a Two Window Tumbling Bucket pattern.
+ * Similar like HDFS HADOOP-3707.
+ *
+ * Two Window Tumbling Bucket for automatic aging and cleanup.
+ *
+ * How It Works:
+ * <li>Each DataNode has two sets: <b>currentWindow</b> and <b>previousWindow</b></li>
+ * <li>New allocations go into <b>currentWindow</b></li>
+ * <li>Every <b>ROLL_INTERVAL</b> (default 10 minutes):
+ * <ul>
+ * <li>previousWindow = currentWindow (shift)</li>
+ * <li>currentWindow = new empty set (reset)</li>
+ * <li>Old previousWindow is discarded (automatic aging)</li>
+ * </ul>
+ * </li>
+ * <li>When checking pending: return <b>union</b> of currentWindow + previousWindow</li>
+ *
+ *
+ * Example Timeline:
+ * <pre>
+ * Time | Action | CurrentWindow | PreviousWindow | Total Pending
+ * ------+---------------------------+---------------+----------------+--------------
+ * 00:00 | Allocate Container-1 | {C1} | {} | {C1}
+ * 00:05 | Allocate Container-2 | {C1, C2} | {} | {C1, C2}
+ * 00:10 | [ROLL] Window tumbles | {} | {C1, C2} | {C1, C2}
+ * 00:12 | Allocate Container-3 | {C3} | {C1, C2} | {C1, C2, C3}
+ * 00:15 | Report confirms C1 | {C3} | {C2} | {C2, C3}
+ * 00:20 | [ROLL] Window tumbles | {} | {C3} | {C3}
+ * | (C2 aged out if not reported)
+ * </pre>
+ *
+ */
+public class PendingContainerTracker {
+
+ private static final Logger LOG = LoggerFactory.getLogger(PendingContainerTracker.class);
+
+ /**
+ * Roll interval in milliseconds.
+ * Configurable via hdds.scm.container.pending-allocation.roll-interval.
+ * Default: 10 minutes.
+ * Containers automatically age out after 2 × rollIntervalMs.
+ */
+ private final long rollIntervalMs;
+
+ /**
+ * Map of DataNode UUID to TwoWindowBucket.
+ */
+ private final ConcurrentHashMap<UUID, TwoWindowBucket> datanodeBuckets;
+
+ /**
+ * Maximum container size in bytes.
+ */
+ private final long maxContainerSize;
+
+ /**
+ * Metrics for tracking pending containers.
+ */
+ private final SCMContainerManagerMetrics metrics;
+
+ /**
+ * Two-window bucket for a single DataNode.
+ * Contains current and previous window sets, plus last roll timestamp.
+ */
+ private static class TwoWindowBucket {
+ private Set<ContainerID> currentWindow = ConcurrentHashMap.newKeySet();
+ private Set<ContainerID> previousWindow = ConcurrentHashMap.newKeySet();
+ private long lastRollTime = Time.monotonicNow();
+ private final long rollIntervalMs;
+
+ TwoWindowBucket(long rollIntervalMs) {
+ this.rollIntervalMs = rollIntervalMs;
+ }
+
+ /**
+ * Roll the windows: previous = current, current = empty.
+ * Called when current time exceeds lastRollTime + rollIntervalMs.
+ */
+ synchronized void rollIfNeeded() {
+ long now = Time.monotonicNow();
+ if (now - lastRollTime >= rollIntervalMs) {
+ // Shift: current becomes previous
+ previousWindow = currentWindow;
+ // Reset: new empty current window
+ currentWindow = ConcurrentHashMap.newKeySet();
+ lastRollTime = now;
+ LOG.debug("Rolled window. Previous window size: {}, Current window reset to empty", previousWindow.size());
+ }
+ }
+
+ /**
+ * Get union of both windows (all pending containers).
+ */
+ synchronized Set<ContainerID> getAllPending() {
+ Set<ContainerID> all = new HashSet<>();
+ all.addAll(currentWindow);
+ all.addAll(previousWindow);
+ return all;
+ }
+
+ /**
+ * Add container to current window.
+ */
+ synchronized boolean add(ContainerID containerID) {
+ return currentWindow.add(containerID);
+ }
+
+ /**
+ * Remove container from both windows.
+ */
+ synchronized boolean remove(ContainerID containerID) {
+ boolean removedFromCurrent = currentWindow.remove(containerID);
+ boolean removedFromPrevious = previousWindow.remove(containerID);
+ return removedFromCurrent || removedFromPrevious;
+ }
+
+ /**
+ * Check if either window is non-empty.
+ */
+ synchronized boolean isEmpty() {
+ return currentWindow.isEmpty() && previousWindow.isEmpty();
+ }
+
+ /**
+ * Get count of all pending containers (union).
+ */
+ synchronized int getCount() {
+ return getAllPending().size();
+ }
+ }
+
+ public PendingContainerTracker(long maxContainerSize) {
+ this(maxContainerSize, 10 * 60 * 1000, null); // Default 10 minutes
+ }
+
+ public PendingContainerTracker(long maxContainerSize, long rollIntervalMs,
+ SCMContainerManagerMetrics metrics) {
+ this.datanodeBuckets = new ConcurrentHashMap<>();
+ this.maxContainerSize = maxContainerSize;
+ this.rollIntervalMs = rollIntervalMs;
+ this.metrics = metrics;
+ LOG.info("PendingContainerTracker initialized with maxContainerSize={}B, rollInterval={}ms",
+ maxContainerSize, rollIntervalMs);
+ }
+
+ /**
+ * Record a pending container allocation for all DataNodes in the pipeline.
+ * Container is added to the current window.
+ *
+ * @param pipeline The pipeline where container is allocated
+ * @param containerID The container being allocated
+ */
+ public void recordPendingAllocation(Pipeline pipeline, ContainerID containerID) {
+ if (pipeline == null || containerID == null) {
+ LOG.warn("Ignoring null pipeline or containerID");
+ return;
+ }
+
+ for (DatanodeDetails node : pipeline.getNodes()) {
+ recordPendingAllocationForDatanode(node, containerID);
+ }
+ }
+
+ /**
+ * Record a pending container allocation for a single DataNode.
+ * Container is added to the current window.
+ *
+ * @param node The DataNode where container is being allocated/replicated
+ * @param containerID The container being allocated/replicated
+ */
+ public void recordPendingAllocationForDatanode(DatanodeDetails node, ContainerID containerID) {
+ if (node == null || containerID == null) {
+ LOG.warn("Ignoring null node or containerID");
+ return;
+ }
+
+ TwoWindowBucket bucket = datanodeBuckets.computeIfAbsent(
+ node.getUuid(),
+ k -> new TwoWindowBucket(rollIntervalMs)
+ );
+
+ // Roll window if needed before adding
+ bucket.rollIfNeeded();
+
+ boolean added = bucket.add(containerID);
+ LOG.info("Recorded pending container {} on DataNode {}. Added={}, Total pending={}",
Review Comment:
We can change all the LOG to debug. This will become too noisy on the SCM log for every allocation and removal.
##########
hadoop-hdds/server-scm/src/main/java/org/apache/hadoop/hdds/scm/container/PendingContainerTracker.java:
##########
@@ -0,0 +1,338 @@
+/*
+ * 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;
+
+import com.google.common.annotations.VisibleForTesting;
+import java.util.Collections;
+import java.util.HashSet;
+import java.util.Set;
+import java.util.UUID;
+import java.util.concurrent.ConcurrentHashMap;
+import org.apache.hadoop.hdds.protocol.DatanodeDetails;
+import org.apache.hadoop.hdds.scm.container.metrics.SCMContainerManagerMetrics;
+import org.apache.hadoop.hdds.scm.pipeline.Pipeline;
+import org.apache.hadoop.util.Time;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * Tracks pending container allocations using a Two Window Tumbling Bucket pattern.
+ * Similar like HDFS HADOOP-3707.
+ *
+ * Two Window Tumbling Bucket for automatic aging and cleanup.
+ *
+ * How It Works:
+ * <li>Each DataNode has two sets: <b>currentWindow</b> and <b>previousWindow</b></li>
+ * <li>New allocations go into <b>currentWindow</b></li>
+ * <li>Every <b>ROLL_INTERVAL</b> (default 10 minutes):
+ * <ul>
+ * <li>previousWindow = currentWindow (shift)</li>
+ * <li>currentWindow = new empty set (reset)</li>
+ * <li>Old previousWindow is discarded (automatic aging)</li>
+ * </ul>
+ * </li>
+ * <li>When checking pending: return <b>union</b> of currentWindow + previousWindow</li>
+ *
+ *
+ * Example Timeline:
+ * <pre>
+ * Time | Action | CurrentWindow | PreviousWindow | Total Pending
+ * ------+---------------------------+---------------+----------------+--------------
+ * 00:00 | Allocate Container-1 | {C1} | {} | {C1}
+ * 00:05 | Allocate Container-2 | {C1, C2} | {} | {C1, C2}
+ * 00:10 | [ROLL] Window tumbles | {} | {C1, C2} | {C1, C2}
+ * 00:12 | Allocate Container-3 | {C3} | {C1, C2} | {C1, C2, C3}
+ * 00:15 | Report confirms C1 | {C3} | {C2} | {C2, C3}
+ * 00:20 | [ROLL] Window tumbles | {} | {C3} | {C3}
+ * | (C2 aged out if not reported)
+ * </pre>
+ *
+ */
+public class PendingContainerTracker {
+
+ private static final Logger LOG = LoggerFactory.getLogger(PendingContainerTracker.class);
+
+ /**
+ * Roll interval in milliseconds.
+ * Configurable via hdds.scm.container.pending-allocation.roll-interval.
+ * Default: 10 minutes.
+ * Containers automatically age out after 2 × rollIntervalMs.
+ */
+ private final long rollIntervalMs;
+
+ /**
+ * Map of DataNode UUID to TwoWindowBucket.
+ */
+ private final ConcurrentHashMap<UUID, TwoWindowBucket> datanodeBuckets;
+
+ /**
+ * Maximum container size in bytes.
+ */
+ private final long maxContainerSize;
+
+ /**
+ * Metrics for tracking pending containers.
+ */
+ private final SCMContainerManagerMetrics metrics;
+
+ /**
+ * Two-window bucket for a single DataNode.
+ * Contains current and previous window sets, plus last roll timestamp.
+ */
+ private static class TwoWindowBucket {
+ private Set<ContainerID> currentWindow = ConcurrentHashMap.newKeySet();
+ private Set<ContainerID> previousWindow = ConcurrentHashMap.newKeySet();
+ private long lastRollTime = Time.monotonicNow();
+ private final long rollIntervalMs;
+
+ TwoWindowBucket(long rollIntervalMs) {
+ this.rollIntervalMs = rollIntervalMs;
+ }
+
+ /**
+ * Roll the windows: previous = current, current = empty.
+ * Called when current time exceeds lastRollTime + rollIntervalMs.
+ */
+ synchronized void rollIfNeeded() {
+ long now = Time.monotonicNow();
+ if (now - lastRollTime >= rollIntervalMs) {
+ // Shift: current becomes previous
+ previousWindow = currentWindow;
+ // Reset: new empty current window
+ currentWindow = ConcurrentHashMap.newKeySet();
+ lastRollTime = now;
+ LOG.debug("Rolled window. Previous window size: {}, Current window reset to empty", previousWindow.size());
+ }
+ }
+
+ /**
+ * Get union of both windows (all pending containers).
+ */
+ synchronized Set<ContainerID> getAllPending() {
+ Set<ContainerID> all = new HashSet<>();
+ all.addAll(currentWindow);
+ all.addAll(previousWindow);
+ return all;
+ }
+
+ /**
+ * Add container to current window.
+ */
+ synchronized boolean add(ContainerID containerID) {
+ return currentWindow.add(containerID);
+ }
+
+ /**
+ * Remove container from both windows.
+ */
+ synchronized boolean remove(ContainerID containerID) {
+ boolean removedFromCurrent = currentWindow.remove(containerID);
+ boolean removedFromPrevious = previousWindow.remove(containerID);
+ return removedFromCurrent || removedFromPrevious;
+ }
+
+ /**
+ * Check if either window is non-empty.
+ */
+ synchronized boolean isEmpty() {
+ return currentWindow.isEmpty() && previousWindow.isEmpty();
+ }
+
+ /**
+ * Get count of all pending containers (union).
+ */
+ synchronized int getCount() {
+ return getAllPending().size();
Review Comment:
Can we just return the count of both windows instead of adding them to separate set just to get the count here.
##########
hadoop-hdds/server-scm/src/main/java/org/apache/hadoop/hdds/scm/container/IncrementalContainerReportHandler.java:
##########
@@ -89,6 +89,15 @@ protected void processICR(IncrementalContainerReportFromDatanode report,
ContainerID id = ContainerID.valueOf(replicaProto.getContainerID());
final ContainerInfo container;
try {
+ // Check if container is already known to this DN before adding
+ boolean alreadyOnDn = false;
Review Comment:
Agreed. Instead of checking and then removing. We can just check the pending list and remove it. It will be the same, We can just avoid one extra op.
##########
hadoop-hdds/server-scm/src/main/java/org/apache/hadoop/hdds/scm/container/PendingContainerTracker.java:
##########
@@ -0,0 +1,338 @@
+/*
+ * 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;
+
+import com.google.common.annotations.VisibleForTesting;
+import java.util.Collections;
+import java.util.HashSet;
+import java.util.Set;
+import java.util.UUID;
+import java.util.concurrent.ConcurrentHashMap;
+import org.apache.hadoop.hdds.protocol.DatanodeDetails;
+import org.apache.hadoop.hdds.scm.container.metrics.SCMContainerManagerMetrics;
+import org.apache.hadoop.hdds.scm.pipeline.Pipeline;
+import org.apache.hadoop.util.Time;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * Tracks pending container allocations using a Two Window Tumbling Bucket pattern.
+ * Similar like HDFS HADOOP-3707.
+ *
+ * Two Window Tumbling Bucket for automatic aging and cleanup.
+ *
+ * How It Works:
+ * <li>Each DataNode has two sets: <b>currentWindow</b> and <b>previousWindow</b></li>
+ * <li>New allocations go into <b>currentWindow</b></li>
+ * <li>Every <b>ROLL_INTERVAL</b> (default 10 minutes):
+ * <ul>
+ * <li>previousWindow = currentWindow (shift)</li>
+ * <li>currentWindow = new empty set (reset)</li>
+ * <li>Old previousWindow is discarded (automatic aging)</li>
+ * </ul>
+ * </li>
+ * <li>When checking pending: return <b>union</b> of currentWindow + previousWindow</li>
+ *
+ *
+ * Example Timeline:
+ * <pre>
+ * Time | Action | CurrentWindow | PreviousWindow | Total Pending
+ * ------+---------------------------+---------------+----------------+--------------
+ * 00:00 | Allocate Container-1 | {C1} | {} | {C1}
+ * 00:05 | Allocate Container-2 | {C1, C2} | {} | {C1, C2}
+ * 00:10 | [ROLL] Window tumbles | {} | {C1, C2} | {C1, C2}
+ * 00:12 | Allocate Container-3 | {C3} | {C1, C2} | {C1, C2, C3}
+ * 00:15 | Report confirms C1 | {C3} | {C2} | {C2, C3}
+ * 00:20 | [ROLL] Window tumbles | {} | {C3} | {C3}
+ * | (C2 aged out if not reported)
+ * </pre>
+ *
+ */
+public class PendingContainerTracker {
+
+ private static final Logger LOG = LoggerFactory.getLogger(PendingContainerTracker.class);
+
+ /**
+ * Roll interval in milliseconds.
+ * Configurable via hdds.scm.container.pending-allocation.roll-interval.
+ * Default: 10 minutes.
+ * Containers automatically age out after 2 × rollIntervalMs.
+ */
+ private final long rollIntervalMs;
+
+ /**
+ * Map of DataNode UUID to TwoWindowBucket.
+ */
+ private final ConcurrentHashMap<UUID, TwoWindowBucket> datanodeBuckets;
+
+ /**
+ * Maximum container size in bytes.
+ */
+ private final long maxContainerSize;
+
+ /**
+ * Metrics for tracking pending containers.
+ */
+ private final SCMContainerManagerMetrics metrics;
+
+ /**
+ * Two-window bucket for a single DataNode.
+ * Contains current and previous window sets, plus last roll timestamp.
+ */
+ private static class TwoWindowBucket {
+ private Set<ContainerID> currentWindow = ConcurrentHashMap.newKeySet();
+ private Set<ContainerID> previousWindow = ConcurrentHashMap.newKeySet();
+ private long lastRollTime = Time.monotonicNow();
+ private final long rollIntervalMs;
+
+ TwoWindowBucket(long rollIntervalMs) {
+ this.rollIntervalMs = rollIntervalMs;
+ }
+
+ /**
+ * Roll the windows: previous = current, current = empty.
+ * Called when current time exceeds lastRollTime + rollIntervalMs.
+ */
+ synchronized void rollIfNeeded() {
+ long now = Time.monotonicNow();
+ if (now - lastRollTime >= rollIntervalMs) {
+ // Shift: current becomes previous
+ previousWindow = currentWindow;
+ // Reset: new empty current window
+ currentWindow = ConcurrentHashMap.newKeySet();
+ lastRollTime = now;
+ LOG.debug("Rolled window. Previous window size: {}, Current window reset to empty", previousWindow.size());
+ }
+ }
+
+ /**
+ * Get union of both windows (all pending containers).
+ */
+ synchronized Set<ContainerID> getAllPending() {
+ Set<ContainerID> all = new HashSet<>();
+ all.addAll(currentWindow);
+ all.addAll(previousWindow);
+ return all;
+ }
+
+ /**
+ * Add container to current window.
+ */
+ synchronized boolean add(ContainerID containerID) {
+ return currentWindow.add(containerID);
+ }
+
+ /**
+ * Remove container from both windows.
+ */
+ synchronized boolean remove(ContainerID containerID) {
+ boolean removedFromCurrent = currentWindow.remove(containerID);
+ boolean removedFromPrevious = previousWindow.remove(containerID);
+ return removedFromCurrent || removedFromPrevious;
+ }
+
+ /**
+ * Check if either window is non-empty.
+ */
+ synchronized boolean isEmpty() {
+ return currentWindow.isEmpty() && previousWindow.isEmpty();
+ }
+
+ /**
+ * Get count of all pending containers (union).
+ */
+ synchronized int getCount() {
+ return getAllPending().size();
+ }
+ }
+
+ public PendingContainerTracker(long maxContainerSize) {
+ this(maxContainerSize, 10 * 60 * 1000, null); // Default 10 minutes
+ }
+
+ public PendingContainerTracker(long maxContainerSize, long rollIntervalMs,
+ SCMContainerManagerMetrics metrics) {
+ this.datanodeBuckets = new ConcurrentHashMap<>();
+ this.maxContainerSize = maxContainerSize;
+ this.rollIntervalMs = rollIntervalMs;
+ this.metrics = metrics;
+ LOG.info("PendingContainerTracker initialized with maxContainerSize={}B, rollInterval={}ms",
+ maxContainerSize, rollIntervalMs);
+ }
+
+ /**
+ * Record a pending container allocation for all DataNodes in the pipeline.
+ * Container is added to the current window.
+ *
+ * @param pipeline The pipeline where container is allocated
+ * @param containerID The container being allocated
+ */
+ public void recordPendingAllocation(Pipeline pipeline, ContainerID containerID) {
+ if (pipeline == null || containerID == null) {
+ LOG.warn("Ignoring null pipeline or containerID");
+ return;
+ }
+
+ for (DatanodeDetails node : pipeline.getNodes()) {
+ recordPendingAllocationForDatanode(node, containerID);
+ }
+ }
+
+ /**
+ * Record a pending container allocation for a single DataNode.
+ * Container is added to the current window.
+ *
+ * @param node The DataNode where container is being allocated/replicated
+ * @param containerID The container being allocated/replicated
+ */
+ public void recordPendingAllocationForDatanode(DatanodeDetails node, ContainerID containerID) {
+ if (node == null || containerID == null) {
+ LOG.warn("Ignoring null node or containerID");
+ return;
+ }
+
+ TwoWindowBucket bucket = datanodeBuckets.computeIfAbsent(
+ node.getUuid(),
+ k -> new TwoWindowBucket(rollIntervalMs)
+ );
+
+ // Roll window if needed before adding
+ bucket.rollIfNeeded();
+
+ boolean added = bucket.add(containerID);
+ LOG.info("Recorded pending container {} on DataNode {}. Added={}, Total pending={}",
+ containerID, node.getUuidString(), added, bucket.getCount());
+
+ // Increment metrics counter
+ if (added && metrics != null) {
+ metrics.incNumPendingContainersAdded();
+ }
+ }
+
+ /**
+ * Remove a pending container allocation from a specific DataNode.
+ * Removes from both current and previous windows.
+ * Called when container is confirmed.
+ *
+ * @param node The DataNode
+ * @param containerID The container to remove from pending
+ */
+ public void removePendingAllocation(DatanodeDetails node, ContainerID containerID) {
+ if (node == null || containerID == null) {
+ return;
+ }
+
+ TwoWindowBucket bucket = datanodeBuckets.get(node.getUuid());
+ if (bucket != null) {
+ // Roll window if needed before removing
+ bucket.rollIfNeeded();
+
+ boolean removed = bucket.remove(containerID);
+ LOG.info("Removed pending container {} from DataNode {}. Removed={}, Remaining={}",
Review Comment:
Same as above for all the LOG in this class.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org
For additional commands, e-mail: issues-help@ozone.apache.org
Re: [PR] HDDS-14921. Improve space accounting in SCM with In-Flight container allocation tracking. [ozone]
Posted by "ashishkumar50 (via GitHub)" <gi...@apache.org>.
ashishkumar50 commented on code in PR #10000:
URL: https://github.com/apache/ozone/pull/10000#discussion_r3035995487
##########
hadoop-hdds/server-scm/src/main/java/org/apache/hadoop/hdds/scm/node/PendingContainerTracker.java:
##########
@@ -0,0 +1,338 @@
+/*
+ * 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;
+
+import com.google.common.annotations.VisibleForTesting;
+import java.util.Collections;
+import java.util.HashSet;
+import java.util.Set;
+import java.util.UUID;
+import java.util.concurrent.ConcurrentHashMap;
+import org.apache.hadoop.hdds.protocol.DatanodeDetails;
+import org.apache.hadoop.hdds.scm.container.metrics.SCMContainerManagerMetrics;
+import org.apache.hadoop.hdds.scm.pipeline.Pipeline;
+import org.apache.hadoop.util.Time;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * Tracks pending container allocations using a Two Window Tumbling Bucket pattern.
+ * Similar like HDFS HADOOP-3707.
+ *
+ * Two Window Tumbling Bucket for automatic aging and cleanup.
+ *
+ * How It Works:
+ * <li>Each DataNode has two sets: <b>currentWindow</b> and <b>previousWindow</b></li>
+ * <li>New allocations go into <b>currentWindow</b></li>
+ * <li>Every <b>ROLL_INTERVAL</b> (default 10 minutes):
+ * <ul>
+ * <li>previousWindow = currentWindow (shift)</li>
+ * <li>currentWindow = new empty set (reset)</li>
+ * <li>Old previousWindow is discarded (automatic aging)</li>
+ * </ul>
+ * </li>
+ * <li>When checking pending: return <b>union</b> of currentWindow + previousWindow</li>
+ *
+ *
+ * Example Timeline:
+ * <pre>
+ * Time | Action | CurrentWindow | PreviousWindow | Total Pending
+ * ------+---------------------------+---------------+----------------+--------------
+ * 00:00 | Allocate Container-1 | {C1} | {} | {C1}
+ * 00:05 | Allocate Container-2 | {C1, C2} | {} | {C1, C2}
+ * 00:10 | [ROLL] Window tumbles | {} | {C1, C2} | {C1, C2}
+ * 00:12 | Allocate Container-3 | {C3} | {C1, C2} | {C1, C2, C3}
+ * 00:15 | Report confirms C1 | {C3} | {C2} | {C2, C3}
+ * 00:20 | [ROLL] Window tumbles | {} | {C3} | {C3}
+ * | (C2 aged out if not reported)
+ * </pre>
+ *
+ */
+public class PendingContainerTracker {
+
+ private static final Logger LOG = LoggerFactory.getLogger(PendingContainerTracker.class);
+
+ /**
+ * Roll interval in milliseconds.
+ * Configurable via hdds.scm.container.pending-allocation.roll-interval.
+ * Default: 10 minutes.
+ * Containers automatically age out after 2 × rollIntervalMs.
+ */
+ private final long rollIntervalMs;
+
+ /**
+ * Map of DataNode UUID to TwoWindowBucket.
+ */
+ private final ConcurrentHashMap<UUID, TwoWindowBucket> datanodeBuckets;
+
+ /**
+ * Maximum container size in bytes.
+ */
+ private final long maxContainerSize;
+
+ /**
+ * Metrics for tracking pending containers.
+ */
+ private final SCMContainerManagerMetrics metrics;
+
+ /**
+ * Two-window bucket for a single DataNode.
+ * Contains current and previous window sets, plus last roll timestamp.
+ */
+ private static class TwoWindowBucket {
+ private Set<ContainerID> currentWindow = ConcurrentHashMap.newKeySet();
+ private Set<ContainerID> previousWindow = ConcurrentHashMap.newKeySet();
+ private long lastRollTime = Time.monotonicNow();
+ private final long rollIntervalMs;
+
+ TwoWindowBucket(long rollIntervalMs) {
+ this.rollIntervalMs = rollIntervalMs;
+ }
+
+ /**
+ * Roll the windows: previous = current, current = empty.
+ * Called when current time exceeds lastRollTime + rollIntervalMs.
+ */
+ synchronized void rollIfNeeded() {
+ long now = Time.monotonicNow();
+ if (now - lastRollTime >= rollIntervalMs) {
+ // Shift: current becomes previous
+ previousWindow = currentWindow;
+ // Reset: new empty current window
+ currentWindow = ConcurrentHashMap.newKeySet();
+ lastRollTime = now;
+ LOG.debug("Rolled window. Previous window size: {}, Current window reset to empty", previousWindow.size());
+ }
+ }
+
+ /**
+ * Get union of both windows (all pending containers).
+ */
+ synchronized Set<ContainerID> getAllPending() {
+ Set<ContainerID> all = new HashSet<>();
+ all.addAll(currentWindow);
+ all.addAll(previousWindow);
+ return all;
+ }
+
+ /**
+ * Add container to current window.
+ */
+ synchronized boolean add(ContainerID containerID) {
+ return currentWindow.add(containerID);
+ }
+
+ /**
+ * Remove container from both windows.
+ */
+ synchronized boolean remove(ContainerID containerID) {
+ boolean removedFromCurrent = currentWindow.remove(containerID);
+ boolean removedFromPrevious = previousWindow.remove(containerID);
+ return removedFromCurrent || removedFromPrevious;
+ }
+
+ /**
+ * Check if either window is non-empty.
+ */
+ synchronized boolean isEmpty() {
+ return currentWindow.isEmpty() && previousWindow.isEmpty();
+ }
+
+ /**
+ * Get count of all pending containers (union).
+ */
+ synchronized int getCount() {
+ return getAllPending().size();
+ }
+ }
+
+ public PendingContainerTracker(long maxContainerSize) {
+ this(maxContainerSize, 10 * 60 * 1000, null); // Default 10 minutes
+ }
+
+ public PendingContainerTracker(long maxContainerSize, long rollIntervalMs,
+ SCMContainerManagerMetrics metrics) {
+ this.datanodeBuckets = new ConcurrentHashMap<>();
+ this.maxContainerSize = maxContainerSize;
+ this.rollIntervalMs = rollIntervalMs;
+ this.metrics = metrics;
+ LOG.info("PendingContainerTracker initialized with maxContainerSize={}B, rollInterval={}ms",
+ maxContainerSize, rollIntervalMs);
+ }
+
+ /**
+ * Record a pending container allocation for all DataNodes in the pipeline.
+ * Container is added to the current window.
+ *
+ * @param pipeline The pipeline where container is allocated
+ * @param containerID The container being allocated
+ */
+ public void recordPendingAllocation(Pipeline pipeline, ContainerID containerID) {
Review Comment:
Moved to node package
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org
For additional commands, e-mail: issues-help@ozone.apache.org
Re: [PR] HDDS-14921. Improve space accounting in SCM with In-Flight container allocation tracking. [ozone]
Posted by "aswinshakil (via GitHub)" <gi...@apache.org>.
aswinshakil commented on code in PR #10000:
URL: https://github.com/apache/ozone/pull/10000#discussion_r3048152699
##########
hadoop-hdds/server-scm/src/main/java/org/apache/hadoop/hdds/scm/pipeline/PipelineManager.java:
##########
@@ -227,4 +228,11 @@ void reinitialize(Table<PipelineID, Pipeline> pipelineStore)
* Get the pipeline metrics.
*/
SCMPipelineMetrics getMetrics();
+
+ /**
+ * Get DatanodeInfo for a specific DataNode which includes per-volume storage reports.
+ * @param datanodeDetails The datanode to get info for
+ * @return DatanodeInfo containing detailed node information including per-disk stats, or null if not available
+ */
+ DatanodeInfo getDatanodeInfo(DatanodeDetails datanodeDetails);
Review Comment:
Looks like this is not used, It can be removed.
##########
hadoop-hdds/server-scm/src/main/java/org/apache/hadoop/hdds/scm/node/PendingContainerTracker.java:
##########
@@ -0,0 +1,425 @@
+/*
+ * 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.node;
+
+import com.google.common.annotations.VisibleForTesting;
+import java.util.Collections;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Set;
+import java.util.UUID;
+import java.util.concurrent.ConcurrentHashMap;
+import org.apache.hadoop.hdds.protocol.DatanodeDetails;
+import org.apache.hadoop.hdds.protocol.proto.StorageContainerDatanodeProtocolProtos.StorageReportProto;
+import org.apache.hadoop.hdds.scm.container.ContainerID;
+import org.apache.hadoop.hdds.scm.pipeline.Pipeline;
+import org.apache.hadoop.ozone.container.common.volume.VolumeUsage;
+import org.apache.hadoop.util.Time;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * Tracks per-datanode pending container allocations at SCM using a Two Window Tumbling Bucket
+ * pattern (similar to HDFS HADOOP-3707).
+ *
+ * Two Window Tumbling Bucket for automatic aging and cleanup.
+ *
+ * How It Works:
+ * <li>Each DataNode has two sets: <b>currentWindow</b> and <b>previousWindow</b></li>
+ * <li>New allocations go into <b>currentWindow</b></li>
+ * <li>Every <b>ROLL_INTERVAL</b> (default 5 minutes):
+ * <ul>
+ * <li>previousWindow = currentWindow (shift)</li>
+ * <li>currentWindow = new empty set (reset)</li>
+ * <li>Old previousWindow is discarded (automatic aging)</li>
+ * </ul>
+ * </li>
+ * <li>When checking pending: return <b>union</b> of currentWindow + previousWindow</li>
+ *
+ *
+ * Example Timeline:
+ * <pre>
+ * Time | Action | CurrentWindow | PreviousWindow | Total Pending
+ * ------+---------------------------+---------------+----------------+--------------
+ * 00:00 | Allocate Container-1 | {C1} | {} | {C1}
+ * 00:02 | Allocate Container-2 | {C1, C2} | {} | {C1, C2}
+ * 00:05 | [ROLL] Window tumbles | {} | {C1, C2} | {C1, C2}
+ * 00:07 | Allocate Container-3 | {C3} | {C1, C2} | {C1, C2, C3}
+ * 00:08 | Report confirms C1 | {C3} | {C2} | {C2, C3}
+ * 00:10 | [ROLL] Window tumbles | {} | {C3} | {C3}
+ * | (C2 aged out if not reported)
+ * </pre>
+ *
+ * <p>Thread-safety: all mutations and reads for a given datanode run under
+ * {@code synchronized (bucket)} on that datanode's {@link TwoWindowBucket}, including
+ * map insert/remove, so concurrent record/remove/report paths cannot interleave or orphan
+ * a bucket after it was dropped from the map.</p>
+ */
+public class PendingContainerTracker {
+
+ private static final Logger LOG = LoggerFactory.getLogger(PendingContainerTracker.class);
+
+ /**
+ * Roll interval in milliseconds.
+ * Configurable via hdds.scm.container.pending.allocation.roll.interval.
+ * Default: 5 minutes.
+ * Containers automatically age out after 2 × rollIntervalMs.
+ */
+ private final long rollIntervalMs;
+
+ /**
+ * Map of DataNode UUID to TwoWindowBucket.
+ */
+ private final ConcurrentHashMap<UUID, TwoWindowBucket> datanodeBuckets;
+
+ /**
+ * Maximum container size in bytes.
+ */
+ private final long maxContainerSize;
+
+ /**
+ * Metrics for tracking pending containers (same instance as {@link SCMNodeManager}'s node metrics).
+ */
+ private final SCMNodeMetrics metrics;
+
+ /**
+ * Two-window bucket for a single DataNode.
+ * Contains current and previous window sets, plus last roll timestamp.
+ */
+ private static class TwoWindowBucket {
+ private Set<ContainerID> currentWindow = new HashSet<>();
+ private Set<ContainerID> previousWindow = new HashSet<>();
+ private long lastRollTime = Time.monotonicNow();
+ private final long rollIntervalMs;
+
+ TwoWindowBucket(long rollIntervalMs) {
+ this.rollIntervalMs = rollIntervalMs;
+ }
+
+ /**
+ * Roll the windows: previous = current, current = empty.
+ * Called when current time exceeds lastRollTime + rollIntervalMs.
+ */
+ synchronized void rollIfNeeded() {
+ long now = Time.monotonicNow();
+ if (now - lastRollTime >= rollIntervalMs) {
+ // Shift: current becomes previous
+ previousWindow = currentWindow;
+ // Reset: new empty current window
+ currentWindow = new HashSet<>();
+ lastRollTime = now;
+ LOG.debug("Rolled window. Previous window size: {}, Current window reset to empty", previousWindow.size());
+ }
+ }
+
+ /**
+ * Get union of both windows (all pending containers).
+ */
+ synchronized Set<ContainerID> getAllPending() {
+ Set<ContainerID> all = new HashSet<>();
+ all.addAll(currentWindow);
+ all.addAll(previousWindow);
+ return all;
+ }
+
+ /**
+ * Add container to current window.
+ */
+ synchronized boolean add(ContainerID containerID) {
+ return currentWindow.add(containerID);
+ }
+
+ /**
+ * Remove container from both windows.
+ */
+ synchronized boolean remove(ContainerID containerID) {
+ boolean removedFromCurrent = currentWindow.remove(containerID);
+ boolean removedFromPrevious = previousWindow.remove(containerID);
+ return removedFromCurrent || removedFromPrevious;
+ }
+
+ /**
+ * Check if either window is non-empty.
+ */
+ synchronized boolean isEmpty() {
+ return currentWindow.isEmpty() && previousWindow.isEmpty();
+ }
+
+ /**
+ * Count of pending containers in both windows.
+ */
+ synchronized int getCount() {
+ return currentWindow.size() + previousWindow.size();
+ }
+ }
+
+ public PendingContainerTracker(long maxContainerSize) {
+ this(maxContainerSize, 10 * 60 * 1000, null); // Default 10 minutes
+ }
+
+ public PendingContainerTracker(long maxContainerSize, long rollIntervalMs,
+ SCMNodeMetrics metrics) {
+ this.datanodeBuckets = new ConcurrentHashMap<>();
+ this.maxContainerSize = maxContainerSize;
+ this.rollIntervalMs = rollIntervalMs;
+ this.metrics = metrics;
+ LOG.info("PendingContainerTracker initialized with maxContainerSize={}B, rollInterval={}ms",
+ maxContainerSize, rollIntervalMs);
+ }
+
+ /**
+ * Whether the datanode can fit another container of {@code containerSize} after accounting for
+ * SCM pending allocations for {@code node} (this tracker) and usable space on {@code datanodeInfo}.
+ * Combines {@link #getPendingAllocationSize} with the per-disk slot check in one call.
+ *
+ * @param node identity used to look up pending allocations (same DN as {@code datanodeInfo})
+ * @param datanodeInfo storage reports for the datanode
+ * @param containerSize required container size in bytes (typically SCM max container size)
+ */
+ /**
+ * Advances the two-window tumbling bucket for this datanode when the roll interval has elapsed.
+ * Call on periodic paths (e.g. node report) so windows age even when there are no new
+ * allocations or container reports touching this tracker.
+ */
+ public void rollWindowsIfNeeded(DatanodeDetails node) {
+ if (node == null) {
+ return;
+ }
+ UUID uuid = node.getUuid();
Review Comment:
`node.getUuid()` is being deprecated, We can use `node.getID()` instead. If we change here, need to change in all the places in the class
##########
hadoop-hdds/server-scm/src/main/java/org/apache/hadoop/hdds/scm/node/PendingContainerTracker.java:
##########
@@ -0,0 +1,338 @@
+/*
+ * 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;
+
+import com.google.common.annotations.VisibleForTesting;
+import java.util.Collections;
+import java.util.HashSet;
+import java.util.Set;
+import java.util.UUID;
+import java.util.concurrent.ConcurrentHashMap;
+import org.apache.hadoop.hdds.protocol.DatanodeDetails;
+import org.apache.hadoop.hdds.scm.container.metrics.SCMContainerManagerMetrics;
+import org.apache.hadoop.hdds.scm.pipeline.Pipeline;
+import org.apache.hadoop.util.Time;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * Tracks pending container allocations using a Two Window Tumbling Bucket pattern.
+ * Similar like HDFS HADOOP-3707.
+ *
+ * Two Window Tumbling Bucket for automatic aging and cleanup.
+ *
+ * How It Works:
+ * <li>Each DataNode has two sets: <b>currentWindow</b> and <b>previousWindow</b></li>
+ * <li>New allocations go into <b>currentWindow</b></li>
+ * <li>Every <b>ROLL_INTERVAL</b> (default 10 minutes):
+ * <ul>
+ * <li>previousWindow = currentWindow (shift)</li>
+ * <li>currentWindow = new empty set (reset)</li>
+ * <li>Old previousWindow is discarded (automatic aging)</li>
+ * </ul>
+ * </li>
+ * <li>When checking pending: return <b>union</b> of currentWindow + previousWindow</li>
+ *
+ *
+ * Example Timeline:
+ * <pre>
+ * Time | Action | CurrentWindow | PreviousWindow | Total Pending
+ * ------+---------------------------+---------------+----------------+--------------
+ * 00:00 | Allocate Container-1 | {C1} | {} | {C1}
+ * 00:05 | Allocate Container-2 | {C1, C2} | {} | {C1, C2}
+ * 00:10 | [ROLL] Window tumbles | {} | {C1, C2} | {C1, C2}
+ * 00:12 | Allocate Container-3 | {C3} | {C1, C2} | {C1, C2, C3}
+ * 00:15 | Report confirms C1 | {C3} | {C2} | {C2, C3}
+ * 00:20 | [ROLL] Window tumbles | {} | {C3} | {C3}
+ * | (C2 aged out if not reported)
+ * </pre>
+ *
+ */
+public class PendingContainerTracker {
+
+ private static final Logger LOG = LoggerFactory.getLogger(PendingContainerTracker.class);
+
+ /**
+ * Roll interval in milliseconds.
+ * Configurable via hdds.scm.container.pending-allocation.roll-interval.
+ * Default: 10 minutes.
+ * Containers automatically age out after 2 × rollIntervalMs.
+ */
+ private final long rollIntervalMs;
+
+ /**
+ * Map of DataNode UUID to TwoWindowBucket.
+ */
+ private final ConcurrentHashMap<UUID, TwoWindowBucket> datanodeBuckets;
+
+ /**
+ * Maximum container size in bytes.
+ */
+ private final long maxContainerSize;
+
+ /**
+ * Metrics for tracking pending containers.
+ */
+ private final SCMContainerManagerMetrics metrics;
+
+ /**
+ * Two-window bucket for a single DataNode.
+ * Contains current and previous window sets, plus last roll timestamp.
+ */
+ private static class TwoWindowBucket {
+ private Set<ContainerID> currentWindow = ConcurrentHashMap.newKeySet();
+ private Set<ContainerID> previousWindow = ConcurrentHashMap.newKeySet();
+ private long lastRollTime = Time.monotonicNow();
+ private final long rollIntervalMs;
+
+ TwoWindowBucket(long rollIntervalMs) {
+ this.rollIntervalMs = rollIntervalMs;
+ }
+
+ /**
+ * Roll the windows: previous = current, current = empty.
+ * Called when current time exceeds lastRollTime + rollIntervalMs.
+ */
+ synchronized void rollIfNeeded() {
Review Comment:
We don't have to roll for every node report. If there are 10,000+ datanodes then we will try to roll for each report every minute. Even if the node is not even used for allocation we still roll every time. We are already rolling when there are some container allocation/removal ops.
Also rolling shouldn't just depend on the timing of the report to roll, The node might go down and come back. if someone sets the `ozone.scm.stale.node.interval` and `ozone.scm.stale.node.interval `> 10mins then this logic wouldn't work. If the node comes back after 10 mins and then sends a report we will only roll once. We can just roll like mentioned in https://github.com/apache/ozone/pull/10000/changes#r3044295093 or something like this
```
long now = Time.monotonicNow();
long elapsed = now - lastRollTime;
if (elapsed >= 2 * rollIntervalMs) {
previousWindow.clear();
currentWindow.clear();
lastRollTime = now;
} else if (elapsed >= rollIntervalMs) {
previousWindow = currentWindow;
currentWindow = new HashSet<>();
lastRollTime = now;
}
```
##########
hadoop-hdds/server-scm/src/main/java/org/apache/hadoop/hdds/scm/container/ContainerManagerImpl.java:
##########
Review Comment:
@rakeshadr @ashishkr200 `pipelineManager.hasEnoughSpace` is not a synchronized operation on the datanodes. We take lock on the pipeline `synchronized (pipeline.getId())`. Still two different pipelines can still allocate container on the same datanode.
We record the pending allocation on only Line 289. Until the code reaches that point multiple pipeline will be allocated to the same space on the datanode.
Let's say we only have 6GB space available in d1.
Pipeline 1: d1, d2, d3
Pipeline 2: d1, d4, d5
When we allocate container on both the pipeline, will get past `pipelineManager.hasEnoughSpace` and both will be allocated container 5GB *2 = 10GB. But we only have 5GB on d1
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org
For additional commands, e-mail: issues-help@ozone.apache.org
Re: [PR] HDDS-14921. Improve space accounting in SCM with In-Flight container allocation tracking. [ozone]
Posted by "ashishkumar50 (via GitHub)" <gi...@apache.org>.
ashishkumar50 commented on code in PR #10000:
URL: https://github.com/apache/ozone/pull/10000#discussion_r3036008474
##########
hadoop-hdds/server-scm/src/main/java/org/apache/hadoop/hdds/scm/container/ContainerManagerImpl.java:
##########
@@ -242,12 +262,75 @@ private ContainerInfo createContainer(Pipeline pipeline, String owner)
return containerInfo;
}
+ /**
+ * Check if a pipeline has sufficient space after considering pending allocations.
+ * Tracks containers scheduled but not yet written to DataNodes, preventing over-allocation.
+ *
+ * @param pipeline The pipeline to check
+ * @return true if sufficient space is available, false otherwise
+ */
+ private boolean hasSpaceAfterPendingAllocations(Pipeline pipeline) {
+ try {
+ for (DatanodeDetails node : pipeline.getNodes()) {
+ // Get DN's storage statistics
+ DatanodeInfo datanodeInfo = pipelineManager.getDatanodeInfo(node);
+ if (datanodeInfo == null) {
+ LOG.warn("DatanodeInfo not found for node {}", node.getUuidString());
+ return false;
+ }
+
+ List<StorageReportProto> storageReports = datanodeInfo.getStorageReports();
+ if (storageReports == null || storageReports.isEmpty()) {
+ LOG.warn("No storage reports for node {}", node.getUuidString());
+ return false;
+ }
+
+ // Calculate total capacity and effective allocatable space
+ // For each disk, calculate how many containers can actually fit,
+ // since containers are written to individual disks, not spread across them.
+ // Example: disk1=9GB, disk2=14GB with 5GB containers
+ // (1*5GB) + (2*5GB) = 15GB → actually 3 containers
+ long totalCapacity = 0L;
+ long effectiveAllocatableSpace = 0L;
+ for (StorageReportProto report : storageReports) {
Review Comment:
Updated the logic to break when enough space is available on any volume
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org
For additional commands, e-mail: issues-help@ozone.apache.org
Re: [PR] HDDS-14921. Improve space accounting in SCM with In-Flight container allocation tracking. [ozone]
Posted by "ashishkumar50 (via GitHub)" <gi...@apache.org>.
ashishkumar50 commented on PR #10000:
URL: https://github.com/apache/ozone/pull/10000#issuecomment-4280063160
@szetszwo @rakeshadr Updated this PR to use pending container tracker during container creation and remove container tracking during ICR/FCR processing. Can you please take a look.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org
For additional commands, e-mail: issues-help@ozone.apache.org
Re: [PR] HDDS-14921. Improve space accounting in SCM with In-Flight container allocation tracking. [ozone]
Posted by "szetszwo (via GitHub)" <gi...@apache.org>.
szetszwo commented on code in PR #10000:
URL: https://github.com/apache/ozone/pull/10000#discussion_r3328941800
##########
hadoop-hdds/server-scm/src/main/java/org/apache/hadoop/hdds/scm/pipeline/PipelineManagerImpl.java:
##########
@@ -634,22 +636,23 @@ private boolean isOpenWithUnregisteredNodes(Pipeline pipeline) {
}
@Override
- public boolean hasEnoughSpace(Pipeline pipeline) {
- for (DatanodeDetails node : pipeline.getNodes()) {
- if (!nodeManager.hasSpaceForNewContainerAllocation(node.getID())) {
+ public boolean checkSpaceAndRecordAllocation(Pipeline pipeline, ContainerID containerID) {
+ List<DatanodeDetails> successfulNodes = new ArrayList<>();
+ for (DatanodeDetails dn : pipeline.getNodes()) {
Review Comment:
We should getDatanodeInfo first:
```java
public boolean checkSpaceAndRecordAllocation(Pipeline pipeline, ContainerID containerID) {
final Set<DatanodeDetails> datanodeDetails = pipeline.getNodeSet();
final List<DatanodeInfo> datanodeInfos = new ArrayList<>(datanodeDetails.size());
for (DatanodeDetails dn : datanodeDetails) {
final DatanodeInfo info = nodeManager.getDatanodeInfo(dn);
if (info == null) {
LOG.warn("DatanodeInfo not found for {}", dn.getID());
return false;
}
datanodeInfos.add(info);
}
final List<DatanodeInfo> successfulNodes = new ArrayList<>(datanodeInfos.size());
for (DatanodeInfo dn : datanodeInfos) {
if (!nodeManager.checkSpaceAndRecordAllocation(dn, containerID)) {
for (DatanodeInfo rollbackNode : successfulNodes) {
nodeManager.removePendingAllocationForDatanode(rollbackNode, containerID);
}
return false;
}
successfulNodes.add(dn);
}
return true;
}
```
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org
For additional commands, e-mail: issues-help@ozone.apache.org
Re: [PR] HDDS-14921. Improve space accounting in SCM with In-Flight container allocation tracking. [ozone]
Posted by "szetszwo (via GitHub)" <gi...@apache.org>.
szetszwo commented on PR #10000:
URL: https://github.com/apache/ozone/pull/10000#issuecomment-4511657887
@ashishkumar50 , sorry for the late reply. Will review this soon.
BTW, could you resolve the conflict?
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org
For additional commands, e-mail: issues-help@ozone.apache.org
Re: [PR] HDDS-14921. Improve space accounting in SCM with In-Flight container allocation tracking. [ozone]
Posted by "ashishkumar50 (via GitHub)" <gi...@apache.org>.
ashishkumar50 commented on code in PR #10000:
URL: https://github.com/apache/ozone/pull/10000#discussion_r3043314221
##########
hadoop-hdds/server-scm/src/main/java/org/apache/hadoop/hdds/scm/container/ContainerManagerImpl.java:
##########
Review Comment:
Checked other places already have safeguard. [SCMClientProtocolServer.java#L258](https://github.com/apache/ozone/blob/master/hadoop-hdds/server-scm/src/main/java/org/apache/hadoop/hdds/scm/server/SCMClientProtocolServer.java#L258) is used only for test or tools. Added a safeguard here.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org
For additional commands, e-mail: issues-help@ozone.apache.org
Re: [PR] HDDS-14921. Improve space accounting in SCM with In-Flight container allocation tracking. [ozone]
Posted by "ashishkumar50 (via GitHub)" <gi...@apache.org>.
ashishkumar50 commented on code in PR #10000:
URL: https://github.com/apache/ozone/pull/10000#discussion_r3036009750
##########
hadoop-hdds/server-scm/src/main/java/org/apache/hadoop/hdds/scm/container/ContainerManagerImpl.java:
##########
@@ -242,12 +262,75 @@ private ContainerInfo createContainer(Pipeline pipeline, String owner)
return containerInfo;
}
+ /**
+ * Check if a pipeline has sufficient space after considering pending allocations.
+ * Tracks containers scheduled but not yet written to DataNodes, preventing over-allocation.
+ *
+ * @param pipeline The pipeline to check
+ * @return true if sufficient space is available, false otherwise
+ */
+ private boolean hasSpaceAfterPendingAllocations(Pipeline pipeline) {
+ try {
+ for (DatanodeDetails node : pipeline.getNodes()) {
+ // Get DN's storage statistics
+ DatanodeInfo datanodeInfo = pipelineManager.getDatanodeInfo(node);
+ if (datanodeInfo == null) {
+ LOG.warn("DatanodeInfo not found for node {}", node.getUuidString());
+ return false;
+ }
+
+ List<StorageReportProto> storageReports = datanodeInfo.getStorageReports();
+ if (storageReports == null || storageReports.isEmpty()) {
+ LOG.warn("No storage reports for node {}", node.getUuidString());
+ return false;
+ }
+
+ // Calculate total capacity and effective allocatable space
+ // For each disk, calculate how many containers can actually fit,
+ // since containers are written to individual disks, not spread across them.
+ // Example: disk1=9GB, disk2=14GB with 5GB containers
+ // (1*5GB) + (2*5GB) = 15GB → actually 3 containers
+ long totalCapacity = 0L;
+ long effectiveAllocatableSpace = 0L;
+ for (StorageReportProto report : storageReports) {
+ totalCapacity += report.getCapacity();
+ long usableSpace = VolumeUsage.getUsableSpace(report);
+ // Calculate how many containers can fit on this disk
+ long containersOnThisDisk = usableSpace / maxContainerSize;
+ // Add effective space (containers that fit * container size)
+ effectiveAllocatableSpace += containersOnThisDisk * maxContainerSize;
+ }
+
+ // Get pending allocations from tracker
+ long pendingAllocations = pendingContainerTracker.getPendingAllocationSize(node);
+
+ // Calculate effective remaining space after pending allocations
+ long effectiveRemaining = effectiveAllocatableSpace - pendingAllocations;
+
+ // Check if there's enough space for a new container
+ if (effectiveRemaining < maxContainerSize) {
+ LOG.info("Node {} insufficient space: capacity={}, effective allocatable={}, " +
+ "pending allocations={}, effective remaining={}, required={}",
+ node.getUuidString(), totalCapacity, effectiveAllocatableSpace,
+ pendingAllocations, effectiveRemaining, maxContainerSize);
+ return false;
+ }
+ }
+
+ return true;
+ } catch (Exception e) {
+ LOG.warn("Error checking space for pipeline {}", pipeline.getId(), e);
+ return true;
Review Comment:
Moved the code, there is no exception here.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org
For additional commands, e-mail: issues-help@ozone.apache.org
Re: [PR] HDDS-14921. Improve space accounting in SCM with In-Flight container allocation tracking. [ozone]
Posted by "ashishkumar50 (via GitHub)" <gi...@apache.org>.
ashishkumar50 commented on code in PR #10000:
URL: https://github.com/apache/ozone/pull/10000#discussion_r3050030672
##########
hadoop-hdds/server-scm/src/main/java/org/apache/hadoop/hdds/scm/node/PendingContainerTracker.java:
##########
@@ -0,0 +1,425 @@
+/*
+ * 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.node;
+
+import com.google.common.annotations.VisibleForTesting;
+import java.util.Collections;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Set;
+import java.util.UUID;
+import java.util.concurrent.ConcurrentHashMap;
+import org.apache.hadoop.hdds.protocol.DatanodeDetails;
+import org.apache.hadoop.hdds.protocol.proto.StorageContainerDatanodeProtocolProtos.StorageReportProto;
+import org.apache.hadoop.hdds.scm.container.ContainerID;
+import org.apache.hadoop.hdds.scm.pipeline.Pipeline;
+import org.apache.hadoop.ozone.container.common.volume.VolumeUsage;
+import org.apache.hadoop.util.Time;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * Tracks per-datanode pending container allocations at SCM using a Two Window Tumbling Bucket
+ * pattern (similar to HDFS HADOOP-3707).
+ *
+ * Two Window Tumbling Bucket for automatic aging and cleanup.
+ *
+ * How It Works:
+ * <li>Each DataNode has two sets: <b>currentWindow</b> and <b>previousWindow</b></li>
+ * <li>New allocations go into <b>currentWindow</b></li>
+ * <li>Every <b>ROLL_INTERVAL</b> (default 5 minutes):
+ * <ul>
+ * <li>previousWindow = currentWindow (shift)</li>
+ * <li>currentWindow = new empty set (reset)</li>
+ * <li>Old previousWindow is discarded (automatic aging)</li>
+ * </ul>
+ * </li>
+ * <li>When checking pending: return <b>union</b> of currentWindow + previousWindow</li>
+ *
+ *
+ * Example Timeline:
+ * <pre>
+ * Time | Action | CurrentWindow | PreviousWindow | Total Pending
+ * ------+---------------------------+---------------+----------------+--------------
+ * 00:00 | Allocate Container-1 | {C1} | {} | {C1}
+ * 00:02 | Allocate Container-2 | {C1, C2} | {} | {C1, C2}
+ * 00:05 | [ROLL] Window tumbles | {} | {C1, C2} | {C1, C2}
+ * 00:07 | Allocate Container-3 | {C3} | {C1, C2} | {C1, C2, C3}
+ * 00:08 | Report confirms C1 | {C3} | {C2} | {C2, C3}
+ * 00:10 | [ROLL] Window tumbles | {} | {C3} | {C3}
+ * | (C2 aged out if not reported)
+ * </pre>
+ *
+ * <p>Thread-safety: all mutations and reads for a given datanode run under
+ * {@code synchronized (bucket)} on that datanode's {@link TwoWindowBucket}, including
+ * map insert/remove, so concurrent record/remove/report paths cannot interleave or orphan
+ * a bucket after it was dropped from the map.</p>
+ */
+public class PendingContainerTracker {
+
+ private static final Logger LOG = LoggerFactory.getLogger(PendingContainerTracker.class);
+
+ /**
+ * Roll interval in milliseconds.
+ * Configurable via hdds.scm.container.pending.allocation.roll.interval.
+ * Default: 5 minutes.
+ * Containers automatically age out after 2 × rollIntervalMs.
+ */
+ private final long rollIntervalMs;
+
+ /**
+ * Map of DataNode UUID to TwoWindowBucket.
+ */
+ private final ConcurrentHashMap<UUID, TwoWindowBucket> datanodeBuckets;
+
+ /**
+ * Maximum container size in bytes.
+ */
+ private final long maxContainerSize;
+
+ /**
+ * Metrics for tracking pending containers (same instance as {@link SCMNodeManager}'s node metrics).
+ */
+ private final SCMNodeMetrics metrics;
+
+ /**
+ * Two-window bucket for a single DataNode.
+ * Contains current and previous window sets, plus last roll timestamp.
+ */
+ private static class TwoWindowBucket {
+ private Set<ContainerID> currentWindow = new HashSet<>();
+ private Set<ContainerID> previousWindow = new HashSet<>();
+ private long lastRollTime = Time.monotonicNow();
+ private final long rollIntervalMs;
+
+ TwoWindowBucket(long rollIntervalMs) {
+ this.rollIntervalMs = rollIntervalMs;
+ }
+
+ /**
+ * Roll the windows: previous = current, current = empty.
+ * Called when current time exceeds lastRollTime + rollIntervalMs.
+ */
+ synchronized void rollIfNeeded() {
+ long now = Time.monotonicNow();
+ if (now - lastRollTime >= rollIntervalMs) {
+ // Shift: current becomes previous
+ previousWindow = currentWindow;
+ // Reset: new empty current window
+ currentWindow = new HashSet<>();
+ lastRollTime = now;
+ LOG.debug("Rolled window. Previous window size: {}, Current window reset to empty", previousWindow.size());
+ }
+ }
+
+ /**
+ * Get union of both windows (all pending containers).
+ */
+ synchronized Set<ContainerID> getAllPending() {
+ Set<ContainerID> all = new HashSet<>();
+ all.addAll(currentWindow);
+ all.addAll(previousWindow);
+ return all;
+ }
+
+ /**
+ * Add container to current window.
+ */
+ synchronized boolean add(ContainerID containerID) {
+ return currentWindow.add(containerID);
+ }
+
+ /**
+ * Remove container from both windows.
+ */
+ synchronized boolean remove(ContainerID containerID) {
+ boolean removedFromCurrent = currentWindow.remove(containerID);
+ boolean removedFromPrevious = previousWindow.remove(containerID);
+ return removedFromCurrent || removedFromPrevious;
+ }
+
+ /**
+ * Check if either window is non-empty.
+ */
+ synchronized boolean isEmpty() {
+ return currentWindow.isEmpty() && previousWindow.isEmpty();
+ }
+
+ /**
+ * Count of pending containers in both windows.
+ */
+ synchronized int getCount() {
+ return currentWindow.size() + previousWindow.size();
Review Comment:
getAllPending is creating two new set which may be costly. Instead this looks less costly. Sumit has given comment above to avoid creating new list. If we want other way then we need to cache size value, which i think may not be needed here to store size as well.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org
For additional commands, e-mail: issues-help@ozone.apache.org
Re: [PR] HDDS-14921. Improve space accounting in SCM with In-Flight container allocation tracking. [ozone]
Posted by "szetszwo (via GitHub)" <gi...@apache.org>.
szetszwo commented on code in PR #10000:
URL: https://github.com/apache/ozone/pull/10000#discussion_r3175500259
##########
hadoop-hdds/server-scm/src/main/java/org/apache/hadoop/hdds/scm/node/SCMNodeManager.java:
##########
@@ -1103,6 +1103,27 @@ public void recordPendingAllocationForDatanode(DatanodeID datanodeID, ContainerI
pendingContainerTracker.recordPendingAllocationForDatanode(datanodeInfo, containerID);
}
+ @Override
+ public boolean checkSpaceAndRecordAllocation(DatanodeID datanodeID, ContainerID containerID) {
+ DatanodeInfo datanodeInfo = getNode(datanodeID);
+ if (datanodeInfo == null) {
+ LOG.warn("DatanodeInfo not found for node {}", datanodeID);
+ return false;
+ }
+ return pendingContainerTracker.checkSpaceAndRecordAllocation(datanodeInfo, containerID);
+ }
+
+ @Override
+ public void removePendingAllocationForDatanode(DatanodeID datanodeID, ContainerID containerID) {
+ DatanodeInfo datanodeInfo = getNode(datanodeID);
Review Comment:
@ashishkumar50 , we should get datanodeInfo outside the loop instead looking the same datanodeInfo up for each container.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org
For additional commands, e-mail: issues-help@ozone.apache.org
Re: [PR] HDDS-14921. Improve space accounting in SCM with In-Flight container allocation tracking. [ozone]
Posted by "ashishkumar50 (via GitHub)" <gi...@apache.org>.
ashishkumar50 commented on code in PR #10000:
URL: https://github.com/apache/ozone/pull/10000#discussion_r3187594757
##########
hadoop-hdds/server-scm/src/main/java/org/apache/hadoop/hdds/scm/node/PendingContainerTracker.java:
##########
@@ -189,6 +190,47 @@ public boolean hasEffectiveAllocatableSpaceForNewContainer(DatanodeInfo datanode
return false;
}
+ /**
+ * Atomically checks if the datanode has space for a new container and records the allocation
+ * if space is available. This prevents race conditions where multiple threads check space
+ * concurrently and over-allocate.
+ *
+ * @param datanodeInfo storage reports for the datanode
+ * @param containerID The container being allocated
+ * @return true if space was available and allocation was recorded, false otherwise
+ */
+ public boolean checkSpaceAndRecordAllocation(DatanodeInfo datanodeInfo, ContainerID containerID) {
+ Objects.requireNonNull(datanodeInfo, "datanodeInfo == null");
+ Objects.requireNonNull(containerID, "containerID == null");
+
+ TwoWindowBucket bucket = datanodeInfo.getPendingContainerAllocations();
+ synchronized (bucket) {
Review Comment:
Moved to TwoWindowBucket.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org
For additional commands, e-mail: issues-help@ozone.apache.org
Re: [PR] HDDS-14921. Improve space accounting in SCM with In-Flight container allocation tracking. [ozone]
Posted by "rakeshadr (via GitHub)" <gi...@apache.org>.
rakeshadr commented on code in PR #10000:
URL: https://github.com/apache/ozone/pull/10000#discussion_r3021573986
##########
hadoop-hdds/server-scm/src/main/java/org/apache/hadoop/hdds/scm/container/PendingContainerTracker.java:
##########
@@ -0,0 +1,338 @@
+/*
+ * 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;
+
+import com.google.common.annotations.VisibleForTesting;
+import java.util.Collections;
+import java.util.HashSet;
+import java.util.Set;
+import java.util.UUID;
+import java.util.concurrent.ConcurrentHashMap;
+import org.apache.hadoop.hdds.protocol.DatanodeDetails;
+import org.apache.hadoop.hdds.scm.container.metrics.SCMContainerManagerMetrics;
+import org.apache.hadoop.hdds.scm.pipeline.Pipeline;
+import org.apache.hadoop.util.Time;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * Tracks pending container allocations using a Two Window Tumbling Bucket pattern.
+ * Similar like HDFS HADOOP-3707.
+ *
+ * Two Window Tumbling Bucket for automatic aging and cleanup.
+ *
+ * How It Works:
+ * <li>Each DataNode has two sets: <b>currentWindow</b> and <b>previousWindow</b></li>
+ * <li>New allocations go into <b>currentWindow</b></li>
+ * <li>Every <b>ROLL_INTERVAL</b> (default 10 minutes):
+ * <ul>
+ * <li>previousWindow = currentWindow (shift)</li>
+ * <li>currentWindow = new empty set (reset)</li>
+ * <li>Old previousWindow is discarded (automatic aging)</li>
+ * </ul>
+ * </li>
+ * <li>When checking pending: return <b>union</b> of currentWindow + previousWindow</li>
+ *
+ *
+ * Example Timeline:
+ * <pre>
+ * Time | Action | CurrentWindow | PreviousWindow | Total Pending
+ * ------+---------------------------+---------------+----------------+--------------
+ * 00:00 | Allocate Container-1 | {C1} | {} | {C1}
+ * 00:05 | Allocate Container-2 | {C1, C2} | {} | {C1, C2}
+ * 00:10 | [ROLL] Window tumbles | {} | {C1, C2} | {C1, C2}
+ * 00:12 | Allocate Container-3 | {C3} | {C1, C2} | {C1, C2, C3}
+ * 00:15 | Report confirms C1 | {C3} | {C2} | {C2, C3}
+ * 00:20 | [ROLL] Window tumbles | {} | {C3} | {C3}
+ * | (C2 aged out if not reported)
+ * </pre>
+ *
+ */
+public class PendingContainerTracker {
+
+ private static final Logger LOG = LoggerFactory.getLogger(PendingContainerTracker.class);
+
+ /**
+ * Roll interval in milliseconds.
+ * Configurable via hdds.scm.container.pending-allocation.roll-interval.
+ * Default: 10 minutes.
+ * Containers automatically age out after 2 × rollIntervalMs.
+ */
+ private final long rollIntervalMs;
+
+ /**
+ * Map of DataNode UUID to TwoWindowBucket.
+ */
+ private final ConcurrentHashMap<UUID, TwoWindowBucket> datanodeBuckets;
+
+ /**
+ * Maximum container size in bytes.
+ */
+ private final long maxContainerSize;
+
+ /**
+ * Metrics for tracking pending containers.
+ */
+ private final SCMContainerManagerMetrics metrics;
+
+ /**
+ * Two-window bucket for a single DataNode.
+ * Contains current and previous window sets, plus last roll timestamp.
+ */
+ private static class TwoWindowBucket {
+ private Set<ContainerID> currentWindow = ConcurrentHashMap.newKeySet();
+ private Set<ContainerID> previousWindow = ConcurrentHashMap.newKeySet();
+ private long lastRollTime = Time.monotonicNow();
+ private final long rollIntervalMs;
+
+ TwoWindowBucket(long rollIntervalMs) {
+ this.rollIntervalMs = rollIntervalMs;
+ }
+
+ /**
+ * Roll the windows: previous = current, current = empty.
+ * Called when current time exceeds lastRollTime + rollIntervalMs.
+ */
+ synchronized void rollIfNeeded() {
+ long now = Time.monotonicNow();
+ if (now - lastRollTime >= rollIntervalMs) {
+ // Shift: current becomes previous
+ previousWindow = currentWindow;
+ // Reset: new empty current window
+ currentWindow = ConcurrentHashMap.newKeySet();
+ lastRollTime = now;
+ LOG.debug("Rolled window. Previous window size: {}, Current window reset to empty", previousWindow.size());
+ }
+ }
+
+ /**
+ * Get union of both windows (all pending containers).
+ */
+ synchronized Set<ContainerID> getAllPending() {
+ Set<ContainerID> all = new HashSet<>();
+ all.addAll(currentWindow);
+ all.addAll(previousWindow);
+ return all;
+ }
+
+ /**
+ * Add container to current window.
+ */
+ synchronized boolean add(ContainerID containerID) {
+ return currentWindow.add(containerID);
+ }
+
+ /**
+ * Remove container from both windows.
+ */
+ synchronized boolean remove(ContainerID containerID) {
+ boolean removedFromCurrent = currentWindow.remove(containerID);
+ boolean removedFromPrevious = previousWindow.remove(containerID);
+ return removedFromCurrent || removedFromPrevious;
+ }
+
+ /**
+ * Check if either window is non-empty.
+ */
+ synchronized boolean isEmpty() {
+ return currentWindow.isEmpty() && previousWindow.isEmpty();
+ }
+
+ /**
+ * Get count of all pending containers (union).
+ */
+ synchronized int getCount() {
+ return getAllPending().size();
+ }
+ }
+
+ public PendingContainerTracker(long maxContainerSize) {
+ this(maxContainerSize, 10 * 60 * 1000, null); // Default 10 minutes
+ }
+
+ public PendingContainerTracker(long maxContainerSize, long rollIntervalMs,
+ SCMContainerManagerMetrics metrics) {
+ this.datanodeBuckets = new ConcurrentHashMap<>();
+ this.maxContainerSize = maxContainerSize;
+ this.rollIntervalMs = rollIntervalMs;
+ this.metrics = metrics;
+ LOG.info("PendingContainerTracker initialized with maxContainerSize={}B, rollInterval={}ms",
+ maxContainerSize, rollIntervalMs);
+ }
+
+ /**
+ * Record a pending container allocation for all DataNodes in the pipeline.
+ * Container is added to the current window.
+ *
+ * @param pipeline The pipeline where container is allocated
+ * @param containerID The container being allocated
+ */
+ public void recordPendingAllocation(Pipeline pipeline, ContainerID containerID) {
+ if (pipeline == null || containerID == null) {
+ LOG.warn("Ignoring null pipeline or containerID");
+ return;
+ }
+
+ for (DatanodeDetails node : pipeline.getNodes()) {
+ recordPendingAllocationForDatanode(node, containerID);
+ }
+ }
+
+ /**
+ * Record a pending container allocation for a single DataNode.
+ * Container is added to the current window.
+ *
+ * @param node The DataNode where container is being allocated/replicated
+ * @param containerID The container being allocated/replicated
+ */
+ public void recordPendingAllocationForDatanode(DatanodeDetails node, ContainerID containerID) {
+ if (node == null || containerID == null) {
+ LOG.warn("Ignoring null node or containerID");
+ return;
+ }
+
+ TwoWindowBucket bucket = datanodeBuckets.computeIfAbsent(
+ node.getUuid(),
+ k -> new TwoWindowBucket(rollIntervalMs)
+ );
+
+ // Roll window if needed before adding
+ bucket.rollIfNeeded();
+
+ boolean added = bucket.add(containerID);
+ LOG.info("Recorded pending container {} on DataNode {}. Added={}, Total pending={}",
+ containerID, node.getUuidString(), added, bucket.getCount());
+
+ // Increment metrics counter
+ if (added && metrics != null) {
+ metrics.incNumPendingContainersAdded();
+ }
+ }
+
+ /**
+ * Remove a pending container allocation from a specific DataNode.
+ * Removes from both current and previous windows.
+ * Called when container is confirmed.
+ *
+ * @param node The DataNode
+ * @param containerID The container to remove from pending
+ */
+ public void removePendingAllocation(DatanodeDetails node, ContainerID containerID) {
+ if (node == null || containerID == null) {
+ return;
+ }
+
+ TwoWindowBucket bucket = datanodeBuckets.get(node.getUuid());
+ if (bucket != null) {
+ // Roll window if needed before removing
+ bucket.rollIfNeeded();
+
+ boolean removed = bucket.remove(containerID);
+ LOG.info("Removed pending container {} from DataNode {}. Removed={}, Remaining={}",
+ containerID, node.getUuidString(), removed, bucket.getCount());
+
+ // Increment metrics counter
+ if (removed && metrics != null) {
+ metrics.incNumPendingContainersRemoved();
+ }
+
+ // Cleanup empty buckets to prevent memory leak
+ if (bucket.isEmpty()) {
Review Comment:
Potentially hits concurrency issue. Say two threads entered this block.
`Thread-1 (removePendingAllocation)`: bucket.isEmpty(), returns true
`Thread-2 (recordPendingAllocationForDatanode)`: computeIfAbsent(uuid) returns same bucket
reference (key still exists), calls bucket.add(containerID) and now the bucket will be non-empty
`Thread-1: datanodeBuckets.remove(uuid, bucket)`, then removes the non-empty bucket and now the containerID will be in a detached bucket object, right?
I think, we need to add synchronization to avoid detached bucket object.
##########
hadoop-hdds/server-scm/src/test/java/org/apache/hadoop/hdds/scm/container/TestPendingContainerTracker.java:
##########
@@ -0,0 +1,375 @@
+/*
+ * 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;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+
+import java.io.IOException;
+import java.util.Set;
+import org.apache.hadoop.hdds.protocol.DatanodeDetails;
+import org.apache.hadoop.hdds.protocol.MockDatanodeDetails;
+import org.apache.hadoop.hdds.scm.pipeline.MockPipeline;
+import org.apache.hadoop.hdds.scm.pipeline.Pipeline;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+
+/**
+ * Tests for PendingContainerTracker.
+ */
+public class TestPendingContainerTracker {
+
+ private static final long MAX_CONTAINER_SIZE = 5L * 1024 * 1024 * 1024; // 5GB
+
+ private PendingContainerTracker tracker;
+ private Pipeline pipeline;
+ private DatanodeDetails dn1;
+ private DatanodeDetails dn2;
+ private DatanodeDetails dn3;
+ private ContainerID container1;
+ private ContainerID container2;
+ private ContainerID container3;
+
+ @BeforeEach
+ public void setUp() throws IOException {
+ tracker = new PendingContainerTracker(MAX_CONTAINER_SIZE);
+
+ // Create a 3-node Ratis pipeline
+ pipeline = MockPipeline.createPipeline(3);
+ dn1 = pipeline.getNodes().get(0);
+ dn2 = pipeline.getNodes().get(1);
+ dn3 = pipeline.getNodes().get(2);
+
+ container1 = ContainerID.valueOf(1L);
+ container2 = ContainerID.valueOf(2L);
+ container3 = ContainerID.valueOf(3L);
+ }
+
+ @Test
+ public void testRecordPendingAllocation() {
+ // Initially no pending containers
+ assertEquals(0, tracker.getPendingContainers(dn1).size());
+ assertEquals(0, tracker.getPendingAllocationSize(dn1));
+
+ // Record a pending allocation
+ tracker.recordPendingAllocation(pipeline, container1);
+
+ // All 3 DNs should have the container pending
+ assertEquals(1, tracker.getPendingContainers(dn1).size());
+ assertEquals(1, tracker.getPendingContainers(dn2).size());
+ assertEquals(1, tracker.getPendingContainers(dn3).size());
+
+ // Size should be MAX_CONTAINER_SIZE for each DN
+ assertEquals(MAX_CONTAINER_SIZE, tracker.getPendingAllocationSize(dn1));
+ assertEquals(MAX_CONTAINER_SIZE, tracker.getPendingAllocationSize(dn2));
+ assertEquals(MAX_CONTAINER_SIZE, tracker.getPendingAllocationSize(dn3));
+ }
+
+ @Test
+ public void testRecordMultiplePendingAllocations() {
+ tracker.recordPendingAllocation(pipeline, container1);
+ tracker.recordPendingAllocation(pipeline, container2);
+ tracker.recordPendingAllocation(pipeline, container3);
+
+ // Each DN should have 3 pending containers
+ assertEquals(3, tracker.getPendingContainers(dn1).size());
+ assertEquals(3, tracker.getPendingContainers(dn2).size());
+ assertEquals(3, tracker.getPendingContainers(dn3).size());
+
+ // Size should be 3 × MAX_CONTAINER_SIZE
+ assertEquals(3 * MAX_CONTAINER_SIZE, tracker.getPendingAllocationSize(dn1));
+ }
+
+ @Test
+ public void testIdempotentRecording() {
+ tracker.recordPendingAllocation(pipeline, container1);
+ tracker.recordPendingAllocation(pipeline, container1); // Duplicate
+
+ // Should still be 1 container (Set deduplication)
+ assertEquals(1, tracker.getPendingContainers(dn1).size());
+ assertEquals(MAX_CONTAINER_SIZE, tracker.getPendingAllocationSize(dn1));
+ }
+
+ @Test
+ public void testRemovePendingAllocation() {
+ tracker.recordPendingAllocation(pipeline, container1);
+ tracker.recordPendingAllocation(pipeline, container2);
+
+ assertEquals(2, tracker.getPendingContainers(dn1).size());
+
+ // Remove one container from DN1
+ tracker.removePendingAllocation(dn1, container1);
+
+ assertEquals(1, tracker.getPendingContainers(dn1).size());
+ assertEquals(MAX_CONTAINER_SIZE, tracker.getPendingAllocationSize(dn1));
+
+ // DN2 and DN3 should still have both containers
+ assertEquals(2, tracker.getPendingContainers(dn2).size());
+ assertEquals(2, tracker.getPendingContainers(dn3).size());
+ }
+
+ @Test
+ public void testRemovePendingAllocationFromPipeline() {
+ tracker.recordPendingAllocation(pipeline, container1);
+ tracker.recordPendingAllocation(pipeline, container2);
+
+ // Remove container1 from all nodes in pipeline
+ for (DatanodeDetails dn : pipeline.getNodes()) {
+ tracker.removePendingAllocation(dn, container1);
+ }
+
+ // All DNs should have only container2 remaining
+ assertEquals(1, tracker.getPendingContainers(dn1).size());
+ assertEquals(1, tracker.getPendingContainers(dn2).size());
+ assertEquals(1, tracker.getPendingContainers(dn3).size());
+ }
+
+ @Test
+ public void testRemoveNonExistentContainer() {
+ tracker.recordPendingAllocation(pipeline, container1);
+
+ // Remove a container that was never added - should not throw exception
+ tracker.removePendingAllocation(dn1, container2);
+
+ // DN1 should still have container1
+ assertEquals(1, tracker.getPendingContainers(dn1).size());
+ }
+
+ @Test
+ public void testGetPendingContainers() {
+ tracker.recordPendingAllocation(pipeline, container1);
+ tracker.recordPendingAllocation(pipeline, container2);
+
+ Set<ContainerID> pending = tracker.getPendingContainers(dn1);
+
+ assertEquals(2, pending.size());
+ assertThat(pending.contains(container1));
+ assertThat(pending.contains(container2));
+
+ // Returned set should be a copy - modifying it shouldn't affect tracker
+ pending.add(container3);
+ assertEquals(2, tracker.getPendingContainers(dn1).size()); // Should still be 2
+ }
+
+ @Test
+ public void testGetPendingContainersForNonExistentDN() {
+ DatanodeDetails unknownDN = MockDatanodeDetails.randomDatanodeDetails();
+
+ Set<ContainerID> pending = tracker.getPendingContainers(unknownDN);
+
+ assertThat(pending.isEmpty());
+ }
+
+ @Test
+ public void testGetTotalPendingCount() {
+ assertEquals(0, tracker.getTotalPendingCount());
+
+ tracker.recordPendingAllocation(pipeline, container1);
+
+ // 1 container × 3 DNs = 3 total pending
+ assertEquals(3, tracker.getTotalPendingCount());
+
+ tracker.recordPendingAllocation(pipeline, container2);
+
+ // 2 containers × 3 DNs = 6 total pending
+ assertEquals(6, tracker.getTotalPendingCount());
+
+ // Remove from one DN
+ tracker.removePendingAllocation(dn1, container1);
+
+ // (2 containers × 2 DNs) + (1 container × 1 DN) = 5 total
+ assertEquals(5, tracker.getTotalPendingCount());
+ }
+
+ @Test
+ public void testConcurrentModification() throws InterruptedException {
+ // Test thread-safety by having multiple threads add/remove containers
+ final int numThreads = 10;
+ final int operationsPerThread = 100;
+
+ Thread[] threads = new Thread[numThreads];
+
+ for (int i = 0; i < numThreads; i++) {
+ final int threadId = i;
+ threads[i] = new Thread(() -> {
+ for (int j = 0; j < operationsPerThread; j++) {
+ ContainerID cid = ContainerID.valueOf(threadId * 1000L + j);
+ tracker.recordPendingAllocation(pipeline, cid);
+
+ if (j % 2 == 0) {
+ tracker.removePendingAllocation(dn1, cid);
+ }
+ }
+ });
+ }
+
+ // Start all threads
+ for (Thread thread : threads) {
+ thread.start();
+ }
+
+ // Wait for all to finish
+ for (Thread thread : threads) {
+ thread.join();
+ }
+
+ // Verify no exceptions occurred and counts are reasonable
+ assertThat(tracker.getTotalPendingCount() >= 0);
+ assertThat(tracker.getDataNodeCount() <= 3);
+ }
+
+ @Test
+ public void testMemoryCleanupOnEmptySet() {
+ tracker.recordPendingAllocation(pipeline, container1);
+
+ assertEquals(3, tracker.getDataNodeCount());
+
+ // Remove the only pending container from DN1
+ tracker.removePendingAllocation(dn1, container1);
+
+ // DN1 should be removed from the map (memory cleanup)
+ assertEquals(2, tracker.getDataNodeCount());
+ }
+
+ @Test
+ public void testPendingContainer() {
+ // Simulate allocation and confirmation flow
+
+ // Allocate 3 containers
+ tracker.recordPendingAllocation(pipeline, container1);
+ tracker.recordPendingAllocation(pipeline, container2);
+ tracker.recordPendingAllocation(pipeline, container3);
+
+ // Each DN should have 3 pending, 15GB total
+ assertEquals(3, tracker.getPendingContainers(dn1).size());
+ assertEquals(3 * MAX_CONTAINER_SIZE, tracker.getPendingAllocationSize(dn1));
+
+ // DN1 confirms container1 via container report
+ tracker.removePendingAllocation(dn1, container1);
+
+ // DN1 now has 2 pending, 10GB
+ assertEquals(2, tracker.getPendingContainers(dn1).size());
+ assertEquals(2 * MAX_CONTAINER_SIZE, tracker.getPendingAllocationSize(dn1));
+
+ // DN2 and DN3 still have 3 pending
+ assertEquals(3, tracker.getPendingContainers(dn2).size());
+ assertEquals(3, tracker.getPendingContainers(dn3).size());
+
+ // All DNs eventually confirm all containers
+ for (DatanodeDetails dn : pipeline.getNodes()) {
+ tracker.removePendingAllocation(dn, container1);
+ tracker.removePendingAllocation(dn, container2);
+ tracker.removePendingAllocation(dn, container3);
+ }
+
+ // All DNs should have 0 pending
+ assertEquals(0, tracker.getPendingContainers(dn1).size());
+ assertEquals(0, tracker.getPendingContainers(dn2).size());
+ assertEquals(0, tracker.getPendingContainers(dn3).size());
+ assertEquals(0, tracker.getTotalPendingCount());
+ assertEquals(0, tracker.getDataNodeCount());
+ }
+
+ @Test
+ public void testRemoveFromBothWindows() {
Review Comment:
Do we have test scenario covering roll over?
The two-window rolling behavior (container in previousWindow roll after 2× interval). Say, add C1 in currentWindow, then moves C1 to previousWindow, then wait for the roll over.
##########
hadoop-hdds/server-scm/src/main/java/org/apache/hadoop/hdds/scm/container/IncrementalContainerReportHandler.java:
##########
@@ -103,6 +112,13 @@ protected void processICR(IncrementalContainerReportFromDatanode report,
}
if (ContainerReportValidator.validate(container, dd, replicaProto)) {
processContainerReplica(dd, container, replicaProto, publisher, detailsForLogging);
+
+ // Remove from pending tracker when container is added to DN
+ if (!alreadyOnDn && getContainerManager() instanceof ContainerManagerImpl) {
+ ((ContainerManagerImpl) getContainerManager())
+ .getPendingContainerTracker()
+ .removePendingAllocation(dd, id);
Review Comment:
Say, DN is healthy, all containers confirmed, no new allocations → that DN's bucket never rolls even though heartbeats come every 30 seconds, right?
```
t=0 Container C1 allocated → pending recorded in tracker
t=60-120 FCR arrives from DN
→ cid = C1
→ alreadyInDn = expectedContainersInDatanode.remove(C1) = FALSE
→ !alreadyInDn = TRUE → removePendingAllocation called → rollIfNeeded fires ✓
→ C1 added to NM DN-set
```
How abt rolls on every `processHeartbeat`, every 30 seconds regardless of container state changes ?
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org
For additional commands, e-mail: issues-help@ozone.apache.org
Re: [PR] HDDS-14921. Improve space accounting in SCM with In-Flight container allocation tracking. [ozone]
Posted by "ashishkumar50 (via GitHub)" <gi...@apache.org>.
ashishkumar50 commented on PR #10000:
URL: https://github.com/apache/ozone/pull/10000#issuecomment-4378389820
> > ... hasEnoughSpace and recordPendingAllocation methods as we need this during replication which is used by placement policy for space check. ...
>
> @ashishkumar50 , hasEnoughSpace is unusable since it only checks the space but not updates the value. It will have synchronization issue similar to [#10000 (comment)](https://github.com/apache/ozone/pull/10000#discussion_r3162988799)
I have removed for `hasEnoughSpace,` from this PR but as i said we need it for placement policy which is used by replication.
I wanted to allow placement policy to use `hasEnoughSpace` and RM to use `checkSpaceAndAdd`. Because placement policy doesn't require container for checking space availability for a DN.
We can discuss more about this in [HDDS-14924](https://issues.apache.org/jira/browse/HDDS-14924).
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org
For additional commands, e-mail: issues-help@ozone.apache.org
Re: [PR] HDDS-14921. Improve space accounting in SCM with In-Flight container allocation tracking. [ozone]
Posted by "ashishkumar50 (via GitHub)" <gi...@apache.org>.
ashishkumar50 commented on code in PR #10000:
URL: https://github.com/apache/ozone/pull/10000#discussion_r3050013136
##########
hadoop-hdds/server-scm/src/main/java/org/apache/hadoop/hdds/scm/node/PendingContainerTracker.java:
##########
@@ -0,0 +1,425 @@
+/*
+ * 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.node;
+
+import com.google.common.annotations.VisibleForTesting;
+import java.util.Collections;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Set;
+import java.util.UUID;
+import java.util.concurrent.ConcurrentHashMap;
+import org.apache.hadoop.hdds.protocol.DatanodeDetails;
+import org.apache.hadoop.hdds.protocol.proto.StorageContainerDatanodeProtocolProtos.StorageReportProto;
+import org.apache.hadoop.hdds.scm.container.ContainerID;
+import org.apache.hadoop.hdds.scm.pipeline.Pipeline;
+import org.apache.hadoop.ozone.container.common.volume.VolumeUsage;
+import org.apache.hadoop.util.Time;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * Tracks per-datanode pending container allocations at SCM using a Two Window Tumbling Bucket
+ * pattern (similar to HDFS HADOOP-3707).
+ *
+ * Two Window Tumbling Bucket for automatic aging and cleanup.
+ *
+ * How It Works:
+ * <li>Each DataNode has two sets: <b>currentWindow</b> and <b>previousWindow</b></li>
+ * <li>New allocations go into <b>currentWindow</b></li>
+ * <li>Every <b>ROLL_INTERVAL</b> (default 5 minutes):
+ * <ul>
+ * <li>previousWindow = currentWindow (shift)</li>
+ * <li>currentWindow = new empty set (reset)</li>
+ * <li>Old previousWindow is discarded (automatic aging)</li>
+ * </ul>
+ * </li>
+ * <li>When checking pending: return <b>union</b> of currentWindow + previousWindow</li>
+ *
+ *
+ * Example Timeline:
+ * <pre>
+ * Time | Action | CurrentWindow | PreviousWindow | Total Pending
+ * ------+---------------------------+---------------+----------------+--------------
+ * 00:00 | Allocate Container-1 | {C1} | {} | {C1}
+ * 00:02 | Allocate Container-2 | {C1, C2} | {} | {C1, C2}
+ * 00:05 | [ROLL] Window tumbles | {} | {C1, C2} | {C1, C2}
+ * 00:07 | Allocate Container-3 | {C3} | {C1, C2} | {C1, C2, C3}
+ * 00:08 | Report confirms C1 | {C3} | {C2} | {C2, C3}
+ * 00:10 | [ROLL] Window tumbles | {} | {C3} | {C3}
+ * | (C2 aged out if not reported)
+ * </pre>
+ *
+ * <p>Thread-safety: all mutations and reads for a given datanode run under
+ * {@code synchronized (bucket)} on that datanode's {@link TwoWindowBucket}, including
+ * map insert/remove, so concurrent record/remove/report paths cannot interleave or orphan
+ * a bucket after it was dropped from the map.</p>
+ */
+public class PendingContainerTracker {
+
+ private static final Logger LOG = LoggerFactory.getLogger(PendingContainerTracker.class);
+
+ /**
+ * Roll interval in milliseconds.
+ * Configurable via hdds.scm.container.pending.allocation.roll.interval.
+ * Default: 5 minutes.
+ * Containers automatically age out after 2 × rollIntervalMs.
+ */
+ private final long rollIntervalMs;
+
+ /**
+ * Map of DataNode UUID to TwoWindowBucket.
+ */
+ private final ConcurrentHashMap<UUID, TwoWindowBucket> datanodeBuckets;
+
+ /**
+ * Maximum container size in bytes.
+ */
+ private final long maxContainerSize;
+
+ /**
+ * Metrics for tracking pending containers (same instance as {@link SCMNodeManager}'s node metrics).
+ */
+ private final SCMNodeMetrics metrics;
+
+ /**
+ * Two-window bucket for a single DataNode.
+ * Contains current and previous window sets, plus last roll timestamp.
+ */
+ private static class TwoWindowBucket {
+ private Set<ContainerID> currentWindow = new HashSet<>();
+ private Set<ContainerID> previousWindow = new HashSet<>();
+ private long lastRollTime = Time.monotonicNow();
+ private final long rollIntervalMs;
+
+ TwoWindowBucket(long rollIntervalMs) {
+ this.rollIntervalMs = rollIntervalMs;
+ }
+
+ /**
+ * Roll the windows: previous = current, current = empty.
+ * Called when current time exceeds lastRollTime + rollIntervalMs.
+ */
+ synchronized void rollIfNeeded() {
+ long now = Time.monotonicNow();
+ if (now - lastRollTime >= rollIntervalMs) {
Review Comment:
Handled based on if condition as per Aswin's comment. As we have just two bucket avoiding while loop here.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org
For additional commands, e-mail: issues-help@ozone.apache.org
Re: [PR] HDDS-14921. Improve space accounting in SCM with In-Flight container allocation tracking. [ozone]
Posted by "aswinshakil (via GitHub)" <gi...@apache.org>.
aswinshakil commented on code in PR #10000:
URL: https://github.com/apache/ozone/pull/10000#discussion_r3048384046
##########
hadoop-hdds/server-scm/src/main/java/org/apache/hadoop/hdds/scm/container/ContainerManagerImpl.java:
##########
Review Comment:
@rakeshadr @ashishkr200 `pipelineManager.hasEnoughSpace` is not a synchronized operation on the datanodes. We take lock on the pipeline `synchronized (pipeline.getId())`. Still two different pipelines can still allocate container on the same datanode.
We record the pending allocation on only Line 289. Until the code reaches that point multiple pipeline will be allocated to the same space on the datanode.
Let's say we only have 6GB space available in d1.
Pipeline 1: d1, d2, d3
Pipeline 2: d1, d4, d5
When we allocate container on both the pipeline, will get past `pipelineManager.hasEnoughSpace` and both will be allocated container 5GB *2 = 10GB. But we only have 6GB on d1
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org
For additional commands, e-mail: issues-help@ozone.apache.org
Re: [PR] HDDS-14921. Improve space accounting in SCM with In-Flight container allocation tracking. [ozone]
Posted by "ashishkumar50 (via GitHub)" <gi...@apache.org>.
ashishkumar50 commented on code in PR #10000:
URL: https://github.com/apache/ozone/pull/10000#discussion_r3035997148
##########
hadoop-hdds/server-scm/src/main/java/org/apache/hadoop/hdds/scm/container/ContainerReportHandler.java:
##########
@@ -175,6 +175,15 @@ public void onMessage(final ContainerReportFromDatanode reportFromDatanode,
if (!alreadyInDn) {
// This is a new Container not in the nodeManager -> dn map yet
getNodeManager().addContainer(datanodeDetails, cid);
+
+ // Remove from pending tracker when container is added to DN
+ // This container was just confirmed for the first time on this DN
+ // No need to remove on subsequent reports (it's already been removed)
+ if (container != null && getContainerManager() instanceof ContainerManagerImpl) {
Review Comment:
Moved to node package, so not required these conversions now.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org
For additional commands, e-mail: issues-help@ozone.apache.org
Re: [PR] HDDS-14921. Improve space accounting in SCM with In-Flight container allocation tracking. [ozone]
Posted by "ashishkumar50 (via GitHub)" <gi...@apache.org>.
ashishkumar50 commented on PR #10000:
URL: https://github.com/apache/ozone/pull/10000#issuecomment-4567385707
> @ashishkumar50 , sorry for the late reply. Will review this soon.
>
> BTW, could you resolve the conflict?
@szetszwo, conflicts are resolved. Can you please take a look.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org
For additional commands, e-mail: issues-help@ozone.apache.org
Re: [PR] HDDS-14921. Improve space accounting in SCM with In-Flight container allocation tracking. [ozone]
Posted by "szetszwo (via GitHub)" <gi...@apache.org>.
szetszwo commented on code in PR #10000:
URL: https://github.com/apache/ozone/pull/10000#discussion_r3328959533
##########
hadoop-hdds/server-scm/src/main/java/org/apache/hadoop/hdds/scm/node/PendingContainerTracker.java:
##########
@@ -158,52 +177,36 @@ public PendingContainerTracker(long maxContainerSize, long rollIntervalMs, SCMNo
}
/**
- * Whether the datanode can fit another container of {@link #maxContainerSize} after accounting for
- * SCM pending allocations for {@code node} (this tracker) and usable space across volumes on
- * {@code datanodeInfo}. Pending bytes are count × {@code maxContainerSize};
- * effective allocatable space sums full-container slots per storage report.
+ * Atomically checks if the datanode has space for a new container and records the allocation
+ * if space is available. The check-and-add atomicity is enforced inside
+ * {@link TwoWindowBucket#checkSpaceAndAdd}.
*
- * @param datanodeInfo storage reports for the datanode
+ * @param datanodeInfo datanode whose storage reports and pending bucket
+ * @param containerID the container being allocated
+ * @return true if space was available and the allocation was recorded, false otherwise
*/
- public boolean hasEffectiveAllocatableSpaceForNewContainer(DatanodeInfo datanodeInfo) {
+ public boolean checkSpaceAndRecordAllocation(DatanodeInfo datanodeInfo, ContainerID containerID) {
Objects.requireNonNull(datanodeInfo, "datanodeInfo == null");
+ Objects.requireNonNull(containerID, "containerID == null");
- long pendingAllocationSize = datanodeInfo.getPendingContainerAllocations().getCount() * maxContainerSize;
List<StorageReportProto> storageReports = datanodeInfo.getStorageReports();
Objects.requireNonNull(storageReports, "storageReports == null");
if (storageReports.isEmpty()) {
return false;
}
- long effectiveAllocatableSpace = 0L;
- for (StorageReportProto report : storageReports) {
- long usableSpace = VolumeUsage.getUsableSpace(report);
- long containersOnThisDisk = usableSpace / maxContainerSize;
- effectiveAllocatableSpace += containersOnThisDisk * maxContainerSize;
- if (effectiveAllocatableSpace - pendingAllocationSize >= maxContainerSize) {
- return true;
- }
- }
- if (metrics != null) {
- metrics.incNumSkippedFullNodeContainerAllocation();
- }
- return false;
- }
- /**
- * Record a pending container allocation for a single DataNode.
- * Container is added to the current window.
- *
- * @param containerID The container being allocated/replicated
- */
- public void recordPendingAllocationForDatanode(DatanodeInfo datanodeInfo, ContainerID containerID) {
- Objects.requireNonNull(containerID, "containerID == null");
- if (datanodeInfo == null) {
- return;
- }
- final boolean added = datanodeInfo.getPendingContainerAllocations().add(containerID);
- if (added && metrics != null) {
- metrics.incNumPendingContainersAdded();
+ boolean added = datanodeInfo.getPendingContainerAllocations()
+ .checkSpaceAndAdd(storageReports, maxContainerSize, containerID);
+ if (added) {
+ if (metrics != null) {
+ metrics.incNumPendingContainersAdded();
+ }
+ } else {
+ if (metrics != null) {
+ metrics.incNumSkippedFullNodeContainerAllocation();
+ }
}
Review Comment:
Check null first:
```java
if (metrics != null) {
if (added) {
metrics.incNumPendingContainersAdded();
} else {
metrics.incNumSkippedFullNodeContainerAllocation();
}
}
```
##########
hadoop-hdds/server-scm/src/main/java/org/apache/hadoop/hdds/scm/pipeline/PipelineManagerImpl.java:
##########
@@ -634,22 +636,23 @@ private boolean isOpenWithUnregisteredNodes(Pipeline pipeline) {
}
@Override
- public boolean hasEnoughSpace(Pipeline pipeline) {
- for (DatanodeDetails node : pipeline.getNodes()) {
- if (!nodeManager.hasSpaceForNewContainerAllocation(node.getID())) {
+ public boolean checkSpaceAndRecordAllocation(Pipeline pipeline, ContainerID containerID) {
+ List<DatanodeDetails> successfulNodes = new ArrayList<>();
+ for (DatanodeDetails dn : pipeline.getNodes()) {
Review Comment:
We should getDatanodeInfo first:
```java
public boolean checkSpaceAndRecordAllocation(Pipeline pipeline, ContainerID containerID) {
final Set<DatanodeDetails> datanodeDetails = pipeline.getNodeSet();
final List<DatanodeInfo> datanodeInfos = new ArrayList<>(datanodeDetails.size());
for (DatanodeDetails dn : datanodeDetails) {
final DatanodeInfo info = nodeManager.getDatanodeInfo(dn);
if (info == null) {
LOG.warn("DatanodeInfo not found for {}", dn.getID());
return false;
}
datanodeInfos.add(info);
}
final List<DatanodeInfo> successfulNodes = new ArrayList<>(datanodeInfos.size());
for (DatanodeInfo dn : datanodeInfos) {
if (!nodeManager.checkSpaceAndRecordAllocation(dn, containerID)) {
for (DatanodeInfo rollbackNode : successfulNodes) {
nodeManager.removePendingAllocationForDatanode(rollbackNode, containerID);
}
return false;
}
successfulNodes.add(dn);
}
return true;
}
```
##########
hadoop-hdds/server-scm/src/main/java/org/apache/hadoop/hdds/scm/node/PendingContainerTracker.java:
##########
@@ -148,6 +139,34 @@ synchronized boolean remove(ContainerID containerID) {
synchronized int getCount() {
return currentWindow.size() + previousWindow.size();
}
+
+ /**
+ * Atomically checks whether there is allocatable space for one more container of
+ * {@code maxContainerSize} given the current pending count, and adds {@code containerID}
+ * to the current window if so.
+ *
+ * @param storageReports storage reports for the datanode
+ * @param maxContainerSize maximum size of a single container in bytes
+ * @param containerID the container being allocated
+ * @return true if space was available and the container was recorded, false otherwise
+ */
+ synchronized boolean checkSpaceAndAdd(
+ List<StorageReportProto> storageReports, long maxContainerSize, ContainerID containerID) {
+ long pendingAllocationSize = getCount() * maxContainerSize;
+ long effectiveAllocatableSpace = 0L;
+ for (StorageReportProto report : storageReports) {
+ long usableSpace = VolumeUsage.getUsableSpace(report);
+ long containersOnThisDisk = usableSpace / maxContainerSize;
+ effectiveAllocatableSpace += containersOnThisDisk * maxContainerSize;
+ if (effectiveAllocatableSpace - pendingAllocationSize >= maxContainerSize) {
Review Comment:
Use count instead of size (Cc @rakeshadr):
```java
synchronized boolean checkSpaceAndAdd(
List<StorageReportProto> storageReports, long maxContainerSize, ContainerID containerID) {
final int pendingAllocationCount = getCount();
long allocatableCount = 0;
for (StorageReportProto report : storageReports) {
final long allocatableCountOnThisDisk = VolumeUsage.getUsableSpace(report) / maxContainerSize;
allocatableCount += allocatableCountOnThisDisk;
if (allocatableCount > pendingAllocationCount) {
final boolean added = currentWindow.add(containerID);
LOG.debug("Recorded pending container {} on DataNode {}. Added={}, Total pending={}",
containerID, datanodeID, added, getCount());
return added;
}
}
return false;
}
}
```
##########
hadoop-hdds/server-scm/src/main/java/org/apache/hadoop/hdds/scm/node/PendingContainerTracker.java:
##########
@@ -148,6 +139,34 @@ synchronized boolean remove(ContainerID containerID) {
synchronized int getCount() {
return currentWindow.size() + previousWindow.size();
}
+
+ /**
+ * Atomically checks whether there is allocatable space for one more container of
+ * {@code maxContainerSize} given the current pending count, and adds {@code containerID}
+ * to the current window if so.
+ *
+ * @param storageReports storage reports for the datanode
+ * @param maxContainerSize maximum size of a single container in bytes
+ * @param containerID the container being allocated
+ * @return true if space was available and the container was recorded, false otherwise
+ */
+ synchronized boolean checkSpaceAndAdd(
+ List<StorageReportProto> storageReports, long maxContainerSize, ContainerID containerID) {
+ long pendingAllocationSize = getCount() * maxContainerSize;
+ long effectiveAllocatableSpace = 0L;
+ for (StorageReportProto report : storageReports) {
+ long usableSpace = VolumeUsage.getUsableSpace(report);
+ long containersOnThisDisk = usableSpace / maxContainerSize;
+ effectiveAllocatableSpace += containersOnThisDisk * maxContainerSize;
+ if (effectiveAllocatableSpace - pendingAllocationSize >= maxContainerSize) {
+ boolean added = currentWindow.add(containerID);
+ LOG.debug("Recorded pending container {} on DataNode {}. Added={}, Total pending={}",
+ containerID, datanodeID, added, getCount());
+ return true;
Review Comment:
return added;
##########
hadoop-hdds/server-scm/src/main/java/org/apache/hadoop/hdds/scm/node/NodeManager.java:
##########
@@ -185,17 +185,23 @@ default int getAllNodeCount() {
DatanodeInfo getDatanodeInfo(DatanodeDetails dn);
/**
- * True if the node can accept another container of the given size.
+ * Atomically checks if the datanode has space for a new container and records the allocation
+ * if space is available. This prevents race conditions where multiple threads check space
+ * concurrently and over-allocate.
+ *
+ * @param datanodeID the ID of the DataNode receiving the allocation
+ * @param containerID the container being allocated
+ * @return true if space was available and allocation was recorded, false otherwise
*/
- boolean hasSpaceForNewContainerAllocation(DatanodeID datanodeID);
+ boolean checkSpaceAndRecordAllocation(DatanodeID datanodeID, ContainerID containerID);
Review Comment:
Pass DatanodeInfo.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org
For additional commands, e-mail: issues-help@ozone.apache.org
Re: [PR] HDDS-14921. Improve space accounting in SCM with In-Flight container allocation tracking. [ozone]
Posted by "ashishkumar50 (via GitHub)" <gi...@apache.org>.
ashishkumar50 commented on code in PR #10000:
URL: https://github.com/apache/ozone/pull/10000#discussion_r3036001082
##########
hadoop-hdds/server-scm/src/main/java/org/apache/hadoop/hdds/scm/node/PendingContainerTracker.java:
##########
@@ -0,0 +1,338 @@
+/*
+ * 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;
+
+import com.google.common.annotations.VisibleForTesting;
+import java.util.Collections;
+import java.util.HashSet;
+import java.util.Set;
+import java.util.UUID;
+import java.util.concurrent.ConcurrentHashMap;
+import org.apache.hadoop.hdds.protocol.DatanodeDetails;
+import org.apache.hadoop.hdds.scm.container.metrics.SCMContainerManagerMetrics;
+import org.apache.hadoop.hdds.scm.pipeline.Pipeline;
+import org.apache.hadoop.util.Time;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * Tracks pending container allocations using a Two Window Tumbling Bucket pattern.
+ * Similar like HDFS HADOOP-3707.
+ *
+ * Two Window Tumbling Bucket for automatic aging and cleanup.
+ *
+ * How It Works:
+ * <li>Each DataNode has two sets: <b>currentWindow</b> and <b>previousWindow</b></li>
+ * <li>New allocations go into <b>currentWindow</b></li>
+ * <li>Every <b>ROLL_INTERVAL</b> (default 10 minutes):
+ * <ul>
+ * <li>previousWindow = currentWindow (shift)</li>
+ * <li>currentWindow = new empty set (reset)</li>
+ * <li>Old previousWindow is discarded (automatic aging)</li>
+ * </ul>
+ * </li>
+ * <li>When checking pending: return <b>union</b> of currentWindow + previousWindow</li>
+ *
+ *
+ * Example Timeline:
+ * <pre>
+ * Time | Action | CurrentWindow | PreviousWindow | Total Pending
+ * ------+---------------------------+---------------+----------------+--------------
+ * 00:00 | Allocate Container-1 | {C1} | {} | {C1}
+ * 00:05 | Allocate Container-2 | {C1, C2} | {} | {C1, C2}
+ * 00:10 | [ROLL] Window tumbles | {} | {C1, C2} | {C1, C2}
+ * 00:12 | Allocate Container-3 | {C3} | {C1, C2} | {C1, C2, C3}
+ * 00:15 | Report confirms C1 | {C3} | {C2} | {C2, C3}
+ * 00:20 | [ROLL] Window tumbles | {} | {C3} | {C3}
+ * | (C2 aged out if not reported)
+ * </pre>
+ *
+ */
+public class PendingContainerTracker {
+
+ private static final Logger LOG = LoggerFactory.getLogger(PendingContainerTracker.class);
+
+ /**
+ * Roll interval in milliseconds.
+ * Configurable via hdds.scm.container.pending-allocation.roll-interval.
+ * Default: 10 minutes.
+ * Containers automatically age out after 2 × rollIntervalMs.
+ */
+ private final long rollIntervalMs;
+
+ /**
+ * Map of DataNode UUID to TwoWindowBucket.
+ */
+ private final ConcurrentHashMap<UUID, TwoWindowBucket> datanodeBuckets;
+
+ /**
+ * Maximum container size in bytes.
+ */
+ private final long maxContainerSize;
+
+ /**
+ * Metrics for tracking pending containers.
+ */
+ private final SCMContainerManagerMetrics metrics;
+
+ /**
+ * Two-window bucket for a single DataNode.
+ * Contains current and previous window sets, plus last roll timestamp.
+ */
+ private static class TwoWindowBucket {
+ private Set<ContainerID> currentWindow = ConcurrentHashMap.newKeySet();
+ private Set<ContainerID> previousWindow = ConcurrentHashMap.newKeySet();
+ private long lastRollTime = Time.monotonicNow();
+ private final long rollIntervalMs;
+
+ TwoWindowBucket(long rollIntervalMs) {
+ this.rollIntervalMs = rollIntervalMs;
+ }
+
+ /**
+ * Roll the windows: previous = current, current = empty.
+ * Called when current time exceeds lastRollTime + rollIntervalMs.
+ */
+ synchronized void rollIfNeeded() {
Review Comment:
Roll will be done when node report comes which is every minute, so old entries will get clear.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org
For additional commands, e-mail: issues-help@ozone.apache.org
Re: [PR] HDDS-14921. Improve space accounting in SCM with In-Flight container allocation tracking. [ozone]
Posted by "ashishkumar50 (via GitHub)" <gi...@apache.org>.
ashishkumar50 commented on PR #10000:
URL: https://github.com/apache/ozone/pull/10000#issuecomment-4316003123
> @ashishkumar50 , thanks for the update!
>
> Let's have another subtask to do some refactoring:
>
> * Remove DatanodeBuckets map. Add TwoWindowBucket to DatanodeInfo
> * Remove containerSize parameter from pipelineManager.hasEnoughSpace(pipeline, containerSize)).
> * Remove the DatanodeDetails parameter from hasEffectiveAllocatableSpaceForNewContainer(..) since datanodeInfo already has all the information.
> * PendingContainerTracker should use only DatanodeID and DatanodeInfo but never DatanodeDetails.
@szetszwo raised PR https://github.com/apache/ozone/pull/10124 for refactor code
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org
For additional commands, e-mail: issues-help@ozone.apache.org
Re: [PR] HDDS-14921. Improve space accounting in SCM with In-Flight container allocation tracking. [ozone]
Posted by "szetszwo (via GitHub)" <gi...@apache.org>.
szetszwo commented on code in PR #10000:
URL: https://github.com/apache/ozone/pull/10000#discussion_r3162988799
##########
hadoop-hdds/server-scm/src/main/java/org/apache/hadoop/hdds/scm/container/ContainerManagerImpl.java:
##########
@@ -269,6 +269,7 @@ private ContainerInfo allocateContainer(final Pipeline pipeline,
}
containerStateManager.addContainer(containerInfoBuilder.build());
+ pipelineManager.recordPendingAllocation(pipeline, containerID);
Review Comment:
hasEnoughSpace and recordPendingAllocation should be atomic.
##########
hadoop-hdds/server-scm/src/main/java/org/apache/hadoop/hdds/scm/container/ContainerReportHandler.java:
##########
@@ -175,6 +177,13 @@ public void onMessage(final ContainerReportFromDatanode reportFromDatanode,
if (!alreadyInDn) {
// This is a new Container not in the nodeManager -> dn map yet
getNodeManager().addContainer(datanodeDetails, cid);
+ // Remove from pending tracker when container is added to DN
+ // This container was just confirmed for the first time on this DN
+ PendingContainerTracker tracker = getNodeManager().getPendingContainerTracker();
+ DatanodeInfo datanodeInfo = getNodeManager().getDatanodeInfo(datanodeDetails);
Review Comment:
We should get tracker and datanodeInfo outside the loop.
BTW, the datanodeDetails object actually is already a DatanodeInfo since SCMNodeManager.getNode(..) returns DatanodeInfo; filed HDDS-15146.
##########
hadoop-hdds/server-scm/src/main/java/org/apache/hadoop/hdds/scm/container/IncrementalContainerReportHandler.java:
##########
@@ -103,6 +105,11 @@ protected void processICR(IncrementalContainerReportFromDatanode report,
}
if (ContainerReportValidator.validate(container, dd, replicaProto)) {
processContainerReplica(dd, container, replicaProto, publisher, detailsForLogging);
+ PendingContainerTracker tracker = getNodeManager().getPendingContainerTracker();
+ DatanodeInfo datanodeInfo = getNodeManager().getDatanodeInfo(dd);
Review Comment:
Similarly, we should get tracker and datanodeInfo outside the loop.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org
For additional commands, e-mail: issues-help@ozone.apache.org
Re: [PR] HDDS-14921. Improve space accounting in SCM with In-Flight container allocation tracking. [ozone]
Posted by "szetszwo (via GitHub)" <gi...@apache.org>.
szetszwo commented on code in PR #10000:
URL: https://github.com/apache/ozone/pull/10000#discussion_r3175500259
##########
hadoop-hdds/server-scm/src/main/java/org/apache/hadoop/hdds/scm/node/SCMNodeManager.java:
##########
@@ -1103,6 +1103,27 @@ public void recordPendingAllocationForDatanode(DatanodeID datanodeID, ContainerI
pendingContainerTracker.recordPendingAllocationForDatanode(datanodeInfo, containerID);
}
+ @Override
+ public boolean checkSpaceAndRecordAllocation(DatanodeID datanodeID, ContainerID containerID) {
+ DatanodeInfo datanodeInfo = getNode(datanodeID);
+ if (datanodeInfo == null) {
+ LOG.warn("DatanodeInfo not found for node {}", datanodeID);
+ return false;
+ }
+ return pendingContainerTracker.checkSpaceAndRecordAllocation(datanodeInfo, containerID);
+ }
+
+ @Override
+ public void removePendingAllocationForDatanode(DatanodeID datanodeID, ContainerID containerID) {
+ DatanodeInfo datanodeInfo = getNode(datanodeID);
Review Comment:
@ashishkumar50 , we should get datanodeInfo outside the loop instead get it for each element.
##########
hadoop-hdds/server-scm/src/main/java/org/apache/hadoop/hdds/scm/node/SCMNodeManager.java:
##########
@@ -1103,6 +1103,27 @@ public void recordPendingAllocationForDatanode(DatanodeID datanodeID, ContainerI
pendingContainerTracker.recordPendingAllocationForDatanode(datanodeInfo, containerID);
}
+ @Override
+ public boolean checkSpaceAndRecordAllocation(DatanodeID datanodeID, ContainerID containerID) {
+ DatanodeInfo datanodeInfo = getNode(datanodeID);
+ if (datanodeInfo == null) {
+ LOG.warn("DatanodeInfo not found for node {}", datanodeID);
+ return false;
+ }
+ return pendingContainerTracker.checkSpaceAndRecordAllocation(datanodeInfo, containerID);
+ }
+
+ @Override
+ public void removePendingAllocationForDatanode(DatanodeID datanodeID, ContainerID containerID) {
+ DatanodeInfo datanodeInfo = getNode(datanodeID);
Review Comment:
@ashishkumar50 , we should get datanodeInfo outside the loop instead get it for each container.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org
For additional commands, e-mail: issues-help@ozone.apache.org
Re: [PR] HDDS-14921. Improve space accounting in SCM with In-Flight container allocation tracking. [ozone]
Posted by "rakeshadr (via GitHub)" <gi...@apache.org>.
rakeshadr commented on code in PR #10000:
URL: https://github.com/apache/ozone/pull/10000#discussion_r3044878303
##########
hadoop-hdds/server-scm/src/main/java/org/apache/hadoop/hdds/scm/node/PendingContainerTracker.java:
##########
@@ -0,0 +1,425 @@
+/*
+ * 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.node;
+
+import com.google.common.annotations.VisibleForTesting;
+import java.util.Collections;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Set;
+import java.util.UUID;
+import java.util.concurrent.ConcurrentHashMap;
+import org.apache.hadoop.hdds.protocol.DatanodeDetails;
+import org.apache.hadoop.hdds.protocol.proto.StorageContainerDatanodeProtocolProtos.StorageReportProto;
+import org.apache.hadoop.hdds.scm.container.ContainerID;
+import org.apache.hadoop.hdds.scm.pipeline.Pipeline;
+import org.apache.hadoop.ozone.container.common.volume.VolumeUsage;
+import org.apache.hadoop.util.Time;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * Tracks per-datanode pending container allocations at SCM using a Two Window Tumbling Bucket
+ * pattern (similar to HDFS HADOOP-3707).
+ *
+ * Two Window Tumbling Bucket for automatic aging and cleanup.
+ *
+ * How It Works:
+ * <li>Each DataNode has two sets: <b>currentWindow</b> and <b>previousWindow</b></li>
+ * <li>New allocations go into <b>currentWindow</b></li>
+ * <li>Every <b>ROLL_INTERVAL</b> (default 5 minutes):
+ * <ul>
+ * <li>previousWindow = currentWindow (shift)</li>
+ * <li>currentWindow = new empty set (reset)</li>
+ * <li>Old previousWindow is discarded (automatic aging)</li>
+ * </ul>
+ * </li>
+ * <li>When checking pending: return <b>union</b> of currentWindow + previousWindow</li>
+ *
+ *
+ * Example Timeline:
+ * <pre>
+ * Time | Action | CurrentWindow | PreviousWindow | Total Pending
+ * ------+---------------------------+---------------+----------------+--------------
+ * 00:00 | Allocate Container-1 | {C1} | {} | {C1}
+ * 00:02 | Allocate Container-2 | {C1, C2} | {} | {C1, C2}
+ * 00:05 | [ROLL] Window tumbles | {} | {C1, C2} | {C1, C2}
+ * 00:07 | Allocate Container-3 | {C3} | {C1, C2} | {C1, C2, C3}
+ * 00:08 | Report confirms C1 | {C3} | {C2} | {C2, C3}
+ * 00:10 | [ROLL] Window tumbles | {} | {C3} | {C3}
+ * | (C2 aged out if not reported)
+ * </pre>
+ *
+ * <p>Thread-safety: all mutations and reads for a given datanode run under
+ * {@code synchronized (bucket)} on that datanode's {@link TwoWindowBucket}, including
+ * map insert/remove, so concurrent record/remove/report paths cannot interleave or orphan
+ * a bucket after it was dropped from the map.</p>
+ */
+public class PendingContainerTracker {
+
+ private static final Logger LOG = LoggerFactory.getLogger(PendingContainerTracker.class);
+
+ /**
+ * Roll interval in milliseconds.
+ * Configurable via hdds.scm.container.pending.allocation.roll.interval.
+ * Default: 5 minutes.
+ * Containers automatically age out after 2 × rollIntervalMs.
+ */
+ private final long rollIntervalMs;
+
+ /**
+ * Map of DataNode UUID to TwoWindowBucket.
+ */
+ private final ConcurrentHashMap<UUID, TwoWindowBucket> datanodeBuckets;
+
+ /**
+ * Maximum container size in bytes.
+ */
+ private final long maxContainerSize;
+
+ /**
+ * Metrics for tracking pending containers (same instance as {@link SCMNodeManager}'s node metrics).
+ */
+ private final SCMNodeMetrics metrics;
+
+ /**
+ * Two-window bucket for a single DataNode.
+ * Contains current and previous window sets, plus last roll timestamp.
+ */
+ private static class TwoWindowBucket {
+ private Set<ContainerID> currentWindow = new HashSet<>();
+ private Set<ContainerID> previousWindow = new HashSet<>();
+ private long lastRollTime = Time.monotonicNow();
+ private final long rollIntervalMs;
+
+ TwoWindowBucket(long rollIntervalMs) {
+ this.rollIntervalMs = rollIntervalMs;
+ }
+
+ /**
+ * Roll the windows: previous = current, current = empty.
+ * Called when current time exceeds lastRollTime + rollIntervalMs.
+ */
+ synchronized void rollIfNeeded() {
+ long now = Time.monotonicNow();
+ if (now - lastRollTime >= rollIntervalMs) {
+ // Shift: current becomes previous
+ previousWindow = currentWindow;
+ // Reset: new empty current window
+ currentWindow = new HashSet<>();
+ lastRollTime = now;
+ LOG.debug("Rolled window. Previous window size: {}, Current window reset to empty", previousWindow.size());
+ }
+ }
+
+ /**
+ * Get union of both windows (all pending containers).
+ */
+ synchronized Set<ContainerID> getAllPending() {
+ Set<ContainerID> all = new HashSet<>();
+ all.addAll(currentWindow);
+ all.addAll(previousWindow);
+ return all;
+ }
+
+ /**
+ * Add container to current window.
+ */
+ synchronized boolean add(ContainerID containerID) {
+ return currentWindow.add(containerID);
+ }
+
+ /**
+ * Remove container from both windows.
+ */
+ synchronized boolean remove(ContainerID containerID) {
+ boolean removedFromCurrent = currentWindow.remove(containerID);
+ boolean removedFromPrevious = previousWindow.remove(containerID);
+ return removedFromCurrent || removedFromPrevious;
+ }
+
+ /**
+ * Check if either window is non-empty.
+ */
+ synchronized boolean isEmpty() {
+ return currentWindow.isEmpty() && previousWindow.isEmpty();
+ }
+
+ /**
+ * Count of pending containers in both windows.
+ */
+ synchronized int getCount() {
+ return currentWindow.size() + previousWindow.size();
+ }
+ }
+
+ public PendingContainerTracker(long maxContainerSize) {
+ this(maxContainerSize, 10 * 60 * 1000, null); // Default 10 minutes
+ }
+
+ public PendingContainerTracker(long maxContainerSize, long rollIntervalMs,
+ SCMNodeMetrics metrics) {
+ this.datanodeBuckets = new ConcurrentHashMap<>();
+ this.maxContainerSize = maxContainerSize;
+ this.rollIntervalMs = rollIntervalMs;
+ this.metrics = metrics;
+ LOG.info("PendingContainerTracker initialized with maxContainerSize={}B, rollInterval={}ms",
+ maxContainerSize, rollIntervalMs);
+ }
+
+ /**
+ * Whether the datanode can fit another container of {@code containerSize} after accounting for
+ * SCM pending allocations for {@code node} (this tracker) and usable space on {@code datanodeInfo}.
+ * Combines {@link #getPendingAllocationSize} with the per-disk slot check in one call.
+ *
+ * @param node identity used to look up pending allocations (same DN as {@code datanodeInfo})
+ * @param datanodeInfo storage reports for the datanode
+ * @param containerSize required container size in bytes (typically SCM max container size)
+ */
+ /**
+ * Advances the two-window tumbling bucket for this datanode when the roll interval has elapsed.
+ * Call on periodic paths (e.g. node report) so windows age even when there are no new
+ * allocations or container reports touching this tracker.
+ */
+ public void rollWindowsIfNeeded(DatanodeDetails node) {
+ if (node == null) {
+ return;
+ }
+ UUID uuid = node.getUuid();
+ TwoWindowBucket bucket = datanodeBuckets.get(uuid);
+ if (bucket == null) {
+ return;
+ }
+ synchronized (bucket) {
+ bucket.rollIfNeeded();
+ if (bucket.isEmpty()) {
+ datanodeBuckets.remove(uuid, bucket);
+ }
+ }
+ }
+
+ public boolean hasEffectiveAllocatableSpaceForNewContainer(
+ DatanodeDetails node, DatanodeInfo datanodeInfo, long containerSize) {
+ if (node == null || datanodeInfo == null || containerSize <= 0) {
+ return false;
+ }
+ long pendingBytes = getPendingAllocationSize(node);
+ return hasAllocatableSpaceAfterPending(datanodeInfo, containerSize, pendingBytes);
+ }
+
+ private static boolean hasAllocatableSpaceAfterPending(
+ DatanodeInfo datanodeInfo, long containerSize, long pendingAllocationBytes) {
+ List<StorageReportProto> storageReports = datanodeInfo.getStorageReports();
+ if (storageReports == null || storageReports.isEmpty()) {
+ return false;
+ }
+ long effectiveAllocatableSpace = 0L;
+ for (StorageReportProto report : storageReports) {
+ long usableSpace = VolumeUsage.getUsableSpace(report);
+ long containersOnThisDisk = usableSpace / containerSize;
+ effectiveAllocatableSpace += containersOnThisDisk * containerSize;
+ if (effectiveAllocatableSpace - pendingAllocationBytes >= containerSize) {
+ return true;
+ }
+ }
+ return false;
+ }
+
+ /**
+ * Drops all pending allocation state for a datanode (e.g. stale/dead cleanup).
+ */
+ public void clearPendingForDatanode(DatanodeDetails node) {
+ if (node == null) {
+ return;
+ }
+ UUID uuid = node.getUuid();
+ TwoWindowBucket bucket = datanodeBuckets.get(uuid);
+ if (bucket == null) {
+ return;
+ }
+ synchronized (bucket) {
+ datanodeBuckets.remove(uuid, bucket);
Review Comment:
Please use CHM mutation, that will simplify it.
```
if (node == null) {
return;
}
UUID uuid = node.getUuid();
if (datanodeBuckets.remove(uuid) != null) {
LOG.debug("Cleared pending container allocations for datanode {}",
node.getUuidString());
}
```
_Important lock design principle:-_
PendingContainerTracker: Please ensure no bucket -> map mutation path anymore. You need to switch remove/roll/clear to concurrenthashmap compute-based mutations, keep bucket internals intact.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org
For additional commands, e-mail: issues-help@ozone.apache.org
Re: [PR] HDDS-14921. Improve space accounting in SCM with In-Flight container allocation tracking. [ozone]
Posted by "ashishkumar50 (via GitHub)" <gi...@apache.org>.
ashishkumar50 commented on code in PR #10000:
URL: https://github.com/apache/ozone/pull/10000#discussion_r3035999302
##########
hadoop-hdds/server-scm/src/main/java/org/apache/hadoop/hdds/scm/container/ContainerManagerImpl.java:
##########
@@ -242,12 +262,75 @@ private ContainerInfo createContainer(Pipeline pipeline, String owner)
return containerInfo;
}
+ /**
+ * Check if a pipeline has sufficient space after considering pending allocations.
+ * Tracks containers scheduled but not yet written to DataNodes, preventing over-allocation.
+ *
+ * @param pipeline The pipeline to check
+ * @return true if sufficient space is available, false otherwise
+ */
+ private boolean hasSpaceAfterPendingAllocations(Pipeline pipeline) {
+ try {
+ for (DatanodeDetails node : pipeline.getNodes()) {
+ // Get DN's storage statistics
+ DatanodeInfo datanodeInfo = pipelineManager.getDatanodeInfo(node);
+ if (datanodeInfo == null) {
+ LOG.warn("DatanodeInfo not found for node {}", node.getUuidString());
+ return false;
+ }
+
+ List<StorageReportProto> storageReports = datanodeInfo.getStorageReports();
+ if (storageReports == null || storageReports.isEmpty()) {
+ LOG.warn("No storage reports for node {}", node.getUuidString());
+ return false;
+ }
+
+ // Calculate total capacity and effective allocatable space
+ // For each disk, calculate how many containers can actually fit,
+ // since containers are written to individual disks, not spread across them.
+ // Example: disk1=9GB, disk2=14GB with 5GB containers
+ // (1*5GB) + (2*5GB) = 15GB → actually 3 containers
+ long totalCapacity = 0L;
+ long effectiveAllocatableSpace = 0L;
+ for (StorageReportProto report : storageReports) {
+ totalCapacity += report.getCapacity();
+ long usableSpace = VolumeUsage.getUsableSpace(report);
+ // Calculate how many containers can fit on this disk
+ long containersOnThisDisk = usableSpace / maxContainerSize;
+ // Add effective space (containers that fit * container size)
+ effectiveAllocatableSpace += containersOnThisDisk * maxContainerSize;
+ }
+
+ // Get pending allocations from tracker
+ long pendingAllocations = pendingContainerTracker.getPendingAllocationSize(node);
+
+ // Calculate effective remaining space after pending allocations
+ long effectiveRemaining = effectiveAllocatableSpace - pendingAllocations;
+
+ // Check if there's enough space for a new container
+ if (effectiveRemaining < maxContainerSize) {
Review Comment:
No need of extra buffer here, as we are anyway going to give buffer in DN by considering soft and hard limit. So in case of some overflow DN will accept it until hard limit.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org
For additional commands, e-mail: issues-help@ozone.apache.org
Re: [PR] HDDS-14921. Improve space accounting in SCM with In-Flight container allocation tracking. [ozone]
Posted by "ashishkumar50 (via GitHub)" <gi...@apache.org>.
ashishkumar50 commented on code in PR #10000:
URL: https://github.com/apache/ozone/pull/10000#discussion_r3035995302
##########
hadoop-hdds/server-scm/src/main/java/org/apache/hadoop/hdds/scm/node/PendingContainerTracker.java:
##########
@@ -0,0 +1,338 @@
+/*
+ * 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;
+
+import com.google.common.annotations.VisibleForTesting;
+import java.util.Collections;
+import java.util.HashSet;
+import java.util.Set;
+import java.util.UUID;
+import java.util.concurrent.ConcurrentHashMap;
+import org.apache.hadoop.hdds.protocol.DatanodeDetails;
+import org.apache.hadoop.hdds.scm.container.metrics.SCMContainerManagerMetrics;
+import org.apache.hadoop.hdds.scm.pipeline.Pipeline;
+import org.apache.hadoop.util.Time;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * Tracks pending container allocations using a Two Window Tumbling Bucket pattern.
+ * Similar like HDFS HADOOP-3707.
+ *
+ * Two Window Tumbling Bucket for automatic aging and cleanup.
+ *
+ * How It Works:
+ * <li>Each DataNode has two sets: <b>currentWindow</b> and <b>previousWindow</b></li>
+ * <li>New allocations go into <b>currentWindow</b></li>
+ * <li>Every <b>ROLL_INTERVAL</b> (default 10 minutes):
+ * <ul>
+ * <li>previousWindow = currentWindow (shift)</li>
+ * <li>currentWindow = new empty set (reset)</li>
+ * <li>Old previousWindow is discarded (automatic aging)</li>
+ * </ul>
+ * </li>
+ * <li>When checking pending: return <b>union</b> of currentWindow + previousWindow</li>
+ *
+ *
+ * Example Timeline:
+ * <pre>
+ * Time | Action | CurrentWindow | PreviousWindow | Total Pending
+ * ------+---------------------------+---------------+----------------+--------------
+ * 00:00 | Allocate Container-1 | {C1} | {} | {C1}
+ * 00:05 | Allocate Container-2 | {C1, C2} | {} | {C1, C2}
+ * 00:10 | [ROLL] Window tumbles | {} | {C1, C2} | {C1, C2}
+ * 00:12 | Allocate Container-3 | {C3} | {C1, C2} | {C1, C2, C3}
+ * 00:15 | Report confirms C1 | {C3} | {C2} | {C2, C3}
+ * 00:20 | [ROLL] Window tumbles | {} | {C3} | {C3}
+ * | (C2 aged out if not reported)
+ * </pre>
+ *
+ */
+public class PendingContainerTracker {
+
+ private static final Logger LOG = LoggerFactory.getLogger(PendingContainerTracker.class);
+
+ /**
+ * Roll interval in milliseconds.
+ * Configurable via hdds.scm.container.pending-allocation.roll-interval.
+ * Default: 10 minutes.
+ * Containers automatically age out after 2 × rollIntervalMs.
+ */
+ private final long rollIntervalMs;
+
+ /**
+ * Map of DataNode UUID to TwoWindowBucket.
+ */
+ private final ConcurrentHashMap<UUID, TwoWindowBucket> datanodeBuckets;
+
+ /**
+ * Maximum container size in bytes.
+ */
+ private final long maxContainerSize;
+
+ /**
+ * Metrics for tracking pending containers.
+ */
+ private final SCMContainerManagerMetrics metrics;
+
+ /**
+ * Two-window bucket for a single DataNode.
+ * Contains current and previous window sets, plus last roll timestamp.
+ */
+ private static class TwoWindowBucket {
+ private Set<ContainerID> currentWindow = ConcurrentHashMap.newKeySet();
+ private Set<ContainerID> previousWindow = ConcurrentHashMap.newKeySet();
+ private long lastRollTime = Time.monotonicNow();
+ private final long rollIntervalMs;
+
+ TwoWindowBucket(long rollIntervalMs) {
+ this.rollIntervalMs = rollIntervalMs;
+ }
+
+ /**
+ * Roll the windows: previous = current, current = empty.
+ * Called when current time exceeds lastRollTime + rollIntervalMs.
+ */
+ synchronized void rollIfNeeded() {
+ long now = Time.monotonicNow();
+ if (now - lastRollTime >= rollIntervalMs) {
+ // Shift: current becomes previous
+ previousWindow = currentWindow;
+ // Reset: new empty current window
+ currentWindow = ConcurrentHashMap.newKeySet();
+ lastRollTime = now;
+ LOG.debug("Rolled window. Previous window size: {}, Current window reset to empty", previousWindow.size());
+ }
+ }
+
+ /**
+ * Get union of both windows (all pending containers).
+ */
+ synchronized Set<ContainerID> getAllPending() {
+ Set<ContainerID> all = new HashSet<>();
+ all.addAll(currentWindow);
+ all.addAll(previousWindow);
+ return all;
+ }
+
+ /**
+ * Add container to current window.
+ */
+ synchronized boolean add(ContainerID containerID) {
+ return currentWindow.add(containerID);
+ }
+
+ /**
+ * Remove container from both windows.
+ */
+ synchronized boolean remove(ContainerID containerID) {
+ boolean removedFromCurrent = currentWindow.remove(containerID);
+ boolean removedFromPrevious = previousWindow.remove(containerID);
+ return removedFromCurrent || removedFromPrevious;
+ }
+
+ /**
+ * Check if either window is non-empty.
+ */
+ synchronized boolean isEmpty() {
+ return currentWindow.isEmpty() && previousWindow.isEmpty();
+ }
+
+ /**
+ * Get count of all pending containers (union).
+ */
+ synchronized int getCount() {
+ return getAllPending().size();
+ }
+ }
+
+ public PendingContainerTracker(long maxContainerSize) {
+ this(maxContainerSize, 10 * 60 * 1000, null); // Default 10 minutes
+ }
+
+ public PendingContainerTracker(long maxContainerSize, long rollIntervalMs,
+ SCMContainerManagerMetrics metrics) {
+ this.datanodeBuckets = new ConcurrentHashMap<>();
+ this.maxContainerSize = maxContainerSize;
+ this.rollIntervalMs = rollIntervalMs;
+ this.metrics = metrics;
+ LOG.info("PendingContainerTracker initialized with maxContainerSize={}B, rollInterval={}ms",
+ maxContainerSize, rollIntervalMs);
+ }
+
+ /**
+ * Record a pending container allocation for all DataNodes in the pipeline.
+ * Container is added to the current window.
+ *
+ * @param pipeline The pipeline where container is allocated
+ * @param containerID The container being allocated
+ */
+ public void recordPendingAllocation(Pipeline pipeline, ContainerID containerID) {
+ if (pipeline == null || containerID == null) {
+ LOG.warn("Ignoring null pipeline or containerID");
+ return;
+ }
+
+ for (DatanodeDetails node : pipeline.getNodes()) {
+ recordPendingAllocationForDatanode(node, containerID);
+ }
+ }
+
+ /**
+ * Record a pending container allocation for a single DataNode.
+ * Container is added to the current window.
+ *
+ * @param node The DataNode where container is being allocated/replicated
+ * @param containerID The container being allocated/replicated
+ */
+ public void recordPendingAllocationForDatanode(DatanodeDetails node, ContainerID containerID) {
+ if (node == null || containerID == null) {
+ LOG.warn("Ignoring null node or containerID");
+ return;
+ }
+
+ TwoWindowBucket bucket = datanodeBuckets.computeIfAbsent(
+ node.getUuid(),
+ k -> new TwoWindowBucket(rollIntervalMs)
+ );
+
+ // Roll window if needed before adding
+ bucket.rollIfNeeded();
+
+ boolean added = bucket.add(containerID);
+ LOG.info("Recorded pending container {} on DataNode {}. Added={}, Total pending={}",
+ containerID, node.getUuidString(), added, bucket.getCount());
+
+ // Increment metrics counter
+ if (added && metrics != null) {
+ metrics.incNumPendingContainersAdded();
+ }
+ }
+
+ /**
+ * Remove a pending container allocation from a specific DataNode.
+ * Removes from both current and previous windows.
+ * Called when container is confirmed.
+ *
+ * @param node The DataNode
+ * @param containerID The container to remove from pending
+ */
+ public void removePendingAllocation(DatanodeDetails node, ContainerID containerID) {
+ if (node == null || containerID == null) {
+ return;
+ }
+
+ TwoWindowBucket bucket = datanodeBuckets.get(node.getUuid());
+ if (bucket != null) {
+ // Roll window if needed before removing
+ bucket.rollIfNeeded();
+
+ boolean removed = bucket.remove(containerID);
+ LOG.info("Removed pending container {} from DataNode {}. Removed={}, Remaining={}",
+ containerID, node.getUuidString(), removed, bucket.getCount());
+
+ // Increment metrics counter
+ if (removed && metrics != null) {
+ metrics.incNumPendingContainersRemoved();
+ }
+
+ // Cleanup empty buckets to prevent memory leak
+ if (bucket.isEmpty()) {
Review Comment:
Added sync at bucket level.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org
For additional commands, e-mail: issues-help@ozone.apache.org
Re: [PR] HDDS-14921. Improve space accounting in SCM with In-Flight container allocation tracking. [ozone]
Posted by "ashishkumar50 (via GitHub)" <gi...@apache.org>.
ashishkumar50 commented on code in PR #10000:
URL: https://github.com/apache/ozone/pull/10000#discussion_r3035994340
##########
hadoop-hdds/server-scm/src/main/java/org/apache/hadoop/hdds/scm/container/IncrementalContainerReportHandler.java:
##########
@@ -103,6 +112,13 @@ protected void processICR(IncrementalContainerReportFromDatanode report,
}
if (ContainerReportValidator.validate(container, dd, replicaProto)) {
processContainerReplica(dd, container, replicaProto, publisher, detailsForLogging);
+
+ // Remove from pending tracker when container is added to DN
+ if (!alreadyOnDn && getContainerManager() instanceof ContainerManagerImpl) {
+ ((ContainerManagerImpl) getContainerManager())
+ .getPendingContainerTracker()
+ .removePendingAllocation(dd, id);
Review Comment:
Added roll in every node report which is per minute from DN.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org
For additional commands, e-mail: issues-help@ozone.apache.org
Re: [PR] HDDS-14921. Improve space accounting in SCM with In-Flight container allocation tracking. [ozone]
Posted by "ashishkumar50 (via GitHub)" <gi...@apache.org>.
ashishkumar50 commented on PR #10000:
URL: https://github.com/apache/ozone/pull/10000#issuecomment-4427568023
@szetszwo Can you please take a look, all the comments are addressed.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org
For additional commands, e-mail: issues-help@ozone.apache.org
Re: [PR] HDDS-14921. Improve space accounting in SCM with In-Flight container allocation tracking. [ozone]
Posted by "ashishkumar50 (via GitHub)" <gi...@apache.org>.
ashishkumar50 commented on PR #10000:
URL: https://github.com/apache/ozone/pull/10000#issuecomment-4343026573
@szetszwo updated this PR and fixed comments. Can you please take a look, thanks.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org
For additional commands, e-mail: issues-help@ozone.apache.org
Re: [PR] HDDS-14921. Improve space accounting in SCM with In-Flight container allocation tracking. [ozone]
Posted by "ashishkumar50 (via GitHub)" <gi...@apache.org>.
ashishkumar50 commented on code in PR #10000:
URL: https://github.com/apache/ozone/pull/10000#discussion_r3182504580
##########
hadoop-hdds/server-scm/src/main/java/org/apache/hadoop/hdds/scm/node/SCMNodeManager.java:
##########
@@ -1103,6 +1103,27 @@ public void recordPendingAllocationForDatanode(DatanodeID datanodeID, ContainerI
pendingContainerTracker.recordPendingAllocationForDatanode(datanodeInfo, containerID);
}
+ @Override
+ public boolean checkSpaceAndRecordAllocation(DatanodeID datanodeID, ContainerID containerID) {
+ DatanodeInfo datanodeInfo = getNode(datanodeID);
+ if (datanodeInfo == null) {
+ LOG.warn("DatanodeInfo not found for node {}", datanodeID);
+ return false;
+ }
+ return pendingContainerTracker.checkSpaceAndRecordAllocation(datanodeInfo, containerID);
+ }
+
+ @Override
+ public void removePendingAllocationForDatanode(DatanodeID datanodeID, ContainerID containerID) {
+ DatanodeInfo datanodeInfo = getNode(datanodeID);
Review Comment:
Moved
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org
For additional commands, e-mail: issues-help@ozone.apache.org
Re: [PR] HDDS-14921. Improve space accounting in SCM with In-Flight container allocation tracking. [ozone]
Posted by "aswinshakil (via GitHub)" <gi...@apache.org>.
aswinshakil commented on code in PR #10000:
URL: https://github.com/apache/ozone/pull/10000#discussion_r3030706480
##########
hadoop-hdds/server-scm/src/main/java/org/apache/hadoop/hdds/scm/container/IncrementalContainerReportHandler.java:
##########
@@ -89,6 +89,15 @@ protected void processICR(IncrementalContainerReportFromDatanode report,
ContainerID id = ContainerID.valueOf(replicaProto.getContainerID());
final ContainerInfo container;
try {
+ // Check if container is already known to this DN before adding
+ boolean alreadyOnDn = false;
Review Comment:
Just checked, This inherently does a copy of the containers with a TreeSet`getExisting(id).copyContainers();`, We should avoid this at all cost.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org
For additional commands, e-mail: issues-help@ozone.apache.org