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