- Add vnf identifier creation/deletion notification handler.
Change-Id: I53f18483b55d2ce681a17ef49d478c3421392a0f
Issue-ID: VFC-1095
Signed-off-by: laili <lai.li@zte.com.cn>
 class HandleVnfLcmOocNotification(object):
     def __init__(self, vnfmid, vnfInstanceId, data):
         logger.debug("[Notify LCM] vnfmid=%s, vnfInstanceId=%s, data=%s" % (vnfmid, vnfInstanceId, data))
-        self.vnf_instid = ''
         self.vnfmid = vnfmid
         self.m_vnfInstanceId = vnfInstanceId
+        self.vnf_instid = self.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')
 
     def do_biz(self):
         try:
-            self.vnf_instid = self.get_vnfinstid(self.m_vnfInstanceId, self.vnfmid)
             self.update_Vnfc()
             self.update_Vl()
             self.update_Cp()
                     logger.error('affectedVl struct error: resourceType not euqal network')
                     raise NSLCMException("affectedVl struct error: resourceType not euqal network")
 
-                ownerId = self.get_vnfinstid(self.m_vnfInstanceId, self.vnfmid)
+                ownerId = self.vnf_instid
 
                 if changeType in ['ADDED', 'MODIFIED']:
                     self.create_network_and_subnet_in_aai(vlInstanceId, ownerId)
             logger.debug("Fail to delete vserver from aai, detail message: %s" % e.message)
         except:
             logger.error(traceback.format_exc())
+
+
+class HandleVnfIdentifierCreationNotification(object):
+    def __init__(self, vnfmId, vnfInstanceId, data):
+        logger.debug("[Notify VNF Identifier Creation] vnfmId=%s, vnfInstanceId=%s, data=%s" % (vnfmId, vnfInstanceId, data))
+        self.vnfm_id = vnfmId
+        self.m_vnf_instance_id = vnfInstanceId
+        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')
+
+    def do_biz(self):
+        try:
+            NfInstModel(
+                nfinstid=str(uuid.uuid4()),
+                mnfinstid=self.m_vnf_instance_id,
+                vnfm_inst_id=self.vnfm_id,
+                create_time=self.time_stamp
+            ).save()
+            logger.debug("Notify VNF identifier creation end.")
+        except Exception:
+            logger.error(traceback.format_exc())
+            self.exception('unexpected exception')
+
+
+class HandleVnfIdentifierDeletionNotification(object):
+    def __init__(self, vnfmId, vnfInstanceId, data):
+        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.time_stamp = ignore_case_get(data, 'timeStamp')
+        # TODO: self.subscription_id = ignore_case_get(data, 'subscriptionId')
+        # TODO: self._links = ignore_case_get(data, '_links')
+
+    def do_biz(self):
+        try:
+            nf_insts = NfInstModel.objects.filter(
+                mnfinstid=self.m_vnf_instance_id, vnfm_inst_id=self.vnfm_id)
+            if nf_insts.exists():
+                nf_insts.delete()
+            logger.debug("Notify VNF identifier deletion end.")
+        except Exception:
+            logger.error(traceback.format_exc())
+            self.exception('unexpected exception')
 
         help_text="Identifier of this notification.",
         required=True
     )
