edit activity workflow plan for NS INIT
[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.database.models import VLInstModel, NSInstModel, VNFFGInstModel
22 from lcm.pub.exceptions import NSLCMException
23 from lcm.pub.msapi import extsys, resmgr
24 from lcm.pub.nfvi.vim import const
25 from lcm.pub.nfvi.vim import vimadaptor
26 from lcm.pub.utils.values import ignore_case_get
27
28 logger = logging.getLogger(__name__)
29
30
31 class CreateVls(object):
32     def __init__(self, data):
33         self.owner_id = ignore_case_get(data, "nsInstanceId")
34         self.index = int(float(ignore_case_get(data, "vlIndex")))
35         self.context = ignore_case_get(data, "context")
36         self.additionalParam = ignore_case_get(data, "additionalParamForNs")
37         self.vl_inst_id = str(uuid.uuid4())
38         self.owner_type = OWNER_TYPE.NS
39         self.vld_id = ""
40         self.vl_properties = ""
41         self.vl_inst_name = ""
42         self.related_network_id = ""
43         self.related_subnetwork_id = ""
44         self.vim_id = ""
45         self.vim_name = ""
46         self.tenant = ""
47         self.description = ""
48         self.route_external = ""
49         self.ns_name = ""
50
51     def do(self):
52         try:
53             self.get_data()
54             self.create_vl_to_vim()
55             self.create_vl_to_resmgr()
56             self.save_vl_to_db()
57             return {"result": 0, "detail": "instantiation vl success", "vlId": self.vl_inst_id}
58         except NSLCMException as e:
59             return self.exception_handle(e)
60         except Exception as e:
61             logger.error(traceback.format_exc())
62             return self.exception_handle(e)
63
64     def exception_handle(self, e):
65         detail = "vl instantiation failed, detail message: %s" % e.message
66         logger.error(detail)
67         return {"result": 1, "detail": detail, "vlId": self.vl_inst_id}
68
69     def get_data(self):
70         if isinstance(self.context, (unicode, str)):
71             self.context = json.JSONDecoder().decode(self.context)
72         vl_info = self.get_vl_info(ignore_case_get(self.context, "vls"))
73         self.vld_id = ignore_case_get(vl_info, "vl_id")
74         self.description = ignore_case_get(vl_info, "description")
75         self.vl_properties = ignore_case_get(vl_info, "properties")
76         self.vl_inst_name = ignore_case_get(self.vl_properties, "name")
77         self.route_external = ignore_case_get(vl_info, "route_external")
78         ns_info = NSInstModel.objects.filter(id=self.owner_id)
79         self.ns_name = ns_info[0].name if ns_info else ""
80
81     def get_vl_info(self, vl_all_info):
82         return vl_all_info[self.index - 1]
83
84     def create_vl_to_vim(self):
85         self.vim_id = self.vl_properties["location_info"]["vimid"]
86         if not self.vim_id:
87             self.vim_id = ignore_case_get(self.additionalParam, "location")
88         self.tenant = ignore_case_get(self.vl_properties["location_info"], "tenant")
89         network_data = {
90             "tenant": self.tenant,
91             "network_name": self.vl_properties.get("network_name", ""),
92             "shared": const.SHARED_NET,
93             "network_type": self.vl_properties.get("network_type", ""),
94             "segmentation_id": self.vl_properties.get("segmentation_id", ""),
95             "physical_network": self.vl_properties.get("physical_network", ""),
96             "mtu": self.vl_properties.get("mtu", const.DEFAULT_MTU),
97             "vlan_transparent": self.vl_properties.get("vlan_transparent", False),
98             "subnet_list": [{
99                 "subnet_name": self.vl_properties.get("name", ""),
100                 "cidr": self.vl_properties.get("cidr", "192.168.0.0/24"),
101                 "ip_version": self.vl_properties.get("ip_version", const.IPV4),
102                 "enable_dhcp": self.vl_properties.get("dhcp_enabled", False),
103                 "gateway_ip": self.vl_properties.get("gateway_ip", ""),
104                 "dns_nameservers": self.vl_properties.get("dns_nameservers", ""),
105                 "host_routes": self.vl_properties.get("host_routes", "")}]}
106         startip = self.vl_properties.get("start_ip", "")
107         endip = self.vl_properties.get("end_ip", "")
108         if startip and endip:
109             network_data["subnet_list"][0]["allocation_pools"] = [
110                 {"start": startip, "end": endip}]
111
112         vl_resp = self.create_network_to_vim(network_data)
113         self.related_network_id = vl_resp["id"]
114         self.related_subnetwork_id = vl_resp["subnet_list"][0]["id"] if vl_resp["subnet_list"] else ""
115
116     def create_network_to_vim(self, network_data):
117         vim_resp_body = extsys.get_vim_by_id(self.vim_id)
118         self.vim_name = vim_resp_body["name"]
119         data = {
120             "vimid": self.vim_id,
121             "vimtype": vim_resp_body["type"],
122             "url": vim_resp_body["url"],
123             "user": vim_resp_body["userName"],
124             "passwd": vim_resp_body["password"],
125             "tenant": vim_resp_body["tenant"]}
126         vim_api = vimadaptor.VimAdaptor(data)
127         if not network_data["tenant"]:
128             network_data["tenant"] = vim_resp_body["tenant"]
129         vl_ret = vim_api.create_network(network_data)
130         if vl_ret[0] != 0:
131             logger.error("Send post vl request to vim failed, detail is %s" % vl_ret[1])
132             raise NSLCMException("Send post vl request to vim failed.")
133         return vl_ret[1]
134
135     def save_vl_to_db(self):
136         VLInstModel(vlinstanceid=self.vl_inst_id, vldid=self.vld_id, vlinstancename=self.vl_inst_name,
137                     ownertype=self.owner_type, ownerid=self.owner_id, relatednetworkid=self.related_network_id,
138                     relatedsubnetworkid=self.related_subnetwork_id, vimid=self.vim_id, tenant=self.tenant).save()
139         # do_biz_with_share_lock("create-vllist-in-vnffg-%s" % self.owner_id, self.create_vl_inst_id_in_vnffg)
140         self.create_vl_inst_id_in_vnffg()
141
142     def create_vl_to_resmgr(self):
143         req_param = {
144             "vlInstanceId": self.vl_inst_id,
145             "name": self.vl_properties.get("network_name", ""),
146             "backendId": str(self.related_network_id),
147             "isPublic": "True",
148             "dcName": "",
149             "vimId": str(self.vim_id),
150             "vimName": self.vim_name,
151             "physicialNet": self.vl_properties.get("physical_network", ""),
152             "nsId": self.owner_id,
153             "nsName": self.ns_name,
154             "description": self.description,
155             "networkType": self.vl_properties.get("network_type", ""),
156             "segmentation": str(self.vl_properties.get("segmentation_id", "")),
157             "mtu": str(self.vl_properties.get("mtu", "")),
158             "vlanTransparent": str(self.vl_properties.get("vlan_transparent", "")),
159             "routerExternal": self.route_external,
160             "resourceProviderType": "",
161             "resourceProviderId": ""}
162         resmgr.create_vl(req_param)
163
164     def create_vl_inst_id_in_vnffg(self):
165         if "vnffgs" in self.context:
166             for vnffg_info in self.context["vnffgs"]:
167                 vl_id_list = vnffg_info.get("properties", {}).get("dependent_virtual_link", "")
168                 if vl_id_list:
169                     vl_inst_id_list = []
170                     for vl_id in vl_id_list:
171                         vl_inst_info = VLInstModel.objects.filter(vldid=vl_id)
172                         if vl_inst_info:
173                             vl_inst_id_list.append(vl_inst_info[0].vlinstanceid)
174                         else:
175                             vl_inst_id_list.append("")
176                     vl_inst_id_str = ""
177                     for vl_inst_id in vl_inst_id_list:
178                         vl_inst_id_str += vl_inst_id + ","
179                     vl_inst_id_str = vl_inst_id_str[:-1]
180                     VNFFGInstModel.objects.filter(vnffgdid=vnffg_info["vnffg_id"], nsinstid=self.owner_id).update(
181                         vllist=vl_inst_id_str)