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