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