33a1ece0911ded070bc62c5d7fcde1c80bb98f38
[so.git] /
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.AAIObjectPlurals
43 import org.onap.aaiclient.client.aai.AAIObjectType
44 import org.onap.aaiclient.client.aai.entities.uri.AAIPluralResourceUri
45 import org.onap.aaiclient.client.aai.entities.uri.AAIResourceUri
46 import org.onap.aaiclient.client.aai.entities.uri.AAIUriFactory
47 import org.onap.so.logger.MessageEnum
48 import org.slf4j.Logger
49 import org.slf4j.LoggerFactory
50 import org.w3c.dom.Document
51 import org.w3c.dom.Element
52 import org.w3c.dom.Node
53 import org.w3c.dom.NodeList;
54 import org.xml.sax.InputSource
55
56 /* Subflow for Delete VF Module. When no DoDeleteVfModuleRequest is specified on input,
57  * functions as a building block subflow
58  * Inputs for building block interface:
59  * @param - requestId
60  * @param - isDebugLogEnabled
61  * @param - vnfId
62  * @param - vfModuleId
63  * @param - serviceInstanceId
64  * @param - vfModuleName O
65  * @param - vfModuleModelInfo
66  * @param - cloudConfiguration*
67  * @param - sdncVersion ("1610")
68  * @param - retainResources
69  * @param - aLaCarte
70  *
71  * Outputs:
72  * @param - WorkflowException
73  *
74  */
75 public class DoDeleteVfModule extends AbstractServiceTaskProcessor{
76     private static final Logger logger = LoggerFactory.getLogger( DoDeleteVfModule.class);
77
78     def Prefix="DoDVfMod_"
79
80     ExceptionUtil exceptionUtil = new ExceptionUtil()
81     JsonUtils jsonUtil = new JsonUtils()
82
83     public void initProcessVariables(DelegateExecution execution) {
84         execution.setVariable("prefix",Prefix)
85         execution.setVariable("DoDVfMod_contrailNetworkPolicyFqdnList", null)
86         execution.setVariable("DoDVfMod_oamManagementV4Address", null)
87         execution.setVariable("DoDVfMod_oamManagementV6Address", null)
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("deleteVfModuleRequest: " + request)
320         execution.setVariable("vnfAdapterTaskRequest", request)
321     }
322
323     // parse the incoming DELETE_VF_MODULE request
324     // and formulate the outgoing UpdateAAIVfModuleRequest request
325     public void prepUpdateAAIVfModule(DelegateExecution execution) {
326
327         def vnfId = execution.getVariable("vnfId")
328         def vfModuleId = execution.getVariable("vfModuleId")
329         // formulate the request for UpdateAAIVfModule
330         String request = """<UpdateAAIVfModuleRequest>
331                                                                 <vnf-id>${MsoUtils.xmlEscape(vnfId)}</vnf-id>
332                                                                 <vf-module-id>${MsoUtils.xmlEscape(vfModuleId)}</vf-module-id>
333                                                                 <heat-stack-id>DELETE</heat-stack-id>
334                                                                 <orchestration-status>deleted</orchestration-status>
335                                                         </UpdateAAIVfModuleRequest>""" as String
336         logger.debug("UpdateAAIVfModuleRequest: " + request)
337         execution.setVariable("UpdateAAIVfModuleRequest", request)
338     }
339
340     // parse the incoming DELETE_VF_MODULE request
341     // and formulate the outgoing DeleteAAIVfModuleRequest request
342     public void prepDeleteAAIVfModule(DelegateExecution execution) {
343
344
345         def vnfId = execution.getVariable("vnfId")
346         def vfModuleId = execution.getVariable("vfModuleId")
347         // formulate the request for UpdateAAIVfModule
348         String request = """<DeleteAAIVfModuleRequest>
349                                                                 <vnf-id>${MsoUtils.xmlEscape(vnfId)}</vnf-id>
350                                                                 <vf-module-id>${MsoUtils.xmlEscape(vfModuleId)}</vf-module-id>
351                                                         </DeleteAAIVfModuleRequest>""" as String
352         logger.debug("DeleteAAIVfModuleRequest :" + request)
353         logger.debug("DeleteAAIVfModuleRequest: " + request)
354         execution.setVariable("DeleteAAIVfModuleRequest", request)
355     }
356
357     // generates a WorkflowException if
358     //          -
359     public void handleDoDeleteVfModuleFailure(DelegateExecution execution) {
360         logger.error(LoggingAnchor.FIVE, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(),
361                 "AAI error occurred deleting the Generic Vnf: " + execution.getVariable("DoDVfMod_deleteGenericVnfResponse"),
362                 "BPMN", ErrorCode.UnknownError.getValue(), "Exception");
363         String processKey = getProcessKey(execution);
364         WorkflowException exception = new WorkflowException(processKey, 5000,
365                 execution.getVariable("DoDVfMod_deleteGenericVnfResponse"))
366         execution.setVariable("WorkflowException", exception)
367     }
368
369     public void sdncValidateResponse(DelegateExecution execution, String response){
370
371         execution.setVariable("prefix",Prefix)
372
373         WorkflowException workflowException = execution.getVariable("WorkflowException")
374         boolean successIndicator = execution.getVariable("SDNCA_SuccessIndicator")
375
376         SDNCAdapterUtils sdncAdapterUtils = new SDNCAdapterUtils()
377         sdncAdapterUtils.validateSDNCResponse(execution, response, workflowException, successIndicator)
378
379         if(execution.getVariable(Prefix + 'sdncResponseSuccess') == true){
380             logger.debug("Successfully Validated SDNC Response")
381         }else{
382             throw new BpmnError("MSOWorkflowException")
383         }
384     }
385
386     public void postProcessVNFAdapterRequest(DelegateExecution execution) {
387         def method = getClass().getSimpleName() + '.postProcessVNFAdapterRequest(' +
388                 'execution=' + execution.getId() +
389                 ')'
390
391         logger.trace('Entered ' + method)
392         execution.setVariable("prefix",Prefix)
393         try{
394             logger.trace("STARTED postProcessVNFAdapterRequest Process")
395
396             String vnfResponse = execution.getVariable("DoDVfMod_doDeleteVfModuleResponse")
397             logger.debug("VNF Adapter Response is: " + vnfResponse)
398             logger.debug("deleteVnfAResponse is: \n"  + vnfResponse)
399
400             if(vnfResponse != null){
401
402                 if(vnfResponse.contains("deleteVfModuleResponse")){
403                     logger.debug("Received a Good Response from VNF Adapter for DELETE_VF_MODULE Call.")
404                     execution.setVariable("DoDVfMod_vnfVfModuleDeleteCompleted", true)
405
406                     // Parse vnfOutputs for contrail network polcy FQDNs
407                     if (vnfResponse.contains("vfModuleOutputs")) {
408                         def vfModuleOutputsXml = utils.getNodeXml(vnfResponse, "vfModuleOutputs")
409                         InputSource source = new InputSource(new StringReader(vfModuleOutputsXml));
410                         DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
411                         docFactory.setNamespaceAware(true)
412                         DocumentBuilder docBuilder = docFactory.newDocumentBuilder()
413                         Document outputsXml = docBuilder.parse(source)
414
415                         NodeList entries = outputsXml.getElementsByTagNameNS("*", "entry")
416                         List contrailNetworkPolicyFqdnList = []
417                         for (int i = 0; i< entries.getLength(); i++) {
418                             Node node = entries.item(i)
419                             if (node.getNodeType() == Node.ELEMENT_NODE) {
420                                 Element element = (Element) node
421                                 String key = element.getElementsByTagNameNS("*", "key").item(0).getTextContent()
422                                 if (key.endsWith("contrail_network_policy_fqdn")) {
423                                     String contrailNetworkPolicyFqdn = element.getElementsByTagNameNS("*", "value").item(0).getTextContent()
424                                     logger.debug("Obtained contrailNetworkPolicyFqdn: " + contrailNetworkPolicyFqdn)
425                                     contrailNetworkPolicyFqdnList.add(contrailNetworkPolicyFqdn)
426                                 }
427                                 else if (key.equals("oam_management_v4_address")) {
428                                     String oamManagementV4Address = element.getElementsByTagNameNS("*", "value").item(0).getTextContent()
429                                     logger.debug("Obtained oamManagementV4Address: " + oamManagementV4Address)
430                                     execution.setVariable(Prefix + "oamManagementV4Address", oamManagementV4Address)
431                                 }
432                                 else if (key.equals("oam_management_v6_address")) {
433                                     String oamManagementV6Address = element.getElementsByTagNameNS("*", "value").item(0).getTextContent()
434                                     logger.debug("Obtained oamManagementV6Address: " + oamManagementV6Address)
435                                     execution.setVariable(Prefix + "oamManagementV6Address", oamManagementV6Address)
436                                 }
437
438                             }
439                         }
440                         if (!contrailNetworkPolicyFqdnList.isEmpty()) {
441                             logger.debug("Setting the fqdn list")
442                             execution.setVariable("DoDVfMod_contrailNetworkPolicyFqdnList", contrailNetworkPolicyFqdnList)
443                         }
444                     }
445                 }else{
446                     logger.debug("Received a BAD Response from VNF Adapter for DELETE_VF_MODULE Call.")
447                     exceptionUtil.buildAndThrowWorkflowException(execution, 1002, "VNF Adapter Error")
448                 }
449             }else{
450                 logger.debug("Response from VNF Adapter is Null for DELETE_VF_MODULE Call.")
451                 exceptionUtil.buildAndThrowWorkflowException(execution, 1002, "Empty response from VNF Adapter")
452             }
453
454         }catch(BpmnError b){
455             throw b
456         }catch(Exception e){
457             logger.debug("Internal Error Occured in PostProcess Method")
458             exceptionUtil.buildAndThrowWorkflowException(execution, 1002, "Internal Error Occured in PostProcess Method")
459         }
460         logger.trace("COMPLETED postProcessVnfAdapterResponse Process")
461     }
462
463     public void deleteNetworkPoliciesFromAAI(DelegateExecution execution) {
464         def method = getClass().getSimpleName() + '.deleteNetworkPoliciesFromAAI(' +
465                 'execution=' + execution.getId() +
466                 ')'
467
468         logger.trace('Entered ' + method)
469         execution.setVariable("prefix", Prefix)
470         logger.trace("STARTED deleteNetworkPoliciesFromAAI ")
471
472         try {
473             // get variables
474             List fqdnList = execution.getVariable("DoDVfMod_contrailNetworkPolicyFqdnList")
475             if (fqdnList == null) {
476                 logger.debug("No network policies to delete")
477                 return
478             }
479             int fqdnCount = fqdnList.size()
480
481             execution.setVariable("DoDVfMod_networkPolicyFqdnCount", fqdnCount)
482             logger.debug("DoDVfMod_networkPolicyFqdnCount - " + fqdnCount)
483
484             if (fqdnCount > 0) {
485                 // AII loop call over contrail network policy fqdn list
486                 for (i in 0..fqdnCount-1) {
487                     String fqdn = fqdnList[i]
488                     // Query AAI for this network policy FQDN
489                                         AAIPluralResourceUri uri = AAIUriFactory.createResourceUri(AAIObjectPlurals.NETWORK_POLICY)
490                     uri.queryParam("network-policy-fqdn", fqdn)
491                     try {
492                         Optional<NetworkPolicies> networkPolicies = getAAIClient().get(NetworkPolicies.class, uri)
493                         if (networkPolicies.isPresent() && !networkPolicies.get().getNetworkPolicy().isEmpty()) {
494                             // This network policy FQDN exists in AAI - need to delete it now
495                             NetworkPolicy networkPolicy = networkPolicies.get().getNetworkPolicy().get(0)
496                             execution.setVariable("DCVFM_aaiQueryNetworkPolicyByFqdnReturnCode", 200)
497                             // Retrieve the network policy id for this FQDN
498                             def networkPolicyId = networkPolicy.getNetworkPolicyId()
499                             logger.debug("Deleting network-policy with network-policy-id " + networkPolicyId)
500                             try {
501                                 AAIResourceUri delUri = AAIUriFactory.createResourceUri(AAIObjectType.NETWORK_POLICY, networkPolicyId)
502                                 getAAIClient().delete(delUri)
503                                 execution.setVariable("DoDVfMod_aaiDeleteNetworkPolicyReturnCode", 200)
504                             } catch (Exception e) {
505                                 execution.setVariable("DoDVfMod_aaiDeleteNetworkPolicyReturnCode", 500)
506                                 String delErrorMessage = "Unable to delete network-policy to AAI deleteNetworkPoliciesFromAAI - " + e.getMessage()
507                                 logger.debug(delErrorMessage)
508                                 exceptionUtil.buildAndThrowWorkflowException(execution, 2500, delErrorMessage)
509                             }
510                         } else {
511                             execution.setVariable("DCVFM_aaiQueryNetworkPolicyByFqdnReturnCode", 404)
512                             // This network policy FQDN is not in AAI. No need to delete.
513                             logger.debug("The return code is: " + 404)
514                             logger.debug("This network policy FQDN is not in AAI: " + fqdn)
515                             logger.debug("Network policy FQDN is not in AAI")
516                         }
517                     }catch(Exception e ) {
518                         // aai all errors
519                         String dataErrorMessage = "Unexpected Response from deleteNetworkPoliciesFromAAI - " + e.getMessage()
520                         logger.debug(dataErrorMessage)
521                     }
522                 } // end loop
523             } else {
524                 logger.debug("No contrail network policies to query/create")
525             }
526         } catch (BpmnError e) {
527             throw e;
528         } catch (Exception ex) {
529             String exceptionMessage = "Bpmn error encountered in DoDeletVfModule flow. deleteNetworkPoliciesFromAAI() - " + ex.getMessage()
530             logger.debug(exceptionMessage)
531             exceptionUtil.buildAndThrowWorkflowException(execution, 7000, exceptionMessage)
532         }
533
534     }
535
536     /**
537      * Prepare a Request for invoking the UpdateAAIGenericVnf subflow.
538      *
539      * @param execution The flow's execution instance.
540      */
541     public void prepUpdateAAIGenericVnf(DelegateExecution execution) {
542         def method = getClass().getSimpleName() + '.prepUpdateAAIGenericVnf(' +
543                 'execution=' + execution.getId() +
544                 ')'
545
546         logger.trace('Entered ' + method)
547
548         try {
549             def vnfId = execution.getVariable('vnfId')
550             def oamManagementV4Address = execution.getVariable(Prefix + 'oamManagementV4Address')
551             def oamManagementV6Address = execution.getVariable(Prefix + 'oamManagementV6Address')
552             def ipv4OamAddressElement = ''
553             def managementV6AddressElement = ''
554
555             if (oamManagementV4Address != null) {
556                 ipv4OamAddressElement = '<ipv4-oam-address>' + 'DELETE' + '</ipv4-oam-address>'
557             }
558
559             if (oamManagementV6Address != null) {
560                 managementV6AddressElement = '<management-v6-address>' + 'DELETE' + '</management-v6-address>'
561             }
562
563
564             String updateAAIGenericVnfRequest = """
565                                         <UpdateAAIGenericVnfRequest>
566                                                 <vnf-id>${MsoUtils.xmlEscape(vnfId)}</vnf-id>
567                                                 ${ipv4OamAddressElement}
568                                                 ${managementV6AddressElement}
569                                         </UpdateAAIGenericVnfRequest>
570                                 """
571             updateAAIGenericVnfRequest = utils.formatXml(updateAAIGenericVnfRequest)
572             execution.setVariable(Prefix + 'updateAAIGenericVnfRequest', updateAAIGenericVnfRequest)
573             logger.debug("updateAAIGenericVnfRequest : " + updateAAIGenericVnfRequest)
574             logger.debug('Request for UpdateAAIGenericVnf:\n' + updateAAIGenericVnfRequest)
575
576
577             logger.trace('Exited ' + method)
578         } catch (BpmnError e) {
579             throw e;
580         } catch (Exception e) {
581             logger.error(LoggingAnchor.FIVE, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(),
582                     'Caught exception in ' + method, "BPMN",
583                     ErrorCode.UnknownError.getValue(), "Exception is:\n" + e);
584             exceptionUtil.buildAndThrowWorkflowException(execution, 1002, 'Error in prepUpdateAAIGenericVnf(): ' + e.getMessage())
585         }
586     }
587
588     /**
589      * Using the vnfId and vfModuleId provided in the inputs,
590      * query AAI to get the corresponding VF Module info.
591      * A 200 response is expected with the VF Module info in the response body,
592      * Will determine VF Module's orchestration status if one exists
593      *
594      * @param execution The flow's execution instance.
595      */
596     public void queryAAIVfModuleForStatus(DelegateExecution execution) {
597
598         def method = getClass().getSimpleName() + '.queryAAIVfModuleForStatus(' +
599                 'execution=' + execution.getId() +
600                 ')'
601         logger.trace('Entered ' + method)
602
603         execution.setVariable(Prefix + 'orchestrationStatus', '')
604
605         try {
606             def vnfId = execution.getVariable('vnfId')
607             def vfModuleId = execution.getVariable('vfModuleId')
608
609             AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIObjectType.VF_MODULE, vnfId, vfModuleId)
610
611             try {
612                 Optional<org.onap.aai.domain.yang.VfModule> vfModule = getAAIClient().get(org.onap.aai.domain.yang.VfModule.class, uri);
613                 // Retrieve VF Module info and its orchestration status; if not found, do nothing
614                 if (vfModule.isPresent()) {
615                     execution.setVariable(Prefix + 'queryAAIVfModuleForStatusResponseCode', 200)
616                     execution.setVariable(Prefix + 'queryAAIVfModuleForStatusResponse', vfModule.get())
617                     def orchestrationStatus = vfModule.get().getOrchestrationStatus()
618                     execution.setVariable(Prefix + "orchestrationStatus", orchestrationStatus)
619                     logger.debug("Received orchestration status from A&AI: " + orchestrationStatus)
620                 }
621             } catch (Exception ex) {
622                 logger.debug('Exception occurred while executing AAI GET: {}', ex.getMessage(), ex)
623                 exceptionUtil.buildAndThrowWorkflowException(execution, 1002, 'AAI GET Failed:' + ex.getMessage())
624             }
625             logger.trace('Exited ' + method)
626         } catch (BpmnError e) {
627             throw e;
628         } catch (Exception e) {
629             logger.error(LoggingAnchor.FIVE, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(),
630                     'Caught exception in ' + method, "BPMN",
631                     ErrorCode.UnknownError.getValue(), "Exception is:\n" + e);
632             exceptionUtil.buildAndThrowWorkflowException(execution, 1002, 'Error in queryAAIVfModuleForStatus(): ' + e.getMessage())
633         }
634     }
635
636
637
638
639
640 }