Update VNF interface and IP information in A&AI
[vfc/nfvo/lcm.git] / lcm / ns_vnfs / biz / handle_notification.py
index 5ba685b..56717cd 100644 (file)
@@ -16,17 +16,20 @@ import logging
 import traceback
 import uuid
 
+
 from rest_framework import status
 from rest_framework.response import Response
 
-from lcm.ns_vnfs.const import INST_TYPE
+from lcm.ns_vnfs.enum import INST_TYPE
 from lcm.pub.config.config import REPORT_TO_AAI
 from lcm.pub.database.models import (CPInstModel, NfInstModel, PortInstModel,
                                      VLInstModel, VmInstModel, VNFCInstModel)
-from lcm.pub.exceptions import NSLCMException
+from lcm.pub.exceptions import NSLCMException, RequestException
 from lcm.pub.msapi.aai import (create_network_aai, create_vserver_aai,
                                delete_network_aai, delete_vserver_aai,
-                               query_network_aai, query_vserver_aai)
+                               query_network_aai, query_vserver_aai, create_l_interface_aai,
+                               create_l3_interface_ipv4_address_list_aai, query_l_interface_aai,
+                               delete_l_interface_aai)
 from lcm.pub.msapi.extsys import get_vim_by_id, split_vim_to_owner_region
 from lcm.pub.utils.values import ignore_case_get
 
@@ -38,10 +41,10 @@ class HandleVnfLcmOocNotification(object):
         logger.debug("[Notify LCM] vnfmid=%s, vnfInstanceId=%s, data=%s" % (vnfmid, vnfInstanceId, data))
         self.vnfmid = vnfmid
         self.m_vnfInstanceId = vnfInstanceId
-        self.vnf_instid = self.get_vnfinstid(self.m_vnfInstanceId, self.vnfmid)
+        self.vnf_instid = get_vnfinstid(self.m_vnfInstanceId, self.vnfmid)
         self.operation = ignore_case_get(data, 'operation')
         self.affectedVnfcs = ignore_case_get(data, 'affectedVnfcs')
-        self.affectedVls = ignore_case_get(data, 'affectedVls')
+        self.affectedVls = ignore_case_get(data, 'affectedVirtualLinks')
         self.affectedCps = ignore_case_get(data, 'changedExtConnectivity')
         self.affectedVirtualStorage = ignore_case_get(data, 'affectedVirtualStorages')
 
@@ -53,24 +56,13 @@ class HandleVnfLcmOocNotification(object):
             self.update_Storage()
             if REPORT_TO_AAI:
                 self.update_network_in_aai()
+                self.update_ip_addr_in_aai()
             logger.debug("notify lcm end")
         except NSLCMException as e:
-            self.exception(e.message)
+            exception(e.args[0])
         except Exception:
             logger.error(traceback.format_exc())
-            self.exception('unexpected exception')
-
-    def get_vnfinstid(self, mnfinstid, vnfm_inst_id):
-        logger.debug("vnfinstid in vnfm is:%s,vnfmid is:%s", mnfinstid, vnfm_inst_id)
-        logger.debug("mnfinstid=%s, vnfm_inst_id=%s", mnfinstid, vnfm_inst_id)
-        nfinst = NfInstModel.objects.filter(mnfinstid=mnfinstid, vnfm_inst_id=vnfm_inst_id).first()
-        if nfinst:
-            return nfinst.nfinstid
-        raise NSLCMException("vnfinstid not exist")
-
-    def exception(self, error_msg):
-        logger.error('Notify Lcm failed, detail message: %s' % error_msg)
-        return Response(data={'error': '%s' % error_msg}, status=status.HTTP_409_CONFLICT)
+            exception('unexpected exception')
 
     def update_Vnfc(self):
         for vnfc in self.affectedVnfcs:
@@ -98,7 +90,7 @@ class HandleVnfLcmOocNotification(object):
                                                                                    nfinstid=self.vnf_instid,
                                                                                    vmid=vmId)
             else:
