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