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