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