Class | MCollective::RPC::Helpers |
In: |
lib/mcollective/rpc/helpers.rb
|
Parent: | Object |
Various utilities for the RPC system
Add SimpleRPC common options
# File lib/mcollective/rpc/helpers.rb, line 278 278: def self.add_simplerpc_options(parser, options) 279: parser.separator "" 280: 281: # add SimpleRPC specific options to all clients that use our library 282: parser.on('--np', '--no-progress', 'Do not show the progress bar') do |v| 283: options[:progress_bar] = false 284: end 285: 286: parser.on('--one', '-1', 'Send request to only one discovered nodes') do |v| 287: options[:mcollective_limit_targets] = 1 288: end 289: 290: parser.on('--batch SIZE', Integer, 'Do requests in batches') do |v| 291: options[:batch_size] = v 292: end 293: 294: parser.on('--batch-sleep SECONDS', Float, 'Sleep time between batches') do |v| 295: options[:batch_sleep_time] = v 296: end 297: 298: parser.on('--limit-nodes COUNT', '--ln', 'Send request to only a subset of nodes, can be a percentage') do |v| 299: raise "Invalid limit specified: #{v} valid limits are /^\d+%*$/" unless v =~ /^\d+%*$/ 300: 301: if v =~ /^\d+$/ 302: options[:mcollective_limit_targets] = v.to_i 303: else 304: options[:mcollective_limit_targets] = v 305: end 306: end 307: 308: parser.on('--json', '-j', 'Produce JSON output') do |v| 309: options[:progress_bar] = false 310: options[:output_format] = :json 311: end 312: end
Checks in PATH returns true if the command is found
# 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
# 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"}
]
# 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
# File lib/mcollective/rpc/helpers.rb, line 226 226: def self.old_rpcresults(result, flags = {}) 227: result_text = "" 228: 229: if flags[:flatten] 230: result.each do |r| 231: if r[:statuscode] <= 1 232: data = r[:data] 233: 234: unless data.is_a?(String) 235: result_text << data.pretty_inspect 236: else 237: result_text << data 238: end 239: else 240: result_text << r.pretty_inspect 241: end 242: end 243: 244: result_text << "" 245: else 246: [result].flatten.each do |r| 247: 248: if flags[:verbose] 249: result_text << "%-40s: %s\n" % [r[:sender], r[:statusmsg]] 250: 251: if r[:statuscode] <= 1 252: r[:data].pretty_inspect.split("\n").each {|m| result_text += " #{m}"} 253: result_text << "\n\n" 254: elsif r[:statuscode] == 2 255: # dont print anything, no useful data to display 256: # past what was already shown 257: elsif r[:statuscode] == 3 258: # dont print anything, no useful data to display 259: # past what was already shown 260: elsif r[:statuscode] == 4 261: # dont print anything, no useful data to display 262: # past what was already shown 263: else 264: result_text << " #{r[:statusmsg]}" 265: end 266: else 267: unless r[:statuscode] == 0 268: result_text << "%-40s %s\n" % [r[:sender], Util.colorize(:red, r[:statusmsg])] 269: end 270: end 271: end 272: end 273: 274: result_text << "" 275: 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.
# File lib/mcollective/rpc/helpers.rb, line 87 87: def self.rpcresults(result, flags = {}) 88: flags = {:verbose => false, :flatten => false, :format => :console}.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: display = ddl[:display] 113: result = r[:data] 114: 115: # appand the results only according to what the DDL says 116: case display 117: when :ok 118: if status == 0 119: result_text << text_for_result(sender, status, message, result, ddl) 120: end 121: 122: when :failed 123: if status > 0 124: result_text << text_for_result(sender, status, message, result, ddl) 125: end 126: 127: when :always 128: result_text << text_for_result(sender, status, message, result, ddl) 129: 130: when :flatten 131: result_text << text_for_flattened_result(status, result) 132: 133: end 134: rescue Exception => e 135: # no DDL so just do the old style print unchanged for 136: # backward compat 137: result_text = old_rpcresults(result, flags) 138: end 139: end 140: end 141: end 142: 143: result_text 144: 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
# 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
# File lib/mcollective/rpc/helpers.rb, line 213 213: def self.text_for_flattened_result(status, result) 214: result_text = "" 215: 216: if status <= 1 217: unless result.is_a?(String) 218: result_text << result.pretty_inspect 219: else 220: result_text << result 221: end 222: end 223: end
Return text representing a result
# File lib/mcollective/rpc/helpers.rb, line 147 147: def self.text_for_result(sender, status, msg, result, ddl) 148: statusses = ["", 149: Util.colorize(:red, "Request Aborted"), 150: Util.colorize(:yellow, "Unknown Action"), 151: Util.colorize(:yellow, "Missing Request Data"), 152: Util.colorize(:yellow, "Invalid Request Data"), 153: Util.colorize(:red, "Unknown Request Status")] 154: 155: result_text = "%-40s %s\n" % [sender, statusses[status]] 156: result_text << " %s\n" % [Util.colorize(:yellow, msg)] unless msg == "OK" 157: 158: # only print good data, ignore data that results from failure 159: if [0, 1].include?(status) 160: if result.is_a?(Hash) 161: # figure out the lengths of the display as strings, we'll use 162: # it later to correctly justify the output 163: lengths = result.keys.map do |k| 164: begin 165: ddl[:output][k][:display_as].size 166: rescue 167: k.to_s.size 168: end 169: end 170: 171: result.keys.each do |k| 172: # get all the output fields nicely lined up with a 173: # 3 space front padding 174: begin 175: display_as = ddl[:output][k][:display_as] 176: rescue 177: display_as = k.to_s 178: end 179: 180: display_length = display_as.size 181: padding = lengths.max - display_length + 3 182: result_text << " " * padding 183: 184: result_text << "#{display_as}:" 185: 186: if [String, Numeric].include?(result[k].class) 187: lines = result[k].to_s.split("\n") 188: 189: if lines.empty? 190: result_text << "\n" 191: else 192: lines.each_with_index do |line, i| 193: i == 0 ? padtxt = " " : padtxt = " " * (padding + display_length + 2) 194: 195: result_text << "#{padtxt}#{line}\n" 196: end 197: end 198: else 199: padding = " " * (lengths.max + 5) 200: result_text << " " << result[k].pretty_inspect.split("\n").join("\n" << padding) << "\n" 201: end 202: end 203: else 204: result_text << "\n\t" + result.pretty_inspect.split("\n").join("\n\t") 205: end 206: end 207: 208: result_text << "\n" 209: result_text 210: end