lib/vagrant-hosts/addresses.rb in vagrant-hosts-2.8.0 vs lib/vagrant-hosts/addresses.rb in vagrant-hosts-2.8.1

- old
+ new

@@ -1,18 +1,24 @@ -require 'resolv' require 'ipaddr' +require 'socket' # For Addrinfo +require 'vagrant/errors' + module VagrantHosts::Addresses # Cache for networking data # # @return [Hash{String => Hash{String => String}}] # @private # # @since 2.7.0 CACHE ||= {} + class UnresolvableHostname < ::Vagrant::Errors::VagrantError + error_key(:unresolvable_hostname, 'vagrant_hosts.errors') + end + private def all_hosts(config) all_hosts = [] all_hosts += local_hosts(@machine, config) @@ -90,11 +96,20 @@ next if m.name == machine.name host_provisioners(m).each do |p| imports.each do |k| next unless p.config.exports.has_key?(k) - hosts.concat resolve_host_entries(p.config.exports[k], m) + begin + hosts.concat resolve_host_entries(p.config.exports[k], m) + rescue Vagrant::Errors::VagrantError => e + machine.ui.error I18n.t( + 'vagrant_hosts.errors.collection_failed', + :host => m.name.to_s, + :error_class => e.class, + :message => e.message + ) + end end end end hosts.uniq @@ -182,22 +197,36 @@ # This function resolves a string into an IP address. # IP addresses. # # @param address [String] A string that might be an IP address or a hostname. # - # @raise [IPAddr::InvalidAddressError] Raised when an invalid address is - # supplied. - # @raise [Resolv::ResolvError] When a hostname cannot be resolved to an IP. + # @raise [VagrantHosts::Addresses::UnresolvableHostname] If `address` is a + # maformed IP address or unresolvable hostname. # # @return [IPAddr] An IP address. # # @since 2.7.0 def resolve_ip(address) ip = begin IPAddr.new(address) rescue IPAddr::InvalidAddressError - # Wasn't an IP address. Resolve it. The AWS provider does this. - IPAddr.new(Resolv.getaddress(address)) + nil + end + + ip ||= begin + # Wasn't an IP address. Resolve it. The "@vagrant_ssh" returns a + # hostname instead of IP when the AWS provider is in use. + # + # NOTE: Name resolution is done using Ruby's Addrinfo instead of Resolv + # as Addrinfo always uses the system resolver library and thus picks up + # platform-specific behavior such as the OS X /etc/resolver/ directory. + IPAddr.new(Addrinfo.ip(address).ip_address) + rescue IPAddr::InvalidAddressError, SocketError + nil + end + + if ip.nil? + raise UnresolvableHostname, address: address end ip end