Class MCollective::RPC::Helpers
In: lib/mcollective/rpc/helpers.rb
Parent: Object

Various utilities for the RPC system

Methods

Public Class methods

Add SimpleRPC common options

[Source]

     # File lib/mcollective/rpc/helpers.rb, line 283
283:       def self.add_simplerpc_options(parser, options)
284:         parser.separator ""
285: 
286:         # add SimpleRPC specific options to all clients that use our library
287:         parser.on('--np', '--no-progress', 'Do not show the progress bar') do |v|
288:           options[:progress_bar] = false
289:         end
290: 
291:         parser.on('--one', '-1', 'Send request to only one discovered nodes') do |v|
292:           options[:mcollective_limit_targets] = 1
293:         end
294: 
295:         parser.on('--batch SIZE', Integer, 'Do requests in batches') do |v|
296:           options[:batch_size] = v
297:         end
298: 
299:         parser.on('--batch-sleep SECONDS', Float, 'Sleep time between batches') do |v|
300:           options[:batch_sleep_time] = v
301:         end
302: 
303:         parser.on('--limit-seed NUMBER', Integer, 'Seed value for deterministic random batching') do |v|
304:           options[:limit_seed] = v
305:         end
306: 
307:         parser.on('--limit-nodes COUNT', '--ln', '--limit', 'Send request to only a subset of nodes, can be a percentage') do |v|
308:           raise "Invalid limit specified: #{v} valid limits are /^\d+%*$/" unless v =~ /^\d+%*$/
309: 
310:           if v =~ /^\d+$/
311:             options[:mcollective_limit_targets] = v.to_i
312:           else
313:             options[:mcollective_limit_targets] = v
314:           end
315:         end
316: 
317:         parser.on('--json', '-j', 'Produce JSON output') do |v|
318:           options[:progress_bar] = false
319:           options[:output_format] = :json
320:         end
321: 
322:         parser.on('--display MODE', 'Influence how results are displayed. One of ok, all or failed') do |v|
323:           if v == "all"
324:             options[:force_display_mode] = :always
325:           else
326:             options[:force_display_mode] = v.intern
327:           end
328: 
329:           raise "--display has to be one of 'ok', 'all' or 'failed'" unless [:ok, :failed, :always].include?(options[:force_display_mode])
330:         end
331:       end

Checks in PATH returns true if the command is found

[Source]

    # File lib/mcollective/rpc/helpers.rb, line 6
 6:       def self.command_in_path?(command)
 7:         found = ENV["PATH"].split(File::PATH_SEPARATOR).map do |p|
 8:           File.exist?(File.join(p, command))
 9:         end
10: 
11:         found.include?(true)
12:       end

Given an array of something, make sure each is a string chomp off any new lines and return just the array of hosts

[Source]

    # File lib/mcollective/rpc/helpers.rb, line 38
38:       def self.extract_hosts_from_array(hosts)
39:         [hosts].flatten.map do |host|
40:           raise "#{host} should be a string" unless host.is_a?(String)
41:           host.chomp
42:         end
43:       end

Parse JSON output as produced by printrpc and extract the "sender" of each rpc response

The simplist valid JSON based data would be:

[

 {"sender" => "example.com"},
 {"sender" => "another.com"}

]

[Source]

    # File lib/mcollective/rpc/helpers.rb, line 23
23:       def self.extract_hosts_from_json(json)
24:         hosts = JSON.parse(json)
25: 
26:         raise "JSON hosts list is not an array" unless hosts.is_a?(Array)
27: 
28:         hosts.map do |host|
29:           raise "JSON host list is not an array of Hashes" unless host.is_a?(Hash)
30:           raise "JSON host list does not have senders in it" unless host.include?("sender")
31: 
32:           host["sender"]
33:         end.uniq
34:       end

Backward compatible display block for results without a DDL

[Source]

     # File lib/mcollective/rpc/helpers.rb, line 231
