d57011f61fdf55b91c4d787592a84c8fc0eef807
[so.git] /
1 /*
2  * ============LICENSE_START=======================================================
3  * ONAP - SO
4  * ================================================================================
5  * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
6  * ================================================================================
7  * Modifications Copyright (c) 2019 Samsung
8  * ================================================================================
9  * Licensed under the Apache License, Version 2.0 (the "License");
10  * you may not use this file except in compliance with the License.
11  * You may obtain a copy of the License at
12  * 
13  *      http://www.apache.org/licenses/LICENSE-2.0
14  * 
15  * Unless required by applicable law or agreed to in writing, software
16  * distributed under the License is distributed on an "AS IS" BASIS,
17  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18  * See the License for the specific language governing permissions and
19  * limitations under the License.
20  * ============LICENSE_END=========================================================
21  */
22 package org.onap.so.bpmn.vcpe.scripts
23
24 import org.onap.so.logger.LoggingAnchor
25 import org.onap.so.logger.ErrorCode;
26
27 import static org.apache.commons.lang3.StringUtils.*
28
29 import org.camunda.bpm.engine.delegate.BpmnError
30 import org.camunda.bpm.engine.delegate.DelegateExecution
31 import org.onap.so.bpmn.common.scripts.AbstractServiceTaskProcessor
32 import org.onap.so.bpmn.common.scripts.ExceptionUtil
33 import org.onap.so.bpmn.common.scripts.MsoUtils
34 import org.onap.so.bpmn.common.scripts.VidUtils
35 import org.onap.so.bpmn.core.WorkflowException
36 import org.onap.so.bpmn.core.domain.*
37 import org.onap.so.bpmn.core.json.JsonUtils
38 import org.onap.so.bpmn.core.UrnPropertiesReader
39 import org.onap.so.logger.MessageEnum
40 import org.springframework.web.util.UriUtils
41 import org.slf4j.Logger
42 import org.slf4j.LoggerFactory
43
44 import groovy.json.*
45
46
47
48 /**
49  * This groovy class supports the <class>CreateVcpeResCustService.bpmn</class> process.
50  *
51  * @author ek1439
52  *
53  */
54 public class CreateVcpeResCustService extends AbstractServiceTaskProcessor {
55     private static final Logger logger = LoggerFactory.getLogger(CreateVcpeResCustService.class);
56
57     private static final String DebugFlag = "isDebugLogEnabled"
58
59     String Prefix = "CVRCS_"
60     ExceptionUtil exceptionUtil = new ExceptionUtil()
61     JsonUtils jsonUtil = new JsonUtils()
62     VidUtils vidUtils = new VidUtils()
63
64     /**
65      * This method is executed during the preProcessRequest task of the <class>CreateServiceInstance.bpmn</class> process.
66      * @param execution
67      */
68     private InitializeProcessVariables(DelegateExecution execution) {
69         /* Initialize all the process variables in this block */
70
71         execution.setVariable("createVcpeServiceRequest", "")
72         execution.setVariable("globalSubscriberId", "")
73         execution.setVariable("serviceInstanceName", "")
74         execution.setVariable("msoRequestId", "")
75         execution.setVariable(Prefix + "VnfsCreatedCount", 0)
76         execution.setVariable("productFamilyId", "")
77         execution.setVariable("brgWanMacAddress", "")
78         execution.setVariable("customerLocation", "")
79         execution.setVariable("homingService", "")
80         execution.setVariable("cloudOwner", "")
81         execution.setVariable("cloudRegionId", "")
82         execution.setVariable("homingModelIds", "")
83
84         //TODO
85         execution.setVariable("sdncVersion", "1707")
86     }
87
88     // **************************************************
89     //     Pre or Prepare Request Section
90     // **************************************************
91     /**
92      * This method is executed during the preProcessRequest task of the <class>CreateServiceInstance.bpmn</class> process.
93      * @param execution
94      */
95     public void preProcessRequest(DelegateExecution execution) {
96         def isDebugEnabled = execution.getVariable(DebugFlag)
97         execution.setVariable("prefix", Prefix)
98
99         logger.trace("Inside preProcessRequest CreateVcpeResCustService Request ")
100
101         try {
102             // initialize flow variables
103             InitializeProcessVariables(execution)
104
105             //Config Inputs
106             String aaiDistDelay = UrnPropertiesReader.getVariable("aai.workflowAaiDistributionDelay", execution)
107             if (isBlank(aaiDistDelay)) {
108                 String msg = "workflowAaiDistributionDelay is null"
109                 logger.debug(msg)
110                 exceptionUtil.buildAndThrowWorkflowException(execution, 500, msg)
111             }
112             execution.setVariable("aaiDistDelay", aaiDistDelay)
113             logger.debug("AAI distribution delay: " + aaiDistDelay)
114
115             // check for incoming json message/input
116             String createVcpeServiceRequest = execution.getVariable("bpmnRequest")
117             logger.debug(createVcpeServiceRequest)
118             execution.setVariable("createVcpeServiceRequest", createVcpeServiceRequest);
119             println 'createVcpeServiceRequest - ' + createVcpeServiceRequest
120
121             // extract requestId
122             String requestId = execution.getVariable("mso-request-id")
123             execution.setVariable("msoRequestId", requestId)
124
125             String serviceInstanceId = execution.getVariable("serviceInstanceId")
126
127             if ((serviceInstanceId == null) || (serviceInstanceId.isEmpty())) {
128                 serviceInstanceId = UUID.randomUUID().toString()
129                 logger.debug(" Generated new Service Instance: " + serviceInstanceId)
130             } else {
131                 logger.debug("Using provided Service Instance ID: " + serviceInstanceId)
132             }
133
134             serviceInstanceId = UriUtils.encode(serviceInstanceId, "UTF-8")
135             execution.setVariable("serviceInstanceId", serviceInstanceId)
136             logger.debug("Incoming serviceInstanceId is: " + serviceInstanceId)
137
138             String serviceInstanceName = jsonUtil.getJsonValue(createVcpeServiceRequest, "requestDetails.requestInfo.instanceName")
139             execution.setVariable("serviceInstanceName", serviceInstanceName)
140             logger.debug("Incoming serviceInstanceName is: " + serviceInstanceName)
141
142             String requestAction = execution.getVariable("requestAction")
143             execution.setVariable("requestAction", requestAction)
144
145             setBasicDBAuthHeader(execution, isDebugEnabled)
146
147             String source = jsonUtil.getJsonValue(createVcpeServiceRequest, "requestDetails.requestInfo.source")
148             if ((source == null) || (source.isEmpty())) {
149                 source = "VID"
150             }
151             execution.setVariable("source", source)
152
153             // extract globalSubscriberId
154             String globalSubscriberId = jsonUtil.getJsonValue(createVcpeServiceRequest, "requestDetails.subscriberInfo.globalSubscriberId")
155
156             // verify element global-customer-id is sent from JSON input, throw exception if missing
157             if ((globalSubscriberId == null) || (globalSubscriberId.isEmpty())) {
158                 String dataErrorMessage = " Element 'globalSubscriberId' is missing. "
159                 exceptionUtil.buildAndThrowWorkflowException(execution, 2500, dataErrorMessage)
160
161             } else {
162                 execution.setVariable("globalSubscriberId", globalSubscriberId)
163                 execution.setVariable("globalCustomerId", globalSubscriberId)
164             }
165
166             // extract subscriptionServiceType
167             String subscriptionServiceType = jsonUtil.getJsonValue(createVcpeServiceRequest, "requestDetails.requestParameters.subscriptionServiceType")
168             execution.setVariable("subscriptionServiceType", subscriptionServiceType)
169             logger.debug("Incoming subscriptionServiceType is: " + subscriptionServiceType)
170
171             String suppressRollback = jsonUtil.getJsonValue(createVcpeServiceRequest, "requestDetails.requestInfo.suppressRollback")
172             execution.setVariable("disableRollback", suppressRollback)
173             logger.debug("Incoming Suppress/Disable Rollback is: " + suppressRollback)
174
175             String productFamilyId = jsonUtil.getJsonValue(createVcpeServiceRequest, "requestDetails.requestInfo.productFamilyId")
176             execution.setVariable("productFamilyId", productFamilyId)
177             logger.debug("Incoming productFamilyId is: " + productFamilyId)
178
179             String subscriberInfo = jsonUtil.getJsonValue(createVcpeServiceRequest, "requestDetails.subscriberInfo")
180             execution.setVariable("subscriberInfo", subscriberInfo)
181             logger.debug("Incoming subscriberInfo is: " + subscriberInfo)
182
183             // extract cloud configuration - if underscore "_" is present treat as vimId else it's a cloudRegion
184             String vimId = jsonUtil.getJsonValue(createVcpeServiceRequest,
185                     "requestDetails.cloudConfiguration.lcpCloudRegionId")
186             if (vimId.contains("_") && vimId.split("_").length == 2 ) {
187                 def cloudRegion = vimId.split("_")
188                 def cloudOwner = cloudRegion[0]
189                 def cloudRegionId = cloudRegion[1]
190                 execution.setVariable("cloudOwner", cloudOwner)
191                 logger.debug("cloudOwner: " + cloudOwner)
192                 execution.setVariable("cloudRegionId", cloudRegionId)
193                 logger.debug("cloudRegionId: " + cloudRegionId)
194             } else {
195                 logger.debug("vimId is not present - setting  cloudRegion/cloudOwner from request.")
196                 String cloudOwner = jsonUtil.getJsonValue(createVcpeServiceRequest,
197                         "requestDetails.cloudConfiguration.cloudOwner")
198                 if (!cloudOwner?.empty && cloudOwner != "")
199                 {
200                     execution.setVariable("cloudOwner", cloudOwner)
201                     logger.debug("cloudOwner: " + cloudOwner)
202                 }
203                 def cloudRegionId = vimId
204                 execution.setVariable("cloudRegionId", cloudRegionId)
205                 logger.debug("cloudRegionId: " + cloudRegionId)
206             }
207             /*
208             * Extracting User Parameters from incoming Request and converting into a Map
209             */
210             def jsonSlurper = new JsonSlurper()
211
212             Map reqMap = jsonSlurper.parseText(createVcpeServiceRequest)
213
214             //InputParams
215             def userParams = reqMap.requestDetails?.requestParameters?.userParams
216
217             Map<String, String> inputMap = [:]
218             if (userParams) {
219                 userParams.each {
220                     userParam ->
221                         if ("Customer_Location".equals(userParam?.name)) {
222                             Map<String, String> customerMap = [:]
223                             userParam.value.each {
224                                 param ->
225                                     inputMap.put(param.key, param.value)
226                                     customerMap.put(param.key, param.value)
227                                     }
228                             execution.setVariable("customerLocation", customerMap)
229                         }
230                         if ("Homing_Model_Ids".equals(userParam?.name)) {
231                             logger.debug("Homing_Model_Ids: " + userParam.value.toString() + "  ---- Type is:" +
232                                     userParam.value.getClass())
233                             def modelIdLst = []
234                             userParam.value.each {
235                                 param ->
236                                     def valueMap = [:]
237                                     param.each {
238                                         entry ->
239                                             valueMap.put(entry.key, entry.value)
240                                     }
241                                     modelIdLst.add(valueMap)
242                                     logger.debug("Param: " + param.toString() + "  ---- Type is:" +
243                                             param.getClass())
244                                     }
245                             execution.setVariable("homingModelIds", modelIdLst)
246                         }
247                         if ("BRG_WAN_MAC_Address".equals(userParam?.name)) {
248                             execution.setVariable("brgWanMacAddress", userParam.value)
249                             inputMap.put("BRG_WAN_MAC_Address", userParam.value)
250                         }
251                         if ("Homing_Solution".equals(userParam?.name)) {
252                                     execution.setVariable("homingService", userParam.value)
253                                     execution.setVariable("callHoming", true)
254                                     inputMap.put("Homing_Solution", userParam.value)
255                         }
256                         if ("Orchestrator".equalsIgnoreCase(userParam?.name)) {
257                             execution.setVariable("orchestrator", userParam.value)
258                             inputMap.put("orchestrator", userParam.value)
259                         }
260                         if ("VfModuleNames".equals(userParam?.name)) {
261                             logger.debug("VfModuleNames: " + userParam.value.toString())
262                             def vfModuleNames = [:]
263                             userParam.value.each {
264                                 entry ->
265                                     String vfModuleModelInvariantUuid = null;
266                                     String vfModuleName = null;
267                                     entry.each {
268                                         param ->
269                                             if ("VfModuleModelInvariantUuid".equals(param.key)) {
270                                                 vfModuleModelInvariantUuid = param.value;
271                                             } else if ("VfModuleName".equals(param.key)) {
272                                                 vfModuleName = param.value;
273                                             }
274                                     }
275
276                                     if (vfModuleModelInvariantUuid != null && !vfModuleModelInvariantUuid.isEmpty() && vfModuleName != null && !vfModuleName.isEmpty()) {
277                                         vfModuleNames.put(vfModuleModelInvariantUuid, vfModuleName)
278                                         logger.debug("VfModuleModelInvariantUuid: " + vfModuleModelInvariantUuid + " VfModuleName: " + vfModuleName)
279                                     }
280                             }
281                             execution.setVariable("vfModuleNames", vfModuleNames)
282                         }
283                 }
284             }
285
286             if (execution.getVariable("homingService") == "") {
287                 // Set Default Homing to OOF if not set
288                 execution.setVariable("homingService", "oof")
289             }
290
291             logger.debug("User Input Parameters map: " + userParams.toString())
292             execution.setVariable("serviceInputParams", inputMap) // DOES NOT SEEM TO BE USED
293
294             logger.debug("Incoming brgWanMacAddress is: " + execution.getVariable('brgWanMacAddress'))
295
296             //For Completion Handler & Fallout Handler
297             String requestInfo =
298                     """<request-info xmlns="http://org.onap/so/infra/vnf-request/v1">
299                     <request-id>${MsoUtils.xmlEscape(requestId)}</request-id>
300                     <action>CREATE</action>
301                     <source>${MsoUtils.xmlEscape(source)}</source>
302                    </request-info>"""
303
304             execution.setVariable(Prefix + "requestInfo", requestInfo)
305
306             logger.trace("Completed preProcessRequest CreateVcpeResCustService Request ")
307
308         } catch (BpmnError e) {
309             throw e;
310
311         } catch (Exception ex) {
312             String exceptionMessage = "Bpmn error encountered in CreateVcpeResCustService flow. Unexpected from method preProcessRequest() - " + ex.getMessage()
313             exceptionUtil.buildAndThrowWorkflowException(execution, 7000, exceptionMessage)
314         }
315     }
316
317     public void sendSyncResponse(DelegateExecution execution) {
318
319         logger.trace("Inside sendSyncResponse of CreateVcpeResCustService ")
320
321         try {
322             String serviceInstanceId = execution.getVariable("serviceInstanceId")
323             String requestId = execution.getVariable("mso-request-id")
324
325             // RESTResponse (for API Handler (APIH) Reply Task)
326             String syncResponse = """{"requestReferences":{"instanceId":"${serviceInstanceId}","requestId":"${
327                 requestId
328             }"}}""".trim()
329
330             logger.debug(" sendSynchResponse: xmlSyncResponse - " + "\n" + syncResponse)
331             sendWorkflowResponse(execution, 202, syncResponse)
332
333         } catch (Exception ex) {
334             String exceptionMessage = "Bpmn error encountered in CreateVcpeResCustService flow. Unexpected from method sendSyncResponse() - " + ex.getMessage()
335             exceptionUtil.buildAndThrowWorkflowException(execution, 7000, exceptionMessage)
336         }
337     }
338
339     // *******************************
340     //
341     // *******************************
342     public void prepareDecomposeService(DelegateExecution execution) {
343
344         try {
345             logger.trace("Inside prepareDecomposeService of CreateVcpeResCustService ")
346
347             String createVcpeServiceRequest = execution.getVariable("createVcpeServiceRequest")
348
349             //serviceModelInfo JSON string will be used as-is for DoCreateServiceInstance BB
350             String serviceModelInfo = jsonUtil.getJsonValue(createVcpeServiceRequest, "requestDetails.modelInfo")
351             execution.setVariable("serviceModelInfo", serviceModelInfo)
352
353             logger.trace("Completed prepareDecomposeService of CreateVcpeResCustService ")
354         } catch (Exception ex) {
355             // try error in method block
356             String exceptionMessage = "Bpmn error encountered in CreateVcpeResCustService flow. Unexpected Error from method prepareDecomposeService() - " + ex.getMessage()
357             exceptionUtil.buildAndThrowWorkflowException(execution, 7000, exceptionMessage)
358         }
359     }
360
361     // *******************************
362     //
363     // *******************************
364     public void prepareCreateServiceInstance(DelegateExecution execution) {
365
366         try {
367             logger.trace("Inside prepareCreateServiceInstance of CreateVcpeResCustService ")
368
369             /*
370              * Service modelInfo is created in earlier step. This flow can use it as-is ... or, extract from DecompositionObject
371              *      ServiceDecomposition serviceDecomposition = execution.getVariable("serviceDecomposition")
372              *      ModelInfo modelInfo = serviceDecomposition.getModelInfo()
373              *
374              */
375             String createVcpeServiceRequest = execution.getVariable("createVcpeServiceRequest")
376 //          String serviceInputParams = jsonUtil.getJsonValue(createVcpeServiceRequest, "requestDetails.requestParameters")
377 //          execution.setVariable("serviceInputParams", serviceInputParams)
378
379
380             String serviceInstanceName = jsonUtil.getJsonValue(createVcpeServiceRequest, "requestDetails.requestInfo.instanceName")
381             execution.setVariable("serviceInstanceName", serviceInstanceName)
382
383             ServiceDecomposition serviceDecomposition = execution.getVariable("serviceDecomposition")
384             execution.setVariable("serviceDecompositionString", serviceDecomposition.toJsonStringNoRootName())
385
386             logger.trace("Completed prepareCreateServiceInstance of CreateVcpeResCustService ")
387         } catch (Exception ex) {
388             // try error in method block
389             String exceptionMessage = "Bpmn error encountered in CreateVcpeResCustService flow. Unexpected Error from method prepareCreateServiceInstance() - " + ex.getMessage()
390             exceptionUtil.buildAndThrowWorkflowException(execution, 7000, exceptionMessage)
391         }
392     }
393
394     public void postProcessServiceInstanceCreate(DelegateExecution execution) {
395         def method = getClass().getSimpleName() + '.postProcessServiceInstanceCreate(' + 'execution=' + execution.getId() + ')'
396         logger.trace('Entered ' + method)
397
398         String requestId = execution.getVariable("mso-request-id")
399         String serviceInstanceId = execution.getVariable("serviceInstanceId")
400         String serviceInstanceName = execution.getVariable("serviceInstanceName")
401
402         try {
403
404             String payload = """
405             <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:req="http://org.onap.so/requestsdb">
406             <soapenv:Header/>
407             <soapenv:Body>
408             <req:updateInfraRequest>
409                 <requestId>${MsoUtils.xmlEscape(requestId)}</requestId>
410                 <lastModifiedBy>BPEL</lastModifiedBy>
411                 <serviceInstanceId>${MsoUtils.xmlEscape(serviceInstanceId)}</serviceInstanceId>
412                 <serviceInstanceName>${MsoUtils.xmlEscape(serviceInstanceName)}</serviceInstanceName>
413             </req:updateInfraRequest>
414             </soapenv:Body>
415             </soapenv:Envelope>
416             """
417             execution.setVariable(Prefix + "setUpdateDbInstancePayload", payload)
418             logger.debug(Prefix + "setUpdateDbInstancePayload: " + payload)
419             logger.trace('Exited ' + method)
420
421         } catch (BpmnError e) {
422             throw e;
423         } catch (Exception e) {
424             logger.error(LoggingAnchor.FIVE, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(),
425                     'Caught exception in ' + method, "BPMN",
426                     ErrorCode.UnknownError.getValue(), "Exception is:\n" + e);
427             exceptionUtil.buildAndThrowWorkflowException(execution, 2000, "Internal Error - Occured in" + method)
428         }
429     }
430
431
432     public void processDecomposition(DelegateExecution execution) {
433
434         logger.trace("Inside processDecomposition() of CreateVcpeResCustService ")
435
436         try {
437
438             ServiceDecomposition serviceDecomposition = execution.getVariable("serviceDecomposition")
439
440             // VNFs
441             List<VnfResource> vnfList = serviceDecomposition.getVnfResources()
442             filterVnfs(vnfList)
443             serviceDecomposition.setVnfResources(vnfList)
444
445             execution.setVariable("vnfList", vnfList)
446             execution.setVariable("vnfListString", vnfList.toString())
447
448             String vnfModelInfoString = ""
449             if (vnfList != null && vnfList.size() > 0) {
450                 execution.setVariable(Prefix + "VNFsCount", vnfList.size())
451                 logger.debug("vnfs to create: " + vnfList.size())
452                 ModelInfo vnfModelInfo = vnfList[0].getModelInfo()
453
454                 vnfModelInfoString = vnfModelInfo.toString()
455                 String vnfModelInfoWithRoot = vnfModelInfo.toString()
456                 vnfModelInfoString = jsonUtil.getJsonValue(vnfModelInfoWithRoot, "modelInfo")
457             } else {
458                 execution.setVariable(Prefix + "VNFsCount", 0)
459                 logger.debug("no vnfs to create based upon serviceDecomposition content")
460             }
461
462             execution.setVariable("vnfModelInfo", vnfModelInfoString)
463             execution.setVariable("vnfModelInfoString", vnfModelInfoString)
464             logger.debug(" vnfModelInfoString :" + vnfModelInfoString)
465
466             logger.trace("Completed processDecomposition() of CreateVcpeResCustService ")
467         } catch (Exception ex) {
468             sendSyncError(execution)
469             String exceptionMessage = "Bpmn error encountered in CreateVcpeResCustService flow. processDecomposition() - " + ex.getMessage()
470             logger.debug(exceptionMessage)
471             exceptionUtil.buildAndThrowWorkflowException(execution, 7000, exceptionMessage)
472         }
473     }
474
475     private void filterVnfs(List<VnfResource> vnfList) {
476         if (vnfList == null) {
477             return
478         }
479
480         // remove BRG & TXC from VNF list
481
482         Iterator<VnfResource> it = vnfList.iterator()
483         while (it.hasNext()) {
484             VnfResource vr = it.next()
485
486             String role = vr.getNfRole()
487             if (role == "BRG" || role == "TunnelXConn" || role == "Tunnel XConn") {
488                 it.remove()
489             }
490         }
491     }
492
493
494     public void prepareCreateAllottedResourceTXC(DelegateExecution execution) {
495
496         try {
497             logger.trace("Inside prepareCreateAllottedResourceTXC of CreateVcpeResCustService ")
498
499             /*
500              * Service modelInfo is created in earlier step. This flow can use it as-is ... or, extract from DecompositionObject
501              *      ServiceDecomposition serviceDecomposition = execution.getVariable("serviceDecomposition")
502              *      ModelInfo modelInfo = serviceDecomposition.getModelInfo()
503              *
504              */
505             ServiceDecomposition serviceDecomposition = execution.getVariable("serviceDecomposition")
506
507             //allottedResourceModelInfo
508             //allottedResourceRole
509             //The model Info parameters are a JSON structure as defined in the Service Instantiation API.
510             //It would be sufficient to only include the service model UUID (i.e. the modelVersionId), since this BB will query the full model from the Catalog DB.
511             List<AllottedResource> allottedResources = serviceDecomposition.getAllottedResources()
512             if (allottedResources != null) {
513                 Iterator iter = allottedResources.iterator();
514                 while (iter.hasNext()) {
515                     AllottedResource allottedResource = (AllottedResource) iter.next();
516
517                     logger.debug(" getting model info for AllottedResource # :" + allottedResource.toJsonStringNoRootName())
518                     logger.debug(" allottedResource.getAllottedResourceType() :" + allottedResource.getAllottedResourceType())
519                     if ("TunnelXConn".equalsIgnoreCase(allottedResource.getAllottedResourceType()) || "Tunnel XConn".equalsIgnoreCase(allottedResource.getAllottedResourceType())) {
520                         //set create flag to true
521                         execution.setVariable("createTXCAR", true)
522                         ModelInfo allottedResourceModelInfo = allottedResource.getModelInfo()
523                         execution.setVariable("allottedResourceModelInfoTXC", allottedResourceModelInfo.toJsonStringNoRootName())
524                         execution.setVariable("allottedResourceRoleTXC", allottedResource.getAllottedResourceRole())
525                         execution.setVariable("allottedResourceTypeTXC", allottedResource.getAllottedResourceType())
526                         //After decomposition and homing BBs, there should be an allotted resource object in the decomposition that represents the TXC,
527                         //and in its homingSolution section should be found the infraServiceInstanceId (i.e. infraServiceInstanceId in TXC Allotted Resource structure) (which the Homing BB would have populated).
528                         execution.setVariable("parentServiceInstanceIdTXC", allottedResource.getHomingSolution().getServiceInstanceId())
529                     }
530                 }
531             }
532
533             //unit test only
534             String allottedResourceId = execution.getVariable("allottedResourceId")
535             execution.setVariable("allottedResourceIdTXC", allottedResourceId)
536             logger.debug("setting allottedResourceId CreateVcpeResCustService " + allottedResourceId)
537
538             logger.trace("Completed prepareCreateAllottedResourceTXC of CreateVcpeResCustService ")
539         } catch (Exception ex) {
540             // try error in method block
541             String exceptionMessage = "Bpmn error encountered in prepareCreateAllottedResourceTXC flow. Unexpected Error from method prepareCreateServiceInstance() - " + ex.getMessage()
542             exceptionUtil.buildAndThrowWorkflowException(execution, 7000, exceptionMessage)
543         }
544     }
545
546     public void prepareCreateAllottedResourceBRG(DelegateExecution execution) {
547
548         try {
549             logger.trace("Inside prepareCreateAllottedResourceBRG of CreateVcpeResCustService ")
550
551             /*
552              * Service modelInfo is created in earlier step. This flow can use it as-is ... or, extract from DecompositionObject
553              *      ServiceDecomposition serviceDecomposition = execution.getVariable("serviceDecomposition")
554              *      ModelInfo modelInfo = serviceDecomposition.getModelInfo()
555              *
556              */
557             ServiceDecomposition serviceDecomposition = execution.getVariable("serviceDecomposition")
558
559             //allottedResourceModelInfo
560             //allottedResourceRole
561             //The model Info parameters are a JSON structure as defined in the Service Instantiation API.
562             //It would be sufficient to only include the service model UUID (i.e. the modelVersionId), since this BB will query the full model from the Catalog DB.
563             List<AllottedResource> allottedResources = serviceDecomposition.getAllottedResources()
564             if (allottedResources != null) {
565                 Iterator iter = allottedResources.iterator();
566                 while (iter.hasNext()) {
567                     AllottedResource allottedResource = (AllottedResource) iter.next();
568
569                     logger.debug(" getting model info for AllottedResource # :" + allottedResource.toJsonStringNoRootName())
570                     logger.debug(" allottedResource.getAllottedResourceType() :" + allottedResource.getAllottedResourceType())
571                     if ("BRG".equalsIgnoreCase(allottedResource.getAllottedResourceType())) {
572                         //set create flag to true
573                         execution.setVariable("createBRGAR", true)
574                         ModelInfo allottedResourceModelInfo = allottedResource.getModelInfo()
575                         execution.setVariable("allottedResourceModelInfoBRG", allottedResourceModelInfo.toJsonStringNoRootName())
576                         execution.setVariable("allottedResourceRoleBRG", allottedResource.getAllottedResourceRole())
577                         execution.setVariable("allottedResourceTypeBRG", allottedResource.getAllottedResourceType())
578                         //After decomposition and homing BBs, there should be an allotted resource object in the decomposition that represents the BRG,
579                         //and in its homingSolution section should be found the infraServiceInstanceId (i.e. infraServiceInstanceId in BRG Allotted Resource structure) (which the Homing BB would have populated).
580                         execution.setVariable("parentServiceInstanceIdBRG", allottedResource.getHomingSolution().getServiceInstanceId())
581                     }
582                 }
583             }
584
585             //unit test only
586             String allottedResourceId = execution.getVariable("allottedResourceId")
587             execution.setVariable("allottedResourceIdBRG", allottedResourceId)
588             logger.debug("setting allottedResourceId CreateVcpeResCustService " + allottedResourceId)
589
590             logger.trace("Completed prepareCreateAllottedResourceBRG of CreateVcpeResCustService ")
591         } catch (Exception ex) {
592             // try error in method block
593             String exceptionMessage = "Bpmn error encountered in prepareCreateAllottedResourceBRG flow. Unexpected Error from method prepareCreateServiceInstance() - " + ex.getMessage()
594             exceptionUtil.buildAndThrowWorkflowException(execution, 7000, exceptionMessage)
595         }
596     }
597
598     // *******************************
599     //     Generate Network request Section
600     // *******************************
601     public void prepareVnfAndModulesCreate(DelegateExecution execution) {
602
603         try {
604             logger.trace("Inside prepareVnfAndModulesCreate of CreateVcpeResCustService ")
605
606             //          String disableRollback = execution.getVariable("disableRollback")
607             //          def backoutOnFailure = ""
608             //          if(disableRollback != null){
609             //              if ( disableRollback == true) {
610             //                  backoutOnFailure = "false"
611             //              } else if ( disableRollback == false) {
612             //                  backoutOnFailure = "true"
613             //              }
614             //          }
615             //failIfExists - optional
616
617             String createVcpeServiceRequest = execution.getVariable("createVcpeServiceRequest")
618             String productFamilyId = jsonUtil.getJsonValue(createVcpeServiceRequest, "requestDetails.requestInfo.productFamilyId")
619             execution.setVariable("productFamilyId", productFamilyId)
620             logger.debug("productFamilyId: " + productFamilyId)
621
622             List<VnfResource> vnfList = execution.getVariable("vnfList")
623
624             Integer vnfsCreatedCount = execution.getVariable(Prefix + "VnfsCreatedCount")
625             String vnfModelInfoString = null;
626
627             if (vnfList != null && vnfList.size() > 0) {
628                 logger.debug("getting model info for vnf # " + vnfsCreatedCount)
629                 ModelInfo vnfModelInfo1 = vnfList[0].getModelInfo()
630                 logger.debug("got 0 ")
631                 ModelInfo vnfModelInfo = vnfList[vnfsCreatedCount.intValue()].getModelInfo()
632                 vnfModelInfoString = vnfModelInfo.toString()
633             } else {
634                 //TODO: vnfList does not contain data. Need to investigate why ... . Fro VCPE use model stored
635                 vnfModelInfoString = execution.getVariable("vnfModelInfo")
636             }
637
638             logger.debug(" vnfModelInfoString :" + vnfModelInfoString)
639
640             // extract cloud configuration - if underscore "_" is present treat as vimId else it's a cloudRegion
641             String vimId = jsonUtil.getJsonValue(createVcpeServiceRequest,
642                     "requestDetails.cloudConfiguration.lcpCloudRegionId")
643             if (vimId.contains("_") && vimId.split("_").length == 2 )  {
644                 def cloudRegion = vimId.split("_")
645                 execution.setVariable("cloudOwner", cloudRegion[0])
646                 logger.debug("cloudOwner: " + cloudRegion[0])
647                 execution.setVariable("cloudRegionId", cloudRegion[1])
648                 logger.debug("cloudRegionId: " + cloudRegion[1])
649                 execution.setVariable("lcpCloudRegionId", cloudRegion[1])
650                 logger.debug("lcpCloudRegionId: " + cloudRegion[1])
651             } else {
652                 logger.debug("vimId is not present - setting cloudRegion/cloudOwner from request.")
653                 String cloudOwner = jsonUtil.getJsonValue(createVcpeServiceRequest,
654                         "requestDetails.cloudConfiguration.cloudOwner")
655                 if (!cloudOwner?.empty && cloudOwner != "")
656                 {
657                     execution.setVariable("cloudOwner", cloudOwner)
658                     logger.debug("cloudOwner: " + cloudOwner)
659                 }
660                 execution.setVariable("cloudRegionId", vimId)
661                 logger.debug("cloudRegionId: " + vimId)
662                 execution.setVariable("lcpCloudRegionId", vimId)
663                 logger.debug("lcpCloudRegionId: " + vimId)
664             }
665
666             String tenantId = jsonUtil.getJsonValue(createVcpeServiceRequest,
667                     "requestDetails.cloudConfiguration.tenantId")
668             execution.setVariable("tenantId", tenantId)
669             logger.debug("tenantId: " + tenantId)
670
671             String sdncVersion = execution.getVariable("sdncVersion")
672             logger.debug("sdncVersion: " + sdncVersion)
673
674             logger.trace("Completed prepareVnfAndModulesCreate of CreateVcpeResCustService ")
675         } catch (Exception ex) {
676             // try error in method block
677             String exceptionMessage = "Bpmn error encountered in CreateVcpeResCustService flow. Unexpected Error from method prepareVnfAndModulesCreate() - " + ex.getMessage()
678             exceptionUtil.buildAndThrowWorkflowException(execution, 7000, exceptionMessage)
679         }
680     }
681
682     // *******************************
683     //     Validate Vnf request Section -> increment count
684     // *******************************
685     public void validateVnfCreate(DelegateExecution execution) {
686
687         try {
688             logger.trace("Inside validateVnfCreate of CreateVcpeResCustService ")
689
690             Integer vnfsCreatedCount = execution.getVariable(Prefix + "VnfsCreatedCount")
691             vnfsCreatedCount++
692
693             execution.setVariable(Prefix + "VnfsCreatedCount", vnfsCreatedCount)
694
695             logger.debug(" ***** Completed validateVnfCreate of CreateVcpeResCustService ***** " + " vnf # " + vnfsCreatedCount)
696         } catch (Exception ex) {
697             // try error in method block
698             String exceptionMessage = "Bpmn error encountered in CreateVcpeResCustService flow. Unexpected Error from method validateVnfCreate() - " + ex.getMessage()
699             exceptionUtil.buildAndThrowWorkflowException(execution, 7000, exceptionMessage)
700         }
701     }
702
703     // *****************************************
704     //     Prepare Completion request Section
705     // *****************************************
706     public void postProcessResponse(DelegateExecution execution) {
707
708         logger.trace("Inside postProcessResponse of CreateVcpeResCustService ")
709
710         try {
711             String source = execution.getVariable("source")
712             String requestId = execution.getVariable("mso-request-id")
713             String serviceInstanceId = execution.getVariable("serviceInstanceId")
714
715             String msoCompletionRequest =
716                     """<aetgt:MsoCompletionRequest xmlns:aetgt="http://org.onap/so/workflow/schema/v1"
717                                     xmlns:ns="http://org.onap/so/request/types/v1">
718                             <request-info xmlns="http://org.onap/so/infra/vnf-request/v1">
719                                 <request-id>${MsoUtils.xmlEscape(requestId)}</request-id>
720                                 <action>CREATE</action>
721                                 <source>${MsoUtils.xmlEscape(source)}</source>
722                             </request-info>
723                             <status-message>Service Instance has been created successfully via macro orchestration</status-message>
724                             <serviceInstanceId>${MsoUtils.xmlEscape(serviceInstanceId)}</serviceInstanceId>
725                             <mso-bpel-name>BPMN macro create</mso-bpel-name>
726                         </aetgt:MsoCompletionRequest>"""
727
728             // Format Response
729             String xmlMsoCompletionRequest = utils.formatXml(msoCompletionRequest)
730
731             logger.debug(xmlMsoCompletionRequest)
732             execution.setVariable(Prefix + "Success", true)
733             execution.setVariable(Prefix + "CompleteMsoProcessRequest", xmlMsoCompletionRequest)
734             logger.debug(" SUCCESS flow, going to CompleteMsoProcess - " + "\n" + xmlMsoCompletionRequest)
735         } catch (BpmnError e) {
736             throw e;
737         } catch (Exception ex) {
738             // try error in method block
739             String exceptionMessage = "Bpmn error encountered in CreateVcpeResCustService flow. Unexpected Error from method postProcessResponse() - " + ex.getMessage()
740             exceptionUtil.buildAndThrowWorkflowException(execution, 7000, exceptionMessage)
741         }
742     }
743
744     public void preProcessRollback(DelegateExecution execution) {
745         logger.trace("preProcessRollback of CreateVcpeResCustService ")
746         try {
747
748             Object workflowException = execution.getVariable("WorkflowException");
749
750             if (workflowException instanceof WorkflowException) {
751                 logger.debug("Prev workflowException: " + workflowException.getErrorMessage())
752                 execution.setVariable("prevWorkflowException", workflowException);
753                 //execution.setVariable("WorkflowException", null);
754             }
755         } catch (BpmnError e) {
756             logger.debug("BPMN Error during preProcessRollback")
757         } catch (Exception ex) {
758             String msg = "Exception in preProcessRollback. " + ex.getMessage()
759             logger.debug(msg)
760         }
761         logger.trace("Exit preProcessRollback of CreateVcpeResCustService ")
762     }
763
764     public void postProcessRollback(DelegateExecution execution) {
765         logger.trace("postProcessRollback of CreateVcpeResCustService ")
766         String msg = ""
767         try {
768             Object workflowException = execution.getVariable("prevWorkflowException");
769             if (workflowException instanceof WorkflowException) {
770                 logger.debug("Setting prevException to WorkflowException: ")
771                 execution.setVariable("WorkflowException", workflowException);
772             }
773         } catch (BpmnError b) {
774             logger.debug("BPMN Error during postProcessRollback")
775             throw b;
776         } catch (Exception ex) {
777             msg = "Exception in postProcessRollback. " + ex.getMessage()
778             logger.debug(msg)
779         }
780         logger.trace("Exit postProcessRollback of CreateVcpeResCustService ")
781     }
782
783     public void prepareFalloutRequest(DelegateExecution execution) {
784
785         logger.trace("STARTED CreateVcpeResCustService prepareFalloutRequest Process ")
786
787         try {
788             WorkflowException wfex = execution.getVariable("WorkflowException")
789             logger.debug(" Incoming Workflow Exception: " + wfex.toString())
790             String requestInfo = execution.getVariable(Prefix + "requestInfo")
791             logger.debug(" Incoming Request Info: " + requestInfo)
792
793             //TODO. hmmm. there is no way to UPDATE error message.
794 //          String errorMessage = wfex.getErrorMessage()
795 //          boolean successIndicator = execution.getVariable("DCRESI_rolledBack")
796 //          if (successIndicator){
797 //              errorMessage = errorMessage + ". Rollback successful."
798 //          } else {
799 //              errorMessage = errorMessage + ". Rollback not completed."
800 //          }
801
802             String falloutRequest = exceptionUtil.processMainflowsBPMNException(execution, requestInfo)
803
804             execution.setVariable(Prefix + "falloutRequest", falloutRequest)
805
806         } catch (Exception ex) {
807             logger.debug("Error Occured in CreateVcpeResCustService prepareFalloutRequest Process " + ex.getMessage())
808             exceptionUtil.buildAndThrowWorkflowException(execution, 2500, "Internal Error - Occured in CreateVcpeResCustService prepareFalloutRequest Process")
809         }
810         logger.trace("COMPLETED CreateVcpeResCustService prepareFalloutRequest Process ")
811     }
812
813
814     public void sendSyncError(DelegateExecution execution) {
815         execution.setVariable("prefix", Prefix)
816
817         logger.trace("Inside sendSyncError() of CreateVcpeResCustService ")
818
819         try {
820             String errorMessage = ""
821             def wfe = execution.getVariable("WorkflowException")
822             if (wfe instanceof WorkflowException) {
823                 errorMessage = wfe.getErrorMessage()
824             } else {
825                 errorMessage = "Sending Sync Error."
826             }
827
828             String buildworkflowException =
829                     """<aetgt:WorkflowException xmlns:aetgt="http://org.onap/so/workflow/schema/v1">
830                     <aetgt:ErrorMessage>${MsoUtils.xmlEscape(errorMessage)}</aetgt:ErrorMessage>
831                     <aetgt:ErrorCode>7000</aetgt:ErrorCode>
832                     </aetgt:WorkflowException>"""
833
834             logger.debug(buildworkflowException)
835             sendWorkflowResponse(execution, 500, buildworkflowException)
836         } catch (Exception ex) {
837             logger.debug(" Sending Sync Error Activity Failed. " + "\n" + ex.getMessage())
838         }
839     }
840
841     public void processJavaException(DelegateExecution execution) {
842         execution.setVariable("prefix", Prefix)
843         try {
844             logger.debug("Caught a Java Exception")
845             logger.debug("Started processJavaException Method")
846             logger.debug("Variables List: " + execution.getVariables())
847             execution.setVariable(Prefix + "unexpectedError", "Caught a Java Lang Exception")
848             // Adding this line temporarily until this flows error handling gets updated
849             exceptionUtil.buildAndThrowWorkflowException(execution, 500, "Caught a Java Lang Exception")
850         } catch (BpmnError b) {
851             logger.error(LoggingAnchor.FOUR, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(),
852                     "Rethrowing MSOWorkflowException", "BPMN",
853                     ErrorCode.UnknownError.getValue());
854             throw b
855         } catch (Exception e) {
856             logger.debug("Caught Exception during processJavaException Method: " + e)
857             execution.setVariable(Prefix + "unexpectedError", "Exception in processJavaException method")
858             // Adding this line temporarily until this flows error handling gets updated
859             exceptionUtil.buildAndThrowWorkflowException(execution, 500, "Exception in processJavaException method")
860         }
861         logger.debug("Completed processJavaException Method")
862     }
863 }