-                self.exception('affectedVnfc struct error: changeType not in {ADDED, REMOVED, MODIFIED, TEMPORARY}')
+                exception('affectedVnfc struct error: changeType not in {ADDED, REMOVED, MODIFIED, TEMPORARY}')
         logger.debug("Success to update all vserver to aai.")
 
     def update_Vl(self):
@@ -112,9 +104,9 @@ class HandleVnfLcmOocNotification(object):
             resourceName = ignore_case_get(networkResource, 'resourceId')  # replaced with resouceId temporarily
 
             if resourceType != 'network':
-                self.exception('affectedVl struct error: resourceType not euqal network')
+                exception('affectedVl struct error: resourceType not euqal network')
 
-            ownerId = self.get_vnfinstid(self.m_vnfInstanceId, self.vnfmid)
+            ownerId = self.vnf_instid
 
             if changeType == 'ADDED':
                 VLInstModel(vlinstanceid=vlInstanceId, vldid=vldid, vlinstancename=resourceName, ownertype=0,
@@ -126,11 +118,11 @@ class HandleVnfLcmOocNotification(object):
                     .update(vldid=vldid, vlinstancename=resourceName, ownertype=0, ownerid=ownerId,
                             relatednetworkid=resourceId, vltype=0)
             else:
-                self.exception('affectedVl struct error: changeType not in {ADDED, REMOVED, MODIFIED, TEMPORARY}')
+                exception('affectedVl struct error: changeType not in {ADDED, REMOVED, MODIFIED, TEMPORARY}')
 
     def update_Cp(self):
         for cp in self.affectedCps:
-            virtualLinkInstanceId = ignore_case_get(cp, 'id')
+            virtualLinkInstanceId = ignore_case_get(cp, 'id')
             ownertype = 0
             ownerid = self.vnf_instid
             for extLinkPorts in ignore_case_get(cp, 'extLinkPorts'):
@@ -143,28 +135,97 @@ class HandleVnfLcmOocNotification(object):
                 if portResource:
                     vimId = ignore_case_get(portResource, 'vimConnectionId')
                     resourceId = ignore_case_get(portResource, 'resourceId')
-                    resourceName = ignore_case_get(portResource, 'resourceId')  # replaced with resouceId temporarily
-                    # tenant = ignore_case_get(portResource, 'tenant')
-                    # ipAddress = ignore_case_get(portResource, 'ipAddress')
-                    # macAddress = ignore_case_get(portResource, 'macAddress')
-                    # instId = ignore_case_get(portResource, 'instId')
-                    portid = str(uuid.uuid4())
-
-                    PortInstModel(portid=portid, networkid='unknown', subnetworkid='unknown', vimid=vimId,
-                                  resourceid=resourceId, name=resourceName, instid="unknown", cpinstanceid=cpInstanceId,
-                                  bandwidth='unknown', operationalstate='active', ipaddress="unkown",
-                                  macaddress='unknown',
+                    resourceName = ignore_case_get(portResource, 'resourceProviderId')
+                    tenant = ignore_case_get(portResource, 'tenant')
+                    ipAddress = ignore_case_get(portResource, 'ipAddress')
+                    macAddress = ignore_case_get(portResource, 'macAddress')
+                    instId = ignore_case_get(portResource, 'instId')
+                    portid = ignore_case_get(portResource, 'portId')
+                    networkId = ignore_case_get(portResource, 'networkId')
+                    subnetId = ignore_case_get(portResource, 'subnetId')
+
+                    # portid = str(uuid.uuid4())
+
+                    PortInstModel(portid=portid, networkid=networkId, subnetworkid=subnetId, vimid=vimId,
+                                  resourceid=resourceId, name=resourceName, instid=instId, cpinstanceid=cpInstanceId,
+                                  bandwidth='unknown', operationalstate='active', ipaddress=ipAddress,
+                                  macaddress=macAddress,
                                   floatipaddress='unknown', serviceipaddress='unknown', typevirtualnic='unknown',
-                                  sfcencapsulation='gre', direction='unknown', tenant="unkown").save()
+                                  sfcencapsulation='gre', direction='unknown', tenant=tenant).save()
                     relatedportId = portid
 
                 CPInstModel(cpinstanceid=cpInstanceId, cpdid=cpdId, ownertype=ownertype, ownerid=ownerid,
-                            vlinstanceid=virtualLinkInstanceId, relatedtype=2, relatedport=relatedportId,
-                            status='active').save()
+                            relatedtype=2, relatedport=relatedportId, status='active').save()
 
     def update_Storage(self):
         pass
 
