Class MCollective::RPC::Client
In: lib/mcollective/rpc/client.rb
Parent: Object

The main component of the Simple RPC client system, this wraps around MCollective::Client and just brings in a lot of convention and standard approached.

Methods

Attributes

agent  [R] 
batch_mode  [R] 
batch_size  [R] 
batch_sleep_time  [R] 
client  [R] 
config  [RW] 
ddl  [R] 
discovery_method  [R] 
discovery_options  [R] 
filter  [RW] 
limit_method  [R] 
limit_seed  [R] 
limit_targets  [R] 
output_format  [R] 
progress  [RW] 
reply_to  [RW] 
stats  [R] 
timeout  [RW] 
ttl  [RW] 
verbose  [RW] 

Public Class methods

Creates a stub for a remote agent, you can pass in an options array in the flags which will then be used else it will just create a default options array with filtering enabled based on the standard command line use.

  rpc = RPC::Client.new("rpctest", :configfile => "client.cfg", :options => options)

You typically would not call this directly you‘d use MCollective::RPC#rpcclient instead which is a wrapper around this that can be used as a Mixin

[Source]

     # File lib/mcollective/rpc/client.rb, line 20
 20:       def initialize(agent, flags = {})
 21:         if flags.include?(:options)
 22:           initial_options = flags[:options]
 23: 
 24:         elsif @@initial_options
 25:           initial_options = Marshal.load(@@initial_options)
 26: 
 27:         else
 28:           oparser = MCollective::Optionparser.new({:verbose => false, :progress_bar => true, :mcollective_limit_targets => false, :batch_size => nil, :batch_sleep_time => 1}, "filter")
 29: 
 30:           initial_options = oparser.parse do |parser, opts|
 31:             if block_given?
 32:               yield(parser, opts)
 33:             end
 34: 
 35:             Helpers.add_simplerpc_options(parser, opts)
 36:           end
 37: 
 38:           @@initial_options = Marshal.dump(initial_options)
 39:         end
 40: 
 41:         @initial_options = initial_options
 42:         @stats = Stats.new
 43:         @agent = agent
 44:         @timeout = initial_options[:timeout] || 5
 45:         @verbose = initial_options[:verbose]
 46:         @filter = initial_options[:filter] || Util.empty_filter
 47:         @config = initial_options[:config]
 48:         @discovered_agents = nil
 49:         @progress = initial_options[:progress_bar]
 50:         @limit_targets = initial_options[:mcollective_limit_targets]
 51:         @limit_method = Config.instance.rpclimitmethod
 52:         @limit_seed = initial_options[:limit_seed] || nil
 53:         @output_format = initial_options[:output_format] || :console
 54:         @force_direct_request = false
 55:         @reply_to = initial_options[:reply_to]
 56:         @discovery_method = initial_options[:discovery_method] || Config.instance.default_discovery_method
 57:         @discovery_options = initial_options[:discovery_options] || []
 58:         @force_display_mode = initial_options[:force_display_mode] || false
 59: 
 60:         @batch_size = Integer(initial_options[:batch_size] || 0)
 61:         @batch_sleep_time = Float(initial_options[:batch_sleep_time] || 1)
 62:         @batch_mode = @batch_size > 0
 63: 
 64:         agent_filter agent
 65: 
 66:         @client = MCollective::Client.new(@config)
 67:         @client.options = initial_options
 68: 
 69:         @discovery_timeout = discovery_timeout
 70: 
 71:         @collective = @client.collective
 72:         @ttl = initial_options[:ttl] || Config.instance.ttl
 73: 
 74:         # if we can find a DDL for the service override
 75:         # the timeout of the client so we always magically
 76:         # wait appropriate amounts of time.
 77:         #
 78:         # We add the discovery timeout to the ddl supplied
 79:         # timeout as the discovery timeout tends to be tuned
 80:         # for local network conditions and fact source speed
 81:         # which would other wise not be accounted for and
 82:         # some results might get missed.
 83:         #
 84:         # We do this only if the timeout is the default 5
 85:         # seconds, so that users cli overrides will still
 86:         # get applied
 87:         #
 88:         # DDLs are required, failure to find a DDL is fatal
 89:         @ddl = DDL.new(agent)
 90:         @stats.ddl = @ddl
 91:         @timeout = @ddl.meta[:timeout] + @discovery_timeout if @timeout == 5
 92: 
 93:         # allows stderr and stdout to be overridden for testing
 94:         # but also for web apps that might not want a bunch of stuff
 95:         # generated to actual file handles
 96:         if initial_options[:stderr]
 97:           @stderr = initial_options[:stderr]
 98:         else
 99:           @stderr = STDERR
