refactor(listeners): use emqx_ctl to print cli messages

It's better to keep cli print behaviour consistent.

It also makes tests easier as they can meck emqx_ctl:print to
validate the output.
This commit is contained in:
Zaiming Shi 2021-02-14 20:40:01 +01:00
parent 2d79c870c1
commit dfa9bbc0c2
2 changed files with 18 additions and 17 deletions

View File

@ -554,12 +554,17 @@ listeners(_) ->
]).
stop_listener(false, Input) ->
emqx_ctl:print("No such listener ~p~n", [Input]);
stop_listener(#{} = Listener, _Input) ->
%% Discard reason here, reasons are io:format logged to group leader
%% in case of emqx_ctl RPC call, it's logged to the remore node.
_ = emqx_listeners:stop_listener(Listener),
ok.
ok = emqx_ctl:print("No such listener ~p~n", [Input]);
stop_listener(#{listen_on := ListenOn} = Listener, _Input) ->
ID = emqx_listeners:identifier(Listener),
ListenOnStr = emqx_listeners:format_listen_on(ListenOn),
case emqx_listeners:stop_listener(Listener) of
ok ->
ok = emqx_ctl:print("Stop ~s listener on ~s successfully.~n", [ID, ListenOnStr]);
{error, Reason} ->
ok = emqx_ctl:print("Failed to stop ~s listener on ~s - ~p~n.",
[ID, ListenOnStr, Reason])
end.
%%--------------------------------------------------------------------
%% @doc data Command

View File

@ -28,7 +28,6 @@
-export([ start_listener/1
, start_listener/3
, stop_listener/1
, stop_listener/3
, restart_listener/1
, restart_listener/3
]).
@ -37,6 +36,7 @@
, find_by_listen_on/1
, find_by_id/1
, identifier/1
, format_listen_on/1
]).
-type(listener() :: #{ name := binary()
@ -76,6 +76,10 @@ identifier(#{proto := Proto, name := Name}) ->
start() ->
lists:foreach(fun start_listener/1, emqx:get_env(listeners, [])).
%% @doc Format address:port for logging.
-spec(format_listen_on(esockd:listen_on()) -> binary()).
format_listen_on(ListenOn) -> format(ListenOn).
-spec(start_listener(listener()) -> ok).
start_listener(#{proto := Proto, name := Name, listen_on := ListenOn, opts := Options}) ->
ID = identifier(Proto, Name),
@ -171,16 +175,8 @@ stop() ->
lists:foreach(fun stop_listener/1, emqx:get_env(listeners, [])).
-spec(stop_listener(listener()) -> ok | {error, term()}).
stop_listener(#{proto := Proto, name := Name, listen_on := ListenOn, opts := Opts}) ->
ID = identifier(Proto, Name),
StopRet = stop_listener(Proto, ListenOn, Opts),
case StopRet of
ok -> io:format("Stop ~s listener on ~s successfully.~n", [ID, format(ListenOn)]);
{error, Reason} ->
io:format(standard_error, "Failed to stop mqtt:~s listener on ~s - ~p~n.",
[ID, format(ListenOn), Reason])
end,
StopRet.
stop_listener(#{proto := Proto, listen_on := ListenOn, opts := Opts}) ->
stop_listener(Proto, ListenOn, Opts).
-spec(stop_listener(esockd:proto(), esockd:listen_on(), [esockd:option()])
-> ok | {error, term()}).