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