forked from abecciu/gen_leader_revival
-
Notifications
You must be signed in to change notification settings - Fork 12
/
gen_leader.erl
1637 lines (1513 loc) · 66.4 KB
/
gen_leader.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
%%% ``The contents of this file are subject to the Erlang Public License,
%%% Version 1.1, (the "License"); you may not use this file except in
%%% compliance with the License. You should have received a copy of the
%%% Erlang Public License along with this software. If not, it can be
%%% retrieved via the world wide web at http://www.erlang.org/.
%%%
%%% Software distributed under the License is distributed on an "AS IS"
%%% basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See
%%% the License for the specific language governing rights and limitations
%%% under the License.
%%%
%%% The Initial Developer of the Original Code is Ericsson Utvecklings AB.
%%% Portions created by Ericsson are Copyright 1999, Ericsson Utvecklings
%%% AB. All Rights Reserved.''
%%%
%%%
%%% $Id: gen_leader.erl,v 1.4 2008/09/19 07:40:15 hanssv Exp $
%%%
%%% @author Hans Svensson <hanssv@chalmers.se>
%%% @author Thomas Arts <thomas.arts@ituniv.se>
%%% @author Ulf Wiger <ulf.wiger@ericsson.com>
%%% @author (contributor: Serge Aleynikov <saleyn@gmail.com>)
%%%
%%% @doc Leader election behavior.
%%% <p>This application implements a leader election behavior modeled after
%%% gen_server. This behavior intends to make it reasonably
%%% straightforward to implement a fully distributed server with
%%% master-slave semantics.</p>
%%% <p>The gen_leader behavior supports nearly everything that gen_server
%%% does (some functions, such as multicall() and the internal timeout,
%%% have been removed), and adds a few callbacks and API functions to
%%% support leader election etc.</p>
%%% <p>Also included is an example program, a global dictionary, based
%%% on the modules gen_leader and dict. The callback implementing the
%%% global dictionary is called 'test_cb', for no particularly logical
%%% reason.</p>
%%% <p><b>New version:</b> The internal leader election algorithm was faulty
%%% and has been replaced with a new version based on a different leader
%%% election algorithm. As a consequence of this the query functions
%%% <tt>alive</tt> and <tt>down</tt> can no longer be provided.
%%% The new algorithm also make use of an incarnation parameter, by
%%% default written to disk in the function <tt>incarnation</tt>. This
%%% implies that only one <tt>gen_leader</tt> per node is permitted, if
%%% used in a diskless environment, <tt>incarnation</tt> must be adapted.
%%% </p>
%%% <p>
%%% Modifications contributed by Serge Aleynikov:
%%% <ol>
%%% <li>Added configurable startup options (see leader_options() type)</li>
%%% <li>Implemented handle_DOWN/3 callback with propagation of the
%%% leader's state via broadcast to all connected candidates.</li>
%%% <li>Fixed population of the #election.down member so that down/1 query
%%% can be used in the behavior's implementation</li>
%%% <li>Rewrote implementation of the tau timer to prevent the leader
%%% looping on the timer timeout event when all candidates are connected.</li>
%%% </ol>
%%% </p>
%%% @end
%%%
%%%
-module(gen_leader).
%% Time between rounds of query from the leader
-define(TAU,5000).
-export([start/6,
start_link/6,
leader_call/2, leader_call/3, leader_cast/2,
call/2, call/3, cast/2,
reply/2]).
%% Query functions
-export([alive/1,
down/1,
candidates/1,
workers/1,
broadcast/3,
leader_node/1]).
-export([system_continue/3,
system_terminate/4,
system_code_change/4,
format_status/2,
worker_announce/2
]).
%% Internal exports
-export([init_it/6,
print_event/3,
send_checkleads/4
]).
%% Notification control of candidate membership changes. `all'
%% means that returns from the handle_DOWN/3 and elected/3 leader's events
%% will be broadcast to all candidates.
-type bcast_type() :: 'all' | 'sender'.
-type option() :: {'workers', Workers::[node()]}
| {'vardir', Dir::string()}
| {'bcast_type', Type::bcast_type()}
| {'heartbeat', Seconds::integer()}
| {'seed_node', Seed::node()}
.
-type options() :: [option()].
-type status() :: 'elec1' | 'elec2' | 'wait' | 'joining' | 'worker' |
'waiting_worker' | 'norm'.
%% A locally registered name
-type name() :: atom().
%% A monitor ref
-type mon_ref() :: reference().
-type server_ref() :: name() | {name(),node()} | {global,name()} | pid().
%% Incarnation number
-type incarn() :: non_neg_integer().
%% Logical clock
-type lclock() :: non_neg_integer().
%% Node priority in the election
-type priority() :: integer().
%% Election id
-type elid() :: {priority(), incarn(), lclock()}.
%% See gen_server.
-type caller_ref() :: {pid(), reference()}.
%% Opaque state of the gen_leader behaviour.
-record(election, {
leader = none :: 'none' | pid(),
previous_leader = none :: 'none' | pid(),
name :: name(),
leadernode = none :: 'none' | node(),
candidate_nodes = [] :: [node()],
worker_nodes = [] :: [node()],
down = [] :: [node()],
monitored = [] :: [{mon_ref(), node()}],
buffered = [] :: [{reference(),caller_ref()}],
seed_node = none :: 'none' | node(),
status :: status(),
elid :: elid(),
acks = [] :: [node()],
work_down = [] :: [node()],
cand_timer_int :: integer(),
cand_timer :: term(),
pendack :: node(),
incarn :: incarn(),
nextel :: integer(),
%% all | one. When `all' each election event
%% will be broadcast to all candidate nodes.
bcast_type :: bcast_type()
}).
-opaque election() :: #election{}.
-export_type([election/0]).
-record(server, {
parent,
mod,
state,
monitor_proc = spawn_monitor_proc(),
debug :: [sys:dbg_opt()]
}).
%%% ---------------------------------------------------
%%% Interface functions.
%%% ---------------------------------------------------
-callback init(any()) -> {ok, term()}
| {stop, term()}
| ignore
| {'EXIT', term()}
.
-callback elected(term(), election(), pid() | undefined) -> {ok, term(), term()}
| {reply, term(), term()}
.
-callback surrendered(term(), term(), election()) -> {ok, term()} .
-callback handle_leader_call(term(), pid(), term(), election()) -> {reply, term(), term()}
| {reply, term(), term(), term()}
| {noreply, term()}
| {stop, term(), term(), term()}
.
-callback handle_leader_cast(term(), term(), election()) -> {noreply, term()}
| {ok, term(), term()}
.
-callback from_leader(term(), term(), election()) -> {noreply, term()}
| {ok, term()}
| {stop, term(), term()}
| {'EXIT', term()}
.
-callback handle_call(term(), pid(), term(), election()) -> {noreply, term()}
| {reply, term(), term()}
| {ok, term()}
| {stop, term(), term()}
| {'EXIT', term()}
.
-callback handle_cast(term(), term(), election()) -> {noreply, term()}
| {ok, term()}
| {stop, term(), term()}
| {'EXIT', term()}
.
-callback handle_DOWN(node(), term(), election()) -> {ok, term()}
| {ok, term(), term()}
.
-callback handle_info(term(), term(), election()) -> {noreply, term()}
| {ok, term()}
| {stop, term(), term()}
| {'EXIT', term()}
.
-callback terminate(term(), term()) -> any() .
-callback code_change(term() | {down, term()}, term(), election(), term()) -> {ok, term()}
| {error, term()}
.
-type start_ret() :: {'ok', pid()} | {'error', term()}.
%% @doc Starts a gen_leader process without linking to the parent.
%% @see start_link/6
-spec start(Name::atom(), CandidateNodes::[node()], OptArgs::options(),
Mod::module(), Arg::term(), Options::list()) -> start_ret().
start(Name, CandidateNodes, OptArgs, Mod, Arg, Options)
when is_atom(Name), is_list(CandidateNodes), is_list(OptArgs) ->
gen:start(?MODULE, nolink, {local,Name},
Mod, {CandidateNodes, OptArgs, Arg}, Options).
%% @doc Starts a gen_leader process.
%% <table>
%% <tr><td>Name</td><td>The locally registered name of the process</td></tr>
%% <tr><td>CandidateNodes</td><td>The names of nodes capable of assuming
%% a leadership role</td></tr>
%% <tr><td valign="top">OptArgs</td>
%% <td>Optional arguments given to `gen_leader'.
%% <du>
%% <dl>{workers, Workers}</dl>
%% <dd>The names of nodes that will be part of the "cluster",
%% but cannot ever assume a leadership role. Default: [].</dd>
%% <dl>{vardir, Dir}</dl>
%% <dd>Directory name used to store candidate's incarnation cookie.
%% Default: "."</dd>
%% <dl>{bcast_type, Type}</dl>
%% <dd>When `Type' is 'all' each election event (when a new
%% candidate becomes visible to the leader) will be broadcast
%% to all live candidate nodes. Each candidate will get
%% a from_leader/3 callback. When `Type' is `sender', only
%% the newly registered candidate will get the surrendered/3
%% callback. Default: `sender'.</dd>
%% <dl>{heartbeat, Seconds}</dl>
%% <dd>Heartbeat timeout value used to send ping messages to inactive
%% candidate nodes.</dd>
%% </du>
%% </td></tr>
%% <tr><td>Mod</td><td>The name of the callback module</td></tr>
%% <tr><td>Arg</td><td>Argument passed on to <code>Mod:init/1</code></td></tr>
%% <tr><td>Options</td><td>Same as gen_server's Options</td></tr>
%% </table>
%%
%% <p>The list of candidates needs to be known from the start. Workers
%% could potentially be added at runtime, but no functionality to do
%% this is provided by this version.</p>
%% @end
-spec start_link(Name::atom(), CandidateNodes::[node()], OptArgs::options(),
Mod::module(), Arg::term(), Options::list()) -> start_ret().
start_link(Name, CandidateNodes, OptArgs, Mod, Arg, Options)
when is_atom(Name), is_list(CandidateNodes), is_list(OptArgs) ->
gen:start(?MODULE, link, {local,Name},
Mod, {CandidateNodes, OptArgs, Arg}, Options).
%% Query functions to be used from the callback module
%% @doc Returns list of alive nodes.
-spec alive(election()) -> [node()].
alive(E) ->
candidates(E) -- down(E).
%% @doc Returns list of down nodes.
-spec down(election()) -> [node()].
down(#election{down = Down}) ->
Down.
%% @doc Returns the current leader node.
-spec leader_node(election()) -> node() | 'none'.
leader_node(#election{leadernode=Leader}) ->
Leader.
%% @doc Returns a list of known candidates.
-spec candidates(election()) -> [node()].
candidates(#election{candidate_nodes = Cands}) ->
Cands.
%% @doc Returns a list of known workers.
-spec workers(election()) -> [node()].
workers(#election{worker_nodes = Workers}) ->
Workers.
%% Used by dynamically added workers.
%% @hidden
worker_announce(Name, Pid) ->
Name ! {add_worker, Pid},
Name ! {heartbeat, Pid}.
%%
%% Make a call to a generic server.
%% If the server is located at another node, that node will
%% be monitored.
%% If the client is trapping exits and is linked server termination
%% is handled here (? Shall we do that here (or rely on timeouts) ?).
%%
%% @doc Equivalent to <code>gen_server:call/2</code>, but with a slightly
%% different exit reason if something goes wrong. This function calls
%% the <code>gen_leader</code> process exactly as if it were a gen_server
%% (which, for practical purposes, it is.)
%% @end
-spec call(server_ref(), term()) -> term().
call(Name, Request) ->
case catch gen:call(Name, '$gen_call', Request) of
{ok,Res} ->
Res;
{'EXIT',Reason} ->
exit({Reason, {?MODULE, local_call, [Name, Request]}})
end.
%% @doc Equivalent to <code>gen_server:call/3</code>, but with a slightly
%% different exit reason if something goes wrong. This function calls
%% the <code>gen_leader</code> process exactly as if it were a gen_server
%% (which, for practical purposes, it is.)
%% @end
-spec call(server_ref(), term(), integer()) -> term().
call(Name, Request, Timeout) ->
case catch gen:call(Name, '$gen_call', Request, Timeout) of
{ok,Res} ->
Res;
{'EXIT',Reason} ->
exit({Reason, {?MODULE, local_call, [Name, Request, Timeout]}})
end.
%% @doc Makes a call (similar to <code>gen_server:call/2</code>) to the
%% leader. The call is forwarded via the local gen_leader instance, if
%% that one isn't actually the leader. The client will exit if the
%% leader dies while the request is outstanding.
%% <p>This function uses <code>gen:call/3</code>, and is subject to the
%% same default timeout as e.g. <code>gen_server:call/2</code>.</p>
%% @end
%%
-spec leader_call(Name::server_ref(), Request::term()) -> term().
leader_call(Name, Request) ->
case catch gen:call(Name, '$leader_call', Request) of
{ok,{leader,reply,Res}} ->
Res;
{ok,{error, leader_died}} ->
exit({leader_died, {?MODULE, leader_call, [Name, Request]}});
{'EXIT',Reason} ->
exit({Reason, {?MODULE, leader_call, [Name, Request]}})
end.
%% @doc Makes a call (similar to <code>gen_server:call/3</code>) to the
%% leader. The call is forwarded via the local gen_leader instance, if
%% that one isn't actually the leader. The client will exit if the
%% leader dies while the request is outstanding.
%% @end
%%
-spec leader_call(Name::server_ref(), Request::term(),
Timeout::integer()) -> term().
leader_call(Name, Request, Timeout) ->
case catch gen:call(Name, '$leader_call', Request, Timeout) of
{ok,{leader,reply,Res}} ->
Res;
{'EXIT',Reason} ->
exit({Reason, {?MODULE, leader_call, [Name, Request, Timeout]}})
end.
%% @equiv gen_server:cast/2
-spec cast(Name::server_ref(), Request::term()) -> 'ok'.
cast(Name, Request) ->
catch do_cast('$gen_cast', Name, Request),
ok.
%% @doc Similar to <code>gen_server:cast/2</code> but will be forwarded to
%% the leader via the local gen_leader instance.
-spec leader_cast(Name::server_ref(), Request::term()) -> 'ok'.
leader_cast(Name, Request) ->
catch do_cast('$leader_cast', Name, Request),
ok.
do_cast(Tag, {global, Name}, Request) ->
global:send(Name, {Tag, Request});
do_cast(Tag, ServerRef, Request) ->
ServerRef ! {Tag, Request}.
%% @equiv gen_server:reply/2
-spec reply(From::caller_ref(), Reply::term()) -> term().
reply({To, Tag}, Reply) ->
catch To ! {Tag, Reply}.
%%% ---------------------------------------------------
%%% Initiate the new process.
%%% Register the name using the Rfunc function
%%% Calls the Mod:init/Args function.
%%% Finally an acknowledge is sent to Parent and the main
%%% loop is entered.
%%% ---------------------------------------------------
%%% @hidden
init_it(Starter, Parent, {local, Name}, Mod, {CandidateNodes, Workers, Arg}, Options) ->
%% R13B passes {local, Name} instead of just Name
init_it(Starter, Parent, Name, Mod,
{CandidateNodes, Workers, Arg}, Options);
init_it(Starter, self, Name, Mod, {CandidateNodes, OptArgs, Arg}, Options) ->
init_it(Starter, self(), Name, Mod,
{CandidateNodes, OptArgs, Arg}, Options);
init_it(Starter,Parent,Name,Mod,{UnsortedCandidateNodes,OptArgs,Arg},Options) ->
Workers = proplists:get_value(workers, OptArgs, []),
VarDir = proplists:get_value(vardir, OptArgs, "."),
Interval = proplists:get_value(heartbeat, OptArgs, ?TAU div 1000) * 1000,
BcastType = proplists:get_value(bcast_type,OptArgs, sender),
Seed = proplists:get_value(seed, OptArgs, none),
Debug = debug_options(Name, Options),
CandidateNodes = lists:sort(UnsortedCandidateNodes),
AmCandidate = case lists:member(node(), CandidateNodes) of
true -> true;
false ->
case lists:member(node(), Workers) of
true -> false;
false ->
Seed =/= none
end
end,
Election = #election{
candidate_nodes = CandidateNodes,
worker_nodes = Workers,
name = Name,
nextel = 0,
cand_timer_int = Interval,
bcast_type = BcastType
},
case {AmCandidate, lists:member(node(), Workers)} of
{false, false} ->
%% I am neither a candidate nor a worker - don't start this process
error_logger:warning_msg("~w not started - node is not a candidate/worker\n", [Name]),
proc_lib:init_ack(Starter, ignore),
exit(normal);
_ ->
ok
end,
case {catch Mod:init(Arg), AmCandidate, Seed =/= none} of
{{stop, Reason},_,_} ->
proc_lib:init_ack(Starter, {error, Reason}),
exit(Reason);
{ignore,_,_} ->
proc_lib:init_ack(Starter, ignore),
exit(normal);
{{'EXIT', Reason},_,_} ->
proc_lib:init_ack(Starter, {error, Reason}),
exit(Reason);
{{ok, State}, true, false} ->
Server = #server{parent = Parent,mod = Mod,
state = State,debug = Debug},
Incarn = incarnation(VarDir, Name, node()),
NewE = startStage1(Election#election{incarn = Incarn}, Server),
proc_lib:init_ack(Starter, {ok, self()}),
%% handle the case where there's only one candidate worker and we can't
%% rely on DOWN messages to trigger the elected() call because we never get
%% a DOWN for ourselves
case CandidateNodes =:= [node()] of
true ->
%% there's only one candidate leader; us
hasBecomeLeader(NewE,Server,{init});
false ->
%% more than one candidate worker, broadcast about myself and
%% go to candidate_joining
lists:foreach(
fun(Node) ->
{NewE#election.name,Node} ! {join, self()}
end,
CandidateNodes -- [node()]),
safe_loop(Server, candidate, NewE, {init})
end;
{{ok, State}, true, true} ->
Server = #server{parent = Parent,mod = Mod,
state = State,debug = Debug},
Incarn = incarnation(VarDir, Name, node()),
NewE1 = Election#election{incarn = Incarn, seed_node = Seed},
NewE = joinCluster(NewE1, Server),
proc_lib:init_ack(Starter, {ok, self()}),
safe_loop(Server, candidate_joining, NewE, {init});
{{ok, State}, false, HasSeed} ->
proc_lib:init_ack(Starter, {ok, self()}),
Candidates = case HasSeed of
true ->
{ok, C} = call({Name, Seed}, get_candidates),
C;
false -> CandidateNodes
end,
case lists:member(node(), Workers) of
true ->
rpc:multicall(Candidates, gen_leader,
worker_announce, [Name, node(self())]);
false -> nop
end,
safe_loop(#server{parent = Parent,mod = Mod,
state = State,debug = Debug},
waiting_worker, Election,{init});
{Else,_,_} ->
Error = {bad_return_value, Else},
proc_lib:init_ack(Starter, {error, Error}),
exit(Error)
end.
%%% ---------------------------------------------------
%%% The MAIN loops.
%%% ---------------------------------------------------
% this is the election loop. Only specific messages related
% to the election process are received. User messages, defined
% in e.g. a callback module, are postponed until the (re)election\
% is complete.
safe_loop(#server{mod = Mod, state = State} = Server, Role,
#election{name = Name} = E, _PrevMsg) ->
receive
{system, From, Req} ->
#server{parent = Parent, debug = Debug} = Server,
sys:handle_system_msg(Req, From, Parent, ?MODULE, Debug,
[safe, Server, Role, E]);
{'EXIT', _, Reason} = Msg ->
terminate(Reason, Msg, Server, Role, E);
{update_candidates,_,_,_} = Msg ->
safe_loop(Server,Role,E,Msg);
{halt,T,From} = Msg ->
NewE = halting(E,T,From,Server),
From ! {ackLeader,T,self()},
safe_loop(Server,Role,NewE,Msg);
{hasLeader,Ldr,T,_} = Msg when Role == candidate_joining ->
NewE1 = mon_node(E,Ldr,Server),
NewE = NewE1#election{elid = T, leadernode = node(Ldr)},
Ldr ! {isLeader, T, self()},
safe_loop(Server,Role,NewE,Msg);
{hasLeader,Ldr,T,_} = Msg ->
NewE1 = mon_node(E,Ldr,Server),
case ( (E#election.status == elec2) and (E#election.acks /= []) ) of
true ->
lists:foreach(
fun(Node) ->
{Name,Node} ! {hasLeader,Ldr,T,self()}
end,E#election.acks);
false ->
ok
end,
NewE = NewE1#election{elid = T,
status = wait,
leadernode = node(Ldr),
down = E#election.down -- [node(Ldr)],
acks = []},
Ldr ! {isLeader,T,self()},
safe_loop(Server,Role,NewE,Msg);
{isLeader,T,From} = Msg ->
From ! {notLeader,T,self()},
safe_loop(Server,Role,E,Msg);
{notLeader,T,_} = Msg when Role == candidate_joining ->
NewE = case E#election.elid == T of
true ->
joinCluster(E, Server);
false ->
E
end,
safe_loop(Server,Role,NewE,Msg);
{notLeader,T,_} = Msg ->
NewE =
case ((E#election.status == wait) and (E#election.elid == T)) of
true ->
startStage1(E, Server);
false ->
E
end,
safe_loop(Server,Role,NewE,Msg);
{ackLeader,T,From} = Msg ->
NewE =
case ( (E#election.status == elec2) and (E#election.elid == T)
and (E#election.pendack == node(From)) ) of
true ->
continStage2(
E#election{acks = [node(From)|E#election.acks]},
Server);
false ->
E
end,
hasBecomeLeader(NewE,Server,Msg);
{ldr,Synch,T,_,_,From} = Msg when Role == waiting_worker ->
case ( (T == E#election.elid)
and (node(From) == E#election.leadernode)) of
true ->
NewE = E#election{ leader = From, status = worker },
{ok,NewState} = Mod:surrendered(State,Synch,NewE),
loop(Server#server{state = NewState},worker,NewE,Msg);
false ->
%% This should be a VERY special case...
%% But doing nothing is the right thing!
%% A DOWN message should arrive to solve this situation
safe_loop(Server,Role,E,Msg)
end;
{ldr,Synch,T,Workers,Candidates,From} = Msg ->
case ( ( (E#election.status == wait) or (E#election.status == joining) )
and (E#election.elid == T) ) of
true ->
timer:cancel(E#election.cand_timer),
NewE1 = mon_node(E, From, Server),
NewE2 = NewE1#election{leader = From,
leadernode = node(From),
previous_leader = E#election.leader,
worker_nodes = Workers,
candidate_nodes = Candidates,
status = norm,
cand_timer=undefined},
NewE = case Role == candidate_joining of
true ->
mon_nodes(NewE2, lesser(node(),candidates(NewE2)),Server);
false -> NewE2
end,
{ok,NewState} = Mod:surrendered(State,Synch,NewE),
loop(Server#server{state = NewState},surrendered,NewE,Msg);
false ->
safe_loop(Server,Role,E,Msg)
end;
{normQ,T,From} = Msg ->
NewE =
case ( (E#election.status == elec1)
or ( (E#election.status == wait)
and (E#election.elid == T) ) ) of
true ->
NE = halting(E,T,From,Server),
From ! {notNorm,T,self()},
NE;
false ->
E
end,
safe_loop(Server,Role,NewE,Msg);
{notNorm,_,_} = Msg ->
safe_loop(Server,Role,E,Msg);
{workerAlive,T,From} = Msg ->
NewE =
case E#election.leadernode == none of
true ->
%% We should initiate activation,
%% monitor the possible leader!
NE = mon_node(E#election{leadernode = node(From),
elid = T},
From, Server),
From ! {workerIsAlive,T,self()},
NE;
false ->
%% We should acutally ignore this, the present activation
%% will complete or abort first...
E
end,
safe_loop(Server,Role,NewE,Msg);
{workerIsAlive,_,_} = Msg ->
%% If this happens, the activation process should abort
%% This process is no longer the leader!
%% The sender will notice this via a DOWN message
safe_loop(Server,Role,E,Msg);
{election} = Msg ->
%% We're already in an election, so this is likely an old message.
safe_loop(Server, Role, E, Msg);
{heartbeat, _Node} = Msg ->
safe_loop(Server,Role,E,Msg);
{candidate_timer} = Msg ->
NewE =
case E#election.down of
[] ->
timer:cancel(E#election.cand_timer),
E#election{cand_timer = undefined};
Down ->
%% get rid of any queued up candidate_timers, since we just handled one
flush_candidate_timers(),
%% Some of potential master candidate nodes are down.
%% Try to wake them up
F = fun(N) ->
{E#election.name, N} ! {heartbeat, node()}
end,
[F(N) || N <- Down, {ok, up} =/= net_kernel:node_info(N, state)],
E
end,
safe_loop(Server,Role,NewE,Msg);
{checklead, Node} = Msg ->
%% in the very exceptional case when a candidate comes up when the
%% elected leader is *behind* it in the candidate list *and* all nodes
%% before it in the candidate list are up, the candidate will be stuck in
%% the safe_loop forever. This is because gen_leader relies on either
%% one of the nodes being down, or the nodes responding to the heartbeat
%% sent as part of stage1. However, nodes that are up but are NOT the
%% leader do not respond to heartbeats. In this very exceptional case,
%% we send a heartbeat to the leader in response to the checklead it
%% sent us to bootstrap things and get out of this quagmire.
case lists:member(Node,E#election.candidate_nodes) and
(E#election.status == elec1) of
true ->
case ( pos(Node,E#election.candidate_nodes) >
pos(node(),E#election.candidate_nodes) ) of
true ->
{Name, Node} ! {heartbeat, self()};
_ ->
ok
end;
_ ->
ok
end,
safe_loop(Server,Role,E,Msg);
{ldr, 'DOWN', Node} = Msg when Role == waiting_worker ->
NewE =
case Node == E#election.leadernode of
true ->
E#election{leader = none, leadernode = none,
previous_leader = E#election.leader,
status = waiting_worker,
monitored = []};
false ->
E
end,
safe_loop(Server, Role, NewE,Msg);
{ldr, 'DOWN', Node} = Msg when Role == candidate_joining ->
Ldr = E#election.leadernode,
Seed = E#election.seed_node,
case Node of
Seed ->
case net_adm:ping(Ldr) of
pong -> noop;
pang ->
terminate(seed_nodes_down, Msg, Server, Role, E)
end;
Ldr ->
case net_adm:ping(Seed) of
pong ->
NewE = joinCluster(E, Server),
safe_loop(Server, Role, NewE, Msg);
pang ->
terminate(seed_nodes_down, Msg, Server, Role, E)
end
end;
{ldr, 'DOWN', Node} = Msg ->
NewMon = lists:keydelete(Node, 2, E#election.monitored),
NewE =
case lists:member(Node,E#election.candidate_nodes) of
true ->
NewDown = [Node | E#election.down],
E1 = E#election{down = NewDown, monitored = NewMon},
case ( pos(Node,E#election.candidate_nodes) <
pos(node(),E#election.candidate_nodes) ) of
true ->
Lesser = lesser(node(),E#election.candidate_nodes),
LesserIsSubset = (Lesser -- NewDown) == [],
case ((E#election.status == wait)
and (Node == E#election.leadernode)) of
true ->
startStage1(E1, Server);
false ->
case ((E#election.status == elec1) and
LesserIsSubset) of
true ->
startStage2(
E1#election{down = Lesser},
Server);
false ->
E1
end
end;
false ->
case ( (E#election.status == elec2)
and (Node == E#election.pendack) ) of
true ->
continStage2(E1, Server);
false ->
case ( (E#election.status == wait)
and (Node == E#election.leadernode)) of
true ->
startStage1(E1, Server);
false ->
E1
end
end
end
end,
hasBecomeLeader(NewE,Server,Msg)
end.
% this is the regular operation loop. All messages are received,
% unexpected ones are discarded.
loop(#server{parent = Parent,
mod = Mod,
state = State,
debug = Debug} = Server, Role,
#election{name = Name} = E, _PrevMsg) ->
receive
Msg ->
case Msg of
{system, From, Req} ->
sys:handle_system_msg(Req, From, Parent, ?MODULE, Debug,
[normal, Server, Role, E]);
{'EXIT', Parent, Reason} ->
terminate(Reason, Msg, Server, Role, E);
{join, From} ->
From ! {hasLeader,E#election.leader,E#election.elid,self()},
loop(Server,Role,E,Msg);
{update_candidates, T, Candidates, _From} ->
case E#election.elid == T of
true ->
NewE = E#election{candidate_nodes = Candidates},
loop(Server, Role, NewE, Msg);
false ->
loop(Server, Role, E, Msg)
end;
{halt,_,From} ->
From ! {hasLeader,E#election.leader,E#election.elid,self()},
loop(Server,Role,E,Msg);
{hasLeader,_,_,_} ->
loop(Server,Role,E,Msg);
{isLeader,T,From} ->
case (self() == E#election.leader) of
true ->
NewCandidates =
case lists:member(node(From), candidates(E)) of
true -> candidates(E);
false ->
NC = candidates(E) ++ [node(From)],
lists:foreach(
fun(Node) ->
{Name, Node} !
{update_candidates, E#election.elid,
NC, self()}
end, candidates(E) -- lists:flatten([node()],down(E))),
NC
end,
NewDown = E#election.down -- [node(From)],
NewE1 = mon_node(E#election{down = NewDown},
From, Server),
NewE = NewE1#election{candidate_nodes = NewCandidates},
NewState = call_elected(Mod, State, NewE, From),
loop(Server#server{state = NewState},Role,NewE,Msg);
false ->
From ! {notLeader,T,self()},
loop(Server,Role,E,Msg)
end;
{ackLeader,_,_} ->
loop(Server,Role,E,Msg);
{notLeader,_,_} ->
loop(Server,Role,E,Msg);
{ack,_,_} ->
loop(Server,Role,E,Msg);
{ldr,_,_,_,_} ->
loop(Server,Role,E,Msg);
{normQ,_,_} ->
loop(Server,Role,E,Msg);
{notNorm,T,From} ->
case ( (E#election.leader == self())
and (E#election.elid == T) ) of
true ->
NewDown = E#election.down -- [node(From)],
NewE = mon_node(E#election{down = NewDown},
From,Server),
NewState = call_elected(Mod, State, NewE, From),
loop(Server#server{state = NewState},Role,NewE,Msg);
false ->
loop(Server,Role,E,Msg)
end;
{workerAlive,_,_} ->
%% Do nothing if we get this from a new leader
%% We will soon notice that the prev leader has died, and
%%get the same message again when we are back in safe_loop!
loop(Server,Role,E,Msg);
{activateWorker,_,_,_} ->
%% We ignore this, we are already active...
%% It must be an old message!
loop(Server,Role,E,Msg);
{workerIsAlive,T,From} ->
case ((T == E#election.elid) and (self() == E#election.leader)) of
true ->
NewDown = E#election.work_down -- [node(From)],
NewE = mon_node(E#election{work_down = NewDown},
From, Server),
NewState = call_elected(Mod,State,NewE,From),
loop(Server#server{state = NewState},Role,NewE,Msg);
false ->
loop(Server,Role,E,Msg)
end;
{election} ->
%% Told to do an election because of a leader conflict.
E1 = startStage1(E, Server),
safe_loop(Server, candidate, E1, Msg);
{checklead, Node} ->
case (E#election.leadernode == Node) of
true ->
%% Leaders match, nothing to do
loop(Server, Role, E, Msg);
false when E#election.leader == self() ->
%% We're a leader and we disagree with the other
%% leader. Tell everyone else to have an election.
lists:foreach(
fun(N) ->
{Name, N} ! {election}
end, E#election.candidate_nodes),
%% Start participating in the election ourselves.
E1 = startStage1(E, Server),
safe_loop(Server, candidate, E1, Msg);
false ->
%% Not a leader, just wait to be told to do an
%% election, if applicable.
loop(Server, Role, E, Msg)
end;
{send_checklead} ->
case (E#election.leader == self()) of
true ->
case E#election.down of
[] ->
loop(Server, Role, E, Msg);
Down ->
%% For any nodes which are down, send them
%% a message comparing their leader to our
%% own. This allows us to trigger an
%% election after a netsplit is healed.
spawn(?MODULE, send_checkleads, [Name, E#election.cand_timer_int, self(), Down]),
loop(Server, Role, E, Msg)
end;
false ->
loop(Server, Role, E, Msg)
end;
{heartbeat, _Node} ->
case (E#election.leader == self()) of
true ->
Candidates = E#election.down -- [lists:nth(1,E#election.candidate_nodes)],
lists:foreach(
fun(N) ->
Elid = E#election.elid,
{Name,N} ! {normQ,Elid,self()}
end,Candidates),
lists:foreach(
fun(N) ->
Elid = E#election.elid,
{Name,N} ! {workerAlive,Elid,self()}
end,E#election.work_down);
false ->
ok
end,
loop(Server,Role,E,Msg);
{candidate_timer} = Msg ->
NewE =
if E#election.down =:= [] orelse (Role =/= elected andalso E#election.leadernode =/= none) ->
timer:cancel(E#election.cand_timer),
E#election{cand_timer=undefined};
true ->
%% get rid of any queued up candidate_timers,
%% since we just handled one
flush_candidate_timers(),
E
end,
%% This shouldn't happen in the leader - just ignore
loop(Server,Role,NewE,Msg);
{ldr, 'DOWN', Node} = Msg when Role == worker ->
case Node == E#election.leadernode of
true ->
NewE = E#election{ leader = none, leadernode = none,
status = waiting_worker,
monitored = []},
safe_loop(Server, waiting_worker, NewE,Msg);
false ->
loop(Server, Role, E,Msg)
end;
{ldr, 'DOWN', Node} = Msg ->
NewMon = lists:keydelete(Node, 2, E#election.monitored),
case lists:member(Node,E#election.candidate_nodes) of
true ->
NewDown = [Node | E#election.down],
E1 = E#election{down = NewDown, monitored = NewMon},
case (Node == E#election.leadernode) of
true ->
NewE = startStage1(E1, Server),
safe_loop(Server, candidate, NewE,Msg);
false when E#election.leadernode =:= node() ->
%% Serge: call handle_DOWN
{NewState, NewE} =
case (Server#server.mod):handle_DOWN(Node, Server#server.state, E1) of
{ok, NewState1} ->
{NewState1, E1};
{ok, Synch, NewState1} ->
{NewState1, broadcast({from_leader,Synch}, E1)}