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