release nslcm version 1.4.0
[vfc/nfvo/lcm.git] / lcm / ns_vls / biz / create_vls.py
1 # Copyright 2016-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 json
16 import logging
17 import traceback
18 import uuid
19
20 from lcm.ns.enum import OWNER_TYPE
21 from lcm.pub.config.config import REPORT_TO_AAI
22 from lcm.pub.database.models import VLInstModel, NSInstModel, VNFFGInstModel
23 from lcm.pub.exceptions import NSLCMException
24 from lcm.pub.msapi import extsys, resmgr
25 from lcm.pub.msapi.aai import create_network_aai, create_subnet_aai
26 from lcm.pub.nfvi.vim import const
27 from lcm.pub.nfvi.vim import vimadaptor
28 from lcm.pub.utils.values import ignore_case_get
29
30 logger = logging.getLogger(__name__)
31
32
33 class CreateVls(object):
34     def __init__(self, data):
35         self.owner_id = ignore_case_get(data, "nsInstanceId")
36         self.index = int(float(ignore_case_get(data, "vlIndex")))
37         self.context = ignore_case_get(data, "context")
38         self.additionalParam = ignore_case_get(data, "additionalParamForNs")
39         self.vl_inst_id = str(uuid.uuid4())
40         self.owner_type = OWNER_TYPE.NS
41         self.vld_id = ""
42         self.vl_properties = ""
43         self.vl_profile = ""
44         self.vl_inst_name = ""
45         self.related_network_id = ""
46         self.related_subnetwork_id = ""
47         self.vim_id = ""
48         self.vim_name = ""
49         self.tenant = ""
50         self.description = ""
51         self.route_external = ""
52         self.ns_name = ""
53
54     def do(self):
55         try:
56             self.get_data()
57             self.create_vl_to_vim()
58             self.create_vl_to_resmgr()
59             self.save_vl_to_db()
60             if REPORT_TO_AAI:
61                 self.create_network_aai()
62             return {"result": 0, "detail": "instantiation vl success", "vlId": self.vl_inst_id}
63         except NSLCMException as e:
64             return self.exception_handle(e)
65         except Exception as e:
66             logger.error(traceback.format_exc())
67             return self.exception_handle(e)
68
69     def exception_handle(self, e):
70         detail = "vl instantiation failed, detail message: %s" % e.args[0]
71         logger.error(detail)
72         return {"result": 1, "detail": detail, "vlId": self.vl_inst_id}
73
74     def get_data(self):
75         if isinstance(self.context, str):
76             self.context = json.JSONDecoder().decode(self.context)
77         vl_info = self.get_vl_info(ignore_case_get(self.context, "vls"))
78         self.vld_id = ignore_case_get(vl_info, "vl_id")
79         self.description = ignore_case_get(vl_info, "description")
80         self.vl_properties = ignore_case_get(vl_info, "properties")
81         self.vl_profile = ignore_case_get(self.vl_properties, "vl_profile")
82         self.vl_inst_name = ignore_case_get(self.vl_profile, "networkName")
83         self.route_external = ignore_case_get(vl_info, "route_external")
84         ns_info = NSInstModel.objects.filter(id=self.owner_id)
85         self.ns_name = ns_info[0].name if ns_info else ""
86
87     def get_vl_info(self, vl_all_info):
88         return vl_all_info[self.index - 1]
89
90     def create_vl_to_vim(self):
91         self.vim_id = self.vl_properties["location_info"]["vimid"]
92         if not self.vim_id:
93             if isinstance(self.additionalParam, str):
94                 self.additionalParam = json.JSONDecoder().decode(self.additionalParam)
95             self.vim_id = ignore_case_get(self.additionalParam, "location")
96         self.tenant = ignore_case_get(self.vl_properties["location_info"], "tenant")
97         network_data = {
98             "tenant": self.tenant,
99             "network_name": self.vl_profile.get("networkName", ""),
100             "shared": const.SHARED_NET,
101             "network_type": self.vl_profile.get("networkType", ""),
102             "segmentation_id": self.vl_profile.get("segmentationId", ""),
103             "physical_network": self.vl_profile.get("physicalNetwork", ""),
104             "mtu": self.vl_profile.get("mtu", const.DEFAULT_MTU),
105             "vlan_transparent": self.vl_profile.get("vlanTransparent", False),
106             "subnet_list": [{
107                 "subnet_name": self.vl_profile.get("networkName"),  # self.vl_profile.get("initiationParameters").get("name", ""),
108                 "cidr": self.vl_profile.get("cidr", "192.168.0.0/24"),
109                 "ip_version": self.vl_profile.get("ip_version", const.IPV4),
110                 "enable_dhcp": self.vl_profile.get("dhcpEnabled", False),
111                 "gateway_ip": self.vl_profile.get("gatewayIp", ""),
112                 "dns_nameservers": self.vl_profile.get("dns_nameservers", ""),
113                 "host_routes": self.vl_profile.get("host_routes", "")}]}
114         startip = self.vl_profile.get("startIp", "")
115         endip = self.vl_profile.get("endIp", "")
116         if startip and endip:
117             network_data["subnet_list"][0]["allocation_pools"] = [
118                 {"start": startip, "end": endip}]
119
120         vl_resp = self.create_network_to_vim(network_data)
121         self.related_network_id = vl_resp["id"]
122         self.related_subnetwork_id = vl_resp["subnet_list"][0]["id"] if vl_resp["subnet_list"] else ""
123
124     def create_network_to_vim(self, network_data):
125         vim_resp_body = extsys.get_vim_by_id(self.vim_id)
126         self.vim_name = vim_resp_body["name"]
127         data = {
128             "vimid": self.vim_id,
129             "vimtype": vim_resp_body["type"],
130             "url": vim_resp_body["url"],
131             "user": vim_resp_body["userName"],
132             "passwd": vim_resp_body["password"],
133             "tenant": vim_resp_body["tenant"]}
134         vim_api = vimadaptor.VimAdaptor(data)
135         if not network_data["tenant"]:
136             network_data["tenant"] = vim_resp_body["tenant"]
137         vl_ret = vim_api.create_network(network_data)
138         if vl_ret[0] != 0:
139             logger.error("Send post vl request to vim failed, detail is %s" % vl_ret[1])
140             raise NSLCMException("Send post vl request to vim failed.")
141         return vl_ret[1]
142
143     def create_vl_to_resmgr(self):
144         self.vim_id = json.JSONDecoder().decode(self.vim_id) if isinstance(self.vim_id, str) else self.vim_id
145         vim_id = self.vim_id['cloud_owner'] + self.vim_id['cloud_regionid']
146         req_param = {
147             "vlInstanceId": self.vl_inst_id,
148             "name": self.vl_profile.get("networkName", ""),
149             "backendId": str(self.related_network_id),
150             "isPublic": "True",
151             "dcName": "",
152             "vimId": str(vim_id),
153             "vimName": self.vim_name,
154             "physicialNet": self.vl_profile.get("physicalNetwork", ""),
155             "nsId": self.owner_id,
156             "nsName": self.ns_name,
157             "description": self.description,
158             "networkType": self.vl_profile.get("networkType", ""),
159             "segmentation": str(self.vl_profile.get("segmentationId", "")),
160             "mtu": str(self.vl_profile.get("mtu", "")),
161             "vlanTransparent": str(self.vl_profile.get("vlanTransparent", "")),
162             "routerExternal": self.route_external,
163             "resourceProviderType": "",
164             "resourceProviderId": "",
165             "subnet_list": [{
166                 "subnet_name": self.vl_profile.get("networkName", ""),  # self.vl_profile.get("initiationParameters").get("name", ""),
167                 "cidr": self.vl_profile.get("cidr", "192.168.0.0/24"),
168                 "ip_version": self.vl_profile.get("ip_version", const.IPV4),
169                 "enable_dhcp": self.vl_profile.get("dhcpEnabled", False),
170                 "gateway_ip": self.vl_profile.get("gatewayIp", ""),
171                 "dns_nameservers": self.vl_profile.get("dns_nameservers", ""),
172                 "host_routes": self.vl_profile.get("host_routes", "")
173             }]
174         }
175         resmgr.create_vl(req_param)
176
177     def create_vl_inst_id_in_vnffg(self):
178         if "vnffgs" in self.context:
179             for vnffg_info in self.context["vnffgs"]:
180                 vl_id_list = vnffg_info.get("properties", {}).get("dependent_virtual_link", "")
181                 if vl_id_list:
182                     vl_inst_id_list = []
183                     for vl_id in vl_id_list:
184                         vl_inst_info = VLInstModel.objects.filter(vldid=vl_id)
185                         if vl_inst_info:
186                             vl_inst_id_list.append(vl_inst_info[0].vlinstanceid)
187                         else:
188                             vl_inst_id_list.append("")
189                     vl_inst_id_str = ""
190                     for vl_inst_id in vl_inst_id_list:
191                         vl_inst_id_str += vl_inst_id + ","
192                     vl_inst_id_str = vl_inst_id_str[:-1]
193                     VNFFGInstModel.objects.filter(vnffgdid=vnffg_info["vnffg_id"], nsinstid=self.owner_id).update(
194                         vllist=vl_inst_id_str)
195
196     def save_vl_to_db(self):
197         vim_id = json.JSONEncoder().encode(self.vim_id)
198         VLInstModel(vlinstanceid=self.vl_inst_id, vldid=self.vld_id, vlinstancename=self.vl_inst_name,
199                     ownertype=self.owner_type, ownerid=self.owner_id, relatednetworkid=self.related_network_id,
200                     relatedsubnetworkid=self.related_subnetwork_id, vimid=vim_id, tenant=self.tenant).save()
201         # do_biz_with_share_lock("create-vllist-in-vnffg-%s" % self.owner_id, self.create_vl_inst_id_in_vnffg)
202         self.create_vl_inst_id_in_vnffg()
203
204     def create_network_aai(self):
205         logger.debug("CreateVls::create_network_in_aai::report network[%s] to aai." % self.vl_inst_id)
206         try:
207             ns_insts = NSInstModel.objects.filter(id=self.owner_id)
208             self.global_customer_id = ns_insts[0].global_customer_id
209             self.service_type = ns_insts[0].service_type
210             data = {
211                 "network-id": self.vl_inst_id,
212                 "network-name": self.vl_inst_id,
213                 "is-bound-to-vpn": False,
214                 "is-provider-network": True,
215                 "is-shared-network": True,
216                 "is-external-network": True,
217                 # "subnets": {
218                 #     "subnet": [
219                 #         {
220                 #             "subnet-id": self.related_subnetwork_id,
221                 #             "dhcp-enabled": False
222                 #         }
223                 #     ]
224                 # },
225                 "relationship-list": {
226                     "relationship": [
227                         {
228                             "related-to": "service-instance",
229                             "relationship-data": [
230                                 {
231                                     "relationship-key": "customer.global-customer-id",
232                                     "relationship-value": self.global_customer_id
233                                 },
234                                 {
235                                     "relationship-key": "service-subscription.service-type",
236                                     "relationship-value": self.service_type
237                                 },
238                                 {
239                                     "relationship-key": "service-instance.service-instance-id",
240                                     "relationship-value": self.owner_id
241                                 }
242                             ]
243                         }
244                     ]
245                 }
246             }
247             resp_data, resp_status = create_network_aai(self.vl_inst_id, data)
248             logger.debug("Success to create network[%s] to aai: [%s].", self.vl_inst_id, resp_status)
249         except NSLCMException as e:
250             logger.debug("Fail to create network[%s] to aai, detail message: %s" % (self.vl_inst_id, e.args[0]))
251         except:
252             logger.error(traceback.format_exc())
253
254     def create_subnet_in_aai(self):
255         logger.debug("CreateVls::create_subnet_in_aai::report subnet[%s] to aai." % self.related_subnetwork_id)
256         try:
257             data = {
258                 "subnets": {
259                     "subnet": [
260                         {
261                             "subnet-id": self.related_subnetwork_id,
262                             "dhcp-enabled": False
263                         }
264                     ]
265                 },
266             }
267             resp_data, resp_status = create_subnet_aai(self.vl_inst_id, self.related_subnetwork_id, data)
268             logger.debug("Success to create subnet[%s] to aai: [%s].", self.related_subnetwork_id, resp_status)
269         except NSLCMException as e:
270             logger.debug("Fail to create subnet[%s] to aai, detail message: %s" % (
271                 self.related_subnetwork_id, e.args[0]))
272         except:
273             logger.error(traceback.format_exc())