cowboy_listener.erl 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211
  1. %% Copyright (c) 2011, Loïc Hoguin <essen@dev-extend.eu>
  2. %%
  3. %% Permission to use, copy, modify, and/or distribute this software for any
  4. %% purpose with or without fee is hereby granted, provided that the above
  5. %% copyright notice and this permission notice appear in all copies.
  6. %%
  7. %% THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
  8. %% WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
  9. %% MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
  10. %% ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
  11. %% WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
  12. %% ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
  13. %% OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
  14. %% @doc Public API for managing listeners.
  15. -module(cowboy_listener).
  16. -behaviour(gen_server).
  17. -export([start_link/2, stop/1,
  18. add_connection/4, move_connection/3, remove_connection/2,
  19. get_protocol_options/1, set_protocol_options/2]). %% API.
  20. -export([init/1, handle_call/3, handle_cast/2,
  21. handle_info/2, terminate/2, code_change/3]). %% gen_server.
  22. -type pools() :: [{atom(), non_neg_integer()}].
  23. -record(state, {
  24. req_pools = [] :: pools(),
  25. reqs_table :: ets:tid(),
  26. queue = undefined :: queue(),
  27. max_conns = undefined :: non_neg_integer(),
  28. proto_opts :: any(),
  29. proto_opts_vsn = 1 :: non_neg_integer()
  30. }).
  31. %% API.
  32. %% @private
  33. %%
  34. %% We set the process priority to high because cowboy_listener is the central
  35. %% gen_server in Cowboy and is used to manage all the incoming connections.
  36. %% Setting the process priority to high ensures the connection-related code
  37. %% will always be executed when a connection needs it, allowing Cowboy to
  38. %% scale far beyond what it would with a normal priority.
  39. -spec start_link(non_neg_integer(), any()) -> {ok, pid()}.
  40. start_link(MaxConns, ProtoOpts) ->
  41. gen_server:start_link(?MODULE, [MaxConns, ProtoOpts],
  42. [{spawn_opt, [{priority, high}]}]).
  43. %% @private
  44. -spec stop(pid()) -> stopped.
  45. stop(ServerPid) ->
  46. gen_server:call(ServerPid, stop).
  47. %% @doc Add a connection to the given pool in the listener.
  48. %%
  49. %% Pools of connections are used to restrict the maximum number of connections
  50. %% depending on their type. By default, Cowboy add all connections to the
  51. %% pool <em>default</em>. It also checks for the maximum number of connections
  52. %% in that pool before accepting again. This function only returns when there
  53. %% is free space in the pool.
  54. %%
  55. %% When a process managing a connection dies, the process is removed from the
  56. %% pool. If the socket has been sent to another process, it is up to the
  57. %% protocol code to inform the listener of the new <em>ConnPid</em> by removing
  58. %% the previous and adding the new one.
  59. %%
  60. %% This function also returns whether the protocol options have been modified.
  61. %% If so, then an {upgrade, ProtoOpts, OptsVsn} will be returned instead of
  62. %% the atom 'ok'. The acceptor can then continue with the new protocol options.
  63. -spec add_connection(pid(), atom(), pid(), non_neg_integer())
  64. -> ok | {upgrade, any(), non_neg_integer()}.
  65. add_connection(ServerPid, Pool, ConnPid, OptsVsn) ->
  66. gen_server:call(ServerPid, {add_connection, Pool, ConnPid, OptsVsn},
  67. infinity).
  68. %% @doc Move a connection from one pool to another.
  69. -spec move_connection(pid(), atom(), pid()) -> ok.
  70. move_connection(ServerPid, DestPool, ConnPid) ->
  71. gen_server:cast(ServerPid, {move_connection, DestPool, ConnPid}).
  72. %% @doc Remove the given connection from its pool.
  73. -spec remove_connection(pid(), pid()) -> ok.
  74. remove_connection(ServerPid, ConnPid) ->
  75. gen_server:cast(ServerPid, {remove_connection, ConnPid}).
  76. %% @doc Return the current protocol options.
  77. -spec get_protocol_options(pid()) -> {ok, any()}.
  78. get_protocol_options(ServerPid) ->
  79. gen_server:call(ServerPid, get_protocol_options).
  80. %% @doc Upgrade the protocol options.
  81. -spec set_protocol_options(pid(), any()) -> ok.
  82. set_protocol_options(ServerPid, ProtoOpts) ->
  83. gen_server:call(ServerPid, {set_protocol_options, ProtoOpts}).
  84. %% gen_server.
  85. %% @private
  86. -spec init(list()) -> {ok, #state{}}.
  87. init([MaxConns, ProtoOpts]) ->
  88. ReqsTable = ets:new(requests_table, [set, private]),
  89. Queue = queue:new(),
  90. {ok, #state{reqs_table=ReqsTable, max_conns=MaxConns,
  91. proto_opts=ProtoOpts, queue=Queue}}.
  92. %% @private
  93. -spec handle_call(_, _, State)
  94. -> {reply, ignored, State} | {stop, normal, stopped, State}.
  95. handle_call({add_connection, Pool, ConnPid, AccOptsVsn}, From, State=#state{
  96. req_pools=Pools, reqs_table=ReqsTable,
  97. queue=Queue, max_conns=MaxConns,
  98. proto_opts=ProtoOpts, proto_opts_vsn=LisOptsVsn}) ->
  99. {NbConns, Pools2} = add_pid(ConnPid, Pool, Pools, ReqsTable),
  100. State2 = State#state{req_pools=Pools2},
  101. if AccOptsVsn =/= LisOptsVsn ->
  102. {reply, {upgrade, ProtoOpts, LisOptsVsn}, State2};
  103. NbConns > MaxConns ->
  104. Queue2 = queue:in(From, Queue),
  105. {noreply, State2#state{queue=Queue2}};
  106. true ->
  107. {reply, ok, State2}
  108. end;
  109. handle_call(get_protocol_options, _From, State=#state{proto_opts=ProtoOpts}) ->
  110. {reply, {ok, ProtoOpts}, State};
  111. handle_call({set_protocol_options, ProtoOpts}, _From,
  112. State=#state{proto_opts_vsn=OptsVsn}) ->
  113. {reply, ok, State#state{proto_opts=ProtoOpts, proto_opts_vsn=OptsVsn + 1}};
  114. handle_call(stop, _From, State) ->
  115. {stop, normal, stopped, State};
  116. handle_call(_Request, _From, State) ->
  117. {reply, ignored, State}.
  118. %% @private
  119. -spec handle_cast(_, State) -> {noreply, State}.
  120. handle_cast({move_connection, DestPool, ConnPid}, State=#state{
  121. req_pools=Pools, reqs_table=ReqsTable}) ->
  122. Pools2 = move_pid(ConnPid, DestPool, Pools, ReqsTable),
  123. {noreply, State#state{req_pools=Pools2}};
  124. handle_cast({remove_connection, ConnPid}, State=#state{
  125. req_pools=Pools, reqs_table=ReqsTable, queue=Queue}) ->
  126. {Pools2, Queue2} = remove_pid(ConnPid, Pools, ReqsTable, Queue),
  127. {noreply, State#state{req_pools=Pools2, queue=Queue2}};
  128. handle_cast(_Msg, State) ->
  129. {noreply, State}.
  130. %% @private
  131. -spec handle_info(_, State) -> {noreply, State}.
  132. handle_info({'DOWN', _Ref, process, Pid, _Info}, State=#state{
  133. req_pools=Pools, reqs_table=ReqsTable, queue=Queue}) ->
  134. {Pools2, Queue2} = remove_pid(Pid, Pools, ReqsTable, Queue),
  135. {noreply, State#state{req_pools=Pools2, queue=Queue2}};
  136. handle_info(_Info, State) ->
  137. {noreply, State}.
  138. %% @private
  139. -spec terminate(_, _) -> ok.
  140. terminate(_Reason, _State) ->
  141. ok.
  142. %% @private
  143. -spec code_change(_, State, _) -> {ok, State}.
  144. code_change(_OldVsn, State, _Extra) ->
  145. {ok, State}.
  146. %% Internal.
  147. %% @private
  148. -spec add_pid(pid(), atom(), pools(), ets:tid())
  149. -> {non_neg_integer(), pools()}.
  150. add_pid(ConnPid, Pool, Pools, ReqsTable) ->
  151. MonitorRef = erlang:monitor(process, ConnPid),
  152. ConnPid ! {shoot, self()},
  153. {NbConnsRet, Pools2} = case lists:keyfind(Pool, 1, Pools) of
  154. false ->
  155. {1, [{Pool, 1}|Pools]};
  156. {Pool, NbConns} ->
  157. NbConns2 = NbConns + 1,
  158. {NbConns2, [{Pool, NbConns2}|lists:keydelete(Pool, 1, Pools)]}
  159. end,
  160. ets:insert(ReqsTable, {ConnPid, {MonitorRef, Pool}}),
  161. {NbConnsRet, Pools2}.
  162. %% @private
  163. -spec move_pid(pid(), atom(), pools(), ets:tid()) -> pools().
  164. move_pid(ConnPid, DestPool, Pools, ReqsTable) ->
  165. {MonitorRef, SrcPool} = ets:lookup_element(ReqsTable, ConnPid, 2),
  166. ets:insert(ReqsTable, {ConnPid, {MonitorRef, DestPool}}),
  167. {SrcPool, SrcNbConns} = lists:keyfind(SrcPool, 1, Pools),
  168. DestNbConns = case lists:keyfind(DestPool, 1, Pools) of
  169. false -> 1;
  170. {DestPool, NbConns} -> NbConns + 1
  171. end,
  172. Pools2 = lists:keydelete(SrcPool, 1, lists:keydelete(DestPool, 1, Pools)),
  173. [{SrcPool, SrcNbConns - 1}, {DestPool, DestNbConns}|Pools2].
  174. %% @private
  175. -spec remove_pid(pid(), pools(), ets:tid(), queue()) -> {pools(), queue()}.
  176. remove_pid(Pid, Pools, ReqsTable, Queue) ->
  177. {MonitorRef, Pool} = ets:lookup_element(ReqsTable, Pid, 2),
  178. erlang:demonitor(MonitorRef, [flush]),
  179. {Pool, NbConns} = lists:keyfind(Pool, 1, Pools),
  180. Pools2 = [{Pool, NbConns - 1}|lists:keydelete(Pool, 1, Pools)],
  181. ets:delete(ReqsTable, Pid),
  182. case queue:out(Queue) of
  183. {{value, Client}, Queue2} ->
  184. gen_server:reply(Client, ok),
  185. {Pools2, Queue2};
  186. _ ->
  187. {Pools2, Queue}
  188. end.