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 057ffa399665 CAMEL-27318: camel-kubernetes - setDisabled no longer
adds a chain of leadership refreshes (#30762)
057ffa399665 is described below
commit 057ffa399665050aeaad51fdb05cd1676530d7db
Author: allthingssecurity <[email protected]>
AuthorDate: Wed Nov 25 13:30:42 2026 +0530
CAMEL-27318: camel-kubernetes - setDisabled no longer adds a chain of
leadership refreshes (#30762)
KubernetesLeadershipController.setDisabled ran one more refreshStatus when
the value changed, so that the change is
applied at once. Every run executes or schedules exactly one next run, so
that run started a second chain of
refreshes that never ended: after N changes the pod read the lease and the
pod list N+1 times per retry period.
RebalancingCamelClusterService changes it on every rebalance, so the load
on the API server grew with each rebalance.
Each run now carries the id of its chain, and passes it to the next run.
setDisabled starts a new chain at once, and a
run of an older chain ends without a next run, so there is one chain.
Builds on the not-ready lease holder change and
CAMEL-27296 (same class).
Co-Authored-By: Claude Opus 5.5 <[email protected]>
---
.../lock/KubernetesLeadershipController.java | 49 ++++--
.../cluster/KubernetesLeadershipRefreshTest.java | 172 +++++++++++++++++++++
2 files changed, 208 insertions(+), 13 deletions(-)
diff --git
a/components/camel-kubernetes/src/main/java/org/apache/camel/component/kubernetes/cluster/lock/KubernetesLeadershipController.java
b/components/camel-kubernetes/src/main/java/org/apache/camel/component/kubernetes/cluster/lock/KubernetesLeadershipController.java
index 22f8eb4778ff..00f8da6f163a 100644
---
a/components/camel-kubernetes/src/main/java/org/apache/camel/component/kubernetes/cluster/lock/KubernetesLeadershipController.java
+++
b/components/camel-kubernetes/src/main/java/org/apache/camel/component/kubernetes/cluster/lock/KubernetesLeadershipController.java
@@ -31,6 +31,7 @@ import java.util.concurrent.RejectedExecutionException;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
+import java.util.concurrent.atomic.AtomicLong;
import java.util.stream.Collectors;
import io.fabric8.kubernetes.api.model.HasMetadata;
@@ -92,6 +93,13 @@ public class KubernetesLeadershipController implements
Service {
private boolean disabled;
+ // the refreshes form one chain: each run executes or schedules exactly
one next run. setDisabled starts a new chain,
+ // so that the change is applied at once, and the next run of the previous
chain ends without a next run
+ private final AtomicLong refreshChain = new AtomicLong();
+
+ // the chain of the run in progress (only used by the thread of the
executor)
+ private long runningChain;
+
private final String logPrefix;
public KubernetesLeadershipController(CamelContext camelContext,
KubernetesClient kubernetesClient,
@@ -118,7 +126,7 @@ public class KubernetesLeadershipController implements
Service {
leaderNotifier = new TimedLeaderNotifier(this.camelContext,
this.eventHandler);
leaderNotifier.start();
- serializedExecutor.execute(this::refreshStatus);
+ serializedExecutor.execute(refreshTask(refreshChain.get()));
}
}
@@ -286,14 +294,25 @@ public class KubernetesLeadershipController implements
Service {
ScheduledExecutorService executor = serializedExecutor;
if (oldState != disabled && executor != null) {
try {
- executor.execute(this::refreshStatus);
+ // a new chain of refreshes: the next run of the current chain
ends it, so the API server is not polled
+ // once more for each change (RebalancingCamelClusterService
changes it on every rebalance)
+ executor.execute(refreshTask(refreshChain.incrementAndGet()));
} catch (RejectedExecutionException e) {
LOG.debug("{} Cannot refresh the leadership status as the
controller is stopping", logPrefix);
}
}
}
- private void refreshStatus() {
+ private Runnable refreshTask(long chain) {
+ return () -> refreshStatus(chain);
+ }
+
+ private void refreshStatus(long chain) {
+ if (chain != refreshChain.get()) {
+ LOG.trace("{} A newer leadership status refresh was started,
ending this one", logPrefix);
+ return;
+ }
+ runningChain = chain;
try {
doRefreshStatus();
} catch (Exception e) {
@@ -306,7 +325,7 @@ public class KubernetesLeadershipController implements
Service {
LOG.warn("{} Error while refreshing the leadership status (will
try again): {}", logPrefix, e.getMessage());
LOG.debug("{} Exception thrown while refreshing the leadership
status", logPrefix, e);
try {
- executor.schedule(this::refreshStatus,
+ executor.schedule(refreshTask(chain),
jitter(this.lockConfiguration.getRetryPeriodMillis(),
this.lockConfiguration.getJitterFactor()),
TimeUnit.MILLISECONDS);
} catch (RejectedExecutionException ex) {
@@ -357,7 +376,7 @@ public class KubernetesLeadershipController implements
Service {
if (acquired) {
LOG.info("{} Leadership acquired by current pod with immediate
effect", logPrefix);
this.currentState = State.LEADER;
- this.serializedExecutor.execute(this::refreshStatus);
+ executeNextRefresh();
return;
} else {
LOG.info("{} Unable to acquire the leadership, it may have
been acquired by another pod", logPrefix);
@@ -369,7 +388,7 @@ public class KubernetesLeadershipController implements
Service {
if (acquired) {
LOG.info("{} Leadership acquired by current pod", logPrefix);
this.currentState = State.BECOMING_LEADER;
- this.serializedExecutor.execute(this::refreshStatus);
+ executeNextRefresh();
return;
} else {
LOG.info("{} Unable to acquire the leadership, it may have
been acquired by another pod", logPrefix);
@@ -378,7 +397,7 @@ public class KubernetesLeadershipController implements
Service {
// We are leaders for some reason (e.g. pod restart on failure)
LOG.info("{} Leadership is already owned by current pod",
logPrefix);
this.currentState = State.BECOMING_LEADER;
- this.serializedExecutor.execute(this::refreshStatus);
+ executeNextRefresh();
return;
}
@@ -414,7 +433,7 @@ public class KubernetesLeadershipController implements
Service {
LOG.info("{} Current pod is becoming the new leader now...",
logPrefix);
this.currentState = State.LEADER;
- this.serializedExecutor.execute(this::refreshStatus);
+ executeNextRefresh();
}
/**
@@ -438,7 +457,7 @@ public class KubernetesLeadershipController implements
Service {
LOG.info("{} Current pod is losing leadership now...", logPrefix);
this.currentState = State.LEADERSHIP_LOST;
- this.serializedExecutor.execute(this::refreshStatus);
+ executeNextRefresh();
}
/**
@@ -458,14 +477,14 @@ public class KubernetesLeadershipController implements
Service {
LOG.info("{} Current pod has lost leadership", logPrefix);
this.currentState = State.NOT_LEADER;
- this.serializedExecutor.execute(this::refreshStatus);
+ executeNextRefresh();
}
private void refreshStatusLeader() {
if (this.disabled) {
LOG.debug("{} Leadership disabled, pod is going to lose
leadership", logPrefix);
this.currentState = State.LOSING_LEADERSHIP;
- this.serializedExecutor.execute(this::refreshStatus);
+ executeNextRefresh();
return;
}
@@ -505,12 +524,16 @@ public class KubernetesLeadershipController implements
Service {
lockConfiguration.getLeaseDurationMillis(),
this.latestLeaderInfo.getMembers());
// restart from scratch to acquire leadership
- this.serializedExecutor.execute(this::refreshStatus);
+ executeNextRefresh();
}
}
+ private void executeNextRefresh() {
+ this.serializedExecutor.execute(refreshTask(runningChain));
+ }
+
private void rescheduleAfterDelay() {
- this.serializedExecutor.schedule(this::refreshStatus,
+ this.serializedExecutor.schedule(refreshTask(runningChain),
jitter(this.lockConfiguration.getRetryPeriodMillis(),
this.lockConfiguration.getJitterFactor()),
TimeUnit.MILLISECONDS);
}
diff --git
a/components/camel-kubernetes/src/test/java/org/apache/camel/component/kubernetes/cluster/KubernetesLeadershipRefreshTest.java
b/components/camel-kubernetes/src/test/java/org/apache/camel/component/kubernetes/cluster/KubernetesLeadershipRefreshTest.java
new file mode 100644
index 000000000000..a2c6b5086c3b
--- /dev/null
+++
b/components/camel-kubernetes/src/test/java/org/apache/camel/component/kubernetes/cluster/KubernetesLeadershipRefreshTest.java
@@ -0,0 +1,172 @@
+/*
+ * 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.kubernetes.cluster;
+
+import java.util.HashMap;
+import java.util.Map;
+import java.util.concurrent.TimeUnit;
+
+import io.fabric8.kubernetes.api.model.ConfigMap;
+import io.fabric8.kubernetes.api.model.coordination.v1.Lease;
+import org.apache.camel.component.kubernetes.KubernetesConfiguration;
+import
org.apache.camel.component.kubernetes.cluster.utils.ConfigMapLockSimulator;
+import org.apache.camel.component.kubernetes.cluster.utils.LeaderRecorder;
+import org.apache.camel.component.kubernetes.cluster.utils.LeaseLockSimulator;
+import org.apache.camel.component.kubernetes.cluster.utils.LockTestServer;
+import
org.apache.camel.component.kubernetes.cluster.utils.ResourceLockSimulator;
+import org.apache.camel.test.junit6.CamelTestSupport;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.EnumSource;
+
+import static org.awaitility.Awaitility.await;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+/**
+ * Each change of {@link KubernetesClusterView#setDisabled(boolean)}
(RebalancingCamelClusterService changes it on every
+ * rebalance) refreshes the leadership status at once, and must not leave one
more chain of refreshes behind: the pod
+ * keeps polling the API server once per retry period.
+ */
+class KubernetesLeadershipRefreshTest extends CamelTestSupport {
+
+ private static final int LEASE_TIME_MILLIS = 2000;
+ private static final int RENEW_DEADLINE_MILLIS = 1000;
+ private static final int RETRY_PERIOD_MILLIS = 200;
+ private static final String NS = "app";
+
+ private ResourceLockSimulator<?> lockSimulator;
+ private final Map<String, LockTestServer<?>> servers = new HashMap<>();
+ private final Map<String, KubernetesClusterService> services = new
HashMap<>();
+ private final Map<String, LeaderRecorder> recorders = new HashMap<>();
+
+ @AfterEach
+ void shutdownLock() {
+ context.stop();
+ servers.values().forEach(s -> {
+ try {
+ s.destroy();
+ } catch (Exception e) {
+ // ignore
+ }
+ });
+ }
+
+ @Override
+ public boolean isUseRouteBuilder() {
+ return false;
+ }
+
+ @ParameterizedTest
+ @EnumSource(LeaseResourceType.class)
+ void testSetDisabledDoesNotAddRefreshes(LeaseResourceType type) throws
Exception {
+ String leader = startCluster(type);
+ String follower = leader.equals("mypod1") ? "mypod2" : "mypod1";
+ LockTestServer<?> server = servers.get(follower);
+ KubernetesClusterView view = (KubernetesClusterView)
services.get(follower).getView(NS);
+
+ // the follower reads the lease and the pods once per retry period: 20
requests take about 10 retry periods
+ long before = millisForRequests(server, 20);
+
+ // the partition of the follower is disabled and enabled again, as on
5 rebalances
+ for (int i = 0; i < 5; i++) {
+ view.setDisabled(true);
+ view.setDisabled(false);
+ }
+ long after = millisForRequests(server, 20);
+
+ assertTrue(3 * after > before,
+ "The API server is polled more often after setDisabled: 20
requests took " + after + " ms, " + before
+ + " ms before");
+ assertEquals(leader, getHolder());
+ }
+
+ @ParameterizedTest
+ @EnumSource(LeaseResourceType.class)
+ void testDisabledLeaderGivesUpLeadership(LeaseResourceType type) throws
Exception {
+ String leader = startCluster(type);
+ String other = leader.equals("mypod1") ? "mypod2" : "mypod1";
+
+ ((KubernetesClusterView)
services.get(leader).getView(NS)).setDisabled(true);
+
+ recorders.get(other).waitForLeader(other::equals, 4L *
LEASE_TIME_MILLIS, TimeUnit.MILLISECONDS);
+ await().atMost(LEASE_TIME_MILLIS, TimeUnit.MILLISECONDS).until(() ->
!services.get(leader).isLeader(NS));
+ assertEquals(other, getHolder());
+ }
+
+ private static long millisForRequests(LockTestServer<?> server, int
requests) {
+ int start = server.getRequestCount();
+ long t0 = System.nanoTime();
+ await().atMost(30, TimeUnit.SECONDS).until(() ->
server.getRequestCount() >= start + requests);
+ return TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - t0);
+ }
+
+ private String startCluster(LeaseResourceType type) {
+ lockSimulator = type == LeaseResourceType.Lease
+ ? new LeaseLockSimulator("leaders-" + NS) : new
ConfigMapLockSimulator("leaders");
+ addMember("mypod1", type);
+ addMember("mypod2", type);
+ context.start();
+
+ recorders.get("mypod1").waitForAnyLeader(5, TimeUnit.SECONDS);
+ recorders.get("mypod2").waitForAnyLeader(5, TimeUnit.SECONDS);
+ String leader = recorders.get("mypod1").getCurrentLeader();
+ await().atMost(5, TimeUnit.SECONDS).until(() ->
services.get(leader).isLeader(NS));
+ assertEquals(leader, getHolder());
+ return leader;
+ }
+
+ private String getHolder() {
+ Object resource = lockSimulator.getResource();
+ if (resource instanceof Lease lease) {
+ return lease.getSpec() != null ?
lease.getSpec().getHolderIdentity() : null;
+ }
+ ConfigMap configMap = (ConfigMap) resource;
+ return configMap != null && configMap.getData() != null ?
configMap.getData().get("leader.pod." + NS) : null;
+ }
+
+ private void addMember(String name, LeaseResourceType type) {
+ LockTestServer<?> server = new LockTestServer<>();
+ servers.put(name, server);
+ KubernetesConfiguration configuration = new KubernetesConfiguration();
+ configuration.setKubernetesClient(server.createClient());
+ KubernetesClusterService service = new
KubernetesClusterService(configuration);
+ service.setNamespace("test");
+ service.setPodName(name);
+ service.setLeaseDurationMillis(LEASE_TIME_MILLIS);
+ service.setRenewDeadlineMillis(RENEW_DEADLINE_MILLIS);
+ service.setRetryPeriodMillis(RETRY_PERIOD_MILLIS);
+ service.setJitterFactor(1.1);
+ service.setLeaseResourceType(type);
+ try {
+ context().addService(service);
+ LeaderRecorder recorder = new LeaderRecorder();
+ service.getView(NS).addEventListener(recorder);
+ recorders.put(name, recorder);
+ } catch (Exception e) {
+ throw new IllegalStateException(e);
+ }
+ services.put(name, service);
+
+ for (LockTestServer<?> s : servers.values()) {
+ for (String pod : servers.keySet()) {
+ s.addPod(pod);
+ }
+ s.addSimulator(lockSimulator);
+ }
+ }
+}