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