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