Merge "[Docker] Revert use of Java11"
[so.git] / bpmn / so-bpmn-infrastructure-common / src / main / groovy / org / onap / so / bpmn / infrastructure / scripts / DeleteNetworkInstance.groovy
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP - SO
4  * ================================================================================
5  * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
6  * ================================================================================
7  * Modifications Copyright (c) 2019 Samsung
8  * ================================================================================
9  * Licensed under the Apache License, Version 2.0 (the "License");
10  * you may not use this file except in compliance with the License.
11  * You may obtain a copy of the License at
12  * 
13  *      http://www.apache.org/licenses/LICENSE-2.0
14  * 
15  * Unless required by applicable law or agreed to in writing, software
16  * distributed under the License is distributed on an "AS IS" BASIS,
17  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18  * See the License for the specific language governing permissions and
19  * limitations under the License.
20  * ============LICENSE_END=========================================================
21  */
22
23 package org.onap.so.bpmn.infrastructure.scripts
24
25 import org.onap.so.logger.LoggingAnchor
26 import org.camunda.bpm.engine.delegate.DelegateExecution
27 import org.onap.so.bpmn.common.scripts.AbstractServiceTaskProcessor
28 import org.onap.so.bpmn.common.scripts.ExceptionUtil
29 import org.onap.so.bpmn.common.scripts.MsoUtils
30 import org.onap.so.bpmn.common.scripts.NetworkUtils
31 import org.onap.so.bpmn.common.scripts.VidUtils
32 import org.onap.so.bpmn.core.WorkflowException
33 import org.onap.so.bpmn.core.json.JsonUtils
34 import org.onap.logging.filter.base.ErrorCode;
35 import org.onap.so.logger.MessageEnum
36 import org.slf4j.Logger
37 import org.slf4j.LoggerFactory
38
39 public class DeleteNetworkInstance extends AbstractServiceTaskProcessor {
40         String Prefix="DELNI_"
41         String groovyClassName = "DeleteNetworkInstance"
42         ExceptionUtil exceptionUtil = new ExceptionUtil()
43         JsonUtils jsonUtil = new JsonUtils()
44         VidUtils vidUtils = new VidUtils(this)
45         NetworkUtils networkUtils = new NetworkUtils()
46
47     private static final Logger logger = LoggerFactory.getLogger( DeleteNetworkInstance.class);
48         
49
50         public InitializeProcessVariables(DelegateExecution execution){
51                 
52                 execution.setVariable(Prefix + "Success", false)
53                 
54                 execution.setVariable(Prefix + "CompleteMsoProcessRequest", "")
55                 execution.setVariable(Prefix + "FalloutHandlerRequest", "")
56                 execution.setVariable(Prefix + "isSilentSuccess", false)
57                 
58         }
59         
60         // **************************************************
61         //     Pre or Prepare Request Section
62         // **************************************************
63
64         public void preProcessRequest (DelegateExecution execution) {
65                 def isDebugEnabled=execution.getVariable("isDebugLogEnabled")
66                 execution.setVariable("prefix",Prefix)
67
68                 logger.trace("Inside preProcessRequest() of " + groovyClassName + "")
69
70                 try {
71                         // initialize flow variables
72                         InitializeProcessVariables(execution)
73                                                         
74                         String sdncVersion = execution.getVariable("sdncVersion")
75                         if (sdncVersion == null || sdncVersion == '1610') {                             
76                                 // 'a-la-cart' default, sdncVersion = '1610' 
77                                 execution.setVariable("sdncVersion", "1610")
78                                 String bpmnRequest = execution.getVariable("bpmnRequest")
79                                 // set 'disableRollback'
80                                 if (bpmnRequest != null) {
81                                         String disableRollback = jsonUtil.getJsonValue(bpmnRequest, "requestDetails.requestInfo.suppressRollback")
82                                         if (disableRollback != null) {
83                                                 execution.setVariable("disableRollback", disableRollback)
84                                                 logger.debug("Received 'suppressRollback': " + disableRollback )
85                                         } else {
86                                             execution.setVariable("disableRollback", false)
87                                         }
88                                         logger.debug(" Set 'disableRollback' : " + execution.getVariable("disableRollback") )
89                                 } else {
90                                         String dataErrorMessage = " Invalid 'bpmnRequest' request."
91                                         logger.debug(dataErrorMessage)
92                                         exceptionUtil.buildAndThrowWorkflowException(execution, 2500, dataErrorMessage)
93                                 }
94
95                         } else {
96                             // 'macro' test ONLY, sdncVersion = '1702'
97                             logger.debug(" 'disableRollback' : " + execution.getVariable("disableRollback") )
98                         }       
99                         
100                         // get/set 'msoRequestId' and 'mso-request-id'
101                         String requestId = execution.getVariable("msoRequestId")
102                         if (requestId != null) {
103                                 execution.setVariable("mso-request-id", requestId)
104                         } else {
105                                 requestId = execution.getVariable("mso-request-id")
106                         }
107                         execution.setVariable(Prefix + "requestId", requestId)
108                         
109                         // get/set 'requestId' 
110                     if (execution.getVariable("requestId") == null) {
111                                 execution.setVariable("requestId", requestId)
112                         }
113                         
114                         // set action to "DELETE"
115                         execution.setVariable("action", "DELETE")
116                         
117                         //Place holder for additional code.
118
119                         // TODO ???
120                         // userParams???  1) pre-loads indicator, 2) 'auto-activation'  
121                         // Tag/Value parameters
122                         //
123                         // Map: 'networkInputParams': 'auto-activation''
124                         // Sample format? 
125                         // "requestParameters": {
126                         //     "userParams": [  
127             //          {
128                         //               "name": "someUserParam1",
129                         //               "value": "someValue1"
130                         //          }
131             //     ]
132                     //   }
133                         // 
134                         // String userParams = //use json util to extract "userParams"// 
135                 // execution.setVariable("networkInputParams", userParams)
136                         // else: execution.setVariable("networkInputParams", null)
137                         //
138
139
140                 } catch (Exception ex){
141                         sendSyncError(execution)
142                         String exceptionMessage = "Exception Encountered in " + groovyClassName + ", PreProcessRequest() - " + ex.getMessage()
143                         logger.debug(exceptionMessage)
144                         exceptionUtil.buildAndThrowWorkflowException(execution, 7000, exceptionMessage)
145
146                 }
147
148         }
149
150         public void getNetworkModelInfo (DelegateExecution execution) {
151                 def isDebugEnabled=execution.getVariable("isDebugLogEnabled")
152                 execution.setVariable("prefix", Prefix)
153
154                 logger.trace("Inside getNetworkModelInfo() of DeleteNetworkInstance")
155                 
156                 try {
157                         
158                         // For Ala-Carte (sdnc = 1610): 
159                         // 1. the Network ModelInfo is expected to be sent 
160                         //     via requestDetails.modelInfo (modelType = network), ex: modelCustomizationId.
161                         // 2. the Service ModelInfo is expected to be sent but will be IGNORE 
162                         //     via requestDetails.relatedInstanceList.relatedInstance.modelInfo (modelType = service)
163                                                                                  
164                 } catch (Exception ex) {
165                         sendSyncError(execution)
166                    String exceptionMessage = "Bpmn error encountered in DeleteNetworkInstance flow. getNetworkModelInfo() - " + ex.getMessage()
167                    logger.debug(exceptionMessage)
168                    exceptionUtil.buildAndThrowWorkflowException(execution, 7000, exceptionMessage)
169                         
170                 }
171
172         }
173         
174         public void sendSyncResponse (DelegateExecution execution) {
175                 def isDebugEnabled=execution.getVariable("isDebugLogEnabled")
176                 execution.setVariable("prefix",Prefix)
177
178                 logger.trace("Inside sendSyncResponse() of DeleteNetworkInstance")
179
180                 try {
181                         String requestId = execution.getVariable("mso-request-id")
182                         String serviceInstanceId = execution.getVariable("serviceInstanceId")
183
184                         // RESTResponse (for API Handler (APIH) Reply Task)
185                         String deleteNetworkRestRequest = """{"requestReferences":{"instanceId":"${serviceInstanceId}","requestId":"${requestId}"}}""".trim()
186
187                         logger.debug(" sendSyncResponse to APIH - " + "\n" + deleteNetworkRestRequest)
188
189                         sendWorkflowResponse(execution, 202, deleteNetworkRestRequest)
190
191                 } catch (Exception ex) {
192                          // caught exception
193                         String exceptionMessage = "Exception Encountered in  DeleteNetworkInstance, sendSyncResponse() - " + ex.getMessage()
194                         logger.debug(exceptionMessage)
195                         exceptionUtil.buildAndThrowWorkflowException(execution, 7000, exceptionMessage)
196
197                 }
198
199         }
200
201         public void prepareCompletion (DelegateExecution execution) {
202                 def isDebugEnabled=execution.getVariable("isDebugLogEnabled")
203                 execution.setVariable("prefix",Prefix)
204
205                 logger.trace("Inside prepareCompletion() of CreateNetworkInstance")
206
207                 try {
208
209                         String requestId = execution.getVariable("mso-request-id")
210                         String source = execution.getVariable(Prefix + "source")
211
212                         String msoCompletionRequest =
213                                 """<aetgt:MsoCompletionRequest xmlns:aetgt="http://org.onap/so/workflow/schema/v1"
214                                                                 xmlns:ns="http://org.onap/so/request/types/v1">
215                                                 <request-info xmlns="http://org.onap/so/infra/vnf-request/v1">
216                                                         <request-id>${MsoUtils.xmlEscape(requestId)}</request-id>
217                                                         <action>DELETE</action>
218                                                         <source>VID</source>
219                                                 </request-info>
220                                                 <aetgt:status-message>Network has been deleted successfully.</aetgt:status-message>
221                                                 <aetgt:mso-bpel-name>BPMN Network action: DELETE</aetgt:mso-bpel-name>
222                                         </aetgt:MsoCompletionRequest>"""
223
224                                 // Format Response
225                         String xmlMsoCompletionRequest = utils.formatXml(msoCompletionRequest)
226
227                         // normal path
228                         execution.setVariable(Prefix + "CompleteMsoProcessRequest", xmlMsoCompletionRequest)
229                         logger.debug(" Overall SUCCESS Response going to CompleteMsoProcess - " + "\n" + xmlMsoCompletionRequest)
230                 
231                 } catch (Exception ex) {
232                         String exceptionMessage = " Bpmn error encountered in CreateNetworkInstance flow. prepareCompletion() - " + ex.getMessage()
233                         logger.debug(exceptionMessage)
234                         exceptionUtil.buildAndThrowWorkflowException(execution, 7000, exceptionMessage)
235
236                 }
237
238
239         }
240         
241         public void prepareDBRequestError (DelegateExecution execution) {
242                 def isDebugEnabled=execution.getVariable("isDebugLogEnabled")
243                 execution.setVariable("prefix", Prefix)
244
245                 try {
246                         logger.trace("Inside prepareDBRequestError of DeleteNetworkInstance")
247                         
248                         // set DB Header Authorization 
249                         setBasicDBAuthHeader(execution, isDebugEnabled)
250                         
251                         WorkflowException wfe = execution.getVariable("WorkflowException")
252                         String statusMessage = wfe.getErrorMessage()
253                         String requestId = execution.getVariable(Prefix +"requestId")
254
255                         String dbRequest =
256                                         """<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/">
257                                                 <soapenv:Header/>
258                                                 <soapenv:Body>
259                                                         <ns:updateInfraRequest xmlns:ns="http://org.onap.so/requestsdb">
260                                                                 <requestId>${MsoUtils.xmlEscape(requestId)}</requestId>
261                                                                 <lastModifiedBy>BPMN</lastModifiedBy>
262                                                                 <statusMessage>${MsoUtils.xmlEscape(statusMessage)}</statusMessage>
263                                                                 <responseBody></responseBody>
264                                                                 <requestStatus>FAILED</requestStatus>
265                                                                 <progress></progress>
266                                                                 <vnfOutputs>&lt;network-outputs xmlns="http://org.onap/so/infra/vnf-request/v1" xmlns:aetgt="http://org.onap/so/infra/vnf-request/v1" xmlns:rest="http://schemas.activebpel.org/REST/2007/12/01/aeREST.xsd"/&gt;</vnfOutputs>
267                                                         </ns:updateInfraRequest>
268                                                 </soapenv:Body>
269                                            </soapenv:Envelope>"""
270
271                    execution.setVariable(Prefix + "deleteDBRequest", dbRequest)
272                    logger.debug(" DB Adapter Request - " + "\n" + dbRequest)
273
274                 } catch (Exception ex) {
275                         // caught exception
276                         String exceptionMessage = "Bpmn error encountered in  DeleteNetworkInstance, prepareDBRequestError() - " + ex.getMessage()
277                         logger.debug(exceptionMessage)
278                         exceptionUtil.buildWorkflowException(execution, 7000, exceptionMessage)
279
280                 }
281
282          }
283
284         // **************************************************
285         //     Post or Validate Response Section
286         // **************************************************
287
288         public void postProcessResponse (DelegateExecution execution) {
289                 def isDebugEnabled=execution.getVariable("isDebugLogEnabled")
290                 execution.setVariable("prefix", Prefix)
291         
292                 logger.trace("Inside postProcessResponse() of DeleteNetworkInstance")
293                 
294                 try {
295                         if (execution.getVariable("CMSO_ResponseCode") == "200") {
296                            execution.setVariable(Prefix + "Success", true)
297                            logger.trace("DeleteNetworkInstance Success")
298                            //   Place holder for additional code.
299                            
300                         } else {
301                            execution.setVariable(Prefix + "Success", false)
302                            logger.trace("DeleteNetworkInstance Failed in CompletionMsoProces flow!.")
303                         
304                         }   
305                         
306         
307                 } catch (Exception ex) {
308                         String exceptionMessage = " Bpmn error encountered in DeleteNetworkInstance flow. postProcessResponse() - " + ex.getMessage()
309                         logger.debug(exceptionMessage)
310                         exceptionUtil.buildAndThrowWorkflowException(execution, 7000, exceptionMessage)
311         
312             }
313         
314         }
315
316
317         // *******************************
318         //     Build Error Section
319         // *******************************
320
321         // Prepare for FalloutHandler
322         public void buildErrorResponse (DelegateExecution execution) {
323                 def isDebugEnabled=execution.getVariable("isDebugLogEnabled")
324                 execution.setVariable("prefix", Prefix)
325
326                 logger.trace("Prepare for FalloutHandler. FAILURE - prepare request for sub-process FalloutHandler.")
327
328                 String dbReturnCode = execution.getVariable(Prefix + "dbReturnCode")
329                 logger.debug("DB Update Response Code  : " + dbReturnCode)
330                 logger.debug("DB Update Response String: " + '\n' + execution.getVariable(Prefix + "deleteDBResponse"))
331
332                 String falloutHandlerRequest = ""
333                 String requestId = execution.getVariable("mso-request-id")
334                 String source = execution.getVariable(Prefix + "source")
335                 execution.setVariable(Prefix + "Success", false)
336                 try {
337                         WorkflowException wfe = execution.getVariable("WorkflowException")
338                         String errorCode = String.valueOf(wfe.getErrorCode())
339                         String errorMessage = wfe.getErrorMessage()
340
341                         falloutHandlerRequest =
342                             """<aetgt:FalloutHandlerRequest xmlns:aetgt="http://org.onap/so/workflow/schema/v1"
343                                                                      xmlns:ns="http://org.onap/so/request/types/v1"
344                                                                      xmlns:wfsch="http://org.onap/so/workflow/schema/v1">
345                                            <request-info xmlns="http://org.onap/so/infra/vnf-request/v1">
346                                               <request-id>${MsoUtils.xmlEscape(requestId)}</request-id>
347                                               <action>DELETE</action>
348                                               <source>${MsoUtils.xmlEscape(source)}</source>
349                                            </request-info>
350                                                 <aetgt:WorkflowException xmlns:aetgt="http://org.onap/so/workflow/schema/v1">
351                                                         <aetgt:ErrorMessage>${MsoUtils.xmlEscape(errorMessage)}</aetgt:ErrorMessage>
352                                                         <aetgt:ErrorCode>${MsoUtils.xmlEscape(errorCode)}</aetgt:ErrorCode>
353                                                 </aetgt:WorkflowException>
354                                         </aetgt:FalloutHandlerRequest>"""
355
356                         logger.debug(falloutHandlerRequest)
357                         execution.setVariable(Prefix + "FalloutHandlerRequest", falloutHandlerRequest)
358                         logger.error(LoggingAnchor.FOUR, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(),
359                                         "Overall Error Response going to FalloutHandler: " + "\n" + falloutHandlerRequest, "BPMN",
360                                         ErrorCode.UnknownError.getValue())
361
362                 } catch (Exception ex) {
363                         // caught exception
364                         String exceptionMessage = "Bpmn error encountered in DeleteNetworkInstance, buildErrorResponse() - " + ex.getMessage()
365                         logger.debug(exceptionMessage)
366                         falloutHandlerRequest =
367                         """<aetgt:FalloutHandlerRequest xmlns:aetgt="http://org.onap/so/workflow/schema/v1"
368                                                                      xmlns:ns="http://org.onap/so/request/types/v1"
369                                                                      xmlns:wfsch="http://org.onap/so/workflow/schema/v1">
370                                            <request-info xmlns="http://org.onap/so/infra/vnf-request/v1">
371                                               <request-id>${MsoUtils.xmlEscape(requestId)}</request-id>
372                                               <action>DELEtE</action>
373                                               <source>${MsoUtils.xmlEscape(source)}</source>
374                                            </request-info>
375                                                 <aetgt:WorkflowException xmlns:aetgt="http://org.onap/so/workflow/schema/v1">
376                                                         <aetgt:ErrorMessage>${MsoUtils.xmlEscape(exceptionMessage)}</aetgt:ErrorMessage>
377                                                         <aetgt:ErrorCode>9999</aetgt:ErrorCode>
378                                                 </aetgt:WorkflowException>
379                                         </aetgt:FalloutHandlerRequest>"""
380                         execution.setVariable(Prefix + "FalloutHandlerRequest", falloutHandlerRequest)
381                         logger.error(LoggingAnchor.FIVE, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(),
382                                         "Overall Error Response going to FalloutHandler: " + "\n" + falloutHandlerRequest,"BPMN",
383                                         ErrorCode.UnknownError.getValue(), "Exception is:\n" + ex)
384                 }
385         }
386
387
388         public void sendSyncError (DelegateExecution execution) {
389                 def isDebugEnabled=execution.getVariable("isDebugLogEnabled")
390                 execution.setVariable("prefix", Prefix)
391
392                 try {
393                         String requestId = execution.getVariable("mso-request-id")
394                         String serviceInstanceId = execution.getVariable("serviceInstanceId")
395
396                         // RESTResponse (for API Handler (APIH) Reply Task)
397                         String deleteNetworkRestError = """{"requestReferences":{"instanceId":"${serviceInstanceId}","requestId":"${requestId}"}}""".trim()
398
399                         logger.debug(" sendSyncResponse to APIH - " + "\n" + deleteNetworkRestError)
400
401                         sendWorkflowResponse(execution, 500, deleteNetworkRestError)
402
403                 } catch (Exception ex) {
404                         logger.debug(" Sending Sync Error Activity Failed -  DeleteNetworkInstance, sendSyncError(): " + "\n" + ex.getMessage())
405                 }
406         }
407
408         public void processJavaException(DelegateExecution execution){
409                 def isDebugEnabled=execution.getVariable("isDebugLogEnabled")
410                 execution.setVariable("prefix",Prefix)
411                 try{
412                         logger.debug("Caught a Java Exception")
413                         logger.debug("Started processJavaException Method")
414                         logger.debug("Variables List: " + execution.getVariables())
415                         execution.setVariable("UnexpectedError", "Caught a Java Lang Exception")  // Adding this line temporarily until this flows error handling gets updated
416                         exceptionUtil.buildWorkflowException(execution, 500, "Caught a Java Lang Exception")
417                         
418                 }catch(Exception e){
419                         logger.debug("Caught Exception during processJavaException Method: " + e)
420                         execution.setVariable("UnexpectedError", "Exception in processJavaException method")  // Adding this line temporarily until this flows error handling gets updated
421                         exceptionUtil.buildWorkflowException(execution, 500, "Exception in processJavaException method")
422                 }
423                 logger.debug("Completed processJavaException Method of " + Prefix)
424         }
425
426 }