1710 Rebase - Second Attempt
[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                         String requestId = execution.getVariable("msoRequestId")
106                         if (requestId != null) {
107                                 execution.setVariable("mso-request-id", requestId)
108                         } else {
109                                 requestId = execution.getVariable("mso-request-id")
110                         }
111                         execution.setVariable(Prefix + "requestId", requestId)
112
113                         // get/set 'requestId'
114                         if (execution.getVariable("requestId") == null) {
115                                 execution.setVariable("requestId", requestId)
116                         }
117
118                         //Place holder for additional code.
119
120                         // TODO ???
121                         // userParams???  1) pre-loads indicator, 2) 'auto-activation'
122                         // Tag/Value parameters
123                         //
124                         // Map: 'networkInputParams': 'auto-activation''
125                         // Sample format?
126                         // "requestParameters": {
127                         //     "userParams": [
128             //          {
129                         //               "name": "someUserParam1",
130                         //               "value": "someValue1"
131                         //          }
132             //     ]
133                     //   }
134                         //
135                         // String userParams = //use json util to extract "userParams"//
136                 // execution.setVariable("networkInputParams", userParams)
137                         // else: execution.setVariable("networkInputParams", null)
138                         //
139
140                 } catch (BpmnError e) {
141                     throw e;
142
143                 } catch (Exception ex){
144                         sendSyncError(execution)
145                          // caught exception
146                         String exceptionMessage = "Exception Encountered in UpdateNetworkInstance, PreProcessRequest() - " + ex.getMessage()
147                         utils.log("DEBUG", exceptionMessage, isDebugEnabled)
148                         exceptionUtil.buildAndThrowWorkflowException(execution, 7000, exceptionMessage)
149
150                 }
151         }
152
153         public void sendSyncResponse (Execution execution) {
154                 def isDebugEnabled=execution.getVariable("isDebugLogEnabled")
155                 execution.setVariable("prefix",Prefix)
156
157                 utils.log("DEBUG", " ***** Inside sendSyncResponse() of UpdateNetworkInstance ***** ", isDebugEnabled)
158
159                 try {
160                         String requestId = execution.getVariable("mso-request-id")
161                         String serviceInstanceId = execution.getVariable("serviceInstanceId")
162
163                         // RESTResponse (for API Handler (APIH) Reply Task)
164                         String updateNetworkRestRequest = """{"requestReferences":{"instanceId":"${serviceInstanceId}","requestId":"${requestId}"}}""".trim()
165
166                         utils.log("DEBUG", " sendSyncResponse to APIH - " + "\n" + updateNetworkRestRequest, isDebugEnabled)
167                         sendWorkflowResponse(execution, 202, updateNetworkRestRequest)
168
169                 } catch (Exception ex) {
170                         String exceptionMessage = "Bpmn error encountered in UpdateNetworkInstance flow. sendSyncResponse() - " + ex.getMessage()
171                         utils.log("DEBUG", exceptionMessage, isDebugEnabled)
172                         exceptionUtil.buildAndThrowWorkflowException(execution, 7000, exceptionMessage)
173                 }
174
175         }
176
177
178         public void getNetworkModelInfo (Execution execution) {
179                 def isDebugEnabled=execution.getVariable("isDebugLogEnabled")
180                 execution.setVariable("prefix", Prefix)
181
182                 utils.log("DEBUG", " ***** Inside getNetworkModelInfo() of UpdateNetworkInstance ***** ", isDebugEnabled)
183
184                 try {
185
186                         // For Ala-Carte (sdnc = 1610): 
187                         // 1. the Network ModelInfo is expected to be sent 
188                         //     via requestDetails.modelInfo (modelType = network), ex: modelCustomizationId
189                         // 2. the Service ModelInfo is expected to be sent but will be IGNORE 
190                         //     via requestDetails.relatedInstanceList.relatedInstance.modelInfo (modelType = service)
191                         
192                 } catch (Exception ex) {
193                         sendSyncError(execution)
194                    String exceptionMessage = "Bpmn error encountered in UpdateNetworkInstance flow. getNetworkModelInfo() - " + ex.getMessage()
195                    utils.log("DEBUG", exceptionMessage, isDebugEnabled)
196                    exceptionUtil.buildAndThrowWorkflowException(execution, 7000, exceptionMessage)
197
198                 }
199
200         }
201
202
203         public void sendSyncError (Execution execution) {
204                 def isDebugEnabled=execution.getVariable("isDebugLogEnabled")
205                 execution.setVariable("prefix", Prefix)
206
207                 utils.log("DEBUG", " ***** Inside sendSyncError() of UpdateNetworkInstance ***** ", isDebugEnabled)
208
209                 try {
210
211                         String requestId = execution.getVariable("mso-request-id")
212                         String serviceInstanceId = execution.getVariable("serviceInstanceId")
213
214                         // REST Error (for API Handler (APIH) Reply Task)
215                         String syncError = """{"requestReferences":{"instanceId":"${serviceInstanceId}","requestId":"${requestId}"}}""".trim()
216
217                         sendWorkflowResponse(execution, 500, syncError)
218
219                 } catch (Exception ex) {
220                         utils.log("DEBUG", " Bpmn error encountered in UpdateNetworkInstance flow. sendSyncError() - " + ex.getMessage(), isDebugEnabled)
221                 }
222
223         }
224
225         public void prepareDBRequestError (Execution execution) {
226                 def isDebugEnabled=execution.getVariable("isDebugLogEnabled")
227                 execution.setVariable("prefix",Prefix)
228
229                 try {
230                         utils.log("DEBUG", " ***** Inside prepareDBRequestError() of UpdateNetworkInstance ***** ", isDebugEnabled)
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.openecomp.mso/requestsdb">
250                                                                 <requestId>${requestId}</requestId>
251                                                                 <lastModifiedBy>BPMN</lastModifiedBy>
252                                                                 <statusMessage>${statusMessage}</statusMessage>
253                                                                 <responseBody></responseBody>
254                                                                 <requestStatus>FAILED</requestStatus>
255                                                                 <vnfOutputs>&lt;network-id&gt;${networkId}&lt;/network-id&gt;&lt;network-name&gt;${networkName}&lt;/network-names&gt;</vnfOutputs>
256                                                         </ns:updateInfraRequest>
257                                                 </soapenv:Body>
258                                            </soapenv:Envelope>"""
259
260                    execution.setVariable(Prefix + "createDBRequest", dbRequest)
261                    utils.log("DEBUG", " DB Adapter Request - " + "\n" + dbRequest, isDebugEnabled)
262                    utils.logAudit(dbRequest)
263
264                 } catch (Exception ex) {
265                         String exceptionMessage = " Bpmn error encountered in UpdateNetworkInstance flow. prepareDBRequestError() - " + ex.getMessage()
266                         utils.log("DEBUG", exceptionMessage, isDebugEnabled)
267                         exceptionUtil.buildWorkflowException(execution, 7000, exceptionMessage)
268
269                 }
270
271          }
272
273         public void prepareCompletion (Execution execution) {
274                 def isDebugEnabled=execution.getVariable("isDebugLogEnabled")
275                 execution.setVariable("prefix",Prefix)
276
277                 utils.log("DEBUG", " ***** Inside prepareCompletion() of UpdateNetworkInstance ***** ", isDebugEnabled)
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.openecomp/mso/workflow/schema/v1"
286                                                                 xmlns:ns="http://org.openecomp/mso/request/types/v1">
287                                                 <request-info xmlns="http://org.openecomp/mso/infra/vnf-request/v1">
288                                                         <request-id>${requestId}</request-id>
289                                                         <action>UPDATE</action>
290                                                         <source>VID</source>
291                                                 </request-info>
292                                                 <aetgt:status-message>Network has been updated successfully.</aetgt:status-message>
293                                                 <aetgt:mso-bpel-name>BPMN Network action: UPDATE</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                         utils.log("DEBUG", " Overall SUCCESS Response going to CompleteMsoProcess - " + "\n" + xmlMsoCompletionRequest, isDebugEnabled)
303
304                 } catch (Exception ex) {
305                         String exceptionMessage = " Bpmn error encountered in UpdateNetworkInstance flow. prepareCompletion() - " + ex.getMessage()
306                         utils.log("DEBUG", exceptionMessage, isDebugEnabled)
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 (Execution execution) {
322                 def isDebugEnabled=execution.getVariable("isDebugLogEnabled")
323                 execution.setVariable("prefix", Prefix)
324
325                 utils.log("DEBUG", " ***** Inside postProcessResponse() of UpdateNetworkInstance ***** ", isDebugEnabled)
326
327                 try {
328
329                         if (execution.getVariable("CMSO_ResponseCode") == "200") {
330                                 execution.setVariable(Prefix + "Success", true)
331                                 utils.log("DEBUG", " ***** UpdateNetworkInstance Success ***** ", isDebugEnabled)
332                                 //   Place holder for additional code.
333
334                          } else {
335                                 execution.setVariable(Prefix + "Success", false)
336                                 utils.log("DEBUG", " ***** UpdateNetworkInstance Failed in CompletionMsoProces flow!. ***** ", isDebugEnabled)
337
338                          }
339
340
341                 } catch (Exception ex) {
342                         String exceptionMessage = " Bpmn error encountered in UpdateNetworkInstance flow. postProcessResponse() - " + ex.getMessage()
343                         utils.log("DEBUG", exceptionMessage, isDebugEnabled)
344                         exceptionUtil.buildAndThrowWorkflowException(execution, 7000, exceptionMessage)
345
346             }
347
348         }
349
350
351         // *******************************
352         //     Build Error Section
353         // *******************************
354
355         public void processRollbackData (Execution execution) {
356                 def isDebugEnabled=execution.getVariable("isDebugLogEnabled")
357                 execution.setVariable("prefix", Prefix)
358
359                 utils.log("DEBUG", " ***** Inside processRollbackData() of UpdateNetworkInstance ***** ", isDebugEnabled)
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                         utils.log("DEBUG", " Bpmn error encountered in UpdateNetworkInstance flow. callDBCatalog() - " + ex.getMessage(), isDebugEnabled)
371                 }
372
373         }
374
375         // Prepare for FalloutHandler
376         public void buildErrorResponse (Execution execution) {
377                 def isDebugEnabled=execution.getVariable("isDebugLogEnabled")
378                 execution.setVariable("prefix", Prefix)
379
380                 utils.log("DEBUG", "DB updateInfraRequest ResponseCode: " + execution.getVariable(Prefix + "dbReturnCode"), isDebugEnabled)
381                 utils.log("DEBUG", "DB updateInfraRequest Response: " + execution.getVariable(Prefix + "createDBResponse"), isDebugEnabled)
382                 
383                 utils.log("DEBUG", " ***** Prepare for FalloutHandler. FAILURE - prepare request for sub-process FalloutHandler. *****", isDebugEnabled)
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.openecomp/mso/workflow/schema/v1"
395                                                                      xmlns:ns="http://org.openecomp/mso/request/types/v1"
396                                                                      xmlns:wfsch="http://org.openecomp/mso/workflow/schema/v1">
397                                            <request-info xmlns="http://org.openecomp/mso/infra/vnf-request/v1">
398                                               <request-id>${requestId}</request-id>
399                                               <action>UPDATE</action>
400                                               <source>VID</source>
401                                            </request-info>
402                                                 <aetgt:WorkflowException xmlns:aetgt="http://org.openecomp/mso/workflow/schema/v1">
403                                                         <aetgt:ErrorMessage>${errorMessage}</aetgt:ErrorMessage>
404                                                         <aetgt:ErrorCode>${errorCode}</aetgt:ErrorCode>
405                                                 </aetgt:WorkflowException>
406                                         </aetgt:FalloutHandlerRequest>"""
407
408                         utils.logAudit(falloutHandlerRequest)
409                         execution.setVariable(Prefix + "FalloutHandlerRequest", falloutHandlerRequest)
410                         utils.log("DEBUG", "  Overall Error Response going to FalloutHandler: " + "\n" + falloutHandlerRequest, isDebugEnabled)
411
412                 } catch (Exception ex) {
413                         String errorException = "  Bpmn error encountered in UpdateNetworkInstance flow. FalloutHandlerRequest,  buildErrorResponse() - "
414                         utils.log("DEBUG", "Exception error in UpdateNetworkInstance flow,  buildErrorResponse(): " +  ex.getMessage(), isDebugEnabled)
415                         falloutHandlerRequest =
416                         """<aetgt:FalloutHandlerRequest xmlns:aetgt="http://org.openecomp/mso/workflow/schema/v1"
417                                                                      xmlns:ns="http://org.openecomp/mso/request/types/v1"
418                                                                      xmlns:wfsch="http://org.openecomp/mso/workflow/schema/v1">
419                                            <request-info xmlns="http://org.openecomp/mso/infra/vnf-request/v1">
420                                               <request-id>${requestId}</request-id>
421                                               <action>UPDATE</action>
422                                               <source>VID</source>
423                                            </request-info>
424                                                 <aetgt:WorkflowException xmlns:aetgt="http://org.openecomp/mso/workflow/schema/v1">
425                                                         <aetgt:ErrorMessage>${errorException}</aetgt:ErrorMessage>
426                                                         <aetgt:ErrorCode>7000</aetgt:ErrorCode>
427                                                 </aetgt:WorkflowException>
428                                         </aetgt:FalloutHandlerRequest>"""
429
430                         execution.setVariable(Prefix + "FalloutHandlerRequest", falloutHandlerRequest)
431                         utils.log("DEBUG", "  Overall Error Response going to FalloutHandler: " + "\n" + falloutHandlerRequest, isDebugEnabled)
432
433                 }
434
435         }
436
437         public void processJavaException(Execution execution){
438                 def isDebugEnabled=execution.getVariable("isDebugLogEnabled")
439                 execution.setVariable("prefix",Prefix)
440                 try{
441                         utils.log("DEBUG", "Caught a Java Exception in " + Prefix, isDebugEnabled)
442                         utils.log("DEBUG", "Started processJavaException Method", isDebugEnabled)
443                         utils.log("DEBUG", "Variables List: " + execution.getVariables(), isDebugEnabled)
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                         utils.log("DEBUG", "Caught Exception during processJavaException Method: " + e, isDebugEnabled)
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                 utils.log("DEBUG", "Completed processJavaException Method in " + Prefix, isDebugEnabled)
453         }
454
455 }