Added mcollective 2.3.1 package
[packages/trusty/mcollective.git] / lib / mcollective / rpc / request.rb
1 module MCollective
2   module RPC
3     # Simple class to manage compliant requests for MCollective::RPC agents
4     class Request
5       attr_accessor :time, :action, :data, :sender, :agent, :uniqid, :caller, :ddl
6
7       def initialize(msg, ddl)
8         @time = msg[:msgtime]
9         @action = msg[:body][:action]
10         @data = msg[:body][:data]
11         @sender = msg[:senderid]
12         @agent = msg[:body][:agent]
13         @uniqid = msg[:requestid]
14         @caller = msg[:callerid] || "unknown"
15         @ddl = ddl
16       end
17
18       # If data is a hash, quick helper to get access to it's include? method
19       # else returns false
20       def include?(key)
21         return false unless @data.is_a?(Hash)
22         return @data.include?(key)
23       end
24
25       # If no :process_results is specified always respond else respond
26       # based on the supplied property
27       def should_respond?
28         return @data[:process_results] if @data.include?(:process_results)
29
30         return true
31       end
32
33       # If data is a hash, gives easy access to its members, else returns nil
34       def [](key)
35         return nil unless @data.is_a?(Hash)
36         return @data[key]
37       end
38
39       def fetch(key, default)
40         return nil unless @data.is_a?(Hash)
41         return @data.fetch(key, default)
42       end
43
44       def to_hash
45         return {:agent => @agent,
46                 :action => @action,
47                 :data => @data}
48       end
49
50       # Validate the request against the DDL
51       def validate!
52         @ddl.validate_rpc_request(@action, @data)
53       end
54
55       def to_json
56         to_hash.merge!({:sender   => @sender,
57                         :callerid => @callerid,
58                         :uniqid   => @uniqid}).to_json
59       end
60     end
61   end
62 end