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: 
 43:         @config = initial_options[:config]
 44:         @client = MCollective::Client.new(@config)
 45:         @client.options = initial_options
 46: 
 47:         @stats = Stats.new
 48:         @agent = agent
 49:         @timeout = initial_options[:timeout] || 5
 50:         @verbose = initial_options[:verbose]
 51:         @filter = initial_options[:filter] || Util.empty_filter
 52:         @discovered_agents = nil
 53:         @progress = initial_options[:progress_bar]
 54:         @limit_targets = initial_options[:mcollective_limit_targets]
 55:         @limit_method = Config.instance.rpclimitmethod
 56:         @limit_seed = initial_options[:limit_seed] || nil
 57:         @output_format = initial_options[:output_format] || :console
 58:         @force_direct_request = false
 59:         @reply_to = initial_options[:reply_to]
 60:         @discovery_method = initial_options[:discovery_method] || Config.instance.default_discovery_method
 61:         @discovery_options = initial_options[:discovery_options] || []
 62:         @force_display_mode = initial_options[:force_display_mode] || false
 63: 
 64:         @batch_size = Integer(initial_options[:batch_size] || 0)
 65:         @batch_sleep_time = Float(initial_options[:batch_sleep_time] || 1)
 66:         @batch_mode = @batch_size > 0
 67: 
 68:         agent_filter agent
 69: 
 70:         @discovery_timeout = @initial_options.fetch(:disctimeout, nil)
 71: 
 72:         @collective = @client.collective
 73:         @ttl = initial_options[:ttl] || Config.instance.ttl
 74: 
 75:         # if we can find a DDL for the service override
 76:         # the timeout of the client so we always magically
 77:         # wait appropriate amounts of time.
 78:         #
 79:         # We add the discovery timeout to the ddl supplied
 80:         # timeout as the discovery timeout tends to be tuned
 81:         # for local network conditions and fact source speed
 82:         # which would other wise not be accounted for and
 83:         # some results might get missed.
 84:         #
 85:         # We do this only if the timeout is the default 5
 86:         # seconds, so that users cli overrides will still
 87:         # get applied
 88:         #
 89:         # DDLs are required, failure to find a DDL is fatal
 90:         @ddl = DDL.new(agent)
 91:         @stats.ddl = @ddl
 92:         @timeout = @ddl.meta[:timeout] + discovery_timeout if @timeout == 5
 93: 
 94:         # allows stderr and stdout to be overridden for testing
 95:         # but also for web apps that might not want a bunch of stuff
 96:         # generated to actual file handles
 97:         if initial_options[:stderr]
 98:           @stderr = initial_options[:stderr]
 99:         else
100:           @stderr = STDERR
101:           @stderr.sync = true
102:         end
103: 
104:         if initial_options[:stdout]
105:           @stdout = initial_options[:stdout]
106:         else
107:           @stdout = STDOUT
108:           @stdout.sync = true
109:         end
110:       end

Public Instance methods

Sets the agent filter

[Source]

     # File lib/mcollective/rpc/client.rb, line 401
401:       def agent_filter(agent)
402:         @filter["agent"] << agent
403:         @filter["agent"].compact!
404:         reset
405:       end

[Source]

     # File lib/mcollective/rpc/client.rb, line 680
680:       def aggregate_reply(reply, aggregate)
681:         return nil unless aggregate
682: 
683:         aggregate.call_functions(reply)
684:         return aggregate
685:       rescue Exception => e
686:         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])
687:         return nil
688:       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 601
601:       def batch_size=(limit)
602:         raise "Can only set batch size if direct addressing is supported" unless Config.instance.direct_addressing
603: 
604:         @batch_size = Integer(limit)
605:         @batch_mode = @batch_size > 0
606:       end

[Source]

     # File lib/mcollective/rpc/client.rb, line 608
