Optimized code of GVNFM
authorying.yunlong <ying.yunlong@zte.com.cn>
Sat, 11 Feb 2017 00:51:54 +0000 (08:51 +0800)
committerying.yunlong <ying.yunlong@zte.com.cn>
Sat, 11 Feb 2017 00:51:54 +0000 (08:51 +0800)
Change-Id: Ib846c7311933e5766526201d95d598cee5032d53
Issue-Id: GVNFM-6
Signed-off-by: ying.yunlong <ying.yunlong@zte.com.cn>
lcm/lcm/nf/vnfs/urls.py
lcm/lcm/nf/vnfs/views.py
lcm/lcm/nf/vnfs/vnf_create/create_vnf_identifier.py
lcm/lcm/nf/vnfs/vnf_create/inst_vnf.py
lcm/lcm/pub/msapi/nfvolcm.py

index 4a64bdf..d07dc4f 100644 (file)
 from django.conf.urls import patterns, url
 from rest_framework.urlpatterns import format_suffix_patterns
 
-from lcm.nf.vnfs.views import CreateVnfIdentifier, InstantiateVnf, DeleteVnfIdentifier, QueryMultipleVnf, TerminateVnf, \
-    QuerySingleVnf, GetOperationStatus
+from lcm.nf.vnfs.views import CreateVnfIdentifier, InstantiateVnf, DeleteVnfIdentifier, QueryMultipleVnf,\
+    TerminateVnf, QuerySingleVnf, GetOperationStatus
 
 urlpatterns = patterns('',
                        url(r'^gvnfmapi/lcm/v1/vnf_instances$', CreateVnfIdentifier.as_view()),
-                       url(r'^gvnfmapi/lcm/v1/vnf_instances/(?P<instanceId>[0-9a-zA-Z_-]+)/instantiate$', InstantiateVnf.as_view()),
+                       url(r'^gvnfmapi/lcm/v1/vnf_instances/(?P<instanceId>[0-9a-zA-Z_-]+)/instantiate$',
+                           InstantiateVnf.as_view()),
                        url(r'^gvnfmapi/lcm/v1/vnf_instances/(?P<instanceId>[0-9a-zA-Z_-]+)$',
                            DeleteVnfIdentifier.as_view()),
                        url(r'^gvnfmapi/lcm/v1/vnf_instances/(?P<instanceId>[0-9a-zA-Z_-]+)/terminate$',
                            TerminateVnf.as_view()),
                        url(r'^gvnfmapi/lcm/v1/vnf_instances$', QueryMultipleVnf.as_view()),
                        url(r'^gvnfmapi/lcm/v1/vnf_instances/(?P<instanceId>[0-9a-zA-Z_-]+)$', QuerySingleVnf.as_view()),
-                       url(
-                           r'^gvnfmapi/lcm/v1/vnf_lc_ops/(?P<vnfLcOpId>[0-9a-zA-Z_-]+)&responseId=(?P<responseId>[0-9a-zA-Z_-]+)$',
-                           GetOperationStatus.as_view()),
+                       url(r'^gvnfmapi/lcm/v1/vnf_lc_ops/(?P<vnfLcOpId>[0-9a-zA-Z_-]+)&'
+                           r'responseId=(?P<responseId>[0-9a-zA-Z_-]+)$', GetOperationStatus.as_view()),
                        )
 
-urlpatterns = format_suffix_patterns(urlpatterns)
\ No newline at end of file
+urlpatterns = format_suffix_patterns(urlpatterns)
index 1862b3c..6dbdb73 100644 (file)
@@ -13,6 +13,7 @@
 # limitations under the License.
 
 import logging
+import traceback
 
 from rest_framework import status
 from rest_framework.response import Response
@@ -20,8 +21,8 @@ from rest_framework.views import APIView
 
 from lcm.nf.vnfs.vnf_create.create_vnf_identifier import CreateVnf
 from lcm.nf.vnfs.vnf_create.inst_vnf import InstVnf
+from lcm.pub.exceptions import NFLCMException
 from lcm.pub.utils.jobutil import JobUtil
-from lcm.pub.utils.values import ignore_case_get
 
 logger = logging.getLogger(__name__)
 
@@ -29,31 +30,24 @@ logger = logging.getLogger(__name__)
 class CreateVnfIdentifier(APIView):
     def post(self, request):
         logger.debug("CreateVnfIdentifier--post::> %s" % request.data)
