-
Notifications
You must be signed in to change notification settings - Fork 1.4k
/
LeaderElectorTest.java
292 lines (266 loc) · 11.5 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
/**
* Copyright (C) 2015 Red Hat, Inc.
*
* 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.fabric8.kubernetes.client.extended.leaderelection;
import io.fabric8.kubernetes.client.NamespacedKubernetesClient;
import io.fabric8.kubernetes.client.extended.leaderelection.resourcelock.LeaderElectionRecord;
import io.fabric8.kubernetes.client.extended.leaderelection.resourcelock.Lock;
import io.fabric8.kubernetes.client.extended.leaderelection.resourcelock.LockException;
import io.fabric8.kubernetes.client.utils.CommonThreadPool;
import io.fabric8.kubernetes.client.utils.Utils;
import org.awaitility.Awaitility;
import org.junit.jupiter.api.Test;
import org.mockito.Answers;
import java.time.Duration;
import java.time.Instant;
import java.time.ZoneOffset;
import java.time.ZonedDateTime;
import java.time.temporal.ChronoUnit;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;
import static io.fabric8.kubernetes.client.extended.leaderelection.LeaderElector.jitter;
import static io.fabric8.kubernetes.client.extended.leaderelection.LeaderElector.loop;
import static io.fabric8.kubernetes.client.extended.leaderelection.LeaderElector.now;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.atLeast;
import static org.mockito.Mockito.doAnswer;
import static org.mockito.Mockito.doNothing;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
class LeaderElectorTest {
final static AtomicReference<LeaderElectionRecord> activeLer = new AtomicReference<>(null);
@Test
void runShouldAbortAfterRenewDeadlineExpired() throws Exception {
// Given
final Long renewDeadlineMillis = 1000L;
final LeaderElectionConfig lec = mockLeaderElectionConfiguration();
when(lec.getRenewDeadline()).thenReturn(Duration.ofMillis(renewDeadlineMillis));
final Lock mockedLock = lec.getLock();
doNothing().doAnswer(invocation -> {
// Sleep so that RENEW DEADLINE is reached
Thread.sleep(renewDeadlineMillis * 2);
throw new LockException("");
}).when(mockedLock).update(any(), any());
// When
CompletableFuture<?> future = new LeaderElector(mock(NamespacedKubernetesClient.class), lec, CommonThreadPool.get())
.start();
// Then
future.get(10, TimeUnit.SECONDS);
verify(mockedLock, atLeast(2)).get(any());
verify(mockedLock, times(1)).create(any(), any());
verify(mockedLock, atLeast(2)).update(any(), any());
verify(lec.getLeaderCallbacks(), atLeast(1)).onNewLeader(eq("1337"));
verify(lec.getLeaderCallbacks(), times(1)).onStartLeading();
verify(lec.getLeaderCallbacks(), times(1)).onStopLeading();
}
@Test
void runShouldEndlesslyRun() throws Exception {
// Given
final ExecutorService executor = Executors.newSingleThreadExecutor();
final CountDownLatch signal = new CountDownLatch(1);
final LeaderElectionConfig lec = mockLeaderElectionConfiguration();
final Lock mockedLock = lec.getLock();
doNothing().doThrow(new LockException("Exception won't affect execution")).doNothing().doAnswer(invocation -> {
// Force dedicated thread to gracefully end after a couple of updates
signal.countDown();
return null;
}).when(mockedLock).update(any(), any());
// When
executor.submit(() -> new LeaderElector(mock(NamespacedKubernetesClient.class), lec, CommonThreadPool.get()).run());
signal.await(10, TimeUnit.SECONDS);
// Then
assertEquals(0, signal.getCount());
verify(mockedLock, atLeast(2)).get(any());
verify(mockedLock, times(1)).create(any(), any());
verify(mockedLock, atLeast(2)).update(any(), any());
verify(lec.getLeaderCallbacks(), atLeast(1)).onNewLeader(eq("1337"));
verify(lec.getLeaderCallbacks(), times(1)).onStartLeading();
executor.shutdownNow();
executor.awaitTermination(5, TimeUnit.SECONDS);
verify(lec.getLeaderCallbacks(), times(1)).onStopLeading();
}
@Test
void shouldReleaseWhenCanceled() throws Exception {
// Given
final LeaderElectionConfig lec = mockLeaderElectionConfiguration();
final CountDownLatch signal = new CountDownLatch(1);
final Lock mockedLock = lec.getLock();
when(lec.isReleaseOnCancel()).thenReturn(true);
doAnswer(invocation -> {
activeLer.set(invocation.getArgument(1, LeaderElectionRecord.class));
signal.countDown();
return null;
}).when(mockedLock).update(any(), any());
// When
LeaderElector leaderElector = new LeaderElector(mock(NamespacedKubernetesClient.class), lec, CommonThreadPool.get());
CompletableFuture<?> started = leaderElector.start();
assertTrue(signal.await(10, TimeUnit.SECONDS));
started.cancel(true);
// Then
Awaitility.await().atMost(10, TimeUnit.SECONDS).until(() -> Utils.isNullOrEmpty(activeLer.get().getHolderIdentity()));
assertEquals(0, activeLer.get().getLeaderTransitions());
// create a new elector, they are no good after a single use
leaderElector = new LeaderElector(mock(NamespacedKubernetesClient.class), lec, CommonThreadPool.get());
// the leader is now empty/null, we should be able to re-acquire
assertTrue(leaderElector.tryAcquireOrRenew());
// there should be a transition
assertEquals(1, activeLer.get().getLeaderTransitions());
}
@Test
void isLeaderAndIsLeaderShouldReturnTrue() {
// Given
final LeaderElectionConfig lec = mock(LeaderElectionConfig.class, Answers.RETURNS_DEEP_STUBS);
when(lec.getLock().identity()).thenReturn("1337");
final LeaderElectionRecord ler = mock(LeaderElectionRecord.class);
when(ler.getHolderIdentity()).thenReturn("1337");
// When
final boolean result = new LeaderElector(mock(NamespacedKubernetesClient.class), lec, Runnable::run).isLeader(ler);
// Then
assertTrue(result);
}
@Test
void isLeaderTrueEmptyIdentity() {
// Given
final LeaderElectionConfig lec = mock(LeaderElectionConfig.class, Answers.RETURNS_DEEP_STUBS);
when(lec.getLock().identity()).thenReturn("1337");
when(lec.getLeaseDuration()).thenReturn(Duration.ofMinutes(59L));
final LeaderElectionRecord ler = mock(LeaderElectionRecord.class);
when(ler.getRenewTime()).thenReturn(ZonedDateTime.now(ZoneOffset.UTC));
// When
final boolean result = new LeaderElector(mock(NamespacedKubernetesClient.class), lec, Runnable::run).canBecomeLeader(ler);
// Then
assertTrue(result);
}
@Test
void isLeaderAndIsNotLeaderShouldReturnFalse() {
// Given
final LeaderElectionConfig lec = mock(LeaderElectionConfig.class, Answers.RETURNS_DEEP_STUBS);
when(lec.getLock().identity()).thenReturn("313373");
final LeaderElectionRecord ler = mock(LeaderElectionRecord.class);
when(ler.getHolderIdentity()).thenReturn("1337");
// When
final boolean result = new LeaderElector(mock(NamespacedKubernetesClient.class), lec, Runnable::run).isLeader(ler);
// Then
assertFalse(result);
}
@Test
void canBecomeLeaderAndDifferentLeaderWithExpiredLockShouldReturnTrue() {
// Given
final LeaderElectionConfig lec = mock(LeaderElectionConfig.class);
when(lec.getLeaseDuration()).thenReturn(Duration.ofMinutes(59L));
final LeaderElectionRecord ler = mock(LeaderElectionRecord.class);
when(ler.getHolderIdentity()).thenReturn("someone");
when(ler.getRenewTime()).thenReturn(ZonedDateTime.now(ZoneOffset.UTC).minusHours(1));
// When
final boolean result = new LeaderElector(mock(NamespacedKubernetesClient.class), lec, Runnable::run).canBecomeLeader(ler);
// Then
assertTrue(result);
}
@Test
void canBecomeLeaderAndDifferentLeaderWithActiveLockShouldReturnFalse() {
// Given
final LeaderElectionConfig lec = mock(LeaderElectionConfig.class);
when(lec.getLeaseDuration()).thenReturn(Duration.ofHours(1L));
final LeaderElectionRecord ler = mock(LeaderElectionRecord.class);
when(ler.getHolderIdentity()).thenReturn("someone");
when(ler.getRenewTime()).thenReturn(ZonedDateTime.now(ZoneOffset.UTC));
// When
final boolean result = new LeaderElector(mock(NamespacedKubernetesClient.class), lec, Runnable::run).canBecomeLeader(ler);
// Then
assertFalse(result);
}
@Test
void loopCompletesOk() throws Exception {
// Given
CompletableFuture<?> cf = loop(completion -> {
completion.complete(null);
}, () -> 1L, CommonThreadPool.get());
// When
cf.get(500, TimeUnit.MILLISECONDS);
}
@Test
void loopCancel() throws Exception {
// Given
AtomicInteger count = new AtomicInteger();
CompletableFuture<?> cf = loop(completion -> {
count.getAndIncrement();
}, () -> 10L, CommonThreadPool.get());
// When
Awaitility.await().atMost(1, TimeUnit.SECONDS).until(() -> count.get() >= 1);
cf.cancel(true);
// make sure that the task is no longer running
Thread.sleep(100);
int sample = count.get();
Thread.sleep(100);
assertEquals(sample, count.get());
}
@Test
void nowShouldReturnZonedTimeInUTC() {
// Given
final Instant now = Instant.now();
// When
final ZonedDateTime result = now();
// Then
assertEquals(ZoneOffset.UTC, result.getZone());
final long delta = result.toEpochSecond() - now.getEpochSecond();
assertTrue(delta <= 1);
assertTrue(delta >= 0);
}
@Test
void jitterWithPositiveShouldReturnPositiveDouble() {
// Given
final Duration test = Duration.of(1, ChronoUnit.SECONDS);
// When
final Duration result = jitter(test, 1);
// Then
assertTrue(result.toMillis() < 2000L);
assertTrue(result.toMillis() > 1000L);
}
@Test
void jitterWithNegativeShouldReturnDuration() {
// Given
final Duration test = Duration.of(1, ChronoUnit.SECONDS);
// When
final Duration result = jitter(test, -1);
// Then
assertTrue(result.toMillis() < 2000L);
assertTrue(result.toMillis() > 1000L);
}
private static LeaderElectionConfig mockLeaderElectionConfiguration() throws Exception {
final LeaderElectionConfig lec = mock(LeaderElectionConfig.class, Answers.RETURNS_DEEP_STUBS);
when(lec.getLeaseDuration()).thenReturn(Duration.ofSeconds(2L));
when(lec.getRenewDeadline()).thenReturn(Duration.ofSeconds(1L));
when(lec.getRetryPeriod()).thenReturn(Duration.ofMillis(10L));
final Lock mockedLock = lec.getLock();
when(mockedLock.identity()).thenReturn("1337");
when(mockedLock.get(any())).thenReturn(null).thenAnswer(invocation -> activeLer.get());
doAnswer(invocation -> {
activeLer.set(invocation.getArgument(1, LeaderElectionRecord.class));
return null;
}).when(mockedLock).create(any(), any());
return lec;
}
}