Merge "add instance group support to SO"
[so.git] / bpmn / so-bpmn-infrastructure-common / src / main / groovy / org / onap / so / bpmn / infrastructure / scripts / DoUpdateNetworkInstanceRollback.groovy
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP - SO
4  * ================================================================================
5  * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
6  * ================================================================================
7  * Modifications Copyright (c) 2019 Samsung
8  * ================================================================================
9  * Licensed under the Apache License, Version 2.0 (the "License");
10  * you may not use this file except in compliance with the License.
11  * You may obtain a copy of the License at
12  *
13  *      http://www.apache.org/licenses/LICENSE-2.0
14  *
15  * Unless required by applicable law or agreed to in writing, software
16  * distributed under the License is distributed on an "AS IS" BASIS,
17  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18  * See the License for the specific language governing permissions and
19  * limitations under the License.
20  * ============LICENSE_END=========================================================
21  */
22
23 package org.onap.so.bpmn.infrastructure.scripts;
24
25 import groovy.xml.XmlUtil
26 import groovy.json.*
27
28 import org.onap.so.bpmn.common.scripts.AaiUtil
29 import org.onap.so.bpmn.common.scripts.AbstractServiceTaskProcessor
30 import org.onap.so.bpmn.common.scripts.ExceptionUtil
31 import org.onap.so.bpmn.common.scripts.NetworkUtils
32 import org.onap.so.bpmn.common.scripts.SDNCAdapterUtils
33 import org.onap.so.bpmn.common.scripts.VidUtils
34 import org.onap.so.bpmn.core.WorkflowException
35 import org.onap.so.bpmn.core.UrnPropertiesReader
36 import org.onap.so.bpmn.core.json.JsonUtils
37
38
39 import java.util.UUID;
40
41 import org.camunda.bpm.engine.delegate.BpmnError
42 import org.camunda.bpm.engine.delegate.DelegateExecution
43 import org.apache.commons.lang3.*
44 import org.apache.commons.codec.binary.Base64;
45 import org.springframework.web.util.UriUtils
46
47 import org.slf4j.Logger
48 import org.slf4j.LoggerFactory
49
50 /**
51  * This groovy class supports the <class>DoCreateNetworkInstance.bpmn</class> process.
52  *
53  */
54 public class DoUpdateNetworkInstanceRollback extends AbstractServiceTaskProcessor {
55     private static final Logger logger = LoggerFactory.getLogger( DoUpdateNetworkInstanceRollback.class);
56
57         String Prefix="UPDNETIR_"
58         ExceptionUtil exceptionUtil = new ExceptionUtil()
59         JsonUtils jsonUtil = new JsonUtils()
60         VidUtils vidUtils = new VidUtils(this)
61         NetworkUtils networkUtils = new NetworkUtils()
62         SDNCAdapterUtils sdncAdapterUtils = new SDNCAdapterUtils()
63
64         def className = getClass().getSimpleName()
65
66         /**
67          * This method is executed during the preProcessRequest task of the <class>DoUpdateNetworkInstanceRollback.bpmn</class> process.
68          * @param execution
69          */
70         public InitializeProcessVariables(DelegateExecution execution){
71                 /* Initialize all the process variables in this block */
72
73                 execution.setVariable(Prefix + "rollbackNetworkRequest", null)
74                 execution.setVariable(Prefix + "rollbackSDNCRequest", null)
75                 execution.setVariable(Prefix + "WorkflowException", null)
76
77                 execution.setVariable(Prefix + "rollbackNetworkRequest", "")
78                 execution.setVariable(Prefix + "rollbackNetworkResponse", "")
79                 execution.setVariable(Prefix + "rollbackNetworkReturnCode", "")
80
81                 execution.setVariable(Prefix + "rollbackSDNCRequest", "")
82                 execution.setVariable(Prefix + "rollbackSDNCResponse", "")
83                 execution.setVariable(Prefix + "rollbackSDNCReturnCode", "")
84
85                 execution.setVariable(Prefix + "Success", false)
86                 execution.setVariable(Prefix + "fullRollback", false)
87
88         }
89
90         // **************************************************
91         //     Pre or Prepare Request Section
92         // **************************************************
93         /**
94          * This method is executed during the preProcessRequest task of the <class>DoUpdateNetworkInstanceRollback.bpmn</class> process.
95          * @param execution
96          */
97         public void preProcessRequest (DelegateExecution execution) {
98
99                 execution.setVariable("prefix",Prefix)
100
101                 logger.trace("Inside preProcessRequest() of " + className + ".groovy ")
102
103                 try {
104                         // initialize flow variables
105                         InitializeProcessVariables(execution)
106
107                         // GET Incoming request/variables
108                         String rollbackNetworkRequest = null
109                         String rollbackSDNCRequest = null
110
111                         // Partial Rollback
112                         Map<String, String> rollbackData = execution.getVariable("rollbackData")
113                         if (rollbackData != null && rollbackData instanceof Map) {
114
115                                         if(rollbackData.containsKey("rollbackNetworkRequest")) {
116                                                 rollbackNetworkRequest = rollbackData["rollbackNetworkRequest"]
117                                         }
118
119                                         if(rollbackData.containsKey("rollbackSDNCRequest")) {
120                                            rollbackSDNCRequest = rollbackData["rollbackSDNCRequest"]
121                                         }
122                         }
123
124                         execution.setVariable(Prefix + "rollbackNetworkRequest", rollbackNetworkRequest)
125                         execution.setVariable(Prefix + "rollbackSDNCRequest", rollbackSDNCRequest)
126                         logger.debug("'rollbackData': " + '\n' + execution.getVariable("rollbackData"))
127
128                         String sdncVersion = execution.getVariable("sdncVersion")
129                         logger.debug("sdncVersion? : " + sdncVersion)
130
131                         // PO Authorization Info / headers Authorization=
132                         String basicAuthValuePO = UrnPropertiesReader.getVariable("mso.adapters.po.auth",execution)
133
134                         try {
135                                 def encodedString = utils.getBasicAuth(basicAuthValuePO, UrnPropertiesReader.getVariable("mso.msoKey", execution))
136                                 execution.setVariable("BasicAuthHeaderValuePO",encodedString)
137                                 execution.setVariable("BasicAuthHeaderValueSDNC", encodedString)
138
139                         } catch (IOException ex) {
140                                 String exceptionMessage = "Exception Encountered in DoCreateNetworkInstance, PreProcessRequest() - "
141                                 String dataErrorMessage = exceptionMessage + " Unable to encode PO/SDNC user/password string - " + ex.getMessage()
142                                 logger.debug(dataErrorMessage )
143                                 exceptionUtil.buildAndThrowWorkflowException(execution, 2500, dataErrorMessage)
144                         }
145
146                         if (execution.getVariable("SavedWorkflowException1") != null) {
147                                 execution.setVariable(Prefix + "WorkflowException", execution.getVariable("SavedWorkflowException1"))
148                         } else {
149                                 execution.setVariable(Prefix + "WorkflowException", execution.getVariable("WorkflowException"))
150                         }
151                         logger.debug("*** WorkflowException : " + execution.getVariable(Prefix + "WorkflowException"))
152                         if(execution.getVariable(Prefix + "WorkflowException") != null) {
153                                 // called by: DoCreateNetworkInstance, partial rollback
154                                 execution.setVariable(Prefix + "fullRollback", false)
155
156                         } else {
157                            // called by: Macro - Full Rollback, WorkflowException = null
158                            execution.setVariable(Prefix + "fullRollback", true)
159
160                         }
161                         logger.debug("*** fullRollback? : " + execution.getVariable(Prefix + "fullRollback"))
162
163
164                 } catch (BpmnError e) {
165                 throw e;
166
167                 } catch (Exception ex) {
168                         sendSyncError(execution)
169                         // caught exception
170                         String exceptionMessage = "Exception Encountered in PreProcessRequest() of " + className + ".groovy ***** : " + ex.getMessage()
171                         logger.debug(exceptionMessage)
172                         exceptionUtil.buildAndThrowWorkflowException(execution, 7000, exceptionMessage)
173
174                 }
175
176         }
177
178         public void validateRollbackResponses (DelegateExecution execution) {
179
180                 execution.setVariable("prefix",Prefix)
181
182                 logger.trace("Inside validateRollbackResponses() of DoUpdateNetworkInstanceRollback ")
183
184                 try {
185                         // validate PO network rollback response
186                         String rollbackNetworkErrorMessages = ""
187                         String rollbackNetworkReturnCode = "200"
188                         if (execution.getVariable(Prefix + "rollbackNetworkRequest") != null) {
189                                 rollbackNetworkReturnCode = execution.getVariable(Prefix + "rollbackNetworkReturnCode")
190                                 String rollbackNetworkResponse = execution.getVariable(Prefix + "rollbackNetworkResponse")
191                                 logger.debug(" NetworkRollback Code - " + rollbackNetworkReturnCode)
192                                 logger.debug(" NetworkRollback Response - " + rollbackNetworkResponse)
193                                 if (rollbackNetworkReturnCode != "200") {
194                                         rollbackNetworkErrorMessages = " + PO Network rollback failed. "
195                                 } else {
196                                         rollbackNetworkErrorMessages = " + PO Network rollback completed."
197                                 }
198                         }
199
200                         // validate SDNC rollback response
201                         String rollbackSdncErrorMessages = ""
202                         String rollbackSDNCReturnCode = "200"
203                         if (execution.getVariable(Prefix + "rollbackSDNCRequest") != null) {
204                                 rollbackSDNCReturnCode = execution.getVariable(Prefix + "rollbackSDNCReturnCode")
205                                 String rollbackSDNCResponse = execution.getVariable(Prefix + "rollbackSDNCResponse")
206                                 String rollbackSDNCReturnInnerCode = ""
207                                 SDNCAdapterUtils sdncAdapterUtils = new SDNCAdapterUtils(this)
208                                 rollbackSDNCResponse = rollbackSDNCResponse.replace('$', '').replace('<?xml version="1.0" encoding="UTF-8"?>', "")
209                                 if (rollbackSDNCReturnCode == "200") {
210                                         if (utils.nodeExists(rollbackSDNCResponse, "response-code")) {
211                                                 rollbackSDNCReturnInnerCode = utils.getNodeText(rollbackSDNCResponse, "response-code")
212                                                 if (rollbackSDNCReturnInnerCode == "200" || rollbackSDNCReturnInnerCode == "" || rollbackSDNCReturnInnerCode == "0") {
213                                                     rollbackSdncErrorMessages = " + SNDC changeassign rollback completed."
214                                                 } else {
215                                                         rollbackSdncErrorMessages = " + SDNC changeassign rollback failed. "
216                                                 }
217                                         } else {
218                                                   rollbackSdncErrorMessages = " + SNDC changeassign rollback completed."
219                                         }
220                                  } else {
221                                           rollbackSdncErrorMessages = " + SDNC changeassign rollback failed. "
222                              }
223                                 logger.debug(" SDNC changeassign rollback Code - " + rollbackSDNCReturnCode)
224                                 logger.debug(" SDNC changeassign rollback  Response - " + rollbackSDNCResponse)
225                         }
226
227                         String statusMessage = ""
228                         int errorCode = 7000
229                         logger.debug("*** fullRollback? : " + execution.getVariable(Prefix + "fullRollback"))
230                         if (execution.getVariable(Prefix + "fullRollback") == false) {
231                                 // original WorkflowException,
232                                 WorkflowException wfe = execution.getVariable(Prefix + "WorkflowException")
233                                 if (wfe != null) {
234                                    // rollback due to failure in DoCreate - Partial rollback
235                                    statusMessage = wfe.getErrorMessage()
236                                    errorCode = wfe.getErrorCode()
237                                 } else {
238                                    statusMessage = "See Previous Camunda flows for cause of Error: Undetermined Exception."
239                                    errorCode = '7000'
240                                 }
241
242                                 // set if all rolledbacks are successful
243                                 if (rollbackNetworkReturnCode == "200" && rollbackSDNCReturnCode == "200") {
244                                         execution.setVariable("rolledBack", true)
245
246                                 } else {
247                                         execution.setVariable("rolledBack", false)
248
249                                 }
250
251                                 statusMessage = statusMessage + rollbackNetworkErrorMessages + rollbackSdncErrorMessages
252                                 logger.debug("Final DoUpdateNetworkInstanceRollback status message: " + statusMessage)
253                                 String processKey = getProcessKey(execution);
254                                 WorkflowException exception = new WorkflowException(processKey, errorCode, statusMessage);
255                                 execution.setVariable("workflowException", exception);
256
257                         } else {
258                                 // rollback due to failures in Main flow (Macro) - Full rollback
259                                 // WorkflowException = null
260                                 if (rollbackNetworkReturnCode == "200" && rollbackSDNCReturnCode == "200") {
261                                         execution.setVariable("rollbackSuccessful", true)
262                                         execution.setVariable("rollbackError", false)
263                                 } else {
264                                         String exceptionMessage = "Network Update Rollback was not Successful. "
265                                         logger.debug(exceptionMessage)
266                                         execution.setVariable("rollbackSuccessful", false)
267                                         execution.setVariable("rollbackError", true)
268                                         exceptionUtil.buildWorkflowException(execution, 7000, exceptionMessage)
269                                         throw new BpmnError("MSOWorkflowException")
270                                 }
271
272                         }
273
274
275                 } catch (Exception ex) {
276                         execution.setVariable("WorkflowException", null)
277                         String errorMessage = "See Previous Camunda flows for cause of Error: Undetermined Exception."
278                         String exceptionMessage = " Bpmn error encountered in DoUpdateNetworkInstanceRollback flow. validateRollbackResponses() - " + errorMessage + ": " + ex.getMessage()
279                         logger.debug(exceptionMessage)
280                         exceptionUtil.buildWorkflowException(execution, 7000, exceptionMessage)
281                         execution.setVariable("WorkflowException", execution.getVariable("WorkflowException"))
282
283                 }
284
285         }
286
287         // *******************************
288         //     Build Error Section
289         // *******************************
290
291
292
293         public void processJavaException(DelegateExecution execution){
294
295                 execution.setVariable("prefix",Prefix)
296
297                 try{
298                         logger.debug("Caught a Java Exception in " + Prefix)
299                         logger.debug("Started processJavaException Method")
300                         logger.debug("Variables List: " + execution.getVariables())
301                         execution.setVariable("UnexpectedError", "Caught a Java Lang Exception - " + Prefix)  // Adding this line temporarily until this flows error handling gets updated
302                         exceptionUtil.buildWorkflowException(execution, 500, "Caught a Java Lang Exception")
303
304                 }catch(Exception e){
305                         logger.debug("Caught Exception during processJavaException Method: " + e)
306                         execution.setVariable("UnexpectedError", "Exception in processJavaException method - " + Prefix)  // Adding this line temporarily until this flows error handling gets updated
307                         exceptionUtil.buildWorkflowException(execution, 500, "Exception in processJavaException method" + Prefix)
308                 }
309                 logger.trace("Completed processJavaException Method in " + Prefix)
310         }
311
312 }