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 b02f84a7b43d CAMEL-27496: camel-google-pubsub - a subscriber loop
subscribes or pulls again after any failure, and the consumer has a readiness
health check (#30867)
b02f84a7b43d is described below
commit b02f84a7b43d5edc9ebbf6681745ea32380c4450
Author: Claus Ibsen <[email protected]>
AuthorDate: Thu Nov 26 13:58:00 2026 +0100
CAMEL-27496: camel-google-pubsub - a subscriber loop subscribes or pulls
again after any failure, and the consumer has a readiness health check (#30867)
A subscriber loop of the google-pubsub consumer could end while the consumer
was started, and nothing started it again: a non-retryable error of a
synchronous pull (thrown on, run() only logged it), a non-retryable failure
of an asynchronous Subscriber (the loop ended on purpose), an IOException of
getSubscriber (outside the try), and an Error (run() caught Exception only,
in a Future nobody reads, so not even a log line). The route stayed Started,
its health check UP, and the consumer received nothing until the route was
restarted.
- A failure that ends a pull or a subscription (Exception or Error) is
logged (first in a row at ERROR with the stack trace, repeats in one WARN
line), given to the ExceptionHandler with bridgeErrorHandler, and the loop
subscribes or pulls again after the retry delay counted from the start of
the failed attempt (waitBeforeRetry of CAMEL-27495, now also used by the
asynchronous loop, so a stop ends that wait at once too).
- The failure of an asynchronous Subscriber is reported, instead of the
IllegalStateException of awaitTerminated that wraps it. After failed
attempts, a Subscriber only counts as working once it has run for the
retry delay, as it is running before its streaming pull is answered.
- A VirtualMachineError stops the consumer until the route is restarted
(isStopOnFatalError, handleFatalError of CAMEL-27515), which also ends the
subscribers, pulls and retry delays of the other loops.
- GooglePubsubConsumerHealthCheck (readiness): DOWN with the failure while a
loop of the current start waits to subscribe or pull again, or has ended
for good, and after a fatal error.
- Upgrade guide and component docs.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Claus Ibsen <[email protected]>
---
.../catalog/docs/google-pubsub-component.adoc | 6 +
.../src/main/docs/google-pubsub-component.adoc | 6 +
.../google/pubsub/GooglePubsubConsumer.java | 286 ++++++++++-----
.../pubsub/GooglePubsubConsumerHealthCheck.java | 89 +++++
.../GooglePubsubConsumerLoopRestartTest.java | 392 +++++++++++++++++++++
.../ROOT/pages/camel-4x-upgrade-guide-4_24.adoc | 19 +
6 files changed, 719 insertions(+), 79 deletions(-)
diff --git
a/catalog/camel-catalog/src/generated/resources/org/apache/camel/catalog/docs/google-pubsub-component.adoc
b/catalog/camel-catalog/src/generated/resources/org/apache/camel/catalog/docs/google-pubsub-component.adoc
index 754aa77c15cb..8789a7e02214 100644
---
a/catalog/camel-catalog/src/generated/resources/org/apache/camel/catalog/docs/google-pubsub-component.adoc
+++
b/catalog/camel-catalog/src/generated/resources/org/apache/camel/catalog/docs/google-pubsub-component.adoc
@@ -95,6 +95,12 @@ The component acks or nacks the message it received, also
when the route changed
With manual acknowledgement and the synchronous consumer, the Acknowledgement
IDs are taken from the exchange given to
`ack` or `nack` (see <<Manual Acknowledgement>>).
+When the consumer cannot get messages (Pub/Sub cannot be reached, a missing
permission or subscription, credentials
+that cannot be loaded), it logs the failure (the first one in a row at ERROR,
the next ones in one WARN line), gives it
+to the exception handler (with `bridgeErrorHandler=true`, to the error handler
of the route), and subscribes or pulls
+again every 5 seconds until the cause is gone. Meanwhile, with the consumer
health checks of Camel enabled, the
+readiness check of the consumer of the route (`consumer:<routeId>`) is DOWN
with the failure.
+
=== Delivery Attempts and Dead Letter Queues
When a subscription has a
https://cloud.google.com/pubsub/docs/dead-letter-topics[dead-letter policy]
configured,
diff --git
a/components/camel-google/camel-google-pubsub/src/main/docs/google-pubsub-component.adoc
b/components/camel-google/camel-google-pubsub/src/main/docs/google-pubsub-component.adoc
index 754aa77c15cb..8789a7e02214 100644
---
a/components/camel-google/camel-google-pubsub/src/main/docs/google-pubsub-component.adoc
+++
b/components/camel-google/camel-google-pubsub/src/main/docs/google-pubsub-component.adoc
@@ -95,6 +95,12 @@ The component acks or nacks the message it received, also
when the route changed
With manual acknowledgement and the synchronous consumer, the Acknowledgement
IDs are taken from the exchange given to
`ack` or `nack` (see <<Manual Acknowledgement>>).
+When the consumer cannot get messages (Pub/Sub cannot be reached, a missing
permission or subscription, credentials
+that cannot be loaded), it logs the failure (the first one in a row at ERROR,
the next ones in one WARN line), gives it
+to the exception handler (with `bridgeErrorHandler=true`, to the error handler
of the route), and subscribes or pulls
+again every 5 seconds until the cause is gone. Meanwhile, with the consumer
health checks of Camel enabled, the
+readiness check of the consumer of the route (`consumer:<routeId>`) is DOWN
with the failure.
+
=== Delivery Attempts and Dead Letter Queues
When a subscription has a
https://cloud.google.com/pubsub/docs/dead-letter-topics[dead-letter policy]
configured,
diff --git
a/components/camel-google/camel-google-pubsub/src/main/java/org/apache/camel/component/google/pubsub/GooglePubsubConsumer.java
b/components/camel-google/camel-google-pubsub/src/main/java/org/apache/camel/component/google/pubsub/GooglePubsubConsumer.java
index e04a0756c6bc..bd878276cbe9 100644
---
a/components/camel-google/camel-google-pubsub/src/main/java/org/apache/camel/component/google/pubsub/GooglePubsubConsumer.java
+++
b/components/camel-google/camel-google-pubsub/src/main/java/org/apache/camel/component/google/pubsub/GooglePubsubConsumer.java
@@ -16,8 +16,8 @@
*/
package org.apache.camel.component.google.pubsub;
-import java.io.IOException;
import java.time.Duration;
+import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.concurrent.CancellationException;
@@ -27,12 +27,13 @@ import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
+import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;
import com.google.api.core.AbstractApiService;
import com.google.api.core.ApiFuture;
-import com.google.api.gax.rpc.ApiException;
+import com.google.api.core.ApiService;
import com.google.cloud.pubsub.v1.MessageReceiver;
import com.google.cloud.pubsub.v1.Subscriber;
import com.google.cloud.pubsub.v1.SubscriptionAdminClient;
@@ -60,6 +61,8 @@ import org.apache.camel.support.UnitOfWorkHelper;
import org.apache.camel.support.task.BackgroundTask;
import org.apache.camel.support.task.Tasks;
import org.apache.camel.support.task.budget.Budgets;
+import org.apache.camel.util.ObjectHelper;
+import org.apache.camel.util.TimeUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -84,6 +87,10 @@ public class GooglePubsubConsumer extends DefaultConsumer
implements ShutdownAwa
* The retry delays the subscriber loops wait in now: a stop ends them at
once, as the loops do not pull again.
*/
private final Set<BackgroundTask> retryWaits =
ConcurrentHashMap.newKeySet();
+ /**
+ * The subscriber loops of the current start of this consumer, for the
health check.
+ */
+ private volatile List<SubscriberWrapper> loops = List.of();
private ExecutorService executor;
private ScheduledExecutorService taskExecutor;
private final List<Subscriber> subscribers;
@@ -132,9 +139,19 @@ public class GooglePubsubConsumer extends DefaultConsumer
implements ShutdownAwa
taskExecutor =
endpoint.getCamelContext().getExecutorServiceManager()
.newSingleThreadScheduledExecutor(this,
"PubSubReconnectTask");
}
+ if (getHealthCheck() == null) {
+ // readiness: DOWN while a subscriber loop cannot get messages
(used when the consumer health checks of
+ // Camel are enabled)
+ setHealthCheck(new GooglePubsubConsumerHealthCheck(this,
getRouteId()));
+ }
long current = generation.incrementAndGet();
+ List<SubscriberWrapper> started = new ArrayList<>();
for (int i = 0; i < endpoint.getConcurrentConsumers(); i++) {
- executor.submit(new SubscriberWrapper(current));
+ started.add(new SubscriberWrapper(current));
+ }
+ loops = List.copyOf(started);
+ for (SubscriberWrapper loop : started) {
+ executor.submit(loop);
}
}
@@ -197,6 +214,70 @@ public class GooglePubsubConsumer extends DefaultConsumer
implements ShutdownAwa
// noop
}
+ @Override
+ protected boolean isStopOnFatalError() {
+ // the consumer pulls messages in loops: it stops after a
VirtualMachineError (CAMEL-27515)
+ return true;
+ }
+
+ @Override
+ public boolean handleFatalError(Throwable error) {
+ if (!super.handleFatalError(error)) {
+ return false;
+ }
+ // the loops no longer pull or subscribe again (isRunAllowed() is
false): end their subscribers, pulls and
+ // retry delays now, as a stop does, until the route is restarted
+ cancelRetryWaits();
+ subscribers.forEach(AbstractApiService::stopAsync);
+ safeCancelSynchronousPullResponses();
+ return true;
+ }
+
+ /**
+ * The failure of a subscriber loop of the current start of this consumer
that waits to subscribe or pull again, or
+ * that has ended for good, or null while every loop gets messages (or
tries to for the first time).
+ */
+ Throwable getLoopFailure() {
+ for (SubscriberWrapper loop : loops) {
+ Throwable failure = loop.failure;
+ if (failure != null) {
+ return failure;
+ }
+ }
+ return null;
+ }
+
+ /**
+ * The number of subscriber loops of the current start of this consumer
that cannot get messages.
+ */
+ int getFailingLoops() {
+ int failing = 0;
+ for (SubscriberWrapper loop : loops) {
+ if (loop.failure != null) {
+ failing++;
+ }
+ }
+ return failing;
+ }
+
+ /**
+ * The highest number of failed attempts in a row of the subscriber loops
of the current start of this consumer.
+ */
+ int getFailedAttempts() {
+ int failed = 0;
+ for (SubscriberWrapper loop : loops) {
+ failed = Math.max(failed, loop.failuresInARow.get());
+ }
+ return failed;
+ }
+
+ /**
+ * The retry delay of the subscriber loops.
+ */
+ Duration getRetryDelay() {
+ return retryDelay;
+ }
+
private void cancelRetryWaits() {
// a loop that waits does not pull again after a stop: end the wait
now instead of after the retry delay (in
// doShutdown the scheduler of the wait is shut down, which would
leave the loop waiting until its thread is
@@ -268,8 +349,12 @@ public class GooglePubsubConsumer extends DefaultConsumer
implements ShutdownAwa
private final String subscriptionName;
private final long wrapperGeneration;
- // failed attempts since the last pull or subscription that worked;
only used by the thread of this loop
- private int failuresInARow;
+ // failed attempts since the last pull or subscription that worked;
written by the thread of this loop only, read
+ // by the health check
+ private final AtomicInteger failuresInARow = new AtomicInteger();
+ // the last failure while the loop waits to subscribe or pull again,
or the failure that ended it for good; null
+ // while it gets messages (for the health check)
+ private volatile Throwable failure;
SubscriberWrapper(long wrapperGeneration) {
this.wrapperGeneration = wrapperGeneration;
@@ -298,26 +383,48 @@ public class GooglePubsubConsumer extends DefaultConsumer
implements ShutdownAwa
}
localLog.debug("Exit run for subscription {}",
subscriptionName);
- } catch (Exception e) {
- if (e instanceof InterruptedException) {
- Thread.currentThread().interrupt();
+ } catch (InterruptedException e) {
+ Thread.currentThread().interrupt();
+ ended("Interrupted while getting messages from PubSub " +
subscriptionName, e);
+ } catch (VirtualMachineError e) {
+ // a JVM-level failure: the consumer stops consuming until the
route is restarted, and its health check
+ // is DOWN with the error (CAMEL-27515). It is not thrown on,
as nothing reads the future of this loop. A
+ // loop of an earlier start only logs it: it does not stop the
consumer started again since
+ localLog.error("Fatal error getting messages from PubSub {}.
The consumer stops consuming until the route"
+ + " is restarted.",
+ subscriptionName, e);
+ if (wrapperGeneration == generation.get()) {
+ handleFatalError(e);
}
- localLog.error("Failure getting messages from PubSub", e);
+ } catch (Exception | Error e) {
+ // not expected, as the loops retry after a failure (such as
an exception thrown by the exception
+ // handler)
+ ended("Failure getting messages from PubSub " +
subscriptionName, e);
+ }
+ }
- // allow camel error handler to be aware
- if (endpoint.isBridgeErrorHandler()) {
- getExceptionHandler().handleException(e);
- }
+ /**
+ * This loop ends while it may still pull: it reports the failure
until the consumer is started again.
+ */
+ private void ended(String message, Throwable e) {
+ if (isPullAllowed()) {
+ localLog.error("{}. The subscriber loop ends until the route
is restarted.", message, e);
+ failure = e;
+ } else {
+ localLog.debug(message, e);
}
}
- private void asynchronousPull(String subscriptionName) throws
IOException {
+ private void asynchronousPull(String subscriptionName) throws
InterruptedException {
while (isPullAllowed()) {
- MessageReceiver messageReceiver = new
CamelMessageReceiver(GooglePubsubConsumer.this, endpoint, processor);
-
- Subscriber subscriber =
endpoint.getComponent().getSubscriber(subscriptionName, messageReceiver,
endpoint);
+ long attemptStarted = System.nanoTime();
+ Subscriber subscriber = null;
boolean subscriberAdded = false;
+ Throwable attemptFailure = null;
try {
+ MessageReceiver messageReceiver
+ = new
CamelMessageReceiver(GooglePubsubConsumer.this, endpoint, processor);
+ subscriber =
endpoint.getComponent().getSubscriber(subscriptionName, messageReceiver,
endpoint);
subscriber.startAsync().awaitRunning();
// Only add to list after successful startup
subscribers.add(subscriber);
@@ -326,65 +433,53 @@ public class GooglePubsubConsumer extends DefaultConsumer
implements ShutdownAwa
if (!isPullAllowed()) {
subscriber.stopAsync();
}
- subscriber.awaitTerminated();
- } catch (Exception e) {
- // Remove from list if it was added
- if (subscriberAdded) {
- subscribers.remove(subscriber);
- }
-
- // Check if error is recoverable
- boolean isRecoverable = false;
- if (e instanceof ApiException ae) {
- isRecoverable = ae.isRetryable();
- } else if (e.getCause() instanceof ApiException ae) {
- isRecoverable = ae.isRetryable();
- }
-
- if (isRecoverable) {
- localLog.error("Retryable error getting messages from
PubSub", e);
- } else {
- localLog.error("Non-recoverable error getting messages
from PubSub, stopping subscriber loop", e);
- }
-
- // allow camel error handler to be aware
- if (endpoint.isBridgeErrorHandler()) {
- getExceptionHandler().handleException(e);
- }
-
- // For non-recoverable errors, exit the loop
- if (!isRecoverable) {
- break;
- }
-
- // Add backoff delay for recoverable errors to prevent
tight loop
- // We use initialDelay for the actual delay, and
maxIterations(1) to run once
- Tasks.backgroundTask()
- .withBudget(Budgets.iterationTimeBudget()
- .withMaxIterations(1)
- .withInitialDelay(retryDelay)
- .withInterval(Duration.ofMillis(1))
- .withUnlimitedDuration()
- .build())
- .withScheduledExecutor(taskExecutor)
- .withName("PubSubRetryDelay")
- .build()
- .run(getEndpoint().getCamelContext(), () -> true);
+ awaitTerminated(subscriber);
+ } catch (VirtualMachineError e) {
+ throw e;
+ } catch (Exception | Error e) {
+ // the failure of the subscriber (such as
PERMISSION_DENIED or NOT_FOUND) instead of the
+ // IllegalStateException of awaitRunning or
awaitTerminated that wraps it
+ attemptFailure = subscriber != null && subscriber.state()
== ApiService.State.FAILED
+ ? subscriber.failureCause() : e;
} finally {
- localLog.debug("Stopping async subscriber {}",
subscriptionName);
- subscriber.stopAsync();
+ if (subscriber != null) {
+ localLog.debug("Stopping async subscriber {}",
subscriptionName);
+ subscriber.stopAsync();
+ }
// Ensure cleanup from list
if (subscriberAdded) {
subscribers.remove(subscriber);
}
}
+ if (attemptFailure != null) {
+ retryAfterFailure("Failure getting messages from PubSub "
+ subscriptionName + ". Subscribing again",
+ attemptFailure, attemptStarted);
+ }
+ }
+ }
+
+ /**
+ * Waits until the subscriber terminates. After failed attempts, the
subscriber only counts as working once it
+ * has run for the retry delay: it is running before its streaming
pull is answered, so a missing subscription
+ * or permission fails it right after the start.
+ */
+ private void awaitTerminated(Subscriber subscriber) {
+ if (failuresInARow.get() > 0) {
+ try {
+ subscriber.awaitTerminated(retryDelay.toMillis(),
TimeUnit.MILLISECONDS);
+ return;
+ } catch (TimeoutException e) {
+ pulled();
+ }
}
+ subscriber.awaitTerminated();
}
- private void synchronousPull(String subscriptionName) throws
ExecutionException, InterruptedException {
+ private void synchronousPull(String subscriptionName) throws
InterruptedException {
while (isPullAllowed()) {
long attemptStarted = System.nanoTime();
ApiFuture<PullResponse> synchronousPullResponseFuture = null;
+ Throwable attemptFailure = null;
try (SubscriberStub subscriber =
endpoint.getComponent().getSubscriberStub(endpoint)) {
PullRequest pullRequest = PullRequest.newBuilder()
@@ -497,23 +592,52 @@ public class GooglePubsubConsumer extends DefaultConsumer
implements ShutdownAwa
}
} catch (CancellationException e) {
localLog.debug("PubSub synchronous pull request
cancelled", e);
- } catch (IOException e) {
- // such as credentials that cannot be loaded: an attempt
at once would fail the same way
- logFailure("I/O exception while getting messages from
PubSub. Reconnecting.", e);
- waitBeforeRetry(attemptStarted);
+ } catch (InterruptedException | VirtualMachineError e) {
+ throw e;
} catch (ExecutionException e) {
- if (e.getCause() instanceof ApiException &&
((ApiException) (e.getCause())).isRetryable()) {
- logFailure("Retryable API exception in getting
messages from PubSub", e.getCause());
- waitBeforeRetry(attemptStarted);
- } else {
- throw e;
- }
+ // the failure of the pull, retryable or not (such as
PERMISSION_DENIED while an IAM binding
+ // is changed, or NOT_FOUND while the subscription is
created again)
+ attemptFailure = e.getCause() != null ? e.getCause() : e;
+ } catch (Exception | Error e) {
+ // such as credentials that cannot be loaded
(IOException), or a client library that does not
+ // match (NoClassDefFoundError): an attempt at once would
fail the same way
+ attemptFailure = e;
} finally {
if (synchronousPullResponseFuture != null) {
pendingSynchronousPullResponses.remove(synchronousPullResponseFuture);
}
}
+ if (attemptFailure != null) {
+ retryAfterFailure("Failure getting messages from PubSub "
+ subscriptionName + ". Pulling again",
+ attemptFailure, attemptStarted);
+ }
+ }
+ }
+
+ /**
+ * A failed attempt (Exception or Error) ends the subscription or the
pull, but not the loop: it is logged,
+ * given to the exception handler with bridgeErrorHandler, and the
loop subscribes or pulls again after the
+ * retry delay, until the cause is gone. A VirtualMachineError is
thrown on.
+ */
+ private void retryAfterFailure(String message, Throwable e, long
attemptStarted) throws InterruptedException {
+ VirtualMachineError fatal = ObjectHelper.getVirtualMachineError(e);
+ if (fatal != null) {
+ throw fatal;
+ }
+ if (!isPullAllowed()) {
+ // the consumer stops: a failure of the subscription or pull
it ends
+ localLog.debug(message, e);
+ return;
+ }
+ failuresInARow.incrementAndGet();
+ // after the count: a failure the health check sees comes with its
count
+ failure = e;
+ logFailure(message + " within " +
TimeUtils.printDuration(retryDelay) + '.', e);
+ // allow camel error handler to be aware
+ if (endpoint.isBridgeErrorHandler()) {
+ getExceptionHandler().handleException(e);
}
+ waitBeforeRetry(attemptStarted);
}
/**
@@ -521,10 +645,11 @@ public class GooglePubsubConsumer extends DefaultConsumer
implements ShutdownAwa
* trace at DEBUG), as the loop retries until the cause is gone.
*/
private void logFailure(String message, Throwable e) {
- if (failuresInARow++ == 0) {
+ int failures = failuresInARow.get();
+ if (failures <= 1) {
localLog.error(message, e);
} else {
- localLog.warn("{} ({} failed attempts in a row: {})", message,
failuresInARow, e.toString());
+ localLog.warn("{} ({} failed attempts in a row: {})", message,
failures, e.toString());
localLog.debug(message, e);
}
}
@@ -533,10 +658,13 @@ public class GooglePubsubConsumer extends DefaultConsumer
implements ShutdownAwa
* A pull or a subscription worked: logs once that the loop recovered
from failed attempts.
*/
private void pulled() {
- if (failuresInARow > 0) {
+ int failures = failuresInARow.get();
+ if (failures > 0) {
localLog.info("Getting messages from PubSub {} again after {}
failed attempts", subscriptionName,
- failuresInARow);
- failuresInARow = 0;
+ failures);
+ // the failure before the count, as the health check reads
them in the other order
+ failure = null;
+ failuresInARow.set(0);
}
}
diff --git
a/components/camel-google/camel-google-pubsub/src/main/java/org/apache/camel/component/google/pubsub/GooglePubsubConsumerHealthCheck.java
b/components/camel-google/camel-google-pubsub/src/main/java/org/apache/camel/component/google/pubsub/GooglePubsubConsumerHealthCheck.java
new file mode 100644
index 000000000000..7f61d15b0b2b
--- /dev/null
+++
b/components/camel-google/camel-google-pubsub/src/main/java/org/apache/camel/component/google/pubsub/GooglePubsubConsumerHealthCheck.java
@@ -0,0 +1,89 @@
+/*
+ * 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.google.pubsub;
+
+import java.util.Map;
+
+import org.apache.camel.health.HealthCheck;
+import org.apache.camel.health.HealthCheckResultBuilder;
+import org.apache.camel.util.TimeUtils;
+
+/**
+ * Readiness health check of the Google PubSub consumer: DOWN with the failure
while a subscriber loop of the current
+ * start of the consumer waits to subscribe or pull again after a failure (it
retries every retry delay until the cause
+ * is gone), or has ended for good, and UP otherwise.
+ */
+public class GooglePubsubConsumerHealthCheck implements HealthCheck {
+
+ private final GooglePubsubConsumer consumer;
+ private final String routeId;
+ private volatile boolean enabled = true;
+
+ public GooglePubsubConsumerHealthCheck(GooglePubsubConsumer consumer,
String routeId) {
+ this.consumer = consumer;
+ this.routeId = routeId;
+ }
+
+ @Override
+ public String getGroup() {
+ return "camel";
+ }
+
+ @Override
+ public String getId() {
+ return routeId != null ? "consumer:google-pubsub-" + routeId :
"consumer:google-pubsub";
+ }
+
+ @Override
+ public boolean isEnabled() {
+ return enabled;
+ }
+
+ @Override
+ public void setEnabled(boolean enabled) {
+ this.enabled = enabled;
+ }
+
+ @Override
+ public Result call(Map<String, Object> options) {
+ HealthCheckResultBuilder builder = HealthCheckResultBuilder.on(this);
+ if (!enabled) {
+ // as AbstractHealthCheck of camel-health does for a disabled check
+ return builder.message("Disabled").unknown().build();
+ }
+ Throwable fatal = consumer.getFatalError();
+ if (fatal != null) {
+ return builder.down().error(fatal)
+ .message("The consumer stopped after a fatal error.
Restart the route to start it again.")
+ .build();
+ }
+ // the failure first and the count second: a failure seen here always
comes with its count
+ Throwable failure = consumer.getLoopFailure();
+ if (failure == null) {
+ return builder.up().build();
+ }
+ int failingLoops = consumer.getFailingLoops();
+ int failedAttempts = consumer.getFailedAttempts();
+ builder.detail("failing.loops", failingLoops);
+ builder.detail("failed.attempts", failedAttempts);
+ String message = failedAttempts > 0
+ ? "Cannot get messages from PubSub (" + failedAttempts + "
failed attempt(s) in a row, trying again every "
+ + TimeUtils.printDuration(consumer.getRetryDelay()) + ")"
+ : "Cannot get messages from PubSub: a subscriber loop has
ended. Restart the route to start it again.";
+ return builder.down().error(failure).message(message).build();
+ }
+}
diff --git
a/components/camel-google/camel-google-pubsub/src/test/java/org/apache/camel/component/google/pubsub/GooglePubsubConsumerLoopRestartTest.java
b/components/camel-google/camel-google-pubsub/src/test/java/org/apache/camel/component/google/pubsub/GooglePubsubConsumerLoopRestartTest.java
new file mode 100644
index 000000000000..d021ccccd129
--- /dev/null
+++
b/components/camel-google/camel-google-pubsub/src/test/java/org/apache/camel/component/google/pubsub/GooglePubsubConsumerLoopRestartTest.java
@@ -0,0 +1,392 @@
+/*
+ * 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.google.pubsub;
+
+import java.io.FileNotFoundException;
+import java.io.IOException;
+import java.time.Duration;
+import java.util.List;
+import java.util.UUID;
+import java.util.concurrent.CopyOnWriteArrayList;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.TimeoutException;
+import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.concurrent.atomic.AtomicInteger;
+
+import com.google.api.core.ApiFuture;
+import com.google.api.core.ApiFutures;
+import com.google.api.core.ApiService;
+import com.google.api.core.SettableApiFuture;
+import com.google.api.gax.grpc.GrpcStatusCode;
+import com.google.api.gax.rpc.NotFoundException;
+import com.google.api.gax.rpc.PermissionDeniedException;
+import com.google.api.gax.rpc.UnaryCallable;
+import com.google.cloud.pubsub.v1.AckReplyConsumer;
+import com.google.cloud.pubsub.v1.MessageReceiver;
+import com.google.cloud.pubsub.v1.Subscriber;
+import com.google.cloud.pubsub.v1.stub.SubscriberStub;
+import com.google.protobuf.ByteString;
+import com.google.protobuf.Empty;
+import com.google.pubsub.v1.AcknowledgeRequest;
+import com.google.pubsub.v1.PubsubMessage;
+import com.google.pubsub.v1.PullRequest;
+import com.google.pubsub.v1.PullResponse;
+import com.google.pubsub.v1.ReceivedMessage;
+import io.grpc.Status;
+import org.apache.camel.CamelContext;
+import org.apache.camel.Exchange;
+import org.apache.camel.builder.RouteBuilder;
+import org.apache.camel.component.mock.MockEndpoint;
+import org.apache.camel.health.HealthCheck;
+import org.apache.camel.impl.DefaultCamelContext;
+import org.apache.camel.support.PluginHelper;
+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.Test;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.awaitility.Awaitility.await;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.ArgumentMatchers.anyLong;
+import static org.mockito.Mockito.doAnswer;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.when;
+
+/**
+ * A failure that ends a pull or a subscription (a non-retryable error,
credentials that cannot be loaded, an Error of a
+ * client library that does not match) must not end the subscriber loop: the
loop subscribes or pulls again after the
+ * retry delay, and the health check of the consumer is DOWN with the failure
until it gets messages again.
+ */
+class GooglePubsubConsumerLoopRestartTest {
+
+ private static final Duration RETRY_DELAY = Duration.ofMillis(500);
+
+ private final CamelContext context = new DefaultCamelContext();
+ // a logger of its own, so the log lines of other tests running at the
same time are not captured
+ private final String loggerId = "pubsub-loop-restart-" + UUID.randomUUID();
+ private final LogEventCaptor captor = new LogEventCaptor();
+ private final SettableApiFuture<PullResponse> pending =
SettableApiFuture.create();
+ private final AtomicBoolean failing = new AtomicBoolean(true);
+ private final AtomicInteger attempts = new AtomicInteger();
+
+ @AfterEach
+ void tearDown() {
+ pending.cancel(true);
+ context.stop();
+ ((Logger) LogManager.getLogger(loggerId)).removeAppender(captor);
+ }
+
+ @Test
+ void syncPullFailingWithNonRetryableErrorIsPulledAgain() throws Exception {
+ SubscriberStub stub = stub(() -> failing.get()
+ ? ApiFutures.immediateFailedFuture(new
PermissionDeniedException(
+ "the IAM binding is being changed", null,
GrpcStatusCode.of(Status.Code.PERMISSION_DENIED), false))
+ : ApiFutures.immediateFuture(message()));
+ GooglePubsubConsumer consumer = startRoute(new GooglePubsubComponent()
{
+ @Override
+ public SubscriberStub getSubscriberStub(GooglePubsubEndpoint
endpoint) {
+ return stub;
+ }
+ }, "synchronousPull=true", RETRY_DELAY);
+
+ // the loop pulls again after the retry delay, and the consumer is
DOWN meanwhile
+ await().atMost(Duration.ofSeconds(10)).until(() -> attempts.get() >=
2);
+ HealthCheck.Result down = consumer.getHealthCheck().call();
+ assertThat(down.getState()).isEqualTo(HealthCheck.State.DOWN);
+
assertThat(down.getError()).containsInstanceOf(PermissionDeniedException.class);
+ assertThat(down.getDetails()).containsEntry("failing.loops", 1);
+
+ failing.set(false);
+ assertReceivedAndUp(consumer);
+ // the first failure in a row with its stack trace at ERROR, the next
ones in one WARN line
+ assertThat(captor.events).anySatisfy(event -> {
+ assertThat(event.getLevel()).isEqualTo(Level.ERROR);
+
assertThat(event.getThrown()).isInstanceOf(PermissionDeniedException.class);
+ });
+ assertThat(captor.events).anySatisfy(event -> {
+ assertThat(event.getLevel()).isEqualTo(Level.WARN);
+
assertThat(event.getMessage().getFormattedMessage()).contains("failed attempts
in a row");
+ });
+ }
+
+ @Test
+ void syncPullFailingWithAnErrorIsLoggedAndPulledAgain() throws Exception {
+ SubscriberStub stub = stub(() ->
ApiFutures.immediateFuture(message()));
+ GooglePubsubConsumer consumer = startRoute(new GooglePubsubComponent()
{
+ @Override
+ public SubscriberStub getSubscriberStub(GooglePubsubEndpoint
endpoint) {
+ if (failing.get()) {
+ attempts.incrementAndGet();
+ // a client library that does not match the one the
component was built with
+ throw new
NoClassDefFoundError("io/grpc/internal/SomethingRemoved");
+ }
+ return stub;
+ }
+ }, "synchronousPull=true", RETRY_DELAY);
+
+ await().atMost(Duration.ofSeconds(10)).until(() -> attempts.get() >=
1);
+ await().atMost(Duration.ofSeconds(10)).untilAsserted(() ->
assertThat(captor.events).anySatisfy(event -> {
+ assertThat(event.getLevel()).isEqualTo(Level.ERROR);
+
assertThat(event.getThrown()).isInstanceOf(NoClassDefFoundError.class);
+ }));
+
assertThat(consumer.getHealthCheck().call().getState()).isEqualTo(HealthCheck.State.DOWN);
+
+ failing.set(false);
+ assertReceivedAndUp(consumer);
+ }
+
+ @Test
+ void
asyncSubscriberThatCannotBeCreatedOrFailsAfterTheStartIsSubscribedAgain()
throws Exception {
+ List<CountDownLatch> stops = new CopyOnWriteArrayList<>();
+ GooglePubsubConsumer consumer = startRoute(new GooglePubsubComponent()
{
+ @Override
+ public Subscriber getSubscriber(
+ String subscriptionName, MessageReceiver messageReceiver,
GooglePubsubEndpoint endpoint)
+ throws IOException {
+ int attempt = attempts.incrementAndGet();
+ if (attempt == 1) {
+ // credentials that cannot be loaded at that moment
+ throw new FileNotFoundException("the service account key
file was removed");
+ }
+ // the subscriber of the second attempt fails right after it
started (the subscription is created
+ // again), the next ones work once the failure is gone
+ try {
+ return subscriber(messageReceiver, stops, attempt == 2 ||
failing.get());
+ } catch (TimeoutException e) {
+ // not thrown by the stubbing
+ throw new IllegalStateException(e);
+ }
+ }
+ }, "bridgeErrorHandler=true", RETRY_DELAY);
+
+ await().atMost(Duration.ofSeconds(10)).until(() -> attempts.get() >=
3);
+ HealthCheck.Result down = consumer.getHealthCheck().call();
+ assertThat(down.getState()).isEqualTo(HealthCheck.State.DOWN);
+ // the failure of the subscriber, not the IllegalStateException of
awaitTerminated
+
assertThat(down.getError()).containsInstanceOf(NotFoundException.class);
+ // with bridgeErrorHandler, the failures go to the error handler of
the route
+ MockEndpoint errors = context.getEndpoint("mock:error",
MockEndpoint.class);
+ assertThat(errors.getReceivedExchanges()).anySatisfy(
+ exchange ->
assertThat(exchange.getProperty(Exchange.EXCEPTION_CAUGHT, Throwable.class))
+ .isInstanceOf(FileNotFoundException.class));
+
+ failing.set(false);
+ assertReceivedAndUp(consumer);
+ }
+
+ @Test
+ void asyncStopDuringTheRetryDelayEndsTheWait() throws Exception {
+ startRoute(new GooglePubsubComponent() {
+ @Override
+ public Subscriber getSubscriber(
+ String subscriptionName, MessageReceiver messageReceiver,
GooglePubsubEndpoint endpoint)
+ throws IOException {
+ attempts.incrementAndGet();
+ throw new FileNotFoundException("the service account key file
was removed");
+ }
+ }, "", Duration.ofMinutes(1));
+
+ await().atMost(Duration.ofSeconds(10)).until(this::waitingForRetry);
+ context.getRouteController().stopRoute("pubsub", 10, TimeUnit.SECONDS);
+
+ // the loop does not wait the rest of the minute: it ends with the stop
+ await().atMost(Duration.ofSeconds(5)).until(() -> !waitingForRetry());
+ assertThat(attempts.get()).isEqualTo(1);
+ }
+
+ @Test
+ void virtualMachineErrorStopsTheConsumerUntilTheRouteIsRestarted() throws
Exception {
+ GooglePubsubConsumer consumer = startRoute(new GooglePubsubComponent()
{
+ @Override
+ public SubscriberStub getSubscriberStub(GooglePubsubEndpoint
endpoint) {
+ attempts.incrementAndGet();
+ throw new OutOfMemoryError("thrown by the test");
+ }
+ }, "synchronousPull=true", RETRY_DELAY);
+
+ await().atMost(Duration.ofSeconds(10)).until(() ->
consumer.getFatalError() != null);
+ HealthCheck.Result down = consumer.getHealthCheck().call();
+ assertThat(down.getState()).isEqualTo(HealthCheck.State.DOWN);
+ assertThat(down.getError()).containsInstanceOf(OutOfMemoryError.class);
+ // the loop does not pull again after the retry delay
+
await().during(Duration.ofSeconds(1)).atMost(Duration.ofSeconds(3)).until(() ->
attempts.get() == 1);
+ assertThat(captor.events).anySatisfy(event -> {
+ assertThat(event.getLevel()).isEqualTo(Level.ERROR);
+ assertThat(event.getThrown()).isInstanceOf(OutOfMemoryError.class);
+ });
+ }
+
+ @Test
+ void healthCheckIsReadinessOnly() throws Exception {
+ GooglePubsubConsumer consumer = startRoute(new GooglePubsubComponent()
{
+ @Override
+ public SubscriberStub getSubscriberStub(GooglePubsubEndpoint
endpoint) {
+ return stub(() -> pending);
+ }
+ }, "synchronousPull=true", RETRY_DELAY);
+
+ HealthCheck check = consumer.getHealthCheck();
+ assertThat(check.getId()).isEqualTo("consumer:google-pubsub-pubsub");
+ assertThat(check.isReadiness()).isTrue();
+ assertThat(check.isLiveness()).isFalse();
+ assertThat(check.call().getState()).isEqualTo(HealthCheck.State.UP);
+ }
+
+ private void assertReceivedAndUp(GooglePubsubConsumer consumer) throws
InterruptedException {
+ MockEndpoint result = context.getEndpoint("mock:result",
MockEndpoint.class);
+ result.expectedBodiesReceived("hello");
+ MockEndpoint.assertIsSatisfied(context, 20, TimeUnit.SECONDS);
+ await().atMost(Duration.ofSeconds(10))
+ .until(() -> consumer.getHealthCheck().call().getState() ==
HealthCheck.State.UP);
+ assertThat(captor.events).anySatisfy(event ->
assertThat(event.getMessage().getFormattedMessage())
+ .contains("again after"));
+ }
+
+ private boolean waitingForRetry() {
+ return
PluginHelper.getTaskManagerRegistry(context.getCamelContextExtension()).getTasks().stream()
+ .anyMatch(task -> "PubSubRetryDelay".equals(task.getName()));
+ }
+
+ private GooglePubsubConsumer startRoute(GooglePubsubComponent component,
String options, Duration retryDelay)
+ throws Exception {
+ ((Logger) LogManager.getLogger(loggerId)).addAppender(captor);
+ context.addComponent("google-pubsub", component);
+ context.addRoutes(new RouteBuilder() {
+ @Override
+ public void configure() {
+ onException(Exception.class).handled(true).to("mock:error");
+
+
from("google-pubsub:test-project:test-subscription?maxDeliveryAttempts=5&loggerId="
+ loggerId
+ + (options.isEmpty() ? "" : "&" + options))
+ .routeId("pubsub").autoStartup(false)
+ .to("mock:result");
+ }
+ });
+ context.start();
+ GooglePubsubConsumer consumer = (GooglePubsubConsumer)
context.getRoute("pubsub").getConsumer();
+ consumer.setRetryDelay(retryDelay);
+ context.getRouteController().startRoute("pubsub");
+ return consumer;
+ }
+
+ /**
+ * An asynchronous subscriber: one that fails right after the start, or
one that delivers a message and runs until
+ * it is stopped.
+ */
+ private Subscriber subscriber(MessageReceiver receiver,
List<CountDownLatch> stops, boolean fails)
+ throws TimeoutException {
+ Subscriber subscriber = mock(Subscriber.class);
+ CountDownLatch stopped = new CountDownLatch(1);
+ stops.add(stopped);
+ when(subscriber.startAsync()).thenReturn(subscriber);
+ doAnswer(invocation -> {
+ stopped.countDown();
+ return subscriber;
+ }).when(subscriber).stopAsync();
+ if (fails) {
+ NotFoundException failure = new NotFoundException(
+ "the subscription is being created again", null,
GrpcStatusCode.of(Status.Code.NOT_FOUND), false);
+ when(subscriber.state()).thenReturn(ApiService.State.FAILED);
+ when(subscriber.failureCause()).thenReturn(failure);
+ IllegalStateException terminated = new
IllegalStateException("Expected the service to be TERMINATED", failure);
+ doAnswer(invocation -> {
+ throw terminated;
+ }).when(subscriber).awaitTerminated();
+ doAnswer(invocation -> {
+ throw terminated;
+ }).when(subscriber).awaitTerminated(anyLong(),
any(TimeUnit.class));
+ } else {
+ when(subscriber.state()).thenReturn(ApiService.State.RUNNING);
+ doAnswer(invocation -> {
+
receiver.receiveMessage(PubsubMessage.newBuilder().setMessageId("m1")
+ .setData(ByteString.copyFromUtf8("hello")).build(),
mock(AckReplyConsumer.class));
+ return null;
+ }).when(subscriber).awaitRunning();
+ doAnswer(invocation -> {
+ stopped.await();
+ return null;
+ }).when(subscriber).awaitTerminated();
+ doAnswer(invocation -> {
+ if (!stopped.await(invocation.getArgument(0),
invocation.getArgument(1))) {
+ throw new TimeoutException();
+ }
+ return null;
+ }).when(subscriber).awaitTerminated(anyLong(),
any(TimeUnit.class));
+ }
+ return subscriber;
+ }
+
+ @SuppressWarnings("unchecked")
+ private SubscriberStub stub(PullAnswer firstPulls) {
+ AtomicBoolean received = new AtomicBoolean();
+ UnaryCallable<PullRequest, PullResponse> pullCallable =
mock(UnaryCallable.class);
+
when(pullCallable.futureCall(any(PullRequest.class))).thenAnswer(invocation -> {
+ if (received.get()) {
+ // no more messages; cancelled when the consumer stops
+ return pending;
+ }
+ attempts.incrementAndGet();
+ ApiFuture<PullResponse> response = firstPulls.answer();
+ if (!failing.get()) {
+ received.set(true);
+ }
+ return response;
+ });
+ UnaryCallable<AcknowledgeRequest, Empty> acknowledgeCallable =
mock(UnaryCallable.class);
+
when(acknowledgeCallable.call(any(AcknowledgeRequest.class))).thenReturn(Empty.getDefaultInstance());
+
+ SubscriberStub stub = mock(SubscriberStub.class);
+ when(stub.pullCallable()).thenReturn(pullCallable);
+ when(stub.acknowledgeCallable()).thenReturn(acknowledgeCallable);
+ return stub;
+ }
+
+ private static PullResponse message() {
+ return PullResponse.newBuilder()
+ .addReceivedMessages(ReceivedMessage.newBuilder()
+ .setAckId("ack-1")
+ .setMessage(PubsubMessage.newBuilder()
+ .setMessageId("m1")
+ .setData(ByteString.copyFromUtf8("hello"))))
+ .build();
+ }
+
+ @FunctionalInterface
+ private interface PullAnswer {
+ ApiFuture<PullResponse> answer();
+ }
+
+ private static final class LogEventCaptor extends AbstractAppender {
+ private final List<LogEvent> events = new CopyOnWriteArrayList<>();
+
+ LogEventCaptor() {
+ super("LoopRestartLogEventCaptor", null, null, false,
Property.EMPTY_ARRAY);
+ start();
+ }
+
+ @Override
+ public void append(LogEvent event) {
+ events.add(event.toImmutable());
+ }
+ }
+}
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 909a40f2242a..078068558101 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
@@ -3149,6 +3149,25 @@ again after its ack deadline, and again after each later
delivery.
Manual acknowledgement (`ackMode=NONE`) is unchanged: the
`GooglePubsubAcknowledge` of the synchronous consumer acks
the ack ids of the exchange given to `ack` or `nack`, so that an aggregated
exchange acks every grouped message.
+=== camel-google-pubsub - the consumer subscribes or pulls again after any
failure, and has a health check
+
+A `google-pubsub` consumer no longer stops getting messages for good while its
route stays started. Before, a
+subscriber loop ended after a non-retryable error (such as `PERMISSION_DENIED`
while an IAM binding is changed, or
+`NOT_FOUND` while the subscription is created again, with the synchronous or
the asynchronous pull), after credentials
+that could not be loaded when an asynchronous subscriber was created, and,
without any log line, after an `Error` (such
+as a `NoClassDefFoundError` of client libraries that do not match). The
consumer then received nothing until the route
+was restarted. Now such a failure is logged (the first one in a row at ERROR
with its stack trace, the next ones in one
+WARN line), given to the `ExceptionHandler` (with `bridgeErrorHandler=true`,
to the error handler of the route), and the
+loop subscribes or pulls again every 5 seconds until the cause is gone.
+
+The consumer has a readiness health check: the check of the consumer of the
route (`consumer:<routeId>`, with the
+consumer health checks of Camel enabled, the default) is DOWN with the failure
while a subscriber loop waits to subscribe
+or pull again. After failed attempts, an asynchronous subscriber only counts
as working once it has run for 5 seconds.
+
+A `VirtualMachineError` (such as an `OutOfMemoryError`) of the consumer, or of
a route of a message that it received,
+that the route did not catch now stops the consumer until the route is
restarted, as for the other consumers that pull
+messages in a loop, and its health check is DOWN meanwhile.
+
=== camel-aws2-s3, camel-azure-storage-blob, camel-aws2-sqs - the consumer
deletes or moves what it consumed
With `deleteAfterRead` or `moveAfterRead`, the `aws2-s3` and
`azure-storage-blob` consumers now delete or move the