+    def del_l_interface_from_aai(self, vnf_id, l_interface_name):
+        logger.debug("Delete l_interface::delete_l_interface_in_aai[%s] in aai.", l_interface_name)
+        try:
+            l_interface_info = query_l_interface_aai(vnf_id, l_interface_name)
+            resource_version = l_interface_info.get("resource-version", '')
+            resp_data, resp_status = delete_l_interface_aai(vnf_id, l_interface_name, resource_version)
+            logger.debug("Delete l_interface[%s] from aai successfully, status: %s", l_interface_name,
+                         resp_status)
+        except RequestException:
+            logger.debug("l_interface delete exception in AAI")
+        except NSLCMException as e:
+            logger.debug("Fail to delete l_interface[%s] from aai: %s", l_interface_name, e.args[0])
+        except Exception as e:
+            logger.error("Exception occurs when delete l_interface[%s] from aai: %s", l_interface_name,
+                         e.args[0])
+            logger.error(traceback.format_exc())
+
+    def create_l_interface_aai(self, vnf_instid, l_interfaces_name):
+        logger.debug("Createl_interface::createl_interface_aai::report l_interface[%s] to aai." % l_interfaces_name)
+        try:
+
+            resp_data, resp_status = create_l_interface_aai(vnf_instid, l_interfaces_name)
+            logger.debug("Success to create l_interface[%s] to aai: [%s].", l_interfaces_name, resp_status)
+        except NSLCMException as e:
+            logger.debug(
+                "Fail to create l_interfaces_name[%s] to aai, detail message: %s" % (l_interfaces_name, e.args[0]))
+        except:
+            logger.error(traceback.format_exc())
+
+    def create_l3_interface_ipv4_address_list_aai(self, vnf_instid, l_interfaces_name, ip):
+        logger.debug(
+            "Create l3_interface_ipv4_address_list::create_l3_interface_ipv4_address_list_aai::report "
+            "l_interface[%s]::ip_list[%s] to aai." % (l_interfaces_name, ip))
+        try:
+            resp_data, resp_status = create_l3_interface_ipv4_address_list_aai(vnf_instid, l_interfaces_name, ip)
+            logger.debug("Success to create l_interface_ip_list[%s] to aai: [%s].", ip, resp_status)
+        except NSLCMException as e:
+            logger.debug(
+                "Fail to create ip_list[%s] to aai, detail message: %s" % (l_interfaces_name, e.args[0]))
+        except:
+            logger.error(traceback.format_exc())
+
+    def update_ip_addr_in_aai(self):
+        logger.debug("update ip addr in aai::begin to report ip to aai.")
+        try:
+            for ext in self.affectedCps:
+                extLinkPorts = ignore_case_get(ext, 'extLinkPorts')
+                changeType = ignore_case_get(ext, 'changeType')
+                for res in extLinkPorts:
+                    resourceHandle = ignore_case_get(res, 'resourceHandle')
+                    l_interfaces_name = ignore_case_get(resourceHandle, 'resourceProviderId')
+                    print(l_interfaces_name)
+                    ip = ignore_case_get(resourceHandle, 'ipAddress')
+                    if changeType in ['ADDED', 'MODIFIED']:
+                        self.create_l_interface_aai(self.vnf_instid, l_interfaces_name)
+                        self.create_l3_interface_ipv4_address_list_aai(self.vnf_instid, l_interfaces_name, ip)
+                    elif changeType == 'REMOVED':
+                        self.del_l_interface_from_aai(self.vnf_instid, l_interfaces_name)
+                    else:
+                        logger.error('update ip addr struct error: changeType not in'
+                                     ' {ADDED, REMOVED, MODIFIED, TEMPORARY}')
+        except Exception as e:
+            logger.debug("Fail to update ip addr to aai, detail message: %s" % e.args[0])
+        except:
+            logger.error(traceback.format_exc())
+
     def update_network_in_aai(self):
         logger.debug("update_network_in_aai::begin to report network to aai.")
         try:
