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