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 348ad2bd500a4379ef04f3d06928d3c56cba4715 Author: croway <[email protected]> AuthorDate: Wed Nov 25 17:13:54 2026 +0100 CAMEL-27009: camel-core - name the consumer whose suspend or stop holds up the shutdown after the timeout When the shutdown timeout elapses while the shutdown task is still inside the suspend or stop of a consumer, a WARN names the route, the endpoint it consumes from, and the frames where the call waits. The forced shutdown, and a later stop or start of the route, wait for the same consumer until that call returns: the stop stays synchronous (as decided in CAMEL-7623 and CAMEL-13310), and the components bound their own calls. The javadoc of DefaultShutdownStrategy and ShutdownStrategy.setTimeout, and the graceful shutdown page, say that the timeout is when Camel switches to the forced shutdown, and does not bound the suspend or stop of a consumer. --- .../org/apache/camel/spi/ShutdownStrategy.java | 4 + .../camel/impl/engine/DefaultShutdownStrategy.java | 89 +++++- ...DefaultShutdownStrategyBlockedConsumerTest.java | 303 +++++++++++++++++++++ .../modules/ROOT/pages/graceful-shutdown.adoc | 19 ++ 4 files changed, 406 insertions(+), 9 deletions(-) diff --git a/core/camel-api/src/main/java/org/apache/camel/spi/ShutdownStrategy.java b/core/camel-api/src/main/java/org/apache/camel/spi/ShutdownStrategy.java index ada701b566f8..32e37e7bd1b8 100644 --- a/core/camel-api/src/main/java/org/apache/camel/spi/ShutdownStrategy.java +++ b/core/camel-api/src/main/java/org/apache/camel/spi/ShutdownStrategy.java @@ -120,6 +120,10 @@ public interface ShutdownStrategy extends StaticService { * {@link Long#MAX_VALUE} * <p> * The default timeout unit is <code>SECONDS</code> + * <p> + * When the timeout elapses, the remaining consumers are shutdown now or ignored (see + * {@link #setShutdownNowOnTimeout(boolean)}). The timeout does not bound the suspend or stop of a consumer: one + * that does not return makes the shutdown wait until it returns. * * @throws IllegalArgumentException if the timeout value is 0 or negative * @param timeout timeout diff --git a/core/camel-base-engine/src/main/java/org/apache/camel/impl/engine/DefaultShutdownStrategy.java b/core/camel-base-engine/src/main/java/org/apache/camel/impl/engine/DefaultShutdownStrategy.java index 86375b8a7fee..9253f904c5c8 100644 --- a/core/camel-base-engine/src/main/java/org/apache/camel/impl/engine/DefaultShutdownStrategy.java +++ b/core/camel-base-engine/src/main/java/org/apache/camel/impl/engine/DefaultShutdownStrategy.java @@ -90,9 +90,15 @@ import org.slf4j.LoggerFactory; * and hence why a timeout value can be set. When the timeout triggers you can also specify whether the remainder * consumers should be shutdown now or ignore. * <p> - * Will by default use a timeout of 45 seconds by which it will shutdown now the remaining consumers. This ensures that - * when shutting down Camel it at some point eventually will shutdown. This behavior can of course be configured using - * the {@link #setTimeout(long)} and {@link #setShutdownNowOnTimeout(boolean)} methods. + * Will by default use a timeout of 45 seconds by which it will shutdown now the remaining consumers. This behavior can + * of course be configured using the {@link #setTimeout(long)} and {@link #setShutdownNowOnTimeout(boolean)} methods. + * <p> + * The timeout is when the strategy stops waiting and switches to the forced shutdown: it does not bound the suspend or + * stop of a consumer. A consumer whose suspend or stop does not return (such as a client call that waits for a reply on + * a connection that stopped answering, and ignores the interrupt) makes the shutdown wait until it returns, as the + * forced shutdown, and a later stop or start of the route, need the same consumer. When the timeout elapses while such + * a call runs, a WARN names the consumer, its route, and where the call waits. A component is expected to bound the + * calls that its consumers make while they suspend or stop. * <p> * Routes will by default be shutdown in the reverse order in which they were started. You can customize this using the * {@link #setShutdownRoutesInReverseOrder(boolean)} method. @@ -218,12 +224,14 @@ public class DefaultShutdownStrategy extends ServiceSupport implements ShutdownS // force or cut short the graceful shutdown of another. The fields are only set for the getters. final AtomicBoolean shutdownTimeoutOccurred = new AtomicBoolean(); Future<?> future = null; + ShutdownTask task = null; boolean interrupted = false; timeoutOccurred.set(false); try { - future = getExecutorService().submit(new ShutdownTask( + task = new ShutdownTask( context, routesOrdered, timeout, timeUnit, suspendOnly, - abortAfterTimeout, shutdownTimeoutOccurred, isLogInflightExchangesOnTimeout())); + abortAfterTimeout, shutdownTimeoutOccurred, isLogInflightExchangesOnTimeout()); + future = getExecutorService().submit(task); currentShutdownTaskFuture.set(future); future.get(timeout, timeUnit); } catch (RejectedExecutionException e) { @@ -257,6 +265,7 @@ public class DefaultShutdownStrategy extends ServiceSupport implements ShutdownS // we attempt to force shutdown so lets log the current inflight exchanges which are affected logInflightExchanges(context, routesOrdered, isLogInflightExchangesOnTimeout()); + logConsumerInProgress(task); return false; } else { @@ -266,6 +275,8 @@ public class DefaultShutdownStrategy extends ServiceSupport implements ShutdownS // we attempt to force shutdown so lets log the current inflight exchanges which are affected logInflightExchanges(context, routesOrdered, isLogInflightExchangesOnTimeout()); + // before the forced shutdown, which waits for a consumer whose suspend or stop has not returned + logConsumerInProgress(task); // force the routes to shutdown now shutdownRoutesNow(routesOrdered); @@ -281,6 +292,7 @@ public class DefaultShutdownStrategy extends ServiceSupport implements ShutdownS + " Notice: some resources may still be running as graceful shutdown did not complete successfully."); logInflightExchanges(context, routesOrdered, isLogInflightExchangesOnTimeout()); + logConsumerInProgress(task); } } } finally { @@ -485,6 +497,44 @@ public class DefaultShutdownStrategy extends ServiceSupport implements ShutdownS LOG.trace("Suspend complete for: {}", consumer); } + /** + * Logs the consumer whose suspend or stop the shutdown task still runs when the timeout elapsed, with where the + * call waits: the forced shutdown, and a later stop or start of the route, wait for the same consumer until that + * call returns, so this names what a stop that hangs waits for. + */ + private static void logConsumerInProgress(ShutdownTask task) { + ConsumerInProgress inProgress = task != null ? task.consumerInProgress : null; + if (inProgress == null) { + return; + } + String strategy = DefaultShutdownStrategy.class.getName(); + StringBuilder where = new StringBuilder(); + for (StackTraceElement element : inProgress.thread().getStackTrace()) { + String className = element.getClassName(); + if (className.equals(strategy) || className.startsWith(strategy + "$")) { + // the frames below are the shutdown strategy calling the consumer + break; + } + where.append(System.lineSeparator()).append("\tat ").append(element); + } + if (task.consumerInProgress != inProgress) { + // the call returned meanwhile (and the stack is no longer the one of the call) + return; + } + // use basic endpoint uri to not log verbose details or potential sensitive data + String uri = URISupport.sanitizeUri(inProgress.consumer().getEndpoint().getEndpointBaseUri()); + LOG.warn("The {} of the consumer of route: {} (consuming from: {}) has not returned within the timeout." + + " Stopping or starting this route waits until it returns. The thread {} running it waits at:{}", + inProgress.suspend() ? "suspend" : "stop", inProgress.routeId(), uri, inProgress.thread().getName(), + where); + } + + /** + * The suspend or stop of a consumer that a {@link ShutdownTask} runs. + */ + private record ConsumerInProgress(String routeId, Consumer consumer, boolean suspend, Thread thread) { + } + private ExecutorService getExecutorService() { executorLock.lock(); try { @@ -590,6 +640,9 @@ public class DefaultShutdownStrategy extends ServiceSupport implements ShutdownS private final TimeUnit timeUnit; private final AtomicBoolean timeoutOccurred; private final boolean logInflightExchangesOnTimeout; + // the suspend or stop of a consumer that this task runs, so the thread that waits for this task can name the + // consumer when the timeout elapses + private volatile ConsumerInProgress consumerInProgress; ShutdownTask(CamelContext context, List<RouteStartupOrder> routes, long timeout, TimeUnit timeUnit, boolean suspendOnly, boolean abortAfterTimeout, AtomicBoolean timeoutOccurred, @@ -604,6 +657,24 @@ public class DefaultShutdownStrategy extends ServiceSupport implements ShutdownS this.logInflightExchangesOnTimeout = logInflightExchangesOnTimeout; } + private void suspendConsumer(String routeId, Consumer consumer) { + consumerInProgress = new ConsumerInProgress(routeId, consumer, true, Thread.currentThread()); + try { + suspendNow(routeId, consumer); + } finally { + consumerInProgress = null; + } + } + + private void shutdownConsumer(String routeId, Consumer consumer) { + consumerInProgress = new ConsumerInProgress(routeId, consumer, false, Thread.currentThread()); + try { + shutdownNow(routeId, consumer); + } finally { + consumerInProgress = null; + } + } + // Disable BusyWait as we're only waiting on seconds increment, so any other // strategy would not be much more efficient @SuppressWarnings("BusyWait") @@ -656,7 +727,7 @@ public class DefaultShutdownStrategy extends ServiceSupport implements ShutdownS // log at info level when a route has been shutdown (otherwise log at debug level to not be too noisy) if (suspend) { // only suspend it and then later shutdown it - suspendNow(order.getRoute().getId(), consumer); + suspendConsumer(order.getRoute().getId(), consumer); // add it to the deferred list so the route will be shutdown later deferredConsumers.add(new ShutdownDeferredConsumer(order.getRoute(), consumer)); // use basic endpoint uri to not log verbose details or potential sensitive data @@ -665,7 +736,7 @@ public class DefaultShutdownStrategy extends ServiceSupport implements ShutdownS LOG.debug("Route: {} suspended and shutdown deferred, was consuming from: {}", order.getRoute().getId(), uri); } else if (shutdown) { - shutdownNow(order.getRoute().getId(), consumer); + shutdownConsumer(order.getRoute().getId(), consumer); // use basic endpoint uri to not log verbose details or potential sensitive data String uri = order.getRoute().getEndpoint().getEndpointBaseUri(); uri = URISupport.sanitizeUri(uri); @@ -808,7 +879,7 @@ public class DefaultShutdownStrategy extends ServiceSupport implements ShutdownS } Consumer consumer = deferred.getConsumer(); if (suspendOnly) { - suspendNow(deferred.getRoute().getId(), consumer); + suspendConsumer(deferred.getRoute().getId(), consumer); // use basic endpoint uri to not log verbose details or potential sensitive data String uri = deferred.getRoute().getEndpoint().getEndpointBaseUri(); uri = URISupport.sanitizeUri(uri); @@ -817,7 +888,7 @@ public class DefaultShutdownStrategy extends ServiceSupport implements ShutdownS deferred.getRoute().getId(), uri)); } } else { - shutdownNow(deferred.getRoute().getId(), consumer); + shutdownConsumer(deferred.getRoute().getId(), consumer); // use basic endpoint uri to not log verbose details or potential sensitive data String uri = deferred.getRoute().getEndpoint().getEndpointBaseUri(); uri = URISupport.sanitizeUri(uri); diff --git a/core/camel-core/src/test/java/org/apache/camel/impl/engine/DefaultShutdownStrategyBlockedConsumerTest.java b/core/camel-core/src/test/java/org/apache/camel/impl/engine/DefaultShutdownStrategyBlockedConsumerTest.java new file mode 100644 index 000000000000..9628b95570ef --- /dev/null +++ b/core/camel-core/src/test/java/org/apache/camel/impl/engine/DefaultShutdownStrategyBlockedConsumerTest.java @@ -0,0 +1,303 @@ +/* + * 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.impl.engine; + +import java.util.List; +import java.util.Map; +import java.util.concurrent.CopyOnWriteArrayList; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicReference; + +import org.apache.camel.Consumer; +import org.apache.camel.ContextTestSupport; +import org.apache.camel.Endpoint; +import org.apache.camel.Processor; +import org.apache.camel.Producer; +import org.apache.camel.Suspendable; +import org.apache.camel.builder.RouteBuilder; +import org.apache.camel.support.DefaultComponent; +import org.apache.camel.support.DefaultConsumer; +import org.apache.camel.support.DefaultEndpoint; +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.LoggerContext; +import org.apache.logging.log4j.core.appender.AbstractAppender; +import org.apache.logging.log4j.core.config.LoggerConfig; +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.parallel.Isolated; + +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.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/** + * A consumer whose suspend or stop blocks (such as a client call that waits for a reply on a connection that stopped + * answering) and ignores the interrupt. The graceful shutdown suspends or stops it on the ShutdownTask thread. The stop + * stays synchronous and waits for that call, but when the shutdown timeout elapses a WARN names the consumer, its + * route, and where the call waits. + * <p> + * Isolated: the test adds an appender to the logger of the shutdown strategy, whose configuration other tests (such as + * ShutdownWaitingAtTest) replace and remove while they run. + */ +@Isolated +class DefaultShutdownStrategyBlockedConsumerTest extends ContextTestSupport { + + private static final String LOGGER = DefaultShutdownStrategy.class.getName(); + private static final String NOT_RETURNED = "has not returned within the timeout"; + + private final CountDownLatch blocked = new CountDownLatch(1); + private final CountDownLatch release = new CountDownLatch(1); + private final List<String> warnings = new CopyOnWriteArrayList<>(); + private volatile String blockIn = ""; + private AbstractAppender appender; + + @BeforeEach + void addAppender() { + appender = new AbstractAppender("BlockedConsumerTest", null, null, true, Property.EMPTY_ARRAY) { + @Override + public void append(LogEvent event) { + if (event.getLevel() == Level.WARN) { + warnings.add(event.getMessage().getFormattedMessage()); + } + } + }; + appender.start(); + LoggerContext lc = (LoggerContext) LogManager.getContext(false); + LoggerConfig loggerConfig = new LoggerConfig(LOGGER, Level.INFO, true); + loggerConfig.addAppender(appender, null, null); + lc.getConfiguration().addLogger(LOGGER, loggerConfig); + lc.updateLoggers(); + } + + @AfterEach + void releaseConsumerAndRemoveAppender() { + release.countDown(); + LoggerContext lc = (LoggerContext) LogManager.getContext(false); + lc.getConfiguration().removeLogger(LOGGER); + lc.updateLoggers(); + appender.stop(); + } + + @Override + protected int getShutdownTimeout() { + return 1; + } + + @Override + public boolean isUseRouteBuilder() { + return false; + } + + @Test + void testContextStopWhenSuspendBlocks() throws Exception { + assertStopWaitsAndWarns("blockedSuspend", "suspend", true, "$BlockingSuspendableConsumer.doSuspend(", + () -> context.stop()); + assertTrue(context.isStopped()); + } + + @Test + void testContextStopWhenStopOfSuspendableConsumerBlocks() throws Exception { + // the consumer is suspended first, and its stop (deferred to the end of the graceful shutdown) blocks + assertStopWaitsAndWarns("blockedDeferredStop", "stop", true, "$BlockingConsumer.doStop(", () -> context.stop()); + assertTrue(context.isStopped()); + } + + @Test + void testContextStopWhenStopBlocks() throws Exception { + assertStopWaitsAndWarns("blockedStop", "stop", false, "$BlockingConsumer.doStop(", () -> context.stop()); + assertTrue(context.isStopped()); + } + + @Test + void testRouteStopWhenSuspendBlocks() throws Exception { + assertStopWaitsAndWarns("blockedRouteSuspend", "suspend", true, "$BlockingSuspendableConsumer.doSuspend(", + () -> context.getRouteController().stopRoute("blockedRouteSuspend", 1, TimeUnit.SECONDS)); + assertTrue(context.getRouteController().getRouteStatus("blockedRouteSuspend").isStopped()); + } + + @Test + void testRouteStopWithoutShutdownNowOnTimeoutWhenSuspendBlocks() throws Exception { + context.getShutdownStrategy().setShutdownNowOnTimeout(false); + assertStopWaitsAndWarns("blockedRouteIgnore", "suspend", true, "$BlockingSuspendableConsumer.doSuspend(", + () -> context.getRouteController().stopRoute("blockedRouteIgnore", 1, TimeUnit.SECONDS)); + assertTrue(context.getRouteController().getRouteStatus("blockedRouteIgnore").isStopped()); + } + + @Test + void testNoWarningWhenTheTimeoutWaitsForAnInflightExchange() throws Exception { + CountDownLatch inflight = new CountDownLatch(1); + context.addRoutes(new RouteBuilder() { + @Override + public void configure() { + from("direct:start").routeId("inflight").process(exchange -> { + inflight.countDown(); + release.await(); + }); + } + }); + context.start(); + // a thread of the test (not a thread pool of Camel, whose shutdown would wait for it); send, not sendBody, as the + // exchange fails once released (its route was forced to shut down) + Thread sender = new Thread(() -> template.send("direct:start", e -> e.getMessage().setBody("Hello")), "sender"); + sender.setDaemon(true); + sender.start(); + assertTrue(inflight.await(10, TimeUnit.SECONDS)); + + // the timeout elapses while the graceful shutdown waits for the exchange, not inside a consumer's suspend or stop + context.stop(); + + assertTrue(context.isStopped()); + assertTrue(warningsOf("inflight").isEmpty(), () -> String.valueOf(warningsOf("inflight"))); + } + + private void assertStopWaitsAndWarns( + String routeId, String blockIn, boolean suspendable, String frame, ThrowingRunnable stop) + throws Exception { + this.blockIn = blockIn; + context.addComponent("blocking", new BlockingComponent(suspendable)); + context.addRoutes(new RouteBuilder() { + @Override + public void configure() { + from("blocking:x").routeId(routeId).to("mock:result"); + } + }); + context.start(); + + AtomicReference<Throwable> failure = new AtomicReference<>(); + Thread stopper = new Thread(() -> { + try { + stop.run(); + } catch (Throwable e) { + failure.set(e); + } + }, "stopper"); + stopper.setDaemon(true); + stopper.start(); + assertTrue(blocked.await(10, TimeUnit.SECONDS), "The consumer's " + blockIn + " was not called"); + + // the shutdown timeout elapses while the call blocks: the WARN names the consumer and where the call waits + await().atMost(10, TimeUnit.SECONDS).until(() -> !warningsOf(routeId).isEmpty()); + String warning = warningsOf(routeId).get(0); + assertTrue(warning.startsWith("The " + blockIn + " of the consumer of route: " + routeId + + " (consuming from: blocking://x) " + NOT_RETURNED), + warning); + assertTrue(warning.contains(frame), warning); + // the stop stays synchronous, and waits for the consumer + assertTrue(stopper.isAlive(), "The stop returned while the consumer's " + blockIn + " still blocked"); + + release.countDown(); + stopper.join(TimeUnit.SECONDS.toMillis(10)); + assertFalse(stopper.isAlive(), "The stop did not return after the consumer's " + blockIn + " returned"); + assertNull(failure.get()); + assertEquals(1, warningsOf(routeId).size(), () -> String.valueOf(warningsOf(routeId))); + } + + private List<String> warningsOf(String routeId) { + return warnings.stream().filter(w -> w.contains(NOT_RETURNED) && w.contains("route: " + routeId + " ")).toList(); + } + + private void block() { + blocked.countDown(); + // like a client call that waits for a reply on a silent connection and does not react to the interrupt + boolean interrupted = false; + while (true) { + try { + release.await(); + break; + } catch (InterruptedException e) { + interrupted = true; + } + } + if (interrupted) { + Thread.currentThread().interrupt(); + } + } + + @FunctionalInterface + private interface ThrowingRunnable { + void run() throws Exception; + } + + private final class BlockingComponent extends DefaultComponent { + + private final boolean suspendable; + + BlockingComponent(boolean suspendable) { + this.suspendable = suspendable; + } + + @Override + protected Endpoint createEndpoint(String uri, String remaining, Map<String, Object> parameters) { + return new BlockingEndpoint(uri, this); + } + } + + private final class BlockingEndpoint extends DefaultEndpoint { + + BlockingEndpoint(String uri, BlockingComponent component) { + super(uri, component); + } + + @Override + public Producer createProducer() { + throw new UnsupportedOperationException(); + } + + @Override + public Consumer createConsumer(Processor processor) { + return ((BlockingComponent) getComponent()).suspendable + ? new BlockingSuspendableConsumer(this, processor) : new BlockingConsumer(this, processor); + } + } + + private class BlockingConsumer extends DefaultConsumer { + + BlockingConsumer(Endpoint endpoint, Processor processor) { + super(endpoint, processor); + } + + @Override + protected void doStop() throws Exception { + if ("stop".equals(blockIn)) { + block(); + } + super.doStop(); + } + } + + private final class BlockingSuspendableConsumer extends BlockingConsumer implements Suspendable { + + BlockingSuspendableConsumer(Endpoint endpoint, Processor processor) { + super(endpoint, processor); + } + + @Override + protected void doSuspend() throws Exception { + if ("suspend".equals(blockIn)) { + block(); + } + super.doSuspend(); + } + } +} diff --git a/docs/user-manual/modules/ROOT/pages/graceful-shutdown.adoc b/docs/user-manual/modules/ROOT/pages/graceful-shutdown.adoc index eb44c839986c..db014851d1c7 100644 --- a/docs/user-manual/modules/ROOT/pages/graceful-shutdown.adoc +++ b/docs/user-manual/modules/ROOT/pages/graceful-shutdown.adoc @@ -126,6 +126,25 @@ camel.main.shutdownLogInflightExchangesOnTimeout = false ---- ==== +=== A consumer whose suspend or stop does not return + +The timeout is when Camel stops waiting for the inflight exchanges and switches to the forced shutdown: it does not +bound the suspend or stop of a consumer. A consumer whose suspend or stop does not return, such as a client call that +waits for a reply from a broker or server that stopped answering, makes the shutdown wait until the call returns, as +the forced shutdown, and a later stop or start of the route, need the same consumer. + +When the timeout elapses while such a call runs, Camel logs a WARN that names the route, the endpoint it consumes +from, and where the call waits: + +[source,log] +--------------------------------- +WARN DefaultShutdownStrategy - The suspend of the consumer of route: route1 (consuming from: jms://queue:orders) has not returned within the timeout. Stopping or starting this route waits until it returns. The thread Camel (camel-1) thread #3 - ShutdownTask running it waits at: + at ... +--------------------------------- + +Set the timeouts of the client that the component uses (such as its connection, read or request timeouts) so that its +calls return when the remote system stops answering. + === JMX managed The `ShutdownStrategy` is JMX aware, so you can manage it from a
