aboutsummaryrefslogtreecommitdiff
path: root/src/ejabberd_cluster.erl
blob: ec72b063eaaa49ad788ebd265b9722bf5c416b4c (plain) (blame)
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
%%%-------------------------------------------------------------------
%%% File    : ejabberd_cluster.erl
%%% Author  : Evgeniy Khramtsov <ekhramtsov@process-one.net>
%%% Description :
%%%
%%% Created :  2 Apr 2010 by Evgeniy Khramtsov <ekhramtsov@process-one.net>
%%%-------------------------------------------------------------------
-module(ejabberd_cluster).

-behaviour(gen_server).

%% API
-export([start_link/0, get_node/1, get_node_new/1, announce/1, shutdown/0,
	 node_id/0, get_node_by_id/1, get_nodes/0, rehash_timeout/0, start/0,
         shutdown_migrate/1, migrate_timeout/0]).

%% gen_server callbacks
-export([init/1, handle_call/3, handle_cast/2, handle_info/2,
	 terminate/2, code_change/3]).

-include("ejabberd.hrl").

-define(HASHTBL, nodes_hash).
-define(HASHTBL_NEW, nodes_hash_new).
-define(POINTS, 64).
-define(REHASH_TIMEOUT, timer:seconds(30)).
-define(MIGRATE_TIMEOUT, timer:minutes(2)).
-define(LOCK, {migrate, node()}).

-record(state, {}).

%%====================================================================
%% API
%%====================================================================
start() ->
    ChildSpec = {?MODULE,
                 {?MODULE, start_link, []},
                 permanent,
                 brutal_kill,
                 worker,
                 [?MODULE]},
    supervisor:start_child(ejabberd_sup, ChildSpec).

start_link() ->
    gen_server:start_link(?MODULE, [], []).

get_node(Key) ->
    Hash = erlang:phash2(Key),
    get_node_by_hash(?HASHTBL, Hash).

get_node_new(Key) ->
    Hash = erlang:phash2(Key),
    get_node_by_hash(?HASHTBL_NEW, Hash).

get_nodes() ->
    %% TODO
    mnesia:system_info(running_db_nodes).

announce(Pid) ->
    gen_server:call(Pid, announce, infinity).

node_id() ->
    integer_to_list(erlang:phash2(node())).

rehash_timeout() ->
    case ejabberd_config:get_local_option(rehash_timeout) of
        N when is_integer(N), N > 0 ->
            timer:seconds(N);
        _ ->
            ?REHASH_TIMEOUT
    end.

migrate_timeout() ->
    case ejabberd_config:get_local_option(migrate_timeout) of
        N when is_integer(N), N > 0 ->
            timer:seconds(N);
        _ ->
            ?MIGRATE_TIMEOUT
    end.

get_node_by_id(NodeID) when is_list(NodeID) ->
    case catch list_to_existing_atom(NodeID) of
	{'EXIT', _} ->
	    node();
	Res ->
	    get_node_by_id(Res)
    end;
get_node_by_id(NodeID) ->
    case global:whereis_name(NodeID) of
	Pid when is_pid(Pid) ->
	    node(Pid);
	_ ->
	    node()
    end.

shutdown() ->
    lists:foreach(
      fun(Node) when Node /= node() ->
	      {ejabberd_cluster, Node} ! {node_down, node()};
	 (_) ->
	      ok
      end, get_nodes()).

shutdown_migrate(WaitTime) ->
    delete_node(?HASHTBL_NEW, node()),
    ejabberd_hooks:run(node_down, [node()]),
    shutdown(),
    delete_node(?HASHTBL, node()),
    ejabberd_hooks:run(node_hash_update, [node(), down, WaitTime]),
    ?INFO_MSG("Waiting ~p seconds for the migration to be completed.",
              [WaitTime div 1000]),
    timer:sleep(WaitTime),
    ok.

