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
|
class LeapTest
#
# tcp connection helper with timeout
#
def try_tcp_connect(host, port, timeout = 5)
addr = Socket.getaddrinfo(host, nil)
sockaddr = Socket.pack_sockaddr_in(port, addr[0][3])
Socket.new(Socket.const_get(addr[0][0]), Socket::SOCK_STREAM, 0).tap do |socket|
socket.setsockopt(Socket::IPPROTO_TCP, Socket::TCP_NODELAY, 1)
begin
socket.connect_nonblock(sockaddr)
rescue IO::WaitReadable
if IO.select([socket], nil, nil, timeout) == nil
raise "Connection timeout"
else
socket.connect_nonblock(sockaddr)
end
rescue IO::WaitWritable
if IO.select(nil, [socket], nil, timeout) == nil
raise "Connection timeout"
else
socket.connect_nonblock(sockaddr)
end
end
return socket
end
end
def try_tcp_write(socket, timeout = 5)
begin
socket.write_nonblock("\0")
rescue IO::WaitReadable
if IO.select([socket], nil, nil, timeout) == nil
raise "Write timeout"
else
retry
end
rescue IO::WaitWritable
if IO.select(nil, [socket], nil, timeout) == nil
raise "Write timeout"
else
retry
end
end
end
def try_tcp_read(socket, timeout = 5)
begin
socket.read_nonblock(1)
rescue IO::WaitReadable
if IO.select([socket], nil, nil, timeout) == nil
raise "Read timeout"
else
retry
end
rescue IO::WaitWritable
if IO.select(nil, [socket], nil, timeout) == nil
raise "Read timeout"
else
retry
end
end
end
def assert_tcp_socket(host, port, msg=nil)
begin
socket = try_tcp_connect(host, port, 1)
#try_tcp_write(socket,1)
#try_tcp_read(socket,1)
rescue StandardError => exc
fail ["Failed to open socket #{host}:#{port}", exc].join("\n")
ensure
socket.close if socket
end
end
end
|