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