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