-
Notifications
You must be signed in to change notification settings - Fork 392
/
riak_core_node_watcher.erl
394 lines (309 loc) · 11.8 KB
/
riak_core_node_watcher.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
%% -------------------------------------------------------------------
%%
%% riak_core: Core Riak Application
%%
%% Copyright (c) 2007-2010 Basho Technologies, Inc. All Rights Reserved.
%%
%% This file is provided to you under the Apache License,
%% Version 2.0 (the "License"); you may not use this file
%% except in compliance with the License. You may obtain
%% a copy of the License at
%%
%% http://www.apache.org/licenses/LICENSE-2.0
%%
%% Unless required by applicable law or agreed to in writing,
%% software distributed under the License is distributed on an
%% "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
%% KIND, either express or implied. See the License for the
%% specific language governing permissions and limitations
%% under the License.
%%
%% -------------------------------------------------------------------
-module(riak_core_node_watcher).
-behaviour(gen_server).
%% API
-export([start_link/0,
service_up/2,
service_down/1,
node_up/0,
node_down/0,
services/0, services/1,
nodes/1,
avsn/0]).
%% gen_server callbacks
-export([init/1, handle_call/3, handle_cast/2, handle_info/2,
terminate/2, code_change/3]).
-record(state, { status = up,
services = [],
peers = [],
avsn = 0,
bcast_tref,
bcast_mod = {gen_server, abcast}}).
%% ===================================================================
%% Public API
%% ===================================================================
start_link() ->
gen_server:start_link({local, ?MODULE}, ?MODULE, [], []).
service_up(Id, Pid) ->
gen_server:call(?MODULE, {service_up, Id, Pid}, infinity).
service_down(Id) ->
gen_server:call(?MODULE, {service_down, Id}, infinity).
node_up() ->
gen_server:call(?MODULE, {node_status, up}, infinity).
node_down() ->
gen_server:call(?MODULE, {node_status, down}, infinity).
services() ->
ordsets:from_list([Service || [Service] <- ets:match(?MODULE, {{'_', '$1'}, '_'})]).
services(Node) ->
[Service || [Service] <- ets:match(?MODULE, {{Node, '$1'}, '_'})].
nodes(Service) ->
[Node || [Node] <- ets:match(?MODULE, {{'$1', Service}, '_'})].
%% ===================================================================
%% Test API
%% ===================================================================
avsn() ->
gen_server:call(?MODULE, get_avsn, infinity).
%% ====================================================================
%% gen_server callbacks
%% ====================================================================
init([]) ->
%% Trap exits so that terminate/2 will get called
process_flag(trap_exit, true),
%% Setup callback notification for ring changes; note that we use the
%% supervised variation so that the callback gets removed if this process
%% exits
watch_for_ring_events(),
%% Watch for node up/down events
net_kernel:monitor_nodes(true),
%% Setup ETS table to track node status
ets:new(?MODULE, [protected, named_table]),
{ok, schedule_broadcast(#state{})}.
handle_call({set_bcast_mod, Module, Fn}, _From, State) ->
%% Call available for swapping out how broadcasts are generated
{reply, ok, State#state {bcast_mod = {Module, Fn}}};
handle_call(get_avsn, _From, State) ->
{reply, State#state.avsn, State};
handle_call({service_up, Id, Pid}, _From, State) ->
%% Update the set of active services locally
Services = ordsets:add_element(Id, State#state.services),
S2 = State#state { services = Services },
%% Remove any existing mrefs for this service
delete_service_mref(Id),
%% Setup a monitor for the Pid representing this service
Mref = erlang:monitor(process, Pid),
erlang:put(Mref, Id),
erlang:put(Id, Mref),
%% Update our local ETS table and broadcast
S3 = local_update(S2),
{reply, ok, update_avsn(S3)};
handle_call({service_down, Id}, _From, State) ->
%% Update the set of active services locally
Services = ordsets:del_element(Id, State#state.services),
S2 = State#state { services = Services },
%% Remove any existing mrefs for this service
delete_service_mref(Id),
%% Update local ETS table and broadcast
S3 = local_update(S2),
{reply, ok, update_avsn(S3)};
handle_call({node_status, Status}, _From, State) ->
Transition = {State#state.status, Status},
S2 = case Transition of
{up, down} -> %% up -> down
local_delete(State#state { status = down });
{down, up} -> %% down -> up
local_update(State#state { status = up });
{Status, Status} -> %% noop
State
end,
{reply, ok, update_avsn(S2)}.
handle_cast({ring_update, R}, State) ->
%% Ring has changed; determine what peers are new to us
%% and broadcast out current status to those peers.
Peers0 = ordsets:from_list(riak_core_ring:all_members(R)),
Peers = ordsets:del_element(node(), Peers0),
S2 = peers_update(Peers, State),
{noreply, update_avsn(S2)};
handle_cast({up, Node, Services}, State) ->
S2 = node_up(Node, Services, State),
{noreply, update_avsn(S2)};
handle_cast({down, Node}, State) ->
node_down(Node, State),
{noreply, update_avsn(State)}.
handle_info({nodeup, _Node}, State) ->
%% Ignore node up events; nothing to do here...
{noreply, State};
handle_info({nodedown, Node}, State) ->
node_down(Node, State),
{noreply, update_avsn(State)};
handle_info({'DOWN', Mref, _, _Pid, _Info}, State) ->
%% A sub-system monitored process has terminated. Identify
%% the sub-system in question and notify our peers.
case erlang:get(Mref) of
undefined ->
%% No entry found for this monitor; ignore the message
{noreply, update_avsn(State)};
Id ->
%% Remove the id<->mref entries in the pdict
delete_service_mref(Id),
%% Update our list of active services and ETS table
Services = ordsets:del_element(Id, State#state.services),
S2 = State#state { services = Services },
local_update(S2),
{noreply, update_avsn(S2)}
end;
handle_info({gen_event_EXIT, _, _}, State) ->
%% Ring event handler has been removed for some reason; re-register
watch_for_ring_events(),
{noreply, update_avsn(State)};
handle_info(broadcast, State) ->
S2 = broadcast(State#state.peers, State),
{noreply, S2}.
terminate(_Reason, State) ->
%% Let our peers know that we are shutting down
broadcast(State#state.peers, State#state { status = down }).
code_change(_OldVsn, State, _Extra) ->
{ok, State}.
%% ====================================================================
%% Internal functions
%% ====================================================================
update_avsn(State) ->
State#state { avsn = State#state.avsn + 1 }.
watch_for_ring_events() ->
Self = self(),
Fn = fun(R) ->
gen_server:cast(Self, {ring_update, R})
end,
riak_core_ring_events:add_sup_callback(Fn).
delete_service_mref(Id) ->
%% Cleanup the monitor if one exists
case erlang:get(Id) of
undefined ->
ok;
Mref ->
erlang:erase(Mref),
erlang:erase(Id),
erlang:demonitor(Mref)
end.
broadcast(Nodes, State) ->
case (State#state.status) of
up ->
Msg = {up, node(), State#state.services};
down ->
Msg = {down, node()}
end,
{Mod, Fn} = State#state.bcast_mod,
Mod:Fn(Nodes, ?MODULE, Msg),
schedule_broadcast(State).
schedule_broadcast(State) ->
case (State#state.bcast_tref) of
undefined ->
ok;
OldTref ->
erlang:cancel_timer(OldTref)
end,
Interval = app_helper:get_env(riak_core, gossip_interval),
Tref = erlang:send_after(Interval, self(), broadcast),
State#state { bcast_tref = Tref }.
is_peer(Node, State) ->
ordsets:is_element(Node, State#state.peers).
is_node_up(Node) ->
ets:member(?MODULE, Node).
node_up(Node, Services, State) ->
case is_peer(Node, State) of
true ->
%% Before we alter the ETS table, see if this node was previously down. In
%% that situation, we'll go ahead broadcast out.
S2 = case is_node_up(Node) of
false ->
broadcast([Node], State);
true ->
State
end,
case node_update(Node, Services) of
[] ->
ok;
AffectedServices ->
riak_core_node_watcher_events:service_update(AffectedServices)
end,
S2;
false ->
State
end.
node_down(Node, State) ->
case is_peer(Node, State) of
true ->
case node_delete(Node) of
[] ->
ok;
AffectedServices ->
riak_core_node_watcher_events:service_update(AffectedServices)
end;
false ->
ok
end.
node_delete(Node) ->
Services = services(Node),
ets:match_delete(?MODULE, {{Node, '_'}, '_'}),
ets:delete(?MODULE, Node),
Services.
node_update(Node, Services) ->
%% Check the list of up services against what we already
%% know and determine what's changed (if anything).
Now = riak_core_util:moment(),
NewStatus = ordsets:from_list(Services),
OldStatus = ordsets:from_list(services(Node)),
Added = ordsets:subtract(NewStatus, OldStatus),
Deleted = ordsets:subtract(OldStatus, NewStatus),
Unchanged = ordsets:intersection(NewStatus, OldStatus),
%% Update ets table with changes; make sure to touch unchanged
%% service with latest timestamp
[ets:delete(?MODULE, {Node, Ss}) || Ss <- Deleted],
ets:insert(?MODULE, [{{Node, Ss}, Now} || Ss <- Added ++ Unchanged]),
%% Keep track of the last time we recv'd data from a node
ets:insert(?MODULE, {Node, Now}),
%% Return the list of affected services (added or deleted)
ordsets:union(Added, Deleted).
local_update(#state { status = down } = State) ->
%% Ignore subsystem changes when we're marked as down
State;
local_update(State) ->
%% Update our local ETS table
case node_update(node(), State#state.services) of
[] ->
%% No material changes; no local notification necessary
ok;
AffectedServices ->
%% Generate a local notification about the affected services and
%% also broadcast our status
riak_core_node_watcher_events:service_update(AffectedServices)
end,
broadcast(State#state.peers, State).
local_delete(State) ->
case node_delete(node()) of
[] ->
%% No services changed; no local notification required
State;
AffectedServices ->
riak_core_node_watcher_events:service_update(AffectedServices)
end,
broadcast(State#state.peers, State).
peers_update(NewPeers, State) ->
%% Identify what peers have been added and deleted
Added = ordsets:subtract(NewPeers, State#state.peers),
Deleted = ordsets:subtract(State#state.peers, NewPeers),
%% For peers that have been deleted, remove their entries from
%% the ETS table; we no longer care about their status
Services0 = (lists:foldl(fun(Node, Acc) ->
S = node_delete(Node),
S ++ Acc
end, [], Deleted)),
Services = ordsets:from_list(Services0),
%% Notify local parties if any services are affected by this change
case Services of
[] ->
ok;
_ ->
riak_core_node_watcher_events:service_update(Services)
end,
%% Broadcast our current status to new peers
broadcast(Added, State#state { peers = NewPeers }).