Update python2 to python3
[vfc/nfvo/lcm.git] / lcm / ns_vnfs / biz / grant_vnfs.py
1 # Copyright 2016 ZTE Corporation.
2 #
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
6 #
7 #         http://www.apache.org/licenses/LICENSE-2.0
8 #
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.
14
15 import json
16 import logging
17
18 from lcm.pub.database.models import NfInstModel
19 from lcm.pub.exceptions import NSLCMException
20 from lcm.pub.msapi import resmgr
21 from lcm.pub.msapi.sdc_run_catalog import query_vnfpackage_by_id
22 from lcm.pub.utils.values import ignore_case_get
23 from lcm.ns_vnfs.const import SCALAR_UNIT_DICT
24
25 logger = logging.getLogger(__name__)
26
27
28 class GrantVnfs(object):
29     def __init__(self, data, job_id):
30         self.job_id = job_id
31         self.vnfm_inst_id = ''
32         self.vnf_uuid = ''
33         self.vnfm_job_id = ''
34         self.data = data
35
36     def send_grant_vnf_to_resMgr(self):
37         logger.debug("grant data from vnfm:%s", self.data)
38         if isinstance(self.data, str):
39             self.data = json.JSONDecoder().decode(self.data)
40         has_res_tpl = False
41         grant_type = None
42         if ignore_case_get(self.data, "addResource"):
43             grant_type = "addResource"
44         elif ignore_case_get(self.data, "removeResource"):
45             grant_type = "removeResource"
46         else:
47             has_res_tpl = True
48
49         for res in ignore_case_get(self.data, grant_type):
50             if "resourceTemplate" in res:
51                 has_res_tpl = True
52                 break
53
54         if not has_res_tpl:
55             m_vnf_inst_id = ignore_case_get(self.data, "vnfInstanceId")
56             additional_param = ignore_case_get(self.data, "additionalparam")
57             vnfm_inst_id = ignore_case_get(additional_param, "vnfmid")
58             vim_id = ignore_case_get(additional_param, "vimid")
59
60             vnfinsts = NfInstModel.objects.filter(
61                 mnfinstid=m_vnf_inst_id, vnfm_inst_id=vnfm_inst_id)
62             if not vnfinsts:
63                 raise NSLCMException("Vnfinst(%s) is not found in vnfm(%s)" % (
64                     m_vnf_inst_id, vnfm_inst_id))
65
66             vnf_pkg_id = vnfinsts[0].package_id
67             nfpackage_info = query_vnfpackage_by_id(vnf_pkg_id)
68             vnf_pkg = nfpackage_info["packageInfo"]
69
70             vnfd = json.JSONDecoder().decode(vnf_pkg["vnfdModel"])
71
72             req_param = {
73                 "vnfInstanceId": m_vnf_inst_id,
74                 "vimId": vim_id,
75                 "additionalParam": additional_param,
76                 grant_type: []
77             }
78             for res in ignore_case_get(self.data, grant_type):
79                 vdu_name = ignore_case_get(res, "vdu")
80                 grant_res = {
81                     "resourceDefinitionId": ignore_case_get(res, "resourceDefinitionId"),
82                     "type": ignore_case_get(res, "type"),
83                     "vdu": vdu_name
84                 }
85                 for vdu in vnfd["vdus"]:
86                     if vdu_name in (vdu["vdu_id"], vdu["properties"].get("name", "")):
87                         grant_res["resourceTemplate"] = self.get_res_tpl(vdu, vnfd)
88                         break
89                 req_param[grant_type].append(grant_res)
90             self.data = req_param
91         return resmgr.grant_vnf(self.data)
92
93     def get_res_tpl(self, vdu, vnfd):
94         storage_size = 0
95         for storage_id in vdu["local_storages"]:
96             storage_size = storage_size + self.get_storage_size(storage_id, vnfd)
97         resourceTemplate = {
98             "virtualComputeDescriptor": {
99                 "virtualCpu": {
100                     "numVirtualCpu": int(vdu["virtual_compute"]["virtual_cpu"]["num_virtual_cpu"])
101                 },
102                 "virtualMemory": {
103                     "virtualMemSize": parse_unit(vdu["virtual_compute"]["virtual_memory"]["virtual_mem_size"], "MB")
104                 }
105             },
106             "virtualStorageDescriptor": {
107                 "typeOfStorage": "",
108                 "sizeOfStorage": storage_size,
109                 "swImageDescriptor": ""
110             }
111         }
112         return resourceTemplate
113
114     def get_storage_size(self, storage_id, vnfd):
115         for storage in vnfd["local_storages"]:
116             if storage_id == storage["local_storage_id"]:
117                 return parse_unit(storage["properties"]["size"], "GB")
118         return 0
119
120
121 def parse_unit(val, base_unit):
122     # recognized_units = ["B", "kB", "KiB", "MB", "MiB", "GB", "GiB", "TB", "TiB"]
123     # units_rate = [1, 1000, 1024, 1000000, 1048576, 1000000000, 1073741824, 1000000000000, 1099511627776]
124     # unit_rate_map = {unit.upper(): rate for unit, rate in zip(recognized_units, units_rate)}
125     num_unit = val.strip().split(" ")
126     if len(num_unit) != 2:
127         return val.strip()
128     num, unit = num_unit[0], num_unit[1]
129     return int(num) * SCALAR_UNIT_DICT[unit.upper()] / SCALAR_UNIT_DICT[base_unit.upper()]