Skip to content

Commit 6a4b37c

Browse files
NIFI-16580 Preserve FIFO order of restored FlowFiles when recovering swap files (#11921)
After a restart, FlowFiles restored from the FlowFile Repository are added to the queue before its swap files are recovered, so newer FlowFiles could fill the active queue and be processed before older swapped FlowFiles. When swap files are recovered, keep in the active queue only the FlowFiles that come before the first FlowFile of the oldest swap file, move the rest to the swap queue, and place the queue in swap mode. Co-authored-by: Cursor <cursoragent@cursor.com> Signed-off-by: David Handermann <exceptionfactory@apache.org>
1 parent 8549733 commit 6a4b37c

5 files changed

Lines changed: 257 additions & 0 deletions

File tree

‎nifi-framework-bundle/nifi-framework/nifi-framework-core/src/main/java/org/apache/nifi/controller/queue/SwappablePriorityQueue.java‎

Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1267,6 +1267,13 @@ public SwapSummary recoverSwappedFlowFiles() {
12671267

12681268
incrementSwapQueueSize(swapFlowFileCount, swapByteCount, swapLocations.size());
12691269
this.swapLocations.addAll(swapLocations);
1270+
if (!swapLocations.isEmpty()) {
1271+
// FlowFiles added from now on must wait behind the swap files, even if the oldest swap file cannot be read
1272+
swapMode = true;
1273+
final String oldestSwapLocation = swapLocations.iterator().next();
1274+
restoreActiveFlowFilesToSwapQueue(oldestSwapLocation);
1275+
}
1276+
12701277
updateTopPenaltyExpiration();
12711278
} finally {
12721279
writeLock.unlock("Recover Swap Files");
@@ -1284,6 +1291,59 @@ public SwapSummary recoverSwappedFlowFiles() {
12841291
return new StandardSwapSummary(new QueueSize(swapFlowFileCount, swapByteCount), maxId, resourceClaims, minSwappedQueueDate, totalSwappedQueueDate);
12851292
}
12861293

1294+
/**
1295+
* On restart, the FlowFiles that were held in memory are restored from the FlowFile Repository before the swap files are recovered, so they
1296+
* fill the active queue regardless of whether they were queued before or after the swapped FlowFiles. Because swap files are not swapped in
1297+
* until the active queue is empty, this keeps in the active queue only the FlowFiles that come before the highest priority FlowFile of the
1298+
* oldest swap file and moves all others to the swap queue, which is processed after the swap files.
1299+
*
1300+
* This method MUST be called with the write lock held.
1301+
*
1302+
* @param oldestSwapLocation the location of the oldest recovered swap file
1303+
*/
1304+
private void restoreActiveFlowFilesToSwapQueue(final String oldestSwapLocation) {
1305+
final List<FlowFileRecord> swappedFlowFiles;
1306+
try {
1307+
swappedFlowFiles = swapManager.peek(oldestSwapLocation, flowFileQueue).getFlowFiles();
1308+
} catch (final Exception e) {
1309+
logger.warn("Failed to read Swap File {} for {}; FlowFiles restored from the FlowFile Repository may be processed before older swapped FlowFiles",
1310+
oldestSwapLocation, this, e);
1311+
return;
1312+
}
1313+
1314+
if (swappedFlowFiles.isEmpty()) {
1315+
return;
1316+
}
1317+
1318+
final QueuePrioritizer prioritizer = new QueuePrioritizer(getPriorities());
1319+
final FlowFileRecord firstSwappedFlowFile = Collections.min(swappedFlowFiles, prioritizer);
1320+
1321+
final List<FlowFileRecord> restoredFlowFiles = new ArrayList<>(activeQueue);
1322+
restoredFlowFiles.addAll(swapQueue);
1323+
final int originalActiveCount = activeQueue.size();
1324+
long originalActiveBytes = 0L;
1325+
for (final FlowFileRecord flowFile : activeQueue) {
1326+
originalActiveBytes += flowFile.getSize();
1327+
}
1328+
1329+
activeQueue.clear();
1330+
swapQueue.clear();
1331+
long activeBytes = 0L;
1332+
for (final FlowFileRecord flowFile : restoredFlowFiles) {
1333+
if (prioritizer.compare(flowFile, firstSwappedFlowFile) < 0) {
1334+
activeQueue.add(flowFile);
1335+
activeBytes += flowFile.getSize();
1336+
} else {
1337+
swapQueue.add(flowFile);
1338+
}
1339+
}
1340+
1341+
final int movedToActiveCount = activeQueue.size() - originalActiveCount;
1342+
final long movedToActiveBytes = activeBytes - originalActiveBytes;
1343+
incrementActiveQueueSize(movedToActiveCount, movedToActiveBytes);
1344+
incrementSwapQueueSize(-movedToActiveCount, -movedToActiveBytes, 0);
1345+
}
1346+
12871347
public long getMinLastQueueDate() {
12881348
readLock.lock();
12891349
try {

‎nifi-framework-bundle/nifi-framework/nifi-framework-core/src/test/java/org/apache/nifi/controller/queue/clustered/TestSwappablePriorityQueue.java‎

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -609,6 +609,46 @@ public void testSwapInWhenThresholdIsLessThanSwapSize() {
609609
queue.poll(exp, 500000);
610610
}
611611

612+
@Test
613+
public void testRecoverSwappedFlowFilesPreservesOrder() throws IOException {
614+
final FlowFilePrioritizer iAttributePrioritizer = (o1, o2) -> {
615+
final int i1 = Integer.parseInt(o1.getAttribute("i"));
616+
final int i2 = Integer.parseInt(o2.getAttribute("i"));
617+
return Integer.compare(i1, i2);
618+
};
619+
620+
// 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.
621+
// On restart, the active and in-memory swap queue FlowFiles are restored newest first, and then the swap file is recovered.
622+
for (final int activeCount : new int[] {40, 80}) {
623+
swapManager = new MockSwapManager();
624+
queue = new SwappablePriorityQueue(swapManager, 100, eventReporter, flowFileQueue, dropAction, "local");
625+
queue.setPriorities(List.of(iAttributePrioritizer));
626+
627+
final List<FlowFileRecord> swappedFlowFiles = new ArrayList<>();
628+
for (int i = activeCount; i < activeCount + 100; i++) {
629+
swappedFlowFiles.add(new MockFlowFileRecord(Map.of("i", String.valueOf(i)), 1L));
630+
}
631+
swapManager.swapOut(swappedFlowFiles, flowFileQueue, "local");
632+
633+
final int totalCount = activeCount + 150;
634+
for (int i = totalCount - 1; i >= 0; i--) {
635+
if (i < activeCount || i >= activeCount + 100) {
636+
queue.put(new MockFlowFileRecord(Map.of("i", String.valueOf(i)), 1L));
637+
}
638+
}
639+
640+
queue.recoverSwappedFlowFiles();
641+
queue.put(new MockFlowFileRecord(Map.of("i", String.valueOf(totalCount)), 1L));
642+
assertEquals(totalCount + 1, queue.size().getObjectCount());
643+
644+
for (int i = 0; i <= totalCount; i++) {
645+
assertEquals(String.valueOf(i), queue.poll(Collections.emptySet(), 0L).getAttribute("i"));
646+
}
647+
648+
assertNull(queue.poll(Collections.emptySet(), 0L));
649+
}
650+
}
651+
612652
@Test
613653
public void testQueueCountsUpdatedWhenIncompleteSwapFile() {
614654
for (int i = 1; i <= 20000; i++) {
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,103 @@
1+
/*
2+
* Licensed to the Apache Software Foundation (ASF) under one or more
3+
* contributor license agreements. See the NOTICE file distributed with
4+
* this work for additional information regarding copyright ownership.
5+
* The ASF licenses this file to You under the Apache License, Version 2.0
6+
* (the "License"); you may not use this file except in compliance with
7+
* the License. You may obtain a copy of the License at
8+
*
9+
* http://www.apache.org/licenses/LICENSE-2.0
10+
*
11+
* Unless required by applicable law or agreed to in writing, software
12+
* distributed under the License is distributed on an "AS IS" BASIS,
13+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14+
* See the License for the specific language governing permissions and
15+
* limitations under the License.
16+
*/
17+
18+
package org.apache.nifi.processors.tests.system;
19+
20+
import org.apache.nifi.annotation.behavior.TriggerSerially;
21+
import org.apache.nifi.annotation.documentation.CapabilityDescription;
22+
import org.apache.nifi.components.PropertyDescriptor;
23+
import org.apache.nifi.expression.ExpressionLanguageScope;
24+
import org.apache.nifi.flowfile.FlowFile;
25+
import org.apache.nifi.processor.AbstractProcessor;
26+
import org.apache.nifi.processor.ProcessContext;
27+
import org.apache.nifi.processor.ProcessSession;
28+
import org.apache.nifi.processor.Relationship;
29+
import org.apache.nifi.processor.exception.ProcessException;
30+
import org.apache.nifi.processor.util.StandardValidators;
31+
32+
import java.util.List;
33+
import java.util.Set;
34+
35+
@TriggerSerially
36+
@CapabilityDescription("""
37+
Pulls one FlowFile at a time from the incoming queue and routes it to 'sequential' if its Value to Consider is exactly one greater than the
38+
Value to Consider of the previous FlowFile that this Processor received. Otherwise, the FlowFile is routed to 'failure'. The first FlowFile
39+
that the Processor receives is always routed to 'sequential'.
40+
""")
41+
public class VerifySequentialOrder extends AbstractProcessor {
42+
43+
static final PropertyDescriptor VALUE_TO_CONSIDER = new PropertyDescriptor.Builder()
44+
.name("Value to Consider")
45+
.description("The whole number to compare against the Value to Consider of the previous FlowFile")
46+
.required(true)
47+
.addValidator(StandardValidators.LONG_VALIDATOR)
48+
.expressionLanguageSupported(ExpressionLanguageScope.FLOWFILE_ATTRIBUTES)
49+
.build();
50+
51+
static final Relationship REL_SEQUENTIAL = new Relationship.Builder()
52+
.name("sequential")
53+
.description("The first FlowFile, and any FlowFile whose Value to Consider is exactly one greater than that of the previous FlowFile")
54+
.build();
55+
56+
static final Relationship REL_FAILURE = new Relationship.Builder()
57+
.name("failure")
58+
.description("Any FlowFile whose Value to Consider is not exactly one greater than that of the previous FlowFile, or is not a whole number")
59+
.build();
60+
61+
private static final List<PropertyDescriptor> PROPERTY_DESCRIPTORS = List.of(VALUE_TO_CONSIDER);
62+
private static final Set<Relationship> RELATIONSHIPS = Set.of(REL_SEQUENTIAL, REL_FAILURE);
63+
64+
private volatile Long previousValue;
65+
66+
@Override
67+
protected List<PropertyDescriptor> getSupportedPropertyDescriptors() {
68+
return PROPERTY_DESCRIPTORS;
69+
}
70+
71+
@Override
72+
public Set<Relationship> getRelationships() {
73+
return RELATIONSHIPS;
74+
}
75+
76+
@Override
77+
public void onTrigger(final ProcessContext context, final ProcessSession session) throws ProcessException {
78+
final FlowFile flowFile = session.get();
79+
if (flowFile == null) {
80+
return;
81+
}
82+
83+
final String value = context.getProperty(VALUE_TO_CONSIDER).evaluateAttributeExpressions(flowFile).getValue();
84+
final long currentValue;
85+
try {
86+
currentValue = Long.parseLong(value);
87+
} catch (final NumberFormatException e) {
88+
getLogger().error("Routing {} to failure because its Value to Consider [{}] is not a whole number", flowFile, value);
89+
session.transfer(flowFile, REL_FAILURE);
90+
return;
91+
}
92+
93+
final Long lastValue = previousValue;
94+
previousValue = currentValue;
95+
96+
if (lastValue == null || currentValue == lastValue + 1) {
97+
session.transfer(flowFile, REL_SEQUENTIAL);
98+
} else {
99+
getLogger().warn("Routing {} to failure because its Value to Consider is {} but the previous FlowFile's value was {}", flowFile, currentValue, lastValue);
100+
session.transfer(flowFile, REL_FAILURE);
101+
}
102+
}
103+
}

‎nifi-system-tests/nifi-system-test-extensions-bundle/nifi-system-test-extensions/src/main/resources/META-INF/services/org.apache.nifi.processor.Processor‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -67,6 +67,7 @@ org.apache.nifi.processors.tests.system.VerifyClasspathResource
6767
org.apache.nifi.processors.tests.system.VerifyContents
6868
org.apache.nifi.processors.tests.system.VerifyEvenThenOdd
6969
org.apache.nifi.processors.tests.system.VerifyMethodSignatureResource
70+
org.apache.nifi.processors.tests.system.VerifySequentialOrder
7071
org.apache.nifi.processors.tests.system.WriteFlowFileCountToFile
7172
org.apache.nifi.processors.tests.system.WriteLifecycleEvents
7273
org.apache.nifi.processors.tests.system.WriteToFile

‎nifi-system-tests/nifi-system-test-suite/src/test/java/org/apache/nifi/tests/system/restart/FlowFileRestorationIT.java‎

Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,7 @@
3131
import java.nio.file.Files;
3232
import java.nio.file.StandardOpenOption;
3333
import java.util.Collections;
34+
import java.util.Map;
3435

3536
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
3637
import static org.junit.jupiter.api.Assertions.assertEquals;
@@ -39,6 +40,12 @@
3940
import static org.junit.jupiter.api.Assertions.assertTrue;
4041

4142
public class FlowFileRestorationIT extends NiFiSystemIT {
43+
private static final int SWAP_THRESHOLD = 20;
44+
45+
@Override
46+
protected Map<String, String> getNifiPropertiesOverrides() {
47+
return Map.of("nifi.queue.swap.threshold", String.valueOf(SWAP_THRESHOLD));
48+
}
4249

4350
@Test
4451
public void testDataInMissingQueueRestoredWhenQueueRestored() throws NiFiClientException, IOException, InterruptedException {
@@ -85,6 +92,52 @@ public void testDataInMissingQueueRestoredWhenQueueRestored() throws NiFiClientE
8592
assertArrayEquals(flowFileContents, contentsAfterRestart);
8693
}
8794

95+
@Test
96+
public void testSwappedFlowFileOrderPreservedAfterRestart() throws NiFiClientException, IOException, InterruptedException {
97+
final int flowFileCount = 100;
98+
final int newerFlowFileCount = 2;
99+
ProcessorEntity generate = getClientUtil().createProcessor(GENERATE_FLOWFILE);
100+
generate = getClientUtil().updateProcessorProperties(generate, Map.of("Batch Size", String.valueOf(flowFileCount), "sequence", "${nextInt()}"));
101+
102+
ProcessorEntity verifyOrder = getClientUtil().createProcessor("VerifySequentialOrder");
103+
verifyOrder = getClientUtil().updateProcessorProperties(verifyOrder, Map.of("Value to Consider", "${sequence}"));
104+
final ConnectionEntity connection = getClientUtil().updateConnectionPrioritizer(getClientUtil().createConnection(generate, verifyOrder, SUCCESS), "FirstInFirstOutPrioritizer");
105+
106+
final ProcessorEntity terminate = getClientUtil().createProcessor(TERMINATE_FLOWFILE);
107+
final ConnectionEntity sequentialConnection = getClientUtil().createConnection(verifyOrder, terminate, "sequential");
108+
final ConnectionEntity failureConnection = getClientUtil().createConnection(verifyOrder, terminate, "failure");
109+
110+
generate = getClientUtil().runProcessorOnce(generate);
111+
getClientUtil().waitForStoppedProcessor(generate.getId());
112+
waitForQueueCount(connection.getId(), flowFileCount);
113+
114+
// The oldest FlowFiles are held in memory and the rest are written to swap files. Process as many of the oldest FlowFiles as the number
115+
// of newer FlowFiles and then queue the newer FlowFiles, which wait behind the swapped FlowFiles. All FlowFiles held in memory then fit
116+
// within the swap threshold when they are restored.
117+
for (int i = 0; i < newerFlowFileCount; i++) {
118+
verifyOrder = getClientUtil().runProcessorOnce(verifyOrder);
119+
getClientUtil().waitForStoppedProcessor(verifyOrder.getId());
120+
}
121+
122+
generate = getNifiClient().getProcessorClient().getProcessor(generate.getId());
123+
generate = getClientUtil().updateProcessorProperties(generate, Map.of("Batch Size", String.valueOf(newerFlowFileCount)));
124+
generate = getClientUtil().runProcessorOnce(generate);
125+
getClientUtil().waitForStoppedProcessor(generate.getId());
126+
waitForQueueCount(connection.getId(), flowFileCount);
127+
assertEquals(SWAP_THRESHOLD - newerFlowFileCount, getClientUtil().performQueueListing(connection.getId()).getListingRequest().getFlowFileSummaries().size());
128+
129+
final NiFiInstance nifiInstance = getNiFiInstance();
130+
nifiInstance.stop();
131+
nifiInstance.start();
132+
waitForQueueCount(connection.getId(), flowFileCount);
133+
134+
// Process all FlowFiles, including the swapped FlowFiles. Each FlowFile must be processed directly after the FlowFile created before it.
135+
verifyOrder = getNifiClient().getProcessorClient().getProcessor(verifyOrder.getId());
136+
getClientUtil().startProcessor(verifyOrder);
137+
waitFor(() -> getConnectionQueueSize(sequentialConnection.getId()) + getConnectionQueueSize(failureConnection.getId()) == flowFileCount + newerFlowFileCount);
138+
assertEquals(0, getConnectionQueueSize(failureConnection.getId()));
139+
}
140+
88141
private byte[] getFlowFileContents(final String connectionId, final int flowFileIndex) throws IOException, NiFiClientException {
89142
try (final InputStream in = getClientUtil().getFlowFileContent(connectionId, flowFileIndex);
90143
final ByteArrayOutputStream baos = new ByteArrayOutputStream()) {

0 commit comments

Comments
 (0)