Class: Varnish::SocketFactory

Inherits:
Object
  • Object
show all
Defined in:
lib/varnish/socket_factory.rb

Overview

Wrapper around Ruby’s Socket.

Uses Mike Perhams superior (in both reliability and performance) connection technique with proper timeouts: See: github.com/mperham/memcache-client

Class Method Summary collapse

Class Method Details

.tcp_socket(host, port, timeout = nil) ⇒ Object



28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
# File 'lib/varnish/socket_factory.rb', line 28

def self.tcp_socket(host, port, timeout = nil)
  addr = Socket.getaddrinfo(host, nil)
  sock = Socket.new(Socket.const_get(addr[0][0]), Socket::SOCK_STREAM, 0)

  if timeout
    secs = Integer(timeout)
    usecs = Integer((timeout - secs) * 1_000_000)
    optval = [secs, usecs].pack("l_2")
    sock.setsockopt Socket::SOL_SOCKET, Socket::SO_RCVTIMEO, optval
    sock.setsockopt Socket::SOL_SOCKET, Socket::SO_SNDTIMEO, optval

    # Socket timeouts don't work for more complex IO operations
    # like gets which lay on top of read. We need to fall back to
    # the standard Timeout mechanism.
    sock.instance_eval "      alias :blocking_gets :gets\n      def gets\n        Timer.timeout(\#{timeout}) do\n          self.blocking_gets\n        end\n      end\n    EOR\n  end\n  sock.connect(Socket.pack_sockaddr_in(port, addr[0][3]))\n  sock.setsockopt(Socket::IPPROTO_TCP, Socket::TCP_NODELAY, 1)\n  sock\nend\n"