100:           @stderr.sync = true
101:         end
102: 
103:         if initial_options[:stdout]
104:           @stdout = initial_options[:stdout]
105:         else
106:           @stdout = STDOUT
107:           @stdout.sync = true
108:         end
109:       end

Public Instance methods

Sets the agent filter

[Source]

     # File lib/mcollective/rpc/client.rb, line 384
384:       def agent_filter(agent)
385:         @filter["agent"] << agent
386:         @filter["agent"].compact!
387:         reset
388:       end

[Source]

     # File lib/mcollective/rpc/client.rb, line 663
663:       def aggregate_reply(reply, aggregate)
664:         return nil unless aggregate
665: 
666:         aggregate.call_functions(reply)
667:         return aggregate
668:       rescue Exception => e
669:         Log.error("Failed to calculate aggregate summaries for reply from %s, calculating summaries disabled: %s: %s (%s)" % [reply[:senderid], e.backtrace.first, e.to_s, e.class])
670:         return nil
671:       end

Sets the batch size, if the size is set to 0 that will disable batch mode

[Source]

     # File lib/mcollective/rpc/client.rb, line 584
584:       def batch_size=(limit)
585:         raise "Can only set batch size if direct addressing is supported" unless Config.instance.direct_addressing
586: 
587:         @batch_size = Integer(limit)
588:         @batch_mode = @batch_size > 0
589:       end

[Source]

     # File lib/mcollective/rpc/client.rb, line 591
591:       def batch_sleep_time=(time)
592:         raise "Can only set batch sleep time if direct addressing is supported" unless Config.instance.direct_addressing
593: 
594:         @batch_sleep_time = Float(time)
595:       end

Handles traditional calls to the remote agents with full stats blocks, non blocks and everything else supported.

Other methods of calling the nodes can reuse this code by for example specifying custom options and discovery data

[Source]

     # File lib/mcollective/rpc/client.rb, line 791
791:       def call_agent(action, args, opts, disc=:auto, &block)
792:         # Handle fire and forget requests and make sure
793:         # the :process_results value is set appropriately
794:         #
795:         # specific reply-to requests should be treated like
796:         # fire and forget since the client will never get
797:         # the responses
798:         if args[:process_results] == false || @reply_to
799:           return fire_and_forget_request(action, args)
800:         else
801:           args[:process_results] = true
802:         end
803: 
804:         # Do discovery when no specific discovery array is given
805:         #
806:         # If an array is given set the force_direct_request hint that
807:         # will tell the message object to be a direct request one
808:         if disc == :auto
809:           discovered = discover
810:         else
811:           @force_direct_request = true if Config.instance.direct_addressing
812:           discovered = disc
813:         end
814: 
815:         req = new_request(action.to_s, args)
816: 
817:         message = Message.new(req, nil, {:agent => @agent, :type => :request, :collective => @collective, :filter => opts[:filter], :options => opts})
818:         message.discovered_hosts = discovered.clone
819: 
820:         results = []
821:         respcount = 0
822: 
823:         if discovered.size > 0
824:           message.type = :direct_request if @force_direct_request
825: 
826:           if @progress && !block_given?
827:             twirl = Progress.new
828:             @stdout.puts
829:             @stdout.print twirl.twirl(respcount, discovered.size)
830:           end
831: 
832:           aggregate = load_aggregate_functions(action, @ddl)
833: 
834:           @client.req(message) do |resp|
835:             respcount += 1
836: 
837:             if block_given?
838:               aggregate = process_results_with_block(action, resp, block, aggregate)
839:             else
840:               @stdout.print twirl.twirl(respcount, discovered.size) if @progress
841: 
842:               result, aggregate = process_results_without_block(resp, action, aggregate)
843: 
844:               results << result
845:             end
846:           end
847: 
848:           @stats.aggregate_summary = aggregate.summarize if aggregate
849:           @stats.aggregate_failures = aggregate.failed if aggregate
850:           @stats.client_stats = @client.stats
851:         else
852:           @stderr.print("\nNo request sent, we did not discover any nodes.")
853:         end
854: 
855:         @stats.finish_request
856: 
857:         RPC.stats(@stats)
858: 
859:         @stdout.print("\n\n") if @progress
860: 
861:         if block_given?
862:           return stats
863:         else
864:           return [results].flatten
865:         end
866:       end

