Containerization feature of SO
[so.git] / bpmn / so-bpmn-infrastructure-flows / 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  * 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.AaiUtil
25 import org.onap.so.bpmn.common.scripts.AbstractServiceTaskProcessor
26 import org.onap.so.bpmn.common.scripts.CatalogDbUtils
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.UrnPropertiesReader
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.onap.so.rest.APIResponse
36
37 import static org.apache.commons.lang3.StringUtils.isBlank
38
39
40 /**
41  * This groovy class supports the <class>DeleteVcpeResCustService.bpmn</class> process.
42  *
43  * @author dm4252
44  *
45  */
46 public class DeleteVcpeResCustService extends AbstractServiceTaskProcessor {
47         private static final MsoLogger msoLogger = MsoLogger.getMsoLogger(MsoLogger.Catalog.BPEL, DeleteVcpeResCustService.class);
48
49         private static final String DebugFlag = "isDebugLogEnabled"
50
51         String Prefix = "DVRCS_"
52         ExceptionUtil exceptionUtil = new ExceptionUtil()
53         JsonUtils jsonUtil = new JsonUtils()
54         VidUtils vidUtils = new VidUtils()
55         CatalogDbUtils catalogDbUtils = new CatalogDbUtils()
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 tenantId = jsonUtil.getJsonValue(cloudConfiguration, "tenantId")
142                         execution.setVariable("tenantId", tenantId)
143                         msoLogger.debug("tenantId: "+ tenantId)
144
145                         String sdncVersion = "1707"
146                         execution.setVariable("sdncVersion", sdncVersion)
147                         msoLogger.debug("sdncVersion: "+ sdncVersion)
148                         
149                         //For Completion Handler & Fallout Handler
150                         String requestInfo =
151                         """<request-info xmlns="http://org.onap/so/infra/vnf-request/v1">
152                                         <request-id>${MsoUtils.xmlEscape(requestId)}</request-id>
153                                         <action>DELETE</action>
154                                         <source>${MsoUtils.xmlEscape(source)}</source>
155                                    </request-info>"""
156
157                         execution.setVariable(Prefix+"requestInfo", requestInfo)
158                         
159                         //Setting for Generic Sub Flows
160                         execution.setVariable("GENGS_type", "service-instance")
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         public void prepareServiceDelete(DelegateExecution execution) {
193                 def isDebugEnabled=execution.getVariable(DebugFlag)
194                 msoLogger.trace("Inside prepareServiceDelete() of DeleteVcpeResCustService ")
195                 
196                 try {
197                         
198                         String serviceInstanceId = execution.getVariable("serviceInstanceId")
199                         
200                         // confirm if ServiceInstance was found
201                         if ( !execution.getVariable("GENGS_FoundIndicator") )
202                         {
203                                 String exceptionMessage = "Bpmn error encountered in DeleteVcpeResCustService flow. Service Instance was not found in AAI by id: " + serviceInstanceId
204                                 exceptionUtil.buildAndThrowWorkflowException(execution, 7000, exceptionMessage)
205                         }
206                         
207                         // get variable within incoming json
208                         String DeleteVcpeResCustServiceRequest = execution.getVariable("DeleteVcpeResCustServiceRequest");
209                         
210                         // get SI extracted by GenericGetService
211                         String serviceInstanceAaiRecord = execution.getVariable("GENGS_service");
212                         
213                         msoLogger.debug("serviceInstanceAaiRecord: "+serviceInstanceAaiRecord)
214                         serviceInstanceAaiRecord = utils.removeXmlNamespaces(serviceInstanceAaiRecord)
215                         
216                         def (TXC_found, TXC_id) = new Tuple(false, null)
217                         def (BRG_found, BRG_id) = new Tuple(false, null)
218                         List relatedVnfIdList = []
219                         
220                         for(Node rel: utils.getMultNodeObjects(serviceInstanceAaiRecord, "relationship")) {
221                                 def relto = utils.getChildNodeText(rel, "related-to")
222                                 def relink = utils.getChildNodeText(rel, "related-link")
223                                 msoLogger.debug("check: "+relto+" link: "+relink)
224                                 
225                                 if(isBlank(relto) || isBlank(relink)) {
226                                         
227                                 } else if(relto == "generic-vnf") {
228                                         def id = relink.substring(relink.indexOf("/generic-vnf/")+13)
229                                         if(id.endsWith("/")) {
230                                                 id = id.substring(0, id.length()-1)
231                                         }
232                                         
233                                         relatedVnfIdList.add(id)
234                                         
235                                 } else if(relto == "allotted-resource") {
236                                         def (type, id) = getAaiAr(execution, relink)
237                                         
238                                         if(isBlank(type) || isBlank(id)) {
239                                                 
240                                         } else if(type == "TunnelXConn" || type == "Tunnel XConn") {
241                                                 msoLogger.debug("TunnelXConn AR found")
242                                                 TXC_found = true
243                                                 TXC_id = id
244                                                 
245                                         } else if(type == "BRG") {
246                                                 msoLogger.debug("BRG AR found")
247                                                 BRG_found = true
248                                                 BRG_id = id
249                                         }
250                                 }
251                         }
252                         
253                         execution.setVariable(Prefix+"TunnelXConn", TXC_found)
254                         execution.setVariable("TXC_allottedResourceId", TXC_id)
255                         msoLogger.debug("TXC_allottedResourceId: " + TXC_id)
256                                                 
257                         execution.setVariable(Prefix+"BRG", BRG_found)
258                         execution.setVariable("BRG_allottedResourceId", BRG_id)
259                         msoLogger.debug("BRG_allottedResourceId: " + BRG_id)
260                         
261                         int vnfsCount = relatedVnfIdList.size()
262                         execution.setVariable(Prefix+"vnfsCount", vnfsCount)
263                         msoLogger.debug(" "+Prefix+"vnfsCount : " + vnfsCount)
264                         if(vnfsCount > 0) {
265                                 execution.setVariable(Prefix+"relatedVnfIdList", relatedVnfIdList)
266                         }
267                         
268                         msoLogger.trace("Completed prepareServiceDelete() of DeleteVcpeResCustService ")
269                 } catch (BpmnError e){
270                         throw e;
271                 } catch (Exception ex) {
272                         sendSyncError(execution)
273                     String exceptionMessage = "Bpmn error encountered in DeleteVcpeResCustService flow. prepareServiceDelete() - " + ex.getMessage()
274                     msoLogger.debug(exceptionMessage)
275                     exceptionUtil.buildAndThrowWorkflowException(execution, 7000, exceptionMessage)
276                 }
277         }
278         
279         private getAaiAr(DelegateExecution execution, String relink) {
280                 def isDebugEnabled = execution.getVariable(DebugFlag)
281                 AaiUtil aaiUtil = new AaiUtil(this)
282                 String aaiEndpoint = UrnPropertiesReader.getVariable("aai.endpoint",execution) + relink
283                 
284                 msoLogger.debug("get AR info " + aaiEndpoint)
285                 APIResponse response = aaiUtil.executeAAIGetCall(execution, aaiEndpoint)
286                 
287                 int responseCode = response.getStatusCode()
288                 msoLogger.debug("get AR info responseCode:" + responseCode)
289                 
290                 String aaiResponse = response.getResponseBodyAsString()
291                 msoLogger.debug("get AR info " + aaiResponse)
292                 
293                 if(responseCode < 200 || responseCode >= 300 || isBlank(aaiResponse)) {
294                         return new Tuple2(null, null)
295                 }
296                 
297                 def type = utils.getNodeText(aaiResponse, "type")
298                 def id = utils.getNodeText(aaiResponse, "id")
299                 
300                 return new Tuple2(type, id)
301         }
302         
303         
304         // *******************************
305         //     
306         // *******************************
307         public void prepareVnfAndModulesDelete (DelegateExecution execution) {
308                 def isDebugEnabled=execution.getVariable(DebugFlag)
309                 msoLogger.trace("Inside prepareVnfAndModulesDelete of DeleteVcpeResCustService ")
310
311                 try {
312                         List vnfList = execution.getVariable(Prefix+"relatedVnfIdList")
313                         int vnfsDeletedCount = execution.getVariable(Prefix+"vnfsDeletedCount")
314                         String vnfModelInfoString = ""
315                         String vnfId = ""
316                         if (vnfList.size() > 0 ) {
317                                 vnfId = vnfList.get(vnfsDeletedCount.intValue())
318                         }
319                                                         
320                         execution.setVariable("vnfId", vnfId)
321                         msoLogger.debug("need to delete vnfId:" + vnfId)
322
323                         msoLogger.trace("Completed prepareVnfAndModulesDelete of DeleteVcpeResCustService ")
324                 } catch (Exception ex) {
325                         // try error in method block
326                         String exceptionMessage = "Bpmn error encountered in DeleteVcpeResCustService flow. Unexpected Error from method prepareVnfAndModulesDelete() - " + ex.getMessage()
327                         exceptionUtil.buildAndThrowWorkflowException(execution, 7000, exceptionMessage)
328                 }
329          }
330         
331         // *******************************
332         //     Validate Vnf request Section -> increment count
333         // *******************************
334         public void validateVnfDelete (DelegateExecution execution) {
335                 def isDebugEnabled=execution.getVariable(DebugFlag)
336                 msoLogger.trace("Inside validateVnfDelete of DeleteVcpeResCustService ")
337
338                 try {
339                         int vnfsDeletedCount = execution.getVariable(Prefix+"vnfsDeletedCount")
340                         vnfsDeletedCount++
341                         
342                         execution.setVariable(Prefix+"vnfsDeletedCount", vnfsDeletedCount)
343                         
344                         msoLogger.debug(" ***** Completed validateVnfDelete of DeleteVcpeResCustService ***** "+" vnf # "+vnfsDeletedCount)
345                 } catch (Exception ex) {
346                         // try error in method block
347                         String exceptionMessage = "Bpmn error encountered in DeleteVcpeResCustService flow. Unexpected Error from method validateVnfDelete() - " + ex.getMessage()
348                         exceptionUtil.buildAndThrowWorkflowException(execution, 7000, exceptionMessage)
349                 }
350          }
351
352         
353         // *****************************************
354         //     Prepare Completion request Section
355         // *****************************************
356         public void postProcessResponse (DelegateExecution execution) {
357                 def isDebugEnabled=execution.getVariable(DebugFlag)
358                 msoLogger.trace("Inside postProcessResponse of DeleteVcpeResCustService ")
359
360                 try {
361                         String source = execution.getVariable("source")
362                         String requestId = execution.getVariable("msoRequestId")
363
364                         String msoCompletionRequest =
365                                         """<aetgt:MsoCompletionRequest xmlns:aetgt="http://org.onap/so/workflow/schema/v1"
366                                                                         xmlns:ns="http://org.onap/so/request/types/v1">
367                                                         <request-info xmlns="http://org.onap/so/infra/vnf-request/v1">
368                                                                 <request-id>${MsoUtils.xmlEscape(requestId)}</request-id>
369                                                                 <action>DELETE</action>
370                                                                 <source>${MsoUtils.xmlEscape(source)}</source>
371                                                            </request-info>
372                                                         <aetgt:status-message>vCPE Res Cust Service Instance has been deleted successfully.</aetgt:status-message>
373                                                            <aetgt:mso-bpel-name>BPMN Service Instance macro action: DELETE</aetgt:mso-bpel-name>
374                                                 </aetgt:MsoCompletionRequest>"""
375
376                         // Format Response
377                         String xmlMsoCompletionRequest = utils.formatXml(msoCompletionRequest)
378
379                         msoLogger.debug(xmlMsoCompletionRequest)
380                         execution.setVariable(Prefix+"Success", true)
381                         execution.setVariable(Prefix+"CompleteMsoProcessRequest", xmlMsoCompletionRequest)
382                         msoLogger.debug(" SUCCESS flow, going to CompleteMsoProcess - " + "\n" + xmlMsoCompletionRequest)
383                 } catch (BpmnError e) {
384                 throw e;
385
386                 } catch (Exception ex) {
387                         // try error in method block
388                         String exceptionMessage = "Bpmn error encountered in DeleteServiceInstance flow. Unexpected Error from method postProcessResponse() - " + ex.getMessage()
389                         exceptionUtil.buildAndThrowWorkflowException(execution, 7000, exceptionMessage)
390                 }
391         }
392
393         public void prepareFalloutRequest(DelegateExecution execution){
394                 def isDebugEnabled=execution.getVariable(DebugFlag)
395                 msoLogger.trace("STARTED DeleteVcpeResCustService prepareFalloutRequest Process ")
396
397                 try {
398                         WorkflowException wfex = execution.getVariable("WorkflowException")
399                         msoLogger.debug(" Incoming Workflow Exception: " + wfex.toString())
400                         String requestInfo = execution.getVariable(Prefix+"requestInfo")
401                         msoLogger.debug(" Incoming Request Info: " + requestInfo)
402
403                         String falloutRequest = exceptionUtil.processMainflowsBPMNException(execution, requestInfo)
404
405                         execution.setVariable(Prefix+"falloutRequest", falloutRequest)
406                 } catch (Exception ex) {
407                         msoLogger.debug("Error Occured in DeleteVcpeResCustService prepareFalloutRequest Process " + ex.getMessage())
408                         exceptionUtil.buildAndThrowWorkflowException(execution, 2500, "Internal Error - Occured in DeleteVcpeResCustService prepareFalloutRequest Process")
409                 }
410                 msoLogger.trace("COMPLETED DeleteVcpeResCustService prepareFalloutRequest Process ")
411         }
412
413
414         public void sendSyncError (DelegateExecution execution) {
415                 def isDebugEnabled=execution.getVariable(DebugFlag)
416                 msoLogger.trace("Inside sendSyncError() of DeleteVcpeResCustService ")
417
418                 try {
419                         String errorMessage = ""
420                         if (execution.getVariable("WorkflowException") instanceof WorkflowException) {
421                                 WorkflowException wfe = execution.getVariable("WorkflowException")
422                                 errorMessage = wfe.getErrorMessage()
423                         } else {
424                                 errorMessage = "Sending Sync Error."
425                         }
426
427                         String buildworkflowException =
428                                 """<aetgt:WorkflowException xmlns:aetgt="http://org.onap/so/workflow/schema/v1">
429                                         <aetgt:ErrorMessage>${MsoUtils.xmlEscape(errorMessage)}</aetgt:ErrorMessage>
430                                         <aetgt:ErrorCode>7000</aetgt:ErrorCode>
431                                    </aetgt:WorkflowException>"""
432
433                         msoLogger.debug(buildworkflowException)
434                         sendWorkflowResponse(execution, 500, buildworkflowException)
435                 } catch (Exception ex) {
436                         msoLogger.debug(" Sending Sync Error Activity Failed. " + "\n" + ex.getMessage())
437                 }
438         }
439
440         public void processJavaException(DelegateExecution execution){
441                 def isDebugEnabled=execution.getVariable(DebugFlag)
442                 execution.setVariable("prefix",Prefix)
443                 try{
444                         msoLogger.debug("Caught a Java Exception")
445                         msoLogger.debug("Started processJavaException Method")
446                         msoLogger.debug("Variables List: " + execution.getVariables())
447                         execution.setVariable(Prefix+"unexpectedError", "Caught a Java Lang Exception")  // Adding this line temporarily until this flows error handling gets updated
448                         exceptionUtil.buildAndThrowWorkflowException(execution, 500, "Caught a Java Lang Exception")
449                 }catch(BpmnError b){
450                         msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, "Rethrowing MSOWorkflowException", "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, "");
451                         throw b
452                 }catch(Exception e){
453                         msoLogger.debug("Caught Exception during processJavaException Method: " + e)
454                         execution.setVariable(Prefix+"unexpectedError", "Exception in processJavaException method")  // Adding this line temporarily until this flows error handling gets updated
455                         exceptionUtil.buildAndThrowWorkflowException(execution, 500, "Exception in processJavaException method")
456                 }
457                 msoLogger.debug("Completed processJavaException Method")
458         }
459
460
461 }