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 6452d71a8826edb933c4c789fac47325ab176943 Author: croway <[email protected]> AuthorDate: Wed Nov 25 18:06:09 2026 +0100 CAMEL-27009: camel-spring-rabbitmq - the suspend and stop of the listener container do not wait without bound for a broker that does not answer SpringRabbitMQConsumer suspended and stopped its listener container on the calling thread. The stop of a DirectMessageListenerContainer or SimpleMessageListenerContainer cancels its consumers (RabbitUtils.cancel -> ChannelN.basicCancel), which waits for basic.cancel-ok without reacting to an interrupt, up to the channelRpcTimeout of the RabbitMQ client (10 minutes by default) when the connection stopped answering: a route or CamelContext stop waited that long, past the graceful shutdown timeout. Spring AMQP offers no bounded stop: stop(Runnable) and shutdownTimeout only bound the wait for the consumers after the cancel. The stop (and destroy) of the listener container now runs on a cached thread pool of the component, created by the ExecutorServiceManager, and the consumer waits for it at most the shutdownAwaitTermination of the ExecutorServiceManager (10 seconds by default). When that time elapses, or the waiting thread is interrupted (the shutdown strategy cancels its task when its timeout elapses), the consumer logs a WARN with the endpoint and its queues and detaches the listener container: its stop goes on in the background, destroys it once the cancel returns, and logs a failure. A resume or start after such a suspend creates a new listener container, on the same queues (also a generated one), with a new declaring connection listener, instead of logging that the route must be restarted; a stop that follows has nothing to wait for. The component shuts the thread pool down without waiting when it stops. A listener container that stops in time behaves as before. --- .../catalog/docs/spring-rabbitmq-component.adoc | 7 + .../src/main/docs/spring-rabbitmq-component.adoc | 7 + .../springrabbit/SpringRabbitMQComponent.java | 38 ++ .../springrabbit/SpringRabbitMQConsumer.java | 212 +++++++- .../SpringRabbitMQConsumerStopTest.java | 559 +++++++++++++++++++++ .../RabbitMQConsumerSuspendResumeIT.java | 101 ++++ 6 files changed, 899 insertions(+), 25 deletions(-) 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 5552d8424e92..c0f1e60beabf 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,6 +125,13 @@ 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"> 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 5552d8424e92..c0f1e60beabf 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,6 +125,13 @@ 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"> diff --git a/components/camel-spring-parent/camel-spring-rabbitmq/src/main/java/org/apache/camel/component/springrabbit/SpringRabbitMQComponent.java b/components/camel-spring-parent/camel-spring-rabbitmq/src/main/java/org/apache/camel/component/springrabbit/SpringRabbitMQComponent.java index 14dfc8a4b829..3fd1fbbf2ce3 100644 --- a/components/camel-spring-parent/camel-spring-rabbitmq/src/main/java/org/apache/camel/component/springrabbit/SpringRabbitMQComponent.java +++ b/components/camel-spring-parent/camel-spring-rabbitmq/src/main/java/org/apache/camel/component/springrabbit/SpringRabbitMQComponent.java @@ -18,6 +18,9 @@ package org.apache.camel.component.springrabbit; import java.util.HashMap; import java.util.Map; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.locks.Lock; +import java.util.concurrent.locks.ReentrantLock; import org.apache.camel.Endpoint; import org.apache.camel.spi.Metadata; @@ -124,6 +127,9 @@ public class SpringRabbitMQComponent extends HeaderFilterStrategyComponent { + " For example to declare a queue with message ttl argument: queue.x-message-ttl=60000") private Map<String, Object> args; + private final Lock stopListenerContainerLock = new ReentrantLock(); + private ExecutorService stopListenerContainerExecutorService; + @Override protected void doInit() throws Exception { super.doInit(); @@ -139,6 +145,38 @@ public class SpringRabbitMQComponent extends HeaderFilterStrategyComponent { } } + @Override + protected void doStop() throws Exception { + stopListenerContainerLock.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 { + stopListenerContainerLock.unlock(); + } + super.doStop(); + } + + /** + * The thread pool that stops the listener containers of the consumers, so that they wait for a stop that waits for + * the broker with a bound: a cached thread pool, as such a stop can take long. + */ + ExecutorService getStopListenerContainerExecutorService() { + stopListenerContainerLock.lock(); + try { + if (stopListenerContainerExecutorService == null) { + stopListenerContainerExecutorService = getCamelContext().getExecutorServiceManager() + .newCachedThreadPool(this, "SpringRabbitMQStopListenerContainer"); + } + return stopListenerContainerExecutorService; + } finally { + stopListenerContainerLock.unlock(); + } + } + @Override protected Endpoint createEndpoint(String uri, String remaining, Map<String, Object> parameters) throws Exception { SpringRabbitMQEndpoint endpoint = new SpringRabbitMQEndpoint(uri, this, remaining); 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 b7a895ccdd65..57e07fdaecff 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 @@ -16,11 +16,19 @@ */ package org.apache.camel.component.springrabbit; +import java.util.Arrays; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.CompletionException; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.RejectedExecutionException; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.TimeoutException; import java.util.concurrent.atomic.AtomicBoolean; import org.apache.camel.Endpoint; import org.apache.camel.FailedToCreateConsumerException; import org.apache.camel.Processor; +import org.apache.camel.RuntimeCamelException; import org.apache.camel.Suspendable; import org.apache.camel.support.DefaultConsumer; import org.slf4j.Logger; @@ -37,10 +45,13 @@ public class SpringRabbitMQConsumer extends DefaultConsumer implements Suspendab private static final Logger LOG = LoggerFactory.getLogger(SpringRabbitMQConsumer.class); - private AbstractMessageListenerContainer listenerContainer; + private volatile AbstractMessageListenerContainer listenerContainer; private volatile EndpointMessageListener messageListener; private volatile boolean initialized; private volatile DeclaringConnectionListener declaringConnectionListener; + // the queues of the listener container that a suspend left to stop in the background: the next listener container + // consumes them, as only that listener container knows the name of a queue that it generated + private volatile String[] detachedQueueNames; public SpringRabbitMQConsumer(Endpoint endpoint, Processor processor, AbstractMessageListenerContainer listenerContainer) { super(endpoint, processor); @@ -108,13 +119,7 @@ public class SpringRabbitMQConsumer extends DefaultConsumer implements Suspendab if (listenerContainer == null) { createMessageListenerContainer(); } - - try { - prepareAndStartListenerContainer(); - } catch (Exception e) { - removeDeclaringConnectionListener(); - throw e; - } + doPrepareAndStartListenerContainer(); // mark as initialized for the first time initialized = true; @@ -123,17 +128,20 @@ public class SpringRabbitMQConsumer extends DefaultConsumer implements Suspendab @Override protected void doStop() throws Exception { removeDeclaringConnectionListener(); - if (listenerContainer != null) { - stopAndDestroyListenerContainer(); - } + // also without a listener container (a suspend that did not wait for it to stop), so that a start creates + // everything again + stopAndDestroyListenerContainer(); super.doStop(); } @Override protected void doSuspend() throws Exception { - if (listenerContainer != null) { - listenerContainer.stop(); + AbstractMessageListenerContainer container = listenerContainer; + if (container != null && !stopListenerContainer(container, false)) { + // the listener container stops in the background: resume creates a new one, which that stop cannot touch + detachedQueueNames = container.getQueueNames(); + listenerContainer = null; } } @@ -142,19 +150,43 @@ public class SpringRabbitMQConsumer extends DefaultConsumer implements Suspendab // we may not have been started before, and now the end user calls resume, so lets handle that and start it first if (!initialized) { doStart(); + } else if (listenerContainer != null) { + startListenerContainer(); } else { - if (listenerContainer != null) { - startListenerContainer(); - } else { - LOG.warn( - "The listenerContainer is not instantiated. Probably there was a timeout during the Suspend operation. Please restart your consumer route."); - } + // the suspend did not wait for the listener container to stop, which goes on in the background + LOG.debug("Creating a new listener container for {}, as the previous one did not stop in time when the consumer" + + " was suspended", + getEndpoint()); + // it declares with the previous listener container, also when the new one cannot be created + removeDeclaringConnectionListener(); + createMessageListenerContainer(); + doPrepareAndStartListenerContainer(); + } + } + + /** + * Prepares and starts the listener container. The connection listener that declares on new connections replaces the + * one of a previous preparation (a suspended consumer that is started, or resumed after its listener container did + * not stop in time), and is removed when the start fails. + */ + private void doPrepareAndStartListenerContainer() { + removeDeclaringConnectionListener(); + try { + prepareAndStartListenerContainer(); + } catch (Exception e) { + removeDeclaringConnectionListener(); + throw e; } } protected void createMessageListenerContainer() { listenerContainer = getEndpoint().createMessageListenerContainer(); listenerContainer.setMessageListener(getEndpointMessageListener()); + String[] queueNames = detachedQueueNames; + detachedQueueNames = null; + if (queueNames != null && listenerContainer.getQueueNames().length == 0) { + listenerContainer.setQueueNames(queueNames); + } } protected void prepareAndStartListenerContainer() { @@ -223,16 +255,146 @@ public class SpringRabbitMQConsumer extends DefaultConsumer implements Suspendab } protected void stopAndDestroyListenerContainer() { - if (listenerContainer != null) { - listenerContainer.stop(); - listenerContainer.destroy(); - } - + AbstractMessageListenerContainer container = listenerContainer; // 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 + // then we will use updated configuration from the endpoint that may have been managed using JMX listenerContainer = null; messageListener = null; initialized = false; + detachedQueueNames = null; + + if (container != null) { + stopListenerContainer(container, true); + } + } + + /** + * 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). + * <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. + * + * @param container the listener container, which the caller detaches from this consumer when it stops in the + * background + * @param destroy whether to destroy the listener container once it stopped + * @return {@code true} if the listener container stopped in time, {@code false} if it stops in the + * background + */ + private boolean stopListenerContainer(AbstractMessageListenerContainer container, boolean destroy) { + long timeout = getEndpoint().getCamelContext().getExecutorServiceManager().getShutdownAwaitTermination(); + // 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); + CompletableFuture<Void> stop; + try { + stop = CompletableFuture.runAsync(() -> doStopListenerContainer(container, destroy, waiting), + getEndpoint().getComponent().getStopListenerContainerExecutorService()); + } catch (RejectedExecutionException e) { + // the component stopped meanwhile: as before, on this thread + stopAndDestroy(container, destroy); + return true; + } + + try { + stop.get(timeout, TimeUnit.MILLISECONDS); + return true; + } catch (ExecutionException e) { + 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); + return false; + } + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + 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" + + " started again.", + getEndpoint(), Arrays.toString(container.getQueueNames())); + return false; + } + } + // the stop ended meanwhile + try { + stop.join(); + } catch (CompletionException e) { + throw stopFailure(e.getCause()); + } + return true; + } + + /** + * 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. + */ + private void doStopListenerContainer( + AbstractMessageListenerContainer container, boolean destroy, AtomicBoolean waiting) { + RuntimeException failure = null; + try { + stopAndDestroy(container, destroy); + } catch (RuntimeException e) { + failure = e; + } + if (waiting.compareAndSet(true, false)) { + if (failure != null) { + throw failure; + } + return; + } + + String queues = Arrays.toString(container.getQueueNames()); + if (failure != null) { + LOG.warn("Error stopping the listener container of {} (queues: {}) in the background. This exception is" + + " ignored.", + getEndpoint(), queues, failure); + } + if (!destroy) { + try { + container.destroy(); + } catch (RuntimeException e) { + LOG.warn("Error destroying the listener container of {} (queues: {}) in the background. This exception" + + " is ignored.", + getEndpoint(), queues, e); + } + } + if (failure == null) { + LOG.info("The listener container of {} (queues: {}) stopped in the background", getEndpoint(), queues); + } + } + + private static void stopAndDestroy(AbstractMessageListenerContainer container, boolean destroy) { + try { + container.stop(); + } catch (RuntimeException e) { + if (destroy) { + try { + container.destroy(); + } catch (RuntimeException destroyFailure) { + e.addSuppressed(destroyFailure); + } + } + throw e; + } + if (destroy) { + container.destroy(); + } + } + + private static RuntimeException stopFailure(Throwable cause) { + if (cause instanceof Error error) { + throw error; + } + return RuntimeCamelException.wrapRuntimeException(cause); } /** 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 new file mode 100644 index 000000000000..288f35ec0234 --- /dev/null +++ b/components/camel-spring-parent/camel-spring-rabbitmq/src/test/java/org/apache/camel/component/springrabbit/SpringRabbitMQConsumerStopTest.java @@ -0,0 +1,559 @@ +/* + * 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.springrabbit; + +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.UUID; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.CompletionException; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.CopyOnWriteArrayList; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicReference; + +import com.rabbitmq.client.AMQP; +import com.rabbitmq.client.Channel; +import com.rabbitmq.client.Consumer; +import com.rabbitmq.client.Envelope; +import org.apache.camel.CamelContext; +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.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.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; +import org.springframework.amqp.core.AmqpAdmin; +import org.springframework.amqp.core.Queue; +import org.springframework.amqp.rabbit.connection.Connection; +import org.springframework.amqp.rabbit.connection.ConnectionFactory; +import org.springframework.amqp.rabbit.connection.ConnectionListener; +import org.springframework.amqp.rabbit.listener.AbstractMessageListenerContainer; + +import static org.awaitility.Awaitility.await; +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyBoolean; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.Mockito.doAnswer; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +/** + * The stop of a listener container cancels its consumers 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). The suspend and the stop of the consumer must not wait for it without a bound, and a resume or a + * start must work with a new listener container meanwhile. + * <p/> + * The connection factory is a mock, whose channels answer a cancel only when the test lets them, once they stopped + * answering. + */ +class SpringRabbitMQConsumerStopTest { + + // how long the consumer waits for its listener container to stop (shutdownAwaitTermination) + private static final long BOUND = 1000; + // 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 + // time the broker takes to answer (when the test lets it) + private static final long STOP_TIME = 20000; + + // the exchange and the queue, unique to the test: the log of the test names them only + private final String name = "orders-" + UUID.randomUUID(); + + private final List<AbstractMessageListenerContainer> containers = new CopyOnWriteArrayList<>(); + private final Set<AbstractMessageListenerContainer> destroyed = ConcurrentHashMap.newKeySet(); + // the channels on which a consumer subscribed, in that order + private final List<FakeChannel> subscribed = new CopyOnWriteArrayList<>(); + private final List<ConnectionListener> connectionListeners = new CopyOnWriteArrayList<>(); + private final List<ConnectionListener> removedConnectionListeners = new CopyOnWriteArrayList<>(); + private final AtomicInteger consumerTags = new AtomicInteger(); + // the broker answers the cancel on a channel that stopped answering, only when the test lets it + private final CountDownLatch answer = new CountDownLatch(1); + private final List<LogEvent> events = new CopyOnWriteArrayList<>(); + private final ExecutorService testThreads = Executors.newCachedThreadPool(); + private CamelContext context; + private AbstractAppender appender; + private Logger logger; + + @BeforeEach + void setUp() { + context = new DefaultCamelContext(); + context.getExecutorServiceManager().setShutdownAwaitTermination(BOUND); + // longer than the test waits for a stop: the stop must not end because the graceful shutdown timed out + context.getShutdownStrategy().setTimeout(60); + context.getRegistry().bind("cf", connectionFactory()); + AmqpAdmin admin = mock(AmqpAdmin.class); + 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.setListenerContainerFactory(this::createListenerContainer); + + appender = new AbstractAppender("consumerStop", null, null, true, Property.EMPTY_ARRAY) { + @Override + public void append(LogEvent event) { + events.add(event.toImmutable()); + } + }; + appender.start(); + logger = (Logger) LogManager.getLogger(SpringRabbitMQConsumer.class); + logger.addAppender(appender); + } + + @AfterEach + void tearDown() { + // the broker answers: a stop that waits for it ends + answer.countDown(); + logger.removeAppender(appender); + appender.stop(); + context.stop(); + testThreads.shutdownNow(); + } + + @ParameterizedTest + @ValueSource(strings = { "DMLC", "SMLC" }) + void suspendDoesNotWaitForTheBrokerToAnswerTheCancel(String type) throws Exception { + startRoute(type); + FakeChannel channel = subscribed(0); + channel.stopAnswering(); + + suspendThatDoesNotWait(); + + 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"), + warnings.get(0)); + AbstractMessageListenerContainer container = containers.get(0); + assertFalse(destroyed.contains(container)); + + // the stop that follows has no listener container to wait for + CompletableFuture<Void> stop = inAnotherThread(() -> context.getRouteController().stopRoute("orders")); + await("the stop returns").atMost(STOP_TIME, TimeUnit.MILLISECONDS).until(stop::isDone); + stop.join(); + assertEquals(ServiceStatus.Stopped, context.getRouteController().getRouteStatus("orders")); + assertEquals(1, warnings().size(), "no other WARN: " + warnings()); + + // the broker answers: the stop of the listener container ends, and destroys it + answer.countDown(); + await("the listener container is destroyed").atMost(10, TimeUnit.SECONDS) + .until(() -> destroyed.contains(container)); + assertFalse(container.isRunning()); + assertEquals(1, containers.size()); + } + + @ParameterizedTest + @ValueSource(strings = { "DMLC", "SMLC" }) + void contextStopDoesNotWaitForTheBrokerToAnswerTheCancel(String type) throws Exception { + startRoute(type); + subscribed(0).stopAnswering(); + + CompletableFuture<Void> stop = inAnotherThread(context::stop); + + await("the context stops").atMost(STOP_TIME, TimeUnit.MILLISECONDS).until(stop::isDone); + stop.join(); + assertTrue(context.isStopped()); + // the graceful shutdown suspends the consumer, which does not wait; its stop then has nothing to wait for + assertEquals(1, warnings().size(), "one WARN: " + warnings()); + AbstractMessageListenerContainer container = containers.get(0); + assertFalse(destroyed.contains(container)); + + answer.countDown(); + await("the listener container is destroyed").atMost(10, TimeUnit.SECONDS) + .until(() -> destroyed.contains(container)); + assertFalse(container.isRunning()); + } + + @ParameterizedTest + @ValueSource(strings = { "DMLC", "SMLC" }) + void interruptedSuspendDoesNotWaitForTheBrokerToAnswerTheCancel(String type) throws Exception { + // the graceful shutdown interrupts the suspend when its timeout elapses, which can be before this bound + context.getExecutorServiceManager().setShutdownAwaitTermination(60000); + startRoute(type); + FakeChannel channel = subscribed(0); + channel.stopAnswering(); + SpringRabbitMQConsumer consumer = (SpringRabbitMQConsumer) context.getRoute("orders").getConsumer(); + AtomicReference<Thread> suspending = new AtomicReference<>(); + AtomicBoolean interruptedAfterSuspend = new AtomicBoolean(); + CompletableFuture<Void> suspend = inAnotherThread(() -> { + suspending.set(Thread.currentThread()); + consumer.suspend(); + interruptedAfterSuspend.set(Thread.currentThread().isInterrupted()); + }); + await("the cancel waits for the broker").atMost(10, TimeUnit.SECONDS).until(channel::isCancelling); + + suspending.get().interrupt(); + + await("the suspend returns").atMost(STOP_TIME, TimeUnit.MILLISECONDS).until(suspend::isDone); + suspend.join(); + assertTrue(consumer.isSuspended()); + assertTrue(interruptedAfterSuspend.get(), "the interrupt is kept"); + List<String> warnings = warnings(); + assertEquals(1, warnings.size(), "one WARN: " + warnings); + assertTrue(warnings.get(0).startsWith("Interrupted while waiting for the listener container"), warnings.get(0)); + + answer.countDown(); + await("the listener container is destroyed").atMost(10, TimeUnit.SECONDS) + .until(() -> destroyed.contains(containers.get(0))); + } + + @ParameterizedTest + @ValueSource(strings = { "DMLC", "SMLC" }) + void resumeAfterASuspendThatDidNotWaitConsumesWithANewListenerContainer(String type) throws Exception { + startRoute(type); + subscribed(0).stopAnswering(); + suspendThatDoesNotWait(); + assertEquals(1, connectionListeners.size()); + + // while the previous listener container still waits for the broker + context.getRouteController().resumeRoute("orders"); + + assertEquals(ServiceStatus.Started, context.getRouteController().getRouteStatus("orders")); + assertEquals(2, containers.size()); + AbstractMessageListenerContainer previous = containers.get(0); + AbstractMessageListenerContainer current = containers.get(1); + assertTrue(current.isRunning()); + // the connection listener that declares on new connections declares with the new listener container + assertEquals(2, connectionListeners.size()); + assertEquals(List.of(connectionListeners.get(0)), removedConnectionListeners); + MockEndpoint mock = context.getEndpoint("mock:orders", MockEndpoint.class); + mock.expectedBodiesReceived("Hello", "World"); + subscribed(1).deliver("Hello"); + + // the broker answers: the stop of the previous listener container ends, and does not touch the current one + answer.countDown(); + await("the previous listener container is destroyed").atMost(10, TimeUnit.SECONDS) + .until(() -> destroyed.contains(previous)); + assertFalse(previous.isRunning()); + assertFalse(destroyed.contains(current)); + assertTrue(current.isRunning()); + subscribed(1).deliver("World"); + mock.assertIsSatisfied(); + assertEquals(1, warnings().size(), "one WARN: " + warnings()); + + context.getExecutorServiceManager().setShutdownAwaitTermination(HEALTHY_BOUND); + context.getRouteController().stopRoute("orders"); + assertTrue(destroyed.contains(current)); + assertEquals(connectionListeners, removedConnectionListeners); + } + + @ParameterizedTest + @ValueSource(strings = { "DMLC", "SMLC" }) + void resumeAfterASuspendThatDidNotWaitConsumesTheGeneratedQueue(String type) throws Exception { + // no queues: the consumer consumes a queue with a generated name, which only its listener container knows + startRouteFrom("spring-rabbitmq:" + name + "?connectionFactory=#cf&routingKey=new" + + "&messageListenerContainerType=" + type); + FakeChannel channel = subscribed(0); + String generated = channel.queue; + assertTrue(generated.startsWith("spring.gen-"), generated); + channel.stopAnswering(); + suspendThatDoesNotWait(); + + context.getRouteController().resumeRoute("orders"); + + // the new listener container consumes the same queue, rather than a new one + assertEquals(generated, subscribed(1).queue); + assertArrayEquals(new String[] { generated }, containers.get(1).getQueueNames()); + } + + @ParameterizedTest + @ValueSource(strings = { "DMLC", "SMLC" }) + void startAfterASuspendThatDidNotWaitReplacesTheConnectionListener(String type) throws Exception { + startRoute(type); + subscribed(0).stopAnswering(); + suspendThatDoesNotWait(); + SpringRabbitMQConsumer consumer = (SpringRabbitMQConsumer) context.getRoute("orders").getConsumer(); + + // a start of the suspended consumer, rather than a resume + consumer.start(); + + assertTrue(consumer.isStarted()); + assertEquals(2, containers.size()); + assertTrue(containers.get(1).isRunning()); + assertEquals(2, connectionListeners.size()); + assertEquals(List.of(connectionListeners.get(0)), removedConnectionListeners); + + answer.countDown(); + context.getExecutorServiceManager().setShutdownAwaitTermination(HEALTHY_BOUND); + context.getRouteController().stopRoute("orders"); + assertEquals(connectionListeners, removedConnectionListeners); + } + + @ParameterizedTest + @ValueSource(strings = { "DMLC", "SMLC" }) + void consumerStopDoesNotWaitForTheBrokerToAnswerTheCancel(String type) throws Exception { + startRoute(type); + subscribed(0).stopAnswering(); + SpringRabbitMQConsumer consumer = (SpringRabbitMQConsumer) context.getRoute("orders").getConsumer(); + + CompletableFuture<Void> stop = inAnotherThread(consumer::stop); + + await("the consumer stops").atMost(STOP_TIME, TimeUnit.MILLISECONDS).until(stop::isDone); + stop.join(); + assertTrue(consumer.isStopped()); + assertEquals(1, warnings().size(), "one WARN: " + warnings()); + assertEquals(connectionListeners, removedConnectionListeners); + + // it starts again with a new listener container, while the previous one still waits for the broker + consumer.start(); + assertEquals(2, containers.size()); + AbstractMessageListenerContainer previous = containers.get(0); + AbstractMessageListenerContainer current = containers.get(1); + MockEndpoint mock = context.getEndpoint("mock:orders", MockEndpoint.class); + mock.expectedBodiesReceived("Hello"); + subscribed(1).deliver("Hello"); + mock.assertIsSatisfied(); + + answer.countDown(); + await("the previous listener container is destroyed").atMost(10, TimeUnit.SECONDS) + .until(() -> destroyed.contains(previous)); + assertFalse(destroyed.contains(current)); + assertTrue(current.isRunning()); + } + + @ParameterizedTest + @ValueSource(strings = { "DMLC", "SMLC" }) + void suspendResumeAndStopWhileTheBrokerAnswers(String type) throws Exception { + context.getExecutorServiceManager().setShutdownAwaitTermination(HEALTHY_BOUND); + startRoute(type); + subscribed(0); + AbstractMessageListenerContainer container = containers.get(0); + + context.getRouteController().suspendRoute("orders"); + + assertEquals(ServiceStatus.Suspended, context.getRouteController().getRouteStatus("orders")); + assertFalse(container.isRunning()); + assertFalse(destroyed.contains(container)); + + context.getRouteController().resumeRoute("orders"); + + // the same listener container consumes again + assertEquals(ServiceStatus.Started, context.getRouteController().getRouteStatus("orders")); + assertEquals(List.of(container), containers); + assertTrue(container.isRunning()); + assertEquals(1, connectionListeners.size()); + assertTrue(removedConnectionListeners.isEmpty()); + MockEndpoint mock = context.getEndpoint("mock:orders", MockEndpoint.class); + mock.expectedBodiesReceived("Hello"); + subscribed(1).deliver("Hello"); + mock.assertIsSatisfied(); + + context.getRouteController().stopRoute("orders"); + + assertTrue(destroyed.contains(container)); + assertEquals(connectionListeners, removedConnectionListeners); + 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); + } + + private void startRouteFrom(String uri) throws Exception { + context.addRoutes(new RouteBuilder() { + @Override + public void configure() { + from(uri).routeId("orders").to("mock:orders"); + } + }); + context.start(); + } + + private void suspendThatDoesNotWait() { + CompletableFuture<Void> suspend = inAnotherThread(() -> context.getRouteController().suspendRoute("orders")); + await("the suspend returns").atMost(STOP_TIME, TimeUnit.MILLISECONDS).until(suspend::isDone); + suspend.join(); + assertEquals(ServiceStatus.Suspended, context.getRouteController().getRouteStatus("orders")); + } + + /** + * Creates the listener container of the given type, as the {@link DefaultListenerContainerFactory} does for what + * the test needs, and keeps track of it and of its destroy. + */ + private AbstractMessageListenerContainer createListenerContainer(SpringRabbitMQEndpoint endpoint) { + AbstractMessageListenerContainer container; + if (SpringRabbitMQConstants.SIMPLE_MESSAGE_LISTENER_CONTAINER.equals(endpoint.getMessageListenerContainerType())) { + CamelSimpleMessageListenerContainer simple = new CamelSimpleMessageListenerContainer(endpoint) { + @Override + public void destroy() { + destroyed.add(this); + super.destroy(); + } + }; + // the consumer thread notices a cancel sooner + simple.setReceiveTimeout(50); + container = simple; + } else { + container = new CamelDirectMessageListenerContainer(endpoint) { + @Override + public void destroy() { + destroyed.add(this); + super.destroy(); + } + }; + } + if (endpoint.getQueues() != null) { + container.setQueueNames(endpoint.getQueues()); + } + container.setAmqpAdmin(endpoint.getComponent().getAmqpAdmin()); + container.setAutoDeclare(endpoint.isAutoDeclare()); + container.setShutdownTimeout(endpoint.getComponent().getShutdownTimeout()); + containers.add(container); + return container; + } + + private ConnectionFactory connectionFactory() { + ConnectionFactory cf = mock(ConnectionFactory.class); + Connection connection = mock(Connection.class); + when(connection.isOpen()).thenReturn(true); + when(connection.createChannel(anyBoolean())).thenAnswer(invocation -> new FakeChannel().channel); + when(cf.createConnection()).thenReturn(connection); + when(cf.getHost()).thenReturn("localhost"); + doAnswer(invocation -> connectionListeners.add(invocation.getArgument(0))) + .when(cf).addConnectionListener(any(ConnectionListener.class)); + when(cf.removeConnectionListener(any(ConnectionListener.class))) + .thenAnswer(invocation -> removedConnectionListeners.add(invocation.getArgument(0))); + return cf; + } + + private FakeChannel subscribed(int index) { + await("a consumer subscribes").atMost(10, TimeUnit.SECONDS).until(() -> subscribed.size() > index); + return subscribed.get(index); + } + + /** + * The WARNs about the consumer of this test: the logger is shared with the other tests of the JVM. + */ + private List<String> warnings() { + return events.stream().filter(e -> e.getLevel() == Level.WARN).map(e -> e.getMessage().getFormattedMessage()) + .filter(message -> message.contains(name)).toList(); + } + + private CompletableFuture<Void> inAnotherThread(Action action) { + return CompletableFuture.runAsync(() -> { + try { + action.run(); + } catch (Exception e) { + throw new CompletionException(e); + } + }, testThreads); + } + + @FunctionalInterface + private interface Action { + void run() throws Exception; + } + + /** + * A channel of the broker, on which a consumer subscribes. Once it stopped answering, a cancel waits for the broker + * to answer, as {@code ChannelN.basicCancel} does, and ignores an interrupt. + */ + private final class FakeChannel { + + private final Channel channel = mock(Channel.class); + private final Map<String, Consumer> consumers = new ConcurrentHashMap<>(); + private final CountDownLatch cancelling = new CountDownLatch(1); + private final AtomicInteger deliveryTags = new AtomicInteger(); + private volatile boolean answering = true; + private volatile String queue; + + private FakeChannel() throws IOException { + when(channel.isOpen()).thenReturn(true); + when(channel.queueDeclarePassive(anyString())).thenReturn(mock(AMQP.Queue.DeclareOk.class)); + when(channel.basicConsume(anyString(), anyBoolean(), anyString(), anyBoolean(), anyBoolean(), any(), + any(Consumer.class))).thenAnswer(invocation -> { + String tag = "amq.ctag-" + consumerTags.incrementAndGet(); + queue = invocation.getArgument(0); + Consumer consumer = invocation.getArgument(6); + consumers.put(tag, consumer); + consumer.handleConsumeOk(tag); + subscribed.add(this); + return tag; + }); + doAnswer(invocation -> { + cancel(invocation.getArgument(0)); + return null; + }).when(channel).basicCancel(anyString()); + } + + private void stopAnswering() { + answering = false; + } + + private boolean isCancelling() { + return cancelling.getCount() == 0; + } + + private void cancel(String tag) { + Consumer consumer = consumers.remove(tag); + if (!answering) { + cancelling.countDown(); + awaitAnswer(); + } + consumer.handleCancelOk(tag); + } + + private void awaitAnswer() { + boolean interrupted = false; + try { + while (true) { + try { + // a safety net, so that a test that does not let the broker answer cannot hang the build + if (!answer.await(120, TimeUnit.SECONDS)) { + throw new IllegalStateException("the test did not let the broker answer"); + } + return; + } catch (InterruptedException e) { + interrupted = true; + } + } + } finally { + if (interrupted) { + Thread.currentThread().interrupt(); + } + } + } + + private void deliver(String body) throws IOException { + Map.Entry<String, Consumer> consumer = consumers.entrySet().iterator().next(); + consumer.getValue().handleDelivery(consumer.getKey(), + new Envelope(deliveryTags.incrementAndGet(), false, name, "new"), + new AMQP.BasicProperties.Builder().contentType("text/plain").build(), + body.getBytes(StandardCharsets.UTF_8)); + } + } +} 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 new file mode 100644 index 000000000000..19ffbe21325f --- /dev/null +++ b/components/camel-spring-parent/camel-spring-rabbitmq/src/test/java/org/apache/camel/component/springrabbit/integration/RabbitMQConsumerSuspendResumeIT.java @@ -0,0 +1,101 @@ +/* + * 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.springrabbit.integration; + +import java.util.Properties; +import java.util.concurrent.TimeUnit; + +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.junit.jupiter.api.AfterEach; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; +import org.springframework.amqp.rabbit.connection.CachingConnectionFactory; +import org.springframework.amqp.rabbit.core.RabbitAdmin; + +import static org.awaitility.Awaitility.await; +import static org.junit.jupiter.api.Assertions.assertEquals; + +/** + * A route that is suspended and resumed consumes again, with either type of listener container: while it is suspended, + * the queue has no consumer and keeps the message sent meanwhile, which is consumed once the route is resumed. + */ +public class RabbitMQConsumerSuspendResumeIT extends RabbitMQITSupport { + + // the test checks the queue with its own connection factory + private CachingConnectionFactory testConnectionFactory; + + @AfterEach + void destroyTestConnectionFactory() { + if (testConnectionFactory != null) { + testConnectionFactory.destroy(); + } + } + + @ParameterizedTest + @ValueSource(strings = { "DMLC", "SMLC" }) + public void testSuspendAndResume(String type) throws Exception { + String queue = uniqueName(type + "-queue"); + testConnectionFactory = (CachingConnectionFactory) createConnectionFactory(false); + RabbitAdmin admin = new RabbitAdmin(testConnectionFactory); + MockEndpoint mock = getMockEndpoint("mock:" + type); + mock.expectedBodiesReceived("order 1"); + template.sendBody("direct:" + type, "order 1"); + MockEndpoint.assertIsSatisfied(context, 30, TimeUnit.SECONDS); + + context.getRouteController().suspendRoute(type); + + assertEquals(ServiceStatus.Suspended, context.getRouteController().getRouteStatus(type)); + mock.reset(); + mock.expectedBodiesReceived("order 2"); + template.sendBody("direct:" + type, "order 2"); + // the message waits in the queue, which has no consumer + await().atMost(30, TimeUnit.SECONDS) + .until(() -> count(admin, queue, RabbitAdmin.QUEUE_MESSAGE_COUNT) == 1 + && count(admin, queue, RabbitAdmin.QUEUE_CONSUMER_COUNT) == 0); + + context.getRouteController().resumeRoute(type); + + assertEquals(ServiceStatus.Started, context.getRouteController().getRouteStatus(type)); + MockEndpoint.assertIsSatisfied(context, 30, TimeUnit.SECONDS); + } + + private static int count(RabbitAdmin admin, String queue, Object property) { + Properties properties = admin.getQueueProperties(queue); + return properties == null ? -1 : ((Number) properties.get(property)).intValue(); + } + + @Override + protected RoutesBuilder createRouteBuilder() { + return new RouteBuilder() { + @Override + public void configure() { + for (String type : new String[] { "DMLC", "SMLC" }) { + from("direct:" + type) + .to("spring-rabbitmq:" + uniqueName(type) + "?routingKey=new"); + + from("spring-rabbitmq:" + uniqueName(type) + "?queues=" + uniqueName(type + "-queue") + + "&routingKey=new&messageListenerContainerType=" + type) + .routeId(type) + .to("mock:" + type); + } + } + }; + } +}
