Adding more get voltha apis

Change-Id: I4fe2696e3ffdcb1477e5d97d0405353ab465c062
diff --git a/netconf/grpc_client/grpc_client.py b/netconf/grpc_client/grpc_client.py
index ae19067..1c92f71 100644
--- a/netconf/grpc_client/grpc_client.py
+++ b/netconf/grpc_client/grpc_client.py
@@ -38,7 +38,8 @@
 from netconf.protos.schema_pb2 import SchemaServiceStub
 from google.protobuf.empty_pb2 import Empty
 from common.utils.consulhelpers import get_endpoint_from_consul
-from netconf.protos.voltha_pb2  import VolthaLocalServiceStub
+from netconf.protos.voltha_pb2  import VolthaLocalServiceStub, \
+    VolthaGlobalServiceStub
 from twisted.internet import threads
 from google.protobuf import empty_pb2
 from google.protobuf.json_format import MessageToDict, ParseDict
@@ -133,9 +134,9 @@
                 log.info('grpc-endpoint-connecting', host=host, port=port)
                 self.channel = grpc.insecure_channel('{}:{}'.format(host, port))
 
-                yang_from = self._retrieve_schema()
-                log.info('proto-to-yang-schema', file=yang_from)
-                self._compile_proto_files(yang_from)
+                # yang_from = self._retrieve_schema()
+                # log.info('proto-to-yang-schema', file=yang_from)
+                # self._compile_proto_files(yang_from)
                 self._clear_backoff()
 
                 if self.on_start_callback is not None:
@@ -146,6 +147,7 @@
                     reactor.callLater(0, self.reconnect_callback)
 
                 self.local_stub = VolthaLocalServiceStub(self.channel)
+                self.global_stub = VolthaGlobalServiceStub(self.channel)
 
                 return
 
@@ -286,3 +288,43 @@
         except Exception, e:
             log.error('failure', exception=repr(e))
 
+
+    #TODO: should be generated code
+    @inlineCallbacks
+    def invoke_voltha_api(self, key):
+        # key = ''.join([service, '-', method])
+        try:
+            if key == 'VolthaGlobalService-GetVoltha':
+                res = yield threads.deferToThread(
+                    self.global_stub.GetVoltha, empty_pb2.Empty())
+            elif key == 'VolthaLocalService-GetVolthaInstance':
+                res = yield threads.deferToThread(
+                    self.local_stub.GetVolthaInstance, empty_pb2.Empty())
+            elif key == 'VolthaLocalService-GetHealth':
+                res = yield threads.deferToThread(
+                    self.local_stub.GetHealth, empty_pb2.Empty())
+            elif key == 'VolthaLocalService-ListAdapters':
+                res = yield threads.deferToThread(
+                    self.local_stub.ListAdapters, empty_pb2.Empty())
+            elif key == 'VolthaLocalService-ListLogicalDevices':
+                res = yield threads.deferToThread(
+                    self.local_stub.ListLogicalDevices, empty_pb2.Empty())
+            elif key == 'VolthaLocalService-ListDevices':
+                res = yield threads.deferToThread(
+                    self.local_stub.ListDevices, empty_pb2.Empty())
+            elif key == 'VolthaLocalService-ListDeviceTypes':
+                res = yield threads.deferToThread(
+                    self.local_stub.ListDeviceTypes, empty_pb2.Empty())
+            elif key == 'VolthaLocalService-ListDeviceGroups':
+                res = yield threads.deferToThread(
+                    self.local_stub.ListDeviceGroups, empty_pb2.Empty())
+            else: # for now just return voltha instance data
+                res = yield threads.deferToThread(
+                    self.local_stub.GetVolthaInstance, empty_pb2.Empty())
+
+            out_data = MessageToDict(res, True, True)
+            returnValue(out_data)
+        except Exception, e:
+            log.error('failure', exception=repr(e))
+
+
diff --git a/netconf/nc_rpc/ext/get_voltha.py b/netconf/nc_rpc/ext/get_voltha.py
index 8977b89..271a20e 100644
--- a/netconf/nc_rpc/ext/get_voltha.py
+++ b/netconf/nc_rpc/ext/get_voltha.py
@@ -28,8 +28,9 @@
 
 
 class GetVoltha(Rpc):
