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.
18 from lcm.pub.utils.values import ignore_case_get, set_opt_val
19 from lcm.pub.msapi.aai import get_flavor_info
21 from .exceptions import VimException
23 logger = logging.getLogger(__name__)
26 RES_EXIST, RES_NEW = 0, 1
28 BOOT_FROM_VOLUME, BOOT_FROM_IMAGE = 1, 2
31 RES_NETWORK = "network"
39 def get_tenant_id(vim_cache, vim_id, tenant_name):
40 if vim_id not in vim_cache:
41 tenants = api.list_tenant(vim_id)
42 vim_cache[vim_id] = {}
43 for tenant in tenants["tenants"]:
44 id, name = tenant["id"], tenant["name"]
45 vim_cache[vim_id][name] = id
46 if tenant_name not in vim_cache[vim_id]:
47 raise VimException("Tenant(%s) not found in vim(%s)" % (tenant_name, vim_id), ERR_CODE)
48 return vim_cache[vim_id][tenant_name]
51 def set_res_cache(res_cache, res_type, key, val):
52 if res_type not in res_cache:
53 res_cache[res_type] = {}
54 if key in res_cache[res_type]:
55 raise VimException("Duplicate key(%s) of %s" % (key, res_type), ERR_CODE)
56 res_cache[res_type][key] = val
59 def get_res_id(res_cache, res_type, key):
60 if res_type not in res_cache:
61 raise VimException("%s not found in cache" % res_type, ERR_CODE)
62 if key not in res_cache[res_type]:
63 raise VimException("%s(%s) not found in cache" % (res_type, key), ERR_CODE)
64 return res_cache[res_type][key]
67 def create_vim_res(data, do_notify):
68 vim_cache, res_cache = {}, {}
69 for vol in ignore_case_get(data, "volume_storages"):
70 create_volume(vim_cache, res_cache, vol, do_notify, RES_VOLUME)
71 for network in ignore_case_get(data, "vls"):
72 create_network(vim_cache, res_cache, network, do_notify, RES_NETWORK)
73 for subnet in ignore_case_get(data, "vls"):
74 create_subnet(vim_cache, res_cache, subnet, do_notify, RES_SUBNET)
75 for port in ignore_case_get(data, "cps"):
76 create_port(vim_cache, res_cache, data, port, do_notify, RES_PORT)
77 for vdu in ignore_case_get(data, "vdus"):
78 if vdu["type"] == "tosca.nodes.nfv.Vdu.Compute":
79 create_flavor(vim_cache, res_cache, data, vdu, do_notify, RES_FLAVOR)
80 for vdu in ignore_case_get(data, "vdus"):
81 if vdu["type"] == "tosca.nodes.nfv.Vdu.Compute":
82 create_vm(vim_cache, res_cache, data, vdu, do_notify, RES_VM)
85 def delete_vim_res(data, do_notify):
86 res_types = [RES_VM, RES_FLAVOR, RES_PORT, RES_SUBNET, RES_NETWORK, RES_VOLUME]
87 res_del_funs = [api.delete_vm, api.delete_flavor, api.delete_port,
88 api.delete_subnet, api.delete_network, api.delete_volume]
89 for res_type, res_del_fun in zip(res_types, res_del_funs):
90 for res in ignore_case_get(data, res_type):
92 if NOT_PREDEFINED == res["is_predefined"]:
93 res_del_fun(res["vim_id"], res["tenant_id"], res["res_id"])
94 except VimException as e:
95 logger.error("Failed to delete %s(%s)", res_type, res["res_id"])
96 logger.error("%s:%s", e.http_code, e.message)
97 do_notify(res_type, res["res_id"])
100 def create_volume(vim_cache, res_cache, vol, do_notify, res_type):
101 location_info = vol["properties"]["location_info"]
103 "name": vol["properties"]["volume_name"],
104 "volumeSize": int(ignore_case_get(vol["properties"], "size", "0").replace('GB', '').strip())
106 set_opt_val(param, "imageName", ignore_case_get(vol, "image_file"))
107 set_opt_val(param, "volumeType", ignore_case_get(vol["properties"], "custom_volume_type"))
108 set_opt_val(param, "availabilityZone", ignore_case_get(location_info, "availability_zone"))
109 vim_id, tenant_name = location_info["vimid"], location_info["tenant"]
110 tenant_id = get_tenant_id(vim_cache, vim_id, tenant_name)
111 ret = api.create_volume(vim_id, tenant_id, param)
112 ret["nodeId"] = vol["volume_storage_id"]
113 do_notify(res_type, ret)
114 vol_id, vol_name = ret["id"], ret["name"]
115 set_res_cache(res_cache, res_type, vol["volume_storage_id"], vol_id)
116 retry_count, max_retry_count = 0, 300
117 while retry_count < max_retry_count:
118 vol_info = api.get_volume(vim_id, tenant_id, vol_id)
119 if vol_info["status"].upper() == "AVAILABLE":
120 logger.debug("Volume(%s) is available", vol_id)
123 retry_count = retry_count + 1
124 raise VimException("Failed to create Volume(%s): Timeout." % vol_name, ERR_CODE)
127 def create_network(vim_cache, res_cache, network, do_notify, res_type):
128 location_info = network["properties"]["location_info"]
129 vl_profile = network["properties"]["vl_profile"]
131 "name": vl_profile["networkName"],
133 "networkType": vl_profile["networkType"],
134 "physicalNetwork": ignore_case_get(vl_profile, "physicalNetwork")
136 set_opt_val(param, "vlanTransparent", ignore_case_get(vl_profile, "vlanTransparent"))
137 set_opt_val(param, "segmentationId", int(ignore_case_get(vl_profile, "segmentationId", "0")))
138 set_opt_val(param, "routerExternal", ignore_case_get(network, "route_external"))
139 vim_id, tenant_name = location_info["vimid"], location_info["tenant"]
140 tenant_id = get_tenant_id(vim_cache, vim_id, tenant_name)
141 ret = api.create_network(vim_id, tenant_id, param)
142 ret["nodeId"] = network["vl_id"]
143 do_notify(res_type, ret)
144 set_res_cache(res_cache, res_type, network["vl_id"], ret["id"])
147 def create_subnet(vim_cache, res_cache, subnet, do_notify, res_type):
148 location_info = subnet["properties"]["location_info"]
149 network_id = get_res_id(res_cache, RES_NETWORK, subnet["vl_id"])
150 vl_profile = subnet["properties"]["vl_profile"]
151 layer_protocol = ignore_case_get(subnet["properties"]["connectivity_type"], "layer_protocol")
153 "networkId": network_id,
154 "name": vl_profile["networkName"] + "_subnet",
155 "cidr": ignore_case_get(vl_profile, "cidr"),
156 "ipVersion": IP_V4 if(layer_protocol == 'ipv4') else (IP_V6 if(layer_protocol == 'ipv6') else None)
158 set_opt_val(param, "enableDhcp", ignore_case_get(vl_profile, "dhcpEnabled"))
159 set_opt_val(param, "gatewayIp", ignore_case_get(vl_profile, "gatewayIp"))
160 set_opt_val(param, "dnsNameservers", ignore_case_get(subnet["properties"], "dns_nameservers"))
162 set_opt_val(allocation_pool, "start", ignore_case_get(vl_profile, "startIp"))
163 set_opt_val(allocation_pool, "end", ignore_case_get(vl_profile, "endIp"))
165 param["allocationPools"] = [allocation_pool]
166 set_opt_val(param, "hostRoutes", ignore_case_get(subnet["properties"], "host_routes"))
167 vim_id, tenant_name = location_info["vimid"], location_info["tenant"]
168 tenant_id = get_tenant_id(vim_cache, vim_id, tenant_name)
169 ret = api.create_subnet(vim_id, tenant_id, param)
170 do_notify(res_type, ret)
171 set_res_cache(res_cache, res_type, subnet["vl_id"], ret["id"])
174 def create_port(vim_cache, res_cache, data, port, do_notify, res_type):
176 port_ref_vdu_id = ignore_case_get(port, "vdu_id")
177 for vdu in ignore_case_get(data, "vdus"):
178 if vdu["vdu_id"] == port_ref_vdu_id:
179 location_info = vdu["properties"]["location_info"]
180 if port["cp_id"] not in vdu["cps"]:
181 vdu["cps"].append(port["cp_id"])
183 if not location_info:
184 err_msg = "vdu_id(%s) for cp(%s) is not defined"
185 raise VimException(err_msg % (port_ref_vdu_id, port["cp_id"]), ERR_CODE)
186 network_id = ignore_case_get(port, "networkId")
187 subnet_id = ignore_case_get(port, "subnetId")
189 network_id = get_res_id(res_cache, RES_NETWORK, port["vl_id"])
190 subnet_id = get_res_id(res_cache, RES_SUBNET, port["vl_id"])
192 "networkId": network_id,
193 "name": port["properties"].get("name", "undefined")
195 set_opt_val(param, "subnetId", subnet_id)
196 set_opt_val(param, "macAddress", ignore_case_get(port["properties"], "mac_address"))
198 for one_protocol_data in port["properties"]["protocol_data"]:
199 l3_address_data = one_protocol_data["address_data"]["l3_address_data"]
200 fixed_ip_address = ignore_case_get(l3_address_data, "fixed_ip_address")
201 ip_address.extend(fixed_ip_address)
202 set_opt_val(param, "ip", ip_address)
203 set_opt_val(param, "vnicType", ignore_case_get(port["properties"], "vnic_type"))
204 set_opt_val(param, "securityGroups", "") # TODO
205 vim_id, tenant_name = location_info["vimid"], location_info["tenant"]
206 tenant_id = get_tenant_id(vim_cache, vim_id, tenant_name)
207 ret = api.create_port(vim_id, tenant_id, param)
208 ret["nodeId"] = port["cp_id"]
209 do_notify(res_type, ret)
210 set_res_cache(res_cache, res_type, port["cp_id"], ret["id"])
213 def search_flavor_aai(vim_id, memory_page_size):
214 aai_flavors = get_flavor_info(vim_id)
217 logger.debug("aai_flavors:%s" % aai_flavors)
218 aai_flavor = aai_flavors[0]["flavors"]["flavor"]
219 for one_aai_flavor in aai_flavor:
220 hpa_capabilities = one_aai_flavor["hpa-capabilities"]
221 for one_hpa_capa in hpa_capabilities:
222 hpa_feature_attr = one_hpa_capa["hpa-feature-attributes"]
223 for one_hpa_attr in hpa_feature_attr:
224 hpa_key = one_hpa_attr["hpa-attribute-key"]
225 hpa_value = one_hpa_attr["hpa-attribute-value"]["value"]
226 if hpa_key == "memoryPageSize" and int(hpa_value) == memory_page_size:
227 return one_aai_flavor
230 def create_flavor(vim_cache, res_cache, data, flavor, do_notify, res_type):
231 location_info = flavor["properties"]["location_info"]
232 vim_id, tenant_name = location_info["vimid"], location_info["tenant"]
233 virtual_compute = flavor["virtual_compute"]
235 "name": "Flavor_%s" % flavor["vdu_id"],
236 "vcpu": int(virtual_compute["virtual_cpu"]["num_virtual_cpu"]),
237 "memory": int(virtual_compute["virtual_memory"]["virtual_mem_size"].replace('MB', '').strip()),
241 # just do memory huge page
242 flavor_extra_specs = ""
243 vdu_memory_requirements = virtual_compute["virtual_memory"]["vdu_memory_requirements"]
244 if "memoryPageSize" in vdu_memory_requirements:
245 memory_page_size = int(vdu_memory_requirements["memoryPageSize"].replace('MB', '').strip())
246 flavor_extra_specs = ("hw:mem_page_size=%sMB" % memory_page_size)
247 logger.debug("flavor_extra_specs:%s" % flavor_extra_specs)
250 aai_flavor = search_flavor_aai(vim_id, memory_page_size)
255 do_notify(res_type, ret)
256 set_res_cache(res_cache, res_type, flavor["vdu_id"], ret["flavor-id"])
259 disk_type = virtual_compute["virtual_storage"]["type_of_storage"]
260 disk_size = int(virtual_compute["virtual_storage"]["size_of_storage"].replace('GB', '').strip())
261 if disk_type == "root":
262 param["disk"] = disk_size
263 elif disk_type == "ephemeral":
264 param["ephemeral"] = disk_size
265 elif disk_type == "swap":
266 param["swap"] = disk_size
268 for es in flavor_extra_specs:
269 extra_specs.append({"keyName": es, "value": flavor_extra_specs[es]})
271 set_opt_val(param, "extraSpecs", extra_specs)
272 tenant_id = get_tenant_id(vim_cache, vim_id, tenant_name)
273 logger.debug("param:%s" % param)
274 ret = api.create_flavor(vim_id, tenant_id, param)
275 do_notify(res_type, ret)
276 set_res_cache(res_cache, res_type, flavor["vdu_id"], ret["id"])
279 def create_vm(vim_cache, res_cache, data, vm, do_notify, res_type):
280 location_info = vm["properties"]["location_info"]
281 vim_id, tenant_name = location_info["vimid"], location_info["tenant"]
282 tenant_id = get_tenant_id(vim_cache, vim_id, tenant_name)
284 "name": vm["properties"].get("name", "undefined"),
285 "flavorId": get_res_id(res_cache, RES_FLAVOR, vm["vdu_id"]),
292 if "image_file" in vm and vm["image_file"]:
293 param["boot"]["type"] = BOOT_FROM_IMAGE
295 for img in ignore_case_get(data, "image_files"):
296 if vm["image_file"] == img["image_file_id"]:
297 img_name = img["properties"]["name"]
300 raise VimException("Undefined image(%s)" % vm["image_file"], ERR_CODE)
301 images = api.list_image(vim_id, tenant_id)
302 for image in images["images"]:
303 if img_name == image["name"]:
304 param["boot"]["imageId"] = image["id"]
306 if "imageId" not in param["boot"]:
307 raise VimException("Image(%s) not found in Vim(%s)" % (img_name, vim_id), ERR_CODE)
308 elif vm["volume_storages"]:
309 param["boot"]["type"] = BOOT_FROM_VOLUME
310 vol_id = vm["volume_storages"][0]["volume_storage_id"]
311 param["boot"]["volumeId"] = get_res_id(res_cache, RES_VOLUME, vol_id)
313 raise VimException("No image and volume defined", ERR_CODE)
315 for cp_id in ignore_case_get(vm, "cps"):
316 param["nicArray"].append({
317 "portId": get_res_id(res_cache, RES_PORT, cp_id)
319 for inject_data in ignore_case_get(vm["properties"], "inject_data_list"):
320 param["contextArray"].append({
321 "fileName": inject_data["file_name"],
322 "fileData": inject_data["file_data"]
324 for vol_data in ignore_case_get(vm, "volume_storages"):
325 vol_id = vol_data["volume_storage_id"]
326 param["volumeArray"].append({
327 "volumeId": get_res_id(res_cache, RES_VOLUME, vol_id)
330 set_opt_val(param, "availabilityZone", ignore_case_get(location_info, "availability_zone"))
331 set_opt_val(param, "userdata", "") # TODO Configuration information or scripts to use upon launch
332 set_opt_val(param, "metadata", "") # TODO [{"keyName": "foo", "value": "foo value"}]
333 set_opt_val(param, "securityGroups", "") # TODO List of names of security group
334 set_opt_val(param, "serverGroup", "") # TODO the ServerGroup for anti-affinity and affinity
336 ret = api.create_vm(vim_id, tenant_id, param)
337 do_notify(res_type, ret)
339 if ignore_case_get(ret, "name"):
340 vm_name = vm["properties"].get("name", "undefined")
341 logger.debug("vm_name:%s" % vm_name)
342 opt_vm_status = "Timeout"
343 retry_count, max_retry_count = 0, 100
344 while retry_count < max_retry_count:
345 vm_info = api.get_vm(vim_id, tenant_id, vm_id)
346 if vm_info["status"].upper() == "ACTIVE":
347 logger.debug("Vm(%s) is active", vim_id)
349 if vm_info["status"].upper() == "ERROR":
350 opt_vm_status = vm_info["status"]
353 retry_count = retry_count + 1
354 raise VimException("Failed to create Vm(%s): %s." % (vm_name, opt_vm_status), ERR_CODE)