From 5856d335c0ed0f256fa186373af7165cecb879a6 Mon Sep 17 00:00:00 2001 From: maopengzhang Date: Mon, 6 Aug 2018 18:48:45 +0800 Subject: SOL003 API ALign SOL003 API ALign -VNFLCM Code Structure Change-Id: I8da4ed65004eaa2f03bf7cba47b63227053d49ef Issue-ID: VFC-635 Signed-off-by: maopengzhang --- lcm/lcm/nf/biz/__init__.py | 0 lcm/lcm/nf/biz/create_vnf.py | 98 ++++ lcm/lcm/nf/biz/delete_vnf.py | 48 ++ lcm/lcm/nf/biz/instantiate_vnf.py | 370 +++++++++++++++ lcm/lcm/nf/biz/query_vnf.py | 139 ++++++ lcm/lcm/nf/biz/terminate_vnf.py | 208 +++++++++ lcm/lcm/nf/serializers.py | 453 ------------------ lcm/lcm/nf/serializers/__init__.py | 0 lcm/lcm/nf/serializers/common.py | 13 + lcm/lcm/nf/serializers/serializers.py | 616 +++++++++++++++++++++++++ lcm/lcm/nf/tests/test_create_vnf.py | 78 ++++ lcm/lcm/nf/tests/test_delete_vnf.py | 110 +++++ lcm/lcm/nf/tests/test_instantiate_vnf.py | 166 +++++++ lcm/lcm/nf/tests/test_query_vnf.py | 136 ++++++ lcm/lcm/nf/tests/test_terminate_vnf.py | 153 ++++++ lcm/lcm/nf/tests/test_vnf_cancel.py | 175 ------- lcm/lcm/nf/tests/test_vnf_create.py | 201 -------- lcm/lcm/nf/tests/test_vnf_query.py | 136 ------ lcm/lcm/nf/urls.py | 8 +- lcm/lcm/nf/views.py | 202 -------- lcm/lcm/nf/views/__init__.py | 0 lcm/lcm/nf/views/curd_vnf_views.py | 132 ++++++ lcm/lcm/nf/views/instantiate_vnf_view.py | 62 +++ lcm/lcm/nf/views/terminate_vnf_view.py | 62 +++ lcm/lcm/nf/vnf_cancel/__init__.py | 13 - lcm/lcm/nf/vnf_cancel/delete_vnf_identifier.py | 48 -- lcm/lcm/nf/vnf_cancel/term_vnf.py | 208 --------- lcm/lcm/nf/vnf_create/__init__.py | 13 - lcm/lcm/nf/vnf_create/create_vnf_identifier.py | 98 ---- lcm/lcm/nf/vnf_create/inst_vnf.py | 370 --------------- lcm/lcm/nf/vnf_query/__init__.py | 13 - lcm/lcm/nf/vnf_query/query_vnf.py | 139 ------ lcm/lcm/urls.py | 2 +- lcm/lcm/v2/__init__.py | 13 - lcm/lcm/v2/serializers.py | 177 ------- lcm/lcm/v2/tests/__init__.py | 13 - lcm/lcm/v2/tests/test_vnf_create.py | 84 ---- lcm/lcm/v2/urls.py | 21 - lcm/lcm/v2/views.py | 88 ---- lcm/lcm/v2/vnf_query/__init__.py | 13 - lcm/lcm/v2/vnf_query/query_vnf.py | 146 ------ 41 files changed, 2397 insertions(+), 2628 deletions(-) create mode 100644 lcm/lcm/nf/biz/__init__.py create mode 100644 lcm/lcm/nf/biz/create_vnf.py create mode 100644 lcm/lcm/nf/biz/delete_vnf.py create mode 100644 lcm/lcm/nf/biz/instantiate_vnf.py create mode 100644 lcm/lcm/nf/biz/query_vnf.py create mode 100644 lcm/lcm/nf/biz/terminate_vnf.py delete mode 100644 lcm/lcm/nf/serializers.py create mode 100644 lcm/lcm/nf/serializers/__init__.py create mode 100644 lcm/lcm/nf/serializers/common.py create mode 100644 lcm/lcm/nf/serializers/serializers.py create mode 100644 lcm/lcm/nf/tests/test_create_vnf.py create mode 100644 lcm/lcm/nf/tests/test_delete_vnf.py create mode 100644 lcm/lcm/nf/tests/test_instantiate_vnf.py create mode 100644 lcm/lcm/nf/tests/test_query_vnf.py create mode 100644 lcm/lcm/nf/tests/test_terminate_vnf.py delete mode 100644 lcm/lcm/nf/tests/test_vnf_cancel.py delete mode 100644 lcm/lcm/nf/tests/test_vnf_create.py delete mode 100644 lcm/lcm/nf/tests/test_vnf_query.py delete mode 100644 lcm/lcm/nf/views.py create mode 100644 lcm/lcm/nf/views/__init__.py create mode 100644 lcm/lcm/nf/views/curd_vnf_views.py create mode 100644 lcm/lcm/nf/views/instantiate_vnf_view.py create mode 100644 lcm/lcm/nf/views/terminate_vnf_view.py delete mode 100644 lcm/lcm/nf/vnf_cancel/__init__.py delete mode 100644 lcm/lcm/nf/vnf_cancel/delete_vnf_identifier.py delete mode 100644 lcm/lcm/nf/vnf_cancel/term_vnf.py delete mode 100644 lcm/lcm/nf/vnf_create/__init__.py delete mode 100644 lcm/lcm/nf/vnf_create/create_vnf_identifier.py delete mode 100644 lcm/lcm/nf/vnf_create/inst_vnf.py delete mode 100644 lcm/lcm/nf/vnf_query/__init__.py delete mode 100644 lcm/lcm/nf/vnf_query/query_vnf.py delete mode 100644 lcm/lcm/v2/__init__.py delete mode 100644 lcm/lcm/v2/serializers.py delete mode 100644 lcm/lcm/v2/tests/__init__.py delete mode 100644 lcm/lcm/v2/tests/test_vnf_create.py delete mode 100644 lcm/lcm/v2/urls.py delete mode 100644 lcm/lcm/v2/views.py delete mode 100644 lcm/lcm/v2/vnf_query/__init__.py delete mode 100644 lcm/lcm/v2/vnf_query/query_vnf.py (limited to 'lcm') diff --git a/lcm/lcm/nf/biz/__init__.py b/lcm/lcm/nf/biz/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/lcm/lcm/nf/biz/create_vnf.py b/lcm/lcm/nf/biz/create_vnf.py new file mode 100644 index 00000000..34329a52 --- /dev/null +++ b/lcm/lcm/nf/biz/create_vnf.py @@ -0,0 +1,98 @@ +# Copyright 2017 ZTE Corporation. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +import json +import logging +import traceback +import uuid + +from lcm.pub.database.models import NfInstModel +from lcm.pub.exceptions import NFLCMException +from lcm.pub.msapi.sdc_run_catalog import query_vnfpackage_by_id +from lcm.pub.utils.timeutil import now_time +from lcm.pub.utils.values import ignore_case_get + +logger = logging.getLogger(__name__) + + +class CreateVnf: + def __init__(self, data): + self.data = data + self.csar_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): + self.nf_inst_id = str(uuid.uuid4()) + try: + self.check_valid() + self.save_db() + except NFLCMException as e: + logger.debug('Create VNF instance[%s]: %s', self.nf_inst_id, e.message) + raise NFLCMException(e.message) + except Exception as e: + logger.error(e.message) + logger.error(traceback.format_exc()) + NfInstModel.objects.create(nfinstid=self.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.csar_id, + vnfSoftwareVersion='', + create_time=now_time()) + vnf_inst = NfInstModel.objects.get(nfinstid=self.nf_inst_id) + resp = { + 'id': vnf_inst.nfinstid, + 'vnfInstanceName': vnf_inst.nf_name, + 'vnfInstanceDescription': 'Human-readable description of the VNF instance.', + 'vnfdId': vnf_inst.vnfdid, + 'vnfProvider': vnf_inst.vendor, + 'vnfProductName': vnf_inst.nf_name, + 'vnfSoftwareVersion': vnf_inst.vnfSoftwareVersion, + 'vnfdVersion': vnf_inst.version, + 'vnfPkgId': vnf_inst.package_id, + 'vnfConfigurableProperties': {} + } + return resp + + 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 save_db(self): + metadata = ignore_case_get(self.vnfd_info, "metadata") + 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.create(nfinstid=self.nf_inst_id, + nf_name=self.vnf_instance_mame, + package_id=self.csar_id, + version=version, + vendor=vendor, + netype=netype, + vnfd_model=self.vnfd_info, + status='NOT_INSTANTIATED', + nf_desc=self.description, + vnfdid=self.csar_id, + vnfSoftwareVersion=vnfsoftwareversion, + create_time=now_time()) + logger.debug('Create VNF instance[%s] success', self.nf_inst_id) diff --git a/lcm/lcm/nf/biz/delete_vnf.py b/lcm/lcm/nf/biz/delete_vnf.py new file mode 100644 index 00000000..c0940303 --- /dev/null +++ b/lcm/lcm/nf/biz/delete_vnf.py @@ -0,0 +1,48 @@ +# Copyright 2017 ZTE Corporation. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import logging +import traceback + +from lcm.pub.database.models import NfInstModel, NfvoRegInfoModel +from lcm.pub.exceptions import NFLCMException + +logger = logging.getLogger(__name__) + + +class DeleteVnf: + def __init__(self, data, instanceid): + self.data = data + self.nf_inst_id = instanceid + + def do_biz(self): + try: + self.check_parameter() + self.delete_info_from_db() + logger.debug('VnfInst(%s) is deleted.' % self.nf_inst_id) + except NFLCMException as e: + logger.debug('Delete VNF instance[%s] failed: %s', self.nf_inst_id, e.message) + except Exception as e: + logger.error(e.message) + logger.error(traceback.format_exc()) + logger.debug('Delete VNF instance[%s] failed' % self.nf_inst_id) + + def check_parameter(self): + vnf_insts = NfInstModel.objects.filter(nfinstid=self.nf_inst_id) + if not vnf_insts.exists(): + logger.warn('VnfInst(%s) does not exist' % self.nf_inst_id) + + def delete_info_from_db(self): + NfInstModel.objects.filter(nfinstid=self.nf_inst_id).delete() + NfvoRegInfoModel.objects.filter(nfvoid=self.nf_inst_id).delete() diff --git a/lcm/lcm/nf/biz/instantiate_vnf.py b/lcm/lcm/nf/biz/instantiate_vnf.py new file mode 100644 index 00000000..f47746db --- /dev/null +++ b/lcm/lcm/nf/biz/instantiate_vnf.py @@ -0,0 +1,370 @@ +# Copyright 2017 ZTE Corporation. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import json +import logging +import traceback +import uuid +from threading import Thread + +from lcm.pub.database.models import NfInstModel, VmInstModel, NetworkInstModel, \ + SubNetworkInstModel, PortInstModel, StorageInstModel, FlavourInstModel, VNFCInstModel, NfvoRegInfoModel +from lcm.pub.exceptions import NFLCMException +from lcm.pub.msapi.gvnfmdriver import apply_grant_to_nfvo, notify_lcm_to_nfvo +from lcm.pub.msapi.sdc_run_catalog import query_vnfpackage_by_id +from lcm.pub.utils.jobutil import JobUtil +from lcm.pub.utils.timeutil import now_time +from lcm.pub.utils.values import ignore_case_get, get_none, get_boolean, get_integer +from lcm.pub.vimapi import adaptor + +logger = logging.getLogger(__name__) + + +class InstantiateVnf(Thread): + def __init__(self, data, nf_inst_id, job_id): + super(InstantiateVnf, self).__init__() + self.data = data + self.nf_inst_id = nf_inst_id + self.job_id = job_id + self.vim_id = ignore_case_get(ignore_case_get(self.data, "additionalParams"), "vimId") + + def run(self): + try: + self.inst_pre() + self.apply_grant() + self.create_res() + self.lcm_notify() + JobUtil.add_job_status(self.job_id, 100, "Instantiate Vnf success.") + except NFLCMException as e: + self.vnf_inst_failed_handle(e.message) + except Exception as e: + logger.error(e.message) + logger.error(traceback.format_exc()) + self.vnf_inst_failed_handle('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.') + + 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'], "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}) + vnf_package_info = query_vnfpackage_by_id(self.vnfd_id) + self.vnfd_info = json.loads(ignore_case_get(ignore_case_get(vnf_package_info, "packageInfo"), "vnfdModel")) + + 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=self.vnfd_info, + 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("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 apply_grant(self): + logger.info('Send resource grand request to nfvo') + content_args = { + 'vnfInstanceId': self.nf_inst_id, + 'vnfDescriptorId': '', + 'lifecycleOperation': 'Instantiate', + 'jobId': self.job_id, + 'addResource': [], + 'removeResource': [], + 'placementConstraint': [], + 'additionalParam': {} + } + + vdus = ignore_case_get(self.vnfd_info, "vdus") + res_index = 1 + for vdu in vdus: + res_def = { + 'type': 'VDU', + 'resDefId': str(res_index), + 'resDesId': ignore_case_get(vdu, "vdu_id") + } + content_args['addResource'].append(res_def) + res_index += 1 + + logger.debug("VnfInst = %s", self.nf_inst_id) + vnfmInfo = NfvoRegInfoModel.objects.filter(nfvoid=self.nf_inst_id) + if len(vnfmInfo) == 0: + raise NFLCMException('VnfInst(%s) does not exist' % self.nf_inst_id) + content_args['additionalParam']['vnfmid'] = vnfmInfo[0].vnfminstid + content_args['additionalParam']['vimid'] = vnfmInfo[0].apiurl + logger.info('Grant request data = %s', content_args) + + apply_result = apply_grant_to_nfvo(json.dumps(content_args)) + self.set_location(apply_result) + + logger.info('VnfdInfo = %s' % self.vnfd_info) + NfInstModel.objects.filter(nfinstid=self.nf_inst_id).update(status='INSTANTIATED', lastuptime=now_time()) + JobUtil.add_job_status(self.job_id, 20, 'Nf instancing apply grant finish') + logger.info("Nf instancing apply grant finish") + + def create_res(self): + logger.info("Create resource start") + adaptor.create_vim_res(self.vnfd_info, self.do_notify) + JobUtil.add_job_status(self.job_id, 70, '[NF instantiation] create resource finish') + logger.info("Create resource finish") + + def lcm_notify(self): + logger.info('Send notify request to nfvo') + affected_vnfc = [] + vnfcs = VNFCInstModel.objects.filter(instid=self.nf_inst_id) + for vnfc in vnfcs: + vm_resource = {} + if vnfc.vmid: + vm = VmInstModel.objects.filter(vmid=vnfc.vmid) + if vm: + vm_resource = {'vimId': vm[0].vimid, 'resourceId': vm[0].resouceid, + 'resourceName': vm[0].vmname, 'resourceType': 'vm'} + affected_vnfc.append( + {'vnfcInstanceId': vnfc.vnfcinstanceid, + 'vduId': vnfc.vduid, + 'changeType': 'added', + 'computeResource': vm_resource}) + affected_vl = [] + networks = NetworkInstModel.objects.filter(instid=self.nf_inst_id) + for network in networks: + network_resource = {'vimId': network.vimid, 'resourceId': network.resouceid, + 'resourceName': network.name, 'resourceType': 'network'} + affected_vl.append( + {'vlInstanceId': network.networkid, + 'vldid': network.nodeId, + 'changeType': 'added', + 'networkResource': network_resource}) + affected_cp = [] + ports = PortInstModel.objects.filter(instid=self.nf_inst_id) + for port in ports: + affected_cp.append( + {'vsInstanceId': port.portid, + 'cpdid': port.nodeId, + 'changeType': 'added', + 'portResource': {'vimId': port.vimid, 'resourceId': port.resouceid, + 'resourceName': port.name, 'resourceType': 'port'}}) + affected_vs = [] + vss = StorageInstModel.objects.filter(instid=self.nf_inst_id) + for vs in vss: + affected_vs.append( + {'vsInstanceId': vs.storageid, + 'vsdId': vs.nodeId, + 'changeType': 'added', + 'storageResource': {'vimId': vs.vimid, 'resourceId': vs.resouceid, + 'resourceName': vs.name, 'resourceType': 'volume'}}) + content_args = { + "status": 'result', + "vnfInstanceId": self.nf_inst_id, + "operation": 'instantiate', + "jobId": self.job_id, + 'affectedVnfc': affected_vnfc, + 'affectedVirtualLink': affected_vl, + 'affectedVirtualStorage': affected_vs, + 'affectedCp': affected_cp + } + + vnfmInfo = NfvoRegInfoModel.objects.filter(nfvoid=self.nf_inst_id) + if len(vnfmInfo) == 0: + raise NFLCMException('nf_inst_id(%s) does not exist in NfvoRegInfoModel' % self.nf_inst_id) + content_args['VNFMID'] = vnfmInfo[0].vnfminstid + logger.info('Notify request data = %s' % content_args) + resp = notify_lcm_to_nfvo(json.dumps(content_args)) + logger.info('Lcm notify end, response %s' % resp) + + 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) + + def do_notify(self, res_type, ret): + logger.info('Creating [%s] resource' % res_type) + resource_save_method = globals().get(res_type + '_save') + resource_save_method(self.job_id, self.nf_inst_id, ret) + + def update_cps(self): + for extlink in ignore_case_get(self.data, "extVirtualLinks"): + for cp in ignore_case_get(self.vnfd_info, "cps"): + cpdid = ignore_case_get(extlink, "cpdId") + if cpdid == ignore_case_get(cp, "cp_id"): + cp["networkId"] = ignore_case_get(extlink, "resourceId") + cp["subnetId"] = ignore_case_get(extlink, "resourceSubnetId") + break + + def set_location(self, apply_result): + for resource_type in ['vdus', 'vls']: + for resource in ignore_case_get(self.vnfd_info, resource_type): + if "location_info" in resource["properties"]: + resource["properties"]["location_info"]["vimid"] = ignore_case_get(apply_result, "vimid") + resource["properties"]["location_info"]["tenant"] = ignore_case_get(apply_result, "tenant") + else: + resource["properties"]["location_info"] = { + "vimid": ignore_case_get(apply_result, "vimid"), + "tenant": ignore_case_get(apply_result, "tenant")} + + +def volume_save(job_id, nf_inst_id, ret): + JobUtil.add_job_status(job_id, 25, 'Create vloumns!') + StorageInstModel.objects.create( + storageid=str(uuid.uuid4()), + vimid=ignore_case_get(ret, "vimId"), + resouceid=ignore_case_get(ret, "id"), + name=ignore_case_get(ret, "name"), + tenant=ignore_case_get(ret, "tenantId"), + create_time=ignore_case_get(ret, "createTime"), + storagetype=get_none(ignore_case_get(ret, "type")), + size=ignore_case_get(ret, "size"), + insttype=0, + is_predefined=ignore_case_get(ret, "returnCode"), + nodeId=ignore_case_get(ret, "nodeId"), + instid=nf_inst_id) + + +def network_save(job_id, nf_inst_id, ret): + JobUtil.add_job_status(job_id, 35, 'Create networks!') + NetworkInstModel.objects.create( + networkid=str(uuid.uuid4()), + name=ignore_case_get(ret, "name"), + vimid=ignore_case_get(ret, "vimId"), + resouceid=ignore_case_get(ret, "id"), + tenant=ignore_case_get(ret, "tenantId"), + segmentid=str(ignore_case_get(ret, "segmentationId")), + network_type=ignore_case_get(ret, "networkType"), + physicalNetwork=ignore_case_get(ret, "physicalNetwork"), + vlantrans=get_boolean(ignore_case_get(ret, "vlanTransparent")), + is_shared=get_boolean(ignore_case_get(ret, "shared")), + routerExternal=get_boolean(ignore_case_get(ret, "routerExternal")), + insttype=0, + is_predefined=ignore_case_get(ret, "returnCode"), + nodeId=ignore_case_get(ret, "nodeId"), + instid=nf_inst_id) + + +def subnet_save(job_id, nf_inst_id, ret): + JobUtil.add_job_status(job_id, 40, 'Create subnets!') + SubNetworkInstModel.objects.create( + subnetworkid=str(uuid.uuid4()), + name=ignore_case_get(ret, "name"), + vimid=ignore_case_get(ret, "vimId"), + resouceid=ignore_case_get(ret, "id"), + tenant=ignore_case_get(ret, "tenantId"), + networkid=ignore_case_get(ret, "networkId"), + cidr=ignore_case_get(ret, "cidr"), + ipversion=ignore_case_get(ret, "ipversion"), + isdhcpenabled=ignore_case_get(ret, "enableDhcp"), + gatewayip=ignore_case_get(ret, "gatewayIp"), + dnsNameservers=ignore_case_get(ret, "dnsNameservers"), + hostRoutes=ignore_case_get(ret, "hostRoutes"), + allocationPools=ignore_case_get(ret, "allocationPools"), + insttype=0, + is_predefined=ignore_case_get(ret, "returnCode"), + instid=nf_inst_id) + + +def port_save(job_id, nf_inst_id, ret): + JobUtil.add_job_status(job_id, 50, 'Create ports!') + PortInstModel.objects.create( + portid=str(uuid.uuid4()), + networkid=ignore_case_get(ret, "networkId"), + subnetworkid=ignore_case_get(ret, "subnetId"), + name=ignore_case_get(ret, "name"), + vimid=ignore_case_get(ret, "vimId"), + resouceid=ignore_case_get(ret, "id"), + tenant=ignore_case_get(ret, "tenantId"), + macaddress=ignore_case_get(ret, "macAddress"), + ipaddress=ignore_case_get(ret, "ip"), + typevirtualnic=ignore_case_get(ret, "vnicType"), + securityGroups=ignore_case_get(ret, "securityGroups"), + insttype=0, + is_predefined=ignore_case_get(ret, "returnCode"), + nodeId=ignore_case_get(ret, "nodeId"), + instid=nf_inst_id) + + +def flavor_save(job_id, nf_inst_id, ret): + JobUtil.add_job_status(job_id, 60, 'Create flavors!') + FlavourInstModel.objects.create( + flavourid=str(uuid.uuid4()), + name=ignore_case_get(ret, "name"), + vimid=ignore_case_get(ret, "vimId"), + resouceid=ignore_case_get(ret, "id"), + tenant=ignore_case_get(ret, "tenantId"), + vcpu=get_integer(ignore_case_get(ret, "vcpu")), + memory=get_integer(ignore_case_get(ret, "memory")), + disk=get_integer(ignore_case_get(ret, "disk")), + ephemeral=get_integer(ignore_case_get(ret, "ephemeral")), + swap=get_integer(ignore_case_get(ret, "swap")), + isPublic=get_boolean(ignore_case_get(ret, "isPublic")), + extraspecs=ignore_case_get(ret, "extraSpecs"), + is_predefined=ret.get("returnCode", int(0)), + instid=nf_inst_id) + + +def vm_save(job_id, nf_inst_id, ret): + JobUtil.add_job_status(job_id, 70, 'Create vms!') + vm_id = str(uuid.uuid4()) + VmInstModel.objects.create( + vmid=vm_id, + vmname=ignore_case_get(ret, "name"), + vimid=ignore_case_get(ret, "vimId"), + resouceid=ignore_case_get(ret, "id"), + tenant=ignore_case_get(ret, "tenantId"), + nic_array=ignore_case_get(ret, "nicArray"), + metadata=ignore_case_get(ret, "metadata"), + volume_array=ignore_case_get(ret, "volumeArray"), + server_group=ignore_case_get(ret, "serverGroup"), + availability_zone=str(ignore_case_get(ret, "availabilityZone", "undefined")), + flavor_id=ignore_case_get(ret, "flavorId"), + security_groups=ignore_case_get(ret, "securityGroups"), + operationalstate=ignore_case_get(ret, "status"), + insttype=0, + is_predefined=ignore_case_get(ret, "returnCode"), + instid=nf_inst_id) + VNFCInstModel.objects.create( + vnfcinstanceid=str(uuid.uuid4()), + vduid=ignore_case_get(ret, "id"), + is_predefined=ignore_case_get(ret, "returnCode"), + instid=nf_inst_id, + vmid=vm_id) diff --git a/lcm/lcm/nf/biz/query_vnf.py b/lcm/lcm/nf/biz/query_vnf.py new file mode 100644 index 00000000..1a6bdd90 --- /dev/null +++ b/lcm/lcm/nf/biz/query_vnf.py @@ -0,0 +1,139 @@ +# Copyright 2017 ZTE Corporation. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import logging + +from lcm.pub.database.models import NfInstModel, StorageInstModel, VLInstModel, NetworkInstModel, VNFCInstModel, \ + VmInstModel +from lcm.pub.exceptions import NFLCMException + +logger = logging.getLogger(__name__) + + +class QueryVnf: + def __init__(self, data, instanceid=''): + self.vnf_inst_id = instanceid + self.data = data + + 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 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 fill_resp_data(self, vnf): + logger.info('Get storages') + storage_inst = StorageInstModel.objects.filter(instid=vnf.nfinstid) + arr = [] + for s in storage_inst: + storage = { + "virtualStorageInstanceId": s.storageid, + "storageResource": { + "vimId": s.vimid, + "resourceId": s.resouceid + } + } + arr.append(storage) + logger.info('Get networks') + vl_inst = VLInstModel.objects.filter(ownerid=vnf.nfinstid) + vl_arr = [] + for v in vl_inst: + net = NetworkInstModel.objects.filter(networkid=v.relatednetworkid) + if not net: + raise NFLCMException('NetworkInst(%s) does not exist.' % v.relatednetworkid) + v_dic = { + "virtualLinkInstanceId": v.vlinstanceid, + "virtualLinkDescId": v.vldid, + "networkResource": { + "vimId": net[0].vimid, + "resourceId": net[0].resouceid + } + } + vl_arr.append(v_dic) + logger.info('Get vnfcs') + vnfc_insts = VNFCInstModel.objects.filter(instid=vnf.nfinstid) + vnfc_arr = [] + for vnfc in vnfc_insts: + vm = VmInstModel.objects.filter(vmid=vnfc.vmid) + if not vm: + raise NFLCMException('VmInst(%s) does not exist.' % vnfc.vmid) + storage = StorageInstModel.objects.filter(ownerid=vm[0].vmid) + if not storage: + raise NFLCMException('StorageInst(%s) does not exist.' % vm[0].vmid) + vnfc_dic = { + "vnfcInstanceId": vnfc.vnfcinstanceid, + "vduId": vnfc.vduid, + "computeResource": { + "vimId": vm[0].vimid, + "resourceId": vm[0].resouceid + }, + "storageResourceIds": [s.storageid for s in storage] + } + vnfc_arr.append(vnfc_dic) + logger.info('Get vms') + vms = VmInstModel.objects.filter(instid=vnf.nfinstid) + vm_arr = [] + for vm in vms: + vm_dic = { + "vmid": vm.vmid, + "vimid": vm.vimid, + "tenant": vm.tenant, + "resouceid": vm.resouceid, + "vmname": vm.vmname, + "nic_array": vm.nic_array, + "metadata": vm.metadata, + "volume_array": vm.volume_array, + "server_group": vm.server_group, + "availability_zone": vm.availability_zone, + "flavor_id": vm.flavor_id, + "security_groups": vm.security_groups, + "operationalstate": vm.operationalstate, + "insttype": vm.insttype, + "is_predefined": vm.is_predefined, + "create_time": vm.create_time, + "instid": vm.instid, + "nodeId": vm.nodeId + } + vm_arr.append(vm_dic) + + resp_data = { + "vnfInstanceId": vnf.nfinstid, + "vnfInstanceName": vnf.nf_name, + "onboardedVnfPkgInfoId": vnf.package_id, + "vnfdVersion": vnf.version, + "vnfProvider": vnf.vendor, + "instantiatedVnfInfo": { + "flavourId": vnf.flavour_id, + "vnfState": vnf.status, + "scaleStatus": [], + "extCpInfo": [], + "extVirtualLink": [], + "monitoringParameters": {}, + "vimInfo": vm_arr, + "vnfcResourceInfo": vnfc_arr, + "virtualLinkResourceInfo": vl_arr, + "virtualStorageResourceInfo": arr + } + } + return resp_data diff --git a/lcm/lcm/nf/biz/terminate_vnf.py b/lcm/lcm/nf/biz/terminate_vnf.py new file mode 100644 index 00000000..5d51512f --- /dev/null +++ b/lcm/lcm/nf/biz/terminate_vnf.py @@ -0,0 +1,208 @@ +# Copyright 2017 ZTE Corporation. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import json +import logging +import traceback +from threading import Thread + +from lcm.nf.const import VNF_STATUS, RESOURCE_MAP +from lcm.pub.database.models import NfInstModel, VmInstModel, NetworkInstModel, StorageInstModel, \ + PortInstModel, VNFCInstModel, NfvoRegInfoModel, FlavourInstModel, SubNetworkInstModel +from lcm.pub.exceptions import NFLCMException +from lcm.pub.msapi.gvnfmdriver import apply_grant_to_nfvo, notify_lcm_to_nfvo +from lcm.pub.utils.jobutil import JobUtil +from lcm.pub.utils.timeutil import now_time +from lcm.pub.utils.values import ignore_case_get +from lcm.pub.vimapi import adaptor + +logger = logging.getLogger(__name__) + + +class TerminateVnf(Thread): + def __init__(self, data, nf_inst_id, job_id): + super(TerminateVnf, self).__init__() + self.data = data + self.nf_inst_id = nf_inst_id + self.job_id = job_id + self.terminationType = ignore_case_get(self.data, "terminationType") + self.gracefulTerminationTimeout = ignore_case_get(self.data, "gracefulTerminationTimeout") + self.inst_resource = {'volumn': [], 'network': [], 'subnet': [], 'port': [], 'flavor': [], 'vm': []} + + def run(self): + try: + if self.term_pre(): + self.grant_resource() + self.query_inst_resource() + self.query_notify_data() + self.delete_resource() + self.lcm_notify() + JobUtil.add_job_status(self.job_id, 100, "Terminate Vnf success.") + except NFLCMException as e: + self.vnf_term_failed_handle(e.message) + except Exception as e: + logger.error(e.message) + self.vnf_term_failed_handle(traceback.format_exc()) + + def term_pre(self): + vnf_insts = NfInstModel.objects.filter(nfinstid=self.nf_inst_id) + if not vnf_insts.exists(): + logger.warn('VnfInst(%s) does not exist' % self.nf_inst_id) + return False + if self.terminationType == 'GRACEFUL' and not self.gracefulTerminationTimeout: + logger.warn("Set Graceful default termination timeout = 60") + self.gracefulTerminationTimeout = 60 + NfInstModel.objects.filter(nfinstid=self.nf_inst_id).update(status=VNF_STATUS.TERMINATING) + JobUtil.add_job_status(self.job_id, 10, 'Nf terminating pre-check finish') + logger.info("Nf terminating pre-check finish") + return True + + def grant_resource(self): + logger.info("Grant resource begin") + content_args = { + 'vnfInstanceId': self.nf_inst_id, + 'vnfDescriptorId': '', + 'lifecycleOperation': 'Terminate', + 'jobId': self.job_id, + 'addResource': [], + 'removeResource': [], + 'placementConstraint': [], + 'additionalParam': {} + } + + vdus = VmInstModel.objects.filter(instid=self.nf_inst_id, is_predefined=1) + res_index = 1 + for vdu in vdus: + res_def = { + 'type': 'VDU', + 'resDefId': str(res_index), + 'resDesId': vdu.resouceid} + content_args['removeResource'].append(res_def) + res_index += 1 + + vnfmInfo = NfvoRegInfoModel.objects.filter(nfvoid=self.nf_inst_id) + if len(vnfmInfo) == 0: + raise NFLCMException('VnfId(%s) does not exist' % self.nf_inst_id) + content_args['additionalParam']['vnfmid'] = vnfmInfo[0].vnfminstid + content_args['additionalParam']['vimid'] = vnfmInfo[0].apiurl + logger.info('Grant request data=%s' % content_args) + self.apply_result = apply_grant_to_nfvo(json.dumps(content_args)) + logger.info("Grant resource end, response: %s" % self.apply_result) + JobUtil.add_job_status(self.job_id, 20, 'Nf terminating grant_resource finish') + + def query_inst_resource(self): + logger.info('Query resource begin') + for resource_type in RESOURCE_MAP.keys(): + resource_table = globals().get(resource_type + 'InstModel') + resource_insts = resource_table.objects.filter(instid=self.nf_inst_id) + for resource_inst in resource_insts: + if not resource_inst.resouceid: + continue + self.inst_resource[RESOURCE_MAP.get(resource_type)].append(self.get_resource(resource_inst)) + logger.info('Query resource end, resource=%s' % self.inst_resource) + + def get_resource(self, resource): + return { + "vim_id": resource.vimid, + "tenant_id": resource.tenant, + "res_id": resource.resouceid, + "is_predefined": resource.is_predefined + } + + def query_notify_data(self): + logger.info('Send notify request to nfvo') + affected_vnfc = [] + vnfcs = VNFCInstModel.objects.filter(instid=self.nf_inst_id) + for vnfc in vnfcs: + vm_resource = {} + if vnfc.vmid: + vm = VmInstModel.objects.filter(vmid=vnfc.vmid) + if vm: + vm_resource = {'vimId': vm[0].vimid, 'resourceId': vm[0].resouceid, + 'resourceName': vm[0].vmname, 'resourceType': 'vm'} + affected_vnfc.append( + {'vnfcInstanceId': vnfc.vnfcinstanceid, + 'vduId': vnfc.vduid, + 'changeType': 'removed', + 'computeResource': vm_resource}) + affected_vl = [] + networks = NetworkInstModel.objects.filter(instid=self.nf_inst_id) + for network in networks: + network_resource = { + 'vimId': network.vimid, + 'resourceId': network.resouceid, + 'resourceName': network.name, + 'resourceType': 'network'} + affected_vl.append( + {'vlInstanceId': network.networkid, + 'vldid': network.nodeId, + 'changeType': 'removed', + 'networkResource': network_resource}) + affected_cp = [] + ports = PortInstModel.objects.filter(instid=self.nf_inst_id) + for port in ports: + affected_cp.append( + {'vsInstanceId': port.portid, + 'cpdid': port.nodeId, + 'changeType': 'removed', + 'storageResource': {'vimId': port.vimid, 'resourceId': port.resouceid, + 'resourceName': port.name, 'resourceType': 'port'}}) + affected_vs = [] + vss = StorageInstModel.objects.filter(instid=self.nf_inst_id) + for vs in vss: + affected_vs.append( + {'vsInstanceId': vs.storageid, + 'vsdId': vs.nodeId, + 'changeType': 'removed', + 'storageResource': {'vimId': vs.vimid, 'resourceId': vs.resouceid, + 'resourceName': vs.name, 'resourceType': 'volume'}}) + FlavourInstModel.objects.filter(instid=self.nf_inst_id) + SubNetworkInstModel.objects.filter(instid=self.nf_inst_id) + self.notify_data = { + "status": 'result', + "vnfInstanceId": self.nf_inst_id, + "operation": 'Terminal', + "jobId": self.job_id, + 'affectedVnfc': affected_vnfc, + 'affectedVirtualLink': affected_vl, + 'affectedVirtualStorage': affected_vs, + 'affectedCp': affected_cp} + + vnfmInfo = NfvoRegInfoModel.objects.filter(nfvoid=self.nf_inst_id) + if len(vnfmInfo) == 0: + raise NFLCMException('VnfId(%s) does not exist' % self.nf_inst_id) + self.notify_data['VNFMID'] = vnfmInfo[0].vnfminstid + logger.info('Notify request data=%s' % self.notify_data) + + def delete_resource(self): + logger.info('Rollback resource begin') + adaptor.delete_vim_res(self.inst_resource, self.do_notify_delete) + logger.info('Rollback resource complete') + + def do_notify_delete(self, res_type, res_id): + logger.error('Deleting [%s] resource, resourceid [%s]' % (res_type, res_id)) + resource_type = RESOURCE_MAP.keys()[RESOURCE_MAP.values().index(res_type)] + resource_table = globals().get(resource_type + 'InstModel') + resource_table.objects.filter(instid=self.nf_inst_id, resouceid=res_id).delete() + + def lcm_notify(self): + NfInstModel.objects.filter(nfinstid=self.nf_inst_id).update(status='NOT_INSTANTIATED', lastuptime=now_time()) + logger.info('Send notify request to nfvo') + resp = notify_lcm_to_nfvo(json.dumps(self.notify_data)) + logger.info('Lcm notify end, response: %s' % resp) + + def vnf_term_failed_handle(self, error_msg): + logger.error('VNF termination 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) diff --git a/lcm/lcm/nf/serializers.py b/lcm/lcm/nf/serializers.py deleted file mode 100644 index 98f68232..00000000 --- a/lcm/lcm/nf/serializers.py +++ /dev/null @@ -1,453 +0,0 @@ -# Copyright 2018 ZTE Corporation. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -from rest_framework import serializers - - -class CreateVnfReqSerializer(serializers.Serializer): - vnfdId = serializers.CharField( - help_text="Identifier that identifies the VNFD which defines the VNF instance to be created.", - max_length=255, - required=True, - allow_null=True) - vnfInstanceName = serializers.CharField( - help_text="Human-readable name of the VNF instance to be created.", - max_length=255, - required=True, - allow_null=False) - vnfInstanceDescription = serializers.CharField( - help_text="Human-readable description of the VNF instance to be created.", - max_length=255, - required=False, - allow_null=True) - - -class CreateVnfRespSerializer(serializers.Serializer): - vnfInstanceId = serializers.CharField( - help_text="Identifier of the VNF instance", - required=True, - max_length=255, - allow_null=True) - - -class ResourceSerializer(serializers.Serializer): - resourceId = serializers.CharField( - help_text="resourceId", - required=True, - max_length=255, - allow_null=True) - vimId = serializers.CharField( - help_text="vimId", - required=True, - max_length=255, - allow_null=True) - - -class VirtualStorageResourceInfoSerializer(serializers.Serializer): - virtualStorageInstanceId = serializers.CharField( - help_text="virtualStorageInstanceId", - required=False, - allow_null=True, - max_length=255) - virtualStorageDescId = serializers.CharField( - help_text="virtualStorageDescId", - required=False, - max_length=255, - allow_null=True) - storageResource = ResourceSerializer( - help_text="storageResource", - required=False, - allow_null=True) - - -class VirtualLinkResourceInfoSerializer(serializers.Serializer): - virtualLinkInstanceId = serializers.CharField( - help_text="virtualLinkInstanceId", - required=False, - max_length=255, - allow_null=True) - virtualLinkDescId = serializers.CharField( - help_text="virtualLinkDescId", - required=False, - max_length=255, - allow_null=True) - networkResource = ResourceSerializer( - help_text="networkResource", - required=False, - allow_null=True) - - -class VnfcResourceInfoSerializer(serializers.Serializer): - vnfcInstanceId = serializers.CharField( - help_text="vnfcInstanceId", - required=False, - max_length=255, - allow_null=True) - vduId = serializers.CharField( - help_text="vduId", - required=False, max_length=255, allow_null=True) - storageResourceIds = serializers.CharField( - help_text="storageResourceIds", - required=False, - max_length=255, - allow_null=True) - computeResource = ResourceSerializer( - help_text="computeResource", - required=False, - allow_null=True) - - -class AccessInfoSerializer(serializers.Serializer): - tenant = serializers.CharField( - help_text="tenant", - required=True, - max_length=255, - allow_null=True) - username = serializers.CharField( - help_text="username", - required=True, - max_length=255, - allow_null=True) - password = serializers.CharField( - help_text="password", - required=True, - max_length=255, - allow_null=True) - - -class InterfaceInfoSerializer(serializers.Serializer): - vimType = serializers.CharField( - help_text="vimType", - required=True, - max_length=255, - allow_null=True) - apiVersion = serializers.CharField( - help_text="apiVersion", - required=True, - max_length=255, - allow_null=True) - protocolType = serializers.ChoiceField( - help_text="protocolType", - choices=["http", "https"], - required=True) - - -class VimInfoSerializer(serializers.Serializer): - vimInfoId = serializers.CharField( - help_text="vimInfoId", - required=False, - max_length=255, - allow_null=True) - vimId = serializers.CharField( - help_text="vimId", - required=False, - max_length=255, - allow_null=True) - interfaceEndpoint = serializers.CharField( - help_text="interfaceEndpoint", - required=False, - max_length=255, - allow_null=True) - interfaceInfo = InterfaceInfoSerializer( - help_text="vimInfoId", - required=False, - allow_null=True) - accessInfo = AccessInfoSerializer( - help_text="accessInfo", - required=False, - allow_null=True) - - -class LinkPortsSerializer(serializers.Serializer): - resourceId = serializers.CharField( - help_text="resourceId", - required=True, - max_length=255, - allow_null=True) - vimId = serializers.CharField( - help_text="vimId", - required=False, - max_length=255, - allow_null=True) - - -class ResourceHandleSerializer(serializers.Serializer): - resourceId = serializers.CharField( - help_text="resourceId", - required=True, - max_length=255, - allow_null=True) - vimId = serializers.CharField( - help_text="vimId", - required=False, - max_length=255, - allow_null=True) - resourceProviderId = serializers.CharField( - help_text="resourceProviderId", - required=False, - max_length=255, - allow_null=True) - - -class ExtVirtualLinkInfoSerializer(serializers.Serializer): - extVirtualLinkId = serializers.CharField( - help_text="extVirtualLinkId", - required=True, - max_length=255, - allow_null=True) - resourceHandle = ResourceHandleSerializer( - help_text="iPAddress", - required=True) - linkPorts = LinkPortsSerializer( - help_text="iPAddress", - many=True, - allow_null=True) - - -class L3AddressDataSerializer(serializers.Serializer): - iPAddressType = serializers.ChoiceField( - help_text="iPAddressType", - choices=["IPv4", "IPv6"], - required=True) - iPAddress = serializers.CharField( - help_text="iPAddress", - required=True, - max_length=255, - allow_null=True) - - -class NetworkAddressSerializer(serializers.Serializer): - addressType = serializers.ChoiceField( - help_text="addressType", - choices=["MAC", "IP"], - required=True) - l2AddressData = serializers.CharField( - help_text="l2AddressData", - required=False, - max_length=255, - allow_null=True) - l3AddressData = L3AddressDataSerializer( - help_text="addresses", - required=False) - - -class ExtCpInfoSerializer(serializers.Serializer): - cpInstanceId = serializers.CharField( - help_text="cpInstanceId", - required=False, - max_length=255, - allow_null=True) - cpdId = serializers.CharField( - help_text="cpdId", - required=True, - max_length=255, - allow_null=True) - numDynamicAddresses = serializers.CharField( - help_text="numDynamicAddresses", - required=False, - max_length=255, - allow_null=True) - addresses = NetworkAddressSerializer( - help_text="addresses", - many=True, - allow_null=True) - - -class ScaleInfoSerializer(serializers.Serializer): - aspectId = serializers.CharField( - help_text="aspectId", - required=True, - max_length=255, - allow_null=True) - scaleLevel = serializers.IntegerField( - help_text="scaleLevel", - required=True) - - -class instantiatedVnfInfoSerializer(serializers.Serializer): - flavourId = serializers.CharField( - help_text="flavourId", - required=True, - max_length=255, - allow_null=True) - vnfState = serializers.ChoiceField( - help_text="vnfState", - choices=["STARTED", "STOPPED", "NOT_INSTANTIATED", "INSTANTIATED", "FAILED"], - required=True, - allow_null=True) - scaleStatus = ScaleInfoSerializer( - help_text="scaleStatus", - many=True) - extCpInfo = ExtCpInfoSerializer( - help_text="extCpInfo", - many=True) - extVirtualLink = ExtVirtualLinkInfoSerializer( - help_text="extVirtualLink", - many=True) - monitoringParameters = serializers.DictField( - help_text="monitoringParameters", - child=serializers.CharField(allow_blank=True), - required=False, - allow_null=True) - vimInfo = VimInfoSerializer( - help_text="vimInfo", - many=True) - vnfcResourceInfo = VnfcResourceInfoSerializer( - help_text="vnfcResourceInfo", - many=True) - virtualLinkResourceInfo = VirtualLinkResourceInfoSerializer( - help_text="virtualLinkResourceInfo", - many=True) - virtualStorageResourceInfo = VirtualStorageResourceInfoSerializer( - help_text="virtualStorageResourceInfo", - many=True) - - -class VnfInfoSerializer(serializers.Serializer): - vnfInstanceId = serializers.CharField( - help_text="vnfInstanceId", - required=True, - max_length=255, - allow_null=True) - vnfInstanceName = serializers.CharField( - help_text="vnfInstanceName", - required=True, - max_length=255, - allow_null=True) - onboardedVnfPkgInfoId = serializers.CharField( - help_text="onboardedVnfPkgInfoId", - required=False, - max_length=255, - allow_null=True) - vnfdVersion = serializers.CharField( - help_text="vnfdVersion", - required=False, - max_length=255, - allow_null=True, - allow_blank=True) - vnfProvider = serializers.CharField( - help_text="vnfProvider", - required=False, - max_length=255, - allow_null=True, - allow_blank=True) - instantiatedVnfInfo = instantiatedVnfInfoSerializer( - help_text="instantiatedVnfInfo", - required=True) - - -class VnfsInfoSerializer(serializers.ListSerializer): - child = VnfInfoSerializer() - - -class ExtVirtualLinkSerizlizer(serializers.Serializer): - vlInstanceId = serializers.CharField( - help_text="vlInstanceId", - required=False, - max_length=255, - allow_null=True) - resourceSubnetId = serializers.CharField( - help_text="resourceSubnetId", - required=False, - max_length=255, - allow_null=True) - cpdId = serializers.CharField( - help_text="cpdId", - required=False, - max_length=255, - allow_null=True) - resourceId = serializers.CharField( - help_text="resourceId", - required=False, - max_length=255, - allow_null=True) - vim = VimInfoSerializer( - help_text="vim", - required=False, - allow_null=True) - extCps = ExtCpInfoSerializer( - help_text="extCps", - many=True, - required=False, - allow_null=True) - - -class AdditionalParamsSerializer(serializers.Serializer): - vimId = serializers.CharField( - help_text="vimId", - required=False, - max_length=255, - allow_null=True) - inputs = serializers.DictField( - help_text="inputs", - child=serializers.CharField(help_text="custom key-value", allow_blank=True), - required=False, - allow_null=True) - extVirtualLinks = serializers.ListSerializer( - help_text="extVirtualLinks", - child=ExtVirtualLinkSerizlizer(help_text="extVirtualLinks", required=False, allow_null=True), - required=False, - allow_null=True) - - -class InstantiateVnfRequestSerializer(serializers.Serializer): - flavourId = serializers.CharField( - help_text="flavourId", - required=True, - max_length=255, - allow_null=True) - instantiationLevelId = serializers.CharField( - help_text="instantiationLevelId", - required=True, - max_length=255, - allow_null=True) - localizationLanguage = serializers.CharField( - help_text="localizationLanguage", - required=True, - max_length=255, - allow_null=True) - vnfmId = serializers.CharField( - help_text="vnfmId", - required=False, - max_length=255, - allow_null=True) - extVirtualLinks = serializers.ListSerializer( - help_text="extVirtualLinks", - child=ExtVirtualLinkSerizlizer(help_text="extVirtualLinks", required=False, allow_null=True), - required=False, - allow_null=True) - additionalParams = AdditionalParamsSerializer( - help_text="additionalParams", - required=False, - allow_null=True) - - -class InstOrTeriVnfResponseSerializer(serializers.Serializer): - jobId = serializers.CharField( - help_text="jobId", - required=True, - max_length=255, - allow_null=True) - - -class TerminateVnfRequestSerializer(serializers.Serializer): - terminationType = serializers.CharField( - help_text="terminationType", - required=True, - max_length=255, - allow_null=True) - gracefulTerminationTimeout = serializers.IntegerField( - help_text="gracefulTerminationTimeout", - default=120, - required=False) diff --git a/lcm/lcm/nf/serializers/__init__.py b/lcm/lcm/nf/serializers/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/lcm/lcm/nf/serializers/common.py b/lcm/lcm/nf/serializers/common.py new file mode 100644 index 00000000..ca9a1945 --- /dev/null +++ b/lcm/lcm/nf/serializers/common.py @@ -0,0 +1,13 @@ +# Copyright 2018 ZTE Corporation. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. diff --git a/lcm/lcm/nf/serializers/serializers.py b/lcm/lcm/nf/serializers/serializers.py new file mode 100644 index 00000000..d7555c64 --- /dev/null +++ b/lcm/lcm/nf/serializers/serializers.py @@ -0,0 +1,616 @@ +# Copyright 2018 ZTE Corporation. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from rest_framework import serializers + + +class CreateVnfReqSerializer(serializers.Serializer): + vnfdId = serializers.CharField( + help_text="Identifier that identifies the VNFD which defines the VNF instance to be created.", + max_length=255, + required=True, + allow_null=True) + vnfInstanceName = serializers.CharField( + help_text="Human-readable name of the VNF instance to be created.", + max_length=255, + required=True, + allow_null=False) + vnfInstanceDescription = serializers.CharField( + help_text="Human-readable description of the VNF instance to be created.", + max_length=255, + required=False, + allow_null=True) + + +class CreateVnfRespSerializer(serializers.Serializer): + vnfInstanceId = serializers.CharField( + help_text="Identifier of the VNF instance", + required=True, + max_length=255, + allow_null=True) + + +class ResourceSerializer(serializers.Serializer): + resourceId = serializers.CharField( + help_text="resourceId", + required=True, + max_length=255, + allow_null=True) + vimId = serializers.CharField( + help_text="vimId", + required=True, + max_length=255, + allow_null=True) + + +class VirtualStorageResourceInfoSerializer(serializers.Serializer): + virtualStorageInstanceId = serializers.CharField( + help_text="virtualStorageInstanceId", + required=False, + allow_null=True, + max_length=255) + virtualStorageDescId = serializers.CharField( + help_text="virtualStorageDescId", + required=False, + max_length=255, + allow_null=True) + storageResource = ResourceSerializer( + help_text="storageResource", + required=False, + allow_null=True) + + +class VirtualLinkResourceInfoSerializer(serializers.Serializer): + virtualLinkInstanceId = serializers.CharField( + help_text="virtualLinkInstanceId", + required=False, + max_length=255, + allow_null=True) + virtualLinkDescId = serializers.CharField( + help_text="virtualLinkDescId", + required=False, + max_length=255, + allow_null=True) + networkResource = ResourceSerializer( + help_text="networkResource", + required=False, + allow_null=True) + + +class VnfcResourceInfoSerializer(serializers.Serializer): + vnfcInstanceId = serializers.CharField( + help_text="vnfcInstanceId", + required=False, + max_length=255, + allow_null=True) + vduId = serializers.CharField( + help_text="vduId", + required=False, max_length=255, allow_null=True) + storageResourceIds = serializers.CharField( + help_text="storageResourceIds", + required=False, + max_length=255, + allow_null=True) + computeResource = ResourceSerializer( + help_text="computeResource", + required=False, + allow_null=True) + + +class AccessInfoSerializer(serializers.Serializer): + tenant = serializers.CharField( + help_text="tenant", + required=True, + max_length=255, + allow_null=True) + username = serializers.CharField( + help_text="username", + required=True, + max_length=255, + allow_null=True) + password = serializers.CharField( + help_text="password", + required=True, + max_length=255, + allow_null=True) + + +class InterfaceInfoSerializer(serializers.Serializer): + vimType = serializers.CharField( + help_text="vimType", + required=True, + max_length=255, + allow_null=True) + apiVersion = serializers.CharField( + help_text="apiVersion", + required=True, + max_length=255, + allow_null=True) + protocolType = serializers.ChoiceField( + help_text="protocolType", + choices=["http", "https"], + required=True) + + +class VimInfoSerializer(serializers.Serializer): + vimInfoId = serializers.CharField( + help_text="vimInfoId", + required=False, + max_length=255, + allow_null=True) + vimId = serializers.CharField( + help_text="vimId", + required=False, + max_length=255, + allow_null=True) + interfaceEndpoint = serializers.CharField( + help_text="interfaceEndpoint", + required=False, + max_length=255, + allow_null=True) + interfaceInfo = InterfaceInfoSerializer( + help_text="vimInfoId", + required=False, + allow_null=True) + accessInfo = AccessInfoSerializer( + help_text="accessInfo", + required=False, + allow_null=True) + + +class LinkPortsSerializer(serializers.Serializer): + resourceId = serializers.CharField( + help_text="resourceId", + required=True, + max_length=255, + allow_null=True) + vimId = serializers.CharField( + help_text="vimId", + required=False, + max_length=255, + allow_null=True) + + +class ResourceHandleSerializer(serializers.Serializer): + resourceId = serializers.CharField( + help_text="resourceId", + required=True, + max_length=255, + allow_null=True) + vimId = serializers.CharField( + help_text="vimId", + required=False, + max_length=255, + allow_null=True) + resourceProviderId = serializers.CharField( + help_text="resourceProviderId", + required=False, + max_length=255, + allow_null=True) + + +class ExtVirtualLinkInfoSerializer(serializers.Serializer): + extVirtualLinkId = serializers.CharField( + help_text="extVirtualLinkId", + required=True, + max_length=255, + allow_null=True) + resourceHandle = ResourceHandleSerializer( + help_text="iPAddress", + required=True) + linkPorts = LinkPortsSerializer( + help_text="iPAddress", + many=True, + allow_null=True) + + +class L3AddressDataSerializer(serializers.Serializer): + iPAddressType = serializers.ChoiceField( + help_text="iPAddressType", + choices=["IPv4", "IPv6"], + required=True) + iPAddress = serializers.CharField( + help_text="iPAddress", + required=True, + max_length=255, + allow_null=True) + + +class NetworkAddressSerializer(serializers.Serializer): + addressType = serializers.ChoiceField( + help_text="addressType", + choices=["MAC", "IP"], + required=True) + l2AddressData = serializers.CharField( + help_text="l2AddressData", + required=False, + max_length=255, + allow_null=True) + l3AddressData = L3AddressDataSerializer( + help_text="addresses", + required=False) + + +class ExtCpInfoSerializer(serializers.Serializer): + cpInstanceId = serializers.CharField( + help_text="cpInstanceId", + required=False, + max_length=255, + allow_null=True) + cpdId = serializers.CharField( + help_text="cpdId", + required=True, + max_length=255, + allow_null=True) + numDynamicAddresses = serializers.CharField( + help_text="numDynamicAddresses", + required=False, + max_length=255, + allow_null=True) + addresses = NetworkAddressSerializer( + help_text="addresses", + many=True, + allow_null=True) + + +class ScaleInfoSerializer(serializers.Serializer): + aspectId = serializers.CharField( + help_text="aspectId", + required=True, + max_length=255, + allow_null=True) + scaleLevel = serializers.IntegerField( + help_text="scaleLevel", + required=True) + + +class instantiatedVnfInfoSerializer(serializers.Serializer): + flavourId = serializers.CharField( + help_text="flavourId", + required=True, + max_length=255, + allow_null=True) + vnfState = serializers.ChoiceField( + help_text="vnfState", + choices=["STARTED", "STOPPED", "NOT_INSTANTIATED", "INSTANTIATED", "FAILED"], + required=True, + allow_null=True) + scaleStatus = ScaleInfoSerializer( + help_text="scaleStatus", + many=True) + extCpInfo = ExtCpInfoSerializer( + help_text="extCpInfo", + many=True) + extVirtualLink = ExtVirtualLinkInfoSerializer( + help_text="extVirtualLink", + many=True) + monitoringParameters = serializers.DictField( + help_text="monitoringParameters", + child=serializers.CharField(allow_blank=True), + required=False, + allow_null=True) + vimInfo = VimInfoSerializer( + help_text="vimInfo", + many=True) + vnfcResourceInfo = VnfcResourceInfoSerializer( + help_text="vnfcResourceInfo", + many=True) + virtualLinkResourceInfo = VirtualLinkResourceInfoSerializer( + help_text="virtualLinkResourceInfo", + many=True) + virtualStorageResourceInfo = VirtualStorageResourceInfoSerializer( + help_text="virtualStorageResourceInfo", + many=True) + + +class VnfInfoSerializer(serializers.Serializer): + vnfInstanceId = serializers.CharField( + help_text="vnfInstanceId", + required=True, + max_length=255, + allow_null=True) + vnfInstanceName = serializers.CharField( + help_text="vnfInstanceName", + required=True, + max_length=255, + allow_null=True) + onboardedVnfPkgInfoId = serializers.CharField( + help_text="onboardedVnfPkgInfoId", + required=False, + max_length=255, + allow_null=True) + vnfdVersion = serializers.CharField( + help_text="vnfdVersion", + required=False, + max_length=255, + allow_null=True, + allow_blank=True) + vnfProvider = serializers.CharField( + help_text="vnfProvider", + required=False, + max_length=255, + allow_null=True, + allow_blank=True) + instantiatedVnfInfo = instantiatedVnfInfoSerializer( + help_text="instantiatedVnfInfo", + required=True) + + +class VnfsInfoSerializer(serializers.ListSerializer): + child = VnfInfoSerializer() + + +class ExtVirtualLinkSerizlizer(serializers.Serializer): + vlInstanceId = serializers.CharField( + help_text="vlInstanceId", + required=False, + max_length=255, + allow_null=True) + resourceSubnetId = serializers.CharField( + help_text="resourceSubnetId", + required=False, + max_length=255, + allow_null=True) + cpdId = serializers.CharField( + help_text="cpdId", + required=False, + max_length=255, + allow_null=True) + resourceId = serializers.CharField( + help_text="resourceId", + required=False, + max_length=255, + allow_null=True) + vim = VimInfoSerializer( + help_text="vim", + required=False, + allow_null=True) + extCps = ExtCpInfoSerializer( + help_text="extCps", + many=True, + required=False, + allow_null=True) + + +class AdditionalParamsSerializer(serializers.Serializer): + vimId = serializers.CharField( + help_text="vimId", + required=False, + max_length=255, + allow_null=True) + inputs = serializers.DictField( + help_text="inputs", + child=serializers.CharField(help_text="custom key-value", allow_blank=True), + required=False, + allow_null=True) + extVirtualLinks = serializers.ListSerializer( + help_text="extVirtualLinks", + child=ExtVirtualLinkSerizlizer(help_text="extVirtualLinks", required=False, allow_null=True), + required=False, + allow_null=True) + + +class InstantiateVnfRequestSerializer(serializers.Serializer): + flavourId = serializers.CharField( + help_text="flavourId", + required=True, + max_length=255, + allow_null=True) + instantiationLevelId = serializers.CharField( + help_text="instantiationLevelId", + required=True, + max_length=255, + allow_null=True) + localizationLanguage = serializers.CharField( + help_text="localizationLanguage", + required=True, + max_length=255, + allow_null=True) + vnfmId = serializers.CharField( + help_text="vnfmId", + required=False, + max_length=255, + allow_null=True) + extVirtualLinks = serializers.ListSerializer( + help_text="extVirtualLinks", + child=ExtVirtualLinkSerizlizer(help_text="extVirtualLinks", required=False, allow_null=True), + required=False, + allow_null=True) + additionalParams = AdditionalParamsSerializer( + help_text="additionalParams", + required=False, + allow_null=True) + + +class InstOrTeriVnfResponseSerializer(serializers.Serializer): + jobId = serializers.CharField( + help_text="jobId", + required=True, + max_length=255, + allow_null=True) + + +class TerminateVnfRequestSerializer(serializers.Serializer): + terminationType = serializers.CharField( + help_text="terminationType", + required=True, + max_length=255, + allow_null=True) + gracefulTerminationTimeout = serializers.IntegerField( + help_text="gracefulTerminationTimeout", + default=120, + required=False) + + +class VimInfoSerializer(serializers.Serializer): + id = serializers.CharField( + help_text="The identifier of the VIM Connection. This identifier is managed by the NFVO.", + required=False, + max_length=255, + allow_null=True) + vimId = serializers.CharField( + help_text="The identifier of the VIM instance. This identifier is managed by the NFVO.", + required=False, + max_length=255, + allow_null=True) + vimType = serializers.CharField( + help_text="Discriminator for the different types of the VIM information.", + required=False, + max_length=255, + allow_null=True) + interfaceInfo = serializers.DictField( + help_text="Information about the interface or interfaces to the VIM", + child=serializers.CharField(allow_blank=True), + required=False, + allow_null=True) + accessInfo = serializers.DictField( + help_text="Authentication credentials for accessing the VIM, and other access-related information", + child=serializers.CharField(allow_blank=True), + required=False, + allow_null=True) + extra = serializers.DictField( + help_text="VIM type specific additional information.", + child=serializers.CharField(allow_blank=True), + required=False, + allow_null=True) + + +class ScaleInfoSerializer(serializers.Serializer): + aspectId = serializers.CharField( + help_text="Identifier of the scaling aspect.", + required=True, + max_length=255, + allow_null=True) + scaleLevel = serializers.IntegerField( + help_text="Indicates the scale level.", + required=True) + + +class CpProtocolInfoSerializer(serializers.Serializer): + layerProtocol = serializers.ChoiceField( + help_text="The identifier of layer(s) and protocol(s) associated to the network address information.", + choices=["IP_OVER_ETHERNET"], + required=False, + allow_null=True) + ipOverEthernet = serializers.DictField( + help_text="IP addresses over Ethernet to assign to the extCP instance.", + child=serializers.CharField(allow_blank=True), + required=False, + allow_null=True) + + +class ExtCpInfoSerializer(serializers.Serializer): + id = serializers.CharField( + help_text="Identifier of the external CP instance and the related information instance.", + required=False, + max_length=255, + allow_null=True) + cpdId = serializers.CharField( + help_text="Identifier of the external CPD, VnfExtCpd, in the VNFD.", + required=True, + max_length=255, + allow_null=True) + cpProtocolInfo = CpProtocolInfoSerializer( + help_text="Network protocol information for this CP.", + required=False, + allow_null=True) + extLinkPortId = serializers.CharField( + help_text="Identifier of the 'extLinkPortInfo' structure inside the 'extVirtualLinkInfo' structure.", + required=False, + max_length=255, + allow_null=True) + + +class instantiatedVnfInfoSerializer(serializers.Serializer): + flavourId = serializers.CharField( + help_text="Identifier of the VNF deployment flavour applied to this VNF instance.", + required=True, + max_length=255, + allow_null=True) + vnfState = serializers.ChoiceField( + help_text="State of the VNF instance.", + choices=["STARTED", "STOPPED"], + required=True, + allow_null=True) + scaleStatus = ScaleInfoSerializer( + help_text="Scale status of the VNF, one entry per aspect.", + required=False, + many=True) + extCpInfo = ExtCpInfoSerializer( + help_text="Information about the external CPs exposed by the VNF instance.", + required=False, + many=True) + + +class VnfInstanceSerializer(serializers.Serializer): + id = serializers.CharField( + help_text="Identifier of the VNF instance", + required=True) + vnfInstanceName = serializers.CharField( + help_text="Name of the VNF instance.", + required=False, + allow_null=True, + allow_blank=True) + vnfInstanceDescription = serializers.CharField( + help_text="Human-readable description of the VNF instance.", + required=False, + allow_null=True, + allow_blank=True) + vnfdId = serializers.CharField( + help_text="Identifier of the VNFD on which the VNF instance is based.", + required=False, + allow_null=True, + allow_blank=True) + vnfProvider = serializers.CharField( + help_text="Provider of the VNF and the VNFD. The value is copied from the VNFD.", + required=False, + allow_null=True, + allow_blank=True) + vnfProductName = serializers.CharField( + help_text="Name to identify the VNF Product. The value is copied from the VNFD.", + required=False, + allow_null=True, + allow_blank=True) + vnfSoftwareVersion = serializers.CharField( + help_text="Software version of the VNF. The value is copied from the VNFD.", + required=False, + allow_null=True, + allow_blank=True) + vnfdVersion = serializers.CharField( + help_text="Identifies the version of the VNFD. The value is copied from the VNFD.", + required=False, + allow_null=True, + allow_blank=True) + vnfPkgId = serializers.CharField( + help_text="Identifier of information held by the NFVO about the specific VNF package on which the VNF is based.", + required=False, + allow_null=True, + allow_blank=True) + vnfConfigurableProperties = serializers.DictField( + help_text="Current values of the configurable properties of the VNF instance.", + child=serializers.CharField(allow_blank=True), + required=False, + allow_null=True) + vimConnectionInfo = VimInfoSerializer( + help_text="Information about VIM connections to be used for managing the resources for the VNF instance.", + required=False, + allow_null=True) + instantiationState = serializers.ChoiceField( + help_text="The instantiation state of the VNF.", + choices=["NOT_INSTANTIATED", "INSTANTIATED"], + required=False, + allow_null=True) + instantiatedVnfInfo = instantiatedVnfInfoSerializer( + help_text="Information specific to an instantiated VNF instance.", + required=False) diff --git a/lcm/lcm/nf/tests/test_create_vnf.py b/lcm/lcm/nf/tests/test_create_vnf.py new file mode 100644 index 00000000..368b22f7 --- /dev/null +++ b/lcm/lcm/nf/tests/test_create_vnf.py @@ -0,0 +1,78 @@ +# Copyright 2017 ZTE Corporation. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import json + +import mock +from django.test import TestCase +from rest_framework import status +from rest_framework.test import APIClient +from lcm.nf.const import vnfpackage_info +from lcm.pub.database.models import NfInstModel, JobStatusModel +from lcm.pub.utils import restcall +from lcm.pub.utils.timeutil import now_time + + +class TestNFInstantiate(TestCase): + def setUp(self): + self.client = APIClient() + self.grant_result = { + "vimid": 'vimid_1', + "tenant": 'tenantname_1' + } + + def tearDown(self): + pass + + def assert_job_result(self, job_id, job_progress, job_detail): + jobs = JobStatusModel.objects.filter(jobid=job_id, + progress=job_progress, + descp=job_detail) + self.assertEqual(1, len(jobs)) + + def test_create_vnf_identifier_when_vnf_is_exist(self): + NfInstModel.objects.create(nfinstid='1111', + nf_name='vFW_01', + package_id='222', + version='', + vendor='', + netype='', + vnfd_model='', + status='NOT_INSTANTIATED', + nf_desc='vFW in Nanjing TIC Edge', + vnfdid='111', + create_time=now_time()) + data = { + "vnfdId": "111", + "vnfInstanceName": "vFW_01", + "vnfInstanceDescription": "vFW in Nanjing TIC Edge" + } + response = self.client.post("/api/vnflcm/v1/vnf_instances", data=data, format='json') + self.failUnlessEqual(status.HTTP_500_INTERNAL_SERVER_ERROR, response.status_code) + context = json.loads(response.content) + self.assertEqual({'error': 'VNF is already exist.'}, context) + + @mock.patch.object(restcall, 'call_req') + def test_create_vnf_identifier(self, mock_call_req): + r2_get_vnfpackage_from_catalog = [0, json.JSONEncoder().encode(vnfpackage_info), '200'] + mock_call_req.side_effect = [r2_get_vnfpackage_from_catalog] + data = { + "vnfdId": "111", + "vnfInstanceName": "vFW_01", + "vnfInstanceDescription": "vFW in Nanjing TIC Edge" + } + response = self.client.post("/api/vnflcm/v1/vnf_instances", data=data, format='json') + self.failUnlessEqual(status.HTTP_201_CREATED, response.status_code) + context = json.loads(response.content) + self.assertTrue(NfInstModel.objects.filter(nfinstid=context['vnfInstanceId']).exists()) diff --git a/lcm/lcm/nf/tests/test_delete_vnf.py b/lcm/lcm/nf/tests/test_delete_vnf.py new file mode 100644 index 00000000..26679231 --- /dev/null +++ b/lcm/lcm/nf/tests/test_delete_vnf.py @@ -0,0 +1,110 @@ +# Copyright 2017 ZTE Corporation. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + + +from django.test import TestCase, Client +from rest_framework import status + +from lcm.pub.database.models import NfInstModel, JobStatusModel, VmInstModel, NetworkInstModel, SubNetworkInstModel, \ + PortInstModel, FlavourInstModel, StorageInstModel, NfvoRegInfoModel +from lcm.pub.utils.timeutil import now_time + + +class TestNFTerminate(TestCase): + def setUp(self): + self.client = Client() + StorageInstModel.objects.create(storageid="1", + vimid="1", + resouceid="11", + insttype=0, + instid="1111", + is_predefined=1) + NetworkInstModel.objects.create(networkid='1', + vimid='1', + resouceid='1', + name='pnet_network', + is_predefined=1, + tenant='admin', + insttype=0, + instid='1111') + SubNetworkInstModel.objects.create(subnetworkid='1', + vimid='1', + resouceid='1', + networkid='1', + is_predefined=1, + name='sub_pnet', + tenant='admin', + insttype=0, + instid='1111') + PortInstModel.objects.create(portid='1', + networkid='1', + subnetworkid='1', + vimid='1', + resouceid='1', + is_predefined=1, + name='aaa_pnet_cp', + tenant='admin', + insttype=0, + instid='1111') + FlavourInstModel.objects.create(flavourid="1", + vimid="1", + resouceid="11", + instid="1111", + is_predefined=1) + VmInstModel.objects.create(vmid="1", + vimid="1", + resouceid="11", + insttype=0, + instid="1111", + vmname="test_01", + is_predefined=1, + operationalstate=1) + NfvoRegInfoModel.objects.create(nfvoid='1111', + vnfminstid='11111', + apiurl='1') + + def tearDown(self): + VmInstModel.objects.all().delete() + NetworkInstModel.objects.all().delete() + SubNetworkInstModel.objects.all().delete() + PortInstModel.objects.all().delete() + + def assert_job_result(self, job_id, job_progress, job_detail): + jobs = JobStatusModel.objects.filter(jobid=job_id, + progress=job_progress, + descp=job_detail) + self.assertEqual(1, len(jobs)) + + def test_delete_vnf_identifier(self): + NfInstModel.objects.create(nfinstid='1111', + nf_name='2222', + package_id='todo', + version='', + vendor='', + netype='', + vnfd_model='', + status='NOT_INSTANTIATED', + nf_desc='', + vnfdid='', + vnfSoftwareVersion='', + vnfConfigurableProperties='todo', + localizationLanguage='EN_US', + create_time=now_time()) + response = self.client.delete("/api/vnflcm/v1/vnf_instances/1111") + self.failUnlessEqual(status.HTTP_204_NO_CONTENT, response.status_code) + self.assertEqual(None, response.data) + + def test_delete_vnf_identifier_when_vnf_not_exist(self): + response = self.client.delete("/api/vnflcm/v1/vnf_instances/1111") + self.failUnlessEqual(status.HTTP_204_NO_CONTENT, response.status_code) diff --git a/lcm/lcm/nf/tests/test_instantiate_vnf.py b/lcm/lcm/nf/tests/test_instantiate_vnf.py new file mode 100644 index 00000000..7cf2646f --- /dev/null +++ b/lcm/lcm/nf/tests/test_instantiate_vnf.py @@ -0,0 +1,166 @@ +# Copyright 2017 ZTE Corporation. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import json +import uuid + +import mock +from django.test import TestCase +from rest_framework import status +from rest_framework.test import APIClient + +from lcm.nf.biz.instantiate_vnf import InstantiateVnf +from lcm.nf.const import c1_data_get_tenant_id, c4_data_create_network, c2_data_create_volume, \ + c5_data_create_subnet, c3_data_get_volume, c6_data_create_port, c7_data_create_flavor, c8_data_list_image, \ + c9_data_create_vm, c10_data_get_vm, inst_req_data, vnfpackage_info +from lcm.pub.database.models import NfInstModel, JobStatusModel +from lcm.pub.utils import restcall +from lcm.pub.utils.jobutil import JobUtil +from lcm.pub.utils.timeutil import now_time +from lcm.pub.vimapi import api + + +class TestNFInstantiate(TestCase): + def setUp(self): + self.client = APIClient() + self.grant_result = { + "vimid": 'vimid_1', + "tenant": 'tenantname_1' + } + + def tearDown(self): + pass + + def assert_job_result(self, job_id, job_progress, job_detail): + jobs = JobStatusModel.objects.filter(jobid=job_id, + progress=job_progress, + descp=job_detail) + self.assertEqual(1, len(jobs)) + + @mock.patch.object(InstantiateVnf, 'run') + def test_instantiate_vnf(self, mock_run): + NfInstModel(nfinstid='12', nf_name='VNF1').save() + mock_run.re.return_value = None + response = self.client.post("/api/vnflcm/v1/vnf_instances/12/instantiate", data=inst_req_data, format='json') + self.failUnlessEqual(status.HTTP_202_ACCEPTED, response.status_code) + + 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") + jobs = JobStatusModel.objects.filter(jobid=self.job_id, + progress=0, + descp="INST_VNF_READY") + self.assertEqual(1, len(jobs)) + data = inst_req_data + InstantiateVnf(data, nf_inst_id=self.nf_inst_id, job_id=self.job_id).run() + self.assert_job_result(self.job_id, 255, "VNF nf_inst_id is not exist.") + + @mock.patch.object(restcall, 'call_req') + def test_instantiate_vnf_when_get_packageinfo_by_csarid_failed(self, mock_call_req): + NfInstModel.objects.create(nfinstid='1111', + nf_name='vFW_01', + package_id='222', + version='', + vendor='', + netype='', + vnfd_model='', + status='NOT_INSTANTIATED', + nf_desc='vFW in Nanjing TIC Edge', + vnfdid='111', + create_time=now_time()) + r1_get_vnfpackage_by_vnfdid = [1, json.JSONEncoder().encode(vnfpackage_info), '200'] + mock_call_req.side_effect = [r1_get_vnfpackage_by_vnfdid] + self.nf_inst_id = '1111' + 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 + InstantiateVnf(data, nf_inst_id=self.nf_inst_id, job_id=self.job_id).run() + self.assert_job_result(self.job_id, 255, "Failed to query vnf CSAR(111) from catalog.") + + @mock.patch.object(restcall, 'call_req') + def test_instantiate_vnf_when_applay_grant_failed(self, mock_call_req): + NfInstModel.objects.create(nfinstid='1111', + nf_name='vFW_01', + package_id='222', + version='', + vendor='', + netype='', + vnfd_model='', + status='NOT_INSTANTIATED', + nf_desc='vFW in Nanjing TIC Edge', + vnfdid='111', + create_time=now_time()) + r1_get_vnfpackage_by_vnfdid = [0, json.JSONEncoder().encode(vnfpackage_info), '200'] + r2_apply_grant_result = [1, json.JSONEncoder().encode(self.grant_result), '200'] + mock_call_req.side_effect = [r1_get_vnfpackage_by_vnfdid, r2_apply_grant_result] + self.nf_inst_id = '1111' + 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 + InstantiateVnf(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') + @mock.patch.object(api, 'call') + def test_instantiate_vnf_when_unexpected_exception(self, mock_call, mock_call_req): + NfInstModel.objects.create(nfinstid='1111', + nf_name='vFW_01', + package_id='222', + version='', + vendor='', + netype='', + vnfd_model='', + status='NOT_INSTANTIATED', + nf_desc='vFW in Nanjing TIC Edge', + vnfdid='111', + create_time=now_time()) + r1_get_vnfpackage_by_vnfdid = [0, json.JSONEncoder().encode(vnfpackage_info), '200'] + r2_apply_grant_result = [0, json.JSONEncoder().encode(self.grant_result), '200'] + mock_call_req.side_effect = [r1_get_vnfpackage_by_vnfdid, r2_apply_grant_result] + mock_call.side_effect = [c1_data_get_tenant_id, c2_data_create_volume, c3_data_get_volume] + self.nf_inst_id = '1111' + 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 + InstantiateVnf(data, nf_inst_id=self.nf_inst_id, job_id=self.job_id).run() + self.assert_job_result(self.job_id, 255, "unexpected exception") + + @mock.patch.object(restcall, 'call_req') + @mock.patch.object(api, 'call') + def test_instantiate_vnf_success(self, mock_call, mock_call_req): + NfInstModel.objects.create(nfinstid='1111', + nf_name='vFW_01', + package_id='222', + version='', + vendor='', + netype='', + vnfd_model='', + status='NOT_INSTANTIATED', + nf_desc='vFW in Nanjing TIC Edge', + vnfdid='111', + create_time=now_time()) + r1_get_vnfpackage_by_vnfdid = [0, json.JSONEncoder().encode(vnfpackage_info), '200'] + r2_apply_grant_result = [0, json.JSONEncoder().encode(self.grant_result), '200'] + r3_lcm_notify_result = [0, json.JSONEncoder().encode(''), '200'] + mock_call_req.side_effect = [r1_get_vnfpackage_by_vnfdid, r2_apply_grant_result, r3_lcm_notify_result] + mock_call.side_effect = [c1_data_get_tenant_id, c2_data_create_volume, c3_data_get_volume, + c4_data_create_network, c5_data_create_subnet, c6_data_create_port, + c7_data_create_flavor, c8_data_list_image, c9_data_create_vm, c10_data_get_vm] + self.nf_inst_id = '1111' + 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 + InstantiateVnf(data, nf_inst_id=self.nf_inst_id, job_id=self.job_id).run() + self.assert_job_result(self.job_id, 100, "Instantiate Vnf success.") diff --git a/lcm/lcm/nf/tests/test_query_vnf.py b/lcm/lcm/nf/tests/test_query_vnf.py new file mode 100644 index 00000000..991583e7 --- /dev/null +++ b/lcm/lcm/nf/tests/test_query_vnf.py @@ -0,0 +1,136 @@ +# Copyright 2017 ZTE Corporation. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from django.test import TestCase, Client +from rest_framework import status + +from lcm.pub.database.models import NfInstModel, StorageInstModel + + +class ResourceTest(TestCase): + def setUp(self): + self.client = Client() + self.nf_inst_id = "01" + NfInstModel.objects.all().delete() + self.test_data_single_vnf = { + "vnfInstanceId": "1", + "vnfInstanceName": "VNF1", + "vnfProvider": None, + "instantiatedVnfInfo": { + "vnfState": None, + "extCpInfo": [], + "virtualStorageResourceInfo": [ + { + "virtualStorageInstanceId": "s02", + "storageResource": { + "resourceId": "resource01", + "vimId": "vim01" + } + } + ], + "extVirtualLink": [], + "vnfcResourceInfo": [], + "monitoringParameters": {}, + "vimInfo": [], + "flavourId": None, + "virtualLinkResourceInfo": [], + "scaleStatus": [] + }, + "vnfdVersion": None, + "onboardedVnfPkgInfoId": None + } + self.test_data_multi_vnf = [ + { + "vnfInstanceId": "1", + "vnfInstanceName": "VNF1", + "vnfProvider": None, + "instantiatedVnfInfo": { + "vnfState": None, + "extCpInfo": [], + "virtualStorageResourceInfo": [ + { + "virtualStorageInstanceId": "s01", + "storageResource": { + "resourceId": "resource01", + "vimId": "vim01" + } + } + ], + "extVirtualLink": [], + "vnfcResourceInfo": [], + "monitoringParameters": {}, + "vimInfo": [], + "flavourId": None, + "virtualLinkResourceInfo": [], + "scaleStatus": [] + }, + "vnfdVersion": None, + "onboardedVnfPkgInfoId": None + }, + { + "vnfInstanceId": "2", + "vnfInstanceName": "VNF2", + "vnfProvider": None, + "instantiatedVnfInfo": { + "vnfState": None, + "extCpInfo": [], + "virtualStorageResourceInfo": [ + { + "virtualStorageInstanceId": "s02", + "storageResource": { + "resourceId": "resource02", + "vimId": "vim02" + } + } + ], + "extVirtualLink": [], + "vnfcResourceInfo": [], + "monitoringParameters": {}, + "vimInfo": [], + "flavourId": None, + "virtualLinkResourceInfo": [], + "scaleStatus": [] + }, + "vnfdVersion": None, + "onboardedVnfPkgInfoId": None + } + ] + + def tearDown(self): + pass + + def test_get_vnf(self): + vnf_inst_id = "1" + NfInstModel(nfinstid=vnf_inst_id, nf_name='VNF1').save() + StorageInstModel(storageid='s02', + vimid='vim01', + resouceid='resource01', + insttype=1, + instid=vnf_inst_id).save() + response = self.client.get("/api/vnflcm/v1/vnf_instances/%s" % vnf_inst_id, format='json') + self.assertEqual(response.status_code, status.HTTP_200_OK) + self.assertEqual(self.test_data_single_vnf, response.data) + + def test_get_vnfs(self): + for i in range(1, 3): + NfInstModel(nfinstid='%s' % i, + nf_name='VNF%s' % i).save() + StorageInstModel(storageid='s0%s' % i, + vimid='vim0%s' % i, + resouceid='resource0%s' % i, + insttype=1, + instid='%s' % i).save() + response = self.client.get("/api/vnflcm/v1/vnf_instances", format='json') + self.failUnlessEqual(status.HTTP_200_OK, response.status_code) + self.assertEqual(self.test_data_multi_vnf, response.data) diff --git a/lcm/lcm/nf/tests/test_terminate_vnf.py b/lcm/lcm/nf/tests/test_terminate_vnf.py new file mode 100644 index 00000000..0136862a --- /dev/null +++ b/lcm/lcm/nf/tests/test_terminate_vnf.py @@ -0,0 +1,153 @@ +# Copyright 2017 ZTE Corporation. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + + +import json +import uuid + +import mock +from django.test import TestCase, Client +from rest_framework import status + +from lcm.nf.biz.terminate_vnf import TerminateVnf +from lcm.pub.database.models import NfInstModel, JobStatusModel, VmInstModel, NetworkInstModel, SubNetworkInstModel, \ + PortInstModel, FlavourInstModel, StorageInstModel, NfvoRegInfoModel +from lcm.pub.utils import restcall +from lcm.pub.utils.jobutil import JobUtil +from lcm.pub.utils.timeutil import now_time +from lcm.pub.vimapi import api + + +class TestNFTerminate(TestCase): + def setUp(self): + self.client = Client() + StorageInstModel.objects.create(storageid="1", + vimid="1", + resouceid="11", + insttype=0, + instid="1111", + is_predefined=1) + NetworkInstModel.objects.create(networkid='1', + vimid='1', + resouceid='1', + name='pnet_network', + is_predefined=1, + tenant='admin', + insttype=0, + instid='1111') + SubNetworkInstModel.objects.create(subnetworkid='1', + vimid='1', + resouceid='1', + networkid='1', + is_predefined=1, + name='sub_pnet', + tenant='admin', + insttype=0, + instid='1111') + PortInstModel.objects.create(portid='1', + networkid='1', + subnetworkid='1', + vimid='1', + resouceid='1', + is_predefined=1, + name='aaa_pnet_cp', + tenant='admin', + insttype=0, + instid='1111') + FlavourInstModel.objects.create(flavourid="1", + vimid="1", + resouceid="11", + instid="1111", + is_predefined=1) + VmInstModel.objects.create(vmid="1", + vimid="1", + resouceid="11", + insttype=0, + instid="1111", + vmname="test_01", + is_predefined=1, + operationalstate=1) + NfvoRegInfoModel.objects.create(nfvoid='1111', + vnfminstid='11111', + apiurl='1') + + def tearDown(self): + VmInstModel.objects.all().delete() + NetworkInstModel.objects.all().delete() + SubNetworkInstModel.objects.all().delete() + PortInstModel.objects.all().delete() + + def assert_job_result(self, job_id, job_progress, job_detail): + jobs = JobStatusModel.objects.filter(jobid=job_id, + progress=job_progress, + descp=job_detail) + self.assertEqual(1, len(jobs)) + + @mock.patch.object(TerminateVnf, 'run') + def test_terminate_vnf(self, mock_run): + req_data = { + "terminationType": "GRACEFUL", + "gracefulTerminationTimeout": 120 + } + NfInstModel(nfinstid='12', nf_name='VNF1').save() + mock_run.re.return_value = None + response = self.client.post("/api/vnflcm/v1/vnf_instances/12/terminate", data=req_data, format='json') + self.failUnlessEqual(status.HTTP_202_ACCEPTED, response.status_code) + + def test_terminate_vnf_when_inst_id_not_exist(self): + data = { + "terminationType": "GRACEFUL", + "gracefulTerminationTimeout": 120 + } + 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") + TerminateVnf(data, nf_inst_id=self.nf_inst_id, job_id=self.job_id).run() + self.assert_job_result(self.job_id, 100, "Terminate Vnf success.") + + @mock.patch.object(restcall, 'call_req') + @mock.patch.object(api, 'call') + def test_terminate_vnf_success(self, mock_call, mock_call_req): + NfInstModel.objects.create(nfinstid='1111', + nf_name='2222', + package_id='todo', + version='', + vendor='', + netype='', + vnfd_model='', + status='VNF_INSTANTIATED', + nf_desc='', + vnfdid='', + vnfSoftwareVersion='', + vnfConfigurableProperties='todo', + localizationLanguage='EN_US', + create_time=now_time()) + t1_apply_grant_result = [0, json.JSONEncoder().encode( + { + "vimid": 'vimid_1', + "tenant": 'tenantname_1' + }), '200'] + t2_lcm_notify_result = [0, json.JSONEncoder().encode(''), '200'] + t3_delete_flavor = [0, json.JSONEncoder().encode({"vim_id": "vimid_1"}), '200'] + mock_call_req.side_effect = [t1_apply_grant_result, t2_lcm_notify_result, t3_delete_flavor] + mock_call.return_value = None + data = { + "terminationType": "FORCEFUL", + "gracefulTerminationTimeout": 120 + } + self.nf_inst_id = '1111' + self.job_id = JobUtil.create_job('NF', 'CREATE', self.nf_inst_id) + JobUtil.add_job_status(self.job_id, 0, "INST_VNF_READY") + TerminateVnf(data, nf_inst_id=self.nf_inst_id, job_id=self.job_id).run() + self.assert_job_result(self.job_id, 100, "Terminate Vnf success.") diff --git a/lcm/lcm/nf/tests/test_vnf_cancel.py b/lcm/lcm/nf/tests/test_vnf_cancel.py deleted file mode 100644 index ef0c7cf2..00000000 --- a/lcm/lcm/nf/tests/test_vnf_cancel.py +++ /dev/null @@ -1,175 +0,0 @@ -# Copyright 2017 ZTE Corporation. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - - -import json -import uuid - -import mock -from django.test import TestCase, Client -from rest_framework import status - -from lcm.nf.vnf_cancel.term_vnf import TermVnf -from lcm.pub.database.models import NfInstModel, JobStatusModel, VmInstModel, NetworkInstModel, SubNetworkInstModel, \ - PortInstModel, FlavourInstModel, StorageInstModel, NfvoRegInfoModel -from lcm.pub.utils import restcall -from lcm.pub.utils.jobutil import JobUtil -from lcm.pub.utils.timeutil import now_time -from lcm.pub.vimapi import api - - -class TestNFTerminate(TestCase): - def setUp(self): - self.client = Client() - StorageInstModel.objects.create(storageid="1", - vimid="1", - resouceid="11", - insttype=0, - instid="1111", - is_predefined=1) - NetworkInstModel.objects.create(networkid='1', - vimid='1', - resouceid='1', - name='pnet_network', - is_predefined=1, - tenant='admin', - insttype=0, - instid='1111') - SubNetworkInstModel.objects.create(subnetworkid='1', - vimid='1', - resouceid='1', - networkid='1', - is_predefined=1, - name='sub_pnet', - tenant='admin', - insttype=0, - instid='1111') - PortInstModel.objects.create(portid='1', - networkid='1', - subnetworkid='1', - vimid='1', - resouceid='1', - is_predefined=1, - name='aaa_pnet_cp', - tenant='admin', - insttype=0, - instid='1111') - FlavourInstModel.objects.create(flavourid="1", - vimid="1", - resouceid="11", - instid="1111", - is_predefined=1) - VmInstModel.objects.create(vmid="1", - vimid="1", - resouceid="11", - insttype=0, - instid="1111", - vmname="test_01", - is_predefined=1, - operationalstate=1) - NfvoRegInfoModel.objects.create(nfvoid='1111', - vnfminstid='11111', - apiurl='1') - - def tearDown(self): - VmInstModel.objects.all().delete() - NetworkInstModel.objects.all().delete() - SubNetworkInstModel.objects.all().delete() - PortInstModel.objects.all().delete() - - def assert_job_result(self, job_id, job_progress, job_detail): - jobs = JobStatusModel.objects.filter(jobid=job_id, - progress=job_progress, - descp=job_detail) - self.assertEqual(1, len(jobs)) - - def test_delete_vnf_identifier(self): - NfInstModel.objects.create(nfinstid='1111', - nf_name='2222', - package_id='todo', - version='', - vendor='', - netype='', - vnfd_model='', - status='NOT_INSTANTIATED', - nf_desc='', - vnfdid='', - vnfSoftwareVersion='', - vnfConfigurableProperties='todo', - localizationLanguage='EN_US', - create_time=now_time()) - response = self.client.delete("/api/vnflcm/v1/vnf_instances/1111") - self.failUnlessEqual(status.HTTP_204_NO_CONTENT, response.status_code) - self.assertEqual(None, response.data) - - def test_delete_vnf_identifier_when_vnf_not_exist(self): - response = self.client.delete("/api/vnflcm/v1/vnf_instances/1111") - self.failUnlessEqual(status.HTTP_204_NO_CONTENT, response.status_code) - - @mock.patch.object(TermVnf, 'run') - def test_terminate_vnf(self, mock_run): - req_data = { - "terminationType": "GRACEFUL", - "gracefulTerminationTimeout": 120 - } - mock_run.re.return_value = None - response = self.client.post("/api/vnflcm/v1/vnf_instances/12/terminate", data=req_data, format='json') - self.failUnlessEqual(status.HTTP_202_ACCEPTED, response.status_code) - - def test_terminate_vnf_when_inst_id_not_exist(self): - data = { - "terminationType": "GRACEFUL", - "gracefulTerminationTimeout": 120 - } - 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") - TermVnf(data, nf_inst_id=self.nf_inst_id, job_id=self.job_id).run() - self.assert_job_result(self.job_id, 100, "Terminate Vnf success.") - - @mock.patch.object(restcall, 'call_req') - @mock.patch.object(api, 'call') - def test_terminate_vnf_success(self, mock_call, mock_call_req): - NfInstModel.objects.create(nfinstid='1111', - nf_name='2222', - package_id='todo', - version='', - vendor='', - netype='', - vnfd_model='', - status='VNF_INSTANTIATED', - nf_desc='', - vnfdid='', - vnfSoftwareVersion='', - vnfConfigurableProperties='todo', - localizationLanguage='EN_US', - create_time=now_time()) - t1_apply_grant_result = [0, json.JSONEncoder().encode( - { - "vimid": 'vimid_1', - "tenant": 'tenantname_1' - }), '200'] - t2_lcm_notify_result = [0, json.JSONEncoder().encode(''), '200'] - t3_delete_flavor = [0, json.JSONEncoder().encode({"vim_id": "vimid_1"}), '200'] - mock_call_req.side_effect = [t1_apply_grant_result, t2_lcm_notify_result, t3_delete_flavor] - mock_call.return_value = None - data = { - "terminationType": "FORCEFUL", - "gracefulTerminationTimeout": 120 - } - self.nf_inst_id = '1111' - self.job_id = JobUtil.create_job('NF', 'CREATE', self.nf_inst_id) - JobUtil.add_job_status(self.job_id, 0, "INST_VNF_READY") - TermVnf(data, nf_inst_id=self.nf_inst_id, job_id=self.job_id).run() - self.assert_job_result(self.job_id, 100, "Terminate Vnf success.") diff --git a/lcm/lcm/nf/tests/test_vnf_create.py b/lcm/lcm/nf/tests/test_vnf_create.py deleted file mode 100644 index 5a017499..00000000 --- a/lcm/lcm/nf/tests/test_vnf_create.py +++ /dev/null @@ -1,201 +0,0 @@ -# Copyright 2017 ZTE Corporation. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -import json -import uuid - -import mock -from django.test import TestCase -from rest_framework import status -from rest_framework.test import APIClient - -from lcm.nf.const import c1_data_get_tenant_id, c4_data_create_network, c2_data_create_volume, \ - c5_data_create_subnet, c3_data_get_volume, c6_data_create_port, c7_data_create_flavor, c8_data_list_image, \ - c9_data_create_vm, c10_data_get_vm, inst_req_data, vnfpackage_info -from lcm.nf.vnf_create.inst_vnf import InstVnf -from lcm.pub.database.models import NfInstModel, JobStatusModel -from lcm.pub.utils import restcall -from lcm.pub.utils.jobutil import JobUtil -from lcm.pub.utils.timeutil import now_time -from lcm.pub.vimapi import api - - -class TestNFInstantiate(TestCase): - def setUp(self): - self.client = APIClient() - self.grant_result = { - "vimid": 'vimid_1', - "tenant": 'tenantname_1' - } - - def tearDown(self): - pass - - def assert_job_result(self, job_id, job_progress, job_detail): - jobs = JobStatusModel.objects.filter(jobid=job_id, - progress=job_progress, - descp=job_detail) - self.assertEqual(1, len(jobs)) - - def test_create_vnf_identifier_when_vnf_is_exist(self): - NfInstModel.objects.create(nfinstid='1111', - nf_name='vFW_01', - package_id='222', - version='', - vendor='', - netype='', - vnfd_model='', - status='NOT_INSTANTIATED', - nf_desc='vFW in Nanjing TIC Edge', - vnfdid='111', - create_time=now_time()) - data = { - "vnfdId": "111", - "vnfInstanceName": "vFW_01", - "vnfInstanceDescription": "vFW in Nanjing TIC Edge" - } - response = self.client.post("/api/vnflcm/v1/vnf_instances", data=data, format='json') - self.failUnlessEqual(status.HTTP_500_INTERNAL_SERVER_ERROR, response.status_code) - context = json.loads(response.content) - self.assertEqual({'error': 'VNF is already exist.'}, context) - - @mock.patch.object(restcall, 'call_req') - def test_create_vnf_identifier(self, mock_call_req): - r2_get_vnfpackage_from_catalog = [0, json.JSONEncoder().encode(vnfpackage_info), '200'] - mock_call_req.side_effect = [r2_get_vnfpackage_from_catalog] - data = { - "vnfdId": "111", - "vnfInstanceName": "vFW_01", - "vnfInstanceDescription": "vFW in Nanjing TIC Edge" - } - response = self.client.post("/api/vnflcm/v1/vnf_instances", data=data, format='json') - self.failUnlessEqual(status.HTTP_201_CREATED, response.status_code) - context = json.loads(response.content) - self.assertTrue(NfInstModel.objects.filter(nfinstid=context['vnfInstanceId']).exists()) - - @mock.patch.object(InstVnf, 'run') - def test_instantiate_vnf(self, mock_run): - mock_run.re.return_value = None - response = self.client.post("/api/vnflcm/v1/vnf_instances/12/instantiate", data=inst_req_data, format='json') - self.failUnlessEqual(status.HTTP_202_ACCEPTED, response.status_code) - - 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") - jobs = JobStatusModel.objects.filter(jobid=self.job_id, - progress=0, - descp="INST_VNF_READY") - self.assertEqual(1, len(jobs)) - 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, "VNF nf_inst_id is not exist.") - - @mock.patch.object(restcall, 'call_req') - def test_instantiate_vnf_when_get_packageinfo_by_csarid_failed(self, mock_call_req): - NfInstModel.objects.create(nfinstid='1111', - nf_name='vFW_01', - package_id='222', - version='', - vendor='', - netype='', - vnfd_model='', - status='NOT_INSTANTIATED', - nf_desc='vFW in Nanjing TIC Edge', - vnfdid='111', - create_time=now_time()) - r1_get_vnfpackage_by_vnfdid = [1, json.JSONEncoder().encode(vnfpackage_info), '200'] - mock_call_req.side_effect = [r1_get_vnfpackage_by_vnfdid] - self.nf_inst_id = '1111' - 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, "Failed to query vnf CSAR(111) from catalog.") - - @mock.patch.object(restcall, 'call_req') - def test_instantiate_vnf_when_applay_grant_failed(self, mock_call_req): - NfInstModel.objects.create(nfinstid='1111', - nf_name='vFW_01', - package_id='222', - version='', - vendor='', - netype='', - vnfd_model='', - status='NOT_INSTANTIATED', - nf_desc='vFW in Nanjing TIC Edge', - vnfdid='111', - create_time=now_time()) - r1_get_vnfpackage_by_vnfdid = [0, json.JSONEncoder().encode(vnfpackage_info), '200'] - r2_apply_grant_result = [1, json.JSONEncoder().encode(self.grant_result), '200'] - mock_call_req.side_effect = [r1_get_vnfpackage_by_vnfdid, r2_apply_grant_result] - self.nf_inst_id = '1111' - 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') - @mock.patch.object(api, 'call') - def test_instantiate_vnf_when_unexpected_exception(self, mock_call, mock_call_req): - NfInstModel.objects.create(nfinstid='1111', - nf_name='vFW_01', - package_id='222', - version='', - vendor='', - netype='', - vnfd_model='', - status='NOT_INSTANTIATED', - nf_desc='vFW in Nanjing TIC Edge', - vnfdid='111', - create_time=now_time()) - r1_get_vnfpackage_by_vnfdid = [0, json.JSONEncoder().encode(vnfpackage_info), '200'] - r2_apply_grant_result = [0, json.JSONEncoder().encode(self.grant_result), '200'] - mock_call_req.side_effect = [r1_get_vnfpackage_by_vnfdid, r2_apply_grant_result] - mock_call.side_effect = [c1_data_get_tenant_id, c2_data_create_volume, c3_data_get_volume] - self.nf_inst_id = '1111' - 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, "unexpected exception") - - @mock.patch.object(restcall, 'call_req') - @mock.patch.object(api, 'call') - def test_instantiate_vnf_success(self, mock_call, mock_call_req): - NfInstModel.objects.create(nfinstid='1111', - nf_name='vFW_01', - package_id='222', - version='', - vendor='', - netype='', - vnfd_model='', - status='NOT_INSTANTIATED', - nf_desc='vFW in Nanjing TIC Edge', - vnfdid='111', - create_time=now_time()) - r1_get_vnfpackage_by_vnfdid = [0, json.JSONEncoder().encode(vnfpackage_info), '200'] - r2_apply_grant_result = [0, json.JSONEncoder().encode(self.grant_result), '200'] - r3_lcm_notify_result = [0, json.JSONEncoder().encode(''), '200'] - mock_call_req.side_effect = [r1_get_vnfpackage_by_vnfdid, r2_apply_grant_result, r3_lcm_notify_result] - mock_call.side_effect = [c1_data_get_tenant_id, c2_data_create_volume, c3_data_get_volume, - c4_data_create_network, c5_data_create_subnet, c6_data_create_port, - c7_data_create_flavor, c8_data_list_image, c9_data_create_vm, c10_data_get_vm] - self.nf_inst_id = '1111' - 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, 100, "Instantiate Vnf success.") diff --git a/lcm/lcm/nf/tests/test_vnf_query.py b/lcm/lcm/nf/tests/test_vnf_query.py deleted file mode 100644 index 991583e7..00000000 --- a/lcm/lcm/nf/tests/test_vnf_query.py +++ /dev/null @@ -1,136 +0,0 @@ -# Copyright 2017 ZTE Corporation. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -from django.test import TestCase, Client -from rest_framework import status - -from lcm.pub.database.models import NfInstModel, StorageInstModel - - -class ResourceTest(TestCase): - def setUp(self): - self.client = Client() - self.nf_inst_id = "01" - NfInstModel.objects.all().delete() - self.test_data_single_vnf = { - "vnfInstanceId": "1", - "vnfInstanceName": "VNF1", - "vnfProvider": None, - "instantiatedVnfInfo": { - "vnfState": None, - "extCpInfo": [], - "virtualStorageResourceInfo": [ - { - "virtualStorageInstanceId": "s02", - "storageResource": { - "resourceId": "resource01", - "vimId": "vim01" - } - } - ], - "extVirtualLink": [], - "vnfcResourceInfo": [], - "monitoringParameters": {}, - "vimInfo": [], - "flavourId": None, - "virtualLinkResourceInfo": [], - "scaleStatus": [] - }, - "vnfdVersion": None, - "onboardedVnfPkgInfoId": None - } - self.test_data_multi_vnf = [ - { - "vnfInstanceId": "1", - "vnfInstanceName": "VNF1", - "vnfProvider": None, - "instantiatedVnfInfo": { - "vnfState": None, - "extCpInfo": [], - "virtualStorageResourceInfo": [ - { - "virtualStorageInstanceId": "s01", - "storageResource": { - "resourceId": "resource01", - "vimId": "vim01" - } - } - ], - "extVirtualLink": [], - "vnfcResourceInfo": [], - "monitoringParameters": {}, - "vimInfo": [], - "flavourId": None, - "virtualLinkResourceInfo": [], - "scaleStatus": [] - }, - "vnfdVersion": None, - "onboardedVnfPkgInfoId": None - }, - { - "vnfInstanceId": "2", - "vnfInstanceName": "VNF2", - "vnfProvider": None, - "instantiatedVnfInfo": { - "vnfState": None, - "extCpInfo": [], - "virtualStorageResourceInfo": [ - { - "virtualStorageInstanceId": "s02", - "storageResource": { - "resourceId": "resource02", - "vimId": "vim02" - } - } - ], - "extVirtualLink": [], - "vnfcResourceInfo": [], - "monitoringParameters": {}, - "vimInfo": [], - "flavourId": None, - "virtualLinkResourceInfo": [], - "scaleStatus": [] - }, - "vnfdVersion": None, - "onboardedVnfPkgInfoId": None - } - ] - - def tearDown(self): - pass - - def test_get_vnf(self): - vnf_inst_id = "1" - NfInstModel(nfinstid=vnf_inst_id, nf_name='VNF1').save() - StorageInstModel(storageid='s02', - vimid='vim01', - resouceid='resource01', - insttype=1, - instid=vnf_inst_id).save() - response = self.client.get("/api/vnflcm/v1/vnf_instances/%s" % vnf_inst_id, format='json') - self.assertEqual(response.status_code, status.HTTP_200_OK) - self.assertEqual(self.test_data_single_vnf, response.data) - - def test_get_vnfs(self): - for i in range(1, 3): - NfInstModel(nfinstid='%s' % i, - nf_name='VNF%s' % i).save() - StorageInstModel(storageid='s0%s' % i, - vimid='vim0%s' % i, - resouceid='resource0%s' % i, - insttype=1, - instid='%s' % i).save() - response = self.client.get("/api/vnflcm/v1/vnf_instances", format='json') - self.failUnlessEqual(status.HTTP_200_OK, response.status_code) - self.assertEqual(self.test_data_multi_vnf, response.data) diff --git a/lcm/lcm/nf/urls.py b/lcm/lcm/nf/urls.py index e59286a5..f279b551 100644 --- a/lcm/lcm/nf/urls.py +++ b/lcm/lcm/nf/urls.py @@ -14,11 +14,13 @@ from django.conf.urls import url -from lcm.nf.views import InstantiateVnf, TerminateVnf, DeleteVnfAndQueryVnf, CreateVnfAndQueryVnfs +from lcm.nf.views.curd_vnf_views import DeleteVnfAndQueryVnf, CreateVnfAndQueryVnfs +from lcm.nf.views.instantiate_vnf_view import InstantiateVnfView +from lcm.nf.views.terminate_vnf_view import TerminateVnfView urlpatterns = [ url(r'^api/vnflcm/v1/vnf_instances$', CreateVnfAndQueryVnfs.as_view()), - url(r'^api/vnflcm/v1/vnf_instances/(?P[0-9a-zA-Z_-]+)/instantiate$', InstantiateVnf.as_view()), + url(r'^api/vnflcm/v1/vnf_instances/(?P[0-9a-zA-Z_-]+)/instantiate$', InstantiateVnfView.as_view()), url(r'^api/vnflcm/v1/vnf_instances/(?P[0-9a-zA-Z_-]+)$', DeleteVnfAndQueryVnf.as_view()), - url(r'^api/vnflcm/v1/vnf_instances/(?P[0-9a-zA-Z_-]+)/terminate$', TerminateVnf.as_view()), + url(r'^api/vnflcm/v1/vnf_instances/(?P[0-9a-zA-Z_-]+)/terminate$', TerminateVnfView.as_view()), ] diff --git a/lcm/lcm/nf/views.py b/lcm/lcm/nf/views.py deleted file mode 100644 index 0db9d5fa..00000000 --- a/lcm/lcm/nf/views.py +++ /dev/null @@ -1,202 +0,0 @@ -# Copyright 2017 ZTE Corporation. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -import logging -import traceback - -from drf_yasg.utils import swagger_auto_schema -from rest_framework import status -from rest_framework.response import Response -from rest_framework.views import APIView - -from lcm.nf.serializers import CreateVnfReqSerializer, CreateVnfRespSerializer, VnfsInfoSerializer, \ - InstOrTeriVnfResponseSerializer, InstantiateVnfRequestSerializer, VnfInfoSerializer, TerminateVnfRequestSerializer -from lcm.nf.vnf_cancel.delete_vnf_identifier import DeleteVnf -from lcm.nf.vnf_cancel.term_vnf import TermVnf -from lcm.nf.vnf_create.create_vnf_identifier import CreateVnf -from lcm.nf.vnf_create.inst_vnf import InstVnf -from lcm.nf.vnf_query.query_vnf import QueryVnf -from lcm.pub.exceptions import NFLCMException -from lcm.pub.utils.jobutil import JobUtil - -logger = logging.getLogger(__name__) - - -class CreateVnfAndQueryVnfs(APIView): - @swagger_auto_schema( - responses={ - status.HTTP_200_OK: VnfsInfoSerializer(), - status.HTTP_500_INTERNAL_SERVER_ERROR: "Internal error" - } - ) - def get(self, request): - logger.debug("QueryMultiVnf--get::> %s" % request.data) - try: - resp_data = QueryVnf(request.data).query_multi_vnf() - - vnfs_info_serializer = VnfsInfoSerializer(data=resp_data) - if not vnfs_info_serializer.is_valid(): - raise NFLCMException(vnfs_info_serializer.errors) - - return Response(data=vnfs_info_serializer.data, status=status.HTTP_200_OK) - except NFLCMException as e: - logger.error(e.message) - return Response(data={'error': '%s' % e.message}, status=status.HTTP_500_INTERNAL_SERVER_ERROR) - except Exception as e: - logger.error(e.message) - logger.error(traceback.format_exc()) - return Response(data={'error': 'Failed to get Vnfs'}, status=status.HTTP_500_INTERNAL_SERVER_ERROR) - - @swagger_auto_schema( - request_body=CreateVnfReqSerializer(), - responses={ - status.HTTP_201_CREATED: CreateVnfRespSerializer(), - status.HTTP_500_INTERNAL_SERVER_ERROR: "Internal error" - } - ) - def post(self, request): - logger.debug("CreateVnfIdentifier--post::> %s" % request.data) - try: - req_serializer = CreateVnfReqSerializer(data=request.data) - if not req_serializer.is_valid(): - raise NFLCMException(req_serializer.errors) - - resp = CreateVnf(req_serializer.data).do_biz() - nf_inst_id = resp.get('id', 'undefined') - - create_vnf_resp_serializer = CreateVnfRespSerializer(data={"vnfInstanceId": nf_inst_id}) - if not create_vnf_resp_serializer.is_valid(): - raise NFLCMException(create_vnf_resp_serializer.errors) - return Response(data=create_vnf_resp_serializer.data, status=status.HTTP_201_CREATED) - except NFLCMException as e: - logger.error(e.message) - return Response(data={'error': '%s' % e.message}, status=status.HTTP_500_INTERNAL_SERVER_ERROR) - except Exception as e: - logger.error(e.message) - logger.error(traceback.format_exc()) - return Response(data={'error': 'unexpected exception'}, status=status.HTTP_500_INTERNAL_SERVER_ERROR) - - -class InstantiateVnf(APIView): - @swagger_auto_schema( - request_body=InstantiateVnfRequestSerializer(), - responses={ - status.HTTP_202_ACCEPTED: InstOrTeriVnfResponseSerializer(), - status.HTTP_500_INTERNAL_SERVER_ERROR: "Internal error" - } - ) - def post(self, request, instanceid): - logger.debug("InstantiateVnf--post::> %s" % request.data) - try: - instantiate_vnf_request_serializer = InstantiateVnfRequestSerializer(data=request.data) - if not instantiate_vnf_request_serializer.is_valid(): - raise NFLCMException(instantiate_vnf_request_serializer.errors) - - job_id = JobUtil.create_job('NF', 'INSTANTIATE', instanceid) - JobUtil.add_job_status(job_id, 0, "INST_VNF_READY") - InstVnf(instantiate_vnf_request_serializer.data, instanceid, job_id).start() - - instantiate_vnf_response_serializer = InstOrTeriVnfResponseSerializer(data={"jobId": job_id}) - resp_isvalid = instantiate_vnf_response_serializer.is_valid() - if not resp_isvalid: - raise NFLCMException(instantiate_vnf_response_serializer.errors) - - return Response(data=instantiate_vnf_response_serializer.data, status=status.HTTP_202_ACCEPTED) - except NFLCMException as e: - logger.error(e.message) - return Response(data={'error': '%s' % e.message}, status=status.HTTP_500_INTERNAL_SERVER_ERROR) - except Exception as e: - logger.error(e.message) - logger.error(traceback.format_exc()) - return Response(data={'error': 'unexpected exception'}, status=status.HTTP_500_INTERNAL_SERVER_ERROR) - - -class DeleteVnfAndQueryVnf(APIView): - @swagger_auto_schema( - responses={ - status.HTTP_200_OK: VnfInfoSerializer(), - status.HTTP_500_INTERNAL_SERVER_ERROR: "Internal error" - } - ) - def get(self, request, instanceid): - logger.debug("QuerySingleVnf--get::> %s" % request.data) - try: - resp_data = QueryVnf(request.data, instanceid).query_single_vnf() - - vnf_info_serializer = VnfInfoSerializer(data=resp_data) - if not vnf_info_serializer.is_valid(): - raise NFLCMException(vnf_info_serializer.errors) - - return Response(data=vnf_info_serializer.data, status=status.HTTP_200_OK) - except NFLCMException as e: - logger.error(e.message) - return Response(data={'error': '%s' % e.message}, status=status.HTTP_500_INTERNAL_SERVER_ERROR) - except Exception as e: - logger.eror(e.message) - logger.error(traceback.format_exc()) - return Response(data={'error': 'Failed to get Vnf(%s)' % instanceid}, - status=status.HTTP_500_INTERNAL_SERVER_ERROR) - - @swagger_auto_schema( - responses={ - status.HTTP_204_NO_CONTENT: "Successfully", - status.HTTP_500_INTERNAL_SERVER_ERROR: "Internal error" - } - ) - def delete(self, request, instanceid): - logger.debug("DeleteVnfIdentifier--delete::> %s" % request.data) - try: - DeleteVnf(request.data, instanceid).do_biz() - - return Response(data=None, status=status.HTTP_204_NO_CONTENT) - except NFLCMException as e: - logger.error(e.message) - return Response(data={'error': '%s' % e.message}, status=status.HTTP_500_INTERNAL_SERVER_ERROR) - except Exception as e: - logger.error(e.message) - logger.error(traceback.format_exc()) - return Response(data={'error': 'unexpected exception'}, status=status.HTTP_500_INTERNAL_SERVER_ERROR) - - -class TerminateVnf(APIView): - @swagger_auto_schema( - request_body=TerminateVnfRequestSerializer(), - responses={ - status.HTTP_202_ACCEPTED: InstOrTeriVnfResponseSerializer(), - status.HTTP_500_INTERNAL_SERVER_ERROR: "Internal error" - } - ) - def post(self, request, instanceid): - logger.debug("TerminateVnf--post::> %s" % request.data) - try: - terminate_vnf_request_serializer = TerminateVnfRequestSerializer(data=request.data) - if not terminate_vnf_request_serializer.is_valid(): - raise NFLCMException(terminate_vnf_request_serializer.errors) - - job_id = JobUtil.create_job('NF', 'TERMINATE', instanceid) - JobUtil.add_job_status(job_id, 0, "TERM_VNF_READY") - TermVnf(terminate_vnf_request_serializer.data, instanceid, job_id).start() - - terminate_vnf_response_serializer = InstOrTeriVnfResponseSerializer(data={"jobId": job_id}) - if not terminate_vnf_response_serializer.is_valid(): - raise NFLCMException(terminate_vnf_response_serializer.errors) - - return Response(data=terminate_vnf_response_serializer.data, status=status.HTTP_202_ACCEPTED) - except NFLCMException as e: - logger.error(e.message) - return Response(data={'error': '%s' % e.message}, status=status.HTTP_500_INTERNAL_SERVER_ERROR) - except Exception as e: - logger.error(e.message) - logger.error(traceback.format_exc()) - return Response(data={'error': 'unexpected exception'}, status=status.HTTP_500_INTERNAL_SERVER_ERROR) diff --git a/lcm/lcm/nf/views/__init__.py b/lcm/lcm/nf/views/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/lcm/lcm/nf/views/curd_vnf_views.py b/lcm/lcm/nf/views/curd_vnf_views.py new file mode 100644 index 00000000..16d082c6 --- /dev/null +++ b/lcm/lcm/nf/views/curd_vnf_views.py @@ -0,0 +1,132 @@ +# Copyright 2017 ZTE Corporation. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import logging +import traceback + +from drf_yasg.utils import swagger_auto_schema +from lcm.nf.biz.delete_vnf import DeleteVnf +from rest_framework import status +from rest_framework.response import Response +from rest_framework.views import APIView + +from lcm.nf.biz.create_vnf import CreateVnf +from lcm.nf.biz.query_vnf import QueryVnf +from lcm.nf.serializers.serializers import CreateVnfReqSerializer, CreateVnfRespSerializer, VnfsInfoSerializer, \ + VnfInfoSerializer +from lcm.pub.exceptions import NFLCMException + +logger = logging.getLogger(__name__) + + +class CreateVnfAndQueryVnfs(APIView): + @swagger_auto_schema( + responses={ + status.HTTP_200_OK: VnfsInfoSerializer(), + status.HTTP_500_INTERNAL_SERVER_ERROR: "Internal error" + } + ) + def get(self, request): + logger.debug("QueryMultiVnf--get::> %s" % request.data) + try: + resp_data = QueryVnf(request.data).query_multi_vnf() + + vnfs_info_serializer = VnfsInfoSerializer(data=resp_data) + if not vnfs_info_serializer.is_valid(): + raise NFLCMException(vnfs_info_serializer.errors) + + return Response(data=vnfs_info_serializer.data, status=status.HTTP_200_OK) + except NFLCMException as e: + logger.error(e.message) + return Response(data={'error': '%s' % e.message}, status=status.HTTP_500_INTERNAL_SERVER_ERROR) + except Exception as e: + logger.error(e.message) + logger.error(traceback.format_exc()) + return Response(data={'error': 'Failed to get Vnfs'}, status=status.HTTP_500_INTERNAL_SERVER_ERROR) + + @swagger_auto_schema( + request_body=CreateVnfReqSerializer(), + responses={ + status.HTTP_201_CREATED: CreateVnfRespSerializer(), + status.HTTP_500_INTERNAL_SERVER_ERROR: "Internal error" + } + ) + def post(self, request): + logger.debug("CreateVnfIdentifier--post::> %s" % request.data) + try: + req_serializer = CreateVnfReqSerializer(data=request.data) + if not req_serializer.is_valid(): + raise NFLCMException(req_serializer.errors) + + resp = CreateVnf(req_serializer.data).do_biz() + nf_inst_id = resp.get('id', 'undefined') + + create_vnf_resp_serializer = CreateVnfRespSerializer(data={"vnfInstanceId": nf_inst_id}) + if not create_vnf_resp_serializer.is_valid(): + raise NFLCMException(create_vnf_resp_serializer.errors) + return Response(data=create_vnf_resp_serializer.data, status=status.HTTP_201_CREATED) + except NFLCMException as e: + logger.error(e.message) + return Response(data={'error': '%s' % e.message}, status=status.HTTP_500_INTERNAL_SERVER_ERROR) + except Exception as e: + logger.error(e.message) + logger.error(traceback.format_exc()) + return Response(data={'error': 'unexpected exception'}, status=status.HTTP_500_INTERNAL_SERVER_ERROR) + + +class DeleteVnfAndQueryVnf(APIView): + @swagger_auto_schema( + responses={ + status.HTTP_200_OK: VnfInfoSerializer(), + status.HTTP_500_INTERNAL_SERVER_ERROR: "Internal error" + } + ) + def get(self, request, instanceid): + logger.debug("QuerySingleVnf--get::> %s" % request.data) + try: + resp_data = QueryVnf(request.data, instanceid).query_single_vnf() + + vnf_info_serializer = VnfInfoSerializer(data=resp_data) + if not vnf_info_serializer.is_valid(): + raise NFLCMException(vnf_info_serializer.errors) + + return Response(data=vnf_info_serializer.data, status=status.HTTP_200_OK) + except NFLCMException as e: + logger.error(e.message) + return Response(data={'error': '%s' % e.message}, status=status.HTTP_500_INTERNAL_SERVER_ERROR) + except Exception as e: + logger.eror(e.message) + logger.error(traceback.format_exc()) + return Response(data={'error': 'Failed to get Vnf(%s)' % instanceid}, + status=status.HTTP_500_INTERNAL_SERVER_ERROR) + + @swagger_auto_schema( + responses={ + status.HTTP_204_NO_CONTENT: "Successfully", + status.HTTP_500_INTERNAL_SERVER_ERROR: "Internal error" + } + ) + def delete(self, request, instanceid): + logger.debug("DeleteVnfIdentifier--delete::> %s" % request.data) + try: + DeleteVnf(request.data, instanceid).do_biz() + + return Response(data=None, status=status.HTTP_204_NO_CONTENT) + except NFLCMException as e: + logger.error(e.message) + return Response(data={'error': '%s' % e.message}, status=status.HTTP_500_INTERNAL_SERVER_ERROR) + except Exception as e: + logger.error(e.message) + logger.error(traceback.format_exc()) + return Response(data={'error': 'unexpected exception'}, status=status.HTTP_500_INTERNAL_SERVER_ERROR) diff --git a/lcm/lcm/nf/views/instantiate_vnf_view.py b/lcm/lcm/nf/views/instantiate_vnf_view.py new file mode 100644 index 00000000..3e9c334d --- /dev/null +++ b/lcm/lcm/nf/views/instantiate_vnf_view.py @@ -0,0 +1,62 @@ +# Copyright 2017 ZTE Corporation. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import logging +import traceback + +from drf_yasg.utils import swagger_auto_schema +from lcm.nf.biz.instantiate_vnf import InstantiateVnf +from rest_framework import status +from rest_framework.response import Response +from rest_framework.views import APIView + +from lcm.nf.serializers.serializers import InstOrTeriVnfResponseSerializer, InstantiateVnfRequestSerializer +from lcm.pub.exceptions import NFLCMException +from lcm.pub.utils.jobutil import JobUtil + +logger = logging.getLogger(__name__) + + +class InstantiateVnfView(APIView): + @swagger_auto_schema( + request_body=InstantiateVnfRequestSerializer(), + responses={ + status.HTTP_202_ACCEPTED: InstOrTeriVnfResponseSerializer(), + status.HTTP_500_INTERNAL_SERVER_ERROR: "Internal error" + } + ) + def post(self, request, instanceid): + logger.debug("InstantiateVnf--post::> %s" % request.data) + try: + instantiate_vnf_request_serializer = InstantiateVnfRequestSerializer(data=request.data) + if not instantiate_vnf_request_serializer.is_valid(): + raise NFLCMException(instantiate_vnf_request_serializer.errors) + + job_id = JobUtil.create_job('NF', 'INSTANTIATE', instanceid) + JobUtil.add_job_status(job_id, 0, "INST_VNF_READY") + InstantiateVnf(instantiate_vnf_request_serializer.data, instanceid, job_id).start() + + instantiate_vnf_response_serializer = InstOrTeriVnfResponseSerializer(data={"jobId": job_id}) + resp_isvalid = instantiate_vnf_response_serializer.is_valid() + if not resp_isvalid: + raise NFLCMException(instantiate_vnf_response_serializer.errors) + + return Response(data=instantiate_vnf_response_serializer.data, status=status.HTTP_202_ACCEPTED) + except NFLCMException as e: + logger.error(e.message) + return Response(data={'error': '%s' % e.message}, status=status.HTTP_500_INTERNAL_SERVER_ERROR) + except Exception as e: + logger.error(e.message) + logger.error(traceback.format_exc()) + return Response(data={'error': 'unexpected exception'}, status=status.HTTP_500_INTERNAL_SERVER_ERROR) diff --git a/lcm/lcm/nf/views/terminate_vnf_view.py b/lcm/lcm/nf/views/terminate_vnf_view.py new file mode 100644 index 00000000..8cd26467 --- /dev/null +++ b/lcm/lcm/nf/views/terminate_vnf_view.py @@ -0,0 +1,62 @@ +# Copyright 2017 ZTE Corporation. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import logging +import traceback + +from drf_yasg.utils import swagger_auto_schema +from rest_framework import status +from rest_framework.response import Response +from rest_framework.views import APIView + +from lcm.nf.biz.terminate_vnf import TerminateVnf +from lcm.nf.serializers.serializers import InstOrTeriVnfResponseSerializer, TerminateVnfRequestSerializer +from lcm.pub.exceptions import NFLCMException +from lcm.pub.utils.jobutil import JobUtil + + +logger = logging.getLogger(__name__) + + +class TerminateVnfView(APIView): + @swagger_auto_schema( + request_body=TerminateVnfRequestSerializer(), + responses={ + status.HTTP_202_ACCEPTED: InstOrTeriVnfResponseSerializer(), + status.HTTP_500_INTERNAL_SERVER_ERROR: "Internal error" + } + ) + def post(self, request, instanceid): + logger.debug("TerminateVnf--post::> %s" % request.data) + try: + terminate_vnf_request_serializer = TerminateVnfRequestSerializer(data=request.data) + if not terminate_vnf_request_serializer.is_valid(): + raise NFLCMException(terminate_vnf_request_serializer.errors) + + job_id = JobUtil.create_job('NF', 'TERMINATE', instanceid) + JobUtil.add_job_status(job_id, 0, "TERM_VNF_READY") + TerminateVnf(terminate_vnf_request_serializer.data, instanceid, job_id).start() + + terminate_vnf_response_serializer = InstOrTeriVnfResponseSerializer(data={"jobId": job_id}) + if not terminate_vnf_response_serializer.is_valid(): + raise NFLCMException(terminate_vnf_response_serializer.errors) + + return Response(data=terminate_vnf_response_serializer.data, status=status.HTTP_202_ACCEPTED) + except NFLCMException as e: + logger.error(e.message) + return Response(data={'error': '%s' % e.message}, status=status.HTTP_500_INTERNAL_SERVER_ERROR) + except Exception as e: + logger.error(e.message) + logger.error(traceback.format_exc()) + return Response(data={'error': 'unexpected exception'}, status=status.HTTP_500_INTERNAL_SERVER_ERROR) diff --git a/lcm/lcm/nf/vnf_cancel/__init__.py b/lcm/lcm/nf/vnf_cancel/__init__.py deleted file mode 100644 index c7b6818e..00000000 --- a/lcm/lcm/nf/vnf_cancel/__init__.py +++ /dev/null @@ -1,13 +0,0 @@ -# Copyright 2017 ZTE Corporation. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. diff --git a/lcm/lcm/nf/vnf_cancel/delete_vnf_identifier.py b/lcm/lcm/nf/vnf_cancel/delete_vnf_identifier.py deleted file mode 100644 index c0940303..00000000 --- a/lcm/lcm/nf/vnf_cancel/delete_vnf_identifier.py +++ /dev/null @@ -1,48 +0,0 @@ -# Copyright 2017 ZTE Corporation. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -import logging -import traceback - -from lcm.pub.database.models import NfInstModel, NfvoRegInfoModel -from lcm.pub.exceptions import NFLCMException - -logger = logging.getLogger(__name__) - - -class DeleteVnf: - def __init__(self, data, instanceid): - self.data = data - self.nf_inst_id = instanceid - - def do_biz(self): - try: - self.check_parameter() - self.delete_info_from_db() - logger.debug('VnfInst(%s) is deleted.' % self.nf_inst_id) - except NFLCMException as e: - logger.debug('Delete VNF instance[%s] failed: %s', self.nf_inst_id, e.message) - except Exception as e: - logger.error(e.message) - logger.error(traceback.format_exc()) - logger.debug('Delete VNF instance[%s] failed' % self.nf_inst_id) - - def check_parameter(self): - vnf_insts = NfInstModel.objects.filter(nfinstid=self.nf_inst_id) - if not vnf_insts.exists(): - logger.warn('VnfInst(%s) does not exist' % self.nf_inst_id) - - def delete_info_from_db(self): - NfInstModel.objects.filter(nfinstid=self.nf_inst_id).delete() - NfvoRegInfoModel.objects.filter(nfvoid=self.nf_inst_id).delete() diff --git a/lcm/lcm/nf/vnf_cancel/term_vnf.py b/lcm/lcm/nf/vnf_cancel/term_vnf.py deleted file mode 100644 index 1dd8067f..00000000 --- a/lcm/lcm/nf/vnf_cancel/term_vnf.py +++ /dev/null @@ -1,208 +0,0 @@ -# Copyright 2017 ZTE Corporation. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -import json -import logging -import traceback -from threading import Thread - -from lcm.nf.const import VNF_STATUS, RESOURCE_MAP -from lcm.pub.database.models import NfInstModel, VmInstModel, NetworkInstModel, StorageInstModel, \ - PortInstModel, VNFCInstModel, NfvoRegInfoModel, FlavourInstModel, SubNetworkInstModel -from lcm.pub.exceptions import NFLCMException -from lcm.pub.msapi.gvnfmdriver import apply_grant_to_nfvo, notify_lcm_to_nfvo -from lcm.pub.utils.jobutil import JobUtil -from lcm.pub.utils.timeutil import now_time -from lcm.pub.utils.values import ignore_case_get -from lcm.pub.vimapi import adaptor - -logger = logging.getLogger(__name__) - - -class TermVnf(Thread): - def __init__(self, data, nf_inst_id, job_id): - super(TermVnf, self).__init__() - self.data = data - self.nf_inst_id = nf_inst_id - self.job_id = job_id - self.terminationType = ignore_case_get(self.data, "terminationType") - self.gracefulTerminationTimeout = ignore_case_get(self.data, "gracefulTerminationTimeout") - self.inst_resource = {'volumn': [], 'network': [], 'subnet': [], 'port': [], 'flavor': [], 'vm': []} - - def run(self): - try: - if self.term_pre(): - self.grant_resource() - self.query_inst_resource() - self.query_notify_data() - self.delete_resource() - self.lcm_notify() - JobUtil.add_job_status(self.job_id, 100, "Terminate Vnf success.") - except NFLCMException as e: - self.vnf_term_failed_handle(e.message) - except Exception as e: - logger.error(e.message) - self.vnf_term_failed_handle(traceback.format_exc()) - - def term_pre(self): - vnf_insts = NfInstModel.objects.filter(nfinstid=self.nf_inst_id) - if not vnf_insts.exists(): - logger.warn('VnfInst(%s) does not exist' % self.nf_inst_id) - return False - if self.terminationType == 'GRACEFUL' and not self.gracefulTerminationTimeout: - logger.warn("Set Graceful default termination timeout = 60") - self.gracefulTerminationTimeout = 60 - NfInstModel.objects.filter(nfinstid=self.nf_inst_id).update(status=VNF_STATUS.TERMINATING) - JobUtil.add_job_status(self.job_id, 10, 'Nf terminating pre-check finish') - logger.info("Nf terminating pre-check finish") - return True - - def grant_resource(self): - logger.info("Grant resource begin") - content_args = { - 'vnfInstanceId': self.nf_inst_id, - 'vnfDescriptorId': '', - 'lifecycleOperation': 'Terminate', - 'jobId': self.job_id, - 'addResource': [], - 'removeResource': [], - 'placementConstraint': [], - 'additionalParam': {} - } - - vdus = VmInstModel.objects.filter(instid=self.nf_inst_id, is_predefined=1) - res_index = 1 - for vdu in vdus: - res_def = { - 'type': 'VDU', - 'resDefId': str(res_index), - 'resDesId': vdu.resouceid} - content_args['removeResource'].append(res_def) - res_index += 1 - - vnfmInfo = NfvoRegInfoModel.objects.filter(nfvoid=self.nf_inst_id) - if len(vnfmInfo) == 0: - raise NFLCMException('VnfId(%s) does not exist' % self.nf_inst_id) - content_args['additionalParam']['vnfmid'] = vnfmInfo[0].vnfminstid - content_args['additionalParam']['vimid'] = vnfmInfo[0].apiurl - logger.info('Grant request data=%s' % content_args) - self.apply_result = apply_grant_to_nfvo(json.dumps(content_args)) - logger.info("Grant resource end, response: %s" % self.apply_result) - JobUtil.add_job_status(self.job_id, 20, 'Nf terminating grant_resource finish') - - def query_inst_resource(self): - logger.info('Query resource begin') - for resource_type in RESOURCE_MAP.keys(): - resource_table = globals().get(resource_type + 'InstModel') - resource_insts = resource_table.objects.filter(instid=self.nf_inst_id) - for resource_inst in resource_insts: - if not resource_inst.resouceid: - continue - self.inst_resource[RESOURCE_MAP.get(resource_type)].append(self.get_resource(resource_inst)) - logger.info('Query resource end, resource=%s' % self.inst_resource) - - def get_resource(self, resource): - return { - "vim_id": resource.vimid, - "tenant_id": resource.tenant, - "res_id": resource.resouceid, - "is_predefined": resource.is_predefined - } - - def query_notify_data(self): - logger.info('Send notify request to nfvo') - affected_vnfc = [] - vnfcs = VNFCInstModel.objects.filter(instid=self.nf_inst_id) - for vnfc in vnfcs: - vm_resource = {} - if vnfc.vmid: - vm = VmInstModel.objects.filter(vmid=vnfc.vmid) - if vm: - vm_resource = {'vimId': vm[0].vimid, 'resourceId': vm[0].resouceid, - 'resourceName': vm[0].vmname, 'resourceType': 'vm'} - affected_vnfc.append( - {'vnfcInstanceId': vnfc.vnfcinstanceid, - 'vduId': vnfc.vduid, - 'changeType': 'removed', - 'computeResource': vm_resource}) - affected_vl = [] - networks = NetworkInstModel.objects.filter(instid=self.nf_inst_id) - for network in networks: - network_resource = { - 'vimId': network.vimid, - 'resourceId': network.resouceid, - 'resourceName': network.name, - 'resourceType': 'network'} - affected_vl.append( - {'vlInstanceId': network.networkid, - 'vldid': network.nodeId, - 'changeType': 'removed', - 'networkResource': network_resource}) - affected_cp = [] - ports = PortInstModel.objects.filter(instid=self.nf_inst_id) - for port in ports: - affected_cp.append( - {'vsInstanceId': port.portid, - 'cpdid': port.nodeId, - 'changeType': 'removed', - 'storageResource': {'vimId': port.vimid, 'resourceId': port.resouceid, - 'resourceName': port.name, 'resourceType': 'port'}}) - affected_vs = [] - vss = StorageInstModel.objects.filter(instid=self.nf_inst_id) - for vs in vss: - affected_vs.append( - {'vsInstanceId': vs.storageid, - 'vsdId': vs.nodeId, - 'changeType': 'removed', - 'storageResource': {'vimId': vs.vimid, 'resourceId': vs.resouceid, - 'resourceName': vs.name, 'resourceType': 'volume'}}) - FlavourInstModel.objects.filter(instid=self.nf_inst_id) - SubNetworkInstModel.objects.filter(instid=self.nf_inst_id) - self.notify_data = { - "status": 'result', - "vnfInstanceId": self.nf_inst_id, - "operation": 'Terminal', - "jobId": self.job_id, - 'affectedVnfc': affected_vnfc, - 'affectedVirtualLink': affected_vl, - 'affectedVirtualStorage': affected_vs, - 'affectedCp': affected_cp} - - vnfmInfo = NfvoRegInfoModel.objects.filter(nfvoid=self.nf_inst_id) - if len(vnfmInfo) == 0: - raise NFLCMException('VnfId(%s) does not exist' % self.nf_inst_id) - self.notify_data['VNFMID'] = vnfmInfo[0].vnfminstid - logger.info('Notify request data=%s' % self.notify_data) - - def delete_resource(self): - logger.info('Rollback resource begin') - adaptor.delete_vim_res(self.inst_resource, self.do_notify_delete) - logger.info('Rollback resource complete') - - def do_notify_delete(self, res_type, res_id): - logger.error('Deleting [%s] resource, resourceid [%s]' % (res_type, res_id)) - resource_type = RESOURCE_MAP.keys()[RESOURCE_MAP.values().index(res_type)] - resource_table = globals().get(resource_type + 'InstModel') - resource_table.objects.filter(instid=self.nf_inst_id, resouceid=res_id).delete() - - def lcm_notify(self): - NfInstModel.objects.filter(nfinstid=self.nf_inst_id).update(status='NOT_INSTANTIATED', lastuptime=now_time()) - logger.info('Send notify request to nfvo') - resp = notify_lcm_to_nfvo(json.dumps(self.notify_data)) - logger.info('Lcm notify end, response: %s' % resp) - - def vnf_term_failed_handle(self, error_msg): - logger.error('VNF termination 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) diff --git a/lcm/lcm/nf/vnf_create/__init__.py b/lcm/lcm/nf/vnf_create/__init__.py deleted file mode 100644 index c7b6818e..00000000 --- a/lcm/lcm/nf/vnf_create/__init__.py +++ /dev/null @@ -1,13 +0,0 @@ -# Copyright 2017 ZTE Corporation. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. diff --git a/lcm/lcm/nf/vnf_create/create_vnf_identifier.py b/lcm/lcm/nf/vnf_create/create_vnf_identifier.py deleted file mode 100644 index 34329a52..00000000 --- a/lcm/lcm/nf/vnf_create/create_vnf_identifier.py +++ /dev/null @@ -1,98 +0,0 @@ -# Copyright 2017 ZTE Corporation. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -import json -import logging -import traceback -import uuid - -from lcm.pub.database.models import NfInstModel -from lcm.pub.exceptions import NFLCMException -from lcm.pub.msapi.sdc_run_catalog import query_vnfpackage_by_id -from lcm.pub.utils.timeutil import now_time -from lcm.pub.utils.values import ignore_case_get - -logger = logging.getLogger(__name__) - - -class CreateVnf: - def __init__(self, data): - self.data = data - self.csar_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): - self.nf_inst_id = str(uuid.uuid4()) - try: - self.check_valid() - self.save_db() - except NFLCMException as e: - logger.debug('Create VNF instance[%s]: %s', self.nf_inst_id, e.message) - raise NFLCMException(e.message) - except Exception as e: - logger.error(e.message) - logger.error(traceback.format_exc()) - NfInstModel.objects.create(nfinstid=self.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.csar_id, - vnfSoftwareVersion='', - create_time=now_time()) - vnf_inst = NfInstModel.objects.get(nfinstid=self.nf_inst_id) - resp = { - 'id': vnf_inst.nfinstid, - 'vnfInstanceName': vnf_inst.nf_name, - 'vnfInstanceDescription': 'Human-readable description of the VNF instance.', - 'vnfdId': vnf_inst.vnfdid, - 'vnfProvider': vnf_inst.vendor, - 'vnfProductName': vnf_inst.nf_name, - 'vnfSoftwareVersion': vnf_inst.vnfSoftwareVersion, - 'vnfdVersion': vnf_inst.version, - 'vnfPkgId': vnf_inst.package_id, - 'vnfConfigurableProperties': {} - } - return resp - - 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 save_db(self): - metadata = ignore_case_get(self.vnfd_info, "metadata") - 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.create(nfinstid=self.nf_inst_id, - nf_name=self.vnf_instance_mame, - package_id=self.csar_id, - version=version, - vendor=vendor, - netype=netype, - vnfd_model=self.vnfd_info, - status='NOT_INSTANTIATED', - nf_desc=self.description, - vnfdid=self.csar_id, - vnfSoftwareVersion=vnfsoftwareversion, - create_time=now_time()) - logger.debug('Create VNF instance[%s] success', self.nf_inst_id) diff --git a/lcm/lcm/nf/vnf_create/inst_vnf.py b/lcm/lcm/nf/vnf_create/inst_vnf.py deleted file mode 100644 index b87602c9..00000000 --- a/lcm/lcm/nf/vnf_create/inst_vnf.py +++ /dev/null @@ -1,370 +0,0 @@ -# Copyright 2017 ZTE Corporation. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -import json -import logging -import traceback -import uuid -from threading import Thread - -from lcm.pub.database.models import NfInstModel, VmInstModel, NetworkInstModel, \ - SubNetworkInstModel, PortInstModel, StorageInstModel, FlavourInstModel, VNFCInstModel, NfvoRegInfoModel -from lcm.pub.exceptions import NFLCMException -from lcm.pub.msapi.gvnfmdriver import apply_grant_to_nfvo, notify_lcm_to_nfvo -from lcm.pub.msapi.sdc_run_catalog import query_vnfpackage_by_id -from lcm.pub.utils.jobutil import JobUtil -from lcm.pub.utils.timeutil import now_time -from lcm.pub.utils.values import ignore_case_get, get_none, get_boolean, get_integer -from lcm.pub.vimapi import adaptor - -logger = logging.getLogger(__name__) - - -class InstVnf(Thread): - def __init__(self, data, nf_inst_id, job_id): - super(InstVnf, self).__init__() - self.data = data - self.nf_inst_id = nf_inst_id - self.job_id = job_id - self.vim_id = ignore_case_get(ignore_case_get(self.data, "additionalParams"), "vimId") - - def run(self): - try: - self.inst_pre() - self.apply_grant() - self.create_res() - self.lcm_notify() - JobUtil.add_job_status(self.job_id, 100, "Instantiate Vnf success.") - except NFLCMException as e: - self.vnf_inst_failed_handle(e.message) - except Exception as e: - logger.error(e.message) - logger.error(traceback.format_exc()) - self.vnf_inst_failed_handle('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.') - - 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'], "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}) - vnf_package_info = query_vnfpackage_by_id(self.vnfd_id) - self.vnfd_info = json.loads(ignore_case_get(ignore_case_get(vnf_package_info, "packageInfo"), "vnfdModel")) - - 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=self.vnfd_info, - 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("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 apply_grant(self): - logger.info('Send resource grand request to nfvo') - content_args = { - 'vnfInstanceId': self.nf_inst_id, - 'vnfDescriptorId': '', - 'lifecycleOperation': 'Instantiate', - 'jobId': self.job_id, - 'addResource': [], - 'removeResource': [], - 'placementConstraint': [], - 'additionalParam': {} - } - - vdus = ignore_case_get(self.vnfd_info, "vdus") - res_index = 1 - for vdu in vdus: - res_def = { - 'type': 'VDU', - 'resDefId': str(res_index), - 'resDesId': ignore_case_get(vdu, "vdu_id") - } - content_args['addResource'].append(res_def) - res_index += 1 - - logger.debug("VnfInst = %s", self.nf_inst_id) - vnfmInfo = NfvoRegInfoModel.objects.filter(nfvoid=self.nf_inst_id) - if len(vnfmInfo) == 0: - raise NFLCMException('VnfInst(%s) does not exist' % self.nf_inst_id) - content_args['additionalParam']['vnfmid'] = vnfmInfo[0].vnfminstid - content_args['additionalParam']['vimid'] = vnfmInfo[0].apiurl - logger.info('Grant request data = %s', content_args) - - apply_result = apply_grant_to_nfvo(json.dumps(content_args)) - self.set_location(apply_result) - - logger.info('VnfdInfo = %s' % self.vnfd_info) - NfInstModel.objects.filter(nfinstid=self.nf_inst_id).update(status='INSTANTIATED', lastuptime=now_time()) - JobUtil.add_job_status(self.job_id, 20, 'Nf instancing apply grant finish') - logger.info("Nf instancing apply grant finish") - - def create_res(self): - logger.info("Create resource start") - adaptor.create_vim_res(self.vnfd_info, self.do_notify) - JobUtil.add_job_status(self.job_id, 70, '[NF instantiation] create resource finish') - logger.info("Create resource finish") - - def lcm_notify(self): - logger.info('Send notify request to nfvo') - affected_vnfc = [] - vnfcs = VNFCInstModel.objects.filter(instid=self.nf_inst_id) - for vnfc in vnfcs: - vm_resource = {} - if vnfc.vmid: - vm = VmInstModel.objects.filter(vmid=vnfc.vmid) - if vm: - vm_resource = {'vimId': vm[0].vimid, 'resourceId': vm[0].resouceid, - 'resourceName': vm[0].vmname, 'resourceType': 'vm'} - affected_vnfc.append( - {'vnfcInstanceId': vnfc.vnfcinstanceid, - 'vduId': vnfc.vduid, - 'changeType': 'added', - 'computeResource': vm_resource}) - affected_vl = [] - networks = NetworkInstModel.objects.filter(instid=self.nf_inst_id) - for network in networks: - network_resource = {'vimId': network.vimid, 'resourceId': network.resouceid, - 'resourceName': network.name, 'resourceType': 'network'} - affected_vl.append( - {'vlInstanceId': network.networkid, - 'vldid': network.nodeId, - 'changeType': 'added', - 'networkResource': network_resource}) - affected_cp = [] - ports = PortInstModel.objects.filter(instid=self.nf_inst_id) - for port in ports: - affected_cp.append( - {'vsInstanceId': port.portid, - 'cpdid': port.nodeId, - 'changeType': 'added', - 'portResource': {'vimId': port.vimid, 'resourceId': port.resouceid, - 'resourceName': port.name, 'resourceType': 'port'}}) - affected_vs = [] - vss = StorageInstModel.objects.filter(instid=self.nf_inst_id) - for vs in vss: - affected_vs.append( - {'vsInstanceId': vs.storageid, - 'vsdId': vs.nodeId, - 'changeType': 'added', - 'storageResource': {'vimId': vs.vimid, 'resourceId': vs.resouceid, - 'resourceName': vs.name, 'resourceType': 'volume'}}) - content_args = { - "status": 'result', - "vnfInstanceId": self.nf_inst_id, - "operation": 'instantiate', - "jobId": self.job_id, - 'affectedVnfc': affected_vnfc, - 'affectedVirtualLink': affected_vl, - 'affectedVirtualStorage': affected_vs, - 'affectedCp': affected_cp - } - - vnfmInfo = NfvoRegInfoModel.objects.filter(nfvoid=self.nf_inst_id) - if len(vnfmInfo) == 0: - raise NFLCMException('nf_inst_id(%s) does not exist in NfvoRegInfoModel' % self.nf_inst_id) - content_args['VNFMID'] = vnfmInfo[0].vnfminstid - logger.info('Notify request data = %s' % content_args) - resp = notify_lcm_to_nfvo(json.dumps(content_args)) - logger.info('Lcm notify end, response %s' % resp) - - 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) - - def do_notify(self, res_type, ret): - logger.info('Creating [%s] resource' % res_type) - resource_save_method = globals().get(res_type + '_save') - resource_save_method(self.job_id, self.nf_inst_id, ret) - - def update_cps(self): - for extlink in ignore_case_get(self.data, "extVirtualLinks"): - for cp in ignore_case_get(self.vnfd_info, "cps"): - cpdid = ignore_case_get(extlink, "cpdId") - if cpdid == ignore_case_get(cp, "cp_id"): - cp["networkId"] = ignore_case_get(extlink, "resourceId") - cp["subnetId"] = ignore_case_get(extlink, "resourceSubnetId") - break - - def set_location(self, apply_result): - for resource_type in ['vdus', 'vls']: - for resource in ignore_case_get(self.vnfd_info, resource_type): - if "location_info" in resource["properties"]: - resource["properties"]["location_info"]["vimid"] = ignore_case_get(apply_result, "vimid") - resource["properties"]["location_info"]["tenant"] = ignore_case_get(apply_result, "tenant") - else: - resource["properties"]["location_info"] = { - "vimid": ignore_case_get(apply_result, "vimid"), - "tenant": ignore_case_get(apply_result, "tenant")} - - -def volume_save(job_id, nf_inst_id, ret): - JobUtil.add_job_status(job_id, 25, 'Create vloumns!') - StorageInstModel.objects.create( - storageid=str(uuid.uuid4()), - vimid=ignore_case_get(ret, "vimId"), - resouceid=ignore_case_get(ret, "id"), - name=ignore_case_get(ret, "name"), - tenant=ignore_case_get(ret, "tenantId"), - create_time=ignore_case_get(ret, "createTime"), - storagetype=get_none(ignore_case_get(ret, "type")), - size=ignore_case_get(ret, "size"), - insttype=0, - is_predefined=ignore_case_get(ret, "returnCode"), - nodeId=ignore_case_get(ret, "nodeId"), - instid=nf_inst_id) - - -def network_save(job_id, nf_inst_id, ret): - JobUtil.add_job_status(job_id, 35, 'Create networks!') - NetworkInstModel.objects.create( - networkid=str(uuid.uuid4()), - name=ignore_case_get(ret, "name"), - vimid=ignore_case_get(ret, "vimId"), - resouceid=ignore_case_get(ret, "id"), - tenant=ignore_case_get(ret, "tenantId"), - segmentid=str(ignore_case_get(ret, "segmentationId")), - network_type=ignore_case_get(ret, "networkType"), - physicalNetwork=ignore_case_get(ret, "physicalNetwork"), - vlantrans=get_boolean(ignore_case_get(ret, "vlanTransparent")), - is_shared=get_boolean(ignore_case_get(ret, "shared")), - routerExternal=get_boolean(ignore_case_get(ret, "routerExternal")), - insttype=0, - is_predefined=ignore_case_get(ret, "returnCode"), - nodeId=ignore_case_get(ret, "nodeId"), - instid=nf_inst_id) - - -def subnet_save(job_id, nf_inst_id, ret): - JobUtil.add_job_status(job_id, 40, 'Create subnets!') - SubNetworkInstModel.objects.create( - subnetworkid=str(uuid.uuid4()), - name=ignore_case_get(ret, "name"), - vimid=ignore_case_get(ret, "vimId"), - resouceid=ignore_case_get(ret, "id"), - tenant=ignore_case_get(ret, "tenantId"), - networkid=ignore_case_get(ret, "networkId"), - cidr=ignore_case_get(ret, "cidr"), - ipversion=ignore_case_get(ret, "ipversion"), - isdhcpenabled=ignore_case_get(ret, "enableDhcp"), - gatewayip=ignore_case_get(ret, "gatewayIp"), - dnsNameservers=ignore_case_get(ret, "dnsNameservers"), - hostRoutes=ignore_case_get(ret, "hostRoutes"), - allocationPools=ignore_case_get(ret, "allocationPools"), - insttype=0, - is_predefined=ignore_case_get(ret, "returnCode"), - instid=nf_inst_id) - - -def port_save(job_id, nf_inst_id, ret): - JobUtil.add_job_status(job_id, 50, 'Create ports!') - PortInstModel.objects.create( - portid=str(uuid.uuid4()), - networkid=ignore_case_get(ret, "networkId"), - subnetworkid=ignore_case_get(ret, "subnetId"), - name=ignore_case_get(ret, "name"), - vimid=ignore_case_get(ret, "vimId"), - resouceid=ignore_case_get(ret, "id"), - tenant=ignore_case_get(ret, "tenantId"), - macaddress=ignore_case_get(ret, "macAddress"), - ipaddress=ignore_case_get(ret, "ip"), - typevirtualnic=ignore_case_get(ret, "vnicType"), - securityGroups=ignore_case_get(ret, "securityGroups"), - insttype=0, - is_predefined=ignore_case_get(ret, "returnCode"), - nodeId=ignore_case_get(ret, "nodeId"), - instid=nf_inst_id) - - -def flavor_save(job_id, nf_inst_id, ret): - JobUtil.add_job_status(job_id, 60, 'Create flavors!') - FlavourInstModel.objects.create( - flavourid=str(uuid.uuid4()), - name=ignore_case_get(ret, "name"), - vimid=ignore_case_get(ret, "vimId"), - resouceid=ignore_case_get(ret, "id"), - tenant=ignore_case_get(ret, "tenantId"), - vcpu=get_integer(ignore_case_get(ret, "vcpu")), - memory=get_integer(ignore_case_get(ret, "memory")), - disk=get_integer(ignore_case_get(ret, "disk")), - ephemeral=get_integer(ignore_case_get(ret, "ephemeral")), - swap=get_integer(ignore_case_get(ret, "swap")), - isPublic=get_boolean(ignore_case_get(ret, "isPublic")), - extraspecs=ignore_case_get(ret, "extraSpecs"), - is_predefined=ret.get("returnCode", int(0)), - instid=nf_inst_id) - - -def vm_save(job_id, nf_inst_id, ret): - JobUtil.add_job_status(job_id, 70, 'Create vms!') - vm_id = str(uuid.uuid4()) - VmInstModel.objects.create( - vmid=vm_id, - vmname=ignore_case_get(ret, "name"), - vimid=ignore_case_get(ret, "vimId"), - resouceid=ignore_case_get(ret, "id"), - tenant=ignore_case_get(ret, "tenantId"), - nic_array=ignore_case_get(ret, "nicArray"), - metadata=ignore_case_get(ret, "metadata"), - volume_array=ignore_case_get(ret, "volumeArray"), - server_group=ignore_case_get(ret, "serverGroup"), - availability_zone=str(ignore_case_get(ret, "availabilityZone", "undefined")), - flavor_id=ignore_case_get(ret, "flavorId"), - security_groups=ignore_case_get(ret, "securityGroups"), - operationalstate=ignore_case_get(ret, "status"), - insttype=0, - is_predefined=ignore_case_get(ret, "returnCode"), - instid=nf_inst_id) - VNFCInstModel.objects.create( - vnfcinstanceid=str(uuid.uuid4()), - vduid=ignore_case_get(ret, "id"), - is_predefined=ignore_case_get(ret, "returnCode"), - instid=nf_inst_id, - vmid=vm_id) diff --git a/lcm/lcm/nf/vnf_query/__init__.py b/lcm/lcm/nf/vnf_query/__init__.py deleted file mode 100644 index c7b6818e..00000000 --- a/lcm/lcm/nf/vnf_query/__init__.py +++ /dev/null @@ -1,13 +0,0 @@ -# Copyright 2017 ZTE Corporation. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. diff --git a/lcm/lcm/nf/vnf_query/query_vnf.py b/lcm/lcm/nf/vnf_query/query_vnf.py deleted file mode 100644 index 1a6bdd90..00000000 --- a/lcm/lcm/nf/vnf_query/query_vnf.py +++ /dev/null @@ -1,139 +0,0 @@ -# Copyright 2017 ZTE Corporation. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -import logging - -from lcm.pub.database.models import NfInstModel, StorageInstModel, VLInstModel, NetworkInstModel, VNFCInstModel, \ - VmInstModel -from lcm.pub.exceptions import NFLCMException - -logger = logging.getLogger(__name__) - - -class QueryVnf: - def __init__(self, data, instanceid=''): - self.vnf_inst_id = instanceid - self.data = data - - 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 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 fill_resp_data(self, vnf): - logger.info('Get storages') - storage_inst = StorageInstModel.objects.filter(instid=vnf.nfinstid) - arr = [] - for s in storage_inst: - storage = { - "virtualStorageInstanceId": s.storageid, - "storageResource": { - "vimId": s.vimid, - "resourceId": s.resouceid - } - } - arr.append(storage) - logger.info('Get networks') - vl_inst = VLInstModel.objects.filter(ownerid=vnf.nfinstid) - vl_arr = [] - for v in vl_inst: - net = NetworkInstModel.objects.filter(networkid=v.relatednetworkid) - if not net: - raise NFLCMException('NetworkInst(%s) does not exist.' % v.relatednetworkid) - v_dic = { - "virtualLinkInstanceId": v.vlinstanceid, - "virtualLinkDescId": v.vldid, - "networkResource": { - "vimId": net[0].vimid, - "resourceId": net[0].resouceid - } - } - vl_arr.append(v_dic) - logger.info('Get vnfcs') - vnfc_insts = VNFCInstModel.objects.filter(instid=vnf.nfinstid) - vnfc_arr = [] - for vnfc in vnfc_insts: - vm = VmInstModel.objects.filter(vmid=vnfc.vmid) - if not vm: - raise NFLCMException('VmInst(%s) does not exist.' % vnfc.vmid) - storage = StorageInstModel.objects.filter(ownerid=vm[0].vmid) - if not storage: - raise NFLCMException('StorageInst(%s) does not exist.' % vm[0].vmid) - vnfc_dic = { - "vnfcInstanceId": vnfc.vnfcinstanceid, - "vduId": vnfc.vduid, - "computeResource": { - "vimId": vm[0].vimid, - "resourceId": vm[0].resouceid - }, - "storageResourceIds": [s.storageid for s in storage] - } - vnfc_arr.append(vnfc_dic) - logger.info('Get vms') - vms = VmInstModel.objects.filter(instid=vnf.nfinstid) - vm_arr = [] - for vm in vms: - vm_dic = { - "vmid": vm.vmid, - "vimid": vm.vimid, - "tenant": vm.tenant, - "resouceid": vm.resouceid, - "vmname": vm.vmname, - "nic_array": vm.nic_array, - "metadata": vm.metadata, - "volume_array": vm.volume_array, - "server_group": vm.server_group, - "availability_zone": vm.availability_zone, - "flavor_id": vm.flavor_id, - "security_groups": vm.security_groups, - "operationalstate": vm.operationalstate, - "insttype": vm.insttype, - "is_predefined": vm.is_predefined, - "create_time": vm.create_time, - "instid": vm.instid, - "nodeId": vm.nodeId - } - vm_arr.append(vm_dic) - - resp_data = { - "vnfInstanceId": vnf.nfinstid, - "vnfInstanceName": vnf.nf_name, - "onboardedVnfPkgInfoId": vnf.package_id, - "vnfdVersion": vnf.version, - "vnfProvider": vnf.vendor, - "instantiatedVnfInfo": { - "flavourId": vnf.flavour_id, - "vnfState": vnf.status, - "scaleStatus": [], - "extCpInfo": [], - "extVirtualLink": [], - "monitoringParameters": {}, - "vimInfo": vm_arr, - "vnfcResourceInfo": vnfc_arr, - "virtualLinkResourceInfo": vl_arr, - "virtualStorageResourceInfo": arr - } - } - return resp_data diff --git a/lcm/lcm/urls.py b/lcm/lcm/urls.py index 6226e522..ea213ad6 100644 --- a/lcm/lcm/urls.py +++ b/lcm/lcm/urls.py @@ -18,7 +18,7 @@ from lcm.pub.config.config import REG_TO_MSB_WHEN_START, REG_TO_MSB_REG_URL, REG urlpatterns = [ url(r'^', include('lcm.samples.urls')), url(r'^', include('lcm.nf.urls')), - url(r'^', include('lcm.v2.urls')), + # url(r'^', include('lcm.v2.urls')), url(r'^', include('lcm.jobs.urls')), url(r'^', include('lcm.swagger.urls')), ] diff --git a/lcm/lcm/v2/__init__.py b/lcm/lcm/v2/__init__.py deleted file mode 100644 index 342c2a8c..00000000 --- a/lcm/lcm/v2/__init__.py +++ /dev/null @@ -1,13 +0,0 @@ -# Copyright 2018 ZTE Corporation. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. diff --git a/lcm/lcm/v2/serializers.py b/lcm/lcm/v2/serializers.py deleted file mode 100644 index 3aaad319..00000000 --- a/lcm/lcm/v2/serializers.py +++ /dev/null @@ -1,177 +0,0 @@ -# Copyright 2018 ZTE Corporation. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -from rest_framework import serializers - - -class VimInfoSerializer(serializers.Serializer): - id = serializers.CharField( - help_text="The identifier of the VIM Connection. This identifier is managed by the NFVO.", - required=False, - max_length=255, - allow_null=True) - vimId = serializers.CharField( - help_text="The identifier of the VIM instance. This identifier is managed by the NFVO.", - required=False, - max_length=255, - allow_null=True) - vimType = serializers.CharField( - help_text="Discriminator for the different types of the VIM information.", - required=False, - max_length=255, - allow_null=True) - interfaceInfo = serializers.DictField( - help_text="Information about the interface or interfaces to the VIM", - child=serializers.CharField(allow_blank=True), - required=False, - allow_null=True) - accessInfo = serializers.DictField( - help_text="Authentication credentials for accessing the VIM, and other access-related information", - child=serializers.CharField(allow_blank=True), - required=False, - allow_null=True) - extra = serializers.DictField( - help_text="VIM type specific additional information.", - child=serializers.CharField(allow_blank=True), - required=False, - allow_null=True) - - -class ScaleInfoSerializer(serializers.Serializer): - aspectId = serializers.CharField( - help_text="Identifier of the scaling aspect.", - required=True, - max_length=255, - allow_null=True) - scaleLevel = serializers.IntegerField( - help_text="Indicates the scale level.", - required=True) - - -class CpProtocolInfoSerializer(serializers.Serializer): - layerProtocol = serializers.ChoiceField( - help_text="The identifier of layer(s) and protocol(s) associated to the network address information.", - choices=["IP_OVER_ETHERNET"], - required=False, - allow_null=True) - ipOverEthernet = serializers.DictField( - help_text="IP addresses over Ethernet to assign to the extCP instance.", - child=serializers.CharField(allow_blank=True), - required=False, - allow_null=True) - - -class ExtCpInfoSerializer(serializers.Serializer): - id = serializers.CharField( - help_text="Identifier of the external CP instance and the related information instance.", - required=False, - max_length=255, - allow_null=True) - cpdId = serializers.CharField( - help_text="Identifier of the external CPD, VnfExtCpd, in the VNFD.", - required=True, - max_length=255, - allow_null=True) - cpProtocolInfo = CpProtocolInfoSerializer( - help_text="Network protocol information for this CP.", - required=False, - allow_null=True) - extLinkPortId = serializers.CharField( - help_text="Identifier of the 'extLinkPortInfo' structure inside the 'extVirtualLinkInfo' structure.", - required=False, - max_length=255, - allow_null=True) - - -class instantiatedVnfInfoSerializer(serializers.Serializer): - flavourId = serializers.CharField( - help_text="Identifier of the VNF deployment flavour applied to this VNF instance.", - required=True, - max_length=255, - allow_null=True) - vnfState = serializers.ChoiceField( - help_text="State of the VNF instance.", - choices=["STARTED", "STOPPED"], - required=True, - allow_null=True) - scaleStatus = ScaleInfoSerializer( - help_text="Scale status of the VNF, one entry per aspect.", - required=False, - many=True) - extCpInfo = ExtCpInfoSerializer( - help_text="Information about the external CPs exposed by the VNF instance.", - required=False, - many=True) - - -class VnfInstanceSerializer(serializers.Serializer): - id = serializers.CharField( - help_text="Identifier of the VNF instance", - required=True) - vnfInstanceName = serializers.CharField( - help_text="Name of the VNF instance.", - required=False, - allow_null=True, - allow_blank=True) - vnfInstanceDescription = serializers.CharField( - help_text="Human-readable description of the VNF instance.", - required=False, - allow_null=True, - allow_blank=True) - vnfdId = serializers.CharField( - help_text="Identifier of the VNFD on which the VNF instance is based.", - required=False, - allow_null=True, - allow_blank=True) - vnfProvider = serializers.CharField( - help_text="Provider of the VNF and the VNFD. The value is copied from the VNFD.", - required=False, - allow_null=True, - allow_blank=True) - vnfProductName = serializers.CharField( - help_text="Name to identify the VNF Product. The value is copied from the VNFD.", - required=False, - allow_null=True, - allow_blank=True) - vnfSoftwareVersion = serializers.CharField( - help_text="Software version of the VNF. The value is copied from the VNFD.", - required=False, - allow_null=True, - allow_blank=True) - vnfdVersion = serializers.CharField( - help_text="Identifies the version of the VNFD. The value is copied from the VNFD.", - required=False, - allow_null=True, - allow_blank=True) - vnfPkgId = serializers.CharField( - help_text="Identifier of information held by the NFVO about the specific VNF package on which the VNF is based.", - required=False, - allow_null=True, - allow_blank=True) - vnfConfigurableProperties = serializers.DictField( - help_text="Current values of the configurable properties of the VNF instance.", - child=serializers.CharField(allow_blank=True), - required=False, - allow_null=True) - vimConnectionInfo = VimInfoSerializer( - help_text="Information about VIM connections to be used for managing the resources for the VNF instance.", - required=False, - allow_null=True) - instantiationState = serializers.ChoiceField( - help_text="The instantiation state of the VNF.", - choices=["NOT_INSTANTIATED", "INSTANTIATED"], - required=False, - allow_null=True) - instantiatedVnfInfo = instantiatedVnfInfoSerializer( - help_text="Information specific to an instantiated VNF instance.", - required=False) diff --git a/lcm/lcm/v2/tests/__init__.py b/lcm/lcm/v2/tests/__init__.py deleted file mode 100644 index 342c2a8c..00000000 --- a/lcm/lcm/v2/tests/__init__.py +++ /dev/null @@ -1,13 +0,0 @@ -# Copyright 2018 ZTE Corporation. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. diff --git a/lcm/lcm/v2/tests/test_vnf_create.py b/lcm/lcm/v2/tests/test_vnf_create.py deleted file mode 100644 index 154b781a..00000000 --- a/lcm/lcm/v2/tests/test_vnf_create.py +++ /dev/null @@ -1,84 +0,0 @@ -# Copyright 2018 ZTE Corporation. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -import json - -import mock -from django.test import TestCase -from rest_framework import status -from rest_framework.test import APIClient - -from lcm.nf.const import vnfpackage_info -from lcm.pub.database.models import NfInstModel, JobStatusModel -from lcm.pub.utils import restcall -from lcm.pub.utils.timeutil import now_time - - -class TestNFInstantiate(TestCase): - def setUp(self): - self.client = APIClient() - self.grant_result = { - "vim": { - "vimid": 'vimid_1', - "accessinfo": { - "tenant": 'tenantname_1' - } - } - } - - def tearDown(self): - pass - - def assert_job_result(self, job_id, job_progress, job_detail): - jobs = JobStatusModel.objects.filter(jobid=job_id, - progress=job_progress, - descp=job_detail) - self.assertEqual(1, len(jobs)) - - def test_create_vnf_identifier_when_vnf_is_exist(self): - NfInstModel.objects.create(nfinstid='1111', - nf_name='vFW_01', - package_id='222', - version='', - vendor='', - netype='', - vnfd_model='', - status='NOT_INSTANTIATED', - nf_desc='vFW in Nanjing TIC Edge', - vnfdid='111', - create_time=now_time()) - data = { - "vnfdId": "111", - "vnfInstanceName": "vFW_01", - "vnfInstanceDescription": "vFW in Nanjing TIC Edge" - } - response = self.client.post("/api/vnflcm/v2/vnf_instances", data=data, format='json') - self.failUnlessEqual(status.HTTP_500_INTERNAL_SERVER_ERROR, response.status_code) - context = json.loads(response.content) - self.assertEqual({'error': 'VNF is already exist.'}, context) - - @mock.patch.object(restcall, 'call_req') - def test_create_vnf_identifier(self, mock_call_req): - r2_get_vnfpackage_from_catalog = [0, json.JSONEncoder().encode(vnfpackage_info), '200'] - mock_call_req.side_effect = [r2_get_vnfpackage_from_catalog] - data = { - "vnfdId": "111", - "vnfInstanceName": "vFW_01", - "vnfInstanceDescription": "vFW in Nanjing TIC Edge" - } - response = self.client.post("/api/vnflcm/v2/vnf_instances", data=data, format='json') - self.failUnlessEqual(status.HTTP_201_CREATED, response.status_code) - context = json.loads(response.content) - self.assertEqual(context['vnfInstanceName'], "vFW_01") - self.assertTrue(NfInstModel.objects.filter(nfinstid=context['id']).exists()) diff --git a/lcm/lcm/v2/urls.py b/lcm/lcm/v2/urls.py deleted file mode 100644 index ea23519d..00000000 --- a/lcm/lcm/v2/urls.py +++ /dev/null @@ -1,21 +0,0 @@ -# Copyright 2018 ZTE Corporation. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -from django.conf.urls import url - -from lcm.v2.views import CreateVnfAndQueryVnfs - -urlpatterns = [ - url(r'^api/vnflcm/v2/vnf_instances$', CreateVnfAndQueryVnfs.as_view()), -] diff --git a/lcm/lcm/v2/views.py b/lcm/lcm/v2/views.py deleted file mode 100644 index 4b569584..00000000 --- a/lcm/lcm/v2/views.py +++ /dev/null @@ -1,88 +0,0 @@ -# Copyright 2018 ZTE Corporation. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -import logging -import traceback - -from drf_yasg.utils import swagger_auto_schema -from rest_framework import status -from rest_framework.response import Response -from rest_framework.views import APIView - -from lcm.nf.serializers import CreateVnfReqSerializer -from lcm.nf.vnf_create.create_vnf_identifier import CreateVnf -from lcm.pub.exceptions import NFLCMException -from lcm.v2.serializers import VnfInstanceSerializer -from lcm.v2.vnf_query.query_vnf import QueryVnf - -logger = logging.getLogger(__name__) - - -class CreateVnfAndQueryVnfs(APIView): - @swagger_auto_schema( - responses={ - status.HTTP_200_OK: VnfInstanceSerializer(), - status.HTTP_500_INTERNAL_SERVER_ERROR: "Internal error" - } - ) - def get(self, request): - logger.debug("QueryMultiVnf--get::> %s" % request.data) - try: - resp_data = QueryVnf(request.data).query_multi_vnf() - - # vnfs_info_serializer = VnfsInfoSerializer(data=resp_data) - # if not vnfs_info_serializer.is_valid(): - # raise NFLCMException(vnfs_info_serializer.errors) - # - # return Response(data=vnfs_info_serializer.data, status=status.HTTP_200_OK) - - vnfInstanceSerializer = VnfInstanceSerializer(data=resp_data) - if not vnfInstanceSerializer.is_valid(): - raise NFLCMException(vnfInstanceSerializer.errors) - return Response(data=vnfInstanceSerializer.data, status=status.HTTP_200_OK) - except NFLCMException as e: - logger.error(e.message) - return Response(data={'error': '%s' % e.message}, status=status.HTTP_500_INTERNAL_SERVER_ERROR) - except Exception as e: - logger.error(e.message) - logger.error(traceback.format_exc()) - return Response(data={'error': 'Failed to get Vnfs'}, status=status.HTTP_500_INTERNAL_SERVER_ERROR) - - @swagger_auto_schema( - request_body=CreateVnfReqSerializer(), - responses={ - status.HTTP_201_CREATED: VnfInstanceSerializer(), - status.HTTP_500_INTERNAL_SERVER_ERROR: "Internal error" - } - ) - def post(self, request): - logger.debug("CreateVnfIdentifier--post::> %s" % request.data) - try: - req_serializer = CreateVnfReqSerializer(data=request.data) - if not req_serializer.is_valid(): - raise NFLCMException(req_serializer.errors) - - resp = CreateVnf(req_serializer.data).do_biz() - - vnfInstanceSerializer = VnfInstanceSerializer(data=resp) - if not vnfInstanceSerializer.is_valid(): - raise NFLCMException(vnfInstanceSerializer.errors) - return Response(data=vnfInstanceSerializer.data, status=status.HTTP_201_CREATED) - except NFLCMException as e: - logger.error(e.message) - return Response(data={'error': '%s' % e.message}, status=status.HTTP_500_INTERNAL_SERVER_ERROR) - except Exception as e: - logger.error(e.message) - logger.error(traceback.format_exc()) - return Response(data={'error': 'unexpected exception'}, status=status.HTTP_500_INTERNAL_SERVER_ERROR) diff --git a/lcm/lcm/v2/vnf_query/__init__.py b/lcm/lcm/v2/vnf_query/__init__.py deleted file mode 100644 index 342c2a8c..00000000 --- a/lcm/lcm/v2/vnf_query/__init__.py +++ /dev/null @@ -1,13 +0,0 @@ -# Copyright 2018 ZTE Corporation. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. diff --git a/lcm/lcm/v2/vnf_query/query_vnf.py b/lcm/lcm/v2/vnf_query/query_vnf.py deleted file mode 100644 index 016b1a9c..00000000 --- a/lcm/lcm/v2/vnf_query/query_vnf.py +++ /dev/null @@ -1,146 +0,0 @@ -# Copyright 2018 ZTE Corporation. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -import logging - -from lcm.pub.database.models import NfInstModel, StorageInstModel, VLInstModel, NetworkInstModel, VNFCInstModel, \ - VmInstModel -from lcm.pub.exceptions import NFLCMException - -logger = logging.getLogger(__name__) - - -class QueryVnf: - def __init__(self, data, instanceid=''): - self.vnf_inst_id = instanceid - self.data = data - - 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 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 fill_resp_data(self, vnf): - logger.info('Get storages') - storage_inst = StorageInstModel.objects.filter(instid=vnf.nfinstid) - arr = [] - for s in storage_inst: - storage = { - "virtualStorageInstanceId": s.storageid, - "storageResource": { - "vimId": s.vimid, - "resourceId": s.resouceid - } - } - arr.append(storage) - logger.info('Get networks') - vl_inst = VLInstModel.objects.filter(ownerid=vnf.nfinstid) - vl_arr = [] - for v in vl_inst: - net = NetworkInstModel.objects.filter(networkid=v.relatednetworkid) - if not net: - raise NFLCMException('NetworkInst(%s) does not exist.' % v.relatednetworkid) - v_dic = { - "virtualLinkInstanceId": v.vlinstanceid, - "virtualLinkDescId": v.vldid, - "networkResource": { - "vimId": net[0].vimid, - "resourceId": net[0].resouceid - } - } - vl_arr.append(v_dic) - logger.info('Get vnfcs') - vnfc_insts = VNFCInstModel.objects.filter(instid=vnf.nfinstid) - vnfc_arr = [] - for vnfc in vnfc_insts: - vm = VmInstModel.objects.filter(vmid=vnfc.vmid) - if not vm: - raise NFLCMException('VmInst(%s) does not exist.' % vnfc.vmid) - storage = StorageInstModel.objects.filter(ownerid=vm[0].vmid) - if not storage: - raise NFLCMException('StorageInst(%s) does not exist.' % vm[0].vmid) - vnfc_dic = { - "vnfcInstanceId": vnfc.vnfcinstanceid, - "vduId": vnfc.vduid, - "computeResource": { - "vimId": vm[0].vimid, - "resourceId": vm[0].resouceid - }, - "storageResourceIds": [s.storageid for s in storage] - } - vnfc_arr.append(vnfc_dic) - logger.info('Get vms') - vms = VmInstModel.objects.filter(instid=vnf.nfinstid) - vm_arr = [] - for vm in vms: - vm_dic = { - "vmid": vm.vmid, - "vimid": vm.vimid, - "tenant": vm.tenant, - "resouceid": vm.resouceid, - "vmname": vm.vmname, - "nic_array": vm.nic_array, - "metadata": vm.metadata, - "volume_array": vm.volume_array, - "server_group": vm.server_group, - "availability_zone": vm.availability_zone, - "flavor_id": vm.flavor_id, - "security_groups": vm.security_groups, - "operationalstate": vm.operationalstate, - "insttype": vm.insttype, - "is_predefined": vm.is_predefined, - "create_time": vm.create_time, - "instid": vm.instid, - "nodeId": vm.nodeId - } - vm_arr.append(vm_dic) - - resp_data = { - 'id': vnf.nfinstid, - 'vnfInstanceName': vnf.nf_name, - 'vnfInstanceDescription': 'Human-readable description of the VNF instance.', - 'vnfdId': vnf.vnfdid, - 'vnfProvider': vnf.vendor, - 'vnfProductName': vnf.nf_name, - 'vnfSoftwareVersion': vnf.vnfSoftwareVersion, - 'vnfdVersion': vnf.version, - 'vnfPkgId': vnf.package_id, - 'vnfConfigurableProperties': {}, - 'instantiationState': '', - 'vimConnectionInfo': {}, - "instantiatedVnfInfo": { - "flavourId": vnf.flavour_id, - "vnfState": vnf.status, - "scaleStatus": [], - "extCpInfo": [], - "extVirtualLink": [], - "monitoringParameters": {}, - "vimInfo": vm_arr, - "vnfcResourceInfo": vnfc_arr, - "virtualLinkResourceInfo": vl_arr, - "virtualStorageResourceInfo": arr - } - } - return resp_data -- cgit 1.2.3-korg