Calls an agent in a way very similar to call_agent but it supports batching the queries to the network.

The result sets, stats, block handling etc is all exactly like you would expect from normal call_agent.

This is used by method_missing and works only with direct addressing mode

[Source]

     # File lib/mcollective/rpc/client.rb, line 706
706:       def call_agent_batched(action, args, opts, batch_size, sleep_time, &block)
707:         raise "Batched requests requires direct addressing" unless Config.instance.direct_addressing
708:         raise "Cannot bypass result processing for batched requests" if args[:process_results] == false
709: 
710:         batch_size = Integer(batch_size)
711:         sleep_time = Float(sleep_time)
712: 
713:         Log.debug("Calling #{agent}##{action} in batches of #{batch_size} with sleep time of #{sleep_time}")
714: 
715:         @force_direct_request = true
716: 
717:         discovered = discover
718:         results = []
719:         respcount = 0
720: 
721:         if discovered.size > 0
722:           req = new_request(action.to_s, args)
723: 
724:           aggregate = load_aggregate_functions(action, @ddl)
725: 
726:           if @progress && !block_given?
727:             twirl = Progress.new
728:             @stdout.puts
729:             @stdout.print twirl.twirl(respcount, discovered.size)
730:           end
731: 
732:           @stats.requestid = nil
733: 
734:           discovered.in_groups_of(batch_size) do |hosts, last_batch|
735:             message = Message.new(req, nil, {:agent => @agent, :type => :direct_request, :collective => @collective, :filter => opts[:filter], :options => opts})
736: 
737:             # first time round we let the Message object create a request id
738:             # we then re-use it for future requests to keep auditing sane etc
739:             @stats.requestid = message.create_reqid unless @stats.requestid
740:             message.requestid = @stats.requestid
741: 
742:             message.discovered_hosts = hosts.clone.compact
743: 
744:             @client.req(message) do |resp|
745:               respcount += 1
746: 
747:               if block_given?
748:                 aggregate = process_results_with_block(action, resp, block, aggregate)
749:               else
750:                 @stdout.print twirl.twirl(respcount, discovered.size) if @progress
751: 
752:                 result, aggregate = process_results_without_block(resp, action, aggregate)
753: 
754:                 results << result
755:               end
756:             end
757: 
758:             @stats.noresponsefrom.concat @client.stats[:noresponsefrom]
759:             @stats.responses += @client.stats[:responses]
760:             @stats.blocktime += @client.stats[:blocktime] + sleep_time
761:             @stats.totaltime += @client.stats[:totaltime]
762:             @stats.discoverytime += @client.stats[:discoverytime]
763: 
764:             sleep sleep_time unless last_batch
765:           end
766: 
767:           @stats.aggregate_summary = aggregate.summarize if aggregate
768:           @stats.aggregate_failures = aggregate.failed if aggregate
769:         else
770:           @stderr.print("\nNo request sent, we did not discover any nodes.")
771:         end
772: 
773:         @stats.finish_request
774: 
775:         RPC.stats(@stats)
776: 
777:         @stdout.print("\n") if @progress
778: 
779:         if block_given?
780:           return stats
781:         else
782:           return [results].flatten
783:         end
784:       end

Sets the class filter

[Source]

     # File lib/mcollective/rpc/client.rb, line 360
360:       def class_filter(klass)
361:         @filter["cf_class"] << klass
362:         @filter["cf_class"].compact!
363:         reset
364:       end

Sets the collective we are communicating with

[Source]

     # File lib/mcollective/rpc/client.rb, line 549
549:       def collective=(c)
550:         raise "Unknown collective #{c}" unless Config.instance.collectives.include?(c)
551: 
552:         @collective = c
553:         @client.options = options
554:         reset
555:       end

Set a compound filter

[Source]

     # File lib/mcollective/rpc/client.rb, line 398
398:       def compound_filter(filter)
399:         @filter["compound"] <<  Matcher.create_compound_callstack(filter)
400:         reset
401:       end

Constructs custom requests with custom filters and discovery data the idea is that this would be used in web applications where you might be using a cached copy of data provided by a registration agent to figure out on your own what nodes will be responding and what your filter would be.

This will help you essentially short circuit the traditional cycle of:

mc discover / call / wait for discovered nodes

