d07a356948396c8c3d56f31cf489ce0d947cded0
[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
37
38 def get_tenant_id(vim_cache, vim_id, tenant_name):
39     if vim_id not in vim_cache:
40         tenants = api.list_tenant(vim_id)
41         vim_cache[vim_id] = {}
42         for tenant in tenants["tenants"]:
43             id, name = tenant["id"], tenant["name"]
44             vim_cache[vim_id][name] = id
45     if tenant_name not in vim_cache[vim_id]:
46         raise VimException("Tenant(%s) not found in vim(%s)" % (tenant_name, vim_id), ERR_CODE)
47     return vim_cache[vim_id][tenant_name]
48
49
50 def set_res_cache(res_cache, res_type, key, val):
51     if res_type not in res_cache:
52         res_cache[res_type] = {}
53     if key in res_cache[res_type]:
54         raise VimException("Duplicate key(%s) of %s" % (key, res_type), ERR_CODE)
55     res_cache[res_type][key] = val
56
57
58 def get_res_id(res_cache, res_type, key):
59     if res_type not in res_cache:
60         raise VimException("%s not found in cache" % res_type, ERR_CODE)
61     if key not in res_cache[res_type]:
62         raise VimException("%s(%s) not found in cache" % (res_type, key), ERR_CODE)
63     return res_cache[res_type][key]
64
65
66 def create_vim_res(data, do_notify):
67     vim_cache, res_cache = {}, {}
68     for vol in ignore_case_get(data, "volume_storages"):
69         create_volume(vim_cache, res_cache, vol, do_notify, RES_VOLUME)
70     for network in ignore_case_get(data, "vls"):
71         create_network(vim_cache, res_cache, network, do_notify, RES_NETWORK)
72     for subnet in ignore_case_get(data, "vls"):
73         create_subnet(vim_cache, res_cache, subnet, do_notify, RES_SUBNET)
74     for port in ignore_case_get(data, "cps"):
75         create_port(vim_cache, res_cache, data, port, do_notify, RES_PORT)
76     for flavor in ignore_case_get(data, "vdus"):
77         create_flavor(vim_cache, res_cache, data, flavor, do_notify, RES_FLAVOR)
78     for vm in ignore_case_get(data, "vdus"):
79         create_vm(vim_cache, res_cache, data, vm, do_notify, RES_VM)
80
81
82 def delete_vim_res(data, do_notify):
83     res_types = [RES_VM, RES_FLAVOR, RES_PORT, RES_SUBNET, RES_NETWORK, RES_VOLUME]
84     res_del_funs = [api.delete_vm, api.delete_flavor, api.delete_port,
85                     api.delete_subnet, api.delete_network, api.delete_volume]
86     for res_type, res_del_fun in zip(res_types, res_del_funs):
87         for res in ignore_case_get(data, res_type):
88             try:
89                 if 1 == res["is_predefined"]:
90                     res_del_fun(res["vim_id"], res["tenant_id"], res["res_id"])
91             except VimException as e:
92                 logger.error("Failed to delete %s(%s)", res_type, res["res_id"])
93                 logger.error("%s:%s", e.http_code, e.message)
94             do_notify(res_type, res["res_id"])
95
96
97 def create_volume(vim_cache, res_cache, vol, do_notify, res_type):
98     location_info = vol["properties"]["location_info"]
99     param = {
100         "name": vol["properties"]["volume_name"],
101         "volumeSize": int(ignore_case_get(vol["properties"], "size", "0").replace('GB', '').strip())
102     }
103     set_opt_val(param, "imageName", ignore_case_get(vol, "image_file"))
104     set_opt_val(param, "volumeType", ignore_case_get(vol["properties"], "custom_volume_type"))
105     set_opt_val(param, "availabilityZone", ignore_case_get(location_info, "availability_zone"))
106     vim_id, tenant_name = location_info["vimid"], location_info["tenant"]
107     tenant_id = get_tenant_id(vim_cache, vim_id, tenant_name)
108     ret = api.create_volume(vim_id, tenant_id, param)
109     ret["nodeId"] = vol["volume_storage_id"]
110     do_notify(res_type, ret)
111     vol_id, vol_name = ret["id"], ret["name"]
112     set_res_cache(res_cache, res_type, vol["volume_storage_id"], vol_id)
113     retry_count, max_retry_count = 0, 300
114     while retry_count < max_retry_count:
115         vol_info = api.get_volume(vim_id, tenant_id, vol_id)
116         if vol_info["status"].upper() == "AVAILABLE":
117             logger.debug("Volume(%s) is available", vol_id)
118             return
119         time.sleep(2)
120         retry_count = retry_count + 1
121     raise VimException("Failed to create Volume(%s): Timeout." % vol_name, ERR_CODE)
122
123
124 def create_network(vim_cache, res_cache, network, do_notify, res_type):
125     location_info = network["properties"]["location_info"]
126     param = {
127         "name": network["properties"]["network_name"],
128         "shared": False,
129         "networkType": network["properties"]["network_type"],
130         "physicalNetwork": ignore_case_get(network["properties"], "physical_network")
131     }
132     set_opt_val(param, "vlanTransparent", ignore_case_get(network["properties"], "vlan_transparent"))
133     set_opt_val(param, "segmentationId", int(ignore_case_get(network["properties"], "segmentation_id", "0")))
134     set_opt_val(param, "routerExternal", ignore_case_get(network, "route_external"))
135     vim_id, tenant_name = location_info["vimid"], location_info["tenant"]
136     tenant_id = get_tenant_id(vim_cache, vim_id, tenant_name)
137     ret = api.create_network(vim_id, tenant_id, param)
138     ret["nodeId"] = network["vl_id"]
139     do_notify(res_type, ret)
140     set_res_cache(res_cache, res_type, network["vl_id"], ret["id"])
141
142
143 def create_subnet(vim_cache, res_cache, subnet, do_notify, res_type):
144     location_info = subnet["properties"]["location_info"]
145     network_id = get_res_id(res_cache, RES_NETWORK, subnet["vl_id"])
146     param = {
147         "networkId": network_id,
148         "name": subnet["properties"]["name"],
149         "cidr": ignore_case_get(subnet["properties"], "cidr"),
150         "ipVersion": ignore_case_get(subnet["properties"], "ip_version", IP_V4)
151     }
152     set_opt_val(param, "enableDhcp", ignore_case_get(subnet["properties"], "dhcp_enabled"))
153     set_opt_val(param, "gatewayIp", ignore_case_get(subnet["properties"], "gateway_ip"))
154     set_opt_val(param, "dnsNameservers", ignore_case_get(subnet["properties"], "dns_nameservers"))
155     allocation_pool = {}
156     set_opt_val(allocation_pool, "start", ignore_case_get(subnet["properties"], "start_ip"))
157     set_opt_val(allocation_pool, "end", ignore_case_get(subnet["properties"], "end_ip"))
158     if allocation_pool:
159         param["allocationPools"] = [allocation_pool]
160     set_opt_val(param, "hostRoutes", ignore_case_get(subnet["properties"], "host_routes"))
161     vim_id, tenant_name = location_info["vimid"], location_info["tenant"]
162     tenant_id = get_tenant_id(vim_cache, vim_id, tenant_name)
163     ret = api.create_subnet(vim_id, tenant_id, param)
164     do_notify(res_type, ret)
165     set_res_cache(res_cache, res_type, subnet["vl_id"], ret["id"])
166
167
168 def create_port(vim_cache, res_cache, data, port, do_notify, res_type):
169     location_info = None
170     port_ref_vdu_id = ignore_case_get(port, "vdu_id")
171     for vdu in ignore_case_get(data, "vdus"):
172         if vdu["vdu_id"] == port_ref_vdu_id:
173             location_info = vdu["properties"]["location_info"]
174             if port["cp_id"] not in vdu["cps"]:
175                 vdu["cps"].append(port["cp_id"])
176             break
177     if not location_info:
178         err_msg = "vdu_id(%s) for cp(%s) is not defined"
179         raise VimException(err_msg % (port_ref_vdu_id, port["cp_id"]), ERR_CODE)
180     network_id = ignore_case_get(port, "networkId")
181     subnet_id = ignore_case_get(port, "subnetId")
182     if not network_id:
183         network_id = get_res_id(res_cache, RES_NETWORK, port["vl_id"])
184         subnet_id = get_res_id(res_cache, RES_SUBNET, port["vl_id"])
185     param = {
186         "networkId": network_id,
187         "name": port["properties"].get("name", "undefined")
188     }
189     set_opt_val(param, "subnetId", subnet_id)
190     set_opt_val(param, "macAddress", ignore_case_get(port["properties"], "mac_address"))
191     set_opt_val(param, "ip", ignore_case_get(port["properties"], "ip_address"))
192     set_opt_val(param, "vnicType", ignore_case_get(port["properties"], "vnic_type"))
193     set_opt_val(param, "securityGroups", "")   # TODO
194     vim_id, tenant_name = location_info["vimid"], location_info["tenant"]
195     tenant_id = get_tenant_id(vim_cache, vim_id, tenant_name)
196     ret = api.create_port(vim_id, tenant_id, param)
197     ret["nodeId"] = port["cp_id"]
198     do_notify(res_type, ret)
199     set_res_cache(res_cache, res_type, port["cp_id"], ret["id"])
200
201
202 def create_flavor(vim_cache, res_cache, data, flavor, do_notify, res_type):
203     location_info = flavor["properties"]["location_info"]
204     local_storages = ignore_case_get(data, "local_storages")
205     param = {
206         "name": "Flavor_%s" % flavor["vdu_id"],
207         "vcpu": int(flavor["nfv_compute"]["num_cpus"]),
208         "memory": int(flavor["nfv_compute"]["mem_size"].replace('GB', '').strip()),
209         "isPublic": True
210     }
211     flavor_extra_specs = ignore_case_get(flavor["nfv_compute"], "flavor_extra_specs")
212     vim_id, tenant_name = location_info["vimid"], location_info["tenant"]
213
214     # search aai flavor
215     find = False
216     aai_flavors = get_flavor_info(vim_id)
217     aai_flavor = aai_flavors["flavors"]["flavor"]
218     for i in range(len(aai_flavor)):
219         for fes in flavor_extra_specs:
220             if (str(aai_flavor[i].find(fes)) != -1):
221                 find = True
222                 break
223         if find:
224             break
225
226     # add aai flavor
227     if find:
228         ret = aai_flavor[i]
229     else:
230         extra_specs = []
231         for local_storage_id in ignore_case_get(flavor, "local_storages"):
232             for local_storage in local_storages:
233                 if local_storage_id != local_storage["local_storage_id"]:
234                     continue
235                 disk_type = local_storage["properties"]["disk_type"]
236                 disk_size = int(local_storage["properties"]["size"].replace('GB', '').strip())
237                 if disk_type == "root":
238                     param["disk"] = disk_size
239                 elif disk_type == "ephemeral":
240                     param["ephemeral"] = disk_size
241                 elif disk_type == "swap":
242                     param["swap"] = disk_size
243
244         for es in flavor_extra_specs:
245             extra_specs.append({"keyName": es, "value": flavor_extra_specs[es]})
246
247         set_opt_val(param, "extraSpecs", extra_specs)
248         tenant_id = get_tenant_id(vim_cache, vim_id, tenant_name)
249         ret = api.create_flavor(vim_id, tenant_id, param)
250
251     do_notify(res_type, ret)
252     set_res_cache(res_cache, res_type, flavor["vdu_id"], ret["id"])
253
254
255 def create_vm(vim_cache, res_cache, data, vm, do_notify, res_type):
256     location_info = vm["properties"]["location_info"]
257     vim_id, tenant_name = location_info["vimid"], location_info["tenant"]
258     tenant_id = get_tenant_id(vim_cache, vim_id, tenant_name)
259     param = {
260         "name": vm["properties"].get("name", "undefined"),
261         "flavorId": get_res_id(res_cache, RES_FLAVOR, vm["vdu_id"]),
262         "boot": {},
263         "nicArray": [],
264         "contextArray": [],
265         "volumeArray": []
266     }
267     # set boot param
268     if "image_file" in vm and vm["image_file"]:
269         param["boot"]["type"] = BOOT_FROM_IMAGE
270         img_name = ""
271         for img in ignore_case_get(data, "image_files"):
272             if vm["image_file"] == img["image_file_id"]:
273                 img_name = img["properties"]["name"]
274                 break
275         if not img_name:
276             raise VimException("Undefined image(%s)" % vm["image_file"], ERR_CODE)
277         images = api.list_image(vim_id, tenant_id)
278         for image in images["images"]:
279             if img_name == image["name"]:
280                 param["boot"]["imageId"] = image["id"]
281                 break
282         if "imageId" not in param["boot"]:
283             raise VimException("Image(%s) not found in Vim(%s)" % (img_name, vim_id), ERR_CODE)
284     elif vm["volume_storages"]:
285         param["boot"]["type"] = BOOT_FROM_VOLUME
286         vol_id = vm["volume_storages"][0]["volume_storage_id"]
287         param["boot"]["volumeId"] = get_res_id(res_cache, RES_VOLUME, vol_id)
288     else:
289         raise VimException("No image and volume defined", ERR_CODE)
290
291     for cp_id in ignore_case_get(vm, "cps"):
292         param["nicArray"].append({
293             "portId": get_res_id(res_cache, RES_PORT, cp_id)
294         })
295     for inject_data in ignore_case_get(vm["properties"], "inject_data_list"):
296         param["contextArray"].append({
297             "fileName": inject_data["file_name"],
298             "fileData": inject_data["file_data"]
299         })
300     for vol_data in ignore_case_get(vm, "volume_storages"):
301         vol_id = vol_data["volume_storage_id"]
302         param["volumeArray"].append({
303             "volumeId": get_res_id(res_cache, RES_VOLUME, vol_id)
304         })
305
306     set_opt_val(param, "availabilityZone", ignore_case_get(location_info, "availability_zone"))
307     set_opt_val(param, "userdata", "")         # TODO Configuration information or scripts to use upon launch
308     set_opt_val(param, "metadata", "")         # TODO [{"keyName": "foo", "value": "foo value"}]
309     set_opt_val(param, "securityGroups", "")   # TODO List of names of security group
310     set_opt_val(param, "serverGroup", "")      # TODO the ServerGroup for anti-affinity and affinity
311
312     ret = api.create_vm(vim_id, tenant_id, param)
313     do_notify(res_type, ret)
314     vm_id = ret["id"]
315     if ignore_case_get(ret, "name"):
316         vm_name = vm["properties"].get("name", "undefined")
317         logger.debug("vm_name:%s" % vm_name)
318     opt_vm_status = "Timeout"
319     retry_count, max_retry_count = 0, 100
320     while retry_count < max_retry_count:
321         vm_info = api.get_vm(vim_id, tenant_id, vm_id)
322         if vm_info["status"].upper() == "ACTIVE":
323             logger.debug("Vm(%s) is active", vim_id)
324             return
325         if vm_info["status"].upper() == "ERROR":
326             opt_vm_status = vm_info["status"]
327             break
328         time.sleep(2)
329         retry_count = retry_count + 1
330     raise VimException("Failed to create Vm(%s): %s." % (vm_name, opt_vm_status), ERR_CODE)