Add tenantId to vimdriver url
[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 RES_EXIST, RES_NEW = 0, 1
27 NET_PRIVATE, NET_SHSRED = 0, 1
28 VLAN_TRANSPARENT_NO, VLAN_TRANSPARENT_YES = 0, 1
29 IP_V4, IP_V6 = 4, 6
30 DHCP_DISABLED, DHCP_ENABLED = 0, 1
31 OPT_CREATE_VOLUME = 20
32 OPT_CREATE_NETWORK = 30
33 OPT_CREATE_SUBNET = 40
34 OPT_CREATE_PORT = 50
35 OPT_CREATE_FLAVOR = 60
36 OPT_CREATE_VM = 80
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         err_msg = "Tenant(%s) is not found in vim(%s)"
49         raise VimException(err_msg % (tenant_name, vim_id), "500")
50     return vim_cache[vim_id][tenant_name]
51
52 def create_vim_res(data, do_notify):
53     vim_cache = {}
54     for vol in ignore_case_get(data, "volume_storages"):
55         create_volume(vim_cache, vol, do_notify, OPT_CREATE_VOLUME)
56     for network in ignore_case_get(data, "vls"):
57         create_network(vim_cache, network, do_notify, OPT_CREATE_NETWORK)
58     for subnet in ignore_case_get(data, "vls"):
59         create_subnet(vim_cache, subnet, do_notify, OPT_CREATE_SUBNET)
60     for port in ignore_case_get(data, "cps"):
61         create_port(vim_cache, port, do_notify, OPT_CREATE_PORT)
62     for flavor in ignore_case_get(data, "vdus"):
63         create_flavor(vim_cache, flavor, do_notify, OPT_CREATE_FLAVOR)
64     for vm in ignore_case_get(data, "vdus"):
65         create_vm(vim_cache, vm, do_notify, OPT_CREATE_VM)
66
67 def delete_vim_res(data, do_notify):
68     res_types = ["vm", "flavor", "port", "subnet", "network", "volume"]
69     res_del_funs = [api.delete_vm, api.delete_flavor, api.delete_port, 
70         api.delete_subnet, api.delete_network, api.delete_volume]
71     for res_type, res_del_fun in zip(res_types, res_del_funs):
72         for res in ignore_case_get(data, res_type):
73             try:
74                 res_del_fun(res["vim_id"], res["tenant_id"], res["res_id"])
75             except VimException as e:
76                 logger.error("Failed to delete %s(%s): %s", 
77                     res_type, res["res_id"], e.message)
78             do_notify(res_type, res["res_id"])
79
80 def create_volume(vim_cache, vol, do_notify, progress):
81     param = {
82         "tenant": vol["properties"]["location_info"]["tenant"], 
83         "volumeName": vol["properties"]["volume_name"], 
84         "volumeSize": int(ignore_case_get(vol["properties"], "size", "0"))
85     }
86     set_opt_val(param, "imageName", ignore_case_get(vol, "image_file"))
87     set_opt_val(param, "volumeType", ignore_case_get(vol["properties"], "custom_volume_type"))
88     vim_id = vol["properties"]["location_info"]["vimid"]
89     ret = api.create_volume(vim_id, param)
90     vol_id, vol_name, return_code = ret["id"], ret["name"], ret["returnCode"]
91     retry_count, max_retry_count = 0, 300
92     while retry_count < max_retry_count:
93         vol_info = api.get_volume(vim_id, vol_id)
94         if vol_info["status"].upper() == "AVAILABLE":
95             do_notify(progress, ret)
96             break
97         time.sleep(2)
98         retry_count = retry_count + 1
99     if return_code == RES_NEW:
100         api.delete_volume(vim_id, vol_id)
101     raise VimException("Failed to create Volume(%s): Timeout." % vol_name, "500")
102     
103 def create_network(vim_cache, network, do_notify, progress):
104     param = {
105         "tenant": network["properties"]["location_info"]["tenant"],     
106         "networkName": network["properties"]["network_name"],
107         "shared": NET_PRIVATE,
108         "networkType": network["properties"]["network_type"],
109         "physicalNetwork": ignore_case_get(network["properties"], "physical_network")
110     }
111     set_opt_val(param, "vlanTransparent", 
112         ignore_case_get(network["properties"], "vlan_transparent"), VLAN_TRANSPARENT_YES)
113     set_opt_val(param, "segmentationId", ignore_case_get(network["properties"], "segmentation_id"))
114     vim_id = network["properties"]["location_info"]["vimid"]
115     ret = api.create_network(vim_id, param)
116     do_notify(progress, ret)
117     
118 def create_subnet(vim_cache, subnet, do_notify, progress):
119     param = {
120         "tenant": subnet["properties"]["location_info"]["tenant"],      
121         "networkName": subnet["properties"]["network_name"],
122         "subnetName": subnet["properties"]["name"],
123         "cidr": ignore_case_get(subnet["properties"], "cidr"),
124         "ipVersion": ignore_case_get(subnet["properties"], "ip_version", IP_V4)
125     }
126     set_opt_val(param, "enableDhcp", 
127         ignore_case_get(subnet["properties"], "dhcp_enabled"), DHCP_ENABLED)
128     set_opt_val(param, "gatewayIp", ignore_case_get(subnet["properties"], "gateway_ip"))
129     set_opt_val(param, "dnsNameservers", ignore_case_get(subnet["properties"], "dns_nameservers"))
130     allocation_pool = {}
131     set_opt_val(allocation_pool, "start", ignore_case_get(subnet["properties"], "start_ip"))
132     set_opt_val(allocation_pool, "end", ignore_case_get(subnet["properties"], "end_ip"))
133     if allocation_pool:
134         param["allocationPools"] = [allocation_pool]
135     set_opt_val(param, "hostRoutes", ignore_case_get(subnet["properties"], "host_routes"))
136     vim_id = subnet["properties"]["location_info"]["vimid"]
137     ret = api.create_subnet(vim_id, param)
138     do_notify(progress, ret)
139     
140 def create_port(vim_cache, port, do_notify, progress):
141     param = {
142         "tenant": port["properties"]["location_info"]["tenant"],
143         "networkName": port["properties"]["network_name"],
144         "subnetName": port["properties"]["name"],
145         "portName": port["properties"]["name"]
146     }
147     vim_id = port["properties"]["location_info"]["vimid"]
148     ret = api.create_subnet(vim_id, param)
149     do_notify(progress, ret)
150
151 def create_flavor(vim_cache, flavor, do_notify, progress):
152     param = {
153         "tenant": flavor["properties"]["location_info"]["tenant"],
154         "vcpu": int(flavor["nfv_compute"]["num_cpus"]),
155         "memory": int(flavor["nfv_compute"]["mem_size"].replace('MB', '').strip())
156     }
157     set_opt_val(param, "extraSpecs", ignore_case_get(flavor["nfv_compute"], "flavor_extra_specs"))
158     vim_id = flavor["properties"]["location_info"]["vimid"]
159     ret = api.create_flavor(vim_id, param)
160     do_notify(progress, ret)
161     
162 def create_vm(vim_cache, vm, do_notify, progress):
163     param = {
164         "tenant": vm["properties"]["location_info"]["tenant"],
165         "vmName": vm["properties"]["name"],
166         "boot": {
167             "type": BOOT_FROM_VOLUME,
168             "volumeName": vm["volume_storages"][0]["volume_storage_id"]
169         },
170         "nicArray": [],
171         "contextArray": [],
172         "volumeArray": []
173     }
174     set_opt_val(param, "availabilityZone", 
175         ignore_case_get(vm["properties"]["location_info"], "availability_zone"))
176     for inject_data in ignore_case_get(vm["properties"], "inject_data_list"):
177         param["contextArray"].append({
178             "fileName": inject_data["file_name"],
179             "fileData": inject_data["file_data"]
180         })
181     for vol_data in vm["volume_storages"]:
182         param["contextArray"].append(vol_data["volume_storage_id"])
183     # nicArray TODO:
184     vim_id = vm["properties"]["location_info"]["vimid"]
185     ret = api.create_vm(vim_id, param)
186     vm_id, vm_name, return_code = ret["id"], ret["name"], ret["returnCode"]
187     opt_vm_status = "Timeout"
188     retry_count, max_retry_count = 0, 100
189     while retry_count < max_retry_count:
190         vm_info = api.get_vm(vim_id, vm_id)
191         if vm_info["status"].upper() == "ACTIVE":
192             do_notify(progress, ret)
193             break
194         if vm_info["status"].upper() == "ERROR":
195             opt_vm_status = vm_info["status"]
196             break
197         time.sleep(2)
198         retry_count = retry_count + 1
199     if return_code == RES_NEW:
200         api.delete_vm(vim_id, vm_id)
201     raise VimException("Failed to create Vm(%s): %s." % (vm_name, opt_vm_status), "500")
202
203