nodetool 16 KB

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