b1e7f14577036d102003c0581399d432bda8622f
[packages/precise/mcollective.git] / lib / mcollective / registration / base.rb
1 module MCollective
2   module Registration
3     # This is a base class that other registration plugins can use
4     # to handle regular announcements to the mcollective
5     #
6     # The configuration file determines how often registration messages
7     # gets sent using the _registerinterval_ option, the plugin runs in the
8     # background in a thread.
9     class Base
10       # Register plugins that inherits base
11       def self.inherited(klass)
12         PluginManager << {:type => "registration_plugin", :class => klass.to_s}
13       end
14
15       # Creates a background thread that periodically send a registration notice.
16       #
17       # The actual registration notices comes from the 'body' method of the registration
18       # plugins.
19       def run(connection)
20         return false if interval == 0
21
22         Thread.new do
23           loop do
24             begin
25               publish(body)
26
27               sleep interval
28             rescue Exception => e
29               Log.error("Sending registration message failed: #{e}")
30               sleep interval
31             end
32           end
33         end
34       end
35
36       def config
37         Config.instance
38       end
39
40       def msg_filter
41         filter = Util.empty_filter
42         filter["agent"] << "registration"
43         filter
44       end
45
46       def target_collective
47         main_collective = config.main_collective
48
49         collective = config.registration_collective || main_collective
50
51         unless config.collectives.include?(collective)
52           Log.warn("Sending registration to #{main_collective}: #{collective} is not a valid collective")
53           collective = main_collective
54         end
55
56         return collective
57       end
58
59       def interval
60         config.registerinterval
61       end
62
63       def publish(message)
64         unless message
65           Log.debug("Skipping registration due to nil body")
66         else
67           req = Message.new(message, nil, {:type => :request, :agent => "registration", :collective => target_collective, :filter => msg_filter})
68           req.encode!
69
70           Log.debug("Sending registration #{req.requestid} to collective #{req.collective}")
71
72           req.publish
73         end
74       end
75     end
76   end
77 end