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