231:       def self.old_rpcresults(result, flags = {})
232:         result_text = ""
233: 
234:         if flags[:flatten]
235:           result.each do |r|
236:             if r[:statuscode] <= 1
237:               data = r[:data]
238: 
239:               unless data.is_a?(String)
240:                 result_text << data.pretty_inspect
241:               else
242:                 result_text << data
243:               end
244:             else
245:               result_text << r.pretty_inspect
246:             end
247:           end
248: 
249:           result_text << ""
250:         else
251:           [result].flatten.each do |r|
252: 
253:             if flags[:verbose]
254:               result_text << "%-40s: %s\n" % [r[:sender], r[:statusmsg]]
255: 
256:               if r[:statuscode] <= 1
257:                 r[:data].pretty_inspect.split("\n").each {|m| result_text += "    #{m}"}
258:                 result_text << "\n\n"
259:               elsif r[:statuscode] == 2
260:                 # dont print anything, no useful data to display
261:                 # past what was already shown
262:               elsif r[:statuscode] == 3
263:                 # dont print anything, no useful data to display
264:                 # past what was already shown
265:               elsif r[:statuscode] == 4
266:                 # dont print anything, no useful data to display
267:                 # past what was already shown
268:               else
269:                 result_text << "    #{r[:statusmsg]}"
270:               end
271:             else
272:               unless r[:statuscode] == 0
273:                 result_text << "%-40s %s\n" % [r[:sender], Util.colorize(:red, r[:statusmsg])]
274:               end
275:             end
276:           end
277:         end
278: 
279:         result_text << ""
280:       end

Returns a blob of text representing the results in a standard way

It tries hard to do sane things so you often should not need to write your own display functions

If the agent you are getting results for has a DDL it will use the hints in there to do the right thing specifically it will look at the values of display in the DDL to choose when to show results

If you do not have a DDL you can pass these flags:

   printrpc exim.mailq, :flatten => true
   printrpc exim.mailq, :verbose => true

If you‘ve asked it to flatten the result it will not print sender hostnames, it will just print the result as if it‘s one huge result, handy for things like showing a combined mailq.

[Source]

     # File lib/mcollective/rpc/helpers.rb, line 87
 87:       def self.rpcresults(result, flags = {})
 88:         flags = {:verbose => false, :flatten => false, :format => :console, :force_display_mode => false}.merge(flags)
 89: 
 90:         result_text = ""
 91:         ddl = nil
 92: 
 93:         # if running in verbose mode, just use the old style print
 94:         # no need for all the DDL helpers obfuscating the result
 95:         if flags[:format] == :json
 96:           if STDOUT.tty?
 97:             result_text = JSON.pretty_generate(result)
 98:           else
 99:             result_text = result.to_json
100:           end
101:         else
102:           if flags[:verbose]
103:             result_text = old_rpcresults(result, flags)
104:           else
105:             [result].flatten.each do |r|
106:               begin
107:                 ddl ||= DDL.new(r.agent).action_interface(r.action.to_s)
108: 
109:                 sender = r[:sender]
110:                 status = r[:statuscode]
111:                 message = r[:statusmsg]
112:                 result = r[:data]
113: 
114:                 if flags[:force_display_mode]
115:                   display = flags[:force_display_mode]
116:                 else
117:                   display = ddl[:display]
118:                 end
119: 
120:                 # appand the results only according to what the DDL says
121:                 case display
122:                   when :ok
123:                     if status == 0
124:                       result_text << text_for_result(sender, status, message, result, ddl)
125:                     end
126: 
127:                   when :failed
128:                     if status > 0
129:                       result_text << text_for_result(sender, status, message, result, ddl)
130:                     end
131: 
132:                   when :always
133:                     result_text << text_for_result(sender, status, message, result, ddl)
134: 
135:                   when :flatten
136:                     result_text << text_for_flattened_result(status, result)
137: 
138:                 end
139:               rescue Exception => e
140:                 # no DDL so just do the old style print unchanged for
141:                 # backward compat
142:                 result_text = old_rpcresults(result, flags)
143:               end
144:             end
145:           end
146:         end
147: 
148:         result_text
149:       end

