Merge "Reorder modifiers"
[so.git] / bpmn / MSOInfrastructureBPMN / src / main / groovy / org / openecomp / mso / bpmn / infrastructure / scripts / ScaleCustomE2EServiceInstance.groovy
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP - SO
4  * ================================================================================
5  * Copyright (C) 2018 CMCC. All rights reserved.
6  * ================================================================================
7  * Licensed under the Apache License, Version 2.0 (the "License");
8  * you may not use this file except in compliance with the License.
9  * You may obtain a copy of the License at
10  *
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  *
13  * Unless required by applicable law or agreed to in writing, software
14  * distributed under the License is distributed on an "AS IS" BASIS,
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * See the License for the specific language governing permissions and
17  * limitations under the License.
18  * ============LICENSE_END=========================================================
19  */
20
21 package org.openecomp.mso.bpmn.infrastructure.scripts
22
23 import org.camunda.bpm.engine.delegate.DelegateExecution
24
25 import static org.apache.commons.lang3.StringUtils.*
26 import org.openecomp.mso.logger.MsoLogger
27 import org.openecomp.mso.utils.UUIDChecker
28 import org.openecomp.mso.bpmn.common.scripts.AbstractServiceTaskProcessor
29 import org.openecomp.mso.bpmn.common.scripts.ExceptionUtil
30 import org.openecomp.mso.bpmn.core.WorkflowException
31 import org.openecomp.mso.bpmn.core.json.JsonUtils
32 import org.openecomp.mso.bpmn.common.scripts.ExceptionUtil
33
34 import org.camunda.bpm.engine.delegate.BpmnError
35 import org.camunda.bpm.engine.runtime.Execution
36
37 import org.springframework.web.util.UriUtils
38
39
40 /**
41  * This groovy class supports the <class>ScaleCustomE2EServiceInstance.bpmn</class> process.
42  *
43  */
44 public class ScaleCustomE2EServiceInstance extends AbstractServiceTaskProcessor {
45     String Prefix = "CRESI_"
46     ExceptionUtil exceptionUtil = new ExceptionUtil()
47     JsonUtils jsonUtil = new JsonUtils()
48     private MsoLogger msoLogger = MsoLogger.getMsoLogger(MsoLogger.Catalog.APIH);
49
50     public void preProcessRequest(DelegateExecution execution) {
51         def isDebugEnabled = execution.getVariable("isDebugLogEnabled")
52         execution.setVariable("prefix", Prefix)
53         String msg = ""
54         utils.log("DEBUG", " *** preProcessRequest() *** ", isDebugEnabled)
55
56         try {
57
58             String siRequest = execution.getVariable("bpmnRequest")
59             utils.logAudit(siRequest)
60
61             String requestId = execution.getVariable("mso-request-id")
62             execution.setVariable("msoRequestId", requestId)
63             utils.log("DEBUG", "Input Request:" + siRequest + " reqId:" + requestId, isDebugEnabled)
64
65             String serviceInstanceId = execution.getVariable("serviceInstanceId")
66             if (isBlank(serviceInstanceId)) {
67                 serviceInstanceId = "NULL".toString()
68             }
69             utils.log("DEBUG", "Generated new Service Instance:" + serviceInstanceId, isDebugEnabled)
70             serviceInstanceId = UriUtils.encode(serviceInstanceId, "UTF-8")
71             execution.setVariable("serviceInstanceId", serviceInstanceId)
72
73             // service instance ID is also service ID
74             execution.setVariable("serviceId", serviceInstanceId)
75             // service instance name
76             String serviceInstanceName = jsonUtil.getJsonValue(siRequest, "service.serviceInstanceName")
77             execution.setVariable("serviceInstanceName", serviceInstanceName)
78
79             // service instance name
80             String serviceType = jsonUtil.getJsonValue(siRequest, "service.serviceType")
81             execution.setVariable("serviceType", serviceType)
82
83             // operationa ID (key)
84             //String operationKey = UUIDChecker.generateUUID(msoLogger)
85             String operationId = jsonUtil.getJsonValue(siRequest, "operationId")
86             execution.setVariable("operationId", operationId)
87             utils.log("DEBUG", "Input Request:" + siRequest + " operationId:" + operationId, isDebugEnabled)
88
89
90             String resources = jsonUtil.getJsonValue(siRequest, "service.resources")
91             execution.setVariable("resources", resources)
92
93             // node template UUID
94             String nodeTemplateUUID = UUIDChecker.generateUUID(msoLogger)
95             execution.setVariable("nodeTemplateUUID", nodeTemplateUUID)
96
97             //subscriberInfo
98             String globalSubscriberId = jsonUtil.getJsonValue(siRequest, "service.globalSubscriberId")
99             if (isBlank(globalSubscriberId)) {
100                 msg = "Input globalSubscriberId' is null"
101                 exceptionUtil.buildAndThrowWorkflowException(execution, 500, msg)
102             } else {
103                 execution.setVariable("globalSubscriberId", globalSubscriberId)
104             }
105
106             String requestDescription = "request description for test"
107             execution.setVariable("requestDescription", requestDescription)
108             execution.setVariable("URN_mso_adapters_openecomp_db_endpoint","http://mso.mso.testlab.openecomp.org:8080/dbadapters/RequestsDbAdapter")
109
110         } catch (BpmnError e) {
111             throw e;
112         } catch (Exception ex) {
113             msg = "Exception in preProcessRequest " + ex.getMessage()
114             utils.log("DEBUG", msg, isDebugEnabled)
115             exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg)
116         }
117         utils.log("DEBUG", " ***** Exit preProcessRequest *****", isDebugEnabled)
118     }
119
120     public void sendSyncResponse(DelegateExecution execution) {
121         def isDebugEnabled = execution.getVariable("isDebugLogEnabled")
122         utils.log("DEBUG", " *** sendSyncResponse *** ", isDebugEnabled)
123
124         try {
125             String operationId = execution.getVariable("operationId")
126             String serviceInstanceId = execution.getVariable("serviceInstanceId")
127             // RESTResponse for API Handler (APIH) Reply Task
128             String scaleServiceRestRequest = """{"operationId":"${operationId}"}""".trim()
129             utils.log("DEBUG", " sendSyncResponse to APIH:" + "\n" + scaleServiceRestRequest, isDebugEnabled)
130             sendWorkflowResponse(execution, 202, scaleServiceRestRequest)
131             execution.setVariable("sentSyncResponse", true)
132
133         } catch (Exception ex) {
134             String msg = "Exceptuion in sendSyncResponse:" + ex.getMessage()
135             utils.log("DEBUG", msg, isDebugEnabled)
136             exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg)
137         }
138         utils.log("DEBUG", " ***** Exit sendSyncResopnse *****", isDebugEnabled)
139     }
140
141
142     public void sendSyncError(DelegateExecution execution) {
143         def isDebugEnabled = execution.getVariable("isDebugLogEnabled")
144         utils.log("DEBUG", " *** sendSyncError *** ", isDebugEnabled)
145
146         try {
147             String errorMessage = ""
148             if (execution.getVariable("WorkflowException") instanceof WorkflowException) {
149                 WorkflowException wfe = execution.getVariable("WorkflowException")
150                 errorMessage = wfe.getErrorMessage()
151             } else {
152                 errorMessage = "Sending Sync Error."
153             }
154
155             String buildworkflowException =
156                     """<aetgt:WorkflowException xmlns:aetgt="http://org.openecomp/mso/workflow/schema/v1">
157                                         <aetgt:ErrorMessage>${errorMessage}</aetgt:ErrorMessage>
158                                         <aetgt:ErrorCode>7000</aetgt:ErrorCode>
159                                    </aetgt:WorkflowException>"""
160
161             utils.logAudit(buildworkflowException)
162             sendWorkflowResponse(execution, 500, buildworkflowException)
163
164         } catch (Exception ex) {
165             utils.log("DEBUG", " Sending Sync Error Activity Failed. " + "\n" + ex.getMessage(), isDebugEnabled)
166         }
167
168     }
169
170     public void prepareCompletionRequest(DelegateExecution execution) {
171         def isDebugEnabled = execution.getVariable("isDebugLogEnabled")
172         utils.log("DEBUG", " *** prepareCompletion *** ", isDebugEnabled)
173
174         try {
175             String requestId = execution.getVariable("msoRequestId")
176             String serviceInstanceId = execution.getVariable("serviceInstanceId")
177             String source = execution.getVariable("source")
178
179             String msoCompletionRequest =
180                     """<aetgt:MsoCompletionRequest xmlns:aetgt="http://org.openecomp/mso/workflow/schema/v1"
181                                                                 xmlns:ns="http://org.openecomp/mso/request/types/v1">
182                                                 <request-info xmlns="http://org.openecomp/mso/infra/vnf-request/v1">
183                                                         <request-id>${requestId}</request-id>
184                                                         <action>SCALE</action>
185                                                         <source>${source}</source>
186                                                    </request-info>
187                                                 <status-message>Service Instance was scaled successfully.</status-message>
188                                                 <serviceInstanceId>${serviceInstanceId}</serviceInstanceId>
189                                                    <mso-bpel-name>ScaleGenericALaCarteServiceInstance</mso-bpel-name>
190                                         </aetgt:MsoCompletionRequest>"""
191
192             // Format Response
193             String xmlMsoCompletionRequest = utils.formatXml(msoCompletionRequest)
194
195             execution.setVariable("CompleteMsoProcessRequest", xmlMsoCompletionRequest)
196             utils.log("DEBUG", " Overall SUCCESS Response going to CompleteMsoProcess - " + "\n" + xmlMsoCompletionRequest, isDebugEnabled)
197
198         } catch (Exception ex) {
199             String msg = " Exception in prepareCompletion:" + ex.getMessage()
200             utils.log("DEBUG", msg, isDebugEnabled)
201             exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg)
202         }
203         utils.log("DEBUG", "*** Exit prepareCompletionRequest ***", isDebugEnabled)
204     }
205
206     public void prepareFalloutRequest(DelegateExecution execution) {
207         def isDebugEnabled = execution.getVariable("isDebugLogEnabled")
208         utils.log("DEBUG", " *** prepareFalloutRequest *** ", isDebugEnabled)
209
210         try {
211             WorkflowException wfex = execution.getVariable("WorkflowException")
212             utils.log("DEBUG", " Input Workflow Exception: " + wfex.toString(), isDebugEnabled)
213             String requestId = execution.getVariable("msoRequestId")
214             String source = execution.getVariable("source")
215             String requestInfo =
216                     """<request-info xmlns="http://org.openecomp/mso/infra/vnf-request/v1">
217                                         <request-id>${requestId}</request-id>
218                                         <action>SCALE</action>
219                                         <source>${source}</source>
220                                    </request-info>"""
221
222             String falloutRequest = exceptionUtil.processMainflowsBPMNException(execution, requestInfo)
223             execution.setVariable("falloutRequest", falloutRequest)
224         } catch (Exception ex) {
225             utils.log("DEBUG", "Exception prepareFalloutRequest:" + ex.getMessage(), isDebugEnabled)
226             String errorException = "  Bpmn error encountered in ScaleGenericALaCarteServiceInstance flow. FalloutHandlerRequest,  buildErrorResponse() - " + ex.getMessage()
227             String requestId = execution.getVariable("msoRequestId")
228             String falloutRequest =
229                     """<aetgt:FalloutHandlerRequest xmlns:aetgt="http://org.openecomp/mso/workflow/schema/v1"
230                                                                                                  xmlns:ns="http://org.openecomp/mso/request/types/v1"
231                                                                                                  xmlns:wfsch="http://org.openecomp/mso/workflow/schema/v1">
232                                            <request-info xmlns="http://org.openecomp/mso/infra/vnf-request/v1">
233                                                   <request-id>${requestId}</request-id>
234                                                   <action>SCALE</action>
235                                                   <source>UUI</source>
236                                            </request-info>
237                                                 <aetgt:WorkflowException xmlns:aetgt="http://org.openecomp/mso/workflow/schema/v1">
238                                                         <aetgt:ErrorMessage>${errorException}</aetgt:ErrorMessage>
239                                                         <aetgt:ErrorCode>7000</aetgt:ErrorCode>
240                                                 </aetgt:WorkflowException>
241                                         </aetgt:FalloutHandlerRequest>"""
242
243             execution.setVariable("falloutRequest", falloutRequest)
244         }
245         utils.log("DEBUG", "*** Exit prepareFalloutRequest ***", isDebugEnabled)
246     }
247
248
249     /**
250      * Init the service Operation Status
251      */
252     public void prepareInitServiceOperationStatus(DelegateExecution execution){
253         def isDebugEnabled = execution.getVariable("isDebugLogEnabled")
254         utils.log("INFO", " ======== STARTED prepareInitServiceOperationStatus Process ======== ", isDebugEnabled)
255         try{
256             String serviceId = execution.getVariable("serviceInstanceId")
257             //String serviceName = execution.getVariable("serviceInstanceName")
258             String operationId = execution.getVariable("operationId")
259             String operationType = "SCALE"
260             String userId = ""
261             String result = "processing"
262             String progress = "0"
263             String reason = ""
264             String operationContent = "Prepare service scaling"
265             execution.setVariable("serviceInstanceId", serviceId)
266             execution.setVariable("operationId", operationId)
267             execution.setVariable("operationType", operationType)
268
269             def dbAdapterEndpoint = execution.getVariable("URN_mso_adapters_openecomp_db_endpoint")
270             execution.setVariable("CVFMI_dbAdapterEndpoint", dbAdapterEndpoint)
271             utils.log("INFO", "DB Adapter Endpoint is: " + dbAdapterEndpoint, isDebugEnabled)
272
273             String payload =
274                     """<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"
275                         xmlns:ns="http://org.openecomp.mso/requestsdb">
276                         <soapenv:Header/>
277                         <soapenv:Body>
278                             <ns:updateServiceOperationStatus xmlns:ns="http://org.openecomp.mso/requestsdb">
279                             <serviceId>${serviceId}</serviceId>
280                             <operationId>${operationId}</operationId>
281                             <operationType>${operationType}</operationType>
282                             <userId>${userId}</userId>
283                             <result>${result}</result>
284                             <operationContent>${operationContent}</operationContent>
285                             <progress>${progress}</progress>
286                             <reason>${reason}</reason>
287                         </ns:updateServiceOperationStatus>
288                     </soapenv:Body>
289                 </soapenv:Envelope>"""
290
291             payload = utils.formatXml(payload)
292             execution.setVariable("CVFMI_updateServiceOperStatusRequest", payload)
293             utils.log("INFO", "Outgoing updateServiceOperStatusRequest: \n" + payload, isDebugEnabled)
294             utils.logAudit("Scale network service updateServiceOperStatusRequest Request: " + payload)
295
296         }catch(Exception e){
297             utils.log("ERROR", "Exception Occured Processing prepareInitServiceOperationStatus. Exception is:\n" + e, isDebugEnabled)
298             execution.setVariable("CVFMI_ErrorResponse", "Error Occurred during prepareInitServiceOperationStatus Method:\n" + e.getMessage())
299         }
300         utils.log("INFO", "======== COMPLETED prepareInitServiceOperationStatus Process ======== ", isDebugEnabled)
301     }
302 }