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