Containerization feature of SO
[so.git] / bpmn / so-bpmn-infrastructure-flows / src / main / groovy / org / onap / so / bpmn / infrastructure / scripts / DoCreateVfModule.groovy
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP - SO
4  * ================================================================================
5  * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
6  * ================================================================================
7  * Licensed under the Apache License, Version 2.0 (the "License");
8  * you may not use this file except in compliance with the License.
9  * You may obtain a copy of the License at
10  * 
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  * 
13  * Unless required by applicable law or agreed to in writing, software
14  * distributed under the License is distributed on an "AS IS" BASIS,
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * See the License for the specific language governing permissions and
17  * limitations under the License.
18  * ============LICENSE_END=========================================================
19  */
20
21 package org.onap.so.bpmn.infrastructure.scripts
22
23 import javax.xml.parsers.DocumentBuilder
24 import javax.xml.parsers.DocumentBuilderFactory
25
26 import org.apache.commons.lang3.*
27 import org.camunda.bpm.engine.delegate.BpmnError
28 import org.camunda.bpm.engine.delegate.DelegateExecution
29 import org.json.JSONArray
30 import org.json.JSONObject
31 import org.onap.so.bpmn.common.scripts.AaiUtil
32 import org.onap.so.bpmn.common.scripts.CatalogDbUtils
33 import org.onap.so.bpmn.common.scripts.ExceptionUtil
34 import org.onap.so.bpmn.common.scripts.MsoUtils
35 import org.onap.so.bpmn.common.scripts.NetworkUtils
36 import org.onap.so.bpmn.common.scripts.SDNCAdapterUtils
37 import org.onap.so.bpmn.common.scripts.VfModuleBase
38 import org.onap.so.bpmn.core.RollbackData
39 import org.onap.so.bpmn.core.UrnPropertiesReader
40 import org.onap.so.bpmn.core.WorkflowException
41 import org.onap.so.bpmn.core.domain.CloudFlavor
42 import org.onap.so.bpmn.core.domain.VnfResource
43 import org.onap.so.bpmn.core.json.DecomposeJsonUtil
44 import org.onap.so.bpmn.core.json.JsonUtils
45 import org.onap.so.client.aai.AAIObjectType;
46 import org.onap.so.client.aai.AAIResourcesClient
47 import org.onap.so.client.aai.entities.AAIResultWrapper
48 import org.onap.so.client.aai.entities.uri.AAIUri
49 import org.onap.so.client.aai.entities.uri.AAIUriFactory;
50 import org.onap.so.logger.MessageEnum
51 import org.onap.so.logger.MsoLogger
52 import org.onap.so.rest.APIResponse
53 import org.onap.so.rest.RESTClient
54 import org.onap.so.rest.RESTConfig
55 import org.springframework.web.util.UriUtils
56 import org.w3c.dom.Document
57 import org.w3c.dom.Element
58 import org.w3c.dom.NamedNodeMap
59 import org.w3c.dom.Node
60 import org.w3c.dom.NodeList
61 import org.xml.sax.InputSource
62
63 import com.fasterxml.jackson.databind.ObjectMapper
64
65
66
67 public class DoCreateVfModule extends VfModuleBase {
68         private static final MsoLogger msoLogger = MsoLogger.getMsoLogger(MsoLogger.Catalog.BPEL, DoCreateVfModule.class);
69         
70         String Prefix="DCVFM_"
71         ExceptionUtil exceptionUtil = new ExceptionUtil()
72         JsonUtils jsonUtil = new JsonUtils()
73         SDNCAdapterUtils sdncAdapterUtils = new SDNCAdapterUtils(this)
74         CatalogDbUtils catalog = new CatalogDbUtils()
75         DecomposeJsonUtil decomposeJsonUtils = new DecomposeJsonUtil()
76
77         /**
78          * Validates the request message and sets up the workflow.
79          * @param execution the execution
80          */
81         public void preProcessRequest(DelegateExecution execution) {
82                 def method = getClass().getSimpleName() + '.preProcessRequest(' +
83                         'execution=' + execution.getId() +
84                         ')'
85                 
86                 msoLogger.trace('Entered ' + method)
87
88                 execution.setVariable('prefix', Prefix)
89                 try{
90                         def rollbackData = execution.getVariable("rollbackData")
91                         if (rollbackData == null) {
92                                 rollbackData = new RollbackData()
93                         }
94
95                         execution.setVariable("DCVFM_vnfParamsExistFlag", false)
96                         execution.setVariable("DCVFM_oamManagementV4Address", "")
97                         execution.setVariable("DCVFM_oamManagementV6Address", "")
98
99                         String request = execution.getVariable("DoCreateVfModuleRequest")
100
101                         if (request == null || request.isEmpty()) {
102                                 // Building Block-type request
103
104                                 String vfModuleModelInfo = execution.getVariable("vfModuleModelInfo")           
105                                 
106                                 def serviceModelInfo = execution.getVariable("serviceModelInfo")
107                                 msoLogger.debug("serviceModelInfo: " + serviceModelInfo)
108                                 String modelInvariantUuid = jsonUtil.getJsonValue(serviceModelInfo, "modelInvariantUuid")
109                                 msoLogger.debug("modelInvariantUuid: " + modelInvariantUuid)
110                                 
111                                 def vnfModelInfo = execution.getVariable("vnfModelInfo")
112
113                                 //tenantId
114                                 def tenantId = execution.getVariable("tenantId")
115                                 execution.setVariable("DCVFM_tenantId", tenantId)
116                                 rollbackData.put("VFMODULE", "tenantid", tenantId)
117                                 //volumeGroupId
118                                 def volumeGroupId = execution.getVariable("volumeGroupId")
119                                 execution.setVariable("DCVFM_volumeGroupId", volumeGroupId)
120                                 //volumeGroupName
121                                 def volumeGroupName = execution.getVariable("volumeGroupName")
122                                 execution.setVariable("DCVFM_volumeGroupName", volumeGroupName)
123                                 //cloudSiteId
124                                 def cloudSiteId = execution.getVariable("lcpCloudRegionId")
125                                 execution.setVariable("DCVFM_cloudSiteId", cloudSiteId)
126                                 rollbackData.put("VFMODULE", "aiccloudregion", cloudSiteId)
127                                 msoLogger.debug("cloudSiteId: " + cloudSiteId)
128                                 //vnfType
129                                 def vnfType = execution.getVariable("vnfType")
130                                 execution.setVariable("DCVFM_vnfType", vnfType)
131                                 rollbackData.put("VFMODULE", "vnftype", vnfType)
132                                 msoLogger.debug("vnfType: " + vnfType)
133                                 //vnfName
134                                 def vnfName = execution.getVariable("vnfName")
135                                 execution.setVariable("DCVFM_vnfName", vnfName)
136                                 rollbackData.put("VFMODULE", "vnfname", vnfName)
137                                 msoLogger.debug("vnfName: " + vnfName)
138                                 //vnfId
139                                 def vnfId = execution.getVariable("vnfId")
140                                 execution.setVariable("DCVFM_vnfId", vnfId)
141                                 rollbackData.put("VFMODULE", "vnfid", vnfId)
142                                 msoLogger.debug("vnfId: " + vnfId)
143                                 //vfModuleName
144                                 def vfModuleName = execution.getVariable("vfModuleName")
145                                 execution.setVariable("DCVFM_vfModuleName", vfModuleName)
146                                 rollbackData.put("VFMODULE", "vfmodulename", vfModuleName)
147                                 msoLogger.debug("vfModuleName: " + vfModuleName)
148                                 //vfModuleModelName
149                                 def vfModuleModelName = jsonUtil.getJsonValue(vfModuleModelInfo, "modelName")
150                                 execution.setVariable("DCVFM_vfModuleModelName", vfModuleModelName)
151                                 rollbackData.put("VFMODULE", "vfmodulemodelname", vfModuleModelName)
152                                 msoLogger.debug("vfModuleModelName: " + vfModuleModelName)
153                                 //modelCustomizationUuid
154                                 def modelCustomizationUuid = jsonUtil.getJsonValue(vfModuleModelInfo, "modelCustomizationUuid")
155                                 execution.setVariable("DCVFM_modelCustomizationUuid", modelCustomizationUuid)
156                                 rollbackData.put("VFMODULE", "modelcustomizationuuid", modelCustomizationUuid)
157                                 msoLogger.debug("modelCustomizationUuid: " + modelCustomizationUuid)
158                                 //vfModuleId
159                                 def vfModuleId = execution.getVariable("vfModuleId")
160                                 execution.setVariable("DCVFM_vfModuleId", vfModuleId)
161                                 msoLogger.debug("vfModuleId: " + vfModuleId)
162                                 def requestId = execution.getVariable("msoRequestId")
163                                 execution.setVariable("DCVFM_requestId", requestId)
164                                 msoLogger.debug("requestId: " + requestId)
165                                 rollbackData.put("VFMODULE", "msorequestid", requestId)
166                                 // Set mso-request-id to request-id for VNF Adapter interface
167                                 execution.setVariable("mso-request-id", requestId)
168                                 //serviceId
169                                 def serviceId = execution.getVariable("serviceId")
170                                 execution.setVariable("DCVFM_serviceId", serviceId)
171                                 msoLogger.debug("serviceId: " + serviceId)
172                                 //serviceInstanceId
173                                 def serviceInstanceId = execution.getVariable("serviceInstanceId")
174                                 execution.setVariable("DCVFM_serviceInstanceId", serviceInstanceId)
175                                 rollbackData.put("VFMODULE", "serviceInstanceId", serviceInstanceId)
176                                 msoLogger.debug("serviceInstanceId: " + serviceInstanceId)
177                                 //flavorList
178                                 ArrayList<CloudFlavor> flavorList = execution.getVariable(cloudSiteId + "_flavorList")
179                                 if (flavorList != null) {
180                                         execution.setVariable("DCVFM_flavorList", flavorList)
181                                         logDebug("flavorList is: " + flavorList, isDebugLogEnabled)
182                                 }
183                                 //source - HARDCODED
184                                 def source = "VID"
185                                 execution.setVariable("DCVFM_source", source)
186                                 rollbackData.put("VFMODULE", "source", source)
187                                 msoLogger.debug("source: " + source)
188                                 //backoutOnFailure
189                                 def disableRollback = execution.getVariable("disableRollback")
190                                 def backoutOnFailure = true
191                                 if (disableRollback != null && disableRollback == true) {
192                                         backoutOnFailure = false
193                                 }
194                                 execution.setVariable("DCVFM_backoutOnFailure", backoutOnFailure)
195                                 msoLogger.debug("backoutOnFailure: " + backoutOnFailure)
196                                 //isBaseVfModule
197                                 def isBaseVfModule = execution.getVariable("isBaseVfModule")
198                                 execution.setVariable("DCVFM_isBaseVfModule", isBaseVfModule)
199                                 msoLogger.debug("isBaseVfModule: " + isBaseVfModule)
200                                 //asdcServiceModelVersion
201                                 def asdcServiceModelVersion = execution.getVariable("asdcServiceModelVersion")
202                                 execution.setVariable("DCVFM_asdcServiceModelVersion", asdcServiceModelVersion)
203                                 msoLogger.debug("asdcServiceModelVersion: " + asdcServiceModelVersion)
204                                 //personaModelId
205                                 execution.setVariable("DCVFM_personaModelId", jsonUtil.getJsonValue(vfModuleModelInfo, "modelInvariantUuid"))                   
206                                 //personaModelVersion
207                                 execution.setVariable("DCVFM_personaModelVersion", jsonUtil.getJsonValue(vfModuleModelInfo, "modelUuid"))
208                                 //vfModuleLabel
209                                 def vfModuleLabel = execution.getVariable("vfModuleLabel")
210                                 if (vfModuleLabel != null) {
211                                         execution.setVariable("DCVFM_vfModuleLabel", vfModuleLabel)
212                                         msoLogger.debug("vfModuleLabel: " + vfModuleLabel)
213                                 }
214                                 //Get or Generate UUID
215                                 String uuid = execution.getVariable("DCVFM_uuid")
216                                 if(uuid == null){
217                                         uuid = UUID.randomUUID()
218                                         msoLogger.debug("Generated messageId (UUID) is: " + uuid)
219                                 }else{
220                                         msoLogger.debug("Found messageId (UUID) is: " + uuid)
221                                 }
222                                 //isVidRequest
223                                 String isVidRequest = execution.getVariable("isVidRequest")
224                                 // default to true
225                                 if (isVidRequest == null || isVidRequest.isEmpty()) {
226                                         execution.setVariable("isVidRequest", "true")
227                                 }
228                                 //globalSubscriberId
229                                 String globalSubscriberId = execution.getVariable("globalSubscriberId")
230                                 execution.setVariable("DCVFM_globalSubscriberId", globalSubscriberId)
231                                 msoLogger.debug("globalSubsrciberId: " + globalSubscriberId)                            
232                                 Map<String,String> vfModuleInputParams = execution.getVariable("vfModuleInputParams")
233                                 if (vfModuleInputParams != null) {
234                                         execution.setVariable("DCVFM_vnfParamsMap", vfModuleInputParams)
235                                         execution.setVariable("DCVFM_vnfParamsExistFlag", true)
236                                 }
237                                 //usePreload
238                                 def usePreload = execution.getVariable("usePreload")
239                                 execution.setVariable("DCVFM_usePreload", usePreload)
240                                 msoLogger.debug("usePreload: " + usePreload)
241                                 //aLaCarte
242                                 def aLaCarte = execution.getVariable("aLaCarte")                                
243                                 execution.setVariable("DCVFM_aLaCarte", aLaCarte)
244                                 msoLogger.debug("aLaCarte: " + aLaCarte)
245                                 
246                                 //get workload and environment context from parent SI
247                                 String environmentContext = ""
248                                 String workloadContext =""
249                                 String serviceType =""
250                                 
251                                 try{
252                                         String json = catalog.getServiceResourcesByServiceModelInvariantUuidString(execution,modelInvariantUuid )
253                                         serviceType = jsonUtil.getJsonValue(json, "serviceResources.serviceType")
254                                 }catch(BpmnError e){
255                                         throw e
256                                 } catch (Exception ex){
257                                         String msg = "Exception in preProcessRequest " + ex.getMessage()
258                                         msoLogger.debug(msg)
259                                         exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg)
260                                 }
261                                 
262                                 try{
263                                         AAIUri serviceInstanceURI = AAIUriFactory.create(AAIObjectType.SERVICE_INSTANCE, globalSubscriberId,serviceType,serviceInstanceId)
264                                         AAIResourcesClient aaiRC = new AAIResourcesClient()
265                                         AAIResultWrapper aaiRW = aaiRC.get(serviceInstanceURI)
266                                         Map<String, Object> aaiJson = aaiRW.asMap()
267                                         environmentContext = aaiJson.getOrDefault("environment-context","")
268                                         workloadContext = aaiJson.getOrDefault("workload-context","")
269                                         
270                                 }catch (Exception ex) {
271                                         msoLogger.debug("Error retreiving parent service instance information")
272                                 }
273                                 
274                                 execution.setVariable("DCVFM_environmentContext",environmentContext)
275                                 execution.setVariable("DCVFM_workloadContext",workloadContext)
276                                                                                           
277                         }
278                         else {
279                                 // The info is inside the request - DEAD CODE
280                                 msoLogger.debug("DoCreateVfModule request: " + request)
281
282                                 //tenantId
283                                 def tenantId = ""
284                                 if (utils.nodeExists(request, "tenant-id")) {
285                                         tenantId = utils.getNodeText(request, "tenant-id")
286                                 }
287                                 execution.setVariable("DCVFM_tenantId", tenantId)
288                                 rollbackData.put("VFMODULE", "tenantid", tenantId)
289                                 //volumeGroupId
290                                 def volumeGroupId = ""
291                                 if (utils.nodeExists(request, "volume-group-id")) {
292                                         volumeGroupId = utils.getNodeText(request, "volume-group-id")
293                                 }
294                                 execution.setVariable("DCVFM_volumeGroupId", volumeGroupId)
295                                 //volumeGroupId
296                                 def volumeGroupName = ""
297                                 if (utils.nodeExists(request, "volume-group-name")) {
298                                         volumeGroupName = utils.getNodeText(request, "volume-group-name")
299                                 }
300                                 execution.setVariable("DCVFM_volumeGroupName", volumeGroupName)
301                                 //cloudSiteId
302                                 def cloudSiteId = ""
303                                 if (utils.nodeExists(request, "aic-cloud-region")) {
304                                         cloudSiteId = utils.getNodeText(request, "aic-cloud-region")
305                                 }
306                                 execution.setVariable("DCVFM_cloudSiteId", cloudSiteId)
307                                 rollbackData.put("VFMODULE", "aiccloudregion", cloudSiteId)
308                                 msoLogger.debug("cloudSiteId: " + cloudSiteId)
309                                 //vnfType
310                                 def vnfType = ""
311                                 if (utils.nodeExists(request, "vnf-type")) {
312                                         vnfType = utils.getNodeText(request, "vnf-type")
313                                 }
314                                 execution.setVariable("DCVFM_vnfType", vnfType)
315                                 rollbackData.put("VFMODULE", "vnftype", vnfType)
316                                 msoLogger.debug("vnfType: " + vnfType)
317                                 //vnfName
318                                 def vnfName = ""
319                                 if (utils.nodeExists(request, "vnf-name")) {
320                                         vnfName = utils.getNodeText(request, "vnf-name")
321                                 }
322                                 execution.setVariable("DCVFM_vnfName", vnfName)
323                                 rollbackData.put("VFMODULE", "vnfname", vnfName)
324                                 msoLogger.debug("vnfName: " + vnfName)
325                                 //vnfId
326                                 def vnfId = ""
327                                 if (utils.nodeExists(request, "vnf-id")) {
328                                         vnfId = utils.getNodeText(request, "vnf-id")
329                                 }
330                                 execution.setVariable("DCVFM_vnfId", vnfId)
331                                 rollbackData.put("VFMODULE", "vnfid", vnfId)
332                                 msoLogger.debug("vnfId: " + vnfId)
333                                 //vfModuleName
334                                 def vfModuleName = ""
335                                 if (utils.nodeExists(request, "vf-module-name")) {
336                                         vfModuleName = utils.getNodeText(request, "vf-module-name")
337                                 }
338                                 execution.setVariable("DCVFM_vfModuleName", vfModuleName)
339                                 rollbackData.put("VFMODULE", "vfmodulename", vfModuleName)
340                                 msoLogger.debug("vfModuleName: " + vfModuleName)
341                                 //vfModuleModelName
342                                 def vfModuleModelName = ""
343                                 if (utils.nodeExists(request, "vf-module-model-name")) {
344                                         vfModuleModelName = utils.getNodeText(request, "vf-module-model-name")
345                                 }
346                                 execution.setVariable("DCVFM_vfModuleModelName", vfModuleModelName)
347                                 rollbackData.put("VFMODULE", "vfmodulemodelname", vfModuleModelName)
348                                 msoLogger.debug("vfModuleModelName: " + vfModuleModelName)
349                                 //modelCustomizationUuid
350                                 def modelCustomizationUuid = ""
351                                 if (utils.nodeExists(request, "model-customization-id")) {
352                                         modelCustomizationUuid = utils.getNodeText(request, "model-customization-id")
353                                 }
354                                 execution.setVariable("DCVFM_modelCustomizationUuid", modelCustomizationUuid)
355                                 rollbackData.put("VFMODULE", "modelcustomizationuuid", modelCustomizationUuid)
356                                 msoLogger.debug("modelCustomizationUuid: " + modelCustomizationUuid)
357                                 //vfModuleId
358                                 def vfModuleId = ""
359                                 if (utils.nodeExists(request, "vf-module-id")) {
360                                         vfModuleId = utils.getNodeText(request, "vf-module-id")
361                                 }
362                                 execution.setVariable("DCVFM_vfModuleId", vfModuleId)
363                                 msoLogger.debug("vfModuleId: " + vfModuleId)
364                                 def requestId = ""
365                                 if (utils.nodeExists(request, "request-id")) {
366                                         requestId = utils.getNodeText(request, "request-id")
367                                 }
368                                 execution.setVariable("DCVFM_requestId", requestId)
369                                 msoLogger.debug("requestId: " + requestId)
370                                 //serviceId
371                                 def serviceId = ""
372                                 if (utils.nodeExists(request, "service-id")) {
373                                         serviceId = utils.getNodeText(request, "service-id")
374                                 }
375                                 execution.setVariable("DCVFM_serviceId", serviceId)
376                                 msoLogger.debug("serviceId: " + serviceId)
377                                 //serviceInstanceId
378                                 def serviceInstanceId = ""
379                                 if (utils.nodeExists(request, "service-instance-id")) {
380                                         serviceInstanceId = utils.getNodeText(request, "service-instance-id")
381                                 }
382                                 execution.setVariable("DCVFM_serviceInstanceId", serviceInstanceId)
383                                 rollbackData.put("VFMODULE", "serviceInstanceId", serviceInstanceId)
384                                 msoLogger.debug("serviceInstanceId: " + serviceInstanceId)
385                                 //source
386                                 def source = ""
387                                 if (utils.nodeExists(request, "source")) {
388                                         source = utils.getNodeText(request, "source")
389                                 }
390                                 execution.setVariable("DCVFM_source", source)
391                                 rollbackData.put("VFMODULE", "source", source)
392                                 msoLogger.debug("source: " + source)
393                                 //backoutOnFailure
394                                 NetworkUtils networkUtils = new NetworkUtils()
395                                 def backoutOnFailure = networkUtils.isRollbackEnabled(execution,request)
396                                 execution.setVariable("DCVFM_backoutOnFailure", backoutOnFailure)
397                                 msoLogger.debug("backoutOnFailure: " + backoutOnFailure)
398                                 //isBaseVfModule
399                                 def isBaseVfModule = "false"
400                                 if (utils.nodeExists(request, "is-base-vf-module")) {
401                                         isBaseVfModule = utils.getNodeText(request, "is-base-vf-module")
402                                 }
403                                 execution.setVariable("DCVFM_isBaseVfModule", isBaseVfModule)
404                                 msoLogger.debug("isBaseVfModule: " + isBaseVfModule)                            
405                                 //asdcServiceModelVersion
406                                 def asdcServiceModelVersion = ""
407                                 if (utils.nodeExists(request, "asdc-service-model-version")) {
408                                         asdcServiceModelVersion = utils.getNodeText(request, "asdc-service-model-version")
409                                 }
410                                 execution.setVariable("DCVFM_asdcServiceModelVersion", asdcServiceModelVersion)
411                                 msoLogger.debug("asdcServiceModelVersion: " + asdcServiceModelVersion)
412
413                                 //personaModelId
414                                 def personaModelId = ""
415                                 if (utils.nodeExists(request, "persona-model-id")) {
416                                         personaModelId = utils.getNodeText(request, "persona-model-id")
417                                 }
418                                 execution.setVariable("DCVFM_personaModelId", personaModelId)
419                                 msoLogger.debug("personaModelId: " + personaModelId)
420
421                                 //personaModelVersion
422                                 def personaModelVersion = ""
423                                 if (utils.nodeExists(request, "persona-model-version")) {
424                                         personaModelVersion = utils.getNodeText(request, "persona-model-version")
425                                 }
426                                 execution.setVariable("DCVFM_personaModelVersion", personaModelVersion)
427                                 msoLogger.debug("personaModelVersion: " + personaModelVersion)
428
429                                 // Process the parameters
430
431                                                 String vnfParamsChildNodes = utils.getChildNodes(request, "vnf-params")
432                                                 if(vnfParamsChildNodes == null || vnfParamsChildNodes.length() < 1){
433                                                                 msoLogger.debug("Request contains NO VNF Params")
434                                                 }else{
435                                                                 msoLogger.debug("Request does contain VNF Params")
436                                                                 execution.setVariable("DCVFM_vnfParamsExistFlag", true)
437
438                                                                 InputSource xmlSource = new InputSource(new StringReader(request));
439                                                                 DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
440                                                                 docFactory.setNamespaceAware(true)
441                                                                 DocumentBuilder docBuilder = docFactory.newDocumentBuilder()
442                                                                 Document xml = docBuilder.parse(xmlSource)
443                                                                 //Get params, build map
444                                                                 Map<String, String> paramsMap = new HashMap<String, String>()
445                                                                 NodeList paramsList = xml.getElementsByTagNameNS("*", "param")
446
447                                                                 for (int z = 0; z < paramsList.getLength(); z++) {
448                                                                         Node node = paramsList.item(z)
449                                                                         String paramValue = node.getTextContent()
450                                                                         NamedNodeMap e = node.getAttributes()
451                                                                         String paramName = e.getNamedItem("name").getTextContent()
452                                                                         paramsMap.put(paramName, paramValue)
453                                                                 }
454                                                                 execution.setVariable("DCVFM_vnfParamsMap", paramsMap)
455                                                         }
456                         }
457
458                         //Get or Generate UUID
459                         String uuid = execution.getVariable("DCVFM_uuid")
460                         if(uuid == null){
461                                 uuid = UUID.randomUUID()
462                                 msoLogger.debug("Generated messageId (UUID) is: " + uuid)
463                         }else{
464                                 msoLogger.debug("Found messageId (UUID) is: " + uuid)
465                         }
466                         // Get sdncVersion, default to empty
467                         String sdncVersion = execution.getVariable("sdncVersion")
468                         if (sdncVersion == null) {
469                                 sdncVersion = ""
470                         }
471                         msoLogger.debug("sdncVersion: " + sdncVersion)
472                         execution.setVariable("DCVFM_sdncVersion", sdncVersion)
473                         
474                         execution.setVariable("DCVFM_uuid", uuid)
475                         execution.setVariable("DCVFM_baseVfModuleId", "")
476                         execution.setVariable("DCVFM_baseVfModuleHeatStackId", "")
477                         execution.setVariable("DCVFM_heatStackId", "")
478                         execution.setVariable("DCVFM_contrailServiceInstanceFqdn", "")
479                         execution.setVariable("DCVFM_volumeGroupStackId", "")
480                         execution.setVariable("DCVFM_cloudRegionForVolume", "")
481                         execution.setVariable("DCVFM_contrailNetworkPolicyFqdnList", "")
482                         execution.setVariable("DCVFM_vnfTypeToQuery", "generic-vnf")
483                         rollbackData.put("VFMODULE", "rollbackPrepareUpdateVfModule", "false")
484                         rollbackData.put("VFMODULE", "rollbackUpdateAAIVfModule", "false")
485                         rollbackData.put("VFMODULE", "rollbackVnfAdapterCreate", "false")
486                         rollbackData.put("VFMODULE", "rollbackSDNCRequestActivate", "false")
487                         rollbackData.put("VFMODULE", "rollbackSDNCRequestAssign", "false")
488                         rollbackData.put("VFMODULE", "rollbackCreateAAIVfModule", "false")
489                         rollbackData.put("VFMODULE", "rollbackCreateNetworkPoliciesAAI", "false")
490                         rollbackData.put("VFMODULE", "rollbackUpdateVnfAAI", "false")
491                         rollbackData.put("VFMODULE", "heatstackid", "")
492
493                         String sdncCallbackUrl = (String) UrnPropertiesReader.getVariable("mso.workflow.sdncadapter.callback",execution)
494                                 if (sdncCallbackUrl == null || sdncCallbackUrl.trim().isEmpty()) {
495                                         def msg = 'Required variable \'mso.workflow.sdncadapter.callback\' is missing'
496                                         msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, msg, "BPMN", MsoLogger.getServiceName(),MsoLogger.ErrorCode.UnknownError, msg);
497
498                                         exceptionUtil.buildAndThrowWorkflowException(execution, 2000, msg)
499                                 }
500                                 execution.setVariable("DCVFM_sdncCallbackUrl", sdncCallbackUrl)
501                             msoLogger.debug("SDNC Callback URL is: " + sdncCallbackUrl)
502
503
504                         execution.setVariable("rollbackData", rollbackData)
505                 }catch(BpmnError b){
506                         throw b
507                 }catch(Exception e){
508                         exceptionUtil.buildAndThrowWorkflowException(execution, 2000, "Internal Error encountered in PreProcess method!")
509                 }
510
511                 msoLogger.trace('Exited ' + method)
512         }
513
514         /**
515          * Validates a workflow response.
516          * @param execution the execution
517          * @param responseVar the execution variable in which the response is stored
518          * @param responseCodeVar the execution variable in which the response code is stored
519          * @param errorResponseVar the execution variable in which the error response is stored
520          */
521         public void validateWorkflowResponse(DelegateExecution execution, String responseVar,
522                         String responseCodeVar, String errorResponseVar) {
523                 SDNCAdapterUtils sdncAdapterUtils = new SDNCAdapterUtils(this)
524                 sdncAdapterUtils.validateSDNCResponse(execution, responseVar, responseCodeVar, errorResponseVar)
525         }
526
527
528         /**
529          * Sends the empty, synchronous response back to the API Handler.
530          * @param execution the execution
531          */
532         public void sendResponse(DelegateExecution execution) {
533                 def method = getClass().getSimpleName() + '.sendResponse(' +
534                         'execution=' + execution.getId() +
535                         ')'
536                 
537                 msoLogger.trace('Entered ' + method)
538
539                 try {
540                         sendWorkflowResponse(execution, 200, "")
541                         msoLogger.trace('Exited ' + method)
542                 } catch (BpmnError e) {
543                         throw e;
544                 } catch (Exception e) {
545                         msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, 'Caught exception in ' + method, "BPMN", MsoLogger.getServiceName(),MsoLogger.ErrorCode.UnknownError, "Exception is:\n" + e);
546                         
547                         exceptionUtil.buildAndThrowWorkflowException(execution, 1002, 'Internal Error')
548                 }
549         }
550
551         /**
552          * Using the received vnfId and vfModuleId, query AAI to get the corresponding VNF info.
553          * A 200 response is expected with the VNF info in the response body. Will find out the base module info
554          * and existing VNF's name for add-on modules
555          *
556          * @param execution The flow's execution instance.
557          */
558         public void postProcessCreateAAIVfModule(DelegateExecution execution) {
559                 def method = getClass().getSimpleName() + '.getVfModule(' +
560                         'execution=' + execution.getId() +
561                         ')'
562                 
563                 msoLogger.trace('Entered ' + method)
564
565                 try {
566                         def createResponse = execution.getVariable('DCVFM_createVfModuleResponse')
567                         msoLogger.debug("createVfModule Response: " + createResponse)
568
569                         def rollbackData = execution.getVariable("rollbackData")
570                         String vnfName = utils.getNodeText(createResponse, 'vnf-name')
571                         if (vnfName != null) {
572                                 execution.setVariable('DCVFM_vnfName', vnfName)
573                                 msoLogger.debug("vnfName retrieved from AAI is: " + vnfName)
574                                 rollbackData.put("VFMODULE", "vnfname", vnfName)
575                         }
576                         String vnfId = utils.getNodeText(createResponse, 'vnf-id')
577                         execution.setVariable('DCVFM_vnfId', vnfId)
578                         msoLogger.debug("vnfId is: " + vnfId)
579                         String vfModuleId = utils.getNodeText(createResponse, 'vf-module-id')
580                         execution.setVariable('DCVFM_vfModuleId', vfModuleId)
581                         msoLogger.debug("vfModuleId is: " + vfModuleId)
582                         String vfModuleIndex= utils.getNodeText(createResponse, 'vf-module-index')
583                         execution.setVariable('DCVFM_vfModuleIndex', vfModuleIndex)
584                         msoLogger.debug("vfModuleIndex is: " + vfModuleIndex)
585                         rollbackData.put("VFMODULE", "vnfid", vnfId)
586                         rollbackData.put("VFMODULE", "vfmoduleid", vfModuleId)
587                         rollbackData.put("VFMODULE", "rollbackCreateAAIVfModule", "true")
588                         rollbackData.put("VFMODULE", "rollbackPrepareUpdateVfModule", "true")
589                         execution.setVariable("rollbackData", rollbackData)
590                 } catch (Exception ex) {
591                                 ex.printStackTrace()
592                                 msoLogger.debug('Exception occurred while postProcessing CreateAAIVfModule request:' + ex.getMessage())
593                                 exceptionUtil.buildAndThrowWorkflowException(execution, 1002, 'Bad response from CreateAAIVfModule' + ex.getMessage())
594                 }
595                 msoLogger.trace('Exited ' + method)
596         }
597
598
599         /**
600          * Using the received vnfId and vfModuleId, query AAI to get the corresponding VNF info.
601          * A 200 response is expected with the VNF info in the response body. Will find out the base module info.
602          *
603          * @param execution The flow's execution instance.
604          */
605         public void queryAAIVfModule(DelegateExecution execution) {
606                 
607                 def method = getClass().getSimpleName() + '.getVfModule(' +
608                         'execution=' + execution.getId() +
609                         ')'
610                 msoLogger.trace('Entered ' + method)
611
612                 try {
613                         def vnfId = execution.getVariable('DCVFM_vnfId')
614                         def vfModuleId = execution.getVariable('DCVFM_vfModuleId')
615
616                         AaiUtil aaiUriUtil = new AaiUtil(this)
617                         String  aai_uri = aaiUriUtil.getNetworkGenericVnfUri(execution)
618                         msoLogger.debug('AAI URI is: ' + aai_uri)
619
620                         String endPoint = UrnPropertiesReader.getVariable("aai.endpoint", execution) + "${aai_uri}/" + UriUtils.encode(vnfId, "UTF-8") + "?depth=1"
621
622                         try {
623                                 RESTConfig config = new RESTConfig(endPoint);
624                                 def responseData = ''
625                                 def aaiRequestId = UUID.randomUUID().toString()
626                                 RESTClient client = new RESTClient(config).
627                                         addHeader('X-TransactionId', aaiRequestId).
628                                         addHeader('X-FromAppId', 'MSO').
629                                         addHeader('Content-Type', 'application/xml').
630                                         addHeader('Accept','application/xml');
631                                 msoLogger.debug('sending GET to AAI endpoint \'' + endPoint + '\'')
632                                 APIResponse response = client.httpGet()
633
634                                 responseData = response.getResponseBodyAsString()
635                                 if (responseData != null) {
636                                         msoLogger.debug("Received generic VNF data: " + responseData)
637
638                                 }
639
640                                 execution.setVariable('DCVFM_queryAAIVfModuleResponseCode', response.getStatusCode())
641                                 execution.setVariable('DCVFM_queryAAIVfModuleResponse', responseData)
642                                 msoLogger.debug('Response code:' + response.getStatusCode())
643                                 msoLogger.debug('Response:' + System.lineSeparator() + responseData)
644                                 if (response.getStatusCode() == 200) {
645                                         // Parse the VNF record from A&AI to find base module info
646                                         msoLogger.debug('Parsing the VNF data to find base module info')
647                                         if (responseData != null) {
648                                                 def vfModulesText = utils.getNodeXml(responseData, "vf-modules")
649                                                 def xmlVfModules= new XmlSlurper().parseText(vfModulesText)
650                                                 def vfModules = xmlVfModules.'**'.findAll {it.name() == "vf-module"}
651                                                 int vfModulesSize = 0
652                                                 for (i in 0..vfModules.size()-1) {
653                                                         def vfModuleXml = groovy.xml.XmlUtil.serialize(vfModules[i])
654                                                         def isBaseVfModule = utils.getNodeText(vfModuleXml, "is-base-vf-module")
655
656                                                         if (isBaseVfModule == "true") {
657                                                             String baseModuleId = utils.getNodeText(vfModuleXml, "vf-module-id")
658                                                             execution.setVariable("DCVFM_baseVfModuleId", baseModuleId)
659                                                             msoLogger.debug('Received baseVfModuleId: ' + baseModuleId)
660                                                             String baseModuleHeatStackId = utils.getNodeText(vfModuleXml, "heat-stack-id")
661                                                             execution.setVariable("DCVFM_baseVfModuleHeatStackId", baseModuleHeatStackId)
662                                                             msoLogger.debug('Received baseVfModuleHeatStackId: ' + baseModuleHeatStackId)
663                                                         }
664                                                 }
665                                         }
666                                 }
667                         } catch (Exception ex) {
668                                 ex.printStackTrace()
669                                 msoLogger.debug('Exception occurred while executing AAI GET:' + ex.getMessage())
670                                 exceptionUtil.buildAndThrowWorkflowException(execution, 1002, 'AAI GET Failed:' + ex.getMessage())
671                         }
672                         msoLogger.trace('Exited ' + method)
673                 } catch (BpmnError e) {
674                         throw e;
675                 } catch (Exception e) {
676                         msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, 'Caught exception in ' + method, "BPMN", MsoLogger.getServiceName(),MsoLogger.ErrorCode.UnknownError, "Exception is:\n" + e);
677                         exceptionUtil.buildAndThrowWorkflowException(execution, 1002, 'Error in queryAAIVfModule(): ' + e.getMessage())
678                 }
679         }
680         
681         /**
682          * Using the vnfId and vfModuleName provided in the inputs, 
683          * query AAI to get the corresponding VF Module info.
684          * A 200 response is expected with the VF Module info in the response body, 
685          * or a 404 response if the module does not exist yet. Will determine VF Module's 
686          * orchestration status if one exists
687          *
688          * @param execution The flow's execution instance.
689          */
690         public void queryAAIVfModuleForStatus(DelegateExecution execution) {
691                 
692                 def method = getClass().getSimpleName() + '.queryAAIVfModuleForStatus(' +
693                         'execution=' + execution.getId() +
694                         ')'
695                 msoLogger.trace('Entered ' + method)
696                 
697                 execution.setVariable('DCVFM_orchestrationStatus', '')
698
699                 try {
700                         def vnfId = execution.getVariable('DCVFM_vnfId')
701                         def vfModuleName = execution.getVariable('DCVFM_vfModuleName')
702
703                         AaiUtil aaiUriUtil = new AaiUtil(this)
704                         String  aai_uri = aaiUriUtil.getNetworkGenericVnfUri(execution)
705                         msoLogger.debug('AAI URI is: ' + aai_uri)
706
707                         String endPoint = UrnPropertiesReader.getVariable("aai.endpoint", execution) + "${aai_uri}/" + UriUtils.encode(vnfId, "UTF-8") +
708                                         "/vf-modules/vf-module?vf-module-name=" + UriUtils.encode(vfModuleName, "UTF-8")
709                         msoLogger.debug("AAI endPoint: " + endPoint)
710
711                         try {
712                                 RESTConfig config = new RESTConfig(endPoint);
713                                 def responseData = ''
714                                 def aaiRequestId = UUID.randomUUID().toString()
715                                 RESTClient client = new RESTClient(config).
716                                         addHeader('X-TransactionId', aaiRequestId).
717                                         addHeader('X-FromAppId', 'MSO').
718                                         addHeader('Content-Type', 'application/xml').
719                                         addHeader('Accept','application/xml');
720                                 msoLogger.debug('sending GET to AAI endpoint \'' + endPoint + '\'')
721                                 APIResponse response = client.httpGet()
722                                 msoLogger.debug("createVfModule - invoking httpGet() to AAI")
723
724                                 responseData = response.getResponseBodyAsString()
725                                 if (responseData != null) {
726                                         msoLogger.debug("Received generic VNF data: " + responseData)
727
728                                 }
729
730                                 execution.setVariable('DCVFM_queryAAIVfModuleForStatusResponseCode', response.getStatusCode())
731                                 execution.setVariable('DCVFM_queryAAIVfModuleForStatusResponse', responseData)
732                                 msoLogger.debug('Response code:' + response.getStatusCode())
733                                 msoLogger.debug('Response:' + System.lineSeparator() + responseData)
734                                 // Retrieve VF Module info and its orchestration status; if not found, do nothing
735                                 if (response.getStatusCode() == 200) {
736                                         // Parse the VNF record from A&AI to find base module info
737                                         msoLogger.debug('Parsing the VNF data to find orchestration status')
738                                         if (responseData != null) {
739                                                 def vfModuleText = utils.getNodeXml(responseData, "vf-module")
740                                                 //def xmlVfModule= new XmlSlurper().parseText(vfModuleText)
741                                                 def orchestrationStatus = utils.getNodeText(vfModuleText, "orchestration-status")
742                                                 execution.setVariable("DCVFM_orchestrationStatus", orchestrationStatus)
743                                                 // Also retrieve vfModuleId
744                                                 def vfModuleId = utils.getNodeText(vfModuleText, "vf-module-id")
745                                                 execution.setVariable("DCVFM_vfModuleId", vfModuleId)
746                                                 msoLogger.debug("Received orchestration status from A&AI: " + orchestrationStatus)
747                                                 
748                                         }
749                                 }
750                         } catch (Exception ex) {
751                                 ex.printStackTrace()
752                                 msoLogger.debug('Exception occurred while executing AAI GET:' + ex.getMessage())
753                                 exceptionUtil.buildAndThrowWorkflowException(execution, 1002, 'AAI GET Failed:' + ex.getMessage())
754                         }
755                         msoLogger.trace('Exited ' + method)
756                 } catch (BpmnError e) {
757                         throw e;
758                 } catch (Exception e) {
759                         msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, 'Caught exception in ' + method, "BPMN", MsoLogger.getServiceName(),MsoLogger.ErrorCode.UnknownError, "Exception is:\n" + e);
760                         exceptionUtil.buildAndThrowWorkflowException(execution, 1002, 'Error in queryAAIVfModuleForStatus(): ' + e.getMessage())
761                 }
762         }
763
764
765         public void preProcessSDNCAssignRequest(DelegateExecution execution){
766                 
767                 execution.setVariable("prefix", Prefix)
768                 msoLogger.trace("STARTED preProcessSDNCAssignRequest")
769                 def vnfId = execution.getVariable("DCVFM_vnfId")
770                 def vfModuleId = execution.getVariable("DCVFM_vfModuleId")
771                 def serviceInstanceId = execution.getVariable("DCVFM_serviceInstanceId")
772                 msoLogger.debug("NEW VNF ID: " + vnfId)
773
774                 try{
775
776                         //Build SDNC Request
777
778                         def svcInstId = ""
779                         if (serviceInstanceId == null || serviceInstanceId.isEmpty()) {
780                                 svcInstId = vfModuleId
781                         }
782                         else {
783                                 svcInstId = serviceInstanceId
784                         }
785
786                         String assignSDNCRequest = buildSDNCRequest(execution, svcInstId, "assign")
787
788                         assignSDNCRequest = utils.formatXml(assignSDNCRequest)
789                         execution.setVariable("DCVFM_assignSDNCRequest", assignSDNCRequest)
790                         msoLogger.debug("Outgoing AssignSDNCRequest is: \n" + assignSDNCRequest)
791
792                 }catch(Exception e){
793                         msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, " Exception Occurred Processing preProcessSDNCAssignRequest", "BPMN", MsoLogger.getServiceName(),MsoLogger.ErrorCode.UnknownError, "Exception is:\n" + e);                      
794                         exceptionUtil.buildAndThrowWorkflowException(execution, 1002, "Error Occurred during prepareProvision Method:\n" + e.getMessage())
795                 }
796                 msoLogger.trace("COMPLETED preProcessSDNCAssignRequest")
797         }
798
799         public void preProcessSDNCGetRequest(DelegateExecution execution, String element){
800                 
801                 String sdncVersion = execution.getVariable("DCVFM_sdncVersion")
802                 execution.setVariable("prefix", Prefix)
803                 msoLogger.trace("STARTED preProcessSDNCGetRequest Process")
804                 try{
805                         def serviceInstanceId = execution.getVariable('DCVFM_serviceInstanceId')
806                         
807                         String uuid = execution.getVariable('testReqId') // for junits
808                         if(uuid==null){
809                                 uuid = execution.getVariable("mso-request-id") + "-" +  System.currentTimeMillis()
810                         }
811                                         
812                         def callbackUrl = execution.getVariable("DCVFM_sdncCallbackUrl")
813                         msoLogger.debug("callbackUrl:" + callbackUrl)
814                         
815                         def vfModuleId = execution.getVariable('DCVFM_vfModuleId')
816                         
817                         def svcInstId = ""
818                         if (serviceInstanceId == null || serviceInstanceId.isEmpty()) {
819                                 svcInstId = vfModuleId
820                         }
821                         else {
822                                 svcInstId = serviceInstanceId
823                         }
824                         
825                         def msoAction = ""
826                         if (!sdncVersion.equals("1707")) {
827                                 msoAction = "mobility"
828                         }
829                         else {
830                                 msoAction = "vfmodule"
831                         }
832                         // For VNF, serviceOperation (URI for topology GET) will be retrieved from "selflink" element 
833                         // in the response from GenericGetVnf
834                         // For VF Module, in 1707 serviceOperation will be retrieved from "object-path" element
835                         // in SDNC Assign Response
836                         // For VF Module for older versions, serviceOperation is constructed using vfModuleId
837                         
838                         String serviceOperation = ""
839                         if (element.equals("vnf")) {
840                                 def vnfQueryResponse = execution.getVariable("DCVFM_vnfQueryResponse")
841                                 serviceOperation = utils.getNodeText(vnfQueryResponse, "selflink")
842                                 msoLogger.debug("VNF - service operation: " + serviceOperation)
843                         }
844                         else if (element.equals("vfmodule")) {
845                                 String response = execution.getVariable("DCVFM_assignSDNCAdapterResponse")
846                                 msoLogger.debug("DCVFM_assignSDNCAdapterResponse is: \n" + response)                                                    
847                         
848                                 if (!sdncVersion.equals("1707")) {
849                                         serviceOperation = "/VNF-API:vnfs/vnf-list/" + vfModuleId
850                                         msoLogger.debug("VF Module with sdncVersion before 1707 - service operation: " + serviceOperation)
851                                 }
852                                 else {                          
853                                         String data = utils.getNodeXml(response, "response-data")                                       
854                                         msoLogger.debug("responseData: " + data)
855                                         serviceOperation = utils.getNodeText(data, "object-path")
856                                         msoLogger.debug("VF Module with sdncVersion of 1707 - service operation: " + serviceOperation)
857                                 }                               
858                         }               
859
860                         //!!!! TEMPORARY WORKAROUND FOR SDNC REPLICATION ISSUE
861                         sleep(5000)
862
863                         String SDNCGetRequest =
864                                         """<sdncadapterworkflow:SDNCAdapterWorkflowRequest xmlns:ns5="http://org.onap/so/request/types/v1"
865                                                                                         xmlns:sdncadapterworkflow="http://org.onap/so/workflow/schema/v1"
866                                                                                         xmlns:sdncadapter="http://org.onap/workflow/sdnc/adapter/schema/v1">
867                                         <sdncadapter:RequestHeader>
868                                         <sdncadapter:RequestId>${MsoUtils.xmlEscape(uuid)}</sdncadapter:RequestId>
869                                         <sdncadapter:SvcInstanceId>${MsoUtils.xmlEscape(svcInstId)}</sdncadapter:SvcInstanceId>
870                                         <sdncadapter:SvcAction>query</sdncadapter:SvcAction>
871                                         <sdncadapter:SvcOperation>${MsoUtils.xmlEscape(serviceOperation)}</sdncadapter:SvcOperation>
872                                         <sdncadapter:CallbackUrl>${MsoUtils.xmlEscape(callbackUrl)}</sdncadapter:CallbackUrl>
873                                         <sdncadapter:MsoAction>${MsoUtils.xmlEscape(msoAction)}</sdncadapter:MsoAction>
874                                 </sdncadapter:RequestHeader>
875                                         <sdncadapterworkflow:SDNCRequestData></sdncadapterworkflow:SDNCRequestData>
876                                 </sdncadapterworkflow:SDNCAdapterWorkflowRequest>"""
877
878                         execution.setVariable("DCVFM_getSDNCRequest", SDNCGetRequest)
879                         msoLogger.debug("Outgoing GetSDNCRequest is: \n" + SDNCGetRequest)
880
881                 }catch(Exception e){
882                         msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, "Exception Occurred Processing preProcessSDNCGetRequest", "BPMN", MsoLogger.getServiceName(),MsoLogger.ErrorCode.UnknownError, "Exception is:\n" + e);                  
883                         exceptionUtil.buildAndThrowWorkflowException(execution, 1002, "Error Occured during prepareProvision Method:\n" + e.getMessage())
884                 }
885                 msoLogger.trace("COMPLETED preProcessSDNCGetRequest Process")
886         }
887
888
889         public void preProcessVNFAdapterRequest(DelegateExecution execution) {
890                 def method = getClass().getSimpleName() + '.VNFAdapterCreateVfModule(' +
891                         'execution=' + execution.getId() +
892                         ')'
893                 
894                 msoLogger.trace('Entered ' + method)
895
896                 //def xml = execution.getVariable("DoCreateVfModuleRequest")
897                 //msoLogger.debug('VNF REQUEST is: ' + xml)
898
899                 //Get variables
900                 //cloudSiteId
901                 def cloudSiteId = execution.getVariable("DCVFM_cloudSiteId")
902                 //tenantId
903                 def tenantId = execution.getVariable("DCVFM_tenantId")
904                 //vnfType
905                 def vnfType = execution.getVariable("DCVFM_vnfType")
906                 //vnfName
907                 def vnfName = execution.getVariable("DCVFM_vnfName")
908                 //vnfId
909                 def vnfId = execution.getVariable("DCVFM_vnfId")
910                 //vfModuleName
911                 def vfModuleName = execution.getVariable("DCVFM_vfModuleName")
912                 //vfModuleModelName
913                 def vfModuleModelName = execution.getVariable("DCVFM_vfModuleModelName")
914                 //vfModuleId
915                 def vfModuleId = execution.getVariable("DCVFM_vfModuleId")
916                 //vfModuleIndex
917                 def vfModuleIndex = execution.getVariable("DCVFM_vfModuleIndex")
918                 //requestId
919                 def requestId = execution.getVariable("DCVFM_requestId")
920                 //serviceId
921                 def serviceId = execution.getVariable("DCVFM_serviceId")
922                 //serviceInstanceId
923                 def serviceInstanceId = execution.getVariable("DCVFM_serviceInstanceId")
924                 //flavorList
925                 ArrayList<CloudFlavor> flavorList = execution.getVariable("DCVFM_flavorList")
926                 //backoutOnFailure
927                 def backoutOnFailure = execution.getVariable("DCVFM_backoutOnFailure")
928                 //volumeGroupId
929                 def volumeGroupId = execution.getVariable("DCVFM_volumeGroupId")
930                 // baseVfModuleId
931                 def baseVfModuleId = execution.getVariable("DCVFM_baseVfModuleId")
932                 // baseVfModuleStackId
933                 def baseVfModuleStackId = execution.getVariable("DCVFM_baseVfModuleHeatStackId")
934                 // asdcServiceModelVersion
935                 def asdcServiceModelVersion = execution.getVariable("DCVFM_asdcServiceModelVersion")
936                 //volumeGroupStackId
937                 def volumeGroupStackId = execution.getVariable("DCVFM_volumeGroupStackId")
938                 //modelCustomizationUuid
939                 def modelCustomizationUuid = execution.getVariable("DCVFM_modelCustomizationUuid")
940                 //environmentContext
941                 String environmentContext = execution.getVariable("DCVFM_environmentContext")
942                 //workloadContext
943                 String workloadContext = execution.getVariable("DCVFM_workloadContext")
944                 msoLogger.debug("workloadContext: " + workloadContext)
945                 msoLogger.debug("environmentContext: " + environmentContext)
946                 
947                 def messageId = execution.getVariable('mso-request-id') + '-' +
948                                 System.currentTimeMillis()
949
950                 def notificationUrl = createCallbackURL(execution, "VNFAResponse", messageId)
951                 def useQualifiedHostName = UrnPropertiesReader.getVariable("mso.use.qualified.host",execution)
952
953                 msoLogger.debug("notificationUrl: " + notificationUrl)
954                 msoLogger.debug("QualifiedHostName: " + useQualifiedHostName)
955
956                 if ('true'.equals(useQualifiedHostName)) {
957                         notificationUrl = utils.getQualifiedHostNameForCallback(notificationUrl)
958                 }
959
960                 Map<String, String> vnfParamsMap = execution.getVariable("DCVFM_vnfParamsMap")
961                 // Add flavorLabel List to vnfParamsMap
962                 flavorList.each { cloudFlavor ->
963                         vnfParamsMap.put("label_" + cloudFlavor.getFlavorLabel(), cloudFlavor.getFlavor())
964                 }
965                 String vfModuleParams = ""
966                 //Get SDNC Response Data for VF Module Topology
967                 String vfModuleSdncGetResponse = execution.getVariable('DCVFM_getSDNCAdapterResponse')
968                 msoLogger.debug("sdncGetResponse: " + vfModuleSdncGetResponse)
969                 def sdncVersion = execution.getVariable("sdncVersion")
970                 
971                 if (!sdncVersion.equals("1707")) {
972                                                 
973                         vfModuleParams = buildVfModuleParams(vnfParamsMap, vfModuleSdncGetResponse, vnfId, vnfName,
974                                 vfModuleId, vfModuleName, vfModuleIndex, environmentContext, workloadContext)
975                 }
976                 else {
977                         //Get SDNC Response Data for Vnf Topology
978                         String vnfSdncGetResponse = execution.getVariable('DCVFM_getVnfSDNCAdapterResponse')
979                         msoLogger.debug("vnfSdncGetResponse: " + vnfSdncGetResponse)
980                         
981                         vfModuleParams = buildVfModuleParamsFromCombinedTopologies(vnfParamsMap, vnfSdncGetResponse, vfModuleSdncGetResponse, vnfId, vnfName,
982                                 vfModuleId, vfModuleName, vfModuleIndex, environmentContext, workloadContext)                   
983                 }
984
985                 def svcInstId = ""
986                 if (serviceInstanceId == null || serviceInstanceId.isEmpty()) {
987                                 svcInstId = serviceId
988                 }
989                 else {
990                         svcInstId = serviceInstanceId
991                 }
992
993                 def createVnfARequest = """
994                 <createVfModuleRequest>
995                 <cloudSiteId>${MsoUtils.xmlEscape(cloudSiteId)}</cloudSiteId>
996                 <tenantId>${MsoUtils.xmlEscape(tenantId)}</tenantId>
997                 <vnfId>${MsoUtils.xmlEscape(vnfId)}</vnfId>
998                 <vnfName>${MsoUtils.xmlEscape(vnfName)}</vnfName>
999                 <vfModuleName>${MsoUtils.xmlEscape(vfModuleName)}</vfModuleName>
1000                 <vfModuleId>${MsoUtils.xmlEscape(vfModuleId)}</vfModuleId>
1001                 <vnfType>${MsoUtils.xmlEscape(vnfType)}</vnfType>
1002                 <vfModuleType>${MsoUtils.xmlEscape(vfModuleModelName)}</vfModuleType>
1003                 <vnfVersion>${MsoUtils.xmlEscape(asdcServiceModelVersion)}</vnfVersion>
1004                 <modelCustomizationUuid>${MsoUtils.xmlEscape(modelCustomizationUuid)}</modelCustomizationUuid>
1005                 <requestType></requestType>
1006                 <volumeGroupId>${MsoUtils.xmlEscape(volumeGroupId)}</volumeGroupId>
1007         <volumeGroupStackId>${MsoUtils.xmlEscape(volumeGroupStackId)}</volumeGroupStackId>
1008         <baseVfModuleId>${MsoUtils.xmlEscape(baseVfModuleId)}</baseVfModuleId>
1009         <baseVfModuleStackId>${MsoUtils.xmlEscape(baseVfModuleStackId)}</baseVfModuleStackId>
1010         <skipAAI>true</skipAAI>
1011         <backout>${MsoUtils.xmlEscape(backoutOnFailure)}</backout>
1012         <failIfExists>true</failIfExists>
1013                 <vfModuleParams>
1014                 ${vfModuleParams}
1015                 </vfModuleParams>
1016                 <msoRequest>
1017                         <requestId>${MsoUtils.xmlEscape(requestId)}</requestId>
1018                         <serviceInstanceId>${MsoUtils.xmlEscape(svcInstId)}</serviceInstanceId>
1019                 </msoRequest>
1020                 <messageId>${MsoUtils.xmlEscape(messageId)}</messageId>
1021                 <notificationUrl>${MsoUtils.xmlEscape(notificationUrl)}</notificationUrl>
1022                 </createVfModuleRequest>"""
1023
1024                 msoLogger.debug("Create VfModule Request to VNF Adapter: " + createVnfARequest)
1025                 execution.setVariable("DCVFM_createVnfARequest", createVnfARequest)
1026         }
1027
1028         /**
1029          * Validates the request, request id and service instance id.  If a problem is found,
1030          * a WorkflowException is generated and an MSOWorkflowException event is thrown. This
1031          * method also sets up the log context for the workflow.
1032          * @param execution the execution
1033          * @return the validated request
1034          */
1035         public String validateInfraRequest(DelegateExecution execution) {
1036                 def method = getClass().getSimpleName() + '.validateInfraRequest(' +
1037                         'execution=' + execution.getId() +
1038                         ')'
1039                 
1040                 msoLogger.trace('Entered ' + method)
1041
1042                 String processKey = getProcessKey(execution);
1043                 def prefix = execution.getVariable("prefix")
1044
1045                 if (prefix == null) {
1046                         exceptionUtil.buildAndThrowWorkflowException(execution, 1002, processKey + " prefix is null")
1047                 }
1048
1049                 try {
1050                         def request = execution.getVariable(prefix + 'Request')
1051
1052                         if (request == null) {
1053                                 request = execution.getVariable(processKey + 'Request')
1054
1055                                 if (request == null) {
1056                                         request = execution.getVariable('bpmnRequest')
1057                                 }
1058
1059                                 setVariable(execution, processKey + 'Request', null);
1060                                 setVariable(execution, 'bpmnRequest', null);
1061                                 setVariable(execution, prefix + 'Request', request);
1062                         }
1063
1064                         if (request == null) {
1065                                 exceptionUtil.buildAndThrowWorkflowException(execution, 1002, processKey + " request is null")
1066                         }
1067                         msoLogger.debug("DoCreateVfModule Request: " + request)
1068
1069                         /*
1070
1071                         def requestId = execution.getVariable("mso-request-id")
1072
1073                         if (requestId == null) {
1074                                 exceptionUtil.buildAndThrowWorkflowException(execution, 1002, processKey + " request has no mso-request-id")
1075                         }
1076
1077                         def serviceInstanceId = execution.getVariable("mso-service-instance-id")
1078
1079                         if (serviceInstanceId == null) {
1080                                 exceptionUtil.buildAndThrowWorkflowException(execution, 1002, processKey + " request message has no mso-service-instance-id")
1081                         }
1082
1083                         utils.logContext(requestId, serviceInstanceId)
1084                         */
1085                         msoLogger.debug('Incoming message: ' + System.lineSeparator() + request)
1086                         msoLogger.trace('Exited ' + method)
1087                         return request
1088                 } catch (BpmnError e) {
1089                         throw e;
1090                 } catch (Exception e) {
1091                         msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, 'Caught exception in ' + method, "BPMN", MsoLogger.getServiceName(),MsoLogger.ErrorCode.UnknownError, "Exception is:\n" + e);
1092                         exceptionUtil.buildAndThrowWorkflowException(execution, 1002, "Invalid Message")
1093                 }
1094         }
1095
1096         public boolean isVolumeGroupIdPresent(DelegateExecution execution) {
1097
1098                 def method = getClass().getSimpleName() + '.isVolumeGroupIdPresent(' +
1099                         'execution=' + execution.getId() +
1100                         ')'
1101                 
1102                 msoLogger.trace('Entered ' + method)
1103
1104                 def request = execution.getVariable('DoCreateVfModuleRequest')
1105                 String volumeGroupId = utils.getNodeText(request, "volume-group-id")
1106                 if (volumeGroupId == null || volumeGroupId.isEmpty()) {
1107                         msoLogger.debug('No volume group id is present')
1108                         return false
1109                 }
1110                 else {
1111                         msoLogger.debug('Volume group id is present')
1112                         return true
1113                 }
1114
1115         }
1116
1117         public boolean isVolumeGroupNamePresent(DelegateExecution execution) {
1118
1119                 def method = getClass().getSimpleName() + '.isVolumeGroupNamePresent(' +
1120                         'execution=' + execution.getId() +
1121                         ')'
1122                 
1123                 msoLogger.trace('Entered ' + method)
1124
1125                 def request = execution.getVariable('DoCreateVfModuleRequest')
1126                 String volumeGroupName = utils.getNodeText(request, "volume-group-name")
1127                 if (volumeGroupName == null || volumeGroupName.isEmpty()) {
1128                         msoLogger.debug('No volume group name is present')
1129                         return false
1130                 }
1131                 else {
1132                         msoLogger.debug('Volume group name is present')
1133                         return true
1134                 }
1135
1136         }
1137
1138         public String buildSDNCRequest(DelegateExecution execution, String svcInstId, String action){
1139
1140                 String uuid = execution.getVariable('testReqId') // for junits
1141                 if(uuid==null){
1142                         uuid = execution.getVariable("mso-request-id") + "-" +          System.currentTimeMillis()
1143                 }
1144                 def callbackURL = execution.getVariable("DCVFM_sdncCallbackUrl")
1145                 def requestId = execution.getVariable("DCVFM_requestId")
1146                 def serviceId = execution.getVariable("DCVFM_serviceId")
1147                 def vnfType = execution.getVariable("DCVFM_vnfType")
1148                 def vnfName = execution.getVariable("DCVFM_vnfName")
1149                 def tenantId = execution.getVariable("DCVFM_tenantId")
1150                 def source = execution.getVariable("DCVFM_source")
1151                 def backoutOnFailure = execution.getVariable("DCVFM_backoutOnFailure")
1152                 def vfModuleId = execution.getVariable("DCVFM_vfModuleId")
1153                 def vfModuleName = execution.getVariable("DCVFM_vfModuleName")
1154                 def vfModuleModelName = execution.getVariable("DCVFM_vfModuleModelName")
1155                 def vnfId = execution.getVariable("DCVFM_vnfId")
1156                 def cloudSiteId = execution.getVariable("DCVFM_cloudSiteId")
1157                 def sdncVersion = execution.getVariable("DCVFM_sdncVersion")
1158                 def serviceModelInfo = execution.getVariable("serviceModelInfo")
1159                 def vnfModelInfo = execution.getVariable("vnfModelInfo")
1160                 def vfModuleModelInfo = execution.getVariable("vfModuleModelInfo")
1161                 String serviceEcompModelInformation = sdncAdapterUtils.modelInfoToEcompModelInformation(serviceModelInfo)
1162                 String vnfEcompModelInformation = sdncAdapterUtils.modelInfoToEcompModelInformation(vnfModelInfo)
1163                 String vfModuleEcompModelInformation = sdncAdapterUtils.modelInfoToEcompModelInformation(vfModuleModelInfo)
1164                 def globalSubscriberId = execution.getVariable("DCVFM_globalSubscriberId")
1165                 boolean usePreload = execution.getVariable("DCVFM_usePreload")
1166                 String usePreloadToSDNC = usePreload ? "Y" : "N"
1167                 def modelCustomizationUuid = execution.getVariable("DCVFM_modelCustomizationUuid")
1168                 def modelCustomizationUuidString = ""
1169                 if (!usePreload) {
1170                         modelCustomizationUuidString = "<model-customization-uuid>" + modelCustomizationUuid + "</model-customization-uuid>"
1171                 }
1172
1173                 String sdncVNFParamsXml = ""
1174
1175                 if(execution.getVariable("DCVFM_vnfParamsExistFlag") == true){
1176                         if (!sdncVersion.equals("1707")) {
1177                                 sdncVNFParamsXml = buildSDNCParamsXml(execution)
1178                         }
1179                         else {
1180                                 sdncVNFParamsXml = buildCompleteSDNCParamsXml(execution)
1181                         }
1182                 }else{
1183                         sdncVNFParamsXml = ""
1184                 }
1185                 
1186                 String sdncRequest = ""
1187                 
1188                 if (!sdncVersion.equals("1707")) {
1189
1190                         sdncRequest =
1191                 """<sdncadapterworkflow:SDNCAdapterWorkflowRequest xmlns:ns5="http://org.onap/so/request/types/v1"
1192                                                                                                         xmlns:sdncadapterworkflow="http://org.onap/so/workflow/schema/v1"
1193                                                                                                         xmlns:sdncadapter="http://org.onap/workflow/sdnc/adapter/schema/v1">
1194            <sdncadapter:RequestHeader>
1195                                 <sdncadapter:RequestId>${MsoUtils.xmlEscape(uuid)}</sdncadapter:RequestId>
1196                                 <sdncadapter:SvcInstanceId>${MsoUtils.xmlEscape(svcInstId)}</sdncadapter:SvcInstanceId>
1197                                 <sdncadapter:SvcAction>${MsoUtils.xmlEscape(action)}</sdncadapter:SvcAction>
1198                                 <sdncadapter:SvcOperation>vnf-topology-operation</sdncadapter:SvcOperation>
1199                                 <sdncadapter:CallbackUrl>${MsoUtils.xmlEscape(callbackURL)}</sdncadapter:CallbackUrl>
1200                 </sdncadapter:RequestHeader>
1201         <sdncadapterworkflow:SDNCRequestData>
1202                 <request-information>
1203                         <request-id>${MsoUtils.xmlEscape(requestId)}</request-id>
1204                         <request-action>VNFActivateRequest</request-action>
1205                         <source>${MsoUtils.xmlEscape(source)}</source>
1206                         <notification-url/>
1207                 </request-information>
1208                 <service-information>
1209                         <service-id>${MsoUtils.xmlEscape(serviceId)}</service-id>
1210                         <service-type>${MsoUtils.xmlEscape(serviceId)}</service-type>
1211                         <service-instance-id>${MsoUtils.xmlEscape(svcInstId)}</service-instance-id>
1212                         <subscriber-name>notsurewecare</subscriber-name>
1213                 </service-information>
1214                 <vnf-request-information>
1215                         <vnf-id>${MsoUtils.xmlEscape(vfModuleId)}</vnf-id>
1216                         <vnf-type>${MsoUtils.xmlEscape(vfModuleModelName)}</vnf-type>
1217                         <vnf-name>${MsoUtils.xmlEscape(vfModuleName)}</vnf-name>
1218                         <generic-vnf-id>${MsoUtils.xmlEscape(vnfId)}</generic-vnf-id>
1219                         <generic-vnf-name>${MsoUtils.xmlEscape(vnfName)}</generic-vnf-name>
1220                         <generic-vnf-type>${MsoUtils.xmlEscape(vnfType)}</generic-vnf-type>
1221                         <aic-cloud-region>${MsoUtils.xmlEscape(cloudSiteId)}</aic-cloud-region>
1222                         <tenant>${MsoUtils.xmlEscape(tenantId)}</tenant>
1223                         ${modelCustomizationUuidString}
1224                         <use-preload>${MsoUtils.xmlEscape(usePreloadToSDNC)}</use-preload>
1225                 ${sdncVNFParamsXml}
1226                 </vnf-request-information>
1227         </sdncadapterworkflow:SDNCRequestData>
1228         </sdncadapterworkflow:SDNCAdapterWorkflowRequest>"""
1229                 
1230                 }
1231                 else {  
1232                         
1233                         sdncRequest =
1234                         """<sdncadapterworkflow:SDNCAdapterWorkflowRequest xmlns:ns5="http://org.onap/so/request/types/v1"
1235                                                                                                         xmlns:sdncadapterworkflow="http://org.onap/so/workflow/schema/v1"
1236                                                                                                         xmlns:sdncadapter="http://org.onap/workflow/sdnc/adapter/schema/v1">
1237            <sdncadapter:RequestHeader>
1238                                 <sdncadapter:RequestId>${MsoUtils.xmlEscape(uuid)}</sdncadapter:RequestId>
1239                                 <sdncadapter:SvcInstanceId>${MsoUtils.xmlEscape(svcInstId)}</sdncadapter:SvcInstanceId>
1240                                 <sdncadapter:SvcAction>${MsoUtils.xmlEscape(action)}</sdncadapter:SvcAction>
1241                                 <sdncadapter:SvcOperation>vf-module-topology-operation</sdncadapter:SvcOperation>
1242                                 <sdncadapter:CallbackUrl>${MsoUtils.xmlEscape(callbackURL)}</sdncadapter:CallbackUrl>
1243                                 <sdncadapter:MsoAction>generic-resource</sdncadapter:MsoAction>
1244                 </sdncadapter:RequestHeader>
1245         <sdncadapterworkflow:SDNCRequestData>
1246                 <request-information>
1247                         <request-id>${MsoUtils.xmlEscape(requestId)}</request-id>
1248                         <request-action>CreateVfModuleInstance</request-action>
1249                         <source>${MsoUtils.xmlEscape(source)}</source>
1250                         <notification-url/>
1251                 </request-information>
1252                 <service-information>
1253                         <service-id>${MsoUtils.xmlEscape(serviceId)}</service-id>
1254                         <subscription-service-type>${MsoUtils.xmlEscape(serviceId)}</subscription-service-type>
1255                         ${serviceEcompModelInformation}
1256                         <service-instance-id>${MsoUtils.xmlEscape(svcInstId)}</service-instance-id>
1257                         <global-customer-id>${MsoUtils.xmlEscape(globalSubscriberId)}</global-customer-id>                      
1258                 </service-information>          
1259                 <vnf-information>
1260                         <vnf-id>${MsoUtils.xmlEscape(vnfId)}</vnf-id>
1261                         <vnf-type>${MsoUtils.xmlEscape(vnfType)}</vnf-type>
1262                         ${vnfEcompModelInformation}                     
1263                 </vnf-information>
1264                 <vf-module-information>
1265                         <vf-module-id>${MsoUtils.xmlEscape(vfModuleId)}</vf-module-id>
1266                         <vf-module-type>${MsoUtils.xmlEscape(vfModuleModelName)}</vf-module-type>
1267                         ${vfModuleEcompModelInformation}                        
1268                 </vf-module-information>
1269                 <vf-module-request-input>                       
1270                         <vf-module-name>${MsoUtils.xmlEscape(vfModuleName)}</vf-module-name>
1271                         <tenant>${MsoUtils.xmlEscape(tenantId)}</tenant>
1272                         <aic-cloud-region>${MsoUtils.xmlEscape(cloudSiteId)}</aic-cloud-region>                 
1273                 ${sdncVNFParamsXml}
1274                 </vf-module-request-input>
1275           </sdncadapterworkflow:SDNCRequestData>
1276         </sdncadapterworkflow:SDNCAdapterWorkflowRequest>"""
1277                         
1278                         
1279                         /*
1280                         sdncRequest =
1281                         """<sdncadapterworkflow:SDNCAdapterWorkflowRequest xmlns:ns5="http://org.onap/so/request/types/v1"
1282                                                                                                         xmlns:sdncadapterworkflow="http://org.onap/so/workflow/schema/v1"
1283                                                                                                         xmlns:sdncadapter="http://org.onap/workflow/sdnc/adapter/schema/v1">
1284            <sdncadapter:RequestHeader>
1285                                 <sdncadapter:RequestId>${MsoUtils.xmlEscape(requestId)}</sdncadapter:RequestId>
1286                                 <sdncadapter:SvcInstanceId>${MsoUtils.xmlEscape(svcInstId)}</sdncadapter:SvcInstanceId>
1287                                 <sdncadapter:SvcAction>${MsoUtils.xmlEscape(action)}</sdncadapter:SvcAction>
1288                                 <sdncadapter:SvcOperation>vnf-topology-operation</sdncadapter:SvcOperation>
1289                                 <sdncadapter:CallbackUrl>${MsoUtils.xmlEscape(callbackURL)}</sdncadapter:CallbackUrl>
1290                 </sdncadapter:RequestHeader>
1291         <sdncadapterworkflow:SDNCRequestData>
1292                 <request-information>
1293                         <request-id>${MsoUtils.xmlEscape(requestId)}</request-id>
1294                         <request-action>CreateVfModuleInstance</request-action>
1295                         <source>${MsoUtils.xmlEscape(source)}</source>
1296                         <notification-url/>
1297                 </request-information>
1298                 <service-information>
1299                         <service-id>${MsoUtils.xmlEscape(serviceId)}</service-id>
1300                         <service-type>${MsoUtils.xmlEscape(serviceId)}</service-type>
1301                         ${serviceEcompModelInformation}                 
1302                         <service-instance-id>${MsoUtils.xmlEscape(svcInstId)}</service-instance-id>
1303                         <global-customer-id>${MsoUtils.xmlEscape(globalSubscriberId)}</global-customer-id>
1304                 </service-information>
1305                 <vnf-information>
1306                         <vnf-id>${MsoUtils.xmlEscape(vnfId)}</vnf-id>
1307                         <vnf-type>${MsoUtils.xmlEscape(vnfType)}</vnf-type>
1308                         ${vnfEcompModelInformation}                     
1309                 </vnf-information>
1310                 <vf-module-information>
1311                         <vf-module-id>${MsoUtils.xmlEscape(vfModuleId)}</vf-module-id>
1312                         <vf-module-type>${MsoUtils.xmlEscape(vfModuleModelName)}</vf-module-type>
1313                         ${vfModuleEcompModelInformation}                        
1314                 </vf-module-information>
1315                 <vf-module-request-input>                       
1316                         <vf-module-name>${MsoUtils.xmlEscape(vfModuleName)}</vf-module-name>
1317                         <tenant>${MsoUtils.xmlEscape(tenantId)}</tenant>
1318                         <aic-cloud-region>${MsoUtils.xmlEscape(cloudSiteId)}</aic-cloud-region>                         
1319                 ${sdncVNFParamsXml}
1320                 </vf-module-request-input>              
1321         </sdncadapterworkflow:SDNCRequestData>
1322         </sdncadapterworkflow:SDNCAdapterWorkflowRequest>"""
1323                         */
1324                         
1325                 }
1326
1327         msoLogger.debug("sdncRequest:  " + sdncRequest)
1328         return sdncRequest
1329
1330         }
1331
1332         public void preProcessSDNCActivateRequest(DelegateExecution execution) {
1333                 def method = getClass().getSimpleName() + '.preProcessSDNCActivateRequest(' +
1334                         'execution=' + execution.getId() +
1335                         ')'
1336                 
1337                 msoLogger.trace('Entered ' + method)
1338                 execution.setVariable("prefix", Prefix)
1339                 msoLogger.trace("STARTED preProcessSDNCActivateRequest Process")
1340                 try{
1341                         String vnfId = execution.getVariable("DCVFM_vnfId")
1342                         String vfModuleId = execution.getVariable("DCVFM_vfModuleId")
1343                         String serviceInstanceId = execution.getVariable("DCVFM_serviceInstanceId")
1344
1345                         def svcInstId = ""
1346                         if (serviceInstanceId == null || serviceInstanceId.isEmpty()) {
1347                                 svcInstId = vfModuleId
1348                         }
1349                         else {
1350                                 svcInstId = serviceInstanceId
1351                         }
1352                         String activateSDNCRequest = buildSDNCRequest(execution, svcInstId, "activate")
1353
1354                         execution.setVariable("DCVFM_activateSDNCRequest", activateSDNCRequest)
1355                         msoLogger.debug("Outgoing CommitSDNCRequest is: \n" + activateSDNCRequest)
1356
1357                 }catch(Exception e){
1358                         msoLogger.debug("Exception Occured Processing preProcessSDNCActivateRequest. Exception is:\n" + e)
1359                         exceptionUtil.buildAndThrowWorkflowException(execution, 1002, "Error Occured during  preProcessSDNCActivateRequest Method:\n" + e.getMessage())
1360                 }
1361                 msoLogger.trace("COMPLETED  preProcessSDNCActivateRequest Process")
1362         }
1363
1364         public void postProcessVNFAdapterRequest(DelegateExecution execution) {
1365                 def method = getClass().getSimpleName() + '.postProcessVNFAdapterRequest(' +
1366                         'execution=' + execution.getId() +
1367                         ')'
1368                 
1369                 msoLogger.trace('Entered ' + method)
1370                 execution.setVariable("prefix",Prefix)
1371                 try{
1372                 msoLogger.debug("STARTED postProcessVNFAdapterRequest Process")
1373
1374                 String vnfResponse = execution.getVariable("DCVFM_createVnfAResponse")
1375                 msoLogger.debug("VNF Adapter Response is: " + vnfResponse)
1376
1377                 RollbackData rollbackData = execution.getVariable("rollbackData")
1378                 if(vnfResponse != null){
1379
1380                         if(vnfResponse.contains("createVfModuleResponse")){
1381                                 msoLogger.debug("Received a Good Response from VNF Adapter for CREATE_VF_MODULE Call.")
1382                                 execution.setVariable("DCVFM_vnfVfModuleCreateCompleted", true)
1383                                 String heatStackId = utils.getNodeText(vnfResponse, "vfModuleStackId")
1384                                 execution.setVariable("DCVFM_heatStackId", heatStackId)
1385                                 msoLogger.debug("Received heat stack id from VNF Adapter: " + heatStackId)
1386                                 rollbackData.put("VFMODULE", "heatstackid", heatStackId)
1387                                 // Parse vnfOutputs for network_fqdn
1388                                 if (vnfResponse.contains("vfModuleOutputs")) {
1389                                         def vfModuleOutputsXml = utils.getNodeXml(vnfResponse, "vfModuleOutputs")
1390                                         InputSource source = new InputSource(new StringReader(vfModuleOutputsXml));
1391                         DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
1392                         docFactory.setNamespaceAware(true)
1393                         DocumentBuilder docBuilder = docFactory.newDocumentBuilder()
1394                         Document outputsXml = docBuilder.parse(source)
1395
1396                                         NodeList entries = outputsXml.getElementsByTagNameNS("*", "entry")
1397                                         List contrailNetworkPolicyFqdnList = []
1398                                         for (int i = 0; i< entries.getLength(); i++) {
1399                                                 Node node = entries.item(i)
1400                                                 if (node.getNodeType() == Node.ELEMENT_NODE) {
1401                                                         Element element = (Element) node
1402                                                         String key = element.getElementsByTagNameNS("*", "key").item(0).getTextContent()
1403                                                         if (key.equals("contrail-service-instance-fqdn")) {
1404                                                                 String contrailServiceInstanceFqdn = element.getElementsByTagNameNS("*", "value").item(0).getTextContent()
1405                                                                 msoLogger.debug("Obtained contrailServiceInstanceFqdn: " + contrailServiceInstanceFqdn)
1406                                                                 execution.setVariable("DCVFM_contrailServiceInstanceFqdn", contrailServiceInstanceFqdn)
1407                                                         }
1408                                                         else if (key.endsWith("contrail_network_policy_fqdn")) {
1409                                                                 String contrailNetworkPolicyFqdn = element.getElementsByTagNameNS("*", "value").item(0).getTextContent()
1410                                                                 msoLogger.debug("Obtained contrailNetworkPolicyFqdn: " + contrailNetworkPolicyFqdn)
1411                                                                 contrailNetworkPolicyFqdnList.add(contrailNetworkPolicyFqdn)
1412                                                         }
1413                                                         else if (key.equals("oam_management_v4_address")) {
1414                                                                 String oamManagementV4Address = element.getElementsByTagNameNS("*", "value").item(0).getTextContent()
1415                                                                 msoLogger.debug("Obtained oamManagementV4Address: " + oamManagementV4Address)
1416                                                                 execution.setVariable("DCVFM_oamManagementV4Address", oamManagementV4Address)
1417                                                         }
1418                                                         else if (key.equals("oam_management_v6_address")) {
1419                                                                 String oamManagementV6Address = element.getElementsByTagNameNS("*", "value").item(0).getTextContent()
1420                                                                 msoLogger.debug("Obtained oamManagementV6Address: " + oamManagementV6Address)
1421                                                                 execution.setVariable("DCVFM_oamManagementV6Address", oamManagementV6Address)
1422                                                         }
1423
1424                                                 }
1425                                         }
1426                                         if (!contrailNetworkPolicyFqdnList.isEmpty()) {
1427                                                 execution.setVariable("DCVFM_contrailNetworkPolicyFqdnList", contrailNetworkPolicyFqdnList)
1428                                         }
1429                                 }
1430                         }else{
1431                                 msoLogger.debug("Received a BAD Response from VNF Adapter for CREATE_VF_MODULE Call.")
1432                                 exceptionUtil.buildAndThrowWorkflowException(execution, 1002, "VNF Adapter Error")
1433                         }
1434                 }else{
1435                         msoLogger.debug("Response from VNF Adapter is Null for CREATE_VF_MODULE Call.")
1436                         exceptionUtil.buildAndThrowWorkflowException(execution, 1002, "Empty response from VNF Adapter")
1437                 }
1438
1439                 rollbackData.put("VFMODULE", "rollbackVnfAdapterCreate", "true")
1440                 execution.setVariable("rollbackData", rollbackData)
1441
1442                 }catch(BpmnError b){
1443                         throw b
1444                 }catch(Exception e){
1445                         msoLogger.debug("Internal Error Occured in PostProcess Method")
1446                         exceptionUtil.buildAndThrowWorkflowException(execution, 1002, "Internal Error Occured in PostProcess Method")
1447                 }
1448                 msoLogger.trace("COMPLETED postProcessVnfAdapterResponse Process")
1449         }
1450
1451
1452         public void preProcessUpdateAAIVfModuleRequestOrch(DelegateExecution execution) {
1453                 def method = getClass().getSimpleName() + '.preProcessUpdateAAIVfModuleRequestOrch(' +
1454                         'execution=' + execution.getId() +
1455                         ')'
1456                 
1457                 msoLogger.trace('Entered ' + method)
1458                 execution.setVariable("prefix", Prefix)
1459                 msoLogger.trace("STARTED preProcessUpdateAAIVfModuleRequestOrch")
1460
1461                 try{
1462
1463                         //Build UpdateAAIVfModule Request
1464                         boolean setContrailServiceInstanceFqdn = false
1465                         def contrailServiceInstanceFqdn = execution.getVariable("DCVFM_contrailServiceInstanceFqdn")
1466                         if (!contrailServiceInstanceFqdn.equals("")) {
1467                                 setContrailServiceInstanceFqdn = true
1468                         }
1469                         
1470                         execution.setVariable("DCVFM_orchestrationStatus", "Created")
1471
1472                         String updateAAIVfModuleRequest = buildUpdateAAIVfModuleRequest(execution, false, true, true, setContrailServiceInstanceFqdn)
1473
1474                         updateAAIVfModuleRequest = utils.formatXml(updateAAIVfModuleRequest)
1475                         execution.setVariable("DCVFM_updateAAIVfModuleRequest", updateAAIVfModuleRequest)
1476                         msoLogger.debug("Outgoing UpdateAAIVfModuleRequest is: \n" + updateAAIVfModuleRequest)
1477
1478                 }catch(Exception e){
1479                         msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, "Exception Occured Processing preProcessUpdateAAIVfModuleRequestOrch", "BPMN", MsoLogger.getServiceName(),MsoLogger.ErrorCode.UnknownError, "Exception is:\n" + e);                     
1480                         exceptionUtil.buildAndThrowWorkflowException(execution, 1002, "Error Occured during preProcessUpdateAAIVfModuleRequestOrch Method:\n" + e.getMessage())
1481                 }
1482                 msoLogger.trace("COMPLETED preProcessUpdateAAIVfModuleRequestOrch")
1483
1484         }
1485         
1486         public void preProcessUpdateAAIVfModuleRequestStatus(DelegateExecution execution, String status) {
1487                 def method = getClass().getSimpleName() + '.preProcessUpdateAAIVfModuleStatus(' +
1488                         'execution=' + execution.getId() +
1489                         ')'
1490                 
1491                 msoLogger.trace('Entered ' + method)
1492                 execution.setVariable("prefix", Prefix)
1493                 msoLogger.trace("STARTED preProcessUpdateAAIVfModuleStatus")
1494
1495                 try{
1496
1497                         //Build UpdateAAIVfModule Request
1498                         execution.setVariable("DCVFM_orchestrationStatus", status)
1499
1500                         String updateAAIVfModuleRequest = buildUpdateAAIVfModuleRequest(execution, false, true, false, false)
1501
1502                         updateAAIVfModuleRequest = utils.formatXml(updateAAIVfModuleRequest)
1503                         execution.setVariable("DCVFM_updateAAIVfModuleRequest", updateAAIVfModuleRequest)
1504                         msoLogger.debug("Outgoing UpdateAAIVfModuleRequest is: \n" + updateAAIVfModuleRequest)
1505
1506                 }catch(Exception e){
1507                         msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, "Exception Occured Processing preProcessUpdateAAIVfModuleStatus", "BPMN", MsoLogger.getServiceName(),MsoLogger.ErrorCode.UnknownError, "Exception is:\n" + e);
1508                         exceptionUtil.buildAndThrowWorkflowException(execution, 1002, "Error Occured during preProcessUpdateAAIVfModuleStatus Method:\n" + e.getMessage())
1509                 }
1510                 msoLogger.trace("COMPLETED preProcessUpdateAAIVfModuleStatus")
1511
1512         }
1513
1514
1515         public void preProcessUpdateAAIVfModuleRequestGroup(DelegateExecution execution) {
1516                 def method = getClass().getSimpleName() + '.preProcessUpdateAAIVfModuleRequestGroup(' +
1517                         'execution=' + execution.getId() +
1518                         ')'
1519                 
1520                 msoLogger.trace('Entered ' + method)
1521                 execution.setVariable("prefix", Prefix)
1522                 msoLogger.trace("STARTED preProcessUpdateAAIVfModuleRequestGroup")
1523
1524                 try{
1525
1526                         //Build UpdateAAIVfModule Request
1527
1528                         String updateAAIVfModuleRequest = buildUpdateAAIVfModuleRequest(execution, true, false, false, false)
1529
1530                         updateAAIVfModuleRequest = utils.formatXml(updateAAIVfModuleRequest)
1531                         execution.setVariable("DCVFM_updateAAIVfModuleRequest", updateAAIVfModuleRequest)
1532                         msoLogger.debug("Outgoing UpdateAAIVfModuleRequest is: \n" + updateAAIVfModuleRequest)
1533
1534                 }catch(Exception e){
1535                         msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, "Exception Occured Processing preProcessUpdateAAIVfModuleRequestGroup", "BPMN", MsoLogger.getServiceName(),MsoLogger.ErrorCode.UnknownError, "Exception is:\n" + e);                    
1536                         exceptionUtil.buildAndThrowWorkflowException(execution, 1002, "Error Occured during preProcessUpdateAAIVfModuleRequestGroup Method:\n" + e.getMessage())
1537                 }
1538                 msoLogger.trace("COMPLETED  preProcessUpdateAAIVfModuleRequestGroup")
1539
1540         }
1541
1542         public void validateSDNCResponse(DelegateExecution execution, String response, String method){
1543                 
1544                 execution.setVariable("prefix",Prefix)
1545                 msoLogger.debug("STARTED ValidateSDNCResponse Process")
1546
1547                 WorkflowException workflowException = execution.getVariable("WorkflowException")
1548                 boolean successIndicator = execution.getVariable("SDNCA_SuccessIndicator")
1549
1550                 msoLogger.debug("workflowException: " + workflowException)
1551
1552                 SDNCAdapterUtils sdncAdapterUtils = new SDNCAdapterUtils(this)
1553                 sdncAdapterUtils.validateSDNCResponse(execution, response, workflowException, successIndicator)
1554
1555                 String sdncResponse = response
1556                 if(execution.getVariable(Prefix + 'sdncResponseSuccess') == true){
1557                         msoLogger.debug("Received a Good Response from SDNC Adapter for " + method + " SDNC Call.  Response is: \n" + sdncResponse)
1558                         RollbackData rollbackData = execution.getVariable("rollbackData")
1559
1560                         if(method.equals("assign")){
1561                                 rollbackData.put("VFMODULE", "rollbackSDNCRequestAssign", "true")
1562                                 execution.setVariable("CRTGVNF_sdncAssignCompleted", true)
1563                         }
1564                         else if (method.equals("activate")) {
1565                                 rollbackData.put("VFMODULE", "rollbackSDNCRequestActivate", "true")
1566                         }
1567                         execution.setVariable("rollbackData", rollbackData)
1568                 }else{
1569                         msoLogger.debug("Received a BAD Response from SDNC Adapter for " + method + " SDNC Call.")
1570                         throw new BpmnError("MSOWorkflowException")
1571                 }
1572                 msoLogger.trace("COMPLETED ValidateSDNCResponse Process")
1573         }
1574
1575         public void preProcessUpdateAfterCreateRequest(DelegateExecution execution){
1576                 
1577                 execution.setVariable("prefix", Prefix)
1578                 msoLogger.trace("STARTED preProcessRequest Process")
1579                 try{
1580                         String response = execution.getVariable("DCVFM_assignSDNCAdapterResponse")
1581                         msoLogger.debug("DCVFM_assignSDNCAdapterResponse: " + response)
1582
1583                         String data = utils.getNodeXml(response, "response-data")
1584                         String vnfId = utils.getNodeText(data, "vnf-id")
1585
1586                         String uuid = execution.getVariable('testReqId') // for junits
1587                         if(uuid==null){
1588                                 uuid = execution.getVariable("mso-request-id") + "-" +          System.currentTimeMillis()
1589                         }
1590
1591                         String serviceOperation = "/VNF-API:vnfs/vnf-list/" + vnfId
1592                         def callbackUrl = execution.getVariable("DCVFM_sdncCallbackUrl")
1593                         msoLogger.debug("callbackUrl: " + callbackUrl)
1594
1595                         String SDNCGetRequest =
1596                                         """<sdncadapterworkflow:SDNCAdapterWorkflowRequest xmlns:ns5="http://org.onap/so/request/types/v1"
1597                                                                                         xmlns:sdncadapterworkflow="http://org.onap/so/workflow/schema/v1"
1598                                                                                         xmlns:sdncadapter="http://org.onap/workflow/sdnc/adapter/schema/v1">
1599                                         <sdncadapter:RequestHeader>
1600                                         <sdncadapter:RequestId>${MsoUtils.xmlEscape(uuid)}</sdncadapter:RequestId>
1601                                         <sdncadapter:SvcAction>query</sdncadapter:SvcAction>
1602                                         <sdncadapter:SvcOperation>${MsoUtils.xmlEscape(serviceOperation)}</sdncadapter:SvcOperation>
1603                                         <sdncadapter:CallbackUrl>${MsoUtils.xmlEscape(callbackUrl)}</sdncadapter:CallbackUrl>
1604                                         <sdncadapter:MsoAction>mobility</sdncadapter:MsoAction>
1605                                 </sdncadapter:RequestHeader>
1606                                         <sdncadapterworkflow:SDNCRequestData></sdncadapterworkflow:SDNCRequestData>
1607                                 </sdncadapterworkflow:SDNCAdapterWorkflowRequest>"""
1608
1609                         execution.setVariable("DCVFM_getSDNCRequest", SDNCGetRequest)
1610                         msoLogger.debug("Outgoing GetSDNCRequest is: \n" + SDNCGetRequest)
1611
1612                 }catch(Exception e){
1613                         msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, "Exception Occured Processing preProcessSDNCGetRequest", "BPMN", MsoLogger.getServiceName(),MsoLogger.ErrorCode.UnknownError, "Exception is:\n" + e);
1614                         exceptionUtil.buildAndThrowWorkflowException(execution, 1002, "Error Occured during prepareProvision Method:\n" + e.getMessage())
1615                 }
1616                 msoLogger.trace("COMPLETED preProcessSDNCGetRequest Process")
1617         }
1618
1619         public String buildUpdateAAIVfModuleRequest(DelegateExecution execution, boolean updateVolumeGroupId,
1620                 boolean updateOrchestrationStatus, boolean updateHeatStackId, boolean updateContrailFqdn){
1621
1622                 def vnfId = execution.getVariable("DCVFM_vnfId")
1623                 def vfModuleId = execution.getVariable("DCVFM_vfModuleId")
1624                 def volumeGroupIdString = ""
1625                 if (updateVolumeGroupId) {
1626                         volumeGroupIdString = "<volume-group-id>" + execution.getVariable("DCVFM_volumeGroupId") +
1627                                         "</volume-group-id>"
1628                 }
1629                 def orchestrationStatusString = ""
1630                 if (updateOrchestrationStatus) {
1631                         orchestrationStatusString = "<orchestration-status>" + execution.getVariable("DCVFM_orchestrationStatus") + "</orchestration-status>"
1632                 }
1633                 def heatStackIdString = ""
1634                 if (updateHeatStackId) {
1635                         heatStackIdString = "<heat-stack-id>" + execution.getVariable("DCVFM_heatStackId") + "</heat-stack-id>"
1636                 }
1637                 def contrailFqdnString = ""
1638                 if (updateContrailFqdn) {
1639                         contrailFqdnString = "<contrail-service-instance-fqdn>" + execution.getVariable("DCVFM_contrailServiceInstanceFqdn") +
1640                                 "</contrail-service-instance-fqdn>"
1641                 }
1642
1643                 String updateAAIVfModuleRequest =
1644                         """<UpdateAAIVfModuleRequest>
1645                                 <vnf-id>${MsoUtils.xmlEscape(vnfId)}</vnf-id>
1646                                 <vf-module-id>${MsoUtils.xmlEscape(vfModuleId)}</vf-module-id>
1647                                 ${heatStackIdString}
1648                                 ${orchestrationStatusString}
1649                                 ${volumeGroupIdString}
1650                                 ${contrailFqdnString}
1651                         </UpdateAAIVfModuleRequest>"""
1652
1653         msoLogger.trace("updateAAIVfModule Request: " + updateAAIVfModuleRequest)
1654         return updateAAIVfModuleRequest
1655
1656         }
1657
1658         public String buildSDNCParamsXml(DelegateExecution execution){
1659
1660                 String params = ""
1661                 StringBuilder sb = new StringBuilder()
1662                 Map<String, String> paramsMap = execution.getVariable("DCVFM_vnfParamsMap")
1663
1664                 for (Map.Entry<String, String> entry : paramsMap.entrySet()) {
1665                         String paramsXml
1666                         String key = entry.getKey();
1667                         if(key.endsWith("_network")){
1668                                 String requestKey = key.substring(0, key.indexOf("_network"))
1669                                 String requestValue = entry.getValue()
1670                                 paramsXml =
1671 """<vnf-networks>
1672         <network-role>{ functx:substring-before-match(data($param/@name), '_network') }</network-role>
1673         <network-name>{ $param/text() }</network-name>
1674 </vnf-networks>"""
1675                         }else{
1676                         paramsXml = ""
1677                         }
1678                         params = sb.append(paramsXml)
1679                 }
1680                 return params
1681         }
1682         
1683         public String buildCompleteSDNCParamsXml(DelegateExecution execution){
1684                 
1685                 String params = ""
1686                 StringBuilder sb = new StringBuilder()
1687                 Map<String, String> paramsMap = execution.getVariable("DCVFM_vnfParamsMap")
1688                 
1689                 for (Map.Entry<String, String> entry : paramsMap.entrySet()) {
1690                         String paramsXml
1691                         String key = entry.getKey();                                    
1692                         String value = entry.getValue()
1693                         paramsXml =     """<${key}>$value</$key>"""     
1694                         params = sb.append(paramsXml)
1695                 }
1696                 return params
1697         }
1698
1699    public void queryCloudRegion (DelegateExecution execution) {
1700                 
1701                 execution.setVariable("prefix", Prefix)
1702                 msoLogger.trace("STARTED queryCloudRegion")
1703
1704                 try {
1705                         String cloudRegion = execution.getVariable("DCVFM_cloudSiteId")
1706
1707                         // Prepare AA&I url
1708                         String aai_endpoint = UrnPropertiesReader.getVariable("aai.endpoint", execution)
1709                         AaiUtil aaiUtil = new AaiUtil(this)
1710                         String aai_uri = aaiUtil.getCloudInfrastructureCloudRegionUri(execution)
1711                         String queryCloudRegionRequest = "${aai_endpoint}${aai_uri}/" + cloudRegion
1712
1713                         execution.setVariable("DCVFM_queryCloudRegionRequest", queryCloudRegionRequest)
1714                         msoLogger.debug("DCVFM_queryCloudRegionRequest - " + "\n" + queryCloudRegionRequest)
1715
1716                         cloudRegion = aaiUtil.getAAICloudReqion(execution, queryCloudRegionRequest, "PO", cloudRegion)
1717
1718                         if ((cloudRegion != "ERROR")) {
1719                                 if(execution.getVariable("DCVFM_queryCloudRegionReturnCode") == "404"){
1720                                         execution.setVariable("DCVFM_cloudRegionForVolume", "AAIAIC25")
1721                                 }else{
1722                                 execution.setVariable("DCVFM_cloudRegionForVolume", cloudRegion)
1723                                 }
1724                                 execution.setVariable("DCVFM_isCloudRegionGood", true)
1725                         } else {
1726                                 String errorMessage = "AAI Query Cloud Region Unsuccessful. AAI Response Code: " + execution.getVariable("DCVFM_queryCloudRegionReturnCode")
1727                                 msoLogger.debug(errorMessage)
1728                                 exceptionUtil.buildAndThrowWorkflowException(execution, 2500, errorMessage)
1729                                 execution.setVariable("DCVFM_isCloudRegionGood", false)
1730                         }
1731                         msoLogger.debug(" is Cloud Region Good: " + execution.getVariable("DCVFM_isCloudRegionGood"))
1732
1733                 } catch(BpmnError b){
1734                         msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, "Rethrowing MSOWorkflowException", "BPMN", MsoLogger.getServiceName(),MsoLogger.ErrorCode.UnknownError, "Exception is:\n" + b.getMessage());
1735                         throw b
1736                 }catch (Exception ex) {
1737                         // try error
1738                         String errorMessage = "Bpmn error encountered in CreateVfModule flow. Unexpected Response from AAI - " + ex.getMessage()
1739                         msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, "AAI Query Cloud Region Failed "+errorMessage, "BPMN", MsoLogger.getServiceName(),MsoLogger.ErrorCode.UnknownError, "Exception is:\n" + ex);
1740                         exceptionUtil.buildAndThrowWorkflowException(execution, 500, "Exception occured during queryCloudRegion method")
1741                 }
1742         }
1743
1744    /**
1745     *
1746     *This method occurs when an MSOWorkflowException is caught.  It logs the
1747     *variables and ensures that the "WorkflowException" Variable is set.
1748     *
1749     */
1750    public void processBPMNException(DelegateExecution execution){
1751
1752            execution.setVariable("prefix",Prefix)
1753            try{
1754                    msoLogger.debug("Caught a BPMN Exception")
1755                    msoLogger.debug("Started processBPMNException Method")
1756                    msoLogger.debug("Variables List: " + execution.getVariables())
1757                    if(execution.getVariable("WorkflowException") == null){
1758                            exceptionUtil.buildAndThrowWorkflowException(execution, 500, "Exception occured during DoCreateVfModule Sub Process")
1759                    }
1760
1761            }catch(Exception e){
1762                    msoLogger.debug("Caught Exception during processBPMNException Method: " + e)
1763            }
1764            msoLogger.debug("Completed processBPMNException Method")
1765    }
1766
1767    public void prepareCreateAAIVfModuleVolumeGroupRequest(DelegateExecution execution) {
1768                 def method = getClass().getSimpleName() + '.prepareCreateAAIVfModuleVolumeGroupRequest(' +
1769                         'execution=' + execution.getId() +
1770                         ')'
1771                 
1772                 msoLogger.trace('Entered ' + method)
1773                 execution.setVariable("prefix", Prefix)
1774                 msoLogger.trace("STARTED prepareCreateAAIVfModuleVolumeGroupRequest")
1775
1776                 try{
1777
1778                         //Build CreateAAIVfModuleVolumeGroup Request
1779
1780                         def vnfId = execution.getVariable("DCVFM_vnfId")
1781                         def vfModuleId = execution.getVariable("DCVFM_vfModuleId")
1782                         def volumeGroupId = execution.getVariable("DCVFM_volumeGroupId")
1783                         //def aicCloudRegion = execution.getVariable("DCVFM_cloudSiteId")
1784                         def aicCloudRegion = execution.getVariable("DCVFM_cloudRegionForVolume")
1785                         String createAAIVfModuleVolumeGroupRequest =
1786                         """<CreateAAIVfModuleVolumeGroupRequest>
1787                                 <vnf-id>${MsoUtils.xmlEscape(vnfId)}</vnf-id>
1788                                 <vf-module-id>${MsoUtils.xmlEscape(vfModuleId)}</vf-module-id>
1789                                 <volume-group-id>${MsoUtils.xmlEscape(volumeGroupId)}</volume-group-id>
1790                                 <aic-cloud-region>${MsoUtils.xmlEscape(aicCloudRegion)}</aic-cloud-region>
1791                         </CreateAAIVfModuleVolumeGroupRequest>"""
1792
1793                         createAAIVfModuleVolumeGroupRequest = utils.formatXml(createAAIVfModuleVolumeGroupRequest)
1794                         execution.setVariable("DCVFM_createAAIVfModuleVolumeGroupRequest", createAAIVfModuleVolumeGroupRequest)
1795                         msoLogger.debug("Outgoing CreateAAIVfModuleVolumeGroupRequest is: \n" + createAAIVfModuleVolumeGroupRequest)
1796
1797                 }catch(Exception e){
1798                         msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, 'Exception Occured Processing prepareCreateAAIVfModuleVolumeGroupRequest', "BPMN", MsoLogger.getServiceName(),MsoLogger.ErrorCode.UnknownError, "Exception is:\n" + e);
1799                         exceptionUtil.buildAndThrowWorkflowException(execution, 1002, "Error Occured during prepareCreateAAIVfModuleVolumeGroupRequest Method:\n" + e.getMessage())
1800                 }
1801                 msoLogger.trace("COMPLETED  prepareCreateAAIVfModuleVolumeGroupRequest")
1802
1803         }
1804
1805    public void createNetworkPoliciesInAAI(DelegateExecution execution) {
1806            def method = getClass().getSimpleName() + '.createNetworkPoliciesInAAI(' +
1807            'execution=' + execution.getId() +
1808            ')'
1809            
1810            msoLogger.trace('Entered ' + method)
1811            execution.setVariable("prefix", Prefix)
1812            msoLogger.trace("STARTED createNetworkPoliciesInAAI")
1813
1814            try {
1815                    // get variables
1816                    List fqdnList = execution.getVariable("DCVFM_contrailNetworkPolicyFqdnList")
1817                    int fqdnCount = fqdnList.size()
1818                    def rollbackData = execution.getVariable("rollbackData")
1819
1820                    execution.setVariable("DCVFM_networkPolicyFqdnCount", fqdnCount)
1821                    msoLogger.debug("DCVFM_networkPolicyFqdnCount - " + fqdnCount)
1822
1823                    String aai_endpoint = UrnPropertiesReader.getVariable("aai.endpoint", execution)
1824                    AaiUtil aaiUriUtil = new AaiUtil(this)
1825                    String aai_uri = aaiUriUtil.getNetworkPolicyUri(execution)
1826
1827                    if (fqdnCount > 0) {
1828
1829                            // AII loop call over contrail network policy fqdn list
1830                            for (i in 0..fqdnCount-1) {
1831
1832                                    int counting = i+1
1833                                    String fqdn = fqdnList[i]
1834
1835                                    // Query AAI for this network policy FQDN
1836
1837                                    String queryNetworkPolicyByFqdnAAIRequest = "${aai_endpoint}${aai_uri}?network-policy-fqdn=" + UriUtils.encode(fqdn, "UTF-8")
1838
1839                                    def aaiRequestId = UUID.randomUUID().toString()
1840                                    RESTConfig config = new RESTConfig(queryNetworkPolicyByFqdnAAIRequest);
1841                                    RESTClient client = new RESTClient(config).addHeader("X-TransactionId", aaiRequestId)
1842                                                                                                                          .addHeader("X-FromAppId", "MSO")
1843                                                                                                                          .addHeader("Content-Type", "application/xml")
1844                                                                                                                          .addHeader("Accept","application/xml");
1845                                    APIResponse response = client.get()
1846                                    int returnCode = response.getStatusCode()
1847                                    execution.setVariable("DCVFM_aaiQqueryNetworkPolicyByFqdnReturnCode", returnCode)
1848                                    msoLogger.debug(" ***** AAI query network policy Response Code, NetworkPolicy #" + counting + " : " + returnCode)
1849
1850                                    String aaiResponseAsString = response.getResponseBodyAsString()
1851
1852                                    if (isOneOf(returnCode, 200, 201)) {
1853                                            msoLogger.debug("The return code is: "  + returnCode)
1854                                            // This network policy FQDN already exists in AAI
1855                                            execution.setVariable("DCVFM_queryNetworkPolicyByFqdnAAIResponse", aaiResponseAsString)
1856                                            msoLogger.debug(" QueryAAINetworkPolicyByFQDN Success REST Response, , NetworkPolicy #" + counting + " : " + "\n" + aaiResponseAsString)
1857
1858                                    } else {
1859                                            if (returnCode == 404) {
1860                                                    // This network policy FQDN is not in AAI yet. Add it now
1861                                                    msoLogger.debug("The return code is: "  + returnCode)
1862                                                    msoLogger.debug("This network policy FQDN is not in AAI yet: " + fqdn)
1863                                                    // Add the network policy with this FQDN to AAI
1864                                                    def networkPolicyId = UUID.randomUUID().toString()
1865                                                    msoLogger.debug("Adding network-policy with network-policy-id " + networkPolicyId)
1866
1867                                                    String aaiNamespace = aaiUriUtil.getNamespaceFromUri(execution, aai_uri)
1868                                                    msoLogger.debug('AAI namespace is: ' + aaiNamespace)
1869                                                    String payload = """<network-policy xmlns="${aaiNamespace}">
1870                                                                 <network-policy-id>${MsoUtils.xmlEscape(networkPolicyId)}</network-policy-id>
1871                                                                 <network-policy-fqdn>${MsoUtils.xmlEscape(fqdn)}</network-policy-fqdn>
1872                                                                 <heat-stack-id>${MsoUtils.xmlEscape(execution.getVariable("DCVFM_heatStackId"))}</heat-stack-id>
1873                                                                 </network-policy>""" as String
1874
1875                                                    execution.setVariable("DCVFM_addNetworkPolicyAAIRequestBody", payload)
1876
1877                                                    String addNetworkPolicyAAIRequest = "${aai_endpoint}${aai_uri}/" + UriUtils.encode(networkPolicyId, "UTF-8")
1878                                                    msoLogger.debug("AAI request endpoint: " + addNetworkPolicyAAIRequest)
1879
1880                                                    def aaiRequestIdPut = UUID.randomUUID().toString()
1881                                                    RESTConfig configPut = new RESTConfig(addNetworkPolicyAAIRequest);
1882                                                    RESTClient clientPut = new RESTClient(configPut).addHeader("X-TransactionId", aaiRequestIdPut)
1883                                                                                                                                          .addHeader("X-FromAppId", "MSO")
1884                                                                                                                                          .addHeader("Content-Type", "application/xml")
1885                                                                                                                                          .addHeader("Accept","application/xml");
1886                                                    msoLogger.debug("invoking PUT call to AAI with payload:"+System.lineSeparator()+payload)
1887                                                    APIResponse responsePut = clientPut.httpPut(payload)
1888                                                    int returnCodePut = responsePut.getStatusCode()
1889                                                    execution.setVariable("DCVFM_aaiAddNetworkPolicyReturnCode", returnCodePut)
1890                                                    msoLogger.debug(" ***** AAI add network policy Response Code, NetworkPolicy #" + counting + " : " + returnCodePut)
1891
1892                                                    String aaiResponseAsStringPut = responsePut.getResponseBodyAsString()
1893                                                    if (isOneOf(returnCodePut, 200, 201)) {
1894                                                            msoLogger.debug("The return code from adding network policy is: "  + returnCodePut)
1895                                                            // This network policy was created in AAI successfully
1896                                                            execution.setVariable("DCVFM_addNetworkPolicyAAIResponse", aaiResponseAsStringPut)
1897                                                            msoLogger.debug(" AddAAINetworkPolicy Success REST Response, , NetworkPolicy #" + counting + " : " + "\n" + aaiResponseAsStringPut)
1898                                                            rollbackData.put("VFMODULE", "rollbackCreateNetworkPoliciesAAI", "true")
1899                                                            rollbackData.put("VFMODULE", "contrailNetworkPolicyFqdn" + i, fqdn)
1900                                                            execution.setVariable("rollbackData", rollbackData)
1901
1902                                                    } else {
1903                                                                 // aai all errors
1904                                                                 String putErrorMessage = "Unable to add network-policy to AAI createNetworkPoliciesInAAI - " + returnCodePut
1905                                                                 msoLogger.debug(putErrorMessage)
1906                                                                 exceptionUtil.buildAndThrowWorkflowException(execution, 2500, putErrorMessage)
1907                                                    }
1908
1909                                            } else {
1910                                                   if (aaiResponseAsString.contains("RESTFault")) {
1911                                                           WorkflowException exceptionObject = exceptionUtil.MapAAIExceptionToWorkflowException(aaiResponseAsString, execution)
1912                                                           execution.setVariable("WorkflowException", exceptionObject)
1913                                                           throw new BpmnError("MSOWorkflowException")
1914
1915                                                           } else {
1916                                                                    // aai all errors
1917                                                                    String dataErrorMessage = "Unexpected Response from createNetworkPoliciesInAAI - " + returnCode
1918                                                                    msoLogger.debug(dataErrorMessage)
1919                                                                    exceptionUtil.buildAndThrowWorkflowException(execution, 2500, dataErrorMessage)
1920
1921                                                          }
1922                                            }
1923                                    }
1924
1925                            } // end loop
1926
1927
1928                    } else {
1929                            msoLogger.debug("No contrail network policies to query/create")
1930
1931                    }
1932
1933            } catch (BpmnError e) {
1934                    throw e;
1935
1936            } catch (Exception ex) {
1937                    String exceptionMessage = "Bpmn error encountered in DoCreateVfModule flow. createNetworkPoliciesInAAI() - " + ex.getMessage()
1938                    msoLogger.debug(exceptionMessage)
1939                    exceptionUtil.buildAndThrowWorkflowException(execution, 7000, exceptionMessage)
1940            }
1941
1942    }
1943
1944    /**
1945         * Prepare a Request for invoking the UpdateAAIGenericVnf subflow.
1946         *
1947         * @param execution The flow's execution instance.
1948         */
1949    public void prepUpdateAAIGenericVnf(DelegateExecution execution) {
1950            def method = getClass().getSimpleName() + '.prepUpdateAAIGenericVnf(' +
1951                    'execution=' + execution.getId() +
1952                    ')'
1953            
1954            msoLogger.trace('Entered ' + method)
1955
1956            try {
1957                    def rollbackData = execution.getVariable("rollbackData")
1958                    def vnfId = execution.getVariable('DCVFM_vnfId')
1959                    def oamManagementV4Address = execution.getVariable("DCVFM_oamManagementV4Address")
1960                    def oamManagementV6Address = execution.getVariable("DCVFM_oamManagementV6Address")
1961                    def ipv4OamAddressElement = ''
1962                    def managementV6AddressElement = ''
1963
1964                    if (oamManagementV4Address != null && !oamManagementV4Address.isEmpty()) {
1965                            ipv4OamAddressElement = '<ipv4-oam-address>' + oamManagementV4Address + '</ipv4-oam-address>'
1966                    }
1967
1968                    if (oamManagementV6Address != null && !oamManagementV6Address.isEmpty()) {
1969                            managementV6AddressElement = '<management-v6-address>' + oamManagementV6Address + '</management-v6-address>'
1970                    }
1971
1972                    rollbackData.put("VFMODULE", "oamManagementV4Address", oamManagementV4Address)
1973
1974
1975                    String updateAAIGenericVnfRequest = """
1976                                         <UpdateAAIGenericVnfRequest>
1977                                                 <vnf-id>${MsoUtils.xmlEscape(vnfId)}</vnf-id>
1978                                                 ${ipv4OamAddressElement}
1979                                                 ${managementV6AddressElement}
1980                                         </UpdateAAIGenericVnfRequest>
1981                                 """
1982                            updateAAIGenericVnfRequest = utils.formatXml(updateAAIGenericVnfRequest)
1983                            execution.setVariable('DCVM_updateAAIGenericVnfRequest', updateAAIGenericVnfRequest)
1984                            msoLogger.debug('Request for UpdateAAIGenericVnf:\n' + updateAAIGenericVnfRequest)
1985
1986
1987                    msoLogger.trace('Exited ' + method)
1988            } catch (BpmnError e) {
1989                    throw e;
1990            } catch (Exception e) {
1991                    msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, " Exception Encountered in " + method, "BPMN", MsoLogger.getServiceName(),MsoLogger.ErrorCode.UnknownError, "Exception is:\n" + e);
1992
1993                    exceptionUtil.buildAndThrowWorkflowException(execution, 1002, 'Error in prepUpdateAAIGenericVnf(): ' + e.getMessage())
1994            }
1995    }
1996
1997    /**
1998         * Post process a result from invoking the UpdateAAIGenericVnf subflow.
1999         *
2000         * @param execution The flow's execution instance.
2001         */
2002    public void postProcessUpdateAAIGenericVnf(DelegateExecution execution) {
2003            def method = getClass().getSimpleName() + '.postProcessUpdateAAIGenericVnf(' +
2004                    'execution=' + execution.getId() +
2005                    ')'
2006            
2007            msoLogger.trace('Entered ' + method)
2008
2009            try {
2010                    def rollbackData = execution.getVariable("rollbackData")
2011
2012                    rollbackData.put("VFMODULE", "rollbackUpdateVnfAAI", "true")
2013
2014                    def vnfId = execution.getVariable('DCVFM_vnfId')
2015                    def oamManagementV4Address = execution.getVariable("DCVFM_oamManagementV4Address")
2016                    def oamManagementV6Address = execution.getVariable("DCVFM_oamManagementV6Address")
2017                    def ipv4OamAddressElement = ''
2018                    def managementV6AddressElement = ''
2019
2020                    if (oamManagementV4Address != null && !oamManagementV4Address.isEmpty()) {
2021                            rollbackData.put("VFMODULE", "oamManagementV4Address", oamManagementV4Address)
2022                    }
2023
2024                    if (oamManagementV6Address != null && !oamManagementV6Address.isEmpty()) {
2025                            rollbackData.put("VFMODULE", "oamManagementV6Address", oamManagementV6Address)
2026                    }
2027
2028                    execution.setVariable("rollbackData", rollbackData)
2029
2030                    msoLogger.trace('Exited ' + method)
2031            } catch (BpmnError e) {
2032                    throw e;
2033            } catch (Exception e) {
2034                         msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, 'Caught exception in ' + method, "BPMN", MsoLogger.getServiceName(),MsoLogger.ErrorCode.UnknownError, "Exception is:\n" + e);
2035                    exceptionUtil.buildAndThrowWorkflowException(execution, 1002, 'Error in postProcessUpdateAAIGenericVnf(): ' + e.getMessage())
2036            }
2037    }
2038    
2039    public void queryCatalogDB (DelegateExecution execution) {
2040           
2041            String msg = ""
2042            msoLogger.trace("queryCatalogDB ")
2043
2044            try {
2045                    boolean twoPhaseDesign = false
2046                    // check for input
2047                    
2048                    String vfModuleModelName = execution.getVariable("DCVFM_vfModuleModelName")
2049                    msoLogger.debug("vfModuleModelName: " + vfModuleModelName)
2050                    def vnfModelInfo = execution.getVariable("vnfModelInfo")
2051                    def vnfModelCustomizationUuid = jsonUtil.getJsonValue(vnfModelInfo, "modelCustomizationUuid")
2052                   
2053                    msoLogger.debug("vnfModelCustomizationUuid: " + vnfModelCustomizationUuid)              
2054                 
2055                    JSONArray vnfs = catalog.getAllVnfsByVnfModelCustomizationUuid(execution, vnfModelCustomizationUuid, "v2")
2056                    
2057                    msoLogger.debug("Incoming Query Catalog DB for Vnf Response is: " + vnfModelCustomizationUuid) 
2058                    // Only one match here
2059                    if (vnfs != null) {
2060                            JSONObject vnfObject = vnfs.get(0)
2061                            if (vnfObject != null) {
2062                                    String vnfJson = vnfObject.toString()
2063                                    //
2064                                    ObjectMapper om = new ObjectMapper();                          
2065                                    VnfResource vnf = om.readValue(vnfJson, VnfResource.class);
2066                    
2067                                    // Get multiStageDesign flag
2068                    
2069                                    String multiStageDesignValue = vnf.getMultiStageDesign()
2070                                    msoLogger.debug("multiStageDesign value from Catalog DB is: " + multiStageDesignValue)
2071                                    if (multiStageDesignValue != null) {
2072                                            if (multiStageDesignValue.equalsIgnoreCase("true")) {
2073                                                         twoPhaseDesign = true
2074                                            }
2075                                    }
2076                            }
2077                    }
2078                    
2079                    msoLogger.debug("setting twoPhaseDesign flag to: " + twoPhaseDesign)
2080                    
2081                    execution.setVariable("DCVFM_twoPhaseDesign", twoPhaseDesign)                
2082            } catch (BpmnError e) {
2083                    throw e;
2084            } catch (Exception e) {
2085                         msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, 'Caught exception in queryCatalogDB', "BPMN", MsoLogger.getServiceName(),MsoLogger.ErrorCode.UnknownError, "Exception is:\n" + e);
2086                    exceptionUtil.buildAndThrowWorkflowException(execution, 1002, 'Error in queryCatalogDB(): ' + e.getMessage())
2087            }
2088    }
2089         
2090    
2091    public void preProcessRollback (DelegateExecution execution) {
2092
2093            msoLogger.trace("preProcessRollback")
2094            try {
2095                    
2096                    Object workflowException = execution.getVariable("WorkflowException");
2097
2098                    if (workflowException instanceof WorkflowException) {
2099                            msoLogger.debug("Prev workflowException: " + workflowException.getErrorMessage())
2100                            execution.setVariable("prevWorkflowException", workflowException);
2101                            //execution.setVariable("WorkflowException", null);
2102                    }
2103            } catch (BpmnError e) {
2104                    msoLogger.debug("BPMN Error during preProcessRollback")
2105            } catch(Exception ex) {
2106                    String msg = "Exception in preProcessRollback. " + ex.getMessage()
2107                    msoLogger.debug(msg)
2108            }
2109            msoLogger.trace("Exit preProcessRollback")
2110    }
2111
2112    public void postProcessRollback (DelegateExecution execution) {
2113
2114            msoLogger.trace("postProcessRollback")
2115            String msg = ""
2116            try {
2117                    Object workflowException = execution.getVariable("prevWorkflowException");
2118                    if (workflowException instanceof WorkflowException) {
2119                            msoLogger.debug("Setting prevException to WorkflowException: ")
2120                            execution.setVariable("WorkflowException", workflowException);
2121                    }
2122                    execution.setVariable("rollbackData", null)
2123            } catch (BpmnError b) {
2124                    msoLogger.debug("BPMN Error during postProcessRollback")
2125                    throw b;
2126            } catch(Exception ex) {
2127                    msg = "Exception in postProcessRollback. " + ex.getMessage()
2128                    msoLogger.debug(msg)
2129            }
2130            msoLogger.trace("Exit postProcessRollback")
2131    }
2132
2133 }