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 52bfe8641570 CAMEL-27493: camel-ibm-secrets-manager - a failed poll of 
IBM Event Streams no longer ends the secret refresh task (#30827)
52bfe8641570 is described below

commit 52bfe86415707a8e732a80e9c3984c257bb72a81
Author: allthingssecurity <[email protected]>
AuthorDate: Thu Nov 26 13:31:26 2026 +0530

    CAMEL-27493: camel-ibm-secrets-manager - a failed poll of IBM Event Streams 
no longer ends the secret refresh task (#30827)
    
    IBMEventStreamReloadTriggerTask is scheduled once (PeriodTaskScheduler
    scheduledTask): its run() polls the Event Streams topic in a loop for as
    long as Camel runs, and nothing submits it again when it ends. CAMEL-25702
    put a try around the handling of each record, but not around
    kafkaConsumer.poll(). So the first exception from poll(), for example the
    SaslAuthenticationException that KafkaConsumer.poll throws when the broker
    rejects the credentials, or an authorization error, ended the task. The
    exception went into a Future that nobody reads: nothing was logged, the
    task still looked started, and no later secret rotation reloaded the
    CamelContext until the application was restarted.
    
    run() now catches a failure of poll(): it logs it, waits and polls again,
    with the same consumer (KafkaConsumer connects and authenticates again on
    a later poll, so the loop goes on once the broker accepts the credentials
    again). The consumer keeps the credentials that doStart read once (the
    Event Streams password from the environment or the vault configuration):
    if that API key is revoked, for example after it was rotated, the polls
    keep failing until the application is restarted with the new key, now
    with a WARN. A new consumer would not help there, as it would be built
    from the same password. The wait starts at 1 second and doubles after
    each failure in a row, up to 60 seconds. The first failure in a row is
    logged at WARN (the stack trace at DEBUG), the repeats at DEBUG, and the
    first poll that works again at INFO. An Error is logged at ERROR and
    handled the same way; a VirtualMachineError is thrown on, as elsewhere in
    Camel. The loop still ends when Camel stops (isRunAllowed() is checked
    again after a failure, and the wait checks it every 100 ms), when the
    consumer was closed by doStop, or on a Kafka InterruptException. The
    kafkaConsumer field, which doStop sets to null from another thread, is
    now volatile and read once per poll.
    
    lastCheckTime is now also set after each poll that did not fail (before,
    only when the task started), so the "last check" of the secrets dev
    console stops moving when polls fail or the task is gone.
    
    The scheduler still submits the task only once and never reads its
    Future: changing DefaultPeriodTaskScheduler to submit a task again when it
    ended would also change the Kubernetes secrets and config maps refresh
    tasks, which use scheduledTask too. With this change the loop only ends
    when Camel stops (or its thread is interrupted), or on a
    VirtualMachineError.
    
    New test in IBMEventStreamReloadTriggerTaskTest: a consumer whose first
    poll throws SaslAuthenticationException and whose next poll returns the
    rotation of a watched secret: the reload happens, the task is still
    running, and the failure is logged at WARN. The record tests of
    CAMEL-25702 share the same helper now.
    
    Co-Authored-By: Claude Opus 5.5 <[email protected]>
---
 .../vault/IBMEventStreamReloadTriggerTask.java     | 82 ++++++++++++++++++++--
 .../vault/IBMEventStreamReloadTriggerTaskTest.java | 79 ++++++++++++++++++---
 2 files changed, 146 insertions(+), 15 deletions(-)

diff --git 
a/components/camel-ibm/camel-ibm-secrets-manager/src/main/java/org/apache/camel/component/ibm/secrets/manager/vault/IBMEventStreamReloadTriggerTask.java
 
b/components/camel-ibm/camel-ibm-secrets-manager/src/main/java/org/apache/camel/component/ibm/secrets/manager/vault/IBMEventStreamReloadTriggerTask.java
index aa237218000a..00e192da8ad0 100644
--- 
a/components/camel-ibm/camel-ibm-secrets-manager/src/main/java/org/apache/camel/component/ibm/secrets/manager/vault/IBMEventStreamReloadTriggerTask.java
+++ 
b/components/camel-ibm/camel-ibm-secrets-manager/src/main/java/org/apache/camel/component/ibm/secrets/manager/vault/IBMEventStreamReloadTriggerTask.java
@@ -24,6 +24,7 @@ import java.util.HashMap;
 import java.util.HashSet;
 import java.util.Map;
 import java.util.Set;
+import java.util.concurrent.TimeUnit;
 
 import org.apache.camel.CamelContext;
 import org.apache.camel.CamelContextAware;
@@ -43,6 +44,7 @@ import org.apache.kafka.clients.consumer.ConsumerRecord;
 import org.apache.kafka.clients.consumer.ConsumerRecords;
 import org.apache.kafka.clients.consumer.KafkaConsumer;
 import org.apache.kafka.common.config.SaslConfigs;
+import org.apache.kafka.common.errors.InterruptException;
 import org.apache.kafka.common.serialization.StringDeserializer;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
@@ -75,8 +77,11 @@ public class IBMEventStreamReloadTriggerTask extends 
ServiceSupport implements C
     private volatile Instant lastCheckTime;
     private volatile Instant lastReloadTime;
     private final Map<String, Instant> updates = new HashMap<>();
-    KafkaConsumer<String, String> kafkaConsumer;
+    volatile KafkaConsumer<String, String> kafkaConsumer;
     private static final String IBM_SECRETS_MANAGER_SECRET_ROTATED_EVENT = 
"secret_rotated";
+    // the wait before polling again after a failed poll, doubled after each 
failure in a row up to the maximum
+    private static final long POLL_RETRY_DELAY = 1000;
+    private static final long MAX_POLL_RETRY_DELAY = 60000;
     protected long pollTimeout;
 
     private static final Logger LOG = 
LoggerFactory.getLogger(IBMEventStreamReloadTriggerTask.class);
@@ -174,16 +179,48 @@ public class IBMEventStreamReloadTriggerTask extends 
ServiceSupport implements C
 
         lastCheckTime = Instant.now();
         ObjectMapper mapper = JsonMapper.builderWithJackson2Defaults().build();
+        long retryDelay = POLL_RETRY_DELAY;
+        int failedPolls = 0;
 
+        // this task runs only once (until Camel stops): nothing submits it 
again when it ends, so a failed poll must
+        // not end it, or no later secret rotation would trigger a reload any 
more
         while (isRunAllowed()) {
-            ConsumerRecords<String, String> records = 
kafkaConsumer.poll(Duration.ofMillis(pollTimeout));
+            KafkaConsumer<String, String> consumer = kafkaConsumer;
+            if (consumer == null) {
+                // closed by doStop
+                break;
+            }
+            ConsumerRecords<String, String> records;
+            try {
+                records = consumer.poll(Duration.ofMillis(pollTimeout));
+            } catch (VirtualMachineError e) {
+                throw e;
+            } catch (Throwable e) {
+                if (!isRunAllowed() || e instanceof InterruptException) {
+                    // stopping (InterruptException keeps the interrupt flag 
of this thread set)
+                    break;
+                }
+                failedPolls++;
+                logPollFailure(failedPolls, retryDelay, e);
+                if (!waitBeforeNextPoll(retryDelay)) {
+                    break;
+                }
+                retryDelay = Math.min(retryDelay * 2, MAX_POLL_RETRY_DELAY);
+                continue;
+            }
+            if (failedPolls > 0) {
+                LOG.info("Polling the IBM Event Streams topic for secret 
rotations works again after {} failed poll(s)",
+                        failedPolls);
+                failedPolls = 0;
+                retryDelay = POLL_RETRY_DELAY;
+            }
+            lastCheckTime = Instant.now();
 
             for (ConsumerRecord<String, String> record : records) {
                 try {
                     onRecord(mapper, record);
                 } catch (Exception e) {
-                    // this task runs only once (until Camel stops), so a 
record it cannot read must not end it: no later
-                    // secret rotation would trigger a reload any more
+                    // a record this task cannot read must not end it either
                     LOG.warn("Skipping the IBM Event Streams record at offset 
{} of {}, as it cannot be processed: {}",
                             record.offset(), record.topic(), e.getMessage());
                     LOG.debug("Cannot process the IBM Event Streams record at 
offset {} of {}", record.offset(),
@@ -194,6 +231,40 @@ public class IBMEventStreamReloadTriggerTask extends 
ServiceSupport implements C
 
     }
 
+    private static void logPollFailure(int failedPolls, long retryDelay, 
Throwable e) {
+        if (e instanceof Error) {
+            LOG.error("Polling the IBM Event Streams topic for secret 
rotations failed, polling again in {} ms",
+                    retryDelay, e);
+        } else if (failedPolls == 1) {
+            // the first failure in a row at WARN, the repeats at DEBUG (a 
later poll that works is logged at INFO)
+            LOG.warn("Polling the IBM Event Streams topic for secret rotations 
failed, polling again in {} ms: {}",
+                    retryDelay, e.toString());
+            LOG.debug("Polling the IBM Event Streams topic for secret 
rotations failed", e);
+        } else {
+            LOG.debug("Polling the IBM Event Streams topic failed {} times in 
a row, polling again in {} ms",
+                    failedPolls, retryDelay, e);
+        }
+    }
+
+    /**
+     * Waits before the next poll, in short steps so that stopping Camel does 
not wait for the whole delay.
+     *
+     * @return false when this task should end (stopping, or interrupted)
+     */
+    private boolean waitBeforeNextPoll(long delay) {
+        long deadline = System.nanoTime() + 
TimeUnit.MILLISECONDS.toNanos(delay);
+        try {
+            long remaining;
+            while (isRunAllowed() && (remaining = deadline - 
System.nanoTime()) > 0) {
+                TimeUnit.NANOSECONDS.sleep(Math.min(remaining, 
TimeUnit.MILLISECONDS.toNanos(100)));
+            }
+        } catch (InterruptedException e) {
+            Thread.currentThread().interrupt();
+            return false;
+        }
+        return isRunAllowed();
+    }
+
     private void onRecord(ObjectMapper mapper, ConsumerRecord<String, String> 
record) {
         boolean triggerReloading = false;
         JsonNode recordJson = mapper.readTree(record.value());
@@ -255,7 +326,8 @@ public class IBMEventStreamReloadTriggerTask extends 
ServiceSupport implements C
     }
 
     /**
-     * Last time this task checked IBM for updated secrets.
+     * Last time this task checked IBM for updated secrets: when it started, 
and after each poll of the IBM Event
+     * Streams topic that did not fail.
      */
     public Instant getLastCheckTime() {
         return lastCheckTime;
diff --git 
a/components/camel-ibm/camel-ibm-secrets-manager/src/test/java/org/apache/camel/component/ibm/secrets/manager/vault/IBMEventStreamReloadTriggerTaskTest.java
 
b/components/camel-ibm/camel-ibm-secrets-manager/src/test/java/org/apache/camel/component/ibm/secrets/manager/vault/IBMEventStreamReloadTriggerTaskTest.java
index e3338be49344..b46228bd18d6 100644
--- 
a/components/camel-ibm/camel-ibm-secrets-manager/src/test/java/org/apache/camel/component/ibm/secrets/manager/vault/IBMEventStreamReloadTriggerTaskTest.java
+++ 
b/components/camel-ibm/camel-ibm-secrets-manager/src/test/java/org/apache/camel/component/ibm/secrets/manager/vault/IBMEventStreamReloadTriggerTaskTest.java
@@ -20,6 +20,7 @@ import java.time.Duration;
 import java.util.List;
 import java.util.Map;
 import java.util.concurrent.BlockingQueue;
+import java.util.concurrent.CopyOnWriteArrayList;
 import java.util.concurrent.CountDownLatch;
 import java.util.concurrent.ExecutorService;
 import java.util.concurrent.Executors;
@@ -35,7 +36,15 @@ import org.apache.kafka.clients.consumer.ConsumerRecord;
 import org.apache.kafka.clients.consumer.ConsumerRecords;
 import org.apache.kafka.clients.consumer.KafkaConsumer;
 import org.apache.kafka.common.TopicPartition;
+import org.apache.kafka.common.errors.SaslAuthenticationException;
 import org.apache.kafka.common.serialization.StringDeserializer;
+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.Test;
 import org.junit.jupiter.params.ParameterizedTest;
 import org.junit.jupiter.params.provider.ValueSource;
 
@@ -54,6 +63,43 @@ class IBMEventStreamReloadTriggerTaskTest {
             "{\"data\":{\"secrets\":[]}}",
             "{\"data\":{\"event_type\":\"secret_rotated\"}}" })
     void rotationAfterARecordThatCannotBeReadStillTriggersTheReload(String 
unreadable) throws Exception {
+        ScriptedConsumer scripted = new ScriptedConsumer();
+        // an event that the task cannot read, then the rotation of a secret 
that the task watches
+        scripted.batches.add(unreadable);
+        scripted.batches.add(ROTATED);
+
+        runTask(scripted, "the record [" + unreadable + "]");
+    }
+
+    @Test
+    void rotationAfterAFailedPollStillTriggersTheReload() throws Exception {
+        ScriptedConsumer scripted = new ScriptedConsumer();
+        // what KafkaConsumer.poll throws when the broker rejects the 
credentials; the consumer authenticates again on a
+        // later poll, here once the broker accepts them again
+        scripted.failNextPoll = new 
SaslAuthenticationException("Authentication failed: Invalid username or 
password");
+        scripted.batches.add(ROTATED);
+
+        Logger logger = (Logger) 
LogManager.getLogger(IBMEventStreamReloadTriggerTask.class);
+        LogEventCaptor captor = new LogEventCaptor();
+        logger.addAppender(captor);
+        try {
+            runTask(scripted, "a failed poll");
+        } finally {
+            logger.removeAppender(captor);
+        }
+
+        assertTrue(captor.events.stream()
+                .anyMatch(event -> event.getLevel() == Level.WARN
+                        && 
event.getMessage().getFormattedMessage().contains("SaslAuthenticationException")),
+                "the failed poll was not logged at WARN");
+    }
+
+    /**
+     * Runs the task with the scripted consumer, on its own thread for as long 
as Camel runs (as the period task
+     * scheduler runs it), and checks that the rotation in the scripted 
records triggers a reload and that the task is
+     * still running.
+     */
+    private static void runTask(ScriptedConsumer scripted, String before) 
throws Exception {
         CountDownLatch reloaded = new CountDownLatch(1);
         ExecutorService executor = Executors.newSingleThreadExecutor();
         try (DefaultCamelContext context = new DefaultCamelContext()) {
@@ -78,24 +124,17 @@ class IBMEventStreamReloadTriggerTaskTest {
             IBMEventStreamReloadTriggerTask task = new 
IBMEventStreamReloadTriggerTask();
             task.setCamelContext(context);
             task.start();
-            // replace the client that doStart created (it never connected) by 
one that returns the given records
+            // replace the client that doStart created (it never connected) by 
the scripted one
             KafkaConsumer<String, String> created = task.kafkaConsumer;
-            ScriptedConsumer scripted = new ScriptedConsumer();
             task.kafkaConsumer = scripted;
             created.close(Duration.ZERO);
 
-            // an event that the task cannot read, then the rotation of a 
secret that the task watches
-            scripted.batches.add(unreadable);
-            scripted.batches.add(ROTATED);
-
-            // the task runs once, on its own thread, for as long as Camel 
runs (as the period task scheduler runs it)
             Future<?> running = executor.submit(task);
             boolean reloadTriggered = reloaded.await(10, TimeUnit.SECONDS);
             boolean taskEnded = running.isDone();
 
             task.stop();
-            assertTrue(reloadTriggered,
-                    "the rotation of a watched secret did not trigger a reload 
after the record [" + unreadable + "]");
+            assertTrue(reloadTriggered, "the rotation of a watched secret did 
not trigger a reload after " + before);
             assertFalse(taskEnded, "the reload trigger task ended while Camel 
was running");
         } finally {
             executor.shutdownNow();
@@ -105,11 +144,12 @@ class IBMEventStreamReloadTriggerTaskTest {
 
     /**
      * A Kafka consumer that is never connected: each poll returns the next 
queued record value, or no record when none
-     * is queued within the poll timeout.
+     * is queued within the poll timeout. A poll can be made to throw once 
instead.
      */
     private static final class ScriptedConsumer extends KafkaConsumer<String, 
String> {
 
         private final BlockingQueue<String> batches = new 
LinkedBlockingQueue<>();
+        private volatile RuntimeException failNextPoll;
         private long offset;
 
         ScriptedConsumer() {
@@ -121,6 +161,11 @@ class IBMEventStreamReloadTriggerTaskTest {
 
         @Override
         public ConsumerRecords<String, String> poll(Duration timeout) {
+            RuntimeException failure = failNextPoll;
+            if (failure != null) {
+                failNextPoll = null;
+                throw failure;
+            }
             String value;
             try {
                 value = batches.poll(timeout.toMillis(), 
TimeUnit.MILLISECONDS);
@@ -136,4 +181,18 @@ class IBMEventStreamReloadTriggerTaskTest {
                     Map.of(partition, List.of(new ConsumerRecord<>(TOPIC, 0, 
offset++, "key", value))), Map.of());
         }
     }
+
+    private static final class LogEventCaptor extends AbstractAppender {
+        private final List<LogEvent> events = new CopyOnWriteArrayList<>();
+
+        LogEventCaptor() {
+            super("IBMEventStreamReloadTriggerTaskCaptor", null, null, false, 
Property.EMPTY_ARRAY);
+            start();
+        }
+
+        @Override
+        public void append(LogEvent event) {
+            events.add(event.toImmutable());
+        }
+    }
 }

Reply via email to