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