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 12456912eb7c CAMEL-27488: camel-aws-secrets-manager,
camel-hashicorp-vault - a failed reload after a secret update is tried again at
the next check (#30814)
12456912eb7c is described below
commit 12456912eb7ceae8eaf95f7748b0c994bd0e8bc6
Author: allthingssecurity <[email protected]>
AuthorDate: Thu Nov 26 14:01:01 2026 +0530
CAMEL-27488: camel-aws-secrets-manager, camel-hashicorp-vault - a failed
reload after a secret update is tried again at the next check (#30814)
The AWS Secrets Manager (CloudTrail and SQS) and HashiCorp Vault secret
refresh tasks marked an update as seen before they reloaded the
CamelContext: the CloudTrail task moved lastTime and recorded the event
ids, the SQS mode deleted the notification, the HashiCorp task stored the
new version. DefaultContextReloadStrategy catches a failed reload, logs
and counts it, so the next check found nothing new and never reloaded
again. A reload removes all the routes before it starts them again, so
with the default route controller a route that failed to start during the
reload (a broker briefly unreachable) stayed stopped, and the routes
after it were not added back, until the next update, a manual reload or a
restart. (The supervising route controller starts such a route again by
itself, and the reload counts as succeeded.)
The tasks now mark an update as seen only once the reload succeeded. They
tell a failed reload from the failed counter of the reload strategy
(ReloadStrategy.getFailedCounter(), read before and after onReload, as
ReloadDevConsole does), so no API changes. A reload from another source
that fails meanwhile is also seen as failed, which costs one more reload.
After a failed reload a later check sees the update again and reloads
again, with a WARN each time, at most 10 times in a row
(MAX_RELOAD_ATTEMPTS); then the update is marked as seen, as before. The
SQS mode still deletes at once the messages that are not an update of a
tracked secret (CAMEL-24193); the notification of an update is deleted
after the reload, so after a failed reload the queue delivers it again
once its visibility timeout is over (unless a redrive policy of the queue
moves it to a dead-letter queue first). A failed delete is logged and no
longer ends the check.
Not changed: lastCheckTime and lastReloadTime are still set before the
check and the reload, and the other refresh tasks (GCP, Azure, IBM,
Kubernetes, Spring Cloud Config) also ignore whether the reload
succeeded.
New CloudTrailReloadTriggerTaskReloadRetryTest (mocked CloudTrailClient
and SqsClient) and HashicorpVaultReloadTriggerTaskReloadRetryTest (fake
Vault over HTTP): a consumer that fails to start once during the reload,
the next check reloads again and the route runs with the new value; a
reload that keeps failing is tried 10 times; the SQS notification is
deleted only after the reload succeeded. Both component pages (and their
catalog copies) and the 4.24 upgrade guide describe the retry.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
---
.../docs/aws-secrets-manager-component.adoc | 2 +
.../catalog/docs/hashicorp-vault-component.adoc | 2 +
.../main/docs/aws-secrets-manager-component.adoc | 2 +
.../vault/CloudTrailReloadTriggerTask.java | 94 ++++++--
...CloudTrailReloadTriggerTaskReloadRetryTest.java | 251 +++++++++++++++++++++
.../src/main/docs/hashicorp-vault-component.adoc | 2 +
.../vault/HashicorpVaultReloadTriggerTask.java | 41 +++-
...icorpVaultReloadTriggerTaskReloadRetryTest.java | 211 +++++++++++++++++
.../ROOT/pages/camel-4x-upgrade-guide-4_24.adoc | 9 +
9 files changed, 597 insertions(+), 17 deletions(-)
diff --git
a/catalog/camel-catalog/src/generated/resources/org/apache/camel/catalog/docs/aws-secrets-manager-component.adoc
b/catalog/camel-catalog/src/generated/resources/org/apache/camel/catalog/docs/aws-secrets-manager-component.adoc
index c34ba0168a5c..29ddd740b832 100644
---
a/catalog/camel-catalog/src/generated/resources/org/apache/camel/catalog/docs/aws-secrets-manager-component.adoc
+++
b/catalog/camel-catalog/src/generated/resources/org/apache/camel/catalog/docs/aws-secrets-manager-component.adoc
@@ -456,6 +456,8 @@ where `camel.vault.aws.refreshEnabled` will enable the
automatic context reload,
Note that `camel.vault.aws.secrets` is not mandatory: if not specified the
task responsible for checking updates events will take into accounts or the
properties with an `aws:` prefix.
+If the reload fails (for example a route cannot start because the system it
connects to is briefly unreachable), the update is not marked as seen, so a
later check reloads again, up to 10 times in a row. After that, the task waits
for the next update of a tracked secret. With SQS notifications (see below),
the notification of the update is deleted from the queue only once the reload
succeeded, and the check that receives it again reloads again.
+
=== Automatic Camel context reloading on Secret Refresh with Eventbridge and
AWS SQS Services
Another option is to use AWS EventBridge in conjunction with the AWS SQS
service.
diff --git
a/catalog/camel-catalog/src/generated/resources/org/apache/camel/catalog/docs/hashicorp-vault-component.adoc
b/catalog/camel-catalog/src/generated/resources/org/apache/camel/catalog/docs/hashicorp-vault-component.adoc
index 117b6175c821..cac4311796b7 100644
---
a/catalog/camel-catalog/src/generated/resources/org/apache/camel/catalog/docs/hashicorp-vault-component.adoc
+++
b/catalog/camel-catalog/src/generated/resources/org/apache/camel/catalog/docs/hashicorp-vault-component.adoc
@@ -840,6 +840,8 @@ For example, if a secret named `database` is updated in
Vault:
- On the next check, if `current_version` changes to `6`, a reload is triggered
- The refresh period (default 60 seconds) determines how quickly changes are
detected
+If the reload fails (for example a route cannot start because the system it
connects to is briefly unreachable), the new version is not marked as seen: the
next check reloads again, up to 10 times in a row. After that, the task waits
for the next new version of a tracked secret.
+
This polling approach works with all HashiCorp Vault deployments (on-premise,
cloud, enterprise, and open-source) without requiring additional infrastructure.
diff --git
a/components/camel-aws/camel-aws-secrets-manager/src/main/docs/aws-secrets-manager-component.adoc
b/components/camel-aws/camel-aws-secrets-manager/src/main/docs/aws-secrets-manager-component.adoc
index c34ba0168a5c..29ddd740b832 100644
---
a/components/camel-aws/camel-aws-secrets-manager/src/main/docs/aws-secrets-manager-component.adoc
+++
b/components/camel-aws/camel-aws-secrets-manager/src/main/docs/aws-secrets-manager-component.adoc
@@ -456,6 +456,8 @@ where `camel.vault.aws.refreshEnabled` will enable the
automatic context reload,
Note that `camel.vault.aws.secrets` is not mandatory: if not specified the
task responsible for checking updates events will take into accounts or the
properties with an `aws:` prefix.
+If the reload fails (for example a route cannot start because the system it
connects to is briefly unreachable), the update is not marked as seen, so a
later check reloads again, up to 10 times in a row. After that, the task waits
for the next update of a tracked secret. With SQS notifications (see below),
the notification of the update is deleted from the queue only once the reload
succeeded, and the check that receives it again reloads again.
+
=== Automatic Camel context reloading on Secret Refresh with Eventbridge and
AWS SQS Services
Another option is to use AWS EventBridge in conjunction with the AWS SQS
service.
diff --git
a/components/camel-aws/camel-aws-secrets-manager/src/main/java/org/apache/camel/component/aws/secretsmanager/vault/CloudTrailReloadTriggerTask.java
b/components/camel-aws/camel-aws-secrets-manager/src/main/java/org/apache/camel/component/aws/secretsmanager/vault/CloudTrailReloadTriggerTask.java
index 8d71fae2ba3a..19a036ef7e2f 100644
---
a/components/camel-aws/camel-aws-secrets-manager/src/main/java/org/apache/camel/component/aws/secretsmanager/vault/CloudTrailReloadTriggerTask.java
+++
b/components/camel-aws/camel-aws-secrets-manager/src/main/java/org/apache/camel/component/aws/secretsmanager/vault/CloudTrailReloadTriggerTask.java
@@ -114,6 +114,8 @@ public class CloudTrailReloadTriggerTask extends
ServiceSupport implements Camel
// how far before the newest event seen each check looks again: CloudTrail
can make an event visible after a newer
// one (on average within about 5 minutes, not guaranteed), the default
lookBackWindow of the aws-cloudtrail consumer
private static final Duration LOOK_BACK = Duration.ofMinutes(10);
+ // how many reloads in a row an update triggers when they fail, one per
run, before it is marked as seen anyway
+ static final int MAX_RELOAD_ATTEMPTS = 10;
private CamelContext camelContext;
private boolean reloadEnabled = true;
@@ -133,6 +135,8 @@ public class CloudTrailReloadTriggerTask extends
ServiceSupport implements Camel
private final Map<String, Instant> updates = new HashMap<>();
private boolean useSqsNotification;
private String queueUrl;
+ // the reloads in a row that failed for the updates not marked as seen yet
+ private int failedReloads;
public CloudTrailReloadTriggerTask() {
}
@@ -302,6 +306,7 @@ public class CloudTrailReloadTriggerTask extends
ServiceSupport implements Camel
lastTime = null;
startedAt = null;
seenEventIds.clear();
+ failedReloads = 0;
}
/**
@@ -346,6 +351,10 @@ public class CloudTrailReloadTriggerTask extends
ServiceSupport implements Camel
public void run() {
lastCheckTime = Instant.now();
boolean triggerReloading = false;
+ // marks what this check found as seen: the events, or the SQS
notifications (deleted). When the check triggers
+ // a reload, it runs only once the reload succeeded, so that after a
failed reload a later run sees the update
+ // again and reloads again
+ Runnable markSeen = null;
if (!useSqsNotification) {
@@ -365,10 +374,13 @@ public class CloudTrailReloadTriggerTask extends
ServiceSupport implements Camel
LOG.debug("Found {} events", events.size());
Instant newest = since;
+ // the events this check sees first, added to seenEventIds
when they are marked as seen
+ Map<String, Instant> newEventIds = new HashMap<>();
for (Event event : events) {
Instant eventTime = event.eventTime();
- if (seenEventIds.putIfAbsent(event.eventId(), eventTime)
!= null) {
- // already seen by an earlier check
+ if (seenEventIds.containsKey(event.eventId())
+ || newEventIds.putIfAbsent(event.eventId(),
eventTime) != null) {
+ // already seen by an earlier check (or returned by
both lookups)
continue;
}
if (newest == null || eventTime.isAfter(newest)) {
@@ -393,18 +405,25 @@ public class CloudTrailReloadTriggerTask extends
ServiceSupport implements Camel
}
}
}
- lastTime = newest;
- // the next lookups do not return the events before their
start time again
- Instant nextStart = lookupStart(newest, started);
- if (nextStart != null) {
- seenEventIds.values().removeIf(t -> t.isBefore(nextStart));
- }
+ Instant checked = newest;
+ markSeen = () -> {
+ seenEventIds.putAll(newEventIds);
+ lastTime = checked;
+ // the next lookups do not return the events before their
start time again
+ Instant nextStart = lookupStart(checked, started);
+ if (nextStart != null) {
+ seenEventIds.values().removeIf(t ->
t.isBefore(nextStart));
+ }
+ };
} catch (Exception e) {
LOG.warn(
"Error during AWS Secrets Refresh Task due to {}. This
exception is ignored. Will try again on next run.",
e.getMessage(), e);
}
} else {
+ // the receipt handles of the notifications of the updates found,
deleted when they are marked as seen
+ List<String> updateMessages = new ArrayList<>();
+ markSeen = () -> updateMessages.forEach(this::deleteMessage);
try {
// no long polling, whatever the receive wait time of the
queue: the check runs again after the refresh
// period, and it must not wait on the thread of the periodic
tasks (nor for longer than the call timeout)
@@ -422,6 +441,7 @@ public class CloudTrailReloadTriggerTask extends
ServiceSupport implements Camel
if (messageResult != null) {
for (Message message : messageResult.messages()) {
+ boolean update = false;
try {
JsonNode event = MAPPER.readTree(message.body());
JsonNode innerDetail = event.get("detail");
@@ -434,6 +454,7 @@ public class CloudTrailReloadTriggerTask extends
ServiceSupport implements Camel
String name =
innerDetail.get("requestParameters").get("secretId").asString("");
if (matchSecret(name)) {
updates.put(name,
Instant.parse(innerDetail.get("eventTime").asString("")));
+ update = true;
if (isReloadEnabled()) {
LOG.info("Update for AWS secret: {}
detected, triggering CamelContext reload", name);
triggerReloading = true;
@@ -443,12 +464,15 @@ public class CloudTrailReloadTriggerTask extends
ServiceSupport implements Camel
} catch (JacksonException e) {
LOG.warn("Unable to parse SQS message body,
discarding message: {}", e.getMessage());
}
- // Always delete the examined message so the queue is
drained rather than redelivering it
- // on every poll (matched -> reload recorded above;
unmatched or malformed -> discarded).
- LOG.trace("Deleting message with receipt handle
{}...", message.receiptHandle());
- sqsClient.deleteMessage(
-
DeleteMessageRequest.builder().queueUrl(queueUrl)
-
.receiptHandle(message.receiptHandle()).build());
+ if (update) {
+ // deleted once the reload succeeded: after a
failed reload the queue delivers the message
+ // again (once its visibility timeout is over),
and that run reloads again
+ updateMessages.add(message.receiptHandle());
+ } else {
+ // delete the other messages now, so the queue is
drained rather than redelivering them
+ // on every poll (unmatched or malformed ->
discarded)
+ deleteMessage(message.receiptHandle());
+ }
}
}
} catch (Exception e) {
@@ -463,9 +487,49 @@ public class CloudTrailReloadTriggerTask extends
ServiceSupport implements Camel
if (reload != null) {
// trigger reload
lastReloadTime = Instant.now();
- reload.onReload(this);
+ if (!reload(reload)) {
+ failedReloads++;
+ if (failedReloads < MAX_RELOAD_ATTEMPTS) {
+ LOG.warn("Reloading CamelContext after an update of
AWS secrets failed (attempt {} of {})."
+ + " The update is not marked as seen, so a
later run sees it and reloads again.",
+ failedReloads, MAX_RELOAD_ATTEMPTS);
+ return;
+ }
+ LOG.warn("Reloading CamelContext after an update of AWS
secrets failed {} times in a row."
+ + " The update is marked as seen: no reload is
tried again until the next update.",
+ failedReloads);
+ }
+ failedReloads = 0;
}
}
+ if (markSeen != null) {
+ markSeen.run();
+ }
+ }
+
+ /**
+ * Reloads the CamelContext, and tells whether the reload succeeded: the
reload strategy logs and counts a failed
+ * reload, it does not throw it.
+ */
+ private boolean reload(ContextReloadStrategy reload) {
+ int failed = reload.getFailedCounter();
+ try {
+ reload.onReload(this);
+ } catch (Exception e) {
+ LOG.warn("Error reloading CamelContext due to {}", e.getMessage(),
e);
+ return false;
+ }
+ return reload.getFailedCounter() == failed;
+ }
+
+ private void deleteMessage(String receiptHandle) {
+ LOG.trace("Deleting message with receipt handle {}...", receiptHandle);
+ try {
+ sqsClient.deleteMessage(
+
DeleteMessageRequest.builder().queueUrl(queueUrl).receiptHandle(receiptHandle).build());
+ } catch (Exception e) {
+ LOG.warn("Error deleting SQS message due to {}. The queue delivers
it again.", e.getMessage(), e);
+ }
}
protected boolean matchSecret(String name) {
diff --git
a/components/camel-aws/camel-aws-secrets-manager/src/test/java/org/apache/camel/component/aws/secretsmanager/vault/CloudTrailReloadTriggerTaskReloadRetryTest.java
b/components/camel-aws/camel-aws-secrets-manager/src/test/java/org/apache/camel/component/aws/secretsmanager/vault/CloudTrailReloadTriggerTaskReloadRetryTest.java
new file mode 100644
index 000000000000..a886b3bfdd8c
--- /dev/null
+++
b/components/camel-aws/camel-aws-secrets-manager/src/test/java/org/apache/camel/component/aws/secretsmanager/vault/CloudTrailReloadTriggerTaskReloadRetryTest.java
@@ -0,0 +1,251 @@
+/*
+ * 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.aws.secretsmanager.vault;
+
+import java.lang.reflect.Field;
+import java.time.Instant;
+import java.util.List;
+import java.util.Map;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.CopyOnWriteArrayList;
+import java.util.concurrent.atomic.AtomicInteger;
+
+import org.apache.camel.Consumer;
+import org.apache.camel.Endpoint;
+import org.apache.camel.Processor;
+import org.apache.camel.Producer;
+import org.apache.camel.ServiceStatus;
+import org.apache.camel.builder.RouteBuilder;
+import org.apache.camel.impl.DefaultCamelContext;
+import org.apache.camel.spi.PropertiesFunction;
+import org.apache.camel.support.DefaultComponent;
+import org.apache.camel.support.DefaultConsumer;
+import org.apache.camel.support.DefaultContextReloadStrategy;
+import org.apache.camel.support.DefaultEndpoint;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import software.amazon.awssdk.services.cloudtrail.CloudTrailClient;
+import software.amazon.awssdk.services.cloudtrail.model.Event;
+import software.amazon.awssdk.services.cloudtrail.model.LookupEventsRequest;
+import software.amazon.awssdk.services.cloudtrail.model.LookupEventsResponse;
+import software.amazon.awssdk.services.cloudtrail.model.Resource;
+import software.amazon.awssdk.services.sqs.SqsClient;
+import software.amazon.awssdk.services.sqs.model.DeleteMessageRequest;
+import software.amazon.awssdk.services.sqs.model.Message;
+import software.amazon.awssdk.services.sqs.model.ReceiveMessageRequest;
+import software.amazon.awssdk.services.sqs.model.ReceiveMessageResponse;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.never;
+import static org.mockito.Mockito.times;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+
+/**
+ * A reload triggered by an update of a secret that fails (here a consumer
that cannot start once) is tried again by a
+ * later run of the refresh task, and the routes end up started with the new
value of the secret.
+ */
+class CloudTrailReloadTriggerTaskReloadRetryTest {
+
+ private static final String SECRET = "tracked-secret";
+
+ // the value of the secret in the store, resolved when the route is created
+ private final Map<String, String> store = new ConcurrentHashMap<>();
+ // consumer starts that fail, as when the remote system of the route is
briefly unreachable
+ private final AtomicInteger failStarts = new AtomicInteger();
+ // the password of each consumer that started
+ private final List<String> startedWith = new CopyOnWriteArrayList<>();
+ // the events CloudTrail returns
+ private final List<Event> events = new CopyOnWriteArrayList<>();
+
+ private final CloudTrailClient cloudTrail = mock(CloudTrailClient.class);
+ private final SqsClient sqs = mock(SqsClient.class);
+ private DefaultCamelContext context;
+ private DefaultContextReloadStrategy reload;
+ private CloudTrailReloadTriggerTask task;
+
+ @BeforeEach
+ void setUp() throws Exception {
+ store.put("api", "pw-1");
+
when(cloudTrail.lookupEvents(any(LookupEventsRequest.class))).thenAnswer(inv ->
{
+ LookupEventsRequest request = inv.getArgument(0);
+ String eventName =
request.lookupAttributes().get(0).attributeValue();
+ return LookupEventsResponse.builder()
+ .events(events.stream().filter(e ->
e.eventName().equals(eventName)).toList()).build();
+ });
+
+ context = new DefaultCamelContext();
+ context.getPropertiesComponent().addPropertiesFunction(new
PropertiesFunction() {
+ @Override
+ public String getName() {
+ return "store";
+ }
+
+ @Override
+ public String apply(String remainder) {
+ return store.get(remainder);
+ }
+ });
+ context.addComponent("flaky", new FlakyComponent());
+ reload = new DefaultContextReloadStrategy();
+ context.addService(reload);
+ context.addRoutes(new RouteBuilder() {
+ @Override
+ public void configure() {
+
from("flaky:in?password={{store:api}}").routeId("secured").log("${body}");
+ }
+ });
+ context.start();
+
+ task = new CloudTrailReloadTriggerTask();
+ task.setCamelContext(context);
+ setField("secrets", SECRET);
+ Instant now = Instant.now();
+ setField("lastTime", now);
+ setField("startedAt", now);
+ setField("cloudTrailClient", cloudTrail);
+ }
+
+ @AfterEach
+ void tearDown() {
+ context.stop();
+ }
+
+ private void setField(String name, Object value) throws Exception {
+ Field f = CloudTrailReloadTriggerTask.class.getDeclaredField(name);
+ f.setAccessible(true);
+ f.set(task, value);
+ }
+
+ private void useSqs() throws Exception {
+ setField("useSqsNotification", true);
+ setField("queueUrl", "http://localhost/queue");
+ setField("sqsClient", sqs);
+ setField("cloudTrailClient", null);
+ }
+
+ private void rotate(String password) {
+ store.put("api", password);
+ events.add(Event.builder().eventId("event-" +
password).eventSource("secretsmanager.amazonaws.com")
+ .eventName("PutSecretValue").eventTime(Instant.now())
+
.resources(Resource.builder().resourceName(SECRET).build()).build());
+ }
+
+ private ServiceStatus routeStatus() {
+ return context.getRouteController().getRouteStatus("secured");
+ }
+
+ @Test
+ void failedReloadIsTriedAgainByTheNextRun() {
+ task.run();
+ assertEquals(List.of("pw-1"), startedWith);
+ assertEquals(0, reload.getReloadCounter() + reload.getFailedCounter(),
"no update yet, no reload");
+
+ rotate("pw-2");
+ failStarts.set(1);
+ task.run();
+ assertEquals(1, reload.getFailedCounter(), "the reload failed");
+ assertEquals(ServiceStatus.Stopped, routeStatus());
+
+ task.run();
+ assertEquals(1, reload.getReloadCounter(), "the next run must reload
again");
+ assertEquals(ServiceStatus.Started, routeStatus());
+ assertEquals(List.of("pw-1", "pw-2"), startedWith, "the route runs
with the new value of the secret");
+
+ task.run();
+ assertEquals(1, reload.getReloadCounter(), "the update is marked as
seen once the reload succeeded");
+ assertEquals(1, reload.getFailedCounter());
+ }
+
+ @Test
+ void failedReloadIsTriedAtMostMaxAttemptsTimes() {
+ task.run();
+ rotate("pw-2");
+ failStarts.set(Integer.MAX_VALUE);
+ for (int i = 0; i < CloudTrailReloadTriggerTask.MAX_RELOAD_ATTEMPTS +
3; i++) {
+ task.run();
+ }
+ assertEquals(CloudTrailReloadTriggerTask.MAX_RELOAD_ATTEMPTS,
reload.getFailedCounter(),
+ "one reload per run, until the update is marked as seen");
+
+ failStarts.set(0);
+ task.run();
+ assertEquals(0, reload.getReloadCounter(), "the update was marked as
seen");
+
+ // the next update reloads again
+ rotate("pw-3");
+ task.run();
+ assertEquals(1, reload.getReloadCounter());
+ assertEquals(ServiceStatus.Started, routeStatus());
+ assertEquals("pw-3", startedWith.get(startedWith.size() - 1));
+ }
+
+ @Test
+ void notificationIsDeletedOnlyOnceTheReloadSucceeded() throws Exception {
+ useSqs();
+ // the queue delivers the notification again as long as it is not
deleted
+
when(sqs.receiveMessage(any(ReceiveMessageRequest.class))).thenReturn(ReceiveMessageResponse.builder()
+ .messages(Message.builder().receiptHandle("rh-1")
+
.body("{\"detail\":{\"eventSource\":\"secretsmanager.amazonaws.com\",\"eventName\":\"PutSecretValue\","
+ + "\"requestParameters\":{\"secretId\":\"" +
SECRET + "\"},"
+ + "\"eventTime\":\"2026-01-01T00:00:00Z\"}}")
+ .build())
+ .build());
+
+ store.put("api", "pw-2");
+ failStarts.set(1);
+ task.run();
+ assertEquals(1, reload.getFailedCounter(), "the reload failed");
+ verify(sqs, never()).deleteMessage(any(DeleteMessageRequest.class));
+
+ task.run();
+ assertEquals(1, reload.getReloadCounter(), "the notification received
again must reload again");
+ verify(sqs, times(1)).deleteMessage(any(DeleteMessageRequest.class));
+ assertEquals(ServiceStatus.Started, routeStatus());
+ assertEquals(List.of("pw-1", "pw-2"), startedWith);
+ }
+
+ private final class FlakyComponent extends DefaultComponent {
+ @Override
+ protected Endpoint createEndpoint(String uri, String remaining,
Map<String, Object> parameters) {
+ String password = (String) parameters.remove("password");
+ return new DefaultEndpoint(uri, this) {
+ @Override
+ public Producer createProducer() {
+ throw new UnsupportedOperationException();
+ }
+
+ @Override
+ public Consumer createConsumer(Processor processor) {
+ return new DefaultConsumer(this, processor) {
+ @Override
+ protected void doStart() throws Exception {
+ if (failStarts.getAndUpdate(n -> n > 0 ? n - 1 :
0) > 0) {
+ throw new IllegalStateException("remote system
unreachable");
+ }
+ startedWith.add(password);
+ super.doStart();
+ }
+ };
+ }
+ };
+ }
+ }
+}
diff --git
a/components/camel-hashicorp-vault/src/main/docs/hashicorp-vault-component.adoc
b/components/camel-hashicorp-vault/src/main/docs/hashicorp-vault-component.adoc
index 117b6175c821..cac4311796b7 100644
---
a/components/camel-hashicorp-vault/src/main/docs/hashicorp-vault-component.adoc
+++
b/components/camel-hashicorp-vault/src/main/docs/hashicorp-vault-component.adoc
@@ -840,6 +840,8 @@ For example, if a secret named `database` is updated in
Vault:
- On the next check, if `current_version` changes to `6`, a reload is triggered
- The refresh period (default 60 seconds) determines how quickly changes are
detected
+If the reload fails (for example a route cannot start because the system it
connects to is briefly unreachable), the new version is not marked as seen: the
next check reloads again, up to 10 times in a row. After that, the task waits
for the next new version of a tracked secret.
+
This polling approach works with all HashiCorp Vault deployments (on-premise,
cloud, enterprise, and open-source) without requiring additional infrastructure.
diff --git
a/components/camel-hashicorp-vault/src/main/java/org/apache/camel/component/hashicorp/vault/vault/HashicorpVaultReloadTriggerTask.java
b/components/camel-hashicorp-vault/src/main/java/org/apache/camel/component/hashicorp/vault/vault/HashicorpVaultReloadTriggerTask.java
index dd0bdd655f84..fbe608a05766 100644
---
a/components/camel-hashicorp-vault/src/main/java/org/apache/camel/component/hashicorp/vault/vault/HashicorpVaultReloadTriggerTask.java
+++
b/components/camel-hashicorp-vault/src/main/java/org/apache/camel/component/hashicorp/vault/vault/HashicorpVaultReloadTriggerTask.java
@@ -49,6 +49,8 @@ import org.springframework.vault.support.VaultResponse;
public class HashicorpVaultReloadTriggerTask extends ServiceSupport implements
CamelContextAware, Runnable {
private static final Logger LOG =
LoggerFactory.getLogger(HashicorpVaultReloadTriggerTask.class);
+ // how many reloads in a row an update triggers when they fail, one per
run, before it is marked as seen anyway
+ static final int MAX_RELOAD_ATTEMPTS = 10;
private CamelContext camelContext;
private boolean reloadEnabled = true;
@@ -62,6 +64,8 @@ public class HashicorpVaultReloadTriggerTask extends
ServiceSupport implements C
private final Map<String, Integer> versionsMap = new HashMap<>();
private boolean cloud;
private String namespace;
+ // the reloads in a row that failed for the updates not marked as seen yet
+ private int failedReloads;
public HashicorpVaultReloadTriggerTask() {
}
@@ -157,6 +161,7 @@ public class HashicorpVaultReloadTriggerTask extends
ServiceSupport implements C
client = null;
updates.clear();
versionsMap.clear();
+ failedReloads = 0;
}
@Override
@@ -168,6 +173,10 @@ public class HashicorpVaultReloadTriggerTask extends
ServiceSupport implements C
}
lastCheckTime = Instant.now();
boolean triggerReloading = false;
+ // the new versions this check found, stored in versionsMap when they
are marked as seen. When the check
+ // triggers a reload, that is only once the reload succeeded, so that
after a failed reload the next run sees
+ // the new versions again and reloads again
+ Map<String, Integer> newVersions = new HashMap<>();
try {
// Get set of secrets to check
@@ -207,7 +216,7 @@ public class HashicorpVaultReloadTriggerTask extends
ServiceSupport implements C
LOG.debug("Tracking secret {} at version
{}", secretName, currentVersion);
} else if
(!currentVersion.equals(lastKnownVersion)) {
// Version changed, trigger reload
- versionsMap.put(secretName,
currentVersion);
+ newVersions.put(secretName,
currentVersion);
updates.put(secretName, Instant.now());
if (isReloadEnabled()) {
LOG.info(
@@ -236,9 +245,37 @@ public class HashicorpVaultReloadTriggerTask extends
ServiceSupport implements C
if (reload != null) {
// trigger reload
lastReloadTime = Instant.now();
- reload.onReload(this);
+ if (!reload(reload)) {
+ failedReloads++;
+ if (failedReloads < MAX_RELOAD_ATTEMPTS) {
+ LOG.warn("Reloading CamelContext after an update of
Hashicorp Vault secrets failed (attempt {} of {})."
+ + " The update is not marked as seen, so the
next run sees it and reloads again.",
+ failedReloads, MAX_RELOAD_ATTEMPTS);
+ return;
+ }
+ LOG.warn("Reloading CamelContext after an update of
Hashicorp Vault secrets failed {} times in a row."
+ + " The update is marked as seen: no reload is
tried again until the next update.",
+ failedReloads);
+ }
+ failedReloads = 0;
}
}
+ versionsMap.putAll(newVersions);
+ }
+
+ /**
+ * Reloads the CamelContext, and tells whether the reload succeeded: the
reload strategy logs and counts a failed
+ * reload, it does not throw it.
+ */
+ private boolean reload(ContextReloadStrategy reload) {
+ int failed = reload.getFailedCounter();
+ try {
+ reload.onReload(this);
+ } catch (Exception e) {
+ LOG.warn("Error reloading CamelContext due to {}", e.getMessage(),
e);
+ return false;
+ }
+ return reload.getFailedCounter() == failed;
}
protected boolean matchSecret(String name) {
diff --git
a/components/camel-hashicorp-vault/src/test/java/org/apache/camel/component/hashicorp/vault/vault/HashicorpVaultReloadTriggerTaskReloadRetryTest.java
b/components/camel-hashicorp-vault/src/test/java/org/apache/camel/component/hashicorp/vault/vault/HashicorpVaultReloadTriggerTaskReloadRetryTest.java
new file mode 100644
index 000000000000..a9c0495eaa67
--- /dev/null
+++
b/components/camel-hashicorp-vault/src/test/java/org/apache/camel/component/hashicorp/vault/vault/HashicorpVaultReloadTriggerTaskReloadRetryTest.java
@@ -0,0 +1,211 @@
+/*
+ * 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.hashicorp.vault.vault;
+
+import java.io.IOException;
+import java.io.OutputStream;
+import java.net.InetSocketAddress;
+import java.nio.charset.StandardCharsets;
+import java.util.List;
+import java.util.Map;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.CopyOnWriteArrayList;
+import java.util.concurrent.atomic.AtomicInteger;
+
+import com.sun.net.httpserver.HttpExchange;
+import com.sun.net.httpserver.HttpServer;
+import org.apache.camel.Consumer;
+import org.apache.camel.Endpoint;
+import org.apache.camel.Processor;
+import org.apache.camel.Producer;
+import org.apache.camel.ServiceStatus;
+import org.apache.camel.builder.RouteBuilder;
+import org.apache.camel.impl.DefaultCamelContext;
+import org.apache.camel.support.DefaultComponent;
+import org.apache.camel.support.DefaultConsumer;
+import org.apache.camel.support.DefaultContextReloadStrategy;
+import org.apache.camel.support.DefaultEndpoint;
+import org.apache.camel.vault.HashicorpVaultConfiguration;
+import org.junit.jupiter.api.AfterAll;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeAll;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+
+/**
+ * A reload triggered by a new version of a secret that fails (here a consumer
that cannot start once) is tried again by
+ * the next run of the refresh task, and the routes end up started with the
new version of the secret. Runs against a
+ * minimal fake of the HashiCorp Vault KV v2 HTTP API.
+ */
+class HashicorpVaultReloadTriggerTaskReloadRetryTest {
+
+ private static HttpServer server;
+ // "<engine>/<key>" -> current version
+ private static final Map<String, Integer> VERSIONS = new
ConcurrentHashMap<>();
+
+ // consumer starts that fail, as when the remote system of the route is
briefly unreachable
+ private final AtomicInteger failStarts = new AtomicInteger();
+ // the password of each consumer that started
+ private final List<String> startedWith = new CopyOnWriteArrayList<>();
+
+ private DefaultCamelContext context;
+ private DefaultContextReloadStrategy reload;
+ private HashicorpVaultReloadTriggerTask task;
+
+ @BeforeAll
+ static void startFakeVault() throws IOException {
+ server = HttpServer.create(new InetSocketAddress("localhost", 0), 0);
+ server.createContext("/v1/",
HashicorpVaultReloadTriggerTaskReloadRetryTest::handle);
+ server.start();
+ }
+
+ @AfterAll
+ static void stopFakeVault() {
+ server.stop(0);
+ }
+
+ private static void handle(HttpExchange http) throws IOException {
+ // /v1/<engine>/<data|metadata>/<key>
+ String[] parts =
http.getRequestURI().getPath().substring("/v1/".length()).split("/", 3);
+ String body = null;
+ if (parts.length == 3) {
+ Integer version = VERSIONS.get(parts[0] + "/" + parts[2]);
+ if ("metadata".equals(parts[1]) && version != null) {
+ body = "{\"data\":{\"current_version\":" + version + "}}";
+ } else if ("data".equals(parts[1]) && version != null) {
+ body = "{\"data\":{\"data\":{\"password\":\"pw-" + version +
"\"},\"metadata\":{\"version\":" + version
+ + "}}}";
+ }
+ }
+ int status = body != null ? 200 : 404;
+ byte[] bytes = (body != null ? body :
"{\"errors\":[]}").getBytes(StandardCharsets.UTF_8);
+ http.getResponseHeaders().add("Content-Type", "application/json");
+ http.sendResponseHeaders(status, bytes.length);
+ try (OutputStream os = http.getResponseBody()) {
+ os.write(bytes);
+ }
+ }
+
+ @BeforeEach
+ void setUp() throws Exception {
+ VERSIONS.put("secret/api", 1);
+ context = new DefaultCamelContext();
+ HashicorpVaultConfiguration hashicorp = new
HashicorpVaultConfiguration();
+ hashicorp.setToken("test-token");
+ hashicorp.setHost("localhost");
+ hashicorp.setPort(String.valueOf(server.getAddress().getPort()));
+ hashicorp.setScheme("http");
+
context.getVaultConfiguration().setHashicorpVaultConfiguration(hashicorp);
+ context.addComponent("flaky", new FlakyComponent());
+ reload = new DefaultContextReloadStrategy();
+ context.addService(reload);
+ context.addRoutes(new RouteBuilder() {
+ @Override
+ public void configure() {
+
from("flaky:in?password={{hashicorp:secret:api#password}}").routeId("secured").log("${body}");
+ }
+ });
+ context.start();
+
+ task = new HashicorpVaultReloadTriggerTask();
+ task.setCamelContext(context);
+ task.start();
+ task.run();
+ assertEquals(List.of("pw-1"), startedWith);
+ assertEquals(0, reload.getReloadCounter() + reload.getFailedCounter(),
"no new version yet, no reload");
+ }
+
+ @AfterEach
+ void tearDown() {
+ task.stop();
+ context.stop();
+ VERSIONS.clear();
+ }
+
+ private ServiceStatus routeStatus() {
+ return context.getRouteController().getRouteStatus("secured");
+ }
+
+ @Test
+ void failedReloadIsTriedAgainByTheNextRun() {
+ VERSIONS.put("secret/api", 2);
+ failStarts.set(1);
+ task.run();
+ assertEquals(1, reload.getFailedCounter(), "the reload failed");
+ assertEquals(ServiceStatus.Stopped, routeStatus());
+
+ task.run();
+ assertEquals(1, reload.getReloadCounter(), "the next run must reload
again");
+ assertEquals(ServiceStatus.Started, routeStatus());
+ assertEquals(List.of("pw-1", "pw-2"), startedWith, "the route runs
with the new version of the secret");
+
+ task.run();
+ assertEquals(1, reload.getReloadCounter(), "the new version is marked
as seen once the reload succeeded");
+ assertEquals(1, reload.getFailedCounter());
+ }
+
+ @Test
+ void failedReloadIsTriedAtMostMaxAttemptsTimes() {
+ VERSIONS.put("secret/api", 2);
+ failStarts.set(Integer.MAX_VALUE);
+ for (int i = 0; i <
HashicorpVaultReloadTriggerTask.MAX_RELOAD_ATTEMPTS + 3; i++) {
+ task.run();
+ }
+ assertEquals(HashicorpVaultReloadTriggerTask.MAX_RELOAD_ATTEMPTS,
reload.getFailedCounter(),
+ "one reload per run, until the new version is marked as seen");
+
+ failStarts.set(0);
+ task.run();
+ assertEquals(0, reload.getReloadCounter(), "the new version was marked
as seen");
+
+ // the next version reloads again
+ VERSIONS.put("secret/api", 3);
+ task.run();
+ assertEquals(1, reload.getReloadCounter());
+ assertEquals(ServiceStatus.Started, routeStatus());
+ assertEquals("pw-3", startedWith.get(startedWith.size() - 1));
+ }
+
+ private final class FlakyComponent extends DefaultComponent {
+ @Override
+ protected Endpoint createEndpoint(String uri, String remaining,
Map<String, Object> parameters) {
+ String password = (String) parameters.remove("password");
+ return new DefaultEndpoint(uri, this) {
+ @Override
+ public Producer createProducer() {
+ throw new UnsupportedOperationException();
+ }
+
+ @Override
+ public Consumer createConsumer(Processor processor) {
+ return new DefaultConsumer(this, processor) {
+ @Override
+ protected void doStart() throws Exception {
+ if (failStarts.getAndUpdate(n -> n > 0 ? n - 1 :
0) > 0) {
+ throw new IllegalStateException("remote system
unreachable");
+ }
+ startedWith.add(password);
+ super.doStart();
+ }
+ };
+ }
+ };
+ }
+ }
+}
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 ead1583180c2..1773b1169a6f 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
@@ -3499,6 +3499,15 @@ missing, or a setting of its login is missing. Before, a
missing host failed onl
The `hashicorp-secrets` dev console now shows the login (`Token`, `AppRole`,
`Kubernetes` or `JWT`) instead of
`OAuth Token`.
+=== camel-hashicorp-vault, camel-aws-secrets-manager - a failed reload after a
secret update is tried again
+
+When the context reload that the secret refresh task triggers fails (for
example a route cannot start), the update
+is no longer marked as seen: the next check of the task reloads again, up to
10 times in a row, and logs a warning
+each time. Each such reload stops and starts the routes, as any reload does.
Before, the task did not reload again
+until the next update of a secret, and the routes that did not start stayed
stopped. With SQS notification
+(`camel.vault.aws.useSqsNotification=true`), the notification of the update is
deleted from the queue once the
+reload succeeded, instead of when it is received, so the queue delivers it
again after a failed reload.
+
=== camel-hivemq - a body that does not convert to a byte array fails the
exchange
The `hivemq` producer published a message body that has no conversion to
`byte[]`, such as a `Map`, a POJO or a