Update the nslcm code to update the resourceName
[vfc/nfvo/lcm.git] / lcm / ns_vnfs / biz / handle_notification.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
15 import logging
16 import traceback
17 import uuid
18
19
20 from rest_framework import status
21 from rest_framework.response import Response
22
23 from lcm.ns_vnfs.enum import INST_TYPE
24 from lcm.pub.config.config import REPORT_TO_AAI
25 from lcm.pub.database.models import (CPInstModel, NfInstModel, PortInstModel,
26                                      VLInstModel, VmInstModel, VNFCInstModel)
27 from lcm.pub.exceptions import NSLCMException, RequestException
28 from lcm.pub.msapi.aai import (create_network_aai, create_vserver_aai,
29                                delete_network_aai, delete_vserver_aai,
30                                query_network_aai, query_vserver_aai)
31 from lcm.pub.msapi.extsys import get_vim_by_id, split_vim_to_owner_region
32 from lcm.pub.utils.values import ignore_case_get
33
34 logger = logging.getLogger(__name__)
35
36
37 class HandleVnfLcmOocNotification(object):
38     def __init__(self, vnfmid, vnfInstanceId, data):
39         logger.debug("[Notify LCM] vnfmid=%s, vnfInstanceId=%s, data=%s" % (vnfmid, vnfInstanceId, data))
40         self.vnfmid = vnfmid
41         self.m_vnfInstanceId = vnfInstanceId
42         self.vnf_instid = get_vnfinstid(self.m_vnfInstanceId, self.vnfmid)
43         self.operation = ignore_case_get(data, 'operation')
44         self.affectedVnfcs = ignore_case_get(data, 'affectedVnfcs')
45         self.affectedVls = ignore_case_get(data, 'affectedVirtualLinks')
46         self.affectedCps = ignore_case_get(data, 'changedExtConnectivity')
47         self.affectedVirtualStorage = ignore_case_get(data, 'affectedVirtualStorages')
48
49     def do_biz(self):
50         try:
51             self.update_Vnfc()
52             self.update_Vl()
53             self.update_Cp()
54             self.update_Storage()
55             if REPORT_TO_AAI:
56                 self.update_network_in_aai()
57             logger.debug("notify lcm end")
58         except NSLCMException as e:
59             exception(e.args[0])
60         except Exception:
61             logger.error(traceback.format_exc())
62             exception('unexpected exception')
63
64     def update_Vnfc(self):
65         for vnfc in self.affectedVnfcs:
66             vnfcInstanceId = ignore_case_get(vnfc, 'id')
67             vduId = ignore_case_get(vnfc, 'vduId')
68             changeType = ignore_case_get(vnfc, 'changeType')
69             computeResource = ignore_case_get(vnfc, 'computeResource')
70             vimId = ignore_case_get(computeResource, "vimConnectionId")
71             vmId = ignore_case_get(computeResource, 'resourceId')
72             vmName = ignore_case_get(computeResource, 'resourceId')  # replaced with resouceId temporarily
73
74             if changeType == 'ADDED':
75                 VNFCInstModel(vnfcinstanceid=vnfcInstanceId, vduid=vduId,
76                               nfinstid=self.vnf_instid, vmid=vmId).save()
77                 VmInstModel(vmid=vmId, vimid=vimId, resouceid=vmId, insttype=INST_TYPE.VNF,
78                             instid=self.vnf_instid, vmname=vmName, hostid='1').save()
79                 if REPORT_TO_AAI:
80                     self.create_vserver_in_aai(vimId, vmId, vmName)
81             elif changeType == 'REMOVED':
82                 if REPORT_TO_AAI:
83                     self.delete_vserver_in_aai(vimId, vmId, vmName)
84                 VNFCInstModel.objects.filter(vnfcinstanceid=vnfcInstanceId).delete()
85             elif changeType == 'MODIFIED':
86                 VNFCInstModel.objects.filter(vnfcinstanceid=vnfcInstanceId).update(vduid=vduId,
87                                                                                    nfinstid=self.vnf_instid,
88                                                                                    vmid=vmId)
89             else:
90                 exception('affectedVnfc struct error: changeType not in {ADDED, REMOVED, MODIFIED, TEMPORARY}')
91         logger.debug("Success to update all vserver to aai.")
92
93     def update_Vl(self):
94         for vl in self.affectedVls:
95             vlInstanceId = ignore_case_get(vl, 'id')
96             vldid = ignore_case_get(vl, 'virtualLinkDescId')
97             changeType = ignore_case_get(vl, 'changeType')
98             networkResource = ignore_case_get(vl, 'networkResource')
99             resourceType = ignore_case_get(networkResource, 'vimLevelResourceType')
100             resourceId = ignore_case_get(networkResource, 'resourceId')
101             resourceName = ignore_case_get(networkResource, 'resourceId')  # replaced with resouceId temporarily
102
103             if resourceType != 'network':
104                 exception('affectedVl struct error: resourceType not euqal network')
105
106             ownerId = self.vnf_instid
107
108             if changeType == 'ADDED':
109                 VLInstModel(vlinstanceid=vlInstanceId, vldid=vldid, vlinstancename=resourceName, ownertype=0,
110                             ownerid=ownerId, relatednetworkid=resourceId, vltype=0).save()
111             elif changeType == 'REMOVED':
112                 VLInstModel.objects.filter(vlinstanceid=vlInstanceId).delete()
113             elif changeType == 'MODIFIED':
114                 VLInstModel.objects.filter(vlinstanceid=vlInstanceId)\
115                     .update(vldid=vldid, vlinstancename=resourceName, ownertype=0, ownerid=ownerId,
116                             relatednetworkid=resourceId, vltype=0)
117             else:
118                 exception('affectedVl struct error: changeType not in {ADDED, REMOVED, MODIFIED, TEMPORARY}')
119
120     def update_Cp(self):
121         for cp in self.affectedCps:
122             # virtualLinkInstanceId = ignore_case_get(cp, 'id')
123             ownertype = 0
124             ownerid = self.vnf_instid
125             for extLinkPorts in ignore_case_get(cp, 'extLinkPorts'):
126                 cpInstanceId = ignore_case_get(extLinkPorts, 'cpInstanceId')
127                 cpdId = ignore_case_get(extLinkPorts, 'id')
128                 # changeType = ignore_case_get(cp, 'changeType')
129                 relatedportId = ''
130
131                 portResource = ignore_case_get(extLinkPorts, 'resourceHandle')
132                 if portResource:
133                     vimId = ignore_case_get(portResource, 'vimConnectionId')
134                     resourceId = ignore_case_get(portResource, 'resourceId')
135                     resourceName = ignore_case_get(portResource, 'resourceProviderId')
136                     tenant = ignore_case_get(portResource, 'tenant')
137                     ipAddress = ignore_case_get(portResource, 'ipAddress')
138                     macAddress = ignore_case_get(portResource, 'macAddress')
139                     instId = ignore_case_get(portResource, 'instId')
140                     portid = ignore_case_get(portResource, 'portId')
141                     networkId = ignore_case_get(portResource, 'networkId')
142                     subnetId = ignore_case_get(portResource, 'subnetId')
143
144                     # portid = str(uuid.uuid4())
145
146                     PortInstModel(portid=portid, networkid=networkId, subnetworkid=subnetId, vimid=vimId,
147                                   resourceid=resourceId, name=resourceName, instid=instId, cpinstanceid=cpInstanceId,
148                                   bandwidth='unknown', operationalstate='active', ipaddress=ipAddress,
149                                   macaddress=macAddress,
150                                   floatipaddress='unknown', serviceipaddress='unknown', typevirtualnic='unknown',
151                                   sfcencapsulation='gre', direction='unknown', tenant=tenant).save()
152                     relatedportId = portid
153
154                 CPInstModel(cpinstanceid=cpInstanceId, cpdid=cpdId, ownertype=ownertype, ownerid=ownerid,
155                             relatedtype=2, relatedport=relatedportId, status='active').save()
156
157     def update_Storage(self):
158         pass
159
160     def update_network_in_aai(self):
161         logger.debug("update_network_in_aai::begin to report network to aai.")
162         try:
163             for vl in self.affectedVls:
164                 vlInstanceId = ignore_case_get(vl, 'id')
165                 # vldid = ignore_case_get(vl, 'vldid')
166                 changeType = ignore_case_get(vl, 'changeType')
167                 networkResource = ignore_case_get(vl, 'networkResource')
168                 resourceType = ignore_case_get(networkResource, 'vimLevelResourceType')
169                 # resourceId = ignore_case_get(networkResource, 'resourceId')
170
171                 if resourceType != 'network':
172                     logger.error('affectedVl struct error: resourceType not euqal network')
173                     raise NSLCMException("affectedVl struct error: resourceType not euqal network")
174
175                 ownerId = self.vnf_instid
176
177                 if changeType in ['ADDED', 'MODIFIED']:
178                     self.create_network_and_subnet_in_aai(vlInstanceId, ownerId)
179                 elif changeType == 'REMOVED':
180                     self.delete_network_and_subnet_in_aai(vlInstanceId)
181                 else:
182                     logger.error('affectedVl struct error: changeType not in {ADDED, REMOVED, MODIFIED, TEMPORARY}')
183         except NSLCMException as e:
184             logger.debug("Fail to create internal network to aai, detail message: %s" % e.args[0])
185         except:
186             logger.error(traceback.format_exc())
187
188     def create_network_and_subnet_in_aai(self, vlInstanceId, ownerId):
189         logger.debug("CreateVls::create_network_in_aai::report network[%s] to aai." % vlInstanceId)
190         try:
191             data = {
192                 "network-id": vlInstanceId,
193                 "network-name": vlInstanceId,
194                 "is-bound-to-vpn": False,
195                 "is-provider-network": True,
196                 "is-shared-network": True,
197                 "is-external-network": True,
198                 "relationship-list": {
199                     "relationship": [
200                         {
201                             "related-to": "generic-vnf",
202                             "relationship-data": [
203                                 {
204                                     "relationship-key": "generic-vnf.vnf-id",
205                                     "relationship-value": ownerId
206                                 }
207                             ]
208                         }
209                     ]
210                 }
211             }
212             resp_data, resp_status = create_network_aai(vlInstanceId, data)
213             logger.debug("Success to create network[%s] to aai: [%s].", vlInstanceId, resp_status)
214         except NSLCMException as e:
215             logger.debug("Fail to create network[%s] to aai, detail message: %s" % (vlInstanceId, e.args[0]))
216         except:
217             logger.error(traceback.format_exc())
218
219     def delete_network_and_subnet_in_aai(self, vlInstanceId):
220         logger.debug("DeleteVls::delete_network_in_aai::delete network[%s] in aai." % vlInstanceId)
221         try:
222             # query network in aai, get resource_version
223             customer_info = query_network_aai(vlInstanceId)
224             if customer_info:
225                 resource_version = customer_info["resource-version"]
226
227                 # delete network from aai
228                 resp_data, resp_status = delete_network_aai(vlInstanceId, resource_version)
229                 logger.debug("Success to delete network[%s] from aai, resp_status: [%s]."
230                              % (vlInstanceId, resp_status))
231         except RequestException:
232             logger.debug("Network has been delted in aai")
233         except NSLCMException as e:
234             logger.debug("Fail to delete network[%s] to aai, detail message: %s" % (vlInstanceId, e.args[0]))
235         except:
236             logger.error(traceback.format_exc())
237
238     def create_vserver_in_aai(self, vim_id, vserver_id, vserver_name):
239         logger.debug("NotifyLcm::create_vserver_in_aai::report vserver instance to aai.")
240         try:
241             cloud_owner, cloud_region_id = split_vim_to_owner_region(vim_id)
242
243             # query vim_info from aai
244             vim_info = get_vim_by_id({"cloud_owner": cloud_owner, 'cloud_regionid': cloud_region_id})
245             tenant_id = vim_info["tenantId"]
246             data = {
247                 "vserver-id": vserver_id,
248                 "vserver-name": vserver_name,
249                 "prov-status": "ACTIVE",
250                 "vserver-selflink": "",
251                 "in-maint": True,
252                 "is-closed-loop-disabled": False,
253                 "relationship-list": {
254                     "relationship": [
255                         {
256                             "related-to": "generic-vnf",
257                             "relationship-data": [
258                                 {
259                                     "relationship-key": "generic-vnf.vnf-id",
260                                     "relationship-value": self.vnf_instid
261                                 }
262                             ]
263                         }
264                     ]
265                 }
266             }
267
268             # create vserver instance in aai
269             resp_data, resp_status = create_vserver_aai(cloud_owner, cloud_region_id, tenant_id, vserver_id, data)
270             logger.debug("Success to create vserver[%s] to aai, vnf instance=[%s], resp_status: [%s]."
271                          % (vserver_id, self.vnf_instid, resp_status))
272         except NSLCMException as e:
273             logger.debug("Fail to create vserver to aai, vnf instance=[%s], detail message: %s"
274                          % (self.vnf_instid, e.args[0]))
275         except:
276             logger.error(traceback.format_exc())
277
278     def delete_vserver_in_aai(self, vim_id, vserver_id, vserver_name):
279         logger.debug("delete_vserver_in_aai start![%s]", vserver_name)
280         try:
281             cloud_owner, cloud_region_id = split_vim_to_owner_region(vim_id)
282             # query vim_info from aai, get tenant
283             vim_info = get_vim_by_id({"cloud_owner": cloud_owner, 'cloud_regionid': cloud_region_id})
284             tenant_id = vim_info["tenantId"]
285
286             # query vserver instance in aai, get resource_version
287             vserver_info = query_vserver_aai(cloud_owner, cloud_region_id, tenant_id, vserver_id)
288             if vserver_info:
289                 resource_version = vserver_info["resource-version"]
290
291                 # delete vserver instance from aai
292                 resp_data, resp_status = delete_vserver_aai(cloud_owner, cloud_region_id,
293                                                             tenant_id, vserver_id, resource_version)
294                 logger.debug(
295                     "Success to delete vserver instance[%s] from aai, resp_status: [%s]." %
296                     (vserver_id, resp_status))
297                 logger.debug("delete_vserver_in_aai end!")
298         except RequestException:
299             logger.debug("Vserver has been deleted from aai")
300         except NSLCMException as e:
301             logger.debug("Fail to delete vserver from aai, detail message: %s" % e.args[0])
302         except:
303             logger.error(traceback.format_exc())
304
305
306 class HandleVnfIdentifierCreationNotification(object):
307     def __init__(self, vnfmId, vnfInstanceId, data):
308         logger.debug("[Notify VNF Identifier Creation] vnfmId=%s, vnfInstanceId=%s, data=%s" % (vnfmId, vnfInstanceId, data))
309         self.vnfm_id = vnfmId
310         self.m_vnf_instance_id = vnfInstanceId
311         self.time_stamp = ignore_case_get(data, 'timeStamp')
312         # TODO: self.subscription_id = ignore_case_get(data, 'subscriptionId')
313         # TODO: self._links = ignore_case_get(data, '_links')
314
315     def do_biz(self):
316         try:
317             NfInstModel(
318                 nfinstid=str(uuid.uuid4()),
319                 mnfinstid=self.m_vnf_instance_id,
320                 vnfm_inst_id=self.vnfm_id,
321                 create_time=self.time_stamp
322             ).save()
323             logger.debug("Notify VNF identifier creation end.")
324         except Exception:
325             logger.error(traceback.format_exc())
326             exception('unexpected exception')
327
328
329 class HandleVnfIdentifierDeletionNotification(object):
330     def __init__(self, vnfmId, vnfInstanceId, data):
331         logger.debug("[Notify VNF Identifier Deletion] vnfmId=%s, vnfInstanceId=%s, data=%s" % (vnfmId, vnfInstanceId, data))
332         self.vnfm_id = vnfmId
333         self.m_vnf_instance_id = vnfInstanceId
334         self.vnf_instance_id = get_vnfinstid(self.m_vnf_instance_id, self.vnfm_id)
335         self.time_stamp = ignore_case_get(data, 'timeStamp')
336         # TODO: self.subscription_id = ignore_case_get(data, 'subscriptionId')
337         # TODO: self._links = ignore_case_get(data, '_links')
338
339     def do_biz(self):
340         try:
341             nf_insts = NfInstModel.objects.filter(
342                 mnfinstid=self.m_vnf_instance_id, vnfm_inst_id=self.vnfm_id)
343             if nf_insts.exists():
344                 nf_insts.delete()
345             logger.debug("Notify VNF identifier deletion end.")
346         except Exception:
347             logger.error(traceback.format_exc())
348             exception('unexpected exception')
349
350
351 def get_vnfinstid(mnfinstid, vnfm_inst_id):
352     logger.debug("vnfinstid in vnfm is:%s,vnfmid is:%s", mnfinstid, vnfm_inst_id)
353     logger.debug("mnfinstid=%s, vnfm_inst_id=%s", mnfinstid, vnfm_inst_id)
354     nfinst = NfInstModel.objects.filter(mnfinstid=mnfinstid, vnfm_inst_id=vnfm_inst_id).first()
355     if nfinst:
356         return nfinst.nfinstid
357     raise NSLCMException("vnfinstid not exist")
358
359
360 def exception(error_msg):
361     logger.error('Notify Lcm failed, detail message: %s' % error_msg)
362     return Response(data={'error': '%s' % error_msg}, status=status.HTTP_409_CONFLICT)