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] 
client  [R] 
config  [RW] 
ddl  [R] 
discovery_timeout  [RW] 
filter  [RW] 
limit_targets  [R] 
progress  [RW] 
stats  [R] 
timeout  [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 19
19:             def initialize(agent, flags = {})
20:                 if flags.include?(:options)
21:                     options = flags[:options]
22: 
23:                 elsif @@initial_options
24:                     options = Marshal.load(@@initial_options)
25: 
26:                 else
27:                     oparser = MCollective::Optionparser.new({:verbose => false, :progress_bar => true, :mcollective_limit_targets => false}, "filter")
28: 
29:                     options = oparser.parse do |parser, options|
30:                         if block_given?
31:                             yield(parser, options)
32:                         end
33: 
34:                         Helpers.add_simplerpc_options(parser, options)
35:                     end
36: 
37:                     @@initial_options = Marshal.dump(options)
38:                 end
39: 
40:                 @stats = Stats.new
41:                 @agent = agent
42:                 @discovery_timeout = options[:disctimeout]
43:                 @timeout = options[:timeout]
44:                 @verbose = options[:verbose]
45:                 @filter = options[:filter]
46:                 @config = options[:config]
47:                 @discovered_agents = nil
48:                 @progress = options[:progress_bar]
49:                 @limit_targets = options[:mcollective_limit_targets]
50: 
51:                 agent_filter agent
52: 
53:                 @client = client = MCollective::Client.new(@config)
54:                 @client.options = options
55: 
56:                 # if we can find a DDL for the service override
57:                 # the timeout of the client so we always magically
58:                 # wait appropriate amounts of time.
59:                 #
60:                 # We add the discovery timeout to the ddl supplied
61:                 # timeout as the discovery timeout tends to be tuned
62:                 # for local network conditions and fact source speed
63:                 # which would other wise not be accounted for and
64:                 # some results might get missed.
65:                 #
66:                 # We do this only if the timeout is the default 5
67:                 # seconds, so that users cli overrides will still
68:                 # get applied
69:                 begin
70:                     @ddl = DDL.new(agent)
71:                     @timeout = @ddl.meta[:timeout] + @discovery_timeout if @timeout == 5
72:                 rescue Exception => e
73:                     Log.instance.debug("Could not find DDL: #{e}")
74:                     @ddl = nil
75:                 end
76: 
77:                 STDERR.sync = true
78:                 STDOUT.sync = true
79:             end

Public Instance methods

Sets the agent filter

[Source]

     # File lib/mcollective/rpc/client.rb, line 280
280:             def agent_filter(agent)
281:                 @filter["agent"] << agent
282:                 @filter["agent"].compact!
283:                 reset
284:             end

Sets the class filter

[Source]

     # File lib/mcollective/rpc/client.rb, line 266
266:             def class_filter(klass)
267:                 @filter["cf_class"] << klass
268:                 @filter["cf_class"].compact!
269:                 reset
270:             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", {}, {:identity => "your.box.com"},

                      ["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

[Source]

     # File lib/mcollective/rpc/client.rb, line 224
224:             def custom_request(action, args, expected_agents, filter = {}, &block)
225:                 @ddl.validate_request(action, args) if @ddl
226: 
227:                 @stats.reset
228: 
229:                 custom_filter = Util.empty_filter
230:                 custom_options = options.clone
231: 
232:                 # merge the supplied filter with the standard empty one
233:                 # we could just use the merge method but I want to be sure
234:                 # we dont merge in stuff that isnt actually valid
235:                 ["identity", "fact", "agent", "cf_class"].each do |ftype|
236:                     if filter.include?(ftype)
237:                         custom_filter[ftype] = [filter[ftype], custom_filter[ftype]].flatten
238:                     end
239:                 end
240: 
241:                 # ensure that all filters at least restrict the call to the agent we're a proxy for
242:                 custom_filter["agent"] << @agent unless custom_filter["agent"].include?(@agent)
243:                 custom_options[:filter] = custom_filter
244: 
245:                 # Fake out the stats discovery would have put there
246:                 @stats.discovered_agents([expected_agents].flatten)
247: 
248:                 # Handle fire and forget requests
249:                 if args.include?(:process_results) && args[:process_results] == false
250:                     @filter = custom_filter
251:                     return fire_and_forget_request(action, args)
252:                 end
253: 
254:                 # Now do a call pretty much exactly like in method_missing except with our own
255:                 # options and discovery magic
256:                 if block_given?
257:                     call_agent(action, args, custom_options, [expected_agents].flatten) do |r|
258:                         block.call(r)
259:                     end
260:                 else
261:                     call_agent(action, args, custom_options, [expected_agents].flatten)
262:                 end
263:             end

Disconnects cleanly from the middleware

[Source]

    # File lib/mcollective/rpc/client.rb, line 82
82:             def disconnect
83:                 @client.disconnect
84:             end

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

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 312
312:             def discover(flags={})
313:                 flags.include?(:verbose) ? verbose = flags[:verbose] : verbose = @verbose
314: 
315:                 if @discovered_agents == nil
316:                     @stats.time_discovery :start
317: 
318:                     STDERR.print("Determining the amount of hosts matching filter for #{discovery_timeout} seconds .... ") if verbose
319:                     @discovered_agents = @client.discover(@filter, @discovery_timeout)
320:                     STDERR.puts(@discovered_agents.size) if verbose
321: 
322:                     @stats.time_discovery :end
323: 
324:                 end
325: 
326:                 @stats.discovered_agents(@discovered_agents)
327:                 RPC.discovered(@discovered_agents)
328: 
329:                 @discovered_agents
330:             end

Sets the fact filter

[Source]

     # File lib/mcollective/rpc/client.rb, line 273
273:             def fact_filter(fact, value)
274:                 @filter["fact"] << {:fact => fact, :value => value}
275:                 @filter["fact"].compact!
276:                 reset
277:             end

Returns help for an agent if a DDL was found

[Source]

    # File lib/mcollective/rpc/client.rb, line 87
87:             def help(template)
88:                 if @ddl
89:                     @ddl.help(template)
90:                 else
91:                     return "Can't find DDL for agent '#{@agent}'"
92:                 end
93:             end

Sets the identity filter

[Source]

     # File lib/mcollective/rpc/client.rb, line 287
287:             def identity_filter(identity)
288:                 @filter["identity"] << identity
289:                 @filter["identity"].compact!
290:                 reset
291:             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 344
344:             def limit_targets=(limit)
345:                 if limit.is_a?(String)
346:                     raise "Invalid limit specified: #{limit} valid limits are /^\d+%*$/" unless limit =~ /^\d+%*$/
347:                     @limit_targets = limit
348:                 elsif limit.respond_to?(:to_i)
349:                     limit = limit.to_i
350:                     limit = 1 if limit == 0
351:                     @limit_targets = limit
352:                 else
353:                     raise "Don't know how to handle limit of type #{limit.class}"
354:                 end
355:             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.

[Source]

     # File lib/mcollective/rpc/client.rb, line 175
175:             def method_missing(method_name, *args, &block)
176:                 # set args to an empty hash if nothings given
177:                 args = args[0]
178:                 args = {} if args.nil?
179: 
180:                 action = method_name.to_s
181: 
182:                 @stats.reset
183: 
184:                 @ddl.validate_request(action, args) if @ddl
185: 
186:                 # Handle single target requests by doing discovery and picking
187:                 # a random node.  Then do a custom request specifying a filter
188:                 # that will only match the one node.
189:                 if @limit_targets
190:                     target_nodes = pick_nodes_from_discovered(@limit_targets)
191:                     Log.instance.debug("Picked #{target_nodes.join(',')} as limited target(s)")
192: 
193:                     custom_request(action, args, target_nodes, {"identity" => /^(#{target_nodes.join('|')})$/}, &block)
194:                 else
195:                     # Normal agent requests as per client.action(args)
196:                     call_agent(action, args, options, &block)
197:                 end
198:             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 114
114:             def new_request(action, data)
115:                 callerid = PluginManager["security_plugin"].callerid
116: 
117:                 {:agent  => @agent,
118:                  :action => action,
119:                  :caller => callerid,
120:                  :data   => data}
121:             end

Provides a normal options hash like you would get from Optionparser

[Source]

     # File lib/mcollective/rpc/client.rb, line 334
334:             def options
335:                 {:disctimeout => @discovery_timeout,
336:                  :timeout => @timeout,
337:                  :verbose => @verbose,
338:                  :filter => @filter,
339:                  :config => @config}
340:             end

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

[Source]

     # File lib/mcollective/rpc/client.rb, line 295
295:             def reset
296:                 @discovered_agents = nil
297:             end

Reet the filter to an empty one

[Source]

     # File lib/mcollective/rpc/client.rb, line 300
300:             def reset_filter
301:                 @filter = Util.empty_filter
302:                 agent_filter @agent
303:             end

[Validate]