You are viewing a plain text version of this content. The canonical link for it is here.
Posted to issues@ozone.apache.org by "devmadhuu (via GitHub)" <gi...@apache.org> on 2025/04/01 11:54:36 UTC

[PR] HDDS-12707. Recon - Streaming-Based Approach for Fetch and Extraction of Recon OM DB Snapshot Tar SST files. [ozone]

devmadhuu opened a new pull request, #8212:
URL: https://github.com/apache/ozone/pull/8212

   ## What changes were proposed in this pull request?
   This PR change is to improve Recon OM DB Snapshot Tar ball (SST files) during bootstrap of Recon using streaming-Based approach for fetch and extraction.
   
   Instead of storing the full TAR file by Recon and waiting for complete transfer, let's extract files as they arrive using TarArchiveInputStream.
   This will:
       - Reduce disk I/O
       - Start processing sooner
       - Avoid extra storage needs
   
   **Why This is More Efficient**
       No Temporary TAR File
            -   Directly extracts files while streaming, eliminating the need to store the full TAR.
   
   **Starts Extracting Immediately**
          -    No waiting for the full file to be received; extraction happens as data arrives.
   
   **Lower Disk I/O & Storage Needs**
         - Removes unnecessary FileUtils.copyInputStreamToFile() call.
         - Avoids writing and re-reading the TAR file.
   
   **Handles Both Files & Directories**
           - Ensures correct directory structure before writing files.
   
   **Using Multithreading for Parallel Extraction**
   To extract files in parallel, we need to:
         - Use a thread pool to process multiple files at the same time.
         - Extract files asynchronously while maintaining order and efficiency.
         - Ensure correct handling of directories before writing files.
   
   ## What is the link to the Apache JIRA
   https://issues.apache.org/jira/browse/HDDS-12707
   
   ## How was this patch tested?
   Tested using existing junit test cases and integration tests as well as manually using local docker cluster.
   
   ```
   2025-03-26 13:08:39 2025-03-26 07:38:39,225 [Recon-SyncOM-0] INFO impl.OzoneManagerServiceProviderImpl: Last known sequence number before sync: 0
   2025-03-26 13:08:39 2025-03-26 07:38:39,226 [Recon-SyncOM-0] INFO impl.OzoneManagerServiceProviderImpl: Seq number of Recon's OM DB : 0
   2025-03-26 13:08:39 2025-03-26 07:38:39,226 [Recon-SyncOM-0] INFO impl.OzoneManagerServiceProviderImpl: Obtaining full snapshot from Ozone Manager
   2025-03-26 13:08:39 2025-03-26 07:38:39,236 [Recon-SyncOM-0] INFO impl.OzoneManagerServiceProviderImpl: Permissions for Recon DB directory '/data/metadata/recon' meet the minimum required permissions '750'
   2025-03-26 13:08:39 2025-03-26 07:38:39,521 [Recon-SyncOM-0] INFO impl.OzoneManagerServiceProviderImpl: Enqueued file: 000057.sst
   2025-03-26 13:08:39 2025-03-26 07:38:39,521 [pool-33-thread-1] INFO impl.OzoneManagerServiceProviderImpl: Dequeued file: 000057.sst
   2025-03-26 13:08:39 2025-03-26 07:38:39,522 [Recon-SyncOM-0] INFO impl.OzoneManagerServiceProviderImpl: Enqueued file: 000063.sst
   2025-03-26 13:08:39 2025-03-26 07:38:39,522 [pool-33-thread-2] INFO impl.OzoneManagerServiceProviderImpl: Dequeued file: 000063.sst
   2025-03-26 13:08:39 2025-03-26 07:38:39,522 [Recon-SyncOM-0] INFO impl.OzoneManagerServiceProviderImpl: Enqueued file: 000061.sst
   2025-03-26 13:08:39 2025-03-26 07:38:39,522 [pool-33-thread-3] INFO impl.OzoneManagerServiceProviderImpl: Dequeued file: 000061.sst
   2025-03-26 13:08:39 2025-03-26 07:38:39,522 [Recon-SyncOM-0] INFO impl.OzoneManagerServiceProviderImpl: Enqueued file: 000059.sst
   2025-03-26 13:08:39 2025-03-26 07:38:39,523 [pool-33-thread-4] INFO impl.OzoneManagerServiceProviderImpl: Dequeued file: 000059.sst
   2025-03-26 13:08:39 2025-03-26 07:38:39,523 [Recon-SyncOM-0] INFO impl.OzoneManagerServiceProviderImpl: Enqueued file: 000056.sst
   2025-03-26 13:08:39 2025-03-26 07:38:39,523 [pool-33-thread-1] INFO impl.OzoneManagerServiceProviderImpl: Dequeued file: 000056.sst
   2025-03-26 13:08:39 2025-03-26 07:38:39,524 [Recon-SyncOM-0] INFO impl.OzoneManagerServiceProviderImpl: Enqueued file: 000062.sst
   2025-03-26 13:08:39 2025-03-26 07:38:39,524 [pool-33-thread-2] INFO impl.OzoneManagerServiceProviderImpl: Dequeued file: 000062.sst
   2025-03-26 13:08:39 2025-03-26 07:38:39,524 [Recon-SyncOM-0] INFO impl.OzoneManagerServiceProviderImpl: Enqueued file: 000053.sst
   2025-03-26 13:08:39 2025-03-26 07:38:39,524 [pool-33-thread-3] INFO impl.OzoneManagerServiceProviderImpl: Dequeued file: 000053.sst
   2025-03-26 13:08:39 2025-03-26 07:38:39,524 [Recon-SyncOM-0] INFO impl.OzoneManagerServiceProviderImpl: Enqueued file: 000064.sst
   2025-03-26 13:08:39 2025-03-26 07:38:39,524 [pool-33-thread-4] INFO impl.OzoneManagerServiceProviderImpl: Dequeued file: 000064.sst
   2025-03-26 13:08:39 2025-03-26 07:38:39,525 [Recon-SyncOM-0] INFO impl.OzoneManagerServiceProviderImpl: Enqueued file: 000054.sst
   2025-03-26 13:08:39 2025-03-26 07:38:39,525 [pool-33-thread-1] INFO impl.OzoneManagerServiceProviderImpl: Dequeued file: 000054.sst
   2025-03-26 13:08:39 2025-03-26 07:38:39,525 [Recon-SyncOM-0] INFO impl.OzoneManagerServiceProviderImpl: Enqueued file: CURRENT
   2025-03-26 13:08:39 2025-03-26 07:38:39,525 [pool-33-thread-2] INFO impl.OzoneManagerServiceProviderImpl: Dequeued file: CURRENT
   2025-03-26 13:08:39 2025-03-26 07:38:39,525 [Recon-SyncOM-0] INFO impl.OzoneManagerServiceProviderImpl: Enqueued file: MANIFEST-000005
   2025-03-26 13:08:39 2025-03-26 07:38:39,525 [pool-33-thread-3] INFO impl.OzoneManagerServiceProviderImpl: Dequeued file: MANIFEST-000005
   2025-03-26 13:08:39 2025-03-26 07:38:39,526 [Recon-SyncOM-0] INFO impl.OzoneManagerServiceProviderImpl: Enqueued file: 000060.sst
   2025-03-26 13:08:39 2025-03-26 07:38:39,526 [pool-33-thread-4] INFO impl.OzoneManagerServiceProviderImpl: Dequeued file: 000060.sst
   2025-03-26 13:08:39 2025-03-26 07:38:39,526 [Recon-SyncOM-0] INFO impl.OzoneManagerServiceProviderImpl: Enqueued file: 000058.sst
   2025-03-26 13:08:39 2025-03-26 07:38:39,526 [pool-33-thread-1] INFO impl.OzoneManagerServiceProviderImpl: Dequeued file: 000058.sst
   2025-03-26 13:08:39 2025-03-26 07:38:39,528 [Recon-SyncOM-0] INFO impl.OzoneManagerServiceProviderImpl: Enqueued file: OPTIONS-000051
   2025-03-26 13:08:39 2025-03-26 07:38:39,528 [pool-33-thread-2] INFO impl.OzoneManagerServiceProviderImpl: Dequeued file: OPTIONS-000051
   2025-03-26 13:08:39 2025-03-26 07:38:39,529 [Recon-SyncOM-0] INFO impl.OzoneManagerServiceProviderImpl: Enqueued file: OZONE_RATIS_SNAPSHOT_COMPLETE
   2025-03-26 13:08:39 2025-03-26 07:38:39,529 [pool-33-thread-3] INFO impl.OzoneManagerServiceProviderImpl: Dequeued file: OZONE_RATIS_SNAPSHOT_COMPLETE
   2025-03-26 13:08:39 2025-03-26 07:38:39,529 [pool-33-thread-4] INFO impl.OzoneManagerServiceProviderImpl: Dequeued file: null
   2025-03-26 13:08:39 2025-03-26 07:38:39,529 [pool-33-thread-1] INFO impl.OzoneManagerServiceProviderImpl: Dequeued file: null
   2025-03-26 13:08:39 2025-03-26 07:38:39,529 [pool-33-thread-3] INFO impl.OzoneManagerServiceProviderImpl: Dequeued file: null
   2025-03-26 13:08:39 2025-03-26 07:38:39,529 [pool-33-thread-2] INFO impl.OzoneManagerServiceProviderImpl: Dequeued file: null
   2025-03-26 13:08:39 2025-03-26 07:38:39,529 [Recon-SyncOM-0] INFO recon.ReconContext: Update healthStatus of Recon from true to true.
   2025-03-26 13:08:39 2025-03-26 07:38:39,530 [Recon-SyncOM-0] INFO impl.OzoneManagerServiceProviderImpl: Attempting to update Recon OM DB with new snapshot located at: /data/metadata/om.snapshot.db_1742974719236
   2025-03-26 13:08:39 2025-03-26 07:38:39,576 [Recon-SyncOM-0] INFO recovery.ReconOmMetadataManagerImpl: Created OM DB handle from snapshot at /data/metadata/om.snapshot.db_1742974719236.
   2025-03-26 13:08:39 2025-03-26 07:38:39,586 [Recon-SyncOM-0] INFO impl.OzoneManagerServiceProviderImpl: Successfully updated Recon OM DB with new snapshot.
   2025-03-26 13:08:39 2025-03-26 07:38:39,589 [Recon-SyncOM-0] INFO impl.OzoneManagerServiceProviderImpl: Calling reprocess on Recon tasks.
   2025-03-26 13:08:39 2025-03-26 07:38:39,609 [ReconTaskThread-0] INFO impl.ReconContainerMetadataManagerImpl: KEY_CONTAINER Table is empty, initializing from CONTAINER_KEY Table ...
   2025-03-26 13:08:39 2025-03-26 07:38:39,609 [ReconTaskThread-0] INFO impl.ReconContainerMetadataManagerImpl: It took 0.0 seconds to initialized 0 records to KEY_CONTAINER table
   2025-03-26 13:08:39 2025-03-26 07:38:39,737 [ReconTaskThread-0] INFO tasks.FileSizeCountTaskHelper: Starting Reprocess for FileSizeCountTaskOBS
   2025-03-26 13:08:39 2025-03-26 07:38:39,745 [ReconTaskThread-0] INFO tasks.FileSizeCountTaskHelper: Deleted 5 records from "FILE_COUNT_BY_SIZE"
   2025-03-26 13:08:39 2025-03-26 07:38:39,747 [ReconTaskThread-0] INFO tasks.FileSizeCountTaskHelper: Reprocessed 18 keys for bucket layout OBJECT_STORE.
   2025-03-26 13:08:39 2025-03-26 07:38:39,773 [ReconTaskThread-0] INFO tasks.FileSizeCountTaskHelper: FileSizeCountTaskOBS completed Reprocess in 36 ms.
   2025-03-26 13:08:39 2025-03-26 07:38:39,776 [ReconTaskThread-0] INFO tasks.FileSizeCountTaskHelper: Starting Reprocess for FileSizeCountTaskFSO
   2025-03-26 13:08:39 2025-03-26 07:38:39,776 [ReconTaskThread-0] INFO tasks.FileSizeCountTaskHelper: Table already truncated by another task; waiting for truncation to complete.
   2025-03-26 13:08:39 2025-03-26 07:38:39,777 [ReconTaskThread-0] INFO tasks.FileSizeCountTaskHelper: Reprocessed 6 keys for bucket layout FILE_SYSTEM_OPTIMIZED.
   2025-03-26 13:08:39 2025-03-26 07:38:39,799 [ReconTaskThread-0] INFO tasks.FileSizeCountTaskHelper: FileSizeCountTaskFSO completed Reprocess in 23 ms.
   2025-03-26 13:08:39 2025-03-26 07:38:39,802 [Recon-SyncOM-0] INFO recon.ReconContext: Update healthStatus of Recon from true to true.
   2025-03-26 13:08:39 2025-03-26 07:38:39,802 [Recon-SyncOM-0] INFO impl.OzoneManagerServiceProviderImpl: Sequence number after sync: 301
   2025-03-26 13:09:10 2025-03-26 07:39:10,214 [qtp1063823352-189] WARN conf.TimeDurationUtil: No unit for hdds.scmclient.rpc.timeout(60000) assuming MILLISECONDS
   2025-03-26 13:09:10 2025-03-26 07:39:10,214 [qtp1063823352-189] WARN conf.TimeDurationUtil: No unit for hdds.scmclient.max.retry.timeout(6000) assuming MILLISECONDS
   2025-03-26 13:09:10 2025-03-26 07:39:10,214 [qtp1063823352-189] INFO proxy.SCMContainerLocationFailoverProxyProvider: Created fail-over proxy for protocol StorageContainerLocationProtocolPB with 1 nodes: [nodeId=scmNodeId,nodeAddress=scm/172.18.0.3:9860]
   2025-03-26 13:09:39 2025-03-26 07:39:39,802 [Recon-SyncOM-0] INFO impl.OzoneManagerServiceProviderImpl: Last known sequence number before sync: 301
   2025-03-26 13:09:39 2025-03-26 07:39:39,804 [Recon-SyncOM-0] INFO impl.OzoneManagerServiceProviderImpl: Seq number of Recon's OM DB : 301
   2025-03-26 13:09:39 2025-03-26 07:39:39,824 [Recon-SyncOM-0] INFO impl.OzoneManagerServiceProviderImpl: From Sequence Number:301, Recon DB Sequence Number: 301, Number of updates received from OM : 0, SequenceNumber diff: 0, SequenceNumber Lag from OM 0, isDBUpdateSuccess: true
   2025-03-26 13:09:39 2025-03-26 07:39:39,829 [Recon-SyncOM-0] INFO impl.OzoneManagerServiceProviderImpl: Delta updates received from OM : 1 loops, 0 records
   2025-03-26 13:09:39 2025-03-26 07:39:39,829 [Recon-SyncOM-0] INFO impl.OzoneManagerServiceProviderImpl: Sequence number after sync: 301
   ```
   ![image.png](attachment:bd06ccd8-456a-4037-b0fa-035b86daab22:image.png)
   
   ![image.png](attachment:1ea0e09f-0bdd-49a5-8a3b-a2e666c3d057:image.png)


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org
For additional commands, e-mail: issues-help@ozone.apache.org


