./ct_report/coverage/ejabberd_ctl.COVER.html

1 %%%----------------------------------------------------------------------
2 %%% File : ejabberd_ctl.erl
3 %%% Author : Alexey Shchepin <alexey@process-one.net>
4 %%% Purpose : ejabberd command line admin tool
5 %%% Created : 11 Jan 2004 by Alexey Shchepin <alexey@process-one.net>
6 %%%
7 %%%
8 %%% ejabberd, Copyright (C) 2002-2011 ProcessOne
9 %%%
10 %%% This program is free software; you can redistribute it and/or
11 %%% modify it under the terms of the GNU General Public License as
12 %%% published by the Free Software Foundation; either version 2 of the
13 %%% License, or (at your option) any later version.
14 %%%
15 %%% This program is distributed in the hope that it will be useful,
16 %%% but WITHOUT ANY WARRANTY; without even the implied warranty of
17 %%% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
18 %%% General Public License for more details.
19 %%%
20 %%% You should have received a copy of the GNU General Public License
21 %%% along with this program; if not, write to the Free Software
22 %%% Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
23 %%%
24 %%%----------------------------------------------------------------------
25
26 %%% @headerfile "ejabberd_ctl.hrl"
27
28 %%% @doc Management of mongooseimctl commands and frontend to ejabberd commands.
29 %%%
30 %%% An mongooseimctl command is an abstract function identified by a
31 %%% name, with a defined number of calling arguments, that can be
32 %%% defined in any Erlang module and executed using mongooseimctl
33 %%% administration script.
34 %%%
35 %%% Note: strings cannot have blankspaces
36 %%%
37 %%% Does not support commands that have arguments with ctypes: list, tuple
38 %%%
39 %%% TODO: Update the guide
40 %%% TODO: Mention this in the release notes
41 %%% Note: the commands with several words use now the underline: _
42
43
44 -module(ejabberd_ctl).
45 -author('alexey@process-one.net').
46
47 -export([start/0,
48 process/1]).
49
50 -ignore_xref([process/1, start/0]).
51
52 -include("ejabberd_ctl.hrl").
53 -include("mongoose_logger.hrl").
54
55 -type cmd() :: {CallString :: string(), Args :: [string()], Desc :: string()}.
56
57 -define(ASCII_SPACE_CHARACTER, $\s).
58 -define(PRINT(Format, Args), io:format(lists:flatten(Format), Args)).
59 -define(TIME_HMS_FORMAT, "~B days ~2.10.0B:~2.10.0B:~2.10.0B").
60 -define(a2l(A), atom_to_list(A)).
61
62 %%-----------------------------
63 %% Module
64 %%-----------------------------
65
66 -spec start() -> none().
67 start() ->
68
:-(
case init:get_plain_arguments() of
69 [SNode | Args] ->
70
:-(
SNode1 = case string:tokens(SNode, "@") of
71 [_Node, _Server] ->
72
:-(
SNode;
73 _ ->
74
:-(
case net_kernel:longnames() of
75 true ->
76
:-(
SNode ++ "@" ++ inet_db:gethostname() ++
77 "." ++ inet_db:res_option(domain);
78 false ->
79
:-(
SNode ++ "@" ++ inet_db:gethostname();
80 _ ->
81
:-(
SNode
82 end
83 end,
84
:-(
Node = list_to_atom(SNode1),
85
:-(
Status = case rpc:call(Node, ?MODULE, process, [Args]) of
86 {badrpc, Reason} ->
87
:-(
?PRINT("Failed RPC connection to the node ~p: ~p~n",
88 [Node, Reason]),
89 %% TODO: show minimal start help
90
:-(
?STATUS_BADRPC;
91 S ->
92
:-(
S
93 end,
94
:-(
halt(Status);
95 _ ->
96
:-(
print_usage(),
97
:-(
halt(?STATUS_USAGE)
98 end.
99
100 %%-----------------------------
101 %% Process
102 %%-----------------------------
103
104 %% @doc The commands status, stop and restart are defined here to ensure
105 %% they are usable even if ejabberd is completely stopped.
106 -spec process(_) -> integer().
107 process(["status"]) ->
108 2 {InternalStatus, ProvidedStatus} = init:get_status(),
109 2 MongooseStatus = get_mongoose_status(),
110 2 ?PRINT("~s", [format_status([{node, node()}, {internal_status, InternalStatus},
111 {provided_status, ProvidedStatus},
112 {mongoose_status, MongooseStatus},
113 {os_pid, os:getpid()}, get_uptime(),
114 {dist_proto, get_dist_proto()},
115 {logs, mongoose_logs:get_log_files()}])]),
116 2 case MongooseStatus of
117
:-(
not_running -> ?STATUS_ERROR;
118 2 {running, _, _Version} -> ?STATUS_SUCCESS
119 end;
120 process(["stop"]) ->
121 %%ejabberd_cover:stop(),
122
:-(
init:stop(),
123
:-(
?STATUS_SUCCESS;
124 process(["restart"]) ->
125
:-(
init:restart(),
126
:-(
?STATUS_SUCCESS;
127 process(["mnesia", "info"]) ->
128
:-(
mnesia:info(),
129
:-(
?STATUS_SUCCESS;
130 process(["graphql", Arg]) when is_list(Arg) ->
131 2 Doc = list_to_binary(Arg),
132 2 Ep = mongoose_graphql:get_endpoint(admin),
133 2 Result = mongoose_graphql:execute_cli(Ep, undefined, Doc),
134 2 handle_graphql_result(Result);
135 process(["graphql" | _]) ->
136 2 ?PRINT("This command requires one string type argument!\n", []),
137 2 ?STATUS_ERROR;
138
139 %% @doc The arguments --long and --dual are not documented because they are
140 %% automatically selected depending in the number of columns of the shell
141 process(["help" | Mode]) ->
142 4 {MaxC, ShCode} = get_shell_info(),
143 4 case Mode of
144 [] ->
145 1 print_usage(dual, MaxC, ShCode),
146 1 ?STATUS_USAGE;
147 ["--dual"] ->
148 1 print_usage(dual, MaxC, ShCode),
149 1 ?STATUS_USAGE;
150 ["--long"] ->
151 1 print_usage(long, MaxC, ShCode),
152 1 ?STATUS_USAGE;
153 [_] ->
154 1 print_usage(dual, MaxC, ShCode),
155 1 ?STATUS_USAGE
156 end;
157 process(Args) ->
158 652 case mongoose_graphql_commands:process(Args) of
159 #{status := executed, result := Result} ->
160 638 handle_graphql_result(Result);
161 #{status := error, reason := no_args} = Ctx ->
162 1 print_usage(Ctx),
163 1 ?STATUS_USAGE;
164 #{status := error} = Ctx ->
165 11 ?PRINT(error_message(Ctx) ++ "\n\n", []),
166 11 print_usage(Ctx),
167 11 ?STATUS_ERROR;
168 #{status := usage} = Ctx ->
169 2 print_usage(Ctx),
170 2 ?STATUS_SUCCESS % not STATUS_USAGE, as that would tell the script to print general help
171 end.
172
173 -spec error_message(mongoose_graphql_commands:context()) -> iolist().
174 error_message(#{reason := unknown_command, command := Command}) ->
175 2 io_lib:format("Unknown command '~s'", [Command]);
176 error_message(#{reason := invalid_args}) ->
177 2 "Could not parse the command arguments";
178 error_message(#{reason := unknown_category}) ->
179 2 "Unknown category";
180 error_message(#{reason := {unknown_arg, ArgName}, command := Command}) ->
181 1 io_lib:format("Unknown argument '~s' for command '~s'", [ArgName, Command]);
182 error_message(#{reason := {invalid_arg_value, ArgName, ArgValue}, command := Command}) ->
183 1 io_lib:format("Invalid value '~s' of argument '~s' for command '~s'",
184 [ArgValue, ArgName, Command]);
185 error_message(#{reason := {missing_args, MissingArgs}, command := Command}) ->
186 3 io_lib:format("Missing mandatory arguments for command '~s': ~s",
187 [Command, ["'", lists:join("', '", MissingArgs), "'"]]).
188
189 -spec print_usage(mongoose_graphql_commands:context()) -> any().
190 print_usage(#{category := Category, command := Command, args_spec := ArgsSpec}) ->
191 8 print_usage_command(Category, Command, ArgsSpec);
192 print_usage(#{category := Category, commands := Commands}) ->
193 3 print_usage_category(Category, Commands);
194 print_usage(_) ->
195 3 {MaxC, ShCode} = get_shell_info(),
196 3 print_usage(dual, MaxC, ShCode).
197
198 handle_graphql_result({ok, Result}) ->
199 596 JSONResult = mongoose_graphql_response:term_to_pretty_json(Result),
200 596 ?PRINT("~s\n", [JSONResult]),
201 596 case Result of
202 222 #{errors := _} -> ?STATUS_ERROR;
203 374 _ -> ?STATUS_SUCCESS
204 end;
205 handle_graphql_result({error, Reason}) ->
206 44 {_Code, Error} = mongoose_graphql_errors:format_error(Reason),
207 44 JSONResult = jiffy:encode(#{errors => [Error]}, [pretty]),
208 44 ?PRINT("~s\n", [JSONResult]),
209 44 ?STATUS_ERROR.
210
211 %%-----------------------------
212 %% Format arguments
213 %%-----------------------------
214 format_status([{node, Node}, {internal_status, IS}, {provided_status, PS},
215 {mongoose_status, MS}, {os_pid, OSPid}, {uptime, UptimeHMS},
216 {dist_proto, DistProto}, {logs, LogFiles}]) ->
217 ( ["MongooseIM node ", ?a2l(Node), ":\n",
218 " operating system pid: ", OSPid, "\n",
219 " Erlang VM status: ", ?a2l(IS), " (of: starting | started | stopping)\n",
220 " boot script status: ", io_lib:format("~p", [PS]), "\n",
221 " version: ", case MS of
222 2 {running, App, Version} -> [Version, " (as ", ?a2l(App), ")"];
223
:-(
not_running -> "unavailable - neither ejabberd nor mongooseim is running"
224 end, "\n",
225 " uptime: ", io_lib:format(?TIME_HMS_FORMAT, UptimeHMS), "\n",
226 2 " distribution protocol: ", DistProto, "\n"] ++
227
:-(
[" logs: none - maybe enable logging to a file in app.config?\n" || LogFiles == [] ] ++
228 2 [" logs:\n" || LogFiles /= [] ] ++ [
229 4 [" ", LogFile, "\n"] || LogFile <- LogFiles ] ).
230
231 %%-----------------------------
232 %% Print help
233 %%-----------------------------
234
235 %% Bold
236 -define(B1, "\e[1m").
237 -define(B2, "\e[22m").
238 -define(B(S), case ShCode of true -> [?B1, S, ?B2]; false -> S end).
239
240 %% Underline
241 -define(U1, "\e[4m").
242 -define(U2, "\e[24m").
243 -define(U(S), case ShCode of true -> [?U1, S, ?U2]; false -> S end).
244
245 print_usage() ->
246
:-(
{MaxC, ShCode} = get_shell_info(),
247
:-(
print_usage(dual, MaxC, ShCode).
248
249
250 -spec print_usage(dual | long, MaxC :: integer(), ShCode :: boolean()) -> ok.
251 print_usage(HelpMode, MaxC, ShCode) ->
252 7 ?PRINT(["Usage: ", ?B("mongooseimctl"), " [", ?U("category"), "] ", ?U("command"),
253 7 " [", ?U("arguments"), "]\n\n"
254 "Most MongooseIM commands are grouped into the following categories:\n"], []),
255 7 print_categories(HelpMode, MaxC, ShCode),
256 7 ?PRINT(["\nTo list the commands in a particular category:\n mongooseimctl ", ?U("category"),
257 "\n"], []).
258
259 -spec print_categories(dual | long, MaxC :: integer(), ShCode :: boolean()) -> ok.
260 print_categories(HelpMode, MaxC, ShCode) ->
261 7 SortedSpecs = lists:sort(maps:to_list(mongoose_graphql_commands:get_specs())),
262 7 Categories = [{binary_to_list(Category), [], binary_to_list(Desc)}
263 7 || {Category, #{desc := Desc}} <- SortedSpecs],
264 7 print_usage_commands(HelpMode, MaxC, ShCode, Categories).
265
266 -spec print_usage_category(mongoose_graphql_commands:category(),
267 mongoose_graphql_commands:command_map()) -> ok.
268 print_usage_category(Category, Commands) ->
269 3 {MaxC, ShCode} = get_shell_info(),
270 3 ?PRINT(["Usage: ", ?B("mongooseimctl"), " ", Category, " ", ?U("command"), " ", ?U("arguments"), "\n"
271 "\n"
272 "The following commands are available in the category '", Category, "':\n"], []),
273 3 CmdSpec = [{binary_to_list(Command), [], binary_to_list(Desc)}
274 3 || {Command, #{desc := Desc}} <- maps:to_list(Commands)],
275 3 print_usage_commands(dual, MaxC, ShCode, CmdSpec),
276 3 ?PRINT(["\nTo list the arguments for a particular command:\n"
277 3 " mongooseimctl ", Category, " ", ?U("command"), " --help", "\n"], []).
278
279 -spec print_usage_command(mongoose_graphql_commands:category(),
280 mongoose_graphql_commands:command(),
281 [mongoose_graphql_commands:arg_spec()]) -> ok.
282 print_usage_command(Category, Command, ArgsSpec) ->
283 8 {MaxC, ShCode} = get_shell_info(),
284 8 ?PRINT(["Usage: ", ?B("mongooseimctl"), " ", Category, " ", Command, " ", ?U("arguments"), "\n"
285 "\n",
286 8 "Each argument has the format: --", ?U("name"), " ", ?U("value"), "\n",
287 "Available arguments are listed below with the corresponding GraphQL types:\n"], []),
288 %% Reuse the function initially designed for printing commands for now
289 %% This will be replaced with new logic when old commands are dropped
290 8 Args = [{binary_to_list(Name), [], mongoose_graphql_commands:wrap_type(Wrap, Type)}
291 8 || #{name := Name, type := Type, wrap := Wrap} <- ArgsSpec],
292 8 print_usage_commands(dual, MaxC, ShCode, Args),
293 8 ?PRINT(["\nScalar values do not need quoting unless they contain special characters or spaces.\n"
294 "Complex input types are passed as JSON maps or lists, depending on the type.\n"
295 "When a type is followed by '!', the corresponding argument is required.\n"], []).
296
297 -spec print_usage_commands(HelpMode :: 'dual' | 'long',
298 MaxC :: integer(),
299 ShCode :: boolean(),
300 Commands :: [cmd(), ...]) -> 'ok'.
301 print_usage_commands(HelpMode, MaxC, ShCode, Commands) ->
302 18 CmdDescsSorted = lists:keysort(1, Commands),
303
304 %% What is the length of the largest command?
305 18 {CmdArgsLenDescsSorted, Lens} =
306 lists:mapfoldl(
307 fun({Cmd, Args, Desc}, Lengths) ->
308 180 Len =
309 length(Cmd) +
310 lists:foldl(fun(Arg, R) ->
311
:-(
R + 1 + length(Arg)
312 end,
313 0,
314 Args),
315 180 {{Cmd, Args, Len, Desc}, [Len | Lengths]}
316 end,
317 [],
318 CmdDescsSorted),
319 18 MaxCmdLen = case Lens of
320
:-(
[] -> 80;
321 18 _ -> lists:max(Lens)
322 end,
323
324 %% For each command in the list of commands
325 %% Convert its definition to a line
326 18 FmtCmdDescs = format_command_lines(CmdArgsLenDescsSorted, MaxCmdLen, MaxC, ShCode, HelpMode),
327 18 ?PRINT([FmtCmdDescs], []).
328
329 %% @doc Get some info about the shell: how many columns of width and guess if
330 %% it supports text formatting codes.
331 -spec get_shell_info() -> {integer(), boolean()}.
332 get_shell_info() ->
333 18 case io:columns() of
334
:-(
{ok, C} -> {C-2, true};
335 18 {error, enotsup} -> {78, false}
336 end.
337
338 %% @doc Split this command description in several lines of proper length
339 -spec prepare_description(DescInit :: non_neg_integer(),
340 MaxC :: integer(),
341 Desc :: string()) -> [[[any()]], ...].
342 prepare_description(DescInit, MaxC, Desc) ->
343 180 Words = string:tokens(Desc, " \n"),
344 180 prepare_long_line(DescInit, MaxC, Words).
345
346 -spec prepare_long_line(DescInit :: non_neg_integer(),
347 MaxC :: integer(),
348 Words :: [nonempty_string()]
349 ) -> [[[any()]], ...].
350 prepare_long_line(DescInit, MaxC, Words) ->
351 180 MaxSegmentLen = MaxC - DescInit,
352 180 MarginString = lists:duplicate(DescInit, ?ASCII_SPACE_CHARACTER), % Put spaces
353 180 [FirstSegment | MoreSegments] = split_desc_segments(MaxSegmentLen, Words),
354 180 MoreSegmentsMixed = mix_desc_segments(MarginString, MoreSegments),
355 180 [FirstSegment | MoreSegmentsMixed].
356
357 -spec mix_desc_segments(MarginStr :: [any()],
358 Segments :: [[[any(), ...]]]) -> [[[any()], ...]].
359 mix_desc_segments(MarginString, Segments) ->
360 180 [["\n", MarginString, Segment] || Segment <- Segments].
361
362 split_desc_segments(MaxL, Words) ->
363 180 join(MaxL, Words).
364
365 %% @doc Join words in a segment, but stop adding to a segment if adding this
366 %% word would pass L
367 -spec join(L :: number(), Words :: [nonempty_string()]) -> [[[any(), ...]], ...].
368 join(L, Words) ->
369 180 join(L, Words, 0, [], []).
370
371
372 -spec join(L :: number(),
373 Words :: [nonempty_string()],
374 LenLastSeg :: non_neg_integer(),
375 LastSeg :: [nonempty_string()],
376 ResSeg :: [[[any(), ...]]] ) -> [[[any(), ...]], ...].
377 join(_L, [], _LenLastSeg, LastSeg, ResSeg) ->
378 180 ResSeg2 = [lists:reverse(LastSeg) | ResSeg],
379 180 lists:reverse(ResSeg2);
380 join(L, [Word | Words], LenLastSeg, LastSeg, ResSeg) ->
381 747 LWord = length(Word),
382 747 case LWord + LenLastSeg < L of
383 true ->
384 %% This word fits in the last segment
385 %% If this word ends with "\n", reset column counter
386 738 case string:str(Word, "\n") of
387 0 ->
388 738 join(L, Words, LenLastSeg+LWord+1, [" ", Word | LastSeg], ResSeg);
389 _ ->
390
:-(
join(L, Words, LWord+1, [" ", Word | LastSeg], ResSeg)
391 end;
392 false ->
393 9 join(L, Words, LWord, [" ", Word], [lists:reverse(LastSeg) | ResSeg])
394 end.
395
396 -spec format_command_lines(CALD :: [{[any()], [any()], number(), _}, ...],
397 MaxCmdLen :: integer(),
398 MaxC :: integer(),
399 ShCode :: boolean(),
400 'dual' | 'long') -> [[any(), ...], ...].
401 format_command_lines(CALD, MaxCmdLen, MaxC, ShCode, dual)
402 when MaxC - MaxCmdLen < 40 ->
403 %% If the space available for descriptions is too narrow, enforce long help mode
404
:-(
format_command_lines(CALD, MaxCmdLen, MaxC, ShCode, long);
405 format_command_lines(CALD, MaxCmdLen, MaxC, ShCode, dual) ->
406 17 lists:map(
407 fun({Cmd, Args, CmdArgsL, Desc}) ->
408 160 DescFmt = prepare_description(MaxCmdLen+4, MaxC, Desc),
409 160 [" ", ?B(Cmd), " ", [[?U(Arg), " "] || Arg <- Args], string:chars(?ASCII_SPACE_CHARACTER, MaxCmdLen - CmdArgsL + 1),
410 DescFmt, "\n"]
411 end, CALD);
412 format_command_lines(CALD, _MaxCmdLen, MaxC, ShCode, long) ->
413 1 lists:map(
414 fun({Cmd, Args, _CmdArgsL, Desc}) ->
415 20 DescFmt = prepare_description(8, MaxC, Desc),
416 20 ["\n ", ?B(Cmd), " ", [[?U(Arg), " "] || Arg <- Args], "\n", " ",
417 DescFmt, "\n"]
418 end, CALD).
419
420 %%-----------------------------
421 %% Print usage command
422 %%-----------------------------
423
424 get_mongoose_status() ->
425 2 case lists:keyfind(mongooseim, 1, application:which_applications()) of
426 false ->
427
:-(
not_running;
428 {_, _, Version} ->
429 2 {running, mongooseim, Version}
430 end.
431
432 get_uptime() ->
433 2 {MilliSeconds, _} = erlang:statistics(wall_clock),
434 2 {D, {H, M, S}} = calendar:seconds_to_daystime(MilliSeconds div 1000),
435 2 {uptime, [D, H, M, S]}.
436
437 get_dist_proto() ->
438 %% See kernel/src/net_kernel.erl
439 2 case init:get_argument(proto_dist) of
440
:-(
{ok, [Proto]} -> Proto;
441 2 _ -> "inet_tcp"
442 end.
Line Hits Source