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