1 # Copyright 2018 ZTE Corporation.
3 # Licensed under the Apache License, Version 2.0 (the "License");
4 # you may not use this file except in compliance with the License.
5 # You may obtain a copy of the License at
7 # http://www.apache.org/licenses/LICENSE-2.0
9 # Unless required by applicable law or agreed to in writing, software
10 # distributed under the License is distributed on an "AS IS" BASIS,
11 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 # See the License for the specific language governing permissions and
13 # limitations under the License.
18 from lcm.pub.database.models import NfInstModel, OOFDataModel
19 from lcm.pub.exceptions import NSLCMException
20 from lcm.pub.msapi.sdc_run_catalog import query_vnfpackage_by_id
21 from lcm.pub.utils.values import ignore_case_get
22 from lcm.pub.msapi import resmgr
24 logger = logging.getLogger(__name__)
27 class GrantVnf(object):
28 def __init__(self, grant_data):
29 self.data = grant_data
32 logger.debug("grant data from vnfm:%s", self.data)
33 if isinstance(self.data, (unicode, str)):
34 self.data = json.JSONDecoder().decode(self.data)
38 if ignore_case_get(self.data, "addResources"):
39 grant_type = "addResources"
40 elif ignore_case_get(self.data, "removeResources"):
41 grant_type = "removeResources"
45 for res in ignore_case_get(self.data, grant_type):
46 if "resourceTemplate" in res:
51 m_vnf_inst_id = ignore_case_get(self.data, "vnfInstanceId")
52 additional_param = ignore_case_get(self.data, "additionalparams")
53 vnfm_inst_id = ignore_case_get(additional_param, "vnfmid")
54 vim_id = ignore_case_get(additional_param, "vimid")
56 vnfinsts = NfInstModel.objects.filter(
57 nfinstid=m_vnf_inst_id, vnfm_inst_id=vnfm_inst_id)
59 raise NSLCMException("Vnfinst(%s) is not found in vnfm(%s)" % (
60 m_vnf_inst_id, vnfm_inst_id))
62 vnf_pkg_id = vnfinsts[0].package_id
63 nfpackage_info = query_vnfpackage_by_id(vnf_pkg_id)
64 vnf_pkg = nfpackage_info["packageInfo"]
65 vnfd = json.JSONDecoder().decode(vnf_pkg["vnfdModel"])
68 "vnfInstanceId": m_vnf_inst_id,
70 "vnfLcmOpOccId": ignore_case_get(self.data, "vnfLcmOpOccId"),
71 "additionalParams": additional_param,
74 for res in ignore_case_get(self.data, grant_type):
75 vdu_name = ignore_case_get(res, "vdu")
77 "resourceDefinitionId": ignore_case_get(res, "resourceDefinitionId"),
78 "type": ignore_case_get(res, "type"),
81 for vdu in vnfd["vdus"]:
82 if vdu_name in (vdu["vdu_id"], vdu["properties"].get("name", "")):
83 grant_res["resourceTemplate"] = self.get_res_tpl(vdu, vnfd)
85 req_param[grant_type].append(grant_res)
87 vimConnections.append(resmgr.grant_vnf(self.data))
90 "id": str(uuid.uuid4()),
91 "vnfInstanceId": ignore_case_get(self.data, 'vnfInstanceId'),
92 "vnfLcmOpOccId": ignore_case_get(self.data, "vnfLcmOpOccId"),
93 "vimConnections": vimConnections
96 offs = OOFDataModel.objects.filter(service_resource_id=ignore_case_get(self.data, "vnfInstanceId"))
99 grant_resp['vimAssets']['computeResourceFlavours'].append({
100 'vimConnectionId': off.vim_id,
101 'resourceProviderId': off.vdu_name,
102 'vnfdVirtualComputeDescId': None, # TODO: required
103 'vimFlavourId': off.flavor_name
105 grant_resp['additionalparams'][off.vim_id] = off.directive
107 logger.debug("grant_resp=%s", grant_resp)
110 def get_res_tpl(self, vdu, vnfd):
112 for storage_id in vdu["local_storages"]:
113 storage_size = storage_size + self.get_storage_size(storage_id, vnfd)
115 "virtualComputeDescriptor": {
117 "numVirtualCpu": int(vdu["virtual_compute"]["virtual_cpu"]["num_virtual_cpu"])
120 "virtualMemSize": parse_unit(vdu["virtual_compute"]["virtual_memory"]["virtual_mem_size"], "MB")
123 "virtualStorageDescriptor": {
125 "sizeOfStorage": storage_size,
126 "swImageDescriptor": ""
129 return resourceTemplate
131 def get_storage_size(self, storage_id, vnfd):
132 for storage in vnfd["local_storages"]:
133 if storage_id == storage["local_storage_id"]:
134 return parse_unit(storage["properties"]["size"], "GB")
138 def parse_unit(val, base_unit):
139 recognized_units = ["B", "kB", "KiB", "MB", "MiB", "GB", "GiB", "TB", "TiB"]
140 units_rate = [1, 1000, 1024, 1000000, 1048576, 1000000000, 1073741824, 1000000000000, 1099511627776]
141 unit_rate_map = {unit.upper(): rate for unit, rate in zip(recognized_units, units_rate)}
142 num_unit = val.strip().split(" ")
143 if len(num_unit) != 2:
145 num, unit = num_unit[0], num_unit[1]
146 return int(num) * unit_rate_map[unit.upper()] / unit_rate_map[base_unit.upper()]