-        data = {}
-        data["vnfdId"] = ignore_case_get(request.data, "vnfdId")
-        data["vnfInstanceName"] = ignore_case_get(request.data, "vnfInstanceName")
-        data["vnfInstanceDescription"] = ignore_case_get(request.data, "vnfInstanceDescription")
         try:
-            self.nf_inst_id = CreateVnf(data).do_biz()
-        except Exception as e:
+            nf_inst_id = CreateVnf(request.data).do_biz()
+        except NFLCMException as e:
+            logger.error(e.message)
             return Response(data={'error': '%s' % e.message}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
-        rsp = {"vnfInstanceId": self.nf_inst_id}
+        except Exception:
+            logger.error(traceback.format_exc())
+            return Response(data='unexpected exception', status=status.HTTP_500_INTERNAL_SERVER_ERROR)
+        rsp = {"vnfInstanceId": nf_inst_id}
         return Response(data=rsp, status=status.HTTP_201_CREATED)
 
 
 class InstantiateVnf(APIView):
     def post(self, request, instanceId):
         logger.debug("InstantiateVnf--post::> %s" % request.data)
-        data = {'flavourId': ignore_case_get(request.data, 'flavourId'),
-                'instantiationLevelId': ignore_case_get(request.data, 'instantiationLevelId'),
-                'extVirtualLinks': ignore_case_get(request.data, 'extVirtualLinks'),
-                'localizationLanguage': ignore_case_get(request.data, 'localizationLanguage'),
-                'additionalParams': ignore_case_get(request.data, 'additionalParams')}
-        nf_inst_id = instanceId
-        job_id = JobUtil.create_job('NF', 'INSTANTIATE', nf_inst_id)
+        job_id = JobUtil.create_job('NF', 'INSTANTIATE', instanceId)
         JobUtil.add_job_status(job_id, 0, "INST_VNF_READY")
-
-        InstVnf(data, nf_inst_id, job_id).start()
+        InstVnf(request.data, instanceId, job_id).start()
         rsp = {"jobId": job_id}
         return Response(data=rsp, status=status.HTTP_202_ACCEPTED)
 
@@ -85,4 +79,4 @@ class QuerySingleVnf(APIView):
 class GetOperationStatus(APIView):
     def get(self, request):
         logger.debug("GetOperationStatus--get::> %s" % request.data)
-        return Response(data='', status=status.HTTP_202_ACCEPTED)
\ No newline at end of file
+        return Response(data='', status=status.HTTP_202_ACCEPTED)
index b427e66..96ab163 100644 (file)
@@ -27,39 +27,36 @@ logger = logging.getLogger(__name__)
 class CreateVnf:
     def __init__(self, data):
         self.data = data
-
-    def do_biz(self):
-        logger.debug("CreateVnfIdentifier--CreateVnf::> %s" % self.data)
         self.vnfd_id = ignore_case_get(self.data, "vnfdId")
         self.vnf_instance_mame = ignore_case_get(self.data, "vnfInstanceName")
         self.description = ignore_case_get(self.data, "vnfInstanceDescription")
+
+    def do_biz(self):
+        logger.debug("CreateVnfIdentifier--CreateVnf::> %s" % self.data)
         is_exist = NfInstModel.objects.filter(nf_name=self.vnf_instance_mame).exists()
-        logger.debug("check_ns_inst_name_exist::is_exist=%s" % is_exist)
+        logger.debug("check_inst_name_exist::is_exist=%s" % is_exist)
         if is_exist:
             raise NFLCMException('VNF is already exist.')
 
-        #get rawdata by vnfd_id
         ret = vnfd_rawdata_get(self.vnfd_id)
         if ret[0] != 0:
-            raise NFLCMException('Get vnfd_raw_data failed.')
-        dst_plan = json.JSONDecoder().decode(ret[1])
-        self.vnfd_version = dst_plan['metadata']['vnfd_version']
-        self.vendor = dst_plan['metadata']['vendor']
-        self.producttype = dst_plan['metadata']['domain_type']
-        self.netype = dst_plan['metadata']['vnf_type']
-        self.vnfd_model = dst_plan
-        self.vnfSoftwareVersion = dst_plan['metadata']['version']
+            raise NFLCMException('Get vnfd data failed.')
+        vnfd_info = json.JSONDecoder().decode(ret[1])
+        vnfd_version = vnfd_info['metadata']['vnfd_version']
+        vendor = vnfd_info['metadata']['vendor']
+        producttype = vnfd_info['metadata']['domain_type']
+        netype = vnfd_info['metadata']['vnf_type']
+        vnfd_model = vnfd_info
+        vnfsoftwareversion = vnfd_info['metadata']['version']
 
-        self.nf_inst_id = str(uuid.uuid4())
-        NfInstModel.objects.create(nfinstid=self.nf_inst_id, mnfinstid=self.nf_inst_id, nf_name=self.vnf_instance_mame,
-                                   package_id='todo', vnfm_inst_id='todo', version=self.vnfd_version, vendor=self.vendor,
-                                   producttype=self.producttype,netype=self.netype, vnfd_model=self.vnfd_model,
+        nf_inst_id = str(uuid.uuid4())
+        NfInstModel.objects.create(nfinstid=nf_inst_id, mnfinstid=nf_inst_id, nf_name=self.vnf_instance_mame,
+                                   package_id='todo', vnfm_inst_id='todo', version=vnfd_version, vendor=vendor,
+                                   producttype=producttype, netype=netype, vnfd_model=vnfd_model,
                                    instantiationState='NOT_INSTANTIATED', nf_desc=self.description, vnfdid=self.vnfd_id,
-                                   vnfSoftwareVersion=self.vnfSoftwareVersion, vnfConfigurableProperties='todo',
-                                   localizationLanguage='EN_US',create_time=now_time())
-        is_exist = NfInstModel.objects.filter(nf_name=self.vnf_instance_mame).exists()
-        logger.debug("check_ns_inst_name_exist::is_exist=%s" % is_exist)
-        vnf_inst = NfInstModel.objects.get(nfinstid=self.nf_inst_id)
+                                   vnfSoftwareVersion=vnfsoftwareversion, vnfConfigurableProperties='todo',
+                                   localizationLanguage='EN_US', create_time=now_time())
+        vnf_inst = NfInstModel.objects.get(nfinstid=nf_inst_id)
         logger.debug('id is [%s],name is [%s],vnfd_id is [%s],description is [%s],create_time is [%s]' %
-            (vnf_inst.nfinstid, vnf_inst.nf_name, vnf_inst.vnfdid, vnf_inst.nf_desc, vnf_inst.create_time))
-        return self.nf_inst_id
\ No newline at end of file
+                     (vnf_inst.nfinstid, vnf_inst.nf_name, vnf_inst.vnfdid, vnf_inst.nf_desc, vnf_inst.create_time))
+        return nf_inst_id
index 2225ddc..9340a73 100644 (file)
@@ -20,6 +20,7 @@ from lcm.pub.database.models import NfInstModel, JobStatusModel, NfvoRegInfoMode
 from lcm.pub.exceptions import NFLCMException
 from lcm.pub.msapi.nfvolcm import vnfd_rawdata_get, apply_grant_to_nfvo
 from lcm.pub.utils.jobutil import JobUtil
