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