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