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