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