dfa08bb69ed17b87cf9e66e3f8f1aa697d0cc7ab
[osm/SO.git] / common / python / rift / mano / dts / rpc / core.py
1 """
2 #
3 # Copyright 2016 RIFT.IO Inc
4 #
5 # Licensed under the Apache License, Version 2.0 (the "License");
6 # you may not use this file except in compliance with the License.
7 # You may obtain a copy of the License at
8 #
9 # http://www.apache.org/licenses/LICENSE-2.0
10 #
11 # Unless required by applicable law or agreed to in writing, software
12 # distributed under the License is distributed on an "AS IS" BASIS,
13 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 # See the License for the specific language governing permissions and
15 # limitations under the License.
16 #
17
18 @file core.py
19 @author Varun Prasad (varun.prasad@riftio.com)
20 @date 28-Sep-2016
21
22 """
23
24 import abc
25 import asyncio
26
27 import gi
28 gi.require_version("RwDts", "1.0")
29
30 from gi.repository import RwDts as rwdts
31 import rift.tasklets
32
33 from ..core import DtsHandler
34
35
36 class AbstractRpcHandler(DtsHandler):
37 """Base class to simplify RPC implementation
38 """
39 def __init__(self, log, dts, loop):
40 super().__init__(log, dts, loop)
41
42 if not asyncio.iscoroutinefunction(self.callback):
43 raise ValueError('%s has to be a coroutine' % (self.callback))
44
45 @abc.abstractproperty
46 def xpath(self):
47 pass
48
49 @property
50 def input_xpath(self):
51 return "I,{}".format(self.xpath)
52
53 @property
54 def output_xpath(self):
55 return "O,{}".format(self.xpath)
56
57 def flags(self):
58 return rwdts.Flag.PUBLISHER
59
60 @asyncio.coroutine
61 def on_prepare(self, xact_info, action, ks_path, msg):
62 assert action == rwdts.QueryAction.RPC
63
64 try:
65 rpc_op = yield from self.callback(ks_path, msg)
66 xact_info.respond_xpath(
67 rwdts.XactRspCode.ACK,
68 self.output_xpath,
69 rpc_op)
70
71 except Exception as e:
72 self.log.exception(e)
73 xact_info.respond_xpath(
74 rwdts.XactRspCode.NACK,
75 self.output_xpath)
76
77 @asyncio.coroutine
78 def register(self):
79 reg_event = asyncio.Event(loop=self.loop)
80
81 @asyncio.coroutine
82 def on_ready(regh, status):
83 reg_event.set()
84
85 handler = rift.tasklets.DTS.RegistrationHandler(
86 on_prepare=self.on_prepare,
87 on_ready=on_ready)
88
89 with self.dts.group_create() as group:
90 self.reg = group.register(
91 xpath=self.input_xpath,
92 handler=handler,
93 flags=self.flags())
94
95 yield from reg_event.wait()
96
97 @abc.abstractmethod
98 @asyncio.coroutine
99 def callback(self, ks_path, msg):
100 """Subclass needs to override this method
101
102 Args:
103 ks_path : Key spec path
104 msg : RPC input
105 """
106 pass
107