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 api.action_vm(vimId, tenantId, res_id, param)
94 # TODO Have to check if the resources should be started and stopped in some order.
95 def operate_vim_res(data, changeStateTo, stopType, gracefulStopTimeout, do_notify_op):
96 for res in ignore_case_get(data, "vm"):
98 if changeStateTo == "STARTED":
99 action_vm(ACTION_TYPE.START, res, res["vim_id"], res["tenant_id"])
100 do_notify_op("ACTIVE", res["id"])
101 elif changeStateTo == "STOPPED":
102 if stopType == "GRACEFUL":
103 if gracefulStopTimeout > 60:
104 gracefulStopTimeout = 60
105 time.sleep(gracefulStopTimeout)
106 action_vm(ACTION_TYPE.STOP, res, res["vim_id"], res["tenant_id"])
107 do_notify_op("INACTIVE", res["id"])
108 except VimException as e:
109 logger.error("Failed to Operate %s(%s)", RES_VM, res["res_id"])
110 logger.error("%s:%s", e.http_code, e.message)
111 raise NFLCMException("Failed to Operate %s(%s)", RES_VM, res["res_id"])
114 def heal_vim_res(vdus, vnfd_info, do_notify, data, vim_cache, res_cache):
116 vimid = data["vimid"]
117 tenant = data["tenant"]
118 actionType = data["action"]
119 if actionType == HEAL_ACTION_TYPE.START:
120 create_vm(vim_cache, res_cache, vnfd_info, vdus[0], do_notify, RES_VM)
121 elif actionType == HEAL_ACTION_TYPE.RESTART:
122 vm_info = api.get_vm(vimid, tenant, vdus[0].resourceid)
123 action_vm(ACTION_TYPE.REBOOT, vm_info, vimid, tenant)
124 except VimException as e:
125 logger.error("Failed to Heal %s(%s)", RES_VM, vdus[0]["vdu_id"])
126 logger.error("%s:%s", e.http_code, e.message)
127 raise NFLCMException("Failed to Heal %s(%s)", RES_VM, vdus[0]["vdu_id"])
130 def create_vim_res(data, do_notify, vim_cache={}, res_cache={}):
131 for vol in ignore_case_get(data, "volume_storages"):
132 create_volume(vim_cache, res_cache, vol, do_notify, RES_VOLUME)
133 for network in ignore_case_get(data, "vls"):
134 create_network(vim_cache, res_cache, network, do_notify, RES_NETWORK)
135 for subnet in ignore_case_get(data, "vls"):
136 create_subnet(vim_cache, res_cache, subnet, do_notify, RES_SUBNET)
137 for port in ignore_case_get(data, "cps"):
138 create_port(vim_cache, res_cache, data, port, do_notify, RES_PORT)
139 for vdu in ignore_case_get(data, "vdus"):
140 if vdu["type"] == "tosca.nodes.nfv.Vdu.Compute":
141 create_flavor(vim_cache, res_cache, data, vdu, do_notify, RES_FLAVOR)
142 for vdu in ignore_case_get(data, "vdus"):
143 if vdu["type"] == "tosca.nodes.nfv.Vdu.Compute":
144 create_vm(vim_cache, res_cache, data, vdu, do_notify, RES_VM)
147 def delete_vim_res(data, do_notify):
148 res_types = [RES_VM, RES_FLAVOR, RES_PORT, RES_SUBNET, RES_NETWORK, RES_VOLUME]
149 res_del_funs = [api.delete_vm, api.delete_flavor, api.delete_port,
150 api.delete_subnet, api.delete_network, api.delete_volume]
151 for res_type, res_del_fun in zip(res_types, res_del_funs):
152 for res in ignore_case_get(data, res_type):
154 if NOT_PREDEFINED == res["is_predefined"]:
155 res_del_fun(res["vim_id"], res["tenant_id"], res["res_id"])
156 except VimException as e:
157 logger.error("Failed to delete %s(%s)", res_type, res["res_id"])
158 logger.error("%s:%s", e.http_code, e.message)
159 do_notify(res_type, res["res_id"])
162 def create_volume(vim_cache, res_cache, vol, do_notify, res_type):
163 location_info = vol["properties"]["location_info"]
165 "name": vol["properties"]["volume_name"] if vol["properties"].get("volume_name", None) else vol["volume_storage_id"],
166 "volumeSize": int(ignore_case_get(vol["properties"], "size_of_storage", "0").replace('GB', '').replace('"', '').strip())
168 set_opt_val(param, "imageName", ignore_case_get(vol, "image_file"))
169 set_opt_val(param, "volumeType", ignore_case_get(vol["properties"], "type_of_storage"))
170 set_opt_val(param, "availabilityZone", ignore_case_get(location_info, "availability_zone"))
171 vim_id, tenant_name = location_info["vimid"], location_info["tenant"]
172 tenant_id = get_tenant_id(vim_cache, vim_id, tenant_name)
173 ret = api.create_volume(vim_id, tenant_id, param)
174 ret["nodeId"] = vol["volume_storage_id"]
175 do_notify(res_type, ret)
176 vol_id, vol_name = ret["id"], ret["name"]
177 set_res_cache(res_cache, res_type, vol["volume_storage_id"], vol_id)
178 retry_count, max_retry_count = 0, 300
179 while retry_count < max_retry_count:
180 vol_info = api.get_volume(vim_id, tenant_id, vol_id)
181 if vol_info["status"].upper() == "AVAILABLE":
182 logger.debug("Volume(%s) is available", vol_id)
185 retry_count = retry_count + 1
186 raise VimException("Failed to create Volume(%s): Timeout." % vol_name, ERR_CODE)
189 def create_network(vim_cache, res_cache, network, do_notify, res_type):
190 location_info = network["properties"]["location_info"]
191 vl_profile = network["properties"]["vl_profile"]
193 "name": vl_profile["networkName"],
195 "networkType": ignore_case_get(vl_profile, "networkType"),
196 "physicalNetwork": ignore_case_get(vl_profile, "physicalNetwork")
198 set_opt_val(param, "vlanTransparent", ignore_case_get(vl_profile, "vlanTransparent"))
199 set_opt_val(param, "segmentationId", int(ignore_case_get(vl_profile, "segmentationId", "0")))
200 set_opt_val(param, "routerExternal", ignore_case_get(network, "route_external"))
201 vim_id, tenant_name = location_info["vimid"], location_info["tenant"]
202 tenant_id = get_tenant_id(vim_cache, vim_id, tenant_name)
203 ret = api.create_network(vim_id, tenant_id, param)
204 ret["nodeId"] = network["vl_id"]
205 do_notify(res_type, ret)
206 set_res_cache(res_cache, res_type, network["vl_id"], ret["id"])
209 def create_subnet(vim_cache, res_cache, subnet, do_notify, res_type):
210 location_info = subnet["properties"]["location_info"]
211 network_id = get_res_id(res_cache, RES_NETWORK, subnet["vl_id"])
212 vl_profile = subnet["properties"]["vl_profile"]
213 layer_protocol = ignore_case_get(subnet["properties"]["connectivity_type"], "layer_protocol")
215 "networkId": network_id,
216 "name": vl_profile["networkName"] + "_subnet",
217 "cidr": ignore_case_get(vl_profile, "cidr"),
218 "ipVersion": IP_V4 if(layer_protocol == 'ipv4') else (IP_V6 if(layer_protocol == 'ipv6') else None)
220 set_opt_val(param, "enableDhcp", ignore_case_get(vl_profile, "dhcpEnabled"))
221 set_opt_val(param, "gatewayIp", ignore_case_get(vl_profile, "gatewayIp"))
222 set_opt_val(param, "dnsNameservers", ignore_case_get(subnet["properties"], "dns_nameservers"))
224 set_opt_val(allocation_pool, "start", ignore_case_get(vl_profile, "startIp"))
225 set_opt_val(allocation_pool, "end", ignore_case_get(vl_profile, "endIp"))
227 param["allocationPools"] = [allocation_pool]
228 set_opt_val(param, "hostRoutes", ignore_case_get(subnet["properties"], "host_routes"))
229 vim_id, tenant_name = location_info["vimid"], location_info["tenant"]
230 tenant_id = get_tenant_id(vim_cache, vim_id, tenant_name)
231 ret = api.create_subnet(vim_id, tenant_id, param)
232 do_notify(res_type, ret)
233 set_res_cache(res_cache, res_type, subnet["vl_id"], ret["id"])
236 def create_port(vim_cache, res_cache, data, port, do_notify, res_type):
238 port_ref_vdu_id = ignore_case_get(port, "vdu_id")
239 for vdu in ignore_case_get(data, "vdus"):
240 if vdu["vdu_id"] == port_ref_vdu_id:
241 location_info = vdu["properties"]["location_info"]
242 if port["cp_id"] not in vdu["cps"]:
243 vdu["cps"].append(port["cp_id"])
245 if not location_info:
246 err_msg = "vdu_id(%s) for cp(%s) is not defined."
247 raise VimException(err_msg % (port_ref_vdu_id, port["cp_id"]), ERR_CODE)
248 network_id = ignore_case_get(port, "networkId")
249 subnet_id = ignore_case_get(port, "subnetId")
251 network_id = get_res_id(res_cache, RES_NETWORK, port["vl_id"])
252 subnet_id = get_res_id(res_cache, RES_SUBNET, port["vl_id"])
254 "networkId": network_id,
255 "name": port["properties"].get("name", "")
257 set_opt_val(param, "subnetId", subnet_id)
258 set_opt_val(param, "macAddress", ignore_case_get(port["properties"], "mac_address"))
260 for one_protocol_data in port["properties"]["protocol_data"]:
261 l3_address_data = one_protocol_data["address_data"]["l3_address_data"] # l3 is not 13
262 fixed_ip_address = ignore_case_get(l3_address_data, "fixed_ip_address")
263 ip_address.extend(fixed_ip_address)
264 for one_virtual_network_interface in port["properties"].get("virtual_network_interface_requirements", []):
265 interfaceTypeString = one_virtual_network_interface["network_interface_requirements"]["interfaceType"]
266 interfaceType = json.loads(interfaceTypeString)["configurationValue"]
267 vnic_type = ignore_case_get(port["properties"], "vnic_type")
269 if interfaceType == "SR-IOV":
270 set_opt_val(param, "vnicType", "direct")
272 set_opt_val(param, "vnicType", vnic_type)
274 set_opt_val(param, "ip", ",".join(ip_address))
275 set_opt_val(param, "securityGroups", "") # TODO
276 vim_id, tenant_name = location_info["vimid"], location_info["tenant"]
277 tenant_id = get_tenant_id(vim_cache, vim_id, tenant_name)
278 ret = api.create_port(vim_id, tenant_id, param)
279 ret["nodeId"] = port["cp_id"]
280 do_notify(res_type, ret)
281 set_res_cache(res_cache, res_type, port["cp_id"], ret["id"])
284 def parse_unit(val, base_unit):
285 recognized_units = ["B", "kB", "KiB", "MB", "MiB", "GB", "GiB", "TB", "TiB"]
286 units_rate = [1, 1000, 1024, 1000000, 1048576, 1000000000, 1073741824, 1000000000000, 1099511627776]
287 unit_rate_map = {unit.upper(): rate for unit, rate in zip(recognized_units, units_rate)}
288 num_unit = val.strip().split(" ")
289 if len(num_unit) != 2:
291 num, unit = num_unit[0], num_unit[1]
292 return int(num) * unit_rate_map[unit.upper()] / unit_rate_map[base_unit.upper()]
295 def search_flavor_aai(vim_id, flavor_name):
296 aai_flavors = get_flavor_info(vim_id)
299 aai_flavor = aai_flavors["flavor"]
300 for one_aai_flavor in aai_flavor:
301 if one_aai_flavor["flavor-name"].find(flavor_name) == -1:
302 return one_aai_flavor
307 def create_flavor(vim_cache, res_cache, data, flavor, do_notify, res_type):
308 location_info = flavor["properties"]["location_info"]
309 vim_id, tenant_name = location_info["vimid"], location_info["tenant"]
310 virtual_compute = flavor["virtual_compute"]
311 virtual_storages = flavor["virtual_storages"]
312 virtual_cpu = ignore_case_get(virtual_compute, "virtual_cpu")
313 virtual_memory = ignore_case_get(virtual_compute, "virtual_memory")
315 "name": "Flavor_%s" % flavor["vdu_id"],
316 "vcpu": int(ignore_case_get(virtual_cpu, "num_virtual_cpu")),
317 "memory": int(ignore_case_get(virtual_memory, "virtual_mem_size").replace('MB', '').strip()),
321 # Using flavor name returned by OOF to search falvor
322 vdu_id = ignore_case_get(flavor, "vdu_id")
324 for one_vdu in location_info["vduInfo"]:
325 if one_vdu["vduName"] == vdu_id:
326 aai_flavor = search_flavor_aai(vim_id, one_vdu["flavorName"])
332 do_notify(res_type, ret)
333 set_res_cache(res_cache, res_type, flavor["vdu_id"], ret["flavor-id"])
335 for virtual_storage in virtual_storages:
336 vs_id = virtual_storage["virtual_storage_id"]
337 for vs in data["volume_storages"]:
338 if vs["volume_storage_id"] == vs_id:
339 disk_type = ignore_case_get(vs["properties"], "type_of_storage")
340 disk_size = int(ignore_case_get(vs["properties"], "size_of_storage").replace('GB', '').replace('"', '').strip())
341 if disk_type == "root":
342 param["disk"] = disk_size
343 elif disk_type == "ephemeral":
344 param["ephemeral"] = disk_size
345 elif disk_type == "swap":
346 param["swap"] = disk_size
347 tenant_id = get_tenant_id(vim_cache, vim_id, tenant_name)
348 logger.debug("param:%s" % param)
349 ret = api.create_flavor(vim_id, tenant_id, param)
350 logger.debug("hhb ret:%s" % ret)
351 do_notify(res_type, ret)
352 set_res_cache(res_cache, res_type, flavor["vdu_id"], ret["id"])
355 def create_vm(vim_cache, res_cache, data, vm, do_notify, res_type):
356 location_info = vm["properties"]["location_info"]
357 vim_id, tenant_name = location_info["vimid"], location_info["tenant"]
358 tenant_id = get_tenant_id(vim_cache, vim_id, tenant_name)
360 "name": vm["properties"].get("name", "undefined"),
361 "flavorId": get_res_id(res_cache, RES_FLAVOR, vm["vdu_id"]),
368 if "artifacts" in vm and vm["artifacts"]:
369 param["boot"]["type"] = BOOT_FROM_IMAGE
371 for artifact in vm["artifacts"]:
372 if artifact["artifact_name"] == "sw_image":
373 # TODO: after DM define
374 img_name = os.path.basename(artifact["file"])
377 raise VimException("Undefined image(%s)" % vm["artifacts"], ERR_CODE)
378 images = api.list_image(vim_id, tenant_id)
379 for image in images["images"]:
380 if img_name == image["name"]:
381 param["boot"]["imageId"] = image["id"]
383 if "imageId" not in param["boot"]:
384 raise VimException("Undefined artifacts image(%s)" % vm["artifacts"], ERR_CODE)
385 elif vm["virtual_storages"]:
386 param["boot"]["type"] = BOOT_FROM_VOLUME
387 vol_id = vm["virtual_storages"][0]["virtual_storage_id"]
388 param["boot"]["volumeId"] = get_res_id(res_cache, RES_VOLUME, vol_id)
390 raise VimException("No image and volume defined", ERR_CODE)
392 for cp_id in ignore_case_get(vm, "cps"):
393 param["nicArray"].append({
394 "portId": get_res_id(res_cache, RES_PORT, cp_id)
396 param["contextArray"] = ignore_case_get(vm["properties"], "inject_files")
397 logger.debug("contextArray:%s", param["contextArray"])
398 for vol_data in ignore_case_get(vm, "volume_storages"):
399 vol_id = vol_data["volume_storage_id"]
400 param["volumeArray"].append({
401 "volumeId": get_res_id(res_cache, RES_VOLUME, vol_id)
404 user_data = base64.encodestring(ignore_case_get(vm["properties"], "user_data"))
405 set_opt_val(param, "availabilityZone", ignore_case_get(location_info, "availability_zone"))
406 set_opt_val(param, "userdata", user_data)
407 set_opt_val(param, "metadata", ignore_case_get(vm["properties"], "meta_data"))
408 set_opt_val(param, "securityGroups", "") # TODO List of names of security group
409 set_opt_val(param, "serverGroup", "") # TODO the ServerGroup for anti-affinity and affinity
411 ret = api.create_vm(vim_id, tenant_id, param)
412 do_notify(res_type, ret)
414 if ignore_case_get(ret, "name"):
415 vm_name = vm["properties"].get("name", "undefined")
416 logger.debug("vm_name:%s" % vm_name)
417 opt_vm_status = "Timeout"
418 retry_count, max_retry_count = 0, 100
419 while retry_count < max_retry_count:
420 vm_info = api.get_vm(vim_id, tenant_id, vm_id)
421 if vm_info["status"].upper() == "ACTIVE":
422 logger.debug("Vm(%s) is active", vim_id)
424 if vm_info["status"].upper() == "ERROR":
425 opt_vm_status = vm_info["status"]
428 retry_count = retry_count + 1
429 raise VimException("Failed to create Vm(%s): %s." % (vm_name, opt_vm_status), ERR_CODE)