-    def __init__(self, rpc_request, rpc_method, grpc_client, session):
-        super(GetVoltha, self).__init__(rpc_request, rpc_method,
+    def __init__(self, rpc_request, rpc_method, voltha_method_ref, grpc_client,
+                 session):
+        super(GetVoltha, self).__init__(rpc_request, rpc_method, voltha_method_ref,
                                         grpc_client, session)
         self._validate_parameters()
 
@@ -41,7 +42,9 @@
             returnValue(self.rpc_response)
 
         # Invoke voltha via the grpc client
-        res_dict = yield self.grpc_client.get_voltha_instance()
+        res_dict = yield self.grpc_client.invoke_voltha_api(self.voltha_method_ref)
+
+        # res_dict = yield self.grpc_client.get_voltha_instance()
 
         # convert dict to xml
         xml = dicttoxml.dicttoxml(res_dict)
diff --git a/netconf/nc_rpc/rpc.py b/netconf/nc_rpc/rpc.py
index ff9b303..fb35313 100644
--- a/netconf/nc_rpc/rpc.py
+++ b/netconf/nc_rpc/rpc.py
@@ -22,11 +22,13 @@
 import io
 
 class Rpc(object):
-    def __init__(self,rpc_request, rpc_method, grpc_client, session):
+    def __init__(self,rpc_request, rpc_method, voltha_method_ref,
+                 grpc_client, session):
         self.rpc_request = rpc_request
         self.rpc_method = rpc_method
         self.rpc_response = RpcResponse()
         self.grpc_client =  grpc_client
+        self.voltha_method_ref = voltha_method_ref
         self.session = session
 
     def execute(self):
diff --git a/netconf/nc_rpc/rpc_factory.py b/netconf/nc_rpc/rpc_factory.py
index 72b4734..e409198 100644
--- a/netconf/nc_rpc/rpc_factory.py
+++ b/netconf/nc_rpc/rpc_factory.py
@@ -31,109 +31,114 @@
 from ext.get_voltha import GetVoltha
 from netconf import NSMAP, qmap
 import netconf.nc_common.error as ncerror
+
 log = structlog.get_logger()
 from lxml import etree
 
 
 class RpcFactory:
+    instance = None
 
-	instance = None
+    def __init__(self):
+        self.rpc_map = {}
+        # TODO:  This will be loaded after the yang modules have been
+        # generated from proto files
+        self.register_rpc('{urn:opencord:params:xml:ns:voltha:ietf-voltha}',
+                          'VolthaGlobalService', 'GetVoltha', GetVoltha)
+        self.register_rpc('{urn:opencord:params:xml:ns:voltha:ietf-voltha}',
+                          'any', 'any', GetVoltha)
 
-	def __init__(self):
-		self.rpc_map = {}
-		#TODO:  This will be loaded after the yang modules have been
-		# generated from proto files
-		self.register_rpc('{urn:opencord:params:xml:ns:voltha:ietf-voltha}',
-						 'VolthaGlobalService', 'GetVoltha', GetVoltha)
+    def _get_key(self, namespace, service, name):
+        return ''.join([namespace, service, name])
 
-	def _get_key(self, namespace, service, name):
-		return ''.join([namespace,service,name])
+    def register_rpc(self, namespace, service, name, klass):
+        key = self._get_key(namespace, service, name)
+        if key not in self.rpc_map.keys():
+            self.rpc_map[key] = klass
 
-	def register_rpc(self, namespace, service, name, klass):
-		key = self._get_key(namespace, service, name)
-		if key not in self.rpc_map.keys():
-			self.rpc_map[key] = klass
+    def get_handler(self, namespace, service, name):
+        key = self._get_key(namespace, service, name)
+        if key in self.rpc_map.keys():
+            return self.rpc_map[key]
 
-	def get_handler(self, namespace, service, name):
-		key = self._get_key(namespace, service, name)
-		if key in self.rpc_map.keys():
-			return self.rpc_map[key]
+    def get_rpc_handler(self, rpc_node, msg, grpc_channel, session):
+        try:
+            msg_id = rpc_node.get('message-id')
+            log.info("Received-rpc-message-id", msg_id=msg_id)
 
+        except (TypeError, ValueError):
+            raise ncerror.SessionError(msg,
+                                       "No valid message-id attribute found")
 
-	def get_rpc_handler(self, rpc_node, msg, grpc_channel, session):
-		try:
-			msg_id = rpc_node.get('message-id')
-			log.info("Received-rpc-message-id", msg_id=msg_id)
+        log.info("rpc-node", node=etree.tostring(rpc_node, pretty_print=True))
 
-		except (TypeError, ValueError):
-			raise ncerror.SessionError(msg,
-									   "No valid message-id attribute found")
+        # Get the first child of rpc as the method name
+        rpc_method = rpc_node.getchildren()
+        if len(rpc_method) != 1:
+            log.error("badly-formatted-rpc-method", msg_id=msg_id)
+            raise ncerror.BadMsg(rpc_node)
 
-		log.info("rpc-node", node=etree.tostring(rpc_node, pretty_print=True))
+        rpc_method = rpc_method[0]
 
-		# Get the first child of rpc as the method name
-		rpc_method = rpc_node.getchildren()
-		if len(rpc_method) != 1:
-			log.error("badly-formatted-rpc-method", msg_id=msg_id)
-			raise ncerror.BadMsg(rpc_node)
+        if rpc_method.prefix is None:
+            log.error("rpc-method-has-no-prefix", msg_id=msg_id)
+            raise ncerror.BadMsg(rpc_node)
 
-		rpc_method = rpc_method[0]
+        try:
+            # extract the namespace, service and name
+            namespace = ''.join(
+                ['{', rpc_method.nsmap[rpc_method.prefix], '}'])
+            # rpc_name = rpc_method.tag.replace(qmap('nc'), "")
+            rpc = rpc_method.tag.replace(namespace, "").split('-')
+            rpc_service = rpc[0]
+            rpc_name = rpc[1]
+            log.info("rpc-request",
+                     namespace=namespace,
+                     service=rpc_service,
+                     name=rpc_name)
+        except Exception as e:
+            log.error("rpc-parsing-error", exception=repr(e))
+            raise ncerror.BadMsg(rpc_node)
 
-		if rpc_method.prefix is None:
-			log.error("rpc-method-has-no-prefix", msg_id=msg_id)
-			raise ncerror.BadMsg(rpc_node)
+        class_handler = self.get_handler(namespace, rpc_service, rpc_name)
+        if class_handler is None:
+            # TODO: for now just assume anything in voltha namespace will be
+            #  handled by the same api
+            class_handler = self.get_handler(namespace, 'any', 'any')
 
-		try:
-			# extract the namespace, service and name
-			namespace = ''.join(['{', rpc_method.nsmap[rpc_method.prefix], '}'])
-			# rpc_name = rpc_method.tag.replace(qmap('nc'), "")
-			rpc = rpc_method.tag.replace(namespace, "").split('-')
-			rpc_service = rpc[0]
-			rpc_name = rpc[1]
-			log.info("rpc-request",
-					 namespace=namespace,
-					 service=rpc_service,
-					 name=rpc_name)
-		except Exception as e:
-			log.error("rpc-parsing-error", exception=repr(e))
-			raise ncerror.BadMsg(rpc_node)
+        voltha_method_ref = ''.join([rpc_service, '-', rpc_name])
+        if class_handler is not None:
+            return class_handler(rpc_node, rpc_method, voltha_method_ref,
+                                 grpc_channel, session)
 
-		class_handler = self.get_handler(namespace, rpc_service, rpc_name)
+        log.error("rpc-not-implemented", rpc=rpc_name)
 
-		# class_handler = self.rpc_class_handlers.get(rpc_name, None)
-		if class_handler is not None:
-			return class_handler(rpc_node, rpc_method, grpc_channel, session)
-
-		log.error("rpc-not-implemented", rpc=rpc_name)
-
-
-	rpc_class_handlers = {
-		'getvoltha' : GetVoltha,
-		'get-config': GetConfig,
-		'get': Get,
-		'edit-config': EditConfig,
-		'copy-config': CopyConfig,
-		'delete-config': DeleteConfig,
-		'commit': Commit,
-		'lock': Lock,
-		'unlock': UnLock,
-		'close-session': CloseSession,
-		'kill-session': KillSession
-	}
-
+    rpc_class_handlers = {
+        'getvoltha': GetVoltha,
+        'get-config': GetConfig,
+        'get': Get,
+        'edit-config': EditConfig,
+        'copy-config': CopyConfig,
+        'delete-config': DeleteConfig,
+        'commit': Commit,
+        'lock': Lock,
+        'unlock': UnLock,
+        'close-session': CloseSession,
+        'kill-session': KillSession
+    }
 
 
 def get_rpc_factory_instance():
-	if RpcFactory.instance == None:
-		RpcFactory.instance = RpcFactory()
-	return RpcFactory.instance
+    if RpcFactory.instance == None:
+        RpcFactory.instance = RpcFactory()
+    return RpcFactory.instance
 
 
 if __name__ == '__main__':
-   fac = get_rpc_factory_instance()
-   fac.register_rpc('urn:opencord:params:xml:ns:voltha:ietf-voltha',
-					'VolthaGlobalService', 'GetVoltha', GetVoltha)
-   rpc = fac.get_handler('urn:opencord:params:xml:ns:voltha:ietf-voltha',
-					'VolthaGlobalService', 'GetVoltha')
-   # rpc = fac.rpc_class_handlers.get('getvoltha', None)
-   print rpc(None,None,None, None)
\ No newline at end of file
+    fac = get_rpc_factory_instance()
+    fac.register_rpc('urn:opencord:params:xml:ns:voltha:ietf-voltha',
+                     'VolthaGlobalService', 'GetVoltha', GetVoltha)
+    rpc = fac.get_handler('urn:opencord:params:xml:ns:voltha:ietf-voltha',
+                          'VolthaGlobalService', 'GetVoltha')
+    # rpc = fac.rpc_class_handlers.get('getvoltha', None)
+    print rpc(None, None, None, None)