This is an automated email from the ASF dual-hosted git repository.
davsclaus pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/camel.git
The following commit(s) were added to refs/heads/main by this push:
new 3eceacaea31c CAMEL-27277: Fix flaky SftpSimpleProduceDisconnectIT via
round-trip noop in SftpOperations (#30483)
3eceacaea31c is described below
commit 3eceacaea31c97b2283fdd0e7510d1fec95dcc4c
Author: Guillaume Nodet <[email protected]>
AuthorDate: Mon Nov 23 19:50:48 2026 +0100
CAMEL-27277: Fix flaky SftpSimpleProduceDisconnectIT via round-trip noop in
SftpOperations (#30483)
Co-authored-by: Claude Sonnet 4.6 <[email protected]>
---
.../component/file/remote/SftpOperations.java | 44 ++++++++++--
.../integration/SftpConsumerSendNoopFalseIT.java | 83 +++++++++++++---------
.../integration/SftpSimpleProduceDisconnectIT.java | 22 +++++-
.../sftp/integration/SftpStepwiseRequestsIT.java | 7 +-
.../ROOT/pages/camel-4x-upgrade-guide-4_24.adoc | 7 +-
5 files changed, 122 insertions(+), 41 deletions(-)
diff --git
a/components/camel-ftp/src/main/java/org/apache/camel/component/file/remote/SftpOperations.java
b/components/camel-ftp/src/main/java/org/apache/camel/component/file/remote/SftpOperations.java
index 8de52dd2dd2f..d350ffc2d9b7 100644
---
a/components/camel-ftp/src/main/java/org/apache/camel/component/file/remote/SftpOperations.java
+++
b/components/camel-ftp/src/main/java/org/apache/camel/component/file/remote/SftpOperations.java
@@ -100,6 +100,12 @@ public class SftpOperations
// while the stop of the producer waits for an operation of another
thread, how often it checks whether the shutdown
// is forced, and then how long it waits for the disconnect
private static final long DISCONNECT_ON_STOP_WAIT_MILLIS = 1000;
+ /**
+ * A connection used for an upload, a download or a noop this recently ago
is treated as alive: the noop before the
+ * next upload is skipped, as it would not show anything new about the
connection state. This matches the value used
+ * by {@link FtpOperations}.
+ */
+ private static final long RECENTLY_USED_NANOS =
TimeUnit.SECONDS.toNanos(1);
/**
* How many directories autoCreate remembers on a connection at most: the
gain is for repeated uploads into the same
* directories, and a producer that writes into a new directory for each
message must not grow without limit.
@@ -139,6 +145,12 @@ public class SftpOperations
* {@link #MAX_BUILT_DIRECTORIES} most recently used ones.
*/
private final Set<String> builtDirectories =
Collections.newSetFromMap(LRUCacheFactory.newLRUCache(MAX_BUILT_DIRECTORIES));
+ /**
+ * The timestamp (in nanoseconds, from {@link System#nanoTime()}) of the
last completed upload, download, or noop.
+ * Zero means no operation has completed yet. Used by {@link
#isRecentlyUsed()} to skip the pre-upload noop when the
+ * connection was used a moment ago and is therefore known to be alive.
+ */
+ private volatile long lastCompletedNanos;
private static class TaskPayload {
final RemoteFileConfiguration configuration;
@@ -1076,6 +1088,7 @@ public class SftpOperations
restoreDirectory = null;
stepwiseDirectory = null;
builtDirectories.clear();
+ lastCompletedNanos = 0;
}
/**
@@ -1367,14 +1380,19 @@ public class SftpOperations
try {
LOG.trace("retrieveFile({})", name);
inStepwiseOperation = true;
+ boolean answer;
if (ObjectHelper.isNotEmpty(endpoint.getLocalWorkDirectory())) {
// local work directory is configured so we should store file
// content as files in this local directory
- return retrieveFileToFileInLocalWorkDirectory(name, exchange);
+ answer = retrieveFileToFileInLocalWorkDirectory(name,
exchange);
} else {
// store file content directory as stream on the body
- return retrieveFileToStreamInBody(name, exchange);
+ answer = retrieveFileToStreamInBody(name, exchange);
+ }
+ if (answer) {
+ lastCompletedNanos = System.nanoTime();
}
+ return answer;
} finally {
inStepwiseOperation = false;
lock.unlock();
@@ -1555,6 +1573,7 @@ public class SftpOperations
answer = storeFileInBuiltDirectoryAgain(name, directory,
exchange, e);
}
if (answer) {
+ lastCompletedNanos = System.nanoTime();
rememberBuiltDirectory(directory);
}
return answer;
@@ -1898,16 +1917,33 @@ public class SftpOperations
return getFileAttributes(name) != null;
}
+ @Override
+ public boolean isRecentlyUsed() {
+ long last = lastCompletedNanos;
+ if (last == 0 || System.nanoTime() - last >= RECENTLY_USED_NANOS) {
+ return false;
+ }
+ // Even if recently used, verify the session is still connected: if
the server restarted
+ // within the last second, JSch may have already seen the EOF and
isConnected() returns false.
+ return isConnected();
+ }
+
@Override
public boolean sendNoop() throws GenericFileOperationFailedException {
lock.lock();
try {
if (isConnected()) {
try {
- session.sendKeepAliveMsg();
+ // Use a round-trip SFTP operation (realpath) rather than
the JSch keep-alive
+ // write (sendKeepAliveMsg), which is fire-and-forget and
returns true even when
+ // the server has closed the connection but the kernel has
not yet delivered the
+ // TCP RST to the JSch reader thread. A realpath request
waits for the server's
+ // response, so it reliably detects a stale session after
a server restart.
+ channel.realpath(".");
+ lastCompletedNanos = System.nanoTime();
return true;
} catch (Exception e) {
- LOG.debug("SFTP session was closed. Ignoring this
exception.", e);
+ LOG.debug("SFTP session noop failed. Ignoring this
exception.", e);
return false;
}
}
diff --git
a/components/camel-ftp/src/test/java/org/apache/camel/component/file/remote/sftp/integration/SftpConsumerSendNoopFalseIT.java
b/components/camel-ftp/src/test/java/org/apache/camel/component/file/remote/sftp/integration/SftpConsumerSendNoopFalseIT.java
index 2b21a3ab5ffb..da43cd9535cb 100644
---
a/components/camel-ftp/src/test/java/org/apache/camel/component/file/remote/sftp/integration/SftpConsumerSendNoopFalseIT.java
+++
b/components/camel-ftp/src/test/java/org/apache/camel/component/file/remote/sftp/integration/SftpConsumerSendNoopFalseIT.java
@@ -16,8 +16,6 @@
*/
package org.apache.camel.component.file.remote.sftp.integration;
-import java.util.ArrayList;
-import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import org.apache.camel.Exchange;
@@ -25,10 +23,9 @@ import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.component.file.remote.BaseServerTestSupport;
import org.apache.camel.component.mock.MockEndpoint;
import org.apache.camel.test.infra.ftp.services.embedded.SftpEmbeddedService;
-import org.apache.sshd.common.channel.RequestHandler;
-import org.apache.sshd.common.session.ConnectionService;
import org.apache.sshd.common.session.Session;
import org.apache.sshd.common.session.SessionListener;
+import org.apache.sshd.sftp.common.SftpConstants;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.condition.EnabledIf;
import org.junit.jupiter.api.extension.RegisterExtension;
@@ -37,31 +34,25 @@ import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
/**
- * With sendNoop=false the sftp consumer does not send a keep-alive request
before each poll, and stays connected
- * between polls.
+ * Verifies that sendNoop controls whether a keep-alive REALPATH round-trip is
sent before each poll.
+ * <p>
+ * Both sendNoop=true and sendNoop=false cause REALPATH requests (JSch
resolves "." before every {@code ls}), but
+ * sendNoop=true adds an extra REALPATH per poll for the noop check. The test
runs both modes in sequence against the
+ * same embedded server and asserts that the sendNoop=true run produces
strictly more REALPATH requests <em>per
+ * poll</em> than the sendNoop=false baseline (comparing per-poll rates avoids
a flaky failure if the two runs complete
+ * a different number of polls within the minimum-5 window).
*/
@EnabledIf(value =
"org.apache.camel.test.infra.ftp.services.embedded.SftpUtil#hasRequiredAlgorithms('src/test/resources/hostkey.pem')")
public class SftpConsumerSendNoopFalseIT extends BaseServerTestSupport {
- private final AtomicInteger keepAlives = new AtomicInteger();
private final AtomicInteger logins = new AtomicInteger();
@RegisterExtension
- protected SftpEmbeddedService service = new SftpEmbeddedService() {
+ protected SftpEmbeddedService service = new
SftpExistsFileIT.CountingSftpEmbeddedService() {
@Override
public void setUpServer() throws Exception {
super.setUpServer();
- // count the keep-alive requests and the logins the server sees
- List<RequestHandler<ConnectionService>> handlers = new
ArrayList<>();
- handlers.add((connectionService, request, wantReply, buffer) -> {
- if (request.startsWith("keepalive@")) {
- keepAlives.incrementAndGet();
- }
- // let the default handlers answer the request
- return RequestHandler.Result.Unsupported;
- });
- handlers.addAll(sshd.getGlobalRequestHandlers());
- sshd.setGlobalRequestHandlers(handlers);
+ // count the logins the server sees
sshd.addSessionListener(new SessionListener() {
@Override
public void sessionEvent(Session session, Event event) {
@@ -73,6 +64,10 @@ public class SftpConsumerSendNoopFalseIT extends
BaseServerTestSupport {
}
};
+ private SftpExistsFileIT.CountingSftpEmbeddedService countingService() {
+ return (SftpExistsFileIT.CountingSftpEmbeddedService) service;
+ }
+
private String getSftpUrl() {
return
"sftp://localhost:{{ftp.server.port}}/{{ftp.root.dir}}/sendnoop?username=admin&password=admin"
+ "&knownHostsFile=" + service.getKnownHostsFile()
@@ -80,26 +75,47 @@ public class SftpConsumerSendNoopFalseIT extends
BaseServerTestSupport {
}
@Test
- public void testSendNoopFalse() throws Exception {
- consumeFileAndPollAgain("sendNoopFalse");
-
- assertEquals(0, keepAlives.get(), "The consumer should not send a
keep-alive before a poll when sendNoop=false");
- assertEquals(1, logins.get(), "The consumer should stay connected
between polls");
- }
-
- @Test
- public void testSendNoopDefault() throws Exception {
- consumeFileAndPollAgain("sendNoopDefault");
-
- assertTrue(keepAlives.get() > 0, "The consumer should send a
keep-alive before a poll by default");
- assertEquals(1, logins.get(), "The consumer should stay connected
between polls");
+ public void testSendNoopDifference() throws Exception {
+ // --- Run with sendNoop=false (baseline) ---
+ MockEndpoint mockFalse = consumeFileAndPollAgain("sendNoopFalse");
+ // Stop the route before reading the counter: the consumer polls every
100 ms and may
+ // still be in flight. Reading the counter while the route is running
risks a race where
+ // sendNoop=false accumulates extra REALPATH requests from JSch's
internal cd/ls calls
+ // between assertIsSatisfied() returning and the route actually
stopping.
+ context.getRouteController().stopRoute("sendNoopFalse");
+ // Divide by the number of polls to get a per-poll rate: JSch sends
several REALPATH
+ // requests per poll (for cd/ls), so an extra poll in one run would
skew the raw count.
+ int pollsFalse = mockFalse.getReceivedCounter();
+ double realpathPerPollFalse = (double)
countingService().requests(SftpConstants.SSH_FXP_REALPATH) / pollsFalse;
+ assertEquals(1, logins.get(), "The consumer should stay connected
between polls (sendNoop=false)");
+
+ // reset counters and login count for the second run
+ countingService().reset();
+ logins.set(0);
+
+ // --- Run with sendNoop=true (default) ---
+ MockEndpoint mockTrue = consumeFileAndPollAgain("sendNoopDefault");
+ // Stop the route before reading, same reason as for the
sendNoop=false run above.
+ context.getRouteController().stopRoute("sendNoopDefault");
+ int pollsTrue = mockTrue.getReceivedCounter();
+ double realpathPerPollTrue = (double)
countingService().requests(SftpConstants.SSH_FXP_REALPATH) / pollsTrue;
+ assertEquals(1, logins.get(), "The consumer should stay connected
between polls (sendNoop=true)");
+
+ // sendNoop=true sends an extra REALPATH round-trip before every poll,
so it must produce
+ // strictly more REALPATH per poll. Comparing per-poll rates avoids a
flaky failure when
+ // the two runs complete a different number of polls within the
minimum-5 window.
+ assertTrue(realpathPerPollTrue > realpathPerPollFalse,
+ "sendNoop=true should send more REALPATH requests per poll ("
+ realpathPerPollTrue
+ + ") than
sendNoop=false ("
+ +
realpathPerPollFalse + ")");
}
- private void consumeFileAndPollAgain(String routeId) throws Exception {
+ private MockEndpoint consumeFileAndPollAgain(String routeId) throws
Exception {
template.sendBodyAndHeader("file://" + service.getFtpRootDir() +
"/sendnoop", "Hello World", Exchange.FILE_NAME,
"hello.txt");
MockEndpoint mock = getMockEndpoint("mock:result");
+ mock.reset();
// the file, and then an empty message for each poll that finds no new
file
mock.expectedMinimumMessageCount(5);
mock.message(0).body(String.class).isEqualTo("Hello World");
@@ -107,6 +123,7 @@ public class SftpConsumerSendNoopFalseIT extends
BaseServerTestSupport {
context.getRouteController().startRoute(routeId);
MockEndpoint.assertIsSatisfied(context);
+ return mock;
}
@Override
diff --git
a/components/camel-ftp/src/test/java/org/apache/camel/component/file/remote/sftp/integration/SftpSimpleProduceDisconnectIT.java
b/components/camel-ftp/src/test/java/org/apache/camel/component/file/remote/sftp/integration/SftpSimpleProduceDisconnectIT.java
index aacc601cb3fa..0356cdaa3fb3 100644
---
a/components/camel-ftp/src/test/java/org/apache/camel/component/file/remote/sftp/integration/SftpSimpleProduceDisconnectIT.java
+++
b/components/camel-ftp/src/test/java/org/apache/camel/component/file/remote/sftp/integration/SftpSimpleProduceDisconnectIT.java
@@ -17,11 +17,16 @@
package org.apache.camel.component.file.remote.sftp.integration;
import java.io.File;
+import java.io.IOException;
+import java.net.InetSocketAddress;
+import java.net.Socket;
+import java.util.concurrent.TimeUnit;
import org.apache.camel.Exchange;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.condition.EnabledIf;
+import static org.awaitility.Awaitility.await;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
@@ -39,9 +44,24 @@ public class SftpSimpleProduceDisconnectIT extends
SftpServerTestSupport {
assertTrue(file.exists(), "File should exist: " + file);
assertEquals("Hello World",
context.getTypeConverter().convertTo(String.class, file));
- // restart the SFTP server now
+ // Restart the SFTP server. Wait at least 1100 ms before the second
upload so that
+ // isRecentlyUsed() (which caches the last-used timestamp for 1
second) returns false
+ // regardless of whether JSch has already processed the EOF from the
old connection.
+ // With isRecentlyUsed() returning false, preWriteCheck() calls
sendNoop(), which does a
+ // round-trip REALPATH that detects the stale session and triggers a
reconnect.
service.tearDownServer();
service.setUpServer();
+ int port = service.getPort();
+ await().pollDelay(1100, TimeUnit.MILLISECONDS).atMost(10,
TimeUnit.SECONDS)
+ .pollInterval(50, TimeUnit.MILLISECONDS)
+ .until(() -> {
+ try (Socket s = new Socket()) {
+ s.connect(new InetSocketAddress("localhost", port),
100);
+ return true;
+ } catch (IOException e) {
+ return false;
+ }
+ });
template.sendBodyAndHeader(
"sftp://localhost:{{ftp.server.port}}/{{ftp.root.dir}}?username=admin&password=admin&knownHostsFile="
diff --git
a/components/camel-ftp/src/test/java/org/apache/camel/component/file/remote/sftp/integration/SftpStepwiseRequestsIT.java
b/components/camel-ftp/src/test/java/org/apache/camel/component/file/remote/sftp/integration/SftpStepwiseRequestsIT.java
index 6b8c2273f380..bf32fbb9ebbc 100644
---
a/components/camel-ftp/src/test/java/org/apache/camel/component/file/remote/sftp/integration/SftpStepwiseRequestsIT.java
+++
b/components/camel-ftp/src/test/java/org/apache/camel/component/file/remote/sftp/integration/SftpStepwiseRequestsIT.java
@@ -73,10 +73,15 @@ class SftpStepwiseRequestsIT extends CamelTestSupport {
}
// an OPEN, a WRITE and a CLOSE per file: no REALPATH and STAT to
change directory and back, and no listing or
- // attributes to check that the directory exists
+ // attributes to check that the directory exists. sendNoop=true (the
default) adds a REALPATH before each upload
+ // to check that the connection is alive, via
SftpOperations.sendNoop() — but isRecentlyUsed() skips the noop
+ // when the previous upload completed less than a second ago, so
back-to-back uploads like these see 0 REALPATHs.
assertEquals(10, service.requests(SftpConstants.SSH_FXP_OPEN));
assertEquals(10, service.requests(SftpConstants.SSH_FXP_WRITE));
assertEquals(10, service.requests(SftpConstants.SSH_FXP_CLOSE));
+ // 0 REALPATHs holds only while each upload starts less than a second
after the previous one,
+ // so that isRecentlyUsed() returns true and sendNoop() is skipped. If
the loop were slower
+ // (e.g. because of a debugger or a loaded CI), some uploads would
trigger a noop REALPATH.
assertEquals(0, service.requests(SftpConstants.SSH_FXP_REALPATH));
assertEquals(0, service.requests(SftpConstants.SSH_FXP_STAT));
assertEquals(0, service.requests(SftpConstants.SSH_FXP_LSTAT));
diff --git
a/docs/user-manual/modules/ROOT/pages/camel-4x-upgrade-guide-4_24.adoc
b/docs/user-manual/modules/ROOT/pages/camel-4x-upgrade-guide-4_24.adoc
index 1a480fd068c5..66a245196517 100644
--- a/docs/user-manual/modules/ROOT/pages/camel-4x-upgrade-guide-4_24.adoc
+++ b/docs/user-manual/modules/ROOT/pages/camel-4x-upgrade-guide-4_24.adoc
@@ -549,11 +549,14 @@ stream caching enabled) or a reader, or with
`fileExist=Append`: that upload fai
directory. The directories that a consumer moves files into (`move`,
`preMove`, `moveFailed`) are still checked each
time.
-With the default `sendNoop=true`, the ftp producer no longer sends a `NOOP`
before an upload when the server completed
+With the default `sendNoop=true`, the ftp and sftp producers no longer send a
`NOOP` before an upload when the server completed
an upload, a download or a `NOOP` on that connection less than a second
before. A connection that the server closed
within that second is then found by the upload, which fails, instead of by the
`NOOP`, after which the producer would
have connected again; the next upload connects again. The consumer still sends
a `NOOP` before each poll, and the
-health check before each check.
+health check before each check. For sftp, the noop is now an SFTP `REALPATH`
round-trip (answered by the server)
+instead of an SSH keep-alive write (fire-and-forget), so a stale session that
was idle for more than a
+second is detected before the next upload. This also
+means the sftp consumer with the default `sendNoop=true` sends one `REALPATH`
request per poll.
The absolute paths that the SFTP server sees do not change. The FTP server
sees fewer `CWD` and `PWD` commands, and its
current directory between two uploads is the directory of the last file, not
the starting directory. `FtpOperations`