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