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
20 from .exceptions import VimException
22 logger = logging.getLogger(__name__)
25 RES_EXIST, RES_NEW = 0, 1
27 BOOT_FROM_VOLUME, BOOT_FROM_IMAGE = 1, 2
30 RES_NETWORK = "network"
37 def get_tenant_id(vim_cache, vim_id, tenant_name):
38 if vim_id not in vim_cache:
39 tenants = api.list_tenant(vim_id)
40 vim_cache[vim_id] = {}
41 for tenant in tenants["tenants"]:
42 id, name = tenant["id"], tenant["name"]
43 vim_cache[vim_id][name] = id
44 if tenant_name not in vim_cache[vim_id]:
45 raise VimException("Tenant(%s) not found in vim(%s)" % (tenant_name, vim_id), ERR_CODE)
46 return vim_cache[vim_id][tenant_name]
49 def set_res_cache(res_cache, res_type, key, val):
50 if res_type not in res_cache:
51 res_cache[res_type] = {}
52 if key in res_cache[res_type]:
53 raise VimException("Duplicate key(%s) of %s" % (key, res_type), ERR_CODE)
54 res_cache[res_type][key] = val
57 def get_res_id(res_cache, res_type, key):
58 if res_type not in res_cache:
59 raise VimException("%s not found in cache" % res_type, ERR_CODE)
60 if key not in res_cache[res_type]:
61 raise VimException("%s(%s) not found in cache" % (res_type, key), ERR_CODE)
62 return res_cache[res_type][key]
65 def create_vim_res(data, do_notify):
66 vim_cache, res_cache = {}, {}
67 for vol in ignore_case_get(data, "volume_storages"):
68 create_volume(vim_cache, res_cache, vol, do_notify, RES_VOLUME)
69 for network in ignore_case_get(data, "vls"):
70 create_network(vim_cache, res_cache, network, do_notify, RES_NETWORK)
71 for subnet in ignore_case_get(data, "vls"):
72 create_subnet(vim_cache, res_cache, subnet, do_notify, RES_SUBNET)
73 for port in ignore_case_get(data, "cps"):
74 create_port(vim_cache, res_cache, data, port, do_notify, RES_PORT)
75 for flavor in ignore_case_get(data, "vdus"):
76 create_flavor(vim_cache, res_cache, data, flavor, do_notify, RES_FLAVOR)
77 for vm in ignore_case_get(data, "vdus"):
78 create_vm(vim_cache, res_cache, data, vm, do_notify, RES_VM)
81 def delete_vim_res(data, do_notify):
82 res_types = [RES_VM, RES_FLAVOR, RES_PORT, RES_SUBNET, RES_NETWORK, RES_VOLUME]
83 res_del_funs = [api.delete_vm, api.delete_flavor, api.delete_port,
84 api.delete_subnet, api.delete_network, api.delete_volume]
85 for res_type, res_del_fun in zip(res_types, res_del_funs):
86 for res in ignore_case_get(data, res_type):
88 if 1 == res["is_predefined"]:
89 res_del_fun(res["vim_id"], res["tenant_id"], res["res_id"])
90 except VimException as e:
91 logger.error("Failed to delete %s(%s)", res_type, res["res_id"])
92 logger.error("%s:%s", e.http_code, e.message)
93 do_notify(res_type, res["res_id"])
96 def create_volume(vim_cache, res_cache, vol, do_notify, res_type):
97 location_info = vol["properties"]["location_info"]
99 "name": vol["properties"]["volume_name"],
100 "volumeSize": int(ignore_case_get(vol["properties"], "size", "0").replace('GB', '').strip())
102 set_opt_val(param, "imageName", ignore_case_get(vol, "image_file"))
103 set_opt_val(param, "volumeType", ignore_case_get(vol["properties"], "custom_volume_type"))
104 set_opt_val(param, "availabilityZone", ignore_case_get(location_info, "availability_zone"))
105 vim_id, tenant_name = location_info["vimid"], location_info["tenant"]
106 tenant_id = get_tenant_id(vim_cache, vim_id, tenant_name)
107 ret = api.create_volume(vim_id, tenant_id, param)
108 ret["nodeId"] = vol["volume_storage_id"]
109 do_notify(res_type, ret)
110 vol_id, vol_name = ret["id"], ret["name"]
111 set_res_cache(res_cache, res_type, vol["volume_storage_id"], vol_id)
112 retry_count, max_retry_count = 0, 300
113 while retry_count < max_retry_count:
114 vol_info = api.get_volume(vim_id, tenant_id, vol_id)
115 if vol_info["status"].upper() == "AVAILABLE":
116 logger.debug("Volume(%s) is available", vol_id)
119 retry_count = retry_count + 1
120 raise VimException("Failed to create Volume(%s): Timeout." % vol_name, ERR_CODE)
123 def create_network(vim_cache, res_cache, network, do_notify, res_type):
124 location_info = network["properties"]["location_info"]
126 "name": network["properties"]["network_name"],
128 "networkType": network["properties"]["network_type"],
129 "physicalNetwork": ignore_case_get(network["properties"], "physical_network")
131 set_opt_val(param, "vlanTransparent", ignore_case_get(network["properties"], "vlan_transparent"))
132 set_opt_val(param, "segmentationId", int(ignore_case_get(network["properties"], "segmentation_id", "0")))
133 set_opt_val(param, "routerExternal", ignore_case_get(network, "route_external"))
134 vim_id, tenant_name = location_info["vimid"], location_info["tenant"]
135 tenant_id = get_tenant_id(vim_cache, vim_id, tenant_name)
136 ret = api.create_network(vim_id, tenant_id, param)
137 ret["nodeId"] = network["vl_id"]
138 do_notify(res_type, ret)
139 set_res_cache(res_cache, res_type, network["vl_id"], ret["id"])
142 def create_subnet(vim_cache, res_cache, subnet, do_notify, res_type):
143 location_info = subnet["properties"]["location_info"]
144 network_id = get_res_id(res_cache, RES_NETWORK, subnet["vl_id"])
146 "networkId": network_id,
147 "name": subnet["properties"]["name"],
148 "cidr": ignore_case_get(subnet["properties"], "cidr"),
149 "ipVersion": ignore_case_get(subnet["properties"], "ip_version", IP_V4)
151 set_opt_val(param, "enableDhcp", ignore_case_get(subnet["properties"], "dhcp_enabled"))
152 set_opt_val(param, "gatewayIp", ignore_case_get(subnet["properties"], "gateway_ip"))
153 set_opt_val(param, "dnsNameservers", ignore_case_get(subnet["properties"], "dns_nameservers"))
155 set_opt_val(allocation_pool, "start", ignore_case_get(subnet["properties"], "start_ip"))
156 set_opt_val(allocation_pool, "end", ignore_case_get(subnet["properties"], "end_ip"))
158 param["allocationPools"] = [allocation_pool]
159 set_opt_val(param, "hostRoutes", ignore_case_get(subnet["properties"], "host_routes"))
160 vim_id, tenant_name = location_info["vimid"], location_info["tenant"]
161 tenant_id = get_tenant_id(vim_cache, vim_id, tenant_name)
162 ret = api.create_subnet(vim_id, tenant_id, param)
163 do_notify(res_type, ret)
164 set_res_cache(res_cache, res_type, subnet["vl_id"], ret["id"])
167 def create_port(vim_cache, res_cache, data, port, do_notify, res_type):
169 port_ref_vdu_id = ignore_case_get(port, "vdu_id")
170 for vdu in ignore_case_get(data, "vdus"):
171 if vdu["vdu_id"] == port_ref_vdu_id:
172 location_info = vdu["properties"]["location_info"]
173 if port["cp_id"] not in vdu["cps"]:
174 vdu["cps"].append(port["cp_id"])
176 if not location_info:
177 err_msg = "vdu_id(%s) for cp(%s) is not defined"
178 raise VimException(err_msg % (port_ref_vdu_id, port["cp_id"]), ERR_CODE)
179 network_id = ignore_case_get(port, "networkId")
180 subnet_id = ignore_case_get(port, "subnetId")
182 network_id = get_res_id(res_cache, RES_NETWORK, port["vl_id"])
183 subnet_id = get_res_id(res_cache, RES_SUBNET, port["vl_id"])
185 "networkId": network_id,
186 "name": port["properties"].get("name", "undefined")
188 set_opt_val(param, "subnetId", subnet_id)
189 set_opt_val(param, "macAddress", ignore_case_get(port["properties"], "mac_address"))
190 set_opt_val(param, "ip", ignore_case_get(port["properties"], "ip_address"))
191 set_opt_val(param, "vnicType", ignore_case_get(port["properties"], "vnic_type"))
192 set_opt_val(param, "securityGroups", "") # TODO
193 vim_id, tenant_name = location_info["vimid"], location_info["tenant"]
194 tenant_id = get_tenant_id(vim_cache, vim_id, tenant_name)
195 ret = api.create_port(vim_id, tenant_id, param)
196 ret["nodeId"] = port["cp_id"]
197 do_notify(res_type, ret)
198 set_res_cache(res_cache, res_type, port["cp_id"], ret["id"])
201 def create_flavor(vim_cache, res_cache, data, flavor, do_notify, res_type):
202 location_info = flavor["properties"]["location_info"]
203 local_storages = ignore_case_get(data, "local_storages")
205 "name": "Flavor_%s" % flavor["vdu_id"],
206 "vcpu": int(flavor["nfv_compute"]["num_cpus"]),
207 "memory": int(flavor["nfv_compute"]["mem_size"].replace('GB', '').strip()),
210 for local_storage_id in ignore_case_get(flavor, "local_storages"):
211 for local_storage in local_storages:
212 if local_storage_id != local_storage["local_storage_id"]:
214 disk_type = local_storage["properties"]["disk_type"]
215 disk_size = int(local_storage["properties"]["size"].replace('GB', '').strip())
216 if disk_type == "root":
217 param["disk"] = disk_size
218 elif disk_type == "ephemeral":
219 param["ephemeral"] = disk_size
220 elif disk_type == "swap":
221 param["swap"] = disk_size
222 flavor_extra_specs = ignore_case_get(flavor["nfv_compute"], "flavor_extra_specs")
224 for es in flavor_extra_specs:
225 extra_specs.append({"keyName": es, "value": flavor_extra_specs[es]})
226 set_opt_val(param, "extraSpecs", extra_specs)
227 vim_id, tenant_name = location_info["vimid"], location_info["tenant"]
228 tenant_id = get_tenant_id(vim_cache, vim_id, tenant_name)
229 ret = api.create_flavor(vim_id, tenant_id, param)
230 do_notify(res_type, ret)
231 set_res_cache(res_cache, res_type, flavor["vdu_id"], ret["id"])
234 def create_vm(vim_cache, res_cache, data, vm, do_notify, res_type):
235 location_info = vm["properties"]["location_info"]
236 vim_id, tenant_name = location_info["vimid"], location_info["tenant"]
237 tenant_id = get_tenant_id(vim_cache, vim_id, tenant_name)
239 "name": vm["properties"].get("name", "undefined"),
240 "flavorId": get_res_id(res_cache, RES_FLAVOR, vm["vdu_id"]),
247 if "image_file" in vm and vm["image_file"]:
248 param["boot"]["type"] = BOOT_FROM_IMAGE
250 for img in ignore_case_get(data, "image_files"):
251 if vm["image_file"] == img["image_file_id"]:
252 img_name = img["properties"]["name"]
255 raise VimException("Undefined image(%s)" % vm["image_file"], ERR_CODE)
256 images = api.list_image(vim_id, tenant_id)
257 for image in images["images"]:
258 if img_name == image["name"]:
259 param["boot"]["imageId"] = image["id"]
261 if "imageId" not in param["boot"]:
262 raise VimException("Image(%s) not found in Vim(%s)" % (img_name, vim_id), ERR_CODE)
263 elif vm["volume_storages"]:
264 param["boot"]["type"] = BOOT_FROM_VOLUME
265 vol_id = vm["volume_storages"][0]["volume_storage_id"]
266 param["boot"]["volumeId"] = get_res_id(res_cache, RES_VOLUME, vol_id)
268 raise VimException("No image and volume defined", ERR_CODE)
270 for cp_id in ignore_case_get(vm, "cps"):
271 param["nicArray"].append({
272 "portId": get_res_id(res_cache, RES_PORT, cp_id)
274 for inject_data in ignore_case_get(vm["properties"], "inject_data_list"):
275 param["contextArray"].append({
276 "fileName": inject_data["file_name"],
277 "fileData": inject_data["file_data"]
279 for vol_data in ignore_case_get(vm, "volume_storages"):
280 vol_id = vol_data["volume_storage_id"]
281 param["volumeArray"].append({
282 "volumeId": get_res_id(res_cache, RES_VOLUME, vol_id)
285 set_opt_val(param, "availabilityZone", ignore_case_get(location_info, "availability_zone"))
286 set_opt_val(param, "userdata", "") # TODO Configuration information or scripts to use upon launch
287 set_opt_val(param, "metadata", "") # TODO [{"keyName": "foo", "value": "foo value"}]
288 set_opt_val(param, "securityGroups", "") # TODO List of names of security group
289 set_opt_val(param, "serverGroup", "") # TODO the ServerGroup for anti-affinity and affinity
291 ret = api.create_vm(vim_id, tenant_id, param)
292 do_notify(res_type, ret)
294 if ignore_case_get(ret, "name"):
295 vm_name = vm["properties"].get("name", "undefined")
296 logger.debug("vm_name:%s" % vm_name)
297 opt_vm_status = "Timeout"
298 retry_count, max_retry_count = 0, 100
299 while retry_count < max_retry_count:
300 vm_info = api.get_vm(vim_id, tenant_id, vm_id)
301 if vm_info["status"].upper() == "ACTIVE":
302 logger.debug("Vm(%s) is active", vim_id)
304 if vm_info["status"].upper() == "ERROR":
305 opt_vm_status = vm_info["status"]
308 retry_count = retry_count + 1
309 raise VimException("Failed to create Vm(%s): %s." % (vm_name, opt_vm_status), ERR_CODE)