code of applay grant
authorying.yunlong <ying.yunlong@zte.com.cn>
Fri, 10 Feb 2017 06:52:09 +0000 (14:52 +0800)
committerying.yunlong <ying.yunlong@zte.com.cn>
Fri, 10 Feb 2017 06:52:09 +0000 (14:52 +0800)
Change-Id: Ie9fdb86171522a99b7602c8f4b32cf803cdd9369
Issue-Id: GVNFM-8
Signed-off-by: ying.yunlong <ying.yunlong@zte.com.cn>
lcm/lcm/nf/vnfs/tests/test_vnf_create.py
lcm/lcm/nf/vnfs/views.py
lcm/lcm/nf/vnfs/vnf_create/inst_vnf.py
lcm/lcm/pub/msapi/nfvolcm.py

index 185c829..3819d0c 100644 (file)
@@ -105,7 +105,7 @@ class TestNsInstantiate(TestCase):
         response = self.client.post("/gvnfmapi/lcm/v1/vnf_instances/12/instantiate", data={}, format='json')
         self.failUnlessEqual(status.HTTP_202_ACCEPTED, response.status_code)
 
-    def test_instantiate_vnf_when_instid_not_exist(self):
+    def test_instantiate_vnf_when_inst_id_not_exist(self):
         self.nf_inst_id = str(uuid.uuid4())
         self.job_id = JobUtil.create_job('NF', 'CREATE', self.nf_inst_id)
         JobUtil.add_job_status(self.job_id, 0, "INST_VNF_READY")
@@ -145,13 +145,33 @@ class TestNsInstantiate(TestCase):
         InstVnf(data, nf_inst_id=self.nf_inst_id, job_id=self.job_id).run()
         self.assert_job_result(self.job_id, 255, "Nfvo was not registered")
 
+    @mock.patch.object(restcall, 'call_req')
+    def test_instantiate_vnf_when_applay_grant_failed(self, mock_call_req):
+        NfvoRegInfoModel.objects.create(nfvoid='nfvo111', vnfminstid='vnfm111', apiurl='http://10.74.44.11',
+                                        nfvouser='root', nfvopassword='root123')
+        r1 = [0, json.JSONEncoder().encode(vnfd_model_dict), '200']
+        r2 = [0, json.JSONEncoder().encode(vnfd_model_dict), '200']
+        r3 = [1, json.JSONEncoder().encode(''), '200']
+        mock_call_req.side_effect = [r1, r2, r3]
+        create_data = {
+            "vnfdId": "111",
+            "vnfInstanceName": "vFW_01",
+            "vnfInstanceDescription": " vFW in Nanjing TIC Edge"}
+        self.nf_inst_id = CreateVnf(create_data).do_biz()
+        self.job_id = JobUtil.create_job('NF', 'CREATE', self.nf_inst_id)
+        JobUtil.add_job_status(self.job_id, 0, "INST_VNF_READY")
+        data = inst_req_data
+        InstVnf(data, nf_inst_id=self.nf_inst_id, job_id=self.job_id).run()
+        self.assert_job_result(self.job_id, 255, "Nf instancing apply grant exception")
+
     @mock.patch.object(restcall, 'call_req')
     def test_instantiate_vnf_success(self, mock_call_req):
         NfvoRegInfoModel.objects.create(nfvoid='nfvo111', vnfminstid='vnfm111', apiurl='http://10.74.44.11',
                                         nfvouser='root', nfvopassword='root123')
         r1 = [0, json.JSONEncoder().encode(vnfd_model_dict), '200']
         r2 = [0, json.JSONEncoder().encode(vnfd_model_dict), '200']
-        mock_call_req.side_effect = [r1, r2]
+        r3 = [0, json.JSONEncoder().encode(''), '200']
+        mock_call_req.side_effect = [r1, r2, r3]
         create_data = {
             "vnfdId": "111",
             "vnfInstanceName": "vFW_01",
index d1818a5..1862b3c 100644 (file)
@@ -50,7 +50,7 @@ class InstantiateVnf(APIView):
                 'localizationLanguage': ignore_case_get(request.data, 'localizationLanguage'),
                 'additionalParams': ignore_case_get(request.data, 'additionalParams')}
         nf_inst_id = instanceId
-        job_id = JobUtil.create_job('NF', 'CREATE', nf_inst_id)
+        job_id = JobUtil.create_job('NF', 'INSTANTIATE', nf_inst_id)
         JobUtil.add_job_status(job_id, 0, "INST_VNF_READY")
 
         InstVnf(data, nf_inst_id, job_id).start()
index 0bfeda8..2225ddc 100644 (file)
@@ -18,7 +18,7 @@ from threading import Thread
 
 from lcm.pub.database.models import NfInstModel, JobStatusModel, NfvoRegInfoModel
 from lcm.pub.exceptions import NFLCMException
-from lcm.pub.msapi.nfvolcm import vnfd_rawdata_get
+from lcm.pub.msapi.nfvolcm import vnfd_rawdata_get, apply_grant_to_nfvo
 from lcm.pub.utils.jobutil import JobUtil
 
 logger = logging.getLogger(__name__)
