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