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