Dynamic Cloud Owner Support
[so.git] / bpmn / so-bpmn-infrastructure-common / src / main / groovy / org / onap / so / bpmn / infrastructure / scripts / DoDeleteVfModuleFromVnf.groovy
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP - SO
4  * ================================================================================
5  * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
6  * ================================================================================
7  * Licensed under the Apache License, Version 2.0 (the "License");
8  * you may not use this file except in compliance with the License.
9  * You may obtain a copy of the License at
10  * 
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  * 
13  * Unless required by applicable law or agreed to in writing, software
14  * distributed under the License is distributed on an "AS IS" BASIS,
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * See the License for the specific language governing permissions and
17  * limitations under the License.
18  * ============LICENSE_END=========================================================
19  */
20
21 package org.onap.so.bpmn.infrastructure.scripts
22
23 import static org.apache.commons.lang3.StringUtils.*
24
25 import org.camunda.bpm.engine.delegate.BpmnError
26 import org.camunda.bpm.engine.delegate.DelegateExecution
27 import org.onap.so.bpmn.common.scripts.AaiUtil
28 import org.onap.so.bpmn.common.scripts.ExceptionUtil
29 import org.onap.so.bpmn.common.scripts.MsoUtils
30 import org.onap.so.bpmn.common.scripts.SDNCAdapterUtils
31 import org.onap.so.bpmn.common.scripts.VfModule
32 import org.onap.so.bpmn.common.scripts.VfModuleBase
33 import org.onap.so.bpmn.core.UrnPropertiesReader
34 import org.onap.so.bpmn.core.WorkflowException
35 import org.onap.so.bpmn.core.json.JsonUtils
36 import org.onap.so.client.graphinventory.entities.uri.Depth
37 import org.onap.so.client.aai.AAIObjectPlurals
38 import org.onap.so.client.aai.AAIObjectType
39 import org.onap.so.client.aai.entities.uri.AAIResourceUri
40 import org.onap.so.client.aai.entities.uri.AAIUriFactory
41 import org.onap.so.logger.MessageEnum
42 import org.onap.so.logger.MsoLogger
43 import org.onap.so.rest.APIResponse
44 import org.springframework.web.util.UriUtils
45
46 public class DoDeleteVfModuleFromVnf extends VfModuleBase {
47         private static final MsoLogger msoLogger = MsoLogger.getMsoLogger(MsoLogger.Catalog.BPEL, DoDeleteVfModuleFromVnf.class);
48         
49         def Prefix="DDVFMV_"
50         ExceptionUtil exceptionUtil = new ExceptionUtil()
51         JsonUtils jsonUtil = new JsonUtils()
52
53         public void initProcessVariables(DelegateExecution execution) {
54                 execution.setVariable("prefix",Prefix)
55                 execution.setVariable("DDVFMV_contrailNetworkPolicyFqdnList", null)
56         }
57
58         // parse the incoming request
59         public void preProcessRequest(DelegateExecution execution) {
60
61                 initProcessVariables(execution)
62
63                 try {
64                         
65                                 // Building Block-type request
66
67                                 // Set mso-request-id to request-id for VNF Adapter interface
68                                 String requestId = execution.getVariable("msoRequestId")
69                                 execution.setVariable("mso-request-id", requestId)
70                                 execution.setVariable("requestId", requestId)
71                                 msoLogger.debug("msoRequestId: " + requestId)
72                                 String tenantId = execution.getVariable("tenantId")
73                                 msoLogger.debug("tenantId: " + tenantId)                                
74                                 String cloudSiteId = execution.getVariable("lcpCloudRegionId")
75                                 execution.setVariable("cloudSiteId", cloudSiteId)
76                                 msoLogger.debug("cloudSiteId: " + cloudSiteId)
77                                 // Source is HARDCODED
78                                 String source = "VID"
79                                 execution.setVariable("source", source)
80                                 // isVidRequest is hardcoded to "true"
81                                 execution.setVariable("isVidRequest", "true")
82                                 // SrvInstId is hardcoded to empty
83                                 execution.setVariable("srvInstId", "")
84                                 // ServiceId is hardcoded to empty
85                                 execution.setVariable("serviceId", "")
86                                 String serviceInstanceId = execution.getVariable("serviceInstanceId")
87                                 msoLogger.debug("serviceInstanceId: " + serviceInstanceId)
88                                 String vnfId = execution.getVariable("vnfId")
89                                 msoLogger.debug("vnfId: " + vnfId)
90                                 String vfModuleId = execution.getVariable("vfModuleId")
91                                 msoLogger.debug("vfModuleId: " + vfModuleId)
92                                 if (serviceInstanceId == null || serviceInstanceId.isEmpty()) {
93                                         execution.setVariable(Prefix + "serviceInstanceIdToSdnc", vfModuleId)
94                                 }
95                                 else {
96                                         execution.setVariable(Prefix + "serviceInstanceIdToSdnc", serviceInstanceId)
97                                 }                               
98                                 
99                                 String sdncVersion = execution.getVariable("sdncVersion")
100                                 if (sdncVersion == null) {
101                                         sdncVersion = "1707"
102                                 }
103                                 execution.setVariable(Prefix + "sdncVersion", sdncVersion)
104                                 msoLogger.debug("Incoming Sdnc Version is: " + sdncVersion)                             
105                                 
106                                 String sdncCallbackUrl = (String) UrnPropertiesReader.getVariable("mso.workflow.sdncadapter.callback",execution)
107                                 if (sdncCallbackUrl == null || sdncCallbackUrl.trim().isEmpty()) {
108                                         def msg = 'Required variable \'mso.workflow.sdncadapter.callback\' is missing'
109                                         msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, msg, "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, "Exception");
110                                         exceptionUtil.buildAndThrowWorkflowException(execution, 2000, msg)
111                                 }
112                                 execution.setVariable("sdncCallbackUrl", sdncCallbackUrl)
113                                 msoLogger.debug("SDNC Callback URL: " + sdncCallbackUrl)
114                                 msoLogger.debug("SDNC Callback URL is: " + sdncCallbackUrl)
115
116                         
117                         
118                 }catch(BpmnError b){
119                         throw b
120                 }catch(Exception e){
121                         msoLogger.debug("Exception is: " + e.getMessage())
122                         exceptionUtil.buildAndThrowWorkflowException(execution, 2000, "Internal Error encountered in PreProcess method!")
123                 }
124         }
125         
126         public void queryAAIForVfModule(DelegateExecution execution) {
127                 def method = getClass().getSimpleName() + '.queryAAIForVfModule(' +
128                         'execution=' + execution.getId() +
129                         ')'
130
131                 msoLogger.trace('Entered ' + method)
132
133                 try {
134                         def vnfId = execution.getVariable('vnfId')
135
136                         AaiUtil aaiUriUtil = new AaiUtil(this)
137                         AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIObjectType.GENERIC_VNF, vnfId).depth(Depth.ONE)
138                         
139                         String endPoint = aaiUriUtil.createAaiUri(uri)
140
141                         msoLogger.debug("DoDeleteVfModuleFromVnf: AAI endPoint  : " + endPoint)
142
143                         try {
144                                 msoLogger.debug("DoDeleteVfModuleFromVnf: - invoking httpGet to AAI")
145                                 APIResponse response = aaiUriUtil.executeAAIGetCall(execution, endPoint)
146
147                                 def responseData = response.getResponseBodyAsString()
148                                 execution.setVariable('DDVMFV_getVnfResponseCode', response.getStatusCode())
149                                 execution.setVariable('DDVMFV_getVnfResponse', responseData)
150
151                                 msoLogger.debug("DoDeleteVfModuleFromVnf: AAI Response : " + responseData)
152                                 msoLogger.debug("DoDeleteVfModuleFromVnf: AAI ResponseCode : " + response.getStatusCode())
153
154                                 msoLogger.debug('Response code:' + response.getStatusCode())
155                                 msoLogger.debug('Response:' + System.lineSeparator() + responseData)                    
156                                 
157                         } catch (Exception ex) {
158                                 ex.printStackTrace()
159                                 msoLogger.debug('Exception occurred while executing AAI GET:' + ex.getMessage())
160                                 execution.setVariable('DDVMFV_getVnfResponseCode', 500)
161                                 execution.setVariable('DDVFMV_getVnfResponse', 'AAI GET Failed:' + ex.getMessage())
162                         }
163                         msoLogger.trace('Exited ' + method)
164                 } catch (BpmnError e) {
165                         throw e;
166                 } catch (Exception e) {
167                         msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, 'Caught exception in ' + method, "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, "Exception is:\n" + e);
168                         exceptionUtil.buildAndThrowWorkflowException(execution, 1002, 'Error in queryAAIForVfModule(): ' + e.getMessage())
169                 }
170         }
171         
172         /**
173          * Validate the VF Module.  That is, confirm that a VF Module with the input VF Module ID
174          * exists in the retrieved Generic VNF.  Then, check to make sure that if that VF Module
175          * is the base VF Module and it's not the only VF Module for this Generic VNF, that we're not
176          * attempting to delete it.
177          *
178          * @param execution The flow's execution instance.
179          */
180         public void validateVfModule(DelegateExecution execution) {
181                 def method = getClass().getSimpleName() + '.validateVfModule(' +
182                         'execution=' + execution.getId() +
183                         ')'
184                 def isDebugLogEnabled = execution.getVariable('isDebugLogEnabled')
185                 msoLogger.trace('Entered ' + method)
186
187                 try {
188                         def genericVnf = execution.getVariable('DDVMFV_getVnfResponse')
189                         def vnfId = execution.getVariable('_vnfId')
190                         def vfModuleId = execution.getVariable('vfModuleId')                    
191                         def VfModule vfModule = findVfModule(genericVnf, vfModuleId)
192                         if (vfModule == null) {
193                                 def String msg = 'VF Module \'' + vfModuleId + '\' does not exist in Generic VNF \'' + vnfId + '\''
194                                 msoLogger.debug(msg)
195                                 exceptionUtil.buildAndThrowWorkflowException(execution, 1002, msg)
196                         } else {
197                                 
198                                 if (isDebugLogEnabled) {
199                                         msoLogger.debug('VF Module \'' + vfModuleId + '\': isBaseVfModule=' + vfModule.isBaseVfModule() + ', isOnlyVfModule=' + vfModule.isOnlyVfModule())
200                                 }
201                                 if (vfModule.isBaseVfModule() && !vfModule.isOnlyVfModule()) {
202                                         def String msg = 'Cannot delete VF Module \'' + vfModuleId +
203                                                 '\'since it is the base VF Module and it\'s not the only VF Module in Generic VNF \'' + vnfId + '\''
204                                                 msoLogger.debug("Received a BAD Response from VNF Adapter for CREATE_VF_MODULE Call.")
205                                                 exceptionUtil.buildAndThrowWorkflowException(execution, 1002, "VNF Adapter Error")
206                                 }
207                                 
208                                 def heatStackId = vfModule.getElementText('heat-stack-id')
209                                 execution.setVariable('DDVMFV_heatStackId', heatStackId)
210                                 msoLogger.debug('VF Module heatStackId retrieved from AAI: ' + heatStackId)
211                         }
212
213                         msoLogger.trace('Exited ' + method)
214                 } catch (BpmnError e) {
215                         throw e;
216                 } catch (Exception e) {
217                         msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, 'Caught exception in ' + method, "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, "Exception is:\n" + e);
218                         exceptionUtil.buildAndThrowWorkflowException(execution, 1002, 'Error in validateVfModule(): ' + e.getMessage())
219                 }
220         }
221
222
223         public void preProcessSDNCDeactivateRequest(DelegateExecution execution){
224
225                 execution.setVariable("prefix", Prefix)
226                 msoLogger.trace("STARTED preProcessSDNCDeactivateRequest ")
227                 
228                 def serviceInstanceId = execution.getVariable("serviceInstanceId")
229         
230                 try{
231                         //Build SDNC Request
232                         
233                         String deactivateSDNCRequest = buildSDNCRequest(execution, serviceInstanceId, "deactivate")
234         
235                         deactivateSDNCRequest = utils.formatXml(deactivateSDNCRequest)
236                         execution.setVariable("DDVMFV_deactivateSDNCRequest", deactivateSDNCRequest)
237                         msoLogger.debug("Outgoing DeactivateSDNCRequest is: \n" + deactivateSDNCRequest)
238                         
239         
240                 }catch(Exception e){
241                         msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, "Exception Occured Processing preProcessSDNCDeactivateRequest. Exception is:\n" + e, "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, "Exception is:\n" + e);
242                         exceptionUtil.buildAndThrowWorkflowException(execution, 1002, "Error Occurred during preProcessSDNCDeactivateRequest Method:\n" + e.getMessage())
243                 }
244                 msoLogger.trace("COMPLETED preProcessSDNCDeactivateRequest ")
245         }
246
247         public void preProcessSDNCUnassignRequest(DelegateExecution execution) {
248                 def method = getClass().getSimpleName() + '.preProcessSDNCUnassignRequest(' +
249                         'execution=' + execution.getId() +
250                         ')'
251
252                 msoLogger.trace('Entered ' + method)
253                 execution.setVariable("prefix", Prefix)
254                 msoLogger.trace("STARTED preProcessSDNCUnassignRequest Process ")
255                 try{                    
256                         String serviceInstanceId = execution.getVariable("serviceInstanceId")
257         
258                         String unassignSDNCRequest = buildSDNCRequest(execution, serviceInstanceId, "unassign")
259         
260                         execution.setVariable("DDVMFV_unassignSDNCRequest", unassignSDNCRequest)
261                         msoLogger.debug("Outgoing UnassignSDNCRequest is: \n" + unassignSDNCRequest)
262                         
263         
264                 }catch(Exception e){
265                         msoLogger.debug("Exception Occured Processing preProcessSDNCUnassignRequest. Exception is:\n" + e)
266                         exceptionUtil.buildAndThrowWorkflowException(execution, 1002, "Error Occured during  preProcessSDNCUnassignRequest Method:\n" + e.getMessage())
267                 }
268                 msoLogger.trace("COMPLETED  preProcessSDNCUnassignRequest Process ")
269         }
270
271         public String buildSDNCRequest(DelegateExecution execution, String svcInstId, String action){
272         
273                         String uuid = execution.getVariable('testReqId') // for junits
274                         if(uuid==null){
275                                 uuid = execution.getVariable("msoRequestId") + "-" +    System.currentTimeMillis()
276                         }
277                         def callbackURL = execution.getVariable("sdncCallbackUrl")      
278                         def requestId = execution.getVariable("msoRequestId")
279                         def serviceId = execution.getVariable("serviceId")
280                         def serviceInstanceId = execution.getVariable("serviceInstanceId")
281                         def vfModuleId = execution.getVariable("vfModuleId")
282                         def source = execution.getVariable("source")
283                         def vnfId = execution.getVariable("vnfId")
284                                 
285                         def sdncVersion = execution.getVariable(Prefix + "sdncVersion")
286                         
287                         String sdncRequest =
288                         """<sdncadapterworkflow:SDNCAdapterWorkflowRequest xmlns:ns5="http://org.onap/so/request/types/v1"
289                                                                                                         xmlns:sdncadapterworkflow="http://org.onap/so/workflow/schema/v1"
290                                                                                                         xmlns:sdncadapter="http://org.onap.so/workflow/sdnc/adapter/schema/v1">
291            <sdncadapter:RequestHeader>
292                                 <sdncadapter:RequestId>${MsoUtils.xmlEscape(uuid)}</sdncadapter:RequestId>
293                                 <sdncadapter:SvcInstanceId>${MsoUtils.xmlEscape(svcInstId)}</sdncadapter:SvcInstanceId>
294                                 <sdncadapter:SvcAction>${MsoUtils.xmlEscape(action)}</sdncadapter:SvcAction>
295                                 <sdncadapter:SvcOperation>vf-module-topology-operation</sdncadapter:SvcOperation>
296                                 <sdncadapter:CallbackUrl>${MsoUtils.xmlEscape(callbackURL)}</sdncadapter:CallbackUrl>
297                                 <sdncadapter:MsoAction>generic-resource</sdncadapter:MsoAction>
298                 </sdncadapter:RequestHeader>
299         <sdncadapterworkflow:SDNCRequestData>
300                 <request-information>
301                         <request-id>${MsoUtils.xmlEscape(requestId)}</request-id>
302                         <request-action>DeleteVfModuleInstance</request-action>
303                         <source>${MsoUtils.xmlEscape(source)}</source>
304                         <notification-url/>
305                         <order-number/>
306                         <order-version/>
307                 </request-information>
308                 <service-information>
309                         <service-id/>
310                         <subscription-service-type/>                    
311                         <service-instance-id>${MsoUtils.xmlEscape(serviceInstanceId)}</service-instance-id>
312                         <global-customer-id/>
313                 </service-information>
314                 <vnf-information>
315                         <vnf-id>${MsoUtils.xmlEscape(vnfId)}</vnf-id>
316                         <vnf-type/>                     
317                 </vnf-information>
318                 <vf-module-information>
319                         <vf-module-id>${MsoUtils.xmlEscape(vfModuleId)}</vf-module-id>
320                 </vf-module-information>
321                 <vf-module-request-input/>              
322         </sdncadapterworkflow:SDNCRequestData>
323         </sdncadapterworkflow:SDNCAdapterWorkflowRequest>"""
324         
325                 msoLogger.debug("sdncRequest:  " + sdncRequest)
326                 return sdncRequest
327         }
328         
329         public void validateSDNCResponse(DelegateExecution execution, String response, String method){
330
331                 execution.setVariable("prefix",Prefix)
332                 msoLogger.trace("STARTED ValidateSDNCResponse Process")
333         
334                 WorkflowException workflowException = execution.getVariable("WorkflowException")
335                 boolean successIndicator = execution.getVariable("SDNCA_SuccessIndicator")
336         
337                 msoLogger.debug("workflowException: " + workflowException)
338         
339                 SDNCAdapterUtils sdncAdapterUtils = new SDNCAdapterUtils(this)
340                 sdncAdapterUtils.validateSDNCResponse(execution, response, workflowException, successIndicator)
341         
342                 msoLogger.debug("SDNCResponse: " + response)
343         
344                 String sdncResponse = response
345                 if(execution.getVariable(Prefix + 'sdncResponseSuccess') == true){
346                         msoLogger.debug("Received a Good Response from SDNC Adapter for " + method + " SDNC Call.  Response is: \n" + sdncResponse)
347                 }else{
348                         msoLogger.debug("Received a BAD Response from SDNC Adapter for " + method + " SDNC Call.")
349                         throw new BpmnError("MSOWorkflowException")
350                 }
351                 msoLogger.trace("COMPLETED ValidateSDNCResponse Process")
352         }
353
354
355         // parse the incoming DELETE_VF_MODULE request
356         // and formulate the outgoing VnfAdapterDeleteV1 request
357         public void prepVNFAdapterRequest(DelegateExecution execution) {
358
359                 def requestId = UUID.randomUUID().toString()
360                 def origRequestId = execution.getVariable('requestId')
361                 def srvInstId = execution.getVariable("serviceInstanceId")
362                 def aicCloudRegion = execution.getVariable("cloudSiteId")
363                 def vnfId = execution.getVariable("vnfId")
364                 def vfModuleId = execution.getVariable("vfModuleId")
365                 def vfModuleStackId = execution.getVariable('DDVMFV_heatStackId')
366                 def tenantId = execution.getVariable("tenantId")
367                 def messageId = execution.getVariable('requestId') + '-' +
368                         System.currentTimeMillis()
369                 def notificationUrl = createCallbackURL(execution, "VNFAResponse", messageId)
370                 def useQualifiedHostName = UrnPropertiesReader.getVariable("mso.use.qualified.host",execution)
371                 if ('true'.equals(useQualifiedHostName)) {
372                         notificationUrl = utils.getQualifiedHostNameForCallback(notificationUrl)
373                 }
374
375                 String request = """
376                         <deleteVfModuleRequest>
377                             <cloudSiteId>${MsoUtils.xmlEscape(aicCloudRegion)}</cloudSiteId>
378                             <tenantId>${MsoUtils.xmlEscape(tenantId)}</tenantId>
379                             <vnfId>${MsoUtils.xmlEscape(vnfId)}</vnfId>
380                             <vfModuleId>${MsoUtils.xmlEscape(vfModuleId)}</vfModuleId>
381                             <vfModuleStackId>${MsoUtils.xmlEscape(vfModuleStackId)}</vfModuleStackId>
382                             <skipAAI>true</skipAAI>
383                             <msoRequest>
384                                 <requestId>${MsoUtils.xmlEscape(origRequestId)}</requestId>
385                                 <serviceInstanceId>${MsoUtils.xmlEscape(srvInstId)}</serviceInstanceId>
386                             </msoRequest>
387                             <messageId>${MsoUtils.xmlEscape(messageId)}</messageId>
388                             <notificationUrl>${MsoUtils.xmlEscape(notificationUrl)}</notificationUrl>
389                         </deleteVfModuleRequest>
390                         """ as String
391
392                 msoLogger.debug("vnfAdapterRestV1Request: " + request)
393                 msoLogger.debug("deleteVfModuleRequest: " + request)
394                 execution.setVariable("vnfAdapterRestV1Request", request)
395         }
396
397         
398         // generates a WorkflowException if
399         //              -
400         public void handleDoDeleteVfModuleFailure(DelegateExecution execution) {
401                 msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, "AAI error occurred deleting the Generic Vnf: " + execution.getVariable("DDVFMV_deleteGenericVnfResponse"), "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, "Exception");
402                 String processKey = getProcessKey(execution);
403                 WorkflowException exception = new WorkflowException(processKey, 5000,
404                         execution.getVariable("DDVFMV_deleteGenericVnfResponse"))
405                 execution.setVariable("WorkflowException", exception)
406         }
407         
408         public void postProcessVNFAdapterRequest(DelegateExecution execution) {
409                 def method = getClass().getSimpleName() + '.postProcessVNFAdapterRequest(' +
410                         'execution=' + execution.getId() +
411                         ')'
412
413                 msoLogger.trace('Entered ' + method)
414                 execution.setVariable("prefix",Prefix)
415                 try{
416                 msoLogger.trace("STARTED postProcessVNFAdapterRequest Process")
417                 
418                 String vnfResponse = execution.getVariable("DDVMFV_doDeleteVfModuleResponse")
419                 msoLogger.debug("VNF Adapter Response is: " + vnfResponse)
420                 msoLogger.debug("deleteVnfAResponse is: \n"  + vnfResponse)
421
422                 if(vnfResponse != null){
423
424                         if(vnfResponse.contains("deleteVfModuleResponse")){
425                                 msoLogger.debug("Received a Good Response from VNF Adapter for DELETE_VF_MODULE Call.")
426                                 execution.setVariable("DDVFMV_vnfVfModuleDeleteCompleted", true)
427
428                                 // Parse vnfOutputs for contrail network polcy FQDNs
429                                 def vfModuleOutputsXml = utils.getNodeXml(vnfResponse, "vfModuleOutputs")
430                                 if(!isBlank(vfModuleOutputsXml)) {
431                                         vfModuleOutputsXml = utils.removeXmlNamespaces(vfModuleOutputsXml)
432                                         List contrailNetworkPolicyFqdnList = []
433                                         for(Node node: utils.getMultNodeObjects(vfModuleOutputsXml, "entry")) {
434                                                 String key = utils.getChildNodeText(node, "key")
435                                                 if(key == null) {
436                                                         
437                                                 } else if (key.endsWith("contrail_network_policy_fqdn")) {
438                                                         String contrailNetworkPolicyFqdn = utils.getChildNodeText(node, "value")
439                                                         msoLogger.debug("Obtained contrailNetworkPolicyFqdn: " + contrailNetworkPolicyFqdn)
440                                                         contrailNetworkPolicyFqdnList.add(contrailNetworkPolicyFqdn)
441                                                 }
442                                                 else if (key.equals("oam_management_v4_address")) {
443                                                         String oamManagementV4Address = utils.getChildNodeText(node, "value")
444                                                         msoLogger.debug("Obtained oamManagementV4Address: " + oamManagementV4Address)
445                                                         execution.setVariable(Prefix + "oamManagementV4Address", oamManagementV4Address)
446                                                 }
447                                                 else if (key.equals("oam_management_v6_address")) {
448                                                         String oamManagementV6Address = utils.getChildNodeText(node, "value")
449                                                         msoLogger.debug("Obtained oamManagementV6Address: " + oamManagementV6Address)
450                                                         execution.setVariable(Prefix + "oamManagementV6Address", oamManagementV6Address)
451                                                 }
452                                         }
453                                         if (!contrailNetworkPolicyFqdnList.isEmpty()) {
454                                                 msoLogger.debug("Setting the fqdn list")
455                                                 execution.setVariable("DDVFMV_contrailNetworkPolicyFqdnList", contrailNetworkPolicyFqdnList)
456                                         }
457                                 }
458                         }else{
459                                 msoLogger.debug("Received a BAD Response from VNF Adapter for DELETE_VF_MODULE Call.")
460                                 exceptionUtil.buildAndThrowWorkflowException(execution, 1002, "VNF Adapter Error")
461                         }
462                 }else{
463                         msoLogger.debug("Response from VNF Adapter is Null for DELETE_VF_MODULE Call.")
464                         exceptionUtil.buildAndThrowWorkflowException(execution, 1002, "Empty response from VNF Adapter")
465                 }
466
467                 }catch(BpmnError b){
468                         throw b
469                 }catch(Exception e){
470                         msoLogger.debug("Internal Error Occured in PostProcess Method")
471                         exceptionUtil.buildAndThrowWorkflowException(execution, 1002, "Internal Error Occured in PostProcess Method")
472                 }
473                 msoLogger.trace("COMPLETED postProcessVnfAdapterResponse Process")
474         }
475
476         public void deleteNetworkPoliciesFromAAI(DelegateExecution execution) {
477                 def method = getClass().getSimpleName() + '.deleteNetworkPoliciesFromAAI(' +
478                 'execution=' + execution.getId() +
479                 ')'
480
481                 msoLogger.trace('Entered ' + method)
482                 execution.setVariable("prefix", Prefix)
483                 msoLogger.trace("STARTED deleteNetworkPoliciesFromAAI ")
484
485                 try {
486                         // get variables
487                         List fqdnList = execution.getVariable("DDVFMV_contrailNetworkPolicyFqdnList")
488                         if (fqdnList == null) {
489                                 msoLogger.debug("No network policies to delete")
490                                 return
491                         }
492                         int fqdnCount = fqdnList.size()
493
494                         execution.setVariable("DDVFMV_networkPolicyFqdnCount", fqdnCount)
495                         msoLogger.debug("DDVFMV_networkPolicyFqdnCount - " + fqdnCount)
496
497                         AaiUtil aaiUriUtil = new AaiUtil(this)
498
499                         if (fqdnCount > 0) {
500                                 // AII loop call over contrail network policy fqdn list
501                                 for (i in 0..fqdnCount-1) {
502
503                                         int counting = i+1
504                                         String fqdn = fqdnList[i]
505
506                                         // Query AAI for this network policy FQDN
507
508                                         AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIObjectPlurals.NETWORK_POLICY)
509                                         uri.queryParam("network-policy-fqdn", fqdn)
510                                         String queryNetworkPolicyByFqdnAAIRequest = aaiUriUtil.createAaiUri(uri)
511
512                                         msoLogger.debug("AAI request endpoint: " + queryNetworkPolicyByFqdnAAIRequest)
513                                         
514                                         APIResponse response = aaiUriUtil.executeAAIGetCall(execution, queryNetworkPolicyByFqdnAAIRequest)
515                                         int returnCode = response.getStatusCode()
516                                         execution.setVariable("DCVFM_aaiQueryNetworkPolicyByFqdnReturnCode", returnCode)
517                                         msoLogger.debug(" ***** AAI query network policy Response Code, NetworkPolicy #" + counting + " : " + returnCode)
518
519                                         String aaiResponseAsString = response.getResponseBodyAsString()
520
521                                         if (isOneOf(returnCode, 200, 201)) {
522                                                 msoLogger.debug("The return code is: "  + returnCode)
523                                                 // This network policy FQDN exists in AAI - need to delete it now
524                                                 msoLogger.debug(aaiResponseAsString)
525                                                 execution.setVariable("DDVFMV_queryNetworkPolicyByFqdnAAIResponse", aaiResponseAsString)
526                                                 msoLogger.debug("QueryAAINetworkPolicyByFQDN Success REST Response, , NetworkPolicy #" + counting + " : " + "\n" + aaiResponseAsString)
527                                                 // Retrieve the network policy id for this FQDN
528                                                 def networkPolicyId = utils.getNodeText(aaiResponseAsString, "network-policy-id")
529                                                 msoLogger.debug("Deleting network-policy with network-policy-id " + networkPolicyId)
530
531                                                 // Retrieve the resource version for this network policy
532                                                 def resourceVersion = utils.getNodeText(aaiResponseAsString, "resource-version")
533                                                 msoLogger.debug("Deleting network-policy with resource-version " + resourceVersion)
534
535                                                 AAIResourceUri delUri = AAIUriFactory.createResourceUri(AAIObjectType.NETWORK_POLICY, networkPolicyId)
536                                                 delUri.resourceVersion(resourceVersion)
537                                                 String delNetworkPolicyAAIRequest = aaiUriUtil.createAaiUri(delUri)
538                                                 
539                                                 msoLogger.debug("AAI request endpoint: " + delNetworkPolicyAAIRequest)
540
541                                                 msoLogger.debug("invoking DELETE call to AAI")
542                                                 msoLogger.debug("Sending DELETE call to AAI with Endpoint /n" + delNetworkPolicyAAIRequest)
543                                                 APIResponse responseDel = aaiUriUtil.executeAAIDeleteCall(execution, delNetworkPolicyAAIRequest)
544                                                 int returnCodeDel = responseDel.getStatusCode()
545                                                 execution.setVariable("DDVFMV_aaiDeleteNetworkPolicyReturnCode", returnCodeDel)
546                                                 msoLogger.debug(" ***** AAI delete network policy Response Code, NetworkPolicy #" + counting + " : " + returnCodeDel)
547
548                                                 if (isOneOf(returnCodeDel, 200, 201, 204)) {
549                                                         msoLogger.debug("The return code from deleting network policy is: "  + returnCodeDel)
550                                                         // This network policy was deleted from AAI successfully
551                                                         msoLogger.debug(" DelAAINetworkPolicy Success REST Response, , NetworkPolicy #" + counting + " : ")
552
553                                                 } else {
554                                                                 // aai all errors
555                                                                 String delErrorMessage = "Unable to delete network-policy to AAI deleteNetworkPoliciesFromAAI - " + returnCodeDel
556                                                          msoLogger.debug(delErrorMessage)
557                                                          exceptionUtil.buildAndThrowWorkflowException(execution, 2500, delErrorMessage)
558                                                 }
559                                         } else if (returnCode == 404) {
560                                                 // This network policy FQDN is not in AAI. No need to delete.
561                                                 msoLogger.debug("The return code is: "  + returnCode)
562                                                 msoLogger.debug("This network policy FQDN is not in AAI: " + fqdn)
563                                                 msoLogger.debug("Network policy FQDN is not in AAI")
564                                         } else {
565                                            if (aaiResponseAsString.contains("RESTFault")) {
566                                                    WorkflowException exceptionObject = exceptionUtil.MapAAIExceptionToWorkflowException(aaiResponseAsString, execution)
567                                                    execution.setVariable("WorkflowException", exceptionObject)
568                                                    throw new BpmnError("MSOWorkflowException")
569
570                                                    } else {
571                                                                 // aai all errors
572                                                                 String dataErrorMessage = "Unexpected Response from deleteNetworkPoliciesFromAAI - " + returnCode
573                                                                 msoLogger.debug(dataErrorMessage)
574                                                                 exceptionUtil.buildAndThrowWorkflowException(execution, 2500, dataErrorMessage)
575
576                                                   }
577                                         }
578
579
580
581                                 } // end loop
582
583
584                         } else {
585                                    msoLogger.debug("No contrail network policies to query/create")
586
587                         }
588
589                 } catch (BpmnError e) {
590                         throw e;
591
592                 } catch (Exception ex) {
593                         String exceptionMessage = "Bpmn error encountered in DoDeletVfModule flow. deleteNetworkPoliciesFromAAI() - " + ex.getMessage()
594                         msoLogger.debug(exceptionMessage)
595                         exceptionUtil.buildAndThrowWorkflowException(execution, 7000, exceptionMessage)
596                 }
597
598         }       
599         
600         // and formulate the outgoing DeleteAAIVfModuleRequest request
601         public void prepDeleteAAIVfModule(DelegateExecution execution) {
602
603
604                 def vnfId = execution.getVariable("vnfId")
605                 def vfModuleId = execution.getVariable("vfModuleId")
606                 // formulate the request for UpdateAAIVfModule
607                 String request = """<DeleteAAIVfModuleRequest>
608                                                                 <vnf-id>${MsoUtils.xmlEscape(vnfId)}</vnf-id>
609                                                                 <vf-module-id>${MsoUtils.xmlEscape(vfModuleId)}</vf-module-id>
610                                                         </DeleteAAIVfModuleRequest>""" as String
611                 msoLogger.debug("DeleteAAIVfModuleRequest :" + request)
612                 
613                 execution.setVariable("DeleteAAIVfModuleRequest", request)
614         }
615 }