cowboy_acceptor.erl 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  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/7]). %% API.
  17. -export([acceptor/7]). %% Internal.
  18. %% API.
  19. -spec start_link(inet:socket(), module(), module(), any(),
  20. non_neg_integer(), pid(), pid()) -> {ok, pid()}.
  21. start_link(LSocket, Transport, Protocol, Opts,
  22. MaxConns, ListenerPid, ReqsSup) ->
  23. Pid = spawn_link(?MODULE, acceptor,
  24. [LSocket, Transport, Protocol, Opts, MaxConns, ListenerPid, ReqsSup]),
  25. {ok, Pid}.
  26. %% Internal.
  27. -spec acceptor(inet:socket(), module(), module(), any(),
  28. non_neg_integer(), pid(), pid()) -> no_return().
  29. acceptor(LSocket, Transport, Protocol, Opts, MaxConns, ListenerPid, ReqsSup) ->
  30. case Transport:accept(LSocket, 2000) of
  31. {ok, CSocket} ->
  32. {ok, Pid} = supervisor:start_child(ReqsSup,
  33. [ListenerPid, CSocket, Transport, Protocol, Opts]),
  34. Transport:controlling_process(CSocket, Pid),
  35. {ok, NbConns} = cowboy_listener:add_connection(ListenerPid,
  36. default, Pid),
  37. Pid ! {shoot, ListenerPid},
  38. limit_reqs(ListenerPid, NbConns, MaxConns);
  39. {error, timeout} ->
  40. ignore;
  41. {error, _Reason} ->
  42. %% @todo Probably do something here. If the socket was closed,
  43. %% we may want to try and listen again on the port?
  44. ignore
  45. end,
  46. ?MODULE:acceptor(LSocket, Transport, Protocol, Opts,
  47. MaxConns, ListenerPid, ReqsSup).
  48. -spec limit_reqs(pid(), non_neg_integer(), non_neg_integer()) -> ok.
  49. limit_reqs(_ListenerPid, NbConns, MaxConns) when NbConns =< MaxConns ->
  50. ok;
  51. limit_reqs(ListenerPid, _NbConns, MaxConns) ->
  52. cowboy_listener:wait(ListenerPid, default, MaxConns).