+from lcm.pub.utils.timeutil import now_time
 
 logger = logging.getLogger(__name__)
 
@@ -33,13 +34,10 @@ class InstVnf(Thread):
         self.nfvo_inst_id = ''
         self.vnfm_inst_id = ''
 
-
     def run(self):
         try:
-            self.inst_pre(self.nf_inst_id)
-
+            self.inst_pre()
             self.apply_grant()
-
             # self.apply_res(args)
             # self.check_res_status(args)
             # self.wait_inst_finish(args)
@@ -48,38 +46,30 @@ class InstVnf(Thread):
             is_exist = JobStatusModel.objects.filter(jobid=self.job_id).exists()
             logger.debug("check_ns_inst_name_exist::is_exist=%s" % is_exist)
         except NFLCMException as e:
-            self.inst_exception(e.message)
-            pass
-        except Exception:
+            self.vnf_inst_failed_handle(e.message)
+            # self.rollback(e.message)
+        except:
+            self.vnf_inst_failed_handle('unexpected exception')
             logger.error(traceback.format_exc())
-            self.inst_exception('unexpected exception')
-
-    def inst_pre(self, args):
-        logger.info('inst_pre, args=%s' % args)
-        is_exist = NfInstModel.objects.filter(nfinstid=self.nf_inst_id).exists()
-        logger.debug("check_ns_inst_name_exist::is_exist=%s" % is_exist)
-        if not is_exist:
-            logger.error("VNF nf_inst_id is not exist.")
-            JobUtil.add_job_status(self.job_id, 255, "VNF nf_inst_id is not exist.")
+            # self.rollback('unexpected exception')
+
+    def inst_pre(self):
+        vnf_insts = NfInstModel.objects.filter(nfinstid=self.nf_inst_id)
+        if not vnf_insts.exists():
             raise NFLCMException('VNF nf_inst_id is not exist.')
 
