Debian Codegraph @

doc/src/guide/listeners.asciidoc

raw
1 == Listeners
2
3 A listener is a set of processes whose role is to listen on a port
4 for new connections. It manages a pool of acceptor processes, each
5 of them indefinitely accepting connections. When it does, it starts
6 a new process executing the protocol handler code. All the socket
7 programming is abstracted through the use of transport handlers.
8
9 The listener takes care of supervising all the acceptor and connection
10 processes, allowing developers to focus on building their application.
11
12 === Starting a listener
13
14 Ranch does nothing by default. It is up to the application developer
15 to request that Ranch listens for connections.
16
17 A listener can be started and stopped at will.
18
19 When starting a listener, a number of different settings are required:
20
21 * A name to identify it locally and be able to interact with it.
22 * A transport handler and its associated options.
23 * A protocol handler and its associated options.
24
25 Ranch includes both TCP and SSL transport handlers, respectively
26 `ranch_tcp` and `ranch_ssl`.
27
28 A listener can be started by calling the `ranch:start_listener/5`
29 function. Before doing so however, you must ensure that the `ranch`
30 application is started.
31
32 .Starting the Ranch application
33
34 [source,erlang]
35 ok = application:start(ranch).
36
37 You are then ready to start a listener. Let's call it `tcp_echo`. It will
38 have a pool of 100 acceptors, use a TCP transport and forward connections
39 to the `echo_protocol` handler.
40
41 .Starting a listener for TCP connections on port 5555
42
43 [source,erlang]
44 {ok, _} = ranch:start_listener(tcp_echo,
45 ranch_tcp, #{socket_opts => [{port, 5555}]},
46 echo_protocol, []
47 ).
48
49 You can try this out by compiling and running the `tcp_echo` example in the
50 examples directory. To do so, open a shell in the 'examples/tcp_echo/'
51 directory and run the following command:
52
53 .Building and starting a Ranch example
54
55 [source,bash]
56 $ make run
57
58 You can then connect to it using telnet and see the echo server reply
59 everything you send to it. Then when you're done testing, you can use
60 the `Ctrl+]` key to escape to the telnet command line and type
61 `quit` to exit.
62
63 .Connecting to the example listener with telnet
64
65 [source,bash]
66 ----
67 $ telnet localhost 5555
68 Trying 127.0.0.1...
69 Connected to localhost.
70 Escape character is '^]'.
71 Hello!
72 Hello!
73 It works!
74 It works!
75 ^]
76
77 telnet> quit
78 Connection closed.
79 ----
80
81 === Stopping a listener
82
83 All you need to stop a Ranch listener is to call the
84 `ranch:stop_listener/1` function with the listener's name
85 as argument. In the previous section we started the listener
86 named `tcp_echo`. We can now stop it.
87
88 .Stopping a listener
89
90 [source,erlang]
91 ranch:stop_listener(tcp_echo).
92
93 === Suspending and resuming a listener
94
95 Listeners can be suspended and resumed by calling
96 `ranch:suspend_listener/1` and `ranch:resume_listener/1`,
97 respectively, with the name of the listener as argument.
98
99 Suspending a listener will cause it to stop listening and not accept
100 new connections, but existing connection processes will not be stopped.
101
102 .Suspending a listener
103
104 [source,erlang]
105 ranch:suspend_listener(tcp_echo).
106
107 Resuming a listener will cause it to start listening and accept new
108 connections again.
109 It is worth mentioning, however, that if the listener is configured
110 to listen on a random port, it will listen on a different port than
111 before it was suspended.
112
113 .Resuming a listener
114
115 [source,erlang]
116 ranch:resume_listener(tcp_echo).
117
118 Whether a listener is currently running or suspended can be queried
119 by calling `ranch:get_status/1` with the listener name as argument.
120
121 === Default transport options
122
123 By default the socket will be set to return `binary` data, with the
124 options `{active, false}`, `{packet, raw}`, `{reuseaddr, true}` set.
125 These values can't be overridden when starting the listener, but
126 they can be overridden using `Transport:setopts/2` in the protocol.
127
128 It will also set `{backlog, 1024}` and `{nodelay, true}`, which
129 can be overridden at listener startup.
130
131 === Listening on a random port
132
133 You do not have to specify a specific port to listen on. If you give
134 the port number 0, or if you omit the port number entirely, Ranch will
135 start listening on a random port.
136
137 You can retrieve this port number by calling `ranch:get_port/1`. The
138 argument is the name of the listener you gave in `ranch:start_listener/5`.
139
140 .Starting a listener for TCP connections on a random port
141
142 [source,erlang]
143 {ok, _} = ranch:start_listener(tcp_echo,
144 ranch_tcp, #{socket_opts => [{port, 0}]},
145 echo_protocol, []
146 ).
147 Port = ranch:get_port(tcp_echo).
148
149 === Listening on privileged ports
150
151 Some systems limit access to ports below 1024 for security reasons.
152 This can easily be identified by an `{error, eacces}` error when trying
153 to open a listening socket on such a port.
154
155 The methods for listening on privileged ports vary between systems,
156 please refer to your system's documentation for more information.
157
158 We recommend the use of port rewriting for systems with a single server,
159 and load balancing for systems with multiple servers. Documenting these
160 solutions is however out of the scope of this guide.
161
162 === Listening on a UNIX Domain socket
163
164 On UNIX systems, it is also possible to use Ranch to listen on a UNIX
165 domain socket by specifying `{local, SocketFile}` for the `ip` socket
166 option. In this case, the port must be set to 0 or omitted. The given
167 file must not exist: Ranch must be able to create it.
168
169 .Starting a listener for TCP connections on a UNIX Domain socket
170
171 [source,erlang]
172 {ok, _} = ranch:start_listener(tcp_echo,
173 ranch_tcp, #{socket_opts => [
174 {ip, {local, "/tmp/ranch_echo.sock"}},
175 {port, 0}
176 ]}, echo_protocol, []
177 ).
178
179 === Performing additional setup steps on a listening socket
180
181 If it is necessary to perform additional setup steps on the listening
182 socket, it is possible to specify a function with the transport option
183 `post_listen_callback`. This function will be called after the listening
184 socket has been created but before accepting connections on it,
185 with the socket as the single argument.
186
187 The function must return either the atom `ok`, after which the listener
188 will start accepting connections on the socket, or a tuple
189 `{error, Reason}` which will cause the listener to fail starting with
190 `Reason`.
191
192 .Setting permissions on a UNIX Domain socket file
193
194 [source,erlang]
195 ----
196 PostListenCb = fun (Sock) ->
197 case ranch_tcp:sockname(Sock) of
198 {ok, {local, SockFile}} ->
199 file:change_mode(SockFile, 8#777);
200 {ok, _} ->
201 ok;
202 Error = {error, _} ->
203 Error
204 end
205 end,
206
207 {ok, _} = ranch:start_listener(tcp_echo,
208 ranch_tcp, #{
209 socket_opts => [
210 {ip, {local, "/tmp/ranch_echo.sock"}},
211 {port, 0}],
212 post_listen_callback => PostListenCb},
213 echo_protocol, []
214 ).
215 ----
216
217 === Accepting connections on an existing socket
218
219 If you want to accept connections on an existing socket, you can write
220 a custom `ranch_transport` implementation that fetches or otherwise
221 acquires a listening socket in the `listen/1` callback and returns it
222 in the form of `{ok, ListenSocket}`.
223
224 The custom `listen/1` function must ensure that the listener process
225 (usually the process calling it) is also made the controlling process
226 of the socket it returns. Failing to do so will result in stop/start
227 and suspend/resume not working properly for that listener.
228
229 === Limiting the number of concurrent connections
230
231 The `max_connections` transport option allows you to limit the number
232 of concurrent connections per connection supervisor (see below).
233 It defaults to 1024. Its purpose is to prevent your system from being
234 overloaded and ensuring all the connections are handled optimally.
235
236 .Customizing the maximum number of concurrent connections
237
238 [source,erlang]
239 {ok, _} = ranch:start_listener(tcp_echo,
240 ranch_tcp, #{socket_opts => [{port, 5555}], max_connections => 100},
241 echo_protocol, []
242 ).
243
244 You can disable this limit by setting its value to the atom `infinity`.
245
246 .Disabling the limit for the number of connections
247
248 [source,erlang]
249 {ok, _} = ranch:start_listener(tcp_echo,
250 ranch_tcp, #{socket_opts => [{port, 5555}], max_connections => infinity},
251 echo_protocol, []
252 ).
253
254 The maximum number of connections is a soft limit. In practice, it
255 can reach `max_connections` + the number of acceptors.
256
257 When the maximum number of connections is reached, Ranch will stop
258 accepting connections. This will not result in further connections
259 being rejected, as the kernel option allows queueing incoming
260 connections. The size of this queue is determined by the `backlog`
261 option and defaults to 1024. Ranch does not know about the number
262 of connections that are in the backlog.
263
264 You may not always want connections to be counted when checking for
265 `max_connections`. For example you might have a protocol where both
266 short-lived and long-lived connections are possible. If the long-lived
267 connections are mostly waiting for messages, then they don't consume
268 much resources and can safely be removed from the count.
269
270 To remove the connection from the count, you must call the
271 `ranch:remove_connection/1` from within the connection process,
272 with the name of the listener as the only argument.
273
274 .Removing a connection from the count of connections
275
276 [source,erlang]
277 ranch:remove_connection(Ref).
278
279 As seen in the chapter covering protocols, this reference is received
280 as the first argument of the protocol's `start_link/3` callback.
281
282 You can modify the `max_connections` value on a running listener by
283 using the `ranch:set_max_connections/2` function, with the name of the
284 listener as first argument and the new value as the second.
285
286 .Upgrading the maximum number of connections
287
288 [source,erlang]
289 ranch:set_max_connections(tcp_echo, MaxConns).
290
291 The change will occur immediately.
292
293 === Customizing the number of acceptor processes
294
295 By default Ranch will use 10 acceptor processes. Their role is
296 to accept connections and spawn a connection process for every
297 new connection.
298
299 This number can be tweaked to improve performance. A good
300 number is typically between 10 or 100 acceptors. You must
301 measure to find the best value for your application.
302
303 .Specifying a custom number of acceptor processes
304
305 [source,erlang]
306 {ok, _} = ranch:start_listener(tcp_echo,
307 ranch_tcp, #{socket_opts => [{port, 5555}], num_acceptors => 42},
308 echo_protocol, []
309 ).
310
311 === Customizing the number of connection supervisors
312
313 By default Ranch will use one connection supervisor for each
314 acceptor process (but not vice versa). Their task is to
315 supervise the connection processes started by an acceptor.
316 The number of connection supervisors can be tweaked.
317
318 Note that the association between the individual acceptors and
319 connection supervisors is fixed, meaning that acceptors will
320 always use the same connection supervisor to start connection
321 processes.
322
323 .Specifying a custom number of connection supervisors
324
325 [source,erlang]
326 {ok, _} = ranch:start_listener(tcp_echo,
327 ranch_tcp, #{socket_opts => [{port, 5555}], num_conns_sups => 42},
328 echo_protocol, []
329 ).
330
331 === Setting connection count alarms
332
333 The `alarms` transport option allows you to configure alarms
334 which will be triggered when the number of connections tracked
335 by one connection supervisor reaches or exceeds the defined threshold.
336
337 The `alarms` transport option takes a map with alarm names as keys and alarm
338 options as values.
339
340 Any term is allowed as an alarm name.
341
342 Alarm options include the alarm type and a threshold that, when reached,
343 triggers the given callback. A cooldown prevents the alarm from being
344 triggered too often.
345
346 .Log warnings when the number of connections exceeds 100
347
348 [source,erlang]
349 ----
350 Alarms = #{
351 my_alarm => #{
352 type => num_connections,
353 threshold => 100,
354 callback => fun(Ref, Name, ConnSup, ConnPids]) ->
355 logger:warning("Warning (~s): "
356 "Supervisor ~s of listener ~s "
357 "has ~b connections",
358 [Name, Ref, ConnSup, length(ConnPids)])
359 end
360 }
361 },
362 {ok, _} = ranch:start_listener(tcp_echo,
363 ranch_tcp, #{alarms => Alarms, socket_opts => [{port, 5555}]},
364 echo_protocol, []
365 ).
366 ----
367
368 In the example code, an alarm named `my_alarm` is defined, which will
369 call the given function when the number of connections tracked
370 by the connection supervisor reaches or exceeds 100. When the number of
371 connections is still (or again) above 100 after the default cooldown
372 period of 5 seconds, the alarm will trigger again.
373
374 === When running out of file descriptors
375
376 Operating systems have limits on the number of sockets
377 which can be opened by applications. When this maximum is
378 reached the listener can no longer accept new connections. The
379 accept rate of the listener will be automatically reduced, and a
380 warning message will be logged.
381
382 ----
383 =ERROR REPORT==== 13-Jan-2016::12:24:38 ===
384 Ranch acceptor reducing accept rate: out of file descriptors
385 ----
386
387 If you notice messages like this you should increase the number
388 of file-descriptors which can be opened by your application. How
389 this should be done is operating-system dependent. Please consult
390 the documentation of your operating system.
391
392 === Using a supervisor for connection processes
393
394 Ranch allows you to define the type of process that will be used
395 for the connection processes. By default it expects a `worker`.
396 When the `connection_type` configuration value is set to `supervisor`,
397 Ranch will consider that the connection process it manages is a
398 supervisor and will reflect that in its supervision tree.
399
400 Connection processes of type `supervisor` can either handle the
401 socket directly or through one of their children. In the latter
402 case the start function for the connection process must return
403 two pids: the pid of the supervisor you created (that will be
404 supervised) and the pid of the protocol handling process (that
405 will receive the socket).
406
407 Instead of returning `{ok, ConnPid}`, simply return
408 `{ok, SupPid, ConnPid}`.
409
410 It is very important that the connection process be created
411 under the supervisor process so that everything works as intended.
412 If not, you will most likely experience issues when the supervised
413 process is stopped.
414
415 === Upgrading
416
417 Ranch allows you to upgrade the protocol options. This takes effect
418 immediately and for all subsequent connections.
419
420 To upgrade the protocol options, call `ranch:set_protocol_options/2`
421 with the name of the listener as first argument and the new options
422 as the second.
423
424 .Upgrading the protocol options
425
426 [source,erlang]
427 ranch:set_protocol_options(tcp_echo, NewOpts).
428
429 All future connections will use the new options.
430
431 You can also retrieve the current options similarly by
432 calling `ranch:get_protocol_options/1`.
433
434 .Retrieving the current protocol options
435
436 [source,erlang]
437 Opts = ranch:get_protocol_options(tcp_echo).
438
439 === Changing transport options
440
441 Ranch allows you to change the transport options of a listener with
442 the `ranch:set_transport_options/2` function, for example to change the
443 number of acceptors or to make it listen on a different port.
444
445 .Changing the transport options
446
447 [source,erlang]
448 ranch:set_transport_options(tcp_echo, NewOpts).
449
450 You can retrieve the current transport options by calling
451 `ranch:get_transport_options/1`.
452
453 .Retrieving the current transport options
454
455 [source,erlang]
456 Opts = ranch:get_transport_options(tcp_echo).
457
458 === Obtaining information about listeners
459
460 Ranch provides two functions for retrieving information about the
461 listeners, for reporting and diagnostic purposes.
462
463 The `ranch:info/0` function will return detailed information
464 about all listeners.
465
466 .Retrieving detailed information
467 [source,erlang]
468 ranch:info().
469
470 The `ranch:procs/2` function will return all acceptor or listener
471 processes for a given listener.
472
473 .Get all acceptor processes
474 [source,erlang]
475 ranch:procs(tcp_echo, acceptors).
476
477 .Get all connection processes
478 [source,erlang]
479 ranch:procs(tcp_echo, connections).