608:       def batch_sleep_time=(time)
609:         raise "Can only set batch sleep time if direct addressing is supported" unless Config.instance.direct_addressing
610: 
611:         @batch_sleep_time = Float(time)
612:       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 808
808:       def call_agent(action, args, opts, disc=:auto, &block)
809:         # Handle fire and forget requests and make sure
810:         # the :process_results value is set appropriately
811:         #
812:         # specific reply-to requests should be treated like
813:         # fire and forget since the client will never get
814:         # the responses
815:         if args[:process_results] == false || @reply_to
816:           return fire_and_forget_request(action, args)
817:         else
818:           args[:process_results] = true
819:         end
820: 
821:         # Do discovery when no specific discovery array is given
822:         #
823:         # If an array is given set the force_direct_request hint that
824:         # will tell the message object to be a direct request one
825:         if disc == :auto
826:           discovered = discover
827:         else
828:           @force_direct_request = true if Config.instance.direct_addressing
829:           discovered = disc
830:         end
831: 
832:         req = new_request(action.to_s, args)
833: 
834:         message = Message.new(req, nil, {:agent => @agent, :type => :request, :collective => @collective, :filter => opts[:filter], :options => opts})
835:         message.discovered_hosts = discovered.clone
836: 
837:         results = []
838:         respcount = 0
839: 
840:         if discovered.size > 0
841:           message.type = :direct_request if @force_direct_request
842: 
843:           if @progress && !block_given?
844:             twirl = Progress.new
845:             @stdout.puts
846:             @stdout.print twirl.twirl(respcount, discovered.size)
847:           end
848: 
849:           aggregate = load_aggregate_functions(action, @ddl)
850: 
851:           @client.req(message) do |resp|
852:             respcount += 1
853: 
854:             if block_given?
855:               aggregate = process_results_with_block(action, resp, block, aggregate)
856:             else
857:               @stdout.print twirl.twirl(respcount, discovered.size) if @progress
858: 
859:               result, aggregate = process_results_without_block(resp, action, aggregate)
860: 
861:               results << result
862:             end
863:           end
864: 
865:           @stats.aggregate_summary = aggregate.summarize if aggregate
866:           @stats.aggregate_failures = aggregate.failed if aggregate
867:           @stats.client_stats = @client.stats
868:         else
869:           @stderr.print("\nNo request sent, we did not discover any nodes.")
870:         end
871: 
872:         @stats.finish_request
873: 
874:         RPC.stats(@stats)
875: 
876:         @stdout.print("\n\n") if @progress
877: 
878:         if block_given?
879:           return stats
880:         else
881:           return [results].flatten
882:         end
883:       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 723
723:       def call_agent_batched(action, args, opts, batch_size, sleep_time, &block)
724:         raise "Batched requests requires direct addressing" unless Config.instance.direct_addressing
725:         raise "Cannot bypass result processing for batched requests" if args[:process_results] == false
726: 
727:         batch_size = Integer(batch_size)
728:         sleep_time = Float(sleep_time)
729: 
730:         Log.debug("Calling #{agent}##{action} in batches of #{batch_size} with sleep time of #{sleep_time}")
731: 
732:         @force_direct_request = true
733: 
734:         discovered = discover
735:         results = []
736:         respcount = 0
737: 
738:         if discovered.size > 0
739:           req = new_request(action.to_s, args)
740: 
741:           aggregate = load_aggregate_functions(action, @ddl)
742: 
743:           if @progress && !block_given?
744:             twirl = Progress.new
745:             @stdout.puts
746:             @stdout.print twirl.twirl(respcount, discovered.size)
747:           end
748: 
749:           @stats.requestid = nil
750: 
751:           discovered.in_groups_of(batch_size) do |hosts, last_batch|
752:             message = Message.new(req, nil, {:agent => @agent, :type => :direct_request, :collective => @collective, :filter => opts[:filter], :options => opts})
753: 
754:             # first time round we let the Message object create a request id
755:             # we then re-use it for future requests to keep auditing sane etc
756:             @stats.requestid = message.create_reqid unless @stats.requestid
757:             message.requestid = @stats.requestid
758: 
759:             message.discovered_hosts = hosts.clone.compact
760: 
761:             @client.req(message) do |resp|
762:               respcount += 1
763: 
764:               if block_given?
765:                 aggregate = process_results_with_block(action, resp, block, aggregate)
766:               else
767:                 @stdout.print twirl.twirl(respcount, discovered.size) if @progress
768: 
769:                 result, aggregate = process_results_without_block(resp, action, aggregate)
770: 
771:                 results << result
772:               end
773:             end
774: 
775:             @stats.noresponsefrom.concat @client.stats[:noresponsefrom]
776:             @stats.responses += @client.stats[:responses]
777:             @stats.blocktime += @client.stats[:blocktime] + sleep_time
778:             @stats.totaltime += @client.stats[:totaltime]
779:             @stats.discoverytime += @client.stats[:discoverytime]
780: 
781:             sleep sleep_time unless last_batch
782:           end
783: 
784:           @stats.aggregate_summary = aggregate.summarize if aggregate
785:           @stats.aggregate_failures = aggregate.failed if aggregate
786:         else
787:           @stderr.print("\nNo request sent, we did not discover any nodes.")
788:         end
789: 
790:         @stats.finish_request
791: 
792:         RPC.stats(@stats)
793: 
794:         @stdout.print("\n") if @progress
795: 
796:         if block_given?
797:           return stats
798:         else
799:           return [results].flatten
800:         end
801:       end

