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