1 # A Facter plugin that loads facts from /etc/facts.d.
3 # Facts can be in the form of JSON, YAML or Text files
4 # and any executable that returns key=value pairs.
6 # In the case of scripts you can also create a file that
7 # contains a cache TTL. For foo.sh store the ttl as just
8 # a number in foo.sh.ttl
10 # The cache is stored in /tmp/facts_cache.yaml as a mode
11 # 600 file and will have the end result of not calling your
12 # fact scripts more often than is needed
13 class Facter::Util::DotD
16 def initialize(dir="/etc/facts.d", cache_file="/tmp/facts_cache.yml")
18 @cache_file = cache_file
20 @types = {".txt" => :txt, ".json" => :json, ".yaml" => :yaml}
24 Dir.entries(@dir).reject{|f| f =~ /^\.|\.ttl$/}.sort.map {|f| File.join(@dir, f) }
30 extension = File.extname(file)
32 type = @types[extension] || :unknown
34 type = :script if type == :unknown && File.executable?(file)
40 File.readlines(file).each do |line|
41 if line =~ /^(.+)=(.+)$/
50 Facter.warn("Failed to handle #{file} as text facts: #{e.class}: #{e}")
61 JSON.load(File.read(file)).each_pair do |f, v|
67 Facter.warn("Failed to handle #{file} as json facts: #{e.class}: #{e}")
73 YAML.load_file(file).each_pair do |f, v|
79 Facter.warn("Failed to handle #{file} as yaml facts: #{e.class}: #{e}")
82 def script_parser(file)
83 result = cache_lookup(file)
84 ttl = cache_time(file)
87 result = Facter::Util::Resolution.exec(file)
90 Facter.debug("Updating cache for #{file}")
91 cache_store(file, result)
95 Facter.debug("Using cached data for #{file}")
98 result.split("\n").each do |line|
99 if line =~ /^(.+)=(.+)$/
107 rescue Exception => e
108 Facter.warn("Failed to handle #{file} as script facts: #{e.class}: #{e}")
109 Facter.debug(e.backtrace.join("\n\t"))
114 File.open(@cache_file, "w", 0600) {|f| f.write(YAML.dump(cache)) }
118 def cache_store(file, data)
121 @cache[file] = {:data => data, :stored => Time.now.to_i}
125 def cache_lookup(file)
128 return nil if cache.empty?
130 ttl = cache_time(file)
135 return cache[file][:data] if ttl == -1
136 return cache[file][:data] if (now - cache[file][:stored]) <= ttl
148 return File.read(meta).chomp.to_i
155 if File.exist?(@cache_file)
156 @cache = YAML.load_file(@cache_file)
169 entries.each do |fact|
170 type = fact_type(fact)
171 parser = "#{type}_parser"
173 if respond_to?("#{type}_parser")
174 Facter.debug("Parsing #{fact} using #{parser}")
182 Facter::Util::DotD.new("/etc/facter/facts.d").create
183 Facter::Util::DotD.new("/etc/puppetlabs/facter/facts.d").create