nodetool 14 KB

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