cowboy_acceptor.erl 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  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. %% @private
  15. -module(cowboy_acceptor).
  16. -export([start_link/6]). %% API.
  17. -export([acceptor/6]). %% Internal.
  18. %% API.
  19. -spec start_link(inet:socket(), module(), module(), any(),
  20. non_neg_integer(), pid()) -> {ok, pid()}.
  21. start_link(LSocket, Transport, Protocol, Opts, MaxConns, ReqsSup) ->
  22. Pid = spawn_link(?MODULE, acceptor,
  23. [LSocket, Transport, Protocol, Opts, MaxConns, ReqsSup]),
  24. {ok, Pid}.
  25. %% Internal.
  26. -spec acceptor(inet:socket(), module(), module(), any(),
  27. non_neg_integer(), pid()) -> no_return().
  28. acceptor(LSocket, Transport, Protocol, Opts, MaxConns, ReqsSup) ->
  29. case Transport:accept(LSocket, 2000) of
  30. {ok, CSocket} ->
  31. {ok, Pid} = supervisor:start_child(ReqsSup,
  32. [CSocket, Transport, Protocol, Opts]),
  33. Transport:controlling_process(CSocket, Pid),
  34. limit_reqs(MaxConns, ReqsSup);
  35. {error, timeout} ->
  36. ignore;
  37. {error, _Reason} ->
  38. %% @todo Probably do something here. If the socket was closed,
  39. %% we may want to try and listen again on the port?
  40. ignore
  41. end,
  42. ?MODULE:acceptor(LSocket, Transport, Protocol, Opts, MaxConns, ReqsSup).
  43. -spec limit_reqs(non_neg_integer(), pid()) -> ok.
  44. limit_reqs(MaxConns, ReqsSup) ->
  45. Counts = supervisor:count_children(ReqsSup),
  46. Active = lists:keyfind(active, 1, Counts),
  47. case Active < MaxConns of
  48. true -> ok;
  49. false -> timer:sleep(1)
  50. end.