This is an automated email from the ASF dual-hosted git repository. Croway pushed a commit to branch main in repository https://gitbox.apache.org/repos/asf/camel.git
commit 2a60382c624806a12dde6da1b40b35dc00cb4fd8 Author: croway <[email protected]> AuthorDate: Thu Nov 26 09:53:45 2026 +0100 CAMEL-27009: camel-jms, camel-spring-rabbitmq - address review feedback on the bounded listener container stop - camel-jms: the stop hand-off uses the CompletableFuture + AtomicBoolean pattern of camel-spring-rabbitmq, on a dedicated JmsStopListenerContainer thread pool of the component (the AsyncStartStopListener pool runs the asynchronous starts of CAMEL-27534, which a suspend must not queue behind). - camel-jms: with consumerType=Simple and Spring's SyncTaskExecutor (the JMS client then calls the route itself, and stops the connection once it returns), the consumer waits as long as the route processes messages, and the bound after the last one. - camel-spring-rabbitmq: the bound is the shutdownTimeout of the component (in which Spring AMQP waits for the in-flight deliveries, from any thread) plus the shutdownAwaitTermination, so a slow message or a suspend from the listener thread no longer trips it. - Both: shutdownAwaitTermination counts at least 100 millis; once the waiting thread is interrupted, the consumer still waits up to 100 millis, so the healthy consumers that a cancelled shutdown task still suspends keep their container. - camel-jms (merge with CAMEL-27534): a startOnResume flag makes the resume after a suspend that gave up create and start a new listener container, also after a failed asynchronous start and with a container created by getListenerContainer() meanwhile; a stop releases only a counted container; a failing stop keeps its exception when the destroy fails too; the private thread pool is released once. - Docs: the Spring RabbitMQ paragraph moved after its example and describes the listener-thread suspend; the bound is per consumer (graceful shutdown page); upgrade guide updated. --- .../apache/camel/catalog/docs/jms-component.adoc | 11 +- .../catalog/docs/spring-rabbitmq-component.adoc | 20 +- .../camel-jms/src/main/docs/jms-component.adoc | 11 +- .../component/jms/EndpointMessageListener.java | 22 ++ .../apache/camel/component/jms/JmsComponent.java | 34 ++ .../apache/camel/component/jms/JmsConsumer.java | 435 +++++++++++---------- ...msConsumerListenerContainerStopTimeoutTest.java | 110 ++++++ .../src/main/docs/spring-rabbitmq-component.adoc | 20 +- .../springrabbit/SpringRabbitMQConsumer.java | 61 ++- .../SpringRabbitMQConsumerStopTest.java | 147 ++++++- .../RabbitMQConsumerSuspendResumeIT.java | 97 +++++ .../ROOT/pages/camel-4x-upgrade-guide-4_24.adoc | 17 +- .../modules/ROOT/pages/graceful-shutdown.adoc | 7 +- 13 files changed, 749 insertions(+), 243 deletions(-) diff --git a/catalog/camel-catalog/src/generated/resources/org/apache/camel/catalog/docs/jms-component.adoc b/catalog/camel-catalog/src/generated/resources/org/apache/camel/catalog/docs/jms-component.adoc index 4814fb5e2e1c..5cb9f927b68b 100644 --- a/catalog/camel-catalog/src/generated/resources/org/apache/camel/catalog/docs/jms-component.adoc +++ b/catalog/camel-catalog/src/generated/resources/org/apache/camel/catalog/docs/jms-component.adoc @@ -1189,13 +1189,20 @@ Suspending or stopping a consumer (for example, when its route or the CamelConte container, which stops its JMS connection. When the broker does not answer, the JMS client may only return from that call once a timeout of its own elapses (the `callTimeout` of ActiveMQ Artemis, 30 seconds by default), and does not react to an interrupt. The consumer waits for its listener container to stop up to the `shutdownAwaitTermination` of -the `ExecutorServiceManager` (10 seconds by default), or until the thread that waits is interrupted (as the graceful -shutdown does when its timeout elapses). It then logs a WARN and no longer uses that listener container: +the `ExecutorServiceManager` (10 seconds by default, at least 100 milliseconds), or until the thread that waits is +interrupted (as the graceful shutdown does when its timeout elapses: then it waits at most 100 milliseconds more). It +then logs a WARN and no longer uses that listener container: the listener container is stopped and destroyed in the background, once the call returns, and the consumer creates a new one when it is resumed or started again. A listener container that is destroyed ends its non-durable topic subscriptions: the messages published to the topic until the new listener container subscribes do not reach the consumer. Use a durable subscription when they must. +A JMS client also stops a connection only once the message listeners that it is calling return. With +`consumerType=Simple` and Spring's `SyncTaskExecutor` as `taskExecutor`, the JMS client calls the route itself: the +consumer then waits as long as the route processes messages, and the time above after the last one. With a thread pool +(the one that Camel creates by default, or one of your own), the route processes the messages on its threads, which the +JMS client does not wait for. + With `asyncStopListener=true`, stopping the consumer does not wait for its listener container. Stopping a route or the CamelContext suspends the consumer first, though (unless the route has `shutdownRoute` set to `Defer`), and the suspend waits as described above. A suspend from the thread that processes a message of the consumer, such as by a route diff --git a/catalog/camel-catalog/src/generated/resources/org/apache/camel/catalog/docs/spring-rabbitmq-component.adoc b/catalog/camel-catalog/src/generated/resources/org/apache/camel/catalog/docs/spring-rabbitmq-component.adoc index c0f1e60beabf..9ca620e0ec50 100644 --- a/catalog/camel-catalog/src/generated/resources/org/apache/camel/catalog/docs/spring-rabbitmq-component.adoc +++ b/catalog/camel-catalog/src/generated/resources/org/apache/camel/catalog/docs/spring-rabbitmq-component.adoc @@ -125,13 +125,6 @@ about 34 seconds with 15 seconds. cancelling a consumer when the route stops, waits until the connection is closed or for up to the `channelRpcTimeout` of the client, 10 minutes by default. -*Suspending or stopping a route.* The consumer stops its listener container, which cancels its consumers and waits -for the broker to answer. The consumer waits for the listener container to stop at most the `shutdownAwaitTermination` -of the `ExecutorServiceManager` (10 seconds by default), so that a broker that does not answer does not hold up the -xref:manual::graceful-shutdown.adoc[graceful shutdown]. When that time elapses, the consumer logs a WARN with the -endpoint and its queues, and returns: the listener container goes on stopping in the background, and is destroyed once -the cancel returns. When the route is resumed or started again, the consumer creates a new listener container. - [source,xml] ---- <bean id="rabbitConnectionFactory" class="org.springframework.amqp.rabbit.connection.CachingConnectionFactory"> @@ -155,6 +148,19 @@ After the connection breaks, the broker requeues the messages that the consumer while the consumer may still process the ones it had already received: expect duplicates after a reconnect, up to `prefetchCount` (250 by default) per consumer. Make the processing idempotent, or lower `prefetchCount`. +*Suspending or stopping a route.* The consumer stops its listener container, which cancels its consumers and waits +for the broker to answer, then waits up to its `shutdownTimeout` (the `shutdownTimeout` of the component, 5 seconds by +default, unless a custom `listenerContainerFactory` sets another one) for the messages that the route is still +processing. A route that suspends its own consumer, such as with a route policy when an exchange is done, waits that +whole `shutdownTimeout`, as the listener container waits for the message that the route is processing; the listener +container then closes the channel of that message, so the broker delivers it again once the route is resumed (unless +it was acknowledged on delivery, with `acknowledgeMode=NONE`). The consumer waits for the listener container to stop +at most the `shutdownTimeout` of the component plus the `shutdownAwaitTermination` of the `ExecutorServiceManager` (10 +seconds by default), so that a broker that does not answer the cancel does not hold up the +xref:manual::graceful-shutdown.adoc[graceful shutdown]. When that time elapses, the consumer logs a WARN with the +endpoint and its queues, and returns: the listener container goes on stopping in the background, and is destroyed once +the cancel returns. When the route is resumed or started again, the consumer creates a new listener container. + === Default Exchange Name To use default exchange name (which would be an empty exchange name in RabbitMQ) then you should use `default` as name diff --git a/components/camel-jms/src/main/docs/jms-component.adoc b/components/camel-jms/src/main/docs/jms-component.adoc index 4814fb5e2e1c..5cb9f927b68b 100644 --- a/components/camel-jms/src/main/docs/jms-component.adoc +++ b/components/camel-jms/src/main/docs/jms-component.adoc @@ -1189,13 +1189,20 @@ Suspending or stopping a consumer (for example, when its route or the CamelConte container, which stops its JMS connection. When the broker does not answer, the JMS client may only return from that call once a timeout of its own elapses (the `callTimeout` of ActiveMQ Artemis, 30 seconds by default), and does not react to an interrupt. The consumer waits for its listener container to stop up to the `shutdownAwaitTermination` of -the `ExecutorServiceManager` (10 seconds by default), or until the thread that waits is interrupted (as the graceful -shutdown does when its timeout elapses). It then logs a WARN and no longer uses that listener container: +the `ExecutorServiceManager` (10 seconds by default, at least 100 milliseconds), or until the thread that waits is +interrupted (as the graceful shutdown does when its timeout elapses: then it waits at most 100 milliseconds more). It +then logs a WARN and no longer uses that listener container: the listener container is stopped and destroyed in the background, once the call returns, and the consumer creates a new one when it is resumed or started again. A listener container that is destroyed ends its non-durable topic subscriptions: the messages published to the topic until the new listener container subscribes do not reach the consumer. Use a durable subscription when they must. +A JMS client also stops a connection only once the message listeners that it is calling return. With +`consumerType=Simple` and Spring's `SyncTaskExecutor` as `taskExecutor`, the JMS client calls the route itself: the +consumer then waits as long as the route processes messages, and the time above after the last one. With a thread pool +(the one that Camel creates by default, or one of your own), the route processes the messages on its threads, which the +JMS client does not wait for. + With `asyncStopListener=true`, stopping the consumer does not wait for its listener container. Stopping a route or the CamelContext suspends the consumer first, though (unless the route has `shutdownRoute` set to `Defer`), and the suspend waits as described above. A suspend from the thread that processes a message of the consumer, such as by a route diff --git a/components/camel-jms/src/main/java/org/apache/camel/component/jms/EndpointMessageListener.java b/components/camel-jms/src/main/java/org/apache/camel/component/jms/EndpointMessageListener.java index c38bebe9528a..b93ebe38a275 100644 --- a/components/camel-jms/src/main/java/org/apache/camel/component/jms/EndpointMessageListener.java +++ b/components/camel-jms/src/main/java/org/apache/camel/component/jms/EndpointMessageListener.java @@ -16,6 +16,8 @@ */ package org.apache.camel.component.jms; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicLong; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; @@ -51,6 +53,9 @@ public class EndpointMessageListener implements SessionAwareMessageListener { // the message listener that processes a message on the current thread private static final ThreadLocal<EndpointMessageListener> CURRENT = new ThreadLocal<>(); private final Lock lock = new ReentrantLock(); + // the messages that this message listener is processing, and has processed + private final AtomicInteger processing = new AtomicInteger(); + private final AtomicLong processed = new AtomicLong(); private final JmsConsumer consumer; private final JmsEndpoint endpoint; private final AsyncProcessor processor; @@ -74,9 +79,12 @@ public class EndpointMessageListener implements SessionAwareMessageListener { // stops the listener container of this message listener on this thread EndpointMessageListener previous = CURRENT.get(); CURRENT.set(this); + processing.incrementAndGet(); try { doOnMessage(message, session); } finally { + processing.decrementAndGet(); + processed.incrementAndGet(); if (previous == null) { CURRENT.remove(); } else { @@ -85,6 +93,20 @@ public class EndpointMessageListener implements SessionAwareMessageListener { } } + /** + * Whether this message listener is processing a message (onMessage did not return yet). + */ + boolean isProcessing() { + return processing.get() > 0; + } + + /** + * The number of messages that this message listener has processed (onMessage returned). + */ + long getProcessed() { + return processed.get(); + } + /** * Whether the current thread processes a message in the given message listener (the message listener of a listener * container). diff --git a/components/camel-jms/src/main/java/org/apache/camel/component/jms/JmsComponent.java b/components/camel-jms/src/main/java/org/apache/camel/component/jms/JmsComponent.java index 91d2f810e8d4..2b56bee17f81 100644 --- a/components/camel-jms/src/main/java/org/apache/camel/component/jms/JmsComponent.java +++ b/components/camel-jms/src/main/java/org/apache/camel/component/jms/JmsComponent.java @@ -61,6 +61,7 @@ public class JmsComponent extends HeaderFilterStrategyComponent { private static final int MAX_CREDENTIALS_CONNECTION_FACTORIES = 100; private ExecutorService asyncStartStopExecutorService; + private ExecutorService stopListenerContainerExecutorService; // the connection factory of the component wrapped with the credentials of the endpoints: one per username, which // other credentials (such as a rotated password) replace private final Map<String, CredentialsConnectionFactory> credentialsConnectionFactories @@ -1206,6 +1207,21 @@ public class JmsComponent extends HeaderFilterStrategyComponent { } } + @Override + protected void doStop() throws Exception { + lock.lock(); + try { + if (stopListenerContainerExecutorService != null) { + // without waiting: the stop of a listener container that waits for the broker goes on in the background + getCamelContext().getExecutorServiceManager().shutdown(stopListenerContainerExecutorService); + stopListenerContainerExecutorService = null; + } + } finally { + lock.unlock(); + } + super.doStop(); + } + @Override protected void doShutdown() throws Exception { if (asyncStartStopExecutorService != null) { @@ -1215,6 +1231,24 @@ public class JmsComponent extends HeaderFilterStrategyComponent { super.doShutdown(); } + /** + * The thread pool that stops the listener containers of the consumers when they are suspended or stopped, so that a + * consumer waits with a bound for a stop that waits for the broker: a cached thread pool, as such a stop can take + * long. + */ + ExecutorService getStopListenerContainerExecutorService() { + lock.lock(); + try { + if (stopListenerContainerExecutorService == null) { + stopListenerContainerExecutorService = getCamelContext().getExecutorServiceManager() + .newCachedThreadPool(this, "JmsStopListenerContainer"); + } + return stopListenerContainerExecutorService; + } finally { + lock.unlock(); + } + } + protected ExecutorService getAsyncStartStopExecutorService() { lock.lock(); try { diff --git a/components/camel-jms/src/main/java/org/apache/camel/component/jms/JmsConsumer.java b/components/camel-jms/src/main/java/org/apache/camel/component/jms/JmsConsumer.java index b632a59112ad..d9bdb7625ba9 100644 --- a/components/camel-jms/src/main/java/org/apache/camel/component/jms/JmsConsumer.java +++ b/components/camel-jms/src/main/java/org/apache/camel/component/jms/JmsConsumer.java @@ -16,10 +16,14 @@ */ package org.apache.camel.component.jms; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.CompletionException; +import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.RejectedExecutionException; import java.util.concurrent.TimeUnit; -import java.util.concurrent.locks.Condition; +import java.util.concurrent.TimeoutException; +import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; @@ -28,12 +32,14 @@ import jakarta.jms.ConnectionFactory; import org.apache.camel.FailedToCreateConsumerException; import org.apache.camel.Processor; +import org.apache.camel.RuntimeCamelException; import org.apache.camel.Suspendable; import org.apache.camel.api.management.ManagedAttribute; import org.apache.camel.api.management.ManagedResource; import org.apache.camel.support.DefaultConsumer; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import org.springframework.core.task.SyncTaskExecutor; import org.springframework.jms.listener.AbstractMessageListenerContainer; import org.springframework.jms.listener.DefaultMessageListenerContainer; import org.springframework.jms.listener.SimpleMessageListenerContainer; @@ -50,6 +56,8 @@ import org.springframework.jms.support.JmsUtils; public class JmsConsumer extends DefaultConsumer implements Suspendable { private static final Logger LOG = LoggerFactory.getLogger(JmsConsumer.class); + // the least time to wait for a listener container to stop (also once the waiting thread is interrupted) + private static final long MIN_STOP_WAIT = 100; private volatile AbstractMessageListenerContainer listenerContainer; private volatile EndpointMessageListener messageListener; @@ -64,6 +72,9 @@ public class JmsConsumer extends DefaultConsumer implements Suspendable { // guarded by containerLock: an asynchronous start task of the current listener container has not checked the // status of the consumer yet private boolean asyncStartPending; + // guarded by containerLock: a suspend gave up waiting for the listener container that this consumer had started, + // so a resume starts the next one (also without auto startup), as it starts the one a suspend keeps + private boolean startOnResume; public JmsConsumer(JmsEndpoint endpoint, Processor processor, AbstractMessageListenerContainer listenerContainer) { super(endpoint, processor); @@ -328,6 +339,7 @@ public class JmsConsumer extends DefaultConsumer implements Suspendable { containerLock.lock(); try { if (listenerContainer == container) { + startOnResume = false; if (start && isSuspendingOrSuspended()) { // suspended while this task was starting the container, and doSuspend may have run before // container.start(): stop it here. Under the lock, so a resume that follows reads initialized @@ -371,6 +383,7 @@ public class JmsConsumer extends DefaultConsumer implements Suspendable { try { // a later start creates the listener container, and starts it, as the first start did initialized = false; + startOnResume = false; return doDetachListenerContainer(); } finally { containerLock.unlock(); @@ -378,14 +391,19 @@ public class JmsConsumer extends DefaultConsumer implements Suspendable { } /** - * Takes the given listener container away from this consumer, when its stop for a suspend did not end in time. The - * consumer stays initialized: a resume creates a new listener container and starts it, as it starts the one it - * keeps after a suspend that ended in time. + * Takes the given listener container away from this consumer, when its stop for a suspend did not end in time. A + * resume creates a new listener container, and starts it when this one was started (also without auto startup), as + * it starts the one it keeps after a suspend that ended in time. */ private DetachedListenerContainer detachSuspendedListenerContainer(AbstractMessageListenerContainer container) { containerLock.lock(); try { - return listenerContainer == container ? doDetachListenerContainer() : null; + if (listenerContainer != container) { + return null; + } + startOnResume = startOnResume || initialized; + initialized = false; + return doDetachListenerContainer(); } finally { containerLock.unlock(); } @@ -396,7 +414,8 @@ public class JmsConsumer extends DefaultConsumer implements Suspendable { if (container == null) { return null; } - DetachedListenerContainer answer = new DetachedListenerContainer(container, executorService, shutdownExecutorService); + DetachedListenerContainer answer = new DetachedListenerContainer( + container, executorService, shutdownExecutorService, listenerContainerCounted, new AtomicBoolean()); // null container and listener so they are fully re created if this consumer is restarted // then we will use updated configuration from jms endpoint that may have been managed using JMX listenerContainer = null; @@ -412,81 +431,235 @@ public class JmsConsumer extends DefaultConsumer implements Suspendable { private void stopAndDestroyListenerContainer(DetachedListenerContainer detached) { try { detached.container().stop(); - } finally { - // also when stop fails (a SimpleMessageListenerContainer does not swallow a failing Connection.stop()) - destroyListenerContainer(detached); + } catch (RuntimeException | Error e) { + // also when stop fails (a SimpleMessageListenerContainer does not swallow a failing Connection.stop()), + // and the failure of the stop is the one thrown + try { + destroyListenerContainer(detached); + } catch (RuntimeException | Error destroyFailure) { + if (destroyFailure != e) { + e.addSuppressed(destroyFailure); + } + } + throw e; } + destroyListenerContainer(detached); } private void destroyListenerContainer(DetachedListenerContainer detached) { try { detached.container().destroy(); } finally { - getEndpoint().onListenerContainerStopped(); + if (detached.counted()) { + getEndpoint().onListenerContainerStopped(); + } // shutdown thread pool if listener container was using a private thread pool ExecutorService pool = detached.executorService(); if (detached.shutdownExecutorService() && pool != null) { - if (pool.isShutdown()) { - // shut down (and so no longer managed) when the consumer gave up waiting for the stop - pool.shutdownNow(); - } else { + if (detached.poolReleased().compareAndSet(false, true)) { getEndpoint().getCamelContext().getExecutorServiceManager().shutdownNow(pool); + } else { + // released (and so no longer managed) when the consumer gave up waiting for the stop + pool.shutdownNow(); } } } } /** - * Runs the stop of a listener container on the async start/stop thread pool of the component, and waits for it at - * most the time to wait for a thread pool to shut down + * Stops the listener container for a suspend, or stops and destroys the one that a stop of this consumer detached, + * on a thread of the component, and waits for it at most the time to wait for a thread pool to shut down * ({@code ExecutorServiceManager.getShutdownAwaitTermination()}, 10 seconds by default). * <p/> * The stop of a listener container stops its JMS connection, and a JMS client may not return from that call before * a timeout of its own elapses when the broker does not answer (the call timeout of ActiveMQ Artemis, 30 seconds by * default), whether the thread is interrupted or not. When the wait ends before the stop (the time elapsed, or the - * waiting thread was interrupted), the listener container is no longer used by this consumer, and its stop goes on - * in the background: see {@link ListenerContainerStop}. + * waiting thread was interrupted), the listener container is no longer used by this consumer: its stop goes on in + * the background, and it is destroyed once it stopped. * <p/> - * A suspend or stop from a thread that processes a message of the listener container (such as a route policy that - * suspends the consumer when an exchange is done) stops the listener container on that thread, as before: a JMS - * client stops a connection at once from its own message listener, but waits for that message listener from another - * thread. + * A JMS client also stops a connection only once the message listeners it is calling return: with a simple listener + * container and a {@link SyncTaskExecutor}, that is the route. So the consumer then waits as long as the listener + * container processes messages, and the time above after the last one. A suspend or stop from a thread that + * processes a message of the listener container (such as a route policy that suspends the consumer when an exchange + * is done) stops the listener container on that thread, as before: a JMS client does not wait for its own message + * listener there (ActiveMQ Artemis refuses the call, which the listener container ignores), but waits for that + * message listener from another thread. * * @param operation the operation of this consumer that stops the listener container, for the log + * @param container the listener container + * @param detached for a stop of this consumer: the listener container it detached, to stop and destroy (null for a + * suspend) */ - private void stopWithinBound(String operation, ListenerContainerStop stop) { - long timeout = getEndpoint().getCamelContext().getExecutorServiceManager().getShutdownAwaitTermination(); - if (EndpointMessageListener.isProcessingOnCurrentThread(stop.container.getMessageListener()) - || !runInBackground(stop)) { + private void stopWithinBound( + String operation, AbstractMessageListenerContainer container, DetachedListenerContainer detached) { + Runnable stop = detached != null ? () -> stopAndDestroyListenerContainer(detached) : container::stop; + if (EndpointMessageListener.isProcessingOnCurrentThread(container.getMessageListener()) + || getEndpoint().getComponent() == null) { // from the message listener, or no thread pool to run the stop on: stop the listener container on this thread stop.run(); + return; + } + // whether this thread still waits for the stop: the first of the two that sets it to false (this thread when it + // gives up waiting, or the stop when it ends) completes the stop + AtomicBoolean waiting = new AtomicBoolean(true); + // for a suspend: the listener container that this thread detached when it gave up waiting, which the stop + // destroys once it returns + CompletableFuture<DetachedListenerContainer> givenUp = new CompletableFuture<>(); + CompletableFuture<Void> future; + try { + future = CompletableFuture.runAsync(() -> stopInBackground(container, stop, waiting, givenUp), + getEndpoint().getComponent().getStopListenerContainerExecutorService()); + } catch (RejectedExecutionException e) { + // the component stopped meanwhile: as before, on this thread + stop.run(); + return; + } + + String reason = awaitStop(future, container); + if (reason == null) { + return; + } + if (!waiting.compareAndSet(true, false)) { + // the stop ended meanwhile + joinStop(future); + return; } - String reason = stop.await(timeout); - if (reason != null) { - LOG.warn("The {} of the consumer on destination {} {}: the JMS client may be waiting for a broker that does" - + " not answer. The listener container is stopped and destroyed in the background, and the consumer" - + " creates a new one when it is resumed or started again.", - operation, getDestinationName(stop.container), reason); - DetachedListenerContainer detached = stop.givenUpContainer(); - if (detached != null && detached.shutdownExecutorService() && detached.executorService() != null) { + DetachedListenerContainer abandoned = null; + try { + // a suspend that did not end in time: this consumer no longer uses the listener container + abandoned = detached != null ? detached : detachSuspendedListenerContainer(container); + if (abandoned != null && abandoned.shutdownExecutorService() && abandoned.executorService() != null + && abandoned.poolReleased().compareAndSet(false, true)) { // the threads of its private thread pool end once the listener container is destroyed: the pool takes // no new task, and the ExecutorServiceManager no longer waits for it when the CamelContext stops - getEndpoint().getCamelContext().getExecutorServiceManager().shutdown(detached.executorService()); + getEndpoint().getCamelContext().getExecutorServiceManager().shutdown(abandoned.executorService()); } + } finally { + givenUp.complete(detached != null ? null : abandoned); } + LOG.warn("The {} of the consumer on destination {} {}: the JMS client may be waiting for a broker that does not" + + " answer. The listener container is stopped and destroyed in the background, and the consumer creates a" + + " new one when it is resumed or started again.", + operation, getDestinationName(container), reason); } - private boolean runInBackground(Runnable task) { - if (getEndpoint().getComponent() == null) { - return false; + /** + * Waits for the stop at most the time to wait for a thread pool to shut down, after the time a simple listener + * container processes messages. Once the waiting thread is interrupted (such as by the graceful shutdown when its + * timeout elapses), it waits at most {@link #MIN_STOP_WAIT} more: a listener container that is about to stop (the + * broker answers) still stops in time, also for the consumers that the shutdown suspends after this one. + * + * @return null when the stop ended in time (when it failed, its exception is thrown), otherwise why this consumer + * gives up waiting + */ + private String awaitStop(CompletableFuture<Void> stop, AbstractMessageListenerContainer container) { + long timeout = Math.max(MIN_STOP_WAIT, + getEndpoint().getCamelContext().getExecutorServiceManager().getShutdownAwaitTermination()); + boolean interrupted = false; + EndpointMessageListener listener = getListenerCalledByTheJmsClient(container); + // the messages processed when the wait started, or when the previous wait elapsed: a message processed meanwhile + // gives the full time once more, as the stop may only start once the last message is processed + long processed = listener != null ? listener.getProcessed() : 0; + try { + while (true) { + try { + stop.get(timeout, TimeUnit.MILLISECONDS); + return null; + } catch (TimeoutException e) { + if (listener == null || !listener.isProcessing() && listener.getProcessed() == processed) { + return "did not end within " + timeout + " millis, as its listener container did not stop"; + } + processed = listener.getProcessed(); + LOG.debug("Waiting for the listener container on destination {} to stop: it processes messages", + getDestinationName(container)); + } + } + } catch (ExecutionException e) { + throw stopFailure(e.getCause()); + } catch (InterruptedException e) { + interrupted = true; + try { + stop.get(MIN_STOP_WAIT, TimeUnit.MILLISECONDS); + return null; + } catch (ExecutionException failure) { + throw stopFailure(failure.getCause()); + } catch (TimeoutException | InterruptedException again) { + return "was interrupted before its listener container stopped"; + } + } finally { + if (interrupted) { + Thread.currentThread().interrupt(); + } } + } + + /** + * The message listener of the listener container when the JMS client calls the route itself, and so stops the + * connection only once the route returns: a simple listener container with a synchronous task executor. With a + * thread pool (the one that Camel creates by default, or one of the application), the route runs on its threads, + * which the JMS client does not wait for. + */ + private EndpointMessageListener getListenerCalledByTheJmsClient(AbstractMessageListenerContainer container) { + if (container instanceof SimpleMessageListenerContainer + && getEndpoint().getConfiguration().getTaskExecutor() instanceof SyncTaskExecutor + && container.getMessageListener() instanceof EndpointMessageListener listener) { + return listener; + } + return null; + } + + /** + * The stop that runs on a thread of the component. When this consumer gave up waiting for it, it logs its failure, + * and for a suspend destroys the listener container once it stopped. + */ + private void stopInBackground( + AbstractMessageListenerContainer container, Runnable stop, AtomicBoolean waiting, + CompletableFuture<DetachedListenerContainer> givenUp) { + Throwable failure = null; try { - getEndpoint().getAsyncStartStopExecutorService().execute(task); - return true; - } catch (RejectedExecutionException e) { - LOG.debug("Cannot run the task {} on the async start/stop thread pool: it runs on this thread", task, e); - return false; + stop.run(); + } catch (RuntimeException | Error e) { + failure = e; + } + if (waiting.compareAndSet(true, false)) { + // this consumer waits for the stop: it gets the failure unchanged, as from a stop on its own thread + if (failure instanceof RuntimeException e) { + throw e; + } else if (failure instanceof Error e) { + throw e; + } + return; + } + if (failure != null) { + LOG.warn("Error stopping listener container on destination: {} in the background. This exception will be ignored.", + getDestinationName(container), failure); + } + // handed over by this consumer once it detached it + DetachedListenerContainer suspended = givenUp.join(); + if (suspended != null) { + try { + destroyListenerContainer(suspended); + } catch (RuntimeException | Error e) { + LOG.warn("Error destroying listener container on destination: {} in the background. This exception will be" + + " ignored.", + getDestinationName(container), e); + } + } + } + + private static void joinStop(CompletableFuture<Void> stop) { + try { + stop.join(); + } catch (CompletionException e) { + throw stopFailure(e.getCause()); + } + } + + private static RuntimeException stopFailure(Throwable cause) { + if (cause instanceof Error error) { + throw error; } + return RuntimeCamelException.wrapRuntimeException(cause); } @Override @@ -511,7 +684,7 @@ public class JmsConsumer extends DefaultConsumer implements Suspendable { } }); } else { - stopWithinBound("stop", new ListenerContainerStop(detached)); + stopWithinBound("stop", detached.container(), detached); } } @@ -522,7 +695,7 @@ public class JmsConsumer extends DefaultConsumer implements Suspendable { protected void doSuspend() throws Exception { AbstractMessageListenerContainer container = listenerContainer; if (container != null) { - stopWithinBound("suspend", new ListenerContainerStop(container)); + stopWithinBound("suspend", container, null); } } @@ -531,6 +704,7 @@ public class JmsConsumer extends DefaultConsumer implements Suspendable { final AbstractMessageListenerContainer container; final boolean wasInitialized; final boolean startAgain; + final boolean start; containerLock.lock(); try { container = listenerContainer; @@ -546,11 +720,7 @@ public class JmsConsumer extends DefaultConsumer implements Suspendable { // the listener container was started and counted before, but its start failed (for example // testConnectionOnStartup with asyncStartListener=true) startAgain = !wasInitialized && listenerContainerCounted; - if (wasInitialized && container == null) { - // a suspend that did not end in time took the listener container away from this consumer. The new - // one is initialized by its (possibly asynchronous) start, as at the first start - initialized = false; - } + start = startOnResume; } finally { containerLock.unlock(); } @@ -559,7 +729,12 @@ public class JmsConsumer extends DefaultConsumer implements Suspendable { // start the same listener container again: it is already counted as running on the endpoint LOG.info("Starting listener container on destination {} again, as its earlier start did not complete", getDestinationName(container)); - prepareAndStartListenerContainer(container, getEndpoint().getConfiguration().isAsyncStartListener(), false); + prepareAndStartListenerContainer(container, getEndpoint().getConfiguration().isAsyncStartListener(), start); + } else if (!wasInitialized && start) { + // a suspend that did not end in time took the listener container away from this consumer: create a new one + // (unless created meanwhile), and start it as the resume starts the listener container that a suspend that + // ends in time keeps (also without auto startup) + createAndStartListenerContainer(true); } else if (!wasInitialized) { // we may not have been started before, and now the end user calls resume, so lets handle that and start it first doStart(); @@ -568,9 +743,7 @@ public class JmsConsumer extends DefaultConsumer implements Suspendable { // stopped it after the task's start() startListenerContainer(container); } else { - // create a new listener container, and start it as the resume starts the listener container that a suspend - // that ends in time keeps (also without auto startup) - createAndStartListenerContainer(true); + LOG.warn("The listener container of the consumer of {} is not instantiated: restart the route", getEndpoint()); } } @@ -616,157 +789,13 @@ public class JmsConsumer extends DefaultConsumer implements Suspendable { /** * A listener container detached from this consumer by a stop, or by a suspend that did not end in time, with the * private thread pool it uses (if any). + * + * @param counted whether the start of this consumer counted it as running on the endpoint (not one that + * {@link #getListenerContainer()} created while the consumer had none) + * @param poolReleased whether its private thread pool was handed back to the ExecutorServiceManager */ private record DetachedListenerContainer(AbstractMessageListenerContainer container, ExecutorService executorService, - boolean shutdownExecutorService) { - } - - /** - * The stop of a listener container (for a suspend), or its stop and destroy (for a stop of this consumer, which - * detached it already), which this consumer waits for at most a given time. - * <p/> - * When the consumer gives up waiting, the stop goes on in the background. For a suspend, the consumer detaches the - * listener container: a resume (or a start) creates a new one, and the listener container is destroyed once its - * stop returns. Its private thread pool takes no new task from the time the consumer gives up, and is shut down - * once the listener container is destroyed. An exception of the stop is then logged, as nobody waits for it - * anymore. - */ - private final class ListenerContainerStop implements Runnable { - - private final AbstractMessageListenerContainer container; - // for a stop of the consumer: the listener container it detached, to stop and destroy (null for a suspend) - private final DetachedListenerContainer stopped; - private final Lock lock = new ReentrantLock(); - private final Condition ended = lock.newCondition(); - // guarded by lock - private boolean done; - private boolean givenUp; - // a RuntimeException or an Error - private Throwable failure; - // for a suspend: the listener container the consumer detached when it gave up waiting, to destroy once stopped - private DetachedListenerContainer suspended; - - /** - * The stop of the listener container, for a suspend. - */ - ListenerContainerStop(AbstractMessageListenerContainer container) { - this.container = container; - this.stopped = null; - } - - /** - * The stop and destroy of the detached listener container, for a stop of the consumer. - */ - ListenerContainerStop(DetachedListenerContainer detached) { - this.container = detached.container(); - this.stopped = detached; - } - - @Override - public void run() { - Throwable error = null; - try { - if (stopped != null) { - stopAndDestroyListenerContainer(stopped); - } else { - container.stop(); - } - } catch (RuntimeException | Error e) { - // handed over to the consumer, as the stop of the listener container on its own thread would - error = e; - } - DetachedListenerContainer toDestroy; - lock.lock(); - try { - done = true; - failure = error; - ended.signalAll(); - if (!givenUp) { - // the consumer gets the outcome - return; - } - toDestroy = suspended; - } finally { - lock.unlock(); - } - if (error != null) { - LOG.warn("Error stopping listener container on destination: {} in the background." - + " This exception will be ignored.", - getDestinationName(container), error); - } - if (toDestroy != null) { - try { - destroyListenerContainer(toDestroy); - } catch (RuntimeException | Error e) { - LOG.warn("Error destroying listener container on destination: {} in the background." - + " This exception will be ignored.", - getDestinationName(container), e); - } - } - } - - /** - * Waits for the stop at most the given time. When the stop ended in time and failed, its exception is thrown. - * - * @return <tt>null</tt> when the stop ended in time, otherwise why the consumer gave up waiting - */ - String await(long timeout) { - boolean interrupted = false; - lock.lock(); - try { - long nanos = TimeUnit.MILLISECONDS.toNanos(timeout); - while (!done && nanos > 0) { - try { - nanos = ended.awaitNanos(nanos); - } catch (InterruptedException e) { - // such as the graceful shutdown when its timeout elapses: stop waiting - interrupted = true; - break; - } - } - if (done) { - if (failure instanceof Error error) { - throw error; - } else if (failure != null) { - throw (RuntimeException) failure; - } - return null; - } - givenUp = true; - if (stopped == null) { - // the suspend did not end in time: this consumer no longer uses the listener container - suspended = detachSuspendedListenerContainer(container); - } - return interrupted - ? "was interrupted before its listener container stopped" - : "did not end within " + timeout + " millis, as its listener container did not stop"; - } finally { - lock.unlock(); - if (interrupted) { - Thread.currentThread().interrupt(); - } - } - } - - /** - * The listener container that this consumer gave up waiting for, which is destroyed in the background. - */ - DetachedListenerContainer givenUpContainer() { - lock.lock(); - try { - if (!givenUp) { - return null; - } - return stopped != null ? stopped : suspended; - } finally { - lock.unlock(); - } - } - - @Override - public String toString() { - return (stopped != null ? "StopListenerTask[" : "SuspendListenerTask[") + getDestinationName(container) + "]"; - } + boolean shutdownExecutorService, boolean counted, AtomicBoolean poolReleased) { } } diff --git a/components/camel-jms/src/test/java/org/apache/camel/component/jms/JmsConsumerListenerContainerStopTimeoutTest.java b/components/camel-jms/src/test/java/org/apache/camel/component/jms/JmsConsumerListenerContainerStopTimeoutTest.java index 76a975f0b46b..95fbe705b403 100644 --- a/components/camel-jms/src/test/java/org/apache/camel/component/jms/JmsConsumerListenerContainerStopTimeoutTest.java +++ b/components/camel-jms/src/test/java/org/apache/camel/component/jms/JmsConsumerListenerContainerStopTimeoutTest.java @@ -229,6 +229,58 @@ public class JmsConsumerListenerContainerStopTimeoutTest { assertConsumedOnce("Hello again"); } + /** + * A listener container that the getter creates while the consumer has none, as a management tool reading it would, + * is initialized, counted and started by the resume, and its stop releases only what was counted. + */ + @Test + public void testResumeAfterASuspendThatDidNotEndUsesTheListenerContainerCreatedMeanwhile() throws Exception { + BlockingListenerContainer first = containers.get(0); + JmsEndpoint endpoint = endpoint(); + block = Block.STOP; + assertReturns("the suspend of the route", () -> { + context.getRouteController().suspendRoute("jms"); + return null; + }); + assertWarning("The suspend of the consumer on destination " + queue + " did not end within " + BOUND + " millis"); + AbstractMessageListenerContainer created = consumer().getListenerContainer(); + block = Block.NONE; + + context.getRouteController().resumeRoute("jms"); + + assertSame(created, consumer().getListenerContainer(), "the resume uses the listener container created meanwhile"); + assertTrue(created.isRunning(), "the listener container runs"); + assertConsumedOnce("Bye World"); + release.countDown(); + await().atMost(10, TimeUnit.SECONDS).until(() -> first.destroyed && endpoint.getRunningMessageListeners() == 1); + + context.getRouteController().stopRoute("jms"); + + assertEquals(0, endpoint.getRunningMessageListeners()); + } + + @Test + public void testStopAfterASuspendThatDidNotEndReleasesOnlyWhatWasCounted() throws Exception { + BlockingListenerContainer first = containers.get(0); + JmsEndpoint endpoint = endpoint(); + block = Block.STOP; + assertReturns("the suspend of the route", () -> { + context.getRouteController().suspendRoute("jms"); + return null; + }); + consumer().getListenerContainer(); + block = Block.NONE; + + context.getRouteController().stopRoute("jms"); + release.countDown(); + + // the private thread pool terminates once the endpoint count is released + await().atMost(10, TimeUnit.SECONDS).until(() -> first.destroyed && first.taskExecutor.isTerminated()); + await().atMost(10, TimeUnit.SECONDS) + .until(() -> containers.get(1).destroyed && containers.get(1).taskExecutor.isTerminated()); + assertEquals(0, endpoint.getRunningMessageListeners(), "the listener container created meanwhile was not counted"); + } + @Test public void testStartAfterAStopThatDidNotEndCreatesANewListenerContainer() throws Exception { assertConsumedOnce("Hello World"); @@ -416,6 +468,64 @@ public class JmsConsumerListenerContainerStopTimeoutTest { assertEquals(List.of(), warnings, "no WARN"); } + /** + * A suspend from another thread while the route processes a message, with a simple listener container and a + * synchronous task executor: the JMS client calls the route, and stops the connection once the route returns. The + * suspend waits as long as the message is processed, and the bound after that. + */ + @Test + public void testSuspendWaitsForTheMessageThatTheJmsClientProcesses() throws Exception { + context.getRegistry().bind("syncTaskExecutor", new SyncTaskExecutor()); + String slowQueue = queue + ".slow"; + CountDownLatch processing = new CountDownLatch(1); + CountDownLatch done = new CountDownLatch(1); + context.addRoutes(new RouteBuilder() { + @Override + public void configure() { + from("jms:queue:" + slowQueue + "?consumerType=Simple&taskExecutor=#syncTaskExecutor").routeId("slow") + .process(exchange -> { + processing.countDown(); + done.await(20, TimeUnit.SECONDS); + }) + .to("mock:slow"); + } + }); + JmsConsumer consumer = (JmsConsumer) context.getRoute("slow").getConsumer(); + AbstractMessageListenerContainer container = consumer.getListenerContainer(); + MockEndpoint slow = MockEndpoint.resolve(context, "mock:slow"); + slow.expectedBodiesReceived("Hello World"); + template.sendBody("jms:queue:" + slowQueue, "Hello World"); + assertTrue(processing.await(10, TimeUnit.SECONDS), "the route processes the message"); + + Future<?> suspend = caller.submit(consumer::suspend); + await().atMost(10, TimeUnit.SECONDS).until(consumer::isSuspending); + + // past the bound, the suspend still waits for the message + await().during(2 * BOUND, TimeUnit.MILLISECONDS).atMost(3 * BOUND, TimeUnit.MILLISECONDS) + .until(() -> !suspend.isDone()); + done.countDown(); + suspend.get(10, TimeUnit.SECONDS); + MockEndpoint.assertIsSatisfied(context); + assertTrue(consumer.isSuspended(), "the consumer is suspended"); + assertSame(container, consumer.getListenerContainer(), "the suspended consumer keeps its listener container"); + List<String> warnings = events.stream().filter(e -> e.getLevel() == Level.WARN) + .map(e -> e.getMessage().getFormattedMessage()).filter(m -> m.contains(slowQueue)).toList(); + assertEquals(List.of(), warnings, "no WARN"); + } + + @Test + public void testShutdownAwaitTerminationOfZeroWaitsTheLeastTime() throws Exception { + context.getExecutorServiceManager().setShutdownAwaitTermination(0); + block = Block.STOP; + + assertReturns("the suspend of the route", () -> { + context.getRouteController().suspendRoute("jms"); + return null; + }); + + assertWarning("The suspend of the consumer on destination " + queue + " did not end within 100 millis"); + } + /** * Suspends the route, waiting for the listener container as long as by default (10 seconds), so that only the stop * that follows, which the test blocks, has the short time limit of the test. diff --git a/components/camel-spring-parent/camel-spring-rabbitmq/src/main/docs/spring-rabbitmq-component.adoc b/components/camel-spring-parent/camel-spring-rabbitmq/src/main/docs/spring-rabbitmq-component.adoc index c0f1e60beabf..9ca620e0ec50 100644 --- a/components/camel-spring-parent/camel-spring-rabbitmq/src/main/docs/spring-rabbitmq-component.adoc +++ b/components/camel-spring-parent/camel-spring-rabbitmq/src/main/docs/spring-rabbitmq-component.adoc @@ -125,13 +125,6 @@ about 34 seconds with 15 seconds. cancelling a consumer when the route stops, waits until the connection is closed or for up to the `channelRpcTimeout` of the client, 10 minutes by default. -*Suspending or stopping a route.* The consumer stops its listener container, which cancels its consumers and waits -for the broker to answer. The consumer waits for the listener container to stop at most the `shutdownAwaitTermination` -of the `ExecutorServiceManager` (10 seconds by default), so that a broker that does not answer does not hold up the -xref:manual::graceful-shutdown.adoc[graceful shutdown]. When that time elapses, the consumer logs a WARN with the -endpoint and its queues, and returns: the listener container goes on stopping in the background, and is destroyed once -the cancel returns. When the route is resumed or started again, the consumer creates a new listener container. - [source,xml] ---- <bean id="rabbitConnectionFactory" class="org.springframework.amqp.rabbit.connection.CachingConnectionFactory"> @@ -155,6 +148,19 @@ After the connection breaks, the broker requeues the messages that the consumer while the consumer may still process the ones it had already received: expect duplicates after a reconnect, up to `prefetchCount` (250 by default) per consumer. Make the processing idempotent, or lower `prefetchCount`. +*Suspending or stopping a route.* The consumer stops its listener container, which cancels its consumers and waits +for the broker to answer, then waits up to its `shutdownTimeout` (the `shutdownTimeout` of the component, 5 seconds by +default, unless a custom `listenerContainerFactory` sets another one) for the messages that the route is still +processing. A route that suspends its own consumer, such as with a route policy when an exchange is done, waits that +whole `shutdownTimeout`, as the listener container waits for the message that the route is processing; the listener +container then closes the channel of that message, so the broker delivers it again once the route is resumed (unless +it was acknowledged on delivery, with `acknowledgeMode=NONE`). The consumer waits for the listener container to stop +at most the `shutdownTimeout` of the component plus the `shutdownAwaitTermination` of the `ExecutorServiceManager` (10 +seconds by default), so that a broker that does not answer the cancel does not hold up the +xref:manual::graceful-shutdown.adoc[graceful shutdown]. When that time elapses, the consumer logs a WARN with the +endpoint and its queues, and returns: the listener container goes on stopping in the background, and is destroyed once +the cancel returns. When the route is resumed or started again, the consumer creates a new listener container. + === Default Exchange Name To use default exchange name (which would be an empty exchange name in RabbitMQ) then you should use `default` as name diff --git a/components/camel-spring-parent/camel-spring-rabbitmq/src/main/java/org/apache/camel/component/springrabbit/SpringRabbitMQConsumer.java b/components/camel-spring-parent/camel-spring-rabbitmq/src/main/java/org/apache/camel/component/springrabbit/SpringRabbitMQConsumer.java index e585868eecf3..4f79aa74a5f8 100644 --- a/components/camel-spring-parent/camel-spring-rabbitmq/src/main/java/org/apache/camel/component/springrabbit/SpringRabbitMQConsumer.java +++ b/components/camel-spring-parent/camel-spring-rabbitmq/src/main/java/org/apache/camel/component/springrabbit/SpringRabbitMQConsumer.java @@ -44,6 +44,8 @@ import org.springframework.amqp.rabbit.listener.AbstractMessageListenerContainer public class SpringRabbitMQConsumer extends DefaultConsumer implements Suspendable { private static final Logger LOG = LoggerFactory.getLogger(SpringRabbitMQConsumer.class); + // the least time to wait for a listener container to stop (also once the waiting thread is interrupted) + private static final long MIN_STOP_WAIT = 100; private volatile AbstractMessageListenerContainer listenerContainer; private volatile EndpointMessageListener messageListener; @@ -269,14 +271,20 @@ public class SpringRabbitMQConsumer extends DefaultConsumer implements Suspendab } /** - * Stops the listener container (and destroys it when asked), waiting for it at most the time to wait for a thread - * pool to shut down ({@code ExecutorServiceManager.getShutdownAwaitTermination()}, 10 seconds by default). + * Stops the listener container (and destroys it when asked), waiting for it at most the {@code shutdownTimeout} of + * the component (the time the listener container waits for the messages it is processing, 5 seconds by default) + * plus the time to wait for a thread pool to shut down + * ({@code ExecutorServiceManager.getShutdownAwaitTermination()}, 10 seconds by default). * <p/> * The stop of a listener container cancels its consumers (basic.cancel) and waits for the broker to answer, without * reacting to an interrupt: on a connection that stopped answering, up to the {@code channelRpcTimeout} of the * RabbitMQ client (10 minutes by default) or until the heartbeat closes the connection. So the stop runs on a * thread of the component: when the bound elapses, or the waiting thread is interrupted, it goes on in the * background, and destroys the listener container once it returns. + * <p/> + * A stop from a thread that processes a message of the listener container (such as a route policy that suspends the + * consumer when an exchange is done) runs on a thread of the component too: the listener container waits up to its + * {@code shutdownTimeout} for that message, from whichever thread it is stopped. * * @param container the listener container, which the caller detaches from this consumer when it stops in the * background @@ -285,7 +293,11 @@ public class SpringRabbitMQConsumer extends DefaultConsumer implements Suspendab * background */ private boolean stopListenerContainer(AbstractMessageListenerContainer container, boolean destroy) { - long timeout = getEndpoint().getCamelContext().getExecutorServiceManager().getShutdownAwaitTermination(); + long awaitTermination = Math.max(MIN_STOP_WAIT, + getEndpoint().getCamelContext().getExecutorServiceManager().getShutdownAwaitTermination()); + long shutdownTimeout = Math.max(0, getEndpoint().getComponent().getShutdownTimeout()); + long timeout + = shutdownTimeout > Long.MAX_VALUE - awaitTermination ? Long.MAX_VALUE : shutdownTimeout + awaitTermination; // whether this thread still waits for the stop: the first of the two that sets it to false (this thread when it // stops waiting, or the stop when it ends) completes the stop AtomicBoolean waiting = new AtomicBoolean(true); @@ -299,6 +311,7 @@ public class SpringRabbitMQConsumer extends DefaultConsumer implements Suspendab return true; } + boolean interrupted = false; try { stop.get(timeout, TimeUnit.MILLISECONDS); return true; @@ -306,16 +319,23 @@ public class SpringRabbitMQConsumer extends DefaultConsumer implements Suspendab throw stopFailure(e.getCause()); } catch (TimeoutException e) { if (waiting.compareAndSet(true, false)) { - LOG.warn("The listener container of {} (queues: {}) did not stop within {} millis (the" - + " shutdownAwaitTermination of the ExecutorServiceManager): it may wait for the broker to answer" - + " the cancel of its consumers, on a connection that stopped answering. It stops in the" - + " background, and the consumer creates a new listener container when it is resumed or started" - + " again.", - getEndpoint(), Arrays.toString(container.getQueueNames()), timeout); + LOG.warn("The listener container of {} (queues: {}) did not stop within {} millis (the shutdownTimeout of" + + " the component, {} millis, plus the shutdownAwaitTermination of the ExecutorServiceManager, {}" + + " millis): it may wait for the broker to answer the cancel of its consumers, on a connection" + + " that stopped answering. It stops in the background, and the consumer creates a new listener" + + " container when it is resumed or started again.", + getEndpoint(), Arrays.toString(container.getQueueNames()), timeout, shutdownTimeout, + awaitTermination); return false; } } catch (InterruptedException e) { - Thread.currentThread().interrupt(); + // such as the graceful shutdown when its timeout elapses. A listener container that is about to stop (the + // broker answers) still stops in time, so that the consumers that the shutdown suspends after this one do + // not all give up at once + interrupted = true; + if (awaitAfterInterrupt(stop)) { + return true; + } if (waiting.compareAndSet(true, false)) { LOG.warn("Interrupted while waiting for the listener container of {} (queues: {}) to stop. It stops in" + " the background, and the consumer creates a new listener container when it is resumed or" @@ -323,6 +343,10 @@ public class SpringRabbitMQConsumer extends DefaultConsumer implements Suspendab getEndpoint(), Arrays.toString(container.getQueueNames())); return false; } + } finally { + if (interrupted) { + Thread.currentThread().interrupt(); + } } // the stop ended meanwhile try { @@ -333,6 +357,23 @@ public class SpringRabbitMQConsumer extends DefaultConsumer implements Suspendab return true; } + /** + * Waits for the stop at most {@link #MIN_STOP_WAIT} more, once the waiting thread was interrupted (which cleared + * its interrupt status: the caller sets it again). + * + * @return whether the stop ended meanwhile; when it failed, its exception is thrown + */ + private static boolean awaitAfterInterrupt(CompletableFuture<Void> stop) { + try { + stop.get(MIN_STOP_WAIT, TimeUnit.MILLISECONDS); + return true; + } catch (ExecutionException e) { + throw stopFailure(e.getCause()); + } catch (TimeoutException | InterruptedException e) { + return false; + } + } + /** * The stop that runs on a thread of the component. When nobody waits for it anymore, it destroys the listener * container and logs the outcome by itself, also when the stop fails with an error. diff --git a/components/camel-spring-parent/camel-spring-rabbitmq/src/test/java/org/apache/camel/component/springrabbit/SpringRabbitMQConsumerStopTest.java b/components/camel-spring-parent/camel-spring-rabbitmq/src/test/java/org/apache/camel/component/springrabbit/SpringRabbitMQConsumerStopTest.java index 261f0246d422..6cfd42ba82dc 100644 --- a/components/camel-spring-parent/camel-spring-rabbitmq/src/test/java/org/apache/camel/component/springrabbit/SpringRabbitMQConsumerStopTest.java +++ b/components/camel-spring-parent/camel-spring-rabbitmq/src/test/java/org/apache/camel/component/springrabbit/SpringRabbitMQConsumerStopTest.java @@ -43,6 +43,7 @@ import org.apache.camel.ServiceStatus; import org.apache.camel.builder.RouteBuilder; import org.apache.camel.component.mock.MockEndpoint; import org.apache.camel.impl.DefaultCamelContext; +import org.apache.camel.support.service.ServiceHelper; import org.apache.logging.log4j.Level; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.core.LogEvent; @@ -51,6 +52,7 @@ import org.apache.logging.log4j.core.appender.AbstractAppender; import org.apache.logging.log4j.core.config.Property; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.ValueSource; import org.springframework.amqp.core.AmqpAdmin; @@ -85,8 +87,11 @@ import static org.mockito.Mockito.when; */ class SpringRabbitMQConsumerStopTest { - // how long the consumer waits for its listener container to stop (shutdownAwaitTermination) + // how long the consumer waits for its listener container to stop, after the shutdownTimeout of the component + // (shutdownAwaitTermination) private static final long BOUND = 1000; + // how long a listener container waits for the messages it is processing, when it stops + private static final long SHUTDOWN_TIMEOUT = 500; // much longer than the bound, when the listener container stops in time private static final long HEALTHY_BOUND = 30000; // the time a suspend or a stop that does not wait for the broker may take on a busy machine: far less than the @@ -125,6 +130,7 @@ class SpringRabbitMQConsumerStopTest { when(admin.declareQueue(any(Queue.class))).thenAnswer(invocation -> invocation.getArgument(0, Queue.class).getName()); SpringRabbitMQComponent component = context.getComponent("spring-rabbitmq", SpringRabbitMQComponent.class); component.setAmqpAdmin(admin); + component.setShutdownTimeout(SHUTDOWN_TIMEOUT); component.setListenerContainerFactory(this::createListenerContainer); appender = new AbstractAppender("consumerStop", null, null, true, Property.EMPTY_ARRAY) { @@ -160,7 +166,10 @@ class SpringRabbitMQConsumerStopTest { await("the cancel waits for the broker").atMost(10, TimeUnit.SECONDS).until(channel::isCancelling); List<String> warnings = warnings(); assertEquals(1, warnings.size(), "one WARN for the listener container that stops in the background: " + warnings); - assertTrue(warnings.get(0).contains("(queues: [" + name + "]) did not stop within " + BOUND + " millis"), + assertTrue(warnings.get(0).contains("(queues: [" + name + "]) did not stop within " + (SHUTDOWN_TIMEOUT + BOUND) + + " millis (the shutdownTimeout of the component, " + SHUTDOWN_TIMEOUT + + " millis, plus the shutdownAwaitTermination of the ExecutorServiceManager, " + + BOUND + " millis)"), warnings.get(0)); AbstractMessageListenerContainer container = containers.get(0); assertFalse(destroyed.contains(container)); @@ -417,9 +426,135 @@ class SpringRabbitMQConsumerStopTest { assertTrue(warnings().isEmpty(), "no WARN: " + warnings()); } + /** + * A route that suspends its own consumer while it processes a message, as a route policy such as + * ThrottlingInflightRoutePolicy does when an exchange is done. A listener container waits up to its shutdownTimeout + * for the messages it is processing, whichever thread stops it: the suspend waits for the shutdownTimeout and the + * bound together, so here it ends in time although the shutdownTimeout is longer than the bound. + */ + @ParameterizedTest + @ValueSource(strings = { "DMLC", "SMLC" }) + void suspendFromTheListenerThread(String type) throws Exception { + context.getComponent("spring-rabbitmq", SpringRabbitMQComponent.class).setShutdownTimeout(3 * BOUND); + context.addRoutes(new RouteBuilder() { + @Override + public void configure() { + from(uri(type)).routeId("orders") + .process(exchange -> ServiceHelper + .suspendService(exchange.getContext().getRoute("orders").getConsumer())) + .to("mock:orders"); + } + }); + context.start(); + MockEndpoint mock = context.getEndpoint("mock:orders", MockEndpoint.class); + mock.expectedBodiesReceived("Hello"); + + inAnotherThread(() -> subscribed(0).deliver("Hello")); + + MockEndpoint.assertIsSatisfied(context, 20, TimeUnit.SECONDS); + SpringRabbitMQConsumer consumer = (SpringRabbitMQConsumer) context.getRoute("orders").getConsumer(); + assertTrue(consumer.isSuspended()); + // the suspend did not give up waiting for the listener container + assertEquals(1, containers.size()); + assertFalse(destroyed.contains(containers.get(0))); + assertTrue(warnings().isEmpty(), "no WARN: " + warnings()); + } + + /** + * A suspend from another thread while the route processes a message: the simple listener container waits up to its + * shutdownTimeout for that message (longer than the bound here), and so does the suspend. + */ + @Test + void suspendWaitsForTheMessageThatIsProcessed() throws Exception { + context.getComponent("spring-rabbitmq", SpringRabbitMQComponent.class).setShutdownTimeout(10 * BOUND); + CountDownLatch processing = new CountDownLatch(1); + CountDownLatch done = new CountDownLatch(1); + context.addRoutes(new RouteBuilder() { + @Override + public void configure() { + from(uri("SMLC")).routeId("orders") + .process(exchange -> { + processing.countDown(); + done.await(20, TimeUnit.SECONDS); + }) + .to("mock:orders"); + } + }); + context.start(); + MockEndpoint mock = context.getEndpoint("mock:orders", MockEndpoint.class); + mock.expectedBodiesReceived("Hello"); + subscribed(0).deliver("Hello"); + assertTrue(processing.await(10, TimeUnit.SECONDS), "the route processes the message"); + SpringRabbitMQConsumer consumer = (SpringRabbitMQConsumer) context.getRoute("orders").getConsumer(); + + CompletableFuture<Void> suspend = inAnotherThread(consumer::suspend); + await("the suspend starts").atMost(10, TimeUnit.SECONDS).until(consumer::isSuspending); + + // past the bound, the suspend still waits for the message + await("the suspend waits for the message").during(2 * BOUND, TimeUnit.MILLISECONDS) + .atMost(3 * BOUND, TimeUnit.MILLISECONDS).until(() -> !suspend.isDone()); + done.countDown(); + await("the suspend returns").atMost(10, TimeUnit.SECONDS).until(suspend::isDone); + suspend.join(); + mock.assertIsSatisfied(); + assertTrue(consumer.isSuspended()); + assertEquals(1, containers.size()); + assertFalse(destroyed.contains(containers.get(0))); + assertTrue(warnings().isEmpty(), "no WARN: " + warnings()); + } + + @Test + void shutdownAwaitTerminationOfZeroWaitsTheLeastTime() throws Exception { + context.getExecutorServiceManager().setShutdownAwaitTermination(0); + startRoute("DMLC"); + subscribed(0).stopAnswering(); + + suspendThatDoesNotWait(); + + List<String> warnings = warnings(); + assertEquals(1, warnings.size(), "one WARN: " + warnings); + assertTrue(warnings.get(0).contains("did not stop within " + (SHUTDOWN_TIMEOUT + 100) + " millis"), + warnings.get(0)); + } + + /** + * Once its timeout interrupted its thread, the graceful shutdown goes on suspending the consumers of the other + * routes: a consumer whose listener container stops at once still waits for it, and keeps it. + */ + @Test + void suspendByAnInterruptedThreadWaitsForAListenerContainerThatStopsAtOnce() throws Exception { + context.getExecutorServiceManager().setShutdownAwaitTermination(HEALTHY_BOUND); + startRoute("DMLC"); + subscribed(0); + SpringRabbitMQConsumer consumer = (SpringRabbitMQConsumer) context.getRoute("orders").getConsumer(); + // once, so that the suspend below does not load classes or start threads within the 100 millis it waits + consumer.suspend(); + consumer.resume(); + subscribed(1); + AtomicBoolean interruptKept = new AtomicBoolean(); + + CompletableFuture<Void> suspend = inAnotherThread(() -> { + Thread.currentThread().interrupt(); + consumer.suspend(); + interruptKept.set(Thread.interrupted()); + }); + + await("the suspend returns").atMost(STOP_TIME, TimeUnit.MILLISECONDS).until(suspend::isDone); + suspend.join(); + assertTrue(consumer.isSuspended()); + assertTrue(interruptKept.get(), "the interrupt is kept"); + assertEquals(1, containers.size()); + assertFalse(destroyed.contains(containers.get(0))); + assertTrue(warnings().isEmpty(), "no WARN: " + warnings()); + } + private void startRoute(String type) throws Exception { - startRouteFrom("spring-rabbitmq:" + name + "?connectionFactory=#cf&queues=" + name + "&routingKey=new" - + "&messageListenerContainerType=" + type); + startRouteFrom(uri(type)); + } + + private String uri(String type) { + return "spring-rabbitmq:" + name + "?connectionFactory=#cf&queues=" + name + "&routingKey=new" + + "&messageListenerContainerType=" + type; } private void startRouteFrom(String uri) throws Exception { @@ -578,6 +713,10 @@ class SpringRabbitMQConsumerStopTest { private void cancel(String tag) { Consumer consumer = consumers.remove(tag); + if (consumer == null) { + // cancelled before (a listener container that closes the channel of a consumer it cancelled) + return; + } if (!answering) { cancelling.countDown(); awaitAnswer(); diff --git a/components/camel-spring-parent/camel-spring-rabbitmq/src/test/java/org/apache/camel/component/springrabbit/integration/RabbitMQConsumerSuspendResumeIT.java b/components/camel-spring-parent/camel-spring-rabbitmq/src/test/java/org/apache/camel/component/springrabbit/integration/RabbitMQConsumerSuspendResumeIT.java index 4e527dd62d73..44e2c2f45b1f 100644 --- a/components/camel-spring-parent/camel-spring-rabbitmq/src/test/java/org/apache/camel/component/springrabbit/integration/RabbitMQConsumerSuspendResumeIT.java +++ b/components/camel-spring-parent/camel-spring-rabbitmq/src/test/java/org/apache/camel/component/springrabbit/integration/RabbitMQConsumerSuspendResumeIT.java @@ -16,14 +16,29 @@ */ package org.apache.camel.component.springrabbit.integration; +import java.util.List; import java.util.Properties; import java.util.UUID; +import java.util.concurrent.CopyOnWriteArrayList; import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicLong; +import org.apache.camel.CamelContext; +import org.apache.camel.Consumer; import org.apache.camel.RoutesBuilder; import org.apache.camel.ServiceStatus; import org.apache.camel.builder.RouteBuilder; import org.apache.camel.component.mock.MockEndpoint; +import org.apache.camel.component.springrabbit.SpringRabbitMQComponent; +import org.apache.camel.component.springrabbit.SpringRabbitMQConstants; +import org.apache.camel.component.springrabbit.SpringRabbitMQConsumer; +import org.apache.camel.support.service.ServiceHelper; +import org.apache.logging.log4j.Level; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.core.LogEvent; +import org.apache.logging.log4j.core.Logger; +import org.apache.logging.log4j.core.appender.AbstractAppender; +import org.apache.logging.log4j.core.config.Property; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.ValueSource; @@ -32,6 +47,7 @@ import org.springframework.amqp.rabbit.core.RabbitAdmin; import static org.awaitility.Awaitility.await; import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; /** * A route that is suspended and resumed consumes again, with either type of listener container: while it is suspended, @@ -39,11 +55,20 @@ import static org.junit.jupiter.api.Assertions.assertEquals; */ public class RabbitMQConsumerSuspendResumeIT extends RabbitMQITSupport { + // how long a listener container waits for the messages it is processing when it stops: longer than the + // shutdownAwaitTermination of the test, which the consumer waits for the listener container on top of it + private static final long SHUTDOWN_TIMEOUT = 2000; + private static final long SHUTDOWN_AWAIT_TERMINATION = 1000; + // the exchanges and queues of this test run only, so that another run on the same broker, or a message that a // failed run left in a queue, does not change the counts private final String run = UUID.randomUUID().toString(); // the test checks the queue with its own connection factory private CachingConnectionFactory testConnectionFactory; + // how long the route that suspends its own consumer waited for the suspend + private final AtomicLong suspendTime = new AtomicLong(); + // the messages that the routes which suspend their own consumer received + private final List<String> selfReceived = new CopyOnWriteArrayList<>(); @AfterEach void destroyTestConnectionFactory() { @@ -80,6 +105,60 @@ public class RabbitMQConsumerSuspendResumeIT extends RabbitMQITSupport { MockEndpoint.assertIsSatisfied(context, 30, TimeUnit.SECONDS); } + /** + * A route that suspends its own consumer while it processes a message, as a route policy does when an exchange is + * done: the listener container waits its whole shutdownTimeout for that message, and the suspend still ends in time + * (no WARN), as the consumer waits for the shutdownTimeout plus the shutdownAwaitTermination. The listener + * container then closes the channel of that message, so the broker delivers it again once the consumer is resumed. + */ + @ParameterizedTest + @ValueSource(strings = { "DMLC", "SMLC" }) + public void testSuspendFromTheListenerThread(String type) throws Exception { + String route = "self-" + type; + List<LogEvent> warnings = new CopyOnWriteArrayList<>(); + AbstractAppender appender = new AbstractAppender( + "suspendFromTheListenerThread", null, null, true, + Property.EMPTY_ARRAY) { + @Override + public void append(LogEvent event) { + if (event.getLevel() == Level.WARN) { + warnings.add(event.toImmutable()); + } + } + }; + appender.start(); + Logger logger = (Logger) LogManager.getLogger(SpringRabbitMQConsumer.class); + logger.addAppender(appender); + try { + template.sendBody("direct:" + route, "order 1"); + await().atMost(30, TimeUnit.SECONDS).until(() -> suspendTime.get() > 0); + Consumer consumer = context.getRoute(route).getConsumer(); + + assertTrue(ServiceHelper.isSuspended(consumer), "the consumer is suspended"); + assertTrue(TimeUnit.NANOSECONDS.toMillis(suspendTime.get()) >= SHUTDOWN_TIMEOUT - 100, + "the listener container waited its shutdownTimeout for the message: " + suspendTime.get()); + assertEquals(List.of(), warnings.stream().map(e -> e.getMessage().getFormattedMessage()) + .filter(m -> m.contains(name(route + "-queue"))).toList(), "no WARN"); + + ServiceHelper.resumeService(consumer); + template.sendBody("direct:" + route, "order 2"); + await().atMost(30, TimeUnit.SECONDS).until(() -> selfReceived.size() == 3); + assertEquals(List.of(route + ":order 1:redelivered=false", route + ":order 1:redelivered=true", + route + ":order 2:redelivered=false"), selfReceived); + } finally { + logger.removeAppender(appender); + appender.stop(); + } + } + + @Override + protected CamelContext createCamelContext() throws Exception { + CamelContext context = super.createCamelContext(); + context.getExecutorServiceManager().setShutdownAwaitTermination(SHUTDOWN_AWAIT_TERMINATION); + context.getComponent("spring-rabbitmq", SpringRabbitMQComponent.class).setShutdownTimeout(SHUTDOWN_TIMEOUT); + return context; + } + private String name(String baseName) { return uniqueName(baseName) + "-" + run; } @@ -102,6 +181,24 @@ public class RabbitMQConsumerSuspendResumeIT extends RabbitMQITSupport { + "&routingKey=new&messageListenerContainerType=" + type) .routeId(type) .to("mock:" + type); + + String self = "self-" + type; + from("direct:" + self) + .to("spring-rabbitmq:" + name(self) + "?routingKey=new"); + + from("spring-rabbitmq:" + name(self) + "?queues=" + name(self + "-queue") + + "&routingKey=new&messageListenerContainerType=" + type) + .routeId(self) + .process(exchange -> { + String body = exchange.getMessage().getBody(String.class); + selfReceived.add(self + ":" + body + ":redelivered=" + + exchange.getMessage().getHeader(SpringRabbitMQConstants.REDELIVERED)); + if ("order 1".equals(body) && suspendTime.get() == 0) { + long start = System.nanoTime(); + ServiceHelper.suspendService(exchange.getContext().getRoute(self).getConsumer()); + suspendTime.set(System.nanoTime() - start); + } + }); } } }; 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 4692353a8c92..4966251fbb46 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 @@ -276,8 +276,11 @@ and Camel does not recover from it". Suspending or stopping a consumer of camel-jms (and of the components built on it, such as camel-activemq, camel-activemq6 and camel-amqp) or of camel-spring-rabbitmq now waits for its listener container to stop at most the -`shutdownAwaitTermination` of the `ExecutorServiceManager` (10 seconds by default), or until the waiting thread is -interrupted, as the graceful shutdown does when its timeout elapses. Previously, it waited without bound when the +`shutdownAwaitTermination` of the `ExecutorServiceManager` (10 seconds by default, at least 100 milliseconds), or until +the waiting thread is interrupted, as the graceful shutdown does when its timeout elapses. camel-spring-rabbitmq waits +the `shutdownTimeout` of the component (5 seconds by default), in which the listener container waits for the messages +in progress, on top of that. camel-jms with `consumerType=Simple` and Spring's `SyncTaskExecutor` as `taskExecutor` also +waits as long as the route processes messages, as the JMS client does. Previously, it waited without bound when the broker did not answer: for the `callTimeout` of ActiveMQ Artemis (30 seconds by default), or for the `channelRpcTimeout` of the RabbitMQ client (10 minutes by default), past the shutdown timeout. @@ -288,11 +291,11 @@ ends its non-durable topic subscriptions: the messages published until the new l reach the consumer. A camel-jms suspend or stop from the thread that processes a message of the consumer (such as a route policy when an exchange is done) still stops the listener container on that thread, without this time limit. -The stop of the listener container runs on a thread pool of the component: the `AsyncStartStopListener` thread pool of -camel-jms, and a new `SpringRabbitMQStopListenerContainer` thread pool of camel-spring-rabbitmq. camel-jms with -`asyncStopListener=true` is unchanged. A camel-spring-rabbitmq `shutdownTimeout` above that bound no longer extends the -suspend: raise the `shutdownAwaitTermination` too (`camelContext.getExecutorServiceManager() -.setShutdownAwaitTermination(...)`) if the suspend must wait longer for the messages in progress. +The stop of the listener container runs on a new thread pool of the component: `JmsStopListenerContainer` for +camel-jms, and `SpringRabbitMQStopListenerContainer` for camel-spring-rabbitmq. camel-jms with +`asyncStopListener=true` is unchanged. The `shutdownAwaitTermination` can be raised with +`camelContext.getExecutorServiceManager().setShutdownAwaitTermination(...)`; it is also the time that Camel waits for +each thread pool to terminate when the CamelContext stops. === camel-core - a to with an expression in its endpoint uri logs a WARN diff --git a/docs/user-manual/modules/ROOT/pages/graceful-shutdown.adoc b/docs/user-manual/modules/ROOT/pages/graceful-shutdown.adoc index ec93539fe989..f5e14b169f5d 100644 --- a/docs/user-manual/modules/ROOT/pages/graceful-shutdown.adoc +++ b/docs/user-manual/modules/ROOT/pages/graceful-shutdown.adoc @@ -146,7 +146,12 @@ Set the timeouts of the client that the component uses (such as its connection, calls return when the remote system stops answering. Some consumers bound such calls themselves: the xref:components::jms-component.adoc[JMS] and xref:components::spring-rabbitmq-component.adoc[Spring RabbitMQ] consumers wait for their listener container to stop at most the `shutdownAwaitTermination` of the `ExecutorServiceManager` -(10 seconds by default), and let it stop in the background after that. +(10 seconds by default; Spring RabbitMQ adds the `shutdownTimeout` of the component, in which the listener container +waits for the messages in progress), and let it stop in the background after that. + +That bound is per consumer: with several routes that consume from a broker that does not answer, the graceful shutdown +waits for them one after the other until its own timeout elapses. Then the shutdown interrupts the suspend in +progress, and the consumers that it suspends after that wait for their listener container at most 100 milliseconds. === JMX managed
