-
Notifications
You must be signed in to change notification settings - Fork 1.8k
/
LeaderElector.java
429 lines (384 loc) · 15 KB
/
LeaderElector.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
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
/*
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.extended.leaderelection;
import io.kubernetes.client.openapi.ApiException;
import io.kubernetes.client.util.Threads;
import java.net.HttpURLConnection;
import java.time.Duration;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.CancellationException;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.function.Consumer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class LeaderElector implements AutoCloseable {
private static final Logger log = LoggerFactory.getLogger(LeaderElector.class);
private static final double JITTER_FACTOR = 1.2;
private final LeaderElectionConfig config;
// internal bookkeeping
private LeaderElectionRecord observedRecord;
private long observedTimeMilliSeconds;
private final Consumer<Throwable> exceptionHandler;
// used to implement OnNewLeader(), may lag slightly from the
// value observedRecord.HolderIdentity if the transition has
// not yet been reported.
private String reportedLeader;
private Consumer<String> onNewLeaderHook;
private final ScheduledExecutorService scheduledWorkers =
Executors.newSingleThreadScheduledExecutor(
Threads.threadFactory("leader-elector-scheduled-worker-%d"));
private final ExecutorService leaseWorkers =
Executors.newSingleThreadExecutor(Threads.threadFactory("leader-elector-lease-worker-%d"));
private final ExecutorService hookWorkers =
Executors.newSingleThreadExecutor(Threads.threadFactory("leader-elector-hook-worker-%d"));
public LeaderElector(LeaderElectionConfig config) {
this(
config,
(t) -> {
log.error("Unexpected error on acquiring or renewing the lease", t);
});
}
public LeaderElector(LeaderElectionConfig config, Consumer<Throwable> exceptionHandler) {
if (config == null) {
throw new IllegalArgumentException("Config must be provided.");
}
List<String> errors = new LinkedList<>();
if (config.getLock() == null) {
errors.add("Lock must be provided.");
}
if (config.getLeaseDuration() == null) {
errors.add("LeaseDuration must be provided.");
}
if (config.getRetryPeriod() == null) {
errors.add("RetryPeriod must be provided.");
}
if (config.getRenewDeadline() == null) {
errors.add("RenewDeadline must be provided.");
}
if (config.getLeaseDuration().compareTo(config.getRenewDeadline()) <= 0) {
errors.add("LeaseDuration must be greater than renewDeadline.");
}
if (config.getRenewDeadline().compareTo(config.getRetryPeriod()) <= 0) {
errors.add("RenewDeadline must be greater than retryPeriod.");
}
if (config.getLeaseDuration().isZero() || config.getLeaseDuration().isNegative()) {
errors.add("LeaseDuration must be greater than zero.");
}
if (config.getRenewDeadline().isZero() || config.getRenewDeadline().isNegative()) {
errors.add("RenewDeadline must be greater than zero.");
}
if (config.getRetryPeriod().isZero() || config.getRetryPeriod().isNegative()) {
errors.add("RetryPeriod must be greater than zero.");
}
if (errors.size() > 0) {
throw new IllegalArgumentException(String.join(",", errors));
}
this.config = config;
this.exceptionHandler = exceptionHandler;
}
/**
* Runs the leader election in foreground.
*
* @param startLeadingHook called when a LeaderElector client starts leading
* @param stopLeadingHook called when a LeaderElector client stops leading
*/
public void run(Runnable startLeadingHook, Runnable stopLeadingHook) {
run(startLeadingHook, stopLeadingHook, null);
}
/**
* Runs the leader election in foreground.
*
* @param startLeadingHook called when a LeaderElector client starts leading
* @param stopLeadingHook called when a LeaderElector client stops leading
* @param onNewLeaderHook called when the client observes a leader that is not the previously
* observed leader. This includes the first observed leader when the client starts.
*/
public void run(
Runnable startLeadingHook, Runnable stopLeadingHook, Consumer<String> onNewLeaderHook) {
this.onNewLeaderHook = onNewLeaderHook;
log.info("Start leader election with lock {}", config.getLock().describe());
try {
if (!acquire()) {
// Fail to acquire leadership
return;
}
log.info("Successfully acquired lease, became leader");
// Hook on start leading
hookWorkers.submit(startLeadingHook);
renewLoop();
log.info("Failed to renew lease, lose leadership");
// Hook on stop leading
stopLeadingHook.run();
} catch (Throwable t) {
stopLeadingHook.run();
}
}
private boolean acquire() {
if (log.isDebugEnabled()) {
log.debug("Attempting to acquire leader lease...");
}
Duration retryPeriod = config.getRetryPeriod();
long retryPeriodMillis = retryPeriod.toMillis();
AtomicBoolean acquired = new AtomicBoolean(false);
ScheduledFuture scheduledFuture =
scheduledWorkers.scheduleWithFixedDelay(
() -> {
Future<Boolean> future = leaseWorkers.submit(this::tryAcquireOrRenew);
try {
Boolean success = future.get(retryPeriodMillis, TimeUnit.MILLISECONDS);
if (log.isDebugEnabled()) {
log.debug("The tryAcquireOrRenew result is {}", success);
}
acquired.set(success);
} catch (CancellationException e) {
log.info("Processing tryAcquireOrRenew successfully canceled");
} catch (Throwable t) {
this.exceptionHandler.accept(t);
future.cancel(true); // make sure the acquire work doesn't overlap
} finally {
maybeReportTransition();
}
},
0,
Double.valueOf(retryPeriodMillis * (JITTER_FACTOR * Math.random() + 1)).longValue(),
TimeUnit.MILLISECONDS);
try {
while (!acquired.get()) {
Thread.sleep(retryPeriodMillis);
}
} catch (InterruptedException e) {
log.error("LeaderElection acquire loop gets interrupted", e);
return false;
} finally {
scheduledFuture.cancel(true);
}
return true;
}
private void renewLoop() {
if (log.isDebugEnabled()) {
log.debug("Attempting to renew leader lease...");
}
Duration retryPeriod = config.getRetryPeriod();
long retryPeriodMillis = retryPeriod.toMillis();
Duration renewDeadline = config.getRenewDeadline();
long renewDeadlineMillis = renewDeadline.toMillis();
try {
while (true) {
final Future<Boolean> future =
leaseWorkers.submit(
() -> {
try {
// retry until success or interrupted
while (!tryAcquireOrRenew()) {
Thread.sleep(retryPeriodMillis);
maybeReportTransition();
}
} catch (InterruptedException e) {
return false;
}
return true;
});
boolean renewResult;
try {
renewResult = future.get(renewDeadlineMillis, TimeUnit.MILLISECONDS);
} catch (ExecutionException | TimeoutException t) {
if (log.isDebugEnabled()) {
log.debug("failed to tryAcquireOrRenew", t);
}
renewResult = false;
} finally {
future.cancel(true); // make the lease worker doesn't overlap
}
if (renewResult) {
if (log.isDebugEnabled()) {
log.debug("Successfully renewed lease");
}
Thread.sleep(retryPeriodMillis);
} else {
break;
}
}
} catch (InterruptedException e) {
log.error("LeaderElection renew loop gets interrupted", e);
}
}
private boolean tryAcquireOrRenew() {
Date now = new Date();
Lock lock = config.getLock();
LeaderElectionRecord leaderElectionRecord =
new LeaderElectionRecord(
lock.identity(),
Long.valueOf(config.getLeaseDuration().getSeconds()).intValue(),
now,
now,
0,
config.getOwnerReference());
// 1. obtain or create the ElectionRecord
LeaderElectionRecord oldLeaderElectionRecord;
try {
oldLeaderElectionRecord = lock.get();
} catch (ApiException e) {
if (e.getCode() != HttpURLConnection.HTTP_NOT_FOUND) {
log.error("Error retrieving resource lock {}", lock.describe(), e);
return false;
}
if (log.isDebugEnabled()) {
log.debug("Lock not found, try to create it");
}
// No Lock resource exists, try to get leadership by creating it
return createLock(lock, leaderElectionRecord);
}
// alright, we have an existing lock resource
// 1. Is Lock Empty? --> try to get leadership by updating it
// 2. Am I the Leader? --> update info and renew lease by updating it
// 3. I am not the Leader?
// 3.1 is Lock expired? --> try to get leadership by updating it
// 3.2 Lock not expired? --> update info, try later
if (oldLeaderElectionRecord == null
|| oldLeaderElectionRecord.getAcquireTime() == null
|| oldLeaderElectionRecord.getRenewTime() == null
|| oldLeaderElectionRecord.getHolderIdentity() == null) {
// We found the lock resource with an empty LeaderElectionRecord, try to get leadership by
// updating it
if (log.isDebugEnabled()) {
log.debug("Update lock to get lease");
}
if (oldLeaderElectionRecord != null) {
// maintain the leaderTransitions
leaderElectionRecord.setLeaderTransitions(
oldLeaderElectionRecord.getLeaderTransitions() + 1);
}
return updateLock(lock, leaderElectionRecord);
}
// 2. Record obtained with LeaderElectionRecord, check the Identity & Time
if (!oldLeaderElectionRecord.equals(this.observedRecord)) {
this.observedRecord = oldLeaderElectionRecord;
this.observedTimeMilliSeconds = System.currentTimeMillis();
}
if (observedTimeMilliSeconds + config.getLeaseDuration().toMillis() > now.getTime()
&& !isLeader()) {
if (log.isDebugEnabled()) {
log.debug(
"Lock is held by {} and has not yet expired",
oldLeaderElectionRecord.getHolderIdentity());
}
return false;
}
// 3. We're going to try to update. The leaderElectionRecord is set to it's default
// here. Let's correct it before updating.
if (isLeader()) {
leaderElectionRecord.setAcquireTime(oldLeaderElectionRecord.getAcquireTime());
leaderElectionRecord.setLeaderTransitions(oldLeaderElectionRecord.getLeaderTransitions());
} else {
leaderElectionRecord.setLeaderTransitions(oldLeaderElectionRecord.getLeaderTransitions() + 1);
}
if (log.isDebugEnabled()) {
log.debug("Update lock to renew lease");
}
boolean renewalStatus = updateLock(lock, leaderElectionRecord);
if (renewalStatus && log.isDebugEnabled()) {
log.debug("TryAcquireOrRenew return success");
}
return renewalStatus;
}
private boolean createLock(Lock lock, LeaderElectionRecord leaderElectionRecord) {
boolean createSuccess = lock.create(leaderElectionRecord);
if (!createSuccess) {
return false;
}
this.observedRecord = leaderElectionRecord;
this.observedTimeMilliSeconds = System.currentTimeMillis();
return true;
}
private boolean updateLock(Lock lock, LeaderElectionRecord leaderElectionRecord) {
boolean updateSuccess = lock.update(leaderElectionRecord);
if (!updateSuccess) {
return false;
}
this.observedRecord = leaderElectionRecord;
this.observedTimeMilliSeconds = System.currentTimeMillis();
return true;
}
private boolean isLeader() {
return this.config.getLock().identity().equals(this.observedRecord.getHolderIdentity());
}
private void maybeReportTransition() {
if (this.observedRecord == null) {
return;
}
if (this.observedRecord.getHolderIdentity().equals(this.reportedLeader)) {
return;
}
this.reportedLeader = this.observedRecord.getHolderIdentity();
if (this.onNewLeaderHook != null) {
this.hookWorkers.submit(() -> onNewLeaderHook.accept(this.reportedLeader));
}
}
@Override
public void close() {
log.info("Closing...");
scheduledWorkers.shutdownNow();
leaseWorkers.shutdownNow();
hookWorkers.shutdownNow();
// If I am the leader, free the lock so that other candidates can take it immediately
if (observedRecord != null && isLeader()) {
// First ensure that all executors have stopped
try {
boolean isTerminated =
scheduledWorkers.awaitTermination(
config.getRetryPeriod().getSeconds(), TimeUnit.SECONDS);
if (!isTerminated) {
log.warn("scheduledWorkers executor termination didn't finish.");
return;
}
isTerminated =
leaseWorkers.awaitTermination(config.getRetryPeriod().getSeconds(), TimeUnit.SECONDS);
if (!isTerminated) {
log.warn("leaseWorkers executor termination didn't finish.");
return;
}
isTerminated =
hookWorkers.awaitTermination(config.getRetryPeriod().getSeconds(), TimeUnit.SECONDS);
if (!isTerminated) {
log.warn("hookWorkers executor termination didn't finish.");
return;
}
} catch (InterruptedException ex) {
log.warn("Failed to ensure executors termination.", ex);
return;
}
log.info("Giving up the lock....");
LeaderElectionRecord emptyRecord = new LeaderElectionRecord();
// maintain leaderTransitions count
emptyRecord.setLeaderTransitions(observedRecord.getLeaderTransitions());
// LeaseLock impl requires a non-zero value for leaseDuration
emptyRecord.setLeaseDurationSeconds(
Long.valueOf(config.getLeaseDuration().getSeconds()).intValue());
boolean status = this.config.getLock().update(emptyRecord);
if (!status) {
log.warn("Failed to give up the lock.");
}
}
log.info("Closed");
}
}