SOL003 API Align
[vfc/nfvo/lcm.git] / lcm / ns_vnfs / biz / grant_vnf.py
1 # Copyright 2018 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 import uuid
18 from lcm.pub.database.models import NfInstModel
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
23
24 logger = logging.getLogger(__name__)
25
26
27 class GrantVnf(object):
28     def __init__(self, grant_data):
29         self.data = grant_data
30
31     def exec_grant(self):
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)
35         has_res_tpl = False
36         grant_type = None
37         vimConnections = []
38         if ignore_case_get(self.data, "addResources"):
39             grant_type = "addResources"
40         elif ignore_case_get(self.data, "removeResources"):
41             grant_type = "removeResources"
42         else:
43             has_res_tpl = True
44
45         for res in ignore_case_get(self.data, grant_type):
46             if "resourceTemplate" in res:
47                 has_res_tpl = True
48                 break
49
50         if not has_res_tpl:
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")
55
56             vnfinsts = NfInstModel.objects.filter(
57                 nfinstid=m_vnf_inst_id, vnfm_inst_id=vnfm_inst_id)
58             if not vnfinsts:
59                 raise NSLCMException("Vnfinst(%s) is not found in vnfm(%s)" % (
60                     m_vnf_inst_id, vnfm_inst_id))
61
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"])
66
67             req_param = {
68                 "vnfInstanceId": m_vnf_inst_id,
69                 "vimId": vim_id,
70                 "vnfLcmOpOccId": ignore_case_get(self.data, "vnfLcmOpOccId"),
71                 "additionalParams": additional_param,
72                 grant_type: []
73             }
74             for res in ignore_case_get(self.data, grant_type):
75                 vdu_name = ignore_case_get(res, "vdu")
76                 grant_res = {
77                     "resourceDefinitionId": ignore_case_get(res, "resourceDefinitionId"),
78                     "type": ignore_case_get(res, "type"),
79                     "vdu": vdu_name
80                 }
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)
84                         break
85                 req_param[grant_type].append(grant_res)
86             self.data = req_param
87         vimConnections.append(resmgr.grant_vnf(self.data))
88         grant_resp = {
89             "id": str(uuid.uuid4()),
90             "vnfInstanceId": ignore_case_get(self.data, 'vnfInstanceId'),
91             "vnfLcmOpOccId": ignore_case_get(self.data, "vnfLcmOpOccId"),
92             "vimConnections": vimConnections
93         }
94         logger.debug("grant_resp=%s", grant_resp)
95         return grant_resp
96
97     def get_res_tpl(self, vdu, vnfd):
98         storage_size = 0
99         for storage_id in vdu["local_storages"]:
100             storage_size = storage_size + self.get_storage_size(storage_id, vnfd)
101         resourceTemplate = {
102             "virtualComputeDescriptor": {
103                 "virtualCpu": {
104                     "numVirtualCpu": int(vdu["virtual_compute"]["virtual_cpu"]["num_virtual_cpu"])
105                 },
106                 "virtualMemory": {
107                     "virtualMemSize": parse_unit(vdu["virtual_compute"]["virtual_memory"]["virtual_mem_size"], "MB")
108                 }
109             },
110             "virtualStorageDescriptor": {
111                 "typeOfStorage": "",
112                 "sizeOfStorage": storage_size,
113                 "swImageDescriptor": ""
114             }
115         }
116         return resourceTemplate
117
118     def get_storage_size(self, storage_id, vnfd):
119         for storage in vnfd["local_storages"]:
120             if storage_id == storage["local_storage_id"]:
121                 return parse_unit(storage["properties"]["size"], "GB")
122         return 0
123
124
125 def parse_unit(val, base_unit):
126     recognized_units = ["B", "kB", "KiB", "MB", "MiB", "GB", "GiB", "TB", "TiB"]
127     units_rate = [1, 1000, 1024, 1000000, 1048576, 1000000000, 1073741824, 1000000000000, 1099511627776]
128     unit_rate_map = {unit.upper(): rate for unit, rate in zip(recognized_units, units_rate)}
129     num_unit = val.strip().split(" ")
130     if len(num_unit) != 2:
131         return val.strip()
132     num, unit = num_unit[0], num_unit[1]
133     return int(num) * unit_rate_map[unit.upper()] / unit_rate_map[base_unit.upper()]