Refactor volume create logic
[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 RES_VOLUME = "volume"
30 RES_NETWORK = "network"
31 RES_SUBNET = "subnet"
32 RES_PORT = "port"
33 RES_FLAVOR = "flavor"
34 RES_VM = "vm"
35
36
37 BOOT_FROM_VOLUME = 1
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, 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, 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     do_notify(res_type, ret)
105     vol_id, vol_name, return_code = ret["id"], ret["name"], ret["returnCode"]
106     set_res_cache(res_cache, res_type, vol["volume_storage_id"], vol_id)
107     retry_count, max_retry_count = 0, 300
108     while retry_count < max_retry_count:
109         vol_info = api.get_volume(vim_id, tenant_id, vol_id)
110         if vol_info["status"].upper() == "AVAILABLE":
111             logger.debug("Volume(%s) is available", vol_id)
112             return
113         time.sleep(2)
114         retry_count = retry_count + 1
115     raise VimException("Failed to create Volume(%s): Timeout." % vol_name, ERR_CODE)
116     
117 def create_network(vim_cache, res_cache, network, do_notify, res_type):
118     location_info = network["properties"]["location_info"]
119     param = {
120         "name": network["properties"]["network_name"],
121         "shared": False,
122         "networkType": network["properties"]["network_type"],
123         "physicalNetwork": ignore_case_get(network["properties"], "physical_network")
124     }
125     set_opt_val(param, "vlanTransparent", ignore_case_get(network["properties"], "vlan_transparent"))
126     set_opt_val(param, "segmentationId", int(ignore_case_get(network["properties"], "segmentation_id", "0")))
127     set_opt_val(param, "routerExternal", ignore_case_get(network, "route_external"))
128     vim_id, tenant_name = location_info["vimid"], location_info["tenant"]
129     tenant_id = get_tenant_id(vim_cache, vim_id, tenant_name)
130     ret = api.create_network(vim_id, tenant_id, param)
131     do_notify(res_type, ret)
132     set_res_cache(res_cache, res_type, network["vl_id"], ret["id"])
133     
134 def create_subnet(vim_cache, res_cache, subnet, do_notify, res_type):
135     location_info = subnet["properties"]["location_info"]
136     network_id = get_res_id(res_cache, RES_NETWORK, subnet["vl_id"])
137     param = {
138         "networkId": network_id,
139         "name": subnet["properties"]["name"],
140         "cidr": ignore_case_get(subnet["properties"], "cidr"),
141         "ipVersion": ignore_case_get(subnet["properties"], "ip_version", IP_V4)
142     }
143     set_opt_val(param, "enableDhcp", ignore_case_get(subnet["properties"], "dhcp_enabled"))
144     set_opt_val(param, "gatewayIp", ignore_case_get(subnet["properties"], "gateway_ip"))
145     set_opt_val(param, "dnsNameservers", ignore_case_get(subnet["properties"], "dns_nameservers"))
146     allocation_pool = {}
147     set_opt_val(allocation_pool, "start", ignore_case_get(subnet["properties"], "start_ip"))
148     set_opt_val(allocation_pool, "end", ignore_case_get(subnet["properties"], "end_ip"))
149     if allocation_pool:
150         param["allocationPools"] = [allocation_pool]
151     set_opt_val(param, "hostRoutes", ignore_case_get(subnet["properties"], "host_routes"))
152     vim_id, tenant_name = location_info["vimid"], location_info["tenant"]
153     tenant_id = get_tenant_id(vim_cache, vim_id, tenant_name)
154     ret = api.create_subnet(vim_id, tenant_id, param)
155     do_notify(res_type, ret)
156     set_res_cache(res_cache, res_type, subnet["vl_id"], ret["id"])
157     
158 def create_port(vim_cache, res_cache, port, do_notify, res_type):
159     location_info = port["properties"]["location_info"]
160     network_id = get_res_id(res_cache, RES_NETWORK, port["vl_id"])
161     subnet_id = get_res_id(res_cache, RES_SUBNET, port["vl_id"])
162     param = {
163         "networkId": network_id,
164         "subnetId": subnet_id,
165         "name": port["properties"]["name"]
166     }
167     set_opt_val(param, "macAddress", ignore_case_get(port["properties"], "mac_address"))
168     set_opt_val(param, "ip", ignore_case_get(port["properties"], "ip_address"))
169     set_opt_val(param, "vnicType", ignore_case_get(port["properties"], "vnic_type"))
170     set_opt_val(param, "securityGroups", "") # TODO
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_subnet(vim_id, tenant_id, param)
174     do_notify(res_type, ret)
175     set_res_cache(res_cache, res_type, port["cp_id"], ret["id"])
176
177 def create_flavor(vim_cache, res_cache, data, flavor, do_notify, res_type):
178     location_info = flavor["properties"]["location_info"]
179     local_storages = ignore_case_get(data, "local_storages")
180     param = {
181         "name": "Flavor_%s" % flavor["vdu_id"],
182         "vcpu": int(flavor["nfv_compute"]["num_cpus"]),
183         "memory": int(flavor["nfv_compute"]["mem_size"].replace('MB', '').strip()),
184         "isPublic": True
185     }
186     for local_storage_id in ignore_case_get(flavor, "local_storages"):
187         for local_storage in local_storages:
188             if local_storage_id != local_storage["local_storage_id"]:
189                 continue
190             disk_type = local_storage["properties"]["disk_type"]
191             disk_size = int(local_storage["properties"]["size"].replace('GB', '').strip())
192             if disk_type == "root":
193                 param["disk"] = disk_size
194             elif disk_type == "ephemeral":
195                 param["ephemeral"] = disk_size
196             elif disk_type == "swap":
197                 param["swap"] = disk_size
198     flavor_extra_specs = ignore_case_get(flavor["nfv_compute"], "flavor_extra_specs")
199     extra_specs = []
200     for es in flavor_extra_specs:
201         extra_specs.append({"keyName": es, "value": flavor_extra_specs[es]})
202     set_opt_val(param, "extraSpecs", extra_specs)
203     vim_id, tenant_name = location_info["vimid"], location_info["tenant"]
204     tenant_id = get_tenant_id(vim_cache, vim_id, tenant_name)
205     ret = api.create_flavor(vim_id, tenant_id, param)
206     do_notify(res_type, ret)
207     set_res_cache(res_cache, res_type, flavor["vdu_id"], ret["id"])
208     
209 def create_vm(vim_cache, res_cache, vm, do_notify, res_type):
210     location_info = vm["properties"]["location_info"]
211     param = {
212         "vmName": vm["properties"]["name"],
213         "boot": {
214             "type": BOOT_FROM_VOLUME,
215             "volumeName": vm["volume_storages"][0]["volume_storage_id"]
216         },
217         "nicArray": [],
218         "contextArray": [],
219         "volumeArray": []
220     }
221     set_opt_val(param, "availabilityZone", 
222         ignore_case_get(vm["properties"]["location_info"], "availability_zone"))
223     for inject_data in ignore_case_get(vm["properties"], "inject_data_list"):
224         param["contextArray"].append({
225             "fileName": inject_data["file_name"],
226             "fileData": inject_data["file_data"]
227         })
228     for vol_data in vm["volume_storages"]:
229         param["contextArray"].append(vol_data["volume_storage_id"])
230     # nicArray TODO:
231     vim_id = vm["properties"]["location_info"]["vimid"]
232     ret = api.create_vm(vim_id, param)
233     do_notify(res_type, ret)
234     vm_id, vm_name, return_code = ret["id"], ret["name"], ret["returnCode"]
235     opt_vm_status = "Timeout"
236     retry_count, max_retry_count = 0, 100
237     while retry_count < max_retry_count:
238         vm_info = api.get_vm(vim_id, vm_id)
239         if vm_info["status"].upper() == "ACTIVE":
240             logger.debug("Vm(%s) is active", vim_id)
241             return
242         if vm_info["status"].upper() == "ERROR":
243             opt_vm_status = vm_info["status"]
244             break
245         time.sleep(2)
246         retry_count = retry_count + 1
247     raise VimException("Failed to create Vm(%s): %s." % (vm_name, opt_vm_status), ERR_CODE)
248
249