This is an automated email from the ASF dual-hosted git repository.
exceptionfactory pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/nifi.git
The following commit(s) were added to refs/heads/main by this push:
new f7e73872481 NIFI-16599 Preserve FlowFile order across restart for
queues that are swapping (#11936)
f7e73872481 is described below
commit f7e73872481f474c217d27fc2a86447d6d156ce7
Author: Mark Payne <[email protected]>
AuthorDate: Wed Nov 18 15:31:05 2026 -0500
NIFI-16599 Preserve FlowFile order across restart for queues that are
swapping (#11936)
- Restore FlowFiles in priority order on recovery when there are no swap
files, sharing the logic used when swap files exist
- Keep the place of a swap file rewritten by a selective drop by reusing
the timestamp and counter of the replaced swap file
- Add a counter to swap file names so that swap files written in the same
millisecond are recovered in the order written
Co-authored-by: Cursor <[email protected]>
Signed-off-by: David Handermann <[email protected]>
---
.../controller/repository/FlowFileSwapManager.java | 17 ++++
.../nifi/controller/FileSystemSwapManager.java | 91 +++++++++++++++++-----
.../controller/queue/SwappablePriorityQueue.java | 80 ++++++++++++-------
.../nifi/controller/TestFileSystemSwapManager.java | 18 +++++
.../clustered/TestSwappablePriorityQueue.java | 71 ++++++++++++++---
5 files changed, 215 insertions(+), 62 deletions(-)
diff --git
a/nifi-framework-api/src/main/java/org/apache/nifi/controller/repository/FlowFileSwapManager.java
b/nifi-framework-api/src/main/java/org/apache/nifi/controller/repository/FlowFileSwapManager.java
index b29bb8b3802..7ae2f9a793c 100644
---
a/nifi-framework-api/src/main/java/org/apache/nifi/controller/repository/FlowFileSwapManager.java
+++
b/nifi-framework-api/src/main/java/org/apache/nifi/controller/repository/FlowFileSwapManager.java
@@ -52,6 +52,23 @@ public interface FlowFileSwapManager {
*/
String swapOut(List<FlowFileRecord> flowFiles, FlowFileQueue
flowFileQueue, final String partitionName) throws IOException;
+ /**
+ * Swaps out the given FlowFiles to a new swap file that takes the place
of an existing swap file, such as when some FlowFiles are removed
+ * from the existing swap file. When swap files are recovered, the new
swap file is placed where the existing swap file would have been placed,
+ * rather than after all other swap files. The existing swap file is
neither modified nor deleted.
+ *
+ * @param flowFiles the FlowFiles to swap out to external storage
+ * @param flowFileQueue the queue that the FlowFiles belong to
+ * @param partitionName the name of the partition within the queue, or
<code>null</code> if the queue is not partitioned
+ * @param replacedSwapLocation the location of the existing swap file
whose place the new swap file takes
+ * @return the location of the externally stored swap file
+ *
+ * @throws IOException if unable to swap the FlowFiles out
+ */
+ default String swapOut(final List<FlowFileRecord> flowFiles, final
FlowFileQueue flowFileQueue, final String partitionName, final String
replacedSwapLocation) throws IOException {
+ return swapOut(flowFiles, flowFileQueue, partitionName);
+ }
+
/**
* Recovers the FlowFiles from the swap file that lives at the given
location. This action
* provides a view of the FlowFiles but does not actively swap them in,
meaning that the swap file
diff --git
a/nifi-framework-bundle/nifi-framework/nifi-framework-core/src/main/java/org/apache/nifi/controller/FileSystemSwapManager.java
b/nifi-framework-bundle/nifi-framework/nifi-framework-core/src/main/java/org/apache/nifi/controller/FileSystemSwapManager.java
index 14cd4f505d0..844a10ef6c5 100644
---
a/nifi-framework-bundle/nifi-framework/nifi-framework-core/src/main/java/org/apache/nifi/controller/FileSystemSwapManager.java
+++
b/nifi-framework-bundle/nifi-framework/nifi-framework-core/src/main/java/org/apache/nifi/controller/FileSystemSwapManager.java
@@ -64,6 +64,7 @@ import java.util.List;
import java.util.Objects;
import java.util.Set;
import java.util.UUID;
+import java.util.concurrent.atomic.AtomicLong;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
@@ -86,6 +87,7 @@ public class FileSystemSwapManager implements
FlowFileSwapManager {
private final File storageDirectory;
private final FieldCache fieldCache = new CaffeineFieldCache(10_000_000);
+ private final AtomicLong swapFileCounter = new AtomicLong();
// effectively final
private FlowFileRepository flowFileRepository;
@@ -133,7 +135,26 @@ public class FileSystemSwapManager implements
FlowFileSwapManager {
return null;
}
- final String swapFileName =
getSwapFileName(flowFileQueue.getIdentifier(), partitionName);
+ return writeSwapFile(toSwap, flowFileQueue, partitionName,
System.currentTimeMillis(), swapFileCounter.incrementAndGet());
+ }
+
+ @Override
+ public String swapOut(final List<FlowFileRecord> toSwap, final
FlowFileQueue flowFileQueue, final String partitionName, final String
replacedSwapLocation) throws IOException {
+ if (toSwap == null || toSwap.isEmpty()) {
+ return null;
+ }
+
+ // Swap files are recovered in the order of the timestamp and counter
in their names, so the new swap file takes those of the swap file that it
replaces
+ final Long replacedTimestamp =
getTimestampFromFilename(replacedSwapLocation);
+ if (replacedTimestamp == null) {
+ return swapOut(toSwap, flowFileQueue, partitionName);
+ }
+
+ return writeSwapFile(toSwap, flowFileQueue, partitionName,
replacedTimestamp, getCounterFromFilename(replacedSwapLocation));
+ }
+
+ private String writeSwapFile(final List<FlowFileRecord> toSwap, final
FlowFileQueue flowFileQueue, final String partitionName, final long timestamp,
final long counter) throws IOException {
+ final String swapFileName =
getSwapFileName(flowFileQueue.getIdentifier(), partitionName, timestamp,
counter);
final Path storageDirectoryPath = storageDirectory.toPath();
final Path swapFilePath =
storageDirectoryPath.resolve(swapFileName).toAbsolutePath();
@@ -293,8 +314,8 @@ public class FileSystemSwapManager implements
FlowFileSwapManager {
continue;
}
- // split the filename by dashes. The old filenaming scheme was
"<timestamp>-<randomuuid>.swap" but the new naming scheme is
- // "<timestamp>-<queue identifier>-<random uuid>.[partition
name.]swap".
+ // split the filename by dashes. The old filenaming scheme was
"<timestamp>-<randomuuid>.swap" but newer naming schemes are
+ // "<timestamp>-<queue identifier>-<random uuid>.[partition
name.]swap" and "<timestamp>-<queue identifier>-<counter>-<random
uuid>.[partition name.]swap".
final String ownerQueueId = getOwnerQueueIdentifier(swapFile);
if (ownerQueueId != null) {
if (!ownerQueueId.equals(flowFileQueue.getIdentifier())) {
@@ -425,28 +446,56 @@ public class FileSystemSwapManager implements
FlowFileSwapManager {
return timeComparisonValue;
}
+ final int counterComparisonValue =
Long.compare(getCounterFromFilename(o1), getCounterFromFilename(o2));
+ if (counterComparisonValue != 0) {
+ return counterComparisonValue;
+ }
+
return o1.compareTo(o2);
}
+ }
- private Long getTimestampFromFilename(final String
fullyQualifiedFilename) {
- if (fullyQualifiedFilename == null) {
- return null;
- }
+ private static Long getTimestampFromFilename(final String
fullyQualifiedFilename) {
+ if (fullyQualifiedFilename == null) {
+ return null;
+ }
- final File file = new File(fullyQualifiedFilename);
- final String filename = file.getName();
+ final File file = new File(fullyQualifiedFilename);
+ final String filename = file.getName();
- final int idx = filename.indexOf("-");
- if (idx < 1) {
- return null;
- }
+ final int idx = filename.indexOf("-");
+ if (idx < 1) {
+ return null;
+ }
- final String millisVal = filename.substring(0, idx);
- try {
- return Long.parseLong(millisVal);
- } catch (final NumberFormatException e) {
- return null;
- }
+ final String millisVal = filename.substring(0, idx);
+ try {
+ return Long.parseLong(millisVal);
+ } catch (final NumberFormatException e) {
+ return null;
+ }
+ }
+
+ /**
+ * Returns the counter from a swap file name of the form
"<timestamp>-<queue identifier>-<counter>-<random
uuid>". The counter orders
+ * swap files that were written within the same millisecond.
+ *
+ * @param fullyQualifiedFilename the swap location
+ * @return the counter from the swap file name, or 0 if the name does not
contain a counter
+ */
+ private static long getCounterFromFilename(final String
fullyQualifiedFilename) {
+ final String filename = new File(fullyQualifiedFilename).getName();
+ final int dotIndex = filename.indexOf(".");
+ final String baseName = dotIndex < 0 ? filename :
filename.substring(0, dotIndex);
+ final String[] splits = baseName.split("-");
+ if (splits.length != 12) {
+ return 0L;
+ }
+
+ try {
+ return Long.parseLong(splits[6]);
+ } catch (final NumberFormatException e) {
+ return 0L;
}
}
@@ -475,7 +524,7 @@ public class FileSystemSwapManager implements
FlowFileSwapManager {
return newFile.getAbsolutePath();
}
- private String getSwapFileName(final String flowFileQueueIdentifier, final
String partitionName) {
+ private String getSwapFileName(final String flowFileQueueIdentifier, final
String partitionName, final long timestamp, final long counter) {
final UUID identifier;
final Matcher identifierMatcher =
UUID_PATTERN.matcher(flowFileQueueIdentifier);
if (identifierMatcher.find()) {
@@ -484,7 +533,7 @@ public class FileSystemSwapManager implements
FlowFileSwapManager {
throw new IllegalArgumentException("FlowFile Queue Identifier [%s]
not valid".formatted(flowFileQueueIdentifier));
}
- final String swapFilePrefix = System.currentTimeMillis() + "-" +
identifier + "-" + UUID.randomUUID();
+ final String swapFilePrefix = timestamp + "-" + identifier + "-" +
counter + "-" + UUID.randomUUID();
final String swapFileBaseName = partitionName == null ? swapFilePrefix
: swapFilePrefix + "." + partitionName;
return swapFileBaseName + ".swap";
}
diff --git
a/nifi-framework-bundle/nifi-framework/nifi-framework-core/src/main/java/org/apache/nifi/controller/queue/SwappablePriorityQueue.java
b/nifi-framework-bundle/nifi-framework/nifi-framework-core/src/main/java/org/apache/nifi/controller/queue/SwappablePriorityQueue.java
index 4c22407a5c1..302f024599f 100644
---
a/nifi-framework-bundle/nifi-framework/nifi-framework-core/src/main/java/org/apache/nifi/controller/queue/SwappablePriorityQueue.java
+++
b/nifi-framework-bundle/nifi-framework/nifi-framework-core/src/main/java/org/apache/nifi/controller/queue/SwappablePriorityQueue.java
@@ -1180,8 +1180,8 @@ public class SwappablePriorityQueue {
return new SwapFileDropResult(swapLocation, null,
droppedFromThisSwapFile, droppedFromSwapFileBytes, 0L, 0L);
}
- // Some FlowFiles remain - write to new swap file
- final String newSwapLocation = swapManager.swapOut(remainingFlowFiles,
flowFileQueue, swapPartitionName);
+ // Some FlowFiles remain - write to a new swap file that keeps the
place of the existing swap file when swap files are recovered
+ final String newSwapLocation = swapManager.swapOut(remainingFlowFiles,
flowFileQueue, swapPartitionName, swapLocation);
return new SwapFileDropResult(swapLocation, newSwapLocation,
droppedFromThisSwapFile,
droppedFromSwapFileBytes, remainingMinQueueDate,
remainingTotalQueueDate);
}
@@ -1270,10 +1270,10 @@ public class SwappablePriorityQueue {
if (!swapLocations.isEmpty()) {
// FlowFiles added from now on must wait behind the swap
files, even if the oldest swap file cannot be read
swapMode = true;
- final String oldestSwapLocation =
swapLocations.iterator().next();
- restoreActiveFlowFilesToSwapQueue(oldestSwapLocation);
}
+ restoreFlowFilesInPriorityOrder(swapLocations);
+
updateTopPenaltyExpiration();
} finally {
writeLock.unlock("Recover Swap Files");
@@ -1292,34 +1292,56 @@ public class SwappablePriorityQueue {
}
/**
- * On restart, the FlowFiles that were held in memory are restored from
the FlowFile Repository before the swap files are recovered, so they
- * fill the active queue regardless of whether they were queued before or
after the swapped FlowFiles. Because swap files are not swapped in
- * until the active queue is empty, this keeps in the active queue only
the FlowFiles that come before the highest priority FlowFile of the
- * oldest swap file and moves all others to the swap queue, which is
processed after the swap files.
+ * On restart, the FlowFiles that were held in memory are restored from
the FlowFile Repository in no particular order and before the swap
+ * files are recovered. Whichever FlowFiles are restored first fill the
active queue, regardless of their priority or of whether they were
+ * queued before or after the swapped FlowFiles, and the rest go to the
swap queue. This puts the restored FlowFiles back in priority order.
+ *
+ * Because swap files are not swapped in until the active queue is empty,
when there are swap files the active queue keeps only the restored
+ * FlowFiles that come before the highest priority FlowFile of the oldest
swap file, and all others go to the swap queue, which is processed
+ * after the swap files. When there are no swap files, the active queue
keeps the same number of FlowFiles, chosen from the highest priority
+ * restored FlowFiles.
*
* This method MUST be called with the write lock held.
*
- * @param oldestSwapLocation the location of the oldest recovered swap file
+ * @param recoveredSwapLocations the locations of the recovered swap
files, oldest first
*/
- private void restoreActiveFlowFilesToSwapQueue(final String
oldestSwapLocation) {
- final List<FlowFileRecord> swappedFlowFiles;
- try {
- swappedFlowFiles = swapManager.peek(oldestSwapLocation,
flowFileQueue).getFlowFiles();
- } catch (final Exception e) {
- logger.warn("Failed to read Swap File {} for {}; FlowFiles
restored from the FlowFile Repository may be processed before older swapped
FlowFiles",
- oldestSwapLocation, this, e);
- return;
- }
-
- if (swappedFlowFiles.isEmpty()) {
+ private void restoreFlowFilesInPriorityOrder(final Collection<String>
recoveredSwapLocations) {
+ if (recoveredSwapLocations.isEmpty() && swapQueue.isEmpty()) {
return;
}
final QueuePrioritizer prioritizer = new
QueuePrioritizer(getPriorities());
- final FlowFileRecord firstSwappedFlowFile =
Collections.min(swappedFlowFiles, prioritizer);
-
final List<FlowFileRecord> restoredFlowFiles = new
ArrayList<>(activeQueue);
restoredFlowFiles.addAll(swapQueue);
+ restoredFlowFiles.sort(prioritizer);
+
+ final int activeCount;
+ if (recoveredSwapLocations.isEmpty()) {
+ activeCount = activeQueue.size();
+ } else {
+ final String oldestSwapLocation =
recoveredSwapLocations.iterator().next();
+ final List<FlowFileRecord> swappedFlowFiles;
+ try {
+ swappedFlowFiles = swapManager.peek(oldestSwapLocation,
flowFileQueue).getFlowFiles();
+ } catch (final Exception e) {
+ logger.warn("Failed to read Swap File {} for {}; FlowFiles
restored from the FlowFile Repository may be processed before older swapped
FlowFiles",
+ oldestSwapLocation, this, e);
+ return;
+ }
+
+ if (swappedFlowFiles.isEmpty()) {
+ return;
+ }
+
+ final FlowFileRecord firstSwappedFlowFile =
Collections.min(swappedFlowFiles, prioritizer);
+ int countBeforeSwappedFlowFiles = 0;
+ while (countBeforeSwappedFlowFiles < restoredFlowFiles.size() &&
prioritizer.compare(restoredFlowFiles.get(countBeforeSwappedFlowFiles),
firstSwappedFlowFile) < 0) {
+ countBeforeSwappedFlowFiles++;
+ }
+
+ activeCount = countBeforeSwappedFlowFiles;
+ }
+
final int originalActiveCount = activeQueue.size();
long originalActiveBytes = 0L;
for (final FlowFileRecord flowFile : activeQueue) {
@@ -1328,17 +1350,15 @@ public class SwappablePriorityQueue {
activeQueue.clear();
swapQueue.clear();
+ activeQueue.addAll(restoredFlowFiles.subList(0, activeCount));
+ swapQueue.addAll(restoredFlowFiles.subList(activeCount,
restoredFlowFiles.size()));
+
long activeBytes = 0L;
- for (final FlowFileRecord flowFile : restoredFlowFiles) {
- if (prioritizer.compare(flowFile, firstSwappedFlowFile) < 0) {
- activeQueue.add(flowFile);
- activeBytes += flowFile.getSize();
- } else {
- swapQueue.add(flowFile);
- }
+ for (final FlowFileRecord flowFile : activeQueue) {
+ activeBytes += flowFile.getSize();
}
- final int movedToActiveCount = activeQueue.size() -
originalActiveCount;
+ final int movedToActiveCount = activeCount - originalActiveCount;
final long movedToActiveBytes = activeBytes - originalActiveBytes;
incrementActiveQueueSize(movedToActiveCount, movedToActiveBytes);
incrementSwapQueueSize(-movedToActiveCount, -movedToActiveBytes, 0);
diff --git
a/nifi-framework-bundle/nifi-framework/nifi-framework-core/src/test/java/org/apache/nifi/controller/TestFileSystemSwapManager.java
b/nifi-framework-bundle/nifi-framework/nifi-framework-core/src/test/java/org/apache/nifi/controller/TestFileSystemSwapManager.java
index 4297048ecf5..1d73be4d46a 100644
---
a/nifi-framework-bundle/nifi-framework/nifi-framework-core/src/test/java/org/apache/nifi/controller/TestFileSystemSwapManager.java
+++
b/nifi-framework-bundle/nifi-framework/nifi-framework-core/src/test/java/org/apache/nifi/controller/TestFileSystemSwapManager.java
@@ -107,6 +107,24 @@ public class TestFileSystemSwapManager {
() -> swapManager.swapOut(flowFileRecords, flowFileQueue,
"partition-1"));
}
+ @Test
+ public void testRecoverSwapLocationsInOrderWritten() throws IOException {
+ final FlowFileQueue flowFileQueue = mock(FlowFileQueue.class);
+
when(flowFileQueue.getIdentifier()).thenReturn("87bb99fe-412c-49f6-a441-d1b0af4e20b4");
+ final FlowFileRepository flowFileRepo = mock(FlowFileRepository.class);
+
when(flowFileRepo.isValidSwapLocationSuffix(anyString())).thenReturn(true);
+ final FileSystemSwapManager swapManager =
createSwapManager(flowFileRepo);
+
+ // Writing many small swap files in a row results in several swap
files being written within the same millisecond
+ final List<String> swapLocations = new ArrayList<>();
+ for (int i = 0; i < 100; i++) {
+ swapLocations.add(swapManager.swapOut(List.of(new
MockFlowFileRecord(i)), flowFileQueue, "partition-1"));
+ }
+
+ final FileSystemSwapManager restartedSwapManager =
createSwapManager(flowFileRepo);
+ assertEquals(swapLocations,
restartedSwapManager.recoverSwapLocations(flowFileQueue, "partition-1"));
+ }
+
@Test
public void testSwapFileUnknownToRepoNotSwappedIn() throws IOException {
final FlowFileQueue flowFileQueue = mock(FlowFileQueue.class);
diff --git
a/nifi-framework-bundle/nifi-framework/nifi-framework-core/src/test/java/org/apache/nifi/controller/queue/clustered/TestSwappablePriorityQueue.java
b/nifi-framework-bundle/nifi-framework/nifi-framework-core/src/test/java/org/apache/nifi/controller/queue/clustered/TestSwappablePriorityQueue.java
index 72237fa19b1..8303bd94dfb 100644
---
a/nifi-framework-bundle/nifi-framework/nifi-framework-core/src/test/java/org/apache/nifi/controller/queue/clustered/TestSwappablePriorityQueue.java
+++
b/nifi-framework-bundle/nifi-framework/nifi-framework-core/src/test/java/org/apache/nifi/controller/queue/clustered/TestSwappablePriorityQueue.java
@@ -17,8 +17,10 @@
package org.apache.nifi.controller.queue.clustered;
+import org.apache.nifi.controller.FileSystemSwapManager;
import org.apache.nifi.controller.MockFlowFileRecord;
import org.apache.nifi.controller.MockSwapManager;
+import org.apache.nifi.controller.TestFileSystemSwapManager;
import org.apache.nifi.controller.queue.DropFlowFileAction;
import org.apache.nifi.controller.queue.DropFlowFileRequest;
import org.apache.nifi.controller.queue.FlowFileQueue;
@@ -29,6 +31,9 @@ import org.apache.nifi.controller.queue.QueueSize;
import org.apache.nifi.controller.queue.SelectiveDropResult;
import org.apache.nifi.controller.queue.SwappablePriorityQueue;
import org.apache.nifi.controller.repository.FlowFileRecord;
+import org.apache.nifi.controller.repository.FlowFileRepository;
+import org.apache.nifi.controller.repository.SwapManagerInitializationContext;
+import org.apache.nifi.controller.repository.claim.ResourceClaimManager;
import org.apache.nifi.events.EventReporter;
import org.apache.nifi.flowfile.FlowFile;
import org.apache.nifi.flowfile.FlowFilePrioritizer;
@@ -37,10 +42,12 @@ import org.apache.nifi.util.StringUtils;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.Timeout;
+import org.junit.jupiter.api.io.TempDir;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
+import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
@@ -56,6 +63,7 @@ import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertSame;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
@@ -617,22 +625,27 @@ public class TestSwappablePriorityQueue {
return Integer.compare(i1, i2);
};
- // Before a restart, the active queue held the oldest FlowFiles, a
swap file held the next 100, and the in-memory swap queue held the newest 50.
+ // Before a restart, the active queue held the oldest FlowFiles, a
swap file (if any) held the next ones, and the in-memory swap queue held the
newest 50.
// On restart, the active and in-memory swap queue FlowFiles are
restored newest first, and then the swap file is recovered.
- for (final int activeCount : new int[] {40, 80}) {
+ // Without a swap file, more FlowFiles are restored than the active
queue can hold, so the newest restored FlowFiles fill the active queue first.
+ for (final int[] counts : new int[][] {{40, 100}, {80, 100}, {80, 0}})
{
+ final int activeCount = counts[0];
+ final int swappedCount = counts[1];
swapManager = new MockSwapManager();
queue = new SwappablePriorityQueue(swapManager, 100,
eventReporter, flowFileQueue, dropAction, "local");
queue.setPriorities(List.of(iAttributePrioritizer));
- final List<FlowFileRecord> swappedFlowFiles = new ArrayList<>();
- for (int i = activeCount; i < activeCount + 100; i++) {
- swappedFlowFiles.add(new MockFlowFileRecord(Map.of("i",
String.valueOf(i)), 1L));
+ if (swappedCount > 0) {
+ final List<FlowFileRecord> swappedFlowFiles = new
ArrayList<>();
+ for (int i = activeCount; i < activeCount + swappedCount; i++)
{
+ swappedFlowFiles.add(new MockFlowFileRecord(Map.of("i",
String.valueOf(i)), 1L));
+ }
+ swapManager.swapOut(swappedFlowFiles, flowFileQueue, "local");
}
- swapManager.swapOut(swappedFlowFiles, flowFileQueue, "local");
- final int totalCount = activeCount + 150;
+ final int totalCount = activeCount + swappedCount + 50;
for (int i = totalCount - 1; i >= 0; i--) {
- if (i < activeCount || i >= activeCount + 100) {
+ if (i < activeCount || i >= activeCount + swappedCount) {
queue.put(new MockFlowFileRecord(Map.of("i",
String.valueOf(i)), 1L));
}
}
@@ -788,19 +801,32 @@ public class TestSwappablePriorityQueue {
}
@Test
- public void testSelectiveDropPreservesSwapFileOrdering() throws
IOException {
- queue = new SwappablePriorityQueue(swapManager, 10, eventReporter,
flowFileQueue, dropAction, "local");
+ public void testSelectiveDropPreservesSwapFileOrdering(@TempDir final Path
flowFileRepositoryDirectory) throws IOException {
+
when(flowFileQueue.getIdentifier()).thenReturn("87bb99fe-412c-49f6-a441-d1b0af4e20b4");
+ final FlowFileRepository flowFileRepository =
mock(FlowFileRepository.class);
+
when(flowFileRepository.isValidSwapLocationSuffix(anyString())).thenReturn(true);
+ final FileSystemSwapManager fileSystemSwapManager =
createFileSystemSwapManager(flowFileRepositoryDirectory, flowFileRepository);
+ queue = new SwappablePriorityQueue(fileSystemSwapManager, 10,
eventReporter, flowFileQueue, dropAction, "local");
for (int i = 0; i < 30; i++) {
queue.put(new MockFlowFileRecord(Map.of("index",
Integer.toString(i)), 1L));
}
- assertEquals(2, swapManager.swappedOut.size());
+ assertEquals(2,
fileSystemSwapManager.recoverSwapLocations(flowFileQueue, "local").size());
final SelectiveDropResult result = queue.dropFlowFiles(flowFile ->
"10".equals(flowFile.getAttribute("index")));
assertEquals(1, result.getDroppedCount());
assertEquals(1, result.getSwapLocationUpdates().size());
+ for (final String replacedSwapLocation :
result.getSwapLocationUpdates().keySet()) {
+ fileSystemSwapManager.deleteSwapFile(replacedSwapLocation);
+ }
+
+ // On restart, the rewritten swap file must be recovered ahead of the
swap file that holds FlowFiles 20 through 29
+ final FileSystemSwapManager restartedSwapManager =
createFileSystemSwapManager(flowFileRepositoryDirectory, flowFileRepository);
+ final List<String> recoveredSwapLocations =
restartedSwapManager.recoverSwapLocations(flowFileQueue, "local");
+ assertEquals(2, recoveredSwapLocations.size());
+
assertEquals(result.getSwapLocationUpdates().values().iterator().next(),
recoveredSwapLocations.getFirst());
final Set<FlowFileRecord> expired = new HashSet<>();
for (int expectedIndex = 0; expectedIndex < 30; expectedIndex++) {
@@ -815,6 +841,29 @@ public class TestSwappablePriorityQueue {
assertNull(queue.poll(expired, 0L));
}
+ private FileSystemSwapManager createFileSystemSwapManager(final Path
flowFileRepositoryDirectory, final FlowFileRepository flowFileRepository) {
+ final FileSystemSwapManager fileSystemSwapManager = new
FileSystemSwapManager(flowFileRepositoryDirectory);
+ final ResourceClaimManager resourceClaimManager = new
TestFileSystemSwapManager.NopResourceClaimManager();
+ fileSystemSwapManager.initialize(new
SwapManagerInitializationContext() {
+ @Override
+ public ResourceClaimManager getResourceClaimManager() {
+ return resourceClaimManager;
+ }
+
+ @Override
+ public FlowFileRepository getFlowFileRepository() {
+ return flowFileRepository;
+ }
+
+ @Override
+ public EventReporter getEventReporter() {
+ return EventReporter.NO_OP;
+ }
+ });
+
+ return fileSystemSwapManager;
+ }
+
@Test
@Timeout(120)
public void testSelectiveDropRemovesEntireSwapFileWhenAllMatch() throws
IOException {