blob: dacfc2b50521807979ccfe4dac13ad02944781f9 [file] [log] [blame]
Khen Nursimulu8ffb8932017-01-26 13:40:49 -05001#
2# Copyright 2017 the original author or authors.
3#
4# Licensed under the Apache License, Version 2.0 (the "License");
5# you may not use this file except in compliance with the License.
6# You may obtain a copy of the License at
7#
8# http://www.apache.org/licenses/LICENSE-2.0
9#
10# Unless required by applicable law or agreed to in writing, software
11# distributed under the License is distributed on an "AS IS" BASIS,
12# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13# See the License for the specific language governing permissions and
14# limitations under the License.
15#
16import os
17import sys
18import inspect
19from structlog import get_logger
20
21log = get_logger()
22
23
24class NetconfRPCMapper:
25 # Keeps the mapping between a Netconf RPC request and a voltha GPRC
26 # request. Singleton class.
27
28
29 instance = None
30
31 def __init__(self, work_dir, grpc_client):
32 self.work_dir = work_dir
33 self.grpc_client = grpc_client
34 self.rpc_map = {}
35
36 def _add_rpc_map(self, func_name, func_ref):
37 if not self.rpc_map.has_key(func_name):
38 log.debug('adding-function', name=func_name, ref=func_ref)
39 self.rpc_map[func_name] = func_ref
40
41 def _add_module_rpc(self, mod):
42 for name, ref in self.list_functions(mod):
43 self._add_rpc_map(name, ref)
44
45 def is_mod_function(self, mod, func):
46 return inspect.isfunction(func) and inspect.getmodule(func) == mod
47
48 def list_functions(self, mod):
49 return [(func.__name__, func) for func in mod.__dict__.itervalues()
50 if self.is_mod_function(mod, func)]
51
52 def load_modules(self):
53 if self.work_dir not in sys.path:
54 sys.path.insert(0, self.work_dir)
55
56 for fname in [f for f in os.listdir(self.work_dir)
57 if f.endswith('_rpc_gw.py')]:
58 modname = fname[:-len('.py')]
59 log.debug('load-modules', modname=modname)
60 try:
61 m = __import__(modname)
62 self._add_module_rpc(m)
63 except Exception, e:
64 log.exception('loading-module-exception', modname=modname, e=e)
65
66 def get_function(self, service, method):
67 if service:
68 func_name = ''.join([service, '_', method])
69 else:
70 func_name = method
71
72 if self.rpc_map.has_key(func_name):
73 return self.rpc_map[func_name]
74 else:
75 return None
76
77 def is_rpc_exist(self, rpc_name):
78 return self.rpc_map.has_key(rpc_name)
79
80
81def get_nc_rpc_mapper_instance(work_dir=None, grpc_client=None):
82 if NetconfRPCMapper.instance == None:
83 NetconfRPCMapper.instance = NetconfRPCMapper(work_dir, grpc_client)
84 return NetconfRPCMapper.instance