-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathglobal.erl
executable file
·2462 lines (2211 loc) · 91.4 KB
/
global.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
%% %CopyrightBegin%
%%
%% Copyright Ericsson AB 1996-2012. All Rights Reserved.
%%
%% 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 online 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.
%%
%% %CopyrightEnd%
%%
-module(global).
-behaviour(gen_server).
%% Global provides global registration of process names. The names are
%% dynamically kept up to date with the entire network. Global can
%% operate in two modes: in a fully connected network, or in a
%% non-fully connected network. In the latter case, the name
%% registration mechanism won't work.
%% As a separate service Global also provides global locks.
%% External exports
-export([start/0, start_link/0, stop/0, sync/0, sync/1,
whereis_name/1, register_name/2,
register_name/3, register_name_external/2, register_name_external/3,
unregister_name_external/1,re_register_name/2, re_register_name/3,
unregister_name/1, registered_names/0, send/2, node_disconnected/1,
set_lock/1, set_lock/2, set_lock/3,
del_lock/1, del_lock/2,
trans/2, trans/3, trans/4,
random_exit_name/3, random_notify_name/3, notify_all_name/3]).
%% Internal exports
-export([init/1, handle_call/3, handle_cast/2, handle_info/2, terminate/2,
code_change/3, resolve_it/4]).
-export([info/0]).
-compile(export_all).
-include_lib("stdlib/include/ms_transform.hrl").
%% Set this variable to 'allow' to allow several names of a process.
%% This is for backward compatibility only; the functionality is broken.
-define(WARN_DUPLICATED_NAME, global_multi_name_action).
%% Undocumented Kernel variable. Set this to 0 (zero) to get the old
%% behaviour.
-define(N_CONNECT_RETRIES, global_connect_retries).
-define(DEFAULT_N_CONNECT_RETRIES, 5).
%%% In certain places in the server, calling io:format hangs everything,
%%% so we'd better use erlang:display/1.
%%% my_tracer is used in testsuites
-define(trace(_), ok).
%%-define(trace(T), (catch my_tracer ! {node(), {line,?LINE}, T})).
%%-define(trace(T), erlang:display({node(), {line,?LINE}, T})).
%-define(trace(T), erlang:display({format, node(), cs(), T})).
%cs() ->
% {_Big, Small, Tiny} = now(),
% (Small rem 100) * 100 + (Tiny div 10000).
%% These are the protocol versions:
%% Vsn 1 is the original protocol.
%% Vsn 2 is enhanced with code to take care of registration of names from
%% non erlang nodes, e.g. C-nodes.
%% Vsn 3 is enhanced with a tag in the synch messages to distinguish
%% different synch sessions from each other, see OTP-2766.
%% Vsn 4 uses a single, permanent, locker process, but works like vsn 3
%% when communicating with vsn 3 nodes. (-R10B)
%% Vsn 5 uses an ordered list of self() and HisTheLocker when locking
%% nodes in the own partition. (R11B-)
%% Current version of global does not support vsn 4 or earlier.
-define(vsn, 5).
-define(debug(_), ok).
%%-define(debug(Term), erlang:display({"global_name_server:",Term})).
%%-----------------------------------------------------------------
%% connect_all = boolean() - true if we are supposed to set up a
%% fully connected net
%% known = [Node] - all nodes known to us
%% synced = [Node] - all nodes that have the same names as us
%% resolvers = [{Node, MyTag, Resolver}] -
%% the tag separating different synch sessions,
%% and the pid of the name resolver process
%% syncers = [pid()] - all current syncers processes
%% node_name = atom() - our node name (can change if distribution
%% is started/stopped dynamically)
%%
%% In addition to these, we keep info about messages arrived in
%% the process dictionary:
%% {pre_connect, Node} = {Vsn, InitMsg} - init_connect msgs that
%% arrived before nodeup
%% {wait_lock, Node} = {exchange, NameList, _NamelistExt} | lock_is_set
%% - see comment below (handle_cast)
%% {save_ops, Node} = {resolved, HisKnown, NamesExt, Res} | [operation()]
%% - save the ops between exchange and resolved
%% {prot_vsn, Node} = Vsn - the exchange protocol version (not used now)
%% {sync_tag_my, Node} = My tag, used at synchronization with Node
%% {sync_tag_his, Node} = The Node's tag, used at synchronization
%% {lock_id, Node} = The resource locking the partitions
%%-----------------------------------------------------------------
-type group_name() :: atom().
-type group_tuple() :: {GroupName :: group_name(), [node()]}.
-record(state, {connect_all :: boolean(),
known = [] :: [group_tuple()],
synced = [] :: [group_tuple()],
resolvers = [],
syncers = [] :: [pid()],
node_name = node() :: node(),
s_group = no_group ::group_name(), %% a quick hack for dyamic creation of a_groups;
the_locker, the_registrar, trace,
global_lock_down = false :: boolean()
}).
-type state() :: #state{}.
%%% There are also ETS tables used for bookkeeping of locks and names
%%% (the first position is the key):
%%%
%%% global_locks (set): {ResourceId, LockRequesterId, [{Pid,RPid,ref()]}
%%% Pid is locking ResourceId, ref() is the monitor ref.
%%% RPid =/= Pid if there is an extra process calling erlang:monitor().
%%% global_names (set): {Name, Pid, Method, RPid, ref()}
%%% Registered names. ref() is the monitor ref.
%%% RPid =/= Pid if there is an extra process calling erlang:monitor().
%%% global_names_ext (set): {Name, Pid, RegNode}
%%% External registered names (C-nodes).
%%% (The RPid:s can be removed when/if erlang:monitor() returns before
%%% trying to connect to the other node.)
%%%
%%% Helper tables:
%%% global_pid_names (bag): {Pid, Name} | {ref(), Name}
%%% Name(s) registered for Pid.
%%% There is one {Pid, Name} and one {ref(), Name} for every Pid.
%%% ref() is the same ref() as in global_names.
%%% global_pid_ids (bag): {Pid, ResourceId} | {ref(), ResourceId}
%%% Resources locked by Pid.
%%% ref() is the same ref() as in global_locks.
%%%
%%% global_pid_names is a 'bag' for backward compatibility.
%%% (Before vsn 5 more than one name could be registered for a process.)
%%%
%%% R11B-3 (OTP-6341): The list of pids in the table 'global_locks'
%%% was replaced by a list of {Pid, Ref}, where Ref is a monitor ref.
%%% It was necessary to use monitors to fix bugs regarding locks that
%%% were never removed. The signal {async_del_lock, ...} has been
%%% kept for backward compatibility. It can be removed later.
%%%
%%% R11B-4 (OTP-6428): Monitors are used for registered names.
%%% The signal {delete_name, ...} has been kept for backward compatibility.
%%% It can be removed later as can the deleter process.
%%% An extra process calling erlang:monitor() is sometimes created.
%%% The new_nodes messages has been augmented with the global lock id.
%%%
%%% R14A (OTP-8527): The deleter process has been removed.
start() ->
gen_server:start({local, global_name_server}, ?MODULE, [], []).
start_link() ->
gen_server:start_link({local, global_name_server}, ?MODULE, [], []).
stop() ->
gen_server:call(global_name_server, stop, infinity).
-spec sync() -> 'ok' | {'error', Reason :: term()}.
sync() ->
case check_sync_nodes() of
{error, _} = Error ->
Error;
SyncNodes ->
gen_server:call(global_name_server, {sync, SyncNodes}, infinity)
end.
-spec sync([node()]) -> 'ok' | {'error', Reason :: term()}.
sync(Nodes) ->
case check_sync_nodes(Nodes) of
{error, _} = Error ->
Error;
SyncNodes ->
gen_server:call(global_name_server, {sync, SyncNodes}, infinity)
end.
-spec send(Name, Msg) -> Pid when
Name :: term(),
Msg :: term(),
Pid :: pid().
send(Name, Msg) ->
case whereis_name(Name) of
Pid when is_pid(Pid) ->
Pid ! Msg,
Pid;
undefined ->
exit({badarg, {Name, Msg}})
end.
%% See OTP-3737.
-spec whereis_name(Name) -> pid() | 'undefined' when
Name :: term().
whereis_name(Name) ->
where(Name).
node_disconnected(Node) ->
global_name_server ! {nodedown, Node}.
%%-----------------------------------------------------------------
%% Method = function(Name, Pid1, Pid2) -> Pid | Pid2 | none
%% Method is called if a name conflict is detected when two nodes
%% are connecting to each other. It is supposed to return one of
%% the Pids or 'none'. If a pid is returned, that pid is
%% registered as Name on all nodes. If 'none' is returned, the
%% Name is unregistered on all nodes. If anything else is returned,
%% the Name is unregistered as well.
%% Method is called once at one of the nodes where the processes reside
%% only. If different Methods are used for the same name, it is
%% undefined which one of them is used.
%% Method blocks the name registration, but does not affect global locking.
%%-----------------------------------------------------------------
-spec register_name(Name, Pid) -> 'yes' | 'no' when
Name :: term(),
Pid :: pid().
register_name(Name, Pid) when is_pid(Pid) ->
register_name(Name, Pid, fun random_exit_name/3).
-type method() :: fun((Name :: term(), Pid :: pid(), Pid2 :: pid()) ->
pid() | 'none').
-spec register_name(Name, Pid, Resolve) -> 'yes' | 'no' when
Name :: term(),
Pid :: pid(),
Resolve :: method().
register_name(Name, Pid, Method) when is_pid(Pid) ->
Fun = fun(Nodes) ->
case (where(Name) =:= undefined) andalso check_dupname(Name, Pid) of
true ->
gen_server:multi_call(Nodes,
global_name_server,
{register, Name, Pid, Method}),
yes;
_ ->
no
end
end,
?trace({register_name, self(), Name, Pid, Method}),
gen_server:call(global_name_server, {registrar, Fun}, infinity).
check_dupname(Name, Pid) ->
case ets:lookup(global_pid_names, Pid) of
[] ->
true;
PidNames ->
case application:get_env(kernel, ?WARN_DUPLICATED_NAME) of
{ok, allow} ->
true;
_ ->
S = "global: ~w registered under several names: ~w\n",
Names = [Name | [Name1 || {_Pid, Name1} <- PidNames]],
error_logger:error_msg(S, [Pid, Names]),
false
end
end.
-spec unregister_name(Name) -> _ when
Name :: term().
unregister_name(Name) ->
case where(Name) of
undefined ->
ok;
_ ->
Fun = fun(Nodes) ->
gen_server:multi_call(Nodes,
global_name_server,
{unregister, Name}),
ok
end,
?trace({unregister_name, self(), Name}),
gen_server:call(global_name_server, {registrar, Fun}, infinity)
end.
-spec re_register_name(Name, Pid) -> 'yes' when
Name :: term(),
Pid :: pid().
re_register_name(Name, Pid) when is_pid(Pid) ->
re_register_name(Name, Pid, fun random_exit_name/3).
-spec re_register_name(Name, Pid, Resolve) -> 'yes' when
Name :: term(),
Pid :: pid(),
Resolve :: method().
re_register_name(Name, Pid, Method) when is_pid(Pid) ->
Fun = fun(Nodes) ->
gen_server:multi_call(Nodes,
global_name_server,
{register, Name, Pid, Method}),
yes
end,
?trace({re_register_name, self(), Name, Pid, Method}),
gen_server:call(global_name_server, {registrar, Fun}, infinity).
-spec registered_names() -> [Name] when
Name :: term().
registered_names() ->
MS = ets:fun2ms(fun({Name,_Pid,_M,_RP,_R}) -> Name end),
ets:select(global_names, MS).
%%-----------------------------------------------------------------
%% The external node (e.g. a C-node) registers the name on an Erlang
%% node which links to the process (an Erlang node has to be used
%% since there is no global_name_server on the C-node). If the Erlang
%% node dies the name is to be unregistered on all nodes. Normally
%% node(Pid) is compared to the node that died, but that does not work
%% for external nodes (the process does not run on the Erlang node
%% that died). Therefore a table of all names registered by external
%% nodes is kept up-to-date on all nodes.
%%
%% Note: if the Erlang node dies an EXIT signal is also sent to the
%% C-node due to the link between the global_name_server and the
%% registered process. [This is why the link has been kept despite
%% the fact that monitors do the job now.]
%%-----------------------------------------------------------------
register_name_external(Name, Pid) when is_pid(Pid) ->
register_name_external(Name, Pid, fun random_exit_name/3).
register_name_external(Name, Pid, Method) when is_pid(Pid) ->
Fun = fun(Nodes) ->
case where(Name) of
undefined ->
gen_server:multi_call(Nodes,
global_name_server,
{register_ext, Name, Pid,
Method, node()}),
yes;
_Pid -> no
end
end,
?trace({register_name_external, self(), Name, Pid, Method}),
gen_server:call(global_name_server, {registrar, Fun}, infinity).
unregister_name_external(Name) ->
unregister_name(Name).
-type id() :: {ResourceId :: term(), LockRequesterId :: term()}.
-spec set_lock(Id) -> boolean() when
Id :: id().
set_lock(Id) ->
set_lock(Id, [node() | nodes()], infinity, 1).
-type retries() :: non_neg_integer() | 'infinity'.
-spec set_lock(Id, Nodes) -> boolean() when
Id :: id(),
Nodes :: [node()].
set_lock(Id, Nodes) ->
set_lock(Id, Nodes, infinity, 1).
-spec set_lock(Id, Nodes, Retries) -> boolean() when
Id :: id(),
Nodes :: [node()],
Retries :: retries().
set_lock(Id, Nodes, Retries) when is_integer(Retries), Retries >= 0 ->
set_lock(Id, Nodes, Retries, 1);
set_lock(Id, Nodes, infinity) ->
set_lock(Id, Nodes, infinity, 1).
set_lock({_ResourceId, _LockRequesterId}, [], _Retries, _Times) ->
true;
set_lock({_ResourceId, _LockRequesterId} = Id, Nodes, Retries, Times) ->
?trace({set_lock,{me,self()},Id,{nodes,Nodes},
{retries,Retries}, {times,Times}}),
case set_lock_on_nodes(Id, Nodes) of
true ->
?trace({set_lock_true, Id}),
true;
false=Reply when Retries =:= 0 ->
Reply;
false ->
random_sleep(Times),
set_lock(Id, Nodes, dec(Retries), Times+1)
end.
-spec del_lock(Id) -> 'true' when
Id :: id().
del_lock(Id) ->
del_lock(Id, [node() | nodes()]).
-spec del_lock(Id, Nodes) -> 'true' when
Id :: id(),
Nodes :: [node()].
del_lock({_ResourceId, _LockRequesterId} = Id, Nodes) ->
?trace({del_lock, {me,self()}, Id, {nodes,Nodes}}),
gen_server:multi_call(Nodes, global_name_server, {del_lock, Id}),
true.
-type trans_fun() :: function() | {module(), atom()}.
-spec trans(Id, Fun) -> Res | aborted when
Id :: id(),
Fun :: trans_fun(),
Res :: term().
trans(Id, Fun) -> trans(Id, Fun, [node() | nodes()], infinity).
-spec trans(Id, Fun, Nodes) -> Res | aborted when
Id :: id(),
Fun :: trans_fun(),
Nodes :: [node()],
Res :: term().
trans(Id, Fun, Nodes) -> trans(Id, Fun, Nodes, infinity).
-spec trans(Id, Fun, Nodes, Retries) -> Res | aborted when
Id :: id(),
Fun :: trans_fun(),
Nodes :: [node()],
Retries :: retries(),
Res :: term().
trans(Id, Fun, Nodes, Retries) ->
case set_lock(Id, Nodes, Retries) of
true ->
try
Fun()
after
del_lock(Id, Nodes)
end;
false ->
aborted
end.
info() ->
gen_server:call(global_name_server, info, infinity).
%%%-----------------------------------------------------------------
%%% Call-back functions from gen_server
%%%-----------------------------------------------------------------
-spec init([]) -> {'ok', state()}.
init([]) ->
process_flag(trap_exit, true),
_ = ets:new(global_locks, [set, named_table, protected]),
_ = ets:new(global_names, [set, named_table, protected]),
_ = ets:new(global_names_ext, [set, named_table, protected]),
_ = ets:new(global_pid_names, [bag, named_table, protected]),
_ = ets:new(global_pid_ids, [bag, named_table, protected]),
%% This is for troubleshooting only.
DoTrace = os:getenv("GLOBAL_HIGH_LEVEL_TRACE") =:= "TRUE",
T0 = case DoTrace of
true ->
send_high_level_trace(),
[];
false ->
no_trace
end,
S = #state{the_locker = start_the_locker(DoTrace),
trace = T0,
the_registrar = start_the_registrar()},
S1 = trace_message(S, {init, node()}, []),
case init:get_argument(connect_all) of
{ok, [["false"]]} ->
{ok, S1#state{connect_all = false}};
_ ->
{ok, S1#state{connect_all = true}}
end.
%%-----------------------------------------------------------------
%% Connection algorithm
%% ====================
%% This algorithm solves the problem with partitioned nets as well.
%%
%% The main idea in the algorithm is that when two nodes connect, they
%% try to set a lock in their own partition (i.e. all nodes already
%% known to them; partitions are not necessarily disjoint). When the
%% lock is set in each partition, these two nodes send each other a
%% list with all registered names in resp partition (*). If no conflict
%% is found, the name tables are just updated. If a conflict is found,
%% a resolve function is called once for each conflict. The result of
%% the resolving is sent to the other node. When the names are
%% exchanged, all other nodes in each partition are informed of the
%% other nodes, and they ping each other to form a fully connected
%% net.
%%
%% A few remarks:
%%
%% (*) When this information is being exchanged, no one is allowed to
%% change the global register table. All calls to register etc are
%% protected by a lock. If a registered process dies during this
%% phase the name is unregistered on the local node immediately,
%% but the unregistration on other nodes will take place when the
%% deleter manages to acquire the lock. This is necessary to
%% prevent names from spreading to nodes where they cannot be
%% deleted.
%%
%% - It is assumed that nodeups and nodedowns arrive in an orderly
%% fashion: for every node, nodeup is followed by nodedown, and vice
%% versa. "Double" nodeups and nodedowns must never occur. It is
%% the responsibility of net_kernel to assure this.
%%
%% - There is always a delay between the termination of a registered
%% process and the removal of the name from Global's tables. This
%% delay can sometimes be quite substantial. Global guarantees that
%% the name will eventually be removed, but there is no
%% synchronization between nodes; the name can be removed from some
%% node(s) long before it is removed from other nodes.
%%
%% - Global cannot handle problems with the distribution very well.
%% Depending on the value of the kernel variable 'net_ticktime' long
%% delays may occur. This does not affect the handling of locks but
%% will block name registration.
%%
%% - Old synch session messages may linger on in the message queue of
%% global_name_server after the sending node has died. The tags of
%% such messages do not match the current tag (if there is one),
%% which makes it possible to discard those messages and cancel the
%% corresponding lock.
%%
%% Suppose nodes A and B connect, and C is connected to A.
%% Here's the algorithm's flow:
%%
%% Node A
%% ------
%% << {nodeup, B}
%% TheLocker ! {nodeup, ..., Node, ...} (there is one locker per node)
%% B ! {init_connect, ..., {..., TheLockerAtA, ...}}
%% << {init_connect, TheLockerAtB}
%% [The lockers try to set the lock]
%% << {lock_is_set, B, ...}
%% [Now, lock is set in both partitions]
%% B ! {exchange, A, Names, ...}
%% << {exchange, B, Names, ...}
%% [solve conflict]
%% B ! {resolved, A, ResolvedA, KnownAtA, ...}
%% << {resolved, B, ResolvedB, KnownAtB, ...}
%% C ! {new_nodes, ResolvedAandB, [B]}
%%
%% Node C
%% ------
%% << {new_nodes, ResolvedOps, NewNodes}
%% [insert Ops]
%% ping(NewNodes)
%% << {nodeup, B}
%% <ignore this one>
%%
%% Several things can disturb this picture.
%%
%% First, the init_connect message may arrive _before_ the nodeup
%% message due to delay in net_kernel. We handle this by keeping track
%% of these messages in the pre_connect variable in our state.
%%
%% Of course we must handle that some node goes down during the
%% connection.
%%
%%-----------------------------------------------------------------
%% Messages in the protocol
%% ========================
%% 1. Between global_name_servers on connecting nodes
%% {init_connect, Vsn, Node, InitMsg}
%% InitMsg = {locker, _Unused, HisKnown, HisTheLocker}
%% {exchange, Node, ListOfNames, _ListOfNamesExt, Tag}
%% {resolved, Node, HisOps, HisKnown, _Unused, ListOfNamesExt, Tag}
%% HisKnown = list of known nodes in Node's partition
%% 2. Between lockers on connecting nodes
%% {his_locker, Pid} (from our global)
%% {lock, Bool} loop until both lockers have lock = true,
%% then send to global_name_server {lock_is_set, Node, Tag}
%% 3. Connecting node's global_name_server informs other nodes in the same
%% partition about hitherto unknown nodes in the other partition
%% {new_nodes, Node, Ops, ListOfNamesExt, NewNodes, ExtraInfo}
%% 4. Between global_name_server and resolver
%% {resolve, NameList, Node} to resolver
%% {exchange_ops, Node, Tag, Ops, Resolved} from resolver
%% 5. sync protocol, between global_name_servers in different partitions
%% {in_sync, Node, IsKnown}
%% sent by each node to all new nodes (Node becomes known to them)
%%-----------------------------------------------------------------
-spec handle_call(term(), {pid(), term()}, state()) ->
{'noreply', state()} |
{'reply', term(), state()} |
{'stop', 'normal', 'stopped', state()}.
handle_call({registrar, Fun}, From, S) ->
S#state.the_registrar ! {trans_all_known, Fun, From},
{noreply, S};
%% The pattern {register,'_','_','_'} is traced by the inviso
%% application. Do not change.
handle_call({register, Name, Pid, Method}, {FromPid, _Tag}, S0) ->
S = ins_name(Name, Pid, Method, FromPid, [], S0),
{reply, yes, S};
handle_call({unregister, Name}, _From, S0) ->
S = delete_global_name2(Name, S0),
{reply, ok, S};
handle_call({register_ext, Name, Pid, Method, RegNode}, {FromPid,_Tag}, S0) ->
S = ins_name_ext(Name, Pid, Method, RegNode, FromPid, [], S0),
{reply, yes, S};
handle_call({set_lock, Lock}, {Pid, _Tag}, S0) ->
{Reply, S} = handle_set_lock(Lock, Pid, S0),
{reply, Reply, S};
handle_call({del_lock, Lock}, {Pid, _Tag}, S0) ->
S = handle_del_lock(Lock, Pid, S0),
{reply, true, S};
handle_call(get_known, _From, S) ->
GrpNodes = S#state.known,
{reply, GrpNodes, S};
handle_call({get_known,Group}, _From, S) ->
GrpNodes = S#state.known,
case lists:keyfind(Group, 1, GrpNodes) of
{Group, Ns} ->
{reply, Ns, S};
false ->
{reply, [], S}
end;
handle_call(get_synced, _From, S) ->
{reply, S#state.synced, S};
handle_call({sync, Nodes}, From, S) ->
%% If we have several global groups, this won't work, since we will
%% do start_sync on a nonempty list of nodes even if the system
%% is quiet.
Pid = start_sync(lists:delete(node(), Nodes) -- S#state.synced, From),
{noreply, S#state{syncers = [Pid | S#state.syncers]}};
handle_call(get_protocol_version, _From, S) ->
{reply, ?vsn, S};
handle_call(get_names_ext, _From, S) ->
{reply, get_names_ext(), S};
handle_call(info, _From, S) ->
{reply, S, S};
%% "High level trace". For troubleshooting only.
handle_call(high_level_trace_start, _From, S) ->
S#state.the_locker ! {do_trace, true},
send_high_level_trace(),
{reply, ok, trace_message(S#state{trace = []}, {init, node()}, [])};
handle_call(high_level_trace_stop, _From, S) ->
#state{the_locker = TheLocker, trace = Trace} = S,
TheLocker ! {do_trace, false},
wait_high_level_trace(),
{reply, Trace, S#state{trace = no_trace}};
handle_call(high_level_trace_get, _From, #state{trace = Trace}=S) ->
{reply, Trace, S#state{trace = []}};
handle_call(stop, _From, S) ->
{stop, normal, stopped, S};
handle_call({set_s_group_name, GroupName}, _From, S) ->
{reply, ok, S#state{s_group=GroupName}};
handle_call(get_s_group_name, _From, S) ->
{reply, S#state.s_group, S};
handle_call({remove_s_group, GroupName}, _From, S) ->
NewS=S#state{known=[{G, Ns}||{G, Ns}<-S#state.known,
G/=GroupName],
synced=[{G, Ns}||{G, Ns}<-S#state.synced,
G/=GroupName]
},
{reply, ok, NewS};
handle_call({remove_s_group_nodes,GroupName, NodesToRm}, _From, S) ->
case lists:member(node(), NodesToRm) of
true ->
NewS=S#state{known=[{G, Ns}||{G, Ns}<-S#state.known,
G/=GroupName],
synced=[{G, Ns}||{G, Ns}<-S#state.synced,
G/=GroupName]
},
{reply, ok, NewS};
false ->
KnownGroupNodes = case lists:keyfind(GroupName,1, S#state.known) of
false -> [];
{_, Ns} -> Ns
end,
NewKnownGroupNodes = KnownGroupNodes -- NodesToRm,
SyncedGroupNodes = case lists:keyfind(GroupName, 1, S#state.synced)of
false -> [];
{_, Ns1} -> Ns1
end,
NewSyncedGroupNodes = SyncedGroupNodes -- NodesToRm,
NewKnown = case NewKnownGroupNodes of
[] -> lists:keydelete(GroupName, 1, KnownGroupNodes);
_ -> lists:keyreplace(GroupName,1, S#state.known,
{GroupName, NewKnownGroupNodes})
end,
NewSynced= case NewSyncedGroupNodes of
[] -> lists:keydelete(GroupName, 1, SyncedGroupNodes);
_ -> lists:keyreplace(GroupName,1, S#state.synced,
{GroupName,NewSyncedGroupNodes})
end,
NewS=S#state{known= NewKnown,
synced=NewSynced
},
{reply, ok, NewS}
end;
handle_call({remove_from_no_group,Node}, _From, S) ->
NewKnown = [ case G of
no_group -> {G, Ns--[Node]};
_ -> {G, Ns}
end
||{G,Ns}<-S#state.known,
{G, Ns} /= {no_group, [Node]}],
NewSynced = [ case G of
no_group -> {G, Ns--[Node]};
_ -> {G, Ns}
end
||{G,Ns}<-S#state.synced,
{G, Ns} /= {no_group, [Node]}],
NewS=S#state{known= NewKnown,
synced=NewSynced
},
{reply, ok, NewS};
handle_call(Request, From, S) ->
error_logger:warning_msg("The global_name_server "
"received an unexpected message:\n"
"handle_call(~p, ~p, _)\n",
[Request, From]),
{noreply, S}.
%%========================================================================
%% init_connect
%%
%%========================================================================
-spec handle_cast(term(), state()) -> {'noreply', state()}.
handle_cast({init_connect, Vsn, Node, InitMsg}, S) ->
%% Sent from global_name_server at Node.
?trace({'####', init_connect, {vsn, Vsn}, {node,Node},{initmsg,InitMsg}}),
case Vsn of
%% It is always the responsibility of newer versions to understand
%% older versions of the protocol.
{HisVsn, HisTag} when HisVsn > ?vsn ->
init_connect(?vsn, Node, InitMsg, HisTag, S#state.resolvers, S);
{HisVsn, HisTag} ->
init_connect(HisVsn, Node, InitMsg, HisTag, S#state.resolvers, S);
%% To be future compatible
Tuple when is_tuple(Tuple) ->
List = tuple_to_list(Tuple),
[_HisVsn, HisTag | _] = List,
%% use own version handling if his is newer.
init_connect(?vsn, Node, InitMsg, HisTag, S#state.resolvers, S);
_ ->
Txt = io_lib:format("Illegal global protocol version ~p Node: ~p\n",
[Vsn, Node]),
error_logger:info_report(lists:flatten(Txt))
end,
{noreply, S};
%%=======================================================================
%% lock_is_set
%%
%% Ok, the lock is now set on both partitions. Send our names to other node.
%%=======================================================================
handle_cast({lock_is_set, Node, MyTag, LockId}, S) ->
%% Sent from the_locker at node().
?trace({'####', lock_is_set , {node,Node}}),
case get({sync_tag_my, Node}) of
MyTag ->
lock_is_set(Node, S#state.resolvers, LockId),
{noreply, S};
_ -> %% Illegal tag, delete the old sync session.
NewS = cancel_locker(Node, S, MyTag),
{noreply, NewS}
end;
%%========================================================================
%% exchange
%%
%% Here the names are checked to detect name clashes.
%%========================================================================
handle_cast({exchange, Node, NameList, _NameExtList, MyTag}, S) ->
%% Sent from global_name_server at Node.
case get({sync_tag_my, Node}) of
MyTag ->
exchange(Node, NameList, S#state.resolvers),
{noreply, S};
_ -> %% Illegal tag, delete the old sync session.
NewS = cancel_locker(Node, S, MyTag),
{noreply, NewS}
end;
%% {exchange_ops, ...} is sent by the resolver process (which then
%% dies). It could happen that {resolved, ...} has already arrived
%% from the other node. In that case we can go ahead and run the
%% resolve operations. Otherwise we have to save the operations and
%% wait for {resolve, ...}. This is very much like {lock_is_set, ...}
%% and {exchange, ...}.
handle_cast({exchange_ops, Group, Node, MyTag, Ops, Resolved}, S0) -> %% added Group by HL;
%% Sent from the resolver for Node at node().
?trace({exchange_ops, {node,Node},{group, Group}, {ops,Ops},{resolved,Resolved},
{mytag,MyTag}}),
S = trace_message(S0, {exit_resolver, Node}, [MyTag]),
case get({sync_tag_my, Node}) of
MyTag ->
%% Known = S#state.known,
Known = case lists:keyfind(Group, 1, S#state.known) of
false -> [];
{Group, Nodes} -> Nodes
end,
?trace({resolved, Group, node(), Resolved, Known,
Known,get_names_ext(),get({sync_tag_his,Node})}),
gen_server:cast({global_name_server, Node},
{resolved, Group, node(), Resolved, Known,
Known,get_names_ext(),get({sync_tag_his,Node})}),
case get({save_ops, Node}) of
{resolved, HisKnown, Names_ext, HisResolved} ->
put({save_ops, Node}, Ops),
NewS = resolved(Group, Node, HisResolved, HisKnown, Names_ext,S),
{noreply, NewS};
undefined ->
put({save_ops, Node}, Ops),
{noreply, S}
end;
_ -> %% Illegal tag, delete the old sync session.
NewS = cancel_locker(Node, S, MyTag),
{noreply, NewS}
end;
%%========================================================================
%% resolved
%%
%% Here the name clashes are resolved.
%%========================================================================
handle_cast({resolved, Group, Node, HisResolved, HisKnown, _HisKnown_v2, %%added Group by HL;
Names_ext, MyTag}, S) ->
%% Sent from global_name_server at Node.
?trace({'####', resolved, {his_resolved,HisResolved}, {node,Node}, {group, Group}}),
case get({sync_tag_my, Node}) of
MyTag ->
%% See the comment at handle_case({exchange_ops, ...}).
case get({save_ops, Node}) of
Ops when is_list(Ops) ->
NewS = resolved(Group, Node, HisResolved, HisKnown, Names_ext, S),
{noreply, NewS};
undefined ->
Resolved = {resolved, HisKnown, Names_ext, HisResolved},
put({save_ops, Node}, Resolved),
{noreply, S}
end;
_ -> %% Illegal tag, delete the old sync session.
NewS = cancel_locker(Node, S, MyTag),
{noreply, NewS}
end;
%%========================================================================
%% new_nodes
%%
%% We get to know the other node's known nodes.
%%========================================================================
handle_cast({new_nodes, Group, Node, Ops, Names_ext, Nodes, ExtraInfo}, S) ->
%% Sent from global_name_server at Node.
?trace({new_nodes, {node,Node},{ops,Ops},{nodes,Nodes},{x,ExtraInfo}}),
NewS = new_nodes(Ops, Group, Node, Names_ext, Nodes, ExtraInfo, S),
{noreply, NewS};
%%========================================================================
%% in_sync
%%
%% We are in sync with this node (from the other node's known world).
%%========================================================================
handle_cast({in_sync, Group, Node, _IsKnown}, S) ->
%% Sent from global_name_server at Node (in the other partition).
?trace({'####', in_sync, {Node, _IsKnown}}),
lists:foreach(fun(Pid) -> Pid ! {synced, [Node]} end, S#state.syncers),
NewS = cancel_locker(Node, S, get({sync_tag_my, Node})),
reset_node_state(Node),
Synced = NewS#state.synced,
NSynced = case lists:keyfind(Group, 1, Synced) of
false ->
[{Group, [Node]}|Synced];
{Group, Ss}->
lists:keyreplace(Group,1, Synced,{Group, lists:usort([Node|Ss])})
end,
NSynced1= case Group of
no_group -> NSynced;
_ -> remove_no_group(NSynced)
end,
{noreply, NewS#state{synced = NSynced1}};
%% Called when Pid on other node crashed
handle_cast({async_del_name, _Name, _Pid}, S) ->
%% Sent from the_deleter at some node in the partition but node() (-R13B)
%% The DOWN message deletes the name.
%% R14A nodes and later do not send async_del_name messages.
{noreply, S};
handle_cast({async_del_lock, _ResourceId, _Pid}, S) ->
%% Sent from global_name_server at some node in the partition but
%% node(). (-R13B)
%% The DOWN message deletes the lock.
%% R14A nodes and later do not send async_del_lock messages.
{noreply, S};
handle_cast(Request, S) ->
error_logger:warning_msg("The global_name_server "
"received an unexpected message:\n"
"handle_cast(~p, _)\n", [Request]),
{noreply, S}.
%%========================================================================
-spec handle_info(term(), state()) ->
{'noreply', state()} | {'stop', term(), state()}.
handle_info({'EXIT', Locker, _Reason}=Exit, #state{the_locker=Locker}=S) ->
{stop, {locker_died,Exit}, S#state{the_locker=undefined}};
handle_info({'EXIT', Registrar, _}=Exit, #state{the_registrar=Registrar}=S) ->
{stop, {registrar_died,Exit}, S#state{the_registrar=undefined}};
handle_info({'EXIT', Pid, _Reason}, S) when is_pid(Pid) ->
?trace({global_EXIT,_Reason,Pid}),
%% The process that died was a synch process started by start_sync
%% or a registered process running on an external node (C-node).
%% Links to external names are ignored here (there are also DOWN
%% signals).
Syncers = lists:delete(Pid, S#state.syncers),
{noreply, S#state{syncers = Syncers}};
handle_info({nodedown, Node}, S) when Node =:= S#state.node_name ->
%% Somebody stopped the distribution dynamically - change
%% references to old node name (Node) to new node name ('nonode@nohost')
{noreply, change_our_node_name(node(), S)};
handle_info({nodedown, Node}, S0) ->
?trace({'####', nodedown, {node,Node}}),
S1 = trace_message(S0, {nodedown, Node}, []),
S = handle_nodedown(Node, S1),
{noreply, S};
handle_info({extra_nodedown, Node}, S0) ->
?trace({'####', extra_nodedown, {node,Node}}),
S1 = trace_message(S0, {extra_nodedown, Node}, []),
S = handle_nodedown(Node, S1),
{noreply, S};
handle_info({nodeup, Node}, S) when Node =:= node() ->
?trace({'####', local_nodeup, {node, Node}}),
%% Somebody started the distribution dynamically - change
%% references to old node name ('nonode@nohost') to Node.
{noreply, change_our_node_name(Node, S)};
handle_info({nodeup, _Group, Node}, S) when Node =:= node() ->
?trace({'####', local_nodeup, {node, Node}}),
%% Somebody started the distribution dynamically - change
%% references to old node name ('nonode@nohost') to Node.
{noreply, change_our_node_name(Node, S)};
handle_info({nodeup, _Node}, S) when not S#state.connect_all ->
{noreply, S};
handle_info({nodeup, _Group, _Node}, S) when not S#state.connect_all ->
{noreply, S};
handle_info({nodeup, Node}, S0) when S0#state.connect_all ->
?debug({nodeup, Node}),
handle_node_up(no_group, Node, S0);
handle_info({nodeup, Group, Node}, S0) when S0#state.connect_all ->
?debug({nodeup, Group, Node}),
handle_node_up(Group, Node, S0);
handle_info({whereis, Name, From}, S) ->
do_whereis(Name, From),
{noreply, S};
handle_info(known, S) ->
io:format(">>>> ~p\n",[S#state.known]),
{noreply, S};
%% "High level trace". For troubleshooting only.
handle_info(high_level_trace, S) ->
case S of
#state{trace = [{Node, _Time, _M, Nodes, _X} | _]} ->
send_high_level_trace(),