-        vnf_inst = NfInstModel.objects.get(nfinstid=self.nf_inst_id)
-        self.vnfm_inst_id = vnf_inst.vnfm_inst_id
-        if vnf_inst.instantiationState != 'NOT_INSTANTIATED':
-            logger.error("VNF instantiationState is not NOT_INSTANTIATED.")
-            JobUtil.add_job_status(self.job_id, 255, "VNF instantiationState is not NOT_INSTANTIATED.")
+        self.vnfm_inst_id = vnf_insts[0].vnfm_inst_id
+        if vnf_insts[0].instantiationState != 'NOT_INSTANTIATED':
             raise NFLCMException('VNF instantiationState is not NOT_INSTANTIATED.')
 
         #get rawdata by vnfd_id
-        ret = vnfd_rawdata_get(vnf_inst.vnfdid)
+        ret = vnfd_rawdata_get(vnf_insts[0].vnfdid)
         if ret[0] != 0:
             raise NFLCMException("Get vnfd_raw_data failed.")
         self.vnfd_info = json.JSONDecoder().decode(ret[1])
         #checkParameterExist
         for cp in self.data:
             if cp not in self.vnfd_info:
-                logger.error("[%s] is not defined in vnfd_info."%cp)
-                JobUtil.add_job_status(self.job_id, 255, "Input parameter is not defined in vnfd_info.")
                 raise NFLCMException('Input parameter is not defined in vnfd_info.')
         #get nfvo info
         JobUtil.add_job_status(self.job_id, 5, 'GET_NFVO_CONNECTION_INFO')
@@ -107,9 +97,6 @@ class InstVnf(Thread):
         resp = apply_grant_to_nfvo(content_args)
         logger.info("[NF instantiation] get grant response = %s" % resp)
         if resp[0] != 0:
-            err_msg = str(resp[1])
-            logger.error("Nf instancing apply grant exception.[%s]" % err_msg)
-            JobUtil.add_job_status(self.job_id, 255, 'Nf instancing apply grant exception')
             raise NFLCMException('Nf instancing apply grant exception')
 
         #update_resources_table()
@@ -156,7 +143,7 @@ class InstVnf(Thread):
             logger.error(traceback.format_exc())
             return {'result': '255', 'msg': 'Nf instancing lcm notify exception', 'context': {}}
 
-    def inst_exception(self, args):
+    def rollback(self, args):
         try:
             logger.info('inst_exception, args=%s' % args)
             # InstExceptionTask(args).do_biz()
@@ -173,6 +160,12 @@ class InstVnf(Thread):
             self.nfvo_inst_id = reg_info.nfvoid
             logger.info("[NF instantiation] Registered nfvo id is [%s]"%self.nfvo_inst_id)
         else:
-            JobUtil.add_job_status(self.job_id, 255, "Nfvo was not registered")
             raise NFLCMException("Nfvo was not registered")
         logger.info("[NF instantiation]get nfvo connection info end")
+
+    def vnf_inst_failed_handle(self, error_msg):
+        logger.error('VNF instantiation failed, detail message: %s' % error_msg)
+        NfInstModel.objects.filter(nfinstid=self.nf_inst_id).update(status='failed', lastuptime=now_time())
+        JobUtil.add_job_status(self.job_id, 255, error_msg)
+        # JobUtil.add_job_status(self.job_id, 255, 'VNF instantiation failed, detail message: %s' % error_msg, 0)
+
index 755f335..9ea2eef 100644 (file)
 # See the License for the specific language governing permissions and
 # limitations under the License.
 
-# Query vnfd_rawdata by vnfdid
 from lcm.pub.utils.restcall import req_by_msb
 
-
+#call gvnfm driver
 def vnfd_rawdata_get(vnfdid):
-    ret = req_by_msb("openoapi/nslcm/v1/vnfpackage/%s" % vnfdid, "GET")
+    ret = req_by_msb("openoapi/nslcm/v1/vnfs/%s" % vnfdid, "GET")
     return ret
 
+#call gvnfm driver
 def apply_grant_to_nfvo(data):
-    ret = req_by_msb("openoapi/nslcm/v1/vnfpackage" , "GET", data)
+    ret = req_by_msb("openoapi/nslcm/v1/grantvnf" , "POST", data)
+    return ret
+
+#call gvnfm driver
+def notify_lcm_to_nfvo(data, nf_inst_id):
+    ret = req_by_msb("openoapi/nslcm/v1/vnfs/%s/Notify"%nf_inst_id, "POST", data)
     return ret
\ No newline at end of file