Initial commit
[ta/distributed-state-server.git] / src / dss / server / dss_rpc_processor.py
1 # Copyright 2019 Nokia
2 #
3 # Licensed under the Apache License, Version 2.0 (the "License");
4 # you may not use this file except in compliance with the License.
5 # You may obtain a copy of the License at
6 #
7 #     http://www.apache.org/licenses/LICENSE-2.0
8 #
9 # Unless required by applicable law or agreed to in writing, software
10 # distributed under the License is distributed on an "AS IS" BASIS,
11 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 # See the License for the specific language governing permissions and
13 # limitations under the License.
14 #
15
16 import logging
17 from dss.api import dss_msg
18 from dss.server import dss_rpc_handler
19
20 class RPCProcessor(object):
21     def __init__(self):
22         self.handlers = []
23
24     def add_handler(self, handler):
25         self.handlers.append(handler)
26
27     def get_handler(self, name):
28         for handler in self.handlers:
29             if handler.get_name() == name:
30                 return handler
31         return None
32
33     '''
34     process the request
35     Arguments:
36     reqstring the request string
37     Return:
38     repstring the reply string
39     '''
40     def process(self, reqstring):
41         reppayload = {}
42         result = 'OK'
43         id = None
44         name = None
45         try:
46             # deserialize req string
47             reqmsg = dss_msg.Msg()
48             reqmsg.deserialize(reqstring)
49             name = reqmsg.get_name()
50
51             logging.info("Processing %s" % name)
52
53             id = reqmsg.get_id()
54
55             # find suitable handler
56             handler = self.get_handler(name)
57
58             # process message
59             reppayload = handler.handle(reqmsg.get_payload())
60         except Exception as exp:
61             logging.warning('Failed when processing %s' % reqstring)
62             result = str(exp)
63
64         repmsg = dss_msg.Msg(name, id, reppayload, result)
65
66         return repmsg.serialize()