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