Merge "Add port of SR-IOV NIC support"
[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 ast
18 import json
19
20 from lcm.pub.utils.values import ignore_case_get, set_opt_val
21 from lcm.pub.msapi.aai import get_flavor_info
22 from . import api
23 from .exceptions import VimException
24 from lcm.nf.const import 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                 # TODO check if the we should poll getvm to get the status or the action_vm api
106                 # successful return should suffice to mark vm as Active/Inactive
107                 do_notify_op("INACTIVE", res["id"])
108         except VimException as e:
109             # TODO Have to update database appropriately on failure
110             logger.error("Failed to Heal %s(%s)", RES_VM, res["res_id"])
111             logger.error("%s:%s", e.http_code, e.message)
112
113
114 def create_vim_res(data, do_notify):
115     vim_cache, res_cache = {}, {}
116     for vol in ignore_case_get(data, "volume_storages"):
117         create_volume(vim_cache, res_cache, vol, do_notify, RES_VOLUME)
118     for network in ignore_case_get(data, "vls"):
119         create_network(vim_cache, res_cache, network, do_notify, RES_NETWORK)
120     for subnet in ignore_case_get(data, "vls"):
121         create_subnet(vim_cache, res_cache, subnet, do_notify, RES_SUBNET)
122     for port in ignore_case_get(data, "cps"):
123         create_port(vim_cache, res_cache, data, port, do_notify, RES_PORT)
124     for vdu in ignore_case_get(data, "vdus"):
125         if vdu["type"] == "tosca.nodes.nfv.Vdu.Compute":
126             create_flavor(vim_cache, res_cache, data, vdu, do_notify, RES_FLAVOR)
127     for vdu in ignore_case_get(data, "vdus"):
128         if vdu["type"] == "tosca.nodes.nfv.Vdu.Compute":
129             create_vm(vim_cache, res_cache, data, vdu, do_notify, RES_VM)
130
131
132 def delete_vim_res(data, do_notify):
133     res_types = [RES_VM, RES_FLAVOR, RES_PORT, RES_SUBNET, RES_NETWORK, RES_VOLUME]
134     res_del_funs = [api.delete_vm, api.delete_flavor, api.delete_port,
135                     api.delete_subnet, api.delete_network, api.delete_volume]
136     for res_type, res_del_fun in zip(res_types, res_del_funs):
137         for res in ignore_case_get(data, res_type):
138             try:
139                 if NOT_PREDEFINED == res["is_predefined"]:
140                     res_del_fun(res["vim_id"], res["tenant_id"], res["res_id"])
141             except VimException as e:
142                 logger.error("Failed to delete %s(%s)", res_type, res["res_id"])
143                 logger.error("%s:%s", e.http_code, e.message)
144             do_notify(res_type, res["res_id"])
145
146
147 def create_volume(vim_cache, res_cache, vol, do_notify, res_type):
148     location_info = vol["properties"]["location_info"]
149     param = {
150         "name": vol["properties"]["volume_name"],
151         "volumeSize": int(ignore_case_get(vol["properties"], "size", "0").replace('GB', '').strip())
152     }
153     set_opt_val(param, "imageName", ignore_case_get(vol, "image_file"))
154     set_opt_val(param, "volumeType", ignore_case_get(vol["properties"], "custom_volume_type"))
155     set_opt_val(param, "availabilityZone", ignore_case_get(location_info, "availability_zone"))
156     vim_id, tenant_name = location_info["vimid"], location_info["tenant"]
157     tenant_id = get_tenant_id(vim_cache, vim_id, tenant_name)
158     ret = api.create_volume(vim_id, tenant_id, param)
159     ret["nodeId"] = vol["volume_storage_id"]
160     do_notify(res_type, ret)
161     vol_id, vol_name = ret["id"], ret["name"]
162     set_res_cache(res_cache, res_type, vol["volume_storage_id"], vol_id)
163     retry_count, max_retry_count = 0, 300
164     while retry_count < max_retry_count:
165         vol_info = api.get_volume(vim_id, tenant_id, vol_id)
166         if vol_info["status"].upper() == "AVAILABLE":
167             logger.debug("Volume(%s) is available", vol_id)
168             return
169         time.sleep(2)
170         retry_count = retry_count + 1
171     raise VimException("Failed to create Volume(%s): Timeout." % vol_name, ERR_CODE)
172
173
174 def create_network(vim_cache, res_cache, network, do_notify, res_type):
175     location_info = network["properties"]["location_info"]
176     vl_profile = network["properties"]["vl_profile"]
177     param = {
178         "name": vl_profile["networkName"],
179         "shared": False,
180         "networkType": vl_profile["networkType"],
181         "physicalNetwork": ignore_case_get(vl_profile, "physicalNetwork")
182     }
183     set_opt_val(param, "vlanTransparent", ignore_case_get(vl_profile, "vlanTransparent"))
184     set_opt_val(param, "segmentationId", int(ignore_case_get(vl_profile, "segmentationId", "0")))
185     set_opt_val(param, "routerExternal", ignore_case_get(network, "route_external"))
186     vim_id, tenant_name = location_info["vimid"], location_info["tenant"]
187     tenant_id = get_tenant_id(vim_cache, vim_id, tenant_name)
188     ret = api.create_network(vim_id, tenant_id, param)
189     ret["nodeId"] = network["vl_id"]
190     do_notify(res_type, ret)
191     set_res_cache(res_cache, res_type, network["vl_id"], ret["id"])
192
193
194 def create_subnet(vim_cache, res_cache, subnet, do_notify, res_type):
195     location_info = subnet["properties"]["location_info"]
196     network_id = get_res_id(res_cache, RES_NETWORK, subnet["vl_id"])
197     vl_profile = subnet["properties"]["vl_profile"]
198     layer_protocol = ignore_case_get(subnet["properties"]["connectivity_type"], "layer_protocol")
199     param = {
200         "networkId": network_id,
201         "name": vl_profile["networkName"] + "_subnet",
202         "cidr": ignore_case_get(vl_profile, "cidr"),
203         "ipVersion": IP_V4 if(layer_protocol == 'ipv4') else (IP_V6 if(layer_protocol == 'ipv6') else None)
204     }
205     set_opt_val(param, "enableDhcp", ignore_case_get(vl_profile, "dhcpEnabled"))
206     set_opt_val(param, "gatewayIp", ignore_case_get(vl_profile, "gatewayIp"))
207     set_opt_val(param, "dnsNameservers", ignore_case_get(subnet["properties"], "dns_nameservers"))
208     allocation_pool = {}
209     set_opt_val(allocation_pool, "start", ignore_case_get(vl_profile, "startIp"))
210     set_opt_val(allocation_pool, "end", ignore_case_get(vl_profile, "endIp"))
211     if allocation_pool:
212         param["allocationPools"] = [allocation_pool]
213     set_opt_val(param, "hostRoutes", ignore_case_get(subnet["properties"], "host_routes"))
214     vim_id, tenant_name = location_info["vimid"], location_info["tenant"]
215     tenant_id = get_tenant_id(vim_cache, vim_id, tenant_name)
216     ret = api.create_subnet(vim_id, tenant_id, param)
217     do_notify(res_type, ret)
218     set_res_cache(res_cache, res_type, subnet["vl_id"], ret["id"])
219
220
221 def create_port(vim_cache, res_cache, data, port, do_notify, res_type):
222     location_info = None
223     port_ref_vdu_id = ignore_case_get(port, "vdu_id")
224     for vdu in ignore_case_get(data, "vdus"):
225         if vdu["vdu_id"] == port_ref_vdu_id:
226             location_info = vdu["properties"]["location_info"]
227             if port["cp_id"] not in vdu["cps"]:
228                 vdu["cps"].append(port["cp_id"])
229             break
230     if not location_info:
231         err_msg = "vdu_id(%s) for cp(%s) is not defined."
232         raise VimException(err_msg % (port_ref_vdu_id, port["cp_id"]), ERR_CODE)
233     network_id = ignore_case_get(port, "networkId")
234     subnet_id = ignore_case_get(port, "subnetId")
235     if not network_id:
236         network_id = get_res_id(res_cache, RES_NETWORK, port["vl_id"])
237         subnet_id = get_res_id(res_cache, RES_SUBNET, port["vl_id"])
238     param = {
239         "networkId": network_id,
240         "name": port["properties"].get("name", "undefined")
241     }
242     set_opt_val(param, "subnetId", subnet_id)
243     set_opt_val(param, "macAddress", ignore_case_get(port["properties"], "mac_address"))
244     ip_address = []
245     for one_protocol_data in port["properties"]["protocol_data"]:
246         l3_address_data = one_protocol_data["address_data"]["l3_address_data"]  # l3 is not 13
247         fixed_ip_address = ignore_case_get(l3_address_data, "fixed_ip_address")
248         ip_address.extend(fixed_ip_address)
249     for one_virtual_network_interface in port["properties"]["virtual_network_interface_requirements"]:
250         interfaceTypeString = one_virtual_network_interface["network_interface_requirements"]["interfaceType"]
251         interfaceType = json.loads(interfaceTypeString)["configuration-value"]
252         vnic_type = ignore_case_get(port["properties"], "vnic_type")
253         if vnic_type == "":
254             if interfaceType == "SR-IOV":
255                 set_opt_val(param, "vnicType", "direct")
256         else:
257             set_opt_val(param, "vnicType", vnic_type)
258
259     set_opt_val(param, "ip", ",".join(ip_address))
260     set_opt_val(param, "securityGroups", "")   # TODO
261     vim_id, tenant_name = location_info["vimid"], location_info["tenant"]
262     tenant_id = get_tenant_id(vim_cache, vim_id, tenant_name)
263     ret = api.create_port(vim_id, tenant_id, param)
264     ret["nodeId"] = port["cp_id"]
265     do_notify(res_type, ret)
266     set_res_cache(res_cache, res_type, port["cp_id"], ret["id"])
267
268
269 def parse_unit(val, base_unit):
270     recognized_units = ["B", "kB", "KiB", "MB", "MiB", "GB", "GiB", "TB", "TiB"]
271     units_rate = [1, 1000, 1024, 1000000, 1048576, 1000000000, 1073741824, 1000000000000, 1099511627776]
272     unit_rate_map = {unit.upper(): rate for unit, rate in zip(recognized_units, units_rate)}
273     num_unit = val.strip().split(" ")
274     if len(num_unit) != 2:
275         return val.strip
276     num, unit = num_unit[0], num_unit[1]
277     return int(num) * unit_rate_map[unit.upper()] / unit_rate_map[base_unit.upper()]
278
279
280 def search_flavor_aai(vim_id, memory_page_size, memory_page_unit):
281     aai_flavors = get_flavor_info(vim_id)
282     if not aai_flavors:
283         return None
284     logger.debug("aai_flavors:%s" % aai_flavors)
285     aai_flavor = aai_flavors["flavor"]
286     for one_aai_flavor in aai_flavor:
287         if one_aai_flavor["flavor-name"].find("onap.") == -1:
288             continue
289         hpa_capabilities = one_aai_flavor["hpa-capabilities"]["hpa-capability"]
290         logger.debug("hpa_capabilities=%s", hpa_capabilities)
291         for one_hpa_capa in hpa_capabilities:
292             logger.debug("one_hpa_capa=%s", one_hpa_capa)
293             hpa_feature_attr = one_hpa_capa["hpa-feature-attributes"]
294             for one_hpa_attr in hpa_feature_attr:
295                 hpa_key = one_hpa_attr["hpa-attribute-key"]
296                 hpa_attr_value = ast.literal_eval(one_hpa_attr["hpa-attribute-value"])
297                 mem_size = ignore_case_get(hpa_attr_value, 'value')
298                 mem_unit = ignore_case_get(hpa_attr_value, 'unit')
299                 value = mem_size + " " + mem_unit
300                 hpa_mem_size = parse_unit(value, memory_page_unit)
301                 if hpa_key == "memoryPageSize" and hpa_mem_size == memory_page_size:
302                     return one_aai_flavor
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     # just do memory huge page
320     flavor_extra_specs = ""
321     vdu_memory_requirements = ignore_case_get(virtual_memory, "vdu_memory_requirements")
322     if "memoryPageSize" in vdu_memory_requirements:
323         memory_page_size = int(vdu_memory_requirements["memoryPageSize"].replace('MB', '').strip())
324         flavor_extra_specs = {"hw": memory_page_size, }  # TODO
325         logger.debug("flavor_extra_specs:%s" % flavor_extra_specs)
326
327     # FIXME: search aai flavor
328     aai_flavor = search_flavor_aai(vim_id, memory_page_size, "MB")
329
330     # add aai flavor
331     if aai_flavor:
332         ret = aai_flavor
333         do_notify(res_type, ret)
334         set_res_cache(res_cache, res_type, flavor["vdu_id"], ret["flavor-id"])
335     else:
336         extra_specs = []
337         disk_type = ignore_case_get(virtual_storage, "type_of_storage")
338         disk_size = int(ignore_case_get(virtual_storage, "size_of_storage").replace('GB', '').strip())
339         if disk_type == "root":
340             param["disk"] = disk_size
341         elif disk_type == "ephemeral":
342             param["ephemeral"] = disk_size
343         elif disk_type == "swap":
344             param["swap"] = disk_size
345
346         for es in flavor_extra_specs:
347             extra_specs.append({"keyName": es, "value": flavor_extra_specs[es]})
348
349         set_opt_val(param, "extraSpecs", extra_specs)
350         tenant_id = get_tenant_id(vim_cache, vim_id, tenant_name)
351         logger.debug("param:%s" % param)
352         ret = api.create_flavor(vim_id, tenant_id, param)
353         do_notify(res_type, ret)
354         set_res_cache(res_cache, res_type, flavor["vdu_id"], ret["id"])
355
356
357 def create_vm(vim_cache, res_cache, data, vm, do_notify, res_type):
358     location_info = vm["properties"]["location_info"]
359     vim_id, tenant_name = location_info["vimid"], location_info["tenant"]
360     tenant_id = get_tenant_id(vim_cache, vim_id, tenant_name)
361     param = {
362         "name": vm["properties"].get("name", "undefined"),
363         "flavorId": get_res_id(res_cache, RES_FLAVOR, vm["vdu_id"]),
364         "boot": {},
365         "nicArray": [],
366         "contextArray": [],
367         "volumeArray": []
368     }
369     # set boot param
370     if "artifacts" in vm and vm["artifacts"]:
371         param["boot"]["type"] = BOOT_FROM_IMAGE
372         img_name = ""
373         for artifact in vm["artifacts"]:
374             if artifact["artifact_name"] == "sw_image":
375                 # TODO: after DM define
376                 img_name = artifact["file"]
377                 break
378         if not img_name:
379             raise VimException("Undefined image(%s)" % vm["artifacts"], ERR_CODE)
380         images = api.list_image(vim_id, tenant_id)
381         for image in images["images"]:
382             if img_name == image["name"]:
383                 param["boot"]["imageId"] = image["id"]
384                 break
385         if "imageId" not in param["boot"]:
386             raise VimException("Undefined artifacts image(%s)" % vm["artifacts"], ERR_CODE)
387     elif vm["volume_storages"]:
388         param["boot"]["type"] = BOOT_FROM_VOLUME
389         vol_id = vm["volume_storages"][0]["volume_storage_id"]
390         param["boot"]["volumeId"] = get_res_id(res_cache, RES_VOLUME, vol_id)
391     else:
392         raise VimException("No image and volume defined", ERR_CODE)
393
394     for cp_id in ignore_case_get(vm, "cps"):
395         param["nicArray"].append({
396             "portId": get_res_id(res_cache, RES_PORT, cp_id)
397         })
398     param["contextArray"] = ignore_case_get(vm["properties"], "inject_files")
399     logger.debug("contextArray:%s", param["contextArray"])
400     for vol_data in ignore_case_get(vm, "volume_storages"):
401         vol_id = vol_data["volume_storage_id"]
402         param["volumeArray"].append({
403             "volumeId": get_res_id(res_cache, RES_VOLUME, vol_id)
404         })
405
406     set_opt_val(param, "availabilityZone", ignore_case_get(location_info, "availability_zone"))
407     set_opt_val(param, "userdata", ignore_case_get(vm["properties"], "user_data"))
408     set_opt_val(param, "metadata", ignore_case_get(vm["properties"], "meta_data"))
409     set_opt_val(param, "securityGroups", "")   # TODO List of names of security group
410     set_opt_val(param, "serverGroup", "")      # TODO the ServerGroup for anti-affinity and affinity
411
412     ret = api.create_vm(vim_id, tenant_id, param)
413     do_notify(res_type, ret)
414     vm_id = ret["id"]
415     if ignore_case_get(ret, "name"):
416         vm_name = vm["properties"].get("name", "undefined")
417         logger.debug("vm_name:%s" % vm_name)
418     opt_vm_status = "Timeout"
419     retry_count, max_retry_count = 0, 100
420     while retry_count < max_retry_count:
421         vm_info = api.get_vm(vim_id, tenant_id, vm_id)
422         if vm_info["status"].upper() == "ACTIVE":
423             logger.debug("Vm(%s) is active", vim_id)
424             return
425         if vm_info["status"].upper() == "ERROR":
426             opt_vm_status = vm_info["status"]
427             break
428         time.sleep(2)
429         retry_count = retry_count + 1
430     raise VimException("Failed to create Vm(%s): %s." % (vm_name, opt_vm_status), ERR_CODE)