cowboy_listener.erl 5.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168
  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/0, stop/1,
  18. add_connection/3, move_connection/3, remove_connection/2, wait/3]). %% API.
  19. -export([init/1, handle_call/3, handle_cast/2,
  20. handle_info/2, terminate/2, code_change/3]). %% gen_server.
  21. -record(state, {
  22. req_pools = [] :: [{atom(), non_neg_integer()}],
  23. reqs_table :: ets:tid(),
  24. queue = [] :: [{pid(), reference()}]
  25. }).
  26. %% API.
  27. %% @private
  28. -spec start_link() -> {ok, pid()}.
  29. start_link() ->
  30. gen_server:start_link(?MODULE, [], []).
  31. %% @private
  32. -spec stop(pid()) -> stopped.
  33. stop(ServerPid) ->
  34. gen_server:call(ServerPid, stop).
  35. %% @doc Add a connection to the given pool in the listener.
  36. %%
  37. %% Pools of connections are used to restrict the maximum number of connections
  38. %% depending on their type. By default, Cowboy add all connections to the
  39. %% pool <em>default</em>. It also checks for the maximum number of connections
  40. %% in that pool before accepting again.
  41. %%
  42. %% When a process managing a connection dies, the process is removed from the
  43. %% pool. If the socket has been sent to another process, it is up to the
  44. %% protocol code to inform the listener of the new <em>ConnPid</em> by removing
  45. %% the previous and adding the new one.
  46. -spec add_connection(pid(), atom(), pid()) -> {ok, non_neg_integer()}.
  47. add_connection(ServerPid, Pool, ConnPid) ->
  48. gen_server:call(ServerPid, {add_connection, Pool, ConnPid}).
  49. %% @doc Move a connection from one pool to another.
  50. -spec move_connection(pid(), atom(), pid()) -> ok.
  51. move_connection(ServerPid, DestPool, ConnPid) ->
  52. gen_server:cast(ServerPid, {move_connection, DestPool, ConnPid}).
  53. %% @doc Remove the given connection from its pool.
  54. -spec remove_connection(pid(), pid()) -> ok.
  55. remove_connection(ServerPid, ConnPid) ->
  56. gen_server:cast(ServerPid, {remove_connection, ConnPid}).
  57. %% @doc Wait until the number of connections in the given pool gets below
  58. %% the given threshold.
  59. %%
  60. %% This function will not return until the number of connections in the pool
  61. %% gets below <em>MaxConns</em>. It makes use of <em>gen_server:reply/2</em>
  62. %% to make the process wait for a reply indefinitely.
  63. -spec wait(pid(), atom(), non_neg_integer()) -> ok.
  64. wait(ServerPid, Pool, MaxConns) ->
  65. gen_server:call(ServerPid, {wait, Pool, MaxConns}, infinity).
  66. %% gen_server.
  67. %% @private
  68. -spec init([]) -> {ok, #state{}}.
  69. init([]) ->
  70. ReqsTablePid = ets:new(requests_table, [set, private]),
  71. {ok, #state{reqs_table=ReqsTablePid}}.
  72. %% @private
  73. -spec handle_call(_, _, State)
  74. -> {reply, ignored, State} | {stop, normal, stopped, State}.
  75. handle_call({add_connection, Pool, ConnPid}, _From, State=#state{
  76. req_pools=Pools, reqs_table=ReqsTable}) ->
  77. MonitorRef = erlang:monitor(process, ConnPid),
  78. {NbConnsRet, Pools2} = case lists:keyfind(Pool, 1, Pools) of
  79. false ->
  80. {1, [{Pool, 1}|Pools]};
  81. {Pool, NbConns} ->
  82. NbConns2 = NbConns + 1,
  83. {NbConns2, [{Pool, NbConns2}|lists:keydelete(Pool, 1, Pools)]}
  84. end,
  85. ets:insert(ReqsTable, {ConnPid, {MonitorRef, Pool}}),
  86. {reply, {ok, NbConnsRet}, State#state{req_pools=Pools2}};
  87. handle_call({wait, Pool, MaxConns}, From, State=#state{
  88. req_pools=Pools, queue=Queue}) ->
  89. case lists:keyfind(Pool, 1, Pools) of
  90. {Pool, NbConns} when NbConns > MaxConns ->
  91. {noreply, State#state{queue=[From|Queue]}};
  92. _Any ->
  93. {reply, ok, State}
  94. end;
  95. handle_call(stop, _From, State) ->
  96. {stop, normal, stopped, State};
  97. handle_call(_Request, _From, State) ->
  98. {reply, ignored, State}.
  99. %% @private
  100. -spec handle_cast(_, State) -> {noreply, State}.
  101. handle_cast({move_connection, DestPool, ConnPid}, State=#state{
  102. req_pools=Pools, reqs_table=ReqsTable}) ->
  103. {MonitorRef, SrcPool} = ets:lookup_element(ReqsTable, ConnPid, 2),
  104. ets:insert(ReqsTable, {ConnPid, {MonitorRef, DestPool}}),
  105. {SrcPool, SrcNbConns} = lists:keyfind(SrcPool, 1, Pools),
  106. DestNbConns = case lists:keyfind(DestPool, 1, Pools) of
  107. false -> 1;
  108. {DestPool, NbConns} -> NbConns + 1
  109. end,
  110. Pools2 = lists:keydelete(SrcPool, 1, lists:keydelete(DestPool, 1, Pools)),
  111. Pools3 = [{SrcPool, SrcNbConns - 1}, {DestPool, DestNbConns}|Pools2],
  112. {noreply, State#state{req_pools=Pools3}};
  113. handle_cast({remove_connection, ConnPid}, State) ->
  114. State2 = remove_pid(ConnPid, State),
  115. {noreply, State2};
  116. handle_cast(_Msg, State) ->
  117. {noreply, State}.
  118. %% @private
  119. -spec handle_info(_, State) -> {noreply, State}.
  120. handle_info({'DOWN', _Ref, process, Pid, _Info}, State) ->
  121. State2 = remove_pid(Pid, State),
  122. {noreply, State2};
  123. handle_info(_Info, State) ->
  124. {noreply, State}.
  125. %% @private
  126. -spec terminate(_, _) -> ok.
  127. terminate(_Reason, _State) ->
  128. ok.
  129. %% @private
  130. -spec code_change(_, State, _) -> {ok, State}.
  131. code_change(_OldVsn, State, _Extra) ->
  132. {ok, State}.
  133. %% Internal.
  134. %% @private
  135. -spec remove_pid(pid(), State) -> State.
  136. remove_pid(Pid, State=#state{
  137. req_pools=Pools, reqs_table=ReqsTable, queue=Queue}) ->
  138. {MonitorRef, Pool} = ets:lookup_element(ReqsTable, Pid, 2),
  139. erlang:demonitor(MonitorRef, [flush]),
  140. {Pool, NbConns} = lists:keyfind(Pool, 1, Pools),
  141. Pools2 = [{Pool, NbConns - 1}|lists:keydelete(Pool, 1, Pools)],
  142. ets:delete(ReqsTable, Pid),
  143. case Queue of
  144. [] ->
  145. State#state{req_pools=Pools2};
  146. [Client|Queue2] ->
  147. gen_server:reply(Client, ok),
  148. State#state{req_pools=Pools2, queue=Queue2}
  149. end.