Removed MsoLogger class
[so.git] / bpmn / so-bpmn-infrastructure-common / src / main / groovy / org / onap / so / bpmn / infrastructure / scripts / DoCreateE2EServiceInstance.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 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 javax.ws.rs.NotFoundException
30
31 import org.camunda.bpm.engine.delegate.BpmnError
32 import org.camunda.bpm.engine.delegate.DelegateExecution
33 import org.onap.aai.domain.yang.ServiceInstance
34 import org.onap.so.bpmn.common.scripts.AbstractServiceTaskProcessor
35 import org.onap.so.bpmn.common.scripts.ExceptionUtil
36 import org.onap.so.bpmn.common.scripts.MsoUtils
37 import org.onap.so.bpmn.core.RollbackData
38 import org.onap.so.bpmn.core.WorkflowException
39 import org.onap.so.bpmn.core.domain.Resource
40 import org.onap.so.bpmn.core.domain.ServiceDecomposition
41 import org.onap.so.bpmn.core.json.JsonUtils
42 import org.onap.so.client.aai.AAIObjectType
43 import org.onap.so.client.aai.AAIResourcesClient
44 import org.onap.so.client.aai.entities.AAIResultWrapper
45 import org.onap.so.client.aai.entities.uri.AAIResourceUri
46 import org.onap.so.bpmn.infrastructure.workflow.service.ServicePluginFactory
47 import org.onap.so.client.aai.entities.uri.AAIUriFactory
48 import org.onap.so.logger.MessageEnum
49 import org.slf4j.Logger
50 import org.slf4j.LoggerFactory
51
52 import org.springframework.web.util.UriUtils
53 import org.onap.so.bpmn.core.UrnPropertiesReader
54
55 /**
56  * This groovy class supports the <class>DoCreateServiceInstance.bpmn</class> process.
57  *
58  * Inputs:
59  * @param - msoRequestId
60  * @param - globalSubscriberId
61  * @param - subscriptionServiceType
62  * @param - serviceInstanceId
63  * @param - serviceInstanceName - O
64  * @param - serviceModelInfo
65  * @param - productFamilyId
66  * @param - disableRollback
67  * @param - failExists - TODO
68  * @param - serviceInputParams (should contain aic_zone for serviceTypes TRANSPORT,ATM)
69  * @param - sdncVersion ("1610")
70  * @param - serviceDecomposition - Decomposition for R1710
71  * (if macro provides serviceDecompsition then serviceModelInfo, serviceInstanceId & serviceInstanceName will be ignored)
72  *
73  * Outputs:
74  * @param - rollbackData (localRB->null)
75  * @param - rolledBack (no localRB->null, localRB F->false, localRB S->true)
76  * @param - WorkflowException
77  * @param - serviceInstanceName - (GET from AAI if null in input)
78  *
79  */
80 public class DoCreateE2EServiceInstance extends AbstractServiceTaskProcessor {
81     private static final Logger logger = LoggerFactory.getLogger( DoCreateE2EServiceInstance.class);
82
83
84         String Prefix="DCRESI_"
85         ExceptionUtil exceptionUtil = new ExceptionUtil()
86         JsonUtils jsonUtil = new JsonUtils()
87
88         public void preProcessRequest (DelegateExecution execution) {
89                 String msg = ""
90                 logger.trace("preProcessRequest ")
91
92                 try {
93                         execution.setVariable("prefix", Prefix)
94                         //Inputs
95                         //requestDetails.subscriberInfo. for AAI GET & PUT & SDNC assignToplology
96                         String globalSubscriberId = execution.getVariable("globalSubscriberId") //globalCustomerId
97                         logger.info(" ***** globalSubscriberId *****" + globalSubscriberId)
98                         //requestDetails.requestParameters. for AAI PUT & SDNC assignTopology
99                         String serviceType = execution.getVariable("serviceType")
100                         logger.info(" ***** serviceType *****" + serviceType)
101                         //requestDetails.requestParameters. for SDNC assignTopology
102                         String productFamilyId = execution.getVariable("productFamilyId") //AAI productFamilyId
103
104                         if (isBlank(globalSubscriberId)) {
105                                 msg = "Input globalSubscriberId is null"
106                                 logger.info(msg)
107                                 exceptionUtil.buildAndThrowWorkflowException(execution, 500, msg)
108                         }
109
110                         if (isBlank(serviceType)) {
111                                 msg = "Input serviceType is null"
112                                 logger.info(msg)
113                                 exceptionUtil.buildAndThrowWorkflowException(execution, 500, msg)
114                         }
115
116                         if (productFamilyId == null) {
117                                 execution.setVariable("productFamilyId", "")
118                         }
119
120                         String sdncCallbackUrl = UrnPropertiesReader.getVariable("mso.workflow.sdncadapter.callback", execution)
121                         if (isBlank(sdncCallbackUrl)) {
122                                 msg = "URN_mso_workflow_sdncadapter_callback is null"
123                                 logger.info(msg)
124                                 exceptionUtil.buildAndThrowWorkflowException(execution, 500, msg)
125                         }
126                         execution.setVariable("sdncCallbackUrl", sdncCallbackUrl)
127                         logger.info("SDNC Callback URL: " + sdncCallbackUrl)
128
129                         //requestDetails.modelInfo.for AAI PUT servieInstanceData
130                         //requestDetails.requestInfo. for AAI GET/PUT serviceInstanceData
131                         String serviceInstanceName = execution.getVariable("serviceInstanceName")
132                         String serviceInstanceId = execution.getVariable("serviceInstanceId")
133                         String uuiRequest = execution.getVariable("uuiRequest")
134                         String modelInvariantUuid = jsonUtil.getJsonValue(uuiRequest, "service.serviceInvariantUuid")
135                         String modelUuid = jsonUtil.getJsonValue(uuiRequest, "service.serviceUuid")
136                         String serviceModelName = jsonUtil.getJsonValue(uuiRequest, "service.parameters.templateName")
137                         execution.setVariable("serviceModelName", serviceModelName)
138                         //aai serviceType and Role can be setted as fixed value now.
139                         String aaiServiceType = "E2E Service"
140                         String aaiServiceRole = "E2E Service"
141
142                         execution.setVariable("modelInvariantUuid", modelInvariantUuid)
143                         execution.setVariable("modelUuid", modelUuid)
144
145                         //AAI PUT
146                         String oStatus = execution.getVariable("initialStatus") ?: ""
147                         if ("TRANSPORT".equalsIgnoreCase(serviceType))
148                         {
149                                 oStatus = "Created"
150                         }
151
152                         org.onap.aai.domain.yang.ServiceInstance si = new org.onap.aai.domain.yang.ServiceInstance()
153                         si.setServiceInstanceName(serviceInstanceName)
154                         si.setServiceType(aaiServiceType)
155                         si.setServiceRole(aaiServiceRole)
156                         si.setOrchestrationStatus(oStatus)
157                         si.setModelInvariantId(modelInvariantUuid)
158                         si.setModelVersionId(modelUuid)
159                         si.setInputParameters(uuiRequest)
160                         execution.setVariable("serviceInstanceData", si)
161
162                 } catch (BpmnError e) {
163                         throw e;
164                 } catch (Exception ex){
165                         msg = "Exception in preProcessRequest " + ex.getMessage()
166                         logger.info(msg)
167                         exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg)
168                 }
169                 logger.trace("Exit preProcessRequest ")
170         }
171
172    public void prepareDecomposeService(DelegateExecution execution) {
173         try {
174             logger.trace("Inside prepareDecomposeService of create generic e2e service ")
175             String modelInvariantUuid = execution.getVariable("modelInvariantUuid")
176             String modelUuid = execution.getVariable("modelUuid")
177             //here modelVersion is not set, we use modelUuid to decompose the service.
178             String serviceModelInfo = """{
179             "modelInvariantUuid":"${modelInvariantUuid}",
180             "modelUuid":"${modelUuid}",
181             "modelVersion":""
182              }"""
183             execution.setVariable("serviceModelInfo", serviceModelInfo)
184
185             logger.trace("Completed prepareDecomposeService of  create generic e2e service ")
186         } catch (Exception ex) {
187             // try error in method block
188             String exceptionMessage = "Bpmn error encountered in  create generic e2e service flow. Unexpected Error from method prepareDecomposeService() - " + ex.getMessage()
189             exceptionUtil.buildAndThrowWorkflowException(execution, 7000, exceptionMessage)
190         }
191      }
192
193     public void processDecomposition(DelegateExecution execution) {
194         logger.trace("Inside processDecomposition() of  create generic e2e service flow ")
195         try {
196             ServiceDecomposition serviceDecomposition = execution.getVariable("serviceDecomposition")
197         } catch (Exception ex) {
198             String exceptionMessage = "Bpmn error encountered in  create generic e2e service flow. processDecomposition() - " + ex.getMessage()
199             logger.debug(exceptionMessage)
200             exceptionUtil.buildAndThrowWorkflowException(execution, 7000, exceptionMessage)
201         }
202     }
203
204     public void doServicePreOperation(DelegateExecution execution){
205        //we need a service plugin platform here.
206         ServiceDecomposition serviceDecomposition = execution.getVariable("serviceDecomposition")
207         String uuiRequest = execution.getVariable("uuiRequest")
208         String newUuiRequest = ServicePluginFactory.getInstance().preProcessService(serviceDecomposition, uuiRequest);
209         execution.setVariable("uuiRequest", newUuiRequest)
210     }
211
212     public void doServiceHoming(DelegateExecution execution) {
213         //we need a service plugin platform here.
214         ServiceDecomposition serviceDecomposition = execution.getVariable("serviceDecomposition")
215         String uuiRequest = execution.getVariable("uuiRequest")
216         String newUuiRequest = ServicePluginFactory.getInstance().doServiceHoming(serviceDecomposition, uuiRequest);
217         execution.setVariable("uuiRequest", newUuiRequest)
218     }
219
220         public void postProcessAAIGET(DelegateExecution execution) {
221                 logger.trace("postProcessAAIGET ")
222                 String msg = ""
223
224                 try {
225                         String serviceInstanceName = execution.getVariable("serviceInstanceName")
226                         boolean succInAAI = execution.getVariable("GENGS_SuccessIndicator")
227                         if(!succInAAI){
228                                 logger.info("Error getting Service-instance from AAI", + serviceInstanceName)
229                                 WorkflowException workflowException = execution.getVariable("WorkflowException")
230                                 logger.debug("workflowException: " + workflowException)
231                                 if(workflowException != null){
232                                         exceptionUtil.buildAndThrowWorkflowException(execution, workflowException.getErrorCode(), workflowException.getErrorMessage())
233                                 }
234                                 else
235                                 {
236                                         msg = "Failure in postProcessAAIGET GENGS_SuccessIndicator:" + succInAAI
237                                         logger.info(msg)
238                                         exceptionUtil.buildAndThrowWorkflowException(execution, 2500, msg)
239                                 }
240                         }
241                         else
242                         {
243                                 boolean foundInAAI = execution.getVariable("GENGS_FoundIndicator")
244                                 if(foundInAAI){
245                                         logger.info("Found Service-instance in AAI")
246                                         msg = "ServiceInstance already exists in AAI:" + serviceInstanceName
247                                         logger.info(msg)
248                                         exceptionUtil.buildAndThrowWorkflowException(execution, 2500, msg)
249                                 }
250                         }
251                 } catch (BpmnError e) {
252                         throw e;
253                 } catch (Exception ex) {
254                         msg = "Exception in DoCreateServiceInstance.postProcessAAIGET. " + ex.getMessage()
255                         logger.info(msg)
256                         exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg)
257                 }
258                 logger.trace("Exit postProcessAAIGET ")
259         }
260
261         //TODO use create if not exist
262         public void createServiceInstance(DelegateExecution execution) {
263                 logger.trace("createServiceInstance ")
264                 String msg = ""
265                 String serviceInstanceId = execution.getVariable("serviceInstanceId")
266                 try {
267                         org.onap.aai.domain.yang.ServiceInstance si = execution.getVariable("serviceInstanceData")
268
269                         AAIResourcesClient client = new AAIResourcesClient()
270                         AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIObjectType.SERVICE_INSTANCE, execution.getVariable("globalSubscriberId"), execution.getVariable("serviceType"), serviceInstanceId)
271                         client.create(uri, si)
272
273                 } catch (BpmnError e) {
274                         throw e;
275                 } catch (Exception ex) {
276                         //start rollback set up
277                         RollbackData rollbackData = new RollbackData()
278                         def disableRollback = execution.getVariable("disableRollback")
279                         rollbackData.put("SERVICEINSTANCE", "disableRollback", disableRollback.toString())
280                         rollbackData.put("SERVICEINSTANCE", "rollbackAAI", "true")
281                         rollbackData.put("SERVICEINSTANCE", "serviceInstanceId", serviceInstanceId)
282                         rollbackData.put("SERVICEINSTANCE", "subscriptionServiceType", execution.getVariable("subscriptionServiceType"))
283                         rollbackData.put("SERVICEINSTANCE", "globalSubscriberId", execution.getVariable("globalSubscriberId"))
284                         execution.setVariable("rollbackData", rollbackData)
285
286                         msg = "Exception in DoCreateServiceInstance.createServiceInstance. " + ex.getMessage()
287                         logger.info(msg)
288                         exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg)
289                 }
290                 logger.trace("Exit createServiceInstance ")
291         }
292
293         /**
294          * Gets the service instance and its relationships from aai
295          */
296         public void getServiceInstance(DelegateExecution execution) {
297                 try {
298                         String serviceInstanceId = execution.getVariable('serviceInstanceId')
299                         String globalSubscriberId = execution.getVariable('globalSubscriberId')
300                         String serviceType = execution.getVariable('subscriptionServiceType')
301
302                         AAIResourcesClient resourceClient = new AAIResourcesClient()
303                         AAIResourceUri serviceInstanceUri = AAIUriFactory.createResourceUri(AAIObjectType.SERVICE_INSTANCE, globalSubscriberId, serviceType, serviceInstanceId)
304                         AAIResultWrapper wrapper = resourceClient.get(serviceInstanceUri, NotFoundException.class)
305
306                         Optional<ServiceInstance> si = wrapper.asBean(ServiceInstance.class)
307                         execution.setVariable("serviceInstanceName", si.get().getServiceInstanceName())
308
309                 }catch(BpmnError e) {
310                         throw e;
311                 }catch(Exception ex) {
312                         String msg = "Internal Error in getServiceInstance: " + ex.getMessage()
313                         exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg)
314                 }
315         }
316
317         public void postProcessAAIGET2(DelegateExecution execution) {
318                 logger.trace("postProcessAAIGET2 ")
319                 String msg = ""
320
321                 try {
322                         String serviceInstanceName = execution.getVariable("serviceInstanceName")
323                         boolean succInAAI = execution.getVariable("GENGS_SuccessIndicator")
324                         if(!succInAAI){
325                                 logger.info("Error getting Service-instance from AAI in postProcessAAIGET2", + serviceInstanceName)
326                                 WorkflowException workflowException = execution.getVariable("WorkflowException")
327                                 logger.debug("workflowException: " + workflowException)
328                                 if(workflowException != null){
329                                         exceptionUtil.buildAndThrowWorkflowException(execution, workflowException.getErrorCode(), workflowException.getErrorMessage())
330                                 }
331                                 else
332                                 {
333                                         msg = "Failure in postProcessAAIGET2 GENGS_SuccessIndicator:" + succInAAI
334                                         logger.info(msg)
335                                         exceptionUtil.buildAndThrowWorkflowException(execution, 2500, msg)
336                                 }
337                         }
338                         else
339                         {
340                                 boolean foundInAAI = execution.getVariable("GENGS_FoundIndicator")
341                                 if(foundInAAI){
342                                         String aaiService = execution.getVariable("GENGS_service")
343                                         if (!isBlank(aaiService) && (utils.nodeExists(aaiService, "service-instance-name"))) {
344                                                 execution.setVariable("serviceInstanceName",  utils.getNodeText(aaiService, "service-instance-name"))
345                                                 logger.info("Found Service-instance in AAI.serviceInstanceName:" + execution.getVariable("serviceInstanceName"))
346                                         }
347                                 }
348                         }
349                 } catch (BpmnError e) {
350                         throw e;
351                 } catch (Exception ex) {
352                         msg = "Exception in DoCreateServiceInstance.postProcessAAIGET2 " + ex.getMessage()
353                         logger.info(msg)
354                         exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg)
355                 }
356                 logger.trace("Exit postProcessAAIGET2 ")
357         }
358
359         public void preProcessRollback (DelegateExecution execution) {
360                 logger.trace("preProcessRollback ")
361                 try {
362
363                         Object workflowException = execution.getVariable("WorkflowException");
364
365                         if (workflowException instanceof WorkflowException) {
366                                 logger.info("Prev workflowException: " + workflowException.getErrorMessage())
367                                 execution.setVariable("prevWorkflowException", workflowException);
368                                 //execution.setVariable("WorkflowException", null);
369                         }
370                 } catch (BpmnError e) {
371                         logger.info("BPMN Error during preProcessRollback")
372                 } catch(Exception ex) {
373                         String msg = "Exception in preProcessRollback. " + ex.getMessage()
374                         logger.info(msg)
375                 }
376                 logger.trace("Exit preProcessRollback ")
377         }
378
379         public void postProcessRollback (DelegateExecution execution) {
380                 logger.trace("postProcessRollback ")
381                 String msg = ""
382                 try {
383                         Object workflowException = execution.getVariable("prevWorkflowException");
384                         if (workflowException instanceof WorkflowException) {
385                                 logger.info("Setting prevException to WorkflowException: ")
386                                 execution.setVariable("WorkflowException", workflowException);
387                         }
388                         execution.setVariable("rollbackData", null)
389                 } catch (BpmnError b) {
390                         logger.info("BPMN Error during postProcessRollback")
391                         throw b;
392                 } catch(Exception ex) {
393                         msg = "Exception in postProcessRollback. " + ex.getMessage()
394                         logger.info(msg)
395                 }
396                 logger.trace("Exit postProcessRollback ")
397         }
398
399         public void preInitResourcesOperStatus(DelegateExecution execution){
400         logger.trace("STARTED preInitResourcesOperStatus Process ")
401         try{
402             String serviceId = execution.getVariable("serviceInstanceId")
403             String operationId = execution.getVariable("operationId")
404             String operationType = execution.getVariable("operationType")
405             String resourceTemplateUUIDs = ""
406             String result = "processing"
407             String progress = "0"
408             String reason = ""
409             String operationContent = "Prepare service creation"
410             logger.info("Generated new operation for Service Instance serviceId:" + serviceId + " operationId:" + operationId + " operationType:" + operationType)
411             serviceId = UriUtils.encode(serviceId,"UTF-8")
412             execution.setVariable("serviceInstanceId", serviceId)
413             execution.setVariable("operationId", operationId)
414             execution.setVariable("operationType", operationType)
415             ServiceDecomposition serviceDecomposition = execution.getVariable("serviceDecomposition")
416             List<Resource>  resourceList = serviceDecomposition.getServiceResources()
417
418             for(Resource resource : resourceList){
419                     resourceTemplateUUIDs  = resourceTemplateUUIDs + resource.getModelInfo().getModelCustomizationUuid() + ":"
420             }
421
422             def dbAdapterEndpoint = UrnPropertiesReader.getVariable("mso.adapters.db.endpoint")
423             execution.setVariable("CVFMI_dbAdapterEndpoint", dbAdapterEndpoint)
424             logger.info("DB Adapter Endpoint is: " + dbAdapterEndpoint)
425
426             String payload =
427                 """<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"
428                         xmlns:ns="http://org.onap.so/requestsdb">
429                         <soapenv:Header/>
430                         <soapenv:Body>
431                             <ns:initResourceOperationStatus xmlns:ns="http://org.onap.so/requestsdb">
432                                                                 <serviceId>${MsoUtils.xmlEscape(serviceId)}</serviceId>
433                                                                 <operationId>${MsoUtils.xmlEscape(operationId)}</operationId>
434                                                                 <operationType>${MsoUtils.xmlEscape(operationType)}</operationType>
435                                                                 <resourceTemplateUUIDs>${MsoUtils.xmlEscape(resourceTemplateUUIDs)}</resourceTemplateUUIDs>
436                             </ns:initResourceOperationStatus>
437                         </soapenv:Body>
438                         </soapenv:Envelope>"""
439
440             payload = utils.formatXml(payload)
441             execution.setVariable("CVFMI_initResOperStatusRequest", payload)
442             logger.info("Outgoing initResourceOperationStatus: \n" + payload)
443             logger.debug("CreateVfModuleInfra Outgoing initResourceOperationStatus Request: " + payload)
444
445         }catch(Exception e){
446             logger.error("{} {} {} {} {}", MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(),
447                                         "Exception Occured Processing preInitResourcesOperStatus.", "BPMN",
448                                         ErrorCode.UnknownError.getValue(), e);
449             execution.setVariable("CVFMI_ErrorResponse", "Error Occurred during preInitResourcesOperStatus Method:\n" + e.getMessage())
450         }
451         logger.trace("COMPLETED preInitResourcesOperStatus Process ")
452         }
453
454         // if site location is in local Operator, create all resources in local ONAP;
455         // if site location is in 3rd Operator, only process sp-partner to create all resources in 3rd ONAP
456         public void doProcessSiteLocation(DelegateExecution execution){
457                 logger.trace("======== Start doProcessSiteLocation Process ======== ")
458                 ServiceDecomposition serviceDecomposition = execution.getVariable("serviceDecomposition")
459                 String uuiRequest = execution.getVariable("uuiRequest")
460                 uuiRequest = ServicePluginFactory.getInstance().doProcessSiteLocation(serviceDecomposition, uuiRequest);
461                 execution.setVariable("uuiRequest", uuiRequest)
462                 execution.setVariable("serviceDecomposition", serviceDecomposition)
463
464                 logger.trace("======== COMPLETED doProcessSiteLocation Process ======== ")
465         }
466
467         // Allocate cross link TPs(terminal points) for sotn network only
468         public void doTPResourcesAllocation(DelegateExecution execution){
469                 logger.trace("======== Start doTPResourcesAllocation Process ======== ")
470                 ServiceDecomposition serviceDecomposition = execution.getVariable("serviceDecomposition")
471                 String uuiRequest = execution.getVariable("uuiRequest")
472                 uuiRequest = ServicePluginFactory.getInstance().doTPResourcesAllocation(execution, uuiRequest);
473                 execution.setVariable("uuiRequest", uuiRequest)
474                 logger.trace("======== COMPLETED doTPResourcesAllocation Process ======== ")
475         }
476
477         // prepare input param for using DoCreateResources.bpmn
478         public void preProcessForAddResource(DelegateExecution execution) {
479                 logger.trace("STARTED preProcessForAddResource Process ")
480
481                 ServiceDecomposition serviceDecomposition = execution.getVariable("serviceDecomposition")
482                 List<Resource> addResourceList = serviceDecomposition.getServiceResources()
483                 execution.setVariable("addResourceList", addResourceList)
484
485                 logger.trace("COMPLETED preProcessForAddResource Process ")
486         }
487
488         public void postProcessForAddResource(DelegateExecution execution) {
489                 // do nothing now
490
491         }
492
493 }