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