Dynamic Cloud Owner Support
[so.git] / bpmn / so-bpmn-infrastructure-common / src / main / groovy / org / onap / so / bpmn / vcpe / scripts / DeleteVcpeResCustService.groovy
1 /*
2  * ============LICENSE_START=======================================================
3  * ONAP - SO
4  * ================================================================================
5  * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
6  * ================================================================================
7  * Licensed under the Apache License, Version 2.0 (the "License");
8  * you may not use this file except in compliance with the License.
9  * You may obtain a copy of the License at
10  *
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  *
13  * Unless required by applicable law or agreed to in writing, software
14  * distributed under the License is distributed on an "AS IS" BASIS,
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * See the License for the specific language governing permissions and
17  * limitations under the License.
18  * ============LICENSE_END=========================================================
19  */
20 package org.onap.so.bpmn.vcpe.scripts
21
22 import org.camunda.bpm.engine.delegate.BpmnError
23 import org.camunda.bpm.engine.delegate.DelegateExecution
24 import org.onap.so.bpmn.common.scripts.AaiUtil
25 import org.onap.so.bpmn.common.scripts.AbstractServiceTaskProcessor
26 import org.onap.so.bpmn.common.scripts.CatalogDbUtils
27 import org.onap.so.bpmn.common.scripts.ExceptionUtil
28 import org.onap.so.bpmn.common.scripts.NetworkUtils
29 import org.onap.so.bpmn.common.scripts.VidUtils
30 import org.onap.so.bpmn.core.UrnPropertiesReader
31 import org.onap.so.bpmn.core.WorkflowException
32 import org.onap.so.bpmn.core.json.JsonUtils
33 import org.onap.so.logger.MessageEnum
34 import org.onap.so.logger.MsoLogger
35 import org.onap.so.rest.APIResponse
36 import org.onap.so.client.aai.AAIResourcesClient
37 import org.onap.so.client.aai.AAIObjectType
38 import org.onap.so.client.aai.entities.AAIResultWrapper
39 import org.onap.so.client.aai.entities.Relationships
40 import org.onap.so.client.aai.entities.uri.AAIResourceUri
41 import org.onap.so.client.aai.entities.uri.AAIUriFactory
42 import javax.ws.rs.NotFoundException
43 import org.json.JSONObject
44
45 import static org.apache.commons.lang3.StringUtils.isBlank
46
47
48 /**
49  * This groovy class supports the <class>DeleteVcpeResCustService.bpmn</class> process.
50  *
51  * @author dm4252
52  *
53  */
54 public class DeleteVcpeResCustService extends AbstractServiceTaskProcessor {
55         private static final MsoLogger msoLogger = MsoLogger.getMsoLogger(MsoLogger.Catalog.BPEL, DeleteVcpeResCustService.class);
56
57         private static final String DebugFlag = "isDebugLogEnabled"
58
59         String Prefix = "DVRCS_"
60         ExceptionUtil exceptionUtil = new ExceptionUtil()
61         JsonUtils jsonUtil = new JsonUtils()
62         VidUtils vidUtils = new VidUtils()
63         CatalogDbUtils catalogDbUtils = new CatalogDbUtils()
64         NetworkUtils networkUtils = new NetworkUtils()
65
66         /**
67          * This method is executed during the preProcessRequest task of the <class>DeleteVcpeResCustService.bpmn</class> process.
68          * @param execution
69          */
70         public InitializeProcessVariables(DelegateExecution execution){
71                 /* Initialize all the process variables in this block */
72
73                 execution.setVariable("DeleteVcpeResCustServiceRequest", "")
74                 execution.setVariable("msoRequestId", "")
75                 execution.setVariable(Prefix+"vnfsDeletedCount", 0)
76                 execution.setVariable(Prefix+"vnfsCount", 0)
77         }
78
79         // **************************************************
80         //     Pre or Prepare Request Section
81         // **************************************************
82         /**
83          * This method is executed during the preProcessRequest task of the <class>CreateServiceInstance.bpmn</class> process.
84          * @param execution
85          */
86         public void preProcessRequest (DelegateExecution execution) {
87                 def isDebugEnabled=execution.getVariable(DebugFlag)
88                 execution.setVariable("prefix",Prefix)
89
90                 msoLogger.trace("Inside preProcessRequest DeleteVcpeResCustService Request ")
91
92                 try {
93                         // initialize flow variables
94                         InitializeProcessVariables(execution)
95
96                         // check for incoming json message/input
97                         String DeleteVcpeResCustServiceRequest = execution.getVariable("bpmnRequest")
98                         msoLogger.debug(DeleteVcpeResCustServiceRequest)
99                         execution.setVariable("DeleteVcpeResCustServiceRequest", DeleteVcpeResCustServiceRequest);
100                         println 'DeleteVcpeResCustServiceRequest - ' + DeleteVcpeResCustServiceRequest
101
102                         // extract requestId
103                         String requestId = execution.getVariable("mso-request-id")
104                         execution.setVariable("msoRequestId", requestId)
105
106                         String serviceInstanceId = execution.getVariable("serviceInstanceId")
107                         if ((serviceInstanceId == null) || (serviceInstanceId.isEmpty())) {
108                                 String dataErrorMessage = " Element 'serviceInstanceId' is missing. "
109                                 exceptionUtil.buildAndThrowWorkflowException(execution, 2500, dataErrorMessage)
110                         }
111
112                         String requestAction = execution.getVariable("requestAction")
113                         execution.setVariable("requestAction", requestAction)
114
115                         String source = jsonUtil.getJsonValue(DeleteVcpeResCustServiceRequest, "requestDetails.requestInfo.source")
116                         if ((source == null) || (source.isEmpty())) {
117                                 source = "VID"
118                         }
119                         execution.setVariable("source", source)
120
121                         // extract globalSubscriberId
122                         String globalSubscriberId = jsonUtil.getJsonValue(DeleteVcpeResCustServiceRequest, "requestDetails.subscriberInfo.globalSubscriberId")
123
124                         // global-customer-id is optional on Delete
125
126                         execution.setVariable("globalSubscriberId", globalSubscriberId)
127                         execution.setVariable("globalCustomerId", globalSubscriberId)
128
129                         String suppressRollback = jsonUtil.getJsonValue(DeleteVcpeResCustServiceRequest, "requestDetails.requestInfo.suppressRollback")
130                         execution.setVariable("disableRollback", suppressRollback)
131                         msoLogger.debug("Incoming Suppress/Disable Rollback is: " + suppressRollback)
132
133                         String productFamilyId = jsonUtil.getJsonValue(DeleteVcpeResCustServiceRequest, "requestDetails.requestInfo.productFamilyId")
134                         execution.setVariable("productFamilyId", productFamilyId)
135                         msoLogger.debug("Incoming productFamilyId is: " + productFamilyId)
136
137                         // extract subscriptionServiceType
138                         String subscriptionServiceType = jsonUtil.getJsonValue(DeleteVcpeResCustServiceRequest, "requestDetails.requestParameters.subscriptionServiceType")
139                         execution.setVariable("subscriptionServiceType", subscriptionServiceType)
140                         msoLogger.debug("Incoming subscriptionServiceType is: " + subscriptionServiceType)
141
142                         // extract cloud configuration
143                         String cloudConfiguration = jsonUtil.getJsonValue(DeleteVcpeResCustServiceRequest, "requestDetails.cloudConfiguration")
144                         execution.setVariable("cloudConfiguration", cloudConfiguration)
145                         msoLogger.debug("cloudConfiguration: "+ cloudConfiguration)
146                         String lcpCloudRegionId = jsonUtil.getJsonValue(cloudConfiguration, "lcpCloudRegionId")
147                         execution.setVariable("lcpCloudRegionId", lcpCloudRegionId)
148                         msoLogger.debug("lcpCloudRegionId: "+ lcpCloudRegionId)
149                         String cloudOwner = jsonUtil.getJsonValue(cloudConfiguration, "cloudOwner")
150                         execution.setVariable("cloudOwner", cloudOwner)
151                         msoLogger.debug("cloudOwner: "+ cloudOwner)
152                         String tenantId = jsonUtil.getJsonValue(cloudConfiguration, "tenantId")
153                         execution.setVariable("tenantId", tenantId)
154                         msoLogger.debug("tenantId: "+ tenantId)
155
156                         String sdncVersion = "1707"
157                         execution.setVariable("sdncVersion", sdncVersion)
158                         msoLogger.debug("sdncVersion: "+ sdncVersion)
159
160                         //For Completion Handler & Fallout Handler
161                         String requestInfo =
162                         """<request-info xmlns="http://org.onap/so/infra/vnf-request/v1">
163                                         <request-id>${MsoUtils.xmlEscape(requestId)}</request-id>
164                                         <action>DELETE</action>
165                                         <source>${MsoUtils.xmlEscape(source)}</source>
166                                    </request-info>"""
167
168                         execution.setVariable(Prefix+"requestInfo", requestInfo)
169
170                         msoLogger.trace("Completed preProcessRequest DeleteVcpeResCustServiceRequest Request ")
171
172                 } catch (BpmnError e) {
173                         throw e;
174                 } catch (Exception ex){
175                         String exceptionMessage = "Bpmn error encountered in DeleteVcpeResCustService flow. Unexpected from method preProcessRequest() - " + ex.getMessage()
176                         exceptionUtil.buildAndThrowWorkflowException(execution, 7000, exceptionMessage)
177                 }
178         }
179
180         public void sendSyncResponse(DelegateExecution execution) {
181                 def isDebugEnabled=execution.getVariable(DebugFlag)
182
183                 msoLogger.trace("Inside sendSyncResponse of DeleteVcpeResCustService ")
184
185                 try {
186                         String serviceInstanceId = execution.getVariable("serviceInstanceId")
187                         String requestId = execution.getVariable("mso-request-id")
188
189                         // RESTResponse (for API Handler (APIH) Reply Task)
190                         String syncResponse ="""{"requestReferences":{"instanceId":"${serviceInstanceId}","requestId":"${requestId}"}}""".trim()
191
192                         msoLogger.debug(" sendSynchResponse: xmlSyncResponse - " + "\n" + syncResponse)
193                         sendWorkflowResponse(execution, 202, syncResponse)
194                 } catch (Exception ex) {
195                         String exceptionMessage = "Bpmn error encountered in DeleteVcpeResCustService flow. Unexpected from method preProcessRequest() - " + ex.getMessage()
196                         exceptionUtil.buildAndThrowWorkflowException(execution, 7000, exceptionMessage)
197                 }
198         }
199
200         /**
201          * Gets the service instance and its related resources from aai
202          *
203          * @author cb645j
204          */
205         public void getServiceInstance(DelegateExecution execution) {
206                 try {
207                         String serviceInstanceId = execution.getVariable('serviceInstanceId')
208
209                         AAIResourcesClient resourceClient = new AAIResourcesClient()
210                         AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIObjectType.SERVICE_INSTANCE, serviceInstanceId)
211
212                         if(resourceClient.exists(uri)){
213                                 AAIResultWrapper wrapper = resourceClient.get(uri, NotFoundException.class)
214                                 Optional<Relationships> relationships = wrapper.getRelationships()
215
216                                 def (TXC_found, TXC_id) = new Tuple(false, null)
217                                 def (BRG_found, BRG_id) = new Tuple(false, null)
218                                 List relatedVnfIdList = []
219
220                                 if(relationships.isPresent()){
221
222                                         List<AAIResourceUri> vnfUris = relationships.get().getRelatedAAIUris(AAIObjectType.GENERIC_VNF)
223                                         for(AAIResourceUri u:vnfUris){
224                                                 Map<String, String> keys = u.getURIKeys()
225                                                 String vnfId = keys.get("vnf-id")
226                                                 relatedVnfIdList.add(vnfId)
227                                         }
228                                         List<AAIResourceUri> arUris = relationships.get().getRelatedAAIUris(AAIObjectType.ALLOTTED_RESOURCE)
229                                         for(AAIResourceUri u:arUris){
230                                                 String ar = resourceClient.get(u).getJson()
231
232                                                 def type = jsonUtil.getJsonValue(ar, "type")
233                                                 def id = jsonUtil.getJsonValue(ar, "id")
234
235                                                 if(type == "TunnelXConn" || type == "Tunnel XConn") {
236                                                         msoLogger.debug("TunnelXConn AR found")
237                                                         TXC_found = true
238                                                         TXC_id = id
239
240                                                 }else if(type == "BRG") {
241                                                         msoLogger.debug("BRG AR found")
242                                                         BRG_found = true
243                                                         BRG_id = id
244                                                 }
245
246                                                 execution.setVariable(Prefix+"TunnelXConn", TXC_found)
247                                                 execution.setVariable("TXC_allottedResourceId", TXC_id)
248                                                 msoLogger.debug("TXC_allottedResourceId: " + TXC_id)
249
250                                                 execution.setVariable(Prefix+"BRG", BRG_found)
251                                                 execution.setVariable("BRG_allottedResourceId", BRG_id)
252                                                 msoLogger.debug("BRG_allottedResourceId: " + BRG_id)
253
254                                         }
255                                 }
256
257                                 execution.setVariable(Prefix+"vnfsCount", relatedVnfIdList.size())
258                                 if(relatedVnfIdList.size() > 0) {
259                                         execution.setVariable(Prefix+"relatedVnfIdList", relatedVnfIdList)
260                                 }
261
262                         }else{
263                                 exceptionUtil.buildAndThrowWorkflowException(execution, 2500, "Service Instance was not found in aai")
264                         }
265
266                 }catch(BpmnError e) {
267                         throw e;
268                 }catch(NotFoundException e) {
269                         msoLogger.debug("Service Instance does not exist AAI")
270                         exceptionUtil.buildAndThrowWorkflowException(execution, 404, "Service Instance was not found in aai")
271                 }catch(Exception ex) {
272                         String msg = "Internal Error in getServiceInstance: " + ex.getMessage()
273                         msoLogger.debug(msg)
274                         exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg)
275                 }
276         }
277
278
279         // *******************************
280         //
281         // *******************************
282         public void prepareVnfAndModulesDelete (DelegateExecution execution) {
283                 def isDebugEnabled=execution.getVariable(DebugFlag)
284                 msoLogger.trace("Inside prepareVnfAndModulesDelete of DeleteVcpeResCustService ")
285
286                 try {
287                         List vnfList = execution.getVariable(Prefix+"relatedVnfIdList")
288                         int vnfsDeletedCount = execution.getVariable(Prefix+"vnfsDeletedCount")
289                         String vnfModelInfoString = ""
290                         String vnfId = ""
291                         if (vnfList.size() > 0 ) {
292                                 vnfId = vnfList.get(vnfsDeletedCount.intValue())
293                         }
294
295                         execution.setVariable("vnfId", vnfId)
296                         msoLogger.debug("need to delete vnfId:" + vnfId)
297
298                         msoLogger.trace("Completed prepareVnfAndModulesDelete of DeleteVcpeResCustService ")
299                 } catch (Exception ex) {
300                         // try error in method block
301                         String exceptionMessage = "Bpmn error encountered in DeleteVcpeResCustService flow. Unexpected Error from method prepareVnfAndModulesDelete() - " + ex.getMessage()
302                         exceptionUtil.buildAndThrowWorkflowException(execution, 7000, exceptionMessage)
303                 }
304          }
305
306         // *******************************
307         //     Validate Vnf request Section -> increment count
308         // *******************************
309         public void validateVnfDelete (DelegateExecution execution) {
310                 def isDebugEnabled=execution.getVariable(DebugFlag)
311                 msoLogger.trace("Inside validateVnfDelete of DeleteVcpeResCustService ")
312
313                 try {
314                         int vnfsDeletedCount = execution.getVariable(Prefix+"vnfsDeletedCount")
315                         vnfsDeletedCount++
316
317                         execution.setVariable(Prefix+"vnfsDeletedCount", vnfsDeletedCount)
318
319                         msoLogger.debug(" ***** Completed validateVnfDelete of DeleteVcpeResCustService ***** "+" vnf # "+vnfsDeletedCount)
320                 } catch (Exception ex) {
321                         // try error in method block
322                         String exceptionMessage = "Bpmn error encountered in DeleteVcpeResCustService flow. Unexpected Error from method validateVnfDelete() - " + ex.getMessage()
323                         exceptionUtil.buildAndThrowWorkflowException(execution, 7000, exceptionMessage)
324                 }
325          }
326
327
328         // *****************************************
329         //     Prepare Completion request Section
330         // *****************************************
331         public void postProcessResponse (DelegateExecution execution) {
332                 def isDebugEnabled=execution.getVariable(DebugFlag)
333                 msoLogger.trace("Inside postProcessResponse of DeleteVcpeResCustService ")
334
335                 try {
336                         String source = execution.getVariable("source")
337                         String requestId = execution.getVariable("msoRequestId")
338
339                         String msoCompletionRequest =
340                                         """<aetgt:MsoCompletionRequest xmlns:aetgt="http://org.onap/so/workflow/schema/v1"
341                                                                         xmlns:ns="http://org.onap/so/request/types/v1">
342                                                         <request-info xmlns="http://org.onap/so/infra/vnf-request/v1">
343                                                                 <request-id>${MsoUtils.xmlEscape(requestId)}</request-id>
344                                                                 <action>DELETE</action>
345                                                                 <source>${MsoUtils.xmlEscape(source)}</source>
346                                                            </request-info>
347                                                         <aetgt:status-message>vCPE Res Cust Service Instance has been deleted successfully.</aetgt:status-message>
348                                                            <aetgt:mso-bpel-name>BPMN Service Instance macro action: DELETE</aetgt:mso-bpel-name>
349                                                 </aetgt:MsoCompletionRequest>"""
350
351                         // Format Response
352                         String xmlMsoCompletionRequest = utils.formatXml(msoCompletionRequest)
353
354                         msoLogger.debug(xmlMsoCompletionRequest)
355                         execution.setVariable(Prefix+"Success", true)
356                         execution.setVariable(Prefix+"CompleteMsoProcessRequest", xmlMsoCompletionRequest)
357                         msoLogger.debug(" SUCCESS flow, going to CompleteMsoProcess - " + "\n" + xmlMsoCompletionRequest)
358                 } catch (BpmnError e) {
359                 throw e;
360
361                 } catch (Exception ex) {
362                         // try error in method block
363                         String exceptionMessage = "Bpmn error encountered in DeleteServiceInstance flow. Unexpected Error from method postProcessResponse() - " + ex.getMessage()
364                         exceptionUtil.buildAndThrowWorkflowException(execution, 7000, exceptionMessage)
365                 }
366         }
367
368         public void prepareFalloutRequest(DelegateExecution execution){
369                 def isDebugEnabled=execution.getVariable(DebugFlag)
370                 msoLogger.trace("STARTED DeleteVcpeResCustService prepareFalloutRequest Process ")
371
372                 try {
373                         WorkflowException wfex = execution.getVariable("WorkflowException")
374                         msoLogger.debug(" Incoming Workflow Exception: " + wfex.toString())
375                         String requestInfo = execution.getVariable(Prefix+"requestInfo")
376                         msoLogger.debug(" Incoming Request Info: " + requestInfo)
377
378                         String falloutRequest = exceptionUtil.processMainflowsBPMNException(execution, requestInfo)
379
380                         execution.setVariable(Prefix+"falloutRequest", falloutRequest)
381                 } catch (Exception ex) {
382                         msoLogger.debug("Error Occured in DeleteVcpeResCustService prepareFalloutRequest Process " + ex.getMessage())
383                         exceptionUtil.buildAndThrowWorkflowException(execution, 2500, "Internal Error - Occured in DeleteVcpeResCustService prepareFalloutRequest Process")
384                 }
385                 msoLogger.trace("COMPLETED DeleteVcpeResCustService prepareFalloutRequest Process ")
386         }
387
388
389         public void sendSyncError (DelegateExecution execution) {
390                 def isDebugEnabled=execution.getVariable(DebugFlag)
391                 msoLogger.trace("Inside sendSyncError() of DeleteVcpeResCustService ")
392
393                 try {
394                         String errorMessage = ""
395                         if (execution.getVariable("WorkflowException") instanceof WorkflowException) {
396                                 WorkflowException wfe = execution.getVariable("WorkflowException")
397                                 errorMessage = wfe.getErrorMessage()
398                         } else {
399                                 errorMessage = "Sending Sync Error."
400                         }
401
402                         String buildworkflowException =
403                                 """<aetgt:WorkflowException xmlns:aetgt="http://org.onap/so/workflow/schema/v1">
404                                         <aetgt:ErrorMessage>${MsoUtils.xmlEscape(errorMessage)}</aetgt:ErrorMessage>
405                                         <aetgt:ErrorCode>7000</aetgt:ErrorCode>
406                                    </aetgt:WorkflowException>"""
407
408                         msoLogger.debug(buildworkflowException)
409                         sendWorkflowResponse(execution, 500, buildworkflowException)
410                 } catch (Exception ex) {
411                         msoLogger.debug(" Sending Sync Error Activity Failed. " + "\n" + ex.getMessage())
412                 }
413         }
414
415         public void processJavaException(DelegateExecution execution){
416                 def isDebugEnabled=execution.getVariable(DebugFlag)
417                 execution.setVariable("prefix",Prefix)
418                 try{
419                         msoLogger.debug("Caught a Java Exception")
420                         msoLogger.debug("Started processJavaException Method")
421                         msoLogger.debug("Variables List: " + execution.getVariables())
422                         execution.setVariable(Prefix+"unexpectedError", "Caught a Java Lang Exception")  // Adding this line temporarily until this flows error handling gets updated
423                         exceptionUtil.buildAndThrowWorkflowException(execution, 500, "Caught a Java Lang Exception")
424                 }catch(BpmnError b){
425                         msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, "Rethrowing MSOWorkflowException", "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, "");
426                         throw b
427                 }catch(Exception e){
428                         msoLogger.debug("Caught Exception during processJavaException Method: " + e)
429                         execution.setVariable(Prefix+"unexpectedError", "Exception in processJavaException method")  // Adding this line temporarily until this flows error handling gets updated
430                         exceptionUtil.buildAndThrowWorkflowException(execution, 500, "Exception in processJavaException method")
431                 }
432                 msoLogger.debug("Completed processJavaException Method")
433         }
434
435
436 }