nodetool 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315
  1. #!/usr/bin/env escript
  2. %% -*- mode: erlang;erlang-indent-level: 4;indent-tabs-mode: nil -*-
  3. %% ex: ft=erlang ts=4 sw=4 et
  4. %% -------------------------------------------------------------------
  5. %%
  6. %% nodetool: Helper Script for interacting with live nodes
  7. %%
  8. %% -------------------------------------------------------------------
  9. -mode(compile).
  10. main(Args) ->
  11. case os:type() of
  12. {win32, nt} -> ok;
  13. _nix ->
  14. case init:get_argument(start_epmd) of
  15. {ok, [["true"]]} ->
  16. ok = start_epmd();
  17. _ ->
  18. ok
  19. end
  20. end,
  21. ok = add_libs_dir(),
  22. ok = do_with_halt(Args, "mnesia_dir", fun create_mnesia_dir/2),
  23. ok = do_with_halt(Args, "chkconfig", fun("-config", X) -> chkconfig(X) end),
  24. ok = do_with_halt(Args, "chkconfig", fun chkconfig/1),
  25. Args1 = do_with_ret(Args, "-name",
  26. fun(TargetName) ->
  27. ThisNode = this_node_name(TargetName),
  28. {ok, _} = net_kernel:start([ThisNode, longnames]),
  29. put(target_node, nodename(TargetName))
  30. end),
  31. Args2 = do_with_ret(Args1, "-sname",
  32. fun(TargetName) ->
  33. ThisNode = this_node_name(TargetName),
  34. {ok, _} = net_kernel:start([ThisNode, shortnames]),
  35. put(target_node, nodename(TargetName))
  36. end),
  37. RestArgs = do_with_ret(Args2, "-setcookie",
  38. fun(Cookie) ->
  39. erlang:set_cookie(node(), list_to_atom(Cookie))
  40. end),
  41. [application:start(App) || App <- [crypto, public_key, ssl]],
  42. TargetNode = get(target_node),
  43. %% See if the node is currently running -- if it's not, we'll bail
  44. case {net_kernel:hidden_connect_node(TargetNode), net_adm:ping(TargetNode)} of
  45. {true, pong} ->
  46. ok;
  47. {false, pong} ->
  48. io:format(standard_error, "Failed to connect to node ~p\n", [TargetNode]),
  49. halt(1);
  50. {_, pang} ->
  51. io:format(standard_error, "Node ~p not responding to pings.\n", [TargetNode]),
  52. halt(1)
  53. end,
  54. case RestArgs of
  55. ["getpid"] ->
  56. io:format("~p\n", [list_to_integer(rpc:call(TargetNode, os, getpid, []))]);
  57. ["ping"] ->
  58. %% If we got this far, the node already responsed to a ping, so just dump
  59. %% a "pong"
  60. io:format("pong\n");
  61. ["stop"] ->
  62. rpc:call(TargetNode, emqx_plugins, unload, [], 60000),
  63. io:format("~p\n", [rpc:call(TargetNode, init, stop, [], 60000)]);
  64. ["restart", "-config", ConfigFile | _RestArgs1] ->
  65. io:format("~p\n", [rpc:call(TargetNode, emqx, restart, [ConfigFile], 60000)]);
  66. ["rpc", Module, Function | RpcArgs] ->
  67. case rpc:call(TargetNode, list_to_atom(Module), list_to_atom(Function),
  68. [RpcArgs], 60000) of
  69. ok ->
  70. ok;
  71. {error, cmd_not_found} ->
  72. halt(1);
  73. {error, Reason} ->
  74. io:format("RPC to ~s error: ~p\n", [TargetNode, Reason]),
  75. halt(1);
  76. {badrpc, Reason} ->
  77. io:format("RPC to ~s failed: ~p\n", [TargetNode, Reason]),
  78. halt(1);
  79. _ ->
  80. halt(1)
  81. end;
  82. ["rpc_infinity", Module, Function | RpcArgs] ->
  83. case rpc:call(TargetNode, list_to_atom(Module), list_to_atom(Function), [RpcArgs], infinity) of
  84. ok ->
  85. ok;
  86. {badrpc, Reason} ->
  87. io:format("RPC to ~p failed: ~p\n", [TargetNode, Reason]),
  88. halt(1);
  89. _ ->
  90. halt(1)
  91. end;
  92. ["rpcterms", Module, Function | ArgsAsString] ->
  93. case rpc:call(TargetNode, list_to_atom(Module), list_to_atom(Function),
  94. consult(lists:flatten(ArgsAsString)), 60000) of
  95. {badrpc, Reason} ->
  96. io:format("RPC to ~p failed: ~p\n", [TargetNode, Reason]),
  97. halt(1);
  98. Other ->
  99. io:format("~p\n", [Other])
  100. end;
  101. ["eval" | ListOfArgs] ->
  102. % shells may process args into more than one, and end up stripping
  103. % spaces, so this converts all of that to a single string to parse
  104. String = binary_to_list(
  105. list_to_binary(
  106. join(ListOfArgs," ")
  107. )
  108. ),
  109. % then just as a convenience to users, if they forgot a trailing
  110. % '.' add it for them.
  111. Normalized =
  112. case lists:reverse(String) of
  113. [$. | _] -> String;
  114. R -> lists:reverse([$. | R])
  115. end,
  116. % then scan and parse the string
  117. {ok, Scanned, _} = erl_scan:string(Normalized),
  118. {ok, Parsed } = erl_parse:parse_exprs(Scanned),
  119. % and evaluate it on the remote node
  120. case rpc:call(TargetNode, erl_eval, exprs, [Parsed, [] ]) of
  121. {value, Value, _} ->
  122. io:format ("~p\n",[Value]);
  123. {badrpc, Reason} ->
  124. io:format("RPC to ~p failed: ~p\n", [TargetNode, Reason]),
  125. halt(1)
  126. end;
  127. Other ->
  128. io:format("Other: ~p\n", [Other]),
  129. io:format("Usage: nodetool {genconfig, chkconfig|getpid|ping|stop|restart|reboot|rpc|rpc_infinity|rpcterms|eval [Terms]} [RPC]\n")
  130. end,
  131. net_kernel:stop().
  132. do_with_ret(Args, Name, Handler) ->
  133. {arity, Arity} = erlang:fun_info(Handler, arity),
  134. case take_args(Args, Name, Arity) of
  135. false ->
  136. Args;
  137. {Args1, Rest} ->
  138. _ = erlang:apply(Handler, Args1),
  139. Rest
  140. end.
  141. do_with_halt(Args, Name, Handler) ->
  142. {arity, Arity} = erlang:fun_info(Handler, arity),
  143. case take_args(Args, Name, Arity) of
  144. false ->
  145. ok;
  146. {Args1, _Rest} ->
  147. erlang:apply(Handler, Args1), %% should halt
  148. io:format(standard_error, "~s handler did not halt", [Name]),
  149. halt(?LINE)
  150. end.
  151. %% Return option args list if found, otherwise 'false'.
  152. take_args(Args, OptName, 0) ->
  153. lists:member(OptName, Args) andalso [];
  154. take_args(Args, OptName, OptArity) ->
  155. take_args(Args, OptName, OptArity, _Scanned = []).
  156. take_args([], _, _, _) -> false; %% no such option
  157. take_args([Name | Rest], Name, Arity, Scanned) ->
  158. length(Rest) >= Arity orelse error({not_enough_args_for, Name}),
  159. {Result, Tail} = lists:split(Arity, Rest),
  160. {Result, lists:reverse(Scanned) ++ Tail};
  161. take_args([Other | Rest], Name, Arity, Scanned) ->
  162. take_args(Rest, Name, Arity, [Other | Scanned]).
  163. start_epmd() ->
  164. [] = os:cmd("\"" ++ epmd_path() ++ "\" -daemon"),
  165. ok.
  166. epmd_path() ->
  167. ErtsBinDir = filename:dirname(escript:script_name()),
  168. Name = "epmd",
  169. case os:find_executable(Name, ErtsBinDir) of
  170. false ->
  171. case os:find_executable(Name) of
  172. false ->
  173. io:format("Could not find epmd.~n"),
  174. halt(1);
  175. GlobalEpmd ->
  176. GlobalEpmd
  177. end;
  178. Epmd ->
  179. Epmd
  180. end.
  181. nodename(Name) ->
  182. case re:split(Name, "@", [{return, list}, unicode]) of
  183. [_Node, _Host] ->
  184. list_to_atom(Name);
  185. [Node] ->
  186. [_, Host] = re:split(atom_to_list(node()), "@", [{return, list}, unicode]),
  187. list_to_atom(lists:concat([Node, "@", Host]))
  188. end.
  189. this_node_name(Name) ->
  190. [Node, Host] = re:split(Name, "@", [{return, list}, unicode]),
  191. list_to_atom(lists:concat(["remsh_maint_", Node, os:getpid(), "@", Host])).
  192. %% For windows???
  193. create_mnesia_dir(DataDir, NodeName) ->
  194. MnesiaDir = filename:join(DataDir, NodeName),
  195. file:make_dir(MnesiaDir),
  196. io:format("~s", [MnesiaDir]),
  197. halt(0).
  198. chkconfig(File) ->
  199. case file:consult(File) of
  200. {ok, Terms} ->
  201. case validate(Terms) of
  202. ok ->
  203. halt(0);
  204. {error, Problems} ->
  205. lists:foreach(fun print_issue/1, Problems),
  206. %% halt(1) if any problems were errors
  207. halt(case [x || {error, _} <- Problems] of
  208. [] -> 0;
  209. _ -> 1
  210. end)
  211. end;
  212. {error, {Line, Mod, Term}} ->
  213. io:format(standard_error, ["Error on line ", file:format_error({Line, Mod, Term}), "\n"], []),
  214. halt(1);
  215. {error, Error} ->
  216. io:format(standard_error, ["Error reading config file: ", File, " ", file:format_error(Error), "\n"], []),
  217. halt(1)
  218. end.
  219. %%
  220. %% Given a string or binary, parse it into a list of terms, ala file:consult/0
  221. %%
  222. consult(Str) when is_list(Str) ->
  223. consult([], Str, []);
  224. consult(Bin) when is_binary(Bin)->
  225. consult([], binary_to_list(Bin), []).
  226. consult(Cont, Str, Acc) ->
  227. case erl_scan:tokens(Cont, Str, 0) of
  228. {done, Result, Remaining} ->
  229. case Result of
  230. {ok, Tokens, _} ->
  231. {ok, Term} = erl_parse:parse_term(Tokens),
  232. consult([], Remaining, [Term | Acc]);
  233. {eof, _Other} ->
  234. lists:reverse(Acc);
  235. {error, Info, _} ->
  236. {error, Info}
  237. end;
  238. {more, Cont1} ->
  239. consult(Cont1, eof, Acc)
  240. end.
  241. %%
  242. %% Validation functions for checking the app.config
  243. %%
  244. validate([Terms]) ->
  245. Results = [ValidateFun(Terms) || ValidateFun <- get_validation_funs()],
  246. Failures = [Res || Res <- Results, Res /= true],
  247. case Failures of
  248. [] ->
  249. ok;
  250. _ ->
  251. {error, Failures}
  252. end.
  253. %% Some initial and basic checks for the app.config file
  254. get_validation_funs() ->
  255. [ ].
  256. print_issue({warning, Warning}) ->
  257. io:format(standard_error, "Warning in app.config: ~s~n", [Warning]);
  258. print_issue({error, Error}) ->
  259. io:format(standard_error, "Error in app.config: ~s~n", [Error]).
  260. %% string:join/2 copy; string:join/2 is getting obsoleted
  261. %% and replaced by lists:join/2, but lists:join/2 is too new
  262. %% for version support (only appeared in 19.0) so it cannot be
  263. %% used. Instead we just adopt join/2 locally and hope it works
  264. %% for most unicode use cases anyway.
  265. join([], Sep) when is_list(Sep) ->
  266. [];
  267. join([H|T], Sep) ->
  268. H ++ lists:append([Sep ++ X || X <- T]).
  269. add_libs_dir() ->
  270. [_ | _] = RootDir = os:getenv("RUNNER_ROOT_DIR"),
  271. CurrentVsn = os:getenv("REL_VSN"),
  272. RelFile = filename:join([RootDir, "releases", "RELEASES"]),
  273. case file:consult(RelFile) of
  274. {ok, [Releases]} ->
  275. Release = lists:keyfind(CurrentVsn, 3, Releases),
  276. {release, _Name, _AppVsn, _ErtsVsn, Libs, _State} = Release,
  277. lists:foreach(
  278. fun({Name, Vsn, _}) ->
  279. add_lib_dir(RootDir, Name, Vsn)
  280. end, Libs);
  281. {error, Reason} ->
  282. %% rel file was been deleted by release handler
  283. error({failed_to_read_RELEASES_file, RelFile, Reason})
  284. end.
  285. add_lib_dir(RootDir, Name, Vsn) ->
  286. LibDir = filename:join([RootDir, lib, atom_to_list(Name) ++ "-" ++ Vsn, ebin]),
  287. case code:add_pathz(LibDir) of
  288. true -> ok;
  289. {error, _} -> error(LibDir)
  290. end.