655d6ec9580b409b64bf942d177bd9829de1d282
[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
30 import static org.apache.commons.lang3.StringUtils.*
31 import org.camunda.bpm.engine.delegate.BpmnError
32 import org.camunda.bpm.engine.delegate.DelegateExecution
33 import org.onap.so.bpmn.common.scripts.AaiUtil
34 import org.onap.so.bpmn.common.scripts.ExceptionUtil
35 import org.onap.so.bpmn.common.scripts.MsoUtils
36 import org.onap.so.bpmn.common.scripts.SDNCAdapterUtils
37 import org.onap.so.bpmn.common.scripts.VfModuleBase
38 import org.onap.so.bpmn.core.UrnPropertiesReader
39 import org.onap.so.bpmn.core.WorkflowException
40 import org.onap.so.bpmn.core.json.JsonUtils
41 import org.onap.so.client.graphinventory.entities.uri.Depth
42 import org.onap.so.client.aai.AAIObjectPlurals
43 import org.onap.so.client.aai.AAIObjectType
44 import org.onap.so.client.aai.entities.uri.AAIResourceUri
45 import org.onap.so.client.aai.entities.uri.AAIUriFactory
46 import org.onap.so.logger.MessageEnum
47 import org.onap.so.logger.MsoLogger
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                                 // Source is HARDCODED
83                                 String source = "VID"
84                                 execution.setVariable("source", source)
85                                 // isVidRequest is hardcoded to "true"
86                                 execution.setVariable("isVidRequest", "true")
87                                 // SrvInstId is hardcoded to empty
88                                 execution.setVariable("srvInstId", "")
89                                 // ServiceId is hardcoded to empty
90                                 execution.setVariable("serviceId", "")
91                                 String serviceInstanceId = execution.getVariable("serviceInstanceId")
92                                 logger.debug("serviceInstanceId: " + serviceInstanceId)
93                                 String vnfId = execution.getVariable("vnfId")
94                                 logger.debug("vnfId: " + vnfId)
95                                 String vfModuleId = execution.getVariable("vfModuleId")
96                                 logger.debug("vfModuleId: " + vfModuleId)
97                                 if (serviceInstanceId == null || serviceInstanceId.isEmpty()) {
98                                         execution.setVariable(Prefix + "serviceInstanceIdToSdnc", vfModuleId)
99                                 }
100                                 else {
101                                         execution.setVariable(Prefix + "serviceInstanceIdToSdnc", serviceInstanceId)
102                                 }                               
103                                 
104                                 String sdncVersion = execution.getVariable("sdncVersion")
105                                 if (sdncVersion == null) {
106                                         sdncVersion = "1707"
107                                 }
108                                 execution.setVariable(Prefix + "sdncVersion", sdncVersion)
109                                 logger.debug("Incoming Sdnc Version is: " + sdncVersion)                                
110                                 
111                                 String sdncCallbackUrl = (String) UrnPropertiesReader.getVariable("mso.workflow.sdncadapter.callback",execution)
112                                 if (sdncCallbackUrl == null || sdncCallbackUrl.trim().isEmpty()) {
113                                         def msg = 'Required variable \'mso.workflow.sdncadapter.callback\' is missing'
114                                         logger.error("{} {} {} {} {} {}", MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), msg, "BPMN",
115                                                         MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError.getValue(), "Exception");
116                                         exceptionUtil.buildAndThrowWorkflowException(execution, 2000, msg)
117                                 }
118                                 execution.setVariable("sdncCallbackUrl", sdncCallbackUrl)
119                                 logger.debug("SDNC Callback URL: " + sdncCallbackUrl)
120                                 logger.debug("SDNC Callback URL is: " + sdncCallbackUrl)
121
122                         
123                         
124                 }catch(BpmnError b){
125                         throw b
126                 }catch(Exception e){
127                         logger.debug("Exception is: " + e.getMessage())
128                         exceptionUtil.buildAndThrowWorkflowException(execution, 2000, "Internal Error encountered in PreProcess method!")
129                 }
130         }
131         
132         public void queryAAIForVfModule(DelegateExecution execution) {
133                 def method = getClass().getSimpleName() + '.queryAAIForVfModule(' +
134                         'execution=' + execution.getId() +
135                         ')'
136
137                 logger.trace('Entered ' + method)
138
139                 try {
140                         def vnfId = execution.getVariable('vnfId')
141
142                         AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIObjectType.GENERIC_VNF, vnfId).depth(Depth.ONE)
143                         try {
144                                 Optional<GenericVnf> genericVnf = getAAIClient().get(GenericVnf.class,uri)
145
146                                 if(genericVnf.isPresent()){
147                                         execution.setVariable('DDVMFV_getVnfResponseCode', 200)
148                                         execution.setVariable('DDVMFV_getVnfResponse', genericVnf.get())
149                                 }else{
150                                         execution.setVariable('DDVMFV_getVnfResponseCode', 404)
151                                         execution.setVariable('DDVMFV_getVnfResponse', "Generic Vnf not found!")
152                                 }
153                         } catch (Exception ex) {
154                                 ex.printStackTrace()
155                                 logger.debug('Exception occurred while executing AAI GET:' + ex.getMessage())
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", MsoLogger.getServiceName(),
165                                         MsoLogger.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", MsoLogger.getServiceName(),
218                                         MsoLogger.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                                         MsoLogger.getServiceName(), MsoLogger.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(this)
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 vnfId = execution.getVariable("vnfId")
367                 def vfModuleId = execution.getVariable("vfModuleId")
368                 def vfModuleStackId = execution.getVariable('DDVMFV_heatStackId')
369                 def tenantId = execution.getVariable("tenantId")
370                 def messageId = execution.getVariable('requestId') + '-' +
371                         System.currentTimeMillis()
372                 def notificationUrl = createCallbackURL(execution, "VNFAResponse", messageId)
373                 def useQualifiedHostName = UrnPropertiesReader.getVariable("mso.use.qualified.host",execution)
374                 if ('true'.equals(useQualifiedHostName)) {
375                         notificationUrl = utils.getQualifiedHostNameForCallback(notificationUrl)
376                 }
377
378                 String request = """
379                         <deleteVfModuleRequest>
380                             <cloudSiteId>${MsoUtils.xmlEscape(aicCloudRegion)}</cloudSiteId>
381                             <tenantId>${MsoUtils.xmlEscape(tenantId)}</tenantId>
382                             <vnfId>${MsoUtils.xmlEscape(vnfId)}</vnfId>
383                             <vfModuleId>${MsoUtils.xmlEscape(vfModuleId)}</vfModuleId>
384                             <vfModuleStackId>${MsoUtils.xmlEscape(vfModuleStackId)}</vfModuleStackId>
385                             <skipAAI>true</skipAAI>
386                             <msoRequest>
387                                 <requestId>${MsoUtils.xmlEscape(origRequestId)}</requestId>
388                                 <serviceInstanceId>${MsoUtils.xmlEscape(srvInstId)}</serviceInstanceId>
389                             </msoRequest>
390                             <messageId>${MsoUtils.xmlEscape(messageId)}</messageId>
391                             <notificationUrl>${MsoUtils.xmlEscape(notificationUrl)}</notificationUrl>
392                         </deleteVfModuleRequest>
393                         """ as String
394
395                 logger.debug("vnfAdapterRestV1Request: " + request)
396                 logger.debug("deleteVfModuleRequest: " + request)
397                 execution.setVariable("vnfAdapterRestV1Request", request)
398         }
399
400         
401         // generates a WorkflowException if
402         //              -
403         public void handleDoDeleteVfModuleFailure(DelegateExecution execution) {
404                 logger.error("{} {} {} {} {} {}", MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(),
405                                 "AAI error occurred deleting the Generic Vnf: " + execution.getVariable("DDVFMV_deleteGenericVnfResponse"),
406                                 "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError.getValue(), "Exception");
407                 String processKey = getProcessKey(execution);
408                 WorkflowException exception = new WorkflowException(processKey, 5000,
409                         execution.getVariable("DDVFMV_deleteGenericVnfResponse"))
410                 execution.setVariable("WorkflowException", exception)
411         }
412         
413         public void postProcessVNFAdapterRequest(DelegateExecution execution) {
414                 def method = getClass().getSimpleName() + '.postProcessVNFAdapterRequest(' +
415                         'execution=' + execution.getId() +
416                         ')'
417
418                 logger.trace('Entered ' + method)
419                 execution.setVariable("prefix",Prefix)
420                 try{
421                 logger.trace("STARTED postProcessVNFAdapterRequest Process")
422                 
423                 String vnfResponse = execution.getVariable("DDVMFV_doDeleteVfModuleResponse")
424                 logger.debug("VNF Adapter Response is: " + vnfResponse)
425                 logger.debug("deleteVnfAResponse is: \n"  + vnfResponse)
426
427                 if(vnfResponse != null){
428
429                         if(vnfResponse.contains("deleteVfModuleResponse")){
430                                 logger.debug("Received a Good Response from VNF Adapter for DELETE_VF_MODULE Call.")
431                                 execution.setVariable("DDVFMV_vnfVfModuleDeleteCompleted", true)
432
433                                 // Parse vnfOutputs for contrail network polcy FQDNs
434                                 def vfModuleOutputsXml = utils.getNodeXml(vnfResponse, "vfModuleOutputs")
435                                 if(!isBlank(vfModuleOutputsXml)) {
436                                         vfModuleOutputsXml = utils.removeXmlNamespaces(vfModuleOutputsXml)
437                                         List contrailNetworkPolicyFqdnList = []
438                                         for(Node node: utils.getMultNodeObjects(vfModuleOutputsXml, "entry")) {
439                                                 String key = utils.getChildNodeText(node, "key")
440                                                 if(key == null) {
441                                                         
442                                                 } else if (key.endsWith("contrail_network_policy_fqdn")) {
443                                                         String contrailNetworkPolicyFqdn = utils.getChildNodeText(node, "value")
444                                                         logger.debug("Obtained contrailNetworkPolicyFqdn: " + contrailNetworkPolicyFqdn)
445                                                         contrailNetworkPolicyFqdnList.add(contrailNetworkPolicyFqdn)
446                                                 }
447                                                 else if (key.equals("oam_management_v4_address")) {
448                                                         String oamManagementV4Address = utils.getChildNodeText(node, "value")
449                                                         logger.debug("Obtained oamManagementV4Address: " + oamManagementV4Address)
450                                                         execution.setVariable(Prefix + "oamManagementV4Address", oamManagementV4Address)
451                                                 }
452                                                 else if (key.equals("oam_management_v6_address")) {
453                                                         String oamManagementV6Address = utils.getChildNodeText(node, "value")
454                                                         logger.debug("Obtained oamManagementV6Address: " + oamManagementV6Address)
455                                                         execution.setVariable(Prefix + "oamManagementV6Address", oamManagementV6Address)
456                                                 }
457                                         }
458                                         if (!contrailNetworkPolicyFqdnList.isEmpty()) {
459                                                 logger.debug("Setting the fqdn list")
460                                                 execution.setVariable("DDVFMV_contrailNetworkPolicyFqdnList", contrailNetworkPolicyFqdnList)
461                                         }
462                                 }
463                         }else{
464                                 logger.debug("Received a BAD Response from VNF Adapter for DELETE_VF_MODULE Call.")
465                                 exceptionUtil.buildAndThrowWorkflowException(execution, 1002, "VNF Adapter Error")
466                         }
467                 }else{
468                         logger.debug("Response from VNF Adapter is Null for DELETE_VF_MODULE Call.")
469                         exceptionUtil.buildAndThrowWorkflowException(execution, 1002, "Empty response from VNF Adapter")
470                 }
471
472                 }catch(BpmnError b){
473                         throw b
474                 }catch(Exception e){
475                         logger.debug("Internal Error Occured in PostProcess Method")
476                         exceptionUtil.buildAndThrowWorkflowException(execution, 1002, "Internal Error Occured in PostProcess Method")
477                 }
478                 logger.trace("COMPLETED postProcessVnfAdapterResponse Process")
479         }
480
481         public void deleteNetworkPoliciesFromAAI(DelegateExecution execution) {
482                 def method = getClass().getSimpleName() + '.deleteNetworkPoliciesFromAAI(' +
483                 'execution=' + execution.getId() +
484                 ')'
485
486                 logger.trace('Entered ' + method)
487                 execution.setVariable("prefix", Prefix)
488                 logger.trace("STARTED deleteNetworkPoliciesFromAAI ")
489
490                 try {
491                         // get variables
492                         List fqdnList = execution.getVariable("DDVFMV_contrailNetworkPolicyFqdnList")
493                         if (fqdnList == null) {
494                                 logger.debug("No network policies to delete")
495                                 return
496                         }
497                         int fqdnCount = fqdnList.size()
498
499                         execution.setVariable("DDVFMV_networkPolicyFqdnCount", fqdnCount)
500                         logger.debug("DDVFMV_networkPolicyFqdnCount - " + fqdnCount)
501
502                         AaiUtil aaiUriUtil = new AaiUtil(this)
503
504                         if (fqdnCount > 0) {
505                                 // AII loop call over contrail network policy fqdn list
506                                 for (i in 0..fqdnCount-1) {
507
508                                         int counting = i+1
509                                         String fqdn = fqdnList[i]
510
511                                         // Query AAI for this network policy FQDN
512
513                                         AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIObjectPlurals.NETWORK_POLICY)
514                                         uri.queryParam("network-policy-fqdn", fqdn)
515
516                     try {
517                         Optional<NetworkPolicies> networkPolicies = getAAIClient().get(NetworkPolicies.class, uri)
518
519                         if (networkPolicies.isPresent() && !networkPolicies.get().getNetworkPolicy().isEmpty()) {
520                             NetworkPolicy networkPolicy = networkPolicies.get().getNetworkPolicy().get(0)
521                             execution.setVariable("DCVFM_aaiQueryNetworkPolicyByFqdnReturnCode", 200)
522                             // This network policy FQDN exists in AAI - need to delete it now
523                             // Retrieve the network policy id for this FQDN
524                             def networkPolicyId = networkPolicy.getNetworkPolicyId()
525                             logger.debug("Deleting network-policy with network-policy-id " + networkPolicyId)
526
527                             // Retrieve the resource version for this network policy
528                             try {
529                                 AAIResourceUri delUri = AAIUriFactory.createResourceUri(AAIObjectType.NETWORK_POLICY, networkPolicyId)
530                                 getAAIClient().delete(delUri)
531                                 execution.setVariable("DDVFMV_aaiDeleteNetworkPolicyReturnCode", 200)
532                                 logger.debug(" ***** AAI delete network policy Response Code, NetworkPolicy #" + counting + " : " + 200)
533                                 // This network policy was deleted from AAI successfully
534                                 logger.debug(" DelAAINetworkPolicy Success REST Response, , NetworkPolicy #" + counting + " : ")
535                             } catch (Exception e) {
536                                 // aai all errors
537                                 String delErrorMessage = "Unable to delete network-policy to AAI deleteNetworkPoliciesFromAAI - " + e.getMessage()
538                                 logger.debug(delErrorMessage)
539                                 exceptionUtil.buildAndThrowWorkflowException(execution, 2500, delErrorMessage)
540                             }
541                         } else {
542                             execution.setVariable("DCVFM_aaiQueryNetworkPolicyByFqdnReturnCode", 404)
543                             // This network policy FQDN is not in AAI. No need to delete.
544                             logger.debug("This network policy FQDN is not in AAI: " + fqdn)
545                             logger.debug("Network policy FQDN is not in AAI")
546                         }
547                     } catch (Exception e) {
548                         // aai all errors
549                         String dataErrorMessage = "Unexpected Response from deleteNetworkPoliciesFromAAI - " + e.getMessage()
550                         logger.debug(dataErrorMessage)
551                         exceptionUtil.buildAndThrowWorkflowException(execution, 2500, dataErrorMessage)
552                     }
553                 } // end loop
554                         } else {
555                                    logger.debug("No contrail network policies to query/create")
556
557                         }
558
559                 } catch (BpmnError e) {
560                         throw e;
561
562                 } catch (Exception ex) {
563                         String exceptionMessage = "Bpmn error encountered in DoDeletVfModule flow. deleteNetworkPoliciesFromAAI() - " + ex.getMessage()
564                         logger.debug(exceptionMessage)
565                         exceptionUtil.buildAndThrowWorkflowException(execution, 7000, exceptionMessage)
566                 }
567
568         }       
569         
570         // and formulate the outgoing DeleteAAIVfModuleRequest request
571         public void prepDeleteAAIVfModule(DelegateExecution execution) {
572
573
574                 def vnfId = execution.getVariable("vnfId")
575                 def vfModuleId = execution.getVariable("vfModuleId")
576                 // formulate the request for UpdateAAIVfModule
577                 String request = """<DeleteAAIVfModuleRequest>
578                                                                 <vnf-id>${MsoUtils.xmlEscape(vnfId)}</vnf-id>
579                                                                 <vf-module-id>${MsoUtils.xmlEscape(vfModuleId)}</vf-module-id>
580                                                         </DeleteAAIVfModuleRequest>""" as String
581                 logger.debug("DeleteAAIVfModuleRequest :" + request)
582                 
583                 execution.setVariable("DeleteAAIVfModuleRequest", request)
584         }
585 }