Update code from https://github.com/dmi-try/marionette-collective
[packages/precise/mcollective.git] / lib / mcollective / data / base.rb
1 module MCollective
2   module Data
3     class Base
4       attr_reader :name, :result, :ddl, :timeout
5
6       # Register plugins that inherits base
7       def self.inherited(klass)
8         type = klass.to_s.split("::").last.downcase
9
10         PluginManager << {:type => type, :class => klass.to_s, :single_instance => false}
11       end
12
13       def initialize
14         @name = self.class.to_s.split("::").last.downcase
15         @ddl = DDL.new(@name, :data)
16         @result = Result.new(@ddl.dataquery_interface[:output])
17         @timeout = @ddl.meta[:timeout] || 1
18
19         startup_hook
20       end
21
22       def lookup(what)
23         ddl_validate(what)
24
25         Log.debug("Doing data query %s for '%s'" % [ @name, what ])
26
27         Timeout::timeout(@timeout) do
28           query_data(what)
29         end
30
31         @result
32       rescue Timeout::Error
33         # Timeout::Error is a inherited from Interrupt which seems a really
34         # strange choice, making it an equivelant of ^C and such.  Catch it
35         # and raise something less critical that will not the runner to just
36         # give up the ghost
37         msg = "Data plugin %s timed out on query '%s'" % [@name, what]
38         Log.error(msg)
39         raise MsgTTLExpired, msg
40       end
41
42       def self.query(&block)
43         self.module_eval { define_method("query_data", &block) }
44       end
45
46       def ddl_validate(what)
47         Data.ddl_validate(@ddl, what)
48       end
49
50       # activate_when do
51       #    file.exist?("/usr/bin/puppet")
52       # end
53       def self.activate_when(&block)
54         (class << self; self; end).instance_eval do
55           define_method("activate?", &block)
56         end
57       end
58
59       # Always be active unless a specific block is given with activate_when
60       def self.activate?
61         return true
62       end
63
64       def startup_hook;end
65     end
66   end
67 end