devmadhuu commented on code in PR #10414: URL: https://github.com/apache/ozone/pull/10414#discussion_r3354450876
########## hadoop-ozone/cli-debug/src/main/java/org/apache/hadoop/ozone/debug/datanode/container/analyze/ContainerDirectoryScanner.java: ########## @@ -0,0 +1,282 @@ +/* + * 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.debug.datanode.container.analyze; + +import com.google.common.util.concurrent.ThreadFactoryBuilder; +import java.io.File; +import java.io.IOException; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Properties; +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 org.apache.commons.io.FileUtils; +import org.apache.hadoop.hdds.conf.ConfigurationSource; +import org.apache.hadoop.hdds.scm.ScmConfigKeys; +import org.apache.hadoop.hdds.utils.HddsServerUtil; +import org.apache.hadoop.hdfs.server.datanode.StorageLocation; +import org.apache.hadoop.ozone.common.InconsistentStorageStateException; +import org.apache.hadoop.ozone.common.Storage; +import org.apache.hadoop.ozone.container.common.helpers.ContainerUtils; +import org.apache.hadoop.ozone.container.common.helpers.DatanodeVersionFile; +import org.apache.hadoop.ozone.container.common.impl.ContainerData; +import org.apache.hadoop.ozone.container.common.impl.ContainerDataYaml; +import org.apache.hadoop.ozone.container.common.utils.StorageVolumeUtil; +import org.apache.hadoop.ozone.container.common.volume.HddsVolume; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * Read-only walker for container directories under {@code hdds.datanode.dir}. + * + * <p>Unlike {@link org.apache.hadoop.ozone.container.ozoneimpl.ContainerReader}, + * this scanner records every container directory it finds, including those with + * missing or invalid metadata and duplicate copies across volumes. + */ +public class ContainerDirectoryScanner { + + private static final Logger LOG = LoggerFactory.getLogger(ContainerDirectoryScanner.class); + + /** + * Scan all configured DataNode storage volumes and return every container + * directory found on disk. + * + * @return map of container ID to all on-disk occurrences for that ID + */ + public Map<Long, List<ContainerDiskOccurrence>> scan(ConfigurationSource conf) throws IOException { + Collection<String> storageDirs = HddsServerUtil.getDatanodeStorageDirs(conf); + + if (storageDirs.isEmpty()) { + return Collections.emptyMap(); + } + + validateStorageDirectories(storageDirs); + Map<Long, List<ContainerDiskOccurrence>> result = new ConcurrentHashMap<>(); + int volumeCount = storageDirs.size(); + ExecutorService executor = Executors.newFixedThreadPool(volumeCount, + new ThreadFactoryBuilder() + .setDaemon(true) + .setNameFormat("ContainerDirectoryScanner-%d") + .build()); + + try { + List<Future<?>> futures = new ArrayList<>(volumeCount); + for (String storageDir : storageDirs) { + String volumeRoot = StorageLocation.parse(storageDir).getUri().getPath(); + futures.add(executor.submit(() -> { + try { + scanVolume(volumeRoot, result); + } catch (IOException e) { + throw new RuntimeException( + "Failed to scan volume " + volumeRoot, e); + } + })); + } + for (Future<?> future : futures) { + try { + future.get(); + } catch (ExecutionException e) { + Throwable cause = e.getCause(); + if (cause instanceof RuntimeException) { + throw (RuntimeException) cause; + } + throw new IOException(cause); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + throw new IOException("Volume scan interrupted", e); + } + } + } finally { + executor.shutdownNow(); + } + + return Collections.unmodifiableMap(toImmutableLists(result)); + } + + /** + * Scan a single DataNode storage volume root and merge results into {@code result}. + */ + private void scanVolume(String volumeRoot, Map<Long, List<ContainerDiskOccurrence>> result) throws IOException { + File hddsRoot = new File(volumeRoot, HddsVolume.HDDS_VOLUME_DIR); + if (!hddsRoot.isDirectory()) { + LOG.warn("HDDS root {} does not exist or is not a directory, skipping volume {}", hddsRoot, volumeRoot); + return; + } + + File versionFile = StorageVolumeUtil.getVersionFile(hddsRoot); + Properties props = DatanodeVersionFile.readFrom(versionFile); + if (props.isEmpty()) { + throw new IOException("Version file " + versionFile + " is missing or empty"); + } + String clusterId; + try { + clusterId = StorageVolumeUtil.getClusterID(props, versionFile, null); + } catch (InconsistentStorageStateException e) { + throw new IOException("Invalid version file " + versionFile, e); + } + + File currentDir = resolveCurrentDir(hddsRoot, clusterId); + if (currentDir == null || !currentDir.isDirectory()) { + LOG.info("No current container directory under {}, skipping volume {}", hddsRoot, volumeRoot); + return; + } + + LOG.info("Scanning container directories under {}", currentDir); + File[] containerTopDirs = currentDir.listFiles(File::isDirectory); + if (containerTopDirs == null) { + throw new IOException("Failed to list container top-level directories under " + currentDir); + } + + for (File containerTopDir : containerTopDirs) { + File[] containerDirs = containerTopDir.listFiles(File::isDirectory); + if (containerDirs == null) { + LOG.warn("Failed to list container directories under {}", containerTopDir); + continue; + } + for (File containerDir : containerDirs) { + recordContainerDir(containerDir, volumeRoot, result); + } + } + } + + /** + * Resolve {@code .../current} using the same rules as + * {@link org.apache.hadoop.ozone.container.ozoneimpl.ContainerReader#readVolume(File)}. + */ + static File resolveCurrentDir(File hddsRoot, String clusterId) throws IOException { + File[] storageDirs = hddsRoot.listFiles(File::isDirectory); + if (storageDirs == null) { + throw new IOException("IO error listing " + hddsRoot); + } + if (storageDirs.length == 0) { + return null; + } + + File clusterIdDir = new File(hddsRoot, clusterId); + File idDir = clusterIdDir; + if (storageDirs.length == 1 && !clusterIdDir.exists()) { + idDir = storageDirs[0]; + } else if (!clusterIdDir.exists()) { + throw new IOException("Volume " + hddsRoot + " is in an inconsistent state. " + + "Expected cluster ID directory " + clusterIdDir + " not found."); + } + return new File(idDir, Storage.STORAGE_DIR_CURRENT); + } + + private static void recordContainerDir(File containerDir, String volumeRoot, + Map<Long, List<ContainerDiskOccurrence>> result) { + long containerId; + try { + containerId = ContainerUtils.getContainerID(containerDir); + } catch (NumberFormatException e) { + LOG.warn("Skipping non-numeric container directory {}", containerDir); + return; + } + + File containerFile = ContainerUtils.getContainerFile(containerDir); + ContainerDiskScanStatus status; + if (!containerFile.exists()) { + status = ContainerDiskScanStatus.MISSING_METADATA; + } else { + status = readMetadataStatus(containerId, containerFile); + } + + long sizeBytes; + try { + sizeBytes = FileUtils.sizeOfDirectory(containerDir); + } catch (IllegalArgumentException e) { + LOG.warn("Failed to compute size for container directory {}, using 0", containerDir, e); Review Comment: This will go unnoticed in output. ########## hadoop-ozone/cli-debug/src/main/java/org/apache/hadoop/ozone/debug/datanode/container/analyze/AnalyzeSubcommand.java: ########## @@ -0,0 +1,95 @@ +/* + * 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.debug.datanode.container.analyze; + +import java.io.IOException; +import java.util.List; +import java.util.Map; +import java.util.concurrent.Callable; +import java.util.stream.Collectors; +import org.apache.hadoop.hdds.cli.AbstractSubcommand; +import org.apache.hadoop.hdds.conf.OzoneConfiguration; +import picocli.CommandLine; +import picocli.CommandLine.Command; + +/** + * {@code ozone debug datanode container analyze}. + * + * <p>Compares on-disk container directories on this DataNode against SCM + * metadata to report inconsistencies. + */ +@Command( + name = "analyze", + description = "Analyze container consistency between on-disk container " + + "directories on this DataNode and SCM metadata. Must be run locally on a DataNode.") +public class AnalyzeSubcommand extends AbstractSubcommand implements Callable<Void> { + @CommandLine.Option(names = {"--count"}, + defaultValue = "20", + description = "Number of containers to display") Review Comment: Actually this is "`Number of duplicate containers to display`" ########## hadoop-ozone/cli-debug/src/main/java/org/apache/hadoop/ozone/debug/datanode/container/analyze/AnalyzeSubcommand.java: ########## @@ -0,0 +1,95 @@ +/* + * 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.debug.datanode.container.analyze; + +import java.io.IOException; +import java.util.List; +import java.util.Map; +import java.util.concurrent.Callable; +import java.util.stream.Collectors; +import org.apache.hadoop.hdds.cli.AbstractSubcommand; +import org.apache.hadoop.hdds.conf.OzoneConfiguration; +import picocli.CommandLine; +import picocli.CommandLine.Command; + +/** + * {@code ozone debug datanode container analyze}. + * + * <p>Compares on-disk container directories on this DataNode against SCM + * metadata to report inconsistencies. + */ +@Command( + name = "analyze", + description = "Analyze container consistency between on-disk container " + + "directories on this DataNode and SCM metadata. Must be run locally on a DataNode.") +public class AnalyzeSubcommand extends AbstractSubcommand implements Callable<Void> { + @CommandLine.Option(names = {"--count"}, + defaultValue = "20", + description = "Number of containers to display") + private int count; + + @Override + public Void call() throws Exception { + if (count < 1) { + throw new IOException("Count must be an integer greater than 0."); Review Comment: Will this exception be propagated on command output ? ########## hadoop-ozone/cli-debug/src/main/java/org/apache/hadoop/ozone/debug/datanode/container/analyze/ContainerDirectoryScanner.java: ########## @@ -0,0 +1,282 @@ +/* + * 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.debug.datanode.container.analyze; + +import com.google.common.util.concurrent.ThreadFactoryBuilder; +import java.io.File; +import java.io.IOException; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Properties; +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 org.apache.commons.io.FileUtils; +import org.apache.hadoop.hdds.conf.ConfigurationSource; +import org.apache.hadoop.hdds.scm.ScmConfigKeys; +import org.apache.hadoop.hdds.utils.HddsServerUtil; +import org.apache.hadoop.hdfs.server.datanode.StorageLocation; +import org.apache.hadoop.ozone.common.InconsistentStorageStateException; +import org.apache.hadoop.ozone.common.Storage; +import org.apache.hadoop.ozone.container.common.helpers.ContainerUtils; +import org.apache.hadoop.ozone.container.common.helpers.DatanodeVersionFile; +import org.apache.hadoop.ozone.container.common.impl.ContainerData; +import org.apache.hadoop.ozone.container.common.impl.ContainerDataYaml; +import org.apache.hadoop.ozone.container.common.utils.StorageVolumeUtil; +import org.apache.hadoop.ozone.container.common.volume.HddsVolume; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * Read-only walker for container directories under {@code hdds.datanode.dir}. + * + * <p>Unlike {@link org.apache.hadoop.ozone.container.ozoneimpl.ContainerReader}, + * this scanner records every container directory it finds, including those with + * missing or invalid metadata and duplicate copies across volumes. + */ +public class ContainerDirectoryScanner { + + private static final Logger LOG = LoggerFactory.getLogger(ContainerDirectoryScanner.class); + + /** + * Scan all configured DataNode storage volumes and return every container + * directory found on disk. + * + * @return map of container ID to all on-disk occurrences for that ID + */ + public Map<Long, List<ContainerDiskOccurrence>> scan(ConfigurationSource conf) throws IOException { + Collection<String> storageDirs = HddsServerUtil.getDatanodeStorageDirs(conf); + + if (storageDirs.isEmpty()) { + return Collections.emptyMap(); + } + + validateStorageDirectories(storageDirs); + Map<Long, List<ContainerDiskOccurrence>> result = new ConcurrentHashMap<>(); + int volumeCount = storageDirs.size(); + ExecutorService executor = Executors.newFixedThreadPool(volumeCount, + new ThreadFactoryBuilder() + .setDaemon(true) + .setNameFormat("ContainerDirectoryScanner-%d") + .build()); + + try { + List<Future<?>> futures = new ArrayList<>(volumeCount); + for (String storageDir : storageDirs) { + String volumeRoot = StorageLocation.parse(storageDir).getUri().getPath(); + futures.add(executor.submit(() -> { + try { + scanVolume(volumeRoot, result); + } catch (IOException e) { + throw new RuntimeException( + "Failed to scan volume " + volumeRoot, e); + } + })); + } + for (Future<?> future : futures) { + try { + future.get(); + } catch (ExecutionException e) { + Throwable cause = e.getCause(); + if (cause instanceof RuntimeException) { + throw (RuntimeException) cause; + } + throw new IOException(cause); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + throw new IOException("Volume scan interrupted", e); + } + } + } finally { + executor.shutdownNow(); + } + + return Collections.unmodifiableMap(toImmutableLists(result)); + } + + /** + * Scan a single DataNode storage volume root and merge results into {@code result}. + */ + private void scanVolume(String volumeRoot, Map<Long, List<ContainerDiskOccurrence>> result) throws IOException { + File hddsRoot = new File(volumeRoot, HddsVolume.HDDS_VOLUME_DIR); + if (!hddsRoot.isDirectory()) { + LOG.warn("HDDS root {} does not exist or is not a directory, skipping volume {}", hddsRoot, volumeRoot); + return; + } + + File versionFile = StorageVolumeUtil.getVersionFile(hddsRoot); + Properties props = DatanodeVersionFile.readFrom(versionFile); + if (props.isEmpty()) { + throw new IOException("Version file " + versionFile + " is missing or empty"); + } + String clusterId; + try { + clusterId = StorageVolumeUtil.getClusterID(props, versionFile, null); + } catch (InconsistentStorageStateException e) { + throw new IOException("Invalid version file " + versionFile, e); + } + + File currentDir = resolveCurrentDir(hddsRoot, clusterId); + if (currentDir == null || !currentDir.isDirectory()) { + LOG.info("No current container directory under {}, skipping volume {}", hddsRoot, volumeRoot); + return; + } + + LOG.info("Scanning container directories under {}", currentDir); + File[] containerTopDirs = currentDir.listFiles(File::isDirectory); + if (containerTopDirs == null) { + throw new IOException("Failed to list container top-level directories under " + currentDir); + } + + for (File containerTopDir : containerTopDirs) { + File[] containerDirs = containerTopDir.listFiles(File::isDirectory); + if (containerDirs == null) { + LOG.warn("Failed to list container directories under {}", containerTopDir); + continue; + } + for (File containerDir : containerDirs) { + recordContainerDir(containerDir, volumeRoot, result); + } + } + } + + /** + * Resolve {@code .../current} using the same rules as + * {@link org.apache.hadoop.ozone.container.ozoneimpl.ContainerReader#readVolume(File)}. + */ + static File resolveCurrentDir(File hddsRoot, String clusterId) throws IOException { + File[] storageDirs = hddsRoot.listFiles(File::isDirectory); + if (storageDirs == null) { + throw new IOException("IO error listing " + hddsRoot); + } + if (storageDirs.length == 0) { + return null; + } + + File clusterIdDir = new File(hddsRoot, clusterId); + File idDir = clusterIdDir; + if (storageDirs.length == 1 && !clusterIdDir.exists()) { + idDir = storageDirs[0]; + } else if (!clusterIdDir.exists()) { + throw new IOException("Volume " + hddsRoot + " is in an inconsistent state. " + + "Expected cluster ID directory " + clusterIdDir + " not found."); + } + return new File(idDir, Storage.STORAGE_DIR_CURRENT); + } + + private static void recordContainerDir(File containerDir, String volumeRoot, + Map<Long, List<ContainerDiskOccurrence>> result) { + long containerId; + try { + containerId = ContainerUtils.getContainerID(containerDir); + } catch (NumberFormatException e) { + LOG.warn("Skipping non-numeric container directory {}", containerDir); + return; + } + + File containerFile = ContainerUtils.getContainerFile(containerDir); + ContainerDiskScanStatus status; + if (!containerFile.exists()) { + status = ContainerDiskScanStatus.MISSING_METADATA; + } else { + status = readMetadataStatus(containerId, containerFile); + } + + long sizeBytes; + try { + sizeBytes = FileUtils.sizeOfDirectory(containerDir); Review Comment: This is computed for every container. On a DN with thousands of containers this is a lot of unnecessary stat/I/O and will make the command slow. Since we need the size only for duplicate dirs, so can we compute this lazily ? ########## hadoop-ozone/cli-debug/src/main/java/org/apache/hadoop/ozone/debug/datanode/container/analyze/ContainerDirectoryScanner.java: ########## @@ -0,0 +1,282 @@ +/* + * 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.debug.datanode.container.analyze; + +import com.google.common.util.concurrent.ThreadFactoryBuilder; +import java.io.File; +import java.io.IOException; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Properties; +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 org.apache.commons.io.FileUtils; +import org.apache.hadoop.hdds.conf.ConfigurationSource; +import org.apache.hadoop.hdds.scm.ScmConfigKeys; +import org.apache.hadoop.hdds.utils.HddsServerUtil; +import org.apache.hadoop.hdfs.server.datanode.StorageLocation; +import org.apache.hadoop.ozone.common.InconsistentStorageStateException; +import org.apache.hadoop.ozone.common.Storage; +import org.apache.hadoop.ozone.container.common.helpers.ContainerUtils; +import org.apache.hadoop.ozone.container.common.helpers.DatanodeVersionFile; +import org.apache.hadoop.ozone.container.common.impl.ContainerData; +import org.apache.hadoop.ozone.container.common.impl.ContainerDataYaml; +import org.apache.hadoop.ozone.container.common.utils.StorageVolumeUtil; +import org.apache.hadoop.ozone.container.common.volume.HddsVolume; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * Read-only walker for container directories under {@code hdds.datanode.dir}. + * + * <p>Unlike {@link org.apache.hadoop.ozone.container.ozoneimpl.ContainerReader}, + * this scanner records every container directory it finds, including those with + * missing or invalid metadata and duplicate copies across volumes. + */ +public class ContainerDirectoryScanner { + + private static final Logger LOG = LoggerFactory.getLogger(ContainerDirectoryScanner.class); + + /** + * Scan all configured DataNode storage volumes and return every container + * directory found on disk. + * + * @return map of container ID to all on-disk occurrences for that ID + */ + public Map<Long, List<ContainerDiskOccurrence>> scan(ConfigurationSource conf) throws IOException { + Collection<String> storageDirs = HddsServerUtil.getDatanodeStorageDirs(conf); + + if (storageDirs.isEmpty()) { + return Collections.emptyMap(); + } + + validateStorageDirectories(storageDirs); + Map<Long, List<ContainerDiskOccurrence>> result = new ConcurrentHashMap<>(); + int volumeCount = storageDirs.size(); + ExecutorService executor = Executors.newFixedThreadPool(volumeCount, + new ThreadFactoryBuilder() + .setDaemon(true) + .setNameFormat("ContainerDirectoryScanner-%d") + .build()); + + try { + List<Future<?>> futures = new ArrayList<>(volumeCount); + for (String storageDir : storageDirs) { + String volumeRoot = StorageLocation.parse(storageDir).getUri().getPath(); + futures.add(executor.submit(() -> { + try { + scanVolume(volumeRoot, result); + } catch (IOException e) { + throw new RuntimeException( Review Comment: This will abort the command run if just one volume fails. Ideally we want the duplicate report for the healthy volumes. Better to continue collecting per-volume errors, then printing a "volumes that failed to scan" section at the end. ########## hadoop-ozone/cli-debug/src/main/java/org/apache/hadoop/ozone/debug/datanode/container/analyze/ContainerDirectoryScanner.java: ########## @@ -0,0 +1,282 @@ +/* + * 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.debug.datanode.container.analyze; + +import com.google.common.util.concurrent.ThreadFactoryBuilder; +import java.io.File; +import java.io.IOException; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Properties; +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 org.apache.commons.io.FileUtils; +import org.apache.hadoop.hdds.conf.ConfigurationSource; +import org.apache.hadoop.hdds.scm.ScmConfigKeys; +import org.apache.hadoop.hdds.utils.HddsServerUtil; +import org.apache.hadoop.hdfs.server.datanode.StorageLocation; +import org.apache.hadoop.ozone.common.InconsistentStorageStateException; +import org.apache.hadoop.ozone.common.Storage; +import org.apache.hadoop.ozone.container.common.helpers.ContainerUtils; +import org.apache.hadoop.ozone.container.common.helpers.DatanodeVersionFile; +import org.apache.hadoop.ozone.container.common.impl.ContainerData; +import org.apache.hadoop.ozone.container.common.impl.ContainerDataYaml; +import org.apache.hadoop.ozone.container.common.utils.StorageVolumeUtil; +import org.apache.hadoop.ozone.container.common.volume.HddsVolume; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * Read-only walker for container directories under {@code hdds.datanode.dir}. + * + * <p>Unlike {@link org.apache.hadoop.ozone.container.ozoneimpl.ContainerReader}, + * this scanner records every container directory it finds, including those with + * missing or invalid metadata and duplicate copies across volumes. + */ +public class ContainerDirectoryScanner { + + private static final Logger LOG = LoggerFactory.getLogger(ContainerDirectoryScanner.class); + + /** + * Scan all configured DataNode storage volumes and return every container + * directory found on disk. + * + * @return map of container ID to all on-disk occurrences for that ID + */ + public Map<Long, List<ContainerDiskOccurrence>> scan(ConfigurationSource conf) throws IOException { + Collection<String> storageDirs = HddsServerUtil.getDatanodeStorageDirs(conf); + + if (storageDirs.isEmpty()) { + return Collections.emptyMap(); + } + + validateStorageDirectories(storageDirs); Review Comment: So if any of the storage dir across all volumes has any issue (missing), command will fail ? ########## hadoop-ozone/cli-debug/src/main/java/org/apache/hadoop/ozone/debug/datanode/container/analyze/ContainerDirectoryScanner.java: ########## @@ -0,0 +1,282 @@ +/* + * 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.debug.datanode.container.analyze; + +import com.google.common.util.concurrent.ThreadFactoryBuilder; +import java.io.File; +import java.io.IOException; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Properties; +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 org.apache.commons.io.FileUtils; +import org.apache.hadoop.hdds.conf.ConfigurationSource; +import org.apache.hadoop.hdds.scm.ScmConfigKeys; +import org.apache.hadoop.hdds.utils.HddsServerUtil; +import org.apache.hadoop.hdfs.server.datanode.StorageLocation; +import org.apache.hadoop.ozone.common.InconsistentStorageStateException; +import org.apache.hadoop.ozone.common.Storage; +import org.apache.hadoop.ozone.container.common.helpers.ContainerUtils; +import org.apache.hadoop.ozone.container.common.helpers.DatanodeVersionFile; +import org.apache.hadoop.ozone.container.common.impl.ContainerData; +import org.apache.hadoop.ozone.container.common.impl.ContainerDataYaml; +import org.apache.hadoop.ozone.container.common.utils.StorageVolumeUtil; +import org.apache.hadoop.ozone.container.common.volume.HddsVolume; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * Read-only walker for container directories under {@code hdds.datanode.dir}. + * + * <p>Unlike {@link org.apache.hadoop.ozone.container.ozoneimpl.ContainerReader}, + * this scanner records every container directory it finds, including those with + * missing or invalid metadata and duplicate copies across volumes. + */ +public class ContainerDirectoryScanner { + + private static final Logger LOG = LoggerFactory.getLogger(ContainerDirectoryScanner.class); + + /** + * Scan all configured DataNode storage volumes and return every container + * directory found on disk. + * + * @return map of container ID to all on-disk occurrences for that ID + */ + public Map<Long, List<ContainerDiskOccurrence>> scan(ConfigurationSource conf) throws IOException { + Collection<String> storageDirs = HddsServerUtil.getDatanodeStorageDirs(conf); + + if (storageDirs.isEmpty()) { + return Collections.emptyMap(); + } + + validateStorageDirectories(storageDirs); + Map<Long, List<ContainerDiskOccurrence>> result = new ConcurrentHashMap<>(); + int volumeCount = storageDirs.size(); + ExecutorService executor = Executors.newFixedThreadPool(volumeCount, + new ThreadFactoryBuilder() + .setDaemon(true) + .setNameFormat("ContainerDirectoryScanner-%d") + .build()); + + try { + List<Future<?>> futures = new ArrayList<>(volumeCount); + for (String storageDir : storageDirs) { + String volumeRoot = StorageLocation.parse(storageDir).getUri().getPath(); + futures.add(executor.submit(() -> { + try { + scanVolume(volumeRoot, result); + } catch (IOException e) { + throw new RuntimeException( + "Failed to scan volume " + volumeRoot, e); + } + })); + } + for (Future<?> future : futures) { + try { + future.get(); + } catch (ExecutionException e) { + Throwable cause = e.getCause(); + if (cause instanceof RuntimeException) { + throw (RuntimeException) cause; + } + throw new IOException(cause); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + throw new IOException("Volume scan interrupted", e); + } + } + } finally { + executor.shutdownNow(); + } + + return Collections.unmodifiableMap(toImmutableLists(result)); + } + + /** + * Scan a single DataNode storage volume root and merge results into {@code result}. + */ + private void scanVolume(String volumeRoot, Map<Long, List<ContainerDiskOccurrence>> result) throws IOException { + File hddsRoot = new File(volumeRoot, HddsVolume.HDDS_VOLUME_DIR); + if (!hddsRoot.isDirectory()) { + LOG.warn("HDDS root {} does not exist or is not a directory, skipping volume {}", hddsRoot, volumeRoot); + return; + } + + File versionFile = StorageVolumeUtil.getVersionFile(hddsRoot); + Properties props = DatanodeVersionFile.readFrom(versionFile); + if (props.isEmpty()) { + throw new IOException("Version file " + versionFile + " is missing or empty"); + } + String clusterId; + try { + clusterId = StorageVolumeUtil.getClusterID(props, versionFile, null); + } catch (InconsistentStorageStateException e) { + throw new IOException("Invalid version file " + versionFile, e); + } + + File currentDir = resolveCurrentDir(hddsRoot, clusterId); + if (currentDir == null || !currentDir.isDirectory()) { + LOG.info("No current container directory under {}, skipping volume {}", hddsRoot, volumeRoot); + return; + } + + LOG.info("Scanning container directories under {}", currentDir); + File[] containerTopDirs = currentDir.listFiles(File::isDirectory); + if (containerTopDirs == null) { + throw new IOException("Failed to list container top-level directories under " + currentDir); + } + + for (File containerTopDir : containerTopDirs) { + File[] containerDirs = containerTopDir.listFiles(File::isDirectory); + if (containerDirs == null) { + LOG.warn("Failed to list container directories under {}", containerTopDir); + continue; + } + for (File containerDir : containerDirs) { + recordContainerDir(containerDir, volumeRoot, result); + } + } + } + + /** + * Resolve {@code .../current} using the same rules as + * {@link org.apache.hadoop.ozone.container.ozoneimpl.ContainerReader#readVolume(File)}. + */ + static File resolveCurrentDir(File hddsRoot, String clusterId) throws IOException { + File[] storageDirs = hddsRoot.listFiles(File::isDirectory); + if (storageDirs == null) { + throw new IOException("IO error listing " + hddsRoot); + } + if (storageDirs.length == 0) { + return null; + } + + File clusterIdDir = new File(hddsRoot, clusterId); + File idDir = clusterIdDir; + if (storageDirs.length == 1 && !clusterIdDir.exists()) { + idDir = storageDirs[0]; + } else if (!clusterIdDir.exists()) { + throw new IOException("Volume " + hddsRoot + " is in an inconsistent state. " + + "Expected cluster ID directory " + clusterIdDir + " not found."); + } + return new File(idDir, Storage.STORAGE_DIR_CURRENT); + } + + private static void recordContainerDir(File containerDir, String volumeRoot, + Map<Long, List<ContainerDiskOccurrence>> result) { + long containerId; + try { + containerId = ContainerUtils.getContainerID(containerDir); + } catch (NumberFormatException e) { + LOG.warn("Skipping non-numeric container directory {}", containerDir); + return; + } + + File containerFile = ContainerUtils.getContainerFile(containerDir); + ContainerDiskScanStatus status; + if (!containerFile.exists()) { + status = ContainerDiskScanStatus.MISSING_METADATA; + } else { + status = readMetadataStatus(containerId, containerFile); + } + + long sizeBytes; + try { + sizeBytes = FileUtils.sizeOfDirectory(containerDir); + } catch (IllegalArgumentException e) { + LOG.warn("Failed to compute size for container directory {}, using 0", containerDir, e); + sizeBytes = 0L; + } + + ContainerDiskOccurrence occurrence = new ContainerDiskOccurrence( + containerId, + containerDir.getAbsolutePath(), + volumeRoot, + sizeBytes, + status); + result.compute(containerId, (id, existing) -> { Review Comment: Better to do sorting of container ids here, because this list will be used to show duplicate based on occurrences and they are getting appended in volume scan order, but since that is not deterministic because volumes are scanned concurrently. We would like the output to be stable and consistent across multiple runs if no change in container dirs. ########## hadoop-ozone/cli-debug/src/main/java/org/apache/hadoop/ozone/debug/datanode/container/analyze/ContainerDirectoryScanner.java: ########## @@ -0,0 +1,282 @@ +/* + * 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.debug.datanode.container.analyze; + +import com.google.common.util.concurrent.ThreadFactoryBuilder; +import java.io.File; +import java.io.IOException; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Properties; +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 org.apache.commons.io.FileUtils; +import org.apache.hadoop.hdds.conf.ConfigurationSource; +import org.apache.hadoop.hdds.scm.ScmConfigKeys; +import org.apache.hadoop.hdds.utils.HddsServerUtil; +import org.apache.hadoop.hdfs.server.datanode.StorageLocation; +import org.apache.hadoop.ozone.common.InconsistentStorageStateException; +import org.apache.hadoop.ozone.common.Storage; +import org.apache.hadoop.ozone.container.common.helpers.ContainerUtils; +import org.apache.hadoop.ozone.container.common.helpers.DatanodeVersionFile; +import org.apache.hadoop.ozone.container.common.impl.ContainerData; +import org.apache.hadoop.ozone.container.common.impl.ContainerDataYaml; +import org.apache.hadoop.ozone.container.common.utils.StorageVolumeUtil; +import org.apache.hadoop.ozone.container.common.volume.HddsVolume; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * Read-only walker for container directories under {@code hdds.datanode.dir}. + * + * <p>Unlike {@link org.apache.hadoop.ozone.container.ozoneimpl.ContainerReader}, + * this scanner records every container directory it finds, including those with + * missing or invalid metadata and duplicate copies across volumes. + */ +public class ContainerDirectoryScanner { + + private static final Logger LOG = LoggerFactory.getLogger(ContainerDirectoryScanner.class); + + /** + * Scan all configured DataNode storage volumes and return every container + * directory found on disk. + * + * @return map of container ID to all on-disk occurrences for that ID + */ + public Map<Long, List<ContainerDiskOccurrence>> scan(ConfigurationSource conf) throws IOException { + Collection<String> storageDirs = HddsServerUtil.getDatanodeStorageDirs(conf); + + if (storageDirs.isEmpty()) { + return Collections.emptyMap(); + } + + validateStorageDirectories(storageDirs); + Map<Long, List<ContainerDiskOccurrence>> result = new ConcurrentHashMap<>(); Review Comment: I think, we need to focus on optimizing the whole logic from memory perspective, at 10M or more containers itself, this can shoot upto ~4-5 GB and And later `toImmutableLists` then copies the entire map into a fresh HashMap of fresh ArrayLists, so peak memory is ~2x. IMO, we should not keep single occurrences. Keep a lightweight first occurrence map (`Map<Long, ContainerDiskOccurrence> `or even `Map<Long, String path>`) and only store an ID into a `Map<Long, List<...>>` when a second occurrence is seen. Memory then scales only with the number of duplicates (expected tiny), not total containers. This also lets you drop `toImmutableLists` entirely. ########## hadoop-ozone/cli-debug/src/main/java/org/apache/hadoop/ozone/debug/datanode/container/analyze/ContainerDirectoryScanner.java: ########## @@ -0,0 +1,282 @@ +/* + * 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.debug.datanode.container.analyze; + +import com.google.common.util.concurrent.ThreadFactoryBuilder; +import java.io.File; +import java.io.IOException; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Properties; +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 org.apache.commons.io.FileUtils; +import org.apache.hadoop.hdds.conf.ConfigurationSource; +import org.apache.hadoop.hdds.scm.ScmConfigKeys; +import org.apache.hadoop.hdds.utils.HddsServerUtil; +import org.apache.hadoop.hdfs.server.datanode.StorageLocation; +import org.apache.hadoop.ozone.common.InconsistentStorageStateException; +import org.apache.hadoop.ozone.common.Storage; +import org.apache.hadoop.ozone.container.common.helpers.ContainerUtils; +import org.apache.hadoop.ozone.container.common.helpers.DatanodeVersionFile; +import org.apache.hadoop.ozone.container.common.impl.ContainerData; +import org.apache.hadoop.ozone.container.common.impl.ContainerDataYaml; +import org.apache.hadoop.ozone.container.common.utils.StorageVolumeUtil; +import org.apache.hadoop.ozone.container.common.volume.HddsVolume; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * Read-only walker for container directories under {@code hdds.datanode.dir}. + * + * <p>Unlike {@link org.apache.hadoop.ozone.container.ozoneimpl.ContainerReader}, + * this scanner records every container directory it finds, including those with + * missing or invalid metadata and duplicate copies across volumes. + */ +public class ContainerDirectoryScanner { + + private static final Logger LOG = LoggerFactory.getLogger(ContainerDirectoryScanner.class); + + /** + * Scan all configured DataNode storage volumes and return every container + * directory found on disk. + * + * @return map of container ID to all on-disk occurrences for that ID + */ + public Map<Long, List<ContainerDiskOccurrence>> scan(ConfigurationSource conf) throws IOException { + Collection<String> storageDirs = HddsServerUtil.getDatanodeStorageDirs(conf); + + if (storageDirs.isEmpty()) { + return Collections.emptyMap(); + } + + validateStorageDirectories(storageDirs); + Map<Long, List<ContainerDiskOccurrence>> result = new ConcurrentHashMap<>(); + int volumeCount = storageDirs.size(); + ExecutorService executor = Executors.newFixedThreadPool(volumeCount, + new ThreadFactoryBuilder() + .setDaemon(true) + .setNameFormat("ContainerDirectoryScanner-%d") + .build()); + + try { + List<Future<?>> futures = new ArrayList<>(volumeCount); + for (String storageDir : storageDirs) { + String volumeRoot = StorageLocation.parse(storageDir).getUri().getPath(); + futures.add(executor.submit(() -> { + try { + scanVolume(volumeRoot, result); + } catch (IOException e) { + throw new RuntimeException( + "Failed to scan volume " + volumeRoot, e); + } + })); + } + for (Future<?> future : futures) { + try { + future.get(); + } catch (ExecutionException e) { + Throwable cause = e.getCause(); + if (cause instanceof RuntimeException) { + throw (RuntimeException) cause; + } + throw new IOException(cause); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + throw new IOException("Volume scan interrupted", e); + } + } + } finally { + executor.shutdownNow(); + } + + return Collections.unmodifiableMap(toImmutableLists(result)); + } + + /** + * Scan a single DataNode storage volume root and merge results into {@code result}. + */ + private void scanVolume(String volumeRoot, Map<Long, List<ContainerDiskOccurrence>> result) throws IOException { + File hddsRoot = new File(volumeRoot, HddsVolume.HDDS_VOLUME_DIR); + if (!hddsRoot.isDirectory()) { + LOG.warn("HDDS root {} does not exist or is not a directory, skipping volume {}", hddsRoot, volumeRoot); + return; + } + + File versionFile = StorageVolumeUtil.getVersionFile(hddsRoot); + Properties props = DatanodeVersionFile.readFrom(versionFile); + if (props.isEmpty()) { + throw new IOException("Version file " + versionFile + " is missing or empty"); + } + String clusterId; + try { + clusterId = StorageVolumeUtil.getClusterID(props, versionFile, null); + } catch (InconsistentStorageStateException e) { + throw new IOException("Invalid version file " + versionFile, e); + } + + File currentDir = resolveCurrentDir(hddsRoot, clusterId); + if (currentDir == null || !currentDir.isDirectory()) { + LOG.info("No current container directory under {}, skipping volume {}", hddsRoot, volumeRoot); + return; + } + + LOG.info("Scanning container directories under {}", currentDir); + File[] containerTopDirs = currentDir.listFiles(File::isDirectory); + if (containerTopDirs == null) { + throw new IOException("Failed to list container top-level directories under " + currentDir); + } + + for (File containerTopDir : containerTopDirs) { + File[] containerDirs = containerTopDir.listFiles(File::isDirectory); + if (containerDirs == null) { + LOG.warn("Failed to list container directories under {}", containerTopDir); + continue; + } + for (File containerDir : containerDirs) { + recordContainerDir(containerDir, volumeRoot, result); + } + } + } + + /** + * Resolve {@code .../current} using the same rules as + * {@link org.apache.hadoop.ozone.container.ozoneimpl.ContainerReader#readVolume(File)}. + */ + static File resolveCurrentDir(File hddsRoot, String clusterId) throws IOException { + File[] storageDirs = hddsRoot.listFiles(File::isDirectory); + if (storageDirs == null) { + throw new IOException("IO error listing " + hddsRoot); + } + if (storageDirs.length == 0) { + return null; + } + + File clusterIdDir = new File(hddsRoot, clusterId); + File idDir = clusterIdDir; + if (storageDirs.length == 1 && !clusterIdDir.exists()) { + idDir = storageDirs[0]; + } else if (!clusterIdDir.exists()) { + throw new IOException("Volume " + hddsRoot + " is in an inconsistent state. " + + "Expected cluster ID directory " + clusterIdDir + " not found."); + } + return new File(idDir, Storage.STORAGE_DIR_CURRENT); + } + + private static void recordContainerDir(File containerDir, String volumeRoot, + Map<Long, List<ContainerDiskOccurrence>> result) { + long containerId; + try { + containerId = ContainerUtils.getContainerID(containerDir); + } catch (NumberFormatException e) { + LOG.warn("Skipping non-numeric container directory {}", containerDir); + return; + } + + File containerFile = ContainerUtils.getContainerFile(containerDir); + ContainerDiskScanStatus status; + if (!containerFile.exists()) { + status = ContainerDiskScanStatus.MISSING_METADATA; + } else { + status = readMetadataStatus(containerId, containerFile); + } + + long sizeBytes; + try { + sizeBytes = FileUtils.sizeOfDirectory(containerDir); + } catch (IllegalArgumentException e) { + LOG.warn("Failed to compute size for container directory {}, using 0", containerDir, e); + sizeBytes = 0L; + } + + ContainerDiskOccurrence occurrence = new ContainerDiskOccurrence( + containerId, + containerDir.getAbsolutePath(), + volumeRoot, + sizeBytes, + status); + result.compute(containerId, (id, existing) -> { + if (existing == null) { + List<ContainerDiskOccurrence> list = new ArrayList<>(); + list.add(occurrence); + return list; + } + existing.add(occurrence); + return existing; + }); + } + + private static ContainerDiskScanStatus readMetadataStatus(long containerId, + File containerFile) { + try { + ContainerData containerData = ContainerDataYaml.readContainerFile(containerFile); Review Comment: This also needs optimization only for duplicate set. For pure duplicate-directory detection, the first pass only needs the container ID from the directory name (cheap, `ContainerUtils.getContainerID)`. So basically just focus on detecting duplicate or container id collision , then for those only just compute `size + status + YAML` status. This will bring down unnecessary IO and memory cost. ########## hadoop-ozone/cli-debug/src/main/java/org/apache/hadoop/ozone/debug/datanode/container/analyze/ContainerDirectoryScanner.java: ########## @@ -0,0 +1,282 @@ +/* + * 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.debug.datanode.container.analyze; + +import com.google.common.util.concurrent.ThreadFactoryBuilder; +import java.io.File; +import java.io.IOException; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Properties; +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 org.apache.commons.io.FileUtils; +import org.apache.hadoop.hdds.conf.ConfigurationSource; +import org.apache.hadoop.hdds.scm.ScmConfigKeys; +import org.apache.hadoop.hdds.utils.HddsServerUtil; +import org.apache.hadoop.hdfs.server.datanode.StorageLocation; +import org.apache.hadoop.ozone.common.InconsistentStorageStateException; +import org.apache.hadoop.ozone.common.Storage; +import org.apache.hadoop.ozone.container.common.helpers.ContainerUtils; +import org.apache.hadoop.ozone.container.common.helpers.DatanodeVersionFile; +import org.apache.hadoop.ozone.container.common.impl.ContainerData; +import org.apache.hadoop.ozone.container.common.impl.ContainerDataYaml; +import org.apache.hadoop.ozone.container.common.utils.StorageVolumeUtil; +import org.apache.hadoop.ozone.container.common.volume.HddsVolume; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * Read-only walker for container directories under {@code hdds.datanode.dir}. + * + * <p>Unlike {@link org.apache.hadoop.ozone.container.ozoneimpl.ContainerReader}, + * this scanner records every container directory it finds, including those with + * missing or invalid metadata and duplicate copies across volumes. + */ +public class ContainerDirectoryScanner { + + private static final Logger LOG = LoggerFactory.getLogger(ContainerDirectoryScanner.class); + + /** + * Scan all configured DataNode storage volumes and return every container + * directory found on disk. + * + * @return map of container ID to all on-disk occurrences for that ID + */ + public Map<Long, List<ContainerDiskOccurrence>> scan(ConfigurationSource conf) throws IOException { + Collection<String> storageDirs = HddsServerUtil.getDatanodeStorageDirs(conf); + + if (storageDirs.isEmpty()) { + return Collections.emptyMap(); + } + + validateStorageDirectories(storageDirs); + Map<Long, List<ContainerDiskOccurrence>> result = new ConcurrentHashMap<>(); + int volumeCount = storageDirs.size(); + ExecutorService executor = Executors.newFixedThreadPool(volumeCount, + new ThreadFactoryBuilder() + .setDaemon(true) + .setNameFormat("ContainerDirectoryScanner-%d") + .build()); + + try { + List<Future<?>> futures = new ArrayList<>(volumeCount); + for (String storageDir : storageDirs) { + String volumeRoot = StorageLocation.parse(storageDir).getUri().getPath(); + futures.add(executor.submit(() -> { + try { + scanVolume(volumeRoot, result); + } catch (IOException e) { + throw new RuntimeException( + "Failed to scan volume " + volumeRoot, e); + } + })); + } + for (Future<?> future : futures) { + try { + future.get(); + } catch (ExecutionException e) { + Throwable cause = e.getCause(); + if (cause instanceof RuntimeException) { + throw (RuntimeException) cause; + } + throw new IOException(cause); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + throw new IOException("Volume scan interrupted", e); + } + } + } finally { + executor.shutdownNow(); + } + + return Collections.unmodifiableMap(toImmutableLists(result)); + } + + /** + * Scan a single DataNode storage volume root and merge results into {@code result}. + */ + private void scanVolume(String volumeRoot, Map<Long, List<ContainerDiskOccurrence>> result) throws IOException { + File hddsRoot = new File(volumeRoot, HddsVolume.HDDS_VOLUME_DIR); + if (!hddsRoot.isDirectory()) { + LOG.warn("HDDS root {} does not exist or is not a directory, skipping volume {}", hddsRoot, volumeRoot); + return; + } + + File versionFile = StorageVolumeUtil.getVersionFile(hddsRoot); + Properties props = DatanodeVersionFile.readFrom(versionFile); + if (props.isEmpty()) { + throw new IOException("Version file " + versionFile + " is missing or empty"); + } + String clusterId; + try { + clusterId = StorageVolumeUtil.getClusterID(props, versionFile, null); + } catch (InconsistentStorageStateException e) { + throw new IOException("Invalid version file " + versionFile, e); + } + + File currentDir = resolveCurrentDir(hddsRoot, clusterId); + if (currentDir == null || !currentDir.isDirectory()) { + LOG.info("No current container directory under {}, skipping volume {}", hddsRoot, volumeRoot); + return; + } + + LOG.info("Scanning container directories under {}", currentDir); + File[] containerTopDirs = currentDir.listFiles(File::isDirectory); Review Comment: This below logic is again duplicated. Try using from within `ContainerReader.readVolume` ########## hadoop-ozone/cli-debug/src/main/java/org/apache/hadoop/ozone/debug/datanode/container/analyze/ContainerDirectoryScanner.java: ########## @@ -0,0 +1,282 @@ +/* + * 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.debug.datanode.container.analyze; + +import com.google.common.util.concurrent.ThreadFactoryBuilder; +import java.io.File; +import java.io.IOException; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Properties; +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 org.apache.commons.io.FileUtils; +import org.apache.hadoop.hdds.conf.ConfigurationSource; +import org.apache.hadoop.hdds.scm.ScmConfigKeys; +import org.apache.hadoop.hdds.utils.HddsServerUtil; +import org.apache.hadoop.hdfs.server.datanode.StorageLocation; +import org.apache.hadoop.ozone.common.InconsistentStorageStateException; +import org.apache.hadoop.ozone.common.Storage; +import org.apache.hadoop.ozone.container.common.helpers.ContainerUtils; +import org.apache.hadoop.ozone.container.common.helpers.DatanodeVersionFile; +import org.apache.hadoop.ozone.container.common.impl.ContainerData; +import org.apache.hadoop.ozone.container.common.impl.ContainerDataYaml; +import org.apache.hadoop.ozone.container.common.utils.StorageVolumeUtil; +import org.apache.hadoop.ozone.container.common.volume.HddsVolume; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * Read-only walker for container directories under {@code hdds.datanode.dir}. + * + * <p>Unlike {@link org.apache.hadoop.ozone.container.ozoneimpl.ContainerReader}, + * this scanner records every container directory it finds, including those with + * missing or invalid metadata and duplicate copies across volumes. + */ +public class ContainerDirectoryScanner { + + private static final Logger LOG = LoggerFactory.getLogger(ContainerDirectoryScanner.class); + + /** + * Scan all configured DataNode storage volumes and return every container + * directory found on disk. + * + * @return map of container ID to all on-disk occurrences for that ID + */ + public Map<Long, List<ContainerDiskOccurrence>> scan(ConfigurationSource conf) throws IOException { + Collection<String> storageDirs = HddsServerUtil.getDatanodeStorageDirs(conf); + + if (storageDirs.isEmpty()) { + return Collections.emptyMap(); + } + + validateStorageDirectories(storageDirs); + Map<Long, List<ContainerDiskOccurrence>> result = new ConcurrentHashMap<>(); + int volumeCount = storageDirs.size(); + ExecutorService executor = Executors.newFixedThreadPool(volumeCount, + new ThreadFactoryBuilder() + .setDaemon(true) + .setNameFormat("ContainerDirectoryScanner-%d") + .build()); + + try { + List<Future<?>> futures = new ArrayList<>(volumeCount); + for (String storageDir : storageDirs) { + String volumeRoot = StorageLocation.parse(storageDir).getUri().getPath(); + futures.add(executor.submit(() -> { + try { + scanVolume(volumeRoot, result); + } catch (IOException e) { + throw new RuntimeException( + "Failed to scan volume " + volumeRoot, e); + } + })); + } + for (Future<?> future : futures) { + try { + future.get(); + } catch (ExecutionException e) { + Throwable cause = e.getCause(); + if (cause instanceof RuntimeException) { + throw (RuntimeException) cause; + } + throw new IOException(cause); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + throw new IOException("Volume scan interrupted", e); + } + } + } finally { + executor.shutdownNow(); + } + + return Collections.unmodifiableMap(toImmutableLists(result)); + } + + /** + * Scan a single DataNode storage volume root and merge results into {@code result}. + */ + private void scanVolume(String volumeRoot, Map<Long, List<ContainerDiskOccurrence>> result) throws IOException { + File hddsRoot = new File(volumeRoot, HddsVolume.HDDS_VOLUME_DIR); + if (!hddsRoot.isDirectory()) { + LOG.warn("HDDS root {} does not exist or is not a directory, skipping volume {}", hddsRoot, volumeRoot); + return; + } + + File versionFile = StorageVolumeUtil.getVersionFile(hddsRoot); + Properties props = DatanodeVersionFile.readFrom(versionFile); + if (props.isEmpty()) { + throw new IOException("Version file " + versionFile + " is missing or empty"); + } + String clusterId; + try { + clusterId = StorageVolumeUtil.getClusterID(props, versionFile, null); + } catch (InconsistentStorageStateException e) { + throw new IOException("Invalid version file " + versionFile, e); + } + + File currentDir = resolveCurrentDir(hddsRoot, clusterId); + if (currentDir == null || !currentDir.isDirectory()) { + LOG.info("No current container directory under {}, skipping volume {}", hddsRoot, volumeRoot); + return; + } + + LOG.info("Scanning container directories under {}", currentDir); + File[] containerTopDirs = currentDir.listFiles(File::isDirectory); + if (containerTopDirs == null) { + throw new IOException("Failed to list container top-level directories under " + currentDir); + } + + for (File containerTopDir : containerTopDirs) { + File[] containerDirs = containerTopDir.listFiles(File::isDirectory); + if (containerDirs == null) { + LOG.warn("Failed to list container directories under {}", containerTopDir); + continue; + } + for (File containerDir : containerDirs) { + recordContainerDir(containerDir, volumeRoot, result); + } + } + } + + /** + * Resolve {@code .../current} using the same rules as + * {@link org.apache.hadoop.ozone.container.ozoneimpl.ContainerReader#readVolume(File)}. + */ + static File resolveCurrentDir(File hddsRoot, String clusterId) throws IOException { Review Comment: We should not duplicate logic similar to `ContainerReader.readVolume` here. In future any changes will happen there will impact and double effort. Extract a shared helper (e.g. in `StorageVolumeUtil/HddsVolumeUtil`) that returns the current dir for a (h`ddsRoot, clusterId`) and have both call it. -- This is an automated message from the Apache Git Service. To respond to the message, please log on to GitHub and use the URL above to go to the specific comment. To unsubscribe, e-mail: [email protected] For queries about this service, please contact Infrastructure at: [email protected] --------------------------------------------------------------------- To unsubscribe, e-mail: [email protected] For additional commands, e-mail: [email protected]
