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