Re: [PR] HDDS-12707. Recon - In-memory extraction of om tarball from network input stream [ozone]

Posted by "devmadhuu (via GitHub)" <gi...@apache.org>.
devmadhuu commented on code in PR #8212:
URL: https://github.com/apache/ozone/pull/8212#discussion_r2028089172


##########
hadoop-ozone/recon/src/main/java/org/apache/hadoop/ozone/recon/spi/impl/OzoneManagerServiceProviderImpl.java:
##########
@@ -426,14 +430,17 @@ connectionFactory, getOzoneManagerSnapshotUrl(),
       // RocksDB.
       reconContext.updateHealthStatus(new AtomicBoolean(true));
       reconContext.getErrors().remove(ReconContext.ErrorCode.GET_OM_DB_SNAPSHOT_FAILED);
+
       return new RocksDBCheckpoint(untarredDbDir);
+
     } catch (IOException e) {
-      LOG.error("Unable to obtain Ozone Manager DB Snapshot. ", e);
+      LOG.error("Unable to obtain Ozone Manager DB Snapshot.", e);
       reconContext.updateHealthStatus(new AtomicBoolean(false));
       reconContext.updateErrors(ReconContext.ErrorCode.GET_OM_DB_SNAPSHOT_FAILED);
     } finally {
-      FileUtils.deleteQuietly(targetFile);
+      tarExtractor.shutdown();

Review Comment:
   Thanks @adoroszlai for your review. Good catch. Fixed and pushed the change.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org
For additional commands, e-mail: issues-help@ozone.apache.org


Re: [PR] HDDS-12707. Recon - In-memory extraction of om tarball from network input stream [ozone]

Posted by "sumitagrawl (via GitHub)" <gi...@apache.org>.
sumitagrawl merged PR #8212:
URL: https://github.com/apache/ozone/pull/8212


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org
For additional commands, e-mail: issues-help@ozone.apache.org


Re: [PR] HDDS-12707. Recon - In-memory extraction of om tarball from network input stream [ozone]

Posted by "devmadhuu (via GitHub)" <gi...@apache.org>.
devmadhuu commented on code in PR #8212:
URL: https://github.com/apache/ozone/pull/8212#discussion_r2055319991


##########
hadoop-ozone/recon/src/main/java/org/apache/hadoop/ozone/recon/TarExtractor.java:
##########
@@ -0,0 +1,181 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.hadoop.ozone.recon;
+
+import static org.apache.hadoop.ozone.recon.ReconConstants.STAGING;
+
+import com.google.common.util.concurrent.ThreadFactoryBuilder;
+import java.io.ByteArrayInputStream;
+import java.io.ByteArrayOutputStream;
+import java.io.File;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.StandardCopyOption;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.UUID;
+import java.util.concurrent.ExecutionException;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Future;
+import java.util.concurrent.LinkedBlockingQueue;
+import java.util.concurrent.ThreadFactory;
+import java.util.concurrent.ThreadPoolExecutor;
+import java.util.concurrent.TimeUnit;
+import org.apache.commons.compress.archivers.tar.TarArchiveEntry;
+import org.apache.commons.compress.archivers.tar.TarArchiveInputStream;
+import org.apache.commons.io.FileUtils;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * Utility class for extracting files from a TAR archive using a multi-threaded approach.
+ *
+ * <p>This class utilizes an {@link ExecutorService} to extract files concurrently,
+ * improving performance when handling large TAR archives.</p>
+ *
+ * <p>Usage:</p>
+ * <pre>
+ * {@code
+ * TarExtractor tarExtractor = new TarExtractor(10, "extractor-thread");
+ * tarExtractor.extractTar(inputStream, outputPath);
+ * tarExtractor.shutdown();
+ * }
+ * </pre>
+ */
+public class TarExtractor {
+  private static final Logger LOG =
+      LoggerFactory.getLogger(TarExtractor.class);
+
+  private int threadPoolSize;
+  private ExecutorService executor;
+  private ThreadFactory threadFactory;
+
+  public TarExtractor(int threadPoolSize, String threadNamePrefix) {
+    this.threadPoolSize = threadPoolSize;
+    this.threadFactory =
+        new ThreadFactoryBuilder().setNameFormat("FetchOMDBTar-%d" + threadNamePrefix)
+            .build();
+    start();

Review Comment:
   No, I have removed and handled in different way now.



##########
hadoop-ozone/recon/src/main/java/org/apache/hadoop/ozone/recon/TarExtractor.java:
##########
@@ -0,0 +1,181 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.hadoop.ozone.recon;
+
+import static org.apache.hadoop.ozone.recon.ReconConstants.STAGING;
+
+import com.google.common.util.concurrent.ThreadFactoryBuilder;
+import java.io.ByteArrayInputStream;
+import java.io.ByteArrayOutputStream;
+import java.io.File;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.StandardCopyOption;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.UUID;
+import java.util.concurrent.ExecutionException;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Future;
+import java.util.concurrent.LinkedBlockingQueue;
+import java.util.concurrent.ThreadFactory;
+import java.util.concurrent.ThreadPoolExecutor;
+import java.util.concurrent.TimeUnit;
+import org.apache.commons.compress.archivers.tar.TarArchiveEntry;
+import org.apache.commons.compress.archivers.tar.TarArchiveInputStream;
+import org.apache.commons.io.FileUtils;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * Utility class for extracting files from a TAR archive using a multi-threaded approach.
+ *
+ * <p>This class utilizes an {@link ExecutorService} to extract files concurrently,
+ * improving performance when handling large TAR archives.</p>
+ *
+ * <p>Usage:</p>
+ * <pre>
+ * {@code
+ * TarExtractor tarExtractor = new TarExtractor(10, "extractor-thread");
+ * tarExtractor.extractTar(inputStream, outputPath);
+ * tarExtractor.shutdown();
+ * }
+ * </pre>
+ */
+public class TarExtractor {
+  private static final Logger LOG =
+      LoggerFactory.getLogger(TarExtractor.class);
+
+  private int threadPoolSize;
+  private ExecutorService executor;
+  private ThreadFactory threadFactory;
+
+  public TarExtractor(int threadPoolSize, String threadNamePrefix) {
+    this.threadPoolSize = threadPoolSize;
+    this.threadFactory =
+        new ThreadFactoryBuilder().setNameFormat("FetchOMDBTar-%d" + threadNamePrefix)
+            .build();
+    start();
+  }
+
+  public void extractTar(InputStream tarStream, Path outputDir)
+      throws IOException, InterruptedException, ExecutionException {
+    String stagingDirName = STAGING + UUID.randomUUID();
+    Path parentDir = outputDir.getParent();
+    if (parentDir == null) {
+      parentDir = outputDir; // Handle null parent case
+    }
+    Path stagingDir = parentDir.resolve(stagingDirName);
+
+    Files.createDirectories(stagingDir); // Ensure staging directory exists
+
+    List<Future<Void>> futures = new ArrayList<>();
+
+    try (TarArchiveInputStream tarInput = new TarArchiveInputStream(tarStream)) {
+      TarArchiveEntry entry;
+      while ((entry = tarInput.getNextTarEntry()) != null) {
+        if (!entry.isDirectory()) {
+          byte[] fileData = readEntryData(tarInput, entry.getSize());
+
+          // Submit extraction as a task
+          TarArchiveEntry finalEntry = entry;
+          futures.add(executor.submit(() -> {
+            writeFile(stagingDir, finalEntry.getName(), fileData);
+            return null;
+          }));
+        } else {
+          File dir = new File(stagingDir.toFile(), entry.getName());
+          if (!dir.exists() && !dir.mkdirs()) {
+            throw new IOException("Failed to create directory: " + dir);
+          }
+        }
+      }
+    }
+
+    // Wait for all tasks to complete
+    for (Future<Void> future : futures) {
+      future.get();
+    }
+
+    // Move staging to outputDir atomically
+    if (Files.exists(outputDir)) {
+      FileUtils.deleteDirectory(outputDir.toFile()); // Clean old data
+    }
+    try {
+      Files.move(stagingDir, outputDir, StandardCopyOption.ATOMIC_MOVE, StandardCopyOption.REPLACE_EXISTING);
+    } catch (IOException e) {
+      LOG.warn("Atomic move of staging dir : {} to {} failed.", stagingDir, outputDir, e);
+    }
+
+    LOG.info("Tar extraction completed and moved from staging to: {}", outputDir);
+  }
+
+  private byte[] readEntryData(TarArchiveInputStream tarInput, long size) throws IOException {
+    ByteArrayOutputStream buffer = new ByteArrayOutputStream();
+    byte[] fileData = new byte[(int) size];
+    int bytesRead;
+    while (size > 0 && (bytesRead = tarInput.read(fileData, 0, (int) Math.min(fileData.length, size))) != -1) {
+      buffer.write(fileData, 0, bytesRead);
+      size -= bytesRead;
+    }
+    return buffer.toByteArray();
+  }
+
+  private void writeFile(Path outputDir, String fileName, byte[] fileData) {
+    try {
+      File outputFile = new File(outputDir.toFile(), fileName);
+      Path parentDir = outputFile.toPath().getParent();
+      if (parentDir != null && !Files.exists(parentDir)) {
+        Files.createDirectories(parentDir);
+      }
+
+      try (InputStream fis = new ByteArrayInputStream(fileData);
+           OutputStream fos = Files.newOutputStream(outputFile.toPath())) {
+        byte[] buffer = new byte[8192];  // Use a buffer for efficient reading/writing
+        int bytesRead;
+        while ((bytesRead = fis.read(buffer)) != -1) {
+          fos.write(buffer, 0, bytesRead);
+        }
+      }
+    } catch (IOException e) {
+      throw new RuntimeException("Error writing file: " + fileName, e);
+    }
+  }
+
+  public void start() {
+    this.executor =

Review Comment:
   Ok done.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org
For additional commands, e-mail: issues-help@ozone.apache.org


Re: [PR] HDDS-12707. Recon - In-memory extraction of om tarball from network input stream [ozone]

Posted by "sumitagrawl (via GitHub)" <gi...@apache.org>.
sumitagrawl commented on code in PR #8212:
URL: https://github.com/apache/ozone/pull/8212#discussion_r2023060095


##########
hadoop-ozone/recon/src/main/java/org/apache/hadoop/ozone/recon/spi/impl/OzoneManagerServiceProviderImpl.java:
##########
@@ -393,50 +418,176 @@ private boolean isOmSpnegoEnabled() {
    * @return DBCheckpoint instance.
    */
   @VisibleForTesting
-  DBCheckpoint getOzoneManagerDBSnapshot() {
-    String snapshotFileName = RECON_OM_SNAPSHOT_DB + "_" +
-        System.currentTimeMillis();
-    File targetFile = new File(omSnapshotDBParentDir, snapshotFileName +
-        ".tar");
+  public DBCheckpoint getOzoneManagerDBSnapshot() {
+    String snapshotFileName = RECON_OM_SNAPSHOT_DB + "_" + System.currentTimeMillis();
+    Path untarredDbDir = Paths.get(omSnapshotDBParentDir.getAbsolutePath(), snapshotFileName);

Review Comment:
   extraction can be a temp path and after completion, to to final location, to avoid any partial db.



##########
hadoop-ozone/recon/src/main/java/org/apache/hadoop/ozone/recon/spi/impl/OzoneManagerServiceProviderImpl.java:
##########
@@ -220,6 +236,13 @@ public OzoneManagerServiceProviderImpl(
     this.threadFactory =
         new ThreadFactoryBuilder().setNameFormat(threadNamePrefix + "SyncOM-%d")
             .build();
+    this.omDBTarProcessorThreadCount = Runtime.getRuntime().availableProcessors();
+    // Create a custom ForkJoinWorkerThreadFactory to name threads
+    this.fetchOMDBThreadFactory = pool -> {
+      ForkJoinWorkerThread worker = ForkJoinPool.defaultForkJoinWorkerThreadFactory.newThread(pool);
+      worker.setName("FetchOMDBTar-" + threadNamePrefix + "-" + worker.getPoolIndex());
+      return worker;

Review Comment:
   this can be separate utility class.



##########
hadoop-ozone/recon/src/main/java/org/apache/hadoop/ozone/recon/TarExtractor.java:
##########
@@ -0,0 +1,181 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.hadoop.ozone.recon;
+
+import static org.apache.hadoop.ozone.recon.ReconConstants.STAGING;
+
+import com.google.common.util.concurrent.ThreadFactoryBuilder;
+import java.io.ByteArrayInputStream;
+import java.io.ByteArrayOutputStream;
+import java.io.File;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.StandardCopyOption;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.UUID;
+import java.util.concurrent.ExecutionException;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Future;
+import java.util.concurrent.LinkedBlockingQueue;
+import java.util.concurrent.ThreadFactory;
+import java.util.concurrent.ThreadPoolExecutor;
+import java.util.concurrent.TimeUnit;
+import org.apache.commons.compress.archivers.tar.TarArchiveEntry;
+import org.apache.commons.compress.archivers.tar.TarArchiveInputStream;
+import org.apache.commons.io.FileUtils;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * Utility class for extracting files from a TAR archive using a multi-threaded approach.
+ *
+ * <p>This class utilizes an {@link ExecutorService} to extract files concurrently,
+ * improving performance when handling large TAR archives.</p>
+ *
+ * <p>Usage:</p>
+ * <pre>
+ * {@code
+ * TarExtractor tarExtractor = new TarExtractor(10, "extractor-thread");
+ * tarExtractor.extractTar(inputStream, outputPath);
+ * tarExtractor.shutdown();
+ * }
+ * </pre>
+ */
+public class TarExtractor {
+  private static final Logger LOG =
+      LoggerFactory.getLogger(TarExtractor.class);
+
+  private int threadPoolSize;
+  private ExecutorService executor;
+  private ThreadFactory threadFactory;
+
+  public TarExtractor(int threadPoolSize, String threadNamePrefix) {
+    this.threadPoolSize = threadPoolSize;
+    this.threadFactory =
+        new ThreadFactoryBuilder().setNameFormat("FetchOMDBTar-%d" + threadNamePrefix)
+            .build();
+    start();

Review Comment:
   do we need start() in constructor?



##########
hadoop-ozone/recon/src/main/java/org/apache/hadoop/ozone/recon/spi/impl/OzoneManagerServiceProviderImpl.java:
##########
@@ -220,6 +236,13 @@ public OzoneManagerServiceProviderImpl(
     this.threadFactory =
         new ThreadFactoryBuilder().setNameFormat(threadNamePrefix + "SyncOM-%d")
             .build();
+    this.omDBTarProcessorThreadCount = Runtime.getRuntime().availableProcessors();
+    // Create a custom ForkJoinWorkerThreadFactory to name threads
+    this.fetchOMDBThreadFactory = pool -> {
+      ForkJoinWorkerThread worker = ForkJoinPool.defaultForkJoinWorkerThreadFactory.newThread(pool);

Review Comment:
   can use ExecutorService with pool configuration like default 64, with initial core pool: 0
   And each file extraction and write to location can be a task submitted to pool



##########
hadoop-ozone/recon/src/main/java/org/apache/hadoop/ozone/recon/spi/impl/OzoneManagerServiceProviderImpl.java:
##########
@@ -393,50 +418,176 @@ private boolean isOmSpnegoEnabled() {
    * @return DBCheckpoint instance.
    */
   @VisibleForTesting
-  DBCheckpoint getOzoneManagerDBSnapshot() {
-    String snapshotFileName = RECON_OM_SNAPSHOT_DB + "_" +
-        System.currentTimeMillis();
-    File targetFile = new File(omSnapshotDBParentDir, snapshotFileName +
-        ".tar");
+  public DBCheckpoint getOzoneManagerDBSnapshot() {
+    String snapshotFileName = RECON_OM_SNAPSHOT_DB + "_" + System.currentTimeMillis();
+    Path untarredDbDir = Paths.get(omSnapshotDBParentDir.getAbsolutePath(), snapshotFileName);
+
+    BlockingQueue<TarEntryData> queue = new LinkedBlockingQueue<>(omDBTarProcessorThreadCount * 10);
+
+    List<Future<Void>> futures = new ArrayList<>();
+
     try {
       SecurityUtil.doAsLoginUser(() -> {
         try (InputStream inputStream = reconUtils.makeHttpCall(
-            connectionFactory, getOzoneManagerSnapshotUrl(),
-            isOmSpnegoEnabled()).getInputStream()) {
-          FileUtils.copyInputStreamToFile(inputStream, targetFile);
+            connectionFactory, getOzoneManagerSnapshotUrl(), isOmSpnegoEnabled()).getInputStream();
+             TarArchiveInputStream tarInput = new TarArchiveInputStream(inputStream)) {
+
+          // Start worker threads (Consumers)
+          for (int i = 0; i < omDBTarProcessorThreadCount; i++) {

Review Comment:
   We can do additional test if connection is broken in middle, for the impact as error. 



##########
hadoop-ozone/recon/src/main/java/org/apache/hadoop/ozone/recon/spi/impl/OzoneManagerServiceProviderImpl.java:
##########
@@ -393,50 +418,176 @@ private boolean isOmSpnegoEnabled() {
    * @return DBCheckpoint instance.
    */
   @VisibleForTesting
-  DBCheckpoint getOzoneManagerDBSnapshot() {
-    String snapshotFileName = RECON_OM_SNAPSHOT_DB + "_" +
-        System.currentTimeMillis();
-    File targetFile = new File(omSnapshotDBParentDir, snapshotFileName +
-        ".tar");
+  public DBCheckpoint getOzoneManagerDBSnapshot() {
+    String snapshotFileName = RECON_OM_SNAPSHOT_DB + "_" + System.currentTimeMillis();
+    Path untarredDbDir = Paths.get(omSnapshotDBParentDir.getAbsolutePath(), snapshotFileName);
+
+    BlockingQueue<TarEntryData> queue = new LinkedBlockingQueue<>(omDBTarProcessorThreadCount * 10);
+
+    List<Future<Void>> futures = new ArrayList<>();
+
     try {
       SecurityUtil.doAsLoginUser(() -> {
         try (InputStream inputStream = reconUtils.makeHttpCall(
-            connectionFactory, getOzoneManagerSnapshotUrl(),
-            isOmSpnegoEnabled()).getInputStream()) {
-          FileUtils.copyInputStreamToFile(inputStream, targetFile);
+            connectionFactory, getOzoneManagerSnapshotUrl(), isOmSpnegoEnabled()).getInputStream();
+             TarArchiveInputStream tarInput = new TarArchiveInputStream(inputStream)) {

Review Comment:
   check use of try-with-resource to close stream.



##########
hadoop-ozone/recon/src/main/java/org/apache/hadoop/ozone/recon/TarExtractor.java:
##########
@@ -0,0 +1,181 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.hadoop.ozone.recon;
+
+import static org.apache.hadoop.ozone.recon.ReconConstants.STAGING;
+
+import com.google.common.util.concurrent.ThreadFactoryBuilder;
+import java.io.ByteArrayInputStream;
+import java.io.ByteArrayOutputStream;
+import java.io.File;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.StandardCopyOption;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.UUID;
+import java.util.concurrent.ExecutionException;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Future;
+import java.util.concurrent.LinkedBlockingQueue;
+import java.util.concurrent.ThreadFactory;
+import java.util.concurrent.ThreadPoolExecutor;
+import java.util.concurrent.TimeUnit;
+import org.apache.commons.compress.archivers.tar.TarArchiveEntry;
+import org.apache.commons.compress.archivers.tar.TarArchiveInputStream;
+import org.apache.commons.io.FileUtils;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * Utility class for extracting files from a TAR archive using a multi-threaded approach.
+ *
+ * <p>This class utilizes an {@link ExecutorService} to extract files concurrently,
+ * improving performance when handling large TAR archives.</p>
+ *
+ * <p>Usage:</p>
+ * <pre>
+ * {@code
+ * TarExtractor tarExtractor = new TarExtractor(10, "extractor-thread");
+ * tarExtractor.extractTar(inputStream, outputPath);
+ * tarExtractor.shutdown();
+ * }
+ * </pre>
+ */
+public class TarExtractor {
+  private static final Logger LOG =
+      LoggerFactory.getLogger(TarExtractor.class);
+
+  private int threadPoolSize;
+  private ExecutorService executor;
+  private ThreadFactory threadFactory;
+
+  public TarExtractor(int threadPoolSize, String threadNamePrefix) {
+    this.threadPoolSize = threadPoolSize;
+    this.threadFactory =
+        new ThreadFactoryBuilder().setNameFormat("FetchOMDBTar-%d" + threadNamePrefix)
+            .build();
+    start();
+  }
+
+  public void extractTar(InputStream tarStream, Path outputDir)
+      throws IOException, InterruptedException, ExecutionException {
+    String stagingDirName = STAGING + UUID.randomUUID();
+    Path parentDir = outputDir.getParent();
+    if (parentDir == null) {
+      parentDir = outputDir; // Handle null parent case
+    }
+    Path stagingDir = parentDir.resolve(stagingDirName);
+
+    Files.createDirectories(stagingDir); // Ensure staging directory exists
+
+    List<Future<Void>> futures = new ArrayList<>();
+
+    try (TarArchiveInputStream tarInput = new TarArchiveInputStream(tarStream)) {
+      TarArchiveEntry entry;
+      while ((entry = tarInput.getNextTarEntry()) != null) {
+        if (!entry.isDirectory()) {
+          byte[] fileData = readEntryData(tarInput, entry.getSize());
+
+          // Submit extraction as a task
+          TarArchiveEntry finalEntry = entry;
+          futures.add(executor.submit(() -> {
+            writeFile(stagingDir, finalEntry.getName(), fileData);
+            return null;
+          }));
+        } else {
+          File dir = new File(stagingDir.toFile(), entry.getName());
+          if (!dir.exists() && !dir.mkdirs()) {
+            throw new IOException("Failed to create directory: " + dir);
+          }
+        }
+      }
+    }
+
+    // Wait for all tasks to complete
+    for (Future<Void> future : futures) {
+      future.get();
+    }
+
+    // Move staging to outputDir atomically
+    if (Files.exists(outputDir)) {
+      FileUtils.deleteDirectory(outputDir.toFile()); // Clean old data
+    }
+    try {
+      Files.move(stagingDir, outputDir, StandardCopyOption.ATOMIC_MOVE, StandardCopyOption.REPLACE_EXISTING);
+    } catch (IOException e) {
+      LOG.warn("Atomic move of staging dir : {} to {} failed.", stagingDir, outputDir, e);
+    }
+
+    LOG.info("Tar extraction completed and moved from staging to: {}", outputDir);
+  }
+
+  private byte[] readEntryData(TarArchiveInputStream tarInput, long size) throws IOException {
+    ByteArrayOutputStream buffer = new ByteArrayOutputStream();
+    byte[] fileData = new byte[(int) size];
+    int bytesRead;
+    while (size > 0 && (bytesRead = tarInput.read(fileData, 0, (int) Math.min(fileData.length, size))) != -1) {
+      buffer.write(fileData, 0, bytesRead);
+      size -= bytesRead;
+    }
+    return buffer.toByteArray();
+  }
+
+  private void writeFile(Path outputDir, String fileName, byte[] fileData) {
+    try {
+      File outputFile = new File(outputDir.toFile(), fileName);
+      Path parentDir = outputFile.toPath().getParent();
+      if (parentDir != null && !Files.exists(parentDir)) {
+        Files.createDirectories(parentDir);
+      }
+
+      try (InputStream fis = new ByteArrayInputStream(fileData);
+           OutputStream fos = Files.newOutputStream(outputFile.toPath())) {
+        byte[] buffer = new byte[8192];  // Use a buffer for efficient reading/writing
+        int bytesRead;
+        while ((bytesRead = fis.read(buffer)) != -1) {
+          fos.write(buffer, 0, bytesRead);
+        }
+      }
+    } catch (IOException e) {
+      throw new RuntimeException("Error writing file: " + fileName, e);
+    }
+  }
+
+  public void start() {
+    this.executor =

Review Comment:
   start()/stop() can be safe from leaking the threads in threadpool



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org
For additional commands, e-mail: issues-help@ozone.apache.org


Re: [PR] HDDS-12707. Recon - In-memory extraction of om tarball from network input stream [ozone]

Posted by "adoroszlai (via GitHub)" <gi...@apache.org>.
adoroszlai commented on code in PR #8212:
URL: https://github.com/apache/ozone/pull/8212#discussion_r2027578098


##########
hadoop-ozone/recon/src/main/java/org/apache/hadoop/ozone/recon/spi/impl/OzoneManagerServiceProviderImpl.java:
##########
@@ -426,14 +430,17 @@ connectionFactory, getOzoneManagerSnapshotUrl(),
       // RocksDB.
       reconContext.updateHealthStatus(new AtomicBoolean(true));
       reconContext.getErrors().remove(ReconContext.ErrorCode.GET_OM_DB_SNAPSHOT_FAILED);
+
       return new RocksDBCheckpoint(untarredDbDir);
+
     } catch (IOException e) {
-      LOG.error("Unable to obtain Ozone Manager DB Snapshot. ", e);
+      LOG.error("Unable to obtain Ozone Manager DB Snapshot.", e);
       reconContext.updateHealthStatus(new AtomicBoolean(false));
       reconContext.updateErrors(ReconContext.ErrorCode.GET_OM_DB_SNAPSHOT_FAILED);
     } finally {
-      FileUtils.deleteQuietly(targetFile);
+      tarExtractor.shutdown();

Review Comment:
   `tarExtractor` should be shut down in `stop()`, not after getting a single DB snapshot, if you want to use it more than once.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org
For additional commands, e-mail: issues-help@ozone.apache.org