Figures out the columns and liens of the current tty

Returns [0, 0] if it can‘t figure it out or if you‘re not running on a tty

[Source]

    # File lib/mcollective/rpc/helpers.rb, line 49
49:       def self.terminal_dimensions
50:         return [0, 0] unless STDOUT.tty?
51: 
52:         return [80, 40] if Util.windows?
53: 
54:         if ENV["COLUMNS"] && ENV["LINES"]
55:           return [ENV["COLUMNS"].to_i, ENV["LINES"].to_i]
56: 
57:         elsif ENV["TERM"] && command_in_path?("tput")
58:           return [`tput cols`.to_i, `tput lines`.to_i]
59: 
60:         elsif command_in_path?('stty')
61:           return `stty size`.scan(/\d+/).map {|s| s.to_i }
62:         else
63:           return [0, 0]
64:         end
65:       rescue
66:         [0, 0]
67:       end

Returns text representing a flattened result of only good data

[Source]

     # File lib/mcollective/rpc/helpers.rb, line 218
218:       def self.text_for_flattened_result(status, result)
219:         result_text = ""
220: 
221:         if status <= 1
222:           unless result.is_a?(String)
223:             result_text << result.pretty_inspect
224:           else
225:             result_text << result
226:           end
227:         end
228:       end

Return text representing a result

[Source]

     # File lib/mcollective/rpc/helpers.rb, line 152
152:       def self.text_for_result(sender, status, msg, result, ddl)
153:         statusses = ["",
154:                      Util.colorize(:red, "Request Aborted"),
155:                      Util.colorize(:yellow, "Unknown Action"),
156:                      Util.colorize(:yellow, "Missing Request Data"),
157:                      Util.colorize(:yellow, "Invalid Request Data"),
158:                      Util.colorize(:red, "Unknown Request Status")]
159: 
160:         result_text = "%-40s %s\n" % [sender, statusses[status]]
161:         result_text << "   %s\n" % [Util.colorize(:yellow, msg)] unless msg == "OK"
162: 
163:         # only print good data, ignore data that results from failure
164:         if [0, 1].include?(status)
165:           if result.is_a?(Hash)
166:             # figure out the lengths of the display as strings, we'll use
167:             # it later to correctly justify the output
168:             lengths = result.keys.map do |k|
169:               begin
170:                 ddl[:output][k][:display_as].size
171:               rescue
172:                 k.to_s.size
173:               end
174:             end
175: 
176:             result.keys.sort_by{|k| k}.each do |k|
177:               # get all the output fields nicely lined up with a
178:               # 3 space front padding
179:               begin
180:                 display_as = ddl[:output][k][:display_as]
181:               rescue
182:                 display_as = k.to_s
183:               end
184: 
185:               display_length = display_as.size
186:               padding = lengths.max - display_length + 3
187:               result_text << " " * padding
188: 
189:               result_text << "#{display_as}:"
190: 
191:               if [String, Numeric].include?(result[k].class)
192:                 lines = result[k].to_s.split("\n")
193: 
194:                 if lines.empty?
195:                   result_text << "\n"
196:                 else
197:                   lines.each_with_index do |line, i|
198:                     i == 0 ? padtxt = " " : padtxt = " " * (padding + display_length + 2)
199: 
200:                     result_text << "#{padtxt}#{line}\n"
201:                   end
202:                 end
203:               else
204:                 padding = " " * (lengths.max + 5)
205:                 result_text << " " << result[k].pretty_inspect.split("\n").join("\n" << padding) << "\n"
206:               end
207:             end
208:           else
209:             result_text << "\n\t" + result.pretty_inspect.split("\n").join("\n\t")
210:           end
211:         end
212: 
213:         result_text << "\n"
214:         result_text
215:       end

[Validate]