Groovy scripts header correction
[so.git] / bpmn / MSOInfrastructureBPMN / src / main / groovy / org / openecomp / mso / bpmn / infrastructure / scripts / DoDeleteVfModule.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.openecomp.mso.bpmn.infrastructure.scripts
22 import javax.xml.parsers.DocumentBuilder
23 import javax.xml.parsers.DocumentBuilderFactory
24
25 import org.camunda.bpm.engine.delegate.BpmnError
26 import org.camunda.bpm.engine.runtime.Execution
27 import org.openecomp.mso.bpmn.common.scripts.AaiUtil
28 import org.openecomp.mso.bpmn.common.scripts.AbstractServiceTaskProcessor
29 import org.openecomp.mso.bpmn.common.scripts.ExceptionUtil
30 import org.openecomp.mso.bpmn.common.scripts.SDNCAdapterUtils
31 import org.openecomp.mso.bpmn.common.scripts.VfModule
32 import org.openecomp.mso.bpmn.core.WorkflowException
33 import org.openecomp.mso.bpmn.core.json.JsonUtils
34 import org.openecomp.mso.rest.APIResponse
35 import org.springframework.web.util.UriUtils
36 import org.w3c.dom.Document
37 import org.w3c.dom.Element
38 import org.xml.sax.InputSource
39 import org.w3c.dom.Node
40 import org.w3c.dom.NodeList;
41
42
43 /* Subflow for Delete VF Module. When no DoDeleteVfModuleRequest is specified on input,
44  * functions as a building block subflow
45
46 * Inputs for building block interface:
47 * @param - requestId
48 * @param - isDebugLogEnabled
49 * @param - vnfId
50 * @param - vfModuleId
51 * @param - serviceInstanceId
52 * @param - vfModuleName O
53 * @param - vfModuleModelInfo
54 * @param - cloudConfiguration*
55 * @param - sdncVersion ("1610")
56 * @param - retainResources 
57 *
58 * Outputs:
59 * @param - WorkflowException
60 *
61 */
62 public class DoDeleteVfModule extends AbstractServiceTaskProcessor{
63
64         def Prefix="DoDVfMod_"
65
66         ExceptionUtil exceptionUtil = new ExceptionUtil()
67         JsonUtils jsonUtil = new JsonUtils()
68
69         public void initProcessVariables(Execution execution) {
70                 execution.setVariable("prefix",Prefix)
71                 execution.setVariable("DoDVfMod_contrailNetworkPolicyFqdnList", null)
72                 execution.setVariable("DoDVfMod_oamManagementV4Address", null)
73                 execution.setVariable("DoDVfMod_oamManagementV6Address", null)
74
75         }
76
77         // parse the incoming DELETE_VF_MODULE request for the Generic Vnf and Vf Module Ids
78         // and formulate the outgoing request for PrepareUpdateAAIVfModuleRequest
79         public void preProcessRequest(Execution execution) {
80                 def isDebugEnabled=execution.getVariable("isDebugLogEnabled")
81                 initProcessVariables(execution)
82
83                 try {
84                         def xml = execution.getVariable("DoDeleteVfModuleRequest")
85                         String vnfId = ""
86                         String vfModuleId = ""
87
88                         if (xml == null || xml.isEmpty()) {
89                                 // Building Block-type request
90
91                                 // Set mso-request-id to request-id for VNF Adapter interface
92                                 String requestId = execution.getVariable("requestId")
93                                 execution.setVariable("mso-request-id", requestId)
94
95                                 String cloudConfiguration = execution.getVariable("cloudConfiguration")
96                                 String vfModuleModelInfo = execution.getVariable("vfModuleModelInfo")
97                                 String tenantId = jsonUtil.getJsonValue(cloudConfiguration, "tenantId")
98                                 execution.setVariable("tenantId", tenantId)
99                                 String cloudSiteId = jsonUtil.getJsonValue(cloudConfiguration, "lcpCloudRegionId")
100                                 execution.setVariable("cloudSiteId", cloudSiteId)
101                                 // Source is HARDCODED
102                                 String source = "VID"
103                                 execution.setVariable("source", source)
104                                 // SrvInstId is hardcoded to empty
105                                 execution.setVariable("srvInstId", "")
106                                 // ServiceId is hardcoded to empty
107                                 execution.setVariable("serviceId", "")
108                                 String serviceInstanceId = execution.getVariable("serviceInstanceId")
109                                 vnfId = execution.getVariable("vnfId")
110                                 vfModuleId = execution.getVariable("vfModuleId")
111                                 if (serviceInstanceId == null || serviceInstanceId.isEmpty()) {
112                                         execution.setVariable(Prefix + "serviceInstanceIdToSdnc", vfModuleId)
113                                 }
114                                 else {
115                                         execution.setVariable(Prefix + "serviceInstanceIdToSdnc", serviceInstanceId)
116                                 }
117                                 //vfModuleModelName
118                                 def vfModuleModelName = jsonUtil.getJsonValue(vfModuleModelInfo, "modelName")
119                                 execution.setVariable("vfModuleModelName", vfModuleModelName)
120                                 // retainResources
121                                 def retainResources = execution.getVariable("retainResources")                  
122                                 if (retainResources == null) {
123                                         retainResources  = false
124                                 }
125                                 execution.setVariable("retainResources", retainResources)
126                         }
127                         else {
128
129                                 utils.logAudit("DoDeleteVfModule Request: " + xml)
130
131                                 utils.log("DEBUG", "input request xml: " + xml, isDebugEnabled)
132
133                                 vnfId = utils.getNodeText1(xml,"vnf-id")
134                                 execution.setVariable("vnfId", vnfId)
135                                 vfModuleId = utils.getNodeText1(xml,"vf-module-id")
136                                 execution.setVariable("vfModuleId", vfModuleId)
137                                 def srvInstId = execution.getVariable("mso-service-instance-id")
138                                 execution.setVariable("srvInstId", srvInstId)
139                                 String requestId = ""
140                                 try {
141                                         requestId = execution.getVariable("mso-request-id")
142                                 } catch (Exception ex) {
143                                         requestId = utils.getNodeText1(xml, "request-id")
144                                 }
145                                 execution.setVariable("requestId", requestId)
146                                 String source = utils.getNodeText1(xml, "source")
147                                 execution.setVariable("source", source)
148                                 String serviceId = utils.getNodeText1(xml, "service-id")
149                                 execution.setVariable("serviceId", serviceId)
150                                 String tenantId = utils.getNodeText1(xml, "tenant-id")
151                                 execution.setVariable("tenantId", tenantId)
152
153                                 String serviceInstanceIdToSdnc = ""
154                                 if (xml.contains("service-instance-id")) {
155                                         serviceInstanceIdToSdnc = utils.getNodeText1(xml, "service-instance-id")
156                                 } else {
157                                         serviceInstanceIdToSdnc = vfModuleId
158                                 }
159                                 execution.setVariable(Prefix + "serviceInstanceIdToSdnc", serviceInstanceIdToSdnc)
160                                 String vfModuleName = utils.getNodeText1(xml, "vf-module-name")
161                                 execution.setVariable("vfModuleName", vfModuleName)
162                                 String vfModuleModelName = utils.getNodeText1(xml, "vf-module-model-name")
163                                 execution.setVariable("vfModuleModelName", vfModuleModelName)
164                                 String cloudSiteId = utils.getNodeText1(xml, "aic-cloud-region")
165                                 execution.setVariable("cloudSiteId", cloudSiteId)
166                         }
167
168                         // formulate the request for PrepareUpdateAAIVfModule
169                         String request = """<PrepareUpdateAAIVfModuleRequest>
170                                                                         <vnf-id>${vnfId}</vnf-id>
171                                                                         <vf-module-id>${vfModuleId}</vf-module-id>
172                                                                         <orchestration-status>pending-delete</orchestration-status>
173                                                                 </PrepareUpdateAAIVfModuleRequest>""" as String
174                         utils.log("DEBUG", "PrepareUpdateAAIVfModuleRequest :" + request, isDebugEnabled)
175                         utils.logAudit("UpdateAAIVfModule Request: " + request)
176                         execution.setVariable("PrepareUpdateAAIVfModuleRequest", request)
177                         execution.setVariable("vfModuleFromAAI", null)
178                 }catch(BpmnError b){
179                         throw b
180                 }catch(Exception e){
181                         exceptionUtil.buildAndThrowWorkflowException(execution, 2000, "Internal Error encountered in PreProcess method!")
182                 }
183         }
184
185         // build a SDNC vnf-topology-operation request for the specified action
186         // (note: the action passed is expected to be 'changedelete' or 'delete')
187         public void prepSDNCAdapterRequest(Execution execution, String action) {
188                 def isDebugEnabled=execution.getVariable("isDebugLogEnabled")
189
190                 String uuid = execution.getVariable('testReqId') // for junits
191                 if(uuid==null){
192                         uuid = execution.getVariable("requestId") + "-" +       System.currentTimeMillis()
193                 }
194                 
195                 def srvInstId = execution.getVariable("srvInstId")
196                 def callbackUrl = execution.getVariable("URN_mso_workflow_sdncadapter_callback")
197                 String requestId = execution.getVariable("requestId")
198                 String source = execution.getVariable("source")
199                 String serviceId = execution.getVariable("serviceId")
200                 String vnfId = execution.getVariable("vnfId")
201                 String tenantId = execution.getVariable("tenantId")
202                 String vfModuleId = execution.getVariable("vfModuleId")
203                 String serviceInstanceIdToSdnc = execution.getVariable(Prefix + "serviceInstanceIdToSdnc")
204                 String vfModuleName = execution.getVariable("vfModuleName")
205                 // Get vfModuleName from AAI response if it was not specified on the request
206                 if (vfModuleName == null || vfModuleName.isEmpty()) {
207                         if (execution.getVariable("vfModuleFromAAI") != null) {
208                                 VfModule vfModuleFromAAI = execution.getVariable("vfModuleFromAAI")
209                                 vfModuleName = vfModuleFromAAI.getElementText("vf-module-name")
210                         }
211                 }
212                 String vfModuleModelName = execution.getVariable("vfModuleModelName")
213                 String cloudSiteId = execution.getVariable("cloudSiteId")
214                 boolean retainResources = execution.getVariable("retainResources")
215                 String requestSubActionString = ""
216                 if (retainResources) {
217                         requestSubActionString = "<request-sub-action>RetainResource</request-sub-action>"                      
218                 }
219                 String request = """<sdncadapterworkflow:SDNCAdapterWorkflowRequest xmlns:ns5="http://org.openecomp/mso/request/types/v1"
220                                                                                                         xmlns:sdncadapterworkflow="http://org.openecomp/mso/workflow/schema/v1"
221                                                                                                         xmlns:sdncadapter="http://org.openecomp/workflow/sdnc/adapter/schema/v1">
222                                                       <sdncadapter:RequestHeader>
223                                                          <sdncadapter:RequestId>${uuid}</sdncadapter:RequestId>
224                                                          <sdncadapter:SvcInstanceId>${vfModuleId}</sdncadapter:SvcInstanceId>
225                                                          <sdncadapter:SvcAction>${action}</sdncadapter:SvcAction>
226                                                          <sdncadapter:SvcOperation>vnf-topology-operation</sdncadapter:SvcOperation>
227                                                          <sdncadapter:CallbackUrl>${callbackUrl}</sdncadapter:CallbackUrl>
228                                                       </sdncadapter:RequestHeader>
229                                                       <sdncadapterworkflow:SDNCRequestData>
230                                                          <request-information>
231                                                             <request-id>${requestId}</request-id>
232                                                             <request-action>DisconnectVNFRequest</request-action>
233                                                                         ${requestSubActionString}
234                                                             <source>${source}</source>
235                                                             <notification-url/>
236                                                             <order-number/>
237                                                             <order-version/>
238                                                          </request-information>
239                                                          <service-information>
240                                                             <service-id>${serviceId}</service-id>
241                                                                         <service-type>${serviceId}</service-type>
242                                                             <service-instance-id>${serviceInstanceIdToSdnc}</service-instance-id>
243                                                             <subscriber-name>notsurewecare</subscriber-name>
244                                                          </service-information>
245                                                          <vnf-request-information>
246                                                                 <vnf-id>${vfModuleId}</vnf-id>
247                                                                         <vnf-type>${vfModuleModelName}</vnf-type>
248                                     <vnf-name>${vfModuleName}</vnf-name>
249                                                                         <generic-vnf-id>${vnfId}</generic-vnf-id>
250                                     <generic-vnf-name></generic-vnf-name>
251                                                                         <generic-vnf-type></generic-vnf-type>
252                                                                         <aic-cloud-region>${cloudSiteId}</aic-cloud-region>
253                                                                         <tenant>${tenantId}</tenant>
254                                                          </vnf-request-information>
255                                                       </sdncadapterworkflow:SDNCRequestData>
256                                                    </sdncadapterworkflow:SDNCAdapterWorkflowRequest>"""
257
258                 utils.log("DEBUG", "sdncAdapterWorkflowRequest: " + request, isDebugEnabled)
259                 utils.logAudit("DoDeleteVfModule - SDNCAdapterWorkflowRequest: " + request)
260                 execution.setVariable("sdncAdapterWorkflowRequest", request)
261         }
262
263         // parse the incoming DELETE_VF_MODULE request
264         // and formulate the outgoing VnfAdapterDeleteV1 request
265         public void prepVNFAdapterRequest(Execution execution) {
266                 def isDebugEnabled=execution.getVariable("isDebugLogEnabled")
267                 def requestId = UUID.randomUUID().toString()
268                 def origRequestId = execution.getVariable('requestId')
269                 def srvInstId = execution.getVariable("serviceInstanceId")
270                 def aicCloudRegion = execution.getVariable("cloudSiteId")
271                 def vnfId = execution.getVariable("vnfId")
272                 def vfModuleId = execution.getVariable("vfModuleId")
273                 def vfModuleStackId = execution.getVariable('DoDVfMod_heatStackId')
274                 def tenantId = execution.getVariable("tenantId")
275                 def messageId = execution.getVariable('requestId') + '-' +
276                         System.currentTimeMillis()
277                 def notificationUrl = createCallbackURL(execution, "VNFAResponse", messageId)
278                 def useQualifiedHostName = execution.getVariable("URN_mso_use_qualified_host")
279                 if ('true'.equals(useQualifiedHostName)) {
280                         notificationUrl = utils.getQualifiedHostNameForCallback(notificationUrl)
281                 }
282
283                 String request = """
284                         <deleteVfModuleRequest>
285                             <cloudSiteId>${aicCloudRegion}</cloudSiteId>
286                             <tenantId>${tenantId}</tenantId>
287                             <vnfId>${vnfId}</vnfId>
288                             <vfModuleId>${vfModuleId}</vfModuleId>
289                             <vfModuleStackId>${vfModuleStackId}</vfModuleStackId>
290                             <skipAAI>true</skipAAI>
291                             <msoRequest>
292                                 <requestId>${origRequestId}</requestId>
293                                 <serviceInstanceId>${srvInstId}</serviceInstanceId>
294                             </msoRequest>
295                             <messageId>${messageId}</messageId>
296                             <notificationUrl>${notificationUrl}</notificationUrl>
297                         </deleteVfModuleRequest>
298                         """ as String
299
300                 utils.log("DEBUG", "vnfAdapterRestV1Request: " + request, isDebugEnabled)
301                 utils.logAudit("deleteVfModuleRequest: " + request)
302                 execution.setVariable("vnfAdapterRestV1Request", request)
303         }
304
305         // parse the incoming DELETE_VF_MODULE request
306         // and formulate the outgoing UpdateAAIVfModuleRequest request
307         public void prepUpdateAAIVfModule(Execution execution) {
308                 def isDebugEnabled=execution.getVariable("isDebugLogEnabled")
309                 def vnfId = execution.getVariable("vnfId")
310                 def vfModuleId = execution.getVariable("vfModuleId")
311                 // formulate the request for UpdateAAIVfModule
312                 String request = """<UpdateAAIVfModuleRequest>
313                                                                 <vnf-id>${vnfId}</vnf-id>
314                                                                 <vf-module-id>${vfModuleId}</vf-module-id>
315                                                                 <heat-stack-id>DELETE</heat-stack-id>
316                                                                 <orchestration-status>deleted</orchestration-status>
317                                                         </UpdateAAIVfModuleRequest>""" as String
318                 utils.log("DEBUG", "UpdateAAIVfModuleRequest :" + request, isDebugEnabled)
319                 utils.logAudit("UpdateAAIVfModuleRequest: " + request)
320                 execution.setVariable("UpdateAAIVfModuleRequest", request)
321         }
322
323         // parse the incoming DELETE_VF_MODULE request
324         // and formulate the outgoing DeleteAAIVfModuleRequest request
325         public void prepDeleteAAIVfModule(Execution execution) {
326                 def isDebugEnabled=execution.getVariable("isDebugLogEnabled")
327
328                 def vnfId = execution.getVariable("vnfId")
329                 def vfModuleId = execution.getVariable("vfModuleId")
330                 // formulate the request for UpdateAAIVfModule
331                 String request = """<DeleteAAIVfModuleRequest>
332                                                                 <vnf-id>${vnfId}</vnf-id>
333                                                                 <vf-module-id>${vfModuleId}</vf-module-id>
334                                                         </DeleteAAIVfModuleRequest>""" as String
335                 utils.log("DEBUG", "DeleteAAIVfModuleRequest :" + request, isDebugEnabled)
336                 utils.logAudit("DeleteAAIVfModuleRequest: " + request)
337                 execution.setVariable("DeleteAAIVfModuleRequest", request)
338         }
339
340         // generates a WorkflowException if
341         //              -
342         public void handleDoDeleteVfModuleFailure(Execution execution) {
343                 def isDebugEnabled=execution.getVariable("isDebugLogEnabled")
344                 utils.log("ERROR", "AAI error occurred deleting the Generic Vnf: "
345                         + execution.getVariable("DoDVfMod_deleteGenericVnfResponse"), isDebugEnabled)
346                 String processKey = getProcessKey(execution);
347                 WorkflowException exception = new WorkflowException(processKey, 5000,
348                         execution.getVariable("DoDVfMod_deleteGenericVnfResponse"))
349                 execution.setVariable("WorkflowException", exception)
350         }
351
352         public void sdncValidateResponse(Execution execution, String response){
353                 def isDebugEnabled=execution.getVariable("isDebugLogEnabled")
354                 execution.setVariable("prefix",Prefix)
355
356                 WorkflowException workflowException = execution.getVariable("WorkflowException")
357                 boolean successIndicator = execution.getVariable("SDNCA_SuccessIndicator")
358
359                 SDNCAdapterUtils sdncAdapterUtils = new SDNCAdapterUtils(this)
360                 sdncAdapterUtils.validateSDNCResponse(execution, response, workflowException, successIndicator)
361
362                 if(execution.getVariable(Prefix + 'sdncResponseSuccess') == true){
363                         utils.log("DEBUG", "Successfully Validated SDNC Response", isDebugEnabled)
364                 }else{
365                         throw new BpmnError("MSOWorkflowException")
366                 }
367         }
368
369         public void postProcessVNFAdapterRequest(Execution execution) {
370                 def method = getClass().getSimpleName() + '.postProcessVNFAdapterRequest(' +
371                         'execution=' + execution.getId() +
372                         ')'
373                 def isDebugLogEnabled = execution.getVariable('isDebugLogEnabled')
374                 logDebug('Entered ' + method, isDebugLogEnabled)
375                 execution.setVariable("prefix",Prefix)
376                 try{
377                 logDebug(" *** STARTED postProcessVNFAdapterRequest Process*** ", isDebugLogEnabled)
378
379                 String vnfResponse = execution.getVariable("DoDVfMod_doDeleteVfModuleResponse")
380                 logDebug("VNF Adapter Response is: " + vnfResponse, isDebugLogEnabled)
381                 utils.logAudit("deleteVnfAResponse is: \n"  + vnfResponse)
382
383                 if(vnfResponse != null){
384
385                         if(vnfResponse.contains("deleteVfModuleResponse")){
386                                 logDebug("Received a Good Response from VNF Adapter for DELETE_VF_MODULE Call.", isDebugLogEnabled)
387                                 execution.setVariable("DoDVfMod_vnfVfModuleDeleteCompleted", true)
388
389                                 // Parse vnfOutputs for contrail network polcy FQDNs
390                                 if (vnfResponse.contains("vfModuleOutputs")) {
391                                         def vfModuleOutputsXml = utils.getNodeXml(vnfResponse, "vfModuleOutputs")
392                                         InputSource source = new InputSource(new StringReader(vfModuleOutputsXml));
393                         DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
394                         docFactory.setNamespaceAware(true)
395                         DocumentBuilder docBuilder = docFactory.newDocumentBuilder()
396                         Document outputsXml = docBuilder.parse(source)
397
398                                         NodeList entries = outputsXml.getElementsByTagNameNS("*", "entry")
399                                         List contrailNetworkPolicyFqdnList = []
400                                         for (int i = 0; i< entries.getLength(); i++) {
401                                                 Node node = entries.item(i)
402                                                 if (node.getNodeType() == Node.ELEMENT_NODE) {
403                                                         Element element = (Element) node
404                                                         String key = element.getElementsByTagNameNS("*", "key").item(0).getTextContent()
405                                                         if (key.endsWith("contrail_network_policy_fqdn")) {
406                                                                 String contrailNetworkPolicyFqdn = element.getElementsByTagNameNS("*", "value").item(0).getTextContent()
407                                                                 logDebug("Obtained contrailNetworkPolicyFqdn: " + contrailNetworkPolicyFqdn, isDebugLogEnabled)
408                                                                 contrailNetworkPolicyFqdnList.add(contrailNetworkPolicyFqdn)
409                                                         }
410                                                         else if (key.equals("oam_management_v4_address")) {
411                                                                 String oamManagementV4Address = element.getElementsByTagNameNS("*", "value").item(0).getTextContent()
412                                                                 logDebug("Obtained oamManagementV4Address: " + oamManagementV4Address, isDebugLogEnabled)
413                                                                 execution.setVariable(Prefix + "oamManagementV4Address", oamManagementV4Address)
414                                                         }
415                                                         else if (key.equals("oam_management_v6_address")) {
416                                                                 String oamManagementV6Address = element.getElementsByTagNameNS("*", "value").item(0).getTextContent()
417                                                                 logDebug("Obtained oamManagementV6Address: " + oamManagementV6Address, isDebugLogEnabled)
418                                                                 execution.setVariable(Prefix + "oamManagementV6Address", oamManagementV6Address)
419                                                         }
420
421                                                 }
422                                         }
423                                         if (!contrailNetworkPolicyFqdnList.isEmpty()) {
424                                                 logDebug("Setting the fqdn list", isDebugLogEnabled)
425                                                 execution.setVariable("DoDVfMod_contrailNetworkPolicyFqdnList", contrailNetworkPolicyFqdnList)
426                                         }
427                                 }
428                         }else{
429                                 logDebug("Received a BAD Response from VNF Adapter for DELETE_VF_MODULE Call.", isDebugLogEnabled)
430                                 exceptionUtil.buildAndThrowWorkflowException(execution, 1002, "VNF Adapter Error")
431                         }
432                 }else{
433                         logDebug("Response from VNF Adapter is Null for DELETE_VF_MODULE Call.", isDebugLogEnabled)
434                         exceptionUtil.buildAndThrowWorkflowException(execution, 1002, "Empty response from VNF Adapter")
435                 }
436
437                 }catch(BpmnError b){
438                         throw b
439                 }catch(Exception e){
440                         logDebug("Internal Error Occured in PostProcess Method", isDebugLogEnabled)
441                         exceptionUtil.buildAndThrowWorkflowException(execution, 1002, "Internal Error Occured in PostProcess Method")
442                 }
443                 logDebug(" *** COMPLETED postProcessVnfAdapterResponse Process*** ", isDebugLogEnabled)
444         }
445
446         public void deleteNetworkPoliciesFromAAI(Execution execution) {
447                 def method = getClass().getSimpleName() + '.deleteNetworkPoliciesFromAAI(' +
448                 'execution=' + execution.getId() +
449                 ')'
450                 def isDebugLogEnabled = execution.getVariable('isDebugLogEnabled')
451                 logDebug('Entered ' + method, isDebugLogEnabled)
452                 execution.setVariable("prefix", Prefix)
453                 logDebug(" ======== STARTED deleteNetworkPoliciesFromAAI ======== ", isDebugLogEnabled)
454
455                 try {
456                         // get variables
457                         List fqdnList = execution.getVariable("DoDVfMod_contrailNetworkPolicyFqdnList")
458                         if (fqdnList == null) {
459                                 logDebug("No network policies to delete", isDebugLogEnabled)
460                                 return
461                         }
462                         int fqdnCount = fqdnList.size()
463
464                         execution.setVariable("DoDVfMod_networkPolicyFqdnCount", fqdnCount)
465                         logDebug("DoDVfMod_networkPolicyFqdnCount - " + fqdnCount, isDebugLogEnabled)
466
467                         String aai_endpoint = execution.getVariable("URN_aai_endpoint")
468                         AaiUtil aaiUriUtil = new AaiUtil(this)
469                         String aai_uri = aaiUriUtil.getNetworkPolicyUri(execution)
470
471                         if (fqdnCount > 0) {
472                                 // AII loop call over contrail network policy fqdn list
473                                 for (i in 0..fqdnCount-1) {
474
475                                         int counting = i+1
476                                         String fqdn = fqdnList[i]
477
478                                         // Query AAI for this network policy FQDN
479
480                                         String queryNetworkPolicyByFqdnAAIRequest = "${aai_endpoint}${aai_uri}?network-policy-fqdn=" + UriUtils.encode(fqdn, "UTF-8")
481                                         utils.logAudit("AAI request endpoint: " + queryNetworkPolicyByFqdnAAIRequest)
482                                         logDebug("AAI request endpoint: "  + queryNetworkPolicyByFqdnAAIRequest, isDebugLogEnabled)
483
484                                         APIResponse response = aaiUriUtil.executeAAIGetCall(execution, queryNetworkPolicyByFqdnAAIRequest)
485                                         int returnCode = response.getStatusCode()
486                                         execution.setVariable("DCVFM_aaiQueryNetworkPolicyByFqdnReturnCode", returnCode)
487                                         logDebug(" ***** AAI query network policy Response Code, NetworkPolicy #" + counting + " : " + returnCode, isDebugLogEnabled)
488
489                                         String aaiResponseAsString = response.getResponseBodyAsString()
490
491                                         if (isOneOf(returnCode, 200, 201)) {
492                                                 logDebug("The return code is: "  + returnCode, isDebugLogEnabled)
493                                                 // This network policy FQDN exists in AAI - need to delete it now
494                                                 utils.logAudit(aaiResponseAsString)
495                                                 execution.setVariable("DoDVfMod_queryNetworkPolicyByFqdnAAIResponse", aaiResponseAsString)
496                                                 logDebug("QueryAAINetworkPolicyByFQDN Success REST Response, , NetworkPolicy #" + counting + " : " + "\n" + aaiResponseAsString, isDebugLogEnabled)
497                                                 // Retrieve the network policy id for this FQDN
498                                                 def networkPolicyId = utils.getNodeText1(aaiResponseAsString, "network-policy-id")
499                                                 logDebug("Deleting network-policy with network-policy-id " + networkPolicyId, isDebugLogEnabled)
500
501                                                 // Retrieve the resource version for this network policy
502                                                 def resourceVersion = utils.getNodeText1(aaiResponseAsString, "resource-version")
503                                                 logDebug("Deleting network-policy with resource-version " + resourceVersion, isDebugLogEnabled)
504
505                                                 String delNetworkPolicyAAIRequest = "${aai_endpoint}${aai_uri}/" + UriUtils.encode(networkPolicyId, "UTF-8") +
506                                                         "?resource-version=" + UriUtils.encode(resourceVersion, "UTF-8")
507                                                 utils.logAudit("AAI request endpoint: " + delNetworkPolicyAAIRequest)
508                                                 logDebug("AAI request endpoint: " + delNetworkPolicyAAIRequest, isDebugLogEnabled)
509
510                                                 logDebug("invoking DELETE call to AAI", isDebugLogEnabled)
511                                                 utils.logAudit("Sending DELETE call to AAI with Endpoint /n" + delNetworkPolicyAAIRequest)
512                                                 APIResponse responseDel = aaiUriUtil.executeAAIDeleteCall(execution, delNetworkPolicyAAIRequest)
513                                                 int returnCodeDel = responseDel.getStatusCode()
514                                                 execution.setVariable("DoDVfMod_aaiDeleteNetworkPolicyReturnCode", returnCodeDel)
515                                                 logDebug(" ***** AAI delete network policy Response Code, NetworkPolicy #" + counting + " : " + returnCodeDel, isDebugLogEnabled)
516
517                                                 if (isOneOf(returnCodeDel, 200, 201, 204)) {
518                                                         logDebug("The return code from deleting network policy is: "  + returnCodeDel, isDebugLogEnabled)
519                                                         // This network policy was deleted from AAI successfully
520                                                         logDebug(" DelAAINetworkPolicy Success REST Response, , NetworkPolicy #" + counting + " : ", isDebugLogEnabled)
521
522                                                 } else {
523                                                                 // aai all errors
524                                                                 String delErrorMessage = "Unable to delete network-policy to AAI deleteNetworkPoliciesFromAAI - " + returnCodeDel
525                                                          logDebug(delErrorMessage, isDebugLogEnabled)
526                                                          exceptionUtil.buildAndThrowWorkflowException(execution, 2500, delErrorMessage)
527                                                 }
528                                         } else if (returnCode == 404) {
529                                                 // This network policy FQDN is not in AAI. No need to delete.
530                                                 logDebug("The return code is: "  + returnCode, isDebugLogEnabled)
531                                                 logDebug("This network policy FQDN is not in AAI: " + fqdn, isDebugLogEnabled)
532                                                 utils.logAudit("Network policy FQDN is not in AAI")
533                                         } else {
534                                            if (aaiResponseAsString.contains("RESTFault")) {
535                                                    WorkflowException exceptionObject = exceptionUtil.MapAAIExceptionToWorkflowException(aaiResponseAsString, execution)
536                                                    execution.setVariable("WorkflowException", exceptionObject)
537                                                    throw new BpmnError("MSOWorkflowException")
538
539                                                    } else {
540                                                                 // aai all errors
541                                                                 String dataErrorMessage = "Unexpected Response from deleteNetworkPoliciesFromAAI - " + returnCode
542                                                                 logDebug(dataErrorMessage, isDebugLogEnabled)
543                                                                 exceptionUtil.buildAndThrowWorkflowException(execution, 2500, dataErrorMessage)
544
545                                                   }
546                                         }
547
548
549
550                                 } // end loop
551
552
553                         } else {
554                                    logDebug("No contrail network policies to query/create", isDebugLogEnabled)
555
556                         }
557
558                 } catch (BpmnError e) {
559                         throw e;
560
561                 } catch (Exception ex) {
562                         String exceptionMessage = "Bpmn error encountered in DoDeletVfModule flow. deleteNetworkPoliciesFromAAI() - " + ex.getMessage()
563                         logDebug(exceptionMessage, isDebugLogEnabled)
564                         exceptionUtil.buildAndThrowWorkflowException(execution, 7000, exceptionMessage)
565                 }
566
567         }
568
569         /**
570          * Prepare a Request for invoking the UpdateAAIGenericVnf subflow.
571          *
572          * @param execution The flow's execution instance.
573          */
574         public void prepUpdateAAIGenericVnf(Execution execution) {
575                 def method = getClass().getSimpleName() + '.prepUpdateAAIGenericVnf(' +
576                         'execution=' + execution.getId() +
577                         ')'
578                 def isDebugLogEnabled = execution.getVariable('isDebugLogEnabled')
579                 logDebug('Entered ' + method, isDebugLogEnabled)
580
581                 try {
582                         def vnfId = execution.getVariable('vnfId')
583                         def oamManagementV4Address = execution.getVariable(Prefix + 'oamManagementV4Address')
584                         def oamManagementV6Address = execution.getVariable(Prefix + 'oamManagementV6Address')
585                         def ipv4OamAddressElement = ''
586                         def managementV6AddressElement = ''
587
588                         if (oamManagementV4Address != null) {
589                                 ipv4OamAddressElement = '<ipv4-oam-address>' + 'DELETE' + '</ipv4-oam-address>'
590                         }
591
592                         if (oamManagementV6Address != null) {
593                                 managementV6AddressElement = '<management-v6-address>' + 'DELETE' + '</management-v6-address>'
594                         }
595
596
597                         String updateAAIGenericVnfRequest = """
598                                         <UpdateAAIGenericVnfRequest>
599                                                 <vnf-id>${vnfId}</vnf-id>
600                                                 ${ipv4OamAddressElement}
601                                                 ${managementV6AddressElement}
602                                         </UpdateAAIGenericVnfRequest>
603                                 """
604                                 updateAAIGenericVnfRequest = utils.formatXml(updateAAIGenericVnfRequest)
605                                 execution.setVariable(Prefix + 'updateAAIGenericVnfRequest', updateAAIGenericVnfRequest)
606                                 utils.logAudit("updateAAIGenericVnfRequest : " + updateAAIGenericVnfRequest)
607                                 logDebug('Request for UpdateAAIGenericVnf:\n' + updateAAIGenericVnfRequest, isDebugLogEnabled)
608
609
610                         logDebug('Exited ' + method, isDebugLogEnabled)
611                 } catch (BpmnError e) {
612                         throw e;
613                 } catch (Exception e) {
614                         logError('Caught exception in ' + method, e)
615                         exceptionUtil.buildAndThrowWorkflowException(execution, 1002, 'Error in prepUpdateAAIGenericVnf(): ' + e.getMessage())
616                 }
617         }
618
619
620
621
622 }