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 579f416f33ee CAMEL-27585: camel-kubernetes - a cluster view stopped 
while it takes an empty lease releases the lease (#30907)
579f416f33ee is described below

commit 579f416f33ee056e9f851abfdfb554ec1ec3acd0
Author: allthingssecurity <[email protected]>
AuthorDate: Fri Nov 27 13:43:44 2026 +0530

    CAMEL-27585: camel-kubernetes - a cluster view stopped while it takes an 
empty lease releases the lease (#30907)
    
    CAMEL-27296 made a stopped KubernetesClusterView give up the lease, but
    releaseLeadership only did so when the leadership of the pod had taken
    effect. Two cases where the pod is NOT_LEADER and the lease names it were
    left out, and the lease then named the stopped view: no other pod could
    lead while that pod stayed ready.
    
    - The pod sent the request that takes an empty or absent lease with
      immediate effect, the API server applied it, and the stop interrupted
      the wait for the answer.
    - The leader was not ready for a moment, moved to NOT_LEADER without
      touching the lease, and its view was stopped in that window.
    
    KubernetesLeadershipController remembers that a request to take an empty
    lease was sent and has not succeeded (cleared by the next successful
    lookup). releaseLeadership also releases from NOT_LEADER when that is the
    case or when the last lookup found the lease naming this pod. The release
    still removes the pod only if the lease names it. A stop in
    BECOMING_LEADER keeps the lease, as before.
    
    Review:
    - mayNameThisPod skips a valid leader, start resets the unconfirmed 
acquisition, upgrade guide
    
    Co-Authored-By: Claude Opus 5.5 <[email protected]>
---
 .../lock/KubernetesLeadershipController.java       |  38 +++-
 .../KubernetesClusterViewStopNotLeaderTest.java    | 217 +++++++++++++++++++++
 .../ROOT/pages/camel-4x-upgrade-guide-4_24.adoc    |   4 +-
 3 files changed, 253 insertions(+), 6 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 00f8da6f163a..ef9d2649e710 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
@@ -88,6 +88,11 @@ public class KubernetesLeadershipController implements 
Service {
     // (not for a failure caused by stop), read by releaseLeadership
     private volatile boolean lastLeaseCallFailed;
 
+    // whether a request to take an empty lease (with immediate effect) was 
sent and has not succeeded, with no lookup
+    // since: the API server may have applied it (such as when stop interrupts 
the request while waiting for the answer).
+    // Written by the refreshes, read by releaseLeadership
+    private volatile boolean emptyLeaseAcquisitionUnconfirmed;
+
     // the System.nanoTime() until which stop and releaseLeadership may wait 
together (null before stop)
     private volatile Long stopDeadlineNanos;
 
@@ -121,6 +126,7 @@ public class KubernetesLeadershipController implements 
Service {
             LOG.debug("{} Starting leadership controller...", logPrefix);
             stopDeadlineNanos = null;
             lastLeaseCallFailed = false;
+            emptyLeaseAcquisitionUnconfirmed = false;
             serializedExecutor = 
camelContext.getExecutorServiceManager().newSingleThreadScheduledExecutor(this,
                     "CamelKubernetesLeadershipController");
             leaderNotifier = new TimedLeaderNotifier(this.camelContext, 
this.eventHandler);
@@ -172,15 +178,20 @@ public class KubernetesLeadershipController implements 
Service {
     /**
      * Releases the leadership after {@link #stop(long)}: if the leadership of 
this pod has taken effect and the lease
      * names this pod, the pod is removed from it, so that another pod can 
take over the leadership at once instead of
-     * when this pod is no longer ready. The release is given up when the time 
given to {@link #stop(long)} has passed.
-     * It is not tried when the last lookup (of the lease or of the pods) or 
renewal of the lease failed (after the own
-     * retries of the Kubernetes client), as it would then most likely wait 
for an API server that does not answer. A
-     * failure is logged, and the lease is then kept until this pod is no 
longer ready (as before).
+     * when this pod is no longer ready. The same is done when this pod is not 
leader but the lease may still name it: a
+     * request to take an empty lease may have been applied although it failed 
(such as when the stop interrupted it
+     * while it waited for the answer), or the last lookup found the lease 
naming this pod while it was not ready. This
+     * pod does not act as leader then, so another pod may take over the lease 
at once. The release is given up when the
+     * time given to {@link #stop(long)} has passed. It is not tried when the 
last lookup (of the lease or of the pods)
+     * or renewal of the lease failed (after the own retries of the Kubernetes 
client), as it would then most likely
+     * wait for an API server that does not answer. A failure is logged, and 
the lease is then kept until this pod is no
+     * longer ready (as before).
      */
     public void releaseLeadership() {
         String group = this.lockConfiguration.getGroupName();
         State state = this.currentState;
-        if (state != State.LEADER && state != State.LOSING_LEADERSHIP && state 
!= State.LEADERSHIP_LOST) {
+        if (state != State.LEADER && state != State.LOSING_LEADERSHIP && state 
!= State.LEADERSHIP_LOST
+                && !(state == State.NOT_LEADER && mayNameThisPod())) {
             // when becoming leader, the pod waits for the previous leader to 
give up the leadership: an empty lease
             // would let another pod take it over with immediate effect while 
the previous leader may still act as one
             LOG.debug("{} The leadership for group {} has not taken effect 
({}), the lease is not released", logPrefix,
@@ -229,6 +240,18 @@ public class KubernetesLeadershipController implements 
Service {
         }
     }
 
+    /**
+     * Whether the lease may name this pod while it is not leader: a request 
to take an empty lease may have been
+     * applied although it failed, or the last lookup found the lease naming 
this pod while it was not ready (not a
+     * valid leader; a valid one becomes leader, see {@link 
State#BECOMING_LEADER}).
+     */
+    private boolean mayNameThisPod() {
+        LeaderInfo leaderInfo = this.latestLeaderInfo;
+        String podName = this.lockConfiguration.getPodName();
+        return this.emptyLeaseAcquisitionUnconfirmed
+                || leaderInfo != null && 
podName.equals(leaderInfo.getLeader()) && !leaderInfo.isValidLeader(podName);
+    }
+
     private void doReleaseLeadership() {
         String group = this.lockConfiguration.getGroupName();
         // a conflict means that the lease was changed in the meantime (such 
as the renewal of another group in a
@@ -567,6 +590,7 @@ public class KubernetesLeadershipController implements 
Service {
 
         updateLatestLeaderInfo(leaseResource, members);
         leaseCallSucceeded();
+        this.emptyLeaseAcquisitionUnconfirmed = false;
         return true;
     }
 
@@ -660,6 +684,8 @@ public class KubernetesLeadershipController implements 
Service {
             LOG.debug("{} Lock lease resource is not present in the Kubernetes 
namespace. A new lease resource will be created",
                     logPrefix);
 
+            // the outcome is unknown until the answer arrives, see 
releaseLeadership
+            this.emptyLeaseAcquisitionUnconfirmed = true;
             try {
                 HasMetadata newLeaseResource = 
leaseManager.createNewLeaseResource(kubernetesClient,
                         
this.lockConfiguration.getKubernetesResourcesNamespaceOrDefault(kubernetesClient),
@@ -686,6 +712,8 @@ public class KubernetesLeadershipController implements 
Service {
 
             boolean canAcquire = !leaderInfo.hasValidLeader();
             if (canAcquire) {
+                // the outcome is unknown until the answer arrives, see 
releaseLeadership
+                this.emptyLeaseAcquisitionUnconfirmed = 
leaderInfo.hasEmptyLeader();
                 // Try to be the new leader
                 try {
                     HasMetadata updatedLeaseResource
diff --git 
a/components/camel-kubernetes/src/test/java/org/apache/camel/component/kubernetes/cluster/KubernetesClusterViewStopNotLeaderTest.java
 
b/components/camel-kubernetes/src/test/java/org/apache/camel/component/kubernetes/cluster/KubernetesClusterViewStopNotLeaderTest.java
new file mode 100644
index 000000000000..97130fa7b1bd
--- /dev/null
+++ 
b/components/camel-kubernetes/src/test/java/org/apache/camel/component/kubernetes/cluster/KubernetesClusterViewStopNotLeaderTest.java
@@ -0,0 +1,217 @@
+/*
+ * 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.ConfigMapBuilder;
+import io.fabric8.kubernetes.api.model.coordination.v1.Lease;
+import io.fabric8.kubernetes.api.model.coordination.v1.LeaseBuilder;
+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.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertNull;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+/**
+ * Stopping a {@link KubernetesClusterView} whose pod is not leader, while the 
lease may still name the pod, releases
+ * the lease, so that another pod can lead while the pod stays ready.
+ */
+class KubernetesClusterViewStopNotLeaderTest extends CamelTestSupport {
+
+    private static final int LEASE_TIME_MILLIS = 4000;
+    private static final int RENEW_DEADLINE_MILLIS = 3000;
+    private static final int RETRY_PERIOD_MILLIS = 200;
+    // shorter than the renew deadline, which the stop and the release may 
take together
+    private static final long ANSWER_DELAY_MILLIS = 1000;
+    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() {
+        // stop the services first, as they release the lease through the 
servers
+        context.stop();
+        servers.values().forEach(s -> {
+            try {
+                s.destroy();
+            } catch (Exception e) {
+                // ignore
+            }
+        });
+    }
+
+    @Override
+    public boolean isUseRouteBuilder() {
+        return false;
+    }
+
+    @ParameterizedTest
+    @EnumSource(LeaseResourceType.class)
+    void testStopWhileCreatingTheLeaseReleasesIt(LeaseResourceType type) 
throws Exception {
+        lockSimulator = type == LeaseResourceType.Lease
+                ? new LeaseLockSimulator("leaders-" + NS) : new 
ConfigMapLockSimulator("leaders");
+        stopWhileTakingAnEmptyLeaseReleasesIt(type);
+    }
+
+    @ParameterizedTest
+    @EnumSource(LeaseResourceType.class)
+    void testStopWhileTakingAnEmptyLeaseReleasesIt(LeaseResourceType type) 
throws Exception {
+        if (type == LeaseResourceType.Lease) {
+            LeaseLockSimulator lease = new LeaseLockSimulator("leaders-" + NS);
+            // a lease without holder, as left by a release
+            lease.setResource(new 
LeaseBuilder().withNewMetadata().withName("leaders-" + NS).withNamespace("test")
+                    .endMetadata().withNewSpec().endSpec().build(), true);
+            lockSimulator = lease;
+        } else {
+            ConfigMapLockSimulator configMap = new 
ConfigMapLockSimulator("leaders");
+            configMap.setResource(new 
ConfigMapBuilder().withNewMetadata().withName("leaders").withNamespace("test")
+                    .endMetadata().build(), true);
+            lockSimulator = configMap;
+        }
+        stopWhileTakingAnEmptyLeaseReleasesIt(type);
+    }
+
+    private void stopWhileTakingAnEmptyLeaseReleasesIt(LeaseResourceType type) 
throws Exception {
+        addMember("mypod1", type);
+        addMember("mypod2", type);
+        // mypod2 cannot reach the API server for now, and the API server 
applies a request of mypod1 when it arrives
+        // but answers it only after a delay
+        servers.get("mypod2").setRefuseRequests(true);
+        servers.get("mypod1").setDelayRequests(ANSWER_DELAY_MILLIS);
+        context.start();
+
+        // the API server has applied the request of mypod1 that takes the 
lease, and its answer is on the way
+        await().atMost(10, TimeUnit.SECONDS).pollInterval(10, 
TimeUnit.MILLISECONDS)
+                .until(() -> "mypod1".equals(getHolder()));
+        servers.get("mypod1").setDelayRequests(null);
+        assertFalse(services.get("mypod1").isLeader(NS));
+
+        // the stop interrupts the request: mypod1 never was leader, and the 
lease that names it is released
+        KubernetesClusterView view = stopView("mypod1");
+        assertFalse(view.getLocalMember().isLeader());
+        assertNull(recorders.get("mypod1").getLastTimeOf("mypod1"::equals));
+        assertNull(getHolder());
+
+        // so mypod1, which is still ready, does not keep the other pods from 
leading
+        servers.get("mypod2").setRefuseRequests(false);
+        recorders.get("mypod2").waitForLeader("mypod2"::equals, 10, 
TimeUnit.SECONDS);
+        assertTrue(services.get("mypod2").isLeader(NS));
+        assertEquals("mypod2", getHolder());
+    }
+
+    @ParameterizedTest
+    @EnumSource(LeaseResourceType.class)
+    void testStopWhileNotReadyReleasesTheLease(LeaseResourceType type) throws 
Exception {
+        lockSimulator = type == LeaseResourceType.Lease
+                ? new LeaseLockSimulator("leaders-" + NS) : new 
ConfigMapLockSimulator("leaders");
+        addMember("mypod1", type);
+        addMember("mypod2", type);
+        servers.get("mypod2").setRefuseRequests(true);
+        context.start();
+        await().atMost(10, TimeUnit.SECONDS).until(() -> 
services.get("mypod1").isLeader(NS));
+        assertEquals("mypod1", getHolder());
+
+        // mypod1 is not ready for a moment (and mypod2 cannot reach the API 
server meanwhile, so it cannot take over):
+        // mypod1 is no longer leader, but the lease still names it
+        servers.values().forEach(s -> s.removePod("mypod1"));
+        await().atMost(10, TimeUnit.SECONDS).until(() -> 
!services.get("mypod1").isLeader(NS));
+        assertEquals("mypod1", getHolder());
+
+        // the view of mypod1 is stopped in that window: the lease is released
+        KubernetesClusterView view = stopView("mypod1");
+        assertFalse(view.getLocalMember().isLeader());
+        assertNull(getHolder());
+
+        // so when mypod1 is ready again, it does not keep the other pods from 
leading
+        servers.values().forEach(s -> s.addPod("mypod1"));
+        servers.get("mypod2").setRefuseRequests(false);
+        recorders.get("mypod2").waitForLeader("mypod2"::equals, 10, 
TimeUnit.SECONDS);
+        assertTrue(services.get("mypod2").isLeader(NS));
+        assertEquals("mypod2", getHolder());
+    }
+
+    /**
+     * Releases the view of the pod as its last user does (MasterConsumer, 
ClusteredRoutePolicy), which stops it.
+     */
+    private KubernetesClusterView stopView(String pod) throws Exception {
+        KubernetesClusterService service = services.get(pod);
+        KubernetesClusterView view = (KubernetesClusterView) 
service.getView(NS);
+        // the view was retained once when the recorder was added
+        service.releaseView(view);
+        service.releaseView(view);
+        assertTrue(view.isStopped(), "view should be stopped");
+        return view;
+    }
+
+    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);
+        }
+    }
+}
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 6920d3b417a6..4d6f339655cd 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
@@ -2876,7 +2876,9 @@ A Kubernetes cluster view stops when its last user (such 
as a `master:` consumer
 when the cluster service stops. The stopped view now reports that the pod is 
no longer the leader and tells its
 listeners. If the leadership of the pod had taken effect, the view also 
removes the pod from the lease (the `Lease`, or
 the leader key of the group in the `ConfigMap`). Another pod then takes over 
the leadership on its next check, after the
-retry period.
+retry period. The view also releases the lease when the pod is not leader but 
the lease may still name it: a request
+of the pod to take an empty lease failed (for example the stop interrupted it) 
but may have been applied, or the last
+check found the lease naming the pod while the pod was not ready.
 
 Before, the stopped view kept reporting the pod as leader: 
`CamelClusterService.isLeader` returned `true`, also once the
 view was used again, until its first lookup. The lease kept naming the pod, so 
no other pod could lead the group until

Reply via email to