devmadhuu commented on code in PR #10673:
URL: https://github.com/apache/ozone/pull/10673#discussion_r3542029534


##########
hadoop-hdds/server-scm/src/main/java/org/apache/hadoop/hdds/scm/container/export/ContainerExportManager.java:
##########
@@ -0,0 +1,499 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.hadoop.hdds.scm.container.export;
+
+import java.io.BufferedWriter;
+import java.io.File;
+import java.io.IOException;
+import java.nio.charset.StandardCharsets;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.Paths;
+import java.time.Instant;
+import java.time.ZoneOffset;
+import java.time.format.DateTimeFormatter;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Map;
+import java.util.UUID;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+import java.util.concurrent.Future;
+import java.util.concurrent.TimeUnit;
+import org.apache.commons.io.FileUtils;
+import org.apache.hadoop.hdds.conf.OzoneConfiguration;
+import org.apache.hadoop.hdds.protocol.proto.HddsProtos.LifeCycleState;
+import org.apache.hadoop.hdds.scm.container.ContainerHealthState;
+import org.apache.hadoop.hdds.scm.container.ContainerID;
+import org.apache.hadoop.hdds.scm.container.ContainerManager;
+import org.apache.hadoop.hdds.server.ServerUtils;
+import org.apache.hadoop.hdds.utils.Archiver;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * Manages asynchronous container ID export jobs on SCM leader.
+ */
+public class ContainerExportManager {
+
+  private static final Logger LOG = 
LoggerFactory.getLogger(ContainerExportManager.class);
+
+  private static final DateTimeFormatter METADATA_TIMESTAMP_FORMAT =
+      
DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss'Z'").withZone(ZoneOffset.UTC);
+  private static final DateTimeFormatter FILENAME_TIMESTAMP_FORMAT =
+      
DateTimeFormatter.ofPattern("yyyyMMdd'T'HHmmss'Z'").withZone(ZoneOffset.UTC);
+
+  private static final String EXPORT_SUBDIR = "exports";
+  private static final int DEFAULT_SHARD_SIZE = 500_000;
+  private static final int DEFAULT_PAGE_SIZE = 100_000;
+  private static final int MAX_SHARD_SIZE = 5_000_000;

Review Comment:
   Better to keep both `MAX_SHARD_SIZE` and `MAX_PAGE_SIZE` in some constants 
common file, currently being defined in CLI and server side separately in 
`ExportContainerIDs` class also.



##########
hadoop-ozone/cli-debug/src/main/java/org/apache/hadoop/ozone/debug/scm/container/ExportContainerStatus.java:
##########
@@ -0,0 +1,72 @@
+/*
+ * 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.scm.container;
+
+import java.io.PrintWriter;
+import java.util.concurrent.Callable;
+import org.apache.hadoop.hdds.cli.AbstractSubcommand;
+import org.apache.hadoop.hdds.scm.cli.ContainerOperationClient;
+import org.apache.hadoop.hdds.scm.cli.ScmOption;
+import org.apache.hadoop.hdds.scm.container.export.ContainerExportStatus;
+import picocli.CommandLine;
+
+/**
+ * Command to check status of export container IDs to a TAR file on SCM.
+ */
[email protected](
+    name = "status",

Review Comment:
   This job status is being fetched based on `checkAdminAccess` called inside 
`SCMClientProtocolServer.submitContainerIdExport/getContainerIdExportStatus` , 
so what if leader changes after submitting job, the new leader has no record → 
export status throws "`Export job not found`", while the original job keeps 
running on the now-follower and drops a TAR on a node the operator wasn't told 
about.



##########
hadoop-hdds/server-scm/src/main/java/org/apache/hadoop/hdds/scm/container/export/ContainerExportManager.java:
##########
@@ -0,0 +1,499 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.hadoop.hdds.scm.container.export;
+
+import java.io.BufferedWriter;
+import java.io.File;
+import java.io.IOException;
+import java.nio.charset.StandardCharsets;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.Paths;
+import java.time.Instant;
+import java.time.ZoneOffset;
+import java.time.format.DateTimeFormatter;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Map;
+import java.util.UUID;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+import java.util.concurrent.Future;
+import java.util.concurrent.TimeUnit;
+import org.apache.commons.io.FileUtils;
+import org.apache.hadoop.hdds.conf.OzoneConfiguration;
+import org.apache.hadoop.hdds.protocol.proto.HddsProtos.LifeCycleState;
+import org.apache.hadoop.hdds.scm.container.ContainerHealthState;
+import org.apache.hadoop.hdds.scm.container.ContainerID;
+import org.apache.hadoop.hdds.scm.container.ContainerManager;
+import org.apache.hadoop.hdds.server.ServerUtils;
+import org.apache.hadoop.hdds.utils.Archiver;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * Manages asynchronous container ID export jobs on SCM leader.
+ */
+public class ContainerExportManager {
+
+  private static final Logger LOG = 
LoggerFactory.getLogger(ContainerExportManager.class);
+
+  private static final DateTimeFormatter METADATA_TIMESTAMP_FORMAT =
+      
DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss'Z'").withZone(ZoneOffset.UTC);
+  private static final DateTimeFormatter FILENAME_TIMESTAMP_FORMAT =
+      
DateTimeFormatter.ofPattern("yyyyMMdd'T'HHmmss'Z'").withZone(ZoneOffset.UTC);
+
+  private static final String EXPORT_SUBDIR = "exports";
+  private static final int DEFAULT_SHARD_SIZE = 500_000;
+  private static final int DEFAULT_PAGE_SIZE = 100_000;
+  private static final int MAX_SHARD_SIZE = 5_000_000;
+  private static final int MAX_PAGE_SIZE = 1_000_000;
+
+  private final Map<String, ExportJob> jobTracker = new ConcurrentHashMap<>();
+  private final ExecutorService workerPool;
+  private final Map<String, Future<?>> runningTasks = new 
ConcurrentHashMap<>();
+  private final ContainerManager containerManager;
+  private final String exportDirectory;
+  private final int defaultShardSize;
+  private final int defaultPageSize;
+  private final Object submitLock = new Object();
+
+  public ContainerExportManager(ContainerManager containerManager,
+                                OzoneConfiguration conf) {
+    this(containerManager, resolveExportDirectory(conf),
+        DEFAULT_SHARD_SIZE, DEFAULT_PAGE_SIZE);
+  }
+
+  ContainerExportManager(ContainerManager containerManager,
+      String exportDirectory, int defaultShardSize, int defaultPageSize) {
+    this.containerManager = containerManager;
+    this.exportDirectory = exportDirectory;
+    this.defaultShardSize = defaultShardSize;
+    this.defaultPageSize = defaultPageSize;
+    this.workerPool = Executors.newSingleThreadExecutor(r -> {
+      Thread t = new Thread(r, "ContainerExportWorker");
+      t.setDaemon(true);
+      return t;
+    });
+
+    try {
+      Files.createDirectories(Paths.get(exportDirectory));
+    } catch (IOException e) {
+      LOG.error("Failed to create export directory: {}", exportDirectory, e);
+    }
+    LOG.info("ContainerExportManager initialized (dir={}, defaultShardSize={}, 
defaultPageSize={})",
+        exportDirectory, defaultShardSize, defaultPageSize);
+  }
+
+  private static String resolveExportDirectory(OzoneConfiguration conf) {
+    File scmDbDir = ServerUtils.getScmDbDir(conf);
+    return new File(scmDbDir, EXPORT_SUBDIR).getAbsolutePath();
+  }
+
+  /**
+   * Submit a container ID export job.
+   *
+   * @param start optional inclusive start container ID (0 for beginning)
+   * @param lifeCycleState optional lifecycle filter
+   * @param healthState optional health filter
+   * @param maxRows optional row limit (0 = unlimited)
+   * @param pageSize IDs fetched per SCM read (0 = manager default)
+   * @param shardSize IDs per TAR entry (0 = manager default)
+   * @return job id
+   */
+  public String submitJob(ContainerID start, LifeCycleState lifeCycleState,
+      ContainerHealthState healthState, long maxRows, int pageSize, int 
shardSize) {
+    if (lifeCycleState == null && healthState == null) {
+      throw new IllegalArgumentException("At least one of healthState or 
lifecycleState filter is required.");
+    }
+    validateRequest(start, maxRows, pageSize, shardSize);
+    int resolvedPageSize = pageSize > 0 ? pageSize : defaultPageSize;
+    int resolvedShardSize = shardSize > 0 ? shardSize : defaultShardSize;
+
+    String jobId = UUID.randomUUID().toString();
+    String scope = buildScope(lifeCycleState, healthState);
+    Instant now = Instant.now();
+    String metadataTimestamp = METADATA_TIMESTAMP_FORMAT.format(now);
+    String fileTimestamp = FILENAME_TIMESTAMP_FORMAT.format(now);
+    String tarFileName = String.format("container-ids-%s-%s-%s.tar", scope, 
fileTimestamp, jobId);
+    String tarPath = exportDirectory + File.separator + tarFileName;
+
+    ExportJob job = new ExportJob(jobId, scope, metadataTimestamp, tarPath,
+        start, lifeCycleState, healthState, maxRows, resolvedPageSize, 
resolvedShardSize);
+
+    synchronized (submitLock) {
+      boolean exportInProgress = jobTracker.values().stream()
+          .anyMatch(j -> j.getState() == ContainerExportStatus.State.RUNNING);
+      if (exportInProgress) {
+        throw new IllegalStateException("Another container ID export is 
already running.");
+      }
+      jobTracker.put(jobId, job);
+    }
+
+    Future<?> future = workerPool.submit(() -> executeExport(job));

Review Comment:
   On SCM restart/crash, These submitted jobs or in progress jobs are lost and 
partial work/+.tar artifacts can remain (cleanup only runs on graceful 
FAILED/cancel paths). So any metric or information for user later ? Probably we 
should cleanup any partial incomplete jobs data on restart of SCM if job is 
crashed. Since we are only maintaining a `ConcurrentHashmap` for tracking 
submitted job, this memory will be lost on SCM crash or restart, so some file 
should be there at export location for tracking and on restart SCM should check 
if any partial left out job files should be cleaned up.



##########
hadoop-hdds/server-scm/src/main/java/org/apache/hadoop/hdds/scm/container/export/ContainerExportManager.java:
##########
@@ -0,0 +1,499 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.hadoop.hdds.scm.container.export;
+
+import java.io.BufferedWriter;
+import java.io.File;
+import java.io.IOException;
+import java.nio.charset.StandardCharsets;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.Paths;
+import java.time.Instant;
+import java.time.ZoneOffset;
+import java.time.format.DateTimeFormatter;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Map;
+import java.util.UUID;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+import java.util.concurrent.Future;
+import java.util.concurrent.TimeUnit;
+import org.apache.commons.io.FileUtils;
+import org.apache.hadoop.hdds.conf.OzoneConfiguration;
+import org.apache.hadoop.hdds.protocol.proto.HddsProtos.LifeCycleState;
+import org.apache.hadoop.hdds.scm.container.ContainerHealthState;
+import org.apache.hadoop.hdds.scm.container.ContainerID;
+import org.apache.hadoop.hdds.scm.container.ContainerManager;
+import org.apache.hadoop.hdds.server.ServerUtils;
+import org.apache.hadoop.hdds.utils.Archiver;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * Manages asynchronous container ID export jobs on SCM leader.
+ */
+public class ContainerExportManager {
+
+  private static final Logger LOG = 
LoggerFactory.getLogger(ContainerExportManager.class);
+
+  private static final DateTimeFormatter METADATA_TIMESTAMP_FORMAT =
+      
DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss'Z'").withZone(ZoneOffset.UTC);
+  private static final DateTimeFormatter FILENAME_TIMESTAMP_FORMAT =
+      
DateTimeFormatter.ofPattern("yyyyMMdd'T'HHmmss'Z'").withZone(ZoneOffset.UTC);
+
+  private static final String EXPORT_SUBDIR = "exports";
+  private static final int DEFAULT_SHARD_SIZE = 500_000;
+  private static final int DEFAULT_PAGE_SIZE = 100_000;
+  private static final int MAX_SHARD_SIZE = 5_000_000;
+  private static final int MAX_PAGE_SIZE = 1_000_000;
+
+  private final Map<String, ExportJob> jobTracker = new ConcurrentHashMap<>();
+  private final ExecutorService workerPool;
+  private final Map<String, Future<?>> runningTasks = new 
ConcurrentHashMap<>();
+  private final ContainerManager containerManager;
+  private final String exportDirectory;
+  private final int defaultShardSize;
+  private final int defaultPageSize;
+  private final Object submitLock = new Object();
+
+  public ContainerExportManager(ContainerManager containerManager,
+                                OzoneConfiguration conf) {
+    this(containerManager, resolveExportDirectory(conf),
+        DEFAULT_SHARD_SIZE, DEFAULT_PAGE_SIZE);
+  }
+
+  ContainerExportManager(ContainerManager containerManager,
+      String exportDirectory, int defaultShardSize, int defaultPageSize) {
+    this.containerManager = containerManager;
+    this.exportDirectory = exportDirectory;
+    this.defaultShardSize = defaultShardSize;
+    this.defaultPageSize = defaultPageSize;
+    this.workerPool = Executors.newSingleThreadExecutor(r -> {
+      Thread t = new Thread(r, "ContainerExportWorker");
+      t.setDaemon(true);
+      return t;
+    });
+
+    try {
+      Files.createDirectories(Paths.get(exportDirectory));
+    } catch (IOException e) {
+      LOG.error("Failed to create export directory: {}", exportDirectory, e);
+    }
+    LOG.info("ContainerExportManager initialized (dir={}, defaultShardSize={}, 
defaultPageSize={})",
+        exportDirectory, defaultShardSize, defaultPageSize);
+  }
+
+  private static String resolveExportDirectory(OzoneConfiguration conf) {
+    File scmDbDir = ServerUtils.getScmDbDir(conf);
+    return new File(scmDbDir, EXPORT_SUBDIR).getAbsolutePath();
+  }
+
+  /**
+   * Submit a container ID export job.
+   *
+   * @param start optional inclusive start container ID (0 for beginning)
+   * @param lifeCycleState optional lifecycle filter
+   * @param healthState optional health filter
+   * @param maxRows optional row limit (0 = unlimited)
+   * @param pageSize IDs fetched per SCM read (0 = manager default)
+   * @param shardSize IDs per TAR entry (0 = manager default)
+   * @return job id
+   */
+  public String submitJob(ContainerID start, LifeCycleState lifeCycleState,
+      ContainerHealthState healthState, long maxRows, int pageSize, int 
shardSize) {
+    if (lifeCycleState == null && healthState == null) {
+      throw new IllegalArgumentException("At least one of healthState or 
lifecycleState filter is required.");
+    }
+    validateRequest(start, maxRows, pageSize, shardSize);
+    int resolvedPageSize = pageSize > 0 ? pageSize : defaultPageSize;
+    int resolvedShardSize = shardSize > 0 ? shardSize : defaultShardSize;
+
+    String jobId = UUID.randomUUID().toString();
+    String scope = buildScope(lifeCycleState, healthState);
+    Instant now = Instant.now();
+    String metadataTimestamp = METADATA_TIMESTAMP_FORMAT.format(now);
+    String fileTimestamp = FILENAME_TIMESTAMP_FORMAT.format(now);
+    String tarFileName = String.format("container-ids-%s-%s-%s.tar", scope, 
fileTimestamp, jobId);
+    String tarPath = exportDirectory + File.separator + tarFileName;
+
+    ExportJob job = new ExportJob(jobId, scope, metadataTimestamp, tarPath,
+        start, lifeCycleState, healthState, maxRows, resolvedPageSize, 
resolvedShardSize);
+
+    synchronized (submitLock) {
+      boolean exportInProgress = jobTracker.values().stream()
+          .anyMatch(j -> j.getState() == ContainerExportStatus.State.RUNNING);
+      if (exportInProgress) {
+        throw new IllegalStateException("Another container ID export is 
already running.");
+      }
+      jobTracker.put(jobId, job);

Review Comment:
   Did this map ever gets cleaned up ?



##########
hadoop-hdds/server-scm/src/main/java/org/apache/hadoop/hdds/scm/container/export/ContainerExportManager.java:
##########
@@ -0,0 +1,499 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.hadoop.hdds.scm.container.export;
+
+import java.io.BufferedWriter;
+import java.io.File;
+import java.io.IOException;
+import java.nio.charset.StandardCharsets;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.Paths;
+import java.time.Instant;
+import java.time.ZoneOffset;
+import java.time.format.DateTimeFormatter;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Map;
+import java.util.UUID;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+import java.util.concurrent.Future;
+import java.util.concurrent.TimeUnit;
+import org.apache.commons.io.FileUtils;
+import org.apache.hadoop.hdds.conf.OzoneConfiguration;
+import org.apache.hadoop.hdds.protocol.proto.HddsProtos.LifeCycleState;
+import org.apache.hadoop.hdds.scm.container.ContainerHealthState;
+import org.apache.hadoop.hdds.scm.container.ContainerID;
+import org.apache.hadoop.hdds.scm.container.ContainerManager;
+import org.apache.hadoop.hdds.server.ServerUtils;
+import org.apache.hadoop.hdds.utils.Archiver;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * Manages asynchronous container ID export jobs on SCM leader.
+ */
+public class ContainerExportManager {
+
+  private static final Logger LOG = 
LoggerFactory.getLogger(ContainerExportManager.class);
+
+  private static final DateTimeFormatter METADATA_TIMESTAMP_FORMAT =
+      
DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss'Z'").withZone(ZoneOffset.UTC);
+  private static final DateTimeFormatter FILENAME_TIMESTAMP_FORMAT =
+      
DateTimeFormatter.ofPattern("yyyyMMdd'T'HHmmss'Z'").withZone(ZoneOffset.UTC);
+
+  private static final String EXPORT_SUBDIR = "exports";
+  private static final int DEFAULT_SHARD_SIZE = 500_000;
+  private static final int DEFAULT_PAGE_SIZE = 100_000;
+  private static final int MAX_SHARD_SIZE = 5_000_000;
+  private static final int MAX_PAGE_SIZE = 1_000_000;
+
+  private final Map<String, ExportJob> jobTracker = new ConcurrentHashMap<>();
+  private final ExecutorService workerPool;
+  private final Map<String, Future<?>> runningTasks = new 
ConcurrentHashMap<>();
+  private final ContainerManager containerManager;
+  private final String exportDirectory;
+  private final int defaultShardSize;
+  private final int defaultPageSize;
+  private final Object submitLock = new Object();
+
+  public ContainerExportManager(ContainerManager containerManager,
+                                OzoneConfiguration conf) {
+    this(containerManager, resolveExportDirectory(conf),
+        DEFAULT_SHARD_SIZE, DEFAULT_PAGE_SIZE);
+  }
+
+  ContainerExportManager(ContainerManager containerManager,
+      String exportDirectory, int defaultShardSize, int defaultPageSize) {
+    this.containerManager = containerManager;
+    this.exportDirectory = exportDirectory;
+    this.defaultShardSize = defaultShardSize;
+    this.defaultPageSize = defaultPageSize;
+    this.workerPool = Executors.newSingleThreadExecutor(r -> {
+      Thread t = new Thread(r, "ContainerExportWorker");
+      t.setDaemon(true);
+      return t;
+    });
+
+    try {
+      Files.createDirectories(Paths.get(exportDirectory));
+    } catch (IOException e) {
+      LOG.error("Failed to create export directory: {}", exportDirectory, e);
+    }
+    LOG.info("ContainerExportManager initialized (dir={}, defaultShardSize={}, 
defaultPageSize={})",
+        exportDirectory, defaultShardSize, defaultPageSize);
+  }
+
+  private static String resolveExportDirectory(OzoneConfiguration conf) {
+    File scmDbDir = ServerUtils.getScmDbDir(conf);
+    return new File(scmDbDir, EXPORT_SUBDIR).getAbsolutePath();
+  }
+
+  /**
+   * Submit a container ID export job.
+   *
+   * @param start optional inclusive start container ID (0 for beginning)
+   * @param lifeCycleState optional lifecycle filter
+   * @param healthState optional health filter
+   * @param maxRows optional row limit (0 = unlimited)
+   * @param pageSize IDs fetched per SCM read (0 = manager default)
+   * @param shardSize IDs per TAR entry (0 = manager default)
+   * @return job id
+   */
+  public String submitJob(ContainerID start, LifeCycleState lifeCycleState,
+      ContainerHealthState healthState, long maxRows, int pageSize, int 
shardSize) {
+    if (lifeCycleState == null && healthState == null) {
+      throw new IllegalArgumentException("At least one of healthState or 
lifecycleState filter is required.");
+    }
+    validateRequest(start, maxRows, pageSize, shardSize);
+    int resolvedPageSize = pageSize > 0 ? pageSize : defaultPageSize;
+    int resolvedShardSize = shardSize > 0 ? shardSize : defaultShardSize;
+
+    String jobId = UUID.randomUUID().toString();
+    String scope = buildScope(lifeCycleState, healthState);
+    Instant now = Instant.now();
+    String metadataTimestamp = METADATA_TIMESTAMP_FORMAT.format(now);
+    String fileTimestamp = FILENAME_TIMESTAMP_FORMAT.format(now);
+    String tarFileName = String.format("container-ids-%s-%s-%s.tar", scope, 
fileTimestamp, jobId);
+    String tarPath = exportDirectory + File.separator + tarFileName;
+
+    ExportJob job = new ExportJob(jobId, scope, metadataTimestamp, tarPath,
+        start, lifeCycleState, healthState, maxRows, resolvedPageSize, 
resolvedShardSize);
+
+    synchronized (submitLock) {
+      boolean exportInProgress = jobTracker.values().stream()
+          .anyMatch(j -> j.getState() == ContainerExportStatus.State.RUNNING);
+      if (exportInProgress) {
+        throw new IllegalStateException("Another container ID export is 
already running.");
+      }
+      jobTracker.put(jobId, job);
+    }
+
+    Future<?> future = workerPool.submit(() -> executeExport(job));
+    runningTasks.put(jobId, future);
+    LOG.info("Submitted container ID export job {} (scope={}, start={}, 
maxRows={}, pageSize={}, shardSize={})",

Review Comment:
   Should have some metrics for jobs submitted/failed, rows exported, bytes 
written ?



##########
hadoop-hdds/server-scm/src/main/java/org/apache/hadoop/hdds/scm/container/export/ContainerExportManager.java:
##########
@@ -0,0 +1,499 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.hadoop.hdds.scm.container.export;
+
+import java.io.BufferedWriter;
+import java.io.File;
+import java.io.IOException;
+import java.nio.charset.StandardCharsets;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.Paths;
+import java.time.Instant;
+import java.time.ZoneOffset;
+import java.time.format.DateTimeFormatter;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Map;
+import java.util.UUID;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+import java.util.concurrent.Future;
+import java.util.concurrent.TimeUnit;
+import org.apache.commons.io.FileUtils;
+import org.apache.hadoop.hdds.conf.OzoneConfiguration;
+import org.apache.hadoop.hdds.protocol.proto.HddsProtos.LifeCycleState;
+import org.apache.hadoop.hdds.scm.container.ContainerHealthState;
+import org.apache.hadoop.hdds.scm.container.ContainerID;
+import org.apache.hadoop.hdds.scm.container.ContainerManager;
+import org.apache.hadoop.hdds.server.ServerUtils;
+import org.apache.hadoop.hdds.utils.Archiver;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * Manages asynchronous container ID export jobs on SCM leader.
+ */
+public class ContainerExportManager {
+
+  private static final Logger LOG = 
LoggerFactory.getLogger(ContainerExportManager.class);
+
+  private static final DateTimeFormatter METADATA_TIMESTAMP_FORMAT =
+      
DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss'Z'").withZone(ZoneOffset.UTC);
+  private static final DateTimeFormatter FILENAME_TIMESTAMP_FORMAT =
+      
DateTimeFormatter.ofPattern("yyyyMMdd'T'HHmmss'Z'").withZone(ZoneOffset.UTC);
+
+  private static final String EXPORT_SUBDIR = "exports";
+  private static final int DEFAULT_SHARD_SIZE = 500_000;
+  private static final int DEFAULT_PAGE_SIZE = 100_000;
+  private static final int MAX_SHARD_SIZE = 5_000_000;
+  private static final int MAX_PAGE_SIZE = 1_000_000;
+
+  private final Map<String, ExportJob> jobTracker = new ConcurrentHashMap<>();
+  private final ExecutorService workerPool;
+  private final Map<String, Future<?>> runningTasks = new 
ConcurrentHashMap<>();
+  private final ContainerManager containerManager;
+  private final String exportDirectory;
+  private final int defaultShardSize;
+  private final int defaultPageSize;
+  private final Object submitLock = new Object();
+
+  public ContainerExportManager(ContainerManager containerManager,
+                                OzoneConfiguration conf) {
+    this(containerManager, resolveExportDirectory(conf),
+        DEFAULT_SHARD_SIZE, DEFAULT_PAGE_SIZE);
+  }
+
+  ContainerExportManager(ContainerManager containerManager,
+      String exportDirectory, int defaultShardSize, int defaultPageSize) {
+    this.containerManager = containerManager;
+    this.exportDirectory = exportDirectory;
+    this.defaultShardSize = defaultShardSize;
+    this.defaultPageSize = defaultPageSize;
+    this.workerPool = Executors.newSingleThreadExecutor(r -> {
+      Thread t = new Thread(r, "ContainerExportWorker");
+      t.setDaemon(true);
+      return t;
+    });
+
+    try {
+      Files.createDirectories(Paths.get(exportDirectory));
+    } catch (IOException e) {
+      LOG.error("Failed to create export directory: {}", exportDirectory, e);
+    }
+    LOG.info("ContainerExportManager initialized (dir={}, defaultShardSize={}, 
defaultPageSize={})",
+        exportDirectory, defaultShardSize, defaultPageSize);
+  }
+
+  private static String resolveExportDirectory(OzoneConfiguration conf) {
+    File scmDbDir = ServerUtils.getScmDbDir(conf);
+    return new File(scmDbDir, EXPORT_SUBDIR).getAbsolutePath();

Review Comment:
   `EXPORT_SUBDIR` is hardcoded as "`exports`", then it means user cannot set 
any other location and all tars will land up on same volume where active scm.db 
will be stored. Simply filing up the disk there may increase IO when volume 
gets filled up quickly due to exports and may impact writes on active live scm 
db.  So better add a real `@Config key` (e.g. `ozone.scm.container.export.dir`) 
with {scm.db.dirs}/exports as the fallback



-- 
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]

Reply via email to