3427aaf4d5e1236fa722248aa033e1bf5bb6eb9e
[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 import json
18
19 from lcm.pub.utils.values import ignore_case_get, set_opt_val
20 from lcm.pub.msapi.aai import get_flavor_info
21 from . import api
22 from .exceptions import VimException
23 from lcm.pub.exceptions import NFLCMException
24 from lcm.nf.const import ACTION_TYPE, HEAL_ACTION_TYPE
25
26 logger = logging.getLogger(__name__)
27
28 ERR_CODE = "500"
29 RES_EXIST, RES_NEW = 0, 1
30 IP_V4, IP_V6 = 4, 6
31 BOOT_FROM_VOLUME, BOOT_FROM_IMAGE = 1, 2
32
33 RES_VOLUME = "volume"
34 RES_NETWORK = "network"
35 RES_SUBNET = "subnet"
36 RES_PORT = "port"
37 RES_FLAVOR = "flavor"
38 RES_VM = "vm"
39 NOT_PREDEFINED = 1
40
41
42 def get_tenant_id(vim_cache, vim_id, tenant_name):
43     if vim_id not in vim_cache:
44         tenants = api.list_tenant(vim_id)
45         vim_cache[vim_id] = {}
46         for tenant in tenants["tenants"]:
47             id, name = tenant["id"], tenant["name"]
48             vim_cache[vim_id][name] = id
49     if tenant_name not in vim_cache[vim_id]:
50         raise VimException("Tenant(%s) not found in vim(%s)" % (tenant_name, vim_id), ERR_CODE)
51     return vim_cache[vim_id][tenant_name]
52
53
54 def set_res_cache(res_cache, res_type, key, val):
55     if res_type not in res_cache:
56         res_cache[res_type] = {}
57     if key in res_cache[res_type]:
58         raise VimException("Duplicate key(%s) of %s" % (key, res_type), ERR_CODE)
59     res_cache[res_type][key] = val
60
61
62 def get_res_id(res_cache, res_type, key):
63     if res_type not in res_cache:
64         raise VimException("%s not found in cache" % res_type, ERR_CODE)
65     if key not in res_cache[res_type]:
66         raise VimException("%s(%s) not found in cache" % (res_type, key), ERR_CODE)
67     return res_cache[res_type][key]
68
69
70 def action_vm(action_type, server, vimId, tenantId):
71     param = {}
72     if action_type == ACTION_TYPE.START:
73         param = {
74             "os-start": None,
75         }
76     elif action_type == ACTION_TYPE.STOP:
77         param = {
78             "os-stop": None,
79         }
80     elif action_type == ACTION_TYPE.REBOOT:
81         param = {
82             "reboot": {}
83         }
84         if server["status"] == "ACTIVE":
85             param["reboot"]["type"] = "SOFT"
86         else:
87             param["reboot"]["type"] = "HARD"
88     res_id = server["id"]
89     api.action_vm(vimId, tenantId, res_id, param)
90
91
92 # TODO Have to check if the resources should be started and stopped in some order.
93 def operate_vim_res(data, changeStateTo, stopType, gracefulStopTimeout, do_notify_op):
94     for res in ignore_case_get(data, "vm"):
95         try:
96             if changeStateTo == "STARTED":
97                 action_vm(ACTION_TYPE.START, res, res["vim_id"], res["tenant_id"])
98                 do_notify_op("ACTIVE", res["id"])
99             elif changeStateTo == "STOPPED":
100                 if stopType == "GRACEFUL":
101                     if gracefulStopTimeout > 60:
102                         gracefulStopTimeout = 60
103                     time.sleep(gracefulStopTimeout)
104                 action_vm(ACTION_TYPE.STOP, res, res["vim_id"], res["tenant_id"])
105                 do_notify_op("INACTIVE", res["id"])
106         except VimException as e:
107             logger.error("Failed to Operate %s(%s)", RES_VM, res["res_id"])
108             logger.error("%s:%s", e.http_code, e.message)
109             raise NFLCMException("Failed to Operate %s(%s)", RES_VM, res["res_id"])
110
111
112 def heal_vim_res(vdus, vnfd_info, do_notify, data, vim_cache, res_cache):
113     try:
114         vimid = data["vimid"]
115         tenant = data["tenant"]
116         actionType = data["action"]
117         if actionType == HEAL_ACTION_TYPE.START:
118             create_vm(vim_cache, res_cache, vnfd_info, vdus[0], do_notify, RES_VM)
119         elif actionType == HEAL_ACTION_TYPE.RESTART:
120             vm_info = api.get_vm(vimid, tenant, vdus[0].resourceid)
121             action_vm(ACTION_TYPE.REBOOT, vm_info, vimid, tenant)
122     except VimException as e:
123         logger.error("Failed to Heal %s(%s)", RES_VM, vdus[0]["vdu_id"])
124         logger.error("%s:%s", e.http_code, e.message)
125         raise NFLCMException("Failed to Heal %s(%s)", RES_VM, vdus[0]["vdu_id"])
126
127
128 def create_vim_res(data, do_notify, vim_cache={}, res_cache={}):
129     for vol in ignore_case_get(data, "volume_storages"):
130         create_volume(vim_cache, res_cache, vol, do_notify, RES_VOLUME)
131     for network in ignore_case_get(data, "vls"):
132         create_network(vim_cache, res_cache, network, do_notify, RES_NETWORK)
133     for subnet in ignore_case_get(data, "vls"):
134         create_subnet(vim_cache, res_cache, subnet, do_notify, RES_SUBNET)
135     for port in ignore_case_get(data, "cps"):
136         create_port(vim_cache, res_cache, data, port, do_notify, RES_PORT)
137     for vdu in ignore_case_get(data, "vdus"):
138         if vdu["type"] == "tosca.nodes.nfv.Vdu.Compute":
139             create_flavor(vim_cache, res_cache, data, vdu, do_notify, RES_FLAVOR)
140     for vdu in ignore_case_get(data, "vdus"):
141         if vdu["type"] == "tosca.nodes.nfv.Vdu.Compute":
142             create_vm(vim_cache, res_cache, data, vdu, do_notify, RES_VM)
143
144
145 def delete_vim_res(data, do_notify):
146     res_types = [RES_VM, RES_FLAVOR, RES_PORT, RES_SUBNET, RES_NETWORK, RES_VOLUME]
147     res_del_funs = [api.delete_vm, api.delete_flavor, api.delete_port,
148                     api.delete_subnet, api.delete_network, api.delete_volume]
149     for res_type, res_del_fun in zip(res_types, res_del_funs):
150         for res in ignore_case_get(data, res_type):
151             try:
152                 if NOT_PREDEFINED == res["is_predefined"]:
153                     res_del_fun(res["vim_id"], res["tenant_id"], res["res_id"])
154             except VimException as e:
155                 logger.error("Failed to delete %s(%s)", res_type, res["res_id"])
156                 logger.error("%s:%s", e.http_code, e.message)
157             do_notify(res_type, res["res_id"])
158
159
160 def create_volume(vim_cache, res_cache, vol, do_notify, res_type):
161     location_info = vol["properties"]["location_info"]
162     param = {
163         "name": vol["properties"]["volume_name"],
164         "volumeSize": int(ignore_case_get(vol["properties"], "size", "0").replace('GB', '').strip())
165     }
166     set_opt_val(param, "imageName", ignore_case_get(vol, "image_file"))
167     set_opt_val(param, "volumeType", ignore_case_get(vol["properties"], "custom_volume_type"))
168     set_opt_val(param, "availabilityZone", ignore_case_get(location_info, "availability_zone"))
169     vim_id, tenant_name = location_info["vimid"], location_info["tenant"]
170     tenant_id = get_tenant_id(vim_cache, vim_id, tenant_name)
171     ret = api.create_volume(vim_id, tenant_id, param)
172     ret["nodeId"] = vol["volume_storage_id"]
173     do_notify(res_type, ret)
174     vol_id, vol_name = ret["id"], ret["name"]
175     set_res_cache(res_cache, res_type, vol["volume_storage_id"], vol_id)
176     retry_count, max_retry_count = 0, 300
177     while retry_count < max_retry_count:
178         vol_info = api.get_volume(vim_id, tenant_id, vol_id)
179         if vol_info["status"].upper() == "AVAILABLE":
180             logger.debug("Volume(%s) is available", vol_id)
181             return
182         time.sleep(2)
183         retry_count = retry_count + 1
184     raise VimException("Failed to create Volume(%s): Timeout." % vol_name, ERR_CODE)
185
186
187 def create_network(vim_cache, res_cache, network, do_notify, res_type):
188     location_info = network["properties"]["location_info"]
189     vl_profile = network["properties"]["vl_profile"]
190     param = {
191         "name": vl_profile["networkName"],
192         "shared": False,
193         "networkType": vl_profile["networkType"],
194         "physicalNetwork": ignore_case_get(vl_profile, "physicalNetwork")
195     }
196     set_opt_val(param, "vlanTransparent", ignore_case_get(vl_profile, "vlanTransparent"))
197     set_opt_val(param, "segmentationId", int(ignore_case_get(vl_profile, "segmentationId", "0")))
198     set_opt_val(param, "routerExternal", ignore_case_get(network, "route_external"))
199     vim_id, tenant_name = location_info["vimid"], location_info["tenant"]
200     tenant_id = get_tenant_id(vim_cache, vim_id, tenant_name)
201     ret = api.create_network(vim_id, tenant_id, param)
202     ret["nodeId"] = network["vl_id"]
203     do_notify(res_type, ret)
204     set_res_cache(res_cache, res_type, network["vl_id"], ret["id"])
205
206
207 def create_subnet(vim_cache, res_cache, subnet, do_notify, res_type):
208     location_info = subnet["properties"]["location_info"]
209     network_id = get_res_id(res_cache, RES_NETWORK, subnet["vl_id"])
210     vl_profile = subnet["properties"]["vl_profile"]
211     layer_protocol = ignore_case_get(subnet["properties"]["connectivity_type"], "layer_protocol")
212     param = {
213         "networkId": network_id,
214         "name": vl_profile["networkName"] + "_subnet",
215         "cidr": ignore_case_get(vl_profile, "cidr"),
216         "ipVersion": IP_V4 if(layer_protocol == 'ipv4') else (IP_V6 if(layer_protocol == 'ipv6') else None)
217     }
218     set_opt_val(param, "enableDhcp", ignore_case_get(vl_profile, "dhcpEnabled"))
219     set_opt_val(param, "gatewayIp", ignore_case_get(vl_profile, "gatewayIp"))
220     set_opt_val(param, "dnsNameservers", ignore_case_get(subnet["properties"], "dns_nameservers"))
221     allocation_pool = {}
222     set_opt_val(allocation_pool, "start", ignore_case_get(vl_profile, "startIp"))
223     set_opt_val(allocation_pool, "end", ignore_case_get(vl_profile, "endIp"))
224     if allocation_pool:
225         param["allocationPools"] = [allocation_pool]
226     set_opt_val(param, "hostRoutes", ignore_case_get(subnet["properties"], "host_routes"))
227     vim_id, tenant_name = location_info["vimid"], location_info["tenant"]
228     tenant_id = get_tenant_id(vim_cache, vim_id, tenant_name)
229     ret = api.create_subnet(vim_id, tenant_id, param)
230     do_notify(res_type, ret)
231     set_res_cache(res_cache, res_type, subnet["vl_id"], ret["id"])
232
233
234 def create_port(vim_cache, res_cache, data, port, do_notify, res_type):
235     location_info = None
236     port_ref_vdu_id = ignore_case_get(port, "vdu_id")
237     for vdu in ignore_case_get(data, "vdus"):
238         if vdu["vdu_id"] == port_ref_vdu_id:
239             location_info = vdu["properties"]["location_info"]
240             if port["cp_id"] not in vdu["cps"]:
241                 vdu["cps"].append(port["cp_id"])
242             break
243     if not location_info:
244         err_msg = "vdu_id(%s) for cp(%s) is not defined."
245         raise VimException(err_msg % (port_ref_vdu_id, port["cp_id"]), ERR_CODE)
246     network_id = ignore_case_get(port, "networkId")
247     subnet_id = ignore_case_get(port, "subnetId")
248     if not network_id:
249         network_id = get_res_id(res_cache, RES_NETWORK, port["vl_id"])
250         subnet_id = get_res_id(res_cache, RES_SUBNET, port["vl_id"])
251     param = {
252         "networkId": network_id,
253         "name": port["properties"].get("name", "undefined")
254     }
255     set_opt_val(param, "subnetId", subnet_id)
256     set_opt_val(param, "macAddress", ignore_case_get(port["properties"], "mac_address"))
257     ip_address = []
258     for one_protocol_data in port["properties"]["protocol_data"]:
259         l3_address_data = one_protocol_data["address_data"]["l3_address_data"]  # l3 is not 13
260         fixed_ip_address = ignore_case_get(l3_address_data, "fixed_ip_address")
261         ip_address.extend(fixed_ip_address)
262     for one_virtual_network_interface in port["properties"]["virtual_network_interface_requirements"]:
263         interfaceTypeString = one_virtual_network_interface["network_interface_requirements"]["interfaceType"]
264         interfaceType = json.loads(interfaceTypeString)["configuration-value"]
265         vnic_type = ignore_case_get(port["properties"], "vnic_type")
266         if vnic_type == "":
267             if interfaceType == "SR-IOV":
268                 set_opt_val(param, "vnicType", "direct")
269         else:
270             set_opt_val(param, "vnicType", vnic_type)
271
272     set_opt_val(param, "ip", ",".join(ip_address))
273     set_opt_val(param, "securityGroups", "")   # TODO
274     vim_id, tenant_name = location_info["vimid"], location_info["tenant"]
275     tenant_id = get_tenant_id(vim_cache, vim_id, tenant_name)
276     ret = api.create_port(vim_id, tenant_id, param)
277     ret["nodeId"] = port["cp_id"]
278     do_notify(res_type, ret)
279     set_res_cache(res_cache, res_type, port["cp_id"], ret["id"])
280
281
282 def parse_unit(val, base_unit):
283     recognized_units = ["B", "kB", "KiB", "MB", "MiB", "GB", "GiB", "TB", "TiB"]
284     units_rate = [1, 1000, 1024, 1000000, 1048576, 1000000000, 1073741824, 1000000000000, 1099511627776]
285     unit_rate_map = {unit.upper(): rate for unit, rate in zip(recognized_units, units_rate)}
286     num_unit = val.strip().split(" ")
287     if len(num_unit) != 2:
288         return val.strip
289     num, unit = num_unit[0], num_unit[1]
290     return int(num) * unit_rate_map[unit.upper()] / unit_rate_map[base_unit.upper()]
291
292
293 def search_flavor_aai(vim_id, flavor_name):
294     aai_flavors = get_flavor_info(vim_id)
295     if not aai_flavors:
296         return None
297     aai_flavor = aai_flavors["flavor"]
298     for one_aai_flavor in aai_flavor:
299         if one_aai_flavor["flavor-name"].find(flavor_name) == -1:
300             return one_aai_flavor
301
302     return None
303
304
305 def create_flavor(vim_cache, res_cache, data, flavor, do_notify, res_type):
306     location_info = flavor["properties"]["location_info"]
307     vim_id, tenant_name = location_info["vimid"], location_info["tenant"]
308     virtual_compute = flavor["virtual_compute"]
309     virtual_storage = flavor["virtual_storage"]
310     virtual_cpu = ignore_case_get(virtual_compute, "virtual_cpu")
311     virtual_memory = ignore_case_get(virtual_compute, "virtual_memory")
312     param = {
313         "name": "Flavor_%s" % flavor["vdu_id"],
314         "vcpu": int(ignore_case_get(virtual_cpu, "num_virtual_cpu")),
315         "memory": int(ignore_case_get(virtual_memory, "virtual_mem_size").replace('MB', '').strip()),
316         "isPublic": True
317     }
318
319     # Using flavor name returned by OOF to search falvor
320     vdu_id = ignore_case_get(flavor, "vdu_id")
321     for one_vdu in location_info["vduInfo"]:
322         if one_vdu["vduName"] == vdu_id:
323             break
324     aai_flavor = search_flavor_aai(vim_id, one_vdu["flavorName"])
325
326     # Add aai flavor
327     if aai_flavor:
328         ret = aai_flavor
329         do_notify(res_type, ret)
330         set_res_cache(res_cache, res_type, flavor["vdu_id"], ret["flavor-id"])
331     else:
332         disk_type = ignore_case_get(virtual_storage, "type_of_storage")
333         disk_size = int(ignore_case_get(virtual_storage, "size_of_storage").replace('GB', '').strip())
334         if disk_type == "root":
335             param["disk"] = disk_size
336         elif disk_type == "ephemeral":
337             param["ephemeral"] = disk_size
338         elif disk_type == "swap":
339             param["swap"] = disk_size
340
341         tenant_id = get_tenant_id(vim_cache, vim_id, tenant_name)
342         logger.debug("param:%s" % param)
343         ret = api.create_flavor(vim_id, tenant_id, param)
344         logger.debug("hhb ret:%s" % ret)
345         do_notify(res_type, ret)
346         set_res_cache(res_cache, res_type, flavor["vdu_id"], ret["id"])
347
348
349 def create_vm(vim_cache, res_cache, data, vm, do_notify, res_type):
350     location_info = vm["properties"]["location_info"]
351     vim_id, tenant_name = location_info["vimid"], location_info["tenant"]
352     tenant_id = get_tenant_id(vim_cache, vim_id, tenant_name)
353     param = {
354         "name": vm["properties"].get("name", "undefined"),
355         "flavorId": get_res_id(res_cache, RES_FLAVOR, vm["vdu_id"]),
356         "boot": {},
357         "nicArray": [],
358         "contextArray": [],
359         "volumeArray": []
360     }
361     # set boot param
362     if "artifacts" in vm and vm["artifacts"]:
363         param["boot"]["type"] = BOOT_FROM_IMAGE
364         img_name = ""
365         for artifact in vm["artifacts"]:
366             if artifact["artifact_name"] == "sw_image":
367                 # TODO: after DM define
368                 img_name = artifact["file"]
369                 break
370         if not img_name:
371             raise VimException("Undefined image(%s)" % vm["artifacts"], ERR_CODE)
372         images = api.list_image(vim_id, tenant_id)
373         for image in images["images"]:
374             if img_name == image["name"]:
375                 param["boot"]["imageId"] = image["id"]
376                 break
377         if "imageId" not in param["boot"]:
378             raise VimException("Undefined artifacts image(%s)" % vm["artifacts"], ERR_CODE)
379     elif vm["volume_storages"]:
380         param["boot"]["type"] = BOOT_FROM_VOLUME
381         vol_id = vm["volume_storages"][0]["volume_storage_id"]
382         param["boot"]["volumeId"] = get_res_id(res_cache, RES_VOLUME, vol_id)
383     else:
384         raise VimException("No image and volume defined", ERR_CODE)
385
386     for cp_id in ignore_case_get(vm, "cps"):
387         param["nicArray"].append({
388             "portId": get_res_id(res_cache, RES_PORT, cp_id)
389         })
390     param["contextArray"] = ignore_case_get(vm["properties"], "inject_files")
391     logger.debug("contextArray:%s", param["contextArray"])
392     for vol_data in ignore_case_get(vm, "volume_storages"):
393         vol_id = vol_data["volume_storage_id"]
394         param["volumeArray"].append({
395             "volumeId": get_res_id(res_cache, RES_VOLUME, vol_id)
396         })
397
398     set_opt_val(param, "availabilityZone", ignore_case_get(location_info, "availability_zone"))
399     set_opt_val(param, "userdata", ignore_case_get(vm["properties"], "user_data"))
400     set_opt_val(param, "metadata", ignore_case_get(vm["properties"], "meta_data"))
401     set_opt_val(param, "securityGroups", "")   # TODO List of names of security group
402     set_opt_val(param, "serverGroup", "")      # TODO the ServerGroup for anti-affinity and affinity
403
404     ret = api.create_vm(vim_id, tenant_id, param)
405     do_notify(res_type, ret)
406     vm_id = ret["id"]
407     if ignore_case_get(ret, "name"):
408         vm_name = vm["properties"].get("name", "undefined")
409         logger.debug("vm_name:%s" % vm_name)
410     opt_vm_status = "Timeout"
411     retry_count, max_retry_count = 0, 100
412     while retry_count < max_retry_count:
413         vm_info = api.get_vm(vim_id, tenant_id, vm_id)
414         if vm_info["status"].upper() == "ACTIVE":
415             logger.debug("Vm(%s) is active", vim_id)
416             return
417         if vm_info["status"].upper() == "ERROR":
418             opt_vm_status = vm_info["status"]
419             break
420         time.sleep(2)
421         retry_count = retry_count + 1
422     raise VimException("Failed to create Vm(%s): %s." % (vm_name, opt_vm_status), ERR_CODE)