@@ -189,7 +250,7 @@ class HandleVnfLcmOocNotification(object):
                 else:
                     logger.error('affectedVl struct error: changeType not in {ADDED, REMOVED, MODIFIED, TEMPORARY}')
         except NSLCMException as e:
-            logger.debug("Fail to create internal network to aai, detail message: %s" % e.message)
+            logger.debug("Fail to create internal network to aai, detail message: %s" % e.args[0])
         except:
             logger.error(traceback.format_exc())
 
@@ -220,7 +281,7 @@ class HandleVnfLcmOocNotification(object):
             resp_data, resp_status = create_network_aai(vlInstanceId, data)
             logger.debug("Success to create network[%s] to aai: [%s].", vlInstanceId, resp_status)
         except NSLCMException as e:
-            logger.debug("Fail to create network[%s] to aai, detail message: %s" % (vlInstanceId, e.message))
+            logger.debug("Fail to create network[%s] to aai, detail message: %s" % (vlInstanceId, e.args[0]))
         except:
             logger.error(traceback.format_exc())
 
@@ -229,14 +290,17 @@ class HandleVnfLcmOocNotification(object):
         try:
             # query network in aai, get resource_version
             customer_info = query_network_aai(vlInstanceId)
-            resource_version = customer_info["resource-version"]
-
-            # delete network from aai
-            resp_data, resp_status = delete_network_aai(vlInstanceId, resource_version)
-            logger.debug("Success to delete network[%s] from aai, resp_status: [%s]."
-                         % (vlInstanceId, resp_status))
+            if customer_info:
+                resource_version = customer_info["resource-version"]
+
+                # delete network from aai
+                resp_data, resp_status = delete_network_aai(vlInstanceId, resource_version)
+                logger.debug("Success to delete network[%s] from aai, resp_status: [%s]."
+                             % (vlInstanceId, resp_status))
+        except RequestException:
+            logger.debug("Network has been delted in aai")
         except NSLCMException as e:
-            logger.debug("Fail to delete network[%s] to aai, detail message: %s" % (vlInstanceId, e.message))
+            logger.debug("Fail to delete network[%s] to aai, detail message: %s" % (vlInstanceId, e.args[0]))
         except:
             logger.error(traceback.format_exc())
 
@@ -246,7 +310,7 @@ class HandleVnfLcmOocNotification(object):
             cloud_owner, cloud_region_id = split_vim_to_owner_region(vim_id)
 
             # query vim_info from aai
-            vim_info = get_vim_by_id(vim_id)
+            vim_info = get_vim_by_id({"cloud_owner": cloud_owner, 'cloud_regionid': cloud_region_id})
             tenant_id = vim_info["tenantId"]
             data = {
                 "vserver-id": vserver_id,
@@ -276,7 +340,7 @@ class HandleVnfLcmOocNotification(object):
                          % (vserver_id, self.vnf_instid, resp_status))
         except NSLCMException as e:
             logger.debug("Fail to create vserver to aai, vnf instance=[%s], detail message: %s"
-                         % (self.vnf_instid, e.message))
+                         % (self.vnf_instid, e.args[0]))
         except:
             logger.error(traceback.format_exc())
 
@@ -285,22 +349,25 @@ class HandleVnfLcmOocNotification(object):
         try:
             cloud_owner, cloud_region_id = split_vim_to_owner_region(vim_id)
             # query vim_info from aai, get tenant
