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 61b414f11694 CAMEL-27477: camel-ftp - the producer health check does
not wait for an upload in progress (#30841)
61b414f11694 is described below
commit 61b414f11694ae34d9f647e8dfd500f877efc434
Author: allthingssecurity <[email protected]>
AuthorDate: Thu Nov 26 13:34:01 2026 +0530
CAMEL-27477: camel-ftp - the producer health check does not wait for an
upload in progress (#30841)
The health check of an ftp, ftps or sftp producer (producer health checks
are off by default, camel.health.producersEnabled=true) sends a NOOP through
the operations of the producer. Since CAMEL-27214 each operation of
FtpOperations holds one lock, as SftpOperations and MinaSftpOperations
already did, and an upload holds it for the whole transfer: the check waited
until the upload ended, and every further readiness call waited behind it on
the lock of the check. A readiness probe timed out during each long but
healthy upload, and its thread stayed blocked.
RemoteFileOperations gets a default method runIfIdle(check), which
FtpOperations, SftpOperations and MinaSftpOperations implement with
tryLock(): the health check runs its check only when no other thread uses
the connection, and holds the lock while it runs. When the connection is in
use, the check sends no NOOP and does not connect: it reports the state that
its last check found (UP before the first one) with the detail busy=true.
An upload that hangs keeps the connection busy until it fails (the socket
timeouts bound reads, not a blocked write), and the check reports its last
state meanwhile, as the check of a polling consumer does for a poll that
hangs unless healthCheckMaxPollDuration (CAMEL-26998) is set.
Not changed: on an idle connection to a server that does not answer, the
NOOP still waits up to soTimeout. The checks of two producers to the same
host share one id (own ticket). A probe can leave loggedIn true on a
connection that the route closes (sendNoop=false only), and can reconnect
over a connection the route just opened or after the producer stopped
(narrow windows): left as they are.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
---
.../file/remote/RemoteFileOperations.java | 19 +++
.../file/remote/RemoteFileProducerHealthCheck.java | 14 ++-
.../camel/component/file/remote/FtpOperations.java | 19 +++
.../component/file/remote/SftpOperations.java | 19 +++
.../FtpProducerHealthCheckDuringUploadTest.java | 136 ++++++++++++++++++++
.../RemoteFileProducerHealthCheckBusyTest.java | 83 ++++++++++++
.../SftpProducerHealthCheckDuringUploadIT.java | 139 +++++++++++++++++++++
.../file/remote/mina/MinaSftpOperations.java | 19 +++
.../MinaSftpProducerHealthCheckDuringUploadIT.java | 132 +++++++++++++++++++
.../ROOT/pages/camel-4x-upgrade-guide-4_24.adoc | 10 ++
10 files changed, 589 insertions(+), 1 deletion(-)
diff --git
a/components/camel-ftp-common/src/main/java/org/apache/camel/component/file/remote/RemoteFileOperations.java
b/components/camel-ftp-common/src/main/java/org/apache/camel/component/file/remote/RemoteFileOperations.java
index 0806261d4491..b6206db36d68 100644
---
a/components/camel-ftp-common/src/main/java/org/apache/camel/component/file/remote/RemoteFileOperations.java
+++
b/components/camel-ftp-common/src/main/java/org/apache/camel/component/file/remote/RemoteFileOperations.java
@@ -19,6 +19,7 @@ package org.apache.camel.component.file.remote;
import org.apache.camel.Exchange;
import org.apache.camel.component.file.GenericFileOperationFailedException;
import org.apache.camel.component.file.GenericFileOperations;
+import org.apache.camel.util.function.ThrowingRunnable;
/**
* Remote file operations based on some backing framework
@@ -97,6 +98,24 @@ public interface RemoteFileOperations<T> extends
GenericFileOperations<T> {
return false;
}
+ /**
+ * Runs a check of the connection, such as the noop of the producer health
check, unless another thread runs an
+ * operation on the connection at this time, such as an upload of the
producer. A health check must not wait for
+ * such an operation: an upload uses the connection for as long as the
transfer takes, and on a server that does not
+ * answer, up to the timeout of the connection.
+ * <p>
+ * The default implementation always runs the check.
+ *
+ * @param check the check, which can call the operations
+ * @return {@code true} if the check ran, {@code false} if
another thread was using the connection
+ * @throws Exception thrown by the check
+ * @since 4.24
+ */
+ default boolean runIfIdle(ThrowingRunnable<Exception> check) throws
Exception {
+ check.run();
+ return true;
+ }
+
/**
* Sends a site command to the remote server
*
diff --git
a/components/camel-ftp-common/src/main/java/org/apache/camel/component/file/remote/RemoteFileProducerHealthCheck.java
b/components/camel-ftp-common/src/main/java/org/apache/camel/component/file/remote/RemoteFileProducerHealthCheck.java
index d09bc3dc22f3..ecf1ba5b40cd 100644
---
a/components/camel-ftp-common/src/main/java/org/apache/camel/component/file/remote/RemoteFileProducerHealthCheck.java
+++
b/components/camel-ftp-common/src/main/java/org/apache/camel/component/file/remote/RemoteFileProducerHealthCheck.java
@@ -29,6 +29,8 @@ import org.apache.camel.impl.health.AbstractHealthCheck;
public class RemoteFileProducerHealthCheck extends AbstractHealthCheck {
private final RemoteFileProducer<?> producer;
+ // what the last check of the connection found (UP before the first one);
AbstractHealthCheck runs one call at a time
+ private State lastState = State.UP;
public RemoteFileProducerHealthCheck(RemoteFileProducer<?> producer) {
super("camel", "producer:ftp-" +
producer.getEndpoint().getConfiguration().getHost());
@@ -39,11 +41,20 @@ public class RemoteFileProducerHealthCheck extends
AbstractHealthCheck {
protected void doCall(HealthCheckResultBuilder builder, Map<String,
Object> options) {
Exchange dummy = producer.createExchange();
Exception cause = null;
+ boolean checked = true;
try {
- producer.doPreWriteCheck(dummy, true);
+ // do not wait while the producer uses the connection, such as for
an upload, which can last long
+ checked = producer.getOperations().runIfIdle(() ->
producer.doPreWriteCheck(dummy, true));
} catch (Exception e) {
cause = e;
}
+ if (!checked) {
+ // report what the last check found, the connection is checked
again when the producer no longer uses it
+ builder.state(lastState);
+ builder.message("FtpProducer is busy, the connection is in use");
+ builder.detail("busy", true);
+ return;
+ }
if (cause != null) {
builder.down();
builder.message("FtpProducer is not ready");
@@ -60,5 +71,6 @@ public class RemoteFileProducerHealthCheck extends
AbstractHealthCheck {
} else {
builder.up();
}
+ lastState = builder.state();
}
}
diff --git
a/components/camel-ftp/src/main/java/org/apache/camel/component/file/remote/FtpOperations.java
b/components/camel-ftp/src/main/java/org/apache/camel/component/file/remote/FtpOperations.java
index 7d8386d29e32..e2922fbecc14 100644
---
a/components/camel-ftp/src/main/java/org/apache/camel/component/file/remote/FtpOperations.java
+++
b/components/camel-ftp/src/main/java/org/apache/camel/component/file/remote/FtpOperations.java
@@ -51,6 +51,7 @@ import org.apache.camel.util.FileUtil;
import org.apache.camel.util.IOHelper;
import org.apache.camel.util.StopWatch;
import org.apache.camel.util.TimeUtils;
+import org.apache.camel.util.function.ThrowingRunnable;
import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPClientConfig;
@@ -1559,6 +1560,24 @@ public class FtpOperations implements
RemoteFileOperations<FTPFile> {
}
}
+ /**
+ * Runs the check, such as the noop of the producer health check, unless
another thread holds the lock, such as an
+ * upload, which holds it for the whole transfer. The check runs with the
lock held, so an upload that starts
+ * meanwhile waits for it.
+ */
+ @Override
+ public boolean runIfIdle(ThrowingRunnable<Exception> check) throws
Exception {
+ if (!lock.tryLock()) {
+ return false;
+ }
+ try {
+ check.run();
+ return true;
+ } finally {
+ lock.unlock();
+ }
+ }
+
@Override
public boolean isRecentlyUsed() {
long last = lastCompletedNanos;
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 1f62154b8cff..b95d27d101f2 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
@@ -80,6 +80,7 @@ import org.apache.camel.util.IOHelper;
import org.apache.camel.util.ObjectHelper;
import org.apache.camel.util.StopWatch;
import org.apache.camel.util.TimeUtils;
+import org.apache.camel.util.function.ThrowingRunnable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -1958,6 +1959,24 @@ public class SftpOperations
}
}
+ /**
+ * Runs the check, such as the noop of the producer health check, unless
another thread holds the lock, such as an
+ * upload, which holds it for the whole transfer. The check runs with the
lock held, so an upload that starts
+ * meanwhile waits for it.
+ */
+ @Override
+ public boolean runIfIdle(ThrowingRunnable<Exception> check) throws
Exception {
+ if (!lock.tryLock()) {
+ return false;
+ }
+ try {
+ check.run();
+ return true;
+ } finally {
+ lock.unlock();
+ }
+ }
+
@Override
public boolean sendSiteCommand(String command) throws
GenericFileOperationFailedException {
// is not implemented
diff --git
a/components/camel-ftp/src/test/java/org/apache/camel/component/file/remote/FtpProducerHealthCheckDuringUploadTest.java
b/components/camel-ftp/src/test/java/org/apache/camel/component/file/remote/FtpProducerHealthCheckDuringUploadTest.java
new file mode 100644
index 000000000000..3a183fd1c8b6
--- /dev/null
+++
b/components/camel-ftp/src/test/java/org/apache/camel/component/file/remote/FtpProducerHealthCheckDuringUploadTest.java
@@ -0,0 +1,136 @@
+/*
+ * 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.camel.component.file.remote;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.InterruptedIOException;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.concurrent.CompletableFuture;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+import java.util.concurrent.Future;
+import java.util.concurrent.TimeUnit;
+
+import org.apache.camel.CamelContext;
+import org.apache.camel.Exchange;
+import org.apache.camel.builder.RouteBuilder;
+import org.apache.camel.component.file.remote.integration.FtpServerTestSupport;
+import org.apache.camel.health.HealthCheck;
+import org.apache.camel.health.HealthCheckHelper;
+import org.junit.jupiter.api.Test;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertNull;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+/**
+ * The readiness check of the producer does not wait for an upload in progress
on the connection: the upload can last as
+ * long as the transfer takes, while the server is fine.
+ */
+class FtpProducerHealthCheckDuringUploadTest extends FtpServerTestSupport {
+
+ @Override
+ protected CamelContext createCamelContext() throws Exception {
+ CamelContext context = super.createCamelContext();
+ HealthCheckHelper.getHealthCheckRepository(context,
"producers").setEnabled(true);
+ // the producer reads the body during the upload (stream caching would
read it before)
+ context.setStreamCaching(false);
+ return context;
+ }
+
+ @Test
+ void readinessDoesNotWaitForTheUpload() throws Exception {
+ template.sendBodyAndHeader("direct:start", "hello",
Exchange.FILE_NAME, "small.txt");
+ HealthCheck.Result before = producerCheck();
+ assertEquals(HealthCheck.State.UP, before.getState());
+ assertFalse(before.getDetails().containsKey("busy"));
+
+ GatedInputStream body = new GatedInputStream();
+ CompletableFuture<Exchange> upload =
template.asyncSend("direct:start", e -> {
+ e.getIn().setBody(body);
+ e.getIn().setHeader(Exchange.FILE_NAME, "big.bin");
+ });
+ ExecutorService probes = Executors.newFixedThreadPool(3);
+ try {
+ assertTrue(body.halfway.await(20, TimeUnit.SECONDS), "the upload
started");
+ List<Future<HealthCheck.Result>> calls = new ArrayList<>();
+ for (int i = 0; i < 3; i++) {
+ calls.add(probes.submit(this::producerCheck));
+ }
+ for (Future<HealthCheck.Result> call : calls) {
+ // the upload holds the connection until the test lets it go on
+ HealthCheck.Result during = call.get(5, TimeUnit.SECONDS);
+ assertEquals(HealthCheck.State.UP, during.getState());
+ assertEquals(true, during.getDetails().get("busy"));
+ }
+ } finally {
+ body.release.countDown();
+ probes.shutdownNow();
+ }
+
+ Exchange done = upload.get(20, TimeUnit.SECONDS);
+ assertNull(done.getException());
+ // the producer no longer uses the connection: the check sends the
noop again
+ HealthCheck.Result after = producerCheck();
+ assertEquals(HealthCheck.State.UP, after.getState());
+ assertFalse(after.getDetails().containsKey("busy"));
+ }
+
+ private HealthCheck.Result producerCheck() {
+ return HealthCheckHelper.invokeReadiness(context).stream()
+ .filter(r -> r.getCheck().getId().startsWith("producer:ftp-"))
+ .findFirst().orElseThrow();
+ }
+
+ @Override
+ protected RouteBuilder createRouteBuilder() {
+ return new RouteBuilder() {
+ @Override
+ public void configure() {
+
from("direct:start").to("ftp://admin@localhost:{{ftp.server.port}}/upload?password=admin");
+ }
+ };
+ }
+
+ /**
+ * An upload body that stops half way until the test lets it go on, as a
big file or a slow network would.
+ */
+ static final class GatedInputStream extends InputStream {
+ final CountDownLatch halfway = new CountDownLatch(1);
+ final CountDownLatch release = new CountDownLatch(1);
+ private final int size = 64 * 1024;
+ private int pos;
+
+ @Override
+ public int read() throws IOException {
+ if (pos == size / 2 && release.getCount() > 0) {
+ halfway.countDown();
+ try {
+ release.await();
+ } catch (InterruptedException e) {
+ Thread.currentThread().interrupt();
+ throw new InterruptedIOException();
+ }
+ }
+ return pos < size ? 'a' + pos++ % 26 : -1;
+ }
+ }
+}
diff --git
a/components/camel-ftp/src/test/java/org/apache/camel/component/file/remote/RemoteFileProducerHealthCheckBusyTest.java
b/components/camel-ftp/src/test/java/org/apache/camel/component/file/remote/RemoteFileProducerHealthCheckBusyTest.java
new file mode 100644
index 000000000000..d997394c16d9
--- /dev/null
+++
b/components/camel-ftp/src/test/java/org/apache/camel/component/file/remote/RemoteFileProducerHealthCheckBusyTest.java
@@ -0,0 +1,83 @@
+/*
+ * 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.camel.component.file.remote;
+
+import org.apache.camel.component.file.GenericFileOperationFailedException;
+import org.apache.camel.health.HealthCheck;
+import org.apache.camel.test.junit6.CamelTestSupport;
+import org.apache.camel.util.function.ThrowingRunnable;
+import org.junit.jupiter.api.Test;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.Mockito.doAnswer;
+import static org.mockito.Mockito.doReturn;
+import static org.mockito.Mockito.doThrow;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.times;
+import static org.mockito.Mockito.verify;
+
+/**
+ * While the producer uses its connection, the health check does not check the
connection: it reports the state that its
+ * last check found.
+ */
+class RemoteFileProducerHealthCheckBusyTest extends CamelTestSupport {
+
+ @SuppressWarnings("unchecked")
+ @Test
+ void busyReportsTheStateOfTheLastCheck() throws Exception {
+ RemoteFileEndpoint<Object> endpoint =
context.getEndpoint("ftp://localhost/out", RemoteFileEndpoint.class);
+ RemoteFileOperations<Object> operations =
mock(RemoteFileOperations.class);
+ RemoteFileProducer<Object> producer = new
RemoteFileProducer<>(endpoint, operations);
+ RemoteFileProducerHealthCheck check = new
RemoteFileProducerHealthCheck(producer);
+ check.setCamelContext(context);
+
+ // idle: the check runs, and the server refuses the connection
+ idle(operations);
+ doThrow(new GenericFileOperationFailedException("Connection
refused")).when(operations).connect(any(), any());
+ assertEquals(HealthCheck.State.DOWN, check.call().getState());
+
+ // busy: no connect, the state of the last check
+ doReturn(false).when(operations).runIfIdle(any());
+ HealthCheck.Result busy = check.call();
+ assertEquals(HealthCheck.State.DOWN, busy.getState());
+ assertEquals(true, busy.getDetails().get("busy"));
+ verify(operations, times(1)).connect(any(), any());
+
+ // idle again: the check connects
+ idle(operations);
+ doReturn(true).when(operations).connect(any(), any());
+ doReturn(true).when(operations).isConnected();
+ HealthCheck.Result up = check.call();
+ assertEquals(HealthCheck.State.UP, up.getState());
+ assertFalse(up.getDetails().containsKey("busy"));
+
+ doReturn(false).when(operations).runIfIdle(any());
+ busy = check.call();
+ assertEquals(HealthCheck.State.UP, busy.getState());
+ assertEquals(true, busy.getDetails().get("busy"));
+ verify(operations, times(2)).connect(any(), any());
+ }
+
+ private static void idle(RemoteFileOperations<?> operations) throws
Exception {
+ doAnswer(invocation -> {
+ invocation.<ThrowingRunnable<Exception>> getArgument(0).run();
+ return true;
+ }).when(operations).runIfIdle(any());
+ }
+}
diff --git
a/components/camel-ftp/src/test/java/org/apache/camel/component/file/remote/sftp/integration/SftpProducerHealthCheckDuringUploadIT.java
b/components/camel-ftp/src/test/java/org/apache/camel/component/file/remote/sftp/integration/SftpProducerHealthCheckDuringUploadIT.java
new file mode 100644
index 000000000000..cb6133bbffd8
--- /dev/null
+++
b/components/camel-ftp/src/test/java/org/apache/camel/component/file/remote/sftp/integration/SftpProducerHealthCheckDuringUploadIT.java
@@ -0,0 +1,139 @@
+/*
+ * 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.camel.component.file.remote.sftp.integration;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.InterruptedIOException;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.concurrent.CompletableFuture;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+import java.util.concurrent.Future;
+import java.util.concurrent.TimeUnit;
+
+import org.apache.camel.CamelContext;
+import org.apache.camel.Exchange;
+import org.apache.camel.builder.RouteBuilder;
+import org.apache.camel.health.HealthCheck;
+import org.apache.camel.health.HealthCheckHelper;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.condition.EnabledIf;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertNull;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+/**
+ * The readiness check of the SFTP producer does not wait for an upload in
progress on the connection: the upload can
+ * last as long as the transfer takes, while the server is fine.
+ */
+@EnabledIf(value =
"org.apache.camel.test.infra.ftp.services.embedded.SftpUtil#hasRequiredAlgorithms('src/test/resources/hostkey.pem')")
+class SftpProducerHealthCheckDuringUploadIT extends SftpServerTestSupport {
+
+ @Override
+ protected CamelContext createCamelContext() throws Exception {
+ CamelContext context = super.createCamelContext();
+ HealthCheckHelper.getHealthCheckRepository(context,
"producers").setEnabled(true);
+ // the producer reads the body during the upload (stream caching would
read it before)
+ context.setStreamCaching(false);
+ return context;
+ }
+
+ @Test
+ void readinessDoesNotWaitForTheUpload() throws Exception {
+ template.sendBodyAndHeader("direct:start", "hello",
Exchange.FILE_NAME, "small.txt");
+ HealthCheck.Result before = producerCheck();
+ assertEquals(HealthCheck.State.UP, before.getState());
+ assertFalse(before.getDetails().containsKey("busy"));
+
+ GatedInputStream body = new GatedInputStream();
+ CompletableFuture<Exchange> upload =
template.asyncSend("direct:start", e -> {
+ e.getIn().setBody(body);
+ e.getIn().setHeader(Exchange.FILE_NAME, "big.bin");
+ });
+ ExecutorService probes = Executors.newFixedThreadPool(3);
+ try {
+ assertTrue(body.halfway.await(20, TimeUnit.SECONDS), "the upload
started");
+ List<Future<HealthCheck.Result>> calls = new ArrayList<>();
+ for (int i = 0; i < 3; i++) {
+ calls.add(probes.submit(this::producerCheck));
+ }
+ for (Future<HealthCheck.Result> call : calls) {
+ // the upload holds the connection until the test lets it go on
+ HealthCheck.Result during = call.get(5, TimeUnit.SECONDS);
+ assertEquals(HealthCheck.State.UP, during.getState());
+ assertEquals(true, during.getDetails().get("busy"));
+ }
+ } finally {
+ body.release.countDown();
+ probes.shutdownNow();
+ }
+
+ Exchange done = upload.get(20, TimeUnit.SECONDS);
+ assertNull(done.getException());
+ // the producer no longer uses the connection: the check sends the
noop again
+ HealthCheck.Result after = producerCheck();
+ assertEquals(HealthCheck.State.UP, after.getState());
+ assertFalse(after.getDetails().containsKey("busy"));
+ }
+
+ private HealthCheck.Result producerCheck() {
+ return HealthCheckHelper.invokeReadiness(context).stream()
+ .filter(r -> r.getCheck().getId().startsWith("producer:ftp-"))
+ .findFirst().orElseThrow();
+ }
+
+ @Override
+ protected RouteBuilder createRouteBuilder() {
+ return new RouteBuilder() {
+ @Override
+ public void configure() {
+ from("direct:start")
+
.to("sftp://localhost:{{ftp.server.port}}/{{ftp.root.dir}}/upload?username=admin&password=admin"
+ + "&knownHostsFile=" +
service.getKnownHostsFile());
+ }
+ };
+ }
+
+ /**
+ * An upload body that stops half way until the test lets it go on, as a
big file or a slow network would.
+ */
+ static final class GatedInputStream extends InputStream {
+ final CountDownLatch halfway = new CountDownLatch(1);
+ final CountDownLatch release = new CountDownLatch(1);
+ private final int size = 64 * 1024;
+ private int pos;
+
+ @Override
+ public int read() throws IOException {
+ if (pos == size / 2 && release.getCount() > 0) {
+ halfway.countDown();
+ try {
+ release.await();
+ } catch (InterruptedException e) {
+ Thread.currentThread().interrupt();
+ throw new InterruptedIOException();
+ }
+ }
+ return pos < size ? 'a' + pos++ % 26 : -1;
+ }
+ }
+}
diff --git
a/components/camel-mina-sftp/src/main/java/org/apache/camel/component/file/remote/mina/MinaSftpOperations.java
b/components/camel-mina-sftp/src/main/java/org/apache/camel/component/file/remote/mina/MinaSftpOperations.java
index 03973a80491b..df53dc701590 100644
---
a/components/camel-mina-sftp/src/main/java/org/apache/camel/component/file/remote/mina/MinaSftpOperations.java
+++
b/components/camel-mina-sftp/src/main/java/org/apache/camel/component/file/remote/mina/MinaSftpOperations.java
@@ -61,6 +61,7 @@ import org.apache.camel.support.task.budget.Budgets;
import org.apache.camel.util.FileUtil;
import org.apache.camel.util.IOHelper;
import org.apache.camel.util.ObjectHelper;
+import org.apache.camel.util.function.ThrowingRunnable;
import org.apache.sshd.client.ClientBuilder;
import org.apache.sshd.client.SshClient;
import org.apache.sshd.client.keyverifier.AcceptAllServerKeyVerifier;
@@ -1745,6 +1746,24 @@ public class MinaSftpOperations
}
}
+ /**
+ * Runs the check, such as the noop of the producer health check, unless
another thread holds the lock, such as an
+ * upload, which holds it for the whole transfer. The check runs with the
lock held, so an upload that starts
+ * meanwhile waits for it.
+ */
+ @Override
+ public boolean runIfIdle(ThrowingRunnable<Exception> check) throws
Exception {
+ if (!lock.tryLock()) {
+ return false;
+ }
+ try {
+ check.run();
+ return true;
+ } finally {
+ lock.unlock();
+ }
+ }
+
/**
* Site commands are an FTP-specific feature (RFC 959) and are not part of
the SFTP protocol.
* <p/>
diff --git
a/components/camel-mina-sftp/src/test/java/org/apache/camel/component/file/remote/mina/integration/MinaSftpProducerHealthCheckDuringUploadIT.java
b/components/camel-mina-sftp/src/test/java/org/apache/camel/component/file/remote/mina/integration/MinaSftpProducerHealthCheckDuringUploadIT.java
new file mode 100644
index 000000000000..c55c6fa976cb
--- /dev/null
+++
b/components/camel-mina-sftp/src/test/java/org/apache/camel/component/file/remote/mina/integration/MinaSftpProducerHealthCheckDuringUploadIT.java
@@ -0,0 +1,132 @@
+/*
+ * 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.camel.component.file.remote.mina.integration;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.InterruptedIOException;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.concurrent.CompletableFuture;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+import java.util.concurrent.Future;
+import java.util.concurrent.TimeUnit;
+
+import org.apache.camel.CamelContext;
+import org.apache.camel.Exchange;
+import org.apache.camel.health.HealthCheck;
+import org.apache.camel.health.HealthCheckHelper;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.condition.EnabledIf;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertNull;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+/**
+ * The readiness check of the mina-sftp producer does not wait for an upload
in progress on the connection: the upload
+ * can last as long as the transfer takes, while the server is fine.
+ */
+@EnabledIf(value =
"org.apache.camel.test.infra.ftp.services.embedded.SftpUtil#hasRequiredAlgorithms('src/test/resources/hostkey.pem')")
+class MinaSftpProducerHealthCheckDuringUploadIT extends
MinaSftpServerTestSupport {
+
+ @Override
+ protected CamelContext createCamelContext() throws Exception {
+ CamelContext context = super.createCamelContext();
+ HealthCheckHelper.getHealthCheckRepository(context,
"producers").setEnabled(true);
+ // the producer reads the body during the upload (stream caching would
read it before)
+ context.setStreamCaching(false);
+ return context;
+ }
+
+ @Test
+ void readinessDoesNotWaitForTheUpload() throws Exception {
+ template.sendBodyAndHeader(uri(), "hello", Exchange.FILE_NAME,
"small.txt");
+ HealthCheck.Result before = producerCheck();
+ assertEquals(HealthCheck.State.UP, before.getState());
+ assertFalse(before.getDetails().containsKey("busy"));
+
+ GatedInputStream body = new GatedInputStream();
+ CompletableFuture<Exchange> upload = template.asyncSend(uri(), e -> {
+ e.getIn().setBody(body);
+ e.getIn().setHeader(Exchange.FILE_NAME, "big.bin");
+ });
+ ExecutorService probes = Executors.newFixedThreadPool(3);
+ try {
+ assertTrue(body.halfway.await(20, TimeUnit.SECONDS), "the upload
started");
+ List<Future<HealthCheck.Result>> calls = new ArrayList<>();
+ for (int i = 0; i < 3; i++) {
+ calls.add(probes.submit(this::producerCheck));
+ }
+ for (Future<HealthCheck.Result> call : calls) {
+ // the upload holds the connection until the test lets it go on
+ HealthCheck.Result during = call.get(5, TimeUnit.SECONDS);
+ assertEquals(HealthCheck.State.UP, during.getState());
+ assertEquals(true, during.getDetails().get("busy"));
+ }
+ } finally {
+ body.release.countDown();
+ probes.shutdownNow();
+ }
+
+ Exchange done = upload.get(20, TimeUnit.SECONDS);
+ assertNull(done.getException());
+ // the producer no longer uses the connection: the check sends the
noop again
+ HealthCheck.Result after = producerCheck();
+ assertEquals(HealthCheck.State.UP, after.getState());
+ assertFalse(after.getDetails().containsKey("busy"));
+ }
+
+ private HealthCheck.Result producerCheck() {
+ return HealthCheckHelper.invokeReadiness(context).stream()
+ .filter(r -> r.getCheck().getId().startsWith("producer:ftp-"))
+ .findFirst().orElseThrow();
+ }
+
+ private String uri() {
+ // the port of the server is known once it started, after the routes
of the test were created
+ return "mina-sftp://localhost:" + service.getPort() + "/" +
service.getFtpRootDir()
+ +
"/upload?username=admin&password=admin&strictHostKeyChecking=no&useUserKnownHostsFile=false";
+ }
+
+ /**
+ * An upload body that stops half way until the test lets it go on, as a
big file or a slow network would.
+ */
+ static final class GatedInputStream extends InputStream {
+ final CountDownLatch halfway = new CountDownLatch(1);
+ final CountDownLatch release = new CountDownLatch(1);
+ private final int size = 64 * 1024;
+ private int pos;
+
+ @Override
+ public int read() throws IOException {
+ if (pos == size / 2 && release.getCount() > 0) {
+ halfway.countDown();
+ try {
+ release.await();
+ } catch (InterruptedException e) {
+ Thread.currentThread().interrupt();
+ throw new InterruptedIOException();
+ }
+ }
+ return pos < size ? 'a' + pos++ % 26 : -1;
+ }
+ }
+}
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 4ede109e2809..0ca7742fe5e0 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
@@ -687,6 +687,16 @@ directory than the one it lists. A backslash is a valid
character in the name of
poll such a directory, set `stepwise=false`. With
`handleDirectoryParserAbsoluteResult=true`, a backslash always
separates names, so such a directory cannot be polled.
+=== camel-ftp, camel-sftp - the producer health check does not wait for an
upload
+
+The health check of an ftp, ftps or sftp producer (producer health checks are
off by default and are turned on with
+`camel.health.producersEnabled=true`) no longer waits while the producer uses
its connection, such as for an upload.
+It waited for the whole upload before it sent its `NOOP`, so a readiness probe
could time out during a long but
+healthy upload. While the connection is in use, the check now reports the
state that its last check of the connection
+found (`UP` before the first one), with the detail `busy` set to `true`. The
next call sends the `NOOP` again when the
+connection is no longer in use. An upload that hangs is reported the same way
until it fails, so the check does not
+turn `DOWN` while it hangs (before, the readiness call waited for it).
+
=== camel-ai-resource - fixed resourceUri cannot contain braces
Starting in Camel 4.24, `ai-resource` rejects a fixed `resourceUri` containing
`{` or `}` at route startup. The MCP SDK interprets those characters as
URI-template expressions. Routes that intend variable path segments must use
`uriTemplate` instead, for example
`+ai-resource:customer?uriTemplate=camel:///customers/{id}+`. If the braces are
literal URI characters, percent-encode them as `%7B` and `%7D`.