This is an automated email from the ASF dual-hosted git repository. davsclaus pushed a commit to branch CAMEL-27298-kafka-poll-error in repository https://gitbox.apache.org/repos/asf/camel.git
commit b601725dfa8e7af02114a5add7552cea6e7ae5e7 Author: Claus Ibsen <[email protected]> AuthorDate: Fri Nov 20 14:20:56 2026 +0100 CAMEL-27298: camel-kafka - the consumer logs and terminates visibly when its poll fails with an Error The Kafka client wraps only a RuntimeException of a deserializer in a RecordDeserializationException: an Error, such as the ExceptionInInitializerError of a protobuf class generated for a newer protobuf-java, is thrown out of poll as is. The poll loop handled only exceptions, so the Error ended the consumer thread, and the executor kept it in a Future that nobody reads: nothing was logged, the Kafka consumer was not closed, and the health check stayed UP. The consumer thread now logs what it does not handle at ERROR, closes the Kafka consumer, and terminates with the error as the last error of its health check, which reports DOWN. A VirtualMachineError is thrown on as before. Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: Claus Ibsen <[email protected]> --- .../apache/camel/catalog/docs/kafka-component.adoc | 6 + .../camel-kafka/src/main/docs/kafka-component.adoc | 6 + .../camel/component/kafka/KafkaFetchRecords.java | 28 +++- .../KafkaConsumerPollErrorTerminatesTest.java | 157 +++++++++++++++++++++ 4 files changed, 195 insertions(+), 2 deletions(-) diff --git a/catalog/camel-catalog/src/generated/resources/org/apache/camel/catalog/docs/kafka-component.adoc b/catalog/camel-catalog/src/generated/resources/org/apache/camel/catalog/docs/kafka-component.adoc index e12b361f823a..6b02d329e3aa 100644 --- a/catalog/camel-catalog/src/generated/resources/org/apache/camel/catalog/docs/kafka-component.adoc +++ b/catalog/camel-catalog/src/generated/resources/org/apache/camel/catalog/docs/kafka-component.adoc @@ -76,6 +76,12 @@ The default is *ERROR_HANDLER*, which will let Camel's error handler (if any con Afterwards continue to poll the next message. This behavior is similar to the _bridgeErrorHandler_ option that Camel components have. +The _pollOnError_ configuration applies to exceptions only. The Kafka client wraps only a `RuntimeException` of a +deserializer in a `RecordDeserializationException`. A `java.lang.Error`, such as an `ExceptionInInitializerError` or +`NoClassDefFoundError` of a deserializer whose classes cannot be loaded, fails every poll the same way. The consumer +thread then logs the error, closes its Kafka consumer and terminates, and the consumer health check reports DOWN. Fix +the cause (for example, a dependency version), and then restart the route or the application. + For advanced control a custom implementation of `org.apache.camel.component.kafka.PollExceptionStrategy` can be configured on the component level, which allows controlling which of the strategies to use for each exception. diff --git a/components/camel-kafka/src/main/docs/kafka-component.adoc b/components/camel-kafka/src/main/docs/kafka-component.adoc index e12b361f823a..6b02d329e3aa 100644 --- a/components/camel-kafka/src/main/docs/kafka-component.adoc +++ b/components/camel-kafka/src/main/docs/kafka-component.adoc @@ -76,6 +76,12 @@ The default is *ERROR_HANDLER*, which will let Camel's error handler (if any con Afterwards continue to poll the next message. This behavior is similar to the _bridgeErrorHandler_ option that Camel components have. +The _pollOnError_ configuration applies to exceptions only. The Kafka client wraps only a `RuntimeException` of a +deserializer in a `RecordDeserializationException`. A `java.lang.Error`, such as an `ExceptionInInitializerError` or +`NoClassDefFoundError` of a deserializer whose classes cannot be loaded, fails every poll the same way. The consumer +thread then logs the error, closes its Kafka consumer and terminates, and the consumer health check reports DOWN. Fix +the cause (for example, a dependency version), and then restart the route or the application. + For advanced control a custom implementation of `org.apache.camel.component.kafka.PollExceptionStrategy` can be configured on the component level, which allows controlling which of the strategies to use for each exception. diff --git a/components/camel-kafka/src/main/java/org/apache/camel/component/kafka/KafkaFetchRecords.java b/components/camel-kafka/src/main/java/org/apache/camel/component/kafka/KafkaFetchRecords.java index c936f444bf1b..5e45d22c85fe 100644 --- a/components/camel-kafka/src/main/java/org/apache/camel/component/kafka/KafkaFetchRecords.java +++ b/components/camel-kafka/src/main/java/org/apache/camel/component/kafka/KafkaFetchRecords.java @@ -191,6 +191,15 @@ public class KafkaFetchRecords implements Runnable { } safeConsumerClose(); + } catch (VirtualMachineError e) { + // left as before: thrown on + throw e; + } catch (RuntimeException | Error e) { + // what the poll loop does not handle, such as an Error that a deserializer throws in poll (the Kafka client + // only wraps a RuntimeException of a deserializer in a RecordDeserializationException): this task runs in an + // executor that keeps what it throws in a Future that nobody reads, so terminate visibly + terminateOnUnhandledFailure(e); + throw e; } finally { if (reconnectPool != null) { kafkaConsumer.getEndpoint().getCamelContext().getExecutorServiceManager().shutdown(reconnectPool); @@ -199,6 +208,20 @@ public class KafkaFetchRecords implements Runnable { } } + private void terminateOnUnhandledFailure(Throwable cause) { + String msg = "Terminating KafkaConsumer thread " + threadId + " receiving from " + getPrintableTopic() + + " due to " + cause + ". Restart the route or the application to recover."; + LOG.error(msg, cause); + setLastError(new KafkaConsumerFatalException(msg, cause)); + terminated = true; + setConnected(false); + + // the Kafka consumer is not used again: close it, so it leaves the consumer group and its partitions are + // assigned to the other consumers + safeUnsubscribe(); + safeConsumerClose(); + } + private void setupReconnectException(BackgroundTask task, int max) { String time = TimeUtils.printDuration(task.elapsed(), true); String topic = getPrintableTopic(); @@ -614,8 +637,9 @@ public class KafkaFetchRecords implements Runnable { } private boolean isRecoverable() { - // a suspended consumer keeps polling and reconnecting - return (pollExceptionStrategy != null && pollExceptionStrategy.canContinue() || isReconnect()) + // a suspended consumer keeps polling and reconnecting, a terminated consumer does not + return !terminated + && (pollExceptionStrategy != null && pollExceptionStrategy.canContinue() || isReconnect()) && isKafkaConsumerRunnableAndNotStopped(); } diff --git a/components/camel-kafka/src/test/java/org/apache/camel/component/kafka/KafkaConsumerPollErrorTerminatesTest.java b/components/camel-kafka/src/test/java/org/apache/camel/component/kafka/KafkaConsumerPollErrorTerminatesTest.java new file mode 100644 index 000000000000..a7e29f252c98 --- /dev/null +++ b/components/camel-kafka/src/test/java/org/apache/camel/component/kafka/KafkaConsumerPollErrorTerminatesTest.java @@ -0,0 +1,157 @@ +/* + * 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.kafka; + +import java.time.Duration; +import java.util.List; +import java.util.Map; +import java.util.Properties; +import java.util.concurrent.CopyOnWriteArrayList; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.atomic.AtomicReference; +import java.util.concurrent.locks.LockSupport; + +import org.apache.camel.BindToRegistry; +import org.apache.camel.builder.RouteBuilder; +import org.apache.camel.health.HealthCheck; +import org.apache.camel.test.junit6.CamelTestSupport; +import org.apache.kafka.clients.consumer.Consumer; +import org.apache.kafka.clients.consumer.ConsumerRecord; +import org.apache.kafka.clients.consumer.ConsumerRecords; +import org.apache.kafka.clients.consumer.MockConsumer; +import org.apache.kafka.clients.producer.Producer; +import org.apache.kafka.common.TopicPartition; +import org.junit.jupiter.api.Test; + +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.assertInstanceOf; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/** + * The Kafka client hands only a RuntimeException of a deserializer to the consumer as a RecordDeserializationException: + * an Error, such as the ExceptionInInitializerError of a generated protobuf class that cannot be initialised, is thrown + * out of poll as is. The consumer must then not stop silently: it terminates, closes the Kafka consumer and reports the + * error in its health check. Uses a {@link MockConsumer} instead of a broker. + */ +class KafkaConsumerPollErrorTerminatesTest extends CamelTestSupport { + + private static final String TOPIC = "poll-error-terminates"; + private static final TopicPartition PARTITION = new TopicPartition(TOPIC, 0); + + private final ErrorThrowingMockConsumer mockConsumer = new ErrorThrowingMockConsumer(); + private final List<String> routed = new CopyOnWriteArrayList<>(); + + @BindToRegistry("mockFactory") + private final KafkaClientFactory factory = new KafkaClientFactory() { + @Override + public Producer getProducer(Properties kafkaProps) { + throw new UnsupportedOperationException(); + } + + @Override + public Consumer getConsumer(Properties kafkaProps) { + return mockConsumer; + } + + @Override + public String getBrokers(KafkaConfiguration configuration) { + return "localhost:9092"; + } + }; + + @Override + protected RouteBuilder createRouteBuilder() { + return new RouteBuilder() { + @Override + public void configure() { + from("kafka:" + TOPIC + "?brokers=localhost:9092&kafkaClientFactory=#mockFactory&groupId=test") + .routeId("kafka") + .process(exchange -> routed.add(exchange.getMessage().getBody(String.class))); + } + }; + } + + @Override + protected void setupResources() { + mockConsumer.updateBeginningOffsets(Map.of(PARTITION, 0L)); + mockConsumer.schedulePollTask(() -> mockConsumer.rebalance(List.of(PARTITION))); + } + + @Test + void testErrorFromPollTerminatesTheConsumerVisibly() { + await().atMost(20, TimeUnit.SECONDS).until(() -> mockConsumer.assignment().contains(PARTITION)); + mockConsumer.addRecord(new ConsumerRecord<>(TOPIC, 0, 0L, null, "a")); + await().atMost(20, TimeUnit.SECONDS).until(() -> routed.contains("a")); + + ExceptionInInitializerError error = new ExceptionInInitializerError( + new IllegalStateException("Simulated failure initialising a generated class")); + mockConsumer.pollError.set(error); + await().atMost(20, TimeUnit.SECONDS).until(mockConsumer.closed::get); + + KafkaConsumer consumer = (KafkaConsumer) context.getRoute("kafka").getConsumer(); + List<TaskHealthState> states = consumer.healthStates(); + assertEquals(1, states.size()); + TaskHealthState state = states.get(0); + assertTrue(state.isTerminated(), "The consumer should be terminated"); + assertFalse(state.isReady(), "The consumer should not be ready"); + assertFalse(state.isRecoverable(), "The consumer should not be recoverable"); + KafkaConsumerFatalException fatal = assertInstanceOf(KafkaConsumerFatalException.class, state.getLastError()); + assertSame(error, fatal.getCause()); + + KafkaConsumerHealthCheck check = new KafkaConsumerHealthCheck(consumer, "kafka"); + check.setCamelContext(context); + HealthCheck.Result result = check.call(); + assertEquals(HealthCheck.State.DOWN, result.getState()); + assertTrue(result.getMessage().orElseThrow().contains("terminated the kafka consumer"), + result.getMessage().orElseThrow()); + assertSame(fatal, result.getError().orElseThrow()); + } + + private static final class ErrorThrowingMockConsumer extends MockConsumer<Object, Object> { + final AtomicReference<Error> pollError = new AtomicReference<>(); + final AtomicBoolean closed = new AtomicBoolean(); + + ErrorThrowingMockConsumer() { + super("earliest"); + } + + @Override + public synchronized ConsumerRecords<Object, Object> poll(Duration timeout) { + // as the Kafka client does with an Error that a deserializer throws while it parses the fetched records + Error error = pollError.getAndSet(null); + if (error != null) { + throw error; + } + ConsumerRecords<Object, Object> records = super.poll(timeout); + if (records.isEmpty()) { + // a real consumer waits up to the poll timeout when there is nothing to fetch + LockSupport.parkNanos(TimeUnit.MILLISECONDS.toNanos(10)); + } + return records; + } + + @Override + public synchronized void close() { + closed.set(true); + // keep the mock usable: a stopped route closes the consumer + } + } +}