Sets the class filter

[Source]

     # File lib/mcollective/rpc/client.rb, line 377
377:       def class_filter(klass)
378:         @filter["cf_class"] << klass
379:         @filter["cf_class"].compact!
380:         reset
381:       end

Sets the collective we are communicating with

[Source]

     # File lib/mcollective/rpc/client.rb, line 566
566:       def collective=(c)
567:         raise "Unknown collective #{c}" unless Config.instance.collectives.include?(c)
568: 
569:         @collective = c
570:         @client.options = options
571:         reset
572:       end

Set a compound filter

[Source]

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

Disconnects cleanly from the middleware

[Source]

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

Sets the discovery method. If we change the method there are a number of steps to take:

 - set the new method
 - if discovery options were provided, re-set those to initially
   provided ones else clear them as they might now apply to a
   different provider
 - update the client options so it knows there is a new discovery
   method in force
 - reset discovery data forcing a discover on the next request

The remaining item is the discovery timeout, we leave that as is since that is the user supplied timeout either via initial options or via specifically setting it on the client.

[Source]

     # File lib/mcollective/rpc/client.rb, line 357
357:       def discovery_method=(method)
358:         @discovery_method = method
359: 
360:         if @initial_options[:discovery_options]
361:           @discovery_options = @initial_options[:discovery_options]
362:         else
363:           @discovery_options.clear
364:         end
365: 
366:         @client.options = options
367: 
368:         reset
369:       end

[Source]

     # File lib/mcollective/rpc/client.rb, line 371
371:       def discovery_options=(options)
372:         @discovery_options = [options].flatten
373:         reset
374:       end

[Source]

     # File lib/mcollective/rpc/client.rb, line 324
324:       def discovery_timeout
325:         return @discovery_timeout if @discovery_timeout
326:         return @client.discoverer.ddl.meta[:timeout]
327:       end

[Source]

     # File lib/mcollective/rpc/client.rb, line 329
329:       def discovery_timeout=(timeout)
330:         @discovery_timeout = Float(timeout)
331: 
332:         # we calculate the overall timeout from the DDL of the agent and
333:         # the supplied discovery timeout unless someone specifically
334:         # specifies a timeout to the constructor
335:         #
336:         # But if we also then specifically set a discovery_timeout on the
337:         # agent that has to override the supplied timeout so we then
338:         # calculate a correct timeout based on DDL timeout and the
339:         # supplied discovery timeout
340:         @timeout = @ddl.meta[:timeout] + discovery_timeout
341:       end

Sets the fact filter

[Source]

     # File lib/mcollective/rpc/client.rb, line 384
