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