You are viewing a plain text version of this content. The canonical link for it is here.
Posted to issues@ozone.apache.org by GitBox <gi...@apache.org> on 2022/11/18 18:02:21 UTC

[GitHub] [ozone] GeorgeJahad opened a new pull request, #3980: HDDS-6961. Bootstrapping slow followers/new followers.

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

   
   ## What changes were proposed in this pull request?
   
   This PR updates the om follower bootstrap mechanism to include the snapshot state.
   
   It considers snapshot state to be all files under  *metadataDir/db.snapshots*.
   
   That includes the om snapshot directories, as well as the snapshot diff compaction logs and backup sst files, (which have been moved to the "db.snapshots" dir by this PR.)
   
   This PR adds the contents db.snapshots dir to the tarball sent to the follower.  To reduce the size of the tarball, it does not include multiple copies of any hard links found.  Instead, it includes a list of hard links to be generated by the follower.
   
   Design doc here: https://docs.google.com/document/d/1cFZj-7NRxiHaZ56ndcf1Z1EqapPFy4fo4dDVIy_aCx4/edit
   
   ### Recon
   Recon also uses the same tarball to initialize its copy of the OM rocksdb.  Since it doesn't need the snapshot data, I've added the "includeSnapshotData" parameter to the http request.
   
   ### Renamed OzoneManagerSnapshotProvider
   The ratis code uses the term "snapshot" to mean something other than what we mean.  It uses "snapshot" to refer to the tarball as a whole, (which now includes all of the individual "OM snapshots".)
   
   In particular, this class, in the "om/snapshot" directory is ambiguously named:
   ```
   org/apache/hadoop/ozone/om/snapshot/OzoneManagerSnapshotProvider.java
   ```
   To reduce potential confusion, I've renamed it to:
   ```
   org/apache/hadoop/ozone/om/ratis_snapshot/OmRatisSnapshotProvider.java
   ```
   
   
   ### Internal Consistency of Tarball
   There are two areas of consistency I've thought about:
   
   ##### Snapshot Info Table Entries -> Snapshot Directories
   There needs to be a directory for each snapshot info table entry.  These directories sometimes appear a short while after the snapshot info table entry is created.
   
   This PR addresses that by ensuring the directories exist before creating the tarball, (pausing for a few seconds if needed.)
   
   ##### Compaction Logs -> SST Files
    If the tarball is created during compaction, the snap diff compaction logs for the most recent compaction may not be included.  I'm not sure how bad a problem this is.  Please consider it in your review of this PR.
   
   ### Incremental checkpointing
   The addition of snapshot data will increase the size of the tarball, exacerbating the problem described here: https://issues.apache.org/jira/browse/HDDS-6510
   
   We'll need to decide if incremental checkpointing needs to a part of the initial snapshot release.  If not, it may need to come soon afterwards, otherwise users could be stranded.
   
   ## What is the link to the Apache JIRA
   
   https://issues.apache.org/jira/browse/HDDS-6961
   
   ## How was this patch tested?
   
   Unit/integration tests added
   


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


[GitHub] [ozone] prashantpogde commented on pull request #3980: HDDS-6961. [Snapshot] Bootstrapping slow followers/new followers.

Posted by "prashantpogde (via GitHub)" <gi...@apache.org>.
prashantpogde commented on PR #3980:
URL: https://github.com/apache/ozone/pull/3980#issuecomment-1489205087

   @GeorgeJahad Please fix the CI failure and I can merge the PR.


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


[GitHub] [ozone] GeorgeJahad commented on pull request #3980: HDDS-6961. [Snapshot] Bootstrapping slow followers/new followers.

Posted by "GeorgeJahad (via GitHub)" <gi...@apache.org>.
GeorgeJahad commented on PR #3980:
URL: https://github.com/apache/ozone/pull/3980#issuecomment-1478744509

   @smengcl @prashantpogde 
   I've updated the code based on your requests.  In a few cases, I've pushed the work off to two other PRS:
   
   Handle large tarballs in bootstrapping
   https://issues.apache.org/jira/browse/HDDS-8208
   
   Synchronize tarball creation with background processes
   https://issues.apache.org/jira/browse/HDDS-8209
   
   In one case I was unable to make the change Prashant requested.  I explain my reasoning here:  https://github.com/apache/ozone/pull/3980#discussion_r1144093843
   
   
   Please take a look when you can.
   
   Also, it looks like you need to start the CI workflow for me.
   
   


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


[GitHub] [ozone] prashantpogde commented on a diff in pull request #3980: HDDS-6961. [Snapshot] Bootstrapping slow followers/new followers.

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


##########
hadoop-ozone/ozone-manager/src/main/java/org/apache/hadoop/ozone/om/OMDBCheckpointServlet.java:
##########
@@ -82,4 +113,166 @@ public void init() throws ServletException {
         allowedGroups,
         om.isSpnegoEnabled());
   }
