fa3bfdb0e370e00c05f33946c50d5f44c30bb57b
[so.git] / bpmn / so-bpmn-infrastructure-common / src / main / groovy / org / onap / so / bpmn / infrastructure / scripts / CreateCustomE2EServiceInstance.groovy
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP - SO
4  * ================================================================================
5  * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
6  * Copyright (C) 2017 Huawei Technologies Co., Ltd. All rights reserved. 
7  * ================================================================================
8  * Modifications Copyright (c) 2019 Samsung
9  * ================================================================================
10  * Licensed under the Apache License, Version 2.0 (the "License");
11  * you may not use this file except in compliance with the License.
12  * You may obtain a copy of the License at
13  * 
14  *      http://www.apache.org/licenses/LICENSE-2.0
15  * 
16  * Unless required by applicable law or agreed to in writing, software
17  * distributed under the License is distributed on an "AS IS" BASIS,
18  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
19  * See the License for the specific language governing permissions and
20  * limitations under the License.
21  * ============LICENSE_END=========================================================
22  */
23
24 package org.onap.so.bpmn.infrastructure.scripts
25
26 import org.onap.aai.domain.yang.ServiceInstance
27 import org.onap.so.bpmn.core.domain.ServiceDecomposition
28 import org.onap.so.bpmn.core.domain.VnfResource
29 import org.onap.so.client.aai.AAIObjectType
30 import org.onap.so.client.aai.AAIResourcesClient
31 import org.onap.so.client.aai.entities.uri.AAIResourceUri
32 import org.onap.so.client.aai.entities.uri.AAIUriFactory
33 import org.onap.so.logger.ErrorCode;
34
35 import static org.apache.commons.lang3.StringUtils.*
36
37 import org.camunda.bpm.engine.delegate.BpmnError
38 import org.camunda.bpm.engine.delegate.DelegateExecution
39 import org.onap.so.bpmn.common.scripts.AbstractServiceTaskProcessor
40 import org.onap.so.bpmn.common.scripts.ExceptionUtil
41 import org.onap.so.bpmn.common.scripts.MsoUtils
42 import org.onap.so.bpmn.core.UrnPropertiesReader
43 import org.onap.so.bpmn.core.WorkflowException
44 import org.onap.so.bpmn.core.json.JsonUtils
45 import org.onap.so.logger.MessageEnum
46 import org.slf4j.Logger
47 import org.slf4j.LoggerFactory
48 import org.springframework.web.util.UriUtils
49
50 import groovy.json.*
51
52 /**
53  * This groovy class supports the <class>CreateServiceInstance.bpmn</class> process.
54  * AlaCarte flow for 1702 ServiceInstance Create
55  *
56  */
57 public class CreateCustomE2EServiceInstance extends AbstractServiceTaskProcessor {
58         String Prefix="CRESI_"
59         ExceptionUtil exceptionUtil = new ExceptionUtil()
60         JsonUtils jsonUtil = new JsonUtils()
61     private static final Logger logger = LoggerFactory.getLogger( CreateCustomE2EServiceInstance.class);
62         
63
64         public void preProcessRequest (DelegateExecution execution) {
65                 logger.trace("start preProcessRequest")
66                 execution.setVariable("prefix",Prefix)
67                 String msg = ""
68
69                 try {
70                         String siRequest = execution.getVariable("bpmnRequest")
71                         logger.debug(siRequest)
72
73                         String requestId = execution.getVariable("mso-request-id")
74                         execution.setVariable("msoRequestId", requestId)
75                         logger.debug("Input Request:" + siRequest + " reqId:" + requestId)
76
77                         String serviceInstanceId = execution.getVariable("serviceInstanceId")
78                         if (isBlank(serviceInstanceId)) {
79                                 serviceInstanceId = UUID.randomUUID().toString()
80                         }
81                         logger.debug("Generated new Service Instance:" + serviceInstanceId)
82                         serviceInstanceId = UriUtils.encode(serviceInstanceId,"UTF-8")
83                         execution.setVariable("serviceInstanceId", serviceInstanceId)
84
85                         //subscriberInfo
86                         String globalSubscriberId = jsonUtil.getJsonValue(siRequest, "requestDetails.subscriberInfo.globalSubscriberId")
87                         if (isBlank(globalSubscriberId)) {
88                                 msg = "Input globalSubscriberId' is null"
89                                 exceptionUtil.buildAndThrowWorkflowException(execution, 500, msg)
90                         } else {
91                                 execution.setVariable("globalSubscriberId", globalSubscriberId)
92                         }
93
94                         //requestInfo
95                         execution.setVariable("source", jsonUtil.getJsonValue(siRequest, "requestDetails.requestInfo.source"))
96                         execution.setVariable("serviceInstanceName", jsonUtil.getJsonValue(siRequest, "requestDetails.requestInfo.instanceName"))
97                         execution.setVariable("disableRollback", jsonUtil.getJsonValue(siRequest, "requestDetails.requestInfo.suppressRollback"))
98                         String productFamilyId = jsonUtil.getJsonValue(siRequest, "requestDetails.requestInfo.productFamilyId")
99                         if (isBlank(productFamilyId))
100                         {
101                                 msg = "Input productFamilyId is null"
102                                 logger.debug(msg)
103                                 //exceptionUtil.buildAndThrowWorkflowException(execution, 500, msg)
104                         } else {
105                                 execution.setVariable("productFamilyId", productFamilyId)
106                         }
107
108                         //modelInfo
109                         String serviceModelInfo = jsonUtil.getJsonValue(siRequest, "requestDetails.modelInfo")
110                         if (isBlank(serviceModelInfo)) {
111                                 msg = "Input serviceModelInfo is null"
112                                 logger.debug(msg)
113                                 exceptionUtil.buildAndThrowWorkflowException(execution, 500, msg)
114                         } else
115                         {
116                                 execution.setVariable("serviceModelInfo", serviceModelInfo)
117                         }
118
119                         logger.debug("modelInfo: " + serviceModelInfo)
120
121                         //requestParameters
122                         String subscriptionServiceType = jsonUtil.getJsonValue(siRequest, "requestDetails.requestParameters.subscriptionServiceType")
123                         if (isBlank(subscriptionServiceType)) {
124                                 msg = "Input subscriptionServiceType is null"
125                                 logger.debug(msg)
126                                 exceptionUtil.buildAndThrowWorkflowException(execution, 500, msg)
127                         } else {
128                                 execution.setVariable("subscriptionServiceType", subscriptionServiceType)
129                         }
130
131                         
132                         /*
133                          * Extracting User Parameters from incoming Request and converting into a Map
134                          */
135                         def jsonSlurper = new JsonSlurper()
136                         def jsonOutput = new JsonOutput()
137
138                         Map reqMap = jsonSlurper.parseText(siRequest)
139
140                         //InputParams
141                         def userParamsList = reqMap.requestDetails?.requestParameters?.userParams
142
143                         Map<String, String> inputMap = [:]
144                         if (userParamsList) {
145                                 for (def i=0; i<userParamsList.size(); i++) {
146                                         def userParams1 = userParamsList.get(i)
147                                         userParams1.each { param -> inputMap.put(param.key, param.value)}
148                                 }
149                         }
150                         
151                         logger.debug("User Input Parameters map: " + inputMap.toString())
152                         execution.setVariable("serviceInputParams", inputMap)
153                         execution.setVariable("uuiRequest", inputMap.get("UUIRequest"))
154
155                         //TODO
156                         //execution.setVariable("serviceInputParams", jsonUtil.getJsonValue(siRequest, "requestDetails.requestParameters.userParams"))
157                         //execution.setVariable("failExists", true)
158                 } catch (BpmnError e) {
159                         throw e;
160                 } catch (Exception ex){
161                         msg = "Exception in preProcessRequest " + ex.getMessage()
162                         logger.debug(msg)
163                         exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg)
164                 }
165                 logger.trace("finished preProcessRequest")
166         }
167
168         public void sendSyncResponse (DelegateExecution execution) {
169                 logger.trace("start sendSyncResponse")
170                 try {
171                         String operationId = execution.getVariable("operationId")
172                         String serviceInstanceId = execution.getVariable("serviceInstanceId")
173                         // RESTResponse for API Handler (APIH) Reply Task
174                         String createServiceRestRequest = """{"service":{"serviceId":"${serviceInstanceId}","operationId":"${operationId}"}}""".trim()
175                         logger.debug(" sendSyncResponse to APIH:" + "\n" + createServiceRestRequest)
176                         sendWorkflowResponse(execution, 202, createServiceRestRequest)
177                         execution.setVariable("sentSyncResponse", true)
178                 } catch (Exception ex) {
179                         String msg = "Exceptuion in sendSyncResponse:" + ex.getMessage()
180                         logger.debug(msg)
181                         exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg)
182                 }
183                 logger.trace("finished sendSyncResponse")
184         }
185
186
187         public void sendSyncError (DelegateExecution execution) {
188                 logger.trace("start sendSyncError")
189                 try {
190                         String errorMessage = ""
191                         if (execution.getVariable("WorkflowException") instanceof WorkflowException) {
192                                 WorkflowException wfe = execution.getVariable("WorkflowException")
193                                 errorMessage = wfe.getErrorMessage()
194                         } else {
195                                 errorMessage = "Sending Sync Error."
196                         }
197
198                         String buildworkflowException =
199                                         """<aetgt:WorkflowException xmlns:aetgt="http://org.onap/so/workflow/schema/v1">
200                                         <aetgt:ErrorMessage>${MsoUtils.xmlEscape(errorMessage)}</aetgt:ErrorMessage>
201                                         <aetgt:ErrorCode>7000</aetgt:ErrorCode>
202                                    </aetgt:WorkflowException>"""
203
204                         logger.debug(buildworkflowException)
205                         sendWorkflowResponse(execution, 500, buildworkflowException)
206
207                 } catch (Exception ex) {
208                         logger.debug("Sending Sync Error Activity Failed. " + "\n" + ex.getMessage())
209                 }
210                 logger.trace("finished sendSyncError")
211         }
212
213         public void prepareCompletionRequest (DelegateExecution execution) {
214                 logger.trace("start prepareCompletionRequest")
215                 try {
216                         String requestId = execution.getVariable("msoRequestId")
217                         String serviceInstanceId = execution.getVariable("serviceInstanceId")
218                         String source = execution.getVariable("source")
219                         
220                         String msoCompletionRequest =
221                                         """<aetgt:MsoCompletionRequest xmlns:aetgt="http://org.onap/so/workflow/schema/v1"
222                                                                 xmlns:ns="http://org.onap/so/request/types/v1">
223                                                 <request-info xmlns="http://org.onap/so/infra/vnf-request/v1">
224                                                         <request-id>${MsoUtils.xmlEscape(requestId)}</request-id>
225                                                         <action>CREATE</action>
226                                                         <source>${MsoUtils.xmlEscape(source)}</source>
227                                                 </request-info>
228                                                 <status-message>Service Instance was created successfully.</status-message>
229                                                 <serviceInstanceId>${MsoUtils.xmlEscape(serviceInstanceId)}</serviceInstanceId>
230                                                 <mso-bpel-name>CreateGenericALaCarteServiceInstance</mso-bpel-name>
231                                         </aetgt:MsoCompletionRequest>"""
232
233                         // Format Response
234                         String xmlMsoCompletionRequest = utils.formatXml(msoCompletionRequest)
235
236                         execution.setVariable("completionRequest", xmlMsoCompletionRequest)
237                         logger.debug("Overall SUCCESS Response going to CompleteMsoProcess - " + "\n" + xmlMsoCompletionRequest)
238
239                 } catch (Exception ex) {
240                         String msg = " Exception in prepareCompletion:" + ex.getMessage()
241                         logger.debug(msg)
242                         exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg)
243                 }
244                 logger.trace("finished prepareCompletionRequest")
245         }
246
247         public void prepareFalloutRequest(DelegateExecution execution){
248                 logger.trace("start prepareFalloutRequest")
249                 try {
250                         WorkflowException wfex = execution.getVariable("WorkflowException")
251                         logger.debug("Input Workflow Exception: " + wfex.toString())
252                         String requestId = execution.getVariable("msoRequestId")
253                         String source = execution.getVariable("source")
254                         String requestInfo =
255                                         """<request-info xmlns="http://org.onap/so/infra/vnf-request/v1">
256                                         <request-id>${MsoUtils.xmlEscape(requestId)}</request-id>
257                                         <action>CREATE</action>
258                                         <source>${MsoUtils.xmlEscape(source)}</source>
259                                    </request-info>"""
260
261                         String falloutRequest = exceptionUtil.processMainflowsBPMNException(execution, requestInfo)
262                         execution.setVariable("falloutRequest", falloutRequest)
263                 } catch (Exception ex) {
264                         logger.debug("Exception prepareFalloutRequest:" + ex.getMessage())
265                         String errorException = "  Bpmn error encountered in CreateGenericALaCarteServiceInstance flow. FalloutHandlerRequest,  buildErrorResponse() - " + ex.getMessage()
266                         String requestId = execution.getVariable("msoRequestId")
267                         String falloutRequest =
268                                         """<aetgt:FalloutHandlerRequest xmlns:aetgt="http://org.onap/so/workflow/schema/v1"
269                                                                      xmlns:ns="http://org.onap/so/request/types/v1"
270                                                                      xmlns:wfsch="http://org.onap/so/workflow/schema/v1">
271                                            <request-info xmlns="http://org.onap/so/infra/vnf-request/v1">
272                                               <request-id>${MsoUtils.xmlEscape(requestId)}</request-id>
273                                               <action>CREATE</action>
274                                               <source>UUI</source>
275                                            </request-info>
276                                                 <aetgt:WorkflowException xmlns:aetgt="http://org.onap/so/workflow/schema/v1">
277                                                         <aetgt:ErrorMessage>${MsoUtils.xmlEscape(errorException)}</aetgt:ErrorMessage>
278                                                         <aetgt:ErrorCode>7000</aetgt:ErrorCode>
279                                                 </aetgt:WorkflowException>
280                                         </aetgt:FalloutHandlerRequest>"""
281
282                         execution.setVariable("falloutRequest", falloutRequest)
283                 }
284                 logger.trace("finished prepareFalloutRequest")
285         }
286         
287         /**
288          * Init the service Operation Status
289          */
290         public void prepareInitServiceOperationStatus(DelegateExecution execution){
291                 logger.trace("start prepareInitServiceOperationStatus")
292         try{
293             String serviceId = execution.getVariable("serviceInstanceId")
294             String operationId = UUID.randomUUID().toString()
295             String operationType = "CREATE"
296             String userId = ""
297             String result = "processing"
298             String progress = "0"
299             String reason = ""
300             String operationContent = "Prepare service creation"
301             logger.debug("Generated new operation for Service Instance serviceId:" + serviceId + " operationId:" + operationId)
302             serviceId = UriUtils.encode(serviceId,"UTF-8")
303             execution.setVariable("serviceInstanceId", serviceId)
304             execution.setVariable("operationId", operationId)
305             execution.setVariable("operationType", operationType)
306
307             def dbAdapterEndpoint = UrnPropertiesReader.getVariable("mso.adapters.openecomp.db.endpoint",execution)
308             execution.setVariable("CVFMI_dbAdapterEndpoint", dbAdapterEndpoint)
309             logger.debug("DB Adapter Endpoint is: " + dbAdapterEndpoint)
310
311             String payload =
312                 """<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"
313                         xmlns:ns="http://org.onap.so/requestsdb">
314                         <soapenv:Header/>
315                         <soapenv:Body>
316                             <ns:initServiceOperationStatus xmlns:ns="http://org.onap.so/requestsdb">
317                             <serviceId>${MsoUtils.xmlEscape(serviceId)}</serviceId>
318                             <operationId>${MsoUtils.xmlEscape(operationId)}</operationId>
319                             <operationType>${MsoUtils.xmlEscape(operationType)}</operationType>
320                             <userId>${MsoUtils.xmlEscape(userId)}</userId>
321                             <result>${MsoUtils.xmlEscape(result)}</result>
322                             <operationContent>${MsoUtils.xmlEscape(operationContent)}</operationContent>
323                             <progress>${MsoUtils.xmlEscape(progress)}</progress>
324                             <reason>${MsoUtils.xmlEscape(reason)}</reason>
325                         </ns:initServiceOperationStatus>
326                     </soapenv:Body>
327                 </soapenv:Envelope>"""
328
329             payload = utils.formatXml(payload)
330             execution.setVariable("CVFMI_updateServiceOperStatusRequest", payload)
331             logger.debug("Outgoing updateServiceOperStatusRequest: \n" + payload)
332             logger.debug("CreateVfModuleInfra Outgoing updateServiceOperStatusRequest Request: " + payload)
333
334         }catch(Exception e){
335                         logger.error("{} {} {} {} {}", MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(),
336                                         "Exception Occured Processing prepareInitServiceOperationStatus.", "BPMN",
337                                         ErrorCode.UnknownError.getValue(), "Exception is:\n" + e);
338             execution.setVariable("CVFMI_ErrorResponse", "Error Occurred during prepareInitServiceOperationStatus Method:\n" + e.getMessage())
339         }
340                 logger.trace("finished prepareInitServiceOperationStatus")
341         }
342
343         public void updateAAIOrchStatus (DelegateExecution execution){
344                 logger.debug(" ***** start updateAAIOrchStatus ***** ")
345                 String msg = ""
346                 String serviceInstanceId = execution.getVariable("serviceInstanceId")
347                 logger.debug("serviceInstanceId: "+serviceInstanceId)
348                 ServiceDecomposition serviceDecomposition = execution.getVariable("serviceDecomposition")
349
350                 try {
351                         ServiceInstance si = execution.getVariable("serviceInstanceData")
352                         boolean allActive = true
353                         for (VnfResource resource : serviceDecomposition.vnfResources) {
354                                 logger.debug("resource.modelInfo.getModelName: " + resource.modelInfo.getModelName() +" | resource.getOrchestrationStatus: "+resource.getOrchestrationStatus())
355                                 if (resource.getOrchestrationStatus() != "Active") {
356                                         allActive = false
357                                 }
358                         }
359
360                         if (allActive){
361                                 si.setOrchestrationStatus("Assigned")
362                         }else {
363                                 si.setOrchestrationStatus("Pending")
364                         }
365                         AAIResourcesClient client = new AAIResourcesClient()
366                         AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIObjectType.SERVICE_INSTANCE, serviceInstanceId)
367                         client.update(uri, si)
368                 } catch (BpmnError e) {
369                         throw e
370                 } catch (Exception ex) {
371                         msg = "Exception in org.onap.so.bpmn.common.scripts.CompleteMsoProcess.updateAAIOrchStatus " + ex.getMessage()
372                         logger.info( msg)
373                         exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg)
374                 }
375
376                 logger.debug(" ***** end updateAAIOrchStatus ***** ")
377         }
378         
379 }