Dynamic Cloud Owner Support
[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  * 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                         String networkId = execution.getVariable("networkId") !=null ? execution.getVariable("networkId") : ""
284
285                         String msoCompletionRequest =
286                                 """<aetgt:MsoCompletionRequest xmlns:aetgt="http://org.onap/so/workflow/schema/v1"
287                                                                 xmlns:ns="http://org.onap/so/request/types/v1">
288                                                 <request-info xmlns="http://org.onap/so/infra/vnf-request/v1">
289                                                         <request-id>${MsoUtils.xmlEscape(requestId)}</request-id>
290                                                         <action>CREATE</action>
291                                                         <source>VID</source>
292                                                 </request-info>
293                                                 <aetgt:status-message>Network has been created successfully.</aetgt:status-message>
294                         <aetgt:networkId>${MsoUtils.xmlEscape(networkId)}</aetgt:networkId>
295                                                 <aetgt:mso-bpel-name>BPMN Network action: CREATE</aetgt:mso-bpel-name>
296                                         </aetgt:MsoCompletionRequest>"""
297
298                                 // Format Response
299                         String xmlMsoCompletionRequest = utils.formatXml(msoCompletionRequest)
300
301                         // normal path
302                         execution.setVariable(Prefix + "Success", true)
303                         execution.setVariable(Prefix + "CompleteMsoProcessRequest", xmlMsoCompletionRequest)
304                         msoLogger.debug(" Overall SUCCESS Response going to CompleteMsoProcess - " + "\n" + xmlMsoCompletionRequest)
305                 
306                 } catch (Exception ex) {
307                         String exceptionMessage = " Bpmn error encountered in CreateNetworkInstance flow. prepareCompletion() - " + ex.getMessage()
308                         msoLogger.debug(exceptionMessage)
309                         exceptionUtil.buildAndThrowWorkflowException(execution, 7000, exceptionMessage)
310
311                 }
312
313
314         }
315
316         
317         
318         
319         // **************************************************
320         //     Post or Validate Response Section
321         // **************************************************
322
323         public void postProcessResponse (DelegateExecution execution) {
324                 def isDebugEnabled=execution.getVariable("isDebugLogEnabled")
325                 execution.setVariable("prefix", Prefix)
326         
327                 msoLogger.trace("Start postProcessResponse")
328                 
329                 try {
330                         
331                         if (execution.getVariable("CMSO_ResponseCode") == "200") {
332                                 execution.setVariable(Prefix + "Success", true)
333                                 msoLogger.trace("CreateNetworkInstance Success ****")
334                                 //   Place holder for additional code.
335                                 
336                          } else {
337                                 execution.setVariable(Prefix + "Success", false)
338                                 msoLogger.trace("CreateNetworkInstance Failed in CompletionMsoProces flow!. ****")
339                          
340                          }
341                                 
342         
343                 } catch (Exception ex) {
344                         String exceptionMessage = " Bpmn error encountered in CreateNetworkInstance flow. postProcessResponse() - " + ex.getMessage()
345                         msoLogger.debug(exceptionMessage)
346                         exceptionUtil.buildAndThrowWorkflowException(execution, 7000, exceptionMessage)
347         
348             }
349         
350         }
351
352
353         // *******************************
354         //     Build Error Section
355         // *******************************
356
357         public void processRollbackData (DelegateExecution execution) {
358                 def isDebugEnabled=execution.getVariable("isDebugLogEnabled")
359                 execution.setVariable("prefix", Prefix)
360
361                 msoLogger.trace("Start processRollbackData")
362         
363                 try {
364                         //execution.getVariable("orchestrationStatus")
365                         //execution.getVariable("networkId")
366                         //execution.getVariable("networkName")
367                         //networkOutputParams
368                         //rollbackData
369                         //rolledBack
370
371                 } catch (Exception ex) {
372                         msoLogger.debug(" Bpmn error encountered in CreateNetworkInstance flow. callDBCatalog() - " + ex.getMessage())
373                 }
374                 
375         }
376         
377         // Prepare for FalloutHandler
378         public void buildErrorResponse (DelegateExecution execution) {
379                 def isDebugEnabled=execution.getVariable("isDebugLogEnabled")
380                 execution.setVariable("prefix", Prefix)
381
382                 msoLogger.debug("DB updateInfraRequest ResponseCode: " + execution.getVariable(Prefix + "dbReturnCode"))
383                 msoLogger.debug("DB updateInfraRequest Response: " + execution.getVariable(Prefix + "createDBResponse"))
384                 
385                 msoLogger.trace("Prepare for FalloutHandler. FAILURE - prepare request for sub-process FalloutHandler.")
386
387                 String falloutHandlerRequest = ""
388                 String requestId = execution.getVariable("mso-request-id")
389
390                 try {
391                         
392                         WorkflowException wfe = execution.getVariable("WorkflowException")
393                         String errorCode = String.valueOf(wfe.getErrorCode())
394                         String errorMessage = wfe.getErrorMessage()
395                         falloutHandlerRequest =
396                                 """<aetgt:FalloutHandlerRequest xmlns:aetgt="http://org.onap/so/workflow/schema/v1"
397                                                                      xmlns:ns="http://org.onap/so/request/types/v1"
398                                                                      xmlns:wfsch="http://org.onap/so/workflow/schema/v1">
399                                            <request-info xmlns="http://org.onap/so/infra/vnf-request/v1">
400                                               <request-id>${MsoUtils.xmlEscape(requestId)}</request-id>
401                                               <action>CREATE</action>
402                                               <source>VID</source>
403                                            </request-info>
404                                                 <aetgt:WorkflowException xmlns:aetgt="http://org.onap/so/workflow/schema/v1">
405                                                         <aetgt:ErrorMessage>${MsoUtils.xmlEscape(errorMessage)}</aetgt:ErrorMessage>
406                                                         <aetgt:ErrorCode>${MsoUtils.xmlEscape(errorCode)}</aetgt:ErrorCode>
407                                                 </aetgt:WorkflowException>
408                                         </aetgt:FalloutHandlerRequest>"""
409
410                         msoLogger.debug(falloutHandlerRequest)
411                         execution.setVariable(Prefix + "FalloutHandlerRequest", falloutHandlerRequest)
412                         msoLogger.debug("  Overall Error Response going to FalloutHandler: " + "\n" + falloutHandlerRequest)
413
414                 } catch (Exception ex) {
415                         String errorException = "  Bpmn error encountered in CreateNetworkInstance flow. FalloutHandlerRequest,  buildErrorResponse()"
416                         msoLogger.debug("Exception error in CreateNetworkInstance flow,  buildErrorResponse(): "  + ex.getMessage())
417                         falloutHandlerRequest =
418                         """<aetgt:FalloutHandlerRequest xmlns:aetgt="http://org.onap/so/workflow/schema/v1"
419                                                                      xmlns:ns="http://org.onap/so/request/types/v1"
420                                                                      xmlns:wfsch="http://org.onap/so/workflow/schema/v1">
421                                            <request-info xmlns="http://org.onap/so/infra/vnf-request/v1">
422                                               <request-id>${MsoUtils.xmlEscape(requestId)}</request-id>
423                                               <action>CREATE</action>
424                                               <source>VID</source>
425                                            </request-info>
426                                                 <aetgt:WorkflowException xmlns:aetgt="http://org.onap/so/workflow/schema/v1">
427                                                         <aetgt:ErrorMessage>${MsoUtils.xmlEscape(errorException)}</aetgt:ErrorMessage>
428                                                         <aetgt:ErrorCode>7000</aetgt:ErrorCode>
429                                                 </aetgt:WorkflowException>
430                                         </aetgt:FalloutHandlerRequest>"""
431
432                         execution.setVariable(Prefix + "FalloutHandlerRequest", falloutHandlerRequest)
433                         msoLogger.debug("  Overall Error Response going to FalloutHandler: " + "\n" + falloutHandlerRequest)
434
435                 }
436
437         }
438         
439         public void processJavaException(DelegateExecution execution){
440                 def isDebugEnabled=execution.getVariable("isDebugLogEnabled")
441                 execution.setVariable("prefix",Prefix)
442                 try{
443                         msoLogger.debug("Caught a Java Exception in " + Prefix)
444                         msoLogger.debug("Started processJavaException Method")
445                         msoLogger.debug("Variables List: " + execution.getVariables())
446                         execution.setVariable("UnexpectedError", "Caught a Java Lang Exception - " + Prefix)  // Adding this line temporarily until this flows error handling gets updated
447                         exceptionUtil.buildWorkflowException(execution, 500, "Caught a Java Lang Exception")
448                         
449                 }catch(Exception e){
450                         msoLogger.debug("Caught Exception during processJavaException Method: " + e)
451                         execution.setVariable("UnexpectedError", "Exception in processJavaException method - " + Prefix)  // Adding this line temporarily until this flows error handling gets updated
452                         exceptionUtil.buildWorkflowException(execution, 500, "Exception in processJavaException method" + Prefix)
453                 }
454                 msoLogger.debug("Completed processJavaException Method in " + Prefix)
455         }
456
457 }