Update version according to OSCI-856
[packages/precise/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           # must deep clone this data to avoid accidental updates of the DDL in cases where the
30           # default is for example a string and someone does << on it
31           @data[output] = Marshal.load(Marshal.dump(interface[:output][output].fetch(:default, nil)))
32         end
33       end
34
35       # Helper to fill in statusmsg and code on failure
36       def fail(msg, code=1)
37         @statusmsg = msg
38         @statuscode = code
39       end
40
41       # Helper that fills in statusmsg and code but also raises an appropriate error
42       def fail!(msg, code=1)
43         @statusmsg = msg
44         @statuscode = code
45
46         case code
47           when 1
48             raise RPCAborted, msg
49
50           when 2
51             raise UnknownRPCAction, msg
52
53           when 3
54             raise MissingRPCData, msg
55
56           when 4
57             raise InvalidRPCData, msg
58
59           else
60             raise UnknownRPCError, msg
61         end
62       end
63
64       # Write to the data hash
65       def []=(key, val)
66         @data[key] = val
67       end
68
69       # Read from the data hash
70       def [](key)
71         @data[key]
72       end
73
74       def fetch(key, default)
75         @data.fetch(key, default)
76       end
77
78       # Returns a compliant Hash of the reply that should be sent
79       # over the middleware
80       def to_hash
81         return {:statuscode => @statuscode,
82                 :statusmsg => @statusmsg,
83                 :data => @data}
84       end
85     end
86   end
87 end