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