Skip to content
Draft
Show file tree
Hide file tree
Changes from 12 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -36,9 +36,8 @@
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assertions.fail;
import static org.mockito.ArgumentMatchers.anyCollection;
import static org.mockito.ArgumentMatchers.anyInt;
import static org.mockito.ArgumentMatchers.anyMap;
import static org.mockito.ArgumentMatchers.anySet;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.any;
import static org.mockito.Mockito.anyBoolean;
import static org.mockito.Mockito.doAnswer;
Expand Down Expand Up @@ -84,16 +83,13 @@
import javax.servlet.WriteListener;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.compress.archivers.tar.TarArchiveEntry;
import org.apache.commons.compress.archivers.tar.TarArchiveOutputStream;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.hadoop.fs.FileUtil;
import org.apache.hadoop.hdds.client.ReplicationConfig;
import org.apache.hadoop.hdds.client.ReplicationFactor;
import org.apache.hadoop.hdds.client.ReplicationType;
import org.apache.hadoop.hdds.client.StandaloneReplicationConfig;
import org.apache.hadoop.hdds.conf.OzoneConfiguration;
import org.apache.hadoop.hdds.utils.Archiver;
import org.apache.hadoop.hdds.utils.IOUtils;
import org.apache.hadoop.hdds.utils.db.DBCheckpoint;
import org.apache.hadoop.hdds.utils.db.DBStore;
Expand Down Expand Up @@ -239,19 +235,20 @@ public void write(int b) throws IOException {
doCallRealMethod().when(omDbCheckpointServletMock)
.writeDbDataToStream(any(), any(), any(), any(), any());
doCallRealMethod().when(omDbCheckpointServletMock)
.writeDBToArchive(any(), any(), any(), any(), any(), any(), anyBoolean());
.collectFilesFromDir(any(), any(), any(), anyBoolean(), any());
doCallRealMethod().when(omDbCheckpointServletMock).collectDbDataToTransfer(any(), any(), any());

when(omDbCheckpointServletMock.getBootstrapStateLock())
.thenReturn(lock);
doCallRealMethod().when(omDbCheckpointServletMock).getCheckpoint(any(), anyBoolean());
assertNull(doCallRealMethod().when(omDbCheckpointServletMock).getBootstrapTempData());
doCallRealMethod().when(omDbCheckpointServletMock).
processMetadataSnapshotRequest(any(), any(), anyBoolean(), anyBoolean());
doCallRealMethod().when(omDbCheckpointServletMock).writeDbDataToStream(any(), any(), any(), any());
doCallRealMethod().when(omDbCheckpointServletMock).writeDbDataToStream(any(), any(), any(), any(), any());
doCallRealMethod().when(omDbCheckpointServletMock).getCompactionLogDir();
doCallRealMethod().when(omDbCheckpointServletMock).getSstBackupDir();
doCallRealMethod().when(omDbCheckpointServletMock)
.transferSnapshotData(anySet(), any(), anyCollection(), anyCollection(), any(), any(), anyMap());
.collectSnapshotData(anySet(), anyCollection(), anyCollection(), any(), any());
doCallRealMethod().when(omDbCheckpointServletMock).createAndPrepareCheckpoint(anyBoolean());
doCallRealMethod().when(omDbCheckpointServletMock).getSnapshotDirsFromDB(any(), any(), any());
}
Expand Down Expand Up @@ -298,14 +295,12 @@ public void testWriteDBToArchiveClosesFilesListStream() throws Exception {
// Do not use CALLS_REAL_METHODS for java.nio.file.Files: internal/private static
// methods (eg Files.provider()) get intercepted too and Mockito will try to invoke
// them reflectively, which fails on JDK9+ without --add-opens.
try (MockedStatic<Files> files = mockStatic(Files.class);
TarArchiveOutputStream tar = new TarArchiveOutputStream(new java.io.ByteArrayOutputStream())) {
try (MockedStatic<Files> files = mockStatic(Files.class)) {
files.when(() -> Files.exists(dbDir)).thenReturn(true);
files.when(() -> Files.list(dbDir)).thenReturn(stream);

boolean result = servlet.writeDBToArchive(
new HashSet<>(), dbDir, new AtomicLong(Long.MAX_VALUE),
tar, folder, null, true);
boolean result = servlet.collectFilesFromDir(new HashSet<>(), dbDir,
new AtomicLong(Long.MAX_VALUE), true, new OMDBArchiver());
assertTrue(result);
}

Expand Down Expand Up @@ -446,49 +441,38 @@ public void testWriteDBToArchive(boolean expectOnlySstFiles) throws Exception {
// Create dummy files: one SST, one non-SST
Path sstFile = dbDir.resolve("test.sst");
Files.write(sstFile, "sst content".getBytes(StandardCharsets.UTF_8)); // Write some content to make it non-empty

Path nonSstFile = dbDir.resolve("test.log");
Files.write(nonSstFile, "log content".getBytes(StandardCharsets.UTF_8));
Set<String> sstFilesToExclude = new HashSet<>();
AtomicLong maxTotalSstSize = new AtomicLong(1000000); // Sufficient size
Map<String, String> hardLinkFileMap = new java.util.HashMap<>();
OMDBArchiver omdbArchiver = new OMDBArchiver();
Path tmpDir = folder.resolve("tmp");
Files.createDirectories(tmpDir);
TarArchiveOutputStream mockArchiveOutputStream = mock(TarArchiveOutputStream.class);
omdbArchiver.setTmpDir(tmpDir);
OMDBArchiver omDbArchiverSpy = spy(omdbArchiver);
List<String> fileNames = new ArrayList<>();
try (MockedStatic<Archiver> archiverMock = mockStatic(Archiver.class)) {
archiverMock.when(() -> Archiver.linkAndIncludeFile(any(), any(), any(), any())).thenAnswer(invocation -> {
// Get the actual mockArchiveOutputStream passed from writeDBToArchive
TarArchiveOutputStream aos = invocation.getArgument(2);
File sourceFile = invocation.getArgument(0);
String fileId = invocation.getArgument(1);
fileNames.add(sourceFile.getName());
aos.putArchiveEntry(new TarArchiveEntry(sourceFile, fileId));
aos.write(new byte[100], 0, 100); // Simulate writing
aos.closeArchiveEntry();
return 100L;
});
boolean success = omDbCheckpointServletMock.writeDBToArchive(
sstFilesToExclude, dbDir, maxTotalSstSize, mockArchiveOutputStream,
tmpDir, hardLinkFileMap, expectOnlySstFiles);
assertTrue(success);
verify(mockArchiveOutputStream, times(fileNames.size())).putArchiveEntry(any());
verify(mockArchiveOutputStream, times(fileNames.size())).closeArchiveEntry();
verify(mockArchiveOutputStream, times(fileNames.size())).write(any(byte[].class), anyInt(),
anyInt()); // verify write was called once

boolean containsNonSstFile = false;
for (String fileName : fileNames) {
if (expectOnlySstFiles) {
assertTrue(fileName.endsWith(".sst"), "File is not an SST File");
} else {
containsNonSstFile = true;
}
doAnswer((invocation) -> {
File sourceFile = invocation.getArgument(0);
fileNames.add(sourceFile.getName());
omdbArchiver.recordFileEntry(sourceFile, invocation.getArgument(1));
return null;
}).when(omDbArchiverSpy).recordFileEntry(any(), anyString());
boolean success =
omDbCheckpointServletMock.collectFilesFromDir(sstFilesToExclude, dbDir, maxTotalSstSize, expectOnlySstFiles,
omDbArchiverSpy);
assertTrue(success);
verify(omDbArchiverSpy, times(fileNames.size())).recordFileEntry(any(), anyString());
boolean containsNonSstFile = false;
for (String fileName : fileNames) {
if (expectOnlySstFiles) {
assertTrue(fileName.endsWith(".sst"), "File is not an SST File");
} else {
containsNonSstFile = true;
}
}

if (!expectOnlySstFiles) {
assertTrue(containsNonSstFile, "SST File is not expected");
}
if (!expectOnlySstFiles) {
assertTrue(containsNonSstFile, "SST File is not expected");
}
}

Expand Down Expand Up @@ -905,6 +889,7 @@ private void setupClusterAndMocks(String volumeName, String bucketName,
doCallRealMethod().when(omDbCheckpointServletMock).initialize(any(), any(),
eq(false), any(), any(), eq(false));
doCallRealMethod().when(omDbCheckpointServletMock).getSnapshotDirsFromDB(any(), any(), any());
doCallRealMethod().when(omDbCheckpointServletMock).collectDbDataToTransfer(any(), any(), any());
omDbCheckpointServletMock.initialize(spyDbStore, om.getMetrics().getDBCheckpointMetrics(),
false,
om.getOmAdminUsernames(), om.getOmAdminGroups(), false);
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,150 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package org.apache.hadoop.ozone.om;

import static org.apache.hadoop.hdds.utils.Archiver.includeFile;
import static org.apache.hadoop.hdds.utils.Archiver.tar;
import static org.apache.hadoop.hdds.utils.HddsServerUtil.includeRatisSnapshotCompleteFlag;
import static org.apache.hadoop.ozone.om.OMDBCheckpointServletInodeBasedXfer.writeHardlinkFile;

import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.HashMap;
import java.util.Map;
import org.apache.commons.compress.archivers.ArchiveOutputStream;
import org.apache.commons.compress.archivers.tar.TarArchiveEntry;
import org.apache.hadoop.hdds.conf.OzoneConfiguration;
import org.apache.hadoop.util.Time;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
* Class for handling operations relevant to archiving the OM DB tarball.
* Mainly maintains a map for recording the files collected from reading
* the checkpoint and snapshot DB's. It temporarily creates hardlinks and stores
* the link data in the map to release the bootstrap lock quickly
* and do the actual write at the end outside the lock.
*/
public class OMDBArchiver {

private Path tmpDir;
private Map<String, File> filesToWriteIntoTarball;
private Map<String, String> hardLinkFileMap;
private static final Logger LOG = LoggerFactory.getLogger(OMDBArchiver.class);
private boolean completed;

public OMDBArchiver() {
this.tmpDir = null;
this.filesToWriteIntoTarball = new HashMap<>();
this.hardLinkFileMap = null;
this.completed = false;
}

public void setTmpDir(Path tmpDir) {
this.tmpDir = tmpDir;
}

public Path getTmpDir() {
return tmpDir;
}

public Map<String, String> getHardLinkFileMap() {
return hardLinkFileMap;
}

public Map<String, File> getFilesToWriteIntoTarball() {
return filesToWriteIntoTarball;
}

public void setHardLinkFileMap(Map<String, String> hardLinkFileMap) {
this.hardLinkFileMap = hardLinkFileMap;
}

public boolean isCompleted() {
return completed;
}

public void setCompleted(boolean completed) {
this.completed = completed;
}

/**
* @param file the file to create a hardlink and record into the map
* @param entryName name of the entry corresponding to file
* @return the file size
* @throws IOException in case of hardlink failure
*
* Records the given file entry into the map after taking a hardlink.
*/
public long recordFileEntry(File file, String entryName) throws IOException {
File link = tmpDir.resolve(entryName).toFile();
long bytes = 0;
try {
Files.createLink(link.toPath(), file.toPath());
filesToWriteIntoTarball.put(entryName, link);
bytes = file.length();
} catch (IOException ioe) {
LOG.error("Couldn't create hardlink for file {} while including it in tarball.",
file.getAbsolutePath(), ioe);
throw ioe;
}
return bytes;
}

/**
* @param conf the configuration object to obtain metadata paths
* @param outputStream the tarball archive output stream
* @throws IOException in case of write failure to the archive
*
* Writes all the files captured by the map into the archive and
* also includes the hardlinkFile and the completion marker file.
*/
Comment on lines 126 to 133
Copy link

Copilot AI Jan 20, 2026

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Non-standard javadoc format: Similar to the recordFileEntry method, this javadoc uses @param and @throws tags (lines 113-115) appearing before the method description (lines 117-119). The description should come first, followed by the parameter documentation tags.

Copilot uses AI. Check for mistakes.
public void writeToArchive(OzoneConfiguration conf, OutputStream outputStream)
throws IOException {
long bytesWritten = 0;
long lastLoggedTime = Time.now();
long filesWritten = 0;
try (ArchiveOutputStream<TarArchiveEntry> archiveOutput = tar(outputStream)) {
for (Map.Entry<String, File> kv : filesToWriteIntoTarball.entrySet()) {
String entryName = kv.getKey();
File link = kv.getValue();
try {
bytesWritten += includeFile(link, entryName, archiveOutput);
if (Time.monotonicNow() - lastLoggedTime >= 30000) {
LOG.info("Transferred {} KB, #files {} to checkpoint tarball stream...",
bytesWritten / (1024), filesWritten);
lastLoggedTime = Time.monotonicNow();
}
} catch (IOException ioe) {
LOG.error("Couldn't create hardlink for file {} while including it in tarball.",
link.getAbsolutePath(), ioe);
throw ioe;
} finally {
Files.deleteIfExists(link.toPath());
}
}
if (isCompleted()) {
writeHardlinkFile(conf, hardLinkFileMap, archiveOutput);
includeRatisSnapshotCompleteFlag(archiveOutput);
}
}
}
}
Loading
Loading