by doing discovery however you like, contructing a filter and a list of nodes you expect responses from.

Other than that it will work exactly like a normal call, blocks will behave the same way, stats will be handled the same way etcetc

If you just wanted to contact one machine for example with a client that already has other filter options setup you can do:

puppet.custom_request("runonce", {}, ["your.box.com"], {:identity => "your.box.com"})

This will do runonce action on just ‘your.box.com’, no discovery will be done and after receiving just one response it will stop waiting for responses

If direct_addressing is enabled in the config file you can provide an empty hash as a filter, this will force that request to be a directly addressed request which technically does not need filters. If you try to use this mode with direct addressing disabled an exception will be raise

[Source]

     # File lib/mcollective/rpc/client.rb, line 287
287:       def custom_request(action, args, expected_agents, filter = {}, &block)
288:         validate_request(action, args)
289: 
290:         if filter == {} && !Config.instance.direct_addressing
291:           raise "Attempted to do a filterless custom_request without direct_addressing enabled, preventing unexpected call to all nodes"
292:         end
293: 
294:         @stats.reset
295: 
296:         custom_filter = Util.empty_filter
297:         custom_options = options.clone
298: 
299:         # merge the supplied filter with the standard empty one
300:         # we could just use the merge method but I want to be sure
301:         # we dont merge in stuff that isnt actually valid
302:         ["identity", "fact", "agent", "cf_class", "compound"].each do |ftype|
303:           if filter.include?(ftype)
304:             custom_filter[ftype] = [filter[ftype], custom_filter[ftype]].flatten
305:           end
306:         end
307: 
308:         # ensure that all filters at least restrict the call to the agent we're a proxy for
309:         custom_filter["agent"] << @agent unless custom_filter["agent"].include?(@agent)
310:         custom_options[:filter] = custom_filter
311: 
312:         # Fake out the stats discovery would have put there
313:         @stats.discovered_agents([expected_agents].flatten)
314: 
315:         # Handle fire and forget requests
316:         #
317:         # If a specific reply-to was set then from the client perspective this should
318:         # be a fire and forget request too since no response will ever reach us - it
319:         # will go to the reply-to destination
320:         if args[:process_results] == false || @reply_to
321:           return fire_and_forget_request(action, args, custom_filter)
322:         end
323: 
324:         # Now do a call pretty much exactly like in method_missing except with our own
325:         # options and discovery magic
326:         if block_given?
327:           call_agent(action, args, custom_options, [expected_agents].flatten) do |r|
328:             block.call(r)
329:           end
330:         else
331:           call_agent(action, args, custom_options, [expected_agents].flatten)
332:         end
333:       end

Disconnects cleanly from the middleware

[Source]

     # File lib/mcollective/rpc/client.rb, line 112
112:       def disconnect
113:         @client.disconnect
114:       end

Does discovery based on the filters set, if a discovery was previously done return that else do a new discovery.

Alternatively if identity filters are given and none of them are regular expressions then just use the provided data as discovered data, avoiding discovery

Discovery can be forced if direct_addressing is enabled by passing in an array of nodes with :nodes or JSON data like those produced by mcollective RPC JSON output using :json

Will show a message indicating its doing discovery if running verbose or if the :verbose flag is passed in.

Use reset to force a new discovery

[Source]

     # File lib/mcollective/rpc/client.rb, line 430
