1 |
|
%% @doc Manage starting and stopping of configured listeners |
2 |
|
|
3 |
|
-module(mongoose_listener). |
4 |
|
|
5 |
|
-include("mongoose.hrl"). |
6 |
|
|
7 |
|
%% Only for tests |
8 |
|
-export([start_listener/1, stop_listener/1]). |
9 |
|
-ignore_xref([start_listener/1, stop_listener/1]). |
10 |
|
|
11 |
|
%% API |
12 |
|
-export([start/0, stop/0, socket_type/1]). |
13 |
|
|
14 |
|
-callback start_listener(options()) -> ok. |
15 |
|
-callback socket_type() -> socket_type(). |
16 |
|
|
17 |
|
-type options() :: #{port := inet:port_number(), |
18 |
|
ip_tuple := inet:ip_address(), |
19 |
|
ip_address := string(), |
20 |
|
ip_version := 4 | 6, |
21 |
|
proto := proto(), |
22 |
|
any() => any()}. |
23 |
|
-type id() :: {inet:port_number(), inet:ip_address(), proto()}. |
24 |
|
-type proto() :: tcp. |
25 |
|
-type socket_type() :: independent | xml_stream | raw. |
26 |
|
|
27 |
|
-export_type([options/0, id/0, proto/0, socket_type/0]). |
28 |
|
|
29 |
|
%% API |
30 |
|
|
31 |
|
start() -> |
32 |
76 |
lists:foreach(fun start_listener/1, mongoose_config:get_opt(listen)). |
33 |
|
|
34 |
|
stop() -> |
35 |
76 |
lists:foreach(fun stop_listener/1, mongoose_config:get_opt(listen)). |
36 |
|
|
37 |
|
-spec socket_type(module()) -> any(). |
38 |
|
socket_type(Module) -> |
39 |
5502 |
Module:socket_type(). |
40 |
|
|
41 |
|
%% Internal functions |
42 |
|
|
43 |
|
start_listener(Opts = #{module := Module}) -> |
44 |
988 |
try |
45 |
988 |
Module:start_listener(Opts) % This function should call mongoose_listener_sup:start_child/1 |
46 |
|
catch |
47 |
|
Class:Reason:Stacktrace -> |
48 |
:-( |
?LOG_CRITICAL(#{what => listener_failed_to_start, |
49 |
|
text => <<"Failed to start a listener">>, |
50 |
|
module => Module, opts => Opts, |
51 |
:-( |
class => Class, reason => Reason, stacktrace => Stacktrace}), |
52 |
:-( |
erlang:raise(Class, Reason, Stacktrace) |
53 |
|
end. |
54 |
|
|
55 |
|
stop_listener(Opts) -> |
56 |
988 |
ListenerId = mongoose_listener_config:listener_id(Opts), |
57 |
988 |
supervisor:terminate_child(mongoose_listener_sup, ListenerId), |
58 |
988 |
supervisor:delete_child(mongoose_listener_sup, ListenerId). |