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