diff options
author | Eric Wong <e@80x24.org> | 2013-10-26 10:15:04 +0000 |
---|---|---|
committer | Eric Wong <e@80x24.org> | 2013-10-26 10:15:04 +0000 |
commit | 5f67786b426c9c16408b5f7ce3209cd1710fc75c (patch) | |
tree | 86b312293dc6728e53b53fabbb58a7708e97034e /lib/yahns/socket_helper.rb | |
parent | 1506dcd4741d64538bf6d822413219ddb1ec11c2 (diff) | |
download | yahns-5f67786b426c9c16408b5f7ce3209cd1710fc75c.tar.gz |
This allows users to start an independent instance of unicorn on a the same port as a running unicorn (as long as both instances use :reuseport). ref: https://lwn.net/Articles/542629/
Diffstat (limited to 'lib/yahns/socket_helper.rb')
-rw-r--r-- | lib/yahns/socket_helper.rb | 37 |
1 files changed, 31 insertions, 6 deletions
diff --git a/lib/yahns/socket_helper.rb b/lib/yahns/socket_helper.rb index 691408f..02cacee 100644 --- a/lib/yahns/socket_helper.rb +++ b/lib/yahns/socket_helper.rb @@ -3,6 +3,22 @@ # License: GPLv3 or later (https://www.gnu.org/licenses/gpl-3.0.txt) # this is only meant for Yahns::Server module Yahns::SocketHelper # :nodoc: + + # Linux got SO_REUSEPORT in 3.9, BSDs have had it for ages + def so_reuseport + if defined?(Socket::SO_REUSEPORT) + Socket::SO_REUSEPORT + elsif RUBY_PLATFORM =~ /linux/ + if RUBY_PLATFORM =~ /(?:alpha|mips|parisc|sparc)/ + 0x0200 # untested + else + 15 # only tested on x86_64 and i686 + end + else + nil + end + end + def set_server_sockopt(sock, opt) opt = {backlog: 1024}.merge!(opt) if opt sock.close_on_exec = true @@ -59,9 +75,9 @@ module Yahns::SocketHelper # :nodoc: File.umask(old_umask) end elsif /\A\[([a-fA-F0-9:]+)\]:(\d+)\z/ =~ address - new_ipv6_server($1, $2.to_i, opt) + new_tcp_server($1, $2.to_i, opt.merge(ipv6: true)) elsif /\A(\d+\.\d+\.\d+\.\d+):(\d+)\z/ =~ address - Yahns::TCPServer.new($1, $2.to_i) + new_tcp_server($1, $2.to_i, opt) else raise ArgumentError, "Don't know how to bind: #{address}" end @@ -69,11 +85,20 @@ module Yahns::SocketHelper # :nodoc: sock end - def new_ipv6_server(addr, port, opt) - opt.key?(:ipv6only) or return Yahns::TCPServer.new(addr, port) - sock = Socket.new(:AF_INET6, :SOCK_STREAM, 0) - sock.setsockopt(:IPPROTO_IPV6, :IPV6_V6ONLY, opt[:ipv6only] ? 1 : 0) + def new_tcp_server(addr, port, opt) + sock = Socket.new(opt[:ipv6] ? :INET6 : :INET, :STREAM, 0) + if opt.key?(:ipv6only) + sock.setsockopt(:IPPROTO_IPV6, :IPV6_V6ONLY, opt[:ipv6only] ? 1 : 0) + end sock.setsockopt(:SOL_SOCKET, :SO_REUSEADDR, 1) + + begin + sock.setsockopt(:SOL_SOCKET, so_reuseport, 1) + rescue => e + name = sock_name(sock) + @logger.warn("failed to set SO_REUSEPORT on #{name}: #{e.message}") + end if opt[:reuseport] + sock.bind(Socket.pack_sockaddr_in(port, addr)) sock.autoclose = false Yahns::TCPServer.for_fd(sock.fileno) |