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