forked from kubernetes-client/java
-
Notifications
You must be signed in to change notification settings - Fork 0
/
LeaderElectorTest.java
311 lines (264 loc) · 9.93 KB
/
LeaderElectorTest.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
/*
Copyright 2020 The Kubernetes Authors.
Licensed 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 io.kubernetes.client.e2e.extended.leaderelection;
import io.kubernetes.client.extended.leaderelection.LeaderElectionConfig;
import io.kubernetes.client.extended.leaderelection.LeaderElector;
import io.kubernetes.client.extended.leaderelection.Lock;
import io.kubernetes.client.extended.leaderelection.resourcelock.ConfigMapLock;
import io.kubernetes.client.extended.leaderelection.resourcelock.EndpointsLock;
import io.kubernetes.client.extended.leaderelection.resourcelock.LeaseLock;
import io.kubernetes.client.openapi.ApiClient;
import io.kubernetes.client.openapi.ApiException;
import io.kubernetes.client.openapi.apis.CoordinationV1Api;
import io.kubernetes.client.openapi.apis.CoreV1Api;
import io.kubernetes.client.util.ClientBuilder;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.time.Duration;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@RunWith(Parameterized.class)
public class LeaderElectorTest {
private static final Logger LOGGER = LoggerFactory.getLogger(LeaderElectorTest.class);
private static final String LOCK_RESOURCE_NAME = "leader-election-it";
private static final String NAMESPACE = "default";
private enum LockType {
ConfigMap,
Endpoints,
Lease
}
@Parameterized.Parameters(name = "{0}")
public static Collection<Object[]> constructorFeeder() {
final List<Object[]> args = new ArrayList<>();
args.add(new Object[] {LockType.ConfigMap});
args.add(new Object[] {LockType.Endpoints});
args.add(new Object[] {LockType.Lease});
return args;
}
private final ApiClient apiClient;
private final LockType lockType;
public LeaderElectorTest(LockType lockType) {
try {
apiClient = ClientBuilder.defaultClient();
} catch (IOException ex) {
throw new RuntimeException("Couldn't create ApiClient", ex);
}
this.lockType = lockType;
}
@Before
public void setup() throws Exception {
// delete the lock resource if it exists, or else first leader candidate might need to wait for
// a whole leaseDuration configured
switch (lockType) {
case ConfigMap:
deleteConfigMapLockResource();
break;
case Endpoints:
deleteEndpointsLockResource();
break;
case Lease:
deleteLeaseLockResource();
break;
default:
throw new RuntimeException("Unknown LockType " + lockType);
}
}
@Test(timeout = 30000L)
public void testSingleCandidateLeaderElection() throws Exception {
CountDownLatch startLeadershipLatch = new CountDownLatch(1);
CountDownLatch stopLeadershipLatch = new CountDownLatch(1);
LeaderElector leaderElector =
makeAndRunLeaderElectorAsync(
"candidate",
null,
() -> startLeadershipLatch.countDown(),
() -> stopLeadershipLatch.countDown(),
apiClient);
startLeadershipLatch.await();
leaderElector.close();
stopLeadershipLatch.await();
}
@Test(timeout = 30000L)
public void testMultiCandidateLeaderElection() throws Exception {
CyclicBarrier startBarrier = new CyclicBarrier(2);
CountDownLatch startBeingLeader = new CountDownLatch(1);
CountDownLatch stopBeingLeader = new CountDownLatch(1);
AtomicInteger startBeingLeaderCount = new AtomicInteger();
AtomicInteger stopBeingLeaderCount = new AtomicInteger();
AtomicReference<String> leaderRef = new AtomicReference<>();
String candidate1 = "candidate1";
String candidate2 = "candidate2";
LeaderElector leaderElector1 =
makeAndRunLeaderElectorAsync(
candidate1,
startBarrier,
() -> {
startBeingLeaderCount.incrementAndGet();
leaderRef.set(candidate1);
startBeingLeader.countDown();
},
() -> {
stopBeingLeaderCount.incrementAndGet();
stopBeingLeader.countDown();
},
apiClient);
LeaderElector leaderElector2 =
makeAndRunLeaderElectorAsync(
candidate2,
startBarrier,
() -> {
startBeingLeaderCount.incrementAndGet();
leaderRef.set(candidate2);
startBeingLeader.countDown();
},
() -> {
stopBeingLeaderCount.incrementAndGet();
stopBeingLeader.countDown();
},
apiClient);
// wait till someone becomes leader
startBeingLeader.await();
Assert.assertNotNull(leaderRef.get());
Assert.assertTrue(candidate1.equals(leaderRef.get()) || candidate2.equals(leaderRef.get()));
// stop both LeaderElectors, in order .. non-leader, then leader so that
// non-leader doesn't get to become leader
if (candidate1.equals(leaderRef.get())) {
leaderElector2.close();
leaderElector1.close();
} else {
leaderElector1.close();
leaderElector2.close();
}
stopBeingLeader.await();
// make sure that only one candidate became leader
Assert.assertEquals(1, startBeingLeaderCount.get());
Assert.assertEquals(1, stopBeingLeaderCount.get());
}
@Test(timeout = 30000L)
public void testLeaderGracefulShutdown() throws Exception {
CountDownLatch startBeingLeader1 = new CountDownLatch(1);
CountDownLatch stopBeingLeader1 = new CountDownLatch(1);
LeaderElector leaderElector1 =
makeAndRunLeaderElectorAsync(
"candidate1",
null,
() -> startBeingLeader1.countDown(),
() -> stopBeingLeader1.countDown(),
apiClient);
// wait for candidate1 to become leader
startBeingLeader1.await();
CountDownLatch startBeingLeader2 = new CountDownLatch(1);
CountDownLatch stopBeingLeader2 = new CountDownLatch(1);
LeaderElector leaderElector2 =
makeAndRunLeaderElectorAsync(
"candidate2",
null,
() -> startBeingLeader2.countDown(),
() -> stopBeingLeader2.countDown(),
apiClient);
leaderElector1.close();
// ensure stopBeingLeader hook is called
stopBeingLeader1.await();
// wait for candidate2 to become leader
startBeingLeader2.await();
leaderElector2.close();
}
private LeaderElector makeAndRunLeaderElectorAsync(
String candidateId,
CyclicBarrier startBarrier,
Runnable startBeingLeader,
Runnable stopBeingLeader,
ApiClient apiClient) {
Lock lock = makeLock(candidateId, NAMESPACE, LOCK_RESOURCE_NAME, apiClient);
LeaderElectionConfig leaderElectionConfig =
new LeaderElectionConfig(
lock, Duration.ofSeconds(30), Duration.ofSeconds(23), Duration.ofSeconds(3));
LeaderElector leaderElector = new LeaderElector(leaderElectionConfig);
Thread thread =
new Thread(
() -> {
if (startBarrier != null) {
try {
startBarrier.await();
} catch (InterruptedException | BrokenBarrierException ex) {
LOGGER.error("startBarrier.await() failed", ex);
return;
}
}
leaderElector.run(startBeingLeader, stopBeingLeader);
},
String.format("%s-leader-elector-main", candidateId));
thread.setDaemon(true);
thread.start();
return leaderElector;
}
private Lock makeLock(
String candidateId, String namespace, String lockResourceName, ApiClient k8sApiClient) {
switch (lockType) {
case ConfigMap:
return new ConfigMapLock(namespace, lockResourceName, candidateId, k8sApiClient);
case Endpoints:
return new EndpointsLock(namespace, lockResourceName, candidateId, k8sApiClient);
case Lease:
return new LeaseLock(namespace, lockResourceName, candidateId, k8sApiClient);
default:
throw new RuntimeException("Unknown LockType " + lockType);
}
}
private void deleteConfigMapLockResource() throws Exception {
try {
CoreV1Api coreV1Api = new CoreV1Api(apiClient);
coreV1Api.deleteNamespacedConfigMap(
LOCK_RESOURCE_NAME, NAMESPACE, null, null, null, null, null, null);
} catch (ApiException ex) {
if (ex.getCode() != HttpURLConnection.HTTP_NOT_FOUND) {
throw ex;
}
}
}
private void deleteEndpointsLockResource() throws Exception {
try {
CoreV1Api coreV1Api = new CoreV1Api(apiClient);
coreV1Api.deleteNamespacedEndpoints(
LOCK_RESOURCE_NAME, NAMESPACE, null, null, null, null, null, null);
} catch (ApiException ex) {
if (ex.getCode() != HttpURLConnection.HTTP_NOT_FOUND) {
throw ex;
}
}
}
private void deleteLeaseLockResource() throws Exception {
try {
CoordinationV1Api coordinationV1Api = new CoordinationV1Api(apiClient);
coordinationV1Api.deleteNamespacedLease(
LOCK_RESOURCE_NAME, NAMESPACE, null, null, null, null, null, null);
} catch (ApiException ex) {
if (ex.getCode() != HttpURLConnection.HTTP_NOT_FOUND) {
throw ex;
}
}
}
}