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