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