-
Notifications
You must be signed in to change notification settings - Fork 1k
/
Copy pathruby.rb
427 lines (350 loc) · 11.9 KB
/
ruby.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
# frozen_string_literal: true
require_relative "registry"
require_relative "command_helper"
require_relative "../errors"
require "socket"
require "timeout"
begin
require "openssl"
rescue LoadError
# Not all systems have OpenSSL support
end
class Redis
module Connection
module SocketMixin
CRLF = "\r\n"
def initialize(*args)
super(*args)
@timeout = @write_timeout = nil
@buffer = "".dup
end
def timeout=(timeout)
@timeout = (timeout if timeout && timeout > 0)
end
def write_timeout=(timeout)
@write_timeout = (timeout if timeout && timeout > 0)
end
def read(nbytes)
result = @buffer.slice!(0, nbytes)
result << _read_from_socket(nbytes - result.bytesize) while result.bytesize < nbytes
result
end
def gets
while (crlf = @buffer.index(CRLF)).nil?
@buffer << _read_from_socket(16_384)
end
@buffer.slice!(0, crlf + CRLF.bytesize)
end
def _read_from_socket(nbytes)
loop do
case chunk = read_nonblock(nbytes, exception: false)
when :wait_readable
unless wait_readable(@timeout)
raise Redis::TimeoutError
end
when :wait_writable
unless wait_writable(@timeout)
raise Redis::TimeoutError
end
when nil
raise Errno::ECONNRESET
when String
return chunk
end
end
end
def write(buffer)
return super(buffer) unless @write_timeout
bytes_to_write = buffer.bytesize
total_bytes_written = 0
loop do
case bytes_written = write_nonblock(buffer, exception: false)
when :wait_readable
unless wait_readable(@write_timeout)
raise Redis::TimeoutError
end
when :wait_writable
unless wait_writable(@write_timeout)
raise Redis::TimeoutError
end
when nil
raise Errno::ECONNRESET
when Integer
total_bytes_written += bytes_written
if total_bytes_written >= bytes_to_write
return total_bytes_written
end
buffer = buffer.byteslice(bytes_written..-1)
end
end
end
end
if defined?(RUBY_ENGINE) && RUBY_ENGINE == "jruby"
require "timeout"
class TCPSocket < ::TCPSocket
include SocketMixin
def self.connect(host, port, timeout)
Timeout.timeout(timeout) do
sock = new(host, port)
sock
end
rescue Timeout::Error
raise TimeoutError
end
end
if defined?(::UNIXSocket)
class UNIXSocket < ::UNIXSocket
include SocketMixin
def self.connect(path, timeout)
Timeout.timeout(timeout) do
sock = new(path)
sock
end
rescue Timeout::Error
raise TimeoutError
end
# JRuby raises Errno::EAGAIN on #read_nonblock even when it
# says it is readable (1.6.6, in both 1.8 and 1.9 mode).
# Use the blocking #readpartial method instead.
def _read_from_socket(nbytes)
readpartial(nbytes)
rescue EOFError
raise Errno::ECONNRESET
end
end
end
else
class TCPSocket < ::Socket
include SocketMixin
def self.connect_addrinfo(addrinfo, port, timeout)
sock = new(::Socket.const_get(addrinfo[0]), Socket::SOCK_STREAM, 0)
sockaddr = ::Socket.pack_sockaddr_in(port, addrinfo[3])
begin
sock.connect_nonblock(sockaddr)
rescue Errno::EINPROGRESS
raise TimeoutError unless sock.wait_writable(timeout)
begin
sock.connect_nonblock(sockaddr)
rescue Errno::EISCONN
end
end
sock
end
def self.connect(host, port, timeout)
# Don't pass AI_ADDRCONFIG as flag to getaddrinfo(3)
#
# From the man page for getaddrinfo(3):
#
# If hints.ai_flags includes the AI_ADDRCONFIG flag, then IPv4
# addresses are returned in the list pointed to by res only if the
# local system has at least one IPv4 address configured, and IPv6
# addresses are returned only if the local system has at least one
# IPv6 address configured. The loopback address is not considered
# for this case as valid as a configured address.
#
# We do want the IPv6 loopback address to be returned if applicable,
# even if it is the only configured IPv6 address on the machine.
# Also see: https://github.com/redis/redis-rb/pull/394.
addrinfo = ::Socket.getaddrinfo(host, nil, Socket::AF_UNSPEC, Socket::SOCK_STREAM)
# From the man page for getaddrinfo(3):
#
# Normally, the application should try using the addresses in the
# order in which they are returned. The sorting function used
# within getaddrinfo() is defined in RFC 3484 [...].
#
addrinfo.each_with_index do |ai, i|
begin
return connect_addrinfo(ai, port, timeout)
rescue SystemCallError
# Raise if this was our last attempt.
raise if addrinfo.length == i + 1
end
end
end
end
class UNIXSocket < ::Socket
include SocketMixin
def self.connect(path, timeout)
sock = new(::Socket::AF_UNIX, Socket::SOCK_STREAM, 0)
sockaddr = ::Socket.pack_sockaddr_un(path)
begin
sock.connect_nonblock(sockaddr)
rescue Errno::EINPROGRESS
raise TimeoutError unless sock.wait_writable(timeout)
begin
sock.connect_nonblock(sockaddr)
rescue Errno::EISCONN
end
end
sock
end
end
end
if defined?(OpenSSL)
class SSLSocket < ::OpenSSL::SSL::SSLSocket
include SocketMixin
unless method_defined?(:wait_readable)
def wait_readable(timeout = nil)
to_io.wait_readable(timeout)
end
end
unless method_defined?(:wait_writable)
def wait_writable(timeout = nil)
to_io.wait_writable(timeout)
end
end
def self.connect(host, port, timeout, ssl_params)
# Note: this is using Redis::Connection::TCPSocket
tcp_sock = TCPSocket.connect(host, port, timeout)
ctx = OpenSSL::SSL::SSLContext.new
# The provided parameters are merged into OpenSSL::SSL::SSLContext::DEFAULT_PARAMS
ctx.set_params(ssl_params || {})
ssl_sock = new(tcp_sock, ctx)
ssl_sock.hostname = host
begin
# Initiate the socket connection in the background. If it doesn't fail
# immediately it will raise an IO::WaitWritable (Errno::EINPROGRESS)
# indicating the connection is in progress.
# Unlike waiting for a tcp socket to connect, you can't time out ssl socket
# connections during the connect phase properly, because IO.select only partially works.
# Instead, you have to retry.
ssl_sock.connect_nonblock
rescue Errno::EAGAIN, Errno::EWOULDBLOCK, IO::WaitReadable
if ssl_sock.wait_readable(timeout)
retry
else
raise TimeoutError
end
rescue IO::WaitWritable
if ssl_sock.wait_writable(timeout)
retry
else
raise TimeoutError
end
end
unless ctx.verify_mode == OpenSSL::SSL::VERIFY_NONE || (
ctx.respond_to?(:verify_hostname) &&
!ctx.verify_hostname
)
ssl_sock.post_connection_check(host)
end
ssl_sock
end
end
end
class Ruby
include Redis::Connection::CommandHelper
MINUS = "-"
PLUS = "+"
COLON = ":"
DOLLAR = "$"
ASTERISK = "*"
def self.connect(config)
if config[:scheme] == "unix"
raise ArgumentError, "SSL incompatible with unix sockets" if config[:ssl]
sock = UNIXSocket.connect(config[:path], config[:connect_timeout])
elsif config[:scheme] == "rediss" || config[:ssl]
sock = SSLSocket.connect(config[:host], config[:port], config[:connect_timeout], config[:ssl_params])
else
sock = TCPSocket.connect(config[:host], config[:port], config[:connect_timeout])
end
instance = new(sock)
instance.timeout = config[:read_timeout]
instance.write_timeout = config[:write_timeout]
instance.set_tcp_keepalive config[:tcp_keepalive]
instance.set_tcp_nodelay if sock.is_a? TCPSocket
instance
end
if %i[SOL_SOCKET SO_KEEPALIVE SOL_TCP TCP_KEEPIDLE TCP_KEEPINTVL TCP_KEEPCNT].all? { |c| Socket.const_defined? c }
def set_tcp_keepalive(keepalive)
return unless keepalive.is_a?(Hash)
@sock.setsockopt(Socket::SOL_SOCKET, Socket::SO_KEEPALIVE, true)
@sock.setsockopt(Socket::SOL_TCP, Socket::TCP_KEEPIDLE, keepalive[:time])
@sock.setsockopt(Socket::SOL_TCP, Socket::TCP_KEEPINTVL, keepalive[:intvl])
@sock.setsockopt(Socket::SOL_TCP, Socket::TCP_KEEPCNT, keepalive[:probes])
end
def get_tcp_keepalive
{
time: @sock.getsockopt(Socket::SOL_TCP, Socket::TCP_KEEPIDLE).int,
intvl: @sock.getsockopt(Socket::SOL_TCP, Socket::TCP_KEEPINTVL).int,
probes: @sock.getsockopt(Socket::SOL_TCP, Socket::TCP_KEEPCNT).int
}
end
else
def set_tcp_keepalive(keepalive); end
def get_tcp_keepalive
{
}
end
end
# disables Nagle's Algorithm, prevents multiple round trips with MULTI
if %i[IPPROTO_TCP TCP_NODELAY].all? { |c| Socket.const_defined? c }
def set_tcp_nodelay
@sock.setsockopt(Socket::IPPROTO_TCP, Socket::TCP_NODELAY, 1)
end
else
def set_tcp_nodelay; end
end
def initialize(sock)
@sock = sock
end
def connected?
!!@sock
end
def disconnect
@sock.close
rescue
ensure
@sock = nil
end
def timeout=(timeout)
@sock.timeout = timeout if @sock.respond_to?(:timeout=)
end
def write_timeout=(timeout)
@sock.write_timeout = timeout
end
def write(command)
@sock.write(build_command(command))
end
def read
line = @sock.gets
reply_type = line.slice!(0, 1)
format_reply(reply_type, line)
rescue Errno::EAGAIN
raise TimeoutError
end
def format_reply(reply_type, line)
case reply_type
when MINUS then format_error_reply(line)
when PLUS then format_status_reply(line)
when COLON then format_integer_reply(line)
when DOLLAR then format_bulk_reply(line)
when ASTERISK then format_multi_bulk_reply(line)
else raise ProtocolError, reply_type
end
end
def format_error_reply(line)
CommandError.new(line.strip)
end
def format_status_reply(line)
line.strip
end
def format_integer_reply(line)
line.to_i
end
def format_bulk_reply(line)
bulklen = line.to_i
return if bulklen == -1
reply = encode(@sock.read(bulklen))
@sock.read(2) # Discard CRLF.
reply
end
def format_multi_bulk_reply(line)
n = line.to_i
return if n == -1
Array.new(n) { read }
end
end
end
end
Redis::Connection.drivers << Redis::Connection::Ruby