Remove directive from addtionalParams
[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, 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
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         tmp = resmgr.grant_vnf(self.data)
88         vimConnections.append(
89             {
90                 "id": tmp["vim"]["vimId"],
91                 "vimId": tmp["vim"]["vimId"],
92                 "vimType": None,
93                 "interfaceInfo": None,
94                 "accessInfo": tmp["vim"]["accessInfo"],
95                 "extra": None
96             }
97         )
98
99         grant_resp = {
100             "id": str(uuid.uuid4()),
101             "vnfInstanceId": ignore_case_get(self.data, 'vnfInstanceId'),
102             "vnfLcmOpOccId": ignore_case_get(self.data, "vnfLcmOpOccId"),
103             "vimConnections": vimConnections
104         }
105
106         offs = OOFDataModel.objects.filter(service_resource_id=ignore_case_get(self.data, "vnfInstanceId"))
107         if offs.exists():
108             for off in offs:
109                 grant_resp['vimAssets']['computeResourceFlavours'].append({
110                     'vimConnectionId': off.vim_id,
111                     'resourceProviderId': off.vdu_name,
112                     'vnfdVirtualComputeDescId': None,  # TODO: required
113                     'vimFlavourId': off.flavor_name
114                 })
115                 # grant_resp['additionalparams'][off.vim_id] = off.directive
116
117         logger.debug("grant_resp=%s", grant_resp)
118         return grant_resp
119
120     def get_res_tpl(self, vdu, vnfd):
121         storage_size = 0
122         for storage_id in vdu["local_storages"]:
123             storage_size = storage_size + self.get_storage_size(storage_id, vnfd)
124         resourceTemplate = {
125             "virtualComputeDescriptor": {
126                 "virtualCpu": {
127                     "numVirtualCpu": int(vdu["virtual_compute"]["virtual_cpu"]["num_virtual_cpu"])
128                 },
129                 "virtualMemory": {
130                     "virtualMemSize": parse_unit(vdu["virtual_compute"]["virtual_memory"]["virtual_mem_size"], "MB")
131                 }
132             },
133             "virtualStorageDescriptor": {
134                 "typeOfStorage": "",
135                 "sizeOfStorage": storage_size,
136                 "swImageDescriptor": ""
137             }
138         }
139         return resourceTemplate
140
141     def get_storage_size(self, storage_id, vnfd):
142         for storage in vnfd["local_storages"]:
143             if storage_id == storage["local_storage_id"]:
144                 return parse_unit(storage["properties"]["size"], "GB")
145         return 0
146
147
148 def parse_unit(val, base_unit):
149     recognized_units = ["B", "kB", "KiB", "MB", "MiB", "GB", "GiB", "TB", "TiB"]
150     units_rate = [1, 1000, 1024, 1000000, 1048576, 1000000000, 1073741824, 1000000000000, 1099511627776]
151     unit_rate_map = {unit.upper(): rate for unit, rate in zip(recognized_units, units_rate)}
152     num_unit = val.strip().split(" ")
153     if len(num_unit) != 2:
154         return val.strip()
155     num, unit = num_unit[0], num_unit[1]
156     return int(num) * unit_rate_map[unit.upper()] / unit_rate_map[base_unit.upper()]