fed69b1d9dff6308fbc2502ca2018649ab2f81dd
[vfc/gvnfm/vnflcm.git] / lcm / lcm / pub / vimapi / adaptor.py
1 # Copyright 2017 ZTE Corporation.
2 #
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
6 #
7 #         http://www.apache.org/licenses/LICENSE-2.0
8 #
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.
14
15 import logging
16 import sys
17 import time
18 import traceback
19
20 from lcm.pub.utils.values import ignore_case_get, set_opt_val
21 from . import api
22 from .exceptions import VimException
23
24 logger = logging.getLogger(__name__)
25
26 ERR_CODE = "500"
27 RES_EXIST, RES_NEW = 0, 1
28 IP_V4, IP_V6 = 4, 6
29 BOOT_FROM_VOLUME, BOOT_FROM_IMAGE = 1, 2
30
31 RES_VOLUME = "volume"
32 RES_NETWORK = "network"
33 RES_SUBNET = "subnet"
34 RES_PORT = "port"
35 RES_FLAVOR = "flavor"
36 RES_VM = "vm"
37
38
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]
49
50 def set_res_cache(res_cache, res_type, key, val):
51     if res_type not in res_cache:
52         res_cache[res_type] = {}
53     if key in res_cache[res_type]:
54         raise VimException("Duplicate key(%s) of %s" % (key, res_type), ERR_CODE)
55     res_cache[res_type][key] = val
56
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]
63
64 def create_vim_res(data, do_notify):
65     vim_cache, res_cache = {}, {}
66     for vol in ignore_case_get(data, "volume_storages"):
67         create_volume(vim_cache, res_cache, vol, do_notify, RES_VOLUME)
68     for network in ignore_case_get(data, "vls"):
69         create_network(vim_cache, res_cache, network, do_notify, RES_NETWORK)
70     for subnet in ignore_case_get(data, "vls"):
71         create_subnet(vim_cache, res_cache, subnet, do_notify, RES_SUBNET)
72     for port in ignore_case_get(data, "cps"):
73         create_port(vim_cache, res_cache, data, port, do_notify, RES_PORT)
74     for flavor in ignore_case_get(data, "vdus"):
75         create_flavor(vim_cache, res_cache, data, flavor, do_notify, RES_FLAVOR)
76     for vm in ignore_case_get(data, "vdus"):
77         create_vm(vim_cache, res_cache, data, vm, do_notify, RES_VM)
78
79 def delete_vim_res(data, do_notify):
80     res_types = [RES_VM, RES_FLAVOR, RES_PORT, RES_SUBNET, RES_NETWORK, RES_VOLUME]
81     res_del_funs = [api.delete_vm, api.delete_flavor, api.delete_port, 
82         api.delete_subnet, api.delete_network, api.delete_volume]
83     for res_type, res_del_fun in zip(res_types, res_del_funs):
84         for res in ignore_case_get(data, res_type):
85             try:
86                 res_del_fun(res["vim_id"], res["tenant_id"], res["res_id"])
87             except VimException as e:
88                 logger.error("Failed to delete %s(%s)", res_type, res["res_id"])
89                 logger.error("%s:%s", e.http_code, e.message)
90             do_notify(res_type, res["res_id"])
91
92 def create_volume(vim_cache, res_cache, vol, do_notify, res_type):
93     location_info = vol["properties"]["location_info"]
94     param = {
95         "name": vol["properties"]["volume_name"],
96         "volumeSize": int(ignore_case_get(vol["properties"], "size", "0").replace('GB', '').strip())
97     }
98     set_opt_val(param, "imageName", ignore_case_get(vol, "image_file"))
99     set_opt_val(param, "volumeType", ignore_case_get(vol["properties"], "custom_volume_type"))
100     set_opt_val(param, "availabilityZone", ignore_case_get(location_info, "availability_zone"))
101     vim_id, tenant_name = location_info["vimid"], location_info["tenant"]
102     tenant_id = get_tenant_id(vim_cache, vim_id, tenant_name)
103     ret = api.create_volume(vim_id, tenant_id, param)
104     ret["nodeId"] = vol["volume_storage_id"]
105     do_notify(res_type, ret)
106     vol_id, vol_name, return_code = ret["id"], ret["name"], ret["returnCode"]
107     set_res_cache(res_cache, res_type, vol["volume_storage_id"], vol_id)
108     retry_count, max_retry_count = 0, 300
109     while retry_count < max_retry_count:
110         vol_info = api.get_volume(vim_id, tenant_id, vol_id)
111         if vol_info["status"].upper() == "AVAILABLE":
112             logger.debug("Volume(%s) is available", vol_id)
113             return
114         time.sleep(2)
115         retry_count = retry_count + 1
116     raise VimException("Failed to create Volume(%s): Timeout." % vol_name, ERR_CODE)
117     
118 def create_network(vim_cache, res_cache, network, do_notify, res_type):
119     location_info = network["properties"]["location_info"]
120     param = {
121         "name": network["properties"]["network_name"],
122         "shared": False,
123         "networkType": network["properties"]["network_type"],
124         "physicalNetwork": ignore_case_get(network["properties"], "physical_network")
125     }
126     set_opt_val(param, "vlanTransparent", ignore_case_get(network["properties"], "vlan_transparent"))
127     set_opt_val(param, "segmentationId", int(ignore_case_get(network["properties"], "segmentation_id", "0")))
128     set_opt_val(param, "routerExternal", ignore_case_get(network, "route_external"))
129     vim_id, tenant_name = location_info["vimid"], location_info["tenant"]
130     tenant_id = get_tenant_id(vim_cache, vim_id, tenant_name)
131     ret = api.create_network(vim_id, tenant_id, param)
132     ret["nodeId"] = network["vl_id"]
133     do_notify(res_type, ret)
134     set_res_cache(res_cache, res_type, network["vl_id"], ret["id"])
135     
136 def create_subnet(vim_cache, res_cache, subnet, do_notify, res_type):
137     location_info = subnet["properties"]["location_info"]
138     network_id = get_res_id(res_cache, RES_NETWORK, subnet["vl_id"])
139     param = {
140         "networkId": network_id,
141         "name": subnet["properties"]["name"],
142         "cidr": ignore_case_get(subnet["properties"], "cidr"),
143         "ipVersion": ignore_case_get(subnet["properties"], "ip_version", IP_V4)
144     }
145     set_opt_val(param, "enableDhcp", ignore_case_get(subnet["properties"], "dhcp_enabled"))
146     set_opt_val(param, "gatewayIp", ignore_case_get(subnet["properties"], "gateway_ip"))
147     set_opt_val(param, "dnsNameservers", ignore_case_get(subnet["properties"], "dns_nameservers"))
148     allocation_pool = {}
149     set_opt_val(allocation_pool, "start", ignore_case_get(subnet["properties"], "start_ip"))
150     set_opt_val(allocation_pool, "end", ignore_case_get(subnet["properties"], "end_ip"))
151     if allocation_pool:
152         param["allocationPools"] = [allocation_pool]
153     set_opt_val(param, "hostRoutes", ignore_case_get(subnet["properties"], "host_routes"))
154     vim_id, tenant_name = location_info["vimid"], location_info["tenant"]
155     tenant_id = get_tenant_id(vim_cache, vim_id, tenant_name)
156     ret = api.create_subnet(vim_id, tenant_id, param)
157     do_notify(res_type, ret)
158     set_res_cache(res_cache, res_type, subnet["vl_id"], ret["id"])
159     
160 def create_port(vim_cache, res_cache, data, port, do_notify, res_type):
161     location_info = None
162     port_ref_vdu_id = ignore_case_get(port, "vdu_id")
163     for vdu in ignore_case_get(data, "vdus"):
164         if vdu["vdu_id"] == port_ref_vdu_id:
165             location_info = vdu["properties"]["location_info"]
166             break
167     if not location_info:
168         err_msg = "vdu_id(%s) for cp(%s) is not defined"
169         raise VimException(err_msg % (port_ref_vdu_id, port["cp_id"]), ERR_CODE)
170     network_id = get_res_id(res_cache, RES_NETWORK, port["vl_id"])
171     subnet_id = get_res_id(res_cache, RES_SUBNET, port["vl_id"])
172     param = {
173         "networkId": network_id,
174         "subnetId": subnet_id,
175         "name": port["properties"]["name"]
176     }
177     set_opt_val(param, "macAddress", ignore_case_get(port["properties"], "mac_address"))
178     set_opt_val(param, "ip", ignore_case_get(port["properties"], "ip_address"))
179     set_opt_val(param, "vnicType", ignore_case_get(port["properties"], "vnic_type"))
180     set_opt_val(param, "securityGroups", "") # TODO
181     vim_id, tenant_name = location_info["vimid"], location_info["tenant"]
182     tenant_id = get_tenant_id(vim_cache, vim_id, tenant_name)
183     ret = api.create_subnet(vim_id, tenant_id, param)
184     ret["nodeId"] = port["cp_id"]
185     do_notify(res_type, ret)
186     set_res_cache(res_cache, res_type, port["cp_id"], ret["id"])
187
188 def create_flavor(vim_cache, res_cache, data, flavor, do_notify, res_type):
189     location_info = flavor["properties"]["location_info"]
190     local_storages = ignore_case_get(data, "local_storages")
191     param = {
192         "name": "Flavor_%s" % flavor["vdu_id"],
193         "vcpu": int(flavor["nfv_compute"]["num_cpus"]),
194         "memory": int(flavor["nfv_compute"]["mem_size"].replace('MB', '').strip()),
195         "isPublic": True
196     }
197     for local_storage_id in ignore_case_get(flavor, "local_storages"):
198         for local_storage in local_storages:
199             if local_storage_id != local_storage["local_storage_id"]:
200                 continue
201             disk_type = local_storage["properties"]["disk_type"]
202             disk_size = int(local_storage["properties"]["size"].replace('GB', '').strip())
203             if disk_type == "root":
204                 param["disk"] = disk_size
205             elif disk_type == "ephemeral":
206                 param["ephemeral"] = disk_size
207             elif disk_type == "swap":
208                 param["swap"] = disk_size
209     flavor_extra_specs = ignore_case_get(flavor["nfv_compute"], "flavor_extra_specs")
210     extra_specs = []
211     for es in flavor_extra_specs:
212         extra_specs.append({"keyName": es, "value": flavor_extra_specs[es]})
213     set_opt_val(param, "extraSpecs", extra_specs)
214     vim_id, tenant_name = location_info["vimid"], location_info["tenant"]
215     tenant_id = get_tenant_id(vim_cache, vim_id, tenant_name)
216     ret = api.create_flavor(vim_id, tenant_id, param)
217     do_notify(res_type, ret)
218     set_res_cache(res_cache, res_type, flavor["vdu_id"], ret["id"])
219     
220 def create_vm(vim_cache, res_cache, data, vm, do_notify, res_type):
221     location_info = vm["properties"]["location_info"]
222     vim_id, tenant_name = location_info["vimid"], location_info["tenant"]
223     tenant_id = get_tenant_id(vim_cache, vim_id, tenant_name)
224     param = {
225         "name": vm["properties"]["name"],
226         "flavorId": get_res_id(res_cache, RES_FLAVOR, vm["vdu_id"]),
227         "boot": {},
228         "nicArray": [],
229         "contextArray": [],
230         "volumeArray": []
231     }
232     # set boot param
233     if "image_file" in vm and vm["image_file"]:
234         param["boot"]["type"] = BOOT_FROM_IMAGE
235         img_name = ""
236         for img in ignore_case_get(data, "image_files"):
237             if vm["image_file"] == img["image_file_id"]:
238                img_name = img["properties"]["name"]
239                break
240         if not img_name:
241             raise VimException("Undefined image(%s)" % vm["image_file"], ERR_CODE)
242         images = api.list_image(vim_id, tenant_id)
243         for image in images["imageList"]:
244             if img_name == image["name"]:
245                 param["boot"]["imageId"] = image["id"]
246                 break
247         if "imageId" not in param["boot"]:
248             raise VimException("Image(%s) not found in Vim(%s)" % (img_name, vim_id), ERR_CODE)
249     elif vm["volume_storages"]:
250         param["boot"]["type"] = BOOT_FROM_VOLUME
251         vol_id = vm["volume_storages"][0]["volume_storage_id"]
252         param["boot"]["volumeId"] = get_res_id(res_cache, RES_VOLUME, vol_id)
253     else:
254         raise VimException("No image and volume defined", ERR_CODE)
255
256     for cp_id in ignore_case_get(vm, "cps"):
257         param["nicArray"].append({
258             "portId": get_res_id(res_cache, RES_PORT, cp_id)
259         })
260     for inject_data in ignore_case_get(vm["properties"], "inject_data_list"):
261         param["contextArray"].append({
262             "fileName": inject_data["file_name"],
263             "fileData": inject_data["file_data"]
264         })
265     for vol_data in vm["volume_storages"]:
266         vol_id = vol_data["volume_storage_id"]
267         param["volumeArray"].append({
268             "volumeId": get_res_id(res_cache, RES_VOLUME, vol_id)
269         })
270
271     set_opt_val(param, "availabilityZone", ignore_case_get(location_info, "availability_zone"))
272     set_opt_val(param, "userdata", "") # TODO Configuration information or scripts to use upon launch
273     set_opt_val(param, "metadata", "") # TODO [{"keyName": "foo", "value": "foo value"}]
274     set_opt_val(param, "securityGroups", "") # TODO List of names of security group
275     set_opt_val(param, "serverGroup", "") # TODO the ServerGroup for anti-affinity and affinity
276     
277     ret = api.create_vm(vim_id, tenant_id, param)
278     do_notify(res_type, ret)
279     vm_id, vm_name, return_code = ret["id"], ret["name"], ret["returnCode"]
280     opt_vm_status = "Timeout"
281     retry_count, max_retry_count = 0, 100
282     while retry_count < max_retry_count:
283         vm_info = api.get_vm(vim_id, tenant_id, vm_id)
284         if vm_info["status"].upper() == "ACTIVE":
285             logger.debug("Vm(%s) is active", vim_id)
286             return
287         if vm_info["status"].upper() == "ERROR":
288             opt_vm_status = vm_info["status"]
289             break
290         time.sleep(2)
291         retry_count = retry_count + 1
292     raise VimException("Failed to create Vm(%s): %s." % (vm_name, opt_vm_status), ERR_CODE)