facter_dot_d.rb 4.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194
  1. # A Facter plugin that loads facts from /etc/facter/facts.d
  2. # and /etc/puppetlabs/facter/facts.d.
  3. #
  4. # Facts can be in the form of JSON, YAML or Text files
  5. # and any executable that returns key=value pairs.
  6. #
  7. # In the case of scripts you can also create a file that
  8. # contains a cache TTL. For foo.sh store the ttl as just
  9. # a number in foo.sh.ttl
  10. #
  11. # The cache is stored in $libdir/facts_dot_d.cache as a mode
  12. # 600 file and will have the end result of not calling your
  13. # fact scripts more often than is needed
  14. class Facter::Util::DotD
  15. require 'yaml'
  16. def initialize(dir = '/etc/facts.d', cache_file = File.join(Puppet[:libdir], 'facts_dot_d.cache'))
  17. @dir = dir
  18. @cache_file = cache_file
  19. @cache = nil
  20. @types = { '.txt' => :txt, '.json' => :json, '.yaml' => :yaml }
  21. end
  22. def entries
  23. Dir.entries(@dir).reject { |f| f =~ %r{^\.|\.ttl$} }.sort.map { |f| File.join(@dir, f) }
  24. rescue
  25. []
  26. end
  27. def fact_type(file)
  28. extension = File.extname(file)
  29. type = @types[extension] || :unknown
  30. type = :script if type == :unknown && File.executable?(file)
  31. type
  32. end
  33. def txt_parser(file)
  34. File.readlines(file).each do |line|
  35. next unless line =~ %r{^([^=]+)=(.+)$}
  36. var = Regexp.last_match(1)
  37. val = Regexp.last_match(2)
  38. Facter.add(var) do
  39. setcode { val }
  40. end
  41. end
  42. rescue StandardError => e
  43. Facter.warn("Failed to handle #{file} as text facts: #{e.class}: #{e}")
  44. end
  45. def json_parser(file)
  46. begin
  47. require 'json'
  48. rescue LoadError
  49. retry if require 'rubygems'
  50. raise
  51. end
  52. JSON.parse(File.read(file)).each_pair do |f, v|
  53. Facter.add(f) do
  54. setcode { v }
  55. end
  56. end
  57. rescue StandardError => e
  58. Facter.warn("Failed to handle #{file} as json facts: #{e.class}: #{e}")
  59. end
  60. def yaml_parser(file)
  61. require 'yaml'
  62. YAML.load_file(file).each_pair do |f, v|
  63. Facter.add(f) do
  64. setcode { v }
  65. end
  66. end
  67. rescue StandardError => e
  68. Facter.warn("Failed to handle #{file} as yaml facts: #{e.class}: #{e}")
  69. end
  70. def script_parser(file)
  71. result = cache_lookup(file)
  72. ttl = cache_time(file)
  73. if result
  74. Facter.debug("Using cached data for #{file}")
  75. else
  76. result = Facter::Util::Resolution.exec(file)
  77. if ttl > 0
  78. Facter.debug("Updating cache for #{file}")
  79. cache_store(file, result)
  80. cache_save!
  81. end
  82. end
  83. result.split("\n").each do |line|
  84. next unless line =~ %r{^(.+)=(.+)$}
  85. var = Regexp.last_match(1)
  86. val = Regexp.last_match(2)
  87. Facter.add(var) do
  88. setcode { val }
  89. end
  90. end
  91. rescue StandardError => e
  92. Facter.warn("Failed to handle #{file} as script facts: #{e.class}: #{e}")
  93. Facter.debug(e.backtrace.join("\n\t"))
  94. end
  95. def cache_save!
  96. cache = load_cache
  97. File.open(@cache_file, 'w', 0o600) { |f| f.write(YAML.dump(cache)) }
  98. rescue # rubocop:disable Lint/HandleExceptions
  99. end
  100. def cache_store(file, data)
  101. load_cache
  102. @cache[file] = { :data => data, :stored => Time.now.to_i }
  103. rescue # rubocop:disable Lint/HandleExceptions
  104. end
  105. def cache_lookup(file)
  106. cache = load_cache
  107. return nil if cache.empty?
  108. ttl = cache_time(file)
  109. return nil unless cache[file]
  110. now = Time.now.to_i
  111. return cache[file][:data] if ttl == -1
  112. return cache[file][:data] if (now - cache[file][:stored]) <= ttl
  113. return nil
  114. rescue
  115. return nil
  116. end
  117. def cache_time(file)
  118. meta = file + '.ttl'
  119. return File.read(meta).chomp.to_i
  120. rescue
  121. return 0
  122. end
  123. def load_cache
  124. @cache ||= if File.exist?(@cache_file)
  125. YAML.load_file(@cache_file)
  126. else
  127. {}
  128. end
  129. return @cache
  130. rescue
  131. @cache = {}
  132. return @cache
  133. end
  134. def create
  135. entries.each do |fact|
  136. type = fact_type(fact)
  137. parser = "#{type}_parser"
  138. next unless respond_to?("#{type}_parser")
  139. Facter.debug("Parsing #{fact} using #{parser}")
  140. send(parser, fact)
  141. end
  142. end
  143. end
  144. mdata = Facter.version.match(%r{(\d+)\.(\d+)\.(\d+)})
  145. if mdata
  146. (major, minor, _patch) = mdata.captures.map { |v| v.to_i }
  147. if major < 2
  148. # Facter 1.7 introduced external facts support directly
  149. unless major == 1 && minor > 6
  150. Facter::Util::DotD.new('/etc/facter/facts.d').create
  151. Facter::Util::DotD.new('/etc/puppetlabs/facter/facts.d').create
  152. # Windows has a different configuration directory that defaults to a vendor
  153. # specific sub directory of the %COMMON_APPDATA% directory.
  154. if Dir.const_defined? 'COMMON_APPDATA' # rubocop:disable Metrics/BlockNesting : Any attempt to alter this breaks it
  155. windows_facts_dot_d = File.join(Dir::COMMON_APPDATA, 'PuppetLabs', 'facter', 'facts.d')
  156. Facter::Util::DotD.new(windows_facts_dot_d).create
  157. end
  158. end
  159. end
  160. end