Module: Sensu::Redis::Utilities

Included in:
Sensu::Redis, Client, Sentinel
Defined in:
lib/sensu/redis/utilities.rb

Instance Method Summary collapse

Instance Method Details

#ip_address?(host) ⇒ TrueClass, FalseClass

Determine if a host is an IP address (or DNS hostname).

Parameters:

  • host (String)

Returns:

  • (TrueClass, FalseClass)

11
12
13
14
15
16
17
18
# File 'lib/sensu/redis/utilities.rb', line 11

def ip_address?(host)
  begin
    ip_address = IPAddr.new(host)
    ip_address.ipv4? || ip_address.ipv6?
  rescue IPAddr::InvalidAddressError
    false
  end
end

#resolve_host(host, &block) ⇒ Object

Resolve a hostname to an IP address for a host. This method will return the provided host to the provided block if it is already an IP address. This method will return `nil` to the provided block when the hostname cannot be resolved to an IP address.

Parameters:

  • host (String)
  • block (Proc)

    called with the result of the DNS query (IP address).


59
60
61
62
63
64
65
# File 'lib/sensu/redis/utilities.rb', line 59

def resolve_host(host, &block)
  if ip_address?(host)
    yield host
  else
    resolve_hostname(host, &block)
  end
end

#resolve_hostname(host, &block) ⇒ Object

Resolve a hostname to an IP address for a host. This method will return `nil` to the provided block when the hostname cannot be resolved to an IP address.

Parameters:

  • host (String)
  • block (Proc)

    called with the result of the DNS query (IP address).


27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
# File 'lib/sensu/redis/utilities.rb', line 27

def resolve_hostname(host, &block)
  resolve = Proc.new do
    begin
      info = case RUBY_PLATFORM
      when /linux/
        flags = Socket::AI_NUMERICSERV | Socket::AI_ADDRCONFIG
        Socket.getaddrinfo(host, nil, Socket::AF_UNSPEC, nil, nil, flags)
      else
        Socket.getaddrinfo(host, nil)
      end
      info.first.nil? ? nil : info.first[2]
    rescue => error
      @logger.error("redis connection error", {
        :reason => "unable to resolve hostname",
        :host => host,
        :error => error.to_s
      }) if @logger
      nil
    end
  end
  EM.defer(resolve, block)
end