%%====================================================================
%% gen_server callbacks
%%====================================================================
init([]) ->
    {A, B, C} = now(),
    random:seed(A, B, C),
    net_kernel:monitor_nodes(true, [{node_type, visible}]),
    ets:new(?HASHTBL, [named_table, public, ordered_set]),
    ets:new(?HASHTBL_NEW, [named_table, public, ordered_set]),
    register_node(),
    AllNodes = get_nodes(),
    OtherNodes = case AllNodes of
		     [_MyNode] ->
			 AllNodes;
		     _ ->
			 AllNodes -- [node()]
		 end,
    append_nodes(?HASHTBL, OtherNodes),
    append_nodes(?HASHTBL_NEW, AllNodes),
    {ok, #state{}}.

handle_call(announce, _From, State) ->
    Migrate_timeout = migrate_timeout(),
    case global:set_lock(?LOCK, get_nodes(), 0) of
	false ->
	    ?WARNING_MSG("Another node is recently attached to "
                         "the cluster and is being rebalanced. "
                         "Waiting for the rebalancing to be completed "
                         "before starting this node. "
                         "This will take at least ~p seconds. "
                         "Please, be patient.", [Migrate_timeout div 1000]),
	    global:set_lock(?LOCK, get_nodes(), infinity);
	true ->
	    ok
    end,
    case get_nodes() of
	[_MyNode] ->
	    register(?MODULE, self()),
	    global:del_lock(?LOCK);
	Nodes ->
	    OtherNodes = Nodes -- [node()],
	    ?INFO_MSG("waiting for migration from nodes: ~w",
		      [OtherNodes]),
	    {_Res, BadNodes} = gen_server:multi_call(
				 OtherNodes, ?MODULE,
				 {node_ready, node()}, ?REHASH_TIMEOUT),
	    append_node(?HASHTBL, node()),
	    register(?MODULE, self()),
            case OtherNodes -- BadNodes of
                [] ->
                    global:del_lock(?LOCK);
                WorkingNodes ->
                    gen_server:abcast(WorkingNodes, ?MODULE, {node_ready, node()}),
                    erlang:send_after(Migrate_timeout, self(), del_lock)
            end
    end,
    {reply, ok, State};
handle_call({node_ready, Node}, _From, State) ->
    ?INFO_MSG("node ~p is ready, preparing migration", [Node]),
    append_node(?HASHTBL_NEW, Node),
    ejabberd_hooks:run(node_up, [Node]),
    {reply, ok, State};
handle_call(_Request, _From, State) ->
    Reply = ok,
    {reply, Reply, State}.

handle_cast({node_ready, Node}, State) ->
    ?INFO_MSG("adding node ~p to hash and starting migration", [Node]),
    append_node(?HASHTBL, Node),
    ejabberd_hooks:run(node_hash_update, [Node, up, migrate_timeout()]),
    {noreply, State};
handle_cast(_Msg, State) ->
    {noreply, State}.

handle_info(del_lock, State) ->
    global:del_lock(?LOCK),
    {noreply, State};
handle_info({node_down, Node}, State) ->
    delete_node(?HASHTBL, Node),
    delete_node(?HASHTBL_NEW, Node),
    {noreply, State};
handle_info({nodedown, Node, _}, State) ->
    ?INFO_MSG("node ~p goes down", [Node]),
    delete_node(?HASHTBL, Node),
    delete_node(?HASHTBL_NEW, Node),
    {noreply, State};
handle_info(_Info, State) ->
    {noreply, State}.

terminate(_Reason, _State) ->
    ok.

code_change(_OldVsn, State, _Extra) ->
    {ok, State}.

%%--------------------------------------------------------------------
%% Internal functions
%%--------------------------------------------------------------------
append_nodes(Tab, Nodes) ->
    lists:foreach(
      fun(Node) ->
	      append_node(Tab, Node)
      end, Nodes).

append_node(Tab, Node) ->
    lists:foreach(
      fun(I) ->
	      Hash = erlang:phash2({I, Node}),
	      ets:insert(Tab, {Hash, Node})
      end, lists:seq(1, ?POINTS)).

delete_node(Tab, Node) ->
    lists:foreach(
      fun(I) ->
	      Hash = erlang:phash2({I, Node}),
	      ets:delete(Tab, Hash)
      end, lists:seq(1, ?POINTS)).

get_node_by_hash(Tab, Hash) ->
    NodeHash = case ets:next(Tab, Hash) of
		   '$end_of_table' ->
		       ets:first(Tab);
		   NH ->
		       NH
	       end,
    if NodeHash == '$end_of_table' ->
	    erlang:error(no_running_nodes);
       true ->
	    case ets:lookup(Tab, NodeHash) of
		[] ->
		    get_node_by_hash(Tab, Hash);
		[{_, Node}] ->
		    Node
	    end
    end.

register_node() ->
    global:register_name(list_to_atom(node_id()), self()).