384:       def fact_filter(fact, value=nil, operator="=")
385:         return if fact.nil?
386:         return if fact == false
387: 
388:         if value.nil?
389:           parsed = Util.parse_fact_string(fact)
390:           @filter["fact"] << parsed unless parsed == false
391:         else
392:           parsed = Util.parse_fact_string("#{fact}#{operator}#{value}")
393:           @filter["fact"] << parsed unless parsed == false
394:         end
395: 
396:         @filter["fact"].compact!
397:         reset
398:       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 703
703:       def fire_and_forget_request(action, args, filter=nil)
704:         @ddl.validate_rpc_request(action, args) if @ddl
705: 
706:         req = new_request(action.to_s, args)
707: 
708:         filter = options[:filter] unless filter
709: 
710:         message = Message.new(req, nil, {:agent => @agent, :type => :request, :collective => @collective, :filter => filter, :options => options})
711:         message.reply_to = @reply_to if @reply_to
712: 
713:         return @client.sendreq(message, nil)
714:       end

Returns help for an agent if a DDL was found

[Source]

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

Sets the identity filter

[Source]

     # File lib/mcollective/rpc/client.rb, line 408
408:       def identity_filter(identity)
409:         @filter["identity"] << identity
410:         @filter["identity"].compact!
411:         reset
412:       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 592
592:       def limit_method=(method)
593:         method = method.to_sym unless method.is_a?(Symbol)
594: 
595:         raise "Unknown limit method #{method} must be :random or :first" unless [:random, :first].include?(method)
596: 
597:         @limit_method = method
598:       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 576
576:       def limit_targets=(limit)
577:         if limit.is_a?(String)
578:           raise "Invalid limit specified: #{limit} valid limits are /^\d+%*$/" unless limit =~ /^\d+%*$/
579: 
580:           begin
581:             @limit_targets = Integer(limit)
582:           rescue
583:             @limit_targets = limit
584:           end
585:         else
586:           @limit_targets = Integer(limit)
587:         end
588:       end

[Source]

     # File lib/mcollective/rpc/client.rb, line 669
