b63cf1eefa7f4615e33cc28bce7fc30846a3f5f3
[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 DHCP_DISABLED, DHCP_ENABLED = 0, 1
30 RES_VOLUME = "volume"
31 RES_NETWORK = "network"
32 RES_SUBNET = "subnet"
33 RES_PORT = "port"
34 RES_FLAVOR = "flavor"
35 RES_VM = "vm"
36
37
38 BOOT_FROM_VOLUME = 1
39
40 def get_tenant_id(vim_cache, vim_id, tenant_name):
41     if vim_id not in vim_cache:
42         tenants = api.list_tenant(vim_id)
43         vim_cache[vim_id] = {}
44         for tenant in tenants["tenants"]:
45             id, name = tenant["id"], tenant["name"]
46             vim_cache[vim_id][name] = id
47     if tenant_name not in vim_cache[vim_id]:
48         raise VimException("Tenant(%s) not found in vim(%s)" % (tenant_name, vim_id), ERR_CODE)
49     return vim_cache[vim_id][tenant_name]
50
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
57
58 def get_res_id(res_cache, res_type, key):
59     if res_type not in res_cache:
60         raise VimException("%s not found in cache" % res_type, ERR_CODE)
61     if key not in res_cache[res_type]:
62         raise VimException("%s(%s) not found in cache" % (res_type, key), ERR_CODE)
63     return res_cache[res_type][key]
64
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, 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, vm, do_notify, RES_VM)
79
80 def delete_vim_res(data, do_notify):
81     res_types = [RES_VM, RES_FLAVOR, RES_PORT, RES_SUBNET, RES_NETWORK, RES_VOLUME]
82     res_del_funs = [api.delete_vm, api.delete_flavor, api.delete_port, 
83         api.delete_subnet, api.delete_network, api.delete_volume]
84     for res_type, res_del_fun in zip(res_types, res_del_funs):
85         for res in ignore_case_get(data, res_type):
86             try:
87                 res_del_fun(res["vim_id"], res["tenant_id"], res["res_id"])
88             except VimException as e:
89                 logger.error("Failed to delete %s(%s)", res_type, res["res_id"])
90                 logger.error("%s:%s", e.http_code, e.message)
91             do_notify(res_type, res["res_id"])
92
93 def create_volume(vim_cache, res_cache, vol, do_notify, res_type):
94     location_info = vol["properties"]["location_info"]
95     param = {
96         "name": vol["properties"]["volume_name"],
97         "volumeSize": int(ignore_case_get(vol["properties"], "size", "0"))
98     }
99     set_opt_val(param, "imageName", ignore_case_get(vol, "image_file"))
100     set_opt_val(param, "volumeType", ignore_case_get(vol["properties"], "custom_volume_type"))
101     set_opt_val(param, "availabilityZone", ignore_case_get(location_info, "availability_zone"))
102     vim_id, tenant_name = location_info["vimid"], location_info["tenant"]
103     tenant_id = get_tenant_id(vim_cache, vim_id, tenant_name)
104     ret = api.create_volume(vim_id, tenant_id, param)
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     do_notify(res_type, ret)
133     set_res_cache(res_cache, res_type, network["vl_id"], ret["id"])
134     
135 def create_subnet(vim_cache, res_cache, subnet, do_notify, res_type):
136     location_info = subnet["properties"]["location_info"]
137     network_id = get_res_id(res_cache, RES_NETWORK, subnet["vl_id"])
138     param = {
139         "networkId": network_id,
140         "name": subnet["properties"]["name"],
141         "cidr": ignore_case_get(subnet["properties"], "cidr"),
142         "ipVersion": ignore_case_get(subnet["properties"], "ip_version", IP_V4)
143     }
144     set_opt_val(param, "enableDhcp", ignore_case_get(subnet["properties"], "dhcp_enabled"))
145     set_opt_val(param, "gatewayIp", ignore_case_get(subnet["properties"], "gateway_ip"))
146     set_opt_val(param, "dnsNameservers", ignore_case_get(subnet["properties"], "dns_nameservers"))
147     allocation_pool = {}
148     set_opt_val(allocation_pool, "start", ignore_case_get(subnet["properties"], "start_ip"))
149     set_opt_val(allocation_pool, "end", ignore_case_get(subnet["properties"], "end_ip"))
150     if allocation_pool:
151         param["allocationPools"] = [allocation_pool]
152     set_opt_val(param, "hostRoutes", ignore_case_get(subnet["properties"], "host_routes"))
153     vim_id, tenant_name = location_info["vimid"], location_info["tenant"]
154     tenant_id = get_tenant_id(vim_cache, vim_id, tenant_name)
155     ret = api.create_subnet(vim_id, tenant_id, param)
156     do_notify(res_type, ret)
157     set_res_cache(res_cache, res_type, subnet["vl_id"], ret["id"])
158     
159 def create_port(vim_cache, res_cache, port, do_notify, res_type):
160     location_info = port["properties"]["location_info"]
161     network_id = get_res_id(res_cache, RES_NETWORK, port["vl_id"])
162     subnet_id = get_res_id(res_cache, RES_SUBNET, port["vl_id"])
163     param = {
164         "networkId": network_id,
165         "subnetId": subnet_id,
166         "name": port["properties"]["name"]
167     }
168     set_opt_val(param, "macAddress", ignore_case_get(port["properties"], "mac_address"))
169     set_opt_val(param, "ip", ignore_case_get(port["properties"], "ip_address"))
170     set_opt_val(param, "vnicType", ignore_case_get(port["properties"], "vnic_type"))
171     set_opt_val(param, "securityGroups", "") # TODO
172     vim_id, tenant_name = location_info["vimid"], location_info["tenant"]
173     tenant_id = get_tenant_id(vim_cache, vim_id, tenant_name)
174     ret = api.create_subnet(vim_id, tenant_id, param)
175     do_notify(res_type, ret)
176     set_res_cache(res_cache, res_type, port["cp_id"], ret["id"])
177
178 def create_flavor(vim_cache, res_cache, data, flavor, do_notify, res_type):
179     location_info = flavor["properties"]["location_info"]
180     local_storages = ignore_case_get(data, "local_storages")
181     param = {
182         "name": "Flavor_%s" % flavor["vdu_id"],
183         "vcpu": int(flavor["nfv_compute"]["num_cpus"]),
184         "memory": '',
185         "isPublic": True
186     }
187     for local_storage_id in ignore_case_get(flavor, "local_storages"):
188         for local_storage in local_storages:
189             if local_storage_id != local_storage["local_storage_id"]:
190                 continue
191             disk_type = local_storage["properties"]["disk_type"]
192             disk_size = int(local_storage["properties"]["size"].replace('GB', '').strip())
193             if disk_type == "root":
194                 param["disk"] = disk_size
195             elif disk_type == "ephemeral":
196                 param["ephemeral"] = disk_size
197             elif disk_type == "swap":
198                 param["swap"] = disk_size
199     flavor_extra_specs = ignore_case_get(flavor["nfv_compute"], "flavor_extra_specs")
200     extra_specs = []
201     for es in flavor_extra_specs:
202         extra_specs.append({"keyName": es, "value": flavor_extra_specs[es]})
203     set_opt_val(param, "extraSpecs", extra_specs)
204     vim_id, tenant_name = location_info["vimid"], location_info["tenant"]
205     tenant_id = get_tenant_id(vim_cache, vim_id, tenant_name)
206     ret = api.create_flavor(vim_id, tenant_id, param)
207     do_notify(res_type, ret)
208     set_res_cache(res_cache, res_type, flavor["vdu_id"], ret["id"])
209     
210 def create_vm(vim_cache, res_cache, vm, do_notify, res_type):
211     param = {
212         "tenant": vm["properties"]["location_info"]["tenant"],
213         "vmName": vm["properties"]["name"],
214         "boot": {
215             "type": BOOT_FROM_VOLUME,
216             "volumeName": vm["volume_storages"][0]["volume_storage_id"]
217         },
218         "nicArray": [],
219         "contextArray": [],
220         "volumeArray": []
221     }
222     set_opt_val(param, "availabilityZone", 
223         ignore_case_get(vm["properties"]["location_info"], "availability_zone"))
224     for inject_data in ignore_case_get(vm["properties"], "inject_data_list"):
225         param["contextArray"].append({
226             "fileName": inject_data["file_name"],
227             "fileData": inject_data["file_data"]
228         })
229     for vol_data in vm["volume_storages"]:
230         param["contextArray"].append(vol_data["volume_storage_id"])
231     # nicArray TODO:
232     vim_id = vm["properties"]["location_info"]["vimid"]
233     ret = api.create_vm(vim_id, param)
234     do_notify(res_type, ret)
235     vm_id, vm_name, return_code = ret["id"], ret["name"], ret["returnCode"]
236     opt_vm_status = "Timeout"
237     retry_count, max_retry_count = 0, 100
238     while retry_count < max_retry_count:
239         vm_info = api.get_vm(vim_id, vm_id)
240         if vm_info["status"].upper() == "ACTIVE":
241             logger.debug("Vm(%s) is active", vim_id)
242             return
243         if vm_info["status"].upper() == "ERROR":
244             opt_vm_status = vm_info["status"]
245             break
246         time.sleep(2)
247         retry_count = retry_count + 1
248     raise VimException("Failed to create Vm(%s): %s." % (vm_name, opt_vm_status), ERR_CODE)
249
250