build sndc and user directives in groovy
[so.git] / bpmn / so-bpmn-infrastructure-common / src / main / groovy / org / onap / so / bpmn / infrastructure / scripts / DoCreateVfModule.groovy
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP - SO
4  * ================================================================================
5  * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
6  * ================================================================================
7  * 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()
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()
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                                 logger.debug('Exception occurred while postProcessing CreateAAIVfModule request: {}', ex.getMessage(), ex)
672                                 exceptionUtil.buildAndThrowWorkflowException(execution, 1002, 'Bad response from CreateAAIVfModule' + ex.getMessage())
673                 }
674                 logger.trace('Exited ' + method)
675         }
676
677
678         /**
679          * Using the received vnfId and vfModuleId, query AAI to get the corresponding VNF info.
680          * A 200 response is expected with the VNF info in the response body. Will find out the base module info.
681          *
682          * @param execution The flow's execution instance.
683          */
684         public void queryAAIVfModule(DelegateExecution execution) {
685
686                 def method = getClass().getSimpleName() + '.getVfModule(' +
687                         'execution=' + execution.getId() +
688                         ')'
689                 logger.trace('Entered ' + method)
690
691                 try {
692                         def vnfId = execution.getVariable('DCVFM_vnfId')
693                         def vfModuleId = execution.getVariable('DCVFM_vfModuleId')
694
695                         AaiUtil aaiUriUtil = new AaiUtil(this)
696                         AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIObjectType.GENERIC_VNF, vnfId).depth(Depth.ONE)
697                         String endPoint = aaiUriUtil.createAaiUri(uri)
698
699                         try {
700                                 HttpClient client = httpClientFactory.newXmlClient(new URL(endPoint), TargetEntity.AAI)
701                                 client.addAdditionalHeader('X-TransactionId', UUID.randomUUID().toString())
702                                 client.addAdditionalHeader('X-FromAppId', 'MSO')
703                                 client.addAdditionalHeader('Content-Type', MediaType.APPLICATION_XML)
704                                 client.addAdditionalHeader('Accept', MediaType.APPLICATION_XML)
705
706                                 logger.debug('sending GET to AAI endpoint \'' + endPoint + '\'')
707                                 Response response = client.get()
708
709                                 String responseData = response.readEntity(String.class)
710                                 if (responseData != null) {
711                                         logger.debug("Received generic VNF data: " + responseData)
712
713                                 }
714
715                                 execution.setVariable('DCVFM_queryAAIVfModuleResponseCode', response.getStatus())
716                                 execution.setVariable('DCVFM_queryAAIVfModuleResponse', responseData)
717                                 logger.debug('Response code:' + response.getStatus())
718                                 logger.debug('Response:' + System.lineSeparator() + responseData)
719                                 if (response.getStatus() == 200) {
720                                         // Parse the VNF record from A&AI to find base module info
721                                         logger.debug('Parsing the VNF data to find base module info')
722                                         if (responseData != null) {
723                                                 def vfModulesText = utils.getNodeXml(responseData, "vf-modules")
724                                                 def xmlVfModules= new XmlSlurper().parseText(vfModulesText)
725                                                 def vfModules = xmlVfModules.'**'.findAll {it.name() == "vf-module"}
726                                                 int vfModulesSize = 0
727                                                 for (i in 0..vfModules.size()-1) {
728                                                         def vfModuleXml = groovy.xml.XmlUtil.serialize(vfModules[i])
729                                                         def isBaseVfModule = utils.getNodeText(vfModuleXml, "is-base-vf-module")
730
731                                                         if (isBaseVfModule == "true") {
732                                                             String baseModuleId = utils.getNodeText(vfModuleXml, "vf-module-id")
733                                                             execution.setVariable("DCVFM_baseVfModuleId", baseModuleId)
734                                                             logger.debug('Received baseVfModuleId: ' + baseModuleId)
735                                                             String baseModuleHeatStackId = utils.getNodeText(vfModuleXml, "heat-stack-id")
736                                                             execution.setVariable("DCVFM_baseVfModuleHeatStackId", baseModuleHeatStackId)
737                                                             logger.debug('Received baseVfModuleHeatStackId: ' + baseModuleHeatStackId)
738                                                         }
739                                                 }
740                                         }
741                                 }
742                         } catch (Exception ex) {
743                                 logger.debug('Exception occurred while executing AAI GET: {}', ex.getMessage(), ex)
744                                 exceptionUtil.buildAndThrowWorkflowException(execution, 1002, 'AAI GET Failed:' + ex.getMessage())
745                         }
746                         logger.trace('Exited ' + method)
747                 } catch (BpmnError e) {
748                         throw e;
749                 } catch (Exception e) {
750                         logger.error("{} {} {} {} {}", MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(),
751                                         'Caught exception in ' + method, "BPMN",
752                                         ErrorCode.UnknownError.getValue(), "Exception is:\n" + e);
753                         exceptionUtil.buildAndThrowWorkflowException(execution, 1002, 'Error in queryAAIVfModule(): ' + e.getMessage())
754                 }
755         }
756
757         /**
758          * Using the vnfId and vfModuleName provided in the inputs,
759          * query AAI to get the corresponding VF Module info.
760          * A 200 response is expected with the VF Module info in the response body,
761          * or a 404 response if the module does not exist yet. Will determine VF Module's
762          * orchestration status if one exists
763          *
764          * @param execution The flow's execution instance.
765          */
766         public void queryAAIVfModuleForStatus(DelegateExecution execution) {
767
768                 def method = getClass().getSimpleName() + '.queryAAIVfModuleForStatus(' +
769                         'execution=' + execution.getId() +
770                         ')'
771                 logger.trace('Entered ' + method)
772
773                 execution.setVariable('DCVFM_orchestrationStatus', '')
774
775                 try {
776                         def vnfId = execution.getVariable('DCVFM_vnfId')
777                         def vfModuleName = execution.getVariable('DCVFM_vfModuleName')
778
779                         AaiUtil aaiUriUtil = new AaiUtil(this)
780                         AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIObjectPlurals.VF_MODULE, vnfId).queryParam("vf-module-name",vfModuleName)
781                         String endPoint = aaiUriUtil.createAaiUri(uri)
782
783                         HttpClient client = httpClientFactory.newXmlClient(new URL(endPoint), TargetEntity.AAI)
784                         client.addAdditionalHeader('X-TransactionId', UUID.randomUUID().toString())
785                         client.addAdditionalHeader('X-FromAppId', 'MSO')
786                         client.addAdditionalHeader('Content-Type', MediaType.APPLICATION_XML)
787                         client.addAdditionalHeader('Accept', MediaType.APPLICATION_XML)
788
789                         try {
790                                 def responseData = ''
791
792                                 logger.debug('sending GET to AAI endpoint \'' + endPoint + '\'')
793                                 Response response = client.get()
794                                 logger.debug("createVfModule - invoking httpGet() to AAI")
795
796                                 responseData = response.readEntity(String.class)
797                                 if (responseData != null) {
798                                         logger.debug("Received generic VNF data: " + responseData)
799
800                                 }
801
802                                 execution.setVariable('DCVFM_queryAAIVfModuleForStatusResponseCode', response.getStatus())
803                                 execution.setVariable('DCVFM_queryAAIVfModuleForStatusResponse', responseData)
804                                 logger.debug('Response code:' + response.getStatus())
805                                 logger.debug('Response:' + System.lineSeparator() + responseData)
806                                 // Retrieve VF Module info and its orchestration status; if not found, do nothing
807                                 if (response.getStatus() == 200) {
808                                         // Parse the VNF record from A&AI to find base module info
809                                         logger.debug('Parsing the VNF data to find orchestration status')
810                                         if (responseData != null) {
811                                                 def vfModuleText = utils.getNodeXml(responseData, "vf-module")
812                                                 //def xmlVfModule= new XmlSlurper().parseText(vfModuleText)
813                                                 def orchestrationStatus = utils.getNodeText(vfModuleText, "orchestration-status")
814                                                 execution.setVariable("DCVFM_orchestrationStatus", orchestrationStatus)
815                                                 // Also retrieve vfModuleId
816                                                 def vfModuleId = utils.getNodeText(vfModuleText, "vf-module-id")
817                                                 execution.setVariable("DCVFM_vfModuleId", vfModuleId)
818                                                 logger.debug("Received orchestration status from A&AI: " + orchestrationStatus)
819
820                                         }
821                                 }
822                         } catch (Exception ex) {
823                                 logger.debug('Exception occurred while executing AAI GET: {}', ex.getMessage(), ex)
824                                 exceptionUtil.buildAndThrowWorkflowException(execution, 1002, 'AAI GET Failed:' + ex.getMessage())
825                         }
826                         logger.trace('Exited ' + method)
827                 } catch (BpmnError e) {
828                         throw e;
829                 } catch (Exception e) {
830                         logger.error("{} {} {} {} {} {}", MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(),
831                                         'Caught exception in ' + method, "BPMN",
832                                         ErrorCode.UnknownError.getValue(), "Exception is:\n" + e, e);
833                         exceptionUtil.buildAndThrowWorkflowException(execution, 1002, 'Error in queryAAIVfModuleForStatus(): ' + e.getMessage())
834                 }
835         }
836
837
838         public void preProcessSDNCAssignRequest(DelegateExecution execution){
839
840                 execution.setVariable("prefix", Prefix)
841                 logger.trace("STARTED preProcessSDNCAssignRequest")
842                 def vnfId = execution.getVariable("DCVFM_vnfId")
843                 def vfModuleId = execution.getVariable("DCVFM_vfModuleId")
844                 def serviceInstanceId = execution.getVariable("DCVFM_serviceInstanceId")
845                 logger.debug("NEW VNF ID: " + vnfId)
846
847                 try{
848
849                         //Build SDNC Request
850
851                         def svcInstId = ""
852                         if (serviceInstanceId == null || serviceInstanceId.isEmpty()) {
853                                 svcInstId = vfModuleId
854                         }
855                         else {
856                                 svcInstId = serviceInstanceId
857                         }
858
859                         String assignSDNCRequest = buildSDNCRequest(execution, svcInstId, "assign")
860
861                         assignSDNCRequest = utils.formatXml(assignSDNCRequest)
862                         execution.setVariable("DCVFM_assignSDNCRequest", assignSDNCRequest)
863                         logger.debug("Outgoing AssignSDNCRequest is: \n" + assignSDNCRequest)
864
865                 }catch(Exception e){
866                         logger.error("{} {} {} {} {}", MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(),
867                                         "Exception Occurred Processing preProcessSDNCAssignRequest", "BPMN",
868                                         ErrorCode.UnknownError.getValue(), "Exception is:\n" + e);
869                         exceptionUtil.buildAndThrowWorkflowException(execution, 1002, "Error Occurred during prepareProvision Method:\n" + e.getMessage())
870                 }
871                 logger.trace("COMPLETED preProcessSDNCAssignRequest")
872         }
873
874         public void preProcessSDNCGetRequest(DelegateExecution execution, String element){
875
876                 String sdncVersion = execution.getVariable("DCVFM_sdncVersion")
877                 execution.setVariable("prefix", Prefix)
878                 logger.trace("STARTED preProcessSDNCGetRequest Process")
879                 try{
880                         def serviceInstanceId = execution.getVariable('DCVFM_serviceInstanceId')
881
882                         String uuid = execution.getVariable('testReqId') // for junits
883                         if(uuid==null){
884                                 uuid = execution.getVariable("mso-request-id") + "-" +  System.currentTimeMillis()
885                         }
886
887                         def callbackUrl = execution.getVariable("DCVFM_sdncCallbackUrl")
888                         logger.debug("callbackUrl:" + callbackUrl)
889
890                         def vfModuleId = execution.getVariable('DCVFM_vfModuleId')
891
892                         def svcInstId = ""
893                         if (serviceInstanceId == null || serviceInstanceId.isEmpty()) {
894                                 svcInstId = vfModuleId
895                         }
896                         else {
897                                 svcInstId = serviceInstanceId
898                         }
899
900                         def msoAction = ""
901                         if (!sdncVersion.equals("1707")) {
902                                 msoAction = "mobility"
903                         }
904                         else {
905                                 msoAction = "vfmodule"
906                         }
907                         // For VNF, serviceOperation (URI for topology GET) will be retrieved from "selflink" element
908                         // For VF Module, in 1707 serviceOperation will be retrieved from "object-path" element
909                         // in SDNC Assign Response
910                         // For VF Module for older versions, serviceOperation is constructed using vfModuleId
911
912                         String serviceOperation = ""
913                         if (element.equals("vnf")) {
914                                 AAIResourcesClient resourceClient = new AAIResourcesClient()
915                                 AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIObjectType.GENERIC_VNF, execution.getVariable('DCVFM_vnfId'))
916                                 AAIResultWrapper wrapper = resourceClient.get(uri)
917
918                                 Optional<GenericVnf> vnf = wrapper.asBean(GenericVnf.class)
919                                 serviceOperation = vnf.get().getSelflink()
920                                 logger.debug("VNF - service operation: " + serviceOperation)
921                         }
922                         else if (element.equals("vfmodule")) {
923                                 String response = execution.getVariable("DCVFM_assignSDNCAdapterResponse")
924                                 logger.debug("DCVFM_assignSDNCAdapterResponse is: \n" + response)
925
926                                 if (!sdncVersion.equals("1707")) {
927                                         serviceOperation = "/VNF-API:vnfs/vnf-list/" + vfModuleId
928                                         logger.debug("VF Module with sdncVersion before 1707 - service operation: " + serviceOperation)
929                                 }
930                                 else {
931                                         String data = utils.getNodeXml(response, "response-data")
932                                         logger.debug("responseData: " + data)
933                                         serviceOperation = utils.getNodeText(data, "object-path")
934                                         logger.debug("VF Module with sdncVersion of 1707 - service operation: " + serviceOperation)
935                                 }
936                         }
937
938                         //!!!! TEMPORARY WORKAROUND FOR SDNC REPLICATION ISSUE
939                         sleep(5000)
940
941                         String SDNCGetRequest =
942                                         """<sdncadapterworkflow:SDNCAdapterWorkflowRequest xmlns:ns5="http://org.onap/so/request/types/v1"
943                                                                                         xmlns:sdncadapterworkflow="http://org.onap/so/workflow/schema/v1"
944                                                                                         xmlns:sdncadapter="http://org.onap/workflow/sdnc/adapter/schema/v1">
945                                         <sdncadapter:RequestHeader>
946                                         <sdncadapter:RequestId>${MsoUtils.xmlEscape(uuid)}</sdncadapter:RequestId>
947                                         <sdncadapter:SvcInstanceId>${MsoUtils.xmlEscape(svcInstId)}</sdncadapter:SvcInstanceId>
948                                         <sdncadapter:SvcAction>query</sdncadapter:SvcAction>
949                                         <sdncadapter:SvcOperation>${MsoUtils.xmlEscape(serviceOperation)}</sdncadapter:SvcOperation>
950                                         <sdncadapter:CallbackUrl>${MsoUtils.xmlEscape(callbackUrl)}</sdncadapter:CallbackUrl>
951                                         <sdncadapter:MsoAction>${MsoUtils.xmlEscape(msoAction)}</sdncadapter:MsoAction>
952                                 </sdncadapter:RequestHeader>
953                                         <sdncadapterworkflow:SDNCRequestData></sdncadapterworkflow:SDNCRequestData>
954                                 </sdncadapterworkflow:SDNCAdapterWorkflowRequest>"""
955
956                         execution.setVariable("DCVFM_getSDNCRequest", SDNCGetRequest)
957                         logger.debug("Outgoing GetSDNCRequest is: \n" + SDNCGetRequest)
958
959                 }catch(Exception e){
960                         logger.error("{} {} {} {} {}", MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(),
961                                         "Exception Occurred Processing preProcessSDNCGetRequest", "BPMN",
962                                         ErrorCode.UnknownError.getValue(), "Exception is:\n" + e);
963                         exceptionUtil.buildAndThrowWorkflowException(execution, 1002, "Error Occured during prepareProvision Method:\n" + e.getMessage())
964                 }
965                 logger.trace("COMPLETED preProcessSDNCGetRequest Process")
966         }
967
968
969         public void preProcessVNFAdapterRequest(DelegateExecution execution) {
970                 def method = getClass().getSimpleName() + '.VNFAdapterCreateVfModule(' +
971                         'execution=' + execution.getId() +
972                         ')'
973
974                 logger.trace('Entered ' + method)
975
976                 //def xml = execution.getVariable("DoCreateVfModuleRequest")
977                 //logger.debug('VNF REQUEST is: ' + xml)
978
979                 //Get variables
980                 //cloudSiteId
981                 def cloudSiteId = execution.getVariable("DCVFM_cloudSiteId")
982                 //cloudOwner
983                 def cloudOwner = execution.getVariable("DCVFM_cloudOwner")
984                 //tenantId
985                 def tenantId = execution.getVariable("DCVFM_tenantId")
986                 //vnfType
987                 def vnfType = execution.getVariable("DCVFM_vnfType")
988                 //vnfName
989                 def vnfName = execution.getVariable("DCVFM_vnfName")
990                 //vnfId
991                 def vnfId = execution.getVariable("DCVFM_vnfId")
992                 //vfModuleName
993                 def vfModuleName = execution.getVariable("DCVFM_vfModuleName")
994                 //vfModuleModelName
995                 def vfModuleModelName = execution.getVariable("DCVFM_vfModuleModelName")
996                 //vfModuleId
997                 def vfModuleId = execution.getVariable("DCVFM_vfModuleId")
998                 //vfModuleIndex
999                 def vfModuleIndex = execution.getVariable("DCVFM_vfModuleIndex")
1000                 //requestId
1001                 def requestId = execution.getVariable("DCVFM_requestId")
1002                 //serviceId
1003                 def serviceId = execution.getVariable("DCVFM_serviceId")
1004                 //serviceInstanceId
1005                 def serviceInstanceId = execution.getVariable("DCVFM_serviceInstanceId")
1006                 //backoutOnFailure
1007                 def backoutOnFailure = execution.getVariable("DCVFM_backoutOnFailure")
1008                 //volumeGroupId
1009                 def volumeGroupId = execution.getVariable("DCVFM_volumeGroupId")
1010                 // baseVfModuleId
1011                 def baseVfModuleId = execution.getVariable("DCVFM_baseVfModuleId")
1012                 // baseVfModuleStackId
1013                 def baseVfModuleStackId = execution.getVariable("DCVFM_baseVfModuleHeatStackId")
1014                 // asdcServiceModelVersion
1015                 def asdcServiceModelVersion = execution.getVariable("DCVFM_asdcServiceModelVersion")
1016                 //volumeGroupStackId
1017                 def volumeGroupStackId = execution.getVariable("DCVFM_volumeGroupStackId")
1018                 //modelCustomizationUuid
1019                 def modelCustomizationUuid = execution.getVariable("DCVFM_modelCustomizationUuid")
1020                 //environmentContext
1021                 String environmentContext = execution.getVariable("DCVFM_environmentContext")
1022                 //workloadContext
1023                 String workloadContext = execution.getVariable("DCVFM_workloadContext")
1024                 logger.debug("workloadContext: " + workloadContext)
1025                 logger.debug("environmentContext: " + environmentContext)
1026
1027                 def messageId = execution.getVariable('mso-request-id') + '-' +
1028                                 System.currentTimeMillis()
1029
1030                 def notificationUrl = createCallbackURL(execution, "VNFAResponse", messageId)
1031                 def useQualifiedHostName = UrnPropertiesReader.getVariable("mso.use.qualified.host",execution)
1032
1033                 logger.debug("notificationUrl: " + notificationUrl)
1034                 logger.debug("QualifiedHostName: " + useQualifiedHostName)
1035
1036                 if ('true'.equals(useQualifiedHostName)) {
1037                         notificationUrl = utils.getQualifiedHostNameForCallback(notificationUrl)
1038                 }
1039
1040                 Map<String, String> vnfParamsMap = execution.getVariable("DCVFM_vnfParamsMap")
1041                 String vfModuleParams = ""
1042                 //Get SDNC Response Data for VF Module Topology
1043                 String vfModuleSdncGetResponse = execution.getVariable('DCVFM_getSDNCAdapterResponse')
1044                 logger.debug("sdncGetResponse: " + vfModuleSdncGetResponse)
1045                 def sdncVersion = execution.getVariable("sdncVersion")
1046
1047                 if (!sdncVersion.equals("1707")) {
1048
1049                         vfModuleParams = buildVfModuleParams(vnfParamsMap, vfModuleSdncGetResponse, vnfId, vnfName,
1050                                 vfModuleId, vfModuleName, vfModuleIndex, environmentContext, workloadContext)
1051                 }
1052                 else {
1053                         //Get SDNC Response Data for Vnf Topology
1054                         String vnfSdncGetResponse = execution.getVariable('DCVFM_getVnfSDNCAdapterResponse')
1055                         logger.debug("vnfSdncGetResponse: " + vnfSdncGetResponse)
1056
1057                         vfModuleParams = buildVfModuleParamsFromCombinedTopologies(vnfParamsMap, vnfSdncGetResponse, vfModuleSdncGetResponse, vnfId, vnfName,
1058                                 vfModuleId, vfModuleName, vfModuleIndex, environmentContext, workloadContext)
1059                 }
1060
1061                 def svcInstId = ""
1062                 if (serviceInstanceId == null || serviceInstanceId.isEmpty()) {
1063                                 svcInstId = serviceId
1064                 }
1065                 else {
1066                         svcInstId = serviceInstanceId
1067                 }
1068
1069                 String createVnfARequest = """
1070                 <createVfModuleRequest>
1071                 <cloudSiteId>${MsoUtils.xmlEscape(cloudSiteId)}</cloudSiteId>
1072                 <cloudOwner>${MsoUtils.xmlEscape(cloudOwner)}</cloudOwner>
1073                 <tenantId>${MsoUtils.xmlEscape(tenantId)}</tenantId>
1074                 <vnfId>${MsoUtils.xmlEscape(vnfId)}</vnfId>
1075                 <vnfName>${MsoUtils.xmlEscape(vnfName)}</vnfName>
1076                 <vfModuleName>${MsoUtils.xmlEscape(vfModuleName)}</vfModuleName>
1077                 <vfModuleId>${MsoUtils.xmlEscape(vfModuleId)}</vfModuleId>
1078                 <vnfType>${MsoUtils.xmlEscape(vnfType)}</vnfType>
1079                 <vfModuleType>${MsoUtils.xmlEscape(vfModuleModelName)}</vfModuleType>
1080                 <vnfVersion>${MsoUtils.xmlEscape(asdcServiceModelVersion)}</vnfVersion>
1081                 <modelCustomizationUuid>${MsoUtils.xmlEscape(modelCustomizationUuid)}</modelCustomizationUuid>
1082                 <requestType></requestType>
1083                 <volumeGroupId>${MsoUtils.xmlEscape(volumeGroupId)}</volumeGroupId>
1084         <volumeGroupStackId>${MsoUtils.xmlEscape(volumeGroupStackId)}</volumeGroupStackId>
1085         <baseVfModuleId>${MsoUtils.xmlEscape(baseVfModuleId)}</baseVfModuleId>
1086         <baseVfModuleStackId>${MsoUtils.xmlEscape(baseVfModuleStackId)}</baseVfModuleStackId>
1087         <skipAAI>true</skipAAI>
1088         <backout>${MsoUtils.xmlEscape(backoutOnFailure)}</backout>
1089         <failIfExists>true</failIfExists>
1090                 <vfModuleParams>
1091                 ${vfModuleParams}
1092                 </vfModuleParams>
1093                 <msoRequest>
1094                         <requestId>${MsoUtils.xmlEscape(requestId)}</requestId>
1095                         <serviceInstanceId>${MsoUtils.xmlEscape(svcInstId)}</serviceInstanceId>
1096                 </msoRequest>
1097                 <messageId>${MsoUtils.xmlEscape(messageId)}</messageId>
1098                 <notificationUrl>${MsoUtils.xmlEscape(notificationUrl)}</notificationUrl>
1099                 </createVfModuleRequest>"""
1100
1101                 logger.debug("Create VfModule Request to VNF Adapter: " + createVnfARequest)
1102                 execution.setVariable("DCVFM_createVnfARequest", createVnfARequest)
1103         }
1104
1105         /**
1106          * Validates the request, request id and service instance id.  If a problem is found,
1107          * a WorkflowException is generated and an MSOWorkflowException event is thrown. This
1108          * method also sets up the log context for the workflow.
1109          * @param execution the execution
1110          * @return the validated request
1111          */
1112         public String validateInfraRequest(DelegateExecution execution) {
1113                 def method = getClass().getSimpleName() + '.validateInfraRequest(' +
1114                         'execution=' + execution.getId() +
1115                         ')'
1116
1117                 logger.trace('Entered ' + method)
1118
1119                 String processKey = getProcessKey(execution);
1120                 def prefix = execution.getVariable("prefix")
1121
1122                 if (prefix == null) {
1123                         exceptionUtil.buildAndThrowWorkflowException(execution, 1002, processKey + " prefix is null")
1124                 }
1125
1126                 try {
1127                         def request = execution.getVariable(prefix + 'Request')
1128
1129                         if (request == null) {
1130                                 request = execution.getVariable(processKey + 'Request')
1131
1132                                 if (request == null) {
1133                                         request = execution.getVariable('bpmnRequest')
1134                                 }
1135
1136                                 setVariable(execution, processKey + 'Request', null);
1137                                 setVariable(execution, 'bpmnRequest', null);
1138                                 setVariable(execution, prefix + 'Request', request);
1139                         }
1140
1141                         if (request == null) {
1142                                 exceptionUtil.buildAndThrowWorkflowException(execution, 1002, processKey + " request is null")
1143                         }
1144                         logger.debug("DoCreateVfModule Request: " + request)
1145
1146                         /*
1147
1148                         def requestId = execution.getVariable("mso-request-id")
1149
1150                         if (requestId == null) {
1151                                 exceptionUtil.buildAndThrowWorkflowException(execution, 1002, processKey + " request has no mso-request-id")
1152                         }
1153
1154                         def serviceInstanceId = execution.getVariable("mso-service-instance-id")
1155
1156                         if (serviceInstanceId == null) {
1157                                 exceptionUtil.buildAndThrowWorkflowException(execution, 1002, processKey + " request message has no mso-service-instance-id")
1158                         }
1159
1160                         utils.logContext(requestId, serviceInstanceId)
1161                         */
1162                         logger.debug('Incoming message: ' + System.lineSeparator() + request)
1163                         logger.trace('Exited ' + method)
1164                         return request
1165                 } catch (BpmnError e) {
1166                         throw e;
1167                 } catch (Exception e) {
1168                         logger.error("{} {} {} {} {}", MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(),
1169                                         'Caught exception in ' + method, "BPMN",
1170                                         ErrorCode.UnknownError.getValue(), "Exception is:\n" + e);
1171                         exceptionUtil.buildAndThrowWorkflowException(execution, 1002, "Invalid Message")
1172                 }
1173         }
1174
1175         public boolean isVolumeGroupIdPresent(DelegateExecution execution) {
1176
1177                 def method = getClass().getSimpleName() + '.isVolumeGroupIdPresent(' +
1178                         'execution=' + execution.getId() +
1179                         ')'
1180
1181                 logger.trace('Entered ' + method)
1182
1183                 def request = execution.getVariable('DoCreateVfModuleRequest')
1184                 String volumeGroupId = utils.getNodeText(request, "volume-group-id")
1185                 if (volumeGroupId == null || volumeGroupId.isEmpty()) {
1186                         logger.debug('No volume group id is present')
1187                         return false
1188                 }
1189                 else {
1190                         logger.debug('Volume group id is present')
1191                         return true
1192                 }
1193
1194         }
1195
1196         public boolean isVolumeGroupNamePresent(DelegateExecution execution) {
1197
1198                 def method = getClass().getSimpleName() + '.isVolumeGroupNamePresent(' +
1199                         'execution=' + execution.getId() +
1200                         ')'
1201
1202                 logger.trace('Entered ' + method)
1203
1204                 def request = execution.getVariable('DoCreateVfModuleRequest')
1205                 String volumeGroupName = utils.getNodeText(request, "volume-group-name")
1206                 if (volumeGroupName == null || volumeGroupName.isEmpty()) {
1207                         logger.debug('No volume group name is present')
1208                         return false
1209                 }
1210                 else {
1211                         logger.debug('Volume group name is present')
1212                         return true
1213                 }
1214
1215         }
1216
1217         public String buildSDNCRequest(DelegateExecution execution, String svcInstId, String action){
1218
1219                 String uuid = execution.getVariable('testReqId') // for junits
1220                 if(uuid==null){
1221                         uuid = execution.getVariable("mso-request-id") + "-" +          System.currentTimeMillis()
1222                 }
1223                 def callbackURL = execution.getVariable("DCVFM_sdncCallbackUrl")
1224                 def requestId = execution.getVariable("DCVFM_requestId")
1225                 def serviceId = execution.getVariable("DCVFM_serviceId")
1226                 def vnfType = execution.getVariable("DCVFM_vnfType")
1227                 def vnfName = execution.getVariable("DCVFM_vnfName")
1228                 def tenantId = execution.getVariable("DCVFM_tenantId")
1229                 def source = execution.getVariable("DCVFM_source")
1230                 def backoutOnFailure = execution.getVariable("DCVFM_backoutOnFailure")
1231                 def vfModuleId = execution.getVariable("DCVFM_vfModuleId")
1232                 def vfModuleName = execution.getVariable("DCVFM_vfModuleName")
1233                 def vfModuleModelName = execution.getVariable("DCVFM_vfModuleModelName")
1234                 def vnfId = execution.getVariable("DCVFM_vnfId")
1235                 def cloudSiteId = execution.getVariable("DCVFM_cloudSiteId")
1236                 def cloudOwner = execution.getVariable("DCVFM_cloudOwner")
1237                 def sdncVersion = execution.getVariable("DCVFM_sdncVersion")
1238                 def serviceModelInfo = execution.getVariable("serviceModelInfo")
1239                 def vnfModelInfo = execution.getVariable("vnfModelInfo")
1240                 def vfModuleModelInfo = execution.getVariable("vfModuleModelInfo")
1241                 String serviceEcompModelInformation = sdncAdapterUtils.modelInfoToEcompModelInformation(serviceModelInfo)
1242                 String vnfEcompModelInformation = sdncAdapterUtils.modelInfoToEcompModelInformation(vnfModelInfo)
1243                 String vfModuleEcompModelInformation = sdncAdapterUtils.modelInfoToEcompModelInformation(vfModuleModelInfo)
1244                 def globalSubscriberId = execution.getVariable("DCVFM_globalSubscriberId")
1245                 boolean usePreload = execution.getVariable("DCVFM_usePreload")
1246                 String usePreloadToSDNC = usePreload ? "Y" : "N"
1247                 def modelCustomizationUuid = execution.getVariable("DCVFM_modelCustomizationUuid")
1248                 def modelCustomizationUuidString = ""
1249                 if (!usePreload) {
1250                         modelCustomizationUuidString = "<model-customization-uuid>" + modelCustomizationUuid + "</model-customization-uuid>"
1251                 }
1252
1253                 String sdncVNFParamsXml = ""
1254
1255                 if(execution.getVariable("DCVFM_vnfParamsExistFlag") == true){
1256                         if (!sdncVersion.equals("1707")) {
1257                                 sdncVNFParamsXml = buildSDNCParamsXml(execution)
1258                         }
1259                         else {
1260                                 sdncVNFParamsXml = buildCompleteSDNCParamsXml(execution)
1261                         }
1262                 }else{
1263                         sdncVNFParamsXml = ""
1264                 }
1265
1266                 String sdncRequest = ""
1267
1268                 if (!sdncVersion.equals("1707")) {
1269
1270                         sdncRequest =
1271                 """<sdncadapterworkflow:SDNCAdapterWorkflowRequest xmlns:ns5="http://org.onap/so/request/types/v1"
1272                                                                                                         xmlns:sdncadapterworkflow="http://org.onap/so/workflow/schema/v1"
1273                                                                                                         xmlns:sdncadapter="http://org.onap/workflow/sdnc/adapter/schema/v1">
1274            <sdncadapter:RequestHeader>
1275                                 <sdncadapter:RequestId>${MsoUtils.xmlEscape(uuid)}</sdncadapter:RequestId>
1276                                 <sdncadapter:SvcInstanceId>${MsoUtils.xmlEscape(svcInstId)}</sdncadapter:SvcInstanceId>
1277                                 <sdncadapter:SvcAction>${MsoUtils.xmlEscape(action)}</sdncadapter:SvcAction>
1278                                 <sdncadapter:SvcOperation>vnf-topology-operation</sdncadapter:SvcOperation>
1279                                 <sdncadapter:CallbackUrl>${MsoUtils.xmlEscape(callbackURL)}</sdncadapter:CallbackUrl>
1280                 </sdncadapter:RequestHeader>
1281         <sdncadapterworkflow:SDNCRequestData>
1282                 <request-information>
1283                         <request-id>${MsoUtils.xmlEscape(requestId)}</request-id>
1284                         <request-action>VNFActivateRequest</request-action>
1285                         <source>${MsoUtils.xmlEscape(source)}</source>
1286                         <notification-url/>
1287                 </request-information>
1288                 <service-information>
1289                         <service-id>${MsoUtils.xmlEscape(serviceId)}</service-id>
1290                         <service-type>${MsoUtils.xmlEscape(serviceId)}</service-type>
1291                         <service-instance-id>${MsoUtils.xmlEscape(svcInstId)}</service-instance-id>
1292                         <subscriber-name>notsurewecare</subscriber-name>
1293                 </service-information>
1294                 <vnf-request-information>
1295                         <vnf-id>${MsoUtils.xmlEscape(vfModuleId)}</vnf-id>
1296                         <vnf-type>${MsoUtils.xmlEscape(vfModuleModelName)}</vnf-type>
1297                         <vnf-name>${MsoUtils.xmlEscape(vfModuleName)}</vnf-name>
1298                         <generic-vnf-id>${MsoUtils.xmlEscape(vnfId)}</generic-vnf-id>
1299                         <generic-vnf-name>${MsoUtils.xmlEscape(vnfName)}</generic-vnf-name>
1300                         <generic-vnf-type>${MsoUtils.xmlEscape(vnfType)}</generic-vnf-type>
1301                         <aic-cloud-region>${MsoUtils.xmlEscape(cloudSiteId)}</aic-cloud-region>
1302                         <tenant>${MsoUtils.xmlEscape(tenantId)}</tenant>
1303                         ${modelCustomizationUuidString}
1304                         <use-preload>${MsoUtils.xmlEscape(usePreloadToSDNC)}</use-preload>
1305                 ${sdncVNFParamsXml}
1306                 </vnf-request-information>
1307         </sdncadapterworkflow:SDNCRequestData>
1308         </sdncadapterworkflow:SDNCAdapterWorkflowRequest>"""
1309
1310                 }
1311                 else {
1312
1313                         sdncRequest =
1314                         """<sdncadapterworkflow:SDNCAdapterWorkflowRequest xmlns:ns5="http://org.onap/so/request/types/v1"
1315                                                                                                         xmlns:sdncadapterworkflow="http://org.onap/so/workflow/schema/v1"
1316                                                                                                         xmlns:sdncadapter="http://org.onap/workflow/sdnc/adapter/schema/v1">
1317            <sdncadapter:RequestHeader>
1318                                 <sdncadapter:RequestId>${MsoUtils.xmlEscape(uuid)}</sdncadapter:RequestId>
1319                                 <sdncadapter:SvcInstanceId>${MsoUtils.xmlEscape(svcInstId)}</sdncadapter:SvcInstanceId>
1320                                 <sdncadapter:SvcAction>${MsoUtils.xmlEscape(action)}</sdncadapter:SvcAction>
1321                                 <sdncadapter:SvcOperation>vf-module-topology-operation</sdncadapter:SvcOperation>
1322                                 <sdncadapter:CallbackUrl>${MsoUtils.xmlEscape(callbackURL)}</sdncadapter:CallbackUrl>
1323                                 <sdncadapter:MsoAction>generic-resource</sdncadapter:MsoAction>
1324                 </sdncadapter:RequestHeader>
1325         <sdncadapterworkflow:SDNCRequestData>
1326                 <request-information>
1327                         <request-id>${MsoUtils.xmlEscape(requestId)}</request-id>
1328                         <request-action>CreateVfModuleInstance</request-action>
1329                         <source>${MsoUtils.xmlEscape(source)}</source>
1330                         <notification-url/>
1331                 </request-information>
1332                 <service-information>
1333                         <service-id>${MsoUtils.xmlEscape(serviceId)}</service-id>
1334                         <subscription-service-type>${MsoUtils.xmlEscape(serviceId)}</subscription-service-type>
1335                         ${serviceEcompModelInformation}
1336                         <service-instance-id>${MsoUtils.xmlEscape(svcInstId)}</service-instance-id>
1337                         <global-customer-id>${MsoUtils.xmlEscape(globalSubscriberId)}</global-customer-id>
1338                 </service-information>
1339                 <vnf-information>
1340                         <vnf-id>${MsoUtils.xmlEscape(vnfId)}</vnf-id>
1341                         <vnf-type>${MsoUtils.xmlEscape(vnfType)}</vnf-type>
1342                         ${vnfEcompModelInformation}
1343                 </vnf-information>
1344                 <vf-module-information>
1345                         <vf-module-id>${MsoUtils.xmlEscape(vfModuleId)}</vf-module-id>
1346                         <vf-module-type>${MsoUtils.xmlEscape(vfModuleModelName)}</vf-module-type>
1347                         ${vfModuleEcompModelInformation}
1348                 </vf-module-information>
1349                 <vf-module-request-input>
1350                         <vf-module-name>${MsoUtils.xmlEscape(vfModuleName)}</vf-module-name>
1351                         <tenant>${MsoUtils.xmlEscape(tenantId)}</tenant>
1352                         <aic-cloud-region>${MsoUtils.xmlEscape(cloudSiteId)}</aic-cloud-region>
1353                 ${sdncVNFParamsXml}
1354                 </vf-module-request-input>
1355           </sdncadapterworkflow:SDNCRequestData>
1356         </sdncadapterworkflow:SDNCAdapterWorkflowRequest>"""
1357
1358
1359                         /*
1360                         sdncRequest =
1361                         """<sdncadapterworkflow:SDNCAdapterWorkflowRequest xmlns:ns5="http://org.onap/so/request/types/v1"
1362                                                                                                         xmlns:sdncadapterworkflow="http://org.onap/so/workflow/schema/v1"
1363                                                                                                         xmlns:sdncadapter="http://org.onap/workflow/sdnc/adapter/schema/v1">
1364            <sdncadapter:RequestHeader>
1365                                 <sdncadapter:RequestId>${MsoUtils.xmlEscape(requestId)}</sdncadapter:RequestId>
1366                                 <sdncadapter:SvcInstanceId>${MsoUtils.xmlEscape(svcInstId)}</sdncadapter:SvcInstanceId>
1367                                 <sdncadapter:SvcAction>${MsoUtils.xmlEscape(action)}</sdncadapter:SvcAction>
1368                                 <sdncadapter:SvcOperation>vnf-topology-operation</sdncadapter:SvcOperation>
1369                                 <sdncadapter:CallbackUrl>${MsoUtils.xmlEscape(callbackURL)}</sdncadapter:CallbackUrl>
1370                 </sdncadapter:RequestHeader>
1371         <sdncadapterworkflow:SDNCRequestData>
1372                 <request-information>
1373                         <request-id>${MsoUtils.xmlEscape(requestId)}</request-id>
1374                         <request-action>CreateVfModuleInstance</request-action>
1375                         <source>${MsoUtils.xmlEscape(source)}</source>
1376                         <notification-url/>
1377                 </request-information>
1378                 <service-information>
1379                         <service-id>${MsoUtils.xmlEscape(serviceId)}</service-id>
1380                         <service-type>${MsoUtils.xmlEscape(serviceId)}</service-type>
1381                         ${serviceEcompModelInformation}
1382                         <service-instance-id>${MsoUtils.xmlEscape(svcInstId)}</service-instance-id>
1383                         <global-customer-id>${MsoUtils.xmlEscape(globalSubscriberId)}</global-customer-id>
1384                 </service-information>
1385                 <vnf-information>
1386                         <vnf-id>${MsoUtils.xmlEscape(vnfId)}</vnf-id>
1387                         <vnf-type>${MsoUtils.xmlEscape(vnfType)}</vnf-type>
1388                         ${vnfEcompModelInformation}
1389                 </vnf-information>
1390                 <vf-module-information>
1391                         <vf-module-id>${MsoUtils.xmlEscape(vfModuleId)}</vf-module-id>
1392                         <vf-module-type>${MsoUtils.xmlEscape(vfModuleModelName)}</vf-module-type>
1393                         ${vfModuleEcompModelInformation}
1394                 </vf-module-information>
1395                 <vf-module-request-input>
1396                         <vf-module-name>${MsoUtils.xmlEscape(vfModuleName)}</vf-module-name>
1397                         <tenant>${MsoUtils.xmlEscape(tenantId)}</tenant>
1398                         <aic-cloud-region>${MsoUtils.xmlEscape(cloudSiteId)}</aic-cloud-region>
1399                 ${sdncVNFParamsXml}
1400                 </vf-module-request-input>
1401         </sdncadapterworkflow:SDNCRequestData>
1402         </sdncadapterworkflow:SDNCAdapterWorkflowRequest>"""
1403                         */
1404
1405                 }
1406
1407         logger.debug("sdncRequest:  " + sdncRequest)
1408         return sdncRequest
1409
1410         }
1411
1412         public void preProcessSDNCActivateRequest(DelegateExecution execution) {
1413                 def method = getClass().getSimpleName() + '.preProcessSDNCActivateRequest(' +
1414                         'execution=' + execution.getId() +
1415                         ')'
1416
1417                 logger.trace('Entered ' + method)
1418                 execution.setVariable("prefix", Prefix)
1419                 logger.trace("STARTED preProcessSDNCActivateRequest Process")
1420                 try{
1421                         String vnfId = execution.getVariable("DCVFM_vnfId")
1422                         String vfModuleId = execution.getVariable("DCVFM_vfModuleId")
1423                         String serviceInstanceId = execution.getVariable("DCVFM_serviceInstanceId")
1424
1425                         def svcInstId = ""
1426                         if (serviceInstanceId == null || serviceInstanceId.isEmpty()) {
1427                                 svcInstId = vfModuleId
1428                         }
1429                         else {
1430                                 svcInstId = serviceInstanceId
1431                         }
1432                         String activateSDNCRequest = buildSDNCRequest(execution, svcInstId, "activate")
1433
1434                         execution.setVariable("DCVFM_activateSDNCRequest", activateSDNCRequest)
1435                         logger.debug("Outgoing CommitSDNCRequest is: \n" + activateSDNCRequest)
1436
1437                 }catch(Exception e){
1438                         logger.debug("Exception Occured Processing preProcessSDNCActivateRequest. Exception is:\n" + e)
1439                         exceptionUtil.buildAndThrowWorkflowException(execution, 1002, "Error Occured during  preProcessSDNCActivateRequest Method:\n" + e.getMessage())
1440                 }
1441                 logger.trace("COMPLETED  preProcessSDNCActivateRequest Process")
1442         }
1443
1444         public void postProcessVNFAdapterRequest(DelegateExecution execution) {
1445                 def method = getClass().getSimpleName() + '.postProcessVNFAdapterRequest(' +
1446                         'execution=' + execution.getId() +
1447                         ')'
1448
1449                 logger.trace('Entered ' + method)
1450                 execution.setVariable("prefix",Prefix)
1451                 try{
1452                 logger.debug("STARTED postProcessVNFAdapterRequest Process")
1453
1454                 String vnfResponse = execution.getVariable("DCVFM_createVnfAResponse")
1455                 logger.debug("VNF Adapter Response is: " + vnfResponse)
1456
1457                 RollbackData rollbackData = execution.getVariable("rollbackData")
1458                 if(vnfResponse != null){
1459
1460                         if(vnfResponse.contains("createVfModuleResponse")){
1461                                 logger.debug("Received a Good Response from VNF Adapter for CREATE_VF_MODULE Call.")
1462                                 execution.setVariable("DCVFM_vnfVfModuleCreateCompleted", true)
1463                                 String heatStackId = utils.getNodeText(vnfResponse, "vfModuleStackId")
1464                                 execution.setVariable("DCVFM_heatStackId", heatStackId)
1465                                 logger.debug("Received heat stack id from VNF Adapter: " + heatStackId)
1466                                 rollbackData.put("VFMODULE", "heatstackid", heatStackId)
1467                                 // Parse vnfOutputs for network_fqdn
1468                                 if (vnfResponse.contains("vfModuleOutputs")) {
1469                                         def vfModuleOutputsXml = utils.getNodeXml(vnfResponse, "vfModuleOutputs")
1470                                         InputSource source = new InputSource(new StringReader(vfModuleOutputsXml));
1471                         DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
1472                         docFactory.setNamespaceAware(true)
1473                         DocumentBuilder docBuilder = docFactory.newDocumentBuilder()
1474                         Document outputsXml = docBuilder.parse(source)
1475
1476                                         NodeList entries = outputsXml.getElementsByTagNameNS("*", "entry")
1477                                         List contrailNetworkPolicyFqdnList = []
1478                                         for (int i = 0; i< entries.getLength(); i++) {
1479                                                 Node node = entries.item(i)
1480                                                 if (node.getNodeType() == Node.ELEMENT_NODE) {
1481                                                         Element element = (Element) node
1482                                                         String key = element.getElementsByTagNameNS("*", "key").item(0).getTextContent()
1483                                                         if (key.equals("contrail-service-instance-fqdn")) {
1484                                                                 String contrailServiceInstanceFqdn = element.getElementsByTagNameNS("*", "value").item(0).getTextContent()
1485                                                                 logger.debug("Obtained contrailServiceInstanceFqdn: " + contrailServiceInstanceFqdn)
1486                                                                 execution.setVariable("DCVFM_contrailServiceInstanceFqdn", contrailServiceInstanceFqdn)
1487                                                         }
1488                                                         else if (key.endsWith("contrail_network_policy_fqdn")) {
1489                                                                 String contrailNetworkPolicyFqdn = element.getElementsByTagNameNS("*", "value").item(0).getTextContent()
1490                                                                 logger.debug("Obtained contrailNetworkPolicyFqdn: " + contrailNetworkPolicyFqdn)
1491                                                                 contrailNetworkPolicyFqdnList.add(contrailNetworkPolicyFqdn)
1492                                                         }
1493                                                         else if (key.equals("oam_management_v4_address")) {
1494                                                                 String oamManagementV4Address = element.getElementsByTagNameNS("*", "value").item(0).getTextContent()
1495                                                                 logger.debug("Obtained oamManagementV4Address: " + oamManagementV4Address)
1496                                                                 execution.setVariable("DCVFM_oamManagementV4Address", oamManagementV4Address)
1497                                                         }
1498                                                         else if (key.equals("oam_management_v6_address")) {
1499                                                                 String oamManagementV6Address = element.getElementsByTagNameNS("*", "value").item(0).getTextContent()
1500                                                                 logger.debug("Obtained oamManagementV6Address: " + oamManagementV6Address)
1501                                                                 execution.setVariable("DCVFM_oamManagementV6Address", oamManagementV6Address)
1502                                                         }
1503
1504                                                 }
1505                                         }
1506                                         if (!contrailNetworkPolicyFqdnList.isEmpty()) {
1507                                                 execution.setVariable("DCVFM_contrailNetworkPolicyFqdnList", contrailNetworkPolicyFqdnList)
1508                                         }
1509                                 }
1510                         }else{
1511                                 logger.debug("Received a BAD Response from VNF Adapter for CREATE_VF_MODULE Call.")
1512                                 exceptionUtil.buildAndThrowWorkflowException(execution, 1002, "VNF Adapter Error")
1513                         }
1514                 }else{
1515                         logger.debug("Response from VNF Adapter is Null for CREATE_VF_MODULE Call.")
1516                         exceptionUtil.buildAndThrowWorkflowException(execution, 1002, "Empty response from VNF Adapter")
1517                 }
1518
1519                 rollbackData.put("VFMODULE", "rollbackVnfAdapterCreate", "true")
1520                 execution.setVariable("rollbackData", rollbackData)
1521
1522                 }catch(BpmnError b){
1523                         throw b
1524                 }catch(Exception e){
1525                         logger.debug("Internal Error Occured in PostProcess Method")
1526                         exceptionUtil.buildAndThrowWorkflowException(execution, 1002, "Internal Error Occured in PostProcess Method")
1527                 }
1528                 logger.trace("COMPLETED postProcessVnfAdapterResponse Process")
1529         }
1530
1531
1532         public void preProcessUpdateAAIVfModuleRequestOrch(DelegateExecution execution) {
1533                 def method = getClass().getSimpleName() + '.preProcessUpdateAAIVfModuleRequestOrch(' +
1534                         'execution=' + execution.getId() +
1535                         ')'
1536
1537                 logger.trace('Entered ' + method)
1538                 execution.setVariable("prefix", Prefix)
1539                 logger.trace("STARTED preProcessUpdateAAIVfModuleRequestOrch")
1540
1541                 try{
1542
1543                         //Build UpdateAAIVfModule Request
1544                         boolean setContrailServiceInstanceFqdn = false
1545                         def contrailServiceInstanceFqdn = execution.getVariable("DCVFM_contrailServiceInstanceFqdn")
1546                         if (!contrailServiceInstanceFqdn.equals("")) {
1547                                 setContrailServiceInstanceFqdn = true
1548                         }
1549
1550                         execution.setVariable("DCVFM_orchestrationStatus", "Created")
1551
1552                         String updateAAIVfModuleRequest = buildUpdateAAIVfModuleRequest(execution, false, true, true, setContrailServiceInstanceFqdn)
1553
1554                         updateAAIVfModuleRequest = utils.formatXml(updateAAIVfModuleRequest)
1555                         execution.setVariable("DCVFM_updateAAIVfModuleRequest", updateAAIVfModuleRequest)
1556                         logger.debug("Outgoing UpdateAAIVfModuleRequest is: \n" + updateAAIVfModuleRequest)
1557
1558                 }catch(Exception e){
1559                         logger.error("{} {} {} {} {}", MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(),
1560                                         "Exception Occured Processing preProcessUpdateAAIVfModuleRequestOrch", "BPMN",
1561                                         ErrorCode.UnknownError.getValue(), "Exception is:\n" + e);
1562                         exceptionUtil.buildAndThrowWorkflowException(execution, 1002, "Error Occured during preProcessUpdateAAIVfModuleRequestOrch Method:\n" + e.getMessage())
1563                 }
1564                 logger.trace("COMPLETED preProcessUpdateAAIVfModuleRequestOrch")
1565
1566         }
1567
1568         public void preProcessUpdateAAIVfModuleRequestStatus(DelegateExecution execution, String status) {
1569                 def method = getClass().getSimpleName() + '.preProcessUpdateAAIVfModuleStatus(' +
1570                         'execution=' + execution.getId() +
1571                         ')'
1572
1573                 logger.trace('Entered ' + method)
1574                 execution.setVariable("prefix", Prefix)
1575                 logger.trace("STARTED preProcessUpdateAAIVfModuleStatus")
1576
1577                 try{
1578
1579                         //Build UpdateAAIVfModule Request
1580                         execution.setVariable("DCVFM_orchestrationStatus", status)
1581
1582                         String updateAAIVfModuleRequest = buildUpdateAAIVfModuleRequest(execution, false, true, false, false)
1583
1584                         updateAAIVfModuleRequest = utils.formatXml(updateAAIVfModuleRequest)
1585                         execution.setVariable("DCVFM_updateAAIVfModuleRequest", updateAAIVfModuleRequest)
1586                         logger.debug("Outgoing UpdateAAIVfModuleRequest is: \n" + updateAAIVfModuleRequest)
1587
1588                 }catch(Exception e){
1589                         logger.error("{} {} {} {} {}", MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(),
1590                                         "Exception Occured Processing preProcessUpdateAAIVfModuleStatus", "BPMN",
1591                                         ErrorCode.UnknownError.getValue(), "Exception is:\n" + e);
1592                         exceptionUtil.buildAndThrowWorkflowException(execution, 1002, "Error Occured during preProcessUpdateAAIVfModuleStatus Method:\n" + e.getMessage())
1593                 }
1594                 logger.trace("COMPLETED preProcessUpdateAAIVfModuleStatus")
1595
1596         }
1597
1598
1599         public void preProcessUpdateAAIVfModuleRequestGroup(DelegateExecution execution) {
1600                 def method = getClass().getSimpleName() + '.preProcessUpdateAAIVfModuleRequestGroup(' +
1601                         'execution=' + execution.getId() +
1602                         ')'
1603
1604                 logger.trace('Entered ' + method)
1605                 execution.setVariable("prefix", Prefix)
1606                 logger.trace("STARTED preProcessUpdateAAIVfModuleRequestGroup")
1607
1608                 try{
1609
1610                         //Build UpdateAAIVfModule Request
1611
1612                         String updateAAIVfModuleRequest = buildUpdateAAIVfModuleRequest(execution, true, false, false, false)
1613
1614                         updateAAIVfModuleRequest = utils.formatXml(updateAAIVfModuleRequest)
1615                         execution.setVariable("DCVFM_updateAAIVfModuleRequest", updateAAIVfModuleRequest)
1616                         logger.debug("Outgoing UpdateAAIVfModuleRequest is: \n" + updateAAIVfModuleRequest)
1617
1618                 }catch(Exception e){
1619                         logger.error("{} {} {} {} {}", MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(),
1620                                         "Exception Occured Processing preProcessUpdateAAIVfModuleRequestGroup", "BPMN",
1621                                         ErrorCode.UnknownError.getValue(), "Exception is:\n" + e);
1622                         exceptionUtil.buildAndThrowWorkflowException(execution, 1002, "Error Occured during preProcessUpdateAAIVfModuleRequestGroup Method:\n" + e.getMessage())
1623                 }
1624                 logger.trace("COMPLETED  preProcessUpdateAAIVfModuleRequestGroup")
1625
1626         }
1627
1628         public void validateSDNCResponse(DelegateExecution execution, String response, String method){
1629
1630                 execution.setVariable("prefix",Prefix)
1631                 logger.debug("STARTED ValidateSDNCResponse Process")
1632
1633                 WorkflowException workflowException = execution.getVariable("WorkflowException")
1634                 boolean successIndicator = execution.getVariable("SDNCA_SuccessIndicator")
1635
1636                 logger.debug("workflowException: " + workflowException)
1637
1638                 SDNCAdapterUtils sdncAdapterUtils = new SDNCAdapterUtils()
1639                 sdncAdapterUtils.validateSDNCResponse(execution, response, workflowException, successIndicator)
1640
1641                 String sdncResponse = response
1642                 if(execution.getVariable(Prefix + 'sdncResponseSuccess') == true){
1643                         logger.debug("Received a Good Response from SDNC Adapter for " + method + " SDNC Call.  Response is: \n" + sdncResponse)
1644                         RollbackData rollbackData = execution.getVariable("rollbackData")
1645
1646                         if(method.equals("assign")){
1647                                 rollbackData.put("VFMODULE", "rollbackSDNCRequestAssign", "true")
1648                                 execution.setVariable("CRTGVNF_sdncAssignCompleted", true)
1649                         }
1650                         else if (method.equals("activate")) {
1651                                 rollbackData.put("VFMODULE", "rollbackSDNCRequestActivate", "true")
1652                         }
1653                         execution.setVariable("rollbackData", rollbackData)
1654                 }else{
1655                         logger.debug("Received a BAD Response from SDNC Adapter for " + method + " SDNC Call.")
1656                         throw new BpmnError("MSOWorkflowException")
1657                 }
1658                 logger.trace("COMPLETED ValidateSDNCResponse Process")
1659         }
1660
1661         public void preProcessUpdateAfterCreateRequest(DelegateExecution execution){
1662
1663                 execution.setVariable("prefix", Prefix)
1664                 logger.trace("STARTED preProcessRequest Process")
1665                 try{
1666                         String response = execution.getVariable("DCVFM_assignSDNCAdapterResponse")
1667                         logger.debug("DCVFM_assignSDNCAdapterResponse: " + response)
1668
1669                         String data = utils.getNodeXml(response, "response-data")
1670                         String vnfId = utils.getNodeText(data, "vnf-id")
1671
1672                         String uuid = execution.getVariable('testReqId') // for junits
1673                         if(uuid==null){
1674                                 uuid = execution.getVariable("mso-request-id") + "-" +          System.currentTimeMillis()
1675                         }
1676
1677                         String serviceOperation = "/VNF-API:vnfs/vnf-list/" + vnfId
1678                         def callbackUrl = execution.getVariable("DCVFM_sdncCallbackUrl")
1679                         logger.debug("callbackUrl: " + callbackUrl)
1680
1681                         String SDNCGetRequest =
1682                                         """<sdncadapterworkflow:SDNCAdapterWorkflowRequest xmlns:ns5="http://org.onap/so/request/types/v1"
1683                                                                                         xmlns:sdncadapterworkflow="http://org.onap/so/workflow/schema/v1"
1684                                                                                         xmlns:sdncadapter="http://org.onap/workflow/sdnc/adapter/schema/v1">
1685                                         <sdncadapter:RequestHeader>
1686                                         <sdncadapter:RequestId>${MsoUtils.xmlEscape(uuid)}</sdncadapter:RequestId>
1687                                         <sdncadapter:SvcAction>query</sdncadapter:SvcAction>
1688                                         <sdncadapter:SvcOperation>${MsoUtils.xmlEscape(serviceOperation)}</sdncadapter:SvcOperation>
1689                                         <sdncadapter:CallbackUrl>${MsoUtils.xmlEscape(callbackUrl)}</sdncadapter:CallbackUrl>
1690                                         <sdncadapter:MsoAction>mobility</sdncadapter:MsoAction>
1691                                 </sdncadapter:RequestHeader>
1692                                         <sdncadapterworkflow:SDNCRequestData></sdncadapterworkflow:SDNCRequestData>
1693                                 </sdncadapterworkflow:SDNCAdapterWorkflowRequest>"""
1694
1695                         execution.setVariable("DCVFM_getSDNCRequest", SDNCGetRequest)
1696                         logger.debug("Outgoing GetSDNCRequest is: \n" + SDNCGetRequest)
1697
1698                 }catch(Exception e){
1699                         logger.error("{} {} {} {} {}", MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(),
1700                                         "Exception Occured Processing preProcessSDNCGetRequest", "BPMN",
1701                                         ErrorCode.UnknownError.getValue(), "Exception is:\n" + e);
1702                         exceptionUtil.buildAndThrowWorkflowException(execution, 1002, "Error Occured during prepareProvision Method:\n" + e.getMessage())
1703                 }
1704                 logger.trace("COMPLETED preProcessSDNCGetRequest Process")
1705         }
1706
1707         public String buildUpdateAAIVfModuleRequest(DelegateExecution execution, boolean updateVolumeGroupId,
1708                 boolean updateOrchestrationStatus, boolean updateHeatStackId, boolean updateContrailFqdn){
1709
1710                 def vnfId = execution.getVariable("DCVFM_vnfId")
1711                 def vfModuleId = execution.getVariable("DCVFM_vfModuleId")
1712                 def volumeGroupIdString = ""
1713                 if (updateVolumeGroupId) {
1714                         volumeGroupIdString = "<volume-group-id>" + execution.getVariable("DCVFM_volumeGroupId") +
1715                                         "</volume-group-id>"
1716                 }
1717                 def orchestrationStatusString = ""
1718                 if (updateOrchestrationStatus) {
1719                         orchestrationStatusString = "<orchestration-status>" + execution.getVariable("DCVFM_orchestrationStatus") + "</orchestration-status>"
1720                 }
1721                 def heatStackIdString = ""
1722                 if (updateHeatStackId) {
1723                         heatStackIdString = "<heat-stack-id>" + execution.getVariable("DCVFM_heatStackId") + "</heat-stack-id>"
1724                 }
1725                 def contrailFqdnString = ""
1726                 if (updateContrailFqdn) {
1727                         contrailFqdnString = "<contrail-service-instance-fqdn>" + execution.getVariable("DCVFM_contrailServiceInstanceFqdn") +
1728                                 "</contrail-service-instance-fqdn>"
1729                 }
1730
1731                 String updateAAIVfModuleRequest =
1732                         """<UpdateAAIVfModuleRequest>
1733                                 <vnf-id>${MsoUtils.xmlEscape(vnfId)}</vnf-id>
1734                                 <vf-module-id>${MsoUtils.xmlEscape(vfModuleId)}</vf-module-id>
1735                                 ${heatStackIdString}
1736                                 ${orchestrationStatusString}
1737                                 ${volumeGroupIdString}
1738                                 ${contrailFqdnString}
1739                         </UpdateAAIVfModuleRequest>"""
1740
1741         logger.trace("updateAAIVfModule Request: " + updateAAIVfModuleRequest)
1742         return updateAAIVfModuleRequest
1743
1744         }
1745
1746         public String buildSDNCParamsXml(DelegateExecution execution){
1747
1748                 String params = ""
1749                 StringBuilder sb = new StringBuilder()
1750                 Map<String, String> paramsMap = execution.getVariable("DCVFM_vnfParamsMap")
1751
1752                 for (Map.Entry<String, String> entry : paramsMap.entrySet()) {
1753                         String paramsXml
1754                         String key = entry.getKey();
1755                         if(key.endsWith("_network")){
1756                                 String requestKey = key.substring(0, key.indexOf("_network"))
1757                                 String requestValue = entry.getValue()
1758                                 paramsXml =
1759 """<vnf-networks>
1760         <network-role>{ functx:substring-before-match(data($param/@name), '_network') }</network-role>
1761         <network-name>{ $param/text() }</network-name>
1762 </vnf-networks>"""
1763                         }else{
1764                         paramsXml = ""
1765                         }
1766                         params = sb.append(paramsXml)
1767                 }
1768                 return params
1769         }
1770
1771         public String buildCompleteSDNCParamsXml(DelegateExecution execution){
1772
1773                 String params = ""
1774                 StringBuilder sb = new StringBuilder()
1775                 Map<String, String> paramsMap = execution.getVariable("DCVFM_vnfParamsMap")
1776
1777                 for (Map.Entry<String, String> entry : paramsMap.entrySet()) {
1778                         String paramsXml
1779                         String key = entry.getKey();
1780                         String value = entry.getValue()
1781                         paramsXml =     """<${key}>$value</$key>"""
1782                         params = sb.append(paramsXml)
1783                 }
1784                 return params
1785         }
1786
1787    public void queryCloudRegion (DelegateExecution execution) {
1788
1789                 execution.setVariable("prefix", Prefix)
1790                 logger.trace("STARTED queryCloudRegion")
1791
1792                 try {
1793                         String cloudRegion = execution.getVariable("DCVFM_cloudSiteId")
1794
1795                         // Prepare AA&I url
1796                         AaiUtil aaiUtil = new AaiUtil(this)
1797
1798                         AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIObjectType.CLOUD_REGION, Defaults.CLOUD_OWNER.toString(), cloudRegion)
1799                         def queryCloudRegionRequest = aaiUtil.createAaiUri(uri)
1800
1801                         execution.setVariable("DCVFM_queryCloudRegionRequest", queryCloudRegionRequest)
1802
1803                         cloudRegion = aaiUtil.getAAICloudReqion(execution, queryCloudRegionRequest, "PO", cloudRegion)
1804
1805                         if ((cloudRegion != "ERROR")) {
1806                                 if(execution.getVariable("DCVFM_queryCloudRegionReturnCode") == "404"){
1807                                         execution.setVariable("DCVFM_cloudRegionForVolume", "AAIAIC25")
1808                                 }else{
1809                                 execution.setVariable("DCVFM_cloudRegionForVolume", cloudRegion)
1810                                 }
1811                                 execution.setVariable("DCVFM_isCloudRegionGood", true)
1812                         } else {
1813                                 String errorMessage = "AAI Query Cloud Region Unsuccessful. AAI Response Code: " + execution.getVariable("DCVFM_queryCloudRegionReturnCode")
1814                                 logger.debug(errorMessage)
1815                                 exceptionUtil.buildAndThrowWorkflowException(execution, 2500, errorMessage)
1816                                 execution.setVariable("DCVFM_isCloudRegionGood", false)
1817                         }
1818                         logger.debug(" is Cloud Region Good: " + execution.getVariable("DCVFM_isCloudRegionGood"))
1819
1820                 } catch(BpmnError b){
1821                         logger.error("{} {} {} {} {}", MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(),
1822                                         "Rethrowing MSOWorkflowException", "BPMN",
1823                                         ErrorCode.UnknownError.getValue(), "Exception is:\n" + b.getMessage());
1824                         throw b
1825                 }catch (Exception ex) {
1826                         // try error
1827                         String errorMessage = "Bpmn error encountered in CreateVfModule flow. Unexpected Response from AAI - " + ex.getMessage()
1828                         logger.error("{} {} {} {} {}", MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(),
1829                                         "AAI Query Cloud Region Failed " + errorMessage, "BPMN",
1830                                         ErrorCode.UnknownError.getValue(), "Exception is:\n" + ex);
1831                         exceptionUtil.buildAndThrowWorkflowException(execution, 500, "Exception occured during queryCloudRegion method")
1832                 }
1833         }
1834
1835    /**
1836     *
1837     *This method occurs when an MSOWorkflowException is caught.  It logs the
1838     *variables and ensures that the "WorkflowException" Variable is set.
1839     *
1840     */
1841    public void processBPMNException(DelegateExecution execution){
1842
1843            execution.setVariable("prefix",Prefix)
1844            try{
1845                    logger.debug("Caught a BPMN Exception")
1846                    logger.debug("Started processBPMNException Method")
1847                    logger.debug("Variables List: " + execution.getVariables())
1848                    if(execution.getVariable("WorkflowException") == null){
1849                            exceptionUtil.buildAndThrowWorkflowException(execution, 500, "Exception occured during DoCreateVfModule Sub Process")
1850                    }
1851
1852            }catch(Exception e){
1853                    logger.debug("Caught Exception during processBPMNException Method: " + e)
1854            }
1855            logger.debug("Completed processBPMNException Method")
1856    }
1857
1858    public void prepareCreateAAIVfModuleVolumeGroupRequest(DelegateExecution execution) {
1859                 def method = getClass().getSimpleName() + '.prepareCreateAAIVfModuleVolumeGroupRequest(' +
1860                         'execution=' + execution.getId() +
1861                         ')'
1862
1863                 logger.trace('Entered ' + method)
1864                 execution.setVariable("prefix", Prefix)
1865                 logger.trace("STARTED prepareCreateAAIVfModuleVolumeGroupRequest")
1866
1867                 try{
1868
1869                         //Build CreateAAIVfModuleVolumeGroup Request
1870
1871                         def vnfId = execution.getVariable("DCVFM_vnfId")
1872                         def vfModuleId = execution.getVariable("DCVFM_vfModuleId")
1873                         def volumeGroupId = execution.getVariable("DCVFM_volumeGroupId")
1874                         //def aicCloudRegion = execution.getVariable("DCVFM_cloudSiteId")
1875                         def aicCloudRegion = execution.getVariable("DCVFM_cloudRegionForVolume")
1876                         def cloudOwner = execution.getVariable("DCVFM_cloudOwner")
1877                         String createAAIVfModuleVolumeGroupRequest =
1878                         """<CreateAAIVfModuleVolumeGroupRequest>
1879                                 <vnf-id>${MsoUtils.xmlEscape(vnfId)}</vnf-id>
1880                                 <vf-module-id>${MsoUtils.xmlEscape(vfModuleId)}</vf-module-id>
1881                                 <volume-group-id>${MsoUtils.xmlEscape(volumeGroupId)}</volume-group-id>
1882                                 <aic-cloud-region>${MsoUtils.xmlEscape(aicCloudRegion)}</aic-cloud-region>
1883                                 <cloud-owner>${MsoUtils.xmlEscape(cloudOwner)}</cloud-owner>
1884                         </CreateAAIVfModuleVolumeGroupRequest>"""
1885
1886                         createAAIVfModuleVolumeGroupRequest = utils.formatXml(createAAIVfModuleVolumeGroupRequest)
1887                         execution.setVariable("DCVFM_createAAIVfModuleVolumeGroupRequest", createAAIVfModuleVolumeGroupRequest)
1888                         logger.debug("Outgoing CreateAAIVfModuleVolumeGroupRequest is: \n" + createAAIVfModuleVolumeGroupRequest)
1889
1890                 }catch(Exception e){
1891                         logger.error("{} {} {} {} {}", MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(),
1892                                         'Exception Occured Processing prepareCreateAAIVfModuleVolumeGroupRequest', "BPMN",
1893                                         ErrorCode.UnknownError.getValue(), "Exception is:\n" + e);
1894                         exceptionUtil.buildAndThrowWorkflowException(execution, 1002, "Error Occured during prepareCreateAAIVfModuleVolumeGroupRequest Method:\n" + e.getMessage())
1895                 }
1896                 logger.trace("COMPLETED  prepareCreateAAIVfModuleVolumeGroupRequest")
1897
1898         }
1899
1900    public void createNetworkPoliciesInAAI(DelegateExecution execution) {
1901            def method = getClass().getSimpleName() + '.createNetworkPoliciesInAAI(' +
1902            'execution=' + execution.getId() +
1903            ')'
1904
1905            logger.trace('Entered ' + method)
1906            execution.setVariable("prefix", Prefix)
1907            logger.trace("STARTED createNetworkPoliciesInAAI")
1908
1909            try {
1910                    // get variables
1911                    List fqdnList = execution.getVariable("DCVFM_contrailNetworkPolicyFqdnList")
1912                    int fqdnCount = fqdnList.size()
1913                    def rollbackData = execution.getVariable("rollbackData")
1914
1915                    execution.setVariable("DCVFM_networkPolicyFqdnCount", fqdnCount)
1916                    logger.debug("DCVFM_networkPolicyFqdnCount - " + fqdnCount)
1917
1918                    AaiUtil aaiUriUtil = new AaiUtil(this)
1919
1920                         if (fqdnCount > 0) {
1921
1922                                 // AII loop call over contrail network policy fqdn list
1923                                 for (i in 0..fqdnCount-1) {
1924
1925                                         int counting = i+1
1926                                         String fqdn = fqdnList[i]
1927
1928                                         // Query AAI for this network policy FQDN
1929                                         AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIObjectPlurals.NETWORK_POLICY)
1930                                         uri.queryParam("network-policy-fqdn", fqdn)
1931
1932                                         AAIResourcesClient resourceClient = new AAIResourcesClient()
1933
1934
1935                                         if (resourceClient.exists(uri)) {
1936
1937                                                 logger.debug(" QueryAAINetworkPolicyByFQDN Success REST Response, , NetworkPolicy #" + counting)
1938
1939                                         } else {
1940                                                 // This network policy FQDN is not in AAI yet. Add it now
1941                                                 logger.debug("This network policy FQDN is not in AAI yet: " + fqdn)
1942                                                 // Add the network policy with this FQDN to AAI
1943                                                 def networkPolicyId = UUID.randomUUID().toString()
1944                                                 logger.debug("Adding network-policy with network-policy-id " + networkPolicyId)
1945
1946                                                 NetworkPolicy policy = new NetworkPolicy()
1947                                                 policy.setNetworkPolicyId(networkPolicyId)
1948                                                 policy.setNetworkPolicyFqdn(fqdn)
1949                                                 policy.setHeatStackId(execution.getVariable("DCVFM_heatStackId"))
1950                                                 
1951                                                 AAIResourceUri netUri = AAIUriFactory.createResourceUri(AAIObjectType.NETWORK_POLICY, networkPolicyId)
1952                                                 resourceClient.create(netUri, policy)
1953
1954                                                 rollbackData.put("VFMODULE", "rollbackCreateNetworkPoliciesAAI", "true")
1955                                                 rollbackData.put("VFMODULE", "contrailNetworkPolicyFqdn" + i, fqdn)
1956                                                 execution.setVariable("rollbackData", rollbackData)
1957                                         }
1958
1959                                 } // end loop
1960
1961
1962                    } else {
1963                            logger.debug("No contrail network policies to query/create")
1964
1965                    }
1966
1967            } catch (BpmnError e) {
1968                    throw e;
1969            } catch (Exception ex) {
1970                    String exceptionMessage = "Bpmn error encountered in DoCreateVfModule flow. createNetworkPoliciesInAAI() - " + ex.getMessage()
1971                    logger.debug(exceptionMessage)
1972                    exceptionUtil.buildAndThrowWorkflowException(execution, 7000, exceptionMessage)
1973            }
1974
1975    }
1976
1977    /**
1978         * Prepare a Request for invoking the UpdateAAIGenericVnf subflow.
1979         *
1980         * @param execution The flow's execution instance.
1981         */
1982    public void prepUpdateAAIGenericVnf(DelegateExecution execution) {
1983            def method = getClass().getSimpleName() + '.prepUpdateAAIGenericVnf(' +
1984                    'execution=' + execution.getId() +
1985                    ')'
1986
1987            logger.trace('Entered ' + method)
1988
1989            try {
1990                    def rollbackData = execution.getVariable("rollbackData")
1991                    def vnfId = execution.getVariable('DCVFM_vnfId')
1992                    def oamManagementV4Address = execution.getVariable("DCVFM_oamManagementV4Address")
1993                    def oamManagementV6Address = execution.getVariable("DCVFM_oamManagementV6Address")
1994                    def ipv4OamAddressElement = ''
1995                    def managementV6AddressElement = ''
1996
1997                    if (oamManagementV4Address != null && !oamManagementV4Address.isEmpty()) {
1998                            ipv4OamAddressElement = '<ipv4-oam-address>' + oamManagementV4Address + '</ipv4-oam-address>'
1999                    }
2000
2001                    if (oamManagementV6Address != null && !oamManagementV6Address.isEmpty()) {
2002                            managementV6AddressElement = '<management-v6-address>' + oamManagementV6Address + '</management-v6-address>'
2003                    }
2004
2005                    rollbackData.put("VFMODULE", "oamManagementV4Address", oamManagementV4Address)
2006
2007
2008                    String updateAAIGenericVnfRequest = """
2009                                         <UpdateAAIGenericVnfRequest>
2010                                                 <vnf-id>${MsoUtils.xmlEscape(vnfId)}</vnf-id>
2011                                                 ${ipv4OamAddressElement}
2012                                                 ${managementV6AddressElement}
2013                                         </UpdateAAIGenericVnfRequest>
2014                                 """
2015                            updateAAIGenericVnfRequest = utils.formatXml(updateAAIGenericVnfRequest)
2016                            execution.setVariable('DCVM_updateAAIGenericVnfRequest', updateAAIGenericVnfRequest)
2017                            logger.debug('Request for UpdateAAIGenericVnf:\n' + updateAAIGenericVnfRequest)
2018
2019
2020                    logger.trace('Exited ' + method)
2021            } catch (BpmnError e) {
2022                    throw e;
2023            } catch (Exception e) {
2024                    logger.error("{} {} {} {} {}", MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(),
2025                                    "Exception Encountered in " + method, "BPMN",
2026                                    ErrorCode.UnknownError.getValue(), "Exception is:\n" + e);
2027
2028                    exceptionUtil.buildAndThrowWorkflowException(execution, 1002, 'Error in prepUpdateAAIGenericVnf(): ' + e.getMessage())
2029            }
2030    }
2031
2032    /**
2033         * Post process a result from invoking the UpdateAAIGenericVnf subflow.
2034         *
2035         * @param execution The flow's execution instance.
2036         */
2037    public void postProcessUpdateAAIGenericVnf(DelegateExecution execution) {
2038            def method = getClass().getSimpleName() + '.postProcessUpdateAAIGenericVnf(' +
2039                    'execution=' + execution.getId() +
2040                    ')'
2041
2042            logger.trace('Entered ' + method)
2043
2044            try {
2045                    def rollbackData = execution.getVariable("rollbackData")
2046
2047                    rollbackData.put("VFMODULE", "rollbackUpdateVnfAAI", "true")
2048
2049                    def vnfId = execution.getVariable('DCVFM_vnfId')
2050                    def oamManagementV4Address = execution.getVariable("DCVFM_oamManagementV4Address")
2051                    def oamManagementV6Address = execution.getVariable("DCVFM_oamManagementV6Address")
2052                    def ipv4OamAddressElement = ''
2053                    def managementV6AddressElement = ''
2054
2055                    if (oamManagementV4Address != null && !oamManagementV4Address.isEmpty()) {
2056                            rollbackData.put("VFMODULE", "oamManagementV4Address", oamManagementV4Address)
2057                    }
2058
2059                    if (oamManagementV6Address != null && !oamManagementV6Address.isEmpty()) {
2060                            rollbackData.put("VFMODULE", "oamManagementV6Address", oamManagementV6Address)
2061                    }
2062
2063                    execution.setVariable("rollbackData", rollbackData)
2064
2065                    logger.trace('Exited ' + method)
2066            } catch (BpmnError e) {
2067                    throw e;
2068            } catch (Exception e) {
2069                    logger.error("{} {} {} {} {}", MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(),
2070                                    'Caught exception in ' + method, "BPMN",
2071                                    ErrorCode.UnknownError.getValue(), "Exception is:\n" + e);
2072                    exceptionUtil.buildAndThrowWorkflowException(execution, 1002, 'Error in postProcessUpdateAAIGenericVnf(): ' + e.getMessage())
2073            }
2074    }
2075
2076    public void queryCatalogDB (DelegateExecution execution) {
2077
2078            String msg = ""
2079            logger.trace("queryCatalogDB ")
2080
2081            try {
2082                    boolean twoPhaseDesign = false
2083                    // check for input
2084
2085                    String vfModuleModelName = execution.getVariable("DCVFM_vfModuleModelName")
2086                    logger.debug("vfModuleModelName: " + vfModuleModelName)
2087                    def vnfModelInfo = execution.getVariable("vnfModelInfo")
2088                    def vnfModelCustomizationUuid = jsonUtil.getJsonValue(vnfModelInfo, "modelCustomizationUuid")
2089
2090                    logger.debug("vnfModelCustomizationUuid: " + vnfModelCustomizationUuid)
2091
2092                    JSONArray vnfs = catalogDbUtils.getAllVnfsByVnfModelCustomizationUuid(execution, vnfModelCustomizationUuid, "v2")
2093
2094                    logger.debug("Incoming Query Catalog DB for Vnf Response is: " + vnfModelCustomizationUuid)
2095                    // Only one match here
2096                    if (vnfs != null) {
2097                            JSONObject vnfObject = vnfs.get(0)
2098                            if (vnfObject != null) {
2099                                    String vnfJson = vnfObject.toString()
2100                                    //
2101                                    ObjectMapper om = new ObjectMapper();
2102                                    VnfResource vnf = om.readValue(vnfJson, VnfResource.class);
2103
2104                                    // Get multiStageDesign flag
2105
2106                                    String multiStageDesignValue = vnf.getMultiStageDesign()
2107                                    logger.debug("multiStageDesign value from Catalog DB is: " + multiStageDesignValue)
2108                                    if (multiStageDesignValue != null) {
2109                                            if (multiStageDesignValue.equalsIgnoreCase("true")) {
2110                                                         twoPhaseDesign = true
2111                                            }
2112                                    }
2113                            }
2114                    }
2115
2116                    logger.debug("setting twoPhaseDesign flag to: " + twoPhaseDesign)
2117
2118                    execution.setVariable("DCVFM_twoPhaseDesign", twoPhaseDesign)
2119            } catch (BpmnError e) {
2120                    throw e;
2121            } catch (Exception e) {
2122                    logger.error("{} {} {} {} {}", MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(),
2123                                    'Caught exception in queryCatalogDB', "BPMN",
2124                                    ErrorCode.UnknownError.getValue(), "Exception is:\n" + e);
2125                    exceptionUtil.buildAndThrowWorkflowException(execution, 1002, 'Error in queryCatalogDB(): ' + e.getMessage())
2126            }
2127    }
2128
2129
2130    public void preProcessRollback (DelegateExecution execution) {
2131
2132            logger.trace("preProcessRollback")
2133            try {
2134
2135                    Object workflowException = execution.getVariable("WorkflowException");
2136
2137                    if (workflowException instanceof WorkflowException) {
2138                            logger.debug("Prev workflowException: " + workflowException.getErrorMessage())
2139                            execution.setVariable("prevWorkflowException", workflowException);
2140                            //execution.setVariable("WorkflowException", null);
2141                    }
2142            } catch (BpmnError e) {
2143                    logger.debug("BPMN Error during preProcessRollback")
2144            } catch(Exception ex) {
2145                    String msg = "Exception in preProcessRollback. " + ex.getMessage()
2146                    logger.debug(msg)
2147            }
2148            logger.trace("Exit preProcessRollback")
2149    }
2150
2151    public void postProcessRollback (DelegateExecution execution) {
2152
2153            logger.trace("postProcessRollback")
2154            String msg = ""
2155            try {
2156                    Object workflowException = execution.getVariable("prevWorkflowException");
2157                    if (workflowException instanceof WorkflowException) {
2158                            logger.debug("Setting prevException to WorkflowException: ")
2159                            execution.setVariable("WorkflowException", workflowException);
2160                    }
2161                    execution.setVariable("rollbackData", null)
2162            } catch (BpmnError b) {
2163                    logger.debug("BPMN Error during postProcessRollback")
2164                    throw b;
2165            } catch(Exception ex) {
2166                    msg = "Exception in postProcessRollback. " + ex.getMessage()
2167                    logger.debug(msg)
2168            }
2169            logger.trace("Exit postProcessRollback")
2170    }
2171
2172 }