Remove unnecessary use of Calendar.getInstance()
[so.git] / bpmn / MSOInfrastructureBPMN / src / main / groovy / org / openecomp / mso / bpmn / infrastructure / scripts / DoCreateVfModule.groovy
1 /*-
2  * ============LICENSE_START=======================================================
3  * OPENECOMP - MSO
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.openecomp.mso.bpmn.infrastructure.scripts;
22
23 import javax.xml.parsers.DocumentBuilder
24 import javax.xml.parsers.DocumentBuilderFactory
25
26 import org.apache.commons.lang3.*
27 import org.camunda.bpm.engine.delegate.BpmnError
28 import org.camunda.bpm.engine.runtime.Execution
29 import org.openecomp.mso.bpmn.common.scripts.AaiUtil
30 import org.openecomp.mso.bpmn.common.scripts.ExceptionUtil
31 import org.openecomp.mso.bpmn.common.scripts.NetworkUtils
32 import org.openecomp.mso.bpmn.common.scripts.SDNCAdapterUtils
33 import org.openecomp.mso.bpmn.common.scripts.VfModuleBase
34 import org.openecomp.mso.bpmn.core.RollbackData
35 import org.openecomp.mso.bpmn.core.WorkflowException
36 import org.openecomp.mso.bpmn.core.json.JsonUtils
37 import org.openecomp.mso.rest.APIResponse
38 import org.openecomp.mso.rest.RESTClient
39 import org.openecomp.mso.rest.RESTConfig
40 import org.springframework.web.util.UriUtils
41 import org.w3c.dom.Document
42 import org.w3c.dom.Element
43 import org.w3c.dom.NamedNodeMap
44 import org.w3c.dom.Node
45 import org.w3c.dom.NodeList
46 import org.xml.sax.InputSource
47
48
49
50 public class DoCreateVfModule extends VfModuleBase {
51
52         String Prefix="DCVFM_"
53         ExceptionUtil exceptionUtil = new ExceptionUtil()
54         JsonUtils jsonUtil = new JsonUtils()
55
56         /**
57          * Validates the request message and sets up the workflow.
58          * @param execution the execution
59          */
60         public void preProcessRequest(Execution execution) {
61                 def method = getClass().getSimpleName() + '.preProcessRequest(' +
62                         'execution=' + execution.getId() +
63                         ')'
64                 def isDebugLogEnabled = execution.getVariable('isDebugLogEnabled')
65                 logDebug('Entered ' + method, isDebugLogEnabled)
66
67                 execution.setVariable('prefix', Prefix)
68                 try{                    
69                         def rollbackData = execution.getVariable("RollbackData")
70                         if (rollbackData == null) {
71                                 rollbackData = new RollbackData()
72                         }
73                         
74                         execution.setVariable("DCVFM_vnfParamsExistFlag", false)
75                         execution.setVariable("DCVFM_oamManagementV4Address", "")
76                         execution.setVariable("DCVFM_oamManagementV6Address", "")
77                                                                 
78                         String request = execution.getVariable("DoCreateVfModuleRequest")
79                                 
80                         if (request == null || request.isEmpty()) {
81                                 // Building Block-type request
82                                 
83                                 String cloudConfiguration = execution.getVariable("cloudConfiguration")
84                                 String vfModuleModelInfo = execution.getVariable("vfModuleModelInfo")
85                                 
86                                 //tenantId
87                                 def tenantId = jsonUtil.getJsonValue(cloudConfiguration, "cloudConfiguration.tenantId")
88                                 execution.setVariable("DCVFM_tenantId", tenantId)
89                                 rollbackData.put("VFMODULE", "tenantid", tenantId)
90                                 //volumeGroupId
91                                 def volumeGroupId = execution.getVariable("volumeGroupId")                              
92                                 execution.setVariable("DCVFM_volumeGroupId", volumeGroupId)
93                                 //volumeGroupName
94                                 def volumeGroupName = execution.getVariable("volumeGroupName")                          
95                                 execution.setVariable("DCVFM_volumeGroupName", volumeGroupName)
96                                 //cloudSiteId
97                                 def cloudSiteId = jsonUtil.getJsonValue(cloudConfiguration, "cloudConfiguration.lcpCloudRegionId")
98                                 execution.setVariable("DCVFM_cloudSiteId", cloudSiteId)
99                                 rollbackData.put("VFMODULE", "aiccloudregion", cloudSiteId)
100                                 logDebug("cloudSiteId: " + cloudSiteId, isDebugLogEnabled)
101                                 //vnfType
102                                 def vnfType = execution.getVariable("vnfType")
103                                 execution.setVariable("DCVFM_vnfType", vnfType)
104                                 rollbackData.put("VFMODULE", "vnftype", vnfType)
105                                 logDebug("vnfType: " + vnfType, isDebugLogEnabled)
106                                 //vnfName
107                                 def vnfName = execution.getVariable("vnfName")                          
108                                 execution.setVariable("DCVFM_vnfName", vnfName)
109                                 rollbackData.put("VFMODULE", "vnfname", vnfName)
110                                 logDebug("vnfName: " + vnfName, isDebugLogEnabled)
111                                 //vnfId
112                                 def vnfId = execution.getVariable("vnfId")                              
113                                 execution.setVariable("DCVFM_vnfId", vnfId)
114                                 rollbackData.put("VFMODULE", "vnfid", vnfId)
115                                 logDebug("vnfId: " + vnfId, isDebugLogEnabled)
116                                 //vfModuleName
117                                 def vfModuleName = execution.getVariable("vfModuleName")                                
118                                 execution.setVariable("DCVFM_vfModuleName", vfModuleName)
119                                 rollbackData.put("VFMODULE", "vfmodulename", vfModuleName)
120                                 logDebug("vfModuleName: " + vfModuleName, isDebugLogEnabled)
121                                 //vfModuleModelName
122                                 def vfModuleModelName = jsonUtil.getJsonValue(vfModuleModelInfo, "modelInfo.modelName")                         
123                                 execution.setVariable("DCVFM_vfModuleModelName", vfModuleModelName)
124                                 rollbackData.put("VFMODULE", "vfmodulemodelname", vfModuleModelName)
125                                 logDebug("vfModuleModelName: " + vfModuleModelName, isDebugLogEnabled)
126                                 //modelCustomizationUuid
127                                 def modelCustomizationUuid = jsonUtil.getJsonValue(vfModuleModelInfo, "modelInfo.modelCustomizationId")
128                                 execution.setVariable("DCVFM_modelCustomizationUuid", modelCustomizationUuid)
129                                 rollbackData.put("VFMODULE", "modelcustomizationuuid", modelCustomizationUuid)
130                                 logDebug("modelCustomizationUuid: " + modelCustomizationUuid, isDebugLogEnabled)
131                                 //vfModuleId
132                                 def vfModuleId = execution.getVariable("vfModuleId")                            
133                                 execution.setVariable("DCVFM_vfModuleId", vfModuleId)
134                                 logDebug("vfModuleId: " + vfModuleId, isDebugLogEnabled)
135                                 def requestId = execution.getVariable("requestId")                              
136                                 execution.setVariable("DCVFM_requestId", requestId)
137                                 logDebug("requestId: " + requestId, isDebugLogEnabled)
138                                 // Set mso-request-id to request-id for VNF Adapter interface                           
139                                 execution.setVariable("mso-request-id", requestId)
140                                 //serviceId
141                                 def serviceId = execution.getVariable("serviceId")                              
142                                 execution.setVariable("DCVFM_serviceId", serviceId)
143                                 logDebug("serviceId: " + serviceId, isDebugLogEnabled)
144                                 //serviceInstanceId
145                                 def serviceInstanceId = execution.getVariable("serviceInstanceId")                              
146                                 execution.setVariable("DCVFM_serviceInstanceId", serviceInstanceId)
147                                 rollbackData.put("VFMODULE", "serviceInstanceId", serviceInstanceId)
148                                 logDebug("serviceInstanceId: " + serviceInstanceId, isDebugLogEnabled)
149                                 //source - HARDCODED
150                                 def source = "VID"                              
151                                 execution.setVariable("DCVFM_source", source)
152                                 rollbackData.put("VFMODULE", "source", source)
153                                 logDebug("source: " + source, isDebugLogEnabled)
154                                 //backoutOnFailure
155                                 def disableRollback = execution.getVariable("disableRollback")
156                                 def backoutOnFailure = true
157                                 if (disableRollback != null && disableRollback.equals("true")) {
158                                         backoutOnFailure = false
159                                 }                               
160                                 execution.setVariable("DCVFM_backoutOnFailure", backoutOnFailure)
161                                 logDebug("backoutOnFailure: " + backoutOnFailure, isDebugLogEnabled)
162                                 //isBaseVfModule
163                                 def isBaseVfModule = execution.getVariable("isBaseVfModule")                            
164                                 execution.setVariable("DCVFM_isBaseVfModule", isBaseVfModule)
165                                 logDebug("isBaseVfModule: " + isBaseVfModule, isDebugLogEnabled)                
166                                 //asdcServiceModelVersion
167                                 def asdcServiceModelVersion = execution.getVariable("asdcServiceModelVersion")                          
168                                 execution.setVariable("DCVFM_asdcServiceModelVersion", asdcServiceModelVersion)
169                                 logDebug("asdcServiceModelVersion: " + asdcServiceModelVersion, isDebugLogEnabled)                              
170                                 //personaModelId
171                                 execution.setVariable("DCVFM_personaModelId", jsonUtil.getJsonValue(vfModuleModelInfo, "modelInfo.modelInvariantId"))
172                                 //personaModelVersion
173                                 execution.setVariable("DCVFM_personaModelVersion", jsonUtil.getJsonValue(vfModuleModelInfo, "modelInfo.modelVersion"))          
174                                 //Get or Generate UUID
175                                 String uuid = execution.getVariable("DCVFM_uuid")
176                                 if(uuid == null){
177                                         uuid = UUID.randomUUID()
178                                         logDebug("Generated messageId (UUID) is: " + uuid, isDebugLogEnabled)
179                                 }else{
180                                         logDebug("Found messageId (UUID) is: " + uuid, isDebugLogEnabled)
181                                 }
182                                 //isVidRequest
183                                 String isVidRequest = execution.getVariable("isVidRequest")
184                                 // default to true
185                                 if (isVidRequest == null || isVidRequest.isEmpty()) {
186                                         execution.setVariable("isVidRequest", "true")
187                                 }
188                                 
189                                 String vnfParamsChildNodes = execution.getVariable("vfModuleInputParams")
190                                 
191                         }
192                         else {
193                                 // The info is inside the request
194                                 utils.logAudit("DoCreateVfModule request: " + request)
195                                                                 
196                                 //tenantId
197                                 def tenantId = ""
198                                 if (utils.nodeExists(request, "tenant-id")) {
199                                         tenantId = utils.getNodeText(request, "tenant-id")
200                                 }
201                                 execution.setVariable("DCVFM_tenantId", tenantId)
202                                 rollbackData.put("VFMODULE", "tenantid", tenantId)
203                                 //volumeGroupId
204                                 def volumeGroupId = ""
205                                 if (utils.nodeExists(request, "volume-group-id")) {
206                                         volumeGroupId = utils.getNodeText(request, "volume-group-id")
207                                 }
208                                 execution.setVariable("DCVFM_volumeGroupId", volumeGroupId)
209                                 //volumeGroupId
210                                 def volumeGroupName = ""
211                                 if (utils.nodeExists(request, "volume-group-name")) {
212                                         volumeGroupName = utils.getNodeText(request, "volume-group-name")
213                                 }
214                                 execution.setVariable("DCVFM_volumeGroupName", volumeGroupName)
215                                 //cloudSiteId
216                                 def cloudSiteId = ""
217                                 if (utils.nodeExists(request, "aic-cloud-region")) {
218                                         cloudSiteId = utils.getNodeText(request, "aic-cloud-region")
219                                 }
220                                 execution.setVariable("DCVFM_cloudSiteId", cloudSiteId)
221                                 rollbackData.put("VFMODULE", "aiccloudregion", cloudSiteId)
222                                 logDebug("cloudSiteId: " + cloudSiteId, isDebugLogEnabled)
223                                 //vnfType
224                                 def vnfType = ""
225                                 if (utils.nodeExists(request, "vnf-type")) {
226                                         vnfType = utils.getNodeText(request, "vnf-type")
227                                 }
228                                 execution.setVariable("DCVFM_vnfType", vnfType)
229                                 rollbackData.put("VFMODULE", "vnftype", vnfType)
230                                 logDebug("vnfType: " + vnfType, isDebugLogEnabled)
231                                 //vnfName
232                                 def vnfName = ""
233                                 if (utils.nodeExists(request, "vnf-name")) {
234                                         vnfName = utils.getNodeText(request, "vnf-name")
235                                 }
236                                 execution.setVariable("DCVFM_vnfName", vnfName)
237                                 rollbackData.put("VFMODULE", "vnfname", vnfName)
238                                 logDebug("vnfName: " + vnfName, isDebugLogEnabled)
239                                 //vnfId
240                                 def vnfId = ""
241                                 if (utils.nodeExists(request, "vnf-id")) {
242                                         vnfId = utils.getNodeText(request, "vnf-id")
243                                 }
244                                 execution.setVariable("DCVFM_vnfId", vnfId)
245                                 rollbackData.put("VFMODULE", "vnfid", vnfId)
246                                 logDebug("vnfId: " + vnfId, isDebugLogEnabled)
247                                 //vfModuleName
248                                 def vfModuleName = ""
249                                 if (utils.nodeExists(request, "vf-module-name")) {
250                                         vfModuleName = utils.getNodeText(request, "vf-module-name")
251                                 }
252                                 execution.setVariable("DCVFM_vfModuleName", vfModuleName)
253                                 rollbackData.put("VFMODULE", "vfmodulename", vfModuleName)
254                                 logDebug("vfModuleName: " + vfModuleName, isDebugLogEnabled)
255                                 //vfModuleModelName
256                                 def vfModuleModelName = ""
257                                 if (utils.nodeExists(request, "vf-module-model-name")) {
258                                         vfModuleModelName = utils.getNodeText(request, "vf-module-model-name")
259                                 }
260                                 execution.setVariable("DCVFM_vfModuleModelName", vfModuleModelName)
261                                 rollbackData.put("VFMODULE", "vfmodulemodelname", vfModuleModelName)
262                                 logDebug("vfModuleModelName: " + vfModuleModelName, isDebugLogEnabled)
263                                 //modelCustomizationUuid
264                                 def modelCustomizationUuid = ""
265                                 if (utils.nodeExists(request, "model-customization-id")) {
266                                         modelCustomizationUuid = utils.getNodeText(request, "model-customization-id")
267                                 }
268                                 execution.setVariable("DCVFM_modelCustomizationUuid", modelCustomizationUuid)
269                                 rollbackData.put("VFMODULE", "modelcustomizationuuid", modelCustomizationUuid)
270                                 logDebug("modelCustomizationUuid: " + modelCustomizationUuid, isDebugLogEnabled)
271                                 //vfModuleId
272                                 def vfModuleId = ""
273                                 if (utils.nodeExists(request, "vf-module-id")) {
274                                         vfModuleId = utils.getNodeText(request, "vf-module-id")
275                                 }
276                                 execution.setVariable("DCVFM_vfModuleId", vfModuleId)
277                                 logDebug("vfModuleId: " + vfModuleId, isDebugLogEnabled)
278                                 def requestId = ""
279                                 if (utils.nodeExists(request, "request-id")) {
280                                         requestId = utils.getNodeText(request, "request-id")
281                                 }
282                                 execution.setVariable("DCVFM_requestId", requestId)
283                                 logDebug("requestId: " + requestId, isDebugLogEnabled)
284                                 //serviceId
285                                 def serviceId = ""
286                                 if (utils.nodeExists(request, "service-id")) {
287                                         serviceId = utils.getNodeText(request, "service-id")
288                                 }
289                                 execution.setVariable("DCVFM_serviceId", serviceId)
290                                 logDebug("serviceId: " + serviceId, isDebugLogEnabled)
291                                 //serviceInstanceId
292                                 def serviceInstanceId = ""
293                                 if (utils.nodeExists(request, "service-instance-id")) {
294                                         serviceInstanceId = utils.getNodeText(request, "service-instance-id")
295                                 }
296                                 execution.setVariable("DCVFM_serviceInstanceId", serviceInstanceId)
297                                 rollbackData.put("VFMODULE", "serviceInstanceId", serviceInstanceId)
298                                 logDebug("serviceInstanceId: " + serviceInstanceId, isDebugLogEnabled)
299                                 //source
300                                 def source = ""
301                                 if (utils.nodeExists(request, "source")) {
302                                         source = utils.getNodeText(request, "source")
303                                 }
304                                 execution.setVariable("DCVFM_source", source)
305                                 rollbackData.put("VFMODULE", "source", source)
306                                 logDebug("source: " + source, isDebugLogEnabled)
307                                 //backoutOnFailure
308                                 NetworkUtils networkUtils = new NetworkUtils()
309                                 def backoutOnFailure = networkUtils.isRollbackEnabled(execution,request)
310                                 execution.setVariable("DCVFM_backoutOnFailure", backoutOnFailure)
311                                 logDebug("backoutOnFailure: " + backoutOnFailure, isDebugLogEnabled)
312                                 //isBaseVfModule
313                                 def isBaseVfModule = "false"
314                                 if (utils.nodeExists(request, "is-base-vf-module")) {
315                                         isBaseVfModule = utils.getNodeText(request, "is-base-vf-module")
316                                 }
317                                 execution.setVariable("DCVFM_isBaseVfModule", isBaseVfModule)
318                                 logDebug("isBaseVfModule: " + isBaseVfModule, isDebugLogEnabled)
319                 
320                                 //asdcServiceModelVersion
321                                 def asdcServiceModelVersion = ""
322                                 if (utils.nodeExists(request, "asdc-service-model-version")) {
323                                         asdcServiceModelVersion = utils.getNodeText(request, "asdc-service-model-version")
324                                 }
325                                 execution.setVariable("DCVFM_asdcServiceModelVersion", asdcServiceModelVersion)
326                                 logDebug("asdcServiceModelVersion: " + asdcServiceModelVersion, isDebugLogEnabled)      
327                                 
328                                 //personaModelId
329                                 def personaModelId = ""
330                                 if (utils.nodeExists(request, "persona-model-id")) {
331                                         personaModelId = utils.getNodeText(request, "persona-model-id")
332                                 }
333                                 execution.setVariable("DCVFM_personaModelId", personaModelId)
334                                 logDebug("personaModelId: " + personaModelId, isDebugLogEnabled)
335                                 
336                                 //personaModelVersion
337                                 def personaModelVersion = ""
338                                 if (utils.nodeExists(request, "persona-model-version")) {
339                                         personaModelVersion = utils.getNodeText(request, "persona-model-version")
340                                 }
341                                 execution.setVariable("DCVFM_personaModelVersion", personaModelVersion)
342                                 logDebug("personaModelVersion: " + personaModelVersion, isDebugLogEnabled)
343                                 
344                                 // Process the parameters
345                                 
346                                                 String vnfParamsChildNodes = utils.getChildNodes(request, "vnf-params")
347                                                 if(vnfParamsChildNodes == null || vnfParamsChildNodes.length() < 1){
348                                                                 utils.log("DEBUG", "Request contains NO VNF Params", isDebugLogEnabled)
349                                                 }else{
350                                                                 utils.log("DEBUG", "Request does contain VNF Params", isDebugLogEnabled)
351                                                                 execution.setVariable("DCVFM_vnfParamsExistFlag", true)
352                                 
353                                                                 InputSource xmlSource = new InputSource(new StringReader(request));
354                                                                 DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
355                                                                 docFactory.setNamespaceAware(true)
356                                                                 DocumentBuilder docBuilder = docFactory.newDocumentBuilder()
357                                                                 Document xml = docBuilder.parse(xmlSource)
358                                                                 //Get params, build map
359                                                                 Map<String, String> paramsMap = new HashMap<String, String>()
360                                                                 NodeList paramsList = xml.getElementsByTagNameNS("*", "param")
361                                 
362                                                                 for (int z = 0; z < paramsList.getLength(); z++) {
363                                                                         Node node = paramsList.item(z)
364                                                                         String paramValue = node.getTextContent()
365                                                                         NamedNodeMap e = node.getAttributes()
366                                                                         String paramName = e.getNamedItem("name").getTextContent()
367                                                                         paramsMap.put(paramName, paramValue)
368                                                                 }
369                                                                 execution.setVariable("DCVFM_vnfParamsMap", paramsMap)
370                                                         }
371                         }
372                         
373                         //Get or Generate UUID
374                         String uuid = execution.getVariable("DCVFM_uuid")
375                         if(uuid == null){
376                                 uuid = UUID.randomUUID()
377                                 logDebug("Generated messageId (UUID) is: " + uuid, isDebugLogEnabled)
378                         }else{
379                                 logDebug("Found messageId (UUID) is: " + uuid, isDebugLogEnabled)
380                         }
381                         execution.setVariable("DCVFM_uuid", uuid)
382                         execution.setVariable("DCVFM_baseVfModuleId", "")
383                         execution.setVariable("DCVFM_baseVfModuleHeatStackId", "")
384                         execution.setVariable("DCVFM_heatStackId", "")
385                         execution.setVariable("DCVFM_contrailServiceInstanceFqdn", "")
386                         execution.setVariable("DCVFM_volumeGroupStackId", "")
387                         execution.setVariable("DCVFM_cloudRegionForVolume", "")
388                         execution.setVariable("DCVFM_contrailNetworkPolicyFqdnList", "")
389                         rollbackData.put("VFMODULE", "rollbackPrepareUpdateVfModule", "false")
390                         rollbackData.put("VFMODULE", "rollbackUpdateAAIVfModule", "false")
391                         rollbackData.put("VFMODULE", "rollbackVnfAdapterCreate", "false")
392                         rollbackData.put("VFMODULE", "rollbackSDNCRequestActivate", "false")
393                         rollbackData.put("VFMODULE", "rollbackSDNCRequestAssign", "false")
394                         rollbackData.put("VFMODULE", "rollbackCreateAAIVfModule", "false")
395                         rollbackData.put("VFMODULE", "rollbackCreateNetworkPoliciesAAI", "false")
396                         rollbackData.put("VFMODULE", "rollbackUpdateVnfAAI", "false")
397         
398                         String sdncCallbackUrl = (String) execution.getVariable('URN_mso_workflow_sdncadapter_callback')
399                                 if (sdncCallbackUrl == null || sdncCallbackUrl.trim().isEmpty()) {
400                                         def msg = 'Required variable \'URN_mso_workflow_sdncadapter_callback\' is missing'
401                                         logError(msg)
402                                         exceptionUtil.buildAndThrowWorkflowException(execution, 2000, msg)
403                                 }
404                                 execution.setVariable("DCVFM_sdncCallbackUrl", sdncCallbackUrl)
405                                 utils.logAudit("SDNC Callback URL: " + sdncCallbackUrl)
406                             logDebug("SDNC Callback URL is: " + sdncCallbackUrl, isDebugLogEnabled)     
407                         
408         
409                         execution.setVariable("RollbackData", rollbackData)
410                 }catch(BpmnError b){
411                         throw b
412                 }catch(Exception e){
413                         exceptionUtil.buildAndThrowWorkflowException(execution, 2000, "Internal Error encountered in PreProcess method!")
414                 }
415
416                 logDebug('Exited ' + method, isDebugLogEnabled)
417         }
418
419         /**
420          * Validates a workflow response.
421          * @param execution the execution
422          * @param responseVar the execution variable in which the response is stored
423          * @param responseCodeVar the execution variable in which the response code is stored
424          * @param errorResponseVar the execution variable in which the error response is stored
425          */
426         public void validateWorkflowResponse(Execution execution, String responseVar,
427                         String responseCodeVar, String errorResponseVar) {
428                 SDNCAdapterUtils sdncAdapterUtils = new SDNCAdapterUtils(this)
429                 sdncAdapterUtils.validateSDNCResponse(execution, responseVar, responseCodeVar, errorResponseVar)
430         }
431
432
433         /**
434          * Sends the empty, synchronous response back to the API Handler.
435          * @param execution the execution
436          */
437         public void sendResponse(Execution execution) {
438                 def method = getClass().getSimpleName() + '.sendResponse(' +
439                         'execution=' + execution.getId() +
440                         ')'
441                 def isDebugLogEnabled = execution.getVariable('isDebugLogEnabled')
442                 logDebug('Entered ' + method, isDebugLogEnabled)
443
444                 try {
445                         buildResponse(execution, "", 200)
446                         logDebug('Exited ' + method, isDebugLogEnabled)
447                 } catch (BpmnError e) {
448                         throw e;
449                 } catch (Exception e) {
450                         logError('Caught exception in ' + method, e)
451                         exceptionUtil.buildAndThrowWorkflowException(execution, 1002, 'Internal Error')
452                 }
453         }
454
455         /**
456          * Using the received vnfId and vfModuleId, query AAI to get the corresponding VNF info.
457          * A 200 response is expected with the VNF info in the response body. Will find out the base module info
458          * and existing VNF's name for add-on modules
459          *
460          * @param execution The flow's execution instance.
461          */
462         public void postProcessCreateAAIVfModule(Execution execution) {
463                 def method = getClass().getSimpleName() + '.getVfModule(' +
464                         'execution=' + execution.getId() +
465                         ')'
466                 def isDebugLogEnabled = execution.getVariable('isDebugLogEnabled')
467                 logDebug('Entered ' + method, isDebugLogEnabled)
468
469                 try {
470                         def createResponse = execution.getVariable('DCVFM_createVfModuleResponse')
471                         utils.logAudit("createVfModule Response: " + createResponse)
472
473                         def rollbackData = execution.getVariable("RollbackData")
474                         String vnfName = utils.getNodeText1(createResponse, 'vnf-name')
475                         if (vnfName != null) {
476                                 execution.setVariable('DCVFM_vnfName', vnfName)
477                                 logDebug("vnfName retrieved from AAI is: " + vnfName, isDebugLogEnabled)
478                                 rollbackData.put("VFMODULE", "vnfname", vnfName)
479                         }
480                         String vnfId = utils.getNodeText1(createResponse, 'vnf-id')
481                         execution.setVariable('DCVFM_vnfId', vnfId)
482                         logDebug("vnfId is: " + vnfId, isDebugLogEnabled)
483                         String vfModuleId = utils.getNodeText1(createResponse, 'vf-module-id')
484                         execution.setVariable('DCVFM_vfModuleId', vfModuleId)
485                         logDebug("vfModuleId is: " + vfModuleId, isDebugLogEnabled)
486                         rollbackData.put("VFMODULE", "vnfid", vnfId)
487                         rollbackData.put("VFMODULE", "vfmoduleid", vfModuleId)
488                         rollbackData.put("VFMODULE", "rollbackCreateAAIVfModule", "true")
489                         rollbackData.put("VFMODULE", "rollbackPrepareUpdateVfModule", "true")
490                         execution.setVariable("RollbackData", rollbackData)
491                 } catch (Exception ex) {
492                                 ex.printStackTrace()
493                                 logDebug('Exception occurred while postProcessing CreateAAIVfModule request:' + ex.getMessage(),isDebugLogEnabled)
494                                 exceptionUtil.buildAndThrowWorkflowException(execution, 1002, 'Bad response from CreateAAIVfModule' + ex.getMessage())
495                 }
496                 logDebug('Exited ' + method, isDebugLogEnabled)
497         }
498
499
500         /**
501          * Using the received vnfId and vfModuleId, query AAI to get the corresponding VNF info.
502          * A 200 response is expected with the VNF info in the response body. Will find out the base module info.
503          *
504          * @param execution The flow's execution instance.
505          */
506         public void queryAAIVfModule(Execution execution) {
507                 def isDebugLogEnabled=execution.getVariable("isDebugLogEnabled")
508                 def method = getClass().getSimpleName() + '.getVfModule(' +
509                         'execution=' + execution.getId() +
510                         ')'
511                 logDebug('Entered ' + method, isDebugLogEnabled)
512
513                 try {
514                         def vnfId = execution.getVariable('DCVFM_vnfId')
515                         def vfModuleId = execution.getVariable('DCVFM_vfModuleId')
516
517                         AaiUtil aaiUriUtil = new AaiUtil(this)
518                         String  aai_uri = aaiUriUtil.getNetworkGenericVnfUri(execution)
519                         logDebug('AAI URI is: ' + aai_uri, isDebugLogEnabled)
520
521                         String endPoint = execution.getVariable("URN_aai_endpoint") + "${aai_uri}/" + UriUtils.encode(vnfId, "UTF-8") + "?depth=1"
522                         utils.logAudit("AAI endPoint: " + endPoint)
523
524                         try {
525                                 RESTConfig config = new RESTConfig(endPoint);
526                                 def responseData = ''
527                                 def aaiRequestId = UUID.randomUUID().toString()
528                                 RESTClient client = new RESTClient(config).
529                                         addHeader('X-TransactionId', aaiRequestId).
530                                         addHeader('X-FromAppId', 'MSO').
531                                         addHeader('Content-Type', 'application/xml').
532                                         addHeader('Accept','application/xml');
533                                 logDebug('sending GET to AAI endpoint \'' + endPoint + '\'', isDebugLogEnabled)
534                                 APIResponse response = client.httpGet()
535                                 utils.logAudit("createVfModule - invoking httpGet() to AAI")
536
537                                 responseData = response.getResponseBodyAsString()
538                                 if (responseData != null) {
539                                         logDebug("Received generic VNF data: " + responseData, isDebugLogEnabled)
540
541                                 }
542
543                                 utils.logAudit("createVfModule - queryAAIVfModule Response: " + responseData)
544                                 utils.logAudit("createVfModule - queryAAIVfModule ResponseCode: " + response.getStatusCode())
545
546                                 execution.setVariable('DCVFM_queryAAIVfModuleResponseCode', response.getStatusCode())
547                                 execution.setVariable('DCVFM_queryAAIVfModuleResponse', responseData)
548                                 logDebug('Response code:' + response.getStatusCode(), isDebugLogEnabled)
549                                 logDebug('Response:' + System.lineSeparator() + responseData, isDebugLogEnabled)
550                                 if (response.getStatusCode() == 200) {
551                                         // Parse the VNF record from A&AI to find base module info
552                                         logDebug('Parsing the VNF data to find base module info', isDebugLogEnabled)
553                                         if (responseData != null) {
554                                                 def vfModulesText = utils.getNodeXml(responseData, "vf-modules")
555                                                 def xmlVfModules= new XmlSlurper().parseText(vfModulesText)
556                                                 def vfModules = xmlVfModules.'**'.findAll {it.name() == "vf-module"}
557                                                 int vfModulesSize = 0
558                                                 for (i in 0..vfModules.size()-1) {
559                                                         def vfModuleXml = groovy.xml.XmlUtil.serialize(vfModules[i])
560                                                         def isBaseVfModule = utils.getNodeText(vfModuleXml, "is-base-vf-module")
561
562                                                         if (isBaseVfModule == "true") {
563                                                             String baseModuleId = utils.getNodeText1(vfModuleXml, "vf-module-id")
564                                                             execution.setVariable("DCVFM_baseVfModuleId", baseModuleId)
565                                                             logDebug('Received baseVfModuleId: ' + baseModuleId, isDebugLogEnabled)
566                                                             String baseModuleHeatStackId = utils.getNodeText1(vfModuleXml, "heat-stack-id")
567                                                             execution.setVariable("DCVFM_baseVfModuleHeatStackId", baseModuleHeatStackId)
568                                                             logDebug('Received baseVfModuleHeatStackId: ' + baseModuleHeatStackId, isDebugLogEnabled)
569                                                         }
570                                                 }
571                                         }
572                                 }
573                         } catch (Exception ex) {
574                                 ex.printStackTrace()
575                                 logDebug('Exception occurred while executing AAI GET:' + ex.getMessage(),isDebugLogEnabled)
576                                 exceptionUtil.buildAndThrowWorkflowException(execution, 1002, 'AAI GET Failed:' + ex.getMessage())
577                         }
578                         logDebug('Exited ' + method, isDebugLogEnabled)
579                 } catch (BpmnError e) {
580                         throw e;
581                 } catch (Exception e) {
582                         logError('Caught exception in ' + method, e)
583                         exceptionUtil.buildAndThrowWorkflowException(execution, 1002, 'Error in queryAAIVfModule(): ' + e.getMessage())
584                 }
585         }
586
587
588         public void preProcessSDNCAssignRequest(Execution execution){
589                 def isDebugLogEnabled = execution.getVariable("isDebugLogEnabled")
590                 execution.setVariable("prefix", Prefix)
591                 logDebug(" ======== STARTED preProcessSDNCAssignRequest ======== ", isDebugLogEnabled)
592                 def vnfId = execution.getVariable("DCVFM_vnfId")
593                 def vfModuleId = execution.getVariable("DCVFM_vfModuleId")
594                 def serviceInstanceId = execution.getVariable("DCVFM_serviceInstanceId")
595                 logDebug("NEW VNF ID: " + vnfId, isDebugLogEnabled)
596                 utils.logAudit("NEW VNF ID: " + vnfId)
597
598                 try{
599
600                         //Build SDNC Request
601
602                         def svcInstId = ""
603                         if (serviceInstanceId == null || serviceInstanceId.isEmpty()) {
604                                 svcInstId = vfModuleId
605                         }
606                         else {
607                                 svcInstId = serviceInstanceId
608                         }
609
610                         String assignSDNCRequest = buildSDNCRequest(execution, svcInstId, "assign")
611
612                         assignSDNCRequest = utils.formatXml(assignSDNCRequest)
613                         execution.setVariable("DCVFM_assignSDNCRequest", assignSDNCRequest)
614                         logDebug("Outgoing AssignSDNCRequest is: \n" + assignSDNCRequest, isDebugLogEnabled)
615                         utils.logAudit("Outgoing AssignSDNCRequest is: \n" + assignSDNCRequest)
616
617                 }catch(Exception e){
618                         utils.log("ERROR", "Exception Occured Processing preProcessSDNCAssignRequest. Exception is:\n" + e, isDebugLogEnabled)
619                         exceptionUtil.buildAndThrowWorkflowException(execution, 1002, "Error Occurred during prepareProvision Method:\n" + e.getMessage())
620                 }
621                 logDebug("======== COMPLETED preProcessSDNCAssignRequest ======== ", isDebugLogEnabled)
622         }
623
624         public void preProcessSDNCGetRequest(Execution execution){
625                 def isDebugLogEnabled = execution.getVariable("isDebugLogEnabled")
626                 execution.setVariable("prefix", Prefix)
627                 utils.log("DEBUG", " ======== STARTED preProcessSDNCGetRequest Process ======== ", isDebugLogEnabled)
628                 try{
629                         String response = execution.getVariable("DCVFM_assignSDNCAdapterResponse")
630                         utils.logAudit("DCVFM_assignSDNCAdapterResponse is: \n" + response)
631
632                         String data = utils.getNodeXml(response, "response-data")
633                         data = data.replaceAll("&lt;", "<")
634                         data = data.replaceAll("&gt;", ">")
635                         String vnfId = utils.getNodeText1(data, "vnf-id")
636                         def vfModuleId = execution.getVariable('DCVFM_vfModuleId')
637                         def serviceInstanceId = execution.getVariable('DCVFM_serviceInstanceId')
638
639                         String uuid = execution.getVariable('testReqId') // for junits
640                         if(uuid==null){
641                                 uuid = execution.getVariable("mso-request-id") + "-" +          System.currentTimeMillis()
642                         }
643
644                         String serviceOperation = "/VNF-API:vnfs/vnf-list/" + vfModuleId
645                         def callbackUrl = execution.getVariable("DCVFM_sdncCallbackUrl")
646                         utils.logAudit("callbackUrl:" + callbackUrl)
647
648                         def svcInstId = ""
649                         if (serviceInstanceId == null || serviceInstanceId.isEmpty()) {
650                                 svcInstId = vfModuleId
651                         }
652                         else {
653                                 svcInstId = serviceInstanceId
654                         }
655
656                         //!!!! TEMPORARY WORKAROUND FOR SDNC REPLICATION ISSUE
657                         sleep(5000)
658
659                         String SDNCGetRequest =
660                                         """<sdncadapterworkflow:SDNCAdapterWorkflowRequest xmlns:ns5="http://org.openecomp/mso/request/types/v1"
661                                                                                         xmlns:sdncadapterworkflow="http://org.openecomp/mso/workflow/schema/v1"
662                                                                                         xmlns:sdncadapter="http://org.openecomp/workflow/sdnc/adapter/schema/v1">
663                                         <sdncadapter:RequestHeader>
664                                         <sdncadapter:RequestId>${uuid}</sdncadapter:RequestId>
665                                         <sdncadapter:SvcInstanceId>${svcInstId}</sdncadapter:SvcInstanceId>
666                                         <sdncadapter:SvcAction>query</sdncadapter:SvcAction>
667                                         <sdncadapter:SvcOperation>${serviceOperation}</sdncadapter:SvcOperation>
668                                         <sdncadapter:CallbackUrl>${callbackUrl}</sdncadapter:CallbackUrl>
669                                         <sdncadapter:MsoAction>mobility</sdncadapter:MsoAction>
670                                 </sdncadapter:RequestHeader>
671                                         <sdncadapterworkflow:SDNCRequestData></sdncadapterworkflow:SDNCRequestData>
672                                 </sdncadapterworkflow:SDNCAdapterWorkflowRequest>"""
673
674                         utils.logAudit("SDNCGetRequest: \n" + SDNCGetRequest)
675                         execution.setVariable("DCVFM_getSDNCRequest", SDNCGetRequest)
676                         utils.log("DEBUG", "Outgoing GetSDNCRequest is: \n" + SDNCGetRequest, isDebugLogEnabled)
677
678                 }catch(Exception e){
679                         utils.log("ERROR", "Exception Occurred Processing preProcessSDNCGetRequest. Exception is:\n" + e, isDebugLogEnabled)
680                         exceptionUtil.buildAndThrowWorkflowException(execution, 1002, "Error Occured during prepareProvision Method:\n" + e.getMessage())
681                 }
682                 utils.log("DEBUG", "======== COMPLETED preProcessSDNCGetRequest Process ======== ", isDebugLogEnabled)
683         }
684
685
686         public void preProcessVNFAdapterRequest(Execution execution) {
687                 def method = getClass().getSimpleName() + '.VNFAdapterCreateVfModule(' +
688                         'execution=' + execution.getId() +
689                         ')'
690                 def isDebugLogEnabled = execution.getVariable('isDebugLogEnabled')
691                 logDebug('Entered ' + method, isDebugLogEnabled)
692
693                 //def xml = execution.getVariable("DoCreateVfModuleRequest")
694                 //logDebug('VNF REQUEST is: ' + xml, isDebugLogEnabled)
695
696                 //Get variables
697                 //cloudSiteId
698                 def cloudSiteId = execution.getVariable("DCVFM_cloudSiteId")
699                 //tenantId
700                 def tenantId = execution.getVariable("DCVFM_tenantId")
701                 //vnfType
702                 def vnfType = execution.getVariable("DCVFM_vnfType")
703                 //vnfName
704                 def vnfName = execution.getVariable("DCVFM_vnfName")
705                 //vnfId
706                 def vnfId = execution.getVariable("DCVFM_vnfId")
707                 //vfModuleName
708                 def vfModuleName = execution.getVariable("DCVFM_vfModuleName")
709                 //vfModuleModelName
710                 def vfModuleModelName = execution.getVariable("DCVFM_vfModuleModelName")
711                 //vfModuleId
712                 def vfModuleId = execution.getVariable("DCVFM_vfModuleId")
713                 //requestId
714                 def requestId = execution.getVariable("DCVFM_requestId")
715                 //serviceId
716                 def serviceId = execution.getVariable("DCVFM_serviceId")
717                 //serviceInstanceId
718                 def serviceInstanceId = execution.getVariable("DCVFM_serviceInstanceId")
719                 //backoutOnFailure
720                 def backoutOnFailure = execution.getVariable("DCVFM_backoutOnFailure")
721                 //volumeGroupId
722                 def volumeGroupId = execution.getVariable("DCVFM_volumeGroupId")
723                 // baseVfModuleId
724                 def baseVfModuleId = execution.getVariable("DCVFM_baseVfModuleId")
725                 // baseVfModuleStackId
726                 def baseVfModuleStackId = execution.getVariable("DCVFM_baseVfModuleHeatStackId")
727                 // asdcServiceModelVersion
728                 def asdcServiceModelVersion = execution.getVariable("DCVFM_asdcServiceModelVersion")
729                 //volumeGroupStackId
730                 def volumeGroupStackId = execution.getVariable("DCVFM_volumeGroupStackId")
731                 //modelCustomizationUuid
732                 def modelCustomizationUuid = execution.getVariable("DCVFM_modelCustomizationUuid")
733
734                 def messageId = execution.getVariable('mso-request-id') + '-' +
735                                 System.currentTimeMillis()
736
737                 def notificationUrl = createCallbackURL(execution, "VNFAResponse", messageId)
738                 def useQualifiedHostName = execution.getVariable("URN_mso_use_qualified_host")
739
740                 utils.logAudit("notificationUrl: " + notificationUrl)
741                 utils.logAudit("QualifiedHostName: " + useQualifiedHostName)
742
743                 if ('true'.equals(useQualifiedHostName)) {
744                         notificationUrl = utils.getQualifiedHostNameForCallback(notificationUrl)
745                 }
746
747                 String vnfParams
748                         if(execution.getVariable("DCVFM_vnfParamsExistFlag") == true){
749                                 StringBuilder sbParams = new StringBuilder()
750                                 Map<String, String> paramsMap = execution.getVariable("DCVFM_vnfParamsMap")
751
752                                 for (Map.Entry<String, String> entry : paramsMap.entrySet()) {
753                                         String paramsXml
754                                         String paramName = entry.getKey();
755                                         String paramValue = entry.getValue()
756                                         paramsXml =
757                                                         """     <entry>
758                                                         <key>${paramName}</key>
759                                                 <value>${paramValue}</value>
760                                                 </entry>
761                                         """
762
763                                         vnfParams = sbParams.append(paramsXml)
764                                 }
765                         }else{
766                                 vnfParams = ""
767                         }
768
769                 //Get SDNC Response Data for VnfSubCreate Request
770                 String sdncGetResponse = execution.getVariable('DCVFM_getSDNCAdapterResponse')
771                 utils.logAudit("sdncGetResponse: " + sdncGetResponse)
772
773                 String vfModuleParams = buildVfModuleParams(vnfParams, sdncGetResponse, vnfId, vnfName,
774                                 vfModuleId, vfModuleName)
775
776                 def svcInstId = ""
777                 if (serviceInstanceId == null || serviceInstanceId.isEmpty()) {
778                                 svcInstId = serviceId
779                 }
780                 else {
781                         svcInstId = serviceInstanceId
782                 }
783
784
785                 def createVnfARequest = """
786                 <createVfModuleRequest>
787                 <cloudSiteId>${cloudSiteId}</cloudSiteId>
788                 <tenantId>${tenantId}</tenantId>
789                 <vnfId>${vnfId}</vnfId>
790                 <vnfName>${vnfName}</vnfName>
791                 <vfModuleName>${vfModuleName}</vfModuleName>
792                 <vfModuleId>${vfModuleId}</vfModuleId>
793                 <vnfType>${vnfType}</vnfType>
794                 <vfModuleType>${vfModuleModelName}</vfModuleType>
795                 <vnfVersion>${asdcServiceModelVersion}</vnfVersion>
796                 <modelCustomizationUuid>${modelCustomizationUuid}</modelCustomizationUuid>
797                 <requestType></requestType>
798                 <volumeGroupId>${volumeGroupId}</volumeGroupId>
799         <volumeGroupStackId>${volumeGroupStackId}</volumeGroupStackId>
800         <baseVfModuleId>${baseVfModuleId}</baseVfModuleId>
801         <baseVfModuleStackId>${baseVfModuleStackId}</baseVfModuleStackId>
802         <skipAAI>true</skipAAI>
803         <backout>${backoutOnFailure}</backout>
804         <failIfExists>true</failIfExists>
805                 <vfModuleParams>
806                 ${vfModuleParams}
807                 </vfModuleParams>
808                 <msoRequest>
809                         <requestId>${requestId}</requestId>
810                         <serviceInstanceId>${svcInstId}</serviceInstanceId>
811                 </msoRequest>
812                 <messageId>${messageId}</messageId>
813                 <notificationUrl>${notificationUrl}</notificationUrl>
814                 </createVfModuleRequest>"""
815
816                 utils.logAudit("Create VfModule Request to VNF Adapter : " + createVnfARequest)
817                 logDebug("Create VfModule Request to VNF Adapter: " + createVnfARequest, isDebugLogEnabled)
818                 execution.setVariable("DCVFM_createVnfARequest", createVnfARequest)
819         }
820
821         /**
822          * Validates the request, request id and service instance id.  If a problem is found,
823          * a WorkflowException is generated and an MSOWorkflowException event is thrown. This
824          * method also sets up the log context for the workflow.
825          * @param execution the execution
826          * @return the validated request
827          */
828         public String validateInfraRequest(Execution execution) {
829                 def method = getClass().getSimpleName() + '.validateInfraRequest(' +
830                         'execution=' + execution.getId() +
831                         ')'
832                 def isDebugLogEnabled = execution.getVariable('isDebugLogEnabled')
833                 logDebug('Entered ' + method, isDebugLogEnabled)
834
835                 String processKey = getProcessKey(execution);
836                 def prefix = execution.getVariable("prefix")
837
838                 if (prefix == null) {
839                         exceptionUtil.buildAndThrowWorkflowException(execution, 1002, processKey + " prefix is null")
840                 }
841
842                 try {
843                         def request = execution.getVariable(prefix + 'Request')
844
845                         if (request == null) {
846                                 request = execution.getVariable(processKey + 'Request')
847
848                                 if (request == null) {
849                                         request = execution.getVariable('bpmnRequest')
850                                 }
851
852                                 setVariable(execution, processKey + 'Request', null);
853                                 setVariable(execution, 'bpmnRequest', null);
854                                 setVariable(execution, prefix + 'Request', request);
855                         }
856
857                         if (request == null) {
858                                 exceptionUtil.buildAndThrowWorkflowException(execution, 1002, processKey + " request is null")
859                         }
860                         utils.logAudit("DoCreateVfModule Request: " + request)
861
862                         /*
863
864                         def requestId = execution.getVariable("mso-request-id")
865
866                         if (requestId == null) {
867                                 createWorkflowException(execution, 1002, processKey + " request has no mso-request-id")
868                         }
869
870                         def serviceInstanceId = execution.getVariable("mso-service-instance-id")
871
872                         if (serviceInstanceId == null) {
873                                 createWorkflowException(execution, 1002, processKey + " request message has no mso-service-instance-id")
874                         }
875
876                         utils.logContext(requestId, serviceInstanceId)
877                         */
878                         logDebug('Incoming message: ' + System.lineSeparator() + request, isDebugLogEnabled)
879                         logDebug('Exited ' + method, isDebugLogEnabled)
880                         return request
881                 } catch (BpmnError e) {
882                         throw e;
883                 } catch (Exception e) {
884                         logError('Caught exception in ' + method, e)
885                         exceptionUtil.buildAndThrowWorkflowException(execution, 1002, "Invalid Message")
886                 }
887         }
888
889         public boolean isVolumeGroupIdPresent(Execution execution) {
890
891                 def method = getClass().getSimpleName() + '.isVolumeGroupIdPresent(' +
892                         'execution=' + execution.getId() +
893                         ')'
894                 def isDebugLogEnabled = execution.getVariable('isDebugLogEnabled')
895                 logDebug('Entered ' + method, isDebugLogEnabled)
896
897                 def request = execution.getVariable('DoCreateVfModuleRequest')
898                 String volumeGroupId = utils.getNodeText1(request, "volume-group-id")
899                 if (volumeGroupId == null || volumeGroupId.isEmpty()) {
900                         logDebug('No volume group id is present', isDebugLogEnabled)
901                         return false
902                 }
903                 else {
904                         logDebug('Volume group id is present', isDebugLogEnabled)
905                         return true
906                 }
907
908         }
909
910         public boolean isVolumeGroupNamePresent(Execution execution) {
911
912                 def method = getClass().getSimpleName() + '.isVolumeGroupNamePresent(' +
913                         'execution=' + execution.getId() +
914                         ')'
915                 def isDebugLogEnabled = execution.getVariable('isDebugLogEnabled')
916                 logDebug('Entered ' + method, isDebugLogEnabled)
917
918                 def request = execution.getVariable('DoCreateVfModuleRequest')
919                 String volumeGroupName = utils.getNodeText1(request, "volume-group-name")
920                 if (volumeGroupName == null || volumeGroupName.isEmpty()) {
921                         logDebug('No volume group name is present', isDebugLogEnabled)
922                         return false
923                 }
924                 else {
925                         logDebug('Volume group name is present', isDebugLogEnabled)
926                         return true
927                 }
928
929         }
930
931         public String buildSDNCRequest(Execution execution, String svcInstId, String action){
932
933                 String uuid = execution.getVariable('testReqId') // for junits
934                 if(uuid==null){
935                         uuid = execution.getVariable("mso-request-id") + "-" +          System.currentTimeMillis()
936                 }
937                 def callbackURL = execution.getVariable("DCVFM_sdncCallbackUrl")
938                 def requestId = execution.getVariable("DCVFM_requestId")
939                 def serviceId = execution.getVariable("DCVFM_serviceId")
940                 def vnfType = execution.getVariable("DCVFM_vnfType")
941                 def vnfName = execution.getVariable("DCVFM_vnfName")
942                 def tenantId = execution.getVariable("DCVFM_tenantId")
943                 def source = execution.getVariable("DCVFM_source")
944                 def backoutOnFailure = execution.getVariable("DCVFM_backoutOnFailure")
945                 def vfModuleId = execution.getVariable("DCVFM_vfModuleId")
946                 def vfModuleName = execution.getVariable("DCVFM_vfModuleName")
947                 def vfModuleModelName = execution.getVariable("DCVFM_vfModuleModelName")
948                 def vnfId = execution.getVariable("DCVFM_vnfId")
949                 def cloudSiteId = execution.getVariable("DCVFM_cloudSiteId")
950
951                 String sdncVNFParamsXml = ""
952
953                 if(execution.getVariable("DCVFM_vnfParamsExistFlag") == true){
954                         sdncVNFParamsXml = buildSDNCParamsXml(execution)
955                 }else{
956                         sdncVNFParamsXml = ""
957                 }
958
959                 String sdncRequest =
960                 """<sdncadapterworkflow:SDNCAdapterWorkflowRequest xmlns:ns5="http://org.openecomp/mso/request/types/v1"
961                                                                                                         xmlns:sdncadapterworkflow="http://org.openecomp/mso/workflow/schema/v1"
962                                                                                                         xmlns:sdncadapter="http://org.openecomp/workflow/sdnc/adapter/schema/v1">
963            <sdncadapter:RequestHeader>
964                                 <sdncadapter:RequestId>${requestId}</sdncadapter:RequestId>
965                                 <sdncadapter:SvcInstanceId>${svcInstId}</sdncadapter:SvcInstanceId>
966                                 <sdncadapter:SvcAction>${action}</sdncadapter:SvcAction>
967                                 <sdncadapter:SvcOperation>vnf-topology-operation</sdncadapter:SvcOperation>
968                                 <sdncadapter:CallbackUrl>${callbackURL}</sdncadapter:CallbackUrl>
969                 </sdncadapter:RequestHeader>
970         <sdncadapterworkflow:SDNCRequestData>
971                 <request-information>
972                         <request-id>${requestId}</request-id>
973                         <request-action>VNFActivateRequest</request-action>
974                         <source>${source}</source>
975                         <notification-url/>
976                 </request-information>
977                 <service-information>
978                         <service-id>${serviceId}</service-id>
979                         <service-type>${serviceId}</service-type>
980                         <service-instance-id>${svcInstId}</service-instance-id>
981                         <subscriber-name>notsurewecare</subscriber-name>
982                 </service-information>
983                 <vnf-request-information>
984                         <vnf-id>${vfModuleId}</vnf-id>
985                         <vnf-type>${vfModuleModelName}</vnf-type>
986                         <vnf-name>${vfModuleName}</vnf-name>
987                         <generic-vnf-id>${vnfId}</generic-vnf-id>
988                         <generic-vnf-name>${vnfName}</generic-vnf-name>
989                         <generic-vnf-type>${vnfType}</generic-vnf-type>
990                         <aic-cloud-region>${cloudSiteId}</aic-cloud-region>
991                         <tenant>${tenantId}</tenant>
992                 ${sdncVNFParamsXml}
993                 </vnf-request-information>
994         </sdncadapterworkflow:SDNCRequestData>
995         </sdncadapterworkflow:SDNCAdapterWorkflowRequest>"""
996
997         utils.logAudit("sdncRequest:  " + sdncRequest)
998         return sdncRequest
999
1000         }
1001
1002         public void preProcessSDNCActivateRequest(Execution execution) {
1003                 def method = getClass().getSimpleName() + '.preProcessSDNCActivateRequest(' +
1004                         'execution=' + execution.getId() +
1005                         ')'
1006                 def isDebugLogEnabled = execution.getVariable('isDebugLogEnabled')
1007                 logDebug('Entered ' + method, isDebugLogEnabled)
1008                 execution.setVariable("prefix", Prefix)
1009                 logDebug(" ======== STARTED preProcessSDNCActivateRequest Process ======== ", isDebugLogEnabled)
1010                 try{
1011                         String vnfId = execution.getVariable("DCVFM_vnfId")
1012                         String vfModuleId = execution.getVariable("DCVFM_vfModuleId")
1013                         String serviceInstanceId = execution.getVariable("DCVFM_serviceInstanceId")
1014
1015                         def svcInstId = ""
1016                         if (serviceInstanceId == null || serviceInstanceId.isEmpty()) {
1017                                 svcInstId = vfModuleId
1018                         }
1019                         else {
1020                                 svcInstId = serviceInstanceId
1021                         }
1022                         String activateSDNCRequest = buildSDNCRequest(execution, svcInstId, "activate")
1023
1024                         execution.setVariable("DCVFM_activateSDNCRequest", activateSDNCRequest)
1025                         logDebug("Outgoing CommitSDNCRequest is: \n" + activateSDNCRequest, isDebugLogEnabled)
1026                         utils.logAudit("Outgoing CommitSDNCRequest is: \n"  + activateSDNCRequest)
1027
1028                 }catch(Exception e){
1029                         log.debug("Exception Occured Processing preProcessSDNCActivateRequest. Exception is:\n" + e, isDebugLogEnabled)
1030                         exceptionUtil.buildAndThrowWorkflowException(execution, 1002, "Error Occured during  preProcessSDNCActivateRequest Method:\n" + e.getMessage())
1031                 }
1032                 logDebug("======== COMPLETED  preProcessSDNCActivateRequest Process ======== ", isDebugLogEnabled)
1033         }
1034
1035         public void postProcessVNFAdapterRequest(Execution execution) {
1036                 def method = getClass().getSimpleName() + '.postProcessVNFAdapterRequest(' +
1037                         'execution=' + execution.getId() +
1038                         ')'
1039                 def isDebugLogEnabled = execution.getVariable('isDebugLogEnabled')
1040                 logDebug('Entered ' + method, isDebugLogEnabled)
1041                 execution.setVariable("prefix",Prefix)
1042                 try{
1043                 logDebug(" *** STARTED postProcessVNFAdapterRequest Process*** ", isDebugLogEnabled)
1044
1045                 String vnfResponse = execution.getVariable("DCVFM_createVnfAResponse")
1046                 logDebug("VNF Adapter Response is: " + vnfResponse, isDebugLogEnabled)
1047                 utils.logAudit("createVnfAResponse is: \n"  + vnfResponse)
1048
1049                 RollbackData rollbackData = execution.getVariable("RollbackData")
1050                 if(vnfResponse != null){
1051
1052                         if(vnfResponse.contains("createVfModuleResponse")){
1053                                 logDebug("Received a Good Response from VNF Adapter for CREATE_VF_MODULE Call.", isDebugLogEnabled)
1054                                 execution.setVariable("DCVFM_vnfVfModuleCreateCompleted", true)
1055                                 String heatStackId = utils.getNodeText1(vnfResponse, "vfModuleStackId")
1056                                 execution.setVariable("DCVFM_heatStackId", heatStackId)
1057                                 logDebug("Received heat stack id from VNF Adapter: " + heatStackId, isDebugLogEnabled)
1058                                 rollbackData.put("VFMODULE", "heatstackid", heatStackId)
1059                                 // Parse vnfOutputs for network_fqdn
1060                                 if (vnfResponse.contains("vfModuleOutputs")) {
1061                                         def vfModuleOutputsXml = utils.getNodeXml(vnfResponse, "vfModuleOutputs")
1062                                         InputSource source = new InputSource(new StringReader(vfModuleOutputsXml));
1063                         DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
1064                         docFactory.setNamespaceAware(true)
1065                         DocumentBuilder docBuilder = docFactory.newDocumentBuilder()
1066                         Document outputsXml = docBuilder.parse(source)
1067
1068                                         NodeList entries = outputsXml.getElementsByTagNameNS("*", "entry")
1069                                         List contrailNetworkPolicyFqdnList = []
1070                                         for (int i = 0; i< entries.getLength(); i++) {
1071                                                 Node node = entries.item(i)
1072                                                 if (node.getNodeType() == Node.ELEMENT_NODE) {
1073                                                         Element element = (Element) node
1074                                                         String key = element.getElementsByTagNameNS("*", "key").item(0).getTextContent()
1075                                                         if (key.equals("contrail-service-instance-fqdn")) {
1076                                                                 String contrailServiceInstanceFqdn = element.getElementsByTagNameNS("*", "value").item(0).getTextContent()
1077                                                                 logDebug("Obtained contrailServiceInstanceFqdn: " + contrailServiceInstanceFqdn, isDebugLogEnabled)
1078                                                                 execution.setVariable("DCVFM_contrailServiceInstanceFqdn", contrailServiceInstanceFqdn)
1079                                                         }
1080                                                         else if (key.endsWith("contrail_network_policy_fqdn")) {
1081                                                                 String contrailNetworkPolicyFqdn = element.getElementsByTagNameNS("*", "value").item(0).getTextContent()
1082                                                                 logDebug("Obtained contrailNetworkPolicyFqdn: " + contrailNetworkPolicyFqdn, isDebugLogEnabled)
1083                                                                 contrailNetworkPolicyFqdnList.add(contrailNetworkPolicyFqdn)                                                            
1084                                                         }
1085                                                         else if (key.equals("oam_management_v4_address")) {
1086                                                                 String oamManagementV4Address = element.getElementsByTagNameNS("*", "value").item(0).getTextContent()
1087                                                                 logDebug("Obtained oamManagementV4Address: " + oamManagementV4Address, isDebugLogEnabled)
1088                                                                 execution.setVariable("DCVFM_oamManagementV4Address", oamManagementV4Address)                                                   
1089                                                         }
1090                                                         else if (key.equals("oam_management_v6_address")) {
1091                                                                 String oamManagementV6Address = element.getElementsByTagNameNS("*", "value").item(0).getTextContent()
1092                                                                 logDebug("Obtained oamManagementV6Address: " + oamManagementV6Address, isDebugLogEnabled)
1093                                                                 execution.setVariable("DCVFM_oamManagementV6Address", oamManagementV6Address)
1094                                                         }
1095                                                 
1096                                                 }                                               
1097                                         }
1098                                         if (!contrailNetworkPolicyFqdnList.isEmpty()) {
1099                                                 execution.setVariable("DCVFM_contrailNetworkPolicyFqdnList", contrailNetworkPolicyFqdnList)
1100                                         }
1101                                 }
1102                         }else{
1103                                 logDebug("Received a BAD Response from VNF Adapter for CREATE_VF_MODULE Call.", isDebugLogEnabled)
1104                                 exceptionUtil.buildAndThrowWorkflowException(execution, 1002, "VNF Adapter Error")
1105                         }
1106                 }else{
1107                         logDebug("Response from VNF Adapter is Null for CREATE_VF_MODULE Call.", isDebugLogEnabled)
1108                         exceptionUtil.buildAndThrowWorkflowException(execution, 1002, "Empty response from VNF Adapter")
1109                 }
1110
1111                 rollbackData.put("VFMODULE", "rollbackVnfAdapterCreate", "true")
1112                 execution.setVariable("RollbackData", rollbackData)
1113
1114                 }catch(BpmnError b){
1115                         throw b
1116                 }catch(Exception e){
1117                         logDebug("Internal Error Occured in PostProcess Method", isDebugLogEnabled)
1118                         exceptionUtil.buildAndThrowWorkflowException(execution, 1002, "Internal Error Occured in PostProcess Method")
1119                 }
1120                 logDebug(" *** COMPLETED postProcessVnfAdapterResponse Process*** ", isDebugLogEnabled)
1121         }
1122
1123
1124         public void preProcessUpdateAAIVfModuleRequestOrch(Execution execution) {
1125                 def method = getClass().getSimpleName() + '.preProcessUpdateAAIVfModuleRequestOrch(' +
1126                         'execution=' + execution.getId() +
1127                         ')'
1128                 def isDebugLogEnabled = execution.getVariable('isDebugLogEnabled')
1129                 logDebug('Entered ' + method, isDebugLogEnabled)
1130                 execution.setVariable("prefix", Prefix)
1131                 logDebug(" ======== STARTED preProcessUpdateAAIVfModuleRequestOrch ======== ", isDebugLogEnabled)
1132
1133                 try{
1134
1135                         //Build UpdateAAIVfModule Request
1136                         boolean setContrailServiceInstanceFqdn = false
1137                         def contrailServiceInstanceFqdn = execution.getVariable("DCVFM_contrailServiceInstanceFqdn")
1138                         if (!contrailServiceInstanceFqdn.equals("")) {
1139                                 setContrailServiceInstanceFqdn = true
1140                         }
1141
1142                         String updateAAIVfModuleRequest = buildUpdateAAIVfModuleRequest(execution, false, true, true, setContrailServiceInstanceFqdn)
1143
1144                         updateAAIVfModuleRequest = utils.formatXml(updateAAIVfModuleRequest)
1145                         execution.setVariable("DCVFM_updateAAIVfModuleRequest", updateAAIVfModuleRequest)
1146                         logDebug("Outgoing UpdateAAIVfModuleRequest is: \n" + updateAAIVfModuleRequest, isDebugLogEnabled)
1147                         utils.logAudit("Outgoing UpdateAAIVfModuleRequest is: \n"  + updateAAIVfModuleRequest)
1148
1149                 }catch(Exception e){
1150                         utils.log("ERROR", "Exception Occured Processing preProcessUpdateAAIVfModuleRequestOrch. Exception is:\n" + e, isDebugLogEnabled)
1151                         exceptionUtil.buildAndThrowWorkflowException(execution, 1002, "Error Occured during preProcessUpdateAAIVfModuleRequestOrch Method:\n" + e.getMessage())
1152                 }
1153                 logDebug("======== COMPLETED preProcessUpdateAAIVfModuleRequestOrch ======== ", isDebugLogEnabled)
1154
1155         }
1156
1157         public void preProcessUpdateAAIVfModuleRequestGroup(Execution execution) {
1158                 def method = getClass().getSimpleName() + '.preProcessUpdateAAIVfModuleRequestGroup(' +
1159                         'execution=' + execution.getId() +
1160                         ')'
1161                 def isDebugLogEnabled = execution.getVariable('isDebugLogEnabled')
1162                 logDebug('Entered ' + method, isDebugLogEnabled)
1163                 execution.setVariable("prefix", Prefix)
1164                 logDebug(" ======== STARTED preProcessUpdateAAIVfModuleRequestGroup ======== ", isDebugLogEnabled)
1165
1166                 try{
1167
1168                         //Build UpdateAAIVfModule Request
1169
1170                         String updateAAIVfModuleRequest = buildUpdateAAIVfModuleRequest(execution, true, false, false, false)
1171
1172                         updateAAIVfModuleRequest = utils.formatXml(updateAAIVfModuleRequest)
1173                         execution.setVariable("DCVFM_updateAAIVfModuleRequest", updateAAIVfModuleRequest)
1174                         logDebug("Outgoing UpdateAAIVfModuleRequest is: \n" + updateAAIVfModuleRequest, isDebugLogEnabled)
1175                         utils.logAudit("Outgoing UpdateAAIVfModuleRequest is: \n"  + updateAAIVfModuleRequest)
1176
1177                 }catch(Exception e){
1178                         utils.log("ERROR", "Exception Occured Processing preProcessUpdateAAIVfModuleRequestGroup. Exception is:\n" + e, isDebugLogEnabled)
1179                         exceptionUtil.buildAndThrowWorkflowException(execution, 1002, "Error Occured during preProcessUpdateAAIVfModuleRequestGroup Method:\n" + e.getMessage())
1180                 }
1181                 logDebug("======== COMPLETED  preProcessUpdateAAIVfModuleRequestGroup ======== ", isDebugLogEnabled)
1182
1183         }
1184
1185         public void validateSDNCResponse(Execution execution, String response, String method){
1186                 def isDebugLogEnabled=execution.getVariable("isDebugLogEnabled")
1187                 execution.setVariable("prefix",Prefix)
1188                 logDebug(" *** STARTED ValidateSDNCResponse Process*** ", isDebugLogEnabled)
1189
1190                 WorkflowException workflowException = execution.getVariable("WorkflowException")
1191                 boolean successIndicator = execution.getVariable("SDNCA_SuccessIndicator")
1192
1193                 utils.logAudit("workflowException: " + workflowException)
1194
1195                 SDNCAdapterUtils sdncAdapterUtils = new SDNCAdapterUtils(this)
1196                 sdncAdapterUtils.validateSDNCResponse(execution, response, workflowException, successIndicator)
1197
1198                 utils.logAudit("SDNCResponse: " + response)
1199
1200                 String sdncResponse = response
1201                 if(execution.getVariable(Prefix + 'sdncResponseSuccess') == true){
1202                         logDebug("Received a Good Response from SDNC Adapter for " + method + " SDNC Call.  Response is: \n" + sdncResponse, isDebugLogEnabled)
1203                         RollbackData rollbackData = execution.getVariable("RollbackData")
1204
1205                         if(method.equals("assign")){
1206                                 rollbackData.put("VFMODULE", "rollbackSDNCRequestAssign", "true")
1207                                 execution.setVariable("CRTGVNF_sdncAssignCompleted", true)
1208                         }
1209                         else if (method.equals("activate")) {
1210                                 rollbackData.put("VFMODULE", "rollbackSDNCRequestActivate", "true")
1211                         }
1212                         execution.setVariable("RollbackData", rollbackData)
1213                 }else{
1214                         logDebug("Received a BAD Response from SDNC Adapter for " + method + " SDNC Call.", isDebugLogEnabled)
1215                         throw new BpmnError("MSOWorkflowException")
1216                 }
1217                 logDebug(" *** COMPLETED ValidateSDNCResponse Process*** ", isDebugLogEnabled)
1218         }
1219
1220         public void preProcessUpdateAfterCreateRequest(Execution execution){
1221                 def isDebugLogEnabled = execution.getVariable("isDebugLogEnabled")
1222                 execution.setVariable("prefix", Prefix)
1223                 utils.log("DEBUG", " ======== STARTED preProcessRequest Process ======== ", isDebugLogEnabled)
1224                 try{
1225                         String response = execution.getVariable("DCVFM_assignSDNCAdapterResponse")
1226                         utils.logAudit("DCVFM_assignSDNCAdapterResponse: " + response)
1227
1228                         String data = utils.getNodeXml(response, "response-data")
1229                         data = data.replaceAll("&lt;", "<")
1230                         data = data.replaceAll("&gt;", ">")
1231                         String vnfId = utils.getNodeText1(data, "vnf-id")
1232
1233                         String uuid = execution.getVariable('testReqId') // for junits
1234                         if(uuid==null){
1235                                 uuid = execution.getVariable("mso-request-id") + "-" +          System.currentTimeMillis()
1236                         }
1237
1238                         String serviceOperation = "/VNF-API:vnfs/vnf-list/" + vnfId
1239                         def callbackUrl = execution.getVariable("DCVFM_sdncCallbackUrl")
1240                         utils.logAudit("callbackUrl: " + callbackUrl)
1241
1242                         String SDNCGetRequest =
1243                                         """<sdncadapterworkflow:SDNCAdapterWorkflowRequest xmlns:ns5="http://org.openecomp/mso/request/types/v1"
1244                                                                                         xmlns:sdncadapterworkflow="http://org.openecomp/mso/workflow/schema/v1"
1245                                                                                         xmlns:sdncadapter="http://org.openecomp/workflow/sdnc/adapter/schema/v1">
1246                                         <sdncadapter:RequestHeader>
1247                                         <sdncadapter:RequestId>${uuid}</sdncadapter:RequestId>
1248                                         <sdncadapter:SvcAction>query</sdncadapter:SvcAction>
1249                                         <sdncadapter:SvcOperation>${serviceOperation}</sdncadapter:SvcOperation>
1250                                         <sdncadapter:CallbackUrl>${callbackUrl}</sdncadapter:CallbackUrl>
1251                                         <sdncadapter:MsoAction>mobility</sdncadapter:MsoAction>
1252                                 </sdncadapter:RequestHeader>
1253                                         <sdncadapterworkflow:SDNCRequestData></sdncadapterworkflow:SDNCRequestData>
1254                                 </sdncadapterworkflow:SDNCAdapterWorkflowRequest>"""
1255
1256                         execution.setVariable("DCVFM_getSDNCRequest", SDNCGetRequest)
1257                         utils.log("DEBUG", "Outgoing GetSDNCRequest is: \n" + SDNCGetRequest, isDebugLogEnabled)
1258                         utils.logAudit("Outgoing GetSDNCRequest: " + SDNCGetRequest)
1259
1260                 }catch(Exception e){
1261                         utils.log("ERROR", "Exception Occured Processing preProcessSDNCGetRequest. Exception is:\n" + e, isDebugLogEnabled)
1262                         exceptionUtil.buildAndThrowWorkflowException(execution, 1002, "Error Occured during prepareProvision Method:\n" + e.getMessage())
1263                 }
1264                 utils.log("DEBUG", "======== COMPLETED preProcessSDNCGetRequest Process ======== ", isDebugLogEnabled)
1265         }
1266
1267         public String buildUpdateAAIVfModuleRequest(Execution execution, boolean updateVolumeGroupId,
1268                 boolean updateOrchestrationStatus, boolean updateHeatStackId, boolean updateContrailFqdn){
1269
1270                 def vnfId = execution.getVariable("DCVFM_vnfId")
1271                 def vfModuleId = execution.getVariable("DCVFM_vfModuleId")
1272                 def volumeGroupIdString = ""
1273                 if (updateVolumeGroupId) {
1274                         volumeGroupIdString = "<volume-group-id>" + execution.getVariable("DCVFM_volumeGroupId") +
1275                                         "</volume-group-id>"
1276                 }
1277                 def orchestrationStatusString = ""
1278                 if (updateOrchestrationStatus) {
1279                         orchestrationStatusString = "<orchestration-status>Created</orchestration-status>"
1280                 }
1281                 def heatStackIdString = ""
1282                 if (updateHeatStackId) {
1283                         heatStackIdString = "<heat-stack-id>" + execution.getVariable("DCVFM_heatStackId") + "</heat-stack-id>"
1284                 }
1285                 def contrailFqdnString = ""
1286                 if (updateContrailFqdn) {
1287                         contrailFqdnString = "<contrail-service-instance-fqdn>" + execution.getVariable("DCVFM_contrailServiceInstanceFqdn") +
1288                                 "</contrail-service-instance-fqdn>"
1289                 }
1290
1291                 String updateAAIVfModuleRequest =
1292                         """<UpdateAAIVfModuleRequest>
1293                                 <vnf-id>${vnfId}</vnf-id>
1294                                 <vf-module-id>${vfModuleId}</vf-module-id>
1295                                 ${heatStackIdString}
1296                                 ${orchestrationStatusString}
1297                                 ${volumeGroupIdString}
1298                                 ${contrailFqdnString}
1299                         </UpdateAAIVfModuleRequest>"""
1300
1301         utils.logAudit("updateAAIVfModule Request: " + updateAAIVfModuleRequest)
1302         return updateAAIVfModuleRequest
1303
1304         }
1305
1306         public String buildSDNCParamsXml(Execution execution){
1307
1308                 String params = ""
1309                 StringBuilder sb = new StringBuilder()
1310                 Map<String, String> paramsMap = execution.getVariable("DCVFM_vnfParamsMap")
1311
1312                 for (Map.Entry<String, String> entry : paramsMap.entrySet()) {
1313                         String paramsXml
1314                         String key = entry.getKey();
1315                         if(key.endsWith("_network")){
1316                                 String requestKey = key.substring(0, key.indexOf("_network"))
1317                                 String requestValue = entry.getValue()
1318                                 paramsXml =
1319 """<vnf-networks>
1320         <network-role>{ functx:substring-before-match(data($param/@name), '_network') }</network-role>
1321         <network-name>{ $param/text() }</network-name>
1322 </vnf-networks>"""
1323                         }else{
1324                         paramsXml = ""
1325                         }
1326                         params = sb.append(paramsXml)
1327                 }
1328                 return params
1329         }
1330
1331    public void queryCloudRegion (Execution execution) {
1332                 def isDebugLogEnabled=execution.getVariable("isDebugLogEnabled")
1333                 execution.setVariable("prefix", Prefix)
1334                 utils.log("DEBUG", " ======== STARTED queryCloudRegion ======== ", isDebugLogEnabled)
1335
1336                 try {
1337                         String cloudRegion = execution.getVariable("DCVFM_cloudSiteId")
1338
1339                         // Prepare AA&I url
1340                         String aai_endpoint = execution.getVariable("URN_aai_endpoint")
1341                         AaiUtil aaiUtil = new AaiUtil(this)
1342                         String aai_uri = aaiUtil.getCloudInfrastructureCloudRegionUri(execution)
1343                         String queryCloudRegionRequest = "${aai_endpoint}${aai_uri}/" + cloudRegion
1344                         utils.logAudit("CloudRegion Request: " + queryCloudRegionRequest)
1345
1346                         execution.setVariable("DCVFM_queryCloudRegionRequest", queryCloudRegionRequest)
1347                         utils.log("DEBUG", "DCVFM_queryCloudRegionRequest - " + "\n" + queryCloudRegionRequest, isDebugLogEnabled)
1348
1349                         cloudRegion = aaiUtil.getAAICloudReqion(execution, queryCloudRegionRequest, "PO", cloudRegion)
1350
1351                         if ((cloudRegion != "ERROR")) {
1352                                 if(execution.getVariable("DCVFM_queryCloudRegionReturnCode") == "404"){
1353                                         execution.setVariable("DCVFM_cloudRegionForVolume", "AAIAIC25")
1354                                 }else{
1355                                 execution.setVariable("DCVFM_cloudRegionForVolume", cloudRegion)
1356                                 }
1357                                 execution.setVariable("DCVFM_isCloudRegionGood", true)
1358                         } else {
1359                                 String errorMessage = "AAI Query Cloud Region Unsuccessful. AAI Response Code: " + execution.getVariable("DCVFM_queryCloudRegionReturnCode")
1360                                 utils.log("DEBUG", errorMessage, isDebugLogEnabled)
1361                                 exceptionUtil.buildAndThrowWorkflowException(execution, 2500, errorMessage)
1362                                 execution.setVariable("DCVFM_isCloudRegionGood", false)
1363                         }
1364                         utils.log("DEBUG", " is Cloud Region Good: " + execution.getVariable("DCVFM_isCloudRegionGood"), isDebugLogEnabled)
1365
1366                 } catch(BpmnError b){
1367                         utils.log("ERROR", "Rethrowing MSOWorkflowException", isDebugLogEnabled)
1368                         throw b
1369                 }catch (Exception ex) {
1370                         // try error
1371                         String errorMessage = "Bpmn error encountered in CreateVfModule flow. Unexpected Response from AAI - " + ex.getMessage()
1372                         utils.log("ERROR", " AAI Query Cloud Region Failed.  Exception - " + "\n" + errorMessage, isDebugLogEnabled)
1373                         exceptionUtil.buildAndThrowWorkflowException(execution, 500, "Exception occured during queryCloudRegion method")
1374                 }
1375         }
1376
1377    /**
1378     *
1379     *This method occurs when an MSOWorkflowException is caught.  It logs the
1380     *variables and ensures that the "WorkflowException" Variable is set.
1381     *
1382     */
1383    public void processBPMNException(Execution execution){
1384            def isDebugEnabled=execution.getVariable("isDebugLogEnabled")
1385            execution.setVariable("prefix",Prefix)
1386            try{
1387                    utils.log("DEBUG", "Caught a BPMN Exception", isDebugEnabled)
1388                    utils.log("DEBUG", "Started processBPMNException Method", isDebugEnabled)
1389                    utils.log("DEBUG", "Variables List: " + execution.getVariables(), isDebugEnabled)
1390                    if(execution.getVariable("WorkflowException") == null){
1391                            exceptionUtil.buildAndThrowWorkflowException(execution, 500, "Exception occured during DoCreateVfModule Sub Process")
1392                    }
1393
1394            }catch(Exception e){
1395                    utils.log("DEBUG", "Caught Exception during processBPMNException Method: " + e, isDebugEnabled)
1396            }
1397            utils.log("DEBUG", "Completed processBPMNException Method", isDebugEnabled)
1398    }
1399
1400    public void prepareCreateAAIVfModuleVolumeGroupRequest(Execution execution) {
1401                 def method = getClass().getSimpleName() + '.prepareCreateAAIVfModuleVolumeGroupRequest(' +
1402                         'execution=' + execution.getId() +
1403                         ')'
1404                 def isDebugLogEnabled = execution.getVariable('isDebugLogEnabled')
1405                 logDebug('Entered ' + method, isDebugLogEnabled)
1406                 execution.setVariable("prefix", Prefix)
1407                 logDebug(" ======== STARTED prepareCreateAAIVfModuleVolumeGroupRequest ======== ", isDebugLogEnabled)
1408
1409                 try{
1410
1411                         //Build CreateAAIVfModuleVolumeGroup Request
1412
1413                         def vnfId = execution.getVariable("DCVFM_vnfId")
1414                         def vfModuleId = execution.getVariable("DCVFM_vfModuleId")
1415                         def volumeGroupId = execution.getVariable("DCVFM_volumeGroupId")
1416                         //def aicCloudRegion = execution.getVariable("DCVFM_cloudSiteId")
1417                         def aicCloudRegion = execution.getVariable("DCVFM_cloudRegionForVolume")
1418                         String createAAIVfModuleVolumeGroupRequest =
1419                         """<CreateAAIVfModuleVolumeGroupRequest>
1420                                 <vnf-id>${vnfId}</vnf-id>
1421                                 <vf-module-id>${vfModuleId}</vf-module-id>
1422                                 <volume-group-id>${volumeGroupId}</volume-group-id>
1423                                 <aic-cloud-region>${aicCloudRegion}</aic-cloud-region>
1424                         </CreateAAIVfModuleVolumeGroupRequest>"""
1425
1426                         createAAIVfModuleVolumeGroupRequest = utils.formatXml(createAAIVfModuleVolumeGroupRequest)
1427                         execution.setVariable("DCVFM_createAAIVfModuleVolumeGroupRequest", createAAIVfModuleVolumeGroupRequest)
1428                         logDebug("Outgoing CreateAAIVfModuleVolumeGroupRequest is: \n" + createAAIVfModuleVolumeGroupRequest, isDebugLogEnabled)
1429                         utils.logAudit("Outgoing CreateAAIVfModuleVolumeGroupRequest is: \n"  + createAAIVfModuleVolumeGroupRequest)
1430
1431                 }catch(Exception e){
1432                         utils.log("ERROR", "Exception Occured Processing prepareCreateAAIVfModuleVolumeGroupRequest. Exception is:\n" + e, isDebugLogEnabled)
1433                         exceptionUtil.buildAndThrowWorkflowException(execution, 1002, "Error Occured during prepareCreateAAIVfModuleVolumeGroupRequest Method:\n" + e.getMessage())
1434                 }
1435                 logDebug("======== COMPLETED  prepareCreateAAIVfModuleVolumeGroupRequest ======== ", isDebugLogEnabled)
1436
1437         }
1438    
1439    public void createNetworkPoliciesInAAI(Execution execution) {
1440            def method = getClass().getSimpleName() + '.createNetworkPoliciesInAAI(' +
1441            'execution=' + execution.getId() +
1442            ')'
1443            def isDebugLogEnabled = execution.getVariable('isDebugLogEnabled')
1444            logDebug('Entered ' + method, isDebugLogEnabled)
1445            execution.setVariable("prefix", Prefix)
1446            logDebug(" ======== STARTED createNetworkPoliciesInAAI ======== ", isDebugLogEnabled)
1447           
1448            try {
1449                    // get variables
1450                    List fqdnList = execution.getVariable("DCVFM_contrailNetworkPolicyFqdnList")
1451                    int fqdnCount = fqdnList.size()
1452                    def rollbackData = execution.getVariable("RollbackData")
1453                   
1454                    execution.setVariable("DCVFM_networkPolicyFqdnCount", fqdnCount)
1455                    logDebug("DCVFM_networkPolicyFqdnCount - " + fqdnCount, isDebugLogEnabled)
1456
1457                    String aai_endpoint = execution.getVariable("URN_aai_endpoint")
1458                    AaiUtil aaiUriUtil = new AaiUtil(this)
1459                    String aai_uri = aaiUriUtil.getNetworkPolicyUri(execution)
1460
1461                    if (fqdnCount > 0) {                                   
1462                            
1463                            // AII loop call over contrail network policy fqdn list
1464                            for (i in 0..fqdnCount-1) {
1465
1466                                    int counting = i+1
1467                                    String fqdn = fqdnList[i]
1468
1469                                    // Query AAI for this network policy FQDN
1470                                   
1471                                    String queryNetworkPolicyByFqdnAAIRequest = "${aai_endpoint}${aai_uri}?network-policy-fqdn=" + UriUtils.encode(fqdn, "UTF-8")
1472                                    utils.logAudit("AAI request endpoint: " + queryNetworkPolicyByFqdnAAIRequest)
1473                                    
1474                                    def aaiRequestId = UUID.randomUUID().toString()
1475                                    RESTConfig config = new RESTConfig(queryNetworkPolicyByFqdnAAIRequest);
1476                                    RESTClient client = new RESTClient(config).addHeader("X-TransactionId", aaiRequestId)
1477                                                                                                                          .addHeader("X-FromAppId", "MSO")
1478                                                                                                                          .addHeader("Content-Type", "application/xml")
1479                                                                                                                          .addHeader("Accept","application/xml");
1480                                    APIResponse response = client.get()
1481                                    int returnCode = response.getStatusCode()
1482                                    execution.setVariable("DCVFM_aaiQqueryNetworkPolicyByFqdnReturnCode", returnCode)
1483                                    logDebug(" ***** AAI query network policy Response Code, NetworkPolicy #" + counting + " : " + returnCode, isDebugLogEnabled)
1484
1485                                    String aaiResponseAsString = response.getResponseBodyAsString()
1486
1487                                    if (isOneOf(returnCode, 200, 201)) {
1488                                            logDebug("The return code is: "  + returnCode, isDebugLogEnabled)
1489                                            // This network policy FQDN already exists in AAI
1490                                            utils.logAudit(aaiResponseAsString)
1491                                            execution.setVariable("DCVFM_queryNetworkPolicyByFqdnAAIResponse", aaiResponseAsString)
1492                                            logDebug(" QueryAAINetworkPolicyByFQDN Success REST Response, , NetworkPolicy #" + counting + " : " + "\n" + aaiResponseAsString, isDebugLogEnabled)                                   
1493
1494                                    } else {
1495                                            if (returnCode == 404) {
1496                                                    // This network policy FQDN is not in AAI yet. Add it now
1497                                                    logDebug("The return code is: "  + returnCode, isDebugLogEnabled)
1498                                                    logDebug("This network policy FQDN is not in AAI yet: " + fqdn, isDebugLogEnabled)
1499                                                    utils.logAudit("Network policy FQDN is not in AAI yet")                                                 
1500                                                    // Add the network policy with this FQDN to AAI
1501                                                    def networkPolicyId = UUID.randomUUID().toString()
1502                                                    logDebug("Adding network-policy with network-policy-id " + networkPolicyId, isDebugLogEnabled)                                               
1503                                                                                                    
1504                                                    String aaiNamespace = aaiUriUtil.getNamespaceFromUri(aai_uri)
1505                                                    logDebug('AAI namespace is: ' + aaiNamespace, isDebugLogEnabled)
1506                                                    String payload = """<network-policy xmlns="${aaiNamespace}">
1507                                                                 <network-policy-id>${networkPolicyId}</network-policy-id>
1508                                                                 <network-policy-fqdn>${fqdn}</network-policy-fqdn>
1509                                                                 <heat-stack-id>${execution.getVariable("DCVFM_heatStackId")}</heat-stack-id>                                                            
1510                                                                 </network-policy>""" as String
1511                                                                 
1512                                                    execution.setVariable("DCVFM_addNetworkPolicyAAIRequestBody", payload)
1513                                                    
1514                                                    String addNetworkPolicyAAIRequest = "${aai_endpoint}${aai_uri}/" + UriUtils.encode(networkPolicyId, "UTF-8")
1515                                                    utils.logAudit("AAI request endpoint: " + addNetworkPolicyAAIRequest)
1516                                                    logDebug("AAI request endpoint: " + addNetworkPolicyAAIRequest, isDebugLogEnabled)
1517                                                    
1518                                                    def aaiRequestIdPut = UUID.randomUUID().toString()
1519                                                    RESTConfig configPut = new RESTConfig(addNetworkPolicyAAIRequest);
1520                                                    RESTClient clientPut = new RESTClient(configPut).addHeader("X-TransactionId", aaiRequestIdPut)
1521                                                                                                                                          .addHeader("X-FromAppId", "MSO")
1522                                                                                                                                          .addHeader("Content-Type", "application/xml")
1523                                                                                                                                          .addHeader("Accept","application/xml");
1524                                                    logDebug("invoking PUT call to AAI with payload:"+System.lineSeparator()+payload, isDebugLogEnabled)
1525                                                    utils.logAudit("Sending PUT call to AAI with Endpoint /n" + addNetworkPolicyAAIRequest + " with payload /n" + payload)
1526                                                    APIResponse responsePut = clientPut.httpPut(payload)
1527                                                    int returnCodePut = responsePut.getStatusCode()
1528                                                    execution.setVariable("DCVFM_aaiAddNetworkPolicyReturnCode", returnCodePut)
1529                                                    logDebug(" ***** AAI add network policy Response Code, NetworkPolicy #" + counting + " : " + returnCodePut, isDebugLogEnabled)
1530                 
1531                                                    String aaiResponseAsStringPut = responsePut.getResponseBodyAsString()        
1532                                                    if (isOneOf(returnCodePut, 200, 201)) {
1533                                                            logDebug("The return code from adding network policy is: "  + returnCodePut, isDebugLogEnabled)
1534                                                            // This network policy was created in AAI successfully
1535                                                            utils.logAudit(aaiResponseAsStringPut)
1536                                                            execution.setVariable("DCVFM_addNetworkPolicyAAIResponse", aaiResponseAsStringPut)
1537                                                            logDebug(" AddAAINetworkPolicy Success REST Response, , NetworkPolicy #" + counting + " : " + "\n" + aaiResponseAsStringPut, isDebugLogEnabled)
1538                                                            rollbackData.put("VFMODULE", "rollbackCreateNetworkPoliciesAAI", "true")
1539                                                            rollbackData.put("VFMODULE", "contrailNetworkPolicyFqdn" + i, fqdn)
1540                                                            execution.setVariable("RollbackData", rollbackData)
1541                                                                         
1542                                                    } else {
1543                                                                 // aai all errors
1544                                                                 String putErrorMessage = "Unable to add network-policy to AAI createNetworkPoliciesInAAI - " + returnCodePut
1545                                                                 logDebug(putErrorMessage, isDebugLogEnabled)
1546                                                                 exceptionUtil.buildAndThrowWorkflowException(execution, 2500, putErrorMessage)                                     
1547                                                    }
1548                                                                                                    
1549                                            } else {
1550                                                   if (aaiResponseAsString.contains("RESTFault")) {
1551                                                           WorkflowException exceptionObject = exceptionUtil.MapAAIExceptionToWorkflowException(aaiResponseAsString, execution)
1552                                                           execution.setVariable("WorkflowException", exceptionObject)
1553                                                           throw new BpmnError("MSOWorkflowException")
1554
1555                                                           } else {
1556                                                                    // aai all errors
1557                                                                    String dataErrorMessage = "Unexpected Response from createNetworkPoliciesInAAI - " + returnCode
1558                                                                    logDebug(dataErrorMessage, isDebugLogEnabled)
1559                                                                    exceptionUtil.buildAndThrowWorkflowException(execution, 2500, dataErrorMessage)
1560
1561                                                          }
1562                                            }
1563                                    }
1564
1565                            } // end loop
1566
1567                           
1568                    } else {
1569                            logDebug("No contrail network policies to query/create", isDebugLogEnabled)
1570
1571                    }
1572
1573            } catch (BpmnError e) {
1574                    throw e;
1575
1576            } catch (Exception ex) {
1577                    String exceptionMessage = "Bpmn error encountered in DoCreateVfModule flow. createNetworkPoliciesInAAI() - " + ex.getMessage()
1578                    logDebug(exceptionMessage, isDebugLogEnabled)
1579                    exceptionUtil.buildAndThrowWorkflowException(execution, 7000, exceptionMessage)
1580            }
1581
1582    }
1583    
1584    /**
1585         * Prepare a Request for invoking the UpdateAAIGenericVnf subflow.
1586         *
1587         * @param execution The flow's execution instance.
1588         */
1589    public void prepUpdateAAIGenericVnf(Execution execution) {
1590            def method = getClass().getSimpleName() + '.prepUpdateAAIGenericVnf(' +
1591                    'execution=' + execution.getId() +
1592                    ')'
1593            def isDebugLogEnabled = execution.getVariable('isDebugLogEnabled')
1594            logDebug('Entered ' + method, isDebugLogEnabled)
1595
1596            try {
1597                    def rollbackData = execution.getVariable("RollbackData")
1598                    def vnfId = execution.getVariable('DCVFM_vnfId')
1599                    def oamManagementV4Address = execution.getVariable("DCVFM_oamManagementV4Address")
1600                    def oamManagementV6Address = execution.getVariable("DCVFM_oamManagementV6Address")
1601                    def ipv4OamAddressElement = ''
1602                    def managementV6AddressElement = ''
1603                    
1604                    if (oamManagementV4Address != null && !oamManagementV4Address.isEmpty()) {
1605                            ipv4OamAddressElement = '<ipv4-oam-address>' + oamManagementV4Address + '</ipv4-oam-address>'                          
1606                    }
1607                    
1608                    if (oamManagementV6Address != null && !oamManagementV6Address.isEmpty()) {
1609                            managementV6AddressElement = '<management-v6-address>' + oamManagementV6Address + '</management-v6-address>'
1610                    }
1611                    
1612                    rollbackData.put("VFMODULE", "oamManagementV4Address", oamManagementV4Address)
1613                    
1614                            
1615                    String updateAAIGenericVnfRequest = """
1616                                         <UpdateAAIGenericVnfRequest>
1617                                                 <vnf-id>${vnfId}</vnf-id>
1618                                                 ${ipv4OamAddressElement}
1619                                                 ${managementV6AddressElement}
1620                                         </UpdateAAIGenericVnfRequest>
1621                                 """
1622                            updateAAIGenericVnfRequest = utils.formatXml(updateAAIGenericVnfRequest)
1623                            execution.setVariable('DCVM_updateAAIGenericVnfRequest', updateAAIGenericVnfRequest)
1624                            utils.logAudit("updateAAIGenericVnfRequest : " + updateAAIGenericVnfRequest)
1625                            logDebug('Request for UpdateAAIGenericVnf:\n' + updateAAIGenericVnfRequest, isDebugLogEnabled)
1626                 
1627
1628                    logDebug('Exited ' + method, isDebugLogEnabled)
1629            } catch (BpmnError e) {
1630                    throw e;
1631            } catch (Exception e) {
1632                    logError('Caught exception in ' + method, e)
1633                    createWorkflowException(execution, 1002, 'Error in prepUpdateAAIGenericVnf(): ' + e.getMessage())
1634            }
1635    }
1636    
1637    /**
1638         * Post process a result from invoking the UpdateAAIGenericVnf subflow.
1639         *
1640         * @param execution The flow's execution instance.
1641         */
1642    public void postProcessUpdateAAIGenericVnf(Execution execution) {
1643            def method = getClass().getSimpleName() + '.postProcessUpdateAAIGenericVnf(' +
1644                    'execution=' + execution.getId() +
1645                    ')'
1646            def isDebugLogEnabled = execution.getVariable('isDebugLogEnabled')
1647            logDebug('Entered ' + method, isDebugLogEnabled)
1648
1649            try {
1650                    def rollbackData = execution.getVariable("RollbackData")
1651                    
1652                    rollbackData.put("VFMODULE", "rollbackUpdateVnfAAI", "true")
1653                    
1654                    def vnfId = execution.getVariable('DCVFM_vnfId')
1655                    def oamManagementV4Address = execution.getVariable("DCVFM_oamManagementV4Address")
1656                    def oamManagementV6Address = execution.getVariable("DCVFM_oamManagementV6Address")
1657                    def ipv4OamAddressElement = ''
1658                    def managementV6AddressElement = ''
1659                    
1660                    if (oamManagementV4Address != null && !oamManagementV4Address.isEmpty()) {                      
1661                            rollbackData.put("VFMODULE", "oamManagementV4Address", oamManagementV4Address)
1662                    }
1663                    
1664                    if (oamManagementV6Address != null && !oamManagementV6Address.isEmpty()) {
1665                            rollbackData.put("VFMODULE", "oamManagementV6Address", oamManagementV6Address)                          
1666                    }
1667                    
1668                    execution.setVariable("RollbackData", rollbackData)             
1669                         
1670                    logDebug('Exited ' + method, isDebugLogEnabled)
1671            } catch (BpmnError e) {
1672                    throw e;
1673            } catch (Exception e) {
1674                    logError('Caught exception in ' + method, e)
1675                    createWorkflowException(execution, 1002, 'Error in postProcessUpdateAAIGenericVnf(): ' + e.getMessage())
1676            }
1677    }
1678 }