Skip to content

Instantly share code, notes, and snippets.

Created November 10, 2008 16:06
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save anonymous/23516 to your computer and use it in GitHub Desktop.
Save anonymous/23516 to your computer and use it in GitHub Desktop.
#!/usr/bin/env escript
config() ->
[{app_node, app@localhost},
{appctl_node, appctl@localhost},
{cookie, app},
{timeout, 100}].
main(Args) ->
ScriptDir = filename:dirname(filename:absname(escript:script_name())),
code:add_path(filename:join(ScriptDir, "ebin")),
{AppCtlNode, Cookie} = get_values([appctl_node, cookie]),
os:cmd("epmd -daemon"),
net_kernel:start([AppCtlNode, shortnames]),
erlang:set_cookie(node(), Cookie),
try process(Args, ScriptDir)
catch
error:{cant_start, already_running} ->
error("Error: can't start because App is already running");
error:{cant_stop, isnt_running} ->
error("Error: can't stop because App is not running");
_:Reason ->
Message = io_lib:format("Unknown error occured.~n"
"Reason: ~p.~n"
"Stack trace: ~p",
[Reason, erlang:get_stacktrace()]),
error(Message)
end.
process([Arg], ScriptDir) ->
{AppNode, Cookie} = get_values([app_node, cookie]),
if
Arg =:= "--start"; Arg =:= "-s" ->
start(AppNode, Cookie, ScriptDir);
Arg =:= "--stop"; Arg =:= "-q" ->
stop(AppNode);
Arg =:= "--restart"; Arg =:= "-r" ->
stop(AppNode),
start(AppNode, Cookie, ScriptDir);
true ->
usage()
end;
process(_, _) ->
usage().
start(AppNode, Cookie, ScriptDir) ->
case net_adm:ping(AppNode) of
pong -> erlang:error({cant_start, already_running});
pang -> ok
end,
Deps = string:join(lists:foldl(fun(Dep, Acc) ->
["-pa", filename:join(ScriptDir, Dep) | Acc]
end, [], ["ebin", "deps/*/ebin"]), " "),
Cmd = io_lib:format("erl -detached -sname ~p -setcookie ~p "
"+K true "
"-boot start_sasl -config log "
"~s "
"-s app",
[AppNode, Cookie, Deps]),
os:cmd(Cmd).
stop(AppNode) ->
case net_adm:ping(AppNode) of
pong -> ok;
pang -> erlang:error({cant_stop, isnt_running})
end,
rpc:call(AppNode, init, stop, []),
wait_for_stop(AppNode, get_value(timeout)).
wait_for_stop(AppNode, Timeout) ->
case net_adm:ping(AppNode) of
pong ->
timer:sleep(Timeout),
wait_for_stop(AppNode, Timeout);
pang ->
ok
end.
usage() ->
io:format("Usage: ~s [--start | -s] [--stop | -q] [--restart | -r]~n",
[escript:script_name()]).
get_value(Key) ->
proplists:get_value(Key, config()).
get_values(Keys) ->
get_values(Keys, config()).
get_values(Keys, Config) when is_tuple(Keys) ->
get_values(tuple_to_list(Keys), Config);
get_values(Keys, Config) when is_list (Keys) ->
Values = lists:foldl(fun(Key, Values) ->
[proplists:get_value(Key, Config) | Values]
end, [], Keys),
list_to_tuple(lists:reverse(Values)).
error(Message) ->
io:format(Message ++ ".~n"),
halt(1).
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment