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