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