Commit 407b12fd by Tim Stewart

Initial version of tcprpc

parents
:node-name "tcprpc"
:start-command "rebar3 shell --sname tcprpc"
.rebar3
_*
.eunit
*.o
*.beam
*.plt
*.swp
*.swo
.erlang.cookie
ebin
log
erl_crash.dump
.rebar
logs
_build
Copyright (c) 2016, Tim Stewart <tim@stoo.org>.
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* The names of its contributors may not be used to endorse or promote
products derived from this software without specific prior written
permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
tcprpc
======
A bare-bones TCP-based RPC mechanism. You may start up a test
instance quickly using rebar3:
$ rebar3 shell
Once started, telnet or netcat to the configured port (defaults to
5555), and simply submit an RPC call in Module:Function(Arg1, Arg2,
...) format:
$ echo "erlang:system_info(cpu_topology)." | nc localhost 5555
[{processor,[{thread,{logical,0}},
{thread,{logical,1}},
{thread,{logical,2}},
{thread,{logical,3}}]}]
tcprpc will close the socket once the answer has been sent.
Build
-----
$ rebar3 compile
Acknowledgements
----------------
The `parse_mfa` and `args_to_terms` functions in tcprpc_protocol.erl
were taken largely from Manning's _Erlang and OTP in Action_ by Logan,
Merritt, and Carlsson. Thanks!
{erl_opts, [debug_info]}.
{deps, [ranch]}.
{shell, [ {apps, [ranch, tcprpc]} ]}.
[{<<"ranch">>,{pkg,<<"ranch">>,<<"1.2.1">>},0}].
{application, tcprpc,
[{description, "TCP RPC Server"},
{vsn, "0.1.0"},
{registered, []},
{mod, { tcprpc_app, []}},
{applications,
[kernel,
stdlib,
ranch
]},
{env,[ {listeners, 10}, {port, 5555} ]},
{modules, []},
{maintainers, []},
{licenses, []},
{links, []}
]}.
%%%-------------------------------------------------------------------
%% @doc tcprpc public API
%% @end
%%%-------------------------------------------------------------------
-module(tcprpc_app).
-behaviour(application).
%% Application callbacks
-export([start/2, stop/1]).
%%====================================================================
%% API
%%====================================================================
start(_StartType, _StartArgs) ->
{ok, Listeners} = application:get_env(tcprpc, listeners),
{ok, Port} = application:get_env(tcprpc, port),
{ok, _} = ranch:start_listener(
tcprpc, Listeners, ranch_tcp, [{port, Port}],
tcprpc_protocol, []),
tcprpc_sup:start_link().
stop(_State) ->
_ = ranch:stop_listener(tcprpc),
ok.
%%====================================================================
%% Internal functions
%%====================================================================
%%%-------------------------------------------------------------------------
%%% @author Tim Stewart <tim@stoo.org>
%%% [http://www.stoo.org]
%%% @copyright 2015 Stoo Labs
%%% @doc TCP RPC protocol handler
%%% @end
%%%-------------------------------------------------------------------------
-module(tcprpc_protocol).
-behavior(gen_server).
-behavior(ranch_protocol).
%% Public API
-export([start_link/4, init/4]).
%% gen_server callbacks
-export([init/1, handle_call/3, handle_cast/2, handle_info/2,
terminate/2, code_change/3]).
-define(SERVER, ?MODULE).
-record(state, {socket, transport}).
%%%=========================================================================
%%% ranch_protocol callbacks
%%%=========================================================================
start_link(Ref, Socket, Transport, Opts) ->
proc_lib:start_link(?MODULE, init, [Ref, Socket, Transport, Opts]).
init(Ref, Socket, Transport, _Opts = []) ->
%% Put items that would normally be in gen_server's init/1 here
ok = proc_lib:init_ack({ok, self()}),
ok = ranch:accept_ack(Ref),
ok = Transport:setopts(Socket, [{active, once}, {packet, line}]),
gen_server:enter_loop(?MODULE, [],
#state{socket = Socket, transport = Transport}).
%%%=========================================================================
%%% gen_server callbacks
%%%=========================================================================
init([]) ->
%% Not used because we use proc_lib:start_link/3 and
%% gen_server:enter_loop/3 above
unused.
handle_call(_Request, _From, State) ->
Reply = ok,
{reply, Reply, State}.
handle_cast(_Msg, State) ->
{noreply, State}.
handle_info({tcp, Socket, Data}, State) ->
ok = inet:setopts(Socket, [{active, once}]),
Result = rpc(Data),
ok = gen_tcp:send(Socket, Result),
{stop, normal, State};
handle_info(_Info, State) ->
{noreply, State}.
terminate(_Reason, _State) ->
ok.
code_change(_OldVsn, State, _Extra) ->
{ok, State}.
%% format_status(_Opt, [_PDict, #state{}]) ->
%% Term = [ {state_key, "State Value"} ],
%% [ {data, [ {"State", Term} ]} ].
%%%=========================================================================
%%% Internal functions
%%%=========================================================================
rpc(Data) ->
{M, F, A} = parse_mfa(Data),
Result = apply(M, F, A),
io_lib:fwrite("~p~n", [Result]).
parse_mfa(Data) ->
%% Get rid of line endings
Data2 = re:replace(Data, "\r\n$", "", [{return, list}]),
MFA = re:replace(Data2, "\n$", "", [{return, list}]),
%% Parse out Module, Function, and Arguments: M and F are simply
%% converted to atoms, and the arguments are parsed within
%% args_to_terms/1
Regex = "(.*):(.*)\\s*\\((.*)\\s*\\)\\s*.\\s*$",
{match, [M, F, A]} =
re:run(MFA, Regex,
[{capture, [1, 2, 3], list}, ungreedy]),
{list_to_atom(M), list_to_atom(F), args_to_terms(A)}.
args_to_terms(RawArgs) ->
{ok, Toks, _Line} = erl_scan:string("[" ++ RawArgs ++ "]. ", 1),
{ok, Args} = erl_parse:parse_term(Toks),
Args.
%%%-------------------------------------------------------------------
%% @doc tcprpc top level supervisor.
%% @end
%%%-------------------------------------------------------------------
-module(tcprpc_sup).
-behaviour(supervisor).
%% API
-export([start_link/0]).
%% Supervisor callbacks
-export([init/1]).
-define(SERVER, ?MODULE).
%%====================================================================
%% API functions
%%====================================================================
start_link() ->
supervisor:start_link({local, ?SERVER}, ?MODULE, []).
%%====================================================================
%% Supervisor callbacks
%%====================================================================
%% Child :: {Id,StartFunc,Restart,Shutdown,Type,Modules}
init([]) ->
{ok, { {one_for_all, 0, 1}, []} }.
%%====================================================================
%% Internal functions
%%====================================================================
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment