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