-
Notifications
You must be signed in to change notification settings - Fork 556
/
RaftContext.java
1170 lines (1045 loc) · 36.5 KB
/
RaftContext.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
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright 2015-present Open Networking Foundation
* Copyright © 2020 camunda services GmbH (info@camunda.com)
*
* 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.atomix.raft.impl;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.base.Preconditions.checkState;
import static io.atomix.utils.concurrent.Threads.namedThreads;
import io.atomix.cluster.ClusterMembershipService;
import io.atomix.cluster.MemberId;
import io.atomix.raft.ElectionTimer;
import io.atomix.raft.RaftCommitListener;
import io.atomix.raft.RaftCommittedEntryListener;
import io.atomix.raft.RaftException.ProtocolException;
import io.atomix.raft.RaftRoleChangeListener;
import io.atomix.raft.RaftServer;
import io.atomix.raft.RaftServer.Role;
import io.atomix.raft.RaftThreadContextFactory;
import io.atomix.raft.SnapshotReplicationListener;
import io.atomix.raft.cluster.RaftMember;
import io.atomix.raft.cluster.RaftMember.Type;
import io.atomix.raft.cluster.impl.DefaultRaftMember;
import io.atomix.raft.cluster.impl.RaftClusterContext;
import io.atomix.raft.impl.zeebe.LogCompactor;
import io.atomix.raft.metrics.RaftReplicationMetrics;
import io.atomix.raft.metrics.RaftRoleMetrics;
import io.atomix.raft.partition.RaftElectionConfig;
import io.atomix.raft.partition.RaftPartitionConfig;
import io.atomix.raft.protocol.RaftResponse;
import io.atomix.raft.protocol.RaftResponse.Status;
import io.atomix.raft.protocol.RaftServerProtocol;
import io.atomix.raft.protocol.TransferRequest;
import io.atomix.raft.roles.ActiveRole;
import io.atomix.raft.roles.CandidateRole;
import io.atomix.raft.roles.FollowerRole;
import io.atomix.raft.roles.InactiveRole;
import io.atomix.raft.roles.LeaderRole;
import io.atomix.raft.roles.PassiveRole;
import io.atomix.raft.roles.PromotableRole;
import io.atomix.raft.roles.RaftRole;
import io.atomix.raft.storage.RaftStorage;
import io.atomix.raft.storage.StorageException;
import io.atomix.raft.storage.log.IndexedRaftLogEntry;
import io.atomix.raft.storage.log.RaftLog;
import io.atomix.raft.storage.system.MetaStore;
import io.atomix.raft.zeebe.EntryValidator;
import io.atomix.utils.concurrent.ComposableFuture;
import io.atomix.utils.concurrent.ThreadContext;
import io.atomix.utils.logging.ContextualLoggerFactory;
import io.atomix.utils.logging.LoggerContext;
import io.camunda.zeebe.snapshots.PersistedSnapshot;
import io.camunda.zeebe.snapshots.ReceivableSnapshotStore;
import io.camunda.zeebe.util.exception.UnrecoverableException;
import io.camunda.zeebe.util.health.FailureListener;
import io.camunda.zeebe.util.health.HealthMonitorable;
import io.camunda.zeebe.util.health.HealthReport;
import java.time.Duration;
import java.util.Objects;
import java.util.Random;
import java.util.Set;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CopyOnWriteArraySet;
import java.util.concurrent.ExecutionException;
import java.util.function.Consumer;
import java.util.function.Supplier;
import org.slf4j.Logger;
import org.slf4j.MDC;
/**
* Manages the volatile state and state transitions of a Raft server.
*
* <p>This class is the primary vehicle for managing the state of a server. All state that is shared
* across roles (i.e. follower, candidate, leader) is stored in the cluster state. This includes
* Raft-specific state like the current leader and term, the log, and the cluster configuration.
*/
public class RaftContext implements AutoCloseable, HealthMonitorable {
protected final String name;
protected final ThreadContext threadContext;
protected final ClusterMembershipService membershipService;
protected final RaftClusterContext cluster;
protected final RaftServerProtocol protocol;
protected final RaftStorage storage;
private final Logger log;
private final RaftElectionConfig electionConfig;
private final Set<RaftRoleChangeListener> roleChangeListeners = new CopyOnWriteArraySet<>();
private final Set<Consumer<State>> stateChangeListeners = new CopyOnWriteArraySet<>();
private final Set<Consumer<RaftMember>> electionListeners = new CopyOnWriteArraySet<>();
private final Set<RaftCommitListener> commitListeners = new CopyOnWriteArraySet<>();
private final Set<RaftCommittedEntryListener> committedEntryListeners =
new CopyOnWriteArraySet<>();
private final Set<SnapshotReplicationListener> snapshotReplicationListeners =
new CopyOnWriteArraySet<>();
private final Set<FailureListener> failureListeners = new CopyOnWriteArraySet<>();
private final RaftRoleMetrics raftRoleMetrics;
private final RaftReplicationMetrics replicationMetrics;
private final MetaStore meta;
private final RaftLog raftLog;
private final ReceivableSnapshotStore persistedSnapshotStore;
private final LogCompactor logCompactor;
private volatile State state = State.ACTIVE;
private RaftRole role = new InactiveRole(this);
private volatile MemberId leader;
private volatile long term;
private MemberId lastVotedFor;
private long commitIndex;
private volatile long firstCommitIndex;
private volatile boolean started;
private EntryValidator entryValidator;
// Used for randomizing election timeout
private final Random random;
private PersistedSnapshot currentSnapshot;
private boolean ongoingTransition = false;
// Keeps track of snapshot replication to notify new listeners about missed events
private MissedSnapshotReplicationEvents missedSnapshotReplicationEvents =
MissedSnapshotReplicationEvents.NONE;
@SuppressWarnings("java:S3077") // allow volatile here, health is immutable
private volatile HealthReport health = HealthReport.healthy(this);
private long lastHeartbeat;
private final RaftPartitionConfig partitionConfig;
private final int partitionId;
public RaftContext(
final String name,
final int partitionId,
final MemberId localMemberId,
final ClusterMembershipService membershipService,
final RaftServerProtocol protocol,
final RaftStorage storage,
final RaftThreadContextFactory threadContextFactory,
final Supplier<Random> randomFactory,
final RaftElectionConfig electionConfig,
final RaftPartitionConfig partitionConfig) {
this.name = checkNotNull(name, "name cannot be null");
this.membershipService = checkNotNull(membershipService, "membershipService cannot be null");
this.protocol = checkNotNull(protocol, "protocol cannot be null");
this.storage = checkNotNull(storage, "storage cannot be null");
random = randomFactory.get();
this.partitionId = partitionId;
raftRoleMetrics = new RaftRoleMetrics(name);
log =
ContextualLoggerFactory.getLogger(
getClass(), LoggerContext.builder(RaftServer.class).addValue(name).build());
this.electionConfig = electionConfig;
if (electionConfig.isPriorityElectionEnabled()) {
log.debug(
"Priority election is enabled with target priority {} and node priority {}",
electionConfig.getInitialTargetPriority(),
electionConfig.getNodePriority());
}
// Lock the storage directory.
if (!storage.lock(localMemberId.id())) {
throw new StorageException(
"Failed to acquire storage lock; ensure each Raft server is configured with a distinct storage directory");
}
final String baseThreadName = String.format("raft-server-%s-%s", localMemberId.id(), name);
threadContext =
threadContextFactory.createContext(
namedThreads(baseThreadName, log), this::onUncaughtException);
// in order to set the partition id once in the raft thread
threadContext.execute(() -> MDC.put("partitionId", Integer.toString(partitionId)));
// Open the metadata store.
meta = storage.openMetaStore();
// Load the current term and last vote from disk.
term = meta.loadTerm();
lastVotedFor = meta.loadVote();
// Construct the core log, reader, writer, and compactor.
raftLog = storage.openLog();
// Open the snapshot store.
persistedSnapshotStore = storage.getPersistedSnapshotStore();
persistedSnapshotStore.addSnapshotListener(this::setSnapshot);
// Update the current snapshot because the listener only notifies when a new snapshot is
// created.
persistedSnapshotStore
.getLatestSnapshot()
.ifPresent(persistedSnapshot -> currentSnapshot = persistedSnapshot);
verifySnapshotLogConsistent();
logCompactor = new LogCompactor(this);
this.partitionConfig = partitionConfig;
cluster = new RaftClusterContext(localMemberId, this);
replicationMetrics = new RaftReplicationMetrics(name);
replicationMetrics.setAppendIndex(raftLog.getLastIndex());
lastHeartbeat = System.currentTimeMillis();
// Register protocol listeners.
registerHandlers(protocol);
started = true;
}
private void verifySnapshotLogConsistent() {
final long currentSnapshotIndex = getCurrentSnapshotIndex();
if ((currentSnapshotIndex <= 0L && raftLog.getFirstIndex() != 1)
|| (currentSnapshotIndex > 0L
&& currentSnapshot.getIndex() + 1 < raftLog.getFirstIndex())) {
// There is no snapshot, but the log has been compacted!
throw new IllegalStateException(
String.format(
"Expected to find a snapshot at index >= log's first index %d, but found snapshot %d. A previous snapshot is most likely corrupted.",
raftLog.getFirstIndex(), currentSnapshotIndex));
}
}
private void setSnapshot(final PersistedSnapshot persistedSnapshot) {
threadContext.execute(() -> currentSnapshot = persistedSnapshot);
}
private void onUncaughtException(final Throwable error) {
log.error("An uncaught exception occurred, transition to inactive role", error);
try {
// to prevent further operations submitted to the threadcontext to execute
transition(Role.INACTIVE);
} catch (final Exception e) {
log.error("An error occurred when transitioning to inactive, closing the raft context", e);
close();
}
notifyFailureListeners(error);
}
private void notifyFailureListeners(final Throwable error) {
try {
if (error instanceof UnrecoverableException) {
health = HealthReport.dead(this).withIssue(error);
failureListeners.forEach((l) -> l.onUnrecoverableFailure(health));
} else {
health = HealthReport.unhealthy(this).withIssue(error);
failureListeners.forEach((l) -> l.onFailure(health));
}
} catch (final Exception e) {
log.error("Could not notify failure listeners", e);
}
}
/** Registers server handlers on the configured protocol. */
private void registerHandlers(final RaftServerProtocol protocol) {
protocol.registerConfigureHandler(request -> runOnContext(() -> role.onConfigure(request)));
protocol.registerInstallHandler(request -> runOnContext(() -> role.onInstall(request)));
protocol.registerReconfigureHandler(request -> runOnContext(() -> role.onReconfigure(request)));
protocol.registerTransferHandler(request -> runOnContext(() -> role.onTransfer(request)));
protocol.registerAppendHandler(request -> runOnContext(() -> role.onAppend(request)));
protocol.registerPollHandler(request -> runOnContext(() -> role.onPoll(request)));
protocol.registerVoteHandler(request -> runOnContext(() -> role.onVote(request)));
}
private <R extends RaftResponse> CompletableFuture<R> runOnContext(
final Supplier<CompletableFuture<R>> function) {
final CompletableFuture<R> future = new CompletableFuture<>();
threadContext.execute(
() ->
function
.get()
.whenComplete(
(response, error) -> {
if (error == null) {
future.complete(response);
} else {
future.completeExceptionally(error);
}
}));
return future;
}
public int getMaxAppendBatchSize() {
return partitionConfig.getMaxAppendBatchSize();
}
public int getMaxAppendsPerFollower() {
return partitionConfig.getMaxAppendsPerFollower();
}
/**
* Adds a role change listener. If there isn't currently a transition ongoing the listener is
* called immediately after adding the listener.
*
* @param listener The role change listener.
*/
public void addRoleChangeListener(final RaftRoleChangeListener listener) {
threadContext.execute(
() -> {
roleChangeListeners.add(listener);
// When a transition is currently ongoing, then the given
// listener will be called when the transition completes.
if (!ongoingTransition) {
// Otherwise, the listener will called directly for the last
// completed transition.
listener.onNewRole(getRole(), getTerm());
}
});
}
/**
* Removes a role change listener.
*
* @param listener The role change listener.
*/
public void removeRoleChangeListener(final RaftRoleChangeListener listener) {
roleChangeListeners.remove(listener);
}
/**
* Awaits a state change.
*
* @param state the state for which to wait
* @param listener the listener to call when the next state change occurs
*/
public void awaitState(final State state, final Consumer<State> listener) {
if (this.state == state) {
listener.accept(this.state);
} else {
addStateChangeListener(
new Consumer<>() {
@Override
public void accept(final State state) {
listener.accept(state);
removeStateChangeListener(this);
}
});
}
}
/**
* Adds a state change listener.
*
* @param listener The state change listener.
*/
public void addStateChangeListener(final Consumer<State> listener) {
stateChangeListeners.add(listener);
}
/**
* Removes a state change listener.
*
* @param listener The state change listener.
*/
public void removeStateChangeListener(final Consumer<State> listener) {
stateChangeListeners.remove(listener);
}
/**
* Adds a new commit listener, which will be notified whenever the commit position changes. Note
* that it will be called on the Raft thread, and as such should not perform any heavy
* computation.
*
* @param commitListener the listener to add
*/
public void addCommitListener(final RaftCommitListener commitListener) {
commitListeners.add(commitListener);
}
/**
* Removes registered commit listener
*
* @param commitListener the listenere to remove
*/
public void removeCommitListener(final RaftCommitListener commitListener) {
commitListeners.remove(commitListener);
}
/**
* Adds a new committed entry listener, which will be notified when the Leader commits a new
* entry. If RAFT runs currently in a Follower role this listeners are not called.
*
* <p>Note that it will be called on the Raft thread, and as such should not perform any heavy
* computation.
*
* @param raftCommittedEntryListener the listener to add
*/
public void addCommittedEntryListener(
final RaftCommittedEntryListener raftCommittedEntryListener) {
committedEntryListeners.add(raftCommittedEntryListener);
}
/**
* Removes registered committedEntryListener
*
* @param raftCommittedEntryListener the listener to remove
*/
public void removeCommittedEntryListener(
final RaftCommittedEntryListener raftCommittedEntryListener) {
committedEntryListeners.remove(raftCommittedEntryListener);
}
/**
* Notifies all listeners of the latest entry.
*
* @param lastCommitIndex index of the most recently committed entry
*/
public void notifyCommitListeners(final long lastCommitIndex) {
commitListeners.forEach(listener -> listener.onCommit(lastCommitIndex));
}
/**
* Notifies all listeners of the latest entry.
*
* @param committedEntry the most recently committed entry
*/
public void notifyCommitListeners(final IndexedRaftLogEntry committedEntry) {
commitListeners.forEach(listener -> listener.onCommit(committedEntry.index()));
committedEntryListeners.forEach(listener -> listener.onCommit(committedEntry));
}
/**
* Sets the commit index.
*
* @param commitIndex The commit index.
* @return the previous commit index
*/
public long setCommitIndex(final long commitIndex) {
checkArgument(commitIndex >= 0, "commitIndex must be positive");
final long previousCommitIndex = this.commitIndex;
if (commitIndex > previousCommitIndex) {
this.commitIndex = commitIndex;
raftLog.setCommitIndex(Math.min(commitIndex, raftLog.getLastIndex()));
if (raftLog.shouldFlushExplicitly() && isLeader()) {
// leader counts itself in quorum, so in order to commit the leader must persist
raftLog.flush();
setLastWrittenIndex(commitIndex);
}
final long configurationIndex = cluster.getConfiguration().index();
if (configurationIndex > previousCommitIndex && configurationIndex <= commitIndex) {
cluster.commit();
}
setFirstCommitIndex(commitIndex);
// On start up, set the state to READY after the follower has caught up with the leader
// https://github.com/zeebe-io/zeebe/issues/4877
if (state == State.ACTIVE && commitIndex >= firstCommitIndex) {
state = State.READY;
stateChangeListeners.forEach(l -> l.accept(state));
}
replicationMetrics.setCommitIndex(commitIndex);
}
return previousCommitIndex;
}
/**
* Adds a new snapshot replication listener, which will be notified before and after a new
* snapshot is received from a leader. Note that it will be called on the Raft thread, and hence
* should not perform any heavy computation.
*
* @param snapshotReplicationListener the listener to add
*/
public void addSnapshotReplicationListener(
final SnapshotReplicationListener snapshotReplicationListener) {
threadContext.execute(
() -> {
snapshotReplicationListeners.add(snapshotReplicationListener);
// Notify listener immediately if it registered during an ongoing replication.
// This is to prevent missing necessary state transitions.
switch (missedSnapshotReplicationEvents) {
case STARTED -> snapshotReplicationListener.onSnapshotReplicationStarted();
case COMPLETED -> {
snapshotReplicationListener.onSnapshotReplicationStarted();
snapshotReplicationListener.onSnapshotReplicationCompleted(term);
}
default -> {}
}
});
}
/**
* Removes registered snapshot replication listener
*
* @param snapshotReplicationListener the listener to remove
*/
public void removeSnapshotReplicationListener(
final SnapshotReplicationListener snapshotReplicationListener) {
threadContext.execute(() -> snapshotReplicationListeners.remove(snapshotReplicationListener));
}
public void notifySnapshotReplicationStarted() {
threadContext.execute(
() -> {
missedSnapshotReplicationEvents = MissedSnapshotReplicationEvents.STARTED;
snapshotReplicationListeners.forEach(
SnapshotReplicationListener::onSnapshotReplicationStarted);
});
}
public void notifySnapshotReplicationCompleted() {
threadContext.execute(
() -> {
snapshotReplicationListeners.forEach(l -> l.onSnapshotReplicationCompleted(term));
missedSnapshotReplicationEvents = MissedSnapshotReplicationEvents.COMPLETED;
});
}
/**
* Compacts the server logs.
*
* @return a future to be completed once the logs have been compacted
*/
public CompletableFuture<Void> compact() {
final ComposableFuture<Void> future = new ComposableFuture<>();
threadContext.execute(() -> logCompactor.compact().whenComplete(future));
return future;
}
/** Attempts to become the leader. */
public CompletableFuture<Void> anoint() {
if (role.role() == Role.LEADER) {
return CompletableFuture.completedFuture(null);
}
final CompletableFuture<Void> future = new CompletableFuture<>();
threadContext.execute(
() -> {
// Register a leader election listener to wait for the election of this node.
final Consumer<RaftMember> electionListener =
new Consumer<>() {
@Override
public void accept(final RaftMember member) {
if (member.memberId().equals(cluster.getLocalMember().memberId())) {
future.complete(null);
} else {
future.completeExceptionally(
new ProtocolException("Failed to transfer leadership"));
}
removeLeaderElectionListener(this);
}
};
addLeaderElectionListener(electionListener);
// If a leader already exists, request a leadership transfer from it. Otherwise,
// transition to the candidate
// state and attempt to get elected.
final RaftMember member = getCluster().getLocalMember();
final RaftMember leader = getLeader();
if (leader != null) {
protocol
.transfer(
leader.memberId(),
TransferRequest.builder().withMember(member.memberId()).build())
.whenCompleteAsync(
(response, error) -> {
if (error != null) {
future.completeExceptionally(error);
} else if (response.status() == Status.ERROR) {
future.completeExceptionally(response.error().createException());
} else {
transition(Role.CANDIDATE);
}
},
threadContext);
} else {
transition(Role.CANDIDATE);
}
});
return future;
}
/**
* Adds a leader election listener.
*
* @param listener The leader election listener.
*/
public void addLeaderElectionListener(final Consumer<RaftMember> listener) {
electionListeners.add(listener);
}
/**
* Removes a leader election listener.
*
* @param listener The leader election listener.
*/
public void removeLeaderElectionListener(final Consumer<RaftMember> listener) {
electionListeners.remove(listener);
}
/**
* Returns the cluster state.
*
* @return The cluster state.
*/
public RaftClusterContext getCluster() {
return cluster;
}
/**
* Returns the state leader.
*
* @return The state leader.
*/
public DefaultRaftMember getLeader() {
// Store in a local variable to prevent race conditions and/or multiple volatile lookups.
final MemberId leader = this.leader;
return leader != null ? cluster.getMember(leader) : null;
}
/** Transition handler. */
public void transition(final Role role) {
checkThread();
checkNotNull(role);
if (this.role.role() == role) {
return;
}
log.info("Transitioning to {}", role);
startTransition();
// Close the old state.
try {
this.role.stop().get();
} catch (final InterruptedException | ExecutionException e) {
throw new IllegalStateException("failed to close Raft state", e);
}
// Force state transitions to occur synchronously in order to prevent race conditions.
try {
this.role = createRole(role);
this.role.start().get();
} catch (final InterruptedException | ExecutionException e) {
throw new IllegalStateException("failed to initialize Raft state", e);
}
if (!this.role.role().active() && role.active()) {
health = HealthReport.healthy(this);
failureListeners.forEach(FailureListener::onRecovered);
}
if (this.role.role() == role) {
if (this.role.role() == Role.LEADER) {
// It is safe to assume that transition to leader is only complete after the initial entries
// are committed.
final LeaderRole leaderRole = (LeaderRole) this.role;
leaderRole.onInitialEntriesCommitted(
() -> {
if (this.role == leaderRole) { // ensure no other role change happened in between
notifyRoleChangeListeners();
// Transitioning to leader completes
// once the initial entry gets committed
completeTransition();
}
});
} else {
notifyRoleChangeListeners();
completeTransition();
}
}
}
private void startTransition() {
ongoingTransition = true;
}
private void completeTransition() {
ongoingTransition = false;
}
private void notifyRoleChangeListeners() {
try {
roleChangeListeners.forEach(l -> l.onNewRole(role.role(), getTerm()));
} catch (final Exception exception) {
log.error("Unexpected error on calling role change listeners.", exception);
}
}
/** Checks that the current thread is the state context thread. */
public void checkThread() {
threadContext.checkThread();
}
/** Creates an internal state for the given state type. */
private RaftRole createRole(final Role role) {
switch (role) {
case INACTIVE:
return new InactiveRole(this);
case PASSIVE:
return new PassiveRole(this);
case PROMOTABLE:
return new PromotableRole(this);
case FOLLOWER:
raftRoleMetrics.becomingFollower();
return new FollowerRole(this, this::createElectionTimer);
case CANDIDATE:
raftRoleMetrics.becomingCandidate();
return new CandidateRole(this);
case LEADER:
raftRoleMetrics.becomingLeader();
return new LeaderRole(this);
default:
throw new AssertionError();
}
}
private ElectionTimer createElectionTimer(final Runnable triggerElection, final Logger log) {
if (electionConfig.isPriorityElectionEnabled()) {
return new PriorityElectionTimer(
partitionConfig.getElectionTimeout(),
threadContext,
triggerElection,
log,
electionConfig.getInitialTargetPriority(),
electionConfig.getNodePriority());
} else {
return new RandomizedElectionTimer(
partitionConfig.getElectionTimeout(), threadContext, random, triggerElection, log);
}
}
/** Transitions the server to the base state for the given member type. */
public void transition(final Type type) {
switch (type) {
case ACTIVE:
if (!(role instanceof ActiveRole)) {
transition(Role.FOLLOWER);
}
break;
case PROMOTABLE:
if (role.role() != Role.PROMOTABLE) {
transition(Role.PROMOTABLE);
}
break;
case PASSIVE:
if (role.role() != Role.PASSIVE) {
transition(Role.PASSIVE);
}
break;
default:
if (role.role() != Role.INACTIVE) {
transition(Role.INACTIVE);
}
break;
}
}
@Override
public void close() {
started = false;
// Unregister protocol listeners.
unregisterHandlers(protocol);
logCompactor.close();
// Close the log.
try {
raftLog.close();
} catch (final Exception e) {
log.error("Failed to close raft log", e);
}
// Close the metastore.
try {
meta.close();
} catch (final Exception e) {
log.error("Failed to close metastore", e);
}
// Close the snapshot store.
try {
persistedSnapshotStore.close();
} catch (final Exception e) {
log.error("Failed to close snapshot store", e);
}
// close thread contexts
threadContext.close();
}
/** Unregisters server handlers on the configured protocol. */
private void unregisterHandlers(final RaftServerProtocol protocol) {
protocol.unregisterConfigureHandler();
protocol.unregisterInstallHandler();
protocol.unregisterReconfigureHandler();
protocol.unregisterTransferHandler();
protocol.unregisterAppendHandler();
protocol.unregisterPollHandler();
protocol.unregisterVoteHandler();
}
@Override
public String toString() {
return getClass().getCanonicalName();
}
/**
* Returns the commit index.
*
* @return The commit index.
*/
public long getCommitIndex() {
return commitIndex;
}
/**
* Returns the election timeout.
*
* @return The election timeout.
*/
public Duration getElectionTimeout() {
return partitionConfig.getElectionTimeout();
}
/**
* Returns the first commit index.
*
* @return The first commit index.
*/
public long getFirstCommitIndex() {
return firstCommitIndex;
}
/**
* Sets the first commit index.
*
* @param firstCommitIndex The first commit index.
*/
public void setFirstCommitIndex(final long firstCommitIndex) {
if (this.firstCommitIndex == 0) {
this.firstCommitIndex = firstCommitIndex;
log.info(
"Setting firstCommitIndex to {}. RaftServer is ready only after it has committed events upto this index",
firstCommitIndex);
}
}
/**
* Returns the heartbeat interval.
*
* @return The heartbeat interval.
*/
public Duration getHeartbeatInterval() {
return partitionConfig.getHeartbeatInterval();
}
/**
* Returns the entry validator to be called when an entry is appended.
*
* @return The entry validator.
*/
public EntryValidator getEntryValidator() {
return entryValidator;
}
/**
* Sets the entry validator to be called when an entry is appended.
*
* @param validator The entry validator.
*/
public void setEntryValidator(final EntryValidator validator) {
entryValidator = validator;
}
/**
* Returns the state last voted for candidate.
*
* @return The state last voted for candidate.
*/
public MemberId getLastVotedFor() {
return lastVotedFor;
}
/**
* Sets the state last voted for candidate.
*
* @param candidate The candidate that was voted for.
*/
public void setLastVotedFor(final MemberId candidate) {
// If we've already voted for another candidate in this term then the last voted for candidate
// cannot be overridden.
checkState(!(lastVotedFor != null && candidate != null), "Already voted for another candidate");
final DefaultRaftMember member = cluster.getMember(candidate);
checkState(member != null, "Unknown candidate: %d", candidate);
lastVotedFor = candidate;
meta.storeVote(lastVotedFor);
if (candidate != null) {
log.debug("Voted for {}", member.memberId());
} else {
log.trace("Reset last voted for");
}
}
/**
* Returns the server log.
*
* @return The server log.
*/
public RaftLog getLog() {
return raftLog;
}
/**
* Returns the cluster service.
*
* @return the cluster service
*/
public ClusterMembershipService getMembershipService() {
return membershipService;
}
/**
* Returns the server metadata store.
*
* @return The server metadata store.
*/
public MetaStore getMetaStore() {
return meta;
}
/**
* Returns the server name.
*
* @return The server name.
*/
@Override
public String getName() {
return name;
}
@Override
public HealthReport getHealthReport() {
return health;
}
/** Adds a failure listener which will be invoked when an uncaught exception occurs */
@Override
public void addFailureListener(final FailureListener listener) {
failureListeners.add(listener);
}
/** Remove a failure listener */
@Override
public void removeFailureListener(final FailureListener listener) {
failureListeners.remove(listener);
}
/**
* Returns the server protocol.
*
* @return The server protocol.
*/
public RaftServerProtocol getProtocol() {
return protocol;
}
/**
* Returns the current server state.
*
* @return The current server state.
*/
public RaftRole getRaftRole() {
return role;
}
public RaftRoleMetrics getRaftRoleMetrics() {
return raftRoleMetrics;
}
/**
* Returns the current server role.
*
* @return The current server role.
*/
public Role getRole() {
return role.role();
}
/**
* Returns the server state machine.
*
* @return The log compactor.
*/
public LogCompactor getLogCompactor() {
return logCompactor;
}
/**