Update version according to OSCI-856
[packages/precise/mcollective.git] / plugins / mcollective / discovery / stdin.rb
1 # discovers against stdin instead of the traditional network discovery
2 # the input must be a flat file with a node name per line which should match identities as configured,
3 # or it should be a json string as output by the -j option of mco rpc
4 require 'mcollective/rpc/helpers'
5
6 module MCollective
7   class Discovery
8     class Stdin
9       def self.discover(filter, timeout, limit=0, client=nil)
10         unless client.options[:discovery_options].empty?
11           type = client.options[:discovery_options].first.downcase
12         else
13           type = 'auto'
14         end
15
16         discovered = []
17
18         file = STDIN.read
19
20         if file =~ /^\s*$/
21               raise("data piped on STDIN contained only whitespace - could not discover hosts from it.")
22         end
23
24         if type == 'auto'
25           if file =~ /^\s*\[/
26             type = 'json'
27           else
28             type = 'text'
29           end
30         end
31
32         if type == 'json'
33           hosts = MCollective::RPC::Helpers.extract_hosts_from_json(file)
34         elsif type == 'text'
35           hosts = file.split("\n")
36         else
37           raise("stdin discovery plugin only knows the types auto/text/json, not \"#{type}\"")
38         end
39
40         hosts.map do |host|
41           raise 'Identities can only match /\w\.\-/' unless host.match(/^[\w\.\-]+$/)
42           host
43         end
44
45         # this plugin only supports identity filters, do regex matches etc against
46         # the list found in the flatfile
47         unless filter["identity"].empty?
48           filter["identity"].each do |identity|
49             identity = Regexp.new(identity.gsub("\/", "")) if identity.match("^/")
50
51             if identity.is_a?(Regexp)
52               discovered = hosts.grep(identity)
53             elsif hosts.include?(identity)
54               discovered << identity
55             end
56           end
57         else
58           discovered = hosts
59         end
60
61         discovered
62       end
63     end
64   end
65 end
66