Class: DNSCached

Inherits:
Object show all
Defined in:
puppet/modules/wmflib/lib/puppet/parser/functions/ipresolve.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(cache = nil, default_ttl = 300) ⇒ DNSCached

Returns a new instance of DNSCached.



71
72
73
74
# File 'puppet/modules/wmflib/lib/puppet/parser/functions/ipresolve.rb', line 71

def initialize(cache = nil, default_ttl = 300)
  @cache = cache || BasicTTLCache.new
  @default_ttl = default_ttl
end

Instance Attribute Details

#dnsObject

Returns the value of attribute dns.



70
71
72
# File 'puppet/modules/wmflib/lib/puppet/parser/functions/ipresolve.rb', line 70

def dns
  @dns
end

Instance Method Details

#get_resource(name, type, nameserver) ⇒ Object



76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
# File 'puppet/modules/wmflib/lib/puppet/parser/functions/ipresolve.rb', line 76

def get_resource(name, type, nameserver)
  if nameserver.nil?
    dns = Resolv::DNS.open
  else
    dns = Resolv::DNS.open(:nameserver => [nameserver])
  end
  cache_key = "#{name}_#{type}_#{nameserver}"
  res = @cache.read(cache_key)
  if res.nil?
    begin
      res = dns.getresource(name, type)
      # Ruby < 1.9 returns nil as the ttl...
      if res.ttl
        ttl = res.ttl
      else
        ttl = @default_ttl
      end
      if type == Resolv::DNS::Resource::IN::PTR
        retval = res.name
      else
        retval = res.address
      end
      @cache.write(cache_key, retval, ttl)
      retval.to_s
    rescue
    # If resolution fails and we do have a cached stale value, use it
      res = @cache.read_stale(cache_key)
      if res.nil?
        fail("DNS lookup failed for #{name} #{type}")
      end
      res.to_s
    end
  else
    res.to_s
  end
end