nodetool 15 KB

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