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