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