-
Notifications
You must be signed in to change notification settings - Fork 35
/
Copy pathwa_raft_server.erl
2668 lines (2400 loc) · 153 KB
/
wa_raft_server.erl
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 (c) Meta Platforms, Inc. and affiliates. All rights reserved.
%%%
%%% This source code is licensed under the Apache 2.0 license found in
%%% the LICENSE file in the root directory of this source tree.
%%%
%%% This module implements RPC of raft consensus protocol. See raft spec
%%% on https://raft.github.io/. A wa_raft instance is a participant in
%%% a consensus group. Each participant plays a certain role (follower,
%%% leader or candidate). The mission of a consensus group is to
%%% implement a replicated state machine in a distributed cluster.
-module(wa_raft_server).
-compile(warn_missing_spec_all).
-behaviour(gen_statem).
%%------------------------------------------------------------------------------
%% RAFT Server - OTP Supervision
%%------------------------------------------------------------------------------
-export([
child_spec/1,
start_link/1
]).
%%------------------------------------------------------------------------------
%% RAFT Server - Public APIs - RAFT Cluster Configuration
%%------------------------------------------------------------------------------
-export([
latest_config_version/0
]).
%% Inspection of cluster configuration
-export([
get_config_version/1,
get_config_members/1,
get_config_witnesses/1
]).
%% Creation and modification of cluster configuration
-export([
make_config/0,
make_config/1,
make_config/2
]).
%% Modification of cluster configuration
-export([
set_config_members/2,
set_config_members/3
]).
%%------------------------------------------------------------------------------
%% RAFT Server - Public APIs
%%------------------------------------------------------------------------------
-export([
status/1,
status/2,
membership/1
]).
%%------------------------------------------------------------------------------
%% RAFT Server - Internal APIs - Local Options
%%------------------------------------------------------------------------------
-export([
default_name/2,
registered_name/2
]).
%%------------------------------------------------------------------------------
%% RAFT Server - Internal APIs - RPC Handling
%%------------------------------------------------------------------------------
-export([
make_rpc/3,
parse_rpc/2
]).
%%------------------------------------------------------------------------------
%% RAFT Server - Internal APIs - Commands
%%------------------------------------------------------------------------------
-export([
commit/2,
read/2,
snapshot_available/3,
adjust_membership/3,
adjust_membership/4,
promote/2,
promote/3,
promote/4,
resign/1,
handover/1,
handover/2,
handover_candidates/1,
disable/2,
enable/1
]).
%%------------------------------------------------------------------------------
%% RAFT Server - State Machine Implementation
%%------------------------------------------------------------------------------
%% General callbacks
-export([
init/1,
callback_mode/0,
terminate/3
]).
%% State-specific callbacks
-export([
stalled/3,
leader/3,
follower/3,
candidate/3,
disabled/3,
witness/3
]).
%%------------------------------------------------------------------------------
%% RAFT Server - Test Exports
%%------------------------------------------------------------------------------
-ifdef(TEST).
-export([
compute_quorum/3,
config/1,
max_index_to_apply/3,
adjust_config/3
]).
-endif.
%%------------------------------------------------------------------------------
%% RAFT Server - Public Types
%%------------------------------------------------------------------------------
-export_type([
state/0,
config/0,
config_all/0,
membership/0,
status/0
]).
%%------------------------------------------------------------------------------
-include_lib("kernel/include/logger.hrl").
-include("wa_raft.hrl").
-include("wa_raft_rpc.hrl").
%%------------------------------------------------------------------------------
%% Section 5.2. Randomized election timeout for fast election and to avoid split votes
-define(ELECTION_TIMEOUT(State), {state_timeout, random_election_timeout(State), election}).
%% Timeout in milliseconds before the next heartbeat is to be sent by a RAFT leader with no pending log entries
-define(HEARTBEAT_TIMEOUT(State), {state_timeout, ?RAFT_HEARTBEAT_INTERVAL(State#raft_state.application), heartbeat}).
%% Timeout in milliseconds before the next heartbeat is to be sent by a RAFT leader with pending log entries
-define(COMMIT_BATCH_TIMEOUT(State), {state_timeout, ?RAFT_COMMIT_BATCH_INTERVAL(State#raft_state.application), batch_commit}).
%%------------------------------------------------------------------------------
%% RAFT Server - Public Types
%%------------------------------------------------------------------------------
-type state() ::
stalled |
leader |
follower |
candidate |
disabled |
witness.
-type peer() :: {Name :: atom(), Node :: node()}.
-type membership() :: [peer()].
-opaque config() :: config_v1().
-opaque config_all() :: config_v1().
-type config_v1() ::
#{
version := 1,
membership => membership(),
witness => membership()
}.
-type status() :: [status_element()].
-type status_element() ::
{state, state()}
| {id, atom()}
| {peers, [{atom(), {node(), atom()}}]}
| {partition, wa_raft:partition()}
| {data_dir, file:filename_all()}
| {current_term, wa_raft_log:log_term()}
| {voted_for, node()}
| {commit_index, wa_raft_log:log_index()}
| {last_applied, wa_raft_log:log_index()}
| {leader_id, node()}
| {next_index, wa_raft_log:log_index()}
| {match_index, wa_raft_log:log_index()}
| {log_module, module()}
| {log_first, wa_raft_log:log_index()}
| {log_last, wa_raft_log:log_index()}
| {votes, #{node() => boolean()}}
| {inflight_applies, non_neg_integer()}
| {disable_reason, string()}
| {witness, boolean()}
| {config, config()}
| {config_index, wa_raft_log:log_index()}.
%%------------------------------------------------------------------------------
%% RAFT Server - Private Types
%%------------------------------------------------------------------------------
-type event() :: rpc() | remote(normalized_procedure()) | command() | internal_event() | timeout_type().
-type rpc() :: rpc_named() | legacy_rpc().
-type legacy_rpc() :: ?LEGACY_RAFT_RPC(atom(), wa_raft_log:log_term(), node(), undefined | tuple()).
-type rpc_named() :: ?RAFT_NAMED_RPC(atom(), wa_raft_log:log_term(), atom(), node(), undefined | tuple()).
-type command() :: commit_command() | read_command() | status_command() | promote_command() | resign_command() | adjust_membership_command() | snapshot_available_command() |
handover_candidates_command() | handover_command() | enable_command() | disable_command().
-type commit_command() :: ?COMMIT_COMMAND(wa_raft_acceptor:op()).
-type read_command() :: ?READ_COMMAND(wa_raft_acceptor:read_op()).
-type status_command() :: ?STATUS_COMMAND.
-type promote_command() :: ?PROMOTE_COMMAND(wa_raft_log:log_term(), boolean(), config() | undefined).
-type resign_command() :: ?RESIGN_COMMAND.
-type adjust_membership_command() :: ?ADJUST_MEMBERSHIP_COMMAND(membership_action(), peer() | undefined, wa_raft_log:log_index() | undefined).
-type snapshot_available_command() :: ?SNAPSHOT_AVAILABLE_COMMAND(string(), wa_raft_log:log_pos()).
-type handover_candidates_command() :: ?HANDOVER_CANDIDATES_COMMAND.
-type handover_command() :: ?HANDOVER_COMMAND(node()).
-type enable_command() :: ?ENABLE_COMMAND.
-type disable_command() :: ?DISABLE_COMMAND(term()).
-type internal_event() :: advance_term_event() | force_election_event().
-type advance_term_event() :: ?ADVANCE_TERM(wa_raft_log:log_term()).
-type force_election_event() :: ?FORCE_ELECTION(wa_raft_log:log_term()).
-type timeout_type() :: election | heartbeat.
-type membership_action() :: add | add_witness | remove | remove_witness | refresh.
%%------------------------------------------------------------------------------
%% RAFT Server - OTP Supervision
%%------------------------------------------------------------------------------
-spec child_spec(Options :: #raft_options{}) -> supervisor:child_spec().
child_spec(Options) ->
#{
id => ?MODULE,
start => {?MODULE, start_link, [Options]},
restart => transient,
shutdown => 30000,
modules => [?MODULE]
}.
-spec start_link(Options :: #raft_options{}) -> {ok, Pid :: pid()} | ignore | wa_raft:error().
start_link(#raft_options{server_name = Name} = Options) ->
gen_statem:start_link({local, Name}, ?MODULE, Options, []).
%%------------------------------------------------------------------------------
%% RAFT Server - Public APIs - RAFT Cluster Configuration
%%------------------------------------------------------------------------------
%% Returns the version number for the latest cluster configuration format that
%% is supported by the current RAFT implementation. All cluster configurations
%% returned by methods used to create or modify cluster configurations in this
%% module will return cluster configurations of this version.
-spec latest_config_version() -> pos_integer().
latest_config_version() ->
1.
-spec get_config_version(Config :: config() | config_all()) -> pos_integer().
get_config_version(#{version := Version}) ->
Version.
-spec get_config_members(Config :: config() | config_all()) -> [#raft_identity{}].
get_config_members(#{version := 1, membership := Members}) ->
[#raft_identity{name = Name, node = Node} || {Name, Node} <- Members];
get_config_members(_Config) ->
[].
-spec get_config_witnesses(Config :: config() | config_all()) -> [#raft_identity{}].
get_config_witnesses(#{version := 1, witness := Witnesses}) ->
[#raft_identity{name = Name, node = Node} || {Name, Node} <- Witnesses];
get_config_witnesses(_Config) ->
[].
%% Create a new cluster configuration with no members.
%% Without any members, this cluster configuration should not be used as
%% the active configuration for a RAFT cluster.
-spec make_config() -> config().
make_config() ->
#{
version => 1,
membership => [],
witness => []
}.
%% Create a new cluster configuration with the provided members.
-spec make_config(Members :: [#raft_identity{}]) -> config().
make_config(Members) ->
set_config_members(Members, make_config()).
%% Create a new cluster configuration with the provided members and witnesses.
-spec make_config(Members :: [#raft_identity{}], Witnesses :: [#raft_identity{}]) -> config().
make_config(Members, Witnesses) ->
set_config_members(Members, Witnesses, make_config()).
%% Replace the set of members in the provided cluster configuration.
%% Will upgrade the cluster configuration to the latest version.
-spec set_config_members(Members :: [#raft_identity{}], ConfigAll :: config() | config_all()) -> config().
set_config_members(Members, ConfigAll) ->
Config = maybe_upgrade_config(ConfigAll),
Config#{membership => lists:sort([{Name, Node} || #raft_identity{name = Name, node = Node} <- Members])}.
%% Replace the set of members and witnesses in the provided cluster configuration.
%% Will upgrade the cluster configuration to the latest version.
-spec set_config_members(Members :: [#raft_identity{}], Witnesses :: [#raft_identity{}], ConfigAll :: config() | config_all()) -> config().
set_config_members(Members, Witnesses, ConfigAll) ->
Config = set_config_members(Members, ConfigAll),
Config#{witness => lists:sort([{Name, Node} || #raft_identity{name = Name, node = Node} <- Witnesses])}.
%% Attempt to upgrade any configuration from an older configuration version to the
%% latest configuration version if possible.
-spec maybe_upgrade_config(ConfigAll :: config() | config_all()) -> Config :: config().
maybe_upgrade_config(#{version := 1} = Config) ->
% Fill in any missing fields.
Config#{
membership => maps:get(membership, Config, []),
witness => maps:get(witness, Config, [])
};
maybe_upgrade_config(#{version := Version}) ->
% We are not able to properly handle configurations with newer versions.
error({unsupported_version, Version});
maybe_upgrade_config(_Config) ->
% All valid configurations will contain at least their own version.
error(badarg).
%%------------------------------------------------------------------------------
%% RAFT Server - Public APIs
%%------------------------------------------------------------------------------
-spec status(ServerRef :: gen_statem:server_ref()) -> status().
status(ServerRef) ->
gen_statem:call(ServerRef, ?STATUS_COMMAND, ?RAFT_RPC_CALL_TIMEOUT()).
-spec status
(ServerRef :: gen_statem:server_ref(), Key :: atom()) -> Value :: dynamic();
(ServerRef :: gen_statem:server_ref(), Keys :: [atom()]) -> Value :: [dynamic()].
status(ServerRef, Key) when is_atom(Key) ->
hd(status(ServerRef, [Key]));
status(ServerRef, Keys) when is_list(Keys) ->
case status(ServerRef) of
[_|_] = Status ->
FilterFun =
fun({Key, Value}) ->
case lists:member(Key, Keys) of
true -> {true, Value};
false -> false
end
end,
lists:filtermap(FilterFun, Status);
_ ->
lists:duplicate(length(Keys), undefined)
end.
-spec membership(Service :: gen_statem:server_ref()) -> undefined | [#raft_identity{}].
membership(Service) ->
case proplists:get_value(config, status(Service), undefined) of
undefined -> undefined;
Config -> get_config_members(Config)
end.
%%------------------------------------------------------------------------------
%% RAFT Server - Internal APIs - Local Options
%%------------------------------------------------------------------------------
%% Get the default name for the RAFT server associated with the provided
%% RAFT partition.
-spec default_name(Table :: wa_raft:table(), Partition :: wa_raft:partition()) -> Name :: atom().
default_name(Table, Partition) ->
list_to_atom("raft_server_" ++ atom_to_list(Table) ++ "_" ++ integer_to_list(Partition)).
%% Get the registered name for the RAFT server associated with the provided
%% RAFT partition or the default name if no registration exists.
-spec registered_name(Table :: wa_raft:table(), Partition :: wa_raft:partition()) -> Name :: atom().
registered_name(Table, Partition) ->
case wa_raft_part_sup:options(Table, Partition) of
undefined -> default_name(Table, Partition);
Options -> Options#raft_options.server_name
end.
%%------------------------------------------------------------------------------
%% RAFT Server - Internal APIs - RPC Handling
%%------------------------------------------------------------------------------
-spec make_rpc(Self :: #raft_identity{}, Term :: wa_raft_log:log_term(), Procedure :: normalized_procedure()) -> rpc().
make_rpc(#raft_identity{name = Name, node = Node}, Term, ?PROCEDURE(Procedure, Payload)) ->
% For compatibility with legacy versions that expect RPCs sent with no arguments to have payload 'undefined' instead of {}.
PayloadOrUndefined = case Payload of
{} -> undefined;
_ -> Payload
end,
?RAFT_NAMED_RPC(Procedure, Term, Name, Node, PayloadOrUndefined).
-spec parse_rpc(Self :: #raft_identity{}, RPC :: rpc()) -> {Term :: wa_raft_log:log_term(), Sender :: #raft_identity{}, Procedure :: procedure()}.
parse_rpc(_Self, ?RAFT_NAMED_RPC(Key, Term, SenderName, SenderNode, PayloadOrUndefined)) ->
Payload = case PayloadOrUndefined of
undefined -> {};
_ -> PayloadOrUndefined
end,
#{Key := ?PROCEDURE(Procedure, Defaults)} = protocol(),
{Term, #raft_identity{name = SenderName, node = SenderNode}, ?PROCEDURE(Procedure, defaultize_payload(Defaults, Payload))};
parse_rpc(#raft_identity{name = Name} = Self, ?LEGACY_RAFT_RPC(Procedure, Term, SenderId, Payload)) ->
parse_rpc(Self, ?RAFT_NAMED_RPC(Procedure, Term, Name, SenderId, Payload)).
%%------------------------------------------------------------------------------
%% RAFT Server - Internal APIs - Commands
%%------------------------------------------------------------------------------
-spec commit(
Server :: gen_statem:server_ref(),
Op :: wa_raft_acceptor:op()
) -> ok | wa_raft:error().
commit(Server, Op) ->
gen_statem:cast(Server, ?COMMIT_COMMAND(Op)).
-spec read(
Server :: gen_statem:server_ref(),
Op :: wa_raft_acceptor:read_op()
) -> ok | wa_raft:error().
read(Server, Op) ->
gen_statem:cast(Server, ?READ_COMMAND(Op)).
-spec snapshot_available(
Server :: gen_statem:server_ref(),
Root :: file:filename(),
Position :: wa_raft_log:log_pos()
) -> ok | wa_raft:error().
snapshot_available(Server, Root, Position) ->
% Use the storage call timeout because this command requires the RAFT
% server to make a potentially expensive call against the RAFT storage
% server to complete.
gen_statem:call(Server, ?SNAPSHOT_AVAILABLE_COMMAND(Root, Position), ?RAFT_STORAGE_CALL_TIMEOUT()).
-spec adjust_membership(
Server :: gen_statem:server_ref(),
Action :: add | remove | add_witness | remove_witness,
Peer :: peer()
) ->
{ok, Pos :: wa_raft_log:log_pos()} | wa_raft:error().
adjust_membership(Server, Action, Peer) ->
adjust_membership(Server, Action, Peer, undefined).
-spec adjust_membership(
Server :: gen_statem:server_ref(),
Action :: add | remove | add_witness | remove_witness,
Peer :: peer(),
ConfigIndex :: wa_raft_log:log_index() | undefined
) -> {ok, Pos :: wa_raft_log:log_pos()} | wa_raft:error().
adjust_membership(Server, Action, Peer, ConfigIndex) ->
gen_statem:call(Server, ?ADJUST_MEMBERSHIP_COMMAND(Action, Peer, ConfigIndex), ?RAFT_RPC_CALL_TIMEOUT()).
-spec promote(
Server :: gen_statem:server_ref(),
Term :: wa_raft_log:log_term()
) -> ok | wa_raft:error().
promote(Server, Term) ->
promote(Server, Term, false).
-spec promote(
Server :: gen_statem:server_ref(),
Term :: wa_raft_log:log_term(),
Force :: boolean()
) -> ok | wa_raft:error().
promote(Server, Term, Force) ->
promote(Server, Term, Force, undefined).
-spec promote(
Server :: gen_statem:server_ref(),
Term :: wa_raft_log:log_term(),
Force :: boolean(),
Config :: config() | config_all() | undefined
) -> ok | wa_raft:error().
promote(Server, Term, Force, Config) ->
gen_statem:call(Server, ?PROMOTE_COMMAND(Term, Force, Config), ?RAFT_RPC_CALL_TIMEOUT()).
-spec resign(Server :: gen_statem:server_ref()) -> ok | wa_raft:error().
resign(Server) ->
gen_statem:call(Server, ?RESIGN_COMMAND, ?RAFT_RPC_CALL_TIMEOUT()).
%% Instruct a RAFT leader to attempt a handover to a random handover candidate.
-spec handover(Server :: gen_statem:server_ref()) -> ok.
handover(Server) ->
gen_statem:cast(Server, ?HANDOVER_COMMAND(undefined)).
%% Instruct a RAFT leader to attempt a handover to the specified peer node.
%% If an `undefined` peer node is specified, then handover to a random handover candidate.
%% Returns which peer node the handover was sent to or otherwise an error.
-spec handover(Server :: gen_statem:server_ref(), Peer :: node() | undefined) -> {ok, Peer :: node()} | wa_raft:error().
handover(Server, Peer) ->
gen_statem:call(Server, ?HANDOVER_COMMAND(Peer), ?RAFT_RPC_CALL_TIMEOUT()).
-spec handover_candidates(Server :: gen_statem:server_ref()) -> {ok, Candidates :: [node()]} | wa_raft:error().
handover_candidates(Server) ->
gen_statem:call(Server, ?HANDOVER_CANDIDATES_COMMAND, ?RAFT_RPC_CALL_TIMEOUT()).
-spec disable(Server :: gen_statem:server_ref(), Reason :: term()) -> ok | {error, ErrorReason :: atom()}.
disable(Server, Reason) ->
gen_statem:cast(Server, ?DISABLE_COMMAND(Reason)).
-spec enable(Server :: gen_statem:server_ref()) -> ok | {error, ErrorReason :: atom()}.
enable(Server) ->
gen_statem:call(Server, ?ENABLE_COMMAND, ?RAFT_RPC_CALL_TIMEOUT()).
%%------------------------------------------------------------------------------
%% RAFT Server - State Machine Implementation - General Callbacks
%%------------------------------------------------------------------------------
-spec init(Options :: #raft_options{}) -> gen_statem:init_result(state()).
init(#raft_options{application = Application, table = Table, partition = Partition, witness = Witness, self = Self, identifier = Identifier, database = DataDir,
label_module = LabelModule, distribution_module = DistributionModule, log_name = Log, log_catchup_name = Catchup,
server_name = Name, storage_name = Storage} = Options) ->
process_flag(trap_exit, true),
?LOG_NOTICE("Server[~0p] starting with options ~0p", [Name, Options], #{domain => [whatsapp, wa_raft]}),
% Open storage and the log
{ok, Last} = wa_raft_storage:open(Storage),
{ok, View} = wa_raft_log:open(Log, Last),
Now = erlang:monotonic_time(millisecond),
State0 = #raft_state{
application = Application,
name = Name,
self = Self,
identifier = Identifier,
table = Table,
partition = Partition,
data_dir = DataDir,
log_view = View,
label_module = LabelModule,
last_label = undefined,
distribution_module = DistributionModule,
storage = Storage,
catchup = Catchup,
commit_index = Last#raft_log_pos.index,
last_applied = Last#raft_log_pos.index,
current_term = Last#raft_log_pos.term,
state_start_ts = Now,
witness = Witness
},
State1 = load_config(State0),
rand:seed(exsp, {erlang:monotonic_time(), erlang:time_offset(), erlang:unique_integer()}),
% TODO(hsun324): When we have proper error handling for data corruption vs. stalled server
% then handle {error, Reason} type returns from load_state.
State2 = case wa_raft_durable_state:load(State1) of
{ok, NewState} -> NewState;
_ -> State1
end,
true = wa_raft_info:set_current_term_and_leader(Table, Partition, State2#raft_state.current_term, undefined),
% 1. Begin as disabled if a disable reason is set
% 2. Begin as witness if configured
% 3. Begin as stalled if there is no data
% 4. Begin as follower otherwise
case {State2#raft_state.last_applied, State2#raft_state.disable_reason, Witness} of
{_, undefined, true} -> {ok, witness, State2};
{0, undefined, _} -> {ok, stalled, State2};
{_, undefined, _} -> {ok, follower, State2};
{_, _, _} -> {ok, disabled, State2}
end.
-spec callback_mode() -> gen_statem:callback_mode_result().
callback_mode() ->
[state_functions, state_enter].
-spec terminate(Reason :: term(), State :: state(), Data :: #raft_state{}) -> ok.
terminate(Reason, State, #raft_state{name = Name, table = Table, partition = Partition, current_term = CurrentTerm} = Data) ->
?LOG_NOTICE("Server[~0p, term ~0p, ~0p] terminating due to ~p.",
[Name, CurrentTerm, State, Reason], #{domain => [whatsapp, wa_raft]}),
wa_raft_durable_state:sync(Data),
wa_raft_info:delete_state(Table, Partition),
wa_raft_info:set_stale(Table, Partition, true),
ok.
%%------------------------------------------------------------------------------
%% RAFT Server - State Machine Implementation - Procedure Call Marshalling
%%------------------------------------------------------------------------------
%% A macro that destructures the identity record indicating that the
%% relevant procedure should be refactored to treat identities
%% opaquely.
-define(IDENTITY_REQUIRES_MIGRATION(Name, Node), #raft_identity{name = Name, node = Node}).
-type remote(Call) :: ?REMOTE(#raft_identity{}, Call).
-type procedure() :: ?PROCEDURE(atom(), tuple()).
-type normalized_procedure() :: append_entries() | append_entries_response() | request_vote() | vote() | handover() | handover_failed() | notify_term().
-type append_entries() :: ?APPEND_ENTRIES (wa_raft_log:log_index(), wa_raft_log:log_term(), [wa_raft_log:log_entry()], wa_raft_log:log_index(), wa_raft_log:log_index()).
-type append_entries_response() :: ?APPEND_ENTRIES_RESPONSE(wa_raft_log:log_index(), boolean(), wa_raft_log:log_index()).
-type request_vote() :: ?REQUEST_VOTE (election_type(), wa_raft_log:log_index(), wa_raft_log:log_term()).
-type vote() :: ?VOTE (boolean()).
-type handover() :: ?HANDOVER (reference(), wa_raft_log:log_index(), wa_raft_log:log_term(), [wa_raft_log:log_entry()]).
-type handover_failed() :: ?HANDOVER_FAILED (reference()).
-type notify_term() :: ?NOTIFY_TERM ().
-type election_type() :: normal | force | allowed.
-spec protocol() -> #{atom() => procedure()}.
protocol() ->
#{
?APPEND_ENTRIES => ?APPEND_ENTRIES(0, 0, [], 0, 0),
?APPEND_ENTRIES_RESPONSE => ?APPEND_ENTRIES_RESPONSE(0, false, 0),
?REQUEST_VOTE => ?REQUEST_VOTE(normal, 0, 0),
?VOTE => ?VOTE(false),
?HANDOVER => ?HANDOVER(undefined, 0, 0, []),
?HANDOVER_FAILED => ?HANDOVER_FAILED(undefined)
}.
-spec handle_rpc(Type :: gen_statem:event_type(), RPC :: rpc(), State :: state(), Data :: #raft_state{}) -> gen_statem:event_handler_result(state(), #raft_state{}).
handle_rpc(Type, ?RAFT_NAMED_RPC(Procedure, Term, SenderName, SenderNode, Payload) = Event, State, Data) ->
handle_rpc_impl(Type, Event, Procedure, Term, #raft_identity{name = SenderName, node = SenderNode}, Payload, State, Data);
handle_rpc(Type, ?LEGACY_RAFT_RPC(Procedure, Term, SenderId, Payload) = Event, State, #raft_state{name = Name} = Data) ->
handle_rpc_impl(Type, Event, Procedure, Term, #raft_identity{name = Name, node = SenderId}, Payload, State, Data);
handle_rpc(_Type, RPC, State, #raft_state{name = Name, current_term = CurrentTerm}) ->
?RAFT_COUNT({'raft', State, 'rpc.unrecognized'}),
?LOG_NOTICE("Server[~0p, term ~0p, ~0p] receives unknown RPC format ~P",
[Name, CurrentTerm, State, RPC, 25], #{domain => [whatsapp, wa_raft]}),
keep_state_and_data.
-spec handle_rpc_impl(Type :: gen_statem:event_type(), Event :: rpc(), Key :: atom(), Term :: wa_raft_log:log_term(), Sender :: #raft_identity{},
Payload :: undefined | tuple(), State :: state(), Data :: #raft_state{}) -> gen_statem:event_handler_result(state(), #raft_state{}).
%% [Protocol] Undefined payload should be treated as an empty tuple
handle_rpc_impl(Type, Event, Key, Term, Sender, undefined, State, Data) ->
handle_rpc_impl(Type, Event, Key, Term, Sender, {}, State, Data);
%% [General Rules] Discard any incoming RPCs with a term older than the current term
handle_rpc_impl(_Type, _Event, Key, Term, Sender, _Payload, State, #raft_state{name = Name, current_term = CurrentTerm} = Data) when Term < CurrentTerm ->
?LOG_NOTICE("Server[~0p, term ~0p, ~0p] received stale ~0p from ~0p with old term ~0p. Dropping.",
[Name, CurrentTerm, State, Key, Sender, Term], #{domain => [whatsapp, wa_raft]}),
send_rpc(Sender, ?NOTIFY_TERM(), Data),
keep_state_and_data;
%% [RequestVote RPC]
%% RAFT servers should completely ignore normal RequestVote RPCs that it receives
%% from any peer if it knows about a currently active leader. An active leader is
%% one that is replicating to a quorum so we can check if we have gotten a
%% heartbeat recently.
handle_rpc_impl(Type, Event, ?REQUEST_VOTE, Term, Sender, Payload, State,
#raft_state{application = App, name = Name, current_term = CurrentTerm, leader_heartbeat_ts = LeaderHeartbeatTs} = Data) when is_tuple(Payload), element(1, Payload) =:= normal ->
AllowedDelay = ?RAFT_ELECTION_TIMEOUT_MIN(App) div 2,
Delay = case LeaderHeartbeatTs of
undefined -> infinity;
_ -> erlang:monotonic_time(millisecond) - LeaderHeartbeatTs
end,
case Delay > AllowedDelay of
true ->
% We have not gotten a heartbeat from the leader recently so allow this vote request
% to go through by reraising it with the special 'allowed' election type.
handle_rpc_impl(Type, Event, ?REQUEST_VOTE, Term, Sender, setelement(1, Payload, allowed), State, Data);
false ->
% We have gotten a heartbeat recently so drop this vote request.
% Log this at debug level because we may end up with alot of these when we have
% removed a server from the cluster but not yet shut it down.
?RAFT_COUNT('raft.server.request_vote.drop'),
?LOG_DEBUG("Server[~0p, term ~0p, ~0p] dropping normal vote request from ~p because leader was still active ~p ms ago (allowed ~p ms).",
[Name, CurrentTerm, State, Sender, Delay, AllowedDelay], #{domain => [whatsapp, wa_raft]}),
keep_state_and_data
end;
%% [General Rules] Advance to the newer term and reset state when seeing a newer term in an incoming RPC
handle_rpc_impl(Type, Event, _Key, Term, _Sender, _Payload, _State, #raft_state{current_term = CurrentTerm}) when Term > CurrentTerm ->
{keep_state_and_data, [{next_event, internal, ?ADVANCE_TERM(Term)}, {next_event, Type, Event}]};
%% [NotifyTerm] Drop NotifyTerm RPCs with matching term
handle_rpc_impl(_Type, _Event, ?NOTIFY_TERM, _Term, _Sender, _Payload, _State, _Data) ->
keep_state_and_data;
%% [Protocol] Convert any valid remote procedure call to the appropriate local procedure call.
handle_rpc_impl(Type, _Event, Key, _Term, Sender, Payload, State, #raft_state{name = Name, current_term = CurrentTerm} = Data) when is_tuple(Payload) ->
case protocol() of
#{Key := ?PROCEDURE(Procedure, Defaults)} ->
handle_procedure(Type, ?REMOTE(Sender, ?PROCEDURE(Procedure, defaultize_payload(Defaults, Payload))), State, Data);
#{} ->
?RAFT_COUNT({'raft', State, 'rpc.unknown'}),
?LOG_NOTICE("Server[~0p, term ~0p, ~0p] receives unknown RPC type ~0p with payload ~0P",
[Name, CurrentTerm, State, Key, Payload, 25], #{domain => [whatsapp, wa_raft]}),
keep_state_and_data
end.
-spec handle_procedure(Type :: gen_statem:event_type(), ProcedureCall :: remote(procedure()), State :: state(), Data :: #raft_state{}) -> gen_statem:event_handler_result(state(), #raft_state{}).
%% [AppendEntries] If we haven't discovered leader for this term, record it
handle_procedure(Type, ?REMOTE(Sender, ?APPEND_ENTRIES(_, _, _, _, _)) = Procedure, State, #raft_state{leader_id = undefined} = Data) ->
{keep_state, set_leader(State, Sender, Data), {next_event, Type, Procedure}};
%% [Handover] If we haven't discovered leader for this term, record it
handle_procedure(Type, ?REMOTE(Sender, ?HANDOVER(_, _, _, _)) = Procedure, State, #raft_state{leader_id = undefined} = Data) ->
{keep_state, set_leader(State, Sender, Data), {next_event, Type, Procedure}};
handle_procedure(Type, Procedure, _State, _Data) ->
{keep_state_and_data, {next_event, Type, Procedure}}.
-spec defaultize_payload(tuple(), tuple()) -> tuple().
defaultize_payload(Defaults, Payload) ->
defaultize_payload(Defaults, Payload, tuple_size(Defaults), tuple_size(Payload)).
-spec defaultize_payload(tuple(), tuple(), non_neg_integer(), non_neg_integer()) -> tuple().
defaultize_payload(_Defaults, Payload, N, N) ->
Payload;
defaultize_payload(Defaults, Payload, N, M) when N > M ->
defaultize_payload(Defaults, erlang:insert_element(M + 1, Payload, element(M + 1, Defaults)), N, M + 1);
defaultize_payload(Defaults, Payload, N, M) when N < M ->
defaultize_payload(Defaults, erlang:delete_element(M, Payload), N, M - 1).
%%------------------------------------------------------------------------------
%% RAFT Server - State Machine Implementation - Stalled State
%%------------------------------------------------------------------------------
%% The stalled state is an extension to the RAFT protocol designed to handle
%% situations in which a replica of the FSM is lost or replaced within a RAFT
%% cluster without being removed from the cluster membership. As the replica of
%% the FSM stored before the machine was lost or replaced could have been a
%% critical member of a quorum, it is important to ensure that the replacement
%% does not support a different result for any quorums before it receives a
%% fresh copy of the FSM state and log that is guaranteed to reflect any
%% quorums that the machine supported before it was lost or replaced.
%%
%% This is acheived by preventing a stalled node from participating in quorum
%% for both log entries and election. A leader of the cluster must provide a
%% fresh copy of its FSM state before the stalled node can return to normal
%% operation.
%%------------------------------------------------------------------------------
-spec stalled(Type :: enter, PreviousStateName :: state(), Data :: #raft_state{}) -> gen_statem:state_enter_result(state(), #raft_state{});
(Type :: gen_statem:event_type(), Event :: event(), Data :: #raft_state{}) -> gen_statem:event_handler_result(state(), #raft_state{}).
stalled(enter, PreviousStateName, #raft_state{name = Name, current_term = CurrentTerm} = State) ->
?RAFT_COUNT('raft.stalled.enter'),
?LOG_NOTICE("Server[~0p, term ~0p, stalled] becomes stalled from state ~0p.",
[Name, CurrentTerm, PreviousStateName], #{domain => [whatsapp, wa_raft]}),
{keep_state, enter_state(?FUNCTION_NAME, State)};
%% [AdvanceTerm] Advance to newer term when requested
stalled(internal, ?ADVANCE_TERM(NewerTerm), #raft_state{name = Name, current_term = CurrentTerm} = State) when NewerTerm > CurrentTerm ->
?RAFT_COUNT('raft.stalled.advance_term'),
?LOG_NOTICE("Server[~0p, term ~0p, stalled] advancing to new term ~p.",
[Name, CurrentTerm, NewerTerm], #{domain => [whatsapp, wa_raft]}),
{repeat_state, advance_term(?FUNCTION_NAME, NewerTerm, undefined, State)};
%% [AdvanceTerm] Ignore attempts to advance to an older or current term
stalled(internal, ?ADVANCE_TERM(Term), #raft_state{name = Name, current_term = CurrentTerm}) ->
?LOG_WARNING("Server[~0p, term ~0p, stalled] ignoring attempt to advance to older or current term ~0p.",
[Name, CurrentTerm, Term], #{domain => [whatsapp, wa_raft]}),
keep_state_and_data;
%% [Protocol] Handle any RPCs
stalled(Type, Event, State) when is_tuple(Event), element(1, Event) =:= rpc ->
handle_rpc(Type, Event, ?FUNCTION_NAME, State);
%% [AppendEntries] Stalled nodes always discard AppendEntries
stalled(_Type, ?REMOTE(Sender, ?APPEND_ENTRIES(PrevLogIndex, _PrevLogTerm, _Entries, _LeaderCommit, _TrimIndex)), State) ->
NewState = State#raft_state{leader_heartbeat_ts = erlang:monotonic_time(millisecond)},
send_rpc(Sender, ?APPEND_ENTRIES_RESPONSE(PrevLogIndex, false, 0), NewState),
{keep_state, NewState};
stalled({call, From}, ?SNAPSHOT_AVAILABLE_COMMAND(Root, #raft_log_pos{index = SnapshotIndex, term = SnapshotTerm} = SnapshotPos),
#raft_state{name = Name, log_view = View0, storage = Storage,
current_term = CurrentTerm, last_applied = LastApplied} = State0) ->
case SnapshotIndex > LastApplied orelse LastApplied =:= 0 of
true ->
try
?LOG_NOTICE("Server[~0p, term ~0p, stalled] applying snapshot ~p:~p",
[Name, CurrentTerm, SnapshotIndex, SnapshotTerm], #{domain => [whatsapp, wa_raft]}),
ok = wa_raft_storage:open_snapshot(Storage, Root, SnapshotPos),
{ok, View1} = wa_raft_log:reset(View0, SnapshotPos),
State1 = State0#raft_state{log_view = View1, last_applied = SnapshotIndex, commit_index = SnapshotIndex},
State2 = load_config(State1),
?LOG_NOTICE("Server[~0p, term ~0p, stalled] switching to follower after installing snapshot at ~p:~p.",
[Name, CurrentTerm, SnapshotIndex, SnapshotTerm], #{domain => [whatsapp, wa_raft]}),
State3 = case SnapshotTerm > CurrentTerm of
true -> advance_term(?FUNCTION_NAME, SnapshotTerm, undefined, State2);
false -> State2
end,
% At this point, we assume that we received some cluster membership configuration from
% our peer so it is safe to transition to an operational state.
{next_state, follower, State3, [{reply, From, ok}]}
catch
_:Reason ->
?LOG_WARNING("Server[~0p, term ~0p, stalled] failed to load available snapshot ~p due to ~p",
[Name, CurrentTerm, Root, Reason], #{domain => [whatsapp, wa_raft]}),
{keep_state_and_data, {reply, From, {error, Reason}}}
end;
false ->
?LOG_NOTICE("Server[~0p, term ~0p, stalled] ignoring available snapshot ~p:~p with index not past ours (~p)",
[Name, CurrentTerm, SnapshotIndex, SnapshotTerm, LastApplied], #{domain => [whatsapp, wa_raft]}),
{keep_state_and_data, {reply, From, {error, rejected}}}
end;
stalled(Type, ?RAFT_COMMAND(_COMMAND, _Payload) = Event, State) ->
command(?FUNCTION_NAME, Type, Event, State);
stalled(Type, Event, #raft_state{name = Name, current_term = CurrentTerm}) ->
?LOG_WARNING("Server[~0p, term ~0p, stalled] receives unknown ~p event ~p",
[Name, CurrentTerm, Type, Event], #{domain => [whatsapp, wa_raft]}),
keep_state_and_data.
%%------------------------------------------------------------------------------
%% RAFT Server - State Machine Implementation - Leader State
%%------------------------------------------------------------------------------
%% In a RAFT cluster, the leader of a RAFT term is a replica that has received
%% a quorum of votes from the cluster in that RAFT term, establishing it as the
%% unique coordinator for that RAFT term. The leader is responsible for
%% accepting and replicating new log entries to progress the state of the FSM.
%%------------------------------------------------------------------------------
-spec leader(Type :: enter, PreviousStateName :: state(), Data :: #raft_state{}) -> gen_statem:state_enter_result(state(), #raft_state{});
(Type :: gen_statem:event_type(), Event :: event(), Data :: #raft_state{}) -> gen_statem:event_handler_result(state(), #raft_state{}).
leader(enter, PreviousStateName, #raft_state{name = Name, self = Self, current_term = CurrentTerm, log_view = View0} = State0) ->
?RAFT_COUNT('raft.leader.enter'),
?RAFT_COUNT('raft.leader.elected'),
?LOG_NOTICE("Server[~0p, term ~0p, leader] becomes leader from state ~0p.",
[Name, CurrentTerm, PreviousStateName], #{domain => [whatsapp, wa_raft]}),
% Setup leader state and announce leadership
State1 = enter_state(?FUNCTION_NAME, State0),
State2 = set_leader(?FUNCTION_NAME, Self, State1),
% During promotion, we may add a config update operation to the end of the log.
% If there is such an operation and it has the same term number as the current term,
% then make sure to set the start of the current term so that it gets replicated
% immediately.
LastLogIndex = wa_raft_log:last_index(View0),
State5 = case wa_raft_log:get(View0, LastLogIndex) of
{ok, {CurrentTerm, {_Ref, {config, _NewConfig}}}} ->
State2#raft_state{first_current_term_log_index = LastLogIndex, last_label = undefined};
{ok, {CurrentTerm, {_Ref, LastLabel, {config, _NewConfig}}}} ->
State2#raft_state{first_current_term_log_index = LastLogIndex, last_label = LastLabel};
{ok, LastLogEntry} ->
% Otherwise, the server should add a new log entry to start the current term.
% This will flush pending commits, clear out and log mismatches on replicas,
% and establish a quorum as soon as possible.
State3 = case LastLogEntry of
{_CurrentTerm, {_Ref, LastLabel, _Command}} ->
State2#raft_state{last_label = LastLabel};
{_, undefined} ->
% The RAFT log could have been reset (i.e. after snapshot installation).
% In such case load the log label state from storage.
LastLabel = load_label_state(State2),
State2#raft_state{last_label = LastLabel};
_ ->
State2#raft_state{last_label = undefined}
end,
{State4, LogEntry} = get_log_entry(State3, {make_ref(), noop}),
{ok, NewLastLogIndex, View1} = wa_raft_log:append(View0, [LogEntry]),
State4#raft_state{log_view = View1, first_current_term_log_index = NewLastLogIndex}
end,
% Perform initial heartbeat and log entry resolution
State6 = append_entries_to_followers(State5),
State7 = apply_single_node_cluster(State6), % apply immediately for single node cluster
{keep_state, State7, ?HEARTBEAT_TIMEOUT(State7)};
%% [AdvanceTerm] Advance to newer term when requested
leader(internal, ?ADVANCE_TERM(NewerTerm), #raft_state{name = Name, log_view = View, current_term = CurrentTerm} = State) when NewerTerm > CurrentTerm ->
?RAFT_COUNT('raft.leader.advance_term'),
?LOG_NOTICE("Server[~0p, term ~0p, leader] advancing to new term ~p.",
[Name, CurrentTerm, NewerTerm], #{domain => [whatsapp, wa_raft]}),
%% Drop any pending log entries queued in the log view before advancing
{ok, _Pending, NewView} = wa_raft_log:cancel(View),
{next_state, follower, advance_term(?FUNCTION_NAME, NewerTerm, undefined, State#raft_state{log_view = NewView})};
%% [AdvanceTerm] Ignore attempts to advance to an older or current term
leader(internal, ?ADVANCE_TERM(Term), #raft_state{name = Name, current_term = CurrentTerm}) ->
?LOG_WARNING("Server[~0p, term ~0p, leader] ignoring attempt to advance to older or current term ~0p.",
[Name, CurrentTerm, Term], #{domain => [whatsapp, wa_raft]}),
keep_state_and_data;
%% [Protocol] Handle any RPCs
leader(Type, Event, State) when is_tuple(Event), element(1, Event) =:= rpc ->
handle_rpc(Type, Event, ?FUNCTION_NAME, State);
%% [Leader] Handle AppendEntries RPC (5.1, 5.2)
%% [AppendEntries] We are leader for the current term, so we should never see an
%% AppendEntries RPC from another node for this term
leader(_Type, ?REMOTE(Sender, ?APPEND_ENTRIES(PrevLogIndex, _PrevLogTerm, _Entries, _LeaderCommit, _TrimIndex)),
#raft_state{current_term = CurrentTerm, name = Name, commit_index = CommitIndex} = State) ->
?LOG_ERROR("Server[~0p, term ~0p, leader] got invalid heartbeat from conflicting leader ~p.",
[Name, CurrentTerm, Sender], #{domain => [whatsapp, wa_raft]}),
send_rpc(Sender, ?APPEND_ENTRIES_RESPONSE(PrevLogIndex, false, CommitIndex), State),
keep_state_and_data;
%% [Leader] Handle AppendEntries RPC responses (5.2, 5.3, 7).
%% Handle normal-case successes
leader(cast, ?REMOTE(?IDENTITY_REQUIRES_MIGRATION(_, FollowerId) = Sender, ?APPEND_ENTRIES_RESPONSE(_PrevIndex, true, FollowerEndIndex)),
#raft_state{
name = Name,
current_term = CurrentTerm,
commit_index = CommitIndex0,
next_index = NextIndex0,
match_index = MatchIndex0,
heartbeat_response_ts = HeartbeatResponse0,
first_current_term_log_index = TermStartIndex} = State0) ->
StartT = os:timestamp(),
?LOG_DEBUG("Server[~0p, term ~0p, leader] append ok on ~p. Follower end index ~p. Leader commitIndex ~p",
[Name, CurrentTerm, Sender, FollowerEndIndex, CommitIndex0], #{domain => [whatsapp, wa_raft]}),
HeartbeatResponse1 = HeartbeatResponse0#{FollowerId => erlang:monotonic_time(millisecond)},
State1 = State0#raft_state{heartbeat_response_ts = HeartbeatResponse1},
case select_follower_replication_mode(FollowerEndIndex, State1) of
bulk_logs -> request_bulk_logs_for_follower(Sender, FollowerEndIndex, State1);
_ -> cancel_bulk_logs_for_follower(Sender, State1)
end,
MatchIndex1 = maps:put(FollowerId, FollowerEndIndex, MatchIndex0),
OldNextIndex = maps:get(FollowerId, NextIndex0, TermStartIndex),
NextIndex1 = maps:put(FollowerId, erlang:max(OldNextIndex, FollowerEndIndex + 1), NextIndex0),
State2 = State1#raft_state{match_index = MatchIndex1, next_index = NextIndex1},
State3 = maybe_apply(State2),
?RAFT_GATHER('raft.leader.apply.func', timer:now_diff(os:timestamp(), StartT)),
{keep_state, maybe_heartbeat(State3), ?HEARTBEAT_TIMEOUT(State3)};
%% and failures.
leader(cast, ?REMOTE(?IDENTITY_REQUIRES_MIGRATION(_, FollowerId) = Sender, ?APPEND_ENTRIES_RESPONSE(_PrevLogIndex, false, FollowerEndIndex)),
#raft_state{name = Name, current_term = CurrentTerm, next_index = NextIndex0} = State0) ->
?RAFT_COUNT('raft.leader.append.failure'),
?LOG_DEBUG("Server[~0p, term ~0p, leader] append failure for follower ~p. Follower reports log matches up to ~0p.",
[Name, CurrentTerm, Sender, FollowerEndIndex], #{domain => [whatsapp, wa_raft]}),
select_follower_replication_mode(FollowerEndIndex, State0) =:= snapshot andalso
request_snapshot_for_follower(FollowerId, State0),
cancel_bulk_logs_for_follower(Sender, State0),
% We must trust the follower's last log index here because the follower may have
% applied a snapshot since the last successful heartbeat. In such case, we need
% to fast-forward the follower's next index so that we resume replication at the
% point after the snapshot.
NextIndex1 = maps:put(FollowerId, FollowerEndIndex + 1, NextIndex0),
State1 = State0#raft_state{next_index = NextIndex1},
State2 = maybe_apply(State1),
{keep_state, maybe_heartbeat(State2), ?HEARTBEAT_TIMEOUT(State2)};
%% [RequestVote RPC] We are already leader for the current term, so always decline votes (5.1, 5.2)
leader(_Type, ?REMOTE(Sender, ?REQUEST_VOTE(_ElectionType, _LastLogIndex, _LastLogTerm)),
#raft_state{} = State) ->
send_rpc(Sender, ?VOTE(false), State),
keep_state_and_data;
%% [Vote RPC] We are already leader, so we don't need to consider any more votes (5.1)
leader(_Type, ?REMOTE(Sender, ?VOTE(Vote)), #raft_state{name = Name, current_term = CurrentTerm}) ->
?LOG_NOTICE("Server[~0p, term ~0p, leader] receives vote ~p from ~p after being elected. Ignore it.",
[Name, CurrentTerm, Vote, Sender], #{domain => [whatsapp, wa_raft]}),
keep_state_and_data;
%% [Handover RPC] We are already leader so ignore any handover requests.
leader(_Type, ?REMOTE(Sender, ?HANDOVER(Ref, _PrevLogIndex, _PrevLogTerm, _LogEntries)),
#raft_state{name = Name, current_term = CurrentTerm} = State) ->
?LOG_WARNING("Server[~0p, term ~0p, leader] got orphan handover request from ~p while leader.",
[Name, CurrentTerm, Sender], #{domain => [whatsapp, wa_raft]}),
send_rpc(Sender, ?HANDOVER_FAILED(Ref), State),
keep_state_and_data;
%% [Handover Failed RPC] Our handover failed, so clear the handover status.
leader(_Type, ?REMOTE(?IDENTITY_REQUIRES_MIGRATION(_, NodeId) = Sender, ?HANDOVER_FAILED(Ref)),
#raft_state{name = Name, current_term = CurrentTerm, handover = {NodeId, Ref, _Timeout}} = State) ->
?LOG_NOTICE("Server[~0p, term ~0p, leader] resuming normal operations after failed handover to ~p.",
[Name, CurrentTerm, Sender], #{domain => [whatsapp, wa_raft]}),
{keep_state, State#raft_state{handover = undefined}};
%% [Handover Failed RPC] Got a handover failed with an unknown ID. Ignore.
leader(_Type, ?REMOTE(Sender, ?HANDOVER_FAILED(_Ref)),
#raft_state{name = Name, current_term = CurrentTerm, handover = Handover}) ->
?LOG_NOTICE("Server[~0p, term ~0p, leader] got handover failed RPC from ~p that does not match current handover ~p.",
[Name, CurrentTerm, Sender, Handover], #{domain => [whatsapp, wa_raft]}),
keep_state_and_data;
%% [Timeout] Suspend periodic heartbeat to followers while handover is active
leader(state_timeout = Type, Event, #raft_state{name = Name, current_term = CurrentTerm, handover = {Peer, _Ref, Timeout}} = State) ->
NowMillis = erlang:monotonic_time(millisecond),
case NowMillis > Timeout of
true ->
?LOG_NOTICE("Server[~0p, term ~0p, leader] handover to ~p times out",
[Name, CurrentTerm, Peer], #{domain => [whatsapp, wa_raft]}),
{keep_state, State#raft_state{handover = undefined}, {next_event, Type, Event}};
false ->
{keep_state_and_data, ?HEARTBEAT_TIMEOUT(State)}
end;
%% [Timeout] Periodic heartbeat to followers
leader(state_timeout, _, #raft_state{application = App, name = Name, log_view = View, current_term = CurrentTerm} = State0) ->
case ?RAFT_LEADER_ELIGIBLE(App) andalso ?RAFT_ELECTION_WEIGHT(App) =/= 0 of
true ->
State1 = append_entries_to_followers(State0),
State2 = apply_single_node_cluster(State1),
check_leader_lagging(State2),
{keep_state, State1, ?HEARTBEAT_TIMEOUT(State2)};
false ->
?LOG_NOTICE("Server[~0p, term ~0p, leader] resigns from leadership because this node is ineligible or election weight is zero.",
[Name, CurrentTerm], #{domain => [whatsapp, wa_raft]}),
%% Drop any pending log entries queued in the log view before resigning
{ok, _Pending, NewView} = wa_raft_log:cancel(View),
{next_state, follower, clear_leader(?FUNCTION_NAME, State0#raft_state{log_view = NewView})}
end;
%% [Commit] If a handover is in progress, then try to redirect to handover target