Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to implement a function to notify a node that the other node quit or not

I am creating a cluster of nodes and I want to get notification every time a node is connected or not how could that be possible?

like image 387
Mariem Avatar asked Mar 03 '23 02:03

Mariem


1 Answers

Create a gen_server and call net_kernel:monitor_nodes(true) in the init method. Now the gen_server will receive {node_up, Node} and {node_down, Node} messages whenever a node joins or leaves the cluster.

-module(node_monitor).

-behaviour(gen_server).

%% export API
-export([start_link/0,
     stop/0
    ]).

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

-record(state, {}).

-define(SERVER_NAME, ?MODULE).
%%====================================
%% API
%%====================================
start_link() ->
    gen_server:start_link({local, ?SERVER_NAME}, ?MODULE, [], []).

stop() ->
    gen_server:cast(?SERVER_NAME, stop).

%%====================================
%% callbacks
%%====================================
init([]) ->
    net_kernel:monitor_nodes(true),
    {ok, #state{}}.

terminate(_Reason, _State) ->
    ok.

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

handle_info({nodeup, _Node} = Event, State) ->
%%TODO: do something here
    {noreply, State};

handle_info({nodedown, _Node} = Event, State) ->
  %%TODO: do something here
    {noreply, State};

handle_info(_Msg, State) ->
    {noreply, State}.


handle_cast(stop, State) ->
    {stop, normal, State};
handle_cast(_Msg, State) ->
    {noreply, State}.

handle_call(_Msg, _From, State) ->
    Reply = ok,
    {reply, Reply, State}.

A word of caution though, all the nodes will receive these notifications. So if only one node per cluster should be handling node_up and node_down notifications, that logic needs to be implemented on top of this gen_server.

like image 196
Venkatakumar Srinivasan Avatar answered Mar 22 '23 10:03

Venkatakumar Srinivasan