4ce0e697b4c9aeeee5c3001548c6d1e780e46081
[vfc/gvnfm/vnflcm.git] / lcm / lcm / pub / vimapi / adaptor.py
1 # Copyright 2017 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 logging
16 import time
17
18 from lcm.pub.utils.values import ignore_case_get, set_opt_val
19 from lcm.pub.msapi.aai import get_flavor_info
20 from . import api
21 from .exceptions import VimException
22
23 logger = logging.getLogger(__name__)
24
25 ERR_CODE = "500"
26 RES_EXIST, RES_NEW = 0, 1
27 IP_V4, IP_V6 = 4, 6
28 BOOT_FROM_VOLUME, BOOT_FROM_IMAGE = 1, 2
29
30 RES_VOLUME = "volume"
31 RES_NETWORK = "network"
32 RES_SUBNET = "subnet"
33 RES_PORT = "port"
34 RES_FLAVOR = "flavor"
35 RES_VM = "vm"
36 NOT_PREDEFINED = 1
37
38
39 def get_tenant_id(vim_cache, vim_id, tenant_name):
40     if vim_id not in vim_cache:
41         tenants = api.list_tenant(vim_id)
42         vim_cache[vim_id] = {}
43         for tenant in tenants["tenants"]:
44             id, name = tenant["id"], tenant["name"]
45             vim_cache[vim_id][name] = id
46     if tenant_name not in vim_cache[vim_id]:
47         raise VimException("Tenant(%s) not found in vim(%s)" % (tenant_name, vim_id), ERR_CODE)
48     return vim_cache[vim_id][tenant_name]
49
50
51 def set_res_cache(res_cache, res_type, key, val):
52     if res_type not in res_cache:
53         res_cache[res_type] = {}
54     if key in res_cache[res_type]:
55         raise VimException("Duplicate key(%s) of %s" % (key, res_type), ERR_CODE)
56     res_cache[res_type][key] = val
57
58
59 def get_res_id(res_cache, res_type, key):
60     if res_type not in res_cache:
61         raise VimException("%s not found in cache" % res_type, ERR_CODE)
62     if key not in res_cache[res_type]:
63         raise VimException("%s(%s) not found in cache" % (res_type, key), ERR_CODE)
64     return res_cache[res_type][key]
65
66
67 def create_vim_res(data, do_notify):
68     vim_cache, res_cache = {}, {}
69     for vol in ignore_case_get(data, "volume_storages"):
70         create_volume(vim_cache, res_cache, vol, do_notify, RES_VOLUME)
71     for network in ignore_case_get(data, "vls"):
72         create_network(vim_cache, res_cache, network, do_notify, RES_NETWORK)
73     for subnet in ignore_case_get(data, "vls"):
74         create_subnet(vim_cache, res_cache, subnet, do_notify, RES_SUBNET)
75     for port in ignore_case_get(data, "cps"):
76         create_port(vim_cache, res_cache, data, port, do_notify, RES_PORT)
77     for vdu in ignore_case_get(data, "vdus"):
78         if vdu["type"] == "tosca.nodes.nfv.Vdu.Compute":
79             create_flavor(vim_cache, res_cache, data, vdu, do_notify, RES_FLAVOR)
80     for vdu in ignore_case_get(data, "vdus"):
81         if vdu["type"] == "tosca.nodes.nfv.Vdu.Compute":
82             create_vm(vim_cache, res_cache, data, vdu, do_notify, RES_VM)
83
84
85 def delete_vim_res(data, do_notify):
86     res_types = [RES_VM, RES_FLAVOR, RES_PORT, RES_SUBNET, RES_NETWORK, RES_VOLUME]
87     res_del_funs = [api.delete_vm, api.delete_flavor, api.delete_port,
88                     api.delete_subnet, api.delete_network, api.delete_volume]
89     for res_type, res_del_fun in zip(res_types, res_del_funs):
90         for res in ignore_case_get(data, res_type):
91             try:
92                 if NOT_PREDEFINED == res["is_predefined"]:
93                     res_del_fun(res["vim_id"], res["tenant_id"], res["res_id"])
94             except VimException as e:
95                 logger.error("Failed to delete %s(%s)", res_type, res["res_id"])
96                 logger.error("%s:%s", e.http_code, e.message)
97             do_notify(res_type, res["res_id"])
98
99
100 def create_volume(vim_cache, res_cache, vol, do_notify, res_type):
101     location_info = vol["properties"]["location_info"]
102     param = {
103         "name": vol["properties"]["volume_name"],
104         "volumeSize": int(ignore_case_get(vol["properties"], "size", "0").replace('GB', '').strip())
105     }
106     set_opt_val(param, "imageName", ignore_case_get(vol, "image_file"))
107     set_opt_val(param, "volumeType", ignore_case_get(vol["properties"], "custom_volume_type"))
108     set_opt_val(param, "availabilityZone", ignore_case_get(location_info, "availability_zone"))
109     vim_id, tenant_name = location_info["vimid"], location_info["tenant"]
110     tenant_id = get_tenant_id(vim_cache, vim_id, tenant_name)
111     ret = api.create_volume(vim_id, tenant_id, param)
112     ret["nodeId"] = vol["volume_storage_id"]
113     do_notify(res_type, ret)
114     vol_id, vol_name = ret["id"], ret["name"]
115     set_res_cache(res_cache, res_type, vol["volume_storage_id"], vol_id)
116     retry_count, max_retry_count = 0, 300
117     while retry_count < max_retry_count:
118         vol_info = api.get_volume(vim_id, tenant_id, vol_id)
119         if vol_info["status"].upper() == "AVAILABLE":
120             logger.debug("Volume(%s) is available", vol_id)
121             return
122         time.sleep(2)
123         retry_count = retry_count + 1
124     raise VimException("Failed to create Volume(%s): Timeout." % vol_name, ERR_CODE)
125
126
127 def create_network(vim_cache, res_cache, network, do_notify, res_type):
128     location_info = network["properties"]["location_info"]
129     vl_profile = network["properties"]["vl_profile"]
130     param = {
131         "name": vl_profile["networkName"],
132         "shared": False,
133         "networkType": vl_profile["networkType"],
134         "physicalNetwork": ignore_case_get(vl_profile, "physicalNetwork")
135     }
136     set_opt_val(param, "vlanTransparent", ignore_case_get(vl_profile, "vlanTransparent"))
137     set_opt_val(param, "segmentationId", int(ignore_case_get(vl_profile, "segmentationId", "0")))
138     set_opt_val(param, "routerExternal", ignore_case_get(network, "route_external"))
139     vim_id, tenant_name = location_info["vimid"], location_info["tenant"]
140     tenant_id = get_tenant_id(vim_cache, vim_id, tenant_name)
141     ret = api.create_network(vim_id, tenant_id, param)
142     ret["nodeId"] = network["vl_id"]
143     do_notify(res_type, ret)
144     set_res_cache(res_cache, res_type, network["vl_id"], ret["id"])
145
146
147 def create_subnet(vim_cache, res_cache, subnet, do_notify, res_type):
148     location_info = subnet["properties"]["location_info"]
149     network_id = get_res_id(res_cache, RES_NETWORK, subnet["vl_id"])
150     vl_profile = subnet["properties"]["vl_profile"]
151     layer_protocol = ignore_case_get(subnet["properties"]["connectivity_type"], "layer_protocol")
152     param = {
153         "networkId": network_id,
154         "name": vl_profile["networkName"] + "_subnet",
155         "cidr": ignore_case_get(vl_profile, "cidr"),
156         "ipVersion": IP_V4 if(layer_protocol == 'ipv4') else (IP_V6 if(layer_protocol == 'ipv6') else None)
157     }
158     set_opt_val(param, "enableDhcp", ignore_case_get(vl_profile, "dhcpEnabled"))
159     set_opt_val(param, "gatewayIp", ignore_case_get(vl_profile, "gatewayIp"))
160     set_opt_val(param, "dnsNameservers", ignore_case_get(subnet["properties"], "dns_nameservers"))
161     allocation_pool = {}
162     set_opt_val(allocation_pool, "start", ignore_case_get(vl_profile, "startIp"))
163     set_opt_val(allocation_pool, "end", ignore_case_get(vl_profile, "endIp"))
164     if allocation_pool:
165         param["allocationPools"] = [allocation_pool]
166     set_opt_val(param, "hostRoutes", ignore_case_get(subnet["properties"], "host_routes"))
167     vim_id, tenant_name = location_info["vimid"], location_info["tenant"]
168     tenant_id = get_tenant_id(vim_cache, vim_id, tenant_name)
169     ret = api.create_subnet(vim_id, tenant_id, param)
170     do_notify(res_type, ret)
171     set_res_cache(res_cache, res_type, subnet["vl_id"], ret["id"])
172
173
174 def create_port(vim_cache, res_cache, data, port, do_notify, res_type):
175     location_info = None
176     port_ref_vdu_id = ignore_case_get(port, "vdu_id")
177     for vdu in ignore_case_get(data, "vdus"):
178         if vdu["vdu_id"] == port_ref_vdu_id:
179             location_info = vdu["properties"]["location_info"]
180             if port["cp_id"] not in vdu["cps"]:
181                 vdu["cps"].append(port["cp_id"])
182             break
183     if not location_info:
184         err_msg = "vdu_id(%s) for cp(%s) is not defined"
185         raise VimException(err_msg % (port_ref_vdu_id, port["cp_id"]), ERR_CODE)
186     network_id = ignore_case_get(port, "networkId")
187     subnet_id = ignore_case_get(port, "subnetId")
188     if not network_id:
189         network_id = get_res_id(res_cache, RES_NETWORK, port["vl_id"])
190         subnet_id = get_res_id(res_cache, RES_SUBNET, port["vl_id"])
191     param = {
192         "networkId": network_id,
193         "name": port["properties"].get("name", "undefined")
194     }
195     set_opt_val(param, "subnetId", subnet_id)
196     set_opt_val(param, "macAddress", ignore_case_get(port["properties"], "mac_address"))
197     l3_address_data = port["properties"]["protocol_data"]["address_data"]["l3_address_data"]
198     set_opt_val(param, "ip", ignore_case_get(l3_address_data, "fixed_ip_address"))
199     set_opt_val(param, "vnicType", ignore_case_get(port["properties"], "vnic_type"))
200     set_opt_val(param, "securityGroups", "")   # TODO
201     vim_id, tenant_name = location_info["vimid"], location_info["tenant"]
202     tenant_id = get_tenant_id(vim_cache, vim_id, tenant_name)
203     ret = api.create_port(vim_id, tenant_id, param)
204     ret["nodeId"] = port["cp_id"]
205     do_notify(res_type, ret)
206     set_res_cache(res_cache, res_type, port["cp_id"], ret["id"])
207
208
209 def search_flavor_aai(vim_id, memory_page_size):
210     aai_flavors = get_flavor_info(vim_id)
211     if not aai_flavors:
212         return None
213     logger.debug("aai_flavors:%s" % aai_flavors)
214     aai_flavor = aai_flavors[0]["flavors"]["flavor"]
215     for one_aai_flavor in aai_flavor:
216         hpa_capabilities = one_aai_flavor["hpa-capabilities"]
217         for one_hpa_capa in hpa_capabilities:
218             hpa_feature_attr = one_hpa_capa["hpa-feature-attributes"]
219             for one_hpa_attr in hpa_feature_attr:
220                 hpa_key = one_hpa_attr["hpa-attribute-key"]
221                 hpa_value = one_hpa_attr["hpa-attribute-value"]["value"]
222                 if hpa_key == "memoryPageSize" and int(hpa_value) == memory_page_size:
223                     return one_aai_flavor
224
225
226 def create_flavor(vim_cache, res_cache, data, flavor, do_notify, res_type):
227     location_info = flavor["properties"]["location_info"]
228     vim_id, tenant_name = location_info["vimid"], location_info["tenant"]
229     virtual_compute = flavor["virtual_compute"]
230     param = {
231         "name": "Flavor_%s" % flavor["vdu_id"],
232         "vcpu": int(virtual_compute["virtual_cpu"]["num_virtual_cpu"]),
233         "memory": int(virtual_compute["virtual_memory"]["virtual_mem_size"].replace('MB', '').strip()),
234         "isPublic": True
235     }
236
237     # just do memory huge page
238     flavor_extra_specs = ""
239     vdu_memory_requirements = virtual_compute["virtual_memory"]["vdu_memory_requirements"]
240     if "memoryPageSize" in vdu_memory_requirements:
241         memory_page_size = int(vdu_memory_requirements["memoryPageSize"].replace('MB', '').strip())
242         flavor_extra_specs = ("hw:mem_page_size=%sMB" % memory_page_size)
243         logger.debug("flavor_extra_specs:%s" % flavor_extra_specs)
244
245     # search aai flavor
246     aai_flavor = search_flavor_aai(vim_id, memory_page_size)
247
248     # add aai flavor
249     if aai_flavor:
250         ret = aai_flavor
251         do_notify(res_type, ret)
252         set_res_cache(res_cache, res_type, flavor["vdu_id"], ret["flavor-id"])
253     else:
254         extra_specs = []
255         disk_type = virtual_compute["virtual_storage"]["type_of_storage"]
256         disk_size = int(virtual_compute["virtual_storage"]["size_of_storage"].replace('GB', '').strip())
257         if disk_type == "root":
258             param["disk"] = disk_size
259         elif disk_type == "ephemeral":
260             param["ephemeral"] = disk_size
261         elif disk_type == "swap":
262             param["swap"] = disk_size
263
264         for es in flavor_extra_specs:
265             extra_specs.append({"keyName": es, "value": flavor_extra_specs[es]})
266
267         set_opt_val(param, "extraSpecs", extra_specs)
268         tenant_id = get_tenant_id(vim_cache, vim_id, tenant_name)
269         logger.debug("param:%s" % param)
270         ret = api.create_flavor(vim_id, tenant_id, param)
271         do_notify(res_type, ret)
272         set_res_cache(res_cache, res_type, flavor["vdu_id"], ret["id"])
273
274
275 def create_vm(vim_cache, res_cache, data, vm, do_notify, res_type):
276     location_info = vm["properties"]["location_info"]
277     vim_id, tenant_name = location_info["vimid"], location_info["tenant"]
278     tenant_id = get_tenant_id(vim_cache, vim_id, tenant_name)
279     param = {
280         "name": vm["properties"].get("name", "undefined"),
281         "flavorId": get_res_id(res_cache, RES_FLAVOR, vm["vdu_id"]),
282         "boot": {},
283         "nicArray": [],
284         "contextArray": [],
285         "volumeArray": []
286     }
287     # set boot param
288     if "image_file" in vm and vm["image_file"]:
289         param["boot"]["type"] = BOOT_FROM_IMAGE
290         img_name = ""
291         for img in ignore_case_get(data, "image_files"):
292             if vm["image_file"] == img["image_file_id"]:
293                 img_name = img["properties"]["name"]
294                 break
295         if not img_name:
296             raise VimException("Undefined image(%s)" % vm["image_file"], ERR_CODE)
297         images = api.list_image(vim_id, tenant_id)
298         for image in images["images"]:
299             if img_name == image["name"]:
300                 param["boot"]["imageId"] = image["id"]
301                 break
302         if "imageId" not in param["boot"]:
303             raise VimException("Image(%s) not found in Vim(%s)" % (img_name, vim_id), ERR_CODE)
304     elif vm["volume_storages"]:
305         param["boot"]["type"] = BOOT_FROM_VOLUME
306         vol_id = vm["volume_storages"][0]["volume_storage_id"]
307         param["boot"]["volumeId"] = get_res_id(res_cache, RES_VOLUME, vol_id)
308     else:
309         raise VimException("No image and volume defined", ERR_CODE)
310
311     for cp_id in ignore_case_get(vm, "cps"):
312         param["nicArray"].append({
313             "portId": get_res_id(res_cache, RES_PORT, cp_id)
314         })
315     for inject_data in ignore_case_get(vm["properties"], "inject_data_list"):
316         param["contextArray"].append({
317             "fileName": inject_data["file_name"],
318             "fileData": inject_data["file_data"]
319         })
320     for vol_data in ignore_case_get(vm, "volume_storages"):
321         vol_id = vol_data["volume_storage_id"]
322         param["volumeArray"].append({
323             "volumeId": get_res_id(res_cache, RES_VOLUME, vol_id)
324         })
325
326     set_opt_val(param, "availabilityZone", ignore_case_get(location_info, "availability_zone"))
327     set_opt_val(param, "userdata", "")         # TODO Configuration information or scripts to use upon launch
328     set_opt_val(param, "metadata", "")         # TODO [{"keyName": "foo", "value": "foo value"}]
329     set_opt_val(param, "securityGroups", "")   # TODO List of names of security group
330     set_opt_val(param, "serverGroup", "")      # TODO the ServerGroup for anti-affinity and affinity
331
332     ret = api.create_vm(vim_id, tenant_id, param)
333     do_notify(res_type, ret)
334     vm_id = ret["id"]
335     if ignore_case_get(ret, "name"):
336         vm_name = vm["properties"].get("name", "undefined")
337         logger.debug("vm_name:%s" % vm_name)
338     opt_vm_status = "Timeout"
339     retry_count, max_retry_count = 0, 100
340     while retry_count < max_retry_count:
341         vm_info = api.get_vm(vim_id, tenant_id, vm_id)
342         if vm_info["status"].upper() == "ACTIVE":
343             logger.debug("Vm(%s) is active", vim_id)
344             return
345         if vm_info["status"].upper() == "ERROR":
346             opt_vm_status = vm_info["status"]
347             break
348         time.sleep(2)
349         retry_count = retry_count + 1
350     raise VimException("Failed to create Vm(%s): %s." % (vm_name, opt_vm_status), ERR_CODE)