nodetool 12 KB

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