-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
NodeImpl.java
3579 lines (3251 loc) · 146 KB
/
NodeImpl.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
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 com.alipay.sofa.jraft.core;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Objects;
import java.util.Set;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.stream.Collectors;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.alipay.sofa.jraft.Closure;
import com.alipay.sofa.jraft.FSMCaller;
import com.alipay.sofa.jraft.JRaftServiceFactory;
import com.alipay.sofa.jraft.JRaftUtils;
import com.alipay.sofa.jraft.Node;
import com.alipay.sofa.jraft.NodeManager;
import com.alipay.sofa.jraft.ReadOnlyService;
import com.alipay.sofa.jraft.ReplicatorGroup;
import com.alipay.sofa.jraft.Status;
import com.alipay.sofa.jraft.closure.CatchUpClosure;
import com.alipay.sofa.jraft.closure.ClosureQueue;
import com.alipay.sofa.jraft.closure.ClosureQueueImpl;
import com.alipay.sofa.jraft.closure.ReadIndexClosure;
import com.alipay.sofa.jraft.closure.SynchronizedClosure;
import com.alipay.sofa.jraft.conf.Configuration;
import com.alipay.sofa.jraft.conf.ConfigurationEntry;
import com.alipay.sofa.jraft.conf.ConfigurationManager;
import com.alipay.sofa.jraft.entity.Ballot;
import com.alipay.sofa.jraft.entity.EnumOutter;
import com.alipay.sofa.jraft.entity.LeaderChangeContext;
import com.alipay.sofa.jraft.entity.LogEntry;
import com.alipay.sofa.jraft.entity.LogId;
import com.alipay.sofa.jraft.entity.NodeId;
import com.alipay.sofa.jraft.entity.PeerId;
import com.alipay.sofa.jraft.entity.RaftOutter;
import com.alipay.sofa.jraft.entity.Task;
import com.alipay.sofa.jraft.entity.UserLog;
import com.alipay.sofa.jraft.error.LogIndexOutOfBoundsException;
import com.alipay.sofa.jraft.error.LogNotFoundException;
import com.alipay.sofa.jraft.error.OverloadException;
import com.alipay.sofa.jraft.error.RaftError;
import com.alipay.sofa.jraft.error.RaftException;
import com.alipay.sofa.jraft.option.BallotBoxOptions;
import com.alipay.sofa.jraft.option.BootstrapOptions;
import com.alipay.sofa.jraft.option.FSMCallerOptions;
import com.alipay.sofa.jraft.option.LogManagerOptions;
import com.alipay.sofa.jraft.option.NodeOptions;
import com.alipay.sofa.jraft.option.RaftMetaStorageOptions;
import com.alipay.sofa.jraft.option.RaftOptions;
import com.alipay.sofa.jraft.option.ReadOnlyOption;
import com.alipay.sofa.jraft.option.ReadOnlyServiceOptions;
import com.alipay.sofa.jraft.option.ReplicatorGroupOptions;
import com.alipay.sofa.jraft.option.SnapshotExecutorOptions;
import com.alipay.sofa.jraft.rpc.RaftClientService;
import com.alipay.sofa.jraft.rpc.RaftServerService;
import com.alipay.sofa.jraft.rpc.RpcRequestClosure;
import com.alipay.sofa.jraft.rpc.RpcRequests.AppendEntriesRequest;
import com.alipay.sofa.jraft.rpc.RpcRequests.AppendEntriesResponse;
import com.alipay.sofa.jraft.rpc.RpcRequests.InstallSnapshotRequest;
import com.alipay.sofa.jraft.rpc.RpcRequests.InstallSnapshotResponse;
import com.alipay.sofa.jraft.rpc.RpcRequests.ReadIndexRequest;
import com.alipay.sofa.jraft.rpc.RpcRequests.ReadIndexResponse;
import com.alipay.sofa.jraft.rpc.RpcRequests.RequestVoteRequest;
import com.alipay.sofa.jraft.rpc.RpcRequests.RequestVoteResponse;
import com.alipay.sofa.jraft.rpc.RpcRequests.TimeoutNowRequest;
import com.alipay.sofa.jraft.rpc.RpcRequests.TimeoutNowResponse;
import com.alipay.sofa.jraft.rpc.RpcResponseClosure;
import com.alipay.sofa.jraft.rpc.RpcResponseClosureAdapter;
import com.alipay.sofa.jraft.rpc.impl.core.DefaultRaftClientService;
import com.alipay.sofa.jraft.storage.LogManager;
import com.alipay.sofa.jraft.storage.LogStorage;
import com.alipay.sofa.jraft.storage.RaftMetaStorage;
import com.alipay.sofa.jraft.storage.SnapshotExecutor;
import com.alipay.sofa.jraft.storage.impl.LogManagerImpl;
import com.alipay.sofa.jraft.storage.snapshot.SnapshotExecutorImpl;
import com.alipay.sofa.jraft.util.Describer;
import com.alipay.sofa.jraft.util.DisruptorBuilder;
import com.alipay.sofa.jraft.util.DisruptorMetricSet;
import com.alipay.sofa.jraft.util.JRaftServiceLoader;
import com.alipay.sofa.jraft.util.JRaftSignalHandler;
import com.alipay.sofa.jraft.util.LogExceptionHandler;
import com.alipay.sofa.jraft.util.NamedThreadFactory;
import com.alipay.sofa.jraft.util.OnlyForTest;
import com.alipay.sofa.jraft.util.Platform;
import com.alipay.sofa.jraft.util.RepeatedTimer;
import com.alipay.sofa.jraft.util.Requires;
import com.alipay.sofa.jraft.util.RpcFactoryHelper;
import com.alipay.sofa.jraft.util.SignalHelper;
import com.alipay.sofa.jraft.util.SystemPropertyUtil;
import com.alipay.sofa.jraft.util.ThreadId;
import com.alipay.sofa.jraft.util.ThreadPoolsFactory;
import com.alipay.sofa.jraft.util.Utils;
import com.alipay.sofa.jraft.util.concurrent.LongHeldDetectingReadWriteLock;
import com.alipay.sofa.jraft.util.timer.RaftTimerFactory;
import com.google.protobuf.Message;
import com.lmax.disruptor.BlockingWaitStrategy;
import com.lmax.disruptor.EventFactory;
import com.lmax.disruptor.EventHandler;
import com.lmax.disruptor.EventTranslator;
import com.lmax.disruptor.RingBuffer;
import com.lmax.disruptor.dsl.Disruptor;
import com.lmax.disruptor.dsl.ProducerType;
/**
* The raft replica node implementation.
*
* @author boyan (boyan@alibaba-inc.com)
*
* 2018-Apr-03 4:26:51 PM
*/
public class NodeImpl implements Node, RaftServerService {
private static final Logger LOG = LoggerFactory
.getLogger(NodeImpl.class);
static {
try {
if (SignalHelper.supportSignal()) {
// TODO support windows signal
if (!Platform.isWindows()) {
final List<JRaftSignalHandler> handlers = JRaftServiceLoader.load(JRaftSignalHandler.class) //
.sort();
SignalHelper.addSignal(SignalHelper.SIG_USR2, handlers);
}
}
} catch (final Throwable t) {
LOG.error("Fail to add signal.", t);
}
}
public final static RaftTimerFactory TIMER_FACTORY = JRaftUtils
.raftTimerFactory();
public static final AtomicInteger GLOBAL_NUM_NODES = new AtomicInteger(
0);
/** Internal states */
private final ReadWriteLock readWriteLock = new NodeReadWriteLock(
this);
protected final Lock writeLock = this.readWriteLock
.writeLock();
protected final Lock readLock = this.readWriteLock
.readLock();
private volatile State state;
private volatile CountDownLatch shutdownLatch;
private long currTerm;
private volatile long lastLeaderTimestamp;
private PeerId leaderId = new PeerId();
private PeerId votedId;
private final Ballot voteCtx = new Ballot();
private final Ballot prevVoteCtx = new Ballot();
private ConfigurationEntry conf;
private StopTransferArg stopTransferArg;
/** Raft group and node options and identifier */
private final String groupId;
private NodeOptions options;
private RaftOptions raftOptions;
private final PeerId serverId;
/** Other services */
private final ConfigurationCtx confCtx;
private LogStorage logStorage;
private RaftMetaStorage metaStorage;
private ClosureQueue closureQueue;
private ConfigurationManager configManager;
private LogManager logManager;
private FSMCaller fsmCaller;
private BallotBox ballotBox;
private SnapshotExecutor snapshotExecutor;
private ReplicatorGroup replicatorGroup;
private final List<Closure> shutdownContinuations = new ArrayList<>();
private RaftClientService rpcService;
private ReadOnlyService readOnlyService;
/** Timers */
private Scheduler timerManager;
private RepeatedTimer electionTimer;
private RepeatedTimer voteTimer;
private RepeatedTimer stepDownTimer;
private RepeatedTimer snapshotTimer;
private ScheduledFuture<?> transferTimer;
private ThreadId wakingCandidate;
/** Disruptor to run node service */
private Disruptor<LogEntryAndClosure> applyDisruptor;
private RingBuffer<LogEntryAndClosure> applyQueue;
/** Metrics */
private NodeMetrics metrics;
private NodeId nodeId;
private JRaftServiceFactory serviceFactory;
/** ReplicatorStateListeners */
private final CopyOnWriteArrayList<Replicator.ReplicatorStateListener> replicatorStateListeners = new CopyOnWriteArrayList<>();
/** Node's target leader election priority value */
private volatile int targetPriority;
/** The number of elections time out for current node */
private volatile int electionTimeoutCounter;
private static class NodeReadWriteLock extends LongHeldDetectingReadWriteLock {
static final long MAX_BLOCKING_MS_TO_REPORT = SystemPropertyUtil.getLong(
"jraft.node.detecting.lock.max_blocking_ms_to_report", -1);
private final Node node;
public NodeReadWriteLock(final Node node) {
super(MAX_BLOCKING_MS_TO_REPORT, TimeUnit.MILLISECONDS);
this.node = node;
}
@Override
public void report(final AcquireMode acquireMode, final Thread heldThread,
final Collection<Thread> queuedThreads, final long blockedNanos) {
final long blockedMs = TimeUnit.NANOSECONDS.toMillis(blockedNanos);
LOG.warn(
"Raft-Node-Lock report: currentThread={}, acquireMode={}, heldThread={}, queuedThreads={}, blockedMs={}.",
Thread.currentThread(), acquireMode, heldThread, queuedThreads, blockedMs);
final NodeMetrics metrics = this.node.getNodeMetrics();
if (metrics != null) {
metrics.recordLatency("node-lock-blocked", blockedMs);
}
}
}
/**
* Node service event.
*
* @author boyan (boyan@alibaba-inc.com)
*
* 2018-Apr-03 4:29:55 PM
*/
private static class LogEntryAndClosure {
LogEntry entry;
Closure done;
long expectedTerm;
CountDownLatch shutdownLatch;
public void reset() {
this.entry = null;
this.done = null;
this.expectedTerm = 0;
this.shutdownLatch = null;
}
}
private static class LogEntryAndClosureFactory implements EventFactory<LogEntryAndClosure> {
@Override
public LogEntryAndClosure newInstance() {
return new LogEntryAndClosure();
}
}
/**
* Event handler.
*
* @author boyan (boyan@alibaba-inc.com)
*
* 2018-Apr-03 4:30:07 PM
*/
private class LogEntryAndClosureHandler implements EventHandler<LogEntryAndClosure> {
// task list for batch
private final List<LogEntryAndClosure> tasks = new ArrayList<>(NodeImpl.this.raftOptions.getApplyBatch());
@Override
public void onEvent(final LogEntryAndClosure event, final long sequence, final boolean endOfBatch)
throws Exception {
if (event.shutdownLatch != null) {
if (!this.tasks.isEmpty()) {
executeApplyingTasks(this.tasks);
reset();
}
final int num = GLOBAL_NUM_NODES.decrementAndGet();
LOG.info("The number of active nodes decrement to {}.", num);
event.shutdownLatch.countDown();
return;
}
this.tasks.add(event);
if (this.tasks.size() >= NodeImpl.this.raftOptions.getApplyBatch() || endOfBatch) {
executeApplyingTasks(this.tasks);
reset();
}
}
private void reset() {
for (final LogEntryAndClosure task : this.tasks) {
task.reset();
}
this.tasks.clear();
}
}
/**
* Configuration commit context.
*
* @author boyan (boyan@alibaba-inc.com)
*
* 2018-Apr-03 4:29:38 PM
*/
private static class ConfigurationCtx {
enum Stage {
STAGE_NONE, // none stage
STAGE_CATCHING_UP, // the node is catching-up
STAGE_JOINT, // joint stage
STAGE_STABLE // stable stage
}
final NodeImpl node;
Stage stage;
// Peers change times
int nchanges;
long version;
// peers
List<PeerId> newPeers = new ArrayList<>();
List<PeerId> oldPeers = new ArrayList<>();
List<PeerId> addingPeers = new ArrayList<>();
// learners
List<PeerId> newLearners = new ArrayList<>();
List<PeerId> oldLearners = new ArrayList<>();
Closure done;
public ConfigurationCtx(final NodeImpl node) {
super();
this.node = node;
this.stage = Stage.STAGE_NONE;
this.version = 0;
this.done = null;
}
/**
* Start change configuration.
*/
void start(final Configuration oldConf, final Configuration newConf, final Closure done) {
if (isBusy()) {
if (done != null) {
ThreadPoolsFactory.runClosureInThread(this.node.getGroupId(), done, new Status(RaftError.EBUSY,
"Already in busy stage."));
}
throw new IllegalStateException("Busy stage");
}
if (this.done != null) {
if (done != null) {
ThreadPoolsFactory.runClosureInThread(this.node.getGroupId(), done, new Status(RaftError.EINVAL,
"Already have done closure."));
}
throw new IllegalArgumentException("Already have done closure");
}
this.done = done;
this.stage = Stage.STAGE_CATCHING_UP;
this.oldPeers = oldConf.listPeers();
this.newPeers = newConf.listPeers();
this.oldLearners = oldConf.listLearners();
this.newLearners = newConf.listLearners();
final Configuration adding = new Configuration();
final Configuration removing = new Configuration();
newConf.diff(oldConf, adding, removing);
this.nchanges = adding.size() + removing.size();
addNewLearners();
if (adding.isEmpty()) {
nextStage();
return;
}
addNewPeers(adding);
}
private void addNewPeers(final Configuration adding) {
this.addingPeers = adding.listPeers();
LOG.info("Adding peers: {}.", this.addingPeers);
for (final PeerId newPeer : this.addingPeers) {
if (!this.node.replicatorGroup.addReplicator(newPeer)) {
LOG.error("Node {} start the replicator failed, peer={}.", this.node.getNodeId(), newPeer);
onCaughtUp(this.version, newPeer, false);
return;
}
final OnCaughtUp caughtUp = new OnCaughtUp(this.node, this.node.currTerm, newPeer, this.version);
final long dueTime = Utils.nowMs() + this.node.options.getElectionTimeoutMs();
if (!this.node.replicatorGroup.waitCaughtUp(this.node.getGroupId(), newPeer,
this.node.options.getCatchupMargin(), dueTime, caughtUp)) {
LOG.error("Node {} waitCaughtUp, peer={}.", this.node.getNodeId(), newPeer);
onCaughtUp(this.version, newPeer, false);
return;
}
}
}
private void addNewLearners() {
final Set<PeerId> addingLearners = new HashSet<>(this.newLearners);
addingLearners.removeAll(this.oldLearners);
LOG.info("Adding learners: {}.", addingLearners);
for (final PeerId newLearner : addingLearners) {
if (!this.node.replicatorGroup.addReplicator(newLearner, ReplicatorType.Learner)) {
LOG.error("Node {} start the learner replicator failed, peer={}.", this.node.getNodeId(),
newLearner);
}
}
}
void onCaughtUp(final long version, final PeerId peer, final boolean success) {
if (version != this.version) {
LOG.warn("Ignore onCaughtUp message, mismatch configuration context version, expect {}, but is {}.",
this.version, version);
return;
}
Requires.requireTrue(this.stage == Stage.STAGE_CATCHING_UP, "Stage is not in STAGE_CATCHING_UP");
if (success) {
this.addingPeers.remove(peer);
if (this.addingPeers.isEmpty()) {
nextStage();
return;
}
return;
}
LOG.warn("Node {} fail to catch up peer {} when trying to change peers from {} to {}.",
this.node.getNodeId(), peer, this.oldPeers, this.newPeers);
reset(new Status(RaftError.ECATCHUP, "Peer %s failed to catch up.", peer));
}
void reset() {
reset(null);
}
void reset(final Status st) {
if (st != null && st.isOk()) {
this.node.stopReplicator(this.newPeers, this.oldPeers);
this.node.stopReplicator(this.newLearners, this.oldLearners);
} else {
this.node.stopReplicator(this.oldPeers, this.newPeers);
this.node.stopReplicator(this.oldLearners, this.newLearners);
}
clearPeers();
clearLearners();
this.version++;
this.stage = Stage.STAGE_NONE;
this.nchanges = 0;
if (this.done != null) {
ThreadPoolsFactory.runClosureInThread(this.node.getGroupId(), this.done, st != null ? st : new Status(
RaftError.EPERM, "Leader stepped down."));
this.done = null;
}
}
private void clearLearners() {
this.newLearners.clear();
this.oldLearners.clear();
}
private void clearPeers() {
this.newPeers.clear();
this.oldPeers.clear();
this.addingPeers.clear();
}
/**
* Invoked when this node becomes the leader, write a configuration change log as the first log.
*/
void flush(final Configuration conf, final Configuration oldConf) {
Requires.requireTrue(!isBusy(), "Flush when busy");
this.newPeers = conf.listPeers();
this.newLearners = conf.listLearners();
if (oldConf == null || oldConf.isEmpty()) {
this.stage = Stage.STAGE_STABLE;
this.oldPeers = this.newPeers;
this.oldLearners = this.newLearners;
} else {
this.stage = Stage.STAGE_JOINT;
this.oldPeers = oldConf.listPeers();
this.oldLearners = oldConf.listLearners();
}
this.node.unsafeApplyConfiguration(conf, oldConf == null || oldConf.isEmpty() ? null : oldConf, true);
}
void nextStage() {
Requires.requireTrue(isBusy(), "Not in busy stage");
switch (this.stage) {
case STAGE_CATCHING_UP:
if (this.nchanges > 0) {
this.stage = Stage.STAGE_JOINT;
this.node.unsafeApplyConfiguration(new Configuration(this.newPeers, this.newLearners),
new Configuration(this.oldPeers), false);
return;
}
case STAGE_JOINT:
this.stage = Stage.STAGE_STABLE;
this.node.unsafeApplyConfiguration(new Configuration(this.newPeers, this.newLearners), null, false);
break;
case STAGE_STABLE:
final boolean shouldStepDown = !this.newPeers.contains(this.node.serverId);
reset(new Status());
if (shouldStepDown) {
this.node.stepDown(this.node.currTerm, true, new Status(RaftError.ELEADERREMOVED,
"This node was removed."));
}
break;
case STAGE_NONE:
// noinspection ConstantConditions
Requires.requireTrue(false, "Can't reach here");
break;
}
}
boolean isBusy() {
return this.stage != Stage.STAGE_NONE;
}
}
public NodeImpl() {
this(null, null);
}
public NodeImpl(final String groupId, final PeerId serverId) {
super();
if (groupId != null) {
Utils.verifyGroupId(groupId);
}
this.groupId = groupId;
this.serverId = serverId != null ? serverId.copy() : null;
this.state = State.STATE_UNINITIALIZED;
this.currTerm = 0;
updateLastLeaderTimestamp(Utils.monotonicMs());
this.confCtx = new ConfigurationCtx(this);
this.wakingCandidate = null;
final int num = GLOBAL_NUM_NODES.incrementAndGet();
LOG.info("The number of active nodes increment to {}.", num);
}
private boolean initSnapshotStorage() {
if (StringUtils.isEmpty(this.options.getSnapshotUri())) {
LOG.warn("Do not set snapshot uri, ignore initSnapshotStorage.");
return true;
}
this.snapshotExecutor = new SnapshotExecutorImpl();
final SnapshotExecutorOptions opts = new SnapshotExecutorOptions();
opts.setFsmCaller(this.fsmCaller);
opts.setNode(this);
opts.setLogManager(this.logManager);
opts.setAddr(this.serverId != null ? this.serverId.getEndpoint() : null);
opts.setInitTerm(this.currTerm);
opts.setFilterBeforeCopyRemote(this.options.isFilterBeforeCopyRemote());
// get snapshot throttle
opts.setSnapshotThrottle(this.options.getSnapshotThrottle());
return this.snapshotExecutor.init(opts);
}
private boolean initLogStorage() {
Requires.requireNonNull(this.fsmCaller, "Null fsm caller");
this.logStorage = this.serviceFactory.createLogStorage(this.options.getLogUri(), this.raftOptions);
this.logManager = new LogManagerImpl();
final LogManagerOptions opts = new LogManagerOptions();
opts.setGroupId(this.groupId);
opts.setLogEntryCodecFactory(this.serviceFactory.createLogEntryCodecFactory());
opts.setLogStorage(this.logStorage);
opts.setConfigurationManager(this.configManager);
opts.setFsmCaller(this.fsmCaller);
opts.setNodeMetrics(this.metrics);
opts.setDisruptorBufferSize(this.raftOptions.getDisruptorBufferSize());
opts.setRaftOptions(this.raftOptions);
return this.logManager.init(opts);
}
private boolean initMetaStorage() {
this.metaStorage = this.serviceFactory.createRaftMetaStorage(this.options.getRaftMetaUri(), this.raftOptions);
RaftMetaStorageOptions opts = new RaftMetaStorageOptions();
opts.setNode(this);
if (!this.metaStorage.init(opts)) {
LOG.error("Node {} init meta storage failed, uri={}.", this.serverId, this.options.getRaftMetaUri());
return false;
}
this.currTerm = this.metaStorage.getTerm();
this.votedId = this.metaStorage.getVotedFor().copy();
return true;
}
private void handleSnapshotTimeout() {
this.writeLock.lock();
try {
if (!this.state.isActive()) {
return;
}
} finally {
this.writeLock.unlock();
}
// do_snapshot in another thread to avoid blocking the timer thread.
ThreadPoolsFactory.runInThread(this.groupId, () -> doSnapshot(null, false));
}
private void handleElectionTimeout() {
boolean doUnlock = true;
this.writeLock.lock();
try {
if (this.state != State.STATE_FOLLOWER) {
return;
}
if (isCurrentLeaderValid()) {
return;
}
resetLeaderId(PeerId.emptyPeer(), new Status(RaftError.ERAFTTIMEDOUT, "Lost connection from leader %s.",
this.leaderId));
// Judge whether to launch a election.
if (!allowLaunchElection()) {
return;
}
doUnlock = false;
preVote();
} finally {
if (doUnlock) {
this.writeLock.unlock();
}
}
}
/**
* Whether to allow for launching election or not by comparing node's priority with target
* priority. And at the same time, if next leader is not elected until next election
* timeout, it decays its local target priority exponentially.
*
* @return Whether current node will launch election or not.
*/
@SuppressWarnings("NonAtomicOperationOnVolatileField")
private boolean allowLaunchElection() {
// Priority 0 is a special value so that a node will never participate in election.
if (this.serverId.isPriorityNotElected()) {
LOG.warn("Node {} will never participate in election, because it's priority={}.", getNodeId(),
this.serverId.getPriority());
return false;
}
// If this nodes disable priority election, then it can make a election.
if (this.serverId.isPriorityDisabled()) {
return true;
}
// If current node's priority < target_priority, it does not initiate leader,
// election and waits for the next election timeout.
if (this.serverId.getPriority() < this.targetPriority) {
this.electionTimeoutCounter++;
// If next leader is not elected until next election timeout, it
// decays its local target priority exponentially.
if (this.electionTimeoutCounter > 1) {
decayTargetPriority();
this.electionTimeoutCounter = 0;
}
if (this.electionTimeoutCounter == 1) {
LOG.debug("Node {} does not initiate leader election and waits for the next election timeout.",
getNodeId());
return false;
}
}
return this.serverId.getPriority() >= this.targetPriority;
}
/**
* Decay targetPriority value based on gap value.
*/
@SuppressWarnings("NonAtomicOperationOnVolatileField")
private void decayTargetPriority() {
// Default Gap value should be bigger than 10.
final int decayPriorityGap = Math.max(this.options.getDecayPriorityGap(), 10);
final int gap = Math.max(decayPriorityGap, (this.targetPriority / 5));
final int prevTargetPriority = this.targetPriority;
this.targetPriority = Math.max(ElectionPriority.MinValue, (this.targetPriority - gap));
LOG.info("Node {} priority decay, from: {}, to: {}.", getNodeId(), prevTargetPriority, this.targetPriority);
}
/**
* Check and set configuration for node.At the same time, if configuration is changed,
* then compute and update the target priority value.
*
* @param inLock whether the writeLock has already been locked in other place.
*
*/
private void checkAndSetConfiguration(final boolean inLock) {
if (!inLock) {
this.writeLock.lock();
}
try {
final ConfigurationEntry prevConf = this.conf;
this.conf = this.logManager.checkAndSetConfiguration(prevConf);
if (this.conf != prevConf) {
// Update target priority value
final int prevTargetPriority = this.targetPriority;
this.targetPriority = getMaxPriorityOfNodes(this.conf.getConf().getPeers());
if (prevTargetPriority != this.targetPriority) {
LOG.info("Node {} target priority value has changed from: {}, to: {}.", getNodeId(),
prevTargetPriority, this.targetPriority);
}
this.electionTimeoutCounter = 0;
}
} finally {
if (!inLock) {
this.writeLock.unlock();
}
}
}
/**
* Get max priority value for all nodes in the same Raft group, and update current node's target priority value.
*
* @param peerIds peer nodes in the same Raft group
*
*/
private int getMaxPriorityOfNodes(final List<PeerId> peerIds) {
Requires.requireNonNull(peerIds, "Null peer list");
int maxPriority = Integer.MIN_VALUE;
for (final PeerId peerId : peerIds) {
final int priorityVal = peerId.getPriority();
maxPriority = Math.max(priorityVal, maxPriority);
}
return maxPriority;
}
private boolean initFSMCaller(final LogId bootstrapId) {
if (this.fsmCaller == null) {
LOG.error("Fail to init fsm caller, null instance, bootstrapId={}.", bootstrapId);
return false;
}
this.closureQueue = new ClosureQueueImpl(this.groupId);
final FSMCallerOptions opts = new FSMCallerOptions();
opts.setAfterShutdown(status -> afterShutdown());
opts.setLogManager(this.logManager);
opts.setFsm(this.options.getFsm());
opts.setClosureQueue(this.closureQueue);
opts.setNode(this);
opts.setBootstrapId(bootstrapId);
opts.setDisruptorBufferSize(this.raftOptions.getDisruptorBufferSize());
return this.fsmCaller.init(opts);
}
private static class BootstrapStableClosure extends LogManager.StableClosure {
private final SynchronizedClosure done = new SynchronizedClosure();
public BootstrapStableClosure() {
super(null);
}
public Status await() throws InterruptedException {
return this.done.await();
}
@Override
public void run(final Status status) {
this.done.run(status);
}
}
public boolean bootstrap(final BootstrapOptions opts) throws InterruptedException {
if (opts.getLastLogIndex() > 0 && (opts.getGroupConf().isEmpty() || opts.getFsm() == null)) {
LOG.error("Invalid arguments for bootstrap, groupConf={}, fsm={}, lastLogIndex={}.", opts.getGroupConf(),
opts.getFsm(), opts.getLastLogIndex());
return false;
}
if (opts.getGroupConf().isEmpty()) {
LOG.error("Bootstrapping an empty node makes no sense.");
return false;
}
Requires.requireNonNull(opts.getServiceFactory(), "Null jraft service factory");
this.serviceFactory = opts.getServiceFactory();
// Term is not an option since changing it is very dangerous
final long bootstrapLogTerm = opts.getLastLogIndex() > 0 ? 1 : 0;
final LogId bootstrapId = new LogId(opts.getLastLogIndex(), bootstrapLogTerm);
this.options = new NodeOptions();
this.raftOptions = this.options.getRaftOptions();
this.metrics = new NodeMetrics(opts.isEnableMetrics());
this.options.setFsm(opts.getFsm());
this.options.setLogUri(opts.getLogUri());
this.options.setRaftMetaUri(opts.getRaftMetaUri());
this.options.setSnapshotUri(opts.getSnapshotUri());
this.configManager = new ConfigurationManager();
// Create fsmCaller at first as logManager needs it to report error
this.fsmCaller = new FSMCallerImpl();
if (!initLogStorage()) {
LOG.error("Fail to init log storage.");
return false;
}
if (!initMetaStorage()) {
LOG.error("Fail to init meta storage.");
return false;
}
if (this.currTerm == 0) {
this.currTerm = 1;
if (!this.metaStorage.setTermAndVotedFor(1, new PeerId())) {
LOG.error("Fail to set term.");
return false;
}
}
if (opts.getFsm() != null && !initFSMCaller(bootstrapId)) {
LOG.error("Fail to init fsm caller.");
return false;
}
final LogEntry entry = new LogEntry(EnumOutter.EntryType.ENTRY_TYPE_CONFIGURATION);
entry.getId().setTerm(this.currTerm);
entry.setPeers(opts.getGroupConf().listPeers());
entry.setLearners(opts.getGroupConf().listLearners());
final List<LogEntry> entries = new ArrayList<>();
entries.add(entry);
final BootstrapStableClosure bootstrapDone = new BootstrapStableClosure();
this.logManager.appendEntries(entries, bootstrapDone);
if (!bootstrapDone.await().isOk()) {
LOG.error("Fail to append configuration.");
return false;
}
if (opts.getLastLogIndex() > 0) {
if (!initSnapshotStorage()) {
LOG.error("Fail to init snapshot storage.");
return false;
}
final SynchronizedClosure snapshotDone = new SynchronizedClosure();
this.snapshotExecutor.doSnapshot(snapshotDone);
if (!snapshotDone.await().isOk()) {
LOG.error("Fail to save snapshot, status={}.", snapshotDone.getStatus());
return false;
}
}
if (this.logManager.getFirstLogIndex() != opts.getLastLogIndex() + 1) {
throw new IllegalStateException("First and last log index mismatch");
}
if (opts.getLastLogIndex() > 0) {
if (this.logManager.getLastLogIndex() != opts.getLastLogIndex()) {
throw new IllegalStateException("Last log index mismatch");
}
} else {
if (this.logManager.getLastLogIndex() != opts.getLastLogIndex() + 1) {
throw new IllegalStateException("Last log index mismatch");
}
}
return true;
}
private int heartbeatTimeout(final int electionTimeout) {
return Math.max(electionTimeout / this.raftOptions.getElectionHeartbeatFactor(), 10);
}
private int randomTimeout(final int timeoutMs) {
return ThreadLocalRandom.current().nextInt(timeoutMs, timeoutMs + this.raftOptions.getMaxElectionDelayMs());
}
@Override
public boolean init(final NodeOptions opts) {
Requires.requireNonNull(opts, "Null node options");
Requires.requireNonNull(opts.getRaftOptions(), "Null raft options");
Requires.requireNonNull(opts.getServiceFactory(), "Null jraft service factory");
this.serviceFactory = opts.getServiceFactory();
this.options = opts;
this.raftOptions = opts.getRaftOptions();
this.metrics = new NodeMetrics(opts.isEnableMetrics());
this.serverId.setPriority(opts.getElectionPriority());
this.electionTimeoutCounter = 0;
if (this.serverId.getIp().equals(Utils.IP_ANY)) {
LOG.error("Node can't started from IP_ANY.");
return false;
}
if (!NodeManager.getInstance().serverExists(this.serverId.getEndpoint())) {
LOG.error("No RPC server attached to, did you forget to call addService?");
return false;
}
if (this.options.getAppendEntriesExecutors() == null) {
this.options.setAppendEntriesExecutors(Utils.getDefaultAppendEntriesExecutor());
}
this.timerManager = TIMER_FACTORY.getRaftScheduler(this.options.isSharedTimerPool(),
this.options.getTimerPoolSize(), "JRaft-Node-ScheduleThreadPool");
// Init timers
final String suffix = getNodeId().toString();
String name = "JRaft-VoteTimer-" + suffix;
this.voteTimer = new RepeatedTimer(name, this.options.getElectionTimeoutMs(), TIMER_FACTORY.getVoteTimer(
this.options.isSharedVoteTimer(), name)) {
@Override
protected void onTrigger() {
handleVoteTimeout();
}
@Override
protected int adjustTimeout(final int timeoutMs) {
return randomTimeout(timeoutMs);
}
};
name = "JRaft-ElectionTimer-" + suffix;
this.electionTimer = new RepeatedTimer(name, this.options.getElectionTimeoutMs(),
TIMER_FACTORY.getElectionTimer(this.options.isSharedElectionTimer(), name)) {
@Override
protected void onTrigger() {
handleElectionTimeout();
}
@Override
protected int adjustTimeout(final int timeoutMs) {
return randomTimeout(timeoutMs);
}
};
name = "JRaft-StepDownTimer-" + suffix;
this.stepDownTimer = new RepeatedTimer(name, this.options.getElectionTimeoutMs() >> 1,
TIMER_FACTORY.getStepDownTimer(this.options.isSharedStepDownTimer(), name)) {
@Override
protected void onTrigger() {
handleStepDownTimeout();
}
};
name = "JRaft-SnapshotTimer-" + suffix;
this.snapshotTimer = new RepeatedTimer(name, this.options.getSnapshotIntervalSecs() * 1000,
TIMER_FACTORY.getSnapshotTimer(this.options.isSharedSnapshotTimer(), name)) {
private volatile boolean firstSchedule = true;
@Override
protected void onTrigger() {
handleSnapshotTimeout();
}
@Override
protected int adjustTimeout(final int timeoutMs) {
if (!this.firstSchedule) {
return timeoutMs;
}
// Randomize the first snapshot trigger timeout
this.firstSchedule = false;
if (timeoutMs > 0) {
int half = timeoutMs / 2;
return half + ThreadLocalRandom.current().nextInt(half);
} else {
return timeoutMs;
}
}
};
this.configManager = new ConfigurationManager();
this.applyDisruptor = DisruptorBuilder.<LogEntryAndClosure> newInstance() //
.setRingBufferSize(this.raftOptions.getDisruptorBufferSize()) //
.setEventFactory(new LogEntryAndClosureFactory()) //
.setThreadFactory(new NamedThreadFactory("JRaft-NodeImpl-Disruptor-", true)) //
.setProducerType(ProducerType.MULTI) //
.setWaitStrategy(new BlockingWaitStrategy()) //
.build();
this.applyDisruptor.handleEventsWith(new LogEntryAndClosureHandler());
this.applyDisruptor.setDefaultExceptionHandler(new LogExceptionHandler<Object>(getClass().getSimpleName()));
this.applyQueue = this.applyDisruptor.start();
if (this.metrics.getMetricRegistry() != null) {
this.metrics.getMetricRegistry().register("jraft-node-impl-disruptor",
new DisruptorMetricSet(this.applyQueue));