Speed up open port detection

This commit is contained in:
Chris Roberts 2020-08-07 16:37:32 -07:00
parent 05a3e122fb
commit 98ffa4add0
2 changed files with 8 additions and 22 deletions

View File

@ -1,5 +1,4 @@
require "socket"
require "timeout"
module Vagrant
module Util
@ -14,25 +13,13 @@ module Vagrant
# @return [Boolean] `true` if the port is open (listening), `false`
# otherwise.
def is_port_open?(host, port)
# We wrap this in a timeout because once in awhile the TCPSocket
# _will_ hang, but this signals that the port is closed.
Timeout.timeout(1) do
# Attempt to make a connection
s = TCPSocket.new(host, port)
# A connection was made! Properly clean up the socket, not caring
# at all if any exception is raised, because we already know the
# result.
s.close rescue nil
# The port is open if we reached this point, since we were able
# to connect.
return true
begin
Socket.tcp(host, port, connect_timeout: 0.1).close
true
rescue Errno::ETIMEDOUT, Errno::ECONNREFUSED, Errno::EHOSTUNREACH, \
Errno::ENETUNREACH, Errno::EACCES, Errno::ENOTCONN
false
end
rescue Timeout::Error, Errno::ECONNREFUSED, Errno::EHOSTUNREACH, \
Errno::ENETUNREACH, Errno::EACCES, Errno::ENOTCONN
# Any of the above exceptions signal that the port is closed.
return false
end
extend IsPortOpen

View File

@ -47,13 +47,12 @@ describe Vagrant::Util::IsPortOpen do
end
it "should handle connection refused" do
expect(TCPSocket).to receive(:new).with("0.0.0.0", closed_port).and_raise(Errno::ECONNREFUSED)
expect(Socket).to receive(:tcp).with("0.0.0.0", closed_port, any_args).and_raise(Errno::ECONNREFUSED)
expect(subject.is_port_open?("0.0.0.0", closed_port)).to be(false)
end
it "should raise an error if cannot assign requested address" do
expect(TCPSocket).to receive(:new).with("0.0.0.0", open_port).and_raise(Errno::EADDRNOTAVAIL)
expect(Socket).to receive(:tcp).with("0.0.0.0", open_port, any_args).and_raise(Errno::EADDRNOTAVAIL)
expect { subject.is_port_open?("0.0.0.0", open_port) }.to raise_error(Errno::EADDRNOTAVAIL)
end
end