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 aa66baf90ab8 CAMEL-27296: camel-kubernetes - a stopped cluster view 
gives up the leadership and the lease (#30527)
aa66baf90ab8 is described below

commit aa66baf90ab8460955e3d38dddfa875570be4488
Author: allthingssecurity <[email protected]>
AuthorDate: Sat Nov 21 17:13:50 2026 +0530

    CAMEL-27296: camel-kubernetes - a stopped cluster view gives up the 
leadership and the lease (#30527)
    
    KubernetesClusterView.doStop only stopped the leadership controller and 
closed the client: the stopped view kept
    reporting the pod as leader (also after a restart, until its first 
successful lookup), and the lease kept naming the
    pod, so no other pod could lead the group until the pod became unready.
    
    - The controller stop waits for a running refresh, and tryAcquireLeadership 
does not take the lease once it is
      stopping.
    - The view clears the current leader and, if the pod was the leader, fires 
leadership lost before the lease is
      released.
    - KubernetesLeadershipController.releaseLeadership removes the pod from the 
lease (Lease or ConfigMap) when its
      leadership had taken effect (not in BECOMING_LEADER), retrying a conflict 
up to 3 times. It runs on its own thread,
      and the stop waits for it up to the renew deadline; a failure is logged 
at WARN and the lease is kept as before.
    - The views that stop while the CamelContext or the cluster service stops 
share one renew deadline, and the release
      is not tried when the last lookup or renewal failed.
    - setDisabled no longer races with a stop, and events of a stopped view's 
controller are ignored.
    
    Upgrade guide entry for 4.24. Test: KubernetesClusterViewStopTest.
    
    Closes #30527
    
    Co-Authored-By: Claude Opus 5.5 <[email protected]>
---
 .../cluster/KubernetesClusterService.java          |  46 +++
 .../kubernetes/cluster/KubernetesClusterView.java  |  65 +++-
 .../lock/KubernetesLeadershipController.java       | 214 ++++++++++-
 .../cluster/KubernetesClusterViewStopTest.java     | 414 +++++++++++++++++++++
 .../kubernetes/cluster/utils/LockTestServer.java   |   4 +-
 .../ROOT/pages/camel-4x-upgrade-guide-4_24.adoc    |  32 ++
 6 files changed, 757 insertions(+), 18 deletions(-)

diff --git 
a/components/camel-kubernetes/src/main/java/org/apache/camel/component/kubernetes/cluster/KubernetesClusterService.java
 
b/components/camel-kubernetes/src/main/java/org/apache/camel/component/kubernetes/cluster/KubernetesClusterService.java
index a7372d846f4e..1d39c7b109d4 100644
--- 
a/components/camel-kubernetes/src/main/java/org/apache/camel/component/kubernetes/cluster/KubernetesClusterService.java
+++ 
b/components/camel-kubernetes/src/main/java/org/apache/camel/component/kubernetes/cluster/KubernetesClusterService.java
@@ -19,6 +19,8 @@ package org.apache.camel.component.kubernetes.cluster;
 import java.net.InetAddress;
 import java.util.Collections;
 import java.util.Map;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicLong;
 
 import org.apache.camel.CamelContext;
 import org.apache.camel.DeferredContextBinding;
@@ -85,6 +87,10 @@ public class KubernetesClusterService extends 
AbstractCamelClusterService<Kubern
 
     private KubernetesLockConfiguration lockConfiguration;
 
+    // the time that the views which stopped while this service or the 
CamelContext stops have spent in their stop,
+    // see KubernetesClusterView.doStop
+    private final AtomicLong sharedStopTimeSpentNanos = new AtomicLong();
+
     public KubernetesClusterService() {
     }
 
@@ -109,6 +115,46 @@ public class KubernetesClusterService extends 
AbstractCamelClusterService<Kubern
         return (KubernetesClusterView) super.getView(namespace);
     }
 
+    @Override
+    protected void doStart() throws Exception {
+        sharedStopTimeSpentNanos.set(0);
+        super.doStart();
+    }
+
+    @Override
+    protected void doStop() throws Exception {
+        try {
+            super.doStop();
+        } finally {
+            sharedStopTimeSpentNanos.set(0);
+        }
+    }
+
+    /**
+     * The time that a view that stops now may spend waiting for the API 
server, when this service or the CamelContext
+     * stops. The views then stop one after another (when the CamelContext 
stops, the routes release their views, which
+     * stops a view once no other route uses it, and then this service stops 
the rest), so they share one renew
+     * deadline: the time that the views have spent in their stop (see {@link 
#sharedStopTimeSpent(long)}) is taken from
+     * it. The time between their stops (such as the graceful shutdown of the 
routes) is not.
+     *
+     * @return the time left in nanoseconds, or {@code null} if neither this 
service nor the CamelContext is stopping
+     */
+    Long sharedStopTimeLeftNanos() {
+        CamelContext context = getCamelContext();
+        if (!isStopping() && (context == null || !context.isStopping())) {
+            return null;
+        }
+        long renewDeadline = lockConfiguration != null ? 
lockConfiguration.getRenewDeadlineMillis() : renewDeadlineMillis;
+        return Math.max(0, TimeUnit.MILLISECONDS.toNanos(renewDeadline) - 
sharedStopTimeSpentNanos.get());
+    }
+
+    /**
+     * Records the time that a view spent in its stop, see {@link 
#sharedStopTimeLeftNanos()}.
+     */
+    void sharedStopTimeSpent(long nanos) {
+        sharedStopTimeSpentNanos.addAndGet(nanos);
+    }
+
     protected KubernetesConfiguration setConfigDefaults(
             KubernetesConfiguration configuration, KubernetesLockConfiguration 
lockConfiguration) {
         if (configuration.getConnectionTimeout() == null) {
diff --git 
a/components/camel-kubernetes/src/main/java/org/apache/camel/component/kubernetes/cluster/KubernetesClusterView.java
 
b/components/camel-kubernetes/src/main/java/org/apache/camel/component/kubernetes/cluster/KubernetesClusterView.java
index 733e8c561e77..87a702154a51 100644
--- 
a/components/camel-kubernetes/src/main/java/org/apache/camel/component/kubernetes/cluster/KubernetesClusterView.java
+++ 
b/components/camel-kubernetes/src/main/java/org/apache/camel/component/kubernetes/cluster/KubernetesClusterView.java
@@ -23,6 +23,7 @@ import java.util.List;
 import java.util.Map;
 import java.util.Optional;
 import java.util.Set;
+import java.util.concurrent.TimeUnit;
 import java.util.stream.Collectors;
 
 import io.fabric8.kubernetes.client.KubernetesClient;
@@ -44,6 +45,7 @@ import org.apache.camel.util.ObjectHelper;
 public class KubernetesClusterView extends AbstractCamelClusterView implements 
CamelPreemptiveClusterView {
 
     private CamelContext camelContext;
+    private final KubernetesClusterService kubernetesCluster;
     private KubernetesClient kubernetesClient;
     private KubernetesConfiguration configuration;
     private KubernetesLockConfiguration lockConfiguration;
@@ -53,11 +55,17 @@ public class KubernetesClusterView extends 
AbstractCamelClusterView implements C
     private volatile List<CamelClusterMember> currentMembers = 
Collections.emptyList();
     private KubernetesLeadershipController controller;
     private boolean disabled;
+    // guards generation and the updates of currentLeader by the leadership 
events against doStop
+    private final Object leaderLock = new Object();
+    // incremented on every start and stop: the events of a controller belong 
to the generation of the start that
+    // created it, and are ignored once that generation is over
+    private long generation;
 
     public KubernetesClusterView(CamelContext camelContext, 
KubernetesClusterService cluster,
                                  KubernetesConfiguration configuration,
                                  KubernetesLockConfiguration 
lockConfiguration) {
         super(cluster, lockConfiguration.getGroupName());
+        this.kubernetesCluster = cluster;
         this.camelContext = ObjectHelper.notNull(camelContext, "camelContext");
         this.configuration = ObjectHelper.notNull(configuration, 
"configuration");
         this.lockConfiguration = ObjectHelper.notNull(lockConfiguration, 
"lockConfiguration");
@@ -96,15 +104,31 @@ public class KubernetesClusterView extends 
AbstractCamelClusterView implements C
     protected void doStart() throws Exception {
         if (controller == null) {
             this.kubernetesClient = 
KubernetesHelper.getKubernetesClient(configuration);
+            final long gen;
+            synchronized (leaderLock) {
+                gen = ++generation;
+            }
 
             controller = new KubernetesLeadershipController(camelContext, 
kubernetesClient, this.lockConfiguration, event -> {
                 if (event instanceof 
KubernetesClusterEvent.KubernetesClusterLeaderChangedEvent) {
                     // New leader
                     Optional<String> leader
                             = 
KubernetesClusterEvent.KubernetesClusterLeaderChangedEvent.class.cast(event).getData();
-                    currentLeader = leader.map(this::toMember).orElse(null);
-                    fireLeadershipChangedEvent(currentLeader);
+                    CamelClusterMember newLeader = 
leader.map(this::toMember).orElse(null);
+                    synchronized (leaderLock) {
+                        if (gen != generation) {
+                            // the view has been stopped
+                            return;
+                        }
+                        currentLeader = newLeader;
+                    }
+                    fireLeadershipChangedEvent(newLeader);
                 } else if (event instanceof 
KubernetesClusterEvent.KubernetesClusterMemberListChangedEvent) {
+                    synchronized (leaderLock) {
+                        if (gen != generation) {
+                            return;
+                        }
+                    }
                     Set<String> members
                             = 
KubernetesClusterEvent.KubernetesClusterMemberListChangedEvent.class.cast(event).getData();
                     Set<String> oldMembers = 
currentMembers.stream().map(CamelClusterMember::getId).collect(Collectors.toSet());
@@ -135,10 +159,41 @@ public class KubernetesClusterView extends 
AbstractCamelClusterView implements C
     @Override
     protected void doStop() throws Exception {
         if (controller != null) {
-            controller.stop();
+            KubernetesLeadershipController stopping = controller;
             controller = null;
-            kubernetesClient.close();
-            kubernetesClient = null;
+            synchronized (leaderLock) {
+                generation++;
+            }
+            // the wait for a running refresh and the release take at most the 
renew deadline, and while the cluster
+            // service or the CamelContext stops, at most the renew deadline 
for all the views together
+            long stopStart = System.nanoTime();
+            long timeoutMillis = lockConfiguration.getRenewDeadlineMillis();
+            Long sharedTimeLeft = kubernetesCluster.sharedStopTimeLeftNanos();
+            if (sharedTimeLeft != null) {
+                timeoutMillis = Math.min(timeoutMillis, 
TimeUnit.NANOSECONDS.toMillis(sharedTimeLeft));
+            }
+            try {
+                // no more refreshes of the lease, and no more leadership 
events
+                stopping.stop(timeoutMillis);
+
+                boolean wasLeader;
+                synchronized (leaderLock) {
+                    wasLeader = localMember.isLeader();
+                    currentLeader = null;
+                }
+                if (wasLeader) {
+                    // tell the listeners that this pod is no longer the 
leader, before the lease is released and another
+                    // pod can take over the leadership
+                    fireLeadershipChangedEvent((CamelClusterMember) null);
+                }
+                stopping.releaseLeadership();
+            } finally {
+                kubernetesClient.close();
+                kubernetesClient = null;
+                if (sharedTimeLeft != null) {
+                    kubernetesCluster.sharedStopTimeSpent(System.nanoTime() - 
stopStart);
+                }
+            }
         }
     }
 
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 0b81d0863822..811310ae5d86 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
@@ -18,19 +18,25 @@ package org.apache.camel.component.kubernetes.cluster.lock;
 
 import java.math.BigDecimal;
 import java.math.RoundingMode;
+import java.util.Collections;
 import java.util.Date;
 import java.util.List;
 import java.util.Objects;
 import java.util.Optional;
 import java.util.Set;
+import java.util.concurrent.ExecutionException;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Future;
 import java.util.concurrent.RejectedExecutionException;
 import java.util.concurrent.ScheduledExecutorService;
 import java.util.concurrent.TimeUnit;
+import java.util.concurrent.TimeoutException;
 import java.util.stream.Collectors;
 
 import io.fabric8.kubernetes.api.model.HasMetadata;
 import io.fabric8.kubernetes.api.model.Pod;
 import io.fabric8.kubernetes.client.KubernetesClient;
+import io.fabric8.kubernetes.client.KubernetesClientException;
 import io.fabric8.kubernetes.client.readiness.Readiness;
 import io.fabric8.kubernetes.client.utils.PodStatusUtil;
 import org.apache.camel.CamelContext;
@@ -63,9 +69,11 @@ public class KubernetesLeadershipController implements 
Service {
 
     private final KubernetesClusterEventHandler eventHandler;
 
-    private State currentState = State.NOT_LEADER;
+    // written by the refreshes, read by releaseLeadership once they have ended
+    private volatile State currentState = State.NOT_LEADER;
 
-    private ScheduledExecutorService serializedExecutor;
+    // set to null by stop, which a refresh running on the executor checks
+    private volatile ScheduledExecutorService serializedExecutor;
 
     private TimedLeaderNotifier leaderNotifier;
 
@@ -75,6 +83,13 @@ public class KubernetesLeadershipController implements 
Service {
     private volatile HasMetadata latestLeaseResource;
     private volatile Set<String> latestMembers;
 
+    // whether the last lookup (of the lease or of the pods) or renewal of the 
lease failed: written by the refreshes
+    // (not for a failure caused by stop), read by releaseLeadership
+    private volatile boolean lastLeaseCallFailed;
+
+    // the System.nanoTime() until which stop and releaseLeadership may wait 
together (null before stop)
+    private volatile Long stopDeadlineNanos;
+
     private boolean disabled;
 
     private final String logPrefix;
@@ -96,6 +111,8 @@ public class KubernetesLeadershipController implements 
Service {
     public void start() {
         if (serializedExecutor == null) {
             LOG.debug("{} Starting leadership controller...", logPrefix);
+            stopDeadlineNanos = null;
+            lastLeaseCallFailed = false;
             serializedExecutor = 
camelContext.getExecutorServiceManager().newSingleThreadScheduledExecutor(this,
                     "CamelKubernetesLeadershipController");
             leaderNotifier = new TimedLeaderNotifier(this.camelContext, 
this.eventHandler);
@@ -105,13 +122,38 @@ public class KubernetesLeadershipController implements 
Service {
         }
     }
 
+    /**
+     * Stops the controller, see {@link #stop(long)}, with the renew deadline 
as the time limit.
+     */
     @Override
     public void stop() {
+        stop(lockConfiguration.getRenewDeadlineMillis());
+    }
+
+    /**
+     * Stops the refreshes of the leadership status and the leadership events. 
A refresh that is running is interrupted,
+     * and waited for. This wait and {@link #releaseLeadership()} together 
take at most the given time. The lease is not
+     * released, see {@link #releaseLeadership()}.
+     *
+     * @param timeoutMillis the time that this stop and {@link 
#releaseLeadership()} may take together
+     */
+    public void stop(long timeoutMillis) {
         LOG.debug("{} Stopping leadership controller...", logPrefix);
-        if (serializedExecutor != null) {
-            serializedExecutor.shutdownNow();
-        }
+        long deadline = System.nanoTime() + 
TimeUnit.MILLISECONDS.toNanos(Math.max(0, timeoutMillis));
+        stopDeadlineNanos = deadline;
+        ScheduledExecutorService executor = serializedExecutor;
         serializedExecutor = null;
+        if (executor != null) {
+            executor.shutdownNow();
+            try {
+                if (!executor.awaitTermination(deadline - System.nanoTime(), 
TimeUnit.NANOSECONDS)) {
+                    LOG.debug("{} The leadership status refresh did not end in 
time", logPrefix);
+                }
+            } catch (InterruptedException e) {
+                LOG.debug("{} Interrupted while waiting for the leadership 
status refresh to end", logPrefix);
+                Thread.currentThread().interrupt();
+            }
+        }
 
         if (leaderNotifier != null) {
             leaderNotifier.stop();
@@ -119,6 +161,121 @@ public class KubernetesLeadershipController implements 
Service {
         leaderNotifier = null;
     }
 
+    /**
+     * 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).
+     */
+    public void releaseLeadership() {
+        String group = this.lockConfiguration.getGroupName();
+        State state = this.currentState;
+        if (state != State.LEADER && state != State.LOSING_LEADERSHIP && state 
!= State.LEADERSHIP_LOST) {
+            // 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,
+                    group, state);
+            return;
+        }
+        if (this.lastLeaseCallFailed) {
+            LOG.warn("{} The last lookup or renewal of the lease for group {} 
failed, so the release of the lease is not"
+                     + " tried: if the lease still names the current pod, 
other pods can take it over once the current"
+                     + " pod is no longer ready",
+                    logPrefix, group);
+            return;
+        }
+        Long deadline = this.stopDeadlineNanos;
+        long remaining = deadline != null
+                ? deadline - System.nanoTime() : 
TimeUnit.MILLISECONDS.toNanos(this.lockConfiguration.getRenewDeadlineMillis());
+        if (remaining <= 0) {
+            LOG.warn("{} No time is left to release the leadership for group 
{}, so the release of the lease is not tried:"
+                     + " if the lease still names the current pod, other pods 
can take it over once the current pod is"
+                     + " no longer ready",
+                    logPrefix, group);
+            return;
+        }
+        // the Kubernetes client tries a request again on its own when the API 
server cannot be reached or answers
+        // with 429 or a server error (by default up to 10 times, with a 
growing delay), which can take minutes, so the
+        // release runs on its own thread and the stop waits for it only for 
the time left
+        ExecutorService executor = 
camelContext.getExecutorServiceManager().newSingleThreadExecutor(this,
+                "CamelKubernetesLeadershipRelease");
+        try {
+            Future<?> release = executor.submit(this::doReleaseLeadership);
+            release.get(remaining, TimeUnit.NANOSECONDS);
+        } catch (TimeoutException e) {
+            LOG.warn("{} Unable to release the leadership for group {} in 
time, other pods can take it over once the"
+                     + " current pod is no longer ready",
+                    logPrefix, group);
+        } catch (ExecutionException e) {
+            LOG.warn("{} Unable to release the leadership for group {}: {}", 
logPrefix, group, e.getCause().toString());
+            LOG.debug("{} Error received while releasing the leadership", 
logPrefix, e.getCause());
+        } catch (InterruptedException e) {
+            LOG.warn("{} Interrupted while releasing the leadership for group 
{}", logPrefix, group);
+            Thread.currentThread().interrupt();
+        } finally {
+            // shutdownNow interrupts a release that is still blocked in an 
API call; its termination is not awaited, as
+            // the time for the stop is used up by then
+            camelContext.getExecutorServiceManager().shutdownNow(executor);
+        }
+    }
+
+    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
+        // shared ConfigMap), so it is read again
+        for (int attempt = 1; attempt <= 3; attempt++) {
+            HasMetadata leaseResource;
+            try {
+                leaseResource = 
leaseManager.fetchLeaseResource(kubernetesClient,
+                        
this.lockConfiguration.getKubernetesResourcesNamespaceOrDefault(kubernetesClient),
+                        this.lockConfiguration.getKubernetesResourceName(), 
group);
+            } catch (Exception e) {
+                if (Thread.currentThread().isInterrupted()) {
+                    // the stop has given up the release (logged by 
releaseLeadership)
+                    LOG.debug("{} Interrupted while retrieving the lease 
resource to release the leadership", logPrefix, e);
+                    return;
+                }
+                LOG.warn("{} Unable to retrieve the lease resource {} for 
group {} to release the leadership: {}",
+                        logPrefix, 
this.lockConfiguration.getKubernetesResourceName(), group, e.toString());
+                LOG.debug("{} Exception thrown during lease resource lookup", 
logPrefix, e);
+                return;
+            }
+            String leader = leaseResource != null
+                    ? leaseManager.decodeLeaderInfo(leaseResource, 
Collections.emptySet(), group).getLeader() : null;
+            if (!this.lockConfiguration.getPodName().equals(leader)) {
+                LOG.debug("{} The lease for group {} does not name the current 
pod, nothing to release", logPrefix, group);
+                return;
+            }
+            if (Thread.currentThread().isInterrupted()) {
+                // the stop has given up the release (logged by 
releaseLeadership): do not update the lease afterwards
+                LOG.debug("{} Interrupted before releasing the leadership", 
logPrefix);
+                return;
+            }
+            try {
+                leaseManager.optimisticDeleteLeaderInfo(kubernetesClient, 
leaseResource, group);
+                LOG.info("{} Released the leadership for group {}", logPrefix, 
group);
+                return;
+            } catch (Exception e) {
+                if (attempt < 3 && e instanceof KubernetesClientException kce 
&& kce.getCode() == 409) {
+                    LOG.debug("{} The lease resource for group {} was changed 
while releasing the leadership, trying again",
+                            logPrefix, group);
+                    continue;
+                }
+                if (Thread.currentThread().isInterrupted()) {
+                    LOG.debug("{} Interrupted while releasing the leadership", 
logPrefix, e);
+                    return;
+                }
+                LOG.warn("{} Unable to release the leadership for group {}, 
other pods can take it over once the current"
+                         + " pod is no longer ready: {}",
+                        logPrefix, group, e.toString());
+                LOG.debug("{} Error received while releasing the leadership", 
logPrefix, e);
+                return;
+            }
+        }
+    }
+
     public boolean isDisabled() {
         return disabled;
     }
@@ -126,8 +283,13 @@ public class KubernetesLeadershipController implements 
Service {
     public void setDisabled(boolean disabled) {
         boolean oldState = this.disabled;
         this.disabled = disabled;
-        if (oldState != disabled && serializedExecutor != null) {
-            serializedExecutor.execute(this::refreshStatus);
+        ScheduledExecutorService executor = serializedExecutor;
+        if (oldState != disabled && executor != null) {
+            try {
+                executor.execute(this::refreshStatus);
+            } catch (RejectedExecutionException e) {
+                LOG.debug("{} Cannot refresh the leadership status as the 
controller is stopping", logPrefix);
+            }
         }
     }
 
@@ -241,8 +403,10 @@ public class KubernetesLeadershipController implements 
Service {
         try {
             Thread.sleep(delay);
         } catch (InterruptedException e) {
-            LOG.warn("Thread interrupted", e);
+            // the controller is stopping (shutdownNow): the leadership has 
not taken effect, see releaseLeadership
+            LOG.debug("{} Interrupted while waiting to become the leader", 
logPrefix);
             Thread.currentThread().interrupt();
+            return;
         }
 
         LOG.info("{} Current pod is becoming the new leader now...", 
logPrefix);
@@ -263,8 +427,10 @@ public class KubernetesLeadershipController implements 
Service {
         try {
             Thread.sleep(delay);
         } catch (InterruptedException e) {
-            LOG.warn("Thread interrupted", e);
+            // the controller is stopping (shutdownNow): the state stays 
LOSING_LEADERSHIP, see releaseLeadership
+            LOG.debug("{} Interrupted while waiting to lose the leadership", 
logPrefix);
             Thread.currentThread().interrupt();
+            return;
         }
 
         LOG.info("{} Current pod is losing leadership now...", logPrefix);
@@ -315,9 +481,16 @@ public class KubernetesLeadershipController implements 
Service {
                     this.lockConfiguration.getRenewDeadlineMillis(),
                     this.latestLeaderInfo.getMembers());
 
-            HasMetadata newLease = 
this.leaseManager.refreshLeaseRenewTime(kubernetesClient, 
this.latestLeaseResource,
-                    this.lockConfiguration.getRenewDeadlineSeconds());
+            HasMetadata newLease;
+            try {
+                newLease = 
this.leaseManager.refreshLeaseRenewTime(kubernetesClient, 
this.latestLeaseResource,
+                        this.lockConfiguration.getRenewDeadlineSeconds());
+            } catch (RuntimeException e) {
+                leaseCallFailed();
+                throw e;
+            }
             updateLatestLeaderInfo(newLease, this.latestMembers);
+            leaseCallSucceeded();
 
             rescheduleAfterDelay();
             return;
@@ -349,6 +522,7 @@ public class KubernetesLeadershipController implements 
Service {
                     this.lockConfiguration.getKubernetesResourceName(),
                     this.lockConfiguration.getGroupName());
         } catch (Exception e) {
+            leaseCallFailed();
             LOG.warn("{} Unable to retrieve the current lease resource {} for 
group {} from Kubernetes",
                     logPrefix, 
this.lockConfiguration.getKubernetesResourceName(), 
this.lockConfiguration.getGroupName());
             LOG.debug("{} Exception thrown during lease resource lookup", 
logPrefix, e);
@@ -359,15 +533,28 @@ public class KubernetesLeadershipController implements 
Service {
         try {
             members = Objects.requireNonNull(pullClusterMembers(), "Retrieved 
a null set of members");
         } catch (Exception e) {
+            leaseCallFailed();
             LOG.warn("{} Unable to retrieve the list of cluster members from 
Kubernetes", logPrefix);
             LOG.debug("{} Exception thrown during Pod list lookup", logPrefix, 
e);
             return false;
         }
 
         updateLatestLeaderInfo(leaseResource, members);
+        leaseCallSucceeded();
         return true;
     }
 
+    private void leaseCallSucceeded() {
+        this.lastLeaseCallFailed = false;
+    }
+
+    private void leaseCallFailed() {
+        // a failure caused by stop (which interrupts the refresh) says 
nothing about the API server
+        if (this.serializedExecutor != null) {
+            this.lastLeaseCallFailed = true;
+        }
+    }
+
     private boolean yieldLeadership() {
         LOG.debug("{} Trying to yield the leadership...", logPrefix);
 
@@ -416,6 +603,11 @@ public class KubernetesLeadershipController implements 
Service {
             LOG.debug("{} Won't try to acquire the leadership because it's 
disabled...", logPrefix);
             return false;
         }
+        if (this.serializedExecutor == null) {
+            // stopping: the lease must not be taken after stop has released it
+            LOG.debug("{} Won't try to acquire the leadership because the 
controller is stopping", logPrefix);
+            return false;
+        }
 
         LOG.debug("{} Trying to acquire the leadership...", logPrefix);
 
diff --git 
a/components/camel-kubernetes/src/test/java/org/apache/camel/component/kubernetes/cluster/KubernetesClusterViewStopTest.java
 
b/components/camel-kubernetes/src/test/java/org/apache/camel/component/kubernetes/cluster/KubernetesClusterViewStopTest.java
new file mode 100644
index 000000000000..3cfdca807e54
--- /dev/null
+++ 
b/components/camel-kubernetes/src/test/java/org/apache/camel/component/kubernetes/cluster/KubernetesClusterViewStopTest.java
@@ -0,0 +1,414 @@
+/*
+ * 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.Collection;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.concurrent.CountDownLatch;
+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.Route;
+import org.apache.camel.builder.RouteBuilder;
+import org.apache.camel.component.kubernetes.KubernetesConfiguration;
+import 
org.apache.camel.component.kubernetes.cluster.lock.KubernetesLockConfiguration;
+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.impl.cluster.ClusteredRoutePolicy;
+import org.apache.camel.support.LifecycleStrategySupport;
+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} (its last user releases it, or the 
cluster service stops) gives up the
+ * leadership of the pod: the view no longer reports it, the listeners are 
told, and the lease is released so another
+ * pod takes over.
+ */
+class KubernetesClusterViewStopTest 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 static final List<String> GROUPS = List.of("group-a", "group-b", 
"group-c");
+
+    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 testStoppedViewReleasesLeadership(LeaseResourceType type) throws 
Exception {
+        String leader = startCluster(type);
+        String other = leader.equals("mypod1") ? "mypod2" : "mypod1";
+        KubernetesClusterView view = stopView(leader);
+
+        // the stopped view no longer reports the leadership, and its 
listeners are told
+        assertFalse(view.getLocalMember().isLeader());
+        assertTrue(view.getLeader().isEmpty());
+        assertFalse(services.get(leader).isLeader(NS));
+        assertNull(recorders.get(leader).getCurrentLeader());
+        // the lease no longer names the pod (which is still ready), so the 
other pod takes over
+        assertNull(getHolder());
+        recorders.get(other).waitForLeader(other::equals, 3L * 
LEASE_TIME_MILLIS, TimeUnit.MILLISECONDS);
+        assertTrue(services.get(other).isLeader(NS));
+        assertEquals(other, getHolder());
+        assertFalse(services.get(leader).isLeader(NS));
+    }
+
+    @ParameterizedTest
+    @EnumSource(LeaseResourceType.class)
+    void testRestartedViewDoesNotReportStaleLeadership(LeaseResourceType type) 
throws Exception {
+        String leader = startCluster(type);
+        String other = leader.equals("mypod1") ? "mypod2" : "mypod1";
+        stopView(leader);
+        recorders.get(other).waitForLeader(other::equals, 3L * 
LEASE_TIME_MILLIS, TimeUnit.MILLISECONDS);
+
+        // the view is used again (such as a clustered route added again) 
while the API server cannot be reached
+        servers.get(leader).setRefuseRequests(true);
+        KubernetesClusterView restarted = (KubernetesClusterView) 
services.get(leader).getView(NS);
+        assertTrue(restarted.isStarted());
+        await().during(2L * LEASE_TIME_MILLIS, TimeUnit.MILLISECONDS)
+                .atMost(3L * LEASE_TIME_MILLIS, TimeUnit.MILLISECONDS)
+                .until(() -> !restarted.getLocalMember().isLeader() && 
services.get(other).isLeader(NS));
+    }
+
+    @ParameterizedTest
+    @EnumSource(LeaseResourceType.class)
+    void testStopWhenTheLeaseCannotBeReleased(LeaseResourceType type) throws 
Exception {
+        String leader = startCluster(type);
+        String other = leader.equals("mypod1") ? "mypod2" : "mypod1";
+        servers.get(leader).setRefuseUpdateRequests(true);
+        KubernetesClusterView view = stopView(leader);
+
+        // the failure is logged: the view is stopped and no longer reports 
the leadership, but the lease is kept
+        assertTrue(view.isStopped());
+        assertFalse(view.getLocalMember().isLeader());
+        assertNull(recorders.get(leader).getCurrentLeader());
+        assertEquals(leader, getHolder());
+
+        // until the pod is no longer ready
+        servers.values().forEach(s -> s.removePod(leader));
+        recorders.get(other).waitForLeader(other::equals, 3L * 
LEASE_TIME_MILLIS + 2000, TimeUnit.MILLISECONDS);
+        assertFalse(services.get(leader).isLeader(NS));
+    }
+
+    @ParameterizedTest
+    @EnumSource(LeaseResourceType.class)
+    void testStopGivesUpTheReleaseAfterTheRenewDeadline(LeaseResourceType 
type) throws Exception {
+        String leader = startCluster(type);
+        // the API server answers the leader pod only after a long delay (the 
Kubernetes client would also try a failed
+        // request again, by default up to 10 times): the stop and the release 
together wait the renew deadline at most
+        servers.get(leader).setDelayRequests(5L * RENEW_DEADLINE_MILLIS);
+        long start = System.nanoTime();
+        KubernetesClusterView view = stopView(leader);
+        long millis = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - start);
+
+        assertTrue(millis < 2L * RENEW_DEADLINE_MILLIS, "The stop took " + 
millis + " ms");
+        assertFalse(view.getLocalMember().isLeader());
+        assertNull(recorders.get(leader).getCurrentLeader());
+        // the release was given up, so the lease is kept until the pod is no 
longer ready, as before
+        assertEquals(leader, getHolder());
+    }
+
+    @ParameterizedTest
+    @EnumSource(LeaseResourceType.class)
+    void testStopBeforeTheLeadershipTakesEffectKeepsTheLease(LeaseResourceType 
type) throws Exception {
+        String leader = startCluster(type);
+        String other = leader.equals("mypod1") ? "mypod2" : "mypod1";
+
+        // the leader is no longer ready: the other pod takes the lease, and 
waits for the lease duration before it
+        // acts as leader, so that the old leader has given up the leadership
+        servers.values().forEach(s -> s.removePod(leader));
+        await().atMost(LEASE_TIME_MILLIS, TimeUnit.MILLISECONDS).until(() -> 
other.equals(getHolder()));
+        assertFalse(services.get(other).isLeader(NS));
+
+        // stopped while waiting: the lease is kept, as an empty lease would 
let a pod take it over at once
+        KubernetesClusterView view = stopView(other);
+        assertFalse(view.getLocalMember().isLeader());
+        assertEquals(other, getHolder());
+    }
+
+    @ParameterizedTest
+    @EnumSource(LeaseResourceType.class)
+    void 
testStopOfManyGroupsWaitsOnceForAnApiServerThatStoppedAnswering(LeaseResourceType
 type) throws Exception {
+        Map<String, ResourceLockSimulator<?>> simulators = new HashMap<>();
+        KubernetesClusterService service = startGroups(type, simulators);
+        // the API server answers only after a long delay from now on: the 
groups share one renew deadline, so the
+        // stop of the first group waits for its release until the renew 
deadline, and the next groups do not wait
+        servers.get("mypod1").setDelayRequests(5L * RENEW_DEADLINE_MILLIS);
+        long start = System.nanoTime();
+        service.stop();
+        long millis = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - start);
+
+        assertTrue(millis < 2L * RENEW_DEADLINE_MILLIS, "The stop of " + 
GROUPS.size() + " groups took " + millis + " ms");
+        for (String group : GROUPS) {
+            assertTrue(service.getView(group).isStopped());
+            assertFalse(service.getView(group).getLocalMember().isLeader());
+            // not released, so the lease is kept until the pod is no longer 
ready, as before
+            assertEquals("mypod1", getHolder(type, simulators, group));
+        }
+    }
+
+    @ParameterizedTest
+    @EnumSource(LeaseResourceType.class)
+    void 
testStopOfManyGroupsDoesNotWaitWhenTheLastLookupFailed(LeaseResourceType type) 
throws Exception {
+        Map<String, ResourceLockSimulator<?>> simulators = new HashMap<>();
+        KubernetesClusterService service = startGroups(type, simulators);
+        // the API server fails the lookups (the test client does not try a 
failed request again, while the default
+        // client does so for a while first): the leadership is lost locally 
once the renew deadline has passed
+        LockTestServer<?> server = servers.get("mypod1");
+        server.setRefuseRequests(true);
+        await().atMost(5, TimeUnit.SECONDS).until(() -> 
GROUPS.stream().noneMatch(service::isLeader));
+        // and then answers only after a long delay: the groups do not try to 
release the lease, so the stop does not
+        // wait for the API server (a release that is tried would wait until 
the renew deadline)
+        server.setDelayRequests(5L * RENEW_DEADLINE_MILLIS);
+        long start = System.nanoTime();
+        service.stop();
+        long millis = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - start);
+
+        assertTrue(millis < RENEW_DEADLINE_MILLIS / 2, "The stop of " + 
GROUPS.size() + " groups took " + millis + " ms");
+        for (String group : GROUPS) {
+            assertTrue(service.getView(group).isStopped());
+            assertEquals("mypod1", getHolder(type, simulators, group));
+        }
+    }
+
+    @ParameterizedTest
+    @EnumSource(LeaseResourceType.class)
+    void 
testContextStopWithClusteredRoutesWaitsOnceForAnApiServerThatStoppedAnswering(LeaseResourceType
 type)
+            throws Exception {
+        Map<String, ResourceLockSimulator<?>> simulators = new HashMap<>();
+        KubernetesClusterService service = startGroups(type, simulators, true);
+        // when the CamelContext stops, each clustered route releases its 
view, which stops it, before the cluster
+        // service stops: these views share one renew deadline too
+        servers.get("mypod1").setDelayRequests(5L * RENEW_DEADLINE_MILLIS);
+        long start = System.nanoTime();
+        context.stop();
+        long millis = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - start);
+
+        assertTrue(millis < 2L * RENEW_DEADLINE_MILLIS, "The stop of " + 
GROUPS.size() + " groups took " + millis + " ms");
+        for (String group : GROUPS) {
+            assertEquals("mypod1", getHolder(type, simulators, group));
+        }
+    }
+
+    @ParameterizedTest
+    @EnumSource(LeaseResourceType.class)
+    void 
testContextStopReleasesAllGroupsWhenTheTimeBetweenTheirStopsIsLong(LeaseResourceType
 type) throws Exception {
+        Map<String, ResourceLockSimulator<?>> simulators = new HashMap<>();
+        startGroups(type, simulators, true);
+        // the routes are shut down one after another, and each one takes 
longer than the renew deadline after it has
+        // released its view (like the graceful shutdown of routes): only the 
time that the views spend in their stop
+        // counts against the renew deadline that they share, so every group 
still releases its lease
+        context.addLifecycleStrategy(new LifecycleStrategySupport() {
+            @Override
+            public void onRoutesRemove(Collection<Route> routes) {
+                try {
+                    new CountDownLatch(1).await(RENEW_DEADLINE_MILLIS * 3L / 
2, TimeUnit.MILLISECONDS);
+                } catch (InterruptedException e) {
+                    Thread.currentThread().interrupt();
+                }
+            }
+        });
+        context.stop();
+
+        for (String group : GROUPS) {
+            assertNull(getHolder(type, simulators, group), "The lease of " + 
group + " should be released");
+        }
+    }
+
+    private KubernetesClusterService startGroups(LeaseResourceType type, 
Map<String, ResourceLockSimulator<?>> simulators)
+            throws Exception {
+        return startGroups(type, simulators, false);
+    }
+
+    /**
+     * Starts one pod that leads all the {@link #GROUPS}, and returns its 
cluster service. The views are used by the
+     * test, or by a route with a {@link ClusteredRoutePolicy} for each group.
+     */
+    private KubernetesClusterService startGroups(
+            LeaseResourceType type, Map<String, ResourceLockSimulator<?>> 
simulators, boolean clusteredRoutes)
+            throws Exception {
+        LockTestServer<?> server = new LockTestServer<>();
+        servers.put("mypod1", server);
+        server.addPod("mypod1");
+        if (type == LeaseResourceType.Lease) {
+            for (String group : GROUPS) {
+                simulators.put(group, new LeaseLockSimulator("leaders-" + 
group));
+            }
+        } else {
+            ResourceLockSimulator<?> configMap = new 
ConfigMapLockSimulator("leaders");
+            GROUPS.forEach(group -> simulators.put(group, configMap));
+        }
+        simulators.values().forEach(server::addSimulator);
+
+        KubernetesClusterService service = new KubernetesClusterService(new 
KubernetesConfiguration()) {
+            @Override
+            protected KubernetesConfiguration setConfigDefaults(
+                    KubernetesConfiguration configuration, 
KubernetesLockConfiguration lockConfiguration) {
+                // a client for each view, as when the views create their 
clients from the master URL (a client set on
+                // the configuration is shared by the views, and closed by the 
first view that stops)
+                configuration.setKubernetesClient(server.createClient());
+                return super.setConfigDefaults(configuration, 
lockConfiguration);
+            }
+        };
+        service.setNamespace("test");
+        service.setPodName("mypod1");
+        service.setLeaseDurationMillis(LEASE_TIME_MILLIS);
+        service.setRenewDeadlineMillis(RENEW_DEADLINE_MILLIS);
+        service.setRetryPeriodMillis(RETRY_PERIOD_MILLIS);
+        service.setJitterFactor(1.1);
+        service.setLeaseResourceType(type);
+        services.put("mypod1", service);
+        context().addService(service);
+        if (clusteredRoutes) {
+            context.addRoutes(new RouteBuilder() {
+                @Override
+                public void configure() throws Exception {
+                    for (String group : GROUPS) {
+                        from("direct:" + group).routeId(group)
+                                
.routePolicy(ClusteredRoutePolicy.forNamespace(service, group))
+                                .to("mock:" + group);
+                    }
+                }
+            });
+        } else {
+            for (String group : GROUPS) {
+                service.getView(group);
+            }
+        }
+        context.start();
+
+        await().atMost(5, TimeUnit.SECONDS).until(() -> 
GROUPS.stream().allMatch(service::isLeader));
+        for (String group : GROUPS) {
+            assertEquals("mypod1", getHolder(type, simulators, group));
+        }
+        return service;
+    }
+
+    private static String getHolder(LeaseResourceType type, Map<String, 
ResourceLockSimulator<?>> simulators, String group) {
+        Object resource = simulators.get(group).getResource();
+        if (type == LeaseResourceType.Lease) {
+            Lease lease = (Lease) resource;
+            return lease != null && lease.getSpec() != null ? 
lease.getSpec().getHolderIdentity() : null;
+        }
+        ConfigMap configMap = (ConfigMap) resource;
+        return configMap != null && configMap.getData() != null ? 
configMap.getData().get("leader.pod." + group) : null;
+    }
+
+    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;
+    }
+
+    /**
+     * 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/components/camel-kubernetes/src/test/java/org/apache/camel/component/kubernetes/cluster/utils/LockTestServer.java
 
b/components/camel-kubernetes/src/test/java/org/apache/camel/component/kubernetes/cluster/utils/LockTestServer.java
index d6ece2286a27..49f9917d51d9 100644
--- 
a/components/camel-kubernetes/src/test/java/org/apache/camel/component/kubernetes/cluster/utils/LockTestServer.java
+++ 
b/components/camel-kubernetes/src/test/java/org/apache/camel/component/kubernetes/cluster/utils/LockTestServer.java
@@ -54,13 +54,13 @@ public class LockTestServer<T extends HasMetadata> extends 
KubernetesMockServer
     private static final PodStatus NOT_READY = new 
PodStatusBuilder().withPhase("Running").addNewCondition().withType("Ready")
             .withStatus("false").endCondition().build();
 
-    private boolean refuseRequests;
+    private volatile boolean refuseRequests;
 
     private volatile boolean refuseUpdateRequests;
 
     private final AtomicInteger refusedUpdateRequests = new AtomicInteger();
 
-    private Long delayRequests;
+    private volatile Long delayRequests;
 
     private Set<String> pods;
 
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 6322076c50ab..476e4c24aa6d 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
@@ -2302,6 +2302,38 @@ for the other changes.
   for. Before, it returned the replicas of its status, which lags behind until 
the pods are started or stopped, and
   failed with a `NullPointerException` when the deployment config had no 
status yet.
 
+=== camel-kubernetes - a stopped cluster view gives up the leadership
+
+A Kubernetes cluster view stops when its last user (such as a `master:` 
consumer or a clustered route) releases it, or
+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.
+
+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
+this pod was no longer ready. A pod that is stopped while it waits to become 
the leader keeps the lease, as before. If
+the lease cannot be updated, a WARN is logged and the lease is kept until the 
pod is no longer ready, as before.
+
+The stop of a view now waits for a check of the lease that is running, and 
then for the release. Both together take up
+to about the renew deadline (`renewDeadlineMillis`, 10 seconds by default). 
The Kubernetes client's own retries
+(`requestRetryBackoffLimit`, 10 by default) do not make it longer, but the 
time the leadership listeners of the view take
+when it stops counts against it.
+
+The views are stopped one after another. When the CamelContext stops, each 
clustered route or `master:` consumer
+releases its view, which stops the view once no other route uses it. Then the 
cluster service stops the rest. The views
+that stop while the CamelContext or the cluster service stops share one renew 
deadline:
+
+* The time each view spends in its stop is taken from the deadline. The time 
between their stops (such as the graceful
+  shutdown of the routes) is not.
+* With an API server that does not answer, the views wait up to about the 
renew deadline in all, not once per group.
+* A view that stops after the time is used up does not try the release.
+
+A view that stops on its own while the CamelContext runs (such as when its 
last clustered route is removed) has its own
+renew deadline. A view also does not try the release when its last lookup of 
the lease (or of the pods) or its last
+renewal failed; the Kubernetes client reports those only after its own 
retries. A release that is given up or not tried
+logs a WARN, and the lease is then kept until the pod is no longer ready, as 
before.
+
 === camel-langchain4j-embeddingstore - auto-embedding a TextSegment, a List, a 
Map or a POJO body, and the REMOVE id
 
 With an `embeddingModel` and no `CamelLangChain4jEmbeddingsEmbedding` header, 
ADD and SEARCH now embed a `TextSegment`

Reply via email to