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