ranch_acceptor.erl 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. %% Copyright (c) 2011-2017, Loïc Hoguin <essen@ninenines.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. -module(ranch_acceptor).
  15. -export([start_link/3]).
  16. -export([loop/3]).
  17. -spec start_link(inet:socket(), module(), pid())
  18. -> {ok, pid()}.
  19. start_link(LSocket, Transport, ConnsSup) ->
  20. Pid = spawn_link(?MODULE, loop, [LSocket, Transport, ConnsSup]),
  21. {ok, Pid}.
  22. -spec loop(inet:socket(), module(), pid()) -> no_return().
  23. loop(LSocket, Transport, ConnsSup) ->
  24. _ = case Transport:accept(LSocket, infinity) of
  25. {ok, CSocket} ->
  26. case Transport:controlling_process(CSocket, ConnsSup) of
  27. ok ->
  28. %% This call will not return until process has been started
  29. %% AND we are below the maximum number of connections.
  30. ranch_conns_sup:start_protocol(ConnsSup, CSocket);
  31. {error, _} ->
  32. Transport:close(CSocket)
  33. end;
  34. %% Reduce the accept rate if we run out of file descriptors.
  35. %% We can't accept anymore anyway, so we might as well wait
  36. %% a little for the situation to resolve itself.
  37. {error, emfile} ->
  38. error_logger:warning_msg("Ranch acceptor reducing accept rate: out of file descriptors~n"),
  39. receive after 100 -> ok end;
  40. %% We want to crash if the listening socket got closed.
  41. {error, Reason} when Reason =/= closed ->
  42. ok
  43. end,
  44. flush(),
  45. ?MODULE:loop(LSocket, Transport, ConnsSup).
  46. flush() ->
  47. receive Msg ->
  48. error_logger:error_msg(
  49. "Ranch acceptor received unexpected message: ~p~n",
  50. [Msg]),
  51. flush()
  52. after 0 ->
  53. ok
  54. end.