Added mcollective 2.3.1 package
[packages/trusty/mcollective.git] / lib / mcollective / rpc / reply.rb
1 module MCollective
2   module RPC
3     # Simple class to manage compliant replies to MCollective::RPC
4     class Reply
5       attr_accessor :statuscode, :statusmsg, :data
6
7       def initialize(action, ddl)
8         @data = {}
9         @statuscode = 0
10         @statusmsg = "OK"
11         @ddl = ddl
12         @action = action
13
14         begin
15           initialize_data
16         rescue Exception => e
17           Log.warn("Could not pre-populate reply data from the DDL: %s: %s" % [e.class, e.to_s ])
18         end
19       end
20
21       def initialize_data
22         unless @ddl.actions.include?(@action)
23           raise "No action '%s' defined for agent '%s' in the DDL" % [@action, @ddl.pluginname]
24         end
25
26         interface = @ddl.action_interface(@action)
27
28         interface[:output].keys.each do |output|
29           @data[output] = interface[:output][output][:default]
30         end
31       end
32
33       # Helper to fill in statusmsg and code on failure
34       def fail(msg, code=1)
35         @statusmsg = msg
36         @statuscode = code
37       end
38
39       # Helper that fills in statusmsg and code but also raises an appropriate error
40       def fail!(msg, code=1)
41         @statusmsg = msg
42         @statuscode = code
43
44         case code
45           when 1
46             raise RPCAborted, msg
47
48           when 2
49             raise UnknownRPCAction, msg
50
51           when 3
52             raise MissingRPCData, msg
53
54           when 4
55             raise InvalidRPCData, msg
56
57           else
58             raise UnknownRPCError, msg
59         end
60       end
61
62       # Write to the data hash
63       def []=(key, val)
64         @data[key] = val
65       end
66
67       # Read from the data hash
68       def [](key)
69         @data[key]
70       end
71
72       def fetch(key, default)
73         @data.fetch(key, default)
74       end
75
76       # Returns a compliant Hash of the reply that should be sent
77       # over the middleware
78       def to_hash
79         return {:statuscode => @statuscode,
80                 :statusmsg => @statusmsg,
81                 :data => @data}
82       end
83     end
84   end
85 end