+
+  @Override
+  public void writeDbDataToStream(DBCheckpoint checkpoint,
+                                  HttpServletRequest request,
+                                  OutputStream destination)
+      throws IOException, InterruptedException {
+    // Map of inodes to path.
+    Map<Object, Path> copyFiles = new HashMap<>();
+    // Map of link to path.
+    Map<Path, Path> hardLinkFiles = new HashMap<>();
+
+    getFilesForArchive(checkpoint, copyFiles, hardLinkFiles,
+        includeSnapshotData(request));
+
+    try (TarArchiveOutputStream archiveOutputStream =
+            new TarArchiveOutputStream(destination)) {
+      archiveOutputStream
+          .setLongFileMode(TarArchiveOutputStream.LONGFILE_POSIX);
+      writeFilesToArchive(copyFiles, hardLinkFiles, archiveOutputStream);
+    }
+  }
+
+  private void getFilesForArchive(DBCheckpoint checkpoint,
+                                  Map<Object, Path> copyFiles,
+                                  Map<Path, Path> hardLinkFiles,
+                                  boolean includeSnapshotData)
+      throws IOException, InterruptedException {
+
+    // Get the active fs files.
+    Path dir = checkpoint.getCheckpointLocation();
+    processDir(dir, copyFiles, hardLinkFiles, new HashSet<>());
+
+    if (!includeSnapshotData) {
+      return;
+    }
+
+    // Get the snapshot files.
+    Set<Path> snapshotPaths = waitForSnapshotDirs(checkpoint);
+    Path snapshotDir = Paths.get(OMStorage.getOmDbDir(getConf()).toString(),
+        OM_SNAPSHOT_DIR);
+    processDir(snapshotDir, copyFiles, hardLinkFiles, snapshotPaths);
+  }
+
+  /**
+   * The snapshotInfo table may contain a snapshot that
+   * doesn't yet exist on the fs, so wait a few seconds for it.
+   * @param checkpoint Checkpoint containing snapshot entries expected.
+   * @return Set of expected snapshot dirs.
+   */
+  private Set<Path> waitForSnapshotDirs(DBCheckpoint checkpoint)
+      throws IOException, InterruptedException {
+
+    OzoneConfiguration conf = getConf();
+
+    Set<Path> snapshotPaths = new HashSet<>();
+
+    // get snapshotInfo entries
+    OmMetadataManagerImpl checkpointMetadataManager =
+        OmMetadataManagerImpl.createCheckpointMetadataManager(
+            conf, checkpoint);
+    try (TableIterator<String, ? extends Table.KeyValue<String, SnapshotInfo>>
+        iterator = checkpointMetadataManager
+        .getSnapshotInfoTable().iterator()) {

Review Comment:
   Do we need any synchronization with the garbage collection service here ? If we iterate over the snapshots that are in the process of deletion, we can get weired results here.



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


[GitHub] [ozone] smengcl commented on a diff in pull request #3980: HDDS-6961. [Snapshot] Bootstrapping slow followers/new followers.

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


##########
hadoop-ozone/ozone-manager/src/main/java/org/apache/hadoop/ozone/om/OmMetadataManagerImpl.java:
##########
@@ -328,13 +330,46 @@ protected OmMetadataManagerImpl() {
     this.omEpoch = 0;
   }
 
+  public static OmMetadataManagerImpl createCheckpointMetadataManager(
+      OzoneConfiguration conf, DBCheckpoint checkpoint) throws IOException {
+    Path path = checkpoint.getCheckpointLocation();
+    try {
+      Path parent = path.getParent();
+      File dir = parent.toFile();
+      String name = path.getFileName().toString();
+      return new OmMetadataManagerImpl(conf, dir, name);
+    // NPE check forced by findbugs NP_NULL_ON_SOME_PATH_FROM_RETURN_VALUE
+    } catch (NullPointerException e) {
+      throw new IOException("Invalid database: " +
+                            checkpoint.getCheckpointLocation());
+    }
+  }

Review Comment:
   ```suggestion
     public static OmMetadataManagerImpl createCheckpointMetadataManager(
         OzoneConfiguration conf, DBCheckpoint checkpoint) throws IOException {
       Path path = checkpoint.getCheckpointLocation();
       Path parent = path.getParent();
       if (parent == null) {
         throw new IllegalStateException("DB checkpoint parent path should not "
             + "have been null. Checkpoint path is " + path);
       }
       File dir = parent.toFile();
       Path name = path.getFileName();
       if (name == null) {
         throw new IllegalStateException("DB checkpoint dir name should not "
             + "have been null. Checkpoint path is " + path);
       }
       return new OmMetadataManagerImpl(conf, dir, name.toString());
     }
   ```



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


[GitHub] [ozone] GeorgeJahad commented on a diff in pull request #3980: HDDS-6961. [Snapshot] Bootstrapping slow followers/new followers.

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


##########
hadoop-hdds/framework/src/main/java/org/apache/hadoop/hdds/utils/DBCheckpointServlet.java:
##########
@@ -188,4 +189,11 @@ public void doGet(HttpServletRequest request, HttpServletResponse response) {
     }
   }
 
+  public void writeDbDataToStream(DBCheckpoint checkpoint,
+                                  HttpServletRequest ignoredRequest,

Review Comment:
   It's just a parameter that is used in the child class implementation but not in this parent class.  I'll add a java doc, unless you know of a better way to do 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: 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


[GitHub] [ozone] smengcl commented on a diff in pull request #3980: HDDS-6961. [Snapshot] Bootstrapping slow followers/new followers.

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


##########
hadoop-hdds/framework/src/main/java/org/apache/hadoop/hdds/utils/DBCheckpointServlet.java:
##########
@@ -188,4 +189,11 @@ public void doGet(HttpServletRequest request, HttpServletResponse response) {
     }
   }
 
+  public void writeDbDataToStream(DBCheckpoint checkpoint,
+                                  HttpServletRequest ignoredRequest,

Review Comment:
   Got it. A Javadoc would be nice. Thanks!



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


[GitHub] [ozone] hemantk-12 commented on a diff in pull request #3980: HDDS-6961. [Snapshot] Bootstrapping slow followers/new followers.

Posted by GitBox <gi...@apache.org>.
hemantk-12 commented on code in PR #3980:
URL: https://github.com/apache/ozone/pull/3980#discussion_r1034296160


##########
hadoop-ozone/ozone-manager/src/main/java/org/apache/hadoop/ozone/om/OzoneManager.java:
##########
@@ -3568,7 +3570,7 @@ private DBCheckpoint getDBCheckpointFromLeader(String leaderId) {
         "from the checkpoint.", leaderId);
 
     try {
-      return omSnapshotProvider.getOzoneManagerDBSnapshot(leaderId);
+      return omRatisSnapshotProvider.getOzoneManagerDBSnapshot(leaderId);

Review Comment:
   Sorry about wrong function name. Inside `installSnapshotFromLeader`, we have following line:
   
   ```
   DBCheckpoint omDBCheckpoint = getDBCheckpointFromLeader(leaderId);
   LOG.info("Downloaded checkpoint from Leader {} to the location {}",
       leaderId, omDBCheckpoint.getCheckpointLocation());
   ```
   
   It will throw NPE in log statement at `omDBCheckpoint.getCheckpointLocation()`, if `omDBCheckpoint` is null.



##########
hadoop-hdds/rocksdb-checkpoint-differ/src/main/java/org/apache/ozone/rocksdiff/RocksDBCheckpointDiffer.java:
##########
@@ -164,19 +164,19 @@ public RocksDBCheckpointDiffer(String metadataDir, String sstBackupDir,
     this.activeDBLocationStr = activeDBLocation.toString() + "/";
   }
 
-  private void setCompactionLogDir(String metadataDir,
+  private void setCompactionLogDir(String snapshotDiffDir,
       String compactionLogDirName) {
 
-    final File parentDir = new File(metadataDir);
+    final File parentDir = new File(snapshotDiffDir);
     if (!parentDir.exists()) {
-      if (!parentDir.mkdir()) {
+      if (!parentDir.mkdirs()) {
         LOG.error("Error creating compaction log parent dir.");
         return;
       }
     }
 
     this.compactionLogDir =
-        Paths.get(metadataDir, compactionLogDirName).toString();
+        Paths.get(parentDir.toString(), compactionLogDirName).toString();

Review Comment:
   I meant [File.getPath()](https://docs.oracle.com/javase/7/docs/api/java/io/File.html#getPath()). `File.toString()` internally calls `File.getPath()`.



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


[GitHub] [ozone] GeorgeJahad commented on a diff in pull request #3980: HDDS-6961. [Snapshot] Bootstrapping slow followers/new followers.

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


##########
hadoop-ozone/integration-test/src/test/java/org/apache/hadoop/ozone/om/TestOMDbCheckpointServlet.java:
##########
@@ -257,63 +291,271 @@ public void testSpnegoEnabled() throws Exception {
   }
 
   @Test
-  public void testWriteCheckpointToOutputStream() throws Exception {
+  public void testWriteDbDataToStream() throws Exception {
+    prepSnapshotData();
+    // Set http param to include snapshot data.
+    when(requestMock.getParameter(OZONE_DB_CHECKPOINT_INCLUDE_SNAPSHOT_DATA))
+        .thenReturn("true");
 
+    // Get the tarball.
+    try (FileOutputStream fileOutputStream = new FileOutputStream(tempFile)) {
+      omDbCheckpointServletMock.writeDbDataToStream(dbCheckpoint, requestMock,
+          fileOutputStream);
+    }
+
+    // Untar the file into a temp folder to be examined.
     String testDirName = folder.newFolder().getAbsolutePath();
-    File checkpoint = new File(testDirName, "checkpoint");
-    checkpoint.mkdir();
-    File file = new File(checkpoint, "temp1.txt");
-    OutputStreamWriter writer = new OutputStreamWriter(
-        new FileOutputStream(file), StandardCharsets.UTF_8);
-    writer.write("Test data 1");
-    writer.close();
-
-    file = new File(checkpoint, "/temp2.txt");
-    writer = new OutputStreamWriter(
-        new FileOutputStream(file), StandardCharsets.UTF_8);
-    writer.write("Test data 2");
-    writer.close();
-
-    File outputFile =
-        new File(Paths.get(testDirName, "output_file.tar").toString());
-    TestDBCheckpoint dbCheckpoint = new TestDBCheckpoint(
-        checkpoint.toPath());
-    writeDBCheckpointToStream(dbCheckpoint,
-        new FileOutputStream(outputFile));
-    assertNotNull(outputFile);
+    int testDirLength = testDirName.length() + 1;
+    String newDbDirName = testDirName + OM_KEY_PREFIX + OM_DB_NAME;
+    int newDbDirLength = newDbDirName.length() + 1;
+    File newDbDir = new File(newDbDirName);
+    newDbDir.mkdirs();
+    FileUtil.unTar(tempFile, newDbDir);
+
+    // Move snapshot dir to correct location.
+    new File(newDbDirName, OM_SNAPSHOT_DIR)
+        .renameTo(new File(newDbDir.getParent(), OM_SNAPSHOT_DIR));
+
+
+    // Confirm the checkpoint directories match, (after remove extras).
+    Path checkpointLocation = dbCheckpoint.getCheckpointLocation();
+    Set<String> initialCheckpointSet = getFiles(checkpointLocation,
+        checkpointLocation.toString().length() + 1);
+    Path finalCheckpointLocation = Paths.get(newDbDirName);
+    Set<String> finalCheckpointSet = getFiles(finalCheckpointLocation,
+        newDbDirLength);
+
+    Assert.assertTrue("hardlink file exists in checkpoint dir",
+        finalCheckpointSet.contains(OM_HARDLINK_FILE));
+    finalCheckpointSet.remove(OM_HARDLINK_FILE);
+    Assert.assertEquals(initialCheckpointSet, finalCheckpointSet);
+
+    int metaDirLength = metaDir.toString().length() + 1;
+    String shortSnapshotLocation =
+        truncateFileName(metaDirLength, Paths.get(snapshotDirName));
+    String shortSnapshotLocation2 =
+        truncateFileName(metaDirLength, Paths.get(snapshotDirName2));
+    String shortCompactionDirLocation =
+        truncateFileName(metaDirLength, compactionDirPath);
+
+    Set<String> finalFullSet =
+        getFiles(Paths.get(testDirName, OM_SNAPSHOT_DIR), testDirLength);
+
+    // Check each line in the hard link file.
+    Stream<String> lines = Files.lines(Paths.get(newDbDirName,
+        OM_HARDLINK_FILE));
+
+    List<String> fabricatedLinkLines = new ArrayList<>();
+    for (String line: lines.collect(Collectors.toList())) {
+      Assert.assertFalse("CURRENT file is not a hard link",
+          line.contains("CURRENT"));
+      if (line.contains("fabricatedFile")) {
+        fabricatedLinkLines.add(line);
+      } else {
+        checkLine(shortSnapshotLocation, shortSnapshotLocation2, line);
+        // add links to the final set
+        finalFullSet.add(line.split("\t")[0]);
+      }
+    }

Review Comment:
   will do, thanks!



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


[GitHub] [ozone] prashantpogde commented on a diff in pull request #3980: HDDS-6961. [Snapshot] Bootstrapping slow followers/new followers.

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


##########
hadoop-ozone/ozone-manager/src/main/java/org/apache/hadoop/ozone/om/OzoneManager.java:
##########
@@ -3568,7 +3570,7 @@ private DBCheckpoint getDBCheckpointFromLeader(String leaderId) {
         "from the checkpoint.", leaderId);
 
     try {
-      return omSnapshotProvider.getOzoneManagerDBSnapshot(leaderId);
+      return omRatisSnapshotProvider.getOzoneManagerDBSnapshot(leaderId);

Review Comment:
   +1



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


[GitHub] [ozone] GeorgeJahad commented on a diff in pull request #3980: HDDS-6961. [Snapshot] Bootstrapping slow followers/new followers.

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


##########
hadoop-ozone/integration-test/src/test/java/org/apache/hadoop/ozone/om/TestOMRatisSnapshots.java:
##########
@@ -227,6 +233,20 @@ public void testInstallSnapshot() throws Exception {
         getDefaultBucketLayout()).get(followerOMMetaMngr.getOzoneKey(
         volumeName, bucketName, newKeys.get(0))));
      */
+
+    // read back data from the OM snapshot
+    OmKeyArgs omKeyArgs = new OmKeyArgs.Builder()
+        .setVolumeName(volumeName)
+            .setBucketName(bucketName)
+                .setKeyName(".snapshot/snap1/" + keys.get(0)).build();
+    OmKeyInfo omKeyInfo = null;
+    try {
+      omKeyInfo = followerOM.lookupKey(omKeyArgs);
+    } catch (Exception e) {

Review Comment:
   removed catch



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


[GitHub] [ozone] GeorgeJahad commented on a diff in pull request #3980: HDDS-6961. [Snapshot] Bootstrapping slow followers/new followers.

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


##########
hadoop-ozone/integration-test/src/test/java/org/apache/hadoop/ozone/om/TestOMDbCheckpointServlet.java:
##########
@@ -257,63 +291,271 @@ public void testSpnegoEnabled() throws Exception {
   }
 
   @Test
-  public void testWriteCheckpointToOutputStream() throws Exception {
+  public void testWriteDbDataToStream() throws Exception {
+    prepSnapshotData();
+    // Set http param to include snapshot data.
+    when(requestMock.getParameter(OZONE_DB_CHECKPOINT_INCLUDE_SNAPSHOT_DATA))
+        .thenReturn("true");
 
+    // Get the tarball.
+    try (FileOutputStream fileOutputStream = new FileOutputStream(tempFile)) {
+      omDbCheckpointServletMock.writeDbDataToStream(dbCheckpoint, requestMock,
+          fileOutputStream);
+    }
+
+    // Untar the file into a temp folder to be examined.
     String testDirName = folder.newFolder().getAbsolutePath();
-    File checkpoint = new File(testDirName, "checkpoint");
-    checkpoint.mkdir();
-    File file = new File(checkpoint, "temp1.txt");
-    OutputStreamWriter writer = new OutputStreamWriter(
-        new FileOutputStream(file), StandardCharsets.UTF_8);
-    writer.write("Test data 1");
-    writer.close();
-
-    file = new File(checkpoint, "/temp2.txt");
-    writer = new OutputStreamWriter(
-        new FileOutputStream(file), StandardCharsets.UTF_8);
-    writer.write("Test data 2");
-    writer.close();
-
-    File outputFile =
-        new File(Paths.get(testDirName, "output_file.tar").toString());
-    TestDBCheckpoint dbCheckpoint = new TestDBCheckpoint(
-        checkpoint.toPath());
-    writeDBCheckpointToStream(dbCheckpoint,
-        new FileOutputStream(outputFile));
-    assertNotNull(outputFile);
+    int testDirLength = testDirName.length() + 1;
+    String newDbDirName = testDirName + OM_KEY_PREFIX + OM_DB_NAME;
+    int newDbDirLength = newDbDirName.length() + 1;
+    File newDbDir = new File(newDbDirName);
+    newDbDir.mkdirs();
+    FileUtil.unTar(tempFile, newDbDir);
+
+    // Move snapshot dir to correct location.
+    new File(newDbDirName, OM_SNAPSHOT_DIR)
+        .renameTo(new File(newDbDir.getParent(), OM_SNAPSHOT_DIR));
+
+
+    // Confirm the checkpoint directories match, (after remove extras).
+    Path checkpointLocation = dbCheckpoint.getCheckpointLocation();
+    Set<String> initialCheckpointSet = getFiles(checkpointLocation,
+        checkpointLocation.toString().length() + 1);
+    Path finalCheckpointLocation = Paths.get(newDbDirName);
+    Set<String> finalCheckpointSet = getFiles(finalCheckpointLocation,
+        newDbDirLength);
+
+    Assert.assertTrue("hardlink file exists in checkpoint dir",
+        finalCheckpointSet.contains(OM_HARDLINK_FILE));
+    finalCheckpointSet.remove(OM_HARDLINK_FILE);
+    Assert.assertEquals(initialCheckpointSet, finalCheckpointSet);
+
+    int metaDirLength = metaDir.toString().length() + 1;
+    String shortSnapshotLocation =
+        truncateFileName(metaDirLength, Paths.get(snapshotDirName));
+    String shortSnapshotLocation2 =
+        truncateFileName(metaDirLength, Paths.get(snapshotDirName2));
+    String shortCompactionDirLocation =
+        truncateFileName(metaDirLength, compactionDirPath);
+
+    Set<String> finalFullSet =
+        getFiles(Paths.get(testDirName, OM_SNAPSHOT_DIR), testDirLength);
+
+    // Check each line in the hard link file.
+    Stream<String> lines = Files.lines(Paths.get(newDbDirName,
+        OM_HARDLINK_FILE));
+
+    List<String> fabricatedLinkLines = new ArrayList<>();
+    for (String line: lines.collect(Collectors.toList())) {
+      Assert.assertFalse("CURRENT file is not a hard link",
+          line.contains("CURRENT"));
+      if (line.contains("fabricatedFile")) {
+        fabricatedLinkLines.add(line);
+      } else {
+        checkLine(shortSnapshotLocation, shortSnapshotLocation2, line);
+        // add links to the final set
+        finalFullSet.add(line.split("\t")[0]);
+      }
+    }
+
+    Set<String> directories = Sets.newHashSet(
+        shortSnapshotLocation, shortSnapshotLocation2,
+        shortCompactionDirLocation);
+    checkFabricatedLines(directories, fabricatedLinkLines, testDirName);
+
+    Set<String> initialFullSet =
+        getFiles(Paths.get(metaDir.toString(), OM_SNAPSHOT_DIR), metaDirLength);
+    Assert.assertEquals("found expected snapshot files",
+        initialFullSet, finalFullSet);

Review Comment:
   done



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

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

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


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


[GitHub] [ozone] GeorgeJahad commented on a diff in pull request #3980: HDDS-6961. [Snapshot] Bootstrapping slow followers/new followers.

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


##########
hadoop-ozone/ozone-manager/src/main/java/org/apache/hadoop/ozone/om/OMDBCheckpointServlet.java:
##########
@@ -82,4 +111,164 @@ public void init() throws ServletException {
         allowedGroups,
         om.isSpnegoEnabled());
   }
+
+  @Override
+  public void writeDbDataToStream(DBCheckpoint checkpoint,
+                                  HttpServletRequest request,
+                                  OutputStream destination)
+      throws IOException, InterruptedException {
+    // Map of inodes to path.
+    Map<Object, Path> copyFiles = new HashMap<>();
+    // Map of link to path.
+    Map<Path, Path> hardLinkFiles = new HashMap<>();
+
+    getFilesForArchive(checkpoint, copyFiles, hardLinkFiles,
+        includeSnapshotData(request));
+
+    try (TarArchiveOutputStream archiveOutputStream =
+            new TarArchiveOutputStream(destination)) {
+      archiveOutputStream
+          .setLongFileMode(TarArchiveOutputStream.LONGFILE_POSIX);
+      writeFilesToArchive(copyFiles, hardLinkFiles, archiveOutputStream);
+    }
+  }
+
+  private void getFilesForArchive(DBCheckpoint checkpoint,
+                                  Map<Object, Path> copyFiles,
+                                  Map<Path, Path> hardLinkFiles,
+                                  boolean includeSnapshotData)
+      throws IOException {
+
+    // Get the active fs files.
+    Path dir = checkpoint.getCheckpointLocation();
+    processDir(dir, copyFiles, hardLinkFiles, new HashSet<>());
+
+    if (!includeSnapshotData) {
+      return;
+    }
+
+    // Get the snapshot files.
+    Set<Path> snapshotPaths = waitForSnapshotDirs(checkpoint);
+    Path snapshotDir = Paths.get(OMStorage.getOmDbDir(getConf()).toString(),
+        OM_SNAPSHOT_DIR);
+    processDir(snapshotDir, copyFiles, hardLinkFiles, snapshotPaths);
+  }
+
+  /**
+   * The snapshotInfo table may contain a snapshot that
+   * doesn't yet exist on the fs, so wait a few seconds for it.
+   * @param checkpoint Checkpoint containing snapshot entries expected.
+   * @return Set of expected snapshot dirs.
+   */
+  private Set<Path> waitForSnapshotDirs(DBCheckpoint checkpoint)
+      throws IOException {
+
+    OzoneConfiguration conf = getConf();
+
+    Set<Path> snapshotPaths = new HashSet<>();
+
+    // get snapshotInfo entries
+    OmMetadataManagerImpl checkpointMetadataManager =
+        OmMetadataManagerImpl.createCheckpointMetadataManager(
+            conf, checkpoint);
+    try (TableIterator<String, ? extends Table.KeyValue<String, SnapshotInfo>>
+        iterator = checkpointMetadataManager
+        .getSnapshotInfoTable().iterator()) {
+
+      // For each entry, wait for corresponding directory.
+      while (iterator.hasNext()) {
+        Table.KeyValue<String, SnapshotInfo> entry = iterator.next();
+        Path path = Paths.get(getSnapshotPath(conf, entry.getValue()));
+        waitForDirToExist(path);
+        snapshotPaths.add(path);
+      }
+    }
+    return snapshotPaths;
+  }
+
+  private void waitForDirToExist(Path dir) throws IOException {
+    if (!RDBCheckpointManager.waitForCheckpointDirectoryExist(dir.toFile())) {

Review Comment:
   moved



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


[GitHub] [ozone] GeorgeJahad commented on a diff in pull request #3980: HDDS-6961. [Snapshot] Bootstrapping slow followers/new followers.

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


##########
hadoop-ozone/ozone-manager/src/main/java/org/apache/hadoop/ozone/om/OmSnapshotManager.java:
##########
@@ -279,6 +307,92 @@ private void verifySnapshotInfoForSnapDiff(final SnapshotInfo fromSnapshot,
     }
   }
 
+  /**
+   * Create file of links to add to tarball.
+   * Format of entries are either:
+   * dir1/fileTo fileFrom
+   *    for files in active db or:
+   * dir1/fileTo dir2/fileFrom
+   *    for files in another directory, (either another snapshot dir or
+   *    sst compaction backup directory)
+   * @param truncateLength - Length of initial path to trim in file path.
+   * @param hardLinkFiles - Map of link->file paths.
+   * @return Path to the file of links created.
+   */
+  @SuppressFBWarnings({"NP_NULL_ON_SOME_PATH_FROM_RETURN_VALUE"})
+  static Path createHardLinkList(int truncateLength,
+                                  Map<Path, Path> hardLinkFiles)
+      throws IOException {
+    Path data = Files.createTempFile("data", "txt");
+    StringBuilder sb = new StringBuilder();
+    for (Map.Entry<Path, Path> entry : hardLinkFiles.entrySet()) {
+      String fixedFile = truncateFileName(truncateLength, entry.getValue());
+      // If this file is from the active db, strip the path.
+      if (fixedFile.startsWith(OM_CHECKPOINT_DIR)) {
+        fixedFile = Paths.get(fixedFile).getFileName().toString();
+      }
+      sb.append(truncateFileName(truncateLength, entry.getKey()))

Review Comment:
   I spent some time trying to remove the truncateLength and the path stripping, but was unable to do so in any way that increased the clarity of the code.  It turns out that each serves an important purpose.
   
   The "truncate length" is required to remove the leader specific superdirectories from the path.  So for example it changes this path:
   ```
   /home/gbj/incoming/build-master/hadoop-ozone/integration-test/target/test-dir/MiniOzoneClusterImpl-967d81d4-9ebf-4d14-b384-7912f7535144/omNode-1/db.snapshots/checkpointState/om.db-fd5616df-4c39-47ad-a5d6-37d40fa378f2/CURRENT
   
   ```
   to a relative path for the destination
   ```
   db.snapshots/checkpointState/om.db-fd5616df-4c39-47ad-a5d6-37d40fa378f2/CURRENT
   ```
   
   This is necessary because there is no guarantee that the follower uses the same path to the db, (and in fact in the ha integration tests, all three nodes run on one machine so the path specifically is different between the different nodes.  So it must be truncated and replaced on the follower.)
   
   "Path stripping" refers to removing the path from the file to just leave the file name.  This is needed for the files in the active fs.  Those files come from the checkpoint directory on the leader, not from the directory leaders active fs.
   
   So both the truncateLength and path stripping are required in some form, and I wasn't able to come up with any simpler way.  So I just left them unchanged.
   



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


[GitHub] [ozone] GeorgeJahad commented on a diff in pull request #3980: HDDS-6961. [Snapshot] Bootstrapping slow followers/new followers.

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


##########
hadoop-ozone/ozone-manager/src/main/java/org/apache/hadoop/ozone/om/OMDBCheckpointServlet.java:
##########
@@ -82,4 +113,166 @@ public void init() throws ServletException {
         allowedGroups,
         om.isSpnegoEnabled());
   }
+
+  @Override
+  public void writeDbDataToStream(DBCheckpoint checkpoint,
+                                  HttpServletRequest request,
+                                  OutputStream destination)
+      throws IOException, InterruptedException {
+    // Map of inodes to path.
+    Map<Object, Path> copyFiles = new HashMap<>();
+    // Map of link to path.
+    Map<Path, Path> hardLinkFiles = new HashMap<>();
+
+    getFilesForArchive(checkpoint, copyFiles, hardLinkFiles,
+        includeSnapshotData(request));
+
+    try (TarArchiveOutputStream archiveOutputStream =
+            new TarArchiveOutputStream(destination)) {
+      archiveOutputStream
+          .setLongFileMode(TarArchiveOutputStream.LONGFILE_POSIX);
+      writeFilesToArchive(copyFiles, hardLinkFiles, archiveOutputStream);
+    }
+  }
+
+  private void getFilesForArchive(DBCheckpoint checkpoint,
+                                  Map<Object, Path> copyFiles,
+                                  Map<Path, Path> hardLinkFiles,
+                                  boolean includeSnapshotData)
+      throws IOException, InterruptedException {
+
+    // Get the active fs files.
+    Path dir = checkpoint.getCheckpointLocation();
+    processDir(dir, copyFiles, hardLinkFiles, new HashSet<>());
+
+    if (!includeSnapshotData) {
+      return;
+    }
+
+    // Get the snapshot files.
+    Set<Path> snapshotPaths = waitForSnapshotDirs(checkpoint);
+    Path snapshotDir = Paths.get(OMStorage.getOmDbDir(getConf()).toString(),
+        OM_SNAPSHOT_DIR);
+    processDir(snapshotDir, copyFiles, hardLinkFiles, snapshotPaths);
+  }
+
+  /**
+   * The snapshotInfo table may contain a snapshot that
+   * doesn't yet exist on the fs, so wait a few seconds for it.
+   * @param checkpoint Checkpoint containing snapshot entries expected.
+   * @return Set of expected snapshot dirs.
+   */
+  private Set<Path> waitForSnapshotDirs(DBCheckpoint checkpoint)
+      throws IOException, InterruptedException {
+
+    OzoneConfiguration conf = getConf();
+
+    Set<Path> snapshotPaths = new HashSet<>();
+
+    // get snapshotInfo entries
+    OmMetadataManagerImpl checkpointMetadataManager =
+        OmMetadataManagerImpl.createCheckpointMetadataManager(
+            conf, checkpoint);
+    try (TableIterator<String, ? extends Table.KeyValue<String, SnapshotInfo>>
+        iterator = checkpointMetadataManager
+        .getSnapshotInfoTable().iterator()) {
+
+      // For each entry, wait for corresponding directory.
+      while (iterator.hasNext()) {
+        Table.KeyValue<String, SnapshotInfo> entry = iterator.next();
+        Path path = Paths.get(getSnapshotPath(conf, entry.getValue()));
+        waitForDirToExist(path);
+        snapshotPaths.add(path);
+      }
+    }
+    return snapshotPaths;
+  }
+
+  private void waitForDirToExist(Path dir)
+      throws IOException, InterruptedException {
+    long endTime = System.currentTimeMillis() +
+        Duration.parse(DURATION_TO_WAIT_FOR_DIRECTORY).toMillis();
+    while (!dir.toFile().exists()) {
+      Thread.sleep(100);
+      if (System.currentTimeMillis() > endTime) {
+        throw new IOException("snapshot dir doesn't exist: " + dir);
+      }
+    }
+  }

Review Comment:
   Replaced with: https://github.com/apache/ozone/blob/051b97bf3eecaec31622161ee386002361e19c99/hadoop-hdds/framework/src/main/java/org/apache/hadoop/hdds/utils/db/RDBCheckpointManager.java#L116



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


[GitHub] [ozone] GeorgeJahad commented on a diff in pull request #3980: HDDS-6961. [Snapshot] Bootstrapping slow followers/new followers.

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


##########
hadoop-ozone/ozone-manager/src/main/java/org/apache/hadoop/ozone/om/OmSnapshotManager.java:
##########
@@ -279,6 +307,92 @@ private void verifySnapshotInfoForSnapDiff(final SnapshotInfo fromSnapshot,
     }
   }
 
+  /**
+   * Create file of links to add to tarball.
+   * Format of entries are either:
+   * dir1/fileTo fileFrom
+   *    for files in active db or:
+   * dir1/fileTo dir2/fileFrom
+   *    for files in another directory, (either another snapshot dir or
+   *    sst compaction backup directory)
+   * @param truncateLength - Length of initial path to trim in file path.
+   * @param hardLinkFiles - Map of link->file paths.
+   * @return Path to the file of links created.
+   */
+  @SuppressFBWarnings({"NP_NULL_ON_SOME_PATH_FROM_RETURN_VALUE"})
+  static Path createHardLinkList(int truncateLength,
+                                  Map<Path, Path> hardLinkFiles)
+      throws IOException {
+    Path data = Files.createTempFile("data", "txt");
+    StringBuilder sb = new StringBuilder();
+    for (Map.Entry<Path, Path> entry : hardLinkFiles.entrySet()) {
+      String fixedFile = truncateFileName(truncateLength, entry.getValue());
+      // If this file is from the active db, strip the path.
+      if (fixedFile.startsWith(OM_CHECKPOINT_DIR)) {
+        fixedFile = Paths.get(fixedFile).getFileName().toString();
+      }
+      sb.append(truncateFileName(truncateLength, entry.getKey()))
+          .append("\t")
+          .append(fixedFile)
+          .append("\n");
+    }
+    Files.write(data, sb.toString().getBytes(StandardCharsets.UTF_8));
+    return data;
+  }
+
+  /**
+   * Get the filename without the introductory metadata directory.
+   *
+   * @param truncateLength Length to remove.
+   * @param file File to remove prefix from.
+   * @return Truncated string.
+   */
+  static String truncateFileName(int truncateLength, Path file) {
+    return file.toString().substring(truncateLength);
+  }
+
+  /**
+   * Create hard links listed in OM_HARDLINK_FILE.
+   *
+   * @param dbPath Path to db to have links created.
+   */
+  static void createHardLinks(Path dbPath) throws IOException {

Review Comment:
   Add test here: https://github.com/apache/ozone/blob/051b97bf3eecaec31622161ee386002361e19c99/hadoop-ozone/integration-test/src/test/java/org/apache/hadoop/ozone/om/TestOMRatisSnapshots.java#L263-L304



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


[GitHub] [ozone] GeorgeJahad commented on a diff in pull request #3980: HDDS-6961. [Snapshot] Bootstrapping slow followers/new followers.

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


##########
hadoop-hdds/rocksdb-checkpoint-differ/src/main/java/org/apache/ozone/rocksdiff/RocksDBCheckpointDiffer.java:
##########
@@ -164,19 +164,19 @@ public RocksDBCheckpointDiffer(String metadataDir, String sstBackupDir,
     this.activeDBLocationStr = activeDBLocation.toString() + "/";
   }
 
-  private void setCompactionLogDir(String metadataDir,
+  private void setCompactionLogDir(String snapshotDiffDir,
       String compactionLogDirName) {
 
-    final File parentDir = new File(metadataDir);
+    final File parentDir = new File(snapshotDiffDir);
     if (!parentDir.exists()) {
-      if (!parentDir.mkdir()) {
+      if (!parentDir.mkdirs()) {
         LOG.error("Error creating compaction log parent dir.");
         return;
       }
     }
 
     this.compactionLogDir =
-        Paths.get(metadataDir, compactionLogDirName).toString();
+        Paths.get(parentDir.toString(), compactionLogDirName).toString();

Review Comment:
   This change got superseded by changes in master



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


[GitHub] [ozone] GeorgeJahad commented on a diff in pull request #3980: HDDS-6961. [Snapshot] Bootstrapping slow followers/new followers.

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


##########
hadoop-hdds/common/src/main/java/org/apache/hadoop/ozone/OzoneConsts.java:
##########
@@ -562,7 +564,18 @@ private OzoneConsts() {
   public static final int OZONE_MAXIMUM_ACCESS_ID_LENGTH = 100;
 
   public static final String OM_SNAPSHOT_NAME = "snapshotName";
+  public static final String OM_CHECKPOINT_DIR = "db.checkpoints";
   public static final String OM_SNAPSHOT_DIR = "db.snapshots";
+  public static final String OM_SNAPSHOT_CHECKPOINT_DIR = OM_SNAPSHOT_DIR
+      + OM_KEY_PREFIX + "checkpointState";
+  public static final String OM_SNAPSHOT_DIFF_DIR = OM_SNAPSHOT_DIR
+      + OM_KEY_PREFIX + "diffState";
+
+  // Name of the SST file backup directory placed under diff dir.

Review Comment:
   Replaced by @smengcl  in https://github.com/apache/ozone/pull/4418.



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


[GitHub] [ozone] GeorgeJahad commented on pull request #3980: HDDS-6961. [Snapshot] Bootstrapping slow followers/new followers.

Posted by "GeorgeJahad (via GitHub)" <gi...@apache.org>.
GeorgeJahad commented on PR #3980:
URL: https://github.com/apache/ozone/pull/3980#issuecomment-1461066106

   > Can we write some test that can exercise these code paths end to end ?
   
   As mentioned above, this integration test does excercise it from end to end: 
   https://github.com/apache/ozone/blob/ed069f01142452dfc59b3f9703e486ef0434d7e4/hadoop-ozone/integration-test/src/test/java/org/apache/hadoop/ozone/om/TestOMRatisSnapshots.java#L151
   
   Most of it already existed already, (to test the existing bootstrapping code from end to end.) I just added a snapshot test to it here:  https://github.com/apache/ozone/blob/ed069f01142452dfc59b3f9703e486ef0434d7e4/hadoop-ozone/integration-test/src/test/java/org/apache/hadoop/ozone/om/TestOMRatisSnapshots.java#L243
   
   I believe it does all of your steps except a configurable number of snapshots.  That shouldn't be hard to add.  Is it ok if I just make the configuration a parameter in the test file itself?  Would that satisfy this request?
   


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


[GitHub] [ozone] GeorgeJahad commented on pull request #3980: HDDS-6961. [Snapshot] Bootstrapping slow followers/new followers.

Posted by "GeorgeJahad (via GitHub)" <gi...@apache.org>.
GeorgeJahad commented on PR #3980:
URL: https://github.com/apache/ozone/pull/3980#issuecomment-1426468318

   Since we decided not to integrate with IC yet, I didn't have to change this PR much, since the last time it appeared.
   
   Mainly I've just merged the latest master and dealt with the conflicts.  There were two types of conflicts:
   
   1. The http servlet in master was restructured somewhat since my original draft, (mainly to not zip the tarball.)  So I merged those changes with mine.
   
   2. New snapshot code has been added using the old snapshot directory structure.  (As mentioned above, this PR changes the structure slightly so that the tarball creation code just pull most everything from a single directory.)  So I adjusted those directories as well.
   
   TODO:
   I've written a bunch of code to manage the interlocking between tarball creation and the background tasks that write snapshot state.  I decided to put that in a separate PR because this one is already too big.
   


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


[GitHub] [ozone] GeorgeJahad commented on a diff in pull request #3980: HDDS-6961. [Snapshot] Bootstrapping slow followers/new followers.

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


##########
hadoop-ozone/ozone-manager/src/main/java/org/apache/hadoop/ozone/om/OzoneManager.java:
##########
@@ -3736,13 +3755,17 @@ File replaceOMDBWithCheckpoint(long lastAppliedIndex, File oldDB,
       // starting up.
       Files.createFile(markerFile);
       FileUtils.moveDirectory(checkpointPath, oldDB.toPath());
+      moveOmSnapshotData(oldDB.toPath(), dbSnapshotsDir.toPath());

Review Comment:
   Yes, but to do so I would need to add leader tracking as well.  At that point, I will just be redoing all the work that @Xushaohong has already done more elegantly in the incremental snapshot pr here:  https://github.com/apache/ozone/pull/4294 
   



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


[GitHub] [ozone] GeorgeJahad commented on a diff in pull request #3980: HDDS-6961. [Snapshot] Bootstrapping slow followers/new followers.

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


##########
hadoop-ozone/ozone-manager/src/main/java/org/apache/hadoop/ozone/om/OmSnapshotManager.java:
##########
@@ -279,6 +307,92 @@ private void verifySnapshotInfoForSnapDiff(final SnapshotInfo fromSnapshot,
     }
   }
 
+  /**
+   * Create file of links to add to tarball.
+   * Format of entries are either:
+   * dir1/fileTo fileFrom
+   *    for files in active db or:
+   * dir1/fileTo dir2/fileFrom
+   *    for files in another directory, (either another snapshot dir or
+   *    sst compaction backup directory)
+   * @param truncateLength - Length of initial path to trim in file path.
+   * @param hardLinkFiles - Map of link->file paths.
+   * @return Path to the file of links created.
+   */
+  @SuppressFBWarnings({"NP_NULL_ON_SOME_PATH_FROM_RETURN_VALUE"})
+  static Path createHardLinkList(int truncateLength,
+                                  Map<Path, Path> hardLinkFiles)
+      throws IOException {
+    Path data = Files.createTempFile("data", "txt");
+    StringBuilder sb = new StringBuilder();
+    for (Map.Entry<Path, Path> entry : hardLinkFiles.entrySet()) {
+      String fixedFile = truncateFileName(truncateLength, entry.getValue());
+      // If this file is from the active db, strip the path.
+      if (fixedFile.startsWith(OM_CHECKPOINT_DIR)) {
+        fixedFile = Paths.get(fixedFile).getFileName().toString();
+      }
+      sb.append(truncateFileName(truncateLength, entry.getKey()))

Review Comment:
   Yes, sorry I didn't make this clear in my notes.  I'm trying to keep the tarball format backwards compatible/interoperable with the existing tarball format.  That way we could do a rolling restart on upgrade, (instead of having to shutdown all 3 om nodes.)
   
   The original format just has the active fs at the top of the tarball with no subdirectory prefix.  I couldn't easily maintain interoperability of the tarball format without doing the stripping/truncating.
   
   Maybe that isn't worthwhile.  Let me know what you think.
   



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


[GitHub] [ozone] GeorgeJahad commented on a diff in pull request #3980: HDDS-6961. [Snapshot] Bootstrapping slow followers/new followers.

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


##########
hadoop-hdds/framework/src/main/java/org/apache/hadoop/hdds/utils/DBCheckpointServlet.java:
##########
@@ -188,4 +189,11 @@ public void doGet(HttpServletRequest request, HttpServletResponse response) {
     }
   }
 
+  public void writeDbDataToStream(DBCheckpoint checkpoint,
+                                  HttpServletRequest ignoredRequest,

Review Comment:
   done.



##########
hadoop-ozone/integration-test/src/test/java/org/apache/hadoop/ozone/om/TestOMDbCheckpointServlet.java:
##########
@@ -257,63 +291,271 @@ public void testSpnegoEnabled() throws Exception {
   }
 
   @Test
-  public void testWriteCheckpointToOutputStream() throws Exception {
+  public void testWriteDbDataToStream() throws Exception {
+    prepSnapshotData();
+    // Set http param to include snapshot data.
+    when(requestMock.getParameter(OZONE_DB_CHECKPOINT_INCLUDE_SNAPSHOT_DATA))
+        .thenReturn("true");
 
+    // Get the tarball.
+    try (FileOutputStream fileOutputStream = new FileOutputStream(tempFile)) {
+      omDbCheckpointServletMock.writeDbDataToStream(dbCheckpoint, requestMock,
+          fileOutputStream);
+    }
+
+    // Untar the file into a temp folder to be examined.
     String testDirName = folder.newFolder().getAbsolutePath();
-    File checkpoint = new File(testDirName, "checkpoint");
-    checkpoint.mkdir();
-    File file = new File(checkpoint, "temp1.txt");
-    OutputStreamWriter writer = new OutputStreamWriter(
-        new FileOutputStream(file), StandardCharsets.UTF_8);
-    writer.write("Test data 1");
-    writer.close();
-
-    file = new File(checkpoint, "/temp2.txt");
-    writer = new OutputStreamWriter(
-        new FileOutputStream(file), StandardCharsets.UTF_8);
-    writer.write("Test data 2");
-    writer.close();
-
-    File outputFile =
-        new File(Paths.get(testDirName, "output_file.tar").toString());
-    TestDBCheckpoint dbCheckpoint = new TestDBCheckpoint(
-        checkpoint.toPath());
-    writeDBCheckpointToStream(dbCheckpoint,
-        new FileOutputStream(outputFile));
-    assertNotNull(outputFile);
+    int testDirLength = testDirName.length() + 1;
+    String newDbDirName = testDirName + OM_KEY_PREFIX + OM_DB_NAME;
+    int newDbDirLength = newDbDirName.length() + 1;
+    File newDbDir = new File(newDbDirName);
+    newDbDir.mkdirs();
+    FileUtil.unTar(tempFile, newDbDir);
+
+    // Move snapshot dir to correct location.
+    new File(newDbDirName, OM_SNAPSHOT_DIR)
+        .renameTo(new File(newDbDir.getParent(), OM_SNAPSHOT_DIR));
+
+
+    // Confirm the checkpoint directories match, (after remove extras).
+    Path checkpointLocation = dbCheckpoint.getCheckpointLocation();
+    Set<String> initialCheckpointSet = getFiles(checkpointLocation,
+        checkpointLocation.toString().length() + 1);
+    Path finalCheckpointLocation = Paths.get(newDbDirName);
+    Set<String> finalCheckpointSet = getFiles(finalCheckpointLocation,
+        newDbDirLength);
+
+    Assert.assertTrue("hardlink file exists in checkpoint dir",
+        finalCheckpointSet.contains(OM_HARDLINK_FILE));
+    finalCheckpointSet.remove(OM_HARDLINK_FILE);
+    Assert.assertEquals(initialCheckpointSet, finalCheckpointSet);
+
+    int metaDirLength = metaDir.toString().length() + 1;
+    String shortSnapshotLocation =
+        truncateFileName(metaDirLength, Paths.get(snapshotDirName));
+    String shortSnapshotLocation2 =
+        truncateFileName(metaDirLength, Paths.get(snapshotDirName2));
+    String shortCompactionDirLocation =
+        truncateFileName(metaDirLength, compactionDirPath);
+
+    Set<String> finalFullSet =
+        getFiles(Paths.get(testDirName, OM_SNAPSHOT_DIR), testDirLength);
+
+    // Check each line in the hard link file.
+    Stream<String> lines = Files.lines(Paths.get(newDbDirName,
+        OM_HARDLINK_FILE));
+
+    List<String> fabricatedLinkLines = new ArrayList<>();
+    for (String line: lines.collect(Collectors.toList())) {
+      Assert.assertFalse("CURRENT file is not a hard link",
+          line.contains("CURRENT"));
+      if (line.contains("fabricatedFile")) {
+        fabricatedLinkLines.add(line);
+      } else {
+        checkLine(shortSnapshotLocation, shortSnapshotLocation2, line);
+        // add links to the final set
+        finalFullSet.add(line.split("\t")[0]);
+      }
+    }

Review Comment:
   done



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

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

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


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


[GitHub] [ozone] GeorgeJahad commented on pull request #3980: HDDS-6961. [Snapshot] Bootstrapping slow followers/new followers.

Posted by "GeorgeJahad (via GitHub)" <gi...@apache.org>.
GeorgeJahad commented on PR #3980:
URL: https://github.com/apache/ozone/pull/3980#issuecomment-1478737333

   > Step 3 should be configurable to create even thousands of snapshots. In our local build, we should be able to test this thoroughly.
   
   I added this to this PR but it was failing because of the lack of synchronization: https://issues.apache.org/jira/browse/HDDS-8209
   
   I'll add it back in when I create that PR.


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


[GitHub] [ozone] GeorgeJahad commented on a diff in pull request #3980: HDDS-6961. [Snapshot] Bootstrapping slow followers/new followers.

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


##########
hadoop-ozone/ozone-manager/src/main/java/org/apache/hadoop/ozone/om/OMDBCheckpointServlet.java:
##########
@@ -82,4 +113,166 @@ public void init() throws ServletException {
         allowedGroups,
         om.isSpnegoEnabled());
   }
+
+  @Override
+  public void writeDbDataToStream(DBCheckpoint checkpoint,
+                                  HttpServletRequest request,
+                                  OutputStream destination)
+      throws IOException, InterruptedException {
+    // Map of inodes to path.
+    Map<Object, Path> copyFiles = new HashMap<>();
+    // Map of link to path.
+    Map<Path, Path> hardLinkFiles = new HashMap<>();
+
+    getFilesForArchive(checkpoint, copyFiles, hardLinkFiles,
+        includeSnapshotData(request));
+
+    try (TarArchiveOutputStream archiveOutputStream =
+            new TarArchiveOutputStream(destination)) {
+      archiveOutputStream
+          .setLongFileMode(TarArchiveOutputStream.LONGFILE_POSIX);
+      writeFilesToArchive(copyFiles, hardLinkFiles, archiveOutputStream);
+    }
+  }
+
+  private void getFilesForArchive(DBCheckpoint checkpoint,
+                                  Map<Object, Path> copyFiles,
+                                  Map<Path, Path> hardLinkFiles,
+                                  boolean includeSnapshotData)
+      throws IOException, InterruptedException {
+
+    // Get the active fs files.
+    Path dir = checkpoint.getCheckpointLocation();
+    processDir(dir, copyFiles, hardLinkFiles, new HashSet<>());
+
+    if (!includeSnapshotData) {
+      return;
+    }
+
+    // Get the snapshot files.
+    Set<Path> snapshotPaths = waitForSnapshotDirs(checkpoint);
+    Path snapshotDir = Paths.get(OMStorage.getOmDbDir(getConf()).toString(),
+        OM_SNAPSHOT_DIR);
+    processDir(snapshotDir, copyFiles, hardLinkFiles, snapshotPaths);
+  }
+
+  /**
+   * The snapshotInfo table may contain a snapshot that
+   * doesn't yet exist on the fs, so wait a few seconds for it.
+   * @param checkpoint Checkpoint containing snapshot entries expected.
+   * @return Set of expected snapshot dirs.
+   */
+  private Set<Path> waitForSnapshotDirs(DBCheckpoint checkpoint)
+      throws IOException, InterruptedException {
+
+    OzoneConfiguration conf = getConf();
+
+    Set<Path> snapshotPaths = new HashSet<>();
+
+    // get snapshotInfo entries
+    OmMetadataManagerImpl checkpointMetadataManager =
+        OmMetadataManagerImpl.createCheckpointMetadataManager(
+            conf, checkpoint);
+    try (TableIterator<String, ? extends Table.KeyValue<String, SnapshotInfo>>
+        iterator = checkpointMetadataManager
+        .getSnapshotInfoTable().iterator()) {

Review Comment:
   see above



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


[GitHub] [ozone] GeorgeJahad commented on pull request #3980: HDDS-6961. [Snapshot] Bootstrapping slow followers/new followers.

Posted by "GeorgeJahad (via GitHub)" <gi...@apache.org>.
GeorgeJahad commented on PR #3980:
URL: https://github.com/apache/ozone/pull/3980#issuecomment-1426538216

   @hemantk-12 @smengcl @prashantpogde I updated the bootstrapping PR to the latest master and fixed the merge conflicts. ^^
   
   Please take a look again.


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


[GitHub] [ozone] smengcl commented on pull request #3980: HDDS-6961. [Snapshot] Bootstrapping slow followers/new followers.

Posted by "smengcl (via GitHub)" <gi...@apache.org>.
smengcl commented on PR #3980:
URL: https://github.com/apache/ozone/pull/3980#issuecomment-1478681293

   > @smengcl you ask "Do we have a consensus here?" in a couple of places above.
   > 
   > I've responded to one. But I'm not sure what the second one is referring to. Are they the same thing?
   
   Ah. Actually it is the [same](https://github.com/apache/ozone/pull/3980/#discussion_r1139957157) one. GitHub is showing this in a confusing way when I stage the review comments in one batch so it looks like I have poste twice.


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


[GitHub] [ozone] hemantk-12 commented on a diff in pull request #3980: HDDS-6961. [Snapshot] Bootstrapping slow followers/new followers.

Posted by "hemantk-12 (via GitHub)" <gi...@apache.org>.
hemantk-12 commented on code in PR #3980:
URL: https://github.com/apache/ozone/pull/3980#discussion_r1042781601


##########
hadoop-hdds/framework/src/main/java/org/apache/hadoop/hdds/utils/db/RDBStore.java:
##########
@@ -139,10 +134,10 @@ public RDBStore(File dbFile, ManagedDBOptions dbOptions,
 
       //create snapshot directory if does not exist.
       snapshotsParentDir = Paths.get(dbLocation.getParent(),
-          OM_SNAPSHOT_DIR).toString();
+          OM_SNAPSHOT_CHECKPOINT_DIR).toString();

Review Comment:
   Comment says create snapshot directory but it is actually creating snapshot checkpointing directory. Either `OM_SNAPSHOT_DIR` was updated to `OM_SNAPSHOT_CHECKPOINT_DIR` mistakenly or comment needs update. Exception message may need update accordingly.



##########
hadoop-ozone/ozone-manager/src/main/java/org/apache/hadoop/ozone/om/OmSnapshotManager.java:
##########
@@ -220,6 +241,13 @@ public static String getSnapshotPrefix(String snapshotName) {
         snapshotName + OM_KEY_PREFIX;
   }
 
+  public static String getSnapshotPath(OzoneConfiguration conf,
+                                     SnapshotInfo snapshotInfo) {

Review Comment:
   Alignment is a bit off.
   
   Alignment is off for lots of function in this class. Please fix it.



##########
hadoop-ozone/ozone-manager/src/main/java/org/apache/hadoop/ozone/om/OMDBCheckpointServlet.java:
##########
@@ -82,4 +111,164 @@ public void init() throws ServletException {
         allowedGroups,
         om.isSpnegoEnabled());
   }
+
+  @Override
+  public void writeDbDataToStream(DBCheckpoint checkpoint,
+                                  HttpServletRequest request,
+                                  OutputStream destination)
+      throws IOException, InterruptedException {
+    // Map of inodes to path.
+    Map<Object, Path> copyFiles = new HashMap<>();
+    // Map of link to path.
+    Map<Path, Path> hardLinkFiles = new HashMap<>();
+
+    getFilesForArchive(checkpoint, copyFiles, hardLinkFiles,
+        includeSnapshotData(request));
+
+    try (TarArchiveOutputStream archiveOutputStream =
+            new TarArchiveOutputStream(destination)) {
+      archiveOutputStream
+          .setLongFileMode(TarArchiveOutputStream.LONGFILE_POSIX);
+      writeFilesToArchive(copyFiles, hardLinkFiles, archiveOutputStream);
+    }
+  }
+
+  private void getFilesForArchive(DBCheckpoint checkpoint,
+                                  Map<Object, Path> copyFiles,
+                                  Map<Path, Path> hardLinkFiles,
+                                  boolean includeSnapshotData)
+      throws IOException {
+
+    // Get the active fs files.
+    Path dir = checkpoint.getCheckpointLocation();
+    processDir(dir, copyFiles, hardLinkFiles, new HashSet<>());
+
+    if (!includeSnapshotData) {
+      return;
+    }
+
+    // Get the snapshot files.
+    Set<Path> snapshotPaths = waitForSnapshotDirs(checkpoint);
+    Path snapshotDir = Paths.get(OMStorage.getOmDbDir(getConf()).toString(),
+        OM_SNAPSHOT_DIR);
+    processDir(snapshotDir, copyFiles, hardLinkFiles, snapshotPaths);
+  }
+
+  /**
+   * The snapshotInfo table may contain a snapshot that
+   * doesn't yet exist on the fs, so wait a few seconds for it.
+   * @param checkpoint Checkpoint containing snapshot entries expected.
+   * @return Set of expected snapshot dirs.
+   */
+  private Set<Path> waitForSnapshotDirs(DBCheckpoint checkpoint)
+      throws IOException {
+
+    OzoneConfiguration conf = getConf();
+
+    Set<Path> snapshotPaths = new HashSet<>();
+
+    // get snapshotInfo entries
+    OmMetadataManagerImpl checkpointMetadataManager =
+        OmMetadataManagerImpl.createCheckpointMetadataManager(
+            conf, checkpoint);
+    try (TableIterator<String, ? extends Table.KeyValue<String, SnapshotInfo>>
+        iterator = checkpointMetadataManager
+        .getSnapshotInfoTable().iterator()) {
+
+      // For each entry, wait for corresponding directory.
+      while (iterator.hasNext()) {
+        Table.KeyValue<String, SnapshotInfo> entry = iterator.next();
+        Path path = Paths.get(getSnapshotPath(conf, entry.getValue()));
+        waitForDirToExist(path);
+        snapshotPaths.add(path);
+      }
+    }
+    return snapshotPaths;
+  }
+
+  private void waitForDirToExist(Path dir) throws IOException {
+    if (!RDBCheckpointManager.waitForCheckpointDirectoryExist(dir.toFile())) {

Review Comment:
   Optional: Should we move `waitForCheckpointDirectoryExist` to some Utils class?



##########
hadoop-ozone/ozone-manager/src/main/java/org/apache/hadoop/ozone/om/OMDBCheckpointServlet.java:
##########
@@ -82,4 +115,174 @@ public void init() throws ServletException {
         allowedGroups,
         om.isSpnegoEnabled());
   }
+
+  @Override
+  public void writeDbDataToStream(DBCheckpoint checkpoint,
+                                  HttpServletRequest request,
+                                  OutputStream destination)
+      throws IOException, InterruptedException, CompressorException {
+    // Map of inodes to path.
+    Map<Object, Path> copyFiles = new HashMap<>();
+    // Map of link to path.
+    Map<Path, Path> hardLinkFiles = new HashMap<>();
+
+    getFilesForArchive(checkpoint, copyFiles, hardLinkFiles,
+        includeSnapshotData(request));
+
+    try (CompressorOutputStream gzippedOut = new CompressorStreamFactory()
+        .createCompressorOutputStream(
+            CompressorStreamFactory.GZIP, destination);
+         TarArchiveOutputStream archiveOutputStream = 
+             new TarArchiveOutputStream(gzippedOut)
+    ) {
+      archiveOutputStream
+          .setLongFileMode(TarArchiveOutputStream.LONGFILE_POSIX);
+      writeFilesToArchive(copyFiles, hardLinkFiles, archiveOutputStream);
+    } catch (CompressorException e) {
+      throw new IOException(
+          "Can't compress the checkpoint: " +
+              checkpoint.getCheckpointLocation(), e);
+    }
+  }
+
+  private void getFilesForArchive(DBCheckpoint checkpoint,
+                                  Map<Object, Path> copyFiles,
+                                  Map<Path, Path> hardLinkFiles,
+                                  boolean includeSnapshotData)
+      throws IOException, InterruptedException {
+
+    // Get the active fs files.
+    Path dir = checkpoint.getCheckpointLocation();
+    processDir(dir, copyFiles, hardLinkFiles, new HashSet<>());
+
+    if (!includeSnapshotData) {
+      return;
+    }
+
+    // Get the snapshot files.
+    Set<Path> snapshotPaths = waitForSnapshotDirs(checkpoint);
+    Path snapshotDir = Paths.get(OMStorage.getOmDbDir(getConf()).toString(),
+        OM_SNAPSHOT_DIR);
+    processDir(snapshotDir, copyFiles, hardLinkFiles, snapshotPaths);
+  }
+
+  /**
+   * The snapshotInfo table may contain a snapshot that
+   * doesn't yet exist on the fs, so wait a few seconds for it.
+   * @param checkpoint Checkpoint containing snapshot entries expected.
+   * @return Set of expected snapshot dirs.
+   */
+  private Set<Path> waitForSnapshotDirs(DBCheckpoint checkpoint)
+      throws IOException, InterruptedException {
+
+    OzoneConfiguration conf = getConf();
+
+    Set<Path> snapshotPaths = new HashSet<>();
+
+    // get snapshotInfo entries
+    OmMetadataManagerImpl checkpointMetadataManager =
+        OmMetadataManagerImpl.createCheckpointMetadataManager(
+            conf, checkpoint);
+    try (TableIterator<String, ? extends Table.KeyValue<String, SnapshotInfo>>
+        iterator = checkpointMetadataManager
+        .getSnapshotInfoTable().iterator()) {
+
+      // For each entry, wait for corresponding directory.
+      while (iterator.hasNext()) {
+        Table.KeyValue<String, SnapshotInfo> entry = iterator.next();
+        Path path = Paths.get(getSnapshotPath(conf, entry.getValue()));
+        waitForDirToExist(path);
+        snapshotPaths.add(path);
+      }
+    }
+    return snapshotPaths;
+  }
+
+  private void waitForDirToExist(Path dir)
+      throws IOException, InterruptedException {
+    long endTime = System.currentTimeMillis() +
+        Duration.parse(DURATION_TO_WAIT_FOR_DIRECTORY).toMillis();
+    while (!dir.toFile().exists()) {
+      Thread.sleep(100);
+      if (System.currentTimeMillis() > endTime) {
+        throw new IOException("snapshot dir doesn't exist: " + dir);
+      }
+    }
+  }
+
+  @SuppressFBWarnings("NP_NULL_ON_SOME_PATH_FROM_RETURN_VALUE")
+  private void processDir(Path dir, Map<Object, Path> copyFiles,
+                          Map<Path, Path> hardLinkFiles,
+                          Set<Path> snapshotPaths)
+      throws IOException {
+    try (Stream<Path> files = Files.list(dir)) {
+      for (Path file : files.collect(Collectors.toList())) {
+        if (file.toFile().isDirectory()) {
+          // Skip any unexpected snapshot files.
+          if (file.getParent().toString().endsWith(OM_SNAPSHOT_CHECKPOINT_DIR)
+              && !snapshotPaths.contains(file)) {
+            continue;
+          }
+          processDir(file, copyFiles, hardLinkFiles, snapshotPaths);
+        } else {
+          processFile(file, copyFiles, hardLinkFiles);
+        }
+      }
+    }
+  }
+
+  private void processFile(Path file, Map<Object, Path> copyFiles,
+                           Map<Path, Path> hardLinkFiles) throws IOException {
+    // Get the inode.
+    Object key = OmSnapshotManager.getINode(file);
+    // If we already have the inode, store as hard link.
+    if (copyFiles.containsKey(key)) {
+      hardLinkFiles.put(file, copyFiles.get(key));
+    } else {
+      copyFiles.put(key, file);
+    }
+  }
+
+  // Returns value of http request parameter.
+  private boolean includeSnapshotData(HttpServletRequest request) {
+    String includeParam =

Review Comment:
   [Boolean.parseBoolean()](https://docs.oracle.com/javase/7/docs/api/java/lang/Boolean.html#parseBoolean(java.lang.String)) does a null check for you. Could be simply to:
   
   ```suggestion
       String includeParam =
           request.getParameter(OZONE_DB_CHECKPOINT_INCLUDE_SNAPSHOT_DATA);
       return Boolean.parseBoolean(includeParam);
   ```
   



##########
hadoop-hdds/framework/src/main/java/org/apache/hadoop/hdds/utils/db/RDBStore.java:
##########
@@ -134,7 +130,7 @@ public RDBStore(File dbFile, ManagedDBOptions dbOptions,
 
       //create checkpoints directory if not exists.
       checkpointsParentDir =
-          Paths.get(dbLocation.getParent(), "db.checkpoints").toString();
+          Paths.get(dbLocation.getParent(), OM_CHECKPOINT_DIR).toString();

Review Comment:
   ```suggestion
             dbLocation.getParent() + OM_KEY_PREFIX + OM_CHECKPOINT_DIR;
   ```
   
   I feel it is unnecessary to get create Path and then get the String from it.



##########
hadoop-ozone/ozone-manager/src/main/java/org/apache/hadoop/ozone/om/OmSnapshotManager.java:
##########
@@ -260,4 +288,89 @@ private void verifySnapshotInfoForSnapDiff(final SnapshotInfo fromSnapshot,
           " should be older than to toSnapshot:" + toSnapshot.getName());
     }
   }
+  /**
+   * Create file of links to add to tarball.
+   * Format of entries are either:
+   * dir1/fileTo fileFrom
+   *    for files in active db or:
+   * dir1/fileTo dir2/fileFrom
+   *    for files in another directory, (either another snapshot dir or
+   *    sst compaction backup directory)
+   * @param truncateLength - Length of initial path to trim in file path.
+   * @param hardLinkFiles - Map of link->file paths.
+   * @return Path to the file of links created.
+   */
+  @SuppressFBWarnings({"NP_NULL_ON_SOME_PATH_FROM_RETURN_VALUE"})
+  static Path createHardLinkList(int truncateLength,

Review Comment:
   Both `createHardLinkList(int truncateLength, Map<Path, Path> hardLinkFiles)` and `createHardLinks(Path dbPath)` don't belong to `OmSnapshotManager` according to me.
   
   As I said for `getINode()`, these functions belong to separate Util/Helper class.



##########
hadoop-hdds/common/src/main/java/org/apache/hadoop/ozone/OzoneConsts.java:
##########
@@ -562,7 +564,18 @@ private OzoneConsts() {
   public static final int OZONE_MAXIMUM_ACCESS_ID_LENGTH = 100;
 
   public static final String OM_SNAPSHOT_NAME = "snapshotName";
+  public static final String OM_CHECKPOINT_DIR = "db.checkpoints";
   public static final String OM_SNAPSHOT_DIR = "db.snapshots";
+  public static final String OM_SNAPSHOT_CHECKPOINT_DIR = OM_SNAPSHOT_DIR
+      + OM_KEY_PREFIX + "checkpointState";
+  public static final String OM_SNAPSHOT_DIFF_DIR = OM_SNAPSHOT_DIR
+      + OM_KEY_PREFIX + "diffState";
+
+  // Name of the SST file backup directory placed under diff dir.

Review Comment:
   Should it be `// Name of the SST file backup directory placed under metadata dir.` or `// Name of the SST file backup directory placed under snapshot dir.`? Or may be `snapshot diff`?



##########
hadoop-ozone/ozone-manager/src/main/java/org/apache/hadoop/ozone/om/OmSnapshotManager.java:
##########
@@ -162,6 +177,12 @@ public static DBCheckpoint createOmSnapshotCheckpoint(
     return dbCheckpoint;
   }
 
+  @VisibleForTesting
+  static Object getINode(Path file) throws IOException {

Review Comment:
   This is unnecessary one liner function to me. What's the reason of putting it here? It is not used anywhere inside `OmSnapshotManager`. If this has to be a helper function, may be put it in some util class.



##########
hadoop-hdds/common/src/main/java/org/apache/hadoop/ozone/OzoneConsts.java:
##########
@@ -562,7 +564,18 @@ private OzoneConsts() {
   public static final int OZONE_MAXIMUM_ACCESS_ID_LENGTH = 100;
 
   public static final String OM_SNAPSHOT_NAME = "snapshotName";
+  public static final String OM_CHECKPOINT_DIR = "db.checkpoints";
   public static final String OM_SNAPSHOT_DIR = "db.snapshots";
+  public static final String OM_SNAPSHOT_CHECKPOINT_DIR = OM_SNAPSHOT_DIR
+      + OM_KEY_PREFIX + "checkpointState";
+  public static final String OM_SNAPSHOT_DIFF_DIR = OM_SNAPSHOT_DIR
+      + OM_KEY_PREFIX + "diffState";
+
+  // Name of the SST file backup directory placed under diff dir.
+  public static final String OM_COMPACTION_BACKUP_DIR = "compaction-sst-backup";

Review Comment:
   ```suggestion
     public static final String OM_COMPACTION_SST_BACKUP_DIR = "compaction-sst-backup";
   ```



##########
hadoop-ozone/ozone-manager/src/main/java/org/apache/hadoop/ozone/om/OMDBCheckpointServlet.java:
##########
@@ -82,4 +115,174 @@ public void init() throws ServletException {
         allowedGroups,
         om.isSpnegoEnabled());
   }
+
+  @Override
+  public void writeDbDataToStream(DBCheckpoint checkpoint,
+                                  HttpServletRequest request,
+                                  OutputStream destination)
+      throws IOException, InterruptedException, CompressorException {

Review Comment:
   Are we still throwing `CompressorException` somewhere? I see we have a catch for it at line # 141.



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


[GitHub] [ozone] GeorgeJahad commented on a diff in pull request #3980: HDDS-6961. [Snapshot] Bootstrapping slow followers/new followers.

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


##########
hadoop-ozone/ozone-manager/src/main/java/org/apache/hadoop/ozone/om/OmSnapshotManager.java:
##########
@@ -279,6 +307,92 @@ private void verifySnapshotInfoForSnapDiff(final SnapshotInfo fromSnapshot,
     }
   }
 
+  /**
+   * Create file of links to add to tarball.
+   * Format of entries are either:
+   * dir1/fileTo fileFrom
+   *    for files in active db or:
+   * dir1/fileTo dir2/fileFrom
+   *    for files in another directory, (either another snapshot dir or
+   *    sst compaction backup directory)
+   * @param truncateLength - Length of initial path to trim in file path.
+   * @param hardLinkFiles - Map of link->file paths.
+   * @return Path to the file of links created.
+   */
+  @SuppressFBWarnings({"NP_NULL_ON_SOME_PATH_FROM_RETURN_VALUE"})
+  static Path createHardLinkList(int truncateLength,
+                                  Map<Path, Path> hardLinkFiles)
+      throws IOException {
+    Path data = Files.createTempFile("data", "txt");
+    StringBuilder sb = new StringBuilder();
+    for (Map.Entry<Path, Path> entry : hardLinkFiles.entrySet()) {
+      String fixedFile = truncateFileName(truncateLength, entry.getValue());
+      // If this file is from the active db, strip the path.
+      if (fixedFile.startsWith(OM_CHECKPOINT_DIR)) {
+        fixedFile = Paths.get(fixedFile).getFileName().toString();
+      }
+      sb.append(truncateFileName(truncateLength, entry.getKey()))
+          .append("\t")
+          .append(fixedFile)
+          .append("\n");
+    }
+    Files.write(data, sb.toString().getBytes(StandardCharsets.UTF_8));
+    return data;
+  }
+
+  /**
+   * Get the filename without the introductory metadata directory.
+   *
+   * @param truncateLength Length to remove.
+   * @param file File to remove prefix from.
+   * @return Truncated string.
+   */
+  static String truncateFileName(int truncateLength, Path file) {
+    return file.toString().substring(truncateLength);
+  }
+
+  /**
+   * Create hard links listed in OM_HARDLINK_FILE.
+   *
+   * @param dbPath Path to db to have links created.
+   */
+  static void createHardLinks(Path dbPath) throws IOException {
+    File hardLinkFile = new File(dbPath.toString(),
+        OM_HARDLINK_FILE);
+    if (hardLinkFile.exists()) {
+      // Read file.
+      List<String> lines =
+          Files.lines(hardLinkFile.toPath()).collect(Collectors.toList());

Review Comment:
   Good catch!  thanks!



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


[GitHub] [ozone] GeorgeJahad commented on a diff in pull request #3980: HDDS-6961. [Snapshot] Bootstrapping slow followers/new followers.

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


##########
hadoop-ozone/ozone-manager/src/main/java/org/apache/hadoop/ozone/om/OmSnapshotManager.java:
##########
@@ -279,6 +307,92 @@ private void verifySnapshotInfoForSnapDiff(final SnapshotInfo fromSnapshot,
     }
   }
 
+  /**
+   * Create file of links to add to tarball.
+   * Format of entries are either:
+   * dir1/fileTo fileFrom
+   *    for files in active db or:
+   * dir1/fileTo dir2/fileFrom
+   *    for files in another directory, (either another snapshot dir or
+   *    sst compaction backup directory)
+   * @param truncateLength - Length of initial path to trim in file path.
+   * @param hardLinkFiles - Map of link->file paths.
+   * @return Path to the file of links created.
+   */
+  @SuppressFBWarnings({"NP_NULL_ON_SOME_PATH_FROM_RETURN_VALUE"})
+  static Path createHardLinkList(int truncateLength,
+                                  Map<Path, Path> hardLinkFiles)
+      throws IOException {
+    Path data = Files.createTempFile("data", "txt");

Review Comment:
   My understand is that is does add a random number.  This shows it: https://mkyong.com/java/how-to-create-temporary-file-in-java/



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


[GitHub] [ozone] prashantpogde commented on a diff in pull request #3980: HDDS-6961. [Snapshot] Bootstrapping slow followers/new followers.

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


##########
hadoop-ozone/ozone-manager/src/main/java/org/apache/hadoop/ozone/om/OzoneManager.java:
##########
@@ -3736,13 +3755,17 @@ File replaceOMDBWithCheckpoint(long lastAppliedIndex, File oldDB,
       // starting up.
       Files.createFile(markerFile);
       FileUtils.moveDirectory(checkpointPath, oldDB.toPath());
+      moveOmSnapshotData(oldDB.toPath(), dbSnapshotsDir.toPath());

Review Comment:
   This would work even when we have thousands of snapshots as the process should eventually converge.



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


[GitHub] [ozone] GeorgeJahad commented on a diff in pull request #3980: HDDS-6961. [Snapshot] Bootstrapping slow followers/new followers.

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


##########
hadoop-ozone/integration-test/src/test/java/org/apache/hadoop/ozone/om/TestOMRatisSnapshots.java:
##########
@@ -537,6 +557,36 @@ public void testInstallCorruptedCheckpointFailure() throws Exception {
     Assert.assertTrue(logCapture.getOutput().contains(msg));
   }
 
+  private void createSnapshot(OzoneManager leaderOM, List<String> keys)
+      throws TimeoutException, InterruptedException, IOException {
+    // Avoid double buffer issue waiting for keys
+    GenericTestUtils.waitFor(() -> {
+      try {
+        OmKeyInfo key = leaderOM.getMetadataManager()
+            .getKeyTable(ozoneBucket.getBucketLayout())
+            .getSkipCache(leaderOM.getMetadataManager()
+            .getOzoneKey(volumeName, bucketName, keys.get(0)));
+        return key != null;
+      } catch (Exception e) {
+        return false;
+      }
+    }, 100, 10000);
+    objectStore.createSnapshot(volumeName, bucketName, "snap1");
+
+    // allow the snapshot to be written to the info table
+    GenericTestUtils.waitFor(() -> {
+      try {
+        SnapshotInfo snapshotInfo =

Review Comment:
   done



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

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

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


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


[GitHub] [ozone] smengcl commented on a diff in pull request #3980: HDDS-6961. [Snapshot] Bootstrapping slow followers/new followers.

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


##########
hadoop-ozone/ozone-manager/src/main/java/org/apache/hadoop/ozone/om/OzoneManager.java:
##########
@@ -3736,13 +3755,17 @@ File replaceOMDBWithCheckpoint(long lastAppliedIndex, File oldDB,
       // starting up.
       Files.createFile(markerFile);
       FileUtils.moveDirectory(checkpointPath, oldDB.toPath());
+      moveOmSnapshotData(oldDB.toPath(), dbSnapshotsDir.toPath());

Review Comment:
   Got 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: 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


[GitHub] [ozone] GeorgeJahad commented on a diff in pull request #3980: HDDS-6961. [Snapshot] Bootstrapping slow followers/new followers.

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


##########
hadoop-ozone/integration-test/src/test/java/org/apache/hadoop/ozone/om/TestOMDbCheckpointServlet.java:
##########
@@ -257,63 +291,271 @@ public void testSpnegoEnabled() throws Exception {
   }
 
   @Test
-  public void testWriteCheckpointToOutputStream() throws Exception {
+  public void testWriteDbDataToStream() throws Exception {
+    prepSnapshotData();
+    // Set http param to include snapshot data.
+    when(requestMock.getParameter(OZONE_DB_CHECKPOINT_INCLUDE_SNAPSHOT_DATA))
+        .thenReturn("true");
 
+    // Get the tarball.
+    try (FileOutputStream fileOutputStream = new FileOutputStream(tempFile)) {
+      omDbCheckpointServletMock.writeDbDataToStream(dbCheckpoint, requestMock,
+          fileOutputStream);
+    }
+
+    // Untar the file into a temp folder to be examined.
     String testDirName = folder.newFolder().getAbsolutePath();
-    File checkpoint = new File(testDirName, "checkpoint");
-    checkpoint.mkdir();
-    File file = new File(checkpoint, "temp1.txt");
-    OutputStreamWriter writer = new OutputStreamWriter(
-        new FileOutputStream(file), StandardCharsets.UTF_8);
-    writer.write("Test data 1");
-    writer.close();
-
-    file = new File(checkpoint, "/temp2.txt");
-    writer = new OutputStreamWriter(
-        new FileOutputStream(file), StandardCharsets.UTF_8);
-    writer.write("Test data 2");
-    writer.close();
-
-    File outputFile =
-        new File(Paths.get(testDirName, "output_file.tar").toString());
-    TestDBCheckpoint dbCheckpoint = new TestDBCheckpoint(
-        checkpoint.toPath());
-    writeDBCheckpointToStream(dbCheckpoint,
-        new FileOutputStream(outputFile));
-    assertNotNull(outputFile);
+    int testDirLength = testDirName.length() + 1;

Review Comment:
   yes



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


[GitHub] [ozone] GeorgeJahad commented on a diff in pull request #3980: HDDS-6961. [Snapshot] Bootstrapping slow followers/new followers.

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


##########
hadoop-ozone/ozone-manager/src/main/java/org/apache/hadoop/ozone/om/OzoneManager.java:
##########
@@ -3736,13 +3755,17 @@ File replaceOMDBWithCheckpoint(long lastAppliedIndex, File oldDB,
       // starting up.
       Files.createFile(markerFile);
       FileUtils.moveDirectory(checkpointPath, oldDB.toPath());
+      moveOmSnapshotData(oldDB.toPath(), dbSnapshotsDir.toPath());

Review Comment:
   No, but @prashantpogde and I agreed to hold off on this because this PR is already too big.  I've added this ticket as a reminder to finish it: https://issues.apache.org/jira/browse/HDDS-8208
   



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


[GitHub] [ozone] GeorgeJahad commented on pull request #3980: HDDS-6961. [Snapshot] Bootstrapping slow followers/new followers.

Posted by "GeorgeJahad (via GitHub)" <gi...@apache.org>.
GeorgeJahad commented on PR #3980:
URL: https://github.com/apache/ozone/pull/3980#issuecomment-1489645246

   @smengcl @prashantpogde  The merge conflict is resolved.
   


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


[GitHub] [ozone] GeorgeJahad commented on pull request #3980: HDDS-6961. [Snapshot] Bootstrapping slow followers/new followers.

Posted by "GeorgeJahad (via GitHub)" <gi...@apache.org>.
GeorgeJahad commented on PR #3980:
URL: https://github.com/apache/ozone/pull/3980#issuecomment-1486235855

   @hemantk-12 I've resolved all your suggestions


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


[GitHub] [ozone] prashantpogde commented on pull request #3980: HDDS-6961. [Snapshot] Bootstrapping slow followers/new followers.

Posted by "prashantpogde (via GitHub)" <gi...@apache.org>.
prashantpogde commented on PR #3980:
URL: https://github.com/apache/ozone/pull/3980#issuecomment-1457463142

   Can we write some test that can exercise these code paths end to end ? Perhaps mimic this with an integration test. We may have to tune down the RATIS log size to very small number of transaction so these code paths do get exercised.
   1) Create a  OM HA mini ozone cluster
   2) pause one of the OM nodes
   3) continue creating multiple transactions and multiple snapshots. 
   4) after a while, bring up the paused OM node and make sure that it has identical snapshots + active OS data as the leader OM.
   5) Step 3 should be configurable to create even thousands of snapshots. In our local build, we should be able to test this thoroughly.
   


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


[GitHub] [ozone] prashantpogde commented on a diff in pull request #3980: HDDS-6961. [Snapshot] Bootstrapping slow followers/new followers.

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


##########
hadoop-ozone/ozone-manager/src/main/java/org/apache/hadoop/ozone/om/OzoneManager.java:
##########
@@ -3736,13 +3755,17 @@ File replaceOMDBWithCheckpoint(long lastAppliedIndex, File oldDB,
       // starting up.
       Files.createFile(markerFile);
       FileUtils.moveDirectory(checkpointPath, oldDB.toPath());
+      moveOmSnapshotData(oldDB.toPath(), dbSnapshotsDir.toPath());

Review Comment:
   Getting all of snapshot data and installing it from leader can take a long time. We should at least have the logic to skip getting the snapshot directories from leader that already exist on the follower. 



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


[GitHub] [ozone] prashantpogde commented on a diff in pull request #3980: HDDS-6961. [Snapshot] Bootstrapping slow followers/new followers.

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


##########
hadoop-ozone/ozone-manager/src/main/java/org/apache/hadoop/ozone/om/OmSnapshotManager.java:
##########
@@ -279,6 +307,92 @@ private void verifySnapshotInfoForSnapDiff(final SnapshotInfo fromSnapshot,
     }
   }
 
+  /**
+   * Create file of links to add to tarball.
+   * Format of entries are either:
+   * dir1/fileTo fileFrom
+   *    for files in active db or:
+   * dir1/fileTo dir2/fileFrom
+   *    for files in another directory, (either another snapshot dir or
+   *    sst compaction backup directory)
+   * @param truncateLength - Length of initial path to trim in file path.
+   * @param hardLinkFiles - Map of link->file paths.
+   * @return Path to the file of links created.
+   */
+  @SuppressFBWarnings({"NP_NULL_ON_SOME_PATH_FROM_RETURN_VALUE"})
+  static Path createHardLinkList(int truncateLength,
+                                  Map<Path, Path> hardLinkFiles)
+      throws IOException {
+    Path data = Files.createTempFile("data", "txt");
+    StringBuilder sb = new StringBuilder();
+    for (Map.Entry<Path, Path> entry : hardLinkFiles.entrySet()) {
+      String fixedFile = truncateFileName(truncateLength, entry.getValue());
+      // If this file is from the active db, strip the path.
+      if (fixedFile.startsWith(OM_CHECKPOINT_DIR)) {
+        fixedFile = Paths.get(fixedFile).getFileName().toString();
+      }
+      sb.append(truncateFileName(truncateLength, entry.getKey()))
+          .append("\t")
+          .append(fixedFile)
+          .append("\n");
+    }
+    Files.write(data, sb.toString().getBytes(StandardCharsets.UTF_8));
+    return data;
+  }
+
+  /**
+   * Get the filename without the introductory metadata directory.
+   *
+   * @param truncateLength Length to remove.
+   * @param file File to remove prefix from.
+   * @return Truncated string.
+   */
+  static String truncateFileName(int truncateLength, Path file) {
+    return file.toString().substring(truncateLength);
+  }
+
+  /**
+   * Create hard links listed in OM_HARDLINK_FILE.
+   *
+   * @param dbPath Path to db to have links created.
+   */
+  static void createHardLinks(Path dbPath) throws IOException {

Review Comment:
   Can we have an integration test that exercises these code paths ?



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


[GitHub] [ozone] prashantpogde commented on a diff in pull request #3980: HDDS-6961. [Snapshot] Bootstrapping slow followers/new followers.

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


##########
hadoop-ozone/ozone-manager/src/main/java/org/apache/hadoop/ozone/om/OmSnapshotManager.java:
##########
@@ -279,6 +307,92 @@ private void verifySnapshotInfoForSnapDiff(final SnapshotInfo fromSnapshot,
     }
   }
 
+  /**
+   * Create file of links to add to tarball.
+   * Format of entries are either:
+   * dir1/fileTo fileFrom
+   *    for files in active db or:
+   * dir1/fileTo dir2/fileFrom
+   *    for files in another directory, (either another snapshot dir or
+   *    sst compaction backup directory)
+   * @param truncateLength - Length of initial path to trim in file path.
+   * @param hardLinkFiles - Map of link->file paths.
+   * @return Path to the file of links created.
+   */
+  @SuppressFBWarnings({"NP_NULL_ON_SOME_PATH_FROM_RETURN_VALUE"})
+  static Path createHardLinkList(int truncateLength,
+                                  Map<Path, Path> hardLinkFiles)
+      throws IOException {
+    Path data = Files.createTempFile("data", "txt");
+    StringBuilder sb = new StringBuilder();
+    for (Map.Entry<Path, Path> entry : hardLinkFiles.entrySet()) {
+      String fixedFile = truncateFileName(truncateLength, entry.getValue());
+      // If this file is from the active db, strip the path.
+      if (fixedFile.startsWith(OM_CHECKPOINT_DIR)) {
+        fixedFile = Paths.get(fixedFile).getFileName().toString();
+      }
+      sb.append(truncateFileName(truncateLength, entry.getKey()))

Review Comment:
   why not keep this logic uniform to include the dirname/filefrom both for activedb and snapshots/backupsstfiles  ?



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


[GitHub] [ozone] GeorgeJahad commented on pull request #3980: HDDS-6961. [Snapshot] Bootstrapping slow followers/new followers.

Posted by "GeorgeJahad (via GitHub)" <gi...@apache.org>.
GeorgeJahad commented on PR #3980:
URL: https://github.com/apache/ozone/pull/3980#issuecomment-1474508883

   @smengcl you ask "Do we have a consensus here?"  in a couple of places above.
   
   I've responded to one.  But I'm not sure what the second one is referring to.  Are they the same thing?


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


[GitHub] [ozone] GeorgeJahad commented on pull request #3980: HDDS-6961. [Snapshot] Bootstrapping slow followers/new followers.

Posted by GitBox <gi...@apache.org>.
GeorgeJahad commented on PR #3980:
URL: https://github.com/apache/ozone/pull/3980#issuecomment-1334653708

   FYI: @hemantk-12 , I've made all your requested changes.  In addition, I've fixed a separate issue, so that the tarball creation skips any snapshot directories that are not in rocksdb.  Those changes are mostly in this commit:
   https://github.com/apache/ozone/commit/e3a29217e37c7160c2bb3805e1b831fbc4c617d6
   


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


[GitHub] [ozone] smengcl commented on a diff in pull request #3980: HDDS-6961. [Snapshot] Bootstrapping slow followers/new followers.

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


##########
hadoop-ozone/integration-test/src/test/java/org/apache/hadoop/ozone/om/TestOMDbCheckpointServlet.java:
##########
@@ -257,63 +291,271 @@ public void testSpnegoEnabled() throws Exception {
   }
 
   @Test
-  public void testWriteCheckpointToOutputStream() throws Exception {
+  public void testWriteDbDataToStream() throws Exception {
+    prepSnapshotData();
+    // Set http param to include snapshot data.
+    when(requestMock.getParameter(OZONE_DB_CHECKPOINT_INCLUDE_SNAPSHOT_DATA))
+        .thenReturn("true");
 
+    // Get the tarball.
+    try (FileOutputStream fileOutputStream = new FileOutputStream(tempFile)) {
+      omDbCheckpointServletMock.writeDbDataToStream(dbCheckpoint, requestMock,
+          fileOutputStream);
+    }
+
+    // Untar the file into a temp folder to be examined.
     String testDirName = folder.newFolder().getAbsolutePath();
-    File checkpoint = new File(testDirName, "checkpoint");
-    checkpoint.mkdir();
-    File file = new File(checkpoint, "temp1.txt");
-    OutputStreamWriter writer = new OutputStreamWriter(
-        new FileOutputStream(file), StandardCharsets.UTF_8);
-    writer.write("Test data 1");
-    writer.close();
-
-    file = new File(checkpoint, "/temp2.txt");
-    writer = new OutputStreamWriter(
-        new FileOutputStream(file), StandardCharsets.UTF_8);
-    writer.write("Test data 2");
-    writer.close();
-
-    File outputFile =
-        new File(Paths.get(testDirName, "output_file.tar").toString());
-    TestDBCheckpoint dbCheckpoint = new TestDBCheckpoint(
-        checkpoint.toPath());
-    writeDBCheckpointToStream(dbCheckpoint,
-        new FileOutputStream(outputFile));
-    assertNotNull(outputFile);
+    int testDirLength = testDirName.length() + 1;

Review Comment:
   What is this `+ 1` for? To get rid of trailing `/`?



##########
hadoop-hdds/framework/src/main/java/org/apache/hadoop/hdds/utils/DBCheckpointServlet.java:
##########
@@ -188,4 +189,11 @@ public void doGet(HttpServletRequest request, HttpServletResponse response) {
     }
   }
 
+  public void writeDbDataToStream(DBCheckpoint checkpoint,
+                                  HttpServletRequest ignoredRequest,

Review Comment:
   What is this `ignoredRequest` for?



##########
hadoop-ozone/integration-test/src/test/java/org/apache/hadoop/ozone/om/TestOMDbCheckpointServlet.java:
##########
@@ -257,63 +291,271 @@ public void testSpnegoEnabled() throws Exception {
   }
 
   @Test
-  public void testWriteCheckpointToOutputStream() throws Exception {
+  public void testWriteDbDataToStream() throws Exception {
+    prepSnapshotData();
+    // Set http param to include snapshot data.
+    when(requestMock.getParameter(OZONE_DB_CHECKPOINT_INCLUDE_SNAPSHOT_DATA))
+        .thenReturn("true");
 
+    // Get the tarball.
+    try (FileOutputStream fileOutputStream = new FileOutputStream(tempFile)) {
+      omDbCheckpointServletMock.writeDbDataToStream(dbCheckpoint, requestMock,
+          fileOutputStream);
+    }
+
+    // Untar the file into a temp folder to be examined.
     String testDirName = folder.newFolder().getAbsolutePath();
-    File checkpoint = new File(testDirName, "checkpoint");
-    checkpoint.mkdir();
-    File file = new File(checkpoint, "temp1.txt");
-    OutputStreamWriter writer = new OutputStreamWriter(
-        new FileOutputStream(file), StandardCharsets.UTF_8);
-    writer.write("Test data 1");
-    writer.close();
-
-    file = new File(checkpoint, "/temp2.txt");
-    writer = new OutputStreamWriter(
-        new FileOutputStream(file), StandardCharsets.UTF_8);
-    writer.write("Test data 2");
-    writer.close();
-
-    File outputFile =
-        new File(Paths.get(testDirName, "output_file.tar").toString());
-    TestDBCheckpoint dbCheckpoint = new TestDBCheckpoint(
-        checkpoint.toPath());
-    writeDBCheckpointToStream(dbCheckpoint,
-        new FileOutputStream(outputFile));
-    assertNotNull(outputFile);
+    int testDirLength = testDirName.length() + 1;
+    String newDbDirName = testDirName + OM_KEY_PREFIX + OM_DB_NAME;
+    int newDbDirLength = newDbDirName.length() + 1;
+    File newDbDir = new File(newDbDirName);
+    newDbDir.mkdirs();
+    FileUtil.unTar(tempFile, newDbDir);
+
+    // Move snapshot dir to correct location.
+    new File(newDbDirName, OM_SNAPSHOT_DIR)
+        .renameTo(new File(newDbDir.getParent(), OM_SNAPSHOT_DIR));
+

Review Comment:
   ```suggestion
       Assert.assertTrue(new File(newDbDirName, OM_SNAPSHOT_DIR)
           .renameTo(new File(newDbDir.getParent(), OM_SNAPSHOT_DIR)));
   ```



##########
hadoop-ozone/integration-test/src/test/java/org/apache/hadoop/ozone/om/TestOMDbCheckpointServlet.java:
##########
@@ -257,63 +291,271 @@ public void testSpnegoEnabled() throws Exception {
   }
 
   @Test
-  public void testWriteCheckpointToOutputStream() throws Exception {
+  public void testWriteDbDataToStream() throws Exception {
+    prepSnapshotData();
+    // Set http param to include snapshot data.
+    when(requestMock.getParameter(OZONE_DB_CHECKPOINT_INCLUDE_SNAPSHOT_DATA))
+        .thenReturn("true");
 
+    // Get the tarball.
+    try (FileOutputStream fileOutputStream = new FileOutputStream(tempFile)) {
+      omDbCheckpointServletMock.writeDbDataToStream(dbCheckpoint, requestMock,
+          fileOutputStream);
+    }
+
+    // Untar the file into a temp folder to be examined.
     String testDirName = folder.newFolder().getAbsolutePath();
-    File checkpoint = new File(testDirName, "checkpoint");
-    checkpoint.mkdir();
-    File file = new File(checkpoint, "temp1.txt");
-    OutputStreamWriter writer = new OutputStreamWriter(
-        new FileOutputStream(file), StandardCharsets.UTF_8);
-    writer.write("Test data 1");
-    writer.close();
-
-    file = new File(checkpoint, "/temp2.txt");
-    writer = new OutputStreamWriter(
-        new FileOutputStream(file), StandardCharsets.UTF_8);
-    writer.write("Test data 2");
-    writer.close();
-
-    File outputFile =
-        new File(Paths.get(testDirName, "output_file.tar").toString());
-    TestDBCheckpoint dbCheckpoint = new TestDBCheckpoint(
-        checkpoint.toPath());
-    writeDBCheckpointToStream(dbCheckpoint,
-        new FileOutputStream(outputFile));
-    assertNotNull(outputFile);
+    int testDirLength = testDirName.length() + 1;
+    String newDbDirName = testDirName + OM_KEY_PREFIX + OM_DB_NAME;
+    int newDbDirLength = newDbDirName.length() + 1;
+    File newDbDir = new File(newDbDirName);
+    newDbDir.mkdirs();
+    FileUtil.unTar(tempFile, newDbDir);
+
+    // Move snapshot dir to correct location.
+    new File(newDbDirName, OM_SNAPSHOT_DIR)
+        .renameTo(new File(newDbDir.getParent(), OM_SNAPSHOT_DIR));
+
+
+    // Confirm the checkpoint directories match, (after remove extras).
+    Path checkpointLocation = dbCheckpoint.getCheckpointLocation();
+    Set<String> initialCheckpointSet = getFiles(checkpointLocation,
+        checkpointLocation.toString().length() + 1);
+    Path finalCheckpointLocation = Paths.get(newDbDirName);
+    Set<String> finalCheckpointSet = getFiles(finalCheckpointLocation,
+        newDbDirLength);
+
+    Assert.assertTrue("hardlink file exists in checkpoint dir",
+        finalCheckpointSet.contains(OM_HARDLINK_FILE));
+    finalCheckpointSet.remove(OM_HARDLINK_FILE);
+    Assert.assertEquals(initialCheckpointSet, finalCheckpointSet);
+
+    int metaDirLength = metaDir.toString().length() + 1;
+    String shortSnapshotLocation =
+        truncateFileName(metaDirLength, Paths.get(snapshotDirName));
+    String shortSnapshotLocation2 =
+        truncateFileName(metaDirLength, Paths.get(snapshotDirName2));
+    String shortCompactionDirLocation =
+        truncateFileName(metaDirLength, compactionDirPath);
+
+    Set<String> finalFullSet =
+        getFiles(Paths.get(testDirName, OM_SNAPSHOT_DIR), testDirLength);
+
+    // Check each line in the hard link file.
+    Stream<String> lines = Files.lines(Paths.get(newDbDirName,
+        OM_HARDLINK_FILE));
+
+    List<String> fabricatedLinkLines = new ArrayList<>();
+    for (String line: lines.collect(Collectors.toList())) {
+      Assert.assertFalse("CURRENT file is not a hard link",
+          line.contains("CURRENT"));
+      if (line.contains("fabricatedFile")) {
+        fabricatedLinkLines.add(line);
+      } else {
+        checkLine(shortSnapshotLocation, shortSnapshotLocation2, line);
+        // add links to the final set
+        finalFullSet.add(line.split("\t")[0]);
+      }
+    }
+
+    Set<String> directories = Sets.newHashSet(
+        shortSnapshotLocation, shortSnapshotLocation2,
+        shortCompactionDirLocation);
+    checkFabricatedLines(directories, fabricatedLinkLines, testDirName);
+
+    Set<String> initialFullSet =
+        getFiles(Paths.get(metaDir.toString(), OM_SNAPSHOT_DIR), metaDirLength);
+    Assert.assertEquals("found expected snapshot files",
+        initialFullSet, finalFullSet);

Review Comment:
   iirc the message is printed in `AssertionError`. so should it say the other way?
   
   ```suggestion
       Assert.assertEquals("found expected snapshot files",
           initialFullSet, finalFullSet);
   ```



##########
hadoop-ozone/integration-test/src/test/java/org/apache/hadoop/ozone/om/TestOMDbCheckpointServlet.java:
##########
@@ -257,63 +291,271 @@ public void testSpnegoEnabled() throws Exception {
   }
 
   @Test
-  public void testWriteCheckpointToOutputStream() throws Exception {
+  public void testWriteDbDataToStream() throws Exception {
+    prepSnapshotData();
+    // Set http param to include snapshot data.
+    when(requestMock.getParameter(OZONE_DB_CHECKPOINT_INCLUDE_SNAPSHOT_DATA))
+        .thenReturn("true");
 
+    // Get the tarball.
+    try (FileOutputStream fileOutputStream = new FileOutputStream(tempFile)) {
+      omDbCheckpointServletMock.writeDbDataToStream(dbCheckpoint, requestMock,
+          fileOutputStream);
+    }
+
+    // Untar the file into a temp folder to be examined.
     String testDirName = folder.newFolder().getAbsolutePath();
-    File checkpoint = new File(testDirName, "checkpoint");
-    checkpoint.mkdir();
-    File file = new File(checkpoint, "temp1.txt");
-    OutputStreamWriter writer = new OutputStreamWriter(
-        new FileOutputStream(file), StandardCharsets.UTF_8);
-    writer.write("Test data 1");
-    writer.close();
-
-    file = new File(checkpoint, "/temp2.txt");
-    writer = new OutputStreamWriter(
-        new FileOutputStream(file), StandardCharsets.UTF_8);
-    writer.write("Test data 2");
-    writer.close();
-
-    File outputFile =
-        new File(Paths.get(testDirName, "output_file.tar").toString());
-    TestDBCheckpoint dbCheckpoint = new TestDBCheckpoint(
-        checkpoint.toPath());
-    writeDBCheckpointToStream(dbCheckpoint,
-        new FileOutputStream(outputFile));
-    assertNotNull(outputFile);
+    int testDirLength = testDirName.length() + 1;
+    String newDbDirName = testDirName + OM_KEY_PREFIX + OM_DB_NAME;
+    int newDbDirLength = newDbDirName.length() + 1;
+    File newDbDir = new File(newDbDirName);
+    newDbDir.mkdirs();
+    FileUtil.unTar(tempFile, newDbDir);
+
+    // Move snapshot dir to correct location.
+    new File(newDbDirName, OM_SNAPSHOT_DIR)
+        .renameTo(new File(newDbDir.getParent(), OM_SNAPSHOT_DIR));
+
+
+    // Confirm the checkpoint directories match, (after remove extras).
+    Path checkpointLocation = dbCheckpoint.getCheckpointLocation();
+    Set<String> initialCheckpointSet = getFiles(checkpointLocation,
+        checkpointLocation.toString().length() + 1);
+    Path finalCheckpointLocation = Paths.get(newDbDirName);
+    Set<String> finalCheckpointSet = getFiles(finalCheckpointLocation,
+        newDbDirLength);
+
+    Assert.assertTrue("hardlink file exists in checkpoint dir",
+        finalCheckpointSet.contains(OM_HARDLINK_FILE));
+    finalCheckpointSet.remove(OM_HARDLINK_FILE);
+    Assert.assertEquals(initialCheckpointSet, finalCheckpointSet);
+
+    int metaDirLength = metaDir.toString().length() + 1;
+    String shortSnapshotLocation =
+        truncateFileName(metaDirLength, Paths.get(snapshotDirName));
+    String shortSnapshotLocation2 =
+        truncateFileName(metaDirLength, Paths.get(snapshotDirName2));
+    String shortCompactionDirLocation =
+        truncateFileName(metaDirLength, compactionDirPath);
+
+    Set<String> finalFullSet =
+        getFiles(Paths.get(testDirName, OM_SNAPSHOT_DIR), testDirLength);
+
+    // Check each line in the hard link file.
+    Stream<String> lines = Files.lines(Paths.get(newDbDirName,
+        OM_HARDLINK_FILE));
+
+    List<String> fabricatedLinkLines = new ArrayList<>();
+    for (String line: lines.collect(Collectors.toList())) {
+      Assert.assertFalse("CURRENT file is not a hard link",
+          line.contains("CURRENT"));
+      if (line.contains("fabricatedFile")) {
+        fabricatedLinkLines.add(line);
+      } else {
+        checkLine(shortSnapshotLocation, shortSnapshotLocation2, line);
+        // add links to the final set
+        finalFullSet.add(line.split("\t")[0]);
+      }
+    }
+
+    Set<String> directories = Sets.newHashSet(
+        shortSnapshotLocation, shortSnapshotLocation2,
+        shortCompactionDirLocation);
+    checkFabricatedLines(directories, fabricatedLinkLines, testDirName);
+
+    Set<String> initialFullSet =
+        getFiles(Paths.get(metaDir.toString(), OM_SNAPSHOT_DIR), metaDirLength);
+    Assert.assertEquals("found expected snapshot files",
+        initialFullSet, finalFullSet);
   }
-}
 
-class TestDBCheckpoint implements DBCheckpoint {
+  @Test
+  public void testWriteDbDataWithoutOmSnapshot()
+      throws Exception {
+    prepSnapshotData();
+
+    // Set http param to exclude snapshot data.
+    when(requestMock.getParameter(OZONE_DB_CHECKPOINT_INCLUDE_SNAPSHOT_DATA))
+        .thenReturn(null);
+
+    // Get the tarball.
+    try (FileOutputStream fileOutputStream = new FileOutputStream(tempFile)) {
+      omDbCheckpointServletMock.writeDbDataToStream(dbCheckpoint, requestMock,
+          fileOutputStream);
+    }
+
+    // Untar the file into a temp folder to be examined.
+    String testDirName = folder.newFolder().getAbsolutePath();
+    int testDirLength = testDirName.length() + 1;
+    FileUtil.unTar(tempFile, new File(testDirName));
+
+    // Confirm the checkpoint directories match.
+    Path checkpointLocation = dbCheckpoint.getCheckpointLocation();
+    Set<String> initialCheckpointSet = getFiles(checkpointLocation,
+        checkpointLocation.toString().length() + 1);
+    Path finalCheckpointLocation = Paths.get(testDirName);
+    Set<String> finalCheckpointSet = getFiles(finalCheckpointLocation,
+        testDirLength);
+
+    Assert.assertEquals(initialCheckpointSet, finalCheckpointSet);
+  }
+
+

Review Comment:
   nit
   ```suggestion
   ```



##########
hadoop-ozone/integration-test/src/test/java/org/apache/hadoop/ozone/om/TestOMDbCheckpointServlet.java:
##########
@@ -257,63 +291,271 @@ public void testSpnegoEnabled() throws Exception {
   }
 
   @Test
-  public void testWriteCheckpointToOutputStream() throws Exception {
+  public void testWriteDbDataToStream() throws Exception {
+    prepSnapshotData();
+    // Set http param to include snapshot data.
+    when(requestMock.getParameter(OZONE_DB_CHECKPOINT_INCLUDE_SNAPSHOT_DATA))
+        .thenReturn("true");
 
+    // Get the tarball.
+    try (FileOutputStream fileOutputStream = new FileOutputStream(tempFile)) {
+      omDbCheckpointServletMock.writeDbDataToStream(dbCheckpoint, requestMock,
+          fileOutputStream);
+    }
+
+    // Untar the file into a temp folder to be examined.
     String testDirName = folder.newFolder().getAbsolutePath();
-    File checkpoint = new File(testDirName, "checkpoint");
-    checkpoint.mkdir();
-    File file = new File(checkpoint, "temp1.txt");
-    OutputStreamWriter writer = new OutputStreamWriter(
-        new FileOutputStream(file), StandardCharsets.UTF_8);
-    writer.write("Test data 1");
-    writer.close();
-
-    file = new File(checkpoint, "/temp2.txt");
-    writer = new OutputStreamWriter(
-        new FileOutputStream(file), StandardCharsets.UTF_8);
-    writer.write("Test data 2");
-    writer.close();
-
-    File outputFile =
-        new File(Paths.get(testDirName, "output_file.tar").toString());
-    TestDBCheckpoint dbCheckpoint = new TestDBCheckpoint(
-        checkpoint.toPath());
-    writeDBCheckpointToStream(dbCheckpoint,
-        new FileOutputStream(outputFile));
-    assertNotNull(outputFile);
+    int testDirLength = testDirName.length() + 1;
+    String newDbDirName = testDirName + OM_KEY_PREFIX + OM_DB_NAME;
+    int newDbDirLength = newDbDirName.length() + 1;
+    File newDbDir = new File(newDbDirName);
+    newDbDir.mkdirs();
+    FileUtil.unTar(tempFile, newDbDir);
+
+    // Move snapshot dir to correct location.
+    new File(newDbDirName, OM_SNAPSHOT_DIR)
+        .renameTo(new File(newDbDir.getParent(), OM_SNAPSHOT_DIR));
+
+
+    // Confirm the checkpoint directories match, (after remove extras).
+    Path checkpointLocation = dbCheckpoint.getCheckpointLocation();
+    Set<String> initialCheckpointSet = getFiles(checkpointLocation,
+        checkpointLocation.toString().length() + 1);
+    Path finalCheckpointLocation = Paths.get(newDbDirName);
+    Set<String> finalCheckpointSet = getFiles(finalCheckpointLocation,
+        newDbDirLength);
+
+    Assert.assertTrue("hardlink file exists in checkpoint dir",
+        finalCheckpointSet.contains(OM_HARDLINK_FILE));
+    finalCheckpointSet.remove(OM_HARDLINK_FILE);
+    Assert.assertEquals(initialCheckpointSet, finalCheckpointSet);
+
+    int metaDirLength = metaDir.toString().length() + 1;
+    String shortSnapshotLocation =
+        truncateFileName(metaDirLength, Paths.get(snapshotDirName));
+    String shortSnapshotLocation2 =
+        truncateFileName(metaDirLength, Paths.get(snapshotDirName2));
+    String shortCompactionDirLocation =
+        truncateFileName(metaDirLength, compactionDirPath);
+
+    Set<String> finalFullSet =
+        getFiles(Paths.get(testDirName, OM_SNAPSHOT_DIR), testDirLength);
+
+    // Check each line in the hard link file.
+    Stream<String> lines = Files.lines(Paths.get(newDbDirName,
+        OM_HARDLINK_FILE));
+
+    List<String> fabricatedLinkLines = new ArrayList<>();
+    for (String line: lines.collect(Collectors.toList())) {
+      Assert.assertFalse("CURRENT file is not a hard link",
+          line.contains("CURRENT"));
+      if (line.contains("fabricatedFile")) {
+        fabricatedLinkLines.add(line);
+      } else {
+        checkLine(shortSnapshotLocation, shortSnapshotLocation2, line);
+        // add links to the final set
+        finalFullSet.add(line.split("\t")[0]);
+      }
+    }

Review Comment:
   `Stream<>` needs to be closed. Best wrap it in try-with-resource for better error handling and guarantee closure even when thrown exceptions.
   
   Example:
   
   https://github.com/apache/ozone/blob/7923e25be44ca89e581aa493443f9f9310483883/hadoop-hdds/container-service/src/main/java/org/apache/hadoop/ozone/container/keyvalue/KeyValueContainerMetadataInspector.java#L308-L310



##########
hadoop-ozone/ozone-manager/src/main/java/org/apache/hadoop/ozone/om/OMDBCheckpointServlet.java:
##########
@@ -82,4 +113,166 @@ public void init() throws ServletException {
         allowedGroups,
         om.isSpnegoEnabled());
   }
+
+  @Override
+  public void writeDbDataToStream(DBCheckpoint checkpoint,
+                                  HttpServletRequest request,
+                                  OutputStream destination)
+      throws IOException, InterruptedException {
+    // Map of inodes to path.
+    Map<Object, Path> copyFiles = new HashMap<>();
+    // Map of link to path.
+    Map<Path, Path> hardLinkFiles = new HashMap<>();
+
+    getFilesForArchive(checkpoint, copyFiles, hardLinkFiles,
+        includeSnapshotData(request));
+
+    try (TarArchiveOutputStream archiveOutputStream =
+            new TarArchiveOutputStream(destination)) {
+      archiveOutputStream
+          .setLongFileMode(TarArchiveOutputStream.LONGFILE_POSIX);
+      writeFilesToArchive(copyFiles, hardLinkFiles, archiveOutputStream);
+    }
+  }
+
+  private void getFilesForArchive(DBCheckpoint checkpoint,
+                                  Map<Object, Path> copyFiles,
+                                  Map<Path, Path> hardLinkFiles,
+                                  boolean includeSnapshotData)
+      throws IOException, InterruptedException {
+
+    // Get the active fs files.
+    Path dir = checkpoint.getCheckpointLocation();
+    processDir(dir, copyFiles, hardLinkFiles, new HashSet<>());
+
+    if (!includeSnapshotData) {
+      return;
+    }
+
+    // Get the snapshot files.
+    Set<Path> snapshotPaths = waitForSnapshotDirs(checkpoint);
+    Path snapshotDir = Paths.get(OMStorage.getOmDbDir(getConf()).toString(),
+        OM_SNAPSHOT_DIR);
+    processDir(snapshotDir, copyFiles, hardLinkFiles, snapshotPaths);
+  }
+
+  /**
+   * The snapshotInfo table may contain a snapshot that
+   * doesn't yet exist on the fs, so wait a few seconds for it.
+   * @param checkpoint Checkpoint containing snapshot entries expected.
+   * @return Set of expected snapshot dirs.
+   */
+  private Set<Path> waitForSnapshotDirs(DBCheckpoint checkpoint)
+      throws IOException, InterruptedException {
+
+    OzoneConfiguration conf = getConf();
+
+    Set<Path> snapshotPaths = new HashSet<>();
+
+    // get snapshotInfo entries
+    OmMetadataManagerImpl checkpointMetadataManager =
+        OmMetadataManagerImpl.createCheckpointMetadataManager(
+            conf, checkpoint);
+    try (TableIterator<String, ? extends Table.KeyValue<String, SnapshotInfo>>
+        iterator = checkpointMetadataManager
+        .getSnapshotInfoTable().iterator()) {
+
+      // For each entry, wait for corresponding directory.
+      while (iterator.hasNext()) {
+        Table.KeyValue<String, SnapshotInfo> entry = iterator.next();
+        Path path = Paths.get(getSnapshotPath(conf, entry.getValue()));
+        waitForDirToExist(path);
+        snapshotPaths.add(path);
+      }
+    }
+    return snapshotPaths;
+  }
+
+  private void waitForDirToExist(Path dir)
+      throws IOException, InterruptedException {
+    long endTime = System.currentTimeMillis() +
+        Duration.parse(DURATION_TO_WAIT_FOR_DIRECTORY).toMillis();
+    while (!dir.toFile().exists()) {
+      Thread.sleep(100);
+      if (System.currentTimeMillis() > endTime) {
+        throw new IOException("snapshot dir doesn't exist: " + dir);
+      }
+    }
+  }
+
+  @SuppressFBWarnings("NP_NULL_ON_SOME_PATH_FROM_RETURN_VALUE")
+  private void processDir(Path dir, Map<Object, Path> copyFiles,

Review Comment:
   Is it possible to remove the suppress annotation and fix the findbugs? since this is not test code like the others.



##########
hadoop-ozone/ozone-manager/src/main/java/org/apache/hadoop/ozone/om/OMDBCheckpointServlet.java:
##########
@@ -82,4 +113,166 @@ public void init() throws ServletException {
         allowedGroups,
         om.isSpnegoEnabled());
   }
+
+  @Override
+  public void writeDbDataToStream(DBCheckpoint checkpoint,
+                                  HttpServletRequest request,
+                                  OutputStream destination)
+      throws IOException, InterruptedException {
+    // Map of inodes to path.
+    Map<Object, Path> copyFiles = new HashMap<>();
+    // Map of link to path.
+    Map<Path, Path> hardLinkFiles = new HashMap<>();
+
+    getFilesForArchive(checkpoint, copyFiles, hardLinkFiles,
+        includeSnapshotData(request));
+
+    try (TarArchiveOutputStream archiveOutputStream =
+            new TarArchiveOutputStream(destination)) {
+      archiveOutputStream
+          .setLongFileMode(TarArchiveOutputStream.LONGFILE_POSIX);
+      writeFilesToArchive(copyFiles, hardLinkFiles, archiveOutputStream);
+    }
+  }
+
+  private void getFilesForArchive(DBCheckpoint checkpoint,
+                                  Map<Object, Path> copyFiles,
+                                  Map<Path, Path> hardLinkFiles,
+                                  boolean includeSnapshotData)
+      throws IOException, InterruptedException {
+
+    // Get the active fs files.
+    Path dir = checkpoint.getCheckpointLocation();
+    processDir(dir, copyFiles, hardLinkFiles, new HashSet<>());
+
+    if (!includeSnapshotData) {
+      return;
+    }
+
+    // Get the snapshot files.
+    Set<Path> snapshotPaths = waitForSnapshotDirs(checkpoint);
+    Path snapshotDir = Paths.get(OMStorage.getOmDbDir(getConf()).toString(),
+        OM_SNAPSHOT_DIR);
+    processDir(snapshotDir, copyFiles, hardLinkFiles, snapshotPaths);
+  }
+
+  /**
+   * The snapshotInfo table may contain a snapshot that
+   * doesn't yet exist on the fs, so wait a few seconds for it.
+   * @param checkpoint Checkpoint containing snapshot entries expected.
+   * @return Set of expected snapshot dirs.
+   */
+  private Set<Path> waitForSnapshotDirs(DBCheckpoint checkpoint)
+      throws IOException, InterruptedException {
+
+    OzoneConfiguration conf = getConf();
+
+    Set<Path> snapshotPaths = new HashSet<>();
+
+    // get snapshotInfo entries
+    OmMetadataManagerImpl checkpointMetadataManager =
+        OmMetadataManagerImpl.createCheckpointMetadataManager(
+            conf, checkpoint);
+    try (TableIterator<String, ? extends Table.KeyValue<String, SnapshotInfo>>
+        iterator = checkpointMetadataManager
+        .getSnapshotInfoTable().iterator()) {
+
+      // For each entry, wait for corresponding directory.
+      while (iterator.hasNext()) {
+        Table.KeyValue<String, SnapshotInfo> entry = iterator.next();
+        Path path = Paths.get(getSnapshotPath(conf, entry.getValue()));
+        waitForDirToExist(path);
+        snapshotPaths.add(path);
+      }
+    }
+    return snapshotPaths;
+  }
+
+  private void waitForDirToExist(Path dir)
+      throws IOException, InterruptedException {
+    long endTime = System.currentTimeMillis() +
+        Duration.parse(DURATION_TO_WAIT_FOR_DIRECTORY).toMillis();
+    while (!dir.toFile().exists()) {
+      Thread.sleep(100);
+      if (System.currentTimeMillis() > endTime) {
+        throw new IOException("snapshot dir doesn't exist: " + dir);
+      }
+    }
+  }
+
+  @SuppressFBWarnings("NP_NULL_ON_SOME_PATH_FROM_RETURN_VALUE")
+  private void processDir(Path dir, Map<Object, Path> copyFiles,
+                          Map<Path, Path> hardLinkFiles,
+                          Set<Path> snapshotPaths)
+      throws IOException {
+    try (Stream<Path> files = Files.list(dir)) {
+      for (Path file : files.collect(Collectors.toList())) {
+        if (file.toFile().isDirectory()) {
+          // Skip any unexpected snapshot files.
+          if (file.getParent().toString().endsWith(OM_SNAPSHOT_CHECKPOINT_DIR)
+              && !snapshotPaths.contains(file)) {
+            continue;
+          }
+          processDir(file, copyFiles, hardLinkFiles, snapshotPaths);
+        } else {
+          processFile(file, copyFiles, hardLinkFiles);
+        }
+      }
+    }
+  }
+
+  private void processFile(Path file, Map<Object, Path> copyFiles,
+                           Map<Path, Path> hardLinkFiles) throws IOException {
+    // Get the inode.
+    Object key = OmSnapshotManager.getINode(file);
+    // If we already have the inode, store as hard link.
+    if (copyFiles.containsKey(key)) {
+      hardLinkFiles.put(file, copyFiles.get(key));
+    } else {
+      copyFiles.put(key, file);
+    }
+  }
+
+  // Returns value of http request parameter.
+  private boolean includeSnapshotData(HttpServletRequest request) {
+    String includeParam =
+        request.getParameter(OZONE_DB_CHECKPOINT_INCLUDE_SNAPSHOT_DATA);
+    if (StringUtils.isNotEmpty(includeParam)) {
+      return Boolean.parseBoolean(includeParam);
+    }
+    return false;
+  }
+
+  @SuppressFBWarnings({"NP_NULL_ON_SOME_PATH_FROM_RETURN_VALUE"})
+  private void writeFilesToArchive(Map<Object, Path> copyFiles,

Review Comment:
   Same as above



##########
hadoop-ozone/ozone-manager/src/main/java/org/apache/hadoop/ozone/om/OmMetadataManagerImpl.java:
##########
@@ -326,11 +333,22 @@ private OmMetadataManagerImpl(OzoneConfiguration conf, String snapshotDirName)
    */
   public static OmMetadataManagerImpl createSnapshotMetadataManager(
       OzoneConfiguration conf, String snapshotDirName) throws IOException {
+    File snapshotDir = new File(OMStorage.getOmDbDir(conf) +
+        OM_KEY_PREFIX + OM_SNAPSHOT_CHECKPOINT_DIR);
     OmMetadataManagerImpl smm = new OmMetadataManagerImpl(conf,
-        snapshotDirName);
+        snapshotDir, OM_DB_NAME + snapshotDirName);
     return smm;
   }
 
+  @SuppressFBWarnings({"NP_NULL_ON_SOME_PATH_FROM_RETURN_VALUE"})
+  public static OmMetadataManagerImpl createCheckpointMetadataManager(
+      OzoneConfiguration conf, DBCheckpoint checkpoint) throws IOException {

Review Comment:
   Same here



##########
hadoop-ozone/ozone-manager/src/main/java/org/apache/hadoop/ozone/om/OmSnapshotManager.java:
##########
@@ -279,6 +307,92 @@ private void verifySnapshotInfoForSnapDiff(final SnapshotInfo fromSnapshot,
     }
   }
 
+  /**
+   * Create file of links to add to tarball.
+   * Format of entries are either:
+   * dir1/fileTo fileFrom
+   *    for files in active db or:
+   * dir1/fileTo dir2/fileFrom
+   *    for files in another directory, (either another snapshot dir or
+   *    sst compaction backup directory)
+   * @param truncateLength - Length of initial path to trim in file path.
+   * @param hardLinkFiles - Map of link->file paths.
+   * @return Path to the file of links created.
+   */
+  @SuppressFBWarnings({"NP_NULL_ON_SOME_PATH_FROM_RETURN_VALUE"})
+  static Path createHardLinkList(int truncateLength,
+                                  Map<Path, Path> hardLinkFiles)
+      throws IOException {
+    Path data = Files.createTempFile("data", "txt");

Review Comment:
   Do we need to randomize the temp file name just in case other processes happens to use the same temp file name in tmp dir? (or is the tmp dir per-JVM already, rather than rooted under shared `/tmp/`)



##########
hadoop-ozone/ozone-manager/src/main/java/org/apache/hadoop/ozone/om/OmSnapshotManager.java:
##########
@@ -279,6 +307,92 @@ private void verifySnapshotInfoForSnapDiff(final SnapshotInfo fromSnapshot,
     }
   }
 
+  /**
+   * Create file of links to add to tarball.
+   * Format of entries are either:
+   * dir1/fileTo fileFrom
+   *    for files in active db or:
+   * dir1/fileTo dir2/fileFrom
+   *    for files in another directory, (either another snapshot dir or
+   *    sst compaction backup directory)
+   * @param truncateLength - Length of initial path to trim in file path.
+   * @param hardLinkFiles - Map of link->file paths.
+   * @return Path to the file of links created.
+   */
+  @SuppressFBWarnings({"NP_NULL_ON_SOME_PATH_FROM_RETURN_VALUE"})
+  static Path createHardLinkList(int truncateLength,
+                                  Map<Path, Path> hardLinkFiles)
+      throws IOException {
+    Path data = Files.createTempFile("data", "txt");
+    StringBuilder sb = new StringBuilder();
+    for (Map.Entry<Path, Path> entry : hardLinkFiles.entrySet()) {
+      String fixedFile = truncateFileName(truncateLength, entry.getValue());
+      // If this file is from the active db, strip the path.
+      if (fixedFile.startsWith(OM_CHECKPOINT_DIR)) {
+        fixedFile = Paths.get(fixedFile).getFileName().toString();
+      }
+      sb.append(truncateFileName(truncateLength, entry.getKey()))
+          .append("\t")
+          .append(fixedFile)
+          .append("\n");
+    }
+    Files.write(data, sb.toString().getBytes(StandardCharsets.UTF_8));
+    return data;
+  }
+
+  /**
+   * Get the filename without the introductory metadata directory.
+   *
+   * @param truncateLength Length to remove.
+   * @param file File to remove prefix from.
+   * @return Truncated string.
+   */
+  static String truncateFileName(int truncateLength, Path file) {
+    return file.toString().substring(truncateLength);
+  }
+
+  /**
+   * Create hard links listed in OM_HARDLINK_FILE.
+   *
+   * @param dbPath Path to db to have links created.
+   */
+  static void createHardLinks(Path dbPath) throws IOException {
+    File hardLinkFile = new File(dbPath.toString(),
+        OM_HARDLINK_FILE);
+    if (hardLinkFile.exists()) {
+      // Read file.
+      List<String> lines =
+          Files.lines(hardLinkFile.toPath()).collect(Collectors.toList());

Review Comment:
   Need try-with-resources to properly close the stream as well



##########
hadoop-ozone/integration-test/src/test/java/org/apache/hadoop/ozone/om/TestOMDbCheckpointServlet.java:
##########
@@ -257,63 +291,271 @@ public void testSpnegoEnabled() throws Exception {
   }
 
   @Test
-  public void testWriteCheckpointToOutputStream() throws Exception {
+  public void testWriteDbDataToStream() throws Exception {
+    prepSnapshotData();
+    // Set http param to include snapshot data.
+    when(requestMock.getParameter(OZONE_DB_CHECKPOINT_INCLUDE_SNAPSHOT_DATA))
+        .thenReturn("true");
 
+    // Get the tarball.
+    try (FileOutputStream fileOutputStream = new FileOutputStream(tempFile)) {
+      omDbCheckpointServletMock.writeDbDataToStream(dbCheckpoint, requestMock,
+          fileOutputStream);
+    }
+
+    // Untar the file into a temp folder to be examined.
     String testDirName = folder.newFolder().getAbsolutePath();
-    File checkpoint = new File(testDirName, "checkpoint");
-    checkpoint.mkdir();
-    File file = new File(checkpoint, "temp1.txt");
-    OutputStreamWriter writer = new OutputStreamWriter(
-        new FileOutputStream(file), StandardCharsets.UTF_8);
-    writer.write("Test data 1");
-    writer.close();
-
-    file = new File(checkpoint, "/temp2.txt");
-    writer = new OutputStreamWriter(
-        new FileOutputStream(file), StandardCharsets.UTF_8);
-    writer.write("Test data 2");
-    writer.close();
-
-    File outputFile =
-        new File(Paths.get(testDirName, "output_file.tar").toString());
-    TestDBCheckpoint dbCheckpoint = new TestDBCheckpoint(
-        checkpoint.toPath());
-    writeDBCheckpointToStream(dbCheckpoint,
-        new FileOutputStream(outputFile));
-    assertNotNull(outputFile);
+    int testDirLength = testDirName.length() + 1;
+    String newDbDirName = testDirName + OM_KEY_PREFIX + OM_DB_NAME;
+    int newDbDirLength = newDbDirName.length() + 1;
+    File newDbDir = new File(newDbDirName);
+    newDbDir.mkdirs();
+    FileUtil.unTar(tempFile, newDbDir);
+
+    // Move snapshot dir to correct location.
+    new File(newDbDirName, OM_SNAPSHOT_DIR)
+        .renameTo(new File(newDbDir.getParent(), OM_SNAPSHOT_DIR));
+
+
+    // Confirm the checkpoint directories match, (after remove extras).
+    Path checkpointLocation = dbCheckpoint.getCheckpointLocation();
+    Set<String> initialCheckpointSet = getFiles(checkpointLocation,
+        checkpointLocation.toString().length() + 1);
+    Path finalCheckpointLocation = Paths.get(newDbDirName);
+    Set<String> finalCheckpointSet = getFiles(finalCheckpointLocation,
+        newDbDirLength);
+
+    Assert.assertTrue("hardlink file exists in checkpoint dir",
+        finalCheckpointSet.contains(OM_HARDLINK_FILE));
+    finalCheckpointSet.remove(OM_HARDLINK_FILE);
+    Assert.assertEquals(initialCheckpointSet, finalCheckpointSet);
+
+    int metaDirLength = metaDir.toString().length() + 1;
+    String shortSnapshotLocation =
+        truncateFileName(metaDirLength, Paths.get(snapshotDirName));
+    String shortSnapshotLocation2 =
+        truncateFileName(metaDirLength, Paths.get(snapshotDirName2));
+    String shortCompactionDirLocation =
+        truncateFileName(metaDirLength, compactionDirPath);
+
+    Set<String> finalFullSet =
+        getFiles(Paths.get(testDirName, OM_SNAPSHOT_DIR), testDirLength);
+
+    // Check each line in the hard link file.
+    Stream<String> lines = Files.lines(Paths.get(newDbDirName,
+        OM_HARDLINK_FILE));
+
+    List<String> fabricatedLinkLines = new ArrayList<>();
+    for (String line: lines.collect(Collectors.toList())) {
+      Assert.assertFalse("CURRENT file is not a hard link",
+          line.contains("CURRENT"));
+      if (line.contains("fabricatedFile")) {
+        fabricatedLinkLines.add(line);
+      } else {
+        checkLine(shortSnapshotLocation, shortSnapshotLocation2, line);
+        // add links to the final set
+        finalFullSet.add(line.split("\t")[0]);
+      }
+    }
+
+    Set<String> directories = Sets.newHashSet(
+        shortSnapshotLocation, shortSnapshotLocation2,
+        shortCompactionDirLocation);
+    checkFabricatedLines(directories, fabricatedLinkLines, testDirName);
+
+    Set<String> initialFullSet =
+        getFiles(Paths.get(metaDir.toString(), OM_SNAPSHOT_DIR), metaDirLength);
+    Assert.assertEquals("found expected snapshot files",
+        initialFullSet, finalFullSet);
   }
-}
 
-class TestDBCheckpoint implements DBCheckpoint {
+  @Test
+  public void testWriteDbDataWithoutOmSnapshot()
+      throws Exception {
+    prepSnapshotData();
+
+    // Set http param to exclude snapshot data.
+    when(requestMock.getParameter(OZONE_DB_CHECKPOINT_INCLUDE_SNAPSHOT_DATA))
+        .thenReturn(null);
+
+    // Get the tarball.
+    try (FileOutputStream fileOutputStream = new FileOutputStream(tempFile)) {
+      omDbCheckpointServletMock.writeDbDataToStream(dbCheckpoint, requestMock,
+          fileOutputStream);
+    }
+
+    // Untar the file into a temp folder to be examined.
+    String testDirName = folder.newFolder().getAbsolutePath();
+    int testDirLength = testDirName.length() + 1;
+    FileUtil.unTar(tempFile, new File(testDirName));
+
+    // Confirm the checkpoint directories match.
+    Path checkpointLocation = dbCheckpoint.getCheckpointLocation();
+    Set<String> initialCheckpointSet = getFiles(checkpointLocation,
+        checkpointLocation.toString().length() + 1);
+    Path finalCheckpointLocation = Paths.get(testDirName);
+    Set<String> finalCheckpointSet = getFiles(finalCheckpointLocation,
+        testDirLength);
+
+    Assert.assertEquals(initialCheckpointSet, finalCheckpointSet);
+  }
+
+
 
-  private final Path checkpointFile;
+  private void prepSnapshotData() throws Exception {
+    setupCluster();
+    metaDir = OMStorage.getOmDbDir(conf);
+
+    OzoneBucket bucket = TestDataUtil.createVolumeAndBucket(cluster);
+
+    // Create dummy keys for snapshotting.
+    TestDataUtil.createKey(bucket, UUID.randomUUID().toString(),
+        "content");
+    TestDataUtil.createKey(bucket, UUID.randomUUID().toString(),
+        "content");
+
+    // This sleep can be removed after this is fixed:
+    // https://issues.apache.org/jira/browse/HDDS-7279
+    Thread.sleep(2000);
+    snapshotDirName =
+        createSnapshot(bucket.getVolumeName(), bucket.getName());
+    snapshotDirName2 =
+        createSnapshot(bucket.getVolumeName(), bucket.getName());
+
+    // Create dummy snapshot to make sure it is not included.
+    Path fabricatedSnapshot  = Paths.get(
+        new File(snapshotDirName).getParent(),
+        "fabricatedSnapshot");
+    fabricatedSnapshot.toFile().mkdirs();
+    Paths.get(fabricatedSnapshot.toString(), "fabricatedFile")
+        .toFile().createNewFile();

Review Comment:
   ```suggestion
       Assert.assertTrue(Paths.get(fabricatedSnapshot.toString(), "fabricatedFile")
           .toFile().createNewFile());
   ```



##########
hadoop-ozone/ozone-manager/src/main/java/org/apache/hadoop/ozone/om/OmSnapshotManager.java:
##########
@@ -279,6 +307,92 @@ private void verifySnapshotInfoForSnapDiff(final SnapshotInfo fromSnapshot,
     }
   }
 
+  /**
+   * Create file of links to add to tarball.
+   * Format of entries are either:
+   * dir1/fileTo fileFrom
+   *    for files in active db or:
+   * dir1/fileTo dir2/fileFrom
+   *    for files in another directory, (either another snapshot dir or
+   *    sst compaction backup directory)
+   * @param truncateLength - Length of initial path to trim in file path.
+   * @param hardLinkFiles - Map of link->file paths.
+   * @return Path to the file of links created.
+   */
+  @SuppressFBWarnings({"NP_NULL_ON_SOME_PATH_FROM_RETURN_VALUE"})
+  static Path createHardLinkList(int truncateLength,
+                                  Map<Path, Path> hardLinkFiles)
+      throws IOException {
+    Path data = Files.createTempFile("data", "txt");
+    StringBuilder sb = new StringBuilder();
+    for (Map.Entry<Path, Path> entry : hardLinkFiles.entrySet()) {
+      String fixedFile = truncateFileName(truncateLength, entry.getValue());
+      // If this file is from the active db, strip the path.
+      if (fixedFile.startsWith(OM_CHECKPOINT_DIR)) {
+        fixedFile = Paths.get(fixedFile).getFileName().toString();
+      }
+      sb.append(truncateFileName(truncateLength, entry.getKey()))
+          .append("\t")
+          .append(fixedFile)
+          .append("\n");
+    }
+    Files.write(data, sb.toString().getBytes(StandardCharsets.UTF_8));
+    return data;
+  }
+
+  /**
+   * Get the filename without the introductory metadata directory.
+   *
+   * @param truncateLength Length to remove.
+   * @param file File to remove prefix from.
+   * @return Truncated string.
+   */
+  static String truncateFileName(int truncateLength, Path file) {
+    return file.toString().substring(truncateLength);
+  }
+
+  /**
+   * Create hard links listed in OM_HARDLINK_FILE.
+   *
+   * @param dbPath Path to db to have links created.
+   */
+  static void createHardLinks(Path dbPath) throws IOException {
+    File hardLinkFile = new File(dbPath.toString(),
+        OM_HARDLINK_FILE);
+    if (hardLinkFile.exists()) {
+      // Read file.
+      List<String> lines =
+          Files.lines(hardLinkFile.toPath()).collect(Collectors.toList());
+
+      // Create a link for each line.
+      for (String l : lines) {
+        String from = l.split("\t")[1];
+        String to = l.split("\t")[0];
+        Path fullFromPath = getFullPath(dbPath, from);
+        Path fullToPath = getFullPath(dbPath, to);
+        Files.createLink(fullToPath, fullFromPath);
+      }
+      if (!hardLinkFile.delete()) {
+        throw new IOException(
+            "Failed to delete: " + hardLinkFile);
+      }
+    }
+  }
+
+
+  // Prepend the full path to the hard link entry entry.
+  @SuppressFBWarnings({"NP_NULL_ON_SOME_PATH_FROM_RETURN_VALUE"})
+  private static Path getFullPath(Path dbPath, String fileName) {

Review Comment:
   Same here



##########
hadoop-ozone/integration-test/src/test/java/org/apache/hadoop/ozone/om/TestOMRatisSnapshots.java:
##########
@@ -543,6 +559,38 @@ public void testInstallCorruptedCheckpointFailure() throws Exception {
     Assert.assertTrue(logCapture.getOutput().contains(msg));
   }
 
+  private void createSnapshot(OzoneManager leaderOM, List<String> keys)

Review Comment:
   We could rename this to `createOzoneSnapshot` in the context of Ratis.



##########
hadoop-ozone/integration-test/src/test/java/org/apache/hadoop/ozone/om/TestOMDbCheckpointServlet.java:
##########
@@ -257,63 +291,271 @@ public void testSpnegoEnabled() throws Exception {
   }
 
   @Test
-  public void testWriteCheckpointToOutputStream() throws Exception {
+  public void testWriteDbDataToStream() throws Exception {
+    prepSnapshotData();
+    // Set http param to include snapshot data.
+    when(requestMock.getParameter(OZONE_DB_CHECKPOINT_INCLUDE_SNAPSHOT_DATA))
+        .thenReturn("true");
 
+    // Get the tarball.
+    try (FileOutputStream fileOutputStream = new FileOutputStream(tempFile)) {
+      omDbCheckpointServletMock.writeDbDataToStream(dbCheckpoint, requestMock,
+          fileOutputStream);
+    }
+
+    // Untar the file into a temp folder to be examined.
     String testDirName = folder.newFolder().getAbsolutePath();
-    File checkpoint = new File(testDirName, "checkpoint");
-    checkpoint.mkdir();
-    File file = new File(checkpoint, "temp1.txt");
-    OutputStreamWriter writer = new OutputStreamWriter(
-        new FileOutputStream(file), StandardCharsets.UTF_8);
-    writer.write("Test data 1");
-    writer.close();
-
-    file = new File(checkpoint, "/temp2.txt");
-    writer = new OutputStreamWriter(
-        new FileOutputStream(file), StandardCharsets.UTF_8);
-    writer.write("Test data 2");
-    writer.close();
-
-    File outputFile =
-        new File(Paths.get(testDirName, "output_file.tar").toString());
-    TestDBCheckpoint dbCheckpoint = new TestDBCheckpoint(
-        checkpoint.toPath());
-    writeDBCheckpointToStream(dbCheckpoint,
-        new FileOutputStream(outputFile));
-    assertNotNull(outputFile);
+    int testDirLength = testDirName.length() + 1;
+    String newDbDirName = testDirName + OM_KEY_PREFIX + OM_DB_NAME;
+    int newDbDirLength = newDbDirName.length() + 1;
+    File newDbDir = new File(newDbDirName);
+    newDbDir.mkdirs();
+    FileUtil.unTar(tempFile, newDbDir);
+
+    // Move snapshot dir to correct location.
+    new File(newDbDirName, OM_SNAPSHOT_DIR)
+        .renameTo(new File(newDbDir.getParent(), OM_SNAPSHOT_DIR));
+
+
+    // Confirm the checkpoint directories match, (after remove extras).
+    Path checkpointLocation = dbCheckpoint.getCheckpointLocation();
+    Set<String> initialCheckpointSet = getFiles(checkpointLocation,
+        checkpointLocation.toString().length() + 1);
+    Path finalCheckpointLocation = Paths.get(newDbDirName);
+    Set<String> finalCheckpointSet = getFiles(finalCheckpointLocation,
+        newDbDirLength);
+
+    Assert.assertTrue("hardlink file exists in checkpoint dir",
+        finalCheckpointSet.contains(OM_HARDLINK_FILE));
+    finalCheckpointSet.remove(OM_HARDLINK_FILE);
+    Assert.assertEquals(initialCheckpointSet, finalCheckpointSet);
+
+    int metaDirLength = metaDir.toString().length() + 1;
+    String shortSnapshotLocation =
+        truncateFileName(metaDirLength, Paths.get(snapshotDirName));
+    String shortSnapshotLocation2 =
+        truncateFileName(metaDirLength, Paths.get(snapshotDirName2));
+    String shortCompactionDirLocation =
+        truncateFileName(metaDirLength, compactionDirPath);
+
+    Set<String> finalFullSet =
+        getFiles(Paths.get(testDirName, OM_SNAPSHOT_DIR), testDirLength);
+
+    // Check each line in the hard link file.
+    Stream<String> lines = Files.lines(Paths.get(newDbDirName,
+        OM_HARDLINK_FILE));
+
+    List<String> fabricatedLinkLines = new ArrayList<>();
+    for (String line: lines.collect(Collectors.toList())) {
+      Assert.assertFalse("CURRENT file is not a hard link",
+          line.contains("CURRENT"));
+      if (line.contains("fabricatedFile")) {
+        fabricatedLinkLines.add(line);
+      } else {
+        checkLine(shortSnapshotLocation, shortSnapshotLocation2, line);
+        // add links to the final set
+        finalFullSet.add(line.split("\t")[0]);
+      }
+    }
+
+    Set<String> directories = Sets.newHashSet(
+        shortSnapshotLocation, shortSnapshotLocation2,
+        shortCompactionDirLocation);
+    checkFabricatedLines(directories, fabricatedLinkLines, testDirName);
+
+    Set<String> initialFullSet =
+        getFiles(Paths.get(metaDir.toString(), OM_SNAPSHOT_DIR), metaDirLength);
+    Assert.assertEquals("found expected snapshot files",
+        initialFullSet, finalFullSet);
   }
-}
 
-class TestDBCheckpoint implements DBCheckpoint {
+  @Test
+  public void testWriteDbDataWithoutOmSnapshot()
+      throws Exception {
+    prepSnapshotData();
+
+    // Set http param to exclude snapshot data.
+    when(requestMock.getParameter(OZONE_DB_CHECKPOINT_INCLUDE_SNAPSHOT_DATA))
+        .thenReturn(null);
+
+    // Get the tarball.
+    try (FileOutputStream fileOutputStream = new FileOutputStream(tempFile)) {
+      omDbCheckpointServletMock.writeDbDataToStream(dbCheckpoint, requestMock,
+          fileOutputStream);
+    }
+
+    // Untar the file into a temp folder to be examined.
+    String testDirName = folder.newFolder().getAbsolutePath();
+    int testDirLength = testDirName.length() + 1;
+    FileUtil.unTar(tempFile, new File(testDirName));
+
+    // Confirm the checkpoint directories match.
+    Path checkpointLocation = dbCheckpoint.getCheckpointLocation();
+    Set<String> initialCheckpointSet = getFiles(checkpointLocation,
+        checkpointLocation.toString().length() + 1);
+    Path finalCheckpointLocation = Paths.get(testDirName);
+    Set<String> finalCheckpointSet = getFiles(finalCheckpointLocation,
+        testDirLength);
+
+    Assert.assertEquals(initialCheckpointSet, finalCheckpointSet);
+  }
+
+
 
-  private final Path checkpointFile;
+  private void prepSnapshotData() throws Exception {
+    setupCluster();
+    metaDir = OMStorage.getOmDbDir(conf);
+
+    OzoneBucket bucket = TestDataUtil.createVolumeAndBucket(cluster);
+
+    // Create dummy keys for snapshotting.
+    TestDataUtil.createKey(bucket, UUID.randomUUID().toString(),
+        "content");
+    TestDataUtil.createKey(bucket, UUID.randomUUID().toString(),
+        "content");
+
+    // This sleep can be removed after this is fixed:
+    // https://issues.apache.org/jira/browse/HDDS-7279
+    Thread.sleep(2000);

Review Comment:
   Looks like we can remove this now that HDDS-7279 is resolved :)



##########
hadoop-ozone/integration-test/src/test/java/org/apache/hadoop/ozone/om/TestOMDbCheckpointServlet.java:
##########
@@ -257,63 +291,271 @@ public void testSpnegoEnabled() throws Exception {
   }
 
   @Test
-  public void testWriteCheckpointToOutputStream() throws Exception {
+  public void testWriteDbDataToStream() throws Exception {
+    prepSnapshotData();
+    // Set http param to include snapshot data.
+    when(requestMock.getParameter(OZONE_DB_CHECKPOINT_INCLUDE_SNAPSHOT_DATA))
+        .thenReturn("true");
 
+    // Get the tarball.
+    try (FileOutputStream fileOutputStream = new FileOutputStream(tempFile)) {
+      omDbCheckpointServletMock.writeDbDataToStream(dbCheckpoint, requestMock,
+          fileOutputStream);
+    }
+
+    // Untar the file into a temp folder to be examined.
     String testDirName = folder.newFolder().getAbsolutePath();
-    File checkpoint = new File(testDirName, "checkpoint");
-    checkpoint.mkdir();
-    File file = new File(checkpoint, "temp1.txt");
-    OutputStreamWriter writer = new OutputStreamWriter(
-        new FileOutputStream(file), StandardCharsets.UTF_8);
-    writer.write("Test data 1");
-    writer.close();
-
-    file = new File(checkpoint, "/temp2.txt");
-    writer = new OutputStreamWriter(
-        new FileOutputStream(file), StandardCharsets.UTF_8);
-    writer.write("Test data 2");
-    writer.close();
-
-    File outputFile =
-        new File(Paths.get(testDirName, "output_file.tar").toString());
-    TestDBCheckpoint dbCheckpoint = new TestDBCheckpoint(
-        checkpoint.toPath());
-    writeDBCheckpointToStream(dbCheckpoint,
-        new FileOutputStream(outputFile));
-    assertNotNull(outputFile);
+    int testDirLength = testDirName.length() + 1;
+    String newDbDirName = testDirName + OM_KEY_PREFIX + OM_DB_NAME;
+    int newDbDirLength = newDbDirName.length() + 1;
+    File newDbDir = new File(newDbDirName);
+    newDbDir.mkdirs();
+    FileUtil.unTar(tempFile, newDbDir);
+
+    // Move snapshot dir to correct location.
+    new File(newDbDirName, OM_SNAPSHOT_DIR)
+        .renameTo(new File(newDbDir.getParent(), OM_SNAPSHOT_DIR));
+
+
+    // Confirm the checkpoint directories match, (after remove extras).
+    Path checkpointLocation = dbCheckpoint.getCheckpointLocation();
+    Set<String> initialCheckpointSet = getFiles(checkpointLocation,
+        checkpointLocation.toString().length() + 1);
+    Path finalCheckpointLocation = Paths.get(newDbDirName);
+    Set<String> finalCheckpointSet = getFiles(finalCheckpointLocation,
+        newDbDirLength);
+
+    Assert.assertTrue("hardlink file exists in checkpoint dir",
+        finalCheckpointSet.contains(OM_HARDLINK_FILE));
+    finalCheckpointSet.remove(OM_HARDLINK_FILE);
+    Assert.assertEquals(initialCheckpointSet, finalCheckpointSet);
+
+    int metaDirLength = metaDir.toString().length() + 1;
+    String shortSnapshotLocation =
+        truncateFileName(metaDirLength, Paths.get(snapshotDirName));
+    String shortSnapshotLocation2 =
+        truncateFileName(metaDirLength, Paths.get(snapshotDirName2));
+    String shortCompactionDirLocation =
+        truncateFileName(metaDirLength, compactionDirPath);
+
+    Set<String> finalFullSet =
+        getFiles(Paths.get(testDirName, OM_SNAPSHOT_DIR), testDirLength);
+
+    // Check each line in the hard link file.
+    Stream<String> lines = Files.lines(Paths.get(newDbDirName,
+        OM_HARDLINK_FILE));
+
+    List<String> fabricatedLinkLines = new ArrayList<>();
+    for (String line: lines.collect(Collectors.toList())) {
+      Assert.assertFalse("CURRENT file is not a hard link",
+          line.contains("CURRENT"));
+      if (line.contains("fabricatedFile")) {
+        fabricatedLinkLines.add(line);
+      } else {
+        checkLine(shortSnapshotLocation, shortSnapshotLocation2, line);
+        // add links to the final set
+        finalFullSet.add(line.split("\t")[0]);
+      }
+    }
+
+    Set<String> directories = Sets.newHashSet(
+        shortSnapshotLocation, shortSnapshotLocation2,
+        shortCompactionDirLocation);
+    checkFabricatedLines(directories, fabricatedLinkLines, testDirName);
+
+    Set<String> initialFullSet =
+        getFiles(Paths.get(metaDir.toString(), OM_SNAPSHOT_DIR), metaDirLength);
+    Assert.assertEquals("found expected snapshot files",
+        initialFullSet, finalFullSet);
   }
-}
 
-class TestDBCheckpoint implements DBCheckpoint {
+  @Test
+  public void testWriteDbDataWithoutOmSnapshot()
+      throws Exception {
+    prepSnapshotData();
+
+    // Set http param to exclude snapshot data.
+    when(requestMock.getParameter(OZONE_DB_CHECKPOINT_INCLUDE_SNAPSHOT_DATA))
+        .thenReturn(null);
+
+    // Get the tarball.
+    try (FileOutputStream fileOutputStream = new FileOutputStream(tempFile)) {
+      omDbCheckpointServletMock.writeDbDataToStream(dbCheckpoint, requestMock,
+          fileOutputStream);
+    }
+
+    // Untar the file into a temp folder to be examined.
+    String testDirName = folder.newFolder().getAbsolutePath();
+    int testDirLength = testDirName.length() + 1;
+    FileUtil.unTar(tempFile, new File(testDirName));
+
+    // Confirm the checkpoint directories match.
+    Path checkpointLocation = dbCheckpoint.getCheckpointLocation();
+    Set<String> initialCheckpointSet = getFiles(checkpointLocation,
+        checkpointLocation.toString().length() + 1);
+    Path finalCheckpointLocation = Paths.get(testDirName);
+    Set<String> finalCheckpointSet = getFiles(finalCheckpointLocation,
+        testDirLength);
+
+    Assert.assertEquals(initialCheckpointSet, finalCheckpointSet);
+  }
+
+
 
-  private final Path checkpointFile;
+  private void prepSnapshotData() throws Exception {
+    setupCluster();
+    metaDir = OMStorage.getOmDbDir(conf);
+
+    OzoneBucket bucket = TestDataUtil.createVolumeAndBucket(cluster);
+
+    // Create dummy keys for snapshotting.
+    TestDataUtil.createKey(bucket, UUID.randomUUID().toString(),
+        "content");
+    TestDataUtil.createKey(bucket, UUID.randomUUID().toString(),
+        "content");
+
+    // This sleep can be removed after this is fixed:
+    // https://issues.apache.org/jira/browse/HDDS-7279
+    Thread.sleep(2000);
+    snapshotDirName =
+        createSnapshot(bucket.getVolumeName(), bucket.getName());
+    snapshotDirName2 =
+        createSnapshot(bucket.getVolumeName(), bucket.getName());
+
+    // Create dummy snapshot to make sure it is not included.
+    Path fabricatedSnapshot  = Paths.get(
+        new File(snapshotDirName).getParent(),
+        "fabricatedSnapshot");
+    fabricatedSnapshot.toFile().mkdirs();
+    Paths.get(fabricatedSnapshot.toString(), "fabricatedFile")
+        .toFile().createNewFile();
+
+    // Create fabricated links to snapshot dirs
+    // to confirm that links are recognized even if
+    // they are don't point to the checkpoint directory.
+    Path fabricatedFile = Paths.get(snapshotDirName, "fabricatedFile");
+    Path fabricatedLink = Paths.get(snapshotDirName2, "fabricatedFile");
+
+    Files.write(fabricatedFile,
+        "fabricatedData".getBytes(StandardCharsets.UTF_8));
+    Files.createLink(fabricatedLink, fabricatedFile);
+
+    // Simulate links from the compaction dir.
+    compactionDirPath = Paths.get(metaDir.toString(),
+        OM_SNAPSHOT_DIFF_DIR, OM_COMPACTION_BACKUP_DIR);
+    Path fabricatedLink2 = Paths.get(compactionDirPath.toString(),
+        "fabricatedFile");
+    Files.createLink(fabricatedLink2, fabricatedFile);
+    Path currentFile = Paths.get(metaDir.toString(),
+                                    OM_DB_NAME, "CURRENT");
+    Path currentLink = Paths.get(compactionDirPath.toString(), "CURRENT");
+    Files.createLink(currentLink, currentFile);
+
+    dbCheckpoint = cluster.getOzoneManager()
+        .getMetadataManager().getStore()
+        .getCheckpoint(true);
 
-  TestDBCheckpoint(Path checkpointFile) {
-    this.checkpointFile = checkpointFile;
   }
 
-  @Override
-  public Path getCheckpointLocation() {
-    return checkpointFile;
+  private String createSnapshot(String vname, String bname)
+      throws IOException, InterruptedException, TimeoutException {
+    final OzoneManager om = cluster.getOzoneManager();
+    String snapshotName = UUID.randomUUID().toString();
+    OzoneManagerProtocol writeClient = cluster.getRpcClient().getObjectStore()
+        .getClientProxy().getOzoneManagerClient();
+
+    writeClient.createSnapshot(vname, bname, snapshotName);
+    SnapshotInfo snapshotInfo = om.getMetadataManager().getSnapshotInfoTable()
+        .get(SnapshotInfo.getTableKey(vname, bname, snapshotName));
+    String snapshotPath = getSnapshotPath(conf, snapshotInfo)
+        + OM_KEY_PREFIX;
+    GenericTestUtils.waitFor(() -> new File(snapshotPath).exists(),
+        100, 2000);
+    return snapshotPath;
   }
 
-  @Override
-  public long getCheckpointTimestamp() {
-    return 0;
+  private Set<String> getFiles(Path path, int truncateLength)
+      throws IOException {
+    return getFiles(path, truncateLength, new HashSet<>());
   }
 
-  @Override
-  public long getLatestSequenceNumber() {
-    return 0;
+  // Get all files below path, recursively, (skipping fabricated files).
+  @SuppressFBWarnings({"NP_NULL_ON_SOME_PATH_FROM_RETURN_VALUE"})
+  private Set<String> getFiles(Path path, int truncateLength,
+      Set<String> fileSet) throws IOException {
+    try (Stream<Path> files = Files.list(path)) {
+      for (Path file : files.collect(Collectors.toList())) {
+        if (file.toFile().isDirectory()) {
+          getFiles(file, truncateLength, fileSet);
+        }
+        if (!file.getFileName().toString().startsWith("fabricated")) {
+          fileSet.add(truncateFileName(truncateLength, file));
+        }
+      }
+    }
+    return fileSet;
   }
 
-  @Override
-  public long checkpointCreationTimeTaken() {
-    return 0;
+  /**
+   * Confirm fabricated link lines in hardlink file are properly
+   * formatted: "dir1/fabricatedFile dir2/fabricatedFile".
+   *
+   * The "fabricated" files/links are ones I've created by hand to
+   * fully test the code, (as opposed to the "natural" files/links
+   * created by the create snapshot process).
+   *
+   * @param directories Possible directories for the links to exist in.
+   * @param lines Text lines defining the link paths.
+   * @param testDirName Name of test directory.
+   */
+  @SuppressFBWarnings({"NP_NULL_ON_SOME_PATH_FROM_RETURN_VALUE"})
+  private void checkFabricatedLines(Set<String> directories, List<String> lines,
+                                    String testDirName) {
+    // find the real file

Review Comment:
   Excellent javadoc!



##########
hadoop-ozone/ozone-manager/src/main/java/org/apache/hadoop/ozone/om/OMDBCheckpointServlet.java:
##########
@@ -82,4 +113,166 @@ public void init() throws ServletException {
         allowedGroups,
         om.isSpnegoEnabled());
   }
+
+  @Override
+  public void writeDbDataToStream(DBCheckpoint checkpoint,
+                                  HttpServletRequest request,
+                                  OutputStream destination)
+      throws IOException, InterruptedException {
+    // Map of inodes to path.
+    Map<Object, Path> copyFiles = new HashMap<>();
+    // Map of link to path.
+    Map<Path, Path> hardLinkFiles = new HashMap<>();
+
+    getFilesForArchive(checkpoint, copyFiles, hardLinkFiles,
+        includeSnapshotData(request));
+
+    try (TarArchiveOutputStream archiveOutputStream =
+            new TarArchiveOutputStream(destination)) {
+      archiveOutputStream
+          .setLongFileMode(TarArchiveOutputStream.LONGFILE_POSIX);
+      writeFilesToArchive(copyFiles, hardLinkFiles, archiveOutputStream);
+    }
+  }
+
+  private void getFilesForArchive(DBCheckpoint checkpoint,
+                                  Map<Object, Path> copyFiles,
+                                  Map<Path, Path> hardLinkFiles,
+                                  boolean includeSnapshotData)
+      throws IOException, InterruptedException {
+
+    // Get the active fs files.
+    Path dir = checkpoint.getCheckpointLocation();
+    processDir(dir, copyFiles, hardLinkFiles, new HashSet<>());
+
+    if (!includeSnapshotData) {
+      return;
+    }
+
+    // Get the snapshot files.
+    Set<Path> snapshotPaths = waitForSnapshotDirs(checkpoint);
+    Path snapshotDir = Paths.get(OMStorage.getOmDbDir(getConf()).toString(),
+        OM_SNAPSHOT_DIR);
+    processDir(snapshotDir, copyFiles, hardLinkFiles, snapshotPaths);
+  }
+
+  /**
+   * The snapshotInfo table may contain a snapshot that
+   * doesn't yet exist on the fs, so wait a few seconds for it.
+   * @param checkpoint Checkpoint containing snapshot entries expected.
+   * @return Set of expected snapshot dirs.
+   */
+  private Set<Path> waitForSnapshotDirs(DBCheckpoint checkpoint)
+      throws IOException, InterruptedException {
+
+    OzoneConfiguration conf = getConf();
+
+    Set<Path> snapshotPaths = new HashSet<>();
+
+    // get snapshotInfo entries
+    OmMetadataManagerImpl checkpointMetadataManager =
+        OmMetadataManagerImpl.createCheckpointMetadataManager(
+            conf, checkpoint);
+    try (TableIterator<String, ? extends Table.KeyValue<String, SnapshotInfo>>
+        iterator = checkpointMetadataManager
+        .getSnapshotInfoTable().iterator()) {
+
+      // For each entry, wait for corresponding directory.
+      while (iterator.hasNext()) {
+        Table.KeyValue<String, SnapshotInfo> entry = iterator.next();
+        Path path = Paths.get(getSnapshotPath(conf, entry.getValue()));
+        waitForDirToExist(path);
+        snapshotPaths.add(path);
+      }
+    }
+    return snapshotPaths;
+  }
+
+  private void waitForDirToExist(Path dir)
+      throws IOException, InterruptedException {
+    long endTime = System.currentTimeMillis() +
+        Duration.parse(DURATION_TO_WAIT_FOR_DIRECTORY).toMillis();
+    while (!dir.toFile().exists()) {
+      Thread.sleep(100);
+      if (System.currentTimeMillis() > endTime) {
+        throw new IOException("snapshot dir doesn't exist: " + dir);
+      }
+    }
+  }

Review Comment:
   Ideally we would want to use something like [fsnotify](https://github.com/fsnotify/fsnotify#readme). But if there is no easy way to do this in Java, I guess this is good enough for now.



##########
hadoop-ozone/ozone-manager/src/main/java/org/apache/hadoop/ozone/om/OMDBCheckpointServlet.java:
##########
@@ -82,4 +113,166 @@ public void init() throws ServletException {
         allowedGroups,
         om.isSpnegoEnabled());
   }
+
+  @Override
+  public void writeDbDataToStream(DBCheckpoint checkpoint,
+                                  HttpServletRequest request,
+                                  OutputStream destination)
+      throws IOException, InterruptedException {
+    // Map of inodes to path.
+    Map<Object, Path> copyFiles = new HashMap<>();
+    // Map of link to path.
+    Map<Path, Path> hardLinkFiles = new HashMap<>();
+
+    getFilesForArchive(checkpoint, copyFiles, hardLinkFiles,
+        includeSnapshotData(request));
+
+    try (TarArchiveOutputStream archiveOutputStream =
+            new TarArchiveOutputStream(destination)) {
+      archiveOutputStream
+          .setLongFileMode(TarArchiveOutputStream.LONGFILE_POSIX);
+      writeFilesToArchive(copyFiles, hardLinkFiles, archiveOutputStream);
+    }
+  }
+
+  private void getFilesForArchive(DBCheckpoint checkpoint,
+                                  Map<Object, Path> copyFiles,
+                                  Map<Path, Path> hardLinkFiles,
+                                  boolean includeSnapshotData)
+      throws IOException, InterruptedException {
+
+    // Get the active fs files.
+    Path dir = checkpoint.getCheckpointLocation();
+    processDir(dir, copyFiles, hardLinkFiles, new HashSet<>());
+
+    if (!includeSnapshotData) {
+      return;
+    }
+
+    // Get the snapshot files.
+    Set<Path> snapshotPaths = waitForSnapshotDirs(checkpoint);
+    Path snapshotDir = Paths.get(OMStorage.getOmDbDir(getConf()).toString(),
+        OM_SNAPSHOT_DIR);
+    processDir(snapshotDir, copyFiles, hardLinkFiles, snapshotPaths);
+  }
+
+  /**
+   * The snapshotInfo table may contain a snapshot that
+   * doesn't yet exist on the fs, so wait a few seconds for it.
+   * @param checkpoint Checkpoint containing snapshot entries expected.
+   * @return Set of expected snapshot dirs.
+   */
+  private Set<Path> waitForSnapshotDirs(DBCheckpoint checkpoint)
+      throws IOException, InterruptedException {
+
+    OzoneConfiguration conf = getConf();
+
+    Set<Path> snapshotPaths = new HashSet<>();
+
+    // get snapshotInfo entries
+    OmMetadataManagerImpl checkpointMetadataManager =
+        OmMetadataManagerImpl.createCheckpointMetadataManager(
+            conf, checkpoint);
+    try (TableIterator<String, ? extends Table.KeyValue<String, SnapshotInfo>>
+        iterator = checkpointMetadataManager
+        .getSnapshotInfoTable().iterator()) {
+
+      // For each entry, wait for corresponding directory.
+      while (iterator.hasNext()) {
+        Table.KeyValue<String, SnapshotInfo> entry = iterator.next();
+        Path path = Paths.get(getSnapshotPath(conf, entry.getValue()));
+        waitForDirToExist(path);
+        snapshotPaths.add(path);
+      }
+    }
+    return snapshotPaths;
+  }
+
+  private void waitForDirToExist(Path dir)
+      throws IOException, InterruptedException {
+    long endTime = System.currentTimeMillis() +
+        Duration.parse(DURATION_TO_WAIT_FOR_DIRECTORY).toMillis();
+    while (!dir.toFile().exists()) {
+      Thread.sleep(100);
+      if (System.currentTimeMillis() > endTime) {
+        throw new IOException("snapshot dir doesn't exist: " + dir);
+      }
+    }
+  }
+
+  @SuppressFBWarnings("NP_NULL_ON_SOME_PATH_FROM_RETURN_VALUE")
+  private void processDir(Path dir, Map<Object, Path> copyFiles,
+                          Map<Path, Path> hardLinkFiles,
+                          Set<Path> snapshotPaths)
+      throws IOException {
+    try (Stream<Path> files = Files.list(dir)) {
+      for (Path file : files.collect(Collectors.toList())) {
+        if (file.toFile().isDirectory()) {
+          // Skip any unexpected snapshot files.
+          if (file.getParent().toString().endsWith(OM_SNAPSHOT_CHECKPOINT_DIR)
+              && !snapshotPaths.contains(file)) {
+            continue;
+          }

Review Comment:
   Do we want to log those "unexpected snapshot files"? Is this worth a `LOG.warn()`? Or at least `LOG.debug()` for debuggability.



##########
hadoop-ozone/ozone-manager/src/main/java/org/apache/hadoop/ozone/om/OmSnapshotManager.java:
##########
@@ -279,6 +307,92 @@ private void verifySnapshotInfoForSnapDiff(final SnapshotInfo fromSnapshot,
     }
   }
 
+  /**
+   * Create file of links to add to tarball.
+   * Format of entries are either:
+   * dir1/fileTo fileFrom
+   *    for files in active db or:
+   * dir1/fileTo dir2/fileFrom
+   *    for files in another directory, (either another snapshot dir or
+   *    sst compaction backup directory)
+   * @param truncateLength - Length of initial path to trim in file path.
+   * @param hardLinkFiles - Map of link->file paths.
+   * @return Path to the file of links created.
+   */
+  @SuppressFBWarnings({"NP_NULL_ON_SOME_PATH_FROM_RETURN_VALUE"})
+  static Path createHardLinkList(int truncateLength,
+                                  Map<Path, Path> hardLinkFiles)
+      throws IOException {

Review Comment:
   Same here



##########
hadoop-ozone/ozone-manager/src/main/java/org/apache/hadoop/ozone/om/OmSnapshotManager.java:
##########
@@ -279,6 +307,92 @@ private void verifySnapshotInfoForSnapDiff(final SnapshotInfo fromSnapshot,
     }
   }
 
+  /**
+   * Create file of links to add to tarball.
+   * Format of entries are either:
+   * dir1/fileTo fileFrom
+   *    for files in active db or:
+   * dir1/fileTo dir2/fileFrom
+   *    for files in another directory, (either another snapshot dir or
+   *    sst compaction backup directory)
+   * @param truncateLength - Length of initial path to trim in file path.
+   * @param hardLinkFiles - Map of link->file paths.
+   * @return Path to the file of links created.
+   */
+  @SuppressFBWarnings({"NP_NULL_ON_SOME_PATH_FROM_RETURN_VALUE"})
+  static Path createHardLinkList(int truncateLength,
+                                  Map<Path, Path> hardLinkFiles)
+      throws IOException {
+    Path data = Files.createTempFile("data", "txt");
+    StringBuilder sb = new StringBuilder();
+    for (Map.Entry<Path, Path> entry : hardLinkFiles.entrySet()) {
+      String fixedFile = truncateFileName(truncateLength, entry.getValue());
+      // If this file is from the active db, strip the path.
+      if (fixedFile.startsWith(OM_CHECKPOINT_DIR)) {
+        fixedFile = Paths.get(fixedFile).getFileName().toString();
+      }
+      sb.append(truncateFileName(truncateLength, entry.getKey()))
+          .append("\t")
+          .append(fixedFile)
+          .append("\n");
+    }
+    Files.write(data, sb.toString().getBytes(StandardCharsets.UTF_8));
+    return data;
+  }
+
+  /**
+   * Get the filename without the introductory metadata directory.
+   *
+   * @param truncateLength Length to remove.
+   * @param file File to remove prefix from.
+   * @return Truncated string.
+   */
+  static String truncateFileName(int truncateLength, Path file) {
+    return file.toString().substring(truncateLength);
+  }
+
+  /**
+   * Create hard links listed in OM_HARDLINK_FILE.
+   *
+   * @param dbPath Path to db to have links created.
+   */
+  static void createHardLinks(Path dbPath) throws IOException {
+    File hardLinkFile = new File(dbPath.toString(),
+        OM_HARDLINK_FILE);
+    if (hardLinkFile.exists()) {
+      // Read file.
+      List<String> lines =
+          Files.lines(hardLinkFile.toPath()).collect(Collectors.toList());
+
+      // Create a link for each line.
+      for (String l : lines) {
+        String from = l.split("\t")[1];
+        String to = l.split("\t")[0];
+        Path fullFromPath = getFullPath(dbPath, from);
+        Path fullToPath = getFullPath(dbPath, to);
+        Files.createLink(fullToPath, fullFromPath);
+      }
+      if (!hardLinkFile.delete()) {
+        throw new IOException(
+            "Failed to delete: " + hardLinkFile);
+      }
+    }
+  }
+
+
+  // Prepend the full path to the hard link entry entry.
+  @SuppressFBWarnings({"NP_NULL_ON_SOME_PATH_FROM_RETURN_VALUE"})
+  private static Path getFullPath(Path dbPath, String fileName) {
+    File file = new File(fileName);
+    // If there is no directory then this file belongs in the db.
+    if (file.getName().equals(fileName)) {
+      return Paths.get(dbPath.toString(), fileName);
+    }
+    // Else this file belong in a directory parallel to the db.
+    return Paths.get(dbPath.getParent().toString(), fileName);
+  }
+
+

Review Comment:
   ```suggestion
   
   ```



##########
hadoop-ozone/ozone-manager/src/main/java/org/apache/hadoop/ozone/om/OmSnapshotManager.java:
##########
@@ -279,6 +307,92 @@ private void verifySnapshotInfoForSnapDiff(final SnapshotInfo fromSnapshot,
     }
   }
 
+  /**
+   * Create file of links to add to tarball.
+   * Format of entries are either:
+   * dir1/fileTo fileFrom
+   *    for files in active db or:
+   * dir1/fileTo dir2/fileFrom
+   *    for files in another directory, (either another snapshot dir or
+   *    sst compaction backup directory)
+   * @param truncateLength - Length of initial path to trim in file path.
+   * @param hardLinkFiles - Map of link->file paths.
+   * @return Path to the file of links created.
+   */
+  @SuppressFBWarnings({"NP_NULL_ON_SOME_PATH_FROM_RETURN_VALUE"})
+  static Path createHardLinkList(int truncateLength,
+                                  Map<Path, Path> hardLinkFiles)
+      throws IOException {
+    Path data = Files.createTempFile("data", "txt");
+    StringBuilder sb = new StringBuilder();
+    for (Map.Entry<Path, Path> entry : hardLinkFiles.entrySet()) {
+      String fixedFile = truncateFileName(truncateLength, entry.getValue());
+      // If this file is from the active db, strip the path.
+      if (fixedFile.startsWith(OM_CHECKPOINT_DIR)) {
+        fixedFile = Paths.get(fixedFile).getFileName().toString();
+      }
+      sb.append(truncateFileName(truncateLength, entry.getKey()))
+          .append("\t")
+          .append(fixedFile)
+          .append("\n");
+    }
+    Files.write(data, sb.toString().getBytes(StandardCharsets.UTF_8));
+    return data;
+  }
+
+  /**
+   * Get the filename without the introductory metadata directory.
+   *
+   * @param truncateLength Length to remove.
+   * @param file File to remove prefix from.
+   * @return Truncated string.
+   */
+  static String truncateFileName(int truncateLength, Path file) {
+    return file.toString().substring(truncateLength);
+  }
+
+  /**
+   * Create hard links listed in OM_HARDLINK_FILE.
+   *
+   * @param dbPath Path to db to have links created.
+   */
+  static void createHardLinks(Path dbPath) throws IOException {
+    File hardLinkFile = new File(dbPath.toString(),
+        OM_HARDLINK_FILE);
+    if (hardLinkFile.exists()) {
+      // Read file.
+      List<String> lines =
+          Files.lines(hardLinkFile.toPath()).collect(Collectors.toList());
+
+      // Create a link for each line.
+      for (String l : lines) {
+        String from = l.split("\t")[1];
+        String to = l.split("\t")[0];
+        Path fullFromPath = getFullPath(dbPath, from);
+        Path fullToPath = getFullPath(dbPath, to);
+        Files.createLink(fullToPath, fullFromPath);
+      }
+      if (!hardLinkFile.delete()) {
+        throw new IOException(
+            "Failed to delete: " + hardLinkFile);
+      }
+    }
+  }
+
+

Review Comment:
   nit
   ```suggestion
   
   ```



##########
hadoop-ozone/ozone-manager/src/main/java/org/apache/hadoop/ozone/om/OzoneManager.java:
##########
@@ -3736,13 +3755,17 @@ File replaceOMDBWithCheckpoint(long lastAppliedIndex, File oldDB,
       // starting up.
       Files.createFile(markerFile);
       FileUtils.moveDirectory(checkpointPath, oldDB.toPath());
+      moveOmSnapshotData(oldDB.toPath(), dbSnapshotsDir.toPath());

Review Comment:
   Do we have a consensus here?



##########
hadoop-ozone/ozone-manager/src/main/java/org/apache/hadoop/ozone/om/OzoneManager.java:
##########
@@ -3716,16 +3721,30 @@ File replaceOMDBWithCheckpoint(long lastAppliedIndex, File oldDB,
     String dbBackupName = OzoneConsts.OM_DB_BACKUP_PREFIX +
         lastAppliedIndex + "_" + System.currentTimeMillis();
     File dbDir = oldDB.getParentFile();
-    File dbBackup = new File(dbDir, dbBackupName);
 
-    try {
-      Files.move(oldDB.toPath(), dbBackup.toPath());
-    } catch (IOException e) {
-      LOG.error("Failed to create a backup of the current DB. Aborting " +
-          "snapshot installation.");
-      throw e;
+    // Backup the active fs and snapshot dirs.
+    File dbBackupDir = new File(dbDir, dbBackupName);
+    if (!dbBackupDir.mkdirs()) {
+      throw new IOException("Failed to make db backup dir: " +
+          dbBackupDir);
+    }
+    File dbBackup = new File(dbBackupDir, oldDB.getName());
+    File dbSnapshotsDir = new File(dbDir, OM_SNAPSHOT_DIR);
+    File dbSnapshotsBackup = new File(dbBackupDir, OM_SNAPSHOT_DIR);
+    Files.move(oldDB.toPath(), dbBackup.toPath());
+    if (dbSnapshotsDir.exists()) {
+      Files.move(dbSnapshotsDir.toPath(),
+          dbSnapshotsBackup.toPath());
     }
 
+    moveCheckpointFiles(oldDB, checkpointPath, dbDir, dbBackup, dbSnapshotsDir,
+        dbSnapshotsBackup);
+    return dbBackupDir;
+  }
+
+  private void moveCheckpointFiles(File oldDB, Path checkpointPath, File dbDir,
+                         File dbBackup, File dbSnapshotsDir,
+                         File dbSnapshotsBackup) throws IOException {

Review Comment:
   nit: alignment
   ```suggestion
     private void moveCheckpointFiles(File oldDB, Path checkpointPath, File dbDir,
                                      File dbBackup, File dbSnapshotsDir,
                                      File dbSnapshotsBackup) throws IOException {
   ```



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


[GitHub] [ozone] GeorgeJahad commented on a diff in pull request #3980: HDDS-6961. [Snapshot] Bootstrapping slow followers/new followers.

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


##########
hadoop-ozone/ozone-manager/src/main/java/org/apache/hadoop/ozone/om/OMDBCheckpointServlet.java:
##########
@@ -82,4 +113,166 @@ public void init() throws ServletException {
         allowedGroups,
         om.isSpnegoEnabled());
   }
+
+  @Override
+  public void writeDbDataToStream(DBCheckpoint checkpoint,
+                                  HttpServletRequest request,
+                                  OutputStream destination)
+      throws IOException, InterruptedException {
+    // Map of inodes to path.
+    Map<Object, Path> copyFiles = new HashMap<>();
+    // Map of link to path.
+    Map<Path, Path> hardLinkFiles = new HashMap<>();
+
+    getFilesForArchive(checkpoint, copyFiles, hardLinkFiles,
+        includeSnapshotData(request));
+
+    try (TarArchiveOutputStream archiveOutputStream =
+            new TarArchiveOutputStream(destination)) {
+      archiveOutputStream
+          .setLongFileMode(TarArchiveOutputStream.LONGFILE_POSIX);
+      writeFilesToArchive(copyFiles, hardLinkFiles, archiveOutputStream);
+    }
+  }
+
+  private void getFilesForArchive(DBCheckpoint checkpoint,
+                                  Map<Object, Path> copyFiles,
+                                  Map<Path, Path> hardLinkFiles,
+                                  boolean includeSnapshotData)
+      throws IOException, InterruptedException {
+
+    // Get the active fs files.
+    Path dir = checkpoint.getCheckpointLocation();
+    processDir(dir, copyFiles, hardLinkFiles, new HashSet<>());
+
+    if (!includeSnapshotData) {
+      return;
+    }
+
+    // Get the snapshot files.
+    Set<Path> snapshotPaths = waitForSnapshotDirs(checkpoint);
+    Path snapshotDir = Paths.get(OMStorage.getOmDbDir(getConf()).toString(),
+        OM_SNAPSHOT_DIR);
+    processDir(snapshotDir, copyFiles, hardLinkFiles, snapshotPaths);
+  }
+
+  /**
+   * The snapshotInfo table may contain a snapshot that
+   * doesn't yet exist on the fs, so wait a few seconds for it.
+   * @param checkpoint Checkpoint containing snapshot entries expected.
+   * @return Set of expected snapshot dirs.
+   */
+  private Set<Path> waitForSnapshotDirs(DBCheckpoint checkpoint)
+      throws IOException, InterruptedException {
+
+    OzoneConfiguration conf = getConf();
+
+    Set<Path> snapshotPaths = new HashSet<>();
+
+    // get snapshotInfo entries
+    OmMetadataManagerImpl checkpointMetadataManager =
+        OmMetadataManagerImpl.createCheckpointMetadataManager(
+            conf, checkpoint);
+    try (TableIterator<String, ? extends Table.KeyValue<String, SnapshotInfo>>
+        iterator = checkpointMetadataManager
+        .getSnapshotInfoTable().iterator()) {
+
+      // For each entry, wait for corresponding directory.
+      while (iterator.hasNext()) {
+        Table.KeyValue<String, SnapshotInfo> entry = iterator.next();
+        Path path = Paths.get(getSnapshotPath(conf, entry.getValue()));
+        waitForDirToExist(path);
+        snapshotPaths.add(path);
+      }
+    }
+    return snapshotPaths;
+  }
+
+  private void waitForDirToExist(Path dir)
+      throws IOException, InterruptedException {
+    long endTime = System.currentTimeMillis() +
+        Duration.parse(DURATION_TO_WAIT_FOR_DIRECTORY).toMillis();
+    while (!dir.toFile().exists()) {
+      Thread.sleep(100);
+      if (System.currentTimeMillis() > endTime) {
+        throw new IOException("snapshot dir doesn't exist: " + dir);
+      }
+    }
+  }
+
+  @SuppressFBWarnings("NP_NULL_ON_SOME_PATH_FROM_RETURN_VALUE")
+  private void processDir(Path dir, Map<Object, Path> copyFiles,
+                          Map<Path, Path> hardLinkFiles,
+                          Set<Path> snapshotPaths)
+      throws IOException {
+    try (Stream<Path> files = Files.list(dir)) {
+      for (Path file : files.collect(Collectors.toList())) {
+        if (file.toFile().isDirectory()) {
+          // Skip any unexpected snapshot files.
+          if (file.getParent().toString().endsWith(OM_SNAPSHOT_CHECKPOINT_DIR)
+              && !snapshotPaths.contains(file)) {
+            continue;
+          }

Review Comment:
   These are only "unexpected" because they created after after the active fs was checkpointed and so shouldn't be copied over.  So they could exist without any error in the code, but I'll add a LOG.debug().



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


[GitHub] [ozone] GeorgeJahad commented on a diff in pull request #3980: HDDS-6961. [Snapshot] Bootstrapping slow followers/new followers.

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


##########
hadoop-ozone/ozone-manager/src/main/java/org/apache/hadoop/ozone/om/OmSnapshotManager.java:
##########
@@ -279,6 +307,92 @@ private void verifySnapshotInfoForSnapDiff(final SnapshotInfo fromSnapshot,
     }
   }
 
+  /**
+   * Create file of links to add to tarball.
+   * Format of entries are either:
+   * dir1/fileTo fileFrom
+   *    for files in active db or:
+   * dir1/fileTo dir2/fileFrom
+   *    for files in another directory, (either another snapshot dir or
+   *    sst compaction backup directory)
+   * @param truncateLength - Length of initial path to trim in file path.
+   * @param hardLinkFiles - Map of link->file paths.
+   * @return Path to the file of links created.
+   */
+  @SuppressFBWarnings({"NP_NULL_ON_SOME_PATH_FROM_RETURN_VALUE"})
+  static Path createHardLinkList(int truncateLength,
+                                  Map<Path, Path> hardLinkFiles)
+      throws IOException {
+    Path data = Files.createTempFile("data", "txt");
+    StringBuilder sb = new StringBuilder();
+    for (Map.Entry<Path, Path> entry : hardLinkFiles.entrySet()) {
+      String fixedFile = truncateFileName(truncateLength, entry.getValue());
+      // If this file is from the active db, strip the path.
+      if (fixedFile.startsWith(OM_CHECKPOINT_DIR)) {
+        fixedFile = Paths.get(fixedFile).getFileName().toString();
+      }
+      sb.append(truncateFileName(truncateLength, entry.getKey()))
+          .append("\t")
+          .append(fixedFile)
+          .append("\n");
+    }
+    Files.write(data, sb.toString().getBytes(StandardCharsets.UTF_8));
+    return data;
+  }
+
+  /**
+   * Get the filename without the introductory metadata directory.
+   *
+   * @param truncateLength Length to remove.
+   * @param file File to remove prefix from.
+   * @return Truncated string.
+   */
+  static String truncateFileName(int truncateLength, Path file) {
+    return file.toString().substring(truncateLength);
+  }
+
+  /**
+   * Create hard links listed in OM_HARDLINK_FILE.
+   *
+   * @param dbPath Path to db to have links created.
+   */
+  static void createHardLinks(Path dbPath) throws IOException {

Review Comment:
   Added test here: https://github.com/apache/ozone/blob/051b97bf3eecaec31622161ee386002361e19c99/hadoop-ozone/integration-test/src/test/java/org/apache/hadoop/ozone/om/TestOMRatisSnapshots.java#L263-L304



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


[GitHub] [ozone] GeorgeJahad commented on a diff in pull request #3980: HDDS-6961. [Snapshot] Bootstrapping slow followers/new followers.

Posted by GitBox <gi...@apache.org>.
GeorgeJahad commented on code in PR #3980:
URL: https://github.com/apache/ozone/pull/3980#discussion_r1034166659


##########
hadoop-ozone/ozone-manager/src/main/java/org/apache/hadoop/ozone/om/OzoneManager.java:
##########
@@ -3568,7 +3570,7 @@ private DBCheckpoint getDBCheckpointFromLeader(String leaderId) {
         "from the checkpoint.", leaderId);
 
     try {
-      return omSnapshotProvider.getOzoneManagerDBSnapshot(leaderId);
+      return omRatisSnapshotProvider.getOzoneManagerDBSnapshot(leaderId);

Review Comment:
   I didn't write this code, I just renamed the field.  Studying it a bit further, it does look things will work correctly.
   
   installCheckpoint() will throw an exception, which causes installSnapshotFromLeader() to return a null TermIndex which is handled in ratis here:
   https://github.com/apache/ratis/blob/release-2.3.0/ratis-server/src/main/java/org/apache/ratis/server/impl/SnapshotInstallationHandler.java#L274-L278
   
   



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


[GitHub] [ozone] prashantpogde commented on a diff in pull request #3980: HDDS-6961. [Snapshot] Bootstrapping slow followers/new followers.

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


##########
hadoop-ozone/ozone-manager/src/main/java/org/apache/hadoop/ozone/om/OmSnapshotManager.java:
##########
@@ -279,6 +307,92 @@ private void verifySnapshotInfoForSnapDiff(final SnapshotInfo fromSnapshot,
     }
   }
 
+  /**
+   * Create file of links to add to tarball.
+   * Format of entries are either:
+   * dir1/fileTo fileFrom
+   *    for files in active db or:
+   * dir1/fileTo dir2/fileFrom
+   *    for files in another directory, (either another snapshot dir or
+   *    sst compaction backup directory)
+   * @param truncateLength - Length of initial path to trim in file path.
+   * @param hardLinkFiles - Map of link->file paths.
+   * @return Path to the file of links created.
+   */
+  @SuppressFBWarnings({"NP_NULL_ON_SOME_PATH_FROM_RETURN_VALUE"})
+  static Path createHardLinkList(int truncateLength,
+                                  Map<Path, Path> hardLinkFiles)
+      throws IOException {
+    Path data = Files.createTempFile("data", "txt");
+    StringBuilder sb = new StringBuilder();
+    for (Map.Entry<Path, Path> entry : hardLinkFiles.entrySet()) {
+      String fixedFile = truncateFileName(truncateLength, entry.getValue());
+      // If this file is from the active db, strip the path.
+      if (fixedFile.startsWith(OM_CHECKPOINT_DIR)) {
+        fixedFile = Paths.get(fixedFile).getFileName().toString();
+      }
+      sb.append(truncateFileName(truncateLength, entry.getKey()))

Review Comment:
   This way you don't have to worry about the truncatelength and path stripping.



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


[GitHub] [ozone] GeorgeJahad commented on a diff in pull request #3980: HDDS-6961. [Snapshot] Bootstrapping slow followers/new followers.

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


##########
hadoop-ozone/ozone-manager/src/main/java/org/apache/hadoop/ozone/om/OmSnapshotManager.java:
##########
@@ -279,6 +307,92 @@ private void verifySnapshotInfoForSnapDiff(final SnapshotInfo fromSnapshot,
     }
   }
 
+  /**
+   * Create file of links to add to tarball.
+   * Format of entries are either:
+   * dir1/fileTo fileFrom
+   *    for files in active db or:
+   * dir1/fileTo dir2/fileFrom
+   *    for files in another directory, (either another snapshot dir or
+   *    sst compaction backup directory)
+   * @param truncateLength - Length of initial path to trim in file path.
+   * @param hardLinkFiles - Map of link->file paths.
+   * @return Path to the file of links created.
+   */
+  @SuppressFBWarnings({"NP_NULL_ON_SOME_PATH_FROM_RETURN_VALUE"})
+  static Path createHardLinkList(int truncateLength,
+                                  Map<Path, Path> hardLinkFiles)
+      throws IOException {
+    Path data = Files.createTempFile("data", "txt");
+    StringBuilder sb = new StringBuilder();
+    for (Map.Entry<Path, Path> entry : hardLinkFiles.entrySet()) {
+      String fixedFile = truncateFileName(truncateLength, entry.getValue());
+      // If this file is from the active db, strip the path.
+      if (fixedFile.startsWith(OM_CHECKPOINT_DIR)) {
+        fixedFile = Paths.get(fixedFile).getFileName().toString();
+      }
+      sb.append(truncateFileName(truncateLength, entry.getKey()))
+          .append("\t")
+          .append(fixedFile)
+          .append("\n");
+    }
+    Files.write(data, sb.toString().getBytes(StandardCharsets.UTF_8));
+    return data;
+  }
+
+  /**
+   * Get the filename without the introductory metadata directory.
+   *
+   * @param truncateLength Length to remove.
+   * @param file File to remove prefix from.
+   * @return Truncated string.
+   */
+  static String truncateFileName(int truncateLength, Path file) {
+    return file.toString().substring(truncateLength);
+  }
+
+  /**
+   * Create hard links listed in OM_HARDLINK_FILE.
+   *
+   * @param dbPath Path to db to have links created.
+   */
+  static void createHardLinks(Path dbPath) throws IOException {

Review Comment:
   So there is a unit test here that excercises the details of those methods:
   https://github.com/apache/ozone/blob/ed069f01142452dfc59b3f9703e486ef0434d7e4/hadoop-ozone/ozone-manager/src/test/java/org/apache/hadoop/ozone/om/TestOmSnapshotManager.java#L132
   
   The integration test of which checks a follower bootstrapping existed already already.  I just modified it to add a test to confirm the snapshot data was uploaded as well:
   https://github.com/apache/ozone/blob/ed069f01142452dfc59b3f9703e486ef0434d7e4/hadoop-ozone/integration-test/src/test/java/org/apache/hadoop/ozone/om/TestOMRatisSnapshots.java#L243-L252
   
   Is that sufficient?
   



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


[GitHub] [ozone] GeorgeJahad commented on a diff in pull request #3980: HDDS-6961. [Snapshot] Bootstrapping slow followers/new followers.

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


##########
hadoop-ozone/ozone-manager/src/main/java/org/apache/hadoop/ozone/om/SstFilteringService.java:
##########
@@ -143,9 +144,11 @@ public BackgroundTaskResult call() throws Exception {
 
           String dbName = OM_DB_NAME + snapshotInfo.getCheckpointDirName();
 
+          String snapshotCheckpointDir = omMetadataDir + OM_KEY_PREFIX +
+              OM_SNAPSHOT_CHECKPOINT_DIR;
           RDBStore rdbStore = (RDBStore) OmMetadataManagerImpl
-              .loadDB(ozoneManager.getConfiguration(), new File(snapshotDir),
-                  dbName, true);
+              .loadDB(ozoneManager.getConfiguration(),
+                  new File(snapshotCheckpointDir), dbName, true);
           RocksDatabase db = rdbStore.getDb();
           db.deleteFilesNotMatchingPrefix(prefixPairs, filterFunction);
 

Review Comment:
   I discussed that briefly [above](https://github.com/apache/ozone/pull/3980#issuecomment-1426468318).  Basically I added most of the code for the serialization and then pulled it out because the PR is getting to big.  I'll be ready to create a separate PR soon after this is merged.
   



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


[GitHub] [ozone] GeorgeJahad commented on a diff in pull request #3980: HDDS-6961. [Snapshot] Bootstrapping slow followers/new followers.

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


##########
hadoop-ozone/ozone-manager/src/main/java/org/apache/hadoop/ozone/om/SstFilteringService.java:
##########
@@ -143,9 +144,11 @@ public BackgroundTaskResult call() throws Exception {
 
           String dbName = OM_DB_NAME + snapshotInfo.getCheckpointDirName();
 
+          String snapshotCheckpointDir = omMetadataDir + OM_KEY_PREFIX +
+              OM_SNAPSHOT_CHECKPOINT_DIR;
           RDBStore rdbStore = (RDBStore) OmMetadataManagerImpl
-              .loadDB(ozoneManager.getConfiguration(), new File(snapshotDir),
-                  dbName, true);
+              .loadDB(ozoneManager.getConfiguration(),
+                  new File(snapshotCheckpointDir), dbName, true);
           RocksDatabase db = rdbStore.getDb();
           db.deleteFilesNotMatchingPrefix(prefixPairs, filterFunction);
 

Review Comment:
   added ticket here: https://issues.apache.org/jira/browse/HDDS-8209
   



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


[GitHub] [ozone] GeorgeJahad commented on a diff in pull request #3980: HDDS-6961. [Snapshot] Bootstrapping slow followers/new followers.

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


##########
hadoop-ozone/ozone-manager/src/main/java/org/apache/hadoop/ozone/om/OMDBCheckpointServlet.java:
##########
@@ -82,4 +115,174 @@ public void init() throws ServletException {
         allowedGroups,
         om.isSpnegoEnabled());
   }
+
+  @Override
+  public void writeDbDataToStream(DBCheckpoint checkpoint,
+                                  HttpServletRequest request,
+                                  OutputStream destination)
+      throws IOException, InterruptedException, CompressorException {
+    // Map of inodes to path.
+    Map<Object, Path> copyFiles = new HashMap<>();
+    // Map of link to path.
+    Map<Path, Path> hardLinkFiles = new HashMap<>();
+
+    getFilesForArchive(checkpoint, copyFiles, hardLinkFiles,
+        includeSnapshotData(request));
+
+    try (CompressorOutputStream gzippedOut = new CompressorStreamFactory()
+        .createCompressorOutputStream(
+            CompressorStreamFactory.GZIP, destination);
+         TarArchiveOutputStream archiveOutputStream = 
+             new TarArchiveOutputStream(gzippedOut)
+    ) {
+      archiveOutputStream
+          .setLongFileMode(TarArchiveOutputStream.LONGFILE_POSIX);
+      writeFilesToArchive(copyFiles, hardLinkFiles, archiveOutputStream);
+    } catch (CompressorException e) {
+      throw new IOException(
+          "Can't compress the checkpoint: " +
+              checkpoint.getCheckpointLocation(), e);
+    }
+  }
+
+  private void getFilesForArchive(DBCheckpoint checkpoint,
+                                  Map<Object, Path> copyFiles,
+                                  Map<Path, Path> hardLinkFiles,
+                                  boolean includeSnapshotData)
+      throws IOException, InterruptedException {
+
+    // Get the active fs files.
+    Path dir = checkpoint.getCheckpointLocation();
+    processDir(dir, copyFiles, hardLinkFiles, new HashSet<>());
+
+    if (!includeSnapshotData) {
+      return;
+    }
+
+    // Get the snapshot files.
+    Set<Path> snapshotPaths = waitForSnapshotDirs(checkpoint);
+    Path snapshotDir = Paths.get(OMStorage.getOmDbDir(getConf()).toString(),
+        OM_SNAPSHOT_DIR);
+    processDir(snapshotDir, copyFiles, hardLinkFiles, snapshotPaths);
+  }
+
+  /**
+   * The snapshotInfo table may contain a snapshot that
+   * doesn't yet exist on the fs, so wait a few seconds for it.
+   * @param checkpoint Checkpoint containing snapshot entries expected.
+   * @return Set of expected snapshot dirs.
+   */
+  private Set<Path> waitForSnapshotDirs(DBCheckpoint checkpoint)
+      throws IOException, InterruptedException {
+
+    OzoneConfiguration conf = getConf();
+
+    Set<Path> snapshotPaths = new HashSet<>();
+
+    // get snapshotInfo entries
+    OmMetadataManagerImpl checkpointMetadataManager =
+        OmMetadataManagerImpl.createCheckpointMetadataManager(
+            conf, checkpoint);
+    try (TableIterator<String, ? extends Table.KeyValue<String, SnapshotInfo>>
+        iterator = checkpointMetadataManager
+        .getSnapshotInfoTable().iterator()) {
+
+      // For each entry, wait for corresponding directory.
+      while (iterator.hasNext()) {
+        Table.KeyValue<String, SnapshotInfo> entry = iterator.next();
+        Path path = Paths.get(getSnapshotPath(conf, entry.getValue()));
+        waitForDirToExist(path);
+        snapshotPaths.add(path);
+      }
+    }
+    return snapshotPaths;
+  }
+
+  private void waitForDirToExist(Path dir)
+      throws IOException, InterruptedException {
+    long endTime = System.currentTimeMillis() +
+        Duration.parse(DURATION_TO_WAIT_FOR_DIRECTORY).toMillis();
+    while (!dir.toFile().exists()) {
+      Thread.sleep(100);
+      if (System.currentTimeMillis() > endTime) {
+        throw new IOException("snapshot dir doesn't exist: " + dir);
+      }
+    }
+  }
+
+  @SuppressFBWarnings("NP_NULL_ON_SOME_PATH_FROM_RETURN_VALUE")
+  private void processDir(Path dir, Map<Object, Path> copyFiles,
+                          Map<Path, Path> hardLinkFiles,
+                          Set<Path> snapshotPaths)
+      throws IOException {
+    try (Stream<Path> files = Files.list(dir)) {
+      for (Path file : files.collect(Collectors.toList())) {
+        if (file.toFile().isDirectory()) {
+          // Skip any unexpected snapshot files.
+          if (file.getParent().toString().endsWith(OM_SNAPSHOT_CHECKPOINT_DIR)
+              && !snapshotPaths.contains(file)) {
+            continue;
+          }
+          processDir(file, copyFiles, hardLinkFiles, snapshotPaths);
+        } else {
+          processFile(file, copyFiles, hardLinkFiles);
+        }
+      }
+    }
+  }
+
+  private void processFile(Path file, Map<Object, Path> copyFiles,
+                           Map<Path, Path> hardLinkFiles) throws IOException {
+    // Get the inode.
+    Object key = OmSnapshotManager.getINode(file);
+    // If we already have the inode, store as hard link.
+    if (copyFiles.containsKey(key)) {
+      hardLinkFiles.put(file, copyFiles.get(key));
+    } else {
+      copyFiles.put(key, file);
+    }
+  }
+
+  // Returns value of http request parameter.
+  private boolean includeSnapshotData(HttpServletRequest request) {
+    String includeParam =

Review Comment:
   Nice, thanks!



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


[GitHub] [ozone] hemantk-12 commented on a diff in pull request #3980: HDDS-6961. [Snapshot] Bootstrapping slow followers/new followers.

Posted by GitBox <gi...@apache.org>.
hemantk-12 commented on code in PR #3980:
URL: https://github.com/apache/ozone/pull/3980#discussion_r1027231762


##########
hadoop-ozone/integration-test/src/test/java/org/apache/hadoop/ozone/om/TestOMDbCheckpointServlet.java:
##########
@@ -259,69 +291,259 @@ public void testSpnegoEnabled() throws Exception {
   }
 
   @Test
-  public void testWriteCheckpointToOutputStream() throws Exception {
-
-    FileInputStream fis = null;
-    FileOutputStream fos = null;
-
-    try {
-      String testDirName = folder.newFolder().getAbsolutePath();
-      File file = new File(testDirName + "/temp1.txt");
-      OutputStreamWriter writer = new OutputStreamWriter(
-          new FileOutputStream(file), StandardCharsets.UTF_8);
-      writer.write("Test data 1");
-      writer.close();
-
-      file = new File(testDirName + "/temp2.txt");
-      writer = new OutputStreamWriter(
-          new FileOutputStream(file), StandardCharsets.UTF_8);
-      writer.write("Test data 2");
-      writer.close();
-
-      File outputFile =
-          new File(Paths.get(testDirName, "output_file.tgz").toString());
-      TestDBCheckpoint dbCheckpoint = new TestDBCheckpoint(
-          Paths.get(testDirName));
-      writeDBCheckpointToStream(dbCheckpoint,
-          new FileOutputStream(outputFile));
-      assertNotNull(outputFile);
-    } finally {
-      IOUtils.closeStream(fis);
-      IOUtils.closeStream(fos);
+  public void testWriteDbDataToStream()
+      throws Exception {

Review Comment:
   ```suggestion
     public void testWriteDbDataToStream() throws Exception {
   ```



##########
hadoop-hdds/rocksdb-checkpoint-differ/src/main/java/org/apache/ozone/rocksdiff/RocksDBCheckpointDiffer.java:
##########
@@ -164,19 +164,19 @@ public RocksDBCheckpointDiffer(String metadataDir, String sstBackupDir,
     this.activeDBLocationStr = activeDBLocation.toString() + "/";
   }
 
-  private void setCompactionLogDir(String metadataDir,
+  private void setCompactionLogDir(String snapshotDiffDir,
       String compactionLogDirName) {
 
-    final File parentDir = new File(metadataDir);
+    final File parentDir = new File(snapshotDiffDir);
     if (!parentDir.exists()) {
-      if (!parentDir.mkdir()) {
+      if (!parentDir.mkdirs()) {
         LOG.error("Error creating compaction log parent dir.");
         return;
       }
     }
 
     this.compactionLogDir =
-        Paths.get(metadataDir, compactionLogDirName).toString();
+        Paths.get(parentDir.toString(), compactionLogDirName).toString();

Review Comment:
   Should we use `getPath()` instead of `toString()` on file?



##########
hadoop-ozone/ozone-manager/src/main/java/org/apache/hadoop/ozone/om/OMDBCheckpointServlet.java:
##########
@@ -82,4 +112,165 @@ public void init() throws ServletException {
         allowedGroups,
         om.isSpnegoEnabled());
   }
+
+  @Override
+  public void writeDbDataToStream(DBCheckpoint checkpoint,
+                                  HttpServletRequest request,
+                                  OutputStream destination)
+      throws IOException, InterruptedException, CompressorException {
+    // Map of inodes to path
+    HashMap<Object, Path> copyFiles = new HashMap<>();
+    // Map of link to path
+    HashMap<Path, Path> hardLinkFiles = new HashMap<>();
+
+    getFilesForArchive(checkpoint, copyFiles, hardLinkFiles,
+        includeSnapshotData(request));
+
+    try (CompressorOutputStream gzippedOut = new CompressorStreamFactory()
+        .createCompressorOutputStream(CompressorStreamFactory.GZIP,
+            destination)) {
+
+      try (TarArchiveOutputStream archiveOutputStream =
+          new TarArchiveOutputStream(gzippedOut)) {
+        archiveOutputStream
+            .setLongFileMode(TarArchiveOutputStream.LONGFILE_POSIX);
+
+        writeFilesToArchive(copyFiles, hardLinkFiles, archiveOutputStream);
+      }
+    } catch (CompressorException e) {
+      throw new IOException(
+          "Can't compress the checkpoint: " +
+              checkpoint.getCheckpointLocation(), e);
+    }

Review Comment:
   ```suggestion
       try (CompressorOutputStream gzippedOut = new CompressorStreamFactory()
           .createCompressorOutputStream(CompressorStreamFactory.GZIP, destination);
            TarArchiveOutputStream archiveOutputStream = 
                new TarArchiveOutputStream(gzippedOut)
       ) {
         archiveOutputStream.setLongFileMode(TarArchiveOutputStream.LONGFILE_POSIX);
         writeFilesToArchive(copyFiles, hardLinkFiles, archiveOutputStream);
       } catch (CompressorException e) {
         throw new IOException(
             "Can't compress the checkpoint: " +
                 checkpoint.getCheckpointLocation(), e);
       }
   ````
   
   You can define multiple objects in try. Will remove the unnecessary nesting.



##########
hadoop-ozone/ozone-manager/src/main/java/org/apache/hadoop/ozone/om/OMDBCheckpointServlet.java:
##########
@@ -82,4 +112,165 @@ public void init() throws ServletException {
         allowedGroups,
         om.isSpnegoEnabled());
   }
+
+  @Override
+  public void writeDbDataToStream(DBCheckpoint checkpoint,
+                                  HttpServletRequest request,
+                                  OutputStream destination)
+      throws IOException, InterruptedException, CompressorException {
+    // Map of inodes to path
+    HashMap<Object, Path> copyFiles = new HashMap<>();
+    // Map of link to path
+    HashMap<Path, Path> hardLinkFiles = new HashMap<>();
+
+    getFilesForArchive(checkpoint, copyFiles, hardLinkFiles,
+        includeSnapshotData(request));
+
+    try (CompressorOutputStream gzippedOut = new CompressorStreamFactory()
+        .createCompressorOutputStream(CompressorStreamFactory.GZIP,
+            destination)) {
+
+      try (TarArchiveOutputStream archiveOutputStream =
+          new TarArchiveOutputStream(gzippedOut)) {
+        archiveOutputStream
+            .setLongFileMode(TarArchiveOutputStream.LONGFILE_POSIX);
+
+        writeFilesToArchive(copyFiles, hardLinkFiles, archiveOutputStream);
+      }
+    } catch (CompressorException e) {
+      throw new IOException(
+          "Can't compress the checkpoint: " +
+              checkpoint.getCheckpointLocation(), e);
+    }
+  }
+
+  private void getFilesForArchive(DBCheckpoint checkpoint,
+                                  Map<Object, Path> copyFiles,
+                                  Map<Path, Path> hardLinkFiles,
+                                  boolean includeSnapshotData)
+      throws IOException, InterruptedException {
+
+    // Get the active fs files
+    Path dir = checkpoint.getCheckpointLocation();
+    processDir(dir, copyFiles, hardLinkFiles);
+
+    if (!includeSnapshotData) {
+      return;
+    }
+
+    // Get the snapshot files
+    waitForSnapshotDirs(checkpoint);
+    Path snapshotDir = Paths.get(OMStorage.getOmDbDir(getConf()).toString(),
+        OM_SNAPSHOT_DIR);
+    processDir(snapshotDir, copyFiles, hardLinkFiles);
+  }
+
+  // The snapshotInfo table may contain a snapshot that
+  //  doesn't yet exist on the fs, so wait a few seconds for it
+  private void waitForSnapshotDirs(DBCheckpoint checkpoint)
+      throws IOException, InterruptedException {
+
+    OzoneConfiguration conf = getConf();
+
+    // get snapshotInfo entries
+    OmMetadataManagerImpl checkpointMetadataManager =
+        OmMetadataManagerImpl.createCheckpointMetadataManager(
+            conf, checkpoint);
+    try (TableIterator<String, ? extends Table.KeyValue<String, SnapshotInfo>>
+        iterator = checkpointMetadataManager
+        .getSnapshotInfoTable().iterator()) {
+
+      // for each entry, wait for corresponding directory
+      while (iterator.hasNext()) {
+        Table.KeyValue<String, SnapshotInfo> entry = iterator.next();
+        Path path = Paths.get(getSnapshotPath(conf, entry.getValue()));
+        waitForDirToExist(path);
+      }
+    }
+  }
+
+  private void waitForDirToExist(Path dir)
+      throws IOException, InterruptedException {
+    long endTime = System.currentTimeMillis() +
+        Duration.parse(DURATION_TO_WAIT_FOR_DIRECTORY).toMillis();
+    while (!dir.toFile().exists()) {
+      Thread.sleep(100);
+      if (System.currentTimeMillis() > endTime) {
+        break;
+      }
+    }
+    if (System.currentTimeMillis() > endTime) {
+      throw new IOException("snapshot dir doesn't exist: " + dir);

Review Comment:
   You can throw this exception at line #119. You don't have to check and throw here.



##########
hadoop-ozone/ozone-manager/src/main/java/org/apache/hadoop/ozone/om/OzoneManager.java:
##########
@@ -3568,7 +3570,7 @@ private DBCheckpoint getDBCheckpointFromLeader(String leaderId) {
         "from the checkpoint.", leaderId);
 
     try {
-      return omSnapshotProvider.getOzoneManagerDBSnapshot(leaderId);
+      return omRatisSnapshotProvider.getOzoneManagerDBSnapshot(leaderId);

Review Comment:
   Is it Ok to return null in case of IOException? We don't have a null check where returned value is used at line # 3385-3387. Also the same value is passed to `installCheckpoint` without null check.



##########
hadoop-ozone/ozone-manager/src/main/java/org/apache/hadoop/ozone/om/OmMetadataManagerImpl.java:
##########
@@ -298,15 +301,19 @@ protected OmMetadataManagerImpl() {
     this.omEpoch = 0;
   }
 
-  // metadata constructor for snapshots
-  private OmMetadataManagerImpl(OzoneConfiguration conf, String snapshotDirName)
+  /**
+   * metadata constructor for checkpoints.

Review Comment:
   nit: `* Metadata ....`



##########
hadoop-ozone/ozone-manager/src/main/java/org/apache/hadoop/ozone/om/OzoneManager.java:
##########
@@ -3597,10 +3599,22 @@ File replaceOMDBWithCheckpoint(long lastAppliedIndex, File oldDB,
     String dbBackupName = OzoneConsts.OM_DB_BACKUP_PREFIX +
         lastAppliedIndex + "_" + System.currentTimeMillis();
     File dbDir = oldDB.getParentFile();
-    File dbBackup = new File(dbDir, dbBackupName);
 
+    // Backup the active fs and snapshot dirs
+    File dbBackupDir = new File(dbDir, dbBackupName);
+    if (!dbBackupDir.mkdirs()) {
+      throw new IOException("Failed to make db backup dir: " +
+          dbBackupDir);
+    }
+    File dbBackup = new File(dbBackupDir, oldDB.getName());
+    File dbSnapshotsDir = new File(dbDir, OM_SNAPSHOT_DIR);
+    File dbSnapshotsBackup = new File(dbBackupDir, OM_SNAPSHOT_DIR);
     try {
       Files.move(oldDB.toPath(), dbBackup.toPath());
+      if (dbSnapshotsDir.exists()) {
+        Files.move(dbSnapshotsDir.toPath(),
+            dbSnapshotsBackup.toPath());
+      }
     } catch (IOException e) {

Review Comment:
   This is unnecessary catch. Doing nothing other than double logging and re-throwing the same exception.



##########
hadoop-ozone/integration-test/src/test/java/org/apache/hadoop/ozone/om/TestOMDbCheckpointServlet.java:
##########
@@ -259,69 +291,259 @@ public void testSpnegoEnabled() throws Exception {
   }
 
   @Test
-  public void testWriteCheckpointToOutputStream() throws Exception {
-
-    FileInputStream fis = null;
-    FileOutputStream fos = null;
-
-    try {
-      String testDirName = folder.newFolder().getAbsolutePath();
-      File file = new File(testDirName + "/temp1.txt");
-      OutputStreamWriter writer = new OutputStreamWriter(
-          new FileOutputStream(file), StandardCharsets.UTF_8);
-      writer.write("Test data 1");
-      writer.close();
-
-      file = new File(testDirName + "/temp2.txt");
-      writer = new OutputStreamWriter(
-          new FileOutputStream(file), StandardCharsets.UTF_8);
-      writer.write("Test data 2");
-      writer.close();
-
-      File outputFile =
-          new File(Paths.get(testDirName, "output_file.tgz").toString());
-      TestDBCheckpoint dbCheckpoint = new TestDBCheckpoint(
-          Paths.get(testDirName));
-      writeDBCheckpointToStream(dbCheckpoint,
-          new FileOutputStream(outputFile));
-      assertNotNull(outputFile);
-    } finally {
-      IOUtils.closeStream(fis);
-      IOUtils.closeStream(fos);
+  public void testWriteDbDataToStream()
+      throws Exception {
+    prepSnapshotData();
+    // set http param to include snapshot data
+    when(requestMock.getParameter(OZONE_DB_CHECKPOINT_INCLUDE_SNAPSHOT_DATA))
+        .thenReturn("true");
+
+    // get the tarball
+    try (FileOutputStream fileOutputStream = new FileOutputStream(tempFile)) {
+      omDbCheckpointServletMock.writeDbDataToStream(dbCheckpoint, requestMock,
+          fileOutputStream);
+    }
+
+    // Untar the file into a temp folder to be examined
+    String testDirName = folder.newFolder().getAbsolutePath();
+    int testDirLength = testDirName.length() + 1;
+    String newDbDirName = testDirName + OM_KEY_PREFIX + OM_DB_NAME;
+    int newDbDirLength = newDbDirName.length() + 1;
+    File newDbDir = new File(newDbDirName);
+    newDbDir.mkdirs();
+    FileUtil.unTar(tempFile, newDbDir);
+
+    // Move snapshot dir to correct location
+    new File(newDbDirName, OM_SNAPSHOT_DIR)
+        .renameTo(new File(newDbDir.getParent(), OM_SNAPSHOT_DIR));
+
+
+    // Confirm the checkpoint directories match, (after remove extras)
+    Path checkpointLocation = dbCheckpoint.getCheckpointLocation();
+    Set<String> initialCheckpointSet = getFiles(checkpointLocation,
+        checkpointLocation.toString().length() + 1);
+    Path finalCheckpointLocation = Paths.get(newDbDirName);
+    Set<String> finalCheckpointSet = getFiles(finalCheckpointLocation,
+        newDbDirLength);
+
+    Assert.assertTrue("hardlink file exists in checkpoint dir",
+        finalCheckpointSet.contains(OM_HARDLINK_FILE));
+    finalCheckpointSet.remove(OM_HARDLINK_FILE);
+    Assert.assertEquals(initialCheckpointSet, finalCheckpointSet);
+
+    int metaDirLength = metaDir.toString().length() + 1;
+    String shortSnapshotLocation =
+        truncateFileName(metaDirLength, Paths.get(snapshotDirName));
+    String shortSnapshotLocation2 =
+        truncateFileName(metaDirLength, Paths.get(snapshotDirName2));
+    String shortCompactionDirLocation =
+        truncateFileName(metaDirLength, compactionDirPath);
+
+    Set<String> finalFullSet =
+        getFiles(Paths.get(testDirName, OM_SNAPSHOT_DIR), testDirLength);
+
+    // check each line in the hard link file
+    Stream<String> lines = Files.lines(Paths.get(newDbDirName,
+        OM_HARDLINK_FILE));
+
+    List<String> fabricatedLinkLines = new ArrayList<>();
+    for (String line: lines.collect(Collectors.toList())) {
+      Assert.assertFalse("CURRENT file is not a hard link",
+          line.contains("CURRENT"));
+      if (line.contains("fabricatedFile")) {
+        fabricatedLinkLines.add(line);
+      } else {
+        checkLine(shortSnapshotLocation, shortSnapshotLocation2, line);
+        // add links to the final set
+        finalFullSet.add(line.split("\t")[0]);
+      }
     }
+
+    Set<String> directories = Sets.newHashSet(
+        shortSnapshotLocation, shortSnapshotLocation2,
+        shortCompactionDirLocation);
+    checkFabricatedLines(directories, fabricatedLinkLines, testDirName);
+
+    Set<String> initialFullSet =
+        getFiles(Paths.get(metaDir.toString(), OM_SNAPSHOT_DIR), metaDirLength);
+    Assert.assertEquals("found expected snapshot files",
+        initialFullSet, finalFullSet);
   }
-}
 
-class TestDBCheckpoint implements DBCheckpoint {
+  @Test
+  public void testWriteDbDataWithoutOmSnapshot()
+      throws Exception {
+    prepSnapshotData();
+
+    // set http param to exclude snapshot data
+    when(requestMock.getParameter(OZONE_DB_CHECKPOINT_INCLUDE_SNAPSHOT_DATA))
+        .thenReturn(null);
+
+    // get the tarball
+    try (FileOutputStream fileOutputStream = new FileOutputStream(tempFile)) {
+      omDbCheckpointServletMock.writeDbDataToStream(dbCheckpoint, requestMock,
+          fileOutputStream);
+    }
+
+    // Untar the file into a temp folder to be examined
+    String testDirName = folder.newFolder().getAbsolutePath();
+    int testDirLength = testDirName.length() + 1;
+    FileUtil.unTar(tempFile, new File(testDirName));
 
-  private final Path checkpointFile;
+    // Confirm the checkpoint directories match
+    Path checkpointLocation = dbCheckpoint.getCheckpointLocation();
+    Set<String> initialCheckpointSet = getFiles(checkpointLocation,
+        checkpointLocation.toString().length() + 1);
+    Path finalCheckpointLocation = Paths.get(testDirName);
+    Set<String> finalCheckpointSet = getFiles(finalCheckpointLocation,
+        testDirLength);
 
-  TestDBCheckpoint(Path checkpointFile) {
-    this.checkpointFile = checkpointFile;
+    Assert.assertEquals(initialCheckpointSet, finalCheckpointSet);
   }
 
-  @Override
-  public Path getCheckpointLocation() {
-    return checkpointFile;
+
+
+  private void prepSnapshotData() throws Exception {
+    setupCluster();
+    metaDir = OMStorage.getOmDbDir(conf);
+
+    OzoneBucket bucket = TestDataUtil.createVolumeAndBucket(cluster);
+
+    // Create dummy keys for snapshotting
+    TestDataUtil.createKey(bucket, UUID.randomUUID().toString(),
+        "content");
+    TestDataUtil.createKey(bucket, UUID.randomUUID().toString(),
+        "content");
+
+    // this sleep can be removed after this is fixed:
+    //  https://issues.apache.org/jira/browse/HDDS-7279
+    Thread.sleep(2000);
+    snapshotDirName =
+        createSnapshot(bucket.getVolumeName(), bucket.getName());
+    snapshotDirName2 =
+        createSnapshot(bucket.getVolumeName(), bucket.getName());
+
+
+    // create fabricated links to snapshot dirs
+    //  to confirm that links are recognized even if
+    //  they are don't point to the checkpoint directory
+    Path fabricatedFile = Paths.get(snapshotDirName, "fabricatedFile");
+    Path fabricatedLink = Paths.get(snapshotDirName2, "fabricatedFile");
+
+    Files.write(fabricatedFile,
+        "fabricatedData".getBytes(StandardCharsets.UTF_8));
+    Files.createLink(fabricatedLink, fabricatedFile);
+
+    // simulate links from the compaction dir
+    compactionDirPath = Paths.get(metaDir.toString(),
+        OM_SNAPSHOT_DIFF_DIR, OM_COMPACTION_BACKUP_DIR);
+    Path fabricatedLink2 = Paths.get(compactionDirPath.toString(),
+        "fabricatedFile");
+    Files.createLink(fabricatedLink2, fabricatedFile);
+    Path currentFile = Paths.get(metaDir.toString(),
+                                    OM_DB_NAME, "CURRENT");
+    Path currentLink = Paths.get(compactionDirPath.toString(), "CURRENT");
+    Files.createLink(currentLink, currentFile);
+
+    dbCheckpoint = cluster.getOzoneManager()
+        .getMetadataManager().getStore()
+        .getCheckpoint(true);
+
   }
 
-  @Override
-  public long getCheckpointTimestamp() {
-    return 0;
+  private String createSnapshot(String vname, String bname)
+      throws IOException, InterruptedException, TimeoutException {
+    final OzoneManager om = cluster.getOzoneManager();
+    String snapshotName = UUID.randomUUID().toString();
+    OzoneManagerProtocol writeClient = cluster.getRpcClient().getObjectStore()
+        .getClientProxy().getOzoneManagerClient();
+
+    writeClient.createSnapshot(vname, bname, snapshotName);
+    SnapshotInfo snapshotInfo = om.getMetadataManager().getSnapshotInfoTable()
+        .get(SnapshotInfo.getTableKey(vname, bname, snapshotName));
+    String snapshotPath = getSnapshotPath(conf, snapshotInfo)
+        + OM_KEY_PREFIX;
+    GenericTestUtils.waitFor(() -> new File(snapshotPath).exists(),
+        100, 2000);
+    return snapshotPath;
   }
 
-  @Override
-  public long getLatestSequenceNumber() {
-    return 0;
+  private Set<String> getFiles(Path path, int truncateLength)
+      throws IOException {
+    return getFiles(path, truncateLength, new HashSet<>());
+  }
+
+  // Get all files below path, recursively, (skipping fabricated files)
+  @SuppressFBWarnings({"NP_NULL_ON_SOME_PATH_FROM_RETURN_VALUE"})
+  private Set<String> getFiles(Path path, int truncateLength,
+      Set<String> fileSet) throws IOException {
+    try (Stream<Path> files = Files.list(path)) {
+      for (Path file : files.collect(Collectors.toList())) {
+        if (file.toFile().isDirectory()) {
+          getFiles(file, truncateLength, fileSet);
+        }
+        if (!file.getFileName().toString().equals("fabricatedFile")) {
+          fileSet.add(truncateFileName(truncateLength, file));
+        }
+      }
+    }
+    return fileSet;
   }
 
-  @Override
-  public long checkpointCreationTimeTaken() {
-    return 0;
+  // tests to see that fabricated link lines in hardlink file are

Review Comment:
   1. This is not a test.
   2. Isn't supposed to be a java doc comment?



##########
hadoop-ozone/ozone-manager/src/main/java/org/apache/hadoop/ozone/om/OMDBCheckpointServlet.java:
##########
@@ -82,4 +112,165 @@ public void init() throws ServletException {
         allowedGroups,
         om.isSpnegoEnabled());
   }
+
+  @Override
+  public void writeDbDataToStream(DBCheckpoint checkpoint,
+                                  HttpServletRequest request,
+                                  OutputStream destination)
+      throws IOException, InterruptedException, CompressorException {
+    // Map of inodes to path
+    HashMap<Object, Path> copyFiles = new HashMap<>();
+    // Map of link to path
+    HashMap<Path, Path> hardLinkFiles = new HashMap<>();
+
+    getFilesForArchive(checkpoint, copyFiles, hardLinkFiles,
+        includeSnapshotData(request));
+
+    try (CompressorOutputStream gzippedOut = new CompressorStreamFactory()
+        .createCompressorOutputStream(CompressorStreamFactory.GZIP,
+            destination)) {
+
+      try (TarArchiveOutputStream archiveOutputStream =
+          new TarArchiveOutputStream(gzippedOut)) {
+        archiveOutputStream
+            .setLongFileMode(TarArchiveOutputStream.LONGFILE_POSIX);
+
+        writeFilesToArchive(copyFiles, hardLinkFiles, archiveOutputStream);
+      }
+    } catch (CompressorException e) {
+      throw new IOException(
+          "Can't compress the checkpoint: " +
+              checkpoint.getCheckpointLocation(), e);
+    }
+  }
+
+  private void getFilesForArchive(DBCheckpoint checkpoint,
+                                  Map<Object, Path> copyFiles,
+                                  Map<Path, Path> hardLinkFiles,
+                                  boolean includeSnapshotData)
+      throws IOException, InterruptedException {
+
+    // Get the active fs files
+    Path dir = checkpoint.getCheckpointLocation();
+    processDir(dir, copyFiles, hardLinkFiles);
+
+    if (!includeSnapshotData) {
+      return;
+    }
+
+    // Get the snapshot files
+    waitForSnapshotDirs(checkpoint);
+    Path snapshotDir = Paths.get(OMStorage.getOmDbDir(getConf()).toString(),
+        OM_SNAPSHOT_DIR);
+    processDir(snapshotDir, copyFiles, hardLinkFiles);
+  }
+
+  // The snapshotInfo table may contain a snapshot that
+  //  doesn't yet exist on the fs, so wait a few seconds for it
+  private void waitForSnapshotDirs(DBCheckpoint checkpoint)
+      throws IOException, InterruptedException {
+
+    OzoneConfiguration conf = getConf();
+
+    // get snapshotInfo entries
+    OmMetadataManagerImpl checkpointMetadataManager =
+        OmMetadataManagerImpl.createCheckpointMetadataManager(
+            conf, checkpoint);
+    try (TableIterator<String, ? extends Table.KeyValue<String, SnapshotInfo>>
+        iterator = checkpointMetadataManager
+        .getSnapshotInfoTable().iterator()) {
+
+      // for each entry, wait for corresponding directory
+      while (iterator.hasNext()) {
+        Table.KeyValue<String, SnapshotInfo> entry = iterator.next();
+        Path path = Paths.get(getSnapshotPath(conf, entry.getValue()));
+        waitForDirToExist(path);
+      }
+    }
+  }
+
+  private void waitForDirToExist(Path dir)
+      throws IOException, InterruptedException {
+    long endTime = System.currentTimeMillis() +
+        Duration.parse(DURATION_TO_WAIT_FOR_DIRECTORY).toMillis();
+    while (!dir.toFile().exists()) {
+      Thread.sleep(100);
+      if (System.currentTimeMillis() > endTime) {
+        break;
+      }
+    }
+    if (System.currentTimeMillis() > endTime) {
+      throw new IOException("snapshot dir doesn't exist: " + dir);
+    }
+  }
+
+  private void processDir(Path dir, Map<Object, Path> copyFiles,
+                          Map<Path, Path> hardLinkFiles)
+      throws IOException {
+    try (Stream<Path> files = Files.list(dir)) {
+      for (Path file : files.collect(Collectors.toList())) {
+        if (file.toFile().isDirectory()) {
+          processDir(file, copyFiles, hardLinkFiles);
+        } else {
+          processFile(file, copyFiles, hardLinkFiles);
+        }
+      }
+    }
+  }
+
+  private void processFile(Path file, Map<Object, Path> copyFiles,
+                           Map<Path, Path> hardLinkFiles) throws IOException {
+    // get the inode
+    Object key = OmSnapshotManager.getINode(file);
+    // If we already have the inode, store as hard link
+    if (copyFiles.containsKey(key)) {
+      hardLinkFiles.put(file, copyFiles.get(key));
+    } else {
+      copyFiles.put(key, file);
+    }
+  }
+
+  // returns value of http request parameter
+  private boolean includeSnapshotData(HttpServletRequest request) {
+    String includeParam =
+        request.getParameter(OZONE_DB_CHECKPOINT_INCLUDE_SNAPSHOT_DATA);
+    if (StringUtils.isNotEmpty(includeParam)) {
+      return Boolean.parseBoolean(includeParam);
+    }
+    return false;
+  }
+
+  @SuppressFBWarnings({"NP_NULL_ON_SOME_PATH_FROM_RETURN_VALUE"})
+  private void writeFilesToArchive(HashMap<Object, Path> copyFiles,
+                         HashMap<Path, Path> hardLinkFiles,
+                         ArchiveOutputStream archiveOutputStream)
+      throws IOException {
+
+    File metaDirPath = ServerUtils.getOzoneMetaDirPath(getConf());
+    int truncateLength = metaDirPath.toString().length() + 1;
+
+    // Go through each of the files to be copied and add to archive
+    for (Path file : copyFiles.values()) {
+      String fixedFile = truncateFileName(truncateLength, file);
+      if (fixedFile.startsWith(OM_CHECKPOINT_DIR)) {
+        // checkpoint files go to root of tarball
+        fixedFile = Paths.get(fixedFile).getFileName().toString();
+      }
+      includeFile(file.toFile(), fixedFile,
+          archiveOutputStream);

Review Comment:
   ```suggestion
         includeFile(file.toFile(), fixedFile, archiveOutputStream);
   ```
   Could be fit in one line.



##########
hadoop-ozone/ozone-manager/src/main/java/org/apache/hadoop/ozone/om/OzoneManager.java:
##########
@@ -3632,7 +3650,19 @@ File replaceOMDBWithCheckpoint(long lastAppliedIndex, File oldDB,
       }
       throw e;
     }
-    return dbBackup;
+    return dbBackupDir;
+  }
+
+  // move the new snapshot directory into place and create hard links
+  private void moveOmSnapshotData(Path dbPath, Path dbSnapshotsDir)
+      throws IOException {
+    Path incomingSnapshotsDir = Paths.get(dbPath.toString(),
+        OM_SNAPSHOT_DIR);
+    if (incomingSnapshotsDir.toFile().exists()) {
+      Files.move(incomingSnapshotsDir, dbSnapshotsDir);
+      OmSnapshotManager.createHardLinks(dbPath);
+    }
+

Review Comment:
   unnecessary line.



##########
hadoop-ozone/ozone-manager/src/main/java/org/apache/hadoop/ozone/om/OMDBCheckpointServlet.java:
##########
@@ -82,4 +112,165 @@ public void init() throws ServletException {
         allowedGroups,
         om.isSpnegoEnabled());
   }
+
+  @Override
+  public void writeDbDataToStream(DBCheckpoint checkpoint,
+                                  HttpServletRequest request,
+                                  OutputStream destination)
+      throws IOException, InterruptedException, CompressorException {
+    // Map of inodes to path
+    HashMap<Object, Path> copyFiles = new HashMap<>();
+    // Map of link to path
+    HashMap<Path, Path> hardLinkFiles = new HashMap<>();

Review Comment:
   Use `Map` instead of `HashMap` to declare variables. 
   
   https://medium.com/javarevisited/oop-good-practices-coding-to-the-interface-baea84fd60d3
   



##########
hadoop-ozone/integration-test/src/test/java/org/apache/hadoop/ozone/om/TestOMRatisSnapshots.java:
##########
@@ -227,6 +233,20 @@ public void testInstallSnapshot() throws Exception {
         getDefaultBucketLayout()).get(followerOMMetaMngr.getOzoneKey(
         volumeName, bucketName, newKeys.get(0))));
      */
+
+    // read back data from the OM snapshot
+    OmKeyArgs omKeyArgs = new OmKeyArgs.Builder()
+        .setVolumeName(volumeName)
+            .setBucketName(bucketName)
+                .setKeyName(".snapshot/snap1/" + keys.get(0)).build();

Review Comment:
   ```suggestion
       OmKeyArgs omKeyArgs = new OmKeyArgs.Builder()
           .setVolumeName(volumeName)
           .setBucketName(bucketName)
           .setKeyName(".snapshot/snap1/" + keys.get(0)).build();
   ```
   
   Indentation is bit off. It should be like this.



##########
hadoop-ozone/integration-test/src/test/java/org/apache/hadoop/ozone/om/TestOMRatisSnapshots.java:
##########
@@ -227,6 +233,20 @@ public void testInstallSnapshot() throws Exception {
         getDefaultBucketLayout()).get(followerOMMetaMngr.getOzoneKey(
         volumeName, bucketName, newKeys.get(0))));
      */
+
+    // read back data from the OM snapshot
+    OmKeyArgs omKeyArgs = new OmKeyArgs.Builder()
+        .setVolumeName(volumeName)
+            .setBucketName(bucketName)
+                .setKeyName(".snapshot/snap1/" + keys.get(0)).build();
+    OmKeyInfo omKeyInfo = null;
+    try {
+      omKeyInfo = followerOM.lookupKey(omKeyArgs);
+    } catch (Exception e) {
+      Assertions.fail("received exception: " + e);
+    }
+    Assertions.assertTrue(omKeyInfo != null);

Review Comment:
   ```suggestion
       Assertions.assertNotNull(omKeyInfo);
   ```



##########
hadoop-ozone/ozone-manager/src/test/java/org/apache/hadoop/ozone/om/TestOmSnapshotManager.java:
##########
@@ -114,6 +127,61 @@ public void testCloseOnEviction() throws IOException {
     verify(firstSnapshotStore, timeout(3000).times(1)).close();
   }
 
+  @Test
+  @SuppressFBWarnings({"NP_NULL_ON_SOME_PATH"})
+  public void testHardLinkCreation() throws IOException {
+    byte[] dummyData = {0};
+
+

Review Comment:
   Remove extra line.



##########
hadoop-ozone/ozone-manager/src/main/java/org/apache/hadoop/ozone/om/OMDBCheckpointServlet.java:
##########
@@ -82,4 +112,165 @@ public void init() throws ServletException {
         allowedGroups,
         om.isSpnegoEnabled());
   }
+
+  @Override
+  public void writeDbDataToStream(DBCheckpoint checkpoint,
+                                  HttpServletRequest request,
+                                  OutputStream destination)
+      throws IOException, InterruptedException, CompressorException {
+    // Map of inodes to path
+    HashMap<Object, Path> copyFiles = new HashMap<>();
+    // Map of link to path
+    HashMap<Path, Path> hardLinkFiles = new HashMap<>();
+
+    getFilesForArchive(checkpoint, copyFiles, hardLinkFiles,
+        includeSnapshotData(request));
+
+    try (CompressorOutputStream gzippedOut = new CompressorStreamFactory()
+        .createCompressorOutputStream(CompressorStreamFactory.GZIP,
+            destination)) {
+
+      try (TarArchiveOutputStream archiveOutputStream =
+          new TarArchiveOutputStream(gzippedOut)) {
+        archiveOutputStream
+            .setLongFileMode(TarArchiveOutputStream.LONGFILE_POSIX);
+
+        writeFilesToArchive(copyFiles, hardLinkFiles, archiveOutputStream);
+      }
+    } catch (CompressorException e) {
+      throw new IOException(
+          "Can't compress the checkpoint: " +
+              checkpoint.getCheckpointLocation(), e);
+    }
+  }
+
+  private void getFilesForArchive(DBCheckpoint checkpoint,
+                                  Map<Object, Path> copyFiles,
+                                  Map<Path, Path> hardLinkFiles,
+                                  boolean includeSnapshotData)
+      throws IOException, InterruptedException {
+
+    // Get the active fs files
+    Path dir = checkpoint.getCheckpointLocation();
+    processDir(dir, copyFiles, hardLinkFiles);
+
+    if (!includeSnapshotData) {
+      return;
+    }
+
+    // Get the snapshot files
+    waitForSnapshotDirs(checkpoint);
+    Path snapshotDir = Paths.get(OMStorage.getOmDbDir(getConf()).toString(),
+        OM_SNAPSHOT_DIR);
+    processDir(snapshotDir, copyFiles, hardLinkFiles);
+  }
+
+  // The snapshotInfo table may contain a snapshot that
+  //  doesn't yet exist on the fs, so wait a few seconds for it
+  private void waitForSnapshotDirs(DBCheckpoint checkpoint)
+      throws IOException, InterruptedException {
+
+    OzoneConfiguration conf = getConf();
+
+    // get snapshotInfo entries
+    OmMetadataManagerImpl checkpointMetadataManager =
+        OmMetadataManagerImpl.createCheckpointMetadataManager(
+            conf, checkpoint);
+    try (TableIterator<String, ? extends Table.KeyValue<String, SnapshotInfo>>
+        iterator = checkpointMetadataManager
+        .getSnapshotInfoTable().iterator()) {
+
+      // for each entry, wait for corresponding directory
+      while (iterator.hasNext()) {
+        Table.KeyValue<String, SnapshotInfo> entry = iterator.next();
+        Path path = Paths.get(getSnapshotPath(conf, entry.getValue()));
+        waitForDirToExist(path);
+      }
+    }
+  }
+
+  private void waitForDirToExist(Path dir)
+      throws IOException, InterruptedException {
+    long endTime = System.currentTimeMillis() +
+        Duration.parse(DURATION_TO_WAIT_FOR_DIRECTORY).toMillis();
+    while (!dir.toFile().exists()) {
+      Thread.sleep(100);
+      if (System.currentTimeMillis() > endTime) {
+        break;
+      }
+    }
+    if (System.currentTimeMillis() > endTime) {
+      throw new IOException("snapshot dir doesn't exist: " + dir);
+    }
+  }
+
+  private void processDir(Path dir, Map<Object, Path> copyFiles,
+                          Map<Path, Path> hardLinkFiles)
+      throws IOException {
+    try (Stream<Path> files = Files.list(dir)) {
+      for (Path file : files.collect(Collectors.toList())) {
+        if (file.toFile().isDirectory()) {
+          processDir(file, copyFiles, hardLinkFiles);
+        } else {
+          processFile(file, copyFiles, hardLinkFiles);
+        }
+      }
+    }
+  }
+
+  private void processFile(Path file, Map<Object, Path> copyFiles,
+                           Map<Path, Path> hardLinkFiles) throws IOException {
+    // get the inode
+    Object key = OmSnapshotManager.getINode(file);
+    // If we already have the inode, store as hard link
+    if (copyFiles.containsKey(key)) {
+      hardLinkFiles.put(file, copyFiles.get(key));
+    } else {
+      copyFiles.put(key, file);
+    }
+  }
+
+  // returns value of http request parameter
+  private boolean includeSnapshotData(HttpServletRequest request) {
+    String includeParam =
+        request.getParameter(OZONE_DB_CHECKPOINT_INCLUDE_SNAPSHOT_DATA);
+    if (StringUtils.isNotEmpty(includeParam)) {
+      return Boolean.parseBoolean(includeParam);
+    }
+    return false;
+  }
+
+  @SuppressFBWarnings({"NP_NULL_ON_SOME_PATH_FROM_RETURN_VALUE"})
+  private void writeFilesToArchive(HashMap<Object, Path> copyFiles,
+                         HashMap<Path, Path> hardLinkFiles,
+                         ArchiveOutputStream archiveOutputStream)

Review Comment:
   alignment is off for declaration of `hardLinkFiles` and  `archiveOutputStream`. Also use Map.



##########
hadoop-ozone/integration-test/src/test/java/org/apache/hadoop/ozone/om/TestOMRatisSnapshots.java:
##########
@@ -227,6 +233,20 @@ public void testInstallSnapshot() throws Exception {
         getDefaultBucketLayout()).get(followerOMMetaMngr.getOzoneKey(
         volumeName, bucketName, newKeys.get(0))));
      */
+
+    // read back data from the OM snapshot
+    OmKeyArgs omKeyArgs = new OmKeyArgs.Builder()
+        .setVolumeName(volumeName)
+            .setBucketName(bucketName)
+                .setKeyName(".snapshot/snap1/" + keys.get(0)).build();
+    OmKeyInfo omKeyInfo = null;
+    try {
+      omKeyInfo = followerOM.lookupKey(omKeyArgs);
+    } catch (Exception e) {

Review Comment:
   I feel this is unnecessary to catch exception here.



##########
hadoop-ozone/integration-test/src/test/java/org/apache/hadoop/ozone/om/TestOMRatisSnapshots.java:
##########
@@ -537,6 +557,36 @@ public void testInstallCorruptedCheckpointFailure() throws Exception {
     Assert.assertTrue(logCapture.getOutput().contains(msg));
   }
 
+  private void createSnapshot(OzoneManager leaderOM, List<String> keys)
+      throws TimeoutException, InterruptedException, IOException {
+    // Avoid double buffer issue waiting for keys
+    GenericTestUtils.waitFor(() -> {
+      try {
+        OmKeyInfo key = leaderOM.getMetadataManager()
+            .getKeyTable(ozoneBucket.getBucketLayout())
+            .getSkipCache(leaderOM.getMetadataManager()
+            .getOzoneKey(volumeName, bucketName, keys.get(0)));
+        return key != null;
+      } catch (Exception e) {
+        return false;
+      }
+    }, 100, 10000);
+    objectStore.createSnapshot(volumeName, bucketName, "snap1");
+
+    // allow the snapshot to be written to the info table
+    GenericTestUtils.waitFor(() -> {
+      try {
+        SnapshotInfo snapshotInfo =

Review Comment:
   ```suggestion
           String tableKey = SnapshotInfo.getTableKey(volumeName,
               bucketName,
               "snap1");
           SnapshotInfo snapshotInfo = leaderOM.getMetadataManager()
               .getSnapshotInfoTable()
               .getSkipCache(tableKey);
   ```



##########
hadoop-ozone/ozone-manager/src/main/java/org/apache/hadoop/ozone/om/OzoneManager.java:
##########
@@ -3617,13 +3631,17 @@ File replaceOMDBWithCheckpoint(long lastAppliedIndex, File oldDB,
       // starting up.
       Files.createFile(markerFile);
       FileUtils.moveDirectory(checkpointPath, oldDB.toPath());
+      moveOmSnapshotData(oldDB.toPath(), dbSnapshotsDir.toPath());
       Files.deleteIfExists(markerFile);
     } catch (IOException e) {
       LOG.error("Failed to move downloaded DB checkpoint {} to metadata " +
               "directory {}. Resetting to original DB.", checkpointPath,
           oldDB.toPath());
       try {

Review Comment:
   This try-catch block seems complex if there is no context. It would be better to extract out this part of code to some function.



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


[GitHub] [ozone] GeorgeJahad commented on a diff in pull request #3980: HDDS-6961. [Snapshot] Bootstrapping slow followers/new followers.

Posted by GitBox <gi...@apache.org>.
GeorgeJahad commented on code in PR #3980:
URL: https://github.com/apache/ozone/pull/3980#discussion_r1034123721


##########
hadoop-hdds/rocksdb-checkpoint-differ/src/main/java/org/apache/ozone/rocksdiff/RocksDBCheckpointDiffer.java:
##########
@@ -164,19 +164,19 @@ public RocksDBCheckpointDiffer(String metadataDir, String sstBackupDir,
     this.activeDBLocationStr = activeDBLocation.toString() + "/";
   }
 
-  private void setCompactionLogDir(String metadataDir,
+  private void setCompactionLogDir(String snapshotDiffDir,
       String compactionLogDirName) {
 
-    final File parentDir = new File(metadataDir);
+    final File parentDir = new File(snapshotDiffDir);
     if (!parentDir.exists()) {
-      if (!parentDir.mkdir()) {
+      if (!parentDir.mkdirs()) {
         LOG.error("Error creating compaction log parent dir.");
         return;
       }
     }
 
     this.compactionLogDir =
-        Paths.get(metadataDir, compactionLogDirName).toString();
+        Paths.get(parentDir.toString(), compactionLogDirName).toString();

Review Comment:
   Paths.get() takes a string: https://docs.oracle.com/javase/7/docs/api/java/nio/file/Paths.html#get(java.lang.String,%20java.lang.String...)



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


[GitHub] [ozone] smengcl commented on pull request #3980: HDDS-6961. [Snapshot] Bootstrapping slow followers/new followers.

Posted by "smengcl (via GitHub)" <gi...@apache.org>.
smengcl commented on PR #3980:
URL: https://github.com/apache/ozone/pull/3980#issuecomment-1489726374

   CI passed. I will merge this in a minute.
   
   Thanks @GeorgeJahad a ton for working on the patch. Thanks @hemantk-12 @prashantpogde for reviewing this.


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


[GitHub] [ozone] smengcl merged pull request #3980: HDDS-6961. [Snapshot] Bootstrapping slow followers/new followers.

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


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


[GitHub] [ozone] GeorgeJahad commented on a diff in pull request #3980: HDDS-6961. [Snapshot] Bootstrapping slow followers/new followers.

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


##########
hadoop-ozone/ozone-manager/src/main/java/org/apache/hadoop/ozone/om/OMDBCheckpointServlet.java:
##########
@@ -82,4 +112,165 @@ public void init() throws ServletException {
         allowedGroups,
         om.isSpnegoEnabled());
   }
+
+  @Override
+  public void writeDbDataToStream(DBCheckpoint checkpoint,
+                                  HttpServletRequest request,
+                                  OutputStream destination)
+      throws IOException, InterruptedException, CompressorException {
+    // Map of inodes to path
+    HashMap<Object, Path> copyFiles = new HashMap<>();
+    // Map of link to path
+    HashMap<Path, Path> hardLinkFiles = new HashMap<>();
+
+    getFilesForArchive(checkpoint, copyFiles, hardLinkFiles,
+        includeSnapshotData(request));
+
+    try (CompressorOutputStream gzippedOut = new CompressorStreamFactory()
+        .createCompressorOutputStream(CompressorStreamFactory.GZIP,
+            destination)) {
+
+      try (TarArchiveOutputStream archiveOutputStream =
+          new TarArchiveOutputStream(gzippedOut)) {
+        archiveOutputStream
+            .setLongFileMode(TarArchiveOutputStream.LONGFILE_POSIX);
+
+        writeFilesToArchive(copyFiles, hardLinkFiles, archiveOutputStream);
+      }
+    } catch (CompressorException e) {
+      throw new IOException(
+          "Can't compress the checkpoint: " +
+              checkpoint.getCheckpointLocation(), e);
+    }
+  }
+
+  private void getFilesForArchive(DBCheckpoint checkpoint,
+                                  Map<Object, Path> copyFiles,
+                                  Map<Path, Path> hardLinkFiles,
+                                  boolean includeSnapshotData)
+      throws IOException, InterruptedException {
+
+    // Get the active fs files
+    Path dir = checkpoint.getCheckpointLocation();
+    processDir(dir, copyFiles, hardLinkFiles);
+
+    if (!includeSnapshotData) {
+      return;
+    }
+
+    // Get the snapshot files
+    waitForSnapshotDirs(checkpoint);
+    Path snapshotDir = Paths.get(OMStorage.getOmDbDir(getConf()).toString(),
+        OM_SNAPSHOT_DIR);
+    processDir(snapshotDir, copyFiles, hardLinkFiles);
+  }
+
+  // The snapshotInfo table may contain a snapshot that
+  //  doesn't yet exist on the fs, so wait a few seconds for it
+  private void waitForSnapshotDirs(DBCheckpoint checkpoint)
+      throws IOException, InterruptedException {
+
+    OzoneConfiguration conf = getConf();
+
+    // get snapshotInfo entries
+    OmMetadataManagerImpl checkpointMetadataManager =
+        OmMetadataManagerImpl.createCheckpointMetadataManager(
+            conf, checkpoint);
+    try (TableIterator<String, ? extends Table.KeyValue<String, SnapshotInfo>>
+        iterator = checkpointMetadataManager
+        .getSnapshotInfoTable().iterator()) {
+
+      // for each entry, wait for corresponding directory
+      while (iterator.hasNext()) {
+        Table.KeyValue<String, SnapshotInfo> entry = iterator.next();
+        Path path = Paths.get(getSnapshotPath(conf, entry.getValue()));
+        waitForDirToExist(path);
+      }
+    }
+  }
+
+  private void waitForDirToExist(Path dir)
+      throws IOException, InterruptedException {
+    long endTime = System.currentTimeMillis() +
+        Duration.parse(DURATION_TO_WAIT_FOR_DIRECTORY).toMillis();
+    while (!dir.toFile().exists()) {
+      Thread.sleep(100);
+      if (System.currentTimeMillis() > endTime) {
+        break;
+      }
+    }
+    if (System.currentTimeMillis() > endTime) {
+      throw new IOException("snapshot dir doesn't exist: " + dir);

Review Comment:
   fixed (now line 198)



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


[GitHub] [ozone] GeorgeJahad commented on a diff in pull request #3980: HDDS-6961. [Snapshot] Bootstrapping slow followers/new followers.

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


##########
hadoop-ozone/integration-test/src/test/java/org/apache/hadoop/ozone/om/TestOMDbCheckpointServlet.java:
##########
@@ -259,69 +291,259 @@ public void testSpnegoEnabled() throws Exception {
   }
 
   @Test
-  public void testWriteCheckpointToOutputStream() throws Exception {
-
-    FileInputStream fis = null;
-    FileOutputStream fos = null;
-
-    try {
-      String testDirName = folder.newFolder().getAbsolutePath();
-      File file = new File(testDirName + "/temp1.txt");
-      OutputStreamWriter writer = new OutputStreamWriter(
-          new FileOutputStream(file), StandardCharsets.UTF_8);
-      writer.write("Test data 1");
-      writer.close();
-
-      file = new File(testDirName + "/temp2.txt");
-      writer = new OutputStreamWriter(
-          new FileOutputStream(file), StandardCharsets.UTF_8);
-      writer.write("Test data 2");
-      writer.close();
-
-      File outputFile =
-          new File(Paths.get(testDirName, "output_file.tgz").toString());
-      TestDBCheckpoint dbCheckpoint = new TestDBCheckpoint(
-          Paths.get(testDirName));
-      writeDBCheckpointToStream(dbCheckpoint,
-          new FileOutputStream(outputFile));
-      assertNotNull(outputFile);
-    } finally {
-      IOUtils.closeStream(fis);
-      IOUtils.closeStream(fos);
+  public void testWriteDbDataToStream()
+      throws Exception {
+    prepSnapshotData();
+    // set http param to include snapshot data
+    when(requestMock.getParameter(OZONE_DB_CHECKPOINT_INCLUDE_SNAPSHOT_DATA))
+        .thenReturn("true");
+
+    // get the tarball
+    try (FileOutputStream fileOutputStream = new FileOutputStream(tempFile)) {
+      omDbCheckpointServletMock.writeDbDataToStream(dbCheckpoint, requestMock,
+          fileOutputStream);
+    }
+
+    // Untar the file into a temp folder to be examined
+    String testDirName = folder.newFolder().getAbsolutePath();
+    int testDirLength = testDirName.length() + 1;
+    String newDbDirName = testDirName + OM_KEY_PREFIX + OM_DB_NAME;
+    int newDbDirLength = newDbDirName.length() + 1;
+    File newDbDir = new File(newDbDirName);
+    newDbDir.mkdirs();
+    FileUtil.unTar(tempFile, newDbDir);
+
+    // Move snapshot dir to correct location
+    new File(newDbDirName, OM_SNAPSHOT_DIR)
+        .renameTo(new File(newDbDir.getParent(), OM_SNAPSHOT_DIR));
+
+
+    // Confirm the checkpoint directories match, (after remove extras)
+    Path checkpointLocation = dbCheckpoint.getCheckpointLocation();
+    Set<String> initialCheckpointSet = getFiles(checkpointLocation,
+        checkpointLocation.toString().length() + 1);
+    Path finalCheckpointLocation = Paths.get(newDbDirName);
+    Set<String> finalCheckpointSet = getFiles(finalCheckpointLocation,
+        newDbDirLength);
+
+    Assert.assertTrue("hardlink file exists in checkpoint dir",
+        finalCheckpointSet.contains(OM_HARDLINK_FILE));
+    finalCheckpointSet.remove(OM_HARDLINK_FILE);
+    Assert.assertEquals(initialCheckpointSet, finalCheckpointSet);
+
+    int metaDirLength = metaDir.toString().length() + 1;
+    String shortSnapshotLocation =
+        truncateFileName(metaDirLength, Paths.get(snapshotDirName));
+    String shortSnapshotLocation2 =
+        truncateFileName(metaDirLength, Paths.get(snapshotDirName2));
+    String shortCompactionDirLocation =
+        truncateFileName(metaDirLength, compactionDirPath);
+
+    Set<String> finalFullSet =
+        getFiles(Paths.get(testDirName, OM_SNAPSHOT_DIR), testDirLength);
+
+    // check each line in the hard link file
+    Stream<String> lines = Files.lines(Paths.get(newDbDirName,
+        OM_HARDLINK_FILE));
+
+    List<String> fabricatedLinkLines = new ArrayList<>();
+    for (String line: lines.collect(Collectors.toList())) {
+      Assert.assertFalse("CURRENT file is not a hard link",
+          line.contains("CURRENT"));
+      if (line.contains("fabricatedFile")) {
+        fabricatedLinkLines.add(line);
+      } else {
+        checkLine(shortSnapshotLocation, shortSnapshotLocation2, line);
+        // add links to the final set
+        finalFullSet.add(line.split("\t")[0]);
+      }
     }
+
+    Set<String> directories = Sets.newHashSet(
+        shortSnapshotLocation, shortSnapshotLocation2,
+        shortCompactionDirLocation);
+    checkFabricatedLines(directories, fabricatedLinkLines, testDirName);
+
+    Set<String> initialFullSet =
+        getFiles(Paths.get(metaDir.toString(), OM_SNAPSHOT_DIR), metaDirLength);
+    Assert.assertEquals("found expected snapshot files",
+        initialFullSet, finalFullSet);
   }
-}
 
-class TestDBCheckpoint implements DBCheckpoint {
+  @Test
+  public void testWriteDbDataWithoutOmSnapshot()
+      throws Exception {
+    prepSnapshotData();
+
+    // set http param to exclude snapshot data
+    when(requestMock.getParameter(OZONE_DB_CHECKPOINT_INCLUDE_SNAPSHOT_DATA))
+        .thenReturn(null);
+
+    // get the tarball
+    try (FileOutputStream fileOutputStream = new FileOutputStream(tempFile)) {
+      omDbCheckpointServletMock.writeDbDataToStream(dbCheckpoint, requestMock,
+          fileOutputStream);
+    }
+
+    // Untar the file into a temp folder to be examined
+    String testDirName = folder.newFolder().getAbsolutePath();
+    int testDirLength = testDirName.length() + 1;
+    FileUtil.unTar(tempFile, new File(testDirName));
 
-  private final Path checkpointFile;
+    // Confirm the checkpoint directories match
+    Path checkpointLocation = dbCheckpoint.getCheckpointLocation();
+    Set<String> initialCheckpointSet = getFiles(checkpointLocation,
+        checkpointLocation.toString().length() + 1);
+    Path finalCheckpointLocation = Paths.get(testDirName);
+    Set<String> finalCheckpointSet = getFiles(finalCheckpointLocation,
+        testDirLength);
 
-  TestDBCheckpoint(Path checkpointFile) {
-    this.checkpointFile = checkpointFile;
+    Assert.assertEquals(initialCheckpointSet, finalCheckpointSet);
   }
 
-  @Override
-  public Path getCheckpointLocation() {
-    return checkpointFile;
+
+
+  private void prepSnapshotData() throws Exception {
+    setupCluster();
+    metaDir = OMStorage.getOmDbDir(conf);
+
+    OzoneBucket bucket = TestDataUtil.createVolumeAndBucket(cluster);
+
+    // Create dummy keys for snapshotting
+    TestDataUtil.createKey(bucket, UUID.randomUUID().toString(),
+        "content");
+    TestDataUtil.createKey(bucket, UUID.randomUUID().toString(),
+        "content");
+
+    // this sleep can be removed after this is fixed:
+    //  https://issues.apache.org/jira/browse/HDDS-7279
+    Thread.sleep(2000);
+    snapshotDirName =
+        createSnapshot(bucket.getVolumeName(), bucket.getName());
+    snapshotDirName2 =
+        createSnapshot(bucket.getVolumeName(), bucket.getName());
+
+
+    // create fabricated links to snapshot dirs
+    //  to confirm that links are recognized even if
+    //  they are don't point to the checkpoint directory
+    Path fabricatedFile = Paths.get(snapshotDirName, "fabricatedFile");
+    Path fabricatedLink = Paths.get(snapshotDirName2, "fabricatedFile");
+
+    Files.write(fabricatedFile,
+        "fabricatedData".getBytes(StandardCharsets.UTF_8));
+    Files.createLink(fabricatedLink, fabricatedFile);
+
+    // simulate links from the compaction dir
+    compactionDirPath = Paths.get(metaDir.toString(),
+        OM_SNAPSHOT_DIFF_DIR, OM_COMPACTION_BACKUP_DIR);
+    Path fabricatedLink2 = Paths.get(compactionDirPath.toString(),
+        "fabricatedFile");
+    Files.createLink(fabricatedLink2, fabricatedFile);
+    Path currentFile = Paths.get(metaDir.toString(),
+                                    OM_DB_NAME, "CURRENT");
+    Path currentLink = Paths.get(compactionDirPath.toString(), "CURRENT");
+    Files.createLink(currentLink, currentFile);
+
+    dbCheckpoint = cluster.getOzoneManager()
+        .getMetadataManager().getStore()
+        .getCheckpoint(true);
+
   }
 
-  @Override
-  public long getCheckpointTimestamp() {
-    return 0;
+  private String createSnapshot(String vname, String bname)
+      throws IOException, InterruptedException, TimeoutException {
+    final OzoneManager om = cluster.getOzoneManager();
+    String snapshotName = UUID.randomUUID().toString();
+    OzoneManagerProtocol writeClient = cluster.getRpcClient().getObjectStore()
+        .getClientProxy().getOzoneManagerClient();
+
+    writeClient.createSnapshot(vname, bname, snapshotName);
+    SnapshotInfo snapshotInfo = om.getMetadataManager().getSnapshotInfoTable()
+        .get(SnapshotInfo.getTableKey(vname, bname, snapshotName));
+    String snapshotPath = getSnapshotPath(conf, snapshotInfo)
+        + OM_KEY_PREFIX;
+    GenericTestUtils.waitFor(() -> new File(snapshotPath).exists(),
+        100, 2000);
+    return snapshotPath;
   }
 
-  @Override
-  public long getLatestSequenceNumber() {
-    return 0;
+  private Set<String> getFiles(Path path, int truncateLength)
+      throws IOException {
+    return getFiles(path, truncateLength, new HashSet<>());
+  }
+
+  // Get all files below path, recursively, (skipping fabricated files)
+  @SuppressFBWarnings({"NP_NULL_ON_SOME_PATH_FROM_RETURN_VALUE"})
+  private Set<String> getFiles(Path path, int truncateLength,
+      Set<String> fileSet) throws IOException {
+    try (Stream<Path> files = Files.list(path)) {
+      for (Path file : files.collect(Collectors.toList())) {
+        if (file.toFile().isDirectory()) {
+          getFiles(file, truncateLength, fileSet);
+        }
+        if (!file.getFileName().toString().equals("fabricatedFile")) {
+          fileSet.add(truncateFileName(truncateLength, file));
+        }
+      }
+    }
+    return fileSet;
   }
 
-  @Override
-  public long checkpointCreationTimeTaken() {
-    return 0;
+  // tests to see that fabricated link lines in hardlink file are

Review Comment:
   changed to java doc



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


[GitHub] [ozone] prashantpogde commented on a diff in pull request #3980: HDDS-6961. [Snapshot] Bootstrapping slow followers/new followers.

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


##########
hadoop-ozone/ozone-manager/src/main/java/org/apache/hadoop/ozone/om/OmSnapshotManager.java:
##########
@@ -279,6 +307,92 @@ private void verifySnapshotInfoForSnapDiff(final SnapshotInfo fromSnapshot,
     }
   }
 
+  /**
+   * Create file of links to add to tarball.
+   * Format of entries are either:
+   * dir1/fileTo fileFrom
+   *    for files in active db or:
+   * dir1/fileTo dir2/fileFrom
+   *    for files in another directory, (either another snapshot dir or
+   *    sst compaction backup directory)
+   * @param truncateLength - Length of initial path to trim in file path.
+   * @param hardLinkFiles - Map of link->file paths.
+   * @return Path to the file of links created.
+   */
+  @SuppressFBWarnings({"NP_NULL_ON_SOME_PATH_FROM_RETURN_VALUE"})
+  static Path createHardLinkList(int truncateLength,
+                                  Map<Path, Path> hardLinkFiles)
+      throws IOException {
+    Path data = Files.createTempFile("data", "txt");
+    StringBuilder sb = new StringBuilder();
+    for (Map.Entry<Path, Path> entry : hardLinkFiles.entrySet()) {
+      String fixedFile = truncateFileName(truncateLength, entry.getValue());
+      // If this file is from the active db, strip the path.
+      if (fixedFile.startsWith(OM_CHECKPOINT_DIR)) {
+        fixedFile = Paths.get(fixedFile).getFileName().toString();
+      }
+      sb.append(truncateFileName(truncateLength, entry.getKey()))

Review Comment:
   why not keep this logic uniform to include the dirname/filefrom both for activedb and snapshots/backupsstfiles  ? This way you don't have to worry about the truncatelength and path stripping.



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


[GitHub] [ozone] prashantpogde commented on a diff in pull request #3980: HDDS-6961. [Snapshot] Bootstrapping slow followers/new followers.

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


##########
hadoop-ozone/ozone-manager/src/main/java/org/apache/hadoop/ozone/om/SstFilteringService.java:
##########
@@ -143,9 +144,11 @@ public BackgroundTaskResult call() throws Exception {
 
           String dbName = OM_DB_NAME + snapshotInfo.getCheckpointDirName();
 
+          String snapshotCheckpointDir = omMetadataDir + OM_KEY_PREFIX +
+              OM_SNAPSHOT_CHECKPOINT_DIR;
           RDBStore rdbStore = (RDBStore) OmMetadataManagerImpl
-              .loadDB(ozoneManager.getConfiguration(), new File(snapshotDir),
-                  dbName, true);
+              .loadDB(ozoneManager.getConfiguration(),
+                  new File(snapshotCheckpointDir), dbName, true);
           RocksDatabase db = rdbStore.getDb();
           db.deleteFilesNotMatchingPrefix(prefixPairs, filterFunction);
 

Review Comment:
   Where are we serializing sst file filtering service with tarball creation ? 



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


[GitHub] [ozone] prashantpogde commented on a diff in pull request #3980: HDDS-6961. [Snapshot] Bootstrapping slow followers/new followers.

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


##########
hadoop-ozone/ozone-manager/src/main/java/org/apache/hadoop/ozone/om/OzoneManager.java:
##########
@@ -3736,13 +3755,17 @@ File replaceOMDBWithCheckpoint(long lastAppliedIndex, File oldDB,
       // starting up.
       Files.createFile(markerFile);
       FileUtils.moveDirectory(checkpointPath, oldDB.toPath());
+      moveOmSnapshotData(oldDB.toPath(), dbSnapshotsDir.toPath());

Review Comment:
   Getting all of snapshot data and installing it from leader can take a long time. We should at least have the logic to skip getting the snapshot directories from leader that already exist on the follower.  You can send the list of snapshot (from snapshot info) that already exists on the follower as part of the http request.



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


[GitHub] [ozone] GeorgeJahad commented on a diff in pull request #3980: HDDS-6961. [Snapshot] Bootstrapping slow followers/new followers.

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


##########
hadoop-ozone/ozone-manager/src/main/java/org/apache/hadoop/ozone/om/OmSnapshotManager.java:
##########
@@ -162,6 +177,12 @@ public static DBCheckpoint createOmSnapshotCheckpoint(
     return dbCheckpoint;
   }
 
+  @VisibleForTesting
+  static Object getINode(Path file) throws IOException {

Review Comment:
   moved



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


[GitHub] [ozone] smengcl commented on pull request #3980: HDDS-6961. [Snapshot] Bootstrapping slow followers/new followers.

Posted by "smengcl (via GitHub)" <gi...@apache.org>.
smengcl commented on PR #3980:
URL: https://github.com/apache/ozone/pull/3980#issuecomment-1487639055

   @GeorgeJahad There is one checkstyle [warning](https://github.com/apache/ozone/actions/runs/4540058938/jobs/8001488734?pr=3980):
   
   ```
   hadoop-ozone/ozone-manager/src/main/java/org/apache/hadoop/ozone/om/snapshot/OmSnapshotUtils.java
    56: First sentence should end with a period.
   ```


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