430:       def discover(flags={})
431:         flags.keys.each do |key|
432:           raise "Unknown option #{key} passed to discover" unless [:verbose, :hosts, :nodes, :json].include?(key)
433:         end
434: 
435:         flags.include?(:verbose) ? verbose = flags[:verbose] : verbose = @verbose
436: 
437:         verbose = false unless @output_format == :console
438: 
439:         # flags[:nodes] and flags[:hosts] are the same thing, we should never have
440:         # allowed :hosts as that was inconsistent with the established terminology
441:         flags[:nodes] = flags.delete(:hosts) if flags.include?(:hosts)
442: 
443:         reset if flags[:nodes] || flags[:json]
444: 
445:         unless @discovered_agents
446:           # if either hosts or JSON is supplied try to figure out discovery data from there
447:           # if direct_addressing is not enabled this is a critical error as the user might
448:           # not have supplied filters so raise an exception
449:           if flags[:nodes] || flags[:json]
450:             raise "Can only supply discovery data if direct_addressing is enabled" unless Config.instance.direct_addressing
451: 
452:             hosts = []
453: 
454:             if flags[:nodes]
455:               hosts = Helpers.extract_hosts_from_array(flags[:nodes])
456:             elsif flags[:json]
457:               hosts = Helpers.extract_hosts_from_json(flags[:json])
458:             end
459: 
460:             raise "Could not find any hosts in discovery data provided" if hosts.empty?
461: 
462:             @discovered_agents = hosts
463:             @force_direct_request = true
464: 
465:           # if an identity filter is supplied and it is all strings no regex we can use that
466:           # as discovery data, technically the identity filter is then redundant if we are
467:           # in direct addressing mode and we could empty it out but this use case should
468:           # only really be for a few -I's on the CLI
469:           #
470:           # For safety we leave the filter in place for now, that way we can support this
471:           # enhancement also in broadcast mode.
472:           #
473:           # This is only needed for the 'mc' discovery method, other methods might change
474:           # the concept of identity to mean something else so we should pass the full
475:           # identity filter to them
476:           elsif options[:filter]["identity"].size > 0 && @discovery_method == "mc"
477:             regex_filters = options[:filter]["identity"].select{|i| i.match("^\/")}.size
478: 
479:             if regex_filters == 0
480:               @discovered_agents = options[:filter]["identity"].clone
481:               @force_direct_request = true if Config.instance.direct_addressing
482:             end
483:           end
484:         end
485: 
486:         # All else fails we do it the hard way using a traditional broadcast
487:         unless @discovered_agents
488:           @stats.time_discovery :start
489: 
490:           @client.options = options
491: 
492:           # if compound filters are used the only real option is to use the mc
493:           # discovery plugin since its the only capable of using data queries etc
494:           # and we do not want to degrade that experience just to allow compounds
495:           # on other discovery plugins the UX would be too bad raising complex sets
496:           # of errors etc.
497:           @client.discoverer.force_discovery_method_by_filter(options[:filter])
498: 
499:           if verbose
500:             actual_timeout = @client.discoverer.discovery_timeout(discovery_timeout, options[:filter])
501: 
502:             if actual_timeout > 0
503:               @stderr.print("Discovering hosts using the %s method for %d second(s) .... " % [@client.discoverer.discovery_method, actual_timeout])
504:             else
505:               @stderr.print("Discovering hosts using the %s method .... " % [@client.discoverer.discovery_method])
506:             end
507:           end
508: 
509:           # if the requested limit is a pure number and not a percent
510:           # and if we're configured to use the first found hosts as the
511:           # limit method then pass in the limit thus minimizing the amount
512:           # of work we do in the discover phase and speeding it up significantly
513:           if @limit_method == :first and @limit_targets.is_a?(Fixnum)
514:             @discovered_agents = @client.discover(@filter, discovery_timeout, @limit_targets)
515:           else
516:             @discovered_agents = @client.discover(@filter, discovery_timeout)
517:           end
518: 
519:           @stderr.puts(@discovered_agents.size) if verbose
520: 
521:           @force_direct_request = @client.discoverer.force_direct_mode?
522: 
523:           @stats.time_discovery :end
524:         end
525: 
526:         @stats.discovered_agents(@discovered_agents)
527:         RPC.discovered(@discovered_agents)
528: 
529:         @discovered_agents
530:       end

[Source]

     # File lib/mcollective/rpc/client.rb, line 340
340:       def discovery_method=(method)
341:         @discovery_method = method
342: 
343:         if @initial_options[:discovery_options]
344:           @discovery_options = @initial_options[:discovery_options]
345:         else
346:           @discovery_options.clear
347:         end
348: 
349:         @client.options = options
350:         @discovery_timeout = discovery_timeout
351:         reset
352:       end

[Source]

     # File lib/mcollective/rpc/client.rb, line 354
354:       def discovery_options=(options)
355:         @discovery_options = [options].flatten
356:         reset
357:       end

[Source]

     # File lib/mcollective/rpc/client.rb, line 335
335:       def discovery_timeout
336:         return @initial_options[:disctimeout] if @initial_options[:disctimeout]
337:         return @client.discoverer.ddl.meta[:timeout]
338:       end

Sets the fact filter

[Source]

     # File lib/mcollective/rpc/client.rb, line 367