-    notificationType = serializers.CharField(
+    notificationType = serializers.ChoiceField(
         help_text="Discriminator for the different notification types.",
+        choices=[
+            'VnfLcmOperationOccurrenceNotification',
+            'VnfIdentifierCreationNotification',
+            'VnfIdentifierDeletionNotification'
+        ],
         required=True
     )
     subscriptionId = serializers.CharField(
         allow_null=False,
         allow_blank=False
     )
-    notificationType = serializers.CharField(
-        help_text="Discriminator for the different notification types. \
-        Shall be set to VnfIdentifierCreationNotification for this notification type.",
-        required=True,
-        allow_null=False,
-        allow_blank=False
+    notificationType = serializers.ChoiceField(
+        help_text="Discriminator for the different notification types.",
+        choices=[
+            'VnfLcmOperationOccurrenceNotification',
+            'VnfIdentifierCreationNotification',
+            'VnfIdentifierDeletionNotification'
+        ],
+        required=True
     )
     subscriptionId = serializers.CharField(
         help_text="Identifier of the subscription that this notification relates to.",
         allow_null=False,
         allow_blank=False
     )
-    notificationType = serializers.CharField(
-        help_text="Discriminator for the different notification types. \
-        Shall be set to VnfIdentifierDeletionNotification for this notification type.",
-        required=True,
-        allow_null=False,
-        allow_blank=False
+    notificationType = serializers.ChoiceField(
+        help_text="Discriminator for the different notification types.",
+        choices=[
+            'VnfLcmOperationOccurrenceNotification',
+            'VnfIdentifierCreationNotification',
+            'VnfIdentifierDeletionNotification'
+        ],
+        required=True
     )
     subscriptionId = serializers.CharField(
         help_text="Identifier of the subscription that this notification relates to.",
 
     def test_notify_vnf_normal(self):
         data = {
             "id": "string",
-            "notificationType": "string",
+            "notificationType": "VnfLcmOperationOccurrenceNotification",
             "subscriptionId": "string",
             "timeStamp": "string",
             "notificationStatus": "START",
 
 from lcm.ns_vnfs.views.views import LcmNotify, NfScaleView, NfVerifyView
 from lcm.ns_vnfs.views.views import NfView, NfDetailView, NfGrant, NfPlacement, NfTerminate
 from lcm.ns_vnfs.views.views import NfVnfmInfoView, NfVimInfoView
-from lcm.ns_vnfs.views.grant_vnf_views import VnfGrantView, VnfNotifyView
+from lcm.ns_vnfs.views.vnf_views import VnfGrantView, VnfNotifyView
 
 urlpatterns = [
     url(r'^api/nslcm/v1/ns/vnfs$', NfView.as_view()),
 
 from rest_framework.views import APIView
 
 from lcm.ns_vnfs.biz.grant_vnf import GrantVnf
-from lcm.ns_vnfs.biz.handle_vnflcmooc_notification import HandleVnfLcmOocNotification
+from lcm.ns_vnfs.biz.handle_notification import HandleVnfLcmOocNotification, HandleVnfIdentifierCreationNotification, HandleVnfIdentifierDeletionNotification
 from lcm.ns_vnfs.serializers.grant_vnf_serializer import GrantRequestSerializer
 from lcm.ns_vnfs.serializers.grant_vnf_serializer import GrantSerializer
-from lcm.ns_vnfs.serializers.grant_vnf_serializer import VnfLcmOperationOccurrenceNotificationSerializer
+from lcm.ns_vnfs.serializers.grant_vnf_serializer import VnfLcmOperationOccurrenceNotificationSerializer, VnfIdentifierCreationNotificationSerializer, VnfIdentifierDeletionNotificationSerializer
 
 logger = logging.getLogger(__name__)
 
     def post(self, request):
         logger.debug("VnfGrantView Post: %s" % request.data)
         try:
-            req_serializer = GrantRequestSerializer(data=request.data)
-            if not req_serializer.is_valid():
-                raise Exception(req_serializer.errors)
+            grant_request = GrantRequestSerializer(data=request.data)
+            if not grant_request.is_valid():
+                raise Exception(grant_request.errors)
 
             grant_resp = GrantVnf(request.data).exec_grant()
 
     def post(self, request, vnfmId, vnfInstanceId):
         logger.debug("VnfNotifyView post: %s" % request.data)
         logger.debug("vnfmId: %s vnfInstanceId: %s", vnfmId, vnfInstanceId)
+        notification_type = request.data['notificationType']
         try:
-            vnfLcmOocNotificationSerializer = VnfLcmOperationOccurrenceNotificationSerializer(data=request.data)
-            if not vnfLcmOocNotificationSerializer.is_valid():
-                raise Exception(vnfLcmOocNotificationSerializer.errors)
-
-            HandleVnfLcmOocNotification(vnfmId, vnfInstanceId, vnfLcmOocNotificationSerializer.data).do_biz()
+            if notification_type == 'VnfLcmOperationOccurrenceNotification':
+                notification = VnfLcmOperationOccurrenceNotificationSerializer(data=request.data)
+                if not notification.is_valid():
+                    raise Exception(notification.errors)
+                HandleVnfLcmOocNotification(vnfmId, vnfInstanceId, notification.data).do_biz()
+            elif notification_type == 'VnfIdentifierCreationNotification':
+                notification = VnfIdentifierCreationNotificationSerializer(data=request.data)
+                if not notification.is_valid():
+                    raise Exception(notification.errors)
+                HandleVnfIdentifierCreationNotification(vnfmId, vnfInstanceId, notification.data).do_biz()
+            elif notification_type == 'VnfIdentifierDeletionNotification':
+                notification = VnfIdentifierDeletionNotificationSerializer(data=request.data)
+                if not notification.is_valid():
+                    raise Exception(notification.errors)
+                HandleVnfIdentifierDeletionNotification(vnfmId, vnfInstanceId, notification.data).do_biz()
+            else:
+                raise Exception('Unexpected noitifcation type value.')
             return Response(data={}, status=status.HTTP_204_NO_CONTENT)
         except Exception as e:
             logger.error(traceback.format_exc())