-            vim_info = get_vim_by_id(vim_id)
+            vim_info = get_vim_by_id({"cloud_owner": cloud_owner, 'cloud_regionid': cloud_region_id})
             tenant_id = vim_info["tenantId"]
 
             # query vserver instance in aai, get resource_version
             vserver_info = query_vserver_aai(cloud_owner, cloud_region_id, tenant_id, vserver_id)
-            resource_version = vserver_info["resource-version"]
-
-            # delete vserver instance from aai
-            resp_data, resp_status = delete_vserver_aai(cloud_owner, cloud_region_id,
-                                                        tenant_id, vserver_id, resource_version)
-            logger.debug(
-                "Success to delete vserver instance[%s] from aai, resp_status: [%s]." %
-                (vserver_id, resp_status))
-            logger.debug("delete_vserver_in_aai end!")
+            if vserver_info:
+                resource_version = vserver_info["resource-version"]
+
+                # delete vserver instance from aai
+                resp_data, resp_status = delete_vserver_aai(cloud_owner, cloud_region_id,
+                                                            tenant_id, vserver_id, resource_version)
+                logger.debug(
+                    "Success to delete vserver instance[%s] from aai, resp_status: [%s]." %
+                    (vserver_id, resp_status))
+                logger.debug("delete_vserver_in_aai end!")
+        except RequestException:
+            logger.debug("Vserver has been deleted from aai")
         except NSLCMException as e:
-            logger.debug("Fail to delete vserver from aai, detail message: %s" % e.message)
+            logger.debug("Fail to delete vserver from aai, detail message: %s" % e.args[0])
         except:
             logger.error(traceback.format_exc())
 
@@ -325,7 +392,7 @@ class HandleVnfIdentifierCreationNotification(object):
             logger.debug("Notify VNF identifier creation end.")
         except Exception:
             logger.error(traceback.format_exc())
-            self.exception('unexpected exception')
+            exception('unexpected exception')
 
 
 class HandleVnfIdentifierDeletionNotification(object):
@@ -333,7 +400,7 @@ class HandleVnfIdentifierDeletionNotification(object):
         logger.debug("[Notify VNF Identifier Deletion] vnfmId=%s, vnfInstanceId=%s, data=%s" % (vnfmId, vnfInstanceId, data))
         self.vnfm_id = vnfmId
         self.m_vnf_instance_id = vnfInstanceId
-        self.vnf_instance_id = self.get_vnfinstid(self.m_vnfInstanceId, self.vnfmid)
+        self.vnf_instance_id = get_vnfinstid(self.m_vnf_instance_id, self.vnfm_id)
         self.time_stamp = ignore_case_get(data, 'timeStamp')
         # TODO: self.subscription_id = ignore_case_get(data, 'subscriptionId')
         # TODO: self._links = ignore_case_get(data, '_links')
@@ -347,4 +414,18 @@ class HandleVnfIdentifierDeletionNotification(object):
             logger.debug("Notify VNF identifier deletion end.")
         except Exception:
             logger.error(traceback.format_exc())
-            self.exception('unexpected exception')
+            exception('unexpected exception')
+
+
+def get_vnfinstid(mnfinstid, vnfm_inst_id):
+    logger.debug("vnfinstid in vnfm is:%s,vnfmid is:%s", mnfinstid, vnfm_inst_id)
+    logger.debug("mnfinstid=%s, vnfm_inst_id=%s", mnfinstid, vnfm_inst_id)
+    nfinst = NfInstModel.objects.filter(mnfinstid=mnfinstid, vnfm_inst_id=vnfm_inst_id).first()
+    if nfinst:
+        return nfinst.nfinstid
+    raise NSLCMException("vnfinstid not exist")
+
+
+def exception(error_msg):
+    logger.error('Notify Lcm failed, detail message: %s' % error_msg)
+    return Response(data={'error': '%s' % error_msg}, status=status.HTTP_409_CONFLICT)