367:       def fact_filter(fact, value=nil, operator="=")
368:         return if fact.nil?
369:         return if fact == false
370: 
371:         if value.nil?
372:           parsed = Util.parse_fact_string(fact)
373:           @filter["fact"] << parsed unless parsed == false
374:         else
375:           parsed = Util.parse_fact_string("#{fact}#{operator}#{value}")
376:           @filter["fact"] << parsed unless parsed == false
377:         end
378: 
379:         @filter["fact"].compact!
380:         reset
381:       end

for requests that do not care for results just return the request id and don‘t do any of the response processing.

We send the :process_results flag with to the nodes so they can make decisions based on that.

Should only be called via method_missing

[Source]

     # File lib/mcollective/rpc/client.rb, line 686
686:       def fire_and_forget_request(action, args, filter=nil)
687:         validate_request(action, args)
688: 
689:         req = new_request(action.to_s, args)
690: 
691:         filter = options[:filter] unless filter
692: 
693:         message = Message.new(req, nil, {:agent => @agent, :type => :request, :collective => @collective, :filter => filter, :options => options})
694:         message.reply_to = @reply_to if @reply_to
695: 
696:         return @client.sendreq(message, nil)
697:       end

Returns help for an agent if a DDL was found

[Source]

     # File lib/mcollective/rpc/client.rb, line 117
117:       def help(template)
118:         @ddl.help(template)
119:       end

Sets the identity filter

[Source]

     # File lib/mcollective/rpc/client.rb, line 391
391:       def identity_filter(identity)
392:         @filter["identity"] << identity
393:         @filter["identity"].compact!
394:         reset
395:       end

Sets and sanity check the limit_method variable used to determine how to limit targets if limit_targets is set

[Source]

     # File lib/mcollective/rpc/client.rb, line 575
575:       def limit_method=(method)
576:         method = method.to_sym unless method.is_a?(Symbol)
577: 
578:         raise "Unknown limit method #{method} must be :random or :first" unless [:random, :first].include?(method)
579: 
580:         @limit_method = method
581:       end

Sets and sanity checks the limit_targets variable used to restrict how many nodes we‘ll target

[Source]

     # File lib/mcollective/rpc/client.rb, line 559
559:       def limit_targets=(limit)
560:         if limit.is_a?(String)
561:           raise "Invalid limit specified: #{limit} valid limits are /^\d+%*$/" unless limit =~ /^\d+%*$/
562: 
563:           begin
564:             @limit_targets = Integer(limit)
565:           rescue
566:             @limit_targets = limit
567:           end
568:         else
569:           @limit_targets = Integer(limit)
570:         end
571:       end

[Source]

     # File lib/mcollective/rpc/client.rb, line 652
652:       def load_aggregate_functions(action, ddl)
653:         return nil unless ddl
654:         return nil unless ddl.action_interface(action).keys.include?(:aggregate)
655: 
656:         return Aggregate.new(ddl.action_interface(action))
657: 
658:       rescue => e
659:         Log.error("Failed to load aggregate functions, calculating summaries disabled: %s: %s (%s)" % [e.backtrace.first, e.to_s, e.class])
660:         return nil
661:       end

Magic handler to invoke remote methods

Once the stub is created using the constructor or the RPC#rpcclient helper you can call remote actions easily:

  ret = rpc.echo(:msg => "hello world")

This will call the ‘echo’ action of the ‘rpctest’ agent and return the result as an array, the array will be a simplified result set from the usual full MCollective::Client#req with additional error codes and error text:

{

  :sender => "remote.box.com",
  :statuscode => 0,
  :statusmsg => "OK",
  :data => "hello world"

}

If :statuscode is 0 then everything went find, if it‘s 1 then you supplied the correct arguments etc but the request could not be completed, you‘ll find a human parsable reason in :statusmsg then.

Codes 2 to 5 maps directly to UnknownRPCAction, MissingRPCData, InvalidRPCData and UnknownRPCError see below for a description of those, in each case :statusmsg would be the reason for failure.

To get access to the full result of the MCollective::Client#req calls you can pass in a block:

  rpc.echo(:msg => "hello world") do |resp|
     pp resp
  end

In this case resp will the result from MCollective::Client#req. Instead of returning simple text and codes as above you‘ll also need to handle the following exceptions:

UnknownRPCAction - There is no matching action on the agent MissingRPCData - You did not supply all the needed parameters for the action InvalidRPCData - The data you did supply did not pass validation UnknownRPCError - Some other error prevented the agent from running

During calls a progress indicator will be shown of how many results we‘ve received against how many nodes were discovered, you can disable this by setting progress to false:

  rpc.progress = false

