You are viewing a plain text version of this content. The canonical link for it is here.
Posted to issues@ozone.apache.org by "priyeshkaratha (via GitHub)" <gi...@apache.org> on 2025/11/19 06:35:26 UTC
[PR] HDDS-13465. Adding endpoint at Recon to get consolidated storage dist… [ozone]
priyeshkaratha opened a new pull request, #9326:
URL: https://github.com/apache/ozone/pull/9326
## What changes were proposed in this pull request?
A new REST API endpoint `/storagedistribution` has been introduced to provide a summarized view of storage distribution across the cluster. This endpoint is designed to consolidate various storage-related insights, particularly focusing on used capacity, pending deletions, and overall data distribution across Ozone components.
### Key Functionalities
1. **Endpoint Name:** `/storagedistribution`
* Exposes consolidated metrics related to the usage and distribution of storage.
2. **Data Sources Used:**
* **OMDBInsightEndpoint:**
* Retrieves OM-level data such as bucket-level usage, namespace size, and used capacity
* **SCMClient:**
* Fetches pending deletion metrics from SCM.
* This includes block-level metadata such as size and replicated size info for accurate estimation of reclaimable space.
* **Datanode Storage Reports:**
* Gathers current storage usage statistics from individual datanodes.
* Helps in determining used vs available capacity and contributes to classifying data distribution based on node-wise storage usage.
Here the pending deletion bytes are calculated and updated in the BlockDeletionService metrics, which are then exposed via JMX. This allows for direct access to these metrics by monitoring tools. The primary disadvantage of this approach is the introduction of a dependency on JMX. While this might be a minor concern in some deployments, it's worth noting the additional dependency. This method avoids the unnecessary data transfer to SCM and the associated processing overhead in DN while iterating and calculating pending deletion from the container data list that is present with the Storage Report approach.
## What is the link to the Apache JIRA
HDDS-13465
## How was this patch tested?
Currently tested by unit test cases by mocking SCM and DN data. Also tested manually using postman.
--
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-13465. Adding endpoint at Recon to get consolidated storage dist… [ozone]
Posted by "priyeshkaratha (via GitHub)" <gi...@apache.org>.
priyeshkaratha commented on code in PR #9326:
URL: https://github.com/apache/ozone/pull/9326#discussion_r2546968833
##########
hadoop-ozone/recon/src/main/java/org/apache/hadoop/ozone/recon/ReconUtils.java:
##########
@@ -93,6 +104,13 @@ public class ReconUtils {
private static Logger log = LoggerFactory.getLogger(
ReconUtils.class);
+
+ private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();
+ private static CloseableHttpClient httpClient;
+ private static final int MAX_CONNECTIONS_PER_ROUTE = 20;
+ private static final int MAX_TOTAL_CONNECTIONS = 100;
+ private static final int CONNECTION_TIMEOUT_MS = 5000;
+ private static final int SOCKET_TIMEOUT_MS = 10000;
Review Comment:
Removed few of the configs and added others in config too.
--
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-13465. Adding endpoint at Recon to get consolidated storage dist… [ozone]
Posted by "priyeshkaratha (via GitHub)" <gi...@apache.org>.
priyeshkaratha commented on code in PR #9326:
URL: https://github.com/apache/ozone/pull/9326#discussion_r2546082904
##########
hadoop-ozone/recon/pom.xml:
##########
@@ -126,6 +126,23 @@
<groupId>org.apache.hadoop</groupId>
<artifactId>hadoop-hdfs-client</artifactId>
</dependency>
+ <dependency>
+ <groupId>org.apache.httpcomponents</groupId>
Review Comment:
Removed.
--
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-13465. [Recon] Create API Endpoint to Return Consolidated Storage Report. [ozone]
Posted by "priyeshkaratha (via GitHub)" <gi...@apache.org>.
priyeshkaratha commented on code in PR #9326:
URL: https://github.com/apache/ozone/pull/9326#discussion_r2579875879
##########
hadoop-ozone/integration-test-recon/src/test/java/org/apache/hadoop/ozone/recon/TestStorageDistributionEndpoint.java:
##########
@@ -0,0 +1,289 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.hadoop.ozone.recon;
+
+import static org.apache.hadoop.hdds.HddsConfigKeys.HDDS_CONTAINER_REPORT_INTERVAL;
+import static org.apache.hadoop.hdds.HddsConfigKeys.HDDS_HEARTBEAT_INTERVAL;
+import static org.apache.hadoop.hdds.HddsConfigKeys.HDDS_SCM_WAIT_TIME_AFTER_SAFE_MODE_EXIT;
+import static org.apache.hadoop.hdds.client.ReplicationFactor.THREE;
+import static org.apache.hadoop.hdds.client.ReplicationType.RATIS;
+import static org.apache.hadoop.hdds.scm.ScmConfigKeys.OZONE_SCM_HA_RATIS_SNAPSHOT_GAP;
+import static org.apache.hadoop.hdds.scm.ScmConfigKeys.OZONE_SCM_HEARTBEAT_PROCESS_INTERVAL;
+import static org.apache.hadoop.ozone.OzoneConfigKeys.OZONE_BLOCK_DELETING_SERVICE_INTERVAL;
+import static org.apache.hadoop.ozone.OzoneConfigKeys.OZONE_BLOCK_DELETING_SERVICE_TIMEOUT;
+import static org.apache.hadoop.ozone.recon.TestReconEndpointUtil.getReconWebAddress;
+import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+
+import com.fasterxml.jackson.databind.ObjectMapper;
+import java.time.Duration;
+import java.util.Collections;
+import java.util.List;
+import java.util.concurrent.TimeUnit;
+import org.apache.hadoop.fs.CommonConfigurationKeysPublic;
+import org.apache.hadoop.fs.FSDataOutputStream;
+import org.apache.hadoop.fs.FileStatus;
+import org.apache.hadoop.fs.FileSystem;
+import org.apache.hadoop.fs.Path;
+import org.apache.hadoop.hdds.client.BlockID;
+import org.apache.hadoop.hdds.client.DefaultReplicationConfig;
+import org.apache.hadoop.hdds.client.ReplicationConfig;
+import org.apache.hadoop.hdds.conf.OzoneConfiguration;
+import org.apache.hadoop.hdds.scm.ScmConfig;
+import org.apache.hadoop.hdds.scm.server.StorageContainerManager;
+import org.apache.hadoop.hdds.utils.IOUtils;
+import org.apache.hadoop.ozone.HddsDatanodeService;
+import org.apache.hadoop.ozone.MiniOzoneCluster;
+import org.apache.hadoop.ozone.OzoneConsts;
+import org.apache.hadoop.ozone.client.BucketArgs;
+import org.apache.hadoop.ozone.client.ObjectStore;
+import org.apache.hadoop.ozone.client.OzoneBucket;
+import org.apache.hadoop.ozone.client.OzoneClient;
+import org.apache.hadoop.ozone.client.OzoneVolume;
+import org.apache.hadoop.ozone.container.common.impl.ContainerSet;
+import org.apache.hadoop.ozone.container.common.interfaces.DBHandle;
+import org.apache.hadoop.ozone.container.common.statemachine.DatanodeConfiguration;
+import org.apache.hadoop.ozone.container.keyvalue.KeyValueContainerData;
+import org.apache.hadoop.ozone.container.keyvalue.helpers.BlockUtils;
+import org.apache.hadoop.ozone.om.OzoneManager;
+import org.apache.hadoop.ozone.om.helpers.BucketLayout;
+import org.apache.hadoop.ozone.om.helpers.OmKeyArgs;
+import org.apache.hadoop.ozone.om.helpers.OmKeyLocationInfo;
+import org.apache.hadoop.ozone.om.helpers.OmKeyLocationInfoGroup;
+import org.apache.hadoop.ozone.recon.api.types.StorageCapacityDistributionResponse;
+import org.apache.hadoop.ozone.recon.spi.impl.OzoneManagerServiceProviderImpl;
+import org.apache.ozone.test.GenericTestUtils;
+import org.apache.ratis.util.function.CheckedConsumer;
+import org.junit.jupiter.api.AfterAll;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeAll;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.Arguments;
+import org.junit.jupiter.params.provider.MethodSource;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * Test class for the Storage Distribution REST endpoint in the
+ * Recon service. This class is responsible for setting up the
+ * testing environment, performing operations on an Ozone cluster,
+ * and validating the response of the storage distribution endpoint.
+ */
+public class TestStorageDistributionEndpoint {
+
+ private static final Logger LOG =
+ LoggerFactory.getLogger(TestStorageDistributionEndpoint.class);
+
+ private static OzoneConfiguration conf;
+ private static MiniOzoneCluster cluster;
+ private static OzoneManager om;
+ private static StorageContainerManager scm;
+ private static OzoneClient client;
+ private static ReconService recon;
+ private FileSystem fs;
+ private static final ObjectMapper MAPPER = new ObjectMapper();
+
+ private static final String STORAGE_DIST_ENDPOINT = "/api/v1/storageDistribution";
+
+ static List<Arguments> replicationConfigs() {
+ return Collections.singletonList(
+ Arguments.of(ReplicationConfig.fromTypeAndFactor(RATIS, THREE))
+ );
+ }
+
+ @BeforeAll
+ public static void setup() throws Exception {
+ conf = new OzoneConfiguration();
+ conf.setTimeDuration(OZONE_BLOCK_DELETING_SERVICE_INTERVAL, 100,
+ TimeUnit.MILLISECONDS);
+ conf.setTimeDuration(OZONE_BLOCK_DELETING_SERVICE_TIMEOUT, 100,
+ TimeUnit.MILLISECONDS);
+ conf.setTimeDuration(OZONE_SCM_HEARTBEAT_PROCESS_INTERVAL,
+ 100, TimeUnit.MILLISECONDS);
+ conf.setLong(OZONE_SCM_HA_RATIS_SNAPSHOT_GAP, 1L);
+ conf.setTimeDuration(HDDS_HEARTBEAT_INTERVAL, 50,
+ TimeUnit.MILLISECONDS);
+ conf.setTimeDuration(HDDS_CONTAINER_REPORT_INTERVAL, 200,
+ TimeUnit.MILLISECONDS);
+
+ // Enhanced SCM configuration for faster block deletion processing
+ ScmConfig scmConfig = conf.getObject(ScmConfig.class);
+ scmConfig.setBlockDeletionInterval(Duration.ofMillis(100));
+ conf.setFromObject(scmConfig);
+ conf.set(HDDS_SCM_WAIT_TIME_AFTER_SAFE_MODE_EXIT, "0s");
+
+ // Enhanced DataNode configuration to move pending deletion from SCM to DN faster
+ DatanodeConfiguration dnConf =
+ conf.getObject(DatanodeConfiguration.class);
+ dnConf.setBlockDeletionInterval(Duration.ofMillis(100));
+ // Increase block delete queue limit to allow more queued commands on DN
+ dnConf.setBlockDeleteQueueLimit(50);
+ // Reduce the interval for delete command worker processing
+ dnConf.setBlockDeleteCommandWorkerInterval(Duration.ofMillis(100));
+ // Increase blocks deleted per interval to speed up deletion
+ dnConf.setBlockDeletionLimit(5000);
+ conf.setFromObject(dnConf);
+ // Increase DN delete threads for faster parallel processing
+ conf.setInt("ozone.datanode.block.delete.threads.max", 10);
+
+ recon = new ReconService(conf);
+ cluster = MiniOzoneCluster.newBuilder(conf)
+ .setNumDatanodes(3)
+ .addService(recon)
+ .build();
+ cluster.waitForClusterToBeReady();
+ om = cluster.getOzoneManager();
+ scm = cluster.getStorageContainerManager();
+ client = cluster.newClient();
+ }
+
+ @ParameterizedTest
+ @MethodSource("replicationConfigs")
+ public void testStorageDistributionEndpoint(ReplicationConfig replicationConfig) throws Exception {
+ ObjectStore objectStore = client.getObjectStore();
+ objectStore.createVolume("vol1");
+ BucketArgs bucketArgs = BucketArgs.newBuilder()
+ .setBucketLayout(BucketLayout.FILE_SYSTEM_OPTIMIZED)
+ .setDefaultReplicationConfig(new DefaultReplicationConfig(replicationConfig))
+ .build();
+
+ OzoneVolume volume = objectStore.getVolume("vol1");
+ volume.createBucket("bucket1", bucketArgs);
+ OzoneBucket bucket = volume.getBucket("bucket1");
+
+ String rootPath = String.format("%s://%s.%s/", OzoneConsts.OZONE_URI_SCHEME, bucket.getName(),
+ bucket.getVolumeName());
+
+ conf.set(CommonConfigurationKeysPublic.FS_DEFAULT_NAME_KEY, rootPath);
+ fs = FileSystem.get(conf);
+
+ Path dir1 = new Path("/dir1");
+ fs.mkdirs(dir1);
+ for (int i = 1; i <= 10; i++) {
+ Path path1 = new Path(dir1, "testKey" + i);
+ try (FSDataOutputStream stream = fs.create(path1)) {
+ stream.write(1);
+ }
+ }
+ Path dir2 = new Path("/dir2");
+ fs.mkdirs(dir2);
+ for (int i = 1; i <= 10; i++) {
+ Path path1 = new Path(dir2, "testKey" + i);
+ try (FSDataOutputStream stream = fs.create(path1)) {
+ stream.write(1);
+ }
+ }
+ waitForKeysCreated(replicationConfig);
+ Thread.sleep(10000);
Review Comment:
@adoroszlai Its not followup PR, same test cases are expected to modified as part of [HDDS-14010](https://issues.apache.org/jira/browse/HDDS-14010).
--
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-13465. Adding endpoint at Recon to get consolidated storage dist… [ozone]
Posted by "priyeshkaratha (via GitHub)" <gi...@apache.org>.
priyeshkaratha commented on code in PR #9326:
URL: https://github.com/apache/ozone/pull/9326#discussion_r2542999298
##########
hadoop-ozone/recon/src/main/java/org/apache/hadoop/ozone/recon/api/OMDBInsightEndpoint.java:
##########
@@ -340,7 +340,7 @@ public Response getOpenKeySummary() {
*
* @param keysSummary A map to store the keys summary information.
*/
- private void createKeysSummaryForOpenKey(
+ public void createKeysSummaryForOpenKey(
Review Comment:
Handled.
--
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-13465. Adding endpoint at Recon to get consolidated storage dist… [ozone]
Posted by "ArafatKhan2198 (via GitHub)" <gi...@apache.org>.
ArafatKhan2198 commented on code in PR #9326:
URL: https://github.com/apache/ozone/pull/9326#discussion_r2579629331
##########
hadoop-ozone/integration-test-recon/src/test/java/org/apache/hadoop/ozone/recon/TestStorageDistributionEndpoint.java:
##########
@@ -0,0 +1,289 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.hadoop.ozone.recon;
+
+import static org.apache.hadoop.hdds.HddsConfigKeys.HDDS_CONTAINER_REPORT_INTERVAL;
+import static org.apache.hadoop.hdds.HddsConfigKeys.HDDS_HEARTBEAT_INTERVAL;
+import static org.apache.hadoop.hdds.HddsConfigKeys.HDDS_SCM_WAIT_TIME_AFTER_SAFE_MODE_EXIT;
+import static org.apache.hadoop.hdds.client.ReplicationFactor.THREE;
+import static org.apache.hadoop.hdds.client.ReplicationType.RATIS;
+import static org.apache.hadoop.hdds.scm.ScmConfigKeys.OZONE_SCM_HA_RATIS_SNAPSHOT_GAP;
+import static org.apache.hadoop.hdds.scm.ScmConfigKeys.OZONE_SCM_HEARTBEAT_PROCESS_INTERVAL;
+import static org.apache.hadoop.ozone.OzoneConfigKeys.OZONE_BLOCK_DELETING_SERVICE_INTERVAL;
+import static org.apache.hadoop.ozone.OzoneConfigKeys.OZONE_BLOCK_DELETING_SERVICE_TIMEOUT;
+import static org.apache.hadoop.ozone.recon.TestReconEndpointUtil.getReconWebAddress;
+import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+
+import com.fasterxml.jackson.databind.ObjectMapper;
+import java.time.Duration;
+import java.util.Collections;
+import java.util.List;
+import java.util.concurrent.TimeUnit;
+import org.apache.hadoop.fs.CommonConfigurationKeysPublic;
+import org.apache.hadoop.fs.FSDataOutputStream;
+import org.apache.hadoop.fs.FileStatus;
+import org.apache.hadoop.fs.FileSystem;
+import org.apache.hadoop.fs.Path;
+import org.apache.hadoop.hdds.client.BlockID;
+import org.apache.hadoop.hdds.client.DefaultReplicationConfig;
+import org.apache.hadoop.hdds.client.ReplicationConfig;
+import org.apache.hadoop.hdds.conf.OzoneConfiguration;
+import org.apache.hadoop.hdds.scm.ScmConfig;
+import org.apache.hadoop.hdds.scm.server.StorageContainerManager;
+import org.apache.hadoop.hdds.utils.IOUtils;
+import org.apache.hadoop.ozone.HddsDatanodeService;
+import org.apache.hadoop.ozone.MiniOzoneCluster;
+import org.apache.hadoop.ozone.OzoneConsts;
+import org.apache.hadoop.ozone.client.BucketArgs;
+import org.apache.hadoop.ozone.client.ObjectStore;
+import org.apache.hadoop.ozone.client.OzoneBucket;
+import org.apache.hadoop.ozone.client.OzoneClient;
+import org.apache.hadoop.ozone.client.OzoneVolume;
+import org.apache.hadoop.ozone.container.common.impl.ContainerSet;
+import org.apache.hadoop.ozone.container.common.interfaces.DBHandle;
+import org.apache.hadoop.ozone.container.common.statemachine.DatanodeConfiguration;
+import org.apache.hadoop.ozone.container.keyvalue.KeyValueContainerData;
+import org.apache.hadoop.ozone.container.keyvalue.helpers.BlockUtils;
+import org.apache.hadoop.ozone.om.OzoneManager;
+import org.apache.hadoop.ozone.om.helpers.BucketLayout;
+import org.apache.hadoop.ozone.om.helpers.OmKeyArgs;
+import org.apache.hadoop.ozone.om.helpers.OmKeyLocationInfo;
+import org.apache.hadoop.ozone.om.helpers.OmKeyLocationInfoGroup;
+import org.apache.hadoop.ozone.recon.api.types.StorageCapacityDistributionResponse;
+import org.apache.hadoop.ozone.recon.spi.impl.OzoneManagerServiceProviderImpl;
+import org.apache.ozone.test.GenericTestUtils;
+import org.apache.ratis.util.function.CheckedConsumer;
+import org.junit.jupiter.api.AfterAll;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeAll;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.Arguments;
+import org.junit.jupiter.params.provider.MethodSource;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * Test class for the Storage Distribution REST endpoint in the
+ * Recon service. This class is responsible for setting up the
+ * testing environment, performing operations on an Ozone cluster,
+ * and validating the response of the storage distribution endpoint.
+ */
+public class TestStorageDistributionEndpoint {
+
+ private static final Logger LOG =
+ LoggerFactory.getLogger(TestStorageDistributionEndpoint.class);
+
+ private static OzoneConfiguration conf;
+ private static MiniOzoneCluster cluster;
+ private static OzoneManager om;
+ private static StorageContainerManager scm;
+ private static OzoneClient client;
+ private static ReconService recon;
+ private FileSystem fs;
+ private static final ObjectMapper MAPPER = new ObjectMapper();
+
+ private static final String STORAGE_DIST_ENDPOINT = "/api/v1/storageDistribution";
+
+ static List<Arguments> replicationConfigs() {
+ return Collections.singletonList(
+ Arguments.of(ReplicationConfig.fromTypeAndFactor(RATIS, THREE))
+ );
+ }
+
+ @BeforeAll
+ public static void setup() throws Exception {
+ conf = new OzoneConfiguration();
+ conf.setTimeDuration(OZONE_BLOCK_DELETING_SERVICE_INTERVAL, 100,
+ TimeUnit.MILLISECONDS);
+ conf.setTimeDuration(OZONE_BLOCK_DELETING_SERVICE_TIMEOUT, 100,
+ TimeUnit.MILLISECONDS);
+ conf.setTimeDuration(OZONE_SCM_HEARTBEAT_PROCESS_INTERVAL,
+ 100, TimeUnit.MILLISECONDS);
+ conf.setLong(OZONE_SCM_HA_RATIS_SNAPSHOT_GAP, 1L);
+ conf.setTimeDuration(HDDS_HEARTBEAT_INTERVAL, 50,
+ TimeUnit.MILLISECONDS);
+ conf.setTimeDuration(HDDS_CONTAINER_REPORT_INTERVAL, 200,
+ TimeUnit.MILLISECONDS);
+
+ // Enhanced SCM configuration for faster block deletion processing
+ ScmConfig scmConfig = conf.getObject(ScmConfig.class);
+ scmConfig.setBlockDeletionInterval(Duration.ofMillis(100));
+ conf.setFromObject(scmConfig);
+ conf.set(HDDS_SCM_WAIT_TIME_AFTER_SAFE_MODE_EXIT, "0s");
+
+ // Enhanced DataNode configuration to move pending deletion from SCM to DN faster
+ DatanodeConfiguration dnConf =
+ conf.getObject(DatanodeConfiguration.class);
+ dnConf.setBlockDeletionInterval(Duration.ofMillis(100));
+ // Increase block delete queue limit to allow more queued commands on DN
+ dnConf.setBlockDeleteQueueLimit(50);
+ // Reduce the interval for delete command worker processing
+ dnConf.setBlockDeleteCommandWorkerInterval(Duration.ofMillis(100));
+ // Increase blocks deleted per interval to speed up deletion
+ dnConf.setBlockDeletionLimit(5000);
+ conf.setFromObject(dnConf);
+ // Increase DN delete threads for faster parallel processing
+ conf.setInt("ozone.datanode.block.delete.threads.max", 10);
+
+ recon = new ReconService(conf);
+ cluster = MiniOzoneCluster.newBuilder(conf)
+ .setNumDatanodes(3)
+ .addService(recon)
+ .build();
+ cluster.waitForClusterToBeReady();
+ om = cluster.getOzoneManager();
+ scm = cluster.getStorageContainerManager();
+ client = cluster.newClient();
+ }
+
+ @ParameterizedTest
+ @MethodSource("replicationConfigs")
+ public void testStorageDistributionEndpoint(ReplicationConfig replicationConfig) throws Exception {
+ ObjectStore objectStore = client.getObjectStore();
+ objectStore.createVolume("vol1");
+ BucketArgs bucketArgs = BucketArgs.newBuilder()
+ .setBucketLayout(BucketLayout.FILE_SYSTEM_OPTIMIZED)
+ .setDefaultReplicationConfig(new DefaultReplicationConfig(replicationConfig))
+ .build();
+
+ OzoneVolume volume = objectStore.getVolume("vol1");
+ volume.createBucket("bucket1", bucketArgs);
+ OzoneBucket bucket = volume.getBucket("bucket1");
+
+ String rootPath = String.format("%s://%s.%s/", OzoneConsts.OZONE_URI_SCHEME, bucket.getName(),
+ bucket.getVolumeName());
+
+ conf.set(CommonConfigurationKeysPublic.FS_DEFAULT_NAME_KEY, rootPath);
+ fs = FileSystem.get(conf);
+
+ Path dir1 = new Path("/dir1");
+ fs.mkdirs(dir1);
+ for (int i = 1; i <= 10; i++) {
+ Path path1 = new Path(dir1, "testKey" + i);
+ try (FSDataOutputStream stream = fs.create(path1)) {
+ stream.write(1);
+ }
+ }
+ Path dir2 = new Path("/dir2");
+ fs.mkdirs(dir2);
+ for (int i = 1; i <= 10; i++) {
+ Path path1 = new Path(dir2, "testKey" + i);
+ try (FSDataOutputStream stream = fs.create(path1)) {
+ stream.write(1);
+ }
+ }
+ waitForKeysCreated(replicationConfig);
+ Thread.sleep(10000);
Review Comment:
Suggestion: Hard-coded sleeps can make tests flaky. It would be more robust to replace Thread.sleep() with a polling mechanism such as GenericTestUtils.waitFor. You can poll the endpoint in a loop until it returns the expected values (for example, totalKeys == 20), with a reasonable timeout.
We can handle this in a follow-up PR for the same feature. No need to rerun the tests now and waste resources. Just wanted to flag it; everything else in the changes looks good.
--
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-13465. Adding endpoint at Recon to get consolidated storage dist… [ozone]
Posted by "devmadhuu (via GitHub)" <gi...@apache.org>.
devmadhuu commented on code in PR #9326:
URL: https://github.com/apache/ozone/pull/9326#discussion_r2542711225
##########
hadoop-ozone/recon/src/main/java/org/apache/hadoop/ozone/recon/ReconUtils.java:
##########
@@ -847,4 +899,53 @@ public static String constructObjectPathWithPrefix(long... ids) {
}
return pathBuilder.toString();
}
+
+ public static long getMetricsFromDatanode(DatanodeDetails datanode, String service, String name, String keyName)
+ throws IOException {
+ // Construct metrics URL for DataNode JMX endpoint
+ String metricsUrl = String.format("http://%s:%d/jmx?qry=Hadoop:service=%s,name=%s",
+ datanode.getIpAddress(),
+ datanode.getPort(DatanodeDetails.Port.Name.HTTP).getValue(),
+ service,
+ name);
+ HttpGet request = new HttpGet(metricsUrl);
+ try (CloseableHttpResponse response = httpClient.execute(request)) {
+ if (response.getStatusLine().getStatusCode() != 200) {
+ throw new IOException("HTTP request failed with status: " +
+ response.getStatusLine().getStatusCode());
+ }
+
+ String jsonResponse = EntityUtils.toString(response.getEntity());
+ return parseMetrics(jsonResponse, name, keyName);
+ } catch (IOException e) {
+ log.error("Error getting metrics from datanode: {}", datanode.getIpAddress(), e);
+ }
+ return 0;
Review Comment:
Returning `0` could be mis-leading. The API consumer cannot distinguish between:
- Datanode has 0 pending bytes
- Failed to fetch metrics from datanode
Would suggest to return -1 (indicates error)
##########
hadoop-ozone/recon/src/test/java/org/apache/hadoop/ozone/recon/api/TestStorageDistributionEndpoint.java:
##########
@@ -0,0 +1,452 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.hadoop.ozone.recon.api;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.ArgumentMatchers.anyInt;
+import static org.mockito.ArgumentMatchers.anyString;
+import static org.mockito.Mockito.anyMap;
+import static org.mockito.Mockito.doAnswer;
+import static org.mockito.Mockito.doThrow;
+import static org.mockito.Mockito.eq;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.when;
+
+import java.io.IOException;
+import java.sql.Timestamp;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import javax.ws.rs.core.Response;
+import org.apache.hadoop.hdds.protocol.proto.HddsProtos.DeletedBlocksTransactionSummary;
+import org.apache.hadoop.hdds.scm.container.placement.metrics.LongMetric;
+import org.apache.hadoop.hdds.scm.container.placement.metrics.SCMNodeMetric;
+import org.apache.hadoop.hdds.scm.container.placement.metrics.SCMNodeStat;
+import org.apache.hadoop.hdds.scm.node.DatanodeInfo;
+import org.apache.hadoop.hdds.scm.protocol.StorageContainerLocationProtocol;
+import org.apache.hadoop.hdds.scm.server.OzoneStorageContainerManager;
+import org.apache.hadoop.ozone.recon.api.types.DUResponse;
+import org.apache.hadoop.ozone.recon.api.types.DeletionPendingBytesByComponent;
+import org.apache.hadoop.ozone.recon.api.types.GlobalNamespaceReport;
+import org.apache.hadoop.ozone.recon.api.types.GlobalStorageReport;
+import org.apache.hadoop.ozone.recon.api.types.KeyInsightInfoResponse;
+import org.apache.hadoop.ozone.recon.api.types.StorageCapacityDistributionResponse;
+import org.apache.hadoop.ozone.recon.api.types.UsedSpaceBreakDown;
+import org.apache.hadoop.ozone.recon.scm.ReconNodeManager;
+import org.apache.ozone.recon.schema.generated.tables.daos.GlobalStatsDao;
+import org.apache.ozone.recon.schema.generated.tables.pojos.GlobalStats;
+import org.junit.jupiter.api.Test;
+
+/**
+ * Test class for StorageDistributionEndpoint, responsible for testing
+ * the behavior and responses of the storage distribution endpoint in
+ * different scenarios, including successful responses and exception cases.
+ */
+class TestStorageDistributionEndpoint {
Review Comment:
Kindly see if you can an integration test using MiniOzoneCluster to test the data.
##########
hadoop-ozone/recon/src/main/java/org/apache/hadoop/ozone/recon/api/StorageDistributionEndpoint.java:
##########
@@ -0,0 +1,343 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.hadoop.ozone.recon.api;
+
+import static org.apache.hadoop.ozone.om.codec.OMDBDefinition.FILE_TABLE;
+import static org.apache.hadoop.ozone.om.codec.OMDBDefinition.KEY_TABLE;
+
+import java.io.IOException;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.stream.Collectors;
+import javax.inject.Inject;
+import javax.ws.rs.GET;
+import javax.ws.rs.Path;
+import javax.ws.rs.Produces;
+import javax.ws.rs.core.Response;
+import org.apache.hadoop.hdds.protocol.DatanodeDetails;
+import org.apache.hadoop.hdds.protocol.proto.HddsProtos.DeletedBlocksTransactionSummary;
+import org.apache.hadoop.hdds.scm.container.placement.metrics.SCMNodeMetric;
+import org.apache.hadoop.hdds.scm.container.placement.metrics.SCMNodeStat;
+import org.apache.hadoop.hdds.scm.protocol.StorageContainerLocationProtocol;
+import org.apache.hadoop.hdds.scm.server.OzoneStorageContainerManager;
+import org.apache.hadoop.ozone.recon.ReconUtils;
+import org.apache.hadoop.ozone.recon.api.types.DUResponse;
+import org.apache.hadoop.ozone.recon.api.types.DatanodeStorageReport;
+import org.apache.hadoop.ozone.recon.api.types.DeletionPendingBytesByComponent;
+import org.apache.hadoop.ozone.recon.api.types.GlobalNamespaceReport;
+import org.apache.hadoop.ozone.recon.api.types.GlobalStorageReport;
+import org.apache.hadoop.ozone.recon.api.types.KeyInsightInfoResponse;
+import org.apache.hadoop.ozone.recon.api.types.StorageCapacityDistributionResponse;
+import org.apache.hadoop.ozone.recon.api.types.UsedSpaceBreakDown;
+import org.apache.hadoop.ozone.recon.scm.ReconNodeManager;
+import org.apache.hadoop.ozone.recon.tasks.OmTableInsightTask;
+import org.apache.ozone.recon.schema.generated.tables.daos.GlobalStatsDao;
+import org.apache.ozone.recon.schema.generated.tables.pojos.GlobalStats;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * This endpoint handles requests related to storage distribution across
+ * different datanodes in a Recon instance. It provides detailed reports
+ * on storage capacity, utilization, and associated metrics.
+ * <p>
+ * The data is aggregated from multiple sources, including node manager
+ * statistics, and is used to construct responses with information
+ * about global storage and namespace usage, storage usage breakdown,
+ * and deletion operations in progress.
+ * <p>
+ * An instance of {@link ReconNodeManager} is used to fetch detailed
+ * node-specific statistics required for generating the report.
+ */
+@Path("/storageDistribution")
+@Produces("application/json")
+@AdminOnly
+public class StorageDistributionEndpoint {
+ private final ReconNodeManager nodeManager;
+ private final OMDBInsightEndpoint omdbInsightEndpoint;
+ private final NSSummaryEndpoint nsSummaryEndpoint;
+ private final StorageContainerLocationProtocol scmClient;
+ private static Logger log = LoggerFactory.getLogger(StorageDistributionEndpoint.class);
Review Comment:
```suggestion
private static final Logger LOG = LoggerFactory.getLogger(StorageDistributionEndpoint.class);
```
##########
hadoop-ozone/recon/src/main/java/org/apache/hadoop/ozone/recon/ReconUtils.java:
##########
@@ -847,4 +899,53 @@ public static String constructObjectPathWithPrefix(long... ids) {
}
return pathBuilder.toString();
}
+
+ public static long getMetricsFromDatanode(DatanodeDetails datanode, String service, String name, String keyName)
+ throws IOException {
+ // Construct metrics URL for DataNode JMX endpoint
+ String metricsUrl = String.format("http://%s:%d/jmx?qry=Hadoop:service=%s,name=%s",
Review Comment:
This hardcoding of `http` protocol in metrics URL could be issue for secure or clusters where spnego is enabled in kerberized secure cluster.
##########
hadoop-ozone/recon/src/main/java/org/apache/hadoop/ozone/recon/api/OMDBInsightEndpoint.java:
##########
@@ -340,7 +340,7 @@ public Response getOpenKeySummary() {
*
* @param keysSummary A map to store the keys summary information.
*/
- private void createKeysSummaryForOpenKey(
+ public void createKeysSummaryForOpenKey(
Review Comment:
Exposing private implementation details just to call from another endpoint. Shouldn't it be better to extract these methods into a shared service something like:
```
@Singleton
public class ReconGlobalMetricsService {
public Map<String, Long> getOpenKeySummary();
public Map<String, Long> getDeletedKeySummary();
public Map<String, Long> getMPUKeySummary();
}
```
Then inject this service into both OMDBInsightEndpoint and StorageDistributionEndpoint.
##########
hadoop-ozone/recon/src/main/java/org/apache/hadoop/ozone/recon/ReconUtils.java:
##########
@@ -93,6 +104,13 @@ public class ReconUtils {
private static Logger log = LoggerFactory.getLogger(
ReconUtils.class);
+
+ private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();
+ private static CloseableHttpClient httpClient;
+ private static final int MAX_CONNECTIONS_PER_ROUTE = 20;
+ private static final int MAX_TOTAL_CONNECTIONS = 100;
+ private static final int CONNECTION_TIMEOUT_MS = 5000;
+ private static final int SOCKET_TIMEOUT_MS = 10000;
Review Comment:
Better to make them configurable.
##########
hadoop-ozone/recon/pom.xml:
##########
@@ -126,6 +126,23 @@
<groupId>org.apache.hadoop</groupId>
<artifactId>hadoop-hdfs-client</artifactId>
</dependency>
+ <dependency>
+ <groupId>org.apache.httpcomponents</groupId>
Review Comment:
Not sure if we need this. Ozone already has HTTP client capabilities via Hadoop's HttpURLConnection utilities or jersey-client.
##########
hadoop-ozone/recon/src/main/java/org/apache/hadoop/ozone/recon/api/StorageDistributionEndpoint.java:
##########
@@ -0,0 +1,343 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.hadoop.ozone.recon.api;
+
+import static org.apache.hadoop.ozone.om.codec.OMDBDefinition.FILE_TABLE;
+import static org.apache.hadoop.ozone.om.codec.OMDBDefinition.KEY_TABLE;
+
+import java.io.IOException;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.stream.Collectors;
+import javax.inject.Inject;
+import javax.ws.rs.GET;
+import javax.ws.rs.Path;
+import javax.ws.rs.Produces;
+import javax.ws.rs.core.Response;
+import org.apache.hadoop.hdds.protocol.DatanodeDetails;
+import org.apache.hadoop.hdds.protocol.proto.HddsProtos.DeletedBlocksTransactionSummary;
+import org.apache.hadoop.hdds.scm.container.placement.metrics.SCMNodeMetric;
+import org.apache.hadoop.hdds.scm.container.placement.metrics.SCMNodeStat;
+import org.apache.hadoop.hdds.scm.protocol.StorageContainerLocationProtocol;
+import org.apache.hadoop.hdds.scm.server.OzoneStorageContainerManager;
+import org.apache.hadoop.ozone.recon.ReconUtils;
+import org.apache.hadoop.ozone.recon.api.types.DUResponse;
+import org.apache.hadoop.ozone.recon.api.types.DatanodeStorageReport;
+import org.apache.hadoop.ozone.recon.api.types.DeletionPendingBytesByComponent;
+import org.apache.hadoop.ozone.recon.api.types.GlobalNamespaceReport;
+import org.apache.hadoop.ozone.recon.api.types.GlobalStorageReport;
+import org.apache.hadoop.ozone.recon.api.types.KeyInsightInfoResponse;
+import org.apache.hadoop.ozone.recon.api.types.StorageCapacityDistributionResponse;
+import org.apache.hadoop.ozone.recon.api.types.UsedSpaceBreakDown;
+import org.apache.hadoop.ozone.recon.scm.ReconNodeManager;
+import org.apache.hadoop.ozone.recon.tasks.OmTableInsightTask;
+import org.apache.ozone.recon.schema.generated.tables.daos.GlobalStatsDao;
+import org.apache.ozone.recon.schema.generated.tables.pojos.GlobalStats;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * This endpoint handles requests related to storage distribution across
+ * different datanodes in a Recon instance. It provides detailed reports
+ * on storage capacity, utilization, and associated metrics.
+ * <p>
+ * The data is aggregated from multiple sources, including node manager
+ * statistics, and is used to construct responses with information
+ * about global storage and namespace usage, storage usage breakdown,
+ * and deletion operations in progress.
+ * <p>
+ * An instance of {@link ReconNodeManager} is used to fetch detailed
+ * node-specific statistics required for generating the report.
+ */
+@Path("/storageDistribution")
+@Produces("application/json")
+@AdminOnly
+public class StorageDistributionEndpoint {
+ private final ReconNodeManager nodeManager;
+ private final OMDBInsightEndpoint omdbInsightEndpoint;
+ private final NSSummaryEndpoint nsSummaryEndpoint;
+ private final StorageContainerLocationProtocol scmClient;
+ private static Logger log = LoggerFactory.getLogger(StorageDistributionEndpoint.class);
+ private Map<DatanodeDetails, Long> blockDeletionMetricsMap = new ConcurrentHashMap<>();
+ private GlobalStatsDao globalStatsDao;
+
+ @Inject
+ public StorageDistributionEndpoint(OzoneStorageContainerManager reconSCM,
+ OMDBInsightEndpoint omDbInsightEndpoint,
+ NSSummaryEndpoint nsSummaryEndpoint,
+ GlobalStatsDao globalStatsDao,
+ StorageContainerLocationProtocol scmClient) {
+ this.nodeManager = (ReconNodeManager) reconSCM.getScmNodeManager();
+ this.omdbInsightEndpoint = omDbInsightEndpoint;
+ this.nsSummaryEndpoint = nsSummaryEndpoint;
+ this.scmClient = scmClient;
+ this.globalStatsDao = globalStatsDao;
+ }
+
+ @GET
+ public Response getStorageDistribution() {
+ try {
+ initializeBlockDeletionMetricsMap();
+ List<DatanodeStorageReport> nodeStorageReports = collectDatanodeReports();
+ GlobalStorageReport globalStorageReport = calculateGlobalStorageReport();
+
+ Map<String, Long> namespaceMetrics = new HashMap<>();
+ try {
+ namespaceMetrics = calculateNamespaceMetrics();
+ } catch (Exception e) {
+ log.error("Error calculating namespace metrics", e);
+ // Initialize with default values
+ namespaceMetrics.put("totalUsedNamespace", 0L);
+ namespaceMetrics.put("totalOpenKeySize", 0L);
+ namespaceMetrics.put("totalCommittedSize", 0L);
+ namespaceMetrics.put("pendingDirectorySize", 0L);
+ namespaceMetrics.put("pendingKeySize", 0L);
+ namespaceMetrics.put("totalKeys", 0L);
+ }
+
+ StorageCapacityDistributionResponse response = buildStorageDistributionResponse(
+ nodeStorageReports, globalStorageReport, namespaceMetrics);
+ return Response.ok(response).build();
+ } catch (Exception e) {
+ log.error("Error getting storage distribution", e);
+ return Response.status(Response.Status.INTERNAL_SERVER_ERROR)
+ .entity("Error retrieving storage distribution: " + e.getMessage())
+ .build();
+ }
+ }
+
+ private GlobalStorageReport calculateGlobalStorageReport() {
+ try {
+ SCMNodeStat stats = nodeManager.getStats();
+ if (stats == null) {
+ log.warn("Node manager stats are null, returning default values");
+ return new GlobalStorageReport(0L, 0L, 0L);
+ }
+
+ long scmUsed = stats.getScmUsed() != null ? stats.getScmUsed().get() : 0L;
+ long remaining = stats.getRemaining() != null ? stats.getRemaining().get() : 0L;
+ long capacity = stats.getCapacity() != null ? stats.getCapacity().get() : 0L;
+
+ return new GlobalStorageReport(scmUsed, remaining, capacity);
+ } catch (Exception e) {
+ log.error("Error calculating global storage report", e);
+ return new GlobalStorageReport(0L, 0L, 0L);
+ }
+ }
+
+ private Map<String, Long> calculateNamespaceMetrics() {
+ Map<String, Long> metrics = new HashMap<>();
+ Map<String, Long> totalPendingAtOmSide = calculatePendingSizes();
+ long totalOpenKeySize = calculateOpenKeySizes();
+ long totalCommittedSize = calculateCommittedSize();
+ long pendingDirectorySize = totalPendingAtOmSide.getOrDefault("pendingDirectorySize", 0L);
+ long pendingKeySize = totalPendingAtOmSide.getOrDefault("pendingKeySize", 0L);
+ long totalUsedNamespace = pendingDirectorySize + pendingKeySize + totalOpenKeySize + totalCommittedSize;
+
+ long totalKeys = 0L;
+ // Keys from OBJECT_STORE buckets.
+ GlobalStats keyRecord = globalStatsDao.findById(
+ OmTableInsightTask.getTableCountKeyFromTable(KEY_TABLE));
+ // Keys from FILE_SYSTEM_OPTIMIZED buckets
+ GlobalStats fileRecord = globalStatsDao.findById(
+ OmTableInsightTask.getTableCountKeyFromTable(FILE_TABLE));
+ if (keyRecord != null) {
+ totalKeys += keyRecord.getValue();
+ }
+ if (fileRecord != null) {
+ totalKeys += fileRecord.getValue();
+ }
+
+ metrics.put("pendingDirectorySize", pendingDirectorySize);
+ metrics.put("pendingKeySize", pendingKeySize);
+ metrics.put("totalOpenKeySize", totalOpenKeySize);
+ metrics.put("totalCommittedSize", totalCommittedSize);
+ metrics.put("totalUsedNamespace", totalUsedNamespace);
+ metrics.put("totalKeys", totalKeys);
+ return metrics;
+ }
+
+ private StorageCapacityDistributionResponse buildStorageDistributionResponse(
+ List<DatanodeStorageReport> nodeStorageReports,
+ GlobalStorageReport storageMetrics,
+ Map<String, Long> namespaceMetrics) {
+ DeletedBlocksTransactionSummary scmSummary = null;
+ try {
+ scmSummary = scmClient.getDeletedBlockSummary();
+ } catch (IOException e) {
+ log.error("Failed to get deleted block summary from SCM", e);
+ }
+
+ long totalPendingAtDnSide = 0L;
+ try {
+ totalPendingAtDnSide = blockDeletionMetricsMap.values().stream().reduce(0L, Long::sum);
+ } catch (Exception e) {
+ log.error("Error calculating pending deletion metrics", e);
+ }
+
+ DeletionPendingBytesByComponent deletionPendingBytesByStage =
+ createDeletionPendingBytesByStage(
+ namespaceMetrics.getOrDefault("pendingDirectorySize", 0L),
+ namespaceMetrics.getOrDefault("pendingKeySize", 0L),
+ scmSummary != null ? scmSummary.getTotalBlockReplicatedSize() : 0L,
+ totalPendingAtDnSide);
+
+ // Safely get values from namespaceMetrics with null checks
+ Long totalUsedNamespace = namespaceMetrics.get("totalUsedNamespace");
+ Long totalOpenKeySize = namespaceMetrics.get("totalOpenKeySize");
+ Long totalCommittedSize = namespaceMetrics.get("totalCommittedSize");
+ Long totalKeys = namespaceMetrics.get("totalKeys");
+ Long totalContainerPreAllocated = nodeStorageReports.stream()
+ .map(report -> report.getCommitted())
+ .reduce(0L, Long::sum);
+
+ return StorageCapacityDistributionResponse.newBuilder()
+ .setDataNodeUsage(nodeStorageReports)
+ .setGlobalStorage(storageMetrics)
+ .setGlobalNamespace(new GlobalNamespaceReport(
+ totalUsedNamespace != null ? totalUsedNamespace : 0L,
+ totalKeys != null ? totalKeys : 0L))
+ .setUsedSpaceBreakDown(new UsedSpaceBreakDown(
+ totalOpenKeySize != null ? totalOpenKeySize : 0L,
+ totalCommittedSize != null ? totalCommittedSize : 0L,
+ totalContainerPreAllocated != null ? totalContainerPreAllocated : 0L,
+ deletionPendingBytesByStage))
+ .build();
+ }
+
+ private List<DatanodeStorageReport> collectDatanodeReports() {
+ return nodeManager.getAllNodes().stream()
+ .map(this::getStorageReport)
+ .filter(report -> report != null) // Filter out null reports
+ .collect(Collectors.toList());
+ }
+
+ private Map<String, Long> calculatePendingSizes() {
+ Map<String, Long> result = new HashMap<>();
+ KeyInsightInfoResponse response = (KeyInsightInfoResponse)
+ omdbInsightEndpoint.getDeletedDirInfo(-1, "").getEntity();
+
+ Map<String, Long> pendingKeySize = new HashMap<>();
+ omdbInsightEndpoint.createKeysSummaryForDeletedKey(pendingKeySize);
+ result.put("pendingDirectorySize", response.getReplicatedDataSize());
+ result.put("pendingKeySize", pendingKeySize.getOrDefault("totalReplicatedDataSize", 0L));
+ return result;
+ }
+
+ private long calculateOpenKeySizes() {
+ Map<String, Long> openKeySummary = new HashMap<>();
+ omdbInsightEndpoint.createKeysSummaryForOpenKey(openKeySummary);
+ Map<String, Long> openKeyMPUSummary = new HashMap<>();
+ omdbInsightEndpoint.createKeysSummaryForOpenMPUKey(openKeyMPUSummary);
+ long openKeyDataSize = openKeySummary.getOrDefault("totalReplicatedDataSize", 0L);
+ long totalMPUKeySize = openKeyMPUSummary.getOrDefault("totalReplicatedDataSize", 0L);
+ return openKeyDataSize + totalMPUKeySize;
+ }
+
+ private long calculateCommittedSize() {
+ try {
+ Response rootResponse = nsSummaryEndpoint.getDiskUsage("/", false, true, false);
+ if (rootResponse.getStatus() != Response.Status.OK.getStatusCode()) {
+ log.warn("Failed to get disk usage, status: {}", rootResponse.getStatus());
+ return 0L;
+ }
+ DUResponse duRootRes = (DUResponse) rootResponse.getEntity();
+ return duRootRes != null ? duRootRes.getSizeWithReplica() : 0L;
+ } catch (IOException e) {
+ log.error("IOException while calculating committed size", e);
+ return 0L;
+ }
+ }
+
+ private DeletionPendingBytesByComponent createDeletionPendingBytesByStage(long pendingDirectorySize,
+ long pendingKeySize,
+ long totalPendingAtScmSide,
+ long totalPendingAtDnSide) {
+ long totalPending = pendingDirectorySize + pendingKeySize + totalPendingAtScmSide + totalPendingAtDnSide;
+ Map<String, Map<String, Long>> stageItems = new HashMap<>();
+ Map<String, Long> omMap = new HashMap<>();
+ omMap.put("totalBytes", pendingDirectorySize + pendingKeySize);
+ omMap.put("pendingDirectoryBytes", pendingDirectorySize);
+ omMap.put("pendingKeyBytes", pendingKeySize);
+ Map<String, Long> scmMap = new HashMap<>();
+ scmMap.put("pendingBytes", totalPendingAtScmSide);
+ Map<String, Long> dnMap = new HashMap<>();
+ dnMap.put("pendingBytes", totalPendingAtDnSide);
+ stageItems.put("OM", omMap);
+ stageItems.put("SCM", scmMap);
+ stageItems.put("DN", dnMap);
+ return new DeletionPendingBytesByComponent(totalPending, stageItems);
+ }
+
+ private void initializeBlockDeletionMetricsMap() {
+ nodeManager.getNodeStats().keySet().parallelStream().forEach(nodeId -> {
Review Comment:
This is being called for every datanode per API request.
**Problems:**
- Makes HTTP calls to ALL datanodes on EVERY API request
- In a 1000-node cluster with 10s timeout: worst case 10 seconds latency
- Parallel streams don't control concurrency properly
- Can overwhelm datanodes with JMX requests during high load
**So I would suggest to change this implementation:**
- Implement background polling with configurable interval (e.g., 30 seconds)
- Cache metrics with TTL
- Use ExecutorService with bounded thread pool instead of parallelStream()
- Make timeout configurable
--
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-13465. Adding endpoint at Recon to get consolidated storage dist… [ozone]
Posted by "priyeshkaratha (via GitHub)" <gi...@apache.org>.
priyeshkaratha commented on code in PR #9326:
URL: https://github.com/apache/ozone/pull/9326#discussion_r2546970478
##########
hadoop-ozone/recon/src/main/java/org/apache/hadoop/ozone/recon/ReconUtils.java:
##########
@@ -847,4 +899,53 @@ public static String constructObjectPathWithPrefix(long... ids) {
}
return pathBuilder.toString();
}
+
+ public static long getMetricsFromDatanode(DatanodeDetails datanode, String service, String name, String keyName)
+ throws IOException {
+ // Construct metrics URL for DataNode JMX endpoint
+ String metricsUrl = String.format("http://%s:%d/jmx?qry=Hadoop:service=%s,name=%s",
Review Comment:
I have handled in a tricky way. Can you please check whether this will work?
--
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-13465. Adding endpoint at Recon to get consolidated storage dist… [ozone]
Posted by "priyeshkaratha (via GitHub)" <gi...@apache.org>.
priyeshkaratha commented on code in PR #9326:
URL: https://github.com/apache/ozone/pull/9326#discussion_r2544971681
##########
hadoop-ozone/recon/src/main/java/org/apache/hadoop/ozone/recon/api/StorageDistributionEndpoint.java:
##########
@@ -0,0 +1,343 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.hadoop.ozone.recon.api;
+
+import static org.apache.hadoop.ozone.om.codec.OMDBDefinition.FILE_TABLE;
+import static org.apache.hadoop.ozone.om.codec.OMDBDefinition.KEY_TABLE;
+
+import java.io.IOException;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.stream.Collectors;
+import javax.inject.Inject;
+import javax.ws.rs.GET;
+import javax.ws.rs.Path;
+import javax.ws.rs.Produces;
+import javax.ws.rs.core.Response;
+import org.apache.hadoop.hdds.protocol.DatanodeDetails;
+import org.apache.hadoop.hdds.protocol.proto.HddsProtos.DeletedBlocksTransactionSummary;
+import org.apache.hadoop.hdds.scm.container.placement.metrics.SCMNodeMetric;
+import org.apache.hadoop.hdds.scm.container.placement.metrics.SCMNodeStat;
+import org.apache.hadoop.hdds.scm.protocol.StorageContainerLocationProtocol;
+import org.apache.hadoop.hdds.scm.server.OzoneStorageContainerManager;
+import org.apache.hadoop.ozone.recon.ReconUtils;
+import org.apache.hadoop.ozone.recon.api.types.DUResponse;
+import org.apache.hadoop.ozone.recon.api.types.DatanodeStorageReport;
+import org.apache.hadoop.ozone.recon.api.types.DeletionPendingBytesByComponent;
+import org.apache.hadoop.ozone.recon.api.types.GlobalNamespaceReport;
+import org.apache.hadoop.ozone.recon.api.types.GlobalStorageReport;
+import org.apache.hadoop.ozone.recon.api.types.KeyInsightInfoResponse;
+import org.apache.hadoop.ozone.recon.api.types.StorageCapacityDistributionResponse;
+import org.apache.hadoop.ozone.recon.api.types.UsedSpaceBreakDown;
+import org.apache.hadoop.ozone.recon.scm.ReconNodeManager;
+import org.apache.hadoop.ozone.recon.tasks.OmTableInsightTask;
+import org.apache.ozone.recon.schema.generated.tables.daos.GlobalStatsDao;
+import org.apache.ozone.recon.schema.generated.tables.pojos.GlobalStats;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * This endpoint handles requests related to storage distribution across
+ * different datanodes in a Recon instance. It provides detailed reports
+ * on storage capacity, utilization, and associated metrics.
+ * <p>
+ * The data is aggregated from multiple sources, including node manager
+ * statistics, and is used to construct responses with information
+ * about global storage and namespace usage, storage usage breakdown,
+ * and deletion operations in progress.
+ * <p>
+ * An instance of {@link ReconNodeManager} is used to fetch detailed
+ * node-specific statistics required for generating the report.
+ */
+@Path("/storageDistribution")
+@Produces("application/json")
+@AdminOnly
+public class StorageDistributionEndpoint {
+ private final ReconNodeManager nodeManager;
+ private final OMDBInsightEndpoint omdbInsightEndpoint;
+ private final NSSummaryEndpoint nsSummaryEndpoint;
+ private final StorageContainerLocationProtocol scmClient;
+ private static Logger log = LoggerFactory.getLogger(StorageDistributionEndpoint.class);
+ private Map<DatanodeDetails, Long> blockDeletionMetricsMap = new ConcurrentHashMap<>();
+ private GlobalStatsDao globalStatsDao;
+
+ @Inject
+ public StorageDistributionEndpoint(OzoneStorageContainerManager reconSCM,
+ OMDBInsightEndpoint omDbInsightEndpoint,
+ NSSummaryEndpoint nsSummaryEndpoint,
+ GlobalStatsDao globalStatsDao,
+ StorageContainerLocationProtocol scmClient) {
+ this.nodeManager = (ReconNodeManager) reconSCM.getScmNodeManager();
+ this.omdbInsightEndpoint = omDbInsightEndpoint;
+ this.nsSummaryEndpoint = nsSummaryEndpoint;
+ this.scmClient = scmClient;
+ this.globalStatsDao = globalStatsDao;
+ }
+
+ @GET
+ public Response getStorageDistribution() {
+ try {
+ initializeBlockDeletionMetricsMap();
+ List<DatanodeStorageReport> nodeStorageReports = collectDatanodeReports();
+ GlobalStorageReport globalStorageReport = calculateGlobalStorageReport();
+
+ Map<String, Long> namespaceMetrics = new HashMap<>();
+ try {
+ namespaceMetrics = calculateNamespaceMetrics();
+ } catch (Exception e) {
+ log.error("Error calculating namespace metrics", e);
+ // Initialize with default values
+ namespaceMetrics.put("totalUsedNamespace", 0L);
+ namespaceMetrics.put("totalOpenKeySize", 0L);
+ namespaceMetrics.put("totalCommittedSize", 0L);
+ namespaceMetrics.put("pendingDirectorySize", 0L);
+ namespaceMetrics.put("pendingKeySize", 0L);
+ namespaceMetrics.put("totalKeys", 0L);
+ }
+
+ StorageCapacityDistributionResponse response = buildStorageDistributionResponse(
+ nodeStorageReports, globalStorageReport, namespaceMetrics);
+ return Response.ok(response).build();
+ } catch (Exception e) {
+ log.error("Error getting storage distribution", e);
+ return Response.status(Response.Status.INTERNAL_SERVER_ERROR)
+ .entity("Error retrieving storage distribution: " + e.getMessage())
+ .build();
+ }
+ }
+
+ private GlobalStorageReport calculateGlobalStorageReport() {
+ try {
+ SCMNodeStat stats = nodeManager.getStats();
+ if (stats == null) {
+ log.warn("Node manager stats are null, returning default values");
+ return new GlobalStorageReport(0L, 0L, 0L);
+ }
+
+ long scmUsed = stats.getScmUsed() != null ? stats.getScmUsed().get() : 0L;
+ long remaining = stats.getRemaining() != null ? stats.getRemaining().get() : 0L;
+ long capacity = stats.getCapacity() != null ? stats.getCapacity().get() : 0L;
+
+ return new GlobalStorageReport(scmUsed, remaining, capacity);
+ } catch (Exception e) {
+ log.error("Error calculating global storage report", e);
+ return new GlobalStorageReport(0L, 0L, 0L);
+ }
+ }
+
+ private Map<String, Long> calculateNamespaceMetrics() {
+ Map<String, Long> metrics = new HashMap<>();
+ Map<String, Long> totalPendingAtOmSide = calculatePendingSizes();
+ long totalOpenKeySize = calculateOpenKeySizes();
+ long totalCommittedSize = calculateCommittedSize();
+ long pendingDirectorySize = totalPendingAtOmSide.getOrDefault("pendingDirectorySize", 0L);
+ long pendingKeySize = totalPendingAtOmSide.getOrDefault("pendingKeySize", 0L);
+ long totalUsedNamespace = pendingDirectorySize + pendingKeySize + totalOpenKeySize + totalCommittedSize;
+
+ long totalKeys = 0L;
+ // Keys from OBJECT_STORE buckets.
+ GlobalStats keyRecord = globalStatsDao.findById(
+ OmTableInsightTask.getTableCountKeyFromTable(KEY_TABLE));
+ // Keys from FILE_SYSTEM_OPTIMIZED buckets
+ GlobalStats fileRecord = globalStatsDao.findById(
+ OmTableInsightTask.getTableCountKeyFromTable(FILE_TABLE));
+ if (keyRecord != null) {
+ totalKeys += keyRecord.getValue();
+ }
+ if (fileRecord != null) {
+ totalKeys += fileRecord.getValue();
+ }
+
+ metrics.put("pendingDirectorySize", pendingDirectorySize);
+ metrics.put("pendingKeySize", pendingKeySize);
+ metrics.put("totalOpenKeySize", totalOpenKeySize);
+ metrics.put("totalCommittedSize", totalCommittedSize);
+ metrics.put("totalUsedNamespace", totalUsedNamespace);
+ metrics.put("totalKeys", totalKeys);
+ return metrics;
+ }
+
+ private StorageCapacityDistributionResponse buildStorageDistributionResponse(
+ List<DatanodeStorageReport> nodeStorageReports,
+ GlobalStorageReport storageMetrics,
+ Map<String, Long> namespaceMetrics) {
+ DeletedBlocksTransactionSummary scmSummary = null;
+ try {
+ scmSummary = scmClient.getDeletedBlockSummary();
+ } catch (IOException e) {
+ log.error("Failed to get deleted block summary from SCM", e);
+ }
+
+ long totalPendingAtDnSide = 0L;
+ try {
+ totalPendingAtDnSide = blockDeletionMetricsMap.values().stream().reduce(0L, Long::sum);
+ } catch (Exception e) {
+ log.error("Error calculating pending deletion metrics", e);
+ }
+
+ DeletionPendingBytesByComponent deletionPendingBytesByStage =
+ createDeletionPendingBytesByStage(
+ namespaceMetrics.getOrDefault("pendingDirectorySize", 0L),
+ namespaceMetrics.getOrDefault("pendingKeySize", 0L),
+ scmSummary != null ? scmSummary.getTotalBlockReplicatedSize() : 0L,
+ totalPendingAtDnSide);
+
+ // Safely get values from namespaceMetrics with null checks
+ Long totalUsedNamespace = namespaceMetrics.get("totalUsedNamespace");
+ Long totalOpenKeySize = namespaceMetrics.get("totalOpenKeySize");
+ Long totalCommittedSize = namespaceMetrics.get("totalCommittedSize");
+ Long totalKeys = namespaceMetrics.get("totalKeys");
+ Long totalContainerPreAllocated = nodeStorageReports.stream()
+ .map(report -> report.getCommitted())
+ .reduce(0L, Long::sum);
+
+ return StorageCapacityDistributionResponse.newBuilder()
+ .setDataNodeUsage(nodeStorageReports)
+ .setGlobalStorage(storageMetrics)
+ .setGlobalNamespace(new GlobalNamespaceReport(
+ totalUsedNamespace != null ? totalUsedNamespace : 0L,
+ totalKeys != null ? totalKeys : 0L))
+ .setUsedSpaceBreakDown(new UsedSpaceBreakDown(
+ totalOpenKeySize != null ? totalOpenKeySize : 0L,
+ totalCommittedSize != null ? totalCommittedSize : 0L,
+ totalContainerPreAllocated != null ? totalContainerPreAllocated : 0L,
+ deletionPendingBytesByStage))
+ .build();
+ }
+
+ private List<DatanodeStorageReport> collectDatanodeReports() {
+ return nodeManager.getAllNodes().stream()
+ .map(this::getStorageReport)
+ .filter(report -> report != null) // Filter out null reports
+ .collect(Collectors.toList());
+ }
+
+ private Map<String, Long> calculatePendingSizes() {
+ Map<String, Long> result = new HashMap<>();
+ KeyInsightInfoResponse response = (KeyInsightInfoResponse)
+ omdbInsightEndpoint.getDeletedDirInfo(-1, "").getEntity();
+
+ Map<String, Long> pendingKeySize = new HashMap<>();
+ omdbInsightEndpoint.createKeysSummaryForDeletedKey(pendingKeySize);
+ result.put("pendingDirectorySize", response.getReplicatedDataSize());
+ result.put("pendingKeySize", pendingKeySize.getOrDefault("totalReplicatedDataSize", 0L));
+ return result;
+ }
+
+ private long calculateOpenKeySizes() {
+ Map<String, Long> openKeySummary = new HashMap<>();
+ omdbInsightEndpoint.createKeysSummaryForOpenKey(openKeySummary);
+ Map<String, Long> openKeyMPUSummary = new HashMap<>();
+ omdbInsightEndpoint.createKeysSummaryForOpenMPUKey(openKeyMPUSummary);
+ long openKeyDataSize = openKeySummary.getOrDefault("totalReplicatedDataSize", 0L);
+ long totalMPUKeySize = openKeyMPUSummary.getOrDefault("totalReplicatedDataSize", 0L);
+ return openKeyDataSize + totalMPUKeySize;
+ }
+
+ private long calculateCommittedSize() {
+ try {
+ Response rootResponse = nsSummaryEndpoint.getDiskUsage("/", false, true, false);
+ if (rootResponse.getStatus() != Response.Status.OK.getStatusCode()) {
+ log.warn("Failed to get disk usage, status: {}", rootResponse.getStatus());
+ return 0L;
+ }
+ DUResponse duRootRes = (DUResponse) rootResponse.getEntity();
+ return duRootRes != null ? duRootRes.getSizeWithReplica() : 0L;
+ } catch (IOException e) {
+ log.error("IOException while calculating committed size", e);
+ return 0L;
+ }
+ }
+
+ private DeletionPendingBytesByComponent createDeletionPendingBytesByStage(long pendingDirectorySize,
+ long pendingKeySize,
+ long totalPendingAtScmSide,
+ long totalPendingAtDnSide) {
+ long totalPending = pendingDirectorySize + pendingKeySize + totalPendingAtScmSide + totalPendingAtDnSide;
+ Map<String, Map<String, Long>> stageItems = new HashMap<>();
+ Map<String, Long> omMap = new HashMap<>();
+ omMap.put("totalBytes", pendingDirectorySize + pendingKeySize);
+ omMap.put("pendingDirectoryBytes", pendingDirectorySize);
+ omMap.put("pendingKeyBytes", pendingKeySize);
+ Map<String, Long> scmMap = new HashMap<>();
+ scmMap.put("pendingBytes", totalPendingAtScmSide);
+ Map<String, Long> dnMap = new HashMap<>();
+ dnMap.put("pendingBytes", totalPendingAtDnSide);
+ stageItems.put("OM", omMap);
+ stageItems.put("SCM", scmMap);
+ stageItems.put("DN", dnMap);
+ return new DeletionPendingBytesByComponent(totalPending, stageItems);
+ }
+
+ private void initializeBlockDeletionMetricsMap() {
+ nodeManager.getNodeStats().keySet().parallelStream().forEach(nodeId -> {
Review Comment:
Thanks @devmadhuu for the detailed suggestion. I have already a JIRA available to handle this performance part by caching data - HDDS-13845
--
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-13465. Adding endpoint at Recon to get consolidated storage dist… [ozone]
Posted by "devmadhuu (via GitHub)" <gi...@apache.org>.
devmadhuu commented on code in PR #9326:
URL: https://github.com/apache/ozone/pull/9326#discussion_r2554699989
##########
hadoop-ozone/recon/src/main/java/org/apache/hadoop/ozone/recon/api/StorageDistributionEndpoint.java:
##########
@@ -0,0 +1,353 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.hadoop.ozone.recon.api;
+
+import static org.apache.hadoop.ozone.om.codec.OMDBDefinition.FILE_TABLE;
+import static org.apache.hadoop.ozone.om.codec.OMDBDefinition.KEY_TABLE;
+
+import java.io.IOException;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.ExecutionException;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+import java.util.concurrent.Future;
+import java.util.stream.Collectors;
+import javax.inject.Inject;
+import javax.ws.rs.GET;
+import javax.ws.rs.Path;
+import javax.ws.rs.Produces;
+import javax.ws.rs.core.Response;
+import org.apache.hadoop.hdds.conf.OzoneConfiguration;
+import org.apache.hadoop.hdds.protocol.DatanodeDetails;
+import org.apache.hadoop.hdds.protocol.proto.HddsProtos.DeletedBlocksTransactionSummary;
+import org.apache.hadoop.hdds.recon.ReconConfigKeys;
+import org.apache.hadoop.hdds.scm.container.placement.metrics.SCMNodeMetric;
+import org.apache.hadoop.hdds.scm.container.placement.metrics.SCMNodeStat;
+import org.apache.hadoop.hdds.scm.protocol.StorageContainerLocationProtocol;
+import org.apache.hadoop.hdds.scm.server.OzoneStorageContainerManager;
+import org.apache.hadoop.ozone.recon.api.types.DUResponse;
+import org.apache.hadoop.ozone.recon.api.types.DatanodeStorageReport;
+import org.apache.hadoop.ozone.recon.api.types.DeletionPendingBytesByComponent;
+import org.apache.hadoop.ozone.recon.api.types.GlobalNamespaceReport;
+import org.apache.hadoop.ozone.recon.api.types.GlobalStorageReport;
+import org.apache.hadoop.ozone.recon.api.types.KeyInsightInfoResponse;
+import org.apache.hadoop.ozone.recon.api.types.StorageCapacityDistributionResponse;
+import org.apache.hadoop.ozone.recon.api.types.UsedSpaceBreakDown;
+import org.apache.hadoop.ozone.recon.scm.ReconNodeManager;
+import org.apache.hadoop.ozone.recon.spi.ReconGlobalStatsManager;
+import org.apache.hadoop.ozone.recon.tasks.GlobalStatsValue;
+import org.apache.hadoop.ozone.recon.tasks.JmxMetricsCollectorTask;
+import org.apache.hadoop.ozone.recon.tasks.JmxMetricsCollectorTaskResult;
+import org.apache.hadoop.ozone.recon.tasks.OmTableInsightTask;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * This endpoint handles requests related to storage distribution across
+ * different datanodes in a Recon instance. It provides detailed reports
+ * on storage capacity, utilization, and associated metrics.
+ * <p>
+ * The data is aggregated from multiple sources, including node manager
+ * statistics, and is used to construct responses with information
+ * about global storage and namespace usage, storage usage breakdown,
+ * and deletion operations in progress.
+ * <p>
+ * An instance of {@link ReconNodeManager} is used to fetch detailed
+ * node-specific statistics required for generating the report.
+ */
+@Path("/storageDistribution")
+@Produces("application/json")
+@AdminOnly
+public class StorageDistributionEndpoint {
+ private final ReconNodeManager nodeManager;
+ private final NSSummaryEndpoint nsSummaryEndpoint;
+ private final StorageContainerLocationProtocol scmClient;
+ private static final Logger LOG = LoggerFactory.getLogger(StorageDistributionEndpoint.class);
+ private final Map<DatanodeDetails, Long> blockDeletionMetricsMap = new ConcurrentHashMap<>();
+ private final ReconGlobalStatsManager reconGlobalStatsManager;
+ private final ReconGlobalMetricsService reconGlobalMetricsService;
+ private final OzoneConfiguration conf;
+
+ @Inject
+ public StorageDistributionEndpoint(OzoneStorageContainerManager reconSCM,
+ NSSummaryEndpoint nsSummaryEndpoint,
+ ReconGlobalStatsManager reconGlobalStatsManager,
+ StorageContainerLocationProtocol scmClient,
+ ReconGlobalMetricsService reconGlobalMetricsService,
+ OzoneConfiguration conf) {
+ this.nodeManager = (ReconNodeManager) reconSCM.getScmNodeManager();
+ this.nsSummaryEndpoint = nsSummaryEndpoint;
+ this.scmClient = scmClient;
+ this.reconGlobalStatsManager = reconGlobalStatsManager;
+ this.reconGlobalMetricsService = reconGlobalMetricsService;
+ this.conf = conf;
+ }
+
+ @GET
+ public Response getStorageDistribution() {
+ try {
+ initializeBlockDeletionMetricsMap();
+ List<DatanodeStorageReport> nodeStorageReports = collectDatanodeReports();
+ GlobalStorageReport globalStorageReport = calculateGlobalStorageReport();
+
+ Map<String, Long> namespaceMetrics = new HashMap<>();
+ try {
+ namespaceMetrics = calculateNamespaceMetrics();
+ } catch (Exception e) {
+ LOG.error("Error calculating namespace metrics", e);
+ // Initialize with default values
+ namespaceMetrics.put("totalUsedNamespace", 0L);
+ namespaceMetrics.put("totalOpenKeySize", 0L);
+ namespaceMetrics.put("totalCommittedSize", 0L);
+ namespaceMetrics.put("pendingDirectorySize", 0L);
+ namespaceMetrics.put("pendingKeySize", 0L);
+ namespaceMetrics.put("totalKeys", 0L);
+ }
+
+ StorageCapacityDistributionResponse response = buildStorageDistributionResponse(
+ nodeStorageReports, globalStorageReport, namespaceMetrics);
+ return Response.ok(response).build();
+ } catch (Exception e) {
+ LOG.error("Error getting storage distribution", e);
+ return Response.status(Response.Status.INTERNAL_SERVER_ERROR)
+ .entity("Error retrieving storage distribution: " + e.getMessage())
+ .build();
+ }
+ }
+
+ private GlobalStorageReport calculateGlobalStorageReport() {
+ try {
+ SCMNodeStat stats = nodeManager.getStats();
+ if (stats == null) {
+ LOG.warn("Node manager stats are null, returning default values");
+ return new GlobalStorageReport(0L, 0L, 0L);
+ }
+
+ long scmUsed = stats.getScmUsed() != null ? stats.getScmUsed().get() : 0L;
+ long remaining = stats.getRemaining() != null ? stats.getRemaining().get() : 0L;
+ long capacity = stats.getCapacity() != null ? stats.getCapacity().get() : 0L;
+
+ return new GlobalStorageReport(scmUsed, remaining, capacity);
+ } catch (Exception e) {
+ LOG.error("Error calculating global storage report", e);
+ return new GlobalStorageReport(0L, 0L, 0L);
+ }
+ }
+
+ private Map<String, Long> calculateNamespaceMetrics() throws IOException {
+ Map<String, Long> metrics = new HashMap<>();
+ Map<String, Long> totalPendingAtOmSide = calculatePendingSizes();
+ long totalOpenKeySize = calculateOpenKeySizes();
+ long totalCommittedSize = calculateCommittedSize();
+ long pendingDirectorySize = totalPendingAtOmSide.getOrDefault("pendingDirectorySize", 0L);
+ long pendingKeySize = totalPendingAtOmSide.getOrDefault("pendingKeySize", 0L);
+ long totalUsedNamespace = pendingDirectorySize + pendingKeySize + totalOpenKeySize + totalCommittedSize;
+
+ long totalKeys = 0L;
+ // Keys from OBJECT_STORE buckets.
+ GlobalStatsValue keyRecord = reconGlobalStatsManager.getGlobalStatsValue(
+ OmTableInsightTask.getTableCountKeyFromTable(KEY_TABLE));
+ // Keys from FILE_SYSTEM_OPTIMIZED buckets
+ GlobalStatsValue fileRecord = reconGlobalStatsManager.getGlobalStatsValue(
+ OmTableInsightTask.getTableCountKeyFromTable(FILE_TABLE));
+ if (keyRecord != null) {
+ totalKeys += keyRecord.getValue();
+ }
+ if (fileRecord != null) {
+ totalKeys += fileRecord.getValue();
+ }
+
+ metrics.put("pendingDirectorySize", pendingDirectorySize);
+ metrics.put("pendingKeySize", pendingKeySize);
+ metrics.put("totalOpenKeySize", totalOpenKeySize);
+ metrics.put("totalCommittedSize", totalCommittedSize);
+ metrics.put("totalUsedNamespace", totalUsedNamespace);
+ metrics.put("totalKeys", totalKeys);
+ return metrics;
+ }
+
+ private StorageCapacityDistributionResponse buildStorageDistributionResponse(
+ List<DatanodeStorageReport> nodeStorageReports,
+ GlobalStorageReport storageMetrics,
+ Map<String, Long> namespaceMetrics) {
+ DeletedBlocksTransactionSummary scmSummary = null;
+ try {
+ scmSummary = scmClient.getDeletedBlockSummary();
+ } catch (IOException e) {
+ LOG.error("Failed to get deleted block summary from SCM", e);
+ }
+
+ long totalPendingAtDnSide = 0L;
+ try {
+ totalPendingAtDnSide = blockDeletionMetricsMap.values().stream().reduce(0L, Long::sum);
+ } catch (Exception e) {
+ LOG.error("Error calculating pending deletion metrics", e);
+ }
+
+ DeletionPendingBytesByComponent deletionPendingBytesByStage =
+ createDeletionPendingBytesByStage(
+ namespaceMetrics.getOrDefault("pendingDirectorySize", 0L),
+ namespaceMetrics.getOrDefault("pendingKeySize", 0L),
+ scmSummary != null ? scmSummary.getTotalBlockReplicatedSize() : 0L,
+ totalPendingAtDnSide);
+
+ // Safely get values from namespaceMetrics with null checks
+ Long totalUsedNamespace = namespaceMetrics.get("totalUsedNamespace");
+ Long totalOpenKeySize = namespaceMetrics.get("totalOpenKeySize");
+ Long totalCommittedSize = namespaceMetrics.get("totalCommittedSize");
+ Long totalKeys = namespaceMetrics.get("totalKeys");
+ Long totalContainerPreAllocated = nodeStorageReports.stream()
+ .map(DatanodeStorageReport::getCommitted)
+ .reduce(0L, Long::sum);
+
+ return StorageCapacityDistributionResponse.newBuilder()
+ .setDataNodeUsage(nodeStorageReports)
+ .setGlobalStorage(storageMetrics)
+ .setGlobalNamespace(new GlobalNamespaceReport(
+ totalUsedNamespace != null ? totalUsedNamespace : 0L,
+ totalKeys != null ? totalKeys : 0L))
+ .setUsedSpaceBreakDown(new UsedSpaceBreakDown(
+ totalOpenKeySize != null ? totalOpenKeySize : 0L,
+ totalCommittedSize != null ? totalCommittedSize : 0L, totalContainerPreAllocated,
+ deletionPendingBytesByStage))
+ .build();
+ }
+
+ private List<DatanodeStorageReport> collectDatanodeReports() {
+ return nodeManager.getAllNodes().stream()
+ .map(this::getStorageReport)
+ .filter(Objects::nonNull) // Filter out null reports
+ .collect(Collectors.toList());
+ }
+
+ private Map<String, Long> calculatePendingSizes() {
+ Map<String, Long> result = new HashMap<>();
+ KeyInsightInfoResponse response = reconGlobalMetricsService.getPendingForDeletionDirInfo(-1, "");
+ Map<String, Long> pendingKeySize = reconGlobalMetricsService.getDeletedKeySummary();
+ result.put("pendingDirectorySize", response.getReplicatedDataSize());
+ result.put("pendingKeySize", pendingKeySize.getOrDefault("totalReplicatedDataSize", 0L));
+ return result;
+ }
+
+ private long calculateOpenKeySizes() {
+ Map<String, Long> openKeySummary = reconGlobalMetricsService.getOpenKeySummary();
+ Map<String, Long> openKeyMPUSummary = reconGlobalMetricsService.getMPUKeySummary();
+ long openKeyDataSize = openKeySummary.getOrDefault("totalReplicatedDataSize", 0L);
+ long totalMPUKeySize = openKeyMPUSummary.getOrDefault("totalReplicatedDataSize", 0L);
+ return openKeyDataSize + totalMPUKeySize;
+ }
+
+ private long calculateCommittedSize() {
+ try {
+ Response rootResponse = nsSummaryEndpoint.getDiskUsage("/", false, true, false);
+ if (rootResponse.getStatus() != Response.Status.OK.getStatusCode()) {
+ LOG.warn("Failed to get disk usage, status: {}", rootResponse.getStatus());
+ return 0L;
+ }
+ DUResponse duRootRes = (DUResponse) rootResponse.getEntity();
+ return duRootRes != null ? duRootRes.getSizeWithReplica() : 0L;
+ } catch (IOException e) {
+ LOG.error("IOException while calculating committed size", e);
+ return 0L;
+ }
+ }
+
+ private DeletionPendingBytesByComponent createDeletionPendingBytesByStage(long pendingDirectorySize,
+ long pendingKeySize,
+ long totalPendingAtScmSide,
+ long totalPendingAtDnSide) {
+ long totalPending = pendingDirectorySize + pendingKeySize + totalPendingAtScmSide + totalPendingAtDnSide;
+ Map<String, Map<String, Long>> stageItems = new HashMap<>();
+ Map<String, Long> omMap = new HashMap<>();
+ omMap.put("totalBytes", pendingDirectorySize + pendingKeySize);
+ omMap.put("pendingDirectoryBytes", pendingDirectorySize);
+ omMap.put("pendingKeyBytes", pendingKeySize);
+ Map<String, Long> scmMap = new HashMap<>();
+ scmMap.put("pendingBytes", totalPendingAtScmSide);
+ Map<String, Long> dnMap = new HashMap<>();
+ dnMap.put("pendingBytes", totalPendingAtDnSide);
+ stageItems.put("OM", omMap);
+ stageItems.put("SCM", scmMap);
+ stageItems.put("DN", dnMap);
+ return new DeletionPendingBytesByComponent(totalPending, stageItems);
+ }
+
+ private void initializeBlockDeletionMetricsMap() {
+ List<JmxMetricsCollectorTask> tasks = nodeManager.getNodeStats().keySet().stream().map(dn ->
+ new JmxMetricsCollectorTask(conf, dn, "HddsDatanode",
+ "BlockDeletingService", "TotalPendingBlockBytes"))
+ .collect(Collectors.toList());
+ try {
+ int threadPoolSize = conf.getInt(
+ ReconConfigKeys.OZONE_RECON_JMX_FETCH_THREAD_POOL_SIZE,
+ ReconConfigKeys.OZONE_RECON_JMX_FETCH_THREAD_POOL_SIZE_DEFAULT);
+ ExecutorService executor = Executors.newFixedThreadPool(threadPoolSize);
+ List<Future<JmxMetricsCollectorTaskResult>> results = executor.invokeAll(tasks);
Review Comment:
Concerns below are :
1. Insufficient error handling - Silent failures, no differentiation between timeout/network/parse errors
2. Missing observability - No metrics for success/failure rates, latency
##########
hadoop-ozone/recon/src/main/java/org/apache/hadoop/ozone/recon/tasks/JmxMetricsCollectorTask.java:
##########
@@ -0,0 +1,154 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.hadoop.ozone.recon.tasks;
+
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import java.io.IOException;
+import java.io.InputStream;
+import java.net.HttpURLConnection;
+import java.net.URL;
+import java.nio.charset.StandardCharsets;
+import java.util.concurrent.Callable;
+import org.apache.commons.io.IOUtils;
+import org.apache.hadoop.hdds.conf.OzoneConfiguration;
+import org.apache.hadoop.hdds.protocol.DatanodeDetails;
+import org.apache.hadoop.hdds.recon.ReconConfigKeys;
+
+/**
+ * JmxMetricsCollectorTask is a Callable implementation that retrieves specific
+ * JMX metrics from a given DataNode's HTTP JMX endpoint. It fetches the metrics
+ * for a given service and metric name, parses the response JSON, and extracts
+ * the desired metric value.
+ * This task is primarily designed to collect metrics in a concurrent manner and
+ * return the results wrapped in a JmxMetricsCollectorTaskResult object, which
+ * contains the DataNode details and the fetched metric value.
+ */
+public class JmxMetricsCollectorTask implements Callable<JmxMetricsCollectorTaskResult> {
+
+ private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();
+
+ private final OzoneConfiguration configuration;
+ private final DatanodeDetails datanodeDetails;
+ private final String componentName;
+ private final String serviceName;
+ private final String keyName;
+
+ public JmxMetricsCollectorTask(OzoneConfiguration configuration, DatanodeDetails datanodeDetails,
+ String componentName, String serviceName, String keyName) {
+ this.datanodeDetails = datanodeDetails;
+ this.componentName = componentName;
+ this.serviceName = serviceName;
+ this.keyName = keyName;
+ this.configuration = configuration;
+ }
+
+ @Override
+ public JmxMetricsCollectorTaskResult call() throws Exception {
+ return getMetricsFromDatanode();
+ }
+
+ private JmxMetricsCollectorTaskResult getMetricsFromDatanode() throws IOException {
+ if (datanodeDetails == null) {
+ throw new IOException("DataNode details are null");
+ }
+ HttpURLConnection connection = null;
+ try {
+ // Use standard Java HttpURLConnection (compatible with all HTTP implementations)
+ URL url = new URL(getJmxMetricsUrl());
+ connection = (HttpURLConnection) url.openConnection();
Review Comment:
**Issue:** Better to use `HttpURLConnection` instead of `CloseableHttpClient`
If you use `HttpURLConnection`, then it has following problems:
1. No connection pooling (creates new connection per request)
2. Less robust timeout handling
3. No automatic retry logic
**Recommendation:** Switch to `CloseableHttpClient` used elsewhere in Ozone:
```
try (CloseableHttpClient httpClient = HttpClients.custom()
.setDefaultRequestConfig(RequestConfig.custom()
.setConnectTimeout(connectTimeout)
.setSocketTimeout(socketTimeout)
.build())
.build()) {
// ... make request
}
```
##########
hadoop-ozone/recon/src/main/java/org/apache/hadoop/ozone/recon/api/StorageDistributionEndpoint.java:
##########
@@ -0,0 +1,353 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.hadoop.ozone.recon.api;
+
+import static org.apache.hadoop.ozone.om.codec.OMDBDefinition.FILE_TABLE;
+import static org.apache.hadoop.ozone.om.codec.OMDBDefinition.KEY_TABLE;
+
+import java.io.IOException;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.ExecutionException;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+import java.util.concurrent.Future;
+import java.util.stream.Collectors;
+import javax.inject.Inject;
+import javax.ws.rs.GET;
+import javax.ws.rs.Path;
+import javax.ws.rs.Produces;
+import javax.ws.rs.core.Response;
+import org.apache.hadoop.hdds.conf.OzoneConfiguration;
+import org.apache.hadoop.hdds.protocol.DatanodeDetails;
+import org.apache.hadoop.hdds.protocol.proto.HddsProtos.DeletedBlocksTransactionSummary;
+import org.apache.hadoop.hdds.recon.ReconConfigKeys;
+import org.apache.hadoop.hdds.scm.container.placement.metrics.SCMNodeMetric;
+import org.apache.hadoop.hdds.scm.container.placement.metrics.SCMNodeStat;
+import org.apache.hadoop.hdds.scm.protocol.StorageContainerLocationProtocol;
+import org.apache.hadoop.hdds.scm.server.OzoneStorageContainerManager;
+import org.apache.hadoop.ozone.recon.api.types.DUResponse;
+import org.apache.hadoop.ozone.recon.api.types.DatanodeStorageReport;
+import org.apache.hadoop.ozone.recon.api.types.DeletionPendingBytesByComponent;
+import org.apache.hadoop.ozone.recon.api.types.GlobalNamespaceReport;
+import org.apache.hadoop.ozone.recon.api.types.GlobalStorageReport;
+import org.apache.hadoop.ozone.recon.api.types.KeyInsightInfoResponse;
+import org.apache.hadoop.ozone.recon.api.types.StorageCapacityDistributionResponse;
+import org.apache.hadoop.ozone.recon.api.types.UsedSpaceBreakDown;
+import org.apache.hadoop.ozone.recon.scm.ReconNodeManager;
+import org.apache.hadoop.ozone.recon.spi.ReconGlobalStatsManager;
+import org.apache.hadoop.ozone.recon.tasks.GlobalStatsValue;
+import org.apache.hadoop.ozone.recon.tasks.JmxMetricsCollectorTask;
+import org.apache.hadoop.ozone.recon.tasks.JmxMetricsCollectorTaskResult;
+import org.apache.hadoop.ozone.recon.tasks.OmTableInsightTask;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * This endpoint handles requests related to storage distribution across
+ * different datanodes in a Recon instance. It provides detailed reports
+ * on storage capacity, utilization, and associated metrics.
+ * <p>
+ * The data is aggregated from multiple sources, including node manager
+ * statistics, and is used to construct responses with information
+ * about global storage and namespace usage, storage usage breakdown,
+ * and deletion operations in progress.
+ * <p>
+ * An instance of {@link ReconNodeManager} is used to fetch detailed
+ * node-specific statistics required for generating the report.
+ */
+@Path("/storageDistribution")
+@Produces("application/json")
+@AdminOnly
+public class StorageDistributionEndpoint {
+ private final ReconNodeManager nodeManager;
+ private final NSSummaryEndpoint nsSummaryEndpoint;
+ private final StorageContainerLocationProtocol scmClient;
+ private static final Logger LOG = LoggerFactory.getLogger(StorageDistributionEndpoint.class);
+ private final Map<DatanodeDetails, Long> blockDeletionMetricsMap = new ConcurrentHashMap<>();
+ private final ReconGlobalStatsManager reconGlobalStatsManager;
+ private final ReconGlobalMetricsService reconGlobalMetricsService;
+ private final OzoneConfiguration conf;
+
+ @Inject
+ public StorageDistributionEndpoint(OzoneStorageContainerManager reconSCM,
+ NSSummaryEndpoint nsSummaryEndpoint,
+ ReconGlobalStatsManager reconGlobalStatsManager,
+ StorageContainerLocationProtocol scmClient,
+ ReconGlobalMetricsService reconGlobalMetricsService,
+ OzoneConfiguration conf) {
+ this.nodeManager = (ReconNodeManager) reconSCM.getScmNodeManager();
+ this.nsSummaryEndpoint = nsSummaryEndpoint;
+ this.scmClient = scmClient;
+ this.reconGlobalStatsManager = reconGlobalStatsManager;
+ this.reconGlobalMetricsService = reconGlobalMetricsService;
+ this.conf = conf;
+ }
+
+ @GET
+ public Response getStorageDistribution() {
+ try {
+ initializeBlockDeletionMetricsMap();
+ List<DatanodeStorageReport> nodeStorageReports = collectDatanodeReports();
+ GlobalStorageReport globalStorageReport = calculateGlobalStorageReport();
+
+ Map<String, Long> namespaceMetrics = new HashMap<>();
+ try {
+ namespaceMetrics = calculateNamespaceMetrics();
+ } catch (Exception e) {
+ LOG.error("Error calculating namespace metrics", e);
+ // Initialize with default values
+ namespaceMetrics.put("totalUsedNamespace", 0L);
+ namespaceMetrics.put("totalOpenKeySize", 0L);
+ namespaceMetrics.put("totalCommittedSize", 0L);
+ namespaceMetrics.put("pendingDirectorySize", 0L);
+ namespaceMetrics.put("pendingKeySize", 0L);
+ namespaceMetrics.put("totalKeys", 0L);
+ }
+
+ StorageCapacityDistributionResponse response = buildStorageDistributionResponse(
+ nodeStorageReports, globalStorageReport, namespaceMetrics);
+ return Response.ok(response).build();
+ } catch (Exception e) {
+ LOG.error("Error getting storage distribution", e);
+ return Response.status(Response.Status.INTERNAL_SERVER_ERROR)
+ .entity("Error retrieving storage distribution: " + e.getMessage())
+ .build();
+ }
+ }
+
+ private GlobalStorageReport calculateGlobalStorageReport() {
+ try {
+ SCMNodeStat stats = nodeManager.getStats();
+ if (stats == null) {
+ LOG.warn("Node manager stats are null, returning default values");
+ return new GlobalStorageReport(0L, 0L, 0L);
+ }
+
+ long scmUsed = stats.getScmUsed() != null ? stats.getScmUsed().get() : 0L;
+ long remaining = stats.getRemaining() != null ? stats.getRemaining().get() : 0L;
+ long capacity = stats.getCapacity() != null ? stats.getCapacity().get() : 0L;
+
+ return new GlobalStorageReport(scmUsed, remaining, capacity);
+ } catch (Exception e) {
+ LOG.error("Error calculating global storage report", e);
+ return new GlobalStorageReport(0L, 0L, 0L);
+ }
+ }
+
+ private Map<String, Long> calculateNamespaceMetrics() throws IOException {
+ Map<String, Long> metrics = new HashMap<>();
+ Map<String, Long> totalPendingAtOmSide = calculatePendingSizes();
+ long totalOpenKeySize = calculateOpenKeySizes();
+ long totalCommittedSize = calculateCommittedSize();
+ long pendingDirectorySize = totalPendingAtOmSide.getOrDefault("pendingDirectorySize", 0L);
+ long pendingKeySize = totalPendingAtOmSide.getOrDefault("pendingKeySize", 0L);
+ long totalUsedNamespace = pendingDirectorySize + pendingKeySize + totalOpenKeySize + totalCommittedSize;
+
+ long totalKeys = 0L;
+ // Keys from OBJECT_STORE buckets.
+ GlobalStatsValue keyRecord = reconGlobalStatsManager.getGlobalStatsValue(
+ OmTableInsightTask.getTableCountKeyFromTable(KEY_TABLE));
+ // Keys from FILE_SYSTEM_OPTIMIZED buckets
+ GlobalStatsValue fileRecord = reconGlobalStatsManager.getGlobalStatsValue(
+ OmTableInsightTask.getTableCountKeyFromTable(FILE_TABLE));
+ if (keyRecord != null) {
+ totalKeys += keyRecord.getValue();
+ }
+ if (fileRecord != null) {
+ totalKeys += fileRecord.getValue();
+ }
+
+ metrics.put("pendingDirectorySize", pendingDirectorySize);
+ metrics.put("pendingKeySize", pendingKeySize);
+ metrics.put("totalOpenKeySize", totalOpenKeySize);
+ metrics.put("totalCommittedSize", totalCommittedSize);
+ metrics.put("totalUsedNamespace", totalUsedNamespace);
+ metrics.put("totalKeys", totalKeys);
+ return metrics;
+ }
+
+ private StorageCapacityDistributionResponse buildStorageDistributionResponse(
+ List<DatanodeStorageReport> nodeStorageReports,
+ GlobalStorageReport storageMetrics,
+ Map<String, Long> namespaceMetrics) {
+ DeletedBlocksTransactionSummary scmSummary = null;
+ try {
+ scmSummary = scmClient.getDeletedBlockSummary();
+ } catch (IOException e) {
+ LOG.error("Failed to get deleted block summary from SCM", e);
+ }
+
+ long totalPendingAtDnSide = 0L;
+ try {
+ totalPendingAtDnSide = blockDeletionMetricsMap.values().stream().reduce(0L, Long::sum);
+ } catch (Exception e) {
+ LOG.error("Error calculating pending deletion metrics", e);
+ }
+
+ DeletionPendingBytesByComponent deletionPendingBytesByStage =
+ createDeletionPendingBytesByStage(
+ namespaceMetrics.getOrDefault("pendingDirectorySize", 0L),
+ namespaceMetrics.getOrDefault("pendingKeySize", 0L),
+ scmSummary != null ? scmSummary.getTotalBlockReplicatedSize() : 0L,
+ totalPendingAtDnSide);
+
+ // Safely get values from namespaceMetrics with null checks
+ Long totalUsedNamespace = namespaceMetrics.get("totalUsedNamespace");
+ Long totalOpenKeySize = namespaceMetrics.get("totalOpenKeySize");
+ Long totalCommittedSize = namespaceMetrics.get("totalCommittedSize");
+ Long totalKeys = namespaceMetrics.get("totalKeys");
+ Long totalContainerPreAllocated = nodeStorageReports.stream()
+ .map(DatanodeStorageReport::getCommitted)
+ .reduce(0L, Long::sum);
+
+ return StorageCapacityDistributionResponse.newBuilder()
+ .setDataNodeUsage(nodeStorageReports)
+ .setGlobalStorage(storageMetrics)
+ .setGlobalNamespace(new GlobalNamespaceReport(
+ totalUsedNamespace != null ? totalUsedNamespace : 0L,
+ totalKeys != null ? totalKeys : 0L))
+ .setUsedSpaceBreakDown(new UsedSpaceBreakDown(
+ totalOpenKeySize != null ? totalOpenKeySize : 0L,
+ totalCommittedSize != null ? totalCommittedSize : 0L, totalContainerPreAllocated,
+ deletionPendingBytesByStage))
+ .build();
+ }
+
+ private List<DatanodeStorageReport> collectDatanodeReports() {
+ return nodeManager.getAllNodes().stream()
+ .map(this::getStorageReport)
+ .filter(Objects::nonNull) // Filter out null reports
+ .collect(Collectors.toList());
+ }
+
+ private Map<String, Long> calculatePendingSizes() {
+ Map<String, Long> result = new HashMap<>();
+ KeyInsightInfoResponse response = reconGlobalMetricsService.getPendingForDeletionDirInfo(-1, "");
+ Map<String, Long> pendingKeySize = reconGlobalMetricsService.getDeletedKeySummary();
+ result.put("pendingDirectorySize", response.getReplicatedDataSize());
+ result.put("pendingKeySize", pendingKeySize.getOrDefault("totalReplicatedDataSize", 0L));
+ return result;
+ }
+
+ private long calculateOpenKeySizes() {
+ Map<String, Long> openKeySummary = reconGlobalMetricsService.getOpenKeySummary();
+ Map<String, Long> openKeyMPUSummary = reconGlobalMetricsService.getMPUKeySummary();
+ long openKeyDataSize = openKeySummary.getOrDefault("totalReplicatedDataSize", 0L);
+ long totalMPUKeySize = openKeyMPUSummary.getOrDefault("totalReplicatedDataSize", 0L);
+ return openKeyDataSize + totalMPUKeySize;
+ }
+
+ private long calculateCommittedSize() {
+ try {
+ Response rootResponse = nsSummaryEndpoint.getDiskUsage("/", false, true, false);
+ if (rootResponse.getStatus() != Response.Status.OK.getStatusCode()) {
+ LOG.warn("Failed to get disk usage, status: {}", rootResponse.getStatus());
+ return 0L;
+ }
+ DUResponse duRootRes = (DUResponse) rootResponse.getEntity();
+ return duRootRes != null ? duRootRes.getSizeWithReplica() : 0L;
+ } catch (IOException e) {
+ LOG.error("IOException while calculating committed size", e);
+ return 0L;
+ }
+ }
+
+ private DeletionPendingBytesByComponent createDeletionPendingBytesByStage(long pendingDirectorySize,
+ long pendingKeySize,
+ long totalPendingAtScmSide,
+ long totalPendingAtDnSide) {
+ long totalPending = pendingDirectorySize + pendingKeySize + totalPendingAtScmSide + totalPendingAtDnSide;
+ Map<String, Map<String, Long>> stageItems = new HashMap<>();
+ Map<String, Long> omMap = new HashMap<>();
+ omMap.put("totalBytes", pendingDirectorySize + pendingKeySize);
+ omMap.put("pendingDirectoryBytes", pendingDirectorySize);
+ omMap.put("pendingKeyBytes", pendingKeySize);
+ Map<String, Long> scmMap = new HashMap<>();
+ scmMap.put("pendingBytes", totalPendingAtScmSide);
+ Map<String, Long> dnMap = new HashMap<>();
+ dnMap.put("pendingBytes", totalPendingAtDnSide);
+ stageItems.put("OM", omMap);
+ stageItems.put("SCM", scmMap);
+ stageItems.put("DN", dnMap);
+ return new DeletionPendingBytesByComponent(totalPending, stageItems);
+ }
+
+ private void initializeBlockDeletionMetricsMap() {
+ List<JmxMetricsCollectorTask> tasks = nodeManager.getNodeStats().keySet().stream().map(dn ->
+ new JmxMetricsCollectorTask(conf, dn, "HddsDatanode",
+ "BlockDeletingService", "TotalPendingBlockBytes"))
+ .collect(Collectors.toList());
+ try {
+ int threadPoolSize = conf.getInt(
+ ReconConfigKeys.OZONE_RECON_JMX_FETCH_THREAD_POOL_SIZE,
+ ReconConfigKeys.OZONE_RECON_JMX_FETCH_THREAD_POOL_SIZE_DEFAULT);
Review Comment:
This is not needed to be called in every API call request.
##########
hadoop-ozone/recon/src/main/java/org/apache/hadoop/ozone/recon/api/StorageDistributionEndpoint.java:
##########
@@ -0,0 +1,353 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.hadoop.ozone.recon.api;
+
+import static org.apache.hadoop.ozone.om.codec.OMDBDefinition.FILE_TABLE;
+import static org.apache.hadoop.ozone.om.codec.OMDBDefinition.KEY_TABLE;
+
+import java.io.IOException;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.ExecutionException;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+import java.util.concurrent.Future;
+import java.util.stream.Collectors;
+import javax.inject.Inject;
+import javax.ws.rs.GET;
+import javax.ws.rs.Path;
+import javax.ws.rs.Produces;
+import javax.ws.rs.core.Response;
+import org.apache.hadoop.hdds.conf.OzoneConfiguration;
+import org.apache.hadoop.hdds.protocol.DatanodeDetails;
+import org.apache.hadoop.hdds.protocol.proto.HddsProtos.DeletedBlocksTransactionSummary;
+import org.apache.hadoop.hdds.recon.ReconConfigKeys;
+import org.apache.hadoop.hdds.scm.container.placement.metrics.SCMNodeMetric;
+import org.apache.hadoop.hdds.scm.container.placement.metrics.SCMNodeStat;
+import org.apache.hadoop.hdds.scm.protocol.StorageContainerLocationProtocol;
+import org.apache.hadoop.hdds.scm.server.OzoneStorageContainerManager;
+import org.apache.hadoop.ozone.recon.api.types.DUResponse;
+import org.apache.hadoop.ozone.recon.api.types.DatanodeStorageReport;
+import org.apache.hadoop.ozone.recon.api.types.DeletionPendingBytesByComponent;
+import org.apache.hadoop.ozone.recon.api.types.GlobalNamespaceReport;
+import org.apache.hadoop.ozone.recon.api.types.GlobalStorageReport;
+import org.apache.hadoop.ozone.recon.api.types.KeyInsightInfoResponse;
+import org.apache.hadoop.ozone.recon.api.types.StorageCapacityDistributionResponse;
+import org.apache.hadoop.ozone.recon.api.types.UsedSpaceBreakDown;
+import org.apache.hadoop.ozone.recon.scm.ReconNodeManager;
+import org.apache.hadoop.ozone.recon.spi.ReconGlobalStatsManager;
+import org.apache.hadoop.ozone.recon.tasks.GlobalStatsValue;
+import org.apache.hadoop.ozone.recon.tasks.JmxMetricsCollectorTask;
+import org.apache.hadoop.ozone.recon.tasks.JmxMetricsCollectorTaskResult;
+import org.apache.hadoop.ozone.recon.tasks.OmTableInsightTask;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * This endpoint handles requests related to storage distribution across
+ * different datanodes in a Recon instance. It provides detailed reports
+ * on storage capacity, utilization, and associated metrics.
+ * <p>
+ * The data is aggregated from multiple sources, including node manager
+ * statistics, and is used to construct responses with information
+ * about global storage and namespace usage, storage usage breakdown,
+ * and deletion operations in progress.
+ * <p>
+ * An instance of {@link ReconNodeManager} is used to fetch detailed
+ * node-specific statistics required for generating the report.
+ */
+@Path("/storageDistribution")
+@Produces("application/json")
+@AdminOnly
+public class StorageDistributionEndpoint {
+ private final ReconNodeManager nodeManager;
+ private final NSSummaryEndpoint nsSummaryEndpoint;
+ private final StorageContainerLocationProtocol scmClient;
+ private static final Logger LOG = LoggerFactory.getLogger(StorageDistributionEndpoint.class);
+ private final Map<DatanodeDetails, Long> blockDeletionMetricsMap = new ConcurrentHashMap<>();
+ private final ReconGlobalStatsManager reconGlobalStatsManager;
+ private final ReconGlobalMetricsService reconGlobalMetricsService;
+ private final OzoneConfiguration conf;
+
+ @Inject
+ public StorageDistributionEndpoint(OzoneStorageContainerManager reconSCM,
+ NSSummaryEndpoint nsSummaryEndpoint,
+ ReconGlobalStatsManager reconGlobalStatsManager,
+ StorageContainerLocationProtocol scmClient,
+ ReconGlobalMetricsService reconGlobalMetricsService,
+ OzoneConfiguration conf) {
+ this.nodeManager = (ReconNodeManager) reconSCM.getScmNodeManager();
+ this.nsSummaryEndpoint = nsSummaryEndpoint;
+ this.scmClient = scmClient;
+ this.reconGlobalStatsManager = reconGlobalStatsManager;
+ this.reconGlobalMetricsService = reconGlobalMetricsService;
+ this.conf = conf;
+ }
+
+ @GET
+ public Response getStorageDistribution() {
+ try {
+ initializeBlockDeletionMetricsMap();
+ List<DatanodeStorageReport> nodeStorageReports = collectDatanodeReports();
+ GlobalStorageReport globalStorageReport = calculateGlobalStorageReport();
+
+ Map<String, Long> namespaceMetrics = new HashMap<>();
+ try {
+ namespaceMetrics = calculateNamespaceMetrics();
+ } catch (Exception e) {
+ LOG.error("Error calculating namespace metrics", e);
+ // Initialize with default values
+ namespaceMetrics.put("totalUsedNamespace", 0L);
+ namespaceMetrics.put("totalOpenKeySize", 0L);
+ namespaceMetrics.put("totalCommittedSize", 0L);
+ namespaceMetrics.put("pendingDirectorySize", 0L);
+ namespaceMetrics.put("pendingKeySize", 0L);
+ namespaceMetrics.put("totalKeys", 0L);
+ }
+
+ StorageCapacityDistributionResponse response = buildStorageDistributionResponse(
+ nodeStorageReports, globalStorageReport, namespaceMetrics);
+ return Response.ok(response).build();
+ } catch (Exception e) {
+ LOG.error("Error getting storage distribution", e);
+ return Response.status(Response.Status.INTERNAL_SERVER_ERROR)
+ .entity("Error retrieving storage distribution: " + e.getMessage())
+ .build();
+ }
+ }
+
+ private GlobalStorageReport calculateGlobalStorageReport() {
+ try {
+ SCMNodeStat stats = nodeManager.getStats();
+ if (stats == null) {
+ LOG.warn("Node manager stats are null, returning default values");
+ return new GlobalStorageReport(0L, 0L, 0L);
+ }
+
+ long scmUsed = stats.getScmUsed() != null ? stats.getScmUsed().get() : 0L;
+ long remaining = stats.getRemaining() != null ? stats.getRemaining().get() : 0L;
+ long capacity = stats.getCapacity() != null ? stats.getCapacity().get() : 0L;
+
+ return new GlobalStorageReport(scmUsed, remaining, capacity);
+ } catch (Exception e) {
+ LOG.error("Error calculating global storage report", e);
+ return new GlobalStorageReport(0L, 0L, 0L);
+ }
+ }
+
+ private Map<String, Long> calculateNamespaceMetrics() throws IOException {
+ Map<String, Long> metrics = new HashMap<>();
+ Map<String, Long> totalPendingAtOmSide = calculatePendingSizes();
+ long totalOpenKeySize = calculateOpenKeySizes();
+ long totalCommittedSize = calculateCommittedSize();
+ long pendingDirectorySize = totalPendingAtOmSide.getOrDefault("pendingDirectorySize", 0L);
+ long pendingKeySize = totalPendingAtOmSide.getOrDefault("pendingKeySize", 0L);
+ long totalUsedNamespace = pendingDirectorySize + pendingKeySize + totalOpenKeySize + totalCommittedSize;
+
+ long totalKeys = 0L;
+ // Keys from OBJECT_STORE buckets.
+ GlobalStatsValue keyRecord = reconGlobalStatsManager.getGlobalStatsValue(
+ OmTableInsightTask.getTableCountKeyFromTable(KEY_TABLE));
+ // Keys from FILE_SYSTEM_OPTIMIZED buckets
+ GlobalStatsValue fileRecord = reconGlobalStatsManager.getGlobalStatsValue(
+ OmTableInsightTask.getTableCountKeyFromTable(FILE_TABLE));
+ if (keyRecord != null) {
+ totalKeys += keyRecord.getValue();
+ }
+ if (fileRecord != null) {
+ totalKeys += fileRecord.getValue();
+ }
+
+ metrics.put("pendingDirectorySize", pendingDirectorySize);
+ metrics.put("pendingKeySize", pendingKeySize);
+ metrics.put("totalOpenKeySize", totalOpenKeySize);
+ metrics.put("totalCommittedSize", totalCommittedSize);
+ metrics.put("totalUsedNamespace", totalUsedNamespace);
+ metrics.put("totalKeys", totalKeys);
+ return metrics;
+ }
+
+ private StorageCapacityDistributionResponse buildStorageDistributionResponse(
+ List<DatanodeStorageReport> nodeStorageReports,
+ GlobalStorageReport storageMetrics,
+ Map<String, Long> namespaceMetrics) {
+ DeletedBlocksTransactionSummary scmSummary = null;
+ try {
+ scmSummary = scmClient.getDeletedBlockSummary();
+ } catch (IOException e) {
+ LOG.error("Failed to get deleted block summary from SCM", e);
+ }
+
+ long totalPendingAtDnSide = 0L;
+ try {
+ totalPendingAtDnSide = blockDeletionMetricsMap.values().stream().reduce(0L, Long::sum);
+ } catch (Exception e) {
+ LOG.error("Error calculating pending deletion metrics", e);
+ }
+
+ DeletionPendingBytesByComponent deletionPendingBytesByStage =
+ createDeletionPendingBytesByStage(
+ namespaceMetrics.getOrDefault("pendingDirectorySize", 0L),
+ namespaceMetrics.getOrDefault("pendingKeySize", 0L),
+ scmSummary != null ? scmSummary.getTotalBlockReplicatedSize() : 0L,
+ totalPendingAtDnSide);
+
+ // Safely get values from namespaceMetrics with null checks
+ Long totalUsedNamespace = namespaceMetrics.get("totalUsedNamespace");
+ Long totalOpenKeySize = namespaceMetrics.get("totalOpenKeySize");
+ Long totalCommittedSize = namespaceMetrics.get("totalCommittedSize");
+ Long totalKeys = namespaceMetrics.get("totalKeys");
+ Long totalContainerPreAllocated = nodeStorageReports.stream()
+ .map(DatanodeStorageReport::getCommitted)
+ .reduce(0L, Long::sum);
+
+ return StorageCapacityDistributionResponse.newBuilder()
+ .setDataNodeUsage(nodeStorageReports)
+ .setGlobalStorage(storageMetrics)
+ .setGlobalNamespace(new GlobalNamespaceReport(
+ totalUsedNamespace != null ? totalUsedNamespace : 0L,
+ totalKeys != null ? totalKeys : 0L))
+ .setUsedSpaceBreakDown(new UsedSpaceBreakDown(
+ totalOpenKeySize != null ? totalOpenKeySize : 0L,
+ totalCommittedSize != null ? totalCommittedSize : 0L, totalContainerPreAllocated,
+ deletionPendingBytesByStage))
+ .build();
+ }
+
+ private List<DatanodeStorageReport> collectDatanodeReports() {
+ return nodeManager.getAllNodes().stream()
+ .map(this::getStorageReport)
+ .filter(Objects::nonNull) // Filter out null reports
+ .collect(Collectors.toList());
+ }
+
+ private Map<String, Long> calculatePendingSizes() {
+ Map<String, Long> result = new HashMap<>();
+ KeyInsightInfoResponse response = reconGlobalMetricsService.getPendingForDeletionDirInfo(-1, "");
+ Map<String, Long> pendingKeySize = reconGlobalMetricsService.getDeletedKeySummary();
+ result.put("pendingDirectorySize", response.getReplicatedDataSize());
+ result.put("pendingKeySize", pendingKeySize.getOrDefault("totalReplicatedDataSize", 0L));
+ return result;
+ }
+
+ private long calculateOpenKeySizes() {
+ Map<String, Long> openKeySummary = reconGlobalMetricsService.getOpenKeySummary();
+ Map<String, Long> openKeyMPUSummary = reconGlobalMetricsService.getMPUKeySummary();
+ long openKeyDataSize = openKeySummary.getOrDefault("totalReplicatedDataSize", 0L);
+ long totalMPUKeySize = openKeyMPUSummary.getOrDefault("totalReplicatedDataSize", 0L);
+ return openKeyDataSize + totalMPUKeySize;
+ }
+
+ private long calculateCommittedSize() {
+ try {
+ Response rootResponse = nsSummaryEndpoint.getDiskUsage("/", false, true, false);
+ if (rootResponse.getStatus() != Response.Status.OK.getStatusCode()) {
+ LOG.warn("Failed to get disk usage, status: {}", rootResponse.getStatus());
+ return 0L;
+ }
+ DUResponse duRootRes = (DUResponse) rootResponse.getEntity();
+ return duRootRes != null ? duRootRes.getSizeWithReplica() : 0L;
+ } catch (IOException e) {
+ LOG.error("IOException while calculating committed size", e);
+ return 0L;
+ }
+ }
+
+ private DeletionPendingBytesByComponent createDeletionPendingBytesByStage(long pendingDirectorySize,
+ long pendingKeySize,
+ long totalPendingAtScmSide,
+ long totalPendingAtDnSide) {
+ long totalPending = pendingDirectorySize + pendingKeySize + totalPendingAtScmSide + totalPendingAtDnSide;
+ Map<String, Map<String, Long>> stageItems = new HashMap<>();
+ Map<String, Long> omMap = new HashMap<>();
+ omMap.put("totalBytes", pendingDirectorySize + pendingKeySize);
+ omMap.put("pendingDirectoryBytes", pendingDirectorySize);
+ omMap.put("pendingKeyBytes", pendingKeySize);
+ Map<String, Long> scmMap = new HashMap<>();
+ scmMap.put("pendingBytes", totalPendingAtScmSide);
+ Map<String, Long> dnMap = new HashMap<>();
+ dnMap.put("pendingBytes", totalPendingAtDnSide);
+ stageItems.put("OM", omMap);
+ stageItems.put("SCM", scmMap);
+ stageItems.put("DN", dnMap);
+ return new DeletionPendingBytesByComponent(totalPending, stageItems);
+ }
+
+ private void initializeBlockDeletionMetricsMap() {
+ List<JmxMetricsCollectorTask> tasks = nodeManager.getNodeStats().keySet().stream().map(dn ->
+ new JmxMetricsCollectorTask(conf, dn, "HddsDatanode",
+ "BlockDeletingService", "TotalPendingBlockBytes"))
+ .collect(Collectors.toList());
+ try {
+ int threadPoolSize = conf.getInt(
+ ReconConfigKeys.OZONE_RECON_JMX_FETCH_THREAD_POOL_SIZE,
+ ReconConfigKeys.OZONE_RECON_JMX_FETCH_THREAD_POOL_SIZE_DEFAULT);
+ ExecutorService executor = Executors.newFixedThreadPool(threadPoolSize);
Review Comment:
This is not needed to be called in every API call request.
##########
hadoop-ozone/recon/src/main/java/org/apache/hadoop/ozone/recon/api/StorageDistributionEndpoint.java:
##########
@@ -0,0 +1,353 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.hadoop.ozone.recon.api;
+
+import static org.apache.hadoop.ozone.om.codec.OMDBDefinition.FILE_TABLE;
+import static org.apache.hadoop.ozone.om.codec.OMDBDefinition.KEY_TABLE;
+
+import java.io.IOException;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.ExecutionException;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+import java.util.concurrent.Future;
+import java.util.stream.Collectors;
+import javax.inject.Inject;
+import javax.ws.rs.GET;
+import javax.ws.rs.Path;
+import javax.ws.rs.Produces;
+import javax.ws.rs.core.Response;
+import org.apache.hadoop.hdds.conf.OzoneConfiguration;
+import org.apache.hadoop.hdds.protocol.DatanodeDetails;
+import org.apache.hadoop.hdds.protocol.proto.HddsProtos.DeletedBlocksTransactionSummary;
+import org.apache.hadoop.hdds.recon.ReconConfigKeys;
+import org.apache.hadoop.hdds.scm.container.placement.metrics.SCMNodeMetric;
+import org.apache.hadoop.hdds.scm.container.placement.metrics.SCMNodeStat;
+import org.apache.hadoop.hdds.scm.protocol.StorageContainerLocationProtocol;
+import org.apache.hadoop.hdds.scm.server.OzoneStorageContainerManager;
+import org.apache.hadoop.ozone.recon.api.types.DUResponse;
+import org.apache.hadoop.ozone.recon.api.types.DatanodeStorageReport;
+import org.apache.hadoop.ozone.recon.api.types.DeletionPendingBytesByComponent;
+import org.apache.hadoop.ozone.recon.api.types.GlobalNamespaceReport;
+import org.apache.hadoop.ozone.recon.api.types.GlobalStorageReport;
+import org.apache.hadoop.ozone.recon.api.types.KeyInsightInfoResponse;
+import org.apache.hadoop.ozone.recon.api.types.StorageCapacityDistributionResponse;
+import org.apache.hadoop.ozone.recon.api.types.UsedSpaceBreakDown;
+import org.apache.hadoop.ozone.recon.scm.ReconNodeManager;
+import org.apache.hadoop.ozone.recon.spi.ReconGlobalStatsManager;
+import org.apache.hadoop.ozone.recon.tasks.GlobalStatsValue;
+import org.apache.hadoop.ozone.recon.tasks.JmxMetricsCollectorTask;
+import org.apache.hadoop.ozone.recon.tasks.JmxMetricsCollectorTaskResult;
+import org.apache.hadoop.ozone.recon.tasks.OmTableInsightTask;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * This endpoint handles requests related to storage distribution across
+ * different datanodes in a Recon instance. It provides detailed reports
+ * on storage capacity, utilization, and associated metrics.
+ * <p>
+ * The data is aggregated from multiple sources, including node manager
+ * statistics, and is used to construct responses with information
+ * about global storage and namespace usage, storage usage breakdown,
+ * and deletion operations in progress.
+ * <p>
+ * An instance of {@link ReconNodeManager} is used to fetch detailed
+ * node-specific statistics required for generating the report.
+ */
+@Path("/storageDistribution")
+@Produces("application/json")
+@AdminOnly
+public class StorageDistributionEndpoint {
+ private final ReconNodeManager nodeManager;
+ private final NSSummaryEndpoint nsSummaryEndpoint;
+ private final StorageContainerLocationProtocol scmClient;
+ private static final Logger LOG = LoggerFactory.getLogger(StorageDistributionEndpoint.class);
+ private final Map<DatanodeDetails, Long> blockDeletionMetricsMap = new ConcurrentHashMap<>();
+ private final ReconGlobalStatsManager reconGlobalStatsManager;
+ private final ReconGlobalMetricsService reconGlobalMetricsService;
+ private final OzoneConfiguration conf;
+
+ @Inject
+ public StorageDistributionEndpoint(OzoneStorageContainerManager reconSCM,
+ NSSummaryEndpoint nsSummaryEndpoint,
+ ReconGlobalStatsManager reconGlobalStatsManager,
+ StorageContainerLocationProtocol scmClient,
+ ReconGlobalMetricsService reconGlobalMetricsService,
+ OzoneConfiguration conf) {
+ this.nodeManager = (ReconNodeManager) reconSCM.getScmNodeManager();
+ this.nsSummaryEndpoint = nsSummaryEndpoint;
+ this.scmClient = scmClient;
+ this.reconGlobalStatsManager = reconGlobalStatsManager;
+ this.reconGlobalMetricsService = reconGlobalMetricsService;
+ this.conf = conf;
+ }
+
+ @GET
+ public Response getStorageDistribution() {
+ try {
+ initializeBlockDeletionMetricsMap();
+ List<DatanodeStorageReport> nodeStorageReports = collectDatanodeReports();
+ GlobalStorageReport globalStorageReport = calculateGlobalStorageReport();
+
+ Map<String, Long> namespaceMetrics = new HashMap<>();
+ try {
+ namespaceMetrics = calculateNamespaceMetrics();
+ } catch (Exception e) {
+ LOG.error("Error calculating namespace metrics", e);
+ // Initialize with default values
+ namespaceMetrics.put("totalUsedNamespace", 0L);
+ namespaceMetrics.put("totalOpenKeySize", 0L);
+ namespaceMetrics.put("totalCommittedSize", 0L);
+ namespaceMetrics.put("pendingDirectorySize", 0L);
+ namespaceMetrics.put("pendingKeySize", 0L);
+ namespaceMetrics.put("totalKeys", 0L);
+ }
+
+ StorageCapacityDistributionResponse response = buildStorageDistributionResponse(
+ nodeStorageReports, globalStorageReport, namespaceMetrics);
+ return Response.ok(response).build();
+ } catch (Exception e) {
+ LOG.error("Error getting storage distribution", e);
+ return Response.status(Response.Status.INTERNAL_SERVER_ERROR)
+ .entity("Error retrieving storage distribution: " + e.getMessage())
+ .build();
+ }
+ }
+
+ private GlobalStorageReport calculateGlobalStorageReport() {
+ try {
+ SCMNodeStat stats = nodeManager.getStats();
+ if (stats == null) {
+ LOG.warn("Node manager stats are null, returning default values");
+ return new GlobalStorageReport(0L, 0L, 0L);
+ }
+
+ long scmUsed = stats.getScmUsed() != null ? stats.getScmUsed().get() : 0L;
+ long remaining = stats.getRemaining() != null ? stats.getRemaining().get() : 0L;
+ long capacity = stats.getCapacity() != null ? stats.getCapacity().get() : 0L;
+
+ return new GlobalStorageReport(scmUsed, remaining, capacity);
+ } catch (Exception e) {
+ LOG.error("Error calculating global storage report", e);
+ return new GlobalStorageReport(0L, 0L, 0L);
+ }
+ }
+
+ private Map<String, Long> calculateNamespaceMetrics() throws IOException {
+ Map<String, Long> metrics = new HashMap<>();
+ Map<String, Long> totalPendingAtOmSide = calculatePendingSizes();
+ long totalOpenKeySize = calculateOpenKeySizes();
+ long totalCommittedSize = calculateCommittedSize();
+ long pendingDirectorySize = totalPendingAtOmSide.getOrDefault("pendingDirectorySize", 0L);
+ long pendingKeySize = totalPendingAtOmSide.getOrDefault("pendingKeySize", 0L);
+ long totalUsedNamespace = pendingDirectorySize + pendingKeySize + totalOpenKeySize + totalCommittedSize;
+
+ long totalKeys = 0L;
+ // Keys from OBJECT_STORE buckets.
+ GlobalStatsValue keyRecord = reconGlobalStatsManager.getGlobalStatsValue(
+ OmTableInsightTask.getTableCountKeyFromTable(KEY_TABLE));
+ // Keys from FILE_SYSTEM_OPTIMIZED buckets
+ GlobalStatsValue fileRecord = reconGlobalStatsManager.getGlobalStatsValue(
+ OmTableInsightTask.getTableCountKeyFromTable(FILE_TABLE));
+ if (keyRecord != null) {
+ totalKeys += keyRecord.getValue();
+ }
+ if (fileRecord != null) {
+ totalKeys += fileRecord.getValue();
+ }
+
+ metrics.put("pendingDirectorySize", pendingDirectorySize);
+ metrics.put("pendingKeySize", pendingKeySize);
+ metrics.put("totalOpenKeySize", totalOpenKeySize);
+ metrics.put("totalCommittedSize", totalCommittedSize);
+ metrics.put("totalUsedNamespace", totalUsedNamespace);
+ metrics.put("totalKeys", totalKeys);
+ return metrics;
+ }
+
+ private StorageCapacityDistributionResponse buildStorageDistributionResponse(
+ List<DatanodeStorageReport> nodeStorageReports,
+ GlobalStorageReport storageMetrics,
+ Map<String, Long> namespaceMetrics) {
+ DeletedBlocksTransactionSummary scmSummary = null;
+ try {
+ scmSummary = scmClient.getDeletedBlockSummary();
+ } catch (IOException e) {
+ LOG.error("Failed to get deleted block summary from SCM", e);
+ }
+
+ long totalPendingAtDnSide = 0L;
+ try {
+ totalPendingAtDnSide = blockDeletionMetricsMap.values().stream().reduce(0L, Long::sum);
+ } catch (Exception e) {
+ LOG.error("Error calculating pending deletion metrics", e);
+ }
+
+ DeletionPendingBytesByComponent deletionPendingBytesByStage =
+ createDeletionPendingBytesByStage(
+ namespaceMetrics.getOrDefault("pendingDirectorySize", 0L),
+ namespaceMetrics.getOrDefault("pendingKeySize", 0L),
+ scmSummary != null ? scmSummary.getTotalBlockReplicatedSize() : 0L,
+ totalPendingAtDnSide);
+
+ // Safely get values from namespaceMetrics with null checks
+ Long totalUsedNamespace = namespaceMetrics.get("totalUsedNamespace");
+ Long totalOpenKeySize = namespaceMetrics.get("totalOpenKeySize");
+ Long totalCommittedSize = namespaceMetrics.get("totalCommittedSize");
+ Long totalKeys = namespaceMetrics.get("totalKeys");
+ Long totalContainerPreAllocated = nodeStorageReports.stream()
+ .map(DatanodeStorageReport::getCommitted)
+ .reduce(0L, Long::sum);
+
+ return StorageCapacityDistributionResponse.newBuilder()
+ .setDataNodeUsage(nodeStorageReports)
+ .setGlobalStorage(storageMetrics)
+ .setGlobalNamespace(new GlobalNamespaceReport(
+ totalUsedNamespace != null ? totalUsedNamespace : 0L,
+ totalKeys != null ? totalKeys : 0L))
+ .setUsedSpaceBreakDown(new UsedSpaceBreakDown(
+ totalOpenKeySize != null ? totalOpenKeySize : 0L,
+ totalCommittedSize != null ? totalCommittedSize : 0L, totalContainerPreAllocated,
+ deletionPendingBytesByStage))
+ .build();
+ }
+
+ private List<DatanodeStorageReport> collectDatanodeReports() {
+ return nodeManager.getAllNodes().stream()
+ .map(this::getStorageReport)
+ .filter(Objects::nonNull) // Filter out null reports
+ .collect(Collectors.toList());
+ }
+
+ private Map<String, Long> calculatePendingSizes() {
+ Map<String, Long> result = new HashMap<>();
+ KeyInsightInfoResponse response = reconGlobalMetricsService.getPendingForDeletionDirInfo(-1, "");
+ Map<String, Long> pendingKeySize = reconGlobalMetricsService.getDeletedKeySummary();
+ result.put("pendingDirectorySize", response.getReplicatedDataSize());
+ result.put("pendingKeySize", pendingKeySize.getOrDefault("totalReplicatedDataSize", 0L));
+ return result;
+ }
+
+ private long calculateOpenKeySizes() {
+ Map<String, Long> openKeySummary = reconGlobalMetricsService.getOpenKeySummary();
+ Map<String, Long> openKeyMPUSummary = reconGlobalMetricsService.getMPUKeySummary();
+ long openKeyDataSize = openKeySummary.getOrDefault("totalReplicatedDataSize", 0L);
+ long totalMPUKeySize = openKeyMPUSummary.getOrDefault("totalReplicatedDataSize", 0L);
+ return openKeyDataSize + totalMPUKeySize;
+ }
+
+ private long calculateCommittedSize() {
+ try {
+ Response rootResponse = nsSummaryEndpoint.getDiskUsage("/", false, true, false);
+ if (rootResponse.getStatus() != Response.Status.OK.getStatusCode()) {
+ LOG.warn("Failed to get disk usage, status: {}", rootResponse.getStatus());
+ return 0L;
+ }
+ DUResponse duRootRes = (DUResponse) rootResponse.getEntity();
+ return duRootRes != null ? duRootRes.getSizeWithReplica() : 0L;
+ } catch (IOException e) {
+ LOG.error("IOException while calculating committed size", e);
+ return 0L;
+ }
+ }
+
+ private DeletionPendingBytesByComponent createDeletionPendingBytesByStage(long pendingDirectorySize,
+ long pendingKeySize,
+ long totalPendingAtScmSide,
+ long totalPendingAtDnSide) {
+ long totalPending = pendingDirectorySize + pendingKeySize + totalPendingAtScmSide + totalPendingAtDnSide;
+ Map<String, Map<String, Long>> stageItems = new HashMap<>();
+ Map<String, Long> omMap = new HashMap<>();
+ omMap.put("totalBytes", pendingDirectorySize + pendingKeySize);
+ omMap.put("pendingDirectoryBytes", pendingDirectorySize);
+ omMap.put("pendingKeyBytes", pendingKeySize);
+ Map<String, Long> scmMap = new HashMap<>();
+ scmMap.put("pendingBytes", totalPendingAtScmSide);
+ Map<String, Long> dnMap = new HashMap<>();
+ dnMap.put("pendingBytes", totalPendingAtDnSide);
+ stageItems.put("OM", omMap);
+ stageItems.put("SCM", scmMap);
+ stageItems.put("DN", dnMap);
+ return new DeletionPendingBytesByComponent(totalPending, stageItems);
+ }
+
+ private void initializeBlockDeletionMetricsMap() {
+ List<JmxMetricsCollectorTask> tasks = nodeManager.getNodeStats().keySet().stream().map(dn ->
+ new JmxMetricsCollectorTask(conf, dn, "HddsDatanode",
+ "BlockDeletingService", "TotalPendingBlockBytes"))
+ .collect(Collectors.toList());
+ try {
+ int threadPoolSize = conf.getInt(
+ ReconConfigKeys.OZONE_RECON_JMX_FETCH_THREAD_POOL_SIZE,
+ ReconConfigKeys.OZONE_RECON_JMX_FETCH_THREAD_POOL_SIZE_DEFAULT);
+ ExecutorService executor = Executors.newFixedThreadPool(threadPoolSize);
+ List<Future<JmxMetricsCollectorTaskResult>> results = executor.invokeAll(tasks);
Review Comment:
This solution is not scalable as mentioned earlier. In 1000 nodes cluster with just 10 threads in pool will take lot of time and API response will be very slow. Kindly implement the correct scalable solution. Also creating executor pool like this in every API request and not closing and releasing resources will create further issues:
Every API call creates a new thread pool that's never shutdown. This will cause:
- Thread exhaustion
- Memory leaks
- File descriptor leaks
- Production outages
Also above solution is not scalable , what if some DNs are slow, we don't have any mechanism to timeout ? If even timeout, will it do failure of whole API ? What is the way to handle ?
--
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-13465. Adding endpoint at Recon to get consolidated storage dist… [ozone]
Posted by "priyeshkaratha (via GitHub)" <gi...@apache.org>.
priyeshkaratha commented on code in PR #9326:
URL: https://github.com/apache/ozone/pull/9326#discussion_r2547023021
##########
hadoop-ozone/recon/src/test/java/org/apache/hadoop/ozone/recon/api/TestStorageDistributionEndpoint.java:
##########
@@ -0,0 +1,452 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.hadoop.ozone.recon.api;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.ArgumentMatchers.anyInt;
+import static org.mockito.ArgumentMatchers.anyString;
+import static org.mockito.Mockito.anyMap;
+import static org.mockito.Mockito.doAnswer;
+import static org.mockito.Mockito.doThrow;
+import static org.mockito.Mockito.eq;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.when;
+
+import java.io.IOException;
+import java.sql.Timestamp;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import javax.ws.rs.core.Response;
+import org.apache.hadoop.hdds.protocol.proto.HddsProtos.DeletedBlocksTransactionSummary;
+import org.apache.hadoop.hdds.scm.container.placement.metrics.LongMetric;
+import org.apache.hadoop.hdds.scm.container.placement.metrics.SCMNodeMetric;
+import org.apache.hadoop.hdds.scm.container.placement.metrics.SCMNodeStat;
+import org.apache.hadoop.hdds.scm.node.DatanodeInfo;
+import org.apache.hadoop.hdds.scm.protocol.StorageContainerLocationProtocol;
+import org.apache.hadoop.hdds.scm.server.OzoneStorageContainerManager;
+import org.apache.hadoop.ozone.recon.api.types.DUResponse;
+import org.apache.hadoop.ozone.recon.api.types.DeletionPendingBytesByComponent;
+import org.apache.hadoop.ozone.recon.api.types.GlobalNamespaceReport;
+import org.apache.hadoop.ozone.recon.api.types.GlobalStorageReport;
+import org.apache.hadoop.ozone.recon.api.types.KeyInsightInfoResponse;
+import org.apache.hadoop.ozone.recon.api.types.StorageCapacityDistributionResponse;
+import org.apache.hadoop.ozone.recon.api.types.UsedSpaceBreakDown;
+import org.apache.hadoop.ozone.recon.scm.ReconNodeManager;
+import org.apache.ozone.recon.schema.generated.tables.daos.GlobalStatsDao;
+import org.apache.ozone.recon.schema.generated.tables.pojos.GlobalStats;
+import org.junit.jupiter.api.Test;
+
+/**
+ * Test class for StorageDistributionEndpoint, responsible for testing
+ * the behavior and responses of the storage distribution endpoint in
+ * different scenarios, including successful responses and exception cases.
+ */
+class TestStorageDistributionEndpoint {
Review Comment:
I will handle it as part of https://issues.apache.org/jira/browse/HDDS-13968 since code changes are huge.
--
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-13465. Adding endpoint at Recon to get consolidated storage dist… [ozone]
Posted by "priyeshkaratha (via GitHub)" <gi...@apache.org>.
priyeshkaratha commented on code in PR #9326:
URL: https://github.com/apache/ozone/pull/9326#discussion_r2543000004
##########
hadoop-ozone/recon/src/main/java/org/apache/hadoop/ozone/recon/ReconUtils.java:
##########
@@ -847,4 +899,53 @@ public static String constructObjectPathWithPrefix(long... ids) {
}
return pathBuilder.toString();
}
+
+ public static long getMetricsFromDatanode(DatanodeDetails datanode, String service, String name, String keyName)
+ throws IOException {
+ // Construct metrics URL for DataNode JMX endpoint
+ String metricsUrl = String.format("http://%s:%d/jmx?qry=Hadoop:service=%s,name=%s",
+ datanode.getIpAddress(),
+ datanode.getPort(DatanodeDetails.Port.Name.HTTP).getValue(),
+ service,
+ name);
+ HttpGet request = new HttpGet(metricsUrl);
+ try (CloseableHttpResponse response = httpClient.execute(request)) {
+ if (response.getStatusLine().getStatusCode() != 200) {
+ throw new IOException("HTTP request failed with status: " +
+ response.getStatusLine().getStatusCode());
+ }
+
+ String jsonResponse = EntityUtils.toString(response.getEntity());
+ return parseMetrics(jsonResponse, name, keyName);
+ } catch (IOException e) {
+ log.error("Error getting metrics from datanode: {}", datanode.getIpAddress(), e);
+ }
+ return 0;
Review Comment:
Handled
--
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-13465. [Recon] Create API Endpoint to Return Consolidated Storage Report. [ozone]
Posted by "adoroszlai (via GitHub)" <gi...@apache.org>.
adoroszlai commented on code in PR #9326:
URL: https://github.com/apache/ozone/pull/9326#discussion_r2579755980
##########
hadoop-ozone/integration-test-recon/src/test/java/org/apache/hadoop/ozone/recon/TestStorageDistributionEndpoint.java:
##########
@@ -0,0 +1,289 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.hadoop.ozone.recon;
+
+import static org.apache.hadoop.hdds.HddsConfigKeys.HDDS_CONTAINER_REPORT_INTERVAL;
+import static org.apache.hadoop.hdds.HddsConfigKeys.HDDS_HEARTBEAT_INTERVAL;
+import static org.apache.hadoop.hdds.HddsConfigKeys.HDDS_SCM_WAIT_TIME_AFTER_SAFE_MODE_EXIT;
+import static org.apache.hadoop.hdds.client.ReplicationFactor.THREE;
+import static org.apache.hadoop.hdds.client.ReplicationType.RATIS;
+import static org.apache.hadoop.hdds.scm.ScmConfigKeys.OZONE_SCM_HA_RATIS_SNAPSHOT_GAP;
+import static org.apache.hadoop.hdds.scm.ScmConfigKeys.OZONE_SCM_HEARTBEAT_PROCESS_INTERVAL;
+import static org.apache.hadoop.ozone.OzoneConfigKeys.OZONE_BLOCK_DELETING_SERVICE_INTERVAL;
+import static org.apache.hadoop.ozone.OzoneConfigKeys.OZONE_BLOCK_DELETING_SERVICE_TIMEOUT;
+import static org.apache.hadoop.ozone.recon.TestReconEndpointUtil.getReconWebAddress;
+import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+
+import com.fasterxml.jackson.databind.ObjectMapper;
+import java.time.Duration;
+import java.util.Collections;
+import java.util.List;
+import java.util.concurrent.TimeUnit;
+import org.apache.hadoop.fs.CommonConfigurationKeysPublic;
+import org.apache.hadoop.fs.FSDataOutputStream;
+import org.apache.hadoop.fs.FileStatus;
+import org.apache.hadoop.fs.FileSystem;
+import org.apache.hadoop.fs.Path;
+import org.apache.hadoop.hdds.client.BlockID;
+import org.apache.hadoop.hdds.client.DefaultReplicationConfig;
+import org.apache.hadoop.hdds.client.ReplicationConfig;
+import org.apache.hadoop.hdds.conf.OzoneConfiguration;
+import org.apache.hadoop.hdds.scm.ScmConfig;
+import org.apache.hadoop.hdds.scm.server.StorageContainerManager;
+import org.apache.hadoop.hdds.utils.IOUtils;
+import org.apache.hadoop.ozone.HddsDatanodeService;
+import org.apache.hadoop.ozone.MiniOzoneCluster;
+import org.apache.hadoop.ozone.OzoneConsts;
+import org.apache.hadoop.ozone.client.BucketArgs;
+import org.apache.hadoop.ozone.client.ObjectStore;
+import org.apache.hadoop.ozone.client.OzoneBucket;
+import org.apache.hadoop.ozone.client.OzoneClient;
+import org.apache.hadoop.ozone.client.OzoneVolume;
+import org.apache.hadoop.ozone.container.common.impl.ContainerSet;
+import org.apache.hadoop.ozone.container.common.interfaces.DBHandle;
+import org.apache.hadoop.ozone.container.common.statemachine.DatanodeConfiguration;
+import org.apache.hadoop.ozone.container.keyvalue.KeyValueContainerData;
+import org.apache.hadoop.ozone.container.keyvalue.helpers.BlockUtils;
+import org.apache.hadoop.ozone.om.OzoneManager;
+import org.apache.hadoop.ozone.om.helpers.BucketLayout;
+import org.apache.hadoop.ozone.om.helpers.OmKeyArgs;
+import org.apache.hadoop.ozone.om.helpers.OmKeyLocationInfo;
+import org.apache.hadoop.ozone.om.helpers.OmKeyLocationInfoGroup;
+import org.apache.hadoop.ozone.recon.api.types.StorageCapacityDistributionResponse;
+import org.apache.hadoop.ozone.recon.spi.impl.OzoneManagerServiceProviderImpl;
+import org.apache.ozone.test.GenericTestUtils;
+import org.apache.ratis.util.function.CheckedConsumer;
+import org.junit.jupiter.api.AfterAll;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeAll;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.Arguments;
+import org.junit.jupiter.params.provider.MethodSource;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * Test class for the Storage Distribution REST endpoint in the
+ * Recon service. This class is responsible for setting up the
+ * testing environment, performing operations on an Ozone cluster,
+ * and validating the response of the storage distribution endpoint.
+ */
+public class TestStorageDistributionEndpoint {
+
+ private static final Logger LOG =
+ LoggerFactory.getLogger(TestStorageDistributionEndpoint.class);
+
+ private static OzoneConfiguration conf;
+ private static MiniOzoneCluster cluster;
+ private static OzoneManager om;
+ private static StorageContainerManager scm;
+ private static OzoneClient client;
+ private static ReconService recon;
+ private FileSystem fs;
+ private static final ObjectMapper MAPPER = new ObjectMapper();
+
+ private static final String STORAGE_DIST_ENDPOINT = "/api/v1/storageDistribution";
+
+ static List<Arguments> replicationConfigs() {
+ return Collections.singletonList(
+ Arguments.of(ReplicationConfig.fromTypeAndFactor(RATIS, THREE))
+ );
+ }
+
+ @BeforeAll
+ public static void setup() throws Exception {
+ conf = new OzoneConfiguration();
+ conf.setTimeDuration(OZONE_BLOCK_DELETING_SERVICE_INTERVAL, 100,
+ TimeUnit.MILLISECONDS);
+ conf.setTimeDuration(OZONE_BLOCK_DELETING_SERVICE_TIMEOUT, 100,
+ TimeUnit.MILLISECONDS);
+ conf.setTimeDuration(OZONE_SCM_HEARTBEAT_PROCESS_INTERVAL,
+ 100, TimeUnit.MILLISECONDS);
+ conf.setLong(OZONE_SCM_HA_RATIS_SNAPSHOT_GAP, 1L);
+ conf.setTimeDuration(HDDS_HEARTBEAT_INTERVAL, 50,
+ TimeUnit.MILLISECONDS);
+ conf.setTimeDuration(HDDS_CONTAINER_REPORT_INTERVAL, 200,
+ TimeUnit.MILLISECONDS);
+
+ // Enhanced SCM configuration for faster block deletion processing
+ ScmConfig scmConfig = conf.getObject(ScmConfig.class);
+ scmConfig.setBlockDeletionInterval(Duration.ofMillis(100));
+ conf.setFromObject(scmConfig);
+ conf.set(HDDS_SCM_WAIT_TIME_AFTER_SAFE_MODE_EXIT, "0s");
+
+ // Enhanced DataNode configuration to move pending deletion from SCM to DN faster
+ DatanodeConfiguration dnConf =
+ conf.getObject(DatanodeConfiguration.class);
+ dnConf.setBlockDeletionInterval(Duration.ofMillis(100));
+ // Increase block delete queue limit to allow more queued commands on DN
+ dnConf.setBlockDeleteQueueLimit(50);
+ // Reduce the interval for delete command worker processing
+ dnConf.setBlockDeleteCommandWorkerInterval(Duration.ofMillis(100));
+ // Increase blocks deleted per interval to speed up deletion
+ dnConf.setBlockDeletionLimit(5000);
+ conf.setFromObject(dnConf);
+ // Increase DN delete threads for faster parallel processing
+ conf.setInt("ozone.datanode.block.delete.threads.max", 10);
+
+ recon = new ReconService(conf);
+ cluster = MiniOzoneCluster.newBuilder(conf)
+ .setNumDatanodes(3)
+ .addService(recon)
+ .build();
+ cluster.waitForClusterToBeReady();
+ om = cluster.getOzoneManager();
+ scm = cluster.getStorageContainerManager();
+ client = cluster.newClient();
+ }
+
+ @ParameterizedTest
+ @MethodSource("replicationConfigs")
+ public void testStorageDistributionEndpoint(ReplicationConfig replicationConfig) throws Exception {
+ ObjectStore objectStore = client.getObjectStore();
+ objectStore.createVolume("vol1");
+ BucketArgs bucketArgs = BucketArgs.newBuilder()
+ .setBucketLayout(BucketLayout.FILE_SYSTEM_OPTIMIZED)
+ .setDefaultReplicationConfig(new DefaultReplicationConfig(replicationConfig))
+ .build();
+
+ OzoneVolume volume = objectStore.getVolume("vol1");
+ volume.createBucket("bucket1", bucketArgs);
+ OzoneBucket bucket = volume.getBucket("bucket1");
+
+ String rootPath = String.format("%s://%s.%s/", OzoneConsts.OZONE_URI_SCHEME, bucket.getName(),
+ bucket.getVolumeName());
+
+ conf.set(CommonConfigurationKeysPublic.FS_DEFAULT_NAME_KEY, rootPath);
+ fs = FileSystem.get(conf);
+
+ Path dir1 = new Path("/dir1");
+ fs.mkdirs(dir1);
+ for (int i = 1; i <= 10; i++) {
+ Path path1 = new Path(dir1, "testKey" + i);
+ try (FSDataOutputStream stream = fs.create(path1)) {
+ stream.write(1);
+ }
+ }
+ Path dir2 = new Path("/dir2");
+ fs.mkdirs(dir2);
+ for (int i = 1; i <= 10; i++) {
+ Path path1 = new Path(dir2, "testKey" + i);
+ try (FSDataOutputStream stream = fs.create(path1)) {
+ stream.write(1);
+ }
+ }
+ waitForKeysCreated(replicationConfig);
+ Thread.sleep(10000);
Review Comment:
> We can handle this in a follow-up PR for the same feature. No need to rerun the tests now and waste resources
Addressing this in a follow-up requires more resources, not less:
- same resources for PR run or re-run
- +1 run after PR merge for the follow-up commit
Even most of the first item could have been avoided, since this was noticed at around the same time when the PR workflow was approved to run.
--
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-13465. Adding endpoint at Recon to get consolidated storage dist… [ozone]
Posted by "priyeshkaratha (via GitHub)" <gi...@apache.org>.
priyeshkaratha commented on code in PR #9326:
URL: https://github.com/apache/ozone/pull/9326#discussion_r2543000446
##########
hadoop-ozone/recon/src/main/java/org/apache/hadoop/ozone/recon/api/StorageDistributionEndpoint.java:
##########
@@ -0,0 +1,343 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.hadoop.ozone.recon.api;
+
+import static org.apache.hadoop.ozone.om.codec.OMDBDefinition.FILE_TABLE;
+import static org.apache.hadoop.ozone.om.codec.OMDBDefinition.KEY_TABLE;
+
+import java.io.IOException;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.stream.Collectors;
+import javax.inject.Inject;
+import javax.ws.rs.GET;
+import javax.ws.rs.Path;
+import javax.ws.rs.Produces;
+import javax.ws.rs.core.Response;
+import org.apache.hadoop.hdds.protocol.DatanodeDetails;
+import org.apache.hadoop.hdds.protocol.proto.HddsProtos.DeletedBlocksTransactionSummary;
+import org.apache.hadoop.hdds.scm.container.placement.metrics.SCMNodeMetric;
+import org.apache.hadoop.hdds.scm.container.placement.metrics.SCMNodeStat;
+import org.apache.hadoop.hdds.scm.protocol.StorageContainerLocationProtocol;
+import org.apache.hadoop.hdds.scm.server.OzoneStorageContainerManager;
+import org.apache.hadoop.ozone.recon.ReconUtils;
+import org.apache.hadoop.ozone.recon.api.types.DUResponse;
+import org.apache.hadoop.ozone.recon.api.types.DatanodeStorageReport;
+import org.apache.hadoop.ozone.recon.api.types.DeletionPendingBytesByComponent;
+import org.apache.hadoop.ozone.recon.api.types.GlobalNamespaceReport;
+import org.apache.hadoop.ozone.recon.api.types.GlobalStorageReport;
+import org.apache.hadoop.ozone.recon.api.types.KeyInsightInfoResponse;
+import org.apache.hadoop.ozone.recon.api.types.StorageCapacityDistributionResponse;
+import org.apache.hadoop.ozone.recon.api.types.UsedSpaceBreakDown;
+import org.apache.hadoop.ozone.recon.scm.ReconNodeManager;
+import org.apache.hadoop.ozone.recon.tasks.OmTableInsightTask;
+import org.apache.ozone.recon.schema.generated.tables.daos.GlobalStatsDao;
+import org.apache.ozone.recon.schema.generated.tables.pojos.GlobalStats;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * This endpoint handles requests related to storage distribution across
+ * different datanodes in a Recon instance. It provides detailed reports
+ * on storage capacity, utilization, and associated metrics.
+ * <p>
+ * The data is aggregated from multiple sources, including node manager
+ * statistics, and is used to construct responses with information
+ * about global storage and namespace usage, storage usage breakdown,
+ * and deletion operations in progress.
+ * <p>
+ * An instance of {@link ReconNodeManager} is used to fetch detailed
+ * node-specific statistics required for generating the report.
+ */
+@Path("/storageDistribution")
+@Produces("application/json")
+@AdminOnly
+public class StorageDistributionEndpoint {
+ private final ReconNodeManager nodeManager;
+ private final OMDBInsightEndpoint omdbInsightEndpoint;
+ private final NSSummaryEndpoint nsSummaryEndpoint;
+ private final StorageContainerLocationProtocol scmClient;
+ private static Logger log = LoggerFactory.getLogger(StorageDistributionEndpoint.class);
Review Comment:
Done
--
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-13465. Adding endpoint at Recon to get consolidated storage dist… [ozone]
Posted by "priyeshkaratha (via GitHub)" <gi...@apache.org>.
priyeshkaratha commented on PR #9326:
URL: https://github.com/apache/ozone/pull/9326#issuecomment-3584854718
Hi @devmadhuu As discussed, pending deletion related changes will be moved to separate endpoint considering performance. Created HDDS-14010 for tracking pendingDeletion endpoint 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-13465. [Recon] Create API Endpoint to Return Consolidated Storage Report. [ozone]
Posted by "ArafatKhan2198 (via GitHub)" <gi...@apache.org>.
ArafatKhan2198 merged PR #9326:
URL: https://github.com/apache/ozone/pull/9326
--
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