669:       def load_aggregate_functions(action, ddl)
670:         return nil unless ddl
671:         return nil unless ddl.action_interface(action).keys.include?(:aggregate)
672: 
673:         return Aggregate.new(ddl.action_interface(action))
674: 
675:       rescue => e
676:         Log.error("Failed to load aggregate functions, calculating summaries disabled: %s: %s (%s)" % [e.backtrace.first, e.to_s, e.class])
677:         return nil
678:       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 211
211:       def method_missing(method_name, *args, &block)
212:         # set args to an empty hash if nothings given
213:         args = args[0]
214:         args = {} if args.nil?
215: 
216:         action = method_name.to_s
217: 
218:         @stats.reset
219: 
220:         @ddl.validate_rpc_request(action, args) if @ddl
221: 
222:         # if a global batch size is set just use that else set it
223:         # in the case that it was passed as an argument
224:         batch_mode = args.include?(:batch_size) || @batch_mode
225:         batch_size = args.delete(:batch_size) || @batch_size
226:         batch_sleep_time = args.delete(:batch_sleep_time) || @batch_sleep_time
227: 
228:         # if we were given a batch_size argument thats 0 and batch_mode was
229:         # determined to be on via global options etc this will allow a batch_size
230:         # of 0 to disable or batch_mode for this call only
231:         batch_mode = (batch_mode && Integer(batch_size) > 0)
232: 
233:         # Handle single target requests by doing discovery and picking
234:         # a random node.  Then do a custom request specifying a filter
235:         # that will only match the one node.
236:         if @limit_targets
237:           target_nodes = pick_nodes_from_discovered(@limit_targets)
238:           Log.debug("Picked #{target_nodes.join(',')} as limited target(s)")
239: 
240:           custom_request(action, args, target_nodes, {"identity" => /^(#{target_nodes.join('|')})$/}, &block)
241:         elsif batch_mode
242:           call_agent_batched(action, args, options, batch_size, batch_sleep_time, &block)
243:         else
244:           call_agent(action, args, options, :auto, &block)
245:         end
246:       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 141
141:       def new_request(action, data)
142:         callerid = PluginManager["security_plugin"].callerid
143: 
144:         raise 'callerid received from security plugin is not valid' unless PluginManager["security_plugin"].valid_callerid?(callerid)
145: 
146:         {:agent  => @agent,
147:          :action => action,
148:          :caller => callerid,
149:          :data   => data}
150:       end

Provides a normal options hash like you would get from Optionparser

[Source]

     # File lib/mcollective/rpc/client.rb, line 551
551:       def options
552:         {:disctimeout => discovery_timeout,
553:          :timeout => @timeout,
554:          :verbose => @verbose,
555:          :filter => @filter,
556:          :collective => @collective,
557:          :output_format => @output_format,
558:          :ttl => @ttl,
559:          :discovery_method => @discovery_method,
560:          :discovery_options => @discovery_options,
561:          :force_display_mode => @force_display_mode,
562:          :config => @config}
563:       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 628
628:       def pick_nodes_from_discovered(count)
629:         if count =~ /%$/
630:           pct = Integer((discover.size * (count.to_f / 100)))
631:           pct == 0 ? count = 1 : count = pct
632:         else
633:           count = Integer(count)
634:         end
635: 
636:         return discover if discover.size <= count
637: 
638:         result = []
639: 
640:         if @limit_method == :first
641:           return discover[0, count]
642:         else
643:           # we delete from the discovered list because we want
644:           # to be sure there is no chance that the same node will
645:           # be randomly picked twice.  So we have to clone the
646:           # discovered list else this method will only ever work
647:           # once per discovery cycle and not actually return the
648:           # right nodes.
649:           haystack = discover.clone
650: 
651:           if @limit_seed
652:             haystack.sort!
653:             srand(@limit_seed)
654:           end
655: 
656:           count.times do
657:             rnd = rand(haystack.size)
658:             result << haystack.delete_at(rnd)
659:           end
660: 
661:           # Reset random number generator to fresh seed
662:           # As our seed from options is most likely short
663:           srand if @limit_seed
664:         end
665: 
666:         [result].flatten
667:       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 908
908:       def process_results_with_block(action, resp, block, aggregate)
909:         @stats.node_responded(resp[:senderid])
910: 
911:         result = rpc_result_from_reply(@agent, action, resp)
912:         aggregate = aggregate_reply(result, aggregate) if aggregate
913: 
914:         if resp[:body][:statuscode] == 0 || resp[:body][:statuscode] == 1
915:           @stats.ok if resp[:body][:statuscode] == 0
916:           @stats.fail if resp[:body][:statuscode] == 1
917:           @stats.time_block_execution :start
918: 
919:           case block.arity
920:             when 1
921:               block.call(resp)
922:             when 2
923:               block.call(resp, result)
924:           end
925: 
926:           @stats.time_block_execution :end
927:         else
928:           @stats.fail
929: 
930:           case resp[:body][:statuscode]
931:             when 2
932:               raise UnknownRPCAction, resp[:body][:statusmsg]
933:             when 3
934:               raise MissingRPCData, resp[:body][:statusmsg]
935:             when 4
936:               raise InvalidRPCData, resp[:body][:statusmsg]
937:             when 5
938:               raise UnknownRPCError, resp[:body][:statusmsg]
939:           end
940:         end
941: 
942:         return aggregate
943:       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 888
888:       def process_results_without_block(resp, action, aggregate)
889:         @stats.node_responded(resp[:senderid])
890: 
891:         result = rpc_result_from_reply(@agent, action, resp)
892:         aggregate = aggregate_reply(result, aggregate) if aggregate
893: 
894:         if resp[:body][:statuscode] == 0 || resp[:body][:statuscode] == 1
895:           @stats.ok if resp[:body][:statuscode] == 0
896:           @stats.fail if resp[:body][:statuscode] == 1
897:         else
898:           @stats.fail
899:         end
900: 
901:         [result, aggregate]
902:       end

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

[Source]

     # File lib/mcollective/rpc/client.rb, line 422
422:       def reset
423:         @discovered_agents = nil
424:       end

Reet the filter to an empty one

[Source]

     # File lib/mcollective/rpc/client.rb, line 427
427:       def reset_filter
428:         @filter = Util.empty_filter
429:         agent_filter @agent
430:       end

[Source]

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

[Validate]