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