This supports a 2nd mode where it will send the SimpleRPC request and never handle the responses. It‘s a bit like UDP, it sends the request with the filter attached and you only get back the requestid, you have no indication about results.

You can invoke this using:

  puts rpc.echo(:process_results => false)

This will output just the request id.

Batched processing is supported:

  printrpc rpc.ping(:batch_size => 5)

This will do everything exactly as normal but communicate to only 5 agents at a time

[Source]

     # File lib/mcollective/rpc/client.rb, line 222
222:       def method_missing(method_name, *args, &block)
223:         # set args to an empty hash if nothings given
224:         args = args[0]
225:         args = {} if args.nil?
226: 
227:         action = method_name.to_s
228: 
229:         @stats.reset
230: 
231:         validate_request(action, args)
232: 
233:         # if a global batch size is set just use that else set it
234:         # in the case that it was passed as an argument
235:         batch_mode = args.include?(:batch_size) || @batch_mode
236:         batch_size = args.delete(:batch_size) || @batch_size
237:         batch_sleep_time = args.delete(:batch_sleep_time) || @batch_sleep_time
238: 
239:         # if we were given a batch_size argument thats 0 and batch_mode was
240:         # determined to be on via global options etc this will allow a batch_size
241:         # of 0 to disable or batch_mode for this call only
242:         batch_mode = (batch_mode && Integer(batch_size) > 0)
243: 
244:         # Handle single target requests by doing discovery and picking
245:         # a random node.  Then do a custom request specifying a filter
246:         # that will only match the one node.
247:         if @limit_targets
248:           target_nodes = pick_nodes_from_discovered(@limit_targets)
249:           Log.debug("Picked #{target_nodes.join(',')} as limited target(s)")
250: 
251:           custom_request(action, args, target_nodes, {"identity" => /^(#{target_nodes.join('|')})$/}, &block)
252:         elsif batch_mode
253:           call_agent_batched(action, args, options, batch_size, batch_sleep_time, &block)
254:         else
255:           call_agent(action, args, options, :auto, &block)
256:         end
257:       end

Creates a suitable request hash for the SimpleRPC agent.

You‘d use this if you ever wanted to take care of sending requests on your own - perhaps via Client#sendreq if you didn‘t care for responses.

In that case you can just do:

  msg = your_rpc.new_request("some_action", :foo => :bar)
  filter = your_rpc.filter

  your_rpc.client.sendreq(msg, msg[:agent], filter)

This will send a SimpleRPC request to the action some_action with arguments :foo = :bar, it will return immediately and you will have no indication at all if the request was receieved or not

Clearly the use of this technique should be limited and done only if your code requires such a thing

[Source]

     # File lib/mcollective/rpc/client.rb, line 140
140:       def new_request(action, data)
141:         callerid = PluginManager["security_plugin"].callerid
142: 
143:         raise 'callerid received from security plugin is not valid' unless PluginManager["security_plugin"].valid_callerid?(callerid)
144: 
145:         {:agent  => @agent,
146:          :action => action,
147:          :caller => callerid,
148:          :data   => data}
149:       end

Provides a normal options hash like you would get from Optionparser

[Source]

     # File lib/mcollective/rpc/client.rb, line 534
534:       def options
535:         {:disctimeout => @discovery_timeout,
536:          :timeout => @timeout,
537:          :verbose => @verbose,
538:          :filter => @filter,
539:          :collective => @collective,
540:          :output_format => @output_format,
541:          :ttl => @ttl,
542:          :discovery_method => @discovery_method,
543:          :discovery_options => @discovery_options,
544:          :force_display_mode => @force_display_mode,
545:          :config => @config}
546:       end

Pick a number of nodes from the discovered nodes

The count should be a string that can be either just a number or a percentage like 10%

It will select nodes from the discovered list based on the rpclimitmethod configuration option which can be either :first or anything else

  - :first would be a simple way to do a distance based
    selection
  - anything else will just pick one at random
  - if random chosen, and batch-seed set, then set srand
    for the generator, and reset afterwards

[Source]

     # File lib/mcollective/rpc/client.rb, line 611
611:       def pick_nodes_from_discovered(count)
612:         if count =~ /%$/
613:           pct = Integer((discover.size * (count.to_f / 100)))
614:           pct == 0 ? count = 1 : count = pct
615:         else
616:           count = Integer(count)
617:         end
618: 
619:         return discover if discover.size <= count
620: 
621:         result = []
622: 
623:         if @limit_method == :first
624:           return discover[0, count]
625:         else
626:           # we delete from the discovered list because we want
627:           # to be sure there is no chance that the same node will
628:           # be randomly picked twice.  So we have to clone the
629:           # discovered list else this method will only ever work
630:           # once per discovery cycle and not actually return the
631:           # right nodes.
632:           haystack = discover.clone
633: 
634:           if @limit_seed
635:             haystack.sort!
636:             srand(@limit_seed)
637:           end
638: 
639:           count.times do
640:             rnd = rand(haystack.size)
641:             result << haystack.delete_at(rnd)
642:           end
643: 
644:           # Reset random number generator to fresh seed
645:           # As our seed from options is most likely short
646:           srand if @limit_seed
647:         end
648: 
649:         [result].flatten
650:       end

process client requests by calling a block on each result in this mode we do not do anything fancy with the result objects and we raise exceptions if there are problems with the data

[Source]

     # File lib/mcollective/rpc/client.rb, line 891
891:       def process_results_with_block(action, resp, block, aggregate)
892:         @stats.node_responded(resp[:senderid])
893: 
894:         result = rpc_result_from_reply(@agent, action, resp)
895:         aggregate = aggregate_reply(result, aggregate) if aggregate
896: 
897:         if resp[:body][:statuscode] == 0 || resp[:body][:statuscode] == 1
898:           @stats.ok if resp[:body][:statuscode] == 0
899:           @stats.fail if resp[:body][:statuscode] == 1
900:           @stats.time_block_execution :start
901: 
902:           case block.arity
903:             when 1
904:               block.call(resp)
905:             when 2
906:               block.call(resp, result)
907:           end
908: 
909:           @stats.time_block_execution :end
910:         else
911:           @stats.fail
912: 
913:           case resp[:body][:statuscode]
914:             when 2
915:               raise UnknownRPCAction, resp[:body][:statusmsg]
916:             when 3
917:               raise MissingRPCData, resp[:body][:statusmsg]
918:             when 4
919:               raise InvalidRPCData, resp[:body][:statusmsg]
920:             when 5
921:               raise UnknownRPCError, resp[:body][:statusmsg]
922:           end
923:         end
924: 
925:         return aggregate
926:       end

Handles result sets that has no block associated, sets fails and ok in the stats object and return a hash of the response to send to the caller

[Source]

     # File lib/mcollective/rpc/client.rb, line 871
871:       def process_results_without_block(resp, action, aggregate)
872:         @stats.node_responded(resp[:senderid])
873: 
874:         result = rpc_result_from_reply(@agent, action, resp)
875:         aggregate = aggregate_reply(result, aggregate) if aggregate
876: 
877:         if resp[:body][:statuscode] == 0 || resp[:body][:statuscode] == 1
878:           @stats.ok if resp[:body][:statuscode] == 0
879:           @stats.fail if resp[:body][:statuscode] == 1
880:         else
881:           @stats.fail
882:         end
883: 
884:         [result, aggregate]
885:       end

Resets various internal parts of the class, most importantly it clears out the cached discovery

[Source]

     # File lib/mcollective/rpc/client.rb, line 405
405:       def reset
406:         @discovered_agents = nil
407:       end

Reet the filter to an empty one

[Source]

     # File lib/mcollective/rpc/client.rb, line 410
410:       def reset_filter
411:         @filter = Util.empty_filter
412:         agent_filter @agent
413:       end

[Source]

     # File lib/mcollective/rpc/client.rb, line 673
673:       def rpc_result_from_reply(agent, action, reply)
674:         Result.new(agent, action, {:sender => reply[:senderid], :statuscode => reply[:body][:statuscode],
675:                                    :statusmsg => reply[:body][:statusmsg], :data => reply[:body][:data]})
676:       end

For the provided arguments and action the input arguments get modified by supplying any defaults provided in the DDL for arguments that were not supplied in the request

We then pass the modified arguments to the DDL for validation

[Source]

     # File lib/mcollective/rpc/client.rb, line 156
156:       def validate_request(action, args)
157:         raise "No DDL found for agent %s cannot validate inputs" % @agent unless @ddl
158: 
159:         @ddl.set_default_input_arguments(action, args)
160:         @ddl.validate_rpc_request(action, args)
161:       end

[Validate]