Skip to content

Commit

Permalink
Refactor and tweak canonicalize_hostname logic
Browse files Browse the repository at this point in the history
Signed-off-by: Thomas Powell <thomas.powell@progress.com>
  • Loading branch information
tpowell-progress committed Oct 3, 2023
1 parent 110217d commit 6bde4b1
Showing 1 changed file with 20 additions and 5 deletions.
25 changes: 20 additions & 5 deletions lib/ohai/mixin/network_helper.rb
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
#

require "socket" unless defined?(Socket)
require "resolv" unless defined?(Resolv)

module Ohai
module Mixin
Expand All @@ -37,6 +38,11 @@ def hex_to_dec_netmask(netmask)
dec
end

def ip?(hostname)
!!(canonname =~ Resolv::IPv4::Regex) || !!(canonname =~ Resolv::IPv6::Regex)

Check failure on line 43 in lib/ohai/mixin/network_helper.rb

View workflow job for this annotation

GitHub Actions / chefstyle

[Correctable] Layout/EmptyLinesAroundMethodBody: Extra empty line detected at method body end.
end

# This does a forward and reverse lookup on the hostname to return what should be
# the FQDN for the host determined by name lookup (generally DNS). If the forward
# lookup fails this will throw. If the reverse lookup fails this will return the
Expand All @@ -52,12 +58,21 @@ def canonicalize_hostname(hostname)
.first

canonname = ai&.canonname
# use canonname
return canonname if canonname != hostname || !ChefUtils.windows?
# use canonname if it's an FQDN
# This API is preferred as it never gives us an IP address for broken DNS
# (see https://github.com/chef/ohai/pull/1705)
# However, we have found that Windows hosts that are not joined to a domain
# can return a non-qualified hostname)
return canonname unless ip?(canonname)

# If we got a non-qualified name, then we do a standard reverse resolve
# which, assuming DNS is working, will work around that windows bug
# (and maybe others)
canonname = ai&.getnameinfo&.first
return canonname unless ip?(canonname)

# canonname does not fully qualify the hostname if on Windows node that
# is not joined to a domain, but getnameinfo does.
ai&.getnameinfo&.[](0) || hostname
# if all else fails, return the name we were given as a safety
hostname
end

def canonicalize_hostname_with_retries(hostname)
Expand Down

0 comments on commit 6bde4b1

Please sign in to comment.