@@ -30,16 +30,23 @@ class InstVnf(Thread):
         self.data = data
         self.nf_inst_id = nf_inst_id
         self.job_id = job_id
+        self.nfvo_inst_id = ''
+        self.vnfm_inst_id = ''
+
 
     def run(self):
         try:
             self.inst_pre(self.nf_inst_id)
 
-            # self.apply_grant(args)
+            self.apply_grant()
+
             # self.apply_res(args)
             # self.check_res_status(args)
             # self.wait_inst_finish(args)
             # self.lcm_notify(args)
+            JobUtil.add_job_status(self.job_id, 100, "Instantiate Vnf success.")
+            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
@@ -57,6 +64,7 @@ class InstVnf(Thread):
             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.")
@@ -66,30 +74,47 @@ class InstVnf(Thread):
         ret = vnfd_rawdata_get(vnf_inst.vnfdid)
         if ret[0] != 0:
             raise NFLCMException("Get vnfd_raw_data failed.")
-        dst_plan = json.JSONDecoder().decode(ret[1])
+        self.vnfd_info = json.JSONDecoder().decode(ret[1])
         #checkParameterExist
         for cp in self.data:
-            if cp not in dst_plan:
+            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.')
-
-        JobUtil.add_job_status(self.job_id, 2, 'GET_NFVO_CONNECTION_INFO')
-        self.load_global_config()
-
-        JobUtil.add_job_status(self.job_id, 100, "Instantiate Vnf success.")
-        is_exist = JobStatusModel.objects.filter(jobid=self.job_id).exists()
-        logger.debug("check_ns_inst_name_exist::is_exist=%s" % is_exist)
-
-    def apply_grant(self, args):
-        try:
-            logger.info('apply_grant, args=%s' % args)
-            # ApplyGrantTask(args).do_biz()
-            return {'result': '100', 'msg': 'Nf instancing apply grant finish', 'context': {}}
-        except Exception as e:
-            logger.error('Nf instancing apply grant exception=%s' % e.message)
-            logger.error(traceback.format_exc())
-            return {'result': '255', 'msg': 'Nf instancing apply grant exception', 'context': {}}
+        #get nfvo info
+        JobUtil.add_job_status(self.job_id, 5, 'GET_NFVO_CONNECTION_INFO')
+        self.load_nfvo_config()
+
+    def apply_grant(self):
+        logger.info('[NF instantiation] send resource grand request to nfvo start')
+        #self.check_vm_capacity()
+        content_args = {'nfvoInstanceId': self.nfvo_inst_id, 'vnfmInstanceId': self.vnfm_inst_id,
+                        'nfInstanceId': self.nf_inst_id, 'nfDescriptorId': '',
+                        'lifecycleOperation': 'Instantiate', 'jobId': self.job_id, 'addResource': [],
+                        'removeResource': [], 'placementConstraint': [], 'exVimIdList': [], 'additionalParam': {}}
+
+        vdus = self.vnfd_info['vdus']
+        res_index = 1
+        for vdu in vdus:
+            res_def = {'type': 'VDU', 'resourceDefinitionId': str(res_index), 'vduId': vdu['vdu_id'],
+                       'vimid': '', 'tenant': ''}
+            if self.vnfd_info['metadata']['cross_dc']:
+                res_def['vimid'] = vdu['properties']['location_info']['vimId']
+                res_def['tenant'] = vdu['properties']['location_info']['tenant']
+            content_args['addResource'].append(res_def)
+            res_index += 1
+        logger.info('content_args=%s' % content_args)
+        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()
+        JobUtil.add_job_status(self.job_id, 15, 'Nf instancing apply grant finish')
+        logger.info("Nf instancing apply grant finish")
 
     def apply_res(self, args):
         try:
@@ -141,13 +166,13 @@ class InstVnf(Thread):
             logger.error(traceback.format_exc())
             return {'result': '255', 'msg': 'Nf instancing exception process exception', 'context': {}}
 
-    def load_global_config(self):
+    def load_nfvo_config(self):
         logger.info("[NF instantiation]get nfvo connection info start")
         reg_info = NfvoRegInfoModel.objects.filter(vnfminstid='vnfm111').first()
         if reg_info:
-            self.nfvo_reg_info = reg_info.nfvoid
-            logger.info("[NF instantiation] Registered nfvo id is [%s]"%self.nfvo_reg_info)
+            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")
\ No newline at end of file
+        logger.info("[NF instantiation]get nfvo connection info end")
index 04b1227..755f335 100644 (file)
@@ -18,4 +18,8 @@ from lcm.pub.utils.restcall import req_by_msb
 
 def vnfd_rawdata_get(vnfdid):
     ret = req_by_msb("openoapi/nslcm/v1/vnfpackage/%s" % vnfdid, "GET")
+    return ret
+
+def apply_grant_to_nfvo(data):
+    ret = req_by_msb("openoapi/nslcm/v1/vnfpackage" , "GET", data)
     return ret
\ No newline at end of file