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

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

[Source]

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

Helper to return a string in specific color

[Source]

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

Return text representing a result

[Source]

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

[Validate]