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