nodetool 13 KB

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