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 fb1ba3663ec85cb06a12d997bf59027ba67ac11f Author: croway <[email protected]> AuthorDate: Wed Nov 25 18:03:47 2026 +0100 CAMEL-27009: camel-jms - the suspend and stop of the listener container do not wait without bound for a broker that does not answer JmsConsumer.doSuspend() stopped the listener container on the calling thread, and doStop() stopped and destroyed it there unless asyncStopListener=true. When the broker does not answer, the JMS client may only return from Connection.stop() (or the close of its consumers and sessions) once a timeout of its own elapses (the callTimeout of ActiveMQ Artemis, 30 s by default), and ignores interrupts: a route or CamelContext stop waited for it, past the shutdown timeout. The suspend and the stop now run the stop of the listener container on the async start/stop thread pool of the component, and wait for it up to the shutdownAwaitTermination of the ExecutorServiceManager (10 s by default), or until the waiting thread is interrupted, as the graceful shutdown does when its timeout elapses. When the stop ends in time, the outcome is unchanged. Otherwise the consumer logs a WARN naming the destination and no longer uses the listener container: its stop and destroy, the count of running listeners and the shutdown of its private thread pool (which takes no new task from then on, so the CamelContext stop does not wait for it) complete in the background once the blocked call returns, and their exceptions are logged. A resume or start creates a new listener container (a resume starts it, also with autoStartup=false), and a stop after a suspend that timed out has nothing left to stop. A suspend or stop from a thread that processes a message of the listener container, such as a route policy when an exchange is done, still stops it on that thread: from another thread, a JMS client waits for its message listener to return. asyncStopListener=true is unchanged. --- .../apache/camel/catalog/docs/jms-component.adoc | 17 + .../camel-jms/src/main/docs/jms-component.adoc | 17 + .../component/jms/EndpointMessageListener.java | 26 + .../apache/camel/component/jms/JmsConsumer.java | 328 +++++++++++-- ...msConsumerListenerContainerStopTimeoutTest.java | 543 +++++++++++++++++++++ 5 files changed, 895 insertions(+), 36 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 97b56bb7ae83..682fe3b5c441 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 @@ -1183,6 +1183,23 @@ To act on these errors, set an option on the consumer: The `bridgeErrorHandler` option is not supported: a message that fails already goes to the error handler of the route. +=== Suspending or stopping a consumer when the broker does not answer + +Suspending or stopping a consumer (for example, when its route or the CamelContext is stopped) stops its listener +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 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. + +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 +policy when an exchange is done, stops the listener container on that thread, without this time limit, and so does a +stop from that thread, unless `asyncStopListener=true`. + === Concurrent Consuming A common requirement with JMS is to consume messages concurrently in diff --git a/components/camel-jms/src/main/docs/jms-component.adoc b/components/camel-jms/src/main/docs/jms-component.adoc index 97b56bb7ae83..682fe3b5c441 100644 --- a/components/camel-jms/src/main/docs/jms-component.adoc +++ b/components/camel-jms/src/main/docs/jms-component.adoc @@ -1183,6 +1183,23 @@ To act on these errors, set an option on the consumer: The `bridgeErrorHandler` option is not supported: a message that fails already goes to the error handler of the route. +=== Suspending or stopping a consumer when the broker does not answer + +Suspending or stopping a consumer (for example, when its route or the CamelContext is stopped) stops its listener +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 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. + +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 +policy when an exchange is done, stops the listener container on that thread, without this time limit, and so does a +stop from that thread, unless `asyncStopListener=true`. + === Concurrent Consuming A common requirement with JMS is to consume messages concurrently in 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 e243a16d0d0d..c38bebe9528a 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 @@ -48,6 +48,8 @@ import static org.apache.camel.RuntimeCamelException.wrapRuntimeCamelException; */ public class EndpointMessageListener implements SessionAwareMessageListener { private static final Logger LOG = LoggerFactory.getLogger(EndpointMessageListener.class); + // 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(); private final JmsConsumer consumer; private final JmsEndpoint endpoint; @@ -68,6 +70,30 @@ public class EndpointMessageListener implements SessionAwareMessageListener { @Override public void onMessage(Message message, Session session) throws JMSException { + // a suspend or stop of the consumer from this thread (such as by a route policy when the exchange is done) + // stops the listener container of this message listener on this thread + EndpointMessageListener previous = CURRENT.get(); + CURRENT.set(this); + try { + doOnMessage(message, session); + } finally { + if (previous == null) { + CURRENT.remove(); + } else { + CURRENT.set(previous); + } + } + } + + /** + * Whether the current thread processes a message in the given message listener (the message listener of a listener + * container). + */ + static boolean isProcessingOnCurrentThread(Object messageListener) { + return messageListener != null && CURRENT.get() == messageListener; + } + + private void doOnMessage(Message message, Session session) throws JMSException { LOG.trace("onMessage START"); LOG.debug("{} consumer received JMS message: {}", endpoint, message); 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 472432696dcb..b632a59112ad 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 @@ -17,6 +17,9 @@ package org.apache.camel.component.jms; 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.locks.Lock; import java.util.concurrent.locks.ReentrantLock; @@ -164,7 +167,16 @@ public class JmsConsumer extends DefaultConsumer implements Suspendable { @Override protected void doStart() throws Exception { super.doStart(); + createAndStartListenerContainer(false); + } + /** + * Creates the listener container (unless there is one), counts it as running on the endpoint, and initializes and + * starts it. + * + * @param start whether to start the listener container also when auto startup is disabled + */ + private void createAndStartListenerContainer(boolean start) throws Exception { // create listener container if (listenerContainer == null) { createMessageListenerContainer(); @@ -178,16 +190,18 @@ public class JmsConsumer extends DefaultConsumer implements Suspendable { } finally { containerLock.unlock(); } - prepareAndStartListenerContainer(container, getEndpoint().getConfiguration().isAsyncStartListener()); + prepareAndStartListenerContainer(container, getEndpoint().getConfiguration().isAsyncStartListener(), start); } /** * Initializes and starts the listener container, in a task of the component's async start/stop thread pool when * async is true, otherwise on the calling thread. + * + * @param start whether to start the listener container also when auto startup is disabled */ - private void prepareAndStartListenerContainer(AbstractMessageListenerContainer container, boolean async) { + private void prepareAndStartListenerContainer(AbstractMessageListenerContainer container, boolean async, boolean start) { if (!async) { - prepareAndStartListenerContainer(container); + prepareAndStartListenerContainer(container, start); return; } containerLock.lock(); @@ -200,7 +214,7 @@ public class JmsConsumer extends DefaultConsumer implements Suspendable { @Override public void run() { try { - prepareAndStartListenerContainer(container); + prepareAndStartListenerContainer(container, start); } catch (Exception e) { LOG.warn("Error starting listener container on destination: {}. This exception will be ignored.", getDestinationName(container), e); @@ -215,7 +229,7 @@ public class JmsConsumer extends DefaultConsumer implements Suspendable { } protected void prepareAndStartListenerContainer() { - prepareAndStartListenerContainer(listenerContainer); + prepareAndStartListenerContainer(listenerContainer, false); } /** @@ -252,7 +266,10 @@ public class JmsConsumer extends DefaultConsumer implements Suspendable { getDestinationName(container), consumers, effect); } - private void prepareAndStartListenerContainer(AbstractMessageListenerContainer container) { + /** + * @param startAnyway whether to start the listener container also when auto startup is disabled + */ + private void prepareAndStartListenerContainer(AbstractMessageListenerContainer container, boolean startAnyway) { if (listenerContainer != container) { // an early exit without the lock: the check that decides is the one under containerLock below. // The consumer was stopped (and maybe started again with a new listener container) before this @@ -263,7 +280,7 @@ public class JmsConsumer extends DefaultConsumer implements Suspendable { } // only start listener if auto start is enabled or we are explicit invoking start later - boolean autoStart = initialized || getEndpoint().isAutoStartup(); + boolean autoStart = startAnyway || initialized || getEndpoint().isAutoStartup(); boolean start = false; try { // initialize only once: every initialization of a DefaultMessageListenerContainer schedules another @@ -352,43 +369,126 @@ public class JmsConsumer extends DefaultConsumer implements Suspendable { private DetachedListenerContainer detachListenerContainer() { containerLock.lock(); try { - AbstractMessageListenerContainer container = listenerContainer; - if (container == null) { - return null; - } - DetachedListenerContainer answer - = new DetachedListenerContainer(container, executorService, shutdownExecutorService); - // 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; - messageListener = null; + // a later start creates the listener container, and starts it, as the first start did initialized = false; - listenerContainerCounted = false; - asyncStartPending = false; - executorService = null; - return answer; + return doDetachListenerContainer(); } finally { containerLock.unlock(); } } + /** + * 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. + */ + private DetachedListenerContainer detachSuspendedListenerContainer(AbstractMessageListenerContainer container) { + containerLock.lock(); + try { + return listenerContainer == container ? doDetachListenerContainer() : null; + } finally { + containerLock.unlock(); + } + } + + private DetachedListenerContainer doDetachListenerContainer() { + AbstractMessageListenerContainer container = listenerContainer; + if (container == null) { + return null; + } + DetachedListenerContainer answer = new DetachedListenerContainer(container, executorService, shutdownExecutorService); + // 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; + messageListener = null; + // the detached listener container is no longer counted once it is destroyed, and its start task (if any) no + // longer starts it + listenerContainerCounted = false; + asyncStartPending = false; + executorService = null; + return answer; + } + private void stopAndDestroyListenerContainer(DetachedListenerContainer detached) { try { - try { - detached.container().stop(); - } finally { - // also when stop fails (a SimpleMessageListenerContainer does not swallow a failing Connection.stop()) - detached.container().destroy(); - } + detached.container().stop(); + } finally { + // also when stop fails (a SimpleMessageListenerContainer does not swallow a failing Connection.stop()) + destroyListenerContainer(detached); + } + } + + private void destroyListenerContainer(DetachedListenerContainer detached) { + try { + detached.container().destroy(); } finally { getEndpoint().onListenerContainerStopped(); // shutdown thread pool if listener container was using a private thread pool - if (detached.shutdownExecutorService() && detached.executorService() != null) { - getEndpoint().getCamelContext().getExecutorServiceManager().shutdownNow(detached.executorService()); + 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 { + getEndpoint().getCamelContext().getExecutorServiceManager().shutdownNow(pool); + } + } + } + } + + /** + * 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 + * ({@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}. + * <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. + * + * @param operation the operation of this consumer that stops the listener container, for the log + */ + private void stopWithinBound(String operation, ListenerContainerStop stop) { + long timeout = getEndpoint().getCamelContext().getExecutorServiceManager().getShutdownAwaitTermination(); + if (EndpointMessageListener.isProcessingOnCurrentThread(stop.container.getMessageListener()) + || !runInBackground(stop)) { + // from the message listener, or no thread pool to run the stop on: stop the listener container on this thread + stop.run(); + } + 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) { + // 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()); } } } + private boolean runInBackground(Runnable task) { + if (getEndpoint().getComponent() == null) { + return false; + } + 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; + } + } + @Override protected void doStop() throws Exception { final DetachedListenerContainer detached = detachListenerContainer(); @@ -411,7 +511,7 @@ public class JmsConsumer extends DefaultConsumer implements Suspendable { } }); } else { - stopAndDestroyListenerContainer(detached); + stopWithinBound("stop", new ListenerContainerStop(detached)); } } @@ -420,8 +520,9 @@ public class JmsConsumer extends DefaultConsumer implements Suspendable { @Override protected void doSuspend() throws Exception { - if (listenerContainer != null) { - listenerContainer.stop(); + AbstractMessageListenerContainer container = listenerContainer; + if (container != null) { + stopWithinBound("suspend", new ListenerContainerStop(container)); } } @@ -445,6 +546,11 @@ 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; + } } finally { containerLock.unlock(); } @@ -453,7 +559,7 @@ 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()); + prepareAndStartListenerContainer(container, getEndpoint().getConfiguration().isAsyncStartListener(), false); } 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(); @@ -462,8 +568,9 @@ public class JmsConsumer extends DefaultConsumer implements Suspendable { // stopped it after the task's start() startListenerContainer(container); } else { - LOG.warn( - "The listenerContainer is not instantiated. Probably there was a timeout during the Suspend operation. Please restart your consumer route."); + // 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); } } @@ -507,10 +614,159 @@ public class JmsConsumer extends DefaultConsumer implements Suspendable { } /** - * A listener container detached from this consumer by a stop, with the private thread pool it uses (if any). + * 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). */ 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) + "]"; + } + } + } 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 new file mode 100644 index 000000000000..76a975f0b46b --- /dev/null +++ b/components/camel-jms/src/test/java/org/apache/camel/component/jms/JmsConsumerListenerContainerStopTimeoutTest.java @@ -0,0 +1,543 @@ +/* + * 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.jms; + +import java.util.List; +import java.util.concurrent.Callable; +import java.util.concurrent.CopyOnWriteArrayList; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.Executor; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.TimeoutException; +import java.util.concurrent.atomic.AtomicBoolean; + +import jakarta.jms.JMSException; + +import org.apache.camel.CamelContext; +import org.apache.camel.ProducerTemplate; +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.camel.test.infra.artemis.common.ConnectionFactoryHelper; +import org.apache.camel.test.infra.artemis.services.ArtemisService; +import org.apache.camel.test.infra.artemis.services.ArtemisServiceFactory; +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.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestInfo; +import org.junit.jupiter.api.Timeout; +import org.junit.jupiter.api.extension.RegisterExtension; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; +import org.springframework.core.task.SyncTaskExecutor; +import org.springframework.jms.listener.AbstractMessageListenerContainer; + +import static org.awaitility.Awaitility.await; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNotSame; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; + +/** + * The suspend and the stop of a consumer stop its listener container, which stops its JMS connection. 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), and does not react to an interrupt. The consumer waits for its listener + * container at most the shutdownAwaitTermination of the ExecutorServiceManager: then the listener container is stopped + * and destroyed in the background, and the consumer creates a new one when it is resumed or started again. + * <p/> + * The listener containers of the test block, when the test says so, in the stop of their shared connection or in their + * destroy, until the test releases them, and ignore interrupts. + */ +@Timeout(60) +public class JmsConsumerListenerContainerStopTimeoutTest { + + @RegisterExtension + public static ArtemisService service = ArtemisServiceFactory.createSingletonVMService(); + + // how long the consumer waits for its listener container, in these tests + private static final long BOUND = 1000; + + private final CountDownLatch blocked = new CountDownLatch(1); + private final CountDownLatch release = new CountDownLatch(1); + private final List<BlockingListenerContainer> containers = new CopyOnWriteArrayList<>(); + private final List<LogEvent> events = new CopyOnWriteArrayList<>(); + private final ExecutorService caller = Executors.newCachedThreadPool(); + private volatile Block block = Block.NONE; + private volatile boolean failDestroy; + private AbstractAppender appender; + private CamelContext context; + private ProducerTemplate template; + private String queue; + + private enum Block { + NONE, + // in the stop of the shared connection (the stop of the listener container: a suspend of the consumer) + STOP, + // in the destroy of the listener container (the stop of the consumer) + DESTROY + } + + @BeforeEach + void setUp(TestInfo info) throws Exception { + queue = getClass().getSimpleName() + "." + info.getTestMethod().orElseThrow().getName(); + appender = new AbstractAppender("listenerContainerStop", null, null, true, Property.EMPTY_ARRAY) { + @Override + public void append(LogEvent event) { + events.add(event.toImmutable()); + } + }; + appender.start(); + ((Logger) LogManager.getLogger(JmsConsumer.class)).addAppender(appender); + + context = new DefaultCamelContext(); + context.getExecutorServiceManager().setShutdownAwaitTermination(BOUND); + // longer than the test waits: the suspend or stop must not end because the graceful shutdown timed out + context.getShutdownStrategy().setTimeout(60); + context.getRegistry().bind("blockingFactory", (MessageListenerContainerFactory) endpoint -> { + BlockingListenerContainer container = new BlockingListenerContainer(endpoint); + containers.add(container); + return container; + }); + context.addComponent("jms", JmsComponent.jmsComponent(ConnectionFactoryHelper.createConnectionFactory(service))); + context.addRoutes(new RouteBuilder() { + @Override + public void configure() { + from("jms:queue:" + queue + "?messageListenerContainerFactory=#blockingFactory").routeId("jms") + .to("mock:result"); + } + }); + context.start(); + template = context.createProducerTemplate(); + } + + @AfterEach + void tearDown() { + // the stop of a listener container left in the background returns + release.countDown(); + try { + context.getExecutorServiceManager().setShutdownAwaitTermination(BOUND); + context.stop(); + } finally { + ((Logger) LogManager.getLogger(JmsConsumer.class)).removeAppender(appender); + appender.stop(); + caller.shutdownNow(); + } + } + + @Test + public void testContextStopWhileTheSuspendOfTheListenerContainerDoesNotReturn() throws Exception { + BlockingListenerContainer container = containers.get(0); + JmsEndpoint endpoint = endpoint(); + block = Block.STOP; + + assertReturns("the stop of the CamelContext", () -> { + context.stop(); + return null; + }); + + assertEquals(0, blocked.getCount(), "the stop of the listener container is blocked"); + assertWarning("The suspend of the consumer on destination " + queue + " did not end within " + BOUND + " millis"); + assertFalse(container.destroyed, "the listener container is not destroyed while its stop is blocked"); + // the ExecutorServiceManager did not wait for (and then force) the private thread pool of the listener container + assertFalse(container.taskExecutor.isTerminated(), "the threads of the listener container are left to its stop"); + + release.countDown(); + await().atMost(10, TimeUnit.SECONDS) + .until(() -> container.destroyed && endpoint.getRunningMessageListeners() == 0); + } + + @Test + public void testContextStopWhileTheDestroyOfTheListenerContainerDoesNotReturn() throws Exception { + BlockingListenerContainer container = containers.get(0); + JmsEndpoint endpoint = endpoint(); + suspendRouteInTime(); + block = Block.DESTROY; + + assertReturns("the stop of the CamelContext", () -> { + context.stop(); + return null; + }); + + assertEquals(0, blocked.getCount(), "the destroy of the listener container is blocked"); + assertWarning("The stop of the consumer on destination " + queue + " did not end within " + BOUND + " millis"); + assertEquals(1, endpoint.getRunningMessageListeners(), "the listener container is not stopped yet"); + + release.countDown(); + await().atMost(10, TimeUnit.SECONDS) + .until(() -> container.destroyed && endpoint.getRunningMessageListeners() == 0); + } + + @Test + public void testResumeAfterASuspendThatDidNotEndCreatesANewListenerContainer() throws Exception { + assertConsumedOnce("Hello World"); + BlockingListenerContainer first = containers.get(0); + block = Block.STOP; + + assertReturns("the suspend of the route", () -> { + context.getRouteController().suspendRoute("jms"); + return null; + }); + + assertEquals(ServiceStatus.Suspended, context.getRouteController().getRouteStatus("jms")); + assertWarning("The suspend of the consumer on destination " + queue + " did not end within " + BOUND + " millis"); + assertTrue(first.taskExecutor.isShutdown(), + "the private thread pool of the first listener container takes no new task"); + + context.getRouteController().resumeRoute("jms"); + + assertEquals(ServiceStatus.Started, context.getRouteController().getRouteStatus("jms")); + assertEquals(2, containers.size(), "the resume creates a new listener container"); + BlockingListenerContainer second = containers.get(1); + assertSame(second, consumer().getListenerContainer()); + assertTrue(second.isRunning(), "the new listener container runs"); + assertConsumedOnce("Bye World"); + + // the stop of the first listener container returns: it is destroyed, and its private thread pool shut down + release.countDown(); + await().atMost(10, TimeUnit.SECONDS).until(() -> first.destroyed && first.taskExecutor.isTerminated() + && endpoint().getRunningMessageListeners() == 1); + assertTrue(second.isRunning(), "the new listener container still runs"); + assertFalse(second.taskExecutor.isShutdown(), "the thread pool of the new listener container is not shut down"); + assertConsumedOnce("Hello again"); + } + + @Test + public void testStartAfterAStopThatDidNotEndCreatesANewListenerContainer() throws Exception { + assertConsumedOnce("Hello World"); + BlockingListenerContainer first = containers.get(0); + suspendRouteInTime(); + block = Block.DESTROY; + + assertReturns("the stop of the route", () -> { + context.getRouteController().stopRoute("jms"); + return null; + }); + + assertEquals(ServiceStatus.Stopped, context.getRouteController().getRouteStatus("jms")); + assertWarning("The stop of the consumer on destination " + queue + " did not end within " + BOUND + " millis"); + assertEquals(1, endpoint().getRunningMessageListeners(), "the first listener container is not stopped yet"); + + context.getRouteController().startRoute("jms"); + + assertEquals(2, containers.size(), "the start creates a new listener container"); + BlockingListenerContainer second = containers.get(1); + assertSame(second, consumer().getListenerContainer()); + assertConsumedOnce("Bye World"); + + release.countDown(); + await().atMost(10, TimeUnit.SECONDS).until(() -> first.destroyed && first.taskExecutor.isTerminated() + && endpoint().getRunningMessageListeners() == 1); + assertTrue(second.isRunning(), "the new listener container still runs"); + } + + @Test + public void testSuspendReturnsWhenTheWaitingThreadIsInterrupted() throws Exception { + BlockingListenerContainer container = containers.get(0); + JmsConsumer consumer = consumer(); + // much longer than the test waits + context.getExecutorServiceManager().setShutdownAwaitTermination(TimeUnit.MINUTES.toMillis(5)); + block = Block.STOP; + CountDownLatch suspended = new CountDownLatch(1); + AtomicBoolean interruptKept = new AtomicBoolean(); + Future<?> suspend = caller.submit(() -> { + try { + consumer.suspend(); + interruptKept.set(Thread.currentThread().isInterrupted()); + } finally { + suspended.countDown(); + } + }); + assertTrue(blocked.await(10, TimeUnit.SECONDS), "the stop of the listener container is blocked"); + + // as the graceful shutdown does to its task when its timeout elapses + suspend.cancel(true); + + assertTrue(suspended.await(10, TimeUnit.SECONDS), "the suspend returns once its thread is interrupted"); + assertTrue(interruptKept.get(), "the thread keeps its interrupt status"); + assertTrue(consumer.isSuspended(), "the consumer is suspended"); + assertWarning("The suspend of the consumer on destination " + queue + + " was interrupted before its listener container stopped"); + + release.countDown(); + await().atMost(10, TimeUnit.SECONDS).until(() -> container.destroyed && container.taskExecutor.isTerminated() + && endpoint().getRunningMessageListeners() == 0); + } + + @Test + public void testResumeAfterASuspendThatDidNotEndStartsTheNewListenerContainerWithoutAutoStartup() throws Exception { + String manualQueue = queue + ".manual"; + context.addRoutes(new RouteBuilder() { + @Override + public void configure() { + from("jms:queue:" + manualQueue + "?autoStartup=false&messageListenerContainerFactory=#blockingFactory") + .routeId("manual").to("mock:manual"); + } + }); + JmsConsumer consumer = (JmsConsumer) context.getRoute("manual").getConsumer(); + AbstractMessageListenerContainer first = consumer.getListenerContainer(); + assertFalse(first.isRunning(), "the listener container does not start with the consumer"); + consumer.startListenerContainer(); + assertConsumedOnce("mock:manual", manualQueue, "Hello World"); + block = Block.STOP; + + assertReturns("the suspend of the route", () -> { + context.getRouteController().suspendRoute("manual"); + return null; + }); + assertWarning("The suspend of the consumer on destination " + manualQueue + " did not end within " + BOUND + + " millis"); + + context.getRouteController().resumeRoute("manual"); + + AbstractMessageListenerContainer second = consumer.getListenerContainer(); + assertNotSame(first, second, "the resume creates a new listener container"); + // as the resume starts the listener container that a suspend that ends in time keeps + assertTrue(second.isRunning(), "the resume starts the new listener container"); + assertConsumedOnce("mock:manual", manualQueue, "Bye World"); + } + + @Test + public void testErrorOfTheStopInTheBackgroundIsLogged() throws Exception { + BlockingListenerContainer container = containers.get(0); + suspendRouteInTime(); + block = Block.DESTROY; + failDestroy = true; + + assertReturns("the stop of the route", () -> { + context.getRouteController().stopRoute("jms"); + return null; + }); + assertWarning("The stop of the consumer on destination " + queue + " did not end within " + BOUND + " millis"); + + release.countDown(); + await().atMost(10, TimeUnit.SECONDS).until(() -> warnings().size() == 2); + LogEvent error = warnings().get(1); + assertTrue(error.getMessage().getFormattedMessage() + .startsWith("Error stopping listener container on destination: " + queue + " in the background."), + error.getMessage().getFormattedMessage()); + assertNotNull(error.getThrown(), "the exception is logged"); + assertEquals(0, endpoint().getRunningMessageListeners()); + assertTrue(container.taskExecutor.isShutdown(), "the private thread pool is shut down"); + } + + @Test + public void testSuspendResumeAndStopOfAListenerContainerThatStopsInTime() throws Exception { + // the default: 10 seconds + context.getExecutorServiceManager().setShutdownAwaitTermination(10000); + assertConsumedOnce("Hello World"); + BlockingListenerContainer container = containers.get(0); + + context.getRouteController().suspendRoute("jms"); + + assertSame(container, consumer().getListenerContainer(), "the suspended consumer keeps its listener container"); + assertFalse(container.isRunning(), "the listener container is stopped"); + assertFalse(container.destroyed, "the listener container is not destroyed"); + + context.getRouteController().resumeRoute("jms"); + + assertSame(container, consumer().getListenerContainer(), "the resumed consumer keeps its listener container"); + assertTrue(container.isRunning(), "the listener container runs again"); + assertEquals(1, containers.size()); + assertConsumedOnce("Bye World"); + + context.getRouteController().stopRoute("jms"); + + // the stop returns once the listener container is destroyed and its private thread pool shut down + assertTrue(container.destroyed, "the listener container is destroyed"); + assertTrue(container.taskExecutor.isShutdown(), "the private thread pool is shut down"); + assertEquals(0, endpoint().getRunningMessageListeners()); + assertEquals(List.of(), warnings(), "no WARN"); + } + + /** + * 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. With a synchronous task executor, the simple + * listener container processes the message in the message listener of the JMS client. + */ + @ParameterizedTest + @ValueSource(strings = { "Default", "Simple", "SimpleSync" }) + public void testSuspendFromTheListenerThread(String type) throws Exception { + // the default: 10 seconds + context.getExecutorServiceManager().setShutdownAwaitTermination(10000); + context.getRegistry().bind("syncTaskExecutor", new SyncTaskExecutor()); + String listenerQueue = queue + "." + type; + String options + = "SimpleSync".equals(type) ? "consumerType=Simple&taskExecutor=#syncTaskExecutor" : "consumerType=" + type; + context.addRoutes(new RouteBuilder() { + @Override + public void configure() { + from("jms:queue:" + listenerQueue + "?" + options).routeId("self") + .process(exchange -> ServiceHelper + .suspendService(exchange.getContext().getRoute("self").getConsumer())) + .to("mock:self"); + } + }); + JmsConsumer consumer = (JmsConsumer) context.getRoute("self").getConsumer(); + AbstractMessageListenerContainer container = consumer.getListenerContainer(); + MockEndpoint self = MockEndpoint.resolve(context, "mock:self"); + self.expectedBodiesReceived("Hello World"); + + template.sendBody("jms:queue:" + listenerQueue, "Hello World"); + + MockEndpoint.assertIsSatisfied(context, 20, TimeUnit.SECONDS); + assertTrue(consumer.isSuspended(), "the consumer is suspended"); + // the suspend did not give up waiting for the listener container + 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(listenerQueue)).toList(); + assertEquals(List.of(), warnings, "no WARN"); + } + + /** + * 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. + */ + private void suspendRouteInTime() throws Exception { + context.getExecutorServiceManager().setShutdownAwaitTermination(10000); + context.getRouteController().suspendRoute("jms"); + assertEquals(ServiceStatus.Suspended, context.getRouteController().getRouteStatus("jms")); + context.getExecutorServiceManager().setShutdownAwaitTermination(BOUND); + } + + private JmsEndpoint endpoint() { + return context.getEndpoint("jms:queue:" + queue + "?messageListenerContainerFactory=#blockingFactory", + JmsEndpoint.class); + } + + private JmsConsumer consumer() { + return (JmsConsumer) context.getRoute("jms").getConsumer(); + } + + private void assertConsumedOnce(String body) throws Exception { + assertConsumedOnce("mock:result", queue, body); + } + + private void assertConsumedOnce(String mock, String destination, String body) throws Exception { + MockEndpoint result = MockEndpoint.resolve(context, mock); + result.reset(); + result.expectedBodiesReceived(body); + // and not a second time + result.setAssertPeriod(500); + template.sendBody("jms:queue:" + destination, body); + MockEndpoint.assertIsSatisfied(context); + } + + /** + * Runs the given action on another thread, and fails when it does not return within 10 seconds (the listener + * container of the test blocks until the test releases it). + */ + private void assertReturns(String action, Callable<Void> callable) throws Exception { + Future<Void> future = caller.submit(callable); + try { + future.get(10, TimeUnit.SECONDS); + } catch (TimeoutException e) { + fail(action + " did not return within 10 seconds, while the listener container does not stop"); + } + } + + private List<LogEvent> warnings() { + return events.stream() + .filter(e -> e.getLevel() == Level.WARN && e.getMessage().getFormattedMessage().contains(queue)) + .toList(); + } + + private void assertWarning(String start) { + List<String> warnings = warnings().stream().map(e -> e.getMessage().getFormattedMessage()).toList(); + assertEquals(1, warnings.size(), "one WARN: " + warnings); + assertTrue(warnings.get(0).startsWith(start), warnings.get(0)); + assertTrue(warnings.get(0).contains("The listener container is stopped and destroyed in the background"), + warnings.get(0)); + } + + /** + * Waits until the test releases the listener container: as a JMS client waiting for a broker that does not answer, + * an interrupt does not end the wait. + */ + private void blockUntilReleased() { + blocked.countDown(); + boolean interrupted = false; + try { + while (release.getCount() > 0) { + try { + release.await(); + } catch (InterruptedException e) { + interrupted = true; + } + } + } finally { + if (interrupted) { + Thread.currentThread().interrupt(); + } + } + } + + private final class BlockingListenerContainer extends DefaultJmsMessageListenerContainer { + + private volatile ExecutorService taskExecutor; + private volatile boolean destroyed; + + BlockingListenerContainer(JmsEndpoint endpoint) { + super(endpoint); + } + + @Override + public void setTaskExecutor(Executor taskExecutor) { + super.setTaskExecutor(taskExecutor); + // the private thread pool of the consumer + this.taskExecutor = (ExecutorService) taskExecutor; + } + + @Override + protected void stopSharedConnection() { + super.stopSharedConnection(); + if (block == Block.STOP) { + blockUntilReleased(); + } + } + + @Override + protected void doShutdown() throws JMSException { + if (block == Block.DESTROY) { + blockUntilReleased(); + } + super.doShutdown(); + if (failDestroy) { + throw new JMSException("The broker does not answer"); + } + } + + @Override + public void destroy() { + super.destroy(); + destroyed = true; + } + } +}
