def get_servicetemplate(nsd_id): ret = req_by_msb('/openoapi/catalog/v1/servicetemplates', 'GET') if ret[0] != 0: raise NFLCMException('Failed to get servicetemplates info') stpls = json.JSONDecoder().decode(ret[1]) for stpl in stpls: if stpl["id"] == nsd_id: return stpl return NFLCMException('servicetemplate(%s) does not exist.' % nsd_id)
def check_valid_auth_info(self): logger.debug("SubscribeNotification--post::> Validating Auth " "details if provided") if self.authentication.get("paramsBasic", {}) and \ const.BASIC not in self.authentication.get("authType"): raise NFLCMException('Auth type should be ' + const.BASIC) if self.authentication.get("paramsOauth2ClientCredentials", {}) and \ const.OAUTH2_CLIENT_CREDENTIALS not in self.authentication.get("authType"): raise NFLCMException('Auth type should be ' + const.OAUTH2_CLIENT_CREDENTIALS)
def query_csar_from_catalog(csar_id, key=''): ret = req_by_msb("/openoapi/catalog/v1/csars/%s" % csar_id, "GET") if ret[0] != 0: logger.error("Status code is %s, detail is %s.", ret[2], ret[1]) if ret[2] == '404': raise NFLCMException("CSAR(%s) does not exist." % csar_id) raise NFLCMException("Failed to query CSAR(%s) from catalog." % csar_id) csar_info = json.JSONDecoder().decode(ret[1]) return ignore_case_get(csar_info, key) if key else csar_info
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.') if vnf_insts[0].status != 'NOT_INSTANTIATED': raise NFLCMException('VNF instantiationState is not NOT_INSTANTIATED.') JobUtil.add_job_status(self.job_id, 5, 'Get packageinfo by vnfd_id') self.vnfd_id = vnf_insts[0].vnfdid JobUtil.add_job_status(self.job_id, 10, 'Get vnf package info from catalog by csar_id') input_parameters = [] inputs = ignore_case_get(self.data, "additionalParams") if inputs: if isinstance(inputs, str): inputs = json.loads(inputs) for key, val in list(inputs.items()): input_parameters.append({"key": key, "value": val}) vnf_package = query_vnfpackage_by_id(self.vnfd_id) pkg_info = ignore_case_get(vnf_package, "packageInfo") self.vnfd_info = json.loads(ignore_case_get(pkg_info, "vnfdModel")) verifyvnfd.verify(self.vnfd_info) self.update_cps() metadata = ignore_case_get(self.vnfd_info, "metadata") csar_id = ignore_case_get(metadata, "id") version = ignore_case_get(metadata, "vnfdVersion") vendor = ignore_case_get(metadata, "vendor") netype = ignore_case_get(metadata, "type") vnfsoftwareversion = ignore_case_get(metadata, "version") NfInstModel.objects.filter(nfinstid=self.nf_inst_id).\ update(package_id=csar_id, flavour_id=ignore_case_get(self.data, "flavourId"), version=version, vendor=vendor, netype=netype, vnfd_model=json.dumps(self.vnfd_info), status='NOT_INSTANTIATED', vnfdid=self.vnfd_id, localizationLanguage=ignore_case_get(self.data, 'localizationLanguage'), input_params=input_parameters, vnfSoftwareVersion=vnfsoftwareversion, lastuptime=now_time()) logger.info("VimId = %s" % self.vim_id) ''' is_exist = NfvoRegInfoModel.objects.filter(nfvoid=self.nf_inst_id).exists() if not is_exist: NfvoRegInfoModel.objects.create( nfvoid=self.nf_inst_id, vnfminstid=ignore_case_get(self.data, "vnfmId"), apiurl=self.vim_id) ''' JobUtil.add_job_status(self.job_id, 15, 'Nf instancing pre-check finish') logger.info("Nf instancing pre-check finish")
def check_if_can_scale(self): cur_inst_num = VNFCInstModel.objects.filter( instid=self.nf_inst_id).count() if self.is_scale_in: if cur_inst_num - self.scale_inst_num < self.min_instance_num: msg = "VNF(%s) cannot be scaled: less than min instance." raise NFLCMException(msg % self.nf_inst_id) else: if cur_inst_num + self.scale_inst_num > self.max_instance_num: msg = "VNF(%s) cannot be scaled: max instance exceeded." raise NFLCMException(msg % self.nf_inst_id)
def heal_pre(self): if self.action not in (HEAL_ACTION_TYPE.START, HEAL_ACTION_TYPE.RESTART): raise NFLCMException("Action should be %s or %s" % (HEAL_ACTION_TYPE.START, HEAL_ACTION_TYPE.RESTART)) self.vm_id = ignore_case_get(self.affectedvm, "vmid") self.vdu_id = ignore_case_get(self.affectedvm, "vduid") self.vm_name = ignore_case_get(self.affectedvm, "vmname") if not (self.vm_id and self.vdu_id and self.vm_name): raise NFLCMException("VM identifiers is not present in request.") self.vnf_insts = NfInstModel.objects.filter(nfinstid=self.nf_inst_id) self.vnfd_info = json.loads(self.vnf_insts[0].vnfd_model)
def check_filter_types(self): logger.debug("SubscribeNotification--post::> Validating " "operationTypes and operationStates if exists") if self.operation_types and \ const.LCCNNOTIFICATION not in self.notification_types: raise NFLCMException("If you are setting operationTypes," "then notificationTypes " "must be " + const.LCCNNOTIFICATION) if self.operation_states and \ const.LCCNNOTIFICATION not in self.notification_types: raise NFLCMException("If you are setting operationStates," "then notificationTypes " "must be " + const.LCCNNOTIFICATION)
def get_process_id(name, srv_template_id): ret = req_by_msb( '/openoapi/catalog/v1/servicetemplates/%s/operations' % srv_template_id, 'GET') if ret[0] != 0: raise NFLCMException('Failed to get service[%s,%s] process id' % (name, srv_template_id)) items = json.JSONDecoder().decode(ret[1]) for item in items: if name in item['name']: return item['processId'] raise NFLCMException('service[%s,%s] process id not exist' % (name, srv_template_id))
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.') if vnf_insts[0].status != 'NOT_INSTANTIATED': raise NFLCMException('VNF instantiationState is not NOT_INSTANTIATED.') JobUtil.add_job_status(self.job_id, 5, 'Get packageinfo by vnfd_id') self.vnfd_id = vnf_insts[0].vnfdid package_info = get_packageinfo_by_vnfdid(self.vnfd_id) for val in ignore_case_get(package_info, "csars"): if self.vnfd_id == ignore_case_get(val, "vnfdId"): self.package_id = ignore_case_get(val, "csarId") break JobUtil.add_job_status(self.job_id, 10, 'Get rawdata from catalog by csar_id') input_parameters = [] inputs = ignore_case_get(self.data['additionalParams'], "inputs") if inputs: if isinstance(inputs, (str, unicode)): inputs = json.loads(inputs) for key, val in inputs.items(): input_parameters.append({"key": key, "value": val}) raw_data = query_rawdata_from_catalog(self.package_id, input_parameters) self.vnfd_info = toscautil.convert_vnfd_model(raw_data["rawData"]) # convert to inner json self.vnfd_info = json.JSONDecoder().decode(self.vnfd_info) #self.vnfd_info = vnfd_model_dict # just for test self.update_cps() self.check_parameter_exist() metadata = ignore_case_get(self.vnfd_info, "metadata") version = ignore_case_get(metadata, "vnfd_version") vendor = ignore_case_get(metadata, "vendor") netype = ignore_case_get(metadata, "vnf_type") vnfsoftwareversion = ignore_case_get(metadata, "version") vnfd_model = self.vnfd_info NfInstModel.objects.filter(nfinstid=self.nf_inst_id).\ update(package_id=self.package_id, flavour_id=ignore_case_get(self.data, "flavourId"), version=version, vendor=vendor, netype=netype, vnfd_model=vnfd_model, status='NOT_INSTANTIATED', vnfdid=self.vnfd_id, localizationLanguage=ignore_case_get(self.data, 'localizationLanguage'), input_params=self.data, vnfSoftwareVersion=vnfsoftwareversion, lastuptime=now_time()) logger.info("self.vim_id = %s" % self.vim_id) NfvoRegInfoModel.objects.create(nfvoid=self.nf_inst_id, vnfminstid=ignore_case_get(self.data, "vnfmId"), apiurl=self.vim_id) JobUtil.add_job_status(self.job_id, 15, 'Nf instancing pre-check finish') logger.info("Nf instancing pre-check finish")
def scale_pre(self): self.vnfd_info = json.loads(self.vnf_insts[0].vnfd_model) scale_in_vms = VmInstModel.objects.filter(instid=self.nf_inst_id) vms_num = scale_in_vms.count() self.instantiation_level_id = self.data.get("instantiationLevelId") self.additional_params = self.data.get("additionalParams", {}) if not self.instantiation_level_id: self.scale_info = self.data.get("scaleInfo") self.aspect_id = self.scale_info.get("aspectId") self.instantiation_level_id = self.get_instantiation_level_id() else: self.aspect_id = self.get_aspect_id() number_of_instances = self.get_number_of_instances() if number_of_instances == vms_num: raise NFLCMException("Don't need scale in/out.") elif number_of_instances > vms_num: self.scale_type = GRANT_TYPE.SCALE_OUT else: self.scale_type = GRANT_TYPE.SCALE_IN self.scale_inst_num = abs(number_of_instances - vms_num) self.is_scale_in = (self.scale_type == GRANT_TYPE.SCALE_IN) self.step_delta = self.get_scale_step_delta() self.target_vdu, self.step_inst_num = self.get_vdu_scale_aspect_deltas( ) self.min_instance_num, self.max_instance_num = self.get_instance_range( ) self.check_if_can_scale() self.scale_out_resource = {}
def query_single_subscription(self): subscription = SubscriptionModel.objects.filter( subscription_id=self.subscription_id) if not subscription.exists(): raise NFLCMException('Subscription(%s) does not exist' % self.subscription_id) return self.fill_resp_data(subscription)
def query_single_vnf(self): vnf_inst = NfInstModel.objects.filter(nfinstid=self.vnf_inst_id) if not vnf_inst.exists(): raise NFLCMException('VnfInst(%s) does not exist' % self.vnf_inst_id) resp_data = self.fill_resp_data(vnf_inst[0]) return resp_data
def notify_lcm_to_nfvo(data): ret = req_by_msb('api/gvnfmdriver/v1/vnfs/lifecyclechangesnotification', 'POST', data) if ret[0] != 0: logger.error('Status code is %s, detail is %s.', ret[2], ret[1]) raise NFLCMException('Nf lcm notify exception') return ret[1]
def get_packageinfo_by_vnfdid(vnfdid): ret = req_by_msb('api/gvnfmdriver/v1/vnfpackages', 'GET') if ret[0] != 0: logger.error('Status code is %s, detail is %s.', ret[2], ret[1]) raise NFLCMException( 'Failed to query package_info of vnfdid(%s) from nslcm.' % vnfdid) return json.JSONDecoder().decode(ret[1])
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_inst_name_exist::is_exist=%s" % is_exist) if is_exist: raise NFLCMException('VNF is already exist.') nf_inst_id = str(uuid.uuid4()) try: self.package_info = get_packageinfo_by_vnfdid(self.vnfd_id) for val in ignore_case_get(self.package_info, "csars"): if self.vnfd_id == ignore_case_get(val, "vnfdId"): self.package_id = ignore_case_get(val, "csarId") break raw_data = query_rawdata_from_catalog(self.package_id) self.vnfd = toscautil.convert_vnfd_model( raw_data["rawData"]) # convert to inner json self.vnfd = json.JSONDecoder().decode(self.vnfd) metadata = ignore_case_get(self.vnfd, "metadata") version = ignore_case_get(metadata, "vnfd_version") vendor = ignore_case_get(metadata, "vendor") netype = ignore_case_get(metadata, "vnf_type") vnfsoftwareversion = ignore_case_get(metadata, "version") vnfd_model = self.vnfd NfInstModel.objects.create(nfinstid=nf_inst_id, nf_name=self.vnf_instance_mame, package_id=self.package_id, version=version, vendor=vendor, netype=netype, vnfd_model=vnfd_model, status='NOT_INSTANTIATED', nf_desc=self.description, vnfdid=self.vnfd_id, vnfSoftwareVersion=vnfsoftwareversion, create_time=now_time()) except: NfInstModel.objects.create(nfinstid=nf_inst_id, nf_name=self.vnf_instance_mame, package_id='', version='', vendor='', netype='', vnfd_model='', status='NOT_INSTANTIATED', nf_desc=self.description, vnfdid=self.vnfd_id, vnfSoftwareVersion='', 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],vnfd_model is [%s],' 'description is [%s],create_time is [%s]' % (vnf_inst.nfinstid, vnf_inst.nf_name, vnf_inst.vnfdid, vnf_inst.vnfd_model, vnf_inst.nf_desc, vnf_inst.create_time)) return nf_inst_id
def query_vnfpackage_by_id(csar_id): ret = req_by_msb("/api/catalog/v1/vnfpackages/%s" % csar_id, "GET") if ret[0] != 0: logger.error("Status code is %s, detail is %s.", ret[2], ret[1]) raise NFLCMException("Failed to query vnf CSAR(%s) from catalog." % csar_id) return json.JSONDecoder().decode(ret[1])
def get_packageinfo_by_vnfdid(vnfdid): ret = req_by_msb("openoapi/gvnfmdriver/v1/vnfpackages", "GET") # TODO if ret[0] != 0: logger.error("Status code is %s, detail is %s.", ret[2], ret[1]) raise NFLCMException( "Failed to query package_info of vnfdid(%s) from nslcm." % vnfdid) return json.JSONDecoder().decode(ret[1])
def get(self, request): logger.debug("QueryMultiVnfLcmOpOccs--get::> %s" % request.query_params) if request.query_params and not set(request.query_params).issubset( set(VALID_FILTERS)): problem_details_serializer = get_problem_details_serializer( status.HTTP_400_BAD_REQUEST, "Not a valid filter") return Response(data=problem_details_serializer.data, status=status.HTTP_400_BAD_REQUEST) resp_data = QueryVnfLcmOpOcc( request.query_params).query_multi_vnf_lcm_op_occ() vnf_lcm_op_occs_serializer = VNFLCMOpOccsSerializer(data=resp_data) if not vnf_lcm_op_occs_serializer.is_valid(): raise NFLCMException(vnf_lcm_op_occs_serializer.errors) logger.debug( "QueryMultiVnfLcmOpOccs--get::> Remove default fields if exclude_default" + " is specified") # TODO(bharath): Add support for "fields", "exclude_fields" in query parameters if 'exclude_default' in list(request.query_params.keys()): for field in EXCLUDE_DEFAULT: for lcm_op in resp_data: del lcm_op[field] return Response(data=resp_data, status=status.HTTP_200_OK)
def get_scale_step_delta(self): for policy in self.vnfd_info.get("policies", []): if policy.get("type") != "tosca.policies.nfv.ScalingAspects": continue aspects = policy["properties"]["aspects"] if self.aspect_id in aspects: return aspects.get(self.aspect_id).get("step_deltas")[0] raise NFLCMException("Aspect(%s) does not exist" % self.aspect_id)
def query_multi_vnf(self): vnf_insts = NfInstModel.objects.all() if not vnf_insts: raise NFLCMException('VnfInsts does not exist') resp_data = [] for vnf_inst in vnf_insts: resp_data.append(self.fill_resp_data(vnf_inst)) return resp_data
def get_aspect_id(self): for policy in self.vnfd_info.get("policies", []): if policy.get("type") != "tosca.policies.nfv.InstantiationLevels": continue levels = policy["properties"]["levels"] level_info = levels.get(self.instantiation_level_id) return list(level_info.get("scale_info").keys())[0] raise NFLCMException("Failed to get aspect_id in vnfd")
def notify_lcm_to_nfvo(data): ret = req_by_msb( "openoapi/gvnfmdriver/v1/vnfs/lifecyclechangesnotification", "POST", data) if ret[0] != 0: logger.error("Status code is %s, detail is %s.", ret[2], ret[1]) raise NFLCMException("Nf lcm notify exception") return ret[1]
def get_instance_range(self): for vdu in self.vnfd_info["vdus"]: if vdu["vdu_id"] == self.target_vdu: vdu_profile = vdu["properties"]["vdu_profile"] min_inst_num = int(vdu_profile["min_number_of_instances"]) max_inst_num = int(vdu_profile["max_number_of_instances"]) return min_inst_num, max_inst_num raise NFLCMException("VDU(%s) does not exist" % self.target_vdu)
def check_valid(self): is_exist = NfInstModel.objects.filter( nf_name=self.vnf_instance_mame).exists() if is_exist: raise NFLCMException('VNF is already exist.') vnf_package_info = query_vnfpackage_by_id(self.csar_id) self.vnfd_info = json.loads( ignore_case_get(ignore_case_get(vnf_package_info, "packageInfo"), "vnfdModel"))
def get(self, request): logger.debug("QueryMultiVnf--get::> %s" % request.data) resp_data = QueryVnf(request.data).query_multi_vnf() if len(resp_data) == 0: return Response(data=[], status=status.HTTP_200_OK) vnf_instances_serializer = VnfInstancesSerializer(data=resp_data) if not vnf_instances_serializer.is_valid(): raise NFLCMException(vnf_instances_serializer.errors) return Response(data=resp_data, status=status.HTTP_200_OK)
def test_instantiate_inner_error(self, mock_run): NfInstModel(nfinstid='144', nf_name='VNF1', status='NOT_INSTANTIATED').save() mock_run.return_value = NFLCMException('Boom!') response = self.client.post( '/api/vnflcm/v1/vnf_instances/144/instantiate', data=inst_req_data, format='json') NfInstModel.objects.filter(nfinstid='144').delete() self.assertEqual(status.HTTP_500_INTERNAL_SERVER_ERROR, response.status_code)
def get_download_url_from_catalog(csar_id, relative_path): ret = req_by_msb( "/openoapi/catalog/v1/csars/%s/files?relativePath=%s" % (csar_id, relative_path), "GET") if ret[0] != 0: logger.error("Status code is %s, detail is %s.", ret[2], ret[1]) raise NFLCMException("Failed to get download url of CSAR(%s)." % csar_id) csar_file_info = json.JSONDecoder().decode(ret[1]) return ignore_case_get(csar_file_info, "downloadUri"), ignore_case_get( csar_file_info, "localPath")
def get(self, request, job_id): try: response_id = ignore_case_get(request.META, 'responseId') ret = GetJobInfoService(job_id, response_id).do_biz() resp_serializer = JobQueryRespSerializer(data=ret) if not resp_serializer.is_valid(): raise NFLCMException(resp_serializer.errors) return Response(data=ret, status=status.HTTP_200_OK) except Exception as e: logger.error(traceback.format_exc()) return Response(data={'error': e.args[0]}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
def parse_vnfd(csar_id, input_parameters=[]): req_param = json.JSONEncoder().encode({ "csarId": csar_id, "inputs": input_parameters }) ret = req_by_msb("/api/catalog/v1/parservnfd", "POST", req_param) if ret[0] != 0: logger.error("Status code is %s, detail is %s.", ret[2], ret[1]) raise NFLCMException("Failed to parse_vnfd of CSAR(%s) from catalog." % csar_id) vnf_model = json.JSONDecoder().decode(ret[1]) return vnf_model.get("model")
def get(self, request, subscriptionid): logger.debug("SubscriptionDetailView--get::> %s" % subscriptionid) resp_data = QuerySubscription( subscription_id=subscriptionid ).query_single_subscription() subscription_serializer = LccnSubscriptionSerializer(data=resp_data) if not subscription_serializer.is_valid(): raise NFLCMException(subscription_serializer.errors) return Response(data=resp_data, status=status.HTTP_200_OK)