This is an automated email from the ASF dual-hosted git repository.
adoroszlai pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/ozone.git
The following commit(s) were added to refs/heads/master by this push:
new c521a16af75 HDDS-17208. Evict old container ID export job records and
archives (#11662)
c521a16af75 is described below
commit c521a16af75bc8eddf51558c8eb809be9dfa2f90
Author: Sarveksha Yeshavantha Raju
<[email protected]>
AuthorDate: Fri Oct 23 20:09:33 2026 +0530
HDDS-17208. Evict old container ID export job records and archives (#11662)
---
.../container/export/ContainerExportManager.java | 49 ++++++++-
.../scm/container/export/ExportFileManager.java | 67 ++++++++++++-
.../export/TestContainerExportManager.java | 109 +++++++++++++++++++--
3 files changed, 208 insertions(+), 17 deletions(-)
diff --git
a/hadoop-hdds/server-scm/src/main/java/org/apache/hadoop/hdds/scm/container/export/ContainerExportManager.java
b/hadoop-hdds/server-scm/src/main/java/org/apache/hadoop/hdds/scm/container/export/ContainerExportManager.java
index a02b59fe48f..beddce4ac66 100644
---
a/hadoop-hdds/server-scm/src/main/java/org/apache/hadoop/hdds/scm/container/export/ContainerExportManager.java
+++
b/hadoop-hdds/server-scm/src/main/java/org/apache/hadoop/hdds/scm/container/export/ContainerExportManager.java
@@ -23,7 +23,9 @@
import java.io.IOException;
import java.io.OutputStream;
import java.nio.charset.StandardCharsets;
+import java.util.ArrayDeque;
import java.util.Collections;
+import java.util.Deque;
import java.util.List;
import java.util.Map;
import java.util.Objects;
@@ -56,12 +58,19 @@
* and the operator must re-submit on the new leader. {@link
ExportFileManager} owns on-disk layout,
* locking, part files, and completed archives; this class tracks {@link
ExportJob} state and
* schedules work.
+ *
+ * <p>Retention: only the {@code maxRetained} most recently finished jobs stay
queryable through
+ * {@link #getExportStatus}, and only the {@code maxRetained} newest completed
archives stay on disk. Older
+ * ones are dropped when a job finishes and when the manager starts, so an
unknown job id can also mean an
+ * evicted one.
*/
public class ContainerExportManager {
private static final Logger LOG =
LoggerFactory.getLogger(ContainerExportManager.class);
private static final long SHUTDOWN_TIMEOUT_MS = 5_000;
+ //TODO: make ozone.scm.container.export.max.terminal.jobs configurable.
+ private static final int DEFAULT_MAX_RETAINED = 10;
private final Map<ExportJob.Id, ExportJob> jobMap = new
ConcurrentHashMap<>();
private final AtomicReference<ExportJob> runningJob = new
AtomicReference<>();
@@ -70,20 +79,29 @@ public class ContainerExportManager {
private final ExportFileManager fileManager;
private final BooleanSupplier isLeaderReady;
private final ExportSizing defaultSizing;
+ private final int maxRetained;
+ // Both deque are only touched by the single worker thread, and by start()
before any job is submitted.
+ private final Deque<ExportJob.Id> finishedJobIds = new ArrayDeque<>();
+ private final Deque<String> completedArchiveNames = new ArrayDeque<>();
public ContainerExportManager(String scmId, ContainerManager
containerManager, BooleanSupplier isLeaderReady,
OzoneConfiguration conf) {
this(scmId, containerManager, isLeaderReady,
- ExportFileManager.resolveExportDirectory(conf), DEFAULT_PART_SIZE,
DEFAULT_BATCH_SIZE);
+ ExportFileManager.resolveExportDirectory(conf), DEFAULT_PART_SIZE,
DEFAULT_BATCH_SIZE, DEFAULT_MAX_RETAINED);
}
ContainerExportManager(String scmId, ContainerManager containerManager,
BooleanSupplier isLeaderReady,
- String exportDirectory, int partSize, int batchSize) {
+ String exportDirectory, int partSize, int batchSize, int maxRetained) {
+ // With maxRetained 0, a finished job would be dropped from jobMap at
once, so its status could never be read.
+ if (maxRetained < 1) {
+ throw new IllegalArgumentException("maxRetained must be at least 1 but
is " + maxRetained);
+ }
this.defaultSizing = new ExportSizing(0, 0, 0, batchSize, partSize);
this.containerManager = Objects.requireNonNull(containerManager,
"containerManager == null");
this.isLeaderReady = Objects.requireNonNull(isLeaderReady, "isLeaderReady
== null");
this.fileManager = new ExportFileManager(exportDirectory);
this.workerPool = newWorkerPool(scmId);
+ this.maxRetained = maxRetained;
}
private ExecutorService newWorkerPool(String scmId) {
@@ -104,8 +122,11 @@ protected void terminated() {
*/
public void start() throws IOException {
fileManager.start();
- LOG.info("ContainerExportManager started (dir={}, partSize={},
batchSize={})",
- fileManager.getExportDirectory(), defaultSizing.getPartSize(),
defaultSizing.getBatchSize());
+ completedArchiveNames.clear();
+ completedArchiveNames.addAll(fileManager.listCompletedArchiveNames());
+ trimCompletedArchives();
+ LOG.info("ContainerExportManager started (dir={}, partSize={},
batchSize={}, maxRetained={})",
+ fileManager.getExportDirectory(), defaultSizing.getPartSize(),
defaultSizing.getBatchSize(), maxRetained);
}
/**
@@ -212,6 +233,8 @@ private void executeExport(ExportJob job) {
if (failure != null) {
fileManager.cleanupFailedJob(job);
}
+ // Evict before publishing the result, so a client that sees this job
done also sees the eviction.
+ retain(job, failure == null && idsWritten > 0);
final boolean cleared = runningJob.compareAndSet(job, null);
if (failure == null) {
job.getFuture().complete(idsWritten);
@@ -222,6 +245,24 @@ private void executeExport(ExportJob job) {
}
}
+ /** Records a finished job and drops the oldest job records and archives
beyond {@code maxRetained}. */
+ private void retain(ExportJob job, boolean hasArchive) {
+ finishedJobIds.addLast(job.getId());
+ while (finishedJobIds.size() > maxRetained) {
+ jobMap.remove(finishedJobIds.removeFirst());
+ }
+ if (hasArchive) {
+ completedArchiveNames.addLast(job.getFileName());
+ trimCompletedArchives();
+ }
+ }
+
+ private void trimCompletedArchives() {
+ while (completedArchiveNames.size() > maxRetained) {
+ fileManager.deleteArchive(completedArchiveNames.removeFirst());
+ }
+ }
+
private Long writeContainerIDs(ExportJob job) throws IOException {
final byte[] buffer = new byte[job.getBatchSize() * 12];
int partNumber = 1;
diff --git
a/hadoop-hdds/server-scm/src/main/java/org/apache/hadoop/hdds/scm/container/export/ExportFileManager.java
b/hadoop-hdds/server-scm/src/main/java/org/apache/hadoop/hdds/scm/container/export/ExportFileManager.java
index 46f66d942b5..f81cab6ae59 100644
---
a/hadoop-hdds/server-scm/src/main/java/org/apache/hadoop/hdds/scm/container/export/ExportFileManager.java
+++
b/hadoop-hdds/server-scm/src/main/java/org/apache/hadoop/hdds/scm/container/export/ExportFileManager.java
@@ -29,10 +29,14 @@
import java.time.Instant;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
+import java.time.format.DateTimeParseException;
import java.util.Arrays;
+import java.util.Collections;
import java.util.Comparator;
+import java.util.List;
import java.util.Objects;
import java.util.function.BooleanSupplier;
+import java.util.stream.Collectors;
import java.util.zip.GZIPOutputStream;
import org.apache.commons.compress.archivers.ArchiveOutputStream;
import org.apache.commons.compress.archivers.tar.TarArchiveEntry;
@@ -70,7 +74,9 @@
*
* <p><b>Incomplete work</b> ({@code export_{jobId}/} and {@code .tar.gz.tmp})
is removed by
* {@link #cleanupFailedJob(ExportJob)} on failure or cancel, and by {@link
#start()} for every
- * leftover directory and temp file after SCM restart. Completed {@code
.tar.gz} files are kept.
+ * leftover directory and temp file after SCM restart. Completed {@code
.tar.gz} files are kept
+ * until the export manager evicts them with {@link #deleteArchive(String)};
{@link #listCompletedArchiveNames()}
+ * returns the existing ones, oldest first.
*
* <p><b>SCM restart:</b> {@link #start()} acquires the export directory lock
and clears incomplete work.
*/
@@ -79,10 +85,12 @@ final class ExportFileManager {
private static final Logger LOG =
LoggerFactory.getLogger(ExportFileManager.class);
static final String EXPORT_JOB_DIR_PREFIX = "export_";
+ static final String EXPORT_ARCHIVE_PREFIX = "container-ids_";
static final String EXPORT_ARCHIVE_JOB_INFIX = "_job";
static final String EXPORT_ARCHIVE_SUFFIX = ".tar.gz";
static final String EXPORT_ARCHIVE_TMP_SUFFIX = EXPORT_ARCHIVE_SUFFIX +
AtomicFileOutputStream.TMP_EXTENSION;
static final String EXPORT_LOCK_NAME = "in_use.lock";
+ private static final int EXPORT_JOB_START_TIME_LENGTH = 19;
private static final DateTimeFormatter EXPORT_JOB_START_TIME_FORMAT =
DateTimeFormatter.ofPattern("yyyy-MM-dd-HH-mm-ss").withZone(ZoneOffset.UTC);
@@ -138,8 +146,8 @@ synchronized void unlock() throws IOException {
}
static String archiveFileName(ExportScope scope, String jobStartTime,
ExportJob.Id jobId) {
- return String.format("container-ids_%s_%s%s%s%s",
- scope, jobStartTime, EXPORT_ARCHIVE_JOB_INFIX, jobId,
EXPORT_ARCHIVE_SUFFIX);
+ return String.format("%s%s_%s%s%s%s",
+ EXPORT_ARCHIVE_PREFIX, scope, jobStartTime, EXPORT_ARCHIVE_JOB_INFIX,
jobId, EXPORT_ARCHIVE_SUFFIX);
}
void createJobDirectory(ExportJob.Id jobId) throws IOException {
@@ -179,10 +187,63 @@ void deleteJobDirectory(ExportJob.Id jobId) {
}
}
+ /**
+ * Returns the file names of completed archives, oldest first. Only names
produced by
+ * {@link #archiveFileName} are returned, so other files in the directory
are never evicted.
+ */
+ List<String> listCompletedArchiveNames() {
+ final File[] archives = new File(exportDirectory).listFiles(
+ (dir, name) -> jobStartTimeFromArchiveFileName(name) != null &&
jobIdFromArchiveFileName(name) != null);
+ if (archives == null) {
+ return Collections.emptyList();
+ }
+ return Arrays.stream(archives)
+ .map(File::getName)
+
.sorted(Comparator.comparing(ExportFileManager::jobStartTimeFromArchiveFileName)
+ .thenComparing(Comparator.naturalOrder()))
+ .collect(Collectors.toList());
+ }
+
+ void deleteArchive(String archiveFileName) {
+ final File archive = new File(exportDirectory, archiveFileName);
+ if (archive.isFile() && !FileUtils.deleteQuietly(archive)) {
+ LOG.warn("Failed to delete container export archive {}; it will be
reconsidered on next SCM start", archive);
+ }
+ }
+
static String formatJobStartTime(Instant jobStartTime) {
return EXPORT_JOB_START_TIME_FORMAT.format(jobStartTime);
}
+ /** Returns the job start time in an archive file name, or null if the name
is not an export archive. */
+ static String jobStartTimeFromArchiveFileName(String fileName) {
+ final int jobIndex = fileName.lastIndexOf(EXPORT_ARCHIVE_JOB_INFIX);
+ if (!fileName.startsWith(EXPORT_ARCHIVE_PREFIX) ||
!fileName.endsWith(EXPORT_ARCHIVE_SUFFIX)
+ || jobIndex < EXPORT_ARCHIVE_PREFIX.length() +
EXPORT_JOB_START_TIME_LENGTH + 1) {
+ return null;
+ }
+ final String jobStartTime = fileName.substring(jobIndex -
EXPORT_JOB_START_TIME_LENGTH, jobIndex);
+ try {
+ EXPORT_JOB_START_TIME_FORMAT.parse(jobStartTime);
+ return jobStartTime;
+ } catch (DateTimeParseException e) {
+ return null;
+ }
+ }
+
+ static ExportJob.Id jobIdFromArchiveFileName(String fileName) {
+ if (!fileName.endsWith(EXPORT_ARCHIVE_SUFFIX)) {
+ return null;
+ }
+ final String nameWithoutSuffix = fileName.substring(0, fileName.length() -
EXPORT_ARCHIVE_SUFFIX.length());
+ final int jobIndex =
nameWithoutSuffix.lastIndexOf(EXPORT_ARCHIVE_JOB_INFIX);
+ if (jobIndex < 0) {
+ return null;
+ }
+ final String jobId = nameWithoutSuffix.substring(jobIndex +
EXPORT_ARCHIVE_JOB_INFIX.length());
+ return UUIDUtil.isValidUuidString(jobId) ? ExportJob.Id.of(jobId) : null;
+ }
+
void cleanupFailedJob(ExportJob job) {
FileUtils.deleteQuietly(jobDirectory(job.getId()).toFile());
File archive = new File(exportDirectory, job.getFileName());
diff --git
a/hadoop-hdds/server-scm/src/test/java/org/apache/hadoop/hdds/scm/container/export/TestContainerExportManager.java
b/hadoop-hdds/server-scm/src/test/java/org/apache/hadoop/hdds/scm/container/export/TestContainerExportManager.java
index 62533ea3fe6..efc2d71cae5 100644
---
a/hadoop-hdds/server-scm/src/test/java/org/apache/hadoop/hdds/scm/container/export/TestContainerExportManager.java
+++
b/hadoop-hdds/server-scm/src/test/java/org/apache/hadoop/hdds/scm/container/export/TestContainerExportManager.java
@@ -71,6 +71,7 @@ public class TestContainerExportManager {
private static final int TEST_BATCH_SIZE = 2;
private static final int TEST_PART_SIZE = 3;
+ private static final int TEST_MAX_RETAINED = 2;
private static final String TEST_SCM_ID = "test-scm";
@TempDir
@@ -82,7 +83,7 @@ public class TestContainerExportManager {
@BeforeEach
public void setup() throws Exception {
containerManager = mock(ContainerManager.class);
- exportManager = newExportManager(TEST_PART_SIZE, TEST_BATCH_SIZE, () ->
true);
+ exportManager = newExportManager(TEST_PART_SIZE, TEST_BATCH_SIZE,
TEST_MAX_RETAINED, () -> true);
}
@AfterEach
@@ -101,7 +102,7 @@ public void testRejectMissingFilters() {
@Test
public void testRejectSubmitWhenNotLeader() throws Exception {
exportManager.shutdown();
- exportManager = newExportManager(TEST_PART_SIZE, TEST_BATCH_SIZE, () ->
false);
+ exportManager = newExportManager(TEST_PART_SIZE, TEST_BATCH_SIZE,
TEST_MAX_RETAINED, () -> false);
SCMException e = assertThrows(SCMException.class, () ->
submit(ContainerID.valueOf(0), null, ContainerHealthState.MISSING));
assertEquals(SCMException.ResultCodes.SCM_NOT_LEADER, e.getResult());
@@ -116,11 +117,16 @@ public void testRejectSubmitAfterShutdown() {
}
@Test
- public void testRejectNonPositiveSizes() {
+ public void testRejectNonPositiveValues() {
+ // part size
assertThrows(IllegalArgumentException.class, () ->
- new ContainerExportManager(TEST_SCM_ID, containerManager, () -> true,
tempDir.getAbsolutePath(), 0, 1));
+ new ContainerExportManager(TEST_SCM_ID, containerManager, () -> true,
tempDir.getAbsolutePath(), 0, 1, 1));
+ // batch size
assertThrows(IllegalArgumentException.class, () ->
- new ContainerExportManager(TEST_SCM_ID, containerManager, () -> true,
tempDir.getAbsolutePath(), 1, 0));
+ new ContainerExportManager(TEST_SCM_ID, containerManager, () -> true,
tempDir.getAbsolutePath(), 1, 0, 1));
+ // max retained
+ assertThrows(IllegalArgumentException.class, () ->
+ new ContainerExportManager(TEST_SCM_ID, containerManager, () -> true,
tempDir.getAbsolutePath(), 1, 1, 0));
}
@Test
@@ -153,7 +159,7 @@ public void
testRejectSubmitWhileArchivingThenAcceptAfterDone() throws Exception
final CountDownLatch archivingStarted = new CountDownLatch(1);
final CountDownLatch releaseArchiving = new CountDownLatch(1);
exportManager.shutdown();
- exportManager = newExportManager(TEST_PART_SIZE, TEST_BATCH_SIZE, () -> {
+ exportManager = newExportManager(TEST_PART_SIZE, TEST_BATCH_SIZE,
TEST_MAX_RETAINED, () -> {
// submitJob also calls this on the caller thread; only hold the worker.
if (allIdsWritten.get() &&
Thread.currentThread().getName().endsWith("-ContainerExportWorker")) {
archivingStarted.countDown();
@@ -260,7 +266,7 @@ public void testZeroMatchesSucceedsWithoutArchive() throws
Exception {
@Test
public void testSinglePartExportCreatesTar() throws Exception {
exportManager.shutdown();
- exportManager = newExportManager(100, TEST_BATCH_SIZE, () -> true);
+ exportManager = newExportManager(100, TEST_BATCH_SIZE, TEST_MAX_RETAINED,
() -> true);
when(containerManager.getContainerIDs(
eq(ContainerID.valueOf(0)), anyInt(), isNull(),
eq(ContainerHealthState.MISSING)))
@@ -398,6 +404,77 @@ public void testLockReleasedOnlyAfterWorkerStops() throws
Exception {
assertTrue(waitForDone(job.getId()).isDone());
}
+ @Test
+ public void testOldestFinishedJobAndArchiveEvictedOverCap() throws Exception
{
+ final ExportJob first = exportOneContainer(ContainerHealthState.MISSING,
1);
+ final ExportJob second = exportOneContainer(ContainerHealthState.EMPTY,
10);
+ assertTrue(archiveFile(first).exists());
+ assertTrue(archiveFile(second).exists());
+
+ final ExportJob third =
exportOneContainer(ContainerHealthState.UNDER_REPLICATED, 20);
+
+ assertNull(exportManager.getExportStatus(first.getId()));
+ assertFalse(archiveFile(first).exists());
+ assertNotNull(exportManager.getExportStatus(second.getId()));
+ assertTrue(archiveFile(second).exists());
+ assertNotNull(exportManager.getExportStatus(third.getId()));
+ assertTrue(archiveFile(third).exists());
+ }
+
+ @Test
+ public void testFailedJobsDoNotEvictArchives() throws Exception {
+ final ExportJob archived =
exportOneContainer(ContainerHealthState.MISSING, 1);
+
+ // More failed jobs than the cap: their records are evicted, but they own
no archive to push out the first one.
+ when(containerManager.getContainerIDs(
+ eq(ContainerID.valueOf(0)), anyInt(), isNull(),
eq(ContainerHealthState.EMPTY)))
+ .thenThrow(new RuntimeException("listing failed"));
+ final List<ExportJob> failed = new ArrayList<>();
+ for (int i = 0; i < TEST_MAX_RETAINED + 1; i++) {
+ final ExportJob job = submit(ContainerID.valueOf(0), null,
ContainerHealthState.EMPTY);
+ assertNotNull(waitForDone(job.getId()).getException());
+ failed.add(job);
+ }
+
+ assertNull(exportManager.getExportStatus(archived.getId()));
+ assertTrue(archiveFile(archived).exists());
+ assertNull(exportManager.getExportStatus(failed.get(0).getId()));
+ assertNotNull(exportManager.getExportStatus(failed.get(failed.size() -
1).getId()));
+ }
+
+ @Test
+ public void testCompletedArchivesTrimmedAndOthersKeptOnRestart() throws
Exception {
+ final ExportJob first = exportOneContainer(ContainerHealthState.MISSING,
1);
+ final ExportJob second = exportOneContainer(ContainerHealthState.EMPTY,
10);
+ exportManager.shutdown();
+
+ // Two more archives left by earlier runs, plus a file that is not an
export archive.
+ final File oldest = new File(tempDir, ExportFileManager.archiveFileName(
+ ExportScope.of(null, ContainerHealthState.MISSING),
"2020-01-01-00-00-00", ExportJob.Id.newId()));
+ final File newest = new File(tempDir, ExportFileManager.archiveFileName(
+ ExportScope.of(null, ContainerHealthState.MISSING),
"2099-01-01-00-00-00", ExportJob.Id.newId()));
+ final List<File> unrelated = Arrays.asList(
+ new File(tempDir, "notes.tar.gz"),
+ // Same shape as an archive name, but no export prefix.
+ new File(tempDir, "backup_of_something_important_job" +
ExportJob.Id.newId() + ".tar.gz"),
+ // Export prefix, but the part before "_job" is not a timestamp.
+ new File(tempDir,
"container-ids_health-MISSING_lifecycle-ANY_not-a-timestamp-ab_job"
+ + ExportJob.Id.newId() + ".tar.gz"));
+ assertTrue(oldest.createNewFile());
+ assertTrue(newest.createNewFile());
+ for (File file : unrelated) {
+ assertTrue(file.createNewFile());
+ }
+
+ exportManager = newExportManager(TEST_PART_SIZE, TEST_BATCH_SIZE,
TEST_MAX_RETAINED, () -> true);
+
+ // Four archives, cap two: the two oldest by job start time are removed,
other files are untouched.
+ assertFalse(oldest.exists());
+ assertTrue(newest.exists());
+ assertTrue(unrelated.stream().allMatch(File::exists));
+ assertEquals(1, Stream.of(first, second).filter(job ->
archiveFile(job).exists()).count());
+ }
+
@Test
public void testSubmitAfterPreviousJobCompletes() throws Exception {
when(containerManager.getContainerIDs(
@@ -427,7 +504,7 @@ public void testSubmitAfterPreviousJobCompletes() throws
Exception {
public void testFailsWhenLeadershipLostDuringExport() throws Exception {
AtomicBoolean leader = new AtomicBoolean(true);
exportManager.shutdown();
- exportManager = newExportManager(TEST_PART_SIZE, TEST_BATCH_SIZE,
leader::get);
+ exportManager = newExportManager(TEST_PART_SIZE, TEST_BATCH_SIZE,
TEST_MAX_RETAINED, leader::get);
when(containerManager.getContainerIDs(
eq(ContainerID.valueOf(0)), anyInt(), isNull(),
eq(ContainerHealthState.MISSING)))
@@ -486,14 +563,26 @@ private File archiveFile(ExportJob job) {
return new File(tempDir, job.getFileName());
}
- private ContainerExportManager newExportManager(int partSize, int batchSize,
+ private ContainerExportManager newExportManager(int partSize, int batchSize,
int maxRetained,
BooleanSupplier isLeaderReady) throws Exception {
ContainerExportManager manager = new ContainerExportManager(TEST_SCM_ID,
containerManager, isLeaderReady,
- tempDir.getAbsolutePath(), partSize, batchSize);
+ tempDir.getAbsolutePath(), partSize, batchSize, maxRetained);
manager.start();
return manager;
}
+ /** Runs an export that matches exactly one container, so it produces an
archive. */
+ private ExportJob exportOneContainer(ContainerHealthState health, long
containerId) throws Exception {
+ when(containerManager.getContainerIDs(
+ eq(ContainerID.valueOf(0)), anyInt(), isNull(),
eq(health))).thenReturn(ids(containerId));
+ when(containerManager.getContainerIDs(
+ eq(ContainerID.valueOf(containerId + 1)), anyInt(), isNull(),
eq(health)))
+ .thenReturn(Collections.emptyList());
+ ExportJob job = submit(ContainerID.valueOf(0), null, health);
+ assertNull(waitForDone(job.getId()).getException());
+ return job;
+ }
+
private static List<ContainerID> ids(long... values) {
return Arrays.stream(values).mapToObj(ContainerID::valueOf)
.collect(Collectors.toList());
---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]