nodetool 15 KB

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