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