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.
19 from lcm.pub.utils.values import ignore_case_get, set_opt_val
20 from lcm.pub.msapi.aai import get_flavor_info
22 from .exceptions import VimException
23 from lcm.nf.const import ACTION_TYPE
25 logger = logging.getLogger(__name__)
28 RES_EXIST, RES_NEW = 0, 1
30 BOOT_FROM_VOLUME, BOOT_FROM_IMAGE = 1, 2
33 RES_NETWORK = "network"
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]
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
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]
69 def action_vm(action_type, server, vimId, tenantId):
71 if action_type == ACTION_TYPE.START:
75 elif action_type == ACTION_TYPE.STOP:
79 elif action_type == ACTION_TYPE.REBOOT:
83 if server["status"] == "ACTIVE":
84 param["reboot"]["type"] = "SOFT"
86 param["reboot"]["type"] = "HARD"
88 api.action_vm(vimId, tenantId, res_id, param)
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"):
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)
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)
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):
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"])
146 def create_volume(vim_cache, res_cache, vol, do_notify, res_type):
147 location_info = vol["properties"]["location_info"]
149 "name": vol["properties"]["volume_name"],
150 "volumeSize": int(ignore_case_get(vol["properties"], "size", "0").replace('GB', '').strip())
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)
169 retry_count = retry_count + 1
170 raise VimException("Failed to create Volume(%s): Timeout." % vol_name, ERR_CODE)
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"]
177 "name": vl_profile["networkName"],
179 "networkType": vl_profile["networkType"],
180 "physicalNetwork": ignore_case_get(vl_profile, "physicalNetwork")
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"])
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")
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)
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"))
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"))
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"])
220 def create_port(vim_cache, res_cache, data, port, do_notify, res_type):
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"])
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")
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"])
238 "networkId": network_id,
239 "name": port["properties"].get("name", "undefined")
241 set_opt_val(param, "subnetId", subnet_id)
242 set_opt_val(param, "macAddress", ignore_case_get(port["properties"], "mac_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 for one_virtual_network_interface in port["properties"]["virtual_network_interface_requirements"]:
249 interfaceTypeString = one_virtual_network_interface["network_interface_requirements"]["interfaceType"]
250 interfaceType = json.loads(interfaceTypeString)["configuration-value"]
251 vnic_type = ignore_case_get(port["properties"], "vnic_type")
253 if interfaceType == "SR-IOV":
254 set_opt_val(param, "vnicType", "direct")
256 set_opt_val(param, "vnicType", vnic_type)
258 set_opt_val(param, "ip", ",".join(ip_address))
259 set_opt_val(param, "securityGroups", "") # TODO
260 vim_id, tenant_name = location_info["vimid"], location_info["tenant"]
261 tenant_id = get_tenant_id(vim_cache, vim_id, tenant_name)
262 ret = api.create_port(vim_id, tenant_id, param)
263 ret["nodeId"] = port["cp_id"]
264 do_notify(res_type, ret)
265 set_res_cache(res_cache, res_type, port["cp_id"], ret["id"])
268 def parse_unit(val, base_unit):
269 recognized_units = ["B", "kB", "KiB", "MB", "MiB", "GB", "GiB", "TB", "TiB"]
270 units_rate = [1, 1000, 1024, 1000000, 1048576, 1000000000, 1073741824, 1000000000000, 1099511627776]
271 unit_rate_map = {unit.upper(): rate for unit, rate in zip(recognized_units, units_rate)}
272 num_unit = val.strip().split(" ")
273 if len(num_unit) != 2:
275 num, unit = num_unit[0], num_unit[1]
276 return int(num) * unit_rate_map[unit.upper()] / unit_rate_map[base_unit.upper()]
279 def search_flavor_aai(vim_id, flavor_name):
280 aai_flavors = get_flavor_info(vim_id)
283 aai_flavor = aai_flavors["flavor"]
284 for one_aai_flavor in aai_flavor:
285 if one_aai_flavor["flavor-name"].find(flavor_name) == -1:
286 return one_aai_flavor
291 def create_flavor(vim_cache, res_cache, data, flavor, do_notify, res_type):
292 location_info = flavor["properties"]["location_info"]
293 vim_id, tenant_name = location_info["vimid"], location_info["tenant"]
294 virtual_compute = flavor["virtual_compute"]
295 virtual_storage = flavor["virtual_storage"]
296 virtual_cpu = ignore_case_get(virtual_compute, "virtual_cpu")
297 virtual_memory = ignore_case_get(virtual_compute, "virtual_memory")
299 "name": "Flavor_%s" % flavor["vdu_id"],
300 "vcpu": int(ignore_case_get(virtual_cpu, "num_virtual_cpu")),
301 "memory": int(ignore_case_get(virtual_memory, "virtual_mem_size").replace('MB', '').strip()),
305 # Using flavor name returned by OOF to search falvor
306 vdu_id = ignore_case_get(flavor, "vdu_id")
307 for one_vdu in location_info["vduInfo"]:
308 if one_vdu["vduName"] == vdu_id:
310 aai_flavor = search_flavor_aai(vim_id, one_vdu["flavorName"])
315 do_notify(res_type, ret)
316 set_res_cache(res_cache, res_type, flavor["vdu_id"], ret["flavor-id"])
318 disk_type = ignore_case_get(virtual_storage, "type_of_storage")
319 disk_size = int(ignore_case_get(virtual_storage, "size_of_storage").replace('GB', '').strip())
320 if disk_type == "root":
321 param["disk"] = disk_size
322 elif disk_type == "ephemeral":
323 param["ephemeral"] = disk_size
324 elif disk_type == "swap":
325 param["swap"] = disk_size
327 tenant_id = get_tenant_id(vim_cache, vim_id, tenant_name)
328 logger.debug("param:%s" % param)
329 ret = api.create_flavor(vim_id, tenant_id, param)
330 logger.debug("hhb ret:%s" % ret)
331 do_notify(res_type, ret)
332 set_res_cache(res_cache, res_type, flavor["vdu_id"], ret["id"])
335 def create_vm(vim_cache, res_cache, data, vm, do_notify, res_type):
336 location_info = vm["properties"]["location_info"]
337 vim_id, tenant_name = location_info["vimid"], location_info["tenant"]
338 tenant_id = get_tenant_id(vim_cache, vim_id, tenant_name)
340 "name": vm["properties"].get("name", "undefined"),
341 "flavorId": get_res_id(res_cache, RES_FLAVOR, vm["vdu_id"]),
348 if "artifacts" in vm and vm["artifacts"]:
349 param["boot"]["type"] = BOOT_FROM_IMAGE
351 for artifact in vm["artifacts"]:
352 if artifact["artifact_name"] == "sw_image":
353 # TODO: after DM define
354 img_name = artifact["file"]
357 raise VimException("Undefined image(%s)" % vm["artifacts"], ERR_CODE)
358 images = api.list_image(vim_id, tenant_id)
359 for image in images["images"]:
360 if img_name == image["name"]:
361 param["boot"]["imageId"] = image["id"]
363 if "imageId" not in param["boot"]:
364 raise VimException("Undefined artifacts image(%s)" % vm["artifacts"], ERR_CODE)
365 elif vm["volume_storages"]:
366 param["boot"]["type"] = BOOT_FROM_VOLUME
367 vol_id = vm["volume_storages"][0]["volume_storage_id"]
368 param["boot"]["volumeId"] = get_res_id(res_cache, RES_VOLUME, vol_id)
370 raise VimException("No image and volume defined", ERR_CODE)
372 for cp_id in ignore_case_get(vm, "cps"):
373 param["nicArray"].append({
374 "portId": get_res_id(res_cache, RES_PORT, cp_id)
376 param["contextArray"] = ignore_case_get(vm["properties"], "inject_files")
377 logger.debug("contextArray:%s", param["contextArray"])
378 for vol_data in ignore_case_get(vm, "volume_storages"):
379 vol_id = vol_data["volume_storage_id"]
380 param["volumeArray"].append({
381 "volumeId": get_res_id(res_cache, RES_VOLUME, vol_id)
384 set_opt_val(param, "availabilityZone", ignore_case_get(location_info, "availability_zone"))
385 set_opt_val(param, "userdata", ignore_case_get(vm["properties"], "user_data"))
386 set_opt_val(param, "metadata", ignore_case_get(vm["properties"], "meta_data"))
387 set_opt_val(param, "securityGroups", "") # TODO List of names of security group
388 set_opt_val(param, "serverGroup", "") # TODO the ServerGroup for anti-affinity and affinity
390 ret = api.create_vm(vim_id, tenant_id, param)
391 do_notify(res_type, ret)
393 if ignore_case_get(ret, "name"):
394 vm_name = vm["properties"].get("name", "undefined")
395 logger.debug("vm_name:%s" % vm_name)
396 opt_vm_status = "Timeout"
397 retry_count, max_retry_count = 0, 100
398 while retry_count < max_retry_count:
399 vm_info = api.get_vm(vim_id, tenant_id, vm_id)
400 if vm_info["status"].upper() == "ACTIVE":
401 logger.debug("Vm(%s) is active", vim_id)
403 if vm_info["status"].upper() == "ERROR":
404 opt_vm_status = vm_info["status"]
407 retry_count = retry_count + 1
408 raise VimException("Failed to create Vm(%s): %s." % (vm_name, opt_vm_status), ERR_CODE)