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