This is an automated email from the ASF dual-hosted git repository.
davsclaus pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/camel.git
The following commit(s) were added to refs/heads/main by this push:
new 00fd61566b50 CAMEL-27487: Keep the ScheduledPollConsumer health check
DOWN after an Error until the route is restarted (#30694)
00fd61566b50 is described below
commit 00fd61566b50142088b1eb3dff4d423036236f64
Author: Nagy Vilmos <[email protected]>
AuthorDate: Wed Nov 25 07:59:39 2026 +0000
CAMEL-27487: Keep the ScheduledPollConsumer health check DOWN after an
Error until the route is restarted (#30694)
When a poll of a ScheduledPollConsumer throws an Error (such as an
OutOfMemoryError or StackOverflowError from the
route of the polled message), the scheduled task stops polling, but the
health check did not record the Error and
stayed UP.
- doRun catches an Error around the whole poll attempt (also one thrown by
the poll strategy rollback or the
exception handler, such as a bridged error handler), records it as a
failed poll and rethrows it, so the scheduled
task still ends as before.
- With the default scheduler, the first Error is kept in a sticky fatal
error (ScheduledPollConsumer.getFatalError())
that only stopping the consumer clears, so the health check stays DOWN
even when other tasks
(scheduler.concurrentConsumers > 1) keep polling. Spring and Quartz keep
running the task after an Error, so there
the Error is the lastError, as an exception.
- An Error of a poll that ran over a stop of the consumer is rethrown but
not kept for the restarted consumer; the
marker is set and cleared under the state lock.
- ScheduledPollConsumerHealthCheck reports DOWN with the Error while the
marker is set.
- Docs: the 4.24 upgrade guide and error-handler.adoc.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
---
.../camel/impl/MockScheduledPollConsumer.java | 15 ++
.../impl/ScheduledPollConsumerStaleRunTest.java | 54 ++++-
.../camel/impl/ScheduledPollConsumerTest.java | 232 +++++++++++++++++++++
.../health/SchedulerConsumerHealthCheckTest.java | 96 ++++++++-
.../camel/support/ScheduledPollConsumer.java | 226 +++++++++++++-------
.../support/ScheduledPollConsumerHealthCheck.java | 15 +-
.../ROOT/pages/camel-4x-upgrade-guide-4_24.adoc | 8 +
.../modules/ROOT/pages/error-handler.adoc | 5 +
8 files changed, 562 insertions(+), 89 deletions(-)
diff --git
a/core/camel-core/src/test/java/org/apache/camel/impl/MockScheduledPollConsumer.java
b/core/camel-core/src/test/java/org/apache/camel/impl/MockScheduledPollConsumer.java
index 9d5710233730..d89bec46f54f 100644
---
a/core/camel-core/src/test/java/org/apache/camel/impl/MockScheduledPollConsumer.java
+++
b/core/camel-core/src/test/java/org/apache/camel/impl/MockScheduledPollConsumer.java
@@ -26,6 +26,8 @@ import org.apache.camel.support.ScheduledPollConsumer;
public class MockScheduledPollConsumer extends ScheduledPollConsumer {
private Exception exceptionToThrowOnPoll;
+ private Error errorToThrowOnPoll;
+ private int pollsUntilError;
public MockScheduledPollConsumer(DefaultEndpoint endpoint, Processor
processor) {
super(endpoint, processor);
@@ -40,6 +42,11 @@ public class MockScheduledPollConsumer extends
ScheduledPollConsumer {
@Override
protected int poll() throws Exception {
+ if (errorToThrowOnPoll != null && --pollsUntilError == 0) {
+ Error error = errorToThrowOnPoll;
+ errorToThrowOnPoll = null;
+ throw error;
+ }
if (exceptionToThrowOnPoll != null) {
throw exceptionToThrowOnPoll;
}
@@ -50,6 +57,14 @@ public class MockScheduledPollConsumer extends
ScheduledPollConsumer {
this.exceptionToThrowOnPoll = exceptionToThrowOnPoll;
}
+ /**
+ * Throws the error once, on the given poll from now on (1 is the next
poll). The polls before and after it succeed.
+ */
+ public void setErrorToThrowOnPoll(Error errorToThrowOnPoll, int onPoll) {
+ this.errorToThrowOnPoll = errorToThrowOnPoll;
+ this.pollsUntilError = onPoll;
+ }
+
@Override
public String toString() {
return "MockScheduled";
diff --git
a/core/camel-core/src/test/java/org/apache/camel/impl/ScheduledPollConsumerStaleRunTest.java
b/core/camel-core/src/test/java/org/apache/camel/impl/ScheduledPollConsumerStaleRunTest.java
index abbf9b66cc7a..7b8121120ad9 100644
---
a/core/camel-core/src/test/java/org/apache/camel/impl/ScheduledPollConsumerStaleRunTest.java
+++
b/core/camel-core/src/test/java/org/apache/camel/impl/ScheduledPollConsumerStaleRunTest.java
@@ -19,9 +19,11 @@ package org.apache.camel.impl;
import java.util.Map;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicReference;
import org.apache.camel.ContextTestSupport;
import org.apache.camel.Endpoint;
+import org.apache.camel.health.HealthCheck;
import org.apache.camel.spi.HttpResponseAware;
import org.apache.camel.support.DefaultScheduledPollConsumerScheduler;
import org.apache.camel.support.ScheduledPollConsumer;
@@ -32,6 +34,7 @@ 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.assertSame;
import static org.junit.jupiter.api.Assertions.assertTrue;
/**
@@ -60,6 +63,7 @@ class ScheduledPollConsumerStaleRunTest extends
ContextTestSupport {
private volatile boolean forceReadyInPoll;
private volatile Exception exceptionToThrowOnPoll;
+ private volatile Error errorToThrowOnPoll;
// set to hold the next poll (the remote call of the poll is in
progress)
private volatile CountDownLatch pollHeld;
// set to hold the next call of addLastErrorDetail (after the
generation check of the poll)
@@ -84,6 +88,10 @@ class ScheduledPollConsumerStaleRunTest extends
ContextTestSupport {
// such as camel-aws2-sqs when its receive call returns
forceConsumerAsReady();
}
+ Error error = errorToThrowOnPoll;
+ if (error != null) {
+ throw error;
+ }
Exception e = exceptionToThrowOnPoll;
if (e != null) {
throw e;
@@ -187,7 +195,20 @@ class ScheduledPollConsumerStaleRunTest extends
ContextTestSupport {
}
private void startPoller() {
- poller = new Thread(consumer::run, "stale-poll");
+ startPoller(new AtomicReference<>());
+ }
+
+ /**
+ * Starts the poll in another thread, and keeps what the run threw (as the
scheduler would see it).
+ */
+ private void startPoller(AtomicReference<Throwable> thrown) {
+ poller = new Thread(() -> {
+ try {
+ consumer.run();
+ } catch (Throwable t) {
+ thrown.set(t);
+ }
+ }, "stale-poll");
poller.start();
}
@@ -262,6 +283,37 @@ class ScheduledPollConsumerStaleRunTest extends
ContextTestSupport {
assertNull(consumer.lastErrorDetails());
}
+ @Test
+ void
errorOfPollFromBeforeStopEndsItsTaskButDoesNotMarkRestartedConsumerDown()
throws Exception {
+ newConsumer();
+ final OutOfMemoryError expectedError = new OutOfMemoryError("Simulated
error on poll");
+ consumer.errorToThrowOnPoll = expectedError;
+ CountDownLatch pollHeld = new CountDownLatch(1);
+ consumer.pollHeld = pollHeld;
+ consumer.start();
+
+ AtomicReference<Throwable> thrown = new AtomicReference<>();
+ startPoller(thrown);
+ assertTrue(pollHeld.await(10, TimeUnit.SECONDS));
+
+ // stop and start while the poll is in progress, which then throws the
Error
+ consumer.stop();
+ consumer.start();
+ release.countDown();
+ joinPoller();
+
+ // the Error still ends the task of the stopped consumer (so the
scheduler does not run it again)
+ assertSame(expectedError, thrown.get());
+ // but the restarted consumer has not polled yet, so the Error is not
kept for it
+ assertNull(consumer.getFatalError());
+ assertEquals(0, consumer.getErrorCounter());
+
+ // a poll of the restarted consumer is healthy
+ consumer.errorToThrowOnPoll = null;
+ consumer.run();
+ assertEquals(HealthCheck.State.UP,
consumer.getHealthCheck().call().getState());
+ }
+
@Test
void repeatCountOfRunFromBeforeStopDoesNotUnscheduleRestartedConsumer()
throws Exception {
newConsumer();
diff --git
a/core/camel-core/src/test/java/org/apache/camel/impl/ScheduledPollConsumerTest.java
b/core/camel-core/src/test/java/org/apache/camel/impl/ScheduledPollConsumerTest.java
index 8842335250c6..ae1f7c03202f 100644
---
a/core/camel-core/src/test/java/org/apache/camel/impl/ScheduledPollConsumerTest.java
+++
b/core/camel-core/src/test/java/org/apache/camel/impl/ScheduledPollConsumerTest.java
@@ -18,18 +18,31 @@ package org.apache.camel.impl;
import java.util.concurrent.atomic.AtomicInteger;
+import org.apache.camel.CamelContext;
import org.apache.camel.Consumer;
import org.apache.camel.ContextTestSupport;
import org.apache.camel.Endpoint;
+import org.apache.camel.Exchange;
+import org.apache.camel.health.HealthCheck;
+import org.apache.camel.spi.ExceptionHandler;
import org.apache.camel.spi.PollingConsumerPollStrategy;
+import org.apache.camel.spi.ScheduledPollConsumerScheduler;
+import org.apache.camel.support.service.ServiceSupport;
import org.junit.jupiter.api.Test;
+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.assertNull;
+import static org.junit.jupiter.api.Assertions.assertSame;
+import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
public class ScheduledPollConsumerTest extends ContextTestSupport {
+ // the poll that throws an Error, after successful polls
+ private static final int ERROR_ON_POLL = 3;
+
private static boolean rollback;
private static String event = "";
@@ -115,6 +128,225 @@ public class ScheduledPollConsumerTest extends
ContextTestSupport {
assertEquals("rollbackrollbackrollbackrollback", event);
}
+ @Test
+ public void testErrorOnPollStopsPollingAndHealthCheckIsDown() {
+ final LinkageError expectedError = new LinkageError("Simulated error
on poll");
+ final AtomicInteger rollbacks = new AtomicInteger();
+ MockScheduledPollConsumer consumer =
createConsumerWithError(expectedError, rollbacks);
+ consumer.start();
+ pollUntilErrorIsNext(consumer);
+
+ // the Error ends the scheduled task, so the scheduler does not run it
again
+ LinkageError thrown = assertThrows(LinkageError.class, consumer::run);
+ assertSame(expectedError, thrown);
+ // an Error is not an exception the poll strategy can retry
+ assertEquals(0, rollbacks.get());
+
+ HealthCheck.Result result = consumer.getHealthCheck().call();
+ assertEquals(HealthCheck.State.DOWN, result.getState());
+ assertSame(expectedError, result.getError().orElse(null));
+
+ consumer.stop();
+ }
+
+ @Test
+ public void testErrorOnPollKeepsHealthCheckDownUntilRestart() {
+ final LinkageError expectedError = new LinkageError("Simulated error
on poll");
+ MockScheduledPollConsumer consumer =
createConsumerWithError(expectedError, new AtomicInteger());
+ consumer.start();
+ pollUntilErrorIsNext(consumer);
+ assertThrows(LinkageError.class, consumer::run);
+ assertEquals(HealthCheck.State.DOWN,
consumer.getHealthCheck().call().getState());
+
+ // with concurrentConsumers > 1 the other tasks keep polling: a
successful poll must not report the
+ // consumer as healthy again, as it now polls with one task less
+ consumer.run();
+ HealthCheck.Result result = consumer.getHealthCheck().call();
+ assertEquals(HealthCheck.State.DOWN, result.getState());
+ assertSame(expectedError, result.getError().orElse(null));
+
+ // only a restart of the consumer clears it
+ consumer.stop();
+ consumer.start();
+ consumer.run();
+ assertEquals(HealthCheck.State.UP,
consumer.getHealthCheck().call().getState());
+
+ consumer.stop();
+ }
+
+ @Test
+ public void
testErrorFromExceptionHandlerStopsPollingAndHealthCheckIsDown() {
+ // such as a bridged error handler whose dead letter route throws a
StackOverflowError
+ final Exception pollException = new Exception("Simulated exception on
poll");
+ final StackOverflowError expectedError = new
StackOverflowError("Simulated error in the exception handler");
+ MockScheduledPollConsumer consumer =
createConsumerWithException(pollException, null);
+ consumer.setExceptionHandler(new ExceptionHandler() {
+ public void handleException(Throwable exception) {
+ handleException(null, exception);
+ }
+
+ public void handleException(String message, Throwable exception) {
+ handleException(message, null, exception);
+ }
+
+ public void handleException(String message, Exchange exchange,
Throwable exception) {
+ throw expectedError;
+ }
+ });
+ consumer.start();
+
+ assertErrorStopsPollingAndHealthCheckIsDown(consumer, expectedError,
pollException);
+
+ consumer.stop();
+ }
+
+ @Test
+ public void testErrorFromRollbackStopsPollingAndHealthCheckIsDown() {
+ final Exception pollException = new Exception("Simulated exception on
poll");
+ final LinkageError expectedError = new LinkageError("Simulated error
on rollback");
+ MockScheduledPollConsumer consumer =
createConsumerWithException(pollException, expectedError);
+ consumer.start();
+
+ assertErrorStopsPollingAndHealthCheckIsDown(consumer, expectedError,
pollException);
+
+ consumer.stop();
+ }
+
+ private static void assertErrorStopsPollingAndHealthCheckIsDown(
+ MockScheduledPollConsumer consumer, Error expectedError, Exception
pollException) {
+ // the Error ends the scheduled task, so the scheduler does not run it
again
+ Error thrown = assertThrows(Error.class, consumer::run);
+ assertSame(expectedError, thrown);
+
+ HealthCheck.Result result = consumer.getHealthCheck().call();
+ assertEquals(HealthCheck.State.DOWN, result.getState());
+ assertSame(expectedError, result.getError().orElse(null));
+ // the exception that was being handled is kept with the Error
+ assertArrayEquals(new Throwable[] { pollException },
thrown.getSuppressed());
+
+ // a poll by another task (scheduler.concurrentConsumers > 1) does not
report the consumer as healthy again
+ consumer.setExceptionToThrowOnPoll(null);
+ consumer.run();
+ assertEquals(HealthCheck.State.DOWN,
consumer.getHealthCheck().call().getState());
+ }
+
+ private MockScheduledPollConsumer createConsumerWithException(Exception
exception, Error rollbackError) {
+ MockScheduledPollConsumer consumer = new
MockScheduledPollConsumer(getMockEndpoint("mock:foo"), exception);
+ consumer.setRouteId("error");
+ // the test runs the polls itself
+ consumer.setStartScheduler(false);
+ consumer.setPollStrategy(new PollingConsumerPollStrategy() {
+ public boolean begin(Consumer consumer, Endpoint endpoint) {
+ return true;
+ }
+
+ public void commit(Consumer consumer, Endpoint endpoint, int
polledMessages) {
+ }
+
+ public boolean rollback(Consumer consumer, Endpoint endpoint, int
retryCounter, Exception e) {
+ if (rollbackError != null) {
+ throw rollbackError;
+ }
+ return false;
+ }
+ });
+ return consumer;
+ }
+
+ @Test
+ public void testErrorOnPollWithOtherSchedulerIsTheLastError() {
+ // such as the Spring or Quartz scheduler, which keep running the task
after an Error
+ final LinkageError expectedError = new LinkageError("Simulated error
on poll");
+ MockScheduledPollConsumer consumer =
createConsumerWithError(expectedError, new AtomicInteger());
+ consumer.setScheduler(new OtherScheduler());
+ consumer.start();
+ pollUntilErrorIsNext(consumer);
+
+ // the Error is still thrown to the scheduler
+ assertSame(expectedError, assertThrows(LinkageError.class,
consumer::run));
+ // but the task keeps polling, so the consumer is not kept DOWN until
restart
+ assertNull(consumer.getFatalError());
+ HealthCheck.Result result = consumer.getHealthCheck().call();
+ assertEquals(HealthCheck.State.DOWN, result.getState());
+ assertSame(expectedError, result.getError().orElse(null));
+
+ // the next successful poll reports the consumer as healthy again, as
for an exception
+ consumer.run();
+ assertEquals(HealthCheck.State.UP,
consumer.getHealthCheck().call().getState());
+
+ consumer.stop();
+ }
+
+ private static final class OtherScheduler extends ServiceSupport
implements ScheduledPollConsumerScheduler {
+
+ private CamelContext camelContext;
+
+ @Override
+ public void onInit(Consumer consumer) {
+ }
+
+ @Override
+ public void scheduleTask(Runnable task) {
+ // the test runs the polls itself
+ }
+
+ @Override
+ public void unscheduleTask() {
+ }
+
+ @Override
+ public void startScheduler() {
+ }
+
+ @Override
+ public boolean isSchedulerStarted() {
+ return true;
+ }
+
+ @Override
+ public CamelContext getCamelContext() {
+ return camelContext;
+ }
+
+ @Override
+ public void setCamelContext(CamelContext camelContext) {
+ this.camelContext = camelContext;
+ }
+ }
+
+ /**
+ * Runs the successful polls before the one that throws the Error, so the
health check is UP because the consumer
+ * polled (and not because of its initial state) before the Error.
+ */
+ private void pollUntilErrorIsNext(MockScheduledPollConsumer consumer) {
+ for (int i = 1; i < ERROR_ON_POLL; i++) {
+ consumer.run();
+ assertEquals(HealthCheck.State.UP,
consumer.getHealthCheck().call().getState());
+ }
+ }
+
+ private MockScheduledPollConsumer createConsumerWithError(Error error,
AtomicInteger rollbacks) {
+ MockScheduledPollConsumer consumer = new
MockScheduledPollConsumer(getMockEndpoint("mock:foo"), (Exception) null);
+ consumer.setErrorToThrowOnPoll(error, ERROR_ON_POLL);
+ consumer.setRouteId("error");
+ // the test runs the polls itself
+ consumer.setStartScheduler(false);
+ consumer.setPollStrategy(new PollingConsumerPollStrategy() {
+ public boolean begin(Consumer consumer, Endpoint endpoint) {
+ return true;
+ }
+
+ public void commit(Consumer consumer, Endpoint endpoint, int
polledMessages) {
+ }
+
+ public boolean rollback(Consumer consumer, Endpoint endpoint, int
retryCounter, Exception e) {
+ rollbacks.incrementAndGet();
+ return false;
+ }
+ });
+ return consumer;
+ }
+
@Test
public void testNoExceptionOnPoll() {
final Endpoint endpoint = getMockEndpoint("mock:foo");
diff --git
a/core/camel-core/src/test/java/org/apache/camel/impl/health/SchedulerConsumerHealthCheckTest.java
b/core/camel-core/src/test/java/org/apache/camel/impl/health/SchedulerConsumerHealthCheckTest.java
index 3408436551e5..8dbcdf11adfb 100644
---
a/core/camel-core/src/test/java/org/apache/camel/impl/health/SchedulerConsumerHealthCheckTest.java
+++
b/core/camel-core/src/test/java/org/apache/camel/impl/health/SchedulerConsumerHealthCheckTest.java
@@ -16,22 +16,39 @@
*/
package org.apache.camel.impl.health;
+import java.time.Duration;
+import java.util.concurrent.atomic.AtomicInteger;
+
import org.apache.camel.CamelContext;
import org.apache.camel.Route;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.component.scheduler.SchedulerConsumer;
import org.apache.camel.health.HealthCheck;
import org.apache.camel.impl.DefaultCamelContext;
+import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
+import static org.awaitility.Awaitility.await;
+
public class SchedulerConsumerHealthCheckTest {
private static final String TEST_ROUTE_ID = "Test-Route";
+ // the exchange that throws an Error, after successful ones
+ private static final int ERROR_ON_POLL = 3;
+
+ private CamelContext context;
+
+ @AfterEach
+ public void stopContext() {
+ if (context != null) {
+ context.stop();
+ }
+ }
@Test
public void testShouldBeUP() throws Exception {
- CamelContext context = new DefaultCamelContext();
+ context = new DefaultCamelContext();
context.addRoutes(new RouteBuilder() {
@Override
public void configure() {
@@ -40,13 +57,80 @@ public class SchedulerConsumerHealthCheckTest {
});
context.start();
- Route route = context.getRoute(TEST_ROUTE_ID);
- SchedulerConsumer consumer = (SchedulerConsumer) route.getConsumer();
- HealthCheck.Result result = consumer.getHealthCheck().call();
+ Assertions.assertEquals(HealthCheck.State.UP,
healthCheck().getState());
+ }
- Assertions.assertEquals(HealthCheck.State.UP, result.getState());
+ @Test
+ public void testErrorThrownByRouteStopsPollingAndShouldBeDown() throws
Exception {
+ AtomicInteger polls =
startRouteThatThrowsOnPoll("scheduler:foo?initialDelay=0&delay=10");
+
+ await().atMost(Duration.ofSeconds(5))
+ .untilAsserted(() ->
Assertions.assertEquals(HealthCheck.State.DOWN, healthCheck().getState()));
+ HealthCheck.Result result = healthCheck();
+ Assertions.assertInstanceOf(OutOfMemoryError.class,
result.getError().orElse(null));
+
+ // the consumer does not poll again
+ await().during(Duration.ofMillis(500)).atMost(Duration.ofSeconds(1))
+ .until(() -> polls.get() == ERROR_ON_POLL);
+ Assertions.assertEquals(HealthCheck.State.DOWN,
healthCheck().getState());
+ }
+
+ @Test
+ public void testErrorThrownByRouteWithConcurrentConsumersShouldStayDown()
throws Exception {
+ AtomicInteger polls = startRouteThatThrowsOnPoll(
+
"scheduler:foo?initialDelay=0&delay=10&poolSize=2&scheduler.concurrentConsumers=2");
+
+ await().atMost(Duration.ofSeconds(5))
+ .untilAsserted(() ->
Assertions.assertEquals(HealthCheck.State.DOWN, healthCheck().getState()));
+
+ // the other task keeps polling successfully, but the consumer now
polls with one task less
+ int pollsWhenDown = polls.get();
+ await().atMost(Duration.ofSeconds(5)).until(() -> polls.get() >
pollsWhenDown + 5);
+ Assertions.assertEquals(HealthCheck.State.DOWN,
healthCheck().getState());
+ }
- context.stop();
+ @Test
+ public void testRouteRestartAfterErrorPollsAgainAndShouldBeUp() throws
Exception {
+ AtomicInteger polls =
startRouteThatThrowsOnPoll("scheduler:foo?initialDelay=0&delay=10");
+
+ await().atMost(Duration.ofSeconds(5))
+ .untilAsserted(() ->
Assertions.assertEquals(HealthCheck.State.DOWN, healthCheck().getState()));
+
+ context.getRouteController().stopRoute(TEST_ROUTE_ID);
+ context.getRouteController().startRoute(TEST_ROUTE_ID);
+
+ await().atMost(Duration.ofSeconds(5)).until(() -> polls.get() >
ERROR_ON_POLL);
+ await().atMost(Duration.ofSeconds(5))
+ .untilAsserted(() ->
Assertions.assertEquals(HealthCheck.State.UP, healthCheck().getState()));
+ }
+
+ /**
+ * Starts a route whose exchange number ERROR_ON_POLL throws an
OutOfMemoryError. Camel's error handling does not
+ * handle a VirtualMachineError, so it reaches the consumer.
+ */
+ private AtomicInteger startRouteThatThrowsOnPoll(String uri) throws
Exception {
+ AtomicInteger polls = new AtomicInteger();
+ context = new DefaultCamelContext();
+ // the exchange that failed with the Error may stay inflight, so do
not wait long for it on shutdown
+ context.getShutdownStrategy().setTimeout(1);
+ context.addRoutes(new RouteBuilder() {
+ @Override
+ public void configure() {
+ from(uri).id(TEST_ROUTE_ID).process(exchange -> {
+ if (polls.incrementAndGet() == ERROR_ON_POLL) {
+ throw new OutOfMemoryError("Simulated error in the
route");
+ }
+ });
+ }
+ });
+ context.start();
+ return polls;
+ }
+
+ private HealthCheck.Result healthCheck() {
+ Route route = context.getRoute(TEST_ROUTE_ID);
+ SchedulerConsumer consumer = (SchedulerConsumer) route.getConsumer();
+ return consumer.getHealthCheck().call();
}
}
diff --git
a/core/camel-support/src/main/java/org/apache/camel/support/ScheduledPollConsumer.java
b/core/camel-support/src/main/java/org/apache/camel/support/ScheduledPollConsumer.java
index 2d4ea9d897e1..09fe2413da7a 100644
---
a/core/camel-support/src/main/java/org/apache/camel/support/ScheduledPollConsumer.java
+++
b/core/camel-support/src/main/java/org/apache/camel/support/ScheduledPollConsumer.java
@@ -23,6 +23,7 @@ import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;
+import java.util.concurrent.atomic.AtomicReference;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
@@ -83,6 +84,9 @@ public abstract class ScheduledPollConsumer extends
DefaultConsumer
private final AtomicLong successCounter = new AtomicLong();
private volatile Throwable lastError;
private volatile Map<String, Object> lastErrorDetails;
+ // the first Error a poll threw since the consumer was started: unlike
lastError, a successful poll (such as by
+ // another task when scheduler.concurrentConsumers > 1) does not clear it,
only stopping the consumer does
+ private final AtomicReference<Throwable> fatalError = new
AtomicReference<>();
private final AtomicLong counter = new AtomicLong();
private volatile boolean firstPollDone;
// the error counter when the last backoff finished (the error threshold
of the backoff counts from this)
@@ -154,8 +158,14 @@ public abstract class ScheduledPollConsumer extends
DefaultConsumer
}
} catch (Error e) {
// need to log so there is visibility as otherwise the user may
not see anything in logs
- LOG.error("Fatal error occurred during running scheduled task on:
{}, due: {}.",
- this.getEndpoint(), e.getMessage(), e);
+ if (isErrorEndingTask()) {
+ LOG.error("Fatal error occurred during running scheduled task
on: {}, due: {}."
+ + " The scheduled task has stopped polling and will
not run again until the route is restarted.",
+ this.getEndpoint(), e.getMessage(), e);
+ } else {
+ LOG.error("Fatal error occurred during running scheduled task
on: {}, due: {}.",
+ this.getEndpoint(), e.getMessage(), e);
+ }
throw e;
} catch (Throwable e) {
LOG.error("Error occurred during running scheduled task on: {},
due: {}."
@@ -226,101 +236,115 @@ public abstract class ScheduledPollConsumer extends
DefaultConsumer
int polledMessages = 0;
while (!done) {
+ // an Error is caught around the whole attempt, so also an Error
that the poll strategy (such as on rollback)
+ // or the exception handler (such as a bridged error handler whose
route throws a StackOverflowError) throws
+ // is kept and ends this task, as one thrown by the poll itself
try {
- // eager assume we are done
- done = true;
- if (isPollAllowed()) {
-
- if (retryCounter == -1) {
- LOG.trace("Starting to poll: {}", this.getEndpoint());
- } else {
- LOG.debug("Retrying attempt {} to poll: {}",
retryCounter, this.getEndpoint());
- }
-
- // mark we are polling which should also include the
begin/poll/commit
- // (the watch first, so whoever sees the counter sees the
watch of this poll or a later one)
- pollStopWatch = new StopWatch();
- pollingCounter.incrementAndGet();
- try {
- boolean begin = pollStrategy.begin(this,
getEndpoint());
- if (begin) {
- retryCounter++;
- int polled = 0;
- pollGeneration.set(currentGeneration);
- try {
- polled = poll();
- } finally {
- pollGeneration.remove();
- // also a poll that failed, so a consumer that
keeps failing is seen polling
- onPolled(currentGeneration, polled);
- }
- polledMessages = polled;
- LOG.trace("Polled {} messages", polledMessages);
+ try {
+ // eager assume we are done
+ done = true;
+ if (isPollAllowed()) {
- if (polledMessages == 0 &&
isSendEmptyMessageWhenIdle()) {
- // send an "empty" exchange
- processEmptyMessage();
- }
+ if (retryCounter == -1) {
+ LOG.trace("Starting to poll: {}",
this.getEndpoint());
+ } else {
+ LOG.debug("Retrying attempt {} to poll: {}",
retryCounter, this.getEndpoint());
+ }
- pollStrategy.commit(this, getEndpoint(),
polledMessages);
+ // mark we are polling which should also include the
begin/poll/commit
+ // (the watch first, so whoever sees the counter sees
the watch of this poll or a later one)
+ pollStopWatch = new StopWatch();
+ pollingCounter.incrementAndGet();
+ try {
+ boolean begin = pollStrategy.begin(this,
getEndpoint());
+ if (begin) {
+ retryCounter++;
+ int polled = 0;
+ pollGeneration.set(currentGeneration);
+ try {
+ polled = poll();
+ } finally {
+ pollGeneration.remove();
+ // also a poll that failed, so a consumer
that keeps failing is seen polling
+ onPolled(currentGeneration, polled);
+ }
+ polledMessages = polled;
+ LOG.trace("Polled {} messages",
polledMessages);
- if (polledMessages > 0 && isGreedy()) {
- done = false;
- retryCounter = -1;
- LOG.trace("Greedy polling after processing {}
messages", polledMessages);
+ if (polledMessages == 0 &&
isSendEmptyMessageWhenIdle()) {
+ // send an "empty" exchange
+ processEmptyMessage();
+ }
- stateLock.lock();
- try {
- if (currentGeneration == generation.get())
{
- // clear any error that might be since
we have successfully polled, otherwise readiness checks might believe the
- // consumer to be unhealthy
- errorCounter.set(0);
- backoffErrorBase.set(0);
- lastError = null;
- lastErrorDetails = null;
-
- // setting firstPollDone to true if
greedy polling is enabled
- firstPollDone = true;
+ pollStrategy.commit(this, getEndpoint(),
polledMessages);
+
+ if (polledMessages > 0 && isGreedy()) {
+ done = false;
+ retryCounter = -1;
+ LOG.trace("Greedy polling after processing
{} messages", polledMessages);
+
+ stateLock.lock();
+ try {
+ if (currentGeneration ==
generation.get()) {
+ // clear any error that might be
since we have successfully polled, otherwise readiness checks might believe the
+ // consumer to be unhealthy
+ errorCounter.set(0);
+ backoffErrorBase.set(0);
+ lastError = null;
+ lastErrorDetails = null;
+
+ // setting firstPollDone to true
if greedy polling is enabled
+ firstPollDone = true;
+ }
+ } finally {
+ stateLock.unlock();
}
- } finally {
- stateLock.unlock();
}
+ } else {
+ LOG.debug("Cannot begin polling as
pollStrategy returned false: {}", pollStrategy);
}
- } else {
- LOG.debug("Cannot begin polling as pollStrategy
returned false: {}", pollStrategy);
+ } finally {
+ pollingCounter.decrementAndGet();
}
- } finally {
- pollingCounter.decrementAndGet();
}
- }
- LOG.trace("Finished polling: {}", this.getEndpoint());
- } catch (Exception e) {
- try {
- boolean retry = pollStrategy.rollback(this, getEndpoint(),
retryCounter, e);
- if (retry) {
- // do not set cause as we retry
- done = false;
- } else {
- cause = e;
+ LOG.trace("Finished polling: {}", this.getEndpoint());
+ } catch (Exception e) {
+ // set before the rollback, so an Error that the rollback
throws keeps this exception
+ cause = e;
+ try {
+ boolean retry = pollStrategy.rollback(this,
getEndpoint(), retryCounter, e);
+ if (retry) {
+ // do not set cause as we retry
+ cause = null;
+ done = false;
+ } else {
+ done = true;
+ }
+ } catch (Exception t) {
+ cause = t;
done = true;
}
- } catch (Exception t) {
- cause = t;
- done = true;
}
- }
- if (cause != null && isRunAllowed()) {
- // let exception handler deal with the caused exception
- // but suppress this during shutdown as the logs may get
flooded with exceptions during shutdown/forced shutdown
- try {
- getExceptionHandler().handleException("Failed polling
endpoint: " + getEndpoint()
- + ". Will try again
at next poll",
- cause);
- } catch (Exception e) {
- LOG.warn("Error handling exception. This exception will be
ignored.", e);
+ if (cause != null && isRunAllowed()) {
+ // let exception handler deal with the caused exception
+ // but suppress this during shutdown as the logs may get
flooded with exceptions during shutdown/forced shutdown
+ try {
+ getExceptionHandler().handleException("Failed polling
endpoint: " + getEndpoint()
+ + ". Will try
again at next poll",
+ cause);
+ } catch (Exception e) {
+ LOG.warn("Error handling exception. This exception
will be ignored.", e);
+ }
+ }
+ } catch (Error error) {
+ if (cause != null && cause != error) {
+ // the Error was thrown while handling this exception, so
keep it with the Error
+ error.addSuppressed(cause);
}
+ cause = error;
+ done = true;
}
}
@@ -329,6 +353,10 @@ public abstract class ScheduledPollConsumer extends
DefaultConsumer
if (currentGeneration != generation.get()) {
// the consumer has been stopped while polling, so the state
(which has been reset) must not be updated
LOG.trace("doRun() done after the consumer was stopped");
+ if (cause instanceof Error error) {
+ // the task of the stopped consumer still ends, but the
Error is not kept for the restarted consumer
+ throw error;
+ }
return;
}
@@ -361,16 +389,38 @@ public abstract class ScheduledPollConsumer extends
DefaultConsumer
// now first pool is done after the poll is complete
firstPollDone = true;
+
+ if (cause instanceof Error && isErrorEndingTask()) {
+ // keep the error until the consumer is stopped, so the health
check stays DOWN even if other tasks
+ // (scheduler.concurrentConsumers > 1) keep polling
successfully. Under the lock, so a stop and start
+ // after the generation check cannot leave the marker on the
restarted consumer
+ fatalError.compareAndSet(null, cause);
+ }
} finally {
stateLock.unlock();
}
+ if (cause instanceof Error error) {
+ // the JVM may be in an unknown state, so run() logs and rethrows
this: with the default scheduler this ends
+ // the scheduled task
+ throw error;
+ }
+
LOG.trace("doRun() done with idleCounter={}, successCounter={},
errorCounter={}", idleCounter.longValue(),
successCounter.longValue(), errorCounter.longValue());
// avoid this thread to throw exceptions because the thread pool wont
re-schedule a new thread
}
+ /**
+ * Whether an {@link Error} thrown by a run ends the scheduled task: the
default scheduler runs the task on a
+ * {@link java.util.concurrent.ScheduledExecutorService}, which does not
run it again after it threw, while other
+ * schedulers (such as Spring or Quartz) catch it and keep running the
task.
+ */
+ private boolean isErrorEndingTask() {
+ return scheduler instanceof DefaultScheduledPollConsumerScheduler;
+ }
+
/**
* Keeps when this poll was done, and when it polled messages also how
many: a quiet consumer can then be told from
* one whose scheduler has stopped. The time is the system clock, as for
the other timestamps that management and
@@ -653,6 +703,19 @@ public abstract class ScheduledPollConsumer extends
DefaultConsumer
return lastPollMessagesCount;
}
+ /**
+ * The first {@link Error} (such as an {@link OutOfMemoryError}) a poll
threw since the consumer was started, or
+ * null if none. With the default scheduler, the scheduled task that
polled stops polling after an Error, so unlike
+ * {@link #getLastError()} this is not cleared by a later successful poll,
only when the consumer is stopped (such
+ * as by restarting the route). Other schedulers (such as Spring or
Quartz) keep running the task after an Error, so
+ * with them this is always null, and the Error is the {@link
#getLastError()} instead.
+ *
+ * @since 4.24
+ */
+ public Throwable getFatalError() {
+ return fatalError.get();
+ }
+
/**
* Whether a first pool attempt has been done (also if the consumer has
been restarted).
*/
@@ -916,6 +979,7 @@ public abstract class ScheduledPollConsumer extends
DefaultConsumer
forceReady = false;
lastError = null;
lastErrorDetails = null;
+ fatalError.set(null);
} finally {
stateLock.unlock();
}
diff --git
a/core/camel-support/src/main/java/org/apache/camel/support/ScheduledPollConsumerHealthCheck.java
b/core/camel-support/src/main/java/org/apache/camel/support/ScheduledPollConsumerHealthCheck.java
index a2b89e0670c2..f75661cf844c 100644
---
a/core/camel-support/src/main/java/org/apache/camel/support/ScheduledPollConsumerHealthCheck.java
+++
b/core/camel-support/src/main/java/org/apache/camel/support/ScheduledPollConsumerHealthCheck.java
@@ -26,7 +26,9 @@ import org.apache.camel.util.URISupport;
/**
* {@link HealthCheck} that uses the last polling state from {@link
ScheduledPollConsumer} when reporting the health,
- * and the poll in progress when it runs longer than {@link
ScheduledPollConsumer#getHealthCheckMaxPollDuration()}.
+ * and the poll in progress when it runs longer than {@link
ScheduledPollConsumer#getHealthCheckMaxPollDuration()}. It
+ * is DOWN after a poll threw an {@link Error} with the default scheduler (see
+ * {@link ScheduledPollConsumer#getFatalError()}) until the consumer is
restarted.
*/
public class ScheduledPollConsumerHealthCheck implements HealthCheck {
@@ -92,6 +94,17 @@ public class ScheduledPollConsumerHealthCheck implements
HealthCheck {
return builder.unknown().build();
}
+ // with the default scheduler, a poll that threw an Error ended its
scheduled task, so the consumer polls no more (or with fewer tasks when
+ // scheduler.concurrentConsumers > 1) until it is restarted, even if
other polls succeed
+ Throwable fatalError = consumer.getFatalError();
+ if (fatalError != null) {
+ builder.down();
+ builder.error(fatalError);
+ String msg = "Consumer stopped polling due to a fatal error
(restart the route to poll again) route: %s (%s)";
+ builder.message(String.format(msg, consumer.getRouteId(),
sanitizedBaseUri));
+ return builder.build();
+ }
+
// a poll that hangs (such as in a read without timeout on a
connection that went silent) is not done, so the
// state below, which a poll updates when it is done, does not see it
long maxPollDuration = consumer.getHealthCheckMaxPollDuration();
diff --git
a/docs/user-manual/modules/ROOT/pages/camel-4x-upgrade-guide-4_24.adoc
b/docs/user-manual/modules/ROOT/pages/camel-4x-upgrade-guide-4_24.adoc
index e9b4e310d599..aa60b14f7473 100644
--- a/docs/user-manual/modules/ROOT/pages/camel-4x-upgrade-guide-4_24.adoc
+++ b/docs/user-manual/modules/ROOT/pages/camel-4x-upgrade-guide-4_24.adoc
@@ -222,6 +222,14 @@ messages, and grew with each one. An exception from a
predicate of `onException`
Split is no longer added to it either, and is logged instead. Use
`throwException(MyException.class, "...")`, or
`exceptionType` and `message`, to get a new exception for each message, with
the previous exception as suppressed.
+=== camel-support - a scheduled poll consumer is DOWN after an Error until the
route is restarted
+
+When a poll of a scheduled poll consumer with the default scheduler throws an
`Error` (such as an `OutOfMemoryError`
+from the route), the scheduled task that ran it stops polling. Previously the
health check of the consumer stayed UP in
+this case; now it flips to DOWN, with the `Error`, and stays DOWN until the
route is restarted, even if other tasks
+(`scheduler.concurrentConsumers`) keep polling. The restart may wait for the
shutdown timeout, as the failed exchange
+may stay inflight (see
xref:error-handler.adoc#_an_error_thrown_by_a_processor[An Error thrown by a
processor]).
+
=== camel-core - a to with an expression in its endpoint uri logs a WARN
A `to` resolves its endpoint once, when the route starts, so
`to("jms:queue:${header.queue}")` sends every message to
diff --git a/docs/user-manual/modules/ROOT/pages/error-handler.adoc
b/docs/user-manual/modules/ROOT/pages/error-handler.adoc
index fe6214b5c3f9..2bee8b700f73 100644
--- a/docs/user-manual/modules/ROOT/pages/error-handler.adoc
+++ b/docs/user-manual/modules/ROOT/pages/error-handler.adoc
@@ -221,6 +221,11 @@ Depending on the error handler, the `Error` reaches the
caller (and the exchange
inflight), or it is only logged and the route continues as if the processor
had succeeded
|===
+When the `VirtualMachineError` reaches a scheduled poll consumer (such as
`file`, `ftp` or `scheduler`) with the
+default scheduler, the scheduled task that ran the poll stops polling, and the
health check of the consumer is DOWN until the route is
+restarted. As the exchange may stay inflight, restarting or stopping the route
then waits for the shutdown timeout of
+the xref:graceful-shutdown.adoc[Graceful Shutdown] before the consumer is
stopped.
+
An application with strict reliability needs should not rely on Camel to react
to a `VirtualMachineError`. For an
`OutOfMemoryError` that the JVM raises, it can let the JVM stop with
`-XX:+ExitOnOutOfMemoryError` or
`-XX:+CrashOnOutOfMemoryError` (these options do not cover a
`StackOverflowError`, or an `OutOfMemoryError` that code