Class: Onering::Reporter
- Inherits:
-
Object
- Object
- Onering::Reporter
- Includes:
- Util
- Defined in:
- lib/onering/plugins/reporter.rb
Defined Under Namespace
Classes: PluginDelegate
Constant Summary collapse
- DEFAULT_PLUGIN_GEMNAMES =
[ 'onering-report-plugins' ]
- DEFAULT_PLUGIN_PATH =
[ '/var/lib/onering/reporter' ]
- DEFAULT_FACTER_PATH =
[ '/etc/facter' ]
- DEFAULT_CACHE_FILE =
'/var/tmp/.onering-report-cache.json'
- DEFAULT_CACHE_MAXAGE =
600
Constants included from Util
Instance Attribute Summary collapse
-
#facter_path ⇒ Object
readonly
Returns the value of attribute facter_path.
Instance Method Summary collapse
- #_cache_expired?(cache, age = DEFAULT_CACHE_MAXAGE) ⇒ Boolean
- #_cached_report(options = {}) ⇒ Object
- #_generated_report ⇒ Object
- #_update_cache_file(cachefile = DEFAULT_CACHE_FILE) ⇒ Object
- #get(field, default = nil, options = {}) ⇒ Object
-
#initialize(config = {}) ⇒ Reporter
constructor
A new instance of Reporter.
- #load_plugins ⇒ Object
- #property(name, value = nil) ⇒ Object
- #report(options = {}) ⇒ Object
Methods included from Util
#fact, #gem_path, #http_status, #make_filter
Constructor Details
#initialize(config = {}) ⇒ Reporter
Returns a new instance of Reporter.
66 67 68 69 70 71 72 73 74 75 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 |
# File 'lib/onering/plugins/reporter.rb', line 66 def initialize(config={}) @options = config @facter_path = DEFAULT_FACTER_PATH @detected_gems = [] @path = [*Onering::Config.get('reporter.plugin_path',[])] @path += DEFAULT_PLUGIN_PATH begin specs = Set.new() @detected_gems = [] Gem::Specification.each do |spec| specs << spec.name end @detected_gems = (specs.to_a.select{|i| i =~ /^onering-report-/ } - DEFAULT_PLUGIN_GEMNAMES) rescue Exception => e Onering::Logger.warn("Unable to detect plugin gems: #{e.class.name} - #{e.}", "Onering::Reporter") end # add gem paths to the @path ([*Onering::Config.get('reporter.plugin_gems',[])]+@detected_gems+DEFAULT_PLUGIN_GEMNAMES).compact.each do |g| begin p = File.join(Util.gem_path(g), 'lib') @path << File.join(p, 'reporter') @facter_path << File.join(p, 'facter') rescue Gem::LoadError => e Onering::Logger.warn("Error loading gem: #{e.}", "Onering::Reporter") next end end begin ENV['FACTERLIB'] = @facter_path.join(':') require 'facter' Onering::Logger.debug("Facter loaded successfully, FACTERLIB is #{ENV['FACTERLIB']}", "Onering::Reporter") rescue LoadError Onering::Logger.error("Unable to load Facter library", "Onering::Reporter") end end |
Instance Attribute Details
#facter_path ⇒ Object (readonly)
Returns the value of attribute facter_path.
27 28 29 |
# File 'lib/onering/plugins/reporter.rb', line 27 def facter_path @facter_path end |
Instance Method Details
#_cache_expired?(cache, age = DEFAULT_CACHE_MAXAGE) ⇒ Boolean
352 353 354 355 356 357 358 |
# File 'lib/onering/plugins/reporter.rb', line 352 def _cache_expired?(cache, age=DEFAULT_CACHE_MAXAGE) if cache.is_a?(Hash) return (Time.parse(cache.get('cached_at')) < (Time.now - age) rescue true) else return true end end |
#_cached_report(options = {}) ⇒ Object
288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 |
# File 'lib/onering/plugins/reporter.rb', line 288 def _cached_report(={}) = @options.merge() cachefile = ([:cachefile] || DEFAULT_CACHE_FILE) tries = 0 catch(:retry) do tries += 1 if tries > 10 Onering::Logger.error("Too many retries reading cache #{cachefile}, generating report", "Onering::Reporter") return _generated_report() end if File.readable?(cachefile) Onering::Logger.debug("Loading cache file at #{cachefile}", "Onering::Reporter") cache = File.read(cachefile) cache = (MultiJson.load(cache) rescue {}) if _cache_expired?(cache, [:maxage]) Onering::Logger.debug("Cache expired, regenerating", "Onering::Reporter") throw :retry if _update_cache_file(cachefile) end if [:cacheregen] == true Onering::Logger.debug("Forcing cache regeneration", "Onering::Reporter") cache = _update_cache_file(cachefile) end if cache # remove cached_at key Onering::Logger.debug("Using cached data (#{Time.now.to_i - Time.parse(cache.get('cached_at')).to_i} seconds old)", "Onering::Reporter") cache.delete('cached_at') return cache end else Onering::Logger.debug("Report cache file could not be read at #{cachefile}", "Onering::Reporter") throw :retry if _update_cache_file(cachefile) end end return {} end |
#_generated_report ⇒ Object
249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 |
# File 'lib/onering/plugins/reporter.rb', line 249 def _generated_report() Timeout.timeout((@options[:timeout] || 60).to_i) do hostname = (Facter.value('fqdn') rescue %x{hostname -f}.strip.chomp) @_report = { :id => @id, :name => hostname, :aliases => @options[:aliases], :tags => @options[:tags], :status => (@options[:status] || 'online'), :inventory => true, :properties => {} } # loads plugins and populates @_report load_plugins() # pull report field overrides from the config file Onering::Config.get('reporter.fields',{}).each do |key, value| Onering::Logger.debug("Override value #{key} from config file", "Onering::CLI::Report") if value.is_a?(Hash) value.coalesce(key, nil, '.').each do |k,v| v = nil if ['null', '', '-'].include?(v.to_s.strip.chomp) @_report = @_report.set(k, v) end else value = nil if ['null', '', '-'].include?(value.to_s.strip.chomp) @_report = @_report.set(key, value) end end # return final report return @_report.stringify_keys() end return {} end |
#_update_cache_file(cachefile = DEFAULT_CACHE_FILE) ⇒ Object
332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 |
# File 'lib/onering/plugins/reporter.rb', line 332 def _update_cache_file(cachefile=DEFAULT_CACHE_FILE) begin report = nil File.open(cachefile, 'w+') do |file| Onering::Logger.debug("Regenerating cache file at #{cachefile}", "Onering::Reporter") report = _generated_report() report['cached_at'] = Time.now.strftime('%Y-%m-%dT%H:%M:%S%z') json = MultiJson.dump(report, :pretty => true) file.puts(json) end return report rescue Exception => e Onering::Logger.info("Unable to write cache file #{cachefile}: #{e.class.name} - #{e.}", "Onering::Reporter") return false end end |
#get(field, default = nil, options = {}) ⇒ Object
191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 |
# File 'lib/onering/plugins/reporter.rb', line 191 def get(field, default=nil, ={}) if [:data].is_a?(Hash) _report = [:data] else _report = self.report() end # this is kinda ugly # because we don't know which property might have an @-prefix, progressively # search through all of them. first non-null match wins parts = field.to_s.split('.') # create an array with every component of the path prefixed with the @-symbol, then with # the path as is. # # e.g.: onering report get metrics.disk.block # -> value exists in the inventory as properties.metrics.disk.@block, # but the user shouldn't need to know where that @-prefix is, so... # # Search for all of these, first non-nil value wins: # * properties.metrics.disk.block # * [email protected] # * [email protected] # * properties.metrics.disk.@block # * metrics.disk.block # candidates = [(['properties']+parts).join('.')] parts.each_index{|ix| candidates << (['properties']+(ix == 0 ? [] : parts[0..(ix-1)]) + ["@#{parts[ix]}"] + parts[ix+1..-1]).join('.') }.flatten() rv = nil # search for the key using science or something candidates.each do |c| rv = _report.get(c) break unless rv.nil? end # if we're still nil by this point, use the fallback value rv = _report.get(field) if rv.nil? # attempt to get the value remotely if not found locally if rv.nil? and not [:local] hid = Onering::Util.fact(:hardwareid) if not hid.nil? Onering::Logger.debug("Getting remote value #{field} for asset #{hid}") return Onering::API.new([:api]).assets.get_field(hid, field, default) end end return default if rv.nil? return rv end |
#load_plugins ⇒ Object
112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 |
# File 'lib/onering/plugins/reporter.rb', line 112 def load_plugins() # load plugins from @path @path.compact.uniq.each do |root| begin Dir["#{root}/*"].uniq.each do |directory| # only process top-level directories if File.directory?(directory) d = File.basename(directory) Onering::Logger.debug("Loading plugins from path #{directory}", "Onering::Reporter") # allow plugins to be conditionally loaded based on fact values: # default - always load # <fact>-<fact_value> - load if <fact> == <fact_value> # if d == 'default' or Facter.value(d.split('-',2).first).to_s.downcase.nil_empty == d.split('-',2).last.to_s.downcase.nil_empty Dir[File.join(directory, '*.rb')].each do |plugin| plugin = File.basename(plugin, '.rb') begin Timeout.timeout((@options[:plugin_timeout] || 10).to_i) do Onering::Logger.debug("Loading plugin #{directory}/#{plugin}.rb", "Onering::Reporter") Onering::Logger.debug3("Properties will be set in report object #{@_report.object_id}", "Onering::Reporter") eval(File.read("#{directory}/#{plugin}.rb"), PluginDelegate.new(self, { :plugin => plugin, :path => "#{directory}/#{plugin}.rb" }).get_binding()) end rescue Timeout::Error Onering::Logger.warn("Plugin #{plugin} took too long to return, skipping", "Onering::Reporter") end end end end end rescue Exception => e raise e if e.class === Timeout::Error Onering::Logger.warn(e., "Onering::Reporter/#{e.class.name}") e.backtrace.each do |eb| Onering::Logger.debug(eb, "Onering::Reporter/#{e.class.name}") end next end end end |
#property(name, value = nil) ⇒ Object
164 165 166 167 168 169 |
# File 'lib/onering/plugins/reporter.rb', line 164 def property(name, value=nil) unless value.nil? Onering::Logger.debug3("-> Set property #{name.to_s} (was: #{@_report[:properties].get(name.to_s,'null')}) in object #{@_report.object_id}", "Onering::Reporter") @_report[:properties].set(name.to_s, value) end end |
#report(options = {}) ⇒ Object
171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 |
# File 'lib/onering/plugins/reporter.rb', line 171 def report(={}) = @options.merge() @id = (@options[:id] || Onering::Config.get('id') || Onering::Config.get('reporter.fields.id') || Onering::Util.fact('hardwareid', nil)) if not @id.nil? if [:nocache] return _generated_report() else rv = _cached_report() return _generated_report() if rv.nil? or rv.empty? return rv end else Onering::Logger.fatal!("Cannot generate report without an ID", "Onering::Reporter") end return {} end |