]>
git.saurik.com Git - redis.git/blob - client-libraries/ruby/lib/server.rb
2 # This class represents a redis server instance.
7 # The amount of time to wait before attempting to re-establish a
8 # connection with a server that is marked dead.
13 # The host the redis server is running on.
18 # The port the redis server is listening on.
28 # The time of next retry if the connection is dead.
33 # A text status string describing the state of the server.
38 # Create a new Redis::Server object for the redis instance
39 # listening on the given host and port.
41 def initialize(host
, port
= DEFAULT_PORT
)
42 raise ArgumentError
, "No host specified" if host
.nil? or host
.empty
?
43 raise ArgumentError
, "No port specified" if port
.nil? or port
.to_i
.zero
?
50 @status = 'NOT CONNECTED'
55 # Return a string representation of the server object.
57 "<Redis::Server: %s:%d (%s)>" % [@host, @port, @status]
61 # Try to connect to the redis server targeted by this object.
62 # Returns the connected socket object on success or nil on failure.
65 return @sock if @sock and not @sock.closed
?
69 # If the host was dead, don't retry for a while.
70 return if @retry and @retry > Time
.now
72 # Attempt to connect if not already connected.
74 @sock = connect_to(@host, @port, @timeout)
75 @sock.setsockopt Socket
::IPPROTO_TCP, Socket
::TCP_NODELAY, 1
78 rescue Errno
::EPIPE, Errno
::ECONNREFUSED => e
79 puts
"Socket died... socket: #{@sock.inspect}\n" if $debug
82 rescue SocketError
, SystemCallError
, IOError
=> err
83 puts
"Unable to open socket: #{err.class.name}, #{err.message}" if $debug
90 def connect_to(host
, port
, timeout
=nil)
91 addrs
= Socket
.getaddrinfo('localhost', nil)
92 addr
= addrs
.detect
{ |ad
| ad
[0] == 'AF_INET' }
93 sock
= Socket
.new(Socket
::AF_INET, Socket
::SOCK_STREAM, 0)
94 #addr = Socket.getaddrinfo(host, nil)
95 #sock = Socket.new(Socket.const_get(addr[0][0]), Socket::SOCK_STREAM, 0)
98 secs
= Integer(timeout
)
99 usecs
= Integer((timeout
- secs
) * 1_000_000)
100 optval
= [secs
, usecs
].pack("l_2")
101 sock
.setsockopt Socket
::SOL_SOCKET, Socket
::SO_RCVTIMEO, optval
102 sock
.setsockopt Socket
::SOL_SOCKET, Socket
::SO_SNDTIMEO, optval
104 sock
.connect(Socket
.pack_sockaddr_in('6379', addr
[3]))
109 # Close the connection to the redis server targeted by this
110 # object. The server is not considered dead.
113 @sock.close
if @sock && !
@sock.closed
?
116 @status = "NOT CONNECTED"
120 # Mark the server as dead and close its socket.
122 @sock.close
if @sock && !
@sock.closed
?
124 @retry = Time
.now
#+ RETRY_DELAY
126 reason
= "#{error.class.name}: #{error.message}"
127 @status = sprintf
"%s:%s DEAD (%s), will retry at %s", @host, @port, reason
, @retry