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