Fix vfc-nslcm vl creation to aai
[vfc/nfvo/lcm.git] / lcm / ns / vnfs / notify_lcm.py
1 # Copyright 2016 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 import uuid
15 import logging
16 import traceback
17
18 from rest_framework import status
19 from rest_framework.response import Response
20 from lcm.ns.vnfs.const import INST_TYPE
21 from lcm.pub.config.config import REPORT_TO_AAI
22 from lcm.pub.exceptions import NSLCMException
23 from lcm.pub.database.models import VNFCInstModel, VLInstModel, NfInstModel, PortInstModel, CPInstModel, VmInstModel
24 from lcm.pub.msapi.aai import create_network_aai, query_network_aai, delete_network_aai
25 from lcm.pub.utils.values import ignore_case_get
26
27
28 logger = logging.getLogger(__name__)
29
30
31 class NotifyLcm(object):
32     def __init__(self, vnfmid, vnfInstanceId, data):
33         logger.debug("[Notify LCM] vnfmid=%s, vnfInstanceId=%s, data=%s" % (vnfmid, vnfInstanceId, data))
34         self.vnf_instid = ''
35         self.vnfmid = vnfmid
36         self.m_vnfInstanceId = vnfInstanceId
37         self.status = ignore_case_get(data, 'status')
38         self.operation = ignore_case_get(data, 'operation')
39         self.lcm_jobid = ignore_case_get(data, 'jobId')
40         self.vnfdmodule = ignore_case_get(data, 'vnfdmodule')
41         self.affectedVnfc = ignore_case_get(data, 'affectedVnfc')
42         self.affectedVl = ignore_case_get(data, 'affectedVl')
43         self.affectedCp = ignore_case_get(data, 'affectedCp')
44         self.affectedVirtualStorage = ignore_case_get(data, 'affectedVirtualStorage')
45
46     def do_biz(self):
47         try:
48             self.vnf_instid = self.get_vnfinstid(self.m_vnfInstanceId, self.vnfmid)
49             self.update_Vnfc()
50             self.update_Vl()
51             self.update_Cp()
52             self.update_Storage()
53             if REPORT_TO_AAI:
54                 self.update_network_in_aai()
55             logger.debug("notify lcm end")
56         except NSLCMException as e:
57             self.exception(e.message)
58         except Exception:
59             logger.error(traceback.format_exc())
60             self.exception('unexpected exception')
61
62     def get_vnfinstid(self, mnfinstid, vnfm_inst_id):
63         nfinst = NfInstModel.objects.filter(mnfinstid=mnfinstid, vnfm_inst_id=vnfm_inst_id).first()
64         if nfinst:
65             return nfinst.nfinstid
66         else:
67             self.exception('vnfinstid not exist')
68
69     def exception(self, error_msg):
70         logger.error('Notify Lcm failed, detail message: %s' % error_msg)
71         return Response(data={'error': '%s' % error_msg}, status=status.HTTP_409_CONFLICT)
72
73     def update_Vnfc(self):
74         for vnfc in self.affectedVnfc:
75             vnfcInstanceId = ignore_case_get(vnfc, 'vnfcInstanceId')
76             vduId = ignore_case_get(vnfc, 'vduId')
77             changeType = ignore_case_get(vnfc, 'changeType')
78             vimId = ignore_case_get(vnfc, 'vimid')
79             vmId = ignore_case_get(vnfc, 'vmid')
80             vmName = ignore_case_get(vnfc, 'vmname')
81
82             if changeType == 'added':
83                 VNFCInstModel(vnfcinstanceid=vnfcInstanceId, vduid=vduId,
84                               nfinstid=self.vnf_instid, vmid=vmId).save()
85                 VmInstModel(vmid=vmId, vimid=vimId, resouceid=vmId, insttype=INST_TYPE.VNF,
86                             instid=self.vnf_instid, vmname=vmName, hostid='1').save()
87             elif changeType == 'removed':
88                 VNFCInstModel.objects.filter(vnfcinstanceid=vnfcInstanceId).delete()
89             elif changeType == 'modified':
90                 VNFCInstModel.objects.filter(vnfcinstanceid=vnfcInstanceId).update(vduid=vduId,
91                                                                                    nfinstid=self.vnf_instid,
92                                                                                    vmid=vmId)
93             else:
94                 self.exception('affectedVnfc struct error: changeType not in {added,removed,modified}')
95
96     def update_Vl(self):
97         for vl in self.affectedVl:
98             vlInstanceId = ignore_case_get(vl, 'vlInstanceId')
99             vldid = ignore_case_get(vl, 'vldid')
100             changeType = ignore_case_get(vl, 'changeType')
101             networkResource = ignore_case_get(vl, 'networkResource')
102             resourceType = ignore_case_get(networkResource, 'resourceType')
103             resourceId = ignore_case_get(networkResource, 'resourceId')
104
105             if resourceType != 'network':
106                 self.exception('affectedVl struct error: resourceType not euqal network')
107
108             ownerId = self.vnf_instid
109             ownerId = self.get_vnfinstid(self.vnf_instid, self.vnfmid)
110
111             if changeType == 'added':
112                 VLInstModel(vlInstanceId=vlInstanceId, vldId=vldid, ownerType=0, ownerId=ownerId,
113                             relatedNetworkId=resourceId, vlType=0).save()
114             elif changeType == 'removed':
115                 VLInstModel.objects.filter(vlInstanceId=vlInstanceId).delete()
116             elif changeType == 'modified':
117                 VLInstModel.objects.filter(vlInstanceId=vlInstanceId)\
118                     .update(vldId=vldid, ownerType=0, ownerId=ownerId, relatedNetworkId=resourceId, vlType=0)
119             else:
120                 self.exception('affectedVl struct error: changeType not in {added,removed,modified}')
121
122     def update_Cp(self):
123         for cp in self.affectedCp:
124             virtualLinkInstanceId = ignore_case_get(cp, 'virtualLinkInstanceId')
125             ownertype = ignore_case_get(cp, 'ownertype')
126             if not ownertype:
127                 ownertype = 0
128             ownerid = self.vnf_instid if str(ownertype) == "0" else ignore_case_get(cp, 'ownerid')
129             cpInstanceId = ignore_case_get(cp, 'cpinstanceid')
130             cpdId = ignore_case_get(cp, 'cpdid')
131             changeType = ignore_case_get(cp, 'changetype')
132             relatedportId = ''
133             portResource = ignore_case_get(cp, 'portResource')
134             if portResource:
135                 vimId = ignore_case_get(portResource, 'vimid')
136                 resourceId = ignore_case_get(portResource, 'resourceid')
137                 resourceName = ignore_case_get(portResource, 'resourceName')
138                 tenant = ignore_case_get(portResource, 'tenant')
139                 ipAddress = ignore_case_get(portResource, 'ipAddress')
140                 macAddress = ignore_case_get(portResource, 'macAddress')
141                 instId = ignore_case_get(portResource, 'instId')
142                 portid = str(uuid.uuid4())
143                 PortInstModel(portid=portid, networkid='unknown', subnetworkid='unknown', vimid=vimId,
144                               resourceid=resourceId, name=resourceName, instid=instId, cpinstanceid=cpInstanceId,
145                               bandwidth='unknown', operationalstate='active', ipaddress=ipAddress, macaddress=macAddress,
146                               floatipaddress='unknown', serviceipaddress='unknown', typevirtualnic='unknown',
147                               sfcencapsulation='gre', direction='unknown', tenant=tenant).save()
148                 relatedportId = portid
149
150             if changeType == 'added':
151                 CPInstModel(cpinstanceid=cpInstanceId, cpdid=cpdId, ownertype=ownertype, ownerid=ownerid,
152                             relatedtype=2, relatedport=relatedportId, status='active').save()
153             elif changeType == 'removed':
154                 CPInstModel.objects.filter(cpinstanceid=cpInstanceId).delete()
155             elif changeType == 'changed':
156                 CPInstModel.objects.filter(cpinstanceid=cpInstanceId).update(cpdid=cpdId, ownertype=ownertype,
157                                                                              ownerid=ownerid,
158                                                                              vlinstanceid=virtualLinkInstanceId,
159                                                                              relatedtype=2, relatedport=relatedportId)
160             else:
161                 self.exception('affectedVl struct error: changeType not in {added,removed,modified}')
162
163     def update_Storage(self):
164         pass
165
166     def update_vnf_by_vnfdmodule(self):
167         NfInstModel.objects.filter(nfinstid=self.vnf_instid).update(vnfd_model=self.vnfdmodule)
168
169     def update_network_in_aai(self):
170         logger.debug("update_network_in_aai::begin to report network to aai.")
171         try:
172             for vl in self.affectedVl:
173                 vlInstanceId = ignore_case_get(vl, 'vlInstanceId')
174                 # vldid = ignore_case_get(vl, 'vldid')
175                 changeType = ignore_case_get(vl, 'changeType')
176                 networkResource = ignore_case_get(vl, 'networkResource')
177                 resourceType = ignore_case_get(networkResource, 'resourceType')
178                 # resourceId = ignore_case_get(networkResource, 'resourceId')
179
180                 if resourceType != 'network':
181                     logger.error('affectedVl struct error: resourceType not euqal network')
182                     raise NSLCMException("affectedVl struct error: resourceType not euqal network")
183
184                 # ownerId = self.vnf_instid
185                 ownerId = self.get_vnfinstid(self.vnf_instid, self.vnfmid)
186
187                 if changeType in ['added', 'modified']:
188                     self.create_network_and_subnet_in_aai(vlInstanceId, ownerId)
189                 elif changeType == 'removed':
190                     self.delete_network_and_subnet_in_aai(vlInstanceId)
191                 else:
192                     logger.error('affectedVl struct error: changeType not in {added,removed,modified}')
193         except NSLCMException as e:
194             logger.debug("Fail to create internal network to aai, detail message: %s" % e.message)
195         except:
196             logger.error(traceback.format_exc())
197
198     def create_network_and_subnet_in_aai(self, vlInstanceId, ownerId):
199         logger.debug("CreateVls::create_network_in_aai::report network[%s] to aai." % vlInstanceId)
200         try:
201             data = {
202                 "network-id": vlInstanceId,
203                 "network-name": vlInstanceId,
204                 "is-bound-to-vpn": False,
205                 "is-provider-network": True,
206                 "is-shared-network": True,
207                 "is-external-network": True,
208                 "relationship-list": {
209                     "relationship": [
210                         {
211                             "related-to": "generic-vnf",
212                             "relationship-data": [
213                                 {
214                                     "relationship-key": "generic-vnf.vnf-id",
215                                     "relationship-value": ownerId
216                                 }
217                             ]
218                         }
219                     ]
220                 }
221             }
222             resp_data, resp_status = create_network_aai(vlInstanceId, data)
223             logger.debug("Success to create network[%s] to aai: [%s].", vlInstanceId, resp_status)
224         except NSLCMException as e:
225             logger.debug("Fail to create network[%s] to aai, detail message: %s" % (vlInstanceId, e.message))
226         except:
227             logger.error(traceback.format_exc())
228
229     def delete_network_and_subnet_in_aai(self, vlInstanceId):
230         logger.debug("DeleteVls::delete_network_in_aai::delete network[%s] in aai." % vlInstanceId)
231         try:
232             # query network in aai, get resource_version
233             customer_info = query_network_aai(vlInstanceId)
234             resource_version = customer_info["resource-version"]
235
236             # delete network from aai
237             resp_data, resp_status = delete_network_aai(vlInstanceId, resource_version)
238             logger.debug("Success to delete network[%s] from aai, resp_status: [%s]."
239                          % (vlInstanceId, resp_status))
240         except NSLCMException as e:
241             logger.debug("Fail to delete network[%s] to aai, detail message: %s" % (vlInstanceId, e.message))
242         except:
243             logger.error(traceback.format_exc())