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 294
294:       def self.add_simplerpc_options(parser, options)
295:         parser.separator ""
296: 
297:         # add SimpleRPC specific options to all clients that use our library
298:         parser.on('--np', '--no-progress', 'Do not show the progress bar') do |v|
299:           options[:progress_bar] = false
300:         end
301: 
302:         parser.on('--one', '-1', 'Send request to only one discovered nodes') do |v|
303:           options[:mcollective_limit_targets] = 1
304:         end
305: 
306:         parser.on('--batch [SIZE]', Integer, 'Do requests in batches') do |v|
307:           raise "Size is required, see --help" unless v
308:           options[:batch_size] = v
309:         end
310: 
311:         parser.on('--batch-sleep [SECONDS]', Float, 'Sleep time between batches') do |v|
312:           raise "Seconds are required, see --help" unless v
313:           options[:batch_sleep_time] = v
314:         end
315: 
316:         parser.on('--limit-nodes [COUNT]', '--ln [COUNT]', 'Send request to only a subset of nodes, can be a percentage') do |v|
317:           raise "Invalid limit specified: #{v} valid limits are /^\d+%*$/" unless v =~ /^\d+%*$/
318: 
319:           if v =~ /^\d+$/
320:             options[:mcollective_limit_targets] = v.to_i
321:           else
322:             options[:mcollective_limit_targets] = v
323:           end
324:         end
325: 
326:         parser.on('--json', '-j', 'Produce JSON output') do |v|
327:           options[:progress_bar] = false
328:           options[:output_format] = :json
329:         end
330:       end

Return color codes, if the config color= option is false just return a empty string

[Source]

    # File lib/mcollective/rpc/helpers.rb, line 69
69:       def self.color(code)
70:         colorize = Config.instance.color
71: 
72:         colors = {:red => "",
73:           :green => "",
74:           :yellow => "",
75:           :cyan => "",
76:           :bold => "",
77:           :reset => ""}
78: 
79:         if colorize
80:           return colors[code] || ""
81:         else
82:           return ""
83:         end
84:       end

Helper to return a string in specific color

[Source]

    # File lib/mcollective/rpc/helpers.rb, line 87
87:       def self.colorize(code, msg)
88:         "#{self.color(code)}#{msg}#{self.color(:reset)}"
89:       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 242
242:       def self.old_rpcresults(result, flags = {})
243:         result_text = ""
244: 
245:         if flags[:flatten]
246:           result.each do |r|
247:             if r[:statuscode] <= 1
248:               data = r[:data]
249: 
250:               unless data.is_a?(String)
251:                 result_text << data.pretty_inspect
252:               else
253:                 result_text << data
254:               end
255:             else
256:               result_text << r.pretty_inspect
257:             end
258:           end
259: 
260:           result_text << ""
261:         else
262:           [result].flatten.each do |r|
263: 
264:             if flags[:verbose]
265:               result_text << "%-40s: %s\n" % [r[:sender], r[:statusmsg]]
266: 
267:               if r[:statuscode] <= 1
268:                 r[:data].pretty_inspect.split("\n").each {|m| result_text += "    #{m}"}
269:                 result_text << "\n\n"
270:               elsif r[:statuscode] == 2
271:                 # dont print anything, no useful data to display
272:                 # past what was already shown
273:               elsif r[:statuscode] == 3
274:                 # dont print anything, no useful data to display
275:                 # past what was already shown
276:               elsif r[:statuscode] == 4
277:                 # dont print anything, no useful data to display
278:                 # past what was already shown
279:               else
280:                 result_text << "    #{r[:statusmsg]}"
281:               end
282:             else
283:               unless r[:statuscode] == 0
284:                 result_text << "%-40s %s\n" % [r[:sender], colorize(:red, r[:statusmsg])]
285:               end
286:             end
287:           end
288:         end
289: 
290:         result_text << ""
291:       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 109
109:       def self.rpcresults(result, flags = {})
110:         flags = {:verbose => false, :flatten => false, :format => :console}.merge(flags)
111: 
112:         result_text = ""
113:         ddl = nil
114: 
115:         # if running in verbose mode, just use the old style print
116:         # no need for all the DDL helpers obfuscating the result
117:         if flags[:format] == :json
118:           if STDOUT.tty?
119:             result_text = JSON.pretty_generate(result)
120:           else
121:             result_text = result.to_json
122:           end
123:         else
124:           if flags[:verbose]
125:             result_text = old_rpcresults(result, flags)
126:           else
127:             [result].flatten.each do |r|
128:               begin
129:                 ddl ||= DDL.new(r.agent).action_interface(r.action.to_s)
130: 
131:                 sender = r[:sender]
132:                 status = r[:statuscode]
133:                 message = r[:statusmsg]
134:                 display = ddl[:display]
135:                 result = r[:data]
136: 
137:                 # appand the results only according to what the DDL says
138:                 case display
139:                 when :ok
140:                   if status == 0
141:                     result_text << text_for_result(sender, status, message, result, ddl)
142:                   end
143: 
144:                 when :failed
145:                   if status > 0
146:                     result_text << text_for_result(sender, status, message, result, ddl)
147:                   end
148: 
149:                 when :always
150:                   result_text << text_for_result(sender, status, message, result, ddl)
151: 
152:                 when :flatten
153:                   result_text << text_for_flattened_result(status, result)
154: 
155:                 end
156:               rescue Exception => e
157:                 # no DDL so just do the old style print unchanged for
158:                 # backward compat
159:                 result_text = old_rpcresults(result, flags)
160:               end
161:             end
162:           end
163:         end
164: 
165:         result_text
166:       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:         if ENV["COLUMNS"] && ENV["LINES"]
53:           return [ENV["COLUMNS"].to_i, ENV["LINES"].to_i]
54: 
55:         elsif ENV["TERM"] && command_in_path?("tput")
56:           return [`tput cols`.to_i, `tput lines`.to_i]
57: 
58:         elsif command_in_path?('stty')
59:           return `stty size`.scan(/\d+/).map {|s| s.to_i }
60:         else
61:           return [0, 0]
62:         end
63:       rescue
64:         [0, 0]
65:       end

Returns text representing a flattened result of only good data

[Source]

     # File lib/mcollective/rpc/helpers.rb, line 229
229:       def self.text_for_flattened_result(status, result)
230:         result_text = ""
231: 
232:         if status <= 1
233:           unless result.is_a?(String)
234:             result_text << result.pretty_inspect
235:           else
236:             result_text << result
237:           end
238:         end
239:       end

Return text representing a result

[Source]

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

[Validate]