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