szetszwo commented on code in PR #11097:
URL: https://github.com/apache/ozone/pull/11097#discussion_r3867606028


##########
hadoop-hdds/server-scm/src/main/java/org/apache/hadoop/hdds/scm/container/export/ContainerExportManager.java:
##########
@@ -0,0 +1,276 @@
+/*
+ * 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.IOException;
+import java.time.Instant;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.locks.ReadWriteLock;
+import java.util.concurrent.locks.ReentrantReadWriteLock;
+import java.util.function.BooleanSupplier;
+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.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * Manages asynchronous container ID export jobs on the SCM leader.
+ *
+ * <p>Health filters read {@link 
org.apache.hadoop.hdds.scm.container.ContainerInfo#getHealthState()}
+ * as last written by Replication Manager; they are not recomputed during 
export and may be stale
+ * if RM has not yet evaluated a container.
+ *
+ * <p>Job status is kept in memory only. On SCM restart or leader failover, 
in-flight jobs are lost
+ * and the operator must re-submit on the new leader. {@link 
ExportFileManager} owns on-disk layout,
+ * locking, part files, and completed archives; this class tracks {@link 
ExportJob} state and
+ * schedules work.
+ *
+ * <p>Job submission and the running-job slot are guarded by a {@link 
ReadWriteLock}. Per-job
+ * progress is read via {@link ExportJob#toStatus()}, which uses its own read 
lock for a consistent
+ * snapshot.
+ */
+public class ContainerExportManager {
+
+  private static final Logger LOG = 
LoggerFactory.getLogger(ContainerExportManager.class);
+
+  private static final int DEFAULT_BATCH_SIZE = 100_000;
+  private static final int DEFAULT_PART_SIZE = 500_000;
+  private static final long SHUTDOWN_TIMEOUT_MS = 5_000;
+
+  private final ReadWriteLock lock = new ReentrantReadWriteLock();

Review Comment:
   Since this lock only protects `runningJobId`, we can simply use 
AtomicReference.



##########
hadoop-hdds/server-scm/src/main/java/org/apache/hadoop/hdds/scm/container/export/ContainerExportManager.java:
##########
@@ -0,0 +1,276 @@
+/*
+ * 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.IOException;
+import java.time.Instant;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.locks.ReadWriteLock;
+import java.util.concurrent.locks.ReentrantReadWriteLock;
+import java.util.function.BooleanSupplier;
+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.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * Manages asynchronous container ID export jobs on the SCM leader.
+ *
+ * <p>Health filters read {@link 
org.apache.hadoop.hdds.scm.container.ContainerInfo#getHealthState()}
+ * as last written by Replication Manager; they are not recomputed during 
export and may be stale
+ * if RM has not yet evaluated a container.
+ *
+ * <p>Job status is kept in memory only. On SCM restart or leader failover, 
in-flight jobs are lost
+ * and the operator must re-submit on the new leader. {@link 
ExportFileManager} owns on-disk layout,
+ * locking, part files, and completed archives; this class tracks {@link 
ExportJob} state and
+ * schedules work.
+ *
+ * <p>Job submission and the running-job slot are guarded by a {@link 
ReadWriteLock}. Per-job
+ * progress is read via {@link ExportJob#toStatus()}, which uses its own read 
lock for a consistent
+ * snapshot.
+ */
+public class ContainerExportManager {
+
+  private static final Logger LOG = 
LoggerFactory.getLogger(ContainerExportManager.class);
+
+  private static final int DEFAULT_BATCH_SIZE = 100_000;
+  private static final int DEFAULT_PART_SIZE = 500_000;
+  private static final long SHUTDOWN_TIMEOUT_MS = 5_000;
+
+  private final ReadWriteLock lock = new ReentrantReadWriteLock();
+  private final Map<ExportJob.Id, ExportJob> jobMap = new 
ConcurrentHashMap<>();
+  private ExportJob.Id runningJobId;
+  private final ExecutorService workerPool;
+  private final ContainerManager containerManager;
+  private final ExportFileManager fileManager;
+  private final BooleanSupplier isLeaderReady;
+  private final int partSize;
+  private final int batchSize;
+
+  public ContainerExportManager(String scmId, ContainerManager 
containerManager, BooleanSupplier isLeaderReady,
+      OzoneConfiguration conf) {
+    this(scmId, containerManager, isLeaderReady,
+        ExportFileManager.resolveExportDirectory(conf), DEFAULT_PART_SIZE, 
DEFAULT_BATCH_SIZE);
+  }
+
+  ContainerExportManager(String scmId, ContainerManager containerManager, 
BooleanSupplier isLeaderReady,
+      String exportDirectory, int partSize, int batchSize) {
+    this.containerManager = Objects.requireNonNull(containerManager, 
"containerManager == null");
+    this.isLeaderReady = Objects.requireNonNull(isLeaderReady, "isLeaderReady 
== null");
+    this.fileManager = new ExportFileManager(exportDirectory);
+    this.partSize = partSize;
+    this.batchSize = batchSize;
+    this.workerPool = newWorkerPool(scmId);
+  }
+
+  private static ExecutorService newWorkerPool(String scmId) {
+    return Executors.newSingleThreadExecutor(r -> {
+      Thread t = new Thread(r, scmId + "-ContainerExportWorker");
+      t.setDaemon(true);
+      return t;
+    });
+  }
+
+  /**
+   * Initializes the export directory. Must be called once before submitting 
jobs.
+   */
+  public void start() throws IOException {
+    fileManager.start();
+    LOG.info("ContainerExportManager started (dir={}, partSize={}, 
batchSize={})",
+        fileManager.getExportDirectory(), partSize, batchSize);
+  }
+
+  /**
+   * Submit a container ID export job on the SCM leader.
+   *
+   * @return job id, or {@code null} if not leader or another export is 
already running
+   */
+  public ExportJob.Id submitJob(ContainerID start, LifeCycleState 
lifeCycleState,
+      ContainerHealthState healthState) {
+    if (!isLeaderReady.getAsBoolean()) {
+      return null;
+    }
+
+    final ExportScope scope = ExportScope.of(lifeCycleState, healthState);
+
+    lock.writeLock().lock();
+    try {
+      if (runningJobId != null) {
+        return null;
+      }
+
+      ExportJob.Id jobId = ExportJob.Id.newId();
+      Instant now = Instant.now();
+      String jobStartTime = ExportFileManager.formatJobStartTime(now);
+      String plannedArchivePath = fileManager.resolveArchiveFile(scope, 
jobStartTime, jobId).getAbsolutePath();
+
+      ExportJob job = new ExportJob(jobId, scope, jobStartTime, 
plannedArchivePath, start, batchSize, partSize);
+      runningJobId = jobId;
+      jobMap.put(jobId, job);
+
+      workerPool.submit(() -> executeExport(job));
+      LOG.info("Submitted container ID export job {} (scope={}, start={}, 
batchSize={}, partSize={})",
+          jobId, scope, start, batchSize, partSize);
+      return jobId;
+    } finally {
+      lock.writeLock().unlock();
+    }
+  }
+
+  public ExportJob.Status getExportStatus(ExportJob.Id jobId) {
+    ExportJob job = jobMap.get(jobId);
+    return job != null ? job.toStatus() : null;
+  }
+
+  public void shutdown() {
+    LOG.info("Shutting down ContainerExportManager");
+    workerPool.shutdownNow();
+    try {
+      if (!workerPool.awaitTermination(SHUTDOWN_TIMEOUT_MS, 
TimeUnit.MILLISECONDS)) {
+        LOG.warn("Timed out waiting for export worker shutdown");
+      }
+    } catch (InterruptedException e) {
+      LOG.warn("Interrupted waiting for export worker shutdown");
+      Thread.currentThread().interrupt();
+    }
+    try {
+      fileManager.unlock();
+    } catch (IOException e) {
+      LOG.warn("Failed to unlock container export directory", e);
+    }
+  }
+
+  private void executeExport(ExportJob job) {

Review Comment:
   This method is too long -- there are nested try-try-while-for.  In such 
case, we should split it into multiple methods for better readibiility.



##########
hadoop-hdds/server-scm/src/main/java/org/apache/hadoop/hdds/scm/container/export/ExportJob.java:
##########
@@ -75,10 +92,158 @@ public int hashCode() {
     }
   }
 
-  ExportJob(Id id, ExportScope scope, String jobStartTime) {
+  /**
+   * Immutable snapshot of export progress.
+   */
+  public static final class Status {

Review Comment:
   Make it non-static.  Then, we don't have to copy the id and other fields.



##########
hadoop-hdds/server-scm/src/main/java/org/apache/hadoop/hdds/scm/container/export/ExportJob.java:
##########
@@ -21,15 +21,32 @@
 import java.io.IOException;
 import java.util.Objects;
 import java.util.UUID;
+import java.util.concurrent.locks.ReadWriteLock;
+import java.util.concurrent.locks.ReentrantReadWriteLock;
+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;
 
 /**
- * Metadata for a container ID export job.
+ * In-memory state for a container ID export job.
+ * <p>Mutable fields are guarded by a {@link ReadWriteLock} so {@link 
#toStatus()} returns a
+ * consistent snapshot while the worker updates progress.
  */
 public final class ExportJob {
 
+  private final ReadWriteLock lock = new ReentrantReadWriteLock();
+
   private final Id id;
   private final ExportScope scope;
   private final String jobStartTime;
+  private final ContainerID startContainerId;
+  private final int batchSize;
+  private final int partSize;
+  // Planned .tar.gz output path, fixed at job creation; used by the worker to 
write the archive.
+  private final String plannedArchivePath;
+  private ExecutionState executionState = ExecutionState.RUNNING;
+  private long totalRows;
+  private String errorMessage;

Review Comment:
   Use CompletableFuture for all these three fields.  Then, we won't need the 
lock and the ExecutionState enum.



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