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