nodetool 12 KB

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