socket_helper: add hint for FreeBSD users for accf_http(9)
[unicorn.git] / lib / unicorn / socket_helper.rb
blob8a6f6ee3440cfd220418ca5e2eedbac20e1fc8ef
1 # -*- encoding: binary -*-
2 # :enddoc:
3 require 'socket'
5 module Unicorn
7   # Instead of using a generic Kgio::Socket for everything,
8   # tag TCP sockets so we can use TCP_INFO under Linux without
9   # incurring extra syscalls for Unix domain sockets.
10   # TODO: remove these when we remove kgio
11   TCPClient = Class.new(Kgio::Socket) # :nodoc:
12   class TCPSrv < Kgio::TCPServer # :nodoc:
13     def kgio_tryaccept # :nodoc:
14       super(TCPClient)
15     end
16   end
18   module SocketHelper
20     # internal interface
21     DEFAULTS = {
22       # The semantics for TCP_DEFER_ACCEPT changed in Linux 2.6.32+
23       # with commit d1b99ba41d6c5aa1ed2fc634323449dd656899e9
24       # This change shouldn't affect unicorn users behind nginx (a
25       # value of 1 remains an optimization).
26       :tcp_defer_accept => 1,
28       # FreeBSD, we need to override this to 'dataready' if we
29       # eventually support non-HTTP/1.x
30       :accept_filter => 'httpready',
32       # same default value as Mongrel
33       :backlog => 1024,
35       # favor latency over bandwidth savings
36       :tcp_nopush => nil,
37       :tcp_nodelay => true,
38     }
40     # configure platform-specific options (only tested on Linux 2.6 so far)
41     def accf_arg(af_name)
42       [ af_name, nil ].pack('a16a240')
43     end if RUBY_PLATFORM =~ /freebsd/ && Socket.const_defined?(:SO_ACCEPTFILTER)
45     def set_tcp_sockopt(sock, opt)
46       # just in case, even LANs can break sometimes.  Linux sysadmins
47       # can lower net.ipv4.tcp_keepalive_* sysctl knobs to very low values.
48       Socket.const_defined?(:SO_KEEPALIVE) and
49         sock.setsockopt(:SOL_SOCKET, :SO_KEEPALIVE, 1)
51       if Socket.const_defined?(:TCP_NODELAY)
52         val = opt[:tcp_nodelay]
53         val = DEFAULTS[:tcp_nodelay] if val.nil?
54         sock.setsockopt(:IPPROTO_TCP, :TCP_NODELAY, val ? 1 : 0)
55       end
57       val = opt[:tcp_nopush]
58       unless val.nil?
59         if Socket.const_defined?(:TCP_CORK) # Linux
60           sock.setsockopt(:IPPROTO_TCP, :TCP_CORK, val)
61         elsif Socket.const_defined?(:TCP_NOPUSH) # FreeBSD
62           sock.setsockopt(:IPPROTO_TCP, :TCP_NOPUSH, val)
63         end
64       end
66       # No good reason to ever have deferred accepts off in single-threaded
67       # servers (except maybe benchmarking)
68       if Socket.const_defined?(:TCP_DEFER_ACCEPT)
69         # this differs from nginx, since nginx doesn't allow us to
70         # configure the the timeout...
71         seconds = opt[:tcp_defer_accept]
72         seconds = DEFAULTS[:tcp_defer_accept] if [true,nil].include?(seconds)
73         seconds = 0 unless seconds # nil/false means disable this
74         sock.setsockopt(:IPPROTO_TCP, :TCP_DEFER_ACCEPT, seconds)
75       elsif respond_to?(:accf_arg)
76         name = opt[:accept_filter]
77         name = DEFAULTS[:accept_filter] if name.nil?
78         sock.listen(opt[:backlog])
79         got = (sock.getsockopt(:SOL_SOCKET, :SO_ACCEPTFILTER) rescue nil).to_s
80         arg = accf_arg(name)
81         begin
82           sock.setsockopt(:SOL_SOCKET, :SO_ACCEPTFILTER, arg)
83         rescue => e
84           logger.error("#{sock_name(sock)} " \
85                        "failed to set accept_filter=#{name} (#{e.inspect})")
86           logger.error("perhaps accf_http(9) needs to be loaded".freeze)
87         end if arg != got
88       end
89     end
91     def set_server_sockopt(sock, opt)
92       opt = DEFAULTS.merge(opt || {})
94       TCPSocket === sock and set_tcp_sockopt(sock, opt)
96       rcvbuf, sndbuf = opt.values_at(:rcvbuf, :sndbuf)
97       if rcvbuf || sndbuf
98         log_buffer_sizes(sock, "before: ")
99         sock.setsockopt(:SOL_SOCKET, :SO_RCVBUF, rcvbuf) if rcvbuf
100         sock.setsockopt(:SOL_SOCKET, :SO_SNDBUF, sndbuf) if sndbuf
101         log_buffer_sizes(sock, " after: ")
102       end
103       sock.listen(opt[:backlog])
104     rescue => e
105       Unicorn.log_error(logger, "#{sock_name(sock)} #{opt.inspect}", e)
106     end
108     def log_buffer_sizes(sock, pfx = '')
109       rcvbuf = sock.getsockopt(:SOL_SOCKET, :SO_RCVBUF).int
110       sndbuf = sock.getsockopt(:SOL_SOCKET, :SO_SNDBUF).int
111       logger.info "#{pfx}#{sock_name(sock)} rcvbuf=#{rcvbuf} sndbuf=#{sndbuf}"
112     end
114     # creates a new server, socket. address may be a HOST:PORT or
115     # an absolute path to a UNIX socket.  address can even be a Socket
116     # object in which case it is immediately returned
117     def bind_listen(address = '0.0.0.0:8080', opt = {})
118       return address unless String === address
120       sock = if address.start_with?('/')
121         if File.exist?(address)
122           if File.socket?(address)
123             begin
124               UNIXSocket.new(address).close
125               # fall through, try to bind(2) and fail with EADDRINUSE
126               # (or succeed from a small race condition we can't sanely avoid).
127             rescue Errno::ECONNREFUSED
128               logger.info "unlinking existing socket=#{address}"
129               File.unlink(address)
130             end
131           else
132             raise ArgumentError,
133                   "socket=#{address} specified but it is not a socket!"
134           end
135         end
136         old_umask = File.umask(opt[:umask] || 0)
137         begin
138           Kgio::UNIXServer.new(address)
139         ensure
140           File.umask(old_umask)
141         end
142       elsif /\A\[([a-fA-F0-9:]+)\]:(\d+)\z/ =~ address
143         new_tcp_server($1, $2.to_i, opt.merge(:ipv6=>true))
144       elsif /\A(\d+\.\d+\.\d+\.\d+):(\d+)\z/ =~ address
145         new_tcp_server($1, $2.to_i, opt)
146       else
147         raise ArgumentError, "Don't know how to bind: #{address}"
148       end
149       set_server_sockopt(sock, opt)
150       sock
151     end
153     def new_tcp_server(addr, port, opt)
154       # n.b. we set FD_CLOEXEC in the workers
155       sock = Socket.new(opt[:ipv6] ? :AF_INET6 : :AF_INET, :SOCK_STREAM)
156       if opt.key?(:ipv6only)
157         Socket.const_defined?(:IPV6_V6ONLY) or
158           abort "Socket::IPV6_V6ONLY not defined, upgrade Ruby and/or your OS"
159         sock.setsockopt(:IPPROTO_IPV6, :IPV6_V6ONLY, opt[:ipv6only] ? 1 : 0)
160       end
161       sock.setsockopt(:SOL_SOCKET, :SO_REUSEADDR, 1)
162       if Socket.const_defined?(:SO_REUSEPORT) && opt[:reuseport]
163         sock.setsockopt(:SOL_SOCKET, :SO_REUSEPORT, 1)
164       end
165       sock.bind(Socket.pack_sockaddr_in(port, addr))
166       sock.autoclose = false
167       TCPSrv.for_fd(sock.fileno)
168     end
170     # returns rfc2732-style (e.g. "[::1]:666") addresses for IPv6
171     def tcp_name(sock)
172       port, addr = Socket.unpack_sockaddr_in(sock.getsockname)
173       addr.include?(':') ? "[#{addr}]:#{port}" : "#{addr}:#{port}"
174     end
175     module_function :tcp_name
177     # Returns the configuration name of a socket as a string.  sock may
178     # be a string value, in which case it is returned as-is
179     # Warning: TCP sockets may not always return the name given to it.
180     def sock_name(sock)
181       case sock
182       when String then sock
183       when UNIXServer
184         Socket.unpack_sockaddr_un(sock.getsockname)
185       when TCPServer
186         tcp_name(sock)
187       when Socket
188         begin
189           tcp_name(sock)
190         rescue ArgumentError
191           Socket.unpack_sockaddr_un(sock.getsockname)
192         end
193       else
194         raise ArgumentError, "Unhandled class #{sock.class}: #{sock.inspect}"
195       end
196     end
198     module_function :sock_name
200     # casts a given Socket to be a TCPServer or UNIXServer
201     def server_cast(sock)
202       begin
203         Socket.unpack_sockaddr_in(sock.getsockname)
204         TCPSrv.for_fd(sock.fileno)
205       rescue ArgumentError
206         Kgio::UNIXServer.for_fd(sock.fileno)
207       end
208     end
210   end # module SocketHelper
211 end # module Unicorn