Skip to content

Commit 02a5906

Browse files
authored
Merge pull request #2075 from wind57/fabric8-native-leader-election
Fabric8 native leader election
2 parents 1cc1535 + 5759a40 commit 02a5906

File tree

48 files changed

+3851
-15
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

48 files changed

+3851
-15
lines changed

docs/modules/ROOT/pages/leader-election.adoc

Lines changed: 89 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -50,4 +50,93 @@ to `false` in `application.[properties | yaml]`:
5050
[source,properties]
5151
----
5252
management.info.leader.enabled=false
53+
54+
'''
55+
56+
There is another way you can configure leader election, and it comes with native support in the fabric8 library (k8s native client support is not yet implemented). In the long run, this will be the default way to configure leader election, while the previous one will be dropped. You can treat this one much like the JDK's "preview" features.
57+
58+
To be able to use it, you need to set the property:
59+
60+
[source]
61+
----
62+
spring.cloud.kubernetes.leader.election.enabled=true
63+
----
64+
65+
Unlike the old implementation, this one will use either the `Lease` _or_ `ConfigMap` as the lock, depending on your cluster version. You can force using configMap still, even if leases are supported, via :
66+
67+
[source]
68+
----
69+
spring.cloud.kubernetes.leader.election.use-config-map-as-lock=true
70+
----
71+
72+
The name of that `Lease` or `ConfigMap` can be defined using the property (default value is `spring-k8s-leader-election-lock`):
73+
74+
[source]
75+
----
76+
spring.cloud.kubernetes.leader.election.lockName=other-name
77+
----
78+
79+
The namespace where the lock is created (`default` being set if no explicit one exists) can be set also:
80+
81+
[source]
82+
----
83+
spring.cloud.kubernetes.leader.election.lockNamespace=other-namespace
84+
----
85+
86+
Before the leader election process kicks in, you can wait until the pod is ready (via the readiness check). This is enabled by default, but you can disable it if needed:
87+
88+
[source]
89+
----
90+
spring.cloud.kubernetes.leader.election.waitForPodReady=false
91+
----
92+
93+
Like with the old implementation, we will publish events by default, but this can be disabled:
94+
95+
[source]
96+
----
97+
spring.cloud.kubernetes.leader.election.publishEvents=false
98+
----
99+
100+
There are a few parameters that control how the leader election process will happen. To explain them, we need to look at the high-level implementation of this process. All the candidate pods try to become the leader, or they try to _acquire_ the lock. If the lock is already taken, they will continue to retry to acquire it every `spring.cloud.kubernetes.leader.election.retryPeriod` (value is specified as `java.time.Duration`, and by default it is 2 seconds).
101+
102+
If the lock is not taken, current pod becomes the leader. It does so by inserting a so-called "record" into the lock (`Lease` or `ConfigMap`). Among the things that the "record" contains, is the `leaseDuration` (that you can specify via `spring.cloud.kubernetes.leader.election.leaseDuration`; by default it is 15 seconds and is of type `java.time.Duration`). This acts like a TTL on the lock: no other candidate can acquire the lock, unless this period has expired (from the last renewal time).
103+
104+
Once a certain pod establishes itself as the leader (by acquiring the lock), it will continuously (every `spring.cloud.kubernetes.leader.election.retryPeriod`) try to renew its lease, or in other words: it will try to extend its leadership. When a renewal happens, the "record" that is stored inside the lock, is updated. For example, `renewTime` is updated inside the record, to denote when the last renewal happened. (You can always peek inside these fields by using `kubectl describe lease...` for example).
105+
106+
Renewal must happen within a certain interval, specified by `spring.cloud.kubernetes.leader.election.renewDeadline`. By default, it is equal to 10 seconds, and it means that the leader pod has a maximum of 10 seconds to renew its leadership. If that does not happen, this pod loses its leadership and leader election starts again. Because other pods try to become leaders every 2 seconds (by default), it could mean that the pod that just lost leadership, will become leader again. If you want other pods to have a higher chance of becoming leaders, you can set the property (specified in seconds, by default it is 3) :
107+
108+
[source]
109+
----
110+
spring.cloud.kubernetes.leader.election.wait-after-renewal-failure=3
111+
----
112+
113+
This will mean that the pod (that could not renew its lease) and lost leadership, will wait this many seconds, before trying to become leader again.
114+
115+
Let's try to explain these settings based on an example: there are two pods that participate in leader election. For simplicity let's call them `podA` and `podB`. They both start at the same time: `12:00:00`, but `podA` establishes itself as the leader. This means that every two seconds (`retryPeriod`), `podB` will try to become the new leader. So at `12:00:02`, then at `12:00:04` and so on, it will basically ask : "Can I become the leader?". In our simplified example, the answer to that question can be answered based on `podA` activity.
116+
117+
After `podA` has become the leader, at every 2 seconds, it will try to "extend" or _renew_ its leadership. So at `12:00:02`, then at `12:00:04` and so on, `podA` goes to the lock and updates its record to reflect that it is still the leader. Between the last successful renewal and the next one, it has exactly 10 seconds (`renewalDeadline`). If it fails to renew its leadership (there is a connection problem or a big GC pause, etc.) within those 10 seconds, it stops leading and `podB` can acquire the leadership now. When `podA` stops being a leader in a graceful way, the lock record is "cleared", basically meaning that `podB` can acquire leadership immediately.
118+
119+
A different story happens when `podA` dies with an OutOfMemory for example, without being able to gracefully update lock record and this is when `leaseDuration` argument matters. The easiest way to explain is via an example:
120+
121+
`podA` has renewed its leadership at `12:00:04`, but at `12:00:05` it has been killed by the OOMKiller. At `12:00:06`, `podB` will try to become the leader. It will check if "now" (`12:00:06`) is _after_ last renewal + lease duration, essentially it will check:
122+
123+
[source]
124+
----
125+
12:00:06 > (12:00:04 + 00:00:10)
126+
----
127+
128+
The condition is not fulfilled, so it can't become the leader. Same result will be at `12:00:08`, `12:00:10` and so on, until `12:00:16` and this is where the TTL (`leaseDuration`) of the lock will expire and `podB` can acquire it. As such, a lower value of `leaseDuration` will mean a faster acquiring of leadership by other pods.
129+
130+
You might have to give proper RBAC to be able to use this functionality, for example:
131+
132+
[source]
133+
----
134+
- apiGroups: [ "coordination.k8s.io" ]
135+
resources: [ "leases" ]
136+
resourceNames: [ "spring-k8s-leader-election-lock" ]
137+
verbs: [ "get", "update", "create" ]
138+
- apiGroups: [ "" ]
139+
resources: [ "configmaps" ]
140+
resourceNames: [ "spring-k8s-leader-election-lock" ]
141+
verbs: [ "get", "update", "create" ]
53142
----

spring-cloud-kubernetes-commons/src/main/java/org/springframework/cloud/kubernetes/commons/leader/LeaderUtils.java

Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,25 +16,84 @@
1616

1717
package org.springframework.cloud.kubernetes.commons.leader;
1818

19+
import java.io.File;
20+
import java.io.IOException;
1921
import java.net.InetAddress;
2022
import java.net.UnknownHostException;
23+
import java.nio.file.Files;
24+
import java.nio.file.Path;
25+
import java.util.Optional;
2126
import java.util.concurrent.locks.ReentrantLock;
2227

2328
import org.springframework.cloud.kubernetes.commons.EnvReader;
29+
import org.springframework.core.log.LogAccessor;
2430
import org.springframework.util.StringUtils;
2531

32+
import static org.springframework.cloud.kubernetes.commons.KubernetesClientProperties.SERVICE_ACCOUNT_NAMESPACE_PATH;
33+
2634
/**
2735
* @author wind57
2836
*/
2937
public final class LeaderUtils {
3038

39+
/**
40+
* Coordination group for leader election.
41+
*/
42+
public static final String COORDINATION_GROUP = "coordination.k8s.io";
43+
44+
/**
45+
* Coordination version for leader election.
46+
*/
47+
public static final String COORDINATION_VERSION = "v1";
48+
49+
/**
50+
* Lease constant.
51+
*/
52+
public static final String LEASE = "Lease";
53+
54+
/**
55+
* Prefix for all properties related to leader election.
56+
*/
57+
public static final String LEADER_ELECTION_PROPERTY_PREFIX = "spring.cloud.kubernetes.leader.election";
58+
59+
/**
60+
* Property that controls whether leader election is enabled.
61+
*/
62+
public static final String LEADER_ELECTION_ENABLED_PROPERTY = LEADER_ELECTION_PROPERTY_PREFIX + ".enabled";
63+
64+
private static final String POD_NAMESPACE = "POD_NAMESPACE";
65+
66+
private static final LogAccessor LOG = new LogAccessor(LeaderUtils.class);
67+
3168
// k8s environment variable responsible for host name
3269
private static final String HOSTNAME = "HOSTNAME";
3370

3471
private LeaderUtils() {
3572

3673
}
3774

75+
/**
76+
* Ideally, should always be present. If not, downward API must enable this one.
77+
*/
78+
public static Optional<String> podNamespace() {
79+
Path serviceAccountPath = new File(SERVICE_ACCOUNT_NAMESPACE_PATH).toPath();
80+
boolean serviceAccountNamespaceExists = Files.isRegularFile(serviceAccountPath);
81+
if (serviceAccountNamespaceExists) {
82+
try {
83+
String namespace = new String(Files.readAllBytes(serviceAccountPath)).replace(System.lineSeparator(),
84+
"");
85+
LOG.info(() -> "read namespace : " + namespace + " from service account " + serviceAccountPath);
86+
return Optional.of(namespace);
87+
}
88+
catch (IOException e) {
89+
LOG.error(e,
90+
() -> "error reading service account, will default to reading env variable : " + POD_NAMESPACE);
91+
}
92+
93+
}
94+
return Optional.ofNullable(EnvReader.getEnv(POD_NAMESPACE));
95+
}
96+
3897
public static String hostName() throws UnknownHostException {
3998
String hostName = EnvReader.getEnv(HOSTNAME);
4099
if (StringUtils.hasText(hostName)) {
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,119 @@
1+
/*
2+
* Copyright 2013-present the original author or authors.
3+
*
4+
* Licensed under the Apache License, Version 2.0 (the "License");
5+
* you may not use this file except in compliance with the License.
6+
* You may obtain a copy of the License at
7+
*
8+
* https://www.apache.org/licenses/LICENSE-2.0
9+
*
10+
* Unless required by applicable law or agreed to in writing, software
11+
* distributed under the License is distributed on an "AS IS" BASIS,
12+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
* See the License for the specific language governing permissions and
14+
* limitations under the License.
15+
*/
16+
17+
package org.springframework.cloud.kubernetes.commons.leader.election;
18+
19+
import java.util.concurrent.Executors;
20+
import java.util.concurrent.ScheduledFuture;
21+
import java.util.concurrent.ScheduledThreadPoolExecutor;
22+
import java.util.concurrent.ThreadFactory;
23+
import java.util.concurrent.TimeUnit;
24+
import java.util.concurrent.locks.ReentrantLock;
25+
26+
import jakarta.annotation.Nonnull;
27+
import org.apache.commons.logging.LogFactory;
28+
29+
import org.springframework.core.log.LogAccessor;
30+
31+
/**
32+
* This is taken from fabric8 with some changes (we need it, so it could be placed in the
33+
* common package). A single thread scheduler that will shutdown itself when there are no
34+
* more jobs running inside it. When all ScheduledFuture::cancel are called, the queue of
35+
* tasks will be empty and there is an internal runnable that checks that.
36+
*
37+
* @author wind57
38+
*/
39+
public final class CachedSingleThreadScheduler {
40+
41+
private static final LogAccessor LOG = new LogAccessor(LogFactory.getLog(CachedSingleThreadScheduler.class));
42+
43+
private final ReentrantLock lock = new ReentrantLock();
44+
45+
private final long ttlMillis;
46+
47+
private final String name;
48+
49+
private ScheduledThreadPoolExecutor executor;
50+
51+
public CachedSingleThreadScheduler(String name, long ttlMillis) {
52+
this.ttlMillis = ttlMillis;
53+
this.name = name;
54+
}
55+
56+
public ScheduledFuture<?> scheduleWithFixedDelay(Runnable command, long initialDelay, long delay, TimeUnit unit) {
57+
try {
58+
lock.lock();
59+
this.startExecutor();
60+
LOG.debug(() -> "Scheduling command to run in : " + name);
61+
return this.executor.scheduleWithFixedDelay(command, initialDelay, delay, unit);
62+
}
63+
finally {
64+
lock.unlock();
65+
}
66+
}
67+
68+
public ScheduledFuture<?> schedule(Runnable command, long delay, TimeUnit unit) {
69+
try {
70+
lock.lock();
71+
this.startExecutor();
72+
LOG.debug(() -> "Scheduling command to run in : " + name);
73+
return this.executor.schedule(command, delay, unit);
74+
}
75+
finally {
76+
lock.unlock();
77+
}
78+
}
79+
80+
private void startExecutor() {
81+
if (this.executor == null) {
82+
this.executor = new ScheduledThreadPoolExecutor(1, threadFactory());
83+
this.executor.setRemoveOnCancelPolicy(true);
84+
this.executor.scheduleWithFixedDelay(this::shutdownCheck, this.ttlMillis, this.ttlMillis,
85+
TimeUnit.MILLISECONDS);
86+
}
87+
88+
}
89+
90+
private void shutdownCheck() {
91+
try {
92+
lock.lock();
93+
if (this.executor.getQueue().isEmpty()) {
94+
LOG.debug(() -> "Shutting down executor : " + name);
95+
this.executor.shutdownNow();
96+
this.executor = null;
97+
}
98+
}
99+
finally {
100+
lock.unlock();
101+
}
102+
103+
}
104+
105+
private ThreadFactory threadFactory() {
106+
return new ThreadFactory() {
107+
final ThreadFactory threadFactory = Executors.defaultThreadFactory();
108+
109+
@Override
110+
public Thread newThread(@Nonnull Runnable runnable) {
111+
Thread thread = threadFactory.newThread(runnable);
112+
thread.setName("cached-single-thread-scheduler" + "-" + thread.getName());
113+
thread.setDaemon(true);
114+
return thread;
115+
}
116+
};
117+
}
118+
119+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
/*
2+
* Copyright 2013-present the original author or authors.
3+
*
4+
* Licensed under the Apache License, Version 2.0 (the "License");
5+
* you may not use this file except in compliance with the License.
6+
* You may obtain a copy of the License at
7+
*
8+
* https://www.apache.org/licenses/LICENSE-2.0
9+
*
10+
* Unless required by applicable law or agreed to in writing, software
11+
* distributed under the License is distributed on an "AS IS" BASIS,
12+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
* See the License for the specific language governing permissions and
14+
* limitations under the License.
15+
*/
16+
17+
package org.springframework.cloud.kubernetes.commons.leader.election;
18+
19+
import java.lang.annotation.Documented;
20+
import java.lang.annotation.ElementType;
21+
import java.lang.annotation.Inherited;
22+
import java.lang.annotation.Retention;
23+
import java.lang.annotation.RetentionPolicy;
24+
import java.lang.annotation.Target;
25+
26+
import org.springframework.boot.autoconfigure.condition.NoneNestedConditions;
27+
import org.springframework.context.annotation.Conditional;
28+
29+
/**
30+
* @author wind57
31+
*/
32+
@Target({ ElementType.TYPE, ElementType.METHOD })
33+
@Retention(RetentionPolicy.RUNTIME)
34+
@Documented
35+
@Inherited
36+
@Conditional(ConditionalOnLeaderElectionDisabled.OnLeaderElectionDisabled.class)
37+
public @interface ConditionalOnLeaderElectionDisabled {
38+
39+
class OnLeaderElectionDisabled extends NoneNestedConditions {
40+
41+
OnLeaderElectionDisabled() {
42+
super(ConfigurationPhase.REGISTER_BEAN);
43+
}
44+
45+
@ConditionalOnLeaderElectionEnabled
46+
static class OnLeaderElectionDisabledClass {
47+
48+
}
49+
50+
}
51+
52+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
/*
2+
* Copyright 2013-present the original author or authors.
3+
*
4+
* Licensed under the Apache License, Version 2.0 (the "License");
5+
* you may not use this file except in compliance with the License.
6+
* You may obtain a copy of the License at
7+
*
8+
* https://www.apache.org/licenses/LICENSE-2.0
9+
*
10+
* Unless required by applicable law or agreed to in writing, software
11+
* distributed under the License is distributed on an "AS IS" BASIS,
12+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
* See the License for the specific language governing permissions and
14+
* limitations under the License.
15+
*/
16+
17+
package org.springframework.cloud.kubernetes.commons.leader.election;
18+
19+
import java.lang.annotation.Documented;
20+
import java.lang.annotation.ElementType;
21+
import java.lang.annotation.Inherited;
22+
import java.lang.annotation.Retention;
23+
import java.lang.annotation.RetentionPolicy;
24+
import java.lang.annotation.Target;
25+
26+
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
27+
28+
import static org.springframework.cloud.kubernetes.commons.leader.LeaderUtils.LEADER_ELECTION_ENABLED_PROPERTY;
29+
30+
/**
31+
* Provides a more succinct conditional for:
32+
* <code>spring.cloud.kubernetes.leader.election.enabled</code>.
33+
*
34+
* @author wind57
35+
*/
36+
@Target({ ElementType.TYPE, ElementType.METHOD })
37+
@Retention(RetentionPolicy.RUNTIME)
38+
@Documented
39+
@Inherited
40+
@ConditionalOnProperty(value = LEADER_ELECTION_ENABLED_PROPERTY, havingValue = "true", matchIfMissing = false)
41+
public @interface ConditionalOnLeaderElectionEnabled {
42+
43+
}

0 commit comments

Comments
 (0)