forked from huiqing/s_group
-
Notifications
You must be signed in to change notification settings - Fork 0
/
net_kernel.erl
1570 lines (1377 loc) · 44.1 KB
/
net_kernel.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-2011. 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(net_kernel).
-behaviour(gen_server).
-define(nodedown(N, State), verbose({?MODULE, ?LINE, nodedown, N}, 1, State)).
-define(nodeup(N, State), verbose({?MODULE, ?LINE, nodeup, N}, 1, State)).
%%-define(dist_debug, true).
%-define(DBG,erlang:display([?MODULE,?LINE])).
-ifdef(dist_debug).
-define(debug(Term), erlang:display(Term)).
-else.
-define(debug(Term), ok).
-endif.
-ifdef(DEBUG).
-define(connect_failure(Node,Term),
io:format("Net Kernel 2: Failed connection to node ~p, reason ~p~n",
[Node,Term])).
-else.
-define(connect_failure(Node,Term),noop).
-endif.
%% Default ticktime change transition period in seconds
-define(DEFAULT_TRANSITION_PERIOD, 60).
%-define(TCKR_DBG, 1).
-ifdef(TCKR_DBG).
-define(tckr_dbg(X), erlang:display({?LINE, X})).
-else.
-define(tckr_dbg(X), ok).
-endif.
%% User Interface Exports
-export([start/1, start_link/1, stop/0,
kernel_apply/3,
monitor_nodes/1,
monitor_nodes/2,
longnames/0,
allow/1,
protocol_childspecs/0,
epmd_module/0]).
-export([connect/1, disconnect/1, hidden_connect/1, passive_cnct/1]).
-export([connect_node/1, hidden_connect_node/1]). %% explicit connect
-export([set_net_ticktime/1, set_net_ticktime/2, get_net_ticktime/0]).
-export([node_info/1, node_info/2, nodes_info/0,
connecttime/0,
i/0, i/1, verbose/1]).
-export([publish_on_node/1, update_publish_nodes/1]).
%% Internal Exports
-export([do_spawn/3,
spawn_func/6,
ticker/2,
ticker_loop/2,
aux_ticker/4]).
-export([init/1,handle_call/3,handle_cast/2,handle_info/2,
terminate/2,code_change/3]).
-export([passive_connect_monitor/2]).
-import(error_logger,[error_msg/2]).
-record(state, {
name, %% The node name
node, %% The node name including hostname
type, %% long or short names
tick, %% tick information
connecttime, %% the connection setuptime.
connections, %% table of connections
conn_owners = [], %% List of connection owner pids,
pend_owners = [], %% List of potential owners
listen, %% list of #listen
allowed, %% list of allowed nodes in a restricted system
verbose = 0, %% level of verboseness
publish_on_nodes = undefined
}).
-record(listen, {
listen, %% listen pid
accept, %% accepting pid
address, %% #net_address
module %% proto module
}).
-define(LISTEN_ID, #listen.listen).
-define(ACCEPT_ID, #listen.accept).
-record(connection, {
node, %% remote node name
state, %% pending | up | up_pending
owner, %% owner pid
pending_owner, %% possible new owner
address, %% #net_address
waiting = [], %% queued processes
type %% normal | hidden
}).
-record(barred_connection, {
node %% remote node name
}).
-record(tick, {ticker, %% ticker : pid()
time %% Ticktime in milli seconds : integer()
}).
-record(tick_change, {ticker, %% Ticker : pid()
time, %% Ticktime in milli seconds : integer()
how %% What type of change : atom()
}).
%% Default connection setup timeout in milliseconds.
%% This timeout is set for every distributed action during
%% the connection setup.
-define(SETUPTIME, 7000).
-include("../include/net_address.hrl").
%% Interface functions
kernel_apply(M,F,A) -> request({apply,M,F,A}).
-spec allow(Nodes) -> ok | error when
Nodes :: [node()].
allow(Nodes) -> request({allow, Nodes}).
longnames() -> request(longnames).
-spec stop() -> ok | {error, Reason} when
Reason :: not_allowed | not_found.
stop() -> erl_distribution:stop().
node_info(Node) -> get_node_info(Node).
node_info(Node, Key) -> get_node_info(Node, Key).
nodes_info() -> get_nodes_info().
i() -> print_info().
i(Node) -> print_info(Node).
verbose(Level) when is_integer(Level) ->
request({verbose, Level}).
-spec set_net_ticktime(NetTicktime, TransitionPeriod) -> Res when
NetTicktime :: pos_integer(),
TransitionPeriod :: non_neg_integer(),
Res :: unchanged
| change_initiated
| {ongoing_change_to, NewNetTicktime},
NewNetTicktime :: pos_integer().
set_net_ticktime(T, TP) when is_integer(T), T > 0, is_integer(TP), TP >= 0 ->
ticktime_res(request({new_ticktime, T*250, TP*1000})).
-spec set_net_ticktime(NetTicktime) -> Res when
NetTicktime :: pos_integer(),
Res :: unchanged
| change_initiated
| {ongoing_change_to, NewNetTicktime},
NewNetTicktime :: pos_integer().
set_net_ticktime(T) when is_integer(T) ->
set_net_ticktime(T, ?DEFAULT_TRANSITION_PERIOD).
-spec get_net_ticktime() -> Res when
Res :: NetTicktime | {ongoing_change_to, NetTicktime} | ignored,
NetTicktime :: pos_integer().
get_net_ticktime() ->
ticktime_res(request(ticktime)).
%% The monitor_nodes() feature has been moved into the emulator.
%% The feature is reached via (intentionally) undocumented process
%% flags (we may want to move it elsewhere later). In order to easily
%% be backward compatible, errors are created here when process_flag()
%% fails.
-spec monitor_nodes(Flag) -> ok | Error when
Flag :: boolean(),
Error :: error | {error, term()}.
monitor_nodes(Flag) ->
case catch process_flag(monitor_nodes, Flag) of
true -> ok;
false -> ok;
_ -> mk_monitor_nodes_error(Flag, [])
end.
-spec monitor_nodes(Flag, Options) -> ok | Error when
Flag :: boolean(),
Options :: [Option],
Option :: {node_type, NodeType}
| nodedown_reason,
NodeType :: visible | hidden | all,
Error :: error | {error, term()}.
monitor_nodes(Flag, Opts) ->
case catch process_flag({monitor_nodes, Opts}, Flag) of
true -> ok;
false -> ok;
_ -> mk_monitor_nodes_error(Flag, Opts)
end.
%% ...
ticktime_res({A, I}) when is_atom(A), is_integer(I) -> {A, I div 250};
ticktime_res(I) when is_integer(I) -> I div 250;
ticktime_res(A) when is_atom(A) -> A.
%% Called though BIF's
connect(Node) -> do_connect(Node, normal, false).
%%% Long timeout if blocked (== barred), only affects nodes with
%%% {dist_auto_connect, once} set.
passive_cnct(Node) -> do_connect(Node, normal, true).
disconnect(Node) -> request({disconnect, Node}).
%% connect but not seen
hidden_connect(Node) -> do_connect(Node, hidden, false).
%% Should this node publish itself on Node?
publish_on_node(Node) when is_atom(Node) ->
request({publish_on_node, Node}).
%% Update publication list
update_publish_nodes(Ns) ->
request({update_publish_nodes, Ns}).
-spec connect_node(Node) -> boolean() | ignored when
Node :: node().
%% explicit connects
connect_node(Node) when is_atom(Node) ->
request({connect, normal, Node}).
hidden_connect_node(Node) when is_atom(Node) ->
request({connect, hidden, Node}).
do_connect(Node, Type, WaitForBarred) -> %% Type = normal | hidden
case catch ets:lookup(sys_dist, Node) of
{'EXIT', _} ->
?connect_failure(Node,{table_missing, sys_dist}),
false;
[#barred_connection{}] ->
case WaitForBarred of
false ->
false;
true ->
Pid = spawn(?MODULE,passive_connect_monitor,[self(),Node]),
receive
{Pid, true} ->
%%io:format("Net Kernel: barred connection (~p) "
%% "connected from other end.~n",[Node]),
true;
{Pid, false} ->
?connect_failure(Node,{barred_connection,
ets:lookup(sys_dist, Node)}),
%%io:format("Net Kernel: barred connection (~p) "
%% "- failure.~n",[Node]),
false
end
end;
Else ->
case application:get_env(kernel, dist_auto_connect) of
{ok, never} ->
?connect_failure(Node,{dist_auto_connect,never}),
false;
% This might happen due to connection close
% not beeing propagated to user space yet.
% Save the day by just not connecting...
{ok, once} when Else =/= [],
(hd(Else))#connection.state =:= up ->
?connect_failure(Node,{barred_connection,
ets:lookup(sys_dist, Node)}),
false;
_ ->
request({connect, Type, Node})
end
end.
passive_connect_monitor(Parent, Node) ->
monitor_nodes(true,[{node_type,all}]),
case lists:member(Node,nodes([connected])) of
true ->
monitor_nodes(false,[{node_type,all}]),
Parent ! {self(),true};
_ ->
Ref = make_ref(),
Tref = erlang:send_after(connecttime(),self(),Ref),
receive
Ref ->
monitor_nodes(false,[{node_type,all}]),
Parent ! {self(), false};
{nodeup,Node,_} ->
monitor_nodes(false,[{node_type,all}]),
erlang:cancel_timer(Tref),
Parent ! {self(),true}
end
end.
%% If the net_kernel isn't running we ignore all requests to the
%% kernel, thus basically accepting them :-)
request(Req) ->
case whereis(net_kernel) of
P when is_pid(P) ->
gen_server:call(net_kernel,Req,infinity);
_ -> ignored
end.
%% This function is used to dynamically start the
%% distribution.
start(Args) ->
erl_distribution:start(Args).
%% This is the main startup routine for net_kernel
%% The defaults are longnames and a ticktime of 15 secs to the tcp_drv.
start_link([Name]) ->
start_link([Name, longnames]);
start_link([Name, LongOrShortNames]) ->
start_link([Name, LongOrShortNames, 15000]);
start_link([Name, LongOrShortNames, Ticktime]) ->
case gen_server:start_link({local, net_kernel}, net_kernel,
{Name, LongOrShortNames, Ticktime}, []) of
{ok, Pid} ->
{ok, Pid};
{error, {already_started, Pid}} ->
{ok, Pid};
_Error ->
exit(nodistribution)
end.
%% auth:get_cookie should only be able to return an atom
%% tuple cookies are unknowns
init({Name, LongOrShortNames, TickT}) ->
process_flag(trap_exit,true),
case init_node(Name, LongOrShortNames) of
{ok, Node, Listeners} ->
process_flag(priority, max),
Ticktime = to_integer(TickT),
Ticker = spawn_link(net_kernel, ticker, [self(), Ticktime]),
{ok, #state{name = Name,
node = Node,
type = LongOrShortNames,
tick = #tick{ticker = Ticker, time = Ticktime},
connecttime = connecttime(),
connections =
ets:new(sys_dist,[named_table,
protected,
{keypos, 2}]),
listen = Listeners,
allowed = [],
verbose = 0
}};
Error ->
{stop, Error}
end.
%% ------------------------------------------------------------
%% handle_call.
%% ------------------------------------------------------------
%%
%% Set up a connection to Node.
%% The response is delayed until the connection is up and
%% running.
%%
handle_call({connect, _, Node}, From, State) when Node =:= node() ->
async_reply({reply, true, State}, From);
handle_call({connect, Type, Node}, From, State) ->
verbose({connect, Type, Node}, 1, State),
case ets:lookup(sys_dist, Node) of
[Conn] when Conn#connection.state =:= up ->
async_reply({reply, true, State}, From);
[Conn] when Conn#connection.state =:= pending ->
Waiting = Conn#connection.waiting,
ets:insert(sys_dist, Conn#connection{waiting = [From|Waiting]}),
{noreply, State};
[Conn] when Conn#connection.state =:= up_pending ->
Waiting = Conn#connection.waiting,
ets:insert(sys_dist, Conn#connection{waiting = [From|Waiting]}),
{noreply, State};
_ ->
case setup(Node,Type,From,State) of
{ok, SetupPid} ->
Owners = [{SetupPid, Node} | State#state.conn_owners],
{noreply,State#state{conn_owners=Owners}};
_ ->
?connect_failure(Node, {setup_call, failed}),
async_reply({reply, false, State}, From)
end
end;
%%
%% Close the connection to Node.
%%
handle_call({disconnect, Node}, From, State) when Node =:= node() ->
async_reply({reply, false, State}, From);
handle_call({disconnect, Node}, From, State) ->
verbose({disconnect, Node}, 1, State),
{Reply, State1} = do_disconnect(Node, State),
async_reply({reply, Reply, State1}, From);
%%
%% The spawn/4 BIF ends up here.
%%
handle_call({spawn,M,F,A,Gleader},{From,Tag},State) when is_pid(From) ->
do_spawn([no_link,{From,Tag},M,F,A,Gleader],[],State);
%%
%% The spawn_link/4 BIF ends up here.
%%
handle_call({spawn_link,M,F,A,Gleader},{From,Tag},State) when is_pid(From) ->
do_spawn([link,{From,Tag},M,F,A,Gleader],[],State);
%%
%% The spawn_opt/5 BIF ends up here.
%%
handle_call({spawn_opt,M,F,A,O,L,Gleader},{From,Tag},State) when is_pid(From) ->
do_spawn([L,{From,Tag},M,F,A,Gleader],O,State);
%%
%% Only allow certain nodes.
%%
handle_call({allow, Nodes}, From, State) ->
case all_atoms(Nodes) of
true ->
Allowed = State#state.allowed,
async_reply({reply,ok,State#state{allowed = Allowed ++ Nodes}},
From);
false ->
async_reply({reply,error,State}, From)
end;
%%
%% authentication, used by auth. Simply works as this:
%% if the message comes through, the other node IS authorized.
%%
handle_call({is_auth, _Node}, From, State) ->
async_reply({reply,yes,State}, From);
%%
%% Not applicable any longer !?
%%
handle_call({apply,_Mod,_Fun,_Args}, {From,Tag}, State)
when is_pid(From), node(From) =:= node() ->
async_gen_server_reply({From,Tag}, not_implemented),
% Port = State#state.port,
% catch apply(Mod,Fun,[Port|Args]),
{noreply,State};
handle_call(longnames, From, State) ->
async_reply({reply, get(longnames), State}, From);
handle_call({update_publish_nodes, Ns}, From, State) ->
async_reply({reply, ok, State#state{publish_on_nodes = Ns}}, From);
handle_call({publish_on_node, Node}, From, State) ->
NewState = case State#state.publish_on_nodes of
undefined ->
State#state{publish_on_nodes =
s_group:publish_on_nodes()};
_ ->
State
end,
Publish = case NewState#state.publish_on_nodes of
all ->
true;
Nodes ->
lists:member(Node, Nodes)
end,
async_reply({reply, Publish, NewState}, From);
handle_call({verbose, Level}, From, State) ->
async_reply({reply, State#state.verbose, State#state{verbose = Level}},
From);
%%
%% Set new ticktime
%%
%% The tick field of the state contains either a #tick{} or a
%% #tick_change{} record if the ticker process has been upgraded;
%% otherwise, an integer or an atom.
handle_call(ticktime, From, #state{tick = #tick{time = T}} = State) ->
async_reply({reply, T, State}, From);
handle_call(ticktime, From, #state{tick = #tick_change{time = T}} = State) ->
async_reply({reply, {ongoing_change_to, T}, State}, From);
handle_call({new_ticktime,T,_TP}, From, #state{tick = #tick{time = T}} = State) ->
?tckr_dbg(no_tick_change),
async_reply({reply, unchanged, State}, From);
handle_call({new_ticktime,T,TP}, From, #state{tick = #tick{ticker = Tckr,
time = OT}} = State) ->
?tckr_dbg(initiating_tick_change),
start_aux_ticker(T, OT, TP),
How = case T > OT of
true ->
?tckr_dbg(longer_ticktime),
Tckr ! {new_ticktime,T},
longer;
false ->
?tckr_dbg(shorter_ticktime),
shorter
end,
async_reply({reply, change_initiated,
State#state{tick = #tick_change{ticker = Tckr,
time = T,
how = How}}}, From);
handle_call({new_ticktime,_T,_TP},
From,
#state{tick = #tick_change{time = T}} = State) ->
async_reply({reply, {ongoing_change_to, T}, State}, From);
handle_call(_Msg, _From, State) ->
{noreply, State}.
%% ------------------------------------------------------------
%% handle_cast.
%% ------------------------------------------------------------
handle_cast(_, State) ->
{noreply,State}.
%% ------------------------------------------------------------
%% code_change.
%% ------------------------------------------------------------
code_change(_OldVsn, State, _Extra) ->
{ok,State}.
%% ------------------------------------------------------------
%% terminate.
%% ------------------------------------------------------------
terminate(no_network, State) ->
lists:foreach(
fun({Node, Type}) ->
case Type of
normal -> ?nodedown(Node, State);
_ -> ok
end
end, get_up_nodes() ++ [{node(), normal}]);
terminate(_Reason, State) ->
lists:foreach(
fun(#listen {listen = Listen,module = Mod}) ->
Mod:close(Listen)
end, State#state.listen),
lists:foreach(
fun({Node, Type}) ->
case Type of
normal -> ?nodedown(Node, State);
_ -> ok
end
end, get_up_nodes() ++ [{node(), normal}]).
%% ------------------------------------------------------------
%% handle_info.
%% ------------------------------------------------------------
%%
%% accept a new connection.
%%
handle_info({accept,AcceptPid,Socket,Family,Proto}, State) ->
MyNode = State#state.node,
case get_proto_mod(Family,Proto,State#state.listen) of
{ok, Mod} ->
Pid = Mod:accept_connection(AcceptPid,
Socket,
MyNode,
State#state.allowed,
State#state.connecttime),
AcceptPid ! {self(), controller, Pid},
{noreply,State};
_ ->
AcceptPid ! {self(), unsupported_protocol},
{noreply, State}
end;
%%
%% A node has successfully been connected.
%%
handle_info({SetupPid, {nodeup,Node,Address,Type,Immediate}},
State) ->
case {Immediate, ets:lookup(sys_dist, Node)} of
{true, [Conn]} when Conn#connection.state =:= pending,
Conn#connection.owner =:= SetupPid ->
ets:insert(sys_dist, Conn#connection{state = up,
address = Address,
waiting = [],
type = Type}),
SetupPid ! {self(), inserted},
reply_waiting(Node,Conn#connection.waiting, true),
{noreply, State};
_ ->
SetupPid ! {self(), bad_request},
{noreply, State}
end;
%%
%% Mark a node as pending (accept) if not busy.
%%
handle_info({AcceptPid, {accept_pending,MyNode,Node,Address,Type}}, State) ->
case ets:lookup(sys_dist, Node) of
[#connection{state=pending}=Conn] ->
if
MyNode > Node ->
AcceptPid ! {self(),{accept_pending,nok_pending}},
{noreply,State};
true ->
%%
%% A simultaneous connect has been detected and we want to
%% change pending process.
%%
OldOwner = Conn#connection.owner,
?debug({net_kernel, remark, old, OldOwner, new, AcceptPid}),
exit(OldOwner, remarked),
receive
{'EXIT', OldOwner, _} ->
true
end,
Owners = lists:keyreplace(OldOwner,
1,
State#state.conn_owners,
{AcceptPid, Node}),
ets:insert(sys_dist, Conn#connection{owner = AcceptPid}),
AcceptPid ! {self(),{accept_pending,ok_pending}},
State1 = State#state{conn_owners=Owners},
{noreply,State1}
end;
[#connection{state=up}=Conn] ->
AcceptPid ! {self(), {accept_pending, up_pending}},
ets:insert(sys_dist, Conn#connection { pending_owner = AcceptPid,
state = up_pending }),
Pend = [{AcceptPid, Node} | State#state.pend_owners ],
{noreply, State#state { pend_owners = Pend }};
[#connection{state=up_pending}] ->
AcceptPid ! {self(), {accept_pending, already_pending}},
{noreply, State};
_ ->
ets:insert(sys_dist, #connection{node = Node,
state = pending,
owner = AcceptPid,
address = Address,
type = Type}),
AcceptPid ! {self(),{accept_pending,ok}},
Owners = [{AcceptPid,Node} | State#state.conn_owners],
{noreply, State#state{conn_owners = Owners}}
end;
handle_info({SetupPid, {is_pending, Node}}, State) ->
Reply = lists:member({SetupPid,Node},State#state.conn_owners),
SetupPid ! {self(), {is_pending, Reply}},
{noreply, State};
%%
%% Handle different types of process terminations.
%%
handle_info({'EXIT', From, Reason}, State) when is_pid(From) ->
verbose({'EXIT', From, Reason}, 1, State),
handle_exit(From, Reason, State);
%%
%% Handle badcookie and badname messages !
%%
handle_info({From,registered_send,To,Mess},State) ->
send(From,To,Mess),
{noreply,State};
%% badcookies SHOULD not be sent
%% (if someone does erlang:set_cookie(node(),foo) this may be)
handle_info({From,badcookie,_To,_Mess}, State) ->
error_logger:error_msg("~n** Got OLD cookie from ~w~n",
[getnode(From)]),
{_Reply, State1} = do_disconnect(getnode(From), State),
{noreply,State1};
%%
%% Tick all connections.
%%
handle_info(tick, State) ->
?tckr_dbg(tick),
lists:foreach(fun({Pid,_Node}) -> Pid ! {self(), tick} end,
State#state.conn_owners),
{noreply,State};
handle_info(aux_tick, State) ->
?tckr_dbg(aux_tick),
lists:foreach(fun({Pid,_Node}) -> Pid ! {self(), aux_tick} end,
State#state.conn_owners),
{noreply,State};
handle_info(transition_period_end,
#state{tick = #tick_change{ticker = Tckr,
time = T,
how = How}} = State) ->
?tckr_dbg(transition_period_ended),
case How of
shorter -> Tckr ! {new_ticktime, T};
_ -> done
end,
{noreply,State#state{tick = #tick{ticker = Tckr, time = T}}};
handle_info(X, State) ->
error_msg("Net kernel got ~w~n",[X]),
{noreply,State}.
%% -----------------------------------------------------------
%% Handle exit signals.
%% We have 6 types of processes to handle.
%%
%% 1. The Listen process.
%% 2. The Accept process.
%% 3. Connection owning processes.
%% 4. The ticker process.
%% (5. Garbage pid.)
%%
%% The process type function that handled the process throws
%% the handle_info return value !
%% -----------------------------------------------------------
handle_exit(Pid, Reason, State) ->
catch do_handle_exit(Pid, Reason, State).
do_handle_exit(Pid, Reason, State) ->
listen_exit(Pid, State),
accept_exit(Pid, State),
conn_own_exit(Pid, Reason, State),
pending_own_exit(Pid, State),
ticker_exit(Pid, State),
{noreply,State}.
listen_exit(Pid, State) ->
case lists:keymember(Pid, ?LISTEN_ID, State#state.listen) of
true ->
error_msg("** Netkernel terminating ... **\n", []),
throw({stop,no_network,State});
false ->
false
end.
accept_exit(Pid, State) ->
Listen = State#state.listen,
case lists:keysearch(Pid, ?ACCEPT_ID, Listen) of
{value, ListenR} ->
ListenS = ListenR#listen.listen,
Mod = ListenR#listen.module,
AcceptPid = Mod:accept(ListenS),
L = lists:keyreplace(Pid, ?ACCEPT_ID, Listen,
ListenR#listen{accept = AcceptPid}),
throw({noreply, State#state{listen = L}});
_ ->
false
end.
conn_own_exit(Pid, Reason, State) ->
Owners = State#state.conn_owners,
case lists:keysearch(Pid, 1, Owners) of
{value, {Pid, Node}} ->
throw({noreply, nodedown(Pid, Node, Reason, State)});
_ ->
false
end.
pending_own_exit(Pid, State) ->
Pend = State#state.pend_owners,
case lists:keysearch(Pid, 1, Pend) of
{value, {Pid, Node}} ->
NewPend = lists:keydelete(Pid, 1, Pend),
State1 = State#state { pend_owners = NewPend },
case get_conn(Node) of
{ok, Conn} when Conn#connection.state =:= up_pending ->
reply_waiting(Node,Conn#connection.waiting, true),
Conn1 = Conn#connection { state = up,
waiting = [],
pending_owner = undefined },
ets:insert(sys_dist, Conn1);
_ ->
ok
end,
throw({noreply, State1});
_ ->
false
end.
ticker_exit(Pid, #state{tick = #tick{ticker = Pid, time = T} = Tck} = State) ->
Tckr = restart_ticker(T),
throw({noreply, State#state{tick = Tck#tick{ticker = Tckr}}});
ticker_exit(Pid, #state{tick = #tick_change{ticker = Pid,
time = T} = TckCng} = State) ->
Tckr = restart_ticker(T),
throw({noreply, State#state{tick = TckCng#tick_change{ticker = Tckr}}});
ticker_exit(_, _) ->
false.
%% -----------------------------------------------------------
%% A node has gone down !!
%% nodedown(Owner, Node, Reason, State) -> State'
%% -----------------------------------------------------------
nodedown(Owner, Node, Reason, State) ->
case get_conn(Node) of
{ok, Conn} ->
nodedown(Conn, Owner, Node, Reason, Conn#connection.type, State);
_ ->
State
end.
get_conn(Node) ->
case ets:lookup(sys_dist, Node) of
[Conn = #connection{}] -> {ok, Conn};
_ -> error
end.
nodedown(Conn, Owner, Node, Reason, Type, OldState) ->
Owners = lists:keydelete(Owner, 1, OldState#state.conn_owners),
State = OldState#state{conn_owners = Owners},
case Conn#connection.state of
pending when Conn#connection.owner =:= Owner ->
pending_nodedown(Conn, Node, Type, State);
up when Conn#connection.owner =:= Owner ->
up_nodedown(Conn, Node, Reason, Type, State);
up_pending when Conn#connection.owner =:= Owner ->
up_pending_nodedown(Conn, Node, Reason, Type, State);
_ ->
OldState
end.
pending_nodedown(Conn, Node, Type, State) ->
% Don't bar connections that have never been alive
%mark_sys_dist_nodedown(Node),
% - instead just delete the node:
ets:delete(sys_dist, Node),
reply_waiting(Node,Conn#connection.waiting, false),
case Type of
normal ->
?nodedown(Node, State);
_ ->
ok
end,
State.
up_pending_nodedown(Conn, Node, _Reason, _Type, State) ->
AcceptPid = Conn#connection.pending_owner,
Owners = State#state.conn_owners,
Pend = lists:keydelete(AcceptPid, 1, State#state.pend_owners),
Conn1 = Conn#connection { owner = AcceptPid,
pending_owner = undefined,
state = pending },
ets:insert(sys_dist, Conn1),
AcceptPid ! {self(), pending},
State#state{conn_owners = [{AcceptPid,Node}|Owners], pend_owners = Pend}.
up_nodedown(_Conn, Node, _Reason, Type, State) ->
mark_sys_dist_nodedown(Node),
case Type of
normal -> ?nodedown(Node, State);
_ -> ok
end,
State.
mark_sys_dist_nodedown(Node) ->
case application:get_env(kernel, dist_auto_connect) of
{ok, once} ->
ets:insert(sys_dist, #barred_connection{node = Node});
_ ->
ets:delete(sys_dist, Node)
end.
%% -----------------------------------------------------------
%% End handle_exit/2 !!
%% -----------------------------------------------------------
%% -----------------------------------------------------------
%% monitor_nodes/[1,2] errors
%% -----------------------------------------------------------
check_opt(Opt, Opts) ->
check_opt(Opt, Opts, false, []).
check_opt(_Opt, [], false, _OtherOpts) ->
false;
check_opt(_Opt, [], {true, ORes}, OtherOpts) ->
{true, ORes, OtherOpts};
check_opt(Opt, [Opt|RestOpts], false, OtherOpts) ->
check_opt(Opt, RestOpts, {true, Opt}, OtherOpts);
check_opt(Opt, [Opt|RestOpts], {true, Opt} = ORes, OtherOpts) ->
check_opt(Opt, RestOpts, ORes, OtherOpts);
check_opt({Opt, value}=TOpt,
[{Opt, _Val}=ORes|RestOpts],
false,
OtherOpts) ->
check_opt(TOpt, RestOpts, {true, ORes}, OtherOpts);
check_opt({Opt, value}=TOpt,
[{Opt, _Val}=ORes|RestOpts],
{true, ORes}=TORes,
OtherOpts) ->
check_opt(TOpt, RestOpts, TORes, OtherOpts);
check_opt({Opt, value},
[{Opt, _Val} = ORes1| _RestOpts],
{true, {Opt, _OtherVal} = ORes2},
_OtherOpts) ->
throw({error, {option_value_mismatch, [ORes1, ORes2]}});
check_opt(Opt, [OtherOpt | RestOpts], TORes, OtherOpts) ->
check_opt(Opt, RestOpts, TORes, [OtherOpt | OtherOpts]).
check_options(Opts) when is_list(Opts) ->
RestOpts1 = case check_opt({node_type, value}, Opts) of
{true, {node_type,Type}, RO1} when Type =:= visible;
Type =:= hidden;
Type =:= all ->
RO1;
{true, {node_type, _Type} = Opt, _RO1} ->
throw({error, {bad_option_value, Opt}});
false ->
Opts
end,
RestOpts2 = case check_opt(nodedown_reason, RestOpts1) of
{true, nodedown_reason, RO2} ->
RO2;
false ->
RestOpts1
end,
case RestOpts2 of
[] ->
%% This should never happen since we only call this function
%% when we know there is an error in the option list
{error, internal_error};
_ ->
{error, {unknown_options, RestOpts2}}
end;
check_options(Opts) ->
{error, {options_not_a_list, Opts}}.
mk_monitor_nodes_error(Flag, _Opts) when Flag =/= true, Flag =/= false ->
error;
mk_monitor_nodes_error(_Flag, Opts) ->
case catch check_options(Opts) of
{error, _} = Error ->
Error;
UnexpectedError ->
{error, {internal_error, UnexpectedError}}
end.
% -------------------------------------------------------------
do_disconnect(Node, State) ->
case ets:lookup(sys_dist, Node) of
[Conn] when Conn#connection.state =:= up ->
disconnect_pid(Conn#connection.owner, State);
[Conn] when Conn#connection.state =:= up_pending ->
disconnect_pid(Conn#connection.owner, State);
_ ->
{false, State}
end.
disconnect_pid(Pid, State) ->
exit(Pid, disconnect),
%% Sync wait for connection to die!!!
receive
{'EXIT',Pid,Reason} ->
{_,State1} = handle_exit(Pid, Reason, State),
{true, State1}
end.
%%
%%
%%
get_nodes(Which) ->
get_nodes(ets:first(sys_dist), Which).