123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335 |
- %% ==========================================================================================================
- %% Syn - A global Process Registry and Process Group manager.
- %%
- %% The MIT License (MIT)
- %%
- %% Copyright (c) 2015 Roberto Ostinelli <roberto@ostinelli.net> and Neato Robotics, Inc.
- %%
- %% Permission is hereby granted, free of charge, to any person obtaining a copy
- %% of this software and associated documentation files (the "Software"), to deal
- %% in the Software without restriction, including without limitation the rights
- %% to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
- %% copies of the Software, and to permit persons to whom the Software is
- %% furnished to do so, subject to the following conditions:
- %%
- %% The above copyright notice and this permission notice shall be included in
- %% all copies or substantial portions of the Software.
- %%
- %% THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
- %% IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
- %% FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
- %% AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
- %% LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
- %% OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
- %% THE SOFTWARE.
- %% ==========================================================================================================
- -module(syn_registry).
- -behaviour(gen_server).
- %% API
- -export([start_link/0]).
- -export([register/2, register/3]).
- -export([unregister/1]).
- -export([find_by_key/1, find_by_key/2]).
- -export([find_by_pid/1, find_by_pid/2]).
- -export([count/0, count/1]).
- %% gen_server callbacks
- -export([init/1, handle_call/3, handle_cast/2, handle_info/2, terminate/2, code_change/3]).
- %% records
- -record(state, {
- registry_process_exit_callback_module = undefined :: atom(),
- registry_process_exit_callback_function = undefined :: atom()
- }).
- %% include
- -include("syn.hrl").
- %% ===================================================================
- %% API
- %% ===================================================================
- -spec start_link() -> {ok, pid()} | {error, any()}.
- start_link() ->
- Options = [],
- gen_server:start_link({local, ?MODULE}, ?MODULE, [], Options).
- -spec find_by_key(Key :: any()) -> pid() | undefined.
- find_by_key(Key) ->
- case i_find_by_key(on_connected_node, Key) of
- undefined -> undefined;
- Process -> Process#syn_registry_table.pid
- end.
- -spec find_by_key(Key :: any(), with_meta) -> {pid(), Meta :: any()} | undefined.
- find_by_key(Key, with_meta) ->
- case i_find_by_key(on_connected_node, Key) of
- undefined -> undefined;
- Process -> {Process#syn_registry_table.pid, Process#syn_registry_table.meta}
- end.
- -spec find_by_pid(Pid :: pid()) -> Key :: any() | undefined.
- find_by_pid(Pid) when is_pid(Pid) ->
- case i_find_by_pid(on_connected_node, Pid) of
- undefined -> undefined;
- Process -> Process#syn_registry_table.key
- end.
- -spec find_by_pid(Pid :: pid(), with_meta) -> {Key :: any(), Meta :: any()} | undefined.
- find_by_pid(Pid, with_meta) when is_pid(Pid) ->
- case i_find_by_pid(on_connected_node, Pid) of
- undefined -> undefined;
- Process -> {Process#syn_registry_table.key, Process#syn_registry_table.meta}
- end.
- -spec register(Key :: any(), Pid :: pid()) -> ok | {error, taken | pid_already_registered}.
- register(Key, Pid) when is_pid(Pid) ->
- register(Key, Pid, undefined).
- -spec register(Key :: any(), Pid :: pid(), Meta :: any()) -> ok | {error, taken | pid_already_registered}.
- register(Key, Pid, Meta) when is_pid(Pid) ->
- Node = node(Pid),
- gen_server:call({?MODULE, Node}, {register_on_node, Key, Pid, Meta}).
- -spec unregister(Key :: any()) -> ok | {error, undefined}.
- unregister(Key) ->
- case i_find_by_key(Key) of
- undefined ->
- {error, undefined};
- Process ->
- Node = node(Process#syn_registry_table.pid),
- gen_server:call({?MODULE, Node}, {unregister_on_node, Key})
- end.
- -spec count() -> non_neg_integer().
- count() ->
- mnesia:table_info(syn_registry_table, size).
- -spec count(Node :: atom()) -> non_neg_integer().
- count(Node) ->
- %% build match specs
- MatchHead = #syn_registry_table{node = '$2', _ = '_'},
- Guard = {'=:=', '$2', Node},
- Result = '$2',
- %% select
- Processes = mnesia:dirty_select(syn_registry_table, [{MatchHead, [Guard], [Result]}]),
- length(Processes).
- %% ===================================================================
- %% Callbacks
- %% ===================================================================
- %% ----------------------------------------------------------------------------------------------------------
- %% Init
- %% ----------------------------------------------------------------------------------------------------------
- -spec init([]) ->
- {ok, #state{}} |
- {ok, #state{}, Timeout :: non_neg_integer()} |
- ignore |
- {stop, Reason :: any()}.
- init([]) ->
- %% trap linked processes signal
- process_flag(trap_exit, true),
- %% get options
- {ok, [ProcessExitCallbackModule, ProcessExitCallbackFunction]} = syn_utils:get_env_value(
- registry_process_exit_callback,
- [undefined, undefined]
- ),
- %% build state
- {ok, #state{
- registry_process_exit_callback_module = ProcessExitCallbackModule,
- registry_process_exit_callback_function = ProcessExitCallbackFunction
- }}.
- %% ----------------------------------------------------------------------------------------------------------
- %% Call messages
- %% ----------------------------------------------------------------------------------------------------------
- -spec handle_call(Request :: any(), From :: any(), #state{}) ->
- {reply, Reply :: any(), #state{}} |
- {reply, Reply :: any(), #state{}, Timeout :: non_neg_integer()} |
- {noreply, #state{}} |
- {noreply, #state{}, Timeout :: non_neg_integer()} |
- {stop, Reason :: any(), Reply :: any(), #state{}} |
- {stop, Reason :: any(), #state{}}.
- handle_call({register_on_node, Key, Pid, Meta}, _From, State) ->
- %% check & register in gen_server process to ensure atomicity at node level without transaction lock
- %% atomicity is obviously not at cluster level, which is covered by syn_consistency.
- case i_find_by_key(Key) of
- undefined ->
- case i_find_by_pid(Pid) of
- undefined ->
- %% add to table
- mnesia:dirty_write(#syn_registry_table{
- key = Key,
- pid = Pid,
- node = node(),
- meta = Meta
- }),
- %% link
- erlang:link(Pid),
- %% return
- {reply, ok, State};
- _ ->
- {reply, {error, pid_already_registered}, State}
- end;
- _ ->
- {reply, {error, taken}, State}
- end;
- handle_call({unregister_on_node, Key}, _From, State) ->
- %% we check again for key to return the correct response regardless of race conditions
- case i_find_by_key(Key) of
- undefined ->
- {reply, {error, undefined}, State};
- Process ->
- %% remove from table
- remove_process_by_key(Key),
- %% unlink
- Pid = Process#syn_registry_table.pid,
- erlang:unlink(Pid),
- %% reply
- {reply, ok, State}
- end;
- handle_call({unlink_process, Pid}, _From, State) ->
- erlang:unlink(Pid),
- {reply, ok, State};
- handle_call(Request, From, State) ->
- error_logger:warning_msg("Received from ~p an unknown call message: ~p", [Request, From]),
- {reply, undefined, State}.
- %% ----------------------------------------------------------------------------------------------------------
- %% Cast messages
- %% ----------------------------------------------------------------------------------------------------------
- -spec handle_cast(Msg :: any(), #state{}) ->
- {noreply, #state{}} |
- {noreply, #state{}, Timeout :: non_neg_integer()} |
- {stop, Reason :: any(), #state{}}.
- handle_cast(Msg, State) ->
- error_logger:warning_msg("Received an unknown cast message: ~p", [Msg]),
- {noreply, State}.
- %% ----------------------------------------------------------------------------------------------------------
- %% All non Call / Cast messages
- %% ----------------------------------------------------------------------------------------------------------
- -spec handle_info(Info :: any(), #state{}) ->
- {noreply, #state{}} |
- {noreply, #state{}, Timeout :: non_neg_integer()} |
- {stop, Reason :: any(), #state{}}.
- handle_info({'EXIT', Pid, Reason}, #state{
- registry_process_exit_callback_module = ProcessExitCallbackModule,
- registry_process_exit_callback_function = ProcessExitCallbackFunction
- } = State) ->
- %% do not lock backbone
- spawn(fun() ->
- %% check if pid is in table
- {Key, Meta} = case i_find_by_pid(Pid) of
- undefined ->
- %% log
- case Reason of
- normal -> ok;
- killed -> ok;
- _ ->
- error_logger:error_msg("Received an exit message from an unlinked process ~p with reason: ~p", [Pid, Reason])
- end,
- %% return
- {undefined, undefined};
- Process ->
- %% get process info
- Key0 = Process#syn_registry_table.key,
- Meta0 = Process#syn_registry_table.meta,
- %% log
- case Reason of
- normal -> ok;
- killed -> ok;
- _ ->
- error_logger:error_msg("Process with key ~p and pid ~p exited with reason: ~p", [Key0, Pid, Reason])
- end,
- %% delete from table
- remove_process_by_key(Key0),
- %% return
- {Key0, Meta0}
- end,
- %% callback
- case ProcessExitCallbackModule of
- undefined -> ok;
- _ -> ProcessExitCallbackModule:ProcessExitCallbackFunction(Key, Pid, Meta, Reason)
- end
- end),
- %% return
- {noreply, State};
- handle_info(Info, State) ->
- error_logger:warning_msg("Received an unknown info message: ~p", [Info]),
- {noreply, State}.
- %% ----------------------------------------------------------------------------------------------------------
- %% Terminate
- %% ----------------------------------------------------------------------------------------------------------
- -spec terminate(Reason :: any(), #state{}) -> terminated.
- terminate(Reason, _State) ->
- error_logger:info_msg("Terminating syn_registry with reason: ~p", [Reason]),
- terminated.
- %% ----------------------------------------------------------------------------------------------------------
- %% Convert process state when code is changed.
- %% ----------------------------------------------------------------------------------------------------------
- -spec code_change(OldVsn :: any(), #state{}, Extra :: any()) -> {ok, #state{}}.
- code_change(_OldVsn, State, _Extra) ->
- {ok, State}.
- %% ===================================================================
- %% Internal
- %% ===================================================================
- -spec i_find_by_key(on_connected_node, Key :: any()) -> Process :: #syn_registry_table{} | undefined.
- i_find_by_key(on_connected_node, Key) ->
- case i_find_by_key(Key) of
- undefined -> undefined;
- Process -> return_if_on_connected_node(Process)
- end.
- -spec i_find_by_key(Key :: any()) -> Process :: #syn_registry_table{} | undefined.
- i_find_by_key(Key) ->
- case mnesia:dirty_read(syn_registry_table, Key) of
- [Process] -> Process;
- _ -> undefined
- end.
- -spec i_find_by_pid(on_connected_node, Pid :: pid()) -> Process :: #syn_registry_table{} | undefined.
- i_find_by_pid(on_connected_node, Pid) ->
- case i_find_by_pid(Pid) of
- undefined -> undefined;
- Process -> return_if_on_connected_node(Process)
- end.
- -spec i_find_by_pid(Pid :: pid()) -> Process :: #syn_registry_table{} | undefined.
- i_find_by_pid(Pid) ->
- case mnesia:dirty_index_read(syn_registry_table, Pid, #syn_registry_table.pid) of
- [Process] -> Process;
- _ -> undefined
- end.
- -spec return_if_on_connected_node(Process :: #syn_registry_table{}) -> Process :: #syn_registry_table{} | undefined.
- return_if_on_connected_node(Process) ->
- case lists:member(Process#syn_registry_table.node, [node() | nodes()]) of
- true -> Process;
- _ -> undefined
- end.
- -spec remove_process_by_key(Key :: any()) -> ok.
- remove_process_by_key(Key) ->
- mnesia:dirty_delete(syn_registry_table, Key).
|