nodetool 13 KB

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