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