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