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