davsclaus commented on code in PR #30527:
URL: https://github.com/apache/camel/pull/30527#discussion_r4651897668
##########
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:
Added the comment in b0b192cbb13a: `shutdownNow` interrupts a release that
is still blocked in an API call, and its termination is not awaited because the
time for the stop is used up by then.
_Claude Code on behalf of Claus Ibsen_
##########
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:
Agreed, no change: `leaseCallFailed()` only sets a flag, and the caller
finds `serializedExecutor == null` right after, as its comment says.
_Claude Code on behalf of Claus Ibsen_
##########
docs/user-manual/modules/ROOT/pages/camel-4x-upgrade-guide-4_24.adoc:
##########
@@ -2302,6 +2302,31 @@ 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
+
+When a Kubernetes cluster view stops (its last user, such as a `master:`
consumer or a clustered route, releases it, or
+the cluster service stops), the view now reports that the pod is no longer the
leader, tells its listeners, and, if the
+leadership of the pod had taken effect, 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), and 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 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, and 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 of them spends in its stop is taken from it (the time
between their stops, such as the graceful
+shutdown of the routes, is not), so with an API server that does not answer
they wait up to about the renew deadline in
+all, not once per group, and a view that stops after the time is used up does
not try the release. A view that stops on
Review Comment:
Rewritten in b0b192cbb13a: the entry is now split into shorter paragraphs,
and the shared renew deadline is a short list. The facts are the same.
_Claude Code on behalf of Claus Ibsen_
--
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]