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