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