gnodet-bot commented on code in PR #30527:
URL: https://github.com/apache/camel/pull/30527#discussion_r4651697036


##########
components/camel-kubernetes/src/main/java/org/apache/camel/component/kubernetes/cluster/lock/KubernetesLeadershipController.java:
##########
@@ -105,29 +122,172 @@ public void start() {
         }
     }
 
+    /**
+     * 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;

Review Comment:
   **Observation (low): narrow race window in `leaseCallFailed()`**
   
   `stopDeadlineNanos` is set **before** `serializedExecutor` is nulled. There 
is a narrow window where `leaseCallFailed()` could read `serializedExecutor != 
null` while `stopDeadlineNanos` is already set. As `leaseCallFailed()` only 
sets `lastLeaseCallFailed = true`, this is benign (the caller will shortly find 
`serializedExecutor == null` and exit). The comment on `leaseCallFailed()` 
already documents this correctly. No change needed.



##########
components/camel-kubernetes/src/main/java/org/apache/camel/component/kubernetes/cluster/lock/KubernetesLeadershipController.java:
##########
@@ -105,29 +122,172 @@ public void start() {
         }
     }
 
+    /**
+     * 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();
         }
         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 {
+            camelContext.getExecutorServiceManager().shutdownNow(executor);

Review Comment:
   **Observation (low): fire-and-forget shutdown of the release executor**
   
   After `Future.get(remaining, NANOSECONDS)` times out, `shutdownNow()` 
interrupts the blocked thread but does **not** await its termination -- the 
thread is left to JVM cleanup. This is intentional given the timeout semantics 
(we have already exceeded our deadline), but worth documenting in a comment so 
future readers don't add an `awaitTermination` and inadvertently block again:
   
   ```java
   // shutdownNow interrupts the blocked API call; we do not await termination
   // because we are already past the deadline -- the JVM will clean up.
   camelContext.getExecutorServiceManager().shutdownNow(executor);
   ```
   
   No code